content
stringlengths
22
815k
id
int64
0
4.91M
def get_data_table_metas(data_table_name, data_table_namespace): """ Gets metas from meta table associated with table named `data_table_name` and namespaced `data_table_namespace`. Parameters --------- data_table_name : string table name of this data table data_table_namespace : string table name of this data table Returns ------- dict metas Examples -------- >>> from common.python import session >>> session.get_data_table_metas("meta", "readme") # {'model_id': 'a_id', 'used_framework': 'fate'} """ return RuntimeInstance.SESSION.get_data_table_metas(data_table_name=data_table_name, data_table_namespace=data_table_namespace)
26,800
def get_at_content(sequence): """Return content of AT in sequence, as float between 0 and 1, inclusive. """ sequence = sequence.upper() a_content = sequence.count('A') t_content = sequence.count('T') return round((a_content+t_content)/len(sequence), 2)
26,801
def page_not_found(e): """Handle nonexistin pages.""" _next = get_next_url() if _next: flash("Page Not Found", "danger") return redirect(_next) return render_template("404.html"), 404
26,802
def test_query(p: int = 1) -> int: """ Example 2 for a unit test :param p: example of description :return: return data """ return p
26,803
def mirror_1d(d, xmin=None, xmax=None): """If necessary apply reflecting boundary conditions.""" if xmin is not None and xmax is not None: xmed = (xmin+xmax)/2 return np.concatenate((2*xmin-d[d < xmed], d, 2*xmax-d[d >= xmed])) elif xmin is not None: return np.concatenate((2*xmin-d, d)) elif xmax is not None: return np.concatenate((d, 2*xmax-d)) else: return d
26,804
def setup(bot): """ :param bot: a discord.client :return: None """ bot.add_cog(AutoCensor(bot))
26,805
def incr_ratelimit(user, domain='all'): """Increases the rate-limit for the specified user""" list_key, set_key, _ = redis_key(user, domain) now = time.time() # If we have no rules, we don't store anything if len(rules) == 0: return # Start redis transaction with client.pipeline() as pipe: count = 0 while True: try: # To avoid a race condition between getting the element we might trim from our list # and removing it from our associated set, we abort this whole transaction if # another agent manages to change our list out from under us # When watching a value, the pipeline is set to Immediate mode pipe.watch(list_key) # Get the last elem that we'll trim (so we can remove it from our sorted set) last_val = pipe.lindex(list_key, max_api_calls(user) - 1) # Restart buffered execution pipe.multi() # Add this timestamp to our list pipe.lpush(list_key, now) # Trim our list to the oldest rule we have pipe.ltrim(list_key, 0, max_api_calls(user) - 1) # Add our new value to the sorted set that we keep # We need to put the score and val both as timestamp, # as we sort by score but remove by value pipe.zadd(set_key, now, now) # Remove the trimmed value from our sorted set, if there was one if last_val is not None: pipe.zrem(set_key, last_val) # Set the TTL for our keys as well api_window = max_api_window(user) pipe.expire(list_key, api_window) pipe.expire(set_key, api_window) pipe.execute() # If no exception was raised in the execution, there were no transaction conflicts break except redis.WatchError: if count > 10: logging.error("Failed to complete incr_ratelimit transaction without interference 10 times in a row! Aborting rate-limit increment") break count += 1 continue
26,806
def TestCleanUp(user_profile_dir): """Cleans up test machine so as not to impact other tests. Args: user_profile_dir: the user-profile folder used by Chromoting tests. """ # Stop the host service. RunCommandInSubProcess(CHROMOTING_HOST_PATH + ' --stop') # Cleanup any host logs. RunCommandInSubProcess('rm /tmp/chrome_remote_desktop_*') # Remove the user-profile dir if os.path.exists(user_profile_dir): shutil.rmtree(user_profile_dir)
26,807
def calc_vertical_avg(fld,msk): """Compute vertical average, ignoring continental or iceshelf points """ # Make mask of nans, assume input msk is 3D of same size as fld 3 spatial dims nanmsk = np.where(msk==1,1,np.NAN) v_avg = fld.copy() v_avg.values = v_avg.values*msk.values if 'Z' in fld.dims: vdim = 'Z' elif 'Zl' in fld.dims: vdim = 'Zl' else: raise TypeError('Could not find recognizable vertical field in input dataset') # Once vertical coordinate is found, compute avg along dimension v_avg = v_avg.sum(dim=vdim,skipna=True) return v_avg
26,808
def get_logger(log_file, log_level="info"): """ create logger and output to file and stdout """ assert log_level in ["info", "debug"] log_formatter = LogFormatter() logger = logging.getLogger() log_level = {"info": logging.INFO, "debug": logging.DEBUG}[log_level] logger.setLevel(log_level) stream = logging.StreamHandler(sys.stdout) stream.setFormatter(log_formatter) logger.addHandler(stream) filep = logging.FileHandler(log_file, mode="a") filep.setFormatter(log_formatter) logger.addHandler(filep) return logger
26,809
def replace(data, match, repl): """Replace values for all key in match on repl value. Recursively apply a function to values in a dict or list until the input data is neither a dict nor a list. """ if isinstance(data, dict): return { key: repl if key in match else replace(value, match, repl) for key, value in data.items() } if isinstance(data, list): return [replace(item, match, repl) for item in data] return data
26,810
def get_current_date() ->str: """Forms a string to represent the current date using the time module""" if len(str(time.gmtime()[2])) == 1: current_date = str(time.gmtime()[0]) + '-' + str(time.gmtime()[1]) + '-0' + str(time.gmtime()[2]) else: current_date = str(time.gmtime()[0]) + '-' + str(time.gmtime()[1]) + '-' + str(time.gmtime()[2]) return current_date
26,811
def to_jsobj(obj): """Convert a Jsonable object to a JSON object, and return it.""" if isinstance(obj, LIST_TYPES): return [to_jsobj(o) for o in obj] if obj.__class__.__module__ == "builtins": return obj return obj.to_jsobj()
26,812
def start( context: Context, on_startup: Callable[[web.Application], Awaitable[Any]], on_cleanup: Callable[[web.Application], Awaitable[Any]], ): """ Start the web app. """ app = web.Application() app['context'] = context app.on_startup.append(on_startup) app.on_cleanup.append(on_cleanup) app.add_routes(routes) templates.setup(app) # noinspection PyTypeChecker web.run_app(app, port=HTTP_PORT, print=None)
26,813
def EVAL_find_counter_exemplars(latent_representation_original, Z, idxs, counter_exemplar_idxs): """ Compute the values of the goal function. """ # prepare the data to apply the diversity optimization data = np.zeros((len(idxs), np.shape(Z)[1])) for i in range(len(idxs)): data[i] = Z[idxs[i]] # min-max normalization (applied on ALL examples) scaler = MinMaxScaler() scaler.fit_transform(data) # list of points points = [row for row in scaler.transform(data)] # MIN MAX normalize instance to explain instance = scaler.transform((latent_representation_original)) # number of nearest neighbors to consider knn = 5 kp = {} lconst = 1 _, d0 = argmax(points, lambda p: -dist(instance, p)) lconst = 0.5 / (-d0) for p1 in points: # compute distances dst = [(p2, dist(p1, p2)) for p2 in points if not np.array_equal(p1, p2)] # sort dst = sorted(dst, key=lambda x: x[1]) # add top knn to kp kp[p1.tobytes()] = set(p2.tobytes() for p2, d in dst[:knn]) # goal function def g(points): dpoints, dx = set(), 0 for p1 in points: # union operator dpoints |= kp[p1.tobytes()] dx += dist(p1, instance) # scaled version 2*cost return len(dpoints) - 2 * lconst * dx # get the extracted CF extracted_CF_data = [] for i in range(len(counter_exemplar_idxs)): extracted_CF_data.append(Z[counter_exemplar_idxs[i]]) # apply scaling extracted_CF_data = scaler.transform((extracted_CF_data)) return g(extracted_CF_data)
26,814
def test_traversal_from_multiple_letters(): """Test if traversal of multiple letters works correctly.""" test_tree = trie.TrieTree() test_list = ['fae', 'fir', 'faerie', 'fox', 'forest'] for i in test_list: test_tree.insert(i) traversal_list = [i for i in test_tree.traversal('fae')] test_list = ['fae', 'faerie'] for i in test_list: assert i in traversal_list assert len(test_list) == len(traversal_list)
26,815
def test_add(): """Test add function.""" from src.kata import Add assert Add(1)(2)(3) == 6
26,816
def min_energy(bond): """Calculate minimum energy. Args: bond: an instance of Bond or array[L1*L2][3]. """ N_unit = L1*L2 coupling = bond.bond if isinstance(bond, Bond) else bond # Create matrix A a = np.zeros((N_unit, N_unit), dtype=float) for i in range(N_unit): a[i][nn_1(i)] += coupling[i][0] a[i][nn_2(i)] += coupling[i][1] a[i][i] += coupling[i][2] u,s,vt = sl.svd(a) det_u = sl.det(u) det_vt = sl.det(vt) # calculate parity of the projection operator ## product of u_{ij} sgn = np.prod(np.sign(coupling)) ## from boundary condition if (L1+L2+M*(L1-M))%2 != 0: sgn *= -1 # (-1)^theta ## det(Q) = det(VU) sgn *= det_u*det_vt min_epsilon = min(s) sum_epsilon = -0.5*sum(s) ene_phys = sum_epsilon ene_unphys = sum_epsilon + min_epsilon # judge whether the vacuume state is physical or not if sgn < 0: # The vacuum state is unphysical. ene_phys, ene_unphys = ene_unphys, ene_phys return ene_phys,ene_unphys,min_epsilon,sgn,det_u,det_vt
26,817
def find_result_node(flat_graph: dict) -> Tuple[str, dict]: """ Find result node in flat graph :return: tuple with node id (str) and node dictionary of the result node. """ result_nodes = [(key, node) for (key, node) in flat_graph.items() if node.get("result")] if len(result_nodes) == 1: return result_nodes[0] elif len(result_nodes) == 0: raise ProcessGraphVisitException("Found no result node in flat process graph") else: keys = [k for (k, n) in result_nodes] raise ProcessGraphVisitException( "Found multiple result nodes in flat process graph: {keys!r}".format(keys=keys))
26,818
def password_generator(size=25, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits): """Returns a random 25 character password""" return ''.join(random.choice(chars) for _ in range(size))
26,819
def create_cleaned_df(df, class_label_str): """Transform the wide-from Dataframe (df) from main.xlsx into one with unique row names, values 0-1001 as the column names and a label column containing the class label as an int. Parameters ---------- df : pandas DataFrame A DataFrame read in from main.xlsx. It must have columns 'Name', 'Analyte' and 'Concentration'. class_label_str: str (len 2) The class label for the dataframe. It must be two characters long and one of 'Cu', 'Cd', 'Pb' or 'Sw'. Returns ------- pandas DataFrame Wide-form dataframe with unique row and column names and a label column. """ # Replace spaces with underscores in Concentration column df['Concentration'] = df['Concentration'].str.replace(' ', '_') # Create new column (we will use this to extract unique names later on) df['metal_concentration'] = df['Analyte'] + '_' + df['Concentration'] df = df.drop(columns=['Name', 'Analyte', 'Concentration']) # Transpose df (now columns are a range - 0, 1, 2, etc.) df['metal_concentration'] = [f'{name}_{i}' for i, name in enumerate(df['metal_concentration'])] df = df.set_index('metal_concentration') df.index.name = None df.columns = range(0, 1002) class_label_to_int_mapping = get_class_label_to_int_mapping() df['label'] = class_label_to_int_mapping[class_label_str] return df
26,820
def uni_to_int(dxu, x, lambda_val): """ Translates from single integrator to unicycle dynamics. Parameters ---------- dxu : Single integrator control input. x : Unicycle states (3 x N) lambda_val : Returns ------- dx : """ n = dxu.shape[1] dx = np.zeros((2, n)) for i in range(0, n): temp = np.array([[np.cos(x[2, i]), -lambda_val * np.sin(x[2, i])], [np.sin(x[2, i]), lambda_val * np.cos(x[2, i])]]) dx[:, i] = np.dot(temp, dxu[:, i]) return dx
26,821
def pack_binary_command(cmd_type, cmd_args, is_response=False): """Packs the given command using the parameter ordering specified in GEARMAN_PARAMS_FOR_COMMAND. *NOTE* Expects that all arguments in cmd_args are already str's. """ expected_cmd_params = GEARMAN_PARAMS_FOR_COMMAND.get(cmd_type, None) if expected_cmd_params is None or cmd_type == GEARMAN_COMMAND_TEXT_COMMAND: raise ProtocolError('Received unknown binary command: %s' % get_command_name(cmd_type)) expected_parameter_set = set(expected_cmd_params) received_parameter_set = set(cmd_args.keys()) if expected_parameter_set != received_parameter_set: raise ProtocolError('Received arguments did not match expected arguments: %r != %r' % (expected_parameter_set, received_parameter_set)) # Select the right expected magic if is_response: magic = MAGIC_RES_STRING else: magic = MAGIC_REQ_STRING # !NOTE! str should be replaced with bytes in Python 3.x # We will iterate in ORDER and str all our command arguments if compat.any(type(param_value) != str for param_value in cmd_args.itervalues()): raise ProtocolError('Received non-binary arguments: %r' % cmd_args) data_items = [cmd_args[param] for param in expected_cmd_params] # Now check that all but the last argument are free of \0 as per the protocol spec. if compat.any('\0' in argument for argument in data_items[:-1]): raise ProtocolError('Received arguments with NULL byte in non-final argument') binary_payload = NULL_CHAR.join(data_items) # Pack the header in the !4sII format then append the binary payload payload_size = len(binary_payload) packing_format = '!4sII%ds' % payload_size return struct.pack(packing_format, magic, cmd_type, payload_size, binary_payload)
26,822
def get_adjacency_spectrum(graph, k=np.inf, eigvals_only=False, which='LA', use_gpu=False): """ Gets the top k eigenpairs of the adjacency matrix :param graph: undirected NetworkX graph :param k: number of top k eigenpairs to obtain :param eigvals_only: get only the eigenvalues i.e., no eigenvectors :param which: the type of k eigenvectors and eigenvalues to find :return: the eigenpair information """ # get all eigenpairs for small graphs if len(graph) < 100: A = nx.adjacency_matrix(graph).todense() eigpairs = eigh(A, eigvals_only=eigvals_only) else: A = nx.to_scipy_sparse_matrix(graph, format='csr', dtype=np.float, nodelist=graph.nodes) if gpu_available() and use_gpu: import cupy as cp import cupyx.scipy.sparse.linalg as cp_linalg A_gpu = cp.sparse.csr_matrix(A) eigpairs = cp_linalg.eigsh(A_gpu, k=min(k, len(graph) - 3), which=which, return_eigenvectors=not eigvals_only) if type(eigpairs) is tuple: eigpairs = list(eigpairs) eigpairs[0], eigpairs[1] = cp.asnumpy(eigpairs[0]), cp.asnumpy(eigpairs[1]) else: eigpairs = cp.asnumpy(eigpairs) else: if use_gpu: print('Warning: GPU requested, but not available') eigpairs = eigsh(A, k=min(k, len(graph) - 1), which=which, return_eigenvectors=not eigvals_only) return eigpairs
26,823
def make_system(*args, **kwargs): """ Factory function for contact systems. Checks the compatibility between the substrate, interaction method and surface and returns an object of the appropriate type to handle it. The returned object is always of a subtype of SystemBase. Parameters: ----------- substrate -- An instance of HalfSpace. Defines the solid mechanics in the substrate surface -- An instance of SurfaceTopography, defines the profile. Returns ------- """ substrate, surface = _make_system_args(*args, **kwargs) return NonSmoothContactSystem(substrate=substrate, surface=surface)
26,824
def _batch_normalization(x, norm, scale=None, norm_epsilon=1e-16, name=None): """ Normalizes a tensor by norm, and applies (optionally) a 'scale' \\(\gamma\\) to it, as well as an 'offset' \\(\beta\\): \\(\frac{\gamma(x)}{norm} + \beta\\) 'norm', 'scale' are all expected to be of shape: * they can have the same number of dimensions as the input 'x', with identical sizes as 'x' for dimensions that are not normalized over, and dimension 1 for the others which are being normalized over :param x: 'Tensor' :param norm: :param scale: :param norm_epsilon: :param name: :return: the normalized, scaled, offset tensor """ with tf.name_scope(name, "batchnorm", [x, norm, scale]): inv = tf.rsqrt(tf.square(norm) + norm_epsilon) if scale is not None: inv *= scale # def _debug_print_func(f): # print("inv={}".format(f)) # return False # debug_print_op = tf.py_func(_debug_print_func,[inv],[tf.bool]) # with tf.control_dependencies(debug_print_op): # inv = tf.identity(inv, name="scale") x *= inv # def _debug_print_func(f): # print("x_bn[0]={}".format(f[0, :])) # # print("x_bn: mean,max,min={},{},{}".format(f.mean(),f.max(),f.min())) # return False # # debug_print_op = tf.py_func(_debug_print_func, [x], [tf.bool]) # with tf.control_dependencies(debug_print_op): # x = tf.identity(x, name="x_norm") return x
26,825
def place_owner_list(user_id): """ It retrieves the list of places for which the user is the owner. Parameters: - user_id: id of the user, which is owner and wants to get its own places. Returns a tuple: - list of Places owned by the user (empty if the user is not an owner) - status message - the http code indicating the type of error, if any """ try: places = Place.get_owner_places(user_id) except TypeError, e: return None, str(e), 400 return places, "OK", 200
26,826
def job_met_heu(prob_label, tr, te, r, ni, n): """MeanEmbeddingTest with test_locs randomized. tr unused.""" # MeanEmbeddingTest random locations with util.ContextTimer() as t: met_heu = tst.MeanEmbeddingTest.create_fit_gauss_heuristic(te, J, alpha, seed=180) met_heu_test = met_heu.perform_test(te) return { #'test_method': met_heu, 'test_result': met_heu_test, 'time_secs': t.secs}
26,827
def download(): """Unchanged from web2py. ``` allows downloading of uploaded files http://..../[app]/default/download/[filename] ``` """ return response.download(request, db)
26,828
def train_revenue_model_q2(df_listings: pd.DataFrame, df_daily_revenue: pd.DataFrame): """Trains the revenue estimator to be used on question 2. Parameters ---------- df_listings : pd.DataFrame Pandas dataframe with information about listings. df_daily_revenue : pd.DataFrame Pandas dataframe with information about daily revenue. Returns ------- pd.DataFrame Returns a sklearn-like regressor instance. """ print("Training revenue model - Q2") X, y = build_features_revenue_model_q2(df_listings, df_daily_revenue) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42 ) preprocessor = fit_preprocess_revenue_model_q2(X_train) X_train = preprocess_transform(X_train, preprocessor) X_test = preprocess_transform(X_test, preprocessor) model = MLPRegressor( hidden_layer_sizes=(5, 10, 10, 5, 5), solver="lbfgs", learning_rate="adaptive", learning_rate_init=0.03, max_iter=10000, random_state=42, ).fit(X_train, y_train) score = mae(y_test, model.predict(X_test)) dump_pickle(preprocessor, PATH_PREPROCESSOR_REVENUE_MODEL_Q2) dump_pickle(model, PATH_REGRESSOR_REVENUE_MODEL_Q2) print("MAE(teste) = {:.2f}".format(score))
26,829
def test_all(model_name): """ Test a given model on the whole MNIST training set * Used for debugging :return: None """ model = models.load_model(model_name) test_loss, test_acc = model.evaluate(image_data_testing, label_data_testing) print("Test Loss: {0} - Test Acc: {1}".format(test_loss, test_acc))
26,830
def setupCLI(): """ Handles the command line arguments for running the code, making optional date arguments easier and cleaner to handle Returns ------- List of formatted Command Line arguments """ parser = argparse.ArgumentParser() parser.add_argument('databaseName', type=str) parser.add_argument('collectionName', type=str) parser.add_argument('filterwords', type=str) parser.add_argument("--server", type=str, help="l=local (default), v=VirtualMachine-3") args = parser.parse_args() dbName = args.databaseName collectionName = args.collectionName filterWordArg = args.filterwords if args.server: if str.lower(args.server) == "l": server = "local" else: server = "vm3" else: server = "local" collection = connectToMongo(dbName, collectionName, server) if " OR " not in filterWordArg: filterList = [filterWordArg] filterText = filterWordArg else: filterList = filterWordArg.split(" OR ") filterText = filterWordArg.replace(" OR ", "|") argList = [collection, server, filterList, filterText] return argList
26,831
def reopen(service, **kwargs): """Reopen an existing closed issue.""" issue = service.issue(kwargs.pop('number')) if issue.state != 'closed': raise GitIssueError('issue %s is not closed' % issue.number) issue = issue.reopen() _finish_('Reopened', issue.number, issue.url())
26,832
def set_transform_rotation(transform, rotation): """ Change the initial rotation of a transform matrix to the specified angle, ignoring previous angles :param transform: The transform to change :param rotation: The angle in degrees for the transform rotation to be :return: """ deg_to_rad = 2*np.pi/360 angle = rotation*deg_to_rad if type(transform) == sitk.Euler2DTransform: transform.SetAngle(angle) if type(transform) == sitk.AffineTransform and len(transform.GetTranslation()) == 2: generic_affine = sitk.AffineTransform(2) generic_affine.SetTranslation(transform.GetTranslation()) generic_affine.Rotate(0, 1, angle) transform.SetParameters(generic_affine.GetParameters()) if type(transform) == sitk.Transform: print('This transform is of generic type, it has no rotation parameter.')
26,833
def named_cache(path): """ Return dictionary of cache with `(package name, package version)` mapped to cache entry. This is a simple convenience wrapper around :py:func:`packages`. """ return {os.path.split(x.path)[1]: x for x in packages(path)}
26,834
def action_id2arr(ids): """ Converts action from id to array format (as understood by the environment) """ return actions[ids]
26,835
def get_args(): """Get command-line arguments.""" parser = argparse.ArgumentParser( description='Emulate the tac program: print file(s) last line first.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', type=argparse.FileType('rt'), nargs='*', help='Input file(s)', metavar='FILE', default=[sys.stdin]) return parser.parse_args()
26,836
def cif_from_ase(ase,full_occupancies=False,add_fake_biso=False): """ Construct a CIF datablock from the ASE structure. The code is taken from https://wiki.fysik.dtu.dk/ase/epydoc/ase.io.cif-pysrc.html#write_cif, as the original ASE code contains a bug in printing the Hermann-Mauguin symmetry space group symbol. :param ase: ASE "images" :return: array of CIF datablocks """ from numpy import arccos, pi, dot from numpy.linalg import norm if not isinstance(ase, (list, tuple)): ase = [ase] datablocks = [] for i, atoms in enumerate(ase): datablock = dict() cell = atoms.cell a = norm(cell[0]) b = norm(cell[1]) c = norm(cell[2]) alpha = arccos(dot(cell[1], cell[2])/(b*c))*180./pi beta = arccos(dot(cell[0], cell[2])/(a*c))*180./pi gamma = arccos(dot(cell[0], cell[1])/(a*b))*180./pi datablock['_cell_length_a'] = str(a) datablock['_cell_length_b'] = str(b) datablock['_cell_length_c'] = str(c) datablock['_cell_angle_alpha'] = str(alpha) datablock['_cell_angle_beta'] = str(beta) datablock['_cell_angle_gamma'] = str(gamma) if atoms.pbc.all(): datablock['_symmetry_space_group_name_H-M'] = 'P 1' datablock['_symmetry_int_tables_number'] = str(1) datablock['_symmetry_equiv_pos_as_xyz'] = ['x, y, z'] datablock['_atom_site_label'] = [] datablock['_atom_site_fract_x'] = [] datablock['_atom_site_fract_y'] = [] datablock['_atom_site_fract_z'] = [] datablock['_atom_site_type_symbol'] = [] if full_occupancies: datablock['_atom_site_occupancy'] = [] if add_fake_biso: datablock['_atom_site_thermal_displace_type'] = [] datablock['_atom_site_B_iso_or_equiv'] = [] scaled = atoms.get_scaled_positions() no = {} for i, atom in enumerate(atoms): symbol = atom.symbol if symbol in no: no[symbol] += 1 else: no[symbol] = 1 datablock['_atom_site_label'].append(symbol + str(no[symbol])) datablock['_atom_site_fract_x'].append(str(scaled[i][0])) datablock['_atom_site_fract_y'].append(str(scaled[i][1])) datablock['_atom_site_fract_z'].append(str(scaled[i][2])) datablock['_atom_site_type_symbol'].append(symbol) if full_occupancies: datablock['_atom_site_occupancy'].append(str(1.0)) if add_fake_biso: datablock['_atom_site_thermal_displace_type'].append('Biso') datablock['_atom_site_B_iso_or_equiv'].append(str(1.0)) datablocks.append(datablock) return datablocks
26,837
def breadcrumb(instance=None, label=None): """ Create HTML Breadcrumb from instance Starting with the instance, walk up the tree building a bootstrap3 compatiable breadcrumb """ from promgen import models def site(obj): yield reverse("site-detail"), obj.domain def shard(obj): yield reverse("shard-list"), _("Shards") yield obj.get_absolute_url(), obj.name def service(obj): yield reverse("service-list"), _("Services") yield obj.get_absolute_url(), obj.name def project(obj): yield from service(obj.service) yield obj.get_absolute_url(), obj.name def alert(obj): yield reverse("alert-list"), _("Alerts") yield obj.get_absolute_url(), obj.pk def rule(obj): if obj.content_type.model == "site": yield from site(obj.content_object) if obj.content_type.model == "service": yield from service(obj.content_object) if obj.content_type.model == "project": yield from project(obj.content_object) # If we have a new rule, it won't have a name if obj.pk: yield obj.get_absolute_url(), obj.name def sender(obj): if obj.content_type.model == "service": yield from service(obj.content_object) if obj.content_type.model == "project": yield from project(obj.content_object) def generator(): yield reverse("home"), _("Home") if isinstance(instance, models.Sender): yield from sender(instance) if isinstance(instance, models.Project): yield from project(instance) if isinstance(instance, models.Service): yield from service(instance) if isinstance(instance, models.Shard): yield from shard(instance) if isinstance(instance, models.Rule): yield from rule(instance) if isinstance(instance, models.Alert): yield from alert(instance) def to_tag(): yield '<ol class="breadcrumb">' for href, text in generator(): yield format_html('<li><a href="{}">{}</a></li>', mark_safe(href), text) if label: yield format_html('<li class="active">{}</li>', _(label)) yield "</ol>" return mark_safe("".join(to_tag()))
26,838
def parse_body_at(path_to_hdf5, num_frame, all=False): """ :param path_to_hdf5: path to annotations 'hdf5' file :param num_frame: frame to extract annotations from :param all: if True, all original landmarks are returned. Otherwise, only those used for evaluation are returned. :return: confidence, landmarks, valid (only useful for validation and test sets) """ assert os.path.exists(path_to_hdf5) or path_to_hdf5.split(".")[-1].lower() != "hdf5", "HDF5 file could not be opened." with h5py.File(path_to_hdf5, "r") as f: key_frame = f"{num_frame:05d}" if "body" not in f[key_frame]: return 0, [], False # -------- BODY -------- confidence = f[key_frame]["body"].attrs["confidence"] if "confidence" in f[key_frame]["body"].attrs.keys() else 0 valid = f[key_frame]["body"].attrs["valid"] if "valid" in f[key_frame]["body"].attrs.keys() else False landmarks = None if "landmarks" in f[key_frame]["body"].keys(): landmarks = f[key_frame]["body"]["landmarks"][()] if not all and landmarks is not None: landmarks = filter_body_landmarks(landmarks).astype(int) return confidence, landmarks, valid
26,839
def get_loader(data_args, transform_args, split, task_sequence, su_frac, nih_frac, cxr_frac, tcga_frac, batch_size, is_training=False, shuffle=False, study_level=False, frontal_lateral=False, return_info_dict=False, covar_list='', fold_num=None): """Returns a dataset loader. If both stanford_frac and nih_frac is one, the loader will sample both NIH and Stanford data. Args: su_frac: Float that specifies what percentage of stanford to load. nih_frac: Float that specifies what percentage of NIH to load. cxr_frac: Dictionary that specifies what fraction of each CXR dataset is needed. # TODO: remove all the frac arguments and instead pass a dictionary split: String determining if this is the train, valid, test, or sample split. shuffle: If true, the loader will shuffle the data. study_level: If true, creates a loader that loads the image on the study level. Only applicable for the SU dataset. frontal_lateral: If true, loads frontal/lateral labels. Only applicable for the SU dataset. return_info_dict: If true, return a dict of info with each image. covar_list: List of strings, specifying the covariates to be sent along with the images. Return: DataLoader: A dataloader """ if is_training: study_level = data_args.train_on_studies datasets = [] for cxr_ds in ['pocus', 'hocus', 'pulm']: if cxr_ds in cxr_frac.keys() and cxr_frac[cxr_ds] != 0: if cxr_ds == 'pocus': data_dir = data_args.pocus_data_dir img_dir = None elif cxr_ds == 'hocus': data_dir = data_args.hocus_data_dir img_dir = None else: data_dir = data_args.pulm_data_dir img_dir = data_args.pulm_img_dir datasets.append( CXRDataset( data_dir, transform_args, split=split, covar_list=covar_list, is_training=is_training, dataset_name=cxr_ds, tasks_to=task_sequence, frac=cxr_frac[cxr_ds], toy=data_args.toy, img_dir=img_dir, fold_num=fold_num, ) ) if len(datasets) == 2: assert study_level is False, "Currently, you can't create concatenated datasets when training on studies" dataset = ConcatDataset(datasets) else: dataset = datasets[0] # Pick collate function if study_level and not data_args.eval_tcga: collate_fn = PadCollate(dim=0) loader = data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=8, collate_fn=collate_fn) else: loader = data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=8) return loader
26,840
def get_domain(arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDomainResult: """ The resource schema to create a CodeArtifact domain. :param str arn: The ARN of the domain. """ __args__ = dict() __args__['arn'] = arn if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('aws-native:codeartifact:getDomain', __args__, opts=opts, typ=GetDomainResult).value return AwaitableGetDomainResult( arn=__ret__.arn, name=__ret__.name, owner=__ret__.owner, permissions_policy_document=__ret__.permissions_policy_document, tags=__ret__.tags)
26,841
def collect_properties(service_instance, view_ref, obj_type, path_set=None, include_mors=False): """ Collect properties for managed objects from a view ref Check the vSphere API documentation for example on retrieving object properties: - http://goo.gl/erbFDz Original Source: https://github.com/dnaeon/py-vconnector/blob/master/src/vconnector/core.py Modified for my purposes here. :param pyVmomi.vim.view.* view_ref: Starting point of inventory navigation :param pyVmomi.vim.* obj_type: Type of managed object :param list path_set: List of properties to retrieve :param bool include_mors: If True include the managed objects refs in the result :return: A list of properties for the managed objects :rtype list: """ collector = service_instance.content.propertyCollector # Create object specification to define the starting point of # inventory navigation obj_spec = vmodl.query.PropertyCollector.ObjectSpec() obj_spec.obj = view_ref obj_spec.skip = True # Create a traversal specification to identify the path for collection traversal_spec = vmodl.query.PropertyCollector.TraversalSpec() traversal_spec.name = 'traverseEntities' traversal_spec.path = 'view' traversal_spec.skip = False traversal_spec.type = view_ref.__class__ obj_spec.selectSet = [traversal_spec] # Identify the properties to the retrieved property_spec = vmodl.query.PropertyCollector.PropertySpec() property_spec.type = obj_type if not path_set: property_spec.all = True property_spec.pathSet = path_set # Add the object and property specification to the # property filter specification filter_spec = vmodl.query.PropertyCollector.FilterSpec() filter_spec.objectSet = [obj_spec] filter_spec.propSet = [property_spec] # Retrieve properties props = collector.RetrieveContents([filter_spec]) data = [] for obj in props: properties = {} for prop in obj.propSet: properties[prop.name] = prop.val if include_mors: properties['obj'] = obj.obj data.append(properties) return data
26,842
async def test_find_in_range_defaults_inverted(hass, mqtt_mock): """Test find in range with default range but inverted.""" mqtt_cover = MqttCover( { "name": "cover.test", "state_topic": "state-topic", "get_position_topic": None, "command_topic": "command-topic", "availability_topic": None, "tilt_command_topic": "tilt-command-topic", "tilt_status_topic": "tilt-status-topic", "qos": 0, "retain": False, "state_open": "OPEN", "state_closed": "CLOSE", "position_open": 0, "position_closed": 100, "payload_open": "OPEN", "payload_close": "CLOSE", "payload_stop": "STOP", "payload_available": None, "payload_not_available": None, "optimistic": False, "value_template": None, "tilt_open_position": 100, "tilt_closed_position": 0, "tilt_min": 0, "tilt_max": 100, "tilt_optimistic": False, "tilt_invert_state": True, "set_position_topic": None, "set_position_template": None, "unique_id": None, "device_config": None, }, None, None, ) assert mqtt_cover.find_in_range_from_percent(56) == 44 assert mqtt_cover.find_in_range_from_percent(56, "cover") == 44
26,843
def _timeout(seconds): """Decorator for preventing a function from running for too long. Inputs: seconds (int): The number of seconds allowed. Notes: This decorator uses signal.SIGALRM, which is only available on Unix. """ assert isinstance(seconds, int), "@timeout(sec) requires an int" def _handler(signum, frame): """Handle the alarm by raising a custom exception.""" raise TimeoutError("Timeout after {0} seconds".format(seconds)) def decorator(func): def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handler) signal.alarm(seconds) # Set the alarm. try: result = func(*args, **kwargs) finally: signal.alarm(0) # Turn the alarm off. return result return wraps(func)(wrapper) return decorator
26,844
def marginal_entropy(problem: dict, train_ixs: np.ndarray, obs_labels: np.ndarray, unlabeled_ixs: np.ndarray, batch_size: int, **kwargs) -> np.ndarray: """ Score is -p(x)log[p(x)] i.e. marginal entropy of the point. :param problem: dictionary that defines the problem, containing keys: * points: an (n_samples, n_dim) matrix of points in the space * num_classes: the number of different classes [0, num_classes) * batch_size: number of points to query each iteration * num_queries: the max number of queries we can make on the data * model: the sk-learn model we are training :param train_ixs: index into `points` of the training examples :param obs_labels: labels for the training examples :param unlabeled_ixs: indices into problem['points'] to score :param kwargs: unused :return: scores for each of selected_ixs """ points = problem['points'] model = problem['model'] test_X = points[unlabeled_ixs] p_x = model.predict_proba(test_X) p_x = p_x.clip(1e-9, 1 - 1e-9) logp_x = np.log(p_x) return -1 * (p_x * logp_x).sum(axis=1) # return 1/ np.abs(model.decision_function(test_X))
26,845
def notify_owner(plugin, vc_room): """Notifies about the deletion of a Vidyo room from the Vidyo server.""" user = vc_room.vidyo_extension.owned_by_user tpl = get_plugin_template_module('emails/remote_deleted.html', plugin=plugin, vc_room=vc_room, event=None, vc_room_event=None, user=user) _send('delete', user, plugin, None, vc_room, tpl)
26,846
def roc_plot_from_thresholds(roc_thresholds_by_model, save=False, debug=False): """ From a given dictionary of thresholds by model, create a ROC curve for each model. Args: roc_thresholds_by_model (dict): A dictionary of ROC thresholds by model name. save (bool): False to display the image (default) or True to save it (but not display it) debug (bool): verbost output. """ # TODO consolidate this and PR plotter into 1 function # TODO make the colors randomly generated from rgb values # Cycle through the colors list color_iterator = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k']) # Initialize plot plt.figure() plt.xlabel('False Positive Rate (FPR)') plt.ylabel('True Positive Rate (TRP)') plt.title('Receiver Operating Characteristic (ROC)') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.plot([0, 1], [0, 1], linestyle=DIAGONAL_LINE_STYLE, color=DIAGONAL_LINE_COLOR) # Calculate and plot for each model for color, (model_name, metrics) in zip(color_iterator, roc_thresholds_by_model.items()): # Extract model name and metrics from dictionary roc_auc = metrics['roc_auc'] tpr = metrics['true_positive_rates'] fpr = metrics['false_positive_rates'] best_true_positive_rate = metrics['best_true_positive_rate'] best_false_positive_rate = metrics['best_false_positive_rate'] if debug: print('{} model:'.format(model_name)) print(pd.DataFrame({'FPR': fpr, 'TPR': tpr})) # plot the line label = '{} (ROC AUC = {})'.format(model_name, round(roc_auc, 2)) plt.plot(fpr, tpr, color=color, label=label) plt.plot([best_false_positive_rate], [best_true_positive_rate], marker='*', markersize=10, color=color) plt.legend(loc="lower right") if save: plt.savefig('ROC.png') source_path = os.path.dirname(os.path.abspath(__file__)) print('\nROC plot saved in: {}'.format(source_path)) plt.show()
26,847
def prepareNNImages(bact_img, ftsz_img, model, bacteria=False): """Preprocess raw iSIM images before running them throught the neural network. Returns a 3D numpy array that contains the data for the neural network and the positions dict generated by getTilePositions for tiling. """ # Set iSIM specific values pixelCalib = 56 # nm per pixel sig = 121.5 / 81 # in pixel resizeParam = pixelCalib / 81 # no unit try: nnImageSize = model.layers[0].input_shape[0][1] except AttributeError: nnImageSize = model positions = None # Preprocess the images if nnImageSize is None or ftsz_img.shape[1] > nnImageSize: # Adjust to 81nm/px bact_img = transform.rescale(bact_img, resizeParam) ftsz_img = transform.rescale(ftsz_img, resizeParam) # This leaves an image that is smaller then initially # gaussian and background subtraction bact_img = filters.gaussian(bact_img, sig, preserve_range=True) ftsz_img = filters.gaussian( ftsz_img, sig, preserve_range=True ) - filters.gaussian(ftsz_img, sig * 5, preserve_range=True) # Tiling if nnImageSize is not None: positions = getTilePositionsV2(ftsz_img, nnImageSize) contrastMax = 255 else: contrastMax = 1 # Contrast ftsz_img = exposure.rescale_intensity( ftsz_img, (np.min(ftsz_img), np.max(ftsz_img)), out_range=(0, contrastMax) ) bact_img = exposure.rescale_intensity( bact_img, (np.mean(bact_img), np.max(bact_img)), out_range=(0, contrastMax) ) else: positions = { "px": [(0, 0, ftsz_img.shape[1], ftsz_img.shape[1])], "n": 1, "overlap": 0, "stitch": 0, } # Put into format for the network if nnImageSize is not None: ftsz_img = ftsz_img.reshape(1, ftsz_img.shape[0], ftsz_img.shape[0], 1) bact_img = bact_img.reshape(1, bact_img.shape[0], bact_img.shape[0], 1) inputDataFull = np.concatenate((bact_img, ftsz_img), axis=3) # Cycle through these tiles and make one array for everything i = 0 inputData = np.zeros( (positions["n"] ** 2, nnImageSize, nnImageSize, 2), dtype=np.uint8() ) for position in positions["px"]: inputData[i, :, :, :] = inputDataFull[ :, position[0] : position[2], position[1] : position[3], : ] if bacteria: inputData[i, :, :, 1] = exposure.rescale_intensity( inputData[i, :, :, 1], (0, np.max(inputData[i, :, :, 1])), out_range=(0, 255), ) inputData[i, :, :, 0] = exposure.rescale_intensity( inputData[i, :, :, 0], (0, np.max(inputData[i, :, :, 0])), out_range=(0, 255), ) i = i + 1 inputData = inputData.astype("uint8") else: # This is now missing the tile-wise rescale_intensity for the mito channel. # Image shape has to be in multiples of 4, not even quadratic cropPixels = ( bact_img.shape[0] - bact_img.shape[0] % 4, bact_img.shape[1] - bact_img.shape[1] % 4, ) bact_img = bact_img[0 : cropPixels[0], 0 : cropPixels[1]] ftsz_img = ftsz_img[0 : cropPixels[0], 0 : cropPixels[1]] positions = getTilePositionsV2(bact_img, 128) bact_img = bact_img.reshape(1, bact_img.shape[0], bact_img.shape[0], 1) ftsz_img = ftsz_img.reshape(1, ftsz_img.shape[0], ftsz_img.shape[0], 1) inputData = np.stack((bact_img, ftsz_img), 3) return inputData, positions
26,848
def com_google_fonts_check_metadata_undeclared_fonts(family_metadata, family_directory): """Ensure METADATA.pb lists all font binaries.""" pb_binaries = [] for font_metadata in family_metadata.fonts: pb_binaries.append(font_metadata.filename) passed = True binaries = [] for entry in os.listdir(family_directory): if entry != "static" and os.path.isdir(os.path.join(family_directory, entry)): for filename in os.listdir(os.path.join(family_directory, entry)): if filename[-4:] in [".ttf", ".otf"]: path = os.path.join(family_directory, entry, filename) passed = False yield WARN,\ Message("font-on-subdir", f'The file "{path}" is a font binary' f' in a subdirectory.\n' f'Please keep all font files (except VF statics) directly' f' on the root directory side-by-side' f' with its corresponding METADATA.pb file.') else: # Note: This does not include any font binaries placed in a "static" subdir! if entry[-4:] in [".ttf", ".otf"]: binaries.append(entry) for filename in sorted(set(pb_binaries) - set(binaries)): passed = False yield FAIL,\ Message("file-missing", f'The file "{filename}" declared on METADATA.pb' f' is not available in this directory.') for filename in sorted(set(binaries) - set(pb_binaries)): passed = False yield FAIL,\ Message("file-not-declared", f'The file "{filename}" is not declared on METADATA.pb') if passed: yield PASS, "OK"
26,849
def get_key(val): """ Get dict key by value :param val: :return: """ for key, value in HANDSHAKE.items(): if val == value: return key
26,850
def switch_to_frame_with_id(self, frame): """Swap Selenium's context to the given frame or iframe.""" elem = world.browser.find_element_by_id(frame) world.browser.switch_to.frame(elem)
26,851
def valid_text(val, rule): """Return True if regex fully matches non-empty string of value.""" if callable(rule): match = rule(val) else: match = re.findall(rule, val) return (False if not match or not val else True if match is True else match[0] == val)
26,852
def settings(): """Render the settings page.""" c = mongo.db[app.config['USERS_COLLECTION']] user = c.find_one({'username': current_user.get_id()}) if not user: return render_template() user['id'] = str(user['_id']) user.pop('_id', None) return render_template('settings.html', user=user)
26,853
def exportAllScansS3(folder_id): """ Exports all Tenable scans found in a folder to S3. """ scan_list = [] scans = client.scan_helper.scans(folder_id=folder_id) for scan in scans: if scan.status() != 'completed': continue scan.download("./%s.html" % scan.details().info.name, format='html') scan_list.append(scan.id) return scan_list
26,854
def pytest_runtest_teardown(): """ Removing log handler which was created in func:`pytest_runtest_setup` """ fh = logging.getLogger().handlers[1] fh.close() logging.getLogger().removeHandler(fh)
26,855
def check_ontology_graph(ontology_key, survol_agent=None): """This checks that a full ontology contains a minimal subset of classes and attributes. This is for testing purpose only.""" url_script = { "survol": "ontologies/Survol_RDFS.py", "wmi": "ontologies/WMI_RDFS.py", "wbem": "ontologies/WBEM_RDFS.py"}[ontology_key] if survol_agent: # TODO: The url syntax differences between SourceLocal and SourceRemote are not convenient. # TODO: Remove this leading "/" slash. my_source = SourceRemote(survol_agent + "/survol/" + url_script) else: my_source = SourceLocal(url_script) ontology_survol = my_source.get_content_moded(None) assert isinstance(ontology_survol, six.binary_type) ontology_graph = rdflib.Graph() result = ontology_graph.parse(data=ontology_survol, format="application/rdf+xml") return lib_kbase.check_minimal_rdsf_ontology(ontology_graph)
26,856
def Retry(retry_value=Exception, max_retries=None, initial_delay_sec=1.0, delay_growth_factor=1.5, delay_growth_fuzz=0.1, max_delay_sec=60): """Returns a retry decorator.""" if max_retries is None: max_retries = 2**30 # Effectively forever. if delay_growth_factor < 1.0: raise ValueError("Invalid delay_growth_factor: %f" % delay_growth_factor) def _Retry(func): @functools.wraps(func) def Wrapper(*args, **kwargs): """Decorator wrapper.""" delay = initial_delay_sec for retries in itertools.count(0): try: return func(*args, **kwargs) except retry_value as e: if retries >= max_retries: raise time.sleep(delay) fuzz_factor = 1.0 + random.random() * delay_growth_fuzz delay += delay * (delay_growth_factor - 1) * fuzz_factor delay = min(delay, max_delay_sec) e_desc_str = "".join(traceback.format_exception_only(e.__class__, e)) stack_traceback_str = "".join(traceback.format_stack()[:-2]) e_traceback = sys.exc_info()[2] e_traceback_str = "".join(traceback.format_tb(e_traceback)) tf.logging.info( "Retry: caught exception: %s while running %s. " "Call failed at (most recent call last):\n%s" "Traceback for above exception (most recent call last):\n%s" "Waiting for %.2f seconds before retrying.", func.__name__, e_desc_str, stack_traceback_str, e_traceback_str, delay) return Wrapper return _Retry
26,857
def download_handler(resource, _, filename=None, inline=False, activity_id=None): """Get the download URL from LFS server and redirect the user there """ if resource.get('url_type') != 'upload' or not resource.get('lfs_prefix'): return None context = get_context() data_dict = {'resource': resource, 'filename': filename, 'inline': inline, 'activity_id': activity_id} resource_download_spec = tk.get_action('get_resource_download_spec')(context, data_dict) href = resource_download_spec.get('href') if href: return tk.redirect_to(href) else: return tk.abort(404, tk._('No download is available'))
26,858
def _add_subtitle(fig, case_date: date, site_name: str): """Adds subtitle into figure.""" text = _get_subtitle_text(case_date, site_name) fig.suptitle(text, fontsize=13, y=0.885, x=0.07, horizontalalignment='left', verticalalignment='bottom')
26,859
def body_open(): """open the main logic""" return " @coroutine\n def __query(__connection):"
26,860
def db_add_entry(user_auth,\ name:str, user_id:str, user_pw:str, url:str=''): """ Add an entry into the credentials database, and returns the inserted row. If insertion fails, return None. """ # SQL Query sql = f'INSERT INTO {DB_TABLE}' sql += '(name, user_id, user_pw, url, date_created, date_modified) ' sql += 'VALUES(?, ?, ?, ?, ?, ?)' # Params user_id_enc = user_auth.encrypt(user_id) user_pw_enc = user_auth.encrypt(user_pw) current_ts = get_current_ts() sql_params = [name, user_id_enc, user_pw_enc, url, current_ts, current_ts] entry_id = -1 # Run SQL try: with user_auth.conn as conn: cur = conn.cursor() cur.execute(sql, sql_params) entry_id = cur.lastrowid cur.close() except sqlite3.DatabaseError: return False # Sign the entry user_auth.sign_entry(entry_id, update_db=True) return True
26,861
def First(): """(read-only) Sets the first sensor active. Returns 0 if none.""" return lib.Sensors_Get_First()
26,862
def rch_from_model_ds(model_ds, gwf): """get recharge package from model dataset. Parameters ---------- model_ds : xarray.Dataset dataset with model data. gwf : flopy ModflowGwf groundwaterflow object. Returns ------- rch : flopy ModflowGwfrch rch package """ # create recharge package rch = recharge.model_datasets_to_rch(gwf, model_ds) return rch
26,863
def _drawdots_on_origin_image(mats, usage, img, notation_type, color=['yellow', 'green', 'blue', 'red']): """ For visualizatoin purpose, draw different color on original image. :param mats: :param usage: Detection or Classfifcation :param img: original image :param color: color list for each category :return: dotted image """ if usage == 'Classification': for i, mat in enumerate(mats): mat_content = mat['detection'] _draw_points(mat_content, img, color[i], notation_type=notation_type) elif usage == 'Detection': mat_content = mats['detection'] _draw_points(mat_content, img, color[0], notation_type=notation_type) return img
26,864
def scale(*args, x = 1, y = 1): """ Returns a transformation which scales a path around the origin by the specified amount. `scale(s)`: Scale uniformly by `s`. `scale(sx, sy)`: Scale by `sx` along the x axis and by `sy` along the y axis. `scale(x = sx)`: Scale along the x axis only. `scale(y = sy)`: Scale along the y axis only. """ if args: if len(args) == 1: args *= 2 x, y = args return transform(x, 0, 0, 0, y, 0)
26,865
def load_tweet_users_posted_rumours(): """ load user history (whether a user posted any rumour in the past) :return: dict {timestamp at which the user posted a rumour: user_id} """ with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tweet_users_posted_rumours'), 'rb') as outfile: rumour_users = pickle.load(outfile) outfile.close() return rumour_users
26,866
def create_power_anomaly_pipeline(hparams): """ Generate anomalies of types 1 to 4 for a given power time series """ pipeline = Pipeline(path=os.path.join('run')) seed = hparams.seed # Type 1: Negative power spike potentially followed by zero values and finally a positive power spike anomaly_type1 = PowerAnomalyGeneration( 'y_hat', anomaly='type1', count=hparams.type1, label=1, seed=seed + 1, length_params={ 'distribution': 'uniform', 'min': hparams.type1_len_min, 'max': hparams.type1_len_max }, anomaly_params={ 'k': hparams.k } )(x=pipeline['y'], labels=None) # Type 2: Drop to potentially zero followed by a positive power spike anomaly_type2 = PowerAnomalyGeneration( 'y_hat', anomaly='type2', count=hparams.type2, label=2, seed=seed + 2, length_params={ 'distribution': 'uniform', 'min': hparams.type2_len_min, 'max': hparams.type2_len_max, }, anomaly_params={ 'softstart': hparams.type2_softstart } )(x=anomaly_type1['y_hat'], labels=anomaly_type1['labels']) # Type 3: Sudden negative power spike if hparams.type3_extreme: anomaly_type3 = PowerAnomalyGeneration( 'y_hat', anomaly='type3', count=hparams.type3, label=32, seed=seed + 4, anomaly_params={ 'is_extreme': True, 'k': hparams.k } )(x=anomaly_type2['y_hat'], labels=anomaly_type2['labels']) else: anomaly_type3 = PowerAnomalyGeneration( 'y_hat', anomaly='type3', count=hparams.type3, label=31, seed=seed + 3, anomaly_params={ 'is_extreme': False, 'range_r': (hparams.type3_r_min, hparams.type3_r_max), } )(x=anomaly_type2['y_hat'], labels=anomaly_type2['labels']) # Type 4: Sudden positive power spike anomaly_type4 = PowerAnomalyGeneration( 'y_hat', anomaly='type4', count=hparams.type4, label=4, seed=seed + 5, anomaly_params={ 'range_r': (hparams.type4_r_min, hparams.type4_r_max) } )(x=anomaly_type3['y_hat'], labels=anomaly_type3['labels']) FunctionModule(lambda x: x, name='y')(x=pipeline['y']) FunctionModule(lambda x: x, name='anomalies')(x=anomaly_type4['labels']) FunctionModule(lambda x: x, name='y_hat')(x=anomaly_type4['y_hat']) return pipeline
26,867
async def async_setup_entry(hass, config_entry): """Set up Tile as config entry.""" websession = aiohttp_client.async_get_clientsession(hass) client = await async_login( config_entry.data[CONF_USERNAME], config_entry.data[CONF_PASSWORD], session=websession, ) async def async_update_data(): """Get new data from the API.""" try: return await client.tiles.all() except SessionExpiredError: LOGGER.info("Tile session expired; creating a new one") await client.async_init() except TileError as err: raise UpdateFailed(f"Error while retrieving data: {err}") from err coordinator = DataUpdateCoordinator( hass, LOGGER, name=config_entry.title, update_interval=DEFAULT_UPDATE_INTERVAL, update_method=async_update_data, ) await coordinator.async_refresh() hass.data[DOMAIN][DATA_COORDINATOR][config_entry.entry_id] = coordinator for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, component) ) return True
26,868
def read_csv_by_chunks_createindices_and_partitionPQbygroup(input_csv_path, parquet_dataset_output_path, indices_csv_output_path, chunksize, n_parts): """ convert csv to parquet by chunks :param str input_csv_path: path to the csv file :param str parquet_dataset_path: path to the output parquet file :param int chunksize: size of the chunk to read :param int n_parts: number of partitions :returns: parquet file """ csv_stream = pd.read_csv(input_csv_path, sep=',', chunksize=chunksize, low_memory=False) fields = [pa.field('Protein Name', pa.string()), pa.field('Peptide Modified Sequence', pa.string()), pa.field('Modified Sequence', pa.string()), pa.field('Isotope Label Type', pa.string()), pa.field('Is Decoy', pa.bool_()), pa.field('Precursor Charge', pa.int64()), pa.field('Precursor Mz', pa.float64()), pa.field('Product Charge', pa.int64()), pa.field('Product Mz', pa.float64()), pa.field('Fragment Ion', pa.string()), pa.field('Transition Locator', pa.string()), pa.field('Quantitative', pa.bool_()), pa.field('File Name', pa.string()), pa.field('Library Dot Product', pa.float64()), pa.field('Min Start Time', pa.float64()), pa.field('Max End Time', pa.float64()), pa.field('Area', pa.float64()), pa.field('Library Intensity', pa.float64()), pa.field('Interpolated Times', pa.string()), pa.field('Interpolated Intensities', pa.string()), pa.field('Interpolated Mass Errors', pa.string()), pa.field('Precursor Result Locator', pa.string()), pa.field('ID_FragmentIon_charge', pa.string()), pa.field('ID_Rep', pa.string()), pa.field('ID_Analyte', pa.string()), pa.field('ID_group', pa.int64()), ] my_schema = pa.schema(fields) for i, chunk in enumerate(csv_stream): print("Chunk", i) df_annotated = create_indices(chunk, n_parts) table = pa.Table.from_pandas(df=df_annotated, schema=my_schema) pq.write_to_dataset(table, root_path=parquet_dataset_output_path, partition_cols=['ID_group', 'ID_Analyte']) df = df_annotated # Create directory files to save the correspondance of the hash ids and the real values def write_to_same_csv_appending(dt, j, path, filename=None): if filename is not None: path_file = os.path.join(path, filename) else: path_file = path if j == 0: dt.to_csv(path_file, index=False, header=True) else: dt.to_csv(path_file, mode='a', index=False, header=False) df_ID_FragmentIon_charge = df[['ID_FragmentIon_charge', 'Fragment Ion', 'Product Charge']].drop_duplicates() write_to_same_csv_appending(df_ID_FragmentIon_charge, i, indices_csv_output_path, "ID_FragmentIon_charge.csv") df_ID_Rep = df[['ID_Rep', 'File Name']].drop_duplicates() write_to_same_csv_appending(df_ID_Rep, i, indices_csv_output_path, "ID_Rep.csv") df_transition_locator = df[['Transition Locator', 'ID_FragmentIon_charge', 'ID_Analyte']].drop_duplicates() write_to_same_csv_appending(df_transition_locator, i, indices_csv_output_path, "ID_transition_locator.csv") df_ID_Analyte = df[['ID_Analyte', 'Protein Name', 'Peptide Modified Sequence', 'Precursor Charge', 'Is Decoy']].drop_duplicates() write_to_same_csv_appending(df_ID_Analyte, i, indices_csv_output_path, "ID_Analyte.csv") df_ID_Analyte_withgroup = df[['ID_Analyte', 'Protein Name', 'Peptide Modified Sequence', 'Precursor Charge', 'Is Decoy', 'ID_group']].drop_duplicates() write_to_same_csv_appending(df_ID_Analyte_withgroup, i, indices_csv_output_path, "ID_Analyte_withgroup.csv") #new df_ID_PrecursorResult = df[['Precursor Result Locator', 'Protein Name', 'Peptide Modified Sequence', 'Isotope Label Type', 'Precursor Charge', 'Is Decoy', 'File Name']].drop_duplicates() write_to_same_csv_appending(df_ID_PrecursorResult, i, indices_csv_output_path, "MetaData_PrecursorResults.csv") # read, drop duplicates and write file again def read_drop_duplicates_rewrite(path): pd.read_csv(path).drop_duplicates().to_csv(path, index=False, header=True) read_drop_duplicates_rewrite(os.path.join(indices_csv_output_path, "ID_FragmentIon_charge.csv")) read_drop_duplicates_rewrite(os.path.join(indices_csv_output_path, "ID_Rep.csv")) read_drop_duplicates_rewrite(os.path.join(indices_csv_output_path, "ID_transition_locator.csv")) read_drop_duplicates_rewrite(os.path.join(indices_csv_output_path, "ID_Analyte.csv")) read_drop_duplicates_rewrite(os.path.join(indices_csv_output_path, "ID_Analyte_withgroup.csv")) # new read_drop_duplicates_rewrite(os.path.join(indices_csv_output_path, "MetaData_PrecursorResults.csv"))
26,869
def _generate_presigned_url(context, bucket, key, callback): """ Generates presigned URL :param Context context: Thumbor's context :param string bucket: Bucket name :param string key: Path to get URL for :param callable callback: Callback method once done """ Bucket(bucket, context.config.get('TC_AWS_REGION')).get_url(key, callback=callback)
26,870
def get_selection_uri_template(): """ Utility function, to build Selection endpoint's Falcon uri_template string >>> get_selection_uri_template() '/v1/source/{source_id}/selection.{type}' """ str_source_uri = get_uri_template(source.str_route) path_selection = selection.str_route param_id = source_parameters.source_id param_type = selection.str_param_type str_selection_uri = ''.join( ['/{', param_id, '}/', path_selection, '{', param_type, '}'] ) return str_source_uri+str_selection_uri
26,871
def client_thread_runner(port, nums=[]): """Client. """ tid = threading.current_thread().ident sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockobj.settimeout(1.0 * len(nums)) sockobj.connect(('localhost', port)) logging.info('Client {0} connected to server'.format(tid)) for num in nums: sockobj.send(bytes(str(num), encoding='ascii')) logging.info('Client {0} sent "{1}"'.format(tid, num)) reply = sockobj.recv(20) logging.info('Client {0} received "{1}"'.format(tid, reply)) if is_prime(num): assert b'prime' in reply else: assert b'composite' in reply sockobj.shutdown(socket.SHUT_RDWR) sockobj.close()
26,872
def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev) b -- Bias parameters contained in a window - matrix of shape (1, 1, 1) Returns: Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data """ ### START CODE HERE ### (≈ 2 lines of code) # Element-wise product between a_slice and W. Do not add the bias yet. s = a_slice_prev * W # Sum over all entries of the volume s. Z = s.sum() # Add bias b to Z. Cast b to a float() so that Z results in a scalar value. Z = Z + np.asscalar(b.astype(np.float)) ### END CODE HERE ### return Z
26,873
def _is_pyqt_obj(obj): """Checks if ``obj`` wraps an underlying C/C++ object.""" if isinstance(obj, QtCore.QObject): try: obj.parent() return True except RuntimeError: return False else: return False
26,874
def get_optimizer( optim_type: str, optimizer_grouped_parameters, lr: float, weight_decay: float, eps: Optional[float] = 1e-6, betas: Optional[Tuple[float, float]] = (0.9, 0.999), momentum: Optional[float] = 0.9, ): """ Choose a Pytorch optimizer based on its name. Parameters ---------- optim_type Name of optimizer. optimizer_grouped_parameters The model parameters to be optimized. lr Learning rate. weight_decay Optimizer weight decay. eps Optimizer eps. betas Optimizer betas. momentum Momentum used in the SGD optimizer. Returns ------- A Pytorch optimizer. """ if optim_type == "adamw": optimizer = optim.AdamW( optimizer_grouped_parameters, lr=lr, weight_decay=weight_decay, eps=eps, betas=betas, ) elif optim_type == "adam": optimizer = optim.Adam( optimizer_grouped_parameters, lr=lr, weight_decay=weight_decay, ) elif optim_type == "sgd": optimizer = optim.SGD( optimizer_grouped_parameters, lr=lr, weight_decay=weight_decay, momentum=momentum, ) else: raise ValueError(f"unknown optimizer: {optim_type}") return optimizer
26,875
def point_maze(): """IRL config for PointMaze environment.""" env_name = "imitation/PointMazeLeftVel-v0" rollout_path = os.path.join( serialize.get_output_dir(), "train_experts/ground_truth/20201203_105631_297835/imitation_PointMazeLeftVel-v0", "evaluating_rewards_PointMazeGroundTruthWithCtrl-v0/best/rollouts/final.pkl", ) total_timesteps = 1e6 _ = locals() del _
26,876
def forward(observations, transitions, sequence_len, batch=False): """Implementation of the forward algorithm in Keras. Returns the log probability of the given observations and transitions by recursively summing over the probabilities of all paths through the state space. All probabilities are in logarithmic space. See e.g. https://en.wikipedia.org/wiki/Forward_algorithm . Args: observations (tensor): A tensor of the observation log probabilities, shape (sequence_len, num_states) if batch is False, (batch_size, sequence_len, num_states) otherwise. transitions (tensor): A (num_states, num_states) tensor of the transition weights (log probabilities). sequence_len (int): The number of steps in the sequence. This must be given because unrolling scan() requires a definite (not tensor) value. batch (bool): Whether to run in batchwise mode. If True, the first dimension of observations corresponds to the batch. Returns: Total log probability if batch is False or vector of log probabiities otherwise. """ step = make_forward_step(transitions, batch) if not batch: first, rest = observations[0, :], observations[1:, :] else: first, rest = observations[:, 0, :], observations[:, 1:, :] sequence_len -= 1 # exclude first outputs, _ = scan(step, rest, first, n_steps=sequence_len, batch=batch) if not batch: last, axis = outputs[sequence_len-1], 0 else: last, axis = outputs[:, sequence_len-1], 1 return logsumexp(last, axis=axis)
26,877
def fib(n): """Return the n'th Fibonacci number. """ if n < 0: raise ValueError("Fibonacci numbers are only defined for n >= 0.") return _fib(n)
26,878
def check_column(board): """ list -> bool This function checks if every column has different numbers and returns True is yes, and False if not. >>> check_column(["**** ****", "***1 ****", "** 3****", \ "* 4 1****", " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"]) False >>> check_column(["**** ****", "***1 ****", "** 3****", \ "* 4 1****", " 9 5 ", " 6 83 *", "3 5 **", " 8 2***", " 2 ****"]) True """ length = len(board) for i in range(length): one_line = [] for line in board: if line[i] == '*' or line[i] == ' ': continue if line[i] in one_line: return False else: one_line.append(line[i]) return True
26,879
def lines_len_in_circle(r, font_size=12, letter_width=7.2): """Return the amount of chars that fits each line in a circle according to its radius *r* Doctest: .. doctest:: >>> lines_len_in_circle(20) [2, 5, 2] """ lines = 2 * r // font_size positions = [ x + (font_size // 2) * (-1 if x <= 0 else 1) for x in text_y(lines) ] return [ int(2 * r * cos(asin(y / r)) / letter_width) for y in positions ]
26,880
def exec_psql(conn_str, query, **args): # type: (str, str, dict) -> str """ Executes SQL queries by forking and exec-ing '/usr/bin/psql'. :param conn_str: A "connection string" that defines the postgresql resource in the format {schema}://{user}:{password}@{host or IP}:{port}/{database} :param query: The query to be run. It can actually be a script containing multiple queries. :returns: The comma-separated columns of each line-delimited row of the results of the query. """ cmd = ["/usr/bin/psql", "--tuples-only", "-d", conn_str, "-c", query] + list(args.values()) proc = subprocess.Popen( cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, ) proc.wait() output = proc.communicate() if proc.returncode != 0: logging.debug("psql exec failed; stderr: %s\n\tstdout: %s", output[1], output[0]) raise OSError("failed to execute database query") if sys.version_info.major >= 3: return output[0].strip() else: return string.strip(output[0])
26,881
def wait_for_dialog(bus, dialogs, context=None, timeout=None): """Wait for one of the dialogs given as argument. Args: bus (InterceptAllBusClient): Bus instance to listen on dialogs (list): list of acceptable dialogs context (behave Context): optional context providing scenario timeout timeout (int): how long to wait for the message, defaults to timeout provided by context or 10 seconds """ if context: timeout_duration = timeout or context.step_timeout else: timeout_duration = timeout or DEFAULT_TIMEOUT wait_for_dialog_match(bus, dialogs, timeout_duration)
26,882
def test_filtered_data_shape(): """Test that filtering data returns same shape.""" data = rs.randn(100) data_filt = glm.fsl_highpass_filter(data, 30) nt.assert_equal(data.shape, data_filt.shape) data = rs.randn(100, 3) data_filt = glm.fsl_highpass_filter(data, 30) nt.assert_equal(data.shape, data_filt.shape)
26,883
def capacitorCorrection(m_cap): """Apply a correction to the measured capacitance value to get a value closer to the real value. One reason this may differ is measurement varies based on frequency. The measurements are performed at 30Hz but capacitance values are normally quoted for 1kHz. The coefficients are based on mutiple linear regression in R using rms-based measurements of capacitors vs readings from multimeter plus a fudge for small values! """ ### These are based on 30Hz sine wave with 2x2k2 + 2x10nF ### + internal_res = 200 and no esr correction ###return -7.599263e-08 + 9.232542e-01 * m_cap + 1.690527e+04 * m_cap * m_cap ### 31Hz sine 2x2k2 + 2x10nF with internal_res = 140 no esr correction poly2_cor = -6.168148e-08 + 8.508691e-01 * m_cap + 2.556320e+04 * m_cap * m_cap return poly2_cor if poly2_cor > 30e-9 else m_cap * 0.2
26,884
def test_mat_vec_math(): """test_mat_vec_math Verifies that the Mat and Vec objects from proteus.LinearAlgebraTools behave as expected together when computing basic linear algebra for one trial. """ from proteus.LinearAlgebraTools import Vec from proteus.LinearAlgebraTools import Mat v1 = Vec(2) v1[:] = [1, 1] m1 = Mat(3, 2) m1[0, :] = [1, 2] m1[1, :] = [3, 2] m1[2, :] = [4, 5] # m1*v1 dot_product = np.asarray([3, 5, 9]) npt.assert_almost_equal(dot_product, m1.dot(v1))
26,885
def set_log_level(level): """Sets log level.""" global _log_level _log_level = level
26,886
def code128_quebrar_partes(partes): """ Obtém as partes em que o Code128 deverá ser quebrado. Os códigos de barras Code128 requerem que os dados possuam um comprimento par, para que os dados possam ser codificados nessa simbologia. Embora a chave do CF-e-SAT possua 44 digitos, nem todas as mídias acomodam a impressão completa de 44 dígitos na simbologia Code128, por isso, o Manual de Orientação do SAT permite que o código de barras da chave seja quebrado em duas ou mais partes, ficando, por exemplo, um Code128 com os primeiros 22 dígitos da chave do CF-e e outro Code128 logo abaixo com os 22 dígitos restantes. Essa quebra pode ser feita em 4 códigos de barras, mas eles não podem ser formados por 4 partes de 11 dígitos, devido à limitação da simbologia Code128 de codificar os dados em sequências pares. Para dar certo quebrar o Code128 em 4 partes, cada parte precisaria indicar comprimentos de ``10, 10, 10, 14``, somando 44 dígitos, ou indicar comprimentos de ``12, 12, 12, 8``, somando 44 dígitos. :param str partes: Uma string que especifica uma lista de números inteiros, pares, maiores que zero e separados por vírgulas, cuja soma deve ser igual a 44, que é o comprimento da chave do CF-e-SAT. :returns: Retorna uma tupla de números inteiros, extraídos da string informada no argumento. :rtype: tuple """ try: lista_partes = [int(p) for p in partes.split(',')] except ValueError: raise ValueError( ( 'Configuracoes do extrato do CF-e-SAT, Code128 em ' 'partes deve especificar as partes em valores inteiros, ' 'todos numeros pares e separados por virgulas; ' 'obtido: {!r}' ).format(partes) ) # checa se a lista contém apenas números pares for i, n in enumerate(lista_partes, 1): if n <= 0 or n % 2 != 0: raise ValueError( ( 'Configuracoes do extrato do CF-e-SAT, Code128, ' 'elemento {!r} deve ser um número par; obtido {!r}' ).format(i, n) ) calculado = sum(lista_partes) if calculado != _TAMANHO_CHAVE_CFESAT: raise ValueError( ( 'Configuracoes do extrato do CF-e-SAT, Code128 em ' 'partes deve especificar as partes em valores inteiros, ' 'todos numeros pares e separados por virgulas; a soma ' 'das partes deve ser igual ao tamanho da chave do ' 'CF-e-SAT; obtido: {!r} (esperado: {!r})' ).format( calculado, _TAMANHO_CHAVE_CFESAT ) ) return tuple(lista_partes)
26,887
def vortexforce(uu, vv, duu, dvv, idx2=1.0, idy2=1.0): """ Add the omega_z component of the vortex force to the momentum du/dt += omega_z * V dv/dt -= omega_z * U where omega_z = ddx(v) - ddy(u) and (U,V) are the contravariant components of (u,v). If the grid is orthogonal, they read U = u/dx**2 V = v/dy**2 The routine assumes that the arrays are properly ordered, namely that - the outer index corresponds to the direction perpendicular to the (u,v) plane, - the middle index to the v direction, - and the inner index to the u direction. """ nz, ny, nx = np.shape(uu) for k in range(nz): # outer loop u = uu[k] v = vv[k] du = duu[k] dv = dvv[k] if False: for j in range(1, ny-1): for i in range(1, nx-1): # vorticity omega = (v[j, i+1]-v[j, i])-(u[j+1, i]-u[j, i]) # v at u-point ! v is the contravariant component vu = 0.25*(v[j, i]+v[j, i+1]+v[j-1, i]+v[j-1, i+1]) # u at v-point ! u is the contravariant component uv = 0.25*(u[j, i]+u[j, i-1]+u[j+1, i]+u[j+1, i-1]) omega_j = omega # upwinded interpolation at u point along j omega_i = omega # upwinded interpolation at v point along i du[j, i] += vu * omega_j * idy2 dv[j, i] -= uv * omega_i * idx2 elif False: omega = sxp(v)-v-syp(v)+u vu = 0.25*(v+sxp(v)+sym(v+sxp(v))) uv = 0.25*(u+syp(u)+sxm(u+syp(u))) du += vu*omega*idy2 dv -= uv*omega*idx2 else: fi.adv_upwind(u,v,du,dv,nh)
26,888
def prepare_connection(conn, database, datasette): """Modify SQLite connection in some way e.g. register custom SQL functions"""
26,889
def saveCountLists(theoryCountList, realCountList): """ Saves the countList to a file for analysis """ wFile = open("count.txt", "w") wFile.write('Predicted:\n') for c in theoryCountList: wFile.write(str(c)) wFile.write('\n') wFile.write('\nActual:\n') for c in realCountList: wFile.write(str(c)) wFile.write('\n') wFile.close()
26,890
def wrist_mounted_calibration(calibration_data_folder, debug=False): """ Parse our config file and run handical. """ extrinsics_out_file = os.path.join(calibration_data_folder, 'extrinsics.txt') config_filename = os.path.join(calibration_data_folder, 'robot_data.yaml') config = read_config(config_filename) ncols = config['header']['target']['width'] nrows = config['header']['target']['height'] cell_size = config['header']['target']['square_edge_length'] board = ChessBoard((nrows, ncols), cell_size) # read the X_BE poses # X_BE_poses = [] X_EB_list = [] for idx, data in enumerate(config['data_list']): ee_to_base = dict_to_pose(data['hand_frame']) base_to_ee = ee_to_base.inverse() # X_BE_poses.append(ee_to_base) X_EB_list.append(base_to_ee) init_X_BM = dict_to_pose( config['header']['target']['transform_to_robot_base']) cam_intrinsics = [] cam_keys = {} image_type = config['header']['image_type'] print "image_type: ", image_type # we only have one camera if image_type == "ir": intrinsics_prefix = "depth" else: intrinsics_prefix = image_type intrinsics_filename = os.path.join(calibration_data_folder, intrinsics_prefix + "_camera_info.yaml") intrinsics = read_intrinsic(intrinsics_filename) key = 0 camera_name = config['header']['camera'] cam_intrinsics.append(intrinsics) cam_keys[camera_name] = key handical = HandicalWristMount(board.size, board.cell_size, init_X_BM, X_EB_list, cam_intrinsics) for pose_id, X_BE in enumerate(X_EB_list): print "X_BE: ", X_BE img_filename = os.path.join( calibration_data_folder, config['data_list'][pose_id]['images'][image_type]['filename']) img = load_image_as_grayscale(img_filename) handical.add_image(img, pose_id, cam_keys[camera_name], debug) print "graph size: ", handical.backend.graph.size() results, error = handical.calibrate() print("Calibration results:") print results, error save_results(extrinsics_out_file, results, cam_keys, error) calibration_results = calibration_results_to_dict(results) return calibration_results
26,891
def debug(func): """Only for debugging purposes: prints a tree It will print a nice execution tree with arguments and results of all decorated functions. """ if not SYMPY_DEBUG: #normal mode - do nothing return func #debug mode def decorated(*args, **kwargs): #r = func(*args, **kwargs) r = maketree(func, *args, **kwargs) #print "%s = %s(%s, %s)" % (r, func.__name__, args, kwargs) return r return decorated
26,892
def get_s3_keys(bucket): """Get a list of keys in an S3 bucket.""" keys = [] resp = s3.list_objects(Bucket=bucket) for obj in resp['Contents']: keys.append(obj['Key']) return keys
26,893
def plot_maxmin_points(lon, lat, data, extrema, nsize, symbol, color='k', plotValue=True, transform=None): """ This function will find and plot relative maximum and minimum for a 2D grid. The function can be used to plot an H for maximum values (e.g., High pressure) and an L for minimum values (e.g., low pressue). It is best to used filetered data to obtain a synoptic scale max/min value. The symbol text can be set to a string value and optionally the color of the symbol and any plotted value can be set with the parameter color lon = plotting longitude values (2D) lat = plotting latitude values (2D) data = 2D data that you wish to plot the max/min symbol placement extrema = Either a value of max for Maximum Values or min for Minimum Values nsize = Size of the grid box to filter the max and min values to plot a reasonable number symbol = String to be placed at location of max/min value color = String matplotlib colorname to plot the symbol (and numerica value, if plotted) plot_value = Boolean (True/False) of whether to plot the numeric value of max/min point The max/min symbol will be plotted on the current axes within the bounding frame (e.g., clip_on=True) ^^^ Notes from MetPy. Function adapted from MetPy. """ from scipy.ndimage.filters import maximum_filter, minimum_filter if (extrema == 'max'): data_ext = maximum_filter(data, nsize, mode='nearest') elif (extrema == 'min'): data_ext = minimum_filter(data, nsize, mode='nearest') else: raise ValueError('Value for hilo must be either max or min') mxy, mxx = np.where(data_ext == data) for i in range(len(mxy)): ax.text(lon[mxy[i], mxx[i]], lat[mxy[i], mxx[i]], symbol, color=color, size=13, clip_on=True, horizontalalignment='center', verticalalignment='center', fontweight='extra bold', transform=transform) ax.text(lon[mxy[i], mxx[i]], lat[mxy[i], mxx[i]], '\n \n' + str(np.int(data[mxy[i], mxx[i]])), color=color, size=8, clip_on=True, fontweight='bold', horizontalalignment='center', verticalalignment='center', transform=transform, zorder=10) return ax
26,894
def _get_results(model): """ Helper function to get the results from the solved model instances """ _invest = {} results = solph.processing.convert_keys_to_strings(model.results()) for i in ["wind", "gas", "storage"]: _invest[i] = results[(i, "electricity")]["scalars"]["invest"] return _invest
26,895
def _get_vlan_list(): """ Aggregate vlan data. Args: Returns: Tree of switches and vlan information by port """ log = logger.getlogger() vlan_list = Tree() for ntmpl_ind in CFG.yield_ntmpl_ind(): ntmpl_ifcs = CFG.get_ntmpl_ifcs_all(ntmpl_ind) for ifc in ntmpl_ifcs: vlan_num, vlan_ifc_name = _get_vlan_info(ifc) if vlan_num: vlan_slaves = _get_vlan_slaves(vlan_ifc_name) for phyintf_idx in CFG.yield_ntmpl_phyintf_data_ind(ntmpl_ind): phy_ifc_lbl = CFG.get_ntmpl_phyintf_data_ifc(ntmpl_ind, phyintf_idx) if phy_ifc_lbl in vlan_slaves: vlan_ports = CFG.get_ntmpl_phyintf_data_ports( ntmpl_ind, phyintf_idx) switch = CFG.get_ntmpl_phyintf_data_switch( ntmpl_ind, phyintf_idx) if vlan_num in vlan_list[switch]: vlan_list[switch][vlan_num] += vlan_ports else: vlan_list[switch][vlan_num] = vlan_ports pretty_str = PP.pformat(vlan_list) log.debug('vlan list') log.debug('\n' + pretty_str) # Aggregate by switch and port number port_vlans = Tree() for switch in vlan_list: for vlan in vlan_list[switch]: for port in vlan_list[switch][vlan]: if str(port) in port_vlans[switch]: port_vlans[switch][str(port)].append(vlan) else: port_vlans[switch][str(port)] = [vlan] pretty_str = PP.pformat(port_vlans) log.debug('port_vlans') log.debug('\n' + pretty_str) return port_vlans
26,896
def subtract_overscan(ccd, overscan=None, overscan_axis=1, fits_section=None, median=False, model=None): """ Subtract the overscan region from an image. Parameters ---------- ccd : `~astropy.nddata.CCDData` Data to have overscan frame corrected. overscan : `~astropy.nddata.CCDData` or None, optional Slice from ``ccd`` that contains the overscan. Must provide either this argument or ``fits_section``, but not both. Default is ``None``. overscan_axis : 0, 1 or None, optional Axis along which overscan should combined with mean or median. Axis numbering follows the *python* convention for ordering, so 0 is the first axis and 1 is the second axis. If overscan_axis is explicitly set to None, the axis is set to the shortest dimension of the overscan section (or 1 in case of a square overscan). Default is ``1``. fits_section : str or None, optional Region of ``ccd`` from which the overscan is extracted, using the FITS conventions for index order and index start. See Notes and Examples below. Must provide either this argument or ``overscan``, but not both. Default is ``None``. median : bool, optional If true, takes the median of each line. Otherwise, uses the mean. Default is ``False``. model : `~astropy.modeling.Model` or None, optional Model to fit to the data. If None, returns the values calculated by the median or the mean. Default is ``None``. {log} Raises ------ TypeError A TypeError is raised if either ``ccd`` or ``overscan`` are not the correct objects. Returns ------- ccd : `~astropy.nddata.CCDData` CCDData object with overscan subtracted. Notes ----- The format of the ``fits_section`` string follow the rules for slices that are consistent with the FITS standard (v3) and IRAF usage of keywords like TRIMSEC and BIASSEC. Its indexes are one-based, instead of the python-standard zero-based, and the first index is the one that increases most rapidly as you move through the array in memory order, opposite the python ordering. The 'fits_section' argument is provided as a convenience for those who are processing files that contain TRIMSEC and BIASSEC. The preferred, more pythonic, way of specifying the overscan is to do it by indexing the data array directly with the ``overscan`` argument. Examples -------- Creating a 100x100 array containing ones just for demonstration purposes:: >>> import numpy as np >>> from astropy import units as u >>> arr1 = CCDData(np.ones([100, 100]), unit=u.adu) The statement below uses all rows of columns 90 through 99 as the overscan:: >>> no_scan = subtract_overscan(arr1, overscan=arr1[:, 90:100]) >>> assert (no_scan.data == 0).all() This statement does the same as the above, but with a FITS-style section:: >>> no_scan = subtract_overscan(arr1, fits_section='[91:100, :]') >>> assert (no_scan.data == 0).all() Spaces are stripped out of the ``fits_section`` string. """ if not (isinstance(ccd, CCDData) or isinstance(ccd, np.ndarray)): raise TypeError('ccddata is not a CCDData or ndarray object.') if ((overscan is not None and fits_section is not None) or (overscan is None and fits_section is None)): raise TypeError('specify either overscan or fits_section, but not ' 'both.') if (overscan is not None) and (not isinstance(overscan, CCDData)): raise TypeError('overscan is not a CCDData object.') if (fits_section is not None and not isinstance(fits_section, str)): raise TypeError('overscan is not a string.') if fits_section is not None: overscan = ccd[slice_from_string(fits_section, fits_convention=True)] if overscan_axis is None: overscan_axis = 0 if overscan.shape[1] > overscan.shape[0] else 1 if median: oscan = np.median(overscan.data, axis=overscan_axis) else: oscan = np.mean(overscan.data, axis=overscan_axis) if model is not None: of = fitting.LinearLSQFitter() yarr = np.arange(len(oscan)) oscan = of(model, yarr, oscan) oscan = oscan(yarr) if overscan_axis == 1: oscan = np.reshape(oscan, (oscan.size, 1)) else: oscan = np.reshape(oscan, (1, oscan.size)) else: if overscan_axis == 1: oscan = np.reshape(oscan, oscan.shape + (1,)) else: oscan = np.reshape(oscan, (1,) + oscan.shape) subtracted = ccd.copy() # subtract the overscan subtracted.data = ccd.data - oscan return subtracted
26,897
def read_raw(omega): """Read the raw temperature, humidity and dewpoint values from an OMEGA iServer. Parameters ---------- omega : :class:`msl.equipment.record_types.EquipmentRecord` The Equipment Record of an OMEGA iServer. Returns ------- :class:`str` The serial number of the OMEGA iServer. :class:`dict` The data. """ nprobes = omega.connection.properties.get('nprobes', 1) nbytes = omega.connection.properties.get('nbytes') error = None try: cxn = omega.connect() thd = cxn.temperature_humidity_dewpoint(probe=1, nbytes=nbytes) if nprobes == 2: thd += cxn.temperature_humidity_dewpoint(probe=2, nbytes=nbytes) cxn.disconnect() except Exception as e: error = str(e) thd = [None] * (nprobes * 3) now_iso = datetime.now().replace(microsecond=0).isoformat(sep='T') data = { 'error': error, 'alias': omega.alias, 'datetime': now_iso, 'report_number': None, } if len(thd) == 3: data.update({ 'temperature': thd[0], 'humidity': thd[1], 'dewpoint': thd[2] }) else: data.update({ 'temperature1': thd[0], 'humidity1': thd[1], 'dewpoint1': thd[2], 'temperature2': thd[3], 'humidity2': thd[4], 'dewpoint2': thd[5] }) return omega.serial, data
26,898
def test_login_logout(client): """Make sure logging in and logging out works""" rv = register_and_login(client, 'user1', 'default') assert b'You were logged in' in rv.data rv = logout(client) assert b'You were logged out' in rv.data rv = login(client, 'user1', 'wrongpassword') assert b'Invalid password' in rv.data rv = login(client, 'user2', 'wrongpassword') assert b'Invalid username' in rv.data
26,899