content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def sort_pulsar_dict(pulsar_dict): """ Sorts a pulsar dict by frequency Parameters: ----------- pulsar_dict: dictionary A dictionary of profiles from get_data_from_epndb returns: -------- pulsar_dict: dictionary The same dictionary sorted by frequency """ freq_list = pulsar_dict["freq"] for key in pulsar_dict.keys(): _, pulsar_dict[key] = (list(t) for t in zip(*sorted(zip(freq_list, pulsar_dict[key])))) return pulsar_dict
4fc0880bb96337f4def3bee5373bdaef63039df9
115,884
def sum_power(n): """Sums digits of 2^n.""" digits = [2] for _ in range(n-1): for i in range(len(digits)-1, -1, -1): d = digits[i] if 2*d > 9: digits[i] = (2*d)%10 if i == len(digits)-1: digits.append((2*d) // 10) else: digits[i+1] += (2*d) // 10 else: digits[i] = 2*d return sum(digits)
38da5319e3e09a1a5c32607073bd94f4dd1a4459
115,890
def n_of(parser, n): """Consumes n of parser, returning a list of the results. """ return [parser() for i in range(n)]
ac5ad5ec18d30f6b221027e25ad624a09e1c2a1c
115,891
def get_stations_by_town(stations): """ Returns a dictionary consisting of a (key, value) pair of towns (key) and a list of the stations inside of them (value) """ towns = {} # dictionary of towns for station in stations: town = station.town if town in towns: towns[town].append(station) else: towns[town] = [station] return towns
cc18f6304f4a05894131173ce36b7dec2e95220a
115,897
from typing import Union from pathlib import Path import glob import re def get_latest_version(file_pattern: Union[str, Path]) -> int: """Assuming the file pattern select list of files tagged with an integer version for every run, this function return the latest version number that you can use to name your next run. For example: 1. If your pattern matches folders: version_1, version_5, version_6, this function will return 6. 2. If your pattern does not match anything, return 0 """ files = [Path(file) for file in sorted(glob.glob(str(file_pattern)))] if len(files) == 0: return 0 file = sorted(files)[-1] match = re.match("[^0-9]*(\d+)[^0-9]*", file.name) if match is None: raise Exception("Invalid naming") return int(match.group(1))
19a4a3cc34ca3d148c8baef96084dda8e174c13c
115,901
def Location(child): """ Return x,y offset of Region See comment in Region.Child() Args: child: '0','1','2','3' Returns: (x,y): lower-left origin """ childnum = int(child) x = childnum & 1 # mask the y bit y = childnum >> 1 # shift over the y bit y = not y return (x,y)
ad27314cf34ecc1515507de129507ca14bcf7732
115,903
def date_second(date): """Find the second from the given date.""" return date.second
774d3def41b78a8a967b9ae25da8713129429966
115,912
import re def remove_string_extras(mytext: str): """ remove_string_extras - removes extra characters from a string. everything except A-Za-z0-9 .,; """ return re.sub(r"[^A-Za-z0-9 .,;]+", "", mytext)
c17da9638225647d3f13a4f9d4cea2b06696e2ab
115,913
def sqr_norm_l2(x): """ Computes the squared l_2 norm of a vector """ return x.T @ x
7aef78a90db6fb797134ef0de1d57c9efacecf7e
115,916
def near(a, b, eps = 0.0000001): """ returns whether numerical values a and b are within a specific epsilon environment """ diff = abs(a-b) return diff < eps
6bc0f2f23caf7864f0e5d5c1260ed8d0b7b2d3d9
115,917
def get_variable_indices(atom): """ Gets the indexes of the variables in the atom. :param atom: the atom :type atom: Atom :return: the indices of the variables :rtype: list[int] """ indexes = [] for i in range(atom.arity()): if not atom.terms[i].is_constant(): indexes.append(i) return indexes
7daf0faab7c8c4470313d7b609b7589b87153bfa
115,919
import six def get_first(predicate, source): """Searches for an item that matches the conditions. :param predicate: Defines the conditions of the item to search for :param source: Iterable collection of items :return: The first item that matches the conditions defined by the specified predicate, if found; otherwise StopIteration is raised """ return six.next(item for item in source if predicate(item))
cfaa1abd9dc70ca1fbc452e2a8f6678f8438af74
115,920
def clean_tag(tag): """ Removes unwanted elements from a tag. :param tag: a bs4.element.Tag object containg an infobox that should be clean :return: cleaned_tag: a bs4.element.Tag object that has had nuisance elements removed """ cleaned_tag = tag for sup in cleaned_tag('sup'): sup.decompose() return cleaned_tag
e85bc836e95e9d935be6cf4bcef8f14a381f4e48
115,927
def get_weekday_occurrence(day): """Calculate how often this weekday has already occurred in a given month. :type day: datetime.date :returns: weekday (0=Monday, ..., 6=Sunday), occurrence :rtype: tuple(int, int) """ xthday = 1 + (day.day - 1) // 7 return day.weekday(), xthday
7b22eefe629cd51312d7a8be0908438ab7fef7d6
115,929
def div_ceil(n, d): """Integer divide that sounds up (to an int). See https://stackoverflow.com/a/54585138/5397207 Examples >>> div_ceil(6, 2) 3 >>> div_ceil(7, 2) 4 >>> div_ceil(8, 2) 4 >>> div_ceil(9, 2) 5 """ return (n + d - 1) // d
eaf647f7d6991804e3465d3166cbea6987087944
115,930
def sanitize_string(str): """ sanitize a string by removing /, \\, and -, and convert to PascalCase """ for strip in ["/", "\\", "-"]: str = str.replace(strip, " ") components = str.split() return "".join(x.title() for x in components)
fdc4a94dc4e5c3dc3ef30d8fbf67ab9814190a27
115,931
def visit_level(t, n, act): """ Visit each node of BinaryTree t at level n and act on it. Return the number of nodes visited visited. @param BinaryTree|None t: binary tree to visit @param int n: level to visit @param (BinaryTree)->Any act: function to execute on nodes at level n @rtype: int >>> b = BinaryTree(8) >>> b = insert(b, 4) >>> b = insert(b, 2) >>> b = insert(b, 6) >>> b = insert(b, 12) >>> b = insert(b, 14) >>> b = insert(b, 10) >>> def f(node): print(node.data) >>> visit_level(b, 2, f) 2 6 10 14 4 """ if t is None: return 0 elif n == 0: act(t) return 1 elif n > 0: return (visit_level(t.left, n-1, act) + visit_level(t.right, n-1, act)) else: return 0
e3286dadc9bc77c1b0a08ddaee31d6bce2722f6c
115,932
def _get_segment_from_id(segment_obj_list, segment_id): """ Get a segment from a list, based on a segment id """ found_segment_obj = None for segment_obj in segment_obj_list: if segment_obj.id == segment_id: found_segment_obj = segment_obj break return found_segment_obj
6cb9a649a40a1c52fdcac7db68e7fd5457344ebd
115,933
def is_rc_supported_for_platform(taskgen): """ Check if the platform supports rc compiling, following these rules: 1. MSVC base target platform 2. Non static library :param tg: The task generator to determine the platform and target type :return: True if windows rc compiling is supported, False if not """ platform = taskgen.bld.env['PLATFORM'] if platform == 'project_generator': return False # Only non-static lib targets are supported (program, shlib) target_type = getattr(taskgen, '_type', None) if target_type not in ('program', 'shlib'): return False # Only msvc based compilers are supported rc_supported_platform = False if platform.startswith('win'): rc_supported_platform = True return rc_supported_platform
03c7d8332f72dbe69cab36f326e1348d15fb46a1
115,938
def get_prefered_quotation_from_string(string): """ Tries to determin the quotation (`"` or `'`) used in a given string. `"` is the default and used when no quotations are found or the amount of `"` and `'` are equal """ return "'" if string.count("'") > string.count('"') else '"'
505c9bcffeb66b7c1f866580274a48e98c4ca915
115,944
def strip_filter(text): """Trim whitespace.""" return text.strip() if text else text
3669789e3ed401e639c63d33675f04548528b89e
115,953
def player_color(player_name): """Return color of a player given his name """ return { 1 : (0, 255, 0), 2 : (0, 0, 255), 3 : (255, 0, 0), 4 : (255, 255, 0), 5 : (0, 255, 255), 6 : (255, 0, 255), 7 : (224, 224, 224), 8 : (153, 153, 255) }[player_name]
ddd38eb23016ae01e9cbce9f36b04d2d8fe2c52a
115,955
def animation(object, *commands): """ animation(object, *commands) -> None Does operations on an animation curve. The following commands are supported: - B{clear} deletes all the keys from the animation. - B{erase} C{index I{last_index}} removes all keyframes between index and last_index - B{expression} C{I{newvalue}} returns or sets the expression for the animation. The default is 'curve' or 'y' which returns the interpolation of the keys. - B{generate} C{start end increment field expression I{field expression} ...} generates an animation with start, end, and increment. Multiple field/expression pairs generate a keyframe. Possible field commands are: - B{x} sets the frame number for the next keyframe - B{y} sets the keyframe value - B{dy} sets the left slope - B{ldy} sets left and right slope to the same value - B{la} and B{ra} are the length of the slope handle in x direction. A value of 1 generates a handle that is one third of the distance to the next keyframe. - B{index} C{x} returns the index of the last key with x <= t, return -1 for none. - B{is_key} return non-zero if there is a key with x == t. The actual return value is the index+1. - B{move} C{field expression I{field expression}} replaces all selected keys in an animation with new ones as explained above in B{generate} - B{name} returns a user-friendly name for this animation. This will eliminate any common prefix between this animation and all other selected ones, and also replaces mangled names returned by animations with nice ones. - B{size} returns the number of keys in the animation. - B{test} errors if no points in the animation are selected - B{y} index C{I{newvalue}} gets or sets the value of an animation. - B{x} index C{I{newvalue}} gets or sets the horizontal postion of a key. If the animation contains an expression or keyframes, the new value will be overridden. See also: animations @param object: The animation curve. @param commands: a varargs-style list of commands, where each command is one of those defined above. @return: None """ return None
bc9f3d9c8950e1e225490d07e7d818b031a8f5cb
115,957
from typing import Any def short(obj: Any, width: int = 45) -> str: """ Elides an object string representation to the specified length, adding ellipsis (...) and the remaining glyph count to the end of the string. Returns the string as-is if string representation is shorter than the specified width. :param obj: object to format the string representation for :param width: required string representation length :return: formatted elided string """ str_ = str(obj) len_ = len(str_) - width if len_ > 0: return str_[:width] + f'[...+{len_}]' return str_
347b885112a364c115cee88b422c7ff244e9c65b
115,959
def get_num_classes(DATASET: str) -> int: """Get the number of classes to be classified by dataset.""" if DATASET == 'MELD': NUM_CLASSES = 7 elif DATASET == 'IEMOCAP': NUM_CLASSES = 6 else: raise ValueError return NUM_CLASSES
4f4d6a17d9f569b9b92599a375c207494d5deb89
115,960
import hashlib def create_checksum(edi_message: str) -> str: """ Creates a SHA-256 checksum for an EDI message. :param edi_message: The input EDI message :returns: The SHA-256 checksum as a hex digest """ return hashlib.sha256(edi_message.encode("utf-8")).hexdigest()
97f1273db531f827f58c34f466b62f1b90853a9f
115,967
def chinese_cycle(date): """Return 'cycle' element of a Chinese date, date.""" return date[0]
0734a1062e81ffd661b9fe3cb12bdbcd34a793be
115,974
def modified_from_status(status_out): """ Return a generator of modified files from git status output. The output is expected to be in the format returned by ``git status --porcelain`` """ stripped = (ln.strip() for ln in status_out.split('\n')) modded = (ln for ln in stripped if ln.startswith('M')) return (ln.split()[1] for ln in modded)
b9675be71388b76753cf530d9f1e3aed98d05505
115,977
def get_op_bbox(frame): """ Arguments: frame: dictionary of joint indices to normalized coords [x, y, conf]. ie {0: [.5, .5, .98]} Returns: 4 normalized bounding box coordinates x1, x2, y1, y2 """ x1 = 1 x2 = 0 y1 = 1 y2 = 0 for key in frame: joint = frame[key] if len(joint) != 0: if (joint[0] != 0): x1 = min(x1, joint[0]) x2 = max(x2, joint[0]) if (joint[1] != 0): y1 = min(y1, joint[1]) y2 = max(y2, joint[1]) return x1, x2, y1, y2
0e60225f29e7cf8da44f206b62dd4e9fbc913515
115,978
def truncate_float(value, digits_after_point=2): """ Truncate long float numbers >>> truncate_float(1.1477784, 2) 1.14 """ pow_10 = 10 ** digits_after_point return (float(int(value * pow_10))) / pow_10
aad8c20e94b45b916629a43b19bd7b72b8b2612a
115,980
def score_n1(matrix, matrix_size): """\ Implements the penalty score feature 1. ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54) ============================================ ======================== ====== Feature Evaluation condition Points ============================================ ======================== ====== Adjacent modules in row/column in same color No. of modules = (5 + i) N1 + i ============================================ ======================== ====== N1 = 3 :param matrix: The matrix to evaluate :param matrix_size: The width (or height) of the matrix. :return int: The penalty score (feature 1) of the matrix. """ score = 0 for i in range(matrix_size): prev_bit_row, prev_bit_col = -1, -1 row_counter, col_counter = 0, 0 for j in range(matrix_size): # Row-wise bit = matrix[i][j] if bit == prev_bit_row: row_counter += 1 else: if row_counter >= 5: score += row_counter - 2 # N1 == 3 row_counter = 1 prev_bit_row = bit # Col-wise bit = matrix[j][i] if bit == prev_bit_col: col_counter += 1 else: if col_counter >= 5: score += col_counter - 2 # N1 == 3 col_counter = 1 prev_bit_col = bit if row_counter >= 5: score += row_counter - 2 # N1 == 3 if col_counter >= 5: score += col_counter - 2 # N1 == 3 return score
09f2140db4684f53793e94c8aa93f40e3c3eebb9
115,982
def anything(_): """ This predicate will always return True, and thus matches anything. :param _: The argument, which is ignored. :return: True """ return True
a15774a645f32ca22bc285054f41f3b0997db4d6
115,983
from typing import Sequence import string def int_to_base( n: int, base: int, numerals: Sequence[str] = '0123456789' + string.ascii_lowercase, ) -> str: """Forms a string representation of a non-negative integer in a given base. Args: n: A non-negative integer value. base: The base in which ``n`` will be represented. Must be a positive integer from 2 to ``len(numerals)``. numerals: A sequence of string tokens that will be used to represent the digits from 0 to ``base - 1`` in order. Returns: A string representation of ``n`` in the given base, where each digit is given by the corresponding value of ``numerals``. References: Adapted from http://stackoverflow.com/questions/2267362/. """ # base case: 0 is represented as numerals[0] in any base if n == 0: return numerals[0] # compute the low-order digit and recurse to compute higher order digits div, mod = divmod(n, base) return int_to_base(div, base, numerals).lstrip(numerals[0]) + numerals[mod]
75b2f7fc0d5b897444bbb397dab93730ef907889
115,985
def module_index(pmt_index): """Returns the module number given the 0-indexed pmt number""" return pmt_index//19
bc7b608aa26ec2f1ff2f26e9cc3be2f7b8f25e99
115,987
def combine(*projectors): """ Given a list of projectors as *args, return another projector which calls each projector in turn and merges the resulting dictionaries. """ def combined(instance): result = {} for projector in projectors: projection = projector(instance) if not isinstance(projection, dict): raise TypeError(f"Projector {projector} did not return a dictionary") result.update(projection) return result return combined
88e46c3bfef9822094b612be7664cadf2fa185c5
115,997
def RGBtoRGBW(R, G, B): """ convert RGB to RGBW color :param R: red value (0;255) :param G: green value (0;255) :param B: blue value (0;255) :return: RGBW tuple (0;255) """ W = min(R, G, B) R -= W G -= W B -= W return R, G, B, W
83fe3702ab1bbcf0aa7d2d61606aee9fa28aa023
115,999
def _set_iraf_section(section_list): """ Convert python list containing section information into string using IRAF syntax """ assert len(section_list) == 4 [y1, y2, x1, x2] = section_list y1 += 1 x1 += 1 return "[{:d}:{:d},{:d}:{:d}]".format(x1, x2, y1, y2)
280aac1a94f6980f3b9ab83fd4274ff29543b34e
116,000
def name_from_path(path): """Returns name of a module given its path, i.e. strips '.py' """ return path[0:-3]
ec0decc3c62e50435c33b99420ce2cde7343d26d
116,006
def resort_list(liste, idx_list, n_x): """ Make sure list is in the same order as some index_variable. Parameters ---------- liste : List of lists. idx_list : List with indices as finished by multiprocessing. n_x : Int. Number of observations. Returns ------- weights : As above, but sorted. """ check_idx = list(range(n_x)) if check_idx != idx_list: liste = [liste[i] for i in idx_list] return liste
5ca6b802253e0a56d18c19a5f7f728e3bca6d371
116,007
def status2str(num): """ Return YubiHSM response status code as string. """ known = {0x80: 'YSM_STATUS_OK', 0x81: 'YSM_KEY_HANDLE_INVALID', 0x82: 'YSM_AEAD_INVALID', 0x83: 'YSM_OTP_INVALID', 0x84: 'YSM_OTP_REPLAY', 0x85: 'YSM_ID_DUPLICATE', 0x86: 'YSM_ID_NOT_FOUND', 0x87: 'YSM_DB_FULL', 0x88: 'YSM_MEMORY_ERROR', 0x89: 'YSM_FUNCTION_DISABLED', 0x8a: 'YSM_KEY_STORAGE_LOCKED', 0x8b: 'YSM_MISMATCH', 0x8c: 'YSM_INVALID_PARAMETER', } if num in known: return known[num] return "0x%02x" % (num)
e67acae9598eed69e8b5f073b4eed081b6d434ea
116,009
def grab_genius(author, song, genius): """ Grabs the lyrics from genius of a given song Parameters ---------- author : String Name of the author song : String Name of the song genius : Genius Genius access to API Returns ------- String The lyrics of a song """ # Search Genius for song song = genius.search_song(song, author) lyrics = song.lyrics.replace("\n", " ").split(" ") return lyrics if (song) else -1
df0ff070e3e66a77879a2fe26798cc9e4698653c
116,012
def _partition(M): """Evenly partition a matrix into 4 blocks (2-by-2). """ block_size = M.shape[0] // 2 M_11 = M[: block_size, : block_size] M_12 = M[: block_size, block_size :] M_21 = M[block_size :, : block_size] M_22 = M[block_size :, block_size :] return (M_11, M_12, M_21, M_22)
5cfec5686fa5c0e30b5e5e36e8ee539e94193996
116,014
def mk_task_map(task, qualified=True): """returns a map of information about the given task function. when `qualified` is `False`, the path to the task is truncated to just the task name""" path = "%s.%s" % (task.__module__.split('.')[-1], task.__name__) unqualified_path = task.__name__ description = (task.__doc__ or '').strip().replace('\n', ' ') return { "name": path if qualified else unqualified_path, "path": path, "description": description, "fn": task, }
0d05d1a6cd1589185b594686b39c371f6c37b120
116,015
import time def _time_left(stime, timeout): """ Return time remaining since ``stime`` before given ``timeout``. This function assists determining the value of ``timeout`` for class method :meth:`~.Terminal.kbhit` and similar functions. :arg float stime: starting time for measurement :arg float timeout: timeout period, may be set to None to indicate no timeout (where None is always returned). :rtype: float or int :returns: time remaining as float. If no time is remaining, then the integer ``0`` is returned. """ return max(0, timeout - (time.time() - stime)) if timeout else timeout
c14ddf228f24f4fa68bf636abfff8636007743e4
116,019
def GetMappingsForTesterKeyName(user): """Returns a str used to uniquely identify mappings for a given user..""" return 'RunTesterMap_Tester_%s' % str(user.user_id())
00173c8ba30174748e04fd405ec9819ebc9817b1
116,022
import re def curlify(content: str) -> str: """ Adds a pair of curly braces to the content. If the content already contains curly brackets, nothing will happen. Example: - curlify("Hello") returns "{Hello}". - curlify("{Hello}") returns "{Hello}". """ curlify_pattern = re.compile(r'^{.*}$', re.DOTALL) # Check if curly brackets are already set if not re.fullmatch(curlify_pattern, content): # Add extra curly brackets to title. Preserves lowercase/uppercase in BIBTeX content = "{{{}}}".format(content) return content
a45b6805eb3250f74fea913478d93f49e09b12cf
116,029
def infer_season_from_date(date): """ Looks at a date and infers the season based on that: Year-1 if month is Aug or before; returns year otherwise. :param date: str, YYYY-MM-DD :return: int, the season. 2007-08 would be 2007. """ season, month, day = [int(x) for x in date.split('-')] if month < 9: season -= 1 return season
111fc42ac1771451551e22cd93687516bc6fd932
116,035
def rewrite_event_to_message(logger, name, event_dict): """ Rewrite the default structlog `event` to a `message`. """ event = event_dict.pop('event', None) if event is not None: event_dict['message'] = event return event_dict
c5a6e2222b08bb6309aea81136791d4a3b3eac1d
116,036
def rpartition(seq, n): """ Partition sequence in groups of n starting from the end of sequence. """ seq = list(seq) out = [] while seq: new = [] for _ in range(n): if not seq: break new.append(seq.pop()) out.append(new[::-1]) return out[::-1]
c6a973f87139067e58dbfa2bf782f813dd67a243
116,043
def PyObject_Call(space, w_obj, w_args, w_kw): """ Call a callable Python object, with arguments given by the tuple args, and named arguments given by the dictionary kw. If no named arguments are needed, kw may be NULL. args must not be NULL, use an empty tuple if no arguments are needed. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression apply(callable_object, args, kw) or callable_object(*args, **kw).""" return space.call(w_obj, w_args, w_kw)
b7139b67477bd09fc6039ca3b1af1dc16c3c28ac
116,044
def expected_workload(L,p): """ Return expected number of votes that need to be counted. L = input list of precincts: (size,name) pairs. p = input list of auditing probabilities. """ return sum([p[i]*L[i][0] for i in range(len(L))])
33434476c95780660ccef05d1de3f30ee429ffdd
116,045
def name2community(name): """ Given the string name of a community, recover the community. """ return str(name).split()
e2509aadcad4db6030de53342fe20d6dfb2ee3a9
116,047
import torch from typing import Tuple def colorize_noise(img: torch.Tensor, color_min: Tuple[int, int, int] = (-255, -255, -255), color_max: Tuple[int, int, int] = (255, 255, 255), p: float = 1) -> torch.Tensor: """ Colorizes given noise images by asserting random color values to pixels that are not black (zero). :param img: torch tensor (n x c x h x w) :param color_min: limit the random color to be greater than this rgb value :param color_max: limit the random color to be less than this rgb value :param p: the chance to change the color of a pixel, on average changes p * h * w many pixels. :return: colorized images """ assert 0 <= p <= 1 orig_img = img.clone() if len(set(color_min)) == 1 and len(set(color_max)) == 1: cmin, cmax = color_min[0], color_max[0] img[img != 0] = torch.randint(cmin, cmax+1, img[img != 0].shape).type(img.dtype) else: img = img.transpose(0, 1) for ch, (cmin, cmax) in enumerate(zip(color_min, color_max)): img[ch][img[ch] != 0] = torch.randint(cmin, cmax+1, img[ch][img[ch] != 0].shape).type(img.dtype) if p < 1: pmask = torch.rand(img[img != 0].shape) >= p tar = img[img != 0] tar[pmask] = orig_img[img != 0][pmask] img[img != 0] = tar return img
2c1c8593e6dc4ee1eb3a3f4b1326bfb8e089b108
116,048
def is_java_ref(S): # @UnusedVariable """ Return True is S looks like a reference to a java class or package in a class file. """ return False
7b05387c367e02dd448664ab6d918e69cdd9d25d
116,052
def rect2poly(ll, ur): """ Convert rectangle defined by lower left/upper right to a closed polygon representation. """ x0, y0 = ll x1, y1 = ur return [ [x0, y0], [x0, y1], [x1, y1], [x1, y0], [x0, y0] ]
b0e63db99ac9f5ab5c9f27041a43d592bbe186a9
116,056
def compareRecord(recA , recB, attr_comp_list): """Generate the similarity vector for the given record pair by comparing attribute values according to the comparison function and attribute numbers in the given attribute comparison list. Parameter Description: recA : List of first record values for comparison recB : List of second record values for comparison attr_comp_list : List of comparison methods for comparing attributes, this needs to be a list of tuples where each tuple contains: (comparison function, attribute number in record A, attribute number in record B). This method returns a similarity vector with one value for each compared attribute. """ sim_vec = [] # Calculate a similarity for each attribute to be compared # for (comp_funct, attr_numA, attr_numB) in attr_comp_list: if (attr_numA >= len(recA)): # Check there is a value for this attribute valA = '' else: valA = recA[attr_numA] if (attr_numB >= len(recB)): valB = '' else: valB = recB[attr_numB] valA = valA.lower() valB = valB.lower() sim = comp_funct(valA, valB) sim_vec.append(sim) return sim_vec
79e7ad8b2d8e248f24ded9ce9264a9784e963476
116,057
def get_id_numbers(data, endpoint): """Return a list of the specified endpoint's primary id numbers.""" ids = set() id_field = '{0:s}_id'.format(endpoint) for rec in data: ids.add(rec.get(id_field)) return list(ids)
337d988f4c8831d24d570c8b5480cb4e289fcd28
116,060
def nth_root(x, n): """Finds the nearest integer root of a number.""" upper = 1 while upper ** n <= x: upper *= 2 mid, lower = None, upper // 2 while lower != upper: mid = (lower + upper) // 2 mid_n = mid ** n if lower < mid and mid_n < x: lower = mid elif upper > mid and mid_n > x: upper = mid else: return mid if mid is not None: return mid + 1
30ffc4f06104e9dc12c4a125afb4cd2c66b599bd
116,066
def product(iterable): """ Calculate the product of the elements of an iterable """ res = 1 for x in iterable: res *= x return res
af8133cc42ee6527a06602bd7b0e742fdfabeb41
116,068
import re def get_auth_header_values(header_string): """ Returns a dict mapping the header keys to their values """ # Get the header key and value (value matches any non-quote contained in quotes) reg = re.compile(r'(\w+)="([^"]+)"') return dict(reg.findall(header_string))
8e9b49fdfaa37f44cbdf0725536cb1f9f787eb6e
116,071
def count_var_match(var_names, relation): """ Count the number of common variables between agt_vars and the dimensions or relation. :param var_names: a list of variable names :param relation: a relation object :return: the number of common variable """ match = 0 for v in relation.dimensions: if v.name in var_names: match += 1 return match
24f450e2cfa8ee193d7e04b14621ac2c43b611bd
116,072
def get_virtuals_asm_policies(bigip): """ Returns a dict of policy_name --> virtual servers """ params = { '$select': 'name,virtualServers,manualVirtualServers', # '$filter': "attachedPoliciesReferences/link eq '*'", } url_base_asm = f'https://{bigip.ip}/mgmt/tm/asm/policies' json_data = bigip.get(url_base_asm, params=params) json_data['items'][0]['name'] result = {} for d in json_data['items']: name = d.get('name') result[name] = d.get('virtualServers', []) return result
7d17342039bd448bec36ad73c66a4a2914696567
116,073
def compare(context, object_field, raw_data, raw_field): """ Compare an object field value against the raw field value it should have come from. Args: context (str): The context of the comparison, used for printing error messages. object_field (Any): The value of the object field being compared. raw_data (dict): Raw data structure we're comparing a field from. raw_field (str): Name of the raw field we're doing the comparison on. Returns: bool: True if comparison was successful, False if not. """ if raw_field in raw_data: result = (object_field == raw_data[raw_field]) else: result = (object_field is None) if not result: print(f"field value {raw_field} did not match in {context} - object value {object_field}, " f"raw value {raw_data.get(raw_field, None)}") return result
55763de771dc977f39c57687d2f53336bc24cf14
116,077
import base64 def is_base64(text: bytes) -> bool: """Check if the string is base64. :param text: Text to check. :return: Whether it is base64. """ try: base64.decodebytes(text) except: return False return True
5557275ee22599ae6aa589d0a3c8af84021ddc6a
116,079
def format_query(query): """ Given query=" word1 word2 word3 Returns " word1 OR word2 OR word3" """ words = query.split() # print words text = "" for idx in range(len(words) - 1): text = text + words[idx] + " OR " text = text + words[-1] return text
04b00f6153057515ae5091d1210080f2be1be28a
116,084
import re def parse_thickness(filename): """ Parses an .opm file and returns the thickness if any. Args: filename: .opm file. Returns: Either half of the bilayer thickness or None if not present. """ thicknesses = [] with open(filename, "r") as fh: for line in fh: if line.startswith("REMARK") and re.search("1/2 of bilayer thickness:", line): thicknesses.append(float(line.strip().split()[-1])) if len(thicknesses) == 0: return None else: return sum(thicknesses)/len(thicknesses)
26e2a52ee09fe5d39ed61a74a13a30f3b8d7b4e6
116,089
def eh_posicao(p): """ Pretende descobrir se o argumento inserido e ou nao uma posicao de um tabuleiro. :param p: Um int, posicao de um tabuleiro (1 a 9). :return: Um bool, veracidade do argumento. """ if type(p) != int: return False elif not 1 <= p <= 9: # posicoes de 1 a 9 return False return True
4a37fc6ef2c6ea38ca0edeb41f1bc302fa73e644
116,092
def parse_behave_table(context_table): """Cast behave's table to a dict.""" return next( dict(zip(context_table.headings, row)) for row in context_table.rows )
3499dbdfb19d33fd1790e61e89a6da2c4132165d
116,093
def payoff_call(underlying, strike, gearing=1.0): """payoff_call Payoff of call option. :param float underlying: :param float strike: :param float gearing: Coefficient of this option. Default value is 1. :return: payoff call option. :rtype: float """ return gearing * max(underlying - strike, 0)
e676c9c84f5e5406884cfd0000cdc9a8c5e59105
116,094
import random def fisherYatesShuffle(arr): """ https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle for i from n−1 downto 1 do j ← random integer such that 0 ≤ j ≤ i exchange a[j] and a[i] """ for i in range(len(arr)-1, 0, -1): j = random.randint(0, i) arr[i], arr[j] = arr[j], arr[i] return arr
979d5004f34600aa1b5977ac17a986c75b01dfa5
116,095
def nextmonth(yr, mo): """get next month from yr/mo pair""" return (yr+mo / 12, mo % 12+1)
149b203b7988980e1ab3f9ca02b3817874437a64
116,097
def hydraulic_resistance_coefficient(Eg, Re, ke, d): """ :param Eg: Coefficient of hydraulic efficiency. If no data: Eg=0.95 for pipelines with scraper system; Eg=0.92 for pipelines without scrapper system. Dimensionless :param Re: Reynolds number. Dimensionless :param ke: equivalent pipe roughness, m :param d: pipe inner diameter, m :returns: Hydraulic resistance coefficient, dimensionless """ return (1.05/Eg**2) * 0.067 * (158/Re + 2*ke/d)**0.2
d67c3feaf882b2e583491d30de5733ce11852324
116,099
def get_sigint_handler(client): """ Return a SIGINT handler for the provided SlippiCommClient object """ def handler(signum, stack): print("Caught SIGINT, stopping client") client.shutdown() exit(0) return handler
2f47c9d4030b91026f8d35d3a88450ca462284e2
116,102
import hashlib def hash_file(content: bytes) -> str: """ Create a hash from the given content """ sha1sum = hashlib.new("sha1") sha1sum.update(content) return sha1sum.hexdigest()
0c1f4bd63c578ff3f40b8ea8e407e9ab6abe98b1
116,106
def check_weights(nodes_with_a_weight): """ Ensure that the sum of the values is 1 :param nodes_with_a_weight: a list of Node objects with a weight attribute """ weights = [n['weight'] for n in nodes_with_a_weight] if abs(sum(weights) - 1.) > 1E-12: raise ValueError('The weights do not sum up to 1: %s' % weights) return nodes_with_a_weight
d65a1b13e7f0b69b69ada731793184fd838e6e4b
116,110
def listify(list_or_value): """ Given a list or a value transforms it to a list Arguments: list_or_value (str or list): List or a value Returns: A list """ if isinstance(list_or_value, list): return list_or_value else: return [list_or_value]
a3d28b4d858e391987885dae3b733df6001745e2
116,117
def network_is_bogon(network): """ Returns if the passed ipaddress network is a bogon Arguments: - network <ipaddress.IPv4Network|ipaddress.IPv6Network> Return: - bool """ return not network.is_global or network.is_reserved
b729a6dcd907a833d4bdedf581e58b8b515f3e07
116,118
def _extrapolate_constant(to_time, from_sample): """Extrapolate a power rating to an earlier or later time. This models a constant power rating before (or after) the `from_sample` input to the `to_time`. It returns a power sample, of the same class as the `from_sample` but at the time specified in `to_time`. """ sample_class = from_sample.__class__ watts = from_sample.watts extrapolated_sample = sample_class(watts=watts, moment=to_time) return extrapolated_sample
e16b488d90e39534ae2647b27740c92928bc2a40
116,119
import hashlib def sha256d(data): """Compute the Double SHA-256 hash.""" sha = hashlib.sha256(data).digest() return hashlib.sha256(sha).digest()
f7693652de1b6c9f300fa2c14f7ee92861d69f02
116,120
def get_lr_metric(optimizer): """ Function for returning the learning rate in the keras model.fit history, as if it were a metric. :param optimizer: a tensorflow optimizer instances :return: float32, the learning rate """ def lr(y_true, y_pred): # return optimizer._decayed_lr(tf.float32) # I use ._decayed_lr method instead of .lr return optimizer.lr return lr
c382d5b536907f8e36afd13419a2916ae877704f
116,126
def get_items(obj): """Get the items of a dict-like or list-like object.""" if hasattr(obj, 'items'): items = obj.items() else: items = enumerate(obj) return items
7a1b9c702915b4e9f8c5fe506de12e6b3e2dab58
116,132
def chk_pfx( msg, p ): """check if msg content contains the given prefix""" return msg[:len(p)] == p
b031ff7765502c52fc8e27e791fe7078b874c911
116,133
from typing import OrderedDict def commits_diff_between_branches(base, divergent, repo): """ Get the commits in branch `divergent` that are not in `base`. :param base: :param divergent: :param repo: :return: an `OrderedDict whose keys are the sha1 of the commits and values the commit titles """ commits = OrderedDict() out = repo.git.log('--oneline', '{}..{}'.format(base, divergent)) for line in out.split('\n'): sha, _, title = line.partition(' ') commits[sha] = title return commits
c6cd08910422c053586c783a2ecef4e4bfbe304f
116,137
import math def miter_butt(points, width, weights, shifts, nib=None): """Represent weighted data points via varying linewidth. Parameters ---------- points : list of 2-tuple Vertices of linear spline. width : float Overall linewidth scaling factor. weights : list of float Weights of `points`. shifts : list of float Displacements in weight direction. nib : float Angle of broad pen nib. If ``None``, the nib is held perpendicular to the direction of the current line segment. Line segments are connected using the miter joint. Returns ------- list of 2-tuple Fatband outline. See Also -------- fatband : Equivalent routine without miter line join. """ N = len(points) x, y = tuple(zip(*points)) upper = [] lower = [] for n in range(N - 1): if nib is not None: alpha = nib else: alpha = math.atan2(y[n + 1] - y[n], x[n + 1] - x[n]) + math.pi / 2 dx = 0.5 * width * math.cos(alpha) dy = 0.5 * width * math.sin(alpha) lower.append((x[n] - dx, y[n] - dy, x[n + 1] - dx, y[n + 1] - dy)) upper.append((x[n] + dx, y[n] + dy, x[n + 1] + dx, y[n + 1] + dy)) X = [] Y = [] for segs in upper, lower: X.append([segs[0][0]]) Y.append([segs[0][1]]) for n in range(1, N - 1): x1a, y1a, x1b, y1b = segs[n - 1] x2a, y2a, x2b, y2b = segs[n] dx1 = x1b - x1a dy1 = y1b - y1a dx2 = x2b - x2a dy2 = y2b - y2a det = dy1 * dx2 - dx1 * dy2 if det: X[-1].append((x1a * dy1 * dx2 - y1a * dx1 * dx2 - x2a * dx1 * dy2 + y2a * dx1 * dx2) / det) Y[-1].append((x1a * dy1 * dy2 - y1a * dx1 * dy2 - x2a * dy1 * dy2 + y2a * dy1 * dx2) / det) else: X[-1].append(x2a) Y[-1].append(y2a) X[-1].append(segs[-1][2]) Y[-1].append(segs[-1][3]) XA = [] XB = [] YA = [] YB = [] for n in range(N): a1 = 0.5 + shifts[n] - 0.5 * weights[n] a2 = 0.5 - shifts[n] + 0.5 * weights[n] b1 = 0.5 + shifts[n] + 0.5 * weights[n] b2 = 0.5 - shifts[n] - 0.5 * weights[n] XA.append(a1 * X[0][n] + a2 * X[1][n]) XB.append(b1 * X[0][n] + b2 * X[1][n]) YA.append(a1 * Y[0][n] + a2 * Y[1][n]) YB.append(b1 * Y[0][n] + b2 * Y[1][n]) return list(zip(XA + XB[::-1], YA + YB[::-1]))
f955e58af33b22122dff1ed3def9cc057b258b4b
116,140
def _vv(vec1, vec2): """ Computes the inner product ``< vec1 | vec 2 >``. """ return (vec1[..., None, :] @ vec2[..., None])[..., 0, 0]
186f9f1cb56ab753557c66ec0b42e589aa3f85e2
116,142
def _key(oid): """Create a key for an OID. Args: oid: SNMP OID Returns: result: Key value """ # Initialize key variables result = '' limit = 8 table = { '.1.3.6.1.2.1.2.2.1.1': 'ifIndex', '.1.3.6.1.2.1.2.2.1.10': 'ifInOctets', '.1.3.6.1.2.1.2.2.1.11': 'ifInUcastPkts', '.1.3.6.1.2.1.2.2.1.12': 'ifInNUcastPkts', '.1.3.6.1.2.1.2.2.1.13': 'ifInDiscards', '.1.3.6.1.2.1.2.2.1.14': 'ifInErrors', '.1.3.6.1.2.1.2.2.1.15': 'ifInUnknownProtos', '.1.3.6.1.2.1.2.2.1.16': 'ifOutOctets', '.1.3.6.1.2.1.2.2.1.17': 'ifOutUcastPkts', '.1.3.6.1.2.1.2.2.1.18': 'ifOutNUcastPkts', '.1.3.6.1.2.1.2.2.1.19': 'ifOutDiscards', '.1.3.6.1.2.1.2.2.1.2': 'ifDescr', '.1.3.6.1.2.1.2.2.1.20': 'ifOutErrors', '.1.3.6.1.2.1.2.2.1.21': 'ifOutQLen', '.1.3.6.1.2.1.2.2.1.22': 'ifSpecific', '.1.3.6.1.2.1.2.2.1.3': 'ifType', '.1.3.6.1.2.1.2.2.1.4': 'ifMtu', '.1.3.6.1.2.1.2.2.1.5': 'ifSpeed', '.1.3.6.1.2.1.2.2.1.6': 'ifPhysAddress', '.1.3.6.1.2.1.2.2.1.7': 'ifAdminStatus', '.1.3.6.1.2.1.2.2.1.8': 'ifOperStatus', '.1.3.6.1.2.1.2.2.1.9': 'ifLastChange', '.1.3.6.1.2.1.31.1.1.1.1': 'ifName', '.1.3.6.1.2.1.31.1.1.1.10': 'ifHCOutOctets', '.1.3.6.1.2.1.31.1.1.1.11': 'ifHCOutUcastPkts', '.1.3.6.1.2.1.31.1.1.1.12': 'ifHCOutMulticastPkts', '.1.3.6.1.2.1.31.1.1.1.13': 'ifHCOutBroadcastPkts', '.1.3.6.1.2.1.31.1.1.1.14': 'ifLinkUpDownTrapEnable', '.1.3.6.1.2.1.31.1.1.1.15': 'ifHighSpeed', '.1.3.6.1.2.1.31.1.1.1.16': 'ifPromiscuousMode', '.1.3.6.1.2.1.31.1.1.1.17': 'ifConnectorPresent', '.1.3.6.1.2.1.31.1.1.1.18': 'ifAlias', '.1.3.6.1.2.1.31.1.1.1.19': 'ifCounterDiscontinuityTime', '.1.3.6.1.2.1.31.1.1.1.2': 'ifInMulticastPkts', '.1.3.6.1.2.1.31.1.1.1.3': 'ifInBroadcastPkts', '.1.3.6.1.2.1.31.1.1.1.4': 'ifOutMulticastPkts', '.1.3.6.1.2.1.31.1.1.1.5': 'ifOutBroadcastPkts', '.1.3.6.1.2.1.31.1.1.1.6': 'ifHCInOctets', '.1.3.6.1.2.1.31.1.1.1.7': 'ifHCInUcastPkts', '.1.3.6.1.2.1.31.1.1.1.8': 'ifHCInMulticastPkts', '.1.3.6.1.2.1.31.1.1.1.9': 'ifHCInBroadcastPkts', } # Search for a match in the table splits = oid.split('.') for count in range(0, limit): key = '.'.join(splits[:-count]) if key in table: result = table[key] break return result
bbde372e38990b57c6106ae52437e0028b4c0649
116,143
def compute_zT(rho, seebeck, kappa, temperature): """Returns the thermoelectric figure of merit. Note: All inputs should have SI units. """ return seebeck ** 2 * temperature / (rho * kappa)
035dd75573f4fc5b9927699e10533de244f43054
116,146
def prettify(soup): """ Prettify HTML source. The HTML source is in a soup object. The return value is a string! """ return soup.prettify()
a12ac0fcbf854ab327375f20a3039ec5da9a55d8
116,150
from datetime import datetime def read_log_file(path): """ Parse a LabView log file and return a dictionary of the parameters. Parses the text of a file line-by-line according to how they're written. Several values present in only newer log files are attempted and excepted as None. Failure to parse one of those lines will pass and return the dictionary as-is. The output of this is designed to and must return a dictionary such that: LogFile(**read_log_file(file)) creates a LogFile without error. :param Path path: path to the file to be read. :return dict: returns a dictionary containing all logged parameters """ data = path.read_text().split('\n') logdata = { 'date': datetime.strptime(data[18].split('\t')[0], '%Y%j%H%M%S'), 'sample_time': data[0].split('\t')[1], 'sample_flow': data[1].split('\t')[1], 'sample_type': data[2].split('\t')[1], 'backflush_time': data[3].split('\t')[1], 'desorb_temp': data[4].split('\t')[1], 'flashheat_time': data[5].split('\t')[1], 'inject_time': data[6].split('\t')[1], 'bakeout_temp': data[7].split('\t')[1], 'bakeout_time': data[8].split('\t')[1], 'carrier_flow': data[9].split('\t')[1], 'sample_flow_act': data[20].split('\t')[1], 'sample_num': data[10].split('\t')[1], 'ads_trap': data[12].split('\t')[1], 'sample_p_start': data[13].split('\t')[1], 'sample_p_during': data[19].split('\t')[1], 'gcheadp_start': data[14].split('\t')[1], 'gcheadp_during': data[31].split('\t')[1], 'wt_sample_start': data[15].split('\t')[1], 'wt_sample_end': data[21].split('\t')[1], 'ads_a_sample_start': data[16].split('\t')[1], 'ads_b_sample_start': data[17].split('\t')[1], 'ads_a_sample_end': data[22].split('\t')[1], 'ads_b_sample_end': data[23].split('\t')[1], 'trap_temp_fh': data[24].split('\t')[1], 'trap_temp_inject': data[26].split('\t')[1], 'trap_temp_bakeout': data[28].split('\t')[1], 'battv_inject': data[27].split('\t')[1], 'battv_bakeout': data[29].split('\t')[1], 'gc_start_temp': data[25].split('\t')[1], 'gc_oven_temp': data[32].split('\t')[1], 'wt_hot_temp': data[30].split('\t')[1], 'sample_code': data[18].split('\t')[0], 'mfc1_ramp': None, 'trapheatout_flashheat': None, 'trapheatout_inject': None, 'trapheatout_bakeout': None } try: logdata['mfc1_ramp'] = data[33].split('\t')[1] logdata['trapheatout_flashheat'] = data[34].split('\t')[1] logdata['trapheatout_inject'] = data[35].split('\t')[1] logdata['trapheatout_bakeout'] = data[36].split('\t')[1] except IndexError: pass return logdata
b9f060d4392267ef5862dd4ff44ea8a62be203ef
116,152
import hashlib def get_sha1_sums(file_bytes): """ Hashes bytes with the SHA-1 algorithm """ return hashlib.sha1(file_bytes).hexdigest()
c2dd9ea4875a8dbd8fa7d554530b1c6c4aef4eac
116,153
def normalize(prices): """Normalize pandas DataFrame by divide by first row""" return prices / prices.iloc[0]
29bad57437372eb72fd227620fda93f48244f741
116,159
import itertools def pairwise(iterable): """This function is used to create pairwise pairs for the input iterable. An example is given below.""" # pairwise('ABCDEFG') --> AB BC CD DE EF FG a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
613bbc69fada73e9c13417f5d6a92227a109c982
116,161
def bytes_to_mac(addr_bytes): """Convert address bytes to MAC.""" return ":".join(f"{b:02x}" for b in reversed(addr_bytes))
52d12d48ce581b72aab83482b614230473a6a5ad
116,163
def check_fields(fields, args): """Check that every field given in fields is included in args.args. - fields (tuple): fieldes to be searched in args - args (dict): dictionary whose keys will be checked against fields """ for field in fields: if field not in args: return False return True
fa6558ef9fdd1cba4c9f0a46b6e910ecbba9a6b4
116,164
import csv def lodict2csv(listofdicts, out, fnames=None, header=True): """ Write a dictionary list with csv formatting to the stream out. :param fnames: when provided as a list, it is used as the column selection, otherwise all keys occuring at least once are used. :param header: should the header be written """ if fnames is None: fnames = set([]) for dictionary in listofdicts: fnames.update(list(dictionary.keys())) fnames = sorted(fnames) csv_writer = csv.DictWriter(out, fieldnames=fnames, restval='NA', extrasaction='ignore') if header: csv_writer.writeheader() csv_writer.writerows(listofdicts) return len(listofdicts)
228936ae84b6977504573376895070f96c986a9a
116,169
import ast def get_full_scope(series): """Get a string of all the words in scope including the cue, in order. """ idx_1 = ast.literal_eval(series["scopes_idx"]) idx_2 = ast.literal_eval(series["cues_idx"]) scope = " ".join([s for i1, i2, s in zip(idx_1, idx_2, series["sent"].split(" ")) if i1 or i2]) return scope
d4178faf6a1b90b25934b6f4610573cdc98a1877
116,180
def get_tr1(name): """In libstd++ the tr1 namespace needs special care. Return either an empty string or tr1::, useful for appending to search patterns. Args: name (str): the name of the declaration Returns: str: an empty string or "tr1::" """ tr1 = "" if "tr1" in name: tr1 = "tr1::" return tr1
c44d1f2830fb0f0ee6fcfeda331a46868676363c
116,181
def parse_line(line): """ Parses a log line and returns its components :param line: :return: tuple """ addr, insn, insnty, val, flow = "", "", "", "", "" parts = line.rstrip().split(" | ") if len(parts) == 5: addr, insn, insnty, val, flow = parts elif len(parts) == 4: addr, insnty, val, flow = parts elif len(parts) == 2: addr, flow = parts else: raise Exception("Incorrect line format: {}".format(line)) return addr, insn, insnty, val, flow
a611f5b483495b2230c615e8adb845e0a16548d7
116,185
def parse_pmofn_qr_part(data): """Parses the QR as a P M-of-N part, extracting the part's content, index, and total""" of_index = data.index("of") space_index = data.index(" ") part_index = int(data[1:of_index]) part_total = int(data[of_index + 2 : space_index]) return data[space_index + 1 :], part_index, part_total
e682731bf471017eed6d22d6bb5bf36af258c963
116,187
def crop(img): """Returns a cropped image to pre-defined shape.""" return img[75:275, 125:425]
571ca0f44637dbd4eabc903d643fcaf346c34df9
116,188