content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def split_with_ratio(dataset: Dataset, valid_ratio: float = 0.1): """split dataset into train and validation dataset with specified ratio""" n_total = len(dataset) # type: ignore n_validate = int(valid_ratio * n_total) ds_train, ds_validate = random_split(dataset, [n_total - n_validate, n_validate]) ...
113a76ed579dfb0109c65647f002fccfa65a1768
61,538
def try_enum(cls, val): """A function that tries to turn the value into enum ``cls``. If it fails it returns the value instead. """ try: return cls._enum_value_map_[val] except (KeyError, TypeError, AttributeError): return val
14b61156d9129d51272b28227b440b7c5b5774c1
61,539
def get_existing_symptoms(journal): """Given a journal w/ proper format, aggregates all the symptoms args: journal (dict) returns: [str]: array of symptom names """ symptoms = [] for log in journal['journal']: symptoms.extend([ symptom['name'] for symptom i...
e8f90ff3344318b53ae91e79d29f572110103959
61,540
def addresses_from_address_families(address_families, spec): """Given a list of AddressFamilies and a Spec, return matching Addresses.""" if type(spec) in (DescendantAddresses, SiblingAddresses, AscendantAddresses): addresses = tuple(a for af in address_families for a in af.addressables.keys()) elif type(spec...
fcb2f39724ca0b3eb8bda7af6123bd876e61fbd1
61,541
import itertools def process_vlen(data_header, array): """Process vlen coming back from NCStream v2. This takes the array of values and slices into an object array, with entries containing the appropriate pieces of the original array. Sizes are controlled by the passed in `data_header`. Paramete...
9504d65ff669e7dea6c7a813619a6253b6a4a3eb
61,542
def analyze(): """ 聚类分析 :return: """ analyze_form = AnalyzeForm() if analyze_form.validate_on_submit(): k = analyze_form.k_cluster.data run_old_all_process(start_time=analyze_form.start_time.data, end_time=analyze_form.end_time.data, ...
82521404b6f9774858150ba887c4acd1e5a7920f
61,543
from typing import Union from pathlib import Path def is_subpath(path: Union[Path, str], base: Union[Path, str]) -> bool: """Return True if path is within base.""" return get_relative_path(path, base) is not None
35a10874d9af23d0d0d3bef64309652c1195f4a9
61,544
def cal_fps(raw_trajs_frequent_pattern: dict, sd_trajs_frequent_pattern: dict) -> float: """ calculate FPS Args: raw_trajs_frequent_pattern: frequent patterns of the original trajectory sd_trajs_frequent_pattern : frequent patterns that generate trajectories Returns: FPS ...
0b877ba77d928d0550f3fb695c0805f9447b4f61
61,545
def smart_page_crop_header_footer( # pylint: disable=too-many-branches, too-many-locals # noqa: C901 # too-complex pdf, elements_list, ): """ Remove header and footer elements smartly. Check element that inside given parameter of header and footer margin, by default is SMART_PAGE_CROP_REL_MARGIN...
7e187547f825b63e06f0d8e179e6ee75ece081ae
61,546
def k_means(X, k, max_iter=300): """ X.shape = (データ数, 次元数) k = クラスタ数 """ n_data, n_features = X.shape # 重心の初期値 centroids = init_centroid(X, k, n_data) # 新しいクラスタを格納するための配列 new_cluster = np.zeros(n_data) # 各データの所属クラスタを保存する配列 cluster = np.zeros(n_data) fo...
56414c07de1f6bfb17488bd8d02ec4527c47ec2e
61,547
import requests import pandas as pd import logging from requests.exceptions import SSLError import pandas as pd from pytz import timezone import pandas as pd import numpy as np import pandas as pd def download_ims_single_station(stationid, savepath=None, channel_name='TD', update=None)...
08c3e116bec0eadae2711c9dca9006ef991591da
61,548
import requests def select(host,user,pswd,cert=None,format=None,ID=None,template=None,title=None): """Get all data that fits a certain simple query Inputs: host - string, URL of MDCS instance user - string, username of desired account on MDCS server pswd - string, password of desi...
d684a87b97a626000673ada9bb49a972bbc80471
61,549
from datetime import datetime def cal2iso(cal): """Calendar date to ISO format. Parameters ---------- cal : string or array Calendar date. Format: YYYY-MM-DD HH:MM:SS.SSS. May be shortened, for example, to YYYY or YYYY-MM. DD == 0 is not allowed and is forced to 1. MM may be a t...
dd0f6fc8c054a33ca4ac1cfd21916f6538364e42
61,550
def sample_recipe(user, **params): """Create and return a sample recipe""" defaults = { 'title': 'Sample Recipe', 'time_minutes': 10, 'price': 5.00 } defaults.update(params) return Recipe.objects.create(user=user, **defaults)
f85925570225b7bdaab87f8f9d0f5f687a12d36c
61,551
def argmax_index(values): """ given an iterable of values return the index of the greatest value """ return argmax(izip(count(), values))
d5ba4642d0d8f2baaef16d8ee9bbd05230c56f3c
61,552
def list_rides(athlete, start_date=None, end_date=None, exclude_keywords=None): """ List all of the rides for individual athlete. :param athlete: The Athlete model object. :type athlete: bafs.orm.Athlete :param start_date: The date to start listing rides. :type start_date: datetime.date :...
24919dda775ad1c954cb2fd5df5cedf48853ffe0
61,554
import torch def calculate_true_values(states, goal, distance, gamma, final_value, nonterminal, distance_scale, reward_scale=10., ...
8f5e0dad55ec46f883ade9f5e615ef21b54128bc
61,555
import logging def kullback_leibler_divergence(x,y, delta = 0.001): """Calculates the jeffrey divergence between the vectors x and y Keyword arguments: x,y -- the vectors between which the distance is to be calculated delta -- a very small value meant to replace 0, to p...
0ea0852d58ca64a16d86cfcd1023b2e01aa145a0
61,556
from functools import reduce def rightchainop(As, Op=None, Bs=None, X=None): """ 2---A1---A2---...-AN--| | | | | |____|__ ... _|_ | | Op ... | X |________ ... __| | | | | | 1---B1---B2---...-BN--| (n...
20724a4c05cf6de660cb636e0e91fc072028db3b
61,557
def equals_decimal_and_corrupted(value, corrupted_value): """ Ex. value is Decimal('0.1'), tender.feature.enum values can be like '0.050000000000000002776', '0.10000000000000000555', '0.14999999999999999445' how do I check this ? :param value: :param corrupted_value: :return: """ ...
7374fb00caf6c2be158d505117518061d3e8cd33
61,558
def compara_assinatura(ass_main, matriz_ass_input): """ Essa funcao recebe duas assinaturas de texto e deve devolver o grau de similaridade nas assinaturas. """ lista_Sab = [] soma_mod = 0 if type(matriz_ass_input[0]) is list: for lin in range(len(matriz_ass_input)): for ...
b9dae58c37f06cbcbab577e54e3bbbcf793d7977
61,560
def pad_to_2_cells(s: str) -> str: """Right-pads s with spaces so that it occupies at least 2 cells. Raises ValueError if s does not occupy at least 1 cell. """ width: int = wcswidth(s) if width <= 0: raise ValueError('Argument must have a width >= 1') if wcswidth(s) >= 2: retu...
ee565f4bd186d7c9126f27841b1564c1508ade34
61,562
from typing import Sequence def deploy_dask(nodes: Sequence[Node]) -> DaskDeployment: """Deploys Dask on cluster nodes. Dask scheduler will be deployed on the first node. Dask workers will be deployed on each node. :param nodes: Nodes for Dask to be deployed on. """ if not nodes...
19ee10341fa4d7f0c01cce0e03074fb306f9807e
61,563
import re def Connect(host='localhost', port=443, user='root', pwd='', service="hostd", adapter="SOAP", namespace=None, path="/sdk", connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC, version=None, keyFile=None, certFile=None, thumbprint=None, sslContext=None, b64t...
93a71f0f227f105c40e73d5897055950f6d7a52e
61,564
import array def guess(s1): """ Guess initial postshock conditions using ideal gas behaviour """ k = s1.k; R = s1.R; M1 = s1.M p2 = s1.p*(2*k*M1**2-(k-1))/(k+1) T2 = s1.T*(2*k*M1**2-(k-1))*((k-1)*M1**2+2.)/((k+1)**2*M1**2) M2= ((M1**2*(k-1)+2)/(2*k*M1**2-(k-1)))**0.5 v2 = M2*(k*R*T2)**0.5 ...
2073bf04cf4a4a921fd9abc16aa3a83a2d997fc2
61,565
def qr_cam(): """Realiza a leitura do qr-code pela camera.""" capture = cv2.VideoCapture(0) while True: # To quit this program press q. if cv2.waitKey(1) & 0xFF == ord('q'): break # Breaks down the video into frames ret, frame = capture.read() # Display...
9d76ce255a0355f151846687fe1d7e09326ebe17
61,566
def efficientnet_b8(pretrained=False, **kwargs): """ EfficientNet-B8 """ # NOTE for train, drop_rate should be 0.5, drop_path_rate should be 0.2 model = _gen_efficientnet( 'efficientnet_b8', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs) return model
38f0e21c830e1ae98c192ed912bd931dde8f81a1
61,568
import re def prune_lines(infile): """ Discard all lines which don't have the data we're after Adapted from http://stackoverflow.com/questions/17131353/problems-targeting-carriage-return-and-newlines-with-regex-in-python """ result = [] with open(infile, 'r') as text: lines = text.read...
0d3bccf996b2afeab3e56cd29e5559235cb34d12
61,571
def delete_comment(request, pk): """ Handles deleting a comment, also checks the correct user doing the deleting """ comment = Comment.objects.get(pk=pk, feed_item__feed__user=request.user) feed_item_id = comment.feed_item_id comment.delete() messages.add_message(request, messages.WARNING, 'Your com...
59b6e39a0b4de73f9649bd4d33a63e4e975c8122
61,573
def generate_inputs(generate_calc_job_node, fixture_localhost, generate_structure, generate_kpoints_mesh): """Create the required inputs for the ``ProjwfcCalculation``.""" def _generate_inputs(output_parameters=None): entry_point_name = 'quantumespresso.pw' parent_inputs = { 'struc...
191bc148760a8ed217caffea1ae235db3de5a231
61,574
def get_times_for_patients( lambda_2, lambda_1, mu, num_of_servers, threshold, seed_num, measurement_type, runtime, ): """Determines the appropriate times to be used set by the user Parameters ---------- lambda_2 : [float] lambda_1 : [float] mu : [float] num_...
725ae599d2f5af2e0589171c477a7a73f9489db3
61,576
def _GetDefiningLayerAndPrim(stage, schemaName): """ Searches the stage LayerStack for a prim whose name is equal to schemaName. """ # SchemaBase is not actually defined in the core schema file, but this # behavior causes the code generator to produce correct C++ inheritance. if schemaName =...
c898b1f1fdd3430b044b556a269b0cdf84a552c1
61,578
def allowed_image_filesize(filesize): """Function to check if image file uploaded is within filesize.""" if int(filesize) <= app.config["MAX_IMAGE_FILESIZE"]: return True else: return False
52e24c8bd8159aa2135664a16c5aa96fac919155
61,579
def twoSum(nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ # Time Complexity - O(n) # Space Complexity - O(n) res = set() for i in nums: if i in res: return True res.add(k - i) return False
93e6d3f4d2d80f28a125b85b3eab5f4601d119d6
61,580
import csv def getCPTcodes(): """ get CPT codes, put in dictionary :return: the dictionary of codes """ with open('../codes/CPT.csv', 'rU') as csvfile: reader = csv.reader(csvfile) codeDict = {rows[0]:rows[1] for rows in reader} return codeDict
b08f1b270c6faf4218b6391e0a84bb752bfcf37d
61,581
import scipy def homogenized_cheby(n: int, kind: str = "t") -> np.ndarray: """Compute the coefficients for the homogenized version of T_n or U'_n. Args: n: degree of the polynomial. May be negative, in that case the degree will be abs(n) but the sign may differ (see notes for exact definit...
e9f890972830e7067a8cc6f02db53665669dc37d
61,582
def unique_by(func, objects): """ Sorts by applying func to each item :param func: Applied to each object to get the sortable result :param objects: iterable :return: The sorted objects """ seen = set() def hash(obj): value = func(obj) return value not in seen and no...
e3f72626543b0b0234530f936e02a100f00e6cba
61,583
def filtered_products(request, filter_group, filter_name): """ The view rendering a page for all products (Artwork) filtered by a user selected criteria """ # Call my helper function in utils.py to run the filter if there is filter if filter_group and filter_name: filtered_products = special_fi...
862bc0c3cbca417bccc05016db6dcaa5ddce64f3
61,584
def get_actual_start_time(task): """Returns the start time of the earliest time logs of the given task if it has any time logs, or it will return the task start_time. :param task: The stalker task instance that the time log will be investigated. :type task: :class:`stalker.models.task.Task` :...
963a6f3b88dcedd12e96396382d144e099111038
61,585
import torch def cls_mse_loss(input_logits, target_logits): """Takes softmax on both sides and returns MSE loss Note: - Returns the sum over all examples. Divide by the batch size afterwards if you want the mean. - Sends gradients to inputs but not the targets. """ assert input_logits.si...
42922316c11243bdf57b2eb3451642a4047bba5c
61,588
def sorted_by_popularity(tokens): """Sort tokens according to popularity (see NAME_CHAR_POPULARITY_MAP) so that tokens that are LESS popular in Japanese names come first, and return the sorted tokens. Args: tokens: tokens to sort. Returns: Sorted tokens. """ return sorted(to...
408e6a236e394bf864e5e867576bf0602abc6c1e
61,590
def property_info(info, delimiter=' | '): """Returns property info from tupple. Input tuple must containts flags if property is writable, readable and deletable. #!jinja {# return someone like this: WRITE | READ | DELETE #} {{ property_info(info) }} """ rv = [] if info[...
0b39c7ba69a05365f0051eab9941fd2ddce02642
61,591
def treeToList(node): """ Converts XML tree to list of entries. Useful to start recursive search. @ In, node, ET.Element, the xml tree root node to convert @ Out, treeToList, list(list(ET.Element)), of full paths to entries in xml tree """ flattened = findBranches(node,[node],[]) return list(tuple(...
ad9608e162f36c41d3b81729d14d61c741b8bdd5
61,592
def extract_title(path): """ Given document file path Extract the title >>> extract_title("/group/home/puls/Shared/capitalization-recovery/12/www.ameinfo.com.rssfeeds.10660/DE01D30EA383DFD9FA1427CB9CC935F2") u'Polaroid launches new range of products at opening day of GITEX Technology Week 2014' ...
d0fb37405e1779d16abaf217e5de52a7a8a2634d
61,593
def new_assignment(): """Provides an interface for adding new assignments.""" return flask.render_template('new_assignment.html', offices = office_utils.get_all_offices())
0e169b800daacad6ab15fc620038eb38d790b7ad
61,594
def list_schemes(): """Returns the tuple (schemes, encodings). `schemes` is an iterator for all supported password schemes (depends on the used Dovecot version and features of the libc). `encodings` is a tuple with all usable encoding suffixes. """ dcv = cfg_dget("misc.dovecot_version") sch...
3355f6bcdbeed2b8599b3246d7f663c118819b5e
61,596
import re def clean(s): """Strip leading & trailing space, remove newlines, compress space. Also expand '{NL}' to a literal newline. :param str s: :rtype: str """ s = s.strip() s = re.sub(' +', ' ', s) s = s.replace('\n', '') s = s.replace('\r', '') s = s.replace('{NL}', '\n') ...
f2c07984de1766b7a1d0258b29ad8030e87896e8
61,597
def dict_label(text, dictionary={}, regulation=[['U', [10]]]): """ 根据词库做实体标注 text = '企业提供部门经理的身份证和身份证明' dictionary = { '主体': ['企业'], '客体': ['部门经理'], '材料': ['身份证', '身份证明'] } regulation = [ ['主体', [1, 2, 3]], ['客体', [4, 5, 6]], ['材料', [7, 8, 9]], ['U', [1...
7ee2de94c5a71dae0b6c2c2ffcb908b98692da71
61,598
import time import math def timeSince(since): """ compute the training/evaluate time """ now = time.time() s = now - since m = math.floor(s / 60) s -= m * 60 h = math.floor(m / 60) m -= h * 60 return '%d h %d m %d s'%(h, m, s)
4fefbf6198bc89ca53eae341c116b0f6e693e8d1
61,599
def test_sparse_classification(): """Check classification for various parameter settings on sparse input.""" class CustomSVC(SVC): """SVC variant that records the nature of the training set""" def fit(self, X, y): super(CustomSVC, self).fit(X, y) self.data_type_ = type(...
95181b2405589c6f7d8aaf561eac513293f0041d
61,600
def unit_uri(ip_address: str) -> str: """Generates URI that is used by MongoDB to connect to a single replica. Args: ip_address: ip address of replica/unit """ return "mongodb://{}:{}/".format(ip_address, PORT)
9b2901c4f00036ed201e82979c0c42ae59c4749f
61,601
def get_ip_spec(addr, subnet=None): """Get the IP address with the subnet prefix length. Args: addr: network.addr object subnet: network.net object Returns: A string of the IP address with prefix length. Raises: Exception: if ip not in subnet """ if subnet is None: ...
d841ec672dcc35fe8352ec368d1841afe92dc885
61,602
import json def load_configuration(descriptor): """ Load configuration from the given descriptor. Could be either a `spleeter:` prefixed embedded configuration name or a file system path to read configuration from. :param descriptor: Configuration descriptor to use for lookup. :returns: Loaded de...
a68e355972510e8aa28be300cfbec6025886be20
61,603
def aim (p, q): """Return true if p is "aiming towards" q's half-plane edge.""" # First check if p.tail is in the half-plane of q inside = inhalfplane(p.tail(), q) # compute cross product of q x p to determine orientation # en.wikipedia.org/wiki/Cross_product#Computational_geometry # normalize ...
a1880f4e472a369abf9c8dace9d1f0b55967f4c3
61,605
def cancer_variants(institute_id, case_name): """Show cancer variants overview.""" form = CancerFiltersForm(request.args) data = controllers.cancer_variants(store, request.args, institute_id, case_name, form) return data
e28f80a4aed77a8e0638895caa9b0471b08eb0aa
61,607
def vecEnv(env_kwargs_local, env_class): """ Local Env Wrapper :param env_kwargs_local: arguments related to the environment wrapper :param env_class: class of the env :return: env for the pretrained algo """ train_env = env_class(**{**env_kwargs_local, "record_data": False, "renders": False...
19bfd52c14815605776dd8fc60d600838e29b4a6
61,609
def searchVisits(**kwargs): """ Search visits data file allVisit-l30e.2.fits, which should be stored in the folder set as environmental variable 'APOGEE_DATA' @Jessica Birky Input: 'id_name' : 2MASS name Output: 'ap_id', 'plates', 'mjds', 'fibers' : info needed to download visit spectra """ ...
1816fed39b3ffd37795247079ff8788d610657cd
61,610
def optimize_read_slicers(sliceobj, in_shape, itemsize, heuristic): """ Calculates slices to read from disk, and apply after reading Parameters ---------- sliceobj : object something that can be used to slice an array as in ``arr[sliceobj]``. Can be assumed to be canonical in the sense ...
4d0fdea55649393ad4d31bf9c332c3cf8d9a437b
61,612
import typing import math def make_pretty_range2(value_low: float, value_high: float, ticks: int = 5, logarithmic: bool = False) -> typing.Tuple[float, float, typing.Sequence[float], float, int, float]: """Returns minimum, maximum, list of tick values, division, and precision. Value high and value low specif...
18e617e696c34919f4ef1eeeb1520300f7d942f4
61,613
from typing import Dict from typing import Any def hardware_compile( schedule: Schedule, hardware_map: Dict[str, Any] ) -> Dict[str, Any]: """ Main function driving the compilation. The principle behind the overall compilation works as follows: For every instrument in the hardware mapping, we ins...
2347e74dc6e4821e455271b297030558f7a670c9
61,614
def two_step(A, B, a, b): """Combine linear step followed by a polynomial step into a single polynomial. Designed to process Sabatke polynomials which had a linear transformation ahead of the polynomial fits. Starting from a pair of polynomial arrays A and B such that u = A[i,j[ * xp**(i-j) * yp**...
2331b615dcce83283d320adb99c5fe0a0caee9a8
61,617
def get_test_specific_options(test, BLIND=False, ignore_others=True, ignore_labels=None): """ Function to use for determining test specific options, currently this is tuned to 4CR dataset; Need to be replaced for specific dataset. """ # Need to change when the total test options changed # Color key ...
0b56619a7eefadc58921a1d7145afeba9e7b9d74
61,618
import pandas def load_groundtruth( groundtruth_path, object_path): """Loads the ground truths for visual relationship detection. This function loads the visual relationship ground truths from csv files. Please refer to the dataset description of ``2.5D Visual Relationship Detection'' for more inform...
351c21dd349532ba21dc242086a3a1c6c9debb84
61,619
def create_schedule(section_schedule): """ Create a object of schedule class. By default, current project use the PrioritySchedule class to execute schedule. if user don't want to implement a schedule strategy by yourself, keep the follow default configuration items: [schedule.schedule_module_name]...
852657f61276fc49164716445b10be610c5c3922
61,620
def sense_landmarks(state, field_map, max_observations): """ Observes num_observations of landmarks for the current time step. The observations will be in the front plan of the robot. :param state: The current state of the robot (format: np.array([x, y, theta])). :param field_map: The FieldMap obje...
46bd76faf59e87d030081ebac0a2f939e0bf12d9
61,621
import math def radians(img): """Converts image from degrees to radians""" return img.toFloat().multiply(math.pi).divide(180)
3a2a11d84a9719937771517f13cc37f83f9bac6c
61,622
def generate_array(xml_file): """ Produce a *Ac.hpp, *Ac.cpp, and *.py files for serializable arrays. Return True if xml file was an array, otherwise return False and generate nothing. """ xml = XmlParser.XmlParser(xml_file) if xml() == "array": # # Parse array xml here ...
1d4c73d55d5006de0ddd15613ce52604f3ba3417
61,623
def people(): """ People in organization :return: list of users """ # users = get_users() return dict()
ac2c0b1403d9d00fe7fa6c8b631fefcf71c8266b
61,624
from .gip_router import GipRouter def classFactory(iface): # pylint: disable=invalid-name """Load GipRouter class from file GipRouter. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # return GipRouter(iface)
e46d334e795c99e942baf4e019227411eb3684b7
61,625
def locked_view_after_tomorrow(request): """View, locked starting from tomorrow.""" return HttpResponse('A locked view.')
a0a11f02a6d6cab325616d098cd3b3960c7a2b70
61,626
def SetupPMLForPolarContactsView(Name, Selection1, Selection2, Enable = True, Color = "yellow", Cutoff = None): """Setup PML commands for creating polar contacts view between a pair of selections. The polar contact view is generated using 'util.dist' command. The distance labels are shown by default. A...
88f0a0b7ccc7a09d9afa51af2652836373cd71b9
61,627
import gcsfs.mapping def write_n_chunk_copies_gcs(gcs_path, gcs_project, gcs_token, size, ncopies): """ Return a function to write a chunk by index to the given file to produce n copies of the array. """ def write_n_chunks(index_arr): gcs = gcsfs.GCSFileSystem(gcs_project, token=gcs_token) ...
dd01134e30c700b775204dd4694b4c341016ac76
61,628
def parse_by_category(category, data): """ filters database content by category from dumps :param category: accepts string :param data: accepts multi-dimensional iterable data type :return: returns filtered multi-dimensional LIST containing TUPLES """ new_dat = [] for entry in data: ...
255d69580ed666aac38eaa70442ee4e215a7e802
61,629
def unzip_axes(x: np.ndarray, start_axis: int = 0, end_axis: int = -1) -> np.ndarray: """Unzip (de-interleave) axes starting from `start_axis`. Changes the shape as follows: `[..., X, X, ..., Y, Y, ..., Z, Z, ...] -> [..., X, Y, Z, ..., X, Y, Z, ...]` Args: x: `np.ndarray` wi...
1274f3f5f65758b55a246e54261945a076dd988e
61,630
def user_to_dict(user): """Build a json flask response using the given data. :Returns: A flask response with json data. :Returns Type: :py:class:`flask.Response` """ data = {} if user.is_authenticated: roles = [{'id': r.id, 'description': r.description, 'name': r.name} f...
aed99bf8ff05dfca0b4bac4b2a674c4e71871c54
61,631
def display_home_page(request): """Display the home page of the application""" return render(request, 'index.html', {})
86dd7328b298effcf7285c766bf2296fb8720569
61,632
def iscsi_initiators_result_list(entity): """ Get the IQN and id associated with the Unity ISCSI initiators """ result = [] if entity: LOG.info('Successfully listed.') for item in entity: result.append( { "IQN": item.initiator_id, ...
40a1577ee19bc286059e771e2a8e70b2dc11871e
61,633
from pagure.hooks import BaseHook def get_enabled_plugins(project): """Returns a list of plugins enabled for a specific project. Args: project (model.Project): The project to look for. Returns: (list): A list of tuples (pluginclass, dbobj) with the plugin classess and dbobjects for plugi...
ca9517a1de2f59bcb770e6f40af431f654d38a38
61,634
def return_saved_jobs(): """Returns all the jobs that a user saved.""" user_id = session.get('user_id') if not user_id: flash("Please sign in first to save this job") return redirect("/login") else: user = User.query.options(db.joinedload('saved_jobs')).get(user_id) ...
067ca3d21b1d96dff1323a7e3868ea36a707f267
61,635
def r1_factor(self, other, scale_factor=None, assume_index_matching=False, use_binning=False): """Get the R1 factor according to this formula .. math:: R1 = \dfrac{\sum{||F| - k|F'||}}{\sum{|F|}} where F is self.data() and F' is other.data() and k is the factor to put F' on the ...
f8b1f80f69fe6d950d9a11cfdfec55f5d521205f
61,636
def scaled_normal_trace(field): """ u1 = scaled_normal_trace(field, ellipse) Return the scaled normal trace of the field u along the ellipse. Parameters ---------- field : Field Field class Returns ------- u_dir : Function t ↦ |γ´(t)| ∂ₙu(ε cos(t), sin(t)) """ ...
4dfd823204d59a97c00e2b0f7f1326ab834636f8
61,637
def convert_port(port: int): """ Converts a port number from Integer to HEX-value :param port: Integer which represents a port :return: HEX representation of port number (string), without preceeding '0x' """ port = hex(int(port)) port = port[2:].zfill(4) return port
1e3ac2f74f47355e601a3ca73a39c3b0b416af9d
61,638
def _feature_check_all_variants(metric_df, baseline_variant, assume_normal=True, percentiles=[2.5, 97.5], min_observations=20, nruns=10000, relative=False): """Applies delta to all variants, given a metric.""" baseline_metric = metric_df.iloc[:, 2][metric_df.variant == baseline_variant] def do_delta...
7c03b7a9ff7b4caf245e4f470dca38b82ad74012
61,639
import numpy def calculate_ccc_values(filename, logger, lo=2.0, hi=96.0, bins=1000): """ Determine min and and max values for a Cumulative Count Cut """ ds = gdal.Open(filename) band = ds.GetRasterBand(1) # min, max, mean, std stats = band.GetStatistics(False, True) hist = numpy.array(band.Get...
f5ffee8a16f58bd9d77390bd78689dfec2bd02f1
61,640
def bytes_to_long(bytestring): """Given a ``bytestring`` returns its integer representation ``N``. """ bytestring = '\x00' + bytestring N = int(bytestring.encode('hex'), 16) return N
d62703c6b23ce23c994160936ec3684cde97133e
61,641
import numpy def flatten_training(training_pairs): """Convert active label training pairs to two lists. Args: :training_pairs: (dict) dictionary of either 'match' or 'distinct', where 'match' is a list of pairs of records which are the same, and 'distinct' is a list of pairs o...
0813134356eed5478cf61b73cc054cda8fc460c5
61,642
def extract_sentences(paper_path, para_yes): """extracts sentences from a paper into two lists, given that para_yes contains a list of document element numbers corresponding to paragraphs manually identified as those containing synthesis information""" f = open(paper_path, 'rb') doc = Document.from...
00d866b1bf3a5005776f3b0a6468b7fe3f6bc4c8
61,643
import logging def setup_logging(log_config, instance_id, verbosity_adjust=0, fluentd=None): """ Set up logging such that: - The primary logging entry method is structlog (see http://structlog.readthedocs.io/en/stable/index.html) - By default, the logging backend is Python standard lib logger ...
5f5975a8a3729b1189d7b666a31235f16ec32795
61,644
from typing import Optional from typing import List from typing import Dict from typing import Any def untag_columns( database: str, table_name: Optional[str] = None, columns: Optional[List[str]] = None, key: Optional[str] = None, table_tag: Optional[str] = None, ) -> Dict[str, Any]: """ R...
60067a7dad270d12fa6f2c76f33c7c18b023bca5
61,645
def find_price_inverter(inverter_model): """ Returns the price of the inverter. """ if inverter_model in INVERTERS: return INVERTERS[inverter_model] else: raise 'The inverter does not in database'
6c667b29c4bff206e6fedf537f27647679f51448
61,646
def XdmfConditionResults(h5_results): """Return a list of XDMF Attribute objects for element results in an HDF5 file. Keyword arguments: h5_results -- the HDF5 group containing the results Checks for results stored by variable name in: - h5_results["ConditionDataValues/<variable>"] If no resu...
5765177d74cee3c8c5d80bb7895d7399ac209d6a
61,647
import time def join_abp(): """Joins the LoRaWAN network using Activation By Personalization (ABP)""" lora = LoRa(mode=LoRa.LORAWAN) log('Initializing LoRaWAN (ABP), DEV EUI: {} ...'.format( hexlify(lora.mac()).decode('ascii').upper())) authentication = (unpack(">l", unhexlify(LORA_ABP_DEVADD...
4eec40ced3002752b1f9fe24569007891a1a56d8
61,648
async def save_https(filename: str = "https_proxygrab.txt", method: str = "all"): """Save https proxies from get_proxies_func() function.""" proxies = await get_proxies_func("https", method) with open(filename, "w+") as f: f.write("\n".join(proxies)) return filename
6dce3e0e82493f49927f067c3a83646dc9a37e86
61,649
def variable_replacement(): """ Displays a website with "Hello <name>!", where <name> is passed in as a "name" HTTP GET parameter. With PyCharm, a link to the HTML file referenced will appear next to the method header. :return: HTML data generated from render_template() """ name = request.args.g...
090520a6743765be28ed0c336cf27c7ba43601fe
61,650
import ctypes def ENgetlinknodes(index): """Retrieves the indexes of the end nodes of a specified link. Arguments: index: link index""" j1= ctypes.c_int() j2= ctypes.c_int() ierr= _lib.ENgetlinknodes(index,ctypes.byref(j1),ctypes.byref(j2)) if ierr!=0: raise ENtoolkitError(ierr) retur...
7bec2e57960857398f22ec935de0df569768721a
61,651
import re def to_boolean(obj, true_values=('true', '1'), false_values=('false', '0')): """Convert `obj` to boolean. This is not like the builtin ``bool`` function. By default commonly considered strings values are converted to their boolean equivalent, i.e., ``'0'`` and ``'false'`` are converted to ``...
079732c32ca3993ca0821915782c74d5ca415d64
61,652
from typing import List def create_merge_table(context_id: str, command_id: str, table_names: List[str]) -> str: """ Parameters ---------- context_id : str The id of the experiment command_id : str The id of the command that the merge table table_names: List[str] Its a ...
107578e1a03d2ac699384ef303df0226636d86ae
61,653
from typing import List def nsga2_selection(population) -> List[Individual]: """Apply NSGA-II selection operator on the *population*. Usually, the size of *population* will be larger than *k* because any individual present in *population* will appear in the returned list at most once. Having the size ...
ef7aa70faf0c3cc8d158599785ca74bbe8aeb5aa
61,654
from typing import Dict from typing import Pattern import re def parse_probes(probe_file: str) -> PROBE_CONTAINER: """ Extracts all of the probe directives from the file pointed to by probe_file. """ # lines contains each line of the file which doesn't # start with a # and is not empty. li...
313fee8ca14358d19273bdf4eb38eafdba81b6e8
61,655
def add_families(yaml_metric_groups, yaml_metrics): """Add all metrics as label groups. Takes the known metric groups and the (possibly expanded by identify_incoming_metrics) known metrics, both from the YAML file. Returns a dictionary with these families. """ # Anatomy: metric group, metric, fa...
ca6e8227d03f21b10095db7be9f3088142af7950
61,658