content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_class_name(obj, instance=True): """ Given a class or instance of a class, returns a string representing the fully specified path of the class. Parameters ---------- obj : object An instance of any object instance: bool Indicates whether given object is an instance of the class to be named """ typ = type(obj) if instance else obj return "{}.{}".format(typ.__module__, typ.__name__)
3a7ebd1fb2682ec5dff6d42cd2cccf918d67f9a0
709,938
def _is_link_up(statedict): """Evaluate current operstate, carrier and link from dict.""" if statedict['link'] == 'yes' and statedict['carrier'] == 'running' and statedict['operstate'] == 'up': return True return False
3215a79448e9d7b9f29b8455a56a336779862a95
246,116
def _n_grams(n, s): """Convert a string into an iterator of n_gram strings.""" return map(''.join, zip(*[s.lower()[i:] for i in range(n)]))
a93ccfcba60ddcf02342ba514e63ed263c060a38
545,144
def wgtd_avg(lines): """ Returns the weighted average of a set of line coefficients """ avg_coeffs = [0,0,0] i = 0 n = len(lines) # Weighted average of line coefficients to get smoothed lane lines for line in lines: i += 1 avg_coeffs = avg_coeffs + (i * line.coeffs / ((n**2 + n) / 2)) return avg_coeffs
e51d44e7f03142dbea6bfe04721552a73ca64b30
391,846
from typing import Tuple def floating_IoU( r1: Tuple[float, float, float, float], r2: Tuple[float, float, float, float] ) -> float: """IoU for non-grid based boxes >>> floating_IoU((0, 0, 1, 1), (0, 0, 1, 2)) 0.5 Params ====== r1 - (x, y, w, h,...) r2 - (x, y, w, h,...) Returns ======= IoU - the insersection over union """ x1, y1, w1, h1 = r1[:4] x2, y2, w2, h2 = r2[:4] left = max(x1, x2) right = min(x1 + w1, x2 + w2) top = max(y1, y2) bottom = min(y1 + h1, y2 + h2) overlap_height = bottom - top overlap_width = right - left if overlap_height <= 0 or overlap_width <= 0: overlap_area = 0 else: overlap_area = overlap_height * overlap_width area1 = w1 * h1 area2 = w2 * h2 union_area = area1 + area2 - overlap_area return overlap_area / union_area
37a40d16c2728782ba65ceb93daa4095960ddcdd
496,545
def penn_to_wn(tag): """ Convert between a Penn Treebank tag to a simplified Wordnet tag """ if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
ffadd9e06a20acdcda4b2d085e086e31ad53c694
593,296
def get_range(padding, *args): """Get a [min, max] for all of the data passed as *args.""" if not isinstance(padding, tuple): padding = (padding, padding) all_data = [item for lst in args for item in lst] return [min(all_data) - padding[0], max(all_data) + padding[1]]
3fd5c11a6986c55fef1a27ccdb7ca04106c107f2
102,323
import torch def stft(y, n_fft, hop_length, win_length): """ Args: y: [B, F, T] n_fft: hop_length: win_length: device: Returns: [B, F, T], **complex-valued** STFT coefficients """ assert y.dim() == 2 return torch.stft( y, n_fft, hop_length, win_length, window=torch.hann_window(n_fft).to(y.device), return_complex=True )
9c48f99b072f766ec63b1ec68b95cd424652b700
260,656
def _parse_zeopp(filecontent: str) -> dict: """Parse the results line of a network call to zeopp Args: filecontent (str): results file Returns: dict: largest included sphere, largest free sphere, largest included sphera along free sphere path """ first_line = filecontent.split("\n")[0] parts = first_line.split() results = { "lis": float(parts[1]), # largest included sphere "lifs": float(parts[2]), # largest free sphere "lifsp": float(parts[3]), # largest included sphere along free sphere path } return results
436e7579883a8c6700d3725756dd03dc7de3cf51
58,476
def handle_same_string(str1, alist): """ if a string already exist in a list, add a number to it """ if str1 in alist: for i in range(1, 1000): str1_ = str1 + ' (%i)' % i if str1_ not in alist: return str1_ else: return str1
ea3ae39166ed81bd046d0ae095d0436c5f88c801
460,890
import pickle def load_basic_model(model_file, vectorizer_file): """Load the either the Logistic Regression or SVM model and vectorizer""" load_model = pickle.load(open(model_file, 'rb')) load_vectorizer = pickle.load(open(vectorizer_file, 'rb')) print(" ### Loading model complete ### ") return load_model, load_vectorizer
b252cadd4067c67b8833dc2c2094fe14d007f504
325,576
def str2int(val): """ Converts a decimal or hex string into an int. Also accepts an int and returns it unchanged. """ if type(val) is int: return int(val) if len(val) < 3: return int(val, 10) if val[:2] == '0x': return int(val, 16) return int(val, 10)
dadddb6a82b3243735c1b0136a6ccc266820bd5b
634,638
def get_entity_name(s): """ Detect entity name from the raw entity string. :param s: Entity string :return: entity name """ tokens = s.split("/") name = tokens[3] return name
90e35aec44801c560cbb8727213fea9a1056ed62
301,400
def translation_changed(verbose, obj_id, key, translation, target_string): """ Checks if the translation for a given key changed """ if target_string == translation: if verbose: print(f"Translation for {obj_id} string '{key}' has not changed -- skipping") return False return True
6fbfc83aa40050919fa62b37dd8dacf85949366e
562,949
def _read_params_from_file(filepath, seperator=None): """Extract key=value pairs from a file. :param filepath: path to a file containing key=value pairs separated by whitespace or newlines. :returns: a dictionary representing the content of the file """ with open(filepath) as f: cmdline = f.read() options = cmdline.split(seperator) params = {} for option in options: if '=' not in option: continue k, v = option.split('=', 1) params[k] = v return params
97818e80342039c33c79f1ce6dc7250d06165877
378,950
def _has_not_created_operation(result, retryer_state): """Takes TransferJob Apitools object and returns if it lacks an operation.""" del retryer_state # Unused. return not result.latestOperationName
f85422d9ddb37efdf0adde8dfc50601c825766c5
283,964
def is_valid(board, guess, row, col) -> bool: """ Check if potential digit is valid in a square :param board: Sudoku board :param guess: guessed digit :param row: row number :param col: column number :return: bool if move is valid """ # Rule 1: No duplicates in same row if guess in board[row]: return False # Rule 2: No duplicates in same column for i in range(9): if board[i][col] == guess: return False # Rule 3: No duplicates in 3x3 grids row_start = (row // 3) * 3 col_start = (col // 3) * 3 for r in range(row_start, row_start + 3): for c in range(col_start, col_start + 3): if board[r][c] == guess: return False return True
b72d8daba26c97c0a8aa7b111d02f83228801c75
187,546
def update_routing_segmentation_segment_by_id( self, segment_id: int, new_segment_name: str, ) -> bool: """Update routing segment name in Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - vrf - PUT - /vrf/config/segments/{id} :param segment_id: Numeric id of routing segment :type segment_id: int :param new_segment_name: New name to assign to routing segment :type new_segment_name: str :return: Returns True/False based on successful call :rtype: bool """ data = {"name": new_segment_name} return self._put( "/vrf/config/segments/{}".format(segment_id), data=data, expected_status=[204], return_type="bool", )
01e58f34897ffc636048a384706a6be7e1f3ae2e
476,239
from typing import Dict from typing import Any def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. """ return {v: k for k, v in d.items()}
2ec76e23d76b82baf7716ed27298f8ae64033cb3
248,953
def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float: """Return an linearly annealed epsilon Epsilon will decrease over time until it reaches `target_episode` (epsilon) | max_e ---|\ | \ | \ | \ min_e ---|____\_______________(episode) | target_episode slope = (min_e - max_e) / (target_episode) intercept = max_e e = slope * episode + intercept Args: episode (int): Current episode min_e (float): Minimum epsilon max_e (float): Maximum epsilon target_episode (int): epsilon becomes the `min_e` at `target_episode` Returns: float: epsilon between `min_e` and `max_e` """ slope = (min_e - max_e) / (target_episode) intercept = max_e return max(min_e, slope * episode + intercept)
fab650085f271f1271025e23f260eb18e645a9ba
402
import base64 def base32_to_base64(base32_string): """Converts base32 string to base64 string""" b64_string = base64.b64encode(base64.b32decode(base32_string)).decode('ascii') return b64_string
4c75717522016b57e19711ed34c0944072831a37
226,491
def request_help_privacy(twhandler): """Return the handler for GET help/privacy.""" return twhandler.help.privacy
aafb7e1ed7328fe5eff31933249205867a239657
595,204
def identity(X, y): """Identity operation. Parameters ---------- X : torch.Tensor EEG input example or batch. y : torch.Tensor EEG labels for the example or batch. Returns ------- torch.Tensor Transformed inputs. torch.Tensor Transformed labels. """ return X, y
c0441302d7c85979fd73475d2d24f993a25490d3
621,779
def link_generator(start: int, end: int, page: int) -> str: """ Generates links with appropriate query parameters. --- Args: start (int): start year of the query end (int): end year of the query page (int): page number Returns: link (str): final link for scrape requests """ link = f"https://www.1000plus.am/hy/compensation?full_name=&status=all&date_from={start}-01-01&date_to={end}-01-01&page={page}" return link
23953bd273ccc11e103e1fc9ff134711c742ba34
477,945
def build_complement(c): """ The function convert alphabets in input c into certain alphabets. :param c: str, can be 'A','T','G','C','a','t','g','c' :return: The string of converted alphabets. """ c = c.upper() # The Str Class method changes input c into capital. total = '' for i in range(len(c)): # Using for loop to convert the input alphabet from index 0 to the last index # to certain alphabet, A to T, C to G vice versa. ans = '' if c[i] == 'A': ans += 'T' if c[i] == 'T': ans += 'A' if c[i] == 'C': ans += 'G' if c[i] == 'G': ans += 'C' total += ans print('The complement of', c, 'is', total) return total
6fece325432ac061d5f7577c85cb59c19918ed83
26,992
from pathlib import Path def GetBadgeClassFileName(readPath: Path) -> Path: """ BadgeClass.csv ใธใฎใƒ‘ใ‚นใจใƒ•ใ‚กใ‚คใƒซๅใ‚’่ฟ”ใ™ใ€‚ unittest.mock ใงใƒ†ใ‚นใƒˆใ—ใ‚„ใ™ใ„ใ‚ˆใ†ใซๅˆ†ๅ‰ฒใ—ใŸใ€‚ """ return (readPath / "BadgeClass.csv")
2893df1f8495a3dc00733190cfb513843a5b5d55
454,373
def c_to_k(tempe): """Receives a temperature in Celsius and returns in Kelvin""" return tempe + 273.15
d88f1daf532b8b592ce0feb6019669ee9b183a20
557,273
def count_orders(values : list[int], max_diff : int) -> int: """Count the valid progressions through the values with a maximum jump size.""" ordered = [0] + sorted(values) + [max(values) + 3] options = [0] * len(ordered) options[0] = 1 # Each element of options should be the sum of all prior elements # where the difference between the matching values in ordered is less than # max_diff for i, val in enumerate(ordered[1:], 1): for j in range(i-1, -1, -1): if val - ordered[j] > max_diff: break # difference too large options[i] += options[j] return options[-1]
864a7a15c0ae6300f39396d9bddc9d60ed073427
454,091
def hamming_distance(list1, list2): """ Calculate the Hamming distance between two lists """ # Make sure we're working with lists # Sorry, no other iterables are permitted assert isinstance(list1, list) assert isinstance(list2, list) dist = 0 # 'zip' is a Python builtin, documented at # <http://www.python.org/doc/lib/built-in-funcs.html> for item1, item2 in zip(list1, list2): if item1 != item2: dist += 1 return dist
81fe2293cd42684b88ab19cb8341a0f55e5323a8
241,069
def dice(u, v): """Return the dice coefficient between two vectors.""" u = u > 0 v = v > 0 return (2.0 * (u * v).sum()) / (u.sum() + v.sum())
ae91be262af779885e805a7f6f0fe49b9efdef57
531,799
import random def clueless(state): """A strategy that ignores the state and chooses at random from possible moves.""" possible_moves = ['roll', 'hold'] return random.choice(possible_moves)
7ba97a5263dcf3bc65c0c37b4313b6c9b603bdbd
160,934
def fake_user(**kwargs): """Fixture to return a dictionary representing a user with default values set.""" kwargs.setdefault("id", 43) kwargs.setdefault("name", "bob the test man") kwargs.setdefault("discriminator", 1337) kwargs.setdefault("avatar_hash", None) kwargs.setdefault("roles", (666,)) kwargs.setdefault("in_guild", True) return kwargs
de688eca8b90b94fd90b7f7a1c8fb8ebbc545283
88,835
def _find_path(start, end, path=tuple()): """Return the path from start to end. If no path exists, return None. """ path = path + (start, ) if start is end: return path else: ret = None if start.low is not None: ret = _find_path(start.low, end, path) if ret is None and start.high is not None: ret = _find_path(start.high, end, path) return ret
0679377669f10094852910d18a47399c33673355
370,332
def append(field, item): """ Appends item to a list at value `field` """ def transform(element): if field not in element: element[field] = [item] else: element[field].append(item) return transform
9dae1273b45314e6522c60b3aa784ec8e90dd0fa
396,063
import torch def CartesianHarmonics(xyz, kx, ky, kz, derivative=0, jacobian=True): """Computes the Real cartesian harmonics x^kx, y^ky z^kz Arguments: xyz {torch.tensor} -- coordinate of each electrons from each BAS center (Nbatch, Nelec, Nbas, Ndim) kx {torch.tensor} -- x exponent ky {torch.tensor} -- y exponent kz {torch.tensor} -- z exponent Keyword Arguments: derivative {int} -- order of the derivative (default: {0}) jacobian (bool, optional) -- Return the jacobian (i.e. the sum of the derivatives) or the individual terms. Defaults to True. False only for derivative=1 """ if derivative == 0: return xyz[..., 0]**kx * xyz[..., 1]**ky * xyz[..., 2]**kz elif derivative == 1: kxm1 = kx - 1 kxm1[kxm1 < 0] = 0 dx = kx * xyz[..., 0]**(kxm1) * \ xyz[..., 1]**ky * xyz[..., 2]**kz kym1 = ky - 1 kym1[kym1 < 0] = 0 dy = xyz[..., 0]**kx * ky * \ xyz[..., 1]**(kym1) * xyz[..., 2]**kz kzm1 = kz - 1 kzm1[kzm1 < 0] = 0 dz = xyz[..., 0]**kx * xyz[..., 1]**ky * \ kz * xyz[..., 2]**(kzm1) if jacobian: return dx + dy + dz else: return torch.stack((dx, dy, dz), dim=-1) elif derivative == 2: kxm2 = kx - 2 kxm2[kxm2 < 0] = 0 d2x = kx * (kx - 1) * xyz[..., 0]**(kxm2) * \ xyz[..., 1]**ky * xyz[..., 2]**kz kym2 = ky - 2 kym2[kym2 < 0] = 0 d2y = xyz[..., 0]**kx * ky * \ (ky - 1) * xyz[..., 1]**(kym2) * xyz[..., 2]**kz kzm2 = kz - 2 kzm2[kzm2 < 0] = 0 d2z = xyz[..., 0]**kx * xyz[..., 1]**ky * \ kz * (kz - 1) * xyz[..., 2]**(kzm2) return d2x + d2y + d2z
1bda66b04637ae9ada6794d5bd696a72e4270574
458,053
def get_residuals_update_tile(st, padded_tile): """ Translates a tile in the padded image to the unpadded image. Given a state and a tile that corresponds to the padded image, returns a tile that corresponds to the the corresponding pixels of the difference image Parameters ---------- st : :class:`peri.states.State` The state padded_tile : :class:`peri.util.Tile` The tile in the padded image. Returns ------- :class:`peri.util.Tile` The tile corresponding to padded_tile in the unpadded image. """ inner_tile = st.ishape.intersection([st.ishape, padded_tile]) return inner_tile.translate(-st.pad)
306f436f6fe59a04542a99a33c07156cb4a14537
365,133
def api_card(text: str, color: str) -> str: """Create a HTML Card for API display""" html = f""" <div class='demo_card' style='background-color:{color}'> <span>{text}</span> </div> """ return html
8758078c92bfe7fafb87537501ba1c8a5490e47e
279,844
def urlize(val): """ Ensures a would-be URL actually starts with "http://" or "https://". :param val: the URL :returns: the cleaned URL >>> urlize('gnu.org') 'http://gnu.org' >>> urlize(None) is None True >>> urlize(u'https://gnu.org') 'https://gnu.org' """ if val and not val.startswith('http://') and not val.startswith('https://'): val = 'http://'+val return val
44fa7ddac48a860fa332bfb2dbb2d18de766c284
393,942
def sum_even_fibonacci(n): """sum of the even-valued terms of the fibonacci sequence not exceeding n""" result = 0 if n >= 2: x, y = 1, 1 for _ in range(n): x, y = y, x + y if x > n: break if x % 2 == 0: # print(x, y) result += x return result
0cfc53863115aa462f6d0558cc3a5018507c737f
35,298
def block_device_has_mounts(device): """ Determines if a block device has filesystems mounted on any of its partitions. Parameters ---------- device: str The block device. Returns ------- bool: True if at least one partitions is mounted; False under any other conditions. """ parts = device.get('partitions') if not parts: return False return sum([len(x['mountpoint']) for x in list(parts.values())]) != 0
75a3ad14962334ec17f336f7abdd0b31d752acae
523,988
def make_params(**kwargs): """ Helper to create a params dict, skipping undefined entries. :returns: (dict) A params dict to pass to `request`. """ return {k: v for k, v in kwargs.items() if v is not None}
a2405b8c5ca2173320f28ab5b668ca1b577360ae
543,199
def strict_dict(pairs): """Creates a dict from a sequence of key-value pairs, verifying uniqueness of each key.""" d = {} for k,v in pairs: if k in d: raise ValueError("duplicate tupkey '%s'" % k) d[k] = v return d
11690b8cde2fb2163f9c07001dc5864f21e0339f
44,293
def convert(nested_dict): """ Convert nested dict with bytes to str. This is needed because bytes are not JSON serializable. :param nested_dict: nested dict with bytes """ if isinstance(nested_dict, dict): return {convert(k): convert(v) for k, v in nested_dict.items()} elif isinstance(nested_dict, list): return [convert(v) for v in nested_dict] elif isinstance(nested_dict, tuple): return tuple(convert(v) for v in nested_dict) elif ( isinstance(nested_dict, str) or isinstance(nested_dict, int) or isinstance(nested_dict, float) ): return nested_dict else: return str(nested_dict)
d267259c6113411d0db757d59248db18beb29e31
165,349
def x_in_process(coord2d: list, x_coord: int, lx: int, processes_in_x: int) -> bool: """ Checks whether a global x coordinate is in a given process or not. Args: coord2d: process coordinates given the cartesian topology x_coord: global x coordinate lx: size of the lattice grid in x direction processes_in_x: number of processes in x direction Returns: boolean whether global x coordinate is in given process or not """ lower = coord2d[0] * (lx // processes_in_x) upper = (coord2d[0] + 1) * (lx // processes_in_x) - 1 if not coord2d[0] == processes_in_x - 1 else lx - 1 return lower <= x_coord <= upper
8dbd5c7a2bba3dc93ededb04452dc67163232af6
430,762
def escape_pg_identifier(engine, name): """ Escape identifiers (tables, fields, roles, etc) for inclusion in SQL statements. psycopg2 can safely merge query arguments, but cannot do the same for dynamically generating queries. See http://initd.org/psycopg/docs/sql.html for more information. """ # New (2.7+) versions of psycopg2 have function: extensions.quote_ident() # But it's too bleeding edge right now. We'll ask the server to escape instead, as # these are not performance sensitive. return engine.execute("select quote_ident(%s)", name).scalar()
ef572754bda07fd174b0ba7d940c1fcfaa665599
322,400
def jamf_records(cls, name="", exclude=()): """ Get Jamf Records :param cls <str>: name of class :param name <str>: name in record['name'] :param exclude <iter>: record['name'] not in exclude :returns: list of dicts: [{'id': jamf_id, 'name': name}, ...] """ # exclude specified records by full name included = [c for c in cls() if c.name not in exclude] # NOTE: empty string ('') always in all other strings return [c for c in included if name in c.name]
12531de9682ab6864d760d7bfa3969e79835b6ca
506,923
import re def clean_variable_name(variable_name): """ Convert the variable name to a name that can be used as a template variable. """ return re.sub(r"[^a-zA-Z0-9_]", '', variable_name.replace(' ', '_'))
ec89b05b299a479584620d82c44b009d3ce3a333
259,175
import shlex def stringToArgList(string): """Converts a single argument string into a list of arguments""" return shlex.split(string)
4ad5613978b082bf95945442128006f5ce8819d7
150,889
def update_search_service(instance, partition_count=0, replica_count=0): """ Update partition and replica of the given search service. :param partition_count: Number of partitions in the search service. :param replica_count: Number of replicas in the search service. """ replica_count = int(replica_count) partition_count = int(partition_count) if replica_count > 0: instance.replica_count = replica_count if partition_count > 0: instance.partition_count = partition_count return instance
c52219347758b5dea03812342019c0a1c23a74b1
362,835
from typing import Union from typing import Dict def form_store( payload: Union[Dict, str], metadata: Union[Dict, str, None], ): """ Processes the payload and the metadata (if any exists) into a JSON-like format. :param payload: A string object or dictionary containing the message data. :param metadata: A dictionary containing the message metadata. :return: A dictionary with "DATA" and (optionally) "METADATA" fields. """ data = {"DATA": payload} if metadata: data["METADATA"] = metadata return data
00b55e1f86eeea934d2ffc53de8237f72c3e99af
233,074
from pathlib import Path def _path_to_module(path: Path) -> str: """Returns the module name corresponding to a file path.""" parts = path.parts if parts[-1] == "__init__.pyi": parts = parts[:-1] if parts[-1].endswith(".pyi"): parts = parts[:-1] + (parts[-1][: -len(".pyi")],) return ".".join(parts).replace("-stubs", "")
f4caa79601793773e746f5f009d8239b0efbb8ee
430,303
def get_new_dim(imgw, imgh, max_dim=400): """Get new image dimension with maximum constraint. Args: imgw: image width. imgh: image height. max_dim: maximum image dimension after. Returns: new img width and height. """ max_val = max(imgw, imgh) ratio = max_val / max_dim new_imgw = int(imgw / ratio) new_imgh = int(imgh / ratio) return new_imgw, new_imgh # new_imgw = imgw # new_imgh = imgh # if imgw > imgh: # new_imgw = max_dim # new_imgh = imgh * max_dim // imgw # if imgh > imgw: # new_imgh = max_dim # new_imgw = imgw * max_dim // imgh # return new_imgw, new_imgh
dd25018f993b688c4e6767f8f196c3bcbf77fd7e
76,545
def read_file_comment(file_path): """Reads info comment in a coin CSV file. Args: file_path (str): given coin file path Raises: ValueError: occurs if no comment exist at the top of coin file Returns: comment (str): info comment in the coin file """ with open(file_path, 'r') as f: line = f.readline() if not line.startswith('#'): file_name = file_path.split('\\')[2] raise ValueError( f"{file_name} does not include coin info comment!\n\n") return line.replace('#', '')
cdc7ae40d942a39811746024819a785b7d917168
556,442
def create_labels(team, name, calender, client, sprints): """ Helper function to create labels for a project. :param Dict team: Team dict :param Dict calender: Calender dict :param jira.client.JIRA client: JIRA client :param String name: Team name :param List sprints: List of sprints :return: Newly Created Issue :rtype: jira.Issue """ # There is no way to 'manage' labels. # See https://community.atlassian.com/t5/Jira-questions/How-to-manage-labels/qaq-p/296536 # Best way is to create an issue for our new board # First gather our labels labels = [] for sprint, value in calender.items(): if value['quarter_string'] not in labels: labels.append(value['quarter_string']) # Create a new JIRA issue title = '%s Sprint Planning for %s-%s' % ( name, calender[0]['quarter_string'], calender[0]['quarter_string'] ) issue = client.create_issue(fields={ 'summary': title, 'issuetype': {'name': 'Story'}, 'labels': labels }) # Add issue to first sprint client.add_issues_to_sprint(sprints[0].id, issue_keys=[issue.key]) return issue
86623adfbc648a940abf6d49cce2872c65f98e30
546,271
def ExpectsMultiple(options): """Decorator for questions that indicates expected values from a list This decorator indicates to the renderer that the question will be answered by a series of check boxes. Args: options: An OrderedDict of Options where the key is the text to be presented to the user and the Option is the value that will be passed to the question if the checkbox is selected.""" def decorate(func): func.expectsMultiple = True func.options = options return func return decorate
70e1be1712269a43998f4073323a3b8e851e1b27
301,134
def levelFromHtmid(htmid): """ Find the level of a trixel from its htmid. The level indicates how refined the triangular mesh is. There are 8*4**(d-1) triangles in a mesh of level=d (equation 2.5 of Szalay A. et al. (2007) "Indexing the Sphere with the Hierarchical Triangular Mesh" arXiv:cs/0701164) Note: valid htmids have 4+2n bits with a leading bit of 1 """ htmid_copy = htmid i_level = 1 while htmid_copy > 15: htmid_copy >>= 2 i_level += 1 if htmid_copy < 8: raise RuntimeError('\n%d is not a valid htmid.\n' % htmid + 'Valid htmids will have 4+2n bits\n' + 'with a leading bit of 1\n') return i_level
86a2ca1c7176b06c38ff1acd028349690fb34aee
675,177
def id_count(df, id_column: str): """ Count the amount of ids from the data frame for future accountability. Returns an int. """ return len(list(set(df[id_column])))
e4d87b8424e12d14a5e3d42a2de52c07ba4d3fd7
381,370
import math def get_indices(width, height, xpartition, ypartition, xinput, yinput): """ Function to get the indices for grid. Args: width (float): width of the pitch. height (float): height of the pitch. xpartition (int): number of rows in a grid ypartition (int): number of colimns in a grid. xinput (float): x-coordinate location. yinput (float): y-coordinate location. Returns: tuple: containing indices for the grid. """ ## calculate number of partitions in x and y x_step = width / xpartition y_step = height / ypartition ## calculate x and y values x = math.ceil((xinput if xinput > 0 else 0.5) / x_step) # handle border cases as well y = math.ceil((yinput if yinput > 0 else 0.5) / y_step) # handle border cases as well return ( ypartition - y, x - 1 )
a93aefb4f04106341b498844751e2bc61b1754d4
83,100
def check_position(grid, num, row, col): """ Based on rules, checks if the given 'num' is in a valid position. """ def box_pos(val): # Determine coordinates of 3x3 box corresponding to val(row or col of the current square) if val < 3: pos = 0 elif 3 <= val < 6: pos = 3 else: pos = 6 return pos # Check row if num in grid[row, :]: return False # Check column if num in grid[:, col]: return False # Check box pos_y = box_pos(row) pos_x = box_pos(col) if num in grid[pos_y:pos_y+3, pos_x:pos_x+3]: return False return True
7e0c612c44d9e743084c295753f73ea9c69b4f36
280,110
def is_patch_inside_FOV(x,y,fov_img,patch_h,patch_w,mode='center'): """ check if the patch is contained in the FOV, The center mode checks whether the center pixel of the patch is within fov, the all mode checks whether all pixels of the patch are within fov. """ if mode == 'center': return fov_img[y,x] elif mode == 'all': fov_patch = fov_img[y-int(patch_h/2):y+int(patch_h/2),x-int(patch_w/2):x+int(patch_w/2)] return fov_patch.all() else: raise ValueError("\033[0;31mmode is incurrent!\033[0m")
45c6be6f8647ae2bd93390fdd0ed4868eea19258
597,403
def add_format_field(record, fieldname): """Return record with fieldname added to the FORMAT field if it doesn't already exist. """ format = record.FORMAT.split(':') if fieldname not in format: record.FORMAT = record.FORMAT + ":" + fieldname return record
bcc3ff87a80bb561462b11428eeba8561bcc100f
42,120
def extract_symbols(lst): """Takes a row or column of idents or alphanumeric symbols and just extracts the symbols (letters). Args: lst (list): list of strings representing the cells in a row or col e.g. ['1a', '1b', '1c', 2, 2] Returns: (list): just the letters from the input e.g. ['a', 'b', 'c'] """ return [char for item in lst if isinstance(item, str) for char in item if not char.isdigit()]
0cbbc621aa4b0f7c6bc837bdb1f76e7317057ccb
396,461
def get_bytes_from_gb(size_in_gb): """ Convert size from GB into bytes """ return size_in_gb*(1024*1024*1024)
9bfd7a0791a08a88ad83b388e25030ef8cc2df6b
650,150
def binary_integer_format(integer: int, number_of_bits: int) -> str: """ Return binary representation of an integer :param integer: :param number_of_bits: NOTE: number of bits can be greater than minimal needed to represent integer :return: """ return "{0:b}".format(integer).zfill(number_of_bits)
4ad126eb37cf781b01552ed2498683a75f8f3f22
340,873
def get_length_of_list_of_iterables(list_of_tuples): """Get the total length of a list of tuples.""" length = 0 for tuple_item in list_of_tuples: length += len(tuple_item) return length
eef9813c2e1e3e27dd94989bdf87cecbc3885b94
521,399
def total_fluorescence_from_intensity(I_par, I_per): """ Calculate total fluorescence from crossed intensities. """ return I_par + 2 * I_per
9e46bc6f2088a0d489f3c94de4cb5248267173cb
306,661
import re def normalize_version(version): """ Normalize a version string by removing extra zeroes and periods. """ return [int(x) for x in re.sub(r'(\.0+)*$', '', version).split('.')]
24f9db935e67495f6583b17627222c68ad5423ee
622,368
def cpu_usage_for_process(results, process): """ Calculate the CPU percentage for a process running in a particular scenario. :param results: Results to extract values from. :param process: Process name to calculate CPU usage for. """ process_results = [ r for r in results if r['metric']['type'] == 'cputime' and r['process'] == process ] cpu_values = sum(r['value'] for r in process_results) wallclock_values = sum(r['wallclock'] for r in process_results) if wallclock_values > 0: return float(cpu_values) / wallclock_values return None
8fc962cf9f7d1fcab1b8a223b4c15dd2eb0e51f4
57,146
def GetPatchDeploymentUriPath(project, patch_deployment): """Returns the URI path of an osconfig patch deployment.""" return '/'.join(['projects', project, 'patchDeployments', patch_deployment])
96298cc379e94fd6acb97f620b6f8dee35959b98
143,364
from typing import Callable def filter_values(d: dict, predicate: Callable) -> dict: """ Returns new subset dict of d where values pass predicate fn >>> d = {'Homer': 39, 'Marge': 36, 'Bart': 10} >>> filter_values(d, lambda x: x < 20) {'Bart': 10} """ return {k: v for k, v in d.items() if predicate(v)}
551b00222361cdb684820d8ce2c22e407d65d362
615,270
from typing import List def loadMatrix(file_name: str) -> List[List[float]]: """ Import matrix from file. Matrix is stored in row oriented list. Such that each row is a nested list. """ with open(file_name, 'r') as file: row_count = int(file.readline()) column_count = int(file.readline()) return [[float(file.readline()) for _ in range(column_count)] for _ in range(row_count)]
860fca72aeb56ce2f30310a0db63c7b212ee2a3b
89,474
def is_word_capitalized(word): """ Check if word is capitalized. Args: word (str): Word. Returns: (boole): True f word is capitalized. False otherwise. """ if not word: return False first_letter = word[0] return first_letter == first_letter.upper()
1e5e2ecc08330774bf5e25e72d1af97d2a73d0af
388,308
def data_sort(gdf,str): """ sort the geodataframe by special string Parameters ---------- gdf : geodataframe geodataframe of gnss data str: sort based on this string Returns ------- geodataframe: geodataframe of gnss data after sorting """ gdf = gdf.sort_values(by = [str]) return gdf
8010c66872ec9c2954659bdcd34bfa313963ffc7
679,960
from typing import Generator def is_gen(x): """Checks if argument is a generator.""" return isinstance(x, Generator)
af91e61f1638c3601c3b8db0bb7f2310ca967fdd
244,422
import difflib import heapq def get_close_matches_and_similarity_ratios(word, possibilities, n=3, cutoff=0.6, junk_str=''): """Use SequenceMatcher to return list of the best "good enough" matches, along with the similarity ratios. Code inspired from: https://docs.python.org/3/library/difflib.html#difflib.get_close_matches word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of strings). Optional arg n (default 3) is the maximum number of close matches to return. n must be > 0. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities that don't score at least that similar to word are ignored. Optional arg junk_str (default '') is a string containing all the junk characters, which are to be omitted. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches_and_similarity_ratios("appel", ["ape", "apple", "peach", "puppy"]) [('apple', 0.8), ('ape', 0.75)] >>> import keyword as _keyword >>> get_close_matches_and_similarity_ratios("wheel", _keyword.kwlist) [('while', 0.6)] >>> get_close_matches_and_similarity_ratios("Apple", _keyword.kwlist) [] >>> get_close_matches_and_similarity_ratios("accept", _keyword.kwlist) [('except', 0.6666666666666666)] """ if not n > 0: raise ValueError("n must be > 0: %r" % (n,)) if not 0.0 <= cutoff <= 1.0: raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,)) result = [] if len(junk_str) > 0: s = difflib.SequenceMatcher(isjunk=lambda x: x in junk_str) else: s = difflib.SequenceMatcher() s.set_seq2(word) for x in possibilities: s.set_seq1(x) if s.real_quick_ratio() >= cutoff and \ s.quick_ratio() >= cutoff and \ s.ratio() >= cutoff: result.append((s.ratio(), x)) # Move the best scorers to head of list result = heapq.nlargest(n, result) # Swap scorers and scores for the best n matches close_matches_and_similarity_ratios = [(x, score) for score, x in result] return close_matches_and_similarity_ratios
831949bd5ef427b01c47af6b4cca081074aef9ae
142,118
def compute_pct_by_group(df, group_col='group', value_col='count'): """ Determine what percent each element contributes to its group's total. - Sum value by group to get group totals - Divide each group element by its group's total to get fraction of group - Multiply by 100 to get percent of group for each group element - Return series with percent-of-group values http://pbpython.com/pandas_transform.html """ total = df.groupby(group_col)[value_col].transform('sum') return df[value_col] / total * 100.
3a6f774806329c9fac02bc04eda3d95f97694361
189,183
import torch def sample_reparameterize(mean, std): """ Perform the reparameterization trick to sample from a distribution with the given mean and std Inputs: mean - Tensor of arbitrary shape and range, denoting the mean of the distributions std - Tensor of arbitrary shape with strictly positive values. Denotes the standard deviation of the distribution Outputs: z - A sample of the distributions, with gradient support for both mean and std. The tensor should have the same shape as the mean and std input tensors. """ # sample random vector from normal distribution epsilon = torch.randn(size=(std.shape), device=mean.device) # compute z z = mean + (epsilon * std) return z
33e44a3ed3d3a12774250b2f9c3a6d019abd0ca2
113,629
def rgbToStrhex(r, g, b): """r (int), g (int), b (int): rgb values to be converted Returned value (str): hex value of the color (ex: #7f866a""" return '#%02x%02x%02x' % (r, g, b)
9bcdb657c3ec3662b80f5fc83a09644b98292896
102,342
def get_element_from_list(attribute, search_string, element_list): """ Get element by attribute and string. :param attribute: string of attribute type :param search_string: identifying string to look for :param element_list: element tree to look in :return: found element """ for element in element_list: if search_string == element.get(attribute): return element return None
834f78dfeae0a1406e1de98925e9052e08d7f6a4
381,023
def construct_wiki_header(wiki_meta): """ Return wiki page Jekyll front matter header for compomics.github.io pages. """ header = """--- title: "{title}" layout: default permalink: "{permalink}" tags: {tags} project: "{project}" github_project: "{github_project}" --- """.format(**wiki_meta) return header
dbc000d7cfa3b91edf243363f1af0d9956c42494
118,020
def _repr_tuple(dumper, data): """Fix yaml tuple representation (use list). """ return dumper.represent_list(list(data))
0365b33bfb039dea11729da88e186082ebdf7e53
377,942
def prefs_line_to_string(line): """ Converts a prefs line to a string. Prefs line is in the format tb(..);tc(..);..;..;. tb(x, y) are "no preference" intervals (i.e., white) that last for y 15-minute intervals (x has no meaning): e.g., tb(0, 4) is an hour of white; tb(2, 8) is two hours. tc(x, y, "z") are colored intervals, where z denotes the color, and they last for y 15-minute intervals (x has no meaning): z-values: 1 = green, 2 = pink, 3 = red e.g., tc(0, 10, "3") is an hour and a half of red. e.g., tc(0, 20, "1") is three hours of green. It gets sent to a string of XPDC characters, where: X - no preference (white) P - prefers to work (green) D - dislikes working (pink) C - cannot work (red) And each character represents 15 minutes of that color, e.g., XXXX = hour of white; RRDD = half hour of red, half hour of pink """ prefs_pieces = line.split(';') prefs_string = '' # Mapping between prefs line code and actual color character codes = {1: "P", 2: "D", 3: "C"} for piece in prefs_pieces: if piece[:2] == "tb": # Format: tb(x,y) where y denotes the number of 15-minute intervals # Split at comma, -> [ 'tb(x', 'y)'] # Extract y as second entry, remove last char (close paren) # and cast to int piece = piece.split(',')[1] length = int(piece[:-1]) # Length tells how many X characters there should be prefs_string += ('X' * length) if piece[:2] == "tc": # Format: tc(x,y,"z") # x is worthless; y is the length; z is the color # Split at comma, -> [ 'tc(x', 'y', '"z")')] # Length, y is the second entry # Extract z as the third entry, stripping first and last two chars # (open quote, and close quote + close paren), and cast to int piece = piece.split(',') length = int(piece[1]) code = int(piece[2][1:-2]) # Lookup which character to add in codes; length tells how many prefs_string += (codes[code] * length) return prefs_string
3497018ebf6306fdd23c8a12b9ad67a09811200c
630,496
def get_region_period_spec_val_subtable(df, region=None, period=None, col='typemaatwerkarrangement', spec_value=None): """ Method to subset the dataframe based on a certain region, period and specific value of a column. Parameters ---------- df : pd.DataFrame DataFrame with the WMO data from CBS with the columns 'codering_regio', 'perioden' and a specific to subset on which gives a type, i.e. a column to subset on type of WMO. region : str String to choose region. Possible strings are: "gemeente", "wijk" period : str String to choose period. Possible strings are: "jaar", "halfjaar" col : str Column where the type of WMO will be subsetted spec_value : str String to choose specific value for the selected column. I.e. form of type of WMO, could be type of financing, but also type of customization. Returns ------- pd.DataFrame """ if region == "gemeente": df = df[df.codering_regio.str.startswith('GM', na=False)] if region == "wijk": df = df[df.codering_regio.str.startswith('WK', na=False)] if region == "buurt": df = df[df.codering_regio.str.startswith('BU', na=False)] if period == "jaar": df = df[~df.perioden.str.contains("halfjaar", na=False)] if period == "halfjaar": df = df[df.perioden.str.contains("halfjaar", na=False)] if spec_value != None: df = df[df[col] == spec_value] return df
c5e8c9771417afa532b90973a08808860d9700de
195,067
def trimmer( scores: list, counts: list, direction: int = 0, threshold: int = 3, frac_retain: float = 0.9, ) -> int: """ Trimmer takes scores and direction as input and returns the position where the sequence has to be trimmed in that direction Parameters --------- scores : list List of scores for each baseid. Scores are 'good', 'warning' or 'failure' counts : list Number of sequences used to calculate scores for each baseid direction : {0, 1}, optional The direction for trimming. 0 is left, 1 is right Default value is 0 threshold : int, optional The minimum number of good bases that need to appear in sequence to stop trimming Default value is 5 frac_retain : float, optional The minimum fraction of sequences that need to be retained after trimming Returns ------ int The position where the sequence is to be trimmed in the given direction """ ord_scores = scores if direction == 0 else scores[::-1] nseqs = counts[0] count_fracs = [c / nseqs for c in counts] try: retain_fail_pos = next( ind for ind, c in enumerate(count_fracs) if c < frac_retain ) except StopIteration: retain_fail_pos = len(scores) stop_flag = 0 pos = len(scores) for i, score in enumerate(ord_scores): if stop_flag <= -threshold: stop_flag = 0 if stop_flag >= threshold: pos = i - threshold break elif score == "good": stop_flag += 1 elif score == "warning": stop_flag += 0 elif score == "failure": stop_flag -= 1 direct_pos = pos if direction == 0 else len(scores) - pos return direct_pos if direction == 0 else min(direct_pos, retain_fail_pos)
ba4a346d53e87bbd4227dfbdfd4a6fef2f9902ed
491,186
from typing import Tuple import math def color_difference_redmean( rgb1: Tuple[float, float, float], rgb2: Tuple[float, float, float] ) -> float: """Distance between colors in RGB space (redmean metric). The maximal distance between (255, 255, 255) and (0, 0, 0) โ‰ˆ 765. Sources: - https://en.wikipedia.org/wiki/Color_difference#Euclidean - https://www.compuphase.com/cmetric.htm """ r_hat = (rgb1[0] + rgb2[0]) / 2 delta_r, delta_g, delta_b = [(col1 - col2) for col1, col2 in zip(rgb1, rgb2)] red_term = (2 + r_hat / 256) * delta_r ** 2 green_term = 4 * delta_g ** 2 blue_term = (2 + (255 - r_hat) / 256) * delta_b ** 2 return math.sqrt(red_term + green_term + blue_term)
47837f4069c37902ba430ca1f52a67590a8a06ad
176,643
def Identity(X): """ Identity fuction is the basic activation function It return the same input value as output. Parameters: - X: int ,-Inf to +Inf Returns: X , -Inf to +Inf """ return X
1b7d1f912e04fed5b503960a0ecd9bf9811ab19b
606,243
def not_all_new(old_elements: list, new_elements: list): """ This function check whether at least one element from new_elements are in old_elements. """ return any([element in old_elements for element in new_elements])
2c9912479561f5a0a62234f4e14138e70abb71d9
203,272
from typing import Tuple def _RGB_to_TkID(RGB: Tuple[int, int, int]) -> str: """ This function converts an RGB tuple (R, G, B) into a colour code which can be used by tkinter. :param RGB: Tuple[int, int, int] :return: str """ r, g, b = RGB return f'#{r:02x}{g:02x}{b:02x}'
cb3a0e7fd57a79351107c06ca5de56eaa7e3667a
334,293
import click def cccv_options(f): """CCCV-specific CLI options.""" f = click.option('--out', type=click.Path(), required=True, help='Output file path for CCCV results.')(f) f = click.option('--conta_steps', type=int, default=20, help='Number of equidistant contamination levels to resample to.')(f) f = click.option('--comple_steps', type=int, default=20, help='Number of equidistant completeness levels to resample to.')(f) return f
3d3852846bf96ba38b91291faca181c26f3a9ab0
144,277
def get_formatted_duration(seconds: float, format: str="hms") -> str: """Format a time in seconds. :param format: "hms" for hours mins secs or "ms" for min secs. """ mins, secs = divmod(seconds, 60) if format == "ms": t = "{:d}m:{:02d}s".format(int(mins), int(secs)) elif format == "hms": h, mins = divmod(mins, 60) t = "{:d}h:{:02d}m:{:02d}s".format(int(h), int(mins), int(secs)) else: raise Exception("Format {} not available, only 'hms' or 'ms'".format(format)) return t
9a968fba1f5cf9882875544a0de6d7e8e814eff0
507,096
def remove_place(net, place): """ Remove a place from a Petri net Parameters ------------- net Petri net place Place to remove Returns ------------- net Petri net """ if place in net.places: in_arcs = place.in_arcs for arc in in_arcs: trans = arc.source trans.out_arcs.remove(arc) net.arcs.remove(arc) out_arcs = place.out_arcs for arc in out_arcs: trans = arc.target trans.in_arcs.remove(arc) net.arcs.remove(arc) net.places.remove(place) return net
b4bc3edabff29e0837c895f82ef9599eb59c811c
74,308
def get_hms_from_seconds(seconds): """ function: get_hms_from_seconds coverts the given number of seconds to hours, minutes, and seconds input: int seconds: the number of seconds to convert output: int hours: the number of hours that fit evenly into the given number of seconds int minutes: the remaining minutes after the hours have been subtracted from the given seconds int seconds: the remaining seconds after the hours and minutes have been subtracted from the given seconds """ seconds = seconds hour = seconds/(60*60) remainder = seconds - hour*(60*60) minute = remainder/(60) remainder = remainder - minute*60 return hour, minute, remainder
fe3804640c508bf7aadf1a7165158e89745e5d70
270,336
def get_cell_count(grid): """Return number alive cells on the grid.""" return len(grid.cell_sprite)
849aaed0d579b1518e51172d6117e58195a98ab7
131,839
def components_in(containers): """ given a list of containers, return the components within """ components = [] for container in containers: instances = container.components() components.extend(instances) subcontainers = container.containers() components.extend(components_in(subcontainers)) return components
316bb95b1fed6183597a3cb6564ce217e3a35ba6
167,916
def c_to_k(image): """Convert temperature from C to K""" return image.add(273.15).copyProperties(image, ['system:time_start'])
97ba24243f2a42fb10a5303e011b4d71e1564f9c
255,981
from datetime import datetime def timestamp_datetime(timestamp): """ Converts a timestamp from the device to a python datetime value """ return datetime.fromtimestamp(timestamp / 1000000000.0)
ff20ae37a5775339e9566942224cc54f22acb6d0
487,958
def convert_version(version): """Convert version into a pin-compatible format according to PEP440.""" version_parts = version.split('.') suffixes = ('post', 'pre') if any(suffix in version_parts[-1] for suffix in suffixes): version_parts.pop() # the max pin length is n-1, but in terms of index this is n-2 max_ver_len = len(version_parts) - 2 version_parts[max_ver_len] = int(version_parts[max_ver_len]) + 1 max_pin = '.'.join(str(v) for v in version_parts[:max_ver_len + 1]) pin_compatible = ' >={},<{}' .format(version, max_pin) return pin_compatible
b62a40768f1f0f5790cb2d1b16b7e7007bffcef3
256,501
def set_date(cdate, is_first_loop, is_force_read_cache, arg_date): """set date given context (read cache, get today date or set date argument) Parameters ---------- is_first_loop : bool true on first calendar call is_force_read_cache : bool force date from cache arg_date : str date in '%m%Y' format Returns ------- CacheDate CacheDate object that contain the date to display """ if not is_first_loop or is_force_read_cache: cdate.read_cache() # read previous date elif is_first_loop and arg_date: cdate.set_month(arg_date) # command line force date else: # at first loop if no force option cdate.now() return cdate
8ec3e542657497b71471bc9755d99191438aa530
594,801
import re def get_values(text): """ Accept a string such as BACKGROUNDCOLOR [r] [g] [b] and return ['r', 'g', 'b'] """ res = re.findall("\[(.*?)\]", text) values = [] for r in res: if "|" in r: params = r.split("|") for p in params: values.append(p) else: values.append(r) values = [str(v.lower()) for v in values] return values
8b315abb66fa7b8b1b35e789deb047026d534c8c
436,448
import math def distance(a, b): """The distance between two (x, y) points.""" return math.hypot((a[0] - b[0]), (a[1] - b[1]))
f1df262eaedac3a0ff21c78c8daafdef4e21dfcc
229,034