content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def load_bikeshare(data_path=FIXTURES): """ Downloads the 'bikeshare' dataset, saving it to the output path specified and returns the data. """ # name of the dataset name = 'bikeshare' data = load_numpy(name, data_path=data_path) return data
5c2799eb19718c670687e8a0b4669463f71bca66
40,800
def svn_wc_add_lock(*args): """svn_wc_add_lock(char const * path, svn_lock_t lock, svn_wc_adm_access_t * adm_access, apr_pool_t pool) -> svn_error_t""" return _wc.svn_wc_add_lock(*args)
3b5ad14ac99aad49b19050e3707078b38b781f88
40,801
def contains_non_ascii_unicode(s): """Determine whether the Unicode string 's' contains non-ASCII code-points.""" # Surely there must be a better way to do this? There's nothing I can see in # the stdlib 'unicodedata' module: # http://docs.python.org/library/unicodedata.html # # Note that list comprehens...
138d3c298598603f2d0dc24518bbea46a4f8b7e6
40,802
def build_profile_information(user): """ Returns a dictionary containing information relevant to an user's profile. Override this function to add additional information to an user's profile. """ context = {} context['user'] = user up_votes = Vote.objects.filter(user = use...
2bc58d6bdcadff44328d50c7edf6ad33ac33e7c0
40,803
def __remove_duplicate_chars(string_input, string_replace): """ Remove duplicate chars from a string. """ while (string_replace * 2) in string_input: string_input = \ string_input.replace((string_replace * 2), string_replace) return string_input
6302bf225fcd5cde822e0640eb7b2c44dcc93fc8
40,804
import os import re def generate_message(username, pr_list): """Generates message using the template provided in PENDING_REVIEW_NOTIFICATION_TEMPLATE.md file. """ template_path = '.github/PENDING_REVIEW_NOTIFICATION_TEMPLATE.md' if not os.path.exists(template_path): raise Exception( ...
df5538f5d0e47415019977a234f85bedb14bc2c9
40,805
def clean_data(df): """Split the categories column to 36 individual columns and convert their values to 0 / 1. Drop the original categories column. Drop duplicated rows. Args: df: the dataset Returns: DataFrame: the cleaned dataset """ # split categories into separate c...
eeeed21b10419f2c3402abecc0710556db979c6c
40,806
def format_birthday_for_database(p_birthday_of_contact_month, p_birthday_of_contact_day, p_birthday_of_contact_year): """Takes an input of contact's birthday month, day, and year and creates a string to insert into the contacts database.""" formated_birthday_string = p_birthday_of_contact_month + "/" + p_birthd...
1b4eff67a4073505f9f693f63db6f7c32646bd53
40,807
from datetime import datetime import uuid def pow_json_serializer(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): #serial = obj.isoformat() serial = obj.strftime(twittercomments.config.myapp["date_format"]) return serial ...
f400b6297b8fb8047c367839fe7be878ab9c9c20
40,808
def scale_poscar(path_poscar,scale=(1,1,1),tol=1e-2): """Create larger/smaller cell from a given POSCAR. - **Parameters** - path_poscar: Path/to/POSCAR or `poscar` data object. - scale: Tuple of three values along (a,b,c) vectors. int or float values. If number of sites are not as expected in ou...
45edf5f79acdd25cc8da8037c461008796a294af
40,809
import math def normal_distribution(x: float) -> float: """ 標準正規分布 f(x) = (1/sqrt(2pi))exp(-x^2/2) """ # 係数 coefficient = 1 / math.sqrt(2 * math.pi) # 指数 exponent = math.exp(-(x ** 2) / 2) # 標準正規分布 return coefficient * exponent
2ee740674ddf2a7b95d507aedf1f5453a75f31f1
40,810
from datetime import datetime def jd_from_datetime_utc(datetime_utc=None): """ Converts a UTC datetime to Julian date. Imported from photrix (E. Dose). :param datetime_utc: date and time (in UTC) to convert [python datetime object] :return: Julian date corresponding to date and time [float]. """ ...
b97a9a6efc4f0783b9c06ca622987d9ccb1ef023
40,811
def reanalyze_callers(*args): """reanalyze_callers(ea_t ea, bool noret)""" return _idaapi.reanalyze_callers(*args)
2a20f6c3cbd5298867bd7c1ef6546659e89d0933
40,812
def parallel(*layers): """Combinator for composing layers in parallel. The layer resulting from this combinator is often used with the `FanOut` and `FanInSum`/`FanInConcat` layers. Based on `jax.experimental.stax.parallel`. Args: :layers: a sequence of layers, each an `(init_fn, apply_fn, kernel_fn)` ...
77cd0f635433c35d0e5fa94ec9e156b7266ef9fe
40,813
def get_datastore_identifier(datastore): """Revieve the NAA identifiers for the requested datastore object. Args: ds(vim.Datastore): Datastore object that the NAA is needed for. Returns: naa_ids(set): Returns a set of NAA(s) associated with the datastore. """ # The variable 'device...
f1386a789376da4cfab8a75cc769f2b45aece0f9
40,814
import os import importlib def _dataset_factory(pth, task: str) -> object: """データセット名に合わせて作成されたディレクトリ内のファイルを読みだす関数 Args: data_source (str): DataCatalog に保存されているデータセット名と同じ文字列 task (str): 実行するタスク名.例: 'classify' Returns: object: 引数で指定した python ソースファイル内に記述されている関数 """ pth = os...
42c8ec3fd3bd75a1b6a75a7f47f01db804136729
40,815
def get_coeff_eq3(hybrid_category): """係数d,e,f Args: hybrid_category(str): 電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機の区分 Returns: tuple: 式(3)における係数 d,e,f """ if hybrid_category == '区分1': return get_table_g_3()[0][0], get_table_g_3()[1][0], get_table_g_3()[2][0] elif hybrid_category == '区分2'...
0cbfd8e8861f8dc0bde1e78b078631c8837811d9
40,816
def bw2sdtrf(bwvol): """ computes the signed distance transform from the surface between the binary True/False elements of logical bwvol Note: the distance transform on either side of the surface will be +1/-1 - i.e. there are no voxels for which the dst should be 0. Runtime: currently the funct...
485cd4852d362073211e05c47cdbec209b0ea47e
40,817
def kzInterp(data_stack_in, kz_stack_in, kz0, pol_name): """ It generates a synthetic SLC stack of acquisitions by interpolating the original stack of SLC data_stack defined over the kz axis specified by kz_stack in correspondence of the desired phase-to-height. Parameters ---------- da...
1dc73c33c947a87f035311e520c3b9ec914c53bd
40,818
def handler(event, context): """ This function fetches content from mysql RDS instance """ item_count = 0 with conn.cursor() as cur: cur.execute("select * from package") for row in cur: item_count += 1 logger.info(row) return "selected %d items from RDS p...
fd0f00ff86c1e5b775470e00b0ef58098819fdb6
40,819
def _map_ragged_tensor_impl(root, root_path, paths, operation, is_repeated, dtype, new_field_name ): """Maps a ragged tensor. Args: root: the root of the expression. ro...
855582254900bc85e857b63f1264e769348971a6
40,820
def ceil(number) -> int: """ >>> import math >>> numbers = [-3.14, 3.14, -3, 3, 0, 0.0, -0.0, -1234.567, 1234.567] >>> all(math.ceil(num) == ceil(num) for num in numbers) True """ return int(number) if number - int(number) <= 0 else int(number) + 1
20c3f5cf56cd149e00a76e368729a76012b24375
40,821
def update_activity_link_parent_child(data): """Update exchange activity links from parent to child (i.e. the current) dataset. Correct an error in ecoinvent master data production. In a few cases, an exchange in a child dataset includes an ``activityLink`` to the parent dataset, from which the datase...
f4a1b30449d31e163ff0c7f72f38606b30877e4d
40,822
def get_all_areas(): """Get a dictionary with all findable areas """ return sattools.ptc.get_all_areas(["satpy", "fcitools"])
150eb0d983c119fcc2af0ea039d567eb85351da5
40,823
def is_valid_unique_product_ids(document: dict) -> bool: """Temporary implementation of rule for unique product ids.""" prod_ids = [] for path in uni_pro_ids.CONDITION_JMES_PATHS: pids = jmespath.search(path, document) if pids is not None: prod_ids.extend(pids) probe = jmespa...
3172c68bed4ab500c3db737492f00fdd0d2070e6
40,824
import bigflow.transform_impls.pipe def pipe(pvalue, command, **options): """ 对于给定的PCollection/PTable,返回通过command处理后的PCollection Args: pvalue (PCollection/PTable): 输入 command: 命令行 **options: 可配置选项 type: pipe类型,目前支持streaming和bistreaming,默认为streaming buffer_size: 缓存大小(单条...
6a883e8689d0f3b6ecdf23983aba9ff709f0fbec
40,825
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/temp_stats_start/yyyy-mm-dd<br/>" f"/api/v1.0/temp_stats_start_end/yyyy-mm-dd/yyyy-...
f8b1ae7435e220103d0013ab930804bc1be928c3
40,826
import re def remove_strange_chars(text): """Remove funky characters that don't belong in a URL.""" return re.sub(STRANGE_CHAR_PATTERN, "", text)
608caf15156b9c2bb4ffa977fa1e80394079bc16
40,827
def load_tfrecords(filenames, batch_size=64): """Loads a set of TFRecord files Args: filenames (str / str[]): TFRecord file(s) extracted by rosbag_to_tfrecord Returns: tf.data.MapDataset """ if not filenames or len(filenames) < 1 or filenames[0] == "...
f19f10546438260ae3f3b894fcd8b75c9144ecae
40,828
from typing import Dict from typing import Any import torch from typing import Tuple import os import yaml def train_pretrained( model_name: str, from_pretrained: str, log_name: str, model_config: None, data_config: Dict[str, Any], log_dir: str, fp16: bool, device: torch.device, ) -> T...
62c4bfa0691a4a3dff79ff8b5472e9b334457f26
40,829
def build_projection_operator(l_x, n_dir=None, l_det=None, subpix=1, offset=0, pixels_mask=None): """ Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int, default l_x number of angles at whi...
170f1ed9fc69cee4edc65aef5f3bc0e79b018022
40,830
def check_permissions(accountid, command): """ Checks The Permission To Player To Executive Command Parameters: accountid : str command : str Returns: Boolean """ roles = pdata.get_roles() if is_server(accountid): return True for role in roles: if accountid in roles[role]["ids"] and "ALL" in ro...
09df6a860a953c240bac65c9f7f99438f6c334c3
40,831
def train(model, train_loader, optimizer, criterion, step): """ train one epoch """ for batch in train_loader: step += 1 optimizer.zero_grad() left_img = batch['left'].to(device) right_img = batch['right'].to(device) target_disp = batch['disp'].to(device) ...
43fed9483ab7c9a78eb9f1addef0f44be4f335ec
40,832
def get_group_followers(group, ignore_permission=False): """Returns a list of group member Contacts owned by the members.""" if not ignore_permission: assert_group_permission(group, 'Group Permission denied') if not group.is_group: return [] return _get_follower_contacts(group.user_id...
b4b787d503c5e0625574d3fc7858570ec47556a1
40,833
import librosa def getCensFeatures(XAudio, Fs, hopSize, squareRoot = False): """ Wrap around librosa to compute CENs features :param XAudio: A flat array of raw audio samples :param Fs: Sample rate :param hopSize: Hop size between STFT windows :param squareRoot: Do square root compression? ...
94cfb7f12c19192faada1e63309921309b641957
40,834
def comet_magnitude_power_law(h=10., n=4., delta=1., r=1.): """The conventional power-law formula to predict a comet's brightness. Parameters ---------- h : float Absolute magnitude. n : float Activity parameter. delta : float Comet's geocentric distance in AU. r : f...
962c67e8f2a6e7ebf95307f5284fecddac3afef2
40,835
import copy def _match_single_exposure_against_pyephem_db( exposure, log): """*summary of function* **Key Arguments:** - ``exposure`` -- the atlas expsosure metadata - ``log`` -- logger **Return:** - None **Usage:** .. todo:: add usage in...
6da5092a5fd8719b2643a0f4de55a9cb6bbaa737
40,836
from typing import Literal def setFilterType(filter_type : Literal[0, 1]): """ Set Filter Type (1 byte) filter_type: - 0 = FILTER_INCLUSIVE - 1 = FILTER_EXCLUSIVE Used for: - RP1210_Set_J1708_Filter_Type (24) - RP1210_Set_J1939_Filter_Type (25) - RP1210_Set_CAN_Filter_Type (26) ...
cb0412e82db0efdc29b2b9f1e5ccbb77acabe1f9
40,837
def nrms(data_fit, data_true): """ Normalized root mean square error. See: https://nl.mathworks.com/help/ident/ref/goodnessoffit.html """ # root_mean_squared_error = np.mean(np.linalg.norm(data_fit - data_true, axis=0), dtype=numpy.float16) # RMSE # normalization_factor = 2 * np.linalg.norm(da...
ee93497c64b0d8a8e7d7c94287277ddaf60bb5f8
40,838
import copy import sys import os import importlib import re import traceback def import_module(rootm, filename, log_function, additional_sys_path=None, first_try=True): """ Imports a module using its filename. @param rootm root of the module (for relative import) ...
7bffb60a6b5ab3f77bfe144ef5056fcbc60ee4fb
40,839
def test_from_file_decorator(tmp_path): """ Test the from_file decorator. """ # create a temp yaml file yaml_content = """ --- get: summary: Hello operationId: hello responses: 200: content: application/json: schema: type:...
ee8042214e68181b2c3d569c115a4c37c98cb766
40,840
import hashlib import hmac def assert_dg_hash( dg_file: bytes, data_group_hash_values: bytes, hash_alg: str, dg_number_bytes: bytes ) -> bool: """ Calculate the hash over the DG file and compare that in the EF.SOD. """ dg_number = int.from_bytes(dg_number_bytes, byteorder="big") # Only hashes ...
5448cd5a8df7a7aee85030100571c5e919980245
40,841
def isPlayerValid(player_id): """ check whether player id is valid in the DB """ try: Player.objects.get(id=player_id) except Player.DoesNotExist: return False else: return True
4c45a400ca61434d420fa2ef7a417ebde543400b
40,842
def str_format(s, *args, **kwargs): """Return a formatted version of S, using substitutions from args and kwargs. (Roughly matches the functionality of str.format but ensures compatibility with Python 2.5) """ args = list(args) x = 0 while x < len(s): # Skip non-start token characters...
addf11c8390c52da7b0f2886d2298bab66a50e49
40,843
def __private_function_example(): """This is a private function example, which is indicated by the leading under scores. :return: tmp_bool""" tmp_bool = True return tmp_bool
be8d0309dc3a52d4f128e2e113046c1c79efe457
40,844
from sage.functions.other import log_gamma def _sympysage_lgamma(self): """ EXAMPLES:: sage: from sympy import Symbol, loggamma sage: assert log_gamma(x)._sympy_() == loggamma(Symbol('x')) sage: assert log_gamma(x) == loggamma(Symbol('x'))._sage_() """ return log_gamma(self.ar...
cde661ce3a3dd2da3968c5048b9ee1fa0ee36cde
40,845
import raylab import functools def initialize_raylab(func): """Wrap cli to register raylab's algorithms and environments.""" @functools.wraps(func) def wrapped(*args, **kwargs): raylab.register_all() return func(*args, **kwargs) return wrapped
3c4f00c662fad9954ecdb09119368bb02d72d03f
40,846
async def pessoa_projeto_edit( request: Request, pessoa_projeto_id: int, pessoa_projeto: PessoaProjetoEdit, db=Depends(get_db), pessoa=Depends(get_current_active_pessoa), ): """ Update pessoa_projeto """ return await edit_pessoa_projeto(db, pessoa_projeto_id, pessoa_projeto, pessoa)
bd611aa8fb726a5d97d75d534d53f92e02e8e943
40,847
def ingest( dtype, shape, colors, data_split, get_buffer, get_local_colors=None ): """ Construct a single-column Table backed by a collection of buffers distributed across the machine. Each buffer is assumed to cover a disjoint dense subset of a rectangular n-dimensional domain, and is identifi...
1459e6e275060a0d29c718dd552012937c6ebb96
40,848
from typing import Any def described_as(description: str, matcher: Matcher[Any], *values) -> Matcher[Any]: """Adds custom failure description to a given matcher. :param description: Overrides the matcher's description. :param matcher: The matcher to satisfy. :param value1,...: Optional comma-separate...
8ccbaa6afe48b4c6ef62399f1f9de5dfcd16de14
40,849
import jinja2 def _render_json_dict_jinja(json_dict): """Render jinja-templated choice variables in cookiecutter.json dictionary .. note:: This function only modifies dictionary values that are strings containing double curly bracket jinja variables such as '{{ varname }}'. All other di...
fefb867d9da47ab4ef0e5f7fdf628f6d91516517
40,850
import os import pprint def ExpectationTest(test_data_dir): # pylint: disable=invalid-name """Mixin for test output generation/comparison.""" class Mixin: """Mixin.""" def _load_expected(self, expected_name, actual): """Load expected data.""" expected_path = os.path.join( test_dat...
b94199b47e0cc112cff4cf7bafac0f871c5740d6
40,851
from typing import Tuple from typing import Callable from typing import Any def get_random_noise() -> Tuple[Callable[..., Any], int]: """Get a random noise augmentation.""" f, (a, b) = choice(NOISE) # noqa S311 return f, choice(range(a, b + 1))
d0114f66b1e4b91f2ab213d152e0c96f82196590
40,852
from typing import Iterable def any_true(iterable) -> bool: """Recursive version of the all() function""" for element in iterable: if isinstance(element, Iterable): if not any_true(element): return True elif element: return True return False
67b4ea1e3c9da9c92a2ed8a26f346d67825e62fd
40,853
from datetime import datetime import pycountry import logging def load_jhu_data(): """Wrap load_jhu_data_raw, to make data more useful.""" # vaccine data (from owid) vac_data = load_owid_vaccinations_data_raw() country_to_date_to_vac_data = {} for country_data in vac_data: country_alpha_3...
164222f4596f91df4e93125e1e549d24f802851f
40,854
def PrintStartTime(printString): """ Print the current time since execution and a msg (printString) """ endTime = time.time() - startTime print str(int(endTime)) + ' s: ' + printString + ' .......' return endTime
17ad1c55e3943b36b1a6b9fcefa5deb0bce668a1
40,855
def __get_type_from_resource(resource_arn): """ Récupère le type d'une ressource donnée :param resource_arn: Ressource AWS arn :type resource_arn: str :return: default/maintenance :rtype: str """ return __get_tag_value_from_resource(resource_arn, con...
5be4f187775ac14c54962bb404196e568246b976
40,856
import random def random_gaussian(gene): """ Random float from gaussian dist. Args: gene (Gene): A gene with a set `mu` and `sig`. Returns: float: Random number. """ stepped_value = random.normal(loc=gene.mu, scale=gene.sig) while stepped_value > gene.gene_max or stepped...
3e25cdfbb88fae304514384d0d2736ce04321e37
40,857
def group_get_object_permissions_as_int_list(self, instance): """ Get a list of strings representing the user's permissions for this object """ return self.get_object_perm(instance, 'int_list')
861cd60e932f5a83e6e3871fc35aed678bb90fea
40,858
def put_device(sn): """PUT a device""" data = request.json i = Instrument.query.filter_by(sn=sn).first() if i is None: abort(400) # Don't update the sn if 'sn' in data.keys(): data.pop('sn') # Update the device i.from_dict(data, partial_update=True) db.session.add...
83f58e1473de047813e86c3d5f314bdc5f08738e
40,859
import yaml def deserialize(stream_or_string, **options): """ Deserialize any string of stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower yaml module. """ options.setdefault('Loader', BaseLoader) ...
2632c638446ed7abedb38ea7db5e9e4b8900357d
40,860
def ReadDir(*args): """ReadDir(char const * utf8_path) -> char **""" return _gdal.ReadDir(*args)
8752dd32478f3cf3a0c4fe8821a0abe4341a425b
40,861
def clocks(now=posix_safe_datetimes()): """ Build ``twisted.internet.task.Clock`` instances set to a time built by ``now``. """ def clock_at_time(when): c = Clock() c.advance((when - _POSIX_EPOCH).total_seconds()) return c return now.map(clock_at_time)
6b4f3146533bd7f404b3bf0e17665376ee7e88ed
40,862
import os import time def fetch_matches_loop(url, skill, start_at_match_id, hero): """Loop until we find matches. There is a bug in valve API with load balancing, sometimes the API returns no matches, so we'll re-try a few times if we expect more matches. """ resp = {} for retry in range(20): ...
7bab2e8306669cc4b4c1cd2c9cdb5421dafeb3d6
40,863
def get_recorded_functions_legend_fig(): """Get Plotly figure used as recorded functions legend. i.e., whether a mutation has recorded functions :return: Plotly figure containing indel legend :rtype: go.Figure """ ret = go.Figure(get_recorded_functions_legend_graph_obj()) ret.update_layout...
94d99b20af89811d3a66540deef89349a23c225f
40,864
def quote_string(s, force=True): """Places a string in double quotes, returning the quoted string. force Always quote the string, defaults to True. If False then valid tokens are not quoted but returned as-is. This is the reverse of :py:func:`decode_quoted_string`. Note that only the...
f1bcb8bcfc9d12fbedd3e108bef0d81400055df0
40,865
import math import numpy def getMatrix3(eulerdata, inplane=False): """ math from http://mathworld.wolfram.com/EulerAngles.html EMAN conventions - could use more testing tested by independently rotating object with EMAN eulers and with the matrix that results from this function """ #theta is a rotation about th...
365b158cd6d5f3150c725a6f8df0d14160168dae
40,866
def constant_value(value_or_tensor_or_var, dtype=None): """Returns value if value_or_tensor_or_var has a constant value. Args: value_or_tensor_or_var: A value, a `Tensor` or a `Variable`. dtype: Optional `tf.dtype`, if set it would check it has the right dtype. Returns: The constant value or N...
c870531ae2a6c4bb5746a96605286ff199f160fb
40,867
def generate_data_batch(batch_size=100, max_seq_length=150, vocabulary=None, embeddings=None, training_split=0.8, train=True): """ Generate a random training batch of size batch_size. """ df = load_split_amzn_reviews() train_test_split_idx = int(training_split * len(df)) if train: df = d...
edbde497289e13127f9844cc6e029725f5d0236c
40,868
import os def setup_paths(): """Sets up the necessary paths to collect videos.""" assert FLAGS.dataset assert FLAGS.mode assert FLAGS.num_views # Setup directory for final images used to create videos for this sequence. tmp_imagedir = os.path.join(FLAGS.tmp_imagedir, FLAGS.dataset, FLAGS.mode) if not o...
17590560370ee0da11a9d0eedd7cf34620082bc3
40,869
def upper_camel(name, split_char="_"): """Converts a given name into upper camel case :param name: The name to be converted :type name: str :param split_char: The character that separates words in the name. :type split_char: str :return: str """ return "".join(w.capitalize() for w in na...
25fe4f07612d2402f3b0107ada9f9efb9133e5dd
40,870
def _py_gaussian_kernel(ksize=3, sigma=-1.0): """Returns a 2D Gaussian kernel. See cv2.getGaussianKernel for details. Args: ksize: aperture size, it should be odd and positive. sigma: Gaussian standard deviation. If it is non-positive, it is computed from ksize as sigma = 0.3 * ((ksize - 1) * 0.5 ...
073f62d2f047f2124878c0d6bc245dbc737bfc82
40,871
def abundant(n): """ A number n is called abundant if the sum of its proper divisors is more than n. Returns True if n is an abundant number, False otherwise. """ return sum(primes.divisors_proper(n)) > n
3b2c370322d7855be9f340cd1582e27e9fe4625f
40,872
def appres_phase_from_data(survey): """ Compute apparent resistivity and phase given impedances (real and imaginary components) and the frequency. """ data = survey.dobs frequency = survey.frequency # data are arranged (Zxy_real, Zxy_imag) for each frequency Zxy_real = data.reshape((...
528fb0e78b1b9f947986ffc59a6e30215ce712a1
40,873
import os import sys def ensure_config_path(config_dir, conf_name=berm_const.CONFIG_PATH): """Check if config file exists.""" if not os.path.isdir(config_dir): print((berm_const.ERR_CONFIG).format(config_dir)) sys.exit(1) config_file = os.path.join(config_dir, conf_name) if not os.pat...
2ec6d006ab6977d4af06b192120313051cca4f82
40,874
from typing import Collection def remove_space(toks: Collection): """ Do not include space for bag-of-word models. :param list[str] toks: list of tokens :return: list of tokens where space tokens (" ") are filtered out :rtype: list[str] """ res = [] for t in toks: if t != " "...
6f638cffa11417ebe975955b3cd2780a07a4a500
40,875
def defaultkeys(root): """keydefs lezen uit keyboard.txt - mapping maken van deze op ... vooralsnog alleen omschrijving """ data = {} ky = [] ky_desc = '' join_keys = False temp = read_lines(root) for x in temp[6:]: x = x.rstrip() if x == "": break ...
f68059bd048f6c87e72120cfe5f17169d5993818
40,876
import glob import os import sqlite3 import json def load_since_ids(cache): """Loads most recent Tweet IDs from database to cache""" since_ids = dict() db_filenames = glob.glob(os.path.join(DIR_PATH, "data/tweet_sentiment_*.db")) for db_filename in db_filenames: conn = sqlite3.connect(db_filen...
f118214e97995ec20d339c7c62b3fb5bc42ce4b3
40,877
def _decompose_unit(unit): """unit should be a Quantities Dimensionality object Returns (conversion, base_unit_str) """ assert isinstance(unit, pq.dimensionality.Dimensionality) if len(unit) != 1: raise NotImplementedError("Compound units not yet supported") # e.g. volt-metre uq, n = u...
9e60224e37df19fdba9db2ecf705d3bfe30699cd
40,878
import tempfile import os import shutil def run_test(options, argv): """ Define the test environment and compile the p4 target Optional: Run the generated model """ assert isinstance(options, Options) tmpdir = tempfile.mkdtemp(dir=os.path.abspath("./")) os.chmod(tmpdir, 0o744) basename = ...
70c54cf21df36baf9023963680acfffd37a458f6
40,879
import json def unknown_method_request(): """Sample unknwon/invalid method request for testing purposes.""" return json.dumps( { "method": "some_random_method", "params": {}, } )
50fcfda030df632a0d1275bcb55c58e2f80e8c6b
40,880
def plot_targets(targets=None, assignments=None, iexp=0, robots=True, hexagon=True, categories=[], observatory='apo'): """Plot targets in the field Parameters ---------- targets : ndarray target information as stored in Field assignments : ndarray ...
dcd94f98dfe65876ec50f6abf0b5e9123d454c44
40,881
def python_text(text="is cool"): """prints Python is cool""" text = text.replace("_", " ") return "Python %s" % text
e63ac18466433973aa4a3fd9f0b7151309c62464
40,882
def matchesSyntax(line): """ parses a configuration line and returns whether it conforms to the syntax""" line = line[1:] # strip leading '+' or '-' s = line.split() (ok0, msg0) = matchesPatternSyntax(s[0]) if len(s) < 1 or ok0: pass else: return (False, msg0) (ok1, msg1) = match...
b9ebd090396bd7d63e0d7c2724b8075123e0720c
40,883
def linear_warmup_and_polynomial_decayed_lr(settings, global_step): """ settings.learning_rate_base settings.warmup_steps settings.decay_steps settings.learning_rate_minimum settings.lr_power settings.lr_cycle """ learning_rate = tf.constant(value = settings.learning_...
2e1bb6ad6c015f81f5907041ad379e44346a42cb
40,884
def get_doc_string_generator(): """Returns the currently registered doc string generator.""" return _generate_doc_string_func
6b28cea0463b71fa4a5f2a03458c02e5cc6caf27
40,885
def _dual_bootstrap(variances): """ helper function to perform the dual bootstrap Takes a 3x... array of variances and computes the corrections assuming: variances[0] are the variances in the double bootstrap variances[1] are the variances in the rdm bootstrap variances[2] are the variances in the ...
e27353c9bd3804c361bad35709314a160968b7df
40,886
def load_ref_system(): """ Returns l-ascorbic_acid as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" H 0.6888 -1.5618 -0.6197 C 0.3271 -0.5321 -0.3981 O 0.5813 -0.3520 ...
c7e43dec47d33beb6ddbc47c6703697c19783c73
40,887
def medfilt_along_axis(x, n, axis=-1): """Applies median filter smoothing on one axis of an N-dimensional array. """ kernel_size = np.array(x.shape) kernel_size[:] = 1 kernel_size[axis] = n return medfilt(x, kernel_size)
f6b5d9a64ff7f7fbfcff3a06156998ee574afd52
40,888
def as_float_array(array: np.ndarray, min_float=np.float32) -> np.ndarray: """Convert array to a floating point array.""" array = np.asanyarray(array) dtype = np.result_type(array, min_float) return np.asanyarray(array, dtype=dtype)
ce6a9d2d5bbf3eecd61e87b1e64e0e3c64b6454b
40,889
def pcy(series, n=1): """Percent change over n years""" return (series/series.shift(n*series.index.freq.periodicity)-1)*100
a18bff66c60bf2620f524e104cf0b9842a85acf4
40,890
def to_eval_str(value): """ Returns an eval(str(value)) if the value is not None. :param value: None or a value that can be converted to a str. :return: None or str(value) """ if isinstance(value, str): value = eval(str(value)) return value
4cb13ad95095b8a6ee494265e600f989d98be05e
40,891
def random_weights(w_cnt, op=lambda l: l): """ Generate random normalized weights Args: w_cnt: size of the weight vector op: additional operation to perform on the generated weight vector """ weights = np.random.random(w_cnt) weights = op(weights) weights /= np.sum(...
20fcc4d8a3f18fc34d9b5647f7437a9dfd29a51b
40,892
import string import random def get_random_string(size=8, chars=string.ascii_uppercase + string.digits): """ Получает случайную строку указанного размера и с указанными символами. """ return ''.join(random.SystemRandom().choice(chars) for _ in range(size))
b546c9a397720d7adef504cb5982c14785038b42
40,893
def company_denomination_year(denomination, year): """ Retrieve company information for a given year by company denomination. Path is /company/denomination/<string:denomination> GET method only and no strict slash. :param denomination: String, denomination of the company. :param year: Year of...
198ce546a33c5e859a22801ebe24ab1909b999c2
40,894
from re import A def TripleDes_Encryption24(data: A, key: A) -> A: """ :type key: object :type data: object """ encrypted_data = triple_des(key).encrypt(data, padmode=PAD_PKCS5) return encrypted_data
a19572b517b64b2e57482ab1cf9aa79f15a00c17
40,895
from typing import Callable from typing import Any def raises(exception: Exception, pattern=None, matching=None) -> Matcher[Callable[..., Any]]: """Matches if the called function raised the expected exception. :param exception: The class of the expected exception :param pattern: Optional regular expr...
442bc1a90504e7f5eb6143792f0a1d131d87c9c7
40,896
def GammaW(tempk, pres): """Function to calculate the moist adiabatic lapse rate (deg C/Pa) based on the environmental temperature and pressure. INPUTS: tempk (K) pres (Pa) RH (%) RETURNS: GammaW: The moist adiabatic lapse rate (Deg C/Pa) REFERENCE: http://glossary.ametsoc.org...
6b8588ca09a72f65261970b69d1f4acf8d56f8e5
40,897
def np_concatenate(paths): """ :param paths: list of paths of .npy arrays :return c: concatenated array """ aa = [] print("\n".join(paths)) for path in paths: a = np.load(path) aa.append(a) pass c = np.concatenate(aa) return c
f9d33451b399d370daebe512080fdc29d29564e1
40,898
from typing import Union from typing import TextIO from typing import Iterator import re def read_multilayer_svg( file: Union[str, TextIO], quantization: float, crop: bool = True, simplify: bool = False, parallel: bool = False, default_width: float = _DEFAULT_WIDTH, default_height: float =...
990b6a321d46e48ca40c28044778d1c77299930a
40,899