content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def message_to_request(msg: bytes) -> TestRequest: """Convert message encoded by common.encode_message to request.""" url, case_id, submission_id = common.decode_message(msg.decode("utf-8")) # We assume here, that data is valid, because it was generated by our code, # and not by user... so we skip error...
bc899dbececd523702a9846b11adc8ae87179b77
74,246
def call_cells_mapping(df_reads,df_pool): """Determine count of top barcodes, barcodes prioritized if barcode maps to given pool design """ guide_info_cols = [SGRNA,GENE_SYMBOL,GENE_ID] # map reads df_mapped = (pd.merge(df_reads,df_pool[[PREFIX]],how='left',left_on=BARCODE,right_on=PREFIX) ...
016118584558cc293bfb8c936326f9afb1da69ce
74,247
def nWaveRiseTime(pmax, patm=101e3, csnd=341, lamb=6.8e-8): """ Calculate N-wave rise time Parameters ---------- pmax -- N-wave overpressure amplitude in Pa patm -- atmospheric pressure in Pa csnd -- speed of sound in m/s lamb -- air molecular mean free path in m Returns ------...
cbcae9d8e3ddaeb6daab5a02a722cd7302ebf562
74,248
def remove_whitespace(string): """ Removes leading spaces, trailing spaces, and empty lines from a string. :param string: string to clean up :type string: str :rtype: str """ empty_line = app.LINE_START + app.maybe(app.LINESPACES) + app.NEWLINE trailing_spaces = app.LINESPACES ...
8fadf491fd1e2710708076214566c0d64a236f88
74,249
def _bp_static_url(blueprint): """ builds the absolute url path for a blueprint's static folder """ u = u'%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or '') return u
3d5e68c411c804aec7ca7dbd68633cb75370761a
74,252
def reduce_dims(array, axis=0): """ Reduce array dimensions at given axis Note: If trying on image array please check if expand_dims is used by you during image preprocessing and axis too. Parameters ---------- array: numpy nd array axis : int or tuple of ints Position in the ...
b018bf72ef200e1d30bb6f58f9567a97172b7fc2
74,254
def selectable(label, selected, *args, **kwargs): """ Selectable line. This widget marks the whole line as selectable. To add widgets to `selectable`, simply append them using `orr_same_line`: ```python c.orr_same_line([ c.selectable("Selectable", False), c.text("Extra text"), ...
65b4aea6d59223630a513daffead7f80b074089b
74,257
def mc_maximum_curvature(magnitudes): """ calculates magnitude of completeness using maximum curvature method. citation: ??? :param catalog : pandas.Series :param method : str """ minimum = round(magnitudes.min(), 2) bins = np.arange(start=minimum, stop=10, step=0.1) hist, edg...
7a0194e50e704893ab67455cc2bdf62e79610c19
74,258
def self_advection( grid: grids.Grid, dt: float, physics_specs: physics_specifications.NavierStokesPhysicsSpecs, advection_module: AdvectionModule = modular_advection, **kwargs ) -> ConvectFn: """Convection module based on simultaneous self-advection of velocities.""" advect_fn = advection_modul...
f7d4260401bd317a7d0daf761006992030a8b259
74,259
def create_model(flags, model_name, inp, rng): """Creates model given model_name.""" new_rng, init_rng, drop_rng = jax.random.split(rng, num=3) if model_name == 'gcn': features = [flags.hid_dim, flags.num_classes] model = models.GCN(features, flags.drop_rate, 'PReLU') init = model.init({'params': init...
3d01fe1a1b04276e94e61591a1221e77fbf15ec4
74,260
from datetime import datetime import json def execute(_start_time: str, _stop_time: str, public_key: str = None, tableName: str = "sps30_output"): """ Function that fetches data entries from database. If public_key is provided data is encrypted and then encoded. If no key is provided the data is only enco...
c7a63451f631e634b8c5fba0714445a383229411
74,261
import glob def csv_to_listofDF(path): """ This function gets the path to csv files, reads all the csv files in, converts them to dataframes, adds distric_id as a column and saves them in a list Parameters ------------- path: The path to CSV files """ files = glob.glob(...
db13832373f14a46febff8cef610dfa5937149e5
74,262
def plot_trace( data, var_names=None, coords=None, divergences="bottom", figsize=None, textsize=None, lines=None, combined=False, kde_kwargs=None, hist_kwargs=None, trace_kwargs=None, ): """Plot samples histograms and values. If `divergences` data is available in `sa...
ab9e0e4bab782c0f667acbd0157293cc11b64913
74,265
def ijk_ljk_to_ilk(A, B): """ Faster version of einsum np.einsum('ijk,ljk->ilk', A, B) I.e A.dot(B.T) for every dimension """ res = np.zeros((A.shape[-1], A.shape[0], B.shape[0])) [np.dot(A[:,:,i], B[:,:,i].T, out=res[i,:,:]) for i in range(A.shape[-1])] res = res.swapaxes(0, 2).swapaxes(0,...
caf14f5e820b7fb3e15b9041afbee00ae5b77f1f
74,266
from typing import Callable import re def to_markdown(text: str, docformat: str = 'numpy,google', *, module: pdoc.Module = None, link: Callable[..., str] = None, # Matches markdown code spans not +directly+ within links. # E.g. `code` and [foo is `bar`]() but not [`code...
3ff3580ce254dd0b68ccc48efd9418cfc22c832f
74,267
def view(): """Returns the app in a nice template for use at awesome-panel.org""" pn.config.sizing_mode = "stretch_width" template = pn.template.FastListTemplate( main_max_width="1024px", ) select_continent = pn.widgets.Select(name="Continent", options=CONTINENTS, value=CONTINENTS[0]) ...
e2e9537418c48adcf8ac3ecb24e9f08082f964b0
74,268
from typing import Callable from typing import Mapping from typing import Any def py_function_dict_output( transform: Callable[..., Mapping[str, tf.Tensor]], inp: Any, signature: Mapping[str, tf.TensorSpec], ) -> Mapping[str, tf.Tensor]: """Wrap a user python function returning a dictionary of tensors...
e550bbbb8f360c35e432ac65c388f70e12712c1b
74,269
def Following(field, dist, fromPt=None): """The 'following F [from X] for D' specifier. Specifies 'position', and optionally 'heading', with no dependencies. Allowed forms: following <field> [from <vector>] for <number> If the 'from <vector>' is omitted, the position of ego is used. """ if fromPt is None: ...
db12f71b0e411a0e1144c6537491911c1757180a
74,270
from bs4 import BeautifulSoup def __parseHTML(pages_html: list) -> list: """Function to parse raw HTML filings from EDGAR, and return a structured list of dictionaries with filing information. Arguments: pages_html {list} -- Raw HTML of listings pages. Returns: list -- Struct...
bcfe11de5b8df910ca0d98f3aab8edc99e062ae6
74,271
def hadoop_fs_ls(stdout, stderr, environ, *args): """Implements hadoop fs -ls.""" if mock_hadoop_uses_yarn(environ) and args and args[0] == '-R': path_args = args[1:] recursive = True else: path_args = args recursive = False return _hadoop_fs_ls('ls', stdout, stderr, env...
e348aaa247fee11394e5495579c5275b53dfa5a9
74,272
def get_encoding(header): """File out encoding.""" for line in header: if line.lstrip().startswith("Content-type"): for entry in line.split(";"): if entry.strip().startswith('charset'): return entry.split('=')[1].strip() return ENCODING
40ba875fdb99562a3eb985b877d7334162d87882
74,273
def prune_scalar_nodes(einsum_node): """ Remove the scalar input nodes of a einsum_node. Args: einsum_node: An fused einsum node. Return: both the scalar and the pruned einsum node. """ in_subs, out_subs, _ = parse_einsum_input( (einsum_node.einsum_sub...
a4553937710b31a50a62ea24c2f4664dc5127cbd
74,274
def web_color_to_hex(name: Text) -> int: """Convert the color from web color name to hexadecimal.""" return hex_to_hex(web.colors[name])
7581085b3bbbb8786584d04224730b5304189108
74,275
def analyze_personality(): """個人のテキストをクエリとし,PersonalityInsightsから性格パラメータを取得する. Returns: dict: Big 5のパラメータ. keyは{'ope', 'con', 'ext', 'agr', 'emo'} """ with open('apikey.txt', 'r') as f: api_key = f.read() authenticator = IAMAuthenticator(api_key) personality_insights = Personal...
9ad9da76785d8c82ade354621d0faaade144bf45
74,276
def calcSquareInnerProduct(modes1, modes2): """Returns the square inner product (SIP) of fluctuations [SK02]_. This function returns a single number. .. [SK02] Kundu S, Melton JS, Sorensen DC, Phillips GN: Dynamics of proteins in crystals: comparison of experiment with simple models. Bi...
e0ce8543870f48f505b1fa1d30739362476c720c
74,277
def skip_line_comment(prefix): """ Given comment prefix this function returns a parser that skips line comments. Note that it stops just before the newline character but doesn't consume the newline. Newline is either supposed to be consumed by 'space' parser or picked up manually. """ return...
8bdfb5ca9a565411fba2292465fd0c8e3d352fb3
74,278
import re def awik(phenny, input): """Search for something on Apertium wiki or point another user to a page on Apertium wiki (supports pointing)""" origterm = input.groups()[1] if "->" in origterm or "→" in origterm: return if not origterm: return phenny.say('Perhaps you meant "....
3e07bbdf6e28f14a1dd0d2b639c9487822cf7f31
74,280
def moments(filename,samples): """ M = first moments, counting down from number of samples to 2 MM = second moments """ f = open(filename,'r') lines = f.readlines() T = np.zeros((len(lines),len(str.split(lines[0])))) c = 0 for l in lines: m = str.split(l) for n in ran...
880d737f5c37dbe0096dfaed8cf8103484739b45
74,281
def extract_exchange(raw_data, exchange): """ Extracts flow value and direction for a given exchange. Returns a float or None. """ search_value = JSON_MAPPING[exchange] interconnection = None for datapoint in raw_data: if datapoint['nombre'] == search_value: interconnect...
f429bdf05d5ecaccc8541a57500059a6b16e7f58
74,282
import math def toECEF(latitude, longitude, altitude=0.0): """ Returns ECEF coordinates as x,y,z in meters. latitude: Latitude in radians longitude: Longitude in radians altitude: Altitude in meters, defaults to 0 """ n = N(latitude) cos_lat = math.cos(latitude) return (n+altitude)*cos_lat*math.cos(...
00336400e139e701eeeb9f2aa6ce47ade2696691
74,283
from typing import List import inspect def get_class_names(module) -> List[str]: """Get class names of a module.""" ans = [] for m in inspect.getmembers(module): if inspect.isclass(m[1]): ans.append(m[0]) ans.sort() return ans
4ae36e8823f28d00693eac3d70affe7f0591a745
74,284
def magnetic_form_factor(element, Qmag=0.): """ Read Magnetic form factor table, calculate <j0(|Q|)> Analytical approximation of the magnetic form factor: <j0(|Q|)> = A*exp(-a*s^2) + B*exp(-b*s^2) + C*exp(-c*s^2) + D, where s = sin(theta)/lambda in A-1 See more about the approximatio here: https...
88dfa1ff7bcb8c6665bc516247191c818e7fbc4b
74,285
def init_provider(): """Init provider factory loader.""" return dict(DGI=DGI)
50a89477d4db4628bcc5c1ce151baa8a3c6a83f9
74,286
def batch_global_rigid_transformation(Rs, Js, parent, rotate_base=False): """ Computes absolute joint locations given pose. rotate_base: if True, rotates the global rotation by 90 deg in x axis. if False, this is the original SMPL coordinate. Args: Rs: N x 24 x 3 x 3 rotation vector of K joi...
432e4d2224c27f01e45b5fe69b9e23584c9c95bd
74,288
def available_clouds(): """ list of regions configured for the current cloud for argparse suggestions """ try: clouds = config_proxy.CLOUDS return clouds.keys() except (ConfigurationError, AttributeError): return None
cbca28783cf393c0f895cf9580aacc41b6c28679
74,289
import yaml import time import copy def heatmap(data_config): """Generate heatmap based on the tile scores Creates a heatmap for the given column, using the color palette `viridis` to set a fill value - the color ranges from purple to yellow, for scores from 0 to 1. Args: data_config (string...
14a51c8736bb9a9413be1bc87acd72e04b8e90e2
74,291
def do_upload(app, fh, actual_freq_display=None, verbosity=0): """Perform a data upload for the named module app: The name of the uploader module that will upload the file, or it's registered dashboard_loader.models.Uploader object fh: A file-like object representing the the file to be uploaded. actual_freq_d...
8a7ca70b9f2b871cfc9d3b1b7c2ad01191da8233
74,292
from typing import List from typing import Tuple def get_slices(all_texts_df: pd.DataFrame, slice_length: int = 25, overlap_percent: float = 0) -> pd.DataFrame: """ Split the given pandas DataFrame into many slices. Parameters ---------- all_texts_df: pd.DataFrame : ...
fcfac23da3882b1507d4c0214468b99983b61ee2
74,293
def object_hook(data): """ detects the type of a JSON object, imports the class of that type and calls `to_dict` """ if '_type' in data: obj = None obj_type = data['_type'] klass = _import_type(obj_type) if hasattr(klass, 'from_dict'): obj = klass.from_di...
a5b29a49a9f5cff5aafc1e775f5b127ba7cc61a0
74,294
import math def create_pose(camR, scale=0, angle_deg=0): """Compute rotation matrix from viewpoint vertex and inplane rotation """ rot = camR.reshape(3,3) transform = np.eye(4) rodriguez = np.asarray([0, 0, 1]) * (angle_deg * math.pi / 180.0) angle_axis = expm(np.cross(np.eye(3), rodriguez)) t...
1a864d83c47c9c869a9cc039221e0b4943d7493a
74,295
def configure_publisher_install(request): """Render publisher install tab""" ctxd = { "i18n": { "title": ugettext_lazy( "configure_publisher_install.title" ), # 'Install or Upgrade Publisher' "fields": { "pickfile": { ...
3fe0fc88795437c00fb188624c485fc01271ac37
74,296
def root(): """Main page renders the index.html page""" return render_template( "index.html", username=app.config['BASIC_AUTH_USERNAME'], passwd=app.config['BASIC_AUTH_PASSWORD'] )
15c4a225f3a358d20b7c4369d8458b1cbde09285
74,299
import email def _getcharset(resp, default='utf-8'): """ Extract the charset from an HTTPResponse. """ # In Python 3, HTTPResponse is a subclass of email.message.Message, so we # can use get_content_chrset. In Python 2, however, it's not so we have # to be "clever". if hasattr(resp, 'heade...
be80b5b1ab527be83cd55a297f3ba65023d38949
74,300
def self_consistent_update(u_kn, N_k, f_k): """Return an improved guess for the dimensionless free energies Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_sta...
66d67a0f467f8d39405435012fc716238fab6bfd
74,301
def find_address_of_type(host_elem, type_): """Return the host's address of the given type, or `None` if there is no address element of that type. """ address_elem = host_elem.find('./address[@addrtype="{}"]'.format(type_)) if address_elem is not None: return address_elem.get('addr')
ff821703d076865da3c6efe0d2d760c4fcb2c997
74,304
import re def IsValidAtom(atom): """Test if an atom conforms to the JHM definition of an atom""" return re.match("([_a-zA-Z][_\-a-zA-Z0-9]*)?",atom)
218e846db1559bb91ab1ab47c5955d43b8274866
74,305
def submit(command, args=None, kwargs=None, name=None, qtype=None, profile=None, queue=None, **kwds): """Submit a script to the cluster. Parameters ---------- command : function/str The command or function to execute. args : tuple/dict, optional Optional arguments to add ...
a7bde7fca3b84d501682a749c2475cc760a36892
74,306
import re def fuzzyfinder(user_input,collection): """ fuzzy matching, to obtain a fuzzy matched list. >>>collection = [ "user_name", "api_user", "school", "email" ] >>>fuzzyfinder("user",collection) ...
db01f13f3caf5dc9a21cfb180776c22b589f1a28
74,307
import pickle def cache_memoize(max_age): """ Memoize decorator that uses Django's cache facility. Parameters ---------- max_age : int Maximum age of memoized results, in seconds. """ def decorator(func): site = Site.objects.get_current() key_prefix = 'cache_m...
9d115f3889a34f21528af8e494452e068f00024a
74,308
import jinja2 import inspect def set_template_env(template_dir): """ Function that sets the Jinja2 template environment from a given dir. Returns nothing. Input: - template_dir path """ env = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir), lstrip_blocks=Tr...
0f2a5375b9f3e2fca26cd12c8878eca23479bf12
74,309
def bq_token_file_path_exists_mock(token_path): """ Mock bq_token_file_path_exist to return True """ return True
54958444c16c4244ab349d60b0add39723ba6d8b
74,310
def view_cadastrar_usuario_passivo(request, callback=None): """ View de cadastro de novos usuários passivos. :param callback: próxima página :param request: POST form :return: """ if request.method == 'POST': form = FormCadastraUsuarioPassivo(request.POST) ...
1c2940b613ea7a27f5a8f1395d579be511be2b86
74,311
def unsqueeze(input, axes, name=None): """ Insert single-dimensional entries to the shape of a Tensor. Takes one required argument axes, a list of dimensions that will be inserted. Dimension indices in axes are as seen in the output tensor. For example: .. code-block:: text Given a tens...
c6d6aa8ac54027164b501fd1c8105a2132dbf5a2
74,312
def masa_strugotine(volumen_strugotine, gustoca_materijala): """ """ return 1e-9*volumen_strugotine*gustoca_materijala
06e65566ff2a9c13fabe1316a7a290c1145a741c
74,314
def get_edges(img): """搜索图片边界 :param img: 图片 :return: left, right, top, bottom """ image = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR) img = cv2.medianBlur(image, 5) # 中值滤波,去除黑色边际中可能含有的噪声干扰 b = cv2.threshold(img, 15, 255, cv2.THRESH_BINARY) # 调整裁剪效果 binary_image = b[1] # 二值图--具有三...
80442261977266ec5e17e5b710fbd09838fca4a3
74,315
def load_data(data_dir): """Loads the data. Returns tuple (`train_ds`, `val_ds`).""" # Training data. train_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, validation_split=VALIDATION_SPLIT, subset="training", seed=123, image_size=(IMG_HEIGHT, IMG_...
eb5fb41d9d98517d5ab72dadc80e59f35fde4c4e
74,316
def put_events(environment, start_response, headers): """ Store events in backends POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), events: { stream_name1 : [event1, event2, ...], stream_name2 : [event1, event2, ...], ... } }...
168bad8c98542a3d194ca61cb7c49c90fe5d2ee5
74,317
def main(important_parameter, ignored_parameter): """ :return: The answer to everything """ important_field = important_parameter # this way the parameter was actually used, hence making it important. def realmain(): def actualrealrealmain(): def nownoteve...
abde26d4c49e4300497a39df4c78f1e1d4ed9b5d
74,318
from typing import List from typing import Dict from typing import Any def _postporcess_edn(decks: List[Dict[str, Any]]) -> Dict[str, Any]: """ Tweak the data representation to fit what mochi expects """ for d in decks: d['name'] = d['name'].split('::')[-1] d['id'] = edn_format.Keyw...
2a4bf126867c624ac89bb9589149d3ec50db8f7c
74,319
from typing import Any def get_parent_dir(test_filepath: Any) -> Any: """Returns PurePath to parent directory of argument filepath. Arguments: test_filepath {Any} -- python Path to .robot file Returns: Any -- python PurePath to parent directory. See: https://docs...
31ae6cc161c292a61ce9ab0eea11b05ff532ae31
74,321
def drop_and_rearrange_columns( dataframe: pd.DataFrame, columns_to_keep: list[str] ) -> pd.DataFrame: """Drops and rearranges columns of a Pandas DataFrame. Args: dataframe (pd.DataFrame): Dataframe to operate on. columns_to_keep (list[str]): List of columns to keep in the order wanted. ...
c6b797270a7ab198bbcd03c88cedf8d75268db55
74,322
def _hitgroup_content_to_sorl_dt(hg): """Convert given HitGroupContent object into valid solr dictionary, that can be added to index using at least pysolr.Solr connection """ doc = { 'group_id': hg.group_id, 'requester_id': hg.requester_id, 'requester_name': hg.requester_name, ...
fa4395e67d2f00bf309a0e04c54272b03411caaa
74,324
def bias_variable(shape, verbose=False): """Creates a CPU variable with constant initialization. Adds summaries. Args: shape: list, the shape of the variable. verbose: if set add histograms. Returns: Bias variable tensor with shape=shape. """ with tf.device('/cpu:0'): with tf.name_scope('bia...
3d0a730d29ee22c231a3e393a654f5c8aed89bce
74,325
import random def title(random=random, *args, **kwargs): """ Return a title! >>> mock_random.seed(0) >>> title(random=mock_random) 'captain' >>> title(random=mock_random, capitalize=True) 'Lieutenant' >>> title(random=mock_random, slugify=True) 'leftenant' """ return rando...
bb379bc6fe6cfb905017bde2f79d68f341757674
74,326
import grp def to_gid(name): """Return a gid, given a group name If the group name is unknown, raises a ValueError. """ if isinstance(name, int): try: grp.getgrgid(name) return name except KeyError: raise ValueError("No such group: %r" % name) ...
aa8a97aff1ef18b425139e4a2e1870d3517d6782
74,327
def tree_price(ap): """ Computes the price-dividend ratio of the Lucas tree. Parameters ---------- ap: AssetPriceModel An instance of AssetPriceModel containing primitives Returns ------- v : array_like(float) Lucas tree price-dividend ratio """ # == Simplify n...
54dc847f5ac91d9b74db22f7eed399e6fc5fad75
74,328
def initialize_clock(): # pragma: no cover """ Initialise le temps. Returns ------- Clock Une horloge """ return pygame.time.Clock()
2e57cdc3d2e0566a498c1517fe8e32a1972ea43d
74,329
def get_hdf_data(name, path): """Get data from a HDF5 file assuming there is replicates of data branching from the top-level nodes """ # First locate the dataset in the first result, # then grab that data for every run. hdf = h5py.File(name, 'r') return [hdf[node + path].value for node...
cb158becfba9bcc3d565f91ed0807b2a12a32853
74,330
def permutation(geo, ref_geo, thresh=1e-4): """ determine the permutation of one geometry that reproduces another (If there isn't one -- the geometries are not aligned, return None) """ natms = count(geo) syms = symbols(geo) xyzs = coordinates(geo) perm_idxs = [None] * natms for idx, (...
18dd8cd74cf015d7585810b674ca03259a4f8e63
74,331
from datetime import datetime def check_realistic_birth_date(date): """ Function to check if the inserted date of birth is not futurist. """ date = date.split("/") today = datetime.strftime(datetime.now(), "%d/%m/%Y").split("/") logic_1 = ( int(date[0]) > int(today[0]) and # Day ...
3b92d322881b9f4dafac6678a1627cec90c8cd50
74,332
import numpy def _generate_segments(im_orig, scale, sigma, min_size): """ segment smallest regions by the algorithm of Felzenswalb and Huttenlocher """ # open the Image im_mask = skimage.segmentation.felzenszwalb( skimage.util.img_as_float(im_orig), scale=scale, sigma=sigma, ...
83e32babd83f5a17353357094b1c986d7bbec635
74,333
from datetime import datetime def get_month_data_range(months_ago=1, include_this_month=False): """ A method that generates a list of dictionaries that describe any given amount of monthly data. """ today = datetime.datetime.now().today() dates_ = [] if include_this_month: # get ne...
8122f759d807dd687bb18e2c013cf32310023c6a
74,334
def getBoundingBoxCoordinates(box, height, width): """ returns coordinates of bounding box in pixels :param box: a Tensor returned of tensorflow object detection prediction of 1 set of ymin, xmin, ymax, xmax :param height: height of image :param width: width of image :return: ymin, xmin, ymax, x...
14f6e94b68d62893d3235c73c0c4943e6edaf4d2
74,335
def deletable_group(request, onefs_client): """Get the name of an existing group that it is ok to delete.""" return _deletable_group(request, onefs_client)
5f9d1533c86b8b153e060e3fabf34c7fd786b735
74,336
def calc_dh(eta): """Calculate the first derivative of the interpolation function Args: eta: the phase field Returns: the value of dh """ return 30 * eta ** 2 * (eta - 1) ** 2
557f3d932c0b380ad291f2af081d1ebe8fcd5baf
74,337
def parse_requirements(): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open('requirements.txt')) return [line for line in lineiter if line and not line.startswith("#")]
8cc21bd86d207338c2e97701e6a42d5ff8edd0ad
74,338
def scale_by_stddev(decay=0.9, eps=1e-8): """Rescale updates by the root of the centered exp. moving average of squares. References: [Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) Args: decay: decay rate for the exponentially weighted average of squared grads. eps: term a...
5fb1cef48fd6486f6388e75ed4759726811ca1b4
74,339
import math def WassersteinMinFlowL1(h1, h2): """ Find the Wasserstein distance using a cutting plane on the dual """ def ID(x,y): return x*s+y n = len(h1) s = int(np.sqrt(n)) print(n,s) # Build model m = Model() #m.setParam(GRB.Param.TimeLimit, 300) #m.setParam(GRB.Param....
a87031f92a20ff671162d9b11d9da15712c66d79
74,340
def create_mesh_object_copies_with_applied_modifiers(scene): """ Creates copies of all mesh objects in the specified scene and applies then the edge split and mirror modifier on the copy. Afterwards it makes the mesh calculate triangle data via mesh.update(calc_tessface=True) """ non_empty_mesh_objects = ...
a3c1ddd939f3f513d4007346cacc0809adf95bc7
74,341
def compute_all_seclists(project_name): """ Make a list of all seclists for instances in project """ data_type = "instances" sections = get_section_data(project_name, data_type) seclists = [] for section in sections: instance_types = get_config_item(project_nam...
31ad8aee019ea10f986c5dd5a619e8ac7e23da09
74,342
def pol2cart(lon, lat): """ Utility function to convert longitude,latitude on a unit sphere to cartesian co-ordinates. """ x = np.cos(lat)*np.cos(lon) y = np.cos(lat)*np.sin(lon) z = np.sin(lat) return np.array([x,y,z])
74b760ebe126b022bd9b34a136f5c8fc2edea89c
74,343
def mod_padding_symmetric(image, factor=64): """Padding the image to be divided by factor.""" height, width = image.shape[0], image.shape[1] height_pad, width_pad = ((height + factor) // factor) * factor, ( (width + factor) // factor) * factor padh = height_pad - height if height % factor != 0 else 0 pa...
b08cc6285dee8bc99c979b081c88f2d4a3f77e06
74,344
def parse_http_response(data): """ Parses HTTP response data into a tuple in the form (cmd, headers). @param data: HTTP response data @type data: string @return: (cmd, headers) for the given data @rtype: tuple """ header, payload = data.split('\r\n\r\n') lines = header.split('\r\n') ...
da4680acd9dd429fdbffbe6927586ba23256286e
74,345
def filter_not_in(c, values, inclusion=None, exclusion=None): """Returns the entries of the specified collection whose values are not in the specified values for all the specified keys.""" values = to_set(values) return filter_not_with(c, lambda v: v in values, inclusion=inclusion, exclusion=exclusion)
677d850ccd2685d63b37b27fa679c821da64d97e
74,346
def get_project_names(): """Searches for Tracker projects at the Tracker home configuration file Returns: <list> -- List of project names """ trackerfile = TrackerFile() projects = trackerfile.get("projects", {}) project_names = [] if projects: for d in projects: ...
adf7a35a567d5cded2aa9100bb65ffa5f8fee2a4
74,347
def AircraftTraj(Nsim, npoint, Time=20, v=500/60, ra=0.25, rc=1/57, sigmac=1): """ Outputs N Aircraft trajectories in form of tuple Xa, Xc from point (0,0) horizontally la position along-track et cross-track. Simulation de N trajectoires d'avion par une discretisation du processus Gaussienn en n...
6829cee95e0b278dc131dd37719143c9dc072e42
74,348
import random from datetime import date from wbia.detecttools.pypascalmarkup import PascalVOC_Markup_Annotation import datetime def export_to_xml( ibs, species_list, species_mapping=None, offset='auto', enforce_viewpoint=False, target_size=900, purge=False, use_maximum_linear_dimension...
9fd9c2c2e224482d8870795c3690c32fbf334cc2
74,349
def setlocation(bot, trigger): """ Sets a nick's default city location """ if not trigger.group(2): bot.reply('Give me a location, like "Washington, DC" or "London".') return NOLIMIT api = bot.memory['owm']['api'] location_lookup = trigger.group(2) location_group_list = lookup_locat...
2d70de406319e10fcfa7c69791f7cc1c4aaa6aa6
74,350
from typing import Dict from typing import Tuple from typing import Union def sum_of_interaction_operator_gate_generators( n_modes: int, gates: Dict[Tuple[int, ...], Union[float, cirq.Gate]], ) -> openfermion.InteractionOperator: """The interaction operator that is the sum of the generators of the...
988d4d4d4285282eb3dfe60cb6ff670d51490adc
74,351
from typing import OrderedDict def remove_layers(summary): """ This is called when print_major_layers_only is True. Removes layers with no weights, like activation layers. Retain layers that manipulate shapes, otherwise reading the model summary can be confusing. """ new_summary =...
772dcc3fcfbe3828e84585c750e9384b0bcc08e6
74,352
def reasonability(x, val, mode): """ Checks to see if an array is within a set of bounds. """ if mode == 'high': return np.all(x <= val) if mode == 'low': return np.all(x >= val)
74d6c6388fc5427795c72ade2b423b113277b7cd
74,353
def topological_ordering(A): """Return a topological ordering for the DAG with adjacency matrix A, using Kahn's 1962 algorithm. Raises a ValueError exception if the given adjacency does not correspond to a DAG. Parameters ---------- A: np.array the adjacency matrix of the graph, wh...
f5ea21b12e8a91308ff680e3bec3fef7ae4ca90c
74,356
def dhcp_relay_detailed_show(dut, interface="", family="ipv4", cli_type=""): """ API to show the DHCP relay detailed output :param dut: :return: """ cli_type = st.get_ui_type(dut, cli_type=cli_type) if cli_type in ['click', 'klish']: ip_val = "ip" if family == "ipv4" else "ipv6" ...
f85839d01c404ddfd9b2c9cc436acb6a54f32415
74,357
def project_3(request): """Third project page""" return render_to_response('frontend/project-3.html', locals())
3ecf54afb5f74be63a01c5c2b0aea54634e0360d
74,358
def calc_cum_abs_deriv(y, sigma=10, order=1, axis=-1): """ Calculates the curvature of the spike count vector `y`""" return np.cumsum(np.abs(gaussian_filter1d(y, sigma=sigma, order=order, axis=axis)), axis=axis)
85dea0d95b4ca41a87f16a8316d24dced89b9155
74,360
def isChildUri(parentUri, childUri): """Return True, if childUri is a child of parentUri. This function accounts for the fact that '/a/b/c' and 'a/b/c/' are children of '/a/b' (and also of '/a/b/'). Note that '/a/b/cd' is NOT a child of 'a/b/c'. """ return parentUri and childUri and childU...
a28a386c38a4d6722f6b7c8bcbeafb8092dbbe77
74,361
from typing import Any def outer(a: Any, b: Any) -> Any: """ Compute the outer product of *a* and *b* while allowing either of them to be an :class:`ArrayContainer`. Tweaks the behavior of :func:`numpy.outer` to return a lower-dimensional object if either/both of *a* and *b* are scalars (whereas ...
9fa62a06e11197f669cd68b20a4cbf6f1743b19d
74,362
def setup_users_eligible_for_object(*perms): """Post-save signal receiver producer to setup a new object Since this is the first time permissions are being setup, the `bulk_create` manager method is used for performance. """ @transaction.commit_on_success @wraps(setup_users_eligible_for_object...
307220cbd24a74d2e5a212c4119486895bb8e742
74,363
def verify_sorted(countykey_list): """! verify that read countykey_list is sorted @param countykey_list List of county regional keys """ countykey_list_is_sorted = np.all(np.array( countykey_list[:-1]) <= np.array(countykey_list[1:])) # this checks if it is sorted if countykey_list_is_sorte...
63898815303629aa9402f023c68d1d2cb4a22cdf
74,364
def _parseUnit(unitString): """string -> multiplier returns how many of the base SI units are equivalent to this unit """ [num, den, *junk] = unitString.split("/") + ["1", "1"] # split string into numerator and denominator [num, den] = [x.split("*") for x in [num, den]] # split by term [num, den...
6c952a47a40297797bf64496c4a6bc7ba0af8c95
74,365