content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def profile(request, profile_slug): """ Display profile details. """ speaker_profile = get_object_or_404(AttendeeProfile, slug=profile_slug) if not profile_page_visible(profile=speaker_profile, for_user=request.user): return TemplateResponse(request, "conference/profiles/profile_unavailable...
a03d10a9c9641f1fdf04810e915e8a483cb4a01b
38,296
def save_file(filename, contents): """Save a file from the editor""" if not filename: return 0, 0 with open(filename, 'w') as f: f.write(contents) return len(contents), hash(contents)
8e973f67a22a2e7b0836f8db25090c65238492e3
38,297
def GetDockerImageFromTagOrDigest(image_name): """Gets an image object given either a tag or a digest. Args: image_name: Either a fully qualified tag or a fully qualified digest. Defaults to latest if no tag specified. Returns: Either a docker_name.Tag or a docker_name.Digest object. """ if no...
7e61f8a3dde64ec5efa833fc72e909e9140f77f9
38,298
def line_label(ax, pos, label, dir='v', loc='top', xx=None, yy=None, ha=None, va=None, line_kwargs={}, text_kwargs={}, dashes=None, rot=None): """Plot a vertical line, and give it a label outside the axes. Arguments --------- ax : `matplotlib.axes.Axes` object Axes on which to pl...
9612f2218ce6559f7deffc0f148c4d205b3608b1
38,299
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
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 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 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 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
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 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
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
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
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
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
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
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
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
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
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
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
from typing import Optional def original_text_sector( run: Optional[Run] = None, clustered: bool = True, ): """the text sector for each company from the original clustering. If the companies were not included in that the text sector clustering, this will be `None` for each company.""" run = ru...
8a92cc66954d90651bb2562afc84e42131a599d1
38,401
from typing import Union from typing import Dict from typing import List def flatten_errors(error_message: Union[Dict, List, str]) -> str: """Flatten Cerberus' error messages.""" def flatten_dict(error_dict: Dict) -> str: """Return a string version of the dict.""" return ", ".join([f"{key}: {f...
ab6f359cc214a5a1929254e6066fdc6740938f09
38,402
def get_byuserid(u_id, categories): """Render all gifts created by a user of id u_id. Arguments: u_id (int): the id of the desired user. categories (object): generally passed through the @include_categories decorator, contains all categories in the data...
615d12e32fc30ab18ea9b1010516ec94e8b17815
38,404
def index(request): """ This view redirects user to home if logged in else it redirects user to login page. """ if request.user.is_authenticated: return HttpResponseRedirect('home') return HttpResponseRedirect('login')
f89da15db58f1ae6e4d206086cac36dd3396acb4
38,405
def _classname(class_): """Returns the full name for a class. Has option for overriding some class names to hide internal details. The overrides are stored in the `_class_aliases` dictionaries. """ rawname = "{}.{}".format(class_.__module__, class_.__name__) if rawname in _class_aliases: ...
ca1e7f66646e5e9dfa3b8ddb4749ebf45dc0f17a
38,406
def fracsimplify(numerator, denominator): """ Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction ...
9f1decc8d9021ea988f6eb28342da8ecc2ceb607
38,407
def polar_adjust_scale(lon, lat, s=1): """Rescale lon, lat by contracting or expanding from the north pole. This is necessary to compensate for the not quite complete coverage of the projection For the test PufferSphere, s=0.833 is a good compensation s sets the scaling factor. """ r = (np.pi/2...
2c294430bc62dfd06ebfcc1d5b5d81d12d08dd8e
38,408
def process_jobs_output(final_df): """ preprocess the dataframe before creating pdf :param final_df: final dataframe :type final_df: pandas.DataFrame :return: processed dataframe """ output_df = final_df.copy() output_df['job_title'] = np.where(output_df['job_title'].str.len() > 30, o...
d833af76ebe05a856c567e47ef7411e116d2cae1
38,409
def _vector2xy(v, pole): """Return stereographic coordinates (X, Y) of 3D unit vectors. (X, Y) is both zero for vectors with z equal to the projection pole. Parameters ---------- v : Vector3d If it's not a unit vector, it will be made into one. pole : int -1 or 1, where -1 (1) ...
c1df4ddd024ffa4d4ba457ece365f015eadfa3f8
38,411
def defer_group_class(node: c.SchemaNode, kw: dict) -> t.Type[IGroupModel]: """Colander helper deferred to assign the current group model. :param node: Colander SchemaNode :param kw: Keyword arguments. :return: IGroupModel """ request = kw.get("request") assert request, "To use this widget ...
59c5da9d2f9c0f79125cd1fa26d242f0dc897a63
38,413
async def search_roles_count(conn, search_query): """Get a count of all search fields for roles in one query.""" resource = ( await roles_search_name(search_query) .union(roles_search_description(search_query)) .distinct() .count() .run(conn) ) return resource
ba43e3c38f28bb9bc10ac757e6b5d2c0cabbfbdb
38,414
def get_db_engine() -> Engine: """ Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, "dbengine"): engine = create_engine(application.config["SQLALCHEMY_DATABASE_URI"], echo=ENV_LOG_FLAG) engine.connect() g.dbengine...
844bce3fc30bc4a3c77a27934107d20d597ae793
38,416
def get_subset(container, subset_bounds): """Returns a subset of the given list with respect to the list of bounds""" subset = [] for bound in subset_bounds: subset += container[bound[0]: bound[1]] return subset
4932ecba987c4936f9f467f270c6c07fd8681840
38,417
def _encode_decimal128(name, value, dummy0, dummy1): """Encode bson.decimal128.Decimal128.""" return b"\x13" + name + value.bid
f0d72f1fdef51559eb66dd2ac65ba6a43a91bf85
38,418