content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def PPVfn(Mw, fc, Rho, V): """Calculates the peak-particle-velocity (PPV) at the source for a given homogeneous density and velocity model. :param Mw: the moment magnitude :type Mw: float :param fc: the corner frequency in Hz :type fc: float :param Rho: Density at the source in kg/m**3 :type Rho: float :param V: Seismic velocity at the source in m/s :type V: float :returns: the PPV :rtype: float """ M0 = Mw2M0(Mw) # the seismic moment w0 = 2 * np.pi * fc PPV = w0 ** 2 * M0 / (4 * np.pi * Rho * (V ** 3)) return PPV
5629abb351e46ff41f11feef00bd8b7195b90e8f
3,637,868
import math def extract_feature_label(feat_path, lab_path, audio_sr=22050, hop_size=1024): """Basic feature extraction block. Parameters ---------- feat_path: Path Path to the raw feature folder. lab_path: Path Path to the corresponding label folder. audio_sr: int sampling rate, default=22050. hop_size: int number of samples between successive CQT columns, default=1024. Returns ------- data: Processed data """ label = load_label(lab_path) feature = load_feature(feat_path) pitch_shift = int(feat_path.replace(".npy", "").split('_pitch_shift=')[-1]) beatles_id = feat_path.replace(".npy", "") n_frames = feature.shape[0] # Get frame-wise labels chords = np.zeros(n_frames, dtype=np.int32) for lab in label: onset_idx = int(lab['onset'] * audio_sr / hop_size) end_idx = int(math.ceil(lab['end'] * audio_sr / hop_size)) chord = CHORD_INT_MAPPING_2[lab['chord']] chords[onset_idx:end_idx] = chord # Chord labels modulation chords_shift = _shift_chord_labels(chords, pitch_shift) # Chord transition transition = _get_chord_transition(chords_shift) data = {'cqt': feature, 'chord': chords_shift, 'transition': transition} # Reshape data = reshape_data(data, beatles_id) return data
2bdca45bcfe19e0b103d4b1762aab6ddf8e67b89
3,637,869
import re def get_m3u8_url(text): # type: (str) -> Union[str, None] """Attempts to get the first m3u8 url from the given string""" m3u8 = re.search(r"https[^\"]*\.m3u8", text) sig = re.search(r"(\?sig=[^\"]*)", text) if m3u8 and sig: return "{}{}".format(clean_uri(m3u8.group()), sig.group()) return None
25373d6fe8958dc28c6ddcb4eda1b02c9497fd18
3,637,872
def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights""" # https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow low = -constant*np.sqrt(6.0/(fan_in + fan_out)) high = constant*np.sqrt(6.0/(fan_in + fan_out)) return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high, dtype=tf.float32)
df8c812a81d22082add014a8bb17e8cc4966f58c
3,637,873
from typing import Union from typing import Optional def object_bbox_flip( bbox: remote_blob_util.BlobDef, image_size: remote_blob_util.BlobDef, flip_code: Union[int, remote_blob_util.BlobDef], name: Optional[str] = None, ) -> remote_blob_util.BlobDef: """This operator flips the object bounding box. The flip code corresponds to the different flip mode: 0 (0x00): Non Flip 1 (0x01): Horizontal Flip 16 (0x10): Vertical Flip 17 (0x11): Both Horizontal and Vertical Flip Args: bbox (BlobDef): The bounding box. image_size (BlobDef): The size of input image. flip_code (Union[int, BlobDef]): The flip code. name (Optional[str], optional): The name for the operation. Defaults to None. Returns: BlobDef: The result Blob For example: .. code-block:: python import numpy as np import oneflow as flow import oneflow.typing as tp def _of_object_bbox_flip(bbox_list, image_size, flip_code): bbox_shape = _get_bbox_static_shape(bbox_list) func_config = flow.FunctionConfig() func_config.default_data_type(flow.float) func_config.default_logical_view(flow.scope.mirrored_view()) @flow.global_function(function_config=func_config) def object_bbox_flip_job( bbox_def: tp.ListListNumpy.Placeholder( shape=tuple(bbox_shape), dtype=flow.float ), image_size_def: tp.ListNumpy.Placeholder( shape=image_size.shape, dtype=flow.int32 ), ) -> tp.ListListNumpy: bbox_buffer = flow.tensor_list_to_tensor_buffer(bbox_def) flip_bbox = flow.object_bbox_flip(bbox_buffer, image_size_def, flip_code) return flow.tensor_buffer_to_tensor_list( flip_bbox, shape=bbox_shape[1:], dtype=flow.float ) input_bbox_list = [np.expand_dims(bbox, axis=0) for bbox in bbox_list] bbox_tensor = object_bbox_flip_job([input_bbox_list], [image_size]) return bbox_tensor[0] def _get_bbox_static_shape(bbox_list): bbox_shapes = [bbox.shape for bbox in bbox_list] bbox_static_shape = np.amax(bbox_shapes, axis=0) assert isinstance( bbox_static_shape, np.ndarray ), "bbox_shapes: {}, bbox_static_shape: {}".format( str(bbox_shapes), str(bbox_static_shape) ) bbox_static_shape = bbox_static_shape.tolist() bbox_static_shape.insert(0, len(bbox_list)) return bbox_static_shape if __name__ == "__main__": bbox = np.array([[[20.0, 40.0, 80.0, 160.0], [30.0, 50.0, 70.0, 100.0]]]).astype(np.single) # [x1, y1, x2, y2] image_size = np.array([[480, 620]]).astype(np.int32) bbox_flip = _of_object_bbox_flip(bbox, image_size, flip_code=1) # Horizontal Flip print(bbox_flip[0][0]) # [[399. 40. 459. 160.] # [409. 50. 449. 100.]] """ assert isinstance(bbox, remote_blob_util.BlobDef) assert isinstance(image_size, remote_blob_util.BlobDef) assert bbox.shape[0] == image_size.shape[0] if name is None: name = id_util.UniqueStr("ObjectBboxFlip_") if not isinstance(flip_code, remote_blob_util.BlobDef): assert isinstance(flip_code, int) flip_code = flow.constant( flip_code, shape=(bbox.shape[0],), dtype=flow.int8, name="{}_FlipCode".format(name), ) else: assert bbox.shape[0] == flip_code.shape[0] op = ( flow.user_op_builder(name) .Op("object_bbox_flip") .Input("bbox", [bbox]) .Input("image_size", [image_size]) .Input("flip_code", [flip_code]) .Output("out") .Build() ) return op.InferAndTryRun().SoleOutputBlob()
8be9a58c2c8a10e8aaba402d45abf25edc42c0ab
3,637,874
def compile(spec): """ Args: spec (dict): A specification dict that attempts to "break" test dicts Returns: JsonMatcher. """ return JsonMatcher(spec)
bddb743e9f4fcbf3987363007f67c7e8dcf44c37
3,637,875
import itertools def labels_to_intervals(labels_list): """ labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs Args: labels_list: list of labels of each frame e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}] Returns: tags - set of time intervals where a tag occurs: { (label, start, end) }, a video from time 0 (inclusive) to time T (exclusive) e.g. {('cat', 3, 9), ('dog', 5, 8), ('people', 0, 6)} e.g. {('cat', 0, 1), ('cat', 2, 4), ('cat', 6, 8), ('dog', 0, 3), ('dog', 6, 8), ('people', 0, 2), ('people', 4, 6)} """ labels_dict = dict() for frame, labels in enumerate(labels_list): for label in labels: if label in labels_dict: labels_dict[label].add(frame) else: labels_dict[label] = {frame} output = set() for key, value in labels_dict.items(): frame_list = sorted(value) for interval in [(t[0][1], t[-1][1]) for t in (tuple(g[1]) for g in itertools.groupby(enumerate(frame_list), lambda x: x[0]-x[1]))]: output.add((key, interval[0], interval[1]+1)) return output
65b63ea3e6f097e9605e1c1ddb8dd434d7db9370
3,637,876
def get_wolfram_query_url(query): """Get Wolfram query URL.""" base_url = 'www.wolframalpha.com' if not query: return 'http://{0}'.format(base_url) return 'http://{0}/input/?i={1}'.format(base_url, query)
0122515f1a666cb897b53ae6bd975f65da072438
3,637,877
from typing import Sequence def center_of_mass(points: Sequence[float]) -> np.ndarray: """Gets the center of mass of the points in space. Parameters ---------- points The points to find the center of mass from. Returns ------- np.ndarray The center of mass of the points. """ points = [np.array(point).astype("float") for point in points] return sum(points) / len(points)
8d142a0b2b680900d5a20a0119702124bcdf3db6
3,637,878
def get_posts(session, client_id, now=None): """Returns all posts.""" now = _utcnow(now) try: results = _get_post_query(session, client_id)\ .order_by(MappedPost.created_datetime.desc()) posts = tuple(_make_post(*result) for result in results) return PaginatedSequence(posts) except sa.exc.IntegrityError: session.rollback() raise db_util.DbException._chain()
8cf5eb1ef9ec84a8d98cd8cc285ade7725f0dc5a
3,637,879
def tessellate_cell(csn, children, acells, position, parent, cell_params): """ Tessellate a cell. :param int csn: Cell number. :param ndarray children: Array specifying children of each cell. :param ndarray acells: Array specifying the adjacent cells of each cell. :param ndarray position: Array specifying the position of each cell. :param ndarray parent: Array specifying the parent of each cell. :param ndarray cell_params: Array specifying the corner parameters of each cell. :return: The number of triangles and the parameter values for each of the three triangle vertices (ntri, triangles). The *triangles* list will be *ntri* x 3, where each row is a triangle and contains a list of three tuples containing two parameter values on the original surface. These parameter values represent a vertex of the triangle. The order of the parameter values should result in a normal vector oriented the same as the original surface. :rtype: tuple Reference: Anderson, J., Khamayseh, A., and Jean, B. "Adaptive Resolution Refinement," Technical Report, Los Alamos National Laboratory. """ # Determine number of interior points and parameters on each edge. nprms = [] edge_prms = [] edge_order = [1, 3, 4, 2] simple = False for i in edge_order: adj_cells = _find_neighbors(csn, i, children, acells, position, parent) prms = _find_edge_params(i, adj_cells, cell_params) nprms.append(len(prms)) edge_prms.append(prms) if len(prms) > 1: simple = True # Use simple triangulation if any edge has more than one interior point. if simple: # Make a single list of parameters in counter-clockwise order. # Edge 1 all_params = [cell_params[csn, 0]] for uv in edge_prms[0]: all_params.append(uv) all_params.append(cell_params[csn, 1]) # Edge 3 for uv in edge_prms[1]: all_params.append(uv) all_params.append(cell_params[csn, 2]) # Edge 4 for uv in edge_prms[2]: all_params.append(uv) all_params.append(cell_params[csn, 3]) # Edge 2 for uv in edge_prms[3]: all_params.append(uv) all_params.append(cell_params[csn, 0]) # Middle parameter. uv0 = cell_params[csn, 0] uv1 = cell_params[csn, 2] uvc = 0.5 * (uv0 + uv1) # Generate triangles triangles = [] for i in range(len(all_params) - 1): uv0 = all_params[i] uv1 = all_params[i + 1] triangles.append([uv0, uv1, uvc]) return len(triangles), triangles # Use predefined triangles. # Determine triangulation case by the number of interior points on each # edge. triangles = [] triapp = triangles.append cprms = cell_params[csn, :] eprms = [row[0] for row in edge_prms if len(row) > 0] case = nprms[0] + nprms[1] * 10 + nprms[2] * 100 + nprms[3] * 1000 # Case 0 if case == 0: triapp([cprms[0], cprms[1], cprms[2]]) triapp([cprms[2], cprms[3], cprms[0]]) return len(triangles), triangles # Case 1 if case == 1: triapp([cprms[0], eprms[0], cprms[3]]) triapp([eprms[0], cprms[1], cprms[2]]) triapp([cprms[2], cprms[3], eprms[0]]) return len(triangles), triangles # Case 2 if case == 10: triapp([cprms[0], cprms[1], eprms[0]]) triapp([eprms[0], cprms[2], cprms[3]]) triapp([cprms[3], cprms[0], eprms[0]]) return len(triangles), triangles # Case 3 if case == 11: triapp([cprms[0], eprms[0], cprms[3]]) triapp([eprms[0], cprms[1], eprms[1]]) triapp([eprms[1], cprms[2], cprms[3]]) triapp([cprms[3], eprms[0], eprms[1]]) return len(triangles), triangles # Case 4 if case == 100: triapp([cprms[0], cprms[1], eprms[0]]) triapp([cprms[1], cprms[2], eprms[0]]) triapp([eprms[0], cprms[3], cprms[0]]) return len(triangles), triangles # Case 5 if case == 101: triapp([cprms[0], eprms[0], cprms[3]]) triapp([eprms[0], eprms[1], cprms[3]]) triapp([eprms[0], cprms[1], eprms[1]]) triapp([cprms[1], cprms[2], eprms[1]]) return len(triangles), triangles # Case 6 if case == 110: triapp([cprms[0], cprms[1], eprms[0]]) triapp([eprms[0], cprms[2], eprms[1]]) triapp([eprms[1], cprms[0], eprms[0]]) triapp([eprms[1], cprms[3], cprms[0]]) return len(triangles), triangles # Case 7 if case == 111: triapp([cprms[0], eprms[0], eprms[2]]) triapp([eprms[0], cprms[1], eprms[1]]) triapp([eprms[1], cprms[2], eprms[2]]) triapp([eprms[2], eprms[0], eprms[1]]) triapp([eprms[2], cprms[3], cprms[0]]) return len(triangles), triangles # Case 8 if case == 1000: triapp([cprms[0], cprms[1], eprms[0]]) triapp([cprms[1], cprms[2], eprms[0]]) triapp([cprms[2], cprms[3], eprms[0]]) return len(triangles), triangles # Case 9 if case == 1001: triapp([cprms[0], eprms[0], eprms[1]]) triapp([eprms[0], cprms[1], cprms[2]]) triapp([cprms[2], eprms[1], eprms[0]]) triapp([cprms[2], cprms[3], eprms[1]]) return len(triangles), triangles # Case 10 if case == 1010: triapp([cprms[0], cprms[1], eprms[0]]) triapp([eprms[0], cprms[2], eprms[1]]) triapp([cprms[2], cprms[3], eprms[1]]) triapp([eprms[1], cprms[0], eprms[0]]) return len(triangles), triangles # Case 11 if case == 1011: triapp([cprms[0], eprms[0], eprms[2]]) triapp([eprms[0], eprms[1], eprms[2]]) triapp([eprms[0], cprms[1], eprms[1]]) triapp([eprms[1], cprms[2], eprms[2]]) triapp([cprms[2], cprms[3], eprms[2]]) return len(triangles), triangles # Case 12 if case == 1100: triapp([cprms[0], cprms[1], eprms[1]]) triapp([cprms[1], cprms[2], eprms[0]]) triapp([eprms[0], eprms[1], cprms[1]]) triapp([eprms[0], cprms[3], eprms[1]]) return len(triangles), triangles # Case 13 if case == 1101: triapp([cprms[0], eprms[0], eprms[2]]) triapp([eprms[0], cprms[1], cprms[2]]) triapp([cprms[2], eprms[1], eprms[0]]) triapp([eprms[1], eprms[2], eprms[0]]) triapp([eprms[1], cprms[3], eprms[2]]) return len(triangles), triangles # Case 14 if case == 1110: triapp([cprms[0], cprms[1], eprms[0]]) triapp([eprms[0], eprms[2], cprms[0]]) triapp([eprms[0], cprms[2], eprms[1]]) triapp([eprms[1], eprms[2], eprms[0]]) triapp([eprms[1], cprms[3], eprms[2]]) return len(triangles), triangles # Case 15 if case == 1111: triapp([cprms[0], eprms[0], eprms[3]]) triapp([eprms[0], eprms[1], eprms[3]]) triapp([eprms[0], cprms[1], eprms[1]]) triapp([eprms[1], cprms[2], eprms[2]]) triapp([eprms[2], eprms[3], eprms[1]]) triapp([eprms[2], cprms[3], eprms[3]]) return len(triangles), triangles # Return empty list. return 0, []
0c9993f49a147488488c7131d772c1996bc12d0f
3,637,880
import torch def add_eig_vec(g, pos_enc_dim): """ Graph positional encoding v/ Laplacian eigenvectors This func is for eigvec visualization, same code as positional_encoding() func, but stores value in a diff key 'eigvec' """ # Laplacian A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float) N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float) L = sp.eye(g.number_of_nodes()) - N * A * N # Eigenvectors with numpy EigVal, EigVec = np.linalg.eig(L.toarray()) idx = EigVal.argsort() # increasing order EigVal, EigVec = EigVal[idx], np.real(EigVec[:, idx]) g.ndata["eigvec"] = torch.from_numpy(EigVec[:, 1 : pos_enc_dim + 1]).float() # zero padding to the end if n < pos_enc_dim n = g.number_of_nodes() if n <= pos_enc_dim: g.ndata["eigvec"] = F.pad( g.ndata["eigvec"], (0, pos_enc_dim - n + 1), value=float("0") ) return g
a7487f048dfd14cc4d9e04e8a754327dd9c8b19a
3,637,881
import numpy as np from scipy import ndimage from skimage.morphology import ball def _advanced_clip( data, p_min=35, p_max=99.98, nonnegative=True, dtype="int16", invert=False ): """ Remove outliers at both ends of the intensity distribution and fit into a given dtype. This interface tries to emulate ANTs workflows' massaging that truncate images into the 0-255 range, and applies percentiles for clipping images. For image registration, normalizing the intensity into a compact range (e.g., uint8) is generally advised. To more robustly determine the clipping thresholds, spikes are removed from data with a median filter. Once the thresholds are calculated, the denoised data are thrown away and the thresholds are applied on the original image. """ # Calculate stats on denoised version, to preempt outliers from biasing denoised = ndimage.median_filter(data, footprint=ball(3)) a_min = np.percentile(denoised[denoised > 0] if nonnegative else denoised, p_min) a_max = np.percentile(denoised[denoised > 0] if nonnegative else denoised, p_max) # Clip and cast data = np.clip(data, a_min=a_min, a_max=a_max) data -= data.min() data /= data.max() if invert: data = 1.0 - data if dtype in ("uint8", "int16"): data = np.round(255 * data).astype(dtype) return data
9444db42b146798900fde89d8436b742ba9082a6
3,637,882
def allocate_buffers(engine): """ Allocates all buffers required for the specified engine """ inputs = [] outputs = [] bindings = [] # Iterate over binding names in engine for binding in engine: # Get binding (tensor/buffer) size size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size # Get binding (tensor/buffer) data type (numpy-equivalent) dtype = trt.nptype(engine.get_binding_dtype(binding)) # Allocate page-locked memory (i.e., pinned memory) buffers host_mem = cuda.pagelocked_empty(size, dtype) # Allocate linear piece of device memory device_mem = cuda.mem_alloc(host_mem.nbytes) # Append the device buffer to device bindings bindings.append(int(device_mem)) # Append to inputs/ouputs list if engine.binding_is_input(binding): inputs.append(HostDeviceMem(host_mem, device_mem)) else: outputs.append(HostDeviceMem(host_mem, device_mem)) # Create a stream (to eventually copy inputs/outputs and run inference) stream = cuda.Stream() return inputs, outputs, bindings, stream
b7f28c256a1ec169392a4cfb27347ae742c922bb
3,637,883
def D_to_M(D, ecc): """Mean anomaly from eccentric anomaly. Parameters ---------- D : float Parabolic eccentric anomaly (rad). ecc : float Eccentricity. Returns ------- M : float Mean anomaly (rad). """ with u.set_enabled_equivalencies(u.dimensionless_angles()): M = _kepler_equation_parabolic(D, 0.0 * u.rad, ecc) return M
2f6b6ac3c3a0d02456f0e9b03dd6a183583a8bb4
3,637,884
def dict_merge(a, b): """Merge a and b. Parameters ---------- a One dictionary that will be merged b Other dictionary that will be merged """ return _merge(dict(a), b)
2209659fafb6c1d7d8877bfe923ca98516d255bc
3,637,885
import copy def merge_dictionary(src: dict, dest: dict) -> dict: """ Merge two dictionaries. :param src: A dictionary with the values to merge. :param dest: A dictionary where to merge the values. """ for name, value in src.items(): if name not in dest: # When field is not available in destination add the value from the source if isinstance(value, dict): # A new dictionary is created to avoid keeping references dest[name] = copy.deepcopy(value) elif isinstance(value, list): # A new list is created to avoid keeping references dest[name] = copy.deepcopy(value) else: dest[name] = value elif isinstance(value, dict): # When field exists in destination and is dict merge the source value merge_dictionary(value, dest[name]) elif isinstance(value, list) and isinstance(dest[name], list): # When both values are a list merge them dest[name].extend(copy.deepcopy(value)) return dest
12305510a9a2d50bcdc691cb7fe8d5a573621e69
3,637,886
def create_from_source(wp_config, source: Location): """ Using a Location object and the WP config, generates the appropriate LuhSql object """ if isinstance(source, SshLocation): ssh_user = source.user ssh_host = source.host elif isinstance(source, LocalLocation): ssh_user = None ssh_host = None else: raise LuhError(f"Unknown source type: {source.__class__.__name__}") return LuhSql( host=wp_config["db_host"], user=wp_config["db_user"], password=wp_config["db_password"], db_name=wp_config["db_name"], ssh_user=ssh_user, ssh_host=ssh_host, )
3854d70889a1fdc0517f2557431887ca560acb14
3,637,887
def eye(N, M=None, k=0, dtype=DEFAULT_FLOAT_DTYPE): """ Returns a 2-D tensor with ones on the diagnoal and zeros elsewhere. Args: N (int): Number of rows in the output, must be larger than 0. M (int, optional): Number of columns in the output. If None, defaults to N, if defined, must be larger than 0. Deault is None. k (int, optional): Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. Default is 0. dtype (Union[mstype.dtype, str], optional): Designated tensor dtype, can be in format of np.float32, or `float32`. Default is mstype.float32. Returns: result (Tensor): A tensor of shape (N,M). A tensor where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import mindspore.numpy as np >>> print(np.eye(2, 2)) [[1. 0.] [0. 1.]] """ dtype = _check_dtype(dtype) make_eye = P.Eye() if M is None: M = N M = int(M) N = int(N) k = int(k) out = None if k != 0 or N == 0 or M == 0: # Fall back to original numpy creation method out = onp.eye(N, M, k) else: out = make_eye(N, M, dtype) return asarray(out, dtype=dtype)
952da74fbedfaa433244a65cff463ccf0b389cf1
3,637,888
import requests def team_game_log(request, team_id, season): """Individual team season game log page. """ response = requests.get(f'http://{request.get_host()}/api/teams/{team_id}/{season}/Regular') return render(request, 'main/team_games.html', context=response.json())
1e4c59febb2d5d5f2c3496242c8de8068c4bb329
3,637,890
def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower,weak_upper): #def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower=0.935,weak_upper=0.98): """ - this is the linear case of getting labels for new spectra best log g = weak_lower = 0.95, weak_upper = 0.98 best teff = weak_lower = 0.95, weak_upper = 0.99 best_feh = weak_lower = 0.935, weak_upper = 0.98 this returns the parameters for a field of data - and normalises if it is not already normalised this is slow because it reads a pickle file """ file_in = open(fn_pickle, 'r') dataall, metaall, labels, offsets, coeffs, covs, scatters,chis,chisqs = pickle.load(file_in) file_in.close() nstars = (testdata.shape)[1] nlabels = len(labels) Params_all = np.zeros((nstars, nlabels)) MCM_rotate_all = np.zeros((nstars, nlabels, nlabels)) for jj in range(0,nstars): if np.any(testdata[:,jj,0] != dataall[:, 0, 0]): print testdata[range(5),jj,0], dataall[range(5),0,0] assert False xdata = testdata[:,jj,0] ydata = testdata[:,jj,1] ysigma = testdata[:,jj,2] ydata_norm = ydata - coeffs[:,0] # subtract the mean cut_to = shape(metaall)[1]*-1. coeffs_slice = coeffs[:,cut_to:] #ind1 = np.logical_and(logical_and(dataall[:,jj,0] > 16200., dataall[:,jj,0] < 16500.), np.logical_and(ydata > weak_lower , ydata < weak_upper)) ind1 = np.logical_and(ydata > weak_lower , ydata < weak_upper) Cinv = 1. / (ysigma ** 2 + scatters ** 2) MCM_rotate = np.dot(coeffs_slice[ind1].T, Cinv[:,None][ind1] * coeffs_slice[ind1]) MCy_vals = np.dot(coeffs_slice[ind1].T, Cinv[ind1] * ydata_norm[ind1]) Params = np.linalg.solve(MCM_rotate, MCy_vals) Params = Params + offsets print Params Params_all[jj,:] = Params MCM_rotate_all[jj,:,:] = MCM_rotate file_in = open(fout_pickle, 'w') pickle.dump((Params_all, MCM_rotate_all), file_in) file_in.close() return Params_all , MCM_rotate_all
8321f8cdc8c7cfb97106a3eba8c5846a108adcb5
3,637,891
import pylab as pl def figure(*args, grid=True, style='default', figsize=(9, 5), **kwargs): """ Returns a matplotlib axis object. """ available = [s for s in pl.style.available + ['default'] if not s.startswith('_')] if style not in available: raise ValueError(f'\n\n Valid Styles are {available}') pl.style.use(style) pl.figure(*args, figsize=figsize, **kwargs) pl.grid(grid) ax = pl.gca() return ax
58a50dfda449518c1fed06a380ec0dac82eb1943
3,637,893
def boundcond(stato): """This function applies the boundary conditions that one chooses to adopt. The boundaries can be reflective, periodic or constant. It takes as input the state to be evolved. """ if bc=='const': status=''.join(('.',stato,'.')) #constant boundaries elif bc=='refl': status=''.join((stato[0],stato,stato[n-1]))#reflective boundaries elif bc=='period': status=''.join((stato[n-1],stato,stato[0]))#periodic boundaries else: print('Invalid BCs') return status
826ea52b1b2bbda01b88f03ce546757225a3bec8
3,637,894
def get_compare_collection(name, csv_line): """get compare collection data""" session = tables.get_session() if session is None: return {'isExist': False} response = {} try: collection_table = CollectionTable() cid = collection_table.get_field_by_key(CollectionTable.collection_id, CollectionTable.collection_name, name, session) cip = collection_table.get_field_by_key(CollectionTable.collection_ip, CollectionTable.collection_name, name, session) get_collection_data_dirs(cip, cid, csv_line, response, session) if csv_line < response['nextCsv']: response['hasNext'] = True else: response['hasNext'] = False except SQLAlchemyError as err: LOGGER.error('Get compare collection data failed: %s', err) return {'isExist': False} finally: session.close() response['isExist'] = True return response
4312336786de0cd2107e4d662d5527bed37e89b9
3,637,896
from qutepart.indenter.base import IndentAlgNormal as indenterClass from qutepart.indenter.base import IndentAlgBase as indenterClass from qutepart.indenter.base import IndentAlgNormal as indenterClass from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass from qutepart.indenter.python import IndentAlgPython as indenterClass from qutepart.indenter.ruby import IndentAlgRuby as indenterClass from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass from qutepart.indenter.haskell import IndenterHaskell as indenterClass from qutepart.indenter.lilypond import IndenterLilypond as indenterClass from qutepart.indenter.lisp import IndentAlgLisp as indenterClass from qutepart.indenter.scheme import IndentAlgScheme as indenterClass def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols """ indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) elif 'none' == indenterName: elif 'normal' == indenterName: elif 'cstyle' == indenterName: elif 'python' == indenterName: elif 'ruby' == indenterName: elif 'xml' == indenterName: elif 'haskell' == indenterName: elif 'lilypond' == indenterName: elif 'lisp' == indenterName: elif 'scheme' == indenterName: else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter)
3d6f905b66fa7808ad6863e891c30b0d0fb02e7f
3,637,897
import json def scheming_multiple_choice_output(value): """ return stored json as a proper list """ if isinstance(value, list): return value try: return json.loads(value) except ValueError: return [value]
d45bbb1af249d0fed00892ccc55cf8f28f7f099f
3,637,898
def logmap(x, x0): """ This functions maps a point lying on the manifold into the tangent space of a second point of the manifold. Parameters ---------- :param x: point on the manifold :param x0: basis point of the tangent space where x will be mapped Returns ------- :return: vector in the tangent space of x0 """ if np.ndim(x0) < 2: x0 = x0[:, None] if np.ndim(x) < 2: x = x[:, None] theta = np.arccos(np.dot(x0.T, x)) u = (x - x0 * np.cos(theta)) * theta/np.sin(theta) u[:, theta[0] < 1e-16] = np.zeros((u.shape[0], 1)) return u
be18b7a78f13f7159572429cf77fbc763747076b
3,637,899
def parse_field(source, loc, tokens): """ Returns the tokens of a field as key-value pair. """ name = tokens[0].lower() value = normalize_value(tokens[2]) if name == 'author' and ' and ' in value: value = [field.strip() for field in value.split(' and ')] return (name, value)
be5533cc53fc73fe84d8bd79465ef03ba22cfa5f
3,637,900
def evaluate_models_exploratory(X_normal:np.ndarray, X_te:np.ndarray, X_adv_deepfool:np.ndarray, X_adv_fgsm:np.ndarray, X_adv_pgd:np.ndarray, X_adv_dt:np.ndarray, Y:np.ndarray, Y_aml:np.ndarray, perfs:dict, contamination:float=.05, degree:float=3., support_fraction:float=.5): """ """ MODELS = [IsolationForest(contamination=contamination), OneClassSVM(kernel='poly', degree=degree), EllipticEnvelope(contamination=contamination, support_fraction=support_fraction), LocalOutlierFactor(contamination=contamination)] MODELS_NAMES = ['if', 'svm', 'ee', 'lo'] ATTACKS = ['baseline', 'deepfool', 'fgsm', 'pgd', 'dt'] for model, model_name in zip(MODELS, MODELS_NAMES): # fit the model on the normal data model.fit(X_normal) # if we are running the local outlier factor then we need to set the novelty bit # in the class if hasattr(model, 'novelty'): model.novelty = True #Y_hat, Y_deepfool, Y_fgsm, Y_pgd, Y_dt outputs = model.predict(X_te), model.predict(X_adv_deepfool), \ model.predict(X_adv_fgsm), model.predict(X_adv_pgd), model.predict(X_adv_dt) for y_hat, attack_type in zip(outputs, ATTACKS): if attack_type == 'baseline': labels = Y else: labels = Y_aml acc, fs, tpr, tnr, mcc = get_performance(y_true=labels, y_hat=y_hat) perfs[''.join(['accs_', model_name, '_', attack_type])] += acc perfs[''.join(['fss_', model_name, '_', attack_type])] += fs perfs[''.join(['tprs_', model_name, '_', attack_type])] += tpr perfs[''.join(['tnrs_', model_name, '_', attack_type])] += tnr perfs[''.join(['mccs_', model_name, '_', attack_type])] += mcc return perfs
17435e38512c9c158db6d6ae12ab44c38f573c61
3,637,901
from typing import Iterable from typing import Optional def is_valid_shipping_method( checkout: Checkout, lines: Iterable["CheckoutLineInfo"], discounts: Iterable[DiscountInfo], subtotal: Optional["TaxedMoney"] = None, ): """Check if shipping method is valid and remove (if not).""" if not checkout.shipping_method: return False if not checkout.shipping_address: return False valid_methods = get_valid_shipping_methods_for_checkout( checkout, lines, discounts, subtotal=subtotal ) if valid_methods is None or checkout.shipping_method not in valid_methods: clear_shipping_method(checkout) return False return True
01cbbc493d74057c8f2e252cfd217b3cd108b97c
3,637,905
async def load_gdq_index(): """ Returns the GDQ index (main) page, includes donation totals :return: json object """ return (await load_gdq_json(f"?type=event&id={config['event_id']}"))[0]['fields']
6d1383990a2fb98c7a42b4423f21728f4f473e1a
3,637,906
def deleteRestaurantForm(r_id): """Create form to delete existing restaurant Args: r_id: id extracted from URL """ session = createDBSession() restaurant = session.query(Restaurant).get(r_id) if restaurant is None: output = ("<p>The restaurant you're looking for doesn't exist.<br>" "<a href='/restaurants'>Back to listings</a></p>") else: output = ("<form method='POST' enctype='multipart/form-data' " "action='/restaurants/%s/delete'>" "<h2>Delete %s restaurant</h2><p>Are you sure? " "<input type='hidden' name='restaurantID' value='%s'>" "<input type='submit' value='Delete'></p></form>" "<p><a href='/restaurants'>No, take me back to the listings" "</a></p>") % (restaurant.id, restaurant.name, restaurant.id) return output
530a03f17bb28e7967c375d7da6f6e077584cd37
3,637,907
def split_pkg(pkg): """nice little code snippet from isuru and CJ""" if not pkg.endswith(".tar.bz2"): raise RuntimeError("Can only process packages that end in .tar.bz2") pkg = pkg[:-8] plat, pkg_name = pkg.split("/") name_ver, build = pkg_name.rsplit("-", 1) name, ver = name_ver.rsplit("-", 1) return plat, name, ver, build
3568fc28c54e7de16e969be627804fbb80938d65
3,637,909
def gaussian(k, x): """ gaussian function k - coefficient array, x - values """ return k[2] * np.exp( -(x - k[0]) * (x - k[0]) / (2 * k[1] * k[1])) + k[3]
f58279de58992efd34bd1fa84bbecc64e3dd52ee
3,637,910
def coins(n, arr): """ Counting all ways e.g.: (5,1) and (1,5) """ # Stop case if n < 0: return 0 if n == 0: return 1 ways = 0 for i in range(0, len(arr)): ways += coins(n - arr[i], arr) return ways
cb269db7aef58ae2368a6e6dc04ce6743ebd3d0e
3,637,912
def compute_diff(old, new): """ Compute a diff that, when applied to object `old`, will give object `new`. Do not modify `old` or `new`. """ if not isinstance(old, dict) or not isinstance(new, dict): return new diff = {} for key, val in new.items(): if key not in old: diff[key] = val elif old[key] != val: diff[key] = compute_diff(old[key], val) for key in old: if key not in new: diff[key] = "$delete" return diff
f6e7674faa2a60be17994fbd110f8e1d67eb9886
3,637,913
def assign_nuts1_to_lad(c, lu=_LAD_NUTS1_LOOKUP): """Assigns nuts1 to LAD""" if c in lu.keys(): return lu[c] elif c[0] == "S": return "Scotland" elif c[0] == "W": return "Wales" elif c[0] == "N": return "Northern Ireland" else: return np.nan
7d9ceb2d2eaedf72eef8243d5880b547c989d2fb
3,637,915
async def get_all_persons(): """List of all people.""" with Session(DB.engine) as session: persons = session.query(Person).all() return [p.to_dict() for p in persons]
455533d6ee6b4139354c524d6fd6db29ff2ad123
3,637,916
from typing import List from typing import Dict def pivot_pull(pull: List[Dict[str, str]]): """Pivot so columns are measures and rows are dates.""" parsed_pull = parse_dates(pull) dates = sorted(list(set(row["sample_date"] for row in parsed_pull))) pivot = list() for date in dates: row = {"sample_date": date} observations = [row for row in parsed_pull if row["sample_date"] == date] for measure in MEASUREMENT_GROUPS: observation = [row for row in observations if row["parameter"] == measure] if len(observation) != 1: raise ValueError( "Should only have one value per date observation combo." ) row[measure] = observation[0]["numeric_result"] pivot.append(row) return pivot
53d945cff023c9cb0233b3198a89da1e57ba18d6
3,637,917
def _location_sensitive_score(W_query, W_fil, W_keys): """Impelements Bahdanau-style (cumulative) scoring function. This attention is described in: J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Ben- gio, “Attention-based models for speech recognition,” in Ad- vances in Neural Information Processing Systems, 2015, pp. 577–585. ############################################################################# hybrid attention (content-based + location-based) f = F * α_{i-1} energy = dot(v_a, tanh(W_keys(h_enc) + W_query(h_dec) + W_fil(f) + b_a)) ############################################################################# Args: W_query: Tensor, shape "[batch_size, 1, attention_dim]" to compare to location features. W_location: processed previous alignments into location features, shape "[batch_size, max_time, attention_dim]" W_keys: Tensor, shape "[batch_size, max_time, attention_dim]", typically the encoder outputs. Returns: A "[batch_size, max_time]" attention score (energy) """ # Get the number of hidden units from the trailing dimension of keys dtype = W_query.dtype num_units = W_keys.shape[-1].value or array_ops.shape(W_keys)[-1] v_a = tf.get_variable( "attention_variable_projection", shape=[num_units], dtype=dtype, initializer=tf.contrib.layers.xavier_initializer()) b_a = tf.get_variable( "attention_bias", shape=[num_units], dtype=dtype, initializer=tf.zeros_initializer()) return tf.reduce_sum(v_a * tf.tanh(W_keys + W_query + W_fil + b_a), [2])
4c91f7f682c1a06303c877a81f434cb265dcb1af
3,637,918
def dh_noConv( value, pattern, limit ): """decoding helper for a single integer value, no conversion, no rounding""" return dh( value, pattern, encNoConv, decSinglVal, limit )
55c2306efc1873a283fc4ed24be6677816029122
3,637,919
def chooseFile(): """ Parameters ---------- None No parameters are specified. Returns ------- filenames: tuple A tuple that contains the list of files to be loaded. """ ## change the wd to dir containing the script curpath = os.path.dirname(os.path.realpath(__file__)) os.chdir(curpath) root = Tk() root.withdraw() filenames = askopenfilename(parent= root, filetypes = (("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*")), multiple= True) if len(filenames) == 1: print len(filenames), " file is loaded." elif len(filenames) > 1: print len(filenames), " files are loaded." else: print "No files are loaded." return filenames
480125e9cef6e2334dd21a113fead441388b1f10
3,637,920
def reward_strategy(orig_reward, actualperf, judgeperf, weight={'TP':1, 'TN': 1, 'FP': -1, 'FN':-1}): """ """ assert list(weight.keys()) == ['TP', 'TN', 'FP', 'FN'], "Please assign weights to TP, TN, FP and FN." # assert sum(weight.values()) == 0, "Summation of weight values needs to be 0." if actualperf & judgeperf: cond = 'TP' elif (not actualperf) & (not judgeperf): cond = 'TN' elif (not actualperf) & judgeperf: cond = 'FP' elif actualperf & (not judgeperf): cond = 'FN' else: pass reward = orig_reward + weight[cond] reward = round(reward, 2) return reward
3bed44a11197898a94939ed2cc9a400243f604b6
3,637,921
def get_user_ids_from_primary_location_ids(domain, location_ids): """ Returns {user_id: primary_location_id, ...} """ result = ( UserES() .domain(domain) .primary_location(location_ids) .non_null('location_id') .fields(['location_id', '_id']) .run().hits ) ret = {} for r in result: if 'location_id' in r: loc = r['location_id'] ret[r['_id']] = loc return ret
9707cda74324c983add4872ca4b27057b7ab8809
3,637,922
def get_next_states(state: State): """Create new states, but prioritize the following: asdjkgnmweormelfkmw Prioritize nothing... """ out = [] # First we check hallways. for i in HALLWAY_IND: # Check if the room has any crabs hall = state.rooms[i] if hall.is_empty(): continue # Get the crab crab, crab_pos = hall.get_next() # Get target room target_room = enum2room[crab] if state.rooms[target_room].is_empty(): # Wait, first we need to see if we can move it to the room if i < target_room: # Hallway is on the left of the room left = i right = target_room else: left = target_room right = i but_can_it_move = True for j in range(left, right): if j % 2: continue if j == i: continue if state.rooms[j].has_space(): continue but_can_it_move = False break if but_can_it_move: # We can move the crab! new_state = _deepcopy(state) # Calculate the new cost # The path is the current position of the crab in the current # hallway, then the position in the target room and finaly # the move between the hallways and rooms target_position = state.rooms[target_room].get_position() move = abs(target_room - i) new_cost = (crab_pos + target_position + move) * crab # Apply changes to the state new_state.rooms[i].pos[crab_pos] = E new_state.rooms[target_room].pos[target_position - 1] = crab new_state.count_completed_rooms() out.append((new_cost, new_state)) for i in ROOMS_INDIC: # Check if room is complete room = state.rooms[i] if room.is_complete(): continue if room.is_empty(): continue # The room is not complete so we have to move the topmost crab out. crab, crab_pos = room.get_next() # See where it has to go target_room = enum2room[crab] # See if target room is empty so we can directly move in to the # target room if state.rooms[target_room].is_empty(): if i < target_room: left = i right = target_room else: left = target_room right = i but_can_it_move = True for j in range(left, right): if j % 2: # Other rooms continue if j == i: continue if state.rooms[j].has_space(): continue but_can_it_move = False break if but_can_it_move: new_state = _deepcopy(state) target_position = state.rooms[target_room].get_position() # Calculate the new state move = abs(target_room - i) + 1 new_cost = (crab_pos + move + target_position) * crab # Apply changes new_state.rooms[i].pos[crab_pos] = E new_state.rooms[target_room].pos[target_position - 1] = crab new_state.count_completed_rooms() out.append((new_cost, new_state)) # Well now let's see if we can move to a halway for j in HALLWAY_IND: # We fill all the hallways. All of them... hall = state.rooms[j] if hall.has_space(): # We can move it here. but_can_it_move = True if i < j: left = i right = j else: left = j right = i for l in range(left, right): if l == j: # Ignore target hall continue if l % 2: # Ignore rooms continue if state.rooms[l].is_empty(): continue but_can_it_move = False break if but_can_it_move: # Fill all possible positions for this hallway. for k in range(hall.s -1, -1, -1): if hall.pos[k]: continue new_state = _deepcopy(state) move = abs(i - j) new_cost = (crab_pos + k + 1 + move) * crab # Make the change new_state.rooms[i].pos[crab_pos] = E new_state.rooms[j].pos[k] = crab new_state.count_completed_rooms() out.append((new_cost, new_state)) return out
fdc270ef292ce1c1507937975743f8877844b063
3,637,923
def _build_trainstep(fcn, projector, optimizer, strategy, temp=1, tau_plus=0, beta=0, weight_decay=0): """ Build a distributed training step for SimCLR or HCL. Set tau_plus and beta to 0 for SimCLR parameters. :model: Keras projection model :optimizer: Keras optimizer :strategy: tf.distribute.Strategy object :temp: temperature parameter :tau_plus: HCL class probability parameter :beta: HCL concentration parameter :weightdecay: L2 loss coefficient. 0 to disable Returns a distributed training function """ trainvars = fcn.trainable_variables + projector.trainable_variables def _step(x1, m1, x2, m2): with tf.GradientTape() as tape: loss = 0 # get replica context- we'll use this to aggregate embeddings # across different GPUs context = tf.distribute.get_replica_context() #print("x,y:", x.shape, y.shape) # run images through model and normalize embeddings. do this # in three steps: # 1) compute features with FCN (N, w, h, feature_dim) # 2) compute segment-weighted features (N*num_samples, feature_dim) # 3) compute projections z (N*num_samples, d) x1 = fcn(x1, training=True) hm1 = _prepare_embeddings(x1, m1) z1 = tf.nn.l2_normalize(projector(hm1, training=True), 1) x2 = fcn(x2, training=True) hm2 = _prepare_embeddings(x2, m2) z2 = tf.nn.l2_normalize(projector(hm2, training=True), 1) # mask out all positive pairs where one mask or the other # is empty mask = tf.stop_gradient(_prepare_mask(m1, m2)) # aggregate projections across replicas. z1 and z2 should # now correspond to the global batch size (gbs*num_samples, d) z1 = context.all_gather(z1, 0) z2 = context.all_gather(z2, 0) print("z1,z2:", z1.shape, z2.shape) mask = context.all_gather(mask, 0) print("mask:", mask.shape) with tape.stop_recording(): gbs = z1.shape[0] negmask = _build_negative_mask(gbs) # SimCLR loss case if (tau_plus == 0)&(beta == 0): softmax_prob, nce_batch_acc = _simclr_softmax_prob(z1, z2, temp, negmask) # HCL loss case elif (tau_plus > 0)&(beta > 0): softmax_prob, nce_batch_acc = _hcl_softmax_prob(z1, z2, temp, beta, tau_plus, negmask) else: assert False, "both tau_plus and beta must be nonzero to run HCL" softmax_loss = tf.reduce_mean(-1*mask*tf.math.log(softmax_prob)) loss += softmax_loss if weight_decay > 0: l2_loss = compute_l2_loss(fcn) + compute_l2_loss(projector) loss += weight_decay*l2_loss else: l2_loss = 0 grad = tape.gradient(loss, trainvars) optimizer.apply_gradients(zip(grad, trainvars)) return {"loss":loss, "nt_xent_loss":softmax_loss, "l2_loss":l2_loss, "nce_batch_accuracy":nce_batch_acc} @tf.function def trainstep(x1, m1, x2, m2): per_example_losses = strategy.run(_step, args=(x1, m1, x2, m2)) lossdict = {k:strategy.reduce( tf.distribute.ReduceOp.MEAN, per_example_losses[k], axis=None) for k in per_example_losses} return lossdict return trainstep
2ceb7aa171835b45376f11e28fd4fe323d1ac7f1
3,637,924
def get_environment(): """ Light-weight routine for reading the <Environment> block: does most of the work through side effects on PETRglobals """ ValidExclude = None ValidInclude = None ValidOnly = True ValidPause = 0 #PETRglobals.CodeWithPetrarch1 = True #PETRglobals.CodeWithPetrarch2 = False line = fin.readline() while len(line) > 0 and not line.startswith("<Environment>"): # loop through the file line = fin.readline() if len(line) == 0: print("Can't find <Environment> block") exit() line = fin.readline() while "</Environment>" not in line: # loop through the file print(line[:-1]) if '<Verbfile' in line: PETRglobals.VerbFileName = line[line.find(">") + 1:line.find("</")] elif '<Actorfile' in line: PETRglobals.ActorFileList = line[line.find(">") + 1:line.find("</")].split(',') elif '<Agentfile' in line: PETRglobals.AgentFileList = line[line.find(">") + 1:line.find("</")].split(',') elif '<Discardfile' in line: PETRglobals.DiscardFileName = line[line.find(">") + 1:line.find("</")] elif '<PICOfile' in line: PETRglobals.InternalCodingOntologyFileName = line[line.find(">") + 1:line.find("</")] elif '<Include' in line: ValidInclude = line[line.find(">") + 1:line.find("</")].split() print('<Include> categories', ValidInclude) if 'valid' in ValidInclude: ValidOnly = True ValidInclude.remove('valid') elif '<Exclude' in line: ValidExclude = line[line.find(">") + 1:line.find("</")].split() print('<Exclude> categories', ValidExclude) elif '<Pause' in line: theval = line[line.find(">") + 1:line.find("</")] if 'lways' in theval: ValidPause = 1 # skip first char to allow upper/lower case elif 'ever' in theval: ValidPause = 2 elif 'top' in theval: ValidPause = 3 line = fin.readline() print(PETRglobals.VerbFileName, PETRglobals.ActorFileList[0], PETRglobals.AgentFileList[0], PETRglobals.DiscardFileName) print(ValidInclude, ValidExclude) print(ValidPause, ValidOnly) return ValidInclude, ValidExclude, ValidPause, ValidOnly
966cb1ad713f5b0c87cdabe12475b4239d5b7469
3,637,926
def create_variables_from_samples(sample_z_logits, sample_z_logp, sample_b, batch_index, sequence_index): """ Create the variables for RELAX control variate. Assumes sampled tokens come from decoder. :param sample_z_logits: [B,T,V] tensor containing sampled processed logits created by stacking logits during decoding loop of sampling process :param sample_z_logp: [B,T,V] tensor containing sampled processed logp created by stacking logp during decoding loop of sampling process :param sample_b: the [B,T] tensor containing the H(z) indices (Gumbel-Max) :param batch_index: [B,T] tensor of the batch size repeated for seq len :param sequence_index: [B,T] tensor of range(0, seq len) :return: z_tilde, and logp(b) for equation """ v = tf.random_uniform(shape=sample_z_logp.get_shape().as_list(), minval=1e-8, maxval=1, dtype=tf.float32) # create index tensor where b is the argmax, to use as indexer for substitution b_new = tf.cast(tf.squeeze(sample_b, 0), tf.int64) # assumes sample_b = [BxT] index_tensor_b = tf.expand_dims(tf.stack([batch_index, sequence_index, b_new], axis=1), 0) v_b = tf.gather_nd(v, index_tensor_b) # values of v where b are the argmax indexes update = -tf.log(-tf.log(v_b)) # for i == b # create z_tilde as for the case where i != b clipped_logit_probs = tf.clip_by_value(tf.math.softmax(sample_z_logits, axis=2), 1e-8, 1.0) z_tilde = -tf.log(-tf.div(tf.log(v), clipped_logit_probs) - tf.expand_dims(tf.log(v_b), 2)) z_tilde = tf.tensor_scatter_nd_update(z_tilde, index_tensor_b, update) logp_b = tf.gather_nd(sample_z_logp, index_tensor_b) # used in loss func return z_tilde, logp_b
615e73b136b16979257eb5b32ec9a696c17730be
3,637,927
from typing import OrderedDict import copy def get2DHisto_(detector,plotNumber,geometry): """ This function opens the appropiate ROOT file, extracts the TProfile2D and turns it into a Histogram, if it is a compound detector, this function takes care of the subdetectors' addition. Note that it takes plotNumber as opposed to plot """ histo = None rootFile = TFile() detectorFilename = 'matbdg_%s_%s.root'%(detector,geometry) if detector not in COMPOUNDS.keys() or checkFile_(detectorFilename): if not checkFile_(detectorFilename): print('Warning: %s not found' % detectorFilename) return 0 rootFile = TFile.Open(detectorFilename,'READ') prof = rootFile.Get("%d" % plotNumber) if not prof: return 0 # Prevent memory leaking by specifing a unique name prof.SetName('%u_%s_%s' %(plotNumber,detector,geometry)) prof.__class__ = TProfile2D histo = prof.ProjectionXY() else: histos = OrderedDict() theFiles = [] for subDetector in COMPOUNDS[detector]: subDetectorFilename = 'matbdg_%s_%s.root' % (subDetector,geometry) if not checkFile_(subDetectorFilename): print('Warning: %s not found'%subDetectorFilename) continue subDetectorFile = TFile.Open(subDetectorFilename,'READ') theFiles.append(subDetectorFile) print('*** Open file... %s' % subDetectorFilename) prof = subDetectorFile.Get('%d'%plotNumber) if not prof: return 0 prof.__class__ = TProfile2D if not histo: histo = prof.ProjectionXY('B_%s' % prof.GetName()) else: histo.Add(prof.ProjectionXY('B_%s' % prof.GetName())) return copy.deepcopy(histo)
5759bc16686642e377c9bd37dde73374f74870ac
3,637,928
import shlex import json import traceback import time def binlog2sql(request): """ 通过解析binlog获取SQL :param request: :return: """ instance_name = request.POST.get('instance_name') save_sql = True if request.POST.get('save_sql') == 'true' else False instance = Instance.objects.get(instance_name=instance_name) no_pk = True if request.POST.get('no_pk') == 'true' else False flashback = True if request.POST.get('flashback') == 'true' else False back_interval = 0 if request.POST.get('back_interval') == '' else int(request.POST.get('back_interval')) num = 30 if request.POST.get('num') == '' else int(request.POST.get('num')) start_file = request.POST.get('start_file') start_pos = request.POST.get('start_pos') if request.POST.get('start_pos') == '' else int( request.POST.get('start_pos')) end_file = request.POST.get('end_file') end_pos = request.POST.get('end_pos') if request.POST.get('end_pos') == '' else int(request.POST.get('end_pos')) stop_time = request.POST.get('stop_time') start_time = request.POST.get('start_time') only_schemas = request.POST.getlist('only_schemas') only_tables = request.POST.getlist('only_tables[]') only_dml = True if request.POST.get('only_dml') == 'true' else False sql_type = ['INSERT', 'UPDATE', 'DELETE'] if request.POST.getlist('sql_type[]') == [] else request.POST.getlist( 'sql_type[]') # 校验sql_type if [i for i in sql_type if i not in ['INSERT', 'UPDATE', 'DELETE']]: return JsonResponse({'status': 1, 'msg': '类型过滤参数不正确', 'data': {}}) # flashback=True获取DML回滚语句 result = {'status': 0, 'msg': 'ok', 'data': ''} # 提交给binlog2sql进行解析 binlog2sql = Binlog2Sql() # 准备参数 args = {"conn_options": fr"-h{shlex.quote(str(instance.host))} -u{shlex.quote(str(instance.user))} \ -p'{shlex.quote(str(instance.password))}' -P{shlex.quote(str(instance.port))} ", "stop_never": False, "no-primary-key": no_pk, "flashback": flashback, "back-interval": back_interval, "start-file": start_file, "start-position": start_pos, "stop-file": end_file, "stop-position": end_pos, "start-datetime": '"'+start_time+'"', "stop-datetime": '"'+stop_time+'"', "databases": ' '.join(only_schemas), "tables": ' '.join(only_tables), "only-dml": only_dml, "sql-type": ' '.join(sql_type), "instance": instance } # 参数检查 args_check_result = binlog2sql.check_args(args) if args_check_result['status'] == 1: return HttpResponse(json.dumps(args_check_result), content_type='application/json') # 参数转换 cmd_args = binlog2sql.generate_args2cmd(args, shell=True) # 执行命令 try: p = binlog2sql.execute_cmd(cmd_args, shell=True) # 读取前num行后结束 rows = [] n = 1 for line in iter(p.stdout.readline, ''): if n <= num: n = n + 1 row_info = {} try: row_info['sql'] = line.split('; #')[0] + ";" row_info['binlog_info'] = line.split('; #')[1].rstrip('\"') except IndexError: row_info['sql'] = line row_info['binlog_info'] = None rows.append(row_info) else: break if rows.__len__() == 0: # 判断是否有异常 stderr = p.stderr.read() if stderr: result['status'] = 1 result['msg'] = stderr return HttpResponse(json.dumps(result), content_type='application/json') # 终止子进程 p.kill() result['data'] = rows except Exception as e: logger.error(traceback.format_exc()) result['status'] = 1 result['msg'] = str(e) # 异步保存到文件 if save_sql: args.pop('conn_options') async_task(binlog2sql_file, args=args, user=request.user, hook=notify_for_binlog2sql, timeout=-1, task_name=f'binlog2sql-{time.time()}') # 返回查询结果 return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True), content_type='application/json')
82cf06637024a0feb2c2ae0203cd795d3f6eb944
3,637,929
def smtp_config_generator_str(results, key, inp): """ Set server/username config. :param kwargs: Values. Refer to `:func:smtp_config_writer`. :type kwargs: dict :param key: Key for results dict. :type key: str :param inp: Input question. :type inp: str """ if results[key] is None: results[key] = input(inp) return results
f2cccfaf569f005e03bb351379db85de7146eda0
3,637,930
def default_rollout_step(policy, obs, step_num): """ The default rollout step function is the policy's compute_action function. A rollout step function allows a developer to specify the behavior that will occur at every step of the rollout--given a policy and the last observation from the env--to decide what action to take next. This usually involves the rollout's policy and may perform learning. It also, may involve using, updating, or saving learning related state including hyper-parameters such as epsilon in epsilon greedy. You can provide your own function with the same signature as this default if you want to have a more complex behavior at each step of the rollout. """ return policy.compute_action(obs)
a6e9dff784e46b9a59ae34334a027b427e8d230a
3,637,932
def perfilsersic(r_e, I_e, n, r): """Evaluate a Sersic Profile. funcion que evalua a un dado radio r el valor de brillo correspondiente a un perfil de sersic r_e : Radio de escala I_e : Intensidad de escala n : Indice de Sersic r : Radio medido desde el centro en pixeles """ b = 1.999 * n - 0.327 I_r = I_e * np.exp(-b * (((r / r_e) ** (1 / np.float(n))) - 1)) I_r = I_r / (I_e * np.exp(-b * (((0.0 / r_e) ** (1 / np.float(n))) - 1))) return I_r
b8cd900d28be3fef1efc142c07012174f30c9f9d
3,637,933
import numpy as np from scipy import interpolate def background_profile(img, smo1=30, badval=None): """ helper routine to determine for the rotated image (spectrum in rows) the background using sigma clipping. """ bgimg = img.copy() nx = bgimg.shape[1] # number of points in direction of dispersion ny = bgimg.shape[0] # width of the image # look at the summed rows of the image u_ysum = [] for i in range(ny): u_ysum.append(bgimg[i,:].mean()) u_ysum = np.asarray(u_ysum) u_ymask = sigclip1d_mask(u_ysum, 2.5, badval=badval, conv=1e-5, maxloop=30) u_ymean = u_ysum[u_ymask].mean() # look at the summed columns after filtering bad rows u_yindex = np.where(u_ymask)[0] u_xsum = [] u_std = [] for i in range(nx): u_x1 = bgimg[u_yindex, i].squeeze() # clip u_x1 u_x1mask = sigclip1d_mask(u_x1, 2.5, badval=None, conv=1e-5, maxloop=30) u_xsum.append(u_x1[u_x1mask].mean()) u_std.append(u_x1[u_x1mask].std()) #print u_x1[u_x1mask] #if np.isfinite(u_x1mask.mean()) & len(u_x1[u_x1mask])>0: # print "%8.2f %8.2f %8.2f "%(u_x1[u_x1mask].mean(),u_x1[u_x1mask].std(),u_x1[u_x1mask].max()) # the best background estimate of the typical row is now u_xsum # fit a smooth spline through the u_xsum values (or boxcar?) #print "u_x means " #print u_xsum u_xsum = np.asarray(u_xsum) u_std = np.asarray(u_std) u_xsum_ok = np.isfinite(u_xsum) bg_tcp = interpolate.splrep(np.arange(nx)[u_xsum_ok], np.asarray(u_xsum)[u_xsum_ok], s=smo1) # representative background profile in column u_x = interpolate.splev(np.arange(nx), bg_tcp, ) return u_xsum, u_x, u_std
59b090a2c05d8a520a3c9f980885c9488bdc7615
3,637,934
def get_object(bucket,key,fname): """Given a bucket and a key, upload a file""" return aws_s3api(['get-object','--bucket',bucket,'--key',key,fname])
6687c657ba364757bd519f370c546ad9b7b033f7
3,637,935
import glob def find_file(filename): """ This helper function checks whether the file exists or not """ file_list = list(glob.glob("*.txt")) if filename in file_list: return True else: return False
42895e66e258ba960c890f871be8c261aec02852
3,637,936
def tweetnacl_crypto_secretbox(max_messagelength=256): """ max_messagelength: maximum length of the message, in bytes. i.e., the symbolic execution will not consider messages longer than max_messagelength """ proj = tweetnaclProject() state = funcEntryState(proj, "crypto_secretbox_xsalsa20poly1305_tweet", [ ("c", pointerToUnconstrainedPublic()), # Output parameter, will hold ciphertext, length 'mlen' ("m", pointerToUnconstrainedPublic()), # message: length 'mlen' ("mlen", publicValue()), # length of message. Not a pointer ("n", pointerTo(secretArray(24), 24)), # nonce, buffer of size crypto_secretbox_NONCEBYTES ("k", pointerTo(secretArray(32), 32)) # secret key: size 32 bytes ]) state.add_constraints(getArgBVS(state, 'mlen') <= max_messagelength) addDevURandom(state) return (proj, state)
b380c2848da0c271895dcf893adf1d12c5d86289
3,637,938
def parameterized_dropout(probs: Tensor, mask: Tensor, values: Tensor, random_rate: float = 0.5, epsilon: float = 0.1) -> Tensor: """ This function returns (values * mask) if random_rate == 1.0 and (values * probs) if random_rate == 0.0 or if we are in eval mode (self.training == false). Otherwise, it randomly selects on frame-by-frame / vector-by-vector basis, which of the two to use. The main point of this function is that it intelligently backpropagates derivatives in such a way that you can meaningfully train `probs`. See the function `get_derivative_scales()` to understand the central point of how we get derivatives w.r.t. `probs`. Args: probs: the probabilities with which the `mask` vector was chosen; we'll be able to compute derivatives w.r.t. this. A Tensor of shape (*, C) where C is interpreted as the channel dimension. These must be in the interval [0,1]. mask: A (possibly boolean) Tensor of shape (*, C) and values 0/False or 1/True, True/1 if this value is to be "passed through". The caller asserts that these values have been chosen with probabilities equal to `probs`, e.g. as: mask = (torch.rand_like(probs) < probs) (In practice we may be sampling with a more complicated method which has marginal probabilities equal to `probs`; the correctness of the derivatives becomes a little weaker in that case). values: A Tensor of shape (*, C), the same as probs_and mask; these are the values that are to be multiplied by a mask (or sometimes scaled by `probs`, if random_rate < 1). The derivatives backpropagated to here are exact, i.e. just output_grad * mask. We currently require that elements of values be in the interval [0,1] (this is needed for a formula involving epsilon). random_rate: A float value that determines how often we use the zero-one mask; the rest of the time, we use the expected value (probs). epsilon: A float value used to prevent division by zero in backprop; controls a bias-variance tradeoff in derivatives (small->lower bias, higher variance). Returns: A Tensor with the same shape as `probs`, `mask` and `values`, i.e. (*, C), which is randomly somewhere between values * mask and values * probs. """ return _ParameterizedDropout.apply(probs, mask, values, random_rate, epsilon)
36d26d0deda5b4394457e235e61f334ea6dc767d
3,637,939
from typing import Optional def get_auto_scale_v_core(resource_group_name: Optional[str] = None, vcore_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAutoScaleVCoreResult: """ Represents an instance of an auto scale v-core resource. Latest API Version: 2021-01-01. :param str resource_group_name: The name of the Azure Resource group of which a given PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no more than 90. :param str vcore_name: The name of the auto scale v-core. It must be a minimum of 3 characters, and a maximum of 63. """ pulumi.log.warn("""get_auto_scale_v_core is deprecated: The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:powerbidedicated:getAutoScaleVCore'.""") __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['vcoreName'] = vcore_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:powerbidedicated/latest:getAutoScaleVCore', __args__, opts=opts, typ=GetAutoScaleVCoreResult).value return AwaitableGetAutoScaleVCoreResult( capacity_limit=__ret__.capacity_limit, capacity_object_id=__ret__.capacity_object_id, id=__ret__.id, location=__ret__.location, name=__ret__.name, provisioning_state=__ret__.provisioning_state, sku=__ret__.sku, system_data=__ret__.system_data, tags=__ret__.tags, type=__ret__.type)
e3eda57b7afdfe2a7e1b7e3e958b5140a7120a95
3,637,940
import json def text_output(xml,count): """Returns JSON-formatted text from the XML retured from E-Fetch""" xmldoc = minidom.parseString(xml.encode('utf-8').strip()) jsonout = [] for i in range(count): title = '' title = xmldoc.getElementsByTagName('ArticleTitle') title = parse_xml(title, i, '') pmid = '' pmid = xmldoc.getElementsByTagName('PMID') pmid = parse_xml(pmid, i, '') abstract = '' abstract = xmldoc.getElementsByTagName('AbstractText') abstract = parse_xml(abstract, i, '') try: authors = xmldoc.getElementsByTagName('AuthorList') authors = authors[i].getElementsByTagName('Author') authorlist = [] for author in authors: LastName = author.getElementsByTagName('LastName') LastName = parse_xml(LastName, 0, '') Initials = author.getElementsByTagName('Initials') Initials = parse_xml(Initials, 0, '') if LastName != '' and Initials != '': author = '%s, %s' % (LastName, Initials) else: author = '' authorlist.append(author) except Exception: authorlist = [] pass try: journalinfo = xmldoc.getElementsByTagName('Journal')[i] journalIssue = journalinfo.getElementsByTagName('JournalIssue')[0] except Exception: journalinfo = None journalIssue = None pass journal = '' year = '' volume = '' issue = '' pages = '' if journalinfo != None: journal = parse_xml(journalinfo.getElementsByTagName('Title'), 0, '') year = journalIssue.getElementsByTagName('Year') year = parse_xml(year, 0, '') volume = journalIssue.getElementsByTagName('Volume') volume = parse_xml(volume, 0, '') issue = journalIssue.getElementsByTagName('Issue') issue = parse_xml(issue, 0, '') pages = xmldoc.getElementsByTagName('MedlinePgn') pages = parse_xml(pages, 0, '') jsonout.append({ 'pmid':pmid, 'title':title, 'authors':authorlist, 'journal':journal, 'year':year, 'volume':volume, 'issue':issue, 'pages':pages, 'abstract':abstract }) return json.dumps(jsonout)
0c48a67b123b55ed5c8777d5fd0ad009578ba1ae
3,637,941
from datetime import datetime def datetime2str(target, fmt='%Y-%m-%d %H:%M:%S'): """ 将datetime对象转换成字符串 :param target: datetime :param fmt: string :return: string """ return datetime.datetime.strftime(target, fmt)
9111040a6136ef675929d30f3aba3eb983b45197
3,637,942
def periodic_targets_form(request, program): """ Returns a form for the periodic targets sub-section, used by the Indicator Form For historical reasons, the input is a POST of the whole indicator form sent via ajax from which a subset of fields are used to generate the returned template """ if not request.has_write_access: raise PermissionDenied program = get_object_or_404(Program, pk=program) form = PTFormInputsForm(data=request.POST) if not form.is_valid(): return JsonResponse(form.errors) event_name = '' start_date = '' target_frequency_num_periods = 1 target_frequency_type = form.cleaned_data.get('target_frequency') if target_frequency_type in Indicator.REGULAR_TARGET_FREQUENCIES: start_date = program.reporting_period_start target_frequency_num_periods = len( [p for p in PeriodicTarget.generate_for_frequency( target_frequency_type)(start_date, program.reporting_period_end)]) generated_targets = generate_periodic_targets( target_frequency_type, start_date, target_frequency_num_periods, event_name) dummy_indicator = Indicator( target_frequency=target_frequency_type, unit_of_measure_type=form.cleaned_data.get('unit_of_measure_type'), is_cumulative=False, ) content = render_to_string('indicators/indicatortargets.html', { 'indicator': dummy_indicator, 'periodic_targets': generated_targets }) return JsonResponse({ 'content': content, })
62e6ef666f113c5aefda858e91c31f3dfd0bcacf
3,637,943
import sqlite3 def get_db(): """Returns an sqlite3.Connection object stored in g. Or creates it if doesn't exist yet.""" db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db
1a8be7a3d42123db213cd4c2a5968bdede92e677
3,637,944
def is_string_like(obj): # from John Hunter, types-free version """Check if obj is string.""" return isinstance(obj, basestring)
5b3b66dd0706f1f0e0257ea50ba48f463a07d6ca
3,637,945
import json def _export_gene_set_pan_genome(meth, pan_genome_id): """Export orthologs from Pangenome as external FeatureSet objects. [26] :param pan_genome_id: ID of pangenome object [26.1] :type pan_genome_id: kbtypes.KBaseGenomes.Pangenome :ui_name pan_genome_id: Pangenome ID :return: Generated Compare Genome :rtype: kbtypes.KBaseGenomes.Pangenome :output_widget: kbasePanGenome """ meth.stages = 1 # for reporting progress return json.dumps({'ws': meth.workspace_id, 'name': pan_genome_id, 'withExport': 'true'})
5dfc5a6d253a66cf7ff50c736f9fdaa43a2334a8
3,637,946
def makeId(timestamp=0, machine=0, flow=0): """ using unix style timestamp, not python timestamp """ timestamp -= _base return (timestamp << 13) | (machine << 8) | flow
0443714cd5e87c93dc8ee8a156cd406f481c6d82
3,637,949
import time def _get_token(cls, token_type): """ when token expire flush,return token value """ assert token_type in ['tenant_access_token', 'app_access_token'], token_type if not hasattr(cls.request, token_type) or hasattr(cls.request, token_type) or\ time.time() >= getattr(cls.request, token_type)['expire']: setattr(cls.request, token_type, getattr(cls, 'get_%s' % token_type)()) return getattr(cls.request, token_type)[token_type]
15ee9c6926f929960b20ee68901f1d675f43639a
3,637,950
from typing import Iterator def chunk(it: Iterator, size: int) -> Iterator: """ Nice chunking method from: https://stackoverflow.com/a/22045226 """ it = iter(it) return iter(lambda: tuple(islice(it, size)), ())
8cd199b1d2092373a156dac74cd80b700fb70fcd
3,637,951
def sort_by_directory(path): """returns 0 if path is a directory, otherwise 1 (for sorting)""" return 1 - path.is_directory
1cd066e69885901ae1b2b167feb061e98ed5f3ed
3,637,952
import json def read_config(config): """ Read config file containing information of type and default values of fields :param config: path to config file :return: dictionary containing type and or default value for each field in the file """ dic_types = json.load(open(config, 'r')) to_remove = [] for attribute, value in dic_types.items(): ls_val = value.keys() if 'type' in ls_val: val = value['type'] value['type'] = str_to_type(val) none_type = False if not value['type']: none_type = True if not 'default' in ls_val and none_type: to_remove.append(attribute) value['type'] = val for to_rm in to_remove: print(' [WARN] Config for' , '\'' + to_rm + '\'', 'incorrect and ommitted: Type', '\'' + dic_types[to_rm]['type'] + '\'' , 'is not valid and no default value is indicated') del dic_types[to_rm] return dic_types
ebdf6a001f65fb2ad2c3da6015a5b8998f1fda4a
3,637,953
def is_right_hand_coordinate_system3(pose): """Checks whether the given pose follows the right-hand rule.""" n, o, a = pose[:3, 0], pose[:3, 1], pose[:3, 2] return n.dot(n).simplify() == 1 and o.dot(o).simplify() == 1 and a.dot(a).simplify() == 1 and sp.simplify(n.cross(o)) == a
f6b1fcff1d3502c78db294fe2ad496a214c13366
3,637,954
def model_airmassfit(hjd, am, rawflux, limbB1, limB2, inc, period, a_Rs, Rp_Rs, show=False): """ Return the bestfit model for the lightcurve using 4 models of airmass correction: 1. model with no airmass correction 2. model with exponential airmass correction 3. model with linear airmass correction 4, model with 2deg polynomial airmass correction ___ INPUT: hjd: am: rawflux: limbB1: limbB2: inc: period: a_Rs: startpar: OUTPUT: result: dataframe structure with besfit values for each model, the errors and BIC values. phase: from the bestfit model lc: lightcurve from the bestfit model """ # Model 1: no airmass correction startpar = [Rp_Rs, np.mean(hjd), 1., 0.] PARINFO = [{'value':Rp_Rs,'limits':(0,1.)}, {'value':np.mean(hjd)}, {'value':1.}, {'value':0.,'fixed':True}] pfit1, results1 = mpyfit.fit(residuals_am_exp, startpar, args = (hjd,rawflux,eflux), parinfo=PARINFO) model1 = model_am_exp(hjd,pfit1[0],pfit1[1],pfit1[2],pfit1[3]) phase1 = (hjd - pfit1[1])/period if show == True: print '...' print 'Model 1: no airmass correction' print 'bestfit values = ',pfit1 print 'error = ', results1['parerrors'] print 'bestnorm1 = ', results1['bestnorm'] print 'chi-square, scipy routine = ',chisquare(rawflux, model1) #Model 2: exponential airmass correction PARINFO = [{'value':Rp_Rs,'limits':(0,1.)}, {'value':np.mean(hjd)}, {'value':1.}, {'value':0.,'fixed':False}] pfit2, results2 = mpyfit.fit(residuals_am_exp, startpar, args = (hjd,rawflux,eflux), parinfo=PARINFO) model2 = model_am_exp(hjd,pfit2[0],pfit2[1],pfit2[2],pfit2[3]) phase2 = (hjd - pfit2[1])/period if show == True: print '...' print 'Model 2: exponential airmass correction' print 'bestfit values = ',pfit2 print 'error = ', results2['parerrors'] print 'bestnorm1 = ', results2['bestnorm'] print 'chi-square, scipy routine = ',chisquare(rawflux, model2) #Model 3: linear airmass correction PARINFO = [{'value':Rp_Rs,'limits':(0,1.)},{'value':np.mean(hjd)},{'value':1.}, {'value':0.,'fixed':False}] pfit3, results3 = mpyfit.fit(residuals_linear, startpar, args = (hjd,rawflux,eflux), parinfo=PARINFO) model3 = model_am_linear(hjd,pfit3[0],pfit3[1],pfit3[2],pfit3[3]) phase3 = (hjd - pfit3[1])/period if show == True: print '...' print 'Model 3: linear airmass correction' print 'bestfit values = ',pfit3 print 'error = ', results3['parerrors'] print 'bestnorm1 = ', results3['bestnorm'] print 'chi-square, scipy routine = ',chisquare(rawflux, model3) #Model 4: 2deg polynomial airmss correction PARINFO = [{'value':Rp_Rs,'limits':(0,1.)},{'value':np.mean(hjd)},{'value':1.},{'value':0.},{'value':0.}] pstart = [Rp_Rs,np.mean(hjd),1.,0.,0.] pfit4, results4 = mpyfit.fit(residuals_2deg_mpfit, pstart, args = (hjd,rawflux,eflux), parinfo=PARINFO) model4 = model_am_2deg(hjd,pfit4[0],pfit4[1],pfit4[2],pfit4[3],pfit4[4]) phase4 = (hjd - pfit4[1])/period if show == True: print '...' print 'Model 4: 2deg poly airmass correction' print 'bestfit values = ',pfit4 print 'error = ', results4['parerrors'] print 'bestnorm1 = ', results4['bestnorm'] print 'chi-square, scipy routine = ',chisquare(rawflux, model4) #Obtain BIC values: #Let's create our fit file and our best BIC BICarray = ['none', 'exponential', 'linear','2nd_deg_poly'] nfree = [3,4,4,5] bestnorm = [results1['bestnorm'],results2['bestnorm'],results3['bestnorm'],results4['bestnorm']] bic = BIC(nfree,bestnorm,len(rawflux)) RpRs = [pfit1[0], pfit2[0], pfit3[0], pfit4[0]] Tc = [pfit1[1], pfit2[1], pfit3[1], pfit4[1]] a = [pfit1[2], pfit2[2], pfit3[2], pfit4[2]] b = [pfit1[3], pfit2[3], pfit3[3], pfit4[3]] c = ['Nan','Nan','Nan',pfit4[4]] error1 = [results1['parerrors'][0], results2['parerrors'][0], results3['parerrors'][0], results4['parerrors'][0]] error2 = [results1['parerrors'][1], results2['parerrors'][1], results3['parerrors'][1], results4['parerrors'][1]] error3 = [results1['parerrors'][2], results2['parerrors'][2], results3['parerrors'][2], results4['parerrors'][2]] error4 = [results1['parerrors'][3], results2['parerrors'][3], results3['parerrors'][3], results4['parerrors'][3]] error5 = ['Nan','Nan','Nan', results4['parerrors'][0]] result = DataFrame([BICarray,list(bic),RpRs,error1,Tc,error2,a,error3,b,error4,c,error5]).T result.columns=['Model','BIC','RpRs','eRpRs','Tc','eTc','a','ea','b','eb','c','ec'] if show == True: print '... Results:' print result print 'The best model is: ',result.Model[result.BIC == result.BIC.min()] print 'with the BIC = ',result.BIC.min() #Saving the bestfit transit image: bestfit = np.where(result.BIC == result.BIC.min()) indx = bestfit[0][0] if indx == 0: lc = model1 phase = phase1 if indx == 1: lc = model2 phase = phase2 if indx == 2: lc = model3 phase = phase3 if indx == 3: lc = model4 phase = phase4 return result, phase, lc
6cc74f5820aff6a36fdd89c37df141d82a558dab
3,637,955
def common_params_for_list(args, fields, field_labels): """Generate 'params' dict that is common for every 'list' command. :param args: arguments from command line. :param fields: possible fields for sorting. :param field_labels: possible field labels for sorting. :returns: a dict with params to pass to the client method. """ params = {} if args.limit is not None: if args.limit < 0: raise exc.CommandError( _('Expected non-negative --limit, got %s') % args.limit) params['limit'] = args.limit if args.sort_key is not None: # Support using both heading and field name for sort_key fields_map = dict(zip(field_labels, fields)) fields_map.update(zip(fields, fields)) try: sort_key = fields_map[args.sort_key] except KeyError: raise exc.CommandError( _("%(sort_key)s is an invalid field for sorting, " "valid values for --sort-key are: %(valid)s") % {'sort_key': args.sort_key, 'valid': list(fields_map)}) params['sort_key'] = sort_key if args.sort_dir is not None: if args.sort_dir not in ('asc', 'desc'): raise exc.CommandError( _("%s is an invalid value for sort direction, " "valid values for --sort-dir are: 'asc', 'desc'") % args.sort_dir) params['sort_dir'] = args.sort_dir marker = getattr(args, 'marker', None) if marker is not None: params['marker'] = marker params['detail'] = args.detail return params
6e432213a504b2423dca4add79c860d9bffe4ad4
3,637,956
def _finditem(obj, key): """ Check if giben key exists in an object :param obj: dictionary/list :param key: key :return: value at the key position """ if key in obj: return obj[key] for k, v in obj.items(): if isinstance(v, dict): item = _finditem(v, key) if item is not None: return item
0f7c5b801acfae6a66d175163d726cba22380f7c
3,637,957
def decompress(obj): """Decompress LZSS-compressed bytes or a file-like object. Shells out to decompress_file() or decompress_bytes() depending on whether or not the passed-in object has a 'read' attribute or not. Returns a bytearray.""" if hasattr(obj, 'read'): return decompress_file(obj) else: return decompress_bytes(obj)
58f090f02e76e90606b7ec83d2f9567235b90213
3,637,958
def trailing_whitespace(text): """Gets trailing whitespace of text.""" trailing = "" while text and text[-1] in WHITESPACE_OR_NL_CHARS: trailing = text[-1] + trailing text = text[:-1] return trailing
ddb3fba9d41261f45a0ea3e0ffd03949950532ce
3,637,959
import numpy def rjust(a, width, fillchar=' '): """ Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.rjust """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = int(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'rjust', (width_arr, fillchar))
05d99fcd2600bcfee19c60b75f50af868d853a87
3,637,960
import tempfile def form_image_helper(caption_list, dummy=True, image_suffix='.jpg'): """ :param caption_list: <class 'list'> :param dummy: <class 'bool'> :param image_suffix: <class 'str'> :return: <class 'dict'> [dict of dummy images for form submission in django unittest] """ try: res = {} image = Image.new('RGB', (100, 100)) tmp_file = tempfile.NamedTemporaryFile(suffix=image_suffix) image.save(tmp_file) with open(tmp_file.name, 'rb') as fp: for title in caption_list: res[title] = fp return res except Exception as e: print(str(e)) raise ValueError(str(e))
b299ce536de33fe04821a7c1306dfff61000eed4
3,637,961
from typing import Any import inspect def is_complex_converter(obj: Any) -> bool: """Check if the object is a complex converter.`""" return isinstance(obj, ComplexConverterABC) or inspect.isclass(obj) and issubclass(obj, ComplexConverterABC)
d6069161819f348a4cec516f348ed93d59d38a74
3,637,962
def some_task(): """ Some task """ get_word_counts('python.txt') get_word_counts('go.txt') get_word_counts('erlang.txt') get_word_counts('javascript.txt') return "Task Done"
a6dcacaf22cb39b886feb4566d05b48c0e7db1e3
3,637,965
def _accelerate(f, n_devices): """JIT-compiled version of `f` running on `n_devices`.""" if n_devices == 1: return fastmath.jit(f) return fastmath.pmap(f, axis_name='batch')
f9735078b012d49e15aa16b9911b2c897f9987c1
3,637,966
from datetime import datetime def parse_shadowserver_time(time_string: Text) -> datetime.datetime: """Parse a date on the format '2018-10-17 20:36:23'""" try: return datetime.datetime.strptime(time_string[:19], '%Y-%m-%d %H:%M:%S') except: print(time_string) raise
9cf267bac24fcd4efdc73d4839493b9440c178ce
3,637,967
import random def sample_along_rays(rng, origins, directions, radii, num_samples, near, far, genspace_fn, ray_shape, single_jitter, diag=True): """Stratified sampling along the rays. Args: rng: random generator. If `None`, use deterministic sampling. origins: [..., 3], ray origins. directions: [..., 3], ray directions. radii: [..., 3], ray radii. num_samples: int. near: [..., 1], near-plane camera distance. far: [..., 1], far-plane camera distance. genspace_fn: Callable, the curve function used when spacing t values. ray_shape: string, which shape ray to assume. single_jitter: bool, if True, apply the same offset to each sample in a ray. diag: bool, if True, produce diagonal covariances (full otherwise). Returns: t_vals: [..., num_samples], sampled t values, (means: [..., num_samples, 3], means, covs: [..., num_samples, 3{, 3}], covariances, shape depends on `diag`). """ t_vals = spacing.genspace(near, far, num_samples + 1, fn=genspace_fn) sample_shape = list(origins.shape)[:-1] + [num_samples + 1] if rng is None: # Broadcast t_vals to make the returned shape consistent. t_vals = jnp.broadcast_to(t_vals, sample_shape) else: mids = 0.5 * (t_vals[Ellipsis, 1:] + t_vals[Ellipsis, :-1]) upper = jnp.concatenate([mids, t_vals[Ellipsis, -1:]], axis=-1) lower = jnp.concatenate([t_vals[Ellipsis, :1], mids], axis=-1) if single_jitter: t_rand = random.uniform(rng, sample_shape[:-1])[Ellipsis, None] else: t_rand = random.uniform(rng, sample_shape) t_vals = lower + (upper - lower) * t_rand means, covs = cast_rays( t_vals, origins, directions, radii, ray_shape, diag=diag) return t_vals, (means, covs)
0745c1e7ed152c93c49bfcf59bb0255422b018ec
3,637,968
import PIL def resize(img, size, interpolation=PIL.Image.BILINEAR): """Resize image to match the given shape. This method uses :mod:`cv2` or :mod:`PIL` for the backend. If :mod:`cv2` is installed, this function uses the implementation in :mod:`cv2`. This implementation is faster than the implementation in :mod:`PIL`. Under Anaconda environment, :mod:`cv2` can be installed by the following command. .. code:: $ conda install -c menpo opencv3=3.2.0 Args: img (~numpy.ndarray): An array to be transformed. This is in CHW format and the type should be :obj:`numpy.float32`. size (tuple): This is a tuple of length 2. Its elements are ordered as (height, width). interpolation (int): Determines sampling strategy. This is one of :obj:`PIL.Image.NEAREST`, :obj:`PIL.Image.BILINEAR`, :obj:`PIL.Image.BICUBIC`, :obj:`PIL.Image.LANCZOS`. Bilinear interpolation is the default strategy. Returns: ~numpy.ndarray: A resize array in CHW format. """ img = _resize(img, size, interpolation) return img
fa2a407f42672e5ea91e8e2bd1c186d4ca05d98c
3,637,969
def build_punt(): """ Construye la ventana del registro del usuario""" easy = PA.dividir_puntajes("facil") medium = PA.dividir_puntajes("medio") hard = PA.dividir_puntajes("dificil") rows = len(max([easy, medium, hard], key=len)) def create_table(data, dif): return sg.Table( values = data, headings = [dif, "Puntos"], auto_size_columns = True, justification = 'center', alternating_row_color = 'lightblue', hide_vertical_scroll = True, num_rows = rows ) layout = [ [ create_table(easy if (len(easy) > 0) else ["Vacio", ""], "Facil"), create_table(medium if (len(medium) > 0) else ["vacio", ""], "Medio"), create_table(hard if (len(hard) > 0) else ["vacio", ""], "Dificil") ], [sg.Ok()] ] window = sg.Window('Mejores puntajes por dificultad ', layout, element_justification='center') return window
a97dc74855ccb8e65096d74c7fe59d89d5a3f92b
3,637,970
def true_fov(M, fov_e=50): """Calulates the True Field of View (FOV) of the telescope & eyepiece pair Args: fov_e (float): FOV of eyepiece; default 50 deg M (float): Magnification of Telescope Returns: float: True Field of View (deg) """ return fov_e/M
7735135d326f3000ac60274972263a8a71648033
3,637,971
async def test_html_content_type_with_utf8_encoding(unused_tcp_port, postgres_db, database_name, async_finalizer): """Test whether API endpoints with a "text/html; charset=UTF-8" content-type work.""" configure(unused_tcp_port, database_name, postgres_db.port) html_content = "<html><body>test</body></html>" @protocol.typedmethod(path="/test", operation="GET", client_types=["api"]) def test_method() -> ReturnValue[str]: # NOQA pass class TestServer(ServerSlice): @protocol.handle(test_method) async def test_methodY(self) -> ReturnValue[str]: # NOQA return ReturnValue(response=html_content, content_type=HTML_CONTENT_WITH_UTF8_CHARSET) rs = Server() server = TestServer(name="testserver") rs.add_slice(server) await rs.start() async_finalizer.add(server.stop) async_finalizer.add(rs.stop) # client based calls client = protocol.Client("client") response = await client.test_method() assert response.code == 200 assert response.result == html_content
74d76c70ede4ad7b6c65170142136a6278c39802
3,637,972
def _increment_inertia(centroid, reference_point, m, mass, cg, I): """helper method""" if m == 0.: return mass (x, y, z) = centroid - reference_point x2 = x * x y2 = y * y z2 = z * z I[0] += m * (y2 + z2) # Ixx I[1] += m * (x2 + z2) # Iyy I[2] += m * (x2 + y2) # Izz I[3] += m * x * y # Ixy I[4] += m * x * z # Ixz I[5] += m * y * z # Iyz mass += m cg += m * centroid return mass
f95d8c01061243929fa1d3dd48903bedc938bbd8
3,637,973
def token_addresses( request, token_amount, number_of_tokens, blockchain_services, cached_genesis, register_tokens): """ Fixture that yields `number_of_tokens` ERC20 token addresses, where the `token_amount` (per token) is distributed among the addresses behind `blockchain_services` and potentially pre-registered with the raiden Registry. The following arguments can control the behavior: Args: token_amount (int): the overall number of units minted per token number_of_tokens (int): the number of token instances register_tokens (bool): controls if tokens will be registered with raiden Registry """ if cached_genesis: token_addresses = [ address_decoder(token_address) for token_address in cached_genesis['config']['tokenAddresses'] ] else: participants = [ privatekey_to_address(blockchain_service.private_key) for blockchain_service in blockchain_services.blockchain_services ] token_addresses = _token_addresses( token_amount, number_of_tokens, blockchain_services.deploy_service, participants, register_tokens ) return token_addresses
8c79175f3a1ca312dfb03de60262f019b74b965c
3,637,974
def saturating_sigmoid(x): """Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1].""" with tf.name_scope("saturating_sigmoid", [x]): y = tf.sigmoid(x) return tf.minimum(1.0, tf.maximum(0.0, 1.2 * y - 0.1))
d779f059251cc99e40bf5d13ee2d31bc786c48b7
3,637,975
def simulate_strategy(game, strategies, init_states, func): """ Harvest an accurate average payoff with the two strategies, considering traversing all possible private cards dealt by nature game : the pyspiel game strategies : the index of player's strategy, a length two list init_states : a set of possible openspiel state after chance deals private cards func : given a strategy index and an infostate, output action """ payoff = np.array([0, 0], dtype=int) for root in init_states: # traverse game tree node = root while not node.is_terminal(): assert not node.is_chance_node(), "Doesn't exist chance nodes in kuhn's poker after private hands are dealt" player = node.current_player() action = func(strategies[player], node.information_state_string(), player) assert action in node.legal_actions(), "action not legal!" node = node.child(action) payoff = payoff + node.returns() return payoff / len(init_states)
47f60a2998ed8deba95b32edfa4221d7f2d767cc
3,637,976
async def is_nsfw_and_guild_predicate(ctx): """A predicate to test if a command was run in an NSFW channel and inside a guild :param ctx: The context of the predicate """ if not ctx.guild or not ctx.channel.is_nsfw(): raise NotNSFWOrGuild() return True
20e5ec228f337fcae1e28ad12cde515be9e50f4b
3,637,977
from typing import Optional def get_account(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountResult: """ Get information on your DigitalOcean account. ## Example Usage Get the account: ```python import pulumi import pulumi_digitalocean as digitalocean example = digitalocean.get_account() ``` """ __args__ = dict() if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('digitalocean:index/getAccount:getAccount', __args__, opts=opts, typ=GetAccountResult).value return AwaitableGetAccountResult( droplet_limit=__ret__.droplet_limit, email=__ret__.email, email_verified=__ret__.email_verified, floating_ip_limit=__ret__.floating_ip_limit, id=__ret__.id, status=__ret__.status, status_message=__ret__.status_message, uuid=__ret__.uuid)
64758aacd0f294a2f08e60d59edec6c088942e11
3,637,978
import six def get_partition_leaders(cluster_config): """Return the current leaders of all partitions. Partitions are returned as a "topic-partition" string. :param cluster_config: the cluster :type cluster_config: kafka_utils.utils.config.ClusterConfig :returns: leaders for partitions :rtype: map of ("topic-partition", broker_id) pairs """ client = KafkaClient(cluster_config.broker_list) result = {} for topic, topic_data in six.iteritems(client.topic_partitions): for partition, p_data in six.iteritems(topic_data): topic_partition = topic + "-" + str(partition) result[topic_partition] = p_data.leader return result
07aed255fa6d2ec65854d4a5ed1ab1ada6dcca73
3,637,979
def WR(df, N=10, N1=6): """ 威廉指标 :param df: :param N: :param N1: :return: """ HIGH = df['high'] LOW = df['low'] CLOSE = df['close'] WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) return pd.DataFrame({ 'WR1': WR1, 'WR2': WR2 })
28cccd0b5f7d0a0a772327901b838e9bf8aa862d
3,637,982
from hask3.lang.hindley_milner import Function def make_fn_type(params): """Turn type parameters into corresponding internal type system object. Returned object will represent the type of a function over the parameters. :param params: a list of type paramaters, e.g. from a type signature. These should be instances of TypeOperator or TypeVariable. :returns: An instance of TypeOperator representing the function type. """ if len(params) == 2: last_input, return_type = params return Function(last_input, return_type) else: return Function(params[0], make_fn_type(params[1:]))
876d1d9c4243e0ed8a71b9fda2b2469519f4c89b
3,637,983
def export(request, wid): """Export the logs from the given workflow :param request: HTML request :param pk: pk of the workflow to export :return: Return a CSV download of the logs """ dataset = LogResource().export( Log.objects.filter(user=request.user, workflow__id=wid) ) # Create the response as a csv download response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="logs.csv"' return response
ff06c49642a4ab84b7c779522a13ce56e19cc9a9
3,637,984
def _validate_valid_xml(value): """ Checks whether the given value is well-formed and valid XML. """ try: # Try to create an XML tree from the given String value. _value = XML_DECL.sub(u'', value) _ = etree.fromstring(_value.encode('utf-8')) return True except etree.ParseError, parse_error: # In case of an exception, we raise a ValidationError. raise ValidationError(parse_error) # cfedermann: in case of other exceptions, raise a ValidationError with # the corresponding error message. This will prevent the exception # page handler to be shown and is hence more acceptable for end users. except Exception, error: raise ValidationError(error)
dbdcce58a6dbbbaf90b98c6f56fa7f9c6f830e00
3,637,985
import importlib import pkgutil def import_submodules(package, recursive=True): """Import all submodules of a module, recursively, including subpackages :param recursive: bool :param package: package (name or actual module) :type package: str | module :rtype: dict[str, types.ModuleType] """ if isinstance(package, str): package = importlib.import_module(package) results = {} for loader, name, is_pkg in pkgutil.walk_packages(package.__path__): full_name = package.__name__ + '.' + name results[full_name] = importlib.import_module(full_name) if recursive and is_pkg: results.update(import_submodules(full_name)) return results
df1756f59763adf446a6e42f92c5bb193a8740bd
3,637,986
def seasonal_pattern(season_time): """Just an arbitrary pattern, you can change it if you wish""" return np.where(season_time < 0.4, np.sin(season_time * 2), 1 / np.exp(3 * season_time))
06430ce5d3da7d44fc4a8b5e32ca4d5567b1cc15
3,637,987