content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import webbrowser def openURL(url): """Opens a URL.""" webbrowser.open_new(url) return True
b2e843a49ddfb4b90e556f4edbaa4e20823f3097
36,900
def plasticmodel_error(bedfunction, tau_val, Bfunction, startpoint, hinit, endpoint, Npoints, obsheightfunction, allow_upstream_breakage=True): """Arguments used: bedfunction should be function of arclength returning bed elevation of the glacier. Bfunction is nondim yield strength. Should be functi...
a2c10ea5ddc953e126562488cce33e966ca3f32e
36,901
def lisp_parens_with_stack(parens): """Output with stack to see whether parens are open(1), broken(-1), or balanced(0).""" open_stack = [] for par in parens: if par == '(': open_stack.append(par) if par == ')': try: open_stack.pop() except ...
f3cd34611fc8ff8cf33a7f62bcddf245c77ff473
36,902
def attention_resnet56(**kwargs): """Constructs a ResNet-34 model. """ model = CifarAttentionResNet(CifarAttentionBasicBlock, 9, **kwargs) return model
a1c211edb9c5fb3d30d715f0b218ebec54c55ca4
36,903
def index(request): """View-func for '' request. Displays ten posts per page, sorted by date added. Returns 'posts/index.html' template. """ post_list = Post.objects.all() page_obj = paginator_page(request, post_list) context = { 'page_obj': page_obj, } cache.clear() ret...
598038d722fb0e20a94a2eea276c067f2476d88e
36,904
def generate_cyclic_group(order, identity_name="e", elem_name="a", name=None, description=None): """Generates a cyclic group with the given order.""" if name: nm = name else: nm = "Z" + str(order) if description: desc = description else: desc = f"Autogenerated cyclic ...
d2bd6be8519cdd5d9c09ded2e9736b6668796026
36,905
from typing import List def format_data(statistics: List = [], group_data_by: str = None): """ Format data to be displayed in the carts. Arguments: statistics {List} -- All device statistics. group_data_by {str} -- User selected aggregation option. """ reports, alerts = {}, {} ...
b3451c82e273850199c4a39fb907a774ec688d3a
36,906
def each_side(token): """Count the found embryo.""" trait = Trait(start=token.start, end=token.end) if token.group.get("subcount"): count = to_positive_int(token.group["subcount"]) trait.value = count + count trait.left = count trait.right = count return trait
cc4c0b347e61ccc7d9f6ddfa253381572eb54da3
36,907
def get_match_data_by_uid(uid): """ 通过用户id获取mysql匹配场数据 :param: uid :return:dict """ # TODO 获取匹配场数据 return mj_hall_bridge.get_match_data_by_uid(uid)
c6bc246ed0ca9cadc786d3b103daa94f62d39420
36,908
import os def str_format_env(value): """ Substitute values with environment variables in a string Parameters ---------- value : str The string object to be formatted and converted into a list Returns ------- str With env variable values substituded """ templat...
356b686a3b9231ca21bc9902bbf90d7ca0b67c4b
36,909
def render_output_preview(output_preview, filename, region): """ We get the exact number of preview lines we want, but some of them might be too long and get wrapped. In this case, the extra lines overflow at the bottom, but we want overflow at the top (and there seems to be no way to fix this natively ...
af42badb8b0a27d70ef600cb9dab1ae4fdbdda89
36,910
import torch def update_quantization_param(bits, rmin, rmax, dtype, scheme): """ calculate the `zero_point` and `scale`. Parameters ---------- bits : int quantization bits length rmin : Tensor min value of real value rmax : Tensor max value of real value dtype ...
9c55cb1b195d64c5f3905488e38864d18045d90b
36,911
def process_correct_phidp0(procstatus, dscfg, radar_list=None): """ corrects phidp of the system phase Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set configurati...
d3f1a624c5f671da5908ea1774e3035d7ead00d8
36,912
def largest_nonadjacent_sum(arr): """ Find the largest sum of non-adjacent numbers """ before_last = 0 last = 0 for elt in arr: cur = before_last + elt before_last = max(before_last, last) last = max(cur, last) return last
39d4ab307e978f4ab9d1bd5a2983292dde3f6933
36,913
def _flip_boxes_up_down(boxes): """Up-down flip the boxes. Args: boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4]. Boxes are in normalized form meaning their coordinates vary between [0, 1]. Each row is in the form of [ymin, xmin, ymax, xmax]. Returns: ...
d69ba328d9cf5d83f6cc32f03ff6f4991208e628
36,914
import os def get_image_id() -> list: """ Returns: [list]: [Return a list with all Image id content in the storage] """ storage_folder = settings.STORAGE_DIR+'/image' list_id = [] i=0 for f in os.listdir(storage_folder): if os.path.isfile(os.path.join(storage_folder...
f57fde65e33087fde51fa949729e180c040fadb9
36,915
from typing import Callable from pathlib import Path import os from shutil import copyfile def parse_replays( game_filter: Callable, unparsed_folder: Path, events_folder: Path, pickle_folder: Path, json_folder: Path, screenshot_iterator: Callable, limit=None, ): # pylint: disable=too-many...
e7c80eede7aecfdbd907fd76ad28b7e2fb54e4f8
36,916
def openTypeOS2WinAscentFallback(info): """ Fallback to the maximum y value of the font's bounding box. If that is not available, fallback to *ascender*. if the maximum y value is negative, fallback to 0 (zero). """ font = info.getParent() if font is None: yMax = getAttrWithFallback(...
d64244b36bd9dab3bcb6074bdac85fd84b54dfa2
36,917
def get_updates_and_outputs(ls): """ Parses the list ``ls`` into outputs and updates. The semantics of ``ls`` is defined by the constructive function of scan. The elemets of ``ls`` are either a list of expressions representing the outputs/states, a dictionary of updates or a condition. """ d...
eba2a883fe1f2ecbdb4602226aa6d0fd8f2eeb6f
36,918
def get_regularized_cost(dims, theta, num_samples, lambd): """ Calculates L2 Regularization cost using hyper parameter lambd Preconditions: dims: list of int length >= 2 theta: dict num_samples: int Parameters: dims: dimensions of the neural network model theta: learned parameters ...
4cfa279426e24c9300204d88d507450d61e1c65b
36,919
from typing import Any def eval_with_import(path: str) -> Any: """Evaluate the string as Python script. Args: path (str): The path to evaluate. Returns: Any: The result of evaluation. """ split_path = path.split('.') for i in range(len(split_path), 0, -1): try: ...
a9d614251f088c9105504aa0f9f99bbc1d8f1712
36,920
from typing import Union from typing import Iterable from typing import List from typing import Optional def get_labeled_measurements(data: DataRowsSet_t, correct_channels: WorkingChannels_t, functionalisations: Functionalisations_t, start_offset: Union[int, Iterable[int]] = 0, ...
df45a3e24f85cda87f0e34f4f03ca6cb101544b1
36,921
import torch def GDL(input, target, weights): """ Generalized Dice Loss :param input: input is a torch variable of size Batch x nclasses x H x W representing the predictions for each class :param target: target is a 1-hot representation of the groundtruth, shoud have same size as the input :ret...
ca224be903dd387568ff4794db7c2b9263fc9d67
36,922
def eval_class(gt_annos, dt_annos, current_class, difficulty, metric, min_overlap, num_parts=50): """Kitti eval. Only support 2d/bev/3d eval for now. Args: gt_annos: dict, must from get_label_annos() in kitti_commo...
97aa6bca80865086c4b36a3f7ce97c58bd66a143
36,923
def integral_curve(h, hstar, hustar, wave_family, g=1., y_axis='u'): """ Return u or hu as a function of h for integral curves through (hstar, hustar). """ ustar = hustar / pospart(hstar) if wave_family == 1: if y_axis == 'u': return ustar + 2*(np.sqrt(g*hstar) - np.sqrt(g*h)...
ee1b99e736c034e02b88ecfbf08f61d423d26ad9
36,924
def dev_guide(request): """ 开发指引 """ return render_mako_context(request, '/home_application/dev_guide.html', {"ssssss": "11111111", "AAA": [{'QQQ': "22222"}] ...
fb285c80ec89c8562503f2faa8cb79bde7ce2e06
36,925
from openff.evaluator.client import ConnectionOptions, EvaluatorClient def _run_calculations( data_set: "PhysicalPropertyDataSet", force_field: "ForceField", polling_interval: int, request_options: "RequestOptions", server_config: EvaluatorServerConfig, ) -> "RequestResult": """Attempt to esti...
dde4400671ab2f29a35321ea3d774d380a15dd89
36,926
def NewtonRaphson(funcion, derivada, x_inicial, num_iteraciones, error): """ La x inicial determinara el numero de iteraciones necesarias para alcanzar el resultado. :param funcion: Nombre de la funcion a utilizar sin parentesis. :param derivada: Nombre de la derivada de la funcion sin parentesis. ...
2c45b76d4b3f8cc11eec111211820114f98b7936
36,927
import os import codecs def readoptions(fname): """ Read `markowik` options from a file, one per line. """ if os.path.exists(fname): with codecs.open(fname, 'r', 'UTF8') as fp: cfg = fp.read() options = [x.strip() for x in cfg.split("\n") if x.strip()] else: op...
2a0149be62a7f57d1c0cb9fa1351d892dc1517c1
36,928
import six def get_train_random_forest_pai_cmd(model_name, data_table, model_attrs, feature_column_names, label_name): """Get a command to submit a KMeans training task to PAI Args: model_name: model name on PAI data_table: input data table name mod...
f826e0b24613b2ea8794524c3a5f982131f9a048
36,929
def GetScaleValue(debug=False, file="CONTCAR"): """Return lattice scale from a VASP POSCAR/CONTCAR file""" try: f = open(file, 'r') l = f.readline() # title scale = float(f.readline().split()[0]) # scale f.close() return scale except IOError as err: print("ERROR: Failed to open CONTCAR or ...
ffad759d7607adf364cdd8c6437a678e53174d21
36,930
def get_max_length(captions): """从标题字典计算图像标题里面最长的标题的长度 Args: captions: 一个dict, key为文件名(不带.jpg后缀), value为图像标题list Returns: 最长标题的长度 """ lines = to_list(captions) return max(len(d.split()) for d in lines)
953f6190a9b3a5e07d6597dbf4e2a117e767ead0
36,931
def diff_all_filter(trail, key=lambda x: x['pid']): """ Filter out trails with last key appeared before """ return trail if key(trail[-1]) not in set([key(c) for c in trail]) else None
6c7b6e7c64c4fcf097b5ac743e3c2720911c0248
36,932
from typing import Union def wrap_jiant_forward( jiant_model: Union[JiantModel, nn.DataParallel], batch: BatchMixin, task: Task, compute_loss: bool = False, ): """Wrapper to repackage model inputs using dictionaries for compatibility with DataParallel. Wrapper that converts batches (type Batc...
bae924f9381163edb4bbce95ed61055a5e36249c
36,933
from numpy import gcd def get_layout_from_drawing(drawing: str) -> tuple[list[Qubit], list[Coupling]]: """ Given a valid `drawing`, return the corresponding qubits and couplings. A valid `drawing` is a string with `X` representing a qubit and one of the following token `/\|-` to represent a coupling. ...
a967d1f9a92b47ac03aa745d334008bccc0af293
36,934
from typing import Dict def get_dataset(config: Dict): """ Returns a pytorch dataset from a config. """ assert 'tokenizer' in config tokenizer = config['tokenizer'] dataset_config = config['dataset'] tokenization_config = config['model']['tokenization'] def encode(instances): return t...
17f674d7fbcf1c53462f1dee7b61b7c8a03ecaab
36,935
from twilio.twiml import TwiML async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Twilio for inbound messages and calls.""" data = dict(await request.post()) data['webhook_id'] = webhook_id hass.bus.async_fire(RECEIVED_DATA, dict(data)) return TwiML().to_xml()
d6d5bfa905bc12c4eb6961a74219cf4353124713
36,936
from typing import Optional from pathlib import Path def get_path() -> Optional[Path]: """Determine the current Python runtime path. :return: The :class:`~pathlib.Path` instance to the current Python path if found :rtype: Optional[~pathlib.Path] """ path_entry = PythonFinder().which("python") ...
95107fee17d1dc3dcd593387cf921839c6d609f1
36,937
import ast def cleanupRanges(a): """Remove any range shenanigans, because Python lets you include unneccessary values""" if not isinstance(a, ast.AST): return a if type(a) == ast.Call: if type(a.func) == ast.Name: if a.func.id in ["range"]: if len(a.args) == 3: # The step defaults to 1! if typ...
9e112ec4d4528967426a081e11fb609176330905
36,938
def slowfast101(**kwargs): """Constructs a SlowFast-101 model. """ model = SlowFast(Bottleneck, [3, 4, 23, 3], **kwargs) return model
9ad824021c5f169b27614241f4958d521d835fec
36,939
import math def xy(n, image_size): """Returns position of pixel n in 2D array""" x = int(n % image_size) y = int(math.floor(n / image_size)) return (x,y)
def36d60055e5084b42d73833c4baeeab9723085
36,940
def filter_contenttypes_by_app(request): """ Accepts an app_label as a query_string and returns its associated model set as JSON in a format designed to fill an in an HTML dropdown menu. HTTP GET is required. """ # If there is not a GET request throw a 404 if not request.GET: raise Http404 # Seed the re...
b8a04fe276da3c889f5c01f74990d9ff41d217b1
36,941
import xml def cot_to_cot_xml(cot: dict, known_craft: dict = {}) -> str: # NOQA pylint: disable=too-many-locals """ Given an input CoT XML Event with an ICAO Hex as the UID, will transform the Event's name, callsign & CoT Event Type based on known craft input database (CSV file). """ uid = str(co...
bda8d7dc8398c65b728eaeac613dcd611cc81d67
36,942
import inspect import typing from typing import Container from typing import Mapping def validator_for(_type): """ Utility function to create a Type validator callable. """ if isinstance(_type, type(None)): return NoneValidator() if inspect.isclass(_type) and issubclass(_type, Schema): ...
72ee001afe229c432389c2c565009b2595427c4e
36,943
def get_db_user(): """Returns the PostgreSQL database user (please don't use the admin 'postgres'), can be retrieved from env var or configuration file.""" return Config.get_var_value( env_var="DB_USER", conf_table="database", conf_value="db_user" )
5190ae65a7b4b65aec73df67d393932cf6842470
36,944
def format_labels(label): """ Assumes that the label can be split by the '_' character. :param label: :return: """ side, anatomy = label.split("_") if side.lower() in ["l", "left"]: side = "left" elif side.lower() in ["r", "right"]: side = "right" else: raise...
9b0add955822713eb579168c9bae7a9ae6908fe6
36,945
def find_definition(view, location, keyword): """Find the local definition of a keyword in the view. Uses the tuple of scopes to search for the local definition of keyword. Arguments: view (sublime.View): the view the keyword is defined in location (int): the text p...
bf4dd6c705cd553b15911ac0784f21d70c746d2b
36,946
def add_datacite(pif, dc): """ Add datacite metadata to an existing pif (out-of-place) :param pif: to which metadata should be added :param dc: dictionary with datacite metadata :return: new PIF with metadata added """ meta_pif = datacite_to_pif(dc) return merge(pif, meta_pif)
2bece798d94137f1ee1c688df29ba26c9f92beec
36,947
import os def is_root(directory): """Check if the directory is the root directory. Args: directory: The directory to check. Return: Whether the directory is a root directory or not. """ # If you're curious as why this works: # dirname('/') = '/' # dirname('/home') = '/' ...
ccbdcce26cd3b8b0826ce2514bbd3612c5381a21
36,948
import json def test_change_participation_status(client): """Test Client.change_participation_status(). :param Client client: Client instance with test data. """ calendar_id = "cal_123" event_uid = "evt_external_439559854" status = "accepted" def request_callback(request): payloa...
aaa2d6330fa6144081478f2b53858e5f49fc9659
36,949
def uploadpartscsv(): """upload csv files of compounds to the database""" form = UploadCSVfile() if form.validate_on_submit(): filename = secure_filename(form.compounds.data.filename) form.compounds.data.save("app/uploads/" + filename) filename_read = "app/uploads/" + filename ...
8f406a60a19f4c8f167d57cb0ea4f728b0919269
36,950
import sys def alpha_028(code, end_date=None, fq="pre"): """ 公式: 3*SMA((CLOSE-TSMIN(LOW,9))/(TSMAX(HIGH,9)-TSMIN(LOW,9))*100,3,1)-2*SMA(SMA((CLOSE-TSMIN(LOW,9))/( MAX(HIGH,9)-TSMAX(LOW,9))*100,3,1),3,1) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date...
830c948235d20c7ccceb14b4c2f06e1ed003d11e
36,951
def class_of ( object ): """ Returns a string containing the class name of an object with the correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image', 'a PlotValue'). """ if isinstance(object, basestring): return add_article( object ) return add_article( object.__class__._...
7a3f09cd191fcd084288f2839bbbe521ea657960
36,952
def mean(input, labels = None, index = None): """Calculate the mean of the values of the array. The index parameter is a single label number or a sequence of label numbers of the objects to be measured. If index is None, all values are used where labels is larger than zero. """ input = numarray...
16d1bc2261a48133fc295282573da3f3afd3b5fa
36,953
import requests import os def run_md5sum(cwl_input): """Pass a local md5sum cwl to the wes-service server, and return the path of the output file that was created.""" endpoint = 'http://localhost:8080/ga4gh/wes/v1/workflows' params = {'output_file': {'path': '/tmp/md5sum.txt', 'class': 'File'}, 'input_fil...
5f4c79953c691e705f66803269f83dd609be1e56
36,954
def calculate_svd(data): """Calculate Singular Value Decomposition This method calculates the Singular Value Decomposition (SVD) of the input data using SciPy. Parameters ---------- data : numpy.ndarray Input data array, 2D matrix Returns ------- tuple Left singula...
3feaca3acde58e440dd8a99c964abf2223991776
36,955
from string import Template from SCons.Util import is_String def _resubst(value, resubst_dict = {}): """Rename placeholders (substrings like ``$name``) in a string value. :Parameters: value the value to process; if it is string it is passed through placeholder renaming procedu...
9f5f31eee9426c19d704e16b01564d4f8bba882c
36,956
async def is_alive(): """is this character alive?""" return app.state.hp > 0
eb9f0816ee8d0385636a14c7a5b365a5ffb864ec
36,957
def get_app_name(): """ liefert ressource """ return 'resource'
580a2cf59b84f28f3efc95b00ffd051b53fa0ffa
36,958
import requests from bs4 import BeautifulSoup def list_folders_from_url(url): """ List all folders from a remote directory. Ignores all files and hidden files and folders. Assumes the URL returns an HTML directory listing. """ request = Request(url) page = requests.get(url).text so...
1cf2569bee9441b7c4dfc9eeb79cdbdeb5836969
36,959
def get_volume(module, array): """Return Volume or None""" try: return array.get_volume(module.params["name"]) except Exception: return None
e416bc84e4a6609def73e18348fce26011c780cb
36,960
def from_nodlink_dat(basename): """ Creates the Kgraph from two ascii files (nodes, and links). Parameters ---------- basename : string The base name used for the input files. The input files are named using the following convention: - basename_nodes.dat: the matrix of 3D ...
b79a8f440e99f865173920a619eb35e69a38b51a
36,961
def write_eol(lines, mat, mf, mt, istart=1): """ Add end-of-line flags MAT, MF, MT and line number to list of strings. Returns ------- `str` A string that is the sum of the list of strings, i.e. including eol falgs, separated by the newline character `\n`. Warns ----- T...
8343f7e71a92879f2bc9cf282d1d4cf2f98fa023
36,962
import math def degree_to_radian(degree: float) -> float: """ Fungsi ini digunakan untuk mengonversi derajat ke radian. Rumus : derajat * (pi / 180 derajat) >>> degree_to_radian(60) 1.0471975511965976 """ return degree * (math.pi / 180)
5935b99621192edae5360b2066397997d2dc34f5
36,963
import time def get_best_matching_metadata(document_row, metadata, logger): """TODO: Docstring for get_matching_metadata. :document_row: TODO :metadata: TODO :returns: TODO """ logger.info(f'Starting with a metadata list totalling {len(metadata)} items') meta = [m for m in metadata if st...
456752404774b292574f85fc5a4e58bb68b56035
36,964
from typing import Type from typing import TypeVar from typing import get_args def _contains_unbound_typevar(t: Type) -> bool: """Recursively check if `t` or any types contained by `t` is a `TypeVar`. Examples where we return `True`: `T`, `Optional[T]`, `Tuple[Optional[T], ...]`, ... Examples where we re...
97e85b3aafea1d9dc86f69078ff39c93b6bd7c19
36,965
import re def _extract_exactly_one_check_letter_from_string(a_string: str) -> str: """ Extracts the check letter out of string that could be a DNI. Will raise an exception if the string does not represnt a DNI. :param a_string: the string that contains the check letter. :return: the check letter ...
756eaf7e994144fc4ddadfb40c163633fb934cc4
36,966
from typing import List def get_locations( db_session: Session = Depends(get_db), # page: int = 1, itemsPerPage: int = 5, q: str = None page: int = 1, items_per_page: int = Query(5, alias="itemsPerPage"), query_str: str = Query(None, alias="q"), sort_by: List[str] = Query(None, alias="sortBy[]"),...
b688a69939e3355e82c8700805a25e70d0559e55
36,967
async def login_by_user_pwd(form_data: OAuth2PasswordRequestForm = Depends()) -> Token: """ OAuth2 compatible token login, get an access token for future requests """ user: User = authenticate(form_data.username, form_data.password) logger.info(f'User[{user.name}] signed in.') access_token_expires = timedelta(min...
f420a99cb785148bbe72b7d14e488212467b9f75
36,968
import os import copy def tudo_separados(dirImagens, folder_name, tipoGrafico, bar_empilha, dirFiles, confTipoGrafico, numPilares, minY, maxY, Freqmax, files): """ Le os ficheiros comos valores. Chama ``desenho()`` para fazer o plot. Aplica as especifiçaões do grafico presentes no .conf em ``Specs = {}``. Guarda o...
cfe75ff8f4b2c6c5348ea2ccbbe7a006a2a141e2
36,969
def get_news_list(): """ 1.获取参数 2.校验参数 3.查询数据库 4.返回数据 :return: """ # 1.获取参数,2. 校验参数 try: cid = request.args.get('cid', 1, type=int) page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', 10, type=int) except Exception as e: ...
8396badece34b8d17d7997452bf28e49e2ecd81e
36,970
def get_tf_map(source, indent_size, indent_level=0): """Turn dict object into a tf map""" outer_line_prefix = "".rjust(indent_level * indent_size) inner_line_prefix = "".rjust((indent_level + 1) * indent_size) formatted = "{\n" tf_items = [] for key in source: item = get_tf_item(source[k...
f7baa384fa71c9f753cdb2f44a8f55c468a5e493
36,971
from typing import Mapping import json import base64 def invoke(name, payload=None, invoke_type=INVOKE_TYPE_REQUEST_RESPONSE, logs=False, context=None): """ Invokes a Lambda function. :param name: The name or ARN of the function :param payload: A dict or JSON string that you want to provide to the Lam...
beccc4d4bc88df6cc9afde23764d79ee84ffdf17
36,972
def segmentation_blocks_test_b(band_pass_signal_hr, sb, sh, dim): """THIS SECTION REMAINS FOR TESTING PURPOSES Function used for the segmentation of the signal into smaller parts of audio (blocks). This has been implemented as described in formula F.16 (section F.3.5) of Annex F (ECMA-74). It has some issu...
59a52485a70e8f7b3de796b246af1b0f5f08dd22
36,973
def _depthwise_conv_block(inputs, pointwise_conv_filters, alpha, depth_multiplier=1, strides=(1, 1), block_id=1): """Adds a depthwise convolution block. A depthwise convolution block consists of a depthwise conv, batch normalization, relu6, pointwise convolution, batch normaliz...
d32a202410b63ea001d475c4031688e47aacfe57
36,974
import sys def _decide_sort_field_args(args): """Auto-correct else reject contradictions among which sort column to sort""" # Reject contradictions # FIXME: sort by multiple columns vote_ext = "-X" if args.X else "" vote_none = "-f" if args.f else "" vote_size = "-S" if args.S else "" vo...
1f4e503f7c50483b3f773eb3c7d13a5b7b157e24
36,975
def _ValidateExperimentGroup(experiment_group, create_message_fn): """Validates one group of one config in a configuration entry.""" name = experiment_group.get('name', '') if not name or not isinstance(name, unicode): return create_message_fn('Missing valid name for experiment') # Add context to other mes...
066a714b6751e3128c17546584f83438e54f33ee
36,976
import os def read_kml_placemark(kml): """ Returns geometry from Google Earth KML file. :param str kml: KML file name without directory. :rtype: dict :return: Geometry dict. """ config = seisnn.utils.Config() kml_file = os.path.join(config.geom, kml) parser = etree.XMLParser() ...
8c4931951c3d70a64d7e254b648648145187f9ab
36,977
def ne_groupnodes(n, e): """Group nodes with same line number.""" nl = n[n.lineNumber != ""].copy() nl.lineNumber = nl.lineNumber.astype(int) nl = nl.sort_values(by="code", key=lambda x: x.str.len(), ascending=False) nl = nl.groupby("lineNumber").head(1) el = e.copy() el.innode = el.line_in ...
b056075e379629c67b25660b155e1d869abc546d
36,978
def make_vct_file(res_fn=res_file, outfn=vct_file): """ Make vct file for re-formatting lev. :param res_fn: :param outfn: :return: """ res_f = xr.open_dataset(res_fn) hyai = 'hyai' hybi = 'hybi' hyai_da = res_f[hyai].values hybi_da = res_f[hybi].values outfile = open(str...
1c3fe7efc9c3dae3c67a41454732da2f9b4a8a92
36,979
def parse_container(node): """Returns containerised data of a node Reads the imprinted data from `containerise`. Arguments: node (nuke.Node): Nuke's node object to read imprinted data Returns: container (dict): imprinted container data """ data = lib.get_avalon_knob_data(node)...
812e67cea8f647d43d727ec0c88ffd1f0ed9aa79
36,980
def get_gas_status_plot(solution): """ @ solution: a solution list, format [(x, rho, v, p)...] """ # prepare list for x, rho, v and p list_x = [] list_rho = [] list_v = [] list_p = [] for i in solution: list_x.append(i[0]) list_rho.append(i[1]) list_v.append(i...
00d9d5a884018c5aa81d20f47eb5e684ecd47578
36,981
def propagate_masks( mask, param_names = WEIGHT_PARAM_NAMES ): """Accounts for implicitly pruned neurons in a model's weight masks. When neurons are randomly ablated in one layer, they can effectively ablate neurons in the next layer if in effect all incoming weights of a neuron are zero. This method a...
c0e69ed1cdda1c8174ca138cbc5a6b86fd80f7cb
36,982
def ControlFromPoint(x, y): """use IUIAutomation ElementFromPoint x,y, may return 0 if mouse is over cmd's title bar icon""" element = _AutomationClient.instance().dll.ElementFromPoint(x, y) return Control.CreateControlFromElement(element)
d77ebd26beb9d98c519cbc9f6fc6efb5d4ab5865
36,983
import os def download_file(url, current_dir): """ Attempt to download file from URL using sane buffer and write to file :param file: input URL :return: full path to downloaded file """ file_name = url.split('/')[-1] response = urlopen(url) if response.status != 200: raise Down...
0c7e194b9b53fb697ebd09b6eff7556d898d930a
36,984
import os def _get_output_dir(output_dir, chunk_arr, name_arr): """Get the directory for the output cutout data.""" # Check the output directory if not os.path.isdir(output_dir): raise ValueError("Output directory '{:s}' does not exist".format(output_dir)) return [os.path.join(output_dir,...
4aff96f5d26c8073f64277a23bbc3eacc9024ea3
36,985
from typing import Tuple from typing import List def extract_and_hide_tables_from_image(image: np.ndarray, lang: str) -> Tuple[np.ndarray, List[LocatedTable]]: """ Detects and returns tables in images using opencv for structure detection and pytesseract for cell content detection. Then hides detected ...
76d2ed323cf40456ce1fbda57ed4da73cc8ff2a9
36,986
def execandcombine(command): """execute a shell command, and return all output in a single string.""" data = execandcapture(command) return "\n".join(data)
40710b844efe23b7933416575fd130fcb811d3f9
36,987
import json def adjacency_matrix_view(request): """Renders adjacency matrix. Uses transmission events data stored in session. :param request: Contains organism_groups_list. :return: Render of adjacency matrix. :rtype: HttpResponse """ organism_groups_list = json.loads(request.GET["organi...
4e543c1c8cb4dea6a44c2be05fc872df67832e9e
36,988
def unauthorized(errormsg=''): """Create a response with HTTP status code 401 - Unauthorized.""" return make_json_response( status=401, success=0, errormsg=errormsg )
1bc1b66aec9ceb63cdb84b694e04ddbf46247486
36,989
def get_revolution_period(accelerator): """.""" return 1 / get_revolution_frequency(accelerator)
22a6b57cf0af1d65239b6e327082ceddb8ef0916
36,990
def topmost_post(subreddits): """Returns the highest-upvoted post of all subreddits.""" tops = all_top_posts(subreddits) top = tops[0] for submission in tops: if submission.score > top.score: top = submission return [top]
508308642567b0e2aa2d2260400f66df40f0f267
36,991
def sub(a_t, b_t): """ sub operator a-b """ return sub_op(a_t, b_t)
0f735c84d197f82c9063e374a6a1eaf1c11d89eb
36,992
import os import glob def dog_names_create(dataImagesTrain=os.path.join(cfg.DATA_DIR, cfg.Dog_DataDir, 'train','*'), dog_names_path=cfg.Dog_LabelsFile): """ Function to create dog_names fi...
de528ea0f284de790da053d1f1d2c287cc923b16
36,993
import torch import os import json def normalize(data, signal_type, carrada_path, norm_type='local'): """Function to normalize the input data. Note that the 'train' and 'tvt' norm methods requires specific files containing statistics on the dataset. PARAMETERS ---------- data: torch tensor ...
2cd7f4acfcbee109e08b619f44427a0524190b25
36,994
def create_sample_db(ntables): """ Create a python description of a sample database """ rv = {} for i in range(1, ntables + 1): rv["table%s" % i] = { "columns": [ { "name": "id", "type": "integer", "use_s...
c49f583b4e7f58f1bbb7ad05902c1fc9010bd35c
36,995
import os import glob def listflat(path, ext=None): """ List files without recursion """ if os.path.isdir(path): if ext: if ext == 'tif' or ext == 'tiff': files = glob.glob(os.path.join(path, '*.tif')) files = files + glob.glob(os.path.join(path, '*....
227a12683472dfbaf298cb54b730049a270187f3
36,996
from typing import Union from typing import Tuple from typing import Dict def get_result( data: AnnData, key: str, params: bool = False, ) -> Union[pd.DataFrame, Tuple[pd.DataFrame, Dict]]: """Read spatialtis result from `AnnData.uns` as `pandas.DataFrame` object To get the params, use `params=Tr...
cf017db1566872c8df80411d5c5a889b2c055b7b
36,997
def _smallest(x, a, m): """ Gives the smallest integer >= x that equals a (mod m) Assumes x >= 0, m >= 1, and 0 <= a < m. """ n = ceiling(x - a, m) return a + n*m
ae158e1905f2f63be7db17f10fdefb612f2fd9bd
36,998
def max_pool_layer(layer_id, inputs, kernel_size, stride): """Build a max-pooling layer. Args: layer_id: int. Integer ID for this layer's variables. inputs: Tensor of shape [num_examples, width, height, in_channels]. Each row corresponds to a single example. kernel_size: int. Width and height to ...
4cd8dbffd9da73d5c7e0051845e6c20772124649
36,999