content
stringlengths
22
815k
id
int64
0
4.91M
def run(): """Default Run Method""" return problem51(8)
5,325,800
def calc_c(e, a, b, u=1): # Check units """ calculate the z components of 4 partial waves in medium e: dielectric tensor a,b: components of wavevector in direction of x and y direction return a list containting 4 roots for the z components of the partial waves """ # assign names x = ...
5,325,801
def printWithReplace(fileDict, opt_searchStr = '', opt_replaceStr = ''): """ Prints the dictionary. @param fileDict: The file dictionary @type fileDict: dict @param fileDict: The optional search string. @type opt_searchStr: string @param fileDict: The optional replace string. @ty...
5,325,802
def _jax_decode( compressed_message: ndarray, tail_limit: int, message_len: int, message_shape: Sequence[int], codec: CrayCodec, cdf_state: Sequence[ndarray], ) -> Tuple[Tuple[ndarray, int], ndarray, Sequence[ndarray]]: """ JAX rANS decoding function. At a high level, this function ...
5,325,803
def test_extract_features(waveform, flat_waveform): """Test the extract features function with and without statistics from the all_features.yaml example config. Args: waveform (Waveform): The waveform PyTest fixture returning an example audio file. flat_waveform (Waveform): The...
5,325,804
def subtask1_eval(_answers, _ref): """ 子任务1的评分函数。 :param _answers: 答卷答案。 :param _ref: 参考答案。 :return: 统计数据对象。 """ _map = { '11': 'TP', '00': 'TN', '10': 'FN', '01': 'FP', } _st = { 'TP': 0, 'TN': 0, 'FN': 0, 'FP': 0, ...
5,325,805
def plot_degree_histogram(G, log_yscale=True): """ Plots the histogram of the degree :param G: nx.Graph :param log_yscale: if True, pyplot's yscale is log """ degree_sequence = sorted([d for n, d in G.degree()], reverse=True) plt.hist(degree_sequence) if log_yscale: plt.yscale('l...
5,325,806
def render_horizontal_fields(*fields_to_render, **kwargs): """Render given fields with optional labels""" labels = kwargs.get('labels', True) media = kwargs.get('media') hidden_fields = [] visible_fields = [] for bound_field in fields_to_render: if bound_field.field.widget.is_hidden: ...
5,325,807
def get_darwin_memory(): """ Use system-call to extract total memory on macOS """ system_output = sabnzbd.newsunpack.run_simple(["sysctl", "hw.memsize"]) return float(system_output.split()[1])
5,325,808
def parseTextModeTimeStr(timeStr): """ Parses the specified SMS text mode time string The time stamp format is "yy/MM/dd,hh:mm:ss±zz" (yy = year, MM = month, dd = day, hh = hour, mm = minute, ss = second, zz = time zone [Note: the unit of time zone is a quarter of an hour]) @param timeStr:...
5,325,809
def main(): """Recording the inbound traffic for a database.""" db_config = config.DB_CONFIG recorder = MongoQueryRecorder(db_config) def signal_handler(sig, dummy): """Handle the Ctrl+C signal""" print 'Trying to gracefully exit the program...' recorder.force_quit_all() sig...
5,325,810
def angle_to_rotation_matrix(angle) -> Tensor: """ Creates a rotation matrix out of angles in degrees Args: angle: (Tensor): tensor of angles in degrees, any shape. Returns: Tensor: tensor of *x2x2 rotation matrices. Shape: - Input: :math:`(*)` - Output: :math:`(*, ...
5,325,811
def main(): """Find every python file recursively inside given directory and call posixlines on them.""" parser = optparse.OptionParser("fix_endl.py directory") (options, args) = parser.parse_args() if len(args) != 1: parser.print_help() parser.error("incorrect number of arguments") ...
5,325,812
def main(): """run-time code""" # consolidate the above steps into a single line using the index_col and parse_dates parameters of the read_csv() function opsd_daily = pd.read_csv('netTraffic.csv', index_col=0, parse_dates=True) # add some additional columns to our data # Add columns with year, mon...
5,325,813
def extract_text(): """Extracts text from an HTML document.""" html = request.form['html'] article = Article(html) try: return article.text except AttributeError as e: log.warn(e) # NOTE: When a parsing error occurs, an AttributeError is raised. # We'll deal with this...
5,325,814
def get_new_account_id(event): """Return account id for new account events.""" create_account_status_id = ( event["detail"] .get("responseElements", {}) .get("createAccountStatus", {})["id"] # fmt: no ) log.info("createAccountStatus = %s", create_account_status_id) org = bo...
5,325,815
def lag_indexes(tf_stat)-> List[pd.Series]: """ Calculates indexes for 3, 6, 9, 12 months backward lag for the given date range :param begin: start of date range :param end: end of date range :return: List of 4 Series, one for each lag. For each Series, index is date in range(begin, end), value is a...
5,325,816
def weather_outfit(req): """Returns a string containing text with a response to the user with a indication if the outfit provided is appropriate for the current weather or a prompt for more information Takes a city, outfit and (optional) dates uses the template responses found in weather_resp...
5,325,817
def get_GEOS5_data_cubes4campaign(ds=None, year=2018, region='Cape_Verde', doys2use=None, vars2use=None, collection='inst3_3d_aer_Nv', limit_lvls=False, limit_lons=False): """ Extract cubes of data for region o...
5,325,818
def WriteTo(linelist, outfile, SoP): """writes the sorted list to a CSV file with name outfile""" file = open(str(outfile),'w') i=0 if SoP == 'P': for line in linelist: file.write(linelist[i].borough+ ',') file.write(linelist[i].block+ ',') file.write...
5,325,819
def _poll_scheduler_status(config, asg_name, scheduler_module, instance_properties): """ Verify scheduler status and ask the ASG new nodes, if required. :param config: JobwatcherConfig object :param asg_name: ASG name :param scheduler_module: scheduler module :param instance_properties: instanc...
5,325,820
def parse_paragraphs(record): """ parse paragraphs into sentences, returns list """ from sentence_splitter import SentenceSplitter splitter = SentenceSplitter(language='en') sentences=splitter.split(record['value']) article_id = remove_prefix(record['key'],'paragraphs:') pre = 'sentence:...
5,325,821
def get_stage_environment() -> str: """ Indicates whether the source is running as PRD or DEV. Accounts for the user preference via TEST_WORKING_STAGE. :return: One of the STAGE_* constants. """ return TEST_WORKING_STAGE
5,325,822
def get_all_table_acls(conn, schema=None): """Get privileges for all tables, views, materialized views, and foreign tables. Specify `schema` to limit the results to that schema. Returns: List of :class:`~.types.SchemaRelationInfo` objects. """ stmt = _table_stmt(schema=schema) retu...
5,325,823
async def test_effect_template(hass, expected_effect, start_ha): """Test the template for the effect.""" state = hass.states.get("light.test_template_light") assert state is not None assert state.attributes.get("effect") == expected_effect
5,325,824
def add_atom_map(molecule, **kwargs): """ Add canonical ordered atom map to molecule Parameters ---------- molecule : `oechem.OEMOl` or `rdkit.Chem.Mol` Returns ------- molecule with map indices """ toolkit = _set_toolkit(molecule) return toolkit.add_atom_map(molecu...
5,325,825
def build_put_dictionary_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest: """Put External Resource as a Dictionary. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :keyword json: Pass in a JSON-seriali...
5,325,826
def midpoint(rooms): """ Helper function to help find the midpoint between the two rooms. Args: rooms: list of rooms Returns: int: Midpoint """ return rooms[0] + (rooms[0] + rooms[2]) // 2, rooms[1] + (rooms[1] + rooms[3]) // 2
5,325,827
def secondSolution( fixed, c1, c2, c3 ): """ If given four tangent circles, calculate the other one that is tangent to the last three. @param fixed: The fixed circle touches the other three, but not the one to be calculated. @param c1, c2, c3: Three circles to which the other tangent c...
5,325,828
def generate_concept_chain(concept_desc, sequential): """ Given a list of availiable concepts, generate a dict with (start, id) pairs giving the start of each concept. Parameters ---------- sequential: bool If true, concept transitions are determined by ID without randomness. ...
5,325,829
def get_inputs(input_queue, num_classes, merge_multiple_label_boxes=False, use_multiclass_scores=False): """Dequeues batch and constructs inputs to object detection model. Args: input_queue: BatchQueue object holding enqueued tensor_dicts. num_classes: Number of...
5,325,830
def merge_metadata(m1, m2): """Given 2 dictionaries that map str->set, merge m2 into m1. For each key in m2, m1's value for that key becomes the union of its own value and m2's value. m1 and m2 must have the same set of keys; otherwise, raise an exception.""" if set(m1) != set(m2): raise Bui...
5,325,831
def doFilter(pTable, proxyService): """ filter candidates by column header candidates - column headers are kept, if they support at least (minSupport * #rows) many cells - only filter for columns that are part of the targets (if activated) subsequently remove: - CTA candidates with less support...
5,325,832
def int_or_float(x): """Convert `x` to either `int` or `float`, preferring `int`. Raises: ValueError : If `x` is not convertible to either `int` or `float` """ try: return int(x) except ValueError: return float(x)
5,325,833
def show(scheme, hexa=cube_points([0.0, 1.0], [0.0, 1.0], [0.0, 1.0]), backend="mpl"): """Shows the quadrature points on a given hexahedron. The size of the balls around the points coincides with their weights. """ edges = numpy.array( [ [hexa[0, 0, 0], hexa[1, 0, 0]], [h...
5,325,834
def setup_torch_process_group( backend: str, world_rank: int, world_size: int, init_method: str, timeout_s: int = 1800, ): """Connects the distributed PyTorch backend. Args: backend (str): The backend (nccl, gloo, etc.) to use for training. world_rank (int): Rank of the curr...
5,325,835
def request_factory(): """Pytest setup for factory.""" return RequestFactory()
5,325,836
def send_tls(text, subject="Testing", address=None): """ Send encrypted via TLS SMTPHeloError The server didn’t reply properly to the HELO greeting. SMTPNotSupportedError The server does not support the STARTTLS extension. RuntimeError SSL/TLS support is not available to your Python interpreter. ""...
5,325,837
def vegaGraphics( cmdTag, id1, id2, parameters, sql, transformedData, verbose,): """Create interactive charts for specified data""" # making function more explicit cmdTag = cmdTag id1 = id1 id2 = id2 parameters = parameters sql = sql ...
5,325,838
def is_onehotencoded(x): """If input is a one-hot encoded representation of some set of values. Parameters ---------- x : array-like Returns ------- bool Whether `x` is a one-hot encoded / categorical representation. """ if x.ndim != 2: return False fractional,...
5,325,839
def test_empty_project(project_test, qtbot): """Test creation of an Empy project, and its configuration files.""" project_dir, project = project_test assert project.root_path == str(project_dir) # Assert Project configs qtbot.wait(3000) for filename in [WORKSPACE, CODESTYLE, ENCODING, VCS]: ...
5,325,840
def sequence_of_words(fname_doc, dictionary): """ Compute Sequence-of-Words from word list and dictionary """ txtdata = loadtxt(fname_doc) words = extract_keyword(txtdata, "all") SOW = [] for i,word in enumerate(words): print(word) if word in dictionary.keys(): S...
5,325,841
def shd(B_est, B_true): """Compute various accuracy metrics for B_est. true positive = predicted association exists in condition in correct direction reverse = predicted association exists in condition in opposite direction false positive = predicted association does not exist in condition Args: B_true (np.nda...
5,325,842
def save_adv_examples(data, **kwargs): """ Serialize generated adversarial examples to an npy file. :param data: the adversarial examples to store. :param kwargs: information needed to construct the file name :return: na """ prefix = kwargs.get('prefix', 'test') dataset = kwargs.get('dat...
5,325,843
def test_separate_networks( configs: dict[str, Any], make_plots: bool = True, **kwargs, ) -> TestOutputs: """Test training on separate networks.""" t0 = time.time() logger.info(f'Testing separate networks') configs_ = dict(copy.deepcopy(configs)) configs_['dynamics_config']['...
5,325,844
async def test_already_configured(hass): """Test we reject already configured devices.""" MockConfigEntry( domain=DOMAIN, data=FIXTURE_USER_INPUT, title="Already configured" ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config...
5,325,845
def main(models, datasets, *args, **kwargs): """ Entry point to the toolkit Returns: """ from .model_evaluator import ModelEvaluator if "all" in models: models = supported_models if "all" in datasets: datasets = supported_datasets evaluate = ModelEvaluator...
5,325,846
def _render_html_page(gallery: Gallery, image: Image) -> None: """Create an HTML document for a single image.""" context = {'gallery': gallery, 'image': image} _render_html_to_file( 'view', context, gallery.destination_path, image.page_name )
5,325,847
def test_jsarray_output(): """Test that the output function for JSArray doesn't bork.""" ja = JSArray(traverser=traverser) ja.elements = [None, None] repr(ja) # Used to throw tracebacks. ja.as_primitive()
5,325,848
def nohighlight(nick): """add a ZWNJ to nick to prevent highlight""" return nick[0] + "\u200c" + nick[1:]
5,325,849
def _get_r_val(z, omega_m, omega_l): """Returns the comoving distance at for one z value. Parameters ---------- z : float Redshift. omega_m : float Present matter density. omega_l : float Present dark energy density. """ r, err = integrate.quad(_get_r_integrand, ...
5,325,850
def user_response_controller(bank_request, user_response): """ processes user's response for bank's request sent : bank_request --> what is user currently requesting for : user_response --> what a user wants to actually do amongst the options in the above bank_requests """ user_re...
5,325,851
def create_features(datestrs): """ Find the features associated with a set of dates. These will include: weekday / weekend day of week season month of year Parameters ---------- datestrs: list of strings Date strings of the format YYYY-MM-DD. Returns...
5,325,852
def reset_print(): """ Resets print """ local_print = print yield builtins.print = local_print
5,325,853
def obj_src(py_obj, escape_docstring=True): """Get the source for the python object that gets passed in Parameters ---------- py_obj : callable Any python object escape_doc_string : bool If true, prepend the escape character to the docstring triple quotes Returns ------- ...
5,325,854
def get_back_button_handler(current_panel: "GenericPanel") -> CallbackQueryHandler: """ returns a Handler for BACK_PATTERN that returns the user to current_panel :param GenericPanel current_panel: the destination panel :return: a CallbackQueryHandler for BACK_PATTERN that returns the user to current_pa...
5,325,855
def main(): """Main function""" model = None if len(sys.argv) > 1: model = sys.argv[1] motor_driver_helper.set_gpio_pins() autonomous_control(model)
5,325,856
def _build_import_library_x86(): """ Build the import libraries for Mingw32-gcc on Windows """ lib_name = "python%d%d.lib" % tuple(sys.version_info[:2]) lib_file = os.path.join(sys.prefix, 'libs', lib_name) out_name = "libpython%d%d.a" % tuple(sys.version_info[:2]) out_file = os.path.join(sys.pr...
5,325,857
def save_image(filename: str, pixels: list, width: int, height: int) -> None: """Create a width by height image containing pixels and save it to a file called filename. """ image = Image.new('RGB', (width, height)) [image.putpixel((x, y), pixels[x + y * width]) for x in range(width) for y in range(heig...
5,325,858
def openocd_prog_path(request: FixtureRequest) -> Optional[str]: """Enable parametrization for the same cli option""" return _request_param_or_config_option_or_default(request, 'openocd_prog_path', None)
5,325,859
def reindexMatrix(iss, jss, A): """iss and jss are lists of indices of equal size, representing a permuation: iss[i] is replaced with jss[i]. all other indices which are not in the lists left unchanged. """ n = len(A) B = np.zeros_like(A) tss = [i for i in range(n)] for i in range(len(is...
5,325,860
def createInfoMatix(character_id): """初始化创建的角色的阵法 """ petlist = getCharacterPetList(character_id) sql = "INSERT INTO `tb_character_matrix`(`characterId`,`eyes_4`,`eyes_5`,`eyes_6`) \ VALUES(%d,%d,%d,%d);"%(character_id,petlist[0],petlist[1],petlist[2]) conn = dbpool.connection() cursor = co...
5,325,861
def help(): """<b>Print available functions as json.<br>""" func_list = {} for rule in app.url_map.iter_rules(): if rule.endpoint != 'static': func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__ return jsonify(func_list)
5,325,862
async def grid_train(params: Grid, background_tasks: BackgroundTasks, credentials: HTTPBasicCredentials = Depends(validate_access)): """ Choose an estimator, and hyper-parameters to optimize for a GridSearchCV. Results can be recorded in Neptune.ai. """ try: X_train, X_test, y_train, y_test = l...
5,325,863
def version(): """ Returns the name, version and api_version of the application when a HTTP GET request is made. """ return jsonify( name='openshift-python-flask-sample', version=VERSION )
5,325,864
def test_get_text_anchors(anchor_type, ndisplay, expected_coords): """Round trip tests for getting anchor coordinates.""" coords = [np.array([[0, 0], [10, 0], [0, 10], [10, 10]])] anchor_coords, _, _ = get_text_anchors( coords, anchor=anchor_type, ndisplay=ndisplay ) np.testing.assert_equal(...
5,325,865
def search_quotes(request, currency): """ Consulta a API procurando por ações que contenham o campo 'currency' no nome """ # verifica se a barra de pesquisa foi preenchida ou se está vazia if currency: conn.request("GET", "/auto-complete?q="+currency+"&region=BR", headers=headers) res = conn...
5,325,866
def destroy(N, dtype=tf.complex64): """Returns a destruction (lowering) operator in the Fock basis. Args: N (int): Dimension of Hilbert space dtype (tf.dtypes.DType, optional): Returned dtype. Defaults to c64. Returns: Tensor([N, N], dtype): NxN creation operator """ a = diag...
5,325,867
def get_nearest_operation( db: Redis[bytes], address: hash_t, subdag: Optional[str] = None ) -> Optional[Operation]: """Return the operation at address or the operation generating address.""" root = "root" art = None try: node = Operation.grab(db, address) return node except Runt...
5,325,868
def load_CIFAR_batch(file_path): """ load single batch of cifar """ data_dict = load_pickle(file_path) data = data_dict['data'] labels = data_dict['labels'] data = data.reshape(10000, 3, 32, 32).astype("float") labels = np.array(labels) return data, labels
5,325,869
def _disposable_and_async_gen_from_obs(obs: Observable): """ Compatability layer for legacy Observable to async generator This should be removed and subscription resolvers changed to return async generators after removal of flask & gevent based dagit. """ queue: Queue = Queue() disposable ...
5,325,870
def interesting_pattern(x: float, y: float) -> float: """This function is interesting in x and y in range -10..10, returning a float value in range 0..1 """ z = 0.5 + (np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)) / 2 return z
5,325,871
def cut(st, sec_before_split=None): """ Cut/trim the record. This method minimally requires that the windows.signal_end method has been run, in which case the record is trimmed to the end of the signal that was estimated by that method. To trim the beginning of the record, the sec_before_split...
5,325,872
def interp_road(d,croad,roads,intersections,normD = False): """ Get the position of a point along a road """ start_int = roads[croad]['start_int'] start_pos = intersections[start_int]['position'] end_int = roads[croad]['end_int'] end_pos = intersections[end_int]['position'] if not normD: ...
5,325,873
def to_ufo_font_attributes(self, family_name): """Generate a list of UFOs with metadata loaded from .glyphs data. Modifies the list of UFOs in the UFOBuilder (self) in-place. """ font = self.font # "date" can be missing; Glyphs.app removes it on saving if it's empty: # https://github.com/goog...
5,325,874
def zero_pad2d(inputs, padding=0, output_dtype="float32", requires_grad=False): """ Zero padding for 2d tensor Args: ----------------------------- inputs : Tensor shape [batch, channel, height, width] padding: (optional:0) int or tuple expected: (h_pad_up, h_pad_down, w_pad_up, ...
5,325,875
def test_inflight_requests(broker, req): """Not all simultaneous requests to a cached service are executed. """ req = dict(req) req["delay"] = 2 results = [] for _ in range(10): results.append(broker.execute("mock_preload_long_ttl", req, cache=True)) status = [cache_status(r.metada...
5,325,876
def my_plot(my_folder='/mnt/closet/ldr2/catalogues'): """Make some plots. Parameters ---------- my_directory : string Working directory. """ df = pd.read_csv('/home/sean/Downloads/ldr2/LDR2 and BZCAT 10_ crossmatch -' ' BL Lacs.csv') compact = df[df['Compact'] =...
5,325,877
def gtfs_admin(request): """admin page for adding new review categories (and potentially other features down the road)""" return render(request, 'admin/gtfs_admin.html')
5,325,878
def get_file_path(): """ Get current file's directory. Return `None` if there is no file path available. """ try: file_path = sublime.active_window().extract_variables()['file_path'] except KeyError: return None else: return file_path
5,325,879
def mutate_word(word): """Introduce a random change into the word: delete, swap, repeat, and add stray character. This may raise a ValueError. """ word = list(word) choice = random.randrange(4) if choice == 0: # Delete a character word.pop(random.randrange(len(word))) elif choice =...
5,325,880
def data_layer_property_from_dict(data_layer_property_dictionary: dict, client: cl.Client = None): """ The method converts a dictionary of DataLayerProperty to a DataLayerProperty object. :param data_layer_property_dict: A dictionary that contains the keys of a Data...
5,325,881
def pcc_vector(v1, v2): """Pearson Correlation Coefficient for 2 vectors """ len1 = len(v1) len2 = len(v2) if len1 != len2: return None else: length = len1 avg1 = 1.0 * sum(v1) / len(v1) avg2 = 1.0 * sum(v2) / len(v2) dxy = [(v1[i] - avg1) * (v2[i] - avg2) for i in ra...
5,325,882
def cypher_repr(obj): """ Generate the Cypher representation of an object. """ string = StringIO() writer = CypherWriter(string) writer.write(obj) return string.getvalue()
5,325,883
def silence(): """Silence the screen reader (if currently speaking).""" tolk.silence()
5,325,884
def firstlastmile_pipeline(**kwargs): """The first and last mile pipeline attaches any unattached elements to ensure a fully-connected graph""" tags = ['flmile'] firstmile_nodes = [ node( firstmile_edge, ['sjoin_oilfields_data','sjoin_edges_pipelines_oilfields','sjoin_po...
5,325,885
def photo_new(request, cast: Cast): """ Add a new Photo to a cast """ if request.method == 'POST': form = CastPhotoForm(request.POST, request.FILES) if form.is_valid(): photo = form.save(commit=False) photo.cast = cast photo.save() messages...
5,325,886
def decode(argument: str) -> tuple[list[int], ...]: """Decode argument string from command line :param argument: argument string :return: pair of list of digits """ char_lists = map(list, argument.split('-')) range_ = tuple(list(map(int, clist)) for clist in char_lists) return range_
5,325,887
def initialize_weights(*models): """ Initialize Model Weights """ for model in models: for module in model.modules(): if isinstance(module, (nn.Conv2d, nn.Linear)): nn.init.kaiming_normal_(module.weight) if module.bias is not None: ...
5,325,888
def zip_files(files, zipfilename, mode='a', compressed=True, fullpath=True): """ Compress/archive a given list of files into a zip file. The mode can be either write "w" or append "a". Duplicates will be ommited in append mode. """ import zipfile if compressed: compression=zipfile.ZI...
5,325,889
def main(duration=0, rate=3300, gain=16, verbose=False, **kwargs): """ Take data from the ADS1015 for duration seconds (or until stdin receives EOF, if duration is 0) at rate and gain. Default argument values may not be the same as for the command line arguments. See the ArgumentParser instance below. ...
5,325,890
def generate_data(p=11, n=400): """ Generates non-linear multivariate data of dimension 'p'. The data is linear in parameters of the type: y = b0 + b1 * x + b2*x^2 + ... + bp * x^p Args: :param p: int dimensions :param n: int number of samples Return...
5,325,891
def get_search_apps(): """Gets all registered search apps.""" return tuple(_load_search_apps().values())
5,325,892
def volume_tetrahedron( point_a: array_like, point_b: array_like, point_c: array_like, point_d: array_like ) -> np.float64: """ Return the volume of a tetrahedron defined by four points. The points are the vertices of the tetrahedron. They must be 3D or less. Parameters ---------- point_a,...
5,325,893
def set_time_mode(time_exe = False): """Enable/Disable code timing Parameters ---------- time_exe : boolean Internal mode setting Returns ------- None """ GLContainer.set_time_mode(time_exe)
5,325,894
def lemmatizer(word): """Returns: lemmatized word if word >= length 5 """ if len(word)<4: return word return wnl.lemmatize(wnl.lemmatize(word, "n"), "v")
5,325,895
def kolmogn(n, x, cdf=True): """Computes the CDF for the two-sided Kolmogorov-Smirnov distribution. The two-sided Kolmogorov-Smirnov distribution has as its CDF Pr(D_n <= x), for a sample of size n drawn from a distribution with CDF F(t), where D_n &= sup_t |F_n(t) - F(t)|, and F_n(t) is the Empiri...
5,325,896
def join_legacy_read_path(sample_path: str, suffix: int) -> str: """ Create a path string for a sample read file using the old file name convention (eg. reads_1.fastq). :param sample_path: the path to the sample directory :param suffix: the read file suffix :return: the read path """ retur...
5,325,897
def fixture_audio_playback(fixture_signal_generator): """ Makes sure that there is some audio being played to our null sink. """ sg = fixture_signal_generator with sg.attach_generator(): time.sleep(1.0) # TODO yield sg
5,325,898
def watermark_pdf(input_file: str, wm_text: str, pages: Tuple = None): """ Adds watermark to a pdf file. """ result, wm_buffer = create_watermark(wm_text) if result: wm_reader = PdfFileReader(wm_buffer) pdf_reader = PdfFileReader(open(input_file, 'rb'), strict=False) pdf_writ...
5,325,899