content
stringlengths
22
815k
id
int64
0
4.91M
def train_cn_image(model, train_loader, optimizer): """Train for one epoch.""" print('running train_cn_image') batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() model.train() end = time.time() for i, (input,...
5,303,100
def checksum(basenum): # type: (str) -> str """ Will compute the checksum digits for a given CNPJ base number. `basenum` needs to be a digit-string of adequate length. """ verifying_digits = str(hashdigit(basenum, 13)) verifying_digits += str(hashdigit(basenum + verifying_digits, 14)) retur...
5,303,101
async def on_startup(): """App startup handler""" initialize_logging() # Initialize api api_wrapper.async_initialize()
5,303,102
def process_move(grid, move): """Returns True if the user is still alive, False otherwise.""" user_x, user_y = move.x, move.y cell = grid[user_x][user_y] if move.flag: cell.flag = not cell.flag return GameState.ALIVE cell.revealed = True if cell.is_bomb: return GameSta...
5,303,103
def factorial_iter(num: int) -> int: """ Return the factorial of an integer non-negative number. Parameters ---------- num : int Raises ------ TypeError if num is not integer. ValueError if num is less than zero. Returns ------- int """ if not ...
5,303,104
def _AddBaselineToBaselineNameToBaselineMap(baseline): """Add entry into BASELINE_NAME_TO_BASELINE_NAME_MAP for the given baseline class.""" baseline_name = dgen_decoder.BaselineName(baseline) bases = BASELINE_NAME_TO_BASELINE_MAP.get(baseline_name) if bases == None: bases = set() BASELINE_NAME_TO_...
5,303,105
def verify_user_registration(DB): """ Validate user registration """ cirrus_config.update(**config["CIRRUS_CFG"]) validation_check(DB)
5,303,106
def run_sepnmf(V): """ Run standard nonnegative matrix factorization. :param V: Target matrix to estimate. :type V: :class:`numpy.matrix` """ # Euclidean rank = 10 sepnmf = nimfa.SepNmf(V, rank=rank, selection='spa') fit = sepnmf() print_info(fit) sepnmf = nimfa.SepNmf(V, ...
5,303,107
def json_to_trec(dataset_file_path: str, prediction_file_path: str, output_file_path: str, run_name: str="", dataset_format: str = "trec", max_depth: int = 1000) -> None: """ :param dataset_file_path: json file :param pred...
5,303,108
def test_stdin_bad_and_bad(style_checker): """Style check test against bad + bad (via stdin) """ style_checker.set_year(2006) stdin_buf = '\n'.join(['ada12-no-first-line-comment.adb', 'gprep_check-ko.adb']) p = style_checker.run_style_checker('hello', ...
5,303,109
def update_Q(Qsa, Qsa_next, reward, alpha, gamma): """ updates the action-value function estimate using the most recent time step """ return Qsa + (alpha * (reward + (gamma * Qsa_next) - Qsa))
5,303,110
def load_psnr(loss_file): """ load image psnr or optical flow psnr. :param loss_file: loss file path :return: """ with open(loss_file, 'rb') as reader: # results { # 'dataset': the name of dataset # 'psnr': the psnr of each testing videos, # } # psnr_...
5,303,111
def check_num(prompt: str) -> float: """Function to check if users input is an integer""" while True: try: num = int(input(prompt)) return num except Exception as e: print(e)
5,303,112
def test_component_map(): """ # TODO: Test component map returns components correctly. Returns ------- None """ Component.reset_ids() with open("config.json") as config_file: data = json.load(config_file) new_arch = TablaTemplate(data) comp_map = new_arch.component_map...
5,303,113
def test_clp_idaes_solve(): """ Make sure there is no issue with the solver class or default settings that break the solver object. Passing a bad solver option will result in failure """ m, x = lp() solver = SolverFactory('clp') solver.solve(m) m.display() assert pytest.approx(x) ==...
5,303,114
def test_query_device_invalid_sort_direction(): """Test an attempt to sort device query results in an invalid direction.""" api = call_cbcloud_api() with pytest.raises(ApiError): api.select(Device).sort_by("policy_name", "BOGUS")
5,303,115
def _convert_to_time_range(timestamp=None): """Create a timestamp range from an HBase / HappyBase timestamp. HBase uses timestamp as an argument to specify an exclusive end deadline. Cloud Bigtable also uses exclusive end times, so the behavior matches. :type timestamp: int :param timestamp: (...
5,303,116
def plot_graph(history: Dict[str, float], loss_fn: Callable, optimizer: str) -> None: """Renders and saves an animation of the data passed in the `history` parameter. Parameters ---------- history : dict[str, float] The values of the weights after every iteration of gradient ...
5,303,117
def deploy(): """ :param token: Token The token to deploy :return: bool: Whether the operation was successful """ if not CheckWitness(TOKEN_OWNER): print("Must be owner to deploy") return False if not Get(context, 'initialized'): # do deploy logic Put(co...
5,303,118
def add_master_legend(mp, exclude_panels=None, loc='upper center', exclude_labels=[], **kwargs): """ Make a big legend! """ handles, labels = [], [] if 'bbox_to_anchor' not in kwargs: kwargs['bbox_to_anchor'] = (0.5, 1.0) if isinstance(mp, MultiPanel): for k, ax in enumer...
5,303,119
def make_messages(locale=None, domain='django', verbosity=1, all=False, extensions=None, symlinks=False, ignore_patterns=None, no_wrap=False, no_location=False, no_obsolete=False, stdout=sys.stdout, include_paths=None): """ Uses the ``locale/`` directory from the Django Git tree or an applic...
5,303,120
def rate_of_change_kernel_n(ohlcv, window_size, out, res_index): """ Calculate the rate of change for the given data. https://en.wikipedia.org/wiki/Momentum_(technical_analysis) :param ohlcv: link to GPU memory with array of timestamp, Open, High, Low, Close, Volume :param window_size: window size ...
5,303,121
def euclidean_silhouette(X, z): """ Computes the average Silhouette Coefficient with euclidean distance Args: X (array<m,n>): m x n float matrix with datapoints z (array<m>): m-length integer vector of cluster assignments Returns: A scalar float with the silhouette score ""...
5,303,122
def in_tcltk_website(text): """Receives the tcltk website text string and returns the range where the colors are written.""" start = text.find('<PRE>') + len('<PRE>') end = text.find('</PRE>') colors = text[start:end] return colors
5,303,123
def nodemodel_spec(): """Check NodeModel's subclass spec.""" for missing in APIs: insuccifient_attrs = APIs[:] insuccifient_attrs.remove(missing) dict_attrs = {name: lambda self: self for name in insuccifient_attrs} NewNodeModel = type('NewNodeModel', (nodemodel.base.NodeModel, )...
5,303,124
def write_centre(draw, y, text, font, fill, img_width): """ Draws centre-aligned text. """ text_width = font.getsize(text)[0] draw.text(((img_width-text_width)/2,y), text, font=font, fill=fill)
5,303,125
def remove(path): """Delete a file @param path (string) Delete filepath """ os.remove(path)
5,303,126
def task_salt_tree() -> types.TaskDict: """Deploy the Salt tree in ISO_ROOT.""" return { 'actions': None, 'task_dep': [ '_deploy_salt_tree:*', ], }
5,303,127
def _convert_all_svg_to_pdf(path): """Convert all svg files on path "path" to pdf. :param path: Path to the root directory with svg files to convert. :type path: str """ cmd = "inkscape -D -z --file={svg} --export-pdf={pdf}" svg_files = get_files(path, "svg", full_path=True) for svg_file ...
5,303,128
def get_diff(l1, l2): """ Returns the difference between two lists. """ diff = list( list(set(l1) - set(l2)) + list(set(l2) - set(l1)) ) return diff
5,303,129
def mlurl(parser, token): """ Based on django url tag. Just adds language postfix to view name for multilinagual stuff. """ bits = token.contents.split(' ') if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" " (path to a view)" % ...
5,303,130
def card_list_difference(cards1: List[card.Card], cards2: List[card.Card]) -> List[card.Card]: """Returns the cards that were in one set but not in another.""" in_cards2: List[bool] = [] for card1 in cards1: remained: bool = False for card2 in cards2: if card1 == card2: ...
5,303,131
def shapes(molecules, threshold, output_dir, plot_suffix): """ Plot molecule shapes of all molecules in dictionary. """ fig, ax = plt.subplots(figsize=(5, 5)) for name in molecules: out_file = ( f"{output_dir}/" f"{name.replace(' ', '_').replace('/', '__')}" ...
5,303,132
def check_feature_set(feature_sets): """ Ensure the # of people is the same in each feature set """ if feature_sets == {}: raise AssertionError("no feature sets present") N = None for ft in feature_sets: N2 = feature_sets[ft].shape[0] if N is None: N = N2 ...
5,303,133
def get_inner_edges(bm, boundary_type): """get the edges to run maze on ignore the outer edge of selection and any edges with any verts on boundary input: bm: the bmesh for the whole mesh output: sel_geom: list of selected verts, edges, faces inner_edges: list of BMEdge """ ...
5,303,134
def read_exif_from_file(filename): """Slices JPEG meta data into a list from JPEG binary data. """ f = open(filename, "rb") data = f.read(6) if data[0:2] != b"\xff\xd8": raise InvalidImageDataError("Given data isn't JPEG.") head = data[2:6] HEAD_LENGTH = 4 exif = None while...
5,303,135
def geo_to_suppl(accession, GEO): """Retrieve supplemental files associated with a GEO ID. :param accession: GEO ID :type id: str :param GEO: Type of GEO entry, either GSM or GSE :type id: str :return: a list of dictionaries with supplemental file information :rtype: list """ if ...
5,303,136
def resnet(input_, dim_in, dim, dim_out, name, use_batch_norm=True, train=True, weight_norm=True, residual_blocks=5, bottleneck=False, skip=True): """Residual convolutional network.""" with tf.variable_scope(name): res = input_ if residual_blocks != 0: res = con...
5,303,137
def create_form_data(self, request, data_map, encoding = "utf-8"): """ Processes the data map, creating a single map with all the attributes described in the form data format. :type request: Request :param request: The request to be used. :type data_map: Dictionary :param data_map: ...
5,303,138
def identical_prediction_lists(prev_prediction_list, curr_prediction_list): """ Check if two predictions lists are the same :param prev_prediction_list: list Last iterations predictions :param curr_prediction_list: list current iterations predictions :return: bool false = not identical, true = ident...
5,303,139
def adder(message, *varargs): """Add any integers passed to us. There isn't any formal way to document functions, although there are various doc tools. The following is an example of epydoc. @type message string @param message Require. What to announce before our sum? @param *varargs Optional. Numbers to ad...
5,303,140
def emailFireNotification(constants, cameraID, imgPath, annotatedFile, driveFileIDs, fireSegment, timestamp): """Send an email alert for a potential new fire Send email with information about the camera and fire score includeing image attachments Args: constants (dict): "global" contants ...
5,303,141
def test_keep_msbs_function(): """Verify functions.keep_msbs """ overflows = [x.name for x in uut.properties.Overflow] + [''] roundings = [x.name for x in uut.properties.Rounding] + [''] alerts = [x.name for x in uut.properties.Alert] + [''] strip_sn = lambda s: s.split('SN')[-1].lstrip('0123456...
5,303,142
def modify_jws_and_forge_signature(raw_jws: bytes, payload_modify_function=None) -> bytes: """Take in a JWS in raw form (concatenated URL-safe base64), modify its payload using payload_modify_function, and then forge a signature with a new CA that will be attached to the cert chain. Arguments: ra...
5,303,143
def convert_session_to_sample(session_file, train_file, dev_file, dev_num=10000): """ convert_session_to_sample """ data_samples = [] with open(session_file, 'r') as f: for i, line in enumerate(f): session = json.loads(line.strip(), encoding="utf-8") sample = dict() ...
5,303,144
def write_counts(in_file, counts, out_file): """ Write read counts to output file """ # open input file with open(in_file) as csvfile: # Auto detect dialect of input file dialect = csv.Sniffer().sniff(csvfile.readline(), delimiters=";,\t") csvfile.seek(0) reader...
5,303,145
def get_dynamic_tenant_prefixed_urlconf(urlconf, dynamic_path): """ Generates a new URLConf module with all patterns prefixed with tenant. """ from types import ModuleType from django.utils.module_loading import import_string class LazyURLConfModule(ModuleType): def __getattr__(self, at...
5,303,146
def get_sigma(voxel_size_z=None, voxel_size_yx=100, psf_z=None, psf_yx=200): """Compute the standard deviation of the PSF of the spots. Parameters ---------- voxel_size_z : int or float or None Height of a voxel, along the z axis, in nanometer. If None, we consider a 2-d PSF. voxel_...
5,303,147
def test_replace_phone_numbers(): """Test case""" text = "یعنی لائن آف کنٹرول پر فائربندی کا معاہدہ 555-123-4567 میں ہوا تھا" proc_text = "یعنی لائن آف کنٹرول پر فائربندی کا معاہدہ *PHONE* میں ہوا تھا" assert replace_phone_numbers(text, '*PHONE*') == proc_text
5,303,148
def main(): """Main function""" module = build_module() config = Config(module, "vpc") try: resource = None if module.params.get('id'): resource = True else: v = search_resource(config) if len(v) > 1: raise Exception("Found mo...
5,303,149
def read_data(path): """Reads data file from disk.""" file = '' for file in os.listdir(path): if file.startswith('data'): break assert file.startswith('data'), "data not found" extension = os.path.splitext(file)[1].lstrip('.') info = 'file extension must be csv, parquet, or pickle' ...
5,303,150
def eval_step( model: nn.Module, params_dict: Dict[str, Any], batch: Dict[str, jnp.ndarray]) -> Tuple[Union[float, List[float]], Any]: """Evaluates the given model on the batch. Args: model: Module to compute predictions. params_dict: Replicated Flax/Linnen parameters dict. batch: Inputs that s...
5,303,151
def test_json(): """ Test auto and auto_add parameter of property >>> db = get_connection('sqlite://') >>> #db.echo = True >>> db.metadata.drop_all() >>> db.metadata.clear() >>> class User(Model): ... username = Field(str, max_length=40) ... memo = Field(JSON, default={}) ...
5,303,152
def harris(img, peaking=(255, 0, 0)): """ Harris corner detection """ img, gray = rgba2rgb(img), rgba2gray(img) dest = cv.cornerHarris(src=gray, blockSize=2, ksize=5, k=0.1) dest = cv.dilate(dest, None) img[dest > 0.01 * dest.max()] = peaking return img, dest,
5,303,153
def _get_paragraphs(response): """Parse HTML and extract paragraphs Args: response: HTML response from Requests-HTML Returns: HTML element """ try: paragraphs = [] for paragraph in response.html.find('p'): paragraphs.append(paragraph.text) return...
5,303,154
def test_slug_called( mocker: MockFixture, tech_group_factory: factories.TechGroupFactory ) -> None: """Test slug is created if not passed.""" mocked_slugger = mocker.patch("domain.utils.generate_unique_slug") mocked_slugger.return_value = "python" tech_group = tech_group_factory(name="Python", desc...
5,303,155
def storage_delete(sender, instance, **kwargs): """When deleting a User object, deletes all the files linked to this object.""" shutil.rmtree( instance.get_storage_absolute_path(), ignore_errors=True, onerror=None, )
5,303,156
def preprocess_box(data): """Pre-process data to take correct values.""" return [[data[2], data[0]], [data[3], data[1]]]
5,303,157
def link_olac(lang): """Links to the OLAC project""" if isinstance(lang, Language) and lang.isocode: return "http://search.language-archives.org/search.html?q=%s" % lang.isocode else: return ""
5,303,158
def dense_image_warp_grad(op, grad): """ Dense image warp grad. """ image = op.inputs[0] flow = op.inputs[1] grad_image, grad_flow = gen_npu_cpu_ops.dense_image_warp_grad( grad, image, flow) return [grad_image, grad_flow]
5,303,159
def _AddressTranslation(rdata, unused_origin): """Returns the address of the given rdata. Args: rdata: Rdata, The data to be translated. unused_origin: Name, The origin domain name. Returns: str, The address of the given rdata. """ return rdata.address
5,303,160
def generate_sents(fsa): """ Generate all possible sentences represented by an fsa. """ # Find the starting node node_sent_dic = {} # {node: list of sentences} start_node = start_state end_node = end_state node_sent_dic[str(start_node)] = [] for nd in fsa.neighbors(start_node): ...
5,303,161
def spectral_roll_off(signal, fs): """Computes the spectral roll-off of the signal. The spectral roll-off corresponds to the frequency where 95% of the signal magnitude is contained below of this value. Feature computational cost: 1 Parameters ---------- signal : nd-array Signal f...
5,303,162
def sample_gaussian_data(logit_fn: LogitFn, x_generator: XGenerator, num_train: int, key: chex.PRNGKey) -> Tuple[testbed_base.Data, float]: """Generates training data for given problem.""" x_key, y_key = jax.random.split(key, 2) # Checkin...
5,303,163
def grab_sponsored_job_links(soup): """ Grab all sponsored job posting links from a Indeed search result page using the given soup object Parameters: soup: the soup object corresponding to a search result page e.g. https://www.indeed.com/jobs?q=data+scientist&l=Paris&start=20 R...
5,303,164
def depth_ctrl_from_depthsensor(target_depth=400, thresh=2): """Controls the diving depth to a preset level Args: target_depth (int, optional): Nominal diving depth thresh (int, optional): Threshold below which dorsal fin is not controlled, [mm] """ depth_sensor.update() if dep...
5,303,165
def _get_start_offset(lines) -> int: """Get the start offset of the license data.""" i = len(lines) - 1 count = 0 for line in lines[::-1]: if "-" * 10 in line: count += 1 if count == 2: break i -= 1 return max(i, 0)
5,303,166
def make_n_grams(seq, n): """ return iterator """ ngrams = (tuple(seq[i:i+n]) for i in range(len(seq)-n+1)) return ngrams
5,303,167
def getDiaphragmaticLungNodes(cache, coordinates, generateParameters, nodes, nodetemplate, nodeFieldParameters, elementsCount1, elementsCount2, elementsCount3, nodeIds, nodeIndex, nodeIdentifier): """ :parameter: :return: nodeIndex, nodeIdentifier """ # Initialise ...
5,303,168
def reader(): """ Open saved data and return the values in lists :return: list with time, list with kinect values, list with kalman values, list with robot movements, list with distance moved, list with time in each loop """ # Delete old files if not os.path.exists(os.path.join(ABSOLUTE_FILE_PAT...
5,303,169
def fJ(dN, toNode): """ children of fromNode become children of toNode""" for node in dN.dependent(b.INPUTS): for c in range(0, node.inputs()): if node.input(c) == dN: node.setInput(c, toNode)
5,303,170
def _mypy_results(session): """Get the cached mypy results for the session, or generate them.""" return _cached_json_results( results_path=( session.config._mypy_results_path if _is_master(session.config) else session.config.slaveinput['_mypy_results_path'] ),...
5,303,171
def printTokens(text, fileId=None): """Prints out a structured list of tokens.""" tokenizer = getTokenizer(text, fileId) indent = 0 while tokenizer.get() and not tokenizer.done(): tokenType = tokenizer.token.type tokenValue = getattr(tokenizer.token, "value", None) if tokenType...
5,303,172
def combine_all_datastream_xlsx(infolder: str, outpath: str = 'all_data.csv', restart: bool = True): """ Combine populated data in XLSX files into single csv file. :param infolder: Folder containing populated XLSX files :param outpath: Full file path to output csv to :param restart: Whether to forc...
5,303,173
def main(sci_filename, size, dark_filename): """ This is a wrapper for calc_cma and shift_cma Parameters "sci_filename" is calc_cma's "filename" parameter "size" is calc_cma's "size" parameter "dark_filename" is shift_cma's "norm_filename" parameter Returns dict result ...
5,303,174
def test_pid_dep4(): """ Test that anddup is complete. """ d = trivariates['anddup'] pid = PID_dep(d) assert pid.complete assert pid.nonnegative assert pid.consistent
5,303,175
def file_looper(rootdir='.',pattern='*',recursive=False,version=None,verbose=False,log2file=False,logoverwrite=True, level=None): """ # ToDo run for list of files or search in subdirs loop over files found with < find_files> Looks for all files in the root directory matching the file ...
5,303,176
def getrows(): """ returns the number of rows in the current map Input: - - Output: - nr of rows in the current clonemap as a scalar """ a = pcr.pcr2numpy(pcr.celllength(), np.nan).shape[0] return a
5,303,177
def list_tables(): """Lists the available tables""" print("\n".join(table_fields.keys()))
5,303,178
def AddRootPassword(parser): """Add the root password field to the parser.""" parser.add_argument( '--root-password', required=False, help='Root Cloud SQL user\'s password.')
5,303,179
def _get_base_docker_compose_path() -> str: """ Return the base docker compose `devops/compose/docker-compose.yml`. """ # Add the default path. dir_name = "devops/compose" # TODO(gp): Factor out the piece below. docker_compose_path = "docker-compose.yml" docker_compose_path = os.path.joi...
5,303,180
def gauss_mode_width_max(hist, bins, var=None, mode_guess=None, n_bins=5, cost_func='Least Squares', inflate_errors=False, gof_method='var'): """ Get the max, mode, and width of a peak based on gauss fit near the max Returns the parameters of a gaussian fit over n_bins in the vicin...
5,303,181
def fetch_libsvm(dataset, replace=False, normalize=True, min_nnz=3): """ This function is deprecated, we now rely on the libsvmdata package. Parameters ---------- dataset: string Name of the dataset. replace: bool Whether to redownload the data. normalize: bool Wheth...
5,303,182
def test_zilch_ends_round(): """" add a test to confirm that a zilch roll ends the turn and no points are awarded """ pass
5,303,183
def ReqTranslatorFactory(hand, trans): """\ This function will make a factory that can create handlers for the HTTP Server If this is used, the requests coming in to that handler will be formatted using the given translator. hand - a factory function that returns a handler to be used by the...
5,303,184
def set_config_path(config_path: Optional[str] = None) -> None: """Set the configuration path to be used for future lazy loading.""" global _CONFIG_PATH _CONFIG_PATH = config_path
5,303,185
def all_countries_risk(): """Function to estimate the risk for all countries consecutively. """ # specify country countries = ['LU','CZ','CH','EE','LV','LT','PT','ES','AT','BE','DK','IE','NL','NO','SE','UK','PL','IT','FI','FR','DE'] for country in countries: losses(country, parallel = ...
5,303,186
def test_memoization_nomatch(capsys: FixtureRequest) -> None: """ Test that already failed match is found in the cache on subsequent matches. """ def grammar() -> List[Any]: return [(rule1, ruleb), [rule1, rulec]] def rule1() -> Tuple[Any, ...]: return rulea, ruleb def rul...
5,303,187
def list_entry(): """List all the entries form entry database. Returns: html with entry data. """ entries = [] for entry in database.entry.select(): entries.append({"id": entry.id, "team_name": entry.team_name, "match_num": entry.matc...
5,303,188
def batch_fastqs(fastqs,batch_size,basename="batched", out_dir=None): """ Splits reads from one or more Fastqs into batches Concatenates input Fastq files and then splits reads into smaller Fastqs using the external 'batch' utility. Arguments: fastqs (list): list of path...
5,303,189
def check_eligibility_for_deletion(status, has_been_available): """Check if a project status is eligible for deletion""" if status not in ["In Progress"]: raise DDSArgumentError("Project Status prevents files from being deleted.") if has_been_available: raise DDSArgumentError( "...
5,303,190
def test_actions_awstest_pass(self): """Lint test: actions_awstest - PASS""" self.lint_obj._load() results = self.lint_obj.actions_awstest() assert results["passed"] == ["'.github/workflows/awstest.yml' is triggered correctly"] assert len(results.get("warned", [])) == 0 assert len(results.get("f...
5,303,191
def main(cmd): """ This is the function to create or delete the service action based on life cycle action command :param cmd: :return: """ arguments = cmd db_password = '' if 'geDbPassword' in os.environ: db_password = os.environ['geDbPassword'] try: ...
5,303,192
def get_urlpatterns(root_url_path: str = None)->str: """获取路由内容列表区域""" if root_url_path is None: root_url_path = SCONFIGS.UrlsPath() if not os.path.exists(root_url_path): return "" # 校验路径是否存在,不存在返回空串 urlpatterns = basetools.get_list_patt_content( retools.PATT_URLPATTERNS, root_ur...
5,303,193
def start_capture(self,wait_time='30s'): """ Start packet capture Target ports are set by the configuration file or by [Set Capture] keyword """ wait = DateTime.convert_time(wait_time) cli = self._clients[self._cur_name] ix = cli['connection'] ix.execute('startCapture') time.slee...
5,303,194
def expectation(samples: List[List[tf.Tensor]], fn: Callable[[List[tf.Tensor]], tf.Tensor]) -> tf.Tensor: """ tfp.monte_carlo.expectation didn't have the right functionality-- I wanted to be able to calculate multiple expectation values concurrently. Args: samples """ return...
5,303,195
def rigged_lstm_model(i) -> DualLSTMModel: """ Create a fake model that is rigged to an inverted probability distribution for an ellipse token. This needs to be a fixure, because it depends on another fixture: c(). """ class FakeModel(DualLSTMModel): @property def bad_token(sel...
5,303,196
def collect_stats(action_text, elastic_info): """ Write the current configuration information into the REPORT file. This information includes the osd, nodes and which osds are on which nodes. The minimum and maximum numbers of osds per node are also computed and saved. Args: action_tex...
5,303,197
def train_som_classifier( train_dataset: "CaseCollection", validate_dataset: "CaseCollection", config: SOMClassifierConfig = None, class_weights = None, model_fun: "Callable" = create_model_multi_input, ) -> "SOMClassifier": """Configure the dataset based on config and train a given model.""" ...
5,303,198
def load_database_singleton_from_image(): """ @description : 获取摘要数据库 @param : @Returns : 摘要数据列表[("唯一id",[摘要]),...] """ print("start to init database singleton") start_time = time.time() reply_db_singleton.load_from_image("database.dat") cost = time.time() - start_time ...
5,303,199