content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def calcTheta(wavelength, z1): """ Calculates the d spacing and the theta angle for a scattering vector z1 @param wavelength @param z1 A 3 component numpy array representing the scattering vector @param A tuple consisting of the d-value and the theta angle in radians ...
9ce846acd4e4b6f211d6b76558d18a54d16f0b75
47,950
def octahedron(): """Return the best integral embedding of the octahedral graph.""" v1 = (13 * root(1, 6, 1) - 2) / 3 v2 = -v1.conjugate() omega = root(1, 3, 1) v3 = v1 * omega v4 = v2 * omega v5 = v1 / omega v6 = v2 / omega vertices = (v1, v2, v3, v4, v5, v6) edges = ((0, 1), (0...
d402fd23e8844bdaad612b17f0930f89b2da248f
47,951
def symbols_for_inclusion(file: CheckFile, match) -> list: """ Return a list of symbols for a match. """ line_number, column = file.line_number_at(match.end()) line = file.line_at(line_number) include_suffix = line[column:] if not is_symbol_list(include_suffix): return [] listing = ...
75455942cc7b6abc46ff793522b1297a7157b63e
47,952
def sample_user(email="student@test.com", password="password123", name="some name"): """Create sample user for tests""" return get_user_model().objects.create_user(email=email, password=password, ...
4d558ca16eb660fe7579ce470e5a2b1c66a369e7
47,953
def reduce(l): """ Args: Rangelist: generic list of tuples (can be either float or int tuple) Return: Reduced int list based on average value of every tuple in input tuple list """ result = [] for s in l: midVal = abs(float(s[0]) - float(s[1])) / 2.0 result.append...
5db6214bc439dcc149d0d4cef1b66930f40694d7
47,954
def polygon_iou(pts1, pts2): """ Intersection over union between two shapely polygons. """ poly1 = Polygon(pts1).convex_hull poly2 = Polygon(pts2).convex_hull # union_poly = np.concatenate((pts1, pts2)) if not poly1.intersects(poly2): # this test is fast and can accelerate calculation ...
0e68901bc422d77f1ba3e14d1285db22f81fd2eb
47,955
import math def choose_team_levels(num_teams, hackathon_level): """ Calculates the average experience level per team and distributes any remaining difference among some of the teams evenly Returns a list of team_levels """ avg_team_level = math.floor(hackathon_level / num_teams) team_levels = [] ...
aaf372f00969da62b966a2a09aff64a188fbce82
47,956
def overall_random_accuracy_calc(item): """ Calculate overall random accuracy. :param item: RACC or RACCU :type item : dict :return: overall random accuracy as float """ try: return sum(item.values()) except Exception: return "None"
0e6cf8ae129235a41db084d2d9d5c92bb5788ed8
47,957
def infer_time_unit(time_seconds_arr): """ Determine the most appropriate time unit for an array of time durations specified in seconds. e.g. 5400 seconds => 'minutes', 36000 seconds => 'hours' """ if len(time_seconds_arr) == 0: return 'hours' max_time_seconds = max(time_seconds_arr...
11f25a712d8d66e8546fea2f7e36309dcebbcc74
47,958
def user_is_author_of_snippet(user, snippet_type, snippet_id): """ Checks if the current user is the author of the snippet provided """ snippet_models = { "project": Project, "skill": Skill, "profile": Profile } snippet = get_object_or_404(snippet_models[snippet_type]...
8408d18971005f3f00bc961f386193dffc28a9f5
47,959
def _batch_hard(query_features, positive_features, item_ids): """ Adapts the 'Batch Hard' triplet mining strategy of Hermans, Beyer, and Leibe. This method differs from Batch Hard in that we don't search for the hardest positive and just use the one positive example provided. Args: query_featur...
ac262b089a24dc48aa6c779c1c3b1772ce4a85ff
47,960
def add_paper_grading_sheet(supervisor, modified_df): """Adding the Paper Grading sheet with all supervised student Papers and grading metrics""" src_grading_wb = load_workbook('DataSources/Foik_GradingSheetSeminar.xlsx') print("The available sheets in the xlsx file") print(src_grading_wb.sheetnames) ...
7a9a64eea8718cf56992b7163aadfece17edfd43
47,961
def addContraints(d, Ca): """ Ajoute les conditions de Robinson qui ne sont pas encore satisfaites à Ca """ addedConstraints = False precision=0.0001 nb=0 # print 'Contraintes ajoutees' for i in range(d.n-2): for j in range(i+2, d.n): if (d[i,j] < d[i,j-1] - precision) and ([...
7967c85ba7207fc2e525451b36432aec973cb95f
47,963
def fprint(prompt: str, question: bool=False, returnstr: bool=False): """ Fancy print function """ tags = {'[o]': '[\033[01;32m+\033[0m]', '[ok]': '[\033[01;32m+\033[0m]', '[+]': '[\033[01;32m+\033[0m]', '[e]': '[\033[01;31m-\033[0m]', '[er]': '[\033[01;31...
27be27f40a112b5f14bbbf728deb319dccb77e7d
47,965
import itertools import random def random_tuple_list(lst1, lst2, lb=1): """ Generate a random list of tuples (x,y) where x is in lst1 and y is in lst2; """ product = list(itertools.product(lst1, lst2)) if len(product) == 0: k = 0 else: k = random.randint(lb, len(product)) ...
d21846b6d4cfee6479050f78046909329c5596b2
47,966
def tmp_img(tmpdir): """Get temp image fixture used by some test.""" img_path = tmpdir.join('image.jpg') im = Image.new('RGB', (160, 160)) im.save(img_path.strpath) return img_path
c6d9335e41b602ab50d54b370b4d671ae7bc433f
47,967
def combine_stage1_stage2(df_1, df_2): """Combines the stage 1 and stage 2 submissions. Replaces the positive class predictions in df_1 with those created in df_2. Args: df_1 (pd.DataFrame): Stage 1 submission df_2 (pd.DataFrame): Stage 2 submission Return: combined_df...
107c20689ae339a115573a28358d5c29f1b9b269
47,968
import time def swap_status_iterator(uuids_list: list, node_proxy: MMProxy) -> dict: """Builds swaps statuses dictionary""" swaps_d = dict.fromkeys(uuids_list, 'unknown') while True: work_d = {} # intermediate dictionary to iterate unfinished swaps values_list = [] for key in swap...
fccb72487afa117963da73457219630620ceddd6
47,969
from datetime import datetime def from_utc(utcTime, fmt="%Y-%m-%dT%H:%M:%SZ"): """ Convert UTC time string to time.struct_time """ return datetime.datetime.strptime(utcTime, fmt)
e4fb9792f8254c6d3a5d20d3da491dbe254c594a
47,970
def intersectGraphs(graph1={}, graph2={}): """Given two Graphs, create a new Graph that is their Relational Intersection ` Preconditions: Graph in Xaya Format Postconditions: returns a graph in XAYA format with intersecting keys and values Invariants: The input graphs do not change ...
639d2ad4a0e5da223aefad13d62f11ad9ec74d9d
47,971
def get_r2(reg, X, y): """Calculate the goodness of fit of regression model. Arguments: reg {model} -- regression model. X {ndarray} -- 2d array object with int or float. y {ndarray} -- 1d array object with int. Returns: float """ if isinstance(y, list): y =...
8e478325fd6790218bb89d5556bcf7190b9f72ae
47,972
def h_m_emg_rvs(mu, sigma, *t_args,N_samples=1): """Draw random samples from negative skewed hyper-EMG probabaility density Parameters ---------- mu : float Nominal position of simulated peak (mean of underlying Gaussian). sigma : float Nominal standard deviation (of the underlying ...
4b23267b7fe8ef4e1596e9ab6e4d8f4fbd32a208
47,973
def user_ajax_answer(request): """Submitting work to task (making Answer of it) is handled here. Accepts only POST requests. POST (ajax) params (all required): wi: work id ti: task id ni: network id a: action, (add or remove) """ if request.method !=...
52138ff6defbce7fa07e6cdad14a991db22c1360
47,974
def get_diff(a, b): """比较图片差异""" return get_match(a, b)[0]
9cdeb2d5da40c58d1c295203502cb694a51bc877
47,975
def get_image_metrics_for_samples( real_images, generator, prior, data_processor, num_eval_samples): """Compute inception score and FID.""" max_classifier_batch = 10 num_batches = num_eval_samples // max_classifier_batch def sample_fn(arg): del arg samples = generator(prior.sample(max_classifier_b...
aa23d8694d0426d90cb3b502c49e13ef4346a87b
47,976
from typing import Tuple def load_data( partition: int, num_clients: int ) -> Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]: """Load partition of randomly shuffled Fashion-MNIST subset.""" # Load training and test data (ignoring the test data for now) (x_train, y_train), (x_test,...
fa4d318d470b83ec0388f9da817f3f92aa435265
47,977
def flip_y(im): """mirrors an image over the x axis.""" source_pix = im.load() im = im.copy() dest_pix = im.load() width, height = im.size for i in range(width): for j in range(height): dest_pix[i,j] = source_pix[i, height-j-1] return im
9ad00b2de3e628cc6dd441884103b9d2e3492333
47,978
def augment_menpo_img_geom_dont_apply(img, p_geom=0): """geometric style image augmentation using random face deformations""" if p_geom > 0.5: lms_geom_warp = deform_face_geometric_style(img.landmarks['PTS'].points.copy(), p_scale=p_geom, p_shift=p_geom) return img
08b7ac4d6e05269ad037c044503110727f2525bd
47,979
import torch def lower_matrix_to_vector(lower: torch.Tensor) -> torch.Tensor: """Convert a lower triangular matrix to a vector. Parameters ---------- lower : torch.Tensor lower Returns ------- torch.Tensor """ shape = lower.shape assert shape[-1] == shape[-2] low...
e4fe825caf5926ce3219c4dd7720d1b7f180b998
47,980
def proxy_line(**kwargs): """ Generates a legend proxy for a line region. Returns ---------- :class:`matplotlib.lines.Line2D` """ return matplotlib.lines.Line2D(range(1), range(1), **kwargs)
62df36751f1de28a6267143844557d3e41adf8f5
47,982
def test_drawing(): """Test circuit drawing""" x = np.array(0.1, requires_grad=True) y = np.array([0.2, 0.3], requires_grad=True) z = np.array(0.4, requires_grad=True) dev = qml.device("default.qubit", wires=2) @qml.beta.qnode(dev, interface="autograd") def circuit(p1, p2=y, **kwargs): ...
1fcb0ab762582b971b70eccc7e09da9ae108377a
47,984
from typing import Union def encrypt_vault_password(key: bytes, password: Union[str, bytes]) -> bytes: """Encrypt and return the given vault password. :param key: The key to be used during the encryption :param password: The password to encrypt """ if isinstance(password, str): password ...
2f366ab3c560a5171e6697bc49fbfd971bc96b31
47,985
def t_to_col(t, tmin=6, tmax=11): """ Given a BPASS time bin, returns a value to input into the time colormap Parameter --------- t : float BPASS log time bin between 6 and 11 Returns ------- out : int Input to tcmap to get the right color out """ co...
cf589a15d1efafaeef037d478cfae21317c2aac5
47,986
def blockify(sudoku): """ Converts 9x9 sudoku list into a list containing lists of values in given sudoku's blocks args: -sudoku - 9x9 sudoku list returns: List with lists of values of sudoku blocks """ i=0 block_row = [] while i<len(sudoku): j=0 while j<7: ...
4f24aa3c3f8eb7132ab512bd74c03d8fd1947db0
47,988
def map_coords_to_scaled_float(coords, orig_size, new_size): """ maps coordinates relative to the original 3-D image to coordinates corresponding to the re-scaled 3-D image, given the coordinates and the shapes of the original and "new" scaled images. Returns a floating-point coordinate center where t...
f5e1e1523366a9e1e37f9d1a304d9deea8d53e00
47,989
def getPosition(junctionID): """getPosition(string) -> (double, double) Returns the coordinates of the center of the junction. """ return _getUniversal(tc.VAR_POSITION, junctionID)
ecb12bb97a7ab1be52723611edb83ceb7de78614
47,990
def _structure_summary(structure): """ Extract messages from the structure. Args: structure: a Pymatgen Structure object Returns: dict of the following messages: nsites (int): number of sites in the structure. is_ordered (bool): whether the structure is ordered or not. ...
65fe88a01d53df7ab487ae1d1ab24a4c2c746477
47,991
def id_type_dict(obj): """Creates dictionary with selected field from supplied object.""" if obj is None: return None return { 'id': str(obj.id), 'type': obj.type, }
7c7d67eee81a3d1553392617304bda4166bce817
47,993
from typing import Sequence from typing import Union from typing import Tuple from typing import List from typing import OrderedDict def _split_selections_property_and_vertex( selections: Sequence[Union[SelectionNode]], # OrderedDict is unsubscriptable (pylint E1136) ) -> Tuple["OrderedDict[str, SelectionNode...
260df2df41c92dfdd8402ca686e03309e96934d8
47,994
def is_3d(mesh: Mesh) -> bool: """Check if a meshio mesh is 3-dimensional""" for cell_block in mesh.cells: # first 3D element type is enough. if meshio_type_to_alpha[cell_block.type] in meshio_3d: return True return False
bd6b6bda26c6269121381ff6d9419f5b9129b76b
47,996
import torch def multiclass_nms(multi_bboxes, multi_scores, score_thr, nms_cfg, max_num=-1, score_factors=None): """NMS for multi-class bboxes. Args: multi_bboxes (Tensor): shape (n, #class*4) or (n, 4) ...
f3152e30eda4286ecfedc1b3fa3cf922470e0ada
47,997
def delete_case_study(case_study_id): """ Delete a case study :param case_study_id: :return: """ updater_json = validate_and_return_updater_request() casestudy = CaseStudy.query.filter( CaseStudy.id == case_study_id ).first_or_404() audit = AuditEvent( audit_type=A...
4ad9b900f294e99b54f4e88d556a6074e7a0fa94
47,998
import random def clustering_kmember(nec_set, k=25): """ group record accroding to QID distance. K-member :param nec_set: natural EC :param k: k :return: grouped clusters """ clusters = [cluster for cluster in nec_set if len(cluster) >= k] nec_set = [cluster for cluster in nec_set if l...
0a18618cf39b688d703694b9700fe1fd0b074de2
47,999
def get_variables_to_train(trainable_scopes, logger): """Returns a list of variables to train. Returns: A list of variables to train by the optimizer. """ if trainable_scopes is None or trainable_scopes == "": return tf.trainable_variables() else: scopes = [scope.strip() for scop...
ae101730521728859ba81ee888522a705f4749c2
48,000
def password_change_done(request): """ View called when the new user password has been accepted """ messages.success( request, _('Your password has been successfully changed.') ) return redirect('common:current_user_details')
3e81e12a270baacf82c3e566353563f78d0ebc4f
48,001
from typing import List def get_most_representative_notices(notice_ids: List[str], mongodb_client: MongoClient, top_k: int = None) -> List[str]: """ This function returns top_k the most representative notices, from the list of notices provided. :param notice_ids: :param mongodb_client: :param ...
e29015e7712f8d6296df70d5dbfbfda2e00569b4
48,002
def remove_ldra_interface( device, interface=None, vlan_id=None, policy=None, interface_id=None, **kwargs): """ Remove DHCP ldra remote-id Args: device ('obj'): device to use interface ('str'): interface to configure vlan_id ('str'): vlan_id to attach policy ...
33a3a2e412dc32552416f074412fae40c9e1f6a8
48,003
def borders(det): """ Calculates the borders for image Parameters -------------- det: int array Detected face Returns ---------------------- l: int list Coordinates for left bound of border r: int list Coordinates for right bound of border t: int...
d6358c88ee26e64b7b209d2f5f9725a5b3fad9ba
48,004
from rdkit.Dbase.DbConnection import DbConnect import pickle def DBToData(dbName, tableName, user='sysdba', password='masterkey', dupCol=-1, what='*', where='', join='', pickleCol=-1, pickleClass=None, ensembleIds=None): """ constructs an _MLData.MLDataSet_ from a database **Arguments** ...
39e2531c54501c837d52c4e2d4f148b8e5531f2e
48,005
def get_line_row(lines, row): """ - lines: (Array string), array of lines - row: int, >=0, the row index to grab RETURN: string, if row greater than or equal to lines length, returns '' """ if row < len(lines): return lines[row] return ''
f03f230b677fabb3c488c496dad7e35f875023fe
48,006
def VerifyLimitsPotential(potential): """Verify if the potential seems to verify the borders conditions (to allow bound states). If it doesn't it ask to the user if he is sure that the potential respects these conditions Parameters: ----------- potential (str) : a string that indicates the mathemat...
a1545b0360cb5de43c610442d5135a20c7da5893
48,007
def _get_head_node_ip(stack_name): """ Get the IP Address of the head node. :param stack_name: The name of the cloudformation stack :param config: Config object :return private/public ip address """ instances = describe_cluster_instances(stack_name, node_type=NodeType.head_node) if not ...
c699c21e84f0810b2c78fb0435dac07d8a963e79
48,008
from typing import Tuple def build_datasets(config: DataConfig) -> Tuple[DataLoader, DataLoader]: """ Build training and validation data loaders for training. Parameters ---------- config: DataConfig Data configuration such as batch size and validation set. Returns ------- tr...
5012ce15954e87dcd4a0a4323750d88242a0cf76
48,009
def fmt_begin_msg(app, fromuser, touser): """Format a PM begin message""" msg = "/me began pestering {touser} {toInit} at {time}".format(touser=touser.display_name, toInit=getInitials(app, touser, ...
43753f431835f6b235dd17dc1057d5c218f53a59
48,010
def filter_dict_null(d): """ Filters recursively null values from dictionary """ if isinstance(d, dict): return dict( (k, filter_dict_null(v)) for k, v in list(d.items()) if filter_dict_null(v) is not None ) elif isinstance(d, list): if len...
13b0288f2e032d0e6ca115d02d6540bb8f8739b5
48,011
import ast def merge(predicates): """ Invoked with a set of predicates that should be merged into a single AST. The new AST uses the PushResults node to return the list of matching predicates, and Both nodes to combine. """ # Merge the AST tree's together first using a tree all_asts = ...
e5425cb0d87e143a3d6d8ac75e5cad1d77a5916b
48,012
def optimize_threshold(model, X, y, TP=0, FP=0, TN=0, FN=0, minimize=True, pos_label=1): """ Find the optimal threshold Returns a tuple containing: A pandas dataframe used for plotting The optimal threshold The cost associated to that threshold """ y_pred = model.predict_prob...
8f586eb8ec7d72f5a33d6a23becc8e8c6c1ec6f2
48,013
def get_backend_defaults_url(config, backend_type): """Return the URL for a backend's pulse defaults.""" hub = config.get('hub', None) group = config.get('group', None) project = config.get('project', None) if hub and group and project: return '/Network/{}/Groups/{}/Projects/{}/devices/{}/d...
ac84179e03d132c64e55a87856f420968004f209
48,014
def ugly_numbers(n: int) -> int: """ Uses dynamic programming technique to return the nth ugly number. >>> ugly_numbers(100) 1536 >>> ugly_numbers(1) 1 >>> ugly_numbers(20) 36 """ ugly_nums = [0] * (n) ugly_nums[0] = 1 i2, i3, i5 = 0, 0, 0 next_2 = ugly_nums[i2] * 2 ...
6691ea90eebe1dc659fea244014f73b9638c3a5d
48,015
def get_publish_dates(df): """Get time distribution of publish dates for the given dataframe Returns ------- list[int] Time distribution in a format friendly towards HighCharts """ return pd.to_datetime(df["publish_date"]).astype(np.int64) / int(1e6)
d80813eefe2bdc10990f5bfd3138fd42c2bb28fe
48,016
def user_delete(request, pk=None): """User Delete View Description: view to delete users """ try: user = Client.objects.get(id=pk) except Exception as e: messages.error(request, e.args[0]) return HttpResponseRedirect('.') if request.method == 'GET': _user ...
de0b17445bc203490f57e910544c9109666c3717
48,017
from pathlib import Path import requests def make_posts( src, src_pattern, dst, layout, category_layout, comment_layout, comment_detail_layout, **params ): """Generate posts from posts directory.""" items = [] for posix_path in Path(src).glob(src_pattern): src_path = str(posix_path) ...
3cf368d5fe3e78ca02d00137b2894399e78310ec
48,018
def binary_search(array, item): """返回 item 在 array 中的下标,没找到返回 None。""" low = 0 high = len(array) - 1 while low <= high: mid = (low + high) // 2 guess = array[mid] if guess == item: return mid elif guess > item: high = mid - 1 else: ...
921c4594fd83aa891e0ee53d1d4680c8cc6a620c
48,019
def is_update(flags): """Is the opcode in flags UPDATE? *flags*, an ``int``, the DNS message flags. Returns a ``bool``. """ return from_flags(flags) == Opcode.UPDATE
e4f43a77f3128c43ea127a387fc172433d111fec
48,021
def get_1obj_gt_scenario(): """ Egovehicle stationary (represented by `o`). Seqeuence of 4-nanosecond timestamps. |-| | | |-| |-| | | |-| o (x,y,z) = (0,0,0) |-| | | |-| |-| | | (x,y,z)=(-3,2,0) |-| """ centers = [] # timestamp 0 cx = -3 cy = 2 cz = 0 centers += [(cx,cy,cz)] # timestamp 1 ...
5f528802f8b7f131fdba344e7bcf195e9414bd0b
48,022
from typing import Optional import binascii def _set_mem(args: [str]) -> Optional[rdcp_command.RDCPCommand]: """addr:int hexadecimal_string: str""" addr = _parse_int_expression(args[0]) value = binascii.unhexlify("".join(args[1:])) return rdcp_command.SetMem(addr, value, handler=print)
fcba48d5c0c272bd1db99719053f1479128a3760
48,024
from re import T def add_board(): """Lets the user add a board.""" logger.info("My session is: %r" % session) form = SQLFORM(db.bulletin_boards) if form.process().accepted: session.flash = T('Your board was created') redirect(URL('default', 'bulletin_board', args=[form.vars.id])) r...
0d9d6d01a2748c99cba0f9d4ffa485259df86b2f
48,025
def fuel(i: int) -> int: """ >>> [fuel(i) for i in [12,14,1969,100756]] [2, 2, 654, 33583] """ return i // 3 - 2
ea738361f4dc7081c5adeaf628c5424d9919e1bc
48,026
from datetime import datetime def about(request): """Renderea a about""" assert isinstance(request, HttpRequest) return render( request, 'app/about.html', { 'year':datetime.now().year, } )
f03cfb5e50a5150fdf8e0db85fec8f380b854669
48,027
import psutil def get_proc_name_from_pid(pid): """ using psutil to obtain proc name from pid :param pid: :return: proc name """ return psutil.Process(pid).name()
300ce9bcb945fce90a08b8dc2326e899180546fc
48,028
def _create_local(name, shape=None, collections=None): """Creates a new local variable. Args: name: The name of the new or existing variable. shape: Shape of the new or existing variable. collections: A list of collection names to which the Variable will be added. Returns: The created variable. ...
70dffd95cb01212016145120fc8e6e1ef7649f4c
48,029
def ReadStampFile(target_os): """Return the contents of the stamp file, or '' if it doesn't exist.""" try: with open(STAMP_FILE % target_os, 'r') as f: return f.read().rstrip() except IOError: return ''
6f6fcdafbdbdbb1d46b2464a7569e3cab7a4f789
48,030
def matmulBackward1(grad: Tensor, t1: 'Tensor', t2: 'Tensor') -> Tensor: """Gradient Function that is used when a tensor is matrix multiplied to a tensor that requires gradient. - Math: let A.shape == m x n let B.shape == n x p Y = A @ B F(Y) = L ...
c0c5b46e8821b6649d6402db8a528513e34accd3
48,032
from typing import List def make_rooks() -> List[Rook]: """Return list of rooks""" rooks: List[Rook] = [] for k in range(2): rooks.extend(( Rook(SQUARE_SIZE * k * 7, SQUARE_SIZE * 7, WHITE, f'{PIECE_PATH}white_rook.png',), Rook(SQUARE_SIZE * k * 7, SQUARE_S...
68f22b46c9275e34dc73e85c19b1327729521799
48,034
from typing import List from typing import Iterable def _domains_in_part(part: dc.DesignPart, exclude_fixed: bool) -> List[Domain]: """ :param part: DesignPart (e.g., :any:`Strand`, :any:`Domani`, Tuple[:any:`Strand`, :any:`Strand`]) :param exclude_fixed: whether to exclude :any:`Domain`'s...
1219b666ee93db2fcc06d6fd48f604d03980df14
48,035
def read_temporal_profiles(tracer, kind, filename): """\ Read temporal profiles for given `tracer` for 'weekly' or 'annual' profiles. """ data = {} countries = [] snaps = [] filename = filename.format(tracer=tracer) with open(filename, "r") as profile_file: for line in prof...
36718952419eebb0024321f777cafcaa23dddf56
48,036
import tests def test_list(): """ Retrieve a list of tests as json objects. See the README for details on the formatting. """ test_json_objs = [] for test_id, test_name in enumerate(tests): exec("name = "+test_name+".name", globals()) exec("desc = "+test_name+".desc", globals...
89ee001a481490a48120b898b682dbd99ef4ad7d
48,037
def load_embeddings(file_name: str, embeddings_format: str): """Load word embeddings from the given file, either in plain-text format ('text') or in gensim format ('gensim')""" if embeddings_format == 'text': return _load_w2v_model_file(filename=file_name) else: return _load_w2v_model_gensim...
a9131785ed2ffcbff6efd10c6ae736e318717842
48,040
def favicon(): """网站图标""" # send_static_file是flask里面的寻找static静态文件的方法。通过查看源码得知 return current_app.send_static_file('news/favicon.ico')
ba7c36e003118605d1a786305f931cf1f436a9c3
48,041
def compute_tpm( counts_df: pd.DataFrame, gene_id2length: pd.DataFrame ) -> pd.DataFrame: """Compute TPM values Args: counts_df: Dataframe containing counts gene_id2length: Dictionary of gene ID to gene length Returns: pd.DataFrame: containing the TPM values """ scaling...
d8fc3bcfcc622b6ffb8f36dc382d23d930d2621e
48,043
import scipy.stats as stats import scipy.stats as stats import numpy def lnprior(pzero_regions, paramSetup): """ Function that computes the ln prior probabilities of the model parameters. """ priorln = 0.0 mu = 1 # import pdb; pdb.set_trace() # ensure all parameters are finite if ...
22e7b57b8a261a74de22580a8a850f6f3dfbcb26
48,045
def render_template_to_file(template_path, file_path=None, **values): """ Render a 'jinja' template resource to a temporary file. :param template_path: relative path to the template. :param file_path: absolute path to the desired output file. :param values: keyword arguments passed to jinja. "...
7af7e2fa2e46bf333ae35985628f81e74cd41f0d
48,046
def fit_generic_continuum(spectrum, median_window=3, model=Chebyshev1D(3), fitter=LevMarLSQFitter(), exclude_regions=None, weights=None): """ Basic fitting of the continuum of an input spectrum. The input spectrum is smoothed using a median filter to remov...
b5e279a401a1ff94e6fa7cb0473747dd5cbf0809
48,049
def sdss_path(): """Path for absorption/emission lines """ return join(_parent_path, 'SDSS')
894eb310d6d9ad756b365a03ed411bd2569e8a1d
48,050
def read_log_file( log_file, log_entries_to_get=[ "x_pixel_um", "y_pixel_um", "z_pixel_um", "image_paths", "registration_config", ], separator=": ", ): """ Reads an amap log file, and returns a dict of entries corresponding to "log_entries_to_get" ...
f339d5cffe1ade818eda1c9ed45a4bb115ce159b
48,052
import gzip import re def miles_graph(): """ Return the cites example graph in miles_dat.txt from the Stanford GraphBase. """ # open file miles_dat.txt.gz (or miles_dat.txt) fh = gzip.open('knuth_miles.txt.gz', 'r') G = nx.Graph() G.position = {} G.population = {} cities = []...
994005c593573e097f7fb4729b8a4f3d288b002e
48,054
def SetErrorHandler(*args): """SetErrorHandler(char const * pszCallbackName=None) -> CPLErr""" return _gdal.SetErrorHandler(*args)
f76abdc5b689f0ed1f2ea913749b6a6fe116b32f
48,055
def get_shift_bits(n, bit_string, shift): """Given a bit-string, return an expression to map to the bit-string. Each index of the given bit-string corresponds to the index of an n-bit bit vector. This function returns those bits, using the variable for the bit if the corresponding index in the bit-string is '1...
6b0b396b3248eeb4cd971256edd70b8052f462e6
48,057
def get_bag_count(list_of_bags: list, colour: str) -> int: """ Recursive function to loop through list. Gather rules on line. While there are still rules to be processed, get colour and recursively call function again. Append to total. :return: Total amount of bags inside colour. :rtype: in...
593bb1d826cd996ca4725fe7e2c18043c8853021
48,058
def get_wikidata_complexes(): """Gets all Wikidata items with a Complex Portal ID property""" get_macromolecular = """ SELECT ?item ?ComplexPortalID WHERE { ?item wdt:P7718 ?ComplexPortalID . }""" wikidata_complexes = WDItemEngine.execute_sparql_query( get_macromolecular, as_da...
a71a3fe63ebd67dec7ce0cb38adaf60daa8a9ad0
48,059
import socket def _pick_port(): """ Returns an unused TCP port. While we can not guarantee it will stay unused, it is very unlikely that it will become used within a few seconds. """ with socket(AF_INET, SOCK_STREAM) as sock: sock.bind(("", 0)) return sock.getsockname()[1]
2f9c0e2aa5619db6212e4dc2c78cf0ff12516447
48,060
def connection_str(): """ SQLAlchemy connection string to test database """ return "postgresql://nebulo_user:password@localhost:4442/nebulo_db"
b5220a9ce7e44acde4154686af00164d2f065a83
48,061
def mfi(high, low, close, volume, length=None, drift=None, offset=None, **kwargs): """Indicator: Money Flow Index (MFI)""" # Validate arguments length = int(length) if length and length > 0 else 14 high = verify_series(high, length) low = verify_series(low, length) close = verify_series(close, l...
ee73c35c4f704360155a1365cdd8eae78d5d0388
48,063
def load(filename): """ """ with open(filename, "rb") as file_: data = read(file_) return data
efc01f2411e910d169d642ed76117cdcff30d6e7
48,064
import numpy def caf_L05burst2(CFR, lMmax, t0, burstamp, ltbegin, ltend): """ Generate age distribution (CAF) following L05 & add a starburst """ # Assume CIMF is a -2 power-law powerlaw # Follow the evolve MF notation in Gieles 2009, MNRAS # Fixed model parameters: lMlim = 2 # minimum m...
72b0ad5461d728ed371da7d147af85a193cdfd1f
48,065
def Y_tester(): """ >>> tmp = Y_tester() >>> tmp(1) 1 >>> tmp(5) 120 >>> tmp(2) 2 """ "*** YOUR CODE HERE ***" return Y(lambda f: lambda x: 1 if x == 1 else x * f(x - 1))
d374a1226da538b7b105de0a8b2ab1e0e2ab5fbc
48,066
def segment_arm(frame: np.ndarray, abs_depth_dev: int = 14) -> np.ndarray: """Segments arm region This method accepts a single-channel depth image of an arm and hand region and extracts the segmented arm region. It is assumed that the hand is placed in the center of the image. :para...
2647e66570c12237aa242cf22cf27872d395ef2c
48,067
def tiploc_record(records): """return CIF file TIPLOC object from 80-character line string""" this_array = [[line[0:2],line[2:9],line[9:11],line[11:17],line[17:18],line[18:44],line[44:49],line[49:53],line[53:56],line[56:72],line[72:79]] for line in records] this_frame = pd.DataFrame(data=this_array, columns...
a2b2737b924ad94ec831fd5206bcf259f3602ee0
48,069
def sort(args) -> list: """Performs a sort based on the given args. Args is of the format (dist, auc, n0, n1) and is one tuple/list. Throws an error if the array did not sort correctly. Returns the results.""" dist, auc, n0, n1 = args results = list() data, D0, D1 = continuousScale(n0, n1) comp = Comparator(dat...
a61156e1de8fd37473c5cfc1a596b8d9511d061c
48,070
def org_new(input_params={}, always_retry=True, **kwargs): """ Invokes the /org/new API method. For more info, see: https://documentation.dnanexus.com/developer/api/organizations#api-method-org-new """ input_params_cp = Nonce.update_nonce(input_params) return DXHTTPRequest('/org/new', input_par...
200489839e21485c8fb862a66e2a3cb0d42865a0
48,073