content
stringlengths
22
815k
id
int64
0
4.91M
def op_lessthan(this): """ Stack operations make this flipped! """ if this.pop() > this.pop(): this.push(1) else: this.push(0)
7,200
def test_safe_print_string(): """[Utils] safe_print: accepts flush and stream name as string.""" with open(os.devnull, 'w') as f, redirect_stdout(f): utils.safe_print('test', flush=True, file="stdout")
7,201
def p(*args, **kwargs): """ Pretty print the object for debug :param kwargs: :param args: :return: """ (frame, filename, line_number, function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[1] print(':: [%s] => %s:%s' % (path.basename(filename), func...
7,202
def calc_dof(model): """ Calculate degrees of freedom. Parameters ---------- model : Model Model. Returns ------- int DoF. """ p = len(model.vars['observed']) return p * (p + 1) // 2 - len(model.param_vals)
7,203
def parse_event_export_xls( file: StrOrBytesPath, parsing_elements: list[str] = _ALL_PARSING_ELEMENTS ) -> ParsedEventResultXlsFile: """Parse a Hytek MeetManager .hy3 file. Args: file (StrOrBytesPath): A path to the file to parse. parsing_elements (Sequence[str]): Elements to extract from t...
7,204
def test_expected_values(runner): """The generate_sample method should return a dictionary containing all expected values""" all_results = [runner.result] + [other_runner.result for other_runner in runner.race.active_runners if other_runner['_id'] != runner['_id']] raw_query_data = [] for key in ('bar...
7,205
def create_form(request, *args, **kwargs): """ Create a :py:class:`deform.Form` instance for this request. This request method creates a :py:class:`deform.Form` object which (by default) will use the renderer configured in the :py:mod:`h.form` module. """ env = request.registry[ENVIRONMENT_KEY]...
7,206
def get_lsl_inlets(streams=None, with_source_ids=('',), with_types=('',), max_chunklen=0): """Return LSL stream inlets for given/discovered LSL streams. If `streams` is not given, will automatically discover all available streams. Args: streams: List of `pylsl.StreamInfo` or...
7,207
def from_dtw2dict(alignment): """Auxiliar function which transform useful information of the dtw function applied in R using rpy2 to python formats. """ dtw_keys = list(alignment.names) bool_traceback = 'index1' in dtw_keys and 'index2' in dtw_keys bool_traceback = bool_traceback and 'stepsTake...
7,208
def fix_bad_symbols(text): """ HTML formatting of characters """ text = text.replace("è", "è") text = text.replace("ä", "ä") text = text.replace("Ö", "Ä") text = text.replace("Ä", "Ä") text = text.replace("ö", "ö") text = text.replace("é", "é") text = text.replace("Ã¥", "å"...
7,209
def _level2partition(A, j): """Return views into A used by the unblocked algorithms""" # diagonal element d is A[j,j] # we access [j, j:j+1] to get a view instead of a copy. rr = A[j, :j] # row dd = A[j, j:j+1] # scalar on diagonal / \ B = A[j+1:, :j] # Block in corner | ...
7,210
def _null_or_int(val: Optional[str]) -> Optional[int]: """Nullify unknown elements and convert ints""" if not isinstance(val, str) or is_unknown(val): return None return int(val)
7,211
def stackset_exists(stackset_name, cf_client): """Check if a stack exists or not Args: stackset_name: The stackset name to check cf_client: Boto3 CloudFormation client Returns: True or False depending on whether the stack exists Raises: Any exceptions raised .describe_...
7,212
def main(argv): """ Main function for optimization demo """ # Get the arguments cfg_file, RobotWrapper, with_lqr = parse_arguments(argv) print RobotWrapper # Compute the motion (motion_planner, optimized_kin_plan, optimized_motion_eff, optimized_dyn_plan, dynamics_feedbac...
7,213
def convert_l_hertz_to_bins(L_p_Hz, Fs=22050, N=1024, H=512): """Convert filter length parameter from Hertz to frequency bins Notebook: C8/C8S1_HPS.ipynb Args: L_p_Hz (float): Filter length (in Hertz) Fs (scalar): Sample rate (Default value = 22050) N (int): Window size (Default va...
7,214
def write_cluster_summary(summary_fn, isoforms_fa, hq_fa=None, lq_fa=None): """Extract number of consensus isoforms predicted, and total number of bases in all consensuus isoforms from isoforms_fa and write the two attributes to summary_fn. if hq_fa (polished high-quality isoforms) is not None, report ...
7,215
def macrostate_to_dnf(macrostate, simplify = True): """ Returns a macrostate in disjunctive normal form (i.e. an OR of ANDs). Note that this may lead to exponential explosion in the number of terms. However it is necessary when creating Multistrand Macrostates, which can only be represented in this way. Also, w...
7,216
def construct_features(all_data): # type: (pd.DataFrame) -> pd.DataFrame """ Create the features for the model :param all_data: combined processed df :return: df with features """ feature_constructor = FeatureConstructor(all_data) return feature_constructor.construct_all_features()
7,217
def tree_viewer(treefolder): """ DESCRIPTION: A function to create the representation of the tree with ete. Given the folder with the files in the tree folder it creates the tree representation in the media folder. :param treefolder: [pathlib] route to the subfolder in the tree folder which contains...
7,218
def restore_ckpt_from_path(ckpt_path: Text, state: Optional[TrainState] = None): """Load a checkpoint from a path.""" if not gfile.exists(ckpt_path): raise ValueError('Could not find checkpoint: {}'.format(ckpt_path)) logging.info('Restoring checkpoint from %s', ckpt_path) with gfile.GFile(ckpt_path, 'rb')...
7,219
def _GetChannelData(): """Look up the channel data from omahaproxy.appspot.com. Returns: A string representing the CSV data describing the Chrome channels. None is returned if reading from the omahaproxy URL fails. """ for unused_i in range(_LOOKUP_RETRIES): try: channel_csv = urllib2.urlopen...
7,220
def look(direction=Dir.HERE): """ Looks in a given direction and returns the object found there. """ if direction in Dir: # Issue the command and let the Obj enumeration find out which object is # in the reply # Don't use formatted strings in order to stay compatible to Python 3....
7,221
def test_fixed_grid_meso(): """ This is equivalent to running the following bash script, which produces GLM grids with split events on the fixed grid at 2 km resolution in a sector defined by a center lon/lat point and a width and height given by using the mesoscale lookup. python make_GLM_grids.py...
7,222
def process_debug_data(debug_data, model): """Process the raw debug data into pandas objects that make visualization easy. Args: debug_data (dict): Dictionary containing the following entries ( and potentially others which are not modified): - filtered_states (list): List of arrays. Eac...
7,223
def check_to_cache(local_object, timeout: float = None) -> Tuple[Optional[bool], Optional[str], Optional[str]]: """ Type-check current commit and save result to cache. Return status, log, and log filename, or None, None, None if a timeout is hit. """ try: # As a hook we know we're in the projec...
7,224
def merge(a, b, path=None): """Deprecated. merges b into a Moved to siem.utils.merge_dicts. """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [str(key)]) ...
7,225
def cudnnActivationBackward(handle, mode, alpha, srcDesc, srcData, srcDiffDesc, srcDiffData, destDesc, destData, beta, destDiffDesc, destDiffData): """" Gradient of activation function. This routine computes the gradient of a neuron activation functio...
7,226
def post_attachment(fbid, media_url, file_type, is_reusable=False, messaging_type="RESPONSE", tag=None): """ Sends a media attachment to the specified user :param str fbid: User id to send the audio. :param str media_url: Url of a hosted media. :param str file_type: 'image'/'audio'/...
7,227
def random_categorical(logits, num_samples, seed): """Returns a sample from a categorical distribution. `logits` must be 2D.""" # TODO(siege): Switch to stateless RNG ops. return tf.random.categorical( logits=logits, num_samples=num_samples, seed=seed)
7,228
def create_or_update_dns_record(stack, record_name, record_type, record_value, hosted_zone_name, condition_field=""): """Create or Update Route53 Record Resource.""" return stack.stack.add_resource(RecordSetType( '{0}'.format(record_name.replace('.', '').replace('*', 'wildcard')), Condition=cond...
7,229
def _append_from_array(h5dataset, array, cstop, truncate=False, axis=0): """Append to a dataset from an array.""" dstart = h5dataset.shape[0] dstop = dstart + cstop h5dataset.resize(dstop, axis=axis) h5dataset[dstart:dstop] = array[0:cstop] if not truncate: h5dataset[dstart+cstop:] = 0.0
7,230
def med_filt(x, k=201): """Apply a length-k median filter to a 1D array x. Boundaries are extended by repeating endpoints. """ if x.ndim > 1: x = np.squeeze(x) med = np.median(x) assert k % 2 == 1, "Median filter length must be odd." assert x.ndim == 1, "Input must be one-dimensional...
7,231
def test_plot_grid(od_cup_anno_bboxes, od_cup_path): """ Test that `plot_grid` works. """ # test callable args def callable_args(): return od_cup_anno_bboxes, od_cup_path plot_grid(display_bboxes, callable_args, rows=1) # test iterable args od_cup_paths = [od_cup_path, od_cup_path, od...
7,232
def sync_or_create_user(openid_user): """ Checks the user, returned by the authentication-service Requires a user-dict with at least: sub, email, updated_at """ def _validate_user(openid_user): error = False msg = '' if not openid_user.get('sub'): error = True ...
7,233
def all_hmm(task): """Concatenate all HMM profiles into a database & press.""" base = noext(task.depends[-1]) # TODO - filter out *_all.hmm from `find` hits sh("cat %s.hmm `find %s/ -name '*.hmm' | grep -v '_all.hmm'` > %s" % (base, base, task.target)) sh("hmmpress -f %s" % task.target)
7,234
def test_catalogs(http_service: Any) -> None: """Should return status code 200 and many catalogs in a turtle body.""" url = f"{http_service}/catalogs" resp = requests.get(url) assert 200 == resp.status_code assert 0 < len(resp.content) assert "text/turtle; charset=utf-8" == resp.headers["Content...
7,235
def add_scalar_typesi_coord(cube, value='sea_ice'): """Add scalar coordinate 'typesi' with value of `value`.""" logger.debug("Adding typesi coordinate (%s)", value) typesi_coord = iris.coords.AuxCoord(value, var_name='type', sta...
7,236
def related_tags(parser, token): """ Retrieves a list of instances of a given model which are tagged with a given ``Tag`` and stores them in a context variable. Usage:: {% related_tags [objects] as [varname] %} The model is specified in ``[appname].[modelname]`` format. The tag must b...
7,237
def test_dates(): """Test using dates.""" rm = RangeMap() rm.set('b', datetime.date(1936, 12, 11)) rm.set('a', datetime.date(1952, 2, 6)) assert rm[datetime.date(1945, 1, 1)] == 'b' assert rm[datetime.date(1965, 4, 6)] == 'a' with pytest.raises(KeyError): rm[datetime.date(1900, 1, 1)]
7,238
def ShowOnce(msg): """Display a message if that message has not been shown already. Unlike logging.log_first_n, this will display multiple messages from the same file/line if they are different. This helps for things like the same line that shows 'missing %s': we'll see each value of %s instead of only the fir...
7,239
def assess(): """ RESTful CRUD controller """ # Load Models assess_tables() impact_tables() tablename = "%s_%s" % (module, resourcename) table = db[tablename] # Pre-processor def prep(r): if session.s3.mobile and r.method == "create" and r.interactive: # redirect t...
7,240
def local_purity(H, y, nn=None, num_samples=10): """ :param H: embedding to evaluate :param y: ground-truth classes :param nn: number of neighbours to consider, if nn=None evaluate for nn=[1...size of max cluster] :param num_samples: number of samples in the range (1, size of max cluster) """ ...
7,241
def test_get_sample_process_captures_output_by_default(): """Test that get_sample_process will enable stdout and stderr capture by default.""" cmd = 'echo "hey there!"' result: snafu.process.ProcessSample = snafu.process.get_process_sample(cmd, LOGGER, shell=True, retries=0) assert result.successful.st...
7,242
def flatten_sxpr(sxpr: str, threshold: int = -1) -> str: """ Returns S-expression ``sxpr`` as a one-liner without unnecessary whitespace. The ``threshold`` value is a maximum number of characters allowed in the flattened expression. If this number is exceeded the the unflattened S-expression is...
7,243
def chunks(sequence: Iterable[T], chunk_size: int = 2) -> Iterable[List[T]]: """ [1,2,3,4,5], 2 --> [[1,2],[3,4],[5]] """ lsequence = list(sequence) while lsequence: size = min(len(lsequence), chunk_size) yield lsequence[:size] lsequence = lsequence[size:]
7,244
def glycan_to_graph(glycan, libr = None): """the monumental function for converting glycans into graphs\n | Arguments: | :- | glycan (string): IUPAC-condensed glycan sequence (string) | libr (list): sorted list of unique glycoletters observed in the glycans of our dataset\n | Returns: | :- | (1) a list ...
7,245
def _check_argument_units(args, dimensionality): """Yield arguments with improper dimensionality.""" for arg, val in args.items(): # Get the needed dimensionality (for printing) as well as cached, parsed version # for this argument. try: need, parsed = dimensionality[arg] ...
7,246
def run(ex: "interactivity.Execution") -> "interactivity.Execution": """Exit the shell.""" ex.shell.shutdown = True return ex.finalize( status="EXIT", message="Shutting down the shell.", echo=True, )
7,247
def get_features(df, row = False): """ Transform the df into a df with basic features and dropna""" df_feat = df df_feat['spread'] = df_feat['high'] - df_feat['low'] df_feat['upper_shadow'] = upper_shadow(df_feat) df_feat['lower_shadow'] = lower_shadow(df_feat) df_feat['close-open'] = df_feat['c...
7,248
def match_prob_for_sto_embed(sto_embed_word, sto_embed_vis): """ Compute match probability for two stochastic embeddings :param sto_embed_word: (batch_size, num_words, hidden_dim * 2) :param sto_embed_vis: (batch_size, num_words, hidden_dim * 2) :return (batch_size, num_words) """ assert not...
7,249
def POST(path): """ Define decorator @post('/path'): """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): return func(*args, **kw) wrapper.__method__ = 'POST' wrapper.__route__ = path return wrapper return decorator
7,250
def BatchNorm( inputs, axis=-1, momentum=0.9, eps=1e-5, use_stats=-1, **kwargs): """Batch Normalization. `[Ioffe & Szegedy, 2015] <https://arxiv.org/abs/1502.03167>`_. We enforce the number of inputs should be *5*, i.e., it is implemented into a fused version. However, you can still fix th...
7,251
async def test_create_doorbell(opp): """Test creation of a doorbell.""" doorbell_one = await _mock_doorbell_from_fixture(opp, "get_doorbell.json") await _create_august_with_devices(opp, [doorbell_one]) binary_sensor_k98gidt45gul_name_motion = opp.states.get( "binary_sensor.k98gidt45gul_name_mot...
7,252
def problem_from_graph(graph): """ Create a problem from the given interaction graph. For each interaction (i,j), 0 <= i <= j <= 1 is added. """ n = graph.vcount() domain = Domain.make([], [f"x{i}" for i in range(n)], real_bounds=(0, 1)) X = domain.get_symbols() support = smt.And(*((X[e.source] <= X...
7,253
def rotate_points(x, y, x0, y0, phi): """ Rotate x and y around designated center (x0, y0). Args: x: x-values of point or array of points to be rotated y: y-values of point or array of points to be rotated x0: horizontal center of rotation y0: vertical center of rotation ...
7,254
def xpme( dates: List[date], cashflows: List[float], prices: List[float], pme_prices: List[float], ) -> float: """Calculate PME for unevenly spaced / scheduled cashflows and return the PME IRR only. """ return verbose_xpme(dates, cashflows, prices, pme_prices)[0]
7,255
def get_node(uuid): """Get node from cache by it's UUID. :param uuid: node UUID. :returns: structure NodeInfo. """ row = _db().execute('select * from nodes where uuid=?', (uuid,)).fetchone() if row is None: raise utils.Error('Could not find node %s in cache' % uuid, code=404) return...
7,256
def bisect_jump_time(tween, value, b, c, d): """ **** Not working yet return t for given value using bisect does not work for whacky curves """ max_iter = 20 resolution = 0.01 iter = 1 lower = 0 upper = d while iter < max_iter: t = (upper - lower) / 2 if twee...
7,257
def __session_kill(): """ unset session on the browser Returns: a 200 HTTP response with set-cookie to "expired" to unset the cookie on the browser """ res = make_response(jsonify(__structure(status="ok", msg=messages(__language(), 166)))) res.set_cookie("key", value="expired") retu...
7,258
def register_errorhandlers(app): """Register error handlers.""" def render_error(error): """Render error template.""" # If a HTTPException, pull the `code` attribute; default to 500 error_code = getattr(error, "code", 500) return render_template(f"errors/{error_code}.html"), err...
7,259
def lock(): """ Locks deploy Parallel deploys are not allowed """ ensure('build_to') echo_subtask("Creating `deploy.lock` file") create_entity( '/'.join([fetch('deploy_to'), 'deploy.lock']) , entity_type='file', protected=False )
7,260
def test_learn_periodic_id(): """Test ovk periodic estimator fit, predict. A=Id.""" regr_1 = ovk.OVKRidge('DPeriodic', lbda=0.01, period=2 * pi, theta=.99) regr_1.fit(X, y) assert regr_1.score(X_test, y_t) > 0.9
7,261
def pca_run(plink, sigmathreshold, projection_on_populations, numof_pc, numof_threads, draw_evec, draw_without_projection): """ run eigenstrat program """ # ------------------------ # # - run eigenstrat program - # # ------------------------ # plink_pca = plink + "_" + str(numof_pc) + "PC" te...
7,262
def login(browser): """ Login to OKPy. """ token = refresh_token(no_browser=not browser) print("Token = {}".format(token)) print("Token automatically saved")
7,263
def register(key): """Register callable object to global registry. This is primarily used to wrap classes and functions into the bcdp pipeline. It is also the primary means for which to customize bcdp for your own usecases when overriding core functionality is required. Parameters ----...
7,264
def _windows_long_path_name(short_path): """Use Windows' `GetLongPathNameW` via ctypes to get the canonical, long path given a short filename. """ if not isinstance(short_path, six.text_type): short_path = short_path.decode(_fsencoding()) import ctypes buf = ctypes.create_unicode_buffer...
7,265
def _create_behavioral_cloning_agent( time_step_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec, preprocessing_layers: types.NestedLayer, policy_network: types.Network) -> tfa.agents.TFAgent: """Creates a behavioral_cloning_agent.""" network = policy_network( time_step_spec.obse...
7,266
def prep_fastq_inputs(in_files, data): """Prepare bgzipped fastq inputs """ if len(in_files) == 1 and _is_bam_input(in_files): out = _bgzip_from_bam(in_files[0], data["dirs"], data) elif len(in_files) == 1 and _is_cram_input(in_files): out = _bgzip_from_cram(in_files[0], data["dirs"], da...
7,267
def Parser_fake_quantize_range_abs_max(args): """ A placeholder for an empty function. """ pass
7,268
def sidequery(): """Serves AJAX call for HTML content for the sidebar (*query* **record** page). Used when the user is switching between **material** and **record** pages. See also [M:RECORD.body][record.RECORD.body]. Client code: [{sidecontent.fetch}][sidecontentfetch]. """ session.forget(re...
7,269
def test_non_positive_integer_min_exclusive004_1580_non_positive_integer_min_exclusive004_1580_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : (facet=minExclusive and value=-7 and facet=maxInclusive and value=-1) and document value=-5 """ assert_bindings( schema="ms...
7,270
def learn_encoding_model_ln(sess, met, stimulus, response, ttf_in=None, initialize_RF_using_ttf=True, scale_ttf=True, lr=0.1, lam_l1_rf=0): """Learn GLM encoding model using the metric. Uses ttf to initialize the RF only if ttf_in...
7,271
def _moveTo(x, y): """Send the mouse move event to Windows by calling SetCursorPos() win32 function. Args: button (str): The mouse button, either 'left', 'middle', or 'right' x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None ...
7,272
def event_speakers_call(transaction): """ GET /speakers-calls/1/event :param transaction: :return: """ with stash['app'].app_context(): speakers_call = SpeakersCallFactory() db.session.add(speakers_call) db.session.commit()
7,273
def random_answers_2020_ml(): """ Generates random answers the machine learning challenge of hackathons :ref:`l-hackathon-2020`. """ df = pandas.DataFrame({"index": numpy.arange(473333)}) df['label'] = numpy.random.randint(low=0, high=2, size=(df.shape[0], )) df['score'] = numpy.random.rando...
7,274
def _buildParser(): """Returns a custom OptionParser for parsing command-line arguments. """ parser = _ErrorOptionParser(__doc__) filter_group = optparse.OptionGroup(parser, 'File Options', 'Options used to select which files to process.') filter_group.add_option( '-f', '--files', dest='files_pa...
7,275
def _sizeof_fmt(num, suffix='B'): """Format a number as human readable, based on 1024 multipliers. Suited to be used to reformat a size expressed in bytes. By Fred Cirera, after https://stackoverflow.com/a/1094933/1870254 Args: num (int): The number to be formatted. suffix (str...
7,276
def train( package: str, config: str, gpus: int, gpus_per_node: int = None, cpus_per_task: int = 2, partition: str = None, launcher: str = 'none', port: int = None, srun_args: Optional[str] = None, yes: bool = True, other_args: tuple = () ) -> Tuple[bool, Union[str, Exception...
7,277
def test_labels_painting(make_napari_viewer): """Test painting labels updates image.""" data = np.zeros((100, 100), dtype=np.int32) viewer = make_napari_viewer(show=True) viewer.add_labels(data) layer = viewer.layers[0] screenshot = viewer.screenshot(canvas_only=True, flash=False) # Check...
7,278
def CrawlWithSmbclient(config): """Crawls a list of SMB file shares, using smbclient. Args: config: Config object holding global configuration from commands flags Returns: report: Report object holding the results from the crawling the shares. """ shares = config.Shares() if not shares: ...
7,279
def new_image(): """ Display an image, and ask the user to label it """ user_id = current_user.user_id categories = current_app.config["CATEGORIES"] label_form = LabelForm() label_form.cat_radio.choices = [(cat,cat) for cat in categories] if request.method=="POST": if not "image...
7,280
def num_cluster_members(matrix, identity_threshold): """ Calculate number of sequences in alignment within given identity_threshold of each other Parameters ---------- matrix : np.array N x L matrix containing N sequences of length L. Matrix must be mapped to range(0, num_symbol...
7,281
def get_score(command: str) -> float: """Get pylint score""" output = check_output(command, shell=True).decode("utf-8") start = output.find("Your code has been rated at ") if start == -1: raise ValueError(f'Could not find quality score in "{output.rstrip()}".') start += len("Your code has ...
7,282
def tf_abstract_eval(f): """Returns a function that evaluates `f` given input shapes and dtypes. It transforms function `f` to a function that performs the same computation as `f` but only on shapes and dtypes (a.k.a. shape inference). Args: f: the function to be transformed. Returns: A function wh...
7,283
def __process_input(request_data: str) -> np.array: """ Converts input request data into numpy array :param request_data in json format :return: numpy array """ return np.asarray(json.loads(request_data)["input"])
7,284
def getDist_P2L(PointP,Pointa,Pointb): """计算点到直线的距离 PointP:定点坐标 Pointa:直线a点坐标 Pointb:直线b点坐标 """ #求直线方程 A=0 B=0 C=0 A=Pointa[1]-Pointb[1] B=Pointb[0]-Pointa[0] C=Pointa[0]*Pointb[1]-Pointa[1]*Pointb[0] #代入点到直线距离公式 distance=0 distance=(A*PointP[0]+B*...
7,285
def test_mean_covariance_metric(metric, mean, get_covmats): """Test mean_covariance for metric""" n_matrices, n_channels = 3, 3 covmats = get_covmats(n_matrices, n_channels) C = mean_covariance(covmats, metric=metric) Ctrue = mean(covmats) assert np.all(C == Ctrue)
7,286
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for SG training objective.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) indptr = mx.nd.arange(len(centers) + 1) centers = mx.nd.array(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_matri...
7,287
def JD2RA(JD, longitude=21.42830, latitude=-30.72152, epoch='current'): """ Convert from Julian date to Equatorial Right Ascension at zenith during a specified epoch. Parameters: ----------- JD : type=float, a float or an array of Julian Dates longitude : type=float, longitude of observer ...
7,288
def _average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. T...
7,289
def player_statistics(players): """query & show historic stats for each player before the game starts""" for player in players: player.score = points_default player.score_history = [] player_wins = int(db.get_wins(player.name)) player_total_games = int(db.get_total_games(player.name)) if player_t...
7,290
def _get_memory_banks_listed_in_dir(path): """Get all memory banks the kernel lists in a given directory. Such a directory can be /sys/devices/system/node/ (contains all memory banks) or /sys/devices/system/cpu/cpu*/ (contains all memory banks on the same NUMA node as that core).""" # Such directories c...
7,291
def iter_datarows_shuffled( parquet_files: List[Path], columns: Union[dict, tuple] = DataRow._fields, filters: List[Callable] = [], random_state: Optional[np.random.RandomState] = None, ) -> RowGen: """Iterate over parquet data in multiple `parquet_files`, randomly chosing the next row. Notes: ...
7,292
def get_online_users(guest=False): # pragma: no cover """Returns all online users within a specified time range :param guest: If True, it will return the online guests """ current = int(time.time()) // 60 minutes = range_method(flaskbb_config['ONLINE_LAST_MINUTES']) if guest: return re...
7,293
def AddConfigFlags(parser): """Add flags for different types of configs.""" parser.add_argument( '--config', help='Filename of a top-level yaml config that specifies ' 'resources to deploy.') parser.add_argument( '--template', help='Filename of a top-level jinja or python config tem...
7,294
def reverse_bearing(bearing: Union[int, float]): """ 180 degrees from supplied bearing :param bearing: :return: """ assert isinstance(bearing, (float, int)) assert 0. <= bearing <= 360. new_bearing = bearing + 180. # Ensure strike is between zero and 360 (bearing) return normali...
7,295
def signUp_page(request): """load signUp page""" return render(request, 'app/signUp_page.html')
7,296
def db(app, request): """ Session-wide test database. """ db_path = app.config["SQLALCHEMY_DATABASE_URI"] db_path = db_path[len("sqlite:///"):] print(db_path) if os.path.exists(db_path): os.unlink(db_path) def teardown(): _db.drop_all() os.unlink(db_path) _d...
7,297
def main(): """ Set virtual desktop """ # https://github.com/ValveSoftware/Proton/issues/872 util.protontricks('vd=1280x720')
7,298
def plot_each_model_prism(mod, title, modelnumber, grid_specification, fig): """ Plots each individual model when called from plot_multiple_models_prism """ marker_dict = {'[]':'s', 'v': '^', 'O': 'o', 'I': '|', '+': 'X', 'L': '$L$', '^': '$V$', '*': '*', 'S': '$S$'} axis = fig.add_su...
7,299