content
stringlengths
0
894k
type
stringclasses
2 values
import pytest from dynaconf import LazySettings from dynaconf.loaders.yaml_loader import load, clean settings = LazySettings( NAMESPACE_FOR_DYNACONF='EXAMPLE', ) YAML = """ # the bellow is just to ensure `,` will not break string YAML a: "a,b" example: password: 99999 host: server.com port: 8080 service: url: service.com port: 80 auth: password: qwerty test: 1234 development: password: 88888 host: dev_server.com """ YAML2 = """ example: # @float casting not needed, used only for testing secret: '@float 42' password: 123456 """ YAMLS = [YAML, YAML2] def test_load_from_yaml(): """Assert loads from YAML string""" load(settings, filename=YAML) assert settings.HOST == 'server.com' assert settings.PORT == 8080 assert settings.SERVICE['url'] == 'service.com' assert settings.SERVICE.url == 'service.com' assert settings.SERVICE.port == 80 assert settings.SERVICE.auth.password == 'qwerty' assert settings.SERVICE.auth.test == 1234 load(settings, filename=YAML, namespace='DEVELOPMENT') assert settings.HOST == 'dev_server.com' load(settings, filename=YAML) assert settings.HOST == 'server.com' def test_load_from_multiple_yaml(): """Assert loads from YAML string""" load(settings, filename=YAMLS) assert settings.HOST == 'server.com' assert settings.PASSWORD == 123456 assert settings.SECRET == 42.0 assert settings.PORT == 8080 assert settings.SERVICE['url'] == 'service.com' assert settings.SERVICE.url == 'service.com' assert settings.SERVICE.port == 80 assert settings.SERVICE.auth.password == 'qwerty' assert settings.SERVICE.auth.test == 1234 load(settings, filename=YAMLS, namespace='DEVELOPMENT') assert settings.HOST == 'dev_server.com' assert settings.PASSWORD == 88888 load(settings, filename=YAMLS) assert settings.HOST == 'server.com' assert settings.PASSWORD == 123456 def test_no_filename_is_none(): """Assert if passed no filename return is None""" assert load(settings) is None def test_key_error_on_invalid_namespace(): """Assert error raised if namespace is not found in YAML""" with pytest.raises(KeyError): load(settings, filename=YAML, namespace='FOOBAR', silent=False) def test_no_key_error_on_invalid_namespace(): """Assert error raised if namespace is not found in YAML""" load(settings, filename=YAML, namespace='FOOBAR', silent=True) def test_load_single_key(): """Test loading a single key""" yaml = """ foo: bar: blaz zaz: naz """ load(settings, filename=yaml, namespace='FOO', key='bar') assert settings.BAR == 'blaz' assert settings.exists('BAR') is True assert settings.exists('ZAZ') is False def test_extra_yaml(): """Test loading extra yaml file""" load(settings, filename=YAML) yaml = """ example: hello: world """ settings.set('YAML', yaml) settings.execute_loaders(namespace='EXAMPLE') assert settings.HELLO == 'world' def test_multi_extra_yaml(): """Test loading extra yaml file""" load(settings, filename=YAMLS) yaml = """ example: hello: world """ yaml2 = """ example: foo: bar """ settings.set('YAML', [yaml, yaml2]) settings.execute_loaders(namespace='EXAMPLE') assert settings.HELLO == 'world' assert settings.FOO == 'bar' def test_empty_value(): load(settings, filename="") def test_multiple_filenames(): load(settings, filename="a.yaml,b.yml,c.yaml,d.yml") def test_cleaner(): load(settings, filename=YAML) assert settings.HOST == 'server.com' assert settings.PORT == 8080 assert settings.SERVICE['url'] == 'service.com' assert settings.SERVICE.url == 'service.com' assert settings.SERVICE.port == 80 assert settings.SERVICE.auth.password == 'qwerty' assert settings.SERVICE.auth.test == 1234 load(settings, filename=YAML, namespace='DEVELOPMENT') assert settings.HOST == 'dev_server.com' load(settings, filename=YAML) assert settings.HOST == 'server.com' clean(settings, settings.namespace)
python
# cls=20, base yolo5 import torch import torch.nn as nn import common as C from torchsummary import summary class YOLOV4(nn.Module): def __init__(self): super(YOLOV4, self).__init__() self.input = nn.Sequential( C.Conv(3, 32, 3, 1, mish_act=True), ) self.group0 = nn.Sequential( C.Conv(32, 64, 3, 2, mish_act=True), C.BottleneckCSP(64, 64, mish_csp=True), ) self.group1 = nn.Sequential( C.Conv(64, 128, 3, 2, mish_act=True), C.BottleneckCSP(128, 128, mish_csp=True), C.BottleneckCSP(128, 128, mish_csp=True), ) self.group2 = nn.Sequential( C.Conv(128, 256, 3, 2, mish_act=True), C.BottleneckCSP(256, 256, mish_csp=True), C.BottleneckCSP(256, 256, mish_csp=True), C.BottleneckCSP(256, 256, mish_csp=True), C.BottleneckCSP(256, 256, mish_csp=True), C.BottleneckCSP(256, 256, mish_csp=True), C.BottleneckCSP(256, 256, mish_csp=True), C.BottleneckCSP(256, 256, mish_csp=True), C.BottleneckCSP(256, 256, mish_csp=True), ) # route -21 self.group3 = nn.Sequential( C.Conv(256, 512, 3, 2, mish_act=True), C.BottleneckCSP(512, 512, mish_csp=True), C.BottleneckCSP(512, 512, mish_csp=True), C.BottleneckCSP(512, 512, mish_csp=True), C.BottleneckCSP(512, 512, mish_csp=True), C.BottleneckCSP(512, 512, mish_csp=True), C.BottleneckCSP(512, 512, mish_csp=True), C.BottleneckCSP(512, 512, mish_csp=True), C.BottleneckCSP(512, 512, mish_csp=True), ) #route -10 self.group4 = nn.Sequential( C.Conv(512, 1024, 3, 2, mish_act=True), C.BottleneckCSP(1024, 1024, mish_csp=True), C.BottleneckCSP(1024, 1024, mish_csp=True), C.BottleneckCSP(1024, 1024, mish_csp=True), C.BottleneckCSP(1024, 1024, mish_csp=True), ) self.spp = nn.Sequential( C.Conv(1024, 512, 1, 1), C.Conv(512, 1024, 3, 1), C.SPP(1024, 512, k=[5, 9, 13]), C.Conv(512, 1024, 3, 1), C.Conv(1024, 512, 1, 1), ) # route 15 ################################################## ############# backbone -> neck -> head ########### ################################################## self.neck0 = C.Conv(512, 256, 1, 1) self.neck0UP = nn.Upsample(scale_factor=2, mode='nearest') self.neck0route = C.Conv(512, 256, 1, 1) ''' Up route concat out 38*38*512 ''' self.neck1 = nn.Sequential( C.Conv(512, 256, 1, 1), C.Conv(256, 512, 3, 1), C.Conv(512, 256, 1, 1), C.Conv(256, 512, 3, 1), C.Conv(512, 256, 1, 1), ) self.neck2 = C.Conv(256, 128, 1, 1) self.neck2UP = nn.Upsample(scale_factor=2, mode='nearest') self.neck2route = C.Conv(256, 128, 1, 1) ''' Up route concat out 76*76*256 ''' self.neck3 = nn.Sequential( C.Conv(256, 128, 1, 1), C.Conv(128, 256, 3, 1), C.Conv(256, 128, 1, 1), C.Conv(128, 256, 3, 1), C.Conv(256, 128, 1, 1), ) self.head0 = nn.Sequential( C.Conv(128, 256, 3, 1), nn.Conv2d(256, 75, 1, 1), ) self.neck3route = C.Conv(128, 256, 3, 2) ''' route concat out:38*38*512 ''' self.neck4 = nn.Sequential( C.Conv(512, 256, 1, 1), C.Conv(256, 512, 3, 1), C.Conv(512, 256, 1, 1), C.Conv(256, 512, 3, 1), C.Conv(512, 256, 1, 1), ) #route -3 self.head1 = nn.Sequential( C.Conv(256, 512, 3, 1), nn.Conv2d(512, 75, 1, 1), ) self.neck4route = C.Conv(256, 512, 3, 2) ''' route concat out:19*19*1024 ''' self.neck5 = nn.Sequential( C.Conv(1024, 512, 1, 1), C.Conv(512, 1024, 3, 1), C.Conv(1024, 512, 1, 1), C.Conv(512, 1024, 3, 1), C.Conv(1024, 512, 1, 1), ) self.head2 = nn.Sequential( C.Conv(512, 1024, 3, 1), nn.Conv2d(1024, 75, 1, 1), ) def forward(self, x): x0 = self.input(x) x1 = self.group0(x0) x2 = self.group1(x1) x3 = self.group2(x2) x4 = self.group3(x3) x5 = self.group4(x4) x6 = self.spp(x5) x7 = self.neck0(x6) x8 = self.neck0UP(x7) x9 = self.neck0route(x4) x10 = torch.cat((x9, x8), 1) x11 = self.neck1(x10) x12 = self.neck2(x11) x13 = self.neck2UP(x12) x14 = self.neck2route(x3) x15 = torch.cat((x14, x13), 1) x16 = self.neck3(x15) head0 = self.head0(x16) x17 = self.neck3route(x16) x18 = torch.cat((x17, x11), 1) x19 = self.neck4(x18) head1 = self.head1(x19) x20 = self.neck4route(x19) x21 = torch.cat((x20, x6), 1) x22 = self.neck5(x21) head2 = self.head2(x22) head0 = head0.view(head0.size(0), -1) head1 = head1.view(head1.size(0), -1) head2 = head2.view(head2.size(0), -1) return head0, head1, head2 if __name__ == "__main__": img = torch.rand((1, 3, 416, 416), dtype = torch.float32) net = YOLOV4() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = net.to(device) print(model) summary(model, (3, 416, 416))
python
import onnxruntime as ort import numpy as np from onnxruntime_extensions import get_library_path # python implementation for results check def compare(x, y): """Comparison helper function for multithresholding. Gets two values and returns 1.0 if x>=y otherwise 0.0.""" if x >= y: return 1.0 else: return 0.0 def multithreshold_elementwise(v, thresholds, out_scale=None, out_bias=None): """Given a set of threshold values t={t_0, t_1 ... t_n} the successive thresholding maps any real number x to an integer in the interval [0, n], where the returned integer is the number of thresholds x is greater than or equal to. The output tensor will be scaled by out_scale and biased by out_bias.""" # the inputs are expected to be in the shape (N,C,H,W) or (N, C) # the MultiThreshold node supports a data_layout attribute that can be set # to 'NHWC' to support (N,H,W,C) data layout mode for in-out as well # N : Batch size # C : Number of channels # H : Heigth of the input images # W : Width of the input images # # the thresholds are expected to be in the shape (C, B) # C : Number of channels (must be the same value as C in input tensor # or 1 if all channels use the same threshold value) # B : Desired activation steps => i.e. for 4-bit activation, # B=7 (2^(n)-1 and n=4) # the output tensor will be scaled by out_scale and biased by out_bias # assert threshold shape is_global_threshold = thresholds.shape[0] == 1 assert ( v.shape[1] == thresholds.shape[0] ) or is_global_threshold, """"Threshold shape incorrect""" # save the required shape sizes for the loops (N, C and B) num_batch = v.shape[0] num_channel = v.shape[1] num_act = thresholds.shape[1] # reshape inputs to enable channel-wise reading vr = v.reshape((v.shape[0], v.shape[1], -1)) # save the new shape size of the images num_img_elem = vr.shape[2] # initiate output tensor ret = np.zeros_like(vr) # iterate over thresholds channel-wise for t in range(num_channel): channel_thresh = thresholds[0] if is_global_threshold else thresholds[t] # iterate over batches for b in range(num_batch): # iterate over image elements on which the thresholds will be applied for elem in range(num_img_elem): # iterate over the different thresholds for one channel for a in range(num_act): # apply successive thresholding to every element ret[b][t][elem] += compare(vr[b][t][elem], channel_thresh[a]) if out_scale is None: out_scale = 1.0 if out_bias is None: out_bias = 0.0 return out_scale * ret.reshape(v.shape) + out_bias inputs = np.ndarray( shape=(6, 3, 2, 2), buffer=np.array( [ 4.8, 3.2, 1.2, 4.9, 7.8, 2.4, 3.1, 4.7, 6.2, 5.1, 4.9, 2.2, 6.2, 0.0, 0.8, 4.7, 0.2, 5.6, 8.9, 9.2, 9.1, 4.0, 3.3, 4.9, 2.3, 1.7, 1.3, 2.2, 4.6, 3.4, 3.7, 9.8, 4.7, 4.9, 2.8, 2.7, 8.3, 6.7, 4.2, 7.1, 2.8, 3.1, 0.8, 0.6, 4.4, 2.7, 6.3, 6.1, 1.4, 5.3, 2.3, 1.9, 4.7, 8.1, 9.3, 3.7, 2.7, 5.1, 4.2, 1.8, 4.1, 7.3, 7.1, 0.4, 0.2, 1.3, 4.3, 8.9, 1.4, 1.6, 8.3, 9.4, ] ), ) thresholds = np.ndarray( shape=(3, 7), buffer=np.array( [ 0.8, 1.4, 1.7, 3.5, 5.2, 6.8, 8.2, 0.2, 2.2, 3.5, 4.5, 6.6, 8.6, 9.2, 1.3, 4.1, 4.5, 6.5, 7.8, 8.1, 8.9, ] ), ) outputs = np.ndarray( shape=(6, 3, 2, 2), buffer=np.array( [ 4.0, 3.0, 1.0, 4.0, 5.0, 2.0, 2.0, 4.0, 3.0, 3.0, 3.0, 1.0, 5.0, 0.0, 1.0, 4.0, 1.0, 4.0, 6.0, 7.0, 7.0, 1.0, 1.0, 3.0, 3.0, 3.0, 1.0, 3.0, 4.0, 2.0, 3.0, 7.0, 3.0, 3.0, 1.0, 1.0, 7.0, 5.0, 4.0, 6.0, 2.0, 2.0, 1.0, 1.0, 2.0, 1.0, 3.0, 3.0, 2.0, 5.0, 3.0, 3.0, 4.0, 5.0, 7.0, 3.0, 1.0, 3.0, 2.0, 1.0, 4.0, 6.0, 6.0, 0.0, 1.0, 1.0, 3.0, 6.0, 1.0, 1.0, 6.0, 7.0, ] ), ) so = ort.SessionOptions() so.register_custom_ops_library(get_library_path()) sess = ort.InferenceSession("test.onnx", so) inname = [input.name for input in sess.get_inputs()] outname = [output.name for output in sess.get_outputs()] print("Inputs name:", inname) print("Output name:", outname) results = sess.run(outname, {inname[0]: inputs, inname[1]: thresholds})[0] # assert (results == outputs).all() outputs_scaled = 2.0 * outputs - 1.0 assert (results == outputs_scaled).all() # performance and random test np.random.seed(0) inputs = np.random.random((6, 3, 2, 2)) thresholds = (np.array([[1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7, 8], [3, 4, 5, 6, 7, 8, 9]]) - 0.5) / 6 ort_results = sess.run(outname, {inname[0]: inputs, inname[1]: thresholds})[0] py_results = multithreshold_elementwise(inputs, thresholds) py_results_scaled = 2.0 * py_results - 1.0 assert (ort_results == py_results_scaled).all()
python
from itertools import permutations from pytest import raises import math import networkx as nx from networkx.algorithms.matching import matching_dict_to_set from networkx.utils import edges_equal class TestMaxWeightMatching: """Unit tests for the :func:`~networkx.algorithms.matching.max_weight_matching` function. """ def test_trivial1(self): """Empty graph""" G = nx.Graph() assert nx.max_weight_matching(G) == set() assert nx.min_weight_matching(G) == set() def test_trivial2(self): """Self loop""" G = nx.Graph() G.add_edge(0, 0, weight=100) assert nx.max_weight_matching(G) == set() assert nx.min_weight_matching(G) == set() def test_trivial3(self): """Single edge""" G = nx.Graph() G.add_edge(0, 1) assert edges_equal( nx.max_weight_matching(G), matching_dict_to_set({0: 1, 1: 0}) ) assert edges_equal( nx.min_weight_matching(G), matching_dict_to_set({0: 1, 1: 0}) ) def test_trivial4(self): """Small graph""" G = nx.Graph() G.add_edge("one", "two", weight=10) G.add_edge("two", "three", weight=11) assert edges_equal( nx.max_weight_matching(G), matching_dict_to_set({"three": "two", "two": "three"}), ) assert edges_equal( nx.min_weight_matching(G), matching_dict_to_set({"one": "two", "two": "one"}), ) def test_trivial5(self): """Path""" G = nx.Graph() G.add_edge(1, 2, weight=5) G.add_edge(2, 3, weight=11) G.add_edge(3, 4, weight=5) assert edges_equal( nx.max_weight_matching(G), matching_dict_to_set({2: 3, 3: 2}) ) assert edges_equal( nx.max_weight_matching(G, 1), matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3}) ) assert edges_equal( nx.min_weight_matching(G), matching_dict_to_set({1: 2, 3: 4}) ) assert edges_equal( nx.min_weight_matching(G, 1), matching_dict_to_set({1: 2, 3: 4}) ) def test_trivial6(self): """Small graph with arbitrary weight attribute""" G = nx.Graph() G.add_edge("one", "two", weight=10, abcd=11) G.add_edge("two", "three", weight=11, abcd=10) assert edges_equal( nx.max_weight_matching(G, weight="abcd"), matching_dict_to_set({"one": "two", "two": "one"}), ) assert edges_equal( nx.min_weight_matching(G, weight="abcd"), matching_dict_to_set({"three": "two"}), ) def test_floating_point_weights(self): """Floating point weights""" G = nx.Graph() G.add_edge(1, 2, weight=math.pi) G.add_edge(2, 3, weight=math.exp(1)) G.add_edge(1, 3, weight=3.0) G.add_edge(1, 4, weight=math.sqrt(2.0)) assert edges_equal( nx.max_weight_matching(G), matching_dict_to_set({1: 4, 2: 3, 3: 2, 4: 1}) ) assert edges_equal( nx.min_weight_matching(G), matching_dict_to_set({1: 4, 2: 3, 3: 2, 4: 1}) ) def test_negative_weights(self): """Negative weights""" G = nx.Graph() G.add_edge(1, 2, weight=2) G.add_edge(1, 3, weight=-2) G.add_edge(2, 3, weight=1) G.add_edge(2, 4, weight=-1) G.add_edge(3, 4, weight=-6) assert edges_equal( nx.max_weight_matching(G), matching_dict_to_set({1: 2, 2: 1}) ) assert edges_equal( nx.max_weight_matching(G, 1), matching_dict_to_set({1: 3, 2: 4, 3: 1, 4: 2}) ) assert edges_equal( nx.min_weight_matching(G), matching_dict_to_set({1: 2, 3: 4}) ) assert edges_equal( nx.min_weight_matching(G, 1), matching_dict_to_set({1: 2, 3: 4}) ) def test_s_blossom(self): """Create S-blossom and use it for augmentation:""" G = nx.Graph() G.add_weighted_edges_from([(1, 2, 8), (1, 3, 9), (2, 3, 10), (3, 4, 7)]) answer = matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) G.add_weighted_edges_from([(1, 6, 5), (4, 5, 6)]) answer = matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_s_t_blossom(self): """Create S-blossom, relabel as T-blossom, use for augmentation:""" G = nx.Graph() G.add_weighted_edges_from( [(1, 2, 9), (1, 3, 8), (2, 3, 10), (1, 4, 5), (4, 5, 4), (1, 6, 3)] ) answer = matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 5, 5: 4, 6: 1}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) G.add_edge(4, 5, weight=3) G.add_edge(1, 6, weight=4) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) G.remove_edge(1, 6) G.add_edge(3, 6, weight=4) answer = matching_dict_to_set({1: 2, 2: 1, 3: 6, 4: 5, 5: 4, 6: 3}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nested_s_blossom(self): """Create nested S-blossom, use for augmentation:""" G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 9), (1, 3, 9), (2, 3, 10), (2, 4, 8), (3, 5, 8), (4, 5, 10), (5, 6, 6), ] ) dict_format = {1: 3, 2: 4, 3: 1, 4: 2, 5: 6, 6: 5} expected = {frozenset(e) for e in matching_dict_to_set(dict_format)} answer = {frozenset(e) for e in nx.max_weight_matching(G)} assert answer == expected answer = {frozenset(e) for e in nx.min_weight_matching(G)} assert answer == expected def test_nested_s_blossom_relabel(self): """Create S-blossom, relabel as S, include in nested S-blossom:""" G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 10), (1, 7, 10), (2, 3, 12), (3, 4, 20), (3, 5, 20), (4, 5, 25), (5, 6, 10), (6, 7, 10), (7, 8, 8), ] ) answer = matching_dict_to_set({1: 2, 2: 1, 3: 4, 4: 3, 5: 6, 6: 5, 7: 8, 8: 7}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nested_s_blossom_expand(self): """Create nested S-blossom, augment, expand recursively:""" G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 8), (1, 3, 8), (2, 3, 10), (2, 4, 12), (3, 5, 12), (4, 5, 14), (4, 6, 12), (5, 7, 12), (6, 7, 14), (7, 8, 12), ] ) answer = matching_dict_to_set({1: 2, 2: 1, 3: 5, 4: 6, 5: 3, 6: 4, 7: 8, 8: 7}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_s_blossom_relabel_expand(self): """Create S-blossom, relabel as T, expand:""" G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 23), (1, 5, 22), (1, 6, 15), (2, 3, 25), (3, 4, 22), (4, 5, 25), (4, 8, 14), (5, 7, 13), ] ) answer = matching_dict_to_set({1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nested_s_blossom_relabel_expand(self): """Create nested S-blossom, relabel as T, expand:""" G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 19), (1, 3, 20), (1, 8, 8), (2, 3, 25), (2, 4, 18), (3, 5, 18), (4, 5, 13), (4, 7, 7), (5, 6, 7), ] ) answer = matching_dict_to_set({1: 8, 2: 3, 3: 2, 4: 7, 5: 6, 6: 5, 7: 4, 8: 1}) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nasty_blossom1(self): """Create blossom, relabel as T in more than one way, expand, augment: """ G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 45), (1, 5, 45), (2, 3, 50), (3, 4, 45), (4, 5, 50), (1, 6, 30), (3, 9, 35), (4, 8, 35), (5, 7, 26), (9, 10, 5), ] ) ansdict = {1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4, 9: 10, 10: 9} answer = matching_dict_to_set(ansdict) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nasty_blossom2(self): """Again but slightly different:""" G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 45), (1, 5, 45), (2, 3, 50), (3, 4, 45), (4, 5, 50), (1, 6, 30), (3, 9, 35), (4, 8, 26), (5, 7, 40), (9, 10, 5), ] ) ans = {1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4, 9: 10, 10: 9} answer = matching_dict_to_set(ans) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nasty_blossom_least_slack(self): """Create blossom, relabel as T, expand such that a new least-slack S-to-free dge is produced, augment: """ G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 45), (1, 5, 45), (2, 3, 50), (3, 4, 45), (4, 5, 50), (1, 6, 30), (3, 9, 35), (4, 8, 28), (5, 7, 26), (9, 10, 5), ] ) ans = {1: 6, 2: 3, 3: 2, 4: 8, 5: 7, 6: 1, 7: 5, 8: 4, 9: 10, 10: 9} answer = matching_dict_to_set(ans) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nasty_blossom_augmenting(self): """Create nested blossom, relabel as T in more than one way""" # expand outer blossom such that inner blossom ends up on an # augmenting path: G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 45), (1, 7, 45), (2, 3, 50), (3, 4, 45), (4, 5, 95), (4, 6, 94), (5, 6, 94), (6, 7, 50), (1, 8, 30), (3, 11, 35), (5, 9, 36), (7, 10, 26), (11, 12, 5), ] ) ans = { 1: 8, 2: 3, 3: 2, 4: 6, 5: 9, 6: 4, 7: 10, 8: 1, 9: 5, 10: 7, 11: 12, 12: 11, } answer = matching_dict_to_set(ans) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_nasty_blossom_expand_recursively(self): """Create nested S-blossom, relabel as S, expand recursively:""" G = nx.Graph() G.add_weighted_edges_from( [ (1, 2, 40), (1, 3, 40), (2, 3, 60), (2, 4, 55), (3, 5, 55), (4, 5, 50), (1, 8, 15), (5, 7, 30), (7, 6, 10), (8, 10, 10), (4, 9, 30), ] ) ans = {1: 2, 2: 1, 3: 5, 4: 9, 5: 3, 6: 7, 7: 6, 8: 10, 9: 4, 10: 8} answer = matching_dict_to_set(ans) assert edges_equal(nx.max_weight_matching(G), answer) assert edges_equal(nx.min_weight_matching(G), answer) def test_wrong_graph_type(self): error = nx.NetworkXNotImplemented raises(error, nx.max_weight_matching, nx.MultiGraph()) raises(error, nx.max_weight_matching, nx.MultiDiGraph()) raises(error, nx.max_weight_matching, nx.DiGraph()) raises(error, nx.min_weight_matching, nx.DiGraph()) class TestIsMatching: """Unit tests for the :func:`~networkx.algorithms.matching.is_matching` function. """ def test_dict(self): G = nx.path_graph(4) assert nx.is_matching(G, {0: 1, 1: 0, 2: 3, 3: 2}) def test_empty_matching(self): G = nx.path_graph(4) assert nx.is_matching(G, set()) def test_single_edge(self): G = nx.path_graph(4) assert nx.is_matching(G, {(1, 2)}) def test_edge_order(self): G = nx.path_graph(4) assert nx.is_matching(G, {(0, 1), (2, 3)}) assert nx.is_matching(G, {(1, 0), (2, 3)}) assert nx.is_matching(G, {(0, 1), (3, 2)}) assert nx.is_matching(G, {(1, 0), (3, 2)}) def test_valid_matching(self): G = nx.path_graph(4) assert nx.is_matching(G, {(0, 1), (2, 3)}) def test_invalid_input(self): error = nx.NetworkXError G = nx.path_graph(4) # edge to node not in G raises(error, nx.is_matching, G, {(0, 5), (2, 3)}) # edge not a 2-tuple raises(error, nx.is_matching, G, {(0, 1, 2), (2, 3)}) raises(error, nx.is_matching, G, {(0,), (2, 3)}) def test_selfloops(self): error = nx.NetworkXError G = nx.path_graph(4) # selfloop for node not in G raises(error, nx.is_matching, G, {(5, 5), (2, 3)}) # selfloop edge not in G assert not nx.is_matching(G, {(0, 0), (1, 2), (2, 3)}) # selfloop edge in G G.add_edge(0, 0) assert not nx.is_matching(G, {(0, 0), (1, 2), (2, 3)}) def test_invalid_matching(self): G = nx.path_graph(4) assert not nx.is_matching(G, {(0, 1), (1, 2), (2, 3)}) def test_invalid_edge(self): G = nx.path_graph(4) assert not nx.is_matching(G, {(0, 3), (1, 2)}) raises(nx.NetworkXError, nx.is_matching, G, {(0, 55)}) G = nx.DiGraph(G.edges) assert nx.is_matching(G, {(0, 1)}) assert not nx.is_matching(G, {(1, 0)}) class TestIsMaximalMatching: """Unit tests for the :func:`~networkx.algorithms.matching.is_maximal_matching` function. """ def test_dict(self): G = nx.path_graph(4) assert nx.is_maximal_matching(G, {0: 1, 1: 0, 2: 3, 3: 2}) def test_valid(self): G = nx.path_graph(4) assert nx.is_maximal_matching(G, {(0, 1), (2, 3)}) def test_not_matching(self): G = nx.path_graph(4) assert not nx.is_maximal_matching(G, {(0, 1), (1, 2), (2, 3)}) def test_not_maximal(self): G = nx.path_graph(4) assert not nx.is_maximal_matching(G, {(0, 1)}) class TestIsPerfectMatching: """Unit tests for the :func:`~networkx.algorithms.matching.is_perfect_matching` function. """ def test_dict(self): G = nx.path_graph(4) assert nx.is_perfect_matching(G, {0: 1, 1: 0, 2: 3, 3: 2}) def test_valid(self): G = nx.path_graph(4) assert nx.is_perfect_matching(G, {(0, 1), (2, 3)}) def test_valid_not_path(self): G = nx.cycle_graph(4) G.add_edge(0, 4) G.add_edge(1, 4) G.add_edge(5, 2) assert nx.is_perfect_matching(G, {(1, 4), (0, 3), (5, 2)}) def test_not_matching(self): G = nx.path_graph(4) assert not nx.is_perfect_matching(G, {(0, 1), (1, 2), (2, 3)}) def test_maximal_but_not_perfect(self): G = nx.cycle_graph(4) G.add_edge(0, 4) G.add_edge(1, 4) assert not nx.is_perfect_matching(G, {(1, 4), (0, 3)}) class TestMaximalMatching: """Unit tests for the :func:`~networkx.algorithms.matching.maximal_matching`. """ def test_valid_matching(self): edges = [(1, 2), (1, 5), (2, 3), (2, 5), (3, 4), (3, 6), (5, 6)] G = nx.Graph(edges) matching = nx.maximal_matching(G) assert nx.is_maximal_matching(G, matching) def test_single_edge_matching(self): # In the star graph, any maximal matching has just one edge. G = nx.star_graph(5) matching = nx.maximal_matching(G) assert 1 == len(matching) assert nx.is_maximal_matching(G, matching) def test_self_loops(self): # Create the path graph with two self-loops. G = nx.path_graph(3) G.add_edges_from([(0, 0), (1, 1)]) matching = nx.maximal_matching(G) assert len(matching) == 1 # The matching should never include self-loops. assert not any(u == v for u, v in matching) assert nx.is_maximal_matching(G, matching) def test_ordering(self): """Tests that a maximal matching is computed correctly regardless of the order in which nodes are added to the graph. """ for nodes in permutations(range(3)): G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from([(0, 1), (0, 2)]) matching = nx.maximal_matching(G) assert len(matching) == 1 assert nx.is_maximal_matching(G, matching) def test_wrong_graph_type(self): error = nx.NetworkXNotImplemented raises(error, nx.maximal_matching, nx.MultiGraph()) raises(error, nx.maximal_matching, nx.MultiDiGraph()) raises(error, nx.maximal_matching, nx.DiGraph())
python
from unittest import TestCase from src import utils class TestGetLoggerName(TestCase): def test_get_logger_name(self): logger_name = utils.get_logger_name(self.__class__) self.assertEqual("TesGetLogNam", logger_name) class TestGetProxyPort(TestCase): def test_get_proxy_port(self): LOWEST_TOR_PORT = 9050 TOR_PROXY_SERVER_ADDRESS = 'localhost' PROXIES = { 'http': f"socks5h://{TOR_PROXY_SERVER_ADDRESS}:{LOWEST_TOR_PORT}", 'https': f"socks5h://{TOR_PROXY_SERVER_ADDRESS}:{LOWEST_TOR_PORT}" } proxy_port = utils.get_proxy_port(PROXIES) self.assertEqual(9050, proxy_port) class TestDetermineRealCoutry(TestCase): def test_determine_real_country(self): res = [] names = ('France', 'India', 'Belgium', 'Brazil', 'Thailand', 'Turkey', 'Worldwide', 'Åland Islands', 'Austria', 'Anguilla', 'Albania', 'Aruba', 'Egypt', 'China', 'Bangladesh', 'Bolivia', 'Plurinational State of', 'Azerbaijan', 'United Arab Emirates') for name in names: res.append(utils.determine_real_country(name)) b = len(names) == len(set(res)) a = 1 def test_determine_real_country_one(self): names = ( 'Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'France', 'Germany', 'Greece', 'Hungary', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'United Kingdom', 'Ireland', 'Switzerland', 'Liechtenstein', 'Andorra', 'Monaco', 'Finland', 'Iceland', 'Norway', 'Sweden', 'Serbia', 'San Marino', 'Montenegro', 'Macedonia', 'the Former Yugoslav Republic of', 'Bosnia and Herzegovina', 'Albania', 'Ukraine', 'Moldova', 'Republic of', 'Armenia', 'Azerbaijan', 'Georgia', 'Kazakhstan', 'European Union', 'Suriname', 'Peru') res = [] names = ('France', 'India', 'Belgium', 'Brazil', 'Thailand', 'Turkey', 'Worldwide', 'Åland Islands', 'Austria', 'Anguilla', 'Albania', 'Aruba', 'Egypt', 'China', 'Bangladesh', 'Bolivia', 'Plurinational State of', 'Azerbaijan', 'United Arab Emirates') for name in names: res.append(utils.determine_real_country(name)) b = len(names) == len(set(res)) a = 1 class Test(TestCase): def test__contains_world_as_substring(self): # World Wide World Wide World Wide World Wide World Wi # World Wide World Wide World Wide continent1 = utils.determine_real_country("World Wide World Wide World Wide World Wide World Wi") self.assertEqual(('World', None, None, True), continent1) continent2 = utils.determine_real_country("World Wide World Wide World Wide") self.assertEqual(('World', None, None, True), continent2)
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2015-08-24 12:46:36 # @Author : LiangJ import base64 import json from time import time import tornado.gen import tornado.web from BeautifulSoup import BeautifulSoup from sqlalchemy.orm.exc import NoResultFound from tornado.httpclient import HTTPRequest, AsyncHTTPClient from config import * from mod.models.mysql.room_cache import RoomCache from ..auth.handler import authApi class RoomHandler(tornado.web.RequestHandler): @property def db(self): return self.application.db def get(self): self.write('Herald Web Service') def on_finish(self): self.db.close() @tornado.web.asynchronous @tornado.gen.engine def post(self): number = self.get_argument('number',default=None) retjson = {'code':200, 'content':''} data = { 'Login.Token1':number, 'Login.Token2':self.get_argument('password'), } # read from cache try: status = self.db.query(RoomCache).filter(RoomCache.cardnum == number).one() if status.date > int(time())-10000 and status.text != '*': self.write(base64.b64decode(status.text)) self.finish() return except NoResultFound: status = RoomCache(cardnum = number,text = '*',date = int(time())) self.db.add(status) try: self.db.commit() except: self.db.rollback() try: client = AsyncHTTPClient() response = authApi(number,self.get_argument("password")) if response['code'] == 200: cookie = response['content'] request = HTTPRequest( URL, method='GET', headers={'Cookie': cookie}, request_timeout=TIME_OUT) response = yield tornado.gen.Task(client.fetch, request) soup = BeautifulSoup(response.body) table2 = soup.findAll('td') room = table2[9].text bed = table2[10].text retjson['code'] = 200 retjson['content'] = { 'bed': bed, 'room': room } else: retjson['code'] = 401 except Exception,e: retjson['code'] = 200 retjson['content'] = {'bed': "",'room': ""} ret = json.dumps(retjson, ensure_ascii=False, indent=2) self.write(ret) self.finish() # refresh cache if retjson['code'] == 200: status.date = int(time()) status.text = base64.b64encode(ret) self.db.add(status) try: self.db.commit() except Exception,e: self.db.rollback() finally: self.db.remove()
python
# -*- coding: utf-8 -*- """ Created on Sat Jan 20 11:27:20 2018 @author: DrLC """ import pandas import math import nltk import re import gzip, pickle import matplotlib.pyplot as plt def load_csv(path="test.csv"): return pandas.read_csv(path, header=None) def load_class(path="classes.txt"): f = open(path, 'r') lines = f.readlines() f.close() ret = [line.strip('\n') for line in lines] return ret def simple_clean_sentence(sent): punctuation = ['.', ',', '!', '/', ':', ';', '+', '-', '*', '?', '~', '|', '[', ']', '{', '}', '(', ')', '_', '=', '%', '&', '$', '#', '"', '`', '^'] sent = sent.replace('\n', ' ').replace('\\n', ' ').replace('\\', ' ') for p in punctuation: sent = sent.replace(p, ' '+p+' ') sent = re.sub(r'\d+\.?\d*', ' numbernumbernumbernumbernumber ', sent) return sent.lower() def extract_questions_and_labels(d, lookup_table): ret = {"text":[], "label":[], "lookup_table":[]} for idx in range(len(d[0])): ret["label"].append(d[0][idx]) appd = "" if type(d[2][idx]) is float and math.isnan(d[2][idx]): appd = "" else: appd = simple_clean_sentence(d[2][idx]) ret["text"].append((simple_clean_sentence(d[1][idx])+' '+appd).lower()) ret["lookup_table"] = lookup_table return ret def word_tokenize(d, max_len=100): for idx in range(len(d['text'])): d['text'][idx] = nltk.word_tokenize(d['text'][idx]) ret = {"text":[], "label":[], "lookup_table":[]} ret["lookup_table"] = d["lookup_table"] for idx in range(len(d["text"])): if len(d["text"][idx]) <= max_len: ret["text"].append(d["text"][idx]) ret["label"].append(d["label"][idx]) return ret def save_dataset(d, path="yahoo_answers_test.pkl.gz"): f = gzip.open(path, "wb") pickle.dump(d, f) f.close() def load_dataset(path='yahoo_answers_test.pkl.gz'): f = gzip.open(path, "rb") d = pickle.load(f) f.close() return d def stat_word(d): stat = {} for s in d["text"]: for w in s: if w in stat.keys(): stat[w] += 1 else: stat[w] = 1 stat = sorted(stat.items(), key=lambda d:d[1], reverse=True) return stat def stat_sentence_length(d): stat = {} for s in d["text"]: l = len(s) if l in stat.keys(): stat[l] += 1 else: stat[l] = 1 stat = sorted(stat.items(), key=lambda d:d[0], reverse=True) return stat def stat_label(d): stat = {} for l in d["label"]: if l in stat.keys(): stat[l] += 1 else: stat[l] = 1 return stat def generate_pkl_gz(max_len=100, class_path="classes.txt", test_src_path="test.csv", train_src_path="train.csv", test_tgt_path="yahoo_answers_test.pkl.gz", train_tgt_path="yahoo_answers_train.pkl.gz"): lt = load_class(path=class_path) print ("Class lookup table loaded!") d_tr_ = load_csv(path=train_src_path) print ("All training data loaded!") d_tr = extract_questions_and_labels(d_tr_, lt) print ("Training data extracted!") d_tr = word_tokenize(d_tr, max_len) print ("Training data word token generated!") save_dataset(d_tr, path=train_tgt_path) print ("Training data saved!") d_te_ = load_csv(path=test_src_path) print ("All test data loaded!") d_te = extract_questions_and_labels(d_te_, lt) print ("Test data extracted!") d_te = word_tokenize(d_te, max_len) print ("Test data word token generated!") save_dataset(d_te, path=test_tgt_path) print ("Test data saved!") return d_tr, d_te def generate_stat_word(tr=None, te=None, d=None, train_path="yahoo_answers_train.pkl.gz", test_path="yahoo_answers_test.pkl.gz", dict_path="yahoo_answers_dict.pkl.gz"): if (tr is None or te is None) and d is None: d_te = load_dataset(path="yahoo_answers_test.pkl.gz") print ("Test set loaded!") d_tr = load_dataset(path="yahoo_answers_train.pkl.gz") print ("Train set loaded!") if d is None: d = {"text":[], "label":[], "lookup_table":[]} d["lookup_table"] = d_tr["lookup_table"] d["text"] = d_tr["text"] + d_te["text"] d["label"] = d_tr["label"] + d_te["label"] s_word = stat_word(d) f = open("word_stat.txt", "w", encoding="UTF-8") for inst in s_word: f.write(str(inst[1])+"\t"+inst[0]+"\n") f.close() f = gzip.open(dict_path, "wb") pickle.dump(s_word, f) f.close() return s_word, d def generate_stat_sentence_length(tr=None, te=None, d=None, train_path="yahoo_answers_train.pkl.gz", test_path="yahoo_answers_test.pkl.gz"): if (tr is None or te is None) and d is None: d_te = load_dataset(path="yahoo_answers_test.pkl.gz") print ("Test set loaded!") d_tr = load_dataset(path="yahoo_answers_train.pkl.gz") print ("Train set loaded!") if d is None: d = {"text":[], "label":[], "lookup_table":[]} d["lookup_table"] = d_tr["lookup_table"] d["text"] = d_tr["text"] + d_te["text"] d["label"] = d_tr["label"] + d_te["label"] s_senlen = stat_sentence_length(d) count = [i[1] for i in s_senlen] length = [i[0] for i in s_senlen] plt.plot(length, count, 'ro') plt.savefig("len_distribution.png") plt.show() return s_senlen, d def generate_stat_label(tr=None, te=None, d=None, train_path="yahoo_answers_train.pkl.gz", test_path="yahoo_answers_test.pkl.gz"): if (tr is None or te is None) and d is None: d_te = load_dataset(path="yahoo_answers_test.pkl.gz") print ("Test set loaded!") d_tr = load_dataset(path="yahoo_answers_train.pkl.gz") print ("Train set loaded!") if d is None: d = {"text":[], "label":[], "lookup_table":[]} d["lookup_table"] = d_tr["lookup_table"] d["text"] = d_tr["text"] + d_te["text"] d["label"] = d_tr["label"] + d_te["label"] s_label = stat_label(d) s_label = s_label.items() count = [i[1] for i in s_label] length = [i[0] for i in s_label] plt.plot(length, count, 'ro') plt.savefig("label_distribution.png") plt.show() return s_label, d if __name__ == "__main__": #d_tr, d_te = generate_pkl_gz(max_len=100) #s_word, d = generate_stat_word() s_senlen, d = generate_stat_sentence_length() s_label, d = generate_stat_label(d=d)
python
import time import struct import sys import os import re import threading from functools import partial import wx import wx.lib.newevent as NE from spidriver import SPIDriver PingEvent, EVT_PING = NE.NewEvent() def ping_thr(win): while True: wx.PostEvent(win, PingEvent()) time.sleep(1) class HexTextCtrl(wx.TextCtrl): def __init__(self, *args, **kwargs): super(HexTextCtrl, self).__init__(*args, **kwargs) self.Bind(wx.EVT_TEXT, self.on_text) def on_text(self, event): event.Skip() selection = self.GetSelection() value = self.GetValue().upper() hex = "0123456789ABCDEF" value = "".join([c for c in value if c in hex]) self.ChangeValue(value) self.SetSelection(*selection) class Frame(wx.Frame): def __init__(self): self.sd = None def widepair(a, b): r = wx.BoxSizer(wx.HORIZONTAL) r.Add(a, 1, wx.LEFT) r.AddStretchSpacer(prop=1) r.Add(b, 1, wx.RIGHT) return r def pair(a, b): r = wx.BoxSizer(wx.HORIZONTAL) r.Add(a, 1, wx.LEFT) r.Add(b, 0, wx.RIGHT) return r def rpair(a, b): r = wx.BoxSizer(wx.HORIZONTAL) r.Add(a, 0, wx.LEFT) r.Add(b, 1, wx.RIGHT) return r def label(s): return wx.StaticText(self, label = s) def hbox(items): r = wx.BoxSizer(wx.HORIZONTAL) [r.Add(i, 0, wx.EXPAND) for i in items] return r def hcenter(i): r = wx.BoxSizer(wx.HORIZONTAL) r.AddStretchSpacer(prop=1) r.Add(i, 2, wx.CENTER) r.AddStretchSpacer(prop=1) return r def vbox(items): r = wx.BoxSizer(wx.VERTICAL) [r.Add(i, 0, wx.EXPAND) for i in items] return r wx.Frame.__init__(self, None, -1, "SPIDriver") self.label_serial = wx.StaticText(self, label = "-", style = wx.ALIGN_RIGHT) self.label_voltage = wx.StaticText(self, label = "-", style = wx.ALIGN_RIGHT) self.label_current = wx.StaticText(self, label = "-", style = wx.ALIGN_RIGHT) self.label_temp = wx.StaticText(self, label = "-", style = wx.ALIGN_RIGHT) self.label_uptime = wx.StaticText(self, label = "-", style = wx.ALIGN_RIGHT) self.Bind(EVT_PING, self.refresh) self.ckCS = wx.CheckBox(self, label = "CS") self.ckA = wx.CheckBox(self, label = "A") self.ckB = wx.CheckBox(self, label = "B") self.ckCS.Bind(wx.EVT_CHECKBOX, self.check_cs) self.ckA.Bind(wx.EVT_CHECKBOX, self.check_a) self.ckB.Bind(wx.EVT_CHECKBOX, self.check_b) ps = self.GetFont().GetPointSize() fmodern = wx.Font(ps, wx.MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) def logger(): r = wx.TextCtrl(self, style=wx.TE_READONLY | wx.TE_RIGHT | wx.TE_DONTWRAP) r.SetBackgroundColour(wx.Colour(224, 224, 224)) r.SetFont(fmodern) return r self.txMISO = logger() self.txMOSI = logger() self.txVal = HexTextCtrl(self, size=wx.DefaultSize, style=0) self.txVal.SetMaxLength(2) self.txVal.SetFont(wx.Font(14 * ps // 10, wx.MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)) txButton = wx.Button(self, label = "Transfer") txButton.Bind(wx.EVT_BUTTON, partial(self.transfer, self.txVal)) txButton.SetDefault() self.allw = [self.ckCS, self.ckA, self.ckB, self.txVal, txButton, self.txMISO, self.txMOSI] [w.Enable(False) for w in self.allw] self.devs = self.devices() cb = wx.ComboBox(self, choices = sorted(self.devs.keys()), style = wx.CB_READONLY) cb.Bind(wx.EVT_COMBOBOX, self.choose_device) vb = vbox([ label(""), hcenter(cb), label(""), hcenter(pair( vbox([ label("Serial"), label("Voltage"), label("Current"), label("Temp."), label("Running"), ]), vbox([ self.label_serial, self.label_voltage, self.label_current, self.label_temp, self.label_uptime, ]) )), label(""), rpair(label("MISO"), self.txMISO), rpair(label("MOSI"), self.txMOSI), label(""), hcenter(pair(self.ckCS, hbox([self.ckA, self.ckB]))), label(""), hcenter(pair(self.txVal, txButton)), label(""), ]) self.SetSizerAndFit(vb) self.SetAutoLayout(True) if len(self.devs) > 0: d1 = min(self.devs) self.connect(self.devs[d1]) cb.SetValue(d1) t = threading.Thread(target=ping_thr, args=(self, )) t.setDaemon(True) t.start() def devices(self): if sys.platform == 'darwin': devdir = "/dev/" pattern = "^tty.usbserial-(........)" else: devdir = "/dev/serial/by-id/" pattern = "^usb-FTDI_FT230X_Basic_UART_(........)-" if not os.access(devdir, os.R_OK): return {} devs = os.listdir(devdir) def filter(d): m = re.match(pattern, d) if m: return (m.group(1), devdir + d) seldev = [filter(d) for d in devs] return dict([d for d in seldev if d]) def connect(self, dev): self.sd = SPIDriver(dev) [w.Enable(True) for w in self.allw] self.ckCS.SetValue(not self.sd.cs) self.ckA.SetValue(self.sd.a) self.ckB.SetValue(self.sd.b) self.refresh(None) def refresh(self, e): if self.sd: self.sd.getstatus() self.label_serial.SetLabel(self.sd.serial) self.label_voltage.SetLabel("%.2f V" % self.sd.voltage) self.label_current.SetLabel("%d mA" % self.sd.current) self.label_temp.SetLabel("%.1f C" % self.sd.temp) days = self.sd.uptime // (24 * 3600) rem = self.sd.uptime % (24 * 3600) hh = rem // 3600 mm = (rem / 60) % 60 ss = rem % 60; self.label_uptime.SetLabel("%d:%02d:%02d:%02d" % (days, hh, mm, ss)) def choose_device(self, e): self.connect(self.devs[e.EventObject.GetValue()]) def check_cs(self, e): if e.EventObject.GetValue(): self.sd.sel() else: self.sd.unsel() def check_a(self, e): self.sd.seta(e.EventObject.GetValue()) def check_b(self, e): self.sd.setb(e.EventObject.GetValue()) def transfer(self, htc, e): if htc.GetValue(): txb = int(htc.GetValue(), 16) rxb = struct.unpack("B", self.sd.writeread(struct.pack("B", txb)))[0] self.txMOSI.AppendText(" %02X" % txb) self.txMISO.AppendText(" %02X" % rxb) htc.ChangeValue("") if __name__ == '__main__': app = wx.App(0) f = Frame() f.Show(True) app.MainLoop()
python
#!/usr/bin/python """ To add users and see their passwords """ import sqlite3 from passlib.hash import pbkdf2_sha256 conn = sqlite3.connect('DB.db', check_same_thread=False) c = conn.cursor() c.execute('''CREATE table if not exists LOGIN(unix real, username TEXT, password TEXT, hash TEXT)''') print "Opened database successfully" def ReadNMR(): cursor = conn.execute('SELECT max(unix) FROM LOGIN') max_id = cursor.fetchone()[0] if isinstance(max_id, float): return max_id + 1 else: return 1 nmr = ReadNMR() while True: goal = raw_input("Read or Write") if(goal == "R"): cursor = conn.execute("SELECT unix, username, password, hash from LOGIN") for row in cursor: print "ID = ", row[0] print "USER = ", row[1] print "PASSWORD = ", row[2] print "HASH = ", row[3], "\n" elif(goal == "W"): user = raw_input("Username") psw = raw_input("Password") hash = pbkdf2_sha256.encrypt(psw) sql = "INSERT into LOGIN VALUES ("+ str(nmr) + ",'" + user + "', '"+ psw + "','"+ hash +"')" c.execute(sql) nmr = nmr + 1 print(nmr) conn.commit() elif(goal == "S"): query = raw_input("What do you want to search?") cursor = c.execute('SELECT * FROM LOGIN WHERE username=?', (query,)) for row in cursor: print "PASSWORD =",row[2] else: print(ReadNMR()) print "Operation done successfully"; conn.close()
python
import datetime class BaseQuery(object): supports_rolling = False supports_isolated_rolling = False def __init__(self, query_name, client, vars, log): self.log = log self.query_name = query_name self.client = client self.vars = vars self.result = None self.rolling = vars['rolling'] self.query_append = vars.get('query_append', '') self.lower_bound = float(vars.get('lower_bound', '0')) self.upper_bound = float(vars.get('upper_bound', 'inf')) if self.rolling: if not self.supports_rolling: msg = ('The specified query: "{query}" does not support the ' 'rolling argument.').format(query=self.query_name) raise Exception(msg) if not self.supports_isolated_rolling: today = datetime.date.today() begin = datetime.datetime.strptime(vars['begin_date'], '%Y-%m-%d') end = datetime.datetime.strptime(vars['end_date'], '%Y-%m-%d') if not (today >= begin.date() and today <= end.date()): msg = ('The rolling argument can only be used for ' 'date ranges that include today.') raise Exception(msg) def build_query(self): self.queries = {} if not self.query_bases or len(self.query_bases) == 0: raise Exception('Subclass must set query base') for query, query_string in self.query_bases.items(): self.queries[query] = query_string.format(**self.vars) + \ ' ' + self.query_append def set_defaults(self): pass def run(self): self.results = {} for query, query_string in self.queries.items(): self.log.debug('Executing query: {0}'.format(query_string)) self.results[query] = self.client.search_issues(query_string, expand='changelog', maxResults=False)
python
import tensorflow as tf hello = tf.constant('Hello, TF!') mylist = tf.Variable([3.142,3.201,4.019],tf.float16) mylist_rank = tf.rank(mylist) myzeros = tf.zeros([2,2,3]) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.global_variables_initializer()) print(sess.run(myzeros)) print(sess.run(mylist)) sess.run(tf.compat.v1.assign_add(mylist,[1,1,1])) print(sess.run(mylist)) with tf.compat.v1.Session() as sess: x = tf.compat.v1.placeholder(tf.int16, shape=(), name='x') y = tf.compat.v1.placeholder(tf.int16, shape=(), name='y') add = tf.add(x,y) mul = tf.multiply(x,y) print(sess.run(add, feed_dict={x:2,y:3})) print(sess.run(mul, feed_dict={x:2,y:3}))
python
# -*- coding: utf-8 -*- """ .. module:: NamedOpetope :synopsis: Implementation of the named approach for opetopes .. moduleauthor:: Cédric HT """ from copy import deepcopy from typing import ClassVar, Dict, List, Optional, Set, Tuple, Union from opetopy.common import * class Variable: """ A variable is just a string representing its name, annotated by an integer representing its dimension. """ dimension: int name: str def __eq__(self, other) -> bool: """ Tests syntactic equality between two variables. Two variables are equal if they have the same dimension and the same name. """ if not isinstance(other, Variable): raise NotImplementedError return self.name == other.name and self.dimension == other.dimension def __hash__(self): """ Return a hash of the variable. This is for Python purposes. """ return self.name.__hash__() def __init__(self, name: str, dim: int) -> None: if dim < 0 and name is not None: raise DerivationError( "Variable decrlaration", f"Dimension of new variable {name} must be >= 0 (is {dim})") self.dimension = dim self.name = name def __ne__(self, other) -> bool: if not isinstance(other, Variable): raise NotImplementedError return not (self == other) def __repr__(self) -> str: return f"{self.name}{self.dimension}" def __str__(self) -> str: return self.name def toTex(self) -> str: """ Returns the string representation of the variable, which is really just the variable name. """ return self.name class Term(Dict[Variable, 'Term']): """ An :math:`n`-term is represented as follows: * If it is degenerate, then the boolean attribute :py:attr:`NamedOpetope.Term.degenerate` is set to ``True``, and :py:attr:`NamedOpetope.Term.variable` is set to the variable name of which the current term is the degeneracy. * If it is non degenerate, then the boolean attribute :py:attr:`NamedOpetope.Term.degenerate` is set to ``False``, :py:attr:`NamedOpetope.Term.variable` is set to the variable name of the root node, and this class is otherwise used as a ``dict`` mapping :math:`(n-1)`-variables in the source to other :math:`n`-terms. """ degenerate: bool variable: Optional[Variable] def __contains__(self, var) -> bool: """ Checks if a variable is in the term. If the term is degenerate, always return ``False``. Otherwise, assume the term has dimension :math:`n`. * If the variable has dimension :math:`(n-1)`, then it checks against all keys in the underlying ``dict`` and if not found, calls the method recursively on all values of the underlying ``dict`` (which by construction are also :math:`n`-terms). * If the variable has :math:`n`, then it compares it to the root node (:py:attr:`NamedOpetope.Term.variable`), and if not equal, calls the method recursively on all values of the underlying ``dict`` (which by construction are also :math:`n`-terms). """ if not isinstance(var, Variable): raise NotImplementedError elif self.degenerate: return False elif var.dimension == self.dimension - 1: if var in self.keys(): return True else: for t in self.values(): if var in t: return True return False elif var.dimension == self.dimension: if var == self.variable: return True else: for t in self.values(): if var in t: return True return False else: return False def __eq__(self, other) -> bool: """ Tests if two terms are syntactically equal. """ if not isinstance(other, Term): raise NotImplementedError elif self.variable is None and other.variable is None: return True elif self.variable != other.variable or \ self.degenerate != other.degenerate: return False elif len(self.keys()) == len(other.keys()): for k in self.keys(): if k not in other.keys() or self[k] != other[k]: return False return True else: return False def __init__(self, var: Optional[Variable] = None, degen: bool = False) -> None: """ Creates a term from a :class:`opetopy.NamedOpetope.Variable` ``var``. If it is ``None`` (default), then this term represents the unique :math:`(-1)`-term. """ self.degenerate = degen self.variable = var def __ne__(self, other) -> bool: return not (self == other) def __repr__(self) -> str: return str(self) def __str__(self) -> str: if self.dimension == -1: return "∅" elif self.degenerate: return "_" + str(self.variable) elif len(self.keys()) == 0: return str(self.variable) else: grafts = [str(k) + " ← " + str(self[k]) for k in self.keys()] return str(self.variable) + "(" + ", ".join(grafts) + ")" @property def dimension(self) -> int: """ Returns the dimension of the term. If its :py:attr:`NamedOpetope.Term.variable` is ``None``, then it is :math:`-1` by convention. If it is degenerate, then it is the dimension of :py:attr:`NamedOpetope.Term.variable` :math:`+1`, otherwise just the dimension of :py:attr:`NamedOpetope.Term.variable`. """ if self.variable is None: return -1 elif self.degenerate: return self.variable.dimension + 1 else: return self.variable.dimension def graftTuples(self) -> Set[Tuple[Variable, Variable]]: """ This helper function constructs the set of tuples (b, a) for all variables a and b such that the expression :math:`b \\leftarrow a (\\ldots)` occurs in the term. """ res = set() # type: Set[Tuple[Variable, Variable]] for k in self.keys(): if not self[k].degenerate: a = self[k].variable if a is None: raise RuntimeError( f"[Term, graftTuples] An invalid / null term has been " f"grafted at variable {str(k)} in term {str(self)}. In " f"valid proof trees, this should not happen") res |= set({(k, a)}) | self[k].graftTuples() return res def isVariable(self) -> bool: """ Tells wether this term is in fact just a variable. """ return self.variable is not None and not self.degenerate \ and len(self.keys()) == 0 def toTex(self) -> str: """ Converts the term to TeX code. """ if self.dimension == -1 or self.variable is None: return "\\emptyset" elif self.degenerate: return "\\underline{" + self.variable.toTex() + "}" elif len(self.keys()) == 0: return self.variable.toTex() else: grafts = [ k.toTex() + " \\leftarrow " + self[k].toTex() for k in self.keys() ] return self.variable.toTex() + "(" + ", ".join(grafts) + ")" def variables(self, k) -> Set[Variable]: """ Returns the set of all :math:`k` variables contained in the term. Note that degenerate terms don't containe any variables. :see: :meth:`NamedOpetope.Term.__contains__` """ if self.degenerate or self.variable is None: return set() else: res = set() # type: Set[Variable] if self.variable.dimension == k: res |= {self.variable} for a in self.keys(): if a.dimension == k: res |= {a} res |= self[a].variables(k) return res class Type: """ An :math:`n`-type is a sequence of :math:`(n+1)` terms of dimension :math:`(n-1), (n-2), \\ldots, -1`. """ dimension: int terms: List[Term] def __contains__(self, var) -> bool: """ Checks wether a given variable appears in at least one term of the type. """ if not isinstance(var, Variable): raise NotImplementedError for t in self.terms: if var in t: return True return False def __init__(self, terms: List[Term]) -> None: """ Creates a new type from a list of term. The dimension is inferred from the length of the list, and the terms are checked to have the correct dimension. If the list has length :math:`(n+1)`, then the type's dimension will be :math:`n`, and the dimension of the :math:`i` th term in the list must be :math:`n - i - 1` (recall that Python index start at :math:`0`, whence the :math:`-1` correction factor). """ if len(terms) < 1: raise DerivationError("Type declaration", "A type requires at least one term") self.dimension = len(terms) - 1 self.terms = terms for i in range(len(self.terms)): if self.terms[i].dimension != self.dimension - i - 1: raise DerivationError( "Type declaration", f"Invalid dimensions in term list: {i}th term " f"{str(self.terms[i])} has " f"dimension {self.terms[i].dimension}, " f"sould have {self.dimension - i - 1}") def __repr__(self) -> str: return str(self) def __str__(self) -> str: return " ⊷ ".join([str(t) for t in self.terms]) def toTex(self) -> str: """ Converts the type to TeX code. """ return " \\blackwhitespoon ".join([t.toTex() for t in self.terms]) def variables(self, k: int) -> Set[Variable]: """ Returns the set of all :math:`k` variables contained in the terms of the type. Note that degenerate terms don't containe any variables. :see: :meth:`NamedOpetope.Term.__contains__` :see: :meth:`NamedOpetope.Term.variables` """ res = set() # type: Set[Variable] for t in self.terms: res |= t.variables(k) return res class Typing: """ A typing is simply an :math:`n`-term (:class:`opetopy.NamedOpetope.Term`) together with an :math:`n`-type (:class:`opetopy.NamedOpetope.Type`). """ term: Term type: Type def __hash__(self): return self.toTex().__hash__() def __init__(self, term, type) -> None: if term.dimension != type.dimension: raise DerivationError( "Typing declaration", "Dimension mismatch in typing: term has dimension " f"{term.dimension}, type has dimension {type.dimension}") self.term = term self.type = type def __repr__(self) -> str: return str(self) def __str__(self) -> str: return str(self.term) + " : " + str(self.type) def toTex(self) -> str: return self.term.toTex() + " : " + self.type.toTex() class Context(Set[Typing]): """ A context is a set of tyings (see :class:`opetopy.NamedOpetope.Typing`). """ def __add__(self, typing: Typing) -> 'Context': """ Adds a variable typing to a deep copy of the context context, if the typed variable isn't already typed in the context. """ if not typing.term.isVariable(): raise DerivationError( "Context, new typing", f"Context typings only type variables, and {str(typing.term)} " "is not one") elif typing.term.variable in self: raise DerivationError( "Context, new typing", f"Variable {str(typing.term.variable)} is already typed in " "this context" ) else: res = deepcopy(self) res.add(typing) return res def __and__(self, other) -> 'Context': """ Returns the intersection of two contexts, i.e. the set of typings of the first context whose typed variable is in the second """ res = Context() for typing in self: if typing.term.variable in other: res += typing return res def __contains__(self, var) -> bool: """ Tests wether the variable ``var`` is typed in this context. """ if not isinstance(var, Variable): raise NotImplementedError for typing in self: if Term(var) == typing.term: return True return False def __getitem__(self, name: str) -> Variable: """ Returns the varible term in current context whose name is ``name``. """ for typing in self: if typing.term.isVariable and \ typing.term.variable is not None and \ typing.term.variable.name == name: return typing.term.variable raise DerivationError("Context, get variable", f"Context types no variable named {name}") def __or__(self, other): """ Returns the union of two compatible contexts. """ res = deepcopy(self) for t in other: if t.term.variable not in res: res += t return res def __repr__(self) -> str: return str(self) def __str__(self) -> str: return ", ".join([str(t) for t in self]) def graftTuples(self) -> Set[Tuple[Variable, Variable]]: """ Returns all tuples (b, a) for :math:`b \\leftarrow a (\\ldots)` a grafting occurring in a term in a type in the context. :see: :meth:`opetopy.NamedOpetope.Term.graftTuples` :see: :func:`opetopy.NamedOpetopicSet.repres` """ res = set() # type: Set[Tuple[Variable, Variable]] for typing in self: for t in typing.type.terms: res |= t.graftTuples() return res def source(self, var: Variable, k: int = 1) -> Term: """ Returns the :mathm``k``-source of a variable. """ if k < 0 or k > var.dimension + 1: raise DerivationError( "Context, source computation", "Index out of bounds: dimension of variable {var} is {dim}, " "so index should be between 0 and {max} included " "(is {k})", var=str(var), dim=var.dimension, max=var.dimension + 1, k=k) elif var not in self: raise DerivationError( "Context, source computation", "Variable {var} with dimension {dim} is not typed in context, " "so computing its source is not possible", var=str(var), dim=var.dimension) elif k == 0: return Term(var) else: return self.typeOf(var).terms[k - 1] def toTex(self) -> str: """ Converts the type to TeX code. """ return ", ".join([t.toTex() for t in self]) def typeOf(self, var: Variable) -> Type: """ Returns the type of a variable. """ for typing in self: if typing.term == Term(var): return typing.type raise DerivationError( "Context, type computation", "Variable {var} with dimension {dim} is not typed in context, so " "computing its type is not possible", var=str(var), dim=var.dimension) def variables(self) -> Set[Variable]: """ Return the set of all variables typed in the context. """ return set([ typing.term.variable for typing in self if typing.term.variable is not None ]) class EquationalTheory: """ An equational theory (among variables), is here represented as a partition of a subset of the set of all variables. Is is thus a list of sets of variables. (set of sets isn't possible as python ``set`` isn't hashable) """ classes: List[Set[Variable]] def __add__(self, eq: Tuple[Variable, Variable]) -> 'EquationalTheory': """ Adds an equality (represented by a tuple of two :class:`opetopy.NamedOpetope.Variable`) to the theory. """ a, b = eq if a.dimension != b.dimension: raise DerivationError( "Eq. th. extension", "Dimension mismatch in new equality {a} = {b}: respective " "dimensions are {da} and {db}", a=str(a), b=str(b), da=a.dimension, db=b.dimension) else: ia = self._index(a) ib = self._index(b) res = deepcopy(self) if ia == -1 and ib == -1: # Neither a nor b are in a class res.classes += [set({a, b})] elif ia == -1 and ib != -1: # b is in a class but not a res.classes[ib].add(a) elif ia != -1 and ib == -1: # a is in a class but not b res.classes[ia].add(b) elif ia != ib: # a and b are in different classes res.classes[ia] |= res.classes[ib] del res.classes[ib] return res def __init__(self) -> None: self.classes = [] def __or__(self, other: 'EquationalTheory') -> 'EquationalTheory': """ Returns the union of two equational theories """ res = deepcopy(self) for cls in other.classes: lcls = list(cls) for i in range(1, len(lcls)): res += (lcls[0], lcls[i]) return res def __repr__(self) -> str: return str(self) def __str__(self) -> str: cls = [ "{" + ", ".join([str(x) for x in c]) + "}" for c in self.classes ] return ", ".join(cls) def _index(self, a: Variable) -> int: """ Returns the index (in :py:attr:`NamedOpetope.EquationalTheory.classes`) of the class of the variable ``a``, or `-1` of the class doesn't exist. """ for i in range(len(self.classes)): if a in self.classes[i]: return i return -1 def classOf(self, a: Variable) -> Set[Variable]: """ Returns the class of a variable. """ ia = self._index(a) if ia == -1: return set({a}) else: return self.classes[ia] def equal(self, a: Variable, b: Variable) -> bool: """ Tells wether variables (:class:`opetopy.NamedOpetope.Variable`) ``a`` and ``b`` are equal modulo the equational theory. """ ia = self._index(a) if ia == -1: return a == b else: return b in self.classes[ia] def isIn(self, var: Variable, term: Term) -> bool: """ Tells wether a variable is in a term modulo the equational theory of the sequent. :see: :meth:`NamedOpetope.Term.__contains__`. """ for v in self.classOf(var): if v in term: return True return False def toTex(self) -> str: cls = [ "\\left\\{" + ", ".join([x.toTex() for x in c]) + "\\right\\}" for c in self.classes ] return ", ".join(cls) class OCMT: """ Opetopic context modulo theory. Basically the same as a :class:`opetopy.NamedOpetope.Sequent`, without the typing. """ theory: EquationalTheory context: Context targetSymbol: str = "t" def __init__(self, theory: EquationalTheory, context: Context) -> None: self.context = context self.theory = theory def __repr__(self) -> str: return str(self) def __str__(self) -> str: return "{th} ▷ {ctx}".format(th=str(self.theory), ctx=str(self.context)) def equal(self, t: Term, u: Term) -> bool: """ Tells wether two terms ``t`` and ``u`` are equal modulo the equational theory. :see: Similar method for variables only: :meth:`NamedOpetope.EquationalTheory.equal` """ if t.variable is None or u.variable is None: if t.variable is not None or u.variable is not None: return False return True elif t.degenerate != u.degenerate: return False elif not self.theory.equal(t.variable, u.variable): return False elif len(t.keys()) != len(u.keys()): return False else: for kt in t.keys(): ku = None for l in u.keys(): if self.theory.equal(kt, l): ku = l break if ku is None: return False elif not self.equal(t[kt], u[ku]): return False return True def isIn(self, var: Variable, term: Term) -> bool: """ Tells wether a variable is in a term modulo the equational theory of the sequent. :see: :meth:`NamedOpetope.EquationalTheory.isIn` :see: :meth:`NamedOpetope.Term.__contains__` """ return self.theory.isIn(var, term) def source(self, var: Variable, k: int = 1) -> Term: """ Returns the :mathm``k``-source of a variable. :see: :meth:`NamedOpetope.Context.source` """ return self.context.source(var, k) def target(self, var: Variable, k: int = 1) -> Variable: """ Returns the :math:`k` target of a variable. """ if var.dimension == 0: raise DerivationError( "OCMT, target computation", "Cannot compute target of 0-dimensional variable {var}", var=str(var)) else: return Variable((OCMT.targetSymbol * k) + var.name, var.dimension - k) def toTex(self) -> str: return self.theory.toTex() + " \\smalltriangleright " + \ self.context.toTex() def typeOf(self, var: Variable) -> Type: """ Returns the type of a variable. :see: :meth:`NamedOpetope.Context.typeOf` """ return self.context.typeOf(var) class Sequent(OCMT): """ A sequent consists of an equational theory (:class:`opetopy.NamedOpetope.EquationalTheory`), a context (:class:`opetopy.NamedOpetope.Context`), and a typing (:class:`opetopy.NamedOpetope.Typing`). """ typing: Typing """ This variable specifies if contexts should be displayed in :meth:`NamedOpetope.Sequent.toTex` """ texContexts: ClassVar[bool] = True def __init__(self, theory: EquationalTheory, context: Context, typing: Typing) -> None: super().__init__(theory, context) self.typing = typing def __repr__(self) -> str: return str(self) def __str__(self) -> str: return "{th} ▷ {ctx} ⊢ {typ}".format(th=str(self.theory), ctx=str(self.context), typ=str(self.typing)) def graft(self, t: Term, x: Variable, u: Term) -> Term: """ Grafts term (:class:`opetopy.NamedOpetope.Term`) u on term t via variable (:class:`opetopy.NamedOpetope.Variable`) x. In other words, computes :math:`t(x \\leftarrow u)`. """ for k in t.keys(): if self.theory.equal(k, x): raise DerivationError( "Sequent, grafting", "Variable {var} in term {term} has already been used for " "a grafting", var=str(x), term=str(t)) if t.variable is None: raise DerivationError("Sequent, grafting", "Term to be grafted onto is empty") elif t.degenerate: if t.variable == x: return deepcopy(u) else: raise DerivationError( "Sequent, grafting", "Incompatible graft: term {term} is degenerate, so the " "grafting variable must be {var} (is {x})", term=str(t), var=str(t.variable), x=str(x)) else: r = deepcopy(t) if self.isIn(x, self.source(t.variable, 1)): r[x] = u else: for k in r.keys(): r[k] = self.graft(r[k], x, u) return r def substitute(self, u: Term, s: Term, a: Variable) -> \ Tuple[Term, Optional[Tuple[Variable, Variable]]]: """ Substitute term (:class:`opetopy.NamedOpetope.Term`) ``s`` for variable (:class:`opetopy.NamedOpetope.Variable`) ``a`` in term ``u``. In other words, computes :math:`u[s/a]`. Returns a tuple containing 1. the resulting substitution 2. an new equality to add to the equational theory, or ``None`` """ if s.variable is None: raise DerivationError("Sequent, substitute", "Cannot substitute in the null term") elif u.variable is None: raise DerivationError("Sequent, substitute", "Cannot substitute with the null term") elif s.degenerate: if a in [v.variable for v in u.values()]: # a appears grafted on the root of u # ta = None # Term grafted in the root of u whose root is a # ka = None # Key of ta for k in u.keys(): if u[k].variable == a: ta = u[k] ka = k break if len(ta.keys()) == 0: # ta is just the variable a r = deepcopy(u) del r[ka] return (r, (s.variable, ka)) else: # ta has graftings on its root a if len(ta.values()) != 1: # that grafting should be unique assert RuntimeError( "[Sequent, substitution] Term " "{term} was expected to be " "globular... In valid proof " "trees, this error shouldn't " "happen, so congratulations, " "you broke everything".format(term=repr(ta))) r = deepcopy(u) r[ka] = list(ta.values())[0] return (r, (s.variable, ka)) else: r = deepcopy(u) e = None for k in r.keys(): r[k], f = self.substitute(r[k], s, a) if f is not None: e = f return (r, e) else: if self.theory.equal(u.variable, a): r = deepcopy(s) for k in u.keys(): r = self.graft(r, k, u[k]) return (r, None) else: r = deepcopy(u) for k in r.keys(): r[k] = self.substitute(r[k], s, a)[0] return (r, None) def toTex(self) -> str: if Sequent.texContexts: return self.theory.toTex() + " \\smalltriangleright " + \ self.context.toTex() + \ " \\vdash_{" + str(self.typing.term.dimension) + "} " + \ self.typing.toTex() else: return self.theory.toTex() + " \\vdash_{" + \ str(self.typing.term.dimension) + "} " + self.typing.toTex() def point(name: str) -> Sequent: """ The :math:`\\textbf{Opt${}^!$}` :math:`\\texttt{point}` rule. Introduces a :math:`0`-variable with name ``x``. """ t = Typing(Term(Variable(name, 0)), Type([Term()])) return Sequent(EquationalTheory(), Context() + t, t) def shift(seq: Sequent, name: str) -> Sequent: """ The :math:`\\textbf{Opt${}^!$}` :math:`\\texttt{shift}` rule. Takes a sequent ``seq`` typing a term ``t`` and introduces a new variable ``x`` having ``t`` as :math:`1`-source. """ var = Variable(name, seq.typing.term.dimension + 1) if var in seq.context: raise DerivationError("shift rule", "Variable {var} already typed in context", var=name) res = deepcopy(seq) typing = Typing(Term(var), Type([seq.typing.term] + seq.typing.type.terms)) res.context += typing res.typing = typing return res def degen(seq: Sequent) -> Sequent: """ The :math:`\\textbf{Opt${}^!$}` :math:`\\texttt{degen}` rule. Takes a sequent typing a variable and produces a new sequent typing the degeneracy at that variable. """ if not seq.typing.term.isVariable(): raise DerivationError( "degen rule", "Term {term} typed in premiss sequent is expected to be a " "variable", term=str(seq.typing.term)) res = deepcopy(seq) var = res.typing.term.variable res.typing = Typing(Term(var, True), Type([Term(var)] + res.typing.type.terms)) return res def degenfill(seq: Sequent, name: str) -> Sequent: """ The :math:`\\textbf{Opt${}^!$}` :math:`\\texttt{degen-shift}` rule. Applies the degen and the shift rule consecutively. """ return shift(degen(seq), name) def graft(seqt: Sequent, seqx: Sequent, name: str) -> Sequent: """ The :math:`\\textbf{Opt${}^!$}` :math:`\\texttt{graft}` rule. Takes the following arguments: 1. ``seqt`` typing an :math:`n` term :math:`t` 2. ``seqx`` second typing an :math:`n` variable :math:`x` 3. an :math:`(n-1)` variable ``a`` onto which to operate the grafting, specified by its name ``name`` such that the two sequents are compatible, and the intersection of their context is essentially the context typing ``a`` and its variables. It then produces the :math:`n` term :math:`t(a \\leftarrow x)`. The way the intersection condition is checked is by verifying that the only variables typed in both contexts (modulo both theories) are those appearing in the type of ``a`` or of course ``a`` itself. """ if seqt.typing.term.variable is None: raise DerivationError( "graft rule", "First premiss sequent types an invalid / null term") elif seqx.typing.term.variable is None: raise DerivationError( "graft rule", "Second premiss sequent types an invalid / null term") a = Variable(name, seqt.typing.term.dimension - 1) # checking intersection inter = seqt.context & seqx.context typea = seqt.typeOf(a) if a not in seqt.context: # a in the first sequent raise DerivationError( "graft rule", "Graft variable {var} not typed in first sequent", var=str(a)) for i in range(0, a.dimension): # all variables in the type of a are in for v in typea.variables(i): # the context intersection if v not in inter: raise DerivationError( "graft rule", "Intersection of the two premiss contexts does not " "type variable {v} necessary to define variable {a}", v=str(v), a=str(a)) for typing in inter: # all variables in the intersection are in that of a w = typing.term.variable if w not in typea: raise DerivationError( "graft rule", "Intersection of the two premiss contexts, variable {v} " "is typed, but is not required to type variable {a}", v=str(w), a=a.toTex()) # checking rule hypothesis if not seqx.typing.term.isVariable(): raise DerivationError( "graft rule", "Second premiss sequent expected to type a variable (types " "{term})", term=str(seqx.typing.term)) elif a not in seqt.typing.type.terms[0]: raise DerivationError( "graft rule", "Graft variable {a} does not occur in the source of the term" "{term} grafted upon", a=str(a), term=str(seqt.typing.term)) elif a in seqt.typing.term: raise DerivationError( "graft rule", "Graft variable {a} occurs first premiss term {term}, meaning it " " has already been used for grafting", a=str(a), term=str(seqt.typing.term)) elif not seqt.equal(seqt.source(a, 1), seqx.source(seqx.typing.term.variable, 2)): raise DerivationError( "graft rule", "Variables {a} and {x} have incompatible shapes: s{a} = {sa}, " "while ss{x} = {ssx}", a=str(a), x=str(seqx.typing.term.variable), sa=str(seqt.source(a, 1)), ssx=str(seqx.source(seqx.typing.term.variable, 2))) # forming conclusion sequent theory = seqt.theory | seqx.theory # union of both theories context = seqt.context | seqx.context # union of both contexts term = seqt.graft(seqt.typing.term, a, seqx.typing.term) # new term s1, eq = seqt.substitute( seqt.typing.type.terms[0], # 1st source of seqx.typing.type.terms[0], a) # that new term type = deepcopy(seqt.typing.type) # the type of the new term is that of t type.terms[0] = s1 # except for the 1st source, which is s1 if eq is not None: # add new equation on theory if needed theory += eq return Sequent(theory, context, Typing(term, type)) class RuleInstance(AbstractRuleInstance): """ A rule instance of system :math:`\\textbf{Opt${}^!$}`. """ def eval(self) -> Sequent: """ Pure virtual method evaluating a proof tree and returning the final conclusion sequent, or raising an exception if the proof is invalid. """ raise NotImplementedError() class Point(RuleInstance): """ A class representing an instance of the ``point`` rule in a proof tree. """ variableName: str def __init__(self, name: str) -> None: self.variableName = name def __repr__(self) -> str: return "Point({})".format(self.variableName) def __str__(self) -> str: return "Point({})".format(self.variableName) def _toTex(self) -> str: """ Converts the proof tree in TeX code. This method should not be called directly, use :meth:`NamedOpetope.RuleInstance.toTex` instead. """ return "\\AxiomC{}\n\t\\RightLabel{\\texttt{point}}\n\t" + \ "\\UnaryInfC{$" + self.eval().toTex() + "$}" def eval(self) -> Sequent: """ Evaluates the proof tree, in this cases returns the point sequent by calling :func:`opetopy.NamedOpetope.point`. """ return point(self.variableName) class Degen(RuleInstance): """ A class representing an instance of the ``degen`` rule in a proof tree. """ proofTree: RuleInstance def __init__(self, p: RuleInstance) -> None: """ Creates an instance of the ``degen`` rule and plugs proof tree ``p`` on the unique premise. """ self.proofTree = p def __repr__(self) -> str: return "Degen({})".format(repr(self.proofTree)) def __str__(self) -> str: return "Degen({})".format(str(self.proofTree)) def _toTex(self) -> str: """ Converts the proof tree in TeX code. This method should not be called directly, use :meth:`NamedOpetope.RuleInstance.toTex` instead. """ return self.proofTree._toTex() + \ "\n\t\\RightLabel{\\texttt{degen}}\n\t\\UnaryInfC{$" + \ self.eval().toTex() + "$}" def eval(self) -> Sequent: """ Evaluates this instance of ``degen`` by first evaluating its premise, and then applying :func:`opetopy.NamedOpetope.degenerate` on the resulting sequent. """ return degen(self.proofTree.eval()) class Shift(RuleInstance): """ A class representing an instance of the ``shift`` rule in a proof tree. """ proofTree: RuleInstance variableName: str def __init__(self, p: RuleInstance, name: str) -> None: self.proofTree = p self.variableName = name def __repr__(self) -> str: return "Shift({}, {})".format(repr(self.proofTree), self.variableName) def __str__(self) -> str: return "Shift({}, {})".format(str(self.proofTree), self.variableName) def _toTex(self) -> str: """ Converts the proof tree in TeX code. This method should not be called directly, use :meth:`NamedOpetope.RuleInstance.toTex` instead. """ return self.proofTree._toTex() + \ "\n\t\\RightLabel{\\texttt{shift}}\n\t\\UnaryInfC{$" + \ self.eval().toTex() + "$}" def eval(self) -> Sequent: return shift(self.proofTree.eval(), self.variableName) class DegenFill(RuleInstance): """ A class representing an instance of the ``degen-shift`` rule in a proof tree. """ proofTree: RuleInstance def __init__(self, p: RuleInstance, name: str) -> None: self.proofTree = Shift(Degen(p), name) self.eval() def __repr__(self) -> str: return repr(self.proofTree) def __str__(self) -> str: return str(self.proofTree) def _toTex(self) -> str: """ Converts the proof tree in TeX code. This method should not be called directly, use :meth:`NamedOpetope.RuleInstance.toTex` instead. """ return self.proofTree._toTex() def eval(self) -> Sequent: return self.proofTree.eval() class Graft(RuleInstance): """ A class representing an instance of the ``graft`` rule in a proof tree. """ proofTree1: RuleInstance proofTree2: RuleInstance variableName: str def __init__(self, p1: RuleInstance, p2: RuleInstance, a: str) -> None: """ Creates an instance of the ``graft`` rule at variable ``a``, and plugs proof tree ``p1`` on the first premise, and ``p2`` on the second. :see: :func:`opetopy.NamedOpetope.graft`. """ self.proofTree1 = p1 self.proofTree2 = p2 self.variableName = a self.eval() def __repr__(self) -> str: return "Graft({p1}, {p2}, {a})".format(p1=repr(self.proofTree1), p2=repr(self.proofTree2), a=self.variableName) def __str__(self) -> str: return "Graft({p1}, {p2}, {a})".format(p1=str(self.proofTree1), p2=str(self.proofTree2), a=self.variableName) def _toTex(self) -> str: """ Converts the proof tree in TeX code. This method should not be called directly, use :meth:`NamedOpetope.RuleInstance.toTex` instead. """ return self.proofTree1._toTex() + "\n\t" + self.proofTree2._toTex() + \ "\n\t\\RightLabel{\\texttt{graft-}$" + \ self.variableName + "$}\n\t\\BinaryInfC{$" + \ self.eval().toTex() + "$}" def eval(self) -> Sequent: """ Evaluates this instance of ``graft`` by first evaluating its premises, and then applying :func:`opetopy.NamedOpetope.graft` at variable ``self.variableName`` on the resulting sequents. """ return graft(self.proofTree1.eval(), self.proofTree2.eval(), self.variableName) def Arrow(pointName: str = "a", arrowName: str = "f") -> RuleInstance: """ Returns the proof tree of the arrow, with cell names as specified in the arguments. """ return Shift(Point(pointName), arrowName) def OpetopicInteger(n: int, pointName: str = "a", arrowName: str = "f", cellName: str = "A") -> RuleInstance: """ Returns the proof tree of the :math:`n`-th opetopic integer. * if ``n`` is 0, then the unique point is named ``pointName`` (default ``a``), and the unique :math:`2`-cell is named ``cellName`` (default ``A``). * otherwise, the points are named ``a_1``, ``a_2``, ... ``a_n-1`` (with added braces if the index exceeds 10, so that it is :math:`\\TeX` friendly), arrows ``f_1``, ... ``f_n``. Those names can be changed by specifying the ``pointName`` and ``arrowName`` arguments. The unique :math:`2`-cell is named ``cellName`` (default ``A``). """ if n < 0: raise DerivationError("Opetopic integer", "Parameter n must be >=0 (is {n})", n=n) elif n == 0: return DegenFill(Point(pointName), cellName) else: def toTex(i: int) -> str: if 0 <= i and i < 10: return str(i) else: return "{" + str(i) + "}" pointNames = [pointName + "_" + toTex(i) for i in range(1, n + 1)] arrowNames = [arrowName + "_" + toTex(i) for i in range(1, n + 1)] arrows = [ Shift(Point(pointNames[i - 1]), arrowNames[i - 1]) for i in range(1, n + 1) ] res = arrows[0] # type: Union[Shift, Graft] for i in range(1, n): res = Graft(res, arrows[i], pointNames[i - 1]) return Shift(res, cellName)
python
# -*- coding: utf-8 -*- from flask import Flask # 引入 flask from flask import redirect from flask import render_template from flask import url_for from flask_cors import CORS from config import GlobalVar app = Flask(__name__, template_folder=GlobalVar.BASE_DIR + '/templates') # 实例化一个flask 对象 CORS(app) from app.controller import micro_service,message,system,user # from app import views @app.route('/') def index(): return render_template('index.html')
python
# Copyright 2013 Red Hat, Inc. # 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. """ Use gzip compression if the client accepts it. """ import re from oslo_log import log as logging from glance.common import wsgi from glance import i18n LOG = logging.getLogger(__name__) _LI = i18n._LI class GzipMiddleware(wsgi.Middleware): re_zip = re.compile(r'\bgzip\b') def __init__(self, app): LOG.info(_LI("Initialized gzip middleware")) super(GzipMiddleware, self).__init__(app) def process_response(self, response): request = response.request accept_encoding = request.headers.get('Accept-Encoding', '') if self.re_zip.search(accept_encoding): # NOTE(flaper87): Webob removes the content-md5 when # app_iter is called. We'll keep it and reset it later checksum = response.headers.get("Content-MD5") # NOTE(flaper87): We'll use lazy for images so # that they can be compressed without reading # the whole content in memory. Notice that using # lazy will set response's content-length to 0. content_type = response.headers["Content-Type"] lazy = content_type == "application/octet-stream" # NOTE(flaper87): Webob takes care of the compression # process, it will replace the body either with a # compressed body or a generator - used for lazy com # pression - depending on the lazy value. # # Webob itself will set the Content-Encoding header. response.encode_content(lazy=lazy) if checksum: response.headers['Content-MD5'] = checksum return response
python
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import re import os from urllib.parse import urljoin from datetime import datetime from bs4 import BeautifulSoup from ferenda import util from ferenda import DocumentEntry from ferenda.sources.legal.se import SwedishLegalSource class PBR(SwedishLegalSource): alias = "pbr" start_url = "http://www.pbr.se/malregister?sok=&mnr=&mntp=hfd&sak=&dtx=&ktp=&knm=&kob=&mnm=&mob=&klass=&jus=&tes=&lag=&prf=&d1typ=&d1min=&d1max=&d2typ=&d2min=&d2max=&patent=1&vm=1&monster=1&namn=1&vxt=1&ubevis=1&u_bifall=1&u_bifall2=1&u_fastst=1&u_avslag=1&u_avskr=1&u_avvis=1&u_annan=1&vagledande=1&intressant=1&ovrigt=1&esf=&ekf=1" download_iterlinks = False storage_policy = "dir" def download_get_basefiles(self, source): current_url = self.start_url soup = BeautifulSoup(source, "lxml") self.log.debug(soup.find("div", "traffinfo").get_text()) done = False pageidx = 1 while not done: self.log.debug("loading page %s of results" % pageidx) for f in soup.find_all("div", "rad"): link_el = f.find("a", "block") link = urljoin(self.start_url, link_el["href"]) basefile = link.rsplit("?malnr=")[1].replace(" ", "_") # we store the snippet since it's the only place where the # PRVnr metadata is shown with self.store.open_downloaded(basefile, attachment="snippet.html", mode="w") as fp: fp.write(str(f)) yield basefile, link self.log.debug("Looking for link %s on ...%s" % (pageidx+1, current_url[-20:])) next_el = soup.find("a", text=str(pageidx+1)) if not next_el: self.log.debug("Looking for link > on ...%s" % current_url[-20:]) next_el = soup.find("a", text=">") if next_el: pageidx += 1 current_url = urljoin(current_url, next_el["href"]) resp = self.session.get(current_url) resp.raise_for_status() soup = BeautifulSoup(resp.text, "lxml") else: self.log.debug("Didn't find it, we must be done!") done = True def download_single(self, basefile, url): updated = False created = False filename = self.store.downloaded_path(basefile) created = not os.path.exists(filename) # util.print_open_fds() if self.download_if_needed(url, basefile): if created: self.log.info("%s: downloaded from %s" % (basefile, url)) else: self.log.info( "%s: downloaded new version from %s" % (basefile, url)) updated = True else: self.log.debug("%s: exists and is unchanged" % basefile) soup = BeautifulSoup(util.readfile(filename), "lxml") for pdflink in soup.find_all("a", href=re.compile("\.pdf$")): slug = "-".join(pdflink["href"].rsplit("/")[-2:]) attachment_path = self.store.downloaded_path(basefile, attachment=slug) self.download_if_needed(urljoin(url, pdflink["href"]), basefile, filename=attachment_path) vm = soup.find("a", text="Visa Varumärke") if vm: attachment_path = self.store.downloaded_path(basefile, attachment="varumarke.jpg") attachment_url = re.search("http[^'\"]*", vm["href"]).group(0) self.download_if_needed(attachment_url, basefile, filename=attachment_path) entry = DocumentEntry(self.store.documententry_path(basefile)) now = datetime.now() entry.orig_url = url if created: entry.orig_created = now if updated: entry.orig_updated = now entry.orig_checked = now entry.save()
python
# -*- coding: utf-8 -*- # Copyright 2018 IBM. # # 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. # ============================================================================= """The Exact LinearProblem algorithm.""" import logging import numpy as np from qiskit.aqua.algorithms import QuantumAlgorithm from qiskit.aqua import AquaError logger = logging.getLogger(__name__) class ExactLPsolver(QuantumAlgorithm): """The Exact LinearProblem algorithm.""" CONFIGURATION = { 'name': 'ExactLPsolver', 'description': 'ExactLPsolver Algorithm', 'classical': True, 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'ExactLPsolver_schema', 'type': 'object', 'properties': { }, 'additionalProperties': False }, 'problems': ['linear_system'] } def __init__(self, matrix=None, vector=None): """Constructor. Args: matrix (array): the input matrix of linear system of equations vector (array): the input vector of linear system of equations """ self.validate(locals()) super().__init__() self._matrix = matrix self._vector = vector self._ret = {} @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: LinearSystemInput instance """ if algo_input is None: raise AquaError("LinearSystemInput instance is required.") matrix = algo_input.matrix vector = algo_input.vector if not isinstance(matrix, np.ndarray): matrix = np.asarray(matrix) if not isinstance(vector, np.ndarray): vector = np.asarray(vector) if matrix.shape[0] != len(vector): raise ValueError("Input vector dimension does not match input " "matrix dimension!") if matrix.shape[0] != matrix.shape[1]: raise ValueError("Input matrix must be square!") return cls(matrix, vector) def _solve(self): self._ret['eigvals'] = np.linalg.eig(self._matrix)[0] self._ret['solution'] = list(np.linalg.solve(self._matrix, self._vector)) def _run(self): """ Run the algorithm to compute eigenvalues and solution. Returns: Dictionary of results """ self._solve() return self._ret
python
# Generated by Django 3.0.5 on 2020-04-19 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('spectroscopy', '0001_initial'), ] operations = [ migrations.AlterField( model_name='spectrophotometer', name='product_code', field=models.CharField(max_length=10, unique=True), ), ]
python
order = [ 'artellapipe.tools.outliner.widgets.buttons', 'artellapipe.tools.outliner.widgets.items' ]
python
#!/usr/bin/env python # Copyright 2020 T-Mobile, USA, 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. # # Trademark Disclaimer: Neither the name of T-Mobile, USA, Inc. nor the names of # its contributors may be used to endorse or promote products derived from this # software without specific prior written permission. from flask import Flask, request, jsonify from kubernetes import client, config from kubernetes.client.rest import ApiException from logging.handlers import MemoryHandler from prometheus_client import Counter from prometheus_flask_exporter import PrometheusMetrics import base64 import copy import datetime import json import logging import os import re import requests import sys import time app = Flask(__name__) # Setup Prometheus Metrics for Flask app metrics = PrometheusMetrics(app, defaults_prefix="magtape") # Static information as metric metrics.info("app_info", "Application info", version="0.6") # Set logging config log = logging.getLogger("werkzeug") log.disabled = True magtape_log_level = os.environ["MAGTAPE_LOG_LEVEL"] app.logger.setLevel(magtape_log_level) # Set Global variables cluster = os.environ["MAGTAPE_CLUSTER_NAME"] magtape_namespace_name = os.environ["MAGTAPE_NAMESPACE_NAME"] magtape_pod_name = os.environ["MAGTAPE_POD_NAME"] magtape_tls_path = "/tls" # Set Slack related variables slack_enabled = os.environ["MAGTAPE_SLACK_ENABLED"] slack_passive = os.environ["MAGTAPE_SLACK_PASSIVE"] slack_webhook_url_default = os.environ["MAGTAPE_SLACK_WEBHOOK_URL_DEFAULT"] slack_webhook_annotation = os.environ["MAGTAPE_SLACK_ANNOTATION"] slack_user = os.environ["MAGTAPE_SLACK_USER"] slack_icon = os.environ["MAGTAPE_SLACK_ICON"] # Set K8s Events specific variables k8s_events_enabled = os.environ["MAGTAPE_K8S_EVENTS_ENABLED"] # Set OPA Info opa_base_url = os.environ["OPA_BASE_URL"] opa_k8s_path = os.environ["OPA_K8S_PATH"] opa_url = opa_base_url + opa_k8s_path # Set Deny Level magtape_deny_level = os.environ["MAGTAPE_DENY_LEVEL"] # Set Custom Prometheus Counters # Request Metrics represent requests to the MagTape API magtape_metrics_requests = Counter( "magtape_requests", "Request Metrics for MagTape", ["count_type", "ns", "alert_sent"], ) # Policy metrics represent individual policy evaluations magtape_metrics_policies = Counter( "magtape_policy", "Policy Metrics for MagTape", ["count_type", "policy", "ns"] ) ################################################################################ ################################################################################ ################################################################################ @app.route("/", methods=["POST"]) def webhook(): """Function to call main logic and return k8s admission response""" request_info = request.json request_spec = copy.deepcopy(request_info) # Call Main Webhook function admissionReview = magtape(request_spec) # Return JSON formatted response object return jsonify(admissionReview) ################################################################################ ################################################################################ ################################################################################ @app.route("/healthz", methods=["GET"]) def healthz(): """Function to return health info for app""" health_response = { "pod_name": magtape_pod_name, "date_time": str(datetime.datetime.now()), "health": "ok", } # Return JSON formatted response object return jsonify(health_response) ################################################################################ ################################################################################ ################################################################################ def magtape(request_spec): """main function""" # Zero out specific info per call allowed = True skip_alert = False response_message = "" alert_should_send = False alert_targets = [] customer_alert_sent = False # Set Object specific info from request uid = request_spec["request"]["uid"] workload = request_spec["request"]["object"]["metadata"]["name"] workload_type = request_spec["request"]["kind"]["kind"] namespace = request_spec["request"]["namespace"] request_user = request_spec["request"]["userInfo"]["username"] app.logger.info( "##################################################################" ) app.logger.info(f"Deny Level: {magtape_deny_level}") app.logger.info(f"Processing {workload_type}: {namespace}/{workload}") app.logger.info(f"Request User: {request_user}") app.logger.debug( f"Request Object: \n{json.dumps(request_spec, indent=2, sort_keys=True)}" ) if ( "ownerReferences" in request_spec["request"]["object"]["metadata"] and request_spec["request"]["object"]["metadata"]["ownerReferences"][0]["kind"] == "ReplicaSet" ): # Set Owner Info k8s_object_owner_kind = request_spec["request"]["object"]["metadata"][ "ownerReferences" ][0]["kind"] k8s_object_owner_name = request_spec["request"]["object"]["metadata"][ "ownerReferences" ][0]["name"] # Set Skip for Alert skip_alert = True else: # Run MagTape Specific checks on requests objects response_message = build_response_message( request_spec, response_message, namespace ) # Output policy decision for policy_response in response_message.split(", "): if policy_response: app.logger.info(policy_response) else: app.logger.info("[PASS] All checks") app.logger.debug(f"Skip Alert: {skip_alert}") # Set allowed value based on DENY_LEVEL and response_message content if magtape_deny_level == "OFF": app.logger.debug("Deny level detected: OFF") allowed = True elif magtape_deny_level == "LOW": DENY_LIST = ["[FAIL] HIGH"] app.logger.debug("Deny level detected: LOW") if any(denyword in response_message for denyword in DENY_LIST): app.logger.debug("Sev Fail level: HIGH") allowed = False alert_should_send = True elif magtape_deny_level == "MED": DENY_LIST = ["[FAIL] HIGH", "[FAIL] MED"] app.logger.debug("Deny level detected: MED") if any(denyword in response_message for denyword in DENY_LIST): app.logger.debug("Sev Fail level: HIGH/MED") allowed = False alert_should_send = True elif magtape_deny_level == "HIGH": DENY_LIST = ["[FAIL] HIGH", "[FAIL] MED", "[FAIL] LOW"] app.logger.debug("Deny level detected: HIGH") if any(denyword in response_message for denyword in DENY_LIST): app.logger.debug("Sev Fail level: HIGH/MED/LOW") allowed = False alert_should_send = True else: app.logger.debug("Deny level detected: NONE") allowed = False alert_should_send = True # Set optional message if allowed = false if allowed: admission_response = {"allowed": allowed} else: admission_response = { "uid": uid, "allowed": allowed, "status": {"message": response_message}, } # Create K8s Event for target namespace if enabled if k8s_events_enabled == "TRUE": app.logger.info("K8s Event are enabled") if "FAIL" in response_message or alert_should_send: send_k8s_event( magtape_pod_name, namespace, workload_type, workload, response_message ) else: app.logger.info("K8s Events are NOT enabled") # Send Slack message when failure is detected if enabled if slack_enabled == "TRUE": app.logger.info("Slack alerts are enabled") if skip_alert: app.logger.info( f'Skipping alert for child object of previously validated parent "{k8s_object_owner_kind}/{k8s_object_owner_name}"' ) elif ( "FAIL" in response_message and slack_passive == "TRUE" or alert_should_send ): # Add default Webhook URL to alert Targets alert_targets.append(slack_webhook_url_default) # Check Request namespace for custom Slack Webhook get_namespace_annotation(namespace, slack_webhook_annotation, alert_targets) # Set boolean to show whether a customer alert was sent if len(alert_targets) > 1: customer_alert_sent = True # Send alerts to all target Slack Webhooks for slack_target in alert_targets: send_slack_alert( response_message, slack_target, slack_user, slack_icon, cluster, namespace, workload, workload_type, request_user, customer_alert_sent, magtape_deny_level, allowed, ) # Increment Prometheus Counters if allowed: magtape_metrics_requests.labels( count_type="allowed", ns=namespace, alert_sent="true" ).inc() magtape_metrics_requests.labels( count_type="total", ns=namespace, alert_sent="true" ).inc() else: magtape_metrics_requests.labels( count_type="denied", ns=namespace, alert_sent="true" ).inc() magtape_metrics_requests.labels( count_type="total", ns=namespace, alert_sent="true" ).inc() else: app.logger.info(f"Slack alerts are NOT enabled") # Increment Prometheus Counters if allowed: magtape_metrics_requests.labels( count_type="allowed", ns=namespace, alert_sent="false" ).inc() magtape_metrics_requests.labels( count_type="total", ns=namespace, alert_sent="false" ).inc() else: magtape_metrics_requests.labels( count_type="denied", ns=namespace, alert_sent="false" ).inc() magtape_metrics_requests.labels( count_type="total", ns=namespace, alert_sent="false" ).inc() # Build Admission Response admissionReview = {"response": admission_response} app.logger.info("Sending Response to K8s API Server") app.logger.debug( f"Admission Review: \n{json.dumps(admissionReview, indent=2, sort_keys=True)}" ) return admissionReview ################################################################################ ################################################################################ ################################################################################ def build_response_message(object_spec, response_message, namespace): """Function to build the response message used to inform users of policy decisions""" try: opa_response = requests.post( opa_url, json=object_spec, headers={"Content-Type": "application/json"}, timeout=5, ) except requests.exceptions.RequestException as exception: app.logger.info(f"Call to OPA was unsuccessful") print(f"Exception:\n{exception}") response_message = "[FAIL] HIGH - Call to OPA was unsuccessful. Please contact your cluster administrator" return response_message if opa_response and opa_response.status_code == 200: app.logger.info("Call to OPA was successful") app.logger.debug(f"Opa Response Headers: {opa_response.headers}") app.logger.debug(f"OPA Response Text:\n{opa_response.text}") else: app.logger.info( f"Request to OPA returned an error {opa_response.status_code}, the response is:\n{opa_response.text}" ) response_message = "[FAIL] HIGH - Call to OPA was unsuccessful. Please contact your cluster administrator" return response_message # Load OPA request results as JSON opa_response_json = json.loads(opa_response.text)["decisions"] app.logger.debug(f"OPA JSON:\n{opa_response_json}") # Build response message from "msg" component of each object in the OPA response messages = [] # Note this entire statement can likely be broken down into a simpler chained # generator/list comprehension statement.....I tried, but couldn't get it to work # Something similar to: # opa_response_msg = ", ".join(reason['msg'] for reason in decision['reasons'] for decision in opa_response_json) for decision in opa_response_json: for reason in decision["reasons"]: messages.append(reason["msg"]) # Sort messages for consistent output messages.sort() opa_response_msg = ", ".join(messages) # Cleanup artifacts from OPA response before sending to K8s API response_message = re.sub(r"^\[\'|\'\]$|\'(\, )\'", r"\1", opa_response_msg) app.logger.debug(f"response_message:\n{response_message}") # Increment Prometheus counter for each policy object in the OPA response for policy_obj in opa_response_json: policy_name = re.sub("policy-", "", policy_obj["policy"]).replace("_", "-") app.logger.debug(f"Policy Object: {policy_obj}") app.logger.debug(f"Policy Name: {policy_name}") if policy_obj["reasons"]: for reason in policy_obj["reasons"]: app.logger.debug(f"Policy Failed") # Increment Prometheus Counters magtape_metrics_policies.labels( count_type="total", policy=policy_name, ns=namespace ).inc() magtape_metrics_policies.labels( count_type="fail", policy=policy_name, ns=namespace ).inc() else: app.logger.debug(f"Policy Passed") # Increment Prometheus Counters magtape_metrics_policies.labels( count_type="total", policy=policy_name, ns=namespace ).inc() magtape_metrics_policies.labels( count_type="pass", policy=policy_name, ns=namespace ).inc() return response_message ################################################################################ ################################################################################ ################################################################################ def get_namespace_annotation( request_namespace, slack_webhook_annotation, alert_targets ): """Function to check for customer defined Slack Incoming Webhook URL in namespace annotation""" config.load_incluster_config() v1 = client.CoreV1Api() try: request_ns_annotations = v1.read_namespace( request_namespace ).metadata.annotations app.logger.debug(f"Request Namespace Annotations: {request_ns_annotations}") except ApiException as exception: app.logger.info( f"Unable to query K8s namespace for Slack Webhook URL annotation: {exception}\n" ) if request_ns_annotations and slack_webhook_annotation in request_ns_annotations: slack_webhook_url_customer = request_ns_annotations[slack_webhook_annotation] if slack_webhook_url_customer: app.logger.info( f'Slack Webhook Annotation Detected for namespace "{request_namespace}"' ) app.logger.debug( f"Slack Webhook Annotation Value: {slack_webhook_url_customer}" ) alert_targets.append(slack_webhook_url_customer) else: app.logger.info( f"No Slack Incoming Webhook URL Annotation Detected, using default" ) app.logger.debug(f"Default Slack Webhook URL: {slack_webhook_url_default}") ################################################################################ ################################################################################ ################################################################################ def send_k8s_event( magtape_pod_name, namespace, workload_type, workload, response_message ): """Function to create a k8s event in the target namespace upon policy failure""" # Load k8s client config config.load_incluster_config() # Create an instance of the API class api_instance = client.CoreV1Api() k8s_event_time = datetime.datetime.now(datetime.timezone.utc) # Build involved object for k8s event k8s_involved_object = client.V1ObjectReference( name=workload, kind=workload_type, namespace=namespace ) # Build metadata for k8s event k8s_event_metadata = client.V1ObjectMeta( generate_name="magtape-policy-failure.", namespace=namespace, labels={"magtape-event": "policy-failure"}, ) # Build body for k8s event k8s_event_body = client.V1Event( action="MagTape Policy Failure", event_time=k8s_event_time, first_timestamp=k8s_event_time, involved_object=k8s_involved_object, last_timestamp=k8s_event_time, message=response_message, metadata=k8s_event_metadata, reason="MagTapePolicyFailure", type="Warning", reporting_component="magtape", reporting_instance=magtape_pod_name, ) try: api_response = api_instance.create_namespaced_event(namespace, k8s_event_body) except ApiException as exception: app.logger.info(f"Exception when creating a namespace event: {exception}\n") ################################################################################ ################################################################################ ################################################################################ def slack_url_sub(slack_webhook_url): """Function to override the base domain for the Slack Incoming Webhook URL""" if "SLACK_WEBHOOK_URL_BASE" in os.environ: slack_webhook_url_base = os.environ["SLACK_WEBHOOK_URL_BASE"] slack_webhook_url = re.sub( r"(^https://)([a-z0-9\.]+)(.*)$", r"\1" + slack_webhook_url_base + r"\3", slack_webhook_url, ) app.logger.info("Slack Webhook URL override detected") app.logger.debug(f"Slack Webhook URL after substitution: {slack_webhook_url}") return slack_webhook_url ################################################################################ ################################################################################ ################################################################################ def send_slack_alert( response_message, slack_webhook_url, slack_user, slack_icon, cluster, namespace, workload, workload_type, request_user, customer_alert_sent, magtape_deny_level, allowed, ): """Function to format and send Slack alert for policy failures""" # Set Slack alert header and color appropriately for active/passive alerts alert_header = "MagTape | Policy Denial Detected" alert_color = "danger" if allowed: alert_header = "MagTape | Policy Failures Detected" alert_color = "warning" # Override Slack Webhook URL base domain if applicable slack_webhook_url = slack_url_sub(slack_webhook_url) slack_alert_data = { "username": f"{slack_user}", "icon_emoji": f"{slack_icon}", "attachments": [ { "fallback": f'MagTape detected failures for {workload_type} "{workload}" in namespace "{namespace}" on cluster "{cluster}"', "color": f"{alert_color}", "pretext": f"{alert_header}", "text": response_message.replace(",", "\n"), "fields": [ {"title": "Cluster", "value": f"{cluster}", "short": "true"}, {"title": "Namespace", "value": f"{namespace}", "short": "true"}, { "title": "MagTape Deny Level", "value": f"{magtape_deny_level}", "short": "true", }, { "title": "Workload", "value": f"{workload_type.lower()}/{workload}", "short": "false", }, {"title": "User", "value": f"{request_user}", "short": "false"}, { "title": "Customer Alert", "value": f"{customer_alert_sent}", "short": "true", }, ], } ], } app.logger.debug( f"Slack Alert Data: \n{json.dumps(slack_alert_data, indent=2, sort_keys=True)}" ) try: slack_response = requests.post( slack_webhook_url, json=slack_alert_data, headers={"Content-Type": "application/json"}, timeout=5, ) app.logger.info(f"Slack Alert was successful ({slack_response.status_code})") app.logger.debug(f"Slack API Response: {slack_response}") except requests.exceptions.RequestException as exception: app.logger.info(f"Problem sending Alert to Slack: {exception}") ################################################################################ ################################################################################ ################################################################################ def main(): app.logger.info("MagTape Startup") app.run( host="0.0.0.0", port=5000, debug=False, threaded=True, ssl_context=(f"{magtape_tls_path}/cert.pem", f"{magtape_tls_path}/key.pem"), ) ################################################################################ ################################################################################ ################################################################################ if __name__ == "__main__": main()
python
import re from urllib.parse import urlsplit from bs4 import BeautifulSoup from .base_fetcher import BaseFetcher def clean_text(tag): text = tag.find("pre").prettify()[5:-6].replace("<br/>", "\n").replace(u'\xa0', ' ') # print('text', repr(text), repr(tag.find("pre").get_text())) return text class CodeForceFetcher(BaseFetcher): PATTERNS = { 'contest': re.compile("contest/([a-zA-Z0-9]+)/problem/([A-G])"), 'problem': re.compile("problem/([a-zA-Z0-9]+)/([A-G])") } def dirname(self): problem, level = None, None for pattern in self.PATTERNS.values(): match = pattern.search(self.url) if match: problem = match.group(1) level = match.group(2) return 'CF{}-{}'.format(problem, level) def title(self): soup = BeautifulSoup(self.text, 'html.parser') tag = soup.find('div', {'class': 'problem-statement'}).find('div', {'class': 'title'}) return tag.get_text() def tests(self): if not self.text: return soup = BeautifulSoup(self.text, 'html.parser') previous = None for div in soup.find_all('div', {'class': 'sample-test'}): # print('s', div.get_text()) inputs = div.find_all("div", {"class": "input"}) outputs = div.find_all("div", {"class": "output"}) for i, o in zip(inputs, outputs): yield clean_text(i), clean_text(o) # dtype = div['class'][0] # text = div.find('pre').get_text() # if text[0] == '\n': # text = text[1:] # if dtype == 'input': # previous = text # elif dtype == 'output': # yield previous, text
python
from mltoolkit.mldp import Pipeline from mltoolkit.mldp.steps.formatters import PyTorchFormatter class PyTorchPipeline(Pipeline): """ Addresses the issue associated with processes that put PyTorch tensors to a Queue object must be alive when the main processes gets/requests them from the Queue. Formats batches on the main processes. https://discuss.pytorch.org/t/multiprocessing-using-torch-multiprocessing/11029 https://discuss.pytorch.org/t/using-torch-tensor-over-multiprocessing-queue-process-fails/2847/2 """ def __init__(self, **kwargs): super(PyTorchPipeline, self).__init__(**kwargs) self.torch_formatter = PyTorchFormatter() def iter(self, early_term=None, **kwargs): """For more info see the original method.""" itr = super(PyTorchPipeline, self).iter(early_term=early_term, **kwargs) for dc in itr: yield self.torch_formatter(dc)
python
import os import sys sys.path.append('../../') from dquant.markets._binance_spot_rest import Binance from dquant.markets._bitfinex_spot_rest import TradingV1 # from dquant.markets._huobi_spot_rest import HuobiRest from dquant.markets._okex_spot_rest import OkexSpotRest from dquant.markets.market import Market from dquant.util import Util import sys import queue import collections import base64 import hmac import os import datetime import logging from dquant.config import cfg from dquant.constants import Constants import hashlib import json import requests import urllib.parse import requests.adapters requests.adapters.DEFAULT_RETRIES = 5 delay_time = 0.1 class HuobiRest(Market): def __init__(self, meta_code): market_currency, base_currency, symbol = self.parse_meta(meta_code) super().__init__(market_currency, base_currency, meta_code, cfg.get_float_config(Constants.HUOBI_FEE)) self.apikey = cfg.get_config(Constants.HUOBI_APIKEY) self.apisec = cfg.get_config(Constants.HUOBI_APISEC) self.huobi_id = cfg.get_config(Constants.HUOBI_ID) self.strategy_id = cfg.get_config(Constants.HUOBI_STRATEGY_ID) self.ip_pid_sid = Util.bfx_get_gid(self.strategy_id) self.spot_account_id = cfg.get_config(Constants.HUOBI_SPOT_ID) self.minimum_amount = cfg.get_float_config(Constants.HUOBI_MINIMUM_AMOUNT) self.amount_precision = cfg.get_int_config(Constants.HUOBI_AMOUNT_PRECISION) self.price_precision = cfg.get_int_config(Constants.HUOBI_PRICE_PRECISION) self.symbol = symbol self.name = 'HuoBiPro' self.base_url_api = Constants.HUOBI_REST_BASE self.session = requests.session() self.timeout = Constants.OK_HTTP_TIMEOUT self.orders = [] self.order_info_table = {} self.type_map = {'buy-limit':'buy', 'buy-market':'buy', 'sell-limit':'sell', 'sell-market':'sell'} self.order_result_required = False self.q_order_result = queue.Queue() self.hist = {'buy': collections.OrderedDict(), 'sell': collections.OrderedDict()} self.hist_lenth = 10 def deleteOrder(self, order_id, tillOK=True): ''' :param orderId: :param tillOK: :return: {'status': 'ok', 'data': '460960843'} ''' while True: try: params = {} url = "/v1/order/orders/{0}/submitcancel".format(order_id) result = self.api_key_post(params, url) logging.debug('Huobi delete: %s' % result) # print(result) if result['status'] == 'ok': try: self.orders.remove(order_id) except: pass return self.simpleGetOrder(order_id) if not result or result['status'] != 'ok': self.updateOrderInfo(order_id) order_result = self.simpleGetOrder(order_id) if 'state' in order_result and order_result['state'] in ['canceled', 'filled', 'partial-canceled']: try: self.orders.remove(order_id) except: pass return order_result self.error('Huobi Delete Order: %s' % order_result) continue # return self.simpleGetOrder(order_id) except Exception as ex: self.error("Huobi cancel Order %s" % ex) if tillOK: continue def buildMySign(self, params, method, host_url, request_path, secret_key): sorted_params = sorted(params.items(), key=lambda d: d[0], reverse=False) encode_params = urllib.parse.urlencode(sorted_params) payload = [method, host_url, request_path, encode_params] payload = '\n'.join(payload) payload = payload.encode(encoding='UTF8') secret_key = secret_key.encode(encoding='UTF8') digest = hmac.new(secret_key, payload, digestmod=hashlib.sha256).digest() signature = base64.b64encode(digest) signature = signature.decode() return signature def http_get_request(self, url, params, add_to_headers=None): headers = { "Content-type": "application/x-www-form-urlencoded", 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36', } if add_to_headers: headers.update(add_to_headers) postdata = urllib.parse.urlencode(params) try: response = requests.get(url, postdata, headers=headers, timeout=self.timeout) if response.status_code == 200: return response.json() except BaseException as e: self.error("httpGet failed, detail is:%s" % e) return {} def http_post_request(self, url, params, add_to_headers=None): headers = { "Accept": "application/json", 'Content-Type': 'application/json' } if add_to_headers: headers.update(add_to_headers) postdata = json.dumps(params) try: response = requests.post(url, postdata, headers=headers, timeout=self.timeout) if response.status_code == 200: return response.json() except BaseException as e: self.error("httpPost failed, detail is:%s,%s" % (response.text, e)) return {} def api_key_get(self, params, request_path): method = 'GET' timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') params.update({'AccessKeyId': self.apikey, 'SignatureMethod': 'HmacSHA256', 'SignatureVersion': '2', 'Timestamp': timestamp}) host_url = self.base_url_api host_name = urllib.parse.urlparse(host_url).hostname host_name = host_name.lower() params['Signature'] = self.buildMySign(params, method, host_name, request_path, self.apisec) url = host_url + request_path return self.http_get_request(url, params) def api_key_post(self, params, request_path): method = 'POST' timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') params_to_sign = {'AccessKeyId': self.apikey, 'SignatureMethod': 'HmacSHA256', 'SignatureVersion': '2', 'Timestamp': timestamp} host_url = self.base_url_api host_name = urllib.parse.urlparse(host_url).hostname host_name = host_name.lower() params_to_sign['Signature'] = self.buildMySign(params_to_sign, method, host_name, request_path, self.apisec) url = host_url + request_path + '?' + urllib.parse.urlencode(params_to_sign) return self.http_post_request(url, params) def parse_meta(self, meta_code): meta_table = {"eth_usdt": ("eth", "usdt", "ethusdt"), "btc_usdt": ("btc", "usdt", "btcusdt"), "eth_btc": ("eth", "btc", "ethbtc"), "eos_eth": ("eos", "eth", "eoseth"), "eos_btc": ("eos", "btc", "eosbtc"), "bch_btc": ("bch", "btc", "bchbtc")} return meta_table[meta_code] def get_activate_orders(self, tillOK=True): """ :param symbol: :param states: 可选值 {pre-submitted 准备提交, submitted 已提交, partial-filled 部分成交, partial-canceled 部分成交撤销, filled 完全成交, canceled 已撤销} :param types: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖} :param start_date: :param end_date: :param _from: :param direct: 可选值{prev 向前,next 向后} :param size: :return: """ while True: params = {'symbol': self.symbol, 'states': 'submitted'} result = self.api_key_get(params, Constants.HUOBI_GET_ORDER_REST) if (not result or result['status'] != 'ok') and tillOK: self.error('getOrder %s' % result) continue datas = result['data'] res = [] for data in datas: side = self.type_map[data.get('type', '')] tmp = Util.build_order_result( status=True, order_id=data['id'], side=data.get('type', ''), trade_pair=data.get('symbol', ''), price=data.get('price', '0'), amount_filled=data.get('field-amount', '0'), amount_orig=data.get('amount', '0'), amount_remain=float(data.get('amount', '0')) - float(data.get('field-amount', '0'))) res.append(tmp) return res def cancel_active_orders(self, tillOK=True): ''' 单次不超过50个订单id :param tillOK: :return: {'status': 'ok', 'data': {'success': ['562265763'], 'failed': []}} ''' order_ids = [e['order_id'] for e in self.get_activate_orders()] lens = len(order_ids) print('order_ids: ', order_ids, lens) result = {} for i in range(0, lens, 50): params = {'order-ids': order_ids[i:i+50]} result = self.api_key_post(params, Constants.HUOBI_CANCEL_REST) if (not result or result['status'] != 'ok') and tillOK: continue return result def run(self): pass def get_command(): config_map = {'1':'Bitfinex', '2':'Binance', '3':'HuoBiPro', '4':'OKEX'} func_map = {'1':TradingV1, '2':Binance, '3':HuobiRest, '4':OkexSpotRest} if len(sys.argv) == 1: meta_code = 'eth_btc' for key, obj in func_map.items(): print('cancel orders: %s...' % config_map[key]) mkt = obj(meta_code) mkt.cancel_active_orders() print('done.') elif len(sys.argv) == 2: if sys.argv[1] in config_map: meta_code = 'eth_btc' print('cancel orders: %s...' % config_map[sys.argv[1]]) mkt = func_map[sys.argv[1]](meta_code) mkt.cancel_active_orders() print('done.') else: meta_code = sys.argv[1] for key, obj in func_map.items(): print('cancel orders: %s...' % config_map[key]) mkt = obj(meta_code) mkt.cancel_active_orders() print('done.') elif len(sys.argv) == 3: if sys.argv[1] in config_map: meta_code = sys.argv[2] print('cancel orders: %s...' % config_map[sys.argv[1]]) mkt = func_map[sys.argv[1]](meta_code) mkt.cancel_active_orders() else: meta_code = sys.argv[1] print('cancel orders: %s...' % config_map[sys.argv[2]]) mkt = func_map[sys.argv[1]](meta_code) mkt.cancel_active_orders() print('done.') def cancel_huobi_orders(): meta_codes = ['eth_btc', 'eth_usdt', 'btc_usdt'] for meta_code in meta_codes: print(meta_code) try: mkt = HuobiRest(meta_code) mkt.cancel_active_orders() except Exception as ex: print(ex) if __name__ == '__main__': os.environ[Constants.DQUANT_ENV] = "dev" get_command()
python
# Face.py - module for reading and parsing Scintilla.iface file # Implemented 2000 by Neil Hodgson [email protected] # Released to the public domain. # Requires Python 2.5 or later def sanitiseLine(line): if line[-1:] == '\n': line = line[:-1] if line.find("##") != -1: line = line[:line.find("##")] line = line.strip() return line def decodeFunction(featureVal): retType, rest = featureVal.split(" ", 1) nameIdent, params = rest.split("(") name, value = nameIdent.split("=") params, rest = params.split(")") param1, param2 = params.split(",") return retType, name, value, param1, param2 def decodeEvent(featureVal): retType, rest = featureVal.split(" ", 1) nameIdent, params = rest.split("(") name, value = nameIdent.split("=") return retType, name, value def decodeParam(p): param = p.strip() type = "" name = "" value = "" if " " in param: type, nv = param.split(" ") if "=" in nv: name, value = nv.split("=") else: name = nv return type, name, value class Face: def __init__(self): self.order = [] self.features = {} self.values = {} self.events = {} def ReadFromFile(self, name): currentCategory = "" currentComment = [] currentCommentFinished = 0 file = open(name) for line in file.readlines(): line = sanitiseLine(line) if line: if line[0] == "#": if line[1] == " ": if currentCommentFinished: currentComment = [] currentCommentFinished = 0 currentComment.append(line[2:]) else: currentCommentFinished = 1 featureType, featureVal = line.split(" ", 1) if featureType in ["fun", "get", "set"]: try: retType, name, value, param1, param2 = decodeFunction(featureVal) except ValueError: print("Failed to decode %s" % line) raise p1 = decodeParam(param1) p2 = decodeParam(param2) self.features[name] = { "FeatureType": featureType, "ReturnType": retType, "Value": value, "Param1Type": p1[0], "Param1Name": p1[1], "Param1Value": p1[2], "Param2Type": p2[0], "Param2Name": p2[1], "Param2Value": p2[2], "Category": currentCategory, "Comment": currentComment } if value in self.values: raise Exception("Duplicate value " + value + " " + name) self.values[value] = 1 self.order.append(name) currentComment = [] elif featureType == "evt": retType, name, value = decodeEvent(featureVal) self.features[name] = { "FeatureType": featureType, "ReturnType": retType, "Value": value, "Category": currentCategory, "Comment": currentComment } if value in self.events: raise Exception("Duplicate event " + value + " " + name) self.events[value] = 1 self.order.append(name) elif featureType == "cat": currentCategory = featureVal elif featureType == "val": try: name, value = featureVal.split("=", 1) except ValueError: print("Failure %s" % featureVal) raise Exception() self.features[name] = { "FeatureType": featureType, "Category": currentCategory, "Value": value } self.order.append(name) elif featureType == "enu" or featureType == "lex": name, value = featureVal.split("=", 1) self.features[name] = { "FeatureType": featureType, "Category": currentCategory, "Value": value, "Comment": currentComment } self.order.append(name) currentComment = []
python
from setuptools import setup from setuptools_rust import RustExtension, Binding def read(f): return open(f, encoding='utf-8').read() setup( name="PyValico", version="0.0.2", author='Simon Knibbs', license='MIT', url='https://github.com/s-knibbs/pyvalico', author_email='[email protected]', description='Wrapper around the valico rust library for JSON schema validation', long_description=read('README.md'), long_description_content_type='text/markdown', packages=["valico"], rust_extensions=[RustExtension("valico.valico", binding=Binding.RustCPython)], setup_requires=["setuptools_rust"], zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5' 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Libraries' ] )
python
import matplotlib.pyplot as plt import numpy as np import csv markers = { 'heuristic': { 'timestamps': [], 'repl': [], 'repl_err': [], 'cost': [], 'cost_err': [], 'migr': [], 'migr_err': [], 'drop': [], 'drop_err': [], 'effc': [], 'effc_err': [] }, 'optimal': { 'timestamps': [], 'repl': [], 'repl_err': [], 'cost': [], 'cost_err': [], 'migr': [], 'migr_err': [], 'drop': [], 'drop_err': [], 'effc': [], 'effc_err': [] }, 'normal': { 'timestamps': [], 'repl': [], 'repl_err': [], 'cost': [], 'cost_err': [], 'migr': [], 'migr_err': [], 'drop': [], 'drop_err': [], 'effc': [], 'effc_err': [] } } color_map = { 'heuristic': 'r', 'normal': 'm', 'optimal': 'c' } for algorithm in ['optimal', 'heuristic', 'normal']: with open('./timeline-%s.csv' % algorithm, 'r') as csvfile: reader = csv.reader(csvfile, delimiter="\t") for row in reader: markers[algorithm]['timestamps'].append(float(row[1].replace(',', ''))) markers[algorithm]['repl'].append(float(row[2].replace(',', ''))) markers[algorithm]['cost'].append(float(row[3].replace(',', ''))) markers[algorithm]['migr'].append(float(row[4].replace(',', ''))) markers[algorithm]['drop'].append(float(row[7].replace(',', ''))) markers[algorithm]['effc'].append(float(row[8].replace(',', ''))) markers[algorithm]['repl_err'].append(float(row[9].replace(',', '')) - float(row[2].replace(',', ''))) markers[algorithm]['cost_err'].append(float(row[11].replace(',', '')) - float(row[3].replace(',', ''))) markers[algorithm]['migr_err'].append(float(row[13].replace(',', '')) - float(row[4].replace(',', ''))) markers[algorithm]['drop_err'].append(float(row[15].replace(',', '')) - float(row[7].replace(',', ''))) markers[algorithm]['effc_err'].append(float(row[17].replace(',', '')) - float(row[8].replace(',', ''))) fig, axs = plt.subplots(nrows=5, ncols=1, figsize=(12, 30)) for algorithm in ['optimal', 'heuristic', 'normal']: axs[0].errorbar(markers[algorithm]['timestamps'], markers[algorithm]['repl'], yerr=markers[algorithm]['repl_err'], fmt='o', capsize=3, color = color_map[algorithm], alpha=0.7, label=algorithm) axs[1].errorbar(markers[algorithm]['timestamps'], markers[algorithm]['cost'], yerr=markers[algorithm]['cost_err'], fmt='o', capsize=3, color = color_map[algorithm], alpha=0.7, label=algorithm) axs[2].errorbar(markers[algorithm]['timestamps'], markers[algorithm]['drop'], yerr=markers[algorithm]['drop_err'], fmt='o', capsize=3, color = color_map[algorithm], alpha=0.7, label=algorithm) axs[3].errorbar(markers[algorithm]['timestamps'], markers[algorithm]['effc'], yerr=markers[algorithm]['effc_err'], fmt='o', capsize=3, color = color_map[algorithm], alpha=0.7, label=algorithm) axs[4].errorbar(markers[algorithm]['timestamps'], markers[algorithm]['migr'], yerr=markers[algorithm]['migr_err'], fmt='o', capsize=3, color = color_map[algorithm], alpha=0.7, label=algorithm) axs[0].set_xlabel('Time') axs[0].set_ylabel('Replication factor') axs[0].legend() axs[1].set_xlabel('Time') axs[1].set_ylabel('Cost value') axs[1].legend() axs[2].set_xlabel('Time') axs[2].set_ylabel('Drop rate') axs[2].legend() axs[3].set_xlabel('Time') axs[3].set_ylabel('Energy efficiency') axs[3].legend() axs[4].set_xlabel('Time') axs[4].set_ylabel('Migration count') axs[4].legend() plt.tight_layout() plt.grid() plt.savefig('timeline-ci.png')
python
# coding: utf-8 ''' =============================================================================== Sitegen Author: Karlisson M. Bezerra E-mail: [email protected] URL: https://github.com/hacktoon/sitegen License: WTFPL - http://sam.zoy.org/wtfpl/COPYING =============================================================================== ''' import os import re import bisect from datetime import datetime from . import utils from .exceptions import PageValueError DATE_FORMAT = '%Y-%m-%d %H:%M:%S' THUMB_FILENAME = 'thumb.png' EXCERPT_RE = r'<!--\s*more\s*-->' class Page(): '''Define a page''' def __init__(self): self.children = PageList() self.props = [] self.path = '' self.styles = [] self.scripts = [] self.template = '' self.data = {} def __le__(self, other): return self['date'] <= other['date'] def __lt__(self, other): return self['date'] < other['date'] def __len__(self): return 0 def __bool__(self): return True def __str__(self): return 'Page {!r}'.format(self.path) def __setitem__(self, key, value): self.data[key] = value def __getitem__(self, key): return self.data.get(key) def __delitem__(self, key): del self.data[key] def __contains__(self, key): return key in self.data.keys() def initialize(self, params, options): ''' Set books properties dynamically''' if 'title' not in params.keys(): msg = 'The title was not provided!' raise ValueError(msg) for key in params.keys(): method_name = 'set_{}'.format(key) if hasattr(self, method_name): getattr(self, method_name)(params[key], options) else: self.data[key] = params[key] def add_child(self, page): '''Link books in a familiar way''' self.children.insert(page) def set_date(self, date, _): self['date'] = date self['year'] = date.year self['month'] = date.month self['day'] = date.day def set_template(self, tpl, options): '''To give a book a good look and diagramation''' self.template = tpl def convert_param_list(self, param): '''Convert param string to list''' if isinstance(param, str): return [x.strip() for x in param.split(',')] return param def set_props(self, props, options): '''Books can have some different properties''' self.props = self.convert_param_list(props) def set_styles(self, styles, opts): '''To get some extra style''' styles = self.convert_param_list(styles) self.styles = ["{}/{}".format(opts['page_url'], s) for s in styles] def set_scripts(self, scripts, opts): '''To get some extra behavior''' scripts = self.convert_param_list(scripts) self.scripts = ["{}/{}".format(opts['page_url'], s) for s in scripts] def is_draft(self): '''To decide if the book is not ready yet''' return 'draft' in self.props def is_listable(self): '''Sometimes a book shall not be listed''' return 'nolist' not in self.props and not self.is_draft() def is_feed_enabled(self): '''Sometimes book publishers are shy''' return 'nofeed' not in self.props def is_json_enabled(self): '''Sometimes book publishers like other formats''' return 'nojson' not in self.props class PageList: '''Define an ordered list of pages''' def __init__(self): self.ordered_pages = [] self.page_dict = {} def __iter__(self): for page in self.ordered_pages: yield page def __len__(self): return len(self.ordered_pages) def __setitem__(self, key, value): self.ordered_pages[key] = value def __getitem__(self, key): return self.ordered_pages[key] def __delitem__(self, key): del self.ordered_pages[key] def reverse(self): '''To reverse the list of books''' return self.ordered_pages.reverse() def page_struct(self, index): '''To create a tag to find books''' page = self.ordered_pages[index] return { 'url': page['url'], 'title': page['title'] } def paginate(self): '''To sort books in shelves''' length = len(self.ordered_pages) for index, page in enumerate(self.ordered_pages): page['first'] = self.page_struct(0) next_index = index + 1 if index < length - 1 else -1 page['next'] = self.page_struct(next_index) prev_index = index - 1 if index > 0 else 0 page['prev'] = self.page_struct(prev_index) page['last'] = self.page_struct(-1) def insert(self, page): '''To insert book in right position by date''' bisect.insort(self.ordered_pages, page) self.page_dict[page.path] = page class PageBuilder: def __init__(self, env): self.env = env def build_url_from_path(self, path): base_path = self.env['base_path'] + '/data' resource = path.replace(base_path, '').strip('/') return utils.urljoin(self.env['base_url'], resource) def build_thumbnail(self, page_url): thumb_filepath = os.path.join(page_url, THUMB_FILENAME) if os.path.exists(thumb_filepath): return thumb_filepath # TODO: return default thumbnail def build_date(self, date_string, date_format): '''converts date string to datetime object''' if not date_string: return datetime.now() try: date = datetime.strptime(date_string, date_format) except ValueError: raise PageValueError('Wrong date format ' 'in {!r}!'.format(self.path)) return date def build_content(self, page_data): content = page_data.get('content', '') page_data['excerpt'] = re.split(EXCERPT_RE, content, 1)[0] page_data['content'] = re.sub(EXCERPT_RE, '', content) def build_breadcrumbs(self, parent_page, page_data): links = [] template = '/<a href="{}">{}</a>' current_page = template.format(page_data['url'], page_data['title']) links.insert(0, current_page) while parent_page: breadcrumb = template.format(parent_page['url'], parent_page['title']) links.insert(0, breadcrumb) parent_page = parent_page.parent # remove all but home page url return ''.join(links[1:]) def build(self, page_data, parent_page): '''Page object factory''' options = {} page = Page() page.parent = parent_page page.path = page_data['path'] page_url = self.build_url_from_path(page.path) options['date_format'] = self.env.get('date_format', DATE_FORMAT) options['page_url'] = page_url page_data['url'] = page_url page.image = page_data.get('image') page_data['thumb'] = self.build_thumbnail(page_url) page_data['breadcrumbs'] = self.build_breadcrumbs(parent_page, page_data) page_data['date'] = self.build_date(page_data.get('date'), options.get('date_format', '')) self.build_content(page_data) try: page.initialize(page_data, options) except ValueError as error: raise ValueError('{} at page {!r}'.format(error, page.path)) return page
python
from configuration import configuration, dbName, debugEverythingNeedsRolling from optionChain import OptionChain from statistics import median from tinydb import TinyDB, Query import datetime import time import alert import support class Cc: def __init__(self, asset): self.asset = asset def findNew(self, api, existing, existingPremium): asset = self.asset newccExpDate = support.getNewCcExpirationDate() # get option chain of third thursday and friday of the month optionChain = OptionChain(api, asset, newccExpDate, 1) chain = optionChain.get() if not chain: return alert.botFailed(asset, 'No chain found on the third thursday OR friday') # get closest chain to days # it will get friday most of the time, but if a friday is a holiday f.ex. the chain will only return a thursday date chain closestChain = chain[-1] minStrike = configuration[asset]['minStrike'] atmPrice = api.getATMPrice(asset) strikePrice = atmPrice + configuration[asset]['minGapToATM'] if existing and configuration[asset]['rollWithoutDebit']: # prevent paying debit with setting the minYield to the current price of existing minYield = existingPremium else: minYield = configuration[asset]['minYield'] if minStrike > strikePrice: strikePrice = minStrike # get the best matching contract contract = optionChain.getContractFromDateChain(strikePrice, closestChain['contracts']) if not contract: return alert.botFailed(asset, 'No contract over minStrike found') # check minYield projectedPremium = median([contract['bid'], contract['ask']]) if projectedPremium < minYield: if existing and configuration[asset]['rollWithoutDebit']: print('Failed to write contract for CREDIT with ATM price + minGapToATM (' + str(strikePrice) + '), now trying to get a lower strike ...') # we need to get a lower strike instead to not pay debit # this works with overwritten minStrike and minYield config settings. the minGapToATM is only used for max price (ATM price + minGapToATM) contract = optionChain.getContractFromDateChainByMinYield(existing['strike'], strikePrice, minYield, closestChain['contracts']) # edge case where this new contract fails: If even a calendar roll wouldn't result in a credit if not contract: return alert.botFailed(asset, 'minYield not met') projectedPremium = median([contract['bid'], contract['ask']]) else: # the contract we want has not enough premium return alert.botFailed(asset, 'minYield not met') return { 'date': closestChain['date'], 'days': closestChain['days'], 'contract': contract, 'projectedPremium': projectedPremium } def existing(self): db = TinyDB(dbName) ret = db.search(Query().stockSymbol == self.asset) db.close() return ret def writeCcs(api): for asset in configuration: asset = asset.upper() cc = Cc(asset) try: existing = cc.existing()[0] except IndexError: existing = None if (existing and needsRolling(existing)) or not existing: amountToSell = configuration[asset]['amountOfHundreds'] if existing: existingSymbol = existing['optionSymbol'] amountToBuyBack = existing['count'] existingPremium = api.getATMPrice(existing['optionSymbol']) else: existingSymbol = None amountToBuyBack = 0 existingPremium = 0 new = cc.findNew(api, existing, existingPremium) print('The bot wants to write the following contract:') print(new) if not api.checkAccountHasEnoughToCover(asset, existingSymbol, amountToBuyBack, amountToSell, new['contract']['strike'], new['date']): return alert.botFailed(asset, 'The account doesn\'t have enough shares or options to cover selling ' + str(amountToSell) + ' cc(\'s)') writeCc(api, asset, new, existing, existingPremium, amountToBuyBack, amountToSell) else: print('Nothing to write ...') def needsRolling(cc): if debugEverythingNeedsRolling: return True # needs rolling on date BEFORE expiration (if the market is closed, it will trigger ON expiration date) nowPlusOffset = (datetime.datetime.utcnow() + datetime.timedelta(days=support.ccExpDaysOffset)).strftime('%Y-%m-%d') return nowPlusOffset >= cc['expiration'] def writeCc(api, asset, new, existing, existingPremium, amountToBuyBack, amountToSell, retry=0, partialContractsSold=0): maxRetries = configuration[asset]['allowedPriceReductionPercent'] # lower the price by 1% for each retry if we couldn't get filled orderPricePercentage = 100 - retry if retry > maxRetries: return alert.botFailed(asset, 'Order cant be filled, tried with ' + str(orderPricePercentage + 1) + '% of the price.') if existing and existingPremium: orderId = api.writeNewContracts( existing['optionSymbol'], amountToBuyBack, existingPremium, new['contract']['symbol'], amountToSell, new['projectedPremium'], orderPricePercentage ) else: orderId = api.writeNewContracts( None, 0, 0, new['contract']['symbol'], amountToSell, new['projectedPremium'], orderPricePercentage ) checkFillXTimes = 12 if retry > 0: # go faster through it # todo maybe define a max time for writeCc function, as this can run well past 1 hour with dumb config settings and many assets checkFillXTimes = 6 for x in range(checkFillXTimes): # try to fill it for x * 5 seconds print('Waiting for order to be filled ...') time.sleep(5) checkedOrder = api.checkOrder(orderId) if checkedOrder['filled']: print('Order has been filled!') break if not checkedOrder['filled']: api.cancelOrder(orderId) print('Cant fill order, retrying with lower price ...') if checkedOrder['partialFills'] > 0: if checkedOrder['complexOrderStrategyType'] is None or (checkedOrder['complexOrderStrategyType'] and checkedOrder['complexOrderStrategyType'] != 'DIAGONAL'): # partial fills are only possible on DIAGONAL orders, so this should never happen return alert.botFailed(asset, 'Partial fill on custom order, manual review required: ' + str(checkedOrder['partialFills'])) # on diagonal fill is per leg, 1 fill = 1 bought back and 1 sold # quick verification, this should never be true if not (amountToBuyBack == amountToSell and amountToBuyBack > checkedOrder['partialFills']): return alert.botFailed(asset, 'Partial fill amounts do not match, manual review required') diagonalAmountBothWays = amountToBuyBack - checkedOrder['partialFills'] receivedPremium = checkedOrder['price'] * checkedOrder['partialFills'] alert.alert(asset, 'Partial fill: Bought back ' + str(checkedOrder['partialFills']) + 'x ' + existing['optionSymbol'] + ' and sold ' + str( checkedOrder['partialFills']) + 'x ' + new['contract']['symbol'] + ' for ' + str(receivedPremium)) return writeCc(api, asset, new, existing, existingPremium, diagonalAmountBothWays, diagonalAmountBothWays, retry + 1, partialContractsSold + checkedOrder['partialFills']) return writeCc(api, asset, new, existing, existingPremium, amountToBuyBack, amountToSell, retry + 1, partialContractsSold) receivedPremium = checkedOrder['price'] * amountToSell if existing: if amountToBuyBack != amountToSell: # custom order, price is not per contract receivedPremium = checkedOrder['price'] alert.alert(asset, 'Bought back ' + str(amountToBuyBack) + 'x ' + existing['optionSymbol'] + ' and sold ' + str(amountToSell) + 'x ' + new['contract']['symbol'] + ' for ' + str(receivedPremium)) else: alert.alert(asset, 'Sold ' + str(amountToSell) + 'x ' + new['contract']['symbol'] + ' for ' + str(receivedPremium)) if partialContractsSold > 0: amountHasSold = partialContractsSold + amountToSell receivedPremium = receivedPremium + checkedOrder['price'] * partialContractsSold # shouldn't happen if amountHasSold != configuration[asset]['amountOfHundreds']: return alert.botFailed(asset, 'Unexpected amount of contracts sold: ' + str(amountHasSold)) else: amountHasSold = amountToSell soldOption = { 'stockSymbol': asset, 'optionSymbol': new['contract']['symbol'], 'expiration': new['date'], 'count': amountHasSold, 'strike': new['contract']['strike'], 'receivedPremium': receivedPremium } db = TinyDB(dbName) db.remove(Query().stockSymbol == asset) db.insert(soldOption) db.close() return soldOption
python
"""Plotting Module.""" from scphylo.pl._data import heatmap from scphylo.pl._trees import clonal_tree, dendro_tree, networkx_tree, newick_tree __all__ = (heatmap, clonal_tree, dendro_tree, networkx_tree, newick_tree)
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-03-05 02:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('storehouse', '0002_supplier'), ] operations = [ migrations.CreateModel( name='Store', fields=[ ('name', models.TextField(primary_key=True, serialize=False)), ], ), ]
python
import json from pathlib import Path from types import SimpleNamespace from typing import NamedTuple, Any, Optional from flask.testing import FlaskClient from numpy.testing import assert_almost_equal from osgeo_utils.auxiliary.base import PathLikeOrStr test_env = SimpleNamespace() test_env.root = Path('.') test_env.talos = 'http://localhost:5000' test_env.tasc = test_env.talos test_env.talos_wps = test_env.talos + '/wps/' test_env.tasc_api1 = test_env.tasc + '/api/1.0' test_env.talos_api1 = test_env.talos + '/api/1.0' class TalosTest(NamedTuple): c: FlaskClient url: str request: Any response: Any dump_response: Optional[PathLikeOrStr] = None def assert_response(self, other): assert self.response == other def run_test(self, is_json=True): if is_json: rv = self.c.post(self.url, json=self.request) else: rv = self.c.post(self.url, data=self.request) assert rv.status_code == 200 json_data = rv.get_json() if self.dump_response: with open(self.dump_response, 'w') as f: json.dump(json_data, f, indent=4) self.assert_response(json_data) class ProfileTest(TalosTest): def assert_response(self, other): c1 = self.response['features'][0]['geometry']['coordinates'] c2 = other['features'][0]['geometry']['coordinates'] assert_almost_equal(c1, c2) self.response['features'][0]['geometry']['coordinates'] = None other['features'][0]['geometry']['coordinates'] = None super().assert_response(other) class CzmlTest(TalosTest): def assert_response(self, other): self.response[1]['name'] = None other[1]['name'] = None super().assert_response(other) def read_file(filename): with open(filename) as f: data = f.read() return data
python
#!/usr/bin/python import smtplib import subprocess import urllib2 from email.mime.text import MIMEText smtp_address="YOUR SMTP LOGIN" sender="YOUR SMTP LOGIN " receiver="YOUR EMAIL DESTINATION" password="YOURU SMTP PASSWORD" uptime = subprocess.check_output('uptime') ip_ext = urllib2.urlopen("http://ifconfig.me/ip").read() print ip_ext #ip_ext = subprocess.check_output(['curl','ifconfig.me']) msg = MIMEText(uptime+ip_ext) msg ["Subject"] = "Onion Report" server = smtplib.SMTP(smtp_address) server.starttls() server.login(sender,password) server.sendmail(sender,receiver,msg.as_string()) server.quit()
python
from scipy.stats import norm import math def dice_test(stat, alfa, mode_speed): # add parametrs for normal distribution if mode_speed == "plt_6": critical_const = norm.ppf(alfa, loc=0.2700502, scale=math.sqrt(0.0002832429)) p_value = norm.cdf(stat, loc=0.2700502, scale=math.sqrt(0.0002832429)) if mode_speed == "plt_13.5": critical_const = norm.ppf(alfa, loc=0.27328, scale=math.sqrt(0.0009519578)) p_value = norm.cdf(stat, loc=0.27328, scale=math.sqrt(0.0009519578)) if mode_speed == "plt_21": critical_const = norm.ppf(alfa, loc=0.4341689, scale=math.sqrt(0.001787848)) p_value = norm.cdf(stat, loc=0.4341689, scale=math.sqrt(0.001787848)) if mode_speed == "qpz_13.5": critical_const = norm.ppf(alfa, loc=0.4889668, scale=math.sqrt(0.00203925)) p_value = norm.cdf(stat, loc=0.4889668, scale=math.sqrt(0.00203925)) if mode_speed == "str_13.5": critical_const = norm.ppf(alfa, loc=0.4008677, scale=math.sqrt(0.001664502)) p_value = norm.cdf(stat, loc=0.4008677, scale=math.sqrt(0.001664502)) if mode_speed == "str_21": critical_const = norm.ppf(alfa, loc=0.4732636, scale=math.sqrt(0.002565701)) p_value = norm.cdf(stat, loc=0.4732636, scale=math.sqrt(0.002565701)) if mode_speed == "toe_13.5": critical_const = norm.ppf(alfa) p_value = norm.cdf(stat) if mode_speed == "air_13.5": critical_const = norm.ppf(alfa) p_value = norm.cdf(stat) return critical_const, p_value
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from clickhouse_mysql.observable import Observable class Reader(Observable): """Read data from source and notify observers""" converter = None event_handlers = { # called on each WriteRowsEvent 'WriteRowsEvent': [], # called on each row inside WriteRowsEvent (thus can be called multiple times per WriteRowsEvent) 'WriteRowsEvent.EachRow': [], # called when Reader has no data to read 'ReaderIdleEvent': [], # called on each DeleteRowsEvent 'DeleteRowsEvent': [], # called on each UpdateRowsEvent 'UpdateRowsEvent': [], } def __init__(self, converter=None, callbacks={}): self.converter = converter self.subscribe(callbacks) def read(self): pass
python
""" Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities find out if you two are equally strong. Example For yourLeft = 10, yourRight = 15, friendsLeft = 15, and friendsRight = 10, the output should be areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true; For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 10, the output should be areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = true; For yourLeft = 15, yourRight = 10, friendsLeft = 15, and friendsRight = 9, the output should be areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) = false. """ def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): # if (a == c or a == d) and (b == c or b == d): # return true # else: # return False # creates a set of list wit hordered numbers -> set([10, 15]) return {yourLeft, yourRight} == {friendsLeft, friendsRight} a = 15 b = 10 c = 10 d = 15 print(areEquallyStrong(a, b, c, d))
python
import setuptools setuptools.setup( name="confluent_schema_registry_client", version="1.1.0", author="Tom Leach", author_email="[email protected]", description="A simple client Confluent's Avro Schema Registry", license="MIT", keywords="confluent schema registry client avro http rest", url="http://github.com/gamechanger/confluent_schema_registry_client", packages=["confluent_schema_registry_client"], install_requires=['requests>=2.3.0'], tests_require=['nose', 'requests_mock'] )
python
#!/usr/bin/env python2 """ Dump ranks into a JS file, to be included by index.html. The JS file contains a global "raw_data" object, with fields: - contests: list of included contests. Each is an object with: - name: name of the contest. - tasks: list of tasks to include in this contest. - scores: map each username to an object with {task_name: score}. """ import argparse import json import sys import time import yaml from cms.db import SessionGen from cms.grading import task_score from server_utils.cms.scripts.DatabaseUtils import get_contests, get_tasks, \ get_users def create_ranks_object(included_contests=None, excluded_contests=None, included_tasks=None, excluded_tasks=None, included_users=None, excluded_users=None): """ Create a ranks object with the given parameters. """ with SessionGen() as session: # Fetch all relevant data. contests = get_contests(session, included_contests, excluded_contests) tasks = get_tasks(session, included_tasks, excluded_tasks) name_to_task = {task.name: task for task in tasks} users = get_users(session, included_users, excluded_users) usernames_set = set(user.username for user in users) result = {"contests": [], "scores": {}} # Initialize users info. for username in usernames_set: result["scores"][username] = {} # Fill the result according to each contest. for contest in contests: # Relevant tasks only. contest_tasks = [task.name for task in contest.tasks if task.name in name_to_task] # Don't include empty contests (where all tasks were excluded). if not contest_tasks: continue # Contest information. result["contests"] += [{ "name": contest.name, "tasks": contest_tasks }] # Submission information for each user and each task. for participation in contest.participations: username = participation.user.username # Skip irrelevant users. if username not in usernames_set: continue # Get the tasks this user submitted to. submitted_task_names = set(submission.task.name for submission in participation.submissions) for task_name in contest_tasks: # If the user did not submit to this task, we don't write # anything (this is distinct from getting 0). if task_name not in submitted_task_names: continue task = name_to_task[task_name] score, partial = task_score(participation, task) score = round(score, task.score_precision) score_string = str(score) if partial: score_string += "*" result["scores"][username][task_name] = score_string return result def dump_ranks_js(path, ranks_object): """ Dump the given ranks object to the given path as a JS file. The JS file contains only "var raw_data = <object>;". """ js_str = "var raw_data = %s;" % json.dumps(ranks_object) + \ "var scores_timestamp = %d;" % int(time.time()) with open(path, "w") as stream: stream.write(js_str) def main(): """ Read settings file and dump ranks to a JS file. """ parser = argparse.ArgumentParser() parser.add_argument("settings", help="settings file to use") args = parser.parse_args() settings_path = args.settings with open(settings_path) as stream: settings = yaml.safe_load(stream) target_path = settings["target_path"] if not target_path.endswith("scores.js"): raise Exception("Expected scores.js: %s" % target_path) ranks_object = create_ranks_object( settings.get("included_contests"), settings.get("excluded_contests"), settings.get("included_tasks"), settings.get("excluded_tasks"), settings.get("included_users"), settings.get("excluded_users")) dump_ranks_js(target_path, ranks_object) if __name__ == "__main__": sys.exit(main())
python
"""Responses provided by the iov42 platform.""" import json from dataclasses import dataclass from typing import List from typing import Union from ._entity import Identifier from ._request import Request @dataclass(frozen=True) class BaseResponse: """Base class for successful platform responses.""" request: Request # TODO: what information are we going to provide form the HTTP response. # Note: we do not want to leak out the HTTP response itself. content: bytes @dataclass(frozen=True) class EntityCreated(BaseResponse): """Entity was successfully created.""" proof: str resources: List[str] @dataclass(frozen=True) class Endorsement(BaseResponse): """Endorsement against a subject claim of the given endorser exists.""" proof: str endorser_id: Identifier endorsement: str Response = Union[EntityCreated, Endorsement] def deserialize(request: Request, content: bytes) -> Response: """Deserializes the HTTP response content to a Response.""" content_json = json.loads(content.decode()) if request.method == "PUT": return EntityCreated( request, content, content_json["proof"], resources=content_json["resources"], ) else: if "/endorsements/" in request.resource: # pragma: no cover return Endorsement( request, content, content_json["proof"], content_json["endorserId"], content_json["endorsement"], ) raise NotImplementedError( "Response deserialize not implemented" ) # pragma: no cover
python
# -*- coding:utf-8 -*- __author__ = 'shichao' import platform import tensorflow as tf import numpy as np import time def iterator_demo(): ''' python iterator demo :return: ''' class numIter: # def __init__(self, n): self.n = n def __iter__(self): self.x = -1 return self if platform.python_version().startswith('2.'): def next(self): self.x += 1 if self.x < self.n: return self.x else: raise StopIteration else: def __next__(self): # Python 3.x version Python 2.x version uses next() self.x += 1 if self.x < self.n: return self.x else: raise StopIteration for i in numIter(5): print(i) print(isinstance(numIter(1),)) print(isinstance(numIter,list)) def generator_demo(): ''' the generator demo :return: ''' def numGen(n): # generator try: x = 0 while x < n: y = yield x print(y) x += 1 except ValueError: yield 'error' finally: print('finally') num = numGen(5) print(num.next()) print(num.next()) print(num.send(999)) num.close() # print(num.throw(ValueError)) print(num.next()) # print(num.next()) def bubblesort(array,length): ''' the largest number will first down to the bottom, then the second largest, etc :param array: :param length: :return: ''' sorted = False while not sorted: sorted = True for i in range(1,length): if array[i-1] > array[i]: [array[i-1],array[i]] = swap(array[i-1],array[i]) sorted = False print(array) def swap(a,b): tmp = a a = b b = tmp return [a,b] def reverse_1(array,lo,hi): if lo<hi: array[lo],array[hi] = swap(array[lo],array[hi]) reverse_1(array,lo+1,hi-1) return array def reverse_2(array): pass def power2(n): if n==0: return 1 else: return power2(n>>1)**2<<1 if n&1 else power2(n>>1)**2 def power1(n): tmp = 1 for i in range(n): tmp *= 2 return tmp def simple_decorater(f): def wrapper(): print('enter') # f() int('exit') return wrapper @ simple_decorater def hello(): print('hello') def main(): ########## # iterator and generator # iterator_demo() # generator_demo() ######### # array operation # array = np.array([3,1,6,2,5,10,8,9,4,7]) # # bubblesort(array,len(array)) # array = reverse_1(array,0,len(array)-1) # print(array) # # ############# # recursion vs for loop start = time.time() print('%E'%power2(1000)) end = time.time() print('power2 elapsed time: {0}'.format(end-start)) # print('power2 elapsed time: %E'%(end-start)) start = time.time() print('%E'%power1(1000)) end = time.time() # print('power1 elapsed time: %E'%(end-start)) print('power1 elpased time: {0}'.format(end-start)) if __name__ == '__main__': # main() hello()
python
from __future__ import absolute_import, division, print_function, unicode_literals import sys from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QMessageBox, QFileDialog, QGridLayout, QHBoxLayout, \ QVBoxLayout, QGroupBox, QCheckBox, QPushButton, QAction from PatchEdit import * from collections import OrderedDict import copy class PatchGUI(QMainWindow): def __init__(self): self.app = QApplication(sys.argv) super(PatchGUI, self).__init__() self.file_dic = OrderedDict() self.orig_patch_obj_dic = OrderedDict() self.patch_obj_dic = OrderedDict() self.cb_dic = OrderedDict() self.vBox_list = [] self.apply_button = None self.disable_all_button = None self.defaults_button = None self.choose_files() def choose_files(self): fn_list, file_type = QFileDialog.getOpenFileNames(caption='Open File', filter='Kobo Patch (*.patch)') if fn_list: fd = {fn: None for fn in fn_list} self.file_dic, error = read_patch_files(fd) if error: QMessageBox.critical(self, 'Read Error!', error) else: for (fn, patch_text) in iterDic(self.file_dic): self.orig_patch_obj_dic[fn] = gen_patch_obj_list(fn, patch_text) self.initialize() else: self.close() def initialize(self): self.patch_obj_dic = copy.deepcopy(self.orig_patch_obj_dic) cont_index = 0 vBox = QVBoxLayout(self) for (fn, patch_obj_list) in iterDic(self.patch_obj_dic): self.cb_dic[fn] = [] gb = QGroupBox(fn) cb_grid = QGridLayout(self) # Create and add checkboxes to appropriate LabelFrame for (cb_index, obj) in enumerate(patch_obj_list): # Create checkbox variable and checkbox label for display cb_name = '' if obj.group: cb_name = obj.name + '\n(' + obj.group + ')' else: cb_name = obj.name # Create and add checkboxes to the LabelFrame, using the grid geometry manager self.cb_dic[fn].append(QCheckBox(cb_name)) # Set initial state of checkboxes if 'yes' in obj.status: self.cb_dic[fn][cb_index].setCheckState(Qt.Checked) else: self.cb_dic[fn][cb_index].setCheckState(Qt.Unchecked) self.cb_dic[fn][cb_index].stateChanged.connect(self.toggle_check) self.cb_dic[fn][cb_index].setToolTip(self.patch_obj_dic[fn][cb_index].help_text) grid_pos = calc_grid_pos(cb_index, cols=3) cb_grid.addWidget(self.cb_dic[fn][cb_index], grid_pos[0], grid_pos[1]) gb.setLayout(cb_grid) vBox.addWidget(gb) cont_index += 1 self.apply_button = QPushButton('Apply Changes') self.apply_button.clicked.connect(self.app_chgs) self.disable_all_button = QPushButton("Disable All") self.disable_all_button.clicked.connect(self.disable_all_patches) self.defaults_button = QPushButton('Restore Settings') self.defaults_button.clicked.connect(self.restore_defaults) button_box = QHBoxLayout() button_box.addStretch() button_box.addWidget(self.apply_button) button_box.addWidget(self.disable_all_button) button_box.addWidget(self.defaults_button) button_box.addStretch() vBox.addLayout(button_box) self.setCentralWidget(QWidget(self)) self.centralWidget().setLayout(vBox) self.setWindowTitle('Kobo Patch GUI') self.show() sys.exit(self.app.exec_()) def disable_all_patches(self): """ Does what it says on the tin :p Deselects all checkboxes and sets each objects status to 'no' :return: """ for chk_list in self.cb_dic.values(): for cb in chk_list: cb.setCheckState(Qt.Unchecked) for (fn, patch_obj_list) in iterDic(self.patch_obj_dic): for patch_obj in patch_obj_list: patch_obj.status = '`no`' def restore_defaults(self): """ Restores the state of the patch objects and checkboxes back to their original state of when the file was loaded :return: """ self.patch_obj_dic = copy.deepcopy(self.orig_patch_obj_dic) for (cb_list, patch_obj_list) in zip(self.cb_dic.values(), self.patch_obj_dic.values()): for (cb, patch_obj) in zip(cb_list, patch_obj_list): if 'yes' in patch_obj.status: cb.setCheckState(Qt.Checked) else: cb.setCheckState(Qt.Unchecked) def toggle_check(self, event): cb = self.sender() name = cb.text() for patch_list in self.patch_obj_dic.values(): for obj in patch_list: if obj.name in name: if cb.isChecked(): obj.status = '`yes`' else: obj.status = '`no`' def app_chgs(self, event): ask_confirm = QMessageBox.question(self, 'Are you sure?', 'Are you sure you wish to write the changes to the ' 'patch files?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ask_confirm == QMessageBox.Yes: success, error_title, error_msg = apply_changes(self.patch_obj_dic, self.file_dic) if not success: QMessageBox.critical(self, error_title, error_msg) else: QMessageBox.information(self, 'Sussess!', 'The files were successfully written.') def edit(self): pass if __name__ == '__main__': pg = PatchGUI()
python
import typer INFO = typer.style("INFO", fg=typer.colors.GREEN) + ": " HELP = typer.style("HELP", fg=typer.colors.BLUE) + ": " FAIL = typer.style("FAIL", fg=typer.colors.RED) + ": " SUCCESS = typer.style("SUCCESS", fg=typer.colors.BLUE) + ": " typer.echo(f"{INFO} Importing modules, please wait") import os import uvicorn import forest_lite.server.main as _main from forest_lite.server import config, user_db app = typer.Typer() def scan_port(initial_port): """Helper to detect available port""" port = initial_port typer.echo(f"{INFO} Scanning ports") while in_use(port): typer.echo(f"{FAIL} Port {port} in use") port += 1 typer.echo(f"{SUCCESS} Port {port} available") return port def in_use(port): """Check if port is accessible""" import socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(('localhost', port)) == 0 def get_settings(file_name, driver_name, palette): def fn(): return config.Settings(datasets=[ { "label": file_name, "palettes": { "default": { "name": palette, "number": 256, "reverse": True, "low": 200, "high": 300 } }, "driver": { "name": driver_name, "settings": { "pattern": file_name } } } ]) return fn def browser_thread(url): import threading import webbrowser typer.echo(f"{INFO} Opening browser: {url}") return threading.Thread(target=webbrowser.open, args=(url,)) @app.command() def view(file_name: str, driver: str = "eida50", open_tab: bool = True, palette: str = "Viridis", port: int = 1234): """ FOREST Lite viewer A simplified interface to the FOREST Lite server tool """ port = scan_port(port) if open_tab: url = f"http://localhost:{port}" thread = browser_thread(url) thread.start() callback = get_settings(file_name, driver, palette) _main.app.dependency_overrides[config.get_settings] = callback uvicorn.run(_main.app, port=port) @app.command() def serve(config_file: str, open_tab: bool = True, port: int = 1234): """ FOREST Lite server A simplified interface to uvicorn and configuration files used to serve the app """ if not os.path.exists(config_file): typer.echo(f"{FAIL} {config_file} not found on file system") if os.path.isabs(config_file): helper = f"{HELP} Looks like an absolute path, is there a typo?" else: helper = (f"{HELP} Looks like a relative path, " "are you in the right directory?") typer.echo(helper) raise typer.Exit() port = scan_port(port) def get_settings(): import yaml with open(config_file) as stream: data = yaml.safe_load(stream) return config.Settings(**data) if open_tab: url = f"http://localhost:{port}" thread = browser_thread(url) thread.start() _main.app.dependency_overrides[config.get_settings] = get_settings uvicorn.run(_main.app, port=port) @app.command() def database(user_name: str, password: str, db_file: str, user_group: str = "anonymous"): print(f"save: {user_name} to {db_file}") user_db.save_user(user_name, password, db_file, user_group=user_group)
python
#!/usr/bin/env python3.7 # Copyright 2021 DataStax, 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 # # 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. # Delete bucket function is used to delete the state files bucket. # This bucket will be created at make init run. # To delete from google.cloud import storage import os import sys def delete_bucket(bucket_name): storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) try: bucket.delete() print("Bucket {} deleted".format(bucket.name)) except: print("buckeet does not exists") bucket_name = os.getenv("bucket_name") delete_bucket(bucket_name)
python
import torch import onnx from pathlib import Path import sys def convert2onnx(model_path,input_size,out_path=None): if out_path is None: out_path=Path(model_path).with_suffix('.onnx') model=torch.load(model_path) out_path=export2onnx(model,input_size,out_path) return out_path def export2onnx(model,input_size,onnx_path,if_check=True,if_simplify=True): model.eval() c,h,w=tuple(input_size) device='cuda' if torch.cuda.is_available() else 'cpu' model.to(device) dummy_input = torch.randn(1,c,h,w).to(device) assert onnx_path.endswith('.onnx') torch.onnx._export(model,dummy_input,onnx_path, verbose=False) print('onnx exported') if if_check: onnx_path=check_onnx(onnx_path) if if_simplify: out_path=simplify_onnx(onnx_path) Path(onnx_path).unlink() else: out_path=onnx_path return out_path def check_onnx(onnx_path): onnx_model=onnx.load(onnx_path) onnx.checker.check_model(onnx_model) print('valid onnx model') return onnx_path def simplify_onnx(onnx_path): from onnxsim import simplify onnx_path=str(onnx_path) onnx_model=onnx.load(onnx_path) model_simp, check = simplify(onnx_model) assert check, "Simplified ONNX model could not be validated" out_path=onnx_path.replace('.onnx','_simp.onnx') onnx.save(model_simp,out_path) print('simplify done') return out_path if __name__ == '__main__': # model_path,c,w,h=sys.path[1:5] # convert2onnx(model_path,c,w,h) simply_onnx('model/model_Number_aus_bin.onnx')
python
from caffe2.python import core import numpy as np class ParameterTags(object): BIAS = 'BIAS' WEIGHT = 'WEIGHT' COMPUTED_PARAM = 'COMPUTED_PARAM' class ParameterInfo(object): def __init__( self, param_id, param, key=None, shape=None, length=None, grad=None, blob_copy=None): assert isinstance(param, core.BlobReference) self.param_id = param_id self.name = str(param) self.blob = param self.key = key self.shape = shape self.size = None if shape is None else np.prod(shape) self.length = max(1, length if length is not None else 1) self.grad = grad self._cloned_init_net = None # Optionally store equivalent copies of the blob # in different precisions (i.e. half and float copies) # stored as a dict of TensorProto.DataType -> BlobReference self.blob_copy = blob_copy # each param_info can have its own optimizer. It can be set within # OptimizerContext (caffe2/python/optimizer.py) self._optimizer = None @property def parameter(self): return self.blob @property def optimizer(self): return self._optimizer @optimizer.setter def optimizer(self, value): assert self._optimizer is None, "optimizer has already been set" self._optimizer = value def __str__(self): return self.name
python
# Criar e modificar arquivos txt ''' 'r' = Usado somente para ler algo 'w' = Usado somente para escrever algo 'r+' = Usado para ler e escrever algo 'a' = Usado para acrescentar algo ''' numeros = [0, 15, 10, 20, 15, 45] # Criar um arquivo e colocar as informações da lista numeros dentro dele with open('numeros.txt', 'w') as arquivo: for numero in numeros: arquivo.write(str(f"{numero}\n")) # Adicionar ao arquivo as informações da lista numeros dentro dele with open('numeros.txt', 'a') as arquivo: for numero in numeros: arquivo.write(f'{numero}\n') # Ler as informações dentro do arquivo de texto with open('numeros.txt', 'r') as arquivo: for linha in arquivo: print(linha)
python
""" Copyright Tiyab KONLAMBIGUE """ from gce import client import logging import time from model import job as jobmodel import configuration JSON_KEY_FOLDER = configuration.JSON_KEY_FOLDER # Google instance image project configs IMAGES_PROJECT = configuration.IMAGES_PROJECT class instance(): GCE_TERMINATED_STATUS = "TERMINATED" GCE_RUNNING_STATUS = "RUNNING" GCE_STOPPING_STATUS = "STOPPING" def __init__(self, project_id): self.project_id =project_id self.json_key_path = JSON_KEY_FOLDER + project_id + ".json" client.GCE_DEFAULT_ZONE=configuration.GCE_DEFAULT_ZONE client.GCE_DEFAULT_MACHINE_TYPE=configuration.GCE_DEFAULT_MACHINE_TYPE client.GCE_DEFAULT_IMAGE_NAME=configuration.GCE_DEFAULT_IMAGE_NAME client.GCE_DEFAULT_IMAGE_PROJECT=configuration.GCE_DEFAULT_IMAGE_PROJECT client.GCE_DEFAULT_FULL_SCOPE=configuration.GCE_DEFAULT_FULL_SCOPE self.gce_client = client.get_client(json_key_file=self.json_key_path, readonly=False) # Check if instance exist def exist(self, instance_name, project): logging.info("Run instance exist at > %s" % time.strftime("%c")) instance_metadata = self.get(instance_name, project) if instance_metadata: return True return False # Check if machine is running def get(self, instance_name, project): logging.info("Run instance get at > %s" % time.strftime("%c")) instances = self.gce_client.list_instances(project) for instance in instances: if instance['name']== instance_name: return instance return None # Get instance status def status_of(self, instance_name, project): logging.info("Run instance status_of at > %s" % time.strftime("%c")) instance_metadata = self.get(instance_name, project) if instance_metadata: return instance_metadata["status"] return None # Create a new machine if not exist def create(self,project, instance_name, startup_script_path,shutdown_script_path, bucket_id, zone, image_project, image_name,type_machine ): logging.info("Run instance create at > %s" % time.strftime("%c")) if not self.exist(instance_name, project): #Create machine #startup_script_path= SCRIPT_FOLDER + startup_scrip_name self.gce_client.create_instance(project, instance_name, startup_script_path,shutdown_script_path, bucket_id, zone, image_project, image_name,type_machine) #Check if machine is created if self.exist(instance_name, project): return True else: logging.info("Unexpected error, instance is not created...") else: logging.info("Instance "+instance_name+" already exist...") return False # Stop running instance def stop(self, instance_name, project, zone): if self.exist(instance_name, project): current_status = self.status_of(instance_name, project) if current_status != "STOPPING" and \ current_status != "TERMINATED": self.gce_client.stop_instance(project, instance_name, zone) #Check is instance is stopped correctly if self.status_of(instance_name, project) == "TERMINATED": return True else: logging.info("Instance " + instance_name + " not exist...") return False # Start instance stopped def start(self, instance_name, project, zone): if self.exist(instance_name, project): current_status = self.status_of(instance_name, project) if current_status == "TERMINATED": self.gce_client.start_instance(project, instance_name, zone) # Check is instance is stopped correctly if self.status_of(instance_name, project) == "RUNNING": return True else: logging.info("Instance " + instance_name + " not exist...") return False # Remove instance def delete(self, instance_name, project, zone): if self.exist(instance_name, project): self.gce_client.delete_instance(project, instance_name, zone) # Check is instance is removed correctly if not self.exist(instance_name, project): return True else: logging.info("Instance " + instance_name + " not exist...") return False ##################################################################################################### # JOB ##################################################################################################### # Run job def run_job(self, job): creation = job.creation updated = job.updated emails = job.emails project_id = job.project_id bucket_id = job.bucket_id machine_name = job.machine_name startup_script = job.startup_script shutdown_script = job.shutdown_script machine_type = job.machine_type machine_zone = job.machine_zone machine_os = job.machine_os cron_schedule = job.cron_schedule after_run = job.after_run max_running_time = job.max_running_time job_name = job.job_name job_status = job.job_status last_run = job.last_run # Check if instance exist # If instance exist - It's an stopped instance if self.exist(machine_name, project_id): status = self.status_of(machine_name, project_id) print('>>>>>> Status is ' + str(status)) if status!="RUNNING": # Create job by starting instance # By starting up instance, startup script will do the job new_instance_running = self.start(machine_name, project_id, machine_zone) if new_instance_running: # Update Datastore self.update_datastore_running_job(job) else: # If instance not exist create new one #Find image project by machine_os os_project = None for image in IMAGES_PROJECT: if image["key-word"] in machine_os: os_project = image["image-project"] # Create instance if we have image project if not os_project is None: new_instance_running = self.create(project_id,machine_name,startup_script,shutdown_script, bucket_id,machine_zone, os_project, machine_os, machine_type) if new_instance_running: # Update Datastore self.update_datastore_running_job(job) # Stop job def stop_job(self, job): creation = job.creation updated = job.updated emails = job.emails project_id = job.project_id bucket_id = job.bucket_id machine_name = job.machine_name startup_script = job.startup_script shutdown_script = job.shutdown_script machine_type = job.machine_type machine_zone = job.machine_zone machine_os = job.machine_os cron_schedule = job.cron_schedule after_run = job.after_run max_running_time = job.max_running_time job_name = job.job_name job_status = job.job_status last_run = job.last_run if self.exist(machine_name, project_id): if after_run =="stop": self.stop(machine_name, project_id, machine_zone) if after_run =="delete": self.delete(machine_name, project_id, machine_zone) current_status = self.status_of(machine_name, project_id) if current_status == self.GCE_STOPPING_STATUS or \ current_status == self.GCE_TERMINATED_STATUS \ or current_status ==None: # Update Datastore self.update_datastore_stopping_job(job) ################################################################################################# ######## DATASTORE ################################################################################################# #Update datastore and indicate a running job def update_datastore_running_job(self, job): # Check if job exist my_filter = "WHERE job_name='" + job.job_name + "'" existing_job = jobmodel.Job().get(my_filter) if len(existing_job) > 0: logging.info("update_job: Update job " + job.job_name + " to datastore ...") #Update existing job old_job = existing_job[0] old_job.emails = job.emails old_job.project_id = job.project_id old_job.bucket_id = job.bucket_id old_job.machine_name = job.machine_name old_job.startup_script = job.startup_script old_job.shutdown_script = job.shutdown_script old_job.machine_type = job.machine_type old_job.machine_zone = job.machine_zone old_job.after_run=job.after_run old_job.machine_os = job.machine_os old_job.cron_schedule = job.cron_schedule old_job.max_running_time = job.max_running_time old_job.job_name = job.job_name old_job.job_status = "running" old_job.put() else: #Redirect to list logging.info("Unable to update job " + job.job_name + ", job not found ...") #Update datastore and indicate a stopped job def update_datastore_stopping_job(self, job): # Check if job exist my_filter = "WHERE job_name='" + job.job_name + "'" existing_job = jobmodel.Job().get(my_filter) if len(existing_job) > 0: logging.info("update_job: Update job " + job.job_name + " to datastore ...") #Update existing job old_job = existing_job[0] old_job.emails = job.emails old_job.project_id = job.project_id old_job.bucket_id = job.bucket_id old_job.machine_name = job.machine_name old_job.startup_script = job.startup_script old_job.shutdown_script = job.shutdown_script old_job.machine_type = job.machine_type old_job.machine_zone = job.machine_zone old_job.after_run=job.after_run old_job.machine_os = job.machine_os old_job.cron_schedule = job.cron_schedule old_job.max_running_time = job.max_running_time old_job.job_name = job.job_name old_job.job_status = "standby" old_job.put() else: #Redirect to list logging.info("Unable to update job " + job.job_name + ", job not found ...")
python
import datapackage from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url dep_prefix = 'dependency://' parameters, dp, res_iter = ingest() url = parameters['url'] if url.startswith(dep_prefix): dependency = url[len(dep_prefix):].strip() url = get_dependency_datapackage_url(dependency) assert url is not None, "Failed to fetch output datapackage for dependency '%s'" % dependency datapackage = datapackage.DataPackage(url) for k, v in datapackage.descriptor.items(): if k != 'resources': dp[k] = v spew(dp, res_iter)
python
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from functools import reduce import operator import math import dolfin as dl import mshr def sort_points_in_anti_clockwise_order(coords): coords=coords.T center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coords), [len(coords)] * 2)) sorted_coords = sorted(coords, key=lambda coord: (-135 - math.degrees(math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360) sorted_coords = np.array(sorted_coords)[::-1].T return sorted_coords, center def numpy_to_dolfin_points(points): vertices=[] for ii in range(points.shape[1]): point = points[:,ii] vertices.append(dl.Point(point[0],point[1])) return vertices from scipy import io import os def generate_blade_domain(): path = os.path.abspath(os.path.dirname(__file__)) data = io.loadmat(os.path.join(path,'data','blade_geometry.mat')) bedge = data['bedge'] xy = data['xy'] points,bndry = [],[] for ii in range(bedge.shape[1]): kn1 = bedge[0,ii]-1 kn2 = bedge[1,ii]-1 points.append(xy[:,kn1]) points.append(xy[:,kn2]) bndry.append(bedge[2,ii]) bndry.append(bedge[2,ii]) points = np.asarray(points).T bndry = np.asarray(bndry) coords = points[:,bndry==0] sorted_coords,center=sort_points_in_anti_clockwise_order(coords) vertices = numpy_to_dolfin_points(sorted_coords) airfoil_domain = mshr.Polygon(vertices) cooling_domains = [] domain = airfoil_domain for ii in range(1,3): coords = points[:,bndry==ii] sorted_coords,center=sort_points_in_anti_clockwise_order(coords) vertices = numpy_to_dolfin_points(sorted_coords) cooling_domains.append(mshr.Polygon(vertices)) domain-=cooling_domains[-1] #last cooling domain requires special treatment coords = points[:,bndry==3] coords = coords[:,(coords[0]>=0.45)&(coords[0]<=0.7)] sorted_coords,center=sort_points_in_anti_clockwise_order(coords) vertices = numpy_to_dolfin_points(sorted_coords) cooling_domains.append(mshr.Polygon(vertices)) domain-=cooling_domains[-1] coords = points[:,bndry==3] coords = coords[:,(np.absolute(coords[1])<=0.01)&(coords[0]>=0.7)] sorted_coords,center=sort_points_in_anti_clockwise_order(coords) vertices = numpy_to_dolfin_points(sorted_coords) cooling_domains.append(mshr.Polygon(vertices)) domain-=cooling_domains[-1] return domain class CoolingPassage1(dl.SubDomain): def inside(self, x, on_boundary): cond1 = ((abs(x[1])<=0.045+1e-12) and (x[0]>=0.1-1e-12) and (x[0]<=0.2+1e-12)) cond2 = ((abs(x[1])<=0.035+1e-12) and (x[0]<=0.1+1e-12) and (x[0]>=0.05-1e-12)) cond3 = ((abs(x[1])<=0.02+1e-12) and (x[0]<=0.05+1e-12) and (x[0]>=0.025-1e-12)) return ((cond1 or cond2 or cond3) and on_boundary) class CoolingPassage2(dl.SubDomain): def inside(self, x, on_boundary): cond1 = ((abs(x[1])<=0.045+1e-12) and (x[0]<=0.45+1e-12) and (x[0]>=0.25-1e-12)) return (cond1 and on_boundary) class CoolingPassage3(dl.SubDomain): def inside(self, x, on_boundary): cond1 = ((abs(x[1])<=0.01+1e-12) and (x[0]>=0.5)) cond2 = ((abs(x[1])<0.035) and (x[0]>=0.5) and (x[0]<=0.7)) cond3 = ((abs(x[1])<0.04+1e-12) and (x[0]>=0.5) and (x[0]<=0.6)) return ((cond1 or cond2 or cond3) and on_boundary) class Airfoil(dl.SubDomain): def inside(self, x, on_boundary): return on_boundary from pyapprox.fenics_models.advection_diffusion import run_steady_state_model class AirfoilHeatTransferModel(object): def __init__(self,degree): self.degree=degree self.num_config_vars=1 self.domain = generate_blade_domain() def get_boundary_conditions_and_function_space(self,random_sample): function_space = dl.FunctionSpace(self.mesh, "Lagrange", degree) t_c1,t_c2,t_c3,thermal_conductivity,h_le,h_te=random_sample airfoil_expr = dl.Expression( 'h_te+(h_le-h_te)*std::exp(-4*std::pow(x[0]/(chord*lhot),2))', degree=self.degree,h_le=h_le,h_te=h_te,lhot=0.05,chord=0.04) boundary_conditions = [ ['dirichlet',Airfoil(),airfoil_expr], ['dirichlet',CoolingPassage1(),dl.Constant(t_c1)], ['dirichlet',CoolingPassage2(),dl.Constant(t_c2)], ['dirichlet',CoolingPassage3(),dl.Constant(t_c3)]] return boundary_conditions,function_space def initialize_random_expressions(self,random_sample): """ Parameters ---------- random_sample : np.ndarray (6) Realization of model uncertainties. The uncertainties are listed below in the order they appear in ``random_sample`` h_le : float Leading edge heat transfer coefficient h_lt : float Tail edge heat transfer coefficient thermal_conductivity : float Blade thermal conductivity t_c1 : float First passage coolant temperature t_c2 : float Second passage coolant temperature t_c3 : float Thrid passage coolant temperature """ t_c1,t_c2,t_c3,thermal_conductivity,h_le,h_te=random_sample kappa = dl.Constant(thermal_conductivity) forcing = dl.Constant(0) boundary_conditions, function_space = \ self.get_boundary_conditions_and_function_space(random_sample) return kappa,forcing,boundary_conditions,function_space def get_mesh_resolution(self,resolution_level): resolution = 10*(2**resolution_level) return int(resolution) def solve(self,samples): assert samples.ndim==2 assert samples.shape[1]==1 resolution_levels = samples[-self.num_config_vars:,0] self.mesh = self.get_mesh( self.get_mesh_resolution(resolution_levels[-1])) random_sample = samples[:-self.num_config_vars,0] kappa,forcing,boundary_conditions,function_space=\ self.initialize_random_expressions(random_sample) sol = run_steady_state_model( function_space,kappa,forcing,boundary_conditions) return sol def qoi_functional(self,sol): vol = dl.assemble(dl.Constant(1)*dl.dx(sol.function_space().mesh())) bulk_temperature=dl.assemble(sol*dl.dx(sol.function_space().mesh()))/vol print('Bulk (average) temperature',bulk_temperature) return bulk_temperature def __call__(self,samples): sol = self.solve(samples) vals = np.atleast_1d(self.qoi_functional(sol)) if vals.ndim==1: vals = vals[:,np.newaxis] return vals def get_mesh(self,resolution): mesh = mshr.generate_mesh(self.domain,resolution) return mesh if __name__=='__main__': degree=1 model = AirfoilHeatTransferModel(degree) sample = np.array([595,645,705,29,1025,1000,0]) sol = model.solve(sample[:,np.newaxis]) qoi = model(sample[:,np.newaxis]) fig,axs=plt.subplots(1,1) p=dl.plot(sol) plt.colorbar(p) plt.show() # #check boundary # from pyapprox.fenics_models.fenics_utilities import mark_boundaries, collect_dirichlet_boundaries # boundaries = mark_boundaries(mesh,boundary_conditions) # dirichlet_bcs = collect_dirichlet_boundaries( # function_space,boundary_conditions, boundaries) # temp = dl.Function(function_space) # temp.vector()[:]=-1 # for bc in dirichlet_bcs: # bc.apply(temp.vector()) # fig,axs=plt.subplots(1,1) # p=dl.plot(temp) # plt.colorbar(p) # #dl.plot(mesh) # plt.show()
python
from fractions import Fraction from src.seq import fibonacci, stern_diatomic_seq, fib_seq, stern_brocot from src.graph import stern_brocot_graph from itertools import islice import pytest def test_returns_first_5_numbers_of_stern_brocot(): assert take(stern_brocot, 5) == [ Fraction(1, 1), Fraction(1, 2), Fraction(2, 1), Fraction(1, 3), Fraction(3, 2)] @pytest.mark.skip(reason="WIP") def test_returns_first_5_numbers_of_stern_brocot_via_graph(): assert take(stern_brocot_graph, 5) == [ Fraction(1, 1), Fraction(1, 2), Fraction(2, 1), Fraction(1, 3), Fraction(3, 2)] def test_stern_diatomic_seq_appends_previous_fib_result(): assert take(stern_diatomic_seq, 5) == [0, 1, 1, 2, 1] def test_stern_diatomic_seq_appends_previous_fib_result_for_higher_n(): assert take(stern_diatomic_seq, 10) == [0, 1, 1, 2, 1, 3, 2, 3, 1, 4] def test_stern_diatomic_seq_appends_previous_fib_result_for_much_higher_n(): assert take(stern_diatomic_seq, 16) == [ 0, 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4] def test_fibonacci_seq_correct_for_zero(): assert take(fib_seq, 1) == [0] def test_fibonacci_seq_correct_for_one(): assert take(fib_seq, 2) == [0, 1] def test_fibonacci_seq_correct_for_n(): assert take(fib_seq, 8) == [0, 1, 1, 2, 3, 5, 8, 13] def test_fibonacci_correct_for_zero(): assert fibonacci(0) == 0 def test_fibonacci_correct_for_one(): assert fibonacci(1) == 1 def test_fibonacci_correct_for_n(): assert fibonacci(7) == 13 def take(func, n): return list(islice(func(), n))
python
# Copyright 2020 Thiago Teixeira # # 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 unittest from htbuilder.units import px, em, percent class TestUnits(unittest.TestCase): def test_basic_usage(self): self.assertEqual(px(10), ('10px',)) self.assertEqual(px(0), ('0',)) self.assertEqual(em(5), ('5em',)) self.assertEqual(percent(99), ('99%',)) def test_varargs(self): self.assertEqual(px(10, 9, 8), ('10px', '9px', '8px')) self.assertEqual(px(0, 1), ('0', '1px')) self.assertEqual(em(5, 7), ('5em', '7em')) self.assertEqual(percent(99, 99.9), ('99%', '99.9%')) if __name__ == '__main__': unittest.main()
python
from datetime import datetime from importers.e_trac_importer import ETracImporter from importers.nmea_importer import NMEAImporter from pepys_import.core.formats import rep_line def test_nmea_timestamp_parsing(): parse_timestamp = NMEAImporter.parse_timestamp # Invalid day in date result = parse_timestamp("20201045", "111456") assert not result # Invalid hour in time result = parse_timestamp("20201006", "340738") assert not result def test_etrac_timestamp_parsing(): parse_timestamp = ETracImporter.parse_timestamp # Invalid day in date result = parse_timestamp("2020/04/57", "11:46:23") assert not result # Invalid hour in time result = parse_timestamp("2020/04/07", "34:07:38") assert not result def test_rep_timestamp_parsing(): parse_timestamp = rep_line.parse_timestamp date = "20201001" time = "12010" # missing minute in time result = parse_timestamp(date, time) assert not result time = "340100" # invalid hour in time result = parse_timestamp(date, time) assert not result time = "120105" result = parse_timestamp(date, time) assert result == datetime(2020, 10, 1, 12, 1, 5) time = "120105.1" result = parse_timestamp(date, time) assert result == datetime(2020, 10, 1, 12, 1, 5, 100000) time = "120105.11" result = parse_timestamp(date, time) assert result == datetime(2020, 10, 1, 12, 1, 5, 110000) time = "120105.111" result = parse_timestamp(date, time) assert result == datetime(2020, 10, 1, 12, 1, 5, 111000) time = "120105.1111" result = parse_timestamp(date, time) assert result == datetime(2020, 10, 1, 12, 1, 5, 111100) time = "120105.11111" result = parse_timestamp(date, time) assert result == datetime(2020, 10, 1, 12, 1, 5, 111110) time = "120105.111111" result = parse_timestamp(date, time) assert result == datetime(2020, 10, 1, 12, 1, 5, 111111) time = "120101.1234567" # invalid decimals in time result = parse_timestamp(date, time) assert not result
python
from flask_wtf import FlaskForm from wtforms import IntegerField from wtforms import SelectField from wtforms import SubmitField from wtforms import StringField from wtforms import FileField from wtforms import SelectField from wtforms import PasswordField from wtforms.validators import Email, Length, Required from wtforms.fields.html5 import DateField class registroCliente(FlaskForm): numeroIdCliente = IntegerField('Numero Identificacion', validators=[ Required(message='El campo es obligatorio'), Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres') ]) tipoId = SelectField('Tipo Idenficacion', choices=[ ('CC','Cedula de Ciudadania'), ('CE','Cedula de Extrangeria'), ('PA','Pasaporte'), ('RC','Registro Civil'), ('TI','Tarjeta de Identidad')], validators=[ Required(message='El campo es obligatorio'), ]) fechaExpIdCliente = DateField('Fecha Expedicion Documento Identidad', format='%Y,%M,%D') lugarExpIdCliente = SelectField('Ciudad Expedicion Documento Identidad', choices=[ (5001,'Medellín'), (5002,'Abejorral'), (5004,'Abriaquí'), (5021,'Alejandría'), (5030,'Amagá'), (5031,'Amalfi'), (5034,'Andes'), (5036,'Angelópolis'), (5038,'Angostura'), (5040,'Anorí'), (5042,'Santafé De Antioquia'), (5044,'Anza'), (5045,'Apartadó'), (5051,'Arboletes'), (5055,'Argelia'), (5059,'Armenia'), (5079,'Barbosa'), (5086,'Belmira'), (5088,'Bello'), (5091,'Betania'), (5093,'Betulia'), (5101,'Ciudad Bolívar'), (5107,'Briceño'), (5113,'Buriticá'), (5120,'Cáceres'), (5125,'Caicedo'), (5129,'Caldas'), (5134,'Campamento'), (5138,'Cañasgordas'), (5142,'Caracolí'), (5145,'Caramanta'), (5147,'Carepa'), (5148,'El Carmen De Viboral'), (5150,'Carolina'), (5154,'Caucasia'), (5172,'Chigorodó'), (5190,'Cisneros'), (5197,'Cocorná'), (5206,'Concepción'), (5209,'Concordia'), (5212,'Copacabana'), (5234,'Dabeiba'), (5237,'Don Matías'), (5240,'Ebéjico'), (5250,'El Bagre'), (5264,'Entrerrios'), (5266,'Envigado'), (5282,'Fredonia'), (5284,'Frontino'), (5306,'Giraldo'), (5308,'Girardota'), (5310,'Gómez Plata'), (5313,'Granada'), (5315,'Guadalupe'), (5318,'Guarne'), (5321,'Guatape'), (5347,'Heliconia'), (5353,'Hispania'), (5360,'Itagui'), (5361,'Ituango'), (5364,'Jardín'), (5368,'Jericó'), (5376,'La Ceja'), (5380,'La Estrella'), (5390,'La Pintada'), (5400,'La Unión'), (5411,'Liborina'), (5425,'Maceo'), (5440,'Marinilla'), (5467,'Montebello'), (5475,'Murindó'), (5480,'Mutatá'), (5483,'Nariño'), (5490,'Necoclí'), (5495,'Nechí'), (5501,'Olaya'), (5541,'Peñol'), (5543,'Peque'), (5576,'Pueblorrico'), (5579,'Puerto Berrío'), (5585,'Puerto Nare'), (5591,'Puerto Triunfo'), (5604,'Remedios'), (5607,'Retiro'), (5615,'Rionegro'), (5628,'Sabanalarga'), (5631,'Sabaneta'), (5642,'Salgar'), (5647,'San Andrés De Cuerquía'), (5649,'San Carlos'), (5652,'San Francisco'), (5656,'San Jerónimo'), (5658,'San José De La Montaña'), (5659,'San Juan De Urabá'), (5660,'San Luis'), (5664,'San Pedro'), (5665,'San Pedro De Uraba'), (5667,'San Rafael'), (5670,'San Roque'), (5674,'San Vicente'), (5679,'Santa Bárbara'), (5686,'Santa Rosa De Osos'), (5690,'Santo Domingo'), (5697,'El Santuario'), (5736,'Segovia'), (5756,'Sonson'), (5761,'Sopetrán'), (5789,'Támesis'), (5790,'Tarazá'), (5792,'Tarso'), (5809,'Titiribí'), (5819,'Toledo'), (5837,'Turbo'), (5842,'Uramita'), (5847,'Urrao'), (5854,'Valdivia'), (5856,'Valparaíso'), (5858,'Vegachí'), (5861,'Venecia'), (5873,'Vigía Del Fuerte'), (5885,'Yalí'), (5887,'Yarumal'), (5890,'Yolombó'), (5893,'Yondó'), (5895,'Zaragoza'), (8001,'Barranquilla'), (8078,'Baranoa'), (8137,'Campo De La Cruz'), (8141,'Candelaria'), (8296,'Galapa'), (8372,'Juan De Acosta'), (8421,'Luruaco'), (8433,'Malambo'), (8436,'Manatí'), (8520,'Palmar De Varela'), (8549,'Piojó'), (8558,'Polonuevo'), (8560,'Ponedera'), (8573,'Puerto Colombia'), (8606,'Repelón'), (8634,'Sabanagrande'), (8638,'Sabanalarga'), (8675,'Santa Lucía'), (8685,'Santo Tomás'), (8758,'Soledad'), (8770,'Suan'), (8832,'Tubará'), (8849,'Usiacurí'), (11001,'Bogota DC'), (13001,'Cartagena'), (13006,'Choachí'), (13030,'Altos Del Rosario'), (13042,'Arenal'), (13052,'Arjona'), (13062,'Arroyohondo'), (13074,'Barranco De Loba'), (13140,'Calamar'), (13160,'Cantagallo'), (13188,'Cicuco'), (13212,'Córdoba'), (13222,'Clemencia'), (13244,'El Carmen De Bolívar'), (13248,'El Guamo'), (13268,'El Peñón'), (13300,'Hatillo De Loba'), (13430,'Magangué'), (13433,'Mahates'), (13440,'Margarita'), (13442,'María La Baja'), (13458,'Montecristo'), (13468,'Mompós'), (13473,'Morales'), (13549,'Pinillos'), (13580,'Regidor'), (13600,'Río Viejo'), (13620,'San Cristóbal'), (13647,'San Estanislao'), (13650,'San Fernando'), (13654,'San Jacinto'), (13655,'San Jacinto Del Cauca'), (13657,'San Juan Nepomuceno'), (13667,'San Martín De Loba'), (13670,'San Pablo'), (13673,'Santa Catalina'), (13683,'Santa Rosa'), (13688,'Santa Rosa Del Sur'), (13744,'Simití'), (13760,'Soplaviento'), (13780,'Talaigua Nuevo'), (13810,'Tiquisio'), (13836,'Turbaco'), (13838,'Turbaná'), (13873,'Villanueva'), (13894,'Zambrano'), (15001,'Tunja'), (15022,'Almeida'), (15047,'Aquitania'), (15051,'Arcabuco'), (15087,'Belén'), (15090,'Berbeo'), (15092,'Betéitiva'), (15097,'Boavita'), (15104,'Boyacá'), (15106,'Briceño'), (15109,'Buenavista'), (15114,'Busbanzá'), (15131,'Caldas'), (15135,'Campohermoso'), (15162,'Cerinza'), (15172,'Chinavita'), (15176,'Chiquinquirá'), (15180,'Chiscas'), (15183,'Chita'), (15185,'Chitaraque'), (15187,'Chivatá'), (15189,'Ciénega'), (15204,'Cómbita'), (15212,'Coper'), (15215,'Corrales'), (15218,'Covarachía'), (15223,'Cubará'), (15224,'Cucaita'), (15226,'Cuítiva'), (15232,'Chíquiza'), (15236,'Chivor'), (15238,'Duitama'), (15244,'El Cocuy'), (15248,'El6Aspino'), (15272,'Firavitoba'), (15276,'Floresta'), (15293,'Gachantivá'), (15296,'Gameza'), (15299,'Garagoa'), (15317,'Guacamayas'), (15322,'Guateque'), (15325,'Guayatá'), (15332,'Guican'), (15362,'Iza'), (15367,'Jenesano'), (15368,'Jericó'), (15377,'Labranzagrande'), (15380,'La Capilla'), (15401,'La Victoria'), (15403,'La Uvita'), (15407,'Villa De Leyva'), (15425,'Macanal'), (15442,'Maripí'), (15455,'Miraflores'), (15464,'Mongua'), (15466,'Monguí'), (15469,'Moniquirá'), (15476,'Motavita'), (15480,'Muzo'), (15491,'Nobsa'), (15494,'Nuevo Colón'), (15500,'Oicatá'), (15507,'Otanche'), (15511,'Pachavita'), (15514,'Páez'), (15516,'Paipa'), (15518,'Pajarito'), (15522,'Panqueba'), (15531,'Pauna'), (15533,'Paya'), (15537,'Paz De Río'), (15542,'Pesca'), (15550,'Pisba'), (15572,'Puerto Boyacá'), (15580,'Quípama'), (15599,'Ramiriquí'), (15600,'Ráquira'), (15621,'Rondón'), (15632,'Saboyá'), (15638,'Sáchica'), (15646,'Samacá'), (15660,'San Eduardo'), (15664,'San José De Pare'), (15667,'San Luis De Gaceno'), (15673,'San Mateo'), (15676,'San Miguel De Sema'), (15681,'San Pablo De Borbur'), (15686,'Santana'), (15690,'Santa María'), (15693,'Santa Rosa De Viterbo'), (15696,'Santa Sofía'), (15720,'Sativanorte'), (15723,'Sativasur'), (15740,'Siachoque'), (15753,'Soatá'), (15755,'Socotá'), (15757,'Socha'), (15759,'Sogamoso'), (15761,'Somondoco'), (15762,'Sora'), (15763,'Sotaquirá'), (15764,'Soracá'), (15774,'Susacón'), (15776,'Sutamarchán'), (15778,'Sutatenza'), (15790,'Tasco'), (15798,'Tenza'), (15804,'Tibaná'), (15806,'Tibasosa'), (15808,'Tinjacá'), (15810,'Tipacoque'), (15814,'Toca'), (15816,'Togüí'), (15820,'Tópaga'), (15822,'Tota'), (15832,'Tununguá'), (15835,'Turmequé'), (15837,'Tuta'), (15839,'Tutazá'), (15842,'Umbita'), (15861,'Ventaquemada'), (15879,'Viracachá'), (15897,'Zetaquira'), (17001,'Manizales'), (17013,'Aguadas'), (17042,'Anserma'), (17050,'Aranzazu'), (17088,'Belalcázar'), (17174,'Chinchiná'), (17272,'Filadelfia'), (17380,'La Dorada'), (17388,'La Merced'), (17433,'Manzanares'), (17442,'Marmato'), (17444,'Marquetalia'), (17446,'Marulanda'), (17486,'Neira'), (17495,'Norcasia'), (17513,'Pácora'), (17524,'Palestina'), (17541,'Pensilvania'), (17614,'Riosucio'), (17616,'Risaralda'), (17653,'Salamina'), (17662,'Samaná'), (17665,'San José'), (17777,'Supía'), (17867,'Victoria'), (17873,'Villamaría'), (17877,'Viterbo'), (18001,'Florencia'), (18029,'Albania'), (18094,'Belén De Los Andaquies'), (18150,'Cartagena Del Chairá'), (18205,'Curillo'), (18247,'El Doncello'), (18256,'El Paujil'), (18410,'La Montañita'), (18460,'Milán'), (18479,'Morelia'), (18592,'Puerto Rico'), (18610,'San José Del Fragua'), (18753,'San Vicente Del Caguán'), (18756,'Solano'), (18785,'Solita'), (18860,'Valparaíso'), (19001,'Popayán'), (19022,'Almaguer'), (19050,'Argelia'), (19075,'Balboa'), (19100,'Bolívar'), (19110,'Buenos Aires'), (19130,'Cajibío'), (19137,'Caldono'), (19142,'Caloto'), (19212,'Corinto'), (19256,'El Tambo'), (19290,'Florencia'), (19300,'Guachené'), (19318,'Guapi'), (19355,'Inzá'), (19364,'Jambaló'), (19392,'La Sierra'), (19397,'La Vega'), (19418,'López'), (19450,'Mercaderes'), (19455,'Miranda'), (19473,'Morales'), (19513,'Padilla'), (19517,'Paez'), (19532,'Patía'), (19533,'Piamonte'), (19548,'Piendamó'), (19573,'Puerto Tejada'), (19585,'Puracé'), (19622,'Rosas'), (19693,'San Sebastián'), (19698,'Santander De Quilichao'), (19701,'Santa Rosa'), (19743,'Silvia'), (19760,'Sotara'), (19780,'Suárez'), (19785,'Sucre'), (19807,'Timbío'), (19809,'Timbiquí'), (19821,'Toribio'), (19824,'Totoró'), (19845,'Villa Rica'), (20001,'Valledupar'), (20011,'Aguachica'), (20013,'Agustín Codazzi'), (20032,'Astrea'), (20045,'Becerril'), (20060,'Bosconia'), (20175,'Chimichagua'), (20178,'Chiriguaná'), (20228,'Curumaní'), (20238,'El Copey'), (20250,'El Paso'), (20295,'Gamarra'), (20310,'González'), (20383,'La Gloria'), (20400,'La Jagua De Ibirico'), (20443,'Manaure'), (20517,'Pailitas'), (20550,'Pelaya'), (20570,'Pueblo Bello'), (20614,'Río De Oro'), (20621,'La Paz'), (20710,'San Alberto'), (20750,'San Diego'), (20770,'San Martín'), (20787,'Tamalameque'), (23001,'Montería'), (23068,'Ayapel'), (23079,'Buenavista'), (23090,'Canalete'), (23162,'Cereté'), (23168,'Chimá'), (23182,'Chinú'), (23189,'Ciénaga De Oro'), (23300,'Cotorra'), (23350,'La Apartada'), (23417,'Lorica'), (23419,'Los Córdobas'), (23464,'Momil'), (23466,'Montelíbano'), (23500,'Moñitos'), (23555,'Planeta Rica'), (23570,'Pueblo Nuevo'), (23574,'Puerto Escondido'), (23580,'Puerto Libertador'), (23586,'Purísima'), (23660,'Sahagún'), (23670,'San Andrés Sotavento'), (23672,'San Antero'), (23675,'San Bernardo Del Viento'), (23678,'San Carlos'), (23686,'San Pelayo'), (23807,'Tierralta'), (23855,'Valencia'), (25001,'Agua De Dios'), (25019,'Albán'), (25035,'Anapoima'), (25040,'Anolaima'), (25053,'Arbeláez'), (25086,'Beltrán'), (25095,'Bituima'), (25099,'Bojacá'), (25120,'Cabrera'), (25123,'Cachipay'), (25126,'Cajicá'), (25148,'Caparrapí'), (25151,'Caqueza'), (25154,'Carmen De Carupa'), (25168,'Chaguaní'), (25175,'Chía'), (25178,'Chipaque'), (25181,'Choachí'), (25183,'Chocontá'), (25200,'Cogua'), (25214,'Cota'), (25224,'Cucunuba'), (25245,'El Colegio'), (25258,'El Peñón'), (25260,'El Rosal'), (25269,'Facatativá'), (25279,'Fomeque'), (25281,'Fosca'), (25286,'Funza'), (25288,'Fúquene'), (25290,'Fusagasugá'), (25293,'Gachala'), (25295,'Gachancipá'), (25297,'Gachetá'), (25299,'Gama'), (25307,'Girardot'), (25312,'Granada'), (25317,'Guachetá'), (25320,'Guaduas'), (25322,'Guasca'), (25324,'Guataquí'), (25326,'Guatavita'), (25328,'Guayabal De Siquima'), (25335,'Guayabetal'), (25339,'Gutiérrez'), (25368,'Jerusalén'), (25372,'Junín'), (25377,'La Calera'), (25386,'La Mesa'), (25394,'La Palma'), (25398,'La Peña'), (25402,'La Vega'), (25407,'Lenguazaque'), (25426,'Macheta'), (25430,'Madrid'), (25436,'Manta'), (25438,'Medina'), (25473,'Mosquera'), (25483,'Nariño'), (25486,'Nemocón'), (25488,'Nilo'), (25489,'Nimaima'), (25491,'Nocaima'), (25506,'Venecia'), (25513,'Pacho'), (25518,'Paime'), (25524,'Pandi'), (25530,'Paratebueno'), (25535,'Pasca'), (25572,'Puerto Salgar'), (25580,'Pulí'), (25592,'Quebradanegra'), (25594,'Quetame'), (25596,'Quipile'), (25599,'Apulo'), (25612,'Ricaurte'), (25645,'San Antonio Del Tequendama'), (25649,'San Bernardo'), (25653,'San Cayetano'), (25658,'San Francisco'), (25662,'San Juan De Río Seco'), (25718,'Sasaima'), (25736,'Sesquilé'), (25740,'Sibaté'), (25743,'Silvania'), (25745,'Simijaca'), (25754,'Soacha'), (25758,'Sopó'), (25769,'Subachoque'), (25772,'Suesca'), (25777,'Supatá'), (25779,'Susa'), (25781,'Sutatausa'), (25785,'Tabio'), (25793,'Tausa'), (25797,'Tena'), (25799,'Tenjo'), (25805,'Tibacuy'), (25807,'Tibirita'), (25815,'Tocaima'), (25817,'Tocancipá'), (25823,'Topaipi'), (25839,'Ubalá'), (25841,'Ubaque'), (25843,'Villa De San Diego De Ubate'), (25845,'Une'), (25851,'Útica'), (25862,'Vergara'), (25867,'Vianí'), (25871,'Villagómez'), (25873,'Villapinzón'), (25875,'Villeta'), (25878,'Viotá'), (25885,'Yacopí'), (25898,'Zipacón'), (25899,'Zipaquirá'), (27001,'Quibdó'), (27006,'Acandí'), (27025,'Alto Baudo'), (27050,'Atrato'), (27073,'Bagadó'), (27075,'Bahía Solano'), (27077,'Bajo Baudó'), (27086,'Belén De Bajirá'), (27099,'Bojaya'), (27135,'El Cantón Del San Pablo'), (27150,'Carmen Del Darien'), (27160,'Cértegui'), (27205,'Condoto'), (27245,'El Carmen De Atrato'), (27250,'El Litoral Del San Juan'), (27361,'Istmina'), (27372,'Juradó'), (27413,'Lloró'), (27425,'Medio Atrato'), (27430,'Medio Baudó'), (27450,'Medio San Juan'), (27491,'Nóvita'), (27495,'Nuquí'), (27580,'Río Iro'), (27600,'Río Quito'), (27615,'Riosucio'), (27660,'San José Del Palmar'), (27745,'Sipí'), (27787,'Tadó'), (27800,'Unguía'), (27810,'Unión Panamericana'), (41001,'Neiva'), (41006,'Acevedo'), (41013,'Agrado'), (41016,'Aipe'), (41020,'Algeciras'), (41026,'Altamira'), (41078,'Baraya'), (41132,'Campoalegre'), (41206,'Colombia'), (41244,'Elías'), (41298,'Garzón'), (41306,'Gigante'), (41319,'Guadalupe'), (41349,'Hobo'), (41357,'Iquira'), (41359,'Isnos'), (41378,'La Argentina'), (41396,'La Plata'), (41483,'Nátaga'), (41503,'Oporapa'), (41518,'Paicol'), (41524,'Palermo'), (41530,'Palestina'), (41548,'Pital'), (41551,'Pitalito'), (41615,'Rivera'), (41660,'Saladoblanco'), (41668,'San Agustín'), (41676,'Santa María'), (41770,'Suaza'), (41791,'Tarqui'), (41797,'Tesalia'), (41799,'Tello'), (41801,'Teruel'), (41807,'Timana'), (41872,'Villavieja'), (41885,'Yaguará'), (44001,'Riohacha'), (44035,'Albania'), (44078,'Barrancas'), (44090,'Dibulla'), (44098,'Distracción'), (44110,'El Molino'), (44279,'Fonseca'), (44378,'Hatonuevo'), (44420,'La Jagua Del Pilar'), (44430,'Maicao'), (44560,'Manaure'), (44650,'San Juan Del Cesar'), (44847,'Uribia'), (44855,'Urumita'), (44874,'Villanueva'), (47001,'Santa Marta'), (47030,'Algarrobo'), (47053,'Aracataca'), (47058,'Ariguaní'), (47161,'Cerro San Antonio'), (47170,'Chibolo'), (47189,'Ciénaga'), (47205,'Concordia'), (47245,'El Banco'), (47258,'El Piñon'), (47268,'El Retén'), (47288,'Fundación'), (47318,'Guamal'), (47460,'Nueva Granada'), (47541,'Pedraza'), (47545,'Pijiño Del Carmen'), (47551,'Pivijay'), (47555,'Plato'), (47570,'Puebloviejo'), (47605,'Remolino'), (47660,'Sabanas De San Angel'), (47675,'Salamina'), (47692,'San Sebastián De Buenavista'), (47703,'San Zenón'), (47707,'Santa Ana'), (47720,'Santa Bárbara De Pinto'), (47745,'Sitionuevo'), (47798,'Tenerife'), (47960,'Zapayán'), (47980,'Zona Bananera'), (50001,'Villavicencio'), (50006,'Acacías'), (50110,'Barranca De Upía'), (50124,'Cabuyaro'), (50150,'Castilla La Nueva'), (50223,'Cubarral'), (50226,'Cumaral'), (50245,'El Calvario'), (50251,'El Castillo'), (50270,'El Dorado'), (50287,'Fuente De Oro'), (50313,'Granada'), (50318,'Guamal'), (50325,'Mapiripán'), (50330,'Mesetas'), (50350,'La Macarena'), (50370,'Uribe'), (50400,'Lejanías'), (50450,'Puerto Concordia'), (50568,'Puerto Gaitán'), (50573,'Puerto López'), (50577,'Puerto Lleras'), (50590,'Puerto Rico'), (50606,'Restrepo'), (50680,'San Carlos De Guaroa'), (50683,'San Juan De Arama'), (50686,'San Juanito'), (50689,'San Martín'), (50711,'Vistahermosa'), (52001,'Pasto'), (52019,'Albán'), (52022,'Aldana'), (52036,'Ancuya'), (52051,'Arboleda'), (52079,'Barbacoas'), (52083,'Belén'), (52110,'Buesaco'), (52203,'Colón'), (52207,'Consaca'), (52210,'Contadero'), (52215,'Córdoba'), (52224,'Cuaspud'), (52227,'Cumbal'), (52233,'Cumbitara'), (52240,'Chachagüí'), (52250,'El Charco'), (52254,'El Peñol'), (52256,'El Rosario'), (52258,'El Tablón De Gómez'), (52260,'El Tambo'), (52287,'Funes'), (52317,'Guachucal'), (52320,'Guaitarilla'), (52323,'Gualmatán'), (52352,'Iles'), (52354,'Imués'), (52356,'Ipiales'), (52378,'La Cruz'), (52381,'La Florida'), (52385,'La Llanada'), (52390,'La Tola'), (52399,'La Unión'), (52405,'Leiva'), (52411,'Linares'), (52418,'Los Andes'), (52427,'Magüi'), (52435,'Mallama'), (52473,'Mosquera'), (52480,'Nariño'), (52490,'Olaya Herrera'), (52506,'Ospina'), (52520,'Francisco Pizarro'), (52540,'Policarpa'), (52560,'Potosí'), (52565,'Providencia'), (52573,'Puerres'), (52585,'Pupiales'), (52612,'Ricaurte'), (52621,'Roberto Payán'), (52678,'Samaniego'), (52683,'Sandoná'), (52685,'San Bernardo'), (52687,'San Lorenzo'), (52693,'San Pablo'), (52694,'San Pedro De Cartago'), (52696,'Santa Bárbara'), (52699,'Santacruz'), (52720,'Sapuyes'), (52786,'Taminango'), (52788,'Tangua'), (52835,'San Andres De Tumaco'), (52838,'Túquerres'), (52885,'Yacuanquer'), (54001,'Cúcuta'), (54003,'Abrego'), (54051,'Arboledas'), (54099,'Bochalema'), (54109,'Bucarasica'), (54125,'Cácota'), (54128,'Cachirá'), (54172,'Chinácota'), (54174,'Chitagá'), (54206,'Convención'), (54223,'Cucutilla'), (54239,'Durania'), (54245,'El Carmen'), (54250,'El Tarra'), (54261,'El Zulia'), (54313,'Gramalote'), (54344,'Hacarí'), (54347,'Herrán'), (54377,'Labateca'), (54385,'La Esperanza'), (54398,'La Playa'), (54405,'Los Patios'), (54418,'Lourdes'), (54480,'Mutiscua'), (54498,'Ocaña'), (54518,'Pamplona'), (54520,'Pamplonita'), (54553,'Puerto Santander'), (54599,'Ragonvalia'), (54660,'Salazar'), (54670,'San Calixto'), (54673,'San Cayetano'), (54680,'Santiago'), (54720,'Sardinata'), (54743,'Silos'), (54800,'Teorama'), (54810,'Tibú'), (54820,'Toledo'), (54871,'Villa Caro'), (54874,'Villa Del Rosario'), (63001,'Armenia'), (63111,'Buenavista'), (63130,'Calarca'), (63190,'Circasia'), (63212,'Córdoba'), (63272,'Filandia'), (63302,'Génova'), (63401,'La Tebaida'), (63470,'Montenegro'), (63548,'Pijao'), (63594,'Quimbaya'), (63690,'Salento'), (66001,'Pereira'), (66045,'Apía'), (66075,'Balboa'), (66088,'Belén De Umbría'), (66170,'Dosquebradas'), (66318,'Guática'), (66383,'La Celia'), (66400,'La Virginia'), (66440,'Marsella'), (66456,'Mistrató'), (66572,'Pueblo Rico'), (66594,'Quinchía'), (66682,'Santa Rosa De Cabal'), (66687,'Santuario'), (68001,'Bucaramanga'), (68013,'Aguada'), (68020,'Albania'), (68051,'Aratoca'), (68077,'Barbosa'), (68079,'Barichara'), (68081,'Barrancabermeja'), (68092,'Betulia'), (68101,'Bolívar'), (68121,'Cabrera'), (68132,'California'), (68147,'Capitanejo'), (68152,'Carcasí'), (68160,'Cepitá'), (68162,'Cerrito'), (68167,'Charalá'), (68169,'Charta'), (68176,'Chima'), (68179,'Chipatá'), (68190,'Cimitarra'), (68207,'Concepción'), (68209,'Confines'), (68211,'Contratación'), (68217,'Coromoro'), (68229,'Curití'), (68235,'El Carmen De Chucurí'), (68245,'El Guacamayo'), (68250,'El Peñón'), (68255,'El Playón'), (68264,'Encino'), (68266,'Enciso'), (68271,'Florián'), (68276,'Floridablanca'), (68296,'Galan'), (68298,'Gambita'), (68307,'Girón'), (68318,'Guaca'), (68320,'Guadalupe'), (68322,'Guapotá'), (68324,'Guavatá'), (68327,'Güepsa'), (68344,'Hato'), (68368,'Jesús María'), (68370,'Jordán'), (68377,'La Belleza'), (68385,'Landázuri'), (68397,'La Paz'), (68406,'Lebríja'), (68418,'Los Santos'), (68425,'Macaravita'), (68432,'Málaga'), (68444,'Matanza'), (68464,'Mogotes'), (68468,'Molagavita'), (68498,'Ocamonte'), (68500,'Oiba'), (68502,'Onzaga'), (68522,'Palmar'), (68524,'Palmas Del Socorro'), (68533,'Páramo'), (68547,'Piedecuesta'), (68549,'Pinchote'), (68572,'Puente Nacional'), (68573,'Puerto Parra'), (68575,'Puerto Wilches'), (68615,'Rionegro'), (68655,'Sabana De Torres'), (68669,'San Andrés'), (68673,'San Benito'), (68679,'San Gil'), (68682,'San Joaquín'), (68684,'San José De Miranda'), (68686,'San Miguel'), (68689,'San Vicente De Chucurí'), (68705,'Santa Bárbara'), (68720,'Santa Helena Del Opón'), (68745,'Simacota'), (68755,'Socorro'), (68770,'Suaita'), (68773,'Sucre'), (68780,'Suratá'), (68820,'Tona'), (68855,'Valle De San José'), (68861,'Vélez'), (68867,'Vetas'), (68872,'Villanueva'), (68895,'Zapatoca'), (70001,'Sincelejo'), (70110,'Buenavista'), (70124,'Caimito'), (70204,'Coloso'), (70215,'Corozal'), (70221,'Coveñas'), (70230,'Chalán'), (70233,'El Roble'), (70235,'Galeras'), (70265,'Guaranda'), (70400,'La Unión'), (70418,'Los Palmitos'), (70429,'Majagual'), (70473,'Morroa'), (70508,'Ovejas'), (70523,'Palmito'), (70670,'Sampués'), (70678,'San Benito Abad'), (70702,'San Juan De Betulia'), (70708,'San Marcos'), (70713,'San Onofre'), (70717,'San Pedro'), (70742,'San Luis De Sincé'), (70771,'Sucre'), (70820,'Santiago De Tolú'), (70823,'Tolú Viejo'), (73001,'Ibague'), (73024,'Alpujarra'), (73026,'Alvarado'), (73030,'Ambalema'), (73043,'Anzoátegui'), (73055,'Armero'), (73067,'Ataco'), (73124,'Cajamarca'), (73148,'Carmen De Apicalá'), (73152,'Casabianca'), (73168,'Chaparral'), (73200,'Coello'), (73217,'Coyaima'), (73226,'Cunday'), (73236,'Dolores'), (73268,'Espinal'), (73270,'Falan'), (73275,'Flandes'), (73283,'Fresno'), (73319,'Guamo'), (73347,'Herveo'), (73349,'Honda'), (73352,'Icononzo'), (73408,'Lérida'), (73411,'Líbano'), (73443,'Mariquita'), (73449,'Melgar'), (73461,'Murillo'), (73483,'Natagaima'), (73504,'Ortega'), (73520,'Palocabildo'), (73547,'Piedras'), (73555,'Planadas'), (73563,'Prado'), (73585,'Purificación'), (73616,'Rioblanco'), (73622,'Roncesvalles'), (73624,'Rovira'), (73671,'Saldaña'), (73675,'San Antonio'), (73678,'San Luis'), (73686,'Santa Isabel'), (73770,'Suárez'), (73854,'Valle De San Juan'), (73861,'Venadillo'), (73870,'Villahermosa'), (73873,'Villarrica'), (76001,'Cali'), (76020,'Alcalá'), (76036,'Andalucía'), (76041,'Ansermanuevo'), (76054,'Argelia'), (76100,'Bolívar'), (76109,'Buenaventura'), (76111,'Guadalajara De Buga'), (76113,'Bugalagrande'), (76122,'Caicedonia'), (76126,'Calima'), (76130,'Candelaria'), (76147,'Cartago'), (76233,'Dagua'), (76243,'El Águila'), (76246,'El Cairo'), (76248,'El Cerrito'), (76250,'El Dovio'), (76275,'Florida'), (76306,'Ginebra'), (76318,'Guacarí'), (76364,'Jamundí'), (76377,'La Cumbre'), (76400,'La Unión'), (76403,'La Victoria'), (76497,'Obando'), (76520,'Palmira'), (76563,'Pradera'), (76606,'Restrepo'), (76616,'Riofrío'), (76622,'Roldanillo'), (76670,'San Pedro'), (76736,'Sevilla'), (76823,'Toro'), (76828,'Trujillo'), (76834,'Tuluá'), (76845,'Ulloa'), (76863,'Versalles'), (76869,'Vijes'), (76890,'Yotoco'), (76892,'Yumbo'), (76895,'Zarzal'), (81001,'Arauca'), (81065,'Arauquita'), (81220,'Cravo Norte'), (81300,'Fortul'), (81591,'Puerto Rondón'), (81736,'Saravena'), (81794,'Tame'), (85001,'Yopal'), (85010,'Aguazul'), (85015,'Chameza'), (85125,'Hato Corozal'), (85136,'La Salina'), (85139,'Maní'), (85162,'Monterrey'), (85225,'Nunchía'), (85230,'Orocué'), (85250,'Paz De Ariporo'), (85263,'Pore'), (85279,'Recetor'), (85300,'Sabanalarga'), (85315,'Sácama'), (85325,'San Luis De Palenque'), (85400,'Támara'), (85410,'Tauramena'), (85430,'Trinidad'), (85440,'Villanueva'), (86001,'Mocoa'), (86219,'Colón'), (86320,'Orito'), (86568,'Puerto Asís'), (86569,'Puerto Caicedo'), (86571,'Puerto Guzmán'), (86573,'Leguízamo'), (86749,'Sibundoy'), (86755,'San Francisco'), (86757,'San Miguel'), (86760,'Santiago'), (86865,'Valle Del Guamuez'), (86885,'Villagarzón'), (88001,'San Andrés'), (88564,'Providencia'), (91001,'Leticia'), (91263,'El Encanto'), (91405,'La Chorrera'), (91407,'La Pedrera'), (91430,'La Victoria'), (91460,'Miriti - Paraná'), (91530,'Puerto Alegría'), (91536,'Puerto Arica'), (91540,'Puerto Nariño'), (91669,'Puerto Santander'), (91798,'Tarapacá'), (94001,'Inírida'), (94343,'Barranco Minas'), (94663,'Mapiripana'), (94883,'San Felipe'), (94884,'Puerto Colombia'), (94885,'La Guadalupe'), (94886,'Cacahual'), (94887,'Pana Pana'), (94888,'Morichal'), (95001,'San José Del Guaviare'), (95015,'Calamar'), (95025,'El Retorno'), (95200,'Miraflores'), (97001,'Mitú'), (97161,'Caruru'), (97511,'Pacoa'), (97666,'Taraira'), (97777,'Papunaua'), (97889,'Yavaraté'), (99001,'Puerto Carreño'), (99524,'La Primavera'), (99624,'Santa Rosalía'), (99773,'Cumaribo') ], validators=[ Required() ]) primerNombreCliente = StringField('Primer Nombre', validators=[ Required(message='El campo es obligatorio'), Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) segundoNombreCliente = StringField('Segundo Nombre', validators=[ Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) primerApellidoCliente = StringField('Primer Apellido', validators=[ Required(message='El campo es obligatorio'), Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) segundoApellidoCliente = StringField('Segundo Apellido', validators=[ Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) fechaNacimientoCliente = DateField('Fecha de Nacimiento', format='%Y,%M,%D', validators=[]) direccionCliente = StringField('Direccion Residencia', validators=[ Required(message='El campo es obligatorio'), Length(max=50, min=20, message='El campo debe tener entre 20 y 50 caracteres') ]) barrioCliente = StringField('Barrio Residencia', validators=[ Required(message='El campo es obligatorio'), Length(max=20, min=10, message='El campo debe tener entre 10 y 20 caracteres') ]) idPais = SelectField('Pais Residencia', choices=[ ('AD','Andorra'), ('AE','Emiratos Arabes Unid'), ('AF','Afganistan'), ('AG','Antigua Y Barbuda'), ('AI','Anguilla'), ('AL','Albania'), ('AM','Armenia'), ('AN','Antillas Holandesas'), ('AO','Angola'), ('AR','Argentina'), ('AS','Samoa Norteamericana'), ('AT','Austria'), ('AU','Australia'), ('AW','Aruba'), ('AZ','Azerbaijan'), ('BA','Bosnia-Herzegovina'), ('BB','Barbados'), ('BD','Bangladesh'), ('BE','Belgica'), ('BF','Burkina Fasso'), ('BG','Bulgaria'), ('BH','Bahrein'), ('BI','Burundi'), ('BJ','Benin'), ('BM','Bermudas'), ('BN','Brunei Darussalam'), ('BO','Bolivia'), ('BR','Brasil'), ('BS','Bahamas'), ('BT','Butan'), ('BW','Botswana'), ('BY','Belorus'), ('BZ','Belice'), ('CA','Canada'), ('CC','Cocos (Keeling) Islas'), ('CD','Republica Democratica Del Congo'), ('CF','Republica Centroafri'), ('CG','Congo'), ('CH','Suiza'), ('CI','Costa De Marfil'), ('CK','Cook Islas'), ('CL','Chile'), ('CM','Camerun Republica U'), ('CN','China'), ('CO','Colombia'), ('CR','Costa Rica'), ('CU','Cuba'), ('CV','Cabo Verde'), ('CX','Navidad (Christmas)'), ('CY','Chipre'), ('CZ','Republica Checa'), ('DE','Alemania'), ('DJ','Djibouti'), ('DK','Dinamarca'), ('DM','Dominica'), ('DO','Republica Dominicana'), ('DZ','Argelia'), ('EC','Ecuador'), ('EE','Estonia'), ('EG','Egipto'), ('EH','Sahara Occidental'), ('ER','Eritrea'), ('ES','España'), ('ET','Etiopia'), ('EU','Comunidad Europea'), ('FI','Finlandia'), ('FJ','Fiji'), ('FM','Micronesia Estados F'), ('FO','Feroe Islas'), ('FR','Francia'), ('GA','Gabon'), ('GB','Reino Unido'), ('GD','Granada'), ('GE','Georgia'), ('GF','Guayana Francesa'), ('GH','Ghana'), ('GI','Gibraltar'), ('GL','Groenlandia'), ('GM','Gambia'), ('GN','Guinea'), ('GP','Guadalupe'), ('GQ','Guinea Ecuatorial'), ('GR','Grecia'), ('GT','Guatemala'), ('GU','Guam'), ('GW','Guinea - Bissau'), ('GY','Guyana'), ('HK','Hong Kong'), ('HN','Honduras'), ('HR','Croacia'), ('HT','Haiti'), ('HU','Hungria'), ('ID','Indonesia'), ('IE','Irlanda (Eire)'), ('IL','Israel'), ('IM','Isla De Man'), ('IN','India'), ('IO','Territori Britanico'), ('IQ','Irak'), ('IR','Iran Republica Islamica'), ('IS','Islandia'), ('IT','Italia'), ('JM','Jamaica'), ('JO','Jordania'), ('JP','Japon'), ('KE','Kenya'), ('KG','Kirguizistan'), ('KH','Kampuchea (Camboya)'), ('KI','Kiribati'), ('KM','Comoras'), ('KN','San Cristobal Y Nieves'), ('KP','Corea Del Norte Republica'), ('KR','Corea Del Sur Republica'), ('KW','Kuwait'), ('KY','Caiman Islas'), ('KZ','Kazajstan'), ('LA','Laos Republica Popular'), ('LB','Libano'), ('LC','Santa Lucia'), ('LI','Liechtenstein'), ('LK','Sri Lanka'), ('LR','Liberia'), ('LS','Lesotho'), ('LT','Lituania'), ('LU','Luxemburgo'), ('LV','Letonia'), ('LY','Libia(Incluye Fezzan'), ('MA','Marruecos'), ('MC','Monaco'), ('MD','Moldavia'), ('MG','Madagascar'), ('MH','Marshall Islas'), ('MK','Macedonia'), ('ML','Mali'), ('MM','Birmania (Myanmar)'), ('MN','Mongolia'), ('MO','Macao'), ('MP','Marianas Del Norte Islas'), ('MQ','Martinica'), ('MR','Mauritania'), ('MS','Monserrat Islas'), ('MT','Malta'), ('MU','Mauricio'), ('MV','Maldivas'), ('MW','Malawi'), ('MX','Mexico'), ('MY','Malasia'), ('MZ','Mozambique'), ('NA','Namibia'), ('NC','Nueva Caledonia'), ('NE','Niger'), ('NF','Norfolk Isla'), ('NG','Nigeria'), ('NI','Nicaragua'), ('NL','Paises Bajos(Holanda'), ('NO','Noruega'), ('NP','Nepal'), ('NR','Nauru'), ('NU','Nive Isla'), ('NZ','Nueva Zelandia'), ('OM','Oman'), ('PA','Panama'), ('PE','Peru'), ('PF','Polinesia Francesa'), ('PG','Papuasia Nuev Guinea'), ('PH','Filipinas'), ('PK','Pakistan'), ('PL','Polonia'), ('PM','San Pedro Y Miguelon'), ('PN','Pitcairn Isla'), ('PR','Puerto Rico'), ('PS','Palestina'), ('PT','Portugal'), ('PW','Palau Islas'), ('PY','Paraguay'), ('QA','Qatar'), ('RE','Reunion'), ('RO','Rumania'), ('RS','Serbia'), ('RU','Rusia'), ('RW','Rwanda'), ('SA','Arabia Saudita'), ('SB','Salomsn Islas'), ('SC','Seychelles'), ('SD','Sudan'), ('SE','Suecia'), ('SG','Singapur'), ('SH','Santa Elena'), ('SI','Eslovenia'), ('SK','Eslovaquia'), ('SL','Sierra Leona'), ('SM','San Marino'), ('SN','Senegal'), ('SO','Somalia'), ('SR','Surinam'), ('ST','Santo Tome Y Princip'), ('SV','El Salvador'), ('SY','Siria Republica Arabe'), ('SZ','Swazilandia'), ('TC','Turcas Y Caicos Isla'), ('TD','Chad'), ('TG','Togo'), ('TH','Tailandia'), ('TJ','Tadjikistan'), ('TK','Tokelau'), ('TL','Timor Del Este'), ('TM','Turkmenistan'), ('TN','Tunicia'), ('TO','Tonga'), ('TR','Turquia'), ('TT','Trinidad Y Tobago'), ('TV','Tuvalu'), ('TW','Taiwan (Formosa)'), ('TZ','Tanzania Republica'), ('UA','Ucrania'), ('UG','Uganda'), ('UM','Islas Menores De Estados Unidos'), ('UN','Niue Isla'), ('US','Estados Unidos'), ('UY','Uruguay'), ('UZ','Uzbekistan'), ('VA','Ciudad Del Vaticano'), ('VC','San Vicente Y Las Gr'), ('VE','Venezuela'), ('VG','Virgenes Islas Britanicas'), ('VI','Virgenes Islas'), ('VN','Vietnam'), ('VU','Vanuatu'), ('WF','Wallis Y Fortuna Islas'), ('WS','Samoa'), ('YE','Yemen'), ('YU','Yugoslavia'), ('ZA','Sudafrica Republica'), ('ZM','Zambia'), ('ZW','Zimbabwe') ], validate_choice=True) idDepartamento = SelectField('Departamento Residencia', choices=[ (5,'Antioquia'), (8,'Atlántico'), (11,'Bogotá DC'), (13,'Bolívar'), (15,'Boyacá'), (17,'Caldas'), (18,'Caquetá'), (19,'Cauca'), (20,'Cesar'), (23,'Córdoba'), (25,'Cundinamarca'), (27,'Chocó'), (41,'Huila'), (44,'La Guajira'), (47,'Magdalena'), (50,'Meta'), (52,'Nariño'), (54,'Norte de Santander'), (63,'Quindío'), (66,'Risaralda'), (68,'Santander'), (70,'Sucre'), (73,'Tolima'), (76,'Valle del Cauca'), (81,'Arauca'), (85,'Casanare'), (86,'Putumayo'), (88,'San Andres'), (91,'Amazonas'), (94,'Guainía'), (95,'Guaviare'), (97,'Vaupés'), (99,'Vichada'), ], validate_choice=True) idMunicipio = SelectField('Municipio Residencia', choices=[ (5001,'Medellín'), (5002,'Abejorral'), (5004,'Abriaquí'), (5021,'Alejandría'), (5030,'Amagá'), (5031,'Amalfi'), (5034,'Andes'), (5036,'Angelópolis'), (5038,'Angostura'), (5040,'Anorí'), (5042,'Santafé De Antioquia'), (5044,'Anza'), (5045,'Apartadó'), (5051,'Arboletes'), (5055,'Argelia'), (5059,'Armenia'), (5079,'Barbosa'), (5086,'Belmira'), (5088,'Bello'), (5091,'Betania'), (5093,'Betulia'), (5101,'Ciudad Bolívar'), (5107,'Briceño'), (5113,'Buriticá'), (5120,'Cáceres'), (5125,'Caicedo'), (5129,'Caldas'), (5134,'Campamento'), (5138,'Cañasgordas'), (5142,'Caracolí'), (5145,'Caramanta'), (5147,'Carepa'), (5148,'El Carmen De Viboral'), (5150,'Carolina'), (5154,'Caucasia'), (5172,'Chigorodó'), (5190,'Cisneros'), (5197,'Cocorná'), (5206,'Concepción'), (5209,'Concordia'), (5212,'Copacabana'), (5234,'Dabeiba'), (5237,'Don Matías'), (5240,'Ebéjico'), (5250,'El Bagre'), (5264,'Entrerrios'), (5266,'Envigado'), (5282,'Fredonia'), (5284,'Frontino'), (5306,'Giraldo'), (5308,'Girardota'), (5310,'Gómez Plata'), (5313,'Granada'), (5315,'Guadalupe'), (5318,'Guarne'), (5321,'Guatape'), (5347,'Heliconia'), (5353,'Hispania'), (5360,'Itagui'), (5361,'Ituango'), (5364,'Jardín'), (5368,'Jericó'), (5376,'La Ceja'), (5380,'La Estrella'), (5390,'La Pintada'), (5400,'La Unión'), (5411,'Liborina'), (5425,'Maceo'), (5440,'Marinilla'), (5467,'Montebello'), (5475,'Murindó'), (5480,'Mutatá'), (5483,'Nariño'), (5490,'Necoclí'), (5495,'Nechí'), (5501,'Olaya'), (5541,'Peñol'), (5543,'Peque'), (5576,'Pueblorrico'), (5579,'Puerto Berrío'), (5585,'Puerto Nare'), (5591,'Puerto Triunfo'), (5604,'Remedios'), (5607,'Retiro'), (5615,'Rionegro'), (5628,'Sabanalarga'), (5631,'Sabaneta'), (5642,'Salgar'), (5647,'San Andrés De Cuerquía'), (5649,'San Carlos'), (5652,'San Francisco'), (5656,'San Jerónimo'), (5658,'San José De La Montaña'), (5659,'San Juan De Urabá'), (5660,'San Luis'), (5664,'San Pedro'), (5665,'San Pedro De Uraba'), (5667,'San Rafael'), (5670,'San Roque'), (5674,'San Vicente'), (5679,'Santa Bárbara'), (5686,'Santa Rosa De Osos'), (5690,'Santo Domingo'), (5697,'El Santuario'), (5736,'Segovia'), (5756,'Sonson'), (5761,'Sopetrán'), (5789,'Támesis'), (5790,'Tarazá'), (5792,'Tarso'), (5809,'Titiribí'), (5819,'Toledo'), (5837,'Turbo'), (5842,'Uramita'), (5847,'Urrao'), (5854,'Valdivia'), (5856,'Valparaíso'), (5858,'Vegachí'), (5861,'Venecia'), (5873,'Vigía Del Fuerte'), (5885,'Yalí'), (5887,'Yarumal'), (5890,'Yolombó'), (5893,'Yondó'), (5895,'Zaragoza'), (8001,'Barranquilla'), (8078,'Baranoa'), (8137,'Campo De La Cruz'), (8141,'Candelaria'), (8296,'Galapa'), (8372,'Juan De Acosta'), (8421,'Luruaco'), (8433,'Malambo'), (8436,'Manatí'), (8520,'Palmar De Varela'), (8549,'Piojó'), (8558,'Polonuevo'), (8560,'Ponedera'), (8573,'Puerto Colombia'), (8606,'Repelón'), (8634,'Sabanagrande'), (8638,'Sabanalarga'), (8675,'Santa Lucía'), (8685,'Santo Tomás'), (8758,'Soledad'), (8770,'Suan'), (8832,'Tubará'), (8849,'Usiacurí'), (11001,'Bogota DC'), (13001,'Cartagena'), (13006,'Choachí'), (13030,'Altos Del Rosario'), (13042,'Arenal'), (13052,'Arjona'), (13062,'Arroyohondo'), (13074,'Barranco De Loba'), (13140,'Calamar'), (13160,'Cantagallo'), (13188,'Cicuco'), (13212,'Córdoba'), (13222,'Clemencia'), (13244,'El Carmen De Bolívar'), (13248,'El Guamo'), (13268,'El Peñón'), (13300,'Hatillo De Loba'), (13430,'Magangué'), (13433,'Mahates'), (13440,'Margarita'), (13442,'María La Baja'), (13458,'Montecristo'), (13468,'Mompós'), (13473,'Morales'), (13549,'Pinillos'), (13580,'Regidor'), (13600,'Río Viejo'), (13620,'San Cristóbal'), (13647,'San Estanislao'), (13650,'San Fernando'), (13654,'San Jacinto'), (13655,'San Jacinto Del Cauca'), (13657,'San Juan Nepomuceno'), (13667,'San Martín De Loba'), (13670,'San Pablo'), (13673,'Santa Catalina'), (13683,'Santa Rosa'), (13688,'Santa Rosa Del Sur'), (13744,'Simití'), (13760,'Soplaviento'), (13780,'Talaigua Nuevo'), (13810,'Tiquisio'), (13836,'Turbaco'), (13838,'Turbaná'), (13873,'Villanueva'), (13894,'Zambrano'), (15001,'Tunja'), (15022,'Almeida'), (15047,'Aquitania'), (15051,'Arcabuco'), (15087,'Belén'), (15090,'Berbeo'), (15092,'Betéitiva'), (15097,'Boavita'), (15104,'Boyacá'), (15106,'Briceño'), (15109,'Buenavista'), (15114,'Busbanzá'), (15131,'Caldas'), (15135,'Campohermoso'), (15162,'Cerinza'), (15172,'Chinavita'), (15176,'Chiquinquirá'), (15180,'Chiscas'), (15183,'Chita'), (15185,'Chitaraque'), (15187,'Chivatá'), (15189,'Ciénega'), (15204,'Cómbita'), (15212,'Coper'), (15215,'Corrales'), (15218,'Covarachía'), (15223,'Cubará'), (15224,'Cucaita'), (15226,'Cuítiva'), (15232,'Chíquiza'), (15236,'Chivor'), (15238,'Duitama'), (15244,'El Cocuy'), (15248,'El6Aspino'), (15272,'Firavitoba'), (15276,'Floresta'), (15293,'Gachantivá'), (15296,'Gameza'), (15299,'Garagoa'), (15317,'Guacamayas'), (15322,'Guateque'), (15325,'Guayatá'), (15332,'Guican'), (15362,'Iza'), (15367,'Jenesano'), (15368,'Jericó'), (15377,'Labranzagrande'), (15380,'La Capilla'), (15401,'La Victoria'), (15403,'La Uvita'), (15407,'Villa De Leyva'), (15425,'Macanal'), (15442,'Maripí'), (15455,'Miraflores'), (15464,'Mongua'), (15466,'Monguí'), (15469,'Moniquirá'), (15476,'Motavita'), (15480,'Muzo'), (15491,'Nobsa'), (15494,'Nuevo Colón'), (15500,'Oicatá'), (15507,'Otanche'), (15511,'Pachavita'), (15514,'Páez'), (15516,'Paipa'), (15518,'Pajarito'), (15522,'Panqueba'), (15531,'Pauna'), (15533,'Paya'), (15537,'Paz De Río'), (15542,'Pesca'), (15550,'Pisba'), (15572,'Puerto Boyacá'), (15580,'Quípama'), (15599,'Ramiriquí'), (15600,'Ráquira'), (15621,'Rondón'), (15632,'Saboyá'), (15638,'Sáchica'), (15646,'Samacá'), (15660,'San Eduardo'), (15664,'San José De Pare'), (15667,'San Luis De Gaceno'), (15673,'San Mateo'), (15676,'San Miguel De Sema'), (15681,'San Pablo De Borbur'), (15686,'Santana'), (15690,'Santa María'), (15693,'Santa Rosa De Viterbo'), (15696,'Santa Sofía'), (15720,'Sativanorte'), (15723,'Sativasur'), (15740,'Siachoque'), (15753,'Soatá'), (15755,'Socotá'), (15757,'Socha'), (15759,'Sogamoso'), (15761,'Somondoco'), (15762,'Sora'), (15763,'Sotaquirá'), (15764,'Soracá'), (15774,'Susacón'), (15776,'Sutamarchán'), (15778,'Sutatenza'), (15790,'Tasco'), (15798,'Tenza'), (15804,'Tibaná'), (15806,'Tibasosa'), (15808,'Tinjacá'), (15810,'Tipacoque'), (15814,'Toca'), (15816,'Togüí'), (15820,'Tópaga'), (15822,'Tota'), (15832,'Tununguá'), (15835,'Turmequé'), (15837,'Tuta'), (15839,'Tutazá'), (15842,'Umbita'), (15861,'Ventaquemada'), (15879,'Viracachá'), (15897,'Zetaquira'), (17001,'Manizales'), (17013,'Aguadas'), (17042,'Anserma'), (17050,'Aranzazu'), (17088,'Belalcázar'), (17174,'Chinchiná'), (17272,'Filadelfia'), (17380,'La Dorada'), (17388,'La Merced'), (17433,'Manzanares'), (17442,'Marmato'), (17444,'Marquetalia'), (17446,'Marulanda'), (17486,'Neira'), (17495,'Norcasia'), (17513,'Pácora'), (17524,'Palestina'), (17541,'Pensilvania'), (17614,'Riosucio'), (17616,'Risaralda'), (17653,'Salamina'), (17662,'Samaná'), (17665,'San José'), (17777,'Supía'), (17867,'Victoria'), (17873,'Villamaría'), (17877,'Viterbo'), (18001,'Florencia'), (18029,'Albania'), (18094,'Belén De Los Andaquies'), (18150,'Cartagena Del Chairá'), (18205,'Curillo'), (18247,'El Doncello'), (18256,'El Paujil'), (18410,'La Montañita'), (18460,'Milán'), (18479,'Morelia'), (18592,'Puerto Rico'), (18610,'San José Del Fragua'), (18753,'San Vicente Del Caguán'), (18756,'Solano'), (18785,'Solita'), (18860,'Valparaíso'), (19001,'Popayán'), (19022,'Almaguer'), (19050,'Argelia'), (19075,'Balboa'), (19100,'Bolívar'), (19110,'Buenos Aires'), (19130,'Cajibío'), (19137,'Caldono'), (19142,'Caloto'), (19212,'Corinto'), (19256,'El Tambo'), (19290,'Florencia'), (19300,'Guachené'), (19318,'Guapi'), (19355,'Inzá'), (19364,'Jambaló'), (19392,'La Sierra'), (19397,'La Vega'), (19418,'López'), (19450,'Mercaderes'), (19455,'Miranda'), (19473,'Morales'), (19513,'Padilla'), (19517,'Paez'), (19532,'Patía'), (19533,'Piamonte'), (19548,'Piendamó'), (19573,'Puerto Tejada'), (19585,'Puracé'), (19622,'Rosas'), (19693,'San Sebastián'), (19698,'Santander De Quilichao'), (19701,'Santa Rosa'), (19743,'Silvia'), (19760,'Sotara'), (19780,'Suárez'), (19785,'Sucre'), (19807,'Timbío'), (19809,'Timbiquí'), (19821,'Toribio'), (19824,'Totoró'), (19845,'Villa Rica'), (20001,'Valledupar'), (20011,'Aguachica'), (20013,'Agustín Codazzi'), (20032,'Astrea'), (20045,'Becerril'), (20060,'Bosconia'), (20175,'Chimichagua'), (20178,'Chiriguaná'), (20228,'Curumaní'), (20238,'El Copey'), (20250,'El Paso'), (20295,'Gamarra'), (20310,'González'), (20383,'La Gloria'), (20400,'La Jagua De Ibirico'), (20443,'Manaure'), (20517,'Pailitas'), (20550,'Pelaya'), (20570,'Pueblo Bello'), (20614,'Río De Oro'), (20621,'La Paz'), (20710,'San Alberto'), (20750,'San Diego'), (20770,'San Martín'), (20787,'Tamalameque'), (23001,'Montería'), (23068,'Ayapel'), (23079,'Buenavista'), (23090,'Canalete'), (23162,'Cereté'), (23168,'Chimá'), (23182,'Chinú'), (23189,'Ciénaga De Oro'), (23300,'Cotorra'), (23350,'La Apartada'), (23417,'Lorica'), (23419,'Los Córdobas'), (23464,'Momil'), (23466,'Montelíbano'), (23500,'Moñitos'), (23555,'Planeta Rica'), (23570,'Pueblo Nuevo'), (23574,'Puerto Escondido'), (23580,'Puerto Libertador'), (23586,'Purísima'), (23660,'Sahagún'), (23670,'San Andrés Sotavento'), (23672,'San Antero'), (23675,'San Bernardo Del Viento'), (23678,'San Carlos'), (23686,'San Pelayo'), (23807,'Tierralta'), (23855,'Valencia'), (25001,'Agua De Dios'), (25019,'Albán'), (25035,'Anapoima'), (25040,'Anolaima'), (25053,'Arbeláez'), (25086,'Beltrán'), (25095,'Bituima'), (25099,'Bojacá'), (25120,'Cabrera'), (25123,'Cachipay'), (25126,'Cajicá'), (25148,'Caparrapí'), (25151,'Caqueza'), (25154,'Carmen De Carupa'), (25168,'Chaguaní'), (25175,'Chía'), (25178,'Chipaque'), (25181,'Choachí'), (25183,'Chocontá'), (25200,'Cogua'), (25214,'Cota'), (25224,'Cucunuba'), (25245,'El Colegio'), (25258,'El Peñón'), (25260,'El Rosal'), (25269,'Facatativá'), (25279,'Fomeque'), (25281,'Fosca'), (25286,'Funza'), (25288,'Fúquene'), (25290,'Fusagasugá'), (25293,'Gachala'), (25295,'Gachancipá'), (25297,'Gachetá'), (25299,'Gama'), (25307,'Girardot'), (25312,'Granada'), (25317,'Guachetá'), (25320,'Guaduas'), (25322,'Guasca'), (25324,'Guataquí'), (25326,'Guatavita'), (25328,'Guayabal De Siquima'), (25335,'Guayabetal'), (25339,'Gutiérrez'), (25368,'Jerusalén'), (25372,'Junín'), (25377,'La Calera'), (25386,'La Mesa'), (25394,'La Palma'), (25398,'La Peña'), (25402,'La Vega'), (25407,'Lenguazaque'), (25426,'Macheta'), (25430,'Madrid'), (25436,'Manta'), (25438,'Medina'), (25473,'Mosquera'), (25483,'Nariño'), (25486,'Nemocón'), (25488,'Nilo'), (25489,'Nimaima'), (25491,'Nocaima'), (25506,'Venecia'), (25513,'Pacho'), (25518,'Paime'), (25524,'Pandi'), (25530,'Paratebueno'), (25535,'Pasca'), (25572,'Puerto Salgar'), (25580,'Pulí'), (25592,'Quebradanegra'), (25594,'Quetame'), (25596,'Quipile'), (25599,'Apulo'), (25612,'Ricaurte'), (25645,'San Antonio Del Tequendama'), (25649,'San Bernardo'), (25653,'San Cayetano'), (25658,'San Francisco'), (25662,'San Juan De Río Seco'), (25718,'Sasaima'), (25736,'Sesquilé'), (25740,'Sibaté'), (25743,'Silvania'), (25745,'Simijaca'), (25754,'Soacha'), (25758,'Sopó'), (25769,'Subachoque'), (25772,'Suesca'), (25777,'Supatá'), (25779,'Susa'), (25781,'Sutatausa'), (25785,'Tabio'), (25793,'Tausa'), (25797,'Tena'), (25799,'Tenjo'), (25805,'Tibacuy'), (25807,'Tibirita'), (25815,'Tocaima'), (25817,'Tocancipá'), (25823,'Topaipi'), (25839,'Ubalá'), (25841,'Ubaque'), (25843,'Villa De San Diego De Ubate'), (25845,'Une'), (25851,'Útica'), (25862,'Vergara'), (25867,'Vianí'), (25871,'Villagómez'), (25873,'Villapinzón'), (25875,'Villeta'), (25878,'Viotá'), (25885,'Yacopí'), (25898,'Zipacón'), (25899,'Zipaquirá'), (27001,'Quibdó'), (27006,'Acandí'), (27025,'Alto Baudo'), (27050,'Atrato'), (27073,'Bagadó'), (27075,'Bahía Solano'), (27077,'Bajo Baudó'), (27086,'Belén De Bajirá'), (27099,'Bojaya'), (27135,'El Cantón Del San Pablo'), (27150,'Carmen Del Darien'), (27160,'Cértegui'), (27205,'Condoto'), (27245,'El Carmen De Atrato'), (27250,'El Litoral Del San Juan'), (27361,'Istmina'), (27372,'Juradó'), (27413,'Lloró'), (27425,'Medio Atrato'), (27430,'Medio Baudó'), (27450,'Medio San Juan'), (27491,'Nóvita'), (27495,'Nuquí'), (27580,'Río Iro'), (27600,'Río Quito'), (27615,'Riosucio'), (27660,'San José Del Palmar'), (27745,'Sipí'), (27787,'Tadó'), (27800,'Unguía'), (27810,'Unión Panamericana'), (41001,'Neiva'), (41006,'Acevedo'), (41013,'Agrado'), (41016,'Aipe'), (41020,'Algeciras'), (41026,'Altamira'), (41078,'Baraya'), (41132,'Campoalegre'), (41206,'Colombia'), (41244,'Elías'), (41298,'Garzón'), (41306,'Gigante'), (41319,'Guadalupe'), (41349,'Hobo'), (41357,'Iquira'), (41359,'Isnos'), (41378,'La Argentina'), (41396,'La Plata'), (41483,'Nátaga'), (41503,'Oporapa'), (41518,'Paicol'), (41524,'Palermo'), (41530,'Palestina'), (41548,'Pital'), (41551,'Pitalito'), (41615,'Rivera'), (41660,'Saladoblanco'), (41668,'San Agustín'), (41676,'Santa María'), (41770,'Suaza'), (41791,'Tarqui'), (41797,'Tesalia'), (41799,'Tello'), (41801,'Teruel'), (41807,'Timana'), (41872,'Villavieja'), (41885,'Yaguará'), (44001,'Riohacha'), (44035,'Albania'), (44078,'Barrancas'), (44090,'Dibulla'), (44098,'Distracción'), (44110,'El Molino'), (44279,'Fonseca'), (44378,'Hatonuevo'), (44420,'La Jagua Del Pilar'), (44430,'Maicao'), (44560,'Manaure'), (44650,'San Juan Del Cesar'), (44847,'Uribia'), (44855,'Urumita'), (44874,'Villanueva'), (47001,'Santa Marta'), (47030,'Algarrobo'), (47053,'Aracataca'), (47058,'Ariguaní'), (47161,'Cerro San Antonio'), (47170,'Chibolo'), (47189,'Ciénaga'), (47205,'Concordia'), (47245,'El Banco'), (47258,'El Piñon'), (47268,'El Retén'), (47288,'Fundación'), (47318,'Guamal'), (47460,'Nueva Granada'), (47541,'Pedraza'), (47545,'Pijiño Del Carmen'), (47551,'Pivijay'), (47555,'Plato'), (47570,'Puebloviejo'), (47605,'Remolino'), (47660,'Sabanas De San Angel'), (47675,'Salamina'), (47692,'San Sebastián De Buenavista'), (47703,'San Zenón'), (47707,'Santa Ana'), (47720,'Santa Bárbara De Pinto'), (47745,'Sitionuevo'), (47798,'Tenerife'), (47960,'Zapayán'), (47980,'Zona Bananera'), (50001,'Villavicencio'), (50006,'Acacías'), (50110,'Barranca De Upía'), (50124,'Cabuyaro'), (50150,'Castilla La Nueva'), (50223,'Cubarral'), (50226,'Cumaral'), (50245,'El Calvario'), (50251,'El Castillo'), (50270,'El Dorado'), (50287,'Fuente De Oro'), (50313,'Granada'), (50318,'Guamal'), (50325,'Mapiripán'), (50330,'Mesetas'), (50350,'La Macarena'), (50370,'Uribe'), (50400,'Lejanías'), (50450,'Puerto Concordia'), (50568,'Puerto Gaitán'), (50573,'Puerto López'), (50577,'Puerto Lleras'), (50590,'Puerto Rico'), (50606,'Restrepo'), (50680,'San Carlos De Guaroa'), (50683,'San Juan De Arama'), (50686,'San Juanito'), (50689,'San Martín'), (50711,'Vistahermosa'), (52001,'Pasto'), (52019,'Albán'), (52022,'Aldana'), (52036,'Ancuya'), (52051,'Arboleda'), (52079,'Barbacoas'), (52083,'Belén'), (52110,'Buesaco'), (52203,'Colón'), (52207,'Consaca'), (52210,'Contadero'), (52215,'Córdoba'), (52224,'Cuaspud'), (52227,'Cumbal'), (52233,'Cumbitara'), (52240,'Chachagüí'), (52250,'El Charco'), (52254,'El Peñol'), (52256,'El Rosario'), (52258,'El Tablón De Gómez'), (52260,'El Tambo'), (52287,'Funes'), (52317,'Guachucal'), (52320,'Guaitarilla'), (52323,'Gualmatán'), (52352,'Iles'), (52354,'Imués'), (52356,'Ipiales'), (52378,'La Cruz'), (52381,'La Florida'), (52385,'La Llanada'), (52390,'La Tola'), (52399,'La Unión'), (52405,'Leiva'), (52411,'Linares'), (52418,'Los Andes'), (52427,'Magüi'), (52435,'Mallama'), (52473,'Mosquera'), (52480,'Nariño'), (52490,'Olaya Herrera'), (52506,'Ospina'), (52520,'Francisco Pizarro'), (52540,'Policarpa'), (52560,'Potosí'), (52565,'Providencia'), (52573,'Puerres'), (52585,'Pupiales'), (52612,'Ricaurte'), (52621,'Roberto Payán'), (52678,'Samaniego'), (52683,'Sandoná'), (52685,'San Bernardo'), (52687,'San Lorenzo'), (52693,'San Pablo'), (52694,'San Pedro De Cartago'), (52696,'Santa Bárbara'), (52699,'Santacruz'), (52720,'Sapuyes'), (52786,'Taminango'), (52788,'Tangua'), (52835,'San Andres De Tumaco'), (52838,'Túquerres'), (52885,'Yacuanquer'), (54001,'Cúcuta'), (54003,'Abrego'), (54051,'Arboledas'), (54099,'Bochalema'), (54109,'Bucarasica'), (54125,'Cácota'), (54128,'Cachirá'), (54172,'Chinácota'), (54174,'Chitagá'), (54206,'Convención'), (54223,'Cucutilla'), (54239,'Durania'), (54245,'El Carmen'), (54250,'El Tarra'), (54261,'El Zulia'), (54313,'Gramalote'), (54344,'Hacarí'), (54347,'Herrán'), (54377,'Labateca'), (54385,'La Esperanza'), (54398,'La Playa'), (54405,'Los Patios'), (54418,'Lourdes'), (54480,'Mutiscua'), (54498,'Ocaña'), (54518,'Pamplona'), (54520,'Pamplonita'), (54553,'Puerto Santander'), (54599,'Ragonvalia'), (54660,'Salazar'), (54670,'San Calixto'), (54673,'San Cayetano'), (54680,'Santiago'), (54720,'Sardinata'), (54743,'Silos'), (54800,'Teorama'), (54810,'Tibú'), (54820,'Toledo'), (54871,'Villa Caro'), (54874,'Villa Del Rosario'), (63001,'Armenia'), (63111,'Buenavista'), (63130,'Calarca'), (63190,'Circasia'), (63212,'Córdoba'), (63272,'Filandia'), (63302,'Génova'), (63401,'La Tebaida'), (63470,'Montenegro'), (63548,'Pijao'), (63594,'Quimbaya'), (63690,'Salento'), (66001,'Pereira'), (66045,'Apía'), (66075,'Balboa'), (66088,'Belén De Umbría'), (66170,'Dosquebradas'), (66318,'Guática'), (66383,'La Celia'), (66400,'La Virginia'), (66440,'Marsella'), (66456,'Mistrató'), (66572,'Pueblo Rico'), (66594,'Quinchía'), (66682,'Santa Rosa De Cabal'), (66687,'Santuario'), (68001,'Bucaramanga'), (68013,'Aguada'), (68020,'Albania'), (68051,'Aratoca'), (68077,'Barbosa'), (68079,'Barichara'), (68081,'Barrancabermeja'), (68092,'Betulia'), (68101,'Bolívar'), (68121,'Cabrera'), (68132,'California'), (68147,'Capitanejo'), (68152,'Carcasí'), (68160,'Cepitá'), (68162,'Cerrito'), (68167,'Charalá'), (68169,'Charta'), (68176,'Chima'), (68179,'Chipatá'), (68190,'Cimitarra'), (68207,'Concepción'), (68209,'Confines'), (68211,'Contratación'), (68217,'Coromoro'), (68229,'Curití'), (68235,'El Carmen De Chucurí'), (68245,'El Guacamayo'), (68250,'El Peñón'), (68255,'El Playón'), (68264,'Encino'), (68266,'Enciso'), (68271,'Florián'), (68276,'Floridablanca'), (68296,'Galan'), (68298,'Gambita'), (68307,'Girón'), (68318,'Guaca'), (68320,'Guadalupe'), (68322,'Guapotá'), (68324,'Guavatá'), (68327,'Güepsa'), (68344,'Hato'), (68368,'Jesús María'), (68370,'Jordán'), (68377,'La Belleza'), (68385,'Landázuri'), (68397,'La Paz'), (68406,'Lebríja'), (68418,'Los Santos'), (68425,'Macaravita'), (68432,'Málaga'), (68444,'Matanza'), (68464,'Mogotes'), (68468,'Molagavita'), (68498,'Ocamonte'), (68500,'Oiba'), (68502,'Onzaga'), (68522,'Palmar'), (68524,'Palmas Del Socorro'), (68533,'Páramo'), (68547,'Piedecuesta'), (68549,'Pinchote'), (68572,'Puente Nacional'), (68573,'Puerto Parra'), (68575,'Puerto Wilches'), (68615,'Rionegro'), (68655,'Sabana De Torres'), (68669,'San Andrés'), (68673,'San Benito'), (68679,'San Gil'), (68682,'San Joaquín'), (68684,'San José De Miranda'), (68686,'San Miguel'), (68689,'San Vicente De Chucurí'), (68705,'Santa Bárbara'), (68720,'Santa Helena Del Opón'), (68745,'Simacota'), (68755,'Socorro'), (68770,'Suaita'), (68773,'Sucre'), (68780,'Suratá'), (68820,'Tona'), (68855,'Valle De San José'), (68861,'Vélez'), (68867,'Vetas'), (68872,'Villanueva'), (68895,'Zapatoca'), (70001,'Sincelejo'), (70110,'Buenavista'), (70124,'Caimito'), (70204,'Coloso'), (70215,'Corozal'), (70221,'Coveñas'), (70230,'Chalán'), (70233,'El Roble'), (70235,'Galeras'), (70265,'Guaranda'), (70400,'La Unión'), (70418,'Los Palmitos'), (70429,'Majagual'), (70473,'Morroa'), (70508,'Ovejas'), (70523,'Palmito'), (70670,'Sampués'), (70678,'San Benito Abad'), (70702,'San Juan De Betulia'), (70708,'San Marcos'), (70713,'San Onofre'), (70717,'San Pedro'), (70742,'San Luis De Sincé'), (70771,'Sucre'), (70820,'Santiago De Tolú'), (70823,'Tolú Viejo'), (73001,'Ibague'), (73024,'Alpujarra'), (73026,'Alvarado'), (73030,'Ambalema'), (73043,'Anzoátegui'), (73055,'Armero'), (73067,'Ataco'), (73124,'Cajamarca'), (73148,'Carmen De Apicalá'), (73152,'Casabianca'), (73168,'Chaparral'), (73200,'Coello'), (73217,'Coyaima'), (73226,'Cunday'), (73236,'Dolores'), (73268,'Espinal'), (73270,'Falan'), (73275,'Flandes'), (73283,'Fresno'), (73319,'Guamo'), (73347,'Herveo'), (73349,'Honda'), (73352,'Icononzo'), (73408,'Lérida'), (73411,'Líbano'), (73443,'Mariquita'), (73449,'Melgar'), (73461,'Murillo'), (73483,'Natagaima'), (73504,'Ortega'), (73520,'Palocabildo'), (73547,'Piedras'), (73555,'Planadas'), (73563,'Prado'), (73585,'Purificación'), (73616,'Rioblanco'), (73622,'Roncesvalles'), (73624,'Rovira'), (73671,'Saldaña'), (73675,'San Antonio'), (73678,'San Luis'), (73686,'Santa Isabel'), (73770,'Suárez'), (73854,'Valle De San Juan'), (73861,'Venadillo'), (73870,'Villahermosa'), (73873,'Villarrica'), (76001,'Cali'), (76020,'Alcalá'), (76036,'Andalucía'), (76041,'Ansermanuevo'), (76054,'Argelia'), (76100,'Bolívar'), (76109,'Buenaventura'), (76111,'Guadalajara De Buga'), (76113,'Bugalagrande'), (76122,'Caicedonia'), (76126,'Calima'), (76130,'Candelaria'), (76147,'Cartago'), (76233,'Dagua'), (76243,'El Águila'), (76246,'El Cairo'), (76248,'El Cerrito'), (76250,'El Dovio'), (76275,'Florida'), (76306,'Ginebra'), (76318,'Guacarí'), (76364,'Jamundí'), (76377,'La Cumbre'), (76400,'La Unión'), (76403,'La Victoria'), (76497,'Obando'), (76520,'Palmira'), (76563,'Pradera'), (76606,'Restrepo'), (76616,'Riofrío'), (76622,'Roldanillo'), (76670,'San Pedro'), (76736,'Sevilla'), (76823,'Toro'), (76828,'Trujillo'), (76834,'Tuluá'), (76845,'Ulloa'), (76863,'Versalles'), (76869,'Vijes'), (76890,'Yotoco'), (76892,'Yumbo'), (76895,'Zarzal'), (81001,'Arauca'), (81065,'Arauquita'), (81220,'Cravo Norte'), (81300,'Fortul'), (81591,'Puerto Rondón'), (81736,'Saravena'), (81794,'Tame'), (85001,'Yopal'), (85010,'Aguazul'), (85015,'Chameza'), (85125,'Hato Corozal'), (85136,'La Salina'), (85139,'Maní'), (85162,'Monterrey'), (85225,'Nunchía'), (85230,'Orocué'), (85250,'Paz De Ariporo'), (85263,'Pore'), (85279,'Recetor'), (85300,'Sabanalarga'), (85315,'Sácama'), (85325,'San Luis De Palenque'), (85400,'Támara'), (85410,'Tauramena'), (85430,'Trinidad'), (85440,'Villanueva'), (86001,'Mocoa'), (86219,'Colón'), (86320,'Orito'), (86568,'Puerto Asís'), (86569,'Puerto Caicedo'), (86571,'Puerto Guzmán'), (86573,'Leguízamo'), (86749,'Sibundoy'), (86755,'San Francisco'), (86757,'San Miguel'), (86760,'Santiago'), (86865,'Valle Del Guamuez'), (86885,'Villagarzón'), (88001,'San Andrés'), (88564,'Providencia'), (91001,'Leticia'), (91263,'El Encanto'), (91405,'La Chorrera'), (91407,'La Pedrera'), (91430,'La Victoria'), (91460,'Miriti - Paraná'), (91530,'Puerto Alegría'), (91536,'Puerto Arica'), (91540,'Puerto Nariño'), (91669,'Puerto Santander'), (91798,'Tarapacá'), (94001,'Inírida'), (94343,'Barranco Minas'), (94663,'Mapiripana'), (94883,'San Felipe'), (94884,'Puerto Colombia'), (94885,'La Guadalupe'), (94886,'Cacahual'), (94887,'Pana Pana'), (94888,'Morichal'), (95001,'San José Del Guaviare'), (95015,'Calamar'), (95025,'El Retorno'), (95200,'Miraflores'), (97001,'Mitú'), (97161,'Caruru'), (97511,'Pacoa'), (97666,'Taraira'), (97777,'Papunaua'), (97889,'Yavaraté'), (99001,'Puerto Carreño'), (99524,'La Primavera'), (99624,'Santa Rosalía'), (99773,'Cumaribo') ], validate_choice=True) celularCliente = IntegerField('Numero Telefono Movil', validators=[ Required(message='El campo es obligatorio'), Length(max=10, min=10, message='El campo debe tener 10 caracteres') ]) correoElectronicoCliente = StringField('Correo Electronico Principal', validators=[ Required(message='El campo es obligatorio'), Email() ]) contraseñaCliente = PasswordField('Contraseña') enviar = SubmitField("Enviar") class ingresoCliente(FlaskForm): correoElectronicoCliente = StringField('Correo Electronico Principal', validators=[ Required(message='El campo es obligatorio'), Email() ]) contraseñaCliente = PasswordField('Contraseña') enviar = SubmitField("Enviar") class registrarEmpleado(FlaskForm): numeroIdEmpleado = IntegerField('Numero Identificacion', validators=[ Required(message='El campo es obligatorio'), Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres') ]) tipoId = SelectField('Tipo Idenficacion', choices=[ ('CC','Cedula de Ciudadania'), ('CE','Cedula de Extrangeria'), ('PA','Pasaporte'), ('RC','Registro Civil'), ('TI','Tarjeta de Identidad')], validators=[ Required(message='El campo es obligatorio'), ]) fechaExpIdEmpleado = DateField('Fecha Expedicion Documento Identidad', format='%Y,%M,%D') lugarExpIdEmpleado = SelectField('Ciudad Expedicion Documento Identidad', choices=[ (5001,'Medellín'), (5002,'Abejorral'), (5004,'Abriaquí'), (5021,'Alejandría'), (5030,'Amagá'), (5031,'Amalfi'), (5034,'Andes'), (5036,'Angelópolis'), (5038,'Angostura'), (5040,'Anorí'), (5042,'Santafé De Antioquia'), (5044,'Anza'), (5045,'Apartadó'), (5051,'Arboletes'), (5055,'Argelia'), (5059,'Armenia'), (5079,'Barbosa'), (5086,'Belmira'), (5088,'Bello'), (5091,'Betania'), (5093,'Betulia'), (5101,'Ciudad Bolívar'), (5107,'Briceño'), (5113,'Buriticá'), (5120,'Cáceres'), (5125,'Caicedo'), (5129,'Caldas'), (5134,'Campamento'), (5138,'Cañasgordas'), (5142,'Caracolí'), (5145,'Caramanta'), (5147,'Carepa'), (5148,'El Carmen De Viboral'), (5150,'Carolina'), (5154,'Caucasia'), (5172,'Chigorodó'), (5190,'Cisneros'), (5197,'Cocorná'), (5206,'Concepción'), (5209,'Concordia'), (5212,'Copacabana'), (5234,'Dabeiba'), (5237,'Don Matías'), (5240,'Ebéjico'), (5250,'El Bagre'), (5264,'Entrerrios'), (5266,'Envigado'), (5282,'Fredonia'), (5284,'Frontino'), (5306,'Giraldo'), (5308,'Girardota'), (5310,'Gómez Plata'), (5313,'Granada'), (5315,'Guadalupe'), (5318,'Guarne'), (5321,'Guatape'), (5347,'Heliconia'), (5353,'Hispania'), (5360,'Itagui'), (5361,'Ituango'), (5364,'Jardín'), (5368,'Jericó'), (5376,'La Ceja'), (5380,'La Estrella'), (5390,'La Pintada'), (5400,'La Unión'), (5411,'Liborina'), (5425,'Maceo'), (5440,'Marinilla'), (5467,'Montebello'), (5475,'Murindó'), (5480,'Mutatá'), (5483,'Nariño'), (5490,'Necoclí'), (5495,'Nechí'), (5501,'Olaya'), (5541,'Peñol'), (5543,'Peque'), (5576,'Pueblorrico'), (5579,'Puerto Berrío'), (5585,'Puerto Nare'), (5591,'Puerto Triunfo'), (5604,'Remedios'), (5607,'Retiro'), (5615,'Rionegro'), (5628,'Sabanalarga'), (5631,'Sabaneta'), (5642,'Salgar'), (5647,'San Andrés De Cuerquía'), (5649,'San Carlos'), (5652,'San Francisco'), (5656,'San Jerónimo'), (5658,'San José De La Montaña'), (5659,'San Juan De Urabá'), (5660,'San Luis'), (5664,'San Pedro'), (5665,'San Pedro De Uraba'), (5667,'San Rafael'), (5670,'San Roque'), (5674,'San Vicente'), (5679,'Santa Bárbara'), (5686,'Santa Rosa De Osos'), (5690,'Santo Domingo'), (5697,'El Santuario'), (5736,'Segovia'), (5756,'Sonson'), (5761,'Sopetrán'), (5789,'Támesis'), (5790,'Tarazá'), (5792,'Tarso'), (5809,'Titiribí'), (5819,'Toledo'), (5837,'Turbo'), (5842,'Uramita'), (5847,'Urrao'), (5854,'Valdivia'), (5856,'Valparaíso'), (5858,'Vegachí'), (5861,'Venecia'), (5873,'Vigía Del Fuerte'), (5885,'Yalí'), (5887,'Yarumal'), (5890,'Yolombó'), (5893,'Yondó'), (5895,'Zaragoza'), (8001,'Barranquilla'), (8078,'Baranoa'), (8137,'Campo De La Cruz'), (8141,'Candelaria'), (8296,'Galapa'), (8372,'Juan De Acosta'), (8421,'Luruaco'), (8433,'Malambo'), (8436,'Manatí'), (8520,'Palmar De Varela'), (8549,'Piojó'), (8558,'Polonuevo'), (8560,'Ponedera'), (8573,'Puerto Colombia'), (8606,'Repelón'), (8634,'Sabanagrande'), (8638,'Sabanalarga'), (8675,'Santa Lucía'), (8685,'Santo Tomás'), (8758,'Soledad'), (8770,'Suan'), (8832,'Tubará'), (8849,'Usiacurí'), (11001,'Bogota DC'), (13001,'Cartagena'), (13006,'Choachí'), (13030,'Altos Del Rosario'), (13042,'Arenal'), (13052,'Arjona'), (13062,'Arroyohondo'), (13074,'Barranco De Loba'), (13140,'Calamar'), (13160,'Cantagallo'), (13188,'Cicuco'), (13212,'Córdoba'), (13222,'Clemencia'), (13244,'El Carmen De Bolívar'), (13248,'El Guamo'), (13268,'El Peñón'), (13300,'Hatillo De Loba'), (13430,'Magangué'), (13433,'Mahates'), (13440,'Margarita'), (13442,'María La Baja'), (13458,'Montecristo'), (13468,'Mompós'), (13473,'Morales'), (13549,'Pinillos'), (13580,'Regidor'), (13600,'Río Viejo'), (13620,'San Cristóbal'), (13647,'San Estanislao'), (13650,'San Fernando'), (13654,'San Jacinto'), (13655,'San Jacinto Del Cauca'), (13657,'San Juan Nepomuceno'), (13667,'San Martín De Loba'), (13670,'San Pablo'), (13673,'Santa Catalina'), (13683,'Santa Rosa'), (13688,'Santa Rosa Del Sur'), (13744,'Simití'), (13760,'Soplaviento'), (13780,'Talaigua Nuevo'), (13810,'Tiquisio'), (13836,'Turbaco'), (13838,'Turbaná'), (13873,'Villanueva'), (13894,'Zambrano'), (15001,'Tunja'), (15022,'Almeida'), (15047,'Aquitania'), (15051,'Arcabuco'), (15087,'Belén'), (15090,'Berbeo'), (15092,'Betéitiva'), (15097,'Boavita'), (15104,'Boyacá'), (15106,'Briceño'), (15109,'Buenavista'), (15114,'Busbanzá'), (15131,'Caldas'), (15135,'Campohermoso'), (15162,'Cerinza'), (15172,'Chinavita'), (15176,'Chiquinquirá'), (15180,'Chiscas'), (15183,'Chita'), (15185,'Chitaraque'), (15187,'Chivatá'), (15189,'Ciénega'), (15204,'Cómbita'), (15212,'Coper'), (15215,'Corrales'), (15218,'Covarachía'), (15223,'Cubará'), (15224,'Cucaita'), (15226,'Cuítiva'), (15232,'Chíquiza'), (15236,'Chivor'), (15238,'Duitama'), (15244,'El Cocuy'), (15248,'El6Aspino'), (15272,'Firavitoba'), (15276,'Floresta'), (15293,'Gachantivá'), (15296,'Gameza'), (15299,'Garagoa'), (15317,'Guacamayas'), (15322,'Guateque'), (15325,'Guayatá'), (15332,'Guican'), (15362,'Iza'), (15367,'Jenesano'), (15368,'Jericó'), (15377,'Labranzagrande'), (15380,'La Capilla'), (15401,'La Victoria'), (15403,'La Uvita'), (15407,'Villa De Leyva'), (15425,'Macanal'), (15442,'Maripí'), (15455,'Miraflores'), (15464,'Mongua'), (15466,'Monguí'), (15469,'Moniquirá'), (15476,'Motavita'), (15480,'Muzo'), (15491,'Nobsa'), (15494,'Nuevo Colón'), (15500,'Oicatá'), (15507,'Otanche'), (15511,'Pachavita'), (15514,'Páez'), (15516,'Paipa'), (15518,'Pajarito'), (15522,'Panqueba'), (15531,'Pauna'), (15533,'Paya'), (15537,'Paz De Río'), (15542,'Pesca'), (15550,'Pisba'), (15572,'Puerto Boyacá'), (15580,'Quípama'), (15599,'Ramiriquí'), (15600,'Ráquira'), (15621,'Rondón'), (15632,'Saboyá'), (15638,'Sáchica'), (15646,'Samacá'), (15660,'San Eduardo'), (15664,'San José De Pare'), (15667,'San Luis De Gaceno'), (15673,'San Mateo'), (15676,'San Miguel De Sema'), (15681,'San Pablo De Borbur'), (15686,'Santana'), (15690,'Santa María'), (15693,'Santa Rosa De Viterbo'), (15696,'Santa Sofía'), (15720,'Sativanorte'), (15723,'Sativasur'), (15740,'Siachoque'), (15753,'Soatá'), (15755,'Socotá'), (15757,'Socha'), (15759,'Sogamoso'), (15761,'Somondoco'), (15762,'Sora'), (15763,'Sotaquirá'), (15764,'Soracá'), (15774,'Susacón'), (15776,'Sutamarchán'), (15778,'Sutatenza'), (15790,'Tasco'), (15798,'Tenza'), (15804,'Tibaná'), (15806,'Tibasosa'), (15808,'Tinjacá'), (15810,'Tipacoque'), (15814,'Toca'), (15816,'Togüí'), (15820,'Tópaga'), (15822,'Tota'), (15832,'Tununguá'), (15835,'Turmequé'), (15837,'Tuta'), (15839,'Tutazá'), (15842,'Umbita'), (15861,'Ventaquemada'), (15879,'Viracachá'), (15897,'Zetaquira'), (17001,'Manizales'), (17013,'Aguadas'), (17042,'Anserma'), (17050,'Aranzazu'), (17088,'Belalcázar'), (17174,'Chinchiná'), (17272,'Filadelfia'), (17380,'La Dorada'), (17388,'La Merced'), (17433,'Manzanares'), (17442,'Marmato'), (17444,'Marquetalia'), (17446,'Marulanda'), (17486,'Neira'), (17495,'Norcasia'), (17513,'Pácora'), (17524,'Palestina'), (17541,'Pensilvania'), (17614,'Riosucio'), (17616,'Risaralda'), (17653,'Salamina'), (17662,'Samaná'), (17665,'San José'), (17777,'Supía'), (17867,'Victoria'), (17873,'Villamaría'), (17877,'Viterbo'), (18001,'Florencia'), (18029,'Albania'), (18094,'Belén De Los Andaquies'), (18150,'Cartagena Del Chairá'), (18205,'Curillo'), (18247,'El Doncello'), (18256,'El Paujil'), (18410,'La Montañita'), (18460,'Milán'), (18479,'Morelia'), (18592,'Puerto Rico'), (18610,'San José Del Fragua'), (18753,'San Vicente Del Caguán'), (18756,'Solano'), (18785,'Solita'), (18860,'Valparaíso'), (19001,'Popayán'), (19022,'Almaguer'), (19050,'Argelia'), (19075,'Balboa'), (19100,'Bolívar'), (19110,'Buenos Aires'), (19130,'Cajibío'), (19137,'Caldono'), (19142,'Caloto'), (19212,'Corinto'), (19256,'El Tambo'), (19290,'Florencia'), (19300,'Guachené'), (19318,'Guapi'), (19355,'Inzá'), (19364,'Jambaló'), (19392,'La Sierra'), (19397,'La Vega'), (19418,'López'), (19450,'Mercaderes'), (19455,'Miranda'), (19473,'Morales'), (19513,'Padilla'), (19517,'Paez'), (19532,'Patía'), (19533,'Piamonte'), (19548,'Piendamó'), (19573,'Puerto Tejada'), (19585,'Puracé'), (19622,'Rosas'), (19693,'San Sebastián'), (19698,'Santander De Quilichao'), (19701,'Santa Rosa'), (19743,'Silvia'), (19760,'Sotara'), (19780,'Suárez'), (19785,'Sucre'), (19807,'Timbío'), (19809,'Timbiquí'), (19821,'Toribio'), (19824,'Totoró'), (19845,'Villa Rica'), (20001,'Valledupar'), (20011,'Aguachica'), (20013,'Agustín Codazzi'), (20032,'Astrea'), (20045,'Becerril'), (20060,'Bosconia'), (20175,'Chimichagua'), (20178,'Chiriguaná'), (20228,'Curumaní'), (20238,'El Copey'), (20250,'El Paso'), (20295,'Gamarra'), (20310,'González'), (20383,'La Gloria'), (20400,'La Jagua De Ibirico'), (20443,'Manaure'), (20517,'Pailitas'), (20550,'Pelaya'), (20570,'Pueblo Bello'), (20614,'Río De Oro'), (20621,'La Paz'), (20710,'San Alberto'), (20750,'San Diego'), (20770,'San Martín'), (20787,'Tamalameque'), (23001,'Montería'), (23068,'Ayapel'), (23079,'Buenavista'), (23090,'Canalete'), (23162,'Cereté'), (23168,'Chimá'), (23182,'Chinú'), (23189,'Ciénaga De Oro'), (23300,'Cotorra'), (23350,'La Apartada'), (23417,'Lorica'), (23419,'Los Córdobas'), (23464,'Momil'), (23466,'Montelíbano'), (23500,'Moñitos'), (23555,'Planeta Rica'), (23570,'Pueblo Nuevo'), (23574,'Puerto Escondido'), (23580,'Puerto Libertador'), (23586,'Purísima'), (23660,'Sahagún'), (23670,'San Andrés Sotavento'), (23672,'San Antero'), (23675,'San Bernardo Del Viento'), (23678,'San Carlos'), (23686,'San Pelayo'), (23807,'Tierralta'), (23855,'Valencia'), (25001,'Agua De Dios'), (25019,'Albán'), (25035,'Anapoima'), (25040,'Anolaima'), (25053,'Arbeláez'), (25086,'Beltrán'), (25095,'Bituima'), (25099,'Bojacá'), (25120,'Cabrera'), (25123,'Cachipay'), (25126,'Cajicá'), (25148,'Caparrapí'), (25151,'Caqueza'), (25154,'Carmen De Carupa'), (25168,'Chaguaní'), (25175,'Chía'), (25178,'Chipaque'), (25181,'Choachí'), (25183,'Chocontá'), (25200,'Cogua'), (25214,'Cota'), (25224,'Cucunuba'), (25245,'El Colegio'), (25258,'El Peñón'), (25260,'El Rosal'), (25269,'Facatativá'), (25279,'Fomeque'), (25281,'Fosca'), (25286,'Funza'), (25288,'Fúquene'), (25290,'Fusagasugá'), (25293,'Gachala'), (25295,'Gachancipá'), (25297,'Gachetá'), (25299,'Gama'), (25307,'Girardot'), (25312,'Granada'), (25317,'Guachetá'), (25320,'Guaduas'), (25322,'Guasca'), (25324,'Guataquí'), (25326,'Guatavita'), (25328,'Guayabal De Siquima'), (25335,'Guayabetal'), (25339,'Gutiérrez'), (25368,'Jerusalén'), (25372,'Junín'), (25377,'La Calera'), (25386,'La Mesa'), (25394,'La Palma'), (25398,'La Peña'), (25402,'La Vega'), (25407,'Lenguazaque'), (25426,'Macheta'), (25430,'Madrid'), (25436,'Manta'), (25438,'Medina'), (25473,'Mosquera'), (25483,'Nariño'), (25486,'Nemocón'), (25488,'Nilo'), (25489,'Nimaima'), (25491,'Nocaima'), (25506,'Venecia'), (25513,'Pacho'), (25518,'Paime'), (25524,'Pandi'), (25530,'Paratebueno'), (25535,'Pasca'), (25572,'Puerto Salgar'), (25580,'Pulí'), (25592,'Quebradanegra'), (25594,'Quetame'), (25596,'Quipile'), (25599,'Apulo'), (25612,'Ricaurte'), (25645,'San Antonio Del Tequendama'), (25649,'San Bernardo'), (25653,'San Cayetano'), (25658,'San Francisco'), (25662,'San Juan De Río Seco'), (25718,'Sasaima'), (25736,'Sesquilé'), (25740,'Sibaté'), (25743,'Silvania'), (25745,'Simijaca'), (25754,'Soacha'), (25758,'Sopó'), (25769,'Subachoque'), (25772,'Suesca'), (25777,'Supatá'), (25779,'Susa'), (25781,'Sutatausa'), (25785,'Tabio'), (25793,'Tausa'), (25797,'Tena'), (25799,'Tenjo'), (25805,'Tibacuy'), (25807,'Tibirita'), (25815,'Tocaima'), (25817,'Tocancipá'), (25823,'Topaipi'), (25839,'Ubalá'), (25841,'Ubaque'), (25843,'Villa De San Diego De Ubate'), (25845,'Une'), (25851,'Útica'), (25862,'Vergara'), (25867,'Vianí'), (25871,'Villagómez'), (25873,'Villapinzón'), (25875,'Villeta'), (25878,'Viotá'), (25885,'Yacopí'), (25898,'Zipacón'), (25899,'Zipaquirá'), (27001,'Quibdó'), (27006,'Acandí'), (27025,'Alto Baudo'), (27050,'Atrato'), (27073,'Bagadó'), (27075,'Bahía Solano'), (27077,'Bajo Baudó'), (27086,'Belén De Bajirá'), (27099,'Bojaya'), (27135,'El Cantón Del San Pablo'), (27150,'Carmen Del Darien'), (27160,'Cértegui'), (27205,'Condoto'), (27245,'El Carmen De Atrato'), (27250,'El Litoral Del San Juan'), (27361,'Istmina'), (27372,'Juradó'), (27413,'Lloró'), (27425,'Medio Atrato'), (27430,'Medio Baudó'), (27450,'Medio San Juan'), (27491,'Nóvita'), (27495,'Nuquí'), (27580,'Río Iro'), (27600,'Río Quito'), (27615,'Riosucio'), (27660,'San José Del Palmar'), (27745,'Sipí'), (27787,'Tadó'), (27800,'Unguía'), (27810,'Unión Panamericana'), (41001,'Neiva'), (41006,'Acevedo'), (41013,'Agrado'), (41016,'Aipe'), (41020,'Algeciras'), (41026,'Altamira'), (41078,'Baraya'), (41132,'Campoalegre'), (41206,'Colombia'), (41244,'Elías'), (41298,'Garzón'), (41306,'Gigante'), (41319,'Guadalupe'), (41349,'Hobo'), (41357,'Iquira'), (41359,'Isnos'), (41378,'La Argentina'), (41396,'La Plata'), (41483,'Nátaga'), (41503,'Oporapa'), (41518,'Paicol'), (41524,'Palermo'), (41530,'Palestina'), (41548,'Pital'), (41551,'Pitalito'), (41615,'Rivera'), (41660,'Saladoblanco'), (41668,'San Agustín'), (41676,'Santa María'), (41770,'Suaza'), (41791,'Tarqui'), (41797,'Tesalia'), (41799,'Tello'), (41801,'Teruel'), (41807,'Timana'), (41872,'Villavieja'), (41885,'Yaguará'), (44001,'Riohacha'), (44035,'Albania'), (44078,'Barrancas'), (44090,'Dibulla'), (44098,'Distracción'), (44110,'El Molino'), (44279,'Fonseca'), (44378,'Hatonuevo'), (44420,'La Jagua Del Pilar'), (44430,'Maicao'), (44560,'Manaure'), (44650,'San Juan Del Cesar'), (44847,'Uribia'), (44855,'Urumita'), (44874,'Villanueva'), (47001,'Santa Marta'), (47030,'Algarrobo'), (47053,'Aracataca'), (47058,'Ariguaní'), (47161,'Cerro San Antonio'), (47170,'Chibolo'), (47189,'Ciénaga'), (47205,'Concordia'), (47245,'El Banco'), (47258,'El Piñon'), (47268,'El Retén'), (47288,'Fundación'), (47318,'Guamal'), (47460,'Nueva Granada'), (47541,'Pedraza'), (47545,'Pijiño Del Carmen'), (47551,'Pivijay'), (47555,'Plato'), (47570,'Puebloviejo'), (47605,'Remolino'), (47660,'Sabanas De San Angel'), (47675,'Salamina'), (47692,'San Sebastián De Buenavista'), (47703,'San Zenón'), (47707,'Santa Ana'), (47720,'Santa Bárbara De Pinto'), (47745,'Sitionuevo'), (47798,'Tenerife'), (47960,'Zapayán'), (47980,'Zona Bananera'), (50001,'Villavicencio'), (50006,'Acacías'), (50110,'Barranca De Upía'), (50124,'Cabuyaro'), (50150,'Castilla La Nueva'), (50223,'Cubarral'), (50226,'Cumaral'), (50245,'El Calvario'), (50251,'El Castillo'), (50270,'El Dorado'), (50287,'Fuente De Oro'), (50313,'Granada'), (50318,'Guamal'), (50325,'Mapiripán'), (50330,'Mesetas'), (50350,'La Macarena'), (50370,'Uribe'), (50400,'Lejanías'), (50450,'Puerto Concordia'), (50568,'Puerto Gaitán'), (50573,'Puerto López'), (50577,'Puerto Lleras'), (50590,'Puerto Rico'), (50606,'Restrepo'), (50680,'San Carlos De Guaroa'), (50683,'San Juan De Arama'), (50686,'San Juanito'), (50689,'San Martín'), (50711,'Vistahermosa'), (52001,'Pasto'), (52019,'Albán'), (52022,'Aldana'), (52036,'Ancuya'), (52051,'Arboleda'), (52079,'Barbacoas'), (52083,'Belén'), (52110,'Buesaco'), (52203,'Colón'), (52207,'Consaca'), (52210,'Contadero'), (52215,'Córdoba'), (52224,'Cuaspud'), (52227,'Cumbal'), (52233,'Cumbitara'), (52240,'Chachagüí'), (52250,'El Charco'), (52254,'El Peñol'), (52256,'El Rosario'), (52258,'El Tablón De Gómez'), (52260,'El Tambo'), (52287,'Funes'), (52317,'Guachucal'), (52320,'Guaitarilla'), (52323,'Gualmatán'), (52352,'Iles'), (52354,'Imués'), (52356,'Ipiales'), (52378,'La Cruz'), (52381,'La Florida'), (52385,'La Llanada'), (52390,'La Tola'), (52399,'La Unión'), (52405,'Leiva'), (52411,'Linares'), (52418,'Los Andes'), (52427,'Magüi'), (52435,'Mallama'), (52473,'Mosquera'), (52480,'Nariño'), (52490,'Olaya Herrera'), (52506,'Ospina'), (52520,'Francisco Pizarro'), (52540,'Policarpa'), (52560,'Potosí'), (52565,'Providencia'), (52573,'Puerres'), (52585,'Pupiales'), (52612,'Ricaurte'), (52621,'Roberto Payán'), (52678,'Samaniego'), (52683,'Sandoná'), (52685,'San Bernardo'), (52687,'San Lorenzo'), (52693,'San Pablo'), (52694,'San Pedro De Cartago'), (52696,'Santa Bárbara'), (52699,'Santacruz'), (52720,'Sapuyes'), (52786,'Taminango'), (52788,'Tangua'), (52835,'San Andres De Tumaco'), (52838,'Túquerres'), (52885,'Yacuanquer'), (54001,'Cúcuta'), (54003,'Abrego'), (54051,'Arboledas'), (54099,'Bochalema'), (54109,'Bucarasica'), (54125,'Cácota'), (54128,'Cachirá'), (54172,'Chinácota'), (54174,'Chitagá'), (54206,'Convención'), (54223,'Cucutilla'), (54239,'Durania'), (54245,'El Carmen'), (54250,'El Tarra'), (54261,'El Zulia'), (54313,'Gramalote'), (54344,'Hacarí'), (54347,'Herrán'), (54377,'Labateca'), (54385,'La Esperanza'), (54398,'La Playa'), (54405,'Los Patios'), (54418,'Lourdes'), (54480,'Mutiscua'), (54498,'Ocaña'), (54518,'Pamplona'), (54520,'Pamplonita'), (54553,'Puerto Santander'), (54599,'Ragonvalia'), (54660,'Salazar'), (54670,'San Calixto'), (54673,'San Cayetano'), (54680,'Santiago'), (54720,'Sardinata'), (54743,'Silos'), (54800,'Teorama'), (54810,'Tibú'), (54820,'Toledo'), (54871,'Villa Caro'), (54874,'Villa Del Rosario'), (63001,'Armenia'), (63111,'Buenavista'), (63130,'Calarca'), (63190,'Circasia'), (63212,'Córdoba'), (63272,'Filandia'), (63302,'Génova'), (63401,'La Tebaida'), (63470,'Montenegro'), (63548,'Pijao'), (63594,'Quimbaya'), (63690,'Salento'), (66001,'Pereira'), (66045,'Apía'), (66075,'Balboa'), (66088,'Belén De Umbría'), (66170,'Dosquebradas'), (66318,'Guática'), (66383,'La Celia'), (66400,'La Virginia'), (66440,'Marsella'), (66456,'Mistrató'), (66572,'Pueblo Rico'), (66594,'Quinchía'), (66682,'Santa Rosa De Cabal'), (66687,'Santuario'), (68001,'Bucaramanga'), (68013,'Aguada'), (68020,'Albania'), (68051,'Aratoca'), (68077,'Barbosa'), (68079,'Barichara'), (68081,'Barrancabermeja'), (68092,'Betulia'), (68101,'Bolívar'), (68121,'Cabrera'), (68132,'California'), (68147,'Capitanejo'), (68152,'Carcasí'), (68160,'Cepitá'), (68162,'Cerrito'), (68167,'Charalá'), (68169,'Charta'), (68176,'Chima'), (68179,'Chipatá'), (68190,'Cimitarra'), (68207,'Concepción'), (68209,'Confines'), (68211,'Contratación'), (68217,'Coromoro'), (68229,'Curití'), (68235,'El Carmen De Chucurí'), (68245,'El Guacamayo'), (68250,'El Peñón'), (68255,'El Playón'), (68264,'Encino'), (68266,'Enciso'), (68271,'Florián'), (68276,'Floridablanca'), (68296,'Galan'), (68298,'Gambita'), (68307,'Girón'), (68318,'Guaca'), (68320,'Guadalupe'), (68322,'Guapotá'), (68324,'Guavatá'), (68327,'Güepsa'), (68344,'Hato'), (68368,'Jesús María'), (68370,'Jordán'), (68377,'La Belleza'), (68385,'Landázuri'), (68397,'La Paz'), (68406,'Lebríja'), (68418,'Los Santos'), (68425,'Macaravita'), (68432,'Málaga'), (68444,'Matanza'), (68464,'Mogotes'), (68468,'Molagavita'), (68498,'Ocamonte'), (68500,'Oiba'), (68502,'Onzaga'), (68522,'Palmar'), (68524,'Palmas Del Socorro'), (68533,'Páramo'), (68547,'Piedecuesta'), (68549,'Pinchote'), (68572,'Puente Nacional'), (68573,'Puerto Parra'), (68575,'Puerto Wilches'), (68615,'Rionegro'), (68655,'Sabana De Torres'), (68669,'San Andrés'), (68673,'San Benito'), (68679,'San Gil'), (68682,'San Joaquín'), (68684,'San José De Miranda'), (68686,'San Miguel'), (68689,'San Vicente De Chucurí'), (68705,'Santa Bárbara'), (68720,'Santa Helena Del Opón'), (68745,'Simacota'), (68755,'Socorro'), (68770,'Suaita'), (68773,'Sucre'), (68780,'Suratá'), (68820,'Tona'), (68855,'Valle De San José'), (68861,'Vélez'), (68867,'Vetas'), (68872,'Villanueva'), (68895,'Zapatoca'), (70001,'Sincelejo'), (70110,'Buenavista'), (70124,'Caimito'), (70204,'Coloso'), (70215,'Corozal'), (70221,'Coveñas'), (70230,'Chalán'), (70233,'El Roble'), (70235,'Galeras'), (70265,'Guaranda'), (70400,'La Unión'), (70418,'Los Palmitos'), (70429,'Majagual'), (70473,'Morroa'), (70508,'Ovejas'), (70523,'Palmito'), (70670,'Sampués'), (70678,'San Benito Abad'), (70702,'San Juan De Betulia'), (70708,'San Marcos'), (70713,'San Onofre'), (70717,'San Pedro'), (70742,'San Luis De Sincé'), (70771,'Sucre'), (70820,'Santiago De Tolú'), (70823,'Tolú Viejo'), (73001,'Ibague'), (73024,'Alpujarra'), (73026,'Alvarado'), (73030,'Ambalema'), (73043,'Anzoátegui'), (73055,'Armero'), (73067,'Ataco'), (73124,'Cajamarca'), (73148,'Carmen De Apicalá'), (73152,'Casabianca'), (73168,'Chaparral'), (73200,'Coello'), (73217,'Coyaima'), (73226,'Cunday'), (73236,'Dolores'), (73268,'Espinal'), (73270,'Falan'), (73275,'Flandes'), (73283,'Fresno'), (73319,'Guamo'), (73347,'Herveo'), (73349,'Honda'), (73352,'Icononzo'), (73408,'Lérida'), (73411,'Líbano'), (73443,'Mariquita'), (73449,'Melgar'), (73461,'Murillo'), (73483,'Natagaima'), (73504,'Ortega'), (73520,'Palocabildo'), (73547,'Piedras'), (73555,'Planadas'), (73563,'Prado'), (73585,'Purificación'), (73616,'Rioblanco'), (73622,'Roncesvalles'), (73624,'Rovira'), (73671,'Saldaña'), (73675,'San Antonio'), (73678,'San Luis'), (73686,'Santa Isabel'), (73770,'Suárez'), (73854,'Valle De San Juan'), (73861,'Venadillo'), (73870,'Villahermosa'), (73873,'Villarrica'), (76001,'Cali'), (76020,'Alcalá'), (76036,'Andalucía'), (76041,'Ansermanuevo'), (76054,'Argelia'), (76100,'Bolívar'), (76109,'Buenaventura'), (76111,'Guadalajara De Buga'), (76113,'Bugalagrande'), (76122,'Caicedonia'), (76126,'Calima'), (76130,'Candelaria'), (76147,'Cartago'), (76233,'Dagua'), (76243,'El Águila'), (76246,'El Cairo'), (76248,'El Cerrito'), (76250,'El Dovio'), (76275,'Florida'), (76306,'Ginebra'), (76318,'Guacarí'), (76364,'Jamundí'), (76377,'La Cumbre'), (76400,'La Unión'), (76403,'La Victoria'), (76497,'Obando'), (76520,'Palmira'), (76563,'Pradera'), (76606,'Restrepo'), (76616,'Riofrío'), (76622,'Roldanillo'), (76670,'San Pedro'), (76736,'Sevilla'), (76823,'Toro'), (76828,'Trujillo'), (76834,'Tuluá'), (76845,'Ulloa'), (76863,'Versalles'), (76869,'Vijes'), (76890,'Yotoco'), (76892,'Yumbo'), (76895,'Zarzal'), (81001,'Arauca'), (81065,'Arauquita'), (81220,'Cravo Norte'), (81300,'Fortul'), (81591,'Puerto Rondón'), (81736,'Saravena'), (81794,'Tame'), (85001,'Yopal'), (85010,'Aguazul'), (85015,'Chameza'), (85125,'Hato Corozal'), (85136,'La Salina'), (85139,'Maní'), (85162,'Monterrey'), (85225,'Nunchía'), (85230,'Orocué'), (85250,'Paz De Ariporo'), (85263,'Pore'), (85279,'Recetor'), (85300,'Sabanalarga'), (85315,'Sácama'), (85325,'San Luis De Palenque'), (85400,'Támara'), (85410,'Tauramena'), (85430,'Trinidad'), (85440,'Villanueva'), (86001,'Mocoa'), (86219,'Colón'), (86320,'Orito'), (86568,'Puerto Asís'), (86569,'Puerto Caicedo'), (86571,'Puerto Guzmán'), (86573,'Leguízamo'), (86749,'Sibundoy'), (86755,'San Francisco'), (86757,'San Miguel'), (86760,'Santiago'), (86865,'Valle Del Guamuez'), (86885,'Villagarzón'), (88001,'San Andrés'), (88564,'Providencia'), (91001,'Leticia'), (91263,'El Encanto'), (91405,'La Chorrera'), (91407,'La Pedrera'), (91430,'La Victoria'), (91460,'Miriti - Paraná'), (91530,'Puerto Alegría'), (91536,'Puerto Arica'), (91540,'Puerto Nariño'), (91669,'Puerto Santander'), (91798,'Tarapacá'), (94001,'Inírida'), (94343,'Barranco Minas'), (94663,'Mapiripana'), (94883,'San Felipe'), (94884,'Puerto Colombia'), (94885,'La Guadalupe'), (94886,'Cacahual'), (94887,'Pana Pana'), (94888,'Morichal'), (95001,'San José Del Guaviare'), (95015,'Calamar'), (95025,'El Retorno'), (95200,'Miraflores'), (97001,'Mitú'), (97161,'Caruru'), (97511,'Pacoa'), (97666,'Taraira'), (97777,'Papunaua'), (97889,'Yavaraté'), (99001,'Puerto Carreño'), (99524,'La Primavera'), (99624,'Santa Rosalía'), (99773,'Cumaribo') ], validators=[ Required() ]) primerNombreEmpleado = StringField('Primer Nombre', validators=[ Required(message='El campo es obligatorio'), Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) segundoNombreEmpleado = StringField('Segundo Nombre', validators=[ Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) primerApellidoEmpleado = StringField('Primer Apellido', validators=[ Required(message='El campo es obligatorio'), Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) segundoApellidoEmpleado = StringField('Segundo Apellido', validators=[ Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) fechaNacimientoEmpleado = DateField('Fecha de Nacimiento', format='%Y,%M,%D', validators=[]) direccionEmpleado = StringField('Direccion Residencia', validators=[ Required(message='El campo es obligatorio'), Length(max=50, min=20, message='El campo debe tener entre 20 y 50 caracteres') ]) barrioEmpleado = StringField('Barrio Residencia', validators=[ Required(message='El campo es obligatorio'), Length(max=20, min=10, message='El campo debe tener entre 10 y 20 caracteres') ]) idPais = SelectField('Pais Residencia', choices=[ ('AD','Andorra'), ('AE','Emiratos Arabes Unid'), ('AF','Afganistan'), ('AG','Antigua Y Barbuda'), ('AI','Anguilla'), ('AL','Albania'), ('AM','Armenia'), ('AN','Antillas Holandesas'), ('AO','Angola'), ('AR','Argentina'), ('AS','Samoa Norteamericana'), ('AT','Austria'), ('AU','Australia'), ('AW','Aruba'), ('AZ','Azerbaijan'), ('BA','Bosnia-Herzegovina'), ('BB','Barbados'), ('BD','Bangladesh'), ('BE','Belgica'), ('BF','Burkina Fasso'), ('BG','Bulgaria'), ('BH','Bahrein'), ('BI','Burundi'), ('BJ','Benin'), ('BM','Bermudas'), ('BN','Brunei Darussalam'), ('BO','Bolivia'), ('BR','Brasil'), ('BS','Bahamas'), ('BT','Butan'), ('BW','Botswana'), ('BY','Belorus'), ('BZ','Belice'), ('CA','Canada'), ('CC','Cocos (Keeling) Islas'), ('CD','Republica Democratica Del Congo'), ('CF','Republica Centroafri'), ('CG','Congo'), ('CH','Suiza'), ('CI','Costa De Marfil'), ('CK','Cook Islas'), ('CL','Chile'), ('CM','Camerun Republica U'), ('CN','China'), ('CO','Colombia'), ('CR','Costa Rica'), ('CU','Cuba'), ('CV','Cabo Verde'), ('CX','Navidad (Christmas)'), ('CY','Chipre'), ('CZ','Republica Checa'), ('DE','Alemania'), ('DJ','Djibouti'), ('DK','Dinamarca'), ('DM','Dominica'), ('DO','Republica Dominicana'), ('DZ','Argelia'), ('EC','Ecuador'), ('EE','Estonia'), ('EG','Egipto'), ('EH','Sahara Occidental'), ('ER','Eritrea'), ('ES','España'), ('ET','Etiopia'), ('EU','Comunidad Europea'), ('FI','Finlandia'), ('FJ','Fiji'), ('FM','Micronesia Estados F'), ('FO','Feroe Islas'), ('FR','Francia'), ('GA','Gabon'), ('GB','Reino Unido'), ('GD','Granada'), ('GE','Georgia'), ('GF','Guayana Francesa'), ('GH','Ghana'), ('GI','Gibraltar'), ('GL','Groenlandia'), ('GM','Gambia'), ('GN','Guinea'), ('GP','Guadalupe'), ('GQ','Guinea Ecuatorial'), ('GR','Grecia'), ('GT','Guatemala'), ('GU','Guam'), ('GW','Guinea - Bissau'), ('GY','Guyana'), ('HK','Hong Kong'), ('HN','Honduras'), ('HR','Croacia'), ('HT','Haiti'), ('HU','Hungria'), ('ID','Indonesia'), ('IE','Irlanda (Eire)'), ('IL','Israel'), ('IM','Isla De Man'), ('IN','India'), ('IO','Territori Britanico'), ('IQ','Irak'), ('IR','Iran Republica Islamica'), ('IS','Islandia'), ('IT','Italia'), ('JM','Jamaica'), ('JO','Jordania'), ('JP','Japon'), ('KE','Kenya'), ('KG','Kirguizistan'), ('KH','Kampuchea (Camboya)'), ('KI','Kiribati'), ('KM','Comoras'), ('KN','San Cristobal Y Nieves'), ('KP','Corea Del Norte Republica'), ('KR','Corea Del Sur Republica'), ('KW','Kuwait'), ('KY','Caiman Islas'), ('KZ','Kazajstan'), ('LA','Laos Republica Popular'), ('LB','Libano'), ('LC','Santa Lucia'), ('LI','Liechtenstein'), ('LK','Sri Lanka'), ('LR','Liberia'), ('LS','Lesotho'), ('LT','Lituania'), ('LU','Luxemburgo'), ('LV','Letonia'), ('LY','Libia(Incluye Fezzan'), ('MA','Marruecos'), ('MC','Monaco'), ('MD','Moldavia'), ('MG','Madagascar'), ('MH','Marshall Islas'), ('MK','Macedonia'), ('ML','Mali'), ('MM','Birmania (Myanmar)'), ('MN','Mongolia'), ('MO','Macao'), ('MP','Marianas Del Norte Islas'), ('MQ','Martinica'), ('MR','Mauritania'), ('MS','Monserrat Islas'), ('MT','Malta'), ('MU','Mauricio'), ('MV','Maldivas'), ('MW','Malawi'), ('MX','Mexico'), ('MY','Malasia'), ('MZ','Mozambique'), ('NA','Namibia'), ('NC','Nueva Caledonia'), ('NE','Niger'), ('NF','Norfolk Isla'), ('NG','Nigeria'), ('NI','Nicaragua'), ('NL','Paises Bajos(Holanda'), ('NO','Noruega'), ('NP','Nepal'), ('NR','Nauru'), ('NU','Nive Isla'), ('NZ','Nueva Zelandia'), ('OM','Oman'), ('PA','Panama'), ('PE','Peru'), ('PF','Polinesia Francesa'), ('PG','Papuasia Nuev Guinea'), ('PH','Filipinas'), ('PK','Pakistan'), ('PL','Polonia'), ('PM','San Pedro Y Miguelon'), ('PN','Pitcairn Isla'), ('PR','Puerto Rico'), ('PS','Palestina'), ('PT','Portugal'), ('PW','Palau Islas'), ('PY','Paraguay'), ('QA','Qatar'), ('RE','Reunion'), ('RO','Rumania'), ('RS','Serbia'), ('RU','Rusia'), ('RW','Rwanda'), ('SA','Arabia Saudita'), ('SB','Salomsn Islas'), ('SC','Seychelles'), ('SD','Sudan'), ('SE','Suecia'), ('SG','Singapur'), ('SH','Santa Elena'), ('SI','Eslovenia'), ('SK','Eslovaquia'), ('SL','Sierra Leona'), ('SM','San Marino'), ('SN','Senegal'), ('SO','Somalia'), ('SR','Surinam'), ('ST','Santo Tome Y Princip'), ('SV','El Salvador'), ('SY','Siria Republica Arabe'), ('SZ','Swazilandia'), ('TC','Turcas Y Caicos Isla'), ('TD','Chad'), ('TG','Togo'), ('TH','Tailandia'), ('TJ','Tadjikistan'), ('TK','Tokelau'), ('TL','Timor Del Este'), ('TM','Turkmenistan'), ('TN','Tunicia'), ('TO','Tonga'), ('TR','Turquia'), ('TT','Trinidad Y Tobago'), ('TV','Tuvalu'), ('TW','Taiwan (Formosa)'), ('TZ','Tanzania Republica'), ('UA','Ucrania'), ('UG','Uganda'), ('UM','Islas Menores De Estados Unidos'), ('UN','Niue Isla'), ('US','Estados Unidos'), ('UY','Uruguay'), ('UZ','Uzbekistan'), ('VA','Ciudad Del Vaticano'), ('VC','San Vicente Y Las Gr'), ('VE','Venezuela'), ('VG','Virgenes Islas Britanicas'), ('VI','Virgenes Islas'), ('VN','Vietnam'), ('VU','Vanuatu'), ('WF','Wallis Y Fortuna Islas'), ('WS','Samoa'), ('YE','Yemen'), ('YU','Yugoslavia'), ('ZA','Sudafrica Republica'), ('ZM','Zambia'), ('ZW','Zimbabwe') ], validate_choice=True) idDepartamento = SelectField('Departamento Residencia', choices=[ (5,'Antioquia'), (8,'Atlántico'), (11,'Bogotá DC'), (13,'Bolívar'), (15,'Boyacá'), (17,'Caldas'), (18,'Caquetá'), (19,'Cauca'), (20,'Cesar'), (23,'Córdoba'), (25,'Cundinamarca'), (27,'Chocó'), (41,'Huila'), (44,'La Guajira'), (47,'Magdalena'), (50,'Meta'), (52,'Nariño'), (54,'Norte de Santander'), (63,'Quindío'), (66,'Risaralda'), (68,'Santander'), (70,'Sucre'), (73,'Tolima'), (76,'Valle del Cauca'), (81,'Arauca'), (85,'Casanare'), (86,'Putumayo'), (88,'San Andres'), (91,'Amazonas'), (94,'Guainía'), (95,'Guaviare'), (97,'Vaupés'), (99,'Vichada'), ], validate_choice=True) idMunicipio = SelectField('Municipio Residencia', choices=[ (5001,'Medellín'), (5002,'Abejorral'), (5004,'Abriaquí'), (5021,'Alejandría'), (5030,'Amagá'), (5031,'Amalfi'), (5034,'Andes'), (5036,'Angelópolis'), (5038,'Angostura'), (5040,'Anorí'), (5042,'Santafé De Antioquia'), (5044,'Anza'), (5045,'Apartadó'), (5051,'Arboletes'), (5055,'Argelia'), (5059,'Armenia'), (5079,'Barbosa'), (5086,'Belmira'), (5088,'Bello'), (5091,'Betania'), (5093,'Betulia'), (5101,'Ciudad Bolívar'), (5107,'Briceño'), (5113,'Buriticá'), (5120,'Cáceres'), (5125,'Caicedo'), (5129,'Caldas'), (5134,'Campamento'), (5138,'Cañasgordas'), (5142,'Caracolí'), (5145,'Caramanta'), (5147,'Carepa'), (5148,'El Carmen De Viboral'), (5150,'Carolina'), (5154,'Caucasia'), (5172,'Chigorodó'), (5190,'Cisneros'), (5197,'Cocorná'), (5206,'Concepción'), (5209,'Concordia'), (5212,'Copacabana'), (5234,'Dabeiba'), (5237,'Don Matías'), (5240,'Ebéjico'), (5250,'El Bagre'), (5264,'Entrerrios'), (5266,'Envigado'), (5282,'Fredonia'), (5284,'Frontino'), (5306,'Giraldo'), (5308,'Girardota'), (5310,'Gómez Plata'), (5313,'Granada'), (5315,'Guadalupe'), (5318,'Guarne'), (5321,'Guatape'), (5347,'Heliconia'), (5353,'Hispania'), (5360,'Itagui'), (5361,'Ituango'), (5364,'Jardín'), (5368,'Jericó'), (5376,'La Ceja'), (5380,'La Estrella'), (5390,'La Pintada'), (5400,'La Unión'), (5411,'Liborina'), (5425,'Maceo'), (5440,'Marinilla'), (5467,'Montebello'), (5475,'Murindó'), (5480,'Mutatá'), (5483,'Nariño'), (5490,'Necoclí'), (5495,'Nechí'), (5501,'Olaya'), (5541,'Peñol'), (5543,'Peque'), (5576,'Pueblorrico'), (5579,'Puerto Berrío'), (5585,'Puerto Nare'), (5591,'Puerto Triunfo'), (5604,'Remedios'), (5607,'Retiro'), (5615,'Rionegro'), (5628,'Sabanalarga'), (5631,'Sabaneta'), (5642,'Salgar'), (5647,'San Andrés De Cuerquía'), (5649,'San Carlos'), (5652,'San Francisco'), (5656,'San Jerónimo'), (5658,'San José De La Montaña'), (5659,'San Juan De Urabá'), (5660,'San Luis'), (5664,'San Pedro'), (5665,'San Pedro De Uraba'), (5667,'San Rafael'), (5670,'San Roque'), (5674,'San Vicente'), (5679,'Santa Bárbara'), (5686,'Santa Rosa De Osos'), (5690,'Santo Domingo'), (5697,'El Santuario'), (5736,'Segovia'), (5756,'Sonson'), (5761,'Sopetrán'), (5789,'Támesis'), (5790,'Tarazá'), (5792,'Tarso'), (5809,'Titiribí'), (5819,'Toledo'), (5837,'Turbo'), (5842,'Uramita'), (5847,'Urrao'), (5854,'Valdivia'), (5856,'Valparaíso'), (5858,'Vegachí'), (5861,'Venecia'), (5873,'Vigía Del Fuerte'), (5885,'Yalí'), (5887,'Yarumal'), (5890,'Yolombó'), (5893,'Yondó'), (5895,'Zaragoza'), (8001,'Barranquilla'), (8078,'Baranoa'), (8137,'Campo De La Cruz'), (8141,'Candelaria'), (8296,'Galapa'), (8372,'Juan De Acosta'), (8421,'Luruaco'), (8433,'Malambo'), (8436,'Manatí'), (8520,'Palmar De Varela'), (8549,'Piojó'), (8558,'Polonuevo'), (8560,'Ponedera'), (8573,'Puerto Colombia'), (8606,'Repelón'), (8634,'Sabanagrande'), (8638,'Sabanalarga'), (8675,'Santa Lucía'), (8685,'Santo Tomás'), (8758,'Soledad'), (8770,'Suan'), (8832,'Tubará'), (8849,'Usiacurí'), (11001,'Bogota DC'), (13001,'Cartagena'), (13006,'Choachí'), (13030,'Altos Del Rosario'), (13042,'Arenal'), (13052,'Arjona'), (13062,'Arroyohondo'), (13074,'Barranco De Loba'), (13140,'Calamar'), (13160,'Cantagallo'), (13188,'Cicuco'), (13212,'Córdoba'), (13222,'Clemencia'), (13244,'El Carmen De Bolívar'), (13248,'El Guamo'), (13268,'El Peñón'), (13300,'Hatillo De Loba'), (13430,'Magangué'), (13433,'Mahates'), (13440,'Margarita'), (13442,'María La Baja'), (13458,'Montecristo'), (13468,'Mompós'), (13473,'Morales'), (13549,'Pinillos'), (13580,'Regidor'), (13600,'Río Viejo'), (13620,'San Cristóbal'), (13647,'San Estanislao'), (13650,'San Fernando'), (13654,'San Jacinto'), (13655,'San Jacinto Del Cauca'), (13657,'San Juan Nepomuceno'), (13667,'San Martín De Loba'), (13670,'San Pablo'), (13673,'Santa Catalina'), (13683,'Santa Rosa'), (13688,'Santa Rosa Del Sur'), (13744,'Simití'), (13760,'Soplaviento'), (13780,'Talaigua Nuevo'), (13810,'Tiquisio'), (13836,'Turbaco'), (13838,'Turbaná'), (13873,'Villanueva'), (13894,'Zambrano'), (15001,'Tunja'), (15022,'Almeida'), (15047,'Aquitania'), (15051,'Arcabuco'), (15087,'Belén'), (15090,'Berbeo'), (15092,'Betéitiva'), (15097,'Boavita'), (15104,'Boyacá'), (15106,'Briceño'), (15109,'Buenavista'), (15114,'Busbanzá'), (15131,'Caldas'), (15135,'Campohermoso'), (15162,'Cerinza'), (15172,'Chinavita'), (15176,'Chiquinquirá'), (15180,'Chiscas'), (15183,'Chita'), (15185,'Chitaraque'), (15187,'Chivatá'), (15189,'Ciénega'), (15204,'Cómbita'), (15212,'Coper'), (15215,'Corrales'), (15218,'Covarachía'), (15223,'Cubará'), (15224,'Cucaita'), (15226,'Cuítiva'), (15232,'Chíquiza'), (15236,'Chivor'), (15238,'Duitama'), (15244,'El Cocuy'), (15248,'El6Aspino'), (15272,'Firavitoba'), (15276,'Floresta'), (15293,'Gachantivá'), (15296,'Gameza'), (15299,'Garagoa'), (15317,'Guacamayas'), (15322,'Guateque'), (15325,'Guayatá'), (15332,'Guican'), (15362,'Iza'), (15367,'Jenesano'), (15368,'Jericó'), (15377,'Labranzagrande'), (15380,'La Capilla'), (15401,'La Victoria'), (15403,'La Uvita'), (15407,'Villa De Leyva'), (15425,'Macanal'), (15442,'Maripí'), (15455,'Miraflores'), (15464,'Mongua'), (15466,'Monguí'), (15469,'Moniquirá'), (15476,'Motavita'), (15480,'Muzo'), (15491,'Nobsa'), (15494,'Nuevo Colón'), (15500,'Oicatá'), (15507,'Otanche'), (15511,'Pachavita'), (15514,'Páez'), (15516,'Paipa'), (15518,'Pajarito'), (15522,'Panqueba'), (15531,'Pauna'), (15533,'Paya'), (15537,'Paz De Río'), (15542,'Pesca'), (15550,'Pisba'), (15572,'Puerto Boyacá'), (15580,'Quípama'), (15599,'Ramiriquí'), (15600,'Ráquira'), (15621,'Rondón'), (15632,'Saboyá'), (15638,'Sáchica'), (15646,'Samacá'), (15660,'San Eduardo'), (15664,'San José De Pare'), (15667,'San Luis De Gaceno'), (15673,'San Mateo'), (15676,'San Miguel De Sema'), (15681,'San Pablo De Borbur'), (15686,'Santana'), (15690,'Santa María'), (15693,'Santa Rosa De Viterbo'), (15696,'Santa Sofía'), (15720,'Sativanorte'), (15723,'Sativasur'), (15740,'Siachoque'), (15753,'Soatá'), (15755,'Socotá'), (15757,'Socha'), (15759,'Sogamoso'), (15761,'Somondoco'), (15762,'Sora'), (15763,'Sotaquirá'), (15764,'Soracá'), (15774,'Susacón'), (15776,'Sutamarchán'), (15778,'Sutatenza'), (15790,'Tasco'), (15798,'Tenza'), (15804,'Tibaná'), (15806,'Tibasosa'), (15808,'Tinjacá'), (15810,'Tipacoque'), (15814,'Toca'), (15816,'Togüí'), (15820,'Tópaga'), (15822,'Tota'), (15832,'Tununguá'), (15835,'Turmequé'), (15837,'Tuta'), (15839,'Tutazá'), (15842,'Umbita'), (15861,'Ventaquemada'), (15879,'Viracachá'), (15897,'Zetaquira'), (17001,'Manizales'), (17013,'Aguadas'), (17042,'Anserma'), (17050,'Aranzazu'), (17088,'Belalcázar'), (17174,'Chinchiná'), (17272,'Filadelfia'), (17380,'La Dorada'), (17388,'La Merced'), (17433,'Manzanares'), (17442,'Marmato'), (17444,'Marquetalia'), (17446,'Marulanda'), (17486,'Neira'), (17495,'Norcasia'), (17513,'Pácora'), (17524,'Palestina'), (17541,'Pensilvania'), (17614,'Riosucio'), (17616,'Risaralda'), (17653,'Salamina'), (17662,'Samaná'), (17665,'San José'), (17777,'Supía'), (17867,'Victoria'), (17873,'Villamaría'), (17877,'Viterbo'), (18001,'Florencia'), (18029,'Albania'), (18094,'Belén De Los Andaquies'), (18150,'Cartagena Del Chairá'), (18205,'Curillo'), (18247,'El Doncello'), (18256,'El Paujil'), (18410,'La Montañita'), (18460,'Milán'), (18479,'Morelia'), (18592,'Puerto Rico'), (18610,'San José Del Fragua'), (18753,'San Vicente Del Caguán'), (18756,'Solano'), (18785,'Solita'), (18860,'Valparaíso'), (19001,'Popayán'), (19022,'Almaguer'), (19050,'Argelia'), (19075,'Balboa'), (19100,'Bolívar'), (19110,'Buenos Aires'), (19130,'Cajibío'), (19137,'Caldono'), (19142,'Caloto'), (19212,'Corinto'), (19256,'El Tambo'), (19290,'Florencia'), (19300,'Guachené'), (19318,'Guapi'), (19355,'Inzá'), (19364,'Jambaló'), (19392,'La Sierra'), (19397,'La Vega'), (19418,'López'), (19450,'Mercaderes'), (19455,'Miranda'), (19473,'Morales'), (19513,'Padilla'), (19517,'Paez'), (19532,'Patía'), (19533,'Piamonte'), (19548,'Piendamó'), (19573,'Puerto Tejada'), (19585,'Puracé'), (19622,'Rosas'), (19693,'San Sebastián'), (19698,'Santander De Quilichao'), (19701,'Santa Rosa'), (19743,'Silvia'), (19760,'Sotara'), (19780,'Suárez'), (19785,'Sucre'), (19807,'Timbío'), (19809,'Timbiquí'), (19821,'Toribio'), (19824,'Totoró'), (19845,'Villa Rica'), (20001,'Valledupar'), (20011,'Aguachica'), (20013,'Agustín Codazzi'), (20032,'Astrea'), (20045,'Becerril'), (20060,'Bosconia'), (20175,'Chimichagua'), (20178,'Chiriguaná'), (20228,'Curumaní'), (20238,'El Copey'), (20250,'El Paso'), (20295,'Gamarra'), (20310,'González'), (20383,'La Gloria'), (20400,'La Jagua De Ibirico'), (20443,'Manaure'), (20517,'Pailitas'), (20550,'Pelaya'), (20570,'Pueblo Bello'), (20614,'Río De Oro'), (20621,'La Paz'), (20710,'San Alberto'), (20750,'San Diego'), (20770,'San Martín'), (20787,'Tamalameque'), (23001,'Montería'), (23068,'Ayapel'), (23079,'Buenavista'), (23090,'Canalete'), (23162,'Cereté'), (23168,'Chimá'), (23182,'Chinú'), (23189,'Ciénaga De Oro'), (23300,'Cotorra'), (23350,'La Apartada'), (23417,'Lorica'), (23419,'Los Córdobas'), (23464,'Momil'), (23466,'Montelíbano'), (23500,'Moñitos'), (23555,'Planeta Rica'), (23570,'Pueblo Nuevo'), (23574,'Puerto Escondido'), (23580,'Puerto Libertador'), (23586,'Purísima'), (23660,'Sahagún'), (23670,'San Andrés Sotavento'), (23672,'San Antero'), (23675,'San Bernardo Del Viento'), (23678,'San Carlos'), (23686,'San Pelayo'), (23807,'Tierralta'), (23855,'Valencia'), (25001,'Agua De Dios'), (25019,'Albán'), (25035,'Anapoima'), (25040,'Anolaima'), (25053,'Arbeláez'), (25086,'Beltrán'), (25095,'Bituima'), (25099,'Bojacá'), (25120,'Cabrera'), (25123,'Cachipay'), (25126,'Cajicá'), (25148,'Caparrapí'), (25151,'Caqueza'), (25154,'Carmen De Carupa'), (25168,'Chaguaní'), (25175,'Chía'), (25178,'Chipaque'), (25181,'Choachí'), (25183,'Chocontá'), (25200,'Cogua'), (25214,'Cota'), (25224,'Cucunuba'), (25245,'El Colegio'), (25258,'El Peñón'), (25260,'El Rosal'), (25269,'Facatativá'), (25279,'Fomeque'), (25281,'Fosca'), (25286,'Funza'), (25288,'Fúquene'), (25290,'Fusagasugá'), (25293,'Gachala'), (25295,'Gachancipá'), (25297,'Gachetá'), (25299,'Gama'), (25307,'Girardot'), (25312,'Granada'), (25317,'Guachetá'), (25320,'Guaduas'), (25322,'Guasca'), (25324,'Guataquí'), (25326,'Guatavita'), (25328,'Guayabal De Siquima'), (25335,'Guayabetal'), (25339,'Gutiérrez'), (25368,'Jerusalén'), (25372,'Junín'), (25377,'La Calera'), (25386,'La Mesa'), (25394,'La Palma'), (25398,'La Peña'), (25402,'La Vega'), (25407,'Lenguazaque'), (25426,'Macheta'), (25430,'Madrid'), (25436,'Manta'), (25438,'Medina'), (25473,'Mosquera'), (25483,'Nariño'), (25486,'Nemocón'), (25488,'Nilo'), (25489,'Nimaima'), (25491,'Nocaima'), (25506,'Venecia'), (25513,'Pacho'), (25518,'Paime'), (25524,'Pandi'), (25530,'Paratebueno'), (25535,'Pasca'), (25572,'Puerto Salgar'), (25580,'Pulí'), (25592,'Quebradanegra'), (25594,'Quetame'), (25596,'Quipile'), (25599,'Apulo'), (25612,'Ricaurte'), (25645,'San Antonio Del Tequendama'), (25649,'San Bernardo'), (25653,'San Cayetano'), (25658,'San Francisco'), (25662,'San Juan De Río Seco'), (25718,'Sasaima'), (25736,'Sesquilé'), (25740,'Sibaté'), (25743,'Silvania'), (25745,'Simijaca'), (25754,'Soacha'), (25758,'Sopó'), (25769,'Subachoque'), (25772,'Suesca'), (25777,'Supatá'), (25779,'Susa'), (25781,'Sutatausa'), (25785,'Tabio'), (25793,'Tausa'), (25797,'Tena'), (25799,'Tenjo'), (25805,'Tibacuy'), (25807,'Tibirita'), (25815,'Tocaima'), (25817,'Tocancipá'), (25823,'Topaipi'), (25839,'Ubalá'), (25841,'Ubaque'), (25843,'Villa De San Diego De Ubate'), (25845,'Une'), (25851,'Útica'), (25862,'Vergara'), (25867,'Vianí'), (25871,'Villagómez'), (25873,'Villapinzón'), (25875,'Villeta'), (25878,'Viotá'), (25885,'Yacopí'), (25898,'Zipacón'), (25899,'Zipaquirá'), (27001,'Quibdó'), (27006,'Acandí'), (27025,'Alto Baudo'), (27050,'Atrato'), (27073,'Bagadó'), (27075,'Bahía Solano'), (27077,'Bajo Baudó'), (27086,'Belén De Bajirá'), (27099,'Bojaya'), (27135,'El Cantón Del San Pablo'), (27150,'Carmen Del Darien'), (27160,'Cértegui'), (27205,'Condoto'), (27245,'El Carmen De Atrato'), (27250,'El Litoral Del San Juan'), (27361,'Istmina'), (27372,'Juradó'), (27413,'Lloró'), (27425,'Medio Atrato'), (27430,'Medio Baudó'), (27450,'Medio San Juan'), (27491,'Nóvita'), (27495,'Nuquí'), (27580,'Río Iro'), (27600,'Río Quito'), (27615,'Riosucio'), (27660,'San José Del Palmar'), (27745,'Sipí'), (27787,'Tadó'), (27800,'Unguía'), (27810,'Unión Panamericana'), (41001,'Neiva'), (41006,'Acevedo'), (41013,'Agrado'), (41016,'Aipe'), (41020,'Algeciras'), (41026,'Altamira'), (41078,'Baraya'), (41132,'Campoalegre'), (41206,'Colombia'), (41244,'Elías'), (41298,'Garzón'), (41306,'Gigante'), (41319,'Guadalupe'), (41349,'Hobo'), (41357,'Iquira'), (41359,'Isnos'), (41378,'La Argentina'), (41396,'La Plata'), (41483,'Nátaga'), (41503,'Oporapa'), (41518,'Paicol'), (41524,'Palermo'), (41530,'Palestina'), (41548,'Pital'), (41551,'Pitalito'), (41615,'Rivera'), (41660,'Saladoblanco'), (41668,'San Agustín'), (41676,'Santa María'), (41770,'Suaza'), (41791,'Tarqui'), (41797,'Tesalia'), (41799,'Tello'), (41801,'Teruel'), (41807,'Timana'), (41872,'Villavieja'), (41885,'Yaguará'), (44001,'Riohacha'), (44035,'Albania'), (44078,'Barrancas'), (44090,'Dibulla'), (44098,'Distracción'), (44110,'El Molino'), (44279,'Fonseca'), (44378,'Hatonuevo'), (44420,'La Jagua Del Pilar'), (44430,'Maicao'), (44560,'Manaure'), (44650,'San Juan Del Cesar'), (44847,'Uribia'), (44855,'Urumita'), (44874,'Villanueva'), (47001,'Santa Marta'), (47030,'Algarrobo'), (47053,'Aracataca'), (47058,'Ariguaní'), (47161,'Cerro San Antonio'), (47170,'Chibolo'), (47189,'Ciénaga'), (47205,'Concordia'), (47245,'El Banco'), (47258,'El Piñon'), (47268,'El Retén'), (47288,'Fundación'), (47318,'Guamal'), (47460,'Nueva Granada'), (47541,'Pedraza'), (47545,'Pijiño Del Carmen'), (47551,'Pivijay'), (47555,'Plato'), (47570,'Puebloviejo'), (47605,'Remolino'), (47660,'Sabanas De San Angel'), (47675,'Salamina'), (47692,'San Sebastián De Buenavista'), (47703,'San Zenón'), (47707,'Santa Ana'), (47720,'Santa Bárbara De Pinto'), (47745,'Sitionuevo'), (47798,'Tenerife'), (47960,'Zapayán'), (47980,'Zona Bananera'), (50001,'Villavicencio'), (50006,'Acacías'), (50110,'Barranca De Upía'), (50124,'Cabuyaro'), (50150,'Castilla La Nueva'), (50223,'Cubarral'), (50226,'Cumaral'), (50245,'El Calvario'), (50251,'El Castillo'), (50270,'El Dorado'), (50287,'Fuente De Oro'), (50313,'Granada'), (50318,'Guamal'), (50325,'Mapiripán'), (50330,'Mesetas'), (50350,'La Macarena'), (50370,'Uribe'), (50400,'Lejanías'), (50450,'Puerto Concordia'), (50568,'Puerto Gaitán'), (50573,'Puerto López'), (50577,'Puerto Lleras'), (50590,'Puerto Rico'), (50606,'Restrepo'), (50680,'San Carlos De Guaroa'), (50683,'San Juan De Arama'), (50686,'San Juanito'), (50689,'San Martín'), (50711,'Vistahermosa'), (52001,'Pasto'), (52019,'Albán'), (52022,'Aldana'), (52036,'Ancuya'), (52051,'Arboleda'), (52079,'Barbacoas'), (52083,'Belén'), (52110,'Buesaco'), (52203,'Colón'), (52207,'Consaca'), (52210,'Contadero'), (52215,'Córdoba'), (52224,'Cuaspud'), (52227,'Cumbal'), (52233,'Cumbitara'), (52240,'Chachagüí'), (52250,'El Charco'), (52254,'El Peñol'), (52256,'El Rosario'), (52258,'El Tablón De Gómez'), (52260,'El Tambo'), (52287,'Funes'), (52317,'Guachucal'), (52320,'Guaitarilla'), (52323,'Gualmatán'), (52352,'Iles'), (52354,'Imués'), (52356,'Ipiales'), (52378,'La Cruz'), (52381,'La Florida'), (52385,'La Llanada'), (52390,'La Tola'), (52399,'La Unión'), (52405,'Leiva'), (52411,'Linares'), (52418,'Los Andes'), (52427,'Magüi'), (52435,'Mallama'), (52473,'Mosquera'), (52480,'Nariño'), (52490,'Olaya Herrera'), (52506,'Ospina'), (52520,'Francisco Pizarro'), (52540,'Policarpa'), (52560,'Potosí'), (52565,'Providencia'), (52573,'Puerres'), (52585,'Pupiales'), (52612,'Ricaurte'), (52621,'Roberto Payán'), (52678,'Samaniego'), (52683,'Sandoná'), (52685,'San Bernardo'), (52687,'San Lorenzo'), (52693,'San Pablo'), (52694,'San Pedro De Cartago'), (52696,'Santa Bárbara'), (52699,'Santacruz'), (52720,'Sapuyes'), (52786,'Taminango'), (52788,'Tangua'), (52835,'San Andres De Tumaco'), (52838,'Túquerres'), (52885,'Yacuanquer'), (54001,'Cúcuta'), (54003,'Abrego'), (54051,'Arboledas'), (54099,'Bochalema'), (54109,'Bucarasica'), (54125,'Cácota'), (54128,'Cachirá'), (54172,'Chinácota'), (54174,'Chitagá'), (54206,'Convención'), (54223,'Cucutilla'), (54239,'Durania'), (54245,'El Carmen'), (54250,'El Tarra'), (54261,'El Zulia'), (54313,'Gramalote'), (54344,'Hacarí'), (54347,'Herrán'), (54377,'Labateca'), (54385,'La Esperanza'), (54398,'La Playa'), (54405,'Los Patios'), (54418,'Lourdes'), (54480,'Mutiscua'), (54498,'Ocaña'), (54518,'Pamplona'), (54520,'Pamplonita'), (54553,'Puerto Santander'), (54599,'Ragonvalia'), (54660,'Salazar'), (54670,'San Calixto'), (54673,'San Cayetano'), (54680,'Santiago'), (54720,'Sardinata'), (54743,'Silos'), (54800,'Teorama'), (54810,'Tibú'), (54820,'Toledo'), (54871,'Villa Caro'), (54874,'Villa Del Rosario'), (63001,'Armenia'), (63111,'Buenavista'), (63130,'Calarca'), (63190,'Circasia'), (63212,'Córdoba'), (63272,'Filandia'), (63302,'Génova'), (63401,'La Tebaida'), (63470,'Montenegro'), (63548,'Pijao'), (63594,'Quimbaya'), (63690,'Salento'), (66001,'Pereira'), (66045,'Apía'), (66075,'Balboa'), (66088,'Belén De Umbría'), (66170,'Dosquebradas'), (66318,'Guática'), (66383,'La Celia'), (66400,'La Virginia'), (66440,'Marsella'), (66456,'Mistrató'), (66572,'Pueblo Rico'), (66594,'Quinchía'), (66682,'Santa Rosa De Cabal'), (66687,'Santuario'), (68001,'Bucaramanga'), (68013,'Aguada'), (68020,'Albania'), (68051,'Aratoca'), (68077,'Barbosa'), (68079,'Barichara'), (68081,'Barrancabermeja'), (68092,'Betulia'), (68101,'Bolívar'), (68121,'Cabrera'), (68132,'California'), (68147,'Capitanejo'), (68152,'Carcasí'), (68160,'Cepitá'), (68162,'Cerrito'), (68167,'Charalá'), (68169,'Charta'), (68176,'Chima'), (68179,'Chipatá'), (68190,'Cimitarra'), (68207,'Concepción'), (68209,'Confines'), (68211,'Contratación'), (68217,'Coromoro'), (68229,'Curití'), (68235,'El Carmen De Chucurí'), (68245,'El Guacamayo'), (68250,'El Peñón'), (68255,'El Playón'), (68264,'Encino'), (68266,'Enciso'), (68271,'Florián'), (68276,'Floridablanca'), (68296,'Galan'), (68298,'Gambita'), (68307,'Girón'), (68318,'Guaca'), (68320,'Guadalupe'), (68322,'Guapotá'), (68324,'Guavatá'), (68327,'Güepsa'), (68344,'Hato'), (68368,'Jesús María'), (68370,'Jordán'), (68377,'La Belleza'), (68385,'Landázuri'), (68397,'La Paz'), (68406,'Lebríja'), (68418,'Los Santos'), (68425,'Macaravita'), (68432,'Málaga'), (68444,'Matanza'), (68464,'Mogotes'), (68468,'Molagavita'), (68498,'Ocamonte'), (68500,'Oiba'), (68502,'Onzaga'), (68522,'Palmar'), (68524,'Palmas Del Socorro'), (68533,'Páramo'), (68547,'Piedecuesta'), (68549,'Pinchote'), (68572,'Puente Nacional'), (68573,'Puerto Parra'), (68575,'Puerto Wilches'), (68615,'Rionegro'), (68655,'Sabana De Torres'), (68669,'San Andrés'), (68673,'San Benito'), (68679,'San Gil'), (68682,'San Joaquín'), (68684,'San José De Miranda'), (68686,'San Miguel'), (68689,'San Vicente De Chucurí'), (68705,'Santa Bárbara'), (68720,'Santa Helena Del Opón'), (68745,'Simacota'), (68755,'Socorro'), (68770,'Suaita'), (68773,'Sucre'), (68780,'Suratá'), (68820,'Tona'), (68855,'Valle De San José'), (68861,'Vélez'), (68867,'Vetas'), (68872,'Villanueva'), (68895,'Zapatoca'), (70001,'Sincelejo'), (70110,'Buenavista'), (70124,'Caimito'), (70204,'Coloso'), (70215,'Corozal'), (70221,'Coveñas'), (70230,'Chalán'), (70233,'El Roble'), (70235,'Galeras'), (70265,'Guaranda'), (70400,'La Unión'), (70418,'Los Palmitos'), (70429,'Majagual'), (70473,'Morroa'), (70508,'Ovejas'), (70523,'Palmito'), (70670,'Sampués'), (70678,'San Benito Abad'), (70702,'San Juan De Betulia'), (70708,'San Marcos'), (70713,'San Onofre'), (70717,'San Pedro'), (70742,'San Luis De Sincé'), (70771,'Sucre'), (70820,'Santiago De Tolú'), (70823,'Tolú Viejo'), (73001,'Ibague'), (73024,'Alpujarra'), (73026,'Alvarado'), (73030,'Ambalema'), (73043,'Anzoátegui'), (73055,'Armero'), (73067,'Ataco'), (73124,'Cajamarca'), (73148,'Carmen De Apicalá'), (73152,'Casabianca'), (73168,'Chaparral'), (73200,'Coello'), (73217,'Coyaima'), (73226,'Cunday'), (73236,'Dolores'), (73268,'Espinal'), (73270,'Falan'), (73275,'Flandes'), (73283,'Fresno'), (73319,'Guamo'), (73347,'Herveo'), (73349,'Honda'), (73352,'Icononzo'), (73408,'Lérida'), (73411,'Líbano'), (73443,'Mariquita'), (73449,'Melgar'), (73461,'Murillo'), (73483,'Natagaima'), (73504,'Ortega'), (73520,'Palocabildo'), (73547,'Piedras'), (73555,'Planadas'), (73563,'Prado'), (73585,'Purificación'), (73616,'Rioblanco'), (73622,'Roncesvalles'), (73624,'Rovira'), (73671,'Saldaña'), (73675,'San Antonio'), (73678,'San Luis'), (73686,'Santa Isabel'), (73770,'Suárez'), (73854,'Valle De San Juan'), (73861,'Venadillo'), (73870,'Villahermosa'), (73873,'Villarrica'), (76001,'Cali'), (76020,'Alcalá'), (76036,'Andalucía'), (76041,'Ansermanuevo'), (76054,'Argelia'), (76100,'Bolívar'), (76109,'Buenaventura'), (76111,'Guadalajara De Buga'), (76113,'Bugalagrande'), (76122,'Caicedonia'), (76126,'Calima'), (76130,'Candelaria'), (76147,'Cartago'), (76233,'Dagua'), (76243,'El Águila'), (76246,'El Cairo'), (76248,'El Cerrito'), (76250,'El Dovio'), (76275,'Florida'), (76306,'Ginebra'), (76318,'Guacarí'), (76364,'Jamundí'), (76377,'La Cumbre'), (76400,'La Unión'), (76403,'La Victoria'), (76497,'Obando'), (76520,'Palmira'), (76563,'Pradera'), (76606,'Restrepo'), (76616,'Riofrío'), (76622,'Roldanillo'), (76670,'San Pedro'), (76736,'Sevilla'), (76823,'Toro'), (76828,'Trujillo'), (76834,'Tuluá'), (76845,'Ulloa'), (76863,'Versalles'), (76869,'Vijes'), (76890,'Yotoco'), (76892,'Yumbo'), (76895,'Zarzal'), (81001,'Arauca'), (81065,'Arauquita'), (81220,'Cravo Norte'), (81300,'Fortul'), (81591,'Puerto Rondón'), (81736,'Saravena'), (81794,'Tame'), (85001,'Yopal'), (85010,'Aguazul'), (85015,'Chameza'), (85125,'Hato Corozal'), (85136,'La Salina'), (85139,'Maní'), (85162,'Monterrey'), (85225,'Nunchía'), (85230,'Orocué'), (85250,'Paz De Ariporo'), (85263,'Pore'), (85279,'Recetor'), (85300,'Sabanalarga'), (85315,'Sácama'), (85325,'San Luis De Palenque'), (85400,'Támara'), (85410,'Tauramena'), (85430,'Trinidad'), (85440,'Villanueva'), (86001,'Mocoa'), (86219,'Colón'), (86320,'Orito'), (86568,'Puerto Asís'), (86569,'Puerto Caicedo'), (86571,'Puerto Guzmán'), (86573,'Leguízamo'), (86749,'Sibundoy'), (86755,'San Francisco'), (86757,'San Miguel'), (86760,'Santiago'), (86865,'Valle Del Guamuez'), (86885,'Villagarzón'), (88001,'San Andrés'), (88564,'Providencia'), (91001,'Leticia'), (91263,'El Encanto'), (91405,'La Chorrera'), (91407,'La Pedrera'), (91430,'La Victoria'), (91460,'Miriti - Paraná'), (91530,'Puerto Alegría'), (91536,'Puerto Arica'), (91540,'Puerto Nariño'), (91669,'Puerto Santander'), (91798,'Tarapacá'), (94001,'Inírida'), (94343,'Barranco Minas'), (94663,'Mapiripana'), (94883,'San Felipe'), (94884,'Puerto Colombia'), (94885,'La Guadalupe'), (94886,'Cacahual'), (94887,'Pana Pana'), (94888,'Morichal'), (95001,'San José Del Guaviare'), (95015,'Calamar'), (95025,'El Retorno'), (95200,'Miraflores'), (97001,'Mitú'), (97161,'Caruru'), (97511,'Pacoa'), (97666,'Taraira'), (97777,'Papunaua'), (97889,'Yavaraté'), (99001,'Puerto Carreño'), (99524,'La Primavera'), (99624,'Santa Rosalía'), (99773,'Cumaribo') ], validate_choice=True) celularEmpleado = IntegerField('Numero Telefono Movil', validators=[ Required(message='El campo es obligatorio'), Length(max=10, min=10, message='El campo debe tener 10 caracteres') ]) correoElectronicoEmpleado = StringField('Correo Electronico Principal', validators=[ Required(message='El campo es obligatorio'), Email() ]) enviar = SubmitField("Enviar") class ingresoEmpleado(FlaskForm): correoElectronicoEmpleado = StringField('Correo Electronico Principal', validators=[ Required(message='El campo es obligatorio'), Email() ]) contraseñaEmpleado = PasswordField('Contraseña') enviar = SubmitField("Enviar") class editarEmpleado(FlaskForm): numeroIdEmpleado = IntegerField('Numero Identificacion', validators=[ Required(message='El campo es obligatorio'), Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres') ]) tipoId = SelectField('Tipo Idenficacion', choices=[ ('CC','Cedula de Ciudadania'), ('CE','Cedula de Extrangeria'), ('PA','Pasaporte'), ('RC','Registro Civil'), ('TI','Tarjeta de Identidad')], validators=[ Required(message='El campo es obligatorio'), ]) fechaExpIdEmpleado = DateField('Fecha Expedicion Documento Identidad', format='%Y,%M,%D') lugarExpIdEmpleado = SelectField('Ciudad Expedicion Documento Identidad', choices=[ (5001,'Medellín'), (5002,'Abejorral'), (5004,'Abriaquí'), (5021,'Alejandría'), (5030,'Amagá'), (5031,'Amalfi'), (5034,'Andes'), (5036,'Angelópolis'), (5038,'Angostura'), (5040,'Anorí'), (5042,'Santafé De Antioquia'), (5044,'Anza'), (5045,'Apartadó'), (5051,'Arboletes'), (5055,'Argelia'), (5059,'Armenia'), (5079,'Barbosa'), (5086,'Belmira'), (5088,'Bello'), (5091,'Betania'), (5093,'Betulia'), (5101,'Ciudad Bolívar'), (5107,'Briceño'), (5113,'Buriticá'), (5120,'Cáceres'), (5125,'Caicedo'), (5129,'Caldas'), (5134,'Campamento'), (5138,'Cañasgordas'), (5142,'Caracolí'), (5145,'Caramanta'), (5147,'Carepa'), (5148,'El Carmen De Viboral'), (5150,'Carolina'), (5154,'Caucasia'), (5172,'Chigorodó'), (5190,'Cisneros'), (5197,'Cocorná'), (5206,'Concepción'), (5209,'Concordia'), (5212,'Copacabana'), (5234,'Dabeiba'), (5237,'Don Matías'), (5240,'Ebéjico'), (5250,'El Bagre'), (5264,'Entrerrios'), (5266,'Envigado'), (5282,'Fredonia'), (5284,'Frontino'), (5306,'Giraldo'), (5308,'Girardota'), (5310,'Gómez Plata'), (5313,'Granada'), (5315,'Guadalupe'), (5318,'Guarne'), (5321,'Guatape'), (5347,'Heliconia'), (5353,'Hispania'), (5360,'Itagui'), (5361,'Ituango'), (5364,'Jardín'), (5368,'Jericó'), (5376,'La Ceja'), (5380,'La Estrella'), (5390,'La Pintada'), (5400,'La Unión'), (5411,'Liborina'), (5425,'Maceo'), (5440,'Marinilla'), (5467,'Montebello'), (5475,'Murindó'), (5480,'Mutatá'), (5483,'Nariño'), (5490,'Necoclí'), (5495,'Nechí'), (5501,'Olaya'), (5541,'Peñol'), (5543,'Peque'), (5576,'Pueblorrico'), (5579,'Puerto Berrío'), (5585,'Puerto Nare'), (5591,'Puerto Triunfo'), (5604,'Remedios'), (5607,'Retiro'), (5615,'Rionegro'), (5628,'Sabanalarga'), (5631,'Sabaneta'), (5642,'Salgar'), (5647,'San Andrés De Cuerquía'), (5649,'San Carlos'), (5652,'San Francisco'), (5656,'San Jerónimo'), (5658,'San José De La Montaña'), (5659,'San Juan De Urabá'), (5660,'San Luis'), (5664,'San Pedro'), (5665,'San Pedro De Uraba'), (5667,'San Rafael'), (5670,'San Roque'), (5674,'San Vicente'), (5679,'Santa Bárbara'), (5686,'Santa Rosa De Osos'), (5690,'Santo Domingo'), (5697,'El Santuario'), (5736,'Segovia'), (5756,'Sonson'), (5761,'Sopetrán'), (5789,'Támesis'), (5790,'Tarazá'), (5792,'Tarso'), (5809,'Titiribí'), (5819,'Toledo'), (5837,'Turbo'), (5842,'Uramita'), (5847,'Urrao'), (5854,'Valdivia'), (5856,'Valparaíso'), (5858,'Vegachí'), (5861,'Venecia'), (5873,'Vigía Del Fuerte'), (5885,'Yalí'), (5887,'Yarumal'), (5890,'Yolombó'), (5893,'Yondó'), (5895,'Zaragoza'), (8001,'Barranquilla'), (8078,'Baranoa'), (8137,'Campo De La Cruz'), (8141,'Candelaria'), (8296,'Galapa'), (8372,'Juan De Acosta'), (8421,'Luruaco'), (8433,'Malambo'), (8436,'Manatí'), (8520,'Palmar De Varela'), (8549,'Piojó'), (8558,'Polonuevo'), (8560,'Ponedera'), (8573,'Puerto Colombia'), (8606,'Repelón'), (8634,'Sabanagrande'), (8638,'Sabanalarga'), (8675,'Santa Lucía'), (8685,'Santo Tomás'), (8758,'Soledad'), (8770,'Suan'), (8832,'Tubará'), (8849,'Usiacurí'), (11001,'Bogota DC'), (13001,'Cartagena'), (13006,'Choachí'), (13030,'Altos Del Rosario'), (13042,'Arenal'), (13052,'Arjona'), (13062,'Arroyohondo'), (13074,'Barranco De Loba'), (13140,'Calamar'), (13160,'Cantagallo'), (13188,'Cicuco'), (13212,'Córdoba'), (13222,'Clemencia'), (13244,'El Carmen De Bolívar'), (13248,'El Guamo'), (13268,'El Peñón'), (13300,'Hatillo De Loba'), (13430,'Magangué'), (13433,'Mahates'), (13440,'Margarita'), (13442,'María La Baja'), (13458,'Montecristo'), (13468,'Mompós'), (13473,'Morales'), (13549,'Pinillos'), (13580,'Regidor'), (13600,'Río Viejo'), (13620,'San Cristóbal'), (13647,'San Estanislao'), (13650,'San Fernando'), (13654,'San Jacinto'), (13655,'San Jacinto Del Cauca'), (13657,'San Juan Nepomuceno'), (13667,'San Martín De Loba'), (13670,'San Pablo'), (13673,'Santa Catalina'), (13683,'Santa Rosa'), (13688,'Santa Rosa Del Sur'), (13744,'Simití'), (13760,'Soplaviento'), (13780,'Talaigua Nuevo'), (13810,'Tiquisio'), (13836,'Turbaco'), (13838,'Turbaná'), (13873,'Villanueva'), (13894,'Zambrano'), (15001,'Tunja'), (15022,'Almeida'), (15047,'Aquitania'), (15051,'Arcabuco'), (15087,'Belén'), (15090,'Berbeo'), (15092,'Betéitiva'), (15097,'Boavita'), (15104,'Boyacá'), (15106,'Briceño'), (15109,'Buenavista'), (15114,'Busbanzá'), (15131,'Caldas'), (15135,'Campohermoso'), (15162,'Cerinza'), (15172,'Chinavita'), (15176,'Chiquinquirá'), (15180,'Chiscas'), (15183,'Chita'), (15185,'Chitaraque'), (15187,'Chivatá'), (15189,'Ciénega'), (15204,'Cómbita'), (15212,'Coper'), (15215,'Corrales'), (15218,'Covarachía'), (15223,'Cubará'), (15224,'Cucaita'), (15226,'Cuítiva'), (15232,'Chíquiza'), (15236,'Chivor'), (15238,'Duitama'), (15244,'El Cocuy'), (15248,'El6Aspino'), (15272,'Firavitoba'), (15276,'Floresta'), (15293,'Gachantivá'), (15296,'Gameza'), (15299,'Garagoa'), (15317,'Guacamayas'), (15322,'Guateque'), (15325,'Guayatá'), (15332,'Guican'), (15362,'Iza'), (15367,'Jenesano'), (15368,'Jericó'), (15377,'Labranzagrande'), (15380,'La Capilla'), (15401,'La Victoria'), (15403,'La Uvita'), (15407,'Villa De Leyva'), (15425,'Macanal'), (15442,'Maripí'), (15455,'Miraflores'), (15464,'Mongua'), (15466,'Monguí'), (15469,'Moniquirá'), (15476,'Motavita'), (15480,'Muzo'), (15491,'Nobsa'), (15494,'Nuevo Colón'), (15500,'Oicatá'), (15507,'Otanche'), (15511,'Pachavita'), (15514,'Páez'), (15516,'Paipa'), (15518,'Pajarito'), (15522,'Panqueba'), (15531,'Pauna'), (15533,'Paya'), (15537,'Paz De Río'), (15542,'Pesca'), (15550,'Pisba'), (15572,'Puerto Boyacá'), (15580,'Quípama'), (15599,'Ramiriquí'), (15600,'Ráquira'), (15621,'Rondón'), (15632,'Saboyá'), (15638,'Sáchica'), (15646,'Samacá'), (15660,'San Eduardo'), (15664,'San José De Pare'), (15667,'San Luis De Gaceno'), (15673,'San Mateo'), (15676,'San Miguel De Sema'), (15681,'San Pablo De Borbur'), (15686,'Santana'), (15690,'Santa María'), (15693,'Santa Rosa De Viterbo'), (15696,'Santa Sofía'), (15720,'Sativanorte'), (15723,'Sativasur'), (15740,'Siachoque'), (15753,'Soatá'), (15755,'Socotá'), (15757,'Socha'), (15759,'Sogamoso'), (15761,'Somondoco'), (15762,'Sora'), (15763,'Sotaquirá'), (15764,'Soracá'), (15774,'Susacón'), (15776,'Sutamarchán'), (15778,'Sutatenza'), (15790,'Tasco'), (15798,'Tenza'), (15804,'Tibaná'), (15806,'Tibasosa'), (15808,'Tinjacá'), (15810,'Tipacoque'), (15814,'Toca'), (15816,'Togüí'), (15820,'Tópaga'), (15822,'Tota'), (15832,'Tununguá'), (15835,'Turmequé'), (15837,'Tuta'), (15839,'Tutazá'), (15842,'Umbita'), (15861,'Ventaquemada'), (15879,'Viracachá'), (15897,'Zetaquira'), (17001,'Manizales'), (17013,'Aguadas'), (17042,'Anserma'), (17050,'Aranzazu'), (17088,'Belalcázar'), (17174,'Chinchiná'), (17272,'Filadelfia'), (17380,'La Dorada'), (17388,'La Merced'), (17433,'Manzanares'), (17442,'Marmato'), (17444,'Marquetalia'), (17446,'Marulanda'), (17486,'Neira'), (17495,'Norcasia'), (17513,'Pácora'), (17524,'Palestina'), (17541,'Pensilvania'), (17614,'Riosucio'), (17616,'Risaralda'), (17653,'Salamina'), (17662,'Samaná'), (17665,'San José'), (17777,'Supía'), (17867,'Victoria'), (17873,'Villamaría'), (17877,'Viterbo'), (18001,'Florencia'), (18029,'Albania'), (18094,'Belén De Los Andaquies'), (18150,'Cartagena Del Chairá'), (18205,'Curillo'), (18247,'El Doncello'), (18256,'El Paujil'), (18410,'La Montañita'), (18460,'Milán'), (18479,'Morelia'), (18592,'Puerto Rico'), (18610,'San José Del Fragua'), (18753,'San Vicente Del Caguán'), (18756,'Solano'), (18785,'Solita'), (18860,'Valparaíso'), (19001,'Popayán'), (19022,'Almaguer'), (19050,'Argelia'), (19075,'Balboa'), (19100,'Bolívar'), (19110,'Buenos Aires'), (19130,'Cajibío'), (19137,'Caldono'), (19142,'Caloto'), (19212,'Corinto'), (19256,'El Tambo'), (19290,'Florencia'), (19300,'Guachené'), (19318,'Guapi'), (19355,'Inzá'), (19364,'Jambaló'), (19392,'La Sierra'), (19397,'La Vega'), (19418,'López'), (19450,'Mercaderes'), (19455,'Miranda'), (19473,'Morales'), (19513,'Padilla'), (19517,'Paez'), (19532,'Patía'), (19533,'Piamonte'), (19548,'Piendamó'), (19573,'Puerto Tejada'), (19585,'Puracé'), (19622,'Rosas'), (19693,'San Sebastián'), (19698,'Santander De Quilichao'), (19701,'Santa Rosa'), (19743,'Silvia'), (19760,'Sotara'), (19780,'Suárez'), (19785,'Sucre'), (19807,'Timbío'), (19809,'Timbiquí'), (19821,'Toribio'), (19824,'Totoró'), (19845,'Villa Rica'), (20001,'Valledupar'), (20011,'Aguachica'), (20013,'Agustín Codazzi'), (20032,'Astrea'), (20045,'Becerril'), (20060,'Bosconia'), (20175,'Chimichagua'), (20178,'Chiriguaná'), (20228,'Curumaní'), (20238,'El Copey'), (20250,'El Paso'), (20295,'Gamarra'), (20310,'González'), (20383,'La Gloria'), (20400,'La Jagua De Ibirico'), (20443,'Manaure'), (20517,'Pailitas'), (20550,'Pelaya'), (20570,'Pueblo Bello'), (20614,'Río De Oro'), (20621,'La Paz'), (20710,'San Alberto'), (20750,'San Diego'), (20770,'San Martín'), (20787,'Tamalameque'), (23001,'Montería'), (23068,'Ayapel'), (23079,'Buenavista'), (23090,'Canalete'), (23162,'Cereté'), (23168,'Chimá'), (23182,'Chinú'), (23189,'Ciénaga De Oro'), (23300,'Cotorra'), (23350,'La Apartada'), (23417,'Lorica'), (23419,'Los Córdobas'), (23464,'Momil'), (23466,'Montelíbano'), (23500,'Moñitos'), (23555,'Planeta Rica'), (23570,'Pueblo Nuevo'), (23574,'Puerto Escondido'), (23580,'Puerto Libertador'), (23586,'Purísima'), (23660,'Sahagún'), (23670,'San Andrés Sotavento'), (23672,'San Antero'), (23675,'San Bernardo Del Viento'), (23678,'San Carlos'), (23686,'San Pelayo'), (23807,'Tierralta'), (23855,'Valencia'), (25001,'Agua De Dios'), (25019,'Albán'), (25035,'Anapoima'), (25040,'Anolaima'), (25053,'Arbeláez'), (25086,'Beltrán'), (25095,'Bituima'), (25099,'Bojacá'), (25120,'Cabrera'), (25123,'Cachipay'), (25126,'Cajicá'), (25148,'Caparrapí'), (25151,'Caqueza'), (25154,'Carmen De Carupa'), (25168,'Chaguaní'), (25175,'Chía'), (25178,'Chipaque'), (25181,'Choachí'), (25183,'Chocontá'), (25200,'Cogua'), (25214,'Cota'), (25224,'Cucunuba'), (25245,'El Colegio'), (25258,'El Peñón'), (25260,'El Rosal'), (25269,'Facatativá'), (25279,'Fomeque'), (25281,'Fosca'), (25286,'Funza'), (25288,'Fúquene'), (25290,'Fusagasugá'), (25293,'Gachala'), (25295,'Gachancipá'), (25297,'Gachetá'), (25299,'Gama'), (25307,'Girardot'), (25312,'Granada'), (25317,'Guachetá'), (25320,'Guaduas'), (25322,'Guasca'), (25324,'Guataquí'), (25326,'Guatavita'), (25328,'Guayabal De Siquima'), (25335,'Guayabetal'), (25339,'Gutiérrez'), (25368,'Jerusalén'), (25372,'Junín'), (25377,'La Calera'), (25386,'La Mesa'), (25394,'La Palma'), (25398,'La Peña'), (25402,'La Vega'), (25407,'Lenguazaque'), (25426,'Macheta'), (25430,'Madrid'), (25436,'Manta'), (25438,'Medina'), (25473,'Mosquera'), (25483,'Nariño'), (25486,'Nemocón'), (25488,'Nilo'), (25489,'Nimaima'), (25491,'Nocaima'), (25506,'Venecia'), (25513,'Pacho'), (25518,'Paime'), (25524,'Pandi'), (25530,'Paratebueno'), (25535,'Pasca'), (25572,'Puerto Salgar'), (25580,'Pulí'), (25592,'Quebradanegra'), (25594,'Quetame'), (25596,'Quipile'), (25599,'Apulo'), (25612,'Ricaurte'), (25645,'San Antonio Del Tequendama'), (25649,'San Bernardo'), (25653,'San Cayetano'), (25658,'San Francisco'), (25662,'San Juan De Río Seco'), (25718,'Sasaima'), (25736,'Sesquilé'), (25740,'Sibaté'), (25743,'Silvania'), (25745,'Simijaca'), (25754,'Soacha'), (25758,'Sopó'), (25769,'Subachoque'), (25772,'Suesca'), (25777,'Supatá'), (25779,'Susa'), (25781,'Sutatausa'), (25785,'Tabio'), (25793,'Tausa'), (25797,'Tena'), (25799,'Tenjo'), (25805,'Tibacuy'), (25807,'Tibirita'), (25815,'Tocaima'), (25817,'Tocancipá'), (25823,'Topaipi'), (25839,'Ubalá'), (25841,'Ubaque'), (25843,'Villa De San Diego De Ubate'), (25845,'Une'), (25851,'Útica'), (25862,'Vergara'), (25867,'Vianí'), (25871,'Villagómez'), (25873,'Villapinzón'), (25875,'Villeta'), (25878,'Viotá'), (25885,'Yacopí'), (25898,'Zipacón'), (25899,'Zipaquirá'), (27001,'Quibdó'), (27006,'Acandí'), (27025,'Alto Baudo'), (27050,'Atrato'), (27073,'Bagadó'), (27075,'Bahía Solano'), (27077,'Bajo Baudó'), (27086,'Belén De Bajirá'), (27099,'Bojaya'), (27135,'El Cantón Del San Pablo'), (27150,'Carmen Del Darien'), (27160,'Cértegui'), (27205,'Condoto'), (27245,'El Carmen De Atrato'), (27250,'El Litoral Del San Juan'), (27361,'Istmina'), (27372,'Juradó'), (27413,'Lloró'), (27425,'Medio Atrato'), (27430,'Medio Baudó'), (27450,'Medio San Juan'), (27491,'Nóvita'), (27495,'Nuquí'), (27580,'Río Iro'), (27600,'Río Quito'), (27615,'Riosucio'), (27660,'San José Del Palmar'), (27745,'Sipí'), (27787,'Tadó'), (27800,'Unguía'), (27810,'Unión Panamericana'), (41001,'Neiva'), (41006,'Acevedo'), (41013,'Agrado'), (41016,'Aipe'), (41020,'Algeciras'), (41026,'Altamira'), (41078,'Baraya'), (41132,'Campoalegre'), (41206,'Colombia'), (41244,'Elías'), (41298,'Garzón'), (41306,'Gigante'), (41319,'Guadalupe'), (41349,'Hobo'), (41357,'Iquira'), (41359,'Isnos'), (41378,'La Argentina'), (41396,'La Plata'), (41483,'Nátaga'), (41503,'Oporapa'), (41518,'Paicol'), (41524,'Palermo'), (41530,'Palestina'), (41548,'Pital'), (41551,'Pitalito'), (41615,'Rivera'), (41660,'Saladoblanco'), (41668,'San Agustín'), (41676,'Santa María'), (41770,'Suaza'), (41791,'Tarqui'), (41797,'Tesalia'), (41799,'Tello'), (41801,'Teruel'), (41807,'Timana'), (41872,'Villavieja'), (41885,'Yaguará'), (44001,'Riohacha'), (44035,'Albania'), (44078,'Barrancas'), (44090,'Dibulla'), (44098,'Distracción'), (44110,'El Molino'), (44279,'Fonseca'), (44378,'Hatonuevo'), (44420,'La Jagua Del Pilar'), (44430,'Maicao'), (44560,'Manaure'), (44650,'San Juan Del Cesar'), (44847,'Uribia'), (44855,'Urumita'), (44874,'Villanueva'), (47001,'Santa Marta'), (47030,'Algarrobo'), (47053,'Aracataca'), (47058,'Ariguaní'), (47161,'Cerro San Antonio'), (47170,'Chibolo'), (47189,'Ciénaga'), (47205,'Concordia'), (47245,'El Banco'), (47258,'El Piñon'), (47268,'El Retén'), (47288,'Fundación'), (47318,'Guamal'), (47460,'Nueva Granada'), (47541,'Pedraza'), (47545,'Pijiño Del Carmen'), (47551,'Pivijay'), (47555,'Plato'), (47570,'Puebloviejo'), (47605,'Remolino'), (47660,'Sabanas De San Angel'), (47675,'Salamina'), (47692,'San Sebastián De Buenavista'), (47703,'San Zenón'), (47707,'Santa Ana'), (47720,'Santa Bárbara De Pinto'), (47745,'Sitionuevo'), (47798,'Tenerife'), (47960,'Zapayán'), (47980,'Zona Bananera'), (50001,'Villavicencio'), (50006,'Acacías'), (50110,'Barranca De Upía'), (50124,'Cabuyaro'), (50150,'Castilla La Nueva'), (50223,'Cubarral'), (50226,'Cumaral'), (50245,'El Calvario'), (50251,'El Castillo'), (50270,'El Dorado'), (50287,'Fuente De Oro'), (50313,'Granada'), (50318,'Guamal'), (50325,'Mapiripán'), (50330,'Mesetas'), (50350,'La Macarena'), (50370,'Uribe'), (50400,'Lejanías'), (50450,'Puerto Concordia'), (50568,'Puerto Gaitán'), (50573,'Puerto López'), (50577,'Puerto Lleras'), (50590,'Puerto Rico'), (50606,'Restrepo'), (50680,'San Carlos De Guaroa'), (50683,'San Juan De Arama'), (50686,'San Juanito'), (50689,'San Martín'), (50711,'Vistahermosa'), (52001,'Pasto'), (52019,'Albán'), (52022,'Aldana'), (52036,'Ancuya'), (52051,'Arboleda'), (52079,'Barbacoas'), (52083,'Belén'), (52110,'Buesaco'), (52203,'Colón'), (52207,'Consaca'), (52210,'Contadero'), (52215,'Córdoba'), (52224,'Cuaspud'), (52227,'Cumbal'), (52233,'Cumbitara'), (52240,'Chachagüí'), (52250,'El Charco'), (52254,'El Peñol'), (52256,'El Rosario'), (52258,'El Tablón De Gómez'), (52260,'El Tambo'), (52287,'Funes'), (52317,'Guachucal'), (52320,'Guaitarilla'), (52323,'Gualmatán'), (52352,'Iles'), (52354,'Imués'), (52356,'Ipiales'), (52378,'La Cruz'), (52381,'La Florida'), (52385,'La Llanada'), (52390,'La Tola'), (52399,'La Unión'), (52405,'Leiva'), (52411,'Linares'), (52418,'Los Andes'), (52427,'Magüi'), (52435,'Mallama'), (52473,'Mosquera'), (52480,'Nariño'), (52490,'Olaya Herrera'), (52506,'Ospina'), (52520,'Francisco Pizarro'), (52540,'Policarpa'), (52560,'Potosí'), (52565,'Providencia'), (52573,'Puerres'), (52585,'Pupiales'), (52612,'Ricaurte'), (52621,'Roberto Payán'), (52678,'Samaniego'), (52683,'Sandoná'), (52685,'San Bernardo'), (52687,'San Lorenzo'), (52693,'San Pablo'), (52694,'San Pedro De Cartago'), (52696,'Santa Bárbara'), (52699,'Santacruz'), (52720,'Sapuyes'), (52786,'Taminango'), (52788,'Tangua'), (52835,'San Andres De Tumaco'), (52838,'Túquerres'), (52885,'Yacuanquer'), (54001,'Cúcuta'), (54003,'Abrego'), (54051,'Arboledas'), (54099,'Bochalema'), (54109,'Bucarasica'), (54125,'Cácota'), (54128,'Cachirá'), (54172,'Chinácota'), (54174,'Chitagá'), (54206,'Convención'), (54223,'Cucutilla'), (54239,'Durania'), (54245,'El Carmen'), (54250,'El Tarra'), (54261,'El Zulia'), (54313,'Gramalote'), (54344,'Hacarí'), (54347,'Herrán'), (54377,'Labateca'), (54385,'La Esperanza'), (54398,'La Playa'), (54405,'Los Patios'), (54418,'Lourdes'), (54480,'Mutiscua'), (54498,'Ocaña'), (54518,'Pamplona'), (54520,'Pamplonita'), (54553,'Puerto Santander'), (54599,'Ragonvalia'), (54660,'Salazar'), (54670,'San Calixto'), (54673,'San Cayetano'), (54680,'Santiago'), (54720,'Sardinata'), (54743,'Silos'), (54800,'Teorama'), (54810,'Tibú'), (54820,'Toledo'), (54871,'Villa Caro'), (54874,'Villa Del Rosario'), (63001,'Armenia'), (63111,'Buenavista'), (63130,'Calarca'), (63190,'Circasia'), (63212,'Córdoba'), (63272,'Filandia'), (63302,'Génova'), (63401,'La Tebaida'), (63470,'Montenegro'), (63548,'Pijao'), (63594,'Quimbaya'), (63690,'Salento'), (66001,'Pereira'), (66045,'Apía'), (66075,'Balboa'), (66088,'Belén De Umbría'), (66170,'Dosquebradas'), (66318,'Guática'), (66383,'La Celia'), (66400,'La Virginia'), (66440,'Marsella'), (66456,'Mistrató'), (66572,'Pueblo Rico'), (66594,'Quinchía'), (66682,'Santa Rosa De Cabal'), (66687,'Santuario'), (68001,'Bucaramanga'), (68013,'Aguada'), (68020,'Albania'), (68051,'Aratoca'), (68077,'Barbosa'), (68079,'Barichara'), (68081,'Barrancabermeja'), (68092,'Betulia'), (68101,'Bolívar'), (68121,'Cabrera'), (68132,'California'), (68147,'Capitanejo'), (68152,'Carcasí'), (68160,'Cepitá'), (68162,'Cerrito'), (68167,'Charalá'), (68169,'Charta'), (68176,'Chima'), (68179,'Chipatá'), (68190,'Cimitarra'), (68207,'Concepción'), (68209,'Confines'), (68211,'Contratación'), (68217,'Coromoro'), (68229,'Curití'), (68235,'El Carmen De Chucurí'), (68245,'El Guacamayo'), (68250,'El Peñón'), (68255,'El Playón'), (68264,'Encino'), (68266,'Enciso'), (68271,'Florián'), (68276,'Floridablanca'), (68296,'Galan'), (68298,'Gambita'), (68307,'Girón'), (68318,'Guaca'), (68320,'Guadalupe'), (68322,'Guapotá'), (68324,'Guavatá'), (68327,'Güepsa'), (68344,'Hato'), (68368,'Jesús María'), (68370,'Jordán'), (68377,'La Belleza'), (68385,'Landázuri'), (68397,'La Paz'), (68406,'Lebríja'), (68418,'Los Santos'), (68425,'Macaravita'), (68432,'Málaga'), (68444,'Matanza'), (68464,'Mogotes'), (68468,'Molagavita'), (68498,'Ocamonte'), (68500,'Oiba'), (68502,'Onzaga'), (68522,'Palmar'), (68524,'Palmas Del Socorro'), (68533,'Páramo'), (68547,'Piedecuesta'), (68549,'Pinchote'), (68572,'Puente Nacional'), (68573,'Puerto Parra'), (68575,'Puerto Wilches'), (68615,'Rionegro'), (68655,'Sabana De Torres'), (68669,'San Andrés'), (68673,'San Benito'), (68679,'San Gil'), (68682,'San Joaquín'), (68684,'San José De Miranda'), (68686,'San Miguel'), (68689,'San Vicente De Chucurí'), (68705,'Santa Bárbara'), (68720,'Santa Helena Del Opón'), (68745,'Simacota'), (68755,'Socorro'), (68770,'Suaita'), (68773,'Sucre'), (68780,'Suratá'), (68820,'Tona'), (68855,'Valle De San José'), (68861,'Vélez'), (68867,'Vetas'), (68872,'Villanueva'), (68895,'Zapatoca'), (70001,'Sincelejo'), (70110,'Buenavista'), (70124,'Caimito'), (70204,'Coloso'), (70215,'Corozal'), (70221,'Coveñas'), (70230,'Chalán'), (70233,'El Roble'), (70235,'Galeras'), (70265,'Guaranda'), (70400,'La Unión'), (70418,'Los Palmitos'), (70429,'Majagual'), (70473,'Morroa'), (70508,'Ovejas'), (70523,'Palmito'), (70670,'Sampués'), (70678,'San Benito Abad'), (70702,'San Juan De Betulia'), (70708,'San Marcos'), (70713,'San Onofre'), (70717,'San Pedro'), (70742,'San Luis De Sincé'), (70771,'Sucre'), (70820,'Santiago De Tolú'), (70823,'Tolú Viejo'), (73001,'Ibague'), (73024,'Alpujarra'), (73026,'Alvarado'), (73030,'Ambalema'), (73043,'Anzoátegui'), (73055,'Armero'), (73067,'Ataco'), (73124,'Cajamarca'), (73148,'Carmen De Apicalá'), (73152,'Casabianca'), (73168,'Chaparral'), (73200,'Coello'), (73217,'Coyaima'), (73226,'Cunday'), (73236,'Dolores'), (73268,'Espinal'), (73270,'Falan'), (73275,'Flandes'), (73283,'Fresno'), (73319,'Guamo'), (73347,'Herveo'), (73349,'Honda'), (73352,'Icononzo'), (73408,'Lérida'), (73411,'Líbano'), (73443,'Mariquita'), (73449,'Melgar'), (73461,'Murillo'), (73483,'Natagaima'), (73504,'Ortega'), (73520,'Palocabildo'), (73547,'Piedras'), (73555,'Planadas'), (73563,'Prado'), (73585,'Purificación'), (73616,'Rioblanco'), (73622,'Roncesvalles'), (73624,'Rovira'), (73671,'Saldaña'), (73675,'San Antonio'), (73678,'San Luis'), (73686,'Santa Isabel'), (73770,'Suárez'), (73854,'Valle De San Juan'), (73861,'Venadillo'), (73870,'Villahermosa'), (73873,'Villarrica'), (76001,'Cali'), (76020,'Alcalá'), (76036,'Andalucía'), (76041,'Ansermanuevo'), (76054,'Argelia'), (76100,'Bolívar'), (76109,'Buenaventura'), (76111,'Guadalajara De Buga'), (76113,'Bugalagrande'), (76122,'Caicedonia'), (76126,'Calima'), (76130,'Candelaria'), (76147,'Cartago'), (76233,'Dagua'), (76243,'El Águila'), (76246,'El Cairo'), (76248,'El Cerrito'), (76250,'El Dovio'), (76275,'Florida'), (76306,'Ginebra'), (76318,'Guacarí'), (76364,'Jamundí'), (76377,'La Cumbre'), (76400,'La Unión'), (76403,'La Victoria'), (76497,'Obando'), (76520,'Palmira'), (76563,'Pradera'), (76606,'Restrepo'), (76616,'Riofrío'), (76622,'Roldanillo'), (76670,'San Pedro'), (76736,'Sevilla'), (76823,'Toro'), (76828,'Trujillo'), (76834,'Tuluá'), (76845,'Ulloa'), (76863,'Versalles'), (76869,'Vijes'), (76890,'Yotoco'), (76892,'Yumbo'), (76895,'Zarzal'), (81001,'Arauca'), (81065,'Arauquita'), (81220,'Cravo Norte'), (81300,'Fortul'), (81591,'Puerto Rondón'), (81736,'Saravena'), (81794,'Tame'), (85001,'Yopal'), (85010,'Aguazul'), (85015,'Chameza'), (85125,'Hato Corozal'), (85136,'La Salina'), (85139,'Maní'), (85162,'Monterrey'), (85225,'Nunchía'), (85230,'Orocué'), (85250,'Paz De Ariporo'), (85263,'Pore'), (85279,'Recetor'), (85300,'Sabanalarga'), (85315,'Sácama'), (85325,'San Luis De Palenque'), (85400,'Támara'), (85410,'Tauramena'), (85430,'Trinidad'), (85440,'Villanueva'), (86001,'Mocoa'), (86219,'Colón'), (86320,'Orito'), (86568,'Puerto Asís'), (86569,'Puerto Caicedo'), (86571,'Puerto Guzmán'), (86573,'Leguízamo'), (86749,'Sibundoy'), (86755,'San Francisco'), (86757,'San Miguel'), (86760,'Santiago'), (86865,'Valle Del Guamuez'), (86885,'Villagarzón'), (88001,'San Andrés'), (88564,'Providencia'), (91001,'Leticia'), (91263,'El Encanto'), (91405,'La Chorrera'), (91407,'La Pedrera'), (91430,'La Victoria'), (91460,'Miriti - Paraná'), (91530,'Puerto Alegría'), (91536,'Puerto Arica'), (91540,'Puerto Nariño'), (91669,'Puerto Santander'), (91798,'Tarapacá'), (94001,'Inírida'), (94343,'Barranco Minas'), (94663,'Mapiripana'), (94883,'San Felipe'), (94884,'Puerto Colombia'), (94885,'La Guadalupe'), (94886,'Cacahual'), (94887,'Pana Pana'), (94888,'Morichal'), (95001,'San José Del Guaviare'), (95015,'Calamar'), (95025,'El Retorno'), (95200,'Miraflores'), (97001,'Mitú'), (97161,'Caruru'), (97511,'Pacoa'), (97666,'Taraira'), (97777,'Papunaua'), (97889,'Yavaraté'), (99001,'Puerto Carreño'), (99524,'La Primavera'), (99624,'Santa Rosalía'), (99773,'Cumaribo') ], validators=[ Required() ]) primerNombreEmpleado = StringField('Primer Nombre', validators=[ Required(message='El campo es obligatorio'), Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) segundoNombreEmpleado = StringField('Segundo Nombre', validators=[ Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) primerApellidoEmpleado = StringField('Primer Apellido', validators=[ Required(message='El campo es obligatorio'), Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) segundoApellidoEmpleado = StringField('Segundo Apellido', validators=[ Length(max=12, min=3, message='El campo debe tener entre 3 y 12 caracteres') ]) fechaNacimientoEmpleado = DateField('Fecha de Nacimiento', format='%Y,%M,%D', validators=[]) direccionEmpleado = StringField('Direccion Residencia', validators=[ Required(message='El campo es obligatorio'), Length(max=50, min=20, message='El campo debe tener entre 20 y 50 caracteres') ]) barrioEmpleado = StringField('Barrio Residencia', validators=[ Required(message='El campo es obligatorio'), Length(max=20, min=10, message='El campo debe tener entre 10 y 20 caracteres') ]) idPais = SelectField('Pais Residencia', choices=[ ('AD','Andorra'), ('AE','Emiratos Arabes Unid'), ('AF','Afganistan'), ('AG','Antigua Y Barbuda'), ('AI','Anguilla'), ('AL','Albania'), ('AM','Armenia'), ('AN','Antillas Holandesas'), ('AO','Angola'), ('AR','Argentina'), ('AS','Samoa Norteamericana'), ('AT','Austria'), ('AU','Australia'), ('AW','Aruba'), ('AZ','Azerbaijan'), ('BA','Bosnia-Herzegovina'), ('BB','Barbados'), ('BD','Bangladesh'), ('BE','Belgica'), ('BF','Burkina Fasso'), ('BG','Bulgaria'), ('BH','Bahrein'), ('BI','Burundi'), ('BJ','Benin'), ('BM','Bermudas'), ('BN','Brunei Darussalam'), ('BO','Bolivia'), ('BR','Brasil'), ('BS','Bahamas'), ('BT','Butan'), ('BW','Botswana'), ('BY','Belorus'), ('BZ','Belice'), ('CA','Canada'), ('CC','Cocos (Keeling) Islas'), ('CD','Republica Democratica Del Congo'), ('CF','Republica Centroafri'), ('CG','Congo'), ('CH','Suiza'), ('CI','Costa De Marfil'), ('CK','Cook Islas'), ('CL','Chile'), ('CM','Camerun Republica U'), ('CN','China'), ('CO','Colombia'), ('CR','Costa Rica'), ('CU','Cuba'), ('CV','Cabo Verde'), ('CX','Navidad (Christmas)'), ('CY','Chipre'), ('CZ','Republica Checa'), ('DE','Alemania'), ('DJ','Djibouti'), ('DK','Dinamarca'), ('DM','Dominica'), ('DO','Republica Dominicana'), ('DZ','Argelia'), ('EC','Ecuador'), ('EE','Estonia'), ('EG','Egipto'), ('EH','Sahara Occidental'), ('ER','Eritrea'), ('ES','España'), ('ET','Etiopia'), ('EU','Comunidad Europea'), ('FI','Finlandia'), ('FJ','Fiji'), ('FM','Micronesia Estados F'), ('FO','Feroe Islas'), ('FR','Francia'), ('GA','Gabon'), ('GB','Reino Unido'), ('GD','Granada'), ('GE','Georgia'), ('GF','Guayana Francesa'), ('GH','Ghana'), ('GI','Gibraltar'), ('GL','Groenlandia'), ('GM','Gambia'), ('GN','Guinea'), ('GP','Guadalupe'), ('GQ','Guinea Ecuatorial'), ('GR','Grecia'), ('GT','Guatemala'), ('GU','Guam'), ('GW','Guinea - Bissau'), ('GY','Guyana'), ('HK','Hong Kong'), ('HN','Honduras'), ('HR','Croacia'), ('HT','Haiti'), ('HU','Hungria'), ('ID','Indonesia'), ('IE','Irlanda (Eire)'), ('IL','Israel'), ('IM','Isla De Man'), ('IN','India'), ('IO','Territori Britanico'), ('IQ','Irak'), ('IR','Iran Republica Islamica'), ('IS','Islandia'), ('IT','Italia'), ('JM','Jamaica'), ('JO','Jordania'), ('JP','Japon'), ('KE','Kenya'), ('KG','Kirguizistan'), ('KH','Kampuchea (Camboya)'), ('KI','Kiribati'), ('KM','Comoras'), ('KN','San Cristobal Y Nieves'), ('KP','Corea Del Norte Republica'), ('KR','Corea Del Sur Republica'), ('KW','Kuwait'), ('KY','Caiman Islas'), ('KZ','Kazajstan'), ('LA','Laos Republica Popular'), ('LB','Libano'), ('LC','Santa Lucia'), ('LI','Liechtenstein'), ('LK','Sri Lanka'), ('LR','Liberia'), ('LS','Lesotho'), ('LT','Lituania'), ('LU','Luxemburgo'), ('LV','Letonia'), ('LY','Libia(Incluye Fezzan'), ('MA','Marruecos'), ('MC','Monaco'), ('MD','Moldavia'), ('MG','Madagascar'), ('MH','Marshall Islas'), ('MK','Macedonia'), ('ML','Mali'), ('MM','Birmania (Myanmar)'), ('MN','Mongolia'), ('MO','Macao'), ('MP','Marianas Del Norte Islas'), ('MQ','Martinica'), ('MR','Mauritania'), ('MS','Monserrat Islas'), ('MT','Malta'), ('MU','Mauricio'), ('MV','Maldivas'), ('MW','Malawi'), ('MX','Mexico'), ('MY','Malasia'), ('MZ','Mozambique'), ('NA','Namibia'), ('NC','Nueva Caledonia'), ('NE','Niger'), ('NF','Norfolk Isla'), ('NG','Nigeria'), ('NI','Nicaragua'), ('NL','Paises Bajos(Holanda'), ('NO','Noruega'), ('NP','Nepal'), ('NR','Nauru'), ('NU','Nive Isla'), ('NZ','Nueva Zelandia'), ('OM','Oman'), ('PA','Panama'), ('PE','Peru'), ('PF','Polinesia Francesa'), ('PG','Papuasia Nuev Guinea'), ('PH','Filipinas'), ('PK','Pakistan'), ('PL','Polonia'), ('PM','San Pedro Y Miguelon'), ('PN','Pitcairn Isla'), ('PR','Puerto Rico'), ('PS','Palestina'), ('PT','Portugal'), ('PW','Palau Islas'), ('PY','Paraguay'), ('QA','Qatar'), ('RE','Reunion'), ('RO','Rumania'), ('RS','Serbia'), ('RU','Rusia'), ('RW','Rwanda'), ('SA','Arabia Saudita'), ('SB','Salomsn Islas'), ('SC','Seychelles'), ('SD','Sudan'), ('SE','Suecia'), ('SG','Singapur'), ('SH','Santa Elena'), ('SI','Eslovenia'), ('SK','Eslovaquia'), ('SL','Sierra Leona'), ('SM','San Marino'), ('SN','Senegal'), ('SO','Somalia'), ('SR','Surinam'), ('ST','Santo Tome Y Princip'), ('SV','El Salvador'), ('SY','Siria Republica Arabe'), ('SZ','Swazilandia'), ('TC','Turcas Y Caicos Isla'), ('TD','Chad'), ('TG','Togo'), ('TH','Tailandia'), ('TJ','Tadjikistan'), ('TK','Tokelau'), ('TL','Timor Del Este'), ('TM','Turkmenistan'), ('TN','Tunicia'), ('TO','Tonga'), ('TR','Turquia'), ('TT','Trinidad Y Tobago'), ('TV','Tuvalu'), ('TW','Taiwan (Formosa)'), ('TZ','Tanzania Republica'), ('UA','Ucrania'), ('UG','Uganda'), ('UM','Islas Menores De Estados Unidos'), ('UN','Niue Isla'), ('US','Estados Unidos'), ('UY','Uruguay'), ('UZ','Uzbekistan'), ('VA','Ciudad Del Vaticano'), ('VC','San Vicente Y Las Gr'), ('VE','Venezuela'), ('VG','Virgenes Islas Britanicas'), ('VI','Virgenes Islas'), ('VN','Vietnam'), ('VU','Vanuatu'), ('WF','Wallis Y Fortuna Islas'), ('WS','Samoa'), ('YE','Yemen'), ('YU','Yugoslavia'), ('ZA','Sudafrica Republica'), ('ZM','Zambia'), ('ZW','Zimbabwe') ], validate_choice=True) idDepartamento = SelectField('Departamento Residencia', choices=[ (5,'Antioquia'), (8,'Atlántico'), (11,'Bogotá DC'), (13,'Bolívar'), (15,'Boyacá'), (17,'Caldas'), (18,'Caquetá'), (19,'Cauca'), (20,'Cesar'), (23,'Córdoba'), (25,'Cundinamarca'), (27,'Chocó'), (41,'Huila'), (44,'La Guajira'), (47,'Magdalena'), (50,'Meta'), (52,'Nariño'), (54,'Norte de Santander'), (63,'Quindío'), (66,'Risaralda'), (68,'Santander'), (70,'Sucre'), (73,'Tolima'), (76,'Valle del Cauca'), (81,'Arauca'), (85,'Casanare'), (86,'Putumayo'), (88,'San Andres'), (91,'Amazonas'), (94,'Guainía'), (95,'Guaviare'), (97,'Vaupés'), (99,'Vichada'), ], validate_choice=True) idMunicipio = SelectField('Municipio Residencia', choices=[ (5001,'Medellín'), (5002,'Abejorral'), (5004,'Abriaquí'), (5021,'Alejandría'), (5030,'Amagá'), (5031,'Amalfi'), (5034,'Andes'), (5036,'Angelópolis'), (5038,'Angostura'), (5040,'Anorí'), (5042,'Santafé De Antioquia'), (5044,'Anza'), (5045,'Apartadó'), (5051,'Arboletes'), (5055,'Argelia'), (5059,'Armenia'), (5079,'Barbosa'), (5086,'Belmira'), (5088,'Bello'), (5091,'Betania'), (5093,'Betulia'), (5101,'Ciudad Bolívar'), (5107,'Briceño'), (5113,'Buriticá'), (5120,'Cáceres'), (5125,'Caicedo'), (5129,'Caldas'), (5134,'Campamento'), (5138,'Cañasgordas'), (5142,'Caracolí'), (5145,'Caramanta'), (5147,'Carepa'), (5148,'El Carmen De Viboral'), (5150,'Carolina'), (5154,'Caucasia'), (5172,'Chigorodó'), (5190,'Cisneros'), (5197,'Cocorná'), (5206,'Concepción'), (5209,'Concordia'), (5212,'Copacabana'), (5234,'Dabeiba'), (5237,'Don Matías'), (5240,'Ebéjico'), (5250,'El Bagre'), (5264,'Entrerrios'), (5266,'Envigado'), (5282,'Fredonia'), (5284,'Frontino'), (5306,'Giraldo'), (5308,'Girardota'), (5310,'Gómez Plata'), (5313,'Granada'), (5315,'Guadalupe'), (5318,'Guarne'), (5321,'Guatape'), (5347,'Heliconia'), (5353,'Hispania'), (5360,'Itagui'), (5361,'Ituango'), (5364,'Jardín'), (5368,'Jericó'), (5376,'La Ceja'), (5380,'La Estrella'), (5390,'La Pintada'), (5400,'La Unión'), (5411,'Liborina'), (5425,'Maceo'), (5440,'Marinilla'), (5467,'Montebello'), (5475,'Murindó'), (5480,'Mutatá'), (5483,'Nariño'), (5490,'Necoclí'), (5495,'Nechí'), (5501,'Olaya'), (5541,'Peñol'), (5543,'Peque'), (5576,'Pueblorrico'), (5579,'Puerto Berrío'), (5585,'Puerto Nare'), (5591,'Puerto Triunfo'), (5604,'Remedios'), (5607,'Retiro'), (5615,'Rionegro'), (5628,'Sabanalarga'), (5631,'Sabaneta'), (5642,'Salgar'), (5647,'San Andrés De Cuerquía'), (5649,'San Carlos'), (5652,'San Francisco'), (5656,'San Jerónimo'), (5658,'San José De La Montaña'), (5659,'San Juan De Urabá'), (5660,'San Luis'), (5664,'San Pedro'), (5665,'San Pedro De Uraba'), (5667,'San Rafael'), (5670,'San Roque'), (5674,'San Vicente'), (5679,'Santa Bárbara'), (5686,'Santa Rosa De Osos'), (5690,'Santo Domingo'), (5697,'El Santuario'), (5736,'Segovia'), (5756,'Sonson'), (5761,'Sopetrán'), (5789,'Támesis'), (5790,'Tarazá'), (5792,'Tarso'), (5809,'Titiribí'), (5819,'Toledo'), (5837,'Turbo'), (5842,'Uramita'), (5847,'Urrao'), (5854,'Valdivia'), (5856,'Valparaíso'), (5858,'Vegachí'), (5861,'Venecia'), (5873,'Vigía Del Fuerte'), (5885,'Yalí'), (5887,'Yarumal'), (5890,'Yolombó'), (5893,'Yondó'), (5895,'Zaragoza'), (8001,'Barranquilla'), (8078,'Baranoa'), (8137,'Campo De La Cruz'), (8141,'Candelaria'), (8296,'Galapa'), (8372,'Juan De Acosta'), (8421,'Luruaco'), (8433,'Malambo'), (8436,'Manatí'), (8520,'Palmar De Varela'), (8549,'Piojó'), (8558,'Polonuevo'), (8560,'Ponedera'), (8573,'Puerto Colombia'), (8606,'Repelón'), (8634,'Sabanagrande'), (8638,'Sabanalarga'), (8675,'Santa Lucía'), (8685,'Santo Tomás'), (8758,'Soledad'), (8770,'Suan'), (8832,'Tubará'), (8849,'Usiacurí'), (11001,'Bogota DC'), (13001,'Cartagena'), (13006,'Choachí'), (13030,'Altos Del Rosario'), (13042,'Arenal'), (13052,'Arjona'), (13062,'Arroyohondo'), (13074,'Barranco De Loba'), (13140,'Calamar'), (13160,'Cantagallo'), (13188,'Cicuco'), (13212,'Córdoba'), (13222,'Clemencia'), (13244,'El Carmen De Bolívar'), (13248,'El Guamo'), (13268,'El Peñón'), (13300,'Hatillo De Loba'), (13430,'Magangué'), (13433,'Mahates'), (13440,'Margarita'), (13442,'María La Baja'), (13458,'Montecristo'), (13468,'Mompós'), (13473,'Morales'), (13549,'Pinillos'), (13580,'Regidor'), (13600,'Río Viejo'), (13620,'San Cristóbal'), (13647,'San Estanislao'), (13650,'San Fernando'), (13654,'San Jacinto'), (13655,'San Jacinto Del Cauca'), (13657,'San Juan Nepomuceno'), (13667,'San Martín De Loba'), (13670,'San Pablo'), (13673,'Santa Catalina'), (13683,'Santa Rosa'), (13688,'Santa Rosa Del Sur'), (13744,'Simití'), (13760,'Soplaviento'), (13780,'Talaigua Nuevo'), (13810,'Tiquisio'), (13836,'Turbaco'), (13838,'Turbaná'), (13873,'Villanueva'), (13894,'Zambrano'), (15001,'Tunja'), (15022,'Almeida'), (15047,'Aquitania'), (15051,'Arcabuco'), (15087,'Belén'), (15090,'Berbeo'), (15092,'Betéitiva'), (15097,'Boavita'), (15104,'Boyacá'), (15106,'Briceño'), (15109,'Buenavista'), (15114,'Busbanzá'), (15131,'Caldas'), (15135,'Campohermoso'), (15162,'Cerinza'), (15172,'Chinavita'), (15176,'Chiquinquirá'), (15180,'Chiscas'), (15183,'Chita'), (15185,'Chitaraque'), (15187,'Chivatá'), (15189,'Ciénega'), (15204,'Cómbita'), (15212,'Coper'), (15215,'Corrales'), (15218,'Covarachía'), (15223,'Cubará'), (15224,'Cucaita'), (15226,'Cuítiva'), (15232,'Chíquiza'), (15236,'Chivor'), (15238,'Duitama'), (15244,'El Cocuy'), (15248,'El6Aspino'), (15272,'Firavitoba'), (15276,'Floresta'), (15293,'Gachantivá'), (15296,'Gameza'), (15299,'Garagoa'), (15317,'Guacamayas'), (15322,'Guateque'), (15325,'Guayatá'), (15332,'Guican'), (15362,'Iza'), (15367,'Jenesano'), (15368,'Jericó'), (15377,'Labranzagrande'), (15380,'La Capilla'), (15401,'La Victoria'), (15403,'La Uvita'), (15407,'Villa De Leyva'), (15425,'Macanal'), (15442,'Maripí'), (15455,'Miraflores'), (15464,'Mongua'), (15466,'Monguí'), (15469,'Moniquirá'), (15476,'Motavita'), (15480,'Muzo'), (15491,'Nobsa'), (15494,'Nuevo Colón'), (15500,'Oicatá'), (15507,'Otanche'), (15511,'Pachavita'), (15514,'Páez'), (15516,'Paipa'), (15518,'Pajarito'), (15522,'Panqueba'), (15531,'Pauna'), (15533,'Paya'), (15537,'Paz De Río'), (15542,'Pesca'), (15550,'Pisba'), (15572,'Puerto Boyacá'), (15580,'Quípama'), (15599,'Ramiriquí'), (15600,'Ráquira'), (15621,'Rondón'), (15632,'Saboyá'), (15638,'Sáchica'), (15646,'Samacá'), (15660,'San Eduardo'), (15664,'San José De Pare'), (15667,'San Luis De Gaceno'), (15673,'San Mateo'), (15676,'San Miguel De Sema'), (15681,'San Pablo De Borbur'), (15686,'Santana'), (15690,'Santa María'), (15693,'Santa Rosa De Viterbo'), (15696,'Santa Sofía'), (15720,'Sativanorte'), (15723,'Sativasur'), (15740,'Siachoque'), (15753,'Soatá'), (15755,'Socotá'), (15757,'Socha'), (15759,'Sogamoso'), (15761,'Somondoco'), (15762,'Sora'), (15763,'Sotaquirá'), (15764,'Soracá'), (15774,'Susacón'), (15776,'Sutamarchán'), (15778,'Sutatenza'), (15790,'Tasco'), (15798,'Tenza'), (15804,'Tibaná'), (15806,'Tibasosa'), (15808,'Tinjacá'), (15810,'Tipacoque'), (15814,'Toca'), (15816,'Togüí'), (15820,'Tópaga'), (15822,'Tota'), (15832,'Tununguá'), (15835,'Turmequé'), (15837,'Tuta'), (15839,'Tutazá'), (15842,'Umbita'), (15861,'Ventaquemada'), (15879,'Viracachá'), (15897,'Zetaquira'), (17001,'Manizales'), (17013,'Aguadas'), (17042,'Anserma'), (17050,'Aranzazu'), (17088,'Belalcázar'), (17174,'Chinchiná'), (17272,'Filadelfia'), (17380,'La Dorada'), (17388,'La Merced'), (17433,'Manzanares'), (17442,'Marmato'), (17444,'Marquetalia'), (17446,'Marulanda'), (17486,'Neira'), (17495,'Norcasia'), (17513,'Pácora'), (17524,'Palestina'), (17541,'Pensilvania'), (17614,'Riosucio'), (17616,'Risaralda'), (17653,'Salamina'), (17662,'Samaná'), (17665,'San José'), (17777,'Supía'), (17867,'Victoria'), (17873,'Villamaría'), (17877,'Viterbo'), (18001,'Florencia'), (18029,'Albania'), (18094,'Belén De Los Andaquies'), (18150,'Cartagena Del Chairá'), (18205,'Curillo'), (18247,'El Doncello'), (18256,'El Paujil'), (18410,'La Montañita'), (18460,'Milán'), (18479,'Morelia'), (18592,'Puerto Rico'), (18610,'San José Del Fragua'), (18753,'San Vicente Del Caguán'), (18756,'Solano'), (18785,'Solita'), (18860,'Valparaíso'), (19001,'Popayán'), (19022,'Almaguer'), (19050,'Argelia'), (19075,'Balboa'), (19100,'Bolívar'), (19110,'Buenos Aires'), (19130,'Cajibío'), (19137,'Caldono'), (19142,'Caloto'), (19212,'Corinto'), (19256,'El Tambo'), (19290,'Florencia'), (19300,'Guachené'), (19318,'Guapi'), (19355,'Inzá'), (19364,'Jambaló'), (19392,'La Sierra'), (19397,'La Vega'), (19418,'López'), (19450,'Mercaderes'), (19455,'Miranda'), (19473,'Morales'), (19513,'Padilla'), (19517,'Paez'), (19532,'Patía'), (19533,'Piamonte'), (19548,'Piendamó'), (19573,'Puerto Tejada'), (19585,'Puracé'), (19622,'Rosas'), (19693,'San Sebastián'), (19698,'Santander De Quilichao'), (19701,'Santa Rosa'), (19743,'Silvia'), (19760,'Sotara'), (19780,'Suárez'), (19785,'Sucre'), (19807,'Timbío'), (19809,'Timbiquí'), (19821,'Toribio'), (19824,'Totoró'), (19845,'Villa Rica'), (20001,'Valledupar'), (20011,'Aguachica'), (20013,'Agustín Codazzi'), (20032,'Astrea'), (20045,'Becerril'), (20060,'Bosconia'), (20175,'Chimichagua'), (20178,'Chiriguaná'), (20228,'Curumaní'), (20238,'El Copey'), (20250,'El Paso'), (20295,'Gamarra'), (20310,'González'), (20383,'La Gloria'), (20400,'La Jagua De Ibirico'), (20443,'Manaure'), (20517,'Pailitas'), (20550,'Pelaya'), (20570,'Pueblo Bello'), (20614,'Río De Oro'), (20621,'La Paz'), (20710,'San Alberto'), (20750,'San Diego'), (20770,'San Martín'), (20787,'Tamalameque'), (23001,'Montería'), (23068,'Ayapel'), (23079,'Buenavista'), (23090,'Canalete'), (23162,'Cereté'), (23168,'Chimá'), (23182,'Chinú'), (23189,'Ciénaga De Oro'), (23300,'Cotorra'), (23350,'La Apartada'), (23417,'Lorica'), (23419,'Los Córdobas'), (23464,'Momil'), (23466,'Montelíbano'), (23500,'Moñitos'), (23555,'Planeta Rica'), (23570,'Pueblo Nuevo'), (23574,'Puerto Escondido'), (23580,'Puerto Libertador'), (23586,'Purísima'), (23660,'Sahagún'), (23670,'San Andrés Sotavento'), (23672,'San Antero'), (23675,'San Bernardo Del Viento'), (23678,'San Carlos'), (23686,'San Pelayo'), (23807,'Tierralta'), (23855,'Valencia'), (25001,'Agua De Dios'), (25019,'Albán'), (25035,'Anapoima'), (25040,'Anolaima'), (25053,'Arbeláez'), (25086,'Beltrán'), (25095,'Bituima'), (25099,'Bojacá'), (25120,'Cabrera'), (25123,'Cachipay'), (25126,'Cajicá'), (25148,'Caparrapí'), (25151,'Caqueza'), (25154,'Carmen De Carupa'), (25168,'Chaguaní'), (25175,'Chía'), (25178,'Chipaque'), (25181,'Choachí'), (25183,'Chocontá'), (25200,'Cogua'), (25214,'Cota'), (25224,'Cucunuba'), (25245,'El Colegio'), (25258,'El Peñón'), (25260,'El Rosal'), (25269,'Facatativá'), (25279,'Fomeque'), (25281,'Fosca'), (25286,'Funza'), (25288,'Fúquene'), (25290,'Fusagasugá'), (25293,'Gachala'), (25295,'Gachancipá'), (25297,'Gachetá'), (25299,'Gama'), (25307,'Girardot'), (25312,'Granada'), (25317,'Guachetá'), (25320,'Guaduas'), (25322,'Guasca'), (25324,'Guataquí'), (25326,'Guatavita'), (25328,'Guayabal De Siquima'), (25335,'Guayabetal'), (25339,'Gutiérrez'), (25368,'Jerusalén'), (25372,'Junín'), (25377,'La Calera'), (25386,'La Mesa'), (25394,'La Palma'), (25398,'La Peña'), (25402,'La Vega'), (25407,'Lenguazaque'), (25426,'Macheta'), (25430,'Madrid'), (25436,'Manta'), (25438,'Medina'), (25473,'Mosquera'), (25483,'Nariño'), (25486,'Nemocón'), (25488,'Nilo'), (25489,'Nimaima'), (25491,'Nocaima'), (25506,'Venecia'), (25513,'Pacho'), (25518,'Paime'), (25524,'Pandi'), (25530,'Paratebueno'), (25535,'Pasca'), (25572,'Puerto Salgar'), (25580,'Pulí'), (25592,'Quebradanegra'), (25594,'Quetame'), (25596,'Quipile'), (25599,'Apulo'), (25612,'Ricaurte'), (25645,'San Antonio Del Tequendama'), (25649,'San Bernardo'), (25653,'San Cayetano'), (25658,'San Francisco'), (25662,'San Juan De Río Seco'), (25718,'Sasaima'), (25736,'Sesquilé'), (25740,'Sibaté'), (25743,'Silvania'), (25745,'Simijaca'), (25754,'Soacha'), (25758,'Sopó'), (25769,'Subachoque'), (25772,'Suesca'), (25777,'Supatá'), (25779,'Susa'), (25781,'Sutatausa'), (25785,'Tabio'), (25793,'Tausa'), (25797,'Tena'), (25799,'Tenjo'), (25805,'Tibacuy'), (25807,'Tibirita'), (25815,'Tocaima'), (25817,'Tocancipá'), (25823,'Topaipi'), (25839,'Ubalá'), (25841,'Ubaque'), (25843,'Villa De San Diego De Ubate'), (25845,'Une'), (25851,'Útica'), (25862,'Vergara'), (25867,'Vianí'), (25871,'Villagómez'), (25873,'Villapinzón'), (25875,'Villeta'), (25878,'Viotá'), (25885,'Yacopí'), (25898,'Zipacón'), (25899,'Zipaquirá'), (27001,'Quibdó'), (27006,'Acandí'), (27025,'Alto Baudo'), (27050,'Atrato'), (27073,'Bagadó'), (27075,'Bahía Solano'), (27077,'Bajo Baudó'), (27086,'Belén De Bajirá'), (27099,'Bojaya'), (27135,'El Cantón Del San Pablo'), (27150,'Carmen Del Darien'), (27160,'Cértegui'), (27205,'Condoto'), (27245,'El Carmen De Atrato'), (27250,'El Litoral Del San Juan'), (27361,'Istmina'), (27372,'Juradó'), (27413,'Lloró'), (27425,'Medio Atrato'), (27430,'Medio Baudó'), (27450,'Medio San Juan'), (27491,'Nóvita'), (27495,'Nuquí'), (27580,'Río Iro'), (27600,'Río Quito'), (27615,'Riosucio'), (27660,'San José Del Palmar'), (27745,'Sipí'), (27787,'Tadó'), (27800,'Unguía'), (27810,'Unión Panamericana'), (41001,'Neiva'), (41006,'Acevedo'), (41013,'Agrado'), (41016,'Aipe'), (41020,'Algeciras'), (41026,'Altamira'), (41078,'Baraya'), (41132,'Campoalegre'), (41206,'Colombia'), (41244,'Elías'), (41298,'Garzón'), (41306,'Gigante'), (41319,'Guadalupe'), (41349,'Hobo'), (41357,'Iquira'), (41359,'Isnos'), (41378,'La Argentina'), (41396,'La Plata'), (41483,'Nátaga'), (41503,'Oporapa'), (41518,'Paicol'), (41524,'Palermo'), (41530,'Palestina'), (41548,'Pital'), (41551,'Pitalito'), (41615,'Rivera'), (41660,'Saladoblanco'), (41668,'San Agustín'), (41676,'Santa María'), (41770,'Suaza'), (41791,'Tarqui'), (41797,'Tesalia'), (41799,'Tello'), (41801,'Teruel'), (41807,'Timana'), (41872,'Villavieja'), (41885,'Yaguará'), (44001,'Riohacha'), (44035,'Albania'), (44078,'Barrancas'), (44090,'Dibulla'), (44098,'Distracción'), (44110,'El Molino'), (44279,'Fonseca'), (44378,'Hatonuevo'), (44420,'La Jagua Del Pilar'), (44430,'Maicao'), (44560,'Manaure'), (44650,'San Juan Del Cesar'), (44847,'Uribia'), (44855,'Urumita'), (44874,'Villanueva'), (47001,'Santa Marta'), (47030,'Algarrobo'), (47053,'Aracataca'), (47058,'Ariguaní'), (47161,'Cerro San Antonio'), (47170,'Chibolo'), (47189,'Ciénaga'), (47205,'Concordia'), (47245,'El Banco'), (47258,'El Piñon'), (47268,'El Retén'), (47288,'Fundación'), (47318,'Guamal'), (47460,'Nueva Granada'), (47541,'Pedraza'), (47545,'Pijiño Del Carmen'), (47551,'Pivijay'), (47555,'Plato'), (47570,'Puebloviejo'), (47605,'Remolino'), (47660,'Sabanas De San Angel'), (47675,'Salamina'), (47692,'San Sebastián De Buenavista'), (47703,'San Zenón'), (47707,'Santa Ana'), (47720,'Santa Bárbara De Pinto'), (47745,'Sitionuevo'), (47798,'Tenerife'), (47960,'Zapayán'), (47980,'Zona Bananera'), (50001,'Villavicencio'), (50006,'Acacías'), (50110,'Barranca De Upía'), (50124,'Cabuyaro'), (50150,'Castilla La Nueva'), (50223,'Cubarral'), (50226,'Cumaral'), (50245,'El Calvario'), (50251,'El Castillo'), (50270,'El Dorado'), (50287,'Fuente De Oro'), (50313,'Granada'), (50318,'Guamal'), (50325,'Mapiripán'), (50330,'Mesetas'), (50350,'La Macarena'), (50370,'Uribe'), (50400,'Lejanías'), (50450,'Puerto Concordia'), (50568,'Puerto Gaitán'), (50573,'Puerto López'), (50577,'Puerto Lleras'), (50590,'Puerto Rico'), (50606,'Restrepo'), (50680,'San Carlos De Guaroa'), (50683,'San Juan De Arama'), (50686,'San Juanito'), (50689,'San Martín'), (50711,'Vistahermosa'), (52001,'Pasto'), (52019,'Albán'), (52022,'Aldana'), (52036,'Ancuya'), (52051,'Arboleda'), (52079,'Barbacoas'), (52083,'Belén'), (52110,'Buesaco'), (52203,'Colón'), (52207,'Consaca'), (52210,'Contadero'), (52215,'Córdoba'), (52224,'Cuaspud'), (52227,'Cumbal'), (52233,'Cumbitara'), (52240,'Chachagüí'), (52250,'El Charco'), (52254,'El Peñol'), (52256,'El Rosario'), (52258,'El Tablón De Gómez'), (52260,'El Tambo'), (52287,'Funes'), (52317,'Guachucal'), (52320,'Guaitarilla'), (52323,'Gualmatán'), (52352,'Iles'), (52354,'Imués'), (52356,'Ipiales'), (52378,'La Cruz'), (52381,'La Florida'), (52385,'La Llanada'), (52390,'La Tola'), (52399,'La Unión'), (52405,'Leiva'), (52411,'Linares'), (52418,'Los Andes'), (52427,'Magüi'), (52435,'Mallama'), (52473,'Mosquera'), (52480,'Nariño'), (52490,'Olaya Herrera'), (52506,'Ospina'), (52520,'Francisco Pizarro'), (52540,'Policarpa'), (52560,'Potosí'), (52565,'Providencia'), (52573,'Puerres'), (52585,'Pupiales'), (52612,'Ricaurte'), (52621,'Roberto Payán'), (52678,'Samaniego'), (52683,'Sandoná'), (52685,'San Bernardo'), (52687,'San Lorenzo'), (52693,'San Pablo'), (52694,'San Pedro De Cartago'), (52696,'Santa Bárbara'), (52699,'Santacruz'), (52720,'Sapuyes'), (52786,'Taminango'), (52788,'Tangua'), (52835,'San Andres De Tumaco'), (52838,'Túquerres'), (52885,'Yacuanquer'), (54001,'Cúcuta'), (54003,'Abrego'), (54051,'Arboledas'), (54099,'Bochalema'), (54109,'Bucarasica'), (54125,'Cácota'), (54128,'Cachirá'), (54172,'Chinácota'), (54174,'Chitagá'), (54206,'Convención'), (54223,'Cucutilla'), (54239,'Durania'), (54245,'El Carmen'), (54250,'El Tarra'), (54261,'El Zulia'), (54313,'Gramalote'), (54344,'Hacarí'), (54347,'Herrán'), (54377,'Labateca'), (54385,'La Esperanza'), (54398,'La Playa'), (54405,'Los Patios'), (54418,'Lourdes'), (54480,'Mutiscua'), (54498,'Ocaña'), (54518,'Pamplona'), (54520,'Pamplonita'), (54553,'Puerto Santander'), (54599,'Ragonvalia'), (54660,'Salazar'), (54670,'San Calixto'), (54673,'San Cayetano'), (54680,'Santiago'), (54720,'Sardinata'), (54743,'Silos'), (54800,'Teorama'), (54810,'Tibú'), (54820,'Toledo'), (54871,'Villa Caro'), (54874,'Villa Del Rosario'), (63001,'Armenia'), (63111,'Buenavista'), (63130,'Calarca'), (63190,'Circasia'), (63212,'Córdoba'), (63272,'Filandia'), (63302,'Génova'), (63401,'La Tebaida'), (63470,'Montenegro'), (63548,'Pijao'), (63594,'Quimbaya'), (63690,'Salento'), (66001,'Pereira'), (66045,'Apía'), (66075,'Balboa'), (66088,'Belén De Umbría'), (66170,'Dosquebradas'), (66318,'Guática'), (66383,'La Celia'), (66400,'La Virginia'), (66440,'Marsella'), (66456,'Mistrató'), (66572,'Pueblo Rico'), (66594,'Quinchía'), (66682,'Santa Rosa De Cabal'), (66687,'Santuario'), (68001,'Bucaramanga'), (68013,'Aguada'), (68020,'Albania'), (68051,'Aratoca'), (68077,'Barbosa'), (68079,'Barichara'), (68081,'Barrancabermeja'), (68092,'Betulia'), (68101,'Bolívar'), (68121,'Cabrera'), (68132,'California'), (68147,'Capitanejo'), (68152,'Carcasí'), (68160,'Cepitá'), (68162,'Cerrito'), (68167,'Charalá'), (68169,'Charta'), (68176,'Chima'), (68179,'Chipatá'), (68190,'Cimitarra'), (68207,'Concepción'), (68209,'Confines'), (68211,'Contratación'), (68217,'Coromoro'), (68229,'Curití'), (68235,'El Carmen De Chucurí'), (68245,'El Guacamayo'), (68250,'El Peñón'), (68255,'El Playón'), (68264,'Encino'), (68266,'Enciso'), (68271,'Florián'), (68276,'Floridablanca'), (68296,'Galan'), (68298,'Gambita'), (68307,'Girón'), (68318,'Guaca'), (68320,'Guadalupe'), (68322,'Guapotá'), (68324,'Guavatá'), (68327,'Güepsa'), (68344,'Hato'), (68368,'Jesús María'), (68370,'Jordán'), (68377,'La Belleza'), (68385,'Landázuri'), (68397,'La Paz'), (68406,'Lebríja'), (68418,'Los Santos'), (68425,'Macaravita'), (68432,'Málaga'), (68444,'Matanza'), (68464,'Mogotes'), (68468,'Molagavita'), (68498,'Ocamonte'), (68500,'Oiba'), (68502,'Onzaga'), (68522,'Palmar'), (68524,'Palmas Del Socorro'), (68533,'Páramo'), (68547,'Piedecuesta'), (68549,'Pinchote'), (68572,'Puente Nacional'), (68573,'Puerto Parra'), (68575,'Puerto Wilches'), (68615,'Rionegro'), (68655,'Sabana De Torres'), (68669,'San Andrés'), (68673,'San Benito'), (68679,'San Gil'), (68682,'San Joaquín'), (68684,'San José De Miranda'), (68686,'San Miguel'), (68689,'San Vicente De Chucurí'), (68705,'Santa Bárbara'), (68720,'Santa Helena Del Opón'), (68745,'Simacota'), (68755,'Socorro'), (68770,'Suaita'), (68773,'Sucre'), (68780,'Suratá'), (68820,'Tona'), (68855,'Valle De San José'), (68861,'Vélez'), (68867,'Vetas'), (68872,'Villanueva'), (68895,'Zapatoca'), (70001,'Sincelejo'), (70110,'Buenavista'), (70124,'Caimito'), (70204,'Coloso'), (70215,'Corozal'), (70221,'Coveñas'), (70230,'Chalán'), (70233,'El Roble'), (70235,'Galeras'), (70265,'Guaranda'), (70400,'La Unión'), (70418,'Los Palmitos'), (70429,'Majagual'), (70473,'Morroa'), (70508,'Ovejas'), (70523,'Palmito'), (70670,'Sampués'), (70678,'San Benito Abad'), (70702,'San Juan De Betulia'), (70708,'San Marcos'), (70713,'San Onofre'), (70717,'San Pedro'), (70742,'San Luis De Sincé'), (70771,'Sucre'), (70820,'Santiago De Tolú'), (70823,'Tolú Viejo'), (73001,'Ibague'), (73024,'Alpujarra'), (73026,'Alvarado'), (73030,'Ambalema'), (73043,'Anzoátegui'), (73055,'Armero'), (73067,'Ataco'), (73124,'Cajamarca'), (73148,'Carmen De Apicalá'), (73152,'Casabianca'), (73168,'Chaparral'), (73200,'Coello'), (73217,'Coyaima'), (73226,'Cunday'), (73236,'Dolores'), (73268,'Espinal'), (73270,'Falan'), (73275,'Flandes'), (73283,'Fresno'), (73319,'Guamo'), (73347,'Herveo'), (73349,'Honda'), (73352,'Icononzo'), (73408,'Lérida'), (73411,'Líbano'), (73443,'Mariquita'), (73449,'Melgar'), (73461,'Murillo'), (73483,'Natagaima'), (73504,'Ortega'), (73520,'Palocabildo'), (73547,'Piedras'), (73555,'Planadas'), (73563,'Prado'), (73585,'Purificación'), (73616,'Rioblanco'), (73622,'Roncesvalles'), (73624,'Rovira'), (73671,'Saldaña'), (73675,'San Antonio'), (73678,'San Luis'), (73686,'Santa Isabel'), (73770,'Suárez'), (73854,'Valle De San Juan'), (73861,'Venadillo'), (73870,'Villahermosa'), (73873,'Villarrica'), (76001,'Cali'), (76020,'Alcalá'), (76036,'Andalucía'), (76041,'Ansermanuevo'), (76054,'Argelia'), (76100,'Bolívar'), (76109,'Buenaventura'), (76111,'Guadalajara De Buga'), (76113,'Bugalagrande'), (76122,'Caicedonia'), (76126,'Calima'), (76130,'Candelaria'), (76147,'Cartago'), (76233,'Dagua'), (76243,'El Águila'), (76246,'El Cairo'), (76248,'El Cerrito'), (76250,'El Dovio'), (76275,'Florida'), (76306,'Ginebra'), (76318,'Guacarí'), (76364,'Jamundí'), (76377,'La Cumbre'), (76400,'La Unión'), (76403,'La Victoria'), (76497,'Obando'), (76520,'Palmira'), (76563,'Pradera'), (76606,'Restrepo'), (76616,'Riofrío'), (76622,'Roldanillo'), (76670,'San Pedro'), (76736,'Sevilla'), (76823,'Toro'), (76828,'Trujillo'), (76834,'Tuluá'), (76845,'Ulloa'), (76863,'Versalles'), (76869,'Vijes'), (76890,'Yotoco'), (76892,'Yumbo'), (76895,'Zarzal'), (81001,'Arauca'), (81065,'Arauquita'), (81220,'Cravo Norte'), (81300,'Fortul'), (81591,'Puerto Rondón'), (81736,'Saravena'), (81794,'Tame'), (85001,'Yopal'), (85010,'Aguazul'), (85015,'Chameza'), (85125,'Hato Corozal'), (85136,'La Salina'), (85139,'Maní'), (85162,'Monterrey'), (85225,'Nunchía'), (85230,'Orocué'), (85250,'Paz De Ariporo'), (85263,'Pore'), (85279,'Recetor'), (85300,'Sabanalarga'), (85315,'Sácama'), (85325,'San Luis De Palenque'), (85400,'Támara'), (85410,'Tauramena'), (85430,'Trinidad'), (85440,'Villanueva'), (86001,'Mocoa'), (86219,'Colón'), (86320,'Orito'), (86568,'Puerto Asís'), (86569,'Puerto Caicedo'), (86571,'Puerto Guzmán'), (86573,'Leguízamo'), (86749,'Sibundoy'), (86755,'San Francisco'), (86757,'San Miguel'), (86760,'Santiago'), (86865,'Valle Del Guamuez'), (86885,'Villagarzón'), (88001,'San Andrés'), (88564,'Providencia'), (91001,'Leticia'), (91263,'El Encanto'), (91405,'La Chorrera'), (91407,'La Pedrera'), (91430,'La Victoria'), (91460,'Miriti - Paraná'), (91530,'Puerto Alegría'), (91536,'Puerto Arica'), (91540,'Puerto Nariño'), (91669,'Puerto Santander'), (91798,'Tarapacá'), (94001,'Inírida'), (94343,'Barranco Minas'), (94663,'Mapiripana'), (94883,'San Felipe'), (94884,'Puerto Colombia'), (94885,'La Guadalupe'), (94886,'Cacahual'), (94887,'Pana Pana'), (94888,'Morichal'), (95001,'San José Del Guaviare'), (95015,'Calamar'), (95025,'El Retorno'), (95200,'Miraflores'), (97001,'Mitú'), (97161,'Caruru'), (97511,'Pacoa'), (97666,'Taraira'), (97777,'Papunaua'), (97889,'Yavaraté'), (99001,'Puerto Carreño'), (99524,'La Primavera'), (99624,'Santa Rosalía'), (99773,'Cumaribo') ], validate_choice=True) celularEmpleado = IntegerField('Numero Telefono Movil', validators=[ Required(message='El campo es obligatorio'), Length(max=10, min=10, message='El campo debe tener 10 caracteres') ]) correoElectronicoEmpleado = StringField('Correo Electronico Principal', validators=[ Required(message='El campo es obligatorio'), Email() ]) enviar = SubmitField("Enviar") class inscribirDepositos(FlaskForm): tipoDeposito = SelectField('Tipo Deposito Electronico', choices=[ ('DETS','Deposito Electronico De Tramite Simplificado'), ('DECSE','Deposito Electronico Para Canalizar Subsidios Estatales'), ('DETO','Deposito Electronico De Tramite Ordinario'), ('DETTS','Deposito Electronico Transaccional De Tramite Simplificado'), ('DETTO','Deposito Electronico Transaccional De Tramite Ordinario')], validators=[ Required(message='El campo es obligatorio'), ]) depositoElectronico = IntegerField('Deposito Electronico Numero', validators=[ Required(message='El campo es obligatorio') ]) nombrePersonalizado = StringField('Nombre Personalizado', validators=[ Required(message='El campo es obligatorio') ]) tipoId = SelectField('Tipo Identificacion', choices=[ ('CC','Cedula de Ciudadania'), ('CE','Cedula de Extrangeria'), ('PA','Pasaporte'), ('RC','Registro Civil'), ('TI','Tarjeta de Identidad')], validators=[ Required(message='El campo es obligatorio'), ]) numeroIdCliente = IntegerField('Numero Identificacion', validators=[ Required(message='El campo es obligatorio'), Length(max=10, min=6, message='El campo debe tener entre 6 y 10 caracteres') ]) inscribirDeposito = SubmitField("Inscribir Deposito") class transferir(FlaskForm): productoDestino = IntegerField('Deposito de Destino', validators=[ Required(message='El campo es obligatorio') ]) valorATransferir = IntegerField('Valor a Transferir', validators=[ Required(message='El campos es obligatorio') ]) transferir = SubmitField("Realizar Transferencia")
python
from .serializers import User
python
""" Other plotting routines outside of matplotlib """ import matplotlib.transforms as transforms import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib.lines import Line2D import matplotlib.dates as mdates from matplotlib import collections from matplotlib.ticker import Formatter from datetime import datetime, timedelta import numpy as np from sfoda.utils import othertime class StreakPlot(object): """ Class for generating a streak plot """ # Width of the start and end of the tail widthmin = 0.1 widthmax = 1.5 # Plotting parameters colors = '0.9' alpha = 0.9 xlim=None ylim=None def __init__(self,xp,yp,**kwargs): """ StreakPlot: xp, yp - spatial location matrices with dimension Nt x Nxy Streaks are along the first dimension Nt """ self.__dict__.update(**kwargs) self.xp = xp self.yp = yp self.nx,self.nt = np.shape(self.xp) self.create_xy() def create_xy(self): # Create the start and end points self.points = np.concatenate([self.xp[...,np.newaxis],\ self.yp[...,np.newaxis]],axis=-1) # Create the linewidths lwidths = np.linspace(self.widthmin,self.widthmax,self.nt-1) lwidths = lwidths**2 # this thins out the tail a bit self.lwidths = lwidths/lwidths[-1] * self.widthmax # Create a list of segment arrays self.segments=[ np.concatenate([self.points[ii,:-1,np.newaxis,:],\ self.points[ii,1:,np.newaxis,:]],axis=1)\ for ii in range(self.nx) ] # Create a list of line collections self.lcs = [ LineCollection(segment, linewidths=self.lwidths,\ colors=self.colors,alpha=self.alpha)\ for segment in self.segments ] def update(self,xp,yp): """ Update the line collections with new x,y points """ self.xp=xp self.yp=yp # Create the start and end points self.points = np.concatenate([xp[...,np.newaxis],yp[...,np.newaxis]],axis=-1) # Create a list of segment arrays self.segments=[ np.concatenate([self.points[ii,:-1,np.newaxis,:],\ self.points[ii,1:,np.newaxis,:]],axis=1)\ for ii in range(self.nx) ] for lc, seg in zip(self.lcs,self.segments): lc.set_segments(seg) def plot(self, ax): """Inserts each line collection into current plot""" if self.xlim == None: self.xlim = [self.xp.min(),self.xp.max()] if self.ylim == None: self.ylim = [self.yp.min(),self.yp.max()] ax.set_xlim(self.xlim) ax.set_ylim(self.ylim) ax.set_aspect('equal') list(map(ax.add_collection,self.lcs)) #for lc in self.lcs: # ax.add_collection(lc) return ax def streakplot(xp,yp,ax=None,**kwargs): """ Functional call to StreakPlot class """ if ax==None: ax=plt.gca() S = StreakPlot(xp,yp,**kwargs) S.plot(ax) return S def stackplot(t,y,scale=None,gap=0.2,ax=None,fig=None,units='',labels=None,**kwargs): """ Vertically stacked time series plot. Puts all of the time-series into one axes by working out a suitable spacing. Inputs: y - 2d array [nt,ny] where ny is the number of time series t - datetime vector Returns: fig, ax : figure and axes handles ll : plot handles to each line plot [list] """ # Determine the scale factors and the heights of all of the axes ny = y.shape[0] # Make sure that the time is datetime if isinstance(t[0], np.datetime64): t = othertime.datetime64todatetime(t) if scale==None: scale = np.abs(y).max() if not labels == None: assert len(labels)==ny, ' number of labels (%d) must equal number of layers (%d)'%(len(labels),ny) # Height of each axes in normalized coordinates yheight = 1.0 / (ny + (ny+1.0)*gap) # Create a new figure if fig==None: fig=plt.figure() else: fig = plt.gcf() if ax == None: ax = fig.add_subplot(111,frame_on=False,ylim=[0,1.0],yticks=[]) # Now add each line to the figure ll = [] # List of line objects def fakeaxes(yval,dy): cc=[0.5,0.5,0.5] ax.add_line(Line2D([0,1],[yval,yval],linewidth=0.5,color=cc,transform=ax.transAxes,linestyle='--')) yp = yval + dy/2. ym = yval - dy/2. ax.add_line(Line2D([0,0],[yp,ym],linewidth=0.5,color=cc,transform=ax.transAxes)) ax.add_line(Line2D([1,1],[yp,ym],linewidth=0.5,color=cc,transform=ax.transAxes)) #Little caps ax.add_line(Line2D([0,0.01],[yp,yp],linewidth=0.5,color=cc,transform=ax.transAxes)) ax.add_line(Line2D([0,0.01],[ym,ym],linewidth=0.5,color=cc,transform=ax.transAxes)) ax.add_line(Line2D([0.99,1],[yp,yp],linewidth=0.5,color=cc,transform=ax.transAxes)) ax.add_line(Line2D([0.99,1],[ym,ym],linewidth=0.5,color=cc,transform=ax.transAxes)) for N in range(1,ny+1): yoffset = N*(gap*yheight) + 0.5*yheight + (N-1)*yheight # scaling factor #vscale = yheight / (scale+yoffset) vscale = yheight / (2*scale) l = ax.plot(t,vscale*y[N-1,:]+yoffset,**kwargs) ll.append(l) #Adds an axes fakeaxes(yoffset,yheight) if not labels==None: plt.text(0.2,yoffset+0.5*yheight-0.02,labels[N-1],transform=ax.transAxes,fontstyle='italic') # Add a few extra features ax.add_line(Line2D([0,1],[0.01,0.01],linewidth=0.5,color='k',transform=ax.transAxes)) ax.add_line(Line2D([0,1],[1,1],linewidth=0.5,color='k',transform=ax.transAxes)) plt.xticks(rotation=17) plt.ylabel('Scale = $\pm$%2.1f [%s]'%(scale,units)) return fig,ax,ll def polar_pdf( u, v,\ speedmax=1.0, ndirbins=90, nspeedbins=25, cmap='RdYlBu_r',\ ax=None): """ Polar plot of speed-direction joint frequency distribution """ # Convert cartesian polar coordinates u_hat_mod = u + 1j*v speed_mod = np.abs(u_hat_mod) theta_mod = np.angle(u_hat_mod) # Create a 2d histogram of speed direction abins = np.linspace(-np.pi, np.pi, ndirbins) # 0 to 360 in steps of 360/N. sbins = np.linspace(0.0, speedmax, nspeedbins) Hmod, xedges, yedges = np.histogram2d(theta_mod, speed_mod,\ bins=(abins,sbins), normed=True) #Grid to plot your data on using pcolormesh theta = 0.5*abins[1:]+0.5*abins[0:-1] r = 0.5*sbins[1:]+0.5*sbins[0:-1] # Make sure plot covers the whole circle theta[0] = -np.pi theta[-1] = np.pi #theta, r = np.mgrid[0:2*np.pi:360j, 1:100:50j] # Contour levels precentages clevs = [0.001, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0] xlabels = ['E','ENE','N','WNW','W','WSW','S','ESE'] #fig = plt.figure( figsize = (14,6)) if ax is None: ax = plt.subplot(111, projection='polar') ax.set_xticklabels(xlabels) C = ax.contourf(theta, r, Hmod.T, clevs, cmap = cmap) return C, ax def SpeedDirPlot(t,u,v,convention='current',units='m s^{-1}',color1='b',color2='r'): """ Plots speed and direction on the same axes Inputs: t - time vector u,v - velocity cartesian components Returns: ax - list of axes handles h - list of plot handles convention = 'current' or 'wind' See this example: http://matplotlib.org/examples/api/two_scales.html """ import airsea Dir, Spd = airsea.convertUV2SpeedDirn(u,v,convention=convention) ax = list(range(2)) h = list(range(2)) fig = plt.gcf() ax[0] = fig.gca() # Left axes h[0] = ax[0].fill_between(t, Spd, color=color1,alpha=0.7) # Make the y-axis label and tick labels match the line color. ax[0].set_ylabel('Speed [$%s$]'%units, color=color1) for tl in ax[0].get_yticklabels(): tl.set_color(color1) #Right axes ax[1] = ax[0].twinx() # This sets up the second axes ax[1].plot(t, Dir, '.',color=color2) ax[1].set_ylabel("Dir'n [$\circ$]", color=color2) ax[1].set_ylim([0,360]) ax[1].set_yticks([0,90,180,270]) ax[1].set_yticklabels(['N','E','S','W']) for tl in ax[1].get_yticklabels(): tl.set_color(color2) plt.setp( ax[0].xaxis.get_majorticklabels(), rotation=17 ) return ax, h def ProfilePlot(t,y,z,scale=86400,\ axis=0,color=[0.5,0.5,0.5],xlim=None,units='m/s',scalebar=1.0): """ Plot a series of vertical profiles as a time series scale - Sets 1 unit = scale (seconds) See this page on formatting: http://matplotlib.org/examples/pylab_examples/date_index_formatter.html """ class MyFormatter(Formatter): def __init__(self, dates, fmt='%b %d %Y'): self.fmt = fmt self.dates = dates def __call__(self, x, pos=0): 'Return the label for time x s' return datetime.strftime(datetime(1990,1,1)+timedelta(seconds=x),self.fmt) tsec = othertime.SecondsSince(t) formatter = MyFormatter(tsec) y = np.swapaxes(y,0,axis) lines=[] line2 =[] for ii, tt in enumerate(tsec): #xplot = set_scale(y[:,ii],tt) xplot = tt + y[:,ii]*scale lines.append(np.array((xplot,z)).T) line2.append(np.array([[tt,tt],[z[0],z[-1]]]).T) LC1 = collections.LineCollection(lines,colors=color,linewidths=1.5) LC2 = collections.LineCollection(line2,colors='k',linestyles='dashed') # Zero axis ax=plt.gca() ax.add_collection(LC1) ax.add_collection(LC2) ax.set_ylim((z.min(),z.max())) ax.xaxis.set_major_formatter(formatter) if xlim==None: xlim=(tsec[0]-scale/2,tsec[-1]+scale/2) else: xlim=othertime.SecondsSince(xlim) ax.set_xlim(xlim) plt.xticks(rotation=17) ### # Add a scale bar ### # Compute the scale bar size in dimensionless units if not scalebar==None: xscale = scalebar*scale/(xlim[-1]-xlim[0]) x0 = 0.1 y0 = 0.8 dy = 0.02 ax.add_line(Line2D([x0,x0+xscale],[y0,y0],linewidth=0.5,color='k',transform=ax.transAxes)) #Little caps ax.add_line(Line2D([x0,x0],[y0-dy,y0+dy],linewidth=0.5,color='k',transform=ax.transAxes)) ax.add_line(Line2D([x0+xscale,x0+xscale],[y0-dy,y0+dy],linewidth=0.5,color='k',transform=ax.transAxes)) plt.text(x0,y0+0.05,'Scale %3.1f %s'%(scalebar,units),\ transform=ax.transAxes) return ax def monthlyhist(t,y,ylim=0.1,xlabel='',ylabel='',title='',**kwargs): """ Plots 12 histograms on a 6x2 matrix of variable, y, grouped by calendar month Inputs: y - vector of data t - vector of datetime objects kwargs - keyword arguments for numpy.hist """ month = othertime.getMonth(t) fig=plt.gcf() for m in range(1,13): # Find the values ind = np.argwhere(month==m) data=y[ind] ax=plt.subplot(6,2,m) if len(data)>0: plt.hist(data,**kwargs) mon=datetime.strftime(datetime(1900,m,1),'%B') plt.title(mon) plt.ylim([0,ylim]) if m not in (11,12): ax.set_xticklabels([]) else: plt.xlabel(xlabel) if m not in (1,3,5,7,9,11): ax.set_yticklabels([]) else: plt.ylabel(ylabel) #Calc some stats textstr = 'Mean: %6.1f\nStd. Dev.: %6.1f\n'%(np.mean(data),np.std(data)) plt.text(0.5,0.5,textstr,transform=ax.transAxes) # plot a title plt.figtext(0.5,0.95,title,fontsize=14,horizontalalignment='center') return fig def window_index(serieslength,windowsize,overlap): """ Determines the indices for start and end points of a time series window Inputs: serieslength - length of the vector [int] windowsize - length of the window [int] overlap - number of overlap points [int] Returns: pt1,pt2 the start and end indices of each window """ p1=0 p2=p1 + windowsize pt1=[p1] pt2=[p2] while p2 < serieslength: p1 = p2 - overlap p2 = min((p1 + windowsize, serieslength)) pt1.append(p1) pt2.append(p2) return pt1, pt2 def axcolorbar(cbobj,pos=[0.7, 0.8, 0.2, 0.04],ax=None,fig=None,orientation='horizontal',**kwargs): """ Inserts a colorbar with a position relative to an axes and not a figure Inputs: cbobj - plot object for colorbar pos - position vector [x0, y0, width, height] in dimensionless coordinates ax - axes to insert colobar figure - figure **kwargs - arguments for plt.colorbar Returns a colorbar object Derived from this post: http://stackoverflow.com/questions/22413211/cant-fix-position-of-colorbar-in-image-with-multiple-subplots """ if fig is None: fig=plt.gcf() if ax is None: ax=plt.gca() fig.tight_layout() # You call fig.tight_layout BEFORE creating the colorbar # You input the POSITION AND DIMENSIONS RELATIVE TO THE AXES x0, y0, width, height = pos # and transform them after to get the ABSOLUTE POSITION AND DIMENSIONS Bbox = transforms.Bbox.from_bounds(x0, y0, width, height) trans = ax.transAxes + fig.transFigure.inverted() l, b, w, h = transforms.TransformedBbox(Bbox, trans).bounds # Now just create the axes and the colorbar cbaxes = fig.add_axes([l, b, w, h]) cbar = plt.colorbar(cbobj, cax=cbaxes,orientation=orientation, **kwargs) cbar.ax.tick_params(labelsize=9) return cbar
python
import win32gui from src.services.window_managers.base_window_manager import WindowTitleManager class WindowsWindowManager(WindowTitleManager): def fetch_window_title(self) -> str: window_in_focus = win32gui.GetForegroundWindow() return win32gui.GetWindowText(window_in_focus)
python
import requests from bs4 import BeautifulSoup LIMIT = 50 URL = f"https://www.indeed.com/jobs?q=python&limit={LIMIT}" def _check_has_first_page_end() -> bool: """Check if the first page has a link to the last page""" first_response = requests.get(URL) soup = BeautifulSoup(first_response.text, "html.parser") pagination = soup.find("div", class_="pagination") nav_items = pagination.find_all("li") item_labels = [item.findChild()["aria-label"] for item in nav_items] # If 'Next' is not in nav, the first page has the last page link. return "Next" not in item_labels def _extract_last_page_num() -> int: """Get the last page number""" is_last_page = _check_has_first_page_end() item_labels = [] page_index = 0 while not is_last_page: response = requests.get(URL + f"&start={page_index * LIMIT}") soup = BeautifulSoup(response.text, "html.parser") pagination = soup.find("div", class_="pagination") nav_items = pagination.find_all("li") item_labels = [item.findChild()["aria-label"] for item in nav_items] is_last_page = False if "Next" in item_labels else True page_index += 1 return int(item_labels[-1]) def _format_location(location: str) -> str: """Get a location with spaces around plus and template""" return location.replace("+", " + ").replace("•", " • ") def _extract_job(html): """ Get a dictionary of a job's information :param html: Tag :return: dict[str, str] """ title = html.find("span", title=True).string company = html.find("span", class_="companyName").string location = _format_location(html.find("div", class_="companyLocation").text) job_id = html.parent["data-jk"] return { "title": title, "company": company, "location": location, "link": f"https://www.indeed.com/viewjob?jk={job_id}&tk=1fg49gh9apiab801&from=serp&vjs=3", } def _extract_jobs(last_page_num: int): """ Get a list of job info's dictionaries :return: list[dict[str, str]] """ jobs = [] for i in range(last_page_num): print(f"Scraping Indeed's page {i}...") response = requests.get(f"{URL}&start={i * LIMIT}") soup = BeautifulSoup(response.text, "html.parser") job_containers = soup.find_all("div", class_="slider_container") for job_container in job_containers: jobs.append(_extract_job(job_container)) return jobs def get_jobs(): """ Extract jobs until the last page :return: list[dict[str, str]] """ last_page_num = _extract_last_page_num() jobs = _extract_jobs(last_page_num) return jobs
python
from django.contrib import admin from django.urls import include, path from accounts.author.api import ( ForgetPasswordView, LoginAuthorAPIView, RegisterAuthorView, ) from accounts.editor.api import ( ForgetEditorPasswordView, LoginEditorAPIView, RegisterEditorView, ) from accounts.reviewer.api import ( ForgetReviewerPasswordView, LoginReviewerAPIView, RegisterReviewerView, ) from accounts.views import UpdateProfileApiView, UserDetailApiView urlpatterns = [ path("register_author/", RegisterAuthorView.as_view(), name="register_author"), path("login_author/", LoginAuthorAPIView.as_view(), name="login_author"), path("forget-password/", ForgetPasswordView.as_view(), name="forget-password"), # ------------------------------------------------------------------------------ path("register_editor/", RegisterEditorView.as_view(), name="register_editor"), path("login_editor/", LoginEditorAPIView.as_view(), name="login_editor"), path( "forget-editor-password/", ForgetEditorPasswordView.as_view(), name="forget-editor-password", ), # ------------------------------------------------------------------------------ path( "register_reviewer/", RegisterReviewerView.as_view(), name="register_reviewer" ), path("login_reviewer/", LoginReviewerAPIView.as_view(), name="login_reviewer"), path( "forget-reviewer-password/", ForgetReviewerPasswordView.as_view(), name="forget-reviewer-password", ), path("update-profile/", UpdateProfileApiView.as_view(), name="update_profile"), path("user-detail/", UserDetailApiView.as_view(), name="user_detail"), ]
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Useful functions for Counter manipulation. """ from collections import Counter def scale(cntr, factor): cntr_ = Counter() for key, value in cntr.items(): cntr_[key] = value * factor return cntr_ def normalize(cntr): return scale(cntr, 1./sum(cntr.values())) def equals(cntr, cntr_): keys = set(cntr.keys()).union(set(cntr_.keys())) for key in keys: if key not in cntr or key not in cntr_: return False elif cntr[key] != cntr_[key]: return False return True def fequals(cntr, cntr_, eps=1e-5): keys = set(cntr.keys()).union(set(cntr_.keys())) for key in keys: if key not in cntr or key not in cntr_: return False elif abs(cntr[key] - cntr_[key]) > eps: return False return True def test_equals(): assert equals(Counter([1,1,3,4]),Counter([1,3,1,4])) assert not equals(Counter([1,1,3,4]),Counter([1,3,3,4]))
python
# Copyright 2017-2018 The Open SoC Debug Project # # 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 setuptools import setup from setuptools.extension import Extension import os import sys import subprocess if '--use-cython' in sys.argv: USE_CYTHON = True sys.argv.remove('--use-cython') else: USE_CYTHON = False ext = '.pyx' if USE_CYTHON else '.c' def pkgconfig(*packages, **kw): config = kw.setdefault('config', {}) optional_args = kw.setdefault('optional', '') flag_map = {'include_dirs': ['--cflags-only-I', 2], 'library_dirs': ['--libs-only-L', 2], 'libraries': ['--libs-only-l', 2], 'extra_compile_args': ['--cflags-only-other', 0], 'extra_link_args': ['--libs-only-other', 0], } for package in packages: for distutils_key, (pkg_option, n) in flag_map.items(): try: cmd = ['pkg-config', optional_args, pkg_option, package] items = subprocess.check_output(cmd).decode('utf8').split() config.setdefault(distutils_key, []).extend([i[n:] for i in items]) except subprocess.CalledProcessError: return config return config extensions = [ Extension('osd', ['src/osd'+ext], **pkgconfig('osd', 'libglip')) ] if USE_CYTHON: from Cython.Build import cythonize extensions = cythonize(extensions, compiler_directives={'language_level': 3, 'embedsignature': True}) with open("README.md", "r", encoding='utf-8') as readme: long_description = readme.read() version_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "src/version.py") setup( name = "opensocdebug", ext_modules = extensions, use_scm_version = { "root": "../..", "relative_to": __file__, "write_to": version_file, }, author = "Philipp Wagner", author_email = "[email protected]", description = ("Open SoC Debug is a way to interact with and obtain " "information from a System-on-Chip (SoC)."), long_description = long_description, url = "http://www.opensocdebug.org", license = 'Apache License, Version 2.0', classifiers = [ "Development Status :: 3 - Alpha", "Topic :: Utilities", "Topic :: Software Development :: Debuggers", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: Apache Software License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Cython", ], setup_requires = [ 'setuptools_scm', 'pytest-runner', ], tests_require = [ 'pytest', ], )
python
from __future__ import absolute_import import os.path import sys import threading import typing import attr from ddtrace.internal import compat from ddtrace.internal import nogevent from ddtrace.internal.utils import attr as attr_utils from ddtrace.internal.utils import formats from ddtrace.profiling import collector from ddtrace.profiling import event from ddtrace.profiling.collector import _task from ddtrace.profiling.collector import _threading from ddtrace.profiling.collector import _traceback from ddtrace.vendor import wrapt @event.event_class class LockEventBase(event.StackBasedEvent): """Base Lock event.""" lock_name = attr.ib(default="<unknown lock name>", type=str) sampling_pct = attr.ib(default=0, type=int) @event.event_class class LockAcquireEvent(LockEventBase): """A lock has been acquired.""" wait_time_ns = attr.ib(default=0, type=int) @event.event_class class LockReleaseEvent(LockEventBase): """A lock has been released.""" locked_for_ns = attr.ib(default=0, type=int) def _current_thread(): # type: (...) -> typing.Tuple[int, str] thread_id = nogevent.thread_get_ident() return thread_id, _threading.get_thread_name(thread_id) # We need to know if wrapt is compiled in C or not. If it's not using the C module, then the wrappers function will # appear in the stack trace and we need to hide it. if os.environ.get("WRAPT_DISABLE_EXTENSIONS"): WRAPT_C_EXT = False else: try: import ddtrace.vendor.wrapt._wrappers as _w # noqa: F401 except ImportError: WRAPT_C_EXT = False else: WRAPT_C_EXT = True del _w class _ProfiledLock(wrapt.ObjectProxy): def __init__(self, wrapped, recorder, tracer, max_nframes, capture_sampler, endpoint_collection_enabled): wrapt.ObjectProxy.__init__(self, wrapped) self._self_recorder = recorder self._self_tracer = tracer self._self_max_nframes = max_nframes self._self_capture_sampler = capture_sampler self._self_endpoint_collection_enabled = endpoint_collection_enabled frame = sys._getframe(2 if WRAPT_C_EXT else 3) code = frame.f_code self._self_name = "%s:%d" % (os.path.basename(code.co_filename), frame.f_lineno) def acquire(self, *args, **kwargs): if not self._self_capture_sampler.capture(): return self.__wrapped__.acquire(*args, **kwargs) start = compat.monotonic_ns() try: return self.__wrapped__.acquire(*args, **kwargs) finally: try: end = self._self_acquired_at = compat.monotonic_ns() thread_id, thread_name = _current_thread() task_id, task_name, task_frame = _task.get_task(thread_id) if task_frame is None: frame = sys._getframe(1) else: frame = task_frame frames, nframes = _traceback.pyframe_to_frames(frame, self._self_max_nframes) event = LockAcquireEvent( lock_name=self._self_name, frames=frames, nframes=nframes, thread_id=thread_id, thread_name=thread_name, task_id=task_id, task_name=task_name, wait_time_ns=end - start, sampling_pct=self._self_capture_sampler.capture_pct, ) if self._self_tracer is not None: event.set_trace_info(self._self_tracer.current_span(), self._self_endpoint_collection_enabled) self._self_recorder.push_event(event) except Exception: pass def release( self, *args, # type: typing.Any **kwargs # type: typing.Any ): # type: (...) -> None try: return self.__wrapped__.release(*args, **kwargs) finally: try: if hasattr(self, "_self_acquired_at"): try: end = compat.monotonic_ns() thread_id, thread_name = _current_thread() task_id, task_name, task_frame = _task.get_task(thread_id) if task_frame is None: frame = sys._getframe(1) else: frame = task_frame frames, nframes = _traceback.pyframe_to_frames(frame, self._self_max_nframes) event = LockReleaseEvent( # type: ignore[call-arg] lock_name=self._self_name, frames=frames, nframes=nframes, thread_id=thread_id, thread_name=thread_name, task_id=task_id, task_name=task_name, locked_for_ns=end - self._self_acquired_at, sampling_pct=self._self_capture_sampler.capture_pct, ) if self._self_tracer is not None: event.set_trace_info( self._self_tracer.current_span(), self._self_endpoint_collection_enabled ) self._self_recorder.push_event(event) finally: del self._self_acquired_at except Exception: pass acquire_lock = acquire class FunctionWrapper(wrapt.FunctionWrapper): # Override the __get__ method: whatever happens, _allocate_lock is always considered by Python like a "static" # method, even when used as a class attribute. Python never tried to "bind" it to a method, because it sees it is a # builtin function. Override default wrapt behavior here that tries to detect bound method. def __get__(self, instance, owner=None): return self @attr.s class LockCollector(collector.CaptureSamplerCollector): """Record lock usage.""" nframes = attr.ib(factory=attr_utils.from_env("DD_PROFILING_MAX_FRAMES", 64, int)) endpoint_collection_enabled = attr.ib( factory=attr_utils.from_env("DD_PROFILING_ENDPOINT_COLLECTION_ENABLED", True, formats.asbool) ) tracer = attr.ib(default=None) def _start_service(self): # type: ignore[override] # type: (...) -> None """Start collecting `threading.Lock` usage.""" self.patch() super(LockCollector, self)._start_service() def _stop_service(self): # type: ignore[override] # type: (...) -> None """Stop collecting `threading.Lock` usage.""" super(LockCollector, self)._stop_service() self.unpatch() def patch(self): # type: (...) -> None """Patch the threading module for tracking lock allocation.""" # We only patch the lock from the `threading` module. # Nobody should use locks from `_thread`; if they do so, then it's deliberate and we don't profile. self.original = threading.Lock def _allocate_lock(wrapped, instance, args, kwargs): lock = wrapped(*args, **kwargs) return _ProfiledLock( lock, self.recorder, self.tracer, self.nframes, self._capture_sampler, self.endpoint_collection_enabled ) threading.Lock = FunctionWrapper(self.original, _allocate_lock) # type: ignore[misc] def unpatch(self): # type: (...) -> None """Unpatch the threading module for tracking lock allocation.""" threading.Lock = self.original # type: ignore[misc]
python
""" Added dag name column to executions Revision ID: e937a5234ce4 Revises: a472b5ad50b7 Create Date: 2021-02-25 12:14:38.197522 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "e937a5234ce4" down_revision = "a472b5ad50b7" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "executions", sa.Column("dag_name", sa.String(length=256), nullable=True) ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("executions", "dag_name") # ### end Alembic commands ###
python
# Generated by Django 3.1 on 2020-08-05 10:07 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0010_auto_20200804_1433'), ] operations = [ migrations.AlterModelOptions( name='userplugin', options={'ordering': ('plugin__name',)}, ), ]
python
from pathlib import Path def findFullFilename(path, pattern): filenameGenerator = Path(path).glob(pattern) firstPath = next(filenameGenerator, None) if firstPath is None: return None return firstPath.name def findPywFilenameHere(pattern): return findFullFilename(".", f"{pattern}*.pyw")
python
from heuristicSearch.planners.astar import Astar from heuristicSearch.envs.env import GridEnvironment from heuristicSearch.graph.node import Node from heuristicSearch.envs.occupancy_grid import OccupancyGrid from heuristicSearch.utils.visualizer import ImageVisualizer from heuristicSearch.utils.utils import * import matplotlib.pyplot as plt import cv2 as cv import sys import pickle """ Note: Numpy array is accessed as (r, c) while a point is (x, y). The code follows (r, c) convention everywhere. Hence, be careful whenever using a point with opencv. """ def main(): """ The main function that sets up the environment and calls the planner. Each planning run has three components: * Environment * Graph * Planner The Environment class contains details about the specific planning problem, eg: a 2D map for 2D planning. Its primary role is to implement a `getChildren` method that returns the successors of each node. This helps in building the graph implicitly. Each vertex in the graph is an instance of `Node` class. It stores details specific to the node. An Astar instance runs on the graph so created. """ folder = sys.argv[1] image = folder + "/image.png" start_goal = folder + "/start_goal.pkl" startPoint, goalPoint = pickle.load( open(start_goal, "rb") ) # Build the planning environment. occGrid = OccupancyGrid() occMap = occGrid.getMapFromImage(image) print(occMap.shape) gridEnv = GridEnvironment(occMap, occMap.shape[0], occMap.shape[1]) gridEnv.setHeuristicType(0) # For visualization. viz = ImageVisualizer(occMap, True) ## To take input by clicking. #startPoint = (100, 20) #goalPoint = (201, 200) #print("Click start point") #startPoint = inputClickedPoint(occMap) #print("Click end point") #goalPoint = inputClickedPoint(occMap) print(startPoint, goalPoint) assert(gridEnv.isValidPoint(startPoint)) assert(gridEnv.isValidPoint(goalPoint)) startNode = Node(gridEnv.getIdFromPoint(startPoint)) startNode.setParent(None) goalNode = Node(gridEnv.getIdFromPoint(goalPoint)) gridEnv.addNode(goalNode) # Choose your planner. planner = Astar(gridEnv, inflation=1) # Plan! planFound = planner.plan(startNode, goalNode, viz=viz) path = [] if planFound: print("Planning successful") # Retrieve the path. currNode = gridEnv.graph[goalNode.getNodeId()] while(currNode.getNodeId() != startNode.getNodeId()): path.append(currNode) currNode = currNode.getParent() # Reverse the list. path = path[::-1] print("Cost of solution is %f"%path[-1].g) pathPoints = [] for node in path: pathPoints.append(gridEnv.getPointFromId(node.getNodeId())) viz.joinPointsInOrder(pathPoints, thickness=2) viz.displayImage() main()
python
#! /usr/bin/env python from pathlib import Path import re import uxn import sys token_prog = re.compile(r"\s*(\)|\S+)") line_comment_prog = re.compile(r".*") string_prog = re.compile(r".*?(?<!\\)\"") fixed_prog = re.compile(r"(-|\+)?\d+\.\d+") prefix_chars = '%:.;,@&|$#~\'"' def eprint(s): sys.stderr.write(f"{s}\n") class CompilationUnit(): def __init__(self): self.macros = {} self.variables = [] self.body = None self.rst = [] self.current_word = None self.include_stdlib = True self.stdlib_included = False self.pending_token = None self.prev_word = None self.sep = "" self.depth = 0 def compile_file(self, filename): old_body = self.body old_rst = self.rst self.body = read_file(filename) self.sep = "" self.depth = 0 while True: w = self.next_word(keep_newline=True) if not w: break self.compile(w) self.body = old_body self.rst = old_rst print() def next_word(self, keep_newline=False): if self.pending_token: w = self.pending_token self.pending_token = None return w m = token_prog.match(self.body) if not m: return None self.body = self.body[m.end():] w = m.group(1) if keep_newline and '\n' in m.group(): self.pending_token = w return '\n' return w def print(self, w): if self.prev_word == '\n' and w == '\n': pass elif w == '\n': indent = " " * self.depth print() self.sep = indent else: print(self.sep + w, end="") self.sep = " " self.prev_word = w def compile_stdlib(self): self.stdlib_included = True print() self.compile_file(self.forth_path) def compile(self, w): if w == '\n': self.print(w) return if w == ':': self.depth += 1 self.sep = "" name = self.next_word() if name == 'init': self.print('|0100') assert self.current_word == None if self.current_word == 'init' and self.include_stdlib and self.stdlib_included == False: self.current_word = name self.compile_stdlib() else: self.current_word = name self.print(f"@{name}") elif w == ';': self.depth -= 1 self.print('JMP2r\n') if self.current_word == 'init': raise ValueError('init must be closed with brk;') elif w == 'brk;': self.depth -= 1 self.print('BRK\n') elif w == 'do': self.depth += 1 loop_lbl = gensym('loop') pred_lbl = gensym('pred') self.rst.append(['do', loop_lbl, pred_lbl]) self.print('( do )') self.print('SWP2 STH2 STH2') self.print(f';&{pred_lbl} JMP2') self.print(f'&{loop_lbl}') elif w == 'loop' or w == '+loop': header, loop_lbl, pred_lbl = self.rst[-1] assert header == 'do' if w == 'loop': self.print('( loop )') self.print('INC2r') else: self.print('( loop )') self.print('STH2 ADD2r') self.print(f'&{pred_lbl}') self.print(f'GTH2kr STHr ;&{loop_lbl} JCN2') self.print('POP2r POP2r') self.rst.pop() self.depth -= 1 elif w == 'if': false_lbl = gensym('false') end_lbl = gensym('end') self.rst.append(['if', false_lbl, end_lbl]) self.print(f'( if ) #0000 EQU2 ,&{false_lbl} JCN') self.depth += 1 elif w == 'else': self.print('( else )') header, false_lbl, end_lbl = self.rst[-1] assert header == 'if' self.rst[-1][0] = 'else' self.print(f',&{end_lbl} JMP') self.print(f'&{false_lbl}') elif w == 'endif': self.print('( endif )') header, false_lbl, end_lbl = self.rst[-1] if header == 'if': self.print(f'&{false_lbl}') elif header == 'else': self.print(f'&{end_lbl}') else: assert False self.rst.pop() self.depth -= 1 elif w == 'begin': self.depth += 1 begin_lbl = gensym('begin') end_lbl = gensym('end-begin') self.rst.append(['begin', begin_lbl, end_lbl]) self.print('( begin )') self.print(f'&{begin_lbl}') elif w == 'while': header, begin_lbl, end_lbl = self.rst[-1] assert header == 'begin' self.print(f'( while ) #0000 EQU2 ;&{end_lbl} JCN2') elif w == 'repeat': header, begin_lbl, end_lbl = self.rst[-1] assert header == 'begin' self.print('( repeat )') self.print(f';&{begin_lbl} JMP2') self.print(f'&{end_lbl}') self.rst.pop() elif w == 'until': header, begin_lbl, end_lbl = self.rst[-1] assert header == 'begin' self.print(f'( until ) #0000 EQU2 ;&{begin_lbl} JCN2') self.print(f'&{end_lbl}') self.rst.pop() self.depth -= 1 elif w == 'again': header, begin_lbl, end_lbl = self.rst[-1] assert header == 'begin' self.print('( again )') self.print(f';&{begin_lbl} JMP2') self.print(f'&{end_lbl}') self.rst.pop() self.depth -= 1 elif w == 'leave': header, begin_lbl, pred_lbl, end_lbl = self.rst[-1] assert header == 'begin' self.print(f'( leave ) ;&{end_lbl} JMP2') elif w == 'tal': self.read_tal() elif w == 'incbin': self.read_binary_file() elif w == 'variable': self.create_variable() elif w == 'sprite-1bpp': self.compile_sprite_1bpp() elif w == '(': self.read_comment() elif w == '\\': self.read_line_comment() elif w[0] == '"': self.read_string(w[1:]) elif w[0] == '%': self.read_macro(w[1:]) elif w[0] == '~': self.compile_file(w[1:]) elif w in self.macros: body = self.macros[w] for child in body: self.compile(child) elif is_uxntal(w): self.print(f"{w}") elif w in self.variables: self.print(f';{w}') else: try: if w[:2] == '0x': n = int(w[2:], 16) elif w[:2] == '0b': n = int(w[2:], 2) elif fixed_prog.match(w): n = parse_fixed_point(w) else: n = int(w, 10) if n < 0: n += 0x10000 n &= 0xffff self.print(f"#{n:04x}") except ValueError: self.print(f';{w} JSR2') def read_tal(self): #todo count depth for nested comments w = self.next_word() while w != 'endtal': if w == '(': self.read_comment() else: self.print(w) w = self.next_word() def read_binary_file(self): filename = self.next_word() with open(filename, 'rb', buffering=4) as f: while True: line = f.read(16) if len(line) == 0: break tal = ' '.join(f"{c:02x}" for c in line) self.print(tal) def read_line_comment(self): m = line_comment_prog.match(self.body) if not m: return None self.body = self.body[m.end():] comment = m.group().strip() def read_comment(self): depth = 1 body = ['('] while True: w = self.next_word() body.append(w) if w == '(': depth += 1 elif w == ')': depth -= 1 elif w == None: break if depth == 0: break s = ' '.join(body) self.print(s) def read_macro(self, name): nw = self.next_word() assert nw == '{' nw = self.next_word() body = [] while nw != '}': body.append(nw) nw = self.next_word() if name in self.macros: raise ValueError(f"Duplicate macro: {name}") self.macros[name] = body def create_variable(self): name = self.next_word() if name in self.variables: raise ValueError(f"Duplicate variable: {name}") if is_uxntal(name): raise ValueError(f"Invalid varialbe name: {name}, it looks like uxntal.") self.variables.append(name) def compile_variables(self): for name in self.variables: self.print(f"@{name} $2") def compile_sprite_1bpp(self): for i in range(8): w = self.next_word() s = w s = re.sub('\.', '0', s) s = re.sub('[^0]', '1', s) n = int(s, 2) self.print(f"{n:02x}") def read_string(self, w): if w[-1] == '"': s = w[:-1] else: m = string_prog.match(self.body) if not m: raise ValueError("failed to find end of string") s = w + m.group()[:-1] self.body = self.body[m.end():] s = s.replace(r'\"', '"') ss = ' 20 '.join('"' + elem for elem in s.split()) self.print(f"{ss} 00") def read_file(filename): with open(filename) as f: return f.read() counter = 0 def gensym(s): global counter name = f"gs-{s}-{counter}" counter += 1 return name def is_uxntal(w): if uxn.is_op(w): return True elif w[0] in prefix_chars: return len(w) != 1 elif w in ['{', '}', '[', ']']: return True else: return False def parse_fixed_point(s): """ Q11.4 binary: 0 000 0000 0000 0000 ^ ^ ^ fractional part | | integer part | | sign bit """ lhs, rhs = s.split('.') i = int(lhs) if i < 0: i += 0b1_0000_0000_0000 i &= 0b1111_1111_1111 i <<= 4 eprint(f"{i}") eprint(f"{i:x}") eprint(f"{i:b}") # -1.25 # 0100 a = 0b1111 b = a / 16 c = int(b * 255) eprint(f"{a} {b} {c} {c:b}") f = float('0.' + rhs) * 16 f = int(f) & 0b1111 n = i + f return n def main(filename): script_dir = Path(__file__).resolve().parent header_path = script_dir.joinpath('header.tal') footer_path = script_dir.joinpath('footer.tal') #print(script_dir) #print(header_path) #print(forth_path) cu = CompilationUnit() cu.forth_path = script_dir.joinpath('forth.fth') cu.compile_file(header_path) cu.compile_file(filename) if cu.include_stdlib and cu.stdlib_included == False: cu.compile_stdlib() cu.compile_variables() cu.compile_file(footer_path) print() if __name__ == '__main__': main(sys.argv[1])
python
# Python3 program for Painting Fence Algorithm # optimised version # Returns count of ways to color k posts def countWays(n, k): dp = [0] * (n + 1) total = k mod = 1000000007 dp[1] = k dp[2] = k * k for i in range(3,n+1): dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod return dp[n] # Driver code n = 3 k = 2 print(countWays(n, k))
python
""" Manipulate Excel workbooks. """ from datetime import datetime import os from openpyxl import Workbook from openpyxl.styles import NamedStyle, Font, Border, Side, PatternFill from trellominer.api import trello from trellominer.config import yaml class Excel(object): def __init__(self): self.config = yaml.read(os.getenv("TRELLO_CONFIG", default=os.path.join(os.path.expanduser('~'), ".trellominer.yaml"))) self.output_file = os.getenv("TRELLO_OUTPUT_FILE", default=self.config['api']['output_file_name']) self.filename = os.path.join(os.path.expanduser('~'), "{0} {1}.xlsx".format(self.output_file, datetime.now().strftime("%Y-%m-%d"))) def filename(self): return self.filename def process_boards(self, boards): """Creates a series of worksheets in a workbook based on Trello board names.""" highlight = NamedStyle(name='highlight') highlight.font = Font(bold=True, size=20) tabletop = NamedStyle(name='tabletop') tabletop.font = Font(bold=True, color='FFFFFF') bd = Side(style='thin', color="000000", border_style='thin') tabletop.border = Border(left=bd, right=bd, top=bd, bottom=bd) tabletop.fill = PatternFill("solid", bgColor="333333") wb = Workbook() wb.add_named_style(highlight) lookup = trello.Trello() current_row = 6 # Dump the default worksheet from the document. # TODO: (PS) Is there a better way to handle this? for sheet in wb: if "Sheet" in sheet.title: wb.remove_sheet(sheet) for board in boards: if "Projects" in board['name']: ws = wb.create_sheet(title="{0}".format(board['name']), index=0) ws.sheet_properties.tabColor = "0000FF" elif "Break Fix" in board['name']: ws = wb.create_sheet(title="{0}".format(board['name']), index=1) ws.sheet_properties.tabColor = "FF0000" elif "Change Control" in board['name']: ws = wb.create_sheet(title="{0}".format(board['name']), index=2) ws.sheet_properties.tabColor = "228B22" else: ws = wb.create_sheet(title="{0}".format(board['name'][0:30]), index=None) ws['A1'].style = 'highlight' ws['A1'] = "{0}".format(board['name']) ws['A2'] = "" # was going to contain board descriptions. Trello have deprecated these, just not from the API ws['A3'] = "{0}".format(board['url']) ws['A3'].style = 'Hyperlink' ws['A4'] = "" headings = ["Name", "Description", "Status", "Due Date", "Complete", "Perc", "Members"] ws.append(headings) header_row = ws[5] for cell in header_row: cell.style = tabletop cards = lookup.cards(board['shortLink']) # Apply some default column widths to each worksheet ws.column_dimensions["A"].width = 40 ws.column_dimensions["B"].width = 100 ws.column_dimensions["C"].width = 10 ws.column_dimensions["D"].width = 22 ws.column_dimensions["G"].width = 45 for card in cards: # TODO: Pretty slow to iterate like this. Improve. listname = lookup.lists(card['idList']) member_list = "" for member in card['members']: member_list += "{0},".format(member['fullName']) member_list.replace(',', ', ') ws["A{0}".format(current_row)] = card['name'] ws["A{0}".format(current_row)].style = 'Output' ws["B{0}".format(current_row)] = card['desc'] ws["C{0}".format(current_row)] = listname['name'] if 'Conceptual' in listname['name']: ws["C{0}".format(current_row)].style = 'Accent5' elif 'Backlog' in listname['name']: ws["C{0}".format(current_row)].style = 'Accent4' elif 'In Progress' in listname['name']: ws["C{0}".format(current_row)].style = 'Accent1' elif 'Impeded' in listname['name']: ws["C{0}".format(current_row)].style = 'Bad' elif 'Completed' in listname['name']: ws["C{0}".format(current_row)].style = 'Good' elif 'Stopped' in listname['name']: ws["C{0}".format(current_row)].style = 'Accent2' elif 'Planned' in listname['name']: ws["C{0}".format(current_row)].style = 'Accent4' elif 'Successful' in listname['name']: ws["C{0}".format(current_row)].style = 'Good' elif 'Failed' in listname['name']: ws["C{0}".format(current_row)].style = 'Bad' elif 'Cancelled' in listname['name']: ws["C{0}".format(current_row)].style = 'Neutral' elif 'Course Development' in listname['name']: ws["C{0}".format(current_row)].style = 'Neutral' elif 'On Training' in listname['name']: ws["C{0}".format(current_row)].style = 'Accent5' elif 'Once Off Scheduled' in listname['name']: ws["C{0}".format(current_row)].style = 'Accent5' else: ws["C{0}".format(current_row)] = listname['name'] ws["D{0}".format(current_row)] = card['due'] ws["E{0}".format(current_row)] = card['dueComplete'] # ws["F{0}".format(current_row)] = card['closed'] tasks = 0 complete = 0 checklists = lookup.checklists(card['shortLink']) for checklist in checklists: for cl in checklist['checkItems']: tasks += 1 if cl['state'] == 'complete': complete += 1 if tasks > 0: perc = 100 * complete / tasks else: perc = 0 ws["F{0}".format(current_row)] = "{0}%".format(int(perc)) if perc < 25: ws["F{0}".format(current_row)].style = 'Bad' elif perc < 100: ws["F{0}".format(current_row)].style = 'Neutral' else: ws["F{0}".format(current_row)].style = 'Good' ws["G{0}".format(current_row)] = member_list[:-1] current_row += 1 current_row = 6 wb.save(self.filename)
python
# -*- coding: utf-8 -*- """ This is the Keras implementation for the GermEval-2014 dataset on NER This model uses the idea from Collobert et al., Natural Language Processing almost from Scratch. It implements the window approach with an isolated tag criterion. For more details on the task see: https://www.ukp.tu-darmstadt.de/fileadmin/user_upload/Group_UKP/publikationen/2014/2014_GermEval_Nested_Named_Entity_Recognition_with_Neural_Networks.pdf @author: Nils Reimers Code was written & tested with: - Python 2.7 - Theano 0.8.x - Keras 1.0.x """ import numpy as np import theano import theano.tensor as T import time import gzip import GermEvalReader import BIOF1Validation import keras from keras.models import Sequential from keras.layers.core import Dense, Flatten, Merge from keras.optimizers import SGD from keras.utils import np_utils from keras.layers.embeddings import Embedding windowSize = 2 # 2 to the left, 2 to the right numHiddenUnits = 100 trainFile = 'data/NER-de-train.tsv' devFile = 'data/NER-de-dev.tsv' testFile = 'data/NER-de-test.tsv' print "NER with Keras, only token, window size %d, float: %s" % (windowSize, theano.config.floatX) ##################### # # Read in the vocab # ##################### print "Read in the vocab" vocabPath = 'embeddings/GermEval.vocab.gz' word2Idx = {} #Maps a word to the index in the embeddings matrix embeddings = [] #Embeddings matrix with gzip.open(vocabPath, 'r') as fIn: idx = 0 for line in fIn: split = line.strip().split(' ') embeddings.append(np.array([float(num) for num in split[1:]])) word2Idx[split[0]] = idx idx += 1 embeddings = np.asarray(embeddings, dtype='float32') embedding_size = embeddings.shape[1] # Create a mapping for our labels label2Idx = {'O':0} idx = 1 for bioTag in ['B-', 'I-']: for nerClass in ['PER', 'LOC', 'ORG', 'OTH']: for subtype in ['', 'deriv', 'part']: label2Idx[bioTag+nerClass+subtype] = idx idx += 1 #Inverse label mapping idx2Label = {v: k for k, v in label2Idx.items()} #Casing matrix caseLookup = {'numeric': 0, 'allLower':1, 'allUpper':2, 'initialUpper':3, 'other':4, 'mainly_numeric':5, 'contains_digit': 6, 'PADDING':7} caseMatrix = np.identity(len(caseLookup), dtype=theano.config.floatX) # Read in data print "Read in data and create matrices" train_sentences = GermEvalReader.readFile(trainFile) dev_sentences = GermEvalReader.readFile(devFile) test_sentences = GermEvalReader.readFile(testFile) # Create numpy arrays train_x, train_case_x, train_y = GermEvalReader.createNumpyArrayWithCasing(train_sentences, windowSize, word2Idx, label2Idx, caseLookup) dev_x, dev_case_x, dev_y = GermEvalReader.createNumpyArrayWithCasing(dev_sentences, windowSize, word2Idx, label2Idx, caseLookup) test_x, test_case_x, test_y = GermEvalReader.createNumpyArrayWithCasing(test_sentences, windowSize, word2Idx, label2Idx, caseLookup) ##################################### # # Create the Network # ##################################### # Create the train and predict_labels function n_in = 2*windowSize+1 n_hidden = numHiddenUnits n_out = len(label2Idx) number_of_epochs = 10 minibatch_size = 35 embedding_size = embeddings.shape[1] dim_case = 6 x = T.imatrix('x') # the data, one word+context per row y = T.ivector('y') # the labels are presented as 1D vector of [int] labels print "Embeddings shape",embeddings.shape words = Sequential() words.add(Embedding(output_dim=embeddings.shape[1], input_dim=embeddings.shape[0], input_length=n_in, weights=[embeddings])) words.layers[0].trainable_weights = [] #Fixed Embedding layer words.add(Flatten()) casing = Sequential() casing.add(Embedding(output_dim=caseMatrix.shape[1], input_dim=caseMatrix.shape[0], input_length=n_in, weights=[caseMatrix])) casing.layers[0].trainable_weights = [] #Fixed Embedding layer casing.add(Flatten()) model = Sequential() model.add(Merge([words, casing], mode='concat')) model.add(Dense(output_dim=n_hidden, input_dim=n_in*embedding_size, init='uniform', activation='tanh')) model.add(Dense(output_dim=n_out, init='uniform', activation='softmax')) # Use Adam optimizer model.compile(loss='categorical_crossentropy', optimizer='adam') print train_x.shape[0], ' train samples' print train_x.shape[1], ' train dimension' print test_x.shape[0], ' test samples' # Train_y is a 1-dimensional vector containing the index of the label # With np_utils.to_categorical we map it to a 1 hot matrix train_y_cat = np_utils.to_categorical(train_y, n_out) ################################## # # Training of the Network # ################################## number_of_epochs = 10 minibatch_size = 64 print "%d epochs" % number_of_epochs print "%d mini batches" % (len(train_x)/minibatch_size) for epoch in xrange(number_of_epochs): start_time = time.time() #Train for 1 epoch model.fit([train_x, train_case_x], train_y_cat, nb_epoch=1, batch_size=minibatch_size, verbose=False, shuffle=True) print "%.2f sec for training" % (time.time() - start_time) # Compute precision, recall, F1 on dev & test data pre_dev, rec_dev, f1_dev = BIOF1Validation.compute_f1(model.predict_classes([dev_x, dev_case_x], verbose=0), dev_y, idx2Label) pre_test, rec_test, f1_test = BIOF1Validation.compute_f1(model.predict_classes([test_x, test_case_x], verbose=0), test_y, idx2Label) print "%d epoch: F1 on dev: %f, F1 on test: %f" % (epoch+1, f1_dev, f1_test)
python
import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = Cling(get_wsgi_application())
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: fabric_next.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='fabric_next.proto', package='protos', syntax='proto3', serialized_pb=_b('\n\x11\x66\x61\x62ric_next.proto\x12\x06protos\x1a\x1fgoogle/protobuf/timestamp.proto\"@\n\x08\x45nvelope\x12\x11\n\tsignature\x18\x01 \x01(\x0c\x12!\n\x07message\x18\x02 \x01(\x0b\x32\x10.protos.Message2\"\x90\x02\n\x08Message2\x12#\n\x04type\x18\x01 \x01(\x0e\x32\x15.protos.Message2.Type\x12\x0f\n\x07version\x18\x02 \x01(\x05\x12-\n\ttimestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07payload\x18\x04 \x01(\x0c\"\x8d\x01\n\x04Type\x12\r\n\tUNDEFINED\x10\x00\x12\r\n\tDISCOVERY\x10\x01\x12\x08\n\x04SYNC\x10\x02\x12\x0c\n\x08PROPOSAL\x10\x03\x12\x10\n\x0cPROPOSAL_SET\x10\x04\x12\x13\n\x0fPROPOSAL_RESULT\x10\x05\x12\x17\n\x13PROPOSAL_SET_RESULT\x10\x06\x12\x0f\n\x0bTRANSACTION\x10\x07\"r\n\x08Proposal\x12#\n\x04type\x18\x01 \x01(\x0e\x32\x15.protos.Proposal.Type\x12\n\n\x02id\x18\x02 \x01(\t\x12\x0f\n\x07payload\x18\x03 \x01(\x0c\"$\n\x04Type\x12\r\n\tUNDEFINED\x10\x00\x12\r\n\tCHAINCODE\x10\x01\"=\n\tResponse2\x12\x0e\n\x06status\x18\x01 \x01(\x05\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x0f\n\x07payload\x18\x03 \x01(\x0c\"\x1d\n\x0fSystemChaincode\x12\n\n\x02id\x18\x01 \x01(\t\"\x96\x01\n\x06\x41\x63tion\x12\x14\n\x0cproposalHash\x18\x01 \x01(\x0c\x12\x18\n\x10simulationResult\x18\x02 \x01(\x0c\x12\x0e\n\x06\x65vents\x18\x03 \x03(\x0c\x12%\n\x04\x65scc\x18\x04 \x01(\x0b\x32\x17.protos.SystemChaincode\x12%\n\x04vscc\x18\x05 \x01(\x0b\x32\x17.protos.SystemChaincode\" \n\x0b\x45ndorsement\x12\x11\n\tsignature\x18\x01 \x01(\x0c\"v\n\x10ProposalResponse\x12#\n\x08response\x18\x01 \x01(\x0b\x32\x11.protos.Response2\x12\x13\n\x0b\x61\x63tionBytes\x18\x02 \x01(\x0c\x12(\n\x0b\x65ndorsement\x18\x03 \x01(\x0b\x32\x13.protos.Endorsement\"g\n\x0e\x45ndorsedAction\x12\x13\n\x0b\x61\x63tionBytes\x18\x01 \x01(\x0c\x12)\n\x0c\x65ndorsements\x18\x02 \x03(\x0b\x32\x13.protos.Endorsement\x12\x15\n\rproposalBytes\x18\x03 \x01(\x0c\"?\n\x0cTransaction2\x12/\n\x0f\x65ndorsedActions\x18\x01 \x03(\x0b\x32\x16.protos.EndorsedAction2K\n\x08\x45ndorser\x12?\n\x0fProcessProposal\x12\x10.protos.Proposal\x1a\x18.protos.ProposalResponse\"\x00\x62\x06proto3') , dependencies=[google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,]) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _MESSAGE2_TYPE = _descriptor.EnumDescriptor( name='Type', full_name='protos.Message2.Type', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNDEFINED', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='DISCOVERY', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='SYNC', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='PROPOSAL', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='PROPOSAL_SET', index=4, number=4, options=None, type=None), _descriptor.EnumValueDescriptor( name='PROPOSAL_RESULT', index=5, number=5, options=None, type=None), _descriptor.EnumValueDescriptor( name='PROPOSAL_SET_RESULT', index=6, number=6, options=None, type=None), _descriptor.EnumValueDescriptor( name='TRANSACTION', index=7, number=7, options=None, type=None), ], containing_type=None, options=None, serialized_start=260, serialized_end=401, ) _sym_db.RegisterEnumDescriptor(_MESSAGE2_TYPE) _PROPOSAL_TYPE = _descriptor.EnumDescriptor( name='Type', full_name='protos.Proposal.Type', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNDEFINED', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='CHAINCODE', index=1, number=1, options=None, type=None), ], containing_type=None, options=None, serialized_start=481, serialized_end=517, ) _sym_db.RegisterEnumDescriptor(_PROPOSAL_TYPE) _ENVELOPE = _descriptor.Descriptor( name='Envelope', full_name='protos.Envelope', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='signature', full_name='protos.Envelope.signature', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='message', full_name='protos.Envelope.message', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=62, serialized_end=126, ) _MESSAGE2 = _descriptor.Descriptor( name='Message2', full_name='protos.Message2', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='type', full_name='protos.Message2.type', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='version', full_name='protos.Message2.version', index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='timestamp', full_name='protos.Message2.timestamp', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='payload', full_name='protos.Message2.payload', index=3, number=4, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _MESSAGE2_TYPE, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=129, serialized_end=401, ) _PROPOSAL = _descriptor.Descriptor( name='Proposal', full_name='protos.Proposal', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='type', full_name='protos.Proposal.type', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='id', full_name='protos.Proposal.id', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='payload', full_name='protos.Proposal.payload', index=2, number=3, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _PROPOSAL_TYPE, ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=403, serialized_end=517, ) _RESPONSE2 = _descriptor.Descriptor( name='Response2', full_name='protos.Response2', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='protos.Response2.status', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='message', full_name='protos.Response2.message', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='payload', full_name='protos.Response2.payload', index=2, number=3, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=519, serialized_end=580, ) _SYSTEMCHAINCODE = _descriptor.Descriptor( name='SystemChaincode', full_name='protos.SystemChaincode', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='protos.SystemChaincode.id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=582, serialized_end=611, ) _ACTION = _descriptor.Descriptor( name='Action', full_name='protos.Action', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='proposalHash', full_name='protos.Action.proposalHash', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='simulationResult', full_name='protos.Action.simulationResult', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='events', full_name='protos.Action.events', index=2, number=3, type=12, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='escc', full_name='protos.Action.escc', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='vscc', full_name='protos.Action.vscc', index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=614, serialized_end=764, ) _ENDORSEMENT = _descriptor.Descriptor( name='Endorsement', full_name='protos.Endorsement', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='signature', full_name='protos.Endorsement.signature', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=766, serialized_end=798, ) _PROPOSALRESPONSE = _descriptor.Descriptor( name='ProposalResponse', full_name='protos.ProposalResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='response', full_name='protos.ProposalResponse.response', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='actionBytes', full_name='protos.ProposalResponse.actionBytes', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='endorsement', full_name='protos.ProposalResponse.endorsement', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=800, serialized_end=918, ) _ENDORSEDACTION = _descriptor.Descriptor( name='EndorsedAction', full_name='protos.EndorsedAction', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='actionBytes', full_name='protos.EndorsedAction.actionBytes', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='endorsements', full_name='protos.EndorsedAction.endorsements', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='proposalBytes', full_name='protos.EndorsedAction.proposalBytes', index=2, number=3, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=920, serialized_end=1023, ) _TRANSACTION2 = _descriptor.Descriptor( name='Transaction2', full_name='protos.Transaction2', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='endorsedActions', full_name='protos.Transaction2.endorsedActions', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1025, serialized_end=1088, ) _ENVELOPE.fields_by_name['message'].message_type = _MESSAGE2 _MESSAGE2.fields_by_name['type'].enum_type = _MESSAGE2_TYPE _MESSAGE2.fields_by_name['timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _MESSAGE2_TYPE.containing_type = _MESSAGE2 _PROPOSAL.fields_by_name['type'].enum_type = _PROPOSAL_TYPE _PROPOSAL_TYPE.containing_type = _PROPOSAL _ACTION.fields_by_name['escc'].message_type = _SYSTEMCHAINCODE _ACTION.fields_by_name['vscc'].message_type = _SYSTEMCHAINCODE _PROPOSALRESPONSE.fields_by_name['response'].message_type = _RESPONSE2 _PROPOSALRESPONSE.fields_by_name['endorsement'].message_type = _ENDORSEMENT _ENDORSEDACTION.fields_by_name['endorsements'].message_type = _ENDORSEMENT _TRANSACTION2.fields_by_name['endorsedActions'].message_type = _ENDORSEDACTION DESCRIPTOR.message_types_by_name['Envelope'] = _ENVELOPE DESCRIPTOR.message_types_by_name['Message2'] = _MESSAGE2 DESCRIPTOR.message_types_by_name['Proposal'] = _PROPOSAL DESCRIPTOR.message_types_by_name['Response2'] = _RESPONSE2 DESCRIPTOR.message_types_by_name['SystemChaincode'] = _SYSTEMCHAINCODE DESCRIPTOR.message_types_by_name['Action'] = _ACTION DESCRIPTOR.message_types_by_name['Endorsement'] = _ENDORSEMENT DESCRIPTOR.message_types_by_name['ProposalResponse'] = _PROPOSALRESPONSE DESCRIPTOR.message_types_by_name['EndorsedAction'] = _ENDORSEDACTION DESCRIPTOR.message_types_by_name['Transaction2'] = _TRANSACTION2 Envelope = _reflection.GeneratedProtocolMessageType('Envelope', (_message.Message,), dict( DESCRIPTOR = _ENVELOPE, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.Envelope) )) _sym_db.RegisterMessage(Envelope) Message2 = _reflection.GeneratedProtocolMessageType('Message2', (_message.Message,), dict( DESCRIPTOR = _MESSAGE2, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.Message2) )) _sym_db.RegisterMessage(Message2) Proposal = _reflection.GeneratedProtocolMessageType('Proposal', (_message.Message,), dict( DESCRIPTOR = _PROPOSAL, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.Proposal) )) _sym_db.RegisterMessage(Proposal) Response2 = _reflection.GeneratedProtocolMessageType('Response2', (_message.Message,), dict( DESCRIPTOR = _RESPONSE2, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.Response2) )) _sym_db.RegisterMessage(Response2) SystemChaincode = _reflection.GeneratedProtocolMessageType('SystemChaincode', (_message.Message,), dict( DESCRIPTOR = _SYSTEMCHAINCODE, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.SystemChaincode) )) _sym_db.RegisterMessage(SystemChaincode) Action = _reflection.GeneratedProtocolMessageType('Action', (_message.Message,), dict( DESCRIPTOR = _ACTION, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.Action) )) _sym_db.RegisterMessage(Action) Endorsement = _reflection.GeneratedProtocolMessageType('Endorsement', (_message.Message,), dict( DESCRIPTOR = _ENDORSEMENT, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.Endorsement) )) _sym_db.RegisterMessage(Endorsement) ProposalResponse = _reflection.GeneratedProtocolMessageType('ProposalResponse', (_message.Message,), dict( DESCRIPTOR = _PROPOSALRESPONSE, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.ProposalResponse) )) _sym_db.RegisterMessage(ProposalResponse) EndorsedAction = _reflection.GeneratedProtocolMessageType('EndorsedAction', (_message.Message,), dict( DESCRIPTOR = _ENDORSEDACTION, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.EndorsedAction) )) _sym_db.RegisterMessage(EndorsedAction) Transaction2 = _reflection.GeneratedProtocolMessageType('Transaction2', (_message.Message,), dict( DESCRIPTOR = _TRANSACTION2, __module__ = 'fabric_next_pb2' # @@protoc_insertion_point(class_scope:protos.Transaction2) )) _sym_db.RegisterMessage(Transaction2) import grpc from grpc.beta import implementations as beta_implementations from grpc.beta import interfaces as beta_interfaces from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities class EndorserStub(object): def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.ProcessProposal = channel.unary_unary( '/protos.Endorser/ProcessProposal', request_serializer=Proposal.SerializeToString, response_deserializer=ProposalResponse.FromString, ) class EndorserServicer(object): def ProcessProposal(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_EndorserServicer_to_server(servicer, server): rpc_method_handlers = { 'ProcessProposal': grpc.unary_unary_rpc_method_handler( servicer.ProcessProposal, request_deserializer=Proposal.FromString, response_serializer=ProposalResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'protos.Endorser', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) class BetaEndorserServicer(object): def ProcessProposal(self, request, context): context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) class BetaEndorserStub(object): def ProcessProposal(self, request, timeout, metadata=None, with_call=False, protocol_options=None): raise NotImplementedError() ProcessProposal.future = None def beta_create_Endorser_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): request_deserializers = { ('protos.Endorser', 'ProcessProposal'): Proposal.FromString, } response_serializers = { ('protos.Endorser', 'ProcessProposal'): ProposalResponse.SerializeToString, } method_implementations = { ('protos.Endorser', 'ProcessProposal'): face_utilities.unary_unary_inline(servicer.ProcessProposal), } server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) return beta_implementations.server(method_implementations, options=server_options) def beta_create_Endorser_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): request_serializers = { ('protos.Endorser', 'ProcessProposal'): Proposal.SerializeToString, } response_deserializers = { ('protos.Endorser', 'ProcessProposal'): ProposalResponse.FromString, } cardinalities = { 'ProcessProposal': cardinality.Cardinality.UNARY_UNARY, } stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) return beta_implementations.dynamic_stub(channel, 'protos.Endorser', cardinalities, options=stub_options) # @@protoc_insertion_point(module_scope)
python
import torch as th import numpy as np from gym import Env from gym.spaces import Discrete, MultiDiscrete __all__ = [ "MatrixGameEnv" ] class MatrixGameEnv(Env): def __init__(self, matrices, reward_perturbation=0, rand: th.Generator = th.default_generator): super().__init__() matrices = th.as_tensor(matrices) reward_perturbation = th.as_tensor(reward_perturbation) # Check shape of transition matrix n_agents = matrices.dim()-1 if matrices.shape[0]!=n_agents: raise ValueError("Number of matrices does not match dimensions of each matrix") # Check shape of reward perturbation if reward_perturbation.shape!=() and reward_perturbation.shape!=(n_agents,): raise ValueError("Reward perturbation must be either same or specified for each agent") # Check values of reward perturbation if (reward_perturbation<0).any(): raise ValueError("Values of reward perturbation must be non-negative") ## State space self.observation_space = Discrete(1) ## Action space self.action_space = MultiDiscrete(matrices.shape[1:]) ## Matrices of the matrix game self.matrices = matrices ## Standard deviation of reward perturbation self.reward_perturbation = reward_perturbation ## Random number generator self.rand = rand def reset(self): return th.tensor(0) def step(self, actions): # Check validity of joint actions if not self.action_space.contains(np.array(actions)): raise ValueError("Joint actions {} is invalid".format(actions)) # Rewards for each agent rewards = self.matrices[(slice(None), *actions)].clone() # Add random perturbation to rewards reward_perturbation = self.reward_perturbation if (reward_perturbation!=0).all(): rewards += th.normal(0., reward_perturbation, generator=self.rand) # Step result return th.tensor(0), rewards, True, {}
python
from __future__ import division, absolute_import, print_function import sys if sys.version_info < (3,): range = xrange else: unicode = str import os from matplotlib import rc from matplotlib import rcParams font_size=14 rcParams["backend"] = "PDF" rcParams["figure.figsize"] = (4, 3) rcParams["font.family"] = "Serif" rcParams["font.serif"] = ["Palatino"] rcParams["font.size"] = font_size rcParams["axes.labelsize"] = font_size rcParams["xtick.labelsize"] = font_size - 2 rcParams["ytick.labelsize"] = font_size - 2 rcParams["legend.numpoints"] = 1 rcParams["legend.fontsize"] = "small" rcParams["lines.markersize"] = 4 rcParams["figure.subplot.right"] = 0.95 rcParams["figure.subplot.top"] = 0.95 rcParams["figure.subplot.right"] = 0.95 rcParams["figure.subplot.top"] = 0.95 rcParams["figure.subplot.left"] = 0.2 rcParams["figure.subplot.bottom"] = 0.2 rcParams["image.cmap"] = "hot" rcParams["text.usetex"] = True rcParams["ps.usedistiller"] = "xpdf" rcParams["pdf.compression"] = 9 rcParams["ps.useafm"] = True rcParams["path.simplify"] = True rcParams["text.latex.preamble"] = [#"\usepackage{times}", #"\usepackage{euler}", r"\usepackage{amssymb}", r"\usepackage{amsmath}"] import scipy import scipy.stats import numpy as np from pylab import * from numpy import * import graph_tool.all as gt import random as prandom figure() try: gt.openmp_set_num_threads(1) except RuntimeError: pass prandom.seed(42) np.random.seed(42) gt.seed_rng(42)
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- try: from ._models_py3 import AzureEntityResource from ._models_py3 import ComplianceStatus from ._models_py3 import ErrorDefinition from ._models_py3 import ErrorResponse, ErrorResponseException from ._models_py3 import HelmOperatorProperties from ._models_py3 import ProxyResource from ._models_py3 import Resource from ._models_py3 import ResourceProviderOperation from ._models_py3 import ResourceProviderOperationDisplay from ._models_py3 import Result from ._models_py3 import SourceControlConfiguration from ._models_py3 import SystemData from ._models_py3 import TrackedResource except (SyntaxError, ImportError): from ._models import AzureEntityResource from ._models import ComplianceStatus from ._models import ErrorDefinition from ._models import ErrorResponse, ErrorResponseException from ._models import HelmOperatorProperties from ._models import ProxyResource from ._models import Resource from ._models import ResourceProviderOperation from ._models import ResourceProviderOperationDisplay from ._models import Result from ._models import SourceControlConfiguration from ._models import SystemData from ._models import TrackedResource from ._paged_models import ResourceProviderOperationPaged from ._paged_models import SourceControlConfigurationPaged from ._source_control_configuration_client_enums import ( ComplianceStateType, MessageLevelType, OperatorType, OperatorScopeType, ProvisioningStateType, CreatedByType, ) __all__ = [ 'AzureEntityResource', 'ComplianceStatus', 'ErrorDefinition', 'ErrorResponse', 'ErrorResponseException', 'HelmOperatorProperties', 'ProxyResource', 'Resource', 'ResourceProviderOperation', 'ResourceProviderOperationDisplay', 'Result', 'SourceControlConfiguration', 'SystemData', 'TrackedResource', 'SourceControlConfigurationPaged', 'ResourceProviderOperationPaged', 'ComplianceStateType', 'MessageLevelType', 'OperatorType', 'OperatorScopeType', 'ProvisioningStateType', 'CreatedByType', ]
python
# 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 io import json import typing # TODO(slinkydeveloper) is this really needed? class EventGetterSetter(object): def CloudEventVersion(self) -> str: raise Exception("not implemented") # CloudEvent attribute getters def EventType(self) -> str: raise Exception("not implemented") def Source(self) -> str: raise Exception("not implemented") def EventID(self) -> str: raise Exception("not implemented") def EventTime(self) -> str: raise Exception("not implemented") def SchemaURL(self) -> str: raise Exception("not implemented") def Data(self) -> object: raise Exception("not implemented") def Extensions(self) -> dict: raise Exception("not implemented") def ContentType(self) -> str: raise Exception("not implemented") # CloudEvent attribute constructors # Each setter return an instance of its class # in order to build a pipeline of setter def SetEventType(self, eventType: str) -> object: raise Exception("not implemented") def SetSource(self, source: str) -> object: raise Exception("not implemented") def SetEventID(self, eventID: str) -> object: raise Exception("not implemented") def SetEventTime(self, eventTime: str) -> object: raise Exception("not implemented") def SetSchemaURL(self, schemaURL: str) -> object: raise Exception("not implemented") def SetData(self, data: object) -> object: raise Exception("not implemented") def SetExtensions(self, extensions: dict) -> object: raise Exception("not implemented") def SetContentType(self, contentType: str) -> object: raise Exception("not implemented") def SetSubject(self, subject: str) -> object: raise Exception("not implemented") class BaseEvent(EventGetterSetter): def Properties(self, with_nullable=False) -> dict: props = dict() for name, value in self.__dict__.items(): if str(name).startswith("ce__"): v = value.get() if v is not None or with_nullable: props.update({str(name).replace("ce__", ""): value.get()}) return props def Get(self, key: str) -> (object, bool): formatted_key = "ce__{0}".format(key.lower()) ok = hasattr(self, formatted_key) value = getattr(self, formatted_key, None) if not ok: exts = self.Extensions() return exts.get(key), key in exts return value.get(), ok def Set(self, key: str, value: object): formatted_key = "ce__{0}".format(key) key_exists = hasattr(self, formatted_key) if key_exists: attr = getattr(self, formatted_key) attr.set(value) setattr(self, formatted_key, attr) return exts = self.Extensions() exts.update({key: value}) self.Set("extensions", exts) def MarshalJSON(self, data_marshaller: typing.Callable) -> typing.IO: props = self.Properties() props["data"] = data_marshaller(props.get("data")) if not props["extensions"]: del props["extensions"] if props["data"] == 'null' or props["data"] is None: del props["data"] return io.BytesIO(json.dumps(props).encode("utf-8")) def UnmarshalJSON(self, b: typing.IO, data_unmarshaller: typing.Callable): raw_ce = json.load(b) for name, value in raw_ce.items(): if name == "data": value = data_unmarshaller(value) self.Set(name, value) def UnmarshalBinary( self, headers: dict, body: typing.IO, data_unmarshaller: typing.Callable ): for header, value in headers.items(): header = header.lower() if header == "content-type": self.SetContentType(value) elif header.startswith("ce-"): self.Set(header[3:], value) self.Set("data", data_unmarshaller(body)) def MarshalBinary( self, data_marshaller: typing.Callable ) -> (dict, object): headers = {} if self.ContentType(): headers["content-type"] = self.ContentType() props = self.Properties() for key, value in props.items(): if key not in ["data", "extensions", "contenttype"]: if value is not None: headers["ce-{0}".format(key)] = value for key, value in props.get("extensions").items(): headers["ce-{0}".format(key)] = value data, _ = self.Get("data") return headers, data_marshaller(data)
python
#!/usr/bin/env python3 import argparse import sys import logging from pathlib import Path from capanno_utils.validate import * from capanno_utils.validate_inputs import validate_inputs_for_instance from capanno_utils.helpers.validate_cwl import validate_cwl_tool from capanno_utils.helpers.get_paths import get_types_from_path def get_parser(): parser = argparse.ArgumentParser(description="Validate metadata and cwl files.") parser.add_argument('path', type=Path, help='Provide the path to validate. If a directory is specified, all content in the directory will be validated. If a file is specified, only that file will be validated.') parser.add_argument('-p', '--root-repo-path', dest='root_path', type=Path, default=Path.cwd(), help="Specify the root path of your cwl content repo if it is not the current working directory.") parser.add_argument('-q', '--quiet', dest='quiet', action='store_true', help="Silence messages to stdout") return parser def main(argsl=None): if not argsl: argsl = sys.argv[1:] parser = get_parser() args = parser.parse_args(argsl) # from pdb import set_trace; set_trace() if args.path.is_absolute(): full_path = args.path else: full_path = args.root_path / args.path base_type, specific_type = get_types_from_path(full_path, cwl_root_repo_name=args.root_path.name, base_path=args.root_path) if not args.quiet: print(f"Validating {str(full_path)} \n") if base_type == 'tool': # Check for file types. if specific_type == 'common_metadata': validate_parent_tool_metadata(full_path) elif specific_type == 'cwl': validate_cwl_tool(full_path) elif specific_type == 'metadata': validate_subtool_metadata(full_path) elif specific_type == 'instance': validate_inputs_for_instance(full_path) elif specific_type == 'instance_metadata': raise NotImplementedError # Check for directory types. elif specific_type == 'base_dir': validate_tools_dir(base_dir=args.root_path) elif specific_type == 'tool_dir': tool_name = full_path.parts[-1] validate_main_tool_directory(tool_name, base_dir=args.root_path) elif specific_type == 'version_dir': tool_name, version_name = full_path.parts[-2:] validate_tool_version_dir(tool_name, version_name, base_dir=args.root_path) elif specific_type == 'common_dir': tool_name, version_name = full_path.parts[-3:-1] validate_tool_comomon_dir(tool_name, version_name, base_dir=args.root_path) elif specific_type == 'subtool_dir': path_parts = full_path.parts tool_name, version_name = path_parts[-3:-1] subtool_name = path_parts[-1][len(tool_name) + 1:] if subtool_name == '': subtool_name = None validate_subtool_dir(tool_name, version_name, subtool_name, base_dir=args.root_path) elif specific_type == 'instance_dir': # Must do the same as validating a subtool directory. Could skip validating subtool metadata, but won't. Don't see use for that. path_parts = full_path.parts tool_name, version_name = path_parts[-4:-2] subtool_name = path_parts[-2][len(tool_name) + 1:] if subtool_name == '': subtool_name = None validate_subtool_dir(tool_name, version_name, subtool_name=subtool_name, base_dir=args.root_path) else: raise ValueError(f"") elif base_type == 'script': if specific_type == 'cwl': validate_cwl_tool(full_path) elif specific_type == 'metadata': validate_script_metadata(full_path) elif specific_type == 'instance': validate_inputs_for_instance(full_path) elif specific_type == 'instance_metadata': raise NotImplementedError # Check for directory types. elif specific_type == 'base_dir': validate_scripts_dir(base_dir=args.root_path) elif specific_type == 'group_dir': group_name = full_path.parts[-1] validate_group_scripts_dir(group_name, base_dir=args.root_path) elif specific_type == 'project_dir': group_name, project_name = full_path.parts[-2:] validate_project_scripts_dir(group_name, project_name, base_dir=args.root_path) elif specific_type == 'version_dir': group_name, project_name, version_name = full_path.parts[-3:] validate_version_script_dir(group_name, project_name, version_name, base_dir=args.root_path) elif specific_type == 'script_dir': group_name, project_name, version_name, script_name = full_path.parts[-4:] validate_script_dir(group_name, project_name, version_name, script_name, base_dir=args.root_path) elif specific_type == 'instance_dir': group_name, project_name, version_name, script_name = full_path.parts[-5:-1] validate_script_dir(group_name, project_name, version_name, script_name, base_dir=args.root_path) else: raise ValueError(f"") elif base_type == 'workflow': if specific_type == 'cwl': raise NotImplementedError elif specific_type == 'metadata': validate_workflow_metadata(full_path) elif specific_type == 'instance': raise NotImplementedError elif specific_type == 'instance_metadata': raise NotImplementedError else: raise ValueError(f"") elif base_type == 'repo_root': validate_repo(full_path) else: parser.print_help() if not args.quiet: print(f"{full_path} is valid.") return if __name__ == "__main__": sys.exit(main(sys.argv[1:]))
python
_base_ = [ '../../_base_/models/vision_transformer/vit_large_p16_sz224.py', '../../_base_/datasets/imagenet/swin_sz384_8xbs64.py', '../../_base_/default_runtime.py', ] # model model = dict(backbone=dict(img_size=384)) # data data = dict(imgs_per_gpu=64, workers_per_gpu=6) # additional hooks update_interval = 8 # 64 x 8gpus x 8 accumulates = bs4096 # optimizer optimizer = dict( type='AdamW', lr=0.003, # bs4096 weight_decay=0.3, paramwise_options={ '(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0.), 'bias': dict(weight_decay=0.), 'cls_token': dict(weight_decay=0.), 'pos_embed': dict(weight_decay=0.), }) # apex use_fp16 = False fp16 = dict(type='apex', loss_scale=dict(init_scale=512., mode='dynamic')) optimizer_config = dict( grad_clip=dict(max_norm=1.0), update_interval=update_interval, use_fp16=use_fp16) # lr scheduler lr_config = dict( policy='CosineAnnealing', by_epoch=False, min_lr=0, warmup='linear', warmup_iters=10000, warmup_ratio=1e-4, ) # runtime settings runner = dict(type='EpochBasedRunner', max_epochs=300)
python
from rest_framework import serializers from core.models import Link, Comment class LinkSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Link class CommentSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Comment
python
# Generated by Django 3.2.4 on 2021-06-23 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('timewebapp', '0044_alter_settingsmodel_first_login'), ] operations = [ migrations.AlterField( model_name='settingsmodel', name='first_login', field=models.BooleanField(default=True, verbose_name='Enable Tutorial'), ), ]
python
import pytest import os @pytest.mark.processor("gpu") @pytest.mark.model("placeholder") @pytest.mark.skip_cpu @pytest.mark.skip_py2_containers def test_placeholder(): pass
python
#!/usr/bin/env python ''' Experimental viewer for DAVIS + OpenXC data Author: J. Binas <[email protected]>, 2017 This software is released under the GNU LESSER GENERAL PUBLIC LICENSE Version 3. Usage: Play a file from the beginning: $ ./view.py <recorded_file.hdf5> Play a file, starting at X percent: $ ./view.py <recorded_file.hdf5> -s X% Play a file starting at second X $ ./view.py <recorded_file.hdf5> -s Xs ''' from __future__ import print_function import argparse import ctypes from argparse import RawTextHelpFormatter import numpy as np import h5py import cv2 import time import multiprocessing as mp import queue from queue import Empty from interfaces.caer import DVS_SHAPE, unpack_header, unpack_data from datasets import CHUNK_SIZE VIEW_DATA = { 'dvs', 'steering_wheel_angle', 'engine_speed', 'accelerator_pedal_position', 'brake_pedal_status', 'vehicle_speed', } # this changed in version 3 CV_AA = cv2.LINE_AA if int(cv2.__version__[0]) > 2 else cv2.CV_AA def _flush_q(q): ''' flush queue ''' while True: try: q.get(timeout=1e-3) except queue.Empty: if q.empty(): break class HDF5Stream(mp.Process): def __init__(self, filename, tables, bufsize=64): super(HDF5Stream, self).__init__() self.f = h5py.File(filename, 'r') self.tables = tables self.q = {k: mp.Queue(bufsize) for k in self.tables} self.run_search = mp.Event() self.exit = mp.Event() self.done = mp.Event() self.skip_to = mp.Value('L', 0) self._init_count() self._init_time() self.daemon = True self.start() def run(self): while self.blocks_rem and not self.exit.is_set(): blocks_read = 0 for k in list(self.blocks_rem): if self.q[k].full(): time.sleep(1e-6) continue i = self.block_offset[k] self.q[k].put(self.f[k]['data'][int(i*CHUNK_SIZE):int((i+1)*CHUNK_SIZE)]) self.block_offset[k] += 1 if self.blocks_rem[k].value: self.blocks_rem[k].value -= 1 else: self.blocks_rem.pop(k) blocks_read += 1 if not blocks_read: time.sleep(1e-6) if self.run_search.is_set(): self._search() self.f.close() print('closed input file') while not self.exit.is_set(): time.sleep(1e-3) # print('[DEBUG] flushing stream queues') for k in self.q: # print('[DEBUG] flushing', k) _flush_q(self.q[k]) self.q[k].close() self.q[k].join_thread() # print('[DEBUG] flushed all stream queues') self.done.set() print('stream done') def get(self, k, block=True, timeout=None): return self.q[k].get(block, timeout) def _init_count(self, offset={}): self.block_offset = {k: offset.get(k, 0) / CHUNK_SIZE for k in self.tables} self.size = {k: len(self.f[k]['data']) - v * CHUNK_SIZE for k, v in self.block_offset.items()} self.blocks = {k: v / CHUNK_SIZE for k, v in self.size.items()} self.blocks_rem = { k: mp.Value(ctypes.c_double, v) for k, v in self.blocks.items() if v} def _init_time(self): self.ts_start = {} self.ts_stop = {} self.ind_stop = {} for k in self.tables: ts_start = self.f[k]['timestamp'][self.block_offset[k]*CHUNK_SIZE] self.ts_start[k] = mp.Value('L', ts_start) b = self.block_offset[k] + self.blocks_rem[k].value - 1 while b > self.block_offset[k] and \ self.f[k]['timestamp'][b*CHUNK_SIZE] == 0: b -= 1 print(k, 'final block:', b) self.ts_stop[k] = mp.Value( 'L', self.f[k]['timestamp'][(b + 1) * CHUNK_SIZE - 1]) self.ind_stop[k] = b def init_search(self, t): ''' start streaming from given time point ''' if self.run_search.is_set(): return self.skip_to.value = np.uint64(t) self.run_search.set() def _search(self): t = self.skip_to.value offset = {k: self._bsearch_by_timestamp(k, t) for k in self.tables} for k in self.tables: _flush_q(self.q[k]) self._init_count(offset) # self._init_time() self.run_search.clear() def _bsearch_by_timestamp(self, k, t): '''performs binary search on timestamp, returns closest block index''' l, r = 0, self.ind_stop[k] print('searching', k, t) while True: if r - l < 2: print('selecting block', l) return l * CHUNK_SIZE if self.f[k]['timestamp'][(l + (r - l) / 2) * CHUNK_SIZE] > t: r = l + (r - l) / 2 else: l += (r - l) / 2 class MergedStream(mp.Process): ''' Unpacks and merges data from HDF5 stream ''' def __init__(self, fbuf, bufsize=256): super(MergedStream, self).__init__() self.fbuf = fbuf self.ts_start = self.fbuf.ts_start self.ts_stop = self.fbuf.ts_stop self.q = mp.Queue(bufsize) self.run_search = mp.Event() self.skip_to = mp.Value('L', 0) self._init_state() self.done = mp.Event() self.fetched_all = mp.Event() self.exit = mp.Event() self.daemon = True self.start() def run(self): while self.blocks_rem and not self.exit.is_set(): # find next event if self.q.full(): time.sleep(1e-4) continue next_k = min(self.current_ts, key=self.current_ts.get) self.q.put((self.current_ts[next_k], self.current_dat[next_k])) self._inc_current(next_k) # get new blocks if necessary for k in {k for k in self.blocks_rem if self.i[k] == CHUNK_SIZE}: self.current_blk[k] = self.fbuf.get(k) self.i[k] = 0 if self.blocks_rem[k]: self.blocks_rem[k] -= 1 else: self.blocks_rem.pop(k) self.current_ts.pop(k) if self.run_search.is_set(): self._search() self.fetched_all.set() self.fbuf.exit.set() while not self.fbuf.done.is_set(): time.sleep(1) # print('[DEBUG] waiting for stream process') while not self.exit.is_set(): time.sleep(1) # print('[DEBUG] waiting for merger process') _flush_q(self.q) # print('[DEBUG] flushed merger q ->', self.q.qsize()) self.q.close() self.q.join_thread() # print('[DEBUG] joined merger q') self.done.set() def close(self): self.exit.set() def _init_state(self): keys = self.fbuf.blocks_rem.keys() self.blocks_rem = {k: self.fbuf.blocks_rem[k].value for k in keys} self.current_blk = {k: self.fbuf.get(k) for k in keys} self.i = {k: 0 for k in keys} self.current_dat = {} self.current_ts = {} for k in keys: self._inc_current(k) def _inc_current(self, k): ''' get next event of given type and increment row pointer ''' row = self.current_blk[k][self.i[k]] if k == 'dvs': ts, d = caer_event_from_row(row) else: # vi event ts = row[0] * 1e-6 d = {'etype': k, 'timestamp': row[0], 'data': row[1]} if not ts and k in self.current_ts: self.current_ts.pop(k) self.blocks_rem.pop(k) return False self.current_ts[k], self.current_dat[k] = ts, d self.i[k] += 1 def get(self, block=False): return self.q.get(block) @property def has_data(self): return not (self.fetched_all.is_set() and self.q.empty()) @property def tmin(self): return self.ts_start['dvs'].value @property def tmax(self): return self.ts_stop['dvs'].value def search(self, t, block=True): if self.run_search.is_set(): return self.skip_to.value = np.uint64(t) self.run_search.set() def _search(self): self.fbuf.init_search(self.skip_to.value) while self.fbuf.run_search.is_set(): time.sleep(1e-6) _flush_q(self.q) self._init_state() self.q.put((0, {'etype': 'timestamp_reset'})) self.run_search.clear() class Interface(object): def __init__(self, tmin=0, tmax=0, search_callback=None, update_callback=None, create_callback=None, destroy_callback=None): self.tmin, self.tmax = tmin, tmax self.search_callback = search_callback self.update_callback = update_callback self.create_callback = create_callback self.destroy_callback = destroy_callback def _set_t(self, t): self.t_now = int(t - self.tmin) if self.update_callback is not None: self.update_callback(t) def close(self): if self.close_callback is not None: self.close_callback class Viewer(Interface): ''' Simple visualizer for events ''' def __init__(self, max_fps=40, zoom=1, rotate180=False, **kwargs): super(Viewer, self).__init__(**kwargs) self.zoom = zoom cv2.namedWindow('frame') # tobi added from https://stackoverflow.com/questions/21810452/ # cv2-imshow-command-doesnt-work-properly-in-opencv-python/ # 24172409#24172409 cv2.startWindowThread() cv2.namedWindow('polarity') ox = 0 oy = 0 cv2.moveWindow('frame', ox, oy) cv2.moveWindow('polarity', ox + int(448*self.zoom), oy) self.set_fps(max_fps) self.pol_img = 0.5 * np.ones(DVS_SHAPE) self.t_now = 0 self.t_pre = {} self.count = {} self.cache = {} self.font = cv2.FONT_HERSHEY_SIMPLEX self.display_info = True self.display_color = 0 self.playback_speed = 1. # seems to do nothing self.rotate180 = rotate180 # sets contrast for full scale event count for white/black self.dvs_contrast = 2 self.paused = False def set_fps(self, max_fps): self.min_dt = 1. / max_fps def show(self, d, t=None): # handle keyboad input key_pressed = cv2.waitKey(1) & 0xFF # http://www.asciitable.com/ if key_pressed != -1: if key_pressed == ord('i'): # 'i' pressed if self.display_color == 0: self.display_color = 255 elif self.display_color == 255: self.display_color = 0 self.display_info = not self.display_info print('rotated car info display') elif key_pressed == ord('x'): # exit print('exiting from x key') raise SystemExit elif key_pressed == ord('f'): # f (faster) key pressed self.min_dt = self.min_dt*1.2 print('increased min_dt to ', self.min_dt, ' s') # self.playback_speed = min(self.playback_speed + 0.2, 5.0) # print('increased playback speed to ',self.playback_speed) elif key_pressed == ord('s'): # s (slower) key pressed self.min_dt = self.min_dt/1.2 print('decreased min_dt to ', self.min_dt, ' s') # self.playback_speed = max(self.playback_speed - 0.2, 0.2) # print('decreased playback speed to ',self.playback_speed) elif key_pressed == ord('b'): # brighter self.dvs_contrast = max(1, self.dvs_contrast-1) print('increased DVS contrast to ', self.dvs_contrast, ' full scale event count') elif key_pressed == ord('d'): # brighter self.dvs_contrast = self.dvs_contrast+1 print('decreased DVS contrast to ', self.dvs_contrast, ' full scale event count') elif key_pressed == ord(' '): # toggle paused self.paused = not self.paused print('decreased DVS contrast to ', self.dvs_contrast, ' full scale event count') if self.paused: while True: key_paused = cv2.waitKey(1) or 0xff if key_paused == ord(' '): self.paused = False break ''' receive and handle single event ''' if 'etype' not in d: d['etype'] = d['name'] etype = d['etype'] if not self.t_pre.get(etype): self.t_pre[etype] = -1 self.count[etype] = self.count.get(etype, 0) + 1 if etype == 'frame_event' and \ time.time() - self.t_pre[etype] > self.min_dt: if 'data' not in d: unpack_data(d) img = (d['data'] / 256).astype(np.uint8) if self.rotate180 is True: # grab the dimensions of the image and calculate the center # of the image (h, w) = img.shape[:2] center = (w // 2, h // 2) # rotate the image by 180 degrees M = cv2.getRotationMatrix2D(center, 180, 1.0) img = cv2.warpAffine(img, M, (w, h)) if self.display_info: self._plot_steering_wheel(img) self._print(img, (50, 220), 'accelerator_pedal_position', '%') self._print(img, (100, 220), 'brake_pedal_status', 'brake', True) self._print(img, (200, 220), 'vehicle_speed', 'km/h') self._print(img, (300, 220), 'engine_speed', 'rpm') if t is not None: self._plot_timeline(img) if self.zoom != 1: img = cv2.resize( img, None, fx=self.zoom, fy=self.zoom, interpolation=cv2.INTER_CUBIC) cv2.imshow('frame', img) # cv2.waitKey(1) self.t_pre[etype] = time.time() elif etype == 'polarity_event': if 'data' not in d: unpack_data(d) # makes DVS image, but only from latest message self.pol_img[d['data'][:, 2], d['data'][:, 1]] += \ (d['data'][:, 3]-.5)/self.dvs_contrast if time.time() - self.t_pre[etype] > self.min_dt: if self.zoom != 1: self.pol_img = cv2.resize( self.pol_img, None, fx=self.zoom, fy=self.zoom, interpolation=cv2.INTER_CUBIC) if self.rotate180 is True: # grab the dimensions of the image and # calculate the center # of the image (h, w) = self.pol_img.shape[:2] center = (w // 2, h // 2) # rotate the image by 180 degrees M = cv2.getRotationMatrix2D(center, 180, 1.0) self.pol_img = cv2.warpAffine(self.pol_img, M, (w, h)) if self.display_info: self._print_string(self.pol_img, (25, 25), "%.2fms"%(self.min_dt*1000)) cv2.imshow('polarity', self.pol_img) # cv2.waitKey(1) self.pol_img = 0.5 * np.ones(DVS_SHAPE) self.t_pre[etype] = time.time() elif etype in VIEW_DATA: if 'data' not in d: d['data'] = d['value'] self.cache[etype] = d['data'] self.t_pre[etype] = time.time() if t is not None: self._set_t(t) def _plot_steering_wheel(self, img): if 'steering_wheel_angle' not in self.cache: return c, r = (173, 130), 65 # center, radius a = self.cache['steering_wheel_angle'] a_rad = + a / 180. * np.pi + np.pi / 2 if self.rotate180: a_rad = np.pi-a_rad t = (c[0] + int(np.cos(a_rad) * r), c[1] - int(np.sin(a_rad) * r)) cv2.line(img, c, t, self.display_color, 2, CV_AA) cv2.circle(img, c, r, self.display_color, 1, CV_AA) cv2.line(img, (c[0]-r+5, c[1]), (c[0]-r, c[1]), self.display_color, 1, CV_AA) cv2.line(img, (c[0]+r-5, c[1]), (c[0]+r, c[1]), self.display_color, 1, CV_AA) cv2.line(img, (c[0], c[1]-r+5), (c[0], c[1]-r), self.display_color, 1, CV_AA) cv2.line(img, (c[0], c[1]+r-5), (c[0], c[1]+r), self.display_color, 1, CV_AA) cv2.putText( img, '%0.1f deg' % a, (c[0]-35, c[1]+30), self.font, 0.4, self.display_color, 1, CV_AA) def _print(self, img, pos, name, unit, autohide=False): if name not in self.cache: return v = self.cache[name] if autohide and v == 0: return cv2.putText( img, '%d %s' % (v, unit), (pos[0]-40, pos[1]+20), self.font, 0.4, self.display_color, 1, CV_AA) def _print_string(self, img, pos, string): cv2.putText( img, '%s' % string, (pos[0], pos[1]), self.font, 0.4, self.display_color, 1, CV_AA) def _plot_timeline(self, img): pos = (50, 10) p = int(346 * self.t_now / (self.tmax - self.tmin)) cv2.line(img, (0, 2), (p, 2), 255, 1, CV_AA) cv2.putText( img, '%d s' % self.t_now, (pos[0]-40, pos[1]+20), self.font, 0.4, self.display_color, 1, CV_AA) def close(self): cv2.destroyAllWindows() class Controller(Interface): def __init__(self, filename, **kwargs): super(Controller, self).__init__(**kwargs) cv2.namedWindow('control') cv2.moveWindow('control', 400, 698) self.f = h5py.File(filename, 'r') self.tmin, self.tmax = self._get_ts() self.len = int(self.tmax - self.tmin) + 1 img = np.zeros((100, self.len)) self.plot_pixels(img, 'headlamp_status', 0, 10) self.plot_line(img, 'steering_wheel_angle', 20, 30) self.plot_line(img, 'vehicle_speed', 69, 30) self.width = 978 self.img = cv2.resize( img, (self.width, 100), interpolation=cv2.INTER_NEAREST) cv2.setMouseCallback('control', self._set_search) self.t_pre = 0 self.update(0) self.f.close() def update(self, t): self._set_t(t) t = int(float(self.width) / self.len * (t - self.tmin)) if t == self.t_pre: return self.t_pre = t img = self.img.copy() img[:, :t+1] = img[:, :t+1] * 0.5 + 0.5 cv2.imshow('control', img) cv2.waitKey(1) def plot_line(self, img, name, offset, height): x, y = self.get_xy(name) if x is None: return y -= y.min() y = y / y.max() * height x = x.clip(0, self.len - 1) img[offset+height-y.astype(int), x] = 1 def plot_pixels(self, img, name, offset=0, height=1): x, y = self.get_xy(name) if x is None: return img[offset:offset+height, x] = y def _set_search(self, event, x, y, flags, param): if event != cv2.EVENT_LBUTTONDOWN: return t = self.len * 1e6 * x / float(self.width) + self.tmin * 1e6 self._search_callback(t) def _get_ts(self): ts = self.f['dvs']['timestamp'] tmin = ts[0] i = -1 while ts[i] == 0: i -= 1 tmax = ts[i] print('tmin/tmax', tmin, tmax) return int(tmin * 1e-6), int(tmax * 1e-6) def get_xy(self, name): d = self.f[name]['data'] print('name', name) gtz_ids = d[:, 0] > 0 if not gtz_ids.any(): return None, 0 gtz = d[gtz_ids, :] return (gtz[:, 0] * 1e-6 - self.tmin).astype(int), gtz[:, 1] def caer_event_from_row(row): ''' Takes binary dvs data as input, returns unpacked event data or False if event type does not exist. ''' sys_ts, head, body = (v.tobytes() for v in row) if not sys_ts: # rows with 0 timestamp do not contain any data return 0, False d = unpack_header(head) d['dvs_data'] = body return int(sys_ts) * 1e-6, unpack_data(d) if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter) parser.add_argument('filename') parser.add_argument('--start', '-s', type=str, default=0., help="Examples:\n" "-s 50%% - play file starting at 50%%\n" "-s 66s - play file starting at 66s") parser.add_argument('--rotate', '-r', type=bool, default=True, help="Rotate the scene 180 degrees if True, " "Otherwise False") args = parser.parse_args() fname = args.filename c = Controller(fname,) m = MergedStream(HDF5Stream(fname, VIEW_DATA)) c._search_callback = m.search t = time.time() t_pre = 0 t_offset = 0 r180 = args.rotate # r180arg = "-r180" print('recording duration', (m.tmax - m.tmin) * 1e-6, 's') # direct skip by command line # parse second argument try: second_opt = args.start n_, type_ = second_opt[:-1], second_opt[-1] if type_ == '%': m.search((m.tmax - m.tmin) * 1e-2 * float(n_) + m.tmin) elif type_ == 's': m.search(float(n_) * 1e6 + m.tmin) except: pass v = Viewer(tmin=m.tmin * 1e-6, tmax=m.tmax * 1e-6, zoom=1.41, rotate180=r180, update_callback=c.update) # run main loop ts_reset = False while m.has_data: try: sys_ts, d = m.get() # except Queue.Empty: except Empty: continue if not d: continue if d['etype'] == 'timestamp_reset': ts_reset = True continue if not d['etype'] in {'frame_event', 'polarity_event'}: v.show(d) continue if d['timestamp'] < t_pre: print('[WARN] negative dt detected!') t_pre = d['timestamp'] if ts_reset: print('resetting timestamp') t_offset = 0 ts_reset = False if not t_offset: t_offset = time.time() - d['timestamp'] print('setting offset', t_offset) t_sleep = max(d['timestamp'] - time.time() + t_offset, 0) time.sleep(t_sleep) v.show(d, sys_ts) if time.time() - t > 1: print(chr(27) + "[2J") t = time.time() print('fps:\n', '\n'.join( [' %s %s' % ( k.ljust(20), v_) for k, v_ in v.count.items()])) v.count = {k: 0 for k in v.count}
python
from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from pages.top_bars.top_navigate_bar import TopNavigateBar class TemplatesPage(TopNavigateBar): """ Templates page - contains variety of templates to select """ _TEMPLATES_BLOCK = (By.CSS_SELECTOR, "#template-gallery tbody tr") _CHOOSE_BUTTON = (By.CSS_SELECTOR, "a .btn.btn-primary") def __init__(self, driver): super().__init__(driver) def choose_template(self, template_name): self._wait.until( expected_conditions.visibility_of_all_elements_located(self._TEMPLATES_BLOCK)) templates = self._wait.until(expected_conditions.visibility_of_all_elements_located(self._TEMPLATES_BLOCK)) for template in templates: if template_name in template.text: button = template.find_element(*self._CHOOSE_BUTTON) self.move_to_element(button) button.click() break
python
#Hall bar geometry device. Measurements have r_xx and/or r_xy import numpy as np import matplotlib.pyplot as plt import warnings from scipy.signal import savgol_filter from pylectric.analysis import mobility from scipy import optimize as opt class Meas_GatedResistance(): """Class to handle a single sweep of raw data. Measures resistance against gate voltage to infer properties.""" def __init__(self, data, Cg, L, W, D = None): """ Takes numpy array of the form array[rows, columns] Requires columns to be of the form: [V_gate (Volts), Resistance (Ohms)] Also takes Length L, Width W, and Thickness D to infer scaled material properties. If 2D materials, thickness can be left as None, and units don't matter. If 3D, thickness should in cm units (assuming L & W cancel out). """ #1. Cols = [V_gate, Resistance] self.raw_data = np.array(data, np.longfloat).copy() self.conductivity_data = self.raw_data.copy()[:,0:2] #Note, Resistance = Resistivity * L / (W * D) -> Conductivity = 1/Resistance * L / (W * D) self.conductivity_data[:,1] = np.reciprocal(self.conductivity_data[:,1] * W / L) if D is None else np.reciprocal(self.conductivity_data[:,1] * W * D / L) self.L = L self.W = W self.D = D self.Cg = Cg self.is2D = (D is None) def mobility_dtm_2D(self, graph = True, ax=None, graph_kwargs = None, vg_offset = 0): """ Calculates the direct transconductance method mobility. Requires the gate capacitance (Farads). Returns Mobility and a graph if parameter is True. Mobility units are cm$^2$V$^{-1}$s${-1}$""" #Return Analysis gate voltage mu_dtm_2D = mobility.mobility_gated_dtm(self.conductivity_data.copy(), self.Cg) #Graphing if graph: #Check if graph to paste onto: if ax: #exists fig = ax.get_figure() else: #create new graph fig, (ax) = plt.subplots(1,1) #Plot ax.scatter(mu_dtm_2D[:,0] - vg_offset, mu_dtm_2D[:,1], **graph_kwargs) ax.set_xlabel("Gate voltage (V)") ax.set_ylabel("Mobility (cm$^2$V$^{-1}$s${-1}$)") return (mu_dtm_2D, fig) else: return mu_dtm_2D def conductivity_min(self): """ Finds the minimum value of conductivity and returns the index. """ min = np.min(self.conductivity_data[:,1]) index = np.where(self.conductivity_data[:,1] == min)[0][0] return index def discrete_sample_voltages(self, gate_voltages=None, center_voltage = 0, tollerance = 0.01): """ Acquires a subset of resitivities, corresponding to gate voltages. Useful for tracking temperature behaviour over multiple samples. Matches requested voltage to within tollerance, from a central voltage. """ #Default sampling if no list provided. if gate_voltages is None: gate_voltages = [-50,-40,-30,-20,-15,-10,-7.5,-5,-3,-2,-1,0,1,2,3,5,7.5,10,15,20,30,40,50] #Resistsances and gate voltages rvg_sampled = [] #Find for gv in gate_voltages: vdelta = np.abs(self.conductivity_data[:,0] - center_voltage - gv) v_i = np.where(vdelta == np.min(vdelta))[0][0] if vdelta[v_i] < tollerance: #Offset center voltage, and take reciporical of conductivity for resistivity. rvg_sampled.append([self.conductivity_data[v_i,0]-center_voltage, 1.0/self.conductivity_data[v_i,1]]) else: rvg_sampled.append([gv, np.nan]) #Add a NAN value to the array because value out of range. rvg_sampled = np.array(rvg_sampled) return rvg_sampled def discrete_interpolated_voltages(self, gate_voltages=None, center_voltage = 0): """ Acquires a subset of resitivities, corresponding to gate voltages. Useful for tracking temperature behaviour over multiple samples. Matches requested voltage to within tollerance, from a central voltage. """ cv = center_voltage #Default sampling if no list provided. if gate_voltages is None: gate_voltages = [-50,-40,-30,-20,-15,-10,-7.5,-5,-3,-2,-1,0,1,2,3,5,7.5,10,15,20,30,40,50] #Resistsances and gate voltages rvg_sampled = [] #Find for gv in gate_voltages: vraw = self.conductivity_data[:,0] - center_voltage - gv vdelta = np.abs(vraw) v_i = np.where(vdelta == np.min(vdelta))[0][0] if vdelta[v_i] == 0: #Offset center voltage, and take reciporical of conductivity for resistivity. rvg_sampled.append([self.conductivity_data[v_i,0]-center_voltage, 1.0/self.conductivity_data[v_i,1]]) else: if not (v_i < 1 or v_i > len(self.conductivity_data)-2): #check endpoint condition # Interpolate data if not endpoints: B1 = self.conductivity_data[v_i,:] if vdelta[v_i + 1] < vdelta[v_i - 1]: #smaller is better for interpolation, closer to dirac point. B2 = self.conductivity_data[v_i + 1,:] else: B2 = self.conductivity_data[v_i - 1,:] #re-arranged gv = (alpha * (B1-cv) + (1-alpha) * (B2-cv)), finding linear interpolation. alpha = (gv - (B2[0] - cv)) / (B1[0] - B2[0]) # Saftey check for result consistency. if alpha < 0 or alpha > 1: raise(ValueError("Calculation of linear interpolation factor (alpha = " + str(alpha) + ") is outside (0,1).")) #Interolate inter_v = (alpha * (B1[0] - cv)) + ((1-alpha) * (B2[0] - cv)) inter_resistivity = 1.0/(alpha * (B1[1]) + (1-alpha) * (B2[1])) #append rvg_sampled.append([inter_v, inter_resistivity]) #Add a NAN value to the array because value out of range. else: rvg_sampled.append([gv, np.nan]) #Add a NAN value to the array because value out of range. rvg_sampled = np.array(rvg_sampled) return rvg_sampled def global_RVg_fit(self, fit_function, params, boundsU=None, boundsL=None): """ Public function for globally fitting to the R Vg data. Fits to initial provided temperature and gate voltage dependent resistivity. """ return Meas_GatedResistance.__fit(vg=self.conductivity_data[:,0], sigma=self.conductivity_data[:,1], fit_function=fit_function, x0=params, boundsU=boundsU, boundsL=boundsL) def __fit(fit_function, vg, sigma, x0, boundsU=None, boundsL=None): """ Private method to generate a fit to Sigma Vg data, not object specific. Requires 1D arrays of gate voltage and conductivity (sigma). """ #Check that shapes match: vg = np.array(vg, dtype=np.longfloat) sigma = np.array(sigma, dtype=np.longfloat) #conditions if not (vg.shape == sigma.shape and len(vg.shape) == 1): raise ValueError("Either Vg or Sigma arrays do not match in shape, or are not one-dimensional.") params, covar = opt.curve_fit(fit_function, xdata=vg, ydata=sigma, p0=x0 ,bounds=(boundsL, boundsU)) return params, covar ################### PLOTTING PARAMETERS ######################## def __scatterVG(data, ax = None, s=1, c=None, label=None, style=None, vg_offset = 0, scatter=True): if ax is None: fig, (ax1) = plt.subplots(1,1) else: ax1 = ax ax1.set_title("Electronic transport") ax1.set_xlabel("Gate Voltage (V)") ax1.tick_params(direction="in") if c is None: c = plt.rcParams['axes.prop_cycle'].by_key()['color'][0] if style != None: if scatter: ax1.scatter(data[:,0] - vg_offset, data[:,1], style, label=label, s=s, c=c) else: ax1.plot(data[:,0] - vg_offset, data[:,1], style, label=label, linewidth=s, c=c) else: if scatter: ax1.scatter(data[:,0] - vg_offset, data[:,1], label=label, s=s, c=c) else: ax1.plot(data[:,0] - vg_offset, data[:,1], label=label, linewidth=s, c=c) return ax1 def plot_R_vG(self, ax = None, c = None, s=1, label="", vg_offset = 0, scatter=True): """Plots the raw resistance data versus gate voltage""" # Plot Resistance ax1 = Meas_GatedResistance.__scatterVG(self.raw_data[:,0:2], ax=ax, s=s, c=c, label=label, vg_offset=vg_offset, scatter=scatter) # Generate Label ax1.set_ylabel("Resistance ($\Omega$)") return ax1 def plot_Rho_vG(self, ax = None, c = None, s=1, label="", style=None, vg_offset = 0, scatter=True): """Plots the scaled resitivity data versus gate voltage""" # Calculate resistivity Rho = np.reciprocal(self.conductivity_data[:,1]) # Plot restivitiy ax1 = Meas_GatedResistance.__scatterVG(np.c_[self.conductivity_data[:,0], Rho], ax=ax, s=s, c=c, label=label, style=style, vg_offset=vg_offset, scatter=scatter) # Generate 2D/3D Label ax1.set_ylabel("Resisitivity ($\Omega$)") if self.is2D else ax1.set_ylabel("Resisitivity ($\Omega$ cm)") return ax1 def plot_C_vG(self, ax = None, c = None, s=1, label="", vg_offset = 0, scatter=True): """Plots the raw conductance data versus gate voltage""" # Calculate conductance conductance = np.reciprocal(self.raw_data[:,1]) # Plot conductance ax1 = Meas_GatedResistance.__scatterVG(np.c_[self.raw_data[:,0], conductance], ax=ax, s=s, c=c, label=label, vg_offset=vg_offset, scatter=scatter) # Generate Label ax1.set_ylabel("Conductivity (S)") return ax1 def plot_Sigma_vG(self, ax = None, c = None, s=1, label="", vg_offset = 0, scatter=True): """Plots the scaled conductivity data versus gate voltage""" ax1 = Meas_GatedResistance.__scatterVG(self.conductivity_data[:,0:2], ax=ax, s=s, c=c, label=label, vg_offset=vg_offset, scatter=scatter) ax1.set_ylabel("Conductivity (S)") if self.is2D else ax1.set_ylabel("Conductivity (S cm$^{1}$)") return ax1 class Meas_Temp_GatedResistance(): """ Class to handle temperature indexed multiple sweeps of gated data. Measures resistance against gate voltage and temperature to infer properties.""" def __init__(self, temps, vg, resistivity, is2D = True): """ Takes 1D arrays of temperature and gate voltage, and a 2D array (temp, voltage) of corresponding resitivities. """ self.temps = np.array(temps) self.vg = np.array(vg) self.resistivity = np.array(resistivity) self.ylabel = "Resistivity ($\Omega$)" if is2D else "Resistivity ($\Omega$m)" ### Check for null columns or rows in resistivity data. # Clone original resistances new_res = np.copy(self.resistivity) new_vg = np.copy(self.vg) new_temps = np.copy(self.temps) # Find temperatures which are all Vg are null slices = [] for k in range(self.resistivity.shape[0]): if np.all(np.isnan(self.resistivity[k,:])==True): slices.append(k) if len(slices) > 0: warnings.warn("Warning: Rows corresponding to T = " + str(self.temps[slices]) + " only contain NaN values, and are being removed.") new_res = np.delete(new_res, slices, axis=0) new_temps = np.delete(new_temps, slices) # Find voltages which all temperatures are null slices2 = [] for l in range(self.resistivity.shape[1]): if np.all(np.isnan(self.resistivity[:,l])==True): slices2.append(l) if len(slices2) > 0: warnings.warn("Warning: Columns corresponding to Vg = " + str(self.vg[slices2]) + " only contain NaN values, and are being removed.") new_res = np.delete(new_res, slices2, axis=1) new_vg = np.delete(new_vg, slices2) # Set arrays to new object. if len(slices) > 0 or len(slices2) > 0: self.vg = new_vg self.temps = new_temps self.resistivity = new_res #Check dimensions matchup. if not (self.temps.shape[0] == self.resistivity.shape[0] and self.vg.shape[0] == self.resistivity.shape[1]): raise ValueError("Dimension mismatch: Temperature and gate voltage arrays didn't match dimensions of resisitivty array.") return def plot_Rho_vT(self, ax=None, c=None, labels=None, singleLabel=None, offsets=None, hollow=False, **kwargs): """ Generic scatter plot for resistance vs gate voltage. Colours length has to match length of voltages. """ if c is not None and (len(self.vg) > len(c) or (labels is not None and len(self.vg) != len(labels))): raise(AttributeError("There is a mismatch betweeen the number of colours (" + str(len(c)) +"), voltages (" + str(len(self.vg)) + "), and labels (" + str(len(labels)) + ").")) if offsets is not None: if len(offsets) != len(self.vg): raise(AttributeError("There is a mismatch betweeen the number of offsets (" + str(len(offsets)) + ") and the number of voltages (" + str(len(self.vg)) + ")")) else: offsets = [0 for vg in self.vg] if ax is None: fig, (ax1) = plt.subplots(1,1) else: ax1 = ax # kwargs if c is None: c = plt.rcParams['axes.prop_cycle'].by_key()['color'] for i in range(len(self.vg)): #Colour: c_i = c[i % len(c)] kwargs["edgecolors"]=c_i kwargs["c"]=c_i if hollow and "c" in kwargs: kwargs.pop("c") elif not hollow and "edgecolors" in kwargs: kwargs.pop("edgecolors") #Labels: if singleLabel is not None: if i == 0: label=singleLabel else: label=None else: if labels is None: vg = self.vg[i] label="%0.02f" % vg else: label=labels[i] kwargs["label"]=label # Boom. ax1.scatter(self.temps, self.resistivity[:,i] - offsets[i], **kwargs) ax1.set_xlabel("Temperature (K)") ax1.set_ylabel(self.ylabel) return ax1 def global_RTVg_fit(self, fit_function, params, boundsU=None, boundsL=None): """ Public function for globally fitting to the RTVg data. Fits to initial provided temperature and gate voltage dependent resistivity. """ return Meas_Temp_GatedResistance.__fit(temps=self.temps, vg=self.vg, data=self.resistivity, fit_function=fit_function, x0=params, boundsU=boundsU, boundsL=boundsL) def global_RTVg_plot(self, function, params, ax=None, c=None, linewidth=1, labels=None, points=100, style='', singleLabel=None, offsets=None, T_max=None): """ Generic plotting function for parameter set of function. Similar to __fit, requires """ if ax is None: fig, (ax1) = plt.subplots(1,1) else: ax1 = ax #Check if `offset`s exist for each gate voltage. If not generate 0 values. if offsets is not None: if len(offsets) != len(self.vg): raise(AttributeError("There is a mismatch betweeen the number of offsets (" + str(len(offsets)) + ") and the number of voltages (" + str(len(self.vg)) + ")")) else: offsets = [0 for vg in self.vg] # ax1.set_title("Electronic transport") ax1.set_xlabel("Temperature (K)") ax1.set_ylabel(self.ylabel) ax1.tick_params(direction="in") if T_max is None: max_t = np.max(self.temps) else: max_t = T_max min_t = np.min(self.temps) fit_temps = np.linspace(min_t, max_t, points) #Arbitrary 100 plot points to look smooth. #Reshape inputs: First index is temp, second index is vg T = np.array([np.array(fit_temps) for i in range(len(self.vg))], dtype=np.longfloat) #Resize temp list for each vg. VG = np.array([np.array(self.vg) for i in range(len(fit_temps))], dtype=np.longfloat).T #Resize VG list for each temp. #Reshape inputs into 1D arrays: T_1D = np.reshape(T, (-1)) VG_1D = np.reshape(VG, (-1)) X = (T_1D, VG_1D) #Calculate function output param_resistivity = function(X, *params) self.last_vg = VG_1D self.last_T = T_1D self.last_res = param_resistivity #Plot result if c is None: c = plt.rcParams['axes.prop_cycle'].by_key()['color'] for i in range(len(self.vg)): c_i = c[i % len(c)] param_resistivity_subset = param_resistivity[i*len(fit_temps):(i+1)*len(fit_temps)] if singleLabel is not None: if i==0: ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, label=str(singleLabel), c=c_i) else: ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, c=c_i) else: if labels is None: ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, label=str(self.vg[i]), c=c_i) else: ax1.plot(fit_temps, param_resistivity_subset - offsets[i], style, linewidth=linewidth, label=labels[i], c=c_i) return def __fit(temps, vg, data, fit_function, x0, boundsU=None, boundsL=None): """ Private method to generate a fit to RVT data, not object specific. Requires 1D arrays of temperature, gate voltage, and a 2D matching array of data. This function reshapes into a 1D array for T, VG and Data, for the curve fit method to run. """ #Reshape inputs: First index is temp, second index is vg T = np.array([np.array(temps) for i in range(len(vg))], dtype=np.longfloat) #Resize temp list for each vg. VG = np.array([np.array(vg) for i in range(len(temps))], dtype=np.longfloat).T #Resize VG list for each temp. #Reshape inputs into 1D arrays: T_1D = np.reshape(T, (-1)) VG_1D = np.reshape(VG, (-1)) data_1D = np.reshape(data.T, (-1)) #Define warning strings. tmsg = "Warning: Some temperatures were 'NaN' value; %0.0d datalines have been removed (of total %0.0d)." vmsg = "Warning: Some voltages were 'NaN' value; %0.0d datalines have been removed (of total %0.0d)." rmsg = "Warning: Some resistances were 'NaN' value; %0.0d datalines have been removed (of total %0.0d)." xmsg = "Warning: Some initial params were 'NaN' value; %0.0d param values have been set to initialize at 0 (of total %0.0d params)." #Find any NaN data in the reshaped input. nans = np.where(np.isnan(T_1D))[0] # Remove NaN data if len(nans) > 0: T_1D = np.delete(T_1D, nans) VG_1D = np.delete(VG_1D, nans) data_1D = np.delete(data_1D, nans) warnings.warn(tmsg % (len(nans), len(T_1D))) #Repeat nans = np.where(np.isnan(VG_1D))[0] if len(nans) > 0: T_1D = np.delete(T_1D, nans) VG_1D = np.delete(VG_1D, nans) data_1D = np.delete(data_1D, nans) warnings.warn(vmsg % (len(nans), len(VG_1D))) #Repeat nans = np.where(np.isnan(data_1D))[0] if len(nans) > 0: T_1D = np.delete(T_1D, nans) VG_1D = np.delete(VG_1D, nans) data_1D = np.delete(data_1D, nans) warnings.warn(rmsg % (len(nans), len(data_1D))) # Check if nans in x0 as a reuslt too: nans = np.where(np.isnan(x0))[0] if len(nans) > 0: warnings.warn(xmsg % (len(nans), len(x0))) x0 = np.nan_to_num(x0) #Now fit data! params, covar = opt.curve_fit(fit_function, xdata=(T_1D, VG_1D), ydata=np.array(data_1D,dtype=np.longfloat), p0=x0 ,bounds=(boundsL, boundsU)) return params, covar
python
import pyautogui import time while True: initial_mouse = pyautogui.position() time.sleep(0.5) final_mouse = pyautogui.position() print(initial_mouse) print(final_mouse) if initial_mouse != final_mouse: pyautogui.hotkey("alt","tab") else: exit
python
''' Crie um programa: Leia o nome de um aluno leia duas notas do aluno guarde em uma lista composta no final mostre: Um boletim contendo: A média de cada um permita que o usuário possa mostrar as notas de cada aluno individualmente ''' alunos = list() while True: nome = str ( input ( 'Qual seu Nome: ' ) ) nota1 = float ( input ( 'Nota 1: ' ) ) nota2 = float ( input ( 'Nota 2: ' ) ) media = (nota1 + nota1) / 2 alunos.append( [ nome, [ nota1, nota2 ], media] ) resp = str ( input ( 'Quer Continuar? [S/N] ' ) ) if resp in 'Nn': break print('-=' * 30) print(f'{"No.":<4} {"NOME":<10} {"Média":>8}') print('-' * 26) for indice, aluno in enumerate(alunos): print(f'{indice:<4} {aluno[0]:<10} {aluno[2]:>8.1f} \n') print(alunos) while True: print('_' * 35) opcao = int ( input ( 'Mostrar Notas de Qual Aluno? [999 Para Sair]: ' ) ) if opcao == 999: print('Finalizando...') break if opcao <= len(alunos) - 1: print(f'Notas de {alunos[opcao][0]} são {alunos[opcao][1]}')
python
""" pyTRIS ------ pyTRIS - a simple API wrapper for Highways England's WebTRIS Traffic Flow API. """ from .api import API from . import models __all__ = ['API']
python
# -*- coding: utf-8 -*- """ created by huash06 at 2015-04-15 08:45 Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 如果是求不连续的字串 方法1: 令f(i,j)表示s[i:j+1]的最长回文的长度 if s[i]==s[j]: f(i,j) = f(i+1, j-1) else: f(i,j) = max(f(i+1,j), f(i,j-1)) 方法2: 反转s得到rs,然后求s和rs的最长公共子串 """ __author__ = 'huash06' import sys import os import datetime import functools import itertools import collections class Solution: # @param s, a string # @return a string def longestPalindrome(self, s): if not s: return '' starttime = datetime.datetime.now() result = s[0] rlen = 2 for i in range(len(s)): for j in range(i+rlen+1, len(s)): if self.isPalindrome(s[i:j]): if j-i > rlen: rlen = j-i result = s[i:j] print('Time Cost: {}'.format(datetime.datetime.now()-starttime)) return result def longestPalindrome_byval(self, s): if not s: return '' diff = [0] * len(s) for i in range(1, len(s)): diff[i] = s[i]-s[i-1] count = [0]*len(s) start = 0 for i in range(len(s)): count[i] = diff[i]+diff[i-1] def span(self, s): """ 比manacher稍微慢点的方法 :param s: :return: """ if not s: return '' span = [0] * (len(s) * 2) for i in range(len(s)): a, b = i, i span[a + b] = self.calSpan(s, a, b) if i < len(s) - 1: a, b = i, i+1 span[a + b] = self.calSpan(s, a, b) for plen in range(len(s), 0, -1): for i in range(len(s)-plen+1): j = i + plen-1 if self.isPalindrome2(span, i, j): return s[i: j+1] return s[0] def isPalindrome2(self, span, a, b): return span[a+b] >= b - a def calSpan(self, s, a, b): while a >= 0 and b < len(s) and s[a] == s[b]: a -= 1 b += 1 return b - 1 - (a + 1) def manacher(self, s): if not s: return '' starttime = datetime.datetime.now() hs = '$#' for char in s: hs += char + '#' # print(hs) p = [0] * len(hs) mx = 0 mid = 0 for i in range(1, len(hs)-1): if mx > i: # ---mx'------j------mid------i------mx--- # 以mid为中心的最长回文串的右边部分延伸到mx # 1. 如果以j为中心的回文的右边延伸到位置jr==j+p[j]+, # 并且i+p[j]<mx, 可以确定以i为中心的回文字符串至少可以延伸到ir=i+p[j], # 这是因为[jl:jr] 与 [il:ir]关于mid对称 # ---mx'----jl--j--jr----mid----il--i--ir----mx--- # 2. 通过#1能够确定的i的最长右边界是mx,所以取 min(p[2*mid-i], mx-i) # 3. 通过#1,#2可以确定以i为中心的回文串至少可以延伸到的位置,然后继续向右 # 查找看是否能够继续延伸 p[i] = min(p[2*mid-i], mx-i) else: p[i] = 1 # print(p[i]) # corresponding to #3 while i+p[i] < len(hs) and \ i-p[i] > 0 and \ hs[i+p[i]] == hs[i-p[i]]: p[i] += 1 # print(p[i]) if p[i] > mx-mid: mx = p[i]+i mid = i # print(' '.join(list(map(str, p)))) # print('mid {} mx {}'.format(mid, mx)) result = '' for i in range(2*mid-mx+1, mx): if hs[i] != '#': result += hs[i] # print('Time Cost: {}'.format(datetime.datetime.now() - starttime)) return result def longestPalindrome_dp(self, s): """ 动态规划求不连续的子序列 :param s: :return: """ if not s: return '' starttime = datetime.datetime.now() dpa = [[1 for c in range(len(s))] for r in range(len(s))] # dpa = collections.defaultdict(int) for i in range(len(s)-1): # dpa[(i, i)] = 1 if s[i] == s[i+1]: dpa[i][i+1] = 2 # dpa[(i, i+1)] = 2 for gap in range(2, len(s)): for i in range(len(s)-gap): j = i+gap if s[i] == s[j]: dpa[i][j] = dpa[i+1][j-1]+2 # dpa[(i, j)] = dpa[(i+1, j-1)]+2 else: dpa[i][j] = max(dpa[i+1][j], dpa[i][j-1]) # dpa[(i, j)] = max(dpa[(i+1, j)], dpa[(i, j-1)]) print('Build String') result = '' strlen = dpa[0][len(s)-1] # strlen = dpa[(0, len(s)-1)] if strlen <= 1: return s[0] l, r = 0, len(s)-1 while l < r: if dpa[l][r] == strlen and s[l] == s[r]: # if dpa[(l, r)] == strlen and s[l] == s[r]: result += s[l] strlen -= 2 l += 1 r -= 1 elif dpa[l+1][r] == strlen: # elif dpa[(l+1, r)] == strlen or dpa: l += 1 elif dpa[l][r-1] == strlen: # elif dpa.get[(l, r-1)] == strlen: r -= 1 if l == r: result += s[l] + ''.join(reversed(result)) else: result += ''.join(reversed(result)) print('Time Cost: {}'.format(datetime.datetime.now()-starttime)) return result def isPalindrome(self, s): if not s: return True for i in range(len(s) // 2): if s[i] != s[len(s)-i-1]: return False return True # sys.stdin = open('input/A-large-practice.in', 'r') # sys.stdout = open('output/longestPalindrome.txt', 'w') s = Solution() # print('===============BRUTAL============') # print(s.longestPalindrome('zaaaabbbbbaaaacc')) # print(s.longestPalindrome('ab')) # print(s.longestPalindrome('')) # print(s.longestPalindrome("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir")) # print(s.longestPalindrome("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj")) # print(s.longestPalindrome("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg")) # print(s.longestPalindrome("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")) print('===============MANACHER============') print(s.manacher('zaaaabbbbbaaaacc')) print(s.manacher('ab')) print(s.manacher('')) print(s.manacher("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir")) print(s.manacher("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj")) print(s.manacher("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg")) print(s.manacher("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")) print(s.manacher("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) print('===============SPAN============') print(s.span('zaaaabbbbbaaaacc')) print(s.span('ab')) print(s.span('')) print(s.span("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir")) print(s.span("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj")) print(s.span("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg")) print(s.span("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")) print(s.span("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")) # print('===============DP============') # print(s.longestPalindrome_dp('zaaaabbbbbaaaacc')) # print(s.longestPalindrome_dp('ab')) # print(s.longestPalindrome_dp('')) # print(s.longestPalindrome_dp("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir")) # print(s.longestPalindrome_dp("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj")) # print('===============DP MEMO============') # print(s.longestPalindrome_dpmemo('zaaaabbbbbaaaacc')) # print(s.longestPalindrome_dpmemo('ab')) # print(s.longestPalindrome_dpmemo('')) # print(s.longestPalindrome_dpmemo("zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir")) # print(s.longestPalindrome_dpmemo("cyyoacmjwjubfkzrrbvquqkwhsxvmytmjvbborrtoiyotobzjmohpadfrvmxuagbdczsjuekjrmcwyaovpiogspbslcppxojgbfxhtsxmecgqjfuvahzpgprscjwwutwoiksegfreortttdotgxbfkisyakejihfjnrdngkwjxeituomuhmeiesctywhryqtjimwjadhhymydlsmcpycfdzrjhstxddvoqprrjufvihjcsoseltpyuaywgiocfodtylluuikkqkbrdxgjhrqiselmwnpdzdmpsvbfimnoulayqgdiavdgeiilayrafxlgxxtoqskmtixhbyjikfmsmxwribfzeffccczwdwukubopsoxliagenzwkbiveiajfirzvngverrbcwqmryvckvhpiioccmaqoxgmbwenyeyhzhliusupmrgmrcvwmdnniipvztmtklihobbekkgeopgwipihadswbqhzyxqsdgekazdtnamwzbitwfwezhhqznipalmomanbyezapgpxtjhudlcsfqondoiojkqadacnhcgwkhaxmttfebqelkjfigglxjfqegxpcawhpihrxydprdgavxjygfhgpcylpvsfcizkfbqzdnmxdgsjcekvrhesykldgptbeasktkasyuevtxrcrxmiylrlclocldmiwhuizhuaiophykxskufgjbmcmzpogpmyerzovzhqusxzrjcwgsdpcienkizutedcwrmowwolekockvyukyvmeidhjvbkoortjbemevrsquwnjoaikhbkycvvcscyamffbjyvkqkyeavtlkxyrrnsmqohyyqxzgtjdavgwpsgpjhqzttukynonbnnkuqfxgaatpilrrxhcqhfyyextrvqzktcrtrsbimuokxqtsbfkrgoiznhiysfhzspkpvrhtewthpbafmzgchqpgfsuiddjkhnwchpleibavgmuivfiorpteflholmnxdwewj"))
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 31 13:10:45 2018 @author: aloswain """ from datetime import datetime import backtrader as bt class SmaCross(bt.SignalStrategy): def __init__(self): sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30) crossover = bt.ind.CrossOver(sma1, sma2) self.signal_add(bt.SIGNAL_LONG, crossover) cerebro = bt.Cerebro() cerebro.addstrategy(SmaCross) # **NOTE**: Read the note about the Yahoo API above. This sample is kept for # historical reasons. Use any other data feed. data0 = bt.feeds.YahooFinanceData(dataname='BAC', fromdate=datetime(2011, 1, 1), todate=datetime(2012, 12, 31)) cerebro.adddata(data0) cerebro.run() cerebro.plot()
python
''' Algoritmo de Prim 1. T ← vazio; 2. V' ← {u}; 3. para-todo v E V – V' faça 4. L(v) ← peso ({u,v}); 5. fim-para-todo 6. enquanto V' != V faça 7. ache um vértice w tal que L(w) = min {L(v) | v E V-V'}; 8. u = o vértice de V', ligado a w, representando a aresta com o menor custo; 9. e = {u,w}; 10. T ← T U {e}; 11. V'← V' U {w}; 12. para-todo v E V – V' faça 13. se peso({v,w}) < L(v) então 14. L(v) ← p({v,w}); 15. fim-se 16. fim-para-todo 17. fim-enquanto ''' import sys def read_graph(): nodes, edges = map(int, input().split()) # Cria grafo vazio graph = [[0 for i in range(nodes)] for _ in range(nodes)] for _ in range(edges): origin, destiny, weight = map(int, input().split()) # preenche o grafo com os nós -1 para facilitar com indices graph[origin - 1][destiny - 1] = weight graph[destiny - 1][origin - 1] = weight return graph, nodes # Procura o vertice de menor peso na arvore def find_min(weights, tree): aux_min = sys.maxsize node = -1 # Busca no vetor for i in range(len(weights)): # Procura vertice que ainda não esteja na arvore e tenha menor peso if weights[i] < aux_min and i not in tree: aux_min = weights[i] node = i return node def prim(graph, nodes): # Inicializa o vetor de pesos com um valor muito grande weights = [sys.maxsize for i in range(nodes)] # Escolhe o ponto inicial e modifica o peso tree = set() tree_size = 0 weights[0] = 0 # while len(tree) + 1 < nodes: while tree_size < nodes: # acha o vertice de menor peso e adiciona ele a mst u = find_min(weights, tree) tree.add(u) tree_size += 1 # relaxa os vertices for w in range(nodes): # o peso será modificado se o nó n estiver na mst # e se for menor do que o peso já achado if graph[u][w] != 0 and w not in tree and graph[u][w] < weights[w]: weights[w] = graph[u][w] # retorna a soma dos pesos (equivalente ao custo total) return sum(weights) #------------------------------------------------------------------------------- graph, nodes = read_graph() print(prim(graph, nodes))
python
#! /usr/bin/python from pylab import * from sys import argv,exit,stdout import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline from scipy import interpolate import numpy as np from finite_differences_x import * from interp import * def read_EFIT(EFIT_file_name): EFITdict = {} f = open(EFIT_file_name,'r') eqdsk=f.readlines() line1=eqdsk[0].split() if len(line1) == 2: nwnh = eqdsk[0].split()[1] nw = int(nwnh[0:3]) nh = int(nwnh[3:7]) else: nw = int(line1[-2]) nh = int(line1[-1]) EFITdict['nw'] = nw #number of grid for Rgrid EFITdict['nh'] = nh #number of grid for Zgrid entrylength=16 #note: here rmin is rleft from EFIT #print(len(eqdsk[1])/entrylength) is not integer try: rdim,zdim,rcentr,rleft,zmid = \ [float(eqdsk[1][j*entrylength:(j+1)*entrylength]) \ for j in range(len(eqdsk[1])//entrylength)] except: entrylength=15 try: rdim,zdim,rcentr,rleft,zmid = \ [float(eqdsk[1][j*entrylength:(j+1)*entrylength]) \ for j in range(len(eqdsk[1])//entrylength)] except: exit('Error reading EQDSK file, please check format!') rmaxis,zmaxis,simag,sibry,bcentr = \ [float(eqdsk[2][j*entrylength:(j+1)*entrylength]) \ for j in range(len(eqdsk[2])//entrylength)] current,simag2,xdum,rmaxis2,xdum = \ [float(eqdsk[3][j*entrylength:(j+1)*entrylength]) \ for j in range(len(eqdsk[3])//entrylength)] zmaxis2,xdum,sibry2,xdum,xdum = \ [float(eqdsk[4][j*entrylength:(j+1)*entrylength]) \ for j in range(len(eqdsk[4])//entrylength)] EFITdict['rdim'] = rdim EFITdict['zdim'] = zdim EFITdict['rcentr'] = rcentr EFITdict['rleft'] = rleft EFITdict['zmid'] = zmid EFITdict['rmaxis'] = rmaxis # R of magnetic axis (m) EFITdict['zmaxis'] = zmaxis # Z of magnetic axis (m) EFITdict['simag'] = simag # poloidal flux at magnetic axis EFITdict['sibry'] = sibry # poloidal flux at plasma boundary EFITdict['bcentr'] = bcentr # vacuum toroidal magnetic field in Telsa EFITdict['current'] = current # plasma current in Ampere print('EFIT file Resolution: %d x %d' %(EFITdict['nw'],EFITdict['nh'])) print('Horizontal dimension(m): %10.4f' %EFITdict['rdim']) print('Vertical dimension(m): %10.4f' %EFITdict['zdim']) print('Minimum R of rectangular grid: %10.4f' %EFITdict['rleft']) print('(R, Z) of magnetic axis: (%10.4f, %10.4f)' %(EFITdict['rmaxis'],EFITdict['zmaxis'])) print('poloidal flux at magnetic axis in Weber/rad: %10.4f' %EFITdict['simag']) print('poloidal flux at the plasma boundary in Weber/rad: %10.4f' %EFITdict['sibry']) print('Vacuum toroidal magnetic field at R = %10.4f: %10.4f Tesla' %(EFITdict['rcentr'],EFITdict['bcentr'])) print('Z of center of rectangular grid: %10.4f' %EFITdict['zmid']) print('Plasma current: %10.4f Ampere' %EFITdict['current']) Rgrid = np.linspace(0, 1, nw, endpoint = True) * rdim + rleft Zgrid = np.linspace(0, 1, nh, endpoint = True) * zdim + (zmid - zdim/2.) EFITdict['Rgrid'] = Rgrid # Rgrid of psi(Z, R) EFITdict['Zgrid'] = Zgrid # Zgrid of psi(Z, R) Fpol = empty(nw, dtype = float) Pres = empty(nw, dtype = float) FFprime = empty(nw, dtype = float) Pprime = empty(nw, dtype = float) qpsi = empty(nw, dtype = float) jtor = empty(nw, dtype = float) # psi_pol is written on uniform (R,Z) grid (res=nw(R)*nh(Z)) psirz_1d = empty(nw * nh, dtype = float) start_line = 5 wordsInLine = 5 lines=range(nw//wordsInLine) if nw%wordsInLine!=0: lines=range(nw//wordsInLine+1) for i in lines: n_entries=len(eqdsk[i+start_line])//entrylength Fpol[i*wordsInLine:i*wordsInLine+n_entries] = \ [float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \ for j in range(n_entries)] start_line=i+start_line+1 EFITdict['Fpol'] = Fpol # poloidal current function F = R * Btor on psipn grid for i in lines: n_entries=len(eqdsk[i+start_line])//entrylength Pres[i*wordsInLine:i*wordsInLine+n_entries] = \ [float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \ for j in range(n_entries)] start_line=i+start_line+1 EFITdict['Pres'] = Pres # plasma pressure in N / m^2 on psipn grid for i in lines: n_entries=len(eqdsk[i+start_line])//entrylength FFprime[i*wordsInLine:i*wordsInLine+n_entries] = \ [float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \ for j in range(n_entries)] start_line=i+start_line+1 EFITdict['FFprime'] = FFprime # FFprime on psipn grid for i in lines: n_entries=len(eqdsk[i+start_line])//entrylength Pprime[i*wordsInLine:i*wordsInLine+n_entries] = \ [float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \ for j in range(n_entries)] start_line=i+start_line+1 EFITdict['Pprime'] = Pprime # Pprime on psipn grid lines_twod=range(nw*nh//wordsInLine) if nw*nh%wordsInLine!=0: lines_twod=range(nw*nh//wordsInLine+1) for i in lines_twod: n_entries=len(eqdsk[i+start_line])//entrylength psirz_1d[i*wordsInLine:i*wordsInLine+n_entries] = \ [float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \ for j in range(n_entries)] start_line=i+start_line+1 psirz=psirz_1d.reshape(nh,nw) EFITdict['psirz'] = psirz # poloidal flux on the rectangular grid (Rgrid, Zgrid) for i in lines: n_entries=len(eqdsk[i+start_line])//entrylength qpsi[i*wordsInLine:i*wordsInLine+n_entries] = \ [float(eqdsk[i+start_line][j*entrylength:(j+1)*entrylength]) \ for j in range(n_entries)] start_line=i+start_line+1 EFITdict['qpsi'] = qpsi # safety factor on psipn grid # even grid of psi_pol, on which all 1D fields are defined psipn = np.linspace(0., 1., nw) EFITdict['psipn'] = psipn # uniform psipn grid interpol_order = 3 psip = psipn * (sibry - simag) + simag q_spl_psi = UnivariateSpline(psip, qpsi, k=interpol_order, s=1e-5) psi_pol_fine = linspace(psip[0], psip[-1], nw*10) psi_tor_fine = empty((nw*10),dtype=float) psi_tor_fine[0] = 0. for i in range(1, nw * 10): x = psi_pol_fine[:i+1] y = q_spl_psi(x) psi_tor_fine[i] = np.trapz(y,x) rhot_n_fine = np.sqrt(psi_tor_fine/(psi_tor_fine[-1]-psi_tor_fine[0])) rho_tor_spl = UnivariateSpline(psi_pol_fine, rhot_n_fine, k=interpol_order, s=1e-5) rhotn = rho_tor_spl(psip) EFITdict['rhotn'] = rhotn # square root of toroidal flux on psipn grid Z0_ind = np.argmin(abs(Zgrid - zmaxis)) R0_ind = np.argmin(abs(Rgrid - rmaxis - 0.02)) R_obmp = Rgrid[R0_ind:] psirz_obmp = psirz[Z0_ind, R0_ind:] psipn_obmp = (psirz_obmp - simag) / (sibry - simag) sepInd = np.argmin(abs(psipn_obmp - 1.)) psipn_obmp = psipn_obmp[:sepInd + 1] R_obmp = list(R_obmp[:sepInd + 1]) R = interp(psipn_obmp, R_obmp, psipn) if 1 == 0: plt.plot(psipn_obmp, R_obmp, label = 'before') plt.plot(psipn, R, label = 'after') plt.xlabel('psipn') plt.ylabel('R') plt.legend(loc = 2) plt.show() EFITdict['R'] = R # major radius (m) on psipn grid #jtor = rmaxis * Pprime + FFprime / rmaxis jtor = R * Pprime + FFprime / R EFITdict['jtor'] = jtor # toroidal current density on psipn grid #psirz_spl = interpolate.RectBivariateSpline(Zgrid, Rgrid, psirz) Bp_Z_grid = np.empty(np.shape(psirz)) for i in range(nh): Bp_Z_grid_this = first_derivative(psirz[i,:].flatten(), Rgrid) / Rgrid Bp_Z_grid[i,:] = Bp_Z_grid_this.copy() Bp_R_grid = np.empty(np.shape(psirz)) for i in range(nw): Bp_R_grid_this = - first_derivative(psirz[:,i].flatten(), Zgrid) / Rgrid[i] Bp_R_grid[:,i] = Bp_R_grid_this.copy() #Bp_R_spl = interpolate.RectBivariateSpline(Zgrid, Rgrid, Bp_R_grid) #Bp_Z_spl = interpolate.RectBivariateSpline(Zgrid, Rgrid, Bp_Z_grid) Bp_tot_grid = np.sqrt(Bp_R_grid ** 2 + Bp_Z_grid ** 2) Bp_obmp = Bp_tot_grid[Z0_ind, R0_ind : R0_ind + sepInd + 1] Bpol = interp(psipn_obmp, Bp_obmp, psipn) EFITdict['Bpol'] = Bpol # B_pol on psipn grid F_spl = interpolate.UnivariateSpline(psipn, Fpol) Btor = F_spl(psipn) / R EFITdict['Btor'] = abs(Btor) #B_tor on psipn grid return EFITdict def magneticShear(EFITdict, show_plots = False): rhotn = EFITdict['rhotn'] q = EFITdict['qpsi'] #uni_rhot = np.linspace(rhotn[0], rhotn[-1], len(rhotn) * 10) uni_rhot = np.linspace(rhotn[0], rhotn[-1], len(rhotn)) q_unirhot = interp(rhotn, q, uni_rhot) shat_unirhot = uni_rhot / q_unirhot * first_derivative(q_unirhot, uni_rhot) shat = interp(uni_rhot, shat_unirhot, rhotn) R_unirhot = interp(rhotn, EFITdict['R'], uni_rhot) Ls_unirhot = q_unirhot * R_unirhot / shat_unirhot Ls = interp(uni_rhot, Ls_unirhot, rhotn) if show_plots: plt.plot(uni_rhot, shat_unirhot) plt.ylabel('shat') plt.xlabel('rhot') plt.axis([0.8, 1., 0., 10.]) plt.show() plt.plot(uni_rhot, Ls_unirhot) plt.ylabel('Ls') plt.xlabel('rhot') plt.axis([0.8, 1., 0., 2.]) plt.show() return uni_rhot, shat_unirhot, Ls_unirhot
python
# from __future__ import absolute_import from abstractions.recognition import DistanceEstimator import numpy from typing import List class NumpyDistanceEstimator(DistanceEstimator): def distance(self, face_features_we_have : [bytes], face_feature_to_compare ) -> List[float]: if len(face_features_we_have) == 0: return numpy.empty((0)) #todo: there might be a mistake, sometimes for the same picture we get different distances although they should be 0.0 array_we_have = [numpy.frombuffer(face_feature_we_have, dtype=numpy.dtype(float)) for face_feature_we_have in face_features_we_have] if isinstance(face_feature_to_compare, bytes): face_feature_to_compare = numpy.frombuffer(face_feature_to_compare, dtype=numpy.dtype(float)) diff_result = numpy.asfarray(array_we_have) - face_feature_to_compare return numpy.linalg.norm(diff_result, axis=1)
python
import json import os import random import sqlite3 import urllib import requests from flask import Flask app = Flask(__name__) def get_cursor(): connection = sqlite3.connect("database.db") c = connection.cursor() return c USER_ID = 1 def init_db(): c = get_cursor() c.execute(""" CREATE TABLE IF NOT EXISTS meals ( id integer PRIMARY KEY AUTOINCREMENT NOT NULL, title text, available integer, picture text, price real, category integer ) """) c.execute(""" CREATE TABLE IF NOT EXISTS promocodes ( id integer PRIMARY KEY, code text, discount real ) """) c.execute(""" CREATE TABLE IF NOT EXISTS users ( id integer PRIMARY KEY, promocode text ) """) c.execute(""" INSERT INTO meals VALUES (1, "Chicken", 1, "", 20.0, 1) """) c.execute(""" INSERT INTO meals VALUES (2, "Milk", 1, "", 10.0, 1) """) c.execute(""" INSERT INTO promocodes VALUES (1, "stepik", 30.0) """) c.execute(""" INSERT INTO promocodes VALUES (2, "delivery", 20.0) """) c.execute(""" INSERT INTO users VALUES (1, null) """) c.connection.commit() c.connection.close() def fill_database(): """ See https://www.food2fork.com/ :return: """ api_key = "f96f947346e0439bf62117e1c291e685" key_words = "cake" c = get_cursor() for page in range(1, 2): params = urllib.parse.urlencode({'key': api_key, 'q': key_words, 'page': page}) url_string = "https://www.food2fork.com/api/search?" + params r = requests.get(url_string) data = r.json() for recipe in data['recipes']: c.execute(""" INSERT INTO meals (title, available, picture, price, category) VALUES (?, ?, ?, ?, ?) """, [ recipe['title'], 1, recipe['image_url'], recipe['social_rank'] + random.randint(0, 100), 1 ]) c.connection.commit() c.connection.close() @app.route("/promo/<code>") def promo(code): c = get_cursor() c.execute(""" SELECT * FROM promocodes WHERE code = ? """, (code, )) result = c.fetchone() if result is None: return json.dumps({'valid': False}) promo_id, promo_code, promo_discount = result c.execute(""" UPDATE users SET promocode=? WHERE id = ? """, (code, USER_ID)) c.connection.commit() c.connection.close() return json.dumps({'valid': True, 'discount': promo_discount}) @app.route("/meals") def meals(): c = get_cursor() c.execute(""" SELECT discount FROM promocodes WHERE code = ( SELECT promocode FROM users WHERE id = ? ) """, (USER_ID,)) result = c.fetchone() discount = 0 if result is not None: discount = result[0] meals = [] for meal_info in c.execute("SELECT * FROM meals"): meal_id, title, available, picture, price, category = meal_info meals.append({ 'id': meal_id, 'title': title, 'available': bool(available), 'picture': picture, 'price': price * (1.0-discount/100), 'category': category }) return json.dumps(meals) if not os.path.exists("database.db"): init_db() fill_database() app.run('0.0.0.0', 8000)
python
####################################################################### ### Script for Calling Plotting Scripts and Merging the Plots ### ####################################################################### import sys current_path = sys.path[0] ex_op_str = current_path[current_path.index('progs')+6: current_path.index('w2w_ensembleplots')-1] sys.path.append('/progs/{}'.format(ex_op_str)) from w2w_ensembleplots.core.ensemble_spread_maps import ens_spread_contourplot from w2w_ensembleplots.core.download_forecast import calc_latest_run_time from w2w_ensembleplots.core.domain_definitions import get_domain def main(): model = 'icon-eu-eps' run = calc_latest_run_time(model) if run['hour'] == 6 or run['hour'] == 18: run['hour'] -= 6 #run = dict(year = 2020, month = 10, day = 15, hour = 0) domains =[] domains.append(get_domain('EU-Nest')) variable1 = dict(name='gph_500hPa', unit='gpdm', grid='icosahedral') variable2 = dict(name='gph_500hPa', unit='gpdm', grid='latlon_0.2') ens_spread_contourplot(domains, variable1, variable2, model, run) return ######################################################################## ######################################################################## ######################################################################## if __name__ == '__main__': import time t1 = time.time() main() t2 = time.time() delta_t = t2-t1 if delta_t < 60: print('total script time: {:.1f}s'.format(delta_t)) elif 60 <= delta_t <= 3600: print('total script time: {:.0f}min{:.0f}s'.format(delta_t//60, delta_t-delta_t//60*60)) else: print('total script time: {:.0f}h{:.1f}min'.format(delta_t//3600, (delta_t-delta_t//3600*3600)/60))
python
from heapq import heappush, heappop, heapify import itertools class Queue: def __init__(self): self.q = [] def enqueue(self, element): self.q.append(element) def dequeue(self): return self.q.pop(0) def is_empty(self): return len(self.q) == 0 def front(self): return self.q[0] class DisjointSets: def __init__(self, size): self.parent = [int] * size self.rank = [int] * size def make_set(self, x): self.parent[x] = x self.rank[x] = 0 def find_set(self, x): if self.parent[x] != x: self.parent[x] = self.find_set(self.parent[x]) return self.parent[x] def union(self, x, y): xRoot = self.find_set(x) yRoot = self.find_set(y) if xRoot != yRoot: if self.rank[xRoot] < self.rank[yRoot]: self.parent[xRoot] = yRoot elif self.rank[xRoot] > self.rank[yRoot]: self.parent[yRoot] = xRoot else: self.parent[yRoot] = xRoot self.rank[xRoot] += 1 class Heap: REMOVED = -1 def __init__(self, size): self.heap = [] self.finder = {} self.counter = itertools.count() def add_or_update_item(self, elementIndex, priority=0): if elementIndex in self.finder: self.__remove_item(elementIndex) count = next(self.counter) entry = [priority, count, elementIndex] self.finder[elementIndex] = entry heappush(self.heap, entry) def extract_min(self): while self.heap: (priority, count, elementIndex) = heappop(self.heap) if elementIndex is not self.REMOVED: del self.finder[elementIndex] return elementIndex raise KeyError("pop from an empty priority queue") def __remove_item(self, elementIndex): entry = self.finder.pop(elementIndex) entry[-1] = self.REMOVED def key(self, elementIndex): entry = self.finder[elementIndex] return self.heap[entry[-1]] def contains(self, elementIndex): return elementIndex in self.finder def is_empty(self): return len(self.finder) == 0
python
# import pytest # from ..accessor import session # @pytest.mark.skip(reason="initial run on gh actions (please remove)") # def test_session(): # """ # tests that a session can be created without error # """ # with session() as db: # assert db
python
""" This file builds Tiled Squeeze-and-Excitation(TSE) from paper: <STiled Squeeze-and-Excite: Channel Attention With Local Spatial Context> --> https://arxiv.org/abs/2107.02145 Created by Kunhong Yu Date: 2021/07/06 """ import torch as t def weights_init(layer): """ weights initialization Args : --layer: one layer instance """ if isinstance(layer, t.nn.Linear) or isinstance(layer, t.nn.BatchNorm1d): t.nn.init.normal_(layer.weight, 0.0, 0.02) # we use 0.02 as initial value t.nn.init.constant_(layer.bias, 0.0) class TSE(t.nn.Module): """Define TSE operation""" """According to the paper, simple TSE can be implemented by several 1x1 conv followed by a average pooling with kernel size and stride, which is simple and effective to verify and to do parameter sharing In this implementation, column and row pooling kernel sizes are shared! """ def __init__(self, num_channels : int, attn_ratio : float, pool_kernel = 7): """ Args : --num_channels: # of input channels --attn_ratio: hidden size ratio --pool_kernel: pooling kernel size, default best is 7 according to paper """ super().__init__() self.num_channels = num_channels self.sigmoid = t.nn.Sigmoid() self.avg_pool = t.nn.AvgPool2d(kernel_size = pool_kernel, stride = pool_kernel, ceil_mode = True) self.tse = t.nn.Sequential( t.nn.Conv2d(self.num_channels, int(self.num_channels * attn_ratio), kernel_size = 1, stride = 1), t.nn.BatchNorm2d(int(self.num_channels * attn_ratio)), t.nn.ReLU(inplace = True), t.nn.Conv2d(int(self.num_channels * attn_ratio), self.num_channels, kernel_size = 1, stride = 1), t.nn.Sigmoid() ) self.kernel_size = pool_kernel def forward(self, x): """x has shape [m, C, H, W]""" _, C, H, W = x.size() # 1. TSE y = self.tse(self.avg_pool(x)) # 2. Re-calibrated y = t.repeat_interleave(y, self.kernel_size, dim = -2)[:, :, :H, :] y = t.repeat_interleave(y, self.kernel_size, dim = -1)[:, :, :, :W] return x * y # unit test if __name__ == '__main__': tse = TSE(1024, 0.5, 7) print(tse)
python
from typing import Iterable from eth2spec.test.context import PHASE0 from eth2spec.test.phase0.genesis import test_initialization, test_validity from gen_base import gen_runner, gen_typing from gen_from_tests.gen import generate_from_tests from eth2spec.phase0 import spec as spec from importlib import reload from eth2spec.config import config_util from eth2spec.utils import bls def create_provider(handler_name: str, tests_src, config_name: str) -> gen_typing.TestProvider: def prepare_fn(configs_path: str) -> str: config_util.prepare_config(configs_path, config_name) reload(spec) bls.use_milagro() return config_name def cases_fn() -> Iterable[gen_typing.TestCase]: return generate_from_tests( runner_name='genesis', handler_name=handler_name, src=tests_src, fork_name=PHASE0, ) return gen_typing.TestProvider(prepare=prepare_fn, make_cases=cases_fn) if __name__ == "__main__": gen_runner.run_generator("genesis", [ create_provider('initialization', test_initialization, 'minimal'), create_provider('validity', test_validity, 'minimal'), ])
python
#!/usr/bin/env python import os import sys import shutil download_fail_times = 0 pvmp3_path = sys.path[0] download_path = os.path.join(pvmp3_path, "source") final_src_path = os.path.join(pvmp3_path, "src") print('download pvmp3 source file') if not os.path.exists(final_src_path): while True: if not os.path.exists(download_path): #os.system("git clone https://github.com/aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 " + str(download_path)) os.system("git clone https://gitee.com/mirrors_aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 " + str(download_path)) if os.path.exists(download_path): print("Download pvmp3 source success!\n") break else: download_fail_times = download_fail_times + 1 if download_fail_times >= 3: print("Download pvmp3 fail!\n") break break shutil.copytree('source/codecs_v2/audio/mp3/dec/src', 'src') shutil.copytree('source/codecs_v2/audio/mp3/dec/include', 'include') n = 0 filelist = os.listdir(final_src_path) for i in filelist: oldname = os.path.join(final_src_path, filelist[n]) suffix = oldname.split('.')[-1] if suffix == 'h' or suffix == 'cpp': code ='' with open(oldname, 'r') as f: code = f.read() code = code.replace('double(', '(double)(') code = code.replace('int32(', '(int32)(') code = code.replace('huffcodetab ht[HUFF_TBL];', 'struct huffcodetab ht[HUFF_TBL];') code = code.replace('huffcodetab *pHuff;', 'struct huffcodetab *pHuff;') code = code.replace('__inline', 'static inline') code = code.replace('inline int16 saturate16', 'static int16 saturate16') code = code.replace('new_slen[4];', 'new_slen[4] = {0,0,0,0};') with open(oldname, 'w') as f: f.write(code) if suffix == 'cpp': newname = oldname[:-4] + '.c' os.rename(oldname, newname) print(oldname,'->', newname) n = n + 1 shutil.copyfile('oscl_base.h', 'include/oscl_base.h') shutil.copyfile('oscl_mem.h', 'include/oscl_mem.h') shutil.rmtree(download_path) print('Download pvmp3 source file success!')
python
import csv from environs import Env env = Env() env.read_env() fieldnames = ['id', 'nome_da_receita', 'descricao_da_receita'] def listar_receitas(): with open(env('RECEITAS_CSV')) as f: reader = csv.DictReader(f) return [receita for receita in reader] def buscar_receitas(nome): with open(env('RECEITAS_CSV')) as f: reader = csv.DictReader(f) return [receita for receita in reader if receita['nome_da_receita'].lower().startswith(nome.lower()) ] def pega_ultimo_id(): receita = {'id': 1} with open(env('RECEITAS_CSV')) as f: for receita in csv.DictReader(f): pass return int(receita.get('id')) def verifica_se_receita_existe(nome): with open(env('RECEITAS_CSV')) as f: receitas = [receita for receita in csv.DictReader(f) if receita.get('nome_da_receita') == nome] return len(receitas) > 0 def gravar_receita(nome, descricao): if verifica_se_receita_existe(nome): return {'status': 409, 'data': "Receita já existe"} novo_id = pega_ultimo_id() + 1 receita = { 'id': novo_id, 'nome_da_receita': nome, 'descricao_da_receita': descricao } with open(env('RECEITAS_CSV'), 'a+') as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writerow(receita) return {'status': 201, 'data': receita}
python
from datetime import datetime, timedelta from pynput.keyboard import Listener as KeyboardListener from pynput.mouse import Listener as MouseListener from apis.mongo.mongo_client import log_event, log_processes from apis.monitoring_details.win32_window_details import active_window_process, all_open_windows # logging.basicConfig(filename="../window_log.txt", level=logging.DEBUG, format='%(message)s') MOUSE_MOVE = "MOUSE_MOVE" MOUSE_CLICK = "MOUSE_CLICK" MOUSE_SCROLL = "MOUSE_SCROLL" KEYBOARD_RELEASE = "KEYBOARD_RELEASE" KEYBOARD_PRESS = "KEYBOARD_PRESS" event_types = { KEYBOARD_PRESS: 0, KEYBOARD_RELEASE: 1, MOUSE_MOVE: 2, MOUSE_CLICK: 3, MOUSE_SCROLL: 4, } current_event_type = None prev_event_type = None active_window_details = None active_windows = [] last_time = datetime.utcnow() min_log_frequency = timedelta(seconds=2) def set_event_type(event_type_input): global current_event_type global last_time # Determine cause of this event current_event_type = event_types[event_type_input] # Do not log if not enough time since last log has elapsed if last_time + min_log_frequency <= datetime.utcnow(): # Active window details - what is in the foreground payload = active_window_process() if payload is not None: # This fails sometimes... payload['event_type'] = event_type_input log_event(payload) # All window details - what is open on the system log_processes(all_open_windows()) # Update last time a log was made last_time = datetime.utcnow() def on_press(key): # t = Thread(target=set_event_type, args=(KEYBOARD_PRESS,)) # t.start() set_event_type(KEYBOARD_PRESS) # print("ON PRESS:", datetime.utcnow()) # log_event(active_window_process()) # logging.info("Key Press: " + str(key)) # print("Key Press: " + str(key)) def on_release(key): # t = Thread(target=set_event_type, args=(KEYBOARD_RELEASE,)) # t.start() set_event_type(KEYBOARD_RELEASE) # print("ON RELEASE:", datetime.utcnow()) # logging.info("Key Press: " + str(key)) # print("Key Press: " + str(key)) def on_move(x, y): pass # t = Thread(target=set_event_type, args=(MOUSE_MOVE,)) # t.start() set_event_type(MOUSE_MOVE) # print("ON MOVE:", datetime.utcnow()) # log_event(active_window_process()) # time.sleep(5) # logging.info("Mouse moved to ({0}, {1})".format(x, y)) # print("Mouse moved to ({0}, {1})".format(x, y)) def on_click(x, y, button, pressed): if pressed: # t = Thread(target=set_event_type, args=(MOUSE_CLICK,)) # t.start() set_event_type(MOUSE_CLICK) # print("ON CLICK:", datetime.utcnow()) # log_event(active_window_process()) # logging.info('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button)) # print('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button)) def on_scroll(x, y, dx, dy): # t = Thread(target=set_event_type, args=(MOUSE_SCROLL,)) # t.start() set_event_type(MOUSE_SCROLL) # print("ON SCROLL:", datetime.utcnow()) # log_event(active_window_process()) # logging.info('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy)) # print('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy)) def start_listeners(): with MouseListener(on_click=on_click, on_scroll=on_scroll, on_move=on_move) as m_listener: with KeyboardListener(on_press=on_press, on_release=on_release) as k_listener: m_listener.join() k_listener.join() if __name__ == '__main__': start_listeners()
python
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # noc.core.snmp.ber tests # ---------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Third-party modules import pytest # NOC modules from noc.core.snmp.ber import BEREncoder, BERDecoder @pytest.mark.parametrize( "raw, value", [ ("", 0), ("\x00", 0), ("\x01", 1), ("\x7f", 127), ("\x00\x80", 128), ("\x01\x00", 256), ("\x80", -128), ("\xff\x7f", -129), ], ) def test_decode_int(raw, value): decoder = BERDecoder() assert decoder.parse_int(raw) == value @pytest.mark.parametrize( "raw, value", [ ("@", float("+inf")), ("A", float("-inf")), ("\x031E+0", float("1")), ("\x0315E-1", float("1.5")), ], ) def test_decode_real(raw, value): decoder = BERDecoder() assert decoder.parse_real(raw) == value @pytest.mark.parametrize("raw, value", [("B", float("nan")), ("C", float("-0"))]) def test_decode_real_error(raw, value): decoder = BERDecoder() with pytest.raises(Exception): assert decoder.parse_real(raw) == value @pytest.mark.xfail() def test_decode_p_bitstring(): raise NotImplementedError() @pytest.mark.parametrize("raw, value", [("test", "test"), ("public", "public"), ("", "")]) def test_decode_p_octetstring(raw, value): decoder = BERDecoder() assert decoder.parse_p_octetstring(raw) == value @pytest.mark.xfail() def test_decode_p_t61_string(): raise NotImplementedError() @pytest.mark.xfail() def test_decode_c_octetstring(): raise NotImplementedError() @pytest.mark.xfail() def test_decode_c_t61_string(): raise NotImplementedError() @pytest.mark.parametrize("raw", ["\x00"]) def test_decode_null(raw): decoder = BERDecoder() assert decoder.parse_null(raw) is None @pytest.mark.xfail() def test_decode_a_ipaddress(): raise NotImplementedError() @pytest.mark.parametrize("raw, value", [("+\x06\x01\x02\x01\x01\x05\x00", "1.3.6.1.2.1.1.5.0")]) def test_decode_p_oid(raw, value): decoder = BERDecoder() assert decoder.parse_p_oid(raw) == value @pytest.mark.xfail() def test_decode_compressed_oid(): raise NotImplementedError() @pytest.mark.xfail() def test_decode_sequence(): raise NotImplementedError() @pytest.mark.xfail() def test_decode_implicit(): raise NotImplementedError() @pytest.mark.xfail() def test_decode_set(): raise NotImplementedError() @pytest.mark.xfail() def test_decode_utctime(): raise NotImplementedError() @pytest.mark.parametrize( "raw,value", [ ("\x9f\x78\x04\x42\xf6\x00\x00", 123.0), # Opaque ("\x44\x07\x9f\x78\x04\x42\xf6\x00\x00", 123.0), ], ) def test_decode_float(raw, value): decoder = BERDecoder() assert decoder.parse_tlv(raw)[0] == value @pytest.mark.parametrize( "raw,value", [ ("\x9f\x79\x08\x40\x5e\xc0\x00\x00\x00\x00\x00", 123.0), # Opaque ("\x44\x0b\x9f\x79\x08\x40\x5e\xc0\x00\x00\x00\x00\x00", 123.0), ], ) def test_decode_double(raw, value): decoder = BERDecoder() assert decoder.parse_tlv(raw)[0] == value @pytest.mark.parametrize("raw,value", [("\x44\x81\x06\x04\x04test", "test")]) def test_decode_opaque(raw, value): decoder = BERDecoder() assert decoder.parse_tlv(raw)[0] == value @pytest.mark.xfail() def test_encode_tlv(): raise NotImplementedError() @pytest.mark.parametrize( "raw, value", [("test", "\x04\x04test"), ("public", "\x04\x06public"), ("", "\x04\x00")] ) def test_encode_octet_string(raw, value): encoder = BEREncoder() assert encoder.encode_octet_string(raw) == value @pytest.mark.xfail() def test_encode_sequence(): raise NotImplementedError() @pytest.mark.xfail() def test_encode_choice(): raise NotImplementedError() @pytest.mark.parametrize( "value,raw", [ (0, "\x02\x01\x00"), (1, "\x02\x01\x01"), (127, "\x02\x01\x7f"), (128, "\x02\x02\x00\x80"), (256, "\x02\x02\x01\x00"), (0x2085, "\x02\x02\x20\x85"), (0x208511, "\x02\x03\x20\x85\x11"), (-128, "\x02\x01\x80"), (-129, "\x02\x02\xff\x7f"), ], ) def test_encode_int(value, raw): encoder = BEREncoder() assert encoder.encode_int(value) == raw @pytest.mark.parametrize( "raw, value", [ (float("+inf"), "\t\x01@"), (float("-inf"), "\t\x01A"), (float("nan"), "\t\x01B"), (float("-0"), "\t\x01C"), (float("1"), "\t\x080x031E+0"), (float("1.5"), "\t\t0x0315E-1"), ], ) def test_encode_real(raw, value): encoder = BEREncoder() assert encoder.encode_real(raw) == value @pytest.mark.parametrize("value", ["\x05\x00"]) def test_encode_null(value): encoder = BEREncoder() assert encoder.encode_null() == value @pytest.mark.parametrize( "oid,raw", [ ("1.3.6.1.2.1.1.5.0", "\x06\x08+\x06\x01\x02\x01\x01\x05\x00"), ("1.3.6.0", "\x06\x03+\x06\x00"), ("1.3.6.127", "\x06\x03+\x06\x7f"), ("1.3.6.128", "\x06\x04+\x06\x81\x00"), ("1.3.6.255", "\x06\x04+\x06\x81\x7f"), ("1.3.6.256", "\x06\x04+\x06\x82\x00"), ("1.3.6.16383", "\x06\x04+\x06\xff\x7f"), ("1.3.6.16384", "\x06\x05+\x06\x81\x80\x00"), ("1.3.6.65535", "\x06\x05+\x06\x83\xff\x7f"), ("1.3.6.65535", "\x06\x05+\x06\x83\xff\x7f"), ("1.3.6.2097151", "\x06\x05+\x06\xff\xff\x7f"), ("1.3.6.2097152", "\x06\x06+\x06\x81\x80\x80\x00"), ("1.3.6.16777215", "\x06\x06+\x06\x87\xff\xff\x7f"), ("1.3.6.268435455", "\x06\x06+\x06\xff\xff\xff\x7f"), ("1.3.6.268435456", "\x06\x07+\x06\x81\x80\x80\x80\x00"), ("1.3.6.2147483647", "\x06\x07+\x06\x87\xff\xff\xff\x7f"), ], ) def test_encode_oid(oid, raw): encoder = BEREncoder() assert encoder.encode_oid(oid) == raw
python
import logging from itertools import cycle, islice from typing import Callable, List, Optional import torch from hypergraph_nets.hypergraphs import ( EDGES, GLOBALS, N_EDGE, N_NODE, NODES, RECEIVERS, SENDERS, ZERO_PADDING, HypergraphsTuple, ) from strips_hgn.hypergraph.hypergraph_view import HypergraphView _log = logging.getLogger(__name__) def _validate_features(features, expected_size, label): """ Check features conform to expected size. Only support lists for now, no np.ndarray or torch.Tensor """ if features is None: return if isinstance(features, torch.Tensor): assert features.shape[0] == expected_size else: raise NotImplementedError( f"Unexpected features type of {type(features)} for {label}" ) def repeat_up_to_k(lst, k): """ Repeats a list so that it is of length k: https://stackoverflow.com/a/39863275 e.g. _repeat_up_to_k([1,2,3], 10) => [1,2,3,1,2,3,1,2,3,1] """ assert k >= len(lst) return list(islice(cycle(lst), k)) def pad_with_obj_up_to_k(lst, k, pad_with=-1): """ Pads a list with an object so resulting length is k e.g. _pad_with_zeros_up_to_k([1,2,3], 5, 0) => [1,2,3,0,0] """ assert k >= len(lst) return lst + (k - len(lst)) * [pad_with] # noinspection PyArgumentList def hypergraph_view_to_hypergraphs_tuple( hypergraph: HypergraphView, receiver_k: int, sender_k: int, node_features: Optional[torch.Tensor] = None, edge_features: Optional[torch.Tensor] = None, global_features: Optional[torch.Tensor] = None, pad_func: Callable[[list, int], list] = pad_with_obj_up_to_k, ) -> HypergraphsTuple: """ Convert a Delete-Relaxation Task to a Hypergraphs Tuple (with node/edge/global features) :param hypergraph: HypergraphView :param receiver_k: maximum number of receivers for a hyperedge, receivers will be repeated to fit k :param sender_k: maximum number of senders for a hyperedge, senders will be repeated to fit k :param node_features: node features as a torch.Tensor :param edge_features: edge features as a torch.Tensor :param global_features: global features as a torch.Tensor :param pad_func: function for handling different number of sender/receiver nodes :return: parsed HypergraphsTuple """ # Receivers are the additive effects for each action receivers = torch.LongTensor( [ pad_func( [ # FIXME hypergraph.node_to_idx(atom) for atom in sorted(hyperedge.receivers) ], receiver_k, ) for hyperedge in hypergraph.hyperedges ] ) # Senders are preconditions for each action senders = torch.LongTensor( [ pad_func( [ # FIXME hypergraph.node_to_idx(atom) for atom in sorted(hyperedge.senders) ], sender_k, ) for hyperedge in hypergraph.hyperedges ] ) # Validate features _validate_features(node_features, len(hypergraph.nodes), "Nodes") _validate_features(edge_features, len(hypergraph.hyperedges), "Edges") if global_features is not None: _validate_features(global_features, len(global_features), "Global") params = { N_NODE: torch.LongTensor([len(hypergraph.nodes)]), N_EDGE: torch.LongTensor([len(hypergraph.hyperedges)]), # Hyperedge connection information RECEIVERS: receivers, SENDERS: senders, # Features, set to None NODES: node_features, EDGES: edge_features, GLOBALS: global_features, ZERO_PADDING: pad_func == pad_with_obj_up_to_k, } return HypergraphsTuple(**params) def merge_hypergraphs_tuple( graphs_tuple_list: List[HypergraphsTuple] ) -> HypergraphsTuple: """ Merge multiple HypergraphsTuple (each representing one hypergraph) together into one - i.e. batch them up """ assert len(graphs_tuple_list) > 0 def _stack_features(attr_name, force_matrix=True): """ Stack matrices on top of each other """ features = [ getattr(h_tup, attr_name) for h_tup in graphs_tuple_list if getattr(h_tup, attr_name) is not None ] if len(features) == 0: return None else: stacked = torch.cat(features) if force_matrix and len(stacked.shape) == 1: stacked = stacked.reshape(-1, 1) return stacked # New tuple attributes n_node, n_edge, receivers, senders, nodes, edges, globals_ = ( _stack_features(attr_name, force_matrix) for attr_name, force_matrix in [ (N_NODE, False), (N_EDGE, False), (RECEIVERS, True), (SENDERS, True), (NODES, True), (EDGES, True), (GLOBALS, True), ] ) # Check padding consistent across hypergraphs assert len(set(h.zero_padding for h in graphs_tuple_list)) == 1 zero_padding = graphs_tuple_list[0].zero_padding # Check general sizes have been maintained assert len(n_node) == len(n_edge) == len(graphs_tuple_list) assert receivers.shape[0] == senders.shape[0] == torch.sum(n_edge) if edges is not None: assert edges.shape[0] == torch.sum(n_edge) if nodes is not None: assert nodes.shape[0] == torch.sum(n_node) if globals_ is not None: assert globals_.shape[0] == len(graphs_tuple_list) return HypergraphsTuple( **{ N_NODE: n_node, N_EDGE: n_edge, # Hyperedge connection information RECEIVERS: receivers, SENDERS: senders, # Features, turn them to tensors NODES: nodes, EDGES: edges, GLOBALS: globals_, ZERO_PADDING: zero_padding, } )
python