content
stringlengths
22
815k
id
int64
0
4.91M
def _make_rel_url_path(src, dst): """src is a file or dir which wants to adress dst relatively, calculate the appropriate path to get from here to there.""" srcdir = os.path.abspath(src + "/..") dst = os.path.abspath(dst) # For future reference, I hate doing dir munging with string operations #...
20,900
def get_required_params(request, expected_params: list, type: str = 'POST') -> dict: """Gets the list of params from request, or returns None if ANY is missing. :param request: The Request :type request: flask.Request :param expected_params: The list of expected parameters :type expected_params: li...
20,901
def md_to_notebook(text): """Convert a Markdown text to a Jupyter notebook, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(text.encode('utf-8')) tmp_file.close() pandoc(u'--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name...
20,902
def bot_send(msg, bot_id, broadcast): """ Send a message to a telegram user or group specified on chat_id chat_id must be a number! bot_id == bot_username """ if broadcast == True: bot = telegram.Bot(token=config[bot_id]["bot_api_token"]) bot.sendMessage(chat_id=config[bot_id]...
20,903
def output_data(path, df): """ This file removes unwanted columns and outputs the final dataset :param path: :param df: :return: """ df.to_csv(path,index=False)
20,904
def dataset_source_xnat(bids_dir): """ Method to check if the data was downloaded from xnat :param bids_dir: BIDS Directory :return: True or False """ dataset_description_file = glob.glob(bids_dir + "/**/dataset_description.json", recursive = True) if not os.path.exists(dataset_descript...
20,905
def split_dataset(dataset, num_train=1200): """ Split the dataset into a training and test set. Args: dataset: an iterable of Characters. Returns: A tuple (train, test) of Character sequences. """ all_data = list(dataset) random.shuffle(all_data) return all_data[:num_train], ...
20,906
def get_constant(): """ Keep learning rate constant """ def update(lr, epoch): return lr return update
20,907
def spatial_pack_nhwc(data, kernel, stride, padding, in_bits, weight_bits, pack_dtype, out_dtype, dorefa=False): """ Compute convolution with pack on spatial axes. """ assert data.shape[0].value == 1, "spatial pack convolution only support batch size=1" data_q = bitpack(data, in_bits, ...
20,908
def load_random_tt_distribution(numAgents, r, pu, samples): """ Load a file with a population of random turn-taking values, assuming that it exists Parameters: * numAgents -- the desired number of probabilistic agents to include * r -- the turn-taking resolution * pu -- the probability that a bit in each usag...
20,909
def fail_after(seconds: float) -> ContextManager[CancelScope]: """ Create a cancel scope with the given timeout, and raises an error if it is actually cancelled. This function and move_on_after() are similar in that both create a cancel scope with a given timeout, and if the timeout expires then bo...
20,910
def _get_dataset_names_mapping( names: Union[str, Set[str], Dict[str, str]] = None ) -> Dict[str, str]: """Take a name or a collection of dataset names and turn it into a mapping from the old dataset names to the provided ones if necessary. Args: names: A dataset name or collection of dataset n...
20,911
def test_worker_serialise(worker): """Test serialiseation of the worker""" worker_dict = worker.to_dict() worker_dict['computer_id'] = 'remote' worker2 = AiiDAFWorker.from_dict(worker_dict) assert worker2.computer_id == 'remote' worker_dict.pop("username") worker2 = AiiDAFWorker.from_dict(...
20,912
def _json_keyify(args): """ converts arguments into a deterministic key used for memoizing """ args = tuple(sorted(args.items(), key=lambda e: e[0])) return json.dumps(args)
20,913
def tgsegsm_vect(time_in, data_in): """ Transform data from GSE to GSM. Parameters ---------- time_in: list of float Time array. data_in: list of float xgse, ygse, zgse cartesian GSE coordinates. Returns ------- xgsm: list of float Cartesian GSM coordinates...
20,914
async def gmake_(message: Message): """ make folder """ await Worker(message).make_folder()
20,915
def test_xcorr_zscored(): """ Test this function, which is not otherwise tested in the testing of the EventRelatedAnalyzer """ cycles = 10 l = 1024 unit = 2 * np.pi / l t = np.arange(0, 2 * np.pi + unit, unit) signal = np.sin(cycles * t) events = np.zeros(t.shape) #Zero cr...
20,916
def real_main(): """Main program without profiling. """ import django.core.handlers.wsgi # Create a Django application for WSGI. application = django.core.handlers.wsgi.WSGIHandler() from soc.modules import callback from soc.modules import core callback.registerCore(core.Core()) callback.getCore()....
20,917
def choose_a_pick_naive(numbers_left): """ Choose any larger number :param numbers_left: :return: """ if numbers_left[0] > numbers_left[-1]: return 0, numbers_left[0] elif numbers_left[-1] > numbers_left[0]: return -1, numbers_left[-1] else: return 0, numbers_left...
20,918
def get_group_names(exp_path, uniquechannel ='Ki_t', fname="trajectoriesDat.csv"): """Similar to get_grp_list, but uses trajectoriesDat column names""" if "_combined" in exp_path: pattern = 'trajectoriesDat_region' grp_suffix = 'EMS' files = os.listdir(exp_path) trajectories = [...
20,919
def serializer_roundtrip(serializer, obj): """Serializes an object to a file, then deserializes it and returns the result""" @with_temporary_directory def helper(tmp_dir, serializer, obj): """Helper function: takes care of creating and deleting the temp directory for the output""" path = os....
20,920
def _Run(args, holder, target_https_proxy_arg, release_track): """Issues requests necessary to import target HTTPS proxies.""" client = holder.client resources = holder.resources target_https_proxy_ref = target_https_proxy_arg.ResolveAsResource( args, holder.resources, default_scope=compute_s...
20,921
def visualize_data(df): """ Takes in a Pandas Dataframe and then slices and dices it to create graphs """ fig, (ax1, ax2) = plt.subplots(nrows = 2, ncols = 1) ax1.set_xlabel('epochs') ax1.set_ylabel('validation accuracy') ax2.set_xlabel('epochs') ax2.set_ylabel('loss') legend1 = ax...
20,922
def get_mono_cell(locus_file, TotalSNPs, TotalBi_SNPs_used): """Determine value to add to [0,0] cell""" TotalBP, Loci_count = totalbp(locus_file) return int((TotalBi_SNPs_used * TotalBP) / TotalSNPs) - TotalBi_SNPs_used, \ TotalBP, Loci_count
20,923
def remove_bad_particles(st, min_rad='calc', max_rad='calc', min_edge_dist=2.0, check_rad_cutoff=[3.5, 15], check_outside_im=True, tries=50, im_change_frac=0.2, **kwargs): """ Removes improperly-featured particles from the state, based on a combination of pa...
20,924
def _pyside_import_module(moduleName): """ The import for PySide """ pyside = __import__('PySide', globals(), locals(), [moduleName], -1) return getattr(pyside, moduleName)
20,925
def get_models(args): """ :param args: argparse.Namespace commandline arguments :return: dict of BaseReport """ models = dict() if os.path.isfile(args.cm_input): models[args.cm_input] = CheckmarxReport if os.path.isfile(args.sn_input): models[args.sn_input] = SnykRepo...
20,926
def sanitize_str(value: str) -> str: """Removes Unicode control (Cc) characters EXCEPT for tabs (\t), newlines (\n only), line separators (U+2028) and paragraph separators (U+2029).""" return "".join(ch for ch in value if unicodedata.category(ch) != 'Cc' and ch not in {'\t', '\n', '\u2028', '\u2029'})
20,927
def p_assign_semicolon(p): """assign : assignation ';'""" p[0] = p[1]
20,928
def get_tariff_estimated(reporter, partner='000', product='all', year=world_trade_data.defaults.DEFAULT_YEAR, name_or_id='name'): """Tariffs (estimated)""" return _get_data(reporter, partner, product, year, ...
20,929
def task_result_api_view(request, taskid): """ Get task `state` and `result` from API endpoint. Use case: you want to provide to some user with async feedback about about status of some task. Example: # urls.py urlpatterns = [ url(r'^api/task/result/(.+)/', task_result...
20,930
async def test_8(): """Test query POST endpoint. Send a query with missing required params. Expect a bad request (400). """ LOG.debug('Test post query (missing params)') error_text = "Provided input: '{'start': 9, 'referenceBases': 'T', 'alternateBases': 'C', 'assemblyId': 'GRCh38', 'includeDataset...
20,931
def get_horizon_coordinates(fp_pointings_spherical): """ It converts from spherical to Horizon coordinates, with the conventions: Altitute = np.pi / 2 - zenith angle (theta) Azimuth = 2 * np.pi - phi Parameters ---------- fp_pointings_spherical : numpy array of shape (..., 2), radians...
20,932
def add_todo(username, password, title, description): """ To add a todo task -- requires title and description of the task """ userpass = username + password dt = datetime.now().strftime("%m/%d/%Y %H:%M:%S") add_message(userpass, dt, title, description) result = check_user(username, password) i...
20,933
def fire_receiver_type_metric(sender, instance, created, **kwargs): """Fires a metric for each receiver message type of each subscription.""" from .tasks import fire_metric, is_valid_msg_receiver if (created and instance.data and instance.data['msg_receiver'] and is_valid_msg_receiver(instance.d...
20,934
def indexed_chunking_random_test(f_list=indexed_chunking_f_list, x=None, return_debug_info=False, verbose=0): """made it so you can just run a function (several times) to test, but if you want to see print outs use ve...
20,935
def patch_object_type() -> None: """ Patches `graphene.ObjectType` to make it indexable at runttime. This is necessary for it be generic at typechecking time. """ # Lazily import graphene as it is actually an expensive thing to do and we don't want to slow down things at # type-checking time. ...
20,936
def GetFiles(dir, dirname): """Given a directory and the dirname of the directory, recursively traverse the directory and return a list of tuples containing (filename, relative filename), where 'relative filename' is generated using GetZipPath. """ files = [] for (dirpath, dirnames, filename...
20,937
def date_format(time_obj=time, fmt='%Y-%m-%d %H:%M:%S') -> str: """ 时间转字符串 :param time_obj: :param fmt: :return: """ _tm = time_obj.time() _t = time.localtime(_tm) return time.strftime(fmt, _t)
20,938
async def delete( id: str, requester_id: str = Depends(with_user_id), permission: str = Depends( requires_permission(Permission.Participant, Permission.Director) ), db: AsyncSession = Depends(with_db), ) -> None: """ Deletes an application by id """ if Permission.Participant....
20,939
def clean_pin_cite(pin_cite: Optional[str]) -> Optional[str]: """Strip spaces and commas from pin_cite, if it is not None.""" if pin_cite is None: return pin_cite return pin_cite.strip(", ")
20,940
def instrument_code_to_name(rwc_instrument_code): """Use the rwc_instrument_map.json to convert an rwc_instrument_code to its instrument name. Parameters ---------- rwc_instrument_code : str Two character instrument code Returns ------- instrument_name : str Full instru...
20,941
def record_time(ad, fallback_to_launch=True): """ RecordTime falls back to launch time as last-resort and for jobs in the queue For Completed/Removed/Error jobs, try to update it: - to CompletionDate if present - else to EnteredCurrentStatus if present - else fall back to launch tim...
20,942
def getTeamCompatibility(mentor, team): """ Gets a "compatibility score" between a mentor and a team (used as the weight in the later optimization problem) Uses the functions defined above to compute different aspects of the score """ score = 0 # find value from overlapping availabilities # value may differ dep...
20,943
def mean_edges(graph, feat, weight=None): """Averages all the values of edge field :attr:`feat` in :attr:`graph`, optionally multiplies the field by a scalar edge field :attr:`weight`. Parameters ---------- graph : DGLGraph The graph. feat : str The feature field. weight : o...
20,944
async def update_config_file(config: ConfigDTO, reboot_processor: Optional[bool] = True): """ Overwrites the configuration used by the processor. """ config_dict = map_to_file_format(config) success = update_config(config_dict, reboot_processor) if not success: return handle_response(con...
20,945
def integration_session(scope="session"): """ creates a Session object which will persist over the entire test run ("session"). http connections will be reused (higher performance, less resource usage) Returns a Session object """ s = requests.sessions.Session() s.headers.update(test_headers...
20,946
def get_json_dump(json_object, indent=4, sort_keys=False): """ Short handle to get a pretty printed str from a JSON object. """ return json.dumps(json_object, indent=indent, sort_keys=sort_keys)
20,947
def number_of_real_roots(f, *gens, **args): """Returns the number of distinct real roots of `f` in `(inf, sup]`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> from sympy.polys.polyroots import number_of_real_roots >>> f ...
20,948
def test_ui_data_in_record( app, client, minimal_record, headers, ui_headers): """Publish a record and check that it contains the UI data.""" recid = _create_and_publish(client, minimal_record, headers) BibliographicRecord.index.refresh() # Check if list results contain UI data response = ...
20,949
def heap_sort(arr: list): """ Heap sorting a list. Big-O: O(n log n). @see https://www.geeksforgeeks.org/heap-sort/ """ def heapify(sub: list, rdx: int, siz: int): """ Heapifying range between rdx and size ([rdx:siz]). @param sub: a slice of list. @param rdx: root/p...
20,950
def find_max_path(triangle): """ Find maximum-sum path from top of triangle to bottom """ # Start by copying the values sums = [[x for x in row] for row in triangle] # Efficient algorithm: start at the bottom and work our way up, computing max sums for reverse_index, row in enumerate(reverse...
20,951
def plot_partregress(results, exog_idx=None, xnames=None, grid=None, fig=None): """Plot partial regression for a set of regressors. Parameters ---------- results : results instance A regression model results instance exog_idx : None or list of int (column) indices of the exog used i...
20,952
def ufloats_overlap_range(ufloats, vmin, vmax): """Return whether the +/- 1 sigma range overlaps the value range.""" vals = [] sigmas = [] for val in ufloats: if isinstance(val, float): vals.append(val) sigmas.append(0) else: vals.append(val.nominal_va...
20,953
def save_volume(filename, volume, dtype='float32', overwrite_file=True): """ Save volumetric data that is a `Nibabel SpatialImage <http://nipy.org/nibabel/reference/nibabel.spatialimages.html#nibabel.spatialimages.SpatialImage>`_ to a file Parameters ---------- filename: str Full pa...
20,954
def exact_qaoa_values_on_grid( graph: nx.Graph, xlim: Tuple[float, float] = (0, np.pi / 2), ylim: Tuple[float, float] = (-np.pi / 4, np.pi / 4), x_grid_num: int = 20, y_grid_num: int = 20, num_processors: int = 1, dtype=np.complex128): """Compute exact p=1 QAO...
20,955
async def on_command(command, ctx): """when a command happens it logs it""" bot.commands_used[command.name] += 1 message = ctx.message destination = None if message.channel.is_private: destination = 'Private Message' else: destination = '#{0.channel.name} ({0.server.name}...
20,956
def typecheck_eq(expr, ctxt=[]): """(par (A) (= A A Bool :chainable)) (par (A) (distinct A A Bool :pairwise)) """ typ = typecheck_expr(expr.subterms[0], ctxt) for term in expr.subterms[1:]: t = typecheck_expr(term, ctxt) if t != typ: if not (is_subtype(t, typ) or is_subty...
20,957
def precision(x, for_sum=False): """ This function returns the precision of a given datatype using a comporable numpy array """ if not for_sum: return np.finfo(x.dtype).eps else: return np.finfo(x.dtype).eps * x.size
20,958
def parse_line(line, line_count, retries): """Coordinate retrieval of scientific name or taxonomy ID. Read line from input file, calling functions as appropriate to retrieve scientific name or taxonomy ID. :param line: str, line from input file :line_count: number of line in input file - enable tr...
20,959
def prop_rotate(old_image, theta, **kwargs): """Rotate and shift an image via interpolation (bilinear by default) Parameters ---------- old_image : numpy ndarray Image to be rotated theta : float Angle to rotate image in degrees counter-clockwise Retur...
20,960
def append_tf_example(data: Dict[Text, Any], schema: Dict[Text, Any]) -> tf.train.Example: """Add tf example to row""" feature = {} for key, value in data.items(): data_type = schema[key] value = CONVERTER_MAPPING[data_type](value) if data_type == DataType.INT: ...
20,961
def can_login(email, password): """Validation login parameter(email, password) with rules. return validation result True/False. """ login_user = User.find_by_email(email) return login_user is not None and argon2.verify(password, login_user.password_hash)
20,962
def Main(output): """Transforms power_manager prefs/defaults into jsonschema. Args: output: Output file that will be generated by the transform. """ result_lines = ["""powerd_prefs_default: &powerd_prefs_default description: For details, see https://chromium.googlesource.com/chromiumos/platform2/+/HEAD/p...
20,963
def toPlanar(arr: np.ndarray, shape: tuple = None) -> np.ndarray: """ Converts interleaved frame into planar Args: arr (numpy.ndarray): Interleaved frame shape (tuple, optional): If provided, the interleaved frame will be scaled to specified shape before converting into planar Returns:...
20,964
def _convert_client_cert(): """ Convert the client certificate pfx to crt/rsa required by nginx. If the certificate does not exist then no action is taken. """ cert_file = os.path.join(SECRETS, 'streams-certs', 'client.pfx') if not os.path.exists(cert_file): return pwd_file = os...
20,965
def downsample_grid( xg: np.ndarray, yg: np.ndarray, distance: float, mask: np.ndarray = None ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ Downsample grid locations to approximate spacing provided by 'distance'. Notes ----- This implementation is more efficient than the 'downsample_xy' f...
20,966
def convert_12bit_to_type(image, desired_type=np.uint8): """ Converts the 12-bit tiff from a 6X sensor to a numpy compatible form :param desired_type: The desired type :return: The converted image in numpy.array format """ image = image / MAX_VAL_12BIT # Scale to 0-1 image = np.iinfo...
20,967
def dm_hdu(hdu): """ Compute DM HDU from the actual FITS file HDU.""" if lsst.afw.__version__.startswith('12.0'): return hdu + 1 return hdu
20,968
def test_get_formatted_as_type_default_no_subst(): """On get_formatted_as_type returns default no formatting.""" context = Context() result = context.get_formatted_as_type(None, default=10, out_type=int) assert isinstance(result, int) assert result == 10
20,969
def start_upload(): """ Start the cron task to upload new jobs to the elasticsearch database """ sources ={ "adzuna":{ "extract_func": adzuna, }, "jobsearcher":{ "extract_func": jobsearcher, }, "monster":{ "extract_func": monster_scr...
20,970
def get_hdf_filepaths(hdf_dir): """Get a list of downloaded HDF files which is be used for iterating through hdf file conversion.""" print "Building list of downloaded HDF files..." hdf_filename_list = [] hdf_filepath_list = [] for dir in hdf_dir: for dir_path, subdir, files in os.walk(dir):...
20,971
def mask_depth_image(depth_image, min_depth, max_depth): """ mask out-of-range pixel to zero """ ret, depth_image = cv2.threshold( depth_image, min_depth, 100000, cv2.THRESH_TOZERO) ret, depth_image = cv2.threshold( depth_image, max_depth, 100000, cv2.THRESH_TOZERO_INV) depth_image = np....
20,972
def p2naive(): """Good for small inputs""" desc = lines[1].split(",") buses = [(i, int(x)) for i, x in enumerate(desc) if x != "x"] t = 0 while True: if all((t + i) % b == 0 for i, b in buses): print("p2add:", t) break t += buses[0][1]
20,973
def database_exists(url): """Check if a database exists. :param url: A SQLAlchemy engine URL. Performs backend-specific testing to quickly determine if a database exists on the server. :: database_exists('postgres://postgres@localhost/name') #=> False create_database('postgres://post...
20,974
def prompt_for_password(prompt=None): """Fake prompt function that just returns a constant string""" return 'promptpass'
20,975
def preprocess_data(filename_in='../data/chembl_smiles', filename_out='', model_type='BIMODAL', starting_point='fixed', invalid=True, duplicates=True, salts=True, stereochem=True, canonicalize=True, min_len=34, max_len=74, augmentation=1): """Pre-processing of SMILES based o...
20,976
def heading(start, end): """ Find how to get from the point on a planet specified as a tuple start to a point specified in the tuple end """ start = ( radians(start[0]), radians(start[1])) end = ( radians(end[0]), radians(end[1])) delta_lon = end[1] - start[1] delta_lat = log(tan(pi/4 +...
20,977
def get_frame_list(video, jump_size = 6, **kwargs): """ Returns list of frame numbers including first and last frame. """ frame_numbers =\ [frame_number for frame_number in range(0, video.frame_count, jump_size)] last_frame_number = video.frame_count - 1; if frame_numbers[-1] != last_...
20,978
def build_xlsx_response(wb, title="report"): """ Take a workbook and return a xlsx file response """ title = generate_filename(title, '.xlsx') myfile = BytesIO() myfile.write(save_virtual_workbook(wb)) response = HttpResponse( myfile.getvalue(), content_type='application/vnd.openxmlf...
20,979
def top_k(*args, **kwargs): """ See https://www.tensorflow.org/api_docs/python/tf/nn/top_k . """ return tensorflow.nn.top_k(*args, **kwargs)
20,980
def offline_evaluate( predict_fn: Callable[[np.ndarray, Any], Dict[Text, np.ndarray]], observe_fn: Callable[[np.ndarray, np.ndarray, np.ndarray, Any], Any], reset_fn: Callable[..., Any], train_fn: Callable[[Text], None] = None, train_dir: Text = None, enable_train: bool = False, train_eval_i...
20,981
def determine_d_atoms_without_connectivity(zmat, coords, a_atoms, n): """ A helper function to determine d_atoms without connectivity information. Args: zmat (dict): The zmat. coords (list, tuple): Just the 'coords' part of the xyz dict. a_atoms (list): The determined a_atoms. ...
20,982
def plot_confusion_matrix(y_true, y_pred, pad_index=None, ymap=None, figsize=(20, 10), show_total=['x', 'y'], show_zeros=True, show_empty_tags=False, plot_title='Confusion Matrix', save_name=None): """ Generate matrix plot of confusio...
20,983
def choose_domain(path: Path, domain: str or None, dot_mlf_core: dict = None): """ Prompts the user for the template domain. Creates the .mlf_core file. Prompts the user whether or not to create a Github repository :param path: The path, the project should be created at :param domain: Template ...
20,984
def all_of_them(): """ Return page with all products with given name from API. """ if 'username' in session: return render_template('productsearch.html', username=escape(session['username']), vars=lyst) else: return "Your are not logged in"
20,985
def test_downsample_handle_livetime_error(uncal_spec): """Test bad value of handle_livetime""" with pytest.raises(ValueError): uncal_spec.downsample(5, handle_livetime="asdf")
20,986
def is_blank(line): """Determines if a selected line consists entirely of whitespace.""" return whitespace_re.match(line) is not None
20,987
def _gff_line_map(line, params): """Map part of Map-Reduce; parses a line of GFF into a dictionary. Given an input line from a GFF file, this: - decides if the file passes our filtering limits - if so: - breaks it into component elements - determines the type of attribute (flat, parent,...
20,988
def smoothEvolve(problem, orig_point, first_ref, second_ref): """Evolves using RVEA with abrupt change of reference vectors.""" pop = Population(problem, assign_type="empty", plotting=False) try: pop.evolve(slowRVEA, {"generations_per_iteration": 200, "iterations": 15}) except IndexError: ...
20,989
def combine_color_channels(discrete_rgb_images): """ Combine discrete r,g,b images to RGB iamges. :param discrete_rgb_images: :return: """ color_imgs = [] for r, g, b in zip(*discrete_rgb_images): # pca output is float64, positive and negative. normalize the images to [0,...
20,990
def decohere_earlier_link(tA, tB, wA, wB, T_coh): """Applies decoherence to the earlier generated of the two links. Parameters ---------- tA : float Waiting time of one of the links. wA : float Corresponding fidelity tB : float Waiting time of the other link. ...
20,991
def train( network: RNN, data: np.ndarray, epochs: int = 10, _n_seqs: int = 10, _n_steps: int = 50, lr: int = 0.001, clip: int = 5, val_frac: int = 0.2, cuda: bool = True, print_every: int = 10, ): """Train RNN.""" network.train() opt = torch.optim.Adam(network.parame...
20,992
def simple_lunar_phase(jd): """ This just does a quick-and-dirty estimate of the Moon's phase given the date. """ lunations = (jd - 2451550.1) / LUNAR_PERIOD percent = lunations - int(lunations) phase_angle = percent * 360. delta_t = phase_angle * LUNAR_PERIOD / 360. moon_day = int(delt...
20,993
def fetch_traj(data, sample_index, colum_index): """ Returns the state sequence. It also deletes the middle index, which is the transition point from history to future. """ # data shape: [sample_index, time, feature] traj = np.delete(data[sample_index, :, colum_index:colum_index+1], history...
20,994
def validate_date(period: str, start: bool = False) -> pd.Timestamp: """Validate the format of date passed as a string. :param period: Date in string. If None, date of today is assigned. :type period: str :param start: Whether argument passed is a starting date or an ending date, defaults to Fa...
20,995
def rec_module_mic(echograms, mic_specs): """ Apply microphone directivity gains to a set of given echograms. Parameters ---------- echograms : ndarray, dtype = Echogram Target echograms. Dimension = (nSrc, nRec) mic_specs : ndarray Microphone directions and directivity factor. ...
20,996
def is_string_like(obj): # from John Hunter, types-free version """Check if obj is string.""" try: obj + '' except (TypeError, ValueError): return False return True
20,997
def get_firefox_start_cmd(): """Return the command to start firefox.""" start_cmd = "" if platform.system() == "Darwin": start_cmd = ("/Applications/Firefox.app/Contents/MacOS/firefox-bin") elif platform.system() == "Windows": start_cmd = _find_exe_in_registry() or _default_windows...
20,998
def divide(): """Handles division, returns a string of the answer""" a = int(request.args["a"]) b = int(request.args["b"]) quotient = str(int(operations.div(a, b))) return quotient
20,999