content
stringlengths
22
815k
id
int64
0
4.91M
def write_hdfs_site(ctx): """ Add required entries to conf/hdfs-site.xml """ hdfs_site_file = "{tdir}/apache_hadoop/conf/hdfs-site.xml".format( tdir=teuthology.get_testdir(ctx)) hadoop_nodes = ctx.cluster.only(teuthology.is_type('hadoop')) for remote in hadoop_nodes.remotes: ...
3,800
def rotate( img: torch.Tensor, boxes: np.ndarray, angle: float, ) -> Tuple[torch.Tensor, np.ndarray]: """Rotate image around the center, interpolation=NEAREST, pad with 0 (black) Args: img: image to rotate boxes: array of boxes to rotate as well angle: angle in degrees. +: c...
3,801
def population(state_data): """ Sums state populations """ population = 1 sum_ = 0 num_states = len(state_data) for state in range(0,num_states): sum_ = sum_ + state_data[state][population] print("The total population of this list of states is",sum_) print("There are",num_st...
3,802
def _letterbox_image(img, w_in, h_in): """To get the image in boxed format.""" imc, imh, imw = img.shape if (w_in / imw) < (h_in / imh): new_w = w_in new_h = imh * w_in // imw else: new_h = h_in new_w = imw * h_in // imh resized = _resize_image(img, new_w, new_h) ...
3,803
def step_get_token(context, user_key): """Start to hit get-token api.""" use_user_key = parse_token_clause(user_key) perform_get_token_call(context, use_user_key)
3,804
def test_value(): """Check if values are set okay """ piezo = jena.NV40(port) for setpoint in [0,100,200,300] piezo.set_position(setpoint) achieved = piezo.get_position() assert(np.isclose(achieved, setpoint,rtol=0,atol=1))
3,805
def assert_not_in(a, b, msg=None): """ Assert that the first argument is not in second one. """ if a not in b: return assert False, str(a) + ' is in ' + str(b) + _get_msg(msg)
3,806
def to_RRDB(**kwargs): """ Residual in Residual Dense Blocks """ kwargs["n_filer"] = (" ",) * len(kwargs["n_filer"]) # remove x label return _Box(fill="{rgb:white,1;black,3}", **kwargs)
3,807
def continuous_agg_dict_features(n, n_feats, ks): """Listdict-like continuous aggregated features. Parameters ---------- n: int the number of the elements to create their features. n_feats: int the number of features. ks: int the number of perturbations. Returns ...
3,808
async def invite(ctx: commands.Context): """Gets a link to invite Lopez.""" perms = discord.Permissions.none() perms.view_audit_log = True perms.manage_roles = True perms.manage_channels = True perms.create_instant_invite = True perms.send_messages = True perms.manage_messages = True ...
3,809
def mk_table_of_point_for_point_performance(RFR_dict=None, df=None, testset='Test set (strat. 20%)', inc_ensemble=False, var2use='RFR(Ensemble)', ...
3,810
def counts_matrix(x, quantiles): """Count samples in strata Get eta, the number of samples in ``x`` binned by ``quantiles`` in each variable, for continuous variables. The shape of eta is the same as the shape of ``x``, and the shape of ``quantiles`` should be (``numpy.shape(x)[0] + 1``, ``numpy.sh...
3,811
def get_xml_string(stream_pointer): """ This function checks for valid xml in a stream and skips bytes until it hits something that looks like xml. In general, this 'skipping' should never be used, as we expect to see well-formed XML from the server. stream_pointer: input stream returns: st...
3,812
def score_estimator(estimator, df_test): """Score an estimator on the test set.""" y_pred = estimator.predict(df_test) print( "MSE: %.3f" % mean_squared_error( df_test["Frequency"], y_pred, sample_weight=df_test["Exposure"] ) ) print( "MAE: %.3f" ...
3,813
def parse_header(header): """Parse header div for pub. title, authors journal, year, and doi.""" # TITLE title = header.find('h1').text.strip() # JOURNAL journal = header.find('button').text.strip() # PUBLICATION YEAR pub_date = header.find('span', attrs={'class': "cit"}).text year = r...
3,814
def parse_arguments(): """Parse user args There are three subparsers, one for each mode: full, visit, and moab. Full mode runs both the visit and moab steps. Each parser should have a full help message, simplified usage statement, and examples. """ mode_examples = """ To view full options for e...
3,815
def put_this_into_the_db(query, param): """put this value into the database see : find_by_exactly_this_query() Arguments: query {[type]} -- [description] param {[type]} -- [description] Returns: bool -- [description] """ # Connect to the database connection = pymysql.con...
3,816
def _gen_new_aux_page(label: str, is_title: bool) -> str: """Generate latex for auxillary pages""" page = [] if is_title: page.append("\\thispagestyle{empty}") page.append("\\begin{center}") page.append("\t\\vfil") page.append("\t\\vspace*{0.4\\textheight}\n") page.append("\t\\Hug...
3,817
def expand_matrix_col(matrix, max_size, actual_size): """ add columns of zeros to the right of the matrix """ return np.append(matrix, np.zeros((matrix.shape[0], max_size - actual_size), dtype=matrix.dtype), axis=1)
3,818
def vms_list(access_token, config_id): """List FlexVM Virtual Machines""" logging.info("--> List FlexVM Virtual Machines...") uri = FLEXVM_API_BASE_URI + "vms/list" headers = COMMON_HEADERS.copy() headers["Authorization"] = f"Bearer {access_token}" body = {"configId": config_id} results =...
3,819
def add(name, value): """ Add a value to an ipset. """ futils.check_call(["ipset", "add", name, value, "-exist"])
3,820
def formulate_hvdc_flow(problem: LpProblem, angles, Pinj, rates, active, Pt, control_mode, dispatchable, r, F, T, logger: Logger = Logger(), inf=999999): """ :param problem: :param nc: :param angles: :param Pinj: :param t: :param logger: :param inf: :return: ...
3,821
def method_mock(cls, method_name, request): """ Return a mock for method *method_name* on *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, method_name) request.addfinalizer(_patch.stop) return _patch.start()
3,822
def get_eps_float32(): """Return the epsilon value for a 32 bit float. Returns ------- _ : np.float32 Epsilon value. """ return np.finfo(np.float32).eps
3,823
def distributions_to_params(nest): """Convert distributions to its parameters, keep Tensors unchanged. Only returns parameters that have tf.Tensor values. Args: nest (nested Distribution and Tensor): Each Distribution will be converted to dictionary of its Tensor parameters. Return...
3,824
def _return_xarray_system_ids(xarrs: dict): """ Return the system ids for the given xarray object Parameters ---------- xarrs Dataset or DataArray that we want the sectors from Returns ------- list system identifiers as string within a list """ return list(xarr...
3,825
def sub(a, b): """Subtracts b from a and stores the result in a.""" return "{b} {a} ?+1\n".format(a=a, b=b)
3,826
def metrics_cluster(models = None, ytrain = None, ytest = None, testlabels = None, trainlabels = None, Xtrain = None, Xtest = None): """ Calculates Metrics such as accu...
3,827
def prune_cloud_borders (numpy_cloud, clearance=1.2 ): """Delete points at the clouds' borders in range of distance, restricting the x-y plane (ground)""" # get min/max of cloud cloud_max_x = np.max (numpy_cloud[:, 0]) cloud_min_x = np.min (numpy_cloud[:, 0]) cloud_max_y = np.max (numpy_cloud...
3,828
def factory(name, Base, Deriveds): """Find the base or derived class by registered name. Parameters ---------- Base: class Start the lookup here. Deriveds: iterable of (name, class) A list of derived classes with their names. Returns ------- class """ Derived =...
3,829
def test_nsxt_ip_blocks_state_module(nsxt_config, salt_call_cli): """ Tests NSX-T IP Blocks State module to verify the present and absent state in NSX-T Manager """ hostname, username, password = _get_server_info(nsxt_config) display_name = "IP_Block_Salt_State_FT" description = "Created fr...
3,830
def ex12(): """ Collect principal, rate, and term from the user Print the principal plus interest """ while True: try: principal = decimal.Decimal(input('Enter the principal: ')) break except decimal.InvalidOperation: print('Enter a valid principal') ...
3,831
def root_sum_square(values, ax_val, index, Nper, is_aper, is_phys, unit): """Returns the root sum square (arithmetic or integral) of values along given axis Parameters ---------- values: ndarray array to derivate ax_val: ndarray axis values index: int index of axis along...
3,832
def comment_on_tweet(): """" http://127.0.0.1:5000/user/comment_on_tweet body = { "id": "5da61dbed78b3b2b10a53582", "comments" : { "commenter" : "testuser2@myhunter.cuny.edu", "comment" : "comments against tweet : 7" } ...
3,833
def generate_git_api_header(event, sig): """ Create header for GitHub API Request, based on header information from https://developer.github.com/webhooks/. :param event: Name of the event type that triggered the delivery. :param sig: The HMAC hex digest of the response body. The HMAC hex digest is gene...
3,834
def var_gaussian(r, level=5, modified=False): """ Returns the Parametric Gauusian VaR of a Series or DataFrame If "modified" is True, then the modified VaR is returned, using the Cornish-Fisher modification """ # compute the Z score assuming it was Gaussian z = norm.ppf(level/100) if mod...
3,835
def lnglat_to_tile(lon, lat, zoom): """Get the tile which contains longitude and latitude. :param lon: longitude :param lat: latitude :param zoom: zoom level :return: tile tuple """ lon, lat = truncate(lon, lat) n = 1 << zoom tx = int((lon + 180.0) / 360.0 * n) ty = int((1.0 - m...
3,836
def group_obs_annotation( adata: AnnData, gdata: AnnData, *, groups: Union[str, ut.Vector], name: str, formatter: Optional[Callable[[Any], Any]] = None, method: str = "majority", min_value_fraction: float = 0.5, conflict: Optional[Any] = None, inplace: bool = True, ) -> Optional[...
3,837
def test_python_module_ctia_positive_attack_pattern( module_headers, module_tool_client): """Perform testing for attack pattern entity of custom threat intelligence python module ID: CCTRI-160-86d8f8ef-fbf4-4bf4-88c2-a57f4fe6b866 Steps: 1. Send POST request to create new attack patter...
3,838
def load_pipeline(path, tunables=True, defaults=True): """Load a d3m json or yaml pipeline.""" if not os.path.exists(path): base_path = os.path.abspath(os.path.dirname(__file__)) path = os.path.join('templates', path) path = os.path.join(base_path, path) if not os.path.isfile(path...
3,839
def generate_languages(request): """ Returns the languages list. """ validate_api_secret_key(request.data.get('app_key')) request_serializer = GenerateLanguagesRequest(data=request.data) if request_serializer.is_valid(): get_object_or_404(TheUser, auth_token=request.data.get('user_token...
3,840
def all_stocks(): """ #查询当前所有正常上市交易的股票列表 :return: """ data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date') return data["symbol"].values
3,841
def route_transfer(host,route): """ Save a certain route as static HTML file to production """ path = root # default path text = urllib2.urlopen(host+route).read() # grab html codes from route # format html code and fix css/js/anchor for static file soup = BeautifulSoup(text).prettify() anchors...
3,842
def getBotHash(userID, isCompile=False): """Gets the checksum of a user's bot's zipped source code""" params = {"apiKey": API_KEY, "userID": userID} if isCompile: params["compile"] = 1 result = requests.get(MANAGER_URL+"botHash", params=params) print("Getting bot hash:") print(resu...
3,843
def next_remote_buffer_uuid(number=1): """Return the next uuid of a remote buffer.""" global remote_buffer_counter if number == 1: ret = remote_buffer_counter else: ret = np.arange(remote_buffer_counter, remote_buffer_counter + number) remote_buffer_counter = (remote_buffer_counter +...
3,844
def ball_collide(i): """ This function will handle the ball collide interaction between brick and paddle :param i: (int) The index of the ball to interact :return: (Bool) If this ball collide with brick or paddle """ global score collide = False for j in range(2): for k ...
3,845
def gen_sparse_graph(destination_folder: Path, vertices_number: int, edge_probability: float) -> Path: """ Generates sparse graph :param destination_folder: directory to save the graph :type destination_folder: Path :param vertices_number: number of vertice...
3,846
def multivariate_hierarchical_barycentric_lagrange_interpolation( x, abscissa_1d, barycentric_weights_1d, fn_vals, active_dims, active_abscissa_indices_1d): """ Parameters ---------- x : np.ndarray (num_vars, num_samples) The samples at which to ev...
3,847
def deaths(path): """Monthly Deaths from Lung Diseases in the UK A time series giving the monthly deaths from bronchitis, emphysema and asthma in the UK, 1974-1979, both sexes (`deaths`), P. J. Diggle (1990) *Time Series: A Biostatistical Introduction.* Oxford, table A.3 Args: path: str. Path ...
3,848
def test_random_affine_exception_negative_degrees(): """ Test RandomAffine: input degrees in negative, expected to raise ValueError """ logger.info("test_random_affine_exception_negative_degrees") try: _ = py_vision.RandomAffine(degrees=-15) except ValueError as e: logger.info("G...
3,849
def read_csv(path): """Reads the CSV file at the indicated path and returns a list of rows. Parameters: path (str): The path to a CSV file. Returns: list[row]: A list of rows. Each row is a list of strings and numbers. """ with open(path, 'rb') as f: return decode_csv(f.re...
3,850
def obj_mask(im): """Computes the mask for an image with transparent background Keyword arguments: im -- the input image (must be RGBA) """ A = im.split()[-1] T = ImageOps.invert(A) return Image.merge("RGBA", (T, T, T, A))
3,851
def main(argv: t.List[str] = sys.argv): """Wrapper for pgsql-dump.bash script. :param argv: Command line arguments, second one needs to be the uri to a configuration file. :raises sys.SystemExit: """ if len(argv) < 2: usage_message( argv, additional_params='[ARG1, AR...
3,852
def rnn(rnn_type, inputs, length, hidden_size, layer_num=1, dropout_keep_prob=None, concat=True): """ Implements (Bi-)LSTM, (Bi-)GRU and (Bi-)RNN 在这个module中,rnn是主要的接口,所以把rnn放在上面 Args: rnn_type: the type of rnn, such as lstm inputs: padded inputs into rnn, usually a d*p or l*p mat...
3,853
def find_expired(bucket_items, now): """ If there are no expired items in the bucket returns empty list >>> bucket_items = [('k1', 1), ('k2', 2), ('k3', 3)] >>> find_expired(bucket_items, 0) [] >>> bucket_items [('k1', 1), ('k2', 2), ('k3', 3)] Expired items are returned in the lis...
3,854
def find_sprites(image=None, background_color=None): """ Find sprites @image: MUST be an Image object @background_color: optinal, whether tuple (RGB/ RGBA) or int (grayscale) """ def find_sprites_corners(sprite, label_map, numpy_array): columns = set() rows = set() for row_...
3,855
def get_java_package(path): """Extract the java package from path""" segments = path.split("/") # Find different root start indecies based on potential java roots java_root_start_indecies = [_find(segments, root) for root in ["java", "javatests"]] # Choose the root that starts earliest start_...
3,856
def generate_seekr2_model_and_filetree(model_input, force_overwrite): """ Using the Model_input from the user, prepare the Model object and the filetree. Then prepare all building files for each anchor and serialize the Model to XML. """ model = common_prepare.model_factory(model_input) comm...
3,857
def get_plugin(): """Return the filter.""" return TextFilter
3,858
def caltech256(root): """Caltech256 dataset from http://www.vision.caltech.edu/Image_Datasets/Caltech256 Pictures of objects belonging to 256 categories. About 80 to 800 images per category. Collected in September 2003 by Fei-Fei Li, Marco Andreetto, and Marc 'Aurelio Ranzato. The size ...
3,859
def make_highlight(sel, *, highlight_kwargs): """ Create a highlight for a `Selection`. This is a single-dispatch function; implementations for various artist classes follow. """ warnings.warn( f"Highlight support for {type(sel.artist).__name__} is missing")
3,860
def draw__mask_with_edge(cv2_image: np.ndarray, edge_size: int = 10) -> np.ndarray: """ From a color image, get a black white image each instance separated by a border. 1. Change a color image to black white image. 2. Get edge image from `cv2_image`, then invert it to separate instance by a border. ...
3,861
def test_stacer_binary_exists(host): """ Tests if stacer binary file exists. """ assert host.file(PACKAGE_BINARY).exists
3,862
def test_list_id_length_nistxml_sv_iv_list_id_length_1_5(mode, save_output, output_format): """ Type list/ID is restricted by facet length with value 5. """ assert_bindings( schema="nistData/list/ID/Schema+Instance/NISTSchema-SV-IV-list-ID-length-1.xsd", instance="nistData/list/ID/Schema...
3,863
def cba_post_process(output_dir, curtailment_tolerance=0.0001): """Perform post-processing of CBA tables.""" add_curtailment_columns(output_dir, curtailment_tolerance)
3,864
def get_functions(pdb_file): """Get the offset for the functions we are interested in""" methods = {'ssl3_new': 0, 'ssl3_free': 0, 'ssl3_connect': 0, 'ssl3_read_app_data': 0, 'ssl3_write_app_data': 0} try: # Do this the hard way to avoid ha...
3,865
def empty_iterable() -> typing.Iterable: """ Return an empty iterable, i.e., an empty list. :return: an iterable :Example: >>> from flpy.iterators import empty_iterable >>> empty_iterable() [] """ return list()
3,866
def create_namespace(ctx, config): """ Updates kubernetes deployment to use specified version """ settings_dict = get_settings() config_dict = settings_dict['configs'][config] set_context(ctx, config) ctx.run('kubectl create namespace {namespace}' .format(namespace=config_dict['...
3,867
def nearest_pow_2(x): """ Finds the nearest integer that is a power of 2. In contrast to :func:`next_pow_2` also searches for numbers smaller than the input and returns them if they are closer than the next bigger power of 2. """ a = M.pow(2, M.ceil(M.log(x, 2))) b = M.pow(2, M.floor(M.l...
3,868
def timestamp_preprocess(ds, column, name): """This function takes the timestamp in the dataset and create from it features according to the settings above Args: ds ([dataframe]): dataset column ([integer]): column index name ([string]): column name Returns: [dataframe]: dat...
3,869
def test_001_echo(expect): """ This case is about receiving parameters in URLs. URL example: http://localhost:8888/echo?msg=hello """ response = requests.get(URL + '/echo', params={'msg': expect}) response.raise_for_status() assert expect == response.content.decode()
3,870
def make_taubin_loss_function(x, y): """closure around taubin_loss_function to make surviving pixel positions availaboe inside. x, y: positions of pixels surviving the cleaning should not be quantities """ def taubin_loss_function(xc, yc, r): """taubin fit formula reference...
3,871
def init_rf_estimator(): """ Instantiate a Random forest estimator with the optimized hyper-parameters. :return: The RandomForest estimator instance. """ rf = RandomForestClassifier( criterion=RF_CRIT, min_samples_leaf=RF_MIN_SAMPLES_LEAF, max_features='auto', n_estimators=RF_N_ESTS, n_jobs=-1) return r...
3,872
def dict_filter(d, exclude=()): """ Exclude specified keys from a nested dict """ def fix_key(k): return str(k) if isinstance(k, builtin_str) else k if isinstance(d, list): return [dict_filter(e, exclude) for e in d] if isinstance(d, dict): items = ((fix_key(k), v) for...
3,873
async def mongoengine_multiple_objects_exception_handler(request, exc): """ Error handler for MultipleObjectsReturned. Logs the MultipleObjectsReturned error detected and returns the appropriate message and details of the error. """ logger.exception(exc) return JSONResponse( Respo...
3,874
def _get_sample_times(*traces, **kwargs): """Get sample times for all the traces.""" # Set the time boundaries for the DataFrame. max_stop_time = max( [trace.stop_time() for trace in traces if isinstance(trace, Trace)] ) stop_time = kwargs.pop("stop_time", max_stop_time) min_start_time ...
3,875
def get_weak_model(op, diff_type, nonzero2nonzero_weight, zero2zero_weight=0, zero2nonzero_weight=math.inf, nonzero2zero_weight=math.inf, precision=0): """Return the weak model of the given bit-vector operation ``op``. Given the `Operation` ``op``, return the `WeakModel` of ``op`` for th...
3,876
def get_temp(): """ 読み込んだ温度を返す """ return sensor.t
3,877
def load_clean_yield_data(yield_data_filepath): """ Cleans the yield data by making sure any Nan values in the columns we care about are removed """ important_columns = ["Year", "State ANSI", "County ANSI", "Value"] yield_data = pd.read_csv(yield_data_filepath).dropna( subset=important_c...
3,878
async def test_temperature_conversion( hass, enable_custom_integrations, unit_system, native_unit, state_unit, native_value, state_value, ): """Test temperature conversion.""" hass.config.units = unit_system platform = getattr(hass.components, "test.sensor") platform.init(emp...
3,879
def _render_pygame_frame( surface: pygame.Surface, screen: pygame.Surface, orientation: task_pb2.AdbCall.Rotate.Orientation, timestep: dm_env.TimeStep) -> None: """Displays latest observation on pygame surface.""" frame = timestep.observation['pixels'][:, :, :3] # (H x W x C) (RGB) frame = utils...
3,880
def create_element_mapping(repnames_bedfile): """Create a mapping of the element names to their classes and families""" elem_key = defaultdict(lambda : defaultdict(str)) with open(repnames_bedfile, "r") as bed: for line in bed: l = line.strip().split("\t") name = l[3] ...
3,881
def _get_CRABI_iterators(captcha_dataframe, train_indices, validation_indices, batch_size, image_height, image_width, character_length, catego...
3,882
def download_sql_dump(language, file, dump="latest", target_dir="."): """Downloads and decompresses a Wikipedia SQL dump. Args: language: Wikipedia name (language code). file: File name. dump: Dump version. target_dir: Target directory. """ with urlopen(_get_url(languag...
3,883
def run(request, context): """Creates a template. Args: request (orchestrate_pb2.CreateTemplateRequest): Request payload. context: Context. Returns: A orchestrate_pb2.CreateTemplate with the status of the request. """ template = request.template print('Orchestrate.CreateTemplate name={name} pr...
3,884
def fit_2dgaussian(data, error=None, mask=None): """ Fit a 2D Gaussian to a 2D image. Parameters ---------- data : array_like The 2D array of the image. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. mask : array_like (bool), optiona...
3,885
def generate_tf_records(c): """Convert imagenet images to tfrecords """ print("Preparing tf records") if ( _number_img_files_in("/data/train") == 0 or _number_img_files_in("/data/validation") == 0 ): raise Exception( "Not enough files found please make sure you ha...
3,886
def list_dir_files(path: str, suffix: str = "") -> List[str]: """ Lists all files (and only files) in a directory, or return [path] if path is a file itself. :param path: Directory or a file :param suffix: Optional suffix to match (case insensitive). Default is none. :return: list of absolute paths ...
3,887
def map_role_packages(package_map): """Add and sort packages belonging to a role to the role_packages dict. :type package_map: ``dict`` """ for k, v in ROLE_PACKAGES.items(): role_pkgs = package_map['role_packages'][k] = list() for pkg_list in v.values(): role_pkgs.extend(pk...
3,888
def to_roman(number): """ Converts an arabic number within range from 1 to 4999 to the corresponding roman number. Returns None on error conditions. """ try: return roman.toRoman(number) except (roman.NotIntegerError, roman.OutOfRangeError): return None
3,889
def GDAL_like(filename, fileout=""): """ GDAL_like """ BSx, BSy, Mb, Nb, M, N = 0,0, 0,0, 0,0 dataset1 = gdal.Open(filename, gdal.GA_ReadOnly) dataset2 = None if dataset1: band1 = dataset1.GetRasterBand(1) M, N = int(dataset1.RasterYSize), int(dataset1.RasterXSize) B ...
3,890
def take_attendance(methodcnt): """global setup_bool if (setup_bool == False or methodcnt == False): print ("in if statement") setup_bool = True else:""" print ("checking in - F.R.") react_with_sound(attendance_final) client.CheckIn() return 2
3,891
def feature_selection(data, features): """ Choose which features to use for training. :param data: preprocessed dataset :param features: list of features to use :return: data with selected features """ return data[features]
3,892
def randomstr(ctx, nbytes=''): """ generates a URL-safe text string, containing nbytes random bytes sets it to ctx.data """ if nbytes: nbytes = int(nbytes) ctx.data = secrets.token_urlsafe(nbytes) else: ctx.data = secrets.token_urlsafe()
3,893
def parse_docstring(docstring, line=0, filename='<string>', logger=None, format_name=None, options=None): # type: (str, int, Any, Optional[logging.Logger], Optional[str], Any) -> Tuple[OrderedDict[str, Arg], Optional[Arg]] """ Parse the passed docstring. The OrderedDict holding pars...
3,894
def srCyrillicToLatin(cyrillic_text): """ Return a conversion of the given string from cyrillic to latin, using 'digraph' letters (this means that e.g. "nj" is encoded as one character). Unknown letters remain unchanged. CAVEAT: this will ONLY change letters from the cyrillic subset of Unicode. For in...
3,895
def from_phone(func=None): """来自手机的消息(给自己发的) FriendMsg""" if func is None: return from_phone async def inner(ctx): assert isinstance(ctx, FriendMsg) if ctx.MsgType == MsgTypes.PhoneMsg: return await func(ctx) return None return inner
3,896
def fit_and_validate_readout(data: Iterator[Tuple[Tensor, Tensor]], regularization_constants: List[float], get_validation_error: Callable[[Tuple[Tensor, Tensor]], float], verbose: bool = False) -> Tuple[Tensor, Tensor]: """ Ridge regression for big data,...
3,897
def summarize_df(df: DataFrame) -> None: """Show properties of a DataFrame.""" display( df.dtypes.rename("dtype") .to_frame() .merge( df.isna().sum().rename("num_missing").to_frame(), left_index=True, right_index=True, how="left", )...
3,898
def create_scan_message(): """Creates a dummy message of type v3.asset.file to be used by the agent for testing purposes. The files used is the EICAR Anti-Virus Test File. """ file_content = (pathlib.Path(__file__).parents[0] / 'files/malicious_dummy.com').read_bytes() selector = 'v3.asset.file' ...
3,899