content
stringlengths
22
815k
id
int64
0
4.91M
def dnu_sspec_model(params, xdata, ydata, weights): """ Fit 1D function to cut through ACF for decorrelation bandwidth. Default function has is exponential with dnu measured at half power amp = Amplitude dnu = bandwidth at 1/2 power wn = white noise spike in ACF cut """ # # if...
5,352,200
def _write_cnv(catalog, filename, phase_mapping=None, ifx_list=None, weight_mapping=None, default_weight=0): """ Write a :class:`~obspy.core.event.Catalog` object to CNV event summary format (used as event/pick input by VELEST program). .. warning:: This function should NOT be ca...
5,352,201
def _check_draw_graph(graph_file): """Check whether the specified graph file should be redrawn. Currently we use the following heuristic: (1) if graph is older than N minutes, redraw it; (2) if admin has active session(s), redraw on every cron run (we detect this by ajax active timestamp). We cou...
5,352,202
def random_shadow(image): """ Function to add shadow in images randomly at random places, Random shadows meant to make the Convolution model learn Lanes and lane curvature patterns effectively in dissimilar places. """ if np.random.rand() < 0.5: # (x1, y1) and (x2, y2) forms a line ...
5,352,203
def build_channel_header(type, tx_id, channel_id, timestamp, epoch=0, extension=None, tls_cert_hash=None): """Build channel header. Args: type (common_pb2.HeaderType): type tx_id (str): transaction id channel_id (str): channel id ...
5,352,204
def get_character(data, index): """Return one byte from data as a signed char. Args: data (list): raw data from sensor index (int): index entry from which to read data Returns: int: extracted signed char value """ result = data[index] if result > 127: result -= ...
5,352,205
def df_to_embed(df, img_folder): """ Extract image embeddings, sentence embeddings and concatenated embeddings from dataset and image folders :param df: dataset file to use :param img_folder: folder where the corresponding images are stored :return: tuple containing sentence embeddings, image embedding...
5,352,206
def load_release_data(): """ Load the release data. This always prints a warning if the release data contains any release data. :return: """ filen = path.join(PATH_ROOT, PATH_RELEASE_DATA) try: with open(filen, "r") as in_file: data = pickle.load(in_file) if dat...
5,352,207
def generate_player_attributes(): """ Return a list of 53 dicts with player attributes that map to Player model fields. """ # Get player position distribution position_dist = get_position_distribution() # Get player attribute distribution attr_dist = get_attribute_distribution() # G...
5,352,208
def colour_from_loadings(loadings, maxLoading=None, baseColor="#FF0000"): """Computes colors given loading values. Given an array of loading values (loadings), returns an array of colors that graphviz can understand that can be used to colour the nodes. The node with the greatest loading uses baseColor...
5,352,209
def mock_dao(monkeypatch): """Create a mock database table.""" _hazard_1 = RAMSTKHazardRecord() _hazard_1.revision_id = 1 _hazard_1.function_id = 1 _hazard_1.hazard_id = 1 _hazard_1.assembly_effect = "" _hazard_1.assembly_hri = 20 _hazard_1.assembly_hri_f = 4 _hazard_1.assembly_mitig...
5,352,210
def determineDocument(pdf): """ Scans the pdf document for certain text lines and determines the type of investment vehicle traded""" if 'turbop' in pdf or 'turboc' in pdf: return 'certificate' elif 'minil' in pdf: return 'certificate' elif 'call' in pdf or 'put' in pdf: return '...
5,352,211
def setup_parser() -> argparse.ArgumentParser: """Set default values and handle arg parser""" parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="wlanpi-core provides backend services for the WLAN Pi. Read the manual with: man wlanpi-core", ) ...
5,352,212
def deserialize_api_types(class_name: str, d: dict) -> Any: """ Deserializes an API type. Allowed classes are defined in: * :mod:`maestral.core` * :mod:`maestral.model` * :mod:`maestral.exceptions` :param class_name: Name of class to deserialize. :param d: Dictionary of serializ...
5,352,213
def runner() -> CliRunner: """Fixture for invoking command-line interfaces.""" return testing.CliRunner()
5,352,214
def cal_quant_model_accuracy(model, gpu_index, val_loader, args, config_file, record_file): """Save the quantized model and infer the accuracy of the quantized model.""" torch.save({'state_dict': model.state_dict()}, os.path.join(TMP, 'model_best.pth.tar')) print('==> AMCT step3: save_quant_retrain_model..'...
5,352,215
def give_color_to_direction_dynamic(dir): """ Assigns a color to the direction (dynamic-defined colors) Parameters -------------- dir Direction Returns -------------- col Color """ dir = 0.5 + 0.5 * dir norm = mpl.colors.Normalize(vmin=0, vmax=1) nodes =...
5,352,216
def pfilter(plugins, plugin_type=Analyser, **kwargs): """ Filter plugins by different criteria """ if isinstance(plugins, models.Plugins): plugins = plugins.plugins elif isinstance(plugins, dict): plugins = plugins.values() logger.debug('#' * 100) logger.debug('plugin_type {}'.format...
5,352,217
def tmux_session_detection(session_name: str) -> bool: """ Function checks if session already exists. """ cmd = ['tmux', 'has-session', '-t', session_name] result = subprocess.call(cmd, stderr=subprocess.DEVNULL) if result == 0: return True else: return False
5,352,218
def prune_arms(active_arms, sample_arms, verbose=False): """Remove all arms from ``active_arms`` that have an allocation less than two standard deviations below the current best arm. :param active_arms: list of coordinate-tuples corresponding to arms/cohorts currently being sampled :type active_arms: list ...
5,352,219
def prepare_string(dist, digits=None, exact=False, tol=1e-9, show_mask=False, str_outcomes=False): """ Prepares a distribution for a string representation. Parameters ---------- dist : distribution The distribution to be stringified. digits : int or None The p...
5,352,220
def verifier(func): """ Creates a `Verifier` by given specifier. Parameters ---------- func: callable, [callable], (str, callable), [(str, callable)] The specifier of `Verifier` which can take various forms and determines the attributes and behaviors of `Verifier`. When it i...
5,352,221
def obtain_celeba_images(n_people:int) -> pd.DataFrame: """ Unique labels: 10,177 It is expected for the structure to be as following: <CELEBA_PATH>/ ├─ identity_CelebA.txt ├─ img_align_celeba/ ├─<images> * 'identity_CelebA.txt' is the downloaded identity text annotat...
5,352,222
def assert_equal( actual: List[Literal["y4", "y3", "y2", "y1"]], desired: List[Literal["y4", "y3", "y2", "y1"]], ): """ usage.statsmodels: 1 """ ...
5,352,223
def get_add_diff_file_list(git_folder): """List of new files. """ repo = Repo(str(git_folder)) repo.git.add("sdk") output = repo.git.diff("HEAD", "--name-only") return output.splitlines()
5,352,224
def _save_qr_code(qr_code: str, filepath: str = qr_path, filename: str = qr_name) -> str: """Use it for save QrCode from web.whatsapp.com (copied as string) to PNG file to your path and your filename. :param qr_code: QrCode string from web.whatsapp.com. :param filepath: Your path for saving file. :...
5,352,225
def has_read_perm(user, group, is_member, is_private): """ Return True if the user has permission to *read* Articles, False otherwise. """ if (group is None) or (is_member is None) or is_member(user, group): return True if (is_private is not None) and is_private(group): return False ...
5,352,226
def _create_docker_build_ctx( launch_project: LaunchProject, dockerfile_contents: str, ) -> str: """Creates build context temp dir containing Dockerfile and project code, returning path to temp dir.""" directory = tempfile.mkdtemp() dst_path = os.path.join(directory, "src") assert launch_project...
5,352,227
def normalize_df(dataframe, columns): """ normalized all columns passed to zero mean and unit variance, returns a full data set :param dataframe: the dataframe to normalize :param columns: all columns in the df that should be normalized :return: the data, centered around 0 and divided by it's standa...
5,352,228
def PeekTrybotImage(chromeos_root, buildbucket_id): """Get the artifact URL of a given tryjob. Args: buildbucket_id: buildbucket-id chromeos_root: root dir of chrome os checkout Returns: (status, url) where status can be 'pass', 'fail', 'running', and url looks like: gs://chrom...
5,352,229
def frozenset_code_repr(value: frozenset) -> CodeRepresentation: """ Gets the code representation for a frozenset. :param value: The frozenset. :return: It's code representation. """ return container_code_repr("frozenset({", "})", ...
5,352,230
def SRMI(df, n): """ MI修正指标 Args: df (pandas.DataFrame): Dataframe格式的K线序列 n (int): 参数n Returns: pandas.DataFrame: 返回的DataFrame包含2列, 是"a", "mi", 分别代表A值和MI值 Example:: # 获取 CFFEX.IF1903 合约的MI修正指标 from tqsdk import TqApi, TqSim from tqsdk.ta import SR...
5,352,231
def init_db(database_url: PostgresDsn) -> None: """ Runs the migrations and creates all of the database objects. """ alembic_config = get_alembic_config(database_url) upgrade_db(alembic_config)
5,352,232
def get_purchase_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(Purchase, *args, **kwargs)
5,352,233
def depart_delete(request): """ 删除部门 """ nid = request.GET.get('nid') models.Department.objects.filter(id=nid).delete() return redirect("/depart/list/")
5,352,234
def create_condor_scheduler(name, host, username=None, password=None, private_key_path=None, private_key_pass=None): """ Creates a new condor scheduler Args: name (str): The name of the scheduler host (str): The hostname or IP address of the scheduler username (str, optional): The u...
5,352,235
def edit_stack( action : Optional[List[str]] = None, debug : bool = False, **kw ): """ Open docker-compose.yaml or .env for editing """ from meerschaum.config._edit import general_edit_config if action is None: action = [] files = { 'compose' : STACK_C...
5,352,236
def check_compare_list_val(list_comp, name=None): """ Compares list values. Yields warning, if list values are different Parameters ---------- list_comp : list (of floats) List of float values for comparison name : str (optional) Name of list / parameters """ for i in r...
5,352,237
def setenv(): """ Set some environment variables for basic operation. """ # Set version string os.environ['RQ_VERSION'] = "0.2.0" # Set vendor string os.environ['RQ_VENDOR'] = "UNIT" # Standardise some environment variables across systems. # Usernames will always be stored as lowercase for compatibility. if ...
5,352,238
def dot_to_underscore(instring): """Replace dots with underscores""" return instring.replace(".", "_")
5,352,239
def get_birthday_weekday(current_weekday: int, current_day: int, birthday_day: int) -> int: """Return the day of the week it will be on birthday_day, given that the day of the week is current_weekday and the day of the year is current_day. current_weekday is the current day of ...
5,352,240
def matlab_kcit(X: np.ndarray, Y: np.ndarray, Z: np.ndarray, seed: int = None, matlab_engine_instance=None, installed_at=None): """Python-wrapper for original implementation of KCIT by Zhang et al. (2011) References ---------- Zhang, K., Peters, J., Janzing, D., & Schölkopf, B. (2011). Kernel-based Con...
5,352,241
def _check(err, msg=""): """Raise error for non-zero error codes.""" if err < 0: msg += ': ' if msg else '' if err == _lib.paUnanticipatedHostError: info = _lib.Pa_GetLastHostErrorInfo() hostapi = _lib.Pa_HostApiTypeIdToHostApiIndex(info.hostApiType) msg += 'U...
5,352,242
def RunPackage(output_dir, target, package_path, package_name, package_deps, package_args, args): """Copies the Fuchsia package at |package_path| to the target, executes it with |package_args|, and symbolizes its output. output_dir: The path containing the build output files. target: The deploym...
5,352,243
def make_flood_fill_unet(input_fov_shape, output_fov_shape, network_config): """Construct a U-net flood filling network. """ image_input = Input(shape=tuple(input_fov_shape) + (1,), dtype='float32', name='image_input') if network_config.rescale_image: ffn = Lambda(lambda x: (x - 0.5) * 2.0)(imag...
5,352,244
def FRAC(total): """Returns a function that shows the average percentage of the values from the total given.""" def realFrac(values, unit): r = toString(sum(values) / len(values) / total * 100) r += '%' if max(values) > min(values): r += ' avg' return [r] retu...
5,352,245
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: return (None, None) low = ints[0] high = ints[0] for i in ints: if i < low: low = i ...
5,352,246
def SearchOldMessages(p_webSocketSession, p_requestMessage, p_responseMessage): """Handles search old messages message requested by a client Args: p_webSocketSession (WSHandler): the websocket client that requested this. p_requestMessage (dict): the request message. p_re...
5,352,247
def gen_sweep_pts(start: float=None, stop: float=None, center: float=0, span: float=None, num: int=None, step: float=None, endpoint=True): """ Generates an array of sweep points based on different types of input arguments. Boundaries of the array can be specified usin...
5,352,248
def set_lang_owner(cursor, lang, owner): """Set language owner. Args: cursor (cursor): psycopg2 cursor object. lang (str): language name. owner (str): name of new owner. """ query = "ALTER LANGUAGE \"%s\" OWNER TO \"%s\"" % (lang, owner) executed_queries.append(query) cu...
5,352,249
def rstrip_tuple(t: tuple): """Remove trailing zeroes in `t`.""" if not t or t[-1]: return t right = len(t) - 1 while right > 0 and t[right - 1] == 0: right -= 1 return t[:right]
5,352,250
def _calc_active_face_flux_divergence_at_node(grid, unit_flux_at_faces, out=None): """Calculate divergence of face-based fluxes at nodes (active faces only). Given a flux per unit width across each face in the grid, calculate the net outflux (or influx, if negative) divided by cell area, at each node that ...
5,352,251
def get_EL(overlaps): """ a) 1 +++++++++|---|--- 2 --|---|++++++++++ b) 1 ---|---|+++++++++++++ 2 ++++++++++|---|--- """ EL1a = overlaps['query_start'] EL2a = overlaps['target_len'] - overlaps['target_end'] - 1 EL1b = overlaps['query_len'] - overlaps['query_...
5,352,252
def get_line(prompt: str = '') -> Effect[HasConsole, NoReturn, str]: """ Get an `Effect` that reads a `str` from stdin Example: >>> class Env: ... console = Console() >>> greeting = lambda name: f'Hello {name}!' >>> get_line('What is your name? ').map(greeting).run(Env()...
5,352,253
def reconstruct_wave(*args: ndarray, kwargs_istft, n_sample=-1) -> ndarray: """ construct time-domain wave from complex spectrogram Args: *args: the complex spectrogram. kwargs_istft: arguments of Inverse STFT. n_sample: expected audio length. Returns: audio (numpy) "...
5,352,254
def test_inc(): """Verify that 'inc' actually works!""" assert inc(3) == 4
5,352,255
def perfect_score(student_info): """ :param student_info: list of [<student name>, <score>] lists :return: first `[<student name>, 100]` or `[]` if no student score of 100 is found. """ # first = [] student_names = [] score = [] print (student_info) for name in student...
5,352,256
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--cl_kernel_dir", type=str, default="./mace/ops/opencl/cl/", help="The cl kernels directory.") parser.add_argument( "--output_path", type=str, ...
5,352,257
def get_composite_component(current_example_row, cache, model_config): """ maps component_id to dict of {cpu_id: False, ...} :param current_example_row: :param cache: :param model_config: :return: nested mapping_dict = { #there can be multiple components component_id = { #componen...
5,352,258
def presigned_url_both(filename, email): """ Return presigned urls both original image url and thumbnail image url :param filename: :param email: :return: """ prefix = "photos/{0}/".format(email_normalize(email)) prefix_thumb = "photos/{0}/thumbnails/".format(email_normalize(email)) ...
5,352,259
def check_if_event_exists(service, new_summary): """ Description: checks if the event summary exists using a naive approach """ event_exists = False page_token = None calendarId = gcalendarId while True: events = ( service.events().list(calendarId=calendarId, pageToken=pa...
5,352,260
def retry(func, *args, **kwargs): """ You can use the kwargs to override the 'retries' (default: 5) and 'use_account' (default: 1). """ global url, token, parsed, conn retries = kwargs.get('retries', 5) use_account = 1 if 'use_account' in kwargs: use_account = kwargs['use_account...
5,352,261
def eval_f(angles, data=None): """ function to minimize """ x1, x2, d, zt, z, alpha, beta, mask, b1, b2 = data thetaxm, thetaym, thetazm, thetaxp, thetayp, thetazp = angles rm = rotation(thetaxm, thetaym, thetazm) rp = rotation(thetaxp, thetayp, thetazp) x1r = rm.dot(x1.T).T x2r = rp...
5,352,262
def clamp(min_v, max_v, value): """ Clamps a value between a min and max value Args: min_v: Minimum value max_v: Maximum value value: Value to be clamped Returns: Returns the clamped value """ return min_v if value < min_v else max_v if value > max_v else value
5,352,263
def collatz(n): """Sequence generation.""" l = [] while n > 1: l.append(n) if n % 2 == 0: n = n / 2 else: n = (3 * n) + 1 l.append(n) return l
5,352,264
def print_configs(configs) -> None: """Print available configurations.""" print('Available configurations:') for i, config in enumerate(configs): domain = find_by_repr(hook._domains, config.domain) print(f'{i}: {config.name}, using domain "{domain.name}"')
5,352,265
def print_stype_pre(st,fh): """ Print header and paragraph starts """ if st == 'p': print ("<p>", file = fh) elif st == 'h1': print ("<h1>", file = fh)
5,352,266
def _load_tokenizer(path, **kwargs): """TODO: add docstring.""" if not os.path.isdir(path): raise ValueError( "transformers.AutoTokenizer.from_pretrained" " should be called with a path to a model directory." ) return transformers.AutoTokenizer.from_pretrained(path, ...
5,352,267
def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2 ** np.arange(3, 6), stride=16): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size]) - 1 ...
5,352,268
def number_format(number_string, fill=2): """ add padding zeros to make alinged numbers ex. >>> number_format('2') '02' >>> number_format('1-2') '01-02' """ output = [] digits_spliter = r'(?P<digit>\d+)|(?P<nondigit>.)' for token in [m.groups() for m in re.finditer(digits_...
5,352,269
def box_postp2use(pred_boxes, nms_iou_thr=0.7, conf_thr=0.5): """Postprocess prediction boxes to use * Non-Maximum Suppression * Filter boxes with Confidence Score Args: pred_boxes (np.ndarray dtype=np.float32): pred boxes postprocessed by yolo_output2boxes. shape: [cfg.cell_size * cfg.c...
5,352,270
def plotPolarPoint(axe, colorspace, target1, target2, color=None, marker="+"): """Plots polar points which is read from auxiliary_line.json. Args: axe (matplotlib.axes.Axes): Target axe for plotting. colorspace (str): Group key defined in json. target1 (str): Array data key defined under "colorsp...
5,352,271
def many_hsvs_to_rgb(hsvs): """Combine list of hsvs otf [[(h, s, v), ...], ...] and return RGB list.""" num_strips = len(hsvs[0]) num_leds = len(hsvs[0][0]) res = [[[0, 0, 0] for ll in range(num_leds)] for ss in range(num_strips)] for strip in range(num_strips): for led in range(num_leds): ...
5,352,272
def deduplicate(input_file, output_file, columns): """De-duplicate rows in CSV based on columns specified (comma separated)""" df = pd.read_csv(input_file) columns = [x.strip() for x in columns.split(",")] if len(columns) < 1: print("No columns specified") all_ok = True for column in...
5,352,273
def _convert_paths_to_flask(transmute_paths): """flask has it's own route syntax, so we convert it.""" paths = [] for p in transmute_paths: paths.append(p.replace("{", "<").replace("}", ">")) return paths
5,352,274
def check_isup(k, return_client=None): """ Checks ping and returns status Used with concurrent decorator for parallel checks :param k: name to ping :param return_client: to change return format as '{k: {'comments': comments}}' :return(str): ping ok / - """ if is_up(k): comments ...
5,352,275
def histogram(measurements, dataset_name: str, plt=pyplot, show: bool=True): """ Shows a histogram with a fitted normal distribution. Example: histogram(np.array([1, 2, 3, 4, 4, 5, 5, 6, 7]), "X") :param measurements: The measurements to create a histogram for. :param dataset_name: The of ...
5,352,276
def percent_uppercase(text): """Calculates percentage of alphabetical characters that are uppercase, out of total alphabetical characters. Based on findings from spam.csv that spam texts have higher uppercase alphabetical characters (see: avg_uppercase_letters())""" alpha_count = 0 uppercase_count =...
5,352,277
def get_move() -> tuple: """ Utility function to get the player's move. :return: tuple of the move """ return get_tuple('What move to make?')
5,352,278
def database(): """A Database shortcut can auto close.""" db = Database() yield db db.close()
5,352,279
def _delete_file_if_exists(filepath): """Delete the file if it exists. :param filepath: The file path. """ if os.path.exists(filepath): os.remove(filepath)
5,352,280
def list_supported_parset_settings(): """List the ``YandaSoft`` parset settings that are currently supported by ``dstack``. This function uses logger level INFO to return the supported settings Parameters ========== Returns ======= Prints out the supported settings: log """ print_...
5,352,281
def set_value(parent, type, name, value) : """ Sets a value in the format Mitsuba Renderer expects """ curr_elem = etree.SubElement(parent, type) curr_elem.set("name", name) curr_elem.set("id" if type in ["ref", "shapegroup"] else "value", value) # The can be an id return curr_elem
5,352,282
def create_bst(nodes) -> BST: """Creates a BST from a specified nodes.""" root = BST(nodes[0]) for i in range(1, len(nodes)): root.insert(nodes[i]) return root
5,352,283
def get_dec_arch(gen: Generator) -> nn.Sequential: """ Get decoder architecture associated with given generator. Args: gen (Generator): Generator associated with the decoder. Returns: nn.Sequential: Decoder architecture. """ # As defined in the paper. len_z = len(gen.latent...
5,352,284
def add_page_to_xml(alto_xml, alto_xml_page, page_number=0): """ Add new page to end of alto_xml or replace old page. """ # If book empty if (alto_xml == None): page_dom = xml.dom.minidom.parseString(alto_xml_page) page_dom.getElementsByTagName("Page")[0].setAttribute("ID"...
5,352,285
def calculate_performance(all_data): """ Calculates the performance metrics as found in "benchmarks" folder of scikit-optimize and prints them in console. Parameters ---------- * `all_data`: dict Traces data collected during run of algorithms. For more details, see 'evaluate_opt...
5,352,286
def connected_components(num_nodes, Ap, Aj, components): """connected_components(int const num_nodes, int const [] Ap, int const [] Aj, int [] components) -> int""" return _amg_core.connected_components(num_nodes, Ap, Aj, components)
5,352,287
def test_ft_ovr_counters(): """ Author: Ramprakash Reddy ([email protected]) Verify tx_ovr and rx_ovr counters should not increment. Verify rx_err counters should increment, when framesize is more than MTU. """ flag = 1 properties = ['rx_ovr','tx_ovr'] intf_data.port_l...
5,352,288
def main() -> NoReturn: """Run intersect.""" result = intersect( linked_list_1=[13, 4, 12, 27, ], linked_list_2=[29, 23, 82, 11, 12, 27, ] ) print(result)
5,352,289
def get_drm_version(): """ Return DRM library version. Returns: str: DRM library version. """ path = _join(PROJECT_DIR, "CMakeLists.txt") with open(path, "rt") as cmakelists: for line in cmakelists: if line.startswith("set(ACCELIZEDRM_VERSION "): vers...
5,352,290
def pmx(p1, p2): """Perform Partially Mapped Crossover on p1 and p2.""" return pmx_1(p1, p2), pmx_1(p2, p1)
5,352,291
def get_met_rxn_names(raw_data_dir: str, model_name: str) -> tuple: """ Gets the names of metabolites and reactions in the model. Args: raw_data_dir: path to folder with the raw data. model_name: named of the model. Returns: A list with the metabolite names and another with the...
5,352,292
def main(): """ The program will match the DNA with the DNA-substring and find out the most similar DNA-substring in the DNA """ long = input('Please give me a DNA sequence to search: ') short = input('What DNA sequence would you like to match? ') result = match(long, short) print ('The ...
5,352,293
def test_convert_from_pip_fail_if_no_egg(): """Parsing should fail without `#egg=`. """ dep = 'git+https://github.com/kennethreitz/requests.git' with pytest.raises(ValueError) as e: dep = Requirement.from_line(dep).as_pipfile() assert 'pipenv requires an #egg fragment for vcs' in str(e)
5,352,294
def meshparameterspace(shape=(20, 20), psi_limits=(None, None), eta_limits=(None, None), psi_spacing="linear", eta_spacing="linear", user_spacing=(None, None)): """Builds curvilinear mesh inside parameter space. :param ...
5,352,295
def write_file(file_path='', data=''): """write a file from a string.""" fid = codecs.open(file_path, 'w', 'utf-8') try: fid.write(data) except (UnicodeEncodeError, UnicodeDecodeError): fid.write('error: could not write file') fid.close()
5,352,296
def get_key_information(index, harness_result: HarnessResult, testbed_parser, esapi_instance: ESAPI): """ 1. key_exception_dic是以引擎名为key的字典,若能提取错误信息,value为引擎的关键报错信息,若所有引擎均没有报错信息,则value为引擎的完整输出 返回[double_output_id, engine_name, key_exception_dic, api_name, 过滤类型]。过滤类型分为两种:第一类型是指异常结果 存在错误信息,第二类型是指异常结果...
5,352,297
def prepare_data(): """Merge tables generated from simulated data, where columns 'fac1', 'fac2', 'fac3' from **table_2** contain the factor ids in **table_1** and columns 'x1', 'x2' from **table_2** contain control ids in **table_3**. The output are one pandas dataframe (saved as pickle) per factor...
5,352,298
def open_image(asset): """Opens the image represented by the given asset.""" try: asset_path = asset.get_path() except NotImplementedError: return Image.open(StringIO(asset.get_contents())) else: return Image.open(asset_path)
5,352,299