content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def extractFieldValueFromGml(gmlString, labelInit,labelFin): """ Returns the value between two labels in a gml. Eliminates spaces at start and end of the returned value """ g=gmlString s1=labelInit s2=labelFin i=g.find(s1) f=g.find(s2) g2= g[i:f] s1=g2.find('>')+1 g3=g2[s...
a4982771caa9d4b2b445049cc3de335aa6b3521a
661,631
def default_account(web3): """Returns the default account which is used to deploy contracts""" return web3.eth.defaultAccount
f3b5e684fd050e04ff46b508ca516b5047914cd4
661,632
def index_map(idx_lines): """Returns a map from the orbital index to its descriptive quantum numbers :param idx_lines: lines defining the index -> orbital key """ idx_map = dict() for line in idx_lines: row = line.split() row[0] = int(row[0]) idx_map[row[0]] = tuple(row[1...
e274094b9adcbc99ac1b166ee2c54a048d6e0ca3
661,635
def truncate(phrase, n): """Return truncated-at-n-chars version of phrase. If the phrase is longer than, or the same size as, n make sure it ends with '...' and is no longer than n. >>> truncate("Hello World", 6) 'Hel...' >>> truncate("Problem solving is the best!...
f72251162baf220a4cf3555b4b95a7a7ef00aef9
661,636
from typing import Optional from typing import List def trits_from_int(n: int, pad: Optional[int] = 1) -> List[int]: """ Returns a trit representation of an integer value. :param n: Integer value to convert. :param pad: Ensure the result has at least this many trits. References:...
1e823243111486eeeab78ceaa9e2f4d0ead65bbe
661,638
def event_team_object_factory(event_id, team_id): """Cook up a fake eventteam json object from given ids.""" eventteam = { 'event_id': event_id, 'team_id': team_id } return eventteam
b8913a853526a9bee937dfe50b130025b828c69a
661,639
def _GetSetOfAllTestArgs(type_rules, shared_rules): """Build a set of all possible 'gcloud test run' args. We need this set to test for invalid arg combinations because gcloud core adds many args to our args.Namespace that we don't care about and don't want to validate. We also need this to validate args comin...
7f6facc49c6bd98684651079a134eae6b6f759c3
661,640
from typing import Tuple from typing import Optional from typing import Union from typing import Type from typing import Any def split_list_type(ftype) -> Tuple[Optional[Union[Type[list], Type[set]]], Any]: """Checks if the ftype is a List (or Set) type and return the list type and the inner type. Returns: ...
fd6ad37c35bf4a657fd80ae0a343e3bb0819b3f2
661,643
from typing import Any import click def cli_ssh_group_member_id_argument() -> Any: """An argument to specify the ssh group member id. This is effectively the id of a user that is part of the group. """ return click.argument( "ssh_group_member_id", type=str, required=True, ...
07a38d4ee137c007058a2869630a760ed4126de9
661,644
import math def total_level(source_levels): """ Calculates the total sound pressure level based on multiple source levels """ sums = 0.0 for l in source_levels: if l is None: continue if l == 0: continue sums += pow(10.0, float(l) / 10.0) level =...
3117b92f59e821941ac1d8aa80f32c161d357e71
661,649
def take_nth(n): """Take each nth item from a collection, always start on first (0 idx).""" def generator(coll): for i, item in enumerate(coll): if not i % n: yield item return generator
184d5244172a43b00a17504b379e1b3f8fa436ae
661,654
import torch def l2norm(X): """L2-normalize columns of X """ norm = torch.pow(X, 2).sum(dim=-1, keepdim=True).sqrt() X = torch.div(X, norm+1e-10) return X
7517e81e97ec63be085fd2f7f6502e6b3c7541d8
661,657
import colorsys def rgb_to_hsv(r: int, g: int, b: int) -> tuple: """Convert an RGB color (from 0 to 255) to HSV equivalent (from 0 to 1) """ return colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
1389ef4f69e32494aa4b21ed91d9b3aba6d96da5
661,659
def _update_nested_dict(dict_1: dict, dict_2: dict) -> dict: """ Update `dict_1` with elements from `dict_2` in a nested manner. If a value of a key is a dict, it is going to be updated and not replaced by a the whole dict. Parameters ---------- dict_1 : dict The dictionary to be update...
7c7b617e346c692a0cd77fff862dad7dddf64672
661,662
from pathlib import Path def ensure_dmg_extension(filepath: Path) -> Path: """ Make sure given file have .dmg extension """ if filepath.suffix != '.dmg': return filepath.with_suffix(f'{filepath.suffix}.dmg') return filepath
e5189acaa058edb13cb282fbfaf51238e2af0522
661,664
def _NodeShape(data): """Helper callback to set default node shapes.""" node_type = data.get("type", "statement") if node_type == "statement": return "box" elif node_type == "identifier": return "ellipse" elif node_type == "magic": return "doubleoctagon" else: return ""
856bb7d0f728ee171aca8321da644e9d2243b00e
661,665
def find_key_value_in_dict(d, key): """ Searches a dictionary (with nested lists and dictionaries) for the first value matching to the provided key. """ for k, v in d.iteritems(): if k == key: return v elif isinstance(v, dict): r = find_key_value_in_dict(v, ke...
476e5a53b15c9e3049f7f7b9e244481a2174f79f
661,667
def check_pre(v, g, order): """Check if all predecessors have already been placed.""" if order.index(v) > -2: return False for v2 in g.predecessors(v): if order.index(v2) == -2: return False return True
d61b2052bb93098017618ba6ac668712a4a355ce
661,668
from pathlib import Path def is_illegal_dir(d: Path): """Refuse to remove directories for some situations, for safety. """ if (d / ".git").exists(): return ".git file found" if d.absolute() == Path.home().absolute(): return "cannot replace home directory" if d.absolute == Path("/")...
7282f629f631f91b4a332d8f8a7420e41afd9a6b
661,670
def shift_to_include_gamma(mp_grid): """ Calculate the shift required to include $\\Gamma$. in the Monkhorst-Pack grid. Parameters: mp_grid (:obj:`list` of :obj:`int`): number of grid points in each reciprocal space direction. Returns: :obj:`list` of :obj:`float`: shift req...
a8892d916df77f21c502ec395c5ae34b24b7ae27
661,678
def get_support(item, item_set): """ Get support of specified item. Args: item (frozenset): The specified item. item_set (list[tuple]): The frequent item set with support. Returns: Support of specified item. """ for key, value in item_set: if frozenset(key) == i...
bb79d757fe07eb7c1880d6f8ac75330e83b1c903
661,679
def liquidThermalConductivity(T, lTCP): """ liquidThermalConductivity(float T, list lTCP) liquidThermalConductivity (W/m/K) = 10**(A + B*(1-T/C)^(2/7)) Parameters T, temperature in Kelvin lTCP, A=lTCP[0], B=lTCP[1], C=lTCP[2] A, B, and C are regression coefficients Returns...
532221136676cfdf01b155e3d3114aafaabbba03
661,680
def load_stop_words(words): """Load stopwords list, return a set""" with open(words, "r") as lines: set_stop_words = set() for i in lines: set_stop_words.add(i.strip()) return set_stop_words
7f1cb89af7d4cc5b17861af32484cf3c1a2b37f9
661,683
def get_param_value_and_result_list_call(exp_run, val_results_list, **kwargs): """ Callable functions to be used when traversing experiments. Returns dictionary with data organised by environment and agent parameters and their available values in any of the experiments. :param exp_run: Dictionary w...
e6bd19c9a1bfb350757f55070e39ba3414c32c55
661,685
def fitLine(line_points): """ Given 2 points (x1,y1,x2,y2), compute the line equation y = mx + b""" x1 = line_points[0] y1 = line_points[1] x2 = line_points[2] y2 = line_points[3] m = (y2 - y1) / (x2 - x1) b = y1 - m * x1 return (m, b)
c2ae660fbc0f49b868e3f3bbbddea25a6684abed
661,686
def map_items_to_parent(items, parents): """Groups all items into a list based on thier respective parent ex: pages have request, runs have pages """ item_lists = {} if len(parents) > 0: pk = parents.values()[0].pk for p_id in parents: item_lists[p_id] = [] for i...
8d165bae685546662c6be7f86196812e84f6e5a3
661,688
def _check_classifer_response_method(estimator, response_method): """Return prediction method from the response_method Parameters ---------- estimator: object Classifier to check response_method: {'auto', 'predict_proba', 'decision_function'} Specifies whether to use :term:`predict...
10771d4cf3c6bb160f633324c13e2cb61eb62dc9
661,689
import logging def base_func(aggregate_function): """Deals with the possibility of functools.partial being applied to a given function. Allows access to the decorated 'return' attribute whether or not it is also a partial function Args: aggregate_function (callable) Either a raw function or a...
902853a53a5043674b241753d532567d0d6576aa
661,690
def to_rgba_array(arr): """ Convert 2D integer values to RGBA tuples . Parameters ---------- arr: array of input values to split into rgba, will be cast to uint32 Returns ------- array of RGBA tuples: [[[R, G, B, A] ...]] (uint8) """ # from: http://stackoverflow.com/questio...
2a008685ef759a2829ee3c4949a58d3490b95523
661,691
def str_fill(i, n): """Returns i as a string with at least n digits. i: int n: int length returns: string """ return str(i).zfill(n)
78fb17307fc477b6f62497c7f07f57b9cfde948a
661,695
def is_valid_input(ext): """ Checks if input file format is compatible with Open Babel """ formats = ["dat", "ent", "fa", "fasta", "gro", "inp", "log", "mcif", "mdl", "mmcif", "mol", "mol2", "pdb", "pdbqt", "png", "sdf", "smi", "smiles", "txt", "xml", "xtc"] return ext in formats
bb9ca7013470303be4812078b6ec5e7d5092b99c
661,697
def get_exit_code(matches): """ Determine exit code """ exit_code = 0 for match in matches: if match.rule.id[0] == 'W': exit_code = exit_code | 4 elif match.rule.id[0] == 'E': exit_code = exit_code | 2 return exit_code
68bfe810adebf25b1b67af2af10a7ea1404194f6
661,698
def computa_menor_tamanho_lista(lista_de_listas): """ Recebe uma lista de listas e retorna o tamanho da menor lista """ menor_lista = len(lista_de_listas[0]) for lista in lista_de_listas: if(len(lista) < menor_lista): menor_lista = len(lista) return menor_lista
3694bd9abc4054f258986ab0e68e20f38772b676
661,700
def parseBrowserBase(base_config): """ Parses the given option value into type and base url @param base_config: The option value @type base_config: C{str} @return: The type and the base url @rtype: C{tuple} """ if base_config: tokens = base_config.split(None, 1) ...
dd2b686024d77ca317f8421413d256a9b60199fa
661,701
def is_voiced(sound): """ Check if a sound is voiced or not. """ if sound.obj.phonation == "voiced" or sound.obj.breathiness or sound.obj.voicing: return True return False
b10247bdb942bfe59c9e9b9cb193bf4d678958d3
661,702
def update_portfolio(returns, withdrawal, stock_allocation, balance): """Update a portfolio based on performance in a single year. Parameters ---------- returns : dict Stock and bond returns for a single year. withdrawal : float Amount to withdraw from the portfolio. The withdrawal ...
1f05bfcb5857473ec2f9e0ea8a65d0a1f9c4a104
661,708
def get_ratio_served(solution): """Returns the ratio of users that have been assigned a video representation. """ nserved = 0 for u in solution["users"]: if "mos" in u: nserved += 1 return nserved/len(solution["users"])
7e609bee5fa4fe1ce0e45fa1a5490ef718e0af80
661,712
def is_form_post(environ): """Determine whether the request is a POSTed html form""" content_type = environ.get('CONTENT_TYPE', '').lower() if ';' in content_type: content_type = content_type.split(';', 1)[0] return content_type in ('application/x-www-form-urlencoded', ...
4b5966c87263161a1cdf182fc215149f850682de
661,715
def find_cmd0(cmd_stream, cmd) -> int: """Returns parameter of the first command in the stream that matches the given command""" for command in cmd_stream: if (command & 0xFFFF) == cmd.value: return (command >> 16) & 0xFFFF assert False, f"Not in command stream: {cmd}"
f2b4abdce13b3d21eafbe87a3920766dd493c7f8
661,716
from typing import Dict import re def parse_header_links(links_header: str) -> Dict[str, Dict[str, str]]: """ Parse a "Link" header from an HTTP response into a `dict` of the form:: {"next": {"url": "...", "rel": "next"}, "last": { ... }} """ # <https://git.io/JcYZi> links: Dict[str, Dict...
5f64f487cf541154c5751e705933cf41e250a03d
661,717
def filter_pattern_group(note_begin_pattern, note_end_pattern, note_metronome_group, note_end_metronome_group): """ The pattern group from dataset contains all notes. This filters it to only notes present in the new map """ for i,p in enumerate(note_begin_pattern): if i not in note_metronome_gro...
ecbf3d49b358c7bac351f83a3d040d25fcc33a90
661,718
def is_numeric(series, max_unique=16): """Flag if series is numeric.""" if len(set(series.values[:3000])) > max_unique: return True return False
8f3b492b8eb7a230f8dd01d628b12b39a517332a
661,719
def substrings_of_length(length, string): """ Given a string, return a list of all substrings of that string with a given length. For example, substrings_of_len(2, "ABC") returns ["AB", "BC"]. """ # You could also use a generator here, but I don't want to overcomplicate # things. substrings = [] for ...
3f20efbeb11eab840e27d43ea7932480a89f9d55
661,721
def get_cfg_var(interp, var): """ Gets the value of a PHP configuration option""" w_value = interp.config.get_ini_w(var) if w_value is None: return interp.space.w_False return w_value
605f13abd8b09cb0316862f9eb0351137246db5c
661,726
def rank_features(explanation): """ Given an explanation of type (name, value) provide the ranked list of feature names according to importance Parameters ---------- explanation : list Returns ---------- List contained ranked feature names """ ordered_tuples = sorted(explanation, ...
f1d14296434f800fc03313cb447a44a2c11ea123
661,727
def _JoinWithOr(strings): """Joins strings, for example, into a string like 'A or B' or 'A, B, or C'.""" if not strings: return '' elif len(strings) == 1: return strings[0] elif len(strings) == 2: return strings[0] + ' or ' + strings[1] else: return ', '.join(strings[:-1]) + ', or ' + strings[...
dd50c410a11fccd05d5fba6797919c553662e924
661,731
def convert_coco_category(category_id): """ Convert continuous coco class id to discontinuous coco category id (0..79 --> 0..90) """ match = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, ...
f32b96850acfa59b83c0ab01d01a0f0f9fef9196
661,734
def stringToInt(message): """ Convert input string message into an integer """ string_to_binary = message.encode('utf8') return int.from_bytes(string_to_binary, byteorder='big', signed=False)
dc98b5630120b0c8857cd8f07a55b29b964e1334
661,736
def Arn(key): """Get the Arn attribute of the given template resource""" return { 'Fn::GetAtt': [key, 'Arn']}
d92f92789171c005490b4309fd1fc6570c1a0b79
661,738
from typing import Type from typing import Set def _all_subclasses_of(cls: Type) -> Set[Type]: """ All subclasses of cls, including non-direct ones (child of child of ...). """ direct_subclasses = set(cls.__subclasses__()) return direct_subclasses.union( s for d in direct_subclasses for s ...
077908503def08cf519056ca0abb09f5916804db
661,741
def HandleNearestNeighborQuery(locale_finder, lat, lon): """Verifies passed arguments and issues a nearest neighbor lookup. Args: lat (float): Latitude of interest. lon (float): Longitude of interest. Raises: SyntaxError: If expected parameters are not provided (are None). Ret...
1316e2e0f67173a8cb1266dc33a13901eccc6328
661,746
def choose_condition(data, events, condition): """Filters out a specific condition from the data. :param data: data from which to extract conditions from :type data: numpy array :param events: event data of shape [trials x 4] :type events: numpy array :param condition: Condition to be filtered ...
8fa8cc12a11561c3a69a067b1f302dd1ccaf1b31
661,747
def get_attributes(obj): """ Returns all attributes of an object, excluding those that start with an underscore. Args: obj: the object Returns: A dictionary of attributes """ return { key: getattr(obj, key) if not key.startswith("_") else None for key in di...
1b6e39e2d97e50254e67bcbdcc6cd4121b38e370
661,751
import functools import operator def product(xs): """ product :: Num a => [a] -> a The product function computes the product of a finite list of numbers. """ return functools.reduce(operator.mul, xs, 1)
01664f7d4ecdf088a6e996120162ebf6f5e74768
661,752
def in_slots(obj, key, default=False): """ Returns true if key exists in obj.__slots__; false if not in. If obj.__slots__ is absent, return default """ return (key in obj.__slots__) if getattr(obj, '__slots__', None) else default
c64473a323302eacefcf211c1114686ef1feec2d
661,754
def get_color(node, color_map): """ Gets a color for a node from the color map Parameters -------------- node Node color_map Color map """ if node in color_map: return color_map[node] return "black"
3f601fddcb31255bf61c6ac2a61c890a658b3d13
661,758
def format_rp_labels(rp_label: str) -> str: """ Helper function for formatting the RP label. Args: rp_label: Reaction plane orientation label to be formatted. Returns: Properly formatted RP label. """ # Replace "_" with "-" return rp_label.replace("_", "-").capitalize()
6a34102be81ee0a167aa0a24acbe2c6e84b9caa4
661,761
def pad_sentence_batch(sentence_batch, pad_int): """Pad sentences with <PAD> so that each sentence of a batch has the same length""" max_sentence = max([len(sentence) for sentence in sentence_batch]) return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]
fe586a7cd3c3f71bae7b8c753bd8be917855c15d
661,764
def check_is_video(file_name): """ Ensures passed file inputs are of recognized media format. """ formats = ['flv', 'mp4', 'avi', 'mp3', 'flaac'] return any([extension for extension in formats if file_name.endswith(extension)])
645edcf7b440b26c7f1982a38d40c3dd94baf2f5
661,766
def FOREVER(*_, **__): """Will always return False (continue).""" return False
8da7ecdfc4af34f1c7a2f5351ffd76f205d61d71
661,768
def c(field): """Remove " from field""" return field.replace('"', "")
2441c9df35d43909aa1a189e6a349888c00c7483
661,769
def find(strng, ch): """ Find and return the index of ch in strng. Return -1 if ch does not occur in strng. """ ix = 0 while ix < len(strng): if strng[ix] == ch: return ix ix += 1 return -1
8d34718b65e951e3ea957406bab27270211557df
661,771
def wrap(seq, bases=60): """ Print wrapped sequence. Args: seq (str): Nucleotide sequence bases (int): Number of bases to include on each line. """ count = 0 ret = '' for i in seq: if count >= bases: ret = ret + '\n' count = 0 ret = re...
2777fc5c42d36a18dda28966a4db300a212c2a60
661,772
from typing import Any def is_shutdown_time_int(hour: Any, minute: Any) -> bool: """Check if shutdown time are numbers. Args: hour (Any): hour according to user config minute (Any): minute according to user config Returns: bool: True if both are numbers """ return type(h...
767816d79c73bda92ad2bd9d92426073f9e6c18e
661,774
def transform_fs_access_output(result): """ Transform to convert SDK output into a form that is more readily usable by the CLI and tools such as jpterm. """ new_result = {} useful_keys = ['acl', 'group', 'owner', 'permissions'] for key in useful_keys: new_result[key] = result[key] retur...
7cbd87d49c1c1781d6de847ce3c0ccbb7b697f2a
661,778
import numbers def validate_int(x, name, minimum=None, maximum=None) -> int: """Validate integer function parameters. Parameters ---------- x : object Object to validate as an int. name : str Name of the function parameter. minimum : int, optional Minimum value x can t...
f3d56cc494312873d038c92b2f12a21a0a0da1cd
661,782
import re def get_columns_matching(dataframe, pattern, regex=False): """ Returns the columns containing pattern (or satisfying the regex pattern, if regex=True). :param dataframe: Dataframe whose columns are being tested :param pattern: String to test columns for :param regex: If True, then check...
612efab6fbd17d42307f64451a0bfe6eca7f45be
661,783
def isinAngleLimits(angle, min_angle, max_angle): """Check if an angle value is between min and max angles in degrees""" if (min_angle <= angle <= max_angle) or (min_angle <= 180 - angle <= max_angle): return True return False
3ed0ea5857b81b1281afbb7ae1ac91b3e2eb9e1d
661,785
def say_hello(name: str) -> str: """ Greet someone in English. :param name: Name of the person to greet. :return: The greeting. """ return f"Hello {name}!"
819d4dff77813faaa4a852b0d2d4cf9d9020f31e
661,786
def replace(s: str): """ Replace blank to "%20". Parameters ---------- s: str given string Returns ------- out: str return string """ if not s: return s num_blank = 0 for i in s: if i == " ": num_blank += 1 raw_len = len(s...
632c9096a93d5cc3ef08ce4fbf4d699c7fc7c2fc
661,789
def is_same_domain(host, pattern): """ Return ``True`` if the host is either an exact match or a match to the wildcard pattern. Any pattern beginning with a period matches a domain and all of its subdomains. (e.g. ``.example.com`` matches ``example.com`` and ``foo.example.com``). Anything else ...
8581fd2d46a87d5533a017dbaa6a74bf5d98e5fa
661,791
def is_float(s): """ :param s: s is a string :return: True if string s can be cast to a float """ try: x = float(s) return True except: return False
4b98a6a8694868528da801d11a1d93103b97e2b1
661,792
def get_type( type_name ): """Return the type of the given node type string (without *? modifier).""" if type_name[ -1 ] == '*' or type_name[ -1 ] == '?': return type_name[ : -1 ] return type_name
b6fc297d16d704a67d094b1f7e40c0bec51ce049
661,793
def char_age(p0=1.0, p1=1e-12): """ Accepts a spin period (in s) and spin period derivative (in s/s) and returns the characteristic age. Units: years. """ tau = p0 / (2 * p1) return tau / (60 * 60 * 24 * 365)
70d7d124557ee83c1c56ef529b146c272c066870
661,795
def check_dermoscopic(meta): """Checking if a image is acquired through dermoscopy by ISIC's API. Parameter: meta: The metadata of the image getting through the API Return: True if the image is acquired through dermoscopy, False if it isn't """ if "image_type" not in meta["meta"]["acquisiti...
c1e2e31986090a5744fd283b6b702e4beb9b310d
661,796
def tuple_mul(tuple_item, num): """Perform element-wise multiplication by a scaler for a tuple or a number.""" if not isinstance(tuple_item, tuple): return tuple_item * num List = [] for item in tuple_item: if item is not None: List.append(item * num) else: ...
c9eef7ded731065f322752eb498868934a2ceda2
661,801
def _clean_job(job): """Remove and key/value pairs from job where the key is prefixed by an underscore. Args: job (JobState): The job to clean. Returns: JobState with all underscore-prefixed keys removed. """ for key in job.keys(): if key.startswith('_'): job....
e793f8b5626f64ee95a75655bbdba48f3fb9440e
661,803
def _tensor_to_list_of_channel_tensors(img): """Converts a tensor with dimensions of HWC or BHWC to a list of channels.""" if len(img.shape) == 3: # HWC. img_list = [img[:, :, c] for c in range(img.shape[-1])] elif len(img.shape) == 4: # BHWC. img_list = [img[:, :, :, c] for c in range(img.shape[-1])] ...
b257814bb8b10aec8decd3934315105f635a6dae
661,806
def name_without_commas(name): """ Takes a name formatted as "[LastNames], [FirstNames]" and returns it formatted as "[FirstNames] [LastNames]". If a name without commas is passed it is returned unchanged. """ if name and "," in name: name_parts = name.split(",") if len(name_pa...
19cec9abbef59fee3010fb5819febe28edf3fbf5
661,807
import inspect def methodName() -> str: """Returns string containing name of the calling method.""" return inspect.stack()[1][3]
df66e422d387ca398b1d7a0ddefe168318663bb0
661,809
def _dirname_map_fn(f): """Returns the dir name of a file. This function is intended to be used as a mapping function for file passed into `Args.add`. Args: f: The file. Returns: The dirname of the file. """ return f.dirname
4d2d54ff3395dedf571a9e24dbd0cbd3a03fdf8e
661,811
def indent(string, prefix=' '): """ Indent every line of this string. """ return ''.join('%s%s\n' % (prefix, s) for s in string.split('\n'))
9d6ed0fc3d19f2e59b8d34c9f98cbc011c2edd07
661,812
import re def interpret_cv(cv_index, settings): """ Read the cv_index'th CV from settings.cvs, identify its type (distance, angle, dihedral, or differance-of-distances) and the atom indices the define it (one-indexed) and return these. This function is designed for use in the umbrella_sampling jobtyp...
01ef867caf1aa8756182dcab3a0e3bc2261cacc2
661,824
def _parent_dirs(dirs): """Returns a set of parent directories for each directory in dirs.""" return set([f.rpartition("/")[0] for f in dirs])
33254c411bad173b8b02fc444d5ca04ed8748457
661,826
import textwrap def wrap(s): """ Wrap lines of text, retaining existing newlines as paragraph markers. >>> print(wrap(lorem_ipsum)) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nos...
f77a6b98b9a5ab729245fdfd9dfa1c9c823737d4
661,827
def is_string(data): """Utility method to see if data is a string.""" return isinstance(data, str)
0b60e2e766875f80d59ef57dce52a450d6a787e8
661,830
def convert_cache_variables(cache_json: list) -> dict: """ Convert list of cache variables returned by server to dictonary without unnecessary information. cache_json is 'cache' object from response to 'cache' request. """ return dict((entry['key'], entry['value']) for entry in cache_json)
497a1a75efdbbe1760243b4654680e4b0c13894c
661,832
def sort_dict_by_value(d): """ Returns the keys of dictionary d sorted by their values """ items=list(d.items()) backitems=[[v[1],v[0]] for v in items] backitems.sort() return [backitems[i][1] for i in range(0, len(backitems))]
7957b6abc77e29738f3aaa502857af49b7016ed1
661,834
def e(d): """Encode the given string instance using UTF-8.""" return d.encode('UTF-8')
a574fc5123ee838dfc975e3dbe3d101bfe3b5bef
661,835
def _pretty_state_identifier(state): """ returns 'off' for False and 'on' for True """ if state: return 'on' else: return 'off'
a4383b7061e2da73a6faab4819b848bc1375e884
661,838
def task_list_item_list_description(data, singular, plural): """ Returns a description for a task list item depending on how many items are in its contents """ if len(data) == 0: return None elif len(data) == 1: return f"1 {singular} added" else: return f"{len(data)} ...
6fe2230e40690377be8377c332d970fc649c2782
661,843
def is_dlang(syntax): """Returns whether the given syntax corresponds to a D source file""" return syntax == 'Packages/D/D.sublime-syntax'
d4b5b752b0dda3d424068f3c6761a7e65b487454
661,844
def get_confirmation(warningtext): """ Prints a warning message and asks for user confirmation Return Values: True: User selected Yes False: User selected No """ print() print(warningtext) while True: try: user_input = input("Please confirm (Y/N): ") ...
d34f66935d199b5cf230691bb197f0d9f4b78370
661,847
def package_resource_url(package_url, resource_path): """ Converts a package and resource path into a fuchsia pkg url with meta. """ return package_url + "#" + resource_path
88c3da427b383005b4805522b9ed065fe73cc2ee
661,850
def signExtend(x, n=8): """ Returns signed integer that is the sign extention of n bit unsigned integer x in twos complement form where x has n significant bits This is useful when unpacking bit fields where the bit fields use two's complement to represent signed numbers. Assumes the the upper bits...
f77ba0024568ebd6280fcfa5f48d3057109d8823
661,860
def ans_match_wh(wh_word, new_ans): """Returns a function that yields new_ans if the question starts with |wh_word|.""" def func(a, tokens, q, **kwargs): if q.lower().startswith(wh_word + ' '): return new_ans return None return func
e1ea32bd973ea37ccec4b28d8f491d7e8a2b6314
661,862
import inspect def get_caller_name(steps=2): """ When called inside a function, it returns the name of the caller of that function. Keyword arguments: steps - the number of steps up the stack the calling function is """ return inspect.stack()[steps][3]
4c513f561872f80a878906bc384b1826142d9dfd
661,863
def thermalConductivity(T, tCP): """ thermalConductivity(T, tCP) thermalConductivity (W/m/K) = A + B*T + C*T^2 Parameters T, temperature in Kelvin tCP, A=tCP[0], B=tCP[1], C=tCP[2] A, B, and C are regression coefficients Returns thermal conductivity in W/m/K at T ...
348e52dc16a864e72dc56a15635d1e61c51eee37
661,864
def chance(dice): """Score the given role in the 'Chance' category """ return sum(dice)
9a895ff6759e3afd330b56db87e57575c34b630e
661,870
def get_average_velocity(model): """ Gets the total average velocity over all the agents :param model: The model (environment) where the agents exist :return: The total average velocity over all the agents """ df = model.datacollector.get_agent_vars_dataframe() df.reset_index(inplace=True)...
1db399b1a431de715891c22d00f576c802d347d0
661,871