content
stringlengths
22
815k
id
int64
0
4.91M
def _generate_mesh_simplices( *, limits, mesh_size, periodic=False, skip_origin=False ): """ Generate the starting simplices for given limits and mesh size. """ dim = len(limits) if len(mesh_size) != dim: raise ValueError( "Inconsistent dimensions: {}, {}".format(dim,...
5,289,100
def print_score_breakdown(extractor, score_breakdown): """ :type extractor: nlplingo.nn.extractor.Extractor :type score_breakdown: dict """ for index, f1_score in score_breakdown.items(): et = extractor.domain.get_event_type_from_index(index) print('{}\t{}'.format(et, f1_score.to_str...
5,289,101
def register_cmaps(*args, user=None, local=None, default=False): """ Register named colormaps. This is called on import. Parameters ---------- %(rc.cmap_args)s %(rc.cmap_exts)s %(rc.cmap_params)s See also -------- register_cycles register_colors register_fonts pro...
5,289,102
def stop_thread(thread): """未执行完线程终止.""" tid = ctypes.c_long(thread.ident) exctype = SystemExit if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invali...
5,289,103
def write_tfrecords(data_path,video_paths,action_labels, n_vids_per_batch,subset, n_frames_batch = 16, n_frames_chunk = 512): """Function to write tfrecords. :param data_path: name of tfrecords file to write :param video_paths: list contain...
5,289,104
def test_batch(): """ Testing the batch function into chunks of 100 """ full_list = list(range(0, 1000)) initial_batch = list(range(0, 100)) iteration = 0 batch_size = 100 for batch in batcher(full_list, batch_size): expected_batch = [x + (batch_size * iteration) for x in initial_batch] ...
5,289,105
def _set_up_thermo_mets(base_df: pd.DataFrame, mets_list: list, mets_conc_df: pd.DataFrame) -> tuple: """ Given the base excel input file, the list of metabolites in the model and a dataframe with metabolite concentrations averages and respective stdev, fills in the thermoMets sheet. First fills in conc...
5,289,106
def setup_constant(prefix, **kwargs): """ Set up a simple constant function model. :param prefix: Model prefix :type prefix: string :param kwargs: Keyword arguments :return: LMFIT model and parameters :rtype: (lmfit.Model, lmfit.Parameters) """ amplitude = kwargs.pop('amplitude', 5) ...
5,289,107
def subapp_css_static(filename): """ set css files. :param filename: css file name. :return: static path. """ return static_file(filename, root='kokemomo/plugins/subapp/view/resource/css')
5,289,108
def graph1D(n: int, pbc: bool = True) -> Graph: """ 1D PBC chain with n sites :param n: :return: """ g = nx.Graph() for i in range(n): g.add_node(i) for i in range(n - 1): g.add_edge(i, i + 1, weight=1.0) if pbc is True: g.add_edge(n - 1, 0, weight=1.0) ...
5,289,109
def demo_4(win): """Print single lines.""" win.erase() win.box() win.bkgd(' ', pairs[('white','black')]) try: win.move(1,1) win.addstr("What is this??", ATTRS['uline'] | pairs['yellow','pink']) win.move(3,1) win.addstr("What is this??", ATTRS['uline'] | pairs['orange'...
5,289,110
def test_wait_for_ready(main_container): """Wait for container to be ready.""" TIMEOUT = 10 for i in range(TIMEOUT): if READY_MESSAGE in main_container.logs().decode("utf-8"): break time.sleep(1) else: raise Exception( f"Container does not seem ready. " ...
5,289,111
def _solve_triangular_right(a, b, left_side, lower, trans_a): """An unrolled right-looking triangular solve on (blocked) LapaxMatrices.""" n = a.shape[-1] def solve(a, b): return _solve_triangular_left(a, b, left_side, lower, trans_a) if n == 1: return solve(a.bview(1), b.bview(1)) out = full_like(...
5,289,112
def _get_latlons(nlat, nlon): """Short summary. Parameters ---------- nlat : type Description of parameter `nlat`. nlon : type Description of parameter `nlon`. Returns ------- type Description of returned object. """ from numpy import linspace, meshgrid...
5,289,113
def abs(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in abs") return Array._new(np.abs(x._array))
5,289,114
def challenge_hash(peer_challenge, auth_challenge, user_name): """ RFC 2759 section 8.2 ChallengeHash :param peer_challenge: :param auth_challenge: :param user_name: :return: challenge example peer_challenge = "\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x5F\x2B\x3A\x33\x7C\x7E" ...
5,289,115
def var_historic(r, level=5): """ Returns the historic Value at Risk at a specified level i.e. returns the number such that "level" percent of the returns fall below that number, and the (100-level) percent are above """ if isinstance(r, pd.DataFrame): return r.aggregate(var_historic, le...
5,289,116
def ignore_covcl(): """Checking Gaussian covariances for lens0, lens0 """ with open("tests/data/tjpcov_cl.pkl", "rb") as ff: cov0cl = pickle.load(ff) ccl_tracers = ccl_tracers tracer_Noise = tracer_Noise gcov_cl_0 = tjp.cl_gaussian_cov(tracer_comb1=('lens0', 'lens0'), ...
5,289,117
def convert_to_km(distance: float, print_output: bool = True) -> Dict[str, float]: """Convert a miles distance into the double of km. Args: distance: a distance (in miles). print_output: if True, prints the progress. Returns: A dictionary with two keys ('original' and 'converted')....
5,289,118
def discriminator_loss(D, real_images, fake_images): """Loss computed to train the GAN discriminator. Args: D: The discriminator. real_images of shape (batch_size, nc, 28, 28): Real images. fake_images of shape (batch_size, nc, 28, 28): Fake images produces by the generator. Returns: ...
5,289,119
def Lucas_chain(n, f, g, x_0, x_1): """ Given an integer n, two functions f and g, and initial value (x_0, x_1), compute (x_n, x_{n+1}), where the sequence {x_i} is defined as: x_{2i} = f(x_i) x_{2i+1} = g(x_i, x_{i+1}) """ binary = arith1.expand(n, 2) u = x_0 v = x_1 while b...
5,289,120
def build_input_from_segments( history, reply, tokenizer, lm_labels=False, with_eos=True ): """ Build a sequence of input from 2 segments: history and candidate reply. """ bos, eos, speaker1, speaker2 = tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS[:-1]) # build input sequence as: # [bos, person2, ...
5,289,121
async def setup_guardian_fixture(hass, config, data_ping): """Define a fixture to set up Guardian.""" with patch("aioguardian.client.Client.connect"), patch( "aioguardian.commands.system.SystemCommands.ping", return_value=data_ping, ), patch("aioguardian.client.Client.disconnect"), patch( ...
5,289,122
def aiohttp_socket_timeout(socket_timeout_s): """ Return a aiohttp.ClientTimeout object with only socket timeouts set. """ return aiohttp.ClientTimeout(total=None, connect=None, sock_connect=socket_timeout_s, sock_read=sock...
5,289,123
def get_contributions_from_file(site, username): """Get a list of Wikipedia-namespace contributions.""" with open("my-contribs.json") as my_contribs_file: data = json.load(my_contribs_file) for contrib in data: time = datetime.datetime.strptime(contrib["timestamp"], ...
5,289,124
def alignment_to_search_path(algn): """ Given an alignment, make searchpath. Searchpath must step exactly one position in x XOR y at each time step. In the case of a block of deletions, the order found by DP is not meaningful. To make things consistent and to improve the probability of recoveri...
5,289,125
def setLCData(*args): """Access and changes protected lc_data class data. The returned value representation is an array of data from load cells Parameters ---------- lc_data: an array containing the load cell data """ lcd.lc_data = args[0] # return lcd.lc_data
5,289,126
def getMulitples(indices): """Return a subset with no multiples (filters out the bad ones).""" multiples = [] added = [] for i in range(0, len(indices) - 1): if indices[i][0] == indices[i + 1][0]: added.append(indices[i]) elif added: added.append(indices[i]) ...
5,289,127
async def test_lock_locked( hass: HomeAssistant, mock_entry: MockEntityFixture, doorlock: tuple[Doorlock, str], ): """Test lock entity locked.""" new_bootstrap = copy(mock_entry.api.bootstrap) new_lock = doorlock[0].copy() new_lock.lock_status = LockStatusType.CLOSED mock_msg = Mock() ...
5,289,128
def get_pourbaix_info(entry: dict) -> dict: """ Grabs the relevant pourbaix entries for a given mpid from Materials Project and constructs a pourbaix diagram for it. This currently only supports MP materials. Args: entry: bulk structure entry as constructed by catlas.load_bulk_st...
5,289,129
def do_math(a, b, operator): """Helper function that performs computation between two numbers.""" if operator == "+": return int(b) + int(a) elif operator == "-": return int(b) - int(a) elif operator == "*": return int(b) * int(a) elif operator == "/": return int(b)...
5,289,130
def getFrequencyBands(sessionId): """ Get the frequency bands supported by this server. Returns: A list of frequency bands for the sensors managed by this server. """ @testcase def getFrequencyBandsWorker(sessionId): try: if not Config.isConfigured(): util.de...
5,289,131
def test_Get_all_POST(client): """ **GIVEN** a Flask application configured for testing\n **WHEN** a valid endpoint for retrieving all files of a type is hit with a POST request\n **THEN** check that the response is valid for a 405 response (Method not Allowed) """ for endpoint in ['song', 'podc...
5,289,132
def deg_to_arcsec(angle: float) -> float: """ Convert degrees to arcseconds. Args: angle: Angle in units of degrees. Returns: angle: Angle in units of arcseconds. """ return float(angle) * 3600.
5,289,133
def pixel_level_peak_finder_1d(correlation_lines: np.ndarray) -> np.ndarray: """ This function returns a numpy array containing the location of the maximum surface value to pixel level accuracy for each row of the input matrix. :return: The location of the maximum surface values to pixel level accuracy...
5,289,134
def Shift(**kwargs): """ Calculates register shifts between strands based on their pairing and length """ refbluefile = kwargs.get('refblue') seg1 = kwargs.get('seg1') seg2 = kwargs.get('seg2') refblue = Blueprint(refbluefile) nseg1 = len( refblue.segment_...
5,289,135
def mapping_stats(output_dir): """This is UID level mapping summary, the config file is in parent dir""" output_dir = pathlib.Path(output_dir).absolute() config = get_configuration(output_dir.parent / 'mapping_config.ini') mode = config['mode'] if mode == 'mc': final_df = mc_mapping_stats(o...
5,289,136
def ul_lands_download(save_dir = None): """ Downloads las files from University Lands Texas This function downloads files from the university lands ftp website located at publiftp.utlands.utsystem.edu. It inventories readable logs into a csv file containing header data in the save_dir. ...
5,289,137
def cc_random_payoffs(): """ Plotting for experiments with random 3x3 and 32x32 experiments if the results were stored by run_single_config.py """ exp_dir = "Experiments/PaperExperiments/{}/".format("32x32") baseline_dir = "Experiments/PaperExperiments/{}/".format("1598034745") with open(ex...
5,289,138
def copyExecutable(dir, name): """Copy the built exe to the output directory.""" kepath = "./Release" keexe = "kinderegg.exe" # specified in CMakeLists.txt shutil.copyfile( os.path.join(kepath, keexe), os.path.join('..', 'tools', dir, name+'.exe')) # Copy SDL2.dll to output dir s...
5,289,139
async def test_ap_fails(injector): """Async providers must not be usable in sync consumers""" class A: pass a = A() @injector.consumer def consumer(a_: A): assert a_ is a @injector.provider async def bean() -> A: return a with pytest.raises(pyserp.InjectionErr...
5,289,140
def gru_run(params, x_t): """Run the Vanilla RNN T steps, where T is shape[0] of input. Args: params: dict of GRU parameters x_t: np array of inputs with dim ntime x u Returns: 2-tuple of np arrays (hidden states w dim ntime x n, outputs w dim ntim x o) """ return gru_run_with_h0(params, x_...
5,289,141
def set_window_width(image, MIN_BOUND=-1000.0, MAX_BOUND=400.0): """设置窗宽""" image[image > MAX_BOUND] = MAX_BOUND image[image < MIN_BOUND] = MIN_BOUND return image
5,289,142
def assert_allclose( actual: numpy.ndarray, desired: List[Union[int, float]], atol: float ): """ usage.scipy: 5 usage.statsmodels: 1 """ ...
5,289,143
def _process_merge(p1_ctx, p2_ctx, ctx): """compute the appropriate changed files for a changeset with two parents This is a more advance case. The information we need to record is summarise in the following table: ┌──────────────┬──────────────┬──────────────┬──────────────┬──────────────┐ │ diff...
5,289,144
def create_mmt_encoder_inputs(data_cfg: cfg.DataConfig): """Creates inputs for `MmtEncoder`.""" patch_embedding_size = (data_cfg.patch_size ** 2) * 3 num_patch_per_row = data_cfg.image_size // data_cfg.patch_size num_patches = num_patch_per_row ** 2 max_seq_len = data_cfg.max_seq_len word_ids = tf.keras....
5,289,145
def add_course_without_teacher_and_students(access_token): """ Adding a course just setting course name as ADMIN""" data = { "name": "math" } headers = { 'Authorization': f'JWT {access_token}', 'Content-Type': 'application/json' } data = json.dumps(data) response = r...
5,289,146
def update_chart_info(_figure, chart_data_json_str): """ A callback function to set the sample count for the number of samples that have been displayed on the chart. Args: _figure (object): A figure object for a dash-core-components Graph for the strip chart - triggers the callback....
5,289,147
def compare_samples(samples, pipeline, dask_client, verbose): """Compare several samples in a All vs All fashion. """ if len(samples) == 1: raise ValueError( "It's necessary to have at least two samples for the comparison" ) sample_sets = [ SampleSet( [De...
5,289,148
def delete_vnet_lxc_profile(name): """ Deletes a VNet specific LXC profile Profile must not be used when deleting :param str name: The LXC profile to delete """ # Check if the profile even exists if not check_if_lxc_profile_exists(name): logger.warning("Tried to delete LXC profile {}...
5,289,149
def record_copy_all(node, **kwargs): """ A default rcd implementation that copies all kwargs to the tape. the impl is used for the vjp and vjp primitives. the impl is can be used for the apl primitives if no rcd is given; but we use 'record_copy_autodiff' to save a much smaller subset ...
5,289,150
def _merge_annotations(curr,new): """ Private function. Don't use directly. This function will modify the annotations and docstring of `curr` to incorporate those in `new` """ # Merge annotations by items in new for k,v in new.__annotations__.items(): # Get a set of the annotati...
5,289,151
def test_raw_html_648a(): """ Test case 648a: variation of 644 with shorter """ # Arrange source_markdown = """foo <!ELEMENT>""" expected_tokens = [ "[para(1,1):]", "[text(1,1):foo \a<\a&lt;\a!ELEMENT\a>\a&gt;\a:]", "[end-para:::True]", ] expected_gfm = """<p>fo...
5,289,152
def split_df_train_test(data: pd.DataFrame, perc_train: float) -> Tuple[list, list]: """Create train test split""" # get percentages assert perc_train >= 0.0 assert perc_train <= 1.0 # get number of examples to use for training num_train = int(perc_train * len(data)) # get number of exampl...
5,289,153
def read_file(filename): """ Return the content of a file as a list of strings, each corresponding to a line :param filename: string: location and name of the file :return: content of filename """ with open(filename, 'r') as ofile: content = ofile.read().splitlines() return content
5,289,154
def parse_record(raw_record): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized ...
5,289,155
def helicsFederateRegisterGlobalTypeInput(fed: HelicsFederate, name: str, type: str, units: str) -> HelicsInput: """ Register a global publication with an arbitrary type. The publication becomes part of the federate and is destroyed when the federate is freed so there are no separate free functions for subs...
5,289,156
def main(): """ Main function Returns: None """ configfile = "config.json" logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) try: logging.info("Opening config file.") f = open(configfile, "tr") except FileNotFoundError: logging.info("File not found...
5,289,157
def get_cluster(cluster_identifier: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClusterResult: """ Provides details about a specific redshift cluster. ## Example Usage ```python import p...
5,289,158
def fiRna(exName: str, filePath: str = './', copyPath: str = './copy', pattern: str = "0:0>4", boolCopy: bool = True, boolExist: bool = False): """fiRna. 批量重命名 传入扩展名,文件路径及复制路径 """ # 检查 filePath 文件夹是否存在,否则报错退出 pathCheck(filePath) # 提取文件夹下所有文件...
5,289,159
def predict( mixture: str, results_dir: str, split: str, batch_size: int, model_parallelism: int, tpu_name: str, tpu_topology: str, ) -> None: """Predict with the model located at RESULTS_DIR on MIXTURE.""" # Validate arguments. if not results_dir.startswith("gs://"): ra...
5,289,160
def translate_to_origin(structure, weight="mass", atom_mask=None, dimension=None): """Translate a structure to the origin based on the centroid of the whole system or a subset of atom(s). Parameters ---------- structure : str or :class:`parmed.Structure` Molecular structure containing coordinat...
5,289,161
def score_1(game, player): # 82.14% """ Heuristics computing score using #player moves - k * #opponent moves :param game: game :param player: player :return: score """ if game.is_winner(player) or game.is_loser(player): return game.utility(player) opponent = game.get_opponent(p...
5,289,162
def parse_line( line ): """Returns data located in the line.""" tokens = line.split() return int(tokens[1]), tokens[2], ( int(tokens[4]), # n_i int(tokens[6]), # s_i )
5,289,163
def find_ancestors(starting_resource, full_name): """Find the ancestors for a given resource. Take advantage of the full name from the data model which has the entire hierarchy. Keeping this outside of the class, because the class is mocked out during testing. Args: starting_resource ...
5,289,164
def select_from_existing_derivations(): """ Which derivation does the user want to review? Alternatively, the user can generate a PDF >>> select_from_existing_derivations() """ trace_id = str(random.randint(1000000, 9999999)) logger.info("[trace page start " + trace_id + "]") try: ...
5,289,165
async def is_streamable(filename: str) -> bool: """Return if a file is streamable by pyatv. This method will return if the file format of the given file is supported and streamable by pyatv. It will never raise an exception, e.g. because the file is missing or lack of permissions. """ try: ...
5,289,166
def forward_pass(x: np.ndarray, weights: np.ndarray, bias: float) -> np.ndarray: """ Method that calculates the activation of the sigmoid function from a given input, weights and biases. :param x: input data :param weights: tuple with the weights :param bias: value of the biases :return: ac...
5,289,167
def get_long_description(): """ Provides the long description. """ with open("README.rst", "r", encoding="utf-8") as file_stream: return file_stream.read()
5,289,168
def get_connections(ccs_path): """ Returns list of installed connection names. Searches "<ccs_path>/ccs_base/common/targetdb/connections" directory for installed connection names. Args: ccs_path (str): full path to ccs installation to use Returns: list: connection names Raise...
5,289,169
def escape_latex(strng): """Consistently escape LaTeX special characters for _repr_latex_ in IPython Implementation taken from the IPython magic `format_latex` Examples -------- escape_latex('disease_rate') # 'disease\_rate' Parameters ---------- strng : str string to esc...
5,289,170
def list_subnets(sort_by='name'): """ Get list of subnets from maas server CLI Example: .. code-block:: bash salt 'maas-node' maasng.list_subnets """ subnets = {} maas = _create_maas_client() json_res = json.loads(maas.get(u'api/2.0/subnets/').read()) for item in json_res:...
5,289,171
def stream_profile_sample(self, stream_data): # FileData object """Profiles a stream container: look at it as one big blob""" tracks = {} stream_data.crc32 = 0x0 # start value crc meta_length = 0 stream_data.crc32 = calc_crc32(stream_data.name) # do track stuff track = TrackData() track.track_number = 1 tr...
5,289,172
def multinomial_as_basic(multinomial, *symbols): """ Converts the multinomial to Add/Mul/Pow instances. multinomial is a dict of {powers: coefficient} pairs, powers is a tuple of python integers, coefficient is a python integer. """ l = [] for powers, k in multinomial.iteritems(): t...
5,289,173
def nvme_discover(uri): """Discover target.""" u = urlparse(uri) port = u.port host = u.hostname command = "sudo nvme discover -t tcp -s {0} -a {1}".format(port, host) output = subprocess.run( command, check=True, shell=True, capture_output=True, encoding="utf-8" ) if not u.path...
5,289,174
def display_summary(user, sender_id, callback=send_message): """displays a submit score summary Parameters: user: the user dictionary (dict) sender_id: the sender facebook id (? something) callback: the thing to call with a result (function) """ summary = game_summary(user) ...
5,289,175
def topic_modelling(all_data_t: List[List[float]], tfidf: TfidfVectorizer, n_keywords: int, param_grid=TRAIN_PARAM_GRID_LDA, retrain=False, plot=False, random_seed=42) -> Tuple[BaseEstimator, Lis...
5,289,176
def get_gpu_memory() -> List[int]: """Query GPU's for amount of VRAM Modified from: https://stackoverflow.com/questions/59567226/how-to-programmatically-determine-available-gpu-memory-with-tensorflow Returns ------- VRAM, List[int] Total GPU VRAM in bits for each GPU. """ _outp...
5,289,177
def die_screaming(instr): """ Make sure we exit in a way that will get Jenkins's attention. """ LOG.error(instr) sys.exit(1)
5,289,178
def smiles2inchi(smiles): """ Converts SMILES to InChi. This method accepts urlsafe_base64 encoded string containing single or multiple SMILES optionally containing header line, specific to *.smi format. cURL examples: curl -X GET ${BEAKER_ROOT_URL}smiles2inchi/$(cat aspirin_with_header.smi | base64 -w 0 | tr ...
5,289,179
def list_vaults_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]: """Lists all vaults. """ max_results = int(args.get('max_results', 0)) raw_response = client.list_vaults(max_results) vaults = raw_response.get('vault') if vaults: title = f'{INTEGRATION_NAME} - Total of {len(...
5,289,180
def strip_ddp_state_dict(state_dict): """ Workaround the fact that DistributedDataParallel prepends 'module.' to every key, but the sampler models will not be wrapped in DistributedDataParallel. (Solution from PyTorch forums.)""" clean_state_dict = type(state_dict)() for k, v in state_dict.items(): ...
5,289,181
def test_container_count(dockerc): """Verify correct number of containers are running.""" # stopped parameter allows non-running containers in results assert ( len(dockerc.containers(stopped=True)) == 1 ), "Wrong number of containers were started."
5,289,182
def parameter_attention(x, total_key_depth, total_value_depth, output_depth, memory_rows, num_heads, dropout_rate, name=None): """Attention over param...
5,289,183
def plot_gp_plotly( model: GPModel, mins: TensorType, maxs: TensorType, grid_density=20 ) -> go.Figure: """ Plots 2-dimensional plot of a GP model's predictions with mean and 2 standard deviations. :param model: a gpflow model :param mins: list of 2 lower bounds :param maxs: list of 2 upper bou...
5,289,184
def pareto(all_y, maximize=False): """ Returns the indices of Pareto-optimal solutions. Args: Y [list]: A list of lists containing values to be evaluated for Pareto- optimality Returns: list - The indices of the entries which are Pareto-optimal """ all_y = np.asarra...
5,289,185
def _import(module_name, class_name): """ Return class of the module_name, where module_name is of the form package.module (testoob's Asserter, which does simple __import__, returns package, not package.module in this situation). """ mod = __import__(module_name) components = module_name.spl...
5,289,186
def test_compute_id_2NN_wprior(): """Test that the id estimation with a Bayesian 2NN works correctly.""" de = DensityEstimation(coordinates=X) de.compute_id_2NN_wprior() assert pytest.approx(de.intrinsic_dim, abs=0.0001) == 1.8722
5,289,187
def plot_roc(labels, score, title='ROC', verbose=True): """Plot ROC curve Parameters ---------- labels : np.ndarray vector of ground truth score : np.ndarray vector of scores assigned by classifier (i.e. clf.pred_proba(...)[-1] in sklearn) title : str title of p...
5,289,188
def delete_user(username: str): """ Parameters ---------- username : str, required Returns ------- Response: { "deleted": true, } Raises ------ HTTPException """ response = False try: username_constraint(username) ...
5,289,189
def Scan_Mono_Go(scanDIM,start,stop,step,settling_time=0.2,**kwargs): """Starts a mono scan for a given scan dimension Logging is automatic: use **kwargs or the optional logging arguments see scanlog() for details """ scanIOC=BL_ioc() current_energy=caget('29idmono:ENERGY_SP') Scan_Mono(s...
5,289,190
def p_primary(p): """primary: variable_access | unsigned_constant | function_designator | set_constructor | LPAREN expression RPAREN | NOT primary"""
5,289,191
def imread(image_name, colorspace="RGB"): """ Reads image and returns RGB numpy array Parameters: image_name: Image path , str colorspace: RGB or BGR, str Returns: img: numpy array """ img = cv2.imread(image_name) if colorspace == "RGB": img = cv2.cvtColor(img...
5,289,192
def _extract_time_series(data, time_series_name='values'): """ Extract specific time series from provided pandas DataFrame and return as a pandas Series """ # If it's already a series, just return it if isinstance(data, pd.Series): return data if time_series_name not in data: r...
5,289,193
def residual_resampling(weights): """Residual resampling. The counts in each bin are floor(w*N) + N' where N' is sampled from a multinomial with the residual weights.""" N = weights.shape[0] counts = np.floor(weights*N) R = int(np.sum(counts)) new_weights = (weights*N - counts)/(N-R) counts ...
5,289,194
def get_reftypes(exp_type, cal_ver=None, context=None): """Based on the exposure type, CAL s/w version, and CRDS context, determine the list of applicable reference file types. """ return []
5,289,195
def filter_config_set_by_host_name( cfgD, hostname ): """ """ for mach,specD in list( cfgD.items() ): if not satisfies_host_match( hostname, specD ): cfgD.pop( mach )
5,289,196
def mix(n = 1): """Accumulate n composite samples from the active generators.""" # Gather samples and count notes. s = np.zeros(n, dtype=np.float32) n_notes = 0 for note in set(notemap): e = note.envelope() if e == None: # Release is complete. Get rid of the note. ...
5,289,197
def train_step(grid, weights, optimizer, mov, fix): """ Train step function for backprop using gradient tape :param grid: reference grid return from layer_util.get_reference_grid :param weights: trainable affine parameters [1, 4, 3] :param optimizer: tf.optimizers :param mov: moving image [1, m...
5,289,198
def register_pooling(key, module): """ Register a customized GNN pooling layer (for graph classification). After registeration, the module can be directly called by GraphGym. Args: key (string): Name of the module module: PyTorch module """ register(key, module, pooling_dict)
5,289,199