content
stringlengths
22
815k
id
int64
0
4.91M
def _collect_exit_info(container_dir): """Read exitinfo, check if app was aborted and why.""" exitinfo_file = os.path.join(container_dir, 'exitinfo') exitinfo = _read_exitinfo(exitinfo_file) _LOGGER.info('check for exitinfo file %r: %r', exitinfo_file, exitinfo) aborted_file = os.path.join(containe...
5,327,100
def main( # pylint: disable=too-many-arguments,too-many-locals private_key: PrivateKey, state_db: str, web3: Web3, contracts: Dict[str, Contract], start_block: BlockNumber, confirmations: BlockTimeout, host: str, port: int, service_fee: TokenAmount, operator: str, info_messa...
5,327,101
def get_service(hass, config): """Get the Google Voice SMS notification service.""" if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD]}, _LOGGER): return None return GoogleVoiceS...
5,327,102
def hammer_op(context, chase_duration): """what better way to do a lot of gnarly work than to pointer chase?""" ptr_length = context.op_config["chase_size"] data = list(range(0, ptr_length)) random.shuffle(data) curr = random.randint(0, ptr_length - 1) # and away we go start_time = time.ti...
5,327,103
def validate_sourcedata(path, source_type, pattern='sub-\\d+'): """ This function validates the "sourcedata/" directory provided by user to see if it's contents are consistent with the pipeline's requirements. """ if not path: path = './' if not source_type: source_type = ['eeg...
5,327,104
def singularity_plot( pure_fname, rolled_camp, lphase, grads, singularities, avg_singularity, thres_singularity): """ Plot overview over singularity measure """ # handle img directory img_dir = 'images' if not os.path.isdir(os.path.join(img_dir, pure_fname)): os.makedirs(os.path....
5,327,105
def generate_optimization_fns( loss_fn: Callable, opt_fn: Callable, k_fn: Callable, normalize_grad: bool = False, optimizations: Mapping = None, ): """Directly generates upper/outer bilevel program derivative functions. Args: loss_fn: loss_fn(z, *params), upper/outer level loss ...
5,327,106
def host_services(ctx: Configuration): """Home Assistant host reboot.""" _handle(ctx, 'host/services')
5,327,107
def get_weighted_spans(doc, vec, feature_weights): # type: (Any, Any, FeatureWeights) -> Optional[WeightedSpans] """ If possible, return a dict with preprocessed document and a list of spans with weights, corresponding to features in the document. """ if isinstance(vec, FeatureUnion): return...
5,327,108
def get_child(parent, child_index): """ Get the child at the given index, or return None if it doesn't exist. """ if child_index < 0 or child_index >= len(parent.childNodes): return None return parent.childNodes[child_index]
5,327,109
def testAtomicSubatomic(): """ Test atomic/subatomic links defined in memes. """ method = moduleName + '.' + 'testAtomicSubatomic' Graph.logQ.put( [logType , logLevel.DEBUG , method , "entering"]) resultSet = [] errata = [] testResult = "True" expectedResult = "True" errorMs...
5,327,110
def extinction(species, adj, z, independent): """ Returns the presence/absence of each species after taking into account the secondary extinctions. Parameters ---------- species : numpy array of shape (nbsimu, S) with nbsimu being the number of simulations (decompositions). This ar...
5,327,111
def fix_variable_mana(card): """ This function was created to fix a problem in the dataset. We're currently pretty up against the wall and I realized that 'Variable' mana texts were not correctly converted to {X} so this function is fed cards and corrects their mana values if it detects this pro...
5,327,112
def cli_arg( runner: CliRunner, notebook_path: Path, mock_terminal: Mock, remove_link_ids: Callable[[str], str], mock_tempfile_file: Mock, mock_stdin_tty: Mock, mock_stdout_tty: Mock, ) -> Callable[..., str]: """Return function that applies arguments to cli.""" def _cli_arg( ...
5,327,113
def grid_search(x_train, y_train, x_val=None, y_val=None, args=None, config_filename: str = None, folds: int = 5, verbose: int = 0, default_config: str = CONFIG_PATH_MLP, working_dir: str = WORKING_DIR, save_path: str = os.path.join(WORKING_DIR, 'logs')): """ Optimize MLP through gri...
5,327,114
def distinguish_system_application(vulner_info): """ Test whether CVE has system CIA loss or application CIA loss. :param vulner_info: object of class Vulnerability from cve_parser.py :return: result impact or impacts """ result_impacts = [] if system_confidentiality_changed( vu...
5,327,115
def split_missions_and_dates(fname): """ Examples -------- >>> fname = 'nustar-nicer_gt55000_lt58000.csv' >>> outdict = split_missions_and_dates(fname) >>> outdict['mission1'] 'nustar' >>> outdict['mission2'] 'nicer' >>> outdict['mjdstart'] 'MJD 55000' >>> outdict['mjdst...
5,327,116
def run_in_windows_bash(conanfile, command, cwd=None, env=None): """ Will run a unix command inside a bash terminal It requires to have MSYS2, CYGWIN, or WSL""" if env: # Passing env invalidates the conanfile.environment_scripts env_win = [env] if not isinstance(env, list) else env env_s...
5,327,117
def declare_ineq_soc_ub(model, index_set): """ create the constraint for the second order cone """ m = model con_set = decl.declare_set("_con_ineq_soc_ub", model, index_set) m.ineq_soc_ub = pe.Constraint(con_set) for from_bus, to_bus in con_set: m.ineq_soc_ub[(from_bus, to_bus)] = (m...
5,327,118
def remove_uploaded_records(db): """ Removes all records archived and uploaded. :param db: DB Connection to Pony :return: List of Records removed """ list_of_local_records = query.get_records_uploaded(db) if len(list_of_local_records) == 0: return 0 removed_records_list = list...
5,327,119
def nearest_with_mask_regrid( distances: ndarray, indexes: ndarray, surface_type_mask: ndarray, in_latlons: ndarray, out_latlons: ndarray, in_classified: ndarray, out_classified: ndarray, vicinity: float, ) -> Tuple[ndarray, ndarray]: """ Main regridding function for the nearest ...
5,327,120
def _validator( directory: str, output_types: List[str] = OUTPUT_TYPES, log_level: Literal["INFO", "DEBUG"] = "INFO", coverages: dict = {}, schemas_path: Path = Path(__file__).parent.joinpath(r"./schemas"), raise_error: bool = False, ) -> dict: """ Parameters ---------- director...
5,327,121
def main(infile: str, output: TextIO, chunk_size: int, min_tail_size: int): """Takes an assembly as input and produces an output of 'reads': the assembly chopped into pieces (chunks). """ with pysam.FastxFile(infile) as contigs: for contig in contigs: chunk_num = 0 seq = ...
5,327,122
def assert_file_existance(dataset_uri_list): """Assert that provided uris exist in filesystem. Verify that the uris passed in the argument exist on the filesystem if not, raise an exeception indicating which files do not exist Args: dataset_uri_list (list): a list of relative or absolute file ...
5,327,123
def get_renaming(mappers, year): """Get original to final column namings.""" renamers = {} for code, attr in mappers.items(): renamers[code] = attr['df_name'] return renamers
5,327,124
def test_note_reversed(): """Test Note reversed dunder method.""" assert list(reversed(list(Note))) == list(reversed(Note))
5,327,125
async def clap(text, args): """ Puts clap emojis between words. """ if args != []: clap_str = args[0] else: clap_str = "👏" words = text.split(" ") clappy_text = f" {clap_str} ".join(words) return clappy_text
5,327,126
def apply_binary_str( a: Union[pa.Array, pa.ChunkedArray], b: Union[pa.Array, pa.ChunkedArray], *, func: Callable, output_dtype, parallel: bool = False, ): """ Apply an element-wise numba-jitted function on two Arrow columns. The supplied function must return a numpy-compatible scal...
5,327,127
def product_review(product_id: str): """ Shows review statistics for a product. Returns a python dictionary with content-type: application/json """ session = Session() date = request.args.get('date') # parse a query string formatted as BIGINT unixReviewTime # SELECT AVG(overall)...
5,327,128
def remove_extra_two_spaces(text: str) -> str: """Replaces two consecutive spaces with one wherever they occur in a text""" return text.replace(" ", " ")
5,327,129
def reflect_table(table_name, engine): """ Gets the table with the given name from the sqlalchemy engine. Args: table_name (str): Name of the table to extract. engine (sqlalchemy.engine.base.Engine): Engine to extract from. Returns: table (sqlalchemy.ext.declarative.api.Declara...
5,327,130
def load_utt_list(utt_list): """Load a list of utterances. Args: utt_list (str): path to a file containing a list of utterances Returns: List[str]: list of utterances """ with open(utt_list) as f: utt_ids = f.readlines() utt_ids = map(lambda utt_id: utt_id.strip(), utt_...
5,327,131
def kfunc_vals(points, area): """ Input points: a list of Point objects area: an Extent object Return ds: list of radii lds: L(d) values for each radius in ds """ # This function is taken from kfunction file in spatialanalysis library n = len(points) density = n/area...
5,327,132
def test_step(): """ Test step function """ ros_rate = 20 ros_max_ita = 20 * 32 laser_z = 0.086 + 0.043 + 0.035 step_point_list = [[0.2, laser_z], [0.2, laser_z+0.2], [0.2, laser_z+0.4], [0.0, laser_z+0.2], [-0.2, laser_z+0.4], [-0.2, laser_z+0....
5,327,133
async def get_locations(): """ Retrieves the locations from the categories. The locations are cached for 1 hour. :returns: The locations. :rtype: List[Location] """ # Get all of the data categories locations. confirmed = await get_category("confirmed") deaths = await get_category("death...
5,327,134
def corrupted_pdf(papers): """ Do a simple convertion of pdf into txt. Parameters ---------- papers : List with corrupted papers (directory tree) DESCRIPTION. Returns ------- None. """ os.chdir(f'{root}/dados/txt_filesv3') for paper in papers: rsrcmgr = PDF...
5,327,135
def MDAPE(y_true, y_pred, multioutput='raw_values'): """ calculate Median Absolute Percentage Error (MDAPE). :param y_true: array-like of shape = (n_samples, *) Ground truth (correct) target values. :param y_pred: array-like of shape = (n_samples, *) Estimated target values. :param m...
5,327,136
def list_ports(): """List the available serial ports.""" for comport in serial.tools.list_ports.comports(): print(comport)
5,327,137
def fast_spearman(x, y=None): """calculate the spearnab correlation matrix for the columns of x (MxN), or optionally, the spearmancorrelaton matrix between x and y (OxP). In the language of statistics the columns are the variables and the rows are the observations. Args: x (numpy array-like) MxN in...
5,327,138
def analyze_individual_category(k, cocoDt, cocoGt, catId, iou_type, areas=None): """针对某个特定类别,分析忽略亚类混淆和类别混淆时的准确率。 Refer to https://github.com/open-mmlab/mmdetection/blob/master/tools/analysis_tools/coco_error_analysis.py#L174 Args: k (int): 待分析类别的序号。 cocoDt (pycocotols.coco.COCO...
5,327,139
def rename(blocks, scope, stype): """ Rename all sub-blocks moved under another block. (mixins) Args: lst (list): block list scope (object): Scope object """ for p in blocks: if isinstance(p, stype): p.tokens[0].parse(scope) if p.tokens[1]: ...
5,327,140
def read_line1(line): """! Function read_line1 Reads as argument a string formatted as a Line 1 in SEISAN's Nordic format Returns a Hypocenter dataclass with all the fields in a SEISAN's Line 1 @param[in] line string with SEISAN's Nordic hypocenter format (Line 1) @return Hypocenter...
5,327,141
def write_md_files(): """Make a readme.md file for every module in its folder""" for mdl in sheet.modules: mdl.write_md()
5,327,142
def ghidra_headless(address, xml_file_path, bin_file_path, ghidra_headless_path, ghidra_plugins_path): """ Call Ghidra in headless mode and run the plugin FunctionDecompile.py to decompile the code of the function. """ t...
5,327,143
def session_scope(): """When accessing the database, use the following syntax: >>> with session_scope() as session: >>> session.query(...) :return: the session for accessing the database. """ session_obj = scoped_session(DBSession) session = session_obj() try: yield session ...
5,327,144
def write_shellchoice_file(home_directory: Path, configuration: Any) -> None: """Write the shell choice configuration file.""" file_path = Path(os.path.join(home_directory, ".shellchoice")) if does_file_exist(file_path): print("... exists, not creating") return print("... creating file...
5,327,145
def run(parsed_args): """Execute release task creation parsed_args: command line arguemnts""" assert parsed_args.server assert parsed_args.user assert parsed_args.password assert parsed_args.query assert parsed_args.max_results verification_steps_threshold = 0 verification_results...
5,327,146
def validate_id( endpoint_name, type_id, cache_buster=False, config=api_config.CONFIG, logger=logging.getLogger('publicAPI'), ): """Check EVE Online CREST as source-of-truth for id lookup Args: endpoint_name (str): desired endpoint for data lookup type_id...
5,327,147
def init_server_socket() -> socket.socket: """Initialize and bind the server unix socket.""" socket_address = get_socket_address() try: os.unlink(socket_address) except (OSError, EnvironmentError): pass sock = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_DGRAM) sock.bind...
5,327,148
def test_async_request(upload_test_sector_scenario): """ Tests async_request() function """ cmd = reset_simulation() assert cmd == True upload_test_sector_scenario() # Get the position position = all_positions() acid1, acid2 = position.index commands = [] commands.append(...
5,327,149
def getInfo_insert(sql : str, tableInfo : table_info_module.TableInfo) -> tuple: """테이블 이름과 컬럼을 반환합니다.""" sql = string_module.removeNoise(sql) tableName = string_module.getParenthesesContext2(sql, "INSERT INTO ", " ") columns = tableInfo[tableName] return (tableName, columns)
5,327,150
def compute_flow_for_supervised_loss( feature_model, flow_model, batch, training ): """Compute flow for an image batch. Args: feature_model: A model to compute features for flow. flow_model: A model to compute flow. batch: A tf.tensor of shape [b, seq, h, w, c] holding a batch of triple...
5,327,151
def _get_filename_from_request(request): """ Gets the filename from an url request. :param request: url request to get filename from :type request: urllib.requests.Request or urllib2.Request :rtype: str """ try: headers = request.headers content = headers["content-dispositi...
5,327,152
def farey_sequence(n): """Return the nth Farey sequence as order pairs of the form (N,D) where `N' is the numerator and `D' is the denominator.""" a, b, c, d = 0, 1, 1, n sequence=[(a,b)] while (c <= n): k = int((n + b) / d) a, b, c, d = c, d, (k*c-a), (k*d-b) sequence.append( (a...
5,327,153
def test_texture(): """Test adding texture coordinates""" # create a rectangle vertices vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 0.5, 0], [0, 0.5, 0],]) # mesh faces faces = np.hstack([[3, 0, 1, 2], ...
5,327,154
def make_vgg19_block(block): """Builds a vgg19 block from a dictionary Args: block: a dictionary """ layers = [] for i in range(len(block)): one_ = block[i] for k, v in one_.items(): if 'pool' in k: layers += [nn.MaxPool2d(kernel_size=v[0], stride=...
5,327,155
def process_one(f, mesh_directory, dataset_directory, skip_existing, log_level): """Processes a single mesh, adding it to the dataset.""" relpath = f.replace(mesh_directory, '') print('relpath:', relpath) assert relpath[0] == '/' relpath = relpath[1:] split, synset = relpath.split('/')[:2] log.verb...
5,327,156
def test_client_route(mock_request, mock_connect): """Should return RouteResult instance.""" mock_connect.return_value = "some-token", 1234567 mock_request.return_value = MagicMock( status_code=status.HTTP_200_OK, data={ "status_message": "Found route between points", ...
5,327,157
def qsl_ranking(call, key, qsl): """ Add qsl information to either sent or received (determined by key) qsl information is ranked and higher one is kept the order is: direct$ > direct > bureau """ oqsl = getattr(call, key, None) for q in qsl_types: if q == qsl or q == oqsl: c...
5,327,158
def tld(): """ Return a random tld (Top Level Domain) from the tlds list below :return: str """ tlds = ('com', 'org', 'edu', 'gov', 'co.uk', 'net', 'io', 'ru', 'eu',) return pickone(tlds)
5,327,159
def validate_boolean(option, value): """Validates that 'value' is 'true' or 'false'. """ if isinstance(value, bool): return value elif isinstance(value, basestring): if value not in ('true', 'false'): raise ConfigurationError("The value of '%s' must be " ...
5,327,160
def A2RT(room_size, A_wall_all, F_abs, c=343, A_air=None, estimator='Norris_Eyring'): """ Estimate reverberation time based on room acoustic parameters, translated from matlab code developed by Douglas R Campbell Args: room_size: three-dimension measurement of shoebox room A_wall_all: sound ...
5,327,161
def GetVideoFromRate(content): """ 从视频搜索源码页面提取视频信息 """ #av号和标题 regular1 = r'<a href="/video/av(\d+)/" target="_blank" class="title" [^>]*>(.*)</a>' info1 = GetRE(content, regular1) #观看数 regular2 = r'<i class="b-icon b-icon-v-play" title=".+"></i><span number="([^"]+)">\1</span>' info2 = ...
5,327,162
def PPVfn(Mw, fc, Rho, V): """Calculates the peak-particle-velocity (PPV) at the source for a given homogeneous density and velocity model. :param Mw: the moment magnitude :type Mw: float :param fc: the corner frequency in Hz :type fc: float :param Rho: Density at the source in kg/m**3 ...
5,327,163
def extract_feature_label(feat_path, lab_path, audio_sr=22050, hop_size=1024): """Basic feature extraction block. Parameters ---------- feat_path: Path Path to the raw feature folder. lab_path: Path Path to the corresponding label folder. audio_sr: int sampling rate, def...
5,327,164
def includeme(config): """register custom datatables""" config.register_datatable('parameters', Concepts) config.register_datatable('languages', Languages) config.register_datatable('values', Words)
5,327,165
def compute_generic_stats(graph): """ Compute generic statistic for a graph :param graph: :return: """ num_nodes = 0 for g in graph: num_nodes += g.number_of_nodes() if len(graph) > 0: num_nodes /= len(graph) fmtl_print('Average number of nodes (graph size {})'.f...
5,327,166
def get_local_episodes(anime_folder, name): """return a list of files of a anime-folder inside ANIME_FOLDER""" episodes = [] name = name.replace("'", "_") path = os.path.join(anime_folder, name) if not os.path.isdir(path): os.makedirs(path) return episodes for episode in os.listd...
5,327,167
def _find_pkg_info(directory): """find and return the full path to a PKG-INFO file or None if not found""" for root, dirs, files in os.walk(directory): for filename in files: if filename == 'PKG-INFO': return os.path.join(root, filename) # no PKG-INFO file found retur...
5,327,168
def get_m3u8_url(text): # type: (str) -> Union[str, None] """Attempts to get the first m3u8 url from the given string""" m3u8 = re.search(r"https[^\"]*\.m3u8", text) sig = re.search(r"(\?sig=[^\"]*)", text) if m3u8 and sig: return "{}{}".format(clean_uri(m3u8.group()), sig.group()) retur...
5,327,169
def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights""" # https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow low = -constant*np.sqrt(6.0/(fan_in + fan_out)) high = constant*np.sqrt(6.0/(fan_in + fan_out)) return tf.rando...
5,327,170
def object_bbox_flip( bbox: remote_blob_util.BlobDef, image_size: remote_blob_util.BlobDef, flip_code: Union[int, remote_blob_util.BlobDef], name: Optional[str] = None, ) -> remote_blob_util.BlobDef: """This operator flips the object bounding box. The flip code corresponds to the different fli...
5,327,171
def endwin (): """Close down curses mode. """ global screen if screen: try: curses.endwin () except: pass screen = None
5,327,172
def while_K(): """ Upper case Alphabet letter 'K' pattern using Python Python while loop""" row = 0 while row<6: col = 0 while col<4: if col==0 or row+col==3 or row-col==2: print('*', end = ' ') ...
5,327,173
def compile(spec): """ Args: spec (dict): A specification dict that attempts to "break" test dicts Returns: JsonMatcher. """ return JsonMatcher(spec)
5,327,174
def labels_to_intervals(labels_list): """ labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs Args: labels_list: list of labels of each frame e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}] Returns: tags -...
5,327,175
def get_wolfram_query_url(query): """Get Wolfram query URL.""" base_url = 'www.wolframalpha.com' if not query: return 'http://{0}'.format(base_url) return 'http://{0}/input/?i={1}'.format(base_url, query)
5,327,176
def show_2dfit_residuals(x, y, data, fit, xfield=None, yfield=None, nfig=None, cmap=None) : """ Create a figure with a map of the residuals in % :param x: input xaxis coordinates - array :param y: input yaxis coordinates - array (should have the same dim as x) :param data: input data points (should hav...
5,327,177
def test_column_wrangler(): """Columns are transformed into a consistent format. """ data = pd.DataFrame({ 'column1': [1, 2, 3], 'cOLUmn2': [1, 2, 3], ' cOLUmn3 ': [1, 2, 3], ' column 4 ': [1, 2, 3], }) result = _column_wrangler(data).columns expected = pd.In...
5,327,178
def center_of_mass(points: Sequence[float]) -> np.ndarray: """Gets the center of mass of the points in space. Parameters ---------- points The points to find the center of mass from. Returns ------- np.ndarray The center of mass of the points. """ points = [np.array...
5,327,179
def get_posts(session, client_id, now=None): """Returns all posts.""" now = _utcnow(now) try: results = _get_post_query(session, client_id)\ .order_by(MappedPost.created_datetime.desc()) posts = tuple(_make_post(*result) for result in results) return PaginatedSequence(posts) except sa.exc....
5,327,180
def tessellate_cell(csn, children, acells, position, parent, cell_params): """ Tessellate a cell. :param int csn: Cell number. :param ndarray children: Array specifying children of each cell. :param ndarray acells: Array specifying the adjacent cells of each cell. :param ndarray position: Array...
5,327,181
def add_eig_vec(g, pos_enc_dim): """ Graph positional encoding v/ Laplacian eigenvectors This func is for eigvec visualization, same code as positional_encoding() func, but stores value in a diff key 'eigvec' """ # Laplacian A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float) ...
5,327,182
def _advanced_clip( data, p_min=35, p_max=99.98, nonnegative=True, dtype="int16", invert=False ): """ Remove outliers at both ends of the intensity distribution and fit into a given dtype. This interface tries to emulate ANTs workflows' massaging that truncate images into the 0-255 range, and appli...
5,327,183
def allocate_buffers(engine): """ Allocates all buffers required for the specified engine """ inputs = [] outputs = [] bindings = [] # Iterate over binding names in engine for binding in engine: # Get binding (tensor/buffer) size size = trt.volume(engine.get_binding_shape...
5,327,184
def D_to_M(D, ecc): """Mean anomaly from eccentric anomaly. Parameters ---------- D : float Parabolic eccentric anomaly (rad). ecc : float Eccentricity. Returns ------- M : float Mean anomaly (rad). """ with u.set_enabled_equivalencies(u.dimensionless_a...
5,327,185
def dict_merge(a, b): """Merge a and b. Parameters ---------- a One dictionary that will be merged b Other dictionary that will be merged """ return _merge(dict(a), b)
5,327,186
def merge_dictionary(src: dict, dest: dict) -> dict: """ Merge two dictionaries. :param src: A dictionary with the values to merge. :param dest: A dictionary where to merge the values. """ for name, value in src.items(): if name not in dest: # When field is not available i...
5,327,187
def create_from_source(wp_config, source: Location): """ Using a Location object and the WP config, generates the appropriate LuhSql object """ if isinstance(source, SshLocation): ssh_user = source.user ssh_host = source.host elif isinstance(source, LocalLocation): ssh_u...
5,327,188
def eye(N, M=None, k=0, dtype=DEFAULT_FLOAT_DTYPE): """ Returns a 2-D tensor with ones on the diagnoal and zeros elsewhere. Args: N (int): Number of rows in the output, must be larger than 0. M (int, optional): Number of columns in the output. If None, defaults to N, if defined,...
5,327,189
def create_inception_graph(): """ 从被保存的GraphDef文件创建一个graph :return: 受inception 训练过的图,同时保存了几个tensor """ with tf.Session() as sess: model_filename = os.path.join(model_dir, 'def.pb') if not os.path.exists(model_filename): model_filename = os.path.join(model_dir, 'classify_i...
5,327,190
def team_game_log(request, team_id, season): """Individual team season game log page. """ response = requests.get(f'http://{request.get_host()}/api/teams/{team_id}/{season}/Regular') return render(request, 'main/team_games.html', context=response.json())
5,327,191
def _make_allocated_size_testcases(): """ Build test cases for some common allocation_units. """ for unit in (Byte, MB, MiB, GB, GiB): for size in (1, 2, 4, 8): test_case = make_allocated_size_tests(unit(size)) globals()[test_case.__name__] = test_case
5,327,192
def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower,weak_upper): #def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower=0.935,weak_upper=0.98): """ - this is the linear case of getting labels for new spectra best log g = weak_lower = 0.95, weak_upper = 0.98 best teff = weak_lower = 0.9...
5,327,193
def validate_worker(worker: DaskWorkerDeployment): """Validates the worker by accessing the diagnostics server. :param worker: Worker to validate. """ validate_tunnel_http_connection(tunnel=worker.bokeh_tunnel)
5,327,194
def main(): """Console script for vaqc.""" parser = argparse.ArgumentParser() parser.add_argument('derivatives_dir', type=Path, action='store', help='the root folder of a BIDS derivative dataset ' '(sub-XXXXX fol...
5,327,195
def construct_unique_cluster_name_column(cdips_cat_vnum=0.4): """ We already have a catalog with the following columns: source_id;cluster;reference;ext_catalog_name;ra;dec;pmra;pmdec;parallax; phot_g_mean_mag;phot_bp_mean_mag;phot_rp_mean_mag; We want to supplement it with: unique...
5,327,196
def figure(*args, grid=True, style='default', figsize=(9, 5), **kwargs): """ Returns a matplotlib axis object. """ import pylab as pl available = [s for s in pl.style.available + ['default'] if not s.startswith('_')] if style not in available: raise ValueError(f'\n\n Valid Styles are {av...
5,327,197
def test_count_with_chainable_filter_startswith_operator(service): """Check getting $count with $filter in""" # pylint: disable=redefined-outer-name responses.add( responses.GET, f"{service.url}/Employees/$count?$filter=startswith%28NickName%2C%20%27Tim%27%29%20eq%20true", json=3, ...
5,327,198
def boundcond(stato): """This function applies the boundary conditions that one chooses to adopt. The boundaries can be reflective, periodic or constant. It takes as input the state to be evolved. """ if bc=='const': status=''.join(('.',stato,'.')) #constant boundaries elif bc=='refl'...
5,327,199