content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def Bool(name, ctx=None): """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used. >>> p = Bool('p') >>> q = Bool('q') >>> And(p, q) And(p, q) """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
8da9cf5376be9ba7250ffc10cd030bb57e0006a2
3,599,600
import os def get_bitgen_script_filename(config, absolute = False): """ Returns the Bitgen Script filename Args: config (dictionary): configuration dictionary Returns: (string): configuration dictionary filename """ bitgen_dir = get_bitgen_dir(config, absolute) bitgen_scr...
4b45f3f3daa87e391ea53914aa74766ee0c6c9f8
3,599,601
def partial_dMF(x, mf_definition, partial_parameter, func): """Calculates the partial derivative of a membership function at a point x.""" mf_name = func.__name__ if mf_name == 'gaussmf': sigma = mf_definition['sigma'] mean = mf_definition['mean'] if partial_parameter == 'sigma':...
a72dbc2e3a56f647e7c2ee8ac9b23238793a13a1
3,599,602
def get_event_list_current_file(df, fname): """ Get list of events for a given filename :param df: pd.DataFrame, the dataframe to search on :param fname: the filename to extract the value from the dataframe :return: list of events (dictionaries) for the given filename """ event_file = df[df[...
98ba12dcff1854a1cf333cbcf40f6cbd2d273146
3,599,603
def build(package, version_query=None, namespace="default", variables={}, shards=None, endpoint=DEFAULT_ENDPOINT): """ A build is the construction/expansion of a package. The result are the expanded/ready to use resources, including every dependencies. Args: package (:obj:`str`): packag...
551d21186af16edde22333ff8039d9f740baf74b
3,599,604
import os def find_host_ids(): """ This function ... :return: """ # Create a list to contain the host ids ids = [] # Search for files that define remote host configurations hosts_directory = fs.join(introspection.pts_user_dir, "hosts") if not fs.is_directory(hosts_directory): fs...
b5b182935fe722c31d2bb97cdec831d66e4b61f5
3,599,605
def circularArrayLoop( nums): """ :type nums: List[int] :rtype: bool """ def move(i): res = (i+nums[i])%len(nums) return res slow = move(0) fast = move(slow) while slow != fast: slow = move(slow) fast = move(move(fast)) fast = move(slow) if fast ==...
bb25883c698abd0b7d9183799e9c4c866d342409
3,599,606
def nearest_naptan_stop(filename, locality, atcocode, geo="geometry"): """[summary] Returns the next nearest node in the Naptan network to a given stop in the same locality. Arguments: FileName {[type]} -- [Is a file name string of naptan sub dataset] Locality {[type]} -- [A named locality,...
15e8b56f2e5fe23491bcf9c59d97f65f13cf234a
3,599,607
def _clean_str(value, strip_whitespace=True): """ Remove null values and whitespace, return a str This fn is used in two places: in SACTrace.read, to sanitize strings for SACTrace, and in sac_to_obspy_header, to sanitize strings for making a Trace that the user may have manually added. """ ...
41b9f0a1388045b86d019464512a0253eb5d6523
3,599,608
def status(): """获取所有通道流状态""" lst = [] for k in _ff2rtmp: dic = {'id': k, 'status': _ff2rtmp[k].getMediaStatus()} lst.append(dic) return response.make_response_success_data(lst)
04124b6c6698f73ab1e6087addb764e346c87d09
3,599,609
import random def createRandomGraph(): """Creates a digraph with 7 randomly chosen integer nodes from 0 to 9 and randomly chosen directed edges (between 10 and 20 edges) """ g = {} n = random.sample([0,1,2,3,4,5,6,7,8,9], 7) for i in n: g[i] = [] edges = random.randint(10,20) c...
e2ca213a594ad03c5df7a3231e7d246fe7fcb416
3,599,610
def gaussAve(t,y,std=.01): """ Does an average in y with weights based on distances to all other points in t. """ assert len(y) == len(t) n = len(t) dists = (t.reshape(n,1) - t.reshape(1,n)) dists[dists> .5] -= 1 dists[dists<-.5] += 1 w = np.exp(-.5*dists**2/std**2) return np.sum...
efa75dc342b2c5e1fa2f797f87e12eaf2c080c74
3,599,611
import ctypes def task_2_1(id_object, id_nodes, filename_graph=FILENAME_GRAPH): """ Searching tree shortest distances with minimal weight to selected nodes from selected object of infrastructure Arguments :param id_object: int * Id object of infrastructure - SELECTED ...
7f657c5c6e12320dabb0c2570c2d1dcc00c4be49
3,599,612
import json def read_json(filepath, intkeys=True, intvalues=True): """ read text from filepath (`open(find_filepath(expand_filepath(fp)))`) then json.loads() >>> js = read_json('wsj_pugnlp.detector_morse.Detector.json.gz', intvalues=False) >>> list(js.keys()) ['py/object', 'classifier', 'nocase'] ...
2c0cc3a18a41b55007f232727c2c9ceacaee87eb
3,599,613
import math def displace_on_a_sphere(point, radius=0.0): """ Masked points are placed on a random location on a sphere around the original location. Masked points are not placed inside the sphere itself. If we define a coordinate like ... >>> coordinate = Point(0.0, 0.0, 0.0) ... and c...
e5245176299782203024afdaadf6f7d87e667adf
3,599,614
def ini_elec_levels(spc_dct_i, spc_info): """ get initial elec levels """ if 'elec_levels' in spc_dct_i: elec_levels = spc_dct_i['elec_levels'] else: elec_levels = [[0., spc_info[2]]] return elec_levels
95a55a90c95466b2288799e4e24b3250c3afdd84
3,599,615
def check_for_factor(base, factor): """ This function should test if the factor is a factor of base. Factors are numbers you can multiply together to get another number. Return true if it is a factor or false if it is not. :param base: :param factor: :return: """ retur...
6d20a7d2e2ec459e8307007adb332507d0078118
3,599,616
def has_user_run_commands() -> bool: """has_user_run_commands() -> bool (internal) """ return bool()
ed564eafe9c004ed8e524aaf34b108a2994fab11
3,599,617
def IntersectionMatrixColorMap(matrix_data): """ Function to plot and save a colormap for visualisation of intersection matrix Parameter -------- matrix_data: list of lists, a square matrix of interstions Returns: None """ # set figure size fig = plt.figure(figsize=(12, 12)) ...
7fa2277c10ade79af22b2fa8b482962b13a93ce7
3,599,618
def has_access(user, users): """A list of users should look as follows: ['!deny', 'user1', 'user2'] This means that user1 and user2 have deny access. If we have something longer such as ['!deny', 'user1', '!allow', 'user2'] then user2 has access but user1 does not have access. If no keywords are fou...
07d3f47cf3725002023d8c9e487e14280dabc2bf
3,599,619
def log_suppress_or_reraise(*exceptions, logger=None, prelog=None, **kwargs): """Context manager or decorator - logs, raises and can suppress exceptions. Convenince function to support older implementation. """ return LogSuppressOrReraise(*exceptions, logger=logger, prelog=prelog, **kwargs)
f9ac1c021ccf1d6e9807b8faae4a19b3dac4c1d2
3,599,620
import subprocess def check_dfs(): """ This function checks if the dfs is running """ process = subprocess.Popen("jps", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() results = str(stdout) flag = 0 if results.find("NameNode") > -1: ...
6f82750992a5b30322b8c1de12b94b44f7257efb
3,599,621
def foo_endpoint(): """ just some endpoint """ logger = getLogger("foo_endpoint") logger.extra["some_extra"] = "1" logger.info("some message logged in foo_endpoint") return flask.jsonify({'bar': "BAR"})
44c8f33dadc4640b205ed39b9228da0a4698b6de
3,599,622
def check_absolute_continuity_policies_strict(P: np.ndarray, pi: np.ndarray, phi: np.ndarray) -> bool: """ Strict check of absolute continuity of two policies given an environment Used when computing bar I. Assume pi is deterministic, of dimension SxA """ dim_state, dim_action = P.shape[0], P.shape[...
2022c9d899fc9411c799e9bfa3bc6fdbc543070e
3,599,623
def calc_M_by_M0(t, t0, M0, period): """ Computes the mean anomaly as a function of a t, a mean anomaly (M0) at time t0 and the period. Args: t : time of the computation t0: a point in time where Mean anomaly is knwon M0: the mean anomaly in radians at t0 period : peri...
980dbcf9fa9cdb6e52904884aca2e5f39e8b166b
3,599,624
from datetime import datetime def timekeeper_prop(dt: datetime = None, state: str = 'init', enabled: int = 1, round_counter: int = 1, test_mode: bool = True, view_score_mode: bool = True, log_to_datastore: bool = False) -> dict: """ property of timekeeper (kind: 'clock') Parameters ---------- ...
6b5b132404686809f5601f2a84eb46ad6f94e774
3,599,625
def _default_initializer(name, shape, dtype): """The default initializer for variables.""" # pylint: disable=protected-access store = variable_scope._get_default_variable_store() initializer = store._get_default_initializer(name, shape=shape, dtype=dtype) # pylint: enable=protected-access return initializer...
e2530ab30ac2419e333e49de7c9a1ef2af93d6b9
3,599,626
def batchnorm_backward_alt(dout, cache): """ 可选的BN反向传播 """ dx, dgamma, dbeta = None, None, None mu, xmu, carre, var, sqrtvar, invvar, va2, va3, gamma, beta, x, bn_param = cache eps = bn_param.get('eps', 1e-5) N, D = dout.shape dbeta = np.sum(dout, axis=0) dgamma = np.sum((x - mu) * (...
8844619f87f2237b0b3e796cdf2041b86de67fa1
3,599,627
def midpnt(img): """ compute the midpoint pixel of an image The pixel coordinates in dimension (``dim``) are computed as :if ``dim`` is odd: ``(dim - 1)/2`` :if ``dim`` is even: ``dim/2`` :param img: pattern :return: midpoint pixel in image coordinates """ shape = np.asarray(i...
4c4bcf046fbb6a20c07a3dfde647088fe6424382
3,599,628
def simulate_ens(setup,N=1,desc='Simul',squeeze=True): """Generate a simulation on a ensemble (default=1) if squeeze is True and N==1, the output is squeeze on the ens dim""" f,h,chrono,X0 = setup.f, setup.h, setup.t, setup.X0 # Init xx = zeros((chrono.K+1,N,f.m)) xx[0] = X0.sample(N) #Loop for k,k...
5c3a75fe47588d362d18fd7f8863e119121b257d
3,599,629
def run_and_verify_svnlook2(expected_stdout, expected_stderr, expected_exit, *varargs): """Run svnlook command and check its output and exit code.""" exit_code, out, err = main.run_svnlook(*varargs) verify.verify_outputs("Unexpected output", out, err, expected_...
e7d66edf5afea9e652aea462f50616c578a3e8a1
3,599,630
from typing import List def compute_binned_conditional_probability(joint_distribution: np.array, target_idx: int, non_bin_idx: List, bin_idx: List, ...
16dbe8e645307440a395f7219aafc5d3e140d07c
3,599,631
import re def _get_variant_num(file_path): # type: (str) -> int """Returns the number of variants for a file. It assumes the file name suffix has the count. Raises: ValueError: if the file name is not formatted as `count_[COUNT]`. """ _, file_name = filesystems.FileSystems.split(file_path) if not ...
caf77160bc96ae7c31b683953bfc92d6028f58a1
3,599,632
from keras.models import Sequential from keras.layers import Dense def tail_model(nb_feature): """ tail model has the structure 600,300,150,60 nodes :param nb_feature: :return: """ # construct the model model = Sequential() model.add(Dense(600, input_dim=nb_feature, activation='relu'...
51e5a15dcf3a704a3c3b5a037f0d467b32a6c7c3
3,599,633
def return_json_response(): """Return json response sample""" return jsonify({'this is': 'sample'})
761599587948de2907b9cf2eff0496b7800101ae
3,599,634
def is_user_in_group(user, group): """ Check whether the user belongs to the group Args: user(str): user name/id group(class:Group): group to check user membership against Returns: - True if user is in the group, False otherwise """ if isinstance(group, Group) == Fals...
2015739c8bdb53509258f936a7a96ae9e511ad29
3,599,635
def _generate_variable_state(batch_size_tensor, state_size, dtype): """Generate a variable tensor with shape [batch_size, state_size].""" def create_variable(unnested_state_size): flat_dims = tensor_shape.as_shape(unnested_state_size).as_list() init_state_size = [batch_size_tensor] + flat_dims return tf...
0cbae443fdc7220c7a80e14614315f7b43b8e080
3,599,636
def by_cities(sdat): """ this function determines from how often people fly from every city :return: int[from moscow; from st pet.] """ borm = sdat.groupby(["Город вылета"]).size() cities = [] for i in borm: cities.append(i) return cities
d5e438ea7f9d298ff879df479f250342cc02eff1
3,599,637
def base() -> str: """ Handles redirection to other pages. :return: A redirect to the upload page. """ return redirect("upload")
54a58ba00ff10143cb25e93975e9804956a1554e
3,599,638
def drop_points(surf, array, low=-np.inf, upp=np.inf): """Remove surface points whose values fall within the threshold. Cells corresponding to these points are also removed. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. array : str or 1D ndarray Array us...
06ae20616ef8a4c0c5072c90ce70be98f83e3c9d
3,599,639
import inspect def process_signature(app, what, name, obj, options, signature, return_annotation): """Event hook for 'autodoc-process-signature' This captures the signature and returns an updated version of (signature, return_annotation) """ if inspect.isclass(obj) and issubclass(obj, AltairBase)...
db7d7b845e13b40c9df2f0c90aeb05badfbf7f99
3,599,640
def isVowel(letter): """ isVowel checks whether a given letter is a vowel. For purposes of this function, treat y as always a vowel, w never as a vowel. letter should be a string containing a single letter return "error" if the value of the parameter is not a single letter string, return True, if the...
5ba6917c80c4679a59580b8f3a05513d0904cd63
3,599,641
def d_xi(beta, K): """ First derivative of xi(beta). xi(beta) is the entropy of the system when no data has been observed. d_xi is the prior for the nsb estimator """ return K * mp.psi(1, K * beta + 1.) - mp.psi(1, beta + 1.)
13cdd16d55536eeeaa03e060c70b27636d7fd08d
3,599,642
def fn_winkler(weight_jaro, pre_matches, pre_scale): """ Scale the standard Jaro metric by 'pre_scale' units per 'pre_matches'. Note the warning in the docstring of jaro_winkler() regarding the scale. """ weight_jaro += pre_matches * pre_scale * (1.0 - weight_jaro) assert weight_jaro <= 1.0 ...
c938b932038e5344c19847555b70545d239cbb5a
3,599,643
from typing import Dict from typing import Tuple from typing import Set from textwrap import dedent def get_reactome(*, client: Neo4jClient) -> Dict[Tuple[str, str], Set[str]]: """Get Reactome gene sets. Parameters ---------- client : The Neo4j client. Returns ------- : A...
d517ac558d274dec5b4583bfd6f75ce3420fb7e5
3,599,644
def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" ...
e33117eb687077b4fd5970a7d007838e0b0fc58f
3,599,645
def as_rest_table(data, full=False): """ Originally from ActiveState recipes, copy/pasted from GitHub where it is listed with an MIT license. https://github.com/ActiveState/code/tree/master/recipes/Python/579054_Generate_Sphinx_table """ data = data if data else [["No Data"]] table = [] ...
587bfb75d241baa41662e130535828834fb7d62c
3,599,646
def isCCW(ring): """ Determines if a LinearRing is oriented counter-clockwise or not """ area = 0.0 for i in range(0,len(ring)-1): p1 = ring[i] p2 = ring[i+1] area += (p1[1] * p2[0]) - (p1[0] * p2[1]) if area > 0: return False else: return True
ef7b3ad88a3a5926896ab1c627b65f2e4e4dc47f
3,599,647
from typing import Callable def check(predicate: Callable) -> Callable: """A decorator to add a check to a server command Args: predicate: The check that should be run Returns: A decorator function that will add the check to the command """ def decorator(cmd: ServerCommand): ...
3201bc9da236be87ecfa0cb40fdc400973a4dda0
3,599,648
def visualization_grid(subplot_function, pass_ax_or_grid="ax", *args, **kwargs): """Decorator to create a grid for graphs and plot on it. Graphs will be printed by the subplot function to which the decorator is applied. Parameters ---------- pass_ax_or_grid: str Either 'ax' or 'grid'. ...
5f5398146bb2acbb15a6c1221fd8989366a42c8e
3,599,649
import socket import pickle def recv_frame(sock, timeout=None): """ Receive a frame from the socket. Reads the size of frame first followed by the actual data. frame is then de-serialized and returned as an instance of class frame. Arguments ---------- sock :- The socket to read fr...
407a68abcab300ce98fe51502d2e4ce7f5199286
3,599,650
def draw_framelinered(frame,height,width): #Better to pass Color parameter """ Draw alert red frame on video """ # Draw line top left and right cv2.line(frame, (0, 0), (0,int(height/10)), (0,0,255),10) cv2.line(frame, (0, 0), (int(height/10),0), (0,0,255),10) cv2.line(frame, (width, 0), (wid...
c153561adf6f8e8497d27846cecca3aac9624a19
3,599,651
def get_grant_key(grant_statement): """ Create the key from the grant statement. The key will be used as the dictionnary key. :param grant_statement: The grant statement :return: The key """ splitted_statement = grant_statement.split() grant_privilege = splitted_statement[1] if "."...
200b77d0988090628e013463bba5fe395dd76c00
3,599,652
def get_scenes_from_cuts(cut_list, base_timecode, num_frames, start_frame=0): # type: List[FrameTimecode], FrameTimecode, Union[int, FrameTimecode], # Optional[Union[int, FrameTimecode]] -> List[Tuple[FrameTimecode, FrameTimecode]] """ Returns a list of tuples of start/end FrameTimecodes for each scen...
cacb394cc5061e60891d6f50948ca8a8c16fc427
3,599,653
def openfield_pv_merra_ryberg2019(placements, merra_path, global_solar_atlas_ghi_path, module="WINAICO WSx-240P6", elev=300, tracking="fixed", inverter=None, inverter_kwargs={}, tracking_args={}, output_netcdf_path=None, output_variables=None): """ openfield_pv_merra_ryberg2019(placements, merra_path, global_s...
18ac4ea1a1da8dc6632cacacfb17345b26e837f7
3,599,654
def sell_open(id_or_ins, amount, price=None, style=None): """ 卖出开仓 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 ...
ec0557b2bb01e6cc138a61c5b1dc81d2c63150fd
3,599,655
async def async_setup_scanner( opp: OpenPeerPower, config, async_see, discovery_info=None ): """Set up the MySensors device scanner.""" if not discovery_info: return False new_devices = mysensors.setup_mysensors_platform( opp, DOMAIN, discovery_info, MySensorsDev...
f75fd09a9f90368ec81f06d84621c7561b591ba7
3,599,656
def get_all_bbox_masks_with_stride(mask, stride_factor): """ Find the bbox and corresponding masks """ bbox_mask = np.zeros_like(mask) bounding_boxes, _ = get_bbox(mask) y_size, x_size = bbox_mask.shape for x, y, h, w in bounding_boxes: x_min = x - stride_factor x_max = x + h...
d4c366a7a0784eb8701a17f01edafbaa76f78bc4
3,599,657
def get_metrics(): """Returns a list of specified metrics, wrapping up losses as metrics""" metrics = [metric_from_dict(m) for m in config.classify.metrics()] metrics = [LossToMetricWrapper(m) if issubclass(type(m), tf.keras.losses.Loss) else m for m in metrics] return metrics
1e475643fe1c0e2974c5df8e76add7e1ff26a6bd
3,599,658
import logging def add_results_to_json(js, nbest_hyps, char_list): """Function to add N-best results to json :param dict js: groundtruth utterance dict :param list nbest_hyps: list of hypothesis :param list char_list: list of characters :return: N-best results added utterance dict """ # c...
146d241f674fb21d396aa57885d21e4548bcf9e9
3,599,659
def get_timediff(dataset, start_time, end_time): """ Usage: [arg1]:[Pandas DataFrame],[arg2]:[column-start_time],[arg3]:[column-end_time] Returns: DataFrame with additional column [Duration in seconds] """ dataset['secs_diff_' + start_time + '_' + end_time] = (datas...
8fff531201953cd637027c0b6ac76e9ae45dc380
3,599,660
import math def augmentation_complete_tf2(im_x, rotation=[0, 360], gain=[0.8, 1.0, 1.2], gamma=[0.5, 1.0, 2], zoom=[0.9, 1.0, 1.1], gaussian_noise=None, bias=None...
4f01eb2a5f1b2e4d28dc3e7f250854982421150e
3,599,661
from typing import List from typing import Optional from datetime import datetime def parse_datestamp(datestamp: str, *, strict: bool = False) -> date: """Return the date that maps to datestamp. If strict is True, a full datestamp is expected (year/month/day): "2019/11/11" => 2019/11/11 Otherwi...
ac88e6be149565383000edfd4c145cc6a35b055b
3,599,662
from .core import AbstractSimpleExtractor from typing import Any def is_simple_extractor(obj: Any) -> bool: """ Determine the object if it is a simple extractor, return :obj:`True` if it is. """ # Local Folder return isinstance(obj, AbstractSimpleExtractor)
513b1d9f5c7c6db98a7c10a6348c09374e2fb9bb
3,599,663
def invert(d): """Dict of lists -> list of dicts.""" if d: return [dict(zip(d, i)) for i in zip(*d.values())]
1ac60d7c294e159836be3f6c83817ad7de4f7125
3,599,664
def materialize(self): """Materializes the implicit notifications of an observable sequence as explicit notification values. Returns an observable sequence containing the materialized notification values from the source sequence. """ source = self def subscribe(observer): def on_n...
0af5e1107d5185368b03e6308ad2971ec9d0c315
3,599,665
def get_format_style(deck) -> str: """ Возвращает соответствующий класс стиля формата колоды """ matching = {0: 'unknown', 1: 'wild', 2: 'standard', 3: 'classic'} return matching[deck.deck_format.numerical_designation]
79fd7febf913deb684c5499768cdb11621952a6e
3,599,666
def get_day_query_info(): """ get the day query info of product rt during latest 7 days :return: """ all_rt_heat_metric_list = get_rt_day_query_count() day_query_rt_dict = {} for each_rt in all_rt_heat_metric_list: query_list = [] dataset_id = each_rt["key"] query_cou...
53857fab0fd1bd7ca82f8c8f64d15a6fa50e41e4
3,599,667
def get_logp_diff_fn(apply_flat, noise_scale, parallel): """Returned function computes `log p(theta'|X,y) - log p(theta|X,y)`.""" lvar = noise_scale**2 def logp_diff_fn(theta, theta_prime, x, y): preds, preds_prime = apply_flat(theta, x), apply_flat(theta_prime, x) diff = 0.5 * jnp.sum((y - preds) ** 2 ...
4433544b89d95f67b5f9f7b06a70805d57f690ed
3,599,668
def mock_feed_metadata(anchore_db): """ Fixture for delivering mock feed and feed group metadata for metadata ops :param anchore_db: :return: """ feed_names = [] with session_scope() as db: for f in mock_feeds: feed_names.append(f['name']) feed = FeedMetadata...
e62d730404bad7b685c729b88bcb04a318950c88
3,599,669
def custom_filter(image): """ Allows the user to modify the image by multiplying each of the RGB values of each pixel by their input number. """ red_constant = float(input ("Multiply the R value of each pixel by: ")) green_constant = float(input ("Multiply the G value of each pixel by: ")) blue...
c1a23f13f7d5cdf49b7c9a4c1b9a84fa4cb56051
3,599,670
def cart2pol(x, y, z=None): """Convert Cartesian coordinates to polar. x: number or sequence y: number or sequence z: number or sequence (optional) returns: theta, rho OR theta, rho, z """ x = np.asarray(x) y = np.asarray(y) rho = np.hypot(x, y) theta = np.arctan2(y, x) i...
d42c55cb86e23215fdb804832e2870e92fa1ed64
3,599,671
def mean_ecliptic_longitude(t='now'): """Returns the mean ecliptic longitude.""" T = julian_centuries(t) result = 279.696680 + 36000.76892 * T + 0.0003025 * T ** 2 result = result * u.deg return Longitude(result)
d0bf2ad13382e720f58d3871b05c5f5456331e05
3,599,672
def load_presets(lang): """Read presets files, set global presets variable and return dictionary with preset classes.""" global presets class_dict = {} for f in PRESETS_DIR.rglob("*.yaml"): presets_yaml = read_yaml(f) # Skip preset if it is not valid for lang if lang: ...
03e26390f3baae79074cfa479aaded4173965cc8
3,599,673
def _j(pp, n=100, intervals=10, dmin=0.0, dmax=None, d=None): """ J function: Ratio of hazard functions for F and G. Parameters ---------- pp : :class:`.PointPattern` Point Pattern instance. n : int Number of empty space points (random points). int...
1e76732b15dc2dd739fe2b70bfa15474d009f795
3,599,674
from typing import Optional import torch def random_rotation( dtype: Optional[torch.dtype] = None, device=None, requires_grad=False ): """ Generate a single random 3x3 rotation matrix. Args: dtype: Type to return device: Device of returned tensor. Default: if None, uses th...
cd245691abf4afee7536c666be56e2882fc5effe
3,599,675
import copy def covModel1D_to_covModel3D(cov_model_1d): """ Converts a covariance model in 1D to a omni-directional covariance model in 3D. :param cov_model_1d: (CovModel1D class) covariance model in 1D :return cov_model_3d: (CovModel2D class) covariance model in 3D (omni-directional, ...
2a3e7cecef957ce66d4d41b7f338471368f4ea80
3,599,676
def getKlauder(f,t,T=5.0): """ Retrieves a Klauder Wavelet with upper frequency f[0] and lower frequency f[1]. See: http://www.subsurfwiki.org/wiki/Ormsby_filter """ assert len(f) == 2, 'Klauder wavelet needs 2 frequencies as input' k = np.diff(f)/T f0 = np.sum(f)/2.0 wav = np.real(np....
b87289cccd644e85703897230c259391b659253d
3,599,677
def is_transaction_successful(money_inserted, cost_of_the_drink): """Returns True when the transaction is successful, or False if money inserted is insufficient.""" # Checking if money put in is enough to but the drink user requested. if money_inserted >= cost_of_the_drink: # Calculating change and ...
ef9bc584e8860e0c8f915967d6b207cdd16cfaff
3,599,678
def _find_best_feature_split(X, y, max_features, split_score_function, min_samples_split, min_samples_leaf, split_threshold_mode, random_state): """ Finds the best single feature to split on and the split threshold to use. Parameters ---------- ...
0a3a0ddaddc2a34622f2b472499b90a153fe7d00
3,599,679
def create_line_strip(point_list: PointList, color: Color, line_width: float=1): """ Create a multi-point line to be rendered later. This works faster than draw_line because the vertexes are only loaded to the graphics card once, rather than each frame. :Example: >>> import a...
5b6eff4cec5f41a4b1fd5a8d1ebd07330f01b8b8
3,599,680
from re import U from re import X def run(space_step, final_time, generator="numpy", sorder=None, with_plot=True): """ Parameters ---------- space_step: double spatial step final_time: double final time generator: string pylbm generato...
93d2687f516304a4afce8ab56ce5ee0ce3079cb8
3,599,681
import json def unpack_msrest_error(e): """Obtains full response text from an msrest error""" op_err = None try: op_err = json.loads(e.response.text) except (ValueError, TypeError): op_err = e.response.text if not op_err: return str(e) return op_err
f55b08443b0f97f967de837732159b82fd8b5a60
3,599,682
def get_thread_id(pid): """Read thread group id designated in /proc/<pid>/status. """ return proc_readlines(pid, 'status')[2][6:-1]
5468a96e1896c8f848333c27deafa039370c99e2
3,599,683
def get_dependent_files(g, id): """returns the files which are dependent on the given symbol, lib, or file id""" target_node = g.get_node(id) if target_node is None: return None if target_node.type == dagger.graph_consts.NODE_LIB: edge_type = dagger.graph_consts.FIL_LIB elif target...
9715b2583489cff8dc72dfe426d4ae19f6d7f822
3,599,684
import torch def scale_torch(img): """ Scale the image and output it in torch.tensor. :param img: input rgb is in shape [H, W, C], input depth/disp is in shape [H, W] :param scale: the scale factor. float :return: img. [C, H, W] """ if len(img.shape) == 2: img = img[np.newaxis, :, ...
84bbe39e43b48bdbefc8c39ba17e6c08f83cb6ca
3,599,685
def map_file(topics_id, timespan_maps_id): """ The map files are actually stored on S3. We proxy this through out server, rather than directly making a call to the S3 URL, in order to be flexible and to get the mimetype correct. :param topics_id: :param timespan_maps_id: :return: """ as...
f7c70eaa2a9a313c8ed3981b45da430c92967d06
3,599,686
from datetime import datetime def datetime_str_to_datetime(datetime_str): """ This converts the strings generated when matlab datetimes are written to a table to python datetime objects """ if len(datetime_str) == 24: # Check for milliseconds return datetime.strptime(datetime_str, '%d-%b-%Y %H...
84960880bccfb21bdb2dc1a15b0bd09ef358187c
3,599,687
import torch def batched_inference(models, embeddings, rays, ts, N_samples, N_importance, use_disp, chunk, white_back, **kwargs): """Do batched inference on rays using chunk.""" B = rays.shape[0] results = defaultdict(...
baffc6e64e3cbe46c3a3372d5b577396c820c04d
3,599,688
def GenerateId_Hex(hash_sha512, input_file): """ Implement asset id of input file for hex format (with ':' delimiter) @param hash_sha512: string to encode @param input_file: input file to encode """ string_id = _as_hex_str(hash_sha512, ':') return string_id
f9fa7fbc669131f6ce0405abce885c9521ed4671
3,599,689
from numpy.core import isfinite import types def gisfinite(x): """like isfinite, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isfinite and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This fu...
022fd88387aa701c5acd90bff788a1015d8dcf5e
3,599,690
from typing import Dict from typing import Union from typing import Tuple def calculate(graph_client: GremlinClient, metrics_client: HeronMetricsClient, topology_id: str, cluster: str, environ: str, topology_ref: str, start: dt.datetime, end: dt.datetime, io_bucket_length: int, ...
e95f9d198f18a7051175656562a52693b134a51c
3,599,691
from typing import List import re def get_banner_ids(logfile: str = None) -> List[str]: """Gets all banner ids from a log file. You need to open the details of all banners for this to work. :param logfile: A path to a logfile """ log = _read_logfile(logfile) ids = re.findall(r"OnGetWebViewPag...
1b6fd7c9782285caa785c8c26cc76b5a09ee4288
3,599,692
def downcast_variables_dataframe(df): """ Method to downcast the variables in a DataFrame Parameters ---------- df : pd.DataFrame DataFrame to downcast Returns ------- pd.DataFrame """ df_downy = df.copy() # Downcast dataset df_downy[df_downy.select_dtypes(inclu...
0aa3a6d1abead5051f9ee5a7cff88dc6f4f8b2e0
3,599,693
import threading import functools def mutex(func): # type: (TCallable) -> TCallable """Enforce exclusive access on a decorated function.""" lock = threading.Lock() @functools.wraps(func) def wrapper(*args, **kwargs): """Wrapper around `func` which uses a lock to provide exclusive access to t...
d8ee1902a397cc2f200f3cd64f5015f2e85b5dca
3,599,694
def mangle(prefix, name): """Make a unique identifier from the prefix and the name. The name is allowed to start with $.""" if name.startswith('$'): return '%sinternal_%s' % (prefix, name[1:]) else: return '%s_%s' % (prefix, name)
6d949e61a87c6667fdfb262376e476aea64bde4b
3,599,695
def replay_entry(plugin, item_id, **kwargs): """ First executed function after replay_bridge """ return list_root(plugin, item_id)
894b6941571de82ab6ce4cb0daad4871062835b0
3,599,696
def de_normalize_minmax(x_scale, x, min_r, max_r): """ Transforms a min-max normalized and scaled vector back to its un-normalized form. """ x_t = [((i - min_r)/(max_r - min_r)) for i in x_scale] x_inv = [(i*(max(x) - min(x)) + min(x)) for i in x_t] return x_inv
d1a2bd2740552eae2c4bc0b94f2093de7ed03b70
3,599,697
def app(): """Flask application fixture.""" app = flask.Flask(__name__) return app
27300632fb18315529cd199b2771a7441baae9d4
3,599,698
import torch def update_ntk_inv(ntk, ntk_inv, keep_indices): """ A little bit faster implementation. Uses the fact that ntk is a symmetric matrix. """ S = set(keep_indices) remove_indices = [i for i in range(ntk.shape[0]) if i not in S] A12 = ntk[keep_indices][:, remove_indices] A22 = ntk[remove_...
26b62e0c1bca79643930ee822f34cfdd74e977fd
3,599,699