content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple import hashlib def hashfile(path: str, blocksize: int = 65536) -> Tuple[str, str]: """Calculate the MD5 hash of a given file Args: path ()str, os.path): Path to the file to generate a hash for blocksize (int, optional): Memory size to read in the file ...
e38e6622534f27bed109a2e2b71373503ca4e7b0
38,300
import torch def generate_bandit_samples(logging_policy, syn, k=5): """Generates partial-labeled bandit samples with the logging policy. Arguments: k: The number of items to be sampled for each user. """ logging_policy.set_binary(False) with torch.no_grad(): feats = {} fea...
3ec8d36f7e41e779bd4372aadaeac90e1073ec86
38,301
def get(key): """ Retrieve a constant by key. This is just a short cut into a dictionary. Parameters ---------- key : Python string or unicode Key in dictionary in `constants` Returns ------- constant : `~astropy.units.Constant` See Also -------- _constants : Cont...
1d9a73b7089ebd126855e7edd7fe275dbd59763c
38,302
def compute_qvalues(state_action_reward: np.ndarray, discount: float) -> np.ndarray: """Computes the Q-values of `state_action_reward` under deterministic dynamics.""" transitions = build_transitions(*state_action_reward.shape) reward = build_reward(state_action_reward) return reward
06a987b000dc50ed0d02e913fd980c3c2ab97bd6
38,303
import argparse def get_args( ): """ Get args from Argparse """ parser = argparse.ArgumentParser( description=description, formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument( "-i", "--input", required=True, help="H...
2b678c7d87015a62fede9a8951681d83513b3781
38,304
def parse_csr(csr): """ Helper function that parses a CSR. :param csr: :return: """ assert isinstance(csr, str) return x509.load_pem_x509_csr(csr.encode("utf-8"), default_backend())
7de072cce63b8a13c1666013a40b4091418bb1b0
38,305
def docker_compose_yml(opts): """docker-compose.yml for vscode Args: opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: str: file content as string """ template = get_template("docker_compose_yml") return template.safe_substitute(o...
e7e40ee3f9f1946944e6f993e7635636a50cd75d
38,306
def get_directory(): """ Get the name of home directory of usecase. Use the home directory for file path construction. """ home_dir = dirname( dirname(abspath(__file__)) ) # call dirname twice to get parent dir return home_dir
bfbb234cfcaac0e900f8bf472e0f5cf4ac249fd1
38,307
import os import subprocess def edit_pkgbuild(pkgname): """Edit a PKGBUILD interactively. Returns False if user aborts install.""" yesno = DS.fancy_msg_prompt(_('Edit PKGBUILD of {0}? [Y/n] ').format(pkgname)) if yesno.lower().strip().startswith('y') or not yesno.strip(): if os.environ['EDITOR']:...
88a5a0fc6459f67bf8e0aa9a2fcf3d0581fb343b
38,308
import pathlib def package_data() -> pathlib.Path: """ Returns the absolute path to the circe/data directory. """ return pathlib.Path(__file__).parents[1].joinpath("data")
19d8fa28ba872f8633e6efddb310d30264d831e6
38,309
import re def changeFileNoInFilePath(path: str, fileNo: int) -> str: """replaces the number in the path with the given number.""" separator = r"[0-9]+\." splitted_path = re.split(separator, path, 1) new_path = splitted_path[0] + str(fileNo) + "." + splitted_path[1] return new_path
070fbe30d2937b57ef601fb764cf68ec219b9c95
38,310
def common_fill_value(a, b): """Return the common filling value of a and b, if any. If a and b have different filling values, returns None. """ t1 = get_fill_value(a) t2 = get_fill_value(b) if t1 == t2: return t1 return None
f6d7e06c0553efece9972e023f4d6237f62cdb75
38,311
def hybrid_to_plevs(var, hyam, hybm, ps, plev): """Convert from hybrid pressure coordinate to desired pressure level(s).""" p0 = 1000. # mb ps = ps / 100. # convert unit from 'Pa' to mb levels_orig = cdutil.vertical.reconstructPressureFromHybrid( ps, hyam, hybm, p0) levels_orig.units = 'mb...
dce7ff8d3cee56b075b1de63b0d814858d466d5e
38,312
def pentatope(): """ Vertices of the 5-cell """ s = 3.2**-0.5 return np.array([ np.quaternion(1, 0, 0, 0), np.quaternion(-0.25, s, s, s), np.quaternion(-0.25, s, -s, -s), np.quaternion(-0.25, -s, s, -s), np.quaternion(-0.25, -s, -s, s), ])
1315f5f70a01d6112e97461e08917fec5cf1fbb2
38,313
def checkDaysWeeksElapsed(count, days, weeks): """ :param count: the number of checks performed :param days: the number of days elapsed :param weeks: the number of weeks elapsed :return: the number of checks performed (0 if one day has gone). """ if (count % 144) == 0: days += 1 ...
ec425653c6ca21a52ff4a98d18326f6278e83a6c
38,314
def spawnpty(cmd, logfile=None, env=None, callback=None, persistent=False, merge=True, pwent=None, async=False, devnull=False): """Start a child process using a pty. """ pm = get_procmanager() proc = pm.spawnpty(cmd, logfile, env, callback, persistent, merge, pwent, ...
efab388d7f09419272807fdb788bb8794fb92a6c
38,315
import os def dirmap_file_name_filter(file_name): """Nuke callback function with single full path argument. Checks project settings for potential mapping from source to dest. """ dirmap_processor = NukeDirmap("nuke", DirmapCache.project_settings(), ...
996d467e66a62f2eccaf7957b2b241d6711fbf1f
38,316
import typing def update_submission_status( sub_status: SubmissionStatus, values: typing.Union[Annotations, dict], status: str = None, ) -> SubmissionStatus: """Updates submission status and annotations Args: sub_status: A synapseclient.SubmissionStatus values: A synapseclient.A...
8ff18d399048350cea7f8043321a5c4dec346924
38,317
import signal def get_window_radial(xx, yy, zz=None, wtype='hamming', rmax=None, duration=None, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, n=500): """ General method to get a window with shape (xx.shape[:], duration) or (xx.shape[:]) if duration is None ... Wi...
8d8298716e4e2fd825c4c1bcd4adf97d6fde7f1d
38,318
def ldns_resolver_fail(*args): """LDNS buffer.""" return _ldns.ldns_resolver_fail(*args)
c5934c4efbd0786dedf01a800ddfcf72346dc088
38,319
def filter(tracks, condition_func): """A workaround for a bug in pandas 0.12 Parameters ---------- tracks : DataFrame must include column named 'particle' condition_func : function The function is applied to each group of data. It must return True or False. Returns ...
b9b338ff9d3eccf3761102e9f6a02bea94030745
38,320
def get_batch_jdot(selected_source, selected_target, source_data_file, target_data_file, batch_size, n_labels, training_keys_file, validation_keys_file, data_split=0.8, overwrite_data=False, labels=None, augment=False, augment_flip=Tr...
c152bfe13fda3d51a8a6a8763e867ffe46b87149
38,321
from typing import Dict from typing import List import uuid async def _choose_existing_instances( instance_registrar: InstanceRegistrar, resources_required_per_job: Resources, num_jobs: int, ) -> Dict[str, List[str]]: """ Chooses existing registered instances to run the specified job(s). The gener...
ec0bf9ed8ae5a1a9b8234cadff4f358bcf2273f4
38,322
def secret_view(request): """Dummy view with redirect to login.""" return {}
9b0c3a6d2fe0b6aef2328a97d6407b72f8bc3c16
38,323
def get_data_from_all_ezo_devices(device_list): """Returns a list of string output from all EZO devices.""" output = [] for device in device_list: device.write("R") sleep(device.long_timeout) for device in device_list: output.append(read_data(device)) return output
0aab931cd5a7f2a6d48cf3d969ad86286d78460c
38,324
def get_moves(board, castling_availability, enpassant_square): """List of all moves for white for the given position.""" moves = [] points = board.keys() for start, piece in board.items(): if piece == 'P': moves.extend(get_pawn_finish(board, start, enpassant_square)) if piece...
2b18a3d8a100e87a08424fd02defe412ee639e6e
38,325
def get_export_from_line(line): """Get export name from import statements""" if not line.startswith("export * from"): return None start = line.find("\"") if start > 0: return line[start+1:-3] # remove ";\n return None
c4a0396dcb238b89e7b7e82479935b1849003f85
38,326
def all_col(G): """ Check if every column of G contains a nonzero entry Parameters ---------- G : lin_op operator to check Returns ------- Boolean True if every column of G contains a nonzero entry """ ri, ci = G.toCSR().nonzero() return np.all(np.in1d(np.a...
484978f90ee6e015ae1027e682c67293f7f42333
38,327
def get_challenge(request, scopes=["build"]): """Given an unauthenticated request, return a challenge in the Www-Authenticate header Arguments: ========== request (requests.Request): the Request object to inspect repository (str) : the repository name scopes (list) : li...
38c8d419c7712ebd8dc3db11663baa793ba06d0f
38,328
import time def abbn_eva(): """ Real Name: b'"Ab-bn Eva"' Original Eqn: b'Max(0,"monthly evp ab-bn" (Time)*"area ab-bn"/1000)' Units: b'' Limits: (None, None) Type: component b'' """ return np.maximum(0, monthly_evp_abbn(time()) * area_abbn() / 1000)
ba58382353702dd87c451cd199a2e476b8068d2c
38,329
def construct_organisation_role_dict(organisation_roles): """Return a dict with 3 keys: organisations, roles, and organisation_roles. Args: organisation_roles: an iterable of OrganisationRoles. """ data = {} # Defensive programming: make sure we have a unique set of # organisation_rol...
b1105832eab9ee89dfa5d1e43b51c05fb569b953
38,330
def validate_ruletype(t): """Validate fs_use_* rule types.""" if t not in ["fs_use_xattr", "fs_use_trans", "fs_use_task"]: raise exception.InvalidFSUseType("{0} is not a valid fs_use_* type.".format(t)) return t
dd1c33c463f765bb8abe5e5086a9bd0d46b2c7f6
38,331
async def is_dark_theme(monitor=None, app=None): """Return whether or not iTerm2 theme is dark""" theme=None if monitor: theme = await monitor.async_get() elif app: theme = await app.async_get_variable("effectiveTheme") else: raise ValueError('Need a monitor or app instance t...
8c356514d19219af83a36f422d78e688351c9f09
38,332
import json def load_json(path): """Load json from file""" json_object = json.load(open(path)) return json_object
17db7327b6dac16aaeaff2354f828646eff695b2
38,333
def home_url_response(url_endpoint: str) -> Response: """Represent response from `home` page""" return Get(url_endpoint + _home).response()
d8f31c659dfe71c3dcd7b96cdfe5aa86ae96fc03
38,334
import os def module_path(): """Figures out the full path of the directory containing this file. `PACKAGE_DIR` becomes the parent of that directory, which is the root of the solvertools package.""" return os.path.dirname(__file__)
f4576fbdcca394f525b9419a7e9d8a81ed1ff223
38,335
def evidence_download(filename): """Download an evidence file :param filename: Filename to download :returns t_evidence.f_data: Base64 of file contents """ row = db(db.t_evidence.f_evidence == filename).select(db.t_evidence.f_data).first() if row is None: return None return row.f_d...
d8e0265e385039975b3ec9af95546f4c0fc7d628
38,336
def a_h(P, h, region = 0): """Isobaric cubic expansion coefficient [1 / K]""" if region is 0: region = idRegion_h(P, h) if region is 1: return region1.a_h(P, h) elif region is 2: return region2.a_h(P, h) elif region is 4: return region4.a_h(P, h) else: re...
d2fe0ca5819d01ceb4c1e2573134d71f999412e8
38,337
def register_data_module(name: str): """ New data module types can be added to OpenSpeech with the :func:`register_data_module` function decorator. For example:: @register_data_module('ksponspeech') class LightningKsponSpeechDataModule: (...) .. note:: All vocabs must imple...
31ee6d841c41887b831d96ac879108eb5ac9c2c7
38,338
def _bin_labels_to_segments(bin_labels: list) -> list[tuple]: """ Convert bin labels (time-axis list data) to segment data >>> _bin_labels_to_segments(['female'] * 5 + ['male'] * 10 + ['noise'] * 5) [('f', 0, 5), ('bbb', 5, 15), ('v', 15, 20)] """ if len(bin_labels) == 0: return [] ...
6b0eafdaf6affee33a3b655ba8ae7aebf2b38746
38,339
def get_winners(post_link, MEDIA_LINK, bot): """It creates a list of winners.""" favorite_comments = get_favorite_comments(post_link, MEDIA_LINK, bot) maybe_winners = defaultdict(list) for user_id, username, text in favorite_comments: usernames_from_comment = get_usernames_from_comment(text) ...
dcffc9ab9c225e4536a05d4ab8ecf83c465cdbf5
38,340
def get_latest_layer_version(package="boto3", region="ap-southeast-1"): """ return: layer_version (int): returns latest layer version as an integer! """ client = session.client("dynamodb") pk = f"lyr#{region}.{package}" sk = "lyrVrsn0#" response = client.get_item( TableName...
1568bdb5f921e4e33f0b782723e1d7a4d2febacb
38,341
def build_efficiencies(efficiencies, species_names, default_efficiency=1.0): """Creates line with list of third-body species efficiencies. Parameters ---------- efficiencies : dict Dictionary of species efficiencies species_names : dict of str List of all species names default_e...
a8f8912cd290b86697c67465b4aed18220a8c889
38,342
import time import re def extract_job_edit_form(form): """Extract the input from the Job Edit Form and update the MySQL database with the information. """ if not form.has_key("edit_form"): return False job_id = check_job_id(form) if job_id is None: return False mysql.job_...
0f1f00db924f99e1f608217475931a0325300760
38,343
import time def sudo_password_needed(session: SessionBase) -> bool: """ Check whether password reentry is necessary for sudo actions """ timestamp = int(session.get(SUDO_SESSION_KEY, '0')) time_diff = time.time() - timestamp return time_diff >= SUDO_TIMEOUT_SEC or time_diff < 0
5a72a2bdf87e133994768bee170fb2841ebe9142
38,344
import copy def increment_1(time, seconds): """ Pure function,不會修改引數,大多會產出結果。 """ new_time = copy.deepcopy(time) new_time.second += seconds modify_time(new_time) return new_time
f43a7666f10d594feb18dac05126b4a0883ad4e3
38,345
def generate_county_dcids(countyfips): """ Args: countyfips: a county FIPS code Returns: the matching dcid for the FIPS code """ if countyfips != 59: dcid = "dcid:geoId/" + str(countyfips).zfill(5) else: dcid = "dcid:country/USA" return dcid
ae294e5467b9c735e175d4a69ff30f8ca189c71f
38,346
from allennlp.models.archival import load_archive # import here to avoid circular imports from typing import Type from re import T from typing import Any from typing import Dict from typing import List from typing import Tuple from typing import Set from typing import Union def construct_arg(cls: Type[T], # pylint: ...
35a21d9e4efcf88758552017c741ff61d4e45d0a
38,347
import subprocess import apyfal.client.syscall as syscall from apyfal.exceptions import ClientRuntimeException def test_call(tmpdir): """Tests _call""" # Mock Popen dummy_stdout = 'dummy_stdout' dummy_stderr = 'dummy_stderr' dummy_file_content = 'dummy_file'.encode() dummy_file = tmpdir.join...
c9d7f07eafa5c2277d7f28baae875aace5031a53
38,348
def xy2r(x, y, data, xc, yc): """Convert (x, y) values to distance of a (xc, yc) position.""" r = np.hypot((x-xc), (y-yc)) return np.ravel(r), np.ravel(data)
22354dc1925f418f6d1ba55a7a7b45a7671a8f8d
38,349
def _inverse_lookup(dictionary, value): """Does an inverse lookup of key from value""" return [key for key in dictionary if dictionary[key] == value]
4ad34b27fbc35b3bae95bcb8442d1a2f7df94e9f
38,350
def list_delivery_models(request, network): """Propose to create a delivery based on a previous delivery.""" nw = m.Network.objects.get(id=network) vars = { 'user': request.user, 'nw': nw, 'deliveries': m.Delivery.objects.filter(network=nw).order_by("-id") } return render_to_...
d802fef9f0cbc5e70ded037bc26f61c72366d3c6
38,351
import re def tags_score(tags, kw): """ checks library tags see http://www.boost.org/doc/libs/1_35_0/more/getting_started/unix-variants.html 6.1 """ score = 0 needed_tags = { 'threading': kw['tag_threading'], 'abi': kw['tag_abi'], 'toolset': kw['tag_toolset'], 'version': kw['tag_version'], ...
1ca7ed14bde46e7971f2b0a0f011f93221333653
38,352
def access_userPosition(request): """ NOTE: id from users databases must in or equal to users position databases """ user_data = UsersDataSet.getUsersRawData() position_data = UsersDataSet.getUsersPositionData() new_data = [] # almost same, we need some params to access it che...
18a2bea637db4041de6f3d2d99cd9bcd1966a8ef
38,353
def column_to_image(columns, images_shape, filter_shape, stride, padding): """Rearrange columns into image blocks. Parameters ---------- columns images_shape : tuple(n_images, n_channels, height, width) filter_shape : tuple(height, _width) stride : tuple(height, width) padding : tuple(h...
535ca6a945fac65bc7ca02c6f250b347ab17ad2e
38,354
import os def get_expected_returncode(filename): """ Reads expectrc file to determine what the expected return code is """ expected_rc = 0 expected_rc_file = filename + '.expectrc' if os.path.isfile(expected_rc_file): with open(expected_rc_file) as f: expected_rc = int(...
ba52ccaa3e34ed823a9a5f55c3afdcb9c59abc6f
38,355
def horizontal_shear(origin_img, sh = 0.5): """Shears an image horizontal Parameters: ---------- origin_img original image to shear iamge horizontally sv: float, optional shearing percentage Returns: ----- out_img horizontally sheared image """ # find he...
c56e190b08e9656953fecfd3c3863006a70d1ac5
38,356
def isentropic_beta(tab, spec, *XYf): """Isentropic bulk modulus""" return XYf[0]*tab.q['Cs2', spec](*XYf)
3592e31612c94e0000d80f8be13369338fb6b329
38,357
import itertools def tensor_combinations_phases(matrices, repeat, phases): """Compute a list of tensor products for the iteration of matrices, with additional rotation along the z-axis """ products = itertools.product(matrices, repeat=repeat) tensor_products = [] for mats in products: ...
d737b8e22229edbff79ec40cb428ba7ed0e16e97
38,358
import os def urllist(): """加载图片链接 """ list_file = os.path.join('piclist/baidu.txt') url_list = [] with open(list_file, 'r') as f: url_list = [line.strip() for line in f] return url_list[:50]
38c87fb70fc303bf49f09dac2e5f37b9c7ca03ce
38,359
def cluster_verification_get(context, verification_id): """Return verification with the specified verification_id.""" return IMPL.cluster_verification_get(context, verification_id)
cdd87710e29baa637d3f2afcb11918fd43b76d62
38,360
import os import toml def load_conf(filename: str) -> dict: """ Read toml file from the /conf folder. :params filename: str, name of the toml with the extension, ie: model_1.toml """ with open(os.path.join(PKG_PATH, f"conf/{filename}")) as conf_file: conf = toml.load(conf_file) return...
1de2c284cb533c0c3992012853c965c10bdd7234
38,361
def __sub_tree(self, root_node): """ Extract the sub tree rooted in the given node of the current tree. The result is a new tree :math:`st` and a node map :math:`nm` such that: - the node map associates each node of the sub tree :math:`st` to its corresponding node in the original tree - the order...
bae4371722a04d33dac6a301a88521aeb26717c9
38,362
def irls_one_step(pdf: pd.DataFrame, alpha_value: Float, n_cov: Int) -> NDArray[Float]: """ Performs one step of the IRLS algorithm using the components found in pdf and a value of alpha. Returns the resulting coefficient values. If n_cov > 0, then the first n_cov columns from the design matrix X are a...
cc3f4f78857a0099830424ecb44bd47875a7f597
38,363
def get_alns_instance(repair_operators=None, destroy_operators=None, seed=None): """ Test helper method. """ alns = ALNS(rnd.RandomState(seed)) if repair_operators is not None: for idx, repair_operator in enumerate(repair_operators): alns.add_repair_operator(repair_operator, nam...
b56c60e1b9d07fdda994874e06938c2569f2add4
38,364
import random import string def create_key(holder: str) -> AuthKey: """Function for creating an authentication key.""" key: str = ''.join(random.choice(string.ascii_letters) for _ in range(100)) return AuthKey(value = key, holder = holder)
938a60c227f0e5a344a0e3603a883c828b95095c
38,365
def check_for_missing_files(dir_with_files, return_dates=False): """ Checks for missing files after a bulk download. Args: dir_with_files (path): Path to directory with files to verify. return_dates (bool): Return list of dates if True. Otherwise return list of Paths. Returns: ...
db96d3057d140f28a708bc124f0a812cd8b741e1
38,366
import functools def dictify(f): """Convert generator output to a dict""" @functools.wraps(f) def dictify_helper(*args, **kwargs): output = f(*args, **kwargs) if kwargs.get('as_generator'): return output elif output is not None: return dict(output) ...
0da4b552a8757c698060c6bee54509163e210988
38,367
import re def get_song_id(url: str): """Get soundcloud id from website.""" html = session.get(url) match = re.search(r"soundcloud://sounds:(\d+)", html.text) if match: return match.group(1) else: raise RuntimeError(f"Invalid url, {url}")
9389af0e7d8af7acab76fe4d0c5eede1d52dc245
38,368
def checkdeplaid(incidence): """ Given an incidence angle, select the appropriate deplaid method. Parameters ---------- incidence : float incidence angle extracted from the campt results. """ if incidence >= 95 and incidence <= 180: return 'night' elif incidence...
806ef360e7b5b3d7138d88be2f83267e7668d71e
38,369
def error_test(true, predict): """ Function for classifcation of errors. """ if true == predict: return 1 else: return 0
87c1a56ffb52e1cec61a9ce3cab870b7c70fa059
38,370
def determine_high_cor_pair(correlation_row, sorted_correlation_pairs): """Select highest correlated variable given a correlation row with columns: ["pair_a", "pair_b", "correlation"]. For use in a pandas.apply(). Parameters ---------- correlation_row : pandas.core.series.series Pandas seri...
36eccfe0ffb0ac43caf49fe4db8c35c58d0fa29c
38,371
def sgd_optim(config = None, global_step = None): """ Performs vanilla stochastic gradient descent. config format: lr_base: Scalar learning rate. """ learning_rate = config["learning_rate"] train_step = tf.train.GradientDescentOptimizer(learning_rate) #train_step = tf.train.Gradi...
e2c45e72b76b8209d876ab756cb82a3d8eae0228
38,372
from re import T def customise_pr_person_controller(**attr): """ Customise pr_person controller """ s3 = current.response.s3 # Custom prep standard_prep = s3.prep def custom_prep(r): # Call standard prep if callable(standard_prep): result = standard_prep(r...
7a951ca49f212d62c5e52b2d80a37e614e5e61cb
38,373
def get_file_content(file_name): """获取文件的内容""" try: f = open(file_name, 'rb') file_content = f.read() f.close() except Exception as e: print("打开文件异常") else: return file_content
329eb747a6513899b7ccfaf70754fad721f8d88d
38,374
def create_task_a_model(): """ Initializes the mode. Edit the code below if you would like to change the model. """ model = nn.Sequential( nn.Flatten(), # Flattens the image from shape (batch_size, C, Height, width) to (batch_size, C*height*width) nn.Linear(28*28*1, 10) # No...
1330fbe52a047d3c6c16f9122899ab1947906765
38,375
import imp import sys import os def find_module(modulename, filename=None): """Finds a python module or package on the standard path. If a filename is specified, add its containing folder to the system path. Returns a string of the full path to the module/package.""" full_path = [] ...
9d6bc0ad511f6fec3c97dbeffb93f985e2bccdfc
38,376
def title_case(sentence): """ Convert a string to title case. Parameters ---------- sentence: string String to be converted to title case Returns ---------- ret : string String converted to title case. Example ---------- >>> title_case('ThIS iS a StrInG to ...
4a284854d14e655bd09db8d3ae2d254cfb1e4021
38,377
from mpunet.utils import get_last_model import os def init_and_load_latest_model(hparams, model_dir, logger=None, by_name=True): """ Initializes a model according to hparams. Then finds the latest model in model_dir and loads it (see mpunet.utils.get_latest_model). Args: hparams: A YAMLHpa...
310cf116e93f2d4a21a7d721f0c415bca717435f
38,378
def collate_columns(data, column, reset_index=True): """Collate specified column from different DataFrames :param data: dict, of pd.DataFrames spread by {ZoneID: {ScenarioID: result_dataframe}} TODO: {ZoneID: {Climate Scenario: {ScenarioID: result_dataframe}}} :param column: str, name of co...
cd415979efaea317e5520fda7023782939784c55
38,379
import os from datetime import datetime def data_loader(name, path): """ Data loader for all datasets used. :param name: Name of the file (str, without .txt) :param path: Path to where it is :return: """ if name == "dblp": dict_snapshots, dict_weights = load_dblp(name, path) el...
056273e9770bbb0ff021176227faae85d789ce6d
38,380
def preprocess_img(img): """ Images are converted from RGB to grayscale and downsampled by a factor of 2. Deepmind actually used a final 84x84 image by cropping since their GPU wanted a square input for convolutions. We do not preprocess, rather we store as uint8 for the sake of memory. :param i...
0fcd15035f1eb74ca7b343d0de524dd030c6702f
38,381
def logits_fn(features, feature_columns, params): """Calculate logits.""" input_layer = {col.name: tf.keras.layers.DenseFeatures(col)(features) for col in feature_columns} input_layer_mf_user, input_layer_mlp_user = tf.split( input_layer["user_id_embedding"], [params["mf_dim"], params["mlp...
43d185e5e1ded2b38bdb112c6d633cad6884c2c0
38,382
import ctypes def reorder_line(bidi_types_list, text_length=None, line_offset=0, base_direction=None, with_max_levels=False): """ Return visual reordered of a line of logical string """ # TODO """ This function reorders the characters in a line of text from logical to ...
3b1db5b3ddd1393c4169a9d9058b7beed0afe29b
38,383
def processoutgoing(raw, format): """Process outgoing data""" process = mapping.get(format) if not process: return None return process.outgoing(raw)
2375c77a104dd441b7d9131f0aa48acb18cdcd06
38,384
def create_nonlocal_gateway_cluster_name(namespace: str) -> str: """Create the cluster name for the non-local namespace that uses a gateway.""" return "remote-{0}-gateway".format(namespace)
9ca9758a7ee68ede6e57a7f50f2d772b45ee844b
38,385
def add_position_network_count_entries_for_one_organization(voter_id, organization_we_vote_id, google_civic_election_id=0): """ This is called when a voter follows an organization. :param voter_id: :param organization_we_vote_id: :param goo...
fde029043bd824ba346feba46d93f1573602b8e6
38,386
def GetDefaultExecutor(): """Creates a new instance of the configured executor if none exists and returns it""" global DEFAULT_EXECUTOR if DEFAULT_EXECUTOR is not None: return DEFAULT_EXECUTOR executor_name = configuration.conf.get('core', 'EXECUTOR') DEFAULT_EXECUTOR = _get_executor(exec...
0c80b1c5fa3f07a3a94f1d6ef7b55e571cf2bd0a
38,387
import inspect import os import pickle def get_v_info_by_path(session, line_string_path): """This query returns pickled stop_times information from a swuare area defined by 2 points. :param session: the current db session. :type session: Session. :param line_string_2pt: line string defined by 2 points...
0573d273080594eac6f5b4689ef5e23387b76a82
38,388
from typing import List async def get_normalized_node_handler(curie: List[str] = Query(['MESH:D014867', 'NCIT:C34373'])): """ Get value(s) for key(s) using redis MGET """ normalized_nodes = await get_normalized_nodes(app, curie) if not normalized_nodes: raise HTTPException(detail='No matc...
8d30b6361dd9f3d2afa93933454748e7bd737683
38,389
def parse_coords(ifile, ctype=_ctype): """Parses a list of coordinate pairs.""" points = [tuple(map(ctype, pair.split(", "))) for pair in ifile if pair] points = [Point(*pair) for pair in points] return points
057d1395580f5bf313f0e48504adc4a88943f8b6
38,390
def bytecode_from_blockchain(creation_tx_hash, ipc, rpc_host='127.0.0.1', rpc_port=8545, rpc_tls=False): """Load bytecode from a local node via creation_tx_hash = ID of transaction that created the contract. """ if ipc: eth = EthIpc() else: eth = EthJsonRpc(rpc_host, rpc_port, rpc_t...
bc07cfc6e645c93fb4c1b67acdca0a4292ab0f64
38,391
def geometric_estimation(algo='ml', data=None, **kwargs): """ """ return _estimation(algo, data, dict(ml = GeometricDistributionMLEstimation.Estimator), **kwargs)
63f087e60bdb877a9c0417f67085872070656c55
38,392
def get_go2parents_isa(go2obj): """Get set of immediate parents GO IDs""" go2parents = {} for goid_main, goterm in go2obj.items(): parents_goids = set(o.id for o in goterm.parents) if parents_goids: go2parents[goid_main] = parents_goids return go2parents
1a7d79e1233e497dce109690d3e2105f442bc3b9
38,393
def flatten_dict(value): # type: (typing.Mapping[str, Any]) -> Dict[str, Any] """Adds dots to all nested fields in dictionaries. Raises an error if there are entries which are represented with different forms of nesting. (ie {"a": {"b": 1}, "a.b": 2}) """ top_level = {} for key, val in value...
093371728d76ef3d5e8c27d6023b41e282e67e23
38,394
from datetime import datetime def new_text(): """ Write a new text post page """ form = CreatePostForm() if form.validate_on_submit(): t = datetime.utcnow() textpost = TextPost(author=current_user._get_current_object(), title=form.title.data, timestamp=t, tex...
91f69c4648c1af411bfec0d26424981432441cbd
38,395
def Created_Session(msg): """ 创建会话并返回会话id """ try: response = core.create_session() except grpc.RpcError as e: details = e.details() logger.error("error details:{details}") return {"flag": False, "details": details, } session_id = response.session_id logger.i...
628fcfa39746451401ab44fdffeb8716a06d13c9
38,396
from typing import Optional def get_steering_policy_attachment(steering_policy_attachment_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSteeringPolicyAttachmentResult: """ This data source provides details about a specific Steering Pol...
3ee09c995dd9cb620ee0cff1580682333e3345f8
38,397
import subprocess import json def install_latest_brew_formula(log, formula): """Install or upgrade a brew formula""" # Check formula info for install/up-to-date status out, err = subprocess.Popen( [ get_brew(), 'info', '--json=v1', formula ],...
6f5d566c8e1dfb47f1a4a30b6b5bf1db999e5e9e
38,398
def get_parsing_plan_log_str(obj_on_fs_to_parse, desired_type, log_only_last: bool, parser): """ Utility method used by several classes to log a message indicating that a given file object is planned to be parsed to the given object type with the given parser. It is in particular used in str(ParsingPlan), b...
9932894d5184c2e0ed4948d214206307bea4a612
38,399