content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def pending(): """ Display pending reviews. These are reviews that were submitted, but the user hasn’t responded to the confirmation email yet. They are automatically purged after 24 hours. """ if app_unavailable(): return render_template('app_unavailable.html', result=Markup(get_rea...
fa5d6ae7cc721b98bc95ad8f3eaa4832ae47dca7
41,400
def format_directory_path(path: str) -> str: """Replaces windows style path seperators to forward-slashes and adds another slash to the end of the string. """ if path == ".": return path formatted_path = path.replace('\\', '/') if formatted_path[-1] is not '/': formatted_path += ...
0daa0cc65e50bd29c76da64d302c0e01c1bb333b
41,401
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. ...
f6abd2617cb9466932aa4fdeb592971fbafb068f
41,402
def voter_count_doc_view(request): """ Show documentation about voterCount """ url_root = WE_VOTE_SERVER_ROOT_URL template_values = voter_count_doc.voter_count_doc_template_values(url_root) return render(request, 'apis_v1/api_doc_page.html', template_values)
f1ada03285333982f1b2ce219788097da0468be8
41,403
import os def plot_histogram(hist, width=0.9, title='', xlabel=None, datetime_format="%b %Y", labels=None, color=None, alpha=None, normalize=True, percent=False, padding=0.03, num_labels=24, formatter=None, ylabel_precision=2, resolution=3, f...
1e4719008a1d56d3b8019702d844190b397d6fc4
41,404
import os def find_file_in_path(filename): """ Finds |filename| by searching the environment paths """ path_delimiter = ';' if is_windows else ':' for env_path in os.environ['PATH'].split(path_delimiter): full_path = os.path.join(env_path, filename) if os.path.isfile(full_path): ...
6a3b9ca8f602609a790ffc6dc1f02e6064507c0a
41,405
from scipy.linalg import solve_banded, solve def __lobatto__(alpha,beta,xl1,xl2): """ Compute the Lobatto nodes and weights with the preassigned node xl1,xl2 Inputs: alpha - recursion coefficients beta - recursion coefficients xl1 - assigned node location xl2 - ass...
d4eddef75bc452e84606477547003ccb3bad1647
41,406
def create_account(fullname, username, password): """ Function for creating a new user account """ new_user = User(fullname, username, password) return new_user
627efda28257d1fa56d543cd6f4564ce78c3b043
41,407
def count_futures(*args, **kwargs): """ 计数 :param args: :param kwargs: :return: """ return db_instance.count(Futures, *args, **kwargs)
477159e89a4d1c2defdf0a77531ed31f40f8bc4a
41,408
def file_attribs_get(location): """Return mode, owner, and group for remote path. Return mode, owner, and group if remote path exists, 'None' otherwise. """ if file_exists(location): fs_check = run('stat %s %s' % (location, '--format="%a %U %G"')) (mode, owner, group) = fs_check.split(' ') return {'mode': mo...
0525b500b8d6762e74c1bbb71b9abbe5612f9586
41,409
from typing import Dict from typing import Any from typing import List def upsert_sql_from_field_value_dict(schema_table: SchemaTable, field_value_dict: Dict[Field, Any], conflict_field_list: List[Field]) -> sql.Composable: """ Takes a schema table, a dict mapping Fields t...
8364a305cbf349abdd5504c94cae62341a1dcf7a
41,410
def in_date(day, *dates): """check if day is in dates list or date :param day: date :param dates: list of dates or date :return: true if in, otherwise false """ the_date = int(int_date(day) % 100) return _in_range_or_equal(the_date, dates)
9dfb64bcec9d048718edbd0dcbb23e57ced8614e
41,411
def connect_to_server(): """ Connects to the IMAP server specified in Django's settings and returns the connection object. """ c = imapclient.IMAPClient(settings.TICKETUS_MAILGW_HOST, port=getattr(settings, 'TICKETUS_MAILGW_PORT', None), us...
3dec1a1c0a2df3c2b44b12712e33ec31fdc8bbe0
41,412
import numba def jit_filter1d_function(filter_function): """Decorator for use with scipy.ndimage.generic_filter1d.""" jitted_function = numba.jit(filter_function, nopython=True) @cfunc(intc(CPointer(float64), intp, CPointer(float64), intp, voidptr)) def wrapped(in_values_ptr, len_in, out_values_ptr, ...
b1cc2a563d92cd920daa24bf0bde54002a420227
41,413
import os def _mock_server_app(swagger_spec_path, mock_responses_path, custom_view_packages): """Create the WSGI application, post-fork.""" # Create a basic pyramid Configurator. config = Configurator(settings={ 'service_name': 'mobile_api_mock_server', 'pyramid_swagger.dereference_serve...
e33a7c6965c40fe7261ab848d1b4d3e484ff5117
41,414
def get_metagen_search_body(self): """ Get the MetaGenSearchView view body. Attributes ---------- measure: str the genomic measure label. gene: str the gene name. Returns ------- html: str the MetaGenSearchView view body. """ # Get parameters measure...
9b1e8c6072991765cf566f1bccccb38b178141a4
41,415
import websockets import itertools def parse_websocket_frame(s): """ May raise ParseException """ try: reqs = pp.OneOrMore( websockets.WebsocketFrame.expr() ).parseString( s, parseAll=True ) except pp.ParseException as v: rais...
8342936d84adf0893b34d6e7f41cc33657f3bea6
41,416
def csnap(df, fn=lambda x: x.shape, msg=None): """ Custom Help function to print things in method chaining. Will also print a message, which helps if you're printing a bunch of these, so that you know which csnap print happens at which point. Returns back the df to further use in chaining. ...
d37e6093834db7d17664387afe871bc8e1d78c0b
41,417
import logging def start_slideshow(): """ Starting the picture frame slideshow. This starts the independent background process. :return: success """ if not process_is_running.value: # Chaning the process value process_is_running.value = True # Creating the background p...
4dfe7ac916859288303cd1a4dabff82fa1acc714
41,418
def _toCamelCase(string): """Convert a snake case string (PyTorch) to camel case (PopART)""" words = string.split("_") return words[0] + "".join(w.capitalize() for w in words[1:])
f1f21b0313c03b3d63944ee3fcbd5e16b435da6d
41,419
from datetime import datetime import re def filter_by_dates(file_list, start_date, end_date, extra_filter=None): """filter files names in 'file_list' that belongs to creation dates betweeen [start_date, end_date) start_date and end_date are given as YYYY-MM-DD""" filtered_dates = list() sd = date...
f84c53aab73d133fd0d7a1e240256937ffab357a
41,420
from xpedite.dependencies import CONFIG import os def logPath(name=None): """ Returns the path of xpedite log directory :param name: Optional suffix for the log path (Default value = None) """ logpath = CONFIG.logDir if name: logpath = os.path.join(logpath, name) return logpath
ca8c3276bc362ab0ac720d9e2ca2e03789597801
41,421
def pulse(x): """Return the pulse fn of the input.""" return 2*(x % 1 < .5) -1
f54f73ab6656c0242508170c16ab6ee6a0cc5b92
41,422
def instance_update(instance): """ Call update method on spanner client. Note: A ValueError exception is thrown despite the client succeeding. So, we validate the node_count and instance_display_name parameters and then ignore the ValueError exception. :param instance: a Spanner instance objec...
9d3ec54c29f482dd1290daf26b4ebed9726279f7
41,423
def nastran_tube2(DIM1: float, DIM2: float, n: float, material: pre.Material = pre.DEFAULT_MATERIAL) -> Geometry: """Constructs a circular TUBE2 section with the center at the origin *(0, 0)*, with two parameters defining dimensions. See MSC Nastran documentation [1]_ for more details. Added by JohnDN90. ...
b264c6547dc9a348fe27c909fb3fce0c190f16db
41,424
def construct_bootstrap_and_latex_commands(ids, participants, rel_existing_path, static_paths, base_cmd_fmt, to_pdf_fmt): """Construct the commands to bootstrap results and latex generati...
9876078ddef82c66162a1056417569b45d9d772f
41,425
from django.contrib import auth from django.core.urlresolvers import reverse def login(request, next_page=None, required=False, gateway=False): """Forwards to CAS login URL or verifies CAS ticket""" if not next_page: next_page = _redirect_url(request) if request.user.is_authenticated(): r...
a7cbb1a3fa4f713c9cc39ef8b77feca813b05c85
41,426
import random import torch def compute_train_transform(seed=123456): """ This function returns a composition of data augmentations to a single training image. Complete the following lines. Hint: look at available functions in torchvision.transforms """ random.seed(seed) torch.random.manual_see...
165a2db29a7a42aecd3ce86128b67f64b1ec8a17
41,427
def index_singleton_clusters(clusters): """Replace cluster labels of -1 with ascending integers larger than the maximum cluster index. """ clusters = clusters.copy() filt = clusters == -1 n = clusters.max() clusters[filt] = range(n, n + len(filt)) return clusters
9cad0df27d2d99ef3a7478f3c3753cd7795beb54
41,428
def handler(event, context): """Dynamo resource""" machineTable = DynamoTable('Machines') return getMachineId(event, machineTable)
807647d225baddcfaade7b837401e4cf02dfc96f
41,429
def feature_df_to_1d(feature_df, chrom_len_s): """ Converts mulitindex feature_df (chrom,start) to single numeric index running trough all chromosomes. The column 'end' is also converted. See rod_to_1d for details. """ feature_df = feature_df.copy() feature_df.index.names = (feature_df....
34d94fa26adc399ba59020212500347a0c572f3a
41,430
def convert_wavelength_air2vacuum(wavelength_air): """ Convert air wavelength to vacuum wavelength Parameters ----------- wavelength_air: float Air wavelength in Angstroms Returns -------- float Vacuum wavelength in Angstroms """ sigma2 = (1e4/wavelength_air)**2....
919e2586c849fac9f126309ffe183160c9b3e546
41,431
def gaussian_blur(img, kernel_size=5): """Applies a Gaussian Noise kernel, blurring the original image""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
6613d73b6db4cf0c9cd87417a3a932d1babe3ced
41,432
def convolve_sep2(data, hx, hy, res_g=None, sub_blocks=None): """convolves 2d data with kernel h = outer(hx,hy) boundary conditions are clamping to edge. data is either np array or a gpu buffer (OCLArray) """ if isinstance(data, np.ndarray): data = np.ascontiguousarray(data) if s...
8ea0384c644c160ec31fdde5f158d2620cec801f
41,433
import os import time def print_log(info_type="", title="", info=""): """ :param info_type: 日志的等级 :param title: 日志的标题 :param info: 日志的信息 :return: """ if not os.path.exists(get_file_path("logs")): os.mkdir(get_file_path("logs/")) now = time.strftime("%Y-%m-%d %H:%M:%S", time.loc...
7e062c612bca1bb68034cd5d42040e6a5a526279
41,434
def gradebook_bulk_management_enabled(course_key): """ Returns whether bulk management features should be specially enabled for a given course. """ return waffle_flags()[BULK_MANAGEMENT].is_enabled(course_key)
36531886e09fa9d27e3a157b1bc4aaa76be29500
41,435
def bboxes_filter(): """ """ def _augment( image, bboxes, classes=None ): return image, bboxes, classes return _augment
deee3384f7567181eda6e6735aab01d6967787af
41,436
def kl_loss_var(prior_mu, log_var_prior, post_mu, log_var_post): """ Analytical KLD for two gaussians, taking in log_variance instead of scale ( given variance=scale**2) for more stable gradients For version using scale see https://github.com/pytorch/pytorch/blob/master/torch/distributions/kl.py#L398 "...
b52b03d44202be78683efff13896acfd83e393cf
41,437
def get_matching_s3_keys_as_set(bucketname, suffix="") -> set: """ Generate the keys in an S3 bucket as set. :param bucket: Name of the S3 bucket. :param prefix: Only fetch keys that start with this prefix (optional). """ result = set() for obj in get_matching_s3_objects(bucketname): ...
8b1c3ece7cecee91fad170663e3963b4909fbcf4
41,438
import os def write_model_to_file(model: str, file_path: str = "model.py") -> str: """Write the Pydantic Model string to a Python file. Args: model: The Pydantic Model string. file_path: The path must include the .py file extension. * The file_path is relative to the Workspace Root. ...
01ab968d8130c03d748d39338b634e02d6332a0a
41,439
import os def readSite(dir_path, file_name): """ Read a CSS3 type .site file. More info: ftp://ftp.pmel.noaa.gov/newport/lau/tphase/data/css_wfdisc.pdf Arguments: dir_path: [str] Path to the directory where the .site file is located. file_name: [str] Name of the .site file. """ ...
2411c7fb201c0e328d790cebeb1bb8541bbdbb8e
41,440
def scaled_up_roi(roi, scale: int, shape=None): """ Compute ROI for a scaled up image. Given a crop region in the original image compute equivalent crop in the upsampled image. :param roi: ROI in the original image :param scale: integer scale to get scaled up image :return: ROI in the scaled u...
24f160bde7f995861aee3f0c20001ce4093aa58a
41,441
def get_rotation(tracker: TrackerComponent): """Returns the Euler rotation of the tracker.""" # Data is [0]=side-side [1]=flat [2]=forward-back if tracker.is_hardware: torso_state = tracker.get_state('torso') return torso_state.rot_euler return (0, 0, 0)
c352c51513abccdbc716cd02d2d04a057a164cfd
41,442
import torch def lowpass_filtering_in_frequency_domain( image_grad: torch.Tensor, lowpass: torch.Tensor ) -> torch.Tensor: """Applies lowpass filtering in the frequency domain as descibed in Walker et al. 2019. Args: grad (torch.Tensor): gradient lowpass (torch.Tensor): losspass tenso...
847d89f9f0078838b594b61df9dd4544cb2bd062
41,443
def review_detection_html(ibs, image_uuid, result_list, callback_url, callback_method='POST', include_jquery=False): """ Returns the detection review interface for a particular image UUID and a list of results for that image. Args: image_uuid (UUID): the UUID of the image you want to review det...
c155f48e2ebc930f9ee9181107ac65ba0b2ea637
41,444
def mask_label_image(labels: np.ndarray, bg_mask: np.ndarray, bg_label: int = 0): """ Mask an input label image and rearrange the label numbers so that they form the continuous range [0, numlabel]. Note that there is not relabelling of the components, just a renumbering. Args: :param labe...
3bcc9fb1e65884856105048d42756e03f5062237
41,445
import torch def compute_accuracy( x: Tensor, y: Tensor, m: int, nx: int, c1: int, w: Tensor, b: Tensor ) -> float: """Compute accuracy using the given parameters and data. Args: x (Tensor): The input tensor (MNIST images) y (Tensor): The output tensor (a column vector of zeros and ones) ...
eededcbedbf4b0137e16428ab0ed566cb5e6e102
41,446
def modal(item_id): """ Return the information of the specified 'item_id'. This is so that users can open the correct modal item through AJAX """ return jsonify({ "id": item_id, "name": mysqlcommands.get_item(item_id)[1] })
2f7edf7a7ed61b7ad2e6223b4dc8e267bc2fa8a0
41,447
import warnings def get_download_url(data_product_uri): """(Deprecated) Get URL for downloading data product identified by data_product_uri.""" warnings.warn("Use user_storage.get_download_url instead.", DeprecationWarning) return (reverse("django_airavata_api:download_file") + "?" + urlencode...
c095a2dfe43ffb984d3eb6bbecc64106dd29c5fe
41,448
import re def get_remote_version_string(): """ Get the current cvd string from the clamav DNS TXT entry """ resolver = Resolver() resolver.timeout = 5 nameserver = CVDUPDATE_NAMESERVER record = str(resolver.resolve(CVDUPDATE_NAMESERVER, "TXT").response.answer[0]) versions = re.searc...
c58415d26378a804d0b536d7218f14744a673d93
41,449
def lit(val): """Accept a single item and return the given value.""" return lambda seq: ([val], seq[1:], Status.succeed(where='lit'))
3cf40630a20ef53e25e67ffe1e0279e9bfafa24e
41,450
import argparse def build_parser(args): """ This method allows us to test the args. >>> args = build_parser(['--verbose']) >>> print(args.verbose)) True """ parser = argparse.ArgumentParser(usage='$ python logger.py', description='Get the la...
ee70c06da3b464177333766f1cdb2a264fbed552
41,451
def average(data, axis, n): """ Averages data along the given axis by combining n adjacent values. :param data: Data to average along a given axis. :type data: numpy array :param axis: Axis along which to average. :type axis: int :param n: Factor by which to average. :type n: int ...
2f958f48dbf4e14cdcce4c0c06904b7c48007a25
41,452
def _left_operator(func): """Function decorator to treat a method as the left operator.""" def inner(self, other): """Decorator wrapper.""" left = self.value if isinstance(other, NumericType): right = other.value else: right = other return to_aiid...
252cd5b7e9031f0598c998b69cc7157dcd747661
41,453
from typing import Any def normalize_data_values(type_string: TypeStr, data_value: Any) -> Any: """Decodes utf-8 bytes to strings for abi string values. eth-abi v1 returns utf-8 bytes for string values. This can be removed once eth-abi v2 is required. """ _type = parse_type_string(type_string) ...
17e4c3342a8d7dbc5a1274b5368357cb66a9b8e0
41,454
def StringArrayToVideo(string_array): """Converts a N length JPEG encoded string array to NCHW video. TODO: Allow partial decode (only some frames) """ nframes = string_array.shape[0] frames = [StringArrayElementToFrame(string_array, i) for i in range(nframes)] video = np.transpose(np.stack(fram...
927d11dfcfe54dc3c39a525211588c785eeddba3
41,455
def update_bpt(*args): """update_bpt(bpt_t bpt) -> bool""" return _idaapi.update_bpt(*args)
e02507ec02b11a3fb30fe10d6da584bf9535a65d
41,456
def generate_test_data(): """ 生成测试样本数据,来自函数y=sin(2 * pi * x) :return: 生成的测试数据集的X向量和Y向量 """ test_X = np.linspace(0, 1, 4 * data_number) test_Y = np.sin(2 * np.pi * test_X) return test_X, test_Y
9b8e0abbb5b0a68b3fa20105e0e96e9bf40fee6a
41,457
from typing import Dict from sys import path def get_cfg_rabbitMQ(f:str)->Dict: """ Check if the 'rabbitMQ' config file is valid and returns the values :param f: path to the cfg file :return: params """ if path.isfile(f): with open(f, 'r') as cfg: par = {k.lower():v for k,v...
408fb51ac9f1fefedd893144a3bad7cfca07007f
41,458
def usaf_station_to_lat_lng(station): """Return the latitude and longitude coordinates of the given USAF station. Parameters ---------- station : str String representing a USAF Weather station ID Returns ------- lat_lng : tuple of float Latitude and longitude coordinates. ...
591615783f859be3efe36bb754e8142430d69069
41,459
def generate_kwargs(gt, m_vir_thresh, SSPs_in=None, SSP_kwargs={}, **extra_kwargs): """ Generate kwargs for a GAMMA run. Example usage: ## Generate tree and SSP input to GAMMA gt = caga.gamma_tree.load("my_gamma_tree.npy") mvir_thresh = 1e7 SSPs_in = caga.precompute_ssps...
c9b03fb003d778890f8183b2bf4dd7e5ccfb4dca
41,460
def increase_vectors(vectors): """accelerate so that pieces move faster in earlier frames""" new_vecs = [] for vec in vectors: new_vecs.append((vec[0]*VEC_GROWTH, vec[1]*VEC_GROWTH)) return new_vecs
0eaeaa193722b7a135fa7f0d37605d7bf3a7db9e
41,461
def Validate(ciffile,dic = "", diclist=[],mergemode="replace",isdic=False): """Validate the `ciffile` conforms to the definitions in `CifDic` object `dic`, or if `dic` is missing, to the results of merging the `CifDic` objects in `diclist` according to `mergemode`. Flag `isdic` indicates that `ciffile` is ...
d3828279f9cdfae69690122c82ab50cb40fb9662
41,462
def tapis_client(x_tapis_token: str = Depends(tapis_token)) -> Tapis: """Returns a user Tapis client for the provided token""" try: client = _client(x_tapis_token) except BaseTapyException as exc: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="...
cf9b7a70819c8b1f19da9ae4a40e07417032e0ef
41,463
def default_exchange(): """Return a default :class:`kombu.Exchange` created from configuration. Scope: function This fixture offers a default :class:`kombu.Exchange`. """ return Exchange("test-exchange", type="direct")
efff24cd68f6b5bcd2d7628a2bfc399969b64a10
41,464
from ._array import GeoArray def to_geo(values): """Convert values to GeoArray Parameters ---------- values : WKT, GeoJSON or Esri JSON in a list Returns ------- addresses : GeoArray Examples -------- Parse strings >>> to_geo(['{"x" : -118.15, "y" : 33.80, "spatialRefere...
f0eaa16589489c998109fb9d38df96d82435ac32
41,465
def build(name, ask=True, **kwargs): """ Build the malicious mote to its target hardware. :param name: experiment name (or absolute path to experiment) :param ask: ask confirmation :param path: expanded path of the experiment (dynamically filled in through 'command' decorator with 'expand') :pa...
3d1e82946779f298aecb2e90f481588172bbf051
41,466
def cor(y, z): """Compute Pearson's correlation coefficient.""" return np.corrcoef(y, z)[0, 1]
bb7dac07c5070430a2160c85a87fba1a657e0785
41,467
import torch def ldot(u, v, keepdim=False): """Lorentzian scalar product""" uv = u * v uv.narrow(-1, 0, 1).mul_(-1) return torch.sum(uv, dim=-1, keepdim=keepdim)
59c26e622ef5ffe94d92a2e8c0fc40d316b58f5b
41,468
def print_qa(questions, answers_gt, answers_gt_original, answers_pred, era, similarity=dirac, path=''): """ In: questions - list of questions answers_gt - list of answers (after modifications like truncation) answers_gt_original - list of answers (before modifications) answers_pr...
b1379067f4677626522989ea5c2888678b50e8dc
41,469
def thumbiconurl(public_path): """Get the URL of an icon for filename. """ return mimetypeurl(mimetype(public_path))
590f1d75f5bb27aed0f0a81dc2b70b940ad9a677
41,470
def test_depends(func): """Decorator to prevent a test being executed in individual mode""" def invalid(self, test): if self.test_individual: test.description = "Invalid" return test.DISABLED("This test cannot be performed individually") else: return func(self...
4b2db29fc8c0a30ec3a4ec6c3fb93ed958f0094e
41,471
def load( phono3py_yaml=None, # phono3py.yaml-like must be the first argument. supercell_matrix=None, primitive_matrix=None, phonon_supercell_matrix=None, is_nac=True, calculator=None, unitcell=None, supercell=None, nac_params=None, unitcell_filename=None, supercell_filename...
ed2c4b2eceb0a7979ab864b8ff357663086dbc5e
41,472
def pluralize( *, with_quantity: bool = True, with_indicative: bool = False, **word ) -> str: """Pluralize a single kwarg's name depending on the value. ``with_indicative`` must be used with ``with_quantity``. Example ------- >>> pluralize(object=2) "2 objects" >>> pluralize(object=1)...
9dc4fbe280f4794599f57e7af645d9cac51d655e
41,473
def move_bounds(box, ovl_box, padding=0, axis=None): """ given two boxes, return the x and y deltas needed to move the first box to avoid the second. for simplicity, we chose only one axis, whichever is shorter. Also, only allow positive moves. can choose axis with axis='y' or axis='x' ""...
4b3275d97987a95f9962e975ead5f03af3964348
41,474
def ensure_f(func: Function) -> F: """wrap the given function into a F instance""" if not isinstance(func, F): return F(func) return func
7ea54909bac42c2ade1d1a82ec00c9aff3af7cb6
41,475
import re def compiler_call(executable): """ A predicate to decide the entry is a compiler call or not. """ compilers = [ re.compile(r'^([^/]*/)*([^-]*-)*c(c|\+\+)$'), re.compile(r'^([^/]*/)*([^-]*-)*g(cc|\+\+)(-\d+(\.\d+){0,2})?$'), re.compile(r'^([^/]*/)*([^-]*-)*clang(\+\+)?(-\d+(\....
d8fa6fa22f13b13154579e19a4ab18e016a56caf
41,476
def debye(img, fig, center=None): """Draw the Debye-Scherrer rings, calculates diameter and center of each and returns the mean center for mirroring :param fig: a dictionary with keyword arguments for ``sf.show`` or a matplotlib figure .. note:: If you use ``sf.show`` the figure must be cr...
d85c45b176a4cef6077dd2d5379c5c08fadd32d1
41,477
def month_and_year(m=None, y=None): """Creates a string from month and year data, if available.""" if y is None: return "present" if m is None: return str(y) m = month_to_int(m) return "{0} {1}".format(SHORT_MONTH_NAMES[m], y)
6c09800c7b7649c983462b0f1d09829d897c4e1b
41,478
def to_bool(a): """ a: a str or bool object if a is string 'true', 't', 'yes', 'y', '1', 'ok' ==> True 'false', 'f', 'no', 'n', '0' ==> False """ if isinstance(a, bool): return a elif a is None: return False elif isinstance(a, (int, float)): return b...
00cb99d07ba6dc2b149f52930e9916cabb7fb872
41,479
import six def find_nova_host(address, config): """See if a nova instance has the supplied address.""" nova = client.Client(config['username'], config['password'], config['tenant_id'], config['authurl'], region...
11dc70d022996f8134d57a4507f8b495a7b23402
41,480
from typing import Iterable def camera_matrix(fov=const.CAMERA_FOV, resolution=const.CAMERA_RESOLUTION, alpha=0): """Returns camera matrix [1] from Field-of-View, skew, and offset. Parameters ---------- fov : float, Iterable Field-of-View angle (degrees), if type is Iterable it will be interp...
3817ea4f890b423757fb4c29715697f9df5decf4
41,481
import random def LoadUserAgents(uafile): """ uafile : string path to text file of user agents, one per line """ uas = [] with open(uafile, 'rb') as uaf: for ua in uaf.readlines(): if ua: uas.append(ua.strip()[1:-1-1]) random.shuffle(uas) return ...
3942f92c11e16ff979c1ef80552a1340bc149c16
41,482
def comment_threads_list(key, part, allThreadsRelatedToChannelId=None, channelId=None, id=None, videoId=None, maxResults=None, moderationStatus=None, order=None, pageToken=None, searchTerms=None, textFormat=None): """Returns a list of commen...
74ca3da4aee410ed38916ed4193860715ea01614
41,483
def gaussianBlur(img): """Applies gaussian filter to a grayscale image""" return cv2.GaussianBlur(img, (5, 5), 0)
e0a28f50c792ec09a6660beedc2d9e6e1df0d59b
41,484
def fix_month(bib_str: str) -> str: """Fixes the string formatting in a bibtex entry""" return ( bib_str.replace("{Jan}", "jan") .replace("{jan}", "jan") .replace("{Feb}", "feb") .replace("{feb}", "feb") .replace("{Mar}", "mar") .replace("{mar}", "mar") .r...
9bdcb06dc43a6d6748af20d5279ca38ec6aa1d0a
41,485
def multipart_form_message(media, form_data={}): """Return a MIMEMultipart message to upload encoded media via an HTTP form POST request. Args: media: a list of (encoded_data, filename) tuples. form_data: dict of name, value form fields. """ message = MIMEMultipart('form-data', None) if form_data: ...
e8c27c3baf0e0692a017de2bfb3a08755cecfb4a
41,486
def make_well2file_dict(data): """Create a dictionary mapping wells to image files. Parameters ---------- data : pandas data frame A data frame from feature computation. Returns ------- well2file : dictionary, {(int, string): string} A dictionary keyed by a (plate, well) tu...
0baaed068a9b84596749a89bc37cae10f8e3950d
41,487
from typing import Optional def create_balloon( x: units.Distance = units.Distance(m=0.0), y: units.Distance = units.Distance(m=0.0), center_lat: float = 0.0, center_lng: float = 0.0, pressure: float = 7_000.0, power_percent: float = 0.95, date_time: Optional[dt.datetime] = None, time_...
e776684b8aa648acfd18f1e026aec296e4c39329
41,488
import os def _is_attribute_file(filepath): """ Check, if ``filepath`` points to a valid udev attribute filename. Implementation is stolen from udev source code, ``print_all_attributes`` in ``udev/udevadm-info.c``. It excludes hidden files (starting with a dot), the special files ``dev`` and ``u...
6fbfc3b7de0f192ad96118f412ff7ea4ab42e06a
41,489
def calculate_reference_sample(experiment: FCSExperiment, exclude_samples: list) -> str: """ Given an FCS Experiment with multiple FCS files, calculate the optimal reference file. This is performed as described in Li et al paper (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5...
0058d26f7331b5fc1075af1a3a394bc6c64ba2b2
41,490
def get_visibles(photos, user): """ get only photos visible for user """ return photos.filter( Q(owner=user) | Q(shared=user) )
657c336244d2d34b76c12f8964389be4a8d1a300
41,491
import asyncio async def changeTeam(team, member): """enleve tous les rôles d'un utilisateur sauf '@everyone' et '@modo' puis place le member dans la team appropriée return 1 si le changement est effectif 0 sinon""" team = teamName(team) assert team assert isinstance(member, discord.Member) f...
a6accb214e1e09bae59fc4b495f95d019444ac01
41,492
def dataqc_spiketest(dat, acc, N=5, L=5, strict_validation=False): """ Description: Data quality control algorithm testing a time series for spikes. Returns 1 for presumably good data and 0 for data presumed bad. The time series is divided into windows of len L (an odd integer ...
c2c496c6260095b8887b5105ec4305af74959c17
41,493
def pad(text: str, width: int, align: str = '<', fill: str = ' '): """ pad the string with `fill` to length of `width` :param text: text to pad :param width: expected length :param align: left: <, center: ^, right: > :param fill: char to fill the padding :return: """ assert align in ...
74befd22927438961b85e370ed16239d7df52707
41,494
def coins_to_numpy(game): """Game coins info to numpy array Parameters ---------- game : camel up game Camel up game class Returns ------- array Numpy array """ return np.array( [(key[0], key[1]["coins"]) for key in [*game.player_dict.items()]], dty...
2c0614d008f43bbb33e66e6cad169e4e512a6cd9
41,495
import select def edit_mode(obj): """ Select the object and change to edit mode :param obj: string, name of object :return: bpy data object """ bpy.ops.object.mode_set(mode='EDIT') o = select(obj) bpy.ops.object.mode_set(mode='EDIT') bpy.ops.object.mode_set(mode='EDIT') return ...
046c65e6b2beda097776cecb35e25fa8b64314e5
41,496
async def test_cli( aiohttp_client, otupdate_config, monkeypatch, version_file_path, mock_name_synchronizer, ): """ Build an app using dummy versions, then build a test client and return it """ app = buildroot.get_app( name_synchronizer=mock_name_synchronizer, system_...
616c900b2f122ec04cfd3586d9de2937bf9c0d6d
41,497
def check_xform(path_to_xform): """ Returns an array of warnings if the form is valid. Throws an exception if it is not """ # provide useful error message if java is not installed if not _java_installed(): raise EnvironmentError("pyxform odk validate dependency: java not found") #re...
ac31946110fefc462ebc0e9bc9763840f19a77bb
41,498
import torch def slerp(val, low, high): """ val, low, high: bs x frames x coordinates if val == 0 then low if val == 1 then high """ assert low.dim() == 3, low.dim() assert val.dim() == 3, val.dim() assert high.dim() == 3, high.dim() low_norm = low / torch.norm(low, dim=2, keepdim=...
96a74c366139f3f617676e5e011884f698569b97
41,499