content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cuda_reshape(a, shape): """ Reshape a GPUArray. Parameters: a (gpu): GPUArray. shape (tuple): Dimension of new reshaped GPUArray. Returns: gpu: Reshaped GPUArray. Examples: >>> a = cuda_reshape(cuda_give([[1, 2], [3, 4]]), (4, 1)) array([[ 1.], ...
966cae8aeb88aeaeada28a11c284920746771f00
23,881
def test_ep_basic_equivalence(stateful, state_tuple, limits): """ Test that EpisodeRoller is equivalent to a BasicRoller when run on a single environment. """ def env_fn(): return SimpleEnv(3, (4, 5), 'uint8') env = env_fn() model = SimpleModel(env.action_space.low.shape, ...
4f9632bd088a0be806ca9c4f51e3c5bc55431513
23,882
def _find_crate_root_src(srcs, file_names=["lib.rs"]): """Finds the source file for the crate root.""" if len(srcs) == 1: return srcs[0] for src in srcs: if src.basename in file_names: return src fail("No %s source file found." % " or ".join(file_names), "srcs")
dd3488b49dc6c315c3d35ead75a83008e7bcd962
23,883
def decode_check(string): """Returns the base58 decoded value, verifying the checksum. :param string: The data to decode, as a string. """ number = b58decode(string) # Converting to bytes in order to verify the checksum payload = number.to_bytes(sizeof(number), 'big') if payload and sha256d...
716c0a92be68feb2a97cacfd57940e9e43fa07d9
23,884
import math def rotate(origin, point, angle): """ Rotate a point counterclockwise by a given angle around a given origin. The angle should be given in radians. """ ox, oy = origin px, py = point qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy) qy = oy + math.sin(ang...
9c542fd45b8b53bad61121429377298bd9d7fd08
23,885
def get_users_info(token, ids): """Return a response from vk api users.get :param token: access token :param ids: users ids :return: dict with users info """ args = { 'user_ids': ids, 'fields': 'city,bdate,connections,photo_200', 'access_token': token, 'v': set...
02246232df0f3eebc530e05e1734e10f6be5ed9e
23,886
def create_consistencygroup(ctxt, host='test_host@fakedrv#fakepool', name='test_cg', description='this is a test cg', status='available', availability_zone='fake_az', ...
a7548774690eccdc0c44231ae10dd345c9e84eb8
23,887
def ndigit(num): """Returns the number of digits in non-negative number num""" with nowarn(): return np.int32(np.floor(np.maximum(1,np.log10(num))))+1
ac83e0b31ce9213646e856aa47fa8bfba7d74a86
23,888
def data_store_folder_unzip_public(request, pk, pathname): """ Public version of data_store_folder_unzip, incorporating path variables :param request: :param pk: :param pathname: :return HttpResponse: """ return data_store_folder_unzip(request, res_id=pk, zip_with_rel_path=pathname)
7866ed0539a00e16cbe0cbb2ab6902faebfd4434
23,889
def privateDataOffsetLengthTest10(): """ Offset doesn't begin immediately after last table. >>> doctestFunction1(testPrivateDataOffsetAndLength, privateDataOffsetLengthTest10()) (None, 'ERROR') """ header = defaultTestData(header=True) header["privOffset"] = header["length"] + 4 header[...
8744b97da80151a24c480ad29d2b1625f0c687f0
23,890
def meanncov(x, y=[], p=0, norm=True): """ Wrapper to multichannel case of new covariance *ncov*. Args: *x* : numpy.array multidimensional data (channels, data points, trials). *y* = [] : numpy.array multidimensional data. If not given the autocovariance of *x* will...
926bc64a0b7e15822f40f705ac3e770a57bb2e11
23,891
def nasnet_6a4032(**kwargs): """ NASNet-A 6@4032 (NASNet-A-Large) model from 'Learning Transferable Architectures for Scalable Image Recognition,' https://arxiv.org/abs/1707.07012. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ...
78f8862a69c12e8de85dc441e6b45e364d9b3385
23,892
def get_character_card(character_id, preston, access_token): """Get all the info for the character card. Args: character_id (int): ID of the character. preston (preston): Preston object to make scope-required ESI calls. access_token (str): Access token for the scope-required ESI calls. ...
23f201833537a8a596e42acc41061a583ebead38
23,893
def expand_ALL_constant(model, fieldnames): """Replaces the constant ``__all__`` with all concrete fields of the model""" if "__all__" in fieldnames: concrete_fields = [] for f in model._meta.get_fields(): if f.concrete: if f.one_to_one or f.many_to_many: ...
8c44c9b16fd93ca1c9a4efddd1ea85b44d34dba3
23,894
def server(user, password): """A shortcut to use MailServer. SMTP: server.send_mail([recipient,], mail) POP3: server.get_mail(which) server.get_mails(subject, sender, after, before) server.get_latest() server.get_info() server.stat() Parse mail: ...
acd2e2b69b6fe22ac8ae40cbe1b9d51a750e4e46
23,895
def calculate_hessian(model, data, step_size): """ Computes the mixed derivative using finite differences mathod :param model: The imported model module :param data: The sampled data in structured form :param step_size: The dx time step taken between each :returns: mixed derivative """ hessian = pd....
44ebed355e5db7991080e55f786850fb6b0e8908
23,897
def get_quarterly_income_statements(symbol): """ Returns quarterly IS for the past 5 yrs. """ df = query_av(function="INCOME_STATEMENT", symbol=symbol, datatype='quarterlyReports') return df
2b9094da22782d02ff5c6e4f32930c0816d213a9
23,898
def BRepBlend_HCurve2dTool_IsPeriodic(*args): """ :param C: :type C: Handle_Adaptor2d_HCurve2d & :rtype: bool """ return _BRepBlend.BRepBlend_HCurve2dTool_IsPeriodic(*args)
707895ece8aa032bcd6b747c5be0313102758957
23,899
def HLRBRep_SurfaceTool_OffsetValue(*args): """ :param S: :type S: Standard_Address :rtype: float """ return _HLRBRep.HLRBRep_SurfaceTool_OffsetValue(*args)
e1bfa0f05cac1afd82b599f9dd75f2a860b82b3b
23,900
def update_cv_validation_info(test_validation_info, iteration_validation_info): """ Updates a dictionary with given values """ test_validation_info = test_validation_info or {} for metric in iteration_validation_info: test_validation_info.setdefault(metric, []).append(iteration_validation_...
b2509026e968b1c428836c5313e9c5e824663d4f
23,901
from datetime import datetime def epoch_to_datetime(epoch: str) -> datetime: """ :param epoch: :return: """ return datetime.datetime.fromtimestamp(int(epoch) / 1000)
5044c30d4acace727858075d66032e563a5ece0d
23,902
import torch def calculate_log_odds( attr: Tensor, k: float, replacement_emb: Tensor, model, input_emb: Tensor, attention_mask: Tensor, prediction: Tensor, ) -> float: """ Log-odds scoring of an attribution :param attr: Attribution scores for one sentence :param k: top-k v...
d824e6705272eba3d24b061e2255700c05cb3f2a
23,903
import configparser def parse_ini(path): """Simple ini as config parser returning the COHDA protocol.""" config = configparser.ConfigParser() try: config.read(path) return True, "" except ( configparser.NoSectionError, configparser.DuplicateSectionError, configp...
6d6f49f9d59c9ff72086cf9c6262e2bab829a369
23,905
import re def number_of_positional_args(fn): """Return the number of positional arguments for a function, or None if the number is variable. Looks inside any decorated functions.""" try: if hasattr(fn, "__wrapped__"): return number_of_positional_args(fn.__wrapped__) if any(p.ki...
0cb50ea4a8f21d35711ff4848809f9db530d0099
23,906
def check_space(space): """ Check the properties of an environment state or action space """ if isinstance(space, spaces.Box): dim = space.shape discrete = False elif isinstance(space, spaces.Discrete): dim = space.n discrete = True else: raise NotImplementedErr...
b5b186accb94afd1849312959f0c579b94f9300a
23,907
def finish_work(state): """Move all running nodes to done""" state.progress.done = state.progress.done | state.progress.running state.progress.running = set() return state
649e14091737ef36db83b70591b09ee668a416f1
23,908
def show_submit_form(context, task, user, redirect, show_only_source=False): """Renders submit form for specified task""" context["task"] = task context["competition_ignored"] = user.is_competition_ignored(task.round.semester.competition) context["constants"] = constants context["redirect_to"] = red...
7c09408f40da263d346d59ef49c85afb0d93e13a
23,909
def index_of_masked_word(sentence, bert): """Return index of the masked word in `sentence` using `bert`'s' tokenizer. We use this function to calculate the linear distance between the target and controller as BERT sees it. Parameters ---------- sentence : str Returns ------- int ...
b8a3999db7c7ca8379e60998bb9ad0617a878a6d
23,910
def vgg19(down=8, bn=False, o_cn=1, final='abs'): """VGG 19-layer model (configuration "E") model pre-trained on ImageNet """ model = VGG(make_layers(cfg['E'], batch_norm=False), down=down, o_cn=o_cn, final=final) model.load_state_dict(model_zoo.load_url(model_urls['vgg19']), strict=False) r...
c20dcaed98a5dcfee1f78b3d7ec4f2a3d63cce1b
23,912
from vk_auth__requests_re import auth import re from bs4 import BeautifulSoup def get_short_link_from_vk(login: str, password: str, link: str) -> str: """ Функция для получения короткой ссылки используя сервис vk. """ session, rs = auth(login, password) # Страница нужна чтобы получить hash для ...
aec82fc6ec9cce97a3a55926b21f5c3b35a56015
23,913
def student_list(request): """ List all students, or create a new student. """ if request.method == 'GET': students = Student.objects.all() serializer = StudentSerializer(students, many=True) return Response(serializer.data) elif request.method == 'POST': serializer ...
2948d58c18b07d858e094eb4fbf0d5eac2fa1e6e
23,914
import time def get_model_features(url, chromedriver): """For given model url, grab categories and tags for that model""" try: BROWSER.get(url) time.sleep(5) cats = BROWSER.find_elements_by_xpath("//section[@class='model-meta-row categories']//ul//a") cats = [cat.text for cat i...
6fd902186c05027032977fb8ffec741559ae389f
23,915
def sent2labels(sent): """ Extracts gold labels for each sentence. Input: sentence list Output: list with labels list for each token in the sentence """ # gold labels at index 18 return [word[18] for word in sent]
11b4dc93c465d154e8bf8688a5b5c592b94e7265
23,916
def get_course_id_from_capa_module(capa_module): """ Extract a stringified course run key from a CAPA module (aka ProblemBlock). This is a bit of a hack. Its intended use is to allow us to pass the course id (if available) to `safe_exec`, enabling course-run-specific resource limits in the safe exe...
dd76b1d6df12f6c7db0d095bb9a48940a850e5c7
23,917
def _gershgorin_circles_test(expr, var_to_idx): """Check convexity by computing Gershgorin circles without building the coefficients matrix. If the circles lie in the nonnegative (nonpositive) space, then the matrix is positive (negative) definite. Parameters ---------- expr : QuadraticExp...
282d873b4ef691a9402cc57f3a8181417b06ffc1
23,919
from typing import List from faker import Faker import random from datetime import datetime def make_papers( *, n_papers: int, authors: AuthorList, funders: FunderList, publishers: PublisherList, fields_of_study: List, faker: Faker, min_title_length: int = 2, max_title_length: int ...
2422c176e3a170c646a33f4d372057451cc22775
23,920
def parse_cypher_file(path: str): """Returns a list of cypher queries in a file. Comments (starting with "//") will be filtered out and queries needs to be seperated by a semilicon Arguments: path {str} -- Path to the cypher file Returns: [str] -- List of queries """ def chop_comm...
00c4d357dee9e77160875fd8abb6c2b23d60a091
23,921
def del_method(): """del: Cleanup an item on destroy.""" # use __del__ with caution # it is difficult to know when the object will be actually removed context = "" class _Destroyable: def __del__(self): nonlocal context context = "burn the lyrics" item = _Dest...
727e9cee3048ee0c43111dc193746e44f55f5881
23,922
def sample_user(email="test@local.com", password="testpass"): """Create a sample User""" return get_user_model().objects.create_user(email, password)
c0c3c94072e35d2e385cdfafc0cac0bf73eba6b5
23,923
from typing import Optional def _precedence(match): """ in a dict spec, target-keys may match many spec-keys (e.g. 1 will match int, M > 0, and 1); therefore we need a precedence for which order to try keys in; higher = later """ if type(match) in (Required, Optional): match = matc...
9b82462632a5b087e4863144338d746c7687b06a
23,924
def experiment_set_reporting_data(connection, **kwargs): """ Get a snapshot of all experiment sets, their experiments, and files of all of the above. Include uuid, accession, status, and md5sum (for files). """ check = CheckResult(connection, 'experiment_set_reporting_data') check.status = 'IGNO...
9d0e4279788522dc2d12b1693a8c12de06b894de
23,925
def display2D(data,show=None,xsize=None,ysize=None,pal=None): """display2D(data,show=None,xsize=None,ysize=None) - create color image object from 2D list or array data, and the color palette is extracted from 'pal.dat', if show=1 specified by default a 300x300 window shows the data image xsize, ysize override th...
59c8905e29ac680b01821413305b3705e93b4c70
23,926
def read_port_await_str(expected_response_str): """ It appears that the Shapeoko responds with the string "ok" (or an "err nn" string) when a command is processed. Read the shapeoko_port and verify the response string in this routine. If an error occurs, a message. :param expected_response_str: ...
8bbab3158a9afb0769746eeb590812b0b401d557
23,927
import inspect import types def doify(f, *, name=None, tock=0.0, **opts): """ Returns Doist compatible copy, g, of converted generator function f. Each invoction of doify(f) returns a unique copy of doified function f. Imbues copy, g, of converted generator function, f, with attributes used by Doi...
b0f028c1311a47cb191306aa06985e70cdce2a64
23,928
def deserialize(config, custom_objects=None): """Inverse of the `serialize` function. Args: config: Optimizer configuration dictionary. custom_objects: Optional dictionary mapping names (strings) to custom objects (classes and functions) to be considered during deserialization. Returns: ...
acf9290d84d99bd5d630b8ab38734ce245303f6e
23,929
def unquote_to_bytes(string): """unquote_to_bytes('abc%20def') -> b'abc def'.""" # Note: strings are encoded as UTF-8. This is only an issue if it contains # unescaped non-ASCII characters, which URIs should not. if isinstance(string, str): string = string.encode('utf-8') res = string.split(...
7148b06e10fc92864d9875c785a6397a0a4950aa
23,930
def validators(*chained_validators): """ Creates a validator chain from several validator functions. :param chained_validators: :type chained_validators: :return: :rtype: """ def validator_chain(match): # pylint:disable=missing-docstring for chained_validator in chained_valida...
bba03b12c8de007882320e23377a32072734844a
23,931
def jacobian(vf): """Compute the jacobian of a vectorfield pointwise.""" vf0_dz, vf0_dy, vf0_dx = image_gradients(vf[..., 0:1]) vf1_dz, vf1_dy, vf1_dx = image_gradients(vf[..., 1:2]) vf2_dz, vf2_dy, vf2_dx = image_gradients(vf[..., 2:3]) r1 = tf.concat([vf0_dz[..., None], vf0_dy[..., None], vf0_dx[...
c1415852f3bf919818b59e7f6524e9773021ec1f
23,932
def insert_ones(y, segment_end_ms, Ty, steps=50, background_len=10000.0): """Update the label vector y The labels of the output steps strictly after the end of the segment should be set to 1. By strictly we mean that the label of segment_end_y should be 0 while, the 50 followinf labels should be ones. ...
f820a4d9d8720ee5eae916ffe865a822cea15135
23,933
def stream_name_mapping(stream, exclude_params=['name'], reverse=False): """ Return a complete dictionary mapping between stream parameter names to their applicable renames, excluding parameters listed in exclude_params. If reverse is True, the mapping is from the renamed strings to the origina...
5a9c9ab80ad470c45d22f2e360cc53c979300825
23,934
def newton(f, df, x0, tolx, tolf, nmax): """ Algoritmo di Newton per il calcolo dello zero di una funzione. :param f: la funzione di cui calcolare lo zero :param df: la derivata della funzione di cui calcolare lo zero :param x0: il valore di innesco :param tolx: la tolleranza sull'incremento ...
c362e2495034eaeb8a87e1d7363ec9f7a5b146a0
23,935
def preprocess(x, scale='std', clahe=True): """ Preprocess the input features. Args: x: batch of input images clahe: perform a contrast limited histogram equalization before scaling scale: 'normalize' the data into a range of 0 and 1 or 'standardize' ...
dae27316487bbcad3f94fbe538b9c90ffc3dd845
23,936
def endswith(s, tags): """除了模拟str.endswith方法,输入的tag也可以是可迭代对象 >>> endswith('a.dvi', ('.log', '.aux', '.dvi', 'busy')) True """ if isinstance(tags, str): return s.endswith(tags) elif isinstance(tags, (list, tuple)): for t in tags: if s.endswith(t): retu...
c30228f412552d08d09d9c50bdc20f4401477ba5
23,937
from typing import Sequence def parse(data): """ Takes the byte string of an x509 certificate and returns a dict containing the info in the cert :param data: The certificate byte string :return: A dict with the following keys: - version """ structure = load(data...
17e8eceb8e15078d9d4a5a82a95d1f92be3e7819
23,938
def to_auto_diff(x): """ Transforms x into a automatically differentiated function (ADF), unless it is already an ADF (or a subclass of it), in which case x is returned unchanged. Raises an exception unless 'x' belongs to some specific classes of objects that are known not to depend on ADF obj...
9824759c5ee3bee8c00ed7218ae502099b162200
23,939
def voc_eval(class_recs: dict, detect: dict, iou_thresh: float = 0.5, use_07_metric: bool = False): """ recall, precision, ap = voc_eval(class_recs, detection, [iou_thresh], [use_07_metric]) Top level fun...
5842a31523aff85342c69300bcf1aeffa98e14e7
23,940
def birth() -> character.Character: """Gives birth to krydort.""" krydort = character.Character('Krydort Wolverry') krydort.attributes.INT = 8 krydort.attributes.REF = 6 krydort.attributes.DEX = 6 krydort.attributes.BODY = 6 krydort.attributes.SPD = 4 krydort.attributes.EMP = 10 ...
09b81202cd39907f98b7d267445b5a728562288d
23,941
def LinearCombinationOfContVars(doc:NexDoc, resultName, contVar1:NexVar, coeff1, contVar2:NexVar, coeff2): """Calculates a linear combination of two continuous variables.""" return NexRun("LinearCombinationOfContVars", locals())
86e6438b364b78a6cd6cea31593a1304f090df56
23,943
def handler404(request, exception): # pylint: disable=unused-argument """404: NOT FOUND ERROR handler""" response = render_to_string( "404.html", request=request, context=get_base_context(request) ) return HttpResponseNotFound(response)
2e93076db5d3170a9c6d11b68facbabcddd7649f
23,944
def get_notification_user(operations_shift): """ Shift > Site > Project > Reports to """ if operations_shift.supervisor: supervisor = get_employee_user_id(operations_shift.supervisor) if supervisor != doc.owner: return supervisor operations_site = frappe.get_doc("Operations Site", operations_sh...
9bd829f9ba3f1424221d9abab9775f2964ad48ec
23,945
from typing import Optional from typing import List from typing import Dict from typing import Any def list_groups( namespace: str = "default", account_id: Optional[str] = None, boto3_session: Optional[boto3.Session] = None ) -> List[Dict[str, Any]]: """List all QuickSight Groups. Parameters --------...
d599262dc2045a781f840ee82f2d7324605f41ab
23,946
def big_diagram(BFIELD=1000,output='S0'): """ Main code to plot 'big' diagram with the following components: - Theoretical absorption spectrum (top panel) - Breit Rabi diagram for 0 to specified B-field (left) - Energy levels for ground and excited states (bottom panel) - Arrows for each transition, undernea...
ad72a778b067fa09d42a514e85ab499b52f899c4
23,948
def referenced_fmr(X=None, Y=None, Z=None, delta_x_idx:{"type": "int", "min":0, "max": 1, "hint": "Distance of the background signal (in x-index units)"}=0,): """ For each X-index, calculate Z[X]-X([+delta_x_idx], X will be set to X[X] ...
fb0768d2de813b5fde3c167fcb0d738b4476e802
23,949
def categorize_dish(dish_name, dish_ingredients): """ :param dish_name: str :param dish_ingredients: list :return: str "dish name: CATEGORY" This function should return a string with the `dish name: <CATEGORY>` (which meal category the dish belongs to). All dishes will "fit" into one of the ca...
dfe86e53a1bf013f2633c64972ee0415774d24cd
23,950
def generate_points_realistic(N=100, distortion_param=0, rng=None): """Generates two poses and the corresponding scene points and image points.""" # Check if a seed is used (for unittests) if not rng: rng = np.random.default_rng() # Relative translation t = 2 * rng.random((3, 1)) - 1 #...
8ca04480f12f645c62b1b6c65dea49e691c6e35f
23,952
def search_covid_results(patient_id: str, covid_df: pd.DataFrame): """ Given a patient ID and a dataframe of COVID-19 PCR results, return whether a patient had a positive result at any point and the date of their first positive. If no positives but negative results exist, return...
af4a453fb3b3416f7052e08622c1ce28777871e9
23,954
from pathlib import Path def str_is_path(p: str): """Detects if the variable contains absolute paths. If so, we distinguish paths that exist and paths that are images. Args: p: the Path Returns: True is is an absolute path """ try: path = Path(p) if path.is_absolu...
79234f0bfe9a34d3335b2be2306f8ef3d8e90eed
23,956
def PLAY(command: Command) -> Command: """ Moves clip from background to foreground and starts playing it. If a transition (see LOADBG) is prepared, it will be executed. """ return command
eebafb654cf6daef130c928d9b9ce003cb370a4b
23,957
from typing import Any import json def deserialize(data: str) -> dict: """ Given a string, deserialize it from JSON. """ if data is None: return {} def fix(jd: Any) -> Any: if type(jd) == dict: # Fix each element in the dictionary. for key in jd: ...
ce7282fc99985a348ae9cf2748132e0f53993b51
23,958
def seq_windows_df( df, target=None, start_index=0, end_index=None, history_size=1, target_size=1, step=1, single_step=False, ): """ create sliding window tuples for training nns on multivar timeseries """ data = [] labels = [] start_index = start_index + history_...
f95511c761e2da9ed493a71e9e849038d5fbba8b
23,959
from typing import List from typing import Callable def get_cachable_provider( cachables: List[Cachable] = [Collection1(), Collection2()] ) -> Callable[[], List[Cachable]]: """ Returns a cachable_provider. """ return lambda: cachables
5c2e20b35fe472027ba6015ba7e3b896125ca6fd
23,960
def getQuality(component, propertyName): # type: (JComponent, String) -> int """Returns the data quality for the property of the given component as an integer. This function can be used to check the quality of a Tag binding on a component in the middle of the script so that alternative actions ...
a17f8fe581941c67935e0ce61d82ba7a407f77aa
23,961
def norm1(x): """Normalize to the unit sphere.""" return x / x.square().sum(axis=-1, keepdims=True).sqrt()
f65ce24fee174b579243c627e2b5526a83db973e
23,962
def markup_sentence(s, modifiers, targets, prune_inactive=True): """ Function which executes all markup steps at once """ markup = pyConText.ConTextMarkup() markup.setRawText(s) markup.cleanText() markup.markItems(modifiers, mode="modifier") markup.markItems(targets, mode="target") marku...
397a5b2fef35ab3796917bede355e739868ad54e
23,963
def get_stream_info(stream_id): """ Uses the `/stream/info` endpoint taking the stream_id as a parameter. e.g. stream_id="e83a515e-fe69-4b19-afba-20f30d56b719" """ endpoint = KICKFLIP_API_URL + '/stream/info/' payload = {'stream_id': stream_id} response = kickflip_session.post(endpoint, p...
f590a3b3eb6764e01168fb2c93c9c566acd452d1
23,964
def invchisquared_sample(df, scale, size): """Return `size` samples from the inverse-chi-squared distribution.""" # Parametrize inverse-gamma alpha = df/2 beta = df*scale/2. # Parametrize gamma k = alpha theta = 1./beta gamma_samples = np.random.gamma(k, theta, size) return 1./g...
b8151f69efecd62c632e53ec62890223098fc78c
23,965
import scipy.io as sio def get_data_from_matlab(file_url, index, columns, data): """Description:* This function takes a Matlab file .mat and extract some information to a pandas data frame. The structure of the mat file must be known, as the loadmat function used returns a dictionary of arrays a...
e7e28ed0a0a5f9d35e195df847218b4bea110840
23,966
def get_loop_end(header: bytes) -> int: """Return loop end position.""" assert isinstance(value := _unpack(header, "LOOP_END"), int), type(value) assert 0 < value < 65535, value return value
b04b9c109ce1936ca87cdbd61615039e367176fb
23,967
import warnings def measuresegment(waveform, Naverage, minstrhandle, read_ch, mV_range=2000, process=True, device_parameters=None): """Wrapper to identify measurement instrument and run appropriate acquisition function. Supported instruments: m4i digitizer, ZI UHF-LI Args: waveform (dict): wavefo...
d66b8fdb438295e97b6a09b199fff501dab7c2e5
23,969
def grid_definition_proj(): """Custom grid definition using a proj string.""" return { "shape": (1, 1), "bounds": (-4000000.0, -4000000.0, 4000000.0, 4000000.0), "is_global": False, "proj": example_proj, }
b24e7b9d93073cded80b3e0af4b0b35dbc2439e4
23,970
def _compare_lines(line1, line2, tol=1e-14): """ Parameters ---------- line1: list of str line2: list of str Returns ------- bool """ if len(line1) != len(line2): return False for i, a in enumerate(line1): b = line2[i] if type(a) not in {int, float...
ec45a9fea4dfea3988afaa8947d35e0cc5fb27ca
23,971
def helping_func(self, driver, value): """Helper function for testing method composition. """ return value + 1
2a204814213707a255b0b0e57e4d5ca23389045d
23,972
def add_languages_modify(schema, fields, locales=None): """Adds localized field keys to the given schema""" if locales is None: locales = get_locales() ignore_missing = toolkit.get_validator('ignore_missing') convert_to_extras = toolkit.get_converter('convert_to_extras') for locale in locale...
3c2f0e001e5d6c8df90fc67a472a854fe1d3913f
23,973
from re import T def from_iterable( iterable: tp.Union[tp.Iterable[T], pypeln_utils.Undefined] = pypeln_utils.UNDEFINED, use_thread: bool = True, ) -> tp.Union[Stage[T], pypeln_utils.Partial[Stage[T]]]: """ Creates a stage from an iterable. Arguments: iterable: A source Iterable. ...
cc07cf1c74fd9ce65af112753152d3b508575ff0
23,974
def get_consumer_secret(): """This is entirely questionable. See settings.py""" consumer_secret = None try: loc = "%s/consumer_secret.txt" % settings.TWITTER_CONSUMER_URL url = urllib2.urlopen(loc) consumer_secret = url.read().rstrip() exc...
21db497551396920fe87eb02ddb3267d8d4f9d7f
23,975
def preprocess(src, cutoff, shape=(240, 240)): """Pre-processes the image""" # Resizing the image, for computational reasons, else the algorithm will take too much time dst = cv2.resize(src, shape) # (automated) Canny Edge Detection dst = aced.detect(dst) # Binary or Adaptive thresholding ds...
76755a1a2698583f2afc8c05043acef072d6ad67
23,976
def is_aware(value): """ Determines if a given datetime.datetime is aware. The concept is defined in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. ...
82d1199c24ced594d86945b1b76fa595a30083c1
23,977
import fsspec def check_manifest(of: fsspec.core.OpenFile, manifest: str) -> bool: """ Check to see if a given string exists in a manifest file. Parameters ========== x: str The string to check. manifest: str The path to a manifest file. Returns ======= True if ...
3e44cf192081d648698d5049bf39b3b0aa86ec34
23,978
def loadExpObjectFast(filename): """loads a CiPdeN object from a JSON file irnores generation data, expect the first and the last Parameters ---------- filename : str includes path and filename Returns ------- dict returns a dict if it worked, else retu...
abd513ee1b699c6dab882ab8d223243cdf3f7802
23,979
def Vij_beam_correct(j, Vij, centre=None): """Corrects Vij for the beam amplitude. This is required when beam correction has not been done during calibration. Assumes identical beam patterns. Assumes calibrator source is at centre of image""" my_shape = Vij[0, 0, :, :].shape if centre is None: ...
4dafe4c9aaa092b03618fd3eda4fb066ce49a61d
23,980
import requests def get_data(github, selected_repos): """Generate json form custom-cards org.""" org = "custom-cards" data = {} repos = [] if selected_repos: repos.append(selected_repos) else: for repo in list(github.get_user(org).get_repos()): repos.append(repo.nam...
bc7586f024c2017d2a97acd397c46fb29c9b80af
23,981
def fensemble_boosting_regressor(preds_valid, targs_valid, preds_train, targs_train, alpha=0.9): """ Learn combination of ensemble members from training data using Gradient Boosting Regression Also provides prediction intervals (using quantile regression) alpha = % prediction interval https://sciki...
5cf6c04490fc1bb774bae50d305db1df5d266f2e
23,982
def setup_land_units(srank): """ Sets up our land forces for an effective social rank. We go through an populate a dictionary of constants that represent the IDs of unit types and their quantities. That dict is then returned to setup_units for setting the base size of our navy. Args: ...
06f9ba5dd5164355df16cdda28f4c34a1dc4dac9
23,983
def one_hot_encode_test(test, txt_indexes_test): """Return the test dataframe with label-encoded textual features. Keyword arguments: test -- the test dataframe txt_indexes_test -- ndarray of test textual column indexes """ test_dummies = pd.get_dummies(test.iloc[:, txt_indexes_test]) test.drop(test.sele...
41d60b9e3356e99c453ec022bff10ba90c096ad3
23,984
def get_with_label(label, tree): """ Get a tree's node given it's label """ return [n for n in tree.children if n.label == label][0]
fc976bcbbf8f5a03b2a17dd7b5c0061a22bedf60
23,985
import torch def load_state_dicts(checkpoint_file, map_location=None, **kwargs): """ Load torch items from saved state_dictionaries """ if map_location is None: checkpoint = torch.load(checkpoint_file) else: checkpoint = torch.load(checkpoint_file, map_location=map_location) for k...
dc0f6646043a03456e8ab45888866db5c517381d
23,986
import logging from re import T def build_transform_gen(cfg, is_train): """ Create a list of :class:`TransformGen` from config. Now it includes resizing and flipping. Returns: list[TransformGen] """ if is_train: min_size = cfg.INPUT.MIN_SIZE_TRAIN max_size = cfg.INPUT....
9102077f0f4c7e1796399386b64944e6e2cb4087
23,987
def rain_specific_attenuation(R, f, el, tau): """Compute the specific attenuation γ_R (dB/km) given the rainfall rate. A method to compute the specific attenuation γ_R (dB/km) from rain. The value is obtained from the rainfall rate R (mm/h) using a power law relationship. .. math:: \\gamma...
c4a4994c7bbb08b9156e308eb6b8b9a8c7d9a99a
23,988
def parse_input(usr_input): """Main logic of program""" usr_input = usr_input.strip() if usr_input.upper() == QUIT_KEY: #exit logic return False else: usr_input = usr_input.split() if len(usr_input) == 1: #if only one argument supplied default to weekly ...
f80ec34361f35c63a90f688a0e9cc77c67ccbbb1
23,990
def plot_feature_importances(clf, title='Feature Importance', feature_names=None, max_num_features=20, order='descending', x_tick_rotation=0, ax=None, figsize=None, title_fontsize="large", text_fontsize="...
2237451bcde4227bc7f5c912a39e0d7bdf511ced
23,991