content
stringlengths
22
815k
id
int64
0
4.91M
def getName(): """ The purpose of the function """ name = input('Welcome new user. \nPlease eneter your name: ') print(f'You have done well {name}.\ This course will introduce you to core of Python programming.')
43,700
def preprocess_sent(sentence): """input: a string containing multiple sentences; output: a list of tokenized sentences""" sentence = fill_whitespace_in_quote(sentence) output = tokenizer0(sentence) # tokens = [token.text for token in tokenizer.tokenize(sentence)] tokens = list(map(lambda x: x.te...
43,701
def main(): """Entry point.""" args = parse_args() f = open(args.cesar_out, "r") lines = f.readlines() f.close() ref_seq = lines[1] que_seq = lines[3] codons_data = parse_cesar_out(ref_seq, que_seq) for elem in codons_data: print(elem)
43,702
def test_parcel_intra_from_3d_image(): """ test that a parcellation is generated, starting from an input 3D image """ # Generate an image tempdir = mkdtemp() shape = (10, 10, 10) mask_image = Nifti1Image(np.ones(shape), np.eye(4)) data_image = join(tempdir, 'image.nii') surrogate_3d_...
43,703
def save_attention_visualization(source_img_path, att_map, dest_name): """ Visualize the attention map on the image and save the visualization. """ img = cv2.imread(source_img_path) # cv2.imread does auto-rotate # downsample source image img = downsample_image(img) img_h, img_w, img_c = img...
43,704
def average_slope_intercept(image, lines): """ This function combines line segments into one or two lane lines """ left_fit = [] # contains the coordinate of on the line in the left right_fit = [] if lines is None: return None # now loop through very line we did previous...
43,705
def build_upper_limb_roll_jnts(main_net, roll_jnt_count=3): """Add roll jnts, count must be at least 1""" increment = 1.0/float(roll_jnt_count) def create_joints(jnt_a, jnt_b, net, lower_limb=False, up_axis='-Z'): """ :param jnt_a: Start Joint :param jnt_b: End Joint :param...
43,706
def upload(): """UEditor文件上传接口 config 配置文件 result 返回结果 """ mimetype = 'application/json' result = {} action = request.args.get('action') # 解析JSON格式的配置文件 with open(os.path.join(app.static_folder, 'ueditor', 'php', 'config.json')) as fp: try: ...
43,707
def create_one(**kwargs): """ Create a Prediction object with the given fields. Args: Named arguments. date: Date object. Date of the predicted changes. profitable_change: Decimal. Predicted profitable change in pips. instrument: Instrument object...
43,708
def get_lane_lines(img_parms): """ Main jumping into function """ titles = list() images = list() cmaps = list() print("Starting Lane Detection") print("************************") img_in = mpimg.imread(img_parms["image"]) if debug >= 3: make_save_dir(img_parms["...
43,709
def get_distance_wgs84(lon1, lat1, lon2, lat2): """ 根据https://github.com/googollee/eviltransform,里面的算法:WGS - 84 :param lon1: 经度1 :param lat1: 纬度1 :param lon2: 经度2 :param lat2: 纬度2 :return: 距离,单位为 米 """ earthR = 6378137.0 pi180 = math.pi / 180 arcLatA = lat1 * pi180 arcLa...
43,710
def make_uuid(ftype, size=6): """ Unique id for a type. """ uuid = str(uuid4())[:size] return f'{ftype}-{uuid}'
43,711
def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. Args: img (image): Mas...
43,712
def _adjust_utc_datetime_to_phone_datetime(value, phone_tz): """ adjust a UTC datetime so that it's comparable with a phone datetime (like timeEnd, modified_on, etc.) returns a timezone-aware date """ phone_tz = _soft_assert_tz_not_string(phone_tz) assert value.tzinfo is None if phone_...
43,713
def cache_function(length=CACHE_TIMEOUT): """ A variant of the snippet posted by Jeff Wheeler at http://www.djangosnippets.org/snippets/109/ Caches a function, using the function and its arguments as the key, and the return value as the value saved. It passes all arguments on to the function, as ...
43,714
def main() -> None: """ Make a jazz noise here """ args = get_args() done = set() if args.progress and os.path.isfile(args.progress): done = set([line.rstrip() for line in open(args.progress)]) progress_fh = tempfile.NamedTemporaryFile(delete=False, mode='wt') def cleanup(): ...
43,715
def get_yaml_config(file_name): """Return a dict parsed from a YAML file within the config directory. Args: file_name: String that defines the config file name. Returns: A dict with the parsed YAML content from the config file or an empty dict if the file is not found or YAML was u...
43,716
def test_atomic_nmtoken_enumeration_4_nistxml_sv_iv_atomic_nmtoken_enumeration_5_2(mode, save_output, output_format): """ Type atomic/NMTOKEN is restricted by facet enumeration. """ assert_bindings( schema="nistData/atomic/NMTOKEN/Schema+Instance/NISTSchema-SV-IV-atomic-NMTOKEN-enumeration-5.xsd...
43,717
def extract_tarball_at_node(tarball, node): """Extract tarball at given node. Extracts tarball using tar on given node to specific CSIT location. Raise runtime errors when failed. :param tarball: Path to tarball to upload. :param node: Dictionary created from topology. :type tarball: str :...
43,718
def plot_contour_1d(X_grid, Y_grid, data, xlabel, ylabel, xticks, yticks, metric_bars, fillblack=True): """Create contour plots and return the figure and the axes.""" n = len(metric_bars) assert data.shape == (*X_grid.shape, n), ( "data shape must be (X, Y, ...
43,719
def dataset_to_rasa(dataset: JsonDict) -> JsonDict: """Convert dataset to RASA format, ignoring entities See: "https://rasa.com/docs/nlu/dataformat/" """ return { "rasa_nlu_data": { "common_examples": [ {"text": text, "intent": intent, "entities": []} ...
43,720
def get_firewall(args): """ Get a specified firewall rule. parameter: (string) name Name of the firewall rule to return. """ project = SERVICE_ACT_PROJECT_ID name = args.get('name') request = compute.firewalls().get(project=project, firewall=name) response = request.execute() ...
43,721
def SurfacePlot(Fields,save_plot,as_video=False, Freq=None, W=None, L=None, h=None, Er=None): """Plots 3D surface plot over given theta/phi range in Fields by calculating cartesian coordinate equivalent of spherical form.""" print("Processing SurfacePlot...") fig = plt.figure() ax = fig.add_subplot(11...
43,722
def quantize_folder_images( path_images, colors=None, method='color', px_threshold=THRESHOLD_INVALID_PIXELS, nb_workers=1 ): """ perform single or multi thread image quantisation :param str path_images:, input directory and image pattern for loading :param colors: [(int, int, int)], list of possible co...
43,723
def resource_method_wrapper(method): """ Wrap a 0-ary resource method as a generic renderer backend. >>> @resource_method_wrapper ... def func(resource): ... print repr(resource) >>> action = "abc" >>> resource = "def" >>> func(action, resource) 'd...
43,724
def rotation_matrix(axis_vector, angle, degrees = True): """ Return the rotation matrix corresponding to a rotation axis and angle For more information, see: https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Parameters ---------- axis_vector : 3 x 1 numpy ar...
43,725
def test_rsub(): """Ensures that add works correctly.""" sub = _MathExpression() - 4 rsub = 4 - _MathExpression() assert rsub(1) + sub(1) == 0
43,726
def select_int(sql, *args): """ 执行一个sql, 返回一个数值 :param sql: :param args: :return: """ d = _select(sql, True, *args) if d == None: raise StandardError('Result is None') if len(d) != 1: raise MultiColumnsError('Expect only one column.') return d.values()[0]
43,727
def create_workflow_from_json( name, access_token, workflow_json=None, workflow_file=None, parameters=None, workflow_engine="yadage", outputs=None, ): """Create a workflow from json specification. :param name: name or UUID of the workflow to be started. :param access_token: acce...
43,728
def compute_nas_score(any_plain_net, random_structure_str, gpu, args): """ compute net score :param any_plain_net: model class :param random_structure_str (str): model string :param gpu (int): gpu index :param args (list): sys.argv :return score """ # compute network...
43,729
def get_firmware_baselines(authenticated_headers: dict, ome_ip_address: str, device_id: int = None, service_tag: str = None, device_idrac_ip: str = None, device_name: str = None): "...
43,730
def _dict_values_match(*args, **kwargs): """ Matcher that matches a dict where each of they keys match the matcher passed in. Similar to ``MatchesStructure``, but for dictionaries rather than python objects. """ matchers = dict(*args, **kwargs) def extract_val(key): def extract_val...
43,731
def fib_lista(n): """ Função que retorna uma lista contendo os números da sequência de Fibonacci até o número n. """ lista = [] i, j = 0, 1 while i < n: lista.append(i) i, j = j, i + j return lista
43,732
def refresh(): """Write the shell declare variable statements to stdout.""" atexit.register(close_stdio) signal.signal(signal.SIGPIPE, signal.SIG_DFL) args = sys.argv[1:] if len(args) >= 2: abort(USAGE + 'dtags: too many arguments') if len(args) == 1: shell_name = args[0] ...
43,733
def test_main_errored(): """Test that running the application without parameter returns an error.""" runner = CliRunner() result = runner.invoke(main) assert result.exit_code == 2 assert "Missing option" in result.output assert "Usage: main [OPTIONS]" in result.output
43,734
def migrate(db_file=None, migrations_dir=None, verbose=False): """Run the migrations. Read all the migrations in the migrations directory, and add them to the migrations table if they are not already there. They are first inserted with the status 'down'. Then, for all migrations with status 'down',...
43,735
def _get_json_file(module_path): """ Returns the path of the JSON file for a module, empty if doesn't exitst. """ json_file = '%s.json' % module_path.rsplit('.', 1)[0] if os.path.isfile(module_path) and os.path.isfile(json_file): return json_file else: return ''
43,736
def make_item_accessor(idx): """ Returns a property that mirrors access to the idx-th value of an object. """ @property def attr(self): return self[idx] @attr.setter def attr(self, value): self[idx] = value return attr
43,737
def calc_correlation(data, data2): """ Calculate the correlations between 2 DataFrames(). Parameters: - data: The first dataframe. - data2: The second dataframe. Returns: A Series() object. """ return ( data.corrwith(data2). loc[lambda x: x.notnull()] ...
43,738
def boschloo_swap(c1r1: int, c2r1: int, c1r2: int, c2r2: int) -> (int, int, int, int): """ Four contingency tables always give the same pvalue: ['abcd', 'badc', 'cdab', 'dcba'] Compute and save only one version. """ if c1r1 + c1r2 > c2r1 + c2r2: # left > right c1r1, c1r2, c2r1, c2r2 = c2r1...
43,739
def custom_repo(distro, args, cd_conf, rlogger, install_ceph=None): """ A custom repo install helper that will go through config checks to retrieve repos (and any extra repos defined) and install those ``cd_conf`` is the object built from argparse that holds the flags and information needed to dete...
43,740
def create_html_report( args, source_dir, scan_started, cursor, html, siegfried_version, use_hash, ): """Get aggregate statistics and write to html report""" # Gather stats from database. cursor.execute("SELECT COUNT(*) from siegfried;") # total files num_files = cursor.fetchone()[0] cursor.ex...
43,741
def test_utcdatetime_type(session, User): """ Test that UTCDatetime works """ ptz = gettz('US/Pacific') local_time = datetime(2019, 1, 1, 12, 0, tzinfo=ptz) # 12pm PST, 20pm UTC user = User(created_at=local_time) session.add(user) session.commit() # tzinfo should be converted prope...
43,742
def get_unit_scale(scale60, val30=1): """ Returns a function to be used in the UNIT_SCALE of a descriptor that will change the scale depending on if the 60fps flag is set or not. """ assert 0 not in (val30, scale60), ("60fps scale and default 30fps " + "v...
43,743
def get_cex_order_book(bidfile, askfile, symbol='BTC/USD', limit=50): """ doc: https://cex.io/rest-api#orderbook max requests: 180 / min """ main_path = 'https://cex.io/api' info_path = '/order_book/{}/?depth={}'.format(symbol, limit) r = requests.get(main_path + info_path) data_...
43,744
def sample_ingredient(user,name = 'cinnoan'): """create and return a sample ingredient""" return Ingredient.objects.create(user=user,name=name)
43,745
def get_tracks(self): """Collects track metadata from spotify and uploads it to our database. Retreives a list of album ids from the "albums" table in our database. Then, we splits this list into chunks and assigns celery tasks to each one. This allows our program to distribute (e.g., multi-process) ta...
43,746
def test_creating_tools_edition_panel(exopy_qtbot, edition_view, dialog_sleep): """Test creating the tool edition panel using the button. """ edition_view.show() wait_for_window_displayed(exopy_qtbot, edition_view) exopy_qtbot.wait(dialog_sleep) ed = edition_view.widget.dock_widget().widgets()...
43,747
def before(action): """Decorator to execute the given action function *before* the responder. Args: action: A function with a similar signature to a resource responder method, taking (req, resp, params), where params includes values for URI template field names, if any. Hooks may also a...
43,748
def commandLine(Argv): """ Method converting a list of arguments/parameter in a command line format (to include in the execution of a program for exemple). list --> str """ assert type(Argv) is list, "The argument of this method are the arguments to convert in the command line format. (type Lis...
43,749
def validate_flags_or_throw(bert_config): """Validate the input FLAGS or throw an exception.""" if not FLAGS.do_train and not FLAGS.do_predict: raise ValueError("At least one of `{do_train,do_predict}` must be True.") if FLAGS.do_train: if not FLAGS.train_precomputed_file: raise ValueError("If `do_...
43,750
def select_diff_from_dic(dic, spacegroup_tuples, sample_key='Mat', drop_nan=None): """ Get data frame of selected spacegroup_tuples from dictionary of dictionaries. Creating a pandas data frame with columns of samples and selected space group tuples (energy differnces). Parameters: dic: d...
43,751
def add_weighted_spans(doc, vec, vectorized, target_expl): # type: (Any, Any, bool, TargetExplanation) -> None """ Compute and set ``target_expl.weighted_spans`` attribute, when possible. """ if vec is None or vectorized: return weighted_spans = get_weighted_spans(doc, vec, target_expl....
43,752
def prob(n: int, p: float) -> float: """ Parameters: - n (int): số lần thực hiện phép thử - p (float): xác suất phép thử thành công Returns: - float: xác suất hình học """ pr = p * (1 - p) ** (n - 1) return pr
43,753
def to_overall_gpu_process_df(gpu_stats: Mapping) -> DataFrame: """ """ resulta = [] columns = [] for k2, v2 in gpu_stats.items(): device_info = v2["devices"] for device_i in device_info: processes = device_i["processes"] if len(processes) > 0: col...
43,754
def main(): """Source space contrast.""" subjects = config.get_subjects() print(subjects) sessions = config.get_sessions() cfg = get_config() # Usefull for debugging # for sub, ses in itertools.product(subjects, sessions): # one_subject(sub, ses, cfg) parallel, run_func, _ = pa...
43,755
def measure_performance(which, ndims): """ To run a mini-timing benchmark, in the shell run: $ python3 -O -mtimeit -n 5 -r 5 -s'from pysfc import ndgeom' 'ndgeom.measure_performance("sphere", 2)' $ python3 -O -mtimeit -n 5 -r 5 -s'from pysfc import ndgeom' 'ndgeom.measure_performance("corner", 2)' ...
43,756
def test_overwrite_any(): """Test that the alias for jsonmerge.strategies.Overwrite is set up properly""" schema = { "type": "object", "properties": { "a": {"type": "object", "mergeStrategy": "overwriteAny"}, "b": {"type": "number"}, }, } merger...
43,757
def genliq5(): """Generate liq5_f03 Testers. """ from teospy import liq5_f03 funs = liq5_f03.liq_g args1 = (300.,1e5) fargs = [(der+args1) for der in _DERS2] refs = [-5265.05056073,-393.062597709,0.100345554745e-2,-13.9354762020, 0.275754520492e-6,-0.452067557155e-12] fnames = 'l...
43,758
def retrieve_image(image_dir, message): """Actually change the content of message from video bytes to image bytes""" message_id = get_message_id(message.timestamp, message.topic) message_path = os.path.join(image_dir, message_id) if not os.path.exists(message_path): logging.error('message {} not...
43,759
def test_fixture_mock_home(tmp_path): """ The home folder is automatically monkeypatched to a temporary location. """ assert Path.home().parent == tmp_path assert os.path.expanduser("~") == str(Path.home())
43,760
def tridiagonalize_by_lanczos(P, m, k): """ Tridiagonalize matrix by lanczos method Parameters ---------- P : numpy array Target matrix q : numpy array Initial vector k : int Size of the tridiagonal matrix Returns ------- T : numpy array tridiagon...
43,761
def Polygon(xpoints, ypoints, name="", visible=True, strfmt="{:.5f}"): """ Polygon defined by point verticies. Returns --------- :class:`lxml.etree.Element` """ polygon = Element("Polygon", name=str(name), visible=str(visible).lower()) polygon.extend( [ Element("Poin...
43,762
def saveControlShapeToFile(name, icon, curve, filePath): """ Save a control curve to a yaml file. Args: curve (PyNode): A curve transform node containing one or more curve shapes. """ data = { 'name': name, 'icon': icon, 'sort': 100, 'curves': get...
43,763
def test_default_output(regtest): """default output should not change""" fv3fit.set_random_seed(0) config = fv3fit.ConvolutionalNetworkConfig() array = np.random.randn(2, 10, 10, 3) out = config.build(array, n_features_out=3) print_result(out, decimals=4, file=regtest)
43,764
def fake_index_by_name(name, pattern, timezone='+08:00'): """ generate a fake index name for index template matching ATTENTION: - rollover postfix is not supported in index template pattern - timezone is not supported cause tz is not well supported in python 2.x """ if patter...
43,765
def map_code(func): """ Map v to an Ontology code """ def mapper(v): if v is None: return v else: return func(str(v)) return mapper
43,766
def install_dvwa(instance, verbose: bool=True): """ Install and configure DVWA web server instance (object): This argmument define the lxc instance. verbose (bool, optional): This argument define if the function prompt some informations during his execution. Default to True. """ if update(instance,...
43,767
def card_update(handler, delete=False, review=False): """Update or Delete an exisiting Card.""" user_data = get_current_user(handler) if not user_data: return path = handler.request.path route_root = '/api/card/' err_response = '{}' if not path.startswith(route_root) and len(path) ...
43,768
def get(role_arn, principal_arn, assertion, duration): """Use the assertion to get an AWS STS token using Assume Role with SAML""" # We must use a session with a govcloud region for govcloud accounts if role_arn.split(':')[1] == 'aws-us-gov': session = boto3.session.Session(region_name='us-gov-west-...
43,769
def put_keyless(): """ Handle PUT requests for key-less database insertions """ # Check if the PUT request actually carries any data in its body to avoid # storing empty blocks under a key. start = time.clock() data = request.body.getvalue() if not data: return abort(400, "The re...
43,770
def find_nth(s, x, n): """ find the nth occurence in a string takes string where to search, substring, nth-occurence """ i = -1 for _ in range(n): i = s.find(x, i + len(x)) if i == -1: break return i
43,771
def parse_buffer(value: Union[Dict[str, Any], str]) -> str: """Parse value from a buffer data type.""" if isinstance(value, dict): return parse_buffer_from_dict(value) if is_json_string(value): return parse_buffer_from_json(value) return value
43,772
def cancel_job(request): # pylint: disable=unused-argument """Handler for `cancel_job/` request.""" if not job_ids: print('No jobs are running, nothing to cancel!') else: job_id = job_ids.popleft() print('CANCELING JOB:', job_id) long_job.cancel(job_id) return django.htt...
43,773
def test_nms_center_point_box_format_noclass(): """Test NMS - center-point box format.""" # -- boxes = np.array([ [0.5, 0.5, 1.0, 1.0], [0.5, 0.6, 1.0, 1.0], [0.5, 0.4, 1.0, 1.0], [0.5, 10.5, 1.0, 1.0], [0.5, 10.6, 1.0, 1.0], [0.5, 100.5, 1.0, 1.0] ]).asty...
43,774
def LO_solver_multiprocessing(H,N,dis, args,pipe): """ Allows to solve the Hamiltonian using several CPUs. Parameters ---------- H: arr Discretized Lutchyn-Oreg Hamiltonian built with Lutchyn_builder. N: int or arr Number of sites. If it is an ar...
43,775
def register_resources_items(self): """ Quicky register all possible routes to a `Resource` and/or an `Item` """ request_repo = Registry._repo['Request'] resources = Registry.known('Resource') items = Registry.known('Item') for resource in resources: if not resource.TABLE: ...
43,776
def check_lead_time_forecast_time(ds, copy_filename=None): """Check that ds has lead_time and forecast_time as dim and coords and valid_time as coord only.""" assert "lead_time" in ds.coords assert "lead_time" in ds.dims assert "forecast_time" in ds.dims assert "forecast_time" in ds.coords asser...
43,777
def test(nthreads,model,testsongs,npicks,winsize,finaldim,K,typecompress): """ Main function to do the testing Do the main pass with the number of given threads. Then, reads the tmp files, computes the score, delete the tmpfiles. INPUT - nthreads - number of threads to use - model ...
43,778
def _clip_grad(clip_type, clip_value, grad): """ Clip gradients. Inputs: clip_type(int): The way to clip, 0 for 'value', 1 for 'norm'. clip_value(float): Specifies how much to clip. grad (tuple[Tensor]): Gradients. Outputs: tuple[Tensor], clipped gradients. """ ...
43,779
def lightness_correlate(A, A_w, c, z): """ Returns the *Lightness* correlate :math:`J`. Parameters ---------- A : numeric or array_like Achromatic response :math:`A` for the stimulus. A_w : numeric or array_like Achromatic response :math:`A_w` for the whitepoint. c : numeric...
43,780
def get(url, body=None, cookies=None, auth_data=None): """ This function sends REST API GET request and prints some useful information for debugging. """ result = requests.get(url, cookies=cookies, params=body, auth=auth_data) print('GET request to {0}'.format(url)) print('Status code: {0...
43,781
def swap(numbers: List[int], first: int, second: int): """ Swaps two items in a list of numbers. :param numbers: is the list of numbers :param first: is the first index. :param second: is the second index. """ placeholder = numbers[first] numbers[first] = numbers[second] numbers[seco...
43,782
def _cmd_breaks(args): """List the targeted genes in which a copy number breakpoint occurs.""" cnarr = read_cna(args.filename) segarr = read_cna(args.segment) bpoints = do_breaks(cnarr, segarr, args.min_probes) logging.info("Found %d gene breakpoints", len(bpoints)) write_dataframe(args.output, ...
43,783
def fetch_file_from_guest(module, content, vm, username, password, src, dest): """ Use VMWare's filemanager api to fetch a file over http """ result = {'failed': False} tools_status = vm.guest.toolsStatus if tools_status == 'toolsNotInstalled' or tools_status == 'toolsNotRunning': result['fail...
43,784
def method_wrapper(m): """Generates a method from a `GrpcMethod` definition.""" if m.is_simple: def simple_method(self): """TODO: no docstring!""" return apply_transform( self.__service__, m.output_transform, grpc_call(self.__service__, m, unwrap(...
43,785
def handle_csp_report(report_data, session_id): """Processes incoming CSP reports.""" if not 'csp-report' in report_data: return csp_report_raw = report_data['csp-report'] logger.info("Received CSP report") logger.info("Session ID: {}".format(session_id)) logger.info("Report Data: {}".f...
43,786
def ReadFile(filename): """ description: Read program from file param {*} filename return {*} file """ input_file = open(filename, "r") result = [] while True: line = input_file.readline() if not line: break result.append(line) for line_index in ra...
43,787
def item_url(item): """Return a Markdown URL for the WCAG item.""" fragment = item["id"].split(":")[1] return url(item["handle"], f"https://www.w3.org/TR/WCAG21/#{fragment}")
43,788
def gen_nested_prop_getter(val_name, throws, klass): """ generates a nested property getter, it actually returns an _Internal object """ def _internal(self): try: getattr(self, val_name) except AttributeError: setattr(self, val_name, klass()) ...
43,789
def insert_cmds_db(cmds, timeline_id, db): """Insert the ``cmds`` into the ``db`` table 'cmds' with ``timeline_id``. Command parameters are also inserted into 'cmd_intpars' and 'cmd_fltpars' tables. ``timeline_id`` can be None to indicate non-load commands (from ground or autonomous). Each command...
43,790
async def test_dhcp_missing_hostname(hass): """Test we ignore missing hostnames.""" dhcp_watcher = dhcp.DHCPWatcher( hass, [{"domain": "mock-domain", "hostname": "nomatch*"}] ) packet = Ether(RAW_DHCP_REQUEST) packet[DHCP].options = [ ("message-type", 3), ("max_dhcp_size", ...
43,791
def quad_genz_keister(order, dist, rule=24): """ Genz-Keister quadrature rule. Examples: >>> abscissas, weights = quad_genz_keister( ... order=1, dist=chaospy.Iid(chaospy.Uniform(0, 1), 2)) >>> abscissas.round(2) array([[0.04, 0.04, 0.04, 0.5 , 0.5 , 0.5 , 0.96, 0.96...
43,792
def get_maf(variant): """ Gets the MAF (minor allele frequency) tag from the info field for the variant. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ return variant.INFO.get("MAF")
43,793
def check_channels(file_path_address: str, image_type: str): """Manual verifier to determine which images to further clean or remove. This checks to see if there is a consistent third dimension in each of the images. Paramters: --------- file_path_address: str Address of where all jpgs are ...
43,794
def break_large_contigs(contigs, break_t, verbose=False): """Break large contigs in half until all contigs are under the size threshold.""" # initialize a heapq of contigs and lengths contig_heapq = [] for ctg in contigs: ctg_len = ctg.end - ctg.start heapq.heappush(contig_heapq, (-ctg_len, ctg)) ...
43,795
def test_already_consildated(fake_results): """Make sure we can consolidate before preparing.""" results = formatting.consolidate(fake_results) with patch.object(formatting, "consolidate") as patched: formatting.prepare_results(results) assert not patched.called
43,796
def create_content(address, owner, content): """ Create a new page with some content. Args: address (str): the new page's absolute address. owner (Account): the owner of the page to be created. content (str): the Markdown content of the first revision. Returns: page (Pa...
43,797
def update_op_dims_mapping_by_default_dist_impl(op_dist_attr): """Each operator has a default distributed operator, only allowed to be sharded in batch dimension.""" changed = False op_desc = op_dist_attr.get_owner_op().desc # The following statement will be replaced by a more elegent way if op_desc...
43,798
def test_transition_events_fire(evented_switch): """ Assert that :meth:`~decorstate.Transition.before`, :meth:`~decorstate.Transition.after`, and :meth:`~decorstate.Transition.exit` transition events all fire when performing state transitions. """ assert not evented_switch.before_event.is_set() ...
43,799