content
stringlengths
22
815k
id
int64
0
4.91M
def data_fun(times): """Generate time-staggered sinusoids at harmonics of 10Hz""" global n n_samp = len(times) window = np.zeros(n_samp) start, stop = [int(ii * float(n_samp) / (2 * n_dipoles)) for ii in (2 * n, 2 * n + 1)] window[start:stop] = 1. n += 1 data = 1e-7 * ...
5,345,100
def bandstructure(target_db_file, insert): """add workflows for bandstructure based on materials collection""" lpad = get_lpad() source = calcdb_from_mgrant(f'{lpad.host}/{lpad.name}') print('connected to source db with', source.collection.count(), 'tasks') target = VaspCalcDb.from_db_file(target_db...
5,345,101
def var(x, axis=None, ddof=0, keepdims=False): """ Computes the variance along the specified axis. The variance is the average of the squared deviations from the mean, i.e., :math:`var = mean(abs(x - x.mean())**2)`. Returns the variance, which is computed for the flattened array by default, oth...
5,345,102
def check_inputs(supplied_inputs): """Check that the inputs are of some correct type and returned as AttributeDict.""" inputs = None if supplied_inputs is None: inputs = AttributeDict() else: if isinstance(supplied_inputs, DataFactory('dict')): inputs = AttributeDict(supplied...
5,345,103
def _parse_none(arg, fn=None): """Parse arguments with support for conversion to None. Args: arg (str): Argument to potentially convert. fn (func): Function to apply to the argument if not converted to None. Returns: Any: Arguments that are "none" or "0" are converted to None; ...
5,345,104
def generate_constraint(category_id, user): """ generate the proper basic data structure to express a constraint based on the category string """ return {'year': category_id}
5,345,105
def test_zipped_bytes_collection(bytes_coutwildrnp_zip): """Open a zipped stream of bytes as a collection""" with fiona.BytesCollection(bytes_coutwildrnp_zip) as col: assert col.name == 'coutwildrnp' assert len(col) == 67
5,345,106
def get_RIB_IN_capacity(cvg_api, multipath, start_value, step_value, route_type, port_speed,): """ Args: cvg_api (pytest fixture): snappi API temp_tg_port (pytest fixture): Por...
5,345,107
def input_file_exists(filepath): """ Return True if the file path exists, or is the stdin marker. """ return (filepath == '-') or os.path.exists(filepath)
5,345,108
def ladder_length(beginWord: str, endWord: str, wordList: List[str]) -> int: """ 双端交替迫近目标层,根据一层数量最多节点确定为目标层 :param beginWord: :param endWord: :param wordList: :return: >>> ladder_length('hit', 'cog', ["hot","dot","dog","lot","log","cog"]) 5 >>> ladder_length('hit', 'cog', ["hot","dot...
5,345,109
def setup_option(request): """Создаем объект для удобство работы с переменными в тестовых методах """ setup_parameters = {} if request.config.getoption('--site_url'): setup_parameters['site_url'] = request.config.getoption('--site_url') return setup_parameters
5,345,110
def train_one_epoch(img_input,model,optimizer,writer,epoch,args): """ Finish 1.train for one epoch 2.print process, total loss, data time in terminal 3.save loss, lr, output img in tensorboard Note 1.you can change the save frequency """ loss_train = 0 model.train() leng...
5,345,111
def get_unique_tokens(texts): """ Returns a set of unique tokens. >>> get_unique_tokens(['oeffentl', 'ist', 'oeffentl']) {'oeffentl', 'ist'} """ unique_tokens = set() for text in texts: for token in text: unique_tokens.add(token) return unique_tokens
5,345,112
def do_set(): """Callback to set the color on the keyboard.""" w.setb['state'] = tk.DISABLED msg = static_color_msg(state.red, state.green, state.blue) # 0x21: request_type USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT # 0x09: request HID_REQ_SET_REPORT # 0x300: value # 0x01: report ind...
5,345,113
def _symmetric_difference(provided: dict, chosen: dict) -> dict: """ Returns the fields that are not in common between provided and chosen JSON schema. :param provided: the JSON schema to removed the chosen schema from. :param chosen: the JSON schema to remove from the provided schema. :return: a J...
5,345,114
def check_pv_name_in_rados(arg, image_id, pvc_name, pool_name): """ validate pvc information in rados """ omapkey = 'csi.volume.%s' % pvc_name cmd = ['rados', 'getomapval', 'csi.volumes.default', omapkey, "--pool", pool_name] if not arg.userkey: cmd += ["--id", arg.userid, "--...
5,345,115
def moved_in(nn_orig, nn_proj, i, k): """Determine points that are neighbours in the projection space, but were not neighbours in the original space. nn_orig neighbourhood matrix for original data nn_proj neighbourhood matrix for projection data i index of the point considered ...
5,345,116
def _get_lines_changed(line_summary): """ Parse the line diff summary into a list of numbers representing line numbers added or changed :param line_summary: the summary from a git diff of lines that have changed (ex: @@ -1,40 +1,23 @@) :return: a list of integers indicating which lines changed for that ...
5,345,117
def tj_agri_sup(): """ Real Name: b'Tj Agri Sup' Original Eqn: b'MIN(Tj Agri Dem *Agri Tajan Dam Coef, (Tj Outflow-Tj Dom Sup-Tj Env Sup-Tj Ind Sup))' Units: b'' Limits: (None, None) Type: component b'' """ return np.minimum(tj_agri_dem() * agri_tajan_dam_coef(), ...
5,345,118
def correlation_coefficient(y_true, y_pred): """The CC, is the Pearson’s correlation coefficient and treats the saliency and ground truth density maps, as random variables measuring the linear relationship between them.Values are first divided by their sum for each image to yield a distribution...
5,345,119
def check_hbase_table(params, table): """ Validates that an HBase table exists. An exception is raised if the table does not exist. :param params: :param table: The name of the HBase table. """ Logger.info("Checking HBase table '{0}'".format(table)) # if needed kinit as 'hbase' if ...
5,345,120
def init_args(): """Init command line args used for configuration.""" parser = init_main_args() return parser.parse_args()
5,345,121
def _fit_binary(estimator, X, y, classes=None, **kwargs): """Fit a single binary estimator with kwargs.""" unique_y = np.unique(y) if len(unique_y) == 1: if classes is not None: if y[0] == -1: c = 0 else: c = y[0] warnings.warn("Lab...
5,345,122
def lint(ctx): """ Lint code using flake8 tools. """ status("linting code ...") ctx.run("flake8 --show-source --statistics --count")
5,345,123
def data_index(person, dim): """ Output sequence of eye gaze (x, y) positions from the dataset for a person and a dimension of that person (task, session, etc) Index starts at 0. The vectors are [x, y, flag], flag being if it's null """ session = "S1" if dim % 2 == 0 else "S2" # S1_Balura_Ga...
5,345,124
def fairmot_config(): """Yields config while forcing the model to run on CPU.""" with open(PKD_DIR / "configs" / "model" / "fairmot.yml") as infile: node_config = yaml.safe_load(infile) node_config["root"] = Path.cwd() with mock.patch("torch.cuda.is_available", return_value=False): yiel...
5,345,125
def getStatic(): """ These are "static" params for a smoother application flow and fine tuning of some params Not all functions are implemented yet Returns the necessary Params to run this application """ VISU_PAR = { # ============================================================================...
5,345,126
def current_device(): """Return the index of the current active device. Returns ------- int The index of device. """ return dragon.cuda.GetDevice()
5,345,127
def test_create(ldap): """ Test create LDAP object. """ # Create the object. account_1 = Account({ 'uid': "tux1", 'givenName': "Tux", 'sn': "Torvalds", 'cn': "Tux Torvalds", 'telephoneNumber': "000", 'mail': "tuz@example.org", 'o': "Linux Rules", ...
5,345,128
async def access_logger(app, handler): """Simple logging middleware to report info about each request/response. """ async def logging_handler(request): start_time = time.time() request_name = hex(int(start_time * 10000))[-6:] client_ip, _ = request.transport.get_extra_info( ...
5,345,129
def main(source: str) -> Tuple[astroid.Module, TypeInferer]: """Parse a string representing source text, and perform a typecheck. Return the astroid Module node (with the type_constraints attribute set on all nodes in the tree) and TypeInferer object. """ module = astroid.parse(source) type_inf...
5,345,130
def wait_until_active(tol=5): """Wait until awakened by user activity. This function will block and wait until some user activity is detected. Because of the polling method used, it may return `tol` seconds (or less) after user activity actually began. """ liinfo = LASTINPUTINFO() liinfo.c...
5,345,131
def test_generate_cloud(): """Test plotting of word cloud""" tweets = [ "Make America Great Again! @DonaldTrump #America", "It's rocket-science tier investment~~ #LoveElonMusk", "America America America #USA #USA" ] expected_words = { 'america': 1.0, 'usa': 0.4, 'make': ...
5,345,132
def to_literal_scalar(a_str): """Helper function to enforce literal scalar block (ruamel.yaml).""" return ruamel.yaml.scalarstring.LiteralScalarString(a_str)
5,345,133
def get_first_free_address(subnet_id: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFirstFreeAddressResult: """ Use this data source to access information about an existing resource. """ __args__ = dict() __args__['subnetId'] = subnet_id...
5,345,134
def pagenav(object_list, base_url, order_by, reverse, cur_month, is_paginated, paginator): """Display page navigation for given list of objects""" return {'object_list': object_list, 'base_url': base_url, 'order_by': order_by, 'reverse': reverse, 'cur_month': cur_...
5,345,135
def read_input(path: str): """ Read game board file from path. Return list of str. >>> read_input("skyscrapers1.txt") ['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'] """ with open(path, 'r') as f: game_lst = f.readlines() for idx, line in enumerate(...
5,345,136
def run_tweeter(): """ Captures image and sends tweet """ capture_image_and_tweet() return schedule.CancelJob
5,345,137
def get_retro_results( outdir, recos_basedir, events_basedir, recompute_estimate=False, overwrite=False, ): """Extract all rectro reco results from a reco directory tree, merging with original event information from correspoding source events directory tree. Results are populated to a Pa...
5,345,138
def split_surface_v(obj, t, **kwargs): """ Splits the surface at the input parametric coordinate on the v-direction. This method splits the surface into two pieces at the given parametric coordinate on the v-direction, generates two different surface objects and returns them. It does not modify the input s...
5,345,139
def test_stable_read( subject: RadwagScale, scale_connection: MagicMock, masses: List[float], expected: float, ) -> None: """It should read samples.""" scale_connection.readline.side_effect = [ create_radwag_result_line("SU", v) for v in masses ] mass = subject.stable_read(len(ma...
5,345,140
def oidc_userprofile_test(request): """ OIDC-style userinfo """ user = request.user profile, g_o_c = UserProfile.objects.get_or_create(user=user) data = OrderedDict() data['sub'] = user.username data['name'] = "%s %s" % (user.first_name, user.last_name) data['nickname'] = profile.nic...
5,345,141
def split_idx( idx,a,b): """ Shuffle and split a list of indexes into training and test data with a fixed random seed for reproducibility run: index of the current split (zero based) nruns: number of splits (> run) idx: list of indices to split """ rs = np.random.RandomState() ...
5,345,142
def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. val: float or int src: tuple dst: tuple example: print(scale(99, (0.0, 99.0), (-1.0, +1.0))) """ return (float(val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
5,345,143
def celeba_samples( file_paths: List , crop_size: int = 178): """ Create CelebaA samples by center cropping into 178x178 Args: file_paths : List of file paths of CelebA images crop_size : Crop size of image """ y1, y2, x1, x2 = crop_celeba_image_coords(cr...
5,345,144
def add(c1, c2): """Add two encrypted counters""" a1, b1 = c1 a2, b2 = c2 return (a1 + a2, b1 + b2)
5,345,145
def fsevent_callback(stream_ref, full_path, event_count, paths, masks, ids): """Process an FSEvent (consult the Cocoa docs) and call each of our handlers which monitors that path or a parent""" for i in range(event_count): path = os.path.dirname(paths[i]) if masks[i] & kFSEventStreamEventFlagMu...
5,345,146
async def wait_all_tasks_blocked(cushion=0.0): """Block until there are no runnable tasks. This is useful in testing code when you want to give other tasks a chance to "settle down". The calling task is blocked, and doesn't wake up until all other tasks are also blocked for at least ``cushi...
5,345,147
def get_chisq_grid(data, type, forecast=False, errors=None): """ Generates 2d meshgrid for chisq values of a given type (i.e. BBN, CMB etc) """ masses = np.unique(data['mass']) omegabs = np.unique(data['OmegaB']) MASS, OMEGAB = np.meshgrid(masses, omegabs) OMEGABDAT = data['OmegaB'].reshape(...
5,345,148
def collect_samples_clouds_video(upsampling, opt, deferred_shading=False): """ Collect samples of cloud videos. opt is expected to be a dict. Output: DatasetData - samples: list of Sample - images_high: num_frames x output_channels x H*upsampling x W*upsampling - images_low: num_frames x ...
5,345,149
def spectrl2(units, location, datetime, weather, orientation, atmospheric_conditions, albedo): """ Calculate solar spectrum by calling functions exported by :data:`SPECTRL2DLL`. :param units: set ``units`` = 1 for W/m\ :sup:`2`/micron :type units: int :param location: latitude, lon...
5,345,150
def test_int() -> None: """Test integer type.""" type = data_types.Int(bytearray([0x01, 0x9A, 0xFF, 0xFF])) assert type.value == -26111 assert type.size == 4
5,345,151
def decompile_marketplace_bp( name, version, app_source, bp_name, project, with_secrets, bp_dir ): """decompiles marketplace blueprint""" if not version: LOG.info("Fetching latest version of Marketplace Blueprint {} ".format(name)) version = get_mpi_latest_version( name=name, ap...
5,345,152
def setup_transition_list(): """ Creates and returns a list of Transition() objects to represent state transitions for an unbiased random walk. Parameters ---------- (none) Returns ------- xn_list : list of Transition objects List of objects that encode information about th...
5,345,153
def error_message(error, text): """ Gives default or custom text for the error. -------------------- Inputs <datatype>: - error <Error Object>: The error code - text <string>: Custom error text if error has no message Returns <datatype>: - error description <string>: The cust...
5,345,154
def maskguard(maskarray, niter=1, xyonly=False, vonly=False): """ Pad a mask by specified number of pixels in all three dimensions. Parameters ---------- maskarray : `~numpy.ndarray` The 3-D mask array with 1s for valid pixels and 0s otherwise. niter : int, optional Number of i...
5,345,155
def validdest(repo, old, new): """Is the new bookmark destination a valid update from the old one""" repo = repo.unfiltered() if old == new: # Old == new -> nothing to update. return False elif not old: # old is nullrev, anything is valid. # (new != nullrev has been exclu...
5,345,156
def no_rbac_suffix_in_test_filename(filename): """Check that RBAC filenames end with "_rbac" suffix. P101 """ if "patrole_tempest_plugin/tests/api" in filename: if filename.endswith('rbac_base.py'): return if not filename.endswith('_rbac.py'): return 0, "RBAC t...
5,345,157
def import_results(results_file, valid_codes=None, session=None): """Take a iterable which yields result lines and add them to the database. If session is None, the global db.session is used. If valid_codes is non-None, it is a set containing the party codes which are allowed in this database. If None,...
5,345,158
def register_plugins(manager: astroid.Manager) -> None: """Apply our transforms to a given astroid manager object.""" # Hmm; is this still necessary? if VERBOSE: manager.register_failed_import_hook(failed_import_hook) # Completely ignore everything under an 'if TYPE_CHECKING' conditional. ...
5,345,159
def fit_lens_data_with_tracer(lens_data, tracer, padded_tracer=None): """Fit lens data with a model tracer, automatically determining the type of fit based on the \ properties of the galaxies in the tracer. Parameters ----------- lens_data : lens_data.LensData or lens_data.LensDataHyper The...
5,345,160
def sround(a, *ndigits): """Termwise round(a) for an iterable. An optional second argument is supported, and passed through to the built-in ``round`` function. As with the built-in, rounding is correct taking into account the float representation, which is base-2. https://docs.python.org/...
5,345,161
def transform_graph(graph, cpu=None, callcontrol=None, portal_jd=None): """Transform a control flow graph to make it suitable for being flattened in a JitCode. """ constant_fold_ll_issubclass(graph, cpu) t = Transformer(cpu, callcontrol, portal_jd) t.transform(graph)
5,345,162
def test_pb_validation_big_size_number(): """Test if an invalid number, with wrong size, is really invalid""" invalid_number = '0600000151' assert pb.start(invalid_number) == False
5,345,163
def validate_paths(args): """Ensure all of the configured paths actually exist.""" if not path.exists(args.destination): LOGGER.warning('Destination path "%s" does not exist, creating', args.destination) os.makedirs(path.normpath(args.destination)) for file_path in [a...
5,345,164
def run_insert_data_into_single_table(): """ An example demonstrating a simple single-table Hyper file including table creation and data insertion with different types """ print("EXAMPLE - Insert data into a single table within a new Hyper file") path_to_database = Path("customer.hyper") # Star...
5,345,165
def update_usim_inputs_after_warm_start( settings, usim_data_dir=None, warm_start_dir=None): """ TODO: Combine this method with create_usim_input_data() above """ # load usim data if not usim_data_dir: usim_data_dir = settings['usim_local_data_folder'] datastore_name = _get_usim...
5,345,166
def part_b(lines): """ For each valid line consider the stack of opening characters that didn't get closed. Compute a score for each line per the question, then return the median value of these scores. """ scores = [] for line in lines: is_line_valid, stack = assess_line(line) if is_...
5,345,167
def setup_platform(opp, config, add_entities, discovery_info=None): """Set up the ThinkingCleaner platform.""" host = config.get(CONF_HOST) if host: devices = [ThinkingCleaner(host, "unknown")] else: discovery = Discovery() devices = discovery.discover() @util.Throttle(MIN_...
5,345,168
def _get_activation( spec): """Get a rematlib Layer corresponding to a given activation function.""" if spec == mobile_search_space_v3.RELU: result = layers.ReLU() elif spec == mobile_search_space_v3.RELU6: result = layers.ReLU6() elif spec == mobile_search_space_v3.SWISH6: result = layers.Swish...
5,345,169
def addUpdateCarrierGroups(): """ Add or Update a group of carriers """ db = DummySession() try: if not session.get('logged_in'): return redirect(url_for('index')) if (settings.DEBUG): debugEndpoint() db = SessionLoader() form = stripDictV...
5,345,170
def RT2tq(poses, square=False): """ !!NOT TESETED!! :param poses: N x 3 x 4, (R|T) :return: (N, 7) """ N,_,_ = poses.shape R = poses[:,:,:3] T = poses[:,:,3:] # Nx3x1 q = quaternion.as_float_array(quaternion.from_rotation_matrix(R)) #Nx4 t= T.squeeze(-1) tq = np.concatena...
5,345,171
def benchmarking_plot(timeseries, kernel_density=False): """ Plot probability distribution of model outputs """ combined_df = pd.DataFrame() for ts in timeseries: df1 = ts.tp.to_dataframe(name=ts.plot_legend) df2 = df1.reset_index() df3 = df2.drop(["time", "lon", "lat"], axis=1) ...
5,345,172
def send_msg_less_committer_time(keyword='', since=(datetime.datetime.now() - datetime.timedelta(days=1)).astimezone().isoformat(), until=datetime.datetime.now().astimezone().isoformat(), author_infos=[{"committer": git_c...
5,345,173
def make_callback(subscription_path, project_id): """Return a callback closure""" def callback(message): """Handle Pub/Sub resurrection message. Ignore (and ACK) messages that are not well-formed. Try handle any other message, ACKing it eventually (always). """ logger.info('Handling message fr...
5,345,174
def update_account(self, changes, changes_state): """Update an existing account with changes Args: self: -- OandaClient instance changes: -- Changes from account_changes API call changes_state: ChangesState from account_changes API call Returns: None """ # Add / Replace / ...
5,345,175
def _assign_course_staff_role(course_key, enrollments, staff_assignments): """ Grant or remove the course staff role for a set of enrollments on a course. For enrollment without a linked user, a CourseAccessRoleAssignment will be created (or removed) for that enrollment. Arguments: enrollme...
5,345,176
def make_partition_table(target_device, part_name, **kwargs): """ Create new GUID partition table on ``target_device``, with two partitions: 1) GRUB second stage partition with type 0xEF02 2) size of rest of the disk with name ``part_name`` Returns path to the boot partition, whi...
5,345,177
def data_to_bytes(data, encoding): """\ Converts the provided data into bytes. If the data is already a byte sequence, it will be left unchanged. This function tries to use the provided `encoding` (if not ``None``) or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback. Returns th...
5,345,178
def get_session_store(state: State = Depends(get_app_state)) -> SessionStore: """Get a singleton SessionStore to keep track of created sessions.""" session_store = getattr(state, _SESSION_STORE_KEY, None) if session_store is None: session_store = SessionStore() setattr(state, _SESSION_STORE...
5,345,179
def get_comments(filename): """ Get Julia, Python, R comments. """ comments = [] try: with open(filename, 'r', encoding='utf8') as fp: filename = os.path.basename(filename) for comment, start, end in getcomments.get_comment_blocks(fp): comments.append({ "ln%s" % (start[0]) : comment.r...
5,345,180
def setup_function(): """Function which is run before each test in this file. ``create_tmp_dir`` will do the following: 1. Create a directory called ``tmp`` (overwrite if already exists) 2. Copy ``data_testing`` -> ``tmp/data_testing`` Add any other things for setup here. """ create_tmp_di...
5,345,181
def extractCurrentlyTLingBuniMi(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if item['title'].startswith('[BNM]'): return buildReleaseMessageWithType(item, 'Bu ni Mi wo Sasagete Hyaku to ...
5,345,182
def dif_stats(filename, # [<'my/file.txt',...> => name of scored data file] student_id = 'Student_ID', # [<'Student_ID', ...> => student id column label] group = ['Sex', {'focal':0, 'ref':1}], # [<e.g.'Sex', {'focal':'female', 'ref':'male'}]> => column label with assignment to focal an...
5,345,183
def delete_all_devices_for_user(): """ delete all active devices for the given user """ try: username = get_jwt_identity() with session_scope() as session: user = user_service.get_user(username, session) device_count = user.devices.count() if device_...
5,345,184
def initdb(): """Creates database tables.""" db.create_all()
5,345,185
def _GetNormalizationTuple(url): """Parse a URL into a components tuple. Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Args: url:A URL string. Returns: A 6-tuple: (scheme, netloc, path, params, query, fragment). """ url = encoding_util.EncodeToAscii(url) ...
5,345,186
def chest(cont): """ Wood shield chest """ own = cont.owner big_chest(own, logic.OBJECT_CONSTANT.WOOD_SHIELD, "chest.wood_shield") # end own.endObject()
5,345,187
def gCallback(dataset, geneid, colors): """Callback to set initial value of green slider from dict. Positional arguments: dataset -- Currently selected dataset. geneid -- Not needed, only to register input. colors -- Dictionary containing the color values. """ colorsDict = colors try: ...
5,345,188
def intForcesMoments(sliceZnes,method, direction): """ Loops over the sliceZnes and performs an integration of Forces and moments for each slice (Scalar integrals, variables are depending on the method). Returns a ([dir, dirNormalized,fxNr,fyNr,fzNr,mxNr,myNr,mzNr]*Nslices array) """ #dir...
5,345,189
def convert(instance) -> dict: """Convert beautifulsoup to dict. This is a typeclass definition."""
5,345,190
def getSecsInTime(time=85460): """calculates the Hour:Minutes:Seconds of the given time in seconds.""" print(strftime(formatTime, gmtime(time)))
5,345,191
def register_event_callback(event, resource_type, callbacks): """Register each callback with the event. :param event: Action being registered :type event: keystone.notifications.ACTIONS :param resource_type: Type of resource being operated on :type resource_type: str :param callbacks: Callback ...
5,345,192
def test_create_task_script_with_inputs(): """Tests that we can create a basic task (run a script using some inputs).""" workspace = Workspace.from_config(path="./config", _file_name="workspace.json") tes_api = TesApi(workspace) # first we submit the task run_id = tes_api.create_task( name="...
5,345,193
def _other_members(other_members: List[parser.MemberInfo], title: str): """Returns "other_members" rendered to markdown. `other_members` is used for anything that is not a class, function, module, or method. Args: other_members: A list of `MemberInfo` objects. title: Title of the table. Returns: ...
5,345,194
def full_url(parser, token): """Spits out the full URL""" url_node = url(parser, token) f = url_node.render url_node.render = lambda context: _get_host_from_context(context) + f(context) return url_node
5,345,195
def Chi2CoupleDiffFunc(nzbins, nzcorrs, ntheta, mask, data1, xi_obs_1, xi_theo_1, data2, xi_obs_2, xi_theo_2, inDir_cov12, file_name_cov12): """ Estimate chi^2 for difference between two data vectors Note: this assumes two data vectors ...
5,345,196
def generate_entity_file(in_file_name, out_entity_file_name, output_query_file_name): """ Generate entity information of hotpotQA like dataset. Using Hanlp for entity recognizing. :param in_file_name: :param out_entity_file_name: :param output_query_file_name: """ with open(in_file_name,...
5,345,197
def minimax(just_mapping, mapping): """ Scale the mapping to minimize the maximum error from just intonation. """ least_error = float("inf") best_mapping = mapping for i in range(len(just_mapping)): for j in range(i+1, len(just_mapping)): candidate = mapping / (mapping[i] + m...
5,345,198
def app_used_today(): """Check the session and the backend database for a record of app use from the last 24 hours.""" now = UTC.localize(datetime.datetime.utcnow()) last_app_use = get_last_app_use_date() day_length_in_seconds = 60 * 60 * 24 if last_app_use and (last_app_use.timestamp() + day_length...
5,345,199