content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def left2right_decode( symbols_to_logits_fn, start_symbols, context_BxU_dict, batch_size, max_decode_len, vocab_size, top_p, temperature, beam_size = 1, beam_start = 5, beam_alpha = 0.6, beam_min = 0, beam_max = -1, eos_id = 1, ): """left to right decode. N...
e19b89c284235936c6acef43863f0f1f9ae3ad2c
52,292
from typing import Optional from typing import Union import struct def encode_key( key: str, value: Optional[Union[int, float, str]] = None, value_type: str = "str" ) -> bytes: """Encode given header key to a bytes string. Parameters ---------- key : str header key value : Optional[Un...
b38e04fdbd761bd121f0e08a9eee9dfb692f616c
52,293
import json def loads(*args, **kwargs): """ calls json.loads """ return json.loads(*args, **kwargs)
2696e9a9482898d4dfe8fc9cf9f4bb47ec1da050
52,294
def hashIter(bytesiter, hasher, ashexstr=True): """Will hash the blockIter generator and return digest""" for block in bytesiter: hasher.update(block) return hasher.hexdigest() if ashexstr else hasher.digest()
216435e32901661f3f7c90953dd86e5a00a5b703
52,295
from operator import add from operator import sub from operator import mul from operator import mod def parse(code, delimiter=' '): """Return the result of the RPN calculation of the `code` string or list. Supported operatorations are * +, -, *, mult, /, div, //, idiv, pow, %, mod * sin, cos,...
d55073d730f48cab74b94e9de99c8a7a20b298d7
52,296
def get_session(autocommit=True, expire_on_commit=False, use_slave=False): """Helper method to grab session.""" facade = _create_facade_lazily() return facade.get_session(autocommit=autocommit, expire_on_commit=expire_on_commit, use_slave=use_slave...
45093328345652f54afddeca9834941e9c90903b
52,297
def test_141_parseWind_nonstd(): """Check parsing of nonstandard wind groups.""" def report(wind_group): """(Macro) Return Metar object from parsing the given wind group.""" return Metar.Metar(sta_time + wind_group) assert report("OOOOOKT").wind_speed.value() == 0 assert report("OOOOOK...
5260be6a67771e92a599c8f434132e17dc053809
52,298
def query_aisc_shapes(shape=None, metric=False, version=None): """ Queries the AISC steel shape database and returns a list of the shape names in the specified shape category. Parameters ---------- shape : str The shape for which names will be returned. If None, all shape names ...
765b814d1a77c95eddee9496aee3a2f147662f61
52,299
def upload_avatar(): """保存图片""" # 提取参数 req_data = request.files.get("image") # 校验参数 if not req_data: return jsonify(errno=RET.PARAMERR, errmsg="请选择图片文件") # 保存图片 file_data = req_data.read() try: filename = upload_image(file_data) except Exception as e: current...
170e9ad7755cc5d3e83d35b8406835aff2077b43
52,300
def get_roster_alltime(team_id, start_year=START_YEAR, end_year=END_YEAR): """Return the roster file of team with matching id.""" try: return urlopen(ROSTER_ALLTIME_URL.format(team_id, start_year, end_year)) except HTTPError: raise ValueError('Could not find a roster for a team with that id....
af8bf9f6b8cc994092a76ba07f9dfa8b359283ca
52,301
def induced_subgraph(G, nbunch): """Returns a independent deep copy subgraph induced on nbunch. The induced subgraph of a graph on a set of nodes N is the graph with nodes N and edges from G which have both ends in N. Parameters ---------- G : NetworkX Graph nbunch : node, container of nod...
af991494e424f75a7232295a160f0663e03bfd03
52,302
def get_calib_images(calib_img_paths, calib_img_names, resimgs=False): """Reads and returns images used for calibration.""" calibImages = [] calibImgNames = [] for calib_img_path, calib_img_name in zip(calib_img_paths, calib_img_names): calibImage = cv2.imread(calib_img_path) if calibIma...
69025e2fef61316eaea7711fb723e0b0796e72ff
52,303
import io def make_image(imagePath, detections): """ returns "image": a numpy array representing an image, compatible with scikit-image """ image = io.imread(imagePath) logger.info("*** "+str(len(detections))+" Results, color coded by confidence ***") imcaption = [] for detection in de...
c81deeeac9d25d81c85bd9a6845046d9d528c567
52,304
import re def html_chemname_format(name): """ Format a chemical formula to display subscripts and superscripts in HTML (e.g., Plotly plots) Example, "CH3COO-" becomes "CH<sub>3</sub>COO<sup>-</sup>" Parameters ---------- name : str A chemical formula. Returns ...
d6fc5d11c13abe27961ffe118ea077a963883225
52,305
def from_shape_and_word(shape, word): """ Returns the ribbon corresponding to the given ribbon shape and word. EXAMPLES:: sage: import sage.combinat.ribbon as ribbon sage: ribbon.from_shape_and_word([2,3],[1,2,3,4,5]) [[1, 2], [3, 4, 5]] """ pos = 0 r = [] for l...
a472bc5a2f653d29a9e846dbc9083a5270c17471
52,306
import warnings def dcm_to_hvdict( unique_id, slice_paths, patient_name='', mri_type = '', segmentation_info=None, seg_label_info=None, visualization_parameters_override=None ): """ Given a list of dcm file names, creates a dehydrated version of an hv object as a dict. Slices w...
96641fcb79cb2ab3576e45b75e06d075e7acc46c
52,307
def normalize(X, Y=None): """ Normalise X and Y according to the mean and standard deviation of the X values only. """ # # It would be possible to normalize with last rather than mean, such as: # lasts = np.expand_dims(X[:, -1, :], axis=1) # assert (lasts[:, :] == X[:, -1, :]).all(), "{}, {}, {}...
23c134a800c7df6c3e22872f2f24cb1fdc4cb7ab
52,308
def import_maplight_from_json_view(request): """ Take data from Test XML file and store in the local Voting Info Project database """ # If person isn't signed in, we don't want to let them visit this page yet if not request.user.is_authenticated(): return redirect('/admin') import_mapli...
8834d24456be065edfb8123b40283424778056f3
52,309
from . import routes def create_app(): """ Function Construct the core application for the flask """ app = Flask(__name__) CORS(app) app.config.from_object('config.Config') """ Initializing the sqlalchemy db with the app """ db.init_app(app) """ Creating the app cont...
efc3fddbf1313937171cfa67263b2a269a3eb727
52,310
def move_polygons(polygons, from_grid, to_grid=None): """ A function that moves polygons to the origin bounding box (0, 250, 250, 250) """ if(to_grid): x_displacement = (from_grid // 10) - (to_grid // 10) y_displacement = (from_grid % 10) - (to_grid % 10) else: x_displacemen...
3b7667bed2fdcf70331adf107bb4759f8d4d90ab
52,311
def create_tf_strings_model(): """ A model that concatenates two input strings """ g = tf.Graph() with g.as_default(): with tf.name_scope("some_namespace"): x = tf.placeholder(tf.string, name="in_x") y = tf.placeholder(tf.string, name="in_y") # Assigned t...
8f084f7b7cf15523ac5c3feb26d5e1d14b5b7790
52,313
import json def get_numeric_project_id(gcloud, project_id): """Get the numeric project ID.""" project_info = json.loads( gcloud.run('projects', 'describe', project_id, '--format=json')) return project_info['projectNumber']
f9e3086ed1436d4ce075960c191ff4f64a76582b
52,314
def vstran(d1: np.ndarray, d2: np.ndarray) -> tuple: """calculate variance stabilized weights Calculation of variance stabilized weights which describes in paper in section "Variance stabilized weights" Parameters ---------- d1 : np.ndarray 1d ndarray of diagonal elements d2 : np.n...
b08d56f7a776f7a01fc905f6d81993c34f745eeb
52,315
def count_local_minmax(A): """ Count local max and min @author Akafael """ n = len(A) # Trivial Solution if n <= 1: return 1 # Calculate the diff B = [] count = 0 isRising = False isFalling = False for i in range(1, n - 1): B.append(A[i + 1] - A[i]...
03fc5439aad1bf93e8d08d8056beece2c2fe2aee
52,316
from functools import reduce from operator import add def fitness(individual,target): """ individual : the individual to evaluate (a list) target : the target sum the individuals are aiming for """ sum = reduce(add,individual,0) return abs(target-sum)
bcfb4d857be926df249149e224babbc98d358780
52,317
def dynamic_gru(input, size, param_attr=None, bias_attr=None, is_reverse=False, gate_activation='sigmoid', candidate_activation='tanh', h_0=None, origin_mode=False): """ :api_attr: Static...
d44744fc6c427d901273fa05937e4b38b5f65b3b
52,318
def create_schema(name: str) -> str: """Function for generating create schema statements :param str name: The name of the schema :return: Create statement :rtype: str """ statement = f"CREATE SCHEMA {name}" return statement
a82d392ec411e2c412ef3f1959ff7ab229130532
52,319
def test_existing_path_FileLinks_repr_alt_formatter(): """FileLinks: Calling repr() functions as expected w/ alt formatter """ td = mkdtemp() tf1 = NamedTemporaryFile(dir=td) tf2 = NamedTemporaryFile(dir=td) def fake_formatter(dirname,fnames,included_suffixes): return ["hello","world"] ...
976c299cfaf05b1e7af4c55710dc793571b191e4
52,320
def model_cv_mse(Model, X, y, alphas, k = 5): """ This function calculates the MSE resulting from k-fold CV using lasso regression performed on a training subset of X and y for different values of alpha. Inputs: Model (sklearn model): the type of sklearn model with which to fit the data - Ridg...
4e7b815a9f5895a112ddcf8fe58a392007bbc2cd
52,321
def latent_samples_FGPVAE(train_images, train_aux_data, vae, GP, N_t, clipping_qs=False): """ Get latent samples for training data. For t-SNE plots :) :param train_images: :param train_aux_data: :param vae: :param GP: :param clipping_qs: :return: """ train_aux_data = tf.reshape...
4f95691ad97c6ed2898ac1388f9db296534fd3a7
52,322
def rotate_matrix_cw(matrix, angle = 90): """Rotate the matrix clockwise by certain angle (multiples of 90 deg).""" def rotate_matrix_90(matrix): rows, columns = matrix.shape matrix_new = np.zeros((columns, rows)) for i in range(rows): for j in range(columns): ...
82c90fec062c36dea4d6d9a55640ba483c6b07ad
52,323
import copy def SplitRM(instruction): """Split instruction into two versions (using register or memory). Args: instruction: instruction. Returns: List of one or two instructions. If original instruction contains operand that can be either register or memory (such as 'E'), two specific versions ...
5e294f0ce2fa206ad88e7e734280541c272b7d98
52,324
def reduce_mem_usage(df, verbose=False): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ df = pd.DataFrame(df) UINT8 = np.iinfo(np.uint8) UINT16 = np.iinfo(np.uint16) UINT32 = np.iinfo(np.uint32) UINT64 = np.iinfo(np.uint64) ...
22d8633010caf2f5afdd7609f195357a200f42b5
52,325
import io import json def deserialize_ndarray_npy(d): """ Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's :obj:`save` function. Args: d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created using :obj:`numpy.save`. Return...
9c7fa7563b04c715ff0b4c057e1f7e0e880fc7d1
52,326
def compute_hessian(image): """ Compute Hessian components of 2D image using finite difference. Parameters ---------- image: array_like Input image. Returns ------- hxx, hxy, hyy: ndarray, ndim=2 Gradients in x, y directions respectively. """ image = np.asarray(ima...
693feb8ec954e22c3d025b9bf1aa6742439db7b8
52,328
def projectToImage(pts_3D, P): """ PROJECTTOIMAGE projects 3D points in given coordinate system in the image plane using the given projection matrix P. Usage: pts_2D = projectToImage(pts_3D, P) input: pts_3D: 3xn matrix P: 3x4 projection matrix output: pts_2D: 2xn matrix las...
4120834e3e6f50de2d176935fa7b34b7983a19d6
52,330
def docs(): """ Displays the API documentation at '/' """ return render_template('index.html', last_updated=dir_last_updated('app/static'))
f7f0aff36c3ff287cc16220a0f4be79dc2a0530c
52,331
def courant(dx, dt, v_max, **kwargs): """ Calculate the Courant's number describing stability of the numerical scheme. Parameters ---------- dx : float Size of the spatial grid cell [m]. dt : float Time step [s]. v_max : float Max. velocity of the model. Returns ------- C : flo...
58b09b545c4679b845c3e2702af8bffe4262c599
52,332
def weighted_count(instances_obj, m_weights): """Weight nt count by nt weights at each position""" weighted_counts = {} for letter in instances_obj.alphabet: weighted_counts[letter] = [0] * instances_obj.length for idx, instance in enumerate(instances_obj): for position, letter in enumer...
458a6c013fd72c1e418a27c3a6f5511c86be834d
52,333
import tqdm def plot_interaction_network( kg_data: pd.DataFrame ) -> nx.DiGraph: """Plot a knowledge graph based on the interaction data.""" interaction_graph = nx.DiGraph() # Append the source to target mapping to the main data edgelist for idx in tqdm(kg_data.index, desc='Plotting interacti...
c45986f34773b6fcbef789b00c0a41377b6b0c39
52,334
def space_linear_tree(actions, sent=None, SHIFT=0, REDUCE=1): """ Use `( ` instead of `(`. Similarly for ` )`. """ stack = [] pointer = 0 if sent is None: sent = list(map(str, range((len(actions)+1) // 2))) for action in actions: if action == SHIFT: word = sent[poin...
36a7c1d2ba669259f5a2810d1746766470966da4
52,335
def n_thermal_qbits(pops: list) -> DensityMatrix: """ Args: pops: a list of population numbers between 0 and .5 Returns: A density matrix for n thermal qbits with the specified populations """ num_states = 2 ** len(pops) data = [] for i in range(num_states): state = ...
ac2c53514aaafbedf8d908011dd3579c5828047f
52,336
def entropysea(salt=None,temp=None,pres=None,dliq=None,chkvals=False, chktol=_CHKTOL,salt0=None,temp0=None,pres0=None,dliq0=None, chkbnd=False,useext=False,mathargs=None): """Calculate sea-ice seawater entropy. Calculate the specific entropy of seawater in sea-ice. :arg salt: Salinity in k...
e32102631b047df15e083555ac684bc79e6d4d29
52,337
def rm(args): """ Remove files from tracking and delete the file. Args: args (obj): Arguments from command line. """ args.delete = True return remove(args)
b772df32d546deb3680a8c472ad8419b632aa88e
52,339
def compute_cost_rmsle(Y, Y_hat): """ Computes the RMSLE cost. Arguments: Y : true labels vector placeholder, same shape as Y_hat Y_hat : output of forward propagation of shape (1, number of examples) Returns: cost : Tensor of the cost function. """ return tf.sq...
673305a816af99bd3619dc41ba1fe0a93791af0e
52,340
import math def standard_deviation(series): """ implements the sample standard deviation of a series from scratch you may need a for loop and your average function also the function math.sqrt you should get the same result as calling .std() on your data https://pandas.pydata.org/pandas-docs/st...
01a488f4bc8168a92d4a0590daa88bad08032fed
52,341
def ldns_rdf2buffer_str_time(*args): """LDNS buffer.""" return _ldns.ldns_rdf2buffer_str_time(*args)
c994fddcb98570a8f2106af8c1504412e0bad509
52,342
def read_file(netcdf_file_name): """Reads SHIPS data from NetCDF file. :param netcdf_file_name: Path to input file. :return: ships_table_xarray: xarray table. Documentation in the xarray table should make values self-explanatory. """ return xarray.open_dataset(netcdf_file_name)
da193379703d3e15c02de4b5d2117ede7ba5fff4
52,343
def get_settings(values): """ Retrieve settings from command line, and set them up """ settings = Settings() settings.input.XC.GGA = values['functional'] if values['dispersion'] is not None: settings.input.XC.DISPERSION = values['dispersion'] settings.input.BASIS.type = values['b...
4e7a4b12c8a9ea14a6e96c1ca9ab80021b72d1f9
52,344
def o2satv2b(salinity: np.ndarray, temp: np.ndarray) -> np.ndarray: """ Calculate oxygen concentration at saturation :param salinity: :param temp: :return: """ # Define constants, etc. for saturation calculation # The constants used are for units of umol O2/kg a0 = 5.80818 a1 = ...
914169c1b87bd420c6f7b458f7d8ee0990c7dbb6
52,345
def _get_crm_resource_v2(credentials): """ Instantiates a Google Compute Resource Manager v2 resource object to call the Resource Manager API. We need a v2 resource object to query for GCP folders. :param credentials: The GoogleCredentials object :return: A CRM v2 resource object """ return ...
e72c64c5a5dac52a576837066a62b9d96bc6fee9
52,347
def _obtain_rapt(http_request, access_token, requested_scopes, rounds_num=5): """Given an http request method and reauth access token, get rapt token. Args: http_request: callable to run http requests. Accepts uri, method, body and headers. Returns a tuple: (response, content) acces...
36bec3b8e25139860d861da5b1c7d4f7f0312687
52,349
import io def format_attribute( el, visibility=False, is_derived=False, type=False, multiplicity=False, default=False, tags=False, ): """ Create a OCL representation of the attribute, Returns the attribute as a string. If one or more of the parameters (visibility, is_derive...
a879269e3739a66264c26c536ec7fe3909091cc4
52,350
def function(op): """ Convert a function into a delayed evaluator. The value of the function is computed from the values of the parameters at the time that the function value is requested rather than when the function is created. """ # Note: @functools.wraps(op) does not work with numpy ufu...
9169d12064fc4012eade59de86efc2596e157662
52,351
def convolve(x, W, input_multi_channel=False, output_multi_channel=False, mode='full'): """Convolution that supports multi-dimensional and multi-channel inputs. Args: x (array): input array with shape batch_shape + input_shape if input_multi_channel=False. Otherwise with shape ...
66dcc629c0c863d5498c47b31708d8b01f26a979
52,352
def unify_projection(dic): """Unifies names of projections. Some projections are referred using different names like 'Universal Transverse Mercator' and 'Universe Transverse Mercator'. This function replaces synonyms by a unified name. Example of common typo in UTM replaced by correct spelling:: ...
a3cdf4bb2a26ee0391281e8f8b0d3e7ea5c8a962
52,353
def diagonal_zigzag_square(x): """ Fill square matrix in diagonal order. x = [0, ..., 8] y = diagonal_zigzag_square(x) y = [[0 2 5] [1 4 7] [3 6 8]] :param x: vector of length n**2. :return: y """ x = np.array(x) # length of the square side n = np.sqrt(le...
fdbe1dc487f501d028585955555596912e28c551
52,354
def make_access_var(name, agent, target_variable=False, target_value=False, radius=1000, agg_function='sum', decay='flat', log=True, filters=False): """ Generator function for accessibility variables. Registers with orca. """ @orca.column('nodes', name, cache=Tru...
3c34f1d6c4996431098cf3cbc7392fdbbaa44bf7
52,355
import torch def make_path(index): """ Given a size of a node to add get the binary path to reach it. """ order = "{0:b}".format(index + 1) order = torch.tensor(list(map(int, order))) print(order) out = [1] for i in range(1, len(order)): out.append(order[i] + 2 * out[-1]) r...
4d41c969407cc1a0634ae33a8e588c0766394efc
52,356
def getName(full_name): """ the getName function splits the name of the application returning the executable name and ignoring the path details. :param full_name: the path and executable name :return: the executable name """ # Determine if '\\' and ':' are within the full_name if ':' in ...
797825903c3794533b134fc3c03afc79304d62b6
52,357
def _cor_coeff(X, y): """ pearson correlation coefficient """ corr, _ = pearsonr(X, y) return corr
b7e65d203b264acd0602a979525efd6a0656f3ba
52,360
def __battery_charge_decoder__(port: serial.Serial, *args, **kwargs): """Returns the raw battery value as a byte.""" return port.read(1)[0]
5b2763ec1ad61185e997610823d99a1295c39116
52,361
def transform_viewpoint(v): """Transforms the viewpoint vector into a consistentrepresentation""" return np.concatenate([v[:, :3], np.cos(v[:, 3:4]), np.sin(v[:, 3:4]), np.cos(v[:, 4:5]), np.sin(v[:, 4:5...
cb4dcc8f106190a32825d3f766de604db02634ac
52,362
from ._alpino import tokenize, parse_raw, interpret_parse def alpino(doc, output="raw"): """Wrapper around the Alpino (dependency) parser for Dutch. Expects an environment variable ALPINO_HOME to point at the Alpino installation dir. The script uses the 'dependencies' end_hook to generate lemmata an...
4f21c29136e85f63bd7454f12f4d23c9a91a2a15
52,363
import math import random import scipy def inverseKinematics(target, rootJoint, numJoints): """ Solve the inverse Kinematics problem using the BFGS optimisation algorithm as described in: Inverse Kinematics The state of the art (http://image.diku.dk/projects/media/morten.engell_noerregaard.07.pdf) target - The t...
1382ffbdf5d15d698e2c16dcebe46ac4027d7cd6
52,364
def contar_consonantes(cadena): """ Cuenta las vocales en una cadena >>> contar_consonantes('hola') 2 >>> contar_consonantes('Duque') 2 >>> contar_consonantes('qwqwqwq') 7 :param cadena: :return: """ return len(cadena) - contar_vocales(cadena)
af6d7db663451bcb64391a727050f38409005a2b
52,365
def SpecificSub(subject): #Aditi edit """ Function to separate correct and wrong answers on a subject basis from sub_correct and sub_wrong sub_resp is a dictionary with correct and wrong answers for each subject """ sub_resp = {} str1 = subject + '_correct' str2 = subject + '_wrong' cor...
d19bf9992cbe99462240a798d7e2e3239260208b
52,367
import colorsys def get_color(rgb): """Get the name of a color for a RGB value. Resolve the human readable names for a RBG value. This method is a great speed increase over the `get_most_likely_colors` method, however it assumes that the hue is the exact color name and is limited to 16 colors (for no...
ca95f2fc6d1aec73f6393fdd9eb609664eca4a19
52,368
def other_sentence(type, request, sentence): """ process the other from of a sentence Input=type and requesting of sentence and the sentence Output=class Sentence """ #init...
7d63fbc78e38b5ad3b54c0b4c2fe271a63e0dd84
52,369
from indra.tools.expand_families import Expander def expand_families(stmts_in, **kwargs): """Expand FamPlex Agents to individual genes. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to expand. save : Optional[str] The name of a pickle file ...
af62452c7ef526c2e4b00a3e1010da144c908ab1
52,371
def approx_eq_above(a, b): """ a < b :param a: :param b: :return: """ if approx_eq(a, b): return True else: return a <= b
edadc02ccb70c46cd6ef95b60b345309adb23ef2
52,375
def precision_score(targets, preds, cm=None, w=None, average='binary'): """ :purpose: Calculates the precision score between a discrete target and pred array :params: targets, preds : discrete input arrays, both of shape (n,) cm : if you have previously calculated a confusion matrix...
5304af75c5c9f42a5dc7d3104cbc9fdd4303500f
52,376
def complete_feature(ctx, args, incomplete): """Completion function that returns feature/<id> for open issues.""" return sorted([('feature/{}'.format(id), description) for id, description in complete_issue(ctx, args, incomplete)])
c9a4fc34c327c0e8cfb5a37e40970990267708a3
52,377
from typing import Optional from typing import Callable from typing import List def min_weight_simple_path_anneal( graph: nx.Graph, n: int, start_path=None, anneal_schedule: Optional[np.array] = None, weight_fun: Callable[[nx.Graph, List], float] = path_weight): """A simula...
baa1c2be28ab309f0bb845f574c90fa7eadd54da
52,378
def creer_entete(nomFichier) : """!Crée l'en-tête du fichier Prend le nom de base du fichier et sa taille, et l'écrit dans l'en-tête. @param nomFichier Nom du fichier à concaténer @return L'en-tête à écrire dans le fichier d'archive """ # Pour l'en-tête, on fait un truc simple avec le nom du ...
f35b8391da7a77beea4e1932cb280f8f54cf879b
52,379
import array def dX_dt_Duffing(X,t=0): """ Return the Duffing oscillator derivative """ return array([X[1], -epsi*X[1] -X[0]*(beta*X[0]**2+alpha)])
2cec2c5dadf42e881bf1c8b6eea34ebfd3502e4f
52,380
def mySettings(): """ Define your trading system settings here """ settings = {} print('your call') # Futures Contracts settings['markets'] = ['CASH', 'KSU', 'VLO', 'ZTS', 'GOOG', 'AMZN', 'AAPL', 'BA', 'FB', 'NFLX', 'THC', 'F_US', 'F_TU', 'F_ES'] # settings['markets...
2f24d687a2d0b2324c9519b8bb584324fa0c9421
52,381
def iou(segments1, segments2): """Computes pairwise intersection-over-union between segment collections. Args: segments1 (numpy array): shape [N, 2] holding N segments segments2 (numpy array): shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwi...
bd7365f4c9b7f1bcdf42b7f39db29196c067bfc0
52,382
def to_feed(df): """Generate and return a feed item for the given data frame""" fg = FeedGenerator() fg.id(feed["id"]) fg.title(feed["title"]) fg.link(href=feed["link"], rel="self") fg.language(feed["language"]) fg.description(feed["description"]) fg.generator("SNSZ") fg.rights(feed[...
7db6244f37c1a871f84a38f90665351c1754a915
52,383
import re def find_index(filename): """Search the file index of the filename, if any, or return None.""" r = re.search(r"([^\n]+)\.([^\.]+)\.([0-9]+)$", filename) if r: return int(r.group(3)) # If the filename has no index in it, and if the file does not actually # exist, return the index ...
83f963b26a356c6b7d0d96f8335bb1a73031e0aa
52,384
def filter_links(links, **kwargs): """ """ filtered_links = {} for url, v in links.items(): parsed = urlparse(url) if parsed.netloc in ['scholar.google.com', 'scholar.google.ca']: # At this point for google scholar, we are only # interested in the links ...
7e39304b12f2047d54297a55349d3aa85b111691
52,386
def runtimeerror_error(e): """Flask error handler for RuntimeError exceptions""" log.exception("RuntimeError exception raised") return json_error(500, "Internal Server Error", str(e))
57978614ad8a7c6a5512c1776323709724dc747b
52,387
from typing import Dict import json def arg_types_from_json(arg_types_json: str) -> Dict[str, type]: """Reify the encoded argument types from the format produced by arg_types_to_json.""" arg_types = json.loads(arg_types_json) return {name: type_from_dict(type_dict) for name, type_dict in arg_types.items()...
ad8ff9d0335224ae597c0a7c95ca2f0fe758c887
52,388
def service_signal(service, ident=None): """Encode service and identifier into signal.""" signal = "{}_{}".format(DOMAIN, service) if ident: signal += "_{}".format(ident.replace(".", "_")) return signal
fd141a04b83ea7c081ba84960c6ba8a8c1607c5d
52,389
from typing import Mapping from typing import Optional import click def is_version_bump_enabled(bump_config: Mapping, ctx: Optional[click.Context] = None, *, is_publish_from_branch_allowed: Optional[bool] = None) -> bool: """ Check if current branch with version configuration is allowed to bump version To...
c3b4f1a77194b447b8beab70ad57c996ec6c7304
52,390
def add_index(body): """ Added a new Index :param body: Object that needs to be added to the db. :type body: dict | bytes :rtype: AddIndexResponse """ return Indexes.add_index(connexion)
635fdc6f14bd4f3f32e268b2c5b00ea21e8af24c
52,391
def sum_reduce(iter, params): """ Sums the values for each key. This is a convenience function for performing a basic sum in the reduce. """ buf = {} for key, value in iter: buf[key] = buf.get(key, 0) + value return buf.iteritems()
282a45d14db4f693a095331ff5f3a17296994697
52,392
def compose_graph(graph_dict, composed_name, name_list): """ Compose multiple graph together coming from a dictionary under a new entry of the dictionary. Parameters ---------- graph_dict : dict Dictionary of every graph. composed_name : str Name of the new key of graph_dict...
e4f01b2d895299d97282aee8293f9168e24e472b
52,393
import ctypes def subslr(method, target, et, fixref, abcorr, obsrvr): """ Compute the rectangular coordinates of the sub-solar point on a target body at a specified epoch, optionally corrected for light time and stellar aberration. This routine supersedes subsol_c. http://naif.jpl.nasa.gov/p...
8d566d8a55019ca7f47e614704356e0423c6ab09
52,394
def init_default_extractor(): """ create a new extractor, providing the default (all available extractors) """ return SchemaExtractorSet(DEFAULT_EXTRACTOR_LIST)
4f93cf193283a82d1ecd27cbff771f49c721e22e
52,395
import importlib def load_class_from_path(path_and_class: str): """ Dynamically load a class from a module at the specified path Args: path_and_class: relative path where to find the module and its class name i.e. 'neo3.<package>.<package>.<module>.<class name>' Raises: ValueEr...
fc00c6ee3bea277a5c8cc12b1fa29b5c294ff069
52,396
def ROC(ds, count, timeperiod=-2**31): """Rate of change : ((price/prevPrice)-1)*100""" return call_talib_with_ds(ds, count, talib.ROC, timeperiod)
2f50fc35858e983a981604499aba53a76e5722ab
52,397
from io import StringIO def get_xml_bones(document): """ This function returns the "bones" of an XML document, replacing all the text-data and attribute values with a round(length) For example: <xml></xml> ---> xml0/xml <xml>hello</xml> ---> xml0/xm...
5e132f20dd2c5e74888ea7296fabb911a52a9c40
52,398
def graph_encoder_layer(enc_input, # (batch_size, n_block, emb_dim) attn_bias, # (batch_size, n_head, n_block, n_block) graph_attn_bias, # (batch_size, n_head, n_block, n_block) pos_win, n_head, d_...
511c4b4e45b37bffbc8759e9f3ba3bc5463fa763
52,399
def trim_doc(doc): """ Strips indentation from a docstring; also removes leading and trailing blank lines. `doc`: ``str`` or ``None`` A docstring. """ assert isinstance(doc, maybe(oneof(str, unicode))) # Pass `None` through. if doc is None: return None # Convert to...
3fc3df4288a053001c1d70c098b461d7aa2e2eb5
52,400
def abbreviate_id(a_string): """ 1. Hack off the first 6 and the last 4 characters. 2. Then join them with an ellipsis. :param a_string: :return: An abbreviated id string """ return str(a_string[0:6]+'...'+a_string[-4::])
8127ae7e45638d77c7c0b3c414ea96f64dae7228
52,401
from re import T import re def isbn(value: str) -> T.Union[T.Match[str], None]: """ Matched isbn 10 or 13 Example: 978-1-4302-1998-9 1–931836–59–0 1593270127 0 321 15420 7 978-0-07-162612-5 Detail: https://en.wikipedia.org/wiki/International_Standard_Book_Number...
b54f063cca768ae8843c76b828de5f8757d6931a
52,402
import torch def test(net, testloader): """Validate the network on the entire test set.""" criterion = torch.nn.CrossEntropyLoss() correct, total, loss = 0, 0, 0.0 with torch.no_grad(): for data in testloader: images, labels = data[0].to(DEVICE), data[1].to(DEVICE) outp...
3f9c9e118c612b49e771f79ca24248fb72c052ed
52,403
def reverse_integer(x): """Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0. :type x: int :rtype: int """ x_string = str(x) if x_string[0] == "-": # in case t...
0fead2fbc52e09d9442f9c1f4efe5d7eb4a7e0be
52,404
import typing def _convertbits( data: typing.Iterable[int], from_bits: int, to_bits: int, pad: bool ) -> typing.Optional[typing.List[int]]: """General power-of-2 base conversion.""" acc = 0 bits = 0 ret = [] maxv = (1 << to_bits) - 1 max_acc = (1 << (from_bits + to_bits - 1)) - 1 for v...
7794d79b158e157ab8623f298cbc7e56eef5c98c
52,405