content
stringlengths
22
815k
id
int64
0
4.91M
def mock_weather_for_coordinates(*args, **kwargs): # noqa: F841 """Return mock data for request weather product type.""" if args[2] == aiohere.WeatherProductType[MODE_ASTRONOMY]: return astronomy_response if args[2] == aiohere.WeatherProductType[MODE_HOURLY]: return hourly_response if a...
36,600
def get_user(request, project_key): """Return the ID of the current user for the given project""" projects = request.cookies.get('projects') if projects is None: return None try: projects = json.loads(projects) except (ValueError, KeyError, TypeError): print "JSON format erro...
36,601
def test_metaconn_matrix_2brains(epochs): """ Test metaconn_matrix_2brains """ # TODO: test metaconn_matrix and con_matrix # taking random freq-of-interest to test metaconn_freq freq = [11, 12, 13] # computing ch_con and sensors pairs for metaconn calculation ch_con, ch_con_freq = stats....
36,602
def extract_month(cube, month): """ Slice cube to get only the data belonging to a specific month. Parameters ---------- cube: iris.cube.Cube Original data month: int Month to extract as a number from 1 to 12 Returns ------- iris.cube.Cube data cube for spec...
36,603
def debug(context, nautobot_ver=NAUTOBOT_VER, python_ver=PYTHON_VER): """Start Nautobot and its dependencies in debug mode. Args: context (obj): Used to run specific commands nautobot_ver (str): Nautobot version to use to build the container python_ver (str): Will use the Python version...
36,604
def is_insert_grad_of_statement(node): """Check whether a context manager calls `insert_grad_of`. Args: node: The context manager node. Returns: Whether or not this node contains `insert_grad_of` calls. Raises: ValueError: If the `insert_grad_of` calls are mixed with other calls. """ tangent_...
36,605
def get_word(count: typing.Union[int, typing.Tuple[int]] = 1, # pylint: disable=dangerous-default-value sep: str = ' ', func: typing.Optional[typing.Union[str, typing.Callable[[str], str]]] = None, args: typing.Tuple[str] = (), kwargs: typing.Dict[str, str] = {}) -> str: """R...
36,606
def button_debug(): """ Debugger for testing websocket sent signals from RPi buttons (for now simulated in in browser) """ return render_template('button_debug.html')
36,607
def get_int(b): """@TODO: Docs. Contribution is welcome.""" return int(codecs.encode(b, "hex"), 16)
36,608
def test_examples_tensor_sph(): """compare derivatives of tensorial fields for spherical grids""" grid = SphericalSymGrid(1, 32) tf = Tensor2Field.from_expression(grid, [["r**3"] * 3] * 3) tfd = tf.data tfd[0, 1] = tfd[1, 1] = tfd[1, 2] = tfd[2, 1] = tfd[2, 2] = 0 # tensor divergence res = ...
36,609
def chrom_exp_cusp(toas, freqs, log10_Amp=-7, sign_param=-1.0, t0=54000, log10_tau=1.7, idx=2): """ Chromatic exponential-cusp delay term in TOAs. :param t0: time of exponential minimum [MJD] :param tau: 1/e time of exponential [s] :param log10_Amp: amplitude of cusp :param ...
36,610
def powerspectrum_t(flist, mMax=30, rbins=50, paramname=None, parallel=True, spacing='linear'): """ Calculates the power spectrum along the angular direction for a whole simulation (see powerspectrum). Loops through snapshots in a simulation, in parallel. Uses the same radial ...
36,611
def score(scores, main_channel, whiten_filter): """ Whiten scores using whitening filter Parameters ---------- scores: np.array (n_data, n_features, n_neigh) n_data is the number of spikes n_feature is the number features n_neigh is the number of neighboring channels conside...
36,612
def multiple_node_testing(verbose=False, report=False): """ This function ensures the testing of all available nodes. The results of the test are packed into an HTML file which is saved in the current working directory. """ # we define a list of nodes that we do not want to test skipped_dirs...
36,613
def make_title(raw_input): """Capitalize and strip""" return raw_input.title().strip()
36,614
def perform(target, write_function=None): """ Perform an HTTP request against a given target gathering some basic timing and content size values. """ fnc = write_function or (lambda x: None) assert target connection = pycurl.Curl() connection.setopt(pycurl.URL, target) connection.s...
36,615
def keygen(size, priv_key, pub_key): """Generated a RSA keypair""" initial_time = time.time() print("Generating key...") with click_spinner.spinner(): n, e, d, p, q, pubkey, privkey = rsalib.keygen(size) with open(pub_key, "wb") as f: f.write(pubkey.save_pkcs1()) with open(priv_k...
36,616
def load_xml_images(renderer, filename, _filter=[], by_name=False): """ Load images from a TextureAtlas XML file. Images may be filtered and are return in a list, or optionally, a dict images indexed by the name found in the xml file. :param renderer: renderer to attach texture to :param filename: path to a vali...
36,617
def merge_property_into_method( l: Signature, r: typing.Tuple[Metadata, OutputType] ) -> Signature: """ Merges a property into a method by just using method """ return l
36,618
def get_image_paths(dir_path, image_filename_pattern="img_{:05d}.jpg", fps=15): """each dir contains the same number of flow_x_{:05d}.jpg, flow_y_{:05d}.jpg, img_{:05d}.jpg. Index starts at 1, not 0, thus there is no img_00000.jpg, etc. """ num_rgb_images = int(len(os.listdir(dir_path)) / 3) # must be ...
36,619
def app(): """Create and configure a new app instance for each test.""" # create a temporary file to isolate the database for each test # create the app with common test config app = create_app() # create the database and load test data with app.app_context(): db.create_all() yield...
36,620
def _serve_archive(content_hash, file_name, mime_type): """Serve a file from the archive or by generating an external URL.""" url = archive.generate_url(content_hash, file_name=file_name, mime_type=mime_type) if url is not None: return re...
36,621
def do_config(args): """ Handle configuration commands. Currently this only includes setting or retrieving the current api key. """ global apiKey, lab, config config['Auth']['apiKey'] = args.apiKey config['Auth']['lab'] = args.lab write_config() apiKey = args.apiKey print_co...
36,622
def preprocess(path ,scale = 3): """ This method prepares labels and downscaled image given path of image and scale. Modcrop is used on the image label to ensure length and width of image is divisible by scale. Inputs: path: the image directory path scale: scale to ...
36,623
def get_goal_sample_rate(start, goal): """Modifie la probabilité d'obtenir directement le but comme point selon la distance entre le départ et le but. Utile pour la précision et les performances.""" try : dx = goal[0]-start[0] dy = goal[1]-start[1] d = math.sqrt(dx * dx + dy * dy) ...
36,624
def triangulate_mesh(ob): """Triangulate the mesh.""" bpy.context.scene.objects.active = ob bpy.context.tool_settings.mesh_select_mode=(True,False,False) bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.select_all(action='SELECT') bpy.ops.mesh.quads_convert_to_tris() bpy.ops.object.mode_s...
36,625
def sample_cov(prices, returns_data=False, frequency=252, log_returns=False, **kwargs): """ Calculate the annualised sample covariance matrix of (daily) asset returns. :param prices: adjusted closing prices of the asset, each row is a date and each column is a ticker/id. :type prices:...
36,626
def str2bool(v): """Transforms string flag into boolean :param v: boolean as type or string :type v: str :return: bool or argparse error (if it's not recognized) :rtype: bool """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True...
36,627
def read_prev_timings(junit_report_path: str) -> Dict[str, float]: """Read the JUnit XML report in `junit_report_path` and returns its timings grouped by class name. """ tree = ET.parse(junit_report_path) if tree is None: pytest.exit(f"Could not find timings in JUnit XML {junit_report_path}"...
36,628
def update_model(): """ Updates a model """ data = request.get_json() params = data.get('params', {'model_id': 1}) entry = Model.objects(model_id=params.model_id).first() if not entry: return {'error': ModelNotFoundError()} entry.update(**params) return entry.to_json()
36,629
def SmartConnect(protocol='https', host='localhost', port=443, user='root', pwd='', service="hostd", path="/sdk", preferredApiVersions=None, keyFile=None, certFile=Non...
36,630
def _pseudoArrayFromScalars(scalarvalues, type): """Wrap a scalar in a buffer so it can be used as an array""" arr = _bufferPool.getBuffer() arr._check_overflow = 1 newtype = type # _numtypedict[type] arr._strides = (newtype.bytes,) arr._type = newtype arr._itemsize = newtype.bytes arr._...
36,631
def triangulate_ellipse(corners, num_segments=100): """Determines the triangulation of a path. The resulting `offsets` can multiplied by a `width` scalar and be added to the resulting `centers` to generate the vertices of the triangles for the triangulation, i.e. `vertices = centers + width*offsets`. Us...
36,632
def test_snr(): """Test trial to trial coherence""" raw = mne.io.Raw(raw_fname) sfreq = int(raw.info['sfreq']) data, times = raw[0, :5 * sfreq] # Create fake epochs from copies of the raw + noise n_epochs = 40 noise_amp = .01 * data.max() data = np.tile(data, [n_epochs, 1, 1]) data ...
36,633
def is_dbenv_loaded(): """ Return True of the dbenv was already loaded (with a call to load_dbenv), False otherwise. """ return settings.LOAD_DBENV_CALLED
36,634
def parse_python_settings_for_dmlab2d( lab2d_settings: config_dict.ConfigDict) -> Settings: """Flatten lab2d_settings into Lua-friendly properties.""" # Since config_dicts disallow "." in keys, we must use a different character, # "$", in our config and then convert it to "." here. This is particularly # im...
36,635
def get_new_name(x: str) -> str: """ Obtains a new name for the given site. Args: x: The original name. Returns: The new name. """ y = x.lower() if y == "cervical": return "cervical_spine" m = re.match(r"^([lr])\s+(.+)$", y) if not m: raise Val...
36,636
def discover(): """Find and load all available plugins. """ plugin_files = [] for plugin_dir in _get_plugin_dirs(): if os.path.isdir(plugin_dir): for plugin_file in os.listdir(plugin_dir): if plugin_file.endswith(".py") and not plugin_file == "__init__.py": ...
36,637
def read_csv_file2(filename): """Reads a CSV file and prints each row without list brackets. """ f = open(filename) for row in csv.reader(f): pass # replace this line with your code f.close()
36,638
def u2f_from_dict(data: Dict[str, Any]) -> U2F: """ Create an U2F instance from a dict. :param data: Credential parameters from database """ return U2F.from_dict(data)
36,639
def get_sequences(datafile, seq_column = "sequence_1D", test = False, test_size=100): """ Read DF, return sequences. So we do not hold the DF in memory. We could only read csv and grab the sequence column in the future. :return: """ if datafile.endswith(".csv"): df = pandas.read_csv(dat...
36,640
async def test_missing_summary(hass, mock_events_list_items, component_setup): """Test that we can create an event trigger on device.""" start_event = dt_util.now() + datetime.timedelta(minutes=14) end_event = start_event + datetime.timedelta(minutes=60) event = { **TEST_EVENT, "start": ...
36,641
def for_f(): """ Pattern of Small Alphabet: 'f' using for loop""" for i in range(8): for j in range(5): if j==1 and i>0 or i==0 and j in(2,3) or i==1 and j==4 or i==4 and j<4: print('*',end=' ') else: ...
36,642
def filterForDoxygen (contents): """ filterForDoxygen(contents) -> contents Massage the content of a python file to better suit Doxygen's expectations. """ contents = filterContents(contents) contents = filterDocStrings(contents) return contents
36,643
def calculate_quantum_volume( *, num_qubits: int, depth: int, num_circuits: int, seed: int, device: cirq.google.xmon_device.XmonDevice, samplers: List[cirq.Sampler], compiler: Callable[[cirq.Circuit], cirq.Circuit] = None, repetitions=10_000, ) -> ...
36,644
def get_plugin_translator(plugin_path): """Returns a new ui.Translator object for plugin specified by plugin_path argument. If a file is passed, the last path component is removed. """ if os.path.isfile(plugin_path): plugin_path = os.path.split(plugin_path)[0] path = os.path.join(...
36,645
def get_key(item, key_length): """ key + value = item number of words of key = key_length function returns key """ word = item.strip().split() if key_length == 0: # fix return item elif len(word) == key_length: return item else: return ' '.join(word[0:key_le...
36,646
def identity(shape: Tuple[int, ...], gain: float = 1) -> JaxArray: """Returns the identity matrix. This initializer was proposed in `A Simple Way to Initialize Recurrent Networks of Rectified Linear Units <https://arxiv.org/abs/1504.00941>`_. Args: shape: Shape of the tensor. It should have exa...
36,647
def pyreq_nlu_trytrain(httpreq_handler: HTTPRequestHandler, project_id: int, locale: str) -> Optional[Dict]: """ Get try-annotation on utterance with latest run-time NLU model for a Mix project and locale, by sending requests to Mix API endpoint with Python 'requests' package. API endpoint: POST /nlu/a...
36,648
def month_boundaries(month: int, year: int) -> Tuple[datetime_.datetime, datetime_.datetime]: """ Return the boundary datetimes of a given month. """ start_date = datetime_.date(year, month, 1) end_date = start_date + relativedelta(months=1) return (midnight(start_date), midnight(end_date))
36,649
def calculate_Hubble_flow_velocity_from_cMpc(cMpc, cosmology="Planck15"): """ Calculates the Hubble flow recession velocity from comoving distance Parameters ---------- cMpc : array-like, shape (N, ) The distance in units of comoving megaparsecs. Must be 1D or scalar. cosmology : strin...
36,650
def _render_cluster_files( project_name: str, dependency_containers: List[DependencyContainer], rankdir: str, overlap: str, ratio: str, fontsize: str, dpi: str, shape: str, fontname: str, ) -> None: """ """ # Dirty hack to prevent a \t in the first edge edges = """ """ ...
36,651
def join_items( *items, separator="\n", description_mode=None, start="", end="", newlines=1 ): """ joins items using separator, ending with end and newlines Args: *items - the things to join separator - what seperates items description_mode - what mode to use for description...
36,652
def JacobianSpace(Slist, thetalist): """Computes the space Jacobian for an open chain robot :param Slist: The joint screw axes in the space frame when the manipulator is at the home position, in the format of a matrix with axes as the columns :param thetalist: A list of j...
36,653
async def delete_bank(org_id: str, bank_id:str, user: users_schemas.User = Depends(is_authenticated), db:Session = Depends(get_db)): """delete a given bank of id bank_id. Args: bank_id: a unique identifier of the bank object. user: authenticates that the user is a logged ...
36,654
def label_encode( df: pd.DataFrame, column_names: Union[str, Iterable[str], Any] ) -> pd.DataFrame: """ Convert labels into numerical data. This method will create a new column with the string "_enc" appended after the original column's name. Consider this to be syntactic sugar. This method be...
36,655
def chainable(func): """ If no output_path is specified, generate an intermediate file and pass it to the function. Add the path of the intermediate file to the resulting Video.intermediate_files list before returning it. If an output_path is specified, use it and then delete the intermediate files. ...
36,656
def get_server_now_with_delta_str(timedelta): """Get the server now date string with delta""" server_now_with_delta = get_server_now_with_delta(timedelta) result = server_now_with_delta.strftime(DATE_FORMAT_NAMEX_SEARCH) return result
36,657
def GetPrimaryKeyFromURI(uri): """ example: GetPrimaryKeyFromURI(u'mujin:/\u691c\u8a3c\u52d5\u4f5c1_121122.mujin.dae') returns u'%E6%A4%9C%E8%A8%BC%E5%8B%95%E4%BD%9C1_121122' """ return uriutils.GetPrimaryKeyFromURI(uri, fragmentSeparator=uriutils.FRAGMENT_SEPARATOR_AT, primaryKeySeparator=...
36,658
def normalize(score, alpha=15): """ Normalize the score to be between -1 and 1 using an alpha that approximates the max expected value """ norm_score = score/math.sqrt((score*score) + alpha) if norm_score < -1.0: return -1.0 elif norm_score > 1.0: return 1.0 else: return norm_score
36,659
def get_timestamp(request): """ hhs_oauth_server.request_logging.RequestTimeLoggingMiddleware adds request._logging_start_dt we grab it or set a timestamp and return it. """ if not hasattr(request, '_logging_start_dt'): return datetime.now(pytz.utc).isoformat() else: ...
36,660
def human_size(bytes: int | float, units: Optional[List[str]] = None) -> str: """ Convert bytes into a more human-friendly format :param bytes: int Number of bytes :param units: Optional[List[str]] units used :return: str Return size in human friendly format: <number> <size_...
36,661
def ray_casting_2d(p: Point, poly: Poly) -> bool: """Implements ray-casting algorithm to check if a point p is inside a (closed) polygon poly""" intersections = [int(rayintersectseg(p, edge)) for edge in poly.edges] return _odd(sum(intersections))
36,662
def average_price(offers): """Returns the average price of a set of items. The first item is ignored as this is hopefully underpriced. The last item is ignored as it is often greatly overpriced. IMPORTANT: It is important to only trade items with are represented on the market in great numbers. ...
36,663
def repair(train_rate=0.8, test_rate=0.1, dev_rate=0.1): """ 生成数据集dev.json test.json train.json, 生成labels Returns: """ examples = static() dir_path = "../dataset/repair" label_file = os.path.join(dir_path, "labels.json") dev_file = os.path.join(dir_path, "dev.json") test_file = os.pa...
36,664
def update_items(apps, schema_editor): """ Add card's items according to card's tags. """ Card = apps.get_model('cards', 'Card') Item = apps.get_model('confs', 'Item') for x in range(400): for card in Card.objects.filter(tags__name=str(x)): card.items.add(Item.objects.get(nu...
36,665
def main(argv=sys.argv): """Main point of Entry""" return pbparser_runner( argv=argv[1:], parser=_get_parser(), args_runner_func=_args_runner, contract_runner_func=_resolved_tool_contract_runner, alog=log, setup_log_func=setup_log)
36,666
def get_train_data(): """get all the train data from some paths Returns: X: Input data Y_: Compare data """ TrainExamples = [8, 9, 10, 11, 12, 14] # from path set_22 to set_35 path = PATH_SIMPLE + str(5) + '/' X, Y_ = generate(path, isNormalize=True) maxvalue = (get_ima...
36,667
def effective_dimension_vector(emb, normalize=False, is_cov=False): """Effective dimensionality of a set of points in space. Effection dimensionality is the number of orthogonal dimensions needed to capture the overall correlational structure of data. See Del Giudice, M. (2020). Effective Dimensionality: A...
36,668
def getProductMinInventory(db, productID): """ Gives back the minimum inventory for a given product :param db: database pointer :param productID: int :return: int """ # make the query and receive a single tuple (first() allows us to do this) result = db.session.query(Product).filter(Prod...
36,669
def read_config6(section, option, filename='', verbosity=None): #format result: {aaa:[bbb, ccc], ddd:[eee, fff], ggg:[hhh, qqq], xxx:[yyy:zzz]} """ option: section, option, filename='' format result: {aaa:bbb, ccc:ddd, eee:fff, ggg:hhh, qqq:xxx, yyy:zzz} """ filename = get_...
36,670
def setup_module(): """ Test setup. """ env['dir'] = mkdtemp() env['filename'] = os.path.join(env['dir'], 'test.pkl') print(80 * '_') print('setup numpy_pickle') print(80 * '_')
36,671
def bboxes_iou(boxes1, boxes2): """ boxes: [xmin, ymin, xmax, ymax] format coordinates. """ boxes1 = np.array(boxes1) boxes2 = np.array(boxes2) boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1]) boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., ...
36,672
def zip_all_downloadables(getZipped_n_clicks, value, session_data): """Create a downloadable zip of USER selected set of output files. Args: getZipped_n_clicks: int value: str session_data: Dash.dcc.Store(type='session') Returns: html.Div([]): Dash HTML div componen...
36,673
def predict_all_task(trained_model_path, config, subject_specific): """Predict. Parameters ---------- model_path : str Description of parameter `model_path`. config : dict A dictionary of hyper-parameters used in the network. Returns ------- float Predicted labe...
36,674
def hjorth(X): """ Compute Hjorth mobility and complexity of a time series. Notes ----- To speed up, it is recommended to compute D before calling this function because D may also be used by other functions whereas computing it here again will slow down. Parameters ---------- X : a...
36,675
def check_and_set_owner(func): """ Decorator that applies to functions expecting the "owner" name as a second argument. It will check if a user exists with this name and if so add to the request instance a member variable called owner_user pointing to the User instance corresponding to the owner. If the...
36,676
def schedule(self: Client) -> ScheduleProxy: """Delegates to a :py:class:`mcipc.rcon.je.commands.schedule.ScheduleProxy` """ return ScheduleProxy(self, 'schedule')
36,677
def check_permission(permission): """Returns true if the user has the given permission.""" if 'permissions' not in flask.session: return False # Admins always have access to everything. if Permissions.ADMIN in flask.session['permissions']: return True # Otherwise check if the permission is present in ...
36,678
def get_current_max_change_version(context, start_after, school_year: int, use_change_queries: bool): """ If job is configured to use change queries, get the newest change version number from the target Ed-Fi API. Upload data to data lake. """ if use_change_queries: stats = context.insta...
36,679
def number_of_jobs_in_queue(): """ This functions returns the number of jobs in queue for a given user. """ # Initialize # user_name = get_username() process = subprocess.check_output(["squeue", "-u", user_name]) return len([line for line in process.split("\n") if user_name in line])
36,680
async def disable_email( current_user: User = Depends(validate_request), email: EmailStr = Query(None), db: AsyncIOMotorClient = Depends(get_database) ): """Disable as active user """ if email == current_user.email: # cannot disable current user raise HTTPException( ...
36,681
def test_natural_noise_ascend(): """ Feature: Test natural noise. Description: Add natural noise to an. Expectation: success. """ context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") image = np.random.random((32, 32, 3)) trans = NaturalNoise(ratio=0.0001, k_x_range=(1, 30...
36,682
def plot_screentime_over_time(names, show_name, screen_times_by_video_id): """ Plot a scatterplot of screentime over time names is a list of names or a single name screen_times_by_video_id is a dict of video_id to screen_time in seconds or a list of such dicts """ # TODO: fix xlim on ti...
36,683
def Energy_value (x): """ Energy of an input signal """ y = np.sum(x**2) return y
36,684
def test2(): """ test momentum and mass conservation in 3d """ import pylab as pl r,p,rho,u,r_s,p_s,rho_s,u_s,shock_speed = \ sedov(t=0.05, E0=5.0, rho0=5.0, g=5.0/3.0,n=10000) dt = 1e-5 r2,p2,rho2,u2 = sedov(t=0.05+dt, E0=5.0, rho0=5.0, g=5.0/3.0, n=9000)[:4] # align the results f...
36,685
def get_int(): """Read a line of text from standard input and return the equivalent int.""" while True: s = get_string(); if s is None: return None if re.search(r"^[+-]?\d+$", s): try: i = int(s, 10) if type(i) is int: # could becom...
36,686
def create_save_featvec_homogenous_time(yourpath, times, intensities, filelabel, version=0, save=True): """Produces the feature vectors for each light curve and saves them all into a single fits file. requires all light curves on the same time axis parameters: * yourpath = folder you want the file s...
36,687
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Eaton xComfort Bridge from a config entry.""" ip_address = entry.data.get(CONF_IP_ADDRESS) auth_key = entry.data.get("authkey") bridge = Bridge(ip_address, auth_key) # bridge.logger = lambda x: _LOGGER.warning(x) #...
36,688
def get_reviews(source): """ Find and return all review's data """ reviews = source.xpath("//div[@class='revz_container']") for review in reviews: try: data = { 'description': review.xpath(".//span[@itemprop='description']//text()" )[0...
36,689
def _cpu_string(platform_type, settings): """Generates a <platform>_<arch> string for the current target based on the given parameters.""" if platform_type == "ios": ios_cpus = settings["//command_line_option:ios_multi_cpus"] if ios_cpus: return "ios_{}".format(ios_cpus[0]) c...
36,690
def Check2DBounds(atomMatch,mol,pcophore): """ checks to see if a particular mapping of features onto a molecule satisfies a pharmacophore's 2D restrictions >>> activeFeats = [ChemicalFeatures.FreeChemicalFeature('Acceptor', Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Dono...
36,691
def get_sdk_dir(fips_dir) : """return the platform-specific SDK dir""" return util.get_workspace_dir(fips_dir) + '/fips-sdks/' + util.get_host_platform()
36,692
def suggested_params(**kwargs: Any) -> transaction.SuggestedParams: """Return the suggested params from the algod client. Set the provided attributes in ``kwargs`` in the suggested parameters. """ params = _algod_client().suggested_params() for key, value in kwargs.items(): setattr(params,...
36,693
def norm_rl(df): """ Normalizes read length dependent features """ rl_feat = ["US_r", "US_a", "DS_a", "DS_r", "UXO_r", "UXO_a", "DXO_r", "DXO_a", "UMO_r", "UMO_a", "DMO_r", "DMO_a", "MO_r", "MO_a", "XO_r", "XO_a"] rl = df['MO_r'].max() df[rl_feat] = df[rl_feat]/rl return df
36,694
def sendRequest(self, channel, params=None): """发送请求""" # 生成请求 d = {} d['event'] = 'addChannel' d['channel'] = channel # 如果有参数,在参数字典中加上api_key和签名字段 if params is not None: params['api_key'] = apiKey params['sign'] = buildMySign(params, secreteKey) d['parameters'] = pa...
36,695
def altCase(text: str): """ Returns an Alternate Casing of the Text """ return "".join( [ words.upper() if index % 2 else words.lower() for index, words in enumerate(text) ] )
36,696
def makeObjectArray(elem, graph, num, tag=sobject_array): """ Create an object array of num objects based upon elem, which becomes the first child of the new object array This function also can create a delay when passed a different tag """ p = elem.getparent() objarray = etree.Element(etree...
36,697
def test_md019_bad_multiple_spacing(): """ Test to make sure this rule does not trigger with a document that contains Atx Headings with multiple spaces before text. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/rules/md019/multiple_...
36,698
def convert_escaped_utf8_literal( text: str ) -> str: """Convert any escaped UTF-8 hexadecimal character bytes into the proper string characters(s). This function will convert a string, that may contain escaped UTF-8 literal hexadecimal bytes, into a string with the proper characters. Args...
36,699