content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def remove_suboptimal_parses(parses: Parses, just_one: bool) -> Parses: """ Return all parses that have same optimal cost. """ minimum = min(parse_cost(parse) for parse in parses) minimal_parses = [parse for parse in parses if parse_cost(parse) == minimum] if just_one: return Parses([minimal_par...
c223229e73a5319bdb40ac58695aa6f5a8c0bb4b
27,042
def local_ranking(results): """ Parameters ---------- results : list Dataset with initial hand ranking and the global hand ranking. Returns ------- results : list Dataset with the initial hand ranking and the game-local hand ranking (from 0 - nplayers). ""...
2be1ff269ad18ba9439d183f5899f5034927b5d7
27,043
def is_monotonic_increasing(bounds: np.ndarray) -> bool: """Check if int64 values are monotonically increasing.""" n = len(bounds) if n < 2: return True prev = bounds[0] for i in range(1, n): cur = bounds[i] if cur < prev: return False prev = cur retur...
e745ce3825f4e052b2f62c7fdc23e66b5ee5d4d1
27,044
def parse(data): """ Takes binary data, detects the TLS message type, parses the info into a nice Python object, which is what is returned. """ if data[0] == TLS_TYPE_HANDSHAKE: obj = TlsHandshake() obj.version = data[1:3] obj.length = unpack(">H", data[3:5])[0] if data[5] == TLS_TYPE_CLIENT_HELLO: obj....
64698fde904d702181f4d8bacda648d9fbea68a7
27,045
def recoverSecretRanks_GPT(mod_rec, tok_rec, startingText, outInd, finishSentence=True): """ Function to calculate the secret ranks of GPT2 LM of a cover text given the cover text """ startingInd=tok_rec.encode(startingText) endingInd=outInd[len(startingInd):] secretTokensRec=[] for i in ran...
be08520901b5c010d89a248814f96681265bb467
27,046
def threshold_strategies(random_state=None): """Plan (threshold): - [x] aggregated features: (abs(mean - median) < 3dBm) || (2*stdev(x) < 8dBm) - [x] histogram: x < 85dBm - [ ] timeseries batch: p < 10**-3 """ dummy = lambda: dummy_anomaly_injector(scaler=None, random_state=random_s...
d127a36d36360f6733e26538c37d3cbb47f199a4
27,047
import math def ellipse_properties(x, y, w): """ Given a the (x,y) locations of the foci of the ellipse and the width return the center of the ellipse, width, height, and angle relative to the x-axis. :param double x: x-coordinates of the foci :param double y: y-coordinates of the foci :param...
95864eac0feb9c34546eefed5ca158f330f88e3d
27,048
def build_func(f, build_type): """ Custom decorator that is similar to the @conf decorator except that it is intended to mark build functions specifically. All build functions must be decorated with this decorator :param f: build method to bind :type f: function :parm build_type: The WAF build t...
e880b7d5a3c4ac79a3caff48f1a3f991ed321262
27,049
def getnumoflinesinblob(ext_blob): """ Get number of lines in blob """ ext, blob_id = ext_blob return (ext, blob_id, int(getpipeoutput(['git cat-file blob %s' % blob_id, 'wc -l']).split()[0]))
ccc492cc66e046d73389f6822ad04cd943376f7b
27,050
import requests def fetch_data(full_query): """ Fetches data from the given url """ url = requests.get(full_query) # Parse the json dat so it can be used as a normal dict raw_data = url.json() # It's a good practice to always close opened urls! url.close() return raw_data
576b2548c1b89827e7586542e4d7e3f0cc89051d
27,052
import http def post(*args, **kwargs): # pragma: no cover """Make a post request. This method is needed for mocking.""" return http.post(*args, **kwargs)
d5c91da5f39ece36183a8265f74378a35f11c4c7
27,053
def shear_x(image: tf.Tensor, level: float, replace: int) -> tf.Tensor: """Equivalent of PIL Shearing in X dimension.""" # Shear parallel to x axis is a projective transform # with a matrix form of: # [1 level # 0 1]. image = transform( image=wrap(image), transforms=[1., level, 0., 0., 1., 0., 0., ...
230fb5d346a966c4945b0bb39f336c1fddeb94fd
27,054
def extract_const_string(data): """Extract const string information from a string Warning: strings array seems to be practically indistinguishable from strings with ", ". e.g. The following is an array of two elements const/4 v0, 0x1 new-array v0, v0, [Ljava/lang/String; const/4 v1, 0x0 ...
70229ea1a6183218577244f185a5e37d170fe4be
27,056
def choose_action(q, sx, so, epsilon): """ Choose action index for given state. """ # Get valid action indices a_vindices = np.where((sx+so)==False) a_tvindices = np.transpose(a_vindices) q_max_index = tuple(a_tvindices[np.argmax(q[a_vindices])]) # Choose next action based on epsilon-g...
626ccda15c24d983a060bdd6dd90a836c461b1ba
27,057
def soliswets(function, sol, fitness, lower, upper, maxevals, delta): """" Implements the solis wets algorithm """ bias = zeros(delta.shape) evals = 0 num_success = 0 num_failed = 0 dim = len(sol) while evals < maxevals: dif = uniform(0, delta, dim) newsol = clip(so...
19104e717af6701ce3d838d526059575306018cf
27,059
def _get_precision_type(network_el): """Given a network element from a VRP-REP instance, returns its precision type: floor, ceil, or decimals. If no such precision type is present, returns None. """ if 'decimals' in network_el: return 'decimals' if 'floor' in network_el: return 'flo...
b3b451a26ec50ce5f2424ea7a3652123ae96321d
27,060
import json def user_list(): """Retrieves a list of the users currently in the db. Returns: A json object with 'items' set to the list of users in the db. """ users_json = json.dumps(({'items': models.User.get_items_as_list_of_dict()})) return flask.Response(ufo.XSSI_PREFIX + users_json, headers=ufo.JS...
b216b41b35b4b25c23ea2cc987ff4fe2b6464775
27,062
import hashlib def md5_str(content): """ 计算字符串的MD5值 :param content:输入字符串 :return: """ m = hashlib.md5(content.encode('utf-8')) return m.hexdigest()
affe4742c2b44a60ef6dafa52d7a330594a70ed9
27,063
import requests def hurun_rank(indicator: str = "百富榜", year: str = "2020") -> pd.DataFrame: """ 胡润排行榜 http://www.hurun.net/CN/HuList/Index?num=3YwKs889SRIm :param indicator: choice of {"百富榜", "富豪榜", "至尚优品"} :type indicator: str :param year: 指定年份; {"百富榜": "2015至今", "富豪榜": "2015至今", "至尚优品": "201...
d8540f3b7482f8f56f0ec40ac2592ef0cfae4035
27,064
def yamartino_method(a, axis=None): """This function calclates the standard devation along the chosen axis of the array. This function has been writen to calculate the mean of complex numbers correctly by taking the standard devation of the argument & the angle (exp(1j*theta) ). This uses the Yamart...
1a313ac97495a0822de1f071191be08ec5b65269
27,065
def calc_half_fs_axis(total_points, fs): """ Геренирует ось до половины частоты дискр. с числом точек равным заданному """ freq_axis = arange(total_points)*fs/2/total_points # Hz до половины fs return freq_axis
35ef0482e3062d0af6f0e03e03e58e1c3cd33406
27,066
def fetch_weather(): """ select flight records for display """ sql = "select station, latitude,longitude,visibility,coalesce(nullif(windspeed,''),cast(0.0 as varchar)) as windspeed, coalesce(nullif(precipitation,''),cast(0.00 as varchar)) as precipitation from (select station_id AS station, info ->> 'Latitude' ...
8ab9f20255a64cfdaa5bfd6ed9aa675ed76f2f5d
27,067
def update_params(old_param, new_param, errors="raise"): """ Update 'old_param' with 'new_param' """ # Copy old param updated_param = old_param.copy() for k,v in new_param.items(): if k in old_param: updated_param[k] = v else: if errors=="raise": ...
95de4e8e1278b07d2bd8ccc61af4e2dc43f87ca2
27,068
from datetime import datetime def rng_name(): """Generate random string for a username.""" name = "b{dt.second}{dt.microsecond}" return name.format(dt=datetime.datetime.utcnow())
81be1b40770b08ec6b9adce0c3c9970ff1f3d442
27,070
def collections(id=None): """ Return Collections Parameters ---------- id : STR, optional The default is None, which returns all know collections. You can provide a ICOS URI or DOI to filter for a specifict collection Returns ------- query : STR A query, which can...
0cd1704d2ac43f34d6e83a3f9e9ead39db390c2e
27,071
def zmat_to_coords(zmat, keep_dummy=False, skip_undefined=False): """ Generate the cartesian coordinates from a zmat dict. Considers the zmat atomic map so the returned coordinates is ordered correctly. Most common isotopes assumed, if this is not the case, then isotopes should be reassigned to the xyz....
0859a549b611347b4e3d94e4f0965a8a550e198e
27,073
def get_module_version(module_name: str) -> str: """Check module version. Raise exception when not found.""" version = None if module_name == "onnxrt": module_name = "onnx" command = [ "python", "-c", f"import {module_name} as module; print(module.__version__)", ] ...
caadba47f46d96b0318cd90b0f85f8a2ca2275b0
27,074
def pd_images(foc_offsets=[0,0], xt_offsets = [0,0], yt_offsets = [0,0], phase_zernikes=[0,0,0,0], amp_zernikes = [0], outer_diam=200, inner_diam=0, \ stage_pos=[0,-10,10], radians_per_um=None, NA=0.58, wavelength=0.633, sz=512, \ fresnel_focal_length=None, um_per_pix=6.0): """ Create a set of simu...
71a7dd7206936541cc55d8909be7795261aeaefa
27,075
def add_tickets(create_user, add_flights): """Fixture to add tickets""" user = create_user(USER) tickets = [{ "ticket_ref": "LOS29203SLC", "paid": False, "flight": add_flights[0], "type": "ECO", "seat_number": "E001", "made_by": user, }, { "ticket...
27f9ed9a5231c71e98a79632a97137b73831a0e0
27,076
def compute_depth_errors(gt, pred): """Computation of error metrics between predicted and ground truth depths Args: gt (N): ground truth depth pred (N): predicted depth """ thresh = np.maximum((gt / pred), (pred / gt)) a1 = (thresh < 1.25).mean() a2 = (thresh < 1.25 ** 2).mean() ...
a781d5a8c1e61b5562870d75124de64e05fe2789
27,077
def sanitize_bvals(bvals, target_bvals=[0, 1000, 2000, 3000]): """ Remove small variation in bvals and bring them to their closest target bvals """ for idx, bval in enumerate(bvals): bvals[idx] = min(target_bvals, key=lambda x: abs(x - bval)) return bvals
a92b170748b5dbc64c4e62703a3c63103675b702
27,078
def fetch_engines(): """ fetch_engines() : Fetches documents from Firestore collection as JSON all_engines : Return all documents """ all_engines = [] for doc in engine_ref.stream(): engine = doc.to_dict() engine["id"] = doc.id all_engines.append(engine) ret...
a79a623140209ed4e9e7cbea2d8944b3434f720a
27,079
def isone(a: float) -> bool: """Work around with float precision issues""" return np.isclose(a, 1.0, atol=1.0e-8, rtol=0.0)
ee44d5d7a9b00457e51501d8ce5680cd95726e3f
27,080
def kerr(E=0, U=0, gs=None): """ Setup the Kerr nonlinear element """ model = scattering.Model( omegas=[E]*1, links=[], U=[U]) if gs is None: gs = (0.1, 0.1) channels = [] channels.append(scattering.Channel(site=0, strength=gs[0])) channels.append(scatte...
a94ecb4618405a2817267609008bc56ef97033b9
27,082
from typing import Dict import requests import logging def get_estate_urls(last_estate_id: str) -> Dict: """Fetch urls of newly added estates Args: last_estate_id (str): estate_id of the most recent estate added (from last scrape) Returns: Dict: result dict in format {estate_id_1: {estat...
d93299002204edc9d26b3c77e2dff1f56f4b93d8
27,083
from datetime import datetime def revert_transaction(): """Revert a transaction.""" if not (current_user.is_admin or current_user.is_bartender): flash("You don't have the rights to access this page.", 'danger') return redirect(url_for('main.dashboard')) transaction_id = request.args.get('...
39f4fc0c6af9c58197c514d5d648e07da20558aa
27,084
def is_number(s): """returns true if input can be converted to a float""" try: float(s) return True except ValueError: return False
d9fc4411bbc5e5fd8d02b3c105a770e8859048e0
27,085
def bib_to_string(bibliography): """ dict of dict -> str Take a biblatex bibliography represented as a dictionary and return a string representing it as a biblatex file. """ string = '' for entry in bibliography: string += '\n@{}{{{},\n'.format( bibliography[entry]['type'], ...
c8fc4247210f74309929fdf9b210cd6f1e2ece3f
27,086
import io def make_plot(z, figsize=(20, 20), scale=255 * 257, wavelength=800, terrain=None, nir_min=0.2, offset=3.5): """ Make a 3-D plot of image intensity as z-axis and RGB image as an underlay on the z=0 plane. :param z: NIR intensities :param figsize: size of the figure...
1a4dde23a11b320e6564b6657a871a33ecb65eea
27,087
def check_prio_and_sorted(node): """Check that a treap object fulfills the priority requirement and that its sorted correctly.""" if node is None: return None # The root is empty else: if (node.left_node is None) and (node.right_node is None): # No children to compare with ...
64100fd4ba9af699ab362d16f5bbf216effa2da5
27,088
import pickle async def wait_for_msg(channel): """Wait for a message on the specified Redis channel""" while await channel.wait_message(): pickled_msg = await channel.get() return pickle.loads(pickled_msg)
dca398cb3adeb778458dd6be173a53cdd204bcb9
27,090
def abandoned_baby_bull(high, low, open_, close, periods = 10): """ Abandoned Baby Bull Parameters ---------- high : `ndarray` An array containing high prices. low : `ndarray` An array containing low prices. open_ : `ndarray` An array containing open prices. clos...
5fb0f2e3063e7b7aa03663d1e2d04d565ec8e885
27,091
def split_line_num(line): """Split each line into line number and remaining line text Args: line (str): Text of each line to split Returns: tuple consisting of: line number (int): Line number split from the beginning of line remaining text (str): Text for remainder ...
d232fd046ee60ac804fff032494c8c821456c294
27,092
def rad_to_arcmin(angle: float) -> float: """Convert radians to arcmins""" return np.rad2deg(angle)*60
c342286befd79a311edda18e8a7a2e978d8312ad
27,093
def get_tile_prefix(rasterFileName): """ Returns 'rump' of raster file name, to be used as prefix for tile files. rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f) where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"] The rump is defined as <da...
15b517e5ba83b2cfb5f3b0014d800402c9683815
27,094
def get_indices_by_groups(dataset): """ Only use this to see F1-scores for how well we can recover the subgroups """ indices = [] for g in range(len(dataset.group_labels)): indices.append( np.where(dataset.targets_all['group_idx'] == g)[0] ) return indices
864aad8eef0339afd04cce34bee65f46c9fb030b
27,095
def ranksumtest(x, y): """Calculates the rank sum statistics for the two input data sets ``x`` and ``y`` and returns z and p. This method returns a slight difference compared to scipy.stats.ranksumtest in the two-tailed p-value. Should be test drived... Returns: z-value for first data set ``...
d01d0a56cf888983fa1b8358f2f6f0819ca824d9
27,096
def inchi_to_can(inchi, engine="openbabel"): """Convert InChI to canonical SMILES. Parameters ---------- inchi : str InChI string. engine : str (default: "openbabel") Molecular conversion engine ("openbabel" or "rdkit"). Returns ------- str Canonical SMILES. ...
040d091f1cdbc1556fd60b9ee001953e1a382356
27,098
from typing import List from re import T def swap(arr: List[T], i: int, j: int) -> List[T]: """Swap two array elements. :param arr: :param i: :param j: :return: """ arr[i], arr[j] = arr[j], arr[i] return arr
e34c983b816f255a8f0fb438c14b6c81468b38c6
27,099
def is_anno_end_marker(tag): """ Checks for the beginning of a new post """ text = tag.get_text() m = anno_end_marker_regex.match(text) if m: return True else: return False
28b7d216c38dabedaef33f4d71f9749e72344b65
27,100
async def fetch_and_parse(session, url): """ Parse a fatality page from a URL. :param aiohttp.ClientSession session: aiohttp session :param str url: detail page URL :return: a dictionary representing a fatality. :rtype: dict """ # Retrieve the page. # page = await fetch_text(session...
525bf965854a098507046b3408de5e73bcd4abc9
27,101
def wmt_diag_base(): """Set of hyperparameters.""" hparams = iwslt_diag() hparams.batch_size = 4096 hparams.num_hidden_layers = 6 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_heads = 8 # VAE-related flags. hparams.latent_size = 512 hparams.n_posterior_layers = 4 hparams.n_decod...
384820d2fadc13711968a666a6f4d7b1be0726c5
27,102
def K_axialbending(EA, EI_x, EI_y, x_C=0, y_C=0, theta_p=0): """ Axial bending problem. See KK for notations. """ H_xx = EI_x*cos(theta_p)**2 + EI_y*sin(theta_p)**2 H_yy = EI_x*sin(theta_p)**2 + EI_y*cos(theta_p)**2 H_xy = (EI_y-EI_x)*sin(theta_p)*cos(theta_p) return np.array([ [EA ...
f187b35c5324a0aa46e5500a0f37aebbd2b7cc62
27,103
def get_closest_intersection_pt_dist(path1, path2): """Returns the manhattan distance from the start location to the closest intersection point. Args: path1: the first path (list of consecutive (x,y) tuples) path2: the secong path Returns: int of lowest manhattan distance ...
07bbe3a2d5f817f28b4e077989a89a78747c676f
27,104
def is_voiced_offset(c_offset): """ Is the offset a voiced consonant """ return c_offset in VOICED_LIST
6dfad8859ba8992e2f05c9946e9ad7bf9428d181
27,105
def add_boundary_label(lbl, dtype=np.uint16): """ Find boundary labels for a labelled image. Parameters ---------- lbl : array(int) lbl is an integer label image (not binarized). Returns ------- res : array(int) res is an integer label image with boundary encoded as 2. ...
31bae32ad08c66a66b19379d30d6210ba2b61ada
27,107
def kmax(array, k): """ return k largest values of a float32 array """ I = np.zeros(k, dtype='int64') D = np.zeros(k, dtype='float32') ha = float_minheap_array_t() ha.ids = swig_ptr(I) ha.val = swig_ptr(D) ha.nh = 1 ha.k = k ha.heapify() ha.addn(array.size, swig_ptr(array)) h...
41037c924ae240636309f272b95a3c9dcfe10c5e
27,108
def adcp_ins2earth(u, v, w, heading, pitch, roll, vertical): """ Description: This function converts the Instrument Coordinate transformed velocity profiles to the Earth coordinate system. The calculation is defined in the Data Product Specification for Velocity Profile and Echo Intensi...
0a51db6b5d6186c4f9208e4fa2425160e8c43925
27,109
import math def strength(data,l): """ Returns the strength of earthquake as tuple (P(z),S(xy)) """ # FFT # https://momonoki2017.blogspot.com/2018/03/pythonfft-1-fft.html # Fast Fourier Transform # fx = np.fft.fft(data[0]) # fy = np.fft.fft(data[1]) # fz = np.fft.fft(data[2]) #...
705b04644002c2cf826ca6a03838cab66ccea1f8
27,110
def humanize(tag, value): """Make the metadata value human-readable :param tag: The key of the metadata value :param value: The actual raw value :return: Returns ``None`` or a human-readable version ``str`` :rtype: ``str`` or ``None`` """ for formatter in find_humanizers(tag): human...
42a4e1506b4655a86607495790f555cc318b6d82
27,112
import itertools def cartesian(sequences, dtype=None): """ Generate a cartesian product of input arrays. Parameters ---------- sequences : list of array-like 1-D arrays to form the cartesian product of. dtype : data-type, optional Desired output data-type. Returns ---...
51e6031c568eee425f2ea86c16b472474ae499eb
27,113
def nasa_date_to_iso(datestr): """Convert the day-number based NASA format to ISO. Parameters ---------- datestr : str Date string in the form Y-j Returns ------- Datestring in ISO standard yyyy-mm-ddTHH:MM:SS.MMMMMM """ date = dt.datetime.strptime(datestr, nasa_date_format...
d77114c874fdd41a220aae907ce7eabd6dd239bf
27,114
def auto_label_color(labels): """ ???+ note "Create a label->hex color mapping dict." """ use_labels = set(labels) use_labels.discard(module_config.ABSTAIN_DECODED) use_labels = sorted(use_labels, reverse=False) assert len(use_labels) <= 20, "Too many labels to support (max at 20)" pale...
791de575e500bf2c2e0e1d56c390c59a2f62381c
27,116
import re def dedentString(text): """Dedent the docstring, so that docutils can correctly render it.""" dedent = min([len(match) for match in space_re.findall(text)] or [0]) return re.compile('\n {%i}' % dedent, re.M).sub('\n', text)
a384b0c9700a17a7ce621bca16175464192c9aee
27,117
def preprocess(df): """Preprocess the DataFrame, replacing identifiable information""" # Usernames: <USER_TOKEN> username_pattern = r"(?<=\B|^)@\w{1,18}" df.text = df.text.str.replace(username_pattern, "<USERNAME>") # URLs: <URL_TOKEN> url_pattern = ( r"https?://(?:[a-zA-Z]|[0-9]|[$-_@.&...
d592d9e56af9ec17dcebede31d458dfdc001c220
27,118
def mobilenetv3_large_w7d20(**kwargs): """ MobileNetV3 Small 224/0.35 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/model...
550f8273dfe52c67b712f8cd12d1e916f7a917cc
27,119
def random_forest_classifier(model, inputs, method="predict_proba"): """ Creates a SKAST expression corresponding to a given random forest classifier """ trees = [decision_tree(estimator.tree_, inputs, method="predict_proba", value_transform=lambda v: v/len(model.estimators_)) for estimator...
d13e28e05d01a2938116a1bac5ddbd64f7b5438c
27,120
from cowbird.utils import get_settings as real_get_settings import functools def mock_get_settings(test): """ Decorator to mock :func:`cowbird.utils.get_settings` to allow retrieval of settings from :class:`DummyRequest`. .. warning:: Only apply on test methods (not on class TestCase) to ensure t...
8332d08846bcee6e9637f75c5c15fb763d9978a4
27,121
def _convert_to_interbatch_order(order: pd.Series, batch: pd.Series) -> pd.Series: """ Convert the order values from a per-batch order to a interbatch order. Parameters ---------- order: pandas.Series order and batch must share the same index, size and be of...
235e99d8a93ebeecde7bfe274b82fe32980288dd
27,122
def CV_INIT_3X3_DELTAS(*args): """CV_INIT_3X3_DELTAS(double deltas, int step, int nch)""" return _cv.CV_INIT_3X3_DELTAS(*args)
cbcbd6de2593d548c8e5bc02992d1df9a3d66460
27,123
def is_instance_cold_migrated_alarm(alarms, instance, guest_hb=False): """ Check if an instance cold-migrated alarm has been raised """ expected_alarm = {'alarm_id': fm_constants.FM_ALARM_ID_VM_COLD_MIGRATED, 'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL} return _instanc...
8b6db3498d09d4d538382507ffac249226a2912f
27,124
def precision_macro(y_target, y_predicted): """ y_target: m x n 2D array. {0, 1} real labels y_predicted: m x n 2D array {0, 1} prediction labels m (y-axis): # of instances n (x-axis): # of classes """ average = 'macro' score = precision_score(y_target, y_predicted, ave...
4038eb838f35da93b24301809e5f0c3d5c37e2c9
27,125
def layout(mat,widths=None,heights=None): """layout""" ncol=len(mat[0]) nrow=len(mat) arr=[] list(map(lambda m: arr.extend(m),mat)) rscript='layout(matrix(c(%s), %d, %d, byrow = TRUE),' %(str(arr)[1:-1],nrow,ncol) if widths: rscript+='widths=c(%s),' %(str(widths)[1:-1]) if h...
813fb351b4e09d4762255ecbbe6f9ee7e050efd0
27,126
def get_file_language(filename, text=None): """Get file language from filename""" ext = osp.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] # file extension with leading dot language = ext if not ext: if text is None: text, _enc = encoding.read(filename) ...
7cfcd49d94cc1c2246f03946cfea1c99b866f941
27,127
import re def _get_output_name(fpattern,file_ind,ind): """ Returns an output name for volumetric image This function returns a file output name for the image volume based on the names of the file names of the individual z-slices. All variables are kept the same as in the original filename, but the...
8ce392acab2984b5012d8de7a0aa205f9a5e5e3b
27,128
import re def MatchNameComponent(key, name_list, case_sensitive=True): """Try to match a name against a list. This function will try to match a name like test1 against a list like C{['test1.example.com', 'test2.example.com', ...]}. Against this list, I{'test1'} as well as I{'test1.example'} will match, but ...
ad522feba9cabb3407e3b8e1e8c221f3e9800e16
27,129
import requests def news_api(): """Uses news API and returns a dictionary containing news """ news_base_url = "https://newsapi.org/v2/top-headlines?" news_api_key = keys["news"] country = location["country"] news_url = news_base_url + "country=" + country + "&apiKey=" + news_api_key n_api = re...
45e8a9d42d64066e2259fc95727d52e6b5bdfc9e
27,130
def compress(mesh, engine_name="draco"): """ Compress mesh data. Args: mesh (:class:`Mesh`): Input mesh. engine_name (``string``): Valid engines are: * ``draco``: `Google's Draco engine <https://google.github.io/draco/>`_ [#]_ Returns: A binary string rep...
67d8ec030d006f6720bacffad7bacd0c36b9df42
27,131
import configparser def get_hotkey_next(config: configparser.RawConfigParser): """ 获取热键:下一个桌面背景 """ return __get_hotkey(config, 'Hotkey', 'hk_next')
3af499c01778a1defb0a440d042538885d829398
27,133
def get_soup(url): """ Returns beautiful soup object of given url. get_soup(str) -> object(?) """ req = urllib2.Request(url) response = urllib2.urlopen(req) html = response.read() soup = bs4(html) return soup
8d0bb43ae1d404cef5a3873dfd089b88461bf9fd
27,135
def internal_server_error(error): """ Handles unexpected server error with 500_SERVER_ERROR """ message = error.message or str(error) app.logger.info(message) return make_response(jsonify(status=500, error='Internal Server Error', message=message), 500)
8e80a4502a4656a1ccdb2c720177090dd7bcf53a
27,136
import math def diffsnorms(A, S, V, n_iter=20): """ 2-norm accuracy of a Schur decomp. of a matrix. Computes an estimate snorm of the spectral norm (the operator norm induced by the Euclidean vector norm) of A-VSV', using n_iter iterations of the power method started with a random vector; n_i...
2f446a08c6ff5d8377cca22ffcd1570c68f46748
27,137
from typing import Iterator from typing import Tuple def data_selection(workload: spec.Workload, input_queue: Iterator[Tuple[spec.Tensor, spec.Tensor]], optimizer_state: spec.OptimizerState, current_param_container: spec.ParameterContainer, h...
6daa0950e5ce82da081b71a01572dc29374f17f8
27,138
def graph_cases_factory(selenium): """ :type selenium: selenium.webdriver.remote.webdriver.WebDriver :rtype: callable :return: Constructor method to create a graph cases factory with a custom host. """ return lambda host: GraphCaseFactory(selenium=selenium, host=host)
b41b02c148b340c07859e707cbaf4810db3b6004
27,139
def clean_scene_from_file(file_name): """ Args: file_name: The name of the input sequence file Returns: Name of the scene used in the sequence file """ scene = scenename_from_file(file_name) print('Scene: ', scene) mesh_file = SCENE_PATH + scene + '/10M_clean.ply' return ...
cd706c900ca3e3fce6736ce5c4288cce6079b3e0
27,140
def _non_overlapping_chunks(seq, size): """ This function takes an input sequence and produces chunks of chosen size that strictly do not overlap. This is a much faster implemetnation than _overlapping_chunks and should be preferred if running on very large seq. Parameters ---------- seq : ...
15b5d2b4a7d8df9785ccc02b5369a3f162704e9e
27,141
import logging def Compute_Error(X_data, pinn, K, mu, Lf, deltamean, epsilon, ndim) : """ Function to determine error for input data X_data :param array X_data: input data for PINN :param PINN pinn: PINN under investigation :param float K: key parameter for using trapezoidal rule and estimating t...
0789d7c52c96aed5cb40aa45c44c4df09f5cffaf
27,143
import itertools def sort_fiducials(qr_a, qr_b): """Sort 2d fiducial markers in a consistent ordering based on their relative positions. In general, when we find fiducials in an image, we don't expect them to be returned in a consistent order. Additionally, the image coordinate may be rotated from...
daa96f12ef2e94fed86970979e4d140f8a3fa3d5
27,144
from pathlib import Path import jinja2 def form_render(path: str, **kwargs) -> str: """ Just jinja2 """ file_text = Path(path).read_text() template = jinja2.Template(file_text) return template.render(**kwargs)
b5da5afdedcac922c164f644eabeae5f038f9169
27,145
def _names(fg, bg): """3/4 bit encoding part c.f. https://en.wikipedia.org/wiki/ANSI_escape_code#3.2F4_bit Parameters: """ if not (fg is None or fg in _FOREGROUNDS): raise ValueError('Invalid color name fg = "{}"'.format(fg)) if not (bg is None or bg in _BACKGROUNDS): raise Va...
50e4dfe9aa56c1f3fc7622c468045b26da9b4175
27,146
def preprocess(code): """Preprocess a code by removing comments, version and merging includes.""" if code: #code = remove_comments(code) code = merge_includes(code) return code
b4ecbf28fa2043559b744e7351f268a2ba1e8200
27,147
import types def _from_schemas_get_model( stay_within_model: bool, schemas: _oa_types.Schemas, schema: _oa_types.Schema ) -> types.ModelArtifacts: """ Get artifacts for a model. Assume the schema is valid. Args: schema: The schema of the model to get artifacts for. schemas: All d...
0c5166c6baaabda64795729554b7bb3444a902c9
27,148
def solution2(inp): """Solves the second part of the challenge""" return "done"
8e20e1a81911b3f2e54fac058df8a44e54945af0
27,149
import math def juld_to_grdt(juld: JulianDay) -> GregorianDateTime: """ユリウス通日をグレゴリオ曆の日時に變換する.""" A = math.floor(juld.julian_day + 68569.5) B = juld.julian_day + 0.5 a = math.floor(A / 36524.25) b = A - math.floor(36524.25 * a + 0.75) c = math.floor((b + 1) / 365.25025) d = b - math.floor(3...
94559bbec7fef45e6c7f6d8594d20c8039b58672
27,150
def users_all(request): """ Returns name + surname and email of all users Note: This type of function can only be justified when considering the current circumstances: An *INTERNAL* file sharing app (used by staff) Hence, all names and emails may be fetched be other authenticated users ...
53302d074ee1bbbc1156ffa2f94da4f834e9cb3c
27,151
def _resolve_categorical_entities(request, responder): """ This function retrieves all categorical entities as listed below and filters the knowledge base using these entities as filters. The final search object containing the shortlisted employee data is returned back to the calling function. """ ...
d6671d030699df1b0400b1d478dc98f86be06c29
27,152
def filter_c13(df): """ Filter predicted formulas with 13C. Returns filtered df and n excluded """ shape_i = df.shape[0] df = df[df['C13'] == 0] df = df.reset_index(drop=True) shape_f = df.shape[0] n_excluded = shape_i - shape_f return df, n_excluded
4f0d3eb6c9de7c07bc2e3f285ad5502bb6d6dd06
27,153
import random import gzip def getContent(url): """ 此函数用于抓取返回403禁止访问的网页 """ random_header = random.choice(HEARDERS) """ 对于Request中的第二个参数headers,它是字典型参数,所以在传入时 也可以直接将个字典传入,字典中就是下面元组的键值对应 """ req = Request(url) req.add_header("User-Agent", random_header) req.add_header("Ho...
da396d664fb23737ea2d87b6548521948adad709
27,154
def neighbour(x,y,image): """Return 8-neighbours of image point P1(x,y), in a clockwise order""" img = image.copy() x_1, y_1, x1, y1 = x-1, y-1, x+1, y+1; return [img[x_1][y], img[x_1][y1], img[x][y1], img[x1][y1], img[x1][y], img[x1][y_1], img[x][y_1], img[x_1][y_1]]
8e645f7634d089a0e65335f6ea3363d4ed66235b
27,155
def deconv2d(x, kernel, output_shape, strides=(1, 1), border_mode='valid', dim_ordering='default', image_shape=None, filter_shape=None): """2D deconvolution (i.e. transposed convolution). # Arguments x: input tensor. kernel: kernel tensor. output_s...
d1ed452b627764f0f08c669e4bea749886ebd0a6
27,157