content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging import time def computeVoronoiDefects(lattice, refLattice, vacancies, voronoiOptions): """ Compute Voronoi for system containing defects """ logger = logging.getLogger(__name__) vorotime = time.time() logger.info("Computing Voronoi (defects)") logger.debug(" ...
4161b1e8f8b05547b3c962493abc2651068ed2ad
3,618,200
import warnings def mahalnobis(u, v): """ By Robin Hayman gets the mahalanobis distance between two vectors feature arrays u and v a blatant copy of the Mathworks fcn as it doesn't require the covariance matrix to be calculated which is a pain if there are NaNs in the matrix """ u_sz = u....
2f88c6116a3b5fb56f1d97ba98ae8025f1552a01
3,618,201
import urllib def is_valid_uri(uri): """Determine if the string is a valid URL. We use it to distringuish links from workflow variables.""" try: result = urllib.parse.urlparse(uri) return result.scheme and result.path except Exception as e: return False
9cfe68005b8578383543c5d8db498738ae12cd21
3,618,202
def tier_from_reader(stream): """Return a tier object from a stream of strings and numbers. Parameters ---------- stream : iterator of str, int, and float Iterator that yields strings and numbers in the order that Praat expects to define a tier. Returns ------- IntervalTier...
ad95ce728dc257888a5dab817e9de48a14a3bbc1
3,618,203
from typing import Dict from typing import Any def get_house_committees(biennium: str) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/committeeservice.asmx?op=GetHouseCommittees""" argdict: Dict[str, Any] = dict(biennium=biennium) keydict: Dict[str, Any] = {} return waleg.call("Committee"...
efebec8357ba0499120d82684e1c8e3f69990df3
3,618,204
import torch import copy def _train_dsm(x, t, e, folds, params): """Helper Function to train a deep survival machines model. Args: x: a numpy array of input features (Training Data). t: a numpy vector of event times (Training Data). e: a numpy vector of event indicators (1 if event...
30f5706824b060333f1263a3f14360d51852b448
3,618,205
def vote(request): """Ajax call to add an up vote to comment comment_pk.""" comment_pk = request.GET.get('comment_pk') c = Comment.objects.get(pk=int(comment_pk)) c.up_votes += 1 c.save() return JsonResponse({'id': comment_pk, 'count': c.up_votes})
6dd37768a075492460d480ba99a6d81bd3bcd08a
3,618,206
import requests def get_lovelive_info(): """ 从土味情话中获取每日一句 :return: str,土味情话 """ print('获取土味情话...') try: resp = requests.get('https://api.lovelive.tools/api/SweetNothings') if resp.status_code == 200: return resp.text print('土味情话获取失败。') except requests.ex...
daf73060c1caae261408b817a90ba81d25731f5a
3,618,207
def set_exploit_name(id_, name, user, **kwargs): """ Set a Exploit name. :param id_: Exploit ObjectId. :type id_: str :param name: The new name. :type name: str :param user: The user updating the name. :type user: str :returns: dict with keys: "success" (boolean), ...
1d39ce94c390abb4d5581701183a3bd6cb98db05
3,618,208
from typing import Union from pathlib import Path import os import json import yaml def readfile(fname: Union[str, Path]) -> Union[str, dict, np.ndarray]: """ Util function for reading a variety of different files """ fname = str(fname) ext = os.path.splitext(fname)[-1] if ext == ".json": ...
fa55c9ecd93de84c34c640d95a5e56f5cb80ce51
3,618,209
async def async_get_registry(hass) -> DeviceRegistry: """Return device registry instance.""" task = hass.data.get(DATA_REGISTRY) if task is None: async def _load_reg(): registry = DeviceRegistry(hass) await registry.async_load() return registry task = ha...
4d910529bcd026e5237a7ae3a8a5b80eaa9eefef
3,618,210
from typing import Any import json def read_json_file(filename: str) -> Any: """Read a json file Parameters ---------- filename : str The json file Returns ------- A json object Example ------- >>> import allyoucanuse as aycu >>> content = aycu.read_json_file...
e1afe013da96adfa5dd0e3ea998dce1323efe231
3,618,211
import json async def api_user_authenticate(request): """ 用户登录验证API函数 :param request: 请求对象 :return: 回响消息, 并且设置COOKIE """ request_data = RequestData(request) if not await request_data.json_load(): return data_error(u'非法数据格式, 请使用JSON格式') email = request_data.email password =...
9f2a4d4845c44194638fc3a4ba20236c69add098
3,618,212
import os import sys import shutil def get_best_invocation_for_this_pip() -> str: """Try to figure out the best way to invoke pip in the current environment.""" binary_directory = "Scripts" if WINDOWS else "bin" binary_prefix = os.path.join(sys.prefix, binary_directory) # Try to use pip[X[.Y]] names,...
58f6e6d409b321b323590c22db08aa755b928fff
3,618,213
import random import json def next_task(): """ To fetch data at this endpoint: $ curl -X GET localhost:8080/api/v0.1/task """ db = pybackend.database.Database( project=app.config['cloud']['project'], **app.config['cloud']['database']) random_uri = random.choice(list(db.uris(k...
ae4e42613c17ccff6a04fb237ad1a1b396c29c46
3,618,214
from datetime import datetime def get_last_ideas(json_data, d=1): """ Returns last ideas. @param: json_data - List of ideas in JSON format. @param: d - History length in days. """ selected_items = [] for item in json_data: date = format_string_to_date(item['created']) if da...
70ee39aa0fb185541d594faab7e443eb7424d242
3,618,215
def _build_histogram_root_no_hessian(n_bins, binned_feature, all_gradients): """Special case for the root node The root node has to find the split among all the samples from the training set. binned_feature and all_gradients already have a consistent ordering. Hessians are not updated (used when h...
7876c4e79f02dadba318510c9fd8623933a55ab1
3,618,216
from typing import Any from typing import MutableSequence from typing import Tuple from typing import Set from typing import Hashable def is_pipeline(item: Any) -> bool: """Returns whether 'item' is a pipeline.""" return isinstance(item, (MutableSequence, Tuple, Set) and all(isinstance(i...
c9626f5c9c05be44016239d1592e3a2961ec0a68
3,618,217
def cluster_state_circuit(bits): """Return a cluster state on the qubits in `bits`.""" circuit = cirq.Circuit() circuit.append(cirq.H.on_each(bits)) for this_bit, next_bit in zip(bits, bits[1:] + [bits[0]]): circuit.append(cirq.CZ(this_bit, next_bit)) return circuit
b20b34b366bbbfd36f7009d6d78ead2628841998
3,618,218
import functools def once(wrapped): """ Decorates a function that takes no arguments, ensuring it's only called once & that the result is memoized. This function is greenlet safe. """ wrapped._once_called = False wrapped._once_retval = None lock = RLock() @functools.wraps(wrapped) ...
9700e5dbb67e6cb7405cb13ca2d9c3bc5c44e8be
3,618,219
import inspect def get_exposed_members(obj, only_exposed=True, as_lists=False, use_cache=True): """ Return public and exposed members of the given object's class. You can also provide a class directly. Private members are ignored no matter what (names starting with underscore). If only_exposed is ...
daefa6230a0e6aad5d54e2f5f45777e1d9f42e57
3,618,220
def remove_group_project(repo, groupid, username=None, namespace=None): """Remove the specified group from the project.""" if not pagure_config.get("ENABLE_USER_MNGT", True): flask.abort( 404, description="User management is not allowed in this " "pagure instance", ...
3b52052d7242f63c1139144ddc8b7c9bb016aaef
3,618,221
def get_residue_sequence_poly_seq(cf, align_seq=True, verbose=False): """ used to work with load_struct_from_pdbfile, now uses load_pdbfile output :param structure: :return: """ # residue_sequence = list(np.array([[residue.resname.capitalize(), int(residue.id[1])] for residue in # ...
161b79385a2fb0c9e6078b440705643dab484683
3,618,222
import torch def _demo_head_inputs(input_shape=(1, 512, 8, 8)): """Create a superset of inputs needed to run test or train batches. Args: input_shape (tuple): input batch dimensions """ (N, C, H, W) = input_shape rng = np.random.RandomState(0) features = rng.rand(*input_...
cd313f89ac28cbaf98f1e39cb7760ca393e9e565
3,618,223
import torch def load_ckp(checkpoint_fpath,model): """ checkpoint_path: path to save checkpoint model: model that we want to load checkpoint parameters into optimizer: optimizer we defined in previous training """ # load check point # checkpoint = torch.load(checkpoint_fpath) ch...
c6d37907ec8a9a90dd11b9a48ceae46d59938aca
3,618,224
def get_config_string(config): """ Use the given config to extract one string for the output. :param config: a dictionary of configs from a Build object :return: string representation """ configs = {} for key, entry in config.items(): abbrev = entry.get('abbreviation') value ...
15c38f062af7900cb457ff5dfbad287a0edb75e3
3,618,225
def _api_shutdown(name, output, kwargs): """ API: accepts output """ sabnzbd.shutdown_program() return report(output)
795ed94feff5cfb9a9f0f581ab9a705b62f41984
3,618,226
def combine_loss_components(critic_loss_val, actor_loss_val, entropy_val, actor_loss_weight, entropy_bonus): """Combine the components in the combined AWR loss.""" return critic_loss_val + (actor_loss_val * actor_loss_weight) - ( entropy_val * entropy_bonus)
1a060140aa3e08944d2e3f4cf1e4603c88e16921
3,618,227
import json import logging def country_filter() -> str: """ find selected country to gather news from from config.json """ with open('config.json') as config_file: data = json.load(config_file) logging.info('Countries for news briefing located') return data['news_briefing'][0]['country']
35cfee9c0239dfef7ad352f2c17c2d3a4d140eb9
3,618,228
def get_env_agent_current(env = Depends(get_env)) -> str: """Returns name of currently expected agent.""" return env.agent_selection
07bb77fe10919b3ac9ec9401e420cf0fb32d96a0
3,618,229
import random import math def exponential_backoff(attempt_num): """Returns an exponential backoff value in seconds.""" assert attempt_num >= 0 if random.random() < _PROBABILITY_OF_QUICK_COMEBACK: # Randomly ask the bot to return quickly. return 1.0 # If the user provided a max then use it, otherwise ...
4be20f57a48a10bf085ae74d36f9b8ef85dc3e01
3,618,230
from typing import Callable from typing import Any import sys import time def watchdog(timeout: int | float, function: Callable, *args, **kwargs) -> Any: """Time-limited execution for python function. TimeoutError raised if not finished during defined time. Args: timeout (int | float): Max time execu...
c2b85b2a1c7887d940baf302e34b1e50b4e6247c
3,618,231
def _stop_container(container): """ Force remove a container """ try: logger.info(f'Stopping container {container.id}') container.remove(force=True) except: pass finally: return True
99cff9920c5e1789ec0f83c0b306d406cd47a17c
3,618,232
import warnings def _wmd(embedding_1, embedding_2, word_freq_1, word_freq_2, constraint_matrix=None): """ Calculate the Word mover´s Distance parameters --------- - embedding_1 : np.array (distinct words x embedding dimensions) -> embedding of the first article - ...
41e2e042eecc330f85124f09def5e707f2d63653
3,618,233
def converter(): """Bits to Target""" bits = int(request.form['bits'], 16) response = bits_to_target(bits) return jsonify(response), 200
d4e2aa29951cfe57f5cd1f1c809683d81b832725
3,618,234
def _coerce_exceptions(function): """ Decorator that causes exceptions thrown by the decorated function to be coerced into generic exceptions from the hadoop.fs.exceptions module. """ def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except Exception as e: e.msg = force...
fc10e071b5448c0f859f38bb0df523f1d53b7f64
3,618,235
def decode_der(cert_der): """Decode cert DER string to Certificate object. Args: cert_der : Certificate as a DER encoded string Returns: cryptography.Certificate() """ return cryptography.x509.load_der_x509_certificate( data=cert_der, backend=cryptography.hazmat.backends.defau...
007e40763c82c19c9ae9858fd9be0d5115c6e1d9
3,618,236
def find_threshold_by_precision(precisions, thresholds, p_cutoff): """This function finds the lowest index that guarantess a precision of at leat p_cutoff.""" return thresholds[np.argmax(precisions >= p_cutoff)]
b12990b505ed6ccdd2c5aad615ac21e2f9f9d2bd
3,618,237
def compare_vectors(phi, index1, index2): """ A function which compares the directions of two vectors given by polar co-ordinates. The two vectors are identified as being in the same (or opposite) directions for x and y. The returned array indicates which one of 4 possible alignments the two vecto...
11f033aa980c2883ad8d1bc5dafe01da917fd6b6
3,618,238
def cmplx(a,b,*vars): """ See VSIP specification for Information Convert Convert real, imaginary (a,b) into complex Usage: cmplx(a,b,c) where a and b are views of type vview_f or vview_d c is a compliant view of type cvview_f or cvview_d OR: c = cmplx(a,b) ...
dd98372ca40fc9199ad556e752afa186686826aa
3,618,239
import os import logging def pull(remote_path, local_path=None): """Download a file from the device. Arguments: remote_path(str): Path or directory of the file on the device. local_path(str): Path to save the file to. Uses the file's name by default. Return: The conte...
4da1e3b53fbddc75d7f69ea3b19ab8fcddaab76c
3,618,240
def build_vtk_colormap(colormap, vtk_colormap=None) : """ Build either a ``vtkLookupTable`` or a ``vtkColorTransferFunctionWithAlpha`` from the given colormap. The colormap is specified as a custom table -- which must respect the formats of the dictionaries defined in :func:`build_lookup...
3d85011fe2ba6c243192a9955d56d759dc659a23
3,618,241
def _get_message_from_model(message_model): """Converts the FeedbackMessageModel to a FeedbackMessage. Args: message_model: FeedbackMessageModel. The FeedbackMessageModel to be converted. Returns: FeedbackMessage. The resulting FeedbackMessage domain object. """ return ...
e67876b3e044475a66b06c7146df399c0a5894f2
3,618,242
import traceback def get_survey_ids(): """ categoryIdを元に、予約データのsurveyIdを取得する """ command = [] command.append('aws') command.append('dynamodb') command.append('scan') command.append('--table-name') command.append(table_name_survey_results) command.append('--profile') command...
1ff7522aa1502e96bfc83c9613de6796cdb608ae
3,618,243
def list_tracker_issue_field_value(tracker_id: str, field: str, project=None): """ GET /api/tracker/{tracker_id}/issue_field/{issue_field_id} :param tracker_id: :param field: :param project: :return: """ try: return { 'title': 'Succeed to list Issue Field Value from t...
8d0e404c06fde6339c4f1d2dd9b30ddd90f54c8e
3,618,244
def isogenies_5_1728(E): """ Returns a list of 5-isogenies with domain ``E`` when the j-invariant is 1728. OUTPUT: (list) 5-isogenies with codomain E. In general these are normalised; but if `-1` is a square then there are two endomorphisms of degree `5`, for which the codomain is the sam...
43a1ef6e70deedcf90c67ce3da86323fa472da69
3,618,245
from typing import Any def _parse_link(link: str) -> Any: """Parse rapid upload link Format 1: cs3l://<content_md5>#<slice_md5>#<content_crc3>#<content_length>#<filename> Format 2: <content_md5>#<slice_md5>#<content_length>#<filename> Format 3: bdpan://{base64(<filename>|<content_length>|<content_md5...
31dadddaa8cba85ccc954e3176b4fe2be9546bb3
3,618,246
def change_zone_to_coordinates(changing_data, which=None): """ Change zone data into coordinate. Get data with zone data and add coordinate data into original data. Last modified: 2019-11-24T22:19:49+0900 Args: changing_data (DataFrame): Mandatory. The DataFrame which contains zone data. ...
7da7f0f6d2468a87234f50cc39843ab08dcf17d6
3,618,247
def create_unwarp_workflow(name="unwarp", fieldmap_pe=("y", "y-")): """Unwarp functional timeseries using reverse phase-blipped images.""" inputnode = Node(IdentityInterface(["timeseries", "fieldmap"]), "inputs") # Calculate the shift field # Note that setting readout_times to 1 will give a fine # ...
eb7c5b94fbeeb7c5cc9eddb281b629c1da68a8f2
3,618,248
from datetime import datetime import os def main(dt=None): """Encodes the sample data-set. Returns path to where sample data file was saved. """ if dt is None: dt = datetime.datetime.now() filepath = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "sample.unk")) ...
56e0920376664b7cd4dcdcf9e6d70e41e257c8a5
3,618,249
def leadterm(e, x): """ Compute the leading term of the series. Returns ======= tuple The leading term `c_0 w^{e_0}` of the series of `e` in terms of the most rapidly varying subexpression `w` in form of the pair ``(c0, e0)`` of Expr. Examples ======== >>> lea...
b42f5edd78751576c32cda0b5729afc763a4493c
3,618,250
import os import shutil def write_recal_bam(data, region=None, out_file=None): """Step 2 of GATK recalibration -- use covariates to re-write output file. """ config = data["config"] if out_file is None: out_file = "%s-gatkrecal.bam" % os.path.splitext(data["work_bam"])[0] logger.info("Writ...
c39da5490534c6430a2b5c23ec23d895323bfbfe
3,618,251
def delete_group_resource_permissions_view(request): """ Delete a permission from a specific resource for a group. """ group = ar.get_group_matchdict_checked(request) resource = ar.get_resource_matchdict_checked(request) permission = ar.get_permission_multiformat_body_checked(request, resource) ...
442d75af042feb96a3a6c47945e90db87f0bb1c0
3,618,252
def get_bins(data): """Return bin edges for all unique values in data. """ bins = np.unique(data) return np.append(bins[~np.isnan(bins)], max(bins) + 1)
ebdcc658d7d1f6fc34865a9ee2e199c5b86e9c58
3,618,253
def filter_in_out_by_column_values (column, values, data, in_out): """Include rows only for given values in specified column. column - column name. values - list of acceptable values. """ if in_out == 'in': data = data.loc[data[column].isin (values)] else: data = data.loc...
191fa20edae7f67b245ad31658297d4a114f59fe
3,618,254
def parse_example_proto(example_serialized): """Parses an Example proto containing a training example of an image. The output of the build_image_data.py image preprocessing script is a dataset containing serialized Example protocol buffers. Each Example proto contains the following fields: ima...
a654e1ddcc35b2ec834de7bbc1a99c8fe7764eba
3,618,255
def intersection(set_1, set_2): """realisation of two sets intersection(simple set generator inside)""" return {i for i in set_1 if i in set_2}
d46a206e6c202343615c3b045a8885d8efd56607
3,618,256
import inspect def simulated_quantize_compute(attrs, inputs, out_type): """Compiler for simulated_quantize.""" assert len(inputs) == 5 assert attrs.sign assert attrs.rounding == "round" axis = attrs.axis data, in_scale, out_scale, clip_min, clip_max = inputs data = my_print(data, '\n\n***...
54a54e067da92903eb1af88797104f4035f02899
3,618,257
def dy(series, n=1): """Difference over n years""" return (series-series.shift(n*series.index.freq.periodicity))
1cc0561ea0bed5a11dee8da8d285c5faf402648c
3,618,258
def inad(V1,V2): """ Inertial advective wind <div class=jython> INAD ( V1, V2 ) = [ DOT ( V1, GRAD (u2) ), DOT ( V1, GRAD (v2) ) ] </div> """ return vecr(dot(V1,grad(ur(V2))),dot(V1,grad(vr(V2))))
d47240b55401df317fc76fb15d821d9d98406829
3,618,259
def get_node_log(request, biz_cc_id, node_id): """ @summary: 查看某个节点的日志 @param request: @param biz_cc_id: @param node_id @return: """ task_id = request.GET.get('instance_id') history_id = request.GET.get('history_id') try: task = TaskFlowInstance.objects.get(pk=task_id, b...
a5365648857caaf46c9cfe132d0d7c2cec33c5d1
3,618,260
def _app_options(self, url, headers=None, status=None, expect_errors=False): """ To be injected into TestApp if it doesn't have an options method available """ req = TestRequest.blank(path=url, method='OPTIONS', headers=headers, environ=self.extra_environ) return self.do_request(req, status, expect_...
6c78a9a4dc2b7d953fa9c0bacc1fd374a62e287c
3,618,261
from typing import Iterable from typing import Tuple def iter_with_final(it: Iterable[E]) -> Iterable[Tuple[E, bool]]: """ Change given iterator to new one yielding additional *final* flag. >>> list(iter_with_final(iter([1, 2, 3]))) [(1, False), (2, False), (3, True)] >>> list(iter_with_final(it...
8e4392066353b4226d90df2360ed37837280c1f3
3,618,262
def remlplen_herrmann(fp,fs,dp,ds): """ Determine the length of the low pass filter with passband frequency fp, stopband frequency fs, passband ripple dp, and stopband ripple ds. fp and fs must be normalized with respect to the sampling frequency. Note that the filter order is one less than the filt...
f4d3c2d96b5e15ac909155d5b0cb6d53d439352f
3,618,263
def CreateBooleanIntersection1(curveA, curveB, tolerance, multiple=False): """ Calculates the boolean intersection of two closed, planar curves. Note, curves must be co-planar. Args: curveA (Curve): The first closed, planar curve. curveB (Curve): The second closed, planar curve. Re...
13257250aa675ed25d50acd960093c1c8e527980
3,618,264
def pointer_scope(func): """The FDB format has a lot of pointers to structures, so this decorator automatically reads the pointer, seeks to the pointer position, calls the function, and seeks back.""" def wrapper(self, *args, **kwargs): pointer = kwargs.get("pointer") if pointer == None: pointer = self._read_...
a83abfcd0cb9b641aec3125fb267cc6c6f134884
3,618,265
import re def create_example_gpt(example: Example, tokenizer: Tokenizer) -> Example: """ Create example for GPT-[1,2] Substitute mask with <pad>, and store where the token was placed. During repr. collection, we'll need it. Example: >>> x = 'Most apples are [MASK].' ... tokenizer = transfo...
1b5c869ea63582ef2fef434d98add37e18200c94
3,618,266
from enum import Enum def should_smooth_series(tag: Enum) -> bool: """ :param tag: :return: """ if tag is TrainingScalars.training_loss: return True elif tag is TrainingScalars.validation_loss: return True return False
5661773451b0edda0bab8fcf32113e74f13ae518
3,618,267
from typing import Set from typing import Optional def load_all_plugins(module_path: Set[str], plugin_dir: Set[str]) -> Set[Plugin]: """ :说明: 导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入! :参数: - ``module_path: Set[str]``: 指定插件集合 - ``plugin_dir: Set[str]``: 指定插件路径集合 ...
cc7e7fd5cc6b2479e4ea5c1256ba88bba6031f70
3,618,268
import inspect def lineno(): """Returns the current line number in our program.""" return str( inspect.currentframe().f_back.f_lineno )
c973d4a0614cd6dafa5e67d0d4dda7f3d347d51a
3,618,269
def positive_rates(df, score_col, label_col, thresholds): """Compute false positive and true positive rates.""" tpr = [] fpr = [] for threshold in thresholds: confusion = confusion_matrix_counts(df, score_col, label_col, threshold) if ( confusion["tp"] + confusion["fn"] == 0 ...
081cc95b0aa2da7b17065e9aaa7dd54083a69fb2
3,618,270
def get_phrases(): """ Returns a phrases dictionary of the form <callback>:<list of phrases> """ return _config_object["phrases"]
43eb77cbac5274b638a5d8bde1c70dfaad339400
3,618,271
def graham_scan(points: np.ndarray) -> np.ndarray: """Find vertices of convex hull around points. Args: points: (x, y) coordinates of points. Returns: hull: points that are vertices on convex hull. """ primary, remaining_points = extract_primary(points) sorted_points = sort_for...
38dd708ade892c162067f9275e27d9865cd386e5
3,618,272
def waitfor(css_selector, text=None, classes=None): """ Decorator for specifying elements (selected by a CSS-style selector) to explicitly wait for before taking a screenshot. If text is set, wait for the element to contain that text before taking the screenshot. If classes is present, wait until th...
13130146441f20cfd424e52e46f2f2e3a7e33d3f
3,618,273
import argparse def parse_arguments(): """ Parse arguments passed to the script """ parser = argparse.ArgumentParser(description='File uploader to Firebase Storage.') parser.add_argument('config', help='Path of Firebase configuration file.') parser.add_argument('--filetoken', dest='filetoken', default...
1ce3117c64667aa5d50a88bfb64d03bce8b14995
3,618,274
def grandac(e, a, r, f_e): """Returns integrand for probability density of orbital radius where semi-major axis is a constant Args: e (float): Value of eccentricity a (float): Value of semi-major axis (AU) r (float): Value of orbital radius (A...
3e401dae075ceeba52dab250c7d979b23d2f3c85
3,618,275
def get_default_path(name): """this function takes a an import name and returns the path full bash of the library if the library is in stdlib""" name_ = name if isinstance(name, (DottedName, Symbol)): name_ = str(name) if name_ in pyccel_external_lib.keys(): name = pyccel_external...
c19d5e8b06616b1ee595098b4007d21f32117506
3,618,276
def get_requested_countries(countries, country_names): """ gets requested countries for visualization and info :param countries: list of all available countries for research :param country_names: list :return: (list, str) """ print(country_names) # gather the requested information c...
b96f3b001e5a421c333c366f3cdca656d97fe933
3,618,277
def retrieve_plain(monitor, object_string): """Retrieves the request object as-is (doesn't apply any modification). This is valid only for objects which are single values (items from a tensor) :param monitor: either a training or evaluation monitor :param object_string: string to identify the object to...
7fc5042422ae70933691202718036703554cff3e
3,618,278
from typing import Any def unique_id(context: Any) -> str: """ Returns a new unique string that can be used as an id="" attribute in HTML. Usage: {% with new_id=request|unique_id %} <label for="input:{{ new_id }}"> I am labelling a far-away input </label> ... <input id="i...
53bbf556749243591059e91e5342348abb7e8ce2
3,618,279
def get_contrast_in_df(df, img, img_name, contrast_type, grating_mask, white_mask, black_mask, metadata, x0, y0, angle, contrast_prefix=''): """helper function that handles inserting the contrast into the df """ if contrast_type == 'fourier': grating_1d = utils.extract_1d_grat...
7f1f0d5b509666c3fa352889ce099ca9f4d8d9e9
3,618,280
import time import logging import random def cash(ttl=60, key=None, ver=CURRENT_VERSION_ID, pre="", off=False): """ Copyright (C) 2009 twitter.com/rcb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"...
79add02d254e2fd069be9414a71f0cd47ff0953e
3,618,281
def enquiry_client_add(request): """ Add new enquiry and see the list of clients """ success_message, error_message = None, None form = ClientForm clients = Client.objects.all() enquiry_form = EnquiryClientForm enquiry_clients = EnquiryClient.objects.all() if request.method=="POS...
00b55395fcc705a0095000f7fe8b43301254ebdd
3,618,282
def transpose(table): """ Returns a copy of table with rows and columns swapped Example: 1 2 1 3 5 3 4 => 2 4 6 5 6 Parameter table: the table to transpose Precondition: table is a rectangular 2d List of numbers """ # LIST COMPREHENSIO...
2a393a9e3606022d945454da55fd68543e59476b
3,618,283
def memsizeformat(size): """Returns memory size in human readable (rounded) form. """ if size > 1048576: # 1024**2 return "{0} GB".format(size / 1048576) elif size > 1024: return "{0} MB".format(size / 1024) else: return "{0} KB".format(size)
0cd812d83bd85b1e2690e0404a4eb833e2e9824f
3,618,284
def q5(): """Identifying outliers.""" # Definindo os quartis: Q1 = countries['Net_migration'].quantile(q= 0.25) Q3 = countries['Net_migration'].quantile(q= 0.75) # Intervalo interquartil: IQR = Q3 - Q1 # Limite inferior: lim_max = (countries['Net_migration'] < (Q1 - 1.5 * IQR)).sum() ...
8f4d0f3323720af05020619e381c9533d923f4ad
3,618,285
import torch def matrix_div(model_out, *derivative_variable): """Computes the divergence for matrix/tensor-valued functions. Parameters ---------- model_out : torch.tensor The (batch) of matirces that should be differentiated. derivative_variable : torch.tensor The spatial variabl...
ed433674ee85895980b9212ac642ab1545d656ab
3,618,286
def flip_dataframe(df, new_colname='index'): """Flips table such that first row becomes columns Args: df (DataFrame): Data frame to be flipped. new_colname (str): Name of new column. Defaults to 'index'. Returns: DataFrame: flipped data frame. """ colnames = [new_...
3a7c733644e2c67398a511c9dea7fa80845bbecf
3,618,287
def ca65_bytearray(s): """Convert a byteslike into ca65 constant byte statements""" s = [' .byt ' + ','.join("%3d" % ch for ch in s[i:i + 16]) for i in range(0, len(s), 16)] return '\n'.join(s)
8bdc868cc659e6b99f01449c6bf41884c0635c14
3,618,288
import json import os def config(args): """Find the limit transformations to apply globally.""" reference = json.load(open(os.path.join(SELFDIR, 'reference.json'), 'r')) # Language specified on the command-line if args.lang: if args.lang not in reference: print("Error: language '%s...
615b30bdfea9b6f441d7b84e9131e71e6ede95e2
3,618,289
def read_basis_shell_num(trexio_file) -> int: """Read the basis_shell_num variable from the TREXIO file. Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function. Returns: ~num_r~: int Integer value of basis_shell_num variable read from ~trexio_file~. Rai...
831962f686ecaf22c199eaf6d0c87eb9d7269410
3,618,290
from typing import Optional from typing import Any def get_codec( cls: AnyType, /, *, using: Optional[Codec[Any]] = None, fallback: bool = False, ) -> Result[Codec[Any], TestplatesError]: """ Retrieves codec from structure type. If there are multiple codecs attached to given stru...
0a011b8b11038a45d42bf5a70559cea54a6ab6f1
3,618,291
import os def convert_to_pdf(input_path): """ Use external tools to convert the powerpoint file to a pdf. Returns: path of converted file """ path, extension = os.path.splitext(input_path) if extension not in ['.ppt', '.pptx']: raise ValueError("{0} not a valid powerpoint extension".format(exten...
aef761b559d32d6f75790cf41d07f80fb7933308
3,618,292
def convert_db_fetch_to_df(fetched, column_names=None): """ This method converts the cursor.fetchall() output of SELECT query into a Pandas dataframe. :param fetched: the output of SELECT query :type fetched: list of row tuples :param column_names: column names to use for the dataframe :type col...
f2ffdb2472076fd034e7d16b8cc42893358bf866
3,618,293
def get_synsets(s): """Suggested helper method for `synset_featurizer`. This should be completed so that it returns a list of stringified Synsets associated with elements of `s`. """ # Use `parse_lem` from the previous question to get a list of # (word, POS) pairs. Remember to convert the PO...
98ce2c1ce849d2771ab2bae03e0e740c8c3de32e
3,618,294
from typing import List from typing import Any from typing import Callable def tpe_submit_commands( cmds: List[Any], thread_count: int, timeout: int, fn: Callable = subprocess_commands_pipe, di=DI, ) -> list: """Run commands on multiple threads. Stdout and stderr are logged on function su...
ff8d18490b1184625ee6121ad5cf50dd7446b463
3,618,295
def register(): """Register new user.""" form = RegisterForm(request.form, csrf_enabled=False) if form.validate_on_submit(): User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True) flash('Thank you for registering. You can now log in.', 'succ...
8847e4153e0e9767298debe4f7c480c3b344327e
3,618,296
def ind2latlon(index, filePath): """ Use gdal/osr to get latlon point location from georeferenced array indices """ # Load georeferencing ds = gdal.Open(filePath) proj = ds.GetProjection() gt = ds.GetGeoTransform() srs = osr.SpatialReference() srs.ImportFromWkt(proj) x0 = gt[0] ...
55c8005c8106905370631c5a990b2835c0b5b322
3,618,297
def is_response_paginated(response_data): """Checks if the response data dict has expected paginated results keys Returns True if it finds all the paginated keys, False otherwise """ try: keys = list(response_data.keys()) except AttributeError: # If we can't get keys, wer'e certainl...
521c28c1d6e29e5785b3bcbd5d2604210b3a3874
3,618,298
from ..article.models import Tag, Category from ..travel.models import Province from datetime import datetime def get_context(*args, **kwargs) -> dict: """ context 导航栏信息 """ model_list: dict[object:tuple, ...] = { Tag: ('id', 'name'), Category: ('id', 'name'), } # # 初始化 context ...
12d9a6b1262a2a760474c21b410c95ba564b2ae4
3,618,299