content
stringlengths
22
815k
id
int64
0
4.91M
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings"): """Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, s...
5,353,500
def onQQMessage(bot, contact, member, content): """ QQBot 全局调用入口 """ # print(bot) # print(contact) # print(member) # print(content) # 获取群名称 group_name = str(contact) group_name = group_name[2:-1] # print(group_name) # 只接收指定群消息 if contact.ctype == 'group' and group_name ==...
5,353,501
def find_version(infile): """ Given an open file (or some other iterator of lines) holding a configure.ac file, find the current version line. """ for line in infile: m = re.search(r'AC_INIT\(\[tor\],\s*\[([^\]]*)\]\)', line) if m: return m.group(1) return None
5,353,502
def linear_warmup_decay(warmup_steps, total_steps, cosine=True, linear=False): """ Linear warmup for warmup_steps, optionally with cosine annealing or linear decay to 0 at total_steps """ # check if both decays are not True at the same time assert not (linear and cosine) def fn(step): ...
5,353,503
def query_anumbers(bbox,bbox2,bounds2): """ Queries anumbers of the reports within region defined Args: `bbox`= bounds of the region defined Returns: `anumberscode`=list of anumbers """ try: collars_file='http://geo.loop-gis.org/geoserver/loop/wfs?service=WFS&version=1.0....
5,353,504
def Parse(spec_name, arg_r): # type: (str, args.Reader) -> args._Attributes """Parse argv using a given FlagSpec.""" spec = FLAG_SPEC[spec_name] return args.Parse(spec, arg_r)
5,353,505
def go_repositories(): """This Gazelle-generated macro defines repositories for the Go modules in //go.mod.""" go_repository( name = "co_honnef_go_tools", importpath = "honnef.co/go/tools", sum = "h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=", version = "v0.0.1-2020.1.4", ...
5,353,506
def get_path_url(path: PathOrString) -> str: """Covert local path to URL Arguments: path {str} -- path to file Returns: str -- URL to file """ path_obj, path_str = get_path_forms(path) if is_supported_scheme(path_str): return build_request(path_str) return path_ob...
5,353,507
def process_keyqueue(codes, more_available): """ codes -- list of key codes more_available -- if True then raise MoreInputRequired when in the middle of a character sequence (escape/utf8/wide) and caller will attempt to send more key codes on the next call. returns (list of input, list ...
5,353,508
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]: """ Given labels and a constraint type, returns the allowed transitions. It will additionally include transitions for the start and end states, which are used by the conditional random field. # Parameters...
5,353,509
def get_args(**kwargs): """ """ cfg = deepcopy(kwargs) parser = argparse.ArgumentParser( description="Train the Model on CINC2019", formatter_class=argparse.ArgumentDefaultsHelpFormatter) # parser.add_argument( # "-l", "--learning-rate", # metavar="LR", type=float, na...
5,353,510
def initialize(cfg, args): """ purpose: load information and add to config """ if cfg.sessionId in (None, '') or cfg.useSessionTimestamp is True: cfg.useSessionTimestamp = True cfg.sessionId = utils.dateStr30(time.localtime()) else: cfg.useSessionTimestamp = False # MERGE WITH P...
5,353,511
def modulated_count_dist(count_dist, mult_gain, add_gain, samples): """ Generate distribution samples from the modulated count process with additive and multiplicate gains. .. math:: P_{mod}(n|\lambda) = \int P_{count}(n|G_{mul}\lambda + G_{add}) P(G_{mu]}, G_{add}) \mathrm{d}G_{mul} \mathr...
5,353,512
def simple_linear(parent = None, element_count=16, element_pitch=7e-3): """1D line of elements, starting at xyz=0, along y, with given element_pitch Parameters ---------- parent : handybeam.world.World the world to give to this array as parent element_count : int count of ...
5,353,513
def for_all_methods(decorator, exclude_methods=None): """ Class decorator """ if exclude_methods is None: exclude_methods = [] def decorate(cls): for attr in cls.__dict__: if ( callable(getattr(cls, attr)) and attr not in DO_NOT_DECORATE_M...
5,353,514
def download_if_not_there(file, url, path, force=False, local_file=None): """Downloads a file from the given url if and only if the file doesn't already exist in the provided path or ``force=True`` Args: file (str): File name url (str): Url where the file can be found (without the filename)...
5,353,515
def test_atomic_g_month_min_exclusive_nistxml_sv_iv_atomic_g_month_min_exclusive_1_3(mode, save_output, output_format): """ Type atomic/gMonth is restricted by facet minExclusive with value --01. """ assert_bindings( schema="nistData/atomic/gMonth/Schema+Instance/NISTSchema-SV-IV-atomic-gMon...
5,353,516
def _kuramoto_sivashinsky_old(dimensions, system_size, dt, time_steps): """ This function INCORRECTLY simulates the Kuramoto–Sivashinsky PDE It is kept here only for historical reasons. DO NOT USE UNLESS YOU WANT INCORRECT RESULTS Even though it doesn't use the RK4 algorithm, it is bundled with the ot...
5,353,517
def get_geneids_of_user_entity_ids(cursor, unification_table, user_entity_ids): """ Get the Entrez Gene IDs of targets using their BIANA user entity ids """ query_geneid = ("""SELECT G.value, G.type FROM externalEntityGeneID G, {} U WHERE U.externalEntityID...
5,353,518
def create_table(dataset_id, table_id, schema_list, client_bq): """ Create a table if it does not exist, form a schema :param dataset_id: :param table_id: :param schema_list: Columns definitions separate by "," character, A column definition is NAME: TYPE :param client_bq: :return: ...
5,353,519
def alpha_015(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: (-1\*sum(rank(correlation(rank(high), rank(volume), 3)), 3)) """ enddate = to_date_str(enddate) func_name = ...
5,353,520
def query_process( pheader, pworkers, pworker, qry_template, tqueue ): """ A sub-process which constructs and executes queries in a loop until all rows from file are exhausted """ if DEBUG: print("Init Separate Process: ",pworker) conn = get_connection(thread_id=pworker) t_start...
5,353,521
def get_path(root, path): """ Shortcut for ``os.path.join(os.path.dirname(root), path)``. :param root: root path :param path: path to file or folder :returns: path to file or folder relative to root """ return os.path.join(os.path.dirname(root), path)
5,353,522
def int_array_to_hex(iv_array): """ Converts an integer array to a hex string. """ iv_hex = '' for b in iv_array: iv_hex += '{:02x}'.format(b) return iv_hex
5,353,523
def minimal_sphinx_app( configuration=None, sourcedir=None, with_builder=False, raise_on_warning=False ): """Create a minimal Sphinx environment; loading sphinx roles, directives, etc.""" class MockSphinx(Sphinx): """Minimal sphinx init to load roles and directives.""" def __init__(self, c...
5,353,524
def calc_Mo_from_M(M, C=C): """ Calculate seismic moment (Mo) from moment magnitude (M) given a scaling law. C is a scaling constant; should be set at 6, but is defined elsewhere in the module so that all functions using it share a value. """ term1 = 3/2. * C * (np.log(2) + np.log(5) ) ...
5,353,525
def main(): """ stdin: tsv stdout: jsonl """ parser = argparse.ArgumentParser() parser.add_argument('--pas-dir', required=True, type=str, help='path to directory where tagged knp files are located') parser.add_argument('--skipped-file', required=True, type=str, ...
5,353,526
def resource_path(*args): """ Get absolute path to resource, works for dev and for PyInstaller """ base_path = getattr(sys, '_MEIPASS', path.dirname(path.abspath(__file__))) return path.join(base_path, *args)
5,353,527
def _file_format_from_filename(filename): """Determine file format from its name.""" import pathlib filename = pathlib.Path(filename).name return _file_formats[filename] if filename in _file_formats else ""
5,353,528
def r2k(value): """ converts temperature in R(degrees Rankine) to K(Kelvins) :param value: temperature in R(degrees Rankine) :return: temperature in K(Kelvins) """ return const.convert_temperature(value, 'R', 'K')
5,353,529
def test_get_params(tfm): """Test the get_params method.""" for dname in ['aperiodic_params', 'peak_params', 'error', 'r_squared', 'gaussian_params']: assert np.any(tfm.get_params(dname)) if dname == 'aperiodic_params': for dtype in ['offset', 'exponent']: assert np...
5,353,530
def add_version(project, publication_id): """ Takes "title", "filename", "published", "sort_order", "type" as JSON data "type" denotes version type, 1=base text, 2=other variant Returns "msg" and "version_id" on success, otherwise 40x """ request_data = request.get_json() if not request_data...
5,353,531
def verifyPinConnections(): """ Runs through each LED on the display to verify its function Cycle order should be (right to left) White, Red, Yellow, Blue, Green. The same order they are in the perf board Notes ----- This is largely just so I can be sure that the LEDs still work. """ ...
5,353,532
def to_decorator(wrapped_func): """ Encapsulates the decorator logic for most common use cases. Expects a wrapped function with compatible type signature to: wrapped_func(func, args, kwargs, *outer_args, **outer_kwargs) Example: @to_decorator def foo(func, args, kwargs): print(fu...
5,353,533
def _get_unit(my_str): """ Get unit label from suffix """ # matches = [my_str.endswith(suffix) for suffix in _known_units] # check to see if unit makes sense if not any(matches): raise KeyError('Unit unit not recognized <{}>!'.format(my_str)) # pick unit that matches, with prefix ...
5,353,534
def spec_augment(spectrogram, time_mask_para=70, freq_mask_para=20, time_mask_num=2, freq_mask_num=2): """ Provides Augmentation for audio Args: spectrogram, time_mask_para, freq_mask_para, time_mask_num, freq_mask_num spectrogram (torch.Tensor): spectrum time_mask_para (int): Hyper Paramet...
5,353,535
def scale(a: tuple, scalar: float) -> tuple: """Scales the point.""" return a[0] * scalar, a[1] * scalar
5,353,536
def parse_env(env): """Parse the given environment and return useful information about it, such as whether it is continuous or not and the size of the action space. """ # Determine whether input is continuous or discrete. Generally, for # discrete actions, we will take the softmax of the output ...
5,353,537
def encode_dataset(dataset, tester, mode="gate"): """ dataset: object from the `word-embeddings-benchmarks` repo dataset.X: a list of lists of pairs of word dataset.y: similarity between these pairs tester: tester implemented in my `tester.py`""" words_1 = [x[0] for x in dataset["X"]] ...
5,353,538
def _RunSetupTools(package_root, setup_py_path, output_dir): """Executes the setuptools `sdist` command. Specifically, runs `python setup.py sdist` (with the full path to `setup.py` given by setup_py_path) with arguments to put the final output in output_dir and all possible temporary files in a temporary dire...
5,353,539
def default_search_func(search_dict): """ Defaults to calling the data broker's search function Parameters ---------- search_dict : dict The search_dict gets unpacked into the databroker's search function Returns ------- search_results: list The results from the data br...
5,353,540
def readData(filename): """ Read in our data from a CSV file and create a dictionary of records, where the key is a unique record ID and each value is dict """ data_d = {} with open(filename) as f: reader = csv.DictReader(f) for row in reader: clean_row = [(k, preProc...
5,353,541
def share(request, token): """ Serve a shared file. This view does not require login, but requires a token. """ share = get_object_or_404( Share, Q(expires__isnull=True) | Q(expires__gt=datetime.datetime.now()), token=token) # Increment number of views. share.views...
5,353,542
def update_roi_mask(roi_mask1, roi_mask2): """Y.G. Dec 31, 2016 Update qval_dict1 with qval_dict2 Input: roi_mask1, 2d-array, label array, same shape as xpcs frame, roi_mask2, 2d-array, label array, same shape as xpcs frame, Output: roi_mask, 2d-array, label array, same shape ...
5,353,543
def get_latest_recipes(recipe_folder, config, package="*"): """ Generator of recipes. Finds (possibly nested) directories containing a `meta.yaml` file and returns the latest version of each recipe. Parameters ---------- recipe_folder : str Top-level dir of the recipes config ...
5,353,544
def allocate_db(ctx, redis_host, redis_port, environment_name, app_name): """Allocate a Redis database for a specified application and environment""" redis_config_instance = RedisConfig( redis_host=redis_host, redis_port=redis_port, app_name=app_name, environment=environment_name...
5,353,545
def spectral_synthesis(image, palette, n, h): """Plasma texture computation using spectral synthesis.""" width, height = image.size # rozmery obrazku bitmap = np.zeros([height, width]) A = np.empty([n//2, n//2]) # koeficienty Ak B = np.empty([n//2, n//2]) # koeficienty Bk beta =...
5,353,546
def training_loop( train_sequences: List[Tuple[pd.DataFrame, float]], val_sequences: List[Tuple[pd.DataFrame, float]], test_sequences: List[Tuple[pd.DataFrame, float]], parameters: Dict[str, Any], dir_path: str, ): """ Training loop for the LSTM model. Parameters ---------- tra...
5,353,547
def test_empty_headers(tiny_template): """Test that a spreadsheet with empty headers raises a validation error""" tiny_missing_header = { "TEST_SHEET": [ TemplateRow(1, RowType.HEADER, ("test_property", None, "test_time")) ] } search_error_message( tiny_missing_heade...
5,353,548
def update(ctx, client_uid): """Updates a client""" client_service = ClientService(ctx.obj['clients_table']) client_list = client_service.list_clients() client = [cl for cl in client_list if cl['uid'] == client_uid] if client: client = _update_client_flow(Client(**client[0])) clien...
5,353,549
def eliminate_nanoverlap(sen_directory, shape_path): """ eliminates the scenes which would'nt match with all weather stations :return: """ import_list = import_polygons(shape_path=shape_path) file_list = extract_files_to_list(path_to_folder=sen_directory, datatype=".tif") tifs_selected = sen...
5,353,550
def nmi(X, y): """ Normalized mutual information between X and y. :param X: :param y: """ mi = mutual_info_regression(X, y) return mi / mi.max()
5,353,551
def attribute_as_str(path: str, name: str) -> Optional[str]: """Return the two numbers found behind --[A-Z] in path. If several matches are found, the last one is returned. Parameters ---------- path : string String with path of file/folder to get attribute from. name : string ...
5,353,552
def racket_module(value): """ a very minimal racket -> python interpreter """ _awaiting = object() _provide_expect = object() def car(tup): return tup[0] def cdr(tup): return tup[1:] def eval(env, tup): last = None for value in tup: if isinstance(value, tuple): ...
5,353,553
def validate_inputs(input_data: pd.DataFrame) -> pd.DataFrame: """Check model for unprocessable values.""" valudated_data = input_data.copy() # check for numerical variables with NA not seen during training return validated_data
5,353,554
def train_model(model, *, train_generator, validation_generator, train_samples, class_weight, validation_samples, batch_size, epochs): """Train model""" # Configure early stopping to monitor validation accuracy early_stopping = EarlyStopping( monitor='val_acc', min_delta=0, patience...
5,353,555
def index(): """ Check if user is authenticated and render index page Or login page """ if current_user.is_authenticated: user_id = current_user._uid return render_template('index.html', score=get_score(user_id), username=get_username(user_id)) else: return redirect(url_f...
5,353,556
def pick( seq: Iterable[_T], func: Callable[[_T], float], maxobj: Optional[_T] = None ) -> Optional[_T]: """Picks the object obj where func(obj) has the highest value.""" maxscore = None for obj in seq: score = func(obj) if maxscore is None or maxscore < score: (maxscore, max...
5,353,557
def rsync_public_key(server_list): """ 推送PublicKey :return: 只返回推送成功的,失败的直接写错误日志 """ # server_list = [('47.100.231.147', 22, 'root', '-----BEGIN RSA PRIVATE KEYxxxxxEND RSA PRIVATE KEY-----', 'false')] ins_log.read_log('info', 'rsync public key to server') rsync_error_list = [] rsync_suce...
5,353,558
def create_one(url, alias=None): """ Shortens a URL using the TinyURL API. """ if url != '' and url is not None: regex = re.compile(pattern) searchres = regex.search(url) if searchres is not None: if alias is not None: if alias != '': ...
5,353,559
def duplicate_each_element(vector: tf.Tensor, repeat: int): """This method takes a vector and duplicates each element the number of times supplied.""" height = tf.shape(vector)[0] exp_vector = tf.expand_dims(vector, 1) tiled_states = tf.tile(exp_vector, [1, repeat]) mod_vector = tf.reshape(tiled_st...
5,353,560
def apk(actual, predicted, k=3): """ Computes the average precision at k. This function computes the average precision at k for single predictions. Parameters ---------- actual : int The true label predicted : list A list of predicted elements (order does matter)...
5,353,561
def make_predictor(model): """ Factory to build predictor based on model type provided Args: model (DeployedModel): model to use when instantiating a predictor Returns: BasePredictor Child: instantiated predictor object """ verify = False if model.example == '' else True ...
5,353,562
def get(identifier: str) -> RewardScheme: """Gets the `RewardScheme` that matches with the identifier. Arguments: identifier: The identifier for the `RewardScheme` Raises: KeyError: if identifier is not associated with any `RewardScheme` """ if identifier not in _registry.keys(): ...
5,353,563
def add_query_params(url: str, query_params: dict) -> str: """Add query params dict to a given url (which can already contain some query parameters).""" path_result = parse.urlsplit(url) base_url = path_result.path # parse existing query parameters if any existing_query_params = dict(parse.parse_q...
5,353,564
def test_commandline_abbrev_interp(tmpdir): """Specifying abbreviated forms of the Python interpreter should work""" if sys.platform == "win32": fmt = "%s.%s" else: fmt = "python%s.%s" abbrev = fmt % (sys.version_info[0], sys.version_info[1]) subprocess.check_call([sys.executable, VI...
5,353,565
def activate_agent( ctx: typer.Context, agent_ids: List[str], ) -> None: """ Activate pending agent """ api = get_api(ctx) for i in agent_ids: a = _get_agent_by_id(api.syn, i) if a["status"] != "AGENT_STATUS_WAIT": typer.echo(f"id: {i} agent not pending (status: {...
5,353,566
def tokenize_lexicon_str(vocab, lexicon_str, pad_max_length, device): """ #todo add documentation :param lexicon_str: :return: a tensor of ids from vocabulary for each . shape=(batch_size,max_length?) """ out_tensor = [] out_mask = [] for row in lexicon_str: lexicon_words = [] ...
5,353,567
def try_get_mark(obj, mark_name): """Tries getting a specific mark by name from an object, returning None if no such mark is found """ marks = get_marks(obj) if marks is None: return None return marks.get(mark_name, None)
5,353,568
def classSizable(class_): """Monkey the class to be sizable through Five""" # tuck away the original method if necessary if hasattr(class_, "get_size") and not isFiveMethod(class_.get_size): class_.__five_original_get_size = class_.get_size class_.get_size = get_size # remember class for cle...
5,353,569
def release(args): """Peform a release. This will: - check there are no unpushed/unpulled commits - bump the version number and commit - release the package to the cheeseshop Example: $> paver release patch """ # Check we don't have pending commits sh('git diff --qui...
5,353,570
def timedelta_to_seconds(ts): """ Convert the TimedeltaIndex of a pandas.Series into a numpy array of seconds. """ seconds = ts.index.values.astype(float) seconds -= seconds[-1] seconds /= 1e9 return seconds
5,353,571
async def test_disconnection_when_already_disconnected(): """Test the case when disconnecting a connection already disconnected.""" tmpdir = Path(tempfile.mkdtemp()) d = tmpdir / "test_stub" d.mkdir(parents=True) input_file_path = d / "input_file.csv" output_file_path = d / "output_file.csv" ...
5,353,572
def parse_gage(s): """Parse a streamgage key-value pair. Parse a streamgage key-value pair, separated by '='; that's the reverse of ShellArgs. On the command line (argparse) a declaration will typically look like:: foo=hello or foo="hello world" :param s: str :rtype: tuple(key, value) ...
5,353,573
def get_attribute(instance, attrs): """ Similar to Python's built in `getattr(instance, attr)`, but takes a list of nested attributes, instead of a single attribute. Also accepts either attribute lookup on objects or dictionary lookups. """ for attr in attrs: try: # pylint: ...
5,353,574
def pull_cv_project(request, project_id): """pull_cv_project. Delete the local project, parts and images. Pull the remote project from Custom Vision. Args: request: project_id: """ # FIXME: open a Thread/Task logger.info("Pulling CustomVision Project") # Check Customvi...
5,353,575
def get_log_line_components(s_line): """ given a log line, returns its datetime as a datetime object and its log level as a string and the message itself as another string - those three are returned as a tuple. the log level is returned as a single character (first character of the level's name...
5,353,576
def is_eligible_for_bulletpoint_vote(recipient, voter): """ Returns True if the recipient is eligible to receive an award. Checks to ensure recipient is not also the voter. """ if voter is None: return True return (recipient != voter) and is_eligible_user(recipient)
5,353,577
def test_atomic_duration_min_exclusive_nistxml_sv_iv_atomic_duration_min_exclusive_1_4(mode, save_output, output_format): """ Type atomic/duration is restricted by facet minExclusive with value P1970Y01M01DT00H00M00S. """ assert_bindings( schema="nistData/atomic/duration/Schema+Instance/NIST...
5,353,578
def test_resolve_validation(): """Resolve validates first.""" assert tools.resolve(',saoi9w3k490q2k4') == (False, True)
5,353,579
def _get_in_collection_filter_directive(input_filter_name): """Create a @filter directive with in_collecion operation and the desired variable name.""" return DirectiveNode( name=NameNode(value=FilterDirective.name), arguments=[ ArgumentNode( name=NameNode(value="op_n...
5,353,580
def load_labelmap(path): """Loads label map proto. Args: path: path to StringIntLabelMap proto text file. Returns: a StringIntLabelMapProto """ with tf.gfile.GFile(path, 'r') as fid: label_map_string = fid.read() label_map = string_int_label_map_pb2.StringIntLabelMap() try: text_for...
5,353,581
def changenodata_value( inputfile, outputfile, topotypein, topotypeout=None, nodata_valuein=None, nodata_valueout=np.nan, ): """ change the nodata_values in a topo file by interpolating from meaningful values. """ (X, Y, Z) = topofile2griddata(inputfile, topotypein) if topo...
5,353,582
def calc_internal_hours(entries): """ Calculates internal utilizable hours from an array of entry dictionaries """ internal_hours = 0.0 for entry in entries: if entry['project_name'][:22] == "TTS Acq / Internal Acq" and not entry['billable']: internal_hours = internal_hours + flo...
5,353,583
def format_str_strip(form_data, key): """ """ if key not in form_data: return '' return form_data[key].strip()
5,353,584
def get_element(element_path: str): """ For base extension to get main window's widget,event and function,\n pay attention,you must be sure the element's path grammar: element's path (father>attribute>attribute...) like UI_WIDGETS>textViewer """ try: listed_element_path = element_path.s...
5,353,585
def plot_bargraph(df:pd.core.frame.DataFrame, x_axis_column:str='product', y_axis_column:str='avg_order_rev', hue_column_name:str = None, x_label_name:str= 'Product', y_label_name:str='Average Revenue per order', ...
5,353,586
def test_file_open_bug(): """ensure errors raised during reads or writes don't lock the namespace open.""" value = Value('test', clsmap['file']('reentrant_test', data_dir='./cache')) if os.path.exists(value.namespace.file): os.remove(value.namespace.file) value.set_value("x") f = ...
5,353,587
def gravatar_for_email(email, size=None, rating=None): """ Generates a Gravatar URL for the given email address. Syntax:: {% gravatar_for_email <email> [size] [rating] %} Example:: {% gravatar_for_email [email protected] 48 pg %} """ gravatar_url = "%savatar/%s" % (GRAVATAR...
5,353,588
def test_node_exporter_binary_which(host): """Tests output of command matches /usr/local/bin/node_exporter""" assert host.check_output('which node_exporter') == NE_BINARY_FILE
5,353,589
def decmin_to_decdeg(pos, decimals=4): """Convert degrees and decimal minutes into decimal degrees.""" pos = float(pos) output = np.floor(pos / 100.) + (pos % 100) / 60. return round_value(output, nr_decimals=decimals)
5,353,590
def get_selector(selector_list, identifiers, specified_workflow=None): """ Determine the correct workflow selector from a list of selectors, series of identifiers and user specified workflow if defined. Parameters ---------- selector_list list List of dictionaries, where the value of all di...
5,353,591
def register_pth_hook(fname, func=None): """ :: # Add a pth hook. @setup.register_pth_hook("hook_name.pth") def _hook(): '''hook contents.''' """ if func is None: return functools.partial(register_pth_hook, fname) source = inspect.getsource(func) if no...
5,353,592
def feedzone_to_GIS(input_dictionary): """It writes a shapefile (point type) from the wells feedzones position Parameters ---------- input_dictionary : dictionary Dictionary contaning the path and name of database on keyword 'db_path'. Returns ------- file well_survey: on the path ../mesh/GIS Exampl...
5,353,593
def callable_or_raise(obj): """Check that an object is callable, else raise a :exc:`ValueError`. """ if not callable(obj): raise ValueError('Object {0!r} is not callable.'.format(obj)) return obj
5,353,594
def extractLandMarks(fm_results): """TODO: add preprocessing/normalization step here""" x = [] y = [] z = [] for i in range(468): x.append(fm_results.multi_face_landmarks[0].landmark[i].x) y.append(fm_results.multi_face_landmarks[0].landmark[i].y) z.append(fm_results.multi_fa...
5,353,595
def conv_coef(posture="standing", va=0.1, ta=28.8, tsk=34.0,): """ Calculate convective heat transfer coefficient (hc) [W/K.m2] Parameters ---------- posture : str, optional Select posture from standing, sitting or lying. The default is "standing". va : float or iter, option...
5,353,596
def _one_formula(lex, fmt, varname, nvars): """Return one DIMACS SAT formula.""" f = _sat_formula(lex, fmt, varname, nvars) _expect_token(lex, {RPAREN}) return f
5,353,597
def _split_variables(variables): """Split variables into always passed (std) and specified (file). We always pass some variables to each step but need to explicitly define file and algorithm variables so they can be linked in as needed. """ file_vs = [] std_vs = [] for v in variables: ...
5,353,598
def percentiles_fn(data, columns, values=[0.0, 0.25, 0.5, 0.75, 1.0], remove_missing=False): """ Task: Get the data values corresponding to the percentile chosen at the "values" (array of percentiles) after sorting the data. return -1 if no data was found :param data: data struct...
5,353,599