content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import typing import random import itertools def get_word(count: typing.Union[int, typing.Tuple[int]] = 1, # pylint: disable=dangerous-default-value sep: str = ' ', func: typing.Optional[typing.Union[str, typing.Callable[[str], str]]] = None, args: typing.Tuple[str] = (), kwarg...
3d5e1f82a4f32eae88016c0a89e9295b80d382e5
24,933
def chrom_exp_cusp(toas, freqs, log10_Amp=-7, sign_param=-1.0, t0=54000, log10_tau=1.7, idx=2): """ Chromatic exponential-cusp delay term in TOAs. :param t0: time of exponential minimum [MJD] :param tau: 1/e time of exponential [s] :param log10_Amp: amplitude of cusp :param ...
4075901c5dcbe10ad8554835c20a0a22d29f1af7
24,936
def powerspectrum_t(flist, mMax=30, rbins=50, paramname=None, parallel=True, spacing='linear'): """ Calculates the power spectrum along the angular direction for a whole simulation (see powerspectrum). Loops through snapshots in a simulation, in parallel. Uses the same radial ...
e2dd0ab1fa06a111530350e2ab2da119607dc9eb
24,937
def score(scores, main_channel, whiten_filter): """ Whiten scores using whitening filter Parameters ---------- scores: np.array (n_data, n_features, n_neigh) n_data is the number of spikes n_feature is the number features n_neigh is the number of neighboring channels conside...
b416bd38a874f6c8ee3b26b8fec35a19b0604de0
24,938
def make_title(raw_input): """Capitalize and strip""" return raw_input.title().strip()
517977638d72a8e5c8026147246739231be6258f
24,939
def perform(target, write_function=None): """ Perform an HTTP request against a given target gathering some basic timing and content size values. """ fnc = write_function or (lambda x: None) assert target connection = pycurl.Curl() connection.setopt(pycurl.URL, target) connection.s...
0cecdb6bc43acd80ebca701b4607b2013b612d93
24,940
import typing def merge_property_into_method( l: Signature, r: typing.Tuple[Metadata, OutputType] ) -> Signature: """ Merges a property into a method by just using method """ return l
ae626fece9dbd36567f0b8c79cddfbe58c0a2cb4
24,942
def _serve_archive(content_hash, file_name, mime_type): """Serve a file from the archive or by generating an external URL.""" url = archive.generate_url(content_hash, file_name=file_name, mime_type=mime_type) if url is not None: return re...
be30f5585efd229518671b99c1560d44510db2c6
24,944
def preprocess(path ,scale = 3): """ This method prepares labels and downscaled image given path of image and scale. Modcrop is used on the image label to ensure length and width of image is divisible by scale. Inputs: path: the image directory path scale: scale to ...
6b02b81dca775ad9e614b8d285d3784aec433ca2
24,945
import math def get_goal_sample_rate(start, goal): """Modifie la probabilité d'obtenir directement le but comme point selon la distance entre le départ et le but. Utile pour la précision et les performances.""" try : dx = goal[0]-start[0] dy = goal[1]-start[1] d = math.sqrt(dx * d...
a48ad7adba534455a149142cfeae9c47e3a25677
24,946
import warnings def sample_cov(prices, returns_data=False, frequency=252, log_returns=False, **kwargs): """ Calculate the annualised sample covariance matrix of (daily) asset returns. :param prices: adjusted closing prices of the asset, each row is a date and each column is a ticker/id....
3e60ef20b976bf35d9ee818c27dfb7b877fe1f3f
24,947
from typing import Dict def read_prev_timings(junit_report_path: str) -> Dict[str, float]: """Read the JUnit XML report in `junit_report_path` and returns its timings grouped by class name. """ tree = ET.parse(junit_report_path) if tree is None: pytest.exit(f"Could not find timings in JUni...
8c796845289fc08ffb815d649c732fdd1ae626b3
24,949
def update_model(): """ Updates a model """ data = request.get_json() params = data.get('params', {'model_id': 1}) entry = Model.objects(model_id=params.model_id).first() if not entry: return {'error': ModelNotFoundError()} entry.update(**params) return entry.to_json()
8ba13df354c21e72045d319b3c47d8ef4e291182
24,950
def SmartConnect(protocol='https', host='localhost', port=443, user='root', pwd='', service="hostd", path="/sdk", preferredApiVersions=None, keyFile=None, certFile=Non...
19fafca3767b221d0b35c8377c0b367c097a2c8c
24,951
def _pseudoArrayFromScalars(scalarvalues, type): """Wrap a scalar in a buffer so it can be used as an array""" arr = _bufferPool.getBuffer() arr._check_overflow = 1 newtype = type # _numtypedict[type] arr._strides = (newtype.bytes,) arr._type = newtype arr._itemsize = newtype.bytes arr._...
ac2953eeff6b6549ef633de2728d72220e61bd76
24,952
def triangulate_ellipse(corners, num_segments=100): """Determines the triangulation of a path. The resulting `offsets` can multiplied by a `width` scalar and be added to the resulting `centers` to generate the vertices of the triangles for the triangulation, i.e. `vertices = centers + width*offsets`. Us...
feae8b79020c612185dcdcbd9f3d3b9bd897b11b
24,953
def is_dbenv_loaded(): """ Return True of the dbenv was already loaded (with a call to load_dbenv), False otherwise. """ return settings.LOAD_DBENV_CALLED
a4dc5c6b69e457aedf31f7729dd6bab0a75aaa07
24,954
def parse_python_settings_for_dmlab2d( lab2d_settings: config_dict.ConfigDict) -> Settings: """Flatten lab2d_settings into Lua-friendly properties.""" # Since config_dicts disallow "." in keys, we must use a different character, # "$", in our config and then convert it to "." here. This is particularly # im...
5cdf1d1a9a6b82e23f0dffc022bbc0a352f65766
24,955
import IPython import re def get_new_name(x: str) -> str: """ Obtains a new name for the given site. Args: x: The original name. Returns: The new name. """ y = x.lower() if y == "cervical": return "cervical_spine" m = re.match(r"^([lr])\s+(.+)$", y) i...
0481c54c43ddb58758513bd654b7d5b1a7539761
24,956
from typing import Dict from typing import Any def u2f_from_dict(data: Dict[str, Any]) -> U2F: """ Create an U2F instance from a dict. :param data: Credential parameters from database """ return U2F.from_dict(data)
53d90b86fc0a7fd44938b7eb2f9d9f178161642f
24,957
def filterForDoxygen (contents): """ filterForDoxygen(contents) -> contents Massage the content of a python file to better suit Doxygen's expectations. """ contents = filterContents(contents) contents = filterDocStrings(contents) return contents
c216328bed4d9af656dfd61477add1a15ee34bd6
24,959
from typing import List from typing import Callable def calculate_quantum_volume( *, num_qubits: int, depth: int, num_circuits: int, seed: int, device: cirq.google.xmon_device.XmonDevice, samplers: List[cirq.Sampler], compiler: Callable[[cirq.Circuit], c...
da1f2eb072f5d91ec99be8fa6a447c2661aabb6d
24,960
def get_key(item, key_length): """ key + value = item number of words of key = key_length function returns key """ word = item.strip().split() if key_length == 0: # fix return item elif len(word) == key_length: return item else: return ' '.join(word[0:key_le...
6407d98d62a4d83bf577e82be696b6aee1f6d2e8
24,962
from typing import Tuple def identity(shape: Tuple[int, ...], gain: float = 1) -> JaxArray: """Returns the identity matrix. This initializer was proposed in `A Simple Way to Initialize Recurrent Networks of Rectified Linear Units <https://arxiv.org/abs/1504.00941>`_. Args: shape: Shape of the...
59fb436485a04b5861bfdcfbe9bf36f4084aeb3d
24,963
from typing import Optional from typing import Dict def pyreq_nlu_trytrain(httpreq_handler: HTTPRequestHandler, project_id: int, locale: str) -> Optional[Dict]: """ Get try-annotation on utterance with latest run-time NLU model for a Mix project and locale, by sending requests to Mix API endpoint with Pyt...
7103fae177535f5c7d37ce183e9d828ebdca7b7a
24,964
from typing import Tuple def month_boundaries(month: int, year: int) -> Tuple[datetime_.datetime, datetime_.datetime]: """ Return the boundary datetimes of a given month. """ start_date = datetime_.date(year, month, 1) end_date = start_date + relativedelta(months=1) return (midnight(start_date...
f727ae0d8f28bd75f0a326305d172ea45ec29982
24,965
def calculate_Hubble_flow_velocity_from_cMpc(cMpc, cosmology="Planck15"): """ Calculates the Hubble flow recession velocity from comoving distance Parameters ---------- cMpc : array-like, shape (N, ) The distance in units of comoving megaparsecs. Must be 1D or scalar. cosmology : strin...
994722494de5ae918c3f1855b1b58fec21849f7e
24,966
def join_items( *items, separator="\n", description_mode=None, start="", end="", newlines=1 ): """ joins items using separator, ending with end and newlines Args: *items - the things to join separator - what seperates items description_mode - what mode to use for description...
0df5b55f10d73600ea2f55b0e9df86c17622e779
24,967
def JacobianSpace(Slist, thetalist): """Computes the space Jacobian for an open chain robot :param Slist: The joint screw axes in the space frame when the manipulator is at the home position, in the format of a matrix with axes as the columns :param thetalist: A list of j...
e0f3fba57b2d1595a59b708a452fd2b57c6011e7
24,968
async def delete_bank(org_id: str, bank_id:str, user: users_schemas.User = Depends(is_authenticated), db:Session = Depends(get_db)): """delete a given bank of id bank_id. Args: bank_id: a unique identifier of the bank object. user: authenticates that the user is a logged ...
537159c6c19c6bb1dde02eec13f5c55932f9d6ee
24,969
from typing import Union from typing import Iterable from typing import Any def label_encode( df: pd.DataFrame, column_names: Union[str, Iterable[str], Any] ) -> pd.DataFrame: """ Convert labels into numerical data. This method will create a new column with the string "_enc" appended after the or...
62d937dc8bb02db8a099a5647bf0673005489605
24,970
def get_server_now_with_delta_str(timedelta): """Get the server now date string with delta""" server_now_with_delta = get_server_now_with_delta(timedelta) result = server_now_with_delta.strftime(DATE_FORMAT_NAMEX_SEARCH) return result
f555ed28ec98f9edfa62d7f52627ea06cad9513b
24,972
def GetPrimaryKeyFromURI(uri): """ example: GetPrimaryKeyFromURI(u'mujin:/\u691c\u8a3c\u52d5\u4f5c1_121122.mujin.dae') returns u'%E6%A4%9C%E8%A8%BC%E5%8B%95%E4%BD%9C1_121122' """ return uriutils.GetPrimaryKeyFromURI(uri, fragmentSeparator=uriutils.FRAGMENT_SEPARATOR_AT, primaryKeySeparator=...
49a489d02af3195ea7ed0a7f41b9fbb19bb16407
24,973
import math def normalize(score, alpha=15): """ Normalize the score to be between -1 and 1 using an alpha that approximates the max expected value """ norm_score = score/math.sqrt((score*score) + alpha) if norm_score < -1.0: return -1.0 elif norm_score > 1.0: return 1.0 else: return...
ec158416a4199d17948986dfb3f8d659d82e07b7
24,974
from datetime import datetime import pytz def get_timestamp(request): """ hhs_oauth_server.request_logging.RequestTimeLoggingMiddleware adds request._logging_start_dt we grab it or set a timestamp and return it. """ if not hasattr(request, '_logging_start_dt'): return datetime.n...
f3117a66ebfde0b1dc48591e0665c3d7120826fd
24,975
from typing import Optional from typing import List def human_size(bytes: int | float, units: Optional[List[str]] = None) -> str: """ Convert bytes into a more human-friendly format :param bytes: int Number of bytes :param units: Optional[List[str]] units used :return: str ...
9b652f0a09024c22dcefa5909c17f7b14d0183f4
24,976
def ray_casting_2d(p: Point, poly: Poly) -> bool: """Implements ray-casting algorithm to check if a point p is inside a (closed) polygon poly""" intersections = [int(rayintersectseg(p, edge)) for edge in poly.edges] return _odd(sum(intersections))
149f797bdcecce483cf87ed012fe7a21370c2ab6
24,977
def average_price(offers): """Returns the average price of a set of items. The first item is ignored as this is hopefully underpriced. The last item is ignored as it is often greatly overpriced. IMPORTANT: It is important to only trade items with are represented on the market in great numbers. This...
4849996d13e4c00d845f5fb6a5a150397c9b84f0
24,978
def get_train_data(): """get all the train data from some paths Returns: X: Input data Y_: Compare data """ TrainExamples = [8, 9, 10, 11, 12, 14] # from path set_22 to set_35 path = PATH_SIMPLE + str(5) + '/' X, Y_ = generate(path, isNormalize=True) maxvalue = (get_ima...
01517db3cb4b5987b895c2b435771c745837bf65
24,980
def effective_dimension_vector(emb, normalize=False, is_cov=False): """Effective dimensionality of a set of points in space. Effection dimensionality is the number of orthogonal dimensions needed to capture the overall correlational structure of data. See Del Giudice, M. (2020). Effective Dimensionality: A...
5d4247b92216bc9e77eabbd35746c06fec22161c
24,981
def getProductMinInventory(db, productID): """ Gives back the minimum inventory for a given product :param db: database pointer :param productID: int :return: int """ # make the query and receive a single tuple (first() allows us to do this) result = db.session.query(Product).filter(Prod...
032c95685e1c578f9251d269899f4ee04d93e326
24,982
import re def read_config6(section, option, filename='', verbosity=None): #format result: {aaa:[bbb, ccc], ddd:[eee, fff], ggg:[hhh, qqq], xxx:[yyy:zzz]} """ option: section, option, filename='' format result: {aaa:bbb, ccc:ddd, eee:fff, ggg:hhh, qqq:xxx, yyy:zzz} """ fil...
e80c80b2033b10c03c7ee0b2a5e25c5739777f3f
24,983
def bboxes_iou(boxes1, boxes2): """ boxes: [xmin, ymin, xmax, ymax] format coordinates. """ boxes1 = np.array(boxes1) boxes2 = np.array(boxes2) boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1]) boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., ...
ca2083dd0138a6bd1ee741fc58739340dc1bac61
24,984
import torch import collections def predict_all_task(trained_model_path, config, subject_specific): """Predict. Parameters ---------- model_path : str Description of parameter `model_path`. config : dict A dictionary of hyper-parameters used in the network. Returns ------...
ae179d41cff63b52c9836f7bbb25675618e1aa86
24,986
def hjorth(X): """ Compute Hjorth mobility and complexity of a time series. Notes ----- To speed up, it is recommended to compute D before calling this function because D may also be used by other functions whereas computing it here again will slow down. Parameters ---------- X : a...
8ca56b45e2c5af0d28d34c181cc1b6bc915e507d
24,987
def check_and_set_owner(func): """ Decorator that applies to functions expecting the "owner" name as a second argument. It will check if a user exists with this name and if so add to the request instance a member variable called owner_user pointing to the User instance corresponding to the owner. If the...
9c5ba9d0b0bb1058ddf830da5fc59df3724b2c0e
24,988
def schedule(self: Client) -> ScheduleProxy: """Delegates to a :py:class:`mcipc.rcon.je.commands.schedule.ScheduleProxy` """ return ScheduleProxy(self, 'schedule')
a8402088fa9fa697e988b2bdb8f185b14f012873
24,989
def check_permission(permission): """Returns true if the user has the given permission.""" if 'permissions' not in flask.session: return False # Admins always have access to everything. if Permissions.ADMIN in flask.session['permissions']: return True # Otherwise check if the permission is present in ...
b4c45b15a68a07140c70b3f46001f0ca6a737ea5
24,990
def Energy_value (x): """ Energy of an input signal """ y = np.sum(x**2) return y
cf2c650c20f2a7dac8bf35db21f25b8af428404e
24,993
import re def get_int(): """Read a line of text from standard input and return the equivalent int.""" while True: s = get_string(); if s is None: return None if re.search(r"^[+-]?\d+$", s): try: i = int(s, 10) if type(i) is int: #...
e6f4e1c49f4b4bc0306af50283728f016db524d7
24,994
def create_save_featvec_homogenous_time(yourpath, times, intensities, filelabel, version=0, save=True): """Produces the feature vectors for each light curve and saves them all into a single fits file. requires all light curves on the same time axis parameters: * yourpath = folder you want the file s...
29250aad4cfa1aa5bbd89b880f93a7a70a775dfb
24,995
import asyncio async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Eaton xComfort Bridge from a config entry.""" ip_address = entry.data.get(CONF_IP_ADDRESS) auth_key = entry.data.get("authkey") bridge = Bridge(ip_address, auth_key) # bridge.logger = lambda x: _LOGGER...
b24b78054c1e8236b5a29fed7287db4150f9deb0
24,996
def _cpu_string(platform_type, settings): """Generates a <platform>_<arch> string for the current target based on the given parameters.""" if platform_type == "ios": ios_cpus = settings["//command_line_option:ios_multi_cpus"] if ios_cpus: return "ios_{}".format(ios_cpus[0]) c...
7cf483c45bb209a9e3e0775538934945324281a7
24,997
def Check2DBounds(atomMatch,mol,pcophore): """ checks to see if a particular mapping of features onto a molecule satisfies a pharmacophore's 2D restrictions >>> activeFeats = [ChemicalFeatures.FreeChemicalFeature('Acceptor', Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Dono...
d119645de037eeaf536e290766d4dacf9c2e2f08
24,998
def get_sdk_dir(fips_dir) : """return the platform-specific SDK dir""" return util.get_workspace_dir(fips_dir) + '/fips-sdks/' + util.get_host_platform()
f3fcf05a8dd1ae0f14431a84ae570c56dd900c69
24,999
from typing import Any def suggested_params(**kwargs: Any) -> transaction.SuggestedParams: """Return the suggested params from the algod client. Set the provided attributes in ``kwargs`` in the suggested parameters. """ params = _algod_client().suggested_params() for key, value in kwargs.items()...
678f207bdd1152f6a8cb98e9c4964dd43b9dd761
25,000
def norm_rl(df): """ Normalizes read length dependent features """ rl_feat = ["US_r", "US_a", "DS_a", "DS_r", "UXO_r", "UXO_a", "DXO_r", "DXO_a", "UMO_r", "UMO_a", "DMO_r", "DMO_a", "MO_r", "MO_a", "XO_r", "XO_a"] rl = df['MO_r'].max() df[rl_feat] = df[rl_feat]/rl return df
0f7c36a447f04bc647773e99a83f59f3789849d4
25,001
import json def sendRequest(self, channel, params=None): """发送请求""" # 生成请求 d = {} d['event'] = 'addChannel' d['channel'] = channel # 如果有参数,在参数字典中加上api_key和签名字段 if params is not None: params['api_key'] = apiKey params['sign'] = buildMySign(params, secreteKey) d['par...
ddaae8800e0fbcf69ce1e15abba4725ef70eadfa
25,002
def altCase(text: str): """ Returns an Alternate Casing of the Text """ return "".join( [ words.upper() if index % 2 else words.lower() for index, words in enumerate(text) ] )
1d8c25f9b81e360c254ac10ce105f99ca890a87c
25,003
def makeObjectArray(elem, graph, num, tag=sobject_array): """ Create an object array of num objects based upon elem, which becomes the first child of the new object array This function also can create a delay when passed a different tag """ p = elem.getparent() objarray = etree.Element(etree...
5ef896b6514dc0d5ce00bbf0322c9e775fb4a152
25,004
def convert_mg_l_to_mymol_kg(o2, rho_0=1025): """Convert oxygen concentrations in ml/l to mymol/kg.""" converted = o2 * 1/32000 * rho_0/1000 * 1e6 converted.attrs["units"] = "$\mu mol/kg$" return converted
5925cf1f5629a0875bdc777bc3f142b9a664a144
25,006
import xml from typing import List def parse_defines(root: xml.etree.ElementTree.Element, component_id: str) -> List[str]: """Parse pre-processor definitions for a component. Schema: <defines> <define name="EXAMPLE" value="1"/> <define name="OTHER"/> </de...
0f2b06581d89f9be3ff4d733e1db9b56e951cc89
25,007
def make_f_beta(beta): """Create a f beta function Parameters ---------- beta : float The beta to use where a beta of 1 is the f1-score or F-measure Returns ------- function A function to compute the f_beta score """ beta_2 = beta**2 coeff = (1 + beta_2) def...
f0e6993ac956171c58415e1605706c453d3e6d61
25,008
def _autohint_code(f, script): """Return 'not-hinted' if we don't hint this, else return the ttfautohint code, which might be None if ttfautohint doesn't support the script. Note that LGC and MONO return None.""" if script == 'no-script': return script if not script: script = noto_fonts.script_key_to...
4341098cbd9581ef989a65d352493fe28c7ddbd7
25,009
def infostring(message=""): """Info log-string. I normally use this at the end of tasks. Args: message(str): A custom message to add. Returns: (str) """ message.rstrip().replace("\n", " ") return tstamp() + "\t## INFO ## " + message + "\n"
14e3012ad9c6e4c7cd10ea885098e31a3eef3ead
25,010
def geo_point_n(arg, n): """Return the Nth point in a single linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry Parameters ---------- arg : geometry n : in...
6da6e0f362fac5e63093e0b93b5cf75b4f05bb5f
25,012
def replace_pasture_scrubland_with_shrubland(df, start_col, end_col): """Merge pasture and scrubland state transitions into 'shrubland'. 1. Remove transitions /between/ scrubland and pasture and vice versa. 2. Check there are no duplicate transitions which would be caused by an identical set of cond...
9f3102a157e8fbaad1cca3631a117ab45470bae3
25,013
from typing import List def get_storage_backend_descriptions() -> List[dict]: """ Returns: """ result = list() for backend in SUPPORTED_STORAGE_BACKENDS: result.append(get_storage_backend(backend).metadata) return result
2ec097a7c70788da270849332f845316435ac746
25,014
from typing import Tuple def get_business_with_most_location() -> Tuple: """ Fetches LA API and returns the business with most locations from first page :return Tuple: business name and number of locations """ response = _fetch_businesses_from_la_api() business_to_number_of_location = dict...
ee0d7f432387e4587f615bd294cc8c8276d5baf1
25,015
from typing import AbstractSet def degrees_to_polynomial(degrees: AbstractSet[int]) -> Poly: """ For each degree in a set, create the polynomial with those terms having coefficient 1 (and all other terms zero), e.g.: {0, 2, 5} -> x**5 + x**2 + 1 """ degrees_dict = dict.fromkeys(degrees, ...
6c6a27b499f766fae20c2a9cf97b7ae0352e7dc5
25,016
def validate_set_member_filter(filter_vals, vals_type, valid_vals=None): """ Validate filter values that must be of a certain type or found among a set of known values. Args: filter_vals (obj or Set[obj]): Value or values to filter records by. vals_type (type or Tuple[type]): Type(s) of...
a48639473ed0ac303776d50fb4fb09fa45a74d8e
25,017
def update_many(token, checkids, fields, customerid=None): """ Updates a field(s) in multiple existing NodePing checks Accepts a token, a list of checkids, and fields to be updated in a NodePing check. Updates the specified fields for the one check. To update many checks with the same value, use update...
b96d3e29c6335b6bbec357e42a008faa654c72ab
25,018
def main(start, end, csv_name, verbose): """Run script conditioned on user-input.""" print("Collecting Pomological Watercolors {s} throught {e}".format(s=start, e=end)) return get_pomological_data(start=start, end=end, csv_name=csv_name, verbose=verbose)
fd0c619f8e24929e705285bc9330ef1d21825d8b
25,019
import hashlib def _sub_fetch_file(url, md5sum=None): """ Sub-routine of _fetch_file :raises: :exc:`DownloadFailed` """ contents = '' try: fh = urlopen(url) contents = fh.read() if md5sum is not None: filehash = hashlib.md5(contents).hexdigest() ...
0a92aaa55661469686338631913020a99aab0d8c
25,020
def get_path_to_config(config_name: str) -> str: """Returns path to config dir""" return join(get_run_configs_dir(), config_name)
3a4092c66ea18929d001e7bb4e8b5b90b8a38439
25,021
def scan_db_and_save_table_info(data_source_id, db_connection, schema, table): """Scan the database for table info.""" table_info = get_table_info( {}, schema, table, from_db_conn=True, db_conn=db_connection ) old_table_info = fetch_table_info(data_source_id, schema, table, as_obj=True) data...
050183b68891ff0ab0f45435d29206a5800b704c
25,023
def _get_non_heavy_neighbor_residues(df0, df1, cutoff): """Get neighboring residues for non-heavy atom-based distance.""" non_heavy0 = df0[df0['element'] != 'H'] non_heavy1 = df1[df1['element'] != 'H'] dist = spa.distance.cdist(non_heavy0[['x', 'y', 'z']], non_heavy1[['x', 'y', 'z']]) pairs = np.ar...
b27a341cb1e5e5dd74c881036d7002a107270cd5
25,024
def j0(ctx, x): """Computes the Bessel function `J_0(x)`. See :func:`besselj`.""" return ctx.besselj(0, x)
c2defd50be3feb3791f5be5709e5312d1e232590
25,025
def mysql2df(host, user, password, db_name, tb_name): """ Return mysql table data as pandas DataFrame. :param host: host name :param user: user name :param password: password :param db_name: name of the pydb from where data will be exported :param tb_name: name of the table from where data ...
a4ea75b9fa13e6cb48650e69f5d8216f24fdaf07
25,026
def is_int(number): """ Check if a variable can be cast as an int. @param number: The number to check """ try: x = int(number) return True except: return False
e8e8956942d96956cb34b424b34fb028620f8be1
25,027
import pathlib def get_versions(api_type=DEFAULT_TYPE): """Search for API object module files of api_type. Args: api_type (:obj:`str`, optional): Type of object module to load, must be one of :data:`API_TYPES`. Defaults to: :data:`DEFAULT_TYPE`. Raises: :exc:`exc...
58b2df442901b080db12951ab48991371689e955
25,028
def model_flux(parameters_dict, xfibre, yfibre, wavelength, model_name): """Return n_fibre X n_wavelength array of model flux values.""" parameters_array = parameters_dict_to_array(parameters_dict, wavelength, model_name) return moffat_flux(parameters_array, x...
c3cf75fab6b8b4965aefeebf82d40378bcd1de19
25,029
def new_rnn_layer(cfg, num_layer): """Creates new RNN layer for each parameter depending on whether it is bidirectional LSTM or not. Uses the fast LSTM implementation backed by CuDNN if a GPU is available. Note: The normal LSTMs utilize sigmoid recurrent activations so as to retain compatibility CuDNN...
341ca96549f40c8607e44b9ef353313107a8fb0a
25,030
def firfreqz(h, omegas): """Evaluate frequency response of an FIR filter at discrete frequencies. Parameters h: array_like FIR filter coefficient array for numerator polynomial. e.g. H(z) = 1 + a*z^-1 + b*z^-2 h = [1, a, b] """ hh = np.zeros(omegas.shape, dtype='comple...
4463b1dcd73090d2dedbdd0e78066e4d26d19655
25,031
import pickle def write_np2pickle(output_fp: str, array, timestamps: list) -> bool: """ Convert and save Heimann HTPA NumPy array shaped [frames, height, width] to a pickle file. Parameters ---------- output_fp : str Filepath to destination file, including the file name. array : np.ar...
96956829a41f3955440693f0d754b013a218e941
25,032
from re import S import logging import webbrowser def run( client_id_: str, client_secret_: str, server_class=HTTPServer, handler_class=S, port=8080 ) -> str: """ Generates a Mapillary OAuth url and prints to screen as well as opens it automatically in a browser. Declares some global variables to pull...
152e4c0ae5c20b8e39693478ff5d06c1cc5fa8a5
25,033
def sort_by_rank_change(val): """ Sorter by rank change :param val: node :return: nodes' rank value """ return abs(float(val["rank_change"]))
ff5730e7cc765949dcfcfd4a3da32947ce3a411a
25,034
def ping(): """always 200""" status = 200 return flask.Response(response='\n', status=status, mimetype='application/json')
8407d4ef4188badbeff5ba34868d530b06dd5158
25,035
def add_gtid_ranges_to_executed_set(existing_set, *new_ranges): """Takes in a dict like {"uuid1": [[1, 4], [7, 12]], "uuid2": [[1, 100]]} (as returned by e.g. parse_gtid_range_string) and any number of lists of type [{"server_uuid": "uuid", "start": 1, "end": 3}, ...]. Adds all the ranges in the lists to th...
47a71f2a55054d83092ffbb2119bcab7760f28a8
25,037
def fetch_rgb(img): """for outputing rgb values from click event to the terminal. :param img: input image :type img: cv2 image :return: the rgb list :rtype: list """ rgb_list = [] def click_event(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: red = i...
16ff0359d47eb31a4f9c529740a9813680937e22
25,038
import functools def _get_date_filter_consumer(field): """date.{lt, lte, gt, gte}=<ISO DATE>""" date_filter = make_date_filter(functools.partial(django_date_filter, field_name=field)) def _date_consumer(key, value): if '.' in key and key.split(".")[0] == field: prefix, qualifier = key...
37b7938ef5cebd29d487ec1e53cfc86d13a726d3
25,039
def data_path(fname): """ Gets a path for a given filename. This ensures that relative filenames to data files can be used from all modules. model.json -> .../src/data/model.json """ return join(dirname(realpath(__file__)), fname)
294c91a041227fd9da6d1c9c8063de283281e85e
25,040
def _parse_special_functions(sym: sp.Expr, toplevel: bool = True) -> sp.Expr: """ Recursively checks the symbolic expression for functions which have be to parsed in a special way, such as piecewise functions :param sym: symbolic expressions :param toplevel: as this is called recur...
b560521ceee7cb4db16b808e44b1e538e236c00e
25,041
def get_airflow_config(version, timestamp, major, minor, patch, date, rc): """Return a dict of the configuration for the Pipeline.""" config = dict(AIRFLOW_CONFIG) if version is not None: config['VERSION'] = version else: config['VERSION'] = config['VERSION'].format( major=major, minor=minor, pa...
87c76949dba717b801a8d526306d0274eb193cc5
25,044
def find_duplicates(treeroot, tbl=None): """ Find duplicate files in a directory. """ dup = {} if tbl is None: tbl = {} os.path.walk(treeroot, file_walker, tbl) for k,v in tbl.items(): if len(v) > 1: dup[k] = v return dup
0a959e443b7a4f5c67e57b8fc7bf597fee96065a
25,045
def attach_capping(mol1, mol2): """it is connecting all Nterminals with the desired capping Arguments: mol1 {rdKit mol object} -- first molecule to be connected mol2 {rdKit mol object} -- second molecule to be connected - chosen N-capping Returns: rdKit mol object -- mol1 updated (...
24a80efd94c4a5d4e0ddba478240d7c1b82ad52b
25,046
def gather_point(input, index): """ **Gather Point Layer** Output is obtained by gathering entries of X indexed by `index` and concatenate them together. .. math:: Out = X[Index] .. code-block:: text Given: X = [[1, 2, 3], [3, 4, 5], [5, 6, 7]] ...
dc4298ccf7df084abfc7d63f88ae7edb03af4010
25,047
def _apply_size_dependent_ordering(input_feature, feature_level, block_level, expansion_size, use_explicit_padding, use_native_resize_op): """Applies Size-Dependent-Ordering when resizing feature maps. See https://arxiv.org/abs/1912.01106 ...
c44206246102bbddc706be2cb0644676650c4675
25,048
def distance(s1, s2): """Return the Levenshtein distance between strings a and b.""" if len(s1) < len(s2): return distance(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = xrange(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] ...
d7bb6e7a374349fd65bde621a29ee110402d18aa
25,049
def check_diversity(group, L): """check if group satisfy l-diversity """ SA_values = set() for index in group: str_value = list_to_str(gl_data[index][-1], cmp) SA_values.add(str_value) if len(SA_values) >= L: return True return False
7e87f96a80651608688d86c9c9e921d793fb6a9e
25,050