content
stringlengths
22
815k
id
int64
0
4.91M
def make_coord_dict(coord): """helper function to make a dict from a coordinate for logging""" return dict( z=int_if_exact(coord.zoom), x=int_if_exact(coord.column), y=int_if_exact(coord.row), )
65,700
def validate_signature_fragments(fragments, hash_, public_key): # type: (Sequence[TryteString], Hash, TryteString) -> bool """ Returns whether a sequence of signature fragments is valid. :param fragments: Sequence of signature fragments (usually :py:class:`cornode.transaction.Fragment` instances). :...
65,701
def ImageRotate(image, angle, scale): """ :param image: :param angle: :param scale: :return: """ H, W, C = image.shape center = (H / 2, H / 2) # H: rows # 获得旋转矩阵 M = cv2.getRotationMatrix2D(center, angle, scale) # 进行仿射变换,边界填充为255,, borderValue=(255, 255, 255...
65,702
def copy_files_to_destination(gen): """ Copy files to target destination """ global file_mapping for m in file_mapping: if not m[0].exists(): logger.warning(f"dynamic_plot: source file not found ({str(m[0])})") continue os.makedirs(os.path.dirname(str(m[1])),...
65,703
def watcher_limited(mocker): """ Make event streaming finite, watcher exits after depletion. """ mocker.patch('kopf.clients.watching.infinite_watch', new=streaming_watch)
65,704
def create_dir_ifnotexists(dirname): """Create a directory if it doesn't exist Parameters: dirname - name of directory to create Returns: Nothing Raises: Unhandled exceptions """ try: os.makedirs(dirname) logging.debug('created local directory: {}'.format(...
65,705
def deserialize(name, custom_objects=None): """Returns a policy function or class denoted by input string. Arguments: name : String Returns: Policy function or class denoted by input string. For example: >>> softlearning.policies.get({ ... 'class_name': 'ContinuousUniformP...
65,706
def do_stuff4(): """ This is right """ first, second = 1, 2 return first + second
65,707
def _mk_syswow64(): """ Makes the syswow64 folder """ try: os.makedirs(os.path.join(protonprefix(), 'drive_c/windows/syswow64')) except FileExistsError: log.warn('The syswor64 folder already exists')
65,708
def _validate_alias_file_content(alias_file_path, url=''): """ Make sure the alias name and alias command in the alias file is in valid format. Args: The alias file path to import aliases from. """ alias_table = get_config_parser() try: alias_table.read(alias_file_path) ...
65,709
def sqrt(argument: _Union[_Real, Expression]) -> Expression: """ Returns square root of the argument: exact if it is a perfect square, symbolic instead. >>> sqrt(0) == 0 True >>> sqrt(1) == 1 True >>> square_root_of_two = sqrt(2) >>> square_root_of_two ** 2 == 2 True >>>...
65,710
def windowedAverage(window, step, sample): """ Input is a sample, with a list of CHROM, POS, mel, sim, sec Output is a list of CHROM, POS, mel, sim, sec, but a window average around that point """ entryDict = {} ## best to get this in a dict, since things are going to get looked up several times ...
65,711
def main(): """ 主函数 """ op = yes_or_no('请确保手机打开了 ADB 并连接了电脑,' '然后打开跳一跳并【开始游戏】后再用本程序,确定开始?') if not op: print('bye') return print('程序版本号:{}'.format(VERSION)) debug.dump_device_info() screenshot.check_screenshot() i, next_rest, next_rest_time = (0, r...
65,712
def ajouter_vehicule(dfv, t, mark, mod, carb, gam, km): """ ajoute un véhicule à la base de données in : dfv : dataframe de la base de donnees des vehicules dic : dictionnaire contenant toutes les caractéristiques du véhicule à ajouter, sauf le numéro d'identification ('id' : No...
65,713
def main(opts): """ resample SLC """ # prep SLC dataset input productSlc = SLC(hdf5file=opts.product) # get grids needed for resamp object instantiation productGrid = productSlc.getRadarGrid(opts.frequency) # instantiate resamp object based on user input if 'cuda' not in dir(isce3...
65,714
def post_bundle(name, action): # noqa: E501 """post_bundle # noqa: E501 :param name: :type name: str :param action: :type action: str :rtype: None """ return 'do some magic!'
65,715
def non_obs_walko(relation, a, b): """Construct a goal that applies a relation to all nodes above an observed random variable. This is useful if you don't want to apply relations to an observed random variable, but you do want to apply them to every term above one and ultimately reproduce the entire gr...
65,716
def get_project_config_file_name(): """ :returns: config file basename """ return SteveConfig.file_name
65,717
def is_close(a: Union[util.number, list], b: Union[util.number, list], rel_tol=1e-8, abs_tol=1e-8) -> bool: """Checks if the specified numbers are close enough to be considered equal. Due to the usage of IEEE754 floating points number in Python, formulae like 0.1+0.2 can lead to surprising results differen...
65,718
def test_reset( decoy: Decoy, call_stack: CallStack, stub_store: StubStore, warning_checker: WarningChecker, subject: DecoyCore, ) -> None: """It should reset the stores.""" call = SpyCall(spy_id=1, spy_name="my_spy", args=(), kwargs={}) decoy.when(call_stack.get_all()).then_return([cal...
65,719
def epw_header(epw): """ Given an EPW, get the header """ with open(epw, "r") as f: header = f.readline().strip().split(",") return { "city": header[1], "state": header[2], "country": header[3], "source": header[4], "WMO": header[5], "lat": f...
65,720
def prepare_single_asset_payload(args: Dict[str, Any], operation: str) -> Dict[str, Any]: """ Prepare payload for post data in case user wants to add or update single asset. Throws error if valid values are not provided in arguments. :param args: args passed by the user :param operation: operation ...
65,721
def dedup(xs: Iterable[U], on=lambda x: x) -> Iterator[U]: """ Deduplicates an iterable. Any item is guaranteed to only occur once in the result. """ seen = set() for x in xs: identity = on(x) if identity in seen: continue seen.add(identity) yield x
65,722
def repeat(s: str, n: int) -> str: """ Return s repeated n times; if n is negative, return the empty string. >>> repeat('yes', 4) 'yesyesyesyes' >>> repeat('no', 0) '' >>> repeat('no', -2) '' >>> repeat('yesnomaybe', 3) 'yesnomaybeyesnomaybeyesnomaybe' """ return s * n
65,723
def rearange_books_by_category(books_json): """rearange_books_by_category. Returns JSON with following structure: { "Beginner":[ { "title": "author": "url" } ], "Intermediate":[ { "title": "auth...
65,724
def GetTileMatrix(layout, tile_size, values, viewport): """For the given tile layout and per-tile bench values, returns a matrix of bench values with tiles outside the given viewport set to 0. layout, tile_size and viewport are given in string of format <w>x<h>, where <w> is viewport width or number of tile co...
65,725
def reverse(view_name, lang=None, use_lang_prefix=True, *args, **kwargs): """ Similar to django.core.urlresolvers.reverse except for the extra parameter: @param lang: anguage code in which the url is to be translated (ignored if use_lang_prefix is False). @param use_lang_prefix: Is changed to False, get an url wit...
65,726
def train(): """Training model.""" logger.info("Loading data...") logger.info("Training data processing...") train_students = np.load("data/train" + number + ".npy", allow_pickle=True) logger.info("Validation data processing...") test_students = np.load("data/test" + number + ".npy", allo...
65,727
def cal_pop_fitness(target_chrom, pop): """ This method calculates the fitness of all solutions in the population. """ qualities = numpy.zeros(pop.shape[0]) for indv_num in range(pop.shape[0]): # Calling fitness_fun(...) to get the fitness of the current solution. qualities[indv_num]...
65,728
def upload_folder(directory, project_id=None, subject_id=None, session_id=None, scan_id=None, assessor_id=None, resource=None, remove=False, removeall=False, extract=True): """ Upload a folder to some URI in XNAT based on the inputs :param directory: Full path to directo...
65,729
def SetProperties(proxy=None, **params): """Sets one or more properties of the given pipeline object. If an argument is not provided, the active source is used. Pass a list of property_name=value pairs to this function to set property values. For example:: SetProperties(Center=[1, 2, 3], Radius=3.5...
65,730
def get_ldap_vpn_schema_settings(api_client, **kwargs): # noqa: E501 """Get LDAP VPN schema settings # noqa: E501 Get LDAP VPN schema settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> response = aw...
65,731
def aes_encrypt(AES_KEY, AES_IV, data): """ aes_key: 密钥 aes_iv: iv 提交表单加密 """ aes_key = bytes(AES_KEY, 'utf-8') aes_iv = bytes(AES_IV, 'utf-8') data = bytes(data, 'utf-8') data = aes_pkcs7padding(data) cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) encrypted = b64...
65,732
def dap_control(tool, reg_map, cpu_id, desired_state, jwt_not_required, filename): """ Calls DAPControl SysCall over IPC :param tool: Programming/debugging tool :param reg_map: Device register map :param cpu_id: CPU ID (0-CM0, 1-CM4, 2-SYS) :param desired_state: The state to be s...
65,733
def get_preparation_cmd(user, permissions, path): """ Generates the command lines for adjusting a volume's ownership and permission flags. Returns an empty list if there is nothing to adjust. :param user: User to set ownership for on the path via ``chown``. :type user: unicode | str | int | dockerm...
65,734
def _rating_weighted_avg_jk_std(iur, item, sims, use): # JACKKNIFE ESTIMATE OF STANDARD DEVIATION FOR WEIGHTED-AVERAGE """ Sum aggregate Args: iur(matrix._CSR): the item-user ratings matrix item(int): the item index in ``iur`` sims(numpy.ndarray): the similarities for the users who ...
65,735
def dummy_null_python(): """ Equatorial Reverse & Capture """ q0 = [2.5, np.pi / 2, 0.] p0 = [0., 0., -8.5] a = 0.9 end_lambda = 10. step_size = 0.005 julia = False return q0, p0, a, end_lambda, step_size, julia
65,736
def generate_graph(generate_configuration) -> pgv.AGraph: """ Walk a NiFi flow and produce an AGraph. Configuration options will be used to control the depth of the process group recursion, load templates to overload subgraph settings, and set properties on processors If the generate-mocks flag is s...
65,737
def run_jobs(): """ Runs the sensor reading job every 30 seconds. """ schedule.every(30).seconds.do(scheduling_service.sensor_reading_job) scheduling_service.sensor_reading_job() while running: schedule.run_pending() time.sleep(1)
65,738
def _load_schemas(): """Populates ``_SCHEMAS`` with the schemas defined in package ``armada.schemas``. """ schema_dir = _get_schema_dir() for schema_file in os.listdir(schema_dir): with open(os.path.join(schema_dir, schema_file)) as f: for schema in yaml.safe_load_all(f): ...
65,739
def set_or_callable(value): """Convert single str or None to a set. Pass through callables and sets.""" if value is None: return frozenset() if callable(value): return value if isinstance(value, (frozenset, set, list)): return frozenset(value) return frozenset([str(value)])
65,740
def test_feature_columns_exist(): """ Validate that all required columns are present """ df = get_fixture_df() for col in REQUIRED_COLUMNS: assert col in df.columns
65,741
def enable(): """Enable the plenpy logger. The logger is enabled by default. """ lg = get_logger() lg.propagate = True return
65,742
async def test_armed_night_with_specific_pending(hass): """Test arm home method.""" assert await async_setup_component( hass, alarm_control_panel.DOMAIN, { "alarm_control_panel": { "platform": "manual", "name": "test", "arming_t...
65,743
def err(msg): """Pretty-print an error.""" click.echo(click.style(msg, fg="red", bold=True))
65,744
def print_welcome_message(board_values: dict[str, str]): """ Prints a nice welcome message and displays the empty board. :param board_values: Map of current, empty board values. Empty squares should map to their square label. """ print(c.INTRO_MESSAGE) print_board(board...
65,745
def update_award_categories(award_tuple=None): """ This sets the category variable for an award. """ awards = Award.objects.all() if award_tuple: awards = awards.filter(id__in=list(award_tuple)) awards.update( category=Case( When(type__in=['A', 'B', 'C', 'D'], then=Va...
65,746
def remove_numerics(df, col): """function to remove numbers or words with digits""" df[col] = df[col].apply(lambda x: re.sub(r'\w*\d\w*', r'', str(x)))
65,747
def check_case(conv_nonlinearity, mlp_nonlinearity, cost_implemented=True): """Check that ConvNonLinearity and MLPNonlinearity are consistent. This is done by building an MLP with a ConvElemwise layer with the supplied non-linearity, an MLP with a dense layer, and checking that the outputs (and costs i...
65,748
def _isotonic_partial_errors(sequence: Sequence[float], weights: Sequence[float]) -> np.ndarray: """Finds the partial errors of isotonic regression over subsequences. O(n). Pool adjacent violators, but we track the squared error at each step. This is equivalent to performing isotonic...
65,749
def solve_sqrt_lasso_skinny(X, Y, weights=None, initial=None, **solve_kwargs): """ Solve the square-root LASSO optimization problem: $$ \text{minimize}_{\beta} \|y-X\beta\|_2 + D |\beta|, $$ where $D$ is the diagonal matrix with weights on its diagonal. Parameters ---------- y : ...
65,750
def generate_courtyard( uuid: str, max_x: float, max_y: float, excess_x: float, excess_y: float, ) -> List[str]: """ Generate a rectangular courtyard polygon. Args: uuid: The polygon UUID max_x: The half width (x) of the maximum boundary m...
65,751
def loginView(request): """Verifies login information and then authenticates user into Django system.""" data = json.loads(request.body) username = data.get('username') password = data.get('password') if username is None or password is None: return JsonResponse({"Info": "Username and Passw...
65,752
def add_id(pos_list, image_id=0): """ Add id for gather feature, for inference. """ new_list = [] for item in pos_list: new_list.append((image_id, item[0], item[1])) return new_list
65,753
def det_solve_3(m, b): """Решение системы c 3 неизвестными по методу Крамера""" m = np.array(m) det_1 = det(np.column_stack([b, m[:, 1], m[:, 2]])) det_2 = det(np.column_stack([m[:, 0], b, m[:, 2]])) det_3 = det(np.column_stack([m[:, 0], m[:, 1], b])) return (det_1 / det(m), det_2 / det...
65,754
def render_inner_single(items): """render_inner callback for --is-primary""" items = list(items) if len(items) != 1: raise BadInputError("--is-primary specified but specified key matches " "more than one record: %r" % items) return items[0]
65,755
def test_encrypt(): """Test encryption""" assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
65,756
def legendre_poly(n, x=None, **args): """Generates Legendre polynomial of degree `n` in `x`.""" if n < 0: raise ValueError("can't generate Legendre polynomial of degree %s" % n) poly = dup_legendre(int(n), QQ) if x is not None: poly = Poly(poly, x, domain=QQ) else: poly = P...
65,757
def read_sig(path, n_channels, header=None, sep='\t', rem_len=5): """ Read signal in tabular format (csv, tsv) :param path: path of the tabular data file :param n_channels: number of channels to be handled. Extra channels will be ignored :param sep: tabular data separator. Default `tab` :param r...
65,758
def test_version_succeeds() -> None: """It exits with a status code of zero.""" result = runner.invoke(app, ["version"]) assert result.exit_code == 0 assert "Ihsan" in result.stdout
65,759
def find_max_sentence_length(sequences: list) -> int: """ returns the longest sequence, which will be used as the maximum sequence. :param sequences : list[list[int]] :return int """ max_length = None for seq in sequences: if max_length is None or len(seq) > max_length: m...
65,760
def _load_missing_region_edges(regions): """Fill in the missing Has_Parent_Region edges.""" # Existing regions whose parent region is Westeros. westeros_children = [ 'Beyond the Wall', 'The North', 'Iron Islands', 'The Riverlands', 'The Vale of Arryn', 'The We...
65,761
def is_empty_tensor(t): """Returns whether t is an empty tensor.""" return len(t.size()) == 0
65,762
def set_font_sizes(SMALL_SIZE = 13, MEDIUM_SIZE=14): """ Sets up font sizes for plots """ plt.rc('font', size=SMALL_SIZE, family='Arial') plt.rc('axes', titlesize=MEDIUM_SIZE) plt.rc('axes', labelsize=MEDIUM_SIZE) plt.rc('xtick', labelsize=SMALL_SIZE) plt.rc('ytick', labelsize=SMALL_SIZE)
65,763
def admin_ide_list(): """ List all active ide sessions :return: """ # Get all active sessions sessions = TheiaSession.query.filter( TheiaSession.active == True, TheiaSession.course_id == course_context.id, ).all() # Hand back response return success_response({"sess...
65,764
def evaluateHypothalamicSegmentation(SUBJECT, SUBJECTS_DIR, OUTPUT_DIR, CREATE_SCREENSHOT = True, SCREENSHOTS_OUTFILE = []): """ A function to evaluate potential missegmentation of the hypothalamus. This script evaluates potential missegmentation of the hypothalamus as created by FreeSurfer 7.2's modul...
65,765
def test_read_file_returns_bitmap_instance(): """"Test that read_file function returns instance of Bitmap.""" assert isinstance(Bitmap.read_file(BMP_FILE_PATH), Bitmap)
65,766
def construct_sampling_ops(model): """Builds a graph fragment for sampling over a TransformerModel. Args: model: a TransformerModel. Returns: A tuple (ids, scores), where ids is a Tensor with shape (batch_size, max_seq_len) containing one sampled translation for each input sentence...
65,767
def format(datatype: str, value: Optional[Value], default: Optional[str] = None) -> str: """ Format a column *value* based on its *field*. If *value* is `None` then *default* is returned if it is given (i.e., not `None`). If *default* is `None`, `'-1'` is returned if *datatype...
65,768
def sinusoid( frequency, sampling_frequency=16000, duration=0.025 ): """Generate a sinusoid signal. Args: frequency (int): the frequency of the sinusoidal signal. sampling_frequency (int, optional): sampling frequency in Hz. Defaults to 16000. duration (float, optional): ...
65,769
def test_pig(): """Tests for the `pig` function""" tests = [ ('mouse', 'ouse-may'), ('apple', 'apple-ay'), ('chair', 'air-chay'), ('street', 'eet-stray'), ('BOOK', 'OOK-Bay'), ('Creek', 'eek-Cray'), ] for given, expected in tests: assert expected...
65,770
def printc(msg: str, col: Colour_Types, end: str = "\n") -> None: """Print a string, in a specified ansi colour.""" print(f"{col!r}{msg}{Ansi.RESET!r}", end=end)
65,771
def clear_replication_metadata(client: CogniteClient): """Removes the replication metadata from all resources, so that the replicated tenant will look like an original. Sample use-case: clean up a demo-tenant so that extra data is not present. Caution: After clearing replication metadata, the delete_replic...
65,772
def Delete_Portfolio_Holdings(portfolio_name,timestamp,rev): """ Deletes a portfolio. """ BASEURL = "https://investment-portfolio.mybluemix.net/api/v1/portfolios/" + str(portfolio_name) + "/holdings/" + str(timestamp) + "?rev=" + str(rev) print(BASEURL) headers = { 'Content-Type': "appli...
65,773
def get_refs(data: list, num=3): """获取参考音频,和所有同一个说话人的embed余弦相似度最小。""" sim_mat = pairwise_distances(data, metric='cosine') sim_vec = np.mean(sim_mat, axis=0) ids = range(len(sim_vec)) outs = [k for k, v in clt.Counter(dict(zip(ids, 1 - sim_vec))).most_common(num)] # outs = sorted(ids, key=lambda ...
65,774
def test_workspace_rest_list_no_duplicates( workspace: Workspace, user_factory: UserFactory, user: User, authenticated_api_client: APIClient, ): """Test that multiple roles on a workspace results in no duplicates.""" # Set authenticated user as owner workspace.set_owner(user) # Give mul...
65,775
def test_wet_bulb_temperature_2d(): """Test wet bulb calculation with 2d list.""" pressures = [[1013, 1000, 990], [1012, 999, 989]] * units.hPa temperatures = [[25, 20, 15], [24, 19, 14]] * units.degC dewpoints = [[20, 15, 10], [19, 14, 9]] * units.d...
65,776
def add_light_area(xyz=(0, 0, 0), rot_vec_rad=(0, 0, 0), name=None, energy=100, size=0.1): """ Add area light that emits light rays the lambertian way Args: xyz: Location 3-tuple of floats Optional; defaults to (0, 0, 0) rot_vec_rad: Rotation angle in radians around ...
65,777
def DAC_control(node): """ DAC_control This node is the interface between our graph and the DAC hardware. rx_data would be linked to an SPI DAC, in this example is goes nowhere. This node is built as a finite state machine, the accumulator node can issue different commands to control the state mach...
65,778
def get_last_table_stations(): """ Return date from the last row of stations table :return: date returned from database or None """ connection = psycopg2.connect(dbname='air_data', user='docker', password='docker', host='dbserver') cursor = connection.cursor() expression = f"SELECT date FROM...
65,779
def average_trial(trial, isotropic=False): """Take average of thermal conductivities for multiple runs. Assumes all runs have the same number of directions. Args: - isotropic (bool): Isotropy of thermal flux, if True aveage is taken for each direction Returns: - dict: Trial data averag...
65,780
def to_chunks(stream_or_generator): """This generator function receives file-like or generator as input and returns generator. :param file|__generator[bytes] stream_or_generator: readable stream or generator. :rtype: __generator[bytes] :raise: TypeError """ if isinstance(strea...
65,781
def find_SNPs(chromosome, snp_position): """ Looks for SNPs on given position in the genome using pileup. :param chromosome: :param snp_position: """ base_ratios = {'A': [0, 0], 'C': [0, 0], 'G': [0, 0], 'T': [0, 0], '=': [0, 0]} deletions = 0 total_n = 0 variant = v.Variant(chromoso...
65,782
def test_is_json_encodable_namedtuple(): """ Tests the encoding of namedtuples. """ class NamedTupleExampleT(NamedTuple): name: str value: Union[int, float] t = NamedTupleExampleT("t", 1) t_encoding = OrderedDict([("name", "t"), ("value", 1)]) assert to_json_obj(t, NamedT...
65,783
def is_approved(given_user): """ Helper template function to check if a user is approved. given_user: The User object that we are checking to see if they are approved or not. """ # try getting the RegisteredUser of the current user try: get_registered_user = RegisteredUser.objects....
65,784
def all_exception_handler(handler_input: HandlerInput, exception: Exception) -> Response: """Catch all exception handler, log exception and respond with custom message. """ _logger.error(exception, exc_info=True) _: Callable = handler_input.attributes_manager.request_attributes["_"] handler_inpu...
65,785
def rna_cofold_strand_pairs_constraint( threshold: float, temperature: float = dv.default_temperature, weight: float = 1.0, score_transfer_function: Callable[[float], float] = default_score_transfer_function, description: Optional[str] = None, short_description: str = 'rn...
65,786
def generate_token(): """ Generate a token. This is an utility command that generates a valid token needed to configure both the client and the server. Note that by default, the server will generate a token if none was explicitly set. """ from remofile.token import generate_token prin...
65,787
def CheckForEscape(): """Check for 'escape' key.""" KeyPress = event.getKeys(keyList=['escape']) if KeyPress: QuitTask() event.clearEvents()
65,788
def round(x): """Rounds the given number to a globally constant precision.""" return builtins.round(x, this._precision_digits)
65,789
def activate_svc(svc): """ Activates a service. """ resp = requests.post( svc['links']['self'], auth=AUTH, params=dict(action='activate') ) resp.raise_for_status() return resp.json()
65,790
def isNotTrue (b) : """return True if b is not equal to True, return False otherwise >>> isNotTrue(True) False >>> isNotTrue(False) True >>> isNotTrue("hello world") True """ # take care: not(X or Y) is (not X) and (not Y) if b is not True and b != True : # base case: b ...
65,791
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.varia...
65,792
def search(variable: str, target: str) -> str: """Search serice using mwapi on wikidata Args: variable (str): variable name (?film, ?director...) target (str): value to search for Returns: str: service query """ if variable is None or target is None: return "" ...
65,793
def collect_name(etok,s): """ Make a list of all subtokens with name s. >>> collect_name(pstream(r.tdop_rel_prop(),'x,y,z PRIM_BINARY_RELATION_OP u PRIM_BINARY_RELATION_OP x'),'VAR') [Etok(VAR,x,'x'), Etok(VAR,u,'u'), Etok(VAR,y,'y'), Etok(VAR,u,'u'), Etok(VAR,z,'z'), Etok(VAR,u,'u'), Etok(VAR,u,'u'), E...
65,794
def test_delete_room_01(): """ Test deleting last inserted room. """ room_id = client.get("/rooms/last/").json()["room"]["id"] response = client.delete(f"/rooms/{room_id}") deleted_room = client.get(f"/rooms/{room_id}") expect = { 'detail': "Room not found", } assert response.sta...
65,795
def indexresample(adjacency, distance=[], samples=[], percentage=[]): """ Bootstrap method to resample neighborhood indices. For a given adjacency list, sample indices that are at most a distance=k units away from a vertex. Parameters: - - - - - adjacency: surface adjacency list ...
65,796
def scrub_df(df: DataFrame) -> DataFrame: """Prepare DataFrame for loading into Sqlite db """ df.loc[:, 'timestamp_created'] = pd.to_datetime(df['timestamp_created'], unit='s') df.loc[:, 'is_OC'] = df['is_OC'].astype(int) for col in df.select_dtypes(include=np.number).columns: df.loc[:, col...
65,797
def dameraulevenshtein(seq1, seq2): """Calculate the Damerau-Levenshtein distance between sequences. This distance is the number of additions, deletions, substitutions, and transpositions needed to transform the first sequence into the second. Although generally used with strings, any sequences of ...
65,798
def test_compiler_complex_nested_expression_10(parser): """ Ensures that complex nested expressions are compiled correctly """ source = """d['a'] + list[0] / list[1] * d['a'] % d['b']""" result = Compiler.compile(parser.parse(source)) assert result['tree']['1']['method'] == 'expression' asse...
65,799