content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fahrenheit_from(celsius): """Convert Celsius to Fahrenheit degrees.""" try: fahrenheit = float(celsius) * 9 / 5 + 32 fahrenheit = round(fahrenheit, 3) # Round to three decimal places return str(fahrenheit) except ValueError: return "invalid input"
e31ac8c62f108652fe3cc2ee1516a5b3a1a9e568
3,624,500
from typing import Dict def evaluate_task( task: TaskDocument, funct_scores: Dict[str, int] = SETTINGS.QCHEM_FUNCTIONAL_QUALITY_SCORES, basis_scores: Dict[str, int] = SETTINGS.QCHEM_BASIS_QUALITY_SCORES, solvent_scores: Dict[str, int] = SETTINGS.QCHEM_SOLVENT_MODEL_QUALITY_SCORES, task_quality_sco...
881aaa390ecc8b6f532080a3bbc890478c8a6844
3,624,501
import smtplib def send_email_reports(email_setting,summary): """ 根据传入的邮件策略发送邮件 :param email_setting: 邮件策略;string;"1"--代表始终发送 :param summary: 测试结果集;dict;{} :return: response: 统一的结果体;dict;{} """ if '@sina.com' in EMAIL_SEND_USERNAME: smtp_server = 'smtp.sina.com' elif '@163.com...
ca2d46ee29e3220b36047888227221798e39fc0a
3,624,502
def compute_q(a, N): """ Given: an vector a in R^m (except for 0 vector), compute the discrete approximation to the convolution q(u) = (p_0 * p_1 * ...)(u) = int p_0(t) p_1(u-t) ... dt where x_i ~ UNIF[-1,1], i.e. p_i = 1/2 if |x_i|<=1 or 0 o.w. Returns (N,) numpy.array, q = [q_0, ..., q_N-...
9ef04807d55c16542623055e58cadc82629e7a99
3,624,503
import math import traceback def align_face(image, coordinates): """ Face detection from dlib landmark detection :param: facial image local path or image of numpy array :return: faces coordinates list and landmarks """ try: d = dlib.rectangle(coordinates[2], coordinates[0], coordinates[3],...
e8c55e1cf88c9289cbf047634b1ff802fb2f12b3
3,624,504
def make_s3_client(credentials): """Make a client for uploading to S3. credentials: an orgtup.AwsCredentials object """ return client( 's3', aws_access_key_id=credentials.access_key_id, aws_secret_access_key=credentials.secret_access_key)
cc7eb7ace4acb4f4cd99b35e3fe3cf09f738ba5e
3,624,505
def rdkit(function): """ """ def wrapper(self, *args, **kwargs): """ """ if config['extras']['rdkit']: return function(self, *args, **kwargs) else: warn("The RDKit Python wrappers are not installed.", UserWarning) return wrapper
07846fbf3db95bed8897c79f1615983b704c811d
3,624,506
def review_filters_inline(request, review_id, template_name="manage/reviews/review_filters_inline.html"): """Renders the filter section of the review view. """ review_filters = request.session.get("review-filters", {}) review = lfs_get_object_or_404(Review, pk=review_id) return render_to_string(tem...
18491e8cc7c403542e77b621bd1691e27d2220d2
3,624,507
def get_text(title='Enter a label', default=None): """Prompt the user to enter text using QT :param title: Name of the prompt :param default: Default text to show in prompt Returns: The text the user typed, or None """ result, isok = QtWidgets.QInputDialog.getText( None, title, ...
807861a62ade7adc6361e264c422a072a278ed76
3,624,508
def is_edge(): """is_edge. """ try: IoTHubModuleClient.create_from_edge_environment() return True except Exception: return False
1cb09bceb7a12d7fe4361528b07954b9025be265
3,624,509
import imghdr import os def isImgPath(path, silent=False): """ 入力されたパスが画像か判定する [in] path: 画像か判定したいパス [in] silent: cv2.imread失敗時にエラーを表示させない場合はTrue [out] 画像ならTrue """ logger.debug('isImgPath({},{})'.format(path, silent)) if not type(path) is str: return False if not os....
fa30ca537654095f17a34465f2e81590688fd732
3,624,510
def get_target_supported_toolchains(target): """ Returns target supported toolchains list """ return TARGET_MAP[target].supported_toolchains if target in TARGET_MAP else None
cd37a32ec1342bb4825a121c608aec41c4151ec2
3,624,511
def big_endian_to_int(value): """ Ethereum RLP Utils: Convert big endian to int :param value: big ending value :return: int value """ return int.from_bytes(value, byteorder="big")
57c9b05471e3558cae1a0d36dd3089b4d180faeb
3,624,512
def supply(request, page_name): """ Handle the request for viz_chart widget.""" _ = page_name _ = request all_lounges = Team.objects.order_by('name').all() return { "all_lounges": all_lounges, }
4e9090c991069338d8db451d309dd0575d3ea91a
3,624,513
def human_time(runtime, decimals=2): """Display runtime in a human friendly format.""" if runtime < 1: return str('mms: ' + str('{:f}'.format(rounder(runtime * 1000, decimals)))) elif runtime < 60: return str('sec: ' + str('{:f}'.format(rounder(runtime, decimals)))) else: return ...
40364bf000f37e59a23fa3cb8163d9e2ae8f6fbb
3,624,514
def calc_c_s(p, polyol_data_file): """ Estimates the saturation concentration of CO2 in a polyol solution using interpolated measurements of solubility. Parameters ---------- p : float pressure at which to estimate the saturation concentration [Pa] polyol_data_file : string ...
0af3df6554c0c1a4098b54295cde2de9842c2420
3,624,515
def _read_files(file_names): """ Reads content from all specified file names Args: file_names: set of file names Returns: list of lines from all files """ all_lines = [] for file_name in file_names: try: with open(file_name) as f: lines = f...
98fabeeaeaf6dd142acaf7cf84c0ac25583bcdbf
3,624,516
def create_track_log(db, sessionID): """ Instantiate the Track History Collection. :param db: The database object. :param sessionID: Current user's session ID. :return: The Track History Collection object. """ collection_name = 'track_history_' + sessionID track_collection = db[collecti...
5fb72ae83e5a805ad8e35f62c9474e51170d3fb2
3,624,517
def parse_events(handle, blocksz): """ This function reads an events.txt file as it's written by the source engine, returns a list of DemoInfo instances containing demo name, killstreaks and bookmarks. handle : Open file handle to the events file. Must be readable. blocksz : Block size the handle file should be ...
3afd0aa4c28a839d09ac6a85e42d68d0938a60f6
3,624,518
def sum_allcation_from_shimenreservoir(): """ Real Name: Sum Allcation From ShiMenReservoir Original Eqn: Sum Allocation ShiMenReservoir To HouChiWeir+Sum Allocation ShiMenReservoir To ShiMenAgriChannel Units: m3 Limits: (None, None) Type: component Subs: None """ return ( ...
c21e48d87f35451bf2bc090d82272bec9389e24f
3,624,519
from typing import Optional from typing import Callable def scale_by_fromage( step_size: float = 1e-3, min_norm: float = 1e-6, step_size_factor_fn: Optional[Callable[[jnp.ndarray], jnp.ndarray]] = None, ) -> GradientTransformation: """Scale updates by Frobenius norm of parameters and grads. Refer...
af39416b6ccd23d7aced1c65b79fa8e0fbf9cf4e
3,624,520
def create_app(configobj=ProdConfig): """ Create and configure Flask Application """ app = Flask(__name__) app.config.from_object(configobj) configure_blueprints(app) configure_extensions(app) configure_callbacks(app) configure_filters(app) configure_error_handlers(app) return app
bcdfbc1e7a415204d8bc222f40b5d3a874cb0276
3,624,521
def istowest(bb1, bb2, north_vector=[0,1,0]): """ Returns True if bb1 is to the west of bb2. For obj1 to be to west of obj2: - obj1 is close to obj2 - The side faces for obj1 and obj2 overlap - obj1 is west obj2 """ #Currently a North Vector of 0,1,0 (North is in the positive Y...
73f5c4fdf333e2af395fc1b13dd5ccb82837c93d
3,624,522
import warnings def _generic_dimensions(array, unit, className="Dimension", **kwargs): """Return a dimension object based on the array coordinates.""" # labeled if str(array.dtype)[:2] in [">U", "<U"]: if unit != "": warnings.warn("Ignoring unit argument for LabeledDimension.") ...
4fc002cf38560cbfc138332c28034705b894153d
3,624,523
def InvertDepthNorm( depth, maxDepth=1000.0, minDepth=10, transform_type='inverse' ): """Renormalizes predictions back to targets space""" if transform_type == 'inverse': return maxDepth / depth elif transform_type == 'scaled': return depth * minDepth elif transform_type == 'log': ...
634ae5d7e3e92b84328c42683fe321d8c8ab7ced
3,624,524
from typing import Dict def rename_columns(df: pd.DataFrame, columns: Dict[str, str]) -> pd.DataFrame: """ Rename columns of given dataframe `df`. """ return df.rename(columns=columns)
1f321d4856ef75e77e24fb4a6bd60fdab7f2f6f6
3,624,525
def solid_material(color): """Create a material.""" material = rt.StandardMaterial() material.Ambient = color material.Diffuse = color material.Specular = rt.Color(255, 255, 255) material.Shininess = 50.0 material.ShinyStrength = 70.0 material.SpecularLevel = 70.0 return material
4e280b01ba21254fe95260335b33c67c3b2de266
3,624,526
import re def only_en(x): """ Only keeps English alphabets in a string or a pandas.DataFrame. Args: x: The content to be parsed. Either a string or a pandas.DataFrame. Returns: A new string or a pandas.DataFrame only includes English alphabets. | """ def func(_s): ...
8a32bfedf7e1d9bfa6a656bcc67fb718951d1f38
3,624,527
from datetime import datetime def test_reformat_params_reduction(monkeypatch): """reformat_params should remove "%" and convert to float""" yr = datetime.today().year def mock_expr_str_to_datetime(string): return datetime(yr, 12, 31) monkeypatch.setattr(vp, "expiration_str_to_datetime", mock...
571f66e5c826e08af05b4b7bf827f5df1e5fc4d2
3,624,528
def get_cached_connection_stats(return_as='string', memcached_ip='127.0.0.1', memcached_port='11211'): """Obtain connection status string in memcached and return as requested object. Check if memcached has cached connection status for the StorageShares, which would have been uploaded by UGR/Dynafed's perio...
baba55ff5bb3bd288e3dc8027263c1a60809c42d
3,624,529
import torch def gen_noise_Gaussian(num_instance, n_dim=2): """generate n-dim Gaussian random noise""" return torch.randn(num_instance, n_dim)
77237cf7a81408fae9099d4647e30c53e9866ab3
3,624,530
def detect_api_mismatch(ref_api, other_api, *, ignore=()): """Returns the set of items in ref_api not in other_api, except for a defined list of items to be ignored in this check. By default this skips private attributes beginning with '_' but includes all magic methods, i.e. those starting and ending ...
4353f3f6b825570e3193b57dbb08c3a26c7f59b9
3,624,531
def object_storage_name(instance, filename): """ Create a name spaced file path from the File obejct's checksum property. This path will be used to store the content copy :param instance: File (content File model) :param filename: str :return: str """ return generate_object_storage_name...
b836aedf6bc9034f5677796303abfb050d716c9c
3,624,532
def unbatch_padded(x, lens_x): """Make a list of individual batch elements with padded (masked) entries omitted""" x_split = x.chunk(x.shape[0], dim=0) x_clean = [x_split[i].reshape(-1, 2)[:lens_x[i]].detach().cpu().numpy() for i in range(len(lens_x))] return x_clean
8042076f8637ced12ba31e077198de6ed6841145
3,624,533
from typing import Any def strip_non_null_and_list_from_type(graphql_type: GraphQLOutputType) -> Any: """Return the GraphQL type stripped of its GraphQLNonNull and GraphQLList annotations.""" while isinstance(graphql_type, (GraphQLNonNull, GraphQLList)): graphql_type = graphql_type.of_type return ...
a074e5dfd2e6c4855f68e3c6b8b1a2cacadd997f
3,624,534
def _make_p_M_x(p_M_min=5., p_M_max=8.5, M_step=0.1, n_M=None): """ Makes the X values (i.e., the magnitudes) for a p_M distribution. """ if n_M is not None: p_M_x = np.linspace(p_M_min, p_M_max, num=n_M) else: if M_step is None: M_step = 0.1 # in case it's passed a...
be2fbc3fc3d647243775ffd9fb057a982df76cdc
3,624,535
def make_ip_thermostat( device: hm_device.HmDevice, device_address: str, group_base_channels: list[int] ) -> list[hm_entity.BaseEntity]: """Creates IPThermostat entities.""" return make_custom_entity( device=device, device_address=device_address, custom_entity_class=CeIpThermostat, ...
46fc3ac8d19dbde4cac56392f67bef22df887f65
3,624,536
from typing import Iterable def deepmap(func, obj): """Deep traverse obj, and apply func to each of its non-Iterable elements""" if isinstance(obj, Iterable): return [deepmap(func, x) for x in obj] else: return func(obj)
418d3342c86c422f5d4231030d66c03a08e89a9d
3,624,537
def shufflenet_g1_wd4(**kwargs): """ ShuffleNet 0.25x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,' https://arxiv.org/abs/1707.01083. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights f...
929d1b2dd9ff0d8623b6be5bc9b3c352186bdc6a
3,624,538
def glType(typ, *args): """return ctypes array of GLwhatever for Pyglet's OpenGL interface. (This seems to work for all types, but it does almost no type conversion. Just think in terms of "C without type casting".) typ -> ctype or GL name for ctype; see pyglet.gl.GLenum through GLvoid args -> Eithe...
138ec67bb500e40d6e35c06a397f33cb4fb96311
3,624,539
def FisherRao_dist(X1, X2): """ Compute the Fisher-Rao distance between two curves in R³ ... """ # #alignement des centres # X2 = X2 - fs.curve_functions.calculatecentroid(np.transpose(X2)) # #rotations # X2_new = fs.curve_functions.find_best_rotation(np.transpose(X1), np.transpose(X2))[...
0480fa3b33944152eaef829bf17d0b7dcda75863
3,624,540
from typing import Union from typing import Sequence def plot_line( line: Union[do.Line, Sequence[do.Line]], ax: Union[mpl.axes.Axes, None] = None, **kwargs, ) -> mpl.axes.Axes: """Plot a Line Dataobject Parameters ---------- line : Union[do.Line, Sequence[do.Line]] ax : Union[mpl.axe...
626379d9d1d85a4c6149fc03e71047720ec12470
3,624,541
def serialize(obj): """JSON serializer for objects not serializable by default json code""" try: return obj.__dict__ except AttributeError: return None
326421045ebb5990cc9079ef25fc2428cd036b52
3,624,542
def _get_monitor_value_from_hdf5(image, monitor_key): """Return the monitor value from an HDF5 image using an header key. The monotor_key is a path from the image path containing: - A dataset containing a scalar (a constant monitor) - A dataset containing a vector of values (it must containes enougth ...
765925e0b7c6493c8b4d86f806992c2a06c03e8d
3,624,543
def create_MultiRNNCell(hidden_sizes, keep_prob, num_proj=None, memory=None, memory_seq_lengths=None, reuse=False): """ Only the last layer has projection and attention Args: hidden_sizes: a list of hidden sizes for each layer num_proj: the ...
27cd87e0a76771e250d2f83a563e8ce920e77412
3,624,544
def expand_time(data: pd.DataFrame): """ 扩展时间纬度信息 """ tmp = pd.DataFrame(columns=data.columns) tmp['Time'] = pd.date_range( data['Time'].values[0], data['Time'].values[-1], freq='4H' ) tmp = tmp.merge(wipe_anomaly(data), how='outer').groupby('Time').max() return ...
057495e67fdc9d6264d8427c1f8639d849cce72b
3,624,545
def _EffectiveActiveConfigName(): """Gets the currently active configuration. It checks (in order): - Flag values - Environment variable values - The value set in the activator file Returns: str, The name of the active configuration or None if no location declares an active configuration. ...
d8166632caf6153d1ec6d943eab902d168100678
3,624,546
def svn_repos_get_fs_build_parser2(*args): """ svn_repos_get_fs_build_parser2(svn_repos_t * repos, svn_boolean_t use_history, enum svn_repos_load_uuid uuid_action, svn_stream_t * outstream, char const * parent_dir, apr_pool_t pool) -> svn_error_t """ return _repos.svn_repos_get_fs_build_parser2(*ar...
3db064fd42c2fc416bb7f740e3715b0bf1c9af9a
3,624,547
def plotting_context( context: str = "notebook", font_scale: float = 1.5, rc: dict = None ): """ 创建默认画图板样式 参数 --- :param context: seaborn 样式 :param font_scale: 设置字体大小 :param rc: 配置标签 """ if rc is None: rc = {} rc_default = {"lines.linewidth": 1.5} # 如果没有默认设置,增加...
c086aeb7e616d21a0a7789179ac06803c2d47666
3,624,548
def arc(c,rp=False,sn=False,e=False,n=False,samplereverse=False): """ Construct an arc by copying an eisting arc or specifying a center ``c`` and various optional parameters. """ if isarc(c): return deepcopy(c) elif ispoint(c): cen = point(c) w=-1 if samplereverse: ...
5537447777ca6f9b89cc5b0a8c3751827086539b
3,624,549
def factorial(num): """Finds the factorial of the input integer. :arg num: an integer """ #If the number provided is zero then the factorial is 1 if num == 0: fact = 1 #Otherwise set fact to 1 and begin finding the factorial r is #used to find each num-n for n=0 to n=num each v...
0dc8935c5d25acbc9d1d9dff1e86d5b6fcf80638
3,624,550
def MaybeEmulateMultiBleu(nltk_target_fn): """Includes emulate_multibleu argument into nltk_target_fn if necessary. The signature of the NLTK functions corpus_bleu and sentence_bleu depend on the NLTK version. This function works around version differences encountered in the public and internal environments. ...
476770fb9e025360ab9dbeaa71b8a0cc7bdaa96d
3,624,551
import time import json from datetime import datetime def incoming_cloudwatch_alarm(event, _): """ Standard AWS Lambda entry point for receiving CloudWatch alarm notifications. """ print(event) try: updated_timestamp = int(time.time()) ddb_table_name = ALARMS_TABLE_NAME ddb...
16a4a23e0679d22e9cf68e2c45f8973d1b5e0587
3,624,552
def sort_data_into_spectrum( ions: np.ndarray, bin_start: int, bin_end: int ) -> np.ndarray: # pragma: nocover """Sort ion data in 1D array into an overall array and sum them up. :param ions: Arrival time of the ions - number of time bin :param bin_start: First bin of spectrum :param bin_end: Last...
c6c179c00dacd166492f0df242260740ac15e0b2
3,624,553
def RX_partitioning_replicates_extended(data_arr,ind,perc,Issues=[],Skip=False,extension=0,Cap=None,ll=0): """ partition sequence trace using tape measure processes involved: find tape measure peaks (peak_finder) extract sequencing traces between tape measure peaks calculate bin width...
6d055692996249df9caf643c46871e63e7c4d255
3,624,554
def has_same_sign_or_zero(data): """Evaluate whether the array has all elements with the same sign or zero. Args: data (np.array): An array. Returns: bool: Boolean with the evaluation. Examples: >>> data = np.array([(1,2,3),(2,3,4)]) >>> has_same_sign_or_ze...
a772cecfe2885460d63387ae8b09f13d7016198c
3,624,555
import random import string def showLogin(): """Login page view.""" state = ''.join( random.choice(string.ascii_uppercase + string.digits) for x in xrange(32)) login_session['state'] = state return render_template('home/login.html', STATE=state)
ab959bb5bad16375055ac83612099d1da5bd775e
3,624,556
import json def dump_svlengths_report_data(bed_ifs): """Given input-file-stream of BED, return JSON string of svlengths_report_data. """ with BedReader(bed_ifs) as reader: return json.dumps(get_svlengths_report_data(reader))
06aef228ab0ceddcd8f6ce08437a4065c7b61db6
3,624,557
def tree_left_fa_fun(t, assignment=None): """Given some tree node `t`, do FA assuming the left branch is the function.""" result = tree_fa_fun_abstract(t[0], t[1], assignment) if result is None: raise TypeMismatch(t[0], t[1], "FA/left") return BinaryComposite(t[0], t[1], result, source=t)
f98bd12a7733372570b4b75a1d3aed355c8f3172
3,624,558
def list_statistic_ids( hass: HomeAssistant, statistic_type: str | None = None ) -> list[dict[str, str] | None]: """Return statistic_ids and meta data.""" units = hass.config.units statistic_ids = {} with session_scope(hass=hass) as session: metadata = _get_metadata(hass, session, None, stat...
b7bf0deefef827e3eebf12170a2fa32c124cf79b
3,624,559
import logging def GetFirmwareBinaryVersion(path): """Gets the version stored in RO_FRID section of the firmware binary. Args: path: Path to the firmware binary. Returns: The extracted firmware version as a string; or None if the function fails to extract version. """ result = None try: ...
0d66b33ec2812b9c6f5adc1db216cd7268dd7550
3,624,560
def parse_alpino_file(path: str) -> list[Proof]: """ Parses an Alpino file containing a single sentence and returns a list of proofs. """ with open(path, 'r') as f: etree = parse(path) name = etree.find('sentence').attrib['sentid'] trees = prepare_for_extraction(etree, name) retu...
3d9a7591305a6526e4eaf5505bc7282b5d26a559
3,624,561
def integrator(int_alg,timestep,pos,veloc,accel,molec,grad_method): """ Selects the type of integration algorithm to propagate the trajectories Only velocity Verlet implemented (date: 05/23/17 - LAC) Parameters: ---------- string int_alg -- Integrator Algorith to be used ...
d449f4f6e77baabe8841f77d30c6a50ddc214ac5
3,624,562
from typing import Dict def generate_detail_link_dict(instance: Dict) -> Dict: """ Generate a dictionary that consists of this instance's provider discriminators, so that we can convert it to a link to the instance detail page. :param instance: A dict representing an instance, that contains `provider...
ec57d3b9295372d49c8ade746930268c4d25154d
3,624,563
def get_cookie_expiry_datetime(cookie): """ example cookie: sessionid=XXXXXXXXXXXXXXXXXXXXX; expires=Wed, 16-Mar-2011 17:52:10 GMT; Max-Age=2592000; Path=/, ds_user=USERNAME; Max-Age=2592000; Path=/, ds_user_id=USERID; Max-Age=2592000; Path=/ """ try: start = cookie.lower().find('expires') +...
c51a603e998c5962e2fd39d472da58e4e7af1ca6
3,624,564
def colorize_groups(figure, group=None, saturations_map=None): """Colorize groups representations.""" nr_colors = figure.shape[0] assert nr_colors in [4], 'color map assumes four groups.' color_conv = 1 - GROUP_COLORS if group is not None: new_figure = np.dot(color_conv[[group]].T, figure....
81720cbff9c5a6d80d366572f20c043796d841fb
3,624,565
import itertools def combine_targets_and_zeros(target_strings, php_zero_strings, zero_strings, n_collisions): """Combines the zero strings with the target strings until the desired number of collisions is reached""" i = 0 ret = [] while True: for php_zero in php_zero_strings: for ...
4ba76f2b903ce3b7f6797aecd1027331631c282e
3,624,566
import requests from bs4 import BeautifulSoup def get_all_links(url: str) -> LinksType: """ Sends http request to url, downloads all data, extract links Args: url: url of website we want to search Returns: list of all links """ # create response object r = requests.ge...
9a6f0c2c2f60ee27aa5a06f2e841dd3b3758670b
3,624,567
from typing import Sequence def basic_sweep() -> Sequence[ensemble_plus.EnsembleConfig]: """Basic sweep over hyperparams.""" sweep = [] for num_ensemble in [1, 3, 10, 30, 100]: sweep.append(ensemble_plus.EnsembleConfig( num_ensemble=num_ensemble, )) return tuple(sweep)
23dcf9d34482a4e67d967f6a75e9b8f85529f891
3,624,568
def create_event(slope, plateau, tau, dt, alpha=1e-3, smothing_length=None): """ Create an artificial event. Parameters ---------- slope: float Slope of the rising. plateau: float Time of the middle plataue. tau: float Time constant of the capacitor behavior. dt:...
796edf91bde54b3cf1effc12e279d6612711d264
3,624,569
from typing import Optional import fastapi from typing import Union def query_object(*, select: Optional[str] = fastapi.Query( None, title='The list of fields to select.', description='Example: `[id, login, { users: {... } }]`. JSON or YAML.', ), join: Optio...
3c6696065f3fe668602192b4e933d0256149abe6
3,624,570
import numpy def get_storm_track_colours(): """Returns list of colours to use in plotting storm tracks. :return: rgb_matrix: 10-by-3 numpy array. rgb_matrix[i, 0] is the red component of the [i]th colour; rgb_matrix[i, 1] is the green component of the [i]th colour; rgb_matrix[i, 2] is the bl...
69acc4f2a666a86045f10aefe3ffa96bea8e99d0
3,624,571
def calc_delta_lampam_mp(ss, multipanel, constraints, inner_step=-1): """ returns the lamination parameters associated with a group of plies of a multi-panel structure OUTPUTS - delta_lampam: array storing the sublaminate partial lamination parameters INPUTS - ss: array storing the subla...
a3306529e5cbc74e8618a5c83aeef0b022159606
3,624,572
def load_model(model_class): """This function is for loading the saved model""" # Define the file directory for each model if model_class == 'mlp': filedir = './mtn/mlp' elif model_class == 'mlp_angle': filedir = './mtn/mlp_angle' elif model_class == 'lstm': filedir = './mtn/...
fcb3b227f68ffb4604aaea013de07d57bdee91d4
3,624,573
def rvabs_for_orders(ww_all,ff_all,orders,v,M,v2_width=25.,plot=True,ax=None,bx=None,verbose=True,n_points=40): """ Same as rvabs, except loop for different orders. Useful for error estimation EXAMPLE: v = np.linspace(-120,120,2000) rr1, rr2 = rvabs_for_orders(ww_all_targ,ff_all_targ,[4...
49bca456faf5834d96263220e73ca61f88ac8d1d
3,624,574
def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None): """Instantiates a placeholder tensor and returns it. # Arguments shape: Shape of the placeholder (integer tuple, may include `None` entries). ndim: Number of axes of the tensor. At least one of ...
9b9ba94b6d597599958cf36e95a030684bccc501
3,624,575
from datetime import datetime import json def save_json_db_data(): """Saves database tables containing data information, such as 'events_with_value' or 'prosensing_paf' events, to a json file. 'num_entries' for each table specifies how many data rows are in the file for the table, making iterative parsin...
3f7b85c0f3ad6e3219e6bd2ed7fb04dc92a041a6
3,624,576
import os def make_output_dir(outdir): """Make the output_dir if it doesn't exist. Parameters ---------- outdir : output directory to create """ if not os.path.exists(os.path.abspath(outdir)): # XXX Should this use os.makedirs which will make any # necessary parent direct...
4a0f7ba5b51e3ed96138a17c167e733bee1b383d
3,624,577
def replace_number_chunks(msg, tar='?'): """ Replace digits and adjacent alphabets with the given term @param msg: Input message @type msg: String @param tar: New term to replace @type tar: String @return: Replaced message @rtype: String """ def find_first_digit(msg): f...
16466501a41b6f97150264e89cc999b61291be9e
3,624,578
import torch def sortino(rp: torch.Tensor, rf: torch.Tensor) -> torch.Tensor: """Returns the sortino ratios for p portfolios Args: rp (torch.Tensor): p-by-n matrix where the (i, j) entry corresponds to the j-th return of the i-th portfolio rf (torch.Tensor): Scalar risk-free rate (a...
c4af6ad83617976977faef28524c815f810e1f10
3,624,579
from typing import Union from typing import Literal from typing import Optional from typing import Tuple def rl_decon( im: np.ndarray, background: Union[int, Literal["auto"]] = 80, n_iters: int = 10, shift: int = 0, save_deskewed: bool = False, output_shape: Optional[Tuple[int, int, int]] = No...
bc0e0a0472b7476a2839e616f66539224a60dfb6
3,624,580
import os def create_execution_directory(project, suite_name, timestamp): """Create report directory for a suite execution. Directory should have the following path: <testdir>/projects/<project>/reports/<suite_name>/<timestamp>/ """ directory = suite_execution_path(project, suite_name, timestamp)...
e829eb8d1071d8fd19f72b9c91d6de20fd9d0795
3,624,581
def all_gates(QuantumCircuit, nr_qubits, initial): """This function determines the matrix which corresponds to applying the whole circuit. Input ----- QuantumCircuit: np.array The quantum circuit in the form of a numpy array nr_qubits: int ...
dfe35f1945a8c3cee1dec640153353d0b2e923ae
3,624,582
from typing import Iterable import torch def fuse_single_qubit_operators( qubits: Iterable[int], operators: Iterable[torch.Tensor], ): """Multiply together gates acting on various single qubits. Suppose that we have a sequence of single-qubit gates that should act, one after the other, on...
640541a3b0a79deb819bafad5734aca3e0dde23d
3,624,583
def make_message(subject="", body="", from_email=None, to=None, bcc=None, attachments=None, headers=None, priority=None): """ Creates a simple message for the email parameters supplied. The 'to' and 'bcc' lists are filtered using DontSendEntry. If needed, the 'email' attribute can ...
301fad714f59767c21f433e2da37bf5b241cc739
3,624,584
def noneof(*items): """ noneof(*items) → Return the result of “not any(…)” on all non-`None` arguments """ return negate(any)(item for item in items if item is not None)
0a6dbb5d6328df7cd7f8870707a92a4d7a2d5059
3,624,585
def parse_visitor_score(d): """ Used to parse score of visiting team. """ string_value = d.get("uitslag", " 0- 0") (_, v) = string_value.replace(" ", "").split("-") return int(v)
df286924774823ca250b71fcb060278093a7611b
3,624,586
import os def get_written_file_path(line): """ Handles the acquisition of the path string for a written file. It is used to handle linux problems with windows style path strings. :param line: current line of the pandalog :return: path to the written file """ fixed_substring = u'filename,...
e6ff40bcfff2b7ae09a405e20c947bf0324c94a7
3,624,587
def ring2nest(nside, ipix): """Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`.""" ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return ring_to_nested(ipix, nside)
ba13a7c5d89cd20f5f0b389b5fe63a21464fcc16
3,624,588
from nibabel import load as nb_load import errno import os import glob def get_key_info_for_fmap_assignment(json_file, matching_parameter): """ Gets key information needed to assign fmaps to other modalities. (Note: It is the responsibility of the calling function to make sure the arguments are OK) ...
889dfe5dcb3d8926e95fb85ce238e084d3664888
3,624,589
def tag_index(idx): """Return a mapping of tag names to index items. """ tagidx = dict() for i in idx: for t in i.tags: if t not in tagidx: tagidx[t] = set() tagidx[t].add(i) return tagidx
df3ee2a934bfe3c814a9c1ded8d83314064f38bd
3,624,590
def node_text(node): """Needed for things like abstracts which have internal tags (see PMID:27822475)""" if node.text: result = node.text else: result = "" for child in node: if child.tail is not None: result += child.tail return result
076967e644cc99b7339f0cce9f8396a713e61999
3,624,591
def read_stc(filepath): """Read an STC file from the MNE package STC files contain activations or source reconstructions obtained from EEG and MEG data. Parameters ---------- filepath: string Path to STC file Returns ------- data: dict The STC structure. It has the...
8af56bb4ee9784a9af1511a3e126f85c05732ce4
3,624,592
def opd_drift_nogood(opd, drift, nterms=8, defocus_frac=0.8): """ Add some WFE drift (in nm) to an OPD image. Parameters ------------ opd : ndarray OPD images (can be an array of images). header : obj Header file drift : float WFE drift in nm Returns -------...
67d479e27e9332de505f02c3bfc65afe21cf0387
3,624,593
def created_health_check_parser(root, connection): """ Parses the API responses for the :py:meth:`route53.connection.Route53Connection.create_health_check` method. :param lxml.etree._Element root: The root node of the etree parsed response from the API. :param Route53Connection connection: ...
669e5151a90492105c854b33f0bf6e3d424bbf41
3,624,594
def map_nn(names): """ A function used to wrap choices as nn.Module for non-one-shot space definition Parameters ---------- name : list of anything the names of module, can be any type """ return [StrModule(x) for x in names]
cf1c41260e470faa742bfafc5eb4922bd9fbf3b5
3,624,595
from typing import Iterator from typing import Tuple def channels(N: int, radix: int) -> Iterator[Tuple[int, Iterator[int]]]: """Given a 1-d contiguous array of size N, and a FFT of given radix, this returns a map of iterators of the different memory channels.""" parity_r = partial(parity, radix) retu...
aef218ffa257f859a9d19ed2608992e2a0c15b1c
3,624,596
def positive_float(value): """An argparse type method for accepting only positive floats""" try: fvalue = float(value) except (ValueError, TypeError) as e: raise ArgumentTypeError( "Expected a positive float, error message: " "{}".format(e) ) if fvalue <= 0: r...
6abe34452efb17aa10c1239e9f40bf819f2fb3f0
3,624,597
def readfile(space, fname, use_include_path=False, w_ctx=None): """ readfile - Outputs a file """ fname, read_filters, write_filters = _parse_wrapper(fname) if fname == "" or fname is None: space.ec.warn("readfile(): Filename cannot be empty") return space.w_False if not _valid_fname(fn...
2378fcfa0cf05be2f3d57310e35d12e3bcc88865
3,624,598
from functools import reduce import operator def _match_tags_to_names(tag_names): """ INPUT: tag1,tag2,tag3 OUTPUT: <Tag: tag1>, ..., <Tag: tag3> NOTE: Tags NOT created BEFORE being added to new_machine_tags are ignored. """ matches = [Q(name__iexact=name.strip()) for name in tag_names.split('...
472ac9fdcd113bae2d1975c522e34fc1c374ea16
3,624,599