content
stringlengths
22
815k
id
int64
0
4.91M
def test_contrastive_loss3(): """ There should be the most loss here (some from pull term, and some from push term also) """ # which pairs share the same semantic class label y_c = torch.tensor([ 1., 0., 0., 0., 1.], dtype=torch.float32) # distances between pairs pred_dists = torch.tensor([...
55,200
def get_json_file(json_filename, default_data=None): """ try get json file or auto-create the json file with default_data """ default_data = default_data if default_data is not None else {} if not os.path.exists(json_filename): data = default_data write_json(json_filename, data) ...
55,201
def spawner_server(loop, aiohttp_server): """ Spawns backend services (emulates director) """ # uses mountpoint as a unique identifier registry = {} # registry[mountpoint] -> {info:{}, server:} async def list_infos(reg: web.Request): return web.json_response([v["info"] for v in re...
55,202
def csv2df(csv_string): """http://stackoverflow.com/a/22605281""" import pandas as pd return pd.read_csv(six.StringIO(csv_string),index_col=False)
55,203
async def kube_config(ops_test: OpsTest) -> Path: """Return path to the kube config of the tested Kubernetes cluster. Config file is fetched from kubernetes-master unit and stored in the temporary file. """ k8s_master = ops_test.model.applications["kubernetes-master"].units[0] with tempfile.Tempor...
55,204
def fidelity_KS_univariate(fcst, obsv, max_period, by_lead): """ Perform a Kolmogorov-Smirnov test on univariate data """ def _get_KS_statistic(fcst_ds, obsv_ds, by_lead=False): if by_lead: # Applied per lead_time within groupby stack_dim = [d for d in fcst_ds.dims if 'stacked_' ...
55,205
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'): """ Helper function to generate a CSV header line depending on the combination of arguments provided. """ if isinstance(header, str): # user-provided header line header_line = header + newl...
55,206
def cov_ident_plot(biotypes, ordered_genomes, mode, tgt, df, x=None, y=None, xlabel=None): """violin plots for coverage and identity.""" if xlabel is None: xlabel = 'Percent {}'.format(mode) with tgt.open('w') as outf, PdfPages(outf) as pdf: title = 'Overall {}'.format(mode) xmin = i...
55,207
def filter_labeled_genes(genes): """Filter genes which already have a label and return number of labels. Args: genes(dict): dictionary of genes {g_name: gene object} Returns: dict: dictionary of genes without label {g_name: gene object} int: number of distinct labels in the set of labele...
55,208
def get_floss_params(str_floss_options, filename): """Helper routine to build the list of commandline parameters to pass to Floss.""" # First parameter is the name of the Floss "main" routine. list_floss_params = ['main'] # Add the options from app.config list_options = str_floss_options.split(",")...
55,209
def send_rst_frame(protocol: int, pipe: int, dst_ia: int, error_code: int, rid: int, token: int): """ 发送错误码 """ log.info('send rst frame:0x%x!token:%d protocol:%d pipe:0x%x dst ia:0x%x', error_code, token, protocol, pipe, dst_ia) frame = Frame() frame.control_word.code = CODE_RST ...
55,210
def noboot_roc_curve(X=None, y=None, y_score=None, model=None, fitMethod='', predictMethod='', alpha=0.05, method='score'): """Compute ROC curve with confidence intervals using score test and other methods, for the classification model. Code in powercalc.py has been checked against R binom package. "Score" was...
55,211
def fma(x, y, z): """ fma(x, y, z) -> number Return the correctly rounded result of (x * y) + z. """ try: # XXX Optimise res, mpfr_x = _init_check_mpfr(x) res, mpfr_y = _init_check_mpfr(y) res, mpfr_z = _init_check_mpfr(z) gmp.mpfr_fma(res, mpfr_x, mpfr_y, mp...
55,212
def startendcheck(timepoints, startpoint, endpoint): """ Parameters ---------- timepoints startpoint endpoint Returns ------- """ if startpoint > timepoints - 1: print('startpoint is too large (maximum is ', timepoints - 1, ')') sys.exit() if startpoint < 0...
55,213
def is_leap_year(year: int) -> bool: """Whether or not a given year is a leap year. If year is divisible by: +------+-----------------+------+ | 4 | 100 but not 400 | 400 | +======+=================+======+ | True | False | True | +------+-----------------+------+ Args: ...
55,214
def assign_val(callobj, **kwargs): """Assign metadata values passed as kwargs to an object. Useful to easily set metadata fields directly without working with SchedMeta. """ try: meta = getattr(callobj, SCHED_ATTR_NAME) #meta.__dict__.update(kwargs) # dataclass meta.update(...
55,215
def is_allowed_file(filename): """Check if a file extension is allowed. Args: filename (str): Name of the file to check. Returns: True if the file upload is allowed. """ return '.' in filename and \ filename.rsplit('.', 1)[1] in current_app.config['ALLOWED_EXTENSI...
55,216
def _build_distance_estimator(X, y, w2v, PoS, NER, regressor, verbose=1): """Build a vector reprensation of a pair of signatures.""" if w2v == 'glove': PairVecTransformer = PairGloveTransformer elif w2v == 'spacy': PairVecTransformer = PairSpacyVecTransformer elif w2v == 'polyglot': ...
55,217
def serial_connection(path, protocol, is_probing=False): """Opens a serial connection to a device and closes it automatically after use. :param path: path to the device :type path: string :param protocol: an object containing the serial protocol to connect to a device :type protocol: namedtuple ...
55,218
def create_app(**kwargs): """ Create a new WSGI application, register blueprints and initialize extensions. :key name : The name of the Flask application. :key settings: The object with that name will be imported to set environment variables. """ app = Flask(kwargs.pop('name', os.getenv(...
55,219
def trace(project, feature, scenario): """ This command ables you to run the traces generator's tool by running every BDD feature. None of the arguments are required. """ # language = find_language(path) language = 'Ruby' if(language == 'Ruby'): # config = RubyConfig() ...
55,220
def n15hsqc(bmrb_ids: Optional[Union[str, List[str], int, List[int]]] = None, input_file_names: Optional[Union[str, List[str]]] = None, entry_objects: Optional[Union[pynmrstar.Entry, List[pynmrstar.Entry]]] = None, auth_tag: Optional[bool] = False, legend: Optional[str] =...
55,221
def binary_prediction_results(y_true, y_pred): """ Returns a dictionary with counts of TP, TN, FP, and FN Args: y_true, y_pred (numpy-compatible, 1D array-like): binary valued objects holding the ground truth and predictions (respectively), on which validation has already been run. ...
55,222
def SplitFMNIST(n_experiences: int, first_batch_with_half_classes: bool = False, return_task_id=False, seed: Optional[int] = None, fixed_class_order: Optional[Sequence[int]] = None, train_transform=_default_cifar10_train_transform, ...
55,223
def group_by(value, key: Union[str, int] = "", count=False, *, context) -> Dict[any, Union[List[any], int]]: """ Group the incoming values :param value: Incoming list :param key: The key to use in grouping the items. If no key, then the value will be used. Any valid JQL query :param count: Whether t...
55,224
def create_index_page(): """ Dynamically create links for all app pages """ links = [] for page in pages: links.append(dcc.Link("Go to Page " + page, href="/pages/" + page)) links.append(html.Br()) return links
55,225
def createPixelMatrix( imgdata, width, height): """ Create a global array of pixel data from the 'guts' of a .bmp file Inputs: -- imgdata: The .bmp file raw pixel data array -- width: width of image data (stripped from .bmp header) -- height: height of image data (stripped from .bmp header) ...
55,226
def maybe_coroutine(obj): """ If 'obj' is a coroutine and we're using Python3, wrap it in ensureDeferred. Otherwise return the original object. (This is to insert in all callback chains from user code, in case that user code is Python3 and used 'async def') """ if six.PY3 and asyncio.iscoro...
55,227
def inchi(xgr): """ InChI string of this connectivity graph """ ich, _ = _inchi_with_atom_inchi_numbers(xgr) return ich
55,228
def comment_show(user, nodes): """Show the comments of one or multiple nodes.""" for node in nodes: msg = '* Comments for Node<{}>'.format(node.pk) echo.echo('*' * len(msg)) echo.echo(msg) echo.echo('*' * len(msg)) all_comments = node.get_comments() if user is n...
55,229
def _compute_dloss_by_dmin_using_dmax(dloss_by_dmax): """ compute derivative of loss w.r.t min, it is sign flipped version of derivative w.r.t max :param dq_by_dmax derivative w.r.t max :return: derivative w.r.t min """ return tf.negative(dloss_by_dmax)
55,230
def get_gitlab_groups(default_val=False): """ Get a list of groups for display in a drop-down menu box. :return: List of groups name tuples. """ groups = {} try: groups = requests.get( gitlab_import_config.gitlab_url + 'groups?search=' + gitlab_import_config.default_group +...
55,231
def unsalt(): """ Remove salt/solvates. Examples and documentation: [https://wwwdev.ebi.ac.uk/chembl/extra/francis/standardiser/04\_unsalt.html](https://wwwdev.ebi.ac.uk/chembl/extra/francis/standardiser/04_unsalt.html) CTAB is either single molfile or SDF file. cURL examples: curl -X POST --data-binary @unsal...
55,232
def print_debug(text, **kwargs) : """Print debugging information Input ----- text: str pipe: musepipe [None] If provided, will print the text in the logfile """ mypipe = kwargs.pop("pipe", None) try: verbose = mypipe.verbose except: verbose = kwargs.pop("verb...
55,233
def main(): """ Sample echo topology application. This Python application builds a simple topology that echoes its command line arguments to standard output. The application implements the typical pattern of code that declares a topology followed by submission of the topology to a Streams conte...
55,234
def Select3D_SensitiveTriangle_Status(*args): """ :param X: :type X: float :param Y: :type Y: float :param aTol: :type aTol: float :param Dmin: :type Dmin: float & :rtype: int * Dmin gives the distance between the cdg and aPoint return :param p0: :type p0: gp_XY :...
55,235
def count_pred_types(df): """ Print a list of predicted energy types and number of facilities of each type. Parameters ---------- df : Pandas dataframe Must contain a 'pred' column. """ for tp in df.pred.unique(): print(tp, len(df[df.pred == tp]))
55,236
def confirm_action(config, msg=None, allow_auto=True): # type: (dict, str, bool) -> bool """Confirm action with user before proceeding :param dict config: configuration dict :param msg str: confirmation message :param bool allow_auto: allow auto confirmation :rtype: bool :return: if user con...
55,237
def save_image(image, folder_path, filename, file_extend='.png'): """ Save image in to a path with a name. :param image: 3L ndarray, image :param folder_path: a str :param filename: a str :param file_extend: a str """ if not os.path.exists(folder_path): os.makedirs(folder_path) ...
55,238
def read_nam_maps(netcdf_file_name, PREDICTOR_NAMES): """Reads fog-centered maps from NetCDF file. E = number of examples (fog objects) in file M = number of rows in each fog-centered grid N = number of columns in each fog-centered grid C = number of channels (predictor variables) :param netcdf_...
55,239
def get_base_dir(): # type: () -> str """ Get the base directory for mongo repo. This script assumes that it is running in buildscripts/, and uses that to find the base directory. """ try: return subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip() except su...
55,240
def pick_free_port(): """ Pick free port using socket """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', 0)) addr, port = s.getsockname() s.close() return port
55,241
def borders(district, unit): """Check if a unit borders a district.""" if district == []: return True neighbour_coords = [(unit.x+i, unit.y+j) for i in [1, 0, -1] for j in [1, 0, -1] if bool(i) ^ bool(j)] district_coords = [(d_unit.x, d_unit.y) for d_unit in district] ...
55,242
def get_step_g(step_f, norm_L2, N=1, M=1): """Get step_g compatible with step_f (and L) for ADMM, SDMM, GLMM. """ # Nominally: minimum step size is step_f * norm_L2 # see Parikh 2013, sect. 4.4.2 # # BUT: For multiple constraints, need to multiply by M. # AND: For multiple variables, need to...
55,243
def isDefinition(): """Matches if the cursor is a definition >>> from glud import * >>> config = ''' ... class X {}; ... class Y; ... ''' >>> m = cxxRecordDecl(isDefinition()) >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) X """ return PredM...
55,244
def read_string(buff, byteorder="big"): """Read a string from a file-like object.""" length = read_numeric(USHORT, buff, byteorder) return buff.read(length).decode("utf-8")
55,245
def parse_config(): """ Checks the config file for the correct format and directs params to main """ checklist = ["n", "r", "graph_seeds", "output_dir", "num_threads", "algo_seed", "timeout", "verbose", "docker_verbose", "algorithms", "csv_filename"] expected = len...
55,246
def SGD_ninits(setup): """Perform stochastic gradiend descent for a number of initial models. Arguments: setup -- SGDsetup object which contains SGD parameters. """ print_SGDsetup(setup) dRMSEs = [] models_costmin = [] zs_hist = [] mRMSEs = [] for j in range(setup.ninits): ...
55,247
def consume_events(client: ServiceClient, in_queue: Queue, run_id: str) -> None: """Main working loop that sends data to Schemathesis.io.""" try: while True: event = in_queue.get() if event is STOP_MARKER: # It is an equivalent of an internal error in some other h...
55,248
def _cv_checkerboard(image_size, square_size): """Generates a checkerboard level set function. According to Pascal Getreuer, such a level set function has fast convergence. """ yv = np.arange(image_size[0]).reshape(image_size[0], 1) xv = np.arange(image_size[1]) return (np.sin(np.pi/square_size...
55,249
def redirect(url, code=303): """ Aborts execution and causes a 303 redirect """ scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/' location = urljoin(request.url, urljoin(scriptname, url)) raise HTTPResponse("", status=code, header=dict(Location=location))
55,250
def calc_sigma_units(time_vector: np.ndarray, range_los: np.ndarray) -> Tuple[float, float]: """Calculates Gaussian peak std parameters. The amount of smoothing is hard coded. This function calculates how many steps in time and height corresponds to this smoothing. Args: time_vector: 1D vector...
55,251
def test_incorrect_fixture_aggressive(absolute_path): """End-to-End test to check that incorrect code raises warning.""" filename = absolute_path('fixtures', 'incorrect.py') process = subprocess.Popen( [ 'flake8', '--eradicate-aggressive', '--isolated', ...
55,252
async def test_load_handles_generic_exception(aioclient_mock, hass): """Test setup handles global exception.""" def MockInitialize(): raise Exception() device = get_mock_device() device.initialize.side_effect = MockInitialize entry = MockConfigEntry( domain=DOMAIN, data={C...
55,253
def _run(model_file_name, example_dir_name, years, unique_cyclone_id_strings, target_class, half_window_size_px, stride_length_px, fill_value, output_file_name): """Creates occlusion maps. This is effectively the main method. :param model_file_name: See documentation at top of file. ...
55,254
def format_request(routes, route, method, base_url="{{base_Url}}"): """Populates atomic_request dictionary with route metatdata. Returns a postman formatted dictionary request item.""" request = atomic_request() doc = get_route_doc_string(routes, route, method) name = get_route_name(route) url ...
55,255
def reachable(fanin, n): """ Figure out what circuits are reachable from gates with limited fanin. """ seen = set() answer = [] atoms = Toffoli.generate(fanin, n) pending = list(atoms) while pending: circuit = pending.pop() sig = signature(circuit, n) if sig in se...
55,256
def calc_fixPos(etdata, fix, w=50): """ TODO: dublicate function. Update to use calc_event_data """ data=etdata.data ws=round_up_to_odd(w/1000.0*etdata.fs) fix_pos=[] for f in fix: ind_s=f[0]+ws ind_s = ind_s if ind_s < f[1] else f[1] ind_e=f[1]-ws ind_e = ind...
55,257
def process_action(action_info: Dict, sentences_info: List[Dict[str, Any]], words: List[str], sentence_number: int) -> Action: """ Create action and his object Parameters ---------- action_info sentences_info words sentence_number Returns ------- """ ...
55,258
def unique_slugify(data, models, duplicate_key=''): """Returns a unique slug string. If duplicate_key is provided, this is appended for non-unique slugs before adding a count.""" slug_base = slugify(data) counter = 0 slug = slug_base while any(model.objects.filter(slug=slug).exists() for mod...
55,259
def affine_del_homogeneous(affine): """Ensure that the last row of the matrix is _not_ (*zeros, 1). This function is more generic than `make_rect` because it works with images where the dimension of the output space differs from the dimension of the input space. Parameters ---------- affin...
55,260
def basic_rule_generator(data: Sequence[Measurement], args) -> Generator: """ Marginal rule generator. """ crit = CriticalValues() for i, _ in enumerate(data): yield lambda x: all([crit.min_sbp <= x.sbp < crit.max_sbp, crit.min_dbp <= x.dbp < crit.max_dbp])
55,261
def Kurt(poly, dist=None, fisher=True, **kws): """ Kurtosis operator. Element by element 4rd order statistics of a distribution or polynomial. Args: poly (numpoly.ndpoly, Distribution): Input to take kurtosis on. dist (Distribution): Defines the space the skewne...
55,262
def relabel_graph_nodes(graph, label_dict=None, with_data=True): """ Relabel graph nodes.The graph is relabelled (and returned) according to the label dictionary and an inverted dictionary is returned. Only integers are allowed as labels. If some other objects will be passed inn the label_dict, ...
55,263
def add_form_shared(request, client_api, form_acess="", external=False): """ Method to render form request vip """ try: lists = dict() lists["action"] = reverse('vip-request.form') lists['ports'] = '' lists['ports_error'] = '' lists['reals_error'] = '' l...
55,264
def adv_results(request): """ Process the form from an advanced search. We expect to always get here from the advanced search page and always on a get, either from the submit button on the form or the paging navigation buttons. * On first search submission, load the request session dictionary...
55,265
def code_duplication_figure(metrics): """Create the code duplication donut.""" duplicated_loc = metrics["duplicated_loc"] total_loc = metrics["total_loc"] labels = ["Duplicated code", "Non duplicated code"] values = [duplicated_loc, (total_loc - duplicated_loc)] percentage = (duplicated_loc /...
55,266
def adduser(username, uid=None, system=False, no_login=True, no_password=False, gecos=None, arg_mapping=CmdArgMappings.DEBIAN, **kwargs): """ Formats an ``adduser`` command. :param username: User name. :type username: unicode | str :param uid: Optional user id to use. :type uid: lon...
55,267
def lin(p,x): """ Linear function for fitting """ return p[0]+np.dot(p[1],x)
55,268
def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description=( "The storescu application implements a Service Class User " "(SCU) for the Storage Service Class. For each DICOM " "file on the command lin...
55,269
def _chartToDF(c): """internal""" df = pd.DataFrame(c) _toDatetime(df) _reindex(df, "date") return df
55,270
def file_diff_format(filename1, filename2): """ Inputs: filename1 - name of first file filename2 - name of second file Output: Returns a four line string showing the location of the first difference between the two files named by the inputs. If the files are identical, the fun...
55,271
def test_themes_escape_html(): """Themes should escape XSS properly""" app = create_ctfd() with app.app_context(): user = gen_user(app.db, name="<script>alert(1)</script>") user.affiliation = "<script>alert(1)</script>" user.website = "<script>alert(1)</script>" user.country ...
55,272
def isQuerynameSorted(fname, file_type): """Check if a given file file is sorted based on the queryname. Args: fname: a input file name Returns: True if fname is a bam file sorted by read name, otherwise False """ if file_type == "bam": return(isBamQuerynameSorted(f...
55,273
def qlength(rcd): """ Returns "quality length" """ qscore = rcd.letter_annotations["phred_quality"] nq = np.array(qscore) q_mean = [] for i in range(1,len(nq)): q_mean.append(abs(nq[:i].mean() - nq[i:].mean())) q_mean[0] = q_mean[1] return q_mean.index(max(q_mean))
55,274
def test_privates(): """ test private methods called in score public method """ silhouette = Silhouette() mat = np.array([[0,0],[0,1],[1,0],[1,1],[100,100],[100,101],[101,100],[101,101]]) assignments = np.concatenate((np.zeros(int(mat.shape[0] / 2)), np.ones(int(mat.shape[0] / 2)))) centro...
55,275
def social(): """Redirects to the Accent Twitter profile.""" return redirect(SOCIAL_URL)
55,276
def MakeCircleRange(circle_size, slice_side): """factory function that pre computes all circular slices slices are assumed to be 2*slice_side+1 in length """ assert (circle_size - 1) % 2 == 0 slice_collection = {} full_indices = list(range(0, circle_size)) for centre_index in range(circle_s...
55,277
def get_data(directory, tar_filename): """ Extract data and return filenames, grouped by paper. Parameters ---------- directory : string The path to a directory which contains .gz files of the arXiv. tar_filename : string The name of the file which should get analyzed Retur...
55,278
def TDataXtd_Constraint_GetID(*args): """ * Returns the GUID for constraints. :rtype: Standard_GUID """ return _TDataXtd.TDataXtd_Constraint_GetID(*args)
55,279
def test_update_credit_to_online_banking(session): """Assert that update from credit card to online banking works.""" credit_account = PaymentAccountService.create(get_basic_account_payload()) online_banking_account = PaymentAccountService.update(credit_account.auth_account_id, get_basic_account_payload( ...
55,280
def test_csvshape_validate_property_uri_prefixed(): """@@@""" stat = CSVRow(propertyID="wdt:P31") stat._normalize_propid() assert stat._validate_propid()
55,281
def get_memory_usage(pids, verbose=False, exclude=None, use_pss=True): """Returns memory stats for list of pids, aggregated by cmd line.""" # TODO: pylint complains about too many branches, need to refactor. # pylint: disable=R0912 meminfos = [] for pid in pids: thread_id = int(get_thread_i...
55,282
def replace_step_valueFrom_expr_with_etool( expr: str, name: str, workflow: cwl.Workflow, target: Union[cwl.CommandInputParameter, cwl.WorkflowInputParameter], step: cwl.WorkflowStep, step_inp: cwl.WorkflowStepInput, original_process: Union[cwl.CommandLineTool, cwl.ExpressionTool], origi...
55,283
async def test_receive_ssdp_byebye() -> None: """Test handling a ssdp:alive advertisement.""" # pylint: disable=protected-access on_alive = AsyncMock() on_byebye = AsyncMock() on_update = AsyncMock() listener = UpnpAdvertisementListener( on_alive=on_alive, on_byebye=on_byebye, on_update=...
55,284
def dependency_on_infectiousness_width_homogeneous_model_example(): """ Example of several computations of the limit Eff_∞ in homogeneous scenarios (i.e. with no app usage) in which the default distribution ρ^0 of the generation time is rescaled by different factors. """ infectiousness_rescale_fact...
55,285
def octree_et(sc, margin, idx=None, eidx=None, bounds=None, cloth=None): """Adaptive octree. Good for finding doubles or broad phase collision culling. et does edges and tris. Also groups edges in boxes.""" # first box is based on bounds so first box could be any shape rectangle #sh = cloth.pierce_co.s...
55,286
def descriptor_dict_to_uri(ddict): """ Translates a descriptor dictionary into a uri. :param ddict: descriptor dictionary :returns: descriptor uri """ from .base import IODescriptorBase return IODescriptorBase.uri_from_dict(ddict)
55,287
def process_df(df, sentence_column='SentenceID', word_column='Word', tag_column='Tag', verbose=1): """ Extract words, tags, and sentences from dataframe """ # get words and tags words = list(set(df[word_column].values)) n_words = l...
55,288
def self_introduce(obj: object) -> None: """请求obj进行自我介绍""" obj.introduce()
55,289
def process_using_lnurl(amt): """Processes receiving an amount using the lnurl scheme """ # get the new lnurl display.update_lnurl_generation() logger.info("LNURL requested") print("LNURL requested") lnurl = request_lnurl(amt) print(lnurl["lnurl"]) # Check EPD_SIZE is defined ut...
55,290
def ramp_geometric(phi, A): """ Weighted geometric mean according to phi. """ return A[0]**(0.5*(1.+phi))*A[1]**(0.5*(1.-phi))
55,291
def secondary_structure(**kwargs): """ Predict or load secondary structure for an input sequence Parameters ---------- Mandatory kwargs arguments: See list below in code where calling check_required Returns ------- residues : pandas.DataFrame Table with sequence and...
55,292
async def post_login_infos( *, resp_: Response, request : Request, # access_token: str = p_access_token, user_login: UserLogin = Body(..., embed=True), api_key: APIKey = Depends(get_api_key), ): """ Needs an anonymous access_token """ ### DEBUGGING print() print("-+- "*40) log_.debug( "...
55,293
def dipole(sign, simplified=False): """Segmented BC dipole model.""" segtypes = { 'b': ('B', _pyaccel.elements.rbend), 'b_edge': ('edgeB', _pyaccel.elements.marker), 'b_pb': ('physB', _pyaccel.elements.marker), } # FIELDMAP # trajectory centered in good-field region. init_...
55,294
def edge_to_string(token, is_head=False): """ Converts the token to an edge string representation :param token: the token :return: the edge string """ t = token if not isinstance(token, spacy.tokens.token.Token): t = token.root return '/'.join([token_to_lemma(token), t.pos_, t.d...
55,295
def test_MTRegression_normal_loss_10(): """ Test `get_MTRegression_normal_loss()` for the case of 10 tasks. """ # Get metric function. num_tasks = 10 scales = SCALES[num_tasks] metric = get_MTRegression_normal_loss(num_tasks) # Generate labels and outputs. labels = torch.rand((BATCH_SIZE, ...
55,296
def sknet152(**kwargs): """ SKNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for...
55,297
def compressBaseName(path): """if a file is compressed, return the path without the compressed extension""" if isCompressed(path): return os.path.splitext(path)[0] else: return path
55,298
def modify_collection_test_( action: str, item_name: str, item_type: str, item_id: str, ItemClass: Item, Collection: ItemCollection, output_text: str, flags: List[str] = None, ): """ action: 'follow' | 'unfollow' | 'save' | 'unsave' item_type: 'playlist' | 'a...
55,299