content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import torch def ls_discriminator_loss(scores_real, scores_fake): """ Compute the Least-Squares GAN metrics for the discriminator. Inputs: - scores_real: PyTorch Variable of shape (N,) giving scores for the real data. - scores_fake: PyTorch Variable of shape (N,) giving scores for the fake data. Outputs: - metrics: A PyTorch Variable containing the metrics. """ loss = (torch.mean((scores_real - 1) ** 2) + torch.mean(scores_fake ** 2)) / 2 return loss
dfbbfead7e4d64bda2d8b863338016d6722b8c4e
163,348
def has_obj_value(data_obj, attr): """Return weather dict has the given key or object has the given attribute.""" if isinstance(data_obj, dict): return attr in data_obj.keys() return hasattr(data_obj, attr)
c23c00c7fd6cc7a1823dc12744b9eb10e12fe528
239,758
def listify(x): """Puts non-list objects into a list. Parameters ---------- x: Object to ensure is list Returns ---------- :obj:`list` If ``x`` is already a list, this is returned. Otherwise, a list\ containing ``x`` is returned. """ if isinstance(x, list): return x else: return [x]
5251c6e70cce9a6b134e321c89a674915ac389b0
461,702
import re def normalize_hostname_to_rfc(mystr): """ Given a hostname, normalize to Nextdoor hostname standard Args: mystr (str): hostname to normalize Returns: normalized hostname Details: * lower everthing * delete anything which is not alphanumeric * compress multiple '.' or '-' * strip leading '-'s """ return re.sub('^[-]+', '', re.sub('[.]{2,}', '.', re.sub('[-]{2,}', '-', re.sub('[^a-z0-9-._]', '', mystr.lower()))))
ce6d6fd07ba12ac28f0d96bb4ee3dc0345e7bcd4
101,340
def get_auth_token( http_requests, url="https://danielvaughan.eu.auth0.com/oauth/token", client_id="Zdsog4nDAnhQ99yiKwMQWAPc2qUDlR99", client_secret="t-OAE-GQk_nZZtWn-QQezJxDsLXmU7VSzlAh9cKW5vb87i90qlXGTvVNAjfT9weF", audience="http://localhost:8080", grant_type="client_credentials", ): """Request and get the access token for a trusted client from Auth0. .. note:: We have hard-coded some test credentials here temporarily, which do not give any special permissions in the ingest service. Args: http_requests (HttpRequests): the HttpRequests object to use url (str): the url to the Auth0 domain oauth endpoint. client_id (str): the value of the Client ID field of the Non Interactive Client of Auth0. client_secret (str): the value of the Client Secret field of the Non Interactive Client of Auth0. audience (str): the value of the Identifier field of the Auth0 Management API. grant_type (str): type of OAuth 2.0 flow you want to run. e.g. client_credentials Returns: auth_token (dict): A dict containing the JWT (JSON Web Token) and its expiry (24h by default), the scopes granted, and the token type. Raises: requests.HTTPError: for 4xx errors or 5xx errors beyond timeout """ url = url headers = {"content-type": "application/json"} payload = { "client_id": client_id, "client_secret": client_secret, "audience": audience, "grant_type": grant_type, } response = http_requests.post(url=url, headers=headers, json=payload) response.raise_for_status() auth_token = response.json() return auth_token
a1dfc8a1b873138967e7e7c7ed497fda8d22f16c
554,139
import itertools def flatten(gen): """Flatten a sequence, but only one level deep.""" return itertools.chain.from_iterable(gen)
a15b84d9741962a4e4588253a41bb8b538635bfa
567,374
import statistics def get_partition_agreement_score(partitionA, partitionB): """ Compute the partition agreement score for two partitions. """ scores = [] for i, prtB in enumerate(partitionB): score = 0 for j, prtA in enumerate(partitionA): if prtB.issubset(prtA): score = 1 break scores += [score] return statistics.mean(scores or [0])
0a80b858ea768c08c368d97406f181a0b9c75b1c
60,673
def get_filter_par(filter_group, filter_ids, key): """ Given a pandas groupby object 'filter_group' that group the filters by filter_number (giving a filter set) and a key, get the first value for that key in each group. """ return [filter_group[i][0][key] for i in filter_ids]
bd5f9a08c20152956443d8f39a0ebe4ed36f14f6
90,773
def minmax_element(iterable, first=0, last=None, key=None): """ Find and return the minimum and maximum element in an iterable range. Parameters ---------- iterable: an iterable object with __get_item__ first: first element to check last: one past last element to check. None will check until end of iterable key: function to be called on each list element prior to making comparisons Returns ------- min_element, max_element: the resulting minmum and maximum elements """ assert hasattr(iterable, '__getitem__') iterable = iterable if first == 0 and last is None else iterable[first:last] if key is None: return min(iterable), max(iterable) else: return min(iterable, key=key), max(iterable, key=key)
a5176ac552ff720fdd304c12b64a1ec9a9b9a09b
638,555
def migrate(engine): """Replace 'backend' with 'store' in meta_data column of image_locations""" sql_query = ("UPDATE image_locations SET meta_data = REPLACE(meta_data, " "'\"backend\":', '\"store\":') where INSTR(meta_data, " " '\"backend\":') > 0") # NOTE(abhishekk): INSTR function doesn't supported in postgresql if engine.name == 'postgresql': sql_query = ("UPDATE image_locations SET meta_data = REPLACE(" "meta_data, '\"backend\":', '\"store\":') where " "POSITION('\"backend\":' IN meta_data) > 0") with engine.connect() as con: migrated_rows = con.execute(sql_query) return migrated_rows.rowcount
6d7fa2beed8cf38cb7debe556663950a820af1c2
654,084
def morph_word(word: str) -> str: """Apply simple morphing of the word to improve robustness for checking similarity. A derived token is created by concatenating the word and the sorted version of the word. Args: word: Word to be morphed. Returns: The morphed word. """ # word = word.replace(' ', '') # Check if compound word suggestion matches the misspelled word # Perform this opperation to add more robustness to the matching # m_word = word + "".join(sorted(word)) m_word = word return m_word
8b0502d643d71bf2e493d3b903c3f7280f727807
310,891
def _isRunMaskDuplicate(run, lumis, runLumis): """ Test whether run and lumi is a subset of one of the runLumi pairs in runLumis :param run: integer run number :param lumi: set of lumis :param runLumis: list of dictionaries containing run and lumis """ for runLumi in runLumis: if run == runLumi['run_number']: if lumis.issubset(runLumi['lumis']): return True return False
4b17001087175db9325efaa7f7420bc75a6f1e61
655,933
def extract(d, *args, default=None): """Return a tuple of results extracted from the dictionary using strings of paths to the values E.g. extract(d, 'a', 'b.c') is will return (d.get(a), d.get(b).get(c) """ assert isinstance(d, dict) results = [] for key in args: key = key.split('.') result = d for attr in key: if not isinstance(result, dict): result = default break result = result.get(attr) if result is None: result = default break results.append(result) return tuple(results)
7ce7bb4c28d96430388bff4a29e9875c6774716d
243,819
def append_cluster(cluster_a, cluster_b): """ Appends cluster_b to cluster_a :param cluster_a: array of shape [n_points, n_dimensions] :param cluster_b: array of shape [n_points, n_dimensions] """ for point in cluster_b: cluster_a.append(point) return cluster_a
cc5e6fc6d3162fdd8a0f87071039afc80ab582fc
290,868
def is_extrapackages_checked(active_packages, package_name): """ Checks if the given package_name is under the already activate packages """ if package_name in active_packages: return True else: return False
a705c041347f1147bf2e66945983f59a884a19bd
541,965
def parse_secret_from_authentication_url(url): """ This helper will parse the secret part of a totp url like otpauth://totp/alice%07c%40apothekia.de?secret=M3FAFWGD2QA5JJPCPWEOKALPBROHXOL3&algorithm=SHA1&digits=6&period=30 """ return url.split("secret")[1][1:33]
207ed2c0633af4b5eb0c29992dc6c4cb8cc5e40c
312,289
def fixIncorrectDateEncoding(Date): """ Fix date string to make it conform to ISO standard. """ if 'T00:00:00Z' in Date: return Date return Date + "T00:00:00Z"
57b0bed00c214794d3d1e25c313ce3e3cbe61526
648,767
def heart_color(color='red'): """Set the color of the hearts on the player's HUD. Keyword Arguments: color {str} -- The heart color. Options are 'red', 'blue', 'green', and 'yellow' (default: {'red'}) Returns: list -- a list of dictionaries indicating which ROM address offsets to write and what to write to them """ if color is None: color = 'red' cbyte = { 'blue': [44, 13], 'green': [60, 25], 'yellow': [40, 9], 'red': [36, 5], } byte = cbyte[color][0] file_byte = cbyte[color][1] patch = [ {'457246': [byte]}, {'457248': [byte]}, {'457250': [byte]}, {'457252': [byte]}, {'457254': [byte]}, {'457256': [byte]}, {'457258': [byte]}, {'457260': [byte]}, {'457262': [byte]}, {'457264': [byte]}, {'415073': [file_byte]}, ] return patch
1d5e8f9511ad49fe33e1d167f3e5b9ce5c2f3bfb
506,317
def normalize(array): """ This function normalizes a numpy array to sum up to 1 (L1 norm) """ return array/array.cumsum()[-1]
a3ec4e9f867b7548c1fefca3807fa846508a20bc
603,411
import hashlib def hash_sha3_512(password): """ Hashes a password using SHA3-512. Arguments: password <str>: The password to be hashed. """ return hashlib.sha3_512(password.encode('utf-8')).hexdigest()
6357d195e5420855e474f73a17acff55a9d43f78
273,843
import json from typing import OrderedDict def loads(f): """ Load a json stream into an OrderedDict """ return json.JSONDecoder(object_pairs_hook=OrderedDict).decode(f)
9b99189239fc9977375e6a5f650f70ec1ea7f020
359,278
def create_speed_command2(packer, speed3, lsmcdecel, actlbrknocs, actlbrknocnt, actlbrkqf): """Creates a CAN message for the Ford Speed Command.""" values = { "Veh_V_ActlBrk": speed3, "LsmcBrkDecel_D_Stat": lsmcdecel, "VehVActlBrk_No_Cs": actlbrknocs, "VehVActlBrk_No_Cnt": actlbrknocnt, "VehVActlBrk_D_Qf": actlbrkqf, } return packer.make_can_msg("BrakeSysFeatures", 2, values)
89695360160e03945177eeab451eb3f0dd262389
409,570
def show_price(price: float) -> str: """ >>> show_price(1000) '$ 1,000.00' >>> show_price(1_250.75) '$ 1,250.75' """ return "$ {0:,.2f}".format(price)
3c3c9a7532e1a84ddcf5b58d348dda778fdf5e59
681,211
def get_data_meta_path(either_file_path: str) -> tuple: """get either a meta o rr binary file path and return both as a tuple Arguments: either_file_path {str} -- path of a meta/binary file Returns: [type] -- (binary_path, meta_path) """ file_stripped = '.'.join(either_file_path.split('.')[:-1]) return tuple([file_stripped + ext for ext in ['.bin', '.meta']])
0456186cd99d5899e2433ac9e44ba0424077bcc0
707,218
import six def make_hashable(thing): """ Creates a representation of some input data with immutable collections, so the output is hashable. :param thing: The data to create a hashable representation of. """ if isinstance(thing, list): return tuple(make_hashable(elem) for elem in thing) elif isinstance(thing, set): return frozenset(make_hashable(elem) for elem in thing) elif isinstance(thing, dict): return frozenset((make_hashable(k), make_hashable(v)) for k, v in six.iteritems(thing)) else: return thing
42f60d3a0886f7cc8a339ffe0f0c8d5bd2da2873
121,416
from typing import Union def read_field(dictionary: dict, key: str) -> Union[str, None]: """ Read field value from dictionary. If there is no `key` in `dictionary` or value is equal to `N/A` return `None` :param dictionary: container to read from :param key: key to look up :return: value or None if value is not available """ empty_values = {'N/A', '', 'null', 'None'} value = dictionary.get(key, None) return value if value not in empty_values else None
a2a03c65d6cf9acb423e9fff20367ba9d6642873
613,175
import re def _replace_ampersands(html): """Replace ampersand symbols in html""" html = re.sub('&amp;', '&', html, flags=re.DOTALL) html = re.sub('&quot;', '"', html, flags=re.DOTALL) # html = re.sub('&amp;', ' ', html, flags=re.DOTALL) # html = re.sub('&quot;', ' ', html, flags=re.DOTALL) html = re.sub('&lt;', '\<', html) html = re.sub('&gt;', '\>', html) return html
355785a2971a56a9dc73174a019314077f1a12b9
550,781
from typing import Optional from typing import Any from warnings import warn def migrate_deprecated_argument( new_arg: Optional[Any], new_arg_name: str, old_arg: Optional[Any], old_arg_name: str ) -> Any: """ Facilitates the migration of an argument's name. This method handles the situation in which a function has two arguments for the same thing, one old and one new. It ensures that only one of the two arguments is provided, throwing a ValueError is both/neither are provided. If the old version of the argument is provided, it throws a deprecation warning. Parameters ---------- new_arg: Optional[Any] the value provided using the new argument (or None, if not provided) new_arg_name: str the new name of the argument (used for creating user-facing messages) old_arg: Optional[Any] the value provided using the old argument (or None, if not provided) old_arg_name: str the old name of the argument (used for creating user-facing messages) Returns ------- Any the value of the argument to be used by the calling method """ if old_arg is not None: warn(f"\'{old_arg_name}\' is deprecated in favor of \'{new_arg_name}\'", DeprecationWarning) if new_arg is None: return old_arg else: raise ValueError(f"Cannot specify both \'{new_arg_name}\' and \'{new_arg_name}\'") elif new_arg is None: raise ValueError(f"Please specify \'{new_arg_name}\'") return new_arg
5007ef28f027978743f1b83dc688592c5742989d
453,371
def partition(inp_list, n): """ Paritions a given list into chunks of size n Parameters ---------- inp_list: List to be splittted n: Number of equal partitions needed Returns ------- Splits inp_list into n equal chunks """ division = len(inp_list) / float(n) return [ inp_list[int(round(division * i)): int(round(division * (i + 1)))] for i in range(n) ]
d1f4c126c10be18e2c93519113beb76b39a3ac4d
204,419
def ppm_to_pa(ppm, pres): """ Convert ppm (umol mol^-1) to a partial pressure Args: ppm (float) : ppm of gas [umol mol^-1] pres (float) : atmospheric pressure [Pa] Returns: pa (float) : partial pressure of gas [Pa] """ pa = ppm * 1e-6 * pres return pa
3dff62717f30ba5c086a6dfb2c9c7fe9c1cde429
570,221
def extract_values(json_array, key): """ Obtain all values for a key in the JSON (dict) array """ return [item[key] for item in json_array]
18b62abcc25f60ef25a9ec9b312726c541f597a0
342,424
def hamming_distance(x, y): """Return the Hamming distance between `x` and `y`.""" assert len(x) == len(y) return sum(xi != yi for xi, yi in zip(x, y))
c48f4986adbc522f4cbc06743f3aed2034aea598
259,649
from typing import OrderedDict def get_any_value(x): """ Returns a value of a dict, list, or tuple. # Arguments x: object. The object to grab a value for. # Return value If `x` is a dictionary (including an OrderedDict), returns a value from it. If `x` is a list or tuple, returns an element from it. Otherwise, raises ValueError. """ if isinstance(x, (dict, OrderedDict)): for v in x.values(): return v if isinstance(x, (list, tuple)): return x[0] raise ValueError('Unexpected data type: {}'.format(type(x)))
ea9f4e35235d8b80722e365d03aef9c0309b907b
150,877
def to_bazelname(filename: str, mockname: str) -> str: """ maps divided mock class file name to bazel target name e.g. map "test/mocks/server/admin_stream.h" to "//test/mocks/server:admin_stream_mocks" Args: filename: string, mock class header file name (might be the whole path instead of the base name) mockname: string, mock directory name Returns: corresponding bazel target name """ bazelname = "//test/mocks/{}:".format(mockname) bazelname += filename.split('/')[-1].replace('.h', '') + '_mocks'.format(mockname) return bazelname
a6d0507deae0ebdf2c8f3bfe155364e24110617f
272,710
import re def htmldoc(text): """ Format docstring in html for a nice display in IPython. Parameters ---------- text : str The string to convert to html. Returns ------- out : str The html string. """ p = re.compile("^(?P<name>.*:)(.*)", re.MULTILINE) # To get the keywords html = p.sub(r"<b>\1</b>\2", text) html = html.replace("-", "") html = html.split("\n") while html[0].strip() == "": html = html[1:] # suppress initial blank lines for i in range(len(html)): html[i] = html[i].strip() if i == 0: html[i] = "<h3>%s</h3>" % html[i] html[i] = html[i].replace("Parameters", "<h4>Parameters</h4>") html[i] = html[i].replace("Properties", "<h4>Properties</h4>") html[i] = html[i].replace("Methods", "<h4>Methods</h4>") if html[i] != "": if "</h" not in html[i]: html[i] = html[i] + "<br/>" if not html[i].strip().startswith("<"): html[i] = "&nbsp;&nbsp;&nbsp;&nbsp;" + html[i] html = "".join(html) return html
f2385b2dbeaa294270aa9481f85d26eabd5f169a
507,939
import binascii def compute_crc(buf, crc_so_far=0): """ :param buf: bytes to compute CRC over. :param crc_so_far: value of CRC of bytes seen so far. To compute the CRC over multiple buffers, pass the previous buffer's CRC as *crc_so_far*. Use 0 (default) for the first time. :returns: CRC value. """ return binascii.crc32(buf, crc_so_far) & 0xFFffFFff
ab1a066cae8cd85e6d3a57419c46fcd587676507
538,516
def generate_fiscal_month(date): """ Generate fiscal period based on the date provided """ if date.month in [10, 11, 12, "10", "11", "12"]: return date.month - 9 return date.month + 3
6fe0e8945efa22f11835a618b9b234082b45b757
428,420
from typing import Union from typing import List def format_keywords(keywords: Union[str, List]) -> str: """ Format keywords fromm YAML file into the comma string list expected by boto3. Possible inputs are: a) A comma string list, e.g. 'foo, bar, baz, qux' b) A list of strings, e.g. ['foo', 'bar', 'baz', 'qux'] """ if isinstance(keywords, str): return keywords elif isinstance(keywords, list): return ','.join(keywords)
336600193a94a3d3431583e71f18b245d26c4241
340,509
def rect_sum(rect: list[list[int]], x1: int, y1: int, x2: int, y2: int) -> int: """Calculates sum of pixels of a rectangle within given borders Args: rect (list[list[int]]): matrix of integers x1 (int): top left border X coordinate y1 (int): top left border Y coordinate x2 (int): bottom right X coordinate y2 (int): bottom right Y coordinate Returns: int: sum of pixels """ # Checking "image" if not isinstance(rect, list): raise ValueError("\"image\"'s must be a list") else: for index, item in enumerate(rect): if not isinstance(item, list): raise ValueError("items of \"image\" must be lists") for num in item: if not isinstance(num, int): raise ValueError( "items of items of \"image\" must be integers") if index == len(rect) - 1: pass else: if len(rect[index]) != len(rect[index + 1]): raise ValueError( "items of \"image\" must be of the same length") # Checking coordinates top_left_border = (x1, y1) bottom_right_border = (x2, y2) for coordinate in top_left_border: if not isinstance(coordinate, int) or coordinate < 0: raise ValueError( "border coordinate(s) must be positive integer(s)") for coordinate in bottom_right_border: if not isinstance(coordinate, int) or coordinate < 0: raise ValueError( "border coordinate(s) must be positive integer(s)") if x1 > len(rect[0]) - 1 or x2 > len(rect[0]) - 1: raise ValueError( "x1 and/or x2 must not be greater than the number of the matrix columns") if y1 > len(rect) - 1 or y2 > len(rect) - 1: raise ValueError( "y1 and/or y2 must not be greater than the number of the matrix rows") if x1 > x2 or y1 > y2: raise ValueError( "top-left border coordinates must not be greater than bottom-right border coordinates") # Calculatins sum c = sum(rect[y][x] for y in range(y2 + 1) for x in range(x2 + 1)) a = sum(rect[y][x] for y in range(y1) for x in range(x1)) b = sum(rect[y][x] for y in range(y1) for x in range(x2 + 1)) d = sum(rect[y][x] for y in range(y2 + 1) for x in range(x1)) s = a + c - b - d return s
0ee770a2ce72c44b137416ea7dbec140dfb1bd2b
572,113
def get_supporting_points(exponent_bits, linear_bits): """ Get supporting points that have a coarse exponential segments and fine linear segments in the range of 0 to 0.5. The number of segments are given as bits. This kind of support structure is optimal for icdf and hardware implementations. """ points = [0.5] for exp in range(2**exponent_bits): for lin in range(2**linear_bits): pos = (1 + lin * 2 ** (-linear_bits)) * 2 ** (-exp - 2) points.append(pos) return sorted(points)
b02976a08cada8627e3ca481737a7812b464bf71
523,974
def version_no_valid(version: str) -> bool: """ Determine if string version is valid for getting specific PyPi package version :param version: version string :return: True if valid, False otherwise """ try: x = [int(v) for v in version.split('.')] return 2 <= len(x) <=3 except Exception: return False
6fa23fe8c3b65e164094218462d7c02206408074
179,538
from pathlib import Path from typing import Tuple from typing import List from typing import Dict def get_category(label_def_file: Path) -> Tuple[List[Dict], Dict]: """ Returns the list of categories, and a lookup table that for each category/sub_category/value in {label_def_file}, contains that assigned label id. """ with label_def_file.open() as f: content = [x.strip() for x in f.readlines()] categories = [] lookup_table = {} for idx, line_i in enumerate(content): category = {"supercategory": "ssigns", "id": idx + 1, "name": line_i.replace("/", "_")} categories.append(category) for word_i in line_i.split("|"): if word_i: lookup_table.update({word_i.strip(): category["id"]}) return categories, lookup_table
4be53c663726c66c0fe54a7d944641128aee2b48
485,750
def coerce_result(result): """ Coerces return value to a tuple if it returned only a single value. """ if isinstance(result, tuple): return result else: return (result,)
4b750d563edd712fd1c4d0f260fa795b1f404e1e
473,090
def strip_surrounding_spaces(string): """Strip leading and trailing space | str --> str""" if string == '': return string if string[0] == ' ': string = string[1:] if string[-1] == ' ': string = string[:-1] return string
4ea16c545df9c1233425bfafcdfee16e08968229
278,288
def ReplaceParams(text, replace_params): """Replace keys with values in the given text.""" for (key, value) in replace_params.iteritems(): text = text.replace(key, value) return text
4daa374ed6ff084e168f6511dd7d192e2a337002
207,112
import tarfile from pathlib import Path def _list_files(path): """Return files in a .tar.gz file, ignoring hidden files """ with tarfile.open(path) as tar: return set(f for f in tar.getnames() if not Path(f).name.startswith('.'))
c338f5d2a5923e52aed8d0aa8ca2b290299bb39f
465,362
def _next_power_of_2(x): """ Calculate the closest power of 2, greater than the given x. :param x: positive integer :return: int - the closest power of 2, greater than the given x. """ return 1 if x == 0 else 2**(x - 1).bit_length()
616c01f6aacb7442ce1b2afbcac35b26c8f79701
12,191
def is_at_end(word1, word2): """checks if word1 is at the end of word2""" return word1 != word2 and word1 == word2[-len(word1):]
5c894542272aeb4ac08bff13dd562d228a6e638a
386,603
def _bit_str_pad(base_str: str, req_len: int, pad_type: str='0') -> str: """ Pads the left side of a string with pad_type Args: base_str: The string to add padding to req_len: The total required length of the string pad_type: What to pad the string with Returns: A left padded string based on the required length """ for x in range(len(base_str), req_len): base_str = pad_type + base_str return base_str
8e6361ddc8249d213768ca2938ed281196088a52
390,397
def srnirnarrowre1(b5, b8a): """ Simple NIR and Red-edge 1 Ratio (Datt, 1999b). .. math:: SRNIRnarrowRE1 = b8a/b5 :param b5: Red-edge 1. :type b5: numpy.ndarray or float :param b8a: NIR narrow. :type b8a: numpy.ndarray or float :returns SRNIRnarrowRE1: Index value .. Tip:: Datt, B. 1999b. Visible/near infrared reflectance and chlorophyll \ content in Eucalyptus leaves. International Journal of Remote Sensing \ 20, 2741-2759. doi:10.1080/014311699211778. """ SRNIRnarrowRE1 = b8a/b5 return SRNIRnarrowRE1
d1b8517df55f66f28bcb3afc997f7ada9c98d027
401,644
import torch def embeddings_to_cosine_similarity_matrix(z): """Converts a a tensor of n embeddings to an (n, n) tensor of similarities. """ cosine_similarity = torch.matmul(z, z.t()) embedding_norms = torch.norm(z, p=2, dim=1) embedding_norms_mat = embedding_norms.unsqueeze(0)*embedding_norms.unsqueeze(1) cosine_similarity = cosine_similarity / (embedding_norms_mat) return cosine_similarity
f68dcdcceb4eea59d4525650111f3b2720ea878f
103,732
def normalize_index(index, length): """ Normalizes an index per sequence indexing. >>> normalize_index(0, 10) 0 >>> normalize_index(9, 10) 9 >>> normalize_index(-2, 10) 8 """ index = int(index) if 0 <= index < length: return index elif -length <= index < 0: return index + length else: raise IndexError("index out of range: {}".format(index))
bc9be3a3ef554ca95217f93d2d698934c2f1096f
31,570
def guess_type(filename): """ Guess the particle type from the filename Parameters ---------- filename: str Returns ------- str: 'gamma', 'proton', 'electron' or 'unknown' """ particles = ['gamma', 'proton', 'electron'] for p in particles: if p in filename: return p return 'unknown'
1dac0dcca3444244d3a4072a87963822f88724de
372,080
def balance_into_sublists(test_counts, total_shards): """Augment the result of otool into balanced sublists Args: test_counts: (collections.Counter) dict of test_case to test case numbers total_shards: (int) total number of shards this was divided into Returns: list of list of test classes """ class Shard(object): """Stores list of test classes and number of all tests""" def __init__(self): self.test_classes = [] self.size = 0 shards = [Shard() for i in range(total_shards)] # Balances test classes between shards to have # approximately equal number of tests per shard. for test_class, number_of_test_methods in test_counts.most_common(): min_shard = min(shards, key=lambda shard: shard.size) min_shard.test_classes.append(test_class) min_shard.size += number_of_test_methods sublists = [shard.test_classes for shard in shards] return sublists
070efe511682f07b9486279794c63b1d1457bb70
273,791
def get_values(df, rows, column): """Get the desired column value from a list of dataframe iloc indexes.""" return [df.iloc[row][column] for row in rows]
2013275ba248ddcd6170f3bb71a31a468585b739
592,723
def get_expected_validation_developer_message(preference_key, preference_value): """ Returns the expected dict of validation messages for the specified key. """ return "Value '{preference_value}' not valid for preference '{preference_key}': {error}".format( preference_key=preference_key, preference_value=preference_value, error={ "key": ["Ensure this field has no more than 255 characters."] } )
bbfbc9d3c81aa80572096f2ded75d5dafb2c8fc3
160,925
def square_area(side): """Returns the area of a square""" return side*side
6308af2538493b8a24cd456522dbf55ce82b05ca
171,931
def maxstep_terminal_condition(env, max_step=500): """A terminal condition based on the time step. Args: env: An instance of MinitaurGymEnv max_step: The maximum time step allowed for the environment Returns: A boolean indicating if the env.step exceeds the given limit """ return env.env_step_counter > max_step
d3f56346e51984a37cde67225f36497e4da6ca6a
543,121
def certificate_size(rf, mode): """returns the certificate dimension w.r.t. a given mode and RF :param rf: the RF :type rf: model.ReachabilityForm :param mode: either 'min' or 'max' :type mode: str :return: certificate dimension :rtype: int """ assert mode in ["min", "max"] C, N = rf.system.P.shape if mode == "min": return N-2 else: return C-2
5499c0fcebaf7fb829623bc4525dce3a6cd3c1f2
294,281
def read_file_precision(file,precision): """ Read in the file converting floats to the given precision """ file_data=[] with open(file) as file_handle: for line in file_handle: formatted_data=[] for data in line.rstrip().split("\t"): try: data_float=float(data) data="{:.{digits}f}".format(data_float, digits=precision) except ValueError: pass formatted_data.append(data) file_data.append("\t".join(formatted_data)) return file_data
8d1901b7651f0eae04424121a885c48519f05e8d
203,465
def parse_curl_error(proc_stderr): """Report curl failure. Args: proc_stderr (str): Stderr returned from curl command. Returns: str: Reason for curl failure. """ curl_err = "" if isinstance(proc_stderr, bytes): proc_stderr = proc_stderr.decode("utf-8") try: curl_err = proc_stderr.rstrip("\n") curl_err = curl_err.split(None, 2)[2] except IndexError: pass return curl_err
ed7fba8424b00e98a96b898160207047390c3baf
92,421
from pathlib import Path import json def return_event(file_name): """Return a Lambda event object.""" with Path(__file__).parent.joinpath(file_name).open() as json_file: test_event = json.load(json_file) return test_event
ca06628be9f42b2476b0633b9dc36b1ebae43018
550,310
def bangbang_compressor(bangbang_protocol ): """Compresses the bang bang protocol. Merges chunks of contiguous bangbang chunks into a Tuple of duration (in number of chunks) and which Hamiltonian to apply. Args: bangbang_protocol: List of HamiltonianType values, determines which Hamiltonian should be applied at the corresponding chunk. Returns: List of Tuples containing the Hamiltonian type and the number of chunks to apply the Hamiltonian type for. """ current_mode = None compressed_protocol = [] chunk_counter = 0 for protocol_mode in bangbang_protocol: if current_mode is None: current_mode = protocol_mode chunk_counter = 1 elif current_mode == protocol_mode: chunk_counter += 1 else: compressed_protocol.append((chunk_counter, current_mode)) current_mode = protocol_mode chunk_counter = 1 # Append what's left over if chunk_counter > 0: compressed_protocol.append((chunk_counter, current_mode)) return compressed_protocol
7e3b6e0e5678e705c54c39e31561a908900d9b08
697,976
def good_suffix_match(small_l_prime): """ Given a full match of P to T, return amount to shift as determined by good suffix rule. """ return len(small_l_prime) - small_l_prime[1]
5812985a95c439512f8422e2858d94bb3ece2b20
195,669
def strip_specific_magics(source, magic): """ Given the source of a cell, filter out specific cell and line magics. """ filtered=[] for line in source.splitlines(): if line.startswith(f'%{magic}'): filtered.append(line.lstrip(f'%{magic}').strip(' ')) if line.startswith(f'%%{magic}'): filtered.append(line.lstrip(f'%%{magic}').strip(' ')) else: filtered.append(line) return '\n'.join(filtered)
3c2722b86b6fc8e40c8dd51edd06d7edb28e2945
20,452
def bprop_scalar_uadd(x, out, dout): """Backpropagator for `scalar_uadd`.""" return (dout,)
c6258cf655b4a22737b6addd861d4320aaf4901f
593,795
def Pdiff(rho, Pset, T, xi, eos): """ Calculate difference between set point pressure and computed pressure for a given density. Parameters ---------- rho : float Density of system [mol/:math:`m^3`] Pset : float Guess in pressure of the system [Pa] T : float Temperature of the system [K] xi : numpy.ndarray Mole fraction of each component, sum(xi) should equal 1.0 eos : obj An instance of the defined EOS class to be used in thermodynamic computations. Returns ------- Pdiff : float Difference in set pressure and predicted pressure given system conditions. """ #logger = logging.getLogger(__name__) Pguess = eos.P(rho, T, xi) return (Pguess - Pset)
971625d109c3e2d984c656e6a4ef8230f5ab2ddb
344,948
def _HasOneSimplePort(ports): """Check if this list of ports only contains a single simple port. Args: ports: JSON-serializable representation of address ports. Returns: True if ports is length 1 and the only attribute is just a port number with no protocol. """ if len(ports) == 1: protocol = ports[0].get('protocol', None) port_name = ports[0].get('name', None) return (not protocol) and (not port_name) else: return False
e3ebf274c368455383ba1900b554c9bfdbe83ebc
288,975
def capitalized(s: str) -> str: """Returned the string, where first letter is capitalized. Id est: >>> capitalized("Two Words") -> "Two Words" >>> capitalized("another examplE") -> "Another examplE" And so on. Str is empty => return it. """ if not s: return s c, *s_ = s return c.capitalize() + ''.join(s_)
ce05bc057df83898c8956fb74e5b6cb1bded2efd
542,064
def denormalize(img, mean, std): """ Denormalize the image with mean and standard deviation. This inverts the normalization. Parameters ---------- img : array(float) The image to denormalize. mean : float The mean which was used for normalization. std : float The standard deviation which was used for normalization. """ return (img * std) + mean
b2fd8315ef4d282409f648ceb3e6a35652bea6e4
622,201
from typing import Iterable def ensure_iterable(value): """ensure that the results of a command are always iterable""" if isinstance(value, Iterable): return value return tuple((value,))
32ce448b9cc6003abf93f3448c948d32790d14ad
591,060
from typing import Any def is_byte_data(data: Any): """ Checks if the given data is of type byte :param data: The data to check :return: Whether the data is of type bytes or not """ return type(data) is bytes
3b04758f812220b97f21c15cacc4773c92b5bb30
44,312
def format_guesses(past_guesses): """Returns a string of the past_guesses. For example, format_guesses(['x', 'y', 'z']) should return the str 'x y z' Args: past_guesses: a list of strings Returns: A string: of past_guesses """ return " ".join(past_guesses)
5d86dcfc1b68239a908a7d2be4edc27ecb2029b5
252,454
from datetime import datetime def timestamp_to_date(timestamp: float) -> datetime: """convert different timestamp precision to python format Python2.7: https://docs.python.org/2.7/library/datetime.html#datetime.datetime Python3+ :https://docs.python.org/3.7/library/datetime.html#datetime.datetime for datetime.fromtimestamp. It’s common for this to be restricted to years from 1970 through 2038. 2145888000 is 2038-01-01 00:00:00 UTC for second 2145888000 is 1970-01-26 04:04:48 UTC for millisecond Args: timestamp (float): from different source, so, has different timestamp precision """ if timestamp > 2145888000: timestamp = timestamp / 1000 return datetime.fromtimestamp(timestamp)
64d3fe3da8041c6e48199cebc1b847d5294e62f9
571,614
def fixture_cram_path(fixtures_dir): """Return the path to a cram file""" _file_path = fixtures_dir / "bam" / "test.cram" return _file_path
9d2636c5a9a0698332a362fcfa83875e2ea492fc
227,127
def simple_lang(pressure, n_total, k_const): """A simple Langmuir equation returning loading at a pressure.""" return (n_total * k_const * pressure / (1 + k_const * pressure))
46d4143c2dd1267c4f8199d6bbfc73b427a5b62b
294,612
import tempfile def new_temp_handle(**kwargs): """A new temporary handle ready to be written to.""" handle = tempfile.NamedTemporaryFile(delete=False, **kwargs) return handle
1fca94026f15e41d30ef9fac5b09b1fa533f78f4
513,099
from datetime import datetime def parse_time(time): """convert time string to datatime object :param str time: time representation :return: datetime.datetime :rtype: int """ ''' "Fri Aug 29 12:23:59 +0000 2014" ''' return datetime.strptime(time, '%a %b %d %X %z %Y')
27cc16659a40eaf8ef6abc11bef634669668de99
552,197
def Imu_I0c1c2c3c4(mu, c): """ I(mu, c) where c = (I0, c1, c2, c3, c4) """ return c[0]*(1-c[1]*(1-mu**0.5)-c[2]*(1-mu)-c[3]*(1-mu**1.5)-c[4]*(1-mu**2.))
6553deaff09f4a3e00364b271095b5e80472b3a1
12,789
def dec2bin(ndec): """ Convert a decimal number into a string representing the same value in binary format. """ if ndec < 1: return "0" binary = [] while ndec != 0: binary.append(ndec%2) ndec = ndec/2 strbin = "" binary.reverse() for i in binary: strbin = strbin+str(i) return strbin
83251f38dd1c42d28829802ee9e3e5838cef94dc
357,210
import re def _make_url_friendly(title): """Given a title that will be used as flavor text in a URL, returns a string that will look less like garbage in an address bar. """ # RFC 3986 section 2.3 says: letters, numbers, and -_.~ are unreserved return re.sub('[^-_.~a-zA-Z0-9]', '-', title)
d95b158b9d46227935e7035ad54af767d4268a84
178,145
def lookup_name(frame, name): """Get the value of the named variable, as seen by the given frame. The name is first looked for in f_locals, then f_globals, and finally f_builtins. If it's not defined in any of these scopes, NameError is raised. """ try: return frame.f_locals[name] except KeyError: try: return frame.f_globals[name] except KeyError: try: return frame.f_builtins[name] except KeyError: raise NameError(name)
1dab10055941c27e2744ee16738f9746039339a2
254,516
def _get_last_doc_ref(path, doc): """Mutate a document top-down using a path. :param pathlib.Path path: The path. :param dict doc: The document. :rtype: dict """ for part in path.parts: if part not in doc: doc[part] = {} doc = doc[part] return doc
316c2579897e1ce5834a2bf34fc7c5929c7868c9
39,501
def remove_trailing_prefs(proposal_record, preferences): """ Function trims each preference list by eliminating possibilities indexed after accepted proposal Takes in two dictionaries: proposal_record and preference_lists Returns updated preference_lists For example: Inputs of proposal_record = { 'A': ['C', 'B'], - proposed to C and accepted proposal from B 'B': ['A', 'D'], - proposed to A and accepted proposal from D 'C': ['D', 'A'], - proposed to D and accepted proposal from A 'D': ['B', 'C'], - proposed to B and accepted proposal from C } preferences = { 'A': ['C', 'B', 'D'], - remove all prefs that rank lower than B 'B': ['A', 'C', 'D'], 'C': ['D', 'B', 'A'], 'D': ['B', 'A', 'C'], - remove 'A' since 'D' is removed from A's list } Outputs => preferences = { 'A': ['C', 'B'], 'B': ['A', 'C', 'D'], 'C': ['D', 'B', 'A'], 'D': ['B', 'C'], } """ for proposer in proposal_record: proposee = proposal_record[proposer][0] proposee_prefs = preferences[proposee] proposer_ranking = proposee_prefs.index(proposer) successors = proposee_prefs[proposer_ranking+1:] # Updated proposee's preferences, removing successors preferences[proposee] = proposee_prefs[:proposer_ranking+1] # Iterate over successors, deleting proposee from own preference list for successor in successors: if proposee in preferences[successor]: preferences[successor].remove(proposee) return preferences
67dfd38a370691d786624991f9d98915b189a957
387,027
def page_element_conf0(element): """Get confidence (as float value) of the first text result.""" if element.get_TextEquiv(): # generateDS does not convert simpleType for attributes (yet?) return float(element.get_TextEquiv()[0].conf or "1.0") return 1.0
312a7974e02ca06b36e7553c46cc8cec29ae5362
487,809
import re def parse_losses_from_log_file(file_name: str): """ Read a log file produced by VISSL and extract the losses produced at each iteration """ iterations = [] losses = [] regex = re.compile(r"iter: (.*?); lr: (?:.*?); loss: (.*?);") with open(file_name, "r") as file: for line in file: if not line.startswith("INFO"): continue match = regex.search(line) if match is not None: iteration = int(match.group(1)) loss = float(match.group(2)) iterations.append(iteration) losses.append(loss) return iterations, losses
1eedcc7f4439100609a85aceb8bf72a7615b6090
570,869
from typing import Dict from typing import List def nest_fields(data: Dict, nest: str, eggs: List[str]): """Make sure specified fields are nested under "nest" key.""" for egg_field in eggs: if egg_field in data: if not data.get(nest): data[nest] = {} data[nest][egg_field] = data.pop(egg_field) return data
986c66c5ce55e6086f07a77c990a18459b44bbfa
320,596
import pickle def load_pickle(byte_file): """Loads a pickled object""" with open(byte_file, "rb") as f: return pickle.load(f)
932f376bcd3a79398c600056fd327d5b54951e43
677,683
def best_ss_to_expand_greedy(new_set, supersets, ruleWeights, max_mask): """ Returns index of the best superset to expand, given the rule weights and the maximum allowed mask size. -1 if none possible. """ bestSuperset = None bestCost = float('inf') new_set = set(new_set) for superset in supersets: # if this merge would exceed the current mask size limit, skip it if len(new_set.union(superset)) > max_mask: continue # the rule increase is the sum of all rules that involve each part added to the superset cost = sum(ruleWeights[part] for part in new_set.difference(superset)) if cost < bestCost: bestCost = cost bestSuperset = superset # if no merge is possible, return -1 if bestSuperset == None: return -1 return supersets.index(bestSuperset)
e03a5d9d752f24b7b5188ae9babae277642bacf2
186,572
def get_percent_alloc(values): """ Determines a portfolio's allocations. Parameters ---------- values : pd.DataFrame Contains position values or amounts. Returns ------- allocations : pd.DataFrame Positions and their allocations. """ return values.divide( values.sum(axis='columns'), axis='rows' )
7f4ec48b2adbdb812292930e7fda50038b6d5e96
8,906
def get_template_source(jinja2_env, template): """Returns the source text of the given `template`.""" template_source, _, _ = jinja2_env.loader.get_source(jinja2_env, template) return template_source
26c4ee57f5734059d7099fa9b4420fdbfcabbc9b
252,811
import math def is_polygonal_number(m, n): """ Checks whether a given number m is a polygonal number for some n, i.e. whether it is an n-gonal number for some n > 2. If so, it returns the index of the number in the sequence, otherwise it returns null. """ if m == 1: return True k = (((n - 4) + math.sqrt((n - 4) ** 2 + 8 * m * (n - 2))) / (2 * (n - 2))) return int(k) if k.is_integer() else False
5e14b7bb99c3e532ac7af1ffbf03f8a6103d37a6
274,812
def get(amt): """ Creates a quadratic easing interpolator. The amount of easing (curvature of the function) is controlled by ``amt``. -1 gives a *in* type interpolator, 1 gives a *out* type interpolator, 0 just returns the :func:`linear` interpolator. Other values returns something in between. :param float amt: The amount of easing for the function. A float in the range *[-1, 1]*. :return: An interpolating function. """ if amt < -1: amt = -1 elif amt > 1: amt = 1 return lambda t: t * (1 + (1 - t) * amt)
c151990f3d5cfd8adf06549ff61fcc1671f510bf
115,246
import json def get_class_names(path, parent_path=None, subset_path=None): """ Read json file with entries {classname: index} and return an array of class names in order. If parent_path is provided, load and map all children to their ids. Args: path (str): path to class ids json file. File must be in the format {"class1": id1, "class2": id2, ...} parent_path (Optional[str]): path to parent-child json file. File must be in the format {"parent1": ["child1", "child2", ...], ...} subset_path (Optional[str]): path to text file containing a subset of class names, separated by newline characters. Returns: class_names (list of strs): list of class names. class_parents (dict): a dictionary where key is the name of the parent class and value is a list of ids of the children classes. subset_ids (list of ints): list of ids of the classes provided in the subset file. """ try: with open(path, "r") as f: class2idx = json.load(f) except Exception as err: print("Fail to load file from {} with error {}".format(path, err)) return max_key = max(class2idx.values()) class_names = [None] * (max_key + 1) for k, i in class2idx.items(): class_names[i] = k class_parent = None if parent_path is not None and parent_path != "": try: with open(parent_path, "r") as f: d_parent = json.load(f) except EnvironmentError as err: print( "Fail to load file from {} with error {}".format( parent_path, err ) ) return class_parent = {} for parent, children in d_parent.items(): indices = [ class2idx[c] for c in children if class2idx.get(c) is not None ] class_parent[parent] = indices subset_ids = None if subset_path is not None and subset_path != "": try: with open(subset_path, "r") as f: subset = f.read().split("\n") subset_ids = [ class2idx[name] for name in subset if class2idx.get(name) is not None ] except EnvironmentError as err: print( "Fail to load file from {} with error {}".format( subset_path, err ) ) return return class_names, class_parent, subset_ids
65b461a9fa3d573e18ab48d858b6d558050f0a96
148,653
def get_intermittent_node_injections(generators, nodes, dispatch): """Intermittent generator node injections Parameters ---------- generators : pandas DataFrame Generator information nodes : pandas DataFrame Node information dispatch : pandas DataFrame Dispatch at each node Returns ------- intermittent : pandas DataFrame Intermittent generation at each node """ # Intermittent generators mask_intermittent = generators['FUEL_CAT'].isin(['Wind', 'Solar']) generators[mask_intermittent] # Intermittent dispatch at each node intermittent = (dispatch .T .join(generators.loc[mask_intermittent, 'NODE'], how='left') .groupby('NODE').sum() .reindex(nodes.index, fill_value=0)) intermittent['level'] = 'intermittent' return intermittent
7de11b6d5aecfc3f5dd9ced3f08b30cdf652f16e
550,970
import re def filter_url(text): """ Remove URLs from a given string :param text: string of text :return: string of text without URLs """ return re.sub(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", '', text)
3b12ca8ecb2d1072e2e91776b01583e3833f2037
602,579
def _StrConvert(value): """Converts value to str if it is not.""" # This file is imported by c extension and some methods like ClearField # requires string for the field name. py2/py3 has different text # type and may use unicode. if not isinstance(value, str): return value.encode('utf-8') return value
1bba85cd0f6d93abf5a08e1b4b735b8c12578ad1
330,821
def img2windows(img, h_split, w_split): """Convert input tensor into split stripes Args: img: tensor, image tensor with shape [B, C, H, W] h_split: int, splits width in height direction w_split: int, splits width in width direction Returns: out: tensor, splitted image """ B, C, H, W = img.shape out = img.reshape([B, C, H // h_split, h_split, W // w_split, w_split]) out = out.transpose([0, 2, 4, 3, 5, 1]) # [B, H//h_split, W//w_split, h_split, w_split, C] out = out.reshape([-1, h_split * w_split, C]) # [B, H//h_split, W//w_split, h_split*w_split, C] return out
1580c818bf4ba2d0a13d0c039f4d4028dc113061
643,273
from sympy.printing.fortran import FCodePrinter def fcode(expr, assign_to=None, **settings): """Converts an expr to a string of fortran code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. precision : integer, optional DEPRECATED. Use type_mappings instead. The precision for numbers such as pi [default=17]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. source_format : optional The source format can be either 'fixed' or 'free'. [default='fixed'] standard : integer, optional The Fortran standard to be followed. This is specified as an integer. Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77. Note that currently the only distinction internally is between standards before 95, and those 95 and after. This may change later as more features are added. name_mangling : bool, optional If True, then the variables that would become identical in case-insensitive Fortran are mangled by appending different number of ``_`` at the end. If False, SymPy Will not interfere with naming of variables. [default=True] Examples ======== >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor >>> x, tau = symbols("x, tau") >>> fcode((2*tau)**Rational(7, 2)) ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)' >>> fcode(sin(x), assign_to="s") ' s = sin(x)' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "floor": [(lambda x: not x.is_integer, "FLOOR1"), ... (lambda x: x.is_integer, "FLOOR2")] ... } >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions) ' CEIL(x) + FLOOR1(x)' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(fcode(expr, tau)) if (x > 0) then tau = x + 1 else tau = x end if Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> fcode(e.rhs, assign_to=e.lhs, contract=False) ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))' Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions must be provided to ``assign_to``. Note that any expression that can be generated normally can also exist inside a Matrix: >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(fcode(mat, A)) A(1, 1) = x**2 if (x > 0) then A(2, 1) = x + 1 else A(2, 1) = x end if A(3, 1) = sin(x) """ return FCodePrinter(settings).doprint(expr, assign_to)
8f504707ecc5c7a4951529fa2c45f118be6814db
101,271
def convert_to_crlf(string): """Unconditionally convert LF to CRLF.""" return string.replace('\n', '\r\n')
5715bfa5849cafdb9ad80eb63ab7f5bf6a0cd75a
406,579