content
stringlengths
22
815k
id
int64
0
4.91M
def _preclean(Q): """ Clean before annotation. """ Q = re.sub('#([0-9])', r'# \1', Q) Q = Q.replace('€', ' €').replace('\'', ' ').replace(',', '').replace('?', '').replace('\"', '').replace('(s)', '').replace(' ', ' ').replace(u'\xa0', u' ') return Q.lower()
5,314,100
async def job_info(request): """Get job info.""" conn_manager = request.app[common.KEY_CONN_MANAGER] conn_uid = request.match_info[ROUTE_VARIABLE_CONNECTION_UID] job_uid = request.match_info[ROUTE_VARIABLE_JOB_UID] connection = conn_manager.connection(conn_uid) info = await connection.call_simpl...
5,314,101
def load_dataset_map() -> Dict[str, Callable]: """ Get a map of datasets. Returns: Dict[str, Callable]: Key: Dataset name, Value: loader function which returns (X, y). """ dss = { "iris-2d": load_iris_2d, "wine-2d": load_wine_2d, "diabetes": load_diabetes, "a...
5,314,102
def test_bad_ip(service_ranges) -> None: """Unit-test bad IP value throws correct exception.""" with pytest.raises(ValueError) as excinfo: get_aws_service_range("foo", service_ranges) assert "Address must be a valid IPv4 address" in str(excinfo.value)
5,314,103
def m2fs_pixel_flat(flatfname, fiberconfig, Npixcut): """ Use the flat to find pixel variations. DON'T USE THIS. It doesn't work. """ R, eR, header = read_fits_two(flatfname) #shape = R.shape #X, Y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing="ij") tracefn = m2fs...
5,314,104
def runDemo(witness=5631, local=5629, expire=0.0): """ Setup and run one demo controller for Han, like bob only better """ secrets = [ 'A1-QxDkso9-MR1A8rZz_Naw6fgaAtayda8hrbkRVVu1E', 'A6zz7M08-HQSFq92sJ8KJOT2cZ47x7pXFQLPB0pckB3Q', 'ALq-w1UKkdrppwZzGTtz4PWYEeWm0-sDHzOv5sq96xJY' ...
5,314,105
def HTTP405(environ, start_response): """ HTTP 405 Response """ start_response('405 METHOD NOT ALLOWED', [('Content-Type', 'text/plain')]) return ['']
5,314,106
def train_one_batch(batch, generator, optimizer, reward_obj, opt, global_step, tb_writer, lagrangian_params=None, cost_objs=[]): #src, src_lens, src_mask, src_oov, oov_lists, src_str_list, trg_sent_2d_list, trg, trg_oov, trg_lens, trg_mask, _ = batch """ src: a LongTensor containing the word indices of sour...
5,314,107
def main(unused_argv): """训练入口""" global total_feature_columns, label_feature_columns dense_feature_columns, category_feature_columns, label_feature_columns = create_feature_columns() total_feature_columns = dense_feature_columns + category_feature_columns params = { "category_feature_colu...
5,314,108
def getProgramName(): """Get the name of the currently running program.""" progName = sys.argv[0].strip() if progName.startswith('./'): progName = progName[2:] if progName.endswith('.py'): progName = progName[:-3] # Only return the name of the program not the path pName = os.pat...
5,314,109
def get_all_trips(*, date_from: datetime, date_to: datetime, departure_station: BusStation, arrival_station: BusStation) \ -> Iterable[Trip]: """ [Step1] filter trips with departure time between `date_form` and `date_to` [Step2] filter trips with trip route that contain the `departure_station` befor...
5,314,110
def get_coinbase_api_response( get_api_url: Callable, base_url: str, timestamp_from: Optional[datetime] = None, pagination_id: Optional[str] = None, retry=30, ): """Get Coinbase API response.""" try: url = get_api_url( base_url, timestamp_from=timestamp_from, pagination_i...
5,314,111
def intersect(A, B, C, D): """ Finds the intersection of two lines represented by four points. @parameter A: point #1, belongs to line #1 @parameter B: point #2, belongs to line #1 @parameter C: point #3, belongs to line #2 @parameter D: point #4, belongs to line #2 @returns: None if lines are...
5,314,112
def detect(inputs, anchors, n_classes, img_size, scope='detection'): """Detect layer """ with tf.name_scope(scope, 'detection',[inputs]): n_anchors = len(anchors) bbox_attrs = 5+n_classes predictions = inputs grid_size = predictions.get_shape().as_list()[1:3] n_dims = grid_size[0] * grid_size...
5,314,113
def header(f, methods): """ Write header for LaTex tables in paper. Some manual manipulation was done for final version. Args: f (file): file to write header to methods (list of str): list of full method names Returns: str: aggregate loss """ f.write("\\begin{cente...
5,314,114
def test_encrypt_secure_string(mock_encrypt): """ Should encrypt the raw value """ mock_encrypt.return_value = b'SecretData' session = boto3.Session(region_name='us-east-1') entry = SSMParameterEntry( session=session, kms_arn=KEY_ARN, data={ 'name': 'ss...
5,314,115
def get_scenario_data(): """Return sample scenario_data """ return [ { 'population_count': 100, 'county': 'oxford', 'season': 'cold_month', 'timestep': 2017 }, { 'population_count': 150, 'county': 'oxford', ...
5,314,116
def izpisi_vloge(igralec): """ Izpiše vse vloge podanega igralca. """ print(igralec.ime) for naslov, leto, vloga in igralec.poisci_vloge(): print(f'- {naslov} ({leto}, {vloga})')
5,314,117
def user_not_found(error): """Custom error handler. More info: http://flask.pocoo.org/docs/1.0/patterns/apierrors/#registering-an-error-handler """ response = jsonify(error.to_dict()) response.status_code = error.status_code return response
5,314,118
def get_do_pass_with_amendments_by_committee( biennium: str, agency: str, committee_name: str ) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/committeeactionservice.asmx?op=GetDoPassWithAmendmentsByCommittee""" argdict: Dict[str, Any] = dict(biennium=biennium, agency=agency, committeeName=comm...
5,314,119
def petrosian_fd(x): """Petrosian fractal dimension. Parameters ---------- x : list or np.array One dimensional time series Returns ------- pfd : float Petrosian fractal dimension Notes ----- The Petrosian algorithm can be used to provide a fast computation of ...
5,314,120
def write_mix_info(mix_info, info_file): """Prints the content of mix_info dictionary into file.""" if os.path.isfile(info_file): raise ValueError(f'mix_info file {info_file} already exists. Please ' f'delete {info_file} and re-run.') with open(info_file, 'w') as f: for mix in mix_inf...
5,314,121
def lemma(word): """ Transforms a given word to its lemmatized form, checking a lemma dictionary. If the word is not included in the dictionary, the same word is returned. :param word: string containing a single word :type: string :return: the word's lemma :type: string """ return le...
5,314,122
def err(msg): """ Prints a message to stderr, terminating it with a newline """ sys.stderr.write(msg + "\n")
5,314,123
def is_style_file(filename): """Return True if the filename looks like a style file.""" return STYLE_FILE_PATTERN.match(filename) is not None
5,314,124
def test_lab(cli_lab, authenticated_client): """Create and teardown lab""" yield authenticated_client.api.create_lab(**cli_lab) authenticated_client.login( username=os.environ["EVE_NG_USERNAME"], password=os.environ["EVE_NG_PASSWORD"] ) authenticated_client.api.delete_lab(cli_lab["path"] + c...
5,314,125
def loop(): """The main game loop.""" move_player() move_rain() if detect_collisions(): if args.v: render() print('Score: {}'.format(len(x))) stdout.flush() sleep(1) train() reset() else: add_rain() render() record()
5,314,126
def add_subnet(): """add subnet. Must fields: ['subnet'] Optional fields: ['name'] """ data = _get_request_data() return utils.make_json_response( 200, network_api.add_subnet(user=current_user, **data) )
5,314,127
def V_beta(gamma, pi): """ Defining function for the expected utility for insured agent, where we know the coverage ratio gamma and x is drawn from beta distribution. Args: pi(float): insurance premium gamma(float): coverage ratio Returns: Expected utility for agent. ...
5,314,128
def main(): """Unit tests that can also serve as example usage.""" objf = '../../../toy-data/obj-mtl_cube/cube.obj' myobj = Obj() myobj.print_info() myobj.load_file(objf) myobj.print_info() objf_reproduce = objf.replace('.obj', '_reproduce.obj') myobj.write_file(objf_reproduce) myobj...
5,314,129
def counted(fn): """ count number of times a subroutine is called :param fn: :return: """ def wrapper(*args, **kwargs): wrapper.called+= 1 return fn(*args, **kwargs) wrapper.called= 0 wrapper.__name__= fn.__name__ return wrapper
5,314,130
def removeneg(im, key=0): """ remove NAN and INF in an image """ im2 = np.copy(im) arr = im2 < 0 im2[arr] = key return im2
5,314,131
def mape(df, w): """Mean absolute percent error Parameters ---------- df: Cross-validation results dataframe. w: Aggregation window size. Returns ------- Dataframe with columns horizon and mape. """ ape = np.abs((df['y'] - df['yhat']) / df['y']) if w < 0: return pd....
5,314,132
def p3p(pts_2d, pts_3d, K, q_ref=None, allow_imag_roots=False): """An implementation of the ... problem from "A Stable Algebraic Camera Pose Estimation for Minimal Configurations of 2D/3D Point and Line Correspondences", from Zhou et al. at ACCV 2018. 3 points pts_2d - pixels in 2d. Each pixel is ...
5,314,133
def status() -> tuple: """Health check endpoint.""" return xmlify('<status>ok</status>'), HTTP_200_OK
5,314,134
def test_list_date_enumeration_nistxml_sv_iv_list_date_enumeration_1_4(mode, save_output, output_format): """ Type list/date is restricted by facet enumeration. """ assert_bindings( schema="nistData/list/date/Schema+Instance/NISTSchema-SV-IV-list-date-enumeration-1.xsd", instance="nistDa...
5,314,135
def nested_keys(nested_dict: Dict[Text, Any], delimiter: Text = '/', prefix: Text = '') -> Sequence[Text]: """Returns a flattend list of nested key strings of a nested dict. Args: nested_dict: Nested dictionary. delimiter: String that splits the nested keys. prefix: Top-...
5,314,136
def add_it(workbench, file_list, labels): """Add the given file_list to workbench as samples, also add them as nodes. Args: workbench: Instance of Workbench Client. file_list: list of files. labels: labels for the nodes. Returns: A list of md5s. """ md5s = [] f...
5,314,137
def has_id(sxpr, id): """Test if an s-expression has a given id. """ return attribute(sxpr, 'id') == id
5,314,138
def gf_gcdex(f, g, p, K): """Extended Euclidean Algorithm in `GF(p)[x]`. Given polynomials `f` and `g` in `GF(p)[x]`, computes polynomials `s`, `t` and `h`, such that `h = gcd(f, g)` and `s*f + t*g = h`. The typical application of EEA is solving polynomial diophantine equations. Consid...
5,314,139
def animate_datapack(datapack,output_folder,num_processes=1,**kwargs): """ Plot the datapack in parallel, then stitch into movie. datapack: str the datapack filename output_folder: str, folder to store figs in num_processes: int number of parallel plotting processes to run **kwargs: keywords to ...
5,314,140
def _filetime_from_timestamp(timestamp): """ See filetimes.py for details """ # Timezones are hard, sorry moment = datetime.fromtimestamp(timestamp) delta_from_utc = moment - datetime.utcfromtimestamp(timestamp) return dt_to_filetime(moment, delta_from_utc)
5,314,141
def optimize( func: Callable[[np.ndarray], float], x: ArrayLike, trials: int = 3, iterations: Optional[int] = 1500, abs_tol_x: float = 3e-2, abs_tol_f: float = 3e-2, rel_tol_x: float = 1e-1, rel_tol_f: float = 1e-1, check_decreasing: bool = True, refinement_iterations: int = 300,...
5,314,142
def _create_reconstruction( n_cameras: int=0, n_shots_cam=None, n_pano_shots_cam=None, n_points: int=0, dist_to_shots: bool=False, dist_to_pano_shots: bool=False, ): """Creates a reconstruction with n_cameras random cameras and shots, where n_shots_cam is a dictionary, containing the ...
5,314,143
def _validate_dialogue_section( protocol_specification: ProtocolSpecification, performatives_set: Set[str] ) -> Tuple[bool, str]: """ Evaluate whether the dialogue section of a protocol specification is valid. :param protocol_specification: a protocol specification. :param performatives_set: set of...
5,314,144
def test_config_case(): """ https://github.com/geographika/mappyfile/issues/18 """ s = """ MAP CONFIG "PROJ_LIB" "projections" END """ exp = "MAP CONFIG 'PROJ_LIB' 'projections' END" assert(output(s) == exp)
5,314,145
def _hsic_naive(x, y, scale=False, sigma_x=None, sigma_y=None, kernel='gaussian', dof=0): """ Naive (slow) implementation of HSIC (Hilbert-Schmidt Independence Criterion). This function is only used to assert correct results of the faster method ``hsic``. Parameters ---------- ...
5,314,146
def translate(raw_path): """Reads official Rio de Janeiro BRT realized trips file and converts to standarized realized trips. TODO: - get trip_id, maybe from GTFS? - get departure_id and arrival_id, also from GTFS? Parameters ---------- raw_path : str where raw data is locates ...
5,314,147
def get_percentage(numerator, denominator, precision = 2): """ Return a percentage value with the specified precision. """ return round(float(numerator) / float(denominator) * 100, precision)
5,314,148
def error_negative_following_offset(self): """Check that non-positive value of following offset returns an error. """ exitcode = 36 message = "DB::Exception: Frame end offset must be greater than zero, -2 given" sql = ("select max(enroll_date) over (order by salary range between 1 preceding and -2 ...
5,314,149
def _calculate_verification_code(hash: bytes) -> int: """ Verification code is a 4-digit number used in mobile authentication and mobile signing linked with the hash value to be signed. See https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm """ return ((0xFC & hash[0]) << 5) |...
5,314,150
def add_message(user, text, can_dismiss=True): """Add a message to the user's message queue for a variety of purposes. :param user: the instance of `KlaxerUser` to add a message to :param text: the text of the message :param can_dismiss: (optional) whether or not the message can be dismissed :retur...
5,314,151
def test_dist(fmt, extractor, tmp_path): """Make sure the wheel does not contain stuff it shouldn't have """ if Path('build').exists(): shutil.rmtree('build') if Path('dist').exists(): shutil.rmtree('dist') subprocess.run(['python', 'setup.py', fmt], check=True) extractor(Path(...
5,314,152
def enable_autocomplete(shell: RecognizedShell): """ Adds a command to the relevant configuration files s.t. autocompletion code is automatically loaded. This is used with the `--enable` flag for hopla complete [shell] --enable commands. :param shell: :return: """ shell.handle_enable_co...
5,314,153
def dataQC(json_data): """ perform quality analysis on data """ bad_data = {} for device in json_data.keys(): for item in json_data[device]: if item[1] <= check_lower * abs_std[0+omit_lower]: if device not in bad_data: bad_data[device] = [] ...
5,314,154
def get_interatomic_r(atoms: Union[Tuple[str], List[str]], expand: Optional[float] = None) -> float: """ Calculates bond length between two elements Args: atoms (list or tuple): pair of atoms for which the bond length needs to be calculated expand (float): ...
5,314,155
def new(**config): """ Creates a new sanic project with batteries included. """ active_config = {k: v for k, v in config.items() if v is not None} setup_logging(config['verbose']) try: cookiecutter(active_config["template_src"], output_dir=active_config["output_dir"]) except SanicD...
5,314,156
def test_api_get(api_client, endpoint, expected_count): """ Test API GET /<entity type> and GET /<entity type>/<kf_id> """ response = api_client.get(endpoint) r = response.json()['results'] assert response.status_code == 200 assert len(r) == expected_count kf_id = r[0]["kf_id"] endpo...
5,314,157
def annualized_return_nb(returns, ann_factor): """2-dim version of `annualized_return_1d_nb`.""" result = np.empty(returns.shape[1], dtype=np.float_) for col in range(returns.shape[1]): result[col] = annualized_return_1d_nb(returns[:, col], ann_factor) return result
5,314,158
def canon_ref(did: str, ref: str, delimiter: str = None, did_type: str = None): """ Given a reference in a DID document, return it in its canonical form of a URI. Args: did: DID acting as the identifier of the DID document ref: reference to canonicalize, either a DID or a fragment pointing ...
5,314,159
def cars_produced_this_year() -> dict: """Get number of cars produced this year.""" return get_metric_of(label='cars_produced_this_year')
5,314,160
def test_missing_dependencies_action_0(fxtr_setup_empty_db_and_inbox): """Test Function - missing dependencies - action - case0.""" cfg.glob.logger.debug(cfg.glob.LOGGER_START) # ------------------------------------------------------------------------- try: cfg.glob.db_core.exists() # type: ig...
5,314,161
def parse_script_args(): """ """ parser = argparse.ArgumentParser(description="Delete images from filesystem.") parser.add_argument('--reg_ip', type=str, required=True, help='Registry host address e.g. 1.2.3.4') parser.add_argument('images', type=str, nargs='+', ...
5,314,162
def main(): """ all the test of the class Line """ #Header print ("*******************") print (" Line module test") print ("*******************") #creation of 5 stations A = Station("A",[1.,0.]) B = Station("B",[2.,0.]) C = Station("C",[3.,0.]) D = Station("D",[4.,0.]) ...
5,314,163
def merge_authentication_authorities(managed_auth_authority, user_record): """Merge two authentication_authority values, giving precedence to the managed_auth_authority""" existing_auth_authority = get_attribute_for_user( "authentication_authority", user_record) if existing_auth_authority: ...
5,314,164
def _observables(posterior=False): """ Model observables at all design points or drawn from the posterior with experimental data points. """ plots = _observables_plots() fig, axes = plt.subplots( nrows=len(systems), ncols=1, figsize=figsize(.6, aspect=3), sharex=True ...
5,314,165
def preprocess_pil_image(pil_img, color_mode='rgb', target_size=None): """Preprocesses the PIL image Arguments img: PIL Image color_mode: One of "grayscale", "rgb", "rgba". Default: "rgb". The desired image format. target_size: Either `None` (default to original size) ...
5,314,166
def _handle_coord(c, dtype: torch.dtype, device: torch.device) -> torch.Tensor: """ Helper function for _handle_input. Args: c: Python scalar, torch scalar, or 1D torch tensor Returns: c_vec: 1D torch tensor """ if not torch.is_tensor(c): c = torch.tensor(c, dtype=dtype...
5,314,167
def current_time_hhmmss(): """ Fetches current time in GMT UTC+0 Returns: (str): Current time in GMT UTC+0 """ return str(time.gmtime().tm_hour) + ":" + str(time.gmtime().tm_min) + ":" + str(time.gmtime().tm_sec)
5,314,168
def equalize_adaptive_clahe(image, ntiles=8, clip_limit=0.01): """Return contrast limited adaptive histogram equalized image. The return value is normalised to the range 0 to 1. :param image: numpy array or :class:`jicimagelib.image.Image` of dtype float :param ntiles: number of tile regions :...
5,314,169
def predict_write_segmented_img_windows( windows_list, input_img_fp, output_shp_fp, trained_classifier, class_threshold=0.7 ): """Make predictions for each window in specified list, convert to geometries, write all to shapefile. Args: windows_list (list): List of image window indices to process. ...
5,314,170
def suggest_parameters_DRE_NMNIST(trial, list_lr, list_bs, list_opt, list_wd, list_multLam, list_order): """ Suggest hyperparameters. Args: trial: A trial object for optuna optimization. list_lr: A list of floats. Candidates of learning rates. list_bs: A list of ints. Candidate...
5,314,171
def update_projector(): """ Sends the data to the clients, who listen to the projector. """ # TODO: only send necessary html ProjectorSocketHandler.send_updates({'content': get_projector_content()})
5,314,172
def format_seconds(seconds, hide_seconds=False): """ Returns a human-readable string representation of the given amount of seconds. """ if seconds <= 60: return str(seconds) output = "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600)...
5,314,173
def _contains_atom(example, atoms, get_atoms_fn): """Returns True if example contains any atom in atoms.""" example_atoms = get_atoms_fn(example) for example_atom in example_atoms: if example_atom in atoms: return True return False
5,314,174
def load_config_file(filename): """Load the YAML configuration file.""" try: config = None with open(filename, 'r') as f: config = yaml.load(f) print('Using configuration at {0}'.format(filename)) if not config.keys() == default_config.keys(): print('I...
5,314,175
def kllossGn2(o, l: 'xtrue'): """KL loss for Gaussian-mixture output, 2D, precision-matrix parameters.""" dx = o[:,0::6] - l[:,0,np.newaxis] dy = o[:,2::6] - l[:,1,np.newaxis] # precision matrix is positive definite, so has positive diagonal terms Fxx = o[:,1::6]**2 Fyy = o[:,3::6]**2 # precision...
5,314,176
def IngestApprovalDelta(cnxn, user_service, approval_delta, setter_id, config): """Ingest a protoc ApprovalDelta and create a protorpc ApprovalDelta.""" fids_by_name = {fd.field_name.lower(): fd.field_id for fd in config.field_defs} approver_ids_add = IngestUserRefs( cnxn, approval_d...
5,314,177
def get_diff_level(files): """Return the lowest hierarchical file parts level at which there are differences among file paths.""" for i, parts in enumerate(zip(*[f.parts for f in files])): if len(set(parts)) > 1: return i
5,314,178
def get_max(list_tuples): """ Returns from a list a tuple which has the highest value as first element. If empty, it returns -2's """ if len(list_tuples) == 0: return (-2, -2, -2, -2) # evaluate the max result found = max(tup[0] for tup in list_tuples) for result in li...
5,314,179
def prepare_observation_lst(observation_lst): """Prepare the observations to satisfy the input fomat of torch [B, S, W, H, C] -> [B, S x C, W, H] batch, stack num, width, height, channel """ # B, S, W, H, C observation_lst = np.array(observation_lst, dtype=np.uint8) observation_lst = np.move...
5,314,180
def test_problem_builder(name: str, n_of_variables: int = None, n_of_objectives: int = None) -> MOProblem: """Build test problems. Currently supported: ZDT1-4, ZDT6, and DTLZ1-7. Args: name (str): Name of the problem in all caps. For example: "ZDT1", "DTLZ4", etc. n_of_variables (int, optional)...
5,314,181
def fetch_text(session, labelings, verbose=False): """ Fetches article text and metadata for labelings from a MediaWiki API. :Parameters: session : :class:`mwapi.Session` An API session to use for querying labelings : `iterable`(`dict`) A collection of labeling event...
5,314,182
def _on_publish(c, userdata, mid): """Internal callback""" if len(userdata) == 0: c.disconnect() else: _do_publish(c)
5,314,183
def get_coord_y(x, y): """ Function returns the y value of the coordinate :param x: x value of coordinate :param y: y value of coordinate :return: y value of coordinate """ coord = Coordinates(x, y) return coord.get_y()
5,314,184
def install_deps(deps: str, location: str) -> None: """CLI install dependencies.""" click.echo(f"Installing deps... {deps}") _deps(deps, location)
5,314,185
def shutdown_server(host: str, port: int) -> None: """ Shutdown the server running on the specified host and port. """ _shutdown_server(host, port)
5,314,186
def calc_som2_flow(som2c_1, cmix, defac): """Calculate the C that flows from surface SOM2 to soil SOM2. Some C flows from surface SOM2 to soil SOM2 via mixing. This flow is controlled by the parameter cmix. Parameters: som2c_1 (numpy.ndarray): state variable, C in surface SOM2 ...
5,314,187
def cdlseparatinglines(opn, high, low, close): """Separating Lines: Bullish Separating Lines Pattern: With just two candles – one black (or red) and one white (or green) – the Bullish Separating Lines pattern is easy to learn and spot. To confirm its presence, seek out the following criteria: F...
5,314,188
def preparse_tsunami_watch(information_urls, app): """ Filters tsunami watch information from other information. :param information_urls: The information urls list :param app: The Flask app instance """ start_preparse_time = time.perf_counter() app.logger.debug("Start pre-parsing tsunami wa...
5,314,189
def _check_filter_function(filtered, lenx): """ helper function to check the results of a provided filter function Parameters ---------- filtered : :py:class:`numpy.ndarray` must be of length lenx, and only contain 0, 1 or NaNs lenx : int length of the data frame provided to ``f...
5,314,190
def add_history(line): """Append a line to the history buffer, as if it was the last line typed.""" Readline.addToHistory(line)
5,314,191
def get_context(file_in): """Get genomic context from bed file""" output_dict = {} handle = open(file_in,'r') header = handle.readline().rstrip('\n').split('\t') for line in handle: split_line = line.rstrip('\n').split('\t') contig,pos,context = split_line[:3] if context == '...
5,314,192
def get_rating_users_total(contest_id: ContestID) -> int: """Return the number of unique users that have rated bungalows in this contest. """ return User.query \ .join(Rating) \ .join(Contestant) \ .filter(Contestant.contest_id == contest_id) \ .distinct() \ .coun...
5,314,193
def read_from_file(filename): """ Reads the set of known plaintexts from the given file. """ candidates = [] with open(filename) as f: lines = f.readlines() if len(lines) > 5: # from first candidate, # to the end of the file, # counting in incre...
5,314,194
def galactic_offsets_to_celestial(RA, Dec, glongoff=3, glatoff=0): """ Converts offsets in Galactic coordinates to celestial The defaults were chosen by Pineda for Galactic plane survey @param RA : FK5 right ascension in degrees @type RA : float @param Dec : FK5 declination in degrees @type Dec...
5,314,195
def compute_regularizer_term(model: LinearNet, criterion: torch.nn.modules.loss.CrossEntropyLoss, train_data: Tuple[torch.Tensor, torch.Tensor], valid_data: Tuple[torch.Tensor, torch.Tensor], weight_decays: List[torch.Tensor], zeta: ...
5,314,196
def get_to_and(num_bits: int) -> np.ndarray: """ Overview: Get an np.ndarray with ``num_bits`` elements, each equals to :math:`2^n` (n decreases from num_bits-1 to 0). Used by ``batch_binary_encode`` to make bit-wise `and`. Arguments: - num_bits (:obj:`int`): length of the generating...
5,314,197
def in_role_list(role_list): """Requires user is associated with any role in the list""" roles = [] for role in role_list: try: role = Role.query.filter_by( name=role).one() roles.append(role) except NoResultFound: raise ValueError("role '{...
5,314,198
def handle_not_start(fsm_ctx): """ :param ctx: FSM Context :return: False """ global plugin_ctx plugin_ctx.error("Could not start this install operation because an install operation is still in progress") return False
5,314,199