content
stringlengths
22
815k
id
int64
0
4.91M
def set_fact_flags(flag_args: Tuple[str]) -> None: """Take "--fact" flags from the CLI and store them in the config as a dict.""" facts = {} for arg in flag_args: if ":" not in arg: logger.critical('Arguments to "--fact" must be colon seperated.') logger.critical('Like: "ult...
69,400
def test_is_same_file_path(): """Same file is same with path input.""" assert filesystem.is_same_file(Path('./tests/testfiles/test.txt'), Path('./tests/testfiles/test.txt'))
69,401
def _performDragAndDropWithMouse(driver, pages): """Copied from org.openqa.selenium.interactions.TestBasicMouseInterface.""" pages.load("draggableLists.html") dragReporter = driver.find_element_by_id("dragging_reports") toDrag = driver.find_element_by_id("rightitem-3") dragInto = driver.find_element...
69,402
def _parse_option(line): """ Parses option line. Returns (name, value). Raises ValueError on invalid syntax or unknown option. """ match = _OPTION_REGEX.match(line) if not match: raise ValueError('Invalid syntax') for name, type_ in _OPTIONS: if name == match.group(1): ...
69,403
def pyside2_app(): """PySide2 implementation.""" PyCalcConfig('config.ini').write() # Import QApplication from PySide2.QtWidgets from PySide2.QtWidgets import QApplication # Import the view and the controller from pycalc.pyside2_vc.ps2_view import PyCalcUi from pycalc.pyside2_vc.ps2_contro...
69,404
def convert(from_unit, to_unit, *args, **kwargs): """ Convert the value from one unit to another :param from_unit: Source unit :param to_unit: Target unit :param args: Additional parameters (values) :param kwargs: Additional parameters (additional values like for conversion watts to ohms) :r...
69,405
def do_vbox(argv): """ :: Usage: vbox version [--format=FORMAT] vbox image list [--format=FORMAT] vbox image find NAME vbox image add NAME vbox vm list [--format=FORMAT] [-v] vbox vm delete NAME vbox vm config NAME vbox vm ip NAME [--all] ...
69,406
def hex_validator(length=0): """ Returns a function to be used as a model validator for a hex-encoded CharField. This is useful for secret keys of all kinds:: def key_validator(value): return hex_validator(20)(value) key = models.CharField(max_length=40, validators=[key_validat...
69,407
def substitute_domains(regex_list, file_list, root_dir, log_warnings=True): """Runs domain substitution with regex_list over files file_list""" for path in file_list: try: with (root_dir / path).open(mode="r+b") as file_obj: content = file_obj.read() file_sub...
69,408
def bytes_feature(value): """Create a multi-valued bytes feature from a single value.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
69,409
def setup_model(args): """Setup model and optimizer.""" model = get_model(args) # if args.deepspeed: # print_rank_0("DeepSpeed is enabled.") # # model, _, _, _ = deepspeed.initialize( # model=model, # model_parameters=model.parameters(), # args=args,...
69,410
def mkmatrix(m, n): """ Return a random invalid correlation matrix of order `m+n` with a positive definite top left block of order `m`. """ while True: A = randcorr(m) #B = randcorr(n) B = np.identity(n) Y = np.matrix(np.random.randn(m, n) / (m+n)**1.2) M0 = ...
69,411
def deformationGrid(flowFcn, domainRange, gridSize, numPoints, directory=None): """ flowFcn : flow function gridSize : size of the grid, it is a list domainRange: it is a list of tuples specifying the range of the domain numPoints : density of points in each line """ ptsList = [] mvPtsLi...
69,412
def func_to_paired_cols(df, col1, col2, fn, name): """Perform a function such as an arithmetic operation on a pair of columns. Args: df (:obj:`pd.DataFrame`): Data frame, which will be modified in-place. col1 (str): Name of first column. col2 (int): Name of second column. fn...
69,413
def remove_last_range(some_list): """ Returns a given list with its last range removed. list -> list """ return some_list[:-1]
69,414
def test_parse_substitution_from_list_without_is_multiline(): """ Make sure we can parse a list without the is_multiline option set, i.e. just a two element list. """ target = substitute.Substitution('foo', 'bar', False) list_rep = ['foo', 'bar'] actual = config.parse_substitution_from_list(...
69,415
def lazy_bind(concrete_type, unbound_method): """ Returns a function that lazily binds `unbound_method` to a provided Module IValue, then invokes the method. We do this so that any Python shenanigans that will poison type sharing are impossible at compile time. """ def lazy_binding_method(cp...
69,416
def remove_folder(folder): """ Remove folder if it exists. :param str folder: """ if os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True)
69,417
def FigureToSummary(name, fig): """Create tf.Summary proto from matplotlib.figure.Figure. Args: name: Summary name. fig: A matplotlib figure object. Returns: A `tf.Summary` proto containing the figure rendered to an image. """ canvas = backend_agg.FigureCanvasAgg(fig) fig.canvas.draw() ncols...
69,418
def test_plannertree_route(cl_operator): """plannertree route test""" response = cl_operator.get(url_for('visuals.plannertree_route')) assert response.status_code == HTTPStatus.OK
69,419
def temp_paths(): """Creates and deletes paths for letsencrypt-auto and its venv.""" dir = mkdtemp(prefix='le-test-') try: yield join(dir, 'letsencrypt-auto'), join(dir, 'venv') finally: rmtree(dir, ignore_errors=True)
69,420
def require_dict(value: Optional[Dict[Any, Any]], key_type: Any=None, value_type: Any=None, allow_none: bool=False) -> Any: """Make sure a value is a Dict[key_type, value_type]. Used when dealing with http input data. """ if value is None and allow_none: return value if typ...
69,421
def reconstructTimestamp(currentTimestamp, lsbTimestamp): """ Reconstructs a timestamp from a partial timestamp, that only has the least significant bytes. :param currentTimestamp: Current time, obtained with time.time(). :param lsbTimestamp: Partial (least significant) timestamp, as a uint16. :retu...
69,422
def get_date_print_format(date_filter): """ Utility for returning the date format for a given date filter in human readable format @param date filter : the given date filter @return the date format for a given filter """ vals = { 'day': '[YYYY-MM-DD]', 'hour': '[YYYY-MM-DD : HH]' } return vals[date_filter]
69,423
def loadTempTranscript(tempFileName): """ Load a temp transcript file by name """ # todo lot of copy/paste from above if os.path.exists(tempFileName): with open(tempFileName, 'rb') as tempFile: try: return [m for line in tempFile.readlines() for m in json.loads(li...
69,424
def for_l(): """ Lower case Alphabet letter 'l' pattern using Python for loop""" for row in range(6): for col in range(3): if col==0 and row==5 or col==1 and row!=5 or col==2 and row==5: print('*', end = ' ') ...
69,425
def pre_submission(*args, **kwargs): """ Perform a presubmit of a list of local files. This is the first stage for a batch submit of files. Variables: None Arguments: None Data Block (REQUIRED): { "1": # File ID {"sh...
69,426
def _historical_user_data_for_decisions(user: User, days: int) -> List: """ Return public data regarding the clicked Statements for a certain user :param days: The number of days ending with today for which the data shall be procured. :param user: The user for which the data shall be procured. :ret...
69,427
def OptimiseGuestPositionAtWindow(xnDataset,hostData,hostCrystal,arGuestAtomFracPositions,lsGuestAtomChemSymbols,sHostGuestName,sRootOutputDir,bReloadWindowState): """Optimise guest molecule position at the window position using global optimiser. [xnDataset]: XML node, config 'dataset' node with this dataset's detail...
69,428
def collapse_locations(obj_list, keyname): """ Given a CustomQuerySet object, filter/aggregate it down so we just have one item per country or city. keyname is 'country' or 'city'. Also drop the 'privacy_country' or 'privacy_city' field. On input, we might have: country privacy_coun...
69,429
def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new ha...
69,430
def is_sciobj_valid_for_create(): """When RESOURCE_MAP_CREATE == 'reserve', objects that are created and that are also aggregated in one or more resource maps can only be created by a DataONE subject that has write or changePermission on the resource map.""" # TODO return True
69,431
def filter_by_indices(good_indices, vals): """ 从分段算法得到的下标集合中得到 对应的轨迹点集合 :param good_indices: 下标集合 :param vals: 原始点数据(未分段) 集合 :return: 分段后的点集合 """ vals_iter = iter(vals) good_indices_iter = iter(good_indices) out_vals = [] num_vals = 0 for i in good_indices_iter: if i != ...
69,432
def match_func(cor, exc, tolerance): """ Check if coordinate matches expected coordinate within a given tolerance. cor - coordinate exc - expected coordinate tolerance - error rate float coordinate elements will be checked based on this value list/tuple coordinate el...
69,433
def _figure_6(): """Plot of labelled event, zoomed.""" with open('figure6.pkl', 'rb') as f: data_sum, cusum_labels, cusum_pc_1_labels, vae_labels, vae_rnn_labels, true_labels = pickle.load(f) l, r = 1570, 1630 data_sum = data_sum[l:r] cusum_labels = cusum_labels[l:r] cusum_pc_1_labels...
69,434
def transform_tabular_data(xml_input): """ Converts table data (xml) from BambooHR into a dictionary with employee id as key and a list of dictionaries. Each field is a dict with the id as the key and inner text as the value e.g. <table> <row id="321" employeeId="123"> ...
69,435
def gen_index_noddi(in_bval, b0_index): """ This is a function to generate the index file for FSL eddy :param in_bval: :param b0_index: :return: """ import numpy as np import os out_file = os.path.abspath('index.txt') bvals = np.loadtxt(in_bval) vols = len(bvals) index_li...
69,436
def create_workflow(name=None, namespace=None, bucket=None, **kwargs): # pylint: disable=too-many-statements """Create workflow returns an Argo workflow to test kfctl upgrades. Args: name: Name to give to the workflow. This can also be used to name things associated with the workflow. """ builder = B...
69,437
def create_annotation_model(table_name: str, annotation_columns: dict, with_crud_columns: bool=True): """ Create an declarative sqlalchemy annotation model. Parameters ---------- table_name : str Specified table_name. annotation_colum...
69,438
def speed_control(target, current, Kp=1.0): """ Proportional control for the speed. :param target: target speed (m/s) :param current: current speed (m/s) :param Kp: speed proportional gain :return: controller output (m/ss) """ return Kp * (target - current)
69,439
def value_to_name(klass): """ Generate a function to convert an IntEnum value to its name. :param type klass: the class defining the IntEnum :returns: a function to convert a single number to a name :rtype: int -> str """ def the_func(num, terse_unknown=False): """ Convert ...
69,440
def np_ortho(shape, random_state): """ Builds a theano variable filled with orthonormal random values """ g = random_state.randn(*shape) o_g = linalg.svd(g)[0] return o_g.astype(theano.config.floatX)
69,441
def force_func(biorbd_model: biorbd.Model, use_excitation: bool = False): """ Define the casadi function that compute the muscle force. Parameters ---------- biorbd_model : biorbd.Model Model of the system. use_excitation : bool If True, use the excitation of the muscles. R...
69,442
def _flatten_module(module, recursive, predicate, attribute_traversal_key, attributes_to_ignore, with_path, module_path=(), seen=None): """Implementation of `flatten`.""" if se...
69,443
def geolocalize_map(request): """ Args: request (flask.Request): HTTP request object JSON example: {"uri": "https://i.stack.imgur.com/WiDpa.jpg"} """ request_json = request.get_json() if request.args and 'uri' in request.args: uri = request.args.get('uri') elif request_js...
69,444
def ReLU(x, alpha): """ Wrapper for using a ReLU activation function TODO: Implement an option for choosing between relu, leaky relu and prelu. """ # return tf.nn.relu(x) # return leakyReLU(x, 0.001) # return parametricReLU(x, alpha) return tf.nn.elu(x) # return tf.tanh(x)
69,445
def init_db_command(): """The command line version of the function init_db, call it with 'init-db'. """ init_db() click.echo('Initialized the database.')
69,446
def _is_valid_case(obj): """Returns True if ``obj`` is a valid test case Criteria for being a valid test case: - Is a class and a subclass of :class:`WebDriverTestCase <webdriver_test_tools.testcase.webdriver.WebDriverTestCase>` - Is not :class:`WebDriverTestCase <webdriver...
69,447
def cajeroExist(): """ Verifica la existencia de un registro en CajaCajero :return: """ try: movimientoid = CajaCajero.objects.latest('id_movimiento') except CajaCajero.DoesNotExist: movimientoid = None pass return movimientoid
69,448
def get_reaktor(): """Returns the reaktor instance from the app globals.""" if not hasattr(g, '_reaktor'): g._reaktor = Reaktor(**current_app.config['REAKTOR_CONFIG']) return g._reaktor
69,449
async def test_one_lock_operation(hass): """Test creation of a lock with doorsense and bridge.""" lock_one = await _mock_doorsense_enabled_august_lock_detail(hass) await _create_august_with_devices(hass, [lock_one]) lock_online_with_doorsense_name = hass.states.get("lock.online_with_doorsense_name") ...
69,450
def get_outpath(filename, outdir): """Get output filepath. :filename: name of music file :outdir: path of output directory :returns: path of converted music file """ outname = '{}.mp3'.format(os.path.splitext(filename)[0]) outpath = os.path.join(outdir, outname) return outpath
69,451
def test_how_do_i_override_rendering_of_the_input_field(): # language=rst """ .. _Field.input: How do I override rendering of the input field? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pass a template name or a `Template` object to the `input` namespace: """ form = Form( ...
69,452
def _Bezier3Seg(p1, p2, c1, c2, gs): """Return a 'B' segment, transforming coordinates. Args: p1: (float, float) - start point p2: (float, float) - end point c1: (float, float) - first control point c2: (float, float) - second control point gs: _SState - used to transform coordina...
69,453
def gather( v: torch.Tensor, split_in: qp.utils.TaskDivision, comm: qp.MPI.Comm, dim: int, ) -> torch.Tensor: """Return the contents of v, changed from split based on split_in on communicator comm and dimension dim, to not-split i.e. fully available on all processes.""" # Bring split dim...
69,454
def match_nans(x, y): """Performs pairwise matching of nans between ``x`` and ``y``. Args: x, y (ndarray or xarray object): Array-like objects to pairwise match nans over. Returns: x, y (ndarray or xarray object): If either ``x`` or ``y`` has missing data, adds nans in the same...
69,455
def index(): """User's homepage after logging or signing in""" # Fetch posts of user and whoever the user follows. posts = Posts.query.all() return render_template("index.html", posts=posts)
69,456
def calculator_post(): """index_get""" return CalculatorController.post()
69,457
def print_number_str(value, justify_right=True): """Print a 4 character long string of numeric values to the display. This function is similar to print_str but will interpret periods not as characters but as decimal points associated with the previous character. """ setup() display.print_numb...
69,458
def randomPairs(n_records, sample_size): """ Return random combinations of indices for a square matrix of size n records. For a discussion of how this works see http://stackoverflow.com/a/14839010/98080 """ n = int(n_records * (n_records - 1) / 2) if sample_size >= n: random_pairs ...
69,459
def test_sample_processing_pedigree(testapp, sample_proc_fam): """This is an end to end test for calculating relationships Test for roles""" expected_values = { 'GAPIDPROBAND': {'sample_accession': 'GAPSAPROBAND', 'sample_name': 'ext_id_006', 'parents': ['GAPIDMOTHER1', 'GAP...
69,460
def test_shorthand_url(): """Test curl-like shorthand url and auto adding scheme support.""" ns = Namespace(endpoint_url=":3000/foo", user=None, password=None) assert Command(ns).fs.client.base_url == "http://localhost:3000/foo" ns.endpoint_url = ":/foo" assert Command(ns).fs.client.base_url == "ht...
69,461
def test_import_optional_float_field(): """ Test for a Float type """ s = ''' type Swallow { """ What is the airbourn speed of unladen african swallow? """ speed: Float } ''' output = sdl_importer.import_sdl(s) what_it_should_be = ( "import typ...
69,462
def is_parsed_result_successful(parsed_result): """Returns True if a parsed result is successful""" return parsed_result['ResponseMetadata']['HTTPStatusCode'] < 300
69,463
def create_config(config_path, storage_path, log_path, provision_pack_path, iot_api_url): """ Create config for TrustProvisioner """ parser = ConfigParser(interpolation=ExtendedInterpolation()) parser["MAIN"] = { "storag...
69,464
def interact_model( model_name='117M', seed=None, nsamples=1, step=1, length=64, prompt="\n", clear=None, maxlen=-1, temperature=1, top_k=0, top_p=0, penalize=0 ): """ Interactively run the model :model_name=117M : String, which model to use :seed=None : I...
69,465
def validate(game_state: GameState) -> None: """ Runs a series of checks to validate the current game state (e.g., no duplicate cards, the trick points are correct based on won tricks and announced marriages). It does not perform type checks directly. It does not perform complex checks. For example, it does...
69,466
def _generate_random_pos_def_tri_diag( batch_shape: Tuple, outer_dim: int, inner_dim: int, has_sub_diag: bool ) -> Tuple[np.ndarray, SymmetricBlockTriDiagonal]: """ Create a random tri-diagonal symmetric positive definite matrix. This works by creating a lower triangular tri-diagonal matrix and multipl...
69,467
def remove_white(apps, schema_editor): """don't hardcode white announcements""" db_alias = schema_editor.connection.alias announcement_model = apps.get_model("bookwyrm", "Announcement") announcement_model.objects.using(db_alias).filter(display_type="white-ter").update( display_type=None )
69,468
def get_deployment(*, name, namespace, k8s_client, raw=True): """Get a Deployment resource. Parameters ---------- namespace : `str` The Kubernetes namespace where the Strimzi Kafka cluster operates. name : `str` The name of the Deployment. k8s_client A Kubernetes client ...
69,469
def algorithm2(f,r1,r2,x0,y0,L = (1,1),maxit = [1000,1000],tol = [1e-3,1e-3],warmstart=True,): """ Variable projection method for problems of the form min_{x,y} f(x,y) + r_1(x) + r_2(y) with $f$ Lipschitz smooth and r_1, r_2 are convex and proxible. Input ----- f - function retu...
69,470
def reset_modifications() -> None: """ Undo all static modifications and reset to the standard amino acid monoisotopic masses. """ global aa_mass aa_mass = _aa_mass.copy()
69,471
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the CoinMarketCap sensor.""" currency = config.get(CONF_CURRENCY) try: CoinMarketCapData(currency).update() except HTTPError: _LOGGER.warning("Currency '%s' is not available. Using 'bitcoin'", ...
69,472
def iterate_frameworks(path: str) -> Iterator[Tuple[str, str]]: """ Iterates over the known frameworks. :param path: The path to the frameworks.csv file. :return: An iterator over the following fields of the known frameworks: - name - version """ ...
69,473
def PopularTagsPerLang(df, lang, top_k = 10): """ Function: Get top k tags with largest number of fanworks by media and in selected language. Input: - df: pandas.DataFrame. - lang: list[str], languages to include. - top_k: int, number of top tags to include. Output: - df_top: pandas....
69,474
def hist_match(source, template): """ Adjust the pixel values of a grayscale image such that its histogram matches that of a target image Arguments: ----------- source: np.ndarray Image to transform; the histogram is computed over the flattened array templat...
69,475
def keys_are_inserted_in_sd(self, example_sd): """keys are inserted in sd.""" for k, v in self.pairs: assert k in example_sd
69,476
def design_matrix(x): """ Build the design matrix for linear regression for a given array of x-values. This creates a (N, 2) matrix, where the first column are the x values and the second contains all 1. """ X = np.empty((len(x), 2), dtype=x.dtype) X[:, 0] = x X[:, 1] = 1 retur...
69,477
def main(): """omnimacro's main entry point.""" namespace = parse_cmd_args() if namespace.play: play_events(namespace.path) else: log_events(namespace.path)
69,478
def r_min_KimKim(T_sat, sigma, h_fg, rho, deltaT_sub): """ minimum droplet radius """ r_min = 2*T_sat*sigma / (h_fg * rho * deltaT_sub) return r_min
69,479
def get_prefix(given_name): """ Assuming the given name adheres to the naming convention of crab this will extract the prefix element of the name. :param given_name: Name to extract from :type given_name: str or pm.nt.DependNode :return: str """ return str(given_name).split(':')[-1].sp...
69,480
def get_predicates(): # noqa: E501 """get_predicates Get a list of predicates used in statements issued by the knowledge source # noqa: E501 :rtype: List[BeaconPredicate] """ df = dh.load_edges() d = df.groupby(['edgelabel', 'relation']).size().to_dict() predicates = [] for (edge_l...
69,481
def cat_transform(train_var: np.array, test_var: np.array): """remap number to categorical variable and save dictionaries. test_var is then mapped according to the train_var""" dict_list = [] train_var_shape = train_var.shape test_var_shape = test_var.shape if len(train_var.shape)==1: tr...
69,482
def cov(data): """ Covariance matrix note: specifically for mean-centered data note: numpy's `cov` uses N-1 as normalization """ return _np.dot(data.T, data) / data.shape[0]
69,483
def dynesty_loglike_bma(cube, interpolator): """Dynesty log likelihood wrapper for BMA.""" theta = build_params(cube, coordinator, fixed, use_norm) return log_likelihood(theta, star, interpolator, use_norm, av_law)
69,484
def get_graph_from_workflow(workflow): """ :type workflow: dart.model.workflow.Workflow """ entity = GraphEntity('workflow', workflow.id, workflow.data.name, workflow.data.state) return {'results': graph_entity_service().get_entity_graph(entity).to_dict()}
69,485
def update(api, bus_indices, default_line_frequency, period, use_trace, trace_path, state_queue): """Update the state of the sensor. Parameters ---------- api : GridAPI API to use to query the grid for the state. bus_indices : iterable Which buses to obtain the stat...
69,486
def setup_pipeline(config): """ Given a configuration from QLF, this sets up a pipeline [pa,qa] and also returns a conversion dictionary from the configuration dictionary so that Pipeline steps (PA) can take them. This is required for runpipeline. """ qlog=qllogger.QLLogger() log=qlog.getlog...
69,487
def get_module(full_name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the Python module. """ name = full_name.split('.')[-1] base_path = os.path.dirname(file_path) mochi_name = os.path.join(base_path, name + '.mochi') py_name = os.path...
69,488
def justice_league_super(superhero): """Fetch the Justice League character whose super name matches the path variable supplied by the user, or a 404 if not.""" canonicalized = superhero.replace(" ", "").lower() for character in justice_league_members: search_term = character["superhero"].rep...
69,489
def store(username, group, usersList): """Store the scraped users list in a file saved into a folder that has the same name as the username.""" date = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%S') path = '{}/{}{}.pkl'.format(_base_directory(username), group, date) return _write(...
69,490
def northwind(table_name): """ Yield a stream of "records" as dictionaries, with certain adjustments. So it turns out my source of NorthWind data has a bizarre nonstandard format: Embedded commas are those followed by whitespace! The usual csv module doesn't handle that by default and neither does MS Excel. For...
69,491
def get_rbf_svm_classifier(X_train, y_train, random_state=None, cv_folds=5): """ A classifier that performs classification based on support vector machine. X - a (n_training_examples, n_features) np.matrix containing the features of all training examples. y - a (n_training_examples, 1) np.array containi...
69,492
def test_joboffer_get_visualizations_full(): """ Test get_visualizations with all the event types """ joboffer = JobOfferFactory.create() JobOfferAccessLogFactory.create_batch( size=1, event_type=EventType.LISTING_VIEW, joboffer=joboffer ) JobOfferAccessLogFactory.create_batch( s...
69,493
def bump_version_from_release_branch(file): """ Get version from release branch and bump version files """ click.echo( 'Version bumped to "{}"'.format( bump_version_from_release_branch_func(file) ) )
69,494
def invalid_object_type(request, source_session): """Create invalid object types MIGRATION_DATA""" with create_data_object(source_session, DATA_TEMPLATE) as data_obj: yield [MIGRATION_DATA(object_type=request.param, source_handle=data_obj[0])]
69,495
def perform_db_upgrade_0_to_1(conn: ConnectionPlus) -> None: """ Perform the upgrade from version 0 to version 1 Add a GUID column to the runs table and assign guids for all existing runs """ sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='runs'" cur = atomic_transaction(con...
69,496
def connect(sid, test): """ The function to establish a connection. """ try: socket_server.emit('Connected', {'data': 'Connected'}, room=sid) except socketio.exceptions.ConnectionError as error: LOGGER.error("Connection Failed {}".format(error))
69,497
def eddy_fsl_pipeline(low_bval, use_cuda, initrand, name="eddy_fsl"): """Use FSL eddy for head motion correction and eddy current distortion correction.""" import nipype.interfaces.utility as niu import nipype.pipeline.engine as pe from nipype.interfaces.fsl.epi import Eddy from clinica.utils.dwi i...
69,498
def calc_z1_from_Vs30(Vs30_in_meter_per_sec): """ Calculate z1 (basin depth) from Vs30. The correlation used here is z1 = 140.511 * exp(-0.00303 * Vs30), where the units of z1 and Vs30 are both SI units. This formula is documented in Section 2.5 (page 30) of the following PhD thesis: Shi, Ji...
69,499