content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
from typing import Tuple async def wallet_config( context: InjectionContext, provision: bool = False ) -> Tuple[Profile, DIDInfo]: """Initialize the root profile.""" mgr = context.inject(ProfileManager) settings = context.settings profile_cfg = {} for k in CFG_MAP: pk = f"wallet.{k}"...
c770e2882045623fe4384e7ecd59076baa06ddff
23,904
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
import os def _get_headers(): """Get headers for GitHub API request. Attempts to add a GitHub token to headers if available. Returns: dict: The headers for a GitHub API request. """ headers = {} github_token = os.getenv(env.GH_TOKEN, None) if github_token is not None: hea...
c291563fd5876d62b5495c951aadcda26584896e
23,911
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
import os def find_free_box_id() -> str: """ limits = prog_info["limits"] if "limits" in prog_info else {} Returns is of the first available sandbox directory. Searched for non-existing directories in /tmp/box. """ # Search for free id in EXEC_PATH ids = [True for i in range(MAX_CONCURREN...
f034e2e68bb01df189ca2474c3527cf34ce2d369
23,918
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
import os def imagePath(image): """ Return full path to given image. """ return os.path.join(":/images", image)
73d73bbdea81248c7342d60158f6e00f50c39bae
23,942
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
import re import os def find_tm5_output(path, expname=None, varname=None, freq=None): """ Finds TM5 outputfiles, which consist of varname + "_" + "AER"[freq] + * + dates + ".nc" inputs: Path (mandatory) experiment name (optional) varname (optional) frequency (optional) output: list...
6f605f992d7cc6722c523d77e2db9917abe883e3
23,947
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
from typing import Tuple from typing import List import os def read_text_subset( subset: str, source_dir: str = "data/CUB_200_2011_with_text/text" ) -> Tuple[List[str], List[int], List]: """ Read the pretrained embedding caption text for the birds and flowers datasets as encoded using a pretrained cha...
bf4cb73b5c1382965e2525b471992513a755d9d2
23,951
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
import array from typing import Optional def truncated_step( x: array, f_x: float, grad: array, step_size: float = 0.1, search_direction: Optional[array] = None, step_lower_bound: float = 0.0, ): """Motivated by https://arxiv.org/abs/1903.08619 , use knowledge of a lower-bound on f_x t...
af7be387044ddb9ddba4fcf02154dbd00c898035
23,953
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
import os def is_slow_test_hostile(): """Use this to disable some tests in CI enviroment where 15 minute deadline applies.""" return "CI" in os.environ or "SKIP_SLOW_TEST" in os.environ
df6f8028efde1e1dec56b82d93ced6e38b356398
23,955
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 os def report(filename: str, ignore_result: tuple, hide_empty_groups:bool): """{p}arse a report and do a simple output""" if not os.path.exists(filename): logger.error("Failed to find file {}, bailing", filename) return False if ignore_result: print(f"Ignoring the following...
acca7c36fdedf78da9870e42d38c491d1861d365
23,968
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 filter(dg, start=None, end=None, tasks=(), skip_with=states.SKIPPED.name): """Filters a graph TODO(dshulyak) skip_with should also support NOOP, which will instead of blocking task, and its successors, should mark task as visited :param skip_with: SKIPPED or NOOP """ error_msgs = [] su...
fa55364a57652ef655f8c26b1335d40580e4d5a8
23,989
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
def license(soup): """ Find the license text """ license = None try: license_section = get_license_section(soup) license = extract_node_text(license_section[0], "license-p") except(IndexError): return None return license
c7f677e369b7170623968cdfe0d0a85d75e4a339
23,992
def filter_nofix(df,NoFrames): """ Filter for immobilized origami with DNA-PAINT based tracking handle (TH) as described in `spt`_. Positives are groups - with a trajectory within the first 5 frames after the start of the measurement - and number localizations within group are greater...
e115cc479c984037adbe3dd662bed1aa70acaafd
23,993
def read_array(cls, start=None,end=None,weight=None,use_datetime = False, convert_delta = False): """ Read arrays of values for start, end and weight values that represent either the cummulative value of the data steps or the direct step values seperately, indexed by the start and possibly end arrays. ...
98b97a53883ed39d762849313cab64f29fadfd8d
23,994
def store_nugget_nodes(gold_nuggets, sys_nuggets, m_mapping): """ Store nuggets as nodes. :param gold_nuggets: :param sys_nuggets: :param m_mapping: :return: """ # Stores time ML nodes that actually exists in gold standard and system. gold_nodes = [] sys_nodes = [] # Store t...
659eeccc244d7dfe7fc1c4b9813844d70973b5dc
23,995
def return_union_item(item): """union of statements, next statement""" return " __result.update({0})".format(item)
60fff47ff948f5b62ff6c6793b9dd339c23ecfd7
23,996
def normalize_basename(s, force_lowercase=True, maxlen=255): """Replaces some characters from s with a translation table: trans_table = {" ": "_", "/": "_slash_", "\\": "_backslash_", "?": "_question_", "%": "_percent_", ...
8b6c6fee3a55b3d704294d8bdaa7f72101ac477b
23,997
import requests import os import tqdm def download_from_url(url, dst): """ kindly used from https://gist.github.com/wy193777/0e2a4932e81afc6aa4c8f7a2984f34e2 @param: url to download file @param: dst place to put the file """ file_size = int(requests.head(url).headers["Content-Length"]) if ...
5c063c22d927ead69cb1643a1b6a0fe83e92171b
23,998
import re def _get_toc_string_from_log(file_handle): """ Returns a toc string or None for a given log file (EAC or XLD) Copyright (c) 2018 Konstantin Mochalov Released under the MIT License Original source: https://gist.github.com/kolen/765526 """ def _filter_toc_entries(file_handle): ...
1b8152171dcc5a512ea92df96bdc63497f01499a
23,999