content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sort_tables(tables, skip_fn=None, extra_dependencies=None): """sort a collection of Table objects in order of their foreign-key dependency.""" tables = list(tables) tuples = [] if extra_dependencies is not None: tuples.extend(extra_dependencies) def visit_foreign_key(fk...
3a6e3328ff38cb30b68a2d401834ded009f1ef39
68,061
def RNA_to_AA(numeric_columns): """ Translate an RNA codon to its corresponding amino acid """ return translation[codon]
2cc58c83c0caee1f35487d0e6130e689320461e8
68,062
def remove_stopwords(text, swords=None): """Remove stopwords """ if swords is None: swords = stopwords.words('english') words = wordpunct_tokenize(text) words = [w for w in words if w not in swords] text = ' '.join(words) return text
797174c38c6acb58e298e37e6681f34188af6be2
68,063
def u2_(U1, h=1., z1=2., z2=10.): # pragma: no cover """ :param xU1: measurement at one height :param xh: canopy height (m) :param xz: measurement height (m) :return u2: wind at another height """ zo = zo_(h) d = d_(h) return U1*(log((z2 - d) / zo))/(log((z1 - d) / zo))
c551962b912fa2f173a1c3087baf6342c47c57fe
68,064
def build_pmid_exclusion_filter(pmids: Strings) -> EdgePredicate: """Fail for edges with citations whose references are one of the given PubMed identifiers. :param pmids: A PubMed identifier or list of PubMed identifiers to filter against """ return invert_edge_predicate(build_pmid_inclusion_filter(pmi...
719f185c4f1982152e4f89fce7f08df467c47867
68,065
def onboarding_ml_app_patterns_get(): # noqa: E501 """Get list of all MLApp patterns # noqa: E501 :rtype: List[MLAppPattern] """ return 'do some magic!'
25be7fd2797eb7a3e8fd7d5cb41e88dd7c607a7d
68,066
def extractMask(video_masks, frame_time): """ Extract one mask from a group of videomasks given the frame_time :param video_masks: :param frame_time: time or frame number :return: """ extract_time_tuple = tool_set.getMilliSecondsAndFrameCount(frame_time, defaultValue=(0, 1)) timeManager...
bc37d1dc576e3e0e0a290dfa8d77831f9d820ca6
68,067
def FormatArguments(*args, **kwargs): """Format function call arguments in a human-readable way for logging.""" def _FormatArg(arg): return FormatLogArgument(arg) # Truncate arguments. args = [_FormatArg(arg) for arg in args] kwargs = {key: _FormatArg(value) for key, value in kwargs.items()} return "(...
3a9b2e84b717db75a9502f73553ba85dfbc7933f
68,069
def _fetchUnicodes(glif): """ Get a list of unicodes listed in glif. """ parser = _FetchUnicodesParser() parser.parse(glif) return parser.unicodes
271a84f979d8725845ee82dcd13a752010da2851
68,070
from datetime import datetime def login_user(): """ Function to check the user credentials. If they are correct, then generate a valid JWT token and return it. :return: status of the request or the user token """ # if the request doesn't have a Basic Authentication header, then discard it ...
b5404905f916c869e3b8a5d0fc0a8b6fe7830fc6
68,071
def plot3d(*args, **kwargs): """ Create a 3D surface plot of the specified 2D array (matrix). Plot3D image(surface): surface is a 2D array (matrix). Plot3D image(x, y, surface): surface is a 2D array (matrix); x and y are matrices of the same size that provide the x and y coordinates. x and y are expect...
d8e1a1262867981f21e671e8914938e8373486a0
68,072
def run_county(fips): """ Run the R_t inference for each county in a state. Parameters ---------- fips: str County fips to run against """ if not fips: return None df = RtInferenceEngine.run_for_fips(fips) county_output_file = get_run_artifact_path(fips, RunArtifact...
7124b9ee9f78d0267141d437971c3770b2999ce3
68,073
def parse_test_names( filedoc ): """ Determine the test name and check for validity. If this XML file is not an "rtest" then returns None. Otherwise returns a list of test names. """ if filedoc == None or filedoc.getName() != "rtest": return [] # determine the test name name = fi...
461a1f81db109a8527f4e91e1925242ea073b309
68,074
def get_files(path, keywords = ["features_ OR msd_"]): """ Takes in a path and list of keywords. Returns a list of filenames that are within the path that contain one of the keyword in the list. Set keyword to "" to get all files in the path. Parameters ---------- path : string file...
7f6ad0d2785c5646426bc8c17fdb3ea09762a4db
68,075
def EndOfBatches() -> Data: """Construct a 'end of batches' marker.""" return Data(graph_ids=[], data=None, end_of_batches=True)
50003d6ae1a379ce55a931d9843e488fa2bf7bfe
68,076
def GetClientInstance(release_track=base.ReleaseTrack.GA, use_http=True): """Returns an instance of the Cloud Build client. Args: release_track: The desired value of the enum googlecloudsdk.calliope.base.ReleaseTrack. use_http: bool, True to create an http object for this client. Returns: base...
95b156e8de65a8c51f851f204553f419c9d86eac
68,077
def driver_fixture(client, controller_state): """Return a driver instance with a supporting client.""" return Driver(client, controller_state)
8e706ba9e9704b9ea9803355f8e5d36f18db2b9b
68,078
import math def project_onto_ball(positions, head_position, radius): """ params: positions: 3-d numpy array, the original positions collected from unity params: head_position: 3-d numpy array, the center of fitting sphere params: radius: float, radius of the sphere return: """ new_position...
87ee065a30f434def3a742614fd5588d68a31720
68,079
def authorize_twitter(): """Authorize a user's Twitter account.""" TWITTER_REDIRECT_URL = url_for("get_twitter_token", _external=True) twitter_oauth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_RE...
22ab6ccf2c28a45d30b5c4446468c4b16e429102
68,080
import warnings def preprocess_dataset(X, y = None): """ Performs feature scaling, one-hot encoding of labels and shuffles the data if labels are provided. Assumes original dataset is sorted by labels. Parameters ---------- X : ndarray Dataset array c...
e3da84cbb8779350858d193c97fea418a2a3bdf2
68,081
def tenant_user_admin(db) -> TenantUser: """Returns Admin User instance.""" with schema_context('public'): return TenantUser.objects.create_superuser( _USER_PASS, email='super@user.com', )
602b6eff13587f56d38ef5982d0a391fd20c42d7
68,082
def ht_is_filled(x, y, intensity): """Returns 1 if halftone pixel is black, 0 if white""" return bayer_4x4[x&3][y&3] > intensity
eaa7781b5d7e8728dc3a17314e683901aea0c129
68,083
from typing import OrderedDict def _raw_at_zoom(config, zooms): """Return parameter dictionary per zoom level.""" params_per_zoom = OrderedDict() for zoom in zooms: params = OrderedDict() for name, element in config.items(): if name not in _RESERVED_PARAMETERS: ...
c4af99390f0994637f80130767c2caa5395d9d63
68,084
import itertools def get_adj_list(cities_file): """Return a list of adjacencies (assuming all city-to-city edges are feasible) along with the length of each edge (in km). """ cities = load_cities(cities_file) return itertools.combinations(cities, 2)
876b84fde5b715e2ba6d74312c35430261f82719
68,085
from typing import Set def rationalize(flt: float, denominators: Set[int] = None) -> Fraction: """Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is ...
78182602c0892efb7b4b4b5fd17e0f348c0c8e19
68,086
import json import types def async_transcribe(id): """ Transcribe the given audio file asynchronously and output the word time offsets. """ file_metadata = json.loads(get_file_metadata(id)) client = speech.SpeechClient() audio = types.RecognitionAudio(uri=file_metadata['uri']) config ...
fbd6837ce08e375bb9a79ac4439e8e11f8769cbc
68,087
def filtermed_image(data, border=10, filter_size=2): """Process image by removing the borders and filtering it via a median filter Input ----- data: 2d array Array to be processed border: int Number of pixels to remove at each edge filter_size: float Size of the...
968e5e618ee38e7d8d34c080b8a122387d0d91ed
68,088
def has_deco(deconames, tree, userlambdas=[]): """Return whether a FunctionDef or a decorated lambda has any given deco applied. deconames: list of decorator names to test. userlambdas: list of ``id(some_tree)``; when detecting a lambda, only consider it if its id matches one of those in the list. ...
d4473c568609f9f6fa74331a06fc33652bc7d2b5
68,089
from io import StringIO import csv import requests def show_redbull_history_csv(message): """RedBullの月単位の消費履歴をCSVに出力する :param message: slackbotの各種パラメータを保持したclass """ s = Session() consume_hisotry = (s.query(RedbullHistory) .filter(RedbullHistory.delta < 0) ...
b14f71ae30aae80fda05c03231b46b298433d783
68,090
from typing import List def find_closest_indices(values: List[float], target_values: List[float]) -> List[int]: """ Finds the indices in ``values`` that result in values closest to ``target_values``. """ closest_indices = [(np.abs(values - target_value)).argmin() for target_value in target_values] ...
3ada38e221cfa6ad0e9bdc10c413657066d0552c
68,091
def shades(name: str): """Create motorized shades with given name.""" return { "name": name, "type": DeviceType.MOTORIZED_SHADES, "actions": ["Open", "Close", "Hold"], }
87785cc24988c4b7cea7c2d2bfa1da891a56a48a
68,092
def count_comparison(combined_df): """ Provides a DataFrame that compares counts of growthcleanr categories between runs. Parameters: combined_df: A DataFrame in the format provided by prepare_for_comparison Returns: A DataFrame where the categories are the index and the columns are the run names. """ ...
1bbbec1cf0bc1710a53bd504eb094ff8fbc99db0
68,093
def get_decimalized_value(fact_a, fact_b, xule_context): """Adjust 2 fact values based on accuracy. :param fact_a: First fact :type fact_a: ModelFact :param fact_b: Second fact :type fact_b: ModelFact :returns: A tuple of the rounded fact values and the new decimals value for each :rtyp...
f93b206bf6a9f2fe105f5f7bce84d40beed858d7
68,094
def max_minimum_allocation_for_families(instance, families) -> AllocationToFamilies: """ Find the max-minimum (aka Egalitarian) allocation. :param agents: a matrix v in which each row represents an agent, each column represents an object, and v[i][j] is the value of agent i to object j. :param families:...
15659845a7b6779e58b25daf8b877edb3e9112dd
68,095
def _get_matching_coords(coords, params, shape): """ Get the matching coords across a number of broadcast operands. Parameters ---------- coords : list[numpy.ndarray] The input coordinates. params : list[Union[bool, none]] The broadcast parameters. Returns ------- nu...
a9c6618c5d7846af006be53f00ab2193c5318fab
68,096
def decode(daq_path, dataset): """ Converts char array into readible strings from the daq. Inputs: dataset (str): '/' seperated directory path to to_dataset Returns: list of strings contained in the dataset """ with h5py.File(daq_path, 'r') as f: try: strs =...
c194ad3d2c08b30f1493474da647055c1f421650
68,097
def run_process(cmd_args, cwd=None): """Runs the given process and returns its output and exit code. """ try: return subprocess.check_output(cmd_args, stderr=subprocess.STDOUT, cwd=cwd), 0 except subprocess.CalledProcessError, e: return e.output, e.returncode
67b696732afbabf1ec7ff0dc387684bdba3ddbb1
68,098
from operator import inv def generate_normals(m,P): """ Generate a Gaussian sample with mean m and precision P Parameters ---------- m array of shape n: the mean vector P array of shape (n,n): the precision matrix Returns ------- ng : array of shape(n): a draw from th...
67176faa04e260f238b1dd3ab36a6f455cf49b68
68,099
def fixName(name): """PMML tag name substitutions to avoid conflicts with Python syntax.""" out = name.replace("-", "_") if out == "True": out = "AlwaysTrue" elif out == "False": out = "AlwaysFalse" elif out == "from": out = "isfrom" return out
e5bb85465f8a599f45ff12bf48247beab123472e
68,101
import time def microseconds(): """ Get the time in microseconds """ return time.time() * 1000000.0
82d9258a8b0f68295b9ba2c86a9165309c19ae90
68,102
def _compute_input_padding(size, bcount, bsize, boffset, bstride): """Computes the padding for the operation. :param size: `[SZH, SZW]` list-like of ints, size of image :param bcount: `[BCH, BCW]` list of ints :param bsize: :param boffset: :param bstride: :returns: `pad_h, pad_w` for _pad_inputs function...
bce6ed06406f0d259d029c745e3c9f5ff015959e
68,103
from typing import Union import string def _strip_unwanted_chars(price: Union[int, str]) -> str: """Returns price text with all unnecessary chars stripped (nonnumeric etc). Examples: "100" should return "100" "100 yen" should return "100" "10,000" should return "10000" Args: price: The raw val...
18679bbd7e53fcea7cadd3343fc82a3dd875f8af
68,104
import functools def deprecated(useInstead): """Decorator that warns that different function should be used instead.""" def decorate(f): @functools.wraps(f) def decorated(*args, **kwargs): msg = ('Function {} has been deprecated. Use {} instead' .format(f.__name...
1f1872c6744db7601e5dd91056e385098ae37e40
68,105
def select_to_dict(obj: Select) -> dict: """ Serialize SQLAlchemy Select to dict :param obj: :return: """ obj_dict = {} for column in obj.__table__.columns.keys(): val = getattr(obj, column) if isinstance(val, Decimal): val = float(val) obj_dict[column] =...
f51245709c377d1d1317f4c49fafd43f8ad0569c
68,106
import numpy def merge_qcdata_res(qcdata, output, res): """ Merges QC Data at resolutions other than HH (DD, WW, MM, YY) :param qcdata: QC Data array :type qcdata: numpy.recarray :param output: Output Data array :type output: numpy.recarray :param res: temporal resolution :type re...
675e77aec46160884af3cd0884f2afe5545fb91f
68,107
def project_array(fine, coarse): """Projects a coarse array on a finer array. The shapes of the two must be evenly divisible. Mesh must be uniform (i.e., have equal volumes/weights) Tested on: * OpenMC fission rates 285 -> 95 * OpenMC fission rates 190 -> 95 * Arbitrary floating point matrix 4x4 -> 2x2 Par...
84b4476519ff13b629b341d0c3c2048f5975a4fa
68,108
def get_balance(user_id, server_id): """ Returns the users balance in the stonks game :param user_id: the users unique ID :param server_id: the servers unique ID :return: the floating value of the users balance """ user = collection.find_one({"_id": user_id}) balance = user['cash_balance...
3c36f40a4a6c11bc3a1e2aa14ea1ad54c7e0b075
68,109
def single_source_dijkstra_path_length(G, source, weight_function, paths=None, disjunction=sum): """Uses (a custom) Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph source : node Starting node for path. weight_function: function Fun...
35644cee6a8bb43553cec5f4bdfe12fd9d6a9609
68,110
def get_log_data(): """ :return: """ log_data_list = list() conn = connect() log_data = RBX.table("Logs").run(conn) for log_item in log_data: log_data_list.append(log_item) return log_data_list
30b8ea4cb0d75c8b874cc7aaaea271309bf50c65
68,111
import torch def get_relative_position_matrix(length, max_relative_position, direction, offset=True): """ Generate matrix of relative positions between inputs ([..., length]). :param length: :param max_relative_position: :param direction: :return: """ range_vec = torch.arange(length).l...
32ed90e3a8a29d36e4b57a3bcfd066c15985adaf
68,112
def isDocx(filename): """确定上传文件为docx""" return '.' in filename and filename.rsplit('.', 1)[1] in {"docx",}
547236d821e0ecb3bb59a2ea00623adbf7d5c6df
68,113
def extract_features_by_words(text): """ Extract the features from words. :param text: The text to operate on :return: A list of features objects """ features_by_words = [] words = text.split() word_num = 0 for word in words: word_features = features_detection(word) ...
4862a22fa77ab502810c1d17928195eb809eb0df
68,115
import math def formatRA(ra): """Format the ra given in degrees into hours, minutes, seconds.""" if ra is None: return None return formatRA_rad((math.pi/180)*ra)
27fb120f8097ffd0ca9eb4d402dde616ab414976
68,116
import warnings def update(data): """Update the data in place to remove deprecated properties. Args: data (dict): dictionary to be updated Returns: True if data was changed, False otherwise """ updated = False if 'include' in data: msg = ("included configuration files...
2e604cde4455bb1ab784651798fb3be0cd3733db
68,117
def getHtmlItems(templateName, identifier): """ :param templateName: :param identifier: :return: >>> getHtmlItems("sample", "mojeTestId") {'caption': 'Moje Caption', 'shortDescription': 'Moje shortDescription', 'description': 'Moje dDescription'} """ result = {} divContent = getHtm...
e464daa4978c69440c4a459d41c163dca2a5a072
68,118
def find(compiler_spec, scope=None, init_config=True): """Return specs of available compilers that match the supplied compiler spec. Return an empty list if nothing found.""" return [c for c in all_compiler_specs(scope, init_config) if c.satisfies(compiler_spec)]
df2fe11e3674b3ec86bf9aeb25688f4d90bd7892
68,119
def _get_shape(tensor): """Like get_shape().as_list(), but explicitly queries the shape of a tensor if necessary to ensure that the returned value contains no unknown value.""" shape = tensor.get_shape().as_list() none_indices = [i for i, d in enumerate(shape) if d is None] if none_indices: # Query the s...
913ee17456866543bc337bcbaaa6680a9bf5399c
68,120
def add_colorbar(im, aspect=20, pad_fraction=1, **kwargs): """Add a vertical color bar to an image plot.""" divider = axes_grid1.make_axes_locatable(im.axes) width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = plt.gca() ...
3bb2420fb7de41e1c5121c874d51fe32722ccf35
68,122
from typing import List def calc_high_actual_pd(actual_temps_dict: dict, final_high_rcp_list: list) -> List[float]: """ Return a list of percentage differences of high RCP values to actual temperature values """ actual_temps_list = list(actual_temps_dict.values()) high_rcp_...
6aee2dbf9ab62dab7c5b4671a1c1ce64ad4ad2eb
68,123
def import_prediction_regions(bed_file: str, chromosomes: list, chrom_sizes_dictionary: dict, blacklist: str, region_length: int = INPUT_LENGTH, step_size: int = 256): ...
54b378a8075a5f3a4dc71c133df1d25ffe4d7b77
68,124
def fc_net(input_tensor): """Simple function for constructing a fully connected network.""" x = input_tensor for hidden_dim in [40, 40]: x = tf.layers.dense(x, units=hidden_dim) x = tf.nn.relu(x) return tf.layers.dense(x, units=1)
66a3ad3f684a039f0de2ea7b9b2ef34aaf248f8a
68,125
def ResponseFAP_Create(*args): """ Create() -> ResponseFAP ResponseFAP_Create(std::string const & publicID) -> ResponseFAP """ return _DataModel.ResponseFAP_Create(*args)
8ce388841db234a25b53c53967dabd064474b96a
68,127
import math def haversine(lat1, lon1, lat2, lon2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) # haversine formula dl...
24cf45e8805beb64accc4bd0ae3ddf5b3a2fccbe
68,129
def admin_list(page=None): """ 管理员列表 """ if page is None: page = 1 page_data = Admin.query.join( Role ).filter( Role.id == Admin.role_id ).order_by( Admin.addtime.desc() ).paginate(page=page, per_page=8) return render_template("admin/admin_list.html", ...
bc0c80067464a972f67fe95532cd9892348b67a9
68,130
def image_member_delete(context, memb_ref, session=None): """Delete an ImageMember object""" session = session or get_session() memb_ref.update(dict(deleted=True)) memb_ref.save(session=session) return memb_ref
b5d214cf7a1168aaa0108d045803c1b096c52ed7
68,132
from pathlib import Path def readZone(zonePath): """Read zone folder (e.g. '04_teentopia') and return list of Page""" zonePath = Path(zonePath) pages = [ readPage(f) for f in zonePath.iterdir() if not f.name == 'zone.hsp' ] # "links" in zones.hsp not explicitly defined in hsp file zo...
c7cf221fb99765ac77e49def14e29f4d594aab40
68,133
def trigger(hass, config, action): """Listen for state changes based on configuration.""" entity_id = config.get(CONF_ENTITY_ID) below = config.get(CONF_BELOW) above = config.get(CONF_ABOVE) value_template = config.get(CONF_VALUE_TEMPLATE) # pylint: disable=unused-argument def state_automat...
e2b6a4a65c84a266cacd1bdf0fa9927b27698ecd
68,134
def getMagnitudeFactor(filter_band): """ Intermediate computation used by the mfcc function. Compute the band-dependent magnitude factor for the given filter band """ magnitude_factor = 0 if filter_band >= 1 and filter_band <= 14: magnitude_factor = 0.015 elif filter_band >= 15 and ...
2b46157dfbea269cee335240536442d2c7d4b836
68,135
def _default_filter(line): """Default bad header filter. Filters out lines that start with ">From" or "From " (no colon). """ line = line.strip() return (False if line.startswith('>From') or line.startswith('From ') else True)
4867ba376914d7d688038c8471f09405b0a17c24
68,136
def cvGet3D(*args): """cvGet3D(CvArr arr, int idx0, int idx1, int idx2) -> CvScalar""" return _cv.cvGet3D(*args)
904b484d5129c18e0164481e23e2a532e5abfe1a
68,137
def extract_number_missing(data, min_valid, drop_cols=['sample'], group='group'): """ Counts how many valid values exist in each column and filters column labels with more valid values than the minimum threshold defined. :param data: pandas DataFrame with group as rows and protein identifier as column. ...
bd1762374b978a9470cef1fa301bc32b996ad5e7
68,139
from typing import Sequence def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" return [ capability for capability in CAPABILITY_TO_ATTRIB if capability in capabilities ]
d051610f071c31fb03a53a46f20438e5efa8bc56
68,141
import copy def parse_input_json_dict(in_json_dict): """ Parse an input json dictionary into options, example: in_json_dict = { "schema_name": "qc_schema_optimization_input", "schema_version", 1, "keywords": { "coordsys": "tric", "conv": 1.e-7 } ...
bd0bb8651ddac17b5b1fe218a9e493ba93e838bf
68,142
def get_all_users(): """Get all user from Acai game :return user_list: list of all users :rtype: list """ target_url = 'http://acai.berry.ai/api/all_user_ids' data = urllib2.urlopen(target_url).read() user_list = data[1:-1].split(',') for i in range(0, len(user_list)): user_lis...
85d3e13dfc9ee12c167da0dd577b2d141a0fbe60
68,143
import logging def logger(): """Configure logging in console and log file. Returns ------- rl : logger Logging in console (ch) and file (fh). """ # set root logger (rl) rl = logging.getLogger('REEEMLogger') rl.setLevel(logging.INFO) rl.propagate = False # set for...
37b813d1f50f0a9fa4e84a9ca81e96a12ee27067
68,144
def potential_from_kappa_grid(kappa, grid_spacing): """ lensing potential on the convergence grid the computation is performed as a convolution of the Green's function with the convergence map using FFT :param kappa: 2d grid of convergence values :param grid_spacing: pixel size of grid :return:...
602d507e13a5af80452b68a4d2b52c5ad122c48a
68,145
def path_exists(path, fs=None, **kwargs): """ Check if file exists either remote or local. Parameters ---------- path : path to file Returns ------- exists : bool """ fs = fs or fs_from_path(path, **kwargs) fs.invalidate_cache(path=path) return fs.exists(path)
e1c95c556b28533eb3144814f1bee52428263abf
68,146
def line_in_triangles_3d( line_point: np.ndarray, line_direction: np.ndarray, triangles: np.ndarray ): """Determine if a line goes through any of a set of triangles. For example, this could be used to determine if a click was in a triangle of a mesh. Parameters ---------- line_point : np.n...
3a6e747f3bfaa0af820df89ee9a1ce79fdf97624
68,147
import numpy def truncate_curve(x, y, length): """Truncate a curve to target a given length.""" # Compute cumulative sum of the segments length. segment_lengths = numpy.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2) cumul = numpy.cumsum(numpy.insert(segment_lengths, 0, 0.0)) # Find the index of t...
f64cca96b8646dc94a3dbc745241ef0e427a8c2a
68,148
import torch def dot(input_, other): """Wrapper of `torch.dot`. Parameters ---------- input_ : DTensor The first operand. other : DTensor The second operand. """ if input_._data.ndim == 1 and other._data.ndim == 1: return torch.dot(input_._data, other._data) re...
e02d6215764f88263912d69720acb6a8a103ed49
68,149
from django.contrib.syndication.views import feed def blog_post_feed(request, format, **kwargs): """ Blog posts feeds - handle difference between Django 1.3 and 1.4 """ blog_feed_dict = {"rss": PostsRSS, "atom": PostsAtom} try: blog_feed_dict[format] except KeyError: raise Http...
e98f85eb703a54946618faf38e6619eb759fb8a7
68,150
from datetime import datetime def in_curation_window(comment, max_age=561600, min_age=800): """ Based on the max_age (seconds) checks the post is votable or not. """ if isinstance(max_age, str): max_age = int(max_age) if isinstance(min_age, str): min_age = int(min_age) create...
09c182676e889eec0fc356bbbcd831b01b368ad0
68,151
def get_tagged_from_server(input_text, caseless=False): """ Get pos tagged and ner from the CoreNLP Server 从CoreNLP服务器获取pos标记和ner 疑问:CoreNLP服务器? 参数:input_text:字符串形式的输入文本 :param input_text: input text as a string 返回值:带有pos和ne标签的标记化文本 :return: tokenized text with pos and ne tags >>> ge...
15a4eff7735c14f909fb323d241e99bb06b4c4a6
68,152
def get_date(email): """ Takes an email Message object and attempts to parse a date according to the rules in RFC 2822. If successful, returns a string of the datetime in UTC and in ISO 8601 format. Otherwise, returns None. """ date_str = email.get('Date', '') try: email_datetime = e...
d987d62c52c0240b76c46b1939bc77774c64cca3
68,153
def get_observers(): """Makes sure _observers cannot be modified.""" return tuple(_observers)
2da299990eed46a23382944200fb0e939c435031
68,154
import tempfile def xlsx_response(filename, table, max_width=118, max_height=90): """Return a Microsoft Excel 2007+ file of the given table as an HttpResponse. Args: filename: the name of the downloaded file. The extension will be '.xlsx'. This parameter is inserted directly to the resp...
fcdcc7bd5a4d1fda0398763712a6c3d8ab79db10
68,155
def format_pIC50(compound: CompoundAnalysis) -> str: """ Format the compound's experimental pIC50 if present, or TBD if not """ experimental_data = compound.metadata.experimental_data if "pIC50" in experimental_data: return experimental_data["pIC50"] else: return "TBD"
69312c9cdfde4c9765b94f9253e5afb7b871ac26
68,156
def parse_starlog(path_to_log): """Parse star logfile into a dict. Args: path_to_log: filepath containing the star run log Returns: dict that contains metrics from star log """ qc_dict = {} with open(path_to_log) as f: for line in f: if "|" in line: ...
ced4f91846a4c658c1801eeeb75430cdecafb32d
68,157
def make_p_M_uniform(p_M_min=5., p_M_max=8.5, M_step=0.1, n_M=None): """ Creates a uniform PDF between the minimum and maximum magnitudes given by p_M_min and p_M_max. Parameters ---------- p_M_min : Minimum magnitude. p_M_max : Maximum magnitude. M_step : Width of steps in interpolatio...
2e5ba47e8af5de1b8d62d8a4b338ec130bdafef1
68,158
def generate_field_radial_bend( reference_image, body_mask, reference_point, axis_of_rotation=[0, 0, -1], scale=0.1, mask_bend_from_reference_point=("z", "inf"), gaussian_smooth=5, ): """ Generates a synthetic field characterised by radial bending. Typically, this field would be ...
ab4cf885b79df08fc1e3448ad4a1682d110a495c
68,159
def get_distance_metrics(): """Gets a list of distance-based metrics. Returns: list[Metric]: A list of metrics. """ return [HausdorffDistance(), AverageDistance(), MahalanobisDistance(), VariationOfInformation(), GlobalConsistencyError(), ...
d71d263d3d400159b5fe4d92beb010734ab40a5a
68,160
import pandas def age_group(age: int, bin_count: int = 10, age_cutoff: int = 90) -> str: """ Categorical age group given a specific age, codified into a function to enforce consistency. """ if pandas.isna(age) or age < 0: return None bin_size = age_cutoff // bin_count + 1 if age >= ag...
d37297a296fb90f6c33e406300fae7f2855fb578
68,161
import sqlite3 def connect_db(): """Connectts to the specific database.""" return sqlite3.connect(app.config['DATABASE'])
d92187d40f71dc4d4af2866e5877633d7dc34976
68,162
def get_message(): """ Get message by message_id :param message_id :return: """ message_id = request.args.get('message_id') message = Message.query.get(message_id) if not message: return jsonify({ 'error': 'No message found' }) return jsonify({ ...
8ac4ae494c3c3b512c0b19af58db8b0a8a9f131a
68,163
from datetime import datetime def repo_update(request): """ Get the updates for the repo page. """ if 'last_request' not in request.GET or 'limit' not in request.GET or 'repo_id' not in request.GET: return HttpResponseBadRequest('Missing parameters') this_request = TimeUtils.get_local_tim...
bc99425fcf6beeb85a42d74ad9a09e7992ca185a
68,164
def parse_OWS(string, pos): """ Parse optional whitespace from ``string`` at the given position. Return the new position. The whitespace itself isn't returned because it isn't significant. """ # There's always a match, possibly empty, whose content doesn't matter. match = _OWS_re.match(st...
4ab4eb1298406545288af6b807624771b90f92d1
68,165
def addBinaryB(a, b): """ :type a: str :type b: str :rtype: str """ a_decimal=0 b_decimal=0 for i,num in enumerate(a): if num == '1': a_decimal+=pow(2,len(a)-i-1) for x,num in enumerate(b): if num == '1': b_decimal+=pow(2,len(b)-x-1) result=a_decimal+b_decimal if result == 0: return "0" last="...
099167e14b4889ce0c08e5934acd2124de91145c
68,166
def get_universe_id_from_script(universe_script): """ Get the id of a universe given the universe script """ return int(universe_script.split('.')[0].split('_')[1])
a714d1de25f4972c1cccd6c70453d01e2938af2b
68,167
def cut_fiducial(X, ids, isMC, xcorr_flow=False): """ Basic fiducial (kinematic) selections. Args: X: Number of events N x Number of variables D ids: Variable name array (D) isMC: is it MC or Data Returns: ind: Passing indices (N) """ if isMC ==...
53ac7c70f059f9faae4debce3687a32b094a53a8
68,169
def Q_p_NH2D(Tex=5*u.K): """ It returns the particion function for para-NH2D with an excitation temperature. It uses the first 30-energy levels. """ if Tex.size == 1: return np.sum(Q_p_NH2D_i(p_full_index, Tex=Tex)) else: Q_p_NH2D_all = np.zeros_like(Tex.value) for i...
944ecdbc682321982608aaf61155167515f47111
68,173