content
stringlengths
22
815k
id
int64
0
4.91M
def indgen(*shape): """ Create a (multi-dimensional) range of integer values. Notes ----- **porting to python** If ``shape`` is of one dimension only, you can use ``np.arange(n)``. IDL accepts floats as dimension parameters, but applies ``int()`` before using them. While ``np.arange()...
5,343,300
def post_search(request): """ Crear funcion de busqueda de posts llamando el form SearchForm Cuando el formulario es emitido,mandas el formulario usando el metodo GET atraves del POST. Cuando el formulario es emiido se instancia con los datos enviados por GET y verifica que los datos sean validos, s...
5,343,301
def get_bins(values): """ Automatically compute the number of bins for discrete variables. Parameters ---------- values = numpy array values Returns ------- array with the bins Notes ----- Computes the width of the bins by taking the maximun of the Sturges and the ...
5,343,302
def destination_name(data): """ Fonction qui permet de récupérer le nom du terminus en fonction de data passé en paramètre Nom fonction : destination_name Paramètre : data, un flux xml Return : un string qui a comme valeur le libellé de la destination final""" tree = ET.ElementTree(ET.f...
5,343,303
def prim_NumToTensor(mapper, graph, node): """ 构造转为Tensor的PaddleLayer。 TorchScript示例: %other.2 : Tensor = prim::NumToTensor(%1736) 参数含义: %other.2 (Tensor): 输出。 %1736 (-): 输入。 """ scope_name = mapper.normalize_scope_name(node) output_name = mapper._get_outputs_name(no...
5,343,304
def import_taskdict(modname): """Import user module and return its name and TASKDICT""" try: mod = import_module(modname) except (ImportError, ModuleNotFoundError): LOGGER.critical('Module %s not found. ' 'Check it is along PYTHONPATH', modname) raise try:...
5,343,305
def core_periphery(): """Pipeline for core-periphery clustering, using the CP_THRESHOLD.""" with open(INPUT_PICKLED_GRAPH, "rb") as file: G = pickle.load(file) # Reference: https://github.com/skojaku/core-periphery-detection/blob/7d924402caa935e0c2e66fca40457d81afa618a5/cpnet/Rombach.py rb = cp...
5,343,306
def nlp_stem(string): """ Generates a list of the stem for each word in the original string and returns the joined list of stems as a single string. """ ps = nltk.porter.PorterStemmer() stems = [ps.stem(word) for word in string.split()] return " ".join(stems)
5,343,307
def _CreateHostConfigEntityFromHostInventory(lab_name, host): """Creates HostConfig from HostInventory. Args: lab_name: the lab name. host: the ansible inventory Host object. Returns: the HostConfig entity. """ return datastore_entities.HostConfig( id=host.name, lab_name=lab_name, ...
5,343,308
def assert_allclose( actual: numpy.ndarray, desired: numpy.ndarray, rtol: float, atol: int, err_msg: Literal["attribute: tvalues"], ): """ usage.statsmodels: 1 """ ...
5,343,309
def test_simple_case(): """Test a simple case with 3 frames and 2 detections/gts per frame.""" gt = Tracks() gt.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]])) gt.add_frame(1, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]])) gt.add_frame(2, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))...
5,343,310
def visualize_object_detection_custom( image, post_processed, config, prev_state, start_time, duration): """Draw object detection result boxes to image. Args: image (np.ndarray): A inference input RGB image to be draw. post_processed (np.ndarray): A one batch output of model be ...
5,343,311
def all_files(directory="..\\raw_data\\"): """ Return flat list of all csv files in the given directory. Args: directory [string] full path to directory with csv files. Default project layout is used if it is not provided Returns: Flat list of csv files as absolute names. """ ...
5,343,312
def connected_user(**params): """Returns the connected user.""" if g.context.person: return g.context.person == request.view_args.get('person_id')
5,343,313
def remove_plugin(plugin, directory=None): """Removes the specified plugin.""" repo = require_repo(directory) plugins = get_value(repo, 'plugins', expect_type=dict) if plugin not in plugins: return False del plugins[plugin] set_value(repo, 'plugins', plugins) return True
5,343,314
def command_arg(name, value_type=None, help=''): # noqa; pylint: disable=redefined-builtin """ Decorator wrapping functions to add command line arguments to the sub command to be invoked :param name: Name of the argument :param value_type: Type of the argument :param help: Help string for the argu...
5,343,315
def test_gcp_iam_organization_role_get_command(client): """ Retrieve organization role information. Given: - User has provided valid credentials. When: - gcp-iam-organization-role-get called. Then: - Ensure number of items is correct. - Ensure outputs prefix is correct. - En...
5,343,316
def write_file(signum, frame): """Requisited new data from sensor""" print "Requisited new data from sensor" f = open(PASSIVE_FILE, 'w') f.write(msp430['passives']) print msp430['passives'] f.close() try: # Without a real pid, could be dangerous # kill(pid_bikex,SIG2) ...
5,343,317
def ioc_arg_parser(*, desc, default_prefix, argv=None, macros=None, supported_async_libs=None): """ A reusable ArgumentParser for basic example IOCs. Parameters ---------- description : string Human-friendly description of what that IOC does default_prefix : string ...
5,343,318
def count_model_param_and_flops(model): """ Return the number of params and the number of flops of (only) 2DConvolutional Layers and Dense Layers for both the model. :return: """ param_by_layer = dict() flop_by_layer = dict() nb_param_model, nb_flop_model = 0, 0 for layer in model.lay...
5,343,319
def plate_from_dataframe( dataframe, wellname_field="wellname", num_wells="infer", data=None ): """Create a plate from a Pandas dataframe where each row contains the name of a well and data on the well. it is assumed that the dataframe's index is given by the well names. This function is used e.g....
5,343,320
def catch_conn_reset(f): """ A decorator to handle connection reset errors even ones from pyOpenSSL until https://github.com/edsu/twarc/issues/72 is resolved It also handles ChunkedEncodingError which has been observed in the wild. """ try: import OpenSSL ConnectionError = OpenSS...
5,343,321
def S7_plot_static(t, whichplot, tsteps, M, S, gamma): """ Plots the interactions of the galaxies in the S7 initial condition at set time values. Parameters ---------- t: float The current time t[i]. whichplot: str The passage one wants to see. tsteps: int The number...
5,343,322
def register(session): """Register action. Called when used as an event plugin.""" AppplicationsAction(session).register()
5,343,323
def prepared(name): """Prepare the given volume. Args: name (str): Volume name Returns: dict: state return value """ ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Idempotence. if __salt__['metalk8s_volumes.is_prepared'](name): ret['result'] =...
5,343,324
def if_statement(env, node): """ 'If' statement def for AST. interpret - runtime function for Evaluator (true of false statement depending on condition). """ condition_value = node.condition.interpret(env) if condition_value: node.true_stmt.interpret(env) else: if node.altern...
5,343,325
def update_app_downloads(): """ Update download/install stats for all apps. Spread these tasks out successively by `seconds_between` seconds so they don't hit Monolith all at once. """ chunk_size = 50 seconds_between = 2 all_ids = list(Webapp.objects.filter(status=amo.STATUS_PUBLIC) ...
5,343,326
def volCyl(radius:float, height: float) -> float: """Finds volume of a cylinder""" volume: float = pi * radius * radius * height return volume
5,343,327
def req_filter_widgets(): """ Filter widgets for requests @returns: list of filter widgets """ T = current.T from s3 import S3DateFilter, \ S3LocationFilter, \ S3OptionsFilter, \ S3TextFilter, \ s3_get_filter_...
5,343,328
def is_minimally_connected(graph: List[List[int]], num_vertices: int) -> bool: """ 1. Has no cycle. 2. All nodes are connected """ visited = set() has_cycle = is_cyclic(graph, 0, -1, visited) if has_cycle or len(visited) < num_vertices: # if num_vertices > len(visited), it means th...
5,343,329
def to_keep(path): """ :param path: :return: True if heigh and width >= 512 """ img = Image.open(path) h, w = img.size return h >= 512 and w >= 512
5,343,330
def __register(key, *additional_keys, default_handler_info, registry=None, registering_for_name="", overwrite=False): """ Internal decorator to register the non-default handlers for multimethod registry and key_fn_name are keyword arguments with defaults to make it easy to apply functools.partial on the...
5,343,331
def download_from_url_if_not_in_cache(cloud_path: str, cache_dir: str = None): """ :param cloud_path: e.g., https://public-aristo-processes.s3-us-west-2.amazonaws.com/wiqa-model.tar.gz :param to_dir: will be regarded as a cache. :return: the path of file to which the file is downloaded. """ retu...
5,343,332
def assert_array_almost_equal(x: numpy.bool_, y: bool): """ usage.scipy: 2 """ ...
5,343,333
def check(self): """Check that the SlotW27 object is correct Parameters ---------- self : SlotW27 A SlotW27 object Returns ------- None Raises ------- S27_W01CheckError You must have W0 <= W1 S27_W12CheckError You must have W1 <= W2 S27_W03Check...
5,343,334
def test_filter(qtbot, browser): """ Ensure the filter UX works """ initRowCount = browser._listView.model().rowCount() assert initRowCount > 0 # Enter a search term qtbot.keyClicks(browser._lineEdit, 'google') # Press Enter to perform the filter qtbot.keyPress(browser._lineEdit, Q...
5,343,335
def plot_sensors_connectivity(info, con, picks=None, cbar_label='Connectivity'): """Visualize the sensor connectivity in 3D. Parameters ---------- info : dict | None The measurement info. con : array, shape (n_channels, n_channels) | Connectivity The co...
5,343,336
def str_to_list_1(string): """ Parameters ---------- string : str The str of first line in each sample of sample.txt Returns --------- final_list: lst """ final_list = [] li = re.findall(r'\[.*?\]', string) for ...
5,343,337
def batched_nms(boxes, scores, idxs, iou_threshold): """ Same as torchvision.ops.boxes.batched_nms, but safer. """ assert boxes.shape[-1] == 4 # TODO may need better strategy. # Investigate after having a fully-cuda NMS op. if len(boxes) < 40000: return box_ops.batched_nms(boxes, sco...
5,343,338
def one_mini_batch(data, batch_indices): """ 产生每一次的小的batch :param data: :param batch_indices: :return: """ batch_data = { "raw_data": [data[i] for i in batch_indices], "word_id_list": [], "label_vector": [] } for data in batch_data["raw_data"]: batch_d...
5,343,339
def reset_password(reset_key): """Checks the reset key. If successful, displays the password reset prompt.""" username = auth_utils.check_reset_key(reset_key) if username is None: flask.flash( 'Invalid request. If your link has expired, then you will need to generate a new one. ' ...
5,343,340
def williams_diff_test(corr_func: SummaryCorrFunc, X: np.ndarray, Y: np.ndarray, Z: np.ndarray, two_tailed: bool) -> float: """ Calculates the p-value for the difference in correlations using Williams' Test. """ ...
5,343,341
def runProtectionScenario(scenarioName, outputDir=None, workspace=None, scenarioFile=None, xmlFiles=None, inPlace=False, unprotectFirst=False): """ Run the protection named by `scenarioName`, found in `scenarioFile` if given, or the value of config variabl...
5,343,342
def insert_into_topic_rate(): """ 插入积分表 """ postgres = DBPoolHelper(db_type='postgressql', dbname='dingxiangyuan', user='postgres', password='0000', host='localhost', port='5432') data1 = pd.read_sql(sql="select topic_url from posts_replies where floor=1", con=db_conn) data2 = pd.read_sql(sql="select to...
5,343,343
def load_students(max_meeting_seconds: int) -> Tuple[List[str], int]: """Loads student names and wait times from the database.""" try: with sqlite3.connect("students.db") as conn: cursor = conn.cursor() try: cursor.execute("SELECT name FROM students") ...
5,343,344
def coords(gd0, c, pad=True): """Return coordinates along one of the three axes. Useful for plotting:: import matplotlib.pyplot as plt plt.plot(gd.coords(0), data[:, 0, 0]) plt.show() """ L = np.linalg.norm(gd0.cell_cv[c]) N = gd0.N_c[c] h = L / N p = gd0.pbc_c[c] or...
5,343,345
def get_associated_genes(variants_list: list) -> pd.DataFrame: """ Get variant gene information from BioMart. More information on BioMart here: https://www.ensembl.org/info/data/biomart/index.html :param variants_list: the list with variant ids. :return: dataframe with variant and gene information ...
5,343,346
def crc16(data) : """Compute CRC16 for bytes/bytearray/memoryview data""" crc = _CRC16_START for b in data : crc = ((crc << 8) & 0xFFFF) ^ _CRC16_TABLE[(crc >> 8) ^ b] return crc
5,343,347
def sigma(j: int, N: int = 1) -> np.ndarray: """ """ s = [s0, s1, s2, s3] dims = [4] * N idx = np.unravel_index(j, dims) return tensor(s[x] for x in idx)
5,343,348
def backcasting( predictor, window, curves, distance="RMS", columns=("cases", "deaths"), min_series=14, step=1, ): """ Perform a backcasting performance analysis of the given model. For the sake of this method, the model is just a function that receives an epidemic curve data...
5,343,349
def print_linked_list(node): """ 在控制台上打印链表 :type node: ListNode """ visited = set() while node: if node in visited: print(f"{node.val}(环)") return visited.add(node) print(node.val, end="") node = node.next if node: print(" -> ", end="") print()
5,343,350
def write_chat(s, queue) -> None: """This method consume concurrently the queue while reading the messages written in chat. """ last_time_message_sent = datetime.datetime.now() # We exploit `CHAT_SERVER_NOP_SEC` in the config file to send a NOP # to #NOP channel for not being disconnected from the ...
5,343,351
def find_keys(d: Dict[K, V], predicate: Callable[[V], bool]) -> List[K]: """Find keys where values match predicate.""" return [k for k, v in d.items() if predicate(v)]
5,343,352
def inject_local_url(endpoint: str) -> None: """Sets tables' host to use local DynamoDB. :param endpoint: URL to your local DynamoDB service. """ for table in [ResourceTemplateDB]: table.Meta.host = endpoint # type: ignore LOG.info(f"Using local DynamoDB: {endpoint}")
5,343,353
def get_maya_property_name(prop, ignore_channel=False): """ Given a property, return a reasonable Maya name to use for it. If ignore_channel is True, return the property for the whole vector, eg. return '.translate' instead of '.translateX'. This doesn't create or query anything. It just gen...
5,343,354
def name_nonini_file(tmp_path): """Nмя существующего файла не ini формата """ file = tmp_path / "file1.ini" file.write_text('-') yield str(file) file.unlink(missing_ok=True)
5,343,355
def model_deepFlavourReference_test(Inputs,nclasses,dropoutRate=0.1,momentum=0.6): """ reference 1x1 convolutional model for 'deepFlavour' with recurrent layers and batch normalisation standard dropout rate it 0.1 should be trained for flavour prediction first. afterwards, all layers can be fixed ...
5,343,356
def load_spyrelet_class(spyrelet_name, cfg): """Load a spyrelet class from a file (whose location is defined in cfg)""" # discover spyrelet file and class spyrelet_path_str, _ = get_config_param(cfg, [CONFIG_SPYRELETS_KEY, spyrelet_name, CONFIG_SPYRELETS_FILE_KEY]) spyrelet_class_name, spyrelet_cfg_path...
5,343,357
def see_documentation(): """ This function redirects to the api documentation """ return jsonify({ '@context': responses.CONTEXT, 'rdfs:comment': 'See http://www.conceptnet.io for more information about ConceptNet, and http://api.conceptnet.io/docs for the API documentation.' })
5,343,358
def fit_imputer(df, tolerance=0.2, verbose=2, max_iter=20, nearest_features=20, imputation_order='ascending', initial_strategy='most_frequent'): """ A function to train an IterativeImputer using machine learning Args: df: dataset to impute tolerance: Tolerance of stopping fu...
5,343,359
def jhtml_render(request, file_type=None,json_file_url=None, html_template=None, json_render_dict=None, json_render_func=None, file_path=None, url_name=None, app_name=None): """ :param request: :param file_type: json/temp_json :param json_file_url: :param html_template:模板文件路径,不包含templates :para...
5,343,360
def intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name) if not os.path.exists(path): os.makedirs(path,...
5,343,361
def work(): """thread worker function""" global working, analogReadPollingPins x = 0 working = True while(working): x = x + 0.09 y = int(math.cos(x) * 100 + 150) # retcmd = "publishPin/" + str(pin) + "/3/"+ str(y) +"\n" # uart.write(codec.encode(retcmd)) fo...
5,343,362
def image(cache_path, width, height): """ Generate a custom-sized sample image """ # Create unique path size = (width, height) filename = "%sx%s.png" % (width, height) path = os.path.join(cache_path, filename) # Check if image has already been created if not os.path.exists(path): # ...
5,343,363
def truncate(text, length=30, indicator='...', whole_word=False): """Truncate ``text`` with replacement characters. ``length`` The maximum length of ``text`` before replacement ``indicator`` If ``text`` exceeds the ``length``, this string will replace the end of the string ``who...
5,343,364
def prefix_sums(A): """ This function calculate of sums of eements in given slice (contiguous segments of array). Its main idea uses prefix sums which are defined as the consecutive totals of the first 0, 1, 2, . . . , n elements of an array. Args: A: an array represents number of mushroom...
5,343,365
def polar_import(): """Import data from Polar and save as workouts""" from run4it.api.scripts import script_import_polar_exercices as script_func return script_func('polar_import')
5,343,366
def write_ilastik_batch_volume(im, fn): """Write a volume to an HDF5 file for Ilastik batch processing.""" if im.ndim == 2: im = im.reshape((1,1)+im.shape+(1,)) elif im.ndim == 3: im = im.reshape((1,)+im.shape+(1,)) else: raise ValueError('Unsupported number of dimensions in imag...
5,343,367
def dijkstra(G, Gextra, source, target_set, required_datarate, max_path_latency): """ :returns a successful path from source to a target from target_set with lowest path length """ q = DynamicPriorityQueue() q.put((source, 0.0), priority=0.0) marked = set() parents = {source: None} while not q.empty(): path_l...
5,343,368
def build_single_class_dataset(name, class_ind=0, **dataset_params): """ wrapper for the base skeletor dataset loader `build_dataset` this will take in the same arguments, but the loader will only iterate over examples of the given class I'm just going to overwrite standard cifar loading data for n...
5,343,369
def gamma_trace(t): """ trace of a single line of gamma matrices Examples ======== >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \ gamma_trace, LorentzIndex >>> from sympy.tensor.tensor import tensor_indices, tensorhead >>> p, q = tensorhead('p, q', [LorentzInd...
5,343,370
def preprocess(comment): """Pre-Process the comment""" copy_comment = copy.deepcopy(comment) # Replacing link final_comment = replace_link(copy_comment) nftokens = get_nf_tokens(comment) return final_comment, nftokens
5,343,371
def RefreshAnnotations(): """Refresh all annotations""" for Head in ida.Heads(): if GetAnnotation(Head): analysis.AnalyzeAddress(Head,Erase=False)
5,343,372
def voc_label_indices(colormap, colormap2label): """Map a RGB color to a label.""" colormap = colormap.astype('int32') idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256 + colormap[:, :, 2]) return colormap2label[idx]
5,343,373
def add_unlimited_vars_and_constraints(Market, ndds, m): """ For each ndd add binary var in m for each outgoing edge add constraint to m that sum of used edges per ndd is <= 1 for each paired donor edge add outgoing and incoming edges as binary var to m for each paired verte...
5,343,374
def make_noisy_linear(w=1, std=1): """Factory for linear function <w,x> perturbed by gaussian noise N(0,std^2)""" @Oracle def noisy_linear(x): return np.dot(x, w) + np.random.normal(scale=std) return noisy_linear
5,343,375
def update_delegator_distribution(wallet: dict) -> None: """ Update normal wallet outstanding rewards. :param wallet: wallet to update :return: None """ rewards = get_delegator_distribution(wallet["address"]) if rewards["result"]["total"]: for denom_dict in rewards["result"]["total"]...
5,343,376
def distance(turtle, x, y=None): """Return the distance from the turtle to (x,y) in turtle step units. Arguments: turtle -- the turtle x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distan...
5,343,377
def asy_ts(gp, anc_data): """ Returns a recommendation via TS in the asyuential setting. """ anc_data = copy(anc_data) # Always use a random optimiser with a vectorised sampler for TS. if anc_data.acq_opt_method != 'rand': anc_data.acq_opt_method = 'rand' anc_data.max_evals = 4 * anc_data.max_evals gp...
5,343,378
def checkParams(opts): """ 检查模块名是否符合命名规则 检查目录是否存在 """ res = {} for opt, arg in opts: if opt in ('--name'): if re.match('^[a-zA-Z_][a-zA-Z0-9_]*$', arg): res['name'] = arg else: return res elif opt in ('--dir'): r...
5,343,379
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'): """ Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf https://github.com/bharatsingh430/soft-nms """ best_bboxes = [] while len(bboxes) > 0: max_ind = np.argmax(bboxes[:, 4]) best_bbox = bboxes[max_ind] be...
5,343,380
def smart_cast(value): """Intelligently cast the given value to a Python data type. :param value: The value to be cast. :type value: str """ # Handle integers first because is_bool() may interpret 0s and 1s as booleans. if is_integer(value, cast=True): return int(value) elif is_flo...
5,343,381
def _draw_mol_with_property( mol, property, **kwargs ): """ http://rdkit.blogspot.com/2015/02/new-drawing-code.html Parameters --------- property : dict key atom idx, val the property (need to be stringfiable) """ from rdkit.Chem import Draw from rdkit.Chem import AllChem d...
5,343,382
def find_host_biz_relations(bk_host_ids: List[int]) -> Dict: """ 查询主机所属拓扑关系 :param bk_host_ids: 主机ID列表 [1, 2, 3] :return: 主机所属拓扑关系 [ { "bk_biz_id": 3, "bk_host_id": 3, "bk_module_id": 59, "bk_set_id": 11, "bk_supplier_account": "0" } ...
5,343,383
def import_students(dest, filetype="md"): """ Import students and write data to disk """ os.makedirs(dest, exist_ok=True) # Get the spreadsheet data as [(field, value), ...] data = get_spreadsheet_values(STUDENT_SPREADSHEET_ID, STUDENT_RANGE_NAME, rename_fields=STUDENT_FIELD_RENAME) f...
5,343,384
def atom_to_atom_line(atom): """Takes an atomium atom and turns it into a .cif ATOM record. :param Atom atom: the atom to read. :rtype: ``str``""" name = get_atom_name(atom) res_num, res_insert = split_residue_id(atom) return "ATOM {} {} {} . {} {} . {} {} {} {} {} 1 {} {} {} {} {} {} 1".forma...
5,343,385
def set_state_to_approval(): """ This method is called when Peer Reviewer approves a review and moves a CL to approval state """ checkListObj = retrieve_checklist_and_its_decisions( request_data_mgr.get_cl_uuid(), 'peer_review_value') checkListObj.state = CheckListState.approval.name ...
5,343,386
def combine_audio(files, target_audio, pre_normalisation=True): """ input : file names in an array (you can use videos!!) Combine audio_files into one """ import soundfile from transform_audio import wav_to_mono import os import numpy as np #Extract audio from video and conv...
5,343,387
async def edit_chat_invite_link( token: str = TOKEN_VALIDATION, chat_id: Union[int, str] = Query(..., description='Unique identifier for the target chat or username of the target channel (in the format @channelusername)'), invite_link: str = Query(..., description='The invite link to edit'), name: Optio...
5,343,388
def post_live_migrate_at_source(adapter, host_uuid, instance, vif): """Performs the post live migrate on the source host. :param adapter: The pypowervm adapter. :param host_uuid: The host UUID for the PowerVM API. :param instance: The nova instance object. :param vif: The virtual interface of the i...
5,343,389
def conv2date(dtstr,tstart=None): """Convert epoch string or time interval to matplotlib date""" #we possibly have a timeinterval as input so wrap in exception block m=re.search("([\+\-])([0-9]+)([dm])",dtstr) if m: if m.group(3) == "m": dt=30.5*float(m.group(2)) #scale with av...
5,343,390
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(MaskedBasicblock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet...
5,343,391
def logioinfo(func): """ This function is to add IO information """ def write(exec_info): """ This function is to add bucket and object Io information Parameters: exec_info Returns: write """ log.info('in ...
5,343,392
def weather(api_token, city, start, end): """ Returns an hourly report of cloud cover, wind and temperature data for the given city. The report is always in full days. Timestamps are in UTC. Start and end dates are interpreted as UTC. """ a = Astral() city = a[city] # hour=0 would give ...
5,343,393
def skimage_radon_back_projector(sinogram, geometry, range, out=None): """Calculate forward projection using skimage. Parameters ---------- sinogram : `DiscreteLpElement` Sinogram (projections) to backproject. geometry : `Geometry` The projection geometry to use. range : `Discre...
5,343,394
def get_segment_hosts(master_port): """ """ gparray = GpArray.initFromCatalog( dbconn.DbURL(port=master_port), utility=True ) segments = GpArray.getSegmentsByHostName( gparray.getDbList() ) return segments.keys()
5,343,395
def save_database(database): """ Write database back to their individual files """ # Sort all databases for db_name in database.keys(): database[db_name] = {k: v for k, v in sorted(database[db_name].items(), key=lambda item: item)} # Write database to files for filename in database: ...
5,343,396
def get_saved_albums(sp: Spotify) -> List[Dict[str, Any]]: """Returns the list of albums saved in user library""" albums = [] # type: List[Dict[str, Any]] results = sp.current_user_saved_albums(limit=50) albums.extend(results["items"]) while results["next"]: results = sp.next(results) ...
5,343,397
async def test_deprecated_run_migrations_dry_run( migrations, postgresql_conn_factory, postgresql_db ): """If running in dry run mode, pending migration(s) won't be committed. Useful for testing that migrations are error-free""" await run_migrations( migrations["postgresql_a"], postgresql_db, dr...
5,343,398
def createMergerCatalog(hd_obj, obj_conditions, cosmo, time_since_merger=1): """ Function to create Major Merger (MM) catalog @hd_obj :: header file for the object of interest @obj_conditions :: prior conditions to define the object sample @cosmo :: cosmology used in the notebook (Flat Lambda CDM) ...
5,343,399