content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_walrus(s3_url): """ Return True if it's Walrus endpoint, not S3 We assume anything other than *.amazonaws.com is Walrus""" if s3_url is not None: o = urlparse(s3_url) return not o.netloc.endswith('amazonaws.com') else: return False
193eca73a1e3031f3511bb53434b2fc75a5e2066
3,616,000
def word_search(tree, string=''): """ Exercise 2: Implement a word search using either DFS or BFS. Why did you choose one algorithm or the other? """ if tree is None: return [] string += tree.value results = [] if is_word(string): results.append(string) results += ...
11f4a5c67b6084a96d536492df77f1e8f2ddae06
3,616,001
import requests import json def getNameFromAdcode(adcode): """ 根据adcode(行政区编码)获取下级行政区名称 :param adcode: :return: {'name': ['北京市'], 'sub': ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区']} """ ur...
62a924208f4d1d997d09cbf43747a5d367adceff
3,616,002
def _process_entity(request, name, param_parser, key_translations): """Procesa una request GET o POST para consultar datos de una entidad. En caso de ocurrir un error de parseo, se retorna una respuesta HTTP 400. En caso de ocurrir un error interno, se retorna una respuesta HTTP 500. Args: requ...
a4e048f88fde2058e6f1c5904cb0b623993b3c4e
3,616,003
def compute_mean_sem(df, key='fold_change'): """ Computes the mean and standard error of the fold-change given a grouped pandas Series. """ # Compute the properties mean_val = df[key].mean() sem_val = df[key].std() / np.sqrt(len(df)) # Assemble the new pandas series and return. samp...
ec628f966b2fe5d43261c37e44408d7a22fc6583
3,616,004
from netpyne import sim from netpyne.analysis import network from bokeh.plotting import figure, show from bokeh.transform import linear_cmap from bokeh.palettes import Viridis256 from bokeh.models import ColorBar from bokeh.embed import file_html from bokeh.resources import CDN from bokeh.layouts import layout from bok...
76c61788abd7593930850439c34671439560b5b8
3,616,005
def main() -> int: """ Handle program invocation. :returns: Exit code. """ logger.info('Initialising Database Connection') db = ed_bgs.Database(config['database']['url'], logger) ebgs = ed_bgs.EliteBGS(logger, db) # return None # Looping over monitored factions for f in config['monitor_factions']:...
bb95137f110cd7fcb8acec2824e07310350d1d46
3,616,006
import xmlrpc def stop_vm(client, session, vm, params): """Stop an existing virtual machine. It will fail if the virtual machine does not exist.""" if vm['state'] is None: return { 'failed': True, 'msg': NOT_EXISTS_ERR } if vm['state'] in ('hold', 'stopped'): return { 'changed': False,...
39a04448f645c337f876a4d48edb8cb4c3cbbfbb
3,616,007
import torch def accuracy(predictions, labels): """ Evaluate accuracy from model predictions against ground truth labels. """ ind = torch.argmax(predictions, 1) # provide labels only for samples, where prediction is available (during the training, not every samples prediction is returned for effic...
484ba64b2239363daddd206e747f6c1456e236c9
3,616,008
def _quick_reap(): """Reaps a task.""" data = _gen_request_data( properties=dict(dimensions={u'OS': u'Windows-3.1.1'})) request = task_request.make_request(data) _result_summary = task_scheduler.schedule_request(request) reaped_request, run_result = task_scheduler.bot_reap_task( {'OS': 'Windows-3....
54e3c1793a2394ec97158e277fb803b7466fc150
3,616,009
from klab.bio.basics import residue_type_3to1_map def read_and_calculate(workspace, pdb_paths): """ Calculate a variety of score and distance metrics for the given structures. """ # Parse the given restraints file. The restraints definitions are used to # calculate the "restraint_dist" metric, w...
568d9647200ee40868421c7e8a957213e045ebad
3,616,010
from typing import Callable def closure(func: Callable) -> Callable: """Wrap a method to eliminate the self keyword from its signature.""" # tried using @functools.wraps, but could not get it to work right def wrapped(*args, **kwargs): self = args[0] if len(args) > 1: args = a...
79eaac9fc3f4df2cee66c444fef5f8feff18e5bb
3,616,011
def dynamic_stub(end, group, cardinalities, pool): """Creates an face.DynamicStub. Args: end: A base.End. group: The group identifier for all RPCs to be made with the created face.DynamicStub. cardinalities: A dict from method identifier to cardinality.Cardinality value identifying the card...
4f5e0660323071d8bff85fbaa0ebb9bcb837097b
3,616,012
def get_issns_for_journal(nlm_id): """Get a list of the ISSN numbers for a journal given its NLM ID. Structure of the XML output returned by the NLM Catalog query:: NLMCatalogRecordSet NLMCatalogRecord NlmUniqueID DateCreated DateRevised DateAu...
3c490d29066d6218ed21b72fd3f010c9ac7ca4d5
3,616,013
def encode(lng, lat, precision=10, bits_per_char=6): """Encode a lng/lat position as a geohash using a hilbert curve This function encodes a lng/lat coordinate to a geohash of length `precision` on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits per character (allowed are 2...
090bffcd46ff26c2428e1fcfc1537da584f63196
3,616,014
def filter_form(context, *args, **kwargs): """Тег представления filter form как таблицы. """ filter_form = (args[0] if len(args) > 0 else kwargs.get('filter')) if not filter_form: filter_form = context.get('filter') if filter_form is None: raise TemplateSyntaxErr...
50526302a9ea7d08e8818c92a68715313be4591b
3,616,015
def test_lr_monitor_multi_lrs(tmpdir, logging_interval: str): """ Test that learning rates are extracted and logged for multi lr schedulers. """ tutils.reset_seed() class CustomBoringModel(BoringModel): def training_step(self, batch, batch_idx, optimizer_idx): return super().training_s...
51e60dfaf745a0dedb6e492828daa7f0f6942839
3,616,016
def non_max_suppression_bbox(bboxes, confidences, img_size, verbose=False): """ high confidence detections suppress all overlapping detections (including detections at other scales). Detections can partially overlap, but the center of one detection can not be within another detection. :param bboxes: Nx4 nump...
fc80d4e039a5658ba23cbc95c7e32297e71ff081
3,616,017
def inet_ntoa(i): """Convert an int to dotted quad.""" return '.'.join(map(str, [(i >> (3-j)*8) & 0xff for j in range(4)]))
b83a6b08118bcd7858cb588f53b71daaf31d358e
3,616,018
def cleanup_string(string): """ >>> cleanup_string(u', Road - ') u'road' >>> cleanup_string(u',Lighting - ') u'lighting' >>> cleanup_string(u', Length - ') u'length' >>> cleanup_string(None) '' >>> cleanup_string(' LIT ..') 'lit' >>> cleanup_string('poor.') 'poor' ...
5f9a369a52b798ff8c26bea56fbfe585b3612db0
3,616,019
import os import glob def dem_mosaic_custom(output_directory, verbose=False, print_asp_call=False): """ Function to run ASP dem_mosaic. """ output_file = os.path.join(output_directory,'mosaic.tif') stereo_output_directory = os.path.join(output_direc...
d82cf1197a65810febe027315def37aa93255c6e
3,616,020
def termConvection(t, y, schemeData): """ termConvection: approximate a convective term in an HJ PDE with upwinding. [ ydot, stepBound, schemeData ] = termConvection(t, y, schemeData) Computes an approximation of motion by a constant velocity field V(x,t) for a Hamilton-Jacobi PDE (often calle...
6954cef17beb6d1278dddfaf2ac3537efe42cf78
3,616,021
def is_field_allowed(name, field_filter=None): """ Check is field name is eligible for being split. For example, '__str__' is not, but 'related__field' is. """ if field_filter in ["year", "month", "week", "day", "hour", "minute", "second"]: return False return isinstance(name, s...
8be38b79bab3aeb49219155db0159cc143c38111
3,616,022
def build(help: dict) -> str: """Returns the formatted help string. See the GitHub page for info.""" global _cust_config final_str = "" terms = help["terms"] if "config" in help: _cust_config = help["config"] else: _cust_config = {} # Terms for term in terms: if...
2c7c89afed8b2e8dbbed49a2edcfadaf69ae4fa8
3,616,023
import logging def setup_logger(level): """ Setup a logger for the REST handler """ logger = logging.getLogger('splunk.appserver.lookup_editor.rest_handler') logger.propagate = False # Prevent the log messages from being duplicated in the python.log file logger.setLevel(level) log_file_p...
4d0dff0da93d0a32520ebae1c0eaacde284ec179
3,616,024
from django.contrib.contenttypes import models from django.contrib.auth import models as auth_models def _makePermission(perm, model, app_label='editorialmanager'): """ Retrieves a Permission according to the given model and app_label. """ ct = models.ContentType.objects.get(model=model, app_label=ap...
a2219855a89aab4426a1597632dece89b8aa5afc
3,616,025
def greater_equal(lhs, rhs): """Broadcasted elementwise test for (lhs >= rhs). Parameters ---------- lhs : relay.Expr The left hand side input data rhs : relay.Expr The right hand side input data Returns ------- result : relay.Expr The computed result. """ ...
5b9eeab5fb9323a96895c3009cf15f947cb57910
3,616,026
from typing import List from typing import Optional from typing import Dict def mergeVotingResult(vote: List[int], policevote: Optional[int] = None) -> Dict[int, float]: """ Count the vote result and the return the candidates with most votes ### Parameter - vote: `List[int]`, the vote result ##...
38649fc4e1c80d31375cce920b39387fd533b0b0
3,616,027
import zipfile import os def _create_dummy_zip_file(): """ This function creates a dummy zip file and returns a path to the file """ text_file_path = _create_temp_file() zip_file_path = _create_temp_file() with zipfile.ZipFile(zip_file_path, "w") as zip_file: zip_file.write(text_file_...
4626b9d4f281f3ab9feab518486594d8604c9d7d
3,616,028
def get_avatar(burl, height): """ xxx """ return_data = '' uid = user_get_uid() avatar_id = 0 connection = pymysql.connect(host=DB_SRV, user=DB_USR, password=DB_PWD, db=DB_NAME, ...
1cbbcd31adffb4c5c0d60a803ef65b793cf5cd40
3,616,029
def signup(): """ Presents an anonymous user with the registration form and adds their info to the database. Uses user.set_password() to hash their password (instead of storing it plaintext). """ if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm...
76a9f449162f7bd1131ffab9e551f31529431f69
3,616,030
def read_bdf(iterable): """ Read a BDF-format font from the given source. iterable should be an iterable that yields a string for each line of the BDF file - for example, a list of strings, or a file-like object. """ name = "" pointSize = 0.0 resX = 0 resY = 0 comments = [] font = None for line in iterabl...
cb0ae7f28060e702317184ae93d538bd10c1a77c
3,616,031
def parallel_apply(df, group_list, f, num_cores, print_every_n=1000, **kwargs): """ A lightweight version of apply using the multiprocess library :param df: the pandas dataframe that needs to be grouped :param group_list: a list of variable names to group by :param f: the function that operates on ...
d14e3d8a354121abf0dfe193eb1cfa2af89d65bd
3,616,032
import requests import socket def _do_generate_runner(endpoint): """ Get the hostname or IP of the runner. Will try to get the public host name from AWS metadata first, then from reverse lookup, and then fall back to using the local hostname :return: An ip address or a hostname :rtype: str ...
0d2f62f393270f12763e0635df38e6bf2e6c596b
3,616,033
def vectorized_is_element(array, choices): """ Check if each element of ``array`` is in choices. Parameters ---------- array : np.ndarray choices : object Object implementing __contains__. Returns ------- was_element : np.ndarray[bool] Array indicating whether each ...
03818826ea0d7a9bf48a6bfce204f591c96dea58
3,616,034
def what_am_I_from_prob(probabilities, no_of_guesses=5, true_class='', verbose=True): """Function to classify based on 'prob'ability layer inputs probabilities: a vector of input probabilities no_of_guesses: how many of the top probabilities do you want? true_class: the real class name if known outp...
f30692ea00d00dfb12c217751e18f40fde80a7a6
3,616,035
import typing def _parse_term_from_lists( term_list: typing.List, networks: NetworkStore = None ) -> Term: """Term is a list where the first element is either a valid functor or the keyword 'list'. If the first element is list, then this term is a list, we parse recursively all its elements and return the...
7d2bd73d4f63105e627613c47cea4a21c80ad5ff
3,616,036
def create_urine_features(charts): """ features of urine color and appearance""" res = charts.loc[charts.label.str.lower().str.contains('urine', na=False), ['hadm_id', 'eventtime', 'admittime', 'label', 'value', 'valuenum', 'unitname']] # clean the label column res['labe...
379a4707f5a773375e5f289287dd2cc0f4df2c60
3,616,037
def merge_user_settings(settings): """Return the default linter settings merged with the user's settings.""" user = settings.get('user', {}) default = settings.get('default', {}) if user: tooltip_styles = default.get('tooltip_styles', {}) user_tooltip_styles = user.get('tooltip_styles',...
969457f907d8431c9af6ef8a1b587575cb3ba681
3,616,038
def RSRS1(dataFame, Sbuy=1.0, Ssell=0.8): """斜率指标交易策略 """ data = dataFame.copy() data['flag'] = 0 # 买卖标记 data['position'] = 0 # 持仓标记 position = 0 # 是否持仓,持仓:1,不持仓:0 for i in range(1, data.shape[0] - 1): # 开仓 if data.loc[i, 'beta'] > Sbuy and position == 0: data...
a57d6199828b765ceb70d25fc61c4cc559a05580
3,616,039
from typing import Optional from typing import Dict import os def true_color_supported(env: Optional[Dict[str, str]] = None) -> bool: """Check if truecolor is supported by the current tty. Note: this currently only checks to see if COLORTERM contains one of the following enumerated case-sensitive v...
dc69282c90b57bec6ad2eb348ca6c327aacb5426
3,616,040
def rgb2gray(rgb): """ Change RGB color image into grayscale in RGB representation using colorimetric (perceptual luminance-preserving) conversion :param rgb: NumPy array of the RGB image :return: NumPy array of grayscale image, same shape as input """ r, g, b = rgb[:, :, 0]/255, rgb[:, :, 1]/2...
3c0b3a4ad1b2057b2b793569e629d36d7be27f7f
3,616,041
import wave def get_speech_features_from_file(filename, num_features, pad_to=8, features_type='spectrogram', window_size=20e-3, window_stride=10e-3,...
bdb92866fa4014c9a1831e1138d1358a8b4d36c5
3,616,042
def health() -> dict: """ Root Get """ health = schemas.Health( name=settings.PROJECT_NAME, api_version=__version__, model_version=model_version ) return health.dict()
65b059e44f929886576e9c181ffd8b3b785f17ba
3,616,043
import copy def site_response(sp, asig, linear=0, freqs=(0.5, 10), xi=0.03): """ Run seismic analysis of a soil profile - example based on: http://opensees.berkeley.edu/wiki/index.php/Site_Response_Analysis_of_a_Layered_Soil_Column_(Total_Stress_Analysis) Parameters ---------- sp: sfsimodels....
5cbbf8b980156ca579135620c81592950f6b7b41
3,616,044
import os from dateutil import tz def calling(data): """Main function to parallelize peak calling.""" method = dd.get_chip_method(data) caller_fn = get_callers()[data["peak_fn"]] if method == "chip": chip_bam = data.get("work_bam") input_bam = data.get("work_bam_input", None) n...
5476dc8c7d7ef3f032d3fd86fa83967cff145d08
3,616,045
def _try_community_name(row): """ Try to get community name from municipality description in other tables. TODO: reverse geocode these instead? """ return row["MUNICIPALITY"].split("/")[0].replace(" Area", "")
fdf78794d65265e7951911125ae01d61ff1440f8
3,616,046
from typing import Tuple def _get_field_names( schema_field_details: Tuple[Tuple[str, DataType], ...], ) -> Tuple[str, ...]: """Returns field names from schema fields.""" return tuple(field[0] for field in schema_field_details)
9e985b0a2619c24004e35f1ead6912a6fad91769
3,616,047
def strip_outer_matching_chars(s, outer_char): """ If a string has the same characters wrapped around it, remove them. Make sure the pair match. """ s = s.strip() if (s[0] == s[-1]) and s.startswith(outer_char): return s[1:-1] return s
b55d1f966a8b216dce2d4817117f350f639b9b83
3,616,048
import sys def ParseAndUnwrap(code, dumptree=False): """Produces unwrapped lines from the given code. Parses the code into a tree, performs comment splicing and runs the unwrapper. Arguments: code: code to parse as a string dumptree: if True, the parsed pytree (after comment splicing) is dumped ...
472af88a178e9bfe8d10103b4ab5cff7b4c41113
3,616,049
def lr_schedule(step): """Linear scaling rule optimized for 90 epochs.""" steps_per_epoch = 30000 // FLAGS.batch_size current_epoch = step / steps_per_epoch # type: float lr = (1.0 * FLAGS.batch_size) / 32 boundaries = jnp.array((20, 40, 60)) * steps_per_epoch values = jnp.array([1., 0.1, 0.01, 0.001]) * ...
f0579c77084e1092fc09b7a236b4bf4f848fc1cf
3,616,050
def make_chunks(infos, **kwargs): """Generate chunks from note infos""" return s.chunked(make_sound(infos, **kwargs))
1dc4ab1bccc3ed83e008efc45731df4cc532ad99
3,616,051
import sys def get_sentence(lower=True): """Simple function to prompt user for input and return it w/o newline. Frequently used in chat sessions, of course. """ sys.stdout.write("Human: ") sys.stdout.flush() sentence = input() if lower: return sentence.lower() return sentence
8e0ae0591bace7da27dc0d044272793fd397276a
3,616,052
from pathlib import Path def plot_traces_by_qu_unexp_sess(analyspar, sesspar, stimpar, extrapar, quantpar, sess_info, trace_stats, figpar=None, savedir=None, modif=False): """ plot_traces_by_qu_unexp_sess(analyspar, sesspar, stimpar, extrapar, ...
7a1bfcf03b4468b58eff8d842ec82c5a508479db
3,616,053
def to_cartesian(p, direction=1, axis='z'): """ Converts a point given in (r, theta, z) coordinates to cartesian coordinate system. optionally, axis can be aligned with either cartesian axis x* or z and rotation sense can be inverted with direction=-1 *when axis is 'x': theta goes from 0 at y-axis...
9f171da66e66b1f7a580f0f22d9b5bc7c970cd95
3,616,054
def getLimits(locations, current, sortResults=True, verbose=False): """ Find the projections for each delta in the list of locations, relative to the current location. Return only the dimensions that are relevant for current. """ limit = {} for l in locations: a, b = current.comm...
b8c62aecc2ce37fcaefd63544bd64ccba94f257b
3,616,055
def mclag_ka_session_dep_check(ka, session_tmout): """Check if the MCLAG Keepalive timer and session timeout values are multiples of each other and keepalive is < session timeout value """ if not session_tmout >= ( 3 * ka): return False, "MCLAG Keepalive:{} Session_timeout:{} values not satisfying ...
3f3fd6a12711c0c290cdb0fbd68cfd1c743ef515
3,616,056
import struct def pack(fmt, *args): """pack() is wrapper of struct.pack """ value = struct.pack(fmt, *args) result = [] if isinstance(value, str): # For Python2 for v in value: result.append(ord(v)) return result elif isinstance(value, bytes): # F...
a9e4349debf9d9d9e088e8c02a9fc044b9a1897b
3,616,057
def get_teacher_information(gid): """ Retrieve the team information for all teams in a group. Args: gid: the group id Returns: A list of team information """ group = get_group(gid=gid) member_information = [] for tid in group["teachers"]: team_information = api....
c140fc2718f7bef1dd1367fd187b048e31304dfc
3,616,058
def needs_owner(func): """Decorator to require the owner for the given function.""" @wraps(func) def decorated_function(*args, **kwargs): if args[0].chat.id != SETTINGS['owner']: bot.reply_to(args[0], 'Sorry, you are not the owner of this bot') return return func(*ar...
7cbecfb5901b0cab362f30017c615baac1dd9c57
3,616,059
def decompose_to_device(operation: cirq.Operation, atol: float = 1e-8) -> cirq.OP_TREE: """Decompose operation to ionq native operations. Merges single qubit operations and decomposes two qubit operations into CZ gates. Args: operation: `cirq.Operation` to decompose. atol: absolute er...
f0b78287d44922482f81f59c1d8a202cf36167d3
3,616,060
def lucas(n): """ compute the nth Lucas number """ a, b = 2, 1 # notice that all I had to change from fib were these values? if n == 0: return a for _ in range(n - 1): a, b = b, a + b return b
9d9404edf59690cafc49ba70d7dc776376d1f020
3,616,061
def do_map_eval(B, S, param, O, W = None, BGp = None): """ This function evaluate the target function given a output window set. Args: B: . S: . param: . O: . W: . BGp: . Returns: statTmp: . """ statTmp = {} statTmp['W'] = np.array([]) statTmp['Xp'] =...
1cf7ced27aac09a996b359936b28ad00b0fb7527
3,616,062
def transform_disturbances(draws, shocks_mean, shocks_cholesky): """Transform the standard normal deviates to the relevant distribution.""" draws_transformed = draws.dot(shocks_cholesky.T) draws_transformed += shocks_mean draws_transformed[:, :2] = np.clip( np.exp(draws_transformed[:, :2]), 0....
532096f3710ebcf7259dfa8641152efc98db1660
3,616,063
import torch def predict_one_scan_binary_class(rescaled_array, direction, checkpoint_path, array_info, batch_size=16, evaluate=False): """ :param array_info: stores information of the rescaled_array :param rescaled_array: float32 array in shape [512, 512, 512, data_channel + enhanced_channel + semantic_ch...
4b7fb388a1b557c4f2c13eeeea24989cfe9c29a2
3,616,064
def shuffle_batch(labeled_tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, min_after_dequeue=0, seed=None, allow_smaller_final_batch=False, name=None): ""...
923f16f93e9107e8b2969c084751fb78e8f177fe
3,616,065
from typing import Tuple from typing import Union def natural_keys(text: str) -> Tuple[Union[int, str], ...]: """ alist.sort(key=natural_keys) sorts in human order :see: http://nedbatchelder.com/blog/200712/human_sorting.html :see: http://stackoverflow.com/a/5967539/1391325 """ return tuple(__atoi(c) for c in ...
d8c902ee7ee06fa33001e75f2c0fb87d83126175
3,616,066
def return_dict_of_attrs(obj): """ Returns dictionary of attributes of object that are not private or None, and which top namespace is not sqlalchemy or wpipe. Parameters ---------- obj Input object. Returns ------- attrs : dict Dictionary of attributes of obj. ...
465abfd8ebb19d8dbfd5d8e6dd7cbb9099ad0b36
3,616,067
def BenefitSurg(t): """Surgery benefits""" return SizeBenefitSurg(t) * PolsSurg(t)
3376ae734d92b00b0bbb4ec6246e533f00bc88ce
3,616,068
def _get_edge_attrs(edge_attrs, concat_qualifiers): """ get edge attrs, returns for qualifiers always a list """ attrs = dict() if "qualifiers" not in edge_attrs: attrs["qualifiers"] = [] elif edge_attrs["qualifiers"] is None: attrs["qualifiers"] = edge_attrs["qualifiers"] if at...
8500ae7c606041071264d980155fbada98ba870e
3,616,069
def destroy_raid_bdev(client, name): """Destroy pooled device Args: name: raid bdev name Returns: None """ params = {'name': name} return client.call('destroy_raid_bdev', params)
ef377fc024cd326ef3e496ffc94b10ef2076e1e2
3,616,070
def get_closest_point_index(pt, pts): """ Closest point index of the pts from pt. """ distances = [rs.Distance(p, pt) for p in pts] min_index = distances.index(min(distances)) return min_index
5df14d648ead10e694323785625aa842a1ddd1ff
3,616,071
def IFS(FS, T0=2 * np.pi, m_start=-4, m_stop=4, x_min=0, x_max=2 * np.pi, x_num=10): """Function to reconstruct (or check) the periodic function from the obtained Fourier coefficients""" m = np.arange(m_start, m_stop + 1) m = np.reshape(m, (-1, m.size)) M = np.tile(m, (x_num, 1)) x = np.linspa...
466a4e2c967ebda2a8a0ae6804b4427d695c3928
3,616,072
def get_calendar(username, base_url='https://github.com/'): """retrieves the github commit calendar data for a username""" base_url = base_url + 'users/' + username try: url = base_url + '/contributions' page = urllib2.urlopen(url) except (urllib2.HTTPError,urllib2.URLError) as e...
d4c40371ed208046e97e79d92fb97c5a8e60c463
3,616,073
def stop_comm_msg_create(pid: int, ts: float) -> message.Message: """ create a message to stop the comm_handler :param pid: agent pid :type pid: int :param ts: timestamp :type ts: float :return: stop communication handler message :rtype: Message """ return message.Message(pid,...
c9d7c6361f276c1b8d54402aad713b05f17044ac
3,616,074
def _normalize_data(data): """Turn entities in properties into entity ids""" entities = data['layout']['entities'] for obj in entities: schema = model.get(obj.get('schema')) if schema is None: raise InvalidData("Invalid schema %s" % obj.get('schema')) properties = obj.get...
ff5f7de484f1483cc6ce2399d464d73724d3d8ee
3,616,075
def conv2D_generative(inputs, filters, kernel_size=(1, 1), padding="same", activation=None, reuse=False, name="conv2D", strides=(1, 1), dilation_rate=(1, 1), use_bias=True, mask=None, bias_init=0. ): """ 2D...
515915d47c3715ccb60de909e07e10ed65fa60dd
3,616,076
def FlattenList(list): """Flattens a list of lists.""" return [item for sublist in list for item in sublist]
5ab33bd326d221449f9efc0da7ffa39eeedd3add
3,616,077
def _build_state_value(django_request, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Meant to be similar to oauth2client.appengine._build_state_value. A...
4434c025065124f942f436ecf88f383d7cfe6c43
3,616,078
import sh def commit(experiment_name, time): """ Try to commit repo exactly as it is when starting the experiment for reproducibility. """ try: sh.git.commit('-a', m=f'"auto commit tracked ' f'files for new experiment: ' ...
b62a32ddae3c53ce16f2931356493b683fa8794c
3,616,079
import numpy def angd2vec2d(ang: float) -> numpy.array: """Convert angle in degrees to a 2-d unit vector in the x-y plane.""" return ang2vecd(ang)[:2]
03b9ff6f569a1745d6b7a3fb125e92b3eabc95b2
3,616,080
def pair_align(a, b): """ Accurate Registration. :param a: Point cloud for previous frame. :param b: Point cloud for current frame. :return: The matrix. """ x = 0 return x
033515d87b900a7790c4a461409138d420aa164d
3,616,081
async def battery(request): """GET /api/battery cf. https://docs.mistyrobotics.com/misty-ii/rest-api/api-reference/#getbatterylevel """ return web.json_response({ 'status': 'Success', 'result': generate_batterylevel(), })
e1e404ca3cbae05bcf9db0e982fb906197edd05f
3,616,082
def refresh_auth(action): """ Uses the 'Authorization' block in the request header to return a fresh token for a user. """ # first, drop GETs trying to do a refresh: we don't play that shit if action == 'refresh' and flask.request.method == 'GET': return utils.http_405 setattr(flask.reques...
375ac68493ec725245647b252819cb7a295c4f48
3,616,083
from typing import Iterable from typing import Type from typing import Union def apply_noise_to_gates( circuit: Circuit, noise: Iterable[Type[Noise]], target_gates: Union[Iterable[Type[Gate]], np.ndarray], target_qubits: QubitSet, ) -> Circuit: """Apply noise after target gates in target qubits. ...
1299ce4eaa2ad8f5993767d41883d44af1855ee4
3,616,084
def load_info(path = defaults._default_info_path, verbose = False): """ :param path: :param verbose: :return: """ if verbose: print(path) i = classes.InfoClass() i.load(path) return i
582c17e473267b0124ac09a79c0cb9bc9fa9f97a
3,616,085
from typing import Dict from typing import Any async def attach_user(db, document: Dict[str, Any]) -> Dict[str, Any]: """ Attach more complete user data to a document with a `user.id` field. :param db: the application database client :param document: a document to attach user data to :return: a d...
9e2e8a8909f595daab28de5c63352ab3501452ce
3,616,086
import numbers def mlevel(level): """Convert level name/int to log level. Borrowed from celery, with <3""" if level and not isinstance(level, numbers.Integral): return LOG_LEVELS[level.upper()] return level
143f5f4610034d372a55a8a6c1a8c7f4e3ee6a0e
3,616,087
import os def get_size_checksum_dict(path: str) -> dict: """Compute the file size and the sha256 checksum of a file""" m = sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): m.update(chunk) return {"num_bytes": os.path.getsize(path), "checksum": m...
b2cf637512b18b7c84bdf1d821b645ed55e5cf82
3,616,088
import logging import os from pathlib import Path def split( mapfile_df, output_dir=None, output_filename="split_train_dev.csv", params_filepath="params.yaml", ): """Accept a Pandas DataFrame with image filenames and labels, split into train, test, and dev sets and save file. Modify the n...
be930bc1b9cf17488e7af698c9d2ae6bb8624dd9
3,616,089
from datetime import datetime from typing import Dict from typing import Any def get_legislation_introduced_since(since_date: datetime) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/legislationservice.asmx?op=GetLegislationIntroducedSince""" argdict: Dict[str, Any] = dict(sinceDate=since_date) ...
1d6cb1d0eb1fa01c4305dca422b7fdb22ac18520
3,616,090
def generate_core_tsv(): """output a list of the core ili concepts ToDO: sort by frequency""" tsv="""# ili_id\n""" core_ss, core_ili = fetch_core() for ili in core_ili: tsv += "i{}\n".format(ili) return Response(tsv, mimetype='text/tab-separated-values')
0c27e2af478fc9e53f87f960446856169113c1d1
3,616,091
import io def extern(decorated): """ A decorator gadget that generates a Rust extern {} block Usage: properties.name = "my::rust::extern" @extern function(generator, outfile, ...): outfile.write("contents inside generated extern block") Generates: extern ...
d42470dd962c2b92e03b199872726b10b0a8f7d7
3,616,092
def make_exp_vocab(exp_dic): """ Returns a dictionary that maps words to indices. """ exp_vdict = {'<EOS>': 0} exp_vdict[''] = 1 exp_id = 2 for qid in exp_dic.keys(): exp_strings = exp_dic[qid] for exp_str in exp_strings: exp_list = ActivityDataProvider.seq_to_lis...
a496f4bf0e5ef2692f7f904e9dd4c905dc2e7826
3,616,093
def load_frames(folder_name, offset=0, desired_fps=3, max_frames=40): """ :param folder_name: Filename with a gif :param offset: How many frames into the gif we want to start at :param desired_fps: How many fps we'll sample from the image :return: [T, h, w, 3] GIF """ coll = ImageCollection(...
46c41f393cfc73581ef89ba0d4204f0a96a8b303
3,616,094
from typing import Tuple from typing import Union def _verify_data_shape(data, shape, path=None) -> Tuple[bool, Union[str, None]]: """ _verify_data_shape( {'data': []}, {'data': list} ) == (True, None) _verify_data_shape( {'data': ''}, {'data': list} ) == (False, '.data') ...
3e76362938146972d96e34a22373b43dca23381b
3,616,095
def MultipleComparisons(trends, kys, aplha = 0.10, MCmethod="fdr_by"): """ Takes the results of an existing trend detection aproach and modifies them to account for multiple comparisons. args trends: list list of numpy arrays containing results of trend analysis kys: list list of what is in results y...
9c4a74c9ffe319b3a4058a9252ff5f64de71d048
3,616,096
import os from clinicaml.utils.filemanip import get_subject_id from clinicaml.utils.freesurfer import check_flags from clinicaml.utils.ux import print_begin_image def init_input_node(t1w, recon_all_args, output_dir): """Initialize the pipeline. This function will: - Extract <image_id> (e.g. sub-CLNC0...
280c7c6875ee3db8d954383aa37b3d5f298e0cd7
3,616,097
def view_questions_default_page(): """View all tests, for default test page""" questions = Question.select() return questions
8fdf5849bd9536d076f6ffc7f6aa9cc65eb61685
3,616,098
import tempfile import os import tarfile def get_tarinfo(path): """Gets the `TarInfo` object for the file at the specified path. This contains useful information such as the owner and the group. @param path: The path. @type path: str @return: The info for that path @rtype: tarfile.TarInfo ...
365d978083c494bf76c518eeb0fecc8f06d32a0a
3,616,099