content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from . artifactory import Artifactory __all__ = ['Artifactory']
[ 6738, 764, 14077, 9548, 1330, 3683, 361, 9548, 198, 198, 834, 439, 834, 796, 37250, 8001, 361, 9548, 20520, 198 ]
3.25
20
# vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
[ 628, 198, 2, 43907, 25, 4292, 8658, 7400, 11338, 28, 19, 6482, 10394, 28, 19, 2705, 8658, 11338, 28, 19, 783, 2416, 198 ]
2.782609
23
import peewee import playhouse.kv from time import time from . import CacheableAdapter
[ 11748, 613, 413, 1453, 198, 11748, 711, 4803, 13, 74, 85, 198, 6738, 640, 1330, 640, 198, 198, 6738, 764, 1330, 34088, 540, 47307, 628 ]
3.56
25
from collections import namedtuple import torch from torch.nn import (AdaptiveAvgPool2d, BatchNorm2d, Conv2d, MaxPool2d, Module, PReLU, ReLU, Sequential, Sigmoid) # yapf: disable """ ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) # isort:skip # noqa """ # yapf: enable def l2_norm(input, axis=1): """l2 normalization. Args: input (torch.Tensor): The input tensor. axis (int, optional): Specifies which axis of input to calculate the norm across. Defaults to 1. Returns: Tensor: Tensor after L2 normalization per-instance. """ norm = torch.norm(input, 2, axis, True) output = torch.div(input, norm) return output def get_block(in_channel, depth, num_units, stride=2): """Get a single block config. Args: in_channel (int): Input channels. depth (int): Output channels. num_units (int): Number of unit modules. stride (int, optional): Conv2d stride. Defaults to 2. Returns: list: A list of unit modules' config. """ return [Bottleneck(in_channel, depth, stride) ] + [Bottleneck(depth, depth, 1) for i in range(num_units - 1)] def get_blocks(num_layers): """Get block configs of backbone. Args: num_layers (int): Number of ConvBlock layers in backbone. Raises: ValueError: `num_layers` must be one of [50, 100, 152]. Returns: list: A list of block configs. """ if num_layers == 50: blocks = [ get_block(in_channel=64, depth=64, num_units=3), get_block(in_channel=64, depth=128, num_units=4), get_block(in_channel=128, depth=256, num_units=14), get_block(in_channel=256, depth=512, num_units=3) ] elif num_layers == 100: blocks = [ get_block(in_channel=64, depth=64, num_units=3), get_block(in_channel=64, depth=128, num_units=13), get_block(in_channel=128, depth=256, num_units=30), get_block(in_channel=256, depth=512, num_units=3) ] elif num_layers == 152: blocks = [ get_block(in_channel=64, depth=64, num_units=3), get_block(in_channel=64, depth=128, num_units=8), get_block(in_channel=128, depth=256, num_units=36), get_block(in_channel=256, depth=512, num_units=3) ] else: raise ValueError( 'Invalid number of layers: {}. Must be one of [50, 100, 152]'. format(num_layers)) return blocks
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 11748, 28034, 198, 6738, 28034, 13, 20471, 1330, 357, 48003, 425, 48997, 27201, 17, 67, 11, 347, 963, 35393, 17, 67, 11, 34872, 17, 67, 11, 5436, 27201, 17, 67, 11, 198, 220, 220, 220, ...
2.207483
1,176
import os from spotifyclient import SpotifyClient if __name__ == "__main__": main()
[ 11748, 28686, 198, 198, 6738, 4136, 1958, 16366, 1330, 26778, 11792, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419 ]
3.033333
30
# -*- coding: utf-8 -*- from ddtrace.compat import PY2 from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY from ddtrace.contrib.flask.patch import flask_version from ddtrace.ext import http from ddtrace.propagation.http import HTTP_HEADER_TRACE_ID, HTTP_HEADER_PARENT_ID from flask import abort from . import BaseFlaskTestCase from ...utils import assert_span_http_status_code base_exception_name = 'builtins.Exception' if PY2: base_exception_name = 'exceptions.Exception'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 49427, 40546, 13, 5589, 265, 1330, 350, 56, 17, 198, 6738, 49427, 40546, 13, 9979, 1187, 1330, 3537, 1847, 56, 51, 19505, 62, 49302, 16437, 62, 49, 6158, 62, 203...
2.904192
167
import argparse from trec_car import read_data from tqdm import tqdm import pickle import os import json import copy from utils.util import NUM_FOLD def parse_sim_file(filename): """ Reads the deduplicated documents file and stores the duplicate passage ids into a dictionary """ sim_dict = {} lines = open(filename).readlines() for line in lines: data = line.strip().split(':') if len(data[1]) > 0: sim_docs = data[-1].split(',') for docs in sim_docs: sim_dict[docs] = 1 return sim_dict if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--car_cbor", type=str) parser.add_argument("--msmarco_collection", type=str) parser.add_argument("--duplicate_file", type=str) parser.add_argument("--cast_dir", type=str) parser.add_argument("--out_data_dir", type=str) parser.add_argument("--out_collection_dir", type=str) args = parser.parse_args() # INPUT sim_file = args.duplicate_file cast_topics_raw_file = os.path.join(args.cast_dir, "evaluation_topics_v1.0.json") cast_topics_manual_file = os.path.join( args.cast_dir, "evaluation_topics_annotated_resolved_v1.0.tsv") cast_qrels_file = os.path.join(args.cast_dir, "2019qrels.txt") # OUTPUT out_topics_file = os.path.join(args.out_data_dir, "eval_topics.jsonl") out_raw_queries_file = os.path.join(args.out_data_dir, "queries.raw.tsv") out_manual_queries_file = os.path.join(args.out_data_dir, "queries.manual.tsv") out_qrels_file = os.path.join(args.out_data_dir, "qrels.tsv") car_id_to_idx_file = os.path.join(args.out_collection_dir, "car_id_to_idx.pickle") car_idx_to_id_file = os.path.join(args.out_collection_dir, "car_idx_to_id.pickle") out_collection_file = os.path.join(args.out_collection_dir, "collection.tsv") # 1. Combine TREC-CAR & MS MARCO, remove duplicate passages, assign new ids car_id_to_idx = {} car_idx_to_id = [] if os.path.exists(out_collection_file) and os.path.exists( car_id_to_idx_file) and os.path.exists(car_idx_to_id_file): print("Preprocessed collection found. Loading car_id_to_idx...") with open(car_id_to_idx_file, "rb") as f: car_id_to_idx = pickle.load(f) else: sim_dict = parse_sim_file(sim_file) car_base_id = 10000000 i = 0 with open(out_collection_file, "w", encoding="utf-8") as f: #FIX change 'a' to 'w' in normal run print("Processing TREC-CAR...") for para in tqdm( read_data.iter_paragraphs(open(args.car_cbor, 'rb'))): car_id = "CAR_" + para.para_id text = para.get_text() text = text.replace("\t", " ").replace("\n", " ").replace("\r", " ") idx = car_base_id + i car_id_to_idx[ car_id] = idx # e.g. CAR_76a4a716d4b1b01995c6663ee16e94b4ca35fdd3 -> 10000044 car_idx_to_id.append(car_id) f.write("{}\t{}\n".format(idx, text)) i += 1 print("Processing MS MARCO...") removed = 0 with open(args.msmarco_collection, "r") as m: for line in tqdm(m): marco_id, text = line.strip().split("\t") if ("MARCO_" + marco_id) in sim_dict: removed += 1 continue f.write("{}\t{}\n".format(marco_id, text)) print("Removed " + str(removed) + " passages") print("Dumping id mappings to {} and {}...".format(car_id_to_idx_file, car_idx_to_id_file)) with open(car_id_to_idx_file, "wb") as f: pickle.dump(car_id_to_idx, f) with open(car_idx_to_id_file, "wb") as f: pickle.dump(car_idx_to_id, f) # 2. Process queries print("Processing CAsT utterances...") with open(cast_topics_raw_file, "r") as fin: raw_data = json.load(fin) with open(cast_topics_manual_file, "r") as fin: annonated_lines = fin.readlines() out_raw_queries = open(out_raw_queries_file, "w") out_manual_queries = open(out_manual_queries_file, "w") all_annonated = {} for line in annonated_lines: splitted = line.split('\t') out_manual_queries.write(line) topic_query = splitted[0] query = splitted[1].strip() topic_id = topic_query.split('_')[0] query_id = topic_query.split('_')[1] if topic_id not in all_annonated: all_annonated[topic_id] = {} all_annonated[topic_id][query_id] = query out_manual_queries.close() topic_number_dict = {} data = [] for group in raw_data: topic_number, description, turn, title = str( group['number']), group.get('description', ''), group['turn'], group.get( 'title', '') queries = [] for query in turn: query_number, raw_utterance = str( query['number']), query['raw_utterance'] queries.append(raw_utterance) record = {} record['topic_number'] = topic_number record['query_number'] = query_number record['description'] = description record['title'] = title record['input'] = copy.deepcopy(queries) record['target'] = all_annonated[topic_number][query_number] out_raw_queries.write("{}_{}\t{}\n".format(topic_number, query_number, raw_utterance)) if not topic_number in topic_number_dict: topic_number_dict[topic_number] = len(topic_number_dict) data.append(record) out_raw_queries.close() with open(out_topics_file, 'w') as fout: for item in data: json_str = json.dumps(item) fout.write(json_str + '\n') # Split eval data into K-fold topic_per_fold = len(topic_number_dict) // NUM_FOLD for i in range(NUM_FOLD): with open(out_topics_file + "." + str(i), 'w') as fout: for item in data: idx = topic_number_dict[item['topic_number']] if idx // topic_per_fold == i: json_str = json.dumps(item) fout.write(json_str + '\n') # 3. Process and convert qrels print("Processing qrels...") with open(cast_qrels_file, "r") as oq, open(out_qrels_file, "w") as nq: for line in oq: qid, _, pid, rel = line.strip().split() if pid.startswith("CAR_"): assert car_id_to_idx[pid] != -1 pid = car_id_to_idx[pid] elif pid.startswith("MARCO_"): pid = int(pid[6:]) else: continue nq.write(qid + "\t0\t" + str(pid) + "\t" + rel + "\n") print("End")
[ 11748, 1822, 29572, 198, 6738, 2054, 66, 62, 7718, 1330, 1100, 62, 7890, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 2298, 293, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 4866, 198, 6738, 3384, 4487, 13, 22602, ...
1.900779
3,850
__doc__ = 'github: https://github.com/brandonxiang/geojson-python-utils' import math from coordTransform_utils import wgs84togcj02 from coordTransform_utils import gcj02tobd09 def linestrings_intersect(line1, line2): """ To valid whether linestrings from geojson are intersected with each other. reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js Keyword arguments: line1 -- first line geojson object line2 -- second line geojson object if(line1 intersects with other) return intersect point array else empty array """ intersects = [] for i in range(0, len(line1['coordinates']) - 1): for j in range(0, len(line2['coordinates']) - 1): a1_x = line1['coordinates'][i][1] a1_y = line1['coordinates'][i][0] a2_x = line1['coordinates'][i + 1][1] a2_y = line1['coordinates'][i + 1][0] b1_x = line2['coordinates'][j][1] b1_y = line2['coordinates'][j][0] b2_x = line2['coordinates'][j + 1][1] b2_y = line2['coordinates'][j + 1][0] ua_t = (b2_x - b1_x) * (a1_y - b1_y) - \ (b2_y - b1_y) * (a1_x - b1_x) ub_t = (a2_x - a1_x) * (a1_y - b1_y) - \ (a2_y - a1_y) * (a1_x - b1_x) u_b = (b2_y - b1_y) * (a2_x - a1_x) - (b2_x - b1_x) * (a2_y - a1_y) if not u_b == 0: u_a = ua_t / u_b u_b = ub_t / u_b if 0 <= u_a and u_a <= 1 and 0 <= u_b and u_b <= 1: intersects.append({'type': 'Point', 'coordinates': [ a1_x + u_a * (a2_x - a1_x), a1_y + u_a * (a2_y - a1_y)]}) # if len(intersects) == 0: # intersects = False return intersects def _bbox_around_polycoords(coords): """ bounding box """ x_all = [] y_all = [] for first in coords[0]: x_all.append(first[1]) y_all.append(first[0]) return [min(x_all), min(y_all), max(x_all), max(y_all)] def _point_in_bbox(point, bounds): """ valid whether the point is inside the bounding box """ return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2] or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3]) def _pnpoly(x, y, coords): """ the algorithm to judge whether the point is located in polygon reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation """ vert = [[0, 0]] for coord in coords: for node in coord: vert.append(node) vert.append(coord[0]) vert.append([0, 0]) inside = False i = 0 j = len(vert) - 1 while i < len(vert): if ((vert[i][0] > y) != (vert[j][0] > y)) and (x < (vert[j][1] - vert[i][1]) * (y - vert[i][0]) / (vert[j][0] - vert[i][0]) + vert[i][1]): inside = not inside j = i i += 1 return inside def point_in_polygon(point, poly): """ valid whether the point is located in a polygon Keyword arguments: point -- point geojson object poly -- polygon geojson object if(point inside poly) return true else false """ coords = [poly['coordinates']] if poly[ 'type'] == 'Polygon' else poly['coordinates'] return _point_in_polygon(point, coords) def point_in_multipolygon(point, multipoly): """ valid whether the point is located in a mulitpolygon (donut polygon is not supported) Keyword arguments: point -- point geojson object multipoly -- multipolygon geojson object if(point inside multipoly) return true else false """ coords_array = [multipoly['coordinates']] if multipoly[ 'type'] == "MultiPolygon" else multipoly['coordinates'] for coords in coords_array: if _point_in_polygon(point, coords): return True return False def number2radius(number): """ convert degree into radius Keyword arguments: number -- degree return radius """ return number * math.pi / 180 def number2degree(number): """ convert radius into degree Keyword arguments: number -- radius return degree """ return number * 180 / math.pi def draw_circle(radius_in_meters, center_point, steps=15): """ get a circle shape polygon based on centerPoint and radius Keyword arguments: point1 -- point one geojson object point2 -- point two geojson object if(point inside multipoly) return true else false """ steps = steps if steps > 15 else 15 center = [center_point['coordinates'][1], center_point['coordinates'][0]] dist = (radius_in_meters / 1000) / 6371 # convert meters to radiant rad_center = [number2radius(center[0]), number2radius(center[1])] # 15 sided circle poly = [] for step in range(0, steps): brng = 2 * math.pi * step / steps lat = math.asin(math.sin(rad_center[0]) * math.cos(dist) + math.cos(rad_center[0]) * math.sin(dist) * math.cos(brng)) lng = rad_center[1] + math.atan2(math.sin(brng) * math.sin(dist) * math.cos(rad_center[0]), math.cos(dist) - math.sin(rad_center[0]) * math.sin(lat)) poly.append([number2degree(lng), number2degree(lat)]) return {"type": "Polygon", "coordinates": [poly]} def rectangle_centroid(rectangle): """ get the centroid of the rectangle Keyword arguments: rectangle -- polygon geojson object return centroid """ bbox = rectangle['coordinates'][0] xmin = bbox[0][0] ymin = bbox[0][1] xmax = bbox[2][0] ymax = bbox[2][1] xwidth = xmax - xmin ywidth = ymax - ymin return {'type': 'Point', 'coordinates': [xmin + xwidth / 2, ymin + ywidth / 2]} def point_distance(point1, point2): """ calculate the distance between two point on the sphere like google map reference http://www.movable-type.co.uk/scripts/latlong.html Keyword arguments: point1 -- point one geojson object point2 -- point two geojson object if(point inside multipoly) return true else false """ lon1 = point1['coordinates'][0] lat1 = point1['coordinates'][1] lon2 = point2['coordinates'][0] lat2 = point2['coordinates'][1] deg_lat = number2radius(lat2 - lat1) deg_lon = number2radius(lon2 - lon1) a = math.pow(math.sin(deg_lat / 2), 2) + math.cos(number2radius(lat1)) * \ math.cos(number2radius(lat2)) * math.pow(math.sin(deg_lon / 2), 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return (6371 * c) * 1000 def geometry_within_radius(geometry, center, radius): """ To valid whether point or linestring or polygon is inside a radius around a center Keyword arguments: geometry -- point/linstring/polygon geojson object center -- point geojson object radius -- radius if(geometry inside radius) return true else false """ if geometry['type'] == 'Point': return point_distance(geometry, center) <= radius elif geometry['type'] == 'LineString' or geometry['type'] == 'Polygon': point = {} # it's enough to check the exterior ring of the Polygon coordinates = geometry['coordinates'][0] if geometry['type'] == 'Polygon' else geometry['coordinates'] for coordinate in coordinates: point['coordinates'] = coordinate if point_distance(point, center) > radius: return False return True def area(poly): """ calculate the area of polygon Keyword arguments: poly -- polygon geojson object return polygon area """ poly_area = 0 # TODO: polygon holes at coordinates[1] points = poly['coordinates'][0] j = len(points) - 1 count = len(points) for i in range(0, count): p1_x = points[i][1] p1_y = points[i][0] p2_x = points[j][1] p2_y = points[j][0] poly_area += p1_x * p2_y poly_area -= p1_y * p2_x j = i poly_area /= 2 return poly_area def centroid(poly): """ get the centroid of polygon adapted from http://paulbourke.net/geometry/polyarea/javascript.txt Keyword arguments: poly -- polygon geojson object return polygon centroid """ f_total = 0 x_total = 0 y_total = 0 # TODO: polygon holes at coordinates[1] points = poly['coordinates'][0] j = len(points) - 1 count = len(points) for i in range(0, count): p1_x = points[i][1] p1_y = points[i][0] p2_x = points[j][1] p2_y = points[j][0] f_total = p1_x * p2_y - p2_x * p1_y x_total += (p1_x + p2_x) * f_total y_total += (p1_y + p2_y) * f_total j = i six_area = area(poly) * 6 return {'type': 'Point', 'coordinates': [y_total / six_area, x_total / six_area]} def destination_point(point, brng, dist): """ Calculate a destination Point base on a base point and a distance Keyword arguments: pt -- polygon geojson object brng -- an angle in degrees dist -- distance in Kilometer between destination and base point return destination point object """ dist = float(dist) / 6371 # convert dist to angular distance in radians brng = number2radius(brng) lon1 = number2radius(point['coordinates'][0]) lat1 = number2radius(point['coordinates'][1]) lat2 = math.asin(math.sin(lat1) * math.cos(dist) + math.cos(lat1) * math.sin(dist) * math.cos(brng)) lon2 = lon1 + math.atan2(math.sin(brng) * math.sin(dist) * math.cos(lat1), math.cos(dist) - math.sin(lat1) * math.sin(lat2)) lon2 = (lon2 + 3 * math.pi) % (2 * math.pi) - math.pi # normalise to -180 degree +180 degree return {'type': 'Point', 'coordinates': [number2degree(lon2), number2degree(lat2)]} def simplify(source, kink=20): """ source[] array of geojson points kink in metres, kinks above this depth kept kink depth is the height of the triangle abc where a-b and b-c are two consecutive line segments """ source_coord = map(lambda o: {"lng": o.coordinates[0], "lat": o.coordinates[1]}, source) # count, n_stack, n_dest, start, end, i, sig; # dev_sqr, max_dev_sqr, band_sqr; # x12, y12, d12, x13, y13, d13, x23, y23, d23; F = (math.pi / 180.0) * 0.5 index = [] # aray of indexes of source points to include in the reduced line sig_start = [] # indices of start & end of working section sig_end = [] # check for simple cases count = len(source_coord) if count < 3: return source_coord # one or two points # more complex case. initialize stack band_sqr = kink * 360.0 / (2.0 * math.pi * 6378137.0) # Now in degrees band_sqr *= band_sqr n_dest = 0 sig_start[0] = 0 sig_end[0] = count - 1 n_stack = 1 # while the stack is not empty while n_stack > 0: # ... pop the top-most entries off the stacks start = sig_start[n_stack - 1] end = sig_end[n_stack - 1] n_stack -= 1 if (end - start) > 1: #any intermediate points ? # ... yes, so find most deviant intermediate point to either side of line joining start & end points x12 = source[end]["lng"] - source[start]["lng"] y12 = source[end]["lat"] - source[start]["lat"] if math.fabs(x12) > 180.0: x12 = 360.0 - math.fabs(x12) x12 *= math.cos(F * (source[end]["lat"] + source[start]["lat"])) # use avg lat to reduce lng d12 = (x12 * x12) + (y12 * y12) i = start + 1 sig = start max_dev_sqr = -1.0 while i < end: x13 = source[i]["lng"] - source[start]["lng"] y13 = source[i]["lat"] - source[start]["lat"] if math.fabs(x13) > 180.0: x13 = 360.0 - math.fabs(x13) x13 *= math.cos(F * (source[i]["lat"] + source[start]["lat"])) d13 = (x13 * x13) + (y13 * y13) x23 = source[i]["lng"] - source[end]["lng"] y23 = source[i]["lat"] - source[end]["lat"] if math.fabs(x23) > 180.0: x23 = 360.0 - math.fabs(x23) x23 *= math.cos(F * (source[i]["lat"] + source[end]["lat"])) d23 = (x23 * x23) + (y23 * y23) if d13 >= (d12 + d23): dev_sqr = d23 elif d23 >= (d12 + d13): dev_sqr = d13 else: dev_sqr = (x13 * y12 - y13 * x12) * (x13 * y12 - y13 * x12) / d12 # solve triangle if dev_sqr > max_dev_sqr: sig = i max_dev_sqr = dev_sqr i += 1 if max_dev_sqr < band_sqr: # is there a sig. intermediate point ? #... no, so transfer current start point index[n_dest] = start n_dest += 1 else: # ... yes, so push two sub-sections on stack for further processing n_stack += 1 sig_start[n_stack - 1] = sig sig_end[n_stack - 1] = end n_stack += 1 sig_start[n_stack - 1] = start sig_end[n_stack - 1] = sig else: # ... no intermediate points, so transfer current start point index[n_dest] = start n_dest += 1 # transfer last point index[n_dest] = count - 1 n_dest += 1 # make return array r = [] for i in range(0, n_dest): r.append(source_coord[index[i]]) return map(lambda o: {"type": "Point","coordinates": [o.lng, o.lat]}, r) def wgs2gcj(geometry): """ convert wgs84 to gcj referencing by https://github.com/wandergis/coordTransform_py """ # TODO: point linestring point if geometry['type'] == 'MultiLineString': coordinates = geometry['coordinates'] for lines in coordinates: for line in lines: line[0], line[1] = wgs84togcj02(line[0], line[1]) return geometry def gcj2bd(geometry): """ convert gcj to bd referencing by https://github.com/wandergis/coordTransform_py """ # TODO: point linestring point if geometry['type'] == 'MultiLineString': coordinates = geometry['coordinates'] for lines in coordinates: for line in lines: line[0], line[1] = gcj02tobd09(line[0], line[1]) return geometry
[ 834, 15390, 834, 796, 705, 12567, 25, 3740, 1378, 12567, 13, 785, 14, 1671, 5063, 87, 15483, 14, 469, 13210, 1559, 12, 29412, 12, 26791, 6, 198, 11748, 10688, 198, 6738, 6349, 41762, 62, 26791, 1330, 266, 14542, 5705, 83, 519, 66, 7...
2.163481
6,802
import os ''' user = os.environ['POSTGRES_USER'] password = os.environ['POSTGRES_PASSWORD'] host = os.environ['POSTGRES_HOST'] database = os.environ['POSTGRES_DB'] port = os.environ['POSTGRES_PORT'] ''' user = 'test' password = 'password' host = 'localhost' database = 'example' port = '5432' DATABASE_CONNECTION_URI = f'postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}'
[ 11748, 28686, 198, 7061, 6, 198, 7220, 796, 28686, 13, 268, 2268, 17816, 32782, 10761, 1546, 62, 29904, 20520, 198, 28712, 796, 28686, 13, 268, 2268, 17816, 32782, 10761, 1546, 62, 47924, 54, 12532, 20520, 198, 4774, 796, 28686, 13, 268...
2.503226
155
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 3 19:26:47 2019 @author: sercangul """ n = 5 xy = [map(int, input().split()) for _ in range(n)] sx, sy, sx2, sxy = map(sum, zip(*[(x, y, x**2, x * y) for x, y in xy])) b = (n * sxy - sx * sy) / (n * sx2 - sx**2) a = (sy / n) - b * (sx / n) print('{:.3f}'.format(a + b * 80))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 7653, 220, 513, 678, 25, 2075, 25, 2857, 13130, 198, 198, 31, 9800, 25, 1055, 66, ...
1.960452
177
import gym.envs.mujoco.hopper as hopper import numpy as np
[ 11748, 11550, 13, 268, 14259, 13, 76, 23577, 25634, 13, 8873, 2848, 355, 8169, 2848, 198, 11748, 299, 32152, 355, 45941, 628 ]
2.727273
22
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import numpy as np # import tensorflow as tf import abc # class FFMTextIterator(BaseIterator): # """Data loader for FFM format based models, such as xDeepFM. # Iterator will not load the whole data into memory. Instead, it loads data into memory # per mini-batch, so that large files can be used as input data. # """ # def __init__(self, hparams, graph, col_spliter=" ", ID_spliter="%"): # """Initialize an iterator. Create necessary placeholders for the model. # Args: # hparams (obj): Global hyper-parameters. Some key settings such as #_feature and #_field are there. # graph (obj): the running graph. All created placeholder will be added to this graph. # col_spliter (str): column splitter in one line. # ID_spliter (str): ID splitter in one line. # """ # self.feature_cnt = hparams.FEATURE_COUNT # self.field_cnt = hparams.FIELD_COUNT # self.col_spliter = col_spliter # self.ID_spliter = ID_spliter # self.batch_size = hparams.batch_size # self.graph = graph # with self.graph.as_default(): # self.labels = tf.placeholder(tf.float32, [None, 1], name="label") # self.fm_feat_indices = tf.placeholder( # tf.int64, [None, 2], name="fm_feat_indices" # ) # self.fm_feat_values = tf.placeholder( # tf.float32, [None], name="fm_feat_values" # ) # self.fm_feat_shape = tf.placeholder(tf.int64, [None], name="fm_feat_shape") # self.dnn_feat_indices = tf.placeholder( # tf.int64, [None, 2], name="dnn_feat_indices" # ) # self.dnn_feat_values = tf.placeholder( # tf.int64, [None], name="dnn_feat_values" # ) # self.dnn_feat_weights = tf.placeholder( # tf.float32, [None], name="dnn_feat_weights" # ) # self.dnn_feat_shape = tf.placeholder( # tf.int64, [None], name="dnn_feat_shape" # ) # def parser_one_line(self, line): # """Parse one string line into feature values. # Args: # line (str): a string indicating one instance # Returns: # list: Parsed results,including label, features and impression_id # """ # impression_id = 0 # words = line.strip().split(self.ID_spliter) # if len(words) == 2: # impression_id = words[1].strip() # cols = words[0].strip().split(self.col_spliter) # label = float(cols[0]) # features = [] # for word in cols[1:]: # if not word.strip(): # continue # tokens = word.split(":") # features.append([int(tokens[0]) - 1, int(tokens[1]) - 1, float(tokens[2])]) # return label, features, impression_id # def load_data_from_file(self, infile): # """Read and parse data from a file. # Args: # infile (str): text input file. Each line in this file is an instance. # Returns: # obj: An iterator that will yields parsed results, in the format of graph feed_dict. # """ # label_list = [] # features_list = [] # impression_id_list = [] # cnt = 0 # with tf.gfile.GFile(infile, "r") as rd: # for line in rd: # label, features, impression_id = self.parser_one_line(line) # features_list.append(features) # label_list.append(label) # impression_id_list.append(impression_id) # cnt += 1 # if cnt == self.batch_size: # res = self._convert_data(label_list, features_list) # yield self.gen_feed_dict(res), impression_id_list, self.batch_size # label_list = [] # features_list = [] # impression_id_list = [] # cnt = 0 # if cnt > 0: # res = self._convert_data(label_list, features_list) # yield self.gen_feed_dict(res), impression_id_list, cnt # def _convert_data(self, labels, features): # """Convert data into numpy arrays that are good for further operation. # Args: # labels (list): a list of ground-truth labels. # features (list): a 3-dimensional list, carrying a list (batch_size) of feature array, # where each feature array is a list of [field_idx, feature_idx, feature_value] tuple. # Returns: # dict: A dictionary, contains multiple numpy arrays that are convenient for further operation. # """ # dim = self.feature_cnt # FIELD_COUNT = self.field_cnt # instance_cnt = len(labels) # fm_feat_indices = [] # fm_feat_values = [] # fm_feat_shape = [instance_cnt, dim] # dnn_feat_indices = [] # dnn_feat_values = [] # dnn_feat_weights = [] # dnn_feat_shape = [instance_cnt * FIELD_COUNT, -1] # for i in range(instance_cnt): # m = len(features[i]) # dnn_feat_dic = {} # for j in range(m): # fm_feat_indices.append([i, features[i][j][1]]) # fm_feat_values.append(features[i][j][2]) # if features[i][j][0] not in dnn_feat_dic: # dnn_feat_dic[features[i][j][0]] = 0 # else: # dnn_feat_dic[features[i][j][0]] += 1 # dnn_feat_indices.append( # [ # i * FIELD_COUNT + features[i][j][0], # dnn_feat_dic[features[i][j][0]], # ] # ) # dnn_feat_values.append(features[i][j][1]) # dnn_feat_weights.append(features[i][j][2]) # if dnn_feat_shape[1] < dnn_feat_dic[features[i][j][0]]: # dnn_feat_shape[1] = dnn_feat_dic[features[i][j][0]] # dnn_feat_shape[1] += 1 # sorted_index = sorted( # range(len(dnn_feat_indices)), # key=lambda k: (dnn_feat_indices[k][0], dnn_feat_indices[k][1]), # ) # res = {} # res["fm_feat_indices"] = np.asarray(fm_feat_indices, dtype=np.int64) # res["fm_feat_values"] = np.asarray(fm_feat_values, dtype=np.float32) # res["fm_feat_shape"] = np.asarray(fm_feat_shape, dtype=np.int64) # res["labels"] = np.asarray([[label] for label in labels], dtype=np.float32) # res["dnn_feat_indices"] = np.asarray(dnn_feat_indices, dtype=np.int64)[ # sorted_index # ] # res["dnn_feat_values"] = np.asarray(dnn_feat_values, dtype=np.int64)[ # sorted_index # ] # res["dnn_feat_weights"] = np.asarray(dnn_feat_weights, dtype=np.float32)[ # sorted_index # ] # res["dnn_feat_shape"] = np.asarray(dnn_feat_shape, dtype=np.int64) # return res # def gen_feed_dict(self, data_dict): # """Construct a dictionary that maps graph elements to values. # Args: # data_dict (dict): a dictionary that maps string name to numpy arrays. # Returns: # dict: a dictionary that maps graph elements to numpy arrays. # """ # feed_dict = { # self.labels: data_dict["labels"], # self.fm_feat_indices: data_dict["fm_feat_indices"], # self.fm_feat_values: data_dict["fm_feat_values"], # self.fm_feat_shape: data_dict["fm_feat_shape"], # self.dnn_feat_indices: data_dict["dnn_feat_indices"], # self.dnn_feat_values: data_dict["dnn_feat_values"], # self.dnn_feat_weights: data_dict["dnn_feat_weights"], # self.dnn_feat_shape: data_dict["dnn_feat_shape"], # } # return feed_dict
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 198, 11748, 299, 32152, 355, 45941, 198, 2, 1330, 11192, 273, 11125, 355, 48700, 198, 11748, 450, 66, 628, 198, 198, 2, ...
1.915923
4,258
# -*- coding: utf-8 -*- import requests from ncm.encrypt import encrypted_request from ncm.constants import headers from ncm.constants import song_download_url from ncm.constants import get_song_url from ncm.constants import get_album_url from ncm.constants import get_artist_url from ncm.constants import get_playlist_url
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 7007, 198, 198, 6738, 299, 11215, 13, 12685, 6012, 1330, 19365, 62, 25927, 198, 6738, 299, 11215, 13, 9979, 1187, 1330, 24697, 198, 6738, 299, 11215, 13, 997...
3.074766
107
# -*- coding: utf-8 -*- """ The `TreeNode` class provides many helper functions that make the work done in the `BinarySearchTree` class methods much easier. The constructor for a `TreeNode`, along with these helper functions, is shown below. As you can see, many of these helper functions help to classify a node according to its own position as a child, (left or right) and the kind of children the node has. The `TreeNode` class will also explicitly keep track of the parent as an attribute of each node. You will see why this is important when we discuss the implementation for the `del` operator. One of the more interesting methods of `TreeNode` provides an interface to simply iterate over all the keys in the tree in order. You already know how to traverse a binary tree in order, using the `inorder` traversal algorithm. However, because we want our iterator to operate lazily, in this case we use the `yield` keyword to define our `__iter__` method as a Python generator. Pay close attention to the `__iter__` implementation as at first glance you might think that the code is not recursive: in fact, because `__iter__` overrides the `for x in` operation for iteration, it really is recursive! Our full implementation of `TreeNode` is provided below. It includes three further methods `find_successor`, `find_min` and `splice_out` which you can ignore for now as we will return to them later when discussing deletion. """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 37811, 198, 198, 464, 4600, 27660, 19667, 63, 1398, 3769, 867, 31904, 5499, 326, 787, 262, 670, 198, 28060, 287, 262, 4600, 33, 3219, 18243, 27660, 63, 1398, 5050, ...
3.920981
367
# Copyright (C) 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Python Fire is a library for creating CLIs from absolutely any Python object. You can call Fire on any Python object: functions, classes, modules, objects, dictionaries, lists, tuples, etc. They all work! Python Fire turns any Python object into a command line interface. Simply call the Fire function as your main method to create a CLI. When using Fire to build a CLI, your main method includes a call to Fire. Eg: def main(argv): fire.Fire(Component) A Fire CLI command is run by consuming the arguments in the command in order to access a member of current component, call the current component (if it's a function), or instantiate the current component (if it's a class). The target component begins as Component, and at each operation the component becomes the result of the preceding operation. For example "command fn arg1 arg2" might access the "fn" property of the initial target component, and then call that function with arguments 'arg1' and 'arg2'. Additional examples are available in the examples directory. Fire Flags, common to all Fire CLIs, must go after a separating "--". For example, to get help for a command you might run: `command -- --help`. The available flags for all Fire CLIs are: -v --verbose: Include private members in help and usage information. -h --help: Provide help and usage information for the command. -i --interactive: Drop into a Python REPL after running the command. --completion: Write the Bash completion script for the tool to stdout. --separator SEPARATOR: Use SEPARATOR in place of the default separator, '-'. --trace: Get the Fire Trace for the command. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import json import os import pipes import shlex import sys import types from fire import completion from fire import decorators from fire import helputils from fire import inspectutils from fire import interact from fire import parser from fire import trace import six def Fire(component=None, command=None, name=None): """This function, Fire, is the main entrypoint for Python Fire. Executes a command either from the `command` argument or from sys.argv by recursively traversing the target object `component`'s members consuming arguments, evaluating functions, and instantiating classes as it goes. When building a CLI with Fire, your main method should call this function. Args: component: The initial target component. command: Optional. If supplied, this is the command executed. If not supplied, then the command is taken from sys.argv instead. This can be a string or a list of strings; a list of strings is preferred. name: Optional. The name of the command as entered at the command line. Used in interactive mode and for generating the completion script. Returns: The result of executing the Fire command. Execution begins with the initial target component. The component is updated by using the command arguments to either access a member of the current component, call the current component (if it's a function), or instantiate the current component (if it's a class). When all arguments are consumed and there's no function left to call or class left to instantiate, the resulting current component is the final result. Raises: ValueError: If the command argument is supplied, but not a string or a sequence of arguments. FireExit: When Fire encounters a FireError, Fire will raise a FireExit with code 2. When used with the help or trace flags, Fire will raise a FireExit with code 0 if successful. """ name = name or os.path.basename(sys.argv[0]) # Get args as a list. if isinstance(command, six.string_types): args = shlex.split(command) elif isinstance(command, (list, tuple)): args = command elif command is None: # Use the command line args by default if no command is specified. args = sys.argv[1:] else: raise ValueError('The command argument must be a string or a sequence of ' 'arguments.') # Determine the calling context. caller = inspect.stack()[1] caller_frame = caller[0] caller_globals = caller_frame.f_globals caller_locals = caller_frame.f_locals context = {} context.update(caller_globals) context.update(caller_locals) component_trace = _Fire(component, args, context, name) if component_trace.HasError(): for help_flag in ['-h', '--help']: if help_flag in component_trace.elements[-1].args: command = '{cmd} -- --help'.format(cmd=component_trace.GetCommand()) print(('WARNING: The proper way to show help is {cmd}.\n' 'Showing help anyway.\n').format(cmd=pipes.quote(command)), file=sys.stderr) print('Fire trace:\n{trace}\n'.format(trace=component_trace), file=sys.stderr) result = component_trace.GetResult() print( helputils.HelpString(result, component_trace, component_trace.verbose), file=sys.stderr) raise FireExit(2, component_trace) elif component_trace.show_trace and component_trace.show_help: print('Fire trace:\n{trace}\n'.format(trace=component_trace), file=sys.stderr) result = component_trace.GetResult() print( helputils.HelpString(result, component_trace, component_trace.verbose), file=sys.stderr) raise FireExit(0, component_trace) elif component_trace.show_trace: print('Fire trace:\n{trace}'.format(trace=component_trace), file=sys.stderr) raise FireExit(0, component_trace) elif component_trace.show_help: result = component_trace.GetResult() print( helputils.HelpString(result, component_trace, component_trace.verbose), file=sys.stderr) raise FireExit(0, component_trace) else: _PrintResult(component_trace, verbose=component_trace.verbose) result = component_trace.GetResult() return result def CompletionScript(name, component): """Returns the text of the Bash completion script for a Fire CLI.""" return completion.Script(name, component) def _PrintResult(component_trace, verbose=False): """Prints the result of the Fire call to stdout in a human readable way.""" # TODO: Design human readable deserializable serialization method # and move serialization to it's own module. result = component_trace.GetResult() if isinstance(result, (list, set, types.GeneratorType)): for i in result: print(_OneLineResult(i)) elif inspect.isgeneratorfunction(result): raise NotImplementedError elif isinstance(result, dict): print(_DictAsString(result, verbose)) elif isinstance(result, tuple): print(_OneLineResult(result)) elif isinstance(result, (bool, six.string_types, six.integer_types, float, complex)): print(result) elif result is not None: print(helputils.HelpString(result, component_trace, verbose)) def _DictAsString(result, verbose=False): """Returns a dict as a string. Args: result: The dict to convert to a string verbose: Whether to include 'hidden' members, those keys starting with _. Returns: A string representing the dict """ result = {key: value for key, value in result.items() if _ComponentVisible(key, verbose)} if not result: return '{}' longest_key = max(len(str(key)) for key in result.keys()) format_string = '{{key:{padding}s}} {{value}}'.format(padding=longest_key + 1) lines = [] for key, value in result.items(): line = format_string.format(key=str(key) + ':', value=_OneLineResult(value)) lines.append(line) return '\n'.join(lines) def _ComponentVisible(component, verbose=False): """Returns whether a component should be visible in the output.""" return ( verbose or not isinstance(component, six.string_types) or not component.startswith('_')) def _OneLineResult(result): """Returns result serialized to a single line string.""" # TODO: Ensure line is fewer than eg 120 characters. if isinstance(result, six.string_types): return str(result).replace('\n', ' ') try: # Don't force conversion to ascii. return json.dumps(result, ensure_ascii=False) except (TypeError, ValueError): return str(result).replace('\n', ' ') def _Fire(component, args, context, name=None): """Execute a Fire command on a target component using the args supplied. Arguments that come after a final isolated '--' are treated as Flags, eg for interactive mode or completion script generation. Other arguments are consumed by the execution of the Fire command, eg in the traversal of the members of the component, or in calling a function or instantiating a class found during the traversal. The steps performed by this method are: 1. Parse any Flag args (the args after the final --) 2. Start with component as the current component. 2a. If the current component is a class, instantiate it using args from args. 2b. If the current component is a routine, call it using args from args. 2c. Otherwise access a member from component using an arg from args. 2d. Repeat 2a-2c until no args remain. 3a. Embed into ipython REPL if interactive mode is selected. 3b. Generate a completion script if that flag is provided. In step 2, arguments will only ever be consumed up to a separator; a single step will never consume arguments from both sides of a separator. The separator defaults to a hyphen (-), and can be overwritten with the --separator Fire argument. Args: component: The target component for Fire. args: A list of args to consume in Firing on the component, usually from the command line. context: A dict with the local and global variables available at the call to Fire. name: Optional. The name of the command. Used in interactive mode and in the tab completion script. Returns: FireTrace of components starting with component, tracing Fire's execution path as it consumes args. Raises: ValueError: If there are arguments that cannot be consumed. ValueError: If --completion is specified but no name available. """ args, flag_args = parser.SeparateFlagArgs(args) argparser = parser.CreateParser() parsed_flag_args, unused_args = argparser.parse_known_args(flag_args) verbose = parsed_flag_args.verbose interactive = parsed_flag_args.interactive separator = parsed_flag_args.separator show_completion = parsed_flag_args.completion show_help = parsed_flag_args.help show_trace = parsed_flag_args.trace # component can be a module, class, routine, object, etc. if component is None: component = context initial_component = component component_trace = trace.FireTrace( initial_component=initial_component, name=name, separator=separator, verbose=verbose, show_help=show_help, show_trace=show_trace) instance = None remaining_args = args while True: last_component = component initial_args = remaining_args if not remaining_args and (show_help or interactive or show_trace or show_completion): # Don't initialize the final class or call the final function unless # there's a separator after it, and instead process the current component. break saved_args = [] used_separator = False if separator in remaining_args: # For the current component, only use arguments up to the separator. separator_index = remaining_args.index(separator) saved_args = remaining_args[separator_index + 1:] remaining_args = remaining_args[:separator_index] used_separator = True assert separator not in remaining_args if inspect.isclass(component) or inspect.isroutine(component): # The component is a class or a routine; we'll try to initialize it or # call it. isclass = inspect.isclass(component) try: target = component.__name__ filename, lineno = inspectutils.GetFileAndLine(component) component, consumed_args, remaining_args, capacity = _CallCallable( component, remaining_args) # Update the trace. if isclass: component_trace.AddInstantiatedClass( component, target, consumed_args, filename, lineno, capacity) else: component_trace.AddCalledRoutine( component, target, consumed_args, filename, lineno, capacity) except FireError as error: component_trace.AddError(error, initial_args) return component_trace if last_component is initial_component: # If the initial component is a class, keep an instance for use with -i. instance = component elif isinstance(component, (list, tuple)) and remaining_args: # The component is a tuple or list; we'll try to access a member. arg = remaining_args[0] try: index = int(arg) component = component[index] except (ValueError, IndexError): error = FireError( 'Unable to index into component with argument:', arg) component_trace.AddError(error, initial_args) return component_trace remaining_args = remaining_args[1:] filename = None lineno = None component_trace.AddAccessedProperty( component, index, [arg], filename, lineno) elif isinstance(component, dict) and remaining_args: # The component is a dict; we'll try to access a member. target = remaining_args[0] if target in component: component = component[target] elif target.replace('-', '_') in component: component = component[target.replace('-', '_')] else: # The target isn't present in the dict as a string, but maybe it is as # another type. # TODO: Consider alternatives for accessing non-string keys. found_target = False for key, value in component.items(): if target == str(key): component = value found_target = True break if not found_target: error = FireError( 'Cannot find target in dict:', target, component) component_trace.AddError(error, initial_args) return component_trace remaining_args = remaining_args[1:] filename = None lineno = None component_trace.AddAccessedProperty( component, target, [target], filename, lineno) elif remaining_args: # We'll try to access a member of the component. try: target = remaining_args[0] component, consumed_args, remaining_args = _GetMember( component, remaining_args) filename, lineno = inspectutils.GetFileAndLine(component) component_trace.AddAccessedProperty( component, target, consumed_args, filename, lineno) except FireError as error: component_trace.AddError(error, initial_args) return component_trace if used_separator: # Add back in the arguments from after the separator. if remaining_args: remaining_args = remaining_args + [separator] + saved_args elif (inspect.isclass(last_component) or inspect.isroutine(last_component)): remaining_args = saved_args component_trace.AddSeparator() elif component is not last_component: remaining_args = [separator] + saved_args else: # It was an unnecessary separator. remaining_args = saved_args if component is last_component and remaining_args == initial_args: # We're making no progress. break if remaining_args: component_trace.AddError( FireError('Could not consume arguments:', remaining_args), initial_args) return component_trace if show_completion: if name is None: raise ValueError('Cannot make completion script without command name') script = CompletionScript(name, initial_component) component_trace.AddCompletionScript(script) if interactive: variables = context.copy() if name is not None: variables[name] = initial_component variables['component'] = initial_component variables['result'] = component variables['trace'] = component_trace if instance is not None: variables['self'] = instance interact.Embed(variables, verbose) component_trace.AddInteractiveMode() return component_trace def _GetMember(component, args): """Returns a subcomponent of component by consuming an arg from args. Given a starting component and args, this function gets a member from that component, consuming one arg in the process. Args: component: The component from which to get a member. args: Args from which to consume in the search for the next component. Returns: component: The component that was found by consuming an arg. consumed_args: The args that were consumed by getting this member. remaining_args: The remaining args that haven't been consumed yet. Raises: FireError: If we cannot consume an argument to get a member. """ members = dict(inspect.getmembers(component)) arg = args[0] arg_names = [ arg, arg.replace('-', '_'), # treat '-' as '_'. ] for arg_name in arg_names: if arg_name in members: return members[arg_name], [arg], args[1:] raise FireError('Could not consume arg:', arg) def _CallCallable(fn, args): """Calls the function fn by consuming args from args. Args: fn: The function to call or class to instantiate. args: Args from which to consume for calling the function. Returns: component: The object that is the result of the function call. consumed_args: The args that were consumed for the function call. remaining_args: The remaining args that haven't been consumed yet. capacity: Whether the call could have taken additional args. """ parse = _MakeParseFn(fn) (varargs, kwargs), consumed_args, remaining_args, capacity = parse(args) result = fn(*varargs, **kwargs) return result, consumed_args, remaining_args, capacity def _MakeParseFn(fn): """Creates a parse function for fn. Args: fn: The function or class to create the parse function for. Returns: A parse function for fn. The parse function accepts a list of arguments and returns (varargs, kwargs), remaining_args. The original function fn can then be called with fn(*varargs, **kwargs). The remaining_args are the leftover args from the arguments to the parse function. """ fn_spec = inspectutils.GetFullArgSpec(fn) all_args = fn_spec.args + fn_spec.kwonlyargs metadata = decorators.GetMetadata(fn) # Note: num_required_args is the number of positional arguments without # default values. All of these arguments are required. num_required_args = len(fn_spec.args) - len(fn_spec.defaults) required_kwonly = set(fn_spec.kwonlyargs) - set(fn_spec.kwonlydefaults) def _ParseFn(args): """Parses the list of `args` into (varargs, kwargs), remaining_args.""" kwargs, remaining_kwargs, remaining_args = _ParseKeywordArgs( args, all_args, fn_spec.varkw) # Note: _ParseArgs modifies kwargs. parsed_args, kwargs, remaining_args, capacity = _ParseArgs( fn_spec.args, fn_spec.defaults, num_required_args, kwargs, remaining_args, metadata) if fn_spec.varargs or fn_spec.varkw: # If we're allowed *varargs or **kwargs, there's always capacity. capacity = True extra_kw = set(kwargs) - set(fn_spec.kwonlyargs) if fn_spec.varkw is None and extra_kw: raise FireError('Unexpected kwargs present:', extra_kw) missing_kwonly = set(required_kwonly) - set(kwargs) if missing_kwonly: raise FireError('Missing required flags:', missing_kwonly) # If we accept *varargs, then use all remaining arguments for *varargs. if fn_spec.varargs is not None: varargs, remaining_args = remaining_args, [] else: varargs = [] for index, value in enumerate(varargs): varargs[index] = _ParseValue(value, None, None, metadata) varargs = parsed_args + varargs remaining_args += remaining_kwargs consumed_args = args[:len(args) - len(remaining_args)] return (varargs, kwargs), consumed_args, remaining_args, capacity return _ParseFn def _ParseArgs(fn_args, fn_defaults, num_required_args, kwargs, remaining_args, metadata): """Parses the positional and named arguments from the available supplied args. Modifies kwargs, removing args as they are used. Args: fn_args: A list of argument names that the target function accepts, including positional and named arguments, but not the varargs or kwargs names. fn_defaults: A list of the default values in the function argspec. num_required_args: The number of required arguments from the function's argspec. This is the number of arguments without a default value. kwargs: Dict with named command line arguments and their values. remaining_args: The remaining command line arguments, which may still be used as positional arguments. metadata: Metadata about the function, typically from Fire decorators. Returns: parsed_args: A list of values to be used as positional arguments for calling the target function. kwargs: The input dict kwargs modified with the used kwargs removed. remaining_args: A list of the supplied args that have not been used yet. capacity: Whether the call could have taken args in place of defaults. Raises: FireError: if additional positional arguments are expected, but none are available. """ accepts_positional_args = metadata.get(decorators.ACCEPTS_POSITIONAL_ARGS) capacity = False # If we see a default get used, we'll set capacity to True # Select unnamed args. parsed_args = [] for index, arg in enumerate(fn_args): value = kwargs.pop(arg, None) if value is not None: # A value is specified at the command line. value = _ParseValue(value, index, arg, metadata) parsed_args.append(value) else: # No value has been explicitly specified. if remaining_args and accepts_positional_args: # Use a positional arg. value = remaining_args.pop(0) value = _ParseValue(value, index, arg, metadata) parsed_args.append(value) elif index < num_required_args: raise FireError( 'The function received no value for the required argument:', arg) else: # We're past the args for which there's no default value. # There's a default value for this arg. capacity = True default_index = index - num_required_args # index into the defaults. parsed_args.append(fn_defaults[default_index]) for key, value in kwargs.items(): kwargs[key] = _ParseValue(value, None, key, metadata) return parsed_args, kwargs, remaining_args, capacity def _ParseKeywordArgs(args, fn_args, fn_keywords): """Parses the supplied arguments for keyword arguments. Given a list of arguments, finds occurences of --name value, and uses 'name' as the keyword and 'value' as the value. Constructs and returns a dictionary of these keyword arguments, and returns a list of the remaining arguments. Only if fn_keywords is None, this only finds argument names used by the function, specified through fn_args. This returns the values of the args as strings. They are later processed by _ParseArgs, which converts them to the appropriate type. Args: args: A list of arguments fn_args: A list of argument names that the target function accepts, including positional and named arguments, but not the varargs or kwargs names. fn_keywords: The argument name for **kwargs, or None if **kwargs not used Returns: kwargs: A dictionary mapping keywords to values. remaining_kwargs: A list of the unused kwargs from the original args. remaining_args: A list of the unused arguments from the original args. """ kwargs = {} remaining_kwargs = [] remaining_args = [] if not args: return kwargs, remaining_kwargs, remaining_args skip_argument = False for index, argument in enumerate(args): if skip_argument: skip_argument = False continue arg_consumed = False if argument.startswith('--'): # This is a named argument; get its value from this arg or the next. got_argument = False keyword = argument[2:] contains_equals = '=' in keyword is_bool_syntax = ( not contains_equals and (index + 1 == len(args) or args[index + 1].startswith('--'))) if contains_equals: keyword, value = keyword.split('=', 1) got_argument = True elif is_bool_syntax: # Since there's no next arg or the next arg is a Flag, we consider # this flag to be a boolean. got_argument = True if keyword in fn_args: value = 'True' elif keyword.startswith('no'): keyword = keyword[2:] value = 'False' else: value = 'True' else: if index + 1 < len(args): value = args[index + 1] got_argument = True keyword = keyword.replace('-', '_') # In order for us to consume the argument as a keyword arg, we either: # Need to be explicitly expecting the keyword, or we need to be # accepting **kwargs. if got_argument: skip_argument = not contains_equals and not is_bool_syntax arg_consumed = True if keyword in fn_args or fn_keywords: kwargs[keyword] = value else: remaining_kwargs.append(argument) if skip_argument: remaining_kwargs.append(args[index + 1]) if not arg_consumed: # The argument was not consumed, so it is still a remaining argument. remaining_args.append(argument) return kwargs, remaining_kwargs, remaining_args def _ParseValue(value, index, arg, metadata): """Parses value, a string, into the appropriate type. The function used to parse value is determined by the remaining arguments. Args: value: The string value to be parsed, typically a command line argument. index: The index of the value in the function's argspec. arg: The name of the argument the value is being parsed for. metadata: Metadata about the function, typically from Fire decorators. Returns: value, parsed into the appropriate type for calling a function. """ parse_fn = parser.DefaultParseValue # We check to see if any parse function from the fn metadata applies here. parse_fns = metadata.get(decorators.FIRE_PARSE_FNS) if parse_fns: default = parse_fns['default'] positional = parse_fns['positional'] named = parse_fns['named'] if index is not None and 0 <= index < len(positional): parse_fn = positional[index] elif arg in named: parse_fn = named[arg] elif default is not None: parse_fn = default return parse_fn(value)
[ 2, 15069, 357, 34, 8, 2177, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, ...
3.012148
9,220
import os, ast import pandas as pd from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from sklearn.compose import make_column_transformer from sklearn.pipeline import make_pipeline import pickle if __name__ == "__main__": main()
[ 11748, 28686, 11, 6468, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 82, 14761, 1330, 311, 15922, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 198, 6738, 1341, 35720, 13, 3866, 36...
3.076923
104
import base64 def parse_basic_auth(header_value): """ Attempts to parse the given header value as a Base64-encoded Basic auth header. """ if not header_value: return None parts = header_value.split(" ") if len(parts) != 2 or parts[0].lower() != "basic": return None try: basic_parts = base64.b64decode(parts[1]).split(":", 1) if len(basic_parts) != 2: return None return basic_parts except ValueError: return None
[ 11748, 2779, 2414, 628, 198, 4299, 21136, 62, 35487, 62, 18439, 7, 25677, 62, 8367, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 25770, 82, 284, 21136, 262, 1813, 13639, 1988, 355, 257, 7308, 2414, 12, 12685, 9043, 14392, 6284...
2.392523
214
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.core.signals.event import _signals sidemenu = _signals.signal('sidemenu', """ Expected to return ``MenuEntryData`` objects to be added to the event side menu. A single entry can be returned directly, multiple entries must be yielded. """) deleted = _signals.signal('deleted', """ Called when an event is deleted. The *sender* is the event object. The `user` kwarg contains the user performing the deletion if available. """) updated = _signals.signal('updated', """ Called when basic data of an event is updated. The *sender* is the event. A dict of changes is passed in the `changes` kwarg, with ``(old, new)`` tuples for each change. Note than the `person_links` change may happen with `old` and `new` being the same lists for technical reasons. If the key is present, it should be assumed that something changed (usually the order or some data on the person link). """) cloned = _signals.signal('cloned', """ Called when an event is cloned. The *sender* is the `Event` object of the old event, the new event is passed in the `new_event` kwarg. """) type_changed = _signals.signal('type-changed', """ Called when the type of an event is changed. The `sender` is the event, the old type is passed in the `old_type` kwarg. """) moved = _signals.signal('moved', """ Called when an event is moved to a different category. The `sender` is the event, the old category is in the `old_parent` kwarg. """) created = _signals.signal('created', """ Called when a new event is created. The `sender` is the new Event. """) session_updated = _signals.signal('session-updated', """ Called when a session is updated. The *sender* is the session. """) session_deleted = _signals.signal('session-deleted', """ Called when a session is deleted. The *sender* is the session. """) session_block_deleted = _signals.signal('session-block-deleted', """ Called when a session block is deleted. The *sender* is the session block. This signal is called before the ``db.session.delete()`` on the block is executed. """) timetable_buttons = _signals.signal('timetable-buttons', """ Expected to return a list of tuples ('button_name', 'js-call-class'). Called when building the timetable view. """) get_log_renderers = _signals.signal('get-log-renderers', """ Expected to return `EventLogRenderer` classes. """) get_feature_definitions = _signals.signal('get-feature-definitions', """ Expected to return `EventFeature` subclasses. """) metadata_postprocess = _signals.signal('metadata-postprocess', """ Called right after a dict-like representation of an event is created, so that plugins can add their own fields. The *sender* is a string parameter specifying the source of the metadata. The *event* kwarg contains the event object. The metadata is passed in the `data` kwarg. The signal should return a dict that will be used to update the original representation (fields to add or override). """)
[ 2, 770, 2393, 318, 636, 286, 1423, 3713, 13, 198, 2, 15069, 357, 34, 8, 6244, 532, 12131, 327, 28778, 198, 2, 198, 2, 1423, 3713, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 198, 2, 13096, 340, 739, 262, 2846,...
3.335118
934
# Copyright (c) 2013 - 2015 EMC Corporation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from six.moves import urllib from cinder import context from cinder import exception from cinder.tests.unit import fake_constants as fake from cinder.tests.unit import fake_volume from cinder.tests.unit.volume.drivers.emc import scaleio from cinder.tests.unit.volume.drivers.emc.scaleio import mocks
[ 2, 15069, 357, 66, 8, 2211, 532, 1853, 412, 9655, 10501, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 22...
3.395683
278
# -*- coding: utf-8 -*- __version__ = '1.0.2' import os import appdirs import osmnx as ox import joblib import requests from .files import load_vars, save_vars, cached, inflate_tar, download_zipfile from .data import data, list_data, problematic from .tools.view_code import show_file from . import mapping cache_dir = None memory = None def set_cache_dir(location=None, compress=True, verbose=0, **kwargs): """ Set up a cache directory for use with the tutorials. Parameter --------- cache_dir : Path-like or False, optional A path for the cache files. Set to False to disable caching. """ global memory, cache_dir if location is None: location = appdirs.user_cache_dir('transportation_tutorials') if location is False: location = None memory = joblib.Memory(location, compress=compress, verbose=verbose, **kwargs) make_cache = ( (ox, 'gdf_from_place'), (ox, 'graph_from_bbox'), (requests, 'get'), (requests, 'post'), ) for module, func_name in make_cache: try: func = getattr(module, f"_{func_name}_orig") except AttributeError: func = getattr(module, func_name) setattr(module, f"_{func_name}_orig", func) setattr(module, func_name, memory.cache(func)) set_cache_dir()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9641, 834, 796, 705, 16, 13, 15, 13, 17, 6, 198, 198, 11748, 28686, 198, 11748, 598, 15908, 82, 198, 11748, 267, 5796, 77, 87, 355, 12018, 198, 11748, 1693...
2.770787
445
from requests.models import PreparedRequest
[ 6738, 7007, 13, 27530, 1330, 19141, 1144, 18453, 628, 198 ]
4.6
10
import os import sys from . import HendrixTestCase, TEST_SETTINGS from hendrix.contrib import SettingsError from hendrix.options import options as hx_options from hendrix import ux from mock import patch
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 764, 1330, 14666, 8609, 14402, 20448, 11, 43001, 62, 28480, 51, 20754, 198, 6738, 339, 358, 8609, 13, 3642, 822, 1330, 16163, 12331, 198, 6738, 339, 358, 8609, 13, 25811, 1330, 3689, 355, 289,...
3.534483
58
""" The MIT License (MIT) Copyright (c) 2015-2021 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations from typing import Optional, TYPE_CHECKING, Dict, TypedDict, Union, List, Literal from .snowflake import Snowflake from .components import Component, SelectOption from .embed import Embed from .channel import ChannelType, Channel from .member import Member from .role import Role from .user import User if TYPE_CHECKING: from .message import AllowedMentions, Message ApplicationCommandType = Literal[1, 2, 3] ApplicationCommandOptionType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ApplicationCommandPermissionType = Literal[1, 2] InteractionType = Literal[1, 2, 3] ApplicationCommandInteractionDataOption = Union[ _ApplicationCommandInteractionDataOptionString, _ApplicationCommandInteractionDataOptionInteger, _ApplicationCommandInteractionDataOptionSubcommand, _ApplicationCommandInteractionDataOptionBoolean, _ApplicationCommandInteractionDataOptionSnowflake, _ApplicationCommandInteractionDataOptionNumber, ] InteractionResponseType = Literal[1, 4, 5, 6, 7]
[ 37811, 198, 464, 17168, 13789, 357, 36393, 8, 198, 198, 15269, 357, 66, 8, 1853, 12, 1238, 2481, 36962, 22877, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 198, 30073, 286, 428, 3788, ...
3.622896
594
# -*- coding: utf8 -*- import os import re import time import json import random import asyncio from typing import Optional, List, Dict from aiohttp import ClientSession from aiohttp.cookiejar import SimpleCookie from lxml import etree from bs4 import BeautifulSoup from config import * from message import server_chan_send def save_cookies(self, cookies: dict): """cookies""" with open(COOKIES_FILE_PATH, "r") as f: data = json.load(f) data[self.username] = cookies with open(COOKIES_FILE_PATH, 'w') as f2: json.dump(data, f2) def check_activeid(self, activeid): """activeid""" activeid += self.username if "activeid.json" not in os.listdir(ACTIVEID_PATH): with open(ACTIVEID_FILE_PATH, 'w+') as f: f.write("{}") with open(ACTIVEID_FILE_PATH, 'r') as f: try: # data = json.load(f) if data[activeid]: return True except BaseException: # activeid return False def save_activeid(self, activeid): """activeid""" activeid += self.username if "activeid.json" not in os.listdir(ACTIVEID_PATH): with open(ACTIVEID_FILE_PATH, 'w+') as f: f.write("{}") with open(ACTIVEID_FILE_PATH, 'r') as f: data = json.load(f) with open(ACTIVEID_FILE_PATH, 'w') as f2: data[activeid] = True json.dump(data, f2)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 640, 198, 11748, 33918, 198, 11748, 4738, 198, 11748, 30351, 952, 198, 6738, 19720, 1330, 32233, 11, 7343, 11, 360, 713, 198, 198, ...
1.97037
810
#!python import numpy as np from numpy import inf from numpy import nan from scipy.optimize import fmin from scipy.stats import beta from scipy.special import beta as B from scipy.special import comb import argparse import sys def parseArgs(): '''Function for parsing arguments''' parser = argparse.ArgumentParser(description="Pipeline for analyzing barcoded amplicon \ sequencing data with Unique molecular \ identifiers (UMI)") parser.add_argument('-cons', '--cons_file', dest='cons_file', help='Path to cons file, for fitting parameters of the bgmodel') parser.add_argument('-nonbgposfile', '--non-background-positions', dest='nonbgposfile', help='Path to file with non-background positions') parser.add_argument('-out', '--out_file',dest='out_file',help="name of output file, default = %(default)s]",default="bgmodel.params") parser.add_argument('-f','--fsize',dest='fsize', help='Family size cutoff (consensus cutoff) for variant calling. [default = %(default)s]', default=3) args = parser.parse_args(sys.argv[1:]) return(args) if __name__=='__main__': args=parseArgs() run_fit_bgmodel(args)
[ 2, 0, 29412, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 1330, 1167, 198, 6738, 299, 32152, 1330, 15709, 198, 6738, 629, 541, 88, 13, 40085, 1096, 1330, 277, 1084, 198, 6738, 629, 541, 88, 13, 34242, 1330, 12159, 198, ...
2.565923
493
# Copyright (c) 2016-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace from caffe2.python.test_util import TestCase, rand_array if __name__ == "__main__": import unittest unittest.main()
[ 2, 15069, 357, 66, 8, 1584, 12, 25579, 11, 3203, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 26...
3.843511
262
""" Cisco_IOS_XR_fib_common_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR fib\-common package configuration. This module contains definitions for the following management objects\: fib\: CEF configuration Copyright (c) 2013\-2018 by Cisco Systems, Inc. All rights reserved. """ from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YError, YModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error
[ 37811, 28289, 62, 40, 2640, 62, 55, 49, 62, 69, 571, 62, 11321, 62, 37581, 220, 198, 198, 1212, 8265, 4909, 257, 4947, 286, 575, 15567, 17336, 198, 1640, 28289, 314, 2640, 41441, 55, 49, 12900, 41441, 11321, 5301, 8398, 13, 198, 198...
3.388298
188
"""Series of actions that form a combo chain""" from __future__ import annotations from typing import Optional, Sequence, TYPE_CHECKING from action import Action from core.utility import Array from core.constants import PlayerForm, SimActKind, MomentType from core.database import FromDB if TYPE_CHECKING: from entity.player import Player
[ 37811, 27996, 286, 4028, 326, 1296, 257, 14831, 6333, 37811, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 6738, 19720, 1330, 32233, 11, 45835, 11, 41876, 62, 50084, 2751, 198, 198, 6738, 2223, 1330, 7561, 198, 6738, 4755, 13, 315, 87...
3.965909
88
import os from datetime import timedelta from flask_unchained import BundleConfig try: from flask_unchained.bundles.sqlalchemy import db except ImportError: db = None
[ 11748, 28686, 198, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 42903, 62, 3316, 1328, 1330, 25282, 16934, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 42903, 62, 3316, 1328, 13, 65, 917, 829, 13, 25410, 282, 26599, 1330, 20...
3.196429
56
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- __author__ = ["Markus Lning"] __all__ = ["_StatsModelsAdapter"] import numpy as np import pandas as pd from sktime.forecasting.base._base import DEFAULT_ALPHA from sktime.forecasting.base._sktime import _OptionalForecastingHorizonMixin from sktime.forecasting.base._sktime import _SktimeForecaster
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 532, 84, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 796, 14631, 9704, 385, 406, 768, 8973, 198, 834, 439, 834, 796, 14631, 62, 29668, ...
2.869919
123
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from gazebo_msgs/GetLinkPropertiesRequest.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct _struct_I = genpy.struct_I # This Python file uses the following encoding: utf-8 """autogenerated by genpy from gazebo_msgs/GetLinkPropertiesResponse.msg. Do not edit.""" import codecs import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geometry_msgs.msg _struct_I = genpy.struct_I _struct_7dB7dB = None
[ 2, 770, 11361, 2393, 3544, 262, 1708, 21004, 25, 3384, 69, 12, 23, 198, 37811, 2306, 519, 877, 515, 416, 2429, 9078, 422, 308, 1031, 1765, 78, 62, 907, 14542, 14, 3855, 11280, 2964, 18200, 18453, 13, 19662, 13, 2141, 407, 4370, 526,...
3.096447
197
"""Find kernel specifications for a given language""" import os import sys from .languages import same_language from .reraise import reraise try: # I prefer not to take a dependency on jupyter_client from jupyter_client.kernelspec import find_kernel_specs, get_kernel_spec except ImportError as err: find_kernel_specs = reraise(err) get_kernel_spec = reraise(err) def set_kernelspec_from_language(notebook): """Set the kernel specification based on the 'main_language' metadata""" language = notebook.metadata.get("jupytext", {}).get("main_language") if "kernelspec" not in notebook.metadata and language: try: kernelspec = kernelspec_from_language(language) except ValueError: return notebook.metadata["kernelspec"] = kernelspec notebook.metadata.get("jupytext", {}).pop("main_language") def kernelspec_from_language(language): """Return the python kernel that matches the current env, or the first kernel that matches the given language""" if language == "python": # Return the kernel that matches the current Python executable for name in find_kernel_specs(): kernel_specs = get_kernel_spec(name) cmd = kernel_specs.argv[0] if ( kernel_specs.language == "python" and os.path.isfile(cmd) and os.path.samefile(cmd, sys.executable) ): return { "name": name, "language": language, "display_name": kernel_specs.display_name, } raise ValueError( "No kernel found that matches the current python executable {}\n".format( sys.executable ) + "Install one with 'python -m ipykernel install --name kernel_name [--user]'" ) for name in find_kernel_specs(): kernel_specs = get_kernel_spec(name) if same_language(kernel_specs.language, language): return { "name": name, "language": language, "display_name": kernel_specs.display_name, } raise ValueError("No kernel found for the language {}".format(language))
[ 37811, 16742, 9720, 20640, 329, 257, 1813, 3303, 37811, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 764, 75, 33213, 1330, 976, 62, 16129, 198, 6738, 764, 24420, 786, 1330, 302, 40225, 198, 198, 28311, 25, 198, 220, 220, ...
2.360042
961
import numpy as np import scipy.sparse __all__ = ['save_npz', 'load_npz'] # Make loading safe vs. malicious input PICKLE_KWARGS = dict(allow_pickle=False) def save_npz(file, matrix, compressed=True): """ Save a sparse matrix to a file using ``.npz`` format. Parameters ---------- file : str or file-like object Either the file name (string) or an open file (file-like object) where the data will be saved. If file is a string, the ``.npz`` extension will be appended to the file name if it is not already there. matrix: spmatrix (format: ``csc``, ``csr``, ``bsr``, ``dia`` or coo``) The sparse matrix to save. compressed : bool, optional Allow compressing the file. Default: True See Also -------- scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format. numpy.savez: Save several arrays into a ``.npz`` archive. numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive. Examples -------- Store sparse matrix to disk, and load it again: >>> import scipy.sparse >>> sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]])) >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) >>> scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) >>> sparse_matrix = scipy.sparse.load_npz('/tmp/sparse_matrix.npz') >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) """ arrays_dict = {} if matrix.format in ('csc', 'csr', 'bsr'): arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr) elif matrix.format == 'dia': arrays_dict.update(offsets=matrix.offsets) elif matrix.format == 'coo': arrays_dict.update(row=matrix.row, col=matrix.col) else: raise NotImplementedError('Save is not implemented for sparse matrix of format {}.'.format(matrix.format)) arrays_dict.update( format=matrix.format.encode('ascii'), shape=matrix.shape, data=matrix.data ) if compressed: np.savez_compressed(file, **arrays_dict) else: np.savez(file, **arrays_dict) def load_npz(file): """ Load a sparse matrix from a file using ``.npz`` format. Parameters ---------- file : str or file-like object Either the file name (string) or an open file (file-like object) where the data will be loaded. Returns ------- result : csc_matrix, csr_matrix, bsr_matrix, dia_matrix or coo_matrix A sparse matrix containing the loaded data. Raises ------ OSError If the input file does not exist or cannot be read. See Also -------- scipy.sparse.save_npz: Save a sparse matrix to a file using ``.npz`` format. numpy.load: Load several arrays from a ``.npz`` archive. Examples -------- Store sparse matrix to disk, and load it again: >>> import scipy.sparse >>> sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]])) >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) >>> scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) >>> sparse_matrix = scipy.sparse.load_npz('/tmp/sparse_matrix.npz') >>> sparse_matrix <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in Compressed Sparse Column format> >>> sparse_matrix.todense() matrix([[0, 0, 3], [4, 0, 0]], dtype=int64) """ with np.load(file, **PICKLE_KWARGS) as loaded: try: matrix_format = loaded['format'] except KeyError as e: raise ValueError('The file {} does not contain a sparse matrix.'.format(file)) from e matrix_format = matrix_format.item() if not isinstance(matrix_format, str): # Play safe with Python 2 vs 3 backward compatibility; # files saved with SciPy < 1.0.0 may contain unicode or bytes. matrix_format = matrix_format.decode('ascii') try: cls = getattr(scipy.sparse, '{}_matrix'.format(matrix_format)) except AttributeError as e: raise ValueError('Unknown matrix format "{}"'.format(matrix_format)) from e if matrix_format in ('csc', 'csr', 'bsr'): return cls((loaded['data'], loaded['indices'], loaded['indptr']), shape=loaded['shape']) elif matrix_format == 'dia': return cls((loaded['data'], loaded['offsets']), shape=loaded['shape']) elif matrix_format == 'coo': return cls((loaded['data'], (loaded['row'], loaded['col'])), shape=loaded['shape']) else: raise NotImplementedError('Load is not implemented for ' 'sparse matrix of format {}.'.format(matrix_format))
[ 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 82, 29572, 198, 198, 834, 439, 834, 796, 37250, 21928, 62, 37659, 89, 3256, 705, 2220, 62, 37659, 89, 20520, 628, 198, 2, 6889, 11046, 3338, 3691, 13, 17412, 5128, 198, 47...
2.390408
2,231
from typing import Dict, List from simulator.services.resources.directory import Directory from simulator.services.services import Services
[ 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 6738, 35375, 13, 30416, 13, 37540, 13, 34945, 1330, 27387, 198, 6738, 35375, 13, 30416, 13, 30416, 1330, 6168, 628 ]
4.896552
29
# Copyright 2022 Collate # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ TestCase builder """ from metadata.generated.schema.api.tests.createTableTest import CreateTableTestRequest from metadata.generated.schema.tests.table import tableRowCountToEqual from metadata.generated.schema.tests.tableTest import TableTestType from metadata.great_expectations.builders.table.base_table_test_builders import ( BaseTableTestBuilder, )
[ 2, 220, 15069, 33160, 7778, 378, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 220, 921...
3.766129
248
''' This code is based on https://github.com/jrieke/shape-detection/ ''' import matplotlib.pyplot as plt import matplotlib import numpy as np import tensorflow as tf import datetime
[ 7061, 6, 198, 1212, 2438, 318, 1912, 319, 3740, 1378, 12567, 13, 785, 14, 73, 5034, 365, 14, 43358, 12, 15255, 3213, 14, 198, 7061, 6, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019,...
3
61
import pickle import threading from bmconfigparser import BMConfigParser import state knownNodesLock = threading.Lock() knownNodes = {} knownNodesTrimAmount = 2000
[ 11748, 2298, 293, 198, 11748, 4704, 278, 198, 198, 6738, 275, 76, 11250, 48610, 1330, 29944, 16934, 46677, 198, 11748, 1181, 198, 198, 4002, 45, 4147, 25392, 796, 4704, 278, 13, 25392, 3419, 198, 4002, 45, 4147, 796, 23884, 198, 198, ...
3.34
50
# Copyright (c) 2018 DDN. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. import os from chroma_agent.lib.shell import AgentShell from chroma_agent.log import console_log from chroma_agent.device_plugins.action_runner import CallbackAfterResponse from chroma_agent.lib.pacemaker import PacemakerConfig ACTIONS = [reboot_server, shutdown_server, fail_node, stonith]
[ 2, 15069, 357, 66, 8, 2864, 20084, 45, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 17168, 12, 7635, 198, 2, 5964, 326, 460, 307, 1043, 287, 262, 38559, 24290, 2393, 13, 628, 198, 11748, 286...
3.435115
131
#! /usr/bin/env python # -*- coding: utf-8 -* """ A base class that governs how to download and process tables from a Census API table. """ import os import logging import pathlib from . import geotypes from . import decorators logger = logging.getLogger(__name__)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 198, 37811, 198, 32, 2779, 1398, 326, 47049, 703, 284, 4321, 290, 1429, 8893, 422, 257, 20962, 7824, 3084, 13, 198, 37811, 1...
3.283951
81
#!/usr/bin/env python3 import argparse import os from pathlib import Path import shutil import subprocess import sys from tempfile import TemporaryDirectory from uuid import uuid4 from zipfile import ZipFile import jinja2 import sente # type: ignore __version__ = (1, 0, 0) SGF_RENDER_EXECUTABLE = './sgf-render' TEMPLATEDIR = Path(__file__, '..', 'epub_template').resolve() if __name__ == "__main__": parser = argparse.ArgumentParser( description='') parser.add_argument('--input-path', '-i', help='Input files or directory') parser.add_argument('--output-path', '-o', help='Output directory') args = parser.parse_args() path = Path(args.input_path) outpath = Path(args.output_path) if not path.exists(): print(f'Input path {path} not found') sys.exit(1) if path.is_file(): main(path, outpath) if path.is_dir(): for filepath in sorted(path.rglob('*.sgf')): main(filepath, outpath.joinpath(filepath.parent.relative_to(path)))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 4423, 346, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 6738, 20218, 7753, 1330, 46042, 43055,...
2.547264
402
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^settings$', views.household_dashboard, name='household_dashboard'), url(r'^myinfo$', views.my_info, name='my_info'), url(r'^profile$', views.household_profile, name='maintain_household'), url(r'^members$', views.household_members, name='maintain_members'), url(r'^vehicles$', views.household_vehicles, name='maintain_vehicles'), url(r'^ajax/models-by-make/(?P<make_id>\d+)/$', views.ajax_models_by_make), url(r'^ajax/makes-by-type/(?P<type_id>\d+)/$', views.ajax_makes_by_type), url(r'^ajax/add-make/(?P<type_key>\d+)/(?P<make>[\w ]{1,50})/$', views.ajax_add_make), url(r'^ajax/add-model/(?P<make_key>\d+)/(?P<model>[\w -]{1,128})/$', views.ajax_add_model), url(r'^ajax/delete-invite/$', views.ajax_delete_invite), url(r'^ajax/change-member-status/$', views.ajax_change_member_status), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 11, 19016, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 33692, 3, 3256, 5009, 13, 4803, 2946, 62, 42460, 3526, 1...
2.233577
411
# -*- coding: utf-8 -*- try: # Python 2.7 from collections import OrderedDict except: # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from gluon import current from gluon.html import A, URL from gluon.storage import Storage from s3 import s3_fullname T = current.T settings = current.deployment_settings """ Template settings for NYC Prepared """ # Pre-Populate settings.base.prepopulate = ("NYC",) settings.base.system_name = T("NYC Prepared") settings.base.system_name_short = T("NYC Prepared") # Theme (folder to use for views/layout.html) settings.base.theme = "NYC" settings.ui.formstyle_row = "bootstrap" settings.ui.formstyle = "bootstrap" settings.ui.filter_formstyle = "table_inline" settings.msg.parser = "NYC" # Uncomment to Hide the language toolbar settings.L10n.display_toolbar = False # Default timezone for users settings.L10n.utc_offset = "UTC -0500" # Uncomment these to use US-style dates in English settings.L10n.date_format = "%m-%d-%Y" # Start week on Sunday settings.L10n.firstDOW = 0 # Number formats (defaults to ISO 31-0) # Decimal separator for numbers (defaults to ,) settings.L10n.decimal_separator = "." # Thousands separator for numbers (defaults to space) settings.L10n.thousands_separator = "," # Default Country Code for telephone numbers settings.L10n.default_country_code = 1 # Enable this to change the label for 'Mobile Phone' settings.ui.label_mobile_phone = "Cell Phone" # Enable this to change the label for 'Postcode' settings.ui.label_postcode = "ZIP Code" # Uncomment to disable responsive behavior of datatables # - Disabled until tested settings.ui.datatables_responsive = False # PDF to Letter settings.base.paper_size = T("Letter") # Restrict the Location Selector to just certain countries # NB This can also be over-ridden for specific contexts later # e.g. Activities filtered to those of parent Project settings.gis.countries = ("US",) settings.fin.currencies = { "USD" : T("United States Dollars"), } settings.L10n.languages = OrderedDict([ ("en", "English"), ("es", "Espaol"), ]) # Authentication settings # These settings should be changed _after_ the 1st (admin) user is # registered in order to secure the deployment # Should users be allowed to register themselves? settings.security.self_registration = "index" # Do new users need to verify their email address? settings.auth.registration_requires_verification = True # Do new users need to be approved by an administrator prior to being able to login? settings.auth.registration_requires_approval = True # Always notify the approver of a new (verified) user, even if the user is automatically approved #settings.auth.always_notify_approver = False # Uncomment this to request the Mobile Phone when a user registers settings.auth.registration_requests_mobile_phone = True # Uncomment this to request the Organisation when a user registers settings.auth.registration_requests_organisation = True # Uncomment this to request the Site when a user registers #settings.auth.registration_requests_site = True # Roles that newly-registered users get automatically #settings.auth.registration_roles = { 0: ["comms_dispatch"]} #settings.auth.registration_link_user_to = {"staff":T("Staff"), # #"volunteer":T("Volunteer") # } settings.auth.registration_link_user_to_default = "staff" settings.security.policy = 5 # Controller, Function & Table ACLs # Enable this to have Open links in IFrames open a full page in a new tab settings.ui.iframe_opens_full = True settings.ui.label_attachments = "Media" settings.ui.update_label = "Edit" # Uncomment to disable checking that LatLons are within boundaries of their parent #settings.gis.check_within_parent_boundaries = False # GeoNames username settings.gis.geonames_username = "eden_nyc" # Uncomment to show created_by/modified_by using Names not Emails settings.ui.auth_user_represent = "name" # Record Approval settings.auth.record_approval = True settings.auth.record_approval_required_for = ("org_organisation",) # ----------------------------------------------------------------------------- # Audit settings.security.audit_write = audit_write # ----------------------------------------------------------------------------- # CMS # Uncomment to use Bookmarks in Newsfeed settings.cms.bookmarks = True # Uncomment to use have Filter form in Newsfeed be open by default settings.cms.filter_open = True # Uncomment to adjust filters in Newsfeed when clicking on locations instead of opening the profile page settings.cms.location_click_filters = True # Uncomment to use organisation_id instead of created_by in Newsfeed settings.cms.organisation = "post_organisation.organisation_id" # Uncomment to use org_group_id in Newsfeed settings.cms.organisation_group = "post_organisation_group.group_id" # Uncomment to use person_id instead of created_by in Newsfeed settings.cms.person = "person_id" # Uncomment to use Rich Text editor in Newsfeed settings.cms.richtext = True # Uncomment to show Links in Newsfeed settings.cms.show_links = True # Uncomment to show Tags in Newsfeed settings.cms.show_tags = True # Uncomment to show post Titles in Newsfeed settings.cms.show_titles = True # ----------------------------------------------------------------------------- # Inventory Management # Uncomment to customise the label for Facilities in Inventory Management settings.inv.facility_label = "Facility" # Uncomment if you need a simpler (but less accountable) process for managing stock levels #settings.inv.direct_stock_edits = True # Uncomment to call Stock Adjustments, 'Stock Counts' settings.inv.stock_count = True # Uncomment to not track pack values settings.inv.track_pack_values = False settings.inv.send_show_org = False # Types common to both Send and Receive settings.inv.shipment_types = { 1: T("Other Warehouse") } settings.inv.send_types = { #21: T("Distribution") } settings.inv.send_type_default = 1 settings.inv.item_status = { #0: current.messages["NONE"], #1: T("Dump"), #2: T("Sale"), #3: T("Reject"), #4: T("Surplus") } # ----------------------------------------------------------------------------- # Organisations # # Enable the use of Organisation Groups settings.org.groups = "Network" # Make Services Hierarchical settings.org.services_hierarchical = True # Set the label for Sites settings.org.site_label = "Facility" #settings.org.site_label = "Location" # Uncomment to show the date when a Site (Facilities-only for now) was last contacted settings.org.site_last_contacted = True # Enable certain fields just for specific Organisations # empty list => disabled for all (including Admin) #settings.org.dependent_fields = { \ # "pr_person_details.mother_name" : [], # "pr_person_details.father_name" : [], # "pr_person_details.company" : [], # "pr_person_details.affiliations" : [], # "vol_volunteer.active" : [], # "vol_volunteer_cluster.vol_cluster_type_id" : [], # "vol_volunteer_cluster.vol_cluster_id" : [], # "vol_volunteer_cluster.vol_cluster_position_id" : [], # } # Uncomment to use an Autocomplete for Site lookup fields settings.org.site_autocomplete = True # Extra fields to search in Autocompletes & display in Representations settings.org.site_autocomplete_fields = ("organisation_id$name", "location_id$addr_street", ) # Uncomment to hide inv & req tabs from Sites #settings.org.site_inv_req_tabs = True # ----------------------------------------------------------------------------- def facility_marker_fn(record): """ Function to decide which Marker to use for Facilities Map @ToDo: Legend """ db = current.db s3db = current.s3db table = db.org_facility_type ltable = db.org_site_facility_type query = (ltable.site_id == record.site_id) & \ (ltable.facility_type_id == table.id) rows = db(query).select(table.name) types = [row.name for row in rows] # Use Marker in preferential order if "Hub" in types: marker = "warehouse" elif "Medical Clinic" in types: marker = "hospital" elif "Food" in types: marker = "food" elif "Relief Site" in types: marker = "asset" elif "Residential Building" in types: marker = "residence" #elif "Shelter" in types: # marker = "shelter" else: # Unknown marker = "office" if settings.has_module("req"): # Colour code by open/priority requests reqs = record.reqs if reqs == 3: # High marker = "%s_red" % marker elif reqs == 2: # Medium marker = "%s_yellow" % marker elif reqs == 1: # Low marker = "%s_green" % marker mtable = db.gis_marker try: marker = db(mtable.name == marker).select(mtable.image, mtable.height, mtable.width, cache=s3db.cache, limitby=(0, 1) ).first() except: marker = db(mtable.name == "office").select(mtable.image, mtable.height, mtable.width, cache=s3db.cache, limitby=(0, 1) ).first() return marker # ----------------------------------------------------------------------------- def org_facility_onvalidation(form): """ Default the name to the Street Address """ form_vars = form.vars name = form_vars.get("name", None) if name: return address = form_vars.get("address", None) if address: form_vars.name = address else: # We need a default form_vars.name = current.db.org_facility.location_id.represent(form_vars.location_id) # ----------------------------------------------------------------------------- settings.customise_org_facility_controller = customise_org_facility_controller # ----------------------------------------------------------------------------- settings.customise_org_organisation_resource = customise_org_organisation_resource # ----------------------------------------------------------------------------- settings.customise_org_organisation_controller = customise_org_organisation_controller # ----------------------------------------------------------------------------- settings.customise_org_group_controller = customise_org_group_controller # ----------------------------------------------------------------------------- # Persons # Uncomment to hide fields in S3AddPersonWidget settings.pr.request_dob = False settings.pr.request_gender = False # Doesn't yet work (form fails to submit) #settings.pr.select_existing = False settings.pr.show_emergency_contacts = False # ----------------------------------------------------------------------------- # Persons settings.customise_pr_person_controller = customise_pr_person_controller # ----------------------------------------------------------------------------- # Groups def chairperson(row): """ Virtual Field to show the chairperson of a group """ if hasattr(row, "pr_group"): row = row.pr_group try: group_id = row.id except: # not available return current.messages["NONE"] db = current.db mtable = current.s3db.pr_group_membership ptable = db.pr_person query = (mtable.group_id == group_id) & \ (mtable.group_head == True) & \ (mtable.person_id == ptable.id) chair = db(query).select(ptable.first_name, ptable.middle_name, ptable.last_name, ptable.id, limitby=(0, 1)).first() if chair: # Only used in list view so HTML is OK return A(s3_fullname(chair), _href=URL(c="hrm", f="person", args=chair.id)) else: return current.messages["NONE"] # ----------------------------------------------------------------------------- settings.customise_pr_group_controller = customise_pr_group_controller # ----------------------------------------------------------------------------- def customise_pr_group_resource(r, tablename): """ Customise pr_group resource (in group & org_group controllers) - runs after controller customisation - but runs before prep """ s3db = current.s3db table = s3db.pr_group field = table.group_type field.default = 3 # Relief Team, to show up in hrm/group field.readable = field.writable = False table.name.label = T("Name") table.description.label = T("Description") table.meetings.readable = table.meetings.writable = True # Increase size of widget from s3 import s3_comments_widget table.description.widget = s3_comments_widget from gluon import Field table.chairperson = Field.Method("chairperson", chairperson) # Format for filter_widgets & imports s3db.add_components("pr_group", org_group_team = "group_id", ) s3db.configure("pr_group", # Redirect to member list when a new group has been created create_next = URL(c="hrm", f="group", args=["[id]", "group_membership"]), ) settings.customise_pr_group_resource = customise_pr_group_resource # ----------------------------------------------------------------------------- def pr_contact_postprocess(form): """ Import Organisation/Network RSS Feeds """ s3db = current.s3db form_vars = form.vars rss_url = form_vars.rsscontact_i_value_edit_0 or \ form_vars.rsscontact_i_value_edit_none if not rss_url: if form.record: # Update form old_rss = form.record.sub_rsscontact import json data = old_rss = json.loads(old_rss)["data"] if data: # RSS feed is being deleted, so we should disable it old_rss = data[0]["value"]["value"] table = s3db.msg_rss_channel old = current.db(table.url == old_rss).select(table.channel_id, table.enabled, limitby = (0, 1) ).first() if old and old.enabled: s3db.msg_channel_disable("msg_rss_channel", old.channel_id) return else: # Nothing to do :) return # Check if we already have a channel for this Contact db = current.db name = form_vars.name table = s3db.msg_rss_channel name_exists = db(table.name == name).select(table.id, table.channel_id, table.enabled, table.url, limitby = (0, 1) ).first() no_import = current.request.post_vars.get("rss_no_import", None) if name_exists: if name_exists.url == rss_url: # No change to either Contact Name or URL if no_import: if name_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", name_exists.channel_id) return elif name_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", name_exists.channel_id) return # Check if we already have a channel for this URL url_exists = db(table.url == rss_url).select(table.id, table.channel_id, table.enabled, limitby = (0, 1) ).first() if url_exists: # We have 2 feeds: 1 for the Contact & 1 for the URL # Disable the old Contact one and link the URL one to this Contact # and ensure active or not as appropriate # Name field is unique so rename old one name_exists.update_record(name="%s (Old)" % name) if name_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", name_exists.channel_id) url_exists.update_record(name=name) if no_import: if url_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", url_exists.channel_id) return elif url_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", url_exists.channel_id) return else: # Update the URL name_exists.update_record(url=rss_url) if no_import: if name_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", name_exists.channel_id) return elif name_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", name_exists.channel_id) return else: # Check if we already have a channel for this URL url_exists = db(table.url == rss_url).select(table.id, table.channel_id, table.enabled, limitby = (0, 1) ).first() if url_exists: # Either Contact has changed Name or this feed is associated with # another Contact # - update Feed name url_exists.update_record(name=name) if no_import: if url_exists.enabled: # Disable channel (& associated parsers) s3db.msg_channel_disable("msg_rss_channel", url_exists.channel_id) return elif url_exists.enabled: # Nothing to do :) return else: # Enable channel (& associated parsers) s3db.msg_channel_enable("msg_rss_channel", url_exists.channel_id) return elif no_import: # Nothing to do :) return #else: # # Create a new Feed # pass # Add RSS Channel _id = table.insert(name=name, enabled=True, url=rss_url) record = dict(id=_id) s3db.update_super(table, record) # Enable channel_id = record["channel_id"] s3db.msg_channel_enable("msg_rss_channel", channel_id) # Setup Parser table = s3db.msg_parser _id = table.insert(channel_id=channel_id, function_name="parse_rss", enabled=True) s3db.msg_parser_enable(_id) # Check Now async = current.s3task.async async("msg_poll", args=["msg_rss_channel", channel_id]) async("msg_parse", args=[channel_id, "parse_rss"]) # ----------------------------------------------------------------------------- # Human Resource Management # Uncomment to chage the label for 'Staff' settings.hrm.staff_label = "Contacts" # Uncomment to allow Staff & Volunteers to be registered without an email address settings.hrm.email_required = False # Uncomment to allow Staff & Volunteers to be registered without an Organisation settings.hrm.org_required = False # Uncomment to show the Organisation name in HR represents settings.hrm.show_organisation = True # Uncomment to disable Staff experience settings.hrm.staff_experience = False # Uncomment to disable the use of HR Certificates settings.hrm.use_certificates = False # Uncomment to disable the use of HR Credentials settings.hrm.use_credentials = False # Uncomment to enable the use of HR Education settings.hrm.use_education = False # Uncomment to disable the use of HR Skills #settings.hrm.use_skills = False # Uncomment to disable the use of HR Trainings settings.hrm.use_trainings = False # Uncomment to disable the use of HR Description settings.hrm.use_description = False # Change the label of "Teams" to "Groups" settings.hrm.teams = "Groups" # Custom label for Organisations in HR module #settings.hrm.organisation_label = "National Society / Branch" settings.hrm.organisation_label = "Organization" # ----------------------------------------------------------------------------- settings.customise_hrm_human_resource_controller = customise_hrm_human_resource_controller # ----------------------------------------------------------------------------- def customise_hrm_human_resource_resource(r, tablename): """ Customise hrm_human_resource resource (in facility, human_resource, organisation & person controllers) - runs after controller customisation - but runs before prep """ s3db = current.s3db from s3 import S3SQLCustomForm, S3SQLInlineComponent crud_form = S3SQLCustomForm("person_id", "organisation_id", "site_id", S3SQLInlineComponent( "group_person", label = T("Network"), link = False, fields = [("", "group_id")], multiple = False, ), "job_title_id", "start_date", ) list_fields = ["id", "person_id", "job_title_id", "organisation_id", (T("Network"), "group_person.group_id"), (T("Groups"), "person_id$group_membership.group_id"), "site_id", #"site_contact", (T("Email"), "email.value"), (settings.get_ui_label_mobile_phone(), "phone.value"), ] s3db.configure("hrm_human_resource", crud_form = crud_form, list_fields = list_fields, ) settings.customise_hrm_human_resource_resource = customise_hrm_human_resource_resource # ----------------------------------------------------------------------------- settings.customise_hrm_job_title_controller = customise_hrm_job_title_controller # ----------------------------------------------------------------------------- # Projects # Use codes for projects (called 'blurb' in NYC) settings.project.codes = True # Uncomment this to use settings suitable for detailed Task management settings.project.mode_task = False # Uncomment this to use Activities for projects settings.project.activities = True # Uncomment this to use Milestones in project/task. settings.project.milestones = False # Uncomment this to disable Sectors in projects settings.project.sectors = False # Multiple partner organizations settings.project.multiple_organisations = True settings.customise_project_project_controller = customise_project_project_controller # ----------------------------------------------------------------------------- # Requests Management settings.req.req_type = ["People", "Stock"]#, "Summary"] settings.req.prompt_match = False #settings.req.use_commit = False settings.req.requester_optional = True settings.req.date_writable = False settings.req.item_quantities_writable = True settings.req.skill_quantities_writable = True settings.req.items_ask_purpose = False #settings.req.use_req_number = False # Label for Requester settings.req.requester_label = "Site Contact" # Filter Requester as being from the Site settings.req.requester_from_site = True # Label for Inventory Requests settings.req.type_inv_label = "Supplies" # Uncomment to enable Summary 'Site Needs' tab for Offices/Facilities settings.req.summary = True # ----------------------------------------------------------------------------- def req_req_postprocess(form): """ Runs after crud_form completes - creates a cms_post in the newswire - @ToDo: Send out Tweets """ req_id = form.vars.id db = current.db s3db = current.s3db rtable = s3db.req_req # Read the full record row = db(rtable.id == req_id).select(rtable.type, rtable.site_id, rtable.requester_id, rtable.priority, rtable.date_required, rtable.purpose, rtable.comments, limitby=(0, 1) ).first() # Build Title & Body from the Request details priority = rtable.priority.represent(row.priority) date_required = row.date_required if date_required: date = rtable.date_required.represent(date_required) title = "%(priority)s by %(date)s" % dict(priority=priority, date=date) else: title = priority body = row.comments if row.type == 1: # Items ritable = s3db.req_req_item items = db(ritable.req_id == req_id).select(ritable.item_id, ritable.item_pack_id, ritable.quantity) item_represent = s3db.supply_item_represent pack_represent = s3db.supply_item_pack_represent for item in items: item = "%s %s %s" % (item.quantity, pack_represent(item.item_pack_id), item_represent(item.item_id)) body = "%s\n%s" % (item, body) else: # Skills body = "%s\n%s" % (row.purpose, body) rstable = s3db.req_req_skill skills = db(rstable.req_id == req_id).select(rstable.skill_id, rstable.quantity) skill_represent = s3db.hrm_multi_skill_represent for skill in skills: item = "%s %s" % (skill.quantity, skill_represent(skill.skill_id)) body = "%s\n%s" % (item, body) # Lookup series_id stable = s3db.cms_series try: series_id = db(stable.name == "Request").select(stable.id, cache=s3db.cache, limitby=(0, 1) ).first().id except: # Prepop hasn't been run series_id = None # Location is that of the site otable = s3db.org_site location_id = db(otable.site_id == row.site_id).select(otable.location_id, limitby=(0, 1) ).first().location_id # Create Post ptable = s3db.cms_post _id = ptable.insert(series_id=series_id, title=title, body=body, location_id=location_id, person_id=row.requester_id, ) record = dict(id=_id) s3db.update_super(ptable, record) # Add source link url = "%s%s" % (settings.get_base_public_url(), URL(c="req", f="req", args=req_id)) s3db.doc_document.insert(doc_id=record["doc_id"], url=url, ) # ----------------------------------------------------------------------------- settings.customise_req_req_resource = customise_req_req_resource # ----------------------------------------------------------------------------- # Comment/uncomment modules here to disable/enable them settings.modules = OrderedDict([ # Core modules which shouldn't be disabled ("default", Storage( name_nice = T("Home"), restricted = False, # Use ACLs to control access to this module access = None, # All Users (inc Anonymous) can see this module in the default menu & access the controller module_type = None # This item is not shown in the menu )), ("admin", Storage( name_nice = T("Admin"), #description = "Site Administration", restricted = True, access = "|1|", # Only Administrators can see this module in the default menu & access the controller module_type = None # This item is handled separately for the menu )), ("appadmin", Storage( name_nice = T("Administration"), #description = "Site Administration", restricted = True, module_type = None # No Menu )), ("errors", Storage( name_nice = T("Ticket Viewer"), #description = "Needed for Breadcrumbs", restricted = False, module_type = None # No Menu )), ("sync", Storage( name_nice = T("Synchronization"), #description = "Synchronization", restricted = True, access = "|1|", # Only Administrators can see this module in the default menu & access the controller module_type = None # This item is handled separately for the menu )), # Uncomment to enable internal support requests #("support", Storage( # name_nice = T("Support"), # #description = "Support Requests", # restricted = True, # module_type = None # This item is handled separately for the menu # )), ("gis", Storage( name_nice = T("Map"), #description = "Situation Awareness & Geospatial Analysis", restricted = True, module_type = 9, # 8th item in the menu )), ("pr", Storage( name_nice = T("Person Registry"), #description = "Central point to record details on People", restricted = True, access = "|1|", # Only Administrators can see this module in the default menu (access to controller is possible to all still) module_type = 10 )), ("org", Storage( name_nice = T("Locations"), #description = 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities', restricted = True, module_type = 4 )), # All modules below here should be possible to disable safely ("hrm", Storage( name_nice = T("Contacts"), #description = "Human Resources Management", restricted = True, module_type = 3, )), #("vol", Storage( # name_nice = T("Volunteers"), # #description = "Human Resources Management", # restricted = True, # module_type = 2, # )), ("cms", Storage( name_nice = T("Content Management"), #description = "Content Management System", restricted = True, module_type = 10, )), ("doc", Storage( name_nice = T("Documents"), #description = "A library of digital resources, such as photos, documents and reports", restricted = True, module_type = None, )), ("msg", Storage( name_nice = T("Messaging"), #description = "Sends & Receives Alerts via Email & SMS", restricted = True, # The user-visible functionality of this module isn't normally required. Rather it's main purpose is to be accessed from other modules. module_type = None, )), ("supply", Storage( name_nice = T("Supply Chain Management"), #description = "Used within Inventory Management, Request Management and Asset Management", restricted = True, module_type = None, # Not displayed )), ("inv", Storage( name_nice = T("Inventory"), #description = "Receiving and Sending Items", restricted = True, module_type = 10 )), #("proc", Storage( # name_nice = T("Procurement"), # #description = "Ordering & Purchasing of Goods & Services", # restricted = True, # module_type = 10 # )), ("asset", Storage( name_nice = T("Assets"), #description = "Recording and Assigning Assets", restricted = True, module_type = 10, )), # Vehicle depends on Assets #("vehicle", Storage( # name_nice = T("Vehicles"), # #description = "Manage Vehicles", # restricted = True, # module_type = 10, # )), ("req", Storage( name_nice = T("Requests"), #description = "Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.", restricted = True, module_type = 1, )), ("project", Storage( name_nice = T("Projects"), #description = "Tracking of Projects, Activities and Tasks", restricted = True, module_type = 10 )), ("assess", Storage( name_nice = T("Assessments"), #description = "Rapid Assessments & Flexible Impact Assessments", restricted = True, module_type = 5, )), ("event", Storage( name_nice = T("Events"), #description = "Activate Events (e.g. from Scenario templates) for allocation of appropriate Resources (Human, Assets & Facilities).", restricted = True, module_type = 10, )), ("survey", Storage( name_nice = T("Surveys"), #description = "Create, enter, and manage surveys.", restricted = True, module_type = 5, )), #("cr", Storage( # name_nice = T("Shelters"), # #description = "Tracks the location, capacity and breakdown of victims in Shelters", # restricted = True, # module_type = 10 # )), #("dvr", Storage( # name_nice = T("Disaster Victim Registry"), # #description = "Allow affected individuals & households to register to receive compensation and distributions", # restricted = False, # module_type = 10, # )), #("member", Storage( # name_nice = T("Members"), # #description = "Membership Management System", # restricted = True, # module_type = 10, # )), # @ToDo: Rewrite in a modern style #("budget", Storage( # name_nice = T("Budgeting Module"), # #description = "Allows a Budget to be drawn up", # restricted = True, # module_type = 10 # )), # @ToDo: Port these Assessments to the Survey module #("building", Storage( # name_nice = T("Building Assessments"), # #description = "Building Safety Assessments", # restricted = True, # module_type = 10, # )), ])
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 28311, 25, 198, 220, 220, 220, 1303, 11361, 362, 13, 22, 198, 220, 220, 220, 422, 17268, 1330, 14230, 1068, 35, 713, 198, 16341, 25, 198, 220, 220, 220, 1303, 1...
2.255594
16,491
#! /usr/bin/env python # -*- coding: utf-8 -*- from main import main main("issue561-v1", "issue561-v2")
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 1388, 1330, 1388, 198, 198, 12417, 7203, 21949, 47915, 12, 85, 16, 1600, 366, 21949, 47915, 12, 85, 17, ...
2.255319
47
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- from unittest import TestCase, main import qiime2 import os from q2_qemistree import MGFDirFmt, SiriusDirFmt, ZodiacDirFmt, OutputDirs from q2_qemistree import (compute_fragmentation_trees, rerank_molecular_formulas, predict_fingerprints) from q2_qemistree._fingerprint import artifactory if __name__ == '__main__': main()
[ 2, 16529, 10541, 198, 2, 15069, 357, 66, 8, 1584, 12, 7908, 11, 1195, 40, 12789, 362, 2478, 1074, 13, 198, 2, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 40499, 347, 10305, 13789, 13, 198, 2, 198, 2, 383, 1336, 5964, 318, 287,...
3.155172
232
import time import datetime import contextlib
[ 11748, 640, 198, 11748, 4818, 8079, 198, 11748, 4732, 8019, 628, 198 ]
4
12
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 Rackspace # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import kombu from tempo import actions from tempo import config from tempo import db from tempo import notifier from tempo import queue as tempo_queue from tempo.openstack.common import cfg from tempo.openstack.common import exception as common_exception CFG = config.CFG logger = logging.getLogger('tempo.worker') worker_opts = [ cfg.BoolOpt('daemonized', default=False, help='Run worker as a daemon'), cfg.StrOpt('publisher_id', default='host', help='Where the notification came from') ] worker_group = cfg.OptGroup(name='worker', title='Worker options') CFG.register_group(worker_group) CFG.register_opts(worker_opts, group=worker_group)
[ 2, 43907, 25, 7400, 11338, 28, 19, 6482, 10394, 28, 19, 2705, 8658, 11338, 28, 19, 198, 2, 198, 2, 15069, 2321, 37927, 13200, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, ...
2.966245
474
#!/usr/bin/env python # Copyright 2017 Calico LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================= from __future__ import print_function from optparse import OptionParser import copy, os, pdb, random, shutil, subprocess, time import h5py import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.stats import spearmanr import seaborn as sns from sklearn import preprocessing import tensorflow as tf import basenji ''' basenji_motifs.py Collect statistics and make plots to explore the first convolution layer of the given model using the given sequences. ''' weblogo_opts = '-X NO -Y NO --errorbars NO --fineprint ""' weblogo_opts += ' -C "#CB2026" A A' weblogo_opts += ' -C "#34459C" C C' weblogo_opts += ' -C "#FBB116" G G' weblogo_opts += ' -C "#0C8040" T T' ################################################################################ # main ################################################################################ def get_motif_proteins(meme_db_file): """ Hash motif_id's to protein names using the MEME DB file """ motif_protein = {} for line in open(meme_db_file): a = line.split() if len(a) > 0 and a[0] == 'MOTIF': if a[2][0] == '(': motif_protein[a[1]] = a[2][1:a[2].find(')')] else: motif_protein[a[1]] = a[2] return motif_protein def info_content(pwm, transpose=False, bg_gc=0.415): """ Compute PWM information content. In the original analysis, I used a bg_gc=0.5. For any future analysis, I ought to switch to the true hg19 value of 0.415. """ pseudoc = 1e-9 if transpose: pwm = np.transpose(pwm) bg_pwm = [1 - bg_gc, bg_gc, bg_gc, 1 - bg_gc] ic = 0 for i in range(pwm.shape[0]): for j in range(4): # ic += 0.5 + pwm[i][j]*np.log2(pseudoc+pwm[i][j]) ic += -bg_pwm[j] * np.log2( bg_pwm[j]) + pwm[i][j] * np.log2(pseudoc + pwm[i][j]) return ic def make_filter_pwm(filter_fasta): """ Make a PWM for this filter from its top hits """ nts = {'A': 0, 'C': 1, 'G': 2, 'T': 3} pwm_counts = [] nsites = 4 # pseudocounts for line in open(filter_fasta): if line[0] != '>': seq = line.rstrip() nsites += 1 if len(pwm_counts) == 0: # initialize with the length for i in range(len(seq)): pwm_counts.append(np.array([1.0] * 4)) # count for i in range(len(seq)): try: pwm_counts[i][nts[seq[i]]] += 1 except KeyError: pwm_counts[i] += np.array([0.25] * 4) # normalize pwm_freqs = [] for i in range(len(pwm_counts)): pwm_freqs.append([pwm_counts[i][j] / float(nsites) for j in range(4)]) return np.array(pwm_freqs), nsites - 4 def meme_add(meme_out, f, filter_pwm, nsites, trim_filters=False): """ Print a filter to the growing MEME file Attrs: meme_out : open file f (int) : filter index # filter_pwm (array) : filter PWM array nsites (int) : number of filter sites """ if not trim_filters: ic_start = 0 ic_end = filter_pwm.shape[0] - 1 else: ic_t = 0.2 # trim PWM of uninformative prefix ic_start = 0 while ic_start < filter_pwm.shape[0] and info_content( filter_pwm[ic_start:ic_start + 1]) < ic_t: ic_start += 1 # trim PWM of uninformative suffix ic_end = filter_pwm.shape[0] - 1 while ic_end >= 0 and info_content(filter_pwm[ic_end:ic_end + 1]) < ic_t: ic_end -= 1 if ic_start < ic_end: print('MOTIF filter%d' % f, file=meme_out) print( 'letter-probability matrix: alength= 4 w= %d nsites= %d' % (ic_end - ic_start + 1, nsites), file=meme_out) for i in range(ic_start, ic_end + 1): print('%.4f %.4f %.4f %.4f' % tuple(filter_pwm[i]), file=meme_out) print('', file=meme_out) def meme_intro(meme_file, seqs): """ Open MEME motif format file and print intro Attrs: meme_file (str) : filename seqs [str] : list of strings for obtaining background freqs Returns: mem_out : open MEME file """ nts = {'A': 0, 'C': 1, 'G': 2, 'T': 3} # count nt_counts = [1] * 4 for i in range(len(seqs)): for nt in seqs[i]: try: nt_counts[nts[nt]] += 1 except KeyError: pass # normalize nt_sum = float(sum(nt_counts)) nt_freqs = [nt_counts[i] / nt_sum for i in range(4)] # open file for writing meme_out = open(meme_file, 'w') # print intro material print('MEME version 4', file=meme_out) print('', file=meme_out) print('ALPHABET= ACGT', file=meme_out) print('', file=meme_out) print('Background letter frequencies:', file=meme_out) print('A %.4f C %.4f G %.4f T %.4f' % tuple(nt_freqs), file=meme_out) print('', file=meme_out) return meme_out def name_filters(num_filters, tomtom_file, meme_db_file): """ Name the filters using Tomtom matches. Attrs: num_filters (int) : total number of filters tomtom_file (str) : filename of Tomtom output table. meme_db_file (str) : filename of MEME db Returns: filter_names [str] : """ # name by number filter_names = ['f%d' % fi for fi in range(num_filters)] # name by protein if tomtom_file is not None and meme_db_file is not None: motif_protein = get_motif_proteins(meme_db_file) # hash motifs and q-value's by filter filter_motifs = {} tt_in = open(tomtom_file) tt_in.readline() for line in tt_in: a = line.split() fi = int(a[0][6:]) motif_id = a[1] qval = float(a[5]) filter_motifs.setdefault(fi, []).append((qval, motif_id)) tt_in.close() # assign filter's best match for fi in filter_motifs: top_motif = sorted(filter_motifs[fi])[0][1] filter_names[fi] += '_%s' % motif_protein[top_motif] return np.array(filter_names) ################################################################################ # plot_target_corr # # Plot a clustered heatmap of correlations between filter activations and # targets. # # Input # filter_outs: # filter_names: # target_names: # out_pdf: ################################################################################ ################################################################################ # plot_filter_seq_heat # # Plot a clustered heatmap of filter activations in # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_filter_seq_heat # # Plot a clustered heatmap of filter activations in sequence segments. # # Mean doesn't work well for the smaller segments for some reason, but taking # the max looks OK. Still, similar motifs don't cluster quite as well as you # might expect. # # Input # filter_outs ################################################################################ ################################################################################ # filter_motif # # Collapse the filter parameter matrix to a single DNA motif. # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # filter_possum # # Write a Possum-style motif # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_filter_heat # # Plot a heatmap of the filter's parameters. # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_filter_logo # # Plot a weblogo of the filter's occurrences # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # plot_score_density # # Plot the score density and print to the stats table. # # Input # param_matrix: np.array of the filter's parameter matrix # out_pdf: ################################################################################ ################################################################################ # __main__ ################################################################################ if __name__ == '__main__': main() # pdb.runcall(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 2177, 2199, 3713, 11419, 198, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287,...
2.882733
3,249
from django.urls import path from . import views app_name = "shop" urlpatterns = [ path('', views.HomePage.as_view(), name="home-page"), path('shop/', views.ProductListView.as_view(), name="product-list"), path('shop/<int:category_pk>/', views.ProductListView.as_view(), name="product-list"), path('shop/products/<int:pk>/', views.ProductDetailView.as_view(), name="product-detail"), path('cart/', views.cart_view, name="cart"), path('cart/add/<int:product_pk>/', views.add_product_to_order, name="add-product-to-cart"), path('cart/add/<int:product_pk>/json/', views.add_product_to_cart_json, name="add-product-to-cart-json"), path('checkout/', views.CheckOut.as_view(), name="checkout"), path('checkout/<int:address_pk>/', views.CheckOut.as_view(), name="checkout"), path('payment/', views.PaymentChoice.as_view(), name="payment-choice"), path('payment/order/<int:pk>/', views.MomoPayment.as_view(), name="momo-payment"), path('payment/momo/<int:pk>/confirm/', views.ConfirmMomoPayment.as_view(), name="confirm-momo-payment"), path('orders/', views.OrderList.as_view(), name="order-list"), path('orders/<int:pk>/', views.OrderDetail.as_view(), name="order-detail"), path('orders/<int:order_id>/items/<int:pk>/', views.OrderItemDetail.as_view(), name="order-item-detail"), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 1330, 5009, 198, 1324, 62, 3672, 796, 366, 24643, 1, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 16060, 9876, 13, 292, 62, ...
2.586074
517
import autograd.numpy as np from scipy.stats import uniform from autograd import jacobian from numpy import euler_gamma from scipy.special import gamma as gamma_func from scipy.special import ndtri as z from scipy import integrate from scipy.optimize import minimize from surpyval import parametric as para from surpyval import nonparametric as nonp from surpyval.parametric.parametric_fitter import ParametricFitter from .fitters.mpp import mpp ExpoWeibull = ExpoWeibull_('ExpoWeibull')
[ 11748, 1960, 519, 6335, 13, 77, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 34242, 1330, 8187, 198, 6738, 1960, 519, 6335, 1330, 474, 330, 672, 666, 198, 6738, 299, 32152, 1330, 304, 18173, 62, 28483, 2611, 198, 6738, 629, 541, ...
3.055215
163
import pytest from datar import stats from datar.base import * from datar import f from datar.datasets import warpbreaks, state_division, state_region, airquality from .conftest import assert_iterable_equal
[ 11748, 12972, 9288, 198, 198, 6738, 4818, 283, 1330, 9756, 198, 6738, 4818, 283, 13, 8692, 1330, 1635, 198, 6738, 4818, 283, 1330, 277, 198, 6738, 4818, 283, 13, 19608, 292, 1039, 1330, 25825, 30058, 11, 1181, 62, 21426, 11, 1181, 62,...
3.42623
61
from unittest import TestCase from cqlengine.statements import UpdateStatement, WhereClause, AssignmentClause from cqlengine.operators import *
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 269, 13976, 18392, 13, 14269, 3196, 1330, 10133, 48682, 11, 6350, 2601, 682, 11, 50144, 2601, 682, 198, 6738, 269, 13976, 18392, 13, 3575, 2024, 1330, 1635, 628, 198 ]
3.842105
38
# Copyright 2020 Jan Feitsma (Falcons) # SPDX-License-Identifier: Apache-2.0 #!/usr/bin/python import matplotlib.pyplot as plt from matplotlib.patches import Rectangle
[ 2, 15069, 12131, 2365, 5452, 896, 2611, 357, 41129, 5936, 8, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, ...
2.915254
59
from hitori_generator import Generator from argparse import ArgumentParser if __name__ == '__main__': main()
[ 6738, 289, 2072, 72, 62, 8612, 1352, 1330, 35986, 198, 6738, 1822, 29572, 1330, 45751, 46677, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
3.25
36
from lxml import etree from opaflib.filters import defilterData #Logging facility import logging,code logger = logging.getLogger("OPAFXML") #leaf #tree #Factory PDF = PDFXMLFactory() def create_leaf(tag, value, **kwargs): return PDF.create_leaf(tag, value,**kwargs) def create_tree(tag, childs, **kwargs): return PDF.create_tree(tag, *childs, **kwargs) if __name__=="__main__": name = create_leaf('name', "Name") string = create_leaf('string', "Felipe") entry = create_tree('entry',[name,string]) dictionary = create_tree('dictionary',[entry]) stream_data = create_leaf('data',"A"*100) stream = create_tree('stream',[dictionary,stream_data]) indirect = create_tree('indirect_object', [stream], obj=(1,0)) array = create_tree('array', [create_leaf('number', i) for i in range(0,10)]) xml=indirect print etree.tostring(xml), xml.value import code code.interact(local=locals())
[ 6738, 300, 19875, 1330, 2123, 631, 198, 6738, 1034, 1878, 8019, 13, 10379, 1010, 1330, 825, 346, 353, 6601, 198, 2, 11187, 2667, 6841, 198, 11748, 18931, 11, 8189, 220, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7203, 3185, 8...
2.578667
375
import tensorflow as tf # y=ax+b linear model #
[ 11748, 11192, 273, 11125, 355, 48700, 628, 198, 2, 331, 28, 897, 10, 65, 14174, 2746, 628, 198, 2, 220, 198 ]
2.52381
21
from common.make_tx import make_swap_tx from sol.handle_simple import handle_unknown_detect_transfers
[ 6738, 2219, 13, 15883, 62, 17602, 1330, 787, 62, 2032, 499, 62, 17602, 198, 6738, 1540, 13, 28144, 62, 36439, 1330, 5412, 62, 34680, 62, 15255, 478, 62, 7645, 69, 364, 628, 628 ]
3.181818
33
""" Functions for testing independence of several distributions. The functions in this module provide methods for testing if the samples generated from two random vectors are independent. """ import numpy as np import scipy.stats from . import _dcor_internals, _hypothesis from ._dcor import u_distance_correlation_sqr from ._utils import _random_state_init, _transform_to_2d def distance_covariance_test( x, y, *, num_resamples=0, exponent=1, random_state=None, n_jobs=1, ): """ Test of distance covariance independence. Compute the test of independence based on the distance covariance, for two random vectors. The test is a permutation test where the null hypothesis is that the two random vectors are independent. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. exponent: float Exponent of the Euclidean distance, in the range :math:`(0, 2)`. Equivalently, it is twice the Hurst parameter of fractional Brownian motion. num_resamples: int Number of permutations resamples to take in the permutation test. random_state: {None, int, array_like, numpy.random.RandomState} Random state to generate the permutations. Returns ------- HypothesisTest Results of the hypothesis test. See Also -------- distance_covariance Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> dcor.independence.distance_covariance_test(a, a) HypothesisTest(p_value=1.0, statistic=208.0) >>> dcor.independence.distance_covariance_test(a, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=11.75323056...) >>> dcor.independence.distance_covariance_test(b, b) HypothesisTest(p_value=1.0, statistic=1.3604610...) >>> dcor.independence.distance_covariance_test(a, b, ... num_resamples=5, random_state=0) HypothesisTest(p_value=0.5, statistic=11.7532305...) >>> dcor.independence.distance_covariance_test(a, b, ... num_resamples=5, random_state=13) HypothesisTest(p_value=0.3333333..., statistic=11.7532305...) >>> dcor.independence.distance_covariance_test(a, a, ... num_resamples=7, random_state=0) HypothesisTest(p_value=0.125, statistic=208.0) """ x = _transform_to_2d(x) y = _transform_to_2d(y) _dcor_internals._check_same_n_elements(x, y) random_state = _random_state_init(random_state) # Compute U-centered matrices u_x = _dcor_internals._distance_matrix_generic( x, centering=_dcor_internals.double_centered, exponent=exponent) u_y = _dcor_internals._distance_matrix_generic( y, centering=_dcor_internals.double_centered, exponent=exponent) # Use the dcov statistic return _hypothesis._permutation_test_with_sym_matrix( u_x, statistic_function=statistic_function, num_resamples=num_resamples, random_state=random_state, n_jobs=n_jobs) def partial_distance_covariance_test( x, y, z, *, num_resamples=0, exponent=1, random_state=None, n_jobs=1, ): """ Test of partial distance covariance independence. Compute the test of independence based on the partial distance covariance, for two random vectors conditioned on a third. The test is a permutation test where the null hypothesis is that the first two random vectors are independent given the third one. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Observed random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. num_resamples: int Number of permutations resamples to take in the permutation test. random_state: {None, int, array_like, numpy.random.RandomState} Random state to generate the permutations. Returns ------- HypothesisTest Results of the hypothesis test. See Also -------- partial_distance_covariance Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> c = np.array([[1000, 0, 0, 1000], ... [0, 1000, 1000, 1000], ... [1000, 1000, 1000, 1000], ... [1000, 1000, 0, 1000]]) >>> dcor.independence.partial_distance_covariance_test(a, a, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=142.6664416...) >>> dcor.independence.partial_distance_covariance_test(a, b, c) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=7.2690070...e-15) >>> dcor.independence.partial_distance_covariance_test(b, b, c) ... # doctest: +ELLIPSIS HypothesisTest(p_value=1.0, statistic=2.2533380...e-30) >>> dcor.independence.partial_distance_covariance_test(a, b, c, ... num_resamples=5, random_state=0) HypothesisTest(p_value=0.1666666..., statistic=7.2690070...e-15) >>> dcor.independence.partial_distance_covariance_test(a, b, c, ... num_resamples=5, random_state=13) HypothesisTest(p_value=0.1666666..., statistic=7.2690070...e-15) >>> dcor.independence.partial_distance_covariance_test(a, c, b, ... num_resamples=7, random_state=0) HypothesisTest(p_value=1.0, statistic=-7.5701764...e-12) """ random_state = _random_state_init(random_state) # Compute U-centered matrices u_x = _dcor_internals._u_distance_matrix(x, exponent=exponent) u_y = _dcor_internals._u_distance_matrix(y, exponent=exponent) u_z = _dcor_internals._u_distance_matrix(z, exponent=exponent) # Compute projections proj = _dcor_internals.u_complementary_projection(u_z) p_xz = proj(u_x) p_yz = proj(u_y) # Use the pdcor statistic return _hypothesis._permutation_test_with_sym_matrix( p_xz, statistic_function=statistic_function, num_resamples=num_resamples, random_state=random_state, n_jobs=n_jobs) def distance_correlation_t_statistic(x, y): """ Transformation of the bias corrected version of distance correlation used in :func:`distance_correlation_t_test`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar T statistic. See Also -------- distance_correlation_t_test Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_statistic(a, a) inf >>> dcor.independence.distance_correlation_t_statistic(a, b) ... # doctest: +ELLIPSIS -0.4430164... >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_statistic(b, b) inf """ bcdcor = u_distance_correlation_sqr(x, y) n = x.shape[0] v = n * (n - 3) / 2 return np.sqrt(v - 1) * bcdcor / np.sqrt(1 - bcdcor**2) def distance_correlation_t_test(x, y): """ Test of independence for high dimension based on convergence to a Student t distribution. The null hypothesis is that the two random vectors are independent. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- HypothesisTest Results of the hypothesis test. See Also -------- distance_correlation_t_statistic Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1, 0, 0, 1], ... [0, 1, 1, 1], ... [1, 1, 1, 1], ... [1, 1, 0, 1]]) >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_test(a, a) ... # doctest: +ELLIPSIS HypothesisTest(p_value=0.0, statistic=inf) >>> dcor.independence.distance_correlation_t_test(a, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=0.6327451..., statistic=-0.4430164...) >>> with np.errstate(divide='ignore'): ... dcor.independence.distance_correlation_t_test(b, b) ... # doctest: +ELLIPSIS HypothesisTest(p_value=0.0, statistic=inf) """ t_test = distance_correlation_t_statistic(x, y) n = x.shape[0] v = n * (n - 3) / 2 df = v - 1 p_value = 1 - scipy.stats.t.cdf(t_test, df=df) return _hypothesis.HypothesisTest(p_value=p_value, statistic=t_test)
[ 37811, 198, 24629, 2733, 329, 4856, 10404, 286, 1811, 24570, 13, 198, 198, 464, 5499, 287, 428, 8265, 2148, 5050, 329, 4856, 611, 198, 1169, 8405, 7560, 422, 734, 4738, 30104, 389, 4795, 13, 198, 37811, 198, 11748, 299, 32152, 355, 45...
2.301922
4,786
from . import imageview from . import cisview from . import renderer from . import convert
[ 6738, 764, 1330, 2939, 1177, 198, 6738, 764, 1330, 33325, 1177, 198, 6738, 764, 1330, 9851, 11882, 198, 6738, 764, 1330, 10385, 628 ]
4
23
import numpy as np import nibabel as nib import os.path as op import pyglet #pyglet.options['debug_gl'] = True #pyglet.options['debug_x11'] = True #pyglet.options['debug_gl_trace'] = True #pyglet.options['debug_texture'] = True #fos modules from fos.actor.axes import Axes from fos import World, Window, WindowManager from labeler import TrackLabeler from fos.actor.slicer import Slicer #dipy modules from dipy.segment.quickbundles import QuickBundles from dipy.io.dpy import Dpy from dipy.io.pickles import load_pickle,save_pickle from dipy.viz.colormap import orient2rgb import copy if __name__ == '__main__': subject = 5 seeds = 1 qb_dist = 30 #load T1 volume registered in MNI space img = nib.load('data/subj_'+("%02d" % subject)+'/MPRAGE_32/T1_flirt_out.nii.gz') data = img.get_data() affine = img.get_affine() #load the tracks registered in MNI space fdpyw = 'data/subj_'+("%02d" % subject)+'/101_32/DTI/tracks_gqi_'+str(seeds)+'M_linear.dpy' dpr = Dpy(fdpyw, 'r') T = dpr.read_tracks() dpr.close() #load initial QuickBundles with threshold 30mm fpkl = 'data/subj_'+("%02d" % subject)+'/101_32/DTI/qb_gqi_'+str(seeds)+'M_linear_'+str(qb_dist)+'.pkl' #qb=QuickBundles(T,30.,12) qb=load_pickle(fpkl) #create the interaction system for tracks tl = TrackLabeler(qb,qb.downsampled_tracks(),vol_shape=data.shape,tracks_alpha=1) #add a interactive slicing/masking tool sl = Slicer(affine,data) #add one way communication between tl and sl tl.slicer=sl #OpenGL coordinate system axes ax = Axes(100) x,y,z=data.shape #add the actors to the world w=World() w.add(tl) w.add(sl) #w.add(ax) #create a window wi = Window(caption="Interactive Spaghetti using Diffusion Imaging in Python (dipy.org) and Free On Shades (fos.me)",\ bgcolor=(0.3,0.3,0.6,1),width=1200,height=800) #attach the world to the window wi.attach(w) #create a manager which can handle multiple windows wm = WindowManager() wm.add(wi) wm.run() print('Everything is running ;-)')
[ 11748, 299, 32152, 355, 45941, 198, 11748, 33272, 9608, 355, 33272, 198, 11748, 28686, 13, 6978, 355, 1034, 198, 198, 11748, 12972, 70, 1616, 198, 2, 9078, 70, 1616, 13, 25811, 17816, 24442, 62, 4743, 20520, 796, 6407, 198, 2, 9078, 7...
2.281513
952
#coding=utf-8 # import cv2 from keras.models import load_model import numpy as np import chineseText img = cv2.imread("img/gather.png") face_classifier = cv2.CascadeClassifier( "d:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml" ) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_classifier.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=3, minSize=(140, 140)) gender_classifier = load_model( "classifier/gender_models/simple_CNN.81-0.96.hdf5") gender_labels = {0: '', 1: ''} color = (255, 255, 255) for (x, y, w, h) in faces: face = img[(y - 60):(y + h + 60), (x - 30):(x + w + 30)] face = cv2.resize(face, (48, 48)) face = np.expand_dims(face, 0) face = face / 255.0 gender_label_arg = np.argmax(gender_classifier.predict(face)) gender = gender_labels[gender_label_arg] cv2.rectangle(img, (x, y), (x + h, y + w), color, 2) img = chineseText.cv2ImgAddText(img, gender, x + h, y, color, 30) cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
[ 2, 66, 7656, 28, 40477, 12, 23, 198, 2, 198, 198, 11748, 269, 85, 17, 198, 6738, 41927, 292, 13, 27530, 1330, 3440, 62, 19849, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 442, 3762, 8206, 198, 198, 9600, 796, 269, 85, 17, 13, ...
2.286938
467
from django.test import TestCase from os import path from rest_framework import status from rest_framework.test import APIClient import random from scheduler.models import Profile from scheduler.factories import ( CourseFactory, SpacetimeFactory, UserFactory, ProfileFactory, SectionFactory, AttendanceFactory, OverrideFactory, create_attendances_for, ) random.seed(0) COURSE_NAMES = ("CS88", "CS61A", "CS61B", "CS70", "CS61C", "EE16A") ROLE_MAP = Profile.ROLE_MAP BASE_PATH = "/scheduler" # ----- REQUEST UTILITIES ----- # ----- MODEL GENERATION ----- def random_objs(clazz, n=1): """ Generates N instances of the provided class, retrieved from the database. """ src = clazz.objects.all() for _ in range(n): yield random.choice(src) def make_test_courses(): """Creates course objects and persists them to database.""" return [CourseFactory.create(name=name) for name in COURSE_NAMES] def make_test_users(n): """Creates N test users and persists them to database.""" return UserFactory.create_batch(n) def give_role(user, role, course): """ Creates a profile for USER in a given ROLE for the provided COURSE, and saves the profile to database. """ return ProfileFactory.create( user=user, course=course, leader=None, section=None, role=role ) def create_empty_section_for(mentor): """ Creates a section for MENTOR without populated students. """ return SectionFactory.create(course=mentor.course, mentor=mentor) def enroll_user_as_student(user, section): """ Creates a student profile for USER, and assigns them to the given SECTION. Also creates blank attendances as necessary. Returns the created profile. """ student = give_role(user, Profile.STUDENT, section.course) student.section = section student.leader = section.leader create_attendances_for(student) return student def gen_test_data(cls, NUM_USERS=300): """ Adds NUM_USERS users to the database and initializes profiles for them as follows: - 2 coords per course - 4 SMs per coord, each with a section of 3-6 students - 3 JMs per SM, each with a section of 3-6 students """ users = iter(make_test_users(NUM_USERS)) courses = make_test_courses() # for sanity tests, everyone only has one role for now num_courses = len(courses) coords, seniors, juniors, students = [], [], [], [] COORD_COUNT = 2 SM_COUNT = 4 JM_COUNT = 3 try: for c in courses: # coords for i in range(COORD_COUNT): coord = assign(Profile.COORDINATOR, None, c, coords) # SMs for j in range(SM_COUNT): sm = assign(Profile.SENIOR_MENTOR, coord, c, seniors) section = create_empty_section_for(sm) for k in range(random.randint(3, 6)): students.append(enroll_user_as_student(next(users), section)) # JMs for k in range(JM_COUNT): jm = assign(Profile.JUNIOR_MENTOR, sm, c, juniors) for _ in range(random.randint(3, 6)): students.append( enroll_user_as_student(next(users), section) ) except StopIteration: pass cls.users = users cls.courses = courses cls.coords = coords cls.seniors = seniors cls.juniors = juniors cls.students = students
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 28686, 1330, 3108, 198, 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 3486, 2149, 75, 1153, 198, 11748, 4738, 198, 198, 6738, 6038, 18173, 13, ...
2.402307
1,474
import math from fontTools.pens.recordingPen import RecordingPen, replayRecording from fontTools.misc.bezierTools import calcCubicArcLength, splitCubicAtT from coldtype.geometry import Rect, Point __length_cache = {} __split_cache = {}
[ 11748, 10688, 198, 6738, 10369, 33637, 13, 79, 641, 13, 8344, 1284, 25553, 1330, 43905, 25553, 11, 24788, 6690, 1284, 198, 6738, 10369, 33637, 13, 44374, 13, 1350, 89, 959, 33637, 1330, 42302, 43632, 291, 24021, 24539, 11, 6626, 43632, ...
3.434783
69
""" Project for Udacity Danaodgree in Deep Reinforcement Learning This script train an agent to navigate (and collect bananas!) in a large, square world. A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect as many yellow bananas as possible while avoiding blue bananas. The state space has 37 dimensions and contains the agent's velocity, along with ray-based perception of objects around the agent's forward direction. Given this information, the agent has to learn how to best select actions. Four discrete actions are available, corresponding to: 0 - move forward. 1 - move backward. 2 - turn left. 3 - turn right. The task is episodic, and in order to solve the environment, your agent must get an average score of +13 over 100 consecutive episodes. """ from unityagents import UnityEnvironment import numpy as np from collections import deque from dqn_agent import Agent import torch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") """ Unity environment configuration Mac: "path/to/Banana.app" Windows (x86): "path/to/Banana_Windows_x86/Banana.exe" Windows (x86_64): "path/to/Banana_Windows_x86_64/Banana.exe" Linux (x86): "path/to/Banana_Linux/Banana.x86" Linux (x86_64): "path/to/Banana_Linux/Banana.x86_64" Linux (x86, headless): "path/to/Banana_Linux_NoVis/Banana.x86" Linux (x86_64, headless): "path/to/Banana_Linux_NoVis/Banana.x86_64" """ # start Unity environment env = UnityEnvironment(file_name="Banana.app") # get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] env_info = env.reset(train_mode=False)[brain_name] action_size = brain.vector_action_space_size state_size = len(env_info.vector_observations[0]) # initialize agent agent = Agent(state_size=state_size, action_size=action_size, seed=0, device=device) def train(n_episodes=2000, eps_start=1.0, eps_end=0.05, eps_decay=0.99): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes eps_start (float): starting value of epsilon, for epsilon-greedy action selection eps_end (float): minimum value of epsilon eps_decay (float): multiplicative factor (per episode) for decreasing epsilon """ scores = [] # list containing scores from each episode scores_window = deque(maxlen=100) # last 100 scores eps = eps_start # initialize epsilon for i_episode in range(1, n_episodes+1): # reset environment env_info = env.reset(train_mode=True)[brain_name] # get initial state state = env_info.vector_observations[0] # set initial score score = 0 while True: action = agent.act(state, eps) env_info = env.step(action)[brain_name] next_state, reward, done = env_info.vector_observations[0], env_info.rewards[0], env_info.local_done[0] agent.step(state, action, reward, next_state, done) state = next_state score += reward if done: break scores_window.append(score) # save most recent score scores.append(score) # save most recent score eps = max(eps_end, eps_decay*eps) # decrease epsilon print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="") if i_episode % 100 == 0: print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window))) if np.mean(scores_window)>=14: print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window))) torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth') break return scores train()
[ 37811, 198, 16775, 329, 35774, 4355, 22937, 375, 70, 631, 287, 10766, 22299, 13442, 18252, 198, 198, 1212, 4226, 4512, 281, 5797, 284, 16500, 357, 392, 2824, 35484, 8133, 287, 257, 1588, 11, 6616, 995, 13, 198, 198, 32, 6721, 286, 134...
2.587228
1,519
# Warsaw University of Technology from layers.eca_block import ECABasicBlock from models.minkgl import MinkHead, MinkTrunk, MinkGL from models.minkloc import MinkLoc from third_party.minkloc3d.minkloc import MinkLoc3D from misc.utils import ModelParams
[ 2, 32955, 2059, 286, 8987, 198, 198, 6738, 11685, 13, 31047, 62, 9967, 1330, 13182, 6242, 292, 291, 12235, 198, 6738, 4981, 13, 76, 676, 4743, 1330, 337, 676, 13847, 11, 337, 676, 2898, 2954, 11, 337, 676, 8763, 628, 198, 6738, 4981...
3.134146
82
import sys import ctypes from Phidget22.PhidgetSupport import PhidgetSupport from Phidget22.Async import * from Phidget22.ChannelClass import ChannelClass from Phidget22.ChannelSubclass import ChannelSubclass from Phidget22.DeviceClass import DeviceClass from Phidget22.DeviceID import DeviceID from Phidget22.ErrorEventCode import ErrorEventCode from Phidget22.PhidgetException import PhidgetException ANY_SERIAL_NUMBER = -1 ANY_HUB_PORT = -1 ANY_CHANNEL = -1 ANY_LABEL = None INFINITE_TIMEOUT = 0 DEFAULT_TIMEOUT = 1000
[ 11748, 25064, 198, 11748, 269, 19199, 198, 6738, 1380, 17484, 1828, 13, 2725, 17484, 15514, 1330, 1380, 17484, 15514, 198, 6738, 1380, 17484, 1828, 13, 42367, 1330, 1635, 198, 6738, 1380, 17484, 1828, 13, 29239, 9487, 1330, 11102, 9487, 1...
3.255952
168
# coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from contextlib import contextmanager import celery import pytest from celery.signals import setup_logging import scout_apm.celery from scout_apm.api import Config # http://docs.celeryproject.org/en/latest/userguide/testing.html#py-test skip_unless_celery_4_plus = pytest.mark.skipif( celery.VERSION < (4, 0), reason="pytest fixtures added in Celery 4.0" ) def test_hello_eager(tracked_requests): with app_with_scout() as app: result = app.tasks["tests.integration.test_celery.hello"].apply() assert result.result == "Hello World!" assert len(tracked_requests) == 1 tracked_request = tracked_requests[0] assert "task_id" in tracked_request.tags assert tracked_request.tags["is_eager"] is True assert tracked_request.tags["exchange"] == "unknown" assert tracked_request.tags["routing_key"] == "unknown" assert tracked_request.tags["queue"] == "unknown" assert tracked_request.active_spans == [] assert len(tracked_request.complete_spans) == 1 span = tracked_request.complete_spans[0] assert span.operation == "Job/tests.integration.test_celery.hello" def test_no_monitor(tracked_requests): # With an empty config, "monitor" defaults to False. with app_with_scout(config={}) as app: result = app.tasks["tests.integration.test_celery.hello"].apply() assert result.result == "Hello World!" assert tracked_requests == []
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 198, 11748, 18725, 1924, 198, 11748, ...
2.873106
528
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 11748, 4818, 8079, 198, 6738, 5366, 13, 9945, 1330, 20613, 198, 6738, 5366, 13, 85, 17, 1330, 10011, 2611, 44, 4254, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198 ]
3.263158
38
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs __all__ = [ 'GetSubscriptionResult', 'AwaitableGetSubscriptionResult', 'get_subscription', ] def get_subscription(namespace_name: Optional[str] = None, resource_group_name: Optional[str] = None, subscription_name: Optional[str] = None, topic_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSubscriptionResult: """ Description of subscription resource. :param str namespace_name: The namespace name :param str resource_group_name: Name of the Resource group within the Azure subscription. :param str subscription_name: The subscription name. :param str topic_name: The topic name. """ __args__ = dict() __args__['namespaceName'] = namespace_name __args__['resourceGroupName'] = resource_group_name __args__['subscriptionName'] = subscription_name __args__['topicName'] = topic_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:servicebus/v20210601preview:getSubscription', __args__, opts=opts, typ=GetSubscriptionResult).value return AwaitableGetSubscriptionResult( accessed_at=__ret__.accessed_at, auto_delete_on_idle=__ret__.auto_delete_on_idle, client_affine_properties=__ret__.client_affine_properties, count_details=__ret__.count_details, created_at=__ret__.created_at, dead_lettering_on_filter_evaluation_exceptions=__ret__.dead_lettering_on_filter_evaluation_exceptions, dead_lettering_on_message_expiration=__ret__.dead_lettering_on_message_expiration, default_message_time_to_live=__ret__.default_message_time_to_live, duplicate_detection_history_time_window=__ret__.duplicate_detection_history_time_window, enable_batched_operations=__ret__.enable_batched_operations, forward_dead_lettered_messages_to=__ret__.forward_dead_lettered_messages_to, forward_to=__ret__.forward_to, id=__ret__.id, is_client_affine=__ret__.is_client_affine, lock_duration=__ret__.lock_duration, max_delivery_count=__ret__.max_delivery_count, message_count=__ret__.message_count, name=__ret__.name, requires_session=__ret__.requires_session, status=__ret__.status, system_data=__ret__.system_data, type=__ret__.type, updated_at=__ret__.updated_at)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.527098
1,144
#=========================================================================== # # Crystalfontz Raspberry-Pi Python example library for FTDI / BridgeTek # EVE graphic accelerators. # #--------------------------------------------------------------------------- # # This file is part of the port/adaptation of existing C based EVE libraries # to Python for Crystalfontz EVE based displays. # # 2021-10-20 Mark Williams / Crystalfontz America Inc. # https:#www.crystalfontz.com/products/eve-accelerated-tft-displays.php #--------------------------------------------------------------------------- # # This is free and unencumbered software released into the public domain. # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # For more information, please refer to <http:#unlicense.org/> # #============================================================================ #EVE Device Type EVE_DEVICE = 811 # EVE Clock Speed EVE_CLOCK_SPEED = 60000000 # Touch TOUCH_RESISTIVE = False TOUCH_CAPACITIVE = False TOUCH_GOODIX_CAPACITIVE = False # Define RGB output pins order, determined by PCB layout LCD_SWIZZLE = 2 # Define active edge of PCLK. Observed by scope: # 0: Data is put out coincident with falling edge of the clock. # Rising edge of the clock is in the middle of the data. # 1: Data is put out coincident with rising edge of the clock. # Falling edge of the clock is in the middle of the data. LCD_PCLKPOL = 0 # LCD drive strength: 0=5mA, 1=10mA LCD_DRIVE_10MA = 0 # Spread Spectrum on RGB signals. Probably not a good idea at higher # PCLK frequencies. LCD_PCLK_CSPREAD = 0 #This is not a 24-bit display, so dither LCD_DITHER = 0 # Pixel clock divisor LCD_PCLK = 5 #---------------------------------------------------------------------------- # Frame_Rate = 60Hz / 16.7mS #---------------------------------------------------------------------------- # Horizontal timing # Target 60Hz frame rate, using the largest possible line time in order to # maximize the time that the EVE has to process each line. HPX = 240 # Horizontal Pixel Width HSW = 10 # Horizontal Sync Width HBP = 20 # Horizontal Back Porch HFP = 10 # Horizontal Front Porch HPP = 209 # Horizontal Pixel Padding # FTDI needs at least 1 here # Define the constants needed by the EVE based on the timing # Active width of LCD display LCD_WIDTH = HPX # Start of horizontal sync pulse LCD_HSYNC0 = HFP # End of horizontal sync pulse LCD_HSYNC1 = HFP+HSW # Start of active line LCD_HOFFSET = HFP+HSW+HBP # Total number of clocks per line LCD_HCYCLE = HPX+HFP+HSW+HBP+HPP #---------------------------------------------------------------------------- # Vertical timing VLH = 400 # Vertical Line Height VS = 2 # Vertical Sync (in lines) VBP = 2 # Vertical Back Porch VFP = 4 # Vertical Front Porch VLP = 1 # Vertical Line Padding # FTDI needs at least 1 here # Define the constants needed by the EVE based on the timing # Active height of LCD display LCD_HEIGHT = VLH # Start of vertical sync pulse LCD_VSYNC0 = VFP # End of vertical sync pulse LCD_VSYNC1 = VFP+VS # Start of active screen LCD_VOFFSET = VFP+VS+VBP # Total number of lines per screen LCD_VCYCLE = VLH+VFP+VS+VBP+VLP
[ 2, 23926, 2559, 18604, 201, 198, 2, 201, 198, 2, 8152, 301, 1604, 756, 89, 24244, 12, 38729, 11361, 1672, 5888, 329, 19446, 17931, 1220, 10290, 51, 988, 201, 198, 2, 32356, 13028, 8320, 2024, 13, 201, 198, 2, 201, 198, 2, 10097, 3...
3.295368
1,317
import itertools import signal from copy import deepcopy from typing import Union, Callable import numpy as np import quapy as qp from quapy.data.base import LabelledCollection from quapy.evaluation import artificial_prevalence_prediction, natural_prevalence_prediction, gen_prevalence_prediction from quapy.method.aggregative import BaseQuantifier import inspect from util import _check_sample_size
[ 11748, 340, 861, 10141, 198, 11748, 6737, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 19720, 1330, 4479, 11, 4889, 540, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 627, 12826, 355, 10662, 79, 198, 6738, 627, 12826, 13, ...
3.63964
111
# -*- coding: utf-8 -*- import os from flask_migrate import Migrate from app import create_app, db from app.models import User, Role, PoseToLocation app = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(app, db) # migrate #
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 6738, 42903, 62, 76, 42175, 1330, 337, 42175, 198, 6738, 598, 1330, 2251, 62, 1324, 11, 20613, 198, 6738, 598, 13, 27530, 1330, 11787, 11, 20934,...
2.694737
95
INPUT_FILE = "../../input/09.txt" Point = tuple[int, int] Heightmap = dict[Point, int] Basin = set[Point] def parse_input() -> Heightmap: """ Parses the input and returns a Heightmap """ with open(INPUT_FILE) as f: heights = [[int(x) for x in line.strip()] for line in f] heightmap: Heightmap = dict() for (y, row) in enumerate(heights): for (x, height) in enumerate(row): heightmap[(x, y)] = height return heightmap def get_surrounding_points(heightmap: Heightmap, point: Point) -> set[Point]: """ Returns a set of surrounding points within the heightmap """ x, y = point return { (x - 1, y), (x, y - 1), (x, y + 1), (x + 1, y), } & heightmap.keys() def get_surrounding_heights(heightmap: Heightmap, point: Point) -> set[int]: """ Returns the heights of points surrounding the given point """ surrounding_points = get_surrounding_points(heightmap, point) return {heightmap[point] for point in surrounding_points} def get_low_points(heightmap: Heightmap) -> set[Point]: """ Finds the low points on the heightmap """ low_points: set[Point] = set() for point in heightmap: surrounding_heights = get_surrounding_heights(heightmap, point) if all(heightmap[point] < height for height in surrounding_heights): low_points.add(point) return low_points def solve_part1(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the sum of the risk levels of all low points """ return sum(1 + heightmap[point] for point in low_points) def get_basins(heightmap: Heightmap, low_points: set[Point]) -> list[Basin]: """ Finds all basins on the heightmap """ basins: list[Basin] = [] for low_point in low_points: basin: Basin = set() points_to_consider = {low_point} while points_to_consider: point = points_to_consider.pop() if heightmap[point] == 9: continue surrounding_points = get_surrounding_points(heightmap, point) points_to_consider.update(surrounding_points - basin) basin.add(point) basins.append(basin) return basins def solve_part2(heightmap: Heightmap, low_points: set[Point]) -> int: """ Calculates the product of the sizes of the three largest basins """ basins = get_basins(heightmap, low_points) basin_sizes = sorted((len(basin) for basin in basins), reverse=True) return basin_sizes[0] * basin_sizes[1] * basin_sizes[2] if __name__ == "__main__": heightmap = parse_input() low_points = get_low_points(heightmap) part1 = solve_part1(heightmap, low_points) part2 = solve_part2(heightmap, low_points) print(part1) print(part2)
[ 1268, 30076, 62, 25664, 796, 366, 40720, 40720, 15414, 14, 2931, 13, 14116, 1, 198, 198, 12727, 796, 46545, 58, 600, 11, 493, 60, 198, 23106, 8899, 796, 8633, 58, 12727, 11, 493, 60, 198, 15522, 259, 796, 900, 58, 12727, 60, 628, ...
2.472585
1,149
#!/usr/bin/env python3 import signal import logging import sys from gi.repository import GObject GObject.threads_init() import time from lib.args import Args from lib.loghandler import LogHandler import lib.connection as Connection if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 6737, 198, 11748, 18931, 198, 11748, 25064, 628, 198, 198, 6738, 308, 72, 13, 260, 1930, 37765, 1330, 402, 10267, 198, 198, 38, 10267, 13, 16663, 82, 62, 15003, 3419, ...
3.054945
91
import warnings from typing import Any, Callable, Optional, Tuple from tensorboard.backend.event_processing import event_accumulator from torch.utils.tensorboard import SummaryWriter from tianshou.utils.logger.base import LOG_DATA_TYPE, BaseLogger
[ 11748, 14601, 198, 6738, 19720, 1330, 4377, 11, 4889, 540, 11, 32233, 11, 309, 29291, 198, 198, 6738, 11192, 273, 3526, 13, 1891, 437, 13, 15596, 62, 36948, 1330, 1785, 62, 4134, 388, 8927, 198, 6738, 28034, 13, 26791, 13, 83, 22854, ...
3.549296
71
# Jetfuel Game Engine- A SDL-based 2D game-engine # Copyright (C) 2018 InfernoStudios # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ctypes import c_uint from ctypes import c_int from ctypes import c_void_p from ctypes import c_bool from ctypes import c_wchar_p from jetfuel.draw.rectangleinterface import rectangle_interface from jetfuel.draw.image import image
[ 2, 220, 220, 220, 220, 19013, 25802, 3776, 7117, 12, 317, 45417, 12, 3106, 362, 35, 983, 12, 18392, 198, 2, 220, 220, 220, 220, 15069, 357, 34, 8, 2864, 32458, 13007, 4267, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628,...
3.52
250
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # python3 """Train seq-to-seq model on random supervised training tasks.""" # pytype: disable=wrong-arg-count # pytype: disable=attribute-error import collections import functools import json import os import random import sys import time from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import linen as nn from flax import optim from flax.metrics import tensorboard from flax.training import checkpoints from flax.training import common_utils import jax import jax.numpy as jnp import numpy as np import tensorflow.compat.v2 as tf from latent_programmer import decode from latent_programmer import models as base_models from latent_programmer.decomposition_transformer_attention import decomposition_models as models from latent_programmer.decomposition_transformer_attention import input_pipeline from latent_programmer.tasks.robust_fill import dsl from latent_programmer.tasks.robust_fill import tokens as dsl_tokens sys.path.append('../../') gfile = tf.io.gfile FLAGS = flags.FLAGS flags.DEFINE_integer('seed', 0, 'Fixed random seed for training.') flags.DEFINE_float('lr', 1e-3, 'Learning rate.') flags.DEFINE_float('weight_decay', 1e-1, 'Decay factor for AdamW-style weight decay.') flags.DEFINE_integer('embedding_dim', 256, 'Embedding dimension.') flags.DEFINE_integer('hidden_dim', 512, 'Hidden dimension.') flags.DEFINE_integer('num_heads', 4, 'Number of layers.') flags.DEFINE_integer('num_layers', 3, 'Number of Transformer heads.') flags.DEFINE_boolean('slow_decode', True, 'Use slow decoding for prediction?') flags.DEFINE_string('dataset_filepattern', None, 'Filepattern for TFRecord dataset.') flags.DEFINE_integer('per_device_batch_size', 16, 'Number of program tasks in a batch.') flags.DEFINE_integer('num_strings_per_task', 4, 'Number of input/output strings per task.') flags.DEFINE_integer('max_program_length', 100, 'Maximum number of tokens in program.') flags.DEFINE_integer('max_characters', 120, 'Maximum number of characters in input/output strings.') flags.DEFINE_string('save_dir', None, 'Directory to save results to.') flags.DEFINE_integer('num_train_steps', 2000000, 'Number of training steps.') flags.DEFINE_integer('num_eval_steps', 10, 'Number of evaluation steps.') flags.DEFINE_integer('log_freq', 1000, 'Number of steps between training logs.') flags.DEFINE_integer('eval_freq', 2000, 'Number of steps between eval.') flags.DEFINE_integer('predict_freq', 50000, 'Number of steps between prediction (beam search).') flags.DEFINE_integer('checkpoint_freq', 50000, 'Number of steps between checkpoint saves.') flags.DEFINE_integer('finetune_start_step', -1, 'Step the initial checkpoint should start at for ' 'finetuning, or -1 if not finetuning.') flags.DEFINE_bool('restore_checkpoints', True, 'Whether to restore from existing model checkpoints.') flags.DEFINE_string('attention_mask_type', 'bos_full_attention', 'The kind of attention mask to use. Options are: baseline, ' 'bos_to_bos, bos_full_attention') flags.DEFINE_bool('use_relative_attention', True, 'Whether to use relative positonal embeddings.') flags.DEFINE_bool('bos_special_attention', False, 'Whether to use special relative attention computation for ' 'BOS tokens.') _internal = False if not _internal: flags.DEFINE_string('xm_parameters', None, 'String specifying hyperparamter search.') def create_learning_rate_scheduler( base_learning_rate=0.5, factors='constant * linear_warmup * rsqrt_normalized_decay', warmup_steps=16000, decay_factor=0.5, steps_per_decay=50000, steps_per_cycle=100000): """Creates learning rate schedule. Interprets factors in the factors string which can consist of: * constant: interpreted as the constant value, * linear_warmup: interpreted as linear warmup until warmup_steps, * rsqrt_decay: divide by square root of max(step, warmup_steps) * decay_every: Every k steps decay the learning rate by decay_factor. * cosine_decay: Cyclic cosine decay, uses steps_per_cycle parameter. Args: base_learning_rate: float, the starting constant for the lr schedule. factors: a string with factors separated by '*' that defines the schedule. warmup_steps: how many steps to warm up for in the warmup schedule. decay_factor: The amount to decay the learning rate by. steps_per_decay: How often to decay the learning rate. steps_per_cycle: Steps per cycle when using cosine decay. Returns: A function learning_rate(step): float -> {'learning_rate': float}, the step-dependent lr. """ factors = [n.strip() for n in factors.split('*')] def step_fn(step): """Step to learning rate function.""" ret = 1.0 for name in factors: if name == 'constant': ret *= base_learning_rate elif name == 'linear_warmup': ret *= jnp.minimum(1.0, step / warmup_steps) elif name == 'rsqrt_decay': ret /= jnp.sqrt(jnp.maximum(1.0, step - warmup_steps)) elif name == 'rsqrt_normalized_decay': ret *= jnp.sqrt(warmup_steps) ret /= jnp.sqrt(jnp.maximum(step, warmup_steps)) elif name == 'decay_every': ret *= (decay_factor**(step // steps_per_decay)) elif name == 'cosine_decay': progress = jnp.maximum(0.0, (step - warmup_steps) / float(steps_per_cycle)) ret *= jnp.maximum(0.0, 0.5 * (1.0 + jnp.cos(jnp.pi * (progress % 1.0)))) else: raise ValueError('Unknown factor %s.' % name) return jnp.asarray(ret, dtype=jnp.float32) return step_fn def compute_weighted_cross_entropy(logits, targets, weights=None): """Compute weighted cross entropy and entropy for log probs and targets. Args: logits: `[batch, length, num_classes]` float array. targets: categorical targets `[batch, length]` int array. weights: None or array of shape [batch, length, 1] Returns: Tuple of scalar loss and batch normalizing factor. """ if logits.ndim != targets.ndim + 1: raise ValueError('Incorrect shapes. Got shape %s logits and %s targets' % (str(logits.shape), str(targets.shape))) onehot_targets = common_utils.onehot(targets, logits.shape[-1]) loss = -jnp.sum(onehot_targets * nn.log_softmax(logits), axis=-1) normalizing_factor = jnp.prod(jnp.asarray(targets.shape)) if weights is not None: loss = loss * weights normalizing_factor = weights.sum() return loss.sum(), normalizing_factor def compute_weighted_accuracy(logits, targets, weights=None): """Compute weighted accuracy for log probs and targets. Args: logits: `[batch, length, num_classes]` float array. targets: categorical targets `[batch, length]` int array. weights: None or array of shape [batch, length, 1] Returns: Tuple of scalar accuracy and batch normalizing factor. """ if logits.ndim != targets.ndim + 1: raise ValueError('Incorrect shapes. Got shape %s logits and %s targets' % (str(logits.shape), str(targets.shape))) acc = jnp.equal(jnp.argmax(logits, axis=-1), targets) normalizing_factor = jnp.prod(jnp.asarray(targets.shape)) if weights is not None: acc = acc * weights normalizing_factor = weights.sum() return acc.sum(), normalizing_factor def compute_metrics(logits, targets, weights): """Compute summary metrics.""" loss, weight_sum = compute_weighted_cross_entropy(logits, targets, weights) acc, _ = compute_weighted_accuracy(logits, targets, weights) metrics = { 'loss': loss, 'accuracy': acc, 'denominator': weight_sum, } metrics = jax.lax.psum(metrics, 'batch') return metrics # Train / eval / decode step functions. # ----------------------------------------------------------------------------- def train_step(optimizer, inputs, outputs, programs, learning_rate_fn, config, dropout_rng): """Train on batch of program tasks.""" # We handle PRNG splitting inside the top pmap, rather # than handling it outside in the training loop - doing the # latter can add some stalls to the devices. dropout_rng, new_dropout_rng = jax.random.split(dropout_rng) weights = jnp.where(programs > 0, 1, 0).astype(jnp.float32) def loss_fn(params): """Loss function used for training.""" logits = models.DecomposeAttentionTransformer(config).apply( {'params': params}, inputs, outputs, programs, rngs={'dropout': dropout_rng}) loss, weight_sum = compute_weighted_cross_entropy(logits, programs, weights) mean_loss = loss / weight_sum return mean_loss, logits step = optimizer.state.step lr = learning_rate_fn(step) grad_fn = jax.value_and_grad(loss_fn, has_aux=True) (_, logits), grad = grad_fn(optimizer.target) grad = jax.lax.pmean(grad, 'batch') new_optimizer = optimizer.apply_gradient(grad, learning_rate=lr) # Get metrics. metrics = compute_metrics(logits, programs, weights) metrics['learning_rate'] = lr return new_optimizer, metrics, new_dropout_rng def eval_step(params, inputs, outputs, programs, eos_token, config): """Collect metrics for evaluation during training.""" weights = jnp.where( jnp.logical_and(programs > 0, jnp.logical_and(programs != config.base_config.bos_token, programs != eos_token)), 1, 0).astype(jnp.float32) logits = models.DecomposeAttentionTransformer(config).apply( {'params': params}, inputs, outputs, programs) return compute_metrics(logits, programs, weights) def initialize_cache(inputs, outputs, programs, max_decode_len, config): """Initialize a cache for a given input shape and max decode length.""" target_shape = (programs.shape[0], max_decode_len) dtype = config.base_config.dtype initial_variables = models.DecomposeAttentionTransformer(config).init( jax.random.PRNGKey(0), jnp.ones(inputs.shape, dtype), jnp.ones(outputs.shape, dtype), jnp.ones(target_shape, dtype)) return initial_variables['cache'] def predict_step(params, inputs, outputs, cache, beam_size, eos_token, max_decode_len, config, slow_decode=True): """Predict translation with fast decoding beam search on a batch.""" # Prepare transformer fast-decoder call for beam search: for beam search, we # need to set up our decoder model to handle a batch size equal to # batch_size * beam_size, where each batch item's data is expanded in-place # rather than tiled. flat_encoded = decode.flat_batch_beam_expand( models.DecomposeAttentionTransformer(config).apply( {'params': params}, inputs, outputs, method=models.DecomposeAttentionTransformer.encode), beam_size) encoded_padding_mask = jnp.where(outputs > 0, 1, 0).astype(jnp.float32) flat_encoded_padding_mask = decode.flat_batch_beam_expand( encoded_padding_mask, beam_size) if slow_decode: def tokens_ids_to_logits(flat_ids): """Token slice to logits from decoder model.""" # --> [batch * beam, 1, vocab] flat_logits = models.DecomposeAttentionTransformer(config=config).apply( {'params': params}, flat_ids, flat_encoded, flat_encoded_padding_mask, method=models.DecomposeAttentionTransformer.decode) return flat_logits else: def tokens_ids_to_logits(flat_ids, flat_cache): """Token slice to logits from decoder model.""" # --> [batch * beam, 1, vocab] flat_logits, new_vars = models.DecomposeAttentionTransformer( config=config).apply( {'params': params, 'cache': flat_cache}, flat_ids, flat_encoded, flat_encoded_padding_mask, mutable=['cache'], method=models.DecomposeAttentionTransformer.decode) new_flat_cache = new_vars['cache'] # Remove singleton sequence-length dimension: # [batch * beam, 1, vocab] --> [batch * beam, vocab] flat_logits = flat_logits.squeeze(axis=1) return flat_logits, new_flat_cache # Using the above-defined single-step decoder function, run a # beam search over possible sequences given input encoding. beam_seqs, _ = decode.beam_search( inputs, cache, tokens_ids_to_logits, beam_size=beam_size, alpha=0.6, bos_token=config.base_config.bos_token, eos_token=eos_token, max_decode_len=max_decode_len, slow_decode=slow_decode) # Beam search returns [n_batch, n_beam, n_length] with beam dimension # sorted in increasing order of log-probability. return beam_seqs # Util functions for prediction # ----------------------------------------------------------------------------- def pad_examples(x, desired_batch_size): """Expand batch to desired size by repeating last slice.""" batch_pad = desired_batch_size - x.shape[0] tile_dims = [1] * len(x.shape) tile_dims[0] = batch_pad return np.concatenate([x, np.tile(x[-1], tile_dims)], axis=0) def tohost(x): """Collect batches from all devices to host and flatten batch dimensions.""" n_device, n_batch, *remaining_dims = x.shape return x.reshape((n_device * n_batch,) + tuple(remaining_dims)) def per_host_sum_pmap(in_tree): """Execute psum on in_tree's leaves over one device per host.""" host2devices = collections.defaultdict(list) for d in jax.devices(): host2devices[d.host_id].append(d) devices = [host2devices[k][0] for k in host2devices] host_psum = jax.pmap(lambda x: jax.lax.psum(x, 'i'), 'i', devices=devices) return post_pmap(host_psum(pre_pmap(in_tree))) def eval_predicted(predicted, inputs, outputs, parse_beam_fn): """Evaluate predicted program beams.""" best_p, best_score = None, -1 # predicted shape [beam_size, length] for beam in predicted[::-1]: try: p = parse_beam_fn(beam) p_outs = [p(inp) for inp in inputs] score = np.sum([p_out == out for p_out, out in zip(p_outs, outputs)]) if score > best_score: best_p, best_score = p, score except: # pylint: disable=bare-except pass if best_score >= len(inputs): # Found solution. break return best_p, best_score if __name__ == '__main__': app.run(main)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 33448, 383, 3012, 4992, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, ...
2.607034
5,914
import matplotlib.pyplot as plt import numpy as np import pandas as pd import click import numba # def get_value_func(x_mesh, y_mesh, z_mesh, value_mesh): # value_func = RegularGridInterpolator( # (x_mesh, y_mesh, z_mesh), value_mesh, method="nearest") # return value_func def generate_vertical_profile_grids(lon_list, lat_list, dep_list, hnpts, vnpts): lons = np.linspace(lon_list[0], lon_list[1], hnpts) lats = np.linspace(lat_list[0], lat_list[1], hnpts) deps = np.linspace(dep_list[0], dep_list[1], vnpts) return lons, lats, deps if __name__ == "__main__": main()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 3904, 198, 11748, 997, 7012, 628, 628, 628, 198, 198, 2, 825, 651, 62, 8367, 62, 20786, 7...
2.187943
282
from flask import Flask from flask_appconfig import HerokuConfig
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 1324, 11250, 1330, 2332, 11601, 16934, 628, 198 ]
4.1875
16
import logging """ Formatter """ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d:%H:%M:%S') """ Set Flask logger """ logger = logging.getLogger('FLASK_LOG') logger.setLevel(logging.DEBUG) stream_log = logging.StreamHandler() stream_log.setFormatter(formatter) logger.addHandler(stream_log) # if disabled # logger.disabled = True
[ 11748, 18931, 198, 198, 37811, 198, 220, 220, 220, 5178, 1436, 198, 37811, 198, 687, 1436, 796, 18931, 13, 8479, 1436, 10786, 4, 7, 292, 310, 524, 8, 82, 532, 4064, 7, 3672, 8, 82, 532, 4064, 7, 5715, 3672, 8, 82, 532, 4064, 7, ...
2.522293
157
#!/usr/bin/python3 import os import sys import socket CURRENT_DIR = os.path.dirname(__file__) NEWSBLUR_DIR = ''.join([CURRENT_DIR, '/../../']) sys.path.insert(0, NEWSBLUR_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'newsblur_web.settings' import threading import time import boto3 from django.conf import settings BACKUP_DIR = '/srv/newsblur/backup/' s3 = boto3.client('s3', aws_access_key_id=settings.S3_ACCESS_KEY, aws_secret_access_key=settings.S3_SECRET) hostname = socket.gethostname().replace('-','_') s3_object_name = f'backup_{hostname}/backup_{hostname}_{time.strftime("%Y-%m-%d-%H-%M")}.sql' path = os.listdir(BACKUP_DIR)[0] full_path = os.path.join(BACKUP_DIR, path) print('Uploading %s to %s on S3 bucket %s' % (full_path, s3_object_name, settings.S3_BACKUP_BUCKET)) s3.upload_file(full_path, settings.S3_BACKUP_BUCKET, s3_object_name, Callback=ProgressPercentage(full_path)) os.remove(full_path)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 17802, 198, 34, 39237, 62, 34720, 220, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 8, 198, 49597, 9148, 4261, 62, 34720, 796, ...
2.404199
381
#!/usr/bin/python # # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # # pylint: disable=missing-docstring # pylint: disable=duplicate-code import logging import time import onap_tests.components.aai as aai import onap_tests.components.so as so import onap_tests.components.sdnc as sdnc import onap_tests.components.nbi as nbi import onap_tests.utils.stack_checker as sc import onap_tests.utils.utils as onap_utils PROXY = onap_utils.get_config("general.proxy")
[ 2, 48443, 14629, 14, 8800, 14, 29412, 201, 198, 2, 201, 198, 2, 770, 1430, 290, 262, 19249, 5696, 201, 198, 2, 389, 925, 1695, 739, 262, 2846, 286, 262, 24843, 13789, 11, 10628, 362, 13, 15, 201, 198, 2, 543, 48159, 428, 6082, 1...
2.865801
231
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "ricardojvr@gmail.com" __status__ = "Development" from __init__ import * import random, time from PyQt4 import QtCore ################################################################################################################## ################################################################################################################## ################################################################################################################## #Execute the application if __name__ == "__main__": pyforms.start_app( SimpleExample )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 220, 220, 220, 220, 220, 796, 366, 49, 291, 13109, 23133, 68, 7058, 1, 198, 834, 66, 20696, 834, 220,...
3.720379
211
from typing import Tuple import numpy as np import rasterio.warp from opensfm import features from .orthophoto_manager import OrthoPhotoManager from .view import View
[ 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 374, 1603, 952, 13, 86, 5117, 198, 6738, 9808, 38353, 1330, 3033, 198, 198, 6738, 764, 1506, 2522, 2069, 62, 37153, 1330, 47664, 78, 6191, 13511, 198, ...
3.617021
47
# Copyright 2015 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib.services.compute import security_group_default_rules_client from tempest.tests.lib import fake_auth_provider from tempest.tests.lib.services import base
[ 2, 15069, 1853, 41804, 10501, 13, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393...
3.471861
231
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.leveleditor.worldData.interior_spanish_npc_b from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Objects': {'1153420207.67dzlu01': {'Type': 'Building Interior', 'Name': '', 'Instanced': True, 'Objects': {'1165347933.66kmuller': {'Type': 'Log_Stack', 'DisableCollision': True, 'Hpr': VBase3(139.803, 0.0, 0.0), 'Pos': Point3(2.978, 25.796, 0.048), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Log_stack_a'}}, '1166138034.99kmuller': {'Type': 'Log_Stack', 'DisableCollision': True, 'Hpr': VBase3(179.29, 0.0, 0.0), 'Pos': Point3(9.307, 24.592, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Log_stack_b'}}, '1166138092.34kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(-90.005, 0.0, 0.0), 'Pos': Point3(18.672, 15.355, 0.009), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/cabinet_spanish_low'}}, '1166138151.37kmuller': {'Type': 'Pots', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(18.938, 13.997, 2.735), 'Scale': VBase3(1.464, 1.464, 1.464), 'Visual': {'Model': 'models/props/pot_A'}}, '1166138161.79kmuller': {'Type': 'Pots', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(18.511, 15.482, 3.364), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pot_B'}}, '1166138390.93kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.303, 0.276, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Color': (0.75, 0.9300000071525574, 1.0, 1.0), 'Model': 'models/props/table_bar_round'}}, '1166138443.79kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(-134.164, 0.0, 0.0), 'Pos': Point3(4.61, -3.84, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bank'}}, '1166138454.85kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(54.358, 0.0, 0.0), 'Pos': Point3(-6.565, 0.327, 0.038), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bar'}}, '1166138510.96kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(162.38, 0.0, 0.0), 'Pos': Point3(-3.36, -6.982, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bank'}}, '1166138524.92kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(80.452, 0.0, 0.0), 'Pos': Point3(5.079, 5.725, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bar'}}, '1166138537.42kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(25.255, 0.0, 0.0), 'Pos': Point3(-1.381, 6.177, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chair_bank'}}, '1166138621.31kmuller': {'Type': 'Jugs_and_Jars', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(0.672, -2.129, 3.008), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bottle_green'}}, '1166138646.6kmuller': {'Type': 'Jugs_and_Jars', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.184, 1.377, 3.061), 'Scale': VBase3(1.429, 1.429, 1.429), 'Visual': {'Model': 'models/props/waterpitcher'}}, '1166138674.59kmuller': {'Type': 'Baskets', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(1.112, 0.235, 2.971), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/basket'}}, '1166138708.48kmuller': {'Type': 'Food', 'DisableCollision': False, 'Holiday': '', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(19.066, 23.998, 3.071), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/sausage'}}, '1166138742.6kmuller': {'Type': 'Food', 'DisableCollision': False, 'Hpr': VBase3(0.0, -4.607, 0.0), 'Pos': Point3(12.569, 24.56, 2.688), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/garlicString'}}, '1166138817.45kmuller': {'Type': 'Bucket', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(17.053, 10.72, 0.006), 'Scale': VBase3(0.665, 0.665, 0.665), 'Visual': {'Model': 'models/props/washtub'}}, '1166138973.9kmuller': {'Type': 'Tools', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(18.741, 7.367, 0.02), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/butter_churn'}}, '1166139009.4kmuller': {'Type': 'Tools', 'DisableCollision': False, 'Hpr': VBase3(-2.549, 12.708, -168.558), 'Pos': Point3(-7.195, -29.635, 4.369), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.5, 0.5, 0.5, 1.0), 'Model': 'models/props/broom'}}, '1166139125.65kmuller': {'Type': 'Furniture - Fancy', 'DisableCollision': True, 'Hpr': VBase3(179.014, 0.0, 0.0), 'Pos': Point3(-16.599, -28.46, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/cabinet_fancy_tall'}}, '1166139259.49kmuller': {'Type': 'Mortar_Pestle', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(19.246, 16.431, 3.391), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/mortar_pestle_stone'}}, '1166139339.62kmuller': {'Type': 'Prop_Groups', 'DisableCollision': True, 'Hpr': VBase3(57.552, 0.0, 0.0), 'Pos': Point3(15.438, -23.688, 0.048), 'Scale': VBase3(0.879, 0.879, 0.879), 'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0), 'Model': 'models/props/prop_group_G'}}, '1166139450.46kmuller': {'Type': 'Trunks', 'DisableCollision': True, 'Hpr': VBase3(-175.386, 0.0, 0.0), 'Pos': Point3(-11.623, -28.323, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Trunk_rounded_2'}}, '1166139482.6kmuller': {'Type': 'Trunks', 'DisableCollision': False, 'Hpr': VBase3(-100.398, 0.0, 0.0), 'Pos': Point3(17.54, -12.363, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Trunk_square'}}, '1166139534.14kmuller': {'Type': 'Furniture', 'DisableCollision': False, 'Hpr': VBase3(88.8, 0.0, 0.0), 'Pos': Point3(-19.032, -8.401, 0.172), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bench_bank'}}, '1166139664.39kmuller': {'Type': 'Bucket', 'DisableCollision': True, 'Hpr': VBase3(-38.995, 0.0, 0.0), 'Pos': Point3(4.278, 24.282, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bucket_handles'}}, '1166139726.17kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-56.33, 0.0, 0.0), 'Pos': Point3(20.726, 15.931, 4.923), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/candle_holder'}}, '1166139823.07kmuller': {'Type': 'Pan', 'DisableCollision': False, 'Hpr': VBase3(-45.198, -0.006, 0.006), 'Pos': Point3(21.602, 17.485, 4.688), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/pan'}}, '1166139883.79kmuller': {'Type': 'Jugs_and_Jars', 'DisableCollision': False, 'Hpr': VBase3(2.971, 0.0, 0.0), 'Pos': Point3(21.796, 18.912, 4.7), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/largejug_B'}}, '1166140032.53kmuller': {'Type': 'Wall_Hangings', 'DisableCollision': False, 'Hpr': VBase3(0.0, 0.0, 0.0), 'Pos': Point3(-2.651, 29.91, 7.991), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/Map_01'}}, '1166143136.15kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(87.919, 0.0, 0.0), 'Pos': Point3(-19.128, 10.233, 7.623), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143173.57kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(87.919, 0.0, 0.0), 'Pos': Point3(-19.101, -8.222, 7.695), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143204.95kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': VBase3(-90.159, 0.0, 0.0), 'Pos': Point3(18.91, 9.923, 7.471), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143219.04kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(-90.159, 0.0, 0.0), 'Pos': Point3(19.055, -9.027, 7.695), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/lamp_candle'}}, '1166143244.09kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.798, 10.488, 17.608), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chandelier_jail'}}, '1166143275.89kmuller': {'Type': 'Light_Fixtures', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-0.592, -10.927, 17.594), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/chandelier_jail'}}, '1167972216.85kmuller': {'Type': 'Furniture', 'DisableCollision': True, 'Hpr': VBase3(44.958, 0.0, 0.0), 'Pos': Point3(-16.331, 26.168, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/bookshelf_spanish'}}, '1167972409.16kmuller': {'Type': 'Tools', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-19.259, 21.62, 0.0), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Model': 'models/props/butter_churn'}}, '1176423441.61dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '97.7273', 'DropOff': '6.8182', 'FlickRate': 0.5, 'Flickering': False, 'Hpr': VBase3(6.993, -61.677, 8.03), 'Intensity': '0.4242', 'LightType': 'SPOT', 'Pos': Point3(2.574, -18.447, 27.908), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1176423539.22dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '64.3182', 'DropOff': '39.5455', 'FlickRate': 0.5, 'Flickering': False, 'Hpr': VBase3(5.763, -56.906, 6.972), 'Intensity': '0.4848', 'LightType': 'SPOT', 'Pos': Point3(-1.976, 15.649, 24.802), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1176423736.28dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '60.0000', 'DropOff': '0.0000', 'FlickRate': 0.5, 'Flickering': True, 'Hpr': VBase3(0.0, 1.848, 0.0), 'Intensity': '0.5152', 'LightType': 'POINT', 'Pos': Point3(-0.034, -10.675, 13.873), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.95, 0.78, 0.64, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1176424160.2dzlu': {'Type': 'Light - Dynamic', 'Attenuation': '0.005', 'ConeAngle': '60.0000', 'DropOff': '0.0000', 'FlickRate': 0.5, 'Flickering': False, 'Hpr': VBase3(0.0, 1.848, 0.0), 'Intensity': '0.6061', 'LightType': 'POINT', 'Pos': Point3(-0.105, 11.422, 13.384), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0.95, 0.78, 0.64, 1.0), 'Model': 'models/props/light_tool_bulb'}}, '1185496415.31kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(4.727, 26.813, -0.119), 'Scale': VBase3(2.057, 1.302, 1.198), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}}, '1185496487.15kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(45.263, 0.0, 0.0), 'Pos': Point3(-15.061, 24.578, -0.449), 'Scale': VBase3(1.603, 1.0, 1.891), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185496538.15kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-15.225, -28.682, -0.316), 'Scale': VBase3(2.053, 0.567, 2.235), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}}, '1185496598.36kmuller': {'Type': 'Barrel', 'DisableCollision': False, 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(8.521, -28.523, 0.0), 'Scale': VBase3(0.77, 0.77, 0.77), 'Visual': {'Color': (0.47999998927116394, 0.44999998807907104, 0.4099999964237213, 1.0), 'Model': 'models/props/barrel_grey'}}, '1185496634.87kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-105.442, 0.0, 0.0), 'Pos': Point3(6.902, -26.349, -0.415), 'Scale': VBase3(0.856, 1.0, 1.451), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185496663.32kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(-134.387, 0.0, 0.0), 'Pos': Point3(11.183, -19.168, -0.394), 'Scale': VBase3(0.955, 1.0, 1.0), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1185496695.84kmuller': {'Type': 'Collision Barrier', 'DisableCollision': False, 'Hpr': VBase3(177.474, 0.0, 0.0), 'Pos': Point3(18.836, -16.153, -1.477), 'Scale': VBase3(0.944, 1.0, 1.196), 'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}, '1192813036.19akelts': {'Type': 'Effect Node', 'EffectName': 'torch_effect', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(16.066, 27.69, 0.728), 'Scale': VBase3(1.0, 1.0, 1.0), 'Visual': {'Color': (0, 0, 0.65, 1), 'Model': 'models/misc/smiley'}}, '1228171574.52kmuller': {'Type': 'Door Locator Node', 'Name': 'door_locator', 'Hpr': VBase3(-1.084, 0.0, 0.0), 'Pos': Point3(0.226, -30.04, -0.042), 'Scale': VBase3(1.0, 1.0, 1.0)}, '1228171636.05kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.562, -12.628, 9.043), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171658.06kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.497, -4.055, 8.9), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171680.97kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.522, 13.075, 8.571), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171681.0kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-19.48, 6.987, 8.709), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171718.55kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(90.0, 0.0, 0.0), 'Pos': Point3(-23.464, 2.055, 9.623), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1228171851.33kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.558, 12.771, 8.257), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171851.36kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.6, 6.683, 8.394), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171851.37kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.605, -5.139, 8.562), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171851.39kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(19.519, -12.932, 8.729), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoSwag_winter08'}}, '1228171985.95kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-90.0, 0.0, 0.0), 'Pos': Point3(23.294, 2.108, 9.247), 'Scale': VBase3(1.749, 1.749, 1.749), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1228172029.81kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-22.915, 0.0, 0.0), 'Pos': Point3(-14.676, 27.506, 8.319), 'Scale': VBase3(0.745, 0.745, 0.745), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift03_winter08'}}, '1228172067.47kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(97.294, 0.0, 0.0), 'Pos': Point3(17.725, -11.752, 1.974), 'Scale': VBase3(0.877, 0.877, 0.877), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift03_winter08'}}, '1228172094.37kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': '', 'Hpr': VBase3(20.62, 0.0, 0.0), 'Pos': Point3(17.402, -13.417, 1.908), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift02_winter08'}}, '1228172137.52kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(22.222, 0.0, 0.0), 'Pos': Point3(-14.48, 27.114, 2.476), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift03_winter08'}}, '1228172150.87kmuller': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(43.198, 0.0, 0.0), 'Pos': Point3(-15.74, 26.194, 4.277), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift04_winter08'}}, '1257805377.33caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(29.215, 0.0, 0.0), 'Pos': Point3(-17.989, 24.828, 8.291), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}}, '1257805389.23caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-80.692, 0.0, 0.0), 'Pos': Point3(-16.187, 26.439, 8.319), 'Scale': VBase3(1.0, 1.0, 1.0), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift04_winter08'}}, '1257805548.61caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(179.828, 0.0, 0.0), 'Pos': Point3(0.134, -29.849, 16.921), 'Scale': VBase3(1.647, 1.647, 1.647), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoRibbon_winter08'}}, '1257805573.24caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-179.622, 0.0, 0.0), 'Pos': Point3(13.583, -29.761, 16.921), 'Scale': VBase3(1.647, 1.647, 1.647), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoRibbon_winter08'}}, '1257805604.96caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-3.461, -2.873, 38.03), 'Pos': Point3(1.516, -29.874, 17.264), 'Scale': VBase3(3.099, 3.099, 3.099), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}, '1257805629.21caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(178.92, 6.382, 0.0), 'Pos': Point3(-13.08, -29.713, 16.646), 'Scale': VBase3(1.795, 1.795, 1.795), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1257805691.46caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-178.182, 2.38, 35.723), 'Pos': Point3(-1.065, -29.816, 17.292), 'Scale': VBase3(3.099, 3.099, 3.099), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}, '1257805757.37caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(178.92, 6.382, 0.0), 'Pos': Point3(0.206, -29.526, 16.511), 'Scale': VBase3(1.795, 1.795, 1.795), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1257805801.97caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(178.92, 6.382, 0.0), 'Pos': Point3(13.537, -29.768, 16.596), 'Scale': VBase3(1.795, 1.795, 1.795), 'VisSize': '', 'Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}, '1257891327.63caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(40.405, 0.0, 0.0), 'Pos': Point3(-1.49, 0.401, 2.948), 'Scale': VBase3(0.743, 0.743, 0.743), 'VisSize': '', 'Visual': {'Color': (0.6000000238418579, 1.0, 0.800000011920929, 1.0), 'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}}, '1257891346.66caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(-180.0, -89.326, -179.539), 'Pos': Point3(-2.572, 0.139, 2.984), 'Scale': VBase3(0.929, 0.929, 0.929), 'VisSize': '', 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 1.0, 1.0), 'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}, '1257891403.07caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': Point3(0.0, 0.0, 0.0), 'Pos': Point3(-2.297, 1.647, 2.948), 'Scale': VBase3(0.515, 0.515, 0.515), 'VisSize': '', 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 1.0, 1.0), 'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}}, '1257891450.24caoconno': {'Type': 'Holiday', 'DisableCollision': False, 'Holiday': 'WinterFestival', 'Hpr': VBase3(180.0, -89.326, 138.895), 'Pos': Point3(-2.13, -0.697, 2.993), 'Scale': VBase3(0.929, 0.929, 0.929), 'VisSize': '', 'Visual': {'Color': (0.800000011920929, 0.800000011920929, 1.0, 1.0), 'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}}, 'Visual': {'Model': 'models/buildings/interior_spanish_npc'}}}, 'Node Links': [], 'Layers': {}, 'ObjectIds': {'1153420207.67dzlu01': '["Objects"]["1153420207.67dzlu01"]', '1165347933.66kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1165347933.66kmuller"]', '1166138034.99kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138034.99kmuller"]', '1166138092.34kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138092.34kmuller"]', '1166138151.37kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138151.37kmuller"]', '1166138161.79kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138161.79kmuller"]', '1166138390.93kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138390.93kmuller"]', '1166138443.79kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138443.79kmuller"]', '1166138454.85kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138454.85kmuller"]', '1166138510.96kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138510.96kmuller"]', '1166138524.92kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138524.92kmuller"]', '1166138537.42kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138537.42kmuller"]', '1166138621.31kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138621.31kmuller"]', '1166138646.6kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138646.6kmuller"]', '1166138674.59kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138674.59kmuller"]', '1166138708.48kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138708.48kmuller"]', '1166138742.6kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138742.6kmuller"]', '1166138817.45kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138817.45kmuller"]', '1166138973.9kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166138973.9kmuller"]', '1166139009.4kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139009.4kmuller"]', '1166139125.65kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139125.65kmuller"]', '1166139259.49kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139259.49kmuller"]', '1166139339.62kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139339.62kmuller"]', '1166139450.46kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139450.46kmuller"]', '1166139482.6kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139482.6kmuller"]', '1166139534.14kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139534.14kmuller"]', '1166139664.39kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139664.39kmuller"]', '1166139726.17kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139726.17kmuller"]', '1166139823.07kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139823.07kmuller"]', '1166139883.79kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166139883.79kmuller"]', '1166140032.53kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166140032.53kmuller"]', '1166143136.15kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143136.15kmuller"]', '1166143173.57kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143173.57kmuller"]', '1166143204.95kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143204.95kmuller"]', '1166143219.04kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143219.04kmuller"]', '1166143244.09kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143244.09kmuller"]', '1166143275.89kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1166143275.89kmuller"]', '1167972216.85kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1167972216.85kmuller"]', '1167972409.16kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1167972409.16kmuller"]', '1176423441.61dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176423441.61dzlu"]', '1176423539.22dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176423539.22dzlu"]', '1176423736.28dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176423736.28dzlu"]', '1176424160.2dzlu': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1176424160.2dzlu"]', '1185496415.31kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496415.31kmuller"]', '1185496487.15kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496487.15kmuller"]', '1185496538.15kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496538.15kmuller"]', '1185496598.36kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496598.36kmuller"]', '1185496634.87kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496634.87kmuller"]', '1185496663.32kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496663.32kmuller"]', '1185496695.84kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1185496695.84kmuller"]', '1192813036.19akelts': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1192813036.19akelts"]', '1228171574.52kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171574.52kmuller"]', '1228171636.05kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171636.05kmuller"]', '1228171658.06kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171658.06kmuller"]', '1228171680.97kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171680.97kmuller"]', '1228171681.0kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171681.0kmuller"]', '1228171718.55kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171718.55kmuller"]', '1228171851.33kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.33kmuller"]', '1228171851.36kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.36kmuller"]', '1228171851.37kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.37kmuller"]', '1228171851.39kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171851.39kmuller"]', '1228171985.95kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228171985.95kmuller"]', '1228172029.81kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172029.81kmuller"]', '1228172067.47kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172067.47kmuller"]', '1228172094.37kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172094.37kmuller"]', '1228172137.52kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172137.52kmuller"]', '1228172150.87kmuller': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1228172150.87kmuller"]', '1257805377.33caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805377.33caoconno"]', '1257805389.23caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805389.23caoconno"]', '1257805548.61caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805548.61caoconno"]', '1257805573.24caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805573.24caoconno"]', '1257805604.96caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805604.96caoconno"]', '1257805629.21caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805629.21caoconno"]', '1257805691.46caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805691.46caoconno"]', '1257805757.37caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805757.37caoconno"]', '1257805801.97caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257805801.97caoconno"]', '1257891327.63caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891327.63caoconno"]', '1257891346.66caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891346.66caoconno"]', '1257891403.07caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891403.07caoconno"]', '1257891450.24caoconno': '["Objects"]["1153420207.67dzlu01"]["Objects"]["1257891450.24caoconno"]'}} extraInfo = {'camPos': Point3(0, -14, 0), 'camHpr': VBase3(0, 0, 0), 'focalLength': 0.852765381336, 'skyState': -1, 'fog': 0}
[ 2, 34318, 2349, 21, 2196, 513, 13, 17, 13, 15, 198, 2, 11361, 18022, 8189, 362, 13, 19, 357, 38850, 5333, 8, 198, 2, 4280, 3361, 3902, 422, 25, 11361, 362, 13, 22, 13, 1415, 357, 85, 17, 13, 22, 13, 1415, 25, 23, 34825, 1129, ...
2.119957
13,905
# PassGen # These imports will be used for this project. from colorama import Fore, Style from colorama import init import datetime import string import random import sys import os # Initilaze File organizer. os.system('title PassGen') init(autoreset = True) # Create Log Functions. # This will Generate a Strong Password for the User! def Generate(PassLen): JoinChars = [] # Create an Empty List. # Split the List of these String Operations, and Join them to JoinChars List. JoinChars.extend(list(string.ascii_letters)) JoinChars.extend(list(string.digits)) JoinChars.extend(list(string.punctuation)) random.shuffle(JoinChars) # Shuffle the List. # Get the random passoword. return "".join(JoinChars[0:PassLen]) # Code Logic here. LOG.WARN_LOG("Initialized PassGen!") LOG.STATUS_LOG("Generating a Random Password for You.") Password = Generate(random.randint(5, 17)) LOG.INFO_LOG(f"Your Password is: {Password}") with open("Password.log", "a") as File: File.write(f"{Password}\n") if (len(sys.argv) == 1) or (len(sys.argv) > 1 and sys.argv[1].lower() != "-o"): os.system("start Password.log") sys.exit() # Exiting the program successfully.
[ 2, 6251, 13746, 201, 198, 2, 2312, 17944, 481, 307, 973, 329, 428, 1628, 13, 201, 198, 6738, 3124, 1689, 1330, 4558, 11, 17738, 201, 198, 6738, 3124, 1689, 1330, 2315, 201, 198, 11748, 4818, 8079, 201, 198, 11748, 4731, 201, 198, 11...
2.805621
427
""" The model file for a Memo """ import re import os import shutil import json from datetime import datetime from flask import current_app from memos import db from memos.models.User import User from memos.models.MemoState import MemoState from memos.models.MemoFile import MemoFile from memos.models.MemoSignature import MemoSignature from memos.models.MemoReference import MemoReference from memos.models.MemoHistory import MemoHistory from memos.models.MemoActivity import MemoActivity from memos.revletter import b10_to_rev, rev_to_b10
[ 37811, 198, 464, 2746, 2393, 329, 257, 4942, 78, 198, 198, 37811, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 33918, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 42903, 1330, 1459, 62, 1324, 198, ...
3.503226
155
"""Common ETL test fixtures""" import json import pytest
[ 37811, 17227, 12152, 43, 1332, 34609, 37811, 198, 11748, 33918, 198, 198, 11748, 12972, 9288, 628, 628, 198 ]
3.444444
18
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import random def julia(**kwargs): """ temp """ # Initialize Julia Set instance juliaInstance = JuliaSet() # If kwargs not empty update the attributes if kwargs is not None: juliaInstance.param(**kwargs) return juliaInstance if __name__ == "__main__": # execute only if run as a script genJuliaSet = JuliaSet() genJuliaSet.param() genJuliaSet.run()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 11215, 355, 12067, 198, 11748, 4738, 198, 198, 4299, 474, 43640, 7, 1174, 46265, 22046, 2599, 198, 220, 220,...
2.632432
185
#!python3 # eye_detection.py - detect eyes using webcam # tutorial: https://www.roytuts.com/real-time-eye-detection-in-webcam-using-python-3/ import cv2 import math import numpy as np if __name__ == "__main__": main()
[ 2, 0, 29412, 18, 198, 2, 4151, 62, 15255, 3213, 13, 9078, 532, 4886, 2951, 1262, 49823, 198, 2, 11808, 25, 3740, 1378, 2503, 13, 3287, 83, 5500, 13, 785, 14, 5305, 12, 2435, 12, 25379, 12, 15255, 3213, 12, 259, 12, 12384, 20991, ...
2.627907
86
#!/usr/bin/env python descripts = {} with open('macaca_genes.txt') as fh: fh.readline() for line in fh: cols = line.strip('\n').split('\t') if cols[1]: descripts[cols[0]] = cols[1].split('[')[0].strip() else: descripts[cols[0]] = cols[1] with open('gene_info.txt') as fh: for line in fh: cols = line.strip().split('\t') cols.append(descripts[cols[1]]) print "\t".join(cols)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 20147, 1968, 82, 796, 23884, 198, 4480, 1280, 10786, 20285, 22260, 62, 5235, 274, 13, 14116, 11537, 355, 277, 71, 25, 198, 197, 69, 71, 13, 961, 1370, 3419, 198, 197, 1640, 1627...
2.035714
196
import gin from scaper import Scaper, generate_from_jams import copy import logging import p_tqdm import nussl import os import numpy as np def make_one_mixture(sc, path_to_file, num_sources, event_parameters, allow_repeated_label): """ Creates a single mixture, incoherent. Instantiates according to the event parameters for each source. """ check = False while not check: for j in range(num_sources): sc.add_event(**event_parameters) sc.generate( path_to_file, path_to_file.replace('.wav', '.jams'), no_audio=False, allow_repeated_label=allow_repeated_label, save_isolated_events=True, ) _reset_event_spec(sc) check = check_mixture(path_to_file)
[ 11748, 39733, 198, 6738, 629, 2136, 1330, 1446, 2136, 11, 7716, 62, 6738, 62, 73, 4105, 198, 11748, 4866, 198, 11748, 18931, 198, 11748, 279, 62, 83, 80, 36020, 198, 11748, 299, 1046, 75, 198, 11748, 28686, 198, 11748, 299, 32152, 355...
2.164021
378
import json
[ 11748, 33918 ]
5.5
2
import numpy as np from keras import backend as K import os import sys K.set_image_dim_ordering('tf') if __name__ == '__main__': main()
[ 11748, 299, 32152, 355, 45941, 198, 6738, 41927, 292, 1330, 30203, 355, 509, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 42, 13, 2617, 62, 9060, 62, 27740, 62, 34555, 10786, 27110, 11537, 628, 628, 198, 361, 11593, 3672, 834, 6624, ...
2.769231
52
from django.conf import settings
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 628 ]
4.25
8
# -*- coding: utf-8 -*- from scipy import stats import numpy as np import warnings from ...compat import check_is_fitted, pmdarima as pm_compat from .base import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer']
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 629, 541, 88, 1330, 9756, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 14601, 198, 198, 6738, 2644, 5589, 265, 1330, 2198, 62, 271, 62, 38631, 11, 9...
2.884615
78
from baserow.core.registry import Instance, Registry user_data_registry = UserDataRegistry()
[ 6738, 1615, 263, 322, 13, 7295, 13, 2301, 4592, 1330, 2262, 590, 11, 33432, 628, 628, 198, 7220, 62, 7890, 62, 2301, 4592, 796, 11787, 6601, 8081, 4592, 3419, 198 ]
3.233333
30
''' ------------------------------------- Assignment 2 - EE2703 (Jan-May 2020) Done by Akilesh Kannan (EE18B122) Created on 18/01/20 Last Modified on 04/02/20 ------------------------------------- ''' # importing necessary libraries import sys import cmath import numpy as np import pandas as pd # To improve readability CIRCUIT_START = ".circuit" CIRCUIT_END = ".end" RESISTOR = "R" CAPACITOR = "C" INDUCTOR = "L" IVS = "V" ICS = "I" VCVS = "E" VCCS = "G" CCVS = "H" CCCS = "F" PI = np.pi # Classes for each circuit component # Convert a number in engineer's format to math def enggToMath(enggNumber): try: return float(enggNumber) except: lenEnggNumber = len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1] == 'k': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli elif enggNumber[lenEnggNumber-1] == 'm': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro elif enggNumber[lenEnggNumber-1] == 'u': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano elif enggNumber[lenEnggNumber-1] == 'n': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega elif enggNumber[lenEnggNumber-1] == 'M': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit("Please check the component values given. Supported engineer units are: M, k, m, u, n\nYou can also enter values in exponential format (eg. 1e3 = 1000).") if __name__ == "__main__": # checking number of command line arguments if len(sys.argv)!=2 : sys.exit("Invalid number of arguments!") else: try: circuitFile = sys.argv[1] circuitFreq = 1e-100 circuitComponents = { RESISTOR: [], CAPACITOR: [], INDUCTOR: [], IVS: [], ICS: [], VCVS: [], VCCS: [], CCVS: [], CCCS: [] } circuitNodes = [] # checking if given netlist file is of correct type if (not circuitFile.endswith(".netlist")): print("Wrong file type!") else: netlistFileLines = [] with open (circuitFile, "r") as f: for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\n')[0]) # Getting frequency, if any if(line[:3] == '.ac'): circuitFreq = float(line.split()[2]) # Setting Angular Frequency w w = 2*PI*circuitFreq try: # Finding the location of the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for line in circuitBody: # Extracting the data from the line lineTokens = line.split() # Appending new nodes to a list try: if lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue # Resistor if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage Source elif lineTokens[0][0] == IVS: if len(lineTokens) == 5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC Source if circuitFreq == 1e-100: sys.exit("Frequency of AC Source not specified!!") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current Source elif lineTokens[0][0] == ICS: if len(lineTokens) == 5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC Source if circuitFreq == 1e-100: sys.exit("Frequency of AC Source not specified!!") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous Component Name else: sys.exit("Wrong Component Given. ABORT!") try: circuitNodes.remove('GND') circuitNodes = ['GND'] + circuitNodes except: sys.exit("No ground node specified in the circuit!!") # Creating a dictionary with node names and their numbers (to reduce the time taken by later parts of the program) nodeNumbers = {circuitNodes[i]:i for i in range(len(circuitNodes))} numNodes = len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M and b matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex) # GND Equation matrixM[0][0] = 1.0 # Resistor Equations for r in circuitComponents[RESISTOR]: if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor Equations for c in circuitComponents[CAPACITOR]: if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) # Inductor Equations for l in circuitComponents[INDUCTOR]: if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) # Voltage Source Equations for i in range(len(circuitComponents[IVS])): # Equation accounting for current through the source if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source Equations for i in circuitComponents[ICS]: if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] = i.value # VCVS Equations for i in range(len(circuitComponents[VCVS])): # Equation accounting for current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS Equations for i in range(len(circuitComponents[CCVS])): # Equation accounting for current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS Equations for vccs in circuitComponents[VCCS]: if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for cccs in circuitComponents[CCCS]: if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM, matrixB) circuitCurrents = [] # Formatting Output Data for v in circuitComponents[IVS]: circuitCurrents.append("current in "+v.name) for v in circuitComponents[VCVS]: circuitCurrents.append("current in "+v.name) for v in circuitComponents[CCVS]: circuitCurrents.append("current in "+v.name) # Printing output in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print("The values given above are AMPLITUDE values and NOT RMS values.") except np.linalg.LinAlgError: sys.exit("Singular Matrix Formed! Please check if you have entered the circuit definition correctly!") except ValueError: sys.exit("Netlist does not abide to given format!") except FileNotFoundError: sys.exit("Given file does not exist!")
[ 7061, 6, 198, 3880, 30934, 198, 50144, 362, 532, 27254, 1983, 3070, 357, 12128, 12, 6747, 12131, 8, 198, 24429, 416, 9084, 2915, 71, 509, 1236, 272, 357, 6500, 1507, 33, 18376, 8, 198, 15622, 319, 1248, 14, 486, 14, 1238, 198, 4586,...
1.811783
8,368
import subprocess import os.path """ Stylish input() """ """ Execute command locally """ """ Get all subdirectories of a directory. """ """ Rocket science """
[ 11748, 850, 14681, 198, 11748, 28686, 13, 6978, 628, 198, 37811, 198, 18716, 1836, 5128, 3419, 198, 37811, 628, 198, 37811, 198, 23002, 1133, 3141, 15726, 198, 37811, 198, 198, 37811, 198, 3855, 477, 850, 12942, 1749, 286, 257, 8619, 13...
3.192308
52
import numpy as np import matplotlib.pyplot as plt from skimage.exposure import rescale_intensity from unsharp import * # Load file and normalize to 0-1 fname = 'iguana.jpg' im = plt.imread(fname) if im.mean() >= 1: im = im/255. sigma = 5 amplitude = 1.5 imsharp = unsharp_mask(im, sigma, amplitude) imsharp = rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1)) new_fname = fname[:-4]+'_sharp.jpg' plt.imsave(new_fname, imsharp)
[ 11748, 299, 32152, 355, 45941, 220, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1341, 9060, 13, 1069, 26205, 1330, 6811, 1000, 62, 47799, 198, 198, 6738, 555, 48554, 1330, 1635, 198, 198, 2, 8778, 2393, 29...
2.464088
181