content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def show_json(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ r=show(i) if r['return']>0: return r return...
7b95ae3ab51a347d83a9038f8a1954d68290f6b7
36,884
from typing import List from typing import Dict import transformers import torch import tqdm def tokenize_jiant_dataset( tokenizer, texts: List[str], span1s: List[List[int]], span2s: List[List[int]], labels: List[str], labels_to_ids: Dict[str, int], max_seq_leng...
824473158a9dbcba3889b5467c53cd0ec3553c5d
36,885
from typing import Dict def splitLR(geom: geo.base.BaseGeometry, splitter: String_or_Ring) -> SplitGeometry: """Split a geometry into a 'left' and 'right' side using the shapely API""" left,right = [],[] split_geom = ops.split(geom, splitter) if len(split_geom)==1: raise GeometryError("splitte...
141c29677cf223dd5a2e2746685a7f850740bf5d
36,886
def view(): """Returns the ProteinViewer app view""" viewer = ProteinViewer() return viewer.view()
9d3e890c9885a0796d8bba283e5fcc7529c3f26f
36,887
def schaffer(X, Y): """constraints=100, minimum f(0,0)=0""" numer = np.square(np.sin(X**2 - Y**2)) - 0.5 denom = np.square(1.0 + (0.001*(X**2 + Y**2))) return 0.5 + (numer*(1.0/denom))
dbdd3d35476013500762df9346b24e8a5b46eef8
36,888
def get_producer(): # pragma: no cover """Create a Kafka producer.""" producer = Producer({"bootstrap.servers": Config.INSIGHTS_KAFKA_ADDRESS, "message.timeout.ms": 1000}) return producer
6d357d2de307936cdaba38cd0e8ef805225f68ca
36,890
def infer_capture_method(tx, rx): """ Infers the capture method from the indices of transmitters and receivers. Returns: 'hmc', 'fmc', 'unsupported' Parameters ---------- tx : list One per timetrace rx : list One per timetrace Returns ------- capture_method : s...
d41f2cf3a6adf191ba092828d45eae265a8c5a81
36,891
def SieveFilter(*args, **kwargs): """ SieveFilter(Band srcBand, Band maskBand, Band dstBand, int threshold, int connectedness=4, char ** options=None, GDALProgressFunc callback=0, void * callback_data=None) -> int """ return _gdal.SieveFilter(*args, **kwargs)
2f36ad6f6a88e57aadea2fe38b8925d66603ce49
36,893
def desc(col): """Sort by `col` descending.""" return Descending(col)
0979d5628be8647ca8f1414f78150b42992542a2
36,895
def compare_names(tag, name, tagname=None): """Compare a tag against a filename and return if they're the same Common substitutions will be tried. Dates will only require the minimum provided data to match """ if tagname in DATE_TAGS: return Date.parse(tag) == Date.parse(name) is not None ...
a61e1c98d0098ed71a31b2a48f046c934f15f284
36,896
import re def clean_text(text: str, remove_punctuation=False) -> str: """Cleans the inputted text based on the rules given in the comments. Code taken from: https://github.com/kk7nc/Text_Classification/ Args: text (str): the text to be cleaned remove_punctuation (bool): whether to remove ...
0f666041724315696924808c335c0110b7ffc158
36,897
def doc(obj=None, itm=None, docs=None, prefix=None): """Python IVI documentation generator""" st = "" # add a dot to prefix when needed if prefix is None or len(prefix) == 0: prefix = '' elif not prefix[-1] == '.': prefix += '.' # if something passed in docs, iterate ov...
aa5652169f5864fdcecc12a53b964c8e0488186b
36,898
def buscaNumQueries(): """ Pela leitura do arquivo de configuração config.ini, retorna o número de queries configuradas. :return número de consultas cadastradas no arquivo de configuração """ # Cria um set com as queries registradas no arquivo de configuração queries = set() contador...
0b2da81aa7eb8490e3556598982f601802bcf8d4
36,899
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 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
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
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
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 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
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 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 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
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
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
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
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
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
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
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
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
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 pandas_read_xlsb_file(filepath): """ https://stackoverflow.com/questions/45019778/read-xlsb-file-in-pandas-python Accepts a filepath - pathlib.Path object Reads an xlsb file into a dataframe Returns the dataframe """ dfs = [] with open_xlsb(filepath) as wb: with wb.get_sheet(...
eb04c2eee736cca81b1e58a11090517b27bea879
37,001
from typing import List def join_batch_meshes_as_scene( meshes: List[ParametricMeshes], include_textures: bool = True) -> ParametricMeshes: """Join `meshes` as a scene each batch. For ParametricMeshes. The Meshes must share the same batch size, and topology could be different. They must al...
3758e6d3e47b20747669d8f89e3a146b1fe1bb0a
37,002
import pathlib def load_dxf(dxf_filepath: pathlib.Path): """ Import any-old-shape in dxf format for analysis. Code by aegis1980 and connorferster """ if not dxf_filepath.exists(): raise ValueError(f"The filepath does not exist: {dxf_filepath}") my_dxf = c2s.dxf.Dxf...
68af5d3a7c779b468c6235fb5e4534f1695850eb
37,003
def validate_cv_implementation(impl, bootstrap=False): """Validate a back end for computing variables, returning it. Raise an exception if it is invalid. The second argument is for internal use only. """ # Note that the very first call to this with a non-None argument, # and with bootstrap giv...
f87d6ce0b978cc44e82b5a0ad92dfc2b99e8300d
37,004
def accuracy_op(predictions, targets): """ accuracy_op. An op that calculates mean accuracy. Examples: ```python input_data = placeholder(shape=[None, 784]) y_pred = my_network(input_data) # Apply some ops y_true = placeholder(shape=[None, 10]) # Labels acc_op = acc...
b726b0e9a5089f53ed050a70b930ef4603c69cf4
37,005
import time def detect_image(image, yolo, all_classes): """Use yolo v3 to detect images. # Argument: image: original image. yolo: YOLO, yolo model. all_classes: all classes name. # Returns: image: processed image. """ pimage = process_image(image) start = tim...
c50b56f115a95ba2523231291ff1f1873b8bd5e7
37,006
def list_entry_factory(db): """ Fixture to get the factory used to create list entries. """ return factories.ListEntryFactory
a7ddaa90999f0ab5767f96b7abe6502cdb54e663
37,007
def fractals_tholins(wvln, rm, Df, N, db=Database(), **kwargs): """Fractals cross-sections and phase function for tholin aggregate. Use default tholins indexes and Tomasko et al. 2008. Parameters ---------- wvln: float Wavelength (m). rm: float Monomer radius (m). Df: float...
48e9cc54bfccd522333b8df08a7cdbfc814d73bb
37,008
def _apply_quat(quat, pts, move=True): """Apply MaxFilter-formatted head position parameters to points.""" trans = np.concatenate( (quat_to_rot(quat[:3]), quat[3:][:, np.newaxis]), axis=1) return(apply_trans(trans, pts, move=move))
3f43c2b925475e3a53775a3d004b8415e104248e
37,009
def spherical_to_vector(spherical): """ Convert a set of (n, 2) spherical vectors to (n, 3) vectors Parameters ------------ spherical : (n , 2) float Angles, in radians Returns ----------- vectors : (n, 3) float Unit vectors """ spherical = np.asanyarray(spherical,...
61c3140c377bb72e6b0e31b03d1d68c9a4eeca74
37,010