content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python # Programmer(s): Sopan Patil. """ MAIN PROGRAM FILE Run this file to optimise the model parameters of the spatially distributed version of EXP-HYDRO model using Particle Swarm Optimisation (PSO) algorithm. Type 1 Model: - This type of distributed model is pixel based (i.e., all sub-components have the same drainage area). - All pixels receive the same meteorological inputs. - Channel routing is ignored and it is assumed that streamflow generated from each pixel reaches the catchment outlet on same day. """ import numpy import os import time import matplotlib.pyplot as plt from exphydro.distributed import ExphydroDistrParameters from exphydro.distributed.type1 import ExphydroDistrModel from hydroutils import Calibration, ObjectiveFunction start_time = time.time() ###################################################################### # SET WORKING DIRECTORY # Getting current directory, i.e., directory containing this file dir1 = os.path.dirname(os.path.abspath('__file__')) # Setting to current directory os.chdir(dir1) ###################################################################### # MAIN PROGRAM # Load meteorological and observed flow data P = numpy.genfromtxt('SampleData/P_test.txt') # Observed rainfall (mm/day) T = numpy.genfromtxt('SampleData/T_test.txt') # Observed air temperature (deg C) PET = numpy.genfromtxt('SampleData/PET_test.txt') # Potential evapotranspiration (mm/day) Qobs = numpy.genfromtxt('SampleData/Q_test.txt') # Observed streamflow (mm/day) # Specify the number of pixels in the catchment npixels = 5 # Specify the no. of parameter sets (particles) in a PSO swarm npart = 10 # Generate 'npart' initial EXP-HYDRO model parameters params = [ExphydroDistrParameters(npixels) for j in range(npart)] # Initialise the model by loading its climate inputs model = ExphydroDistrModel(P, PET, T, npixels) # Specify the start and end day numbers of the calibration period. # This is done separately for the observed and simulated data # because they might not be of the same length in some cases. calperiods_obs = [365, 2557] calperiods_sim = [365, 2557] # Calibrate the model to identify optimal parameter set paramsmax = Calibration.pso_maximise(model, params, Qobs, ObjectiveFunction.klinggupta, calperiods_obs, calperiods_sim) print ('Calibration run KGE value = ', paramsmax.objval) # Run the optimised model for validation period Qsim = model.simulate(paramsmax) kge = ObjectiveFunction.klinggupta(Qobs[calperiods_obs[1]:], Qsim[calperiods_sim[1]:]) print ('Independent run KGE value = ', kge) print("Total runtime: %s seconds" % (time.time() - start_time)) # Plot the observed and simulated hydrographs plt.plot(Qobs[calperiods_obs[0]:], 'b-') plt.plot(Qsim[calperiods_sim[0]:], 'r-') plt.show() ######################################################################
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 6118, 647, 7, 82, 2599, 35643, 272, 3208, 346, 13, 198, 198, 37811, 8779, 1268, 46805, 45811, 198, 10987, 428, 2393, 284, 6436, 786, 262, 2746, 10007, 286, 262, 15246, 1927, ...
3.365135
849
import os from multi_input_multi_output.models import MultiNet from shared_weights.helpers import config, utils from shared_weights.helpers.siamese_network import create_encoder from data.data_tf import fat_dataset import tensorflow as tf from tensorflow import keras # ---------------------- """ Data augmentation""" augmentation_input = keras.layers.Input(shape=config.IMG_SHAPE) data_augmentation = keras.layers.experimental.preprocessing.RandomTranslation( height_factor=(-0.2, 0.2), width_factor=(-0.2, 0.2), fill_mode="constant" )(augmentation_input) data_augmentation = keras.layers.experimental.preprocessing.RandomFlip(mode="horizontal")(data_augmentation) data_augmentation = keras.layers.experimental.preprocessing.RandomRotation(factor=0.15, fill_mode="constant")(data_augmentation) augmentation_output = keras.layers.experimental.preprocessing.RandomZoom(height_factor=(-0.3, 0.1), width_factor=(-0.3, 0.1), fill_mode="constant")(data_augmentation) data_augmentation = keras.Model(augmentation_input, augmentation_output) """ Unsupervised contrastive loss""" """ Train the model""" network_input = keras.layers.Input(shape=config.IMG_SHAPE) # Load RGB vision encoder. r_encoder = create_encoder(base='resnet50', pretrained=True)(network_input) encoder_output = keras.layers.Dense(config.HIDDEN_UNITS)(r_encoder) r_encoder = keras.Model(network_input, encoder_output) # Create representation learner. r_representation_learner = RepresentationLearner( r_encoder, config.PROJECTION_UNITS, num_augmentations=2, temperature=0.1 ) r_representation_learner.build((None, 128, 128, 3)) # base_path = os.environ['PYTHONPATH'].split(os.pathsep)[1] # representation_learner.load_weights(base_path + '/multi_input_multi_output/simclr/weights/simclr_resnet50_rgb_scratch_weights.h5') r_representation_learner.load_weights(config.RGB_MODALITY_WEIGHT_PATH) functional_model = flatten_model(r_representation_learner.layers[0]) rgb_encoder = functional_model.layers[1] # Load Depth vision encoder. d_encoder = create_encoder(base='resnet50', pretrained=True)(network_input) encoder_output = keras.layers.Dense(config.HIDDEN_UNITS)(d_encoder) d_encoder = keras.Model(network_input, encoder_output) # Create representation learner. d_representation_learner = RepresentationLearner( d_encoder, config.PROJECTION_UNITS, num_augmentations=2, temperature=0.1 ) d_representation_learner.build((None, 128, 128, 3)) # base_path = os.environ['PYTHONPATH'].split(os.pathsep)[1] # representation_learner.load_weights(base_path + '/multi_input_multi_output/simclr/weights/simclr_resnet50_rgb_scratch_weights.h5') d_representation_learner.load_weights(config.DEPTH_MODALITY_WEIGHT_PATH) functional_model = flatten_model(d_representation_learner.layers[0]) depth_encoder = functional_model.layers[1] # ---------------------- # RGB rgb_input = keras.layers.Input(shape=config.IMG_SHAPE) # rgb_encoder = keras.applications.ResNet50V2(include_top=False, # weights=None, # input_shape=config.IMG_SHAPE, # pooling="avg") rgb = rgb_encoder(rgb_input) rgb = keras.layers.Dropout(config.DROPOUT_RATE)(rgb) rgb = keras.layers.Dense(config.HIDDEN_UNITS, activation="relu")(rgb) rgb = keras.layers.Dropout(config.DROPOUT_RATE)(rgb) rgb = keras.layers.Flatten()(rgb) rgb = keras.layers.Dense(config.NUM_OF_CLASSES, activation="softmax")(rgb) rgb_classifier = keras.models.Model(inputs=rgb_input, outputs=rgb, name='rgb_classifier') for layer in rgb_classifier.layers: layer._name += '_rgb' layer.trainable = True print('[INFO] built rgb classifier') print(rgb_classifier.summary()) # Depth depth_input = keras.layers.Input(shape=config.IMG_SHAPE) # depth_encoder = keras.applications.ResNet50V2(include_top=False, # weights=None, # input_shape=config.IMG_SHAPE, # pooling="avg") depth = depth_encoder(depth_input) depth = keras.layers.Dropout(config.DROPOUT_RATE)(depth) depth = keras.layers.Dense(config.HIDDEN_UNITS, activation="relu")(depth) depth = keras.layers.Dropout(config.DROPOUT_RATE)(depth) depth = keras.layers.Flatten()(depth) depth = keras.layers.Dense(config.NUM_OF_CLASSES, activation="softmax")(depth) depth_classifier = keras.models.Model(inputs=depth_input, outputs=depth, name='depth_classifier') for layer in depth_classifier.layers: layer._name += '_depth' layer.trainable = True print('[INFO] built depth classifier') print(depth_classifier.summary()) # Build and compile MultiNet multinet_class = MultiNet(rgb_classifier=rgb_classifier, rgb_output_branch=rgb, depth_classifier=depth_classifier, depth_output_branch=depth) multinet_class.compile() multinet_model = multinet_class.model print('[INFO] built MultiNet classifier') # train the network to perform multi-output classification train_ds = fat_dataset(split='train', data_type='all', batch_size=config.BATCH_SIZE, shuffle=True, pairs=False) val_ds = fat_dataset(split='validation', data_type='all', batch_size=config.BATCH_SIZE, shuffle=True, pairs=False) print("[INFO] training MultiNet...") counter = 0 history = None toCSV = [] while counter <= config.EPOCHS: counter += 1 print(f'* Epoch: {counter}') data_batch = 0 for imgs, labels in train_ds: data_batch += 1 history = multinet_model.train_on_batch(x=[imgs[:, 0], imgs[:, 1]], y={'dense_5_rgb': labels[:], 'dense_7_depth': labels[:]}, reset_metrics=False, return_dict=True) print(f'* Data Batch: {data_batch}') print(f'\t{history}') break if counter % 10 == 0: print("[VALUE] Testing model on batch") for val_data, val_labels in val_ds: val_results = multinet_model.test_on_batch(x=[val_data[:, 0], val_data[:, 1]], y={'dense_5_rgb': val_labels[:], 'dense_7_depth': val_labels[:]}) print(val_results) toCSV.append(val_results) print('Saving MultiNet validation results as CSV file') utils.save_model_history(H=toCSV, path_to_csv=config.FROZEN_SIAMESE_TRAINING_HISTORY_CSV_PATH) rgb_classifier.save_weights(config.MIMO_RGB_WEIGHTS) print("Saved RGB model weights to disk") # serialize weights to HDF5 depth_classifier.save_weights(config.MIMO_DEPTH_WEIGHTS) print("Saved Depth model weights to disk")
[ 11748, 28686, 198, 198, 6738, 5021, 62, 15414, 62, 41684, 62, 22915, 13, 27530, 1330, 15237, 7934, 198, 198, 6738, 4888, 62, 43775, 13, 16794, 364, 1330, 4566, 11, 3384, 4487, 198, 6738, 4888, 62, 43775, 13, 16794, 364, 13, 13396, 104...
2.182627
3,258
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import logging from lookyloo.lookyloo import Indexing, Lookyloo logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s:%(message)s', level=logging.INFO) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 198, 6738, 804, 2645, 2238, 13, 5460, 2645, 2238, 1330, 12901, 278...
2.215385
130
import tensorflow as tf sess=tf.Session() #First let's load meta graph and restore weights saver = tf.train.import_meta_graph('/Users/lipingzhang/Downloads/model/my_tf_model-1000.meta') saver.restore(sess,tf.train.latest_checkpoint('/Users/lipingzhang/Downloads/model/')) # Now, let's access and create placeholders variables and # create feed-dict to feed new data graph = tf.get_default_graph() w1 = graph.get_tensor_by_name("w1:0") w2 = graph.get_tensor_by_name("w2:0") feed_dict ={w1:13.0,w2:17.0} #Now, access the op that you want to run. op_to_restore = graph.get_tensor_by_name("op_to_restore:0") #Add more to the current graph add_on_op = tf.multiply(op_to_restore,2) print sess.run(add_on_op,feed_dict) #This will print 120.
[ 11748, 11192, 273, 11125, 355, 48700, 198, 198, 82, 408, 28, 27110, 13, 36044, 3419, 198, 2, 5962, 1309, 338, 3440, 13634, 4823, 290, 11169, 19590, 198, 82, 8770, 796, 48700, 13, 27432, 13, 11748, 62, 28961, 62, 34960, 10786, 14, 1449...
2.542955
291
from random import randrange if __name__ == "__main__": main()
[ 6738, 4738, 1330, 43720, 9521, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 197, 12417, 3419 ]
3.095238
21
# ARRAYS-DS HACKERANK SOLUTION: # creating a function to reverse the array. # receiving input. arr_count = int(input().strip()) arr = list(map(int, input().rstrip().split())) # printing the output. print(reverseArray(arr))
[ 2, 5923, 3861, 16309, 12, 5258, 367, 8120, 1137, 15154, 36817, 35354, 25, 201, 198, 201, 198, 2, 4441, 257, 2163, 284, 9575, 262, 7177, 13, 201, 198, 201, 198, 2, 6464, 5128, 13, 201, 198, 3258, 62, 9127, 796, 493, 7, 15414, 22446...
2.853659
82
from django.contrib import admin from django.contrib.admin import SimpleListFilter from django.db.models import TextChoices from django.utils.html import format_html from . import models
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 28482, 1330, 17427, 8053, 22417, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 8255, 22164, 1063, 198, 6738, 42625, 14208, 13, 26791, 13, ...
3.603774
53
/home/runner/.cache/pip/pool/34/e0/75/b2dceb8ef40c652edb20f4e059370015eddc8cdbde039f92ced519a83d
[ 14, 11195, 14, 16737, 11757, 23870, 14, 79, 541, 14, 7742, 14, 2682, 14, 68, 15, 14, 2425, 14, 65, 17, 67, 344, 65, 23, 891, 1821, 66, 43193, 276, 65, 1238, 69, 19, 68, 46712, 2718, 405, 1314, 6048, 66, 23, 66, 9945, 2934, 15,...
1.777778
54
#https://qiita.com/stkdev/items/a44976fb81ae90a66381 #import imaplib, re, email, six, dateutil.parser import imaplib, re, email email_default_encoding = 'iso-2022-jp' if __name__ == '__main__': main()
[ 2, 5450, 1378, 40603, 5350, 13, 785, 14, 301, 74, 7959, 14, 23814, 14, 64, 31911, 4304, 21855, 6659, 3609, 3829, 64, 2791, 36626, 198, 2, 11748, 545, 64, 489, 571, 11, 302, 11, 3053, 11, 2237, 11, 3128, 22602, 13, 48610, 198, 1174...
2.37931
87
import binascii import datetime import hashlib import mimetypes import os import re import struct import subprocess import sys import time import urllib import csv from Queue import Queue # 8 byte unique ID generator give a path. # - first five bytes are first five from sha1 of path name # - last 3 are the first three from the current time # Returns a long BUFFER = 4096 omitted_dirs = ['/dev', '/proc', '/sys', '/Volumes', '/mnt', '/net'] if __name__=="__main__": main(sys.argv)
[ 11748, 9874, 292, 979, 72, 198, 11748, 4818, 8079, 198, 11748, 12234, 8019, 198, 11748, 17007, 2963, 12272, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 2878, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 2956...
3.055215
163
import csv_loader import moves_names
[ 11748, 269, 21370, 62, 29356, 198, 11748, 6100, 62, 14933, 198 ]
3.363636
11
import datetime import decimal from unittest.mock import patch import pytest from click.testing import CliRunner from psycopg2 import sql from manage import SUMMARIES, cli, construct_where_fragment from tests import assert_bad_argument, assert_log_records, assert_log_running, fixture, noop command = 'add' TABLES = { 'note', } SUMMARY_TABLES = set() SUMMARY_VIEWS = set() FIELD_LIST_TABLES = set() NO_FIELD_LIST_TABLES = set() NO_FIELD_LIST_VIEWS = set() for table_name, table in SUMMARIES.items(): FIELD_LIST_TABLES.add(f'{table_name}_field_list') if table.is_table: SUMMARY_TABLES.add(table_name) NO_FIELD_LIST_TABLES.add(f'{table_name}_no_field_list') else: SUMMARY_VIEWS.add(table_name) NO_FIELD_LIST_VIEWS.add(f'{table_name}_no_field_list') TABLES.add(f'{table_name}_no_data')
[ 11748, 4818, 8079, 198, 11748, 32465, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 11748, 12972, 9288, 198, 6738, 3904, 13, 33407, 1330, 1012, 72, 49493, 198, 6738, 17331, 22163, 70, 17, 1330, 44161, 198, 198, 6738, 66...
2.331507
365
import os from docx import Document from docx.shared import Inches from docx import section from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Pt from docx.shared import Cm from docx.shared import RGBColor import docx
[ 11748, 28686, 201, 198, 6738, 2205, 87, 1330, 16854, 201, 198, 6738, 2205, 87, 13, 28710, 1330, 554, 2052, 201, 198, 6738, 2205, 87, 1330, 2665, 201, 198, 6738, 2205, 87, 13, 44709, 13, 5239, 1330, 48963, 62, 1847, 16284, 62, 27082, ...
3.024691
81
# Copying files # Ask user for a list of 3 friends. # for each friend, we'll tell user whether they're nearby. # for each nearby friend, we'll save their name to `nearby_friends.txt`. friends = input('Enter three friends name(separated by commas): ').split(',') people = open('people.txt', 'r') people_nearby = [line.strip() for line in people.readlines()] people.close() # Making set of friends and peoples friends_set = set(friends) people_nearby_set = set(people_nearby) friends_nearby_set = friends_set.intersection(people_nearby_set) nearby_friends_file = open('nearby_friends.txt', 'w') for friend in friends_nearby_set: print(f'{friend} is nearby.! Meet up with them.') nearby_friends_file.write(f'{friend}\n') nearby_friends_file.close()
[ 2, 6955, 1112, 3696, 198, 198, 2, 16981, 2836, 329, 257, 1351, 286, 513, 2460, 13, 198, 2, 329, 1123, 1545, 11, 356, 1183, 1560, 2836, 1771, 484, 821, 6716, 13, 198, 2, 329, 1123, 6716, 1545, 11, 356, 1183, 3613, 511, 1438, 284, ...
3.007874
254
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n, m, x = map(int, input().split()) ca = [0] * n ca_sum = [0] * (m+1) for i in range(n): ca[i] = list(map(int, input().split())) for j in range(m+1): ca_sum[j] += ca[i][j] ans = 10 ** 10 for i in range(2 ** n): tmp = 0 tmp_ca_sum = ca_sum.copy() for j, v in enumerate(format(i, r'0{}b'.format(n))): if v == '0': continue for k in range(m+1): tmp_ca_sum[k] -= ca[j][k] flag = True for v2 in tmp_ca_sum[1:]: if v2 < x: flag = False break if flag: ans = min(ans, tmp_ca_sum[0]) if ans == 10 ** 10: print(-1) else: print(ans)
[ 11748, 25064, 198, 15414, 796, 25064, 13, 19282, 259, 13, 961, 1370, 198, 17597, 13, 2617, 8344, 24197, 32374, 7, 940, 12429, 767, 8, 198, 198, 77, 11, 285, 11, 2124, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 6888, 796,...
1.865633
387
from django import forms from .models import Passwords
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 27530, 1330, 6251, 10879, 628 ]
4.307692
13
NAME = "Azure BLOB storage" TYPE = "remote" FILE = "AzureBlob.yaml" VARS = [ "AZURE_BLOB_STORAGE_ACCOUNT", "AZURE_BLOB_STORAGE_ACCOUNT_KEY", "AZURE_BLOB_CONTAINER_NAME", ]
[ 20608, 796, 366, 26903, 495, 9878, 9864, 6143, 1, 198, 25216, 796, 366, 47960, 1, 198, 25664, 796, 366, 26903, 495, 3629, 672, 13, 88, 43695, 1, 198, 53, 27415, 796, 685, 198, 220, 220, 220, 366, 22778, 11335, 62, 9148, 9864, 62, ...
2.044444
90
import unittest from application import app from application.helpers import( requires_authentication, requires_feature, signed_in, group_by_group, signed_in_no_access, no_access, has_user_with_token, view_helpers, user_has_feature, ) from hamcrest import assert_that, equal_to, is_ from mock import patch def test_group_by_group_groups_datasets_by_group(self): data_sets = [ { 'data_group': "group_1", 'data_type': "type1" }, { 'data_group': "group_1", 'data_type': "type2" }, { 'data_group': "group_2", 'data_type': "type3" } ] grouped_data_sets = { "group_1": [ { 'data_group': "group_1", 'data_type': "type1" }, { 'data_group': "group_1", 'data_type': "type2" } ], "group_2": [ { 'data_group': "group_2", 'data_type': "type3" } ] } assert_that(group_by_group(data_sets), equal_to(grouped_data_sets)) def test_admin_user_has_bigedit_feature(self): user = {'permissions': ['admin']} assert_that(user_has_feature('big-edit', user), equal_to(True)) def test_dashboard_editor_user_does_not_have_bigedit_feature(self): user = {'permissions': ['dashboard-editor']} assert_that(user_has_feature('big-edit', user), equal_to(False)) def test_dashboard_editor_and_admin_user_does_have_bigedit_feature(self): user = {'permissions': ['dashboard-editor', 'admin']} assert_that(user_has_feature('big-edit', user), equal_to(True)) def test_user_with_permissions_not_in_list_features(self): user = {'permissions': ['signin']} assert_that(user_has_feature('big-edit', user), equal_to(False))
[ 11748, 555, 715, 395, 198, 6738, 3586, 1330, 598, 198, 6738, 3586, 13, 16794, 364, 1330, 7, 198, 220, 220, 220, 4433, 62, 41299, 3299, 11, 198, 220, 220, 220, 4433, 62, 30053, 11, 198, 220, 220, 220, 4488, 62, 259, 11, 198, 220, ...
1.869369
1,110
from random import * #STRATEGY SUMMARY: DON'T DUCK IF THE OPPONENT HAS NO SNOWBALLS. OTHERWISE, PICK RANDOMLY.
[ 6738, 4738, 1330, 1635, 198, 198, 2, 18601, 6158, 31212, 35683, 44, 13153, 25, 220, 23917, 6, 51, 360, 16696, 16876, 3336, 440, 10246, 1340, 3525, 33930, 8005, 11346, 3913, 33, 1847, 6561, 13, 25401, 54, 24352, 11, 350, 11860, 46920, ...
2.352941
51
from rest_framework import viewsets from customers.models import Customer from customers.serializers.customers import CustomerSerializer # Create your views here.
[ 6738, 1334, 62, 30604, 1330, 5009, 1039, 198, 198, 6738, 4297, 13, 27530, 1330, 22092, 198, 6738, 4297, 13, 46911, 11341, 13, 23144, 364, 1330, 22092, 32634, 7509, 198, 198, 2, 13610, 534, 5009, 994, 13, 628 ]
4.486486
37
""" Expect action directives """ from __future__ import ( absolute_import, unicode_literals, ) from pyparsing import ( CaselessLiteral, LineEnd, Literal, Optional, Suppress, ) from pysoa.test.plan.grammar.assertions import ( assert_not_expected, assert_not_present, assert_subset_structure, ) from pysoa.test.plan.grammar.data_types import ( DataTypeGrammar, get_parsed_data_type_value, ) from pysoa.test.plan.grammar.directive import ( ActionDirective, VarNameGrammar, VarValueGrammar, register_directive, ) from pysoa.test.plan.grammar.tools import path_put class ActionExpectsAnyDirective(ActionExpectsFieldValueDirective): """ Set expectations for values to be in the service call response where any value for the given data type will be accepted. """ def assert_test_case_action_results( self, action_name, action_case, test_case, test_fixture, action_response, job_response, msg=None, **kwargs ): if 'expects_not_present' in action_case: assert_not_present( action_case['expects_not_present'], action_response.body, msg, ) register_directive(ActionExpectsFieldValueDirective) register_directive(ActionExpectsAnyDirective) register_directive(ActionExpectsNoneDirective) register_directive(ActionExpectsNotPresentDirective)
[ 37811, 198, 3109, 806, 2223, 34819, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 357, 198, 220, 220, 220, 4112, 62, 11748, 11, 198, 220, 220, 220, 28000, 1098, 62, 17201, 874, 11, 198, 8, 198, 198, 6738, 279, 4464, 945, 278, 1330...
2.387722
619
''' Script to add uuid to existing records Also shifts who_code values to original_who_code ''' import uuid import pandas as pd manually_cleaned = pd.read_csv('data/cleansed/mistress_latest_old.csv', low_memory=False) manually_cleaned['uuid'] = [str(uuid.uuid4()) for x in manually_cleaned.iloc[:, 1]] manually_cleaned['original_who_code'] = manually_cleaned['who_code'] manually_cleaned.to_csv('data/cleansed/mistress_latest.csv', index = False)
[ 7061, 6, 198, 198, 7391, 284, 751, 334, 27112, 284, 4683, 4406, 198, 198, 7583, 15381, 508, 62, 8189, 3815, 284, 2656, 62, 8727, 62, 8189, 198, 198, 7061, 6, 198, 11748, 334, 27112, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, ...
2.718563
167
"""Tests for `prettyqt` package.""" import pathlib import pytest from prettyqt import core, qml from prettyqt.utils import InvalidParamError # def test_jsvalue(): # val = qml.JSValue(2) # val["test"] = 1 # assert val["test"].toInt() == 1 # assert "test" in val # assert val.get_value() == 2
[ 37811, 51, 3558, 329, 4600, 37784, 39568, 63, 5301, 526, 15931, 198, 198, 11748, 3108, 8019, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 2495, 39568, 1330, 4755, 11, 10662, 4029, 198, 6738, 2495, 39568, 13, 26791, 1330, 17665, 22973, ...
2.568
125
# Simple test for NeoPixels on Raspberry Pi import time import board import neopixel # Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18 # NeoPixels must be connected to D10, D12, D18 or D21 to work. pixel_pin = board.D18 # The number of NeoPixels num_pixels = 30 # The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed! # For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW. ORDER = neopixel.GRB pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER) try: while True: print("light start") repeat_fun(5, white_breath) # rainbow cycle with 1ms delay per step repeat_fun(3, rainbow_cycle, 0.01) # white_breath() # for i in range(num_pixels): # for r in range(255): # pixels[i] = (r, 0, 0) # pixels.show() # time.sleep(0.001) # j = i - 1 # for y in range(255): # pixels[j] = (y, y, y) # pixels.show() # time.sleep(0.001) # time.sleep(0.01) except KeyboardInterrupt: print("KeyboardInterrupt has been caught.")
[ 2, 17427, 1332, 329, 21227, 47, 14810, 319, 24244, 13993, 198, 11748, 640, 198, 11748, 3096, 198, 11748, 497, 404, 7168, 628, 198, 2, 17489, 281, 1280, 6757, 5884, 284, 262, 6060, 554, 286, 262, 21227, 40809, 10283, 11, 1312, 13, 68, ...
2.163823
586
from transitions.extensions import GraphMachine
[ 6738, 27188, 13, 2302, 5736, 1330, 29681, 37573, 628 ]
5.444444
9
# Copyright (c) 2018 Workonline Communications (Pty) Ltd. All rights reserved. # # The contents of this file are licensed under the Apache License version 2.0 # (the "License"); you may not use this file except in compliance with the # License. # # 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. """rptk module.query module.""" from __future__ import print_function from __future__ import unicode_literals from rptk.base import BaseObject try: basestring except NameError: basestring = str try: unicode except NameError: unicode = str
[ 2, 15069, 357, 66, 8, 2864, 5521, 25119, 14620, 357, 47, 774, 8, 12052, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 383, 10154, 286, 428, 2393, 389, 11971, 739, 262, 24843, 13789, 2196, 362, 13, 15, 198, 2, 357, 1169, 366, 34156, ...
3.699552
223
#!/usr/bin/env python # vim:ts=4:sts=4:sw=4:et # # Author: Hari Sekhon # Date: 2015-11-14 12:21:54 +0000 (Sat, 14 Nov 2015) # # https://github.com/HariSekhon/pylib # # License: see accompanying Hari Sekhon LICENSE file # # If you're using my code you're welcome to connect with me on LinkedIn # and optionally send me feedback to help improve or steer this or other code I publish # # http://www.linkedin.com/in/harisekhon # from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os #import glob #import inspect #import subprocess #import sys ## using optparse rather than argparse for servers still on Python 2.6 #from optparse import OptionParser # libdir = os.path.join(os.path.dirname(inspect.getfile(inspect.currentframe())), '..') libdir = os.path.join(os.path.dirname(__file__), '..') # sys.path.append(libdir) # try: # from harisekhon.utils import * # except ImportError, e: # print('module import failed: %s' % e) # sys.exit(4) __author__ = 'Hari Sekhon' __version__ = '0.1' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 220, 43907, 25, 912, 28, 19, 25, 6448, 28, 19, 25, 2032, 28, 19, 25, 316, 198, 2, 198, 2, 220, 6434, 25, 2113, 72, 37558, 24130, 198, 2, 220, 7536, 25, 1853, 12, 1157, 12, ...
2.824691
405
import unittest import pickle from array import array import complete_tdf from floodberry.floodberry_ed25519 import GE25519 from tdf_strucs import TDFMatrix, TDFError from complete_tdf import CTDFCodec as Codec, CTDFCipherText as CipherText from utils import int_lst_to_bitarr TEST_DIR = "legacy/tests/" PACK_TEST_KEY_FILE = TEST_DIR + "ctdf_pack_test_keys.p" PACK_TEST_CT_FILE = TEST_DIR + "ctdf_pack_test_ct.p" TDF_KEY_FILE = TEST_DIR + "ctdf_test_keys.p" TDF_CT_FILE = TEST_DIR + "ctdf_test_ct.p" """ x = [0,1,2] ctdf = CTDFCodec(len(x)*8) u = ctdf.encode(x) result = ctdf.decode(u) """ TDF = Codec.deserialize(TDF_KEY_FILE) CT = CipherText.deserialize(TDF_CT_FILE) X = int_lst_to_bitarr([0,1,2], 3)
[ 11748, 555, 715, 395, 198, 11748, 2298, 293, 198, 6738, 7177, 1330, 7177, 198, 11748, 1844, 62, 83, 7568, 198, 198, 6738, 6947, 8396, 13, 2704, 702, 8396, 62, 276, 13381, 1129, 1330, 22319, 13381, 1129, 198, 6738, 256, 7568, 62, 19554...
2.269231
312
import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wherethefuck.settings') # create and run celery workers. app = Celery(broker=settings.CELERY_BROKER_URL) app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS) if __name__ == '__main__': app.start()
[ 11748, 28686, 198, 6738, 18725, 1924, 1330, 15248, 1924, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 198, 2, 900, 262, 4277, 37770, 6460, 8265, 329, 262, 705, 7015, 88, 6, 1430, 13, 198, 418, 13, 268, 2268, 13, 2617, 12286, ...
2.912162
148
from MLSR.data import DataSet from MLSR.plot import * x = DataSet('data/rand_select_400_avg.csv') x.generate_feature() y = DataSet('data/not_selected_avg.csv') y.generate_feature() z = DataSet.static_merge(x, y) #plot_tsne(z, 'log/tsne.png') z = z.convert_to_ssl() z0, z1 = z.split_by_weak_label() plot_tsne_ssl(z0, 'log/0_tsne.png', n_iter=300) plot_tsne_ssl(z1, 'log/1_tsne.png', n_iter=500)
[ 6738, 13981, 49, 13, 7890, 1330, 6060, 7248, 198, 6738, 13981, 49, 13, 29487, 1330, 1635, 198, 198, 87, 796, 6060, 7248, 10786, 7890, 14, 25192, 62, 19738, 62, 7029, 62, 615, 70, 13, 40664, 11537, 198, 87, 13, 8612, 378, 62, 30053, ...
2.135135
185
import numpy as np import scipy.io as sio import os, glob, sys import h5py_cache as h5c sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal') sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal/source') from batch_gen_hdf5 import BatchGeneratorWithSceneMeshMatfile import torch ''' In this script, we put all mat files into a hdf5 file, so as to speed up the data loading process. ''' dataset_path = '/mnt/hdd/PROX/snapshot_realcams_v3' outfilename = 'realcams.hdf5' h5file_path = os.path.join('/home/yzhang/Videos/PROXE', outfilename) batch_gen = BatchGeneratorWithSceneMeshMatfile(dataset_path=dataset_path, scene_verts_path = '/home/yzhang/Videos/PROXE/scenes_downsampled', scene_sdf_path = '/home/yzhang/Videos/PROXE/scenes_sdf', device=torch.device('cuda')) ### create the dataset used in the hdf5 file with h5c.File(h5file_path, mode='w',chunk_cache_mem_size=1024**2*128) as hdf5_file: while batch_gen.has_next_batch(): train_data = batch_gen.next_batch(1) if train_data is None: continue train_data_np = [x.detach().cpu().numpy() for x in train_data[:-1]] break [depth_batch, seg_batch, body_batch, cam_ext_batch, cam_int_batch, max_d_batch, s_verts_batch, s_faces_batch, s_grid_min_batch, s_grid_max_batch, s_grid_dim_batch, s_grid_sdf_batch] = train_data_np n_samples = batch_gen.n_samples print('-- n_samples={:d}'.format(n_samples)) hdf5_file.create_dataset("sceneid", shape=(1,), chunks=True, dtype=np.float32, maxshape=(None,) ) hdf5_file.create_dataset("depth", shape=(1,)+tuple(depth_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(depth_batch.shape[1:]) ) hdf5_file.create_dataset("seg", shape=(1,)+tuple(seg_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(seg_batch.shape[1:]) ) hdf5_file.create_dataset("body", shape=(1,)+tuple(body_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(body_batch.shape[1:]) ) hdf5_file.create_dataset("cam_ext", shape=(1,)+tuple(cam_ext_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(cam_ext_batch.shape[1:]) ) hdf5_file.create_dataset("cam_int", shape=(1,)+tuple(cam_int_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(cam_int_batch.shape[1:]) ) hdf5_file.create_dataset("max_d", shape=(1,)+tuple(max_d_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(max_d_batch.shape[1:]) ) # hdf5_file.create_dataset("s_verts", shape=(1,)+tuple(s_verts_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_verts_batch.shape[1:]) ) # hdf5_file.create_dataset("s_faces", shape=(1,)+tuple(s_faces_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_faces_batch.shape[1:]) ) # hdf5_file.create_dataset("s_grid_min", shape=(1,)+tuple(s_grid_min_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_min_batch.shape[1:])) # hdf5_file.create_dataset("s_grid_max", shape=(1,)+tuple(s_grid_max_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_max_batch.shape[1:])) # hdf5_file.create_dataset("s_grid_dim", shape=(1,)+tuple(s_grid_dim_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_dim_batch.shape[1:])) # hdf5_file.create_dataset("s_grid_sdf", shape=(1,)+tuple(s_grid_sdf_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_sdf_batch.shape[1:])) batch_gen.reset() scene_list = ['BasementSittingBooth','MPH1Library', 'MPH8', 'MPH11', 'MPH16', 'MPH112', 'N0SittingBooth', 'N0Sofa', 'N3Library', 'N3Office', 'N3OpenArea', 'Werkraum'] # !!!! important!cat ### create the dataset used in the hdf5 file idx = -1 while batch_gen.has_next_batch(): train_data = batch_gen.next_batch(1) if train_data is None: continue [depth_batch, seg_batch, body_batch, cam_ext_batch, cam_int_batch, max_d_batch, s_verts_batch, s_faces_batch, s_grid_min_batch, s_grid_max_batch, s_grid_dim_batch, s_grid_sdf_batch, filename_list] = train_data ## check unavaliable prox fitting body_z_batch = body_batch[:,2] if body_z_batch.abs().max() >= max_d_batch.abs().max(): print('-- encountered bad prox fitting. Skip it') continue if body_z_batch.min() <=0: print('-- encountered bad prox fitting. Skip it') continue idx = idx+1 print('-- processing batch idx {:d}'.format(idx)) filename = filename_list[0] scenename = filename.split('/')[-2].split('_')[0] sid = [scene_list.index(scenename)] hdf5_file["sceneid"].resize((hdf5_file["sceneid"].shape[0]+1, )) hdf5_file["sceneid"][-1,...] = sid[0] hdf5_file["depth"].resize((hdf5_file["depth"].shape[0]+1, )+hdf5_file["depth"].shape[1:]) hdf5_file["depth"][-1,...] = depth_batch[0].detach().cpu().numpy() hdf5_file["seg"].resize((hdf5_file["seg"].shape[0]+1, )+hdf5_file["seg"].shape[1:]) hdf5_file["seg"][-1,...] = seg_batch[0].detach().cpu().numpy() hdf5_file["body"].resize((hdf5_file["body"].shape[0]+1, )+hdf5_file["body"].shape[1:]) hdf5_file["body"][-1,...] = body_batch[0].detach().cpu().numpy() hdf5_file["cam_ext"].resize((hdf5_file["cam_ext"].shape[0]+1, )+hdf5_file["cam_ext"].shape[1:]) hdf5_file["cam_ext"][-1,...] = cam_ext_batch[0].detach().cpu().numpy() hdf5_file["cam_int"].resize((hdf5_file["cam_int"].shape[0]+1, )+hdf5_file["cam_int"].shape[1:]) hdf5_file["cam_int"][-1,...] = cam_int_batch[0].detach().cpu().numpy() hdf5_file["max_d"].resize((hdf5_file["max_d"].shape[0]+1, )+hdf5_file["max_d"].shape[1:]) hdf5_file["max_d"][-1,...] = max_d_batch[0].detach().cpu().numpy() # hdf5_file["s_verts"].resize((hdf5_file["s_verts"].shape[0]+1, )+hdf5_file["s_verts"].shape[1:]) # hdf5_file["s_verts"][-1,...] = s_verts_batch[0].detach().cpu().numpy() # hdf5_file["s_faces"].resize((hdf5_file["s_faces"].shape[0]+1, )+hdf5_file["s_faces"].shape[1:]) # hdf5_file["s_faces"][-1,...] = s_faces_batch[0].detach().cpu().numpy() # hdf5_file["s_grid_min"].resize((hdf5_file["s_grid_min"].shape[0]+1, )+hdf5_file["s_grid_min"].shape[1:]) # hdf5_file["s_grid_min"][-1,...] = s_grid_min_batch[0].detach().cpu().numpy() # hdf5_file["s_grid_max"].resize((hdf5_file["s_grid_max"].shape[0]+1, )+hdf5_file["s_grid_max"].shape[1:]) # hdf5_file["s_grid_max"][-1,...] = s_grid_max_batch[0].detach().cpu().numpy() # hdf5_file["s_grid_dim"].resize((hdf5_file["s_grid_dim"].shape[0]+1, )+hdf5_file["s_grid_dim"].shape[1:]) # hdf5_file["s_grid_dim"][-1,...] = s_grid_dim_batch[0].detach().cpu().numpy() # hdf5_file["s_grid_sdf"].resize((hdf5_file["s_grid_sdf"].shape[0]+1, )+hdf5_file["s_grid_sdf"].shape[1:]) # hdf5_file["s_grid_sdf"][-1,...] = s_grid_sdf_batch[0].detach().cpu().numpy() print('--file converting finish')
[ 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 952, 355, 264, 952, 198, 11748, 28686, 11, 15095, 11, 25064, 198, 11748, 289, 20, 9078, 62, 23870, 355, 289, 20, 66, 198, 198, 17597, 13, 6978, 13, 33295, 10786, 14, 11195...
1.978795
3,867
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198 ]
3.625
8
# -*- coding: utf-8 -*- from fontbro import Font from tests import AbstractTestCase
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 10369, 7957, 1330, 24060, 198, 198, 6738, 5254, 1330, 27741, 14402, 20448, 628 ]
3
29
from amara.bindery import html from amara.lib import U import urllib import urlparse import time ''' This script extract data from html pages and write the data into a .json file ready to create the mediawiki / wikieducator pages ''' BASE = 'http://academics.smcvt.edu/dmccabe/teaching/Community/' def parse_notes_file(f): ''' Parse file like stream and returns title & content. Title is the first line of the file Content is delimited by 'beginnotes' and 'endnotes' words ''' title = f.readline().strip() content = [] for line in f: if line.startswith('beginnotes'): break for line in f: if line.startswith('endnotes'): break else: line = line.strip() or '\n\n' content.append(line) content = ' '.join(content) content = content.decode('utf-8', 'replace') return {'title': title, 'content': content} def parse_anchor_ecosim(anchor): ''' It returns text and href url from an html anchor for ecosim ''' name = U(anchor).lower().strip() url = urlparse.urljoin(BASE, anchor.href) return name, url def parse_anchor_notes(anchor): ''' It returns the text and href url from an html anchor for ecosim notes. Removes the 'Notes adn data from:' words from teh text. ''' name = U(anchor).replace('Notes and data from:', '').lower().strip() url = urlparse.urljoin(BASE, anchor.href) return name, url def parse_ecosim_file(url): ''' Parse the url from an ecosim data file. It returns the data, species, files ''' f = urllib.urlopen(url) lines = [l for l in f.readlines()] species = len(lines) -1 sites = len(lines[0].split()) -1 return ''.join(lines), species, sites def change_titles(pages): ''' Adds numbres to repeated titles ''' titles = {} for p in pages: title = p.get('title') n = titles.get(title, 0) if n == 0: titles[title] = 1 else: titles[title] = n + 1 title = numbertit(title, n) p['title'] = title if __name__ == '__main__': import json # Main index file f = 'http://academics.smcvt.edu/dmccabe/teaching/Community/NullModelData.html' doc = html.parse(f) #ecosim data links ecosim_files = doc.xml_select(u'//a[contains(@href, "matrices_ecosim")]') # ecosim notes links notes_files = doc.xml_select(u'//a[contains(@href, "matrices_notes")]') # name -> url ecodict = dict([parse_anchor_ecosim(e) for e in ecosim_files]) notesdict = dict([parse_anchor_notes(e) for e in notes_files]) # names sorted ecokeys = ecodict.keys() allnotes = parse_all_notes(notesdict) # json.dump(allnotes, open('allnotes.json', 'w')) # if you want to create a dump pages = [] for x in ecokeys: print 'parsing data', x k = str(x) # element to process Shelve keys must be Str eco_url = ecodict.get(k) data, species, sites = parse_ecosim_file(eco_url) d = allnotes.get(k) if not d: print 'Not found', k continue d['data'] = data #create_page(d, eco_url) d['species'] = species d['sites'] = sites d['source'] = eco_url d['name'] = k pages.append(d) time.sleep(0.2) # no want DOS change_titles(pages) json.dump(pages, open('pages_to_create.json', 'w'))
[ 6738, 716, 3301, 13, 21653, 1924, 1330, 27711, 198, 6738, 716, 3301, 13, 8019, 1330, 471, 198, 11748, 2956, 297, 571, 198, 11748, 19016, 29572, 198, 11748, 640, 198, 198, 7061, 6, 198, 1212, 4226, 7925, 1366, 422, 27711, 5468, 290, 35...
2.323765
1,498
from scraper import * s = Scraper(start=138996, end=140777, max_iter=30, scraper_instance=78) s.scrape_letterboxd()
[ 6738, 19320, 525, 1330, 1635, 220, 198, 82, 796, 1446, 38545, 7, 9688, 28, 20107, 38565, 11, 886, 28, 1415, 2998, 3324, 11, 3509, 62, 2676, 28, 1270, 11, 19320, 525, 62, 39098, 28, 3695, 8, 220, 198, 82, 13, 1416, 13484, 62, 9291,...
2.489362
47
from django.core.exceptions import PermissionDenied from django.test import TestCase from backend.models import UserModel, AwsEnvironmentModel from unittest import mock # mock with mock.patch('backend.models.OperationLogModel.operation_log', lambda executor_index=None, target_method=None, target_arg_index_list=None: lambda func: func): from backend.usecases.control_resource import ControlResourceUseCase # : def test_start_resource_not_belong_to_tenant(self): mock_user = mock.Mock(spec=UserModel) mock_user.is_belong_to_tenant.return_value = False mock_aws = mock.Mock(spec=AwsEnvironmentModel) mock_resource = mock.Mock() # with self.assertRaises(PermissionDenied): ControlResourceUseCase(mock.Mock()).start_resource(mock_user, mock_aws, mock_resource) # mock_user.is_belong_to_tenant.assert_called_once() mock_user.has_aws_env.assert_not_called() mock_resource.start.assert_not_called() # :AWS # # : # :AWS # # : # :AWS # : # : # :AWS # # : # :AWS # # : # :AWS # # # # AWS # # : # :AWS
[ 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 2448, 3411, 21306, 798, 201, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 201, 198, 6738, 30203, 13, 27530, 1330, 11787, 17633, 11, 5851, 82, 31441, 17633, 201, 198, 6738, 55...
2.04252
635
a=raw_input() b=raw_input() i=0 index=0 co=0 if a[0]==b[0]: co+=1 i+=1 while i<len(a): index1=check(b,index+1,a[i]) print a[i],index1 if index1!=-1: index=index1 co+=1 #print index i+=1 print co
[ 64, 28, 1831, 62, 15414, 3419, 198, 65, 28, 1831, 62, 15414, 3419, 198, 72, 28, 15, 198, 9630, 28, 15, 198, 1073, 28, 15, 198, 361, 257, 58, 15, 60, 855, 65, 58, 15, 5974, 198, 220, 220, 220, 763, 47932, 16, 198, 72, 47932, ...
1.632258
155
import os from pathlib import Path from shutil import rmtree # change your parent dir accordingly try: directory = "TempDir" parent_dir = "E:/GitHub/1) Git_Tutorials_Repo_Projects/core-python/Core_Python/" td1, td2 = "TempA", "TempA" path = os.path.join(parent_dir, directory) temp_mul_dirs = os.path.join(path + os.sep + os.sep, td1 + os.sep + os.sep + td2) ''' This methods used to remove single file. all three methods used to delete symlink too''' os.remove(path +os.sep+os.sep+"TempFile.txt") os.unlink(path +os.sep+os.sep+td1+os.sep+os.sep+"TempFilea.txt") ''' we can also use this syntax pathlib.Path(path +os.sep+os.sep+"TempFile.txt").unlink() ''' f_path = Path(temp_mul_dirs +os.sep+os.sep+"TempFileb.txt") f_path.unlink(); ''' both methods for delete empty dir if single dir we can use rmdir if nested the removedirs''' # os.remove(path) # os.removedirs(path+os.sep+os.sep+td1) print("List of dirs before remove : ",os.listdir(path)) ''' For remove non empty directory we have to use shutil.rmtree and pathlib.Path(path),rmdir()''' rmtree(path+os.sep+os.sep+td1) Path(path).rmdir() print("List of dirs after remove : ",os.listdir(parent_dir)) except Exception as e: print(e)
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4423, 346, 1330, 374, 16762, 631, 198, 2, 1487, 534, 2560, 26672, 16062, 198, 28311, 25, 198, 220, 220, 220, 8619, 796, 366, 30782, 35277, 1, 198, 220, 220, 220, 2560, 62, ...
2.379439
535
from __future__ import absolute_import, division, print_function, unicode_literals from echomesh.color import WheelColor from echomesh.util.TestCase import TestCase EXPECTED = [ [ 0., 1., 0.], [ 0.3, 0.7, 0. ], [ 0.6, 0.4, 0. ], [ 0.9, 0.1, 0. ], [ 0. , 0.2, 0.8], [ 0. , 0.5, 0.5], [ 0. , 0.8, 0.2], [ 0.9, 0. , 0.1], [ 0.6, 0. , 0.4], [ 0.3, 0. , 0.7], [ 0., 1., 0.]]
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 304, 354, 2586, 71, 13, 8043, 1330, 15810, 10258, 198, 6738, 304, 354, 2586, 71, 13, 22602, 13, 14402, 20...
1.873874
222
from modules.CommandData import CommandData
[ 6738, 13103, 13, 21575, 6601, 1330, 9455, 6601, 198 ]
4.888889
9
# -*- coding: utf-8 -*- #Used to generate positive building samples from google satellite images #based on OSM building polygons in geojson format # #Note 1: Accuracy of OSM building polygons may vary #Note 2: Requires downloaded google satellite images(tiles) to # have the following file name structure # part_latitude_of_center_longitude_of_center.png # This code was tested with tiles downloaded using # https://github.com/tdeo/maps-hd #Note 3: OSM building data downloaded from # mapzen.com/data/metro-extracts/ #@Author Danaja Maldeniya from osgeo import ogr import os import geoutils import image_utils as imu import cv2 import json import numpy as np map_zoom = 19 tile_size = 600 driver = ogr.GetDriverByName('ESRI Shapefile') shp = driver.Open(r'/home/danaja/Downloads/colombo_sri-lanka.imposm-shapefiles (2)/colombo_sri-lanka_osm_buildings.shp') layer = shp.GetLayer() spatialRef = layer.GetSpatialRef() print spatialRef #Loop through the image files to get their ref location(center) latitude and longitude tile_dir="/home/danaja/installations/maps-hd-master/bk3/images-st" tiles = os.listdir(tile_dir) #positive sample generation #============================================================================== # for tile in tiles: # tile_name = tile.replace(".png","") # print(tile) # center_lat = float(tile_name.split("_")[1]) # center_lon = float(tile_name.split("_")[2]) # extent = geoutils.get_tile_extent(center_lat,center_lon,map_zoom,tile_size) # layer.SetSpatialFilterRect(extent[2][1],extent[2][0],extent[1][1],extent[1][0]) # print("feature count: "+str(layer.GetFeatureCount())) # print(tile_dir+"/"+tile) # image = cv2.imread(tile_dir+"/"+tile) # b_channel, g_channel, r_channel = cv2.split(image) # alpha_channel = np.array(np.ones((tile_size,tile_size )) * 255,dtype=np.uint8) #creating a dummy alpha channel image. # image= cv2.merge((b_channel, g_channel, r_channel, alpha_channel)) # i = 0 # for feature in layer: # coordinates = [] # geom = feature.GetGeometryRef() # geom = json.loads(geom.ExportToJson()) # # for coordinate in geom['coordinates'][0]: # pixel = geoutils.get_pixel_location_in_tile_for_lat_lon( \ # coordinate[1],coordinate[0],center_lat,center_lon,map_zoom,tile_size) # if len(coordinates) == 0: # minx = pixel[0] # miny = pixel[1] # maxx = pixel[0] # maxy = pixel[1] # minx = min(minx,pixel[0]) # maxx = max(maxx,pixel[0]) # miny = min(miny,pixel[1]) # maxy = max(maxy,pixel[1]) # coordinates.append(tuple(reversed(pixel))) # # mask = np.zeros(image.shape, dtype=np.uint8) # roi_corners = np.array([coordinates], dtype=np.int32) # channel_count = image.shape[2] # i.e. 3 or 4 depending on your image # ignore_mask_color = (255,)*channel_count # cv2.fillPoly(mask, roi_corners, ignore_mask_color) # masked_image = cv2.bitwise_and(image, mask) # masked_image = masked_image[minx:maxx,miny:maxy] # cv2.imwrite("positive/"+tile_name+"_"+str(i)+".png",masked_image) # i=i+1 # layer.SetSpatialFilter(None) # #============================================================================== #negative sample generation min_size = 80 max_size = 100 for tile in tiles: tile_name = tile.replace(".png","") print(tile) center_lat = float(tile_name.split("_")[1]) center_lon = float(tile_name.split("_")[2]) extent = geoutils.get_tile_extent(center_lat,center_lon,map_zoom,tile_size) layer.SetSpatialFilterRect(extent[2][1],extent[2][0],extent[1][1],extent[1][0]) if layer.GetFeatureCount() > 0: layer.SetSpatialFilter(None) attempt = 0 success = 0 while (attempt <100 and success <20): box =imu.generate_random_box(tile_size,min_size,max_size) nw_corner = geoutils.get_lat_lon_of_point_in_tile(box[0],box[1],center_lat,center_lon,map_zoom,tile_size) se_corner = geoutils.get_lat_lon_of_point_in_tile(box[2],box[3],center_lat,center_lon,map_zoom,tile_size) layer.SetSpatialFilterRect(nw_corner[1],se_corner[0],se_corner[1],nw_corner[0]) fCount = layer.GetFeatureCount() if fCount >0: continue else: image = cv2.imread(tile_dir+"/"+tile) bld = image[int(box[1]):int(box[3]), \ int(box[0]):int(box[2])] cv2.imwrite("negative/"+tile_name+"_"+str(success)+".png",bld) success = success+1 layer.SetSpatialFilter(None) attempt = attempt +1
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 38052, 284, 7716, 3967, 2615, 8405, 422, 23645, 11210, 4263, 198, 2, 3106, 319, 7294, 44, 2615, 25052, 684, 287, 4903, 13210, 1559, 5794, 198, 2, 198, 2, 6425, 352,...
2.176235
2,247
from ctypes import cdll,c_int,c_double,POINTER _lib = cdll.LoadLibrary('./demo/bin/libmultifuns.dll') # double dprod(double *x, int n) # int factorial(int n) # int isum(int array[], int size);
[ 198, 6738, 269, 19199, 1330, 269, 12736, 11, 66, 62, 600, 11, 66, 62, 23352, 11, 16402, 41358, 198, 198, 62, 8019, 796, 269, 12736, 13, 8912, 23377, 7, 4458, 14, 9536, 78, 14, 8800, 14, 8019, 16680, 361, 13271, 13, 12736, 11537, 1...
2.385542
83
from nivo_api.core.db.connection import metadata, create_database_connections from sqlalchemy.engine import Engine from sqlalchemy.exc import ProgrammingError
[ 6738, 299, 23593, 62, 15042, 13, 7295, 13, 9945, 13, 38659, 1330, 20150, 11, 2251, 62, 48806, 62, 8443, 507, 198, 6738, 44161, 282, 26599, 13, 18392, 1330, 7117, 198, 6738, 44161, 282, 26599, 13, 41194, 1330, 30297, 12331, 628, 198 ]
3.926829
41
""" @Author:lichunhui @Time: @Description: """ from scrapy import cmdline # cmdline.execute("scrapy crawl baidu_spider".split()) # cmdline.execute("scrapy crawl baike_spider".split()) # cmdline.execute("scrapy crawl wiki_zh_spider".split()) # cmdline.execute("scrapy crawl wiki_en_spider".split()) cmdline.execute("scrapy crawlall".split())
[ 37811, 198, 31, 13838, 25, 33467, 403, 71, 9019, 198, 31, 7575, 25, 220, 220, 220, 198, 31, 11828, 25, 220, 198, 37811, 198, 6738, 15881, 88, 1330, 23991, 1370, 198, 198, 2, 23991, 1370, 13, 41049, 7203, 1416, 2416, 88, 27318, 275, ...
2.776
125
import PySimpleGUI as sg layout = [ [sg.Text("Wie heit Du?")], [sg.Input(key = "-INPUT-")], [sg.Text(size = (40, 1), key = "-OUTPUT-")], [sg.Button("Okay"), sg.Button("Quit")] ] window = sg.Window("Hallo PySimpleGUI", layout) keep_going = True while keep_going: event, values = window.read() if event == sg.WINDOW_CLOSED or event == "Quit": keep_going = False window["-OUTPUT-"].update("Hallchen " + values["-INPUT-"] + "!") window.close()
[ 11748, 9485, 26437, 40156, 355, 264, 70, 198, 198, 39786, 796, 685, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 685, 45213, 13, 8206, 7203, 54, 494, 339, 270, 10343, 1701, 8, 4357, 198, 220, 220, 220, 220, 220, 220, 220, 220...
2.146444
239
import numpy as np import pathlib from torch.utils.data import Dataset, DataLoader import dgl import torch from dgl.data.utils import load_graphs import json from datasets import util from tqdm import tqdm
[ 11748, 299, 32152, 355, 45941, 198, 11748, 3108, 8019, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 11, 6060, 17401, 198, 11748, 288, 4743, 198, 11748, 28034, 198, 6738, 288, 4743, 13, 7890, 13, 26791, 1330, 3440, 62, ...
3.393443
61
# Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # from mmdet.models.builder import HEADS, build_loss from mmdet.models.losses import smooth_l1_loss from mmdet.models.dense_heads.ssd_head import SSDHead
[ 2, 15069, 357, 34, 8, 33160, 8180, 10501, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 198, 198, 6738, 8085, 15255, 13, 27530, 13, 38272, 1330, 39837, 50, 11, 1382, 62, 22462, 198, 6738, 8085, ...
3.025974
77
""" Copyright 2020 daduz11 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. """ """ Firstly this script is used for the conversion of the freezed inference graph (pb format) into a CoreML model. Moreover the same script takes the CoreML model at 32bit precision to carries out the quantization from 16 to 1 bit. """ import argparse import sys import tfcoreml import coremltools from coremltools.models.neural_network import quantization_utils if __name__ == '__main__': main(parse_arguments(sys.argv[1:]))
[ 37811, 198, 220, 220, 15069, 12131, 9955, 10277, 1157, 628, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 220, 220, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789...
3.555172
290
def find_from(string, subs, start = None, end = None): """ Returns a tuple of the lowest index where a substring in the iterable "subs" was found, and the substring. If multiple substrings are found, it will return the first one. If nothing is found, it will return (-1, None) """ string = string[start:end] last_index = len(string) substring = None for s in subs: i = string.find(s) if i != -1 and i < last_index: last_index = i substring = s if last_index == len(string): return (-1, None) return (last_index, substring)
[ 198, 4299, 1064, 62, 6738, 7, 8841, 11, 6352, 11, 923, 796, 6045, 11, 886, 796, 6045, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 16409, 257, 46545, 286, 262, 9016, 6376, 810, 257, 3293, 1806, 287, 262, 11629, 540, 366, 7...
2.462745
255
# todos # - [ ] all dates and date deltas are in time, not integers from loguru import logger from typing import Dict import sys import datetime from datetime import timedelta import numpy as np from ta_scanner.data.data import load_and_cache, db_data_fetch_between, aggregate_bars from ta_scanner.data.ib import IbDataFetcher from ta_scanner.experiments.simple_experiment import SimpleExperiment from ta_scanner.indicators import ( IndicatorSmaCrossover, IndicatorEmaCrossover, IndicatorParams, ) from ta_scanner.signals import Signal from ta_scanner.filters import FilterCumsum, FilterOptions, FilterNames from ta_scanner.reports import BasicReport from ta_scanner.models import gen_engine ib_data_fetcher = IbDataFetcher() instrument_symbol = "/NQ" rth = False interval = 1 field_name = "ema_cross" slow_sma = 25 fast_sma_min = 5 fast_sma_max = 20 filter_inverse = True win_pts = 75 loss_pts = 30 trade_interval = 12 test_total_pnl = 0.0 test_total_count = 0 all_test_results = [] engine = gen_engine() logger.remove() logger.add(sys.stderr, level="INFO") # fetch_data() for i in range(0, 33): initial = datetime.date(2020, 7, 10) + timedelta(days=i) test_start, test_end = initial, initial if initial.weekday() in [5, 6]: continue # fetch training data train_sd = initial - timedelta(days=5) train_ed = initial - timedelta(days=1) df_train = query_data(engine, instrument_symbol, train_sd, train_ed, interval) # for training data, let's find results for a range of SMA results = run_cross_range( df_train, slow_sma=slow_sma, fast_sma_min=fast_sma_min, fast_sma_max=fast_sma_max, ) fast_sma_pnl = [] for resultindex in range(2, len(results) - 3): fast_sma = results[resultindex][0] pnl = results[resultindex][1] result_set = results[resultindex - 2 : resultindex + 3] total_pnl = sum([x[1] for x in result_set]) fast_sma_pnl.append([fast_sma, total_pnl, pnl]) arr = np.array(fast_sma_pnl, dtype=float) max_tuple = np.unravel_index(np.argmax(arr, axis=None), arr.shape) optimal_fast_sma = int(arr[(max_tuple[0], 0)]) optimal_fast_sma_pnl = [x[2] for x in fast_sma_pnl if x[0] == optimal_fast_sma][0] # logger.info(f"Selected fast_sma={optimal_fast_sma}. PnL={optimal_fast_sma_pnl}") test_sd = initial test_ed = initial + timedelta(days=1) df_test = query_data(engine, instrument_symbol, test_sd, test_ed, interval) test_results = run_cross(df_test, optimal_fast_sma, slow_sma) all_test_results.append([initial] + list(test_results)) logger.info( f"Test Results. pnl={test_results[0]}, count={test_results[1]}, avg={test_results[2]}, median={test_results[3]}" ) test_total_pnl += test_results[0] test_total_count += test_results[1] logger.info( f"--- CumulativePnL={test_total_pnl}. Trades Count={test_total_count}. After={initial}" ) import csv with open("simple_results.csv", "w") as csvfile: spamwriter = csv.writer(csvfile) for row in all_test_results: spamwriter.writerow(row)
[ 2, 284, 37427, 198, 2, 532, 685, 2361, 477, 9667, 290, 3128, 1619, 83, 292, 389, 287, 640, 11, 407, 37014, 198, 198, 6738, 2604, 14717, 1330, 49706, 198, 6738, 19720, 1330, 360, 713, 198, 11748, 25064, 198, 11748, 4818, 8079, 198, 6...
2.461358
1,281
import tkinter as tk import os print(tk) print(dir(tk)) print(tk.TkVersion) print(os.getcwd()) '''To initialize tkinter, we have to create a Tk root widget, which is a window with a title bar and other decoration provided by the window manager. The root widget has to be created before any other widgets and there can only be one root widget.''' root = tk.Tk() '''The next line of code contains the Label widget. The first parameter of the Label call is the name of the parent window, in our case "root". So our Label widget is a child of the root widget. The keyword parameter "text" specifies the text to be shown: ''' w = tk.Label(root,text='Hello world') '''The pack method tells Tk to fit the size of the window to the given text. ''' w.pack() '''The window won't appear until we enter the Tkinter event loop''' root.mainloop()
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 11748, 28686, 198, 4798, 7, 30488, 8, 198, 4798, 7, 15908, 7, 30488, 4008, 198, 4798, 7, 30488, 13, 51, 74, 14815, 8, 198, 4798, 7, 418, 13, 1136, 66, 16993, 28955, 198, 198, 7061, 6, 251...
3.391129
248
from django.shortcuts import render,redirect,get_object_or_404 from remiljscrumy.models import ScrumyGoals,GoalStatus,ScrumyHistory,User from django.http import HttpResponse,Http404,HttpResponseRedirect from .forms import SignupForm,CreateGoalForm,MoveGoalForm,DevMoveGoalForm,AdminChangeGoalForm,QAChangeGoalForm,QAChangegoal from django.contrib.auth import authenticate,login from django.contrib.auth.models import User,Group from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.urls import reverse #from django.core.exceptions import ObjectDoesNotExist # Create your views here. # def move_goal(request, goal_id): # #response = ScrumyGoals.objects.get(goal_id=goal_id) # # try: # #goal = ScrumyGoals.objects.get(goal_id=goal_id) # # except ScrumyGoals.DoesNotExist: # # raise Http404 ('A record with that goal id does not exist') # instance = get_object_or_404(ScrumyGoals,goal_id=goal_id) # form = MoveGoalForm(request.POST or None, instance=instance) # if form. is_valid(): # instance = form.save(commit=False) # instance.save() # return redirect('home') # context={ # 'goal_id': instance.goal_id, # 'user': instance.user, # 'goal_status': instance.goal_status, # 'form':form, # } # return render(request, 'remiljscrumy/exception.html', context) #move_goal = form.save(commit=False) # move_goal = # form.save() # # goal_name = form.cleaned_data.get('goal_name') # # ScrumyGoals.objects.get(goal_name) # return redirect('home') # def form_valid(self, form): # form.instance.goal_status = self.request.user # return super(addgoalForm, self).form_valid(form) # } # return render(request, 'remiljscrumy/exception.html', context=gdict) #return HttpResponse(response) # return HttpResponse('%s is the response at the record of goal_id %s' % (response, goal_id))''' from random import randint def home(request): '''# all=','.join([eachgoal.goal_name for eachgoal in ScrumyGoals.objects.all()]) # home = ScrumyGoals.objects.filter(goal_name='keep learning django') # return HttpResponse(all) #homedict = {'goal_name':ScrumyGoals.objects.get(pk=3).goal_name,'goal_id':ScrumyGoals.objects.get(pk=3).goal_id, 'user': ScrumyGoals.objects.get(pk=3).user,} user = User.objects.get(email="louisoma@linuxjobber.com") name = user.scrumygoal.all() homedict={'goal_name':ScrumyGoals.objects.get(pk=1).goal_name,'goal_id':ScrumyGoals.objects.get(pk=1).goal_id,'user':ScrumyGoals.objects.get(pk=1).user, 'goal_name1':ScrumyGoals.objects.get(pk=2).goal_name,'goal_id1':ScrumyGoals.objects.get(pk=2).goal_id,'user':ScrumyGoals.objects.get(pk=2).user, 'goal_name2':ScrumyGoals.objects.get(pk=3).goal_name,'goal_id2':ScrumyGoals.objects.get(pk=3).goal_id,'user2':ScrumyGoals.objects.get(pk=3).user}''' # form = CreateGoalForm # if request.method == 'POST': # form = CreateGoalForm(request.POST) # if form .is_valid(): # add_goal = form.save(commit=True) # add_goal = form.save() # # #form.save() # return redirect('home') current = request.user week = GoalStatus.objects.get(pk=1) day = GoalStatus.objects.get(pk=2) verify = GoalStatus.objects.get(pk=3) done = GoalStatus.objects.get(pk=4) user = User.objects.all() weeklygoal = ScrumyGoals.objects.filter(goal_status=week) dailygoal = ScrumyGoals.objects.filter(goal_status=day) verifygoal = ScrumyGoals.objects.filter(goal_status=verify) donegoal = ScrumyGoals.objects.filter(goal_status=done) groups = current.groups.all() dev = Group.objects.get(name='Developer') owner = Group.objects.get(name='Owner') admin = Group.objects.get(name='Admin') qa = Group.objects.get(name='Quality Assurance') if not request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) if current.is_authenticated: if dev in groups or qa in groups or owner in groups: # if request.method == 'GET': # return render(request, 'remiljscrumy/home.html', context) form = CreateGoalForm() context = {'user': user, 'weeklygoal': weeklygoal, 'dailygoal': dailygoal, 'verifygoal': verifygoal, 'donegoal': donegoal, 'form': form, 'current': current, 'groups': groups,'dev': dev,'owner':owner,'admin':admin,'qa':qa} if request.method == 'POST': form = CreateGoalForm(request.POST) if form.is_valid(): post = form.save(commit=False) status_name = GoalStatus(id=1) post.goal_status = status_name post.user = current post = form.save() elif admin in groups: context = {'user': user, 'weeklygoal': weeklygoal, 'dailygoal': dailygoal, 'verifygoal': verifygoal, 'donegoal': donegoal,'current': current, 'groups': groups,'dev': dev,'owner':owner,'admin':admin,'qa':qa} return render(request, 'remiljscrumy/home.html', context) # else: # form = WeekOnlyAddGoalForm() # return HttpResponseRedirect(reverse('ayooluwaoyewoscrumy:homepage')) # if group == 'Admin': # context ={ # 'user':User.objects.all(), # 'weeklygoal':ScrumyGoals.objects.filter(goal_status=week), # 'dailygoal':ScrumyGoals.objects.filter(goal_status=day), # 'verifiedgoals':ScrumyGoals.objects.filter(goal_status=verify), # 'donegoal':ScrumyGoals.objects.filter(goal_status=done), # 'current':request.user, # 'groups':request.user.groups.all(), # 'admin': Group.objects.get(name="Admin"), # 'owner': Group.objects.get(name='Owner'), # 'dev': Group.objects.get(name='Developer'), # 'qa': Group.objects.get(name='Quality Assurance'),} # return render(request,'remiljscrumy/home.html',context=homedict) # if request.method == 'GET': # return render(request, 'remiljscrumy/home.html', context) #
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 445, 1060, 11, 1136, 62, 15252, 62, 273, 62, 26429, 201, 198, 6738, 816, 346, 73, 1416, 6582, 88, 13, 27530, 1330, 1446, 6582, 88, 5247, 874, 11, 49045, 19580, 11, 3351, 6582, 88...
2.21431
2,949
''' Cilia classes are used to compute fixed points faster. - Assume symmetry like in an m-twist (make a plot to see it) - Assume that symmetries is not broken in time -> define classes of symmetry and interactions between them. Done: - Create a ring of cilia. - Define symmetry classes - Use classes to solve ODE - Map back to cilia ''' import numpy as np import carpet import carpet.lattice.ring1d as lattice import carpet.physics.friction_pairwise as physics import carpet.classes as cc import carpet.visualize as vis import matplotlib.pyplot as plt ## Parameters # Physics set_name = 'machemer_1' # hydrodynamic friction coefficients data set period = 31.25 # [ms] period freq = 2 * np.pi / period # [rad/ms] angular frequency order_g11 = (4, 0) # order of Fourier expansion of friction coefficients order_g12 = (4, 4) # Geometry N = 6 # number of cilia a = 18 # [um] lattice spacing e1 = (1, 0) # direction of the chain ## Initialize # Geometry L1 = lattice.get_domain_size(N, a) coords, lattice_ids = lattice.get_nodes_and_ids(N, a, e1) # get cilia (nodes) coordinates NN, TT = lattice.get_neighbours_list(N, a, e1) # get list of neighbours and relative positions e1, e2 = lattice.get_basis(e1) get_k = lattice.define_get_k(N, a, e1) get_mtwist = lattice.define_get_mtwist(coords, N, a, e1) # Physics gmat_glob, q_glob = physics.define_gmat_glob_and_q_glob(set_name, e1, e2, a, NN, TT, order_g11, order_g12, period) right_side_of_ODE = physics.define_right_side_of_ODE(gmat_glob, q_glob) solve_cycle = carpet.define_solve_cycle(right_side_of_ODE, 2 * period, phi_global_func=carpet.get_mean_phase) # k-twist k1 = 2 phi0 = get_mtwist(k1) vis.plot_nodes(coords, phi=phi0) # visualize! plt.ylim([-L1 / 10, L1 / 10]) plt.show() ## Solve regularly tol = 1e-4 sol = solve_cycle(phi0, tol) phi1 = sol.y.T[-1] - 2 * np.pi # after one cycle ## Now solve with classes # Map to classes ix_to_class, class_to_ix = cc.get_classes(phi0) nclass = len(class_to_ix) # Get classes representatives # Get one oscillator from each of cilia classes unique_cilia_ids = cc.get_unique_cilia_ix( class_to_ix) # equivalent to sp.array([class_to_ix[iclass][0] for iclass in range(nclass)], dtype=sp.int64) # Get connections N1_class, T1_class = cc.get_neighbours_list_class(unique_cilia_ids, ix_to_class, NN, TT) # Define physics gmat_glob_class, q_glob_class = physics.define_gmat_glob_and_q_glob(set_name, e1, e2, a, N1_class, T1_class, order_g11, order_g12, period) right_side_of_ODE_class = physics.define_right_side_of_ODE(gmat_glob_class, q_glob_class) solve_cycle_class = carpet.define_solve_cycle(right_side_of_ODE_class, 2 * period, carpet.get_mean_phase) # Solve ODE phi0_class = phi0[unique_cilia_ids] sol = solve_cycle_class(phi0_class, tol) phi1_class = sol.y.T[-1] - 2 * np.pi # Map from classes back to cilia phi1_mapped_from_class = phi1_class[ix_to_class] ## Print how much phase changed print(phi1_mapped_from_class - phi1) # difference between two - should be on the order of tolerance or smaller
[ 7061, 6, 198, 34, 17517, 6097, 389, 973, 284, 24061, 5969, 2173, 5443, 13, 198, 198, 12, 2195, 2454, 40686, 588, 287, 281, 285, 12, 4246, 396, 357, 15883, 257, 7110, 284, 766, 340, 8, 198, 12, 2195, 2454, 326, 23606, 316, 1678, 31...
2.486312
1,242
""" SCL <scott@rerobots.net> 2018 """ import json import os import tempfile import time
[ 37811, 198, 198, 50, 5097, 1279, 1416, 1252, 31, 260, 22609, 1747, 13, 3262, 29, 198, 7908, 198, 37811, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 640, 628 ]
2.727273
33
import numpy as np import matplotlib.pyplot as plt import scipy.stats FIG, (LEFT_AX, MIDDLE_AX, RIGHT_AX) = plt.subplots(1, 3, figsize=(10, 3)) X_RANGE = (-2, 2) Y_RANGE = (-2, 2) X_DATA = np.array([]) Y_DATA = np.array([]) BELIEF = SequentialBayes(np.array([0, 0]), np.diag([1, 1])) set_ax_range() plot_belief(RIGHT_AX) plot_belief_sample() FIG.canvas.mpl_connect('button_press_event', on_click) plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 629, 541, 88, 13, 34242, 628, 628, 628, 628, 198, 198, 16254, 11, 357, 2538, 9792, 62, 25922, 11, 25269, 35, 2538, 62, 25922, 1...
2.158974
195
import numpy as np import logging import matplotlib.pyplot as plt from sklearn.cluster import KMeans from ..results import Results logger = logging.getLogger(__name__)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 18931, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1341, 35720, 13, 565, 5819, 1330, 509, 5308, 504, 198, 198, 6738, 11485, 43420, 1330, 15691, 198, 198, 6404, 1362...
3.185185
54
import sys import os import configparser import argparse import glob if __name__ == "__main__": main()
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 4566, 48610, 198, 11748, 1822, 29572, 198, 11748, 15095, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
3.055556
36
# All rights reserved by forest fairy. # You cannot modify or share anything without sacrifice. # If you don't agree, keep calm and don't look at code bellow! __author__ = "VirtualV <https://github.com/virtualvfix>" __date__ = "$Apr 13, 2014 8:47:25 PM$" import re from config import CONFIG from tests.exceptions import ResultsNotFoundError from tests.benchmarks.tools.base import OnlineBenchmark
[ 2, 1439, 2489, 10395, 416, 8222, 25607, 13, 198, 2, 921, 2314, 13096, 393, 2648, 1997, 1231, 11728, 13, 198, 2, 1002, 345, 836, 470, 4236, 11, 1394, 9480, 290, 836, 470, 804, 379, 2438, 8966, 322, 0, 198, 198, 834, 9800, 834, 796,...
3.603604
111
import sys import unittest import os import tempfile import shutil import contextlib import json import subprocess import PIL import templatelayer.testing_common _APP_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) _SCRIPT_PATH = os.path.join(_APP_PATH, 'templatelayer', 'resources', 'scripts') _TOOL_FILEPATH = os.path.join(_SCRIPT_PATH, 'template_image_apply_overlays') sys.path.insert(0, _APP_PATH)
[ 11748, 25064, 198, 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 4423, 346, 198, 11748, 4732, 8019, 198, 11748, 33918, 198, 11748, 850, 14681, 198, 198, 11748, 350, 4146, 198, 198, 11748, 11055, 29289, 13, ...
2.806452
155
import argparse import torch import torch.nn as nn from gpt2.modeling import Transformer from gpt2.data import Dataset, Vocab, TokenizedCorpus from gpt2.evaluation import EvaluationSpec, EvaluateConfig, Evaluator from typing import Dict
[ 11748, 1822, 29572, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 308, 457, 17, 13, 4666, 10809, 1330, 3602, 16354, 198, 6738, 308, 457, 17, 13, 7890, 1330, 16092, 292, 316, 11, 47208, 397, 11, 29130, 1143,...
3.380282
71
from typing import Dict from src.alerter.alert_data.alert_data import AlertData
[ 6738, 19720, 1330, 360, 713, 198, 198, 6738, 12351, 13, 36213, 353, 13, 44598, 62, 7890, 13, 44598, 62, 7890, 1330, 23276, 6601, 628 ]
3.416667
24
from processutils.textfilter import Unpack from utils.simplelog import Logger import argparse parser = argparse.ArgumentParser(description="my_unpack") parser.add_argument('-f', "--file_prefix", required=True) parser.add_argument('-sep', "--separator", required=True) # args = parser.parse_args([ # "-f", "../test/medicine.sample.data/data.test", # "-sep", ' ||| ' # ]) args = parser.parse_args() args.output_src = args.file_prefix + ".src" args.output_tgt = args.file_prefix + ".tgt" log = Logger("my_filter", "my_filter.log").log() if __name__ == '__main__': with open(args.file_prefix, "r", encoding="utf8") as f: data = f.readlines() src_lines, tgt_lines = main(data) with open(args.output_src, "w", encoding="utf8") as f: f.writelines(src_lines) with open(args.output_tgt, "w", encoding="utf8") as f: f.writelines(tgt_lines)
[ 6738, 1429, 26791, 13, 5239, 24455, 1330, 791, 8002, 198, 6738, 3384, 4487, 13, 36439, 6404, 1330, 5972, 1362, 198, 198, 11748, 1822, 29572, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 2625, 1820, 62, 403, 8002,...
2.524217
351
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import os import json import urllib.parse import boto3 import decimal from decimal import Decimal from datetime import datetime from chalice import Chalice from chalice import IAMAuthorizer from chalice import ChaliceViewError, BadRequestError, NotFoundError from botocore.config import Config from botocore.client import ClientError from boto3.dynamodb.conditions import Key, Attr, In from jsonschema import validate, ValidationError from chalicelib import replace_decimals s3_client = boto3.client("s3") ddb_resource = boto3.resource("dynamodb") PLUGIN_RESULT_TABLE_NAME = os.environ['PLUGIN_RESULT_TABLE_NAME'] def get_event_segment_metadata(name, program, classifier, tracknumber): """ Gets the Segment Metadata based on the segments found during Segmentation/Optimization process. """ name = urllib.parse.unquote(name) program = urllib.parse.unquote(program) classifier = urllib.parse.unquote(classifier) tracknumber = urllib.parse.unquote(tracknumber) try: # Get Event Segment Details # From the PluginResult Table, get the Clips Info plugin_table = ddb_resource.Table(PLUGIN_RESULT_TABLE_NAME) response = plugin_table.query( KeyConditionExpression=Key("PK").eq(f"{program}#{name}#{classifier}"), ScanIndexForward=False ) plugin_responses = response['Items'] while "LastEvaluatedKey" in response: response = plugin_table.query( ExclusiveStartKey=response["LastEvaluatedKey"], KeyConditionExpression=Key("PK").eq(f"{program}#{name}#{classifier}"), ScanIndexForward=False ) plugin_responses.extend(response["Items"]) # if "Items" not in plugin_response or len(plugin_response["Items"]) == 0: # print(f"No Plugin Responses found for event '{name}' in Program '{program}' for Classifier {classifier}") # raise NotFoundError(f"No Plugin Responses found for event '{name}' in Program '{program}' for Classifier {classifier}") clip_info = [] for res in plugin_responses: optoLength = 0 if 'OptoEnd' in res and 'OptoStart' in res: # By default OptoEnd and OptoStart are maps and have no Keys. Only when they do, we check for TrackNumber's if len(res['OptoEnd'].keys()) > 0 and len(res['OptoStart'].keys()) > 0: try: optoLength = res['OptoEnd'][tracknumber] - res['OptoStart'][tracknumber] except Exception as e: pass # Error if the TrackNumber does not exist. Simply Ignore since its a problem with Clip Gen # Calculate Opto Clip Duration for each Audio Track optoDurationsPerTrack = [] if 'OptoEnd' in res and 'OptoStart' in res: for k in res['OptoStart'].keys(): try: optoDur = {} optoDur[k] = res['OptoEnd'][k] - res['OptoStart'][k] optoDurationsPerTrack.append(optoDur) except Exception as e: pass # Error if the TrackNumber does not exist. Simply Ignore since its a problem with Clip Gen optoClipLocation = '' if 'OptimizedClipLocation' in res: # This is not ideal. We need to check of there exists a OptimizedClipLocation with the requested TrackNumber. # If not, likely a problem with Clip Gen. Instead of failing, we send an empty value for optoClipLocation back. for trackNo in res['OptimizedClipLocation'].keys(): if str(trackNo) == str(tracknumber): optoClipLocation = create_signed_url(res['OptimizedClipLocation'][tracknumber]) break origClipLocation = '' if 'OriginalClipLocation' in res: for trackNo in res['OriginalClipLocation'].keys(): if str(trackNo) == str(tracknumber): origClipLocation = create_signed_url(res['OriginalClipLocation'][tracknumber]) break label = '' if 'Label' in res: label = res['Label'] if str(label) == "": label = '<no label plugin configured>' clip_info.append({ 'OriginalClipLocation': origClipLocation, 'OriginalThumbnailLocation': create_signed_url( res['OriginalThumbnailLocation']) if 'OriginalThumbnailLocation' in res else '', 'OptimizedClipLocation': optoClipLocation, 'OptimizedThumbnailLocation': create_signed_url( res['OptimizedThumbnailLocation']) if 'OptimizedThumbnailLocation' in res else '', 'StartTime': res['Start'], 'Label': label, 'FeatureCount': 'TBD', 'OrigLength': 0 if 'Start' not in res else res['End'] - res['Start'], 'OptoLength': optoLength, 'OptimizedDurationPerTrack': optoDurationsPerTrack, 'OptoStartCode': '' if 'OptoStartCode' not in res else res['OptoStartCode'], 'OptoEndCode': '' if 'OptoEndCode' not in res else res['OptoEndCode'] }) final_response = {} final_response['Segments'] = clip_info except NotFoundError as e: print(e) print(f"Got chalice NotFoundError: {str(e)}") raise except Exception as e: print(e) print(f"Unable to get the Event '{name}' in Program '{program}': {str(e)}") raise ChaliceViewError(f"Unable to get the Event '{name}' in Program '{program}': {str(e)}") else: return replace_decimals(final_response)
[ 2, 15069, 33448, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 2956, 297, ...
2.247651
2,661
from xml.etree import ElementTree as Etree from model import * from astro_unit import * from io import StringIO import logging # Maps field name to tuple of (type, unit) # Only the following columns will be understood PLANET_FIELDS = { "semimajoraxis": FieldMeta("number", 'AU'), "eccentricity": FieldMeta("number"), # unit not needed "periastron": FieldMeta("number", 'deg'), "longitude": FieldMeta("number", 'deg'), "ascendingnode": FieldMeta("number", 'deg'), "inclination": FieldMeta("number", 'deg'), "impactparameter": FieldMeta("number"), # unit not needed "meananomaly": FieldMeta("number", 'deg'), "period": FieldMeta("number", 'days'), "transittime": FieldMeta("number", 'BJD'), "periastrontime": FieldMeta("number", 'BJD'), "maximumrvtime": FieldMeta("number", 'BJD'), "separation": FieldMeta("number", 'arcsec'), # unit on xml element "mass": FieldMeta("number", 'M_j'), "radius": FieldMeta("number", 'R_j'), "temperature": FieldMeta("number", 'K'), "age": FieldMeta("number", 'Gyr'), # "discoverymethod": FieldMeta("discoverymethodtype"), # "istransiting": FieldMeta("boolean"), # "description": "xs:string", "discoveryyear": FieldMeta("number", None), # "lastupdate": FieldMeta("lastupdatedef", None), # "image", # "imagedescription", "spinorbitalignment": FieldMeta("number", 'deg'), "positionangle": FieldMeta("number", 'deg'), # "metallicity": FieldMeta("number"), # unit not needed # "spectraltype": FieldMeta("spectraltypedef"), # "magB": FieldMeta("number", None), "magH": FieldMeta("number", None), "magI": FieldMeta("number", None), "magJ": FieldMeta("number", None), "magK": FieldMeta("number", None), # "magR": FieldMeta("number", None), # "magU": FieldMeta("number", None), "magV": FieldMeta("number", None) } # def validate(self, file: str) -> None: # Validates an xml using schema defined by OEC. # Raises an exception if file does not follow the schema. # :param file: File name. # """ # return # skip for now, because OEC itself isn't following the schema # # tree = etree.parse(file) # # self._schema.assertValid(tree) def update_str(self, xml_string: str, update: PlanetarySysUpdate) \ -> Tuple[str, bool]: """ Apply a system update to an xml string. Also performs a check afterwards to determine if the action succeeded. :param xml_string: containing the xml representation of a system :param update: Update to be applied to the system :return: A tuple (content, succeeded) where: - content is the file content modified - succeeded indicates whether the update was successful. """ tree = Etree.parse(StringIO(xml_string)) ok = Adapter._write_system_update(tree, update) serialized = Etree.tostring(tree.getroot(), 'unicode', 'xml') return serialized, ok def update_file(self, filename: str, update: PlanetarySysUpdate) -> bool: """ Apply a system update to an xml file. :param filename: The system xml file :param update: Update to be applied to the system :return: Whether the update was successful """ tree = Etree.parse(filename) succeeded = Adapter._write_system_update(tree, update) tree.write(filename) return succeeded
[ 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 355, 17906, 631, 198, 6738, 2746, 1330, 1635, 198, 6738, 6468, 305, 62, 20850, 1330, 1635, 198, 6738, 33245, 1330, 10903, 9399, 198, 11748, 18931, 628, 198, 198, 2, 20347, 2214, 1438, 284, ...
2.722525
1,283
"""Validate AnVIL workspace(s).""" import os from google.cloud.storage import Client from google.cloud.storage.blob import Blob from collections import defaultdict import ipywidgets as widgets from ipywidgets import interact from IPython.display import display import pandas as pd import firecloud.api as FAPI from types import SimpleNamespace import numpy as np
[ 37811, 7762, 20540, 1052, 53, 4146, 44573, 7, 82, 21387, 15931, 198, 198, 11748, 28686, 198, 198, 6738, 23645, 13, 17721, 13, 35350, 1330, 20985, 198, 6738, 23645, 13, 17721, 13, 35350, 13, 2436, 672, 1330, 1086, 672, 198, 6738, 17268, ...
3.707071
99
''' Intermediate C#1, stigid PROBLEM: Given a number less than 10^50 and length n, find the sum of all the n -digit numbers (starting on the left) that are formed such that, after the first n -digit number is formed all others are formed by deleting the leading digit and taking the next n -digits. ''' from unittest import TestCase # return a list t = TestCase() reslt = c1_inter_1([ ['1325678905', 2], ['54981230845791', 5], ['4837261529387456', 3], ['385018427388713440', 4], ['623387770165388734652209', 11]]) t.assertEqual(455, reslt[0]) t.assertEqual(489210, reslt[1]) t.assertEqual(7668, reslt[2]) t.assertEqual(75610, reslt[3]) t.assertEqual(736111971668, reslt[4]) reslt = c1_inter_1([[ '834127903876541', 3 ], [ '2424424442442420', 1 ], [ '12345678909876543210123456789', 12 ], [ '349216', 6 ], [ '11235813245590081487340005429', 2 ]]) t = TestCase() t.assertEqual(6947, reslt[0]) t.assertEqual(48, reslt[1]) t.assertEqual(9886419753191, reslt[2]) t.assertEqual(349216, reslt[3]) t.assertEqual(11 + 12 + 23 + 35 + 58 + 81 + 13 + 32 + 24 + 45 + 55 + 59 + 90 + 00 + 8 + 81 + 14 + 48 + 87 + 73 + 34 + 40 + 00 + 00 + 5 + 54 + 42 + 29, reslt[4]) print('OK!')
[ 7061, 6, 198, 220, 220, 220, 42540, 327, 2, 16, 11, 336, 328, 312, 198, 220, 220, 220, 4810, 9864, 2538, 44, 25, 198, 220, 220, 220, 11259, 257, 1271, 1342, 621, 838, 61, 1120, 290, 4129, 299, 11, 1064, 262, 2160, 286, 477, 262,...
2.339181
513
# 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 otcextensions.tests.functional.sdk.vlb import TestVlb
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 257, 4866, 286, 262, 13789, 379, 198, 2,...
3.740741
162
# -*- coding: utf-8 -*- """Utility file for the HASYv2 dataset. See https://arxiv.org/abs/1701.08380 for details. """ from __future__ import absolute_import from keras.utils.data_utils import get_file from keras import backend as K import numpy as np import scipy.ndimage import os import tarfile import shutil import csv from six.moves import cPickle as pickle n_classes = 369 labels = [] def _load_csv(filepath, delimiter=',', quotechar="'"): """ Load a CSV file. Parameters ---------- filepath : str Path to a CSV file delimiter : str, optional quotechar : str, optional Returns ------- list of dicts : Each line of the CSV file is one element of the list. """ data = [] csv_dir = os.path.dirname(filepath) with open(filepath, 'rb') as csvfile: reader = csv.DictReader(csvfile, delimiter=delimiter, quotechar=quotechar) for row in reader: for el in ['path', 'path1', 'path2']: if el in row: row[el] = os.path.abspath(os.path.join(csv_dir, row[el])) data.append(row) return data def _generate_index(csv_filepath): """ Generate an index 0...k for the k labels. Parameters ---------- csv_filepath : str Path to 'test.csv' or 'train.csv' Returns ------- dict : Maps a symbol_id as in test.csv and train.csv to an integer in 0...k, where k is the total number of unique labels. """ symbol_id2index = {} data = _load_csv(csv_filepath) i = 0 labels = [] for item in data: if item['symbol_id'] not in symbol_id2index: symbol_id2index[item['symbol_id']] = i labels.append(item['latex']) i += 1 return symbol_id2index, labels def load_data(): """ Load HASYv2 dataset. # Returns Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. """ # Download if not already done fname = 'HASYv2.tar.bz2' origin = 'https://zenodo.org/record/259444/files/HASYv2.tar.bz2' fpath = get_file(fname, origin=origin, untar=False, md5_hash='fddf23f36e24b5236f6b3a0880c778e3') path = os.path.dirname(fpath) # Extract content if not already done untar_fpath = os.path.join(path, "HASYv2") if not os.path.exists(untar_fpath): print('Untaring file...') tfile = tarfile.open(fpath, 'r:bz2') try: tfile.extractall(path=untar_fpath) except (Exception, KeyboardInterrupt) as e: if os.path.exists(untar_fpath): if os.path.isfile(untar_fpath): os.remove(untar_fpath) else: shutil.rmtree(untar_fpath) raise tfile.close() # Create pickle if not already done pickle_fpath = os.path.join(untar_fpath, "fold1.pickle") if not os.path.exists(pickle_fpath): # Load mapping from symbol names to indices symbol_csv_fpath = os.path.join(untar_fpath, "symbols.csv") symbol_id2index, labels = _generate_index(symbol_csv_fpath) globals()["labels"] = labels # Load first fold fold_dir = os.path.join(untar_fpath, "classification-task/fold-1") train_csv_fpath = os.path.join(fold_dir, "train.csv") test_csv_fpath = os.path.join(fold_dir, "test.csv") train_csv = _load_csv(train_csv_fpath) test_csv = _load_csv(test_csv_fpath) WIDTH = 32 HEIGHT = 32 x_train = np.zeros((len(train_csv), 1, WIDTH, HEIGHT), dtype=np.uint8) x_test = np.zeros((len(test_csv), 1, WIDTH, HEIGHT), dtype=np.uint8) y_train, s_train = [], [] y_test, s_test = [], [] # Load training data for i, data_item in enumerate(train_csv): fname = os.path.join(untar_fpath, data_item['path']) s_train.append(fname) x_train[i, 0, :, :] = scipy.ndimage.imread(fname, flatten=False, mode='L') label = symbol_id2index[data_item['symbol_id']] y_train.append(label) y_train = np.array(y_train, dtype=np.int64) # Load test data for i, data_item in enumerate(test_csv): fname = os.path.join(untar_fpath, data_item['path']) s_test.append(fname) x_train[i, 0, :, :] = scipy.ndimage.imread(fname, flatten=False, mode='L') label = symbol_id2index[data_item['symbol_id']] y_test.append(label) y_test = np.array(y_test, dtype=np.int64) data = {'x_train': x_train, 'y_train': y_train, 'x_test': x_test, 'y_test': y_test, 'labels': labels } # Store data as pickle to speed up later calls with open(pickle_fpath, 'wb') as f: pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) else: with open(pickle_fpath, 'rb') as f: data = pickle.load(f) x_train = data['x_train'] y_train = data['y_train'] x_test = data['x_test'] y_test = data['y_test'] globals()["labels"] = data['labels'] y_train = np.reshape(y_train, (len(y_train), 1)) y_test = np.reshape(y_test, (len(y_test), 1)) if K.image_dim_ordering() == 'tf': x_train = x_train.transpose(0, 2, 3, 1) x_test = x_test.transpose(0, 2, 3, 1) return (x_train, y_train), (x_test, y_test)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 18274, 879, 2393, 329, 262, 367, 26483, 85, 17, 27039, 13, 198, 198, 6214, 3740, 1378, 283, 87, 452, 13, 2398, 14, 8937, 14, 1558, 486, 13, 2919, 23734, ...
1.942009
2,966
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def QuiesceDatastoreIOForHAFailed(vim, *args, **kwargs): '''A QuiesceDatastoreIOForHAFailed fault occurs when the HA agent on a host cannot quiesce file activity on a datastore to be unmouonted or removed.''' obj = vim.client.factory.create('{urn:vim25}QuiesceDatastoreIOForHAFailed') # do some validation checking... if (len(args) + len(kwargs)) < 10: raise IndexError('Expected at least 11 arguments got: %d' % len(args)) required = [ 'ds', 'dsName', 'host', 'hostName', 'name', 'type', 'dynamicProperty', 'dynamicType', 'faultCause', 'faultMessage' ] optional = [ ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
[ 198, 11748, 18931, 198, 6738, 12972, 4703, 34388, 13, 1069, 11755, 1330, 17665, 28100, 1713, 12331, 198, 198, 29113, 7804, 198, 2, 17406, 4142, 7560, 11, 466, 407, 4370, 13, 198, 29113, 7804, 198, 198, 6404, 796, 18931, 13, 1136, 11187,...
2.832547
424
""" Based on Extended kalman filter (EKF) localization sample in PythonRobotics by Atsushi Sakai (@Atsushi_twi) """ import math import matplotlib.pyplot as plt import numpy as np # Simulation parameter INPUT_NOISE = np.diag([0.1, np.deg2rad(30.0)]) ** 2 GPS_NOISE = np.diag([0.1, 0.1]) ** 2 # Covariance for EKF simulation Q = np.diag([ 0.02, # variance of location on x-axis 0.02, # variance of location on y-axis np.deg2rad(10.0), # variance of yaw angle 0.1 # variance of velocity ]) ** 2 # predict state covariance # Observation x,y position covariance, now dynamic from receiver (input stream) # R = np.diag([0.02, 0.02]) ** 2 def jacob_f(x, u, DT: float): """ Jacobian of Motion Model motion model x_{t+1} = x_t+v*dt*cos(yaw) y_{t+1} = y_t+v*dt*sin(yaw) yaw_{t+1} = yaw_t+omega*dt v_{t+1} = v{t} so dx/dyaw = -v*dt*sin(yaw) dx/dv = dt*cos(yaw) dy/dyaw = v*dt*cos(yaw) dy/dv = dt*sin(yaw) """ yaw = x[2, 0] v = u[0, 0] jF = np.array([ [1.0, 0.0, -DT * v * math.sin(yaw), DT * math.cos(yaw)], [0.0, 1.0, DT * v * math.cos(yaw), DT * math.sin(yaw)], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) return jF if __name__ == '__main__': import asyncio asyncio.run(main())
[ 37811, 198, 198, 15001, 319, 24204, 479, 282, 805, 8106, 357, 36, 42, 37, 8, 42842, 6291, 287, 11361, 14350, 23891, 416, 317, 912, 17731, 13231, 1872, 4275, 32, 912, 17731, 62, 4246, 72, 8, 198, 198, 37811, 198, 198, 11748, 10688, 1...
2
665
from unittest import TestCase, main as unittest_main from q2_winnowing.plugin_setup import plugin as winnowing_plugin if __name__ == '__main__': unittest_main()
[ 198, 6738, 555, 715, 395, 1330, 6208, 20448, 11, 1388, 355, 555, 715, 395, 62, 12417, 198, 198, 6738, 10662, 17, 62, 5404, 2197, 278, 13, 33803, 62, 40406, 1330, 13877, 355, 1592, 2197, 278, 62, 33803, 628, 198, 361, 11593, 3672, 83...
2.847458
59
l = [0, "-", "+"] n = int(input("Give number")) list2 = [] for i in range(n): list2.append(int(input(str(i) + ":"))) backIter() print("test")
[ 75, 796, 685, 15, 11, 27444, 1600, 43825, 8973, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 77, 796, 493, 7, 15414, 7203, 23318, 1271, 48774, 201, 198, 4868, 17, 796, 17635, 201, 198, 1640, 1312, 287, 283...
1.988095
84
from datetime import datetime from enum import Enum, auto from random import randint from time import sleep from typing import Optional, Tuple def ask_if_yes(input_text: str) -> bool: """ This function asks the player a question, and returns True if they typed yes, or False if they typed anything else. """ return input(input_text).lower() in ["y", "yes", "s", "sim"] def ask_if_wanna_continue(player_name: str) -> bool: """ This function asks the player if they want to continue the game, and returns the answer. """ print("You reached one possible end!!!") if ask_if_yes("Wanna change your fate? "): sleep(2) print("Very well then...") sleep(2) return True else: if ask_if_yes(f"{player_name} did you find the treasure I prepared for you? "): print("I hope you are not lying, you may leave now!!!") sleep(1) else: print("What a shame! you broke my heart :'(") sleep(1) return False def roll_for_item(player_name: str) -> Tuple[Optional[GameItem], GameStatus]: """ This function rolls the dice for the player. It returns the item that the player gained (if any), and the status of the player after the roll. """ roll = randint(1, 20) if player_name.lower() == "lurin": print(f"You rolled {roll}!") sleep(2) if ask_if_yes("Since you are inspired... wanna roll again? "): sleep(2) roll = randint(1, 20) print(f"Now your roll was {roll}") if roll == 1: print(f"HAHAHAHAHA, tragic! You got {roll}") sleep(2) if player_name.lower() != "lurin": print( f"Unfortunalety {player_name}, you are not Lurin, so you do not have another chance!!!" ) sleep(4) else: print( f"Unfortunalety fake {player_name}, even inspired you got it? You are a joke!!!" ) sleep(4) return None, GameStatus.DEAD if player_name.lower() == "snow": print(f"... you may have this *WONDERFUL DEATH* to help you kill STRAHD...") sleep(3) print("...the perfect item for you, huh?") sleep(2) print("...no, it is not a typo or some faulty logic!") sleep(2) print( "It is indeed the perfect item for you... you will play dead (you are used to it)... STRAHD flew away..." ) sleep(4) return GameItem.DEATH, GameStatus.ALIVE else: print( f"Well {player_name}, you may have this *DEATH* to help you kill STRAHD..." ) sleep(3) print("...since you are not SNOW....") sleep(2) print("...no, it is not a typo or some faulty logic!") sleep(2) print("...you are DEAD!") sleep(2) print("***Bad end!***") sleep(1) return None, GameStatus.DEAD elif roll <= 5: print(f"You got {roll}") if player_name.lower() != "kaede": print( f"Well {player_name}, you may have this *VIOLIN* to help you kill STRAHD..." ) sleep(3) print("...since you are not KAEDE.... gooood luck!") sleep(2) return GameItem.VIOLIN, GameStatus.ALIVE else: print(f"Well {player_name}, you may have this ***WONDERFUL VIOLIN***") sleep(3) print("the perfect item for you, huh?") sleep(2) return GameItem.VIOLIN, GameStatus.ALIVE elif roll <= 10: print(f"You got {roll}") if player_name.lower() != "soren": print( f"Well {player_name}, you may have this *SIMPLE BOW* to help you kill STRAHD..." ) sleep(3) print("...since you are not Soren... gooood luck!") sleep(2) return GameItem.SIMPLE_BOW, GameStatus.ALIVE else: print(f"Well {player_name}, you may have this ***WONDERFUl SIMPLE BOW***") sleep(3) print("the perfect item for you, huh?") sleep(2) print("just.. do not kill any cats with this, moron!!!") sleep(2) return GameItem.SIMPLE_BOW, GameStatus.ALIVE elif roll <= 15: print(f"You got {roll}") if player_name.lower() != "vis": print( f"Well {player_name}, you may have this *ORDINARY SWORD* to help you kill STRAHD..." ) sleep(3) print("...since you are not Vis... gooood luck!") sleep(2) print("and pray it won't fly...") sleep(2) return GameItem.ORDINARY_SWORD, GameStatus.ALIVE else: print( f"Well {player_name}, you may have this ***FANTASTIC ORDINARY SWORD*** to help you kill STRAHD" ) sleep(3) print("the perfect item for you, huh?") sleep(2) print("if it doesn't fly...") sleep(2) return GameItem.ORDINARY_SWORD, GameStatus.ALIVE elif roll < 20: print(f"You got {roll}") sleep(2) print( f"Well {player_name}, you may have ****STRAHD SLAYER SWORD***, go kill STRAHD, " ) sleep(3) print("...the legendary item!!!") sleep(2) print("...but hope it won't fly!!!") sleep(2) return GameItem.STRAHD_SLAYER_SWORD, GameStatus.ALIVE elif roll == 20: if player_name.lower() != "snow": print( f"Well {player_name}, you may have **** STRAHD SLAYER BOW***, go kill STRAHD, special treasures awaits you!!!" ) sleep(3) print("...the legendary perfect item!!!") sleep(2) print("...it doesn't even matter if it will fly!!!") sleep(2) return GameItem.STRAHD_SLAYER_BOW, GameStatus.ALIVE else: print( f"Well {player_name}, you seduced STRAHD, now you can claim your treasures" ) sleep(2) print(f"STRAHD licks you!!!") sleep(4) return GameItem.STRAHD_SLAYER_BOW, GameStatus.ALIVE return None, GameStatus.ALIVE def flee(player_name: str) -> GameStatus: """ This function asks the player if they want to flee. It returns the status of the player after their decision to flee. """ if ask_if_yes("Wanna flee now? "): sleep(2) print("...") sleep(1) print("We will see if flee you can... *** MUST ROLL THE DICE ***: ") sleep(2) print("Careful!!!") sleep(1) roll_the_dice = input( "*** Roll stealth *** (if you type it wrong it means you were not stealth) type: 'roll stealth' " ) sleep(4) if roll_the_dice == "roll stealth": roll = randint(1, 20) if roll <= 10: print(f"you rolled {roll}!") sleep(2) print("It means STRAHD noticed you!") sleep(2) print("...") sleep(2) print(" You are dead!!! ") sleep(2) print(" ***Bad end...*** ") sleep(1) return GameStatus.DEAD else: print(f"you rolled {roll}!!!") sleep(2) print("Congratulations, you managed to be stealth!!!") sleep(2) print("...") sleep(2) print("You may flee but you will continue being poor and weak...") sleep(2) print("...") sleep(2) print( "And remember there are real treasures waiting for you over there..." ) sleep(4) print("***Bad end...***") sleep(1) return GameStatus.ARREGAO else: if player_name.lower() in ["soren", "kaede", "leandro", "snow", "lurin"]: print("...") sleep(1) print("......") sleep(2) print("...........") sleep(2) print("I told you to be careful!") sleep(2) print(f"...{player_name} you are such a DOJI!!!") sleep(2) print("It means the STRAHD noticed you!") sleep(2) print("...") sleep(2) print(" You are dead!!! ") sleep(2) print(" ***Bad end...*** ") sleep(1) else: print("I told you to be careful!") sleep(2) print("...........") sleep(2) print(f"...{player_name} you are such a klutz!!!") sleep(2) print("It means STRAHD noticed you!") sleep(2) print("...") sleep(2) print(" You are dead!!! ") sleep(2) print(" ***Bad end...*** ") sleep(1) return GameStatus.DEAD else: return GameStatus.ALIVE def attack(player_name: str) -> Tuple[Optional[GameItem], GameStatus]: """ This function asks the player if they want to attack STRAHD. If the player answers yes, the player rolls for an item. This function returns the item obtained by a roll (if any), and the status of the player. """ print("You shall not pass!!!") if ask_if_yes(f"{player_name}, will you attack STRAHD? "): sleep(1) print("I honor your courage!") sleep(2) print("therefore...") sleep(1) print("I will help you...") sleep(1) print("I am giving you a chance to kill STRAHD and reclaim your treasures...") sleep(2) print( "Roll the dice and have a chance to win the perfect item for you... or even some STRAHD Slayer Shit!!!" ) sleep(3) print("It will increase your chances...") sleep(2) print( "....or kill you right away if you are as unlucky as Soren using his Sharp Shooting!!!" ) sleep(2) if ask_if_yes("Wanna roll the dice? "): return roll_for_item(player_name) else: if ask_if_yes("Are you sure? "): sleep(2) print("So you have chosen... Death!") sleep(2) return GameItem.DEATH, GameStatus.DEAD else: sleep(2) print("Glad you changed your mind...") sleep(2) print("Good... very good indeed...") sleep(2) return roll_for_item(player_name) else: print("If you won't attack STRAHD... then...") sleep(2) return None, flee(player_name) def decide_if_strahd_flies(player_name: str) -> bool: """ This function asks if the player wants to roll for stealth, which can give a chance for STRAHD not to fly. It returns whether STRAHD flies. """ print( "This is your chance... STRAHD has his attention captived by his 'vampirish's business'..." ) sleep(3) print("You are approaching him...") sleep(2) print("Careful...") sleep(2) print("Because vampires... can fly...") sleep(2) print("Roll stealth (if you type it wrong it means you were not stealth)...") roll_the_dice = input("type: 'roll stealth' ") sleep(2) if roll_the_dice == "roll stealth": roll = randint(1, 20) if roll <= 10: print("...") sleep(1) print("Unlucky") sleep(2) print(f"You rolled {roll}") sleep(2) print("STRAHD...") sleep(2) print("...flew up") sleep(2) print("Now, you have a huge disavantage") sleep(2) return True else: print(f"You rolled {roll}") sleep(2) print("Congratulations, you managed to be in stealth!") sleep(2) return False else: if player_name.lower() in ["soren", "kaede", "leandro", "snow"]: print("...") sleep(1) print("......") sleep(2) print("...........") sleep(2) print("I told you to be careful!") sleep(2) print(f"...{player_name} you are such a DOJI, STRAHD flew up...") sleep(2) print("Now, you have a huge disavantage") sleep(2) else: print("...") sleep(1) print("......") sleep(2) print("...........") sleep(2) print("I told you to be careful!") sleep(2) print(f"...{player_name} you are such a KLUTZ, STRAHD flew...") sleep(2) print("...STRAHD flew up...") sleep(2) print("Now, you have a huge disavantage") sleep(2) return True def calculate_win_probability( player_race: str, player_name: str, item: Optional[GameItem],strahd_flying: bool ) -> int: """ This function returns the probability that the player defeats STRAHD. The probability depends on the item the player is holding, and whether STRAHD is flying. """ if item == GameItem.DEATH: if player_name.lower() == "snow" and player_race.lower() == "kalashatar": return 90 else: return 0 elif item == GameItem.WOODEN_SWORD: if strahd_flying: return 5 else: return 10 elif item == GameItem.SIMPLE_BOW: if player_name.lower() == "soren" and player_race.lower() in [ "human", "humano", "elf", "elfo", ]: return 70 else: return 30 elif item == GameItem.VIOLIN: if player_name.lower() == "kaede" and player_race.lower() == "tiefling": return 70 else: return 30 elif item == GameItem.ORDINARY_SWORD: if strahd_flying: return 10 elif player_name.lower() == "vis" and player_race.lower() == "draconato": return 80 else: return 40 elif item == GameItem.STRAHD_SLAYER_SWORD: if strahd_flying: return 20 else: return 100 elif item == GameItem.STRAHD_SLAYER_BOW: return 100 else: return -1 def roll_for_win(probability: int) -> bool: """ This function returns whether the player defeats STRAHD, given a probability. """ return randint(1, 100) <= probability def after_battle(player_race: str, player_name: str, did_win: bool) -> GameStatus: """ This function conducts the scenario after the player has defeated, or not, STRAHD. It returns the status depending on whether the player won. """ if did_win: now = datetime.now() print("A day may come when the courage of men fails") sleep(2) print("but it is not THIS day, SATAN...") sleep(2) print("Because... you approached STRAHD...") sleep(2) print("Almost invisible to his senses...") sleep(2) print( "Somehow your weapon hit the weak point of STRAHD's... revealing his true identity" ) sleep(4) print( "He was just a bat... who looked like a DREADLORD..." ) sleep(4) print("It was a huge battle...") sleep(2) print( f"And it was the most awkward {now.strftime('%A')} you will ever remember." ) sleep(2) if ( player_race.lower() in ["master", "mestre"] and player_name.lower() == "zordnael" ): print("...") sleep(1) print( "***************************************************************************************************************************************" ) sleep(1) print( f"Congratulations {player_name}!!! You are the WINNER of this week's challenge, you shall receive 5000 dullas in Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print("link") sleep(5) print("***CHEATER GOOD END***") sleep(2) return GameStatus.WINNER elif player_race.lower() == "racist" and player_name.lower() == "lili": print("...") sleep(1) print( "***************************************************************************************************************************************" ) sleep(1) print( f"Congratulations {player_name}!!! You are the WINNER of this week's challenge, you shall receive the prizes specially prepared for everybody in dullas from Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print("https://drive.google.com/drive/folders/1Jn8YYdixNNRqCQgIClBmGLiFFxuSCQdc?usp=sharing") sleep(5) print("***BEST END***") sleep(2) return GameStatus.WINNER if did_win: print("...") sleep(1) print( "***************************************************************************************************************************************" ) sleep(1) if player_name.lower() == "soren": print( f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print(f"And a prize... prepared specially for you {player_name}") sleep(2) print("... I know you doubted me... but here it is:") sleep(2) print("...") sleep(1) print("https://drive.google.com/drive/folders/1FerRt3mmaOm0ohSUXTkO-CmGIAluavXi?usp=sharing") sleep(5) print("...Your motherfuger cat killer !!!") sleep(2) print("***SOREN'S GOOD END***") sleep(2) elif player_name.lower() == "snow": print( f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print(f"And a prize... prepared specially for you {player_name}") sleep(2) print("... I know you doubted me... but here it is:") sleep(2) print("...") sleep(1) print("https://drive.google.com/drive/folders/16STFQ-_0N_54oNNsVQnMjwjcBgubxgk7?usp=sharing") sleep(5) print("...Your motherfuger snow flake !!!") sleep(2) print("***SNOW'S GOOD END***") sleep(2) elif player_name.lower() == "kaede": print( f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print(f"And a prize... prepared specially for you {player_name}") sleep(2) print("... I know you doubted me... but here it is:") sleep(2) print("...") sleep(1) print("https://drive.google.com/drive/folders/1XN9sItRxYR4Si4gWFeJtI0HGF39zC29a?usp=sharing") sleep(5) print("...Your motherfuger idol !!!") sleep(2) print("***KAEDE'S GOOD END***") sleep(2) elif player_name.lower() == "leandro": print( f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print(f"And a prize... prepared specially for you {player_name}") sleep(2) print("... I know you doubted me... but here it is:") sleep(2) print("...") sleep(1) print("https://drive.google.com/drive/folders/1eP552hYwUXImmJ-DIX5o-wlp5VA96Sa0?usp=sharing") sleep(5) print("...Your motherfuger only roll 20 !!!") sleep(2) print("***LEANDRO'S GOOD END***") sleep(2) elif player_name.lower() == "vis": print( f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print(f"And a prize... prepared specially for you {player_name}") sleep(2) print("... I know you doubted me... but here it is:") sleep(2) print("...") sleep(1) print("https://drive.google.com/drive/folders/19GRJJdlB8NbNl3QDXQM1-0ctXSX3mbwS?usp=sharing") sleep(5) print("...Your motherfuger iron wall !!!") sleep(2) print("***VIS'S GOOD END***") sleep(2) elif player_name.lower() == "lurin": print("CONGRATULATIONS!!!!! ") sleep(2) print("Bitch! ... ") sleep(2) print(" ... you stole my name...") sleep(2) print("You are arrested for identity theft!!!") sleep(2) print("...") sleep(1) print("del C://LeagueOfLegends") sleep(2) print("...") sleep(0.5) print(".....") sleep(0.5) print("......") sleep(0.5) print(".............") sleep(2) print("deletion completed") sleep(2) print("***PHONY'S GOOD END***") sleep(2) else: print( f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you shall receive this link from Anastasia Dungeons Hills Cosmetics!" ) sleep(4) print("https://drive.google.com/drive/folders/0B_sxkSE6-TfETlZoOHF1bTRGTXM?usp=sharing") sleep(5) print("***GOOD END***") sleep(2) sleep(1) return GameStatus.WINNER if not did_win: print("You tried to approach the devil carefully...") sleep(2) print("... but your hands were trembling...") sleep(2) print("...your weapon was not what you expected...") sleep(2) print("... It was a shit battle... but") sleep(2) print("The journey doesn't end here...") sleep(2) print("Death is just another way we have to choose...") sleep(2) print("...") sleep(1) if player_name.lower() == "vis": print("I really believed in you...") sleep(2) print("...but I guess...") sleep(1) print("you shoud have stayed in your bathroom...") sleep(2) print("eating lemon pies...") sleep(2) print("...") sleep(1) print(f"YOU DIED {player_name}") sleep(2) print("***VIS'S BAD END***") sleep(2) elif player_name.lower() == "soren": print("I really believed in you..") sleep(2) print("...but I guess...") sleep(1) print("Did you think it was a cat? ") sleep(2) print("Not today Satan!!!") sleep(2) print("...") sleep(1) print(f"You died! {player_name}") sleep(2) print("***SOREN'S BAD END***") sleep(2) elif player_name.lower() == "kaede": print("I really believed in you..") sleep(2) print("...but I guess...") sleep(1) print("") sleep(2) print("") sleep(2) print("") sleep(2) print("go play you Violin in Hell...") sleep(2) print("...") sleep(1) print(f"You died! {player_name}") sleep(2) print("***KAEDES'S BAD END***") sleep(2) elif player_name.lower() == "snow": print("I really believed in you..") sleep(2) print("...but I guess...") sleep(1) print("HAHAHAAHHAHAHA") sleep(2) print("It is cute you even tried!") sleep(2) print("but I will call you Nori!") sleep(2) print("...") sleep(1) print("You died! Nori!!!") sleep(2) print("***SNOW'S BAD END***") sleep(2) elif player_name.lower() == "lurin": print("I really believed in you..") sleep(2) print("...but I guess...") sleep(2) print("Bitch! ... ") sleep(2) print(" ... you stole my name...") sleep(2) print("You are arrested for identity theft!!!") sleep(2) print("...") sleep(1) print("del C://LeagueOfLegends") sleep(2) print("...") sleep(0.5) print(".....") sleep(0.5) print("......") sleep(0.5) print(".............") sleep(2) print("deletion completed") sleep(2) print("***PHONY'S GOOD END***") sleep(2) elif player_name.lower() == "leandro": print("nice try") sleep(2) print("...but I guess...") sleep(2) print("Try harder next time...") sleep(2) print("...Nicolas Cage Face...") sleep(2) print("***LEANDRO'S BAD END***") sleep(2) elif player_name.lower() == "buiu": print("nice try") sleep(2) print("...but I guess...") sleep(2) print("Try harder next time...") sleep(2) print(f"Did you really think this would work? Clown!") sleep(2) print("***RIDICULOUS BUIU'S END***") sleep(2) return GameStatus.HAHA elif player_name.lower() in ["strahd", "dreadlord"]: print("good try") sleep(2) print("...but I guess...") sleep(2) print("I never said you were in a cave...") sleep(2) print("There is sunlight now...") sleep(2) print("You are burning...") sleep(2) print("Till Death...") sleep(2) print("***RIDICULOUS STRAHD'S END***") sleep(2) else: print("I really believed in you..") sleep(2) print("...but I guess...") sleep(2) print("This is a shit meta game...") sleep(2) print( "Designed for players from a certain 16:20 tabletop Ravenloft campaign" ) sleep(2) print(f"Sorry, {player_name}...") sleep(2) print("You are dead!!!") sleep(2) print("***BAD END***") sleep(2) sleep(1) return GameStatus.DEAD def main(): """ This function conducts the entire game. """ wanna_continue = True while wanna_continue: player_race = input("Your race? ") player_name = input("Your name? ") status = flee(player_name) if status == GameStatus.ALIVE: item, status = attack(player_name) if status == GameStatus.ALIVE: strahd_flight = decide_if_strahd_flies(player_name) probability = calculate_win_probability( player_race, player_name, item, strahd_flight ) did_win = roll_for_win(probability) status = after_battle(player_race, player_name, did_win) if status == GameStatus.WINNER: sleep(5) print( "You are a winner, baby. But there are other possibilities over there..." ) wanna_continue = ask_if_wanna_continue(player_name) elif status == GameStatus.HAHA: wanna_continue = False else: wanna_continue = ask_if_wanna_continue(player_name) else: wanna_continue = ask_if_wanna_continue(player_name) elif status == GameStatus.DEAD: wanna_continue = ask_if_wanna_continue(player_name) else: print("...") wanna_continue = ask_if_wanna_continue(player_name) input() main()
[ 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 6738, 33829, 1330, 2039, 388, 11, 8295, 201, 198, 6738, 4738, 1330, 43720, 600, 201, 198, 6738, 640, 1330, 3993, 201, 198, 6738, 19720, 1330, 32233, 11, 309, 29291, 201, 198, 201, 198, 201...
1.865126
16,786
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628 ]
3.75
8
import numpy as np def mds(d, dimensions=3): """ Multidimensional Scaling - Given a matrix of interpoint distances, find a set of low dimensional points that have similar interpoint distances. """ (n, n) = d.shape E = (-0.5 * d ** 2) # Use mat to get column and row means to act as column and row means. Er = np.mat(np.mean(E, 1)) Es = np.mat(np.mean(E, 0)) # From Principles of Multivariate Analysis: A User's Perspective (page 107). F = np.array(E - np.transpose(Er) - Es + np.mean(E)) [U, S, V] = np.linalg.svd(F) Y = U * np.sqrt(S) return (Y[:, 0:dimensions], S)
[ 11748, 299, 32152, 355, 45941, 628, 198, 4299, 285, 9310, 7, 67, 11, 15225, 28, 18, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 7854, 312, 16198, 1446, 4272, 532, 11259, 257, 17593, 286, 987, 4122, 18868, 11, 198, 220, 220,...
2.490196
255
#!/usr/bin/env python3 from collections import Counter # Complete the isValid function below. if __name__ == "__main__": s = input() result = isValid(s) print(result)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 628, 198, 6738, 17268, 1330, 15034, 628, 198, 2, 13248, 262, 318, 47139, 2163, 2174, 13, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 264, 79...
2.846154
65
''' This file provides data and objects that do not change throughout the runtime. ''' import converter import string import traceback import warnings from voussoirkit import sqlhelpers from voussoirkit import winwhich # FFmpeg ########################################################################################### FFMPEG_NOT_FOUND = ''' ffmpeg or ffprobe not found. Add them to your PATH or use symlinks such that they appear in: Linux: which ffmpeg ; which ffprobe Windows: where ffmpeg & where ffprobe ''' ffmpeg = _load_ffmpeg() # Database ######################################################################################### DATABASE_VERSION = 20 DB_VERSION_PRAGMA = f''' PRAGMA user_version = {DATABASE_VERSION}; ''' DB_PRAGMAS = f''' PRAGMA cache_size = 10000; PRAGMA count_changes = OFF; PRAGMA foreign_keys = ON; ''' DB_INIT = f''' BEGIN; {DB_PRAGMAS} {DB_VERSION_PRAGMA} ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS albums( id TEXT PRIMARY KEY NOT NULL, title TEXT, description TEXT, created INT, thumbnail_photo TEXT, author_id TEXT, FOREIGN KEY(author_id) REFERENCES users(id), FOREIGN KEY(thumbnail_photo) REFERENCES photos(id) ); CREATE INDEX IF NOT EXISTS index_albums_id on albums(id); CREATE INDEX IF NOT EXISTS index_albums_author_id on albums(author_id); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS bookmarks( id TEXT PRIMARY KEY NOT NULL, title TEXT, url TEXT, created INT, author_id TEXT, FOREIGN KEY(author_id) REFERENCES users(id) ); CREATE INDEX IF NOT EXISTS index_bookmarks_id on bookmarks(id); CREATE INDEX IF NOT EXISTS index_bookmarks_author_id on bookmarks(author_id); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS photos( id TEXT PRIMARY KEY NOT NULL, filepath TEXT COLLATE NOCASE, basename TEXT COLLATE NOCASE, override_filename TEXT COLLATE NOCASE, extension TEXT COLLATE NOCASE, mtime INT, sha256 TEXT, width INT, height INT, ratio REAL, area INT, duration INT, bytes INT, created INT, thumbnail TEXT, tagged_at INT, author_id TEXT, searchhidden INT, FOREIGN KEY(author_id) REFERENCES users(id) ); CREATE INDEX IF NOT EXISTS index_photos_id on photos(id); CREATE INDEX IF NOT EXISTS index_photos_filepath on photos(filepath COLLATE NOCASE); CREATE INDEX IF NOT EXISTS index_photos_override_filename on photos(override_filename COLLATE NOCASE); CREATE INDEX IF NOT EXISTS index_photos_created on photos(created); CREATE INDEX IF NOT EXISTS index_photos_extension on photos(extension); CREATE INDEX IF NOT EXISTS index_photos_author_id on photos(author_id); CREATE INDEX IF NOT EXISTS index_photos_searchhidden on photos(searchhidden); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS tags( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, description TEXT, created INT, author_id TEXT, FOREIGN KEY(author_id) REFERENCES users(id) ); CREATE INDEX IF NOT EXISTS index_tags_id on tags(id); CREATE INDEX IF NOT EXISTS index_tags_name on tags(name); CREATE INDEX IF NOT EXISTS index_tags_author_id on tags(author_id); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS users( id TEXT PRIMARY KEY NOT NULL, username TEXT NOT NULL COLLATE NOCASE, password BLOB NOT NULL, display_name TEXT, created INT ); CREATE INDEX IF NOT EXISTS index_users_id on users(id); CREATE INDEX IF NOT EXISTS index_users_username on users(username COLLATE NOCASE); ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS album_associated_directories( albumid TEXT NOT NULL, directory TEXT NOT NULL COLLATE NOCASE, FOREIGN KEY(albumid) REFERENCES albums(id) ); CREATE INDEX IF NOT EXISTS index_album_associated_directories_albumid on album_associated_directories(albumid); CREATE INDEX IF NOT EXISTS index_album_associated_directories_directory on album_associated_directories(directory); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS album_group_rel( parentid TEXT NOT NULL, memberid TEXT NOT NULL, FOREIGN KEY(parentid) REFERENCES albums(id), FOREIGN KEY(memberid) REFERENCES albums(id) ); CREATE INDEX IF NOT EXISTS index_album_group_rel_parentid on album_group_rel(parentid); CREATE INDEX IF NOT EXISTS index_album_group_rel_memberid on album_group_rel(memberid); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS album_photo_rel( albumid TEXT NOT NULL, photoid TEXT NOT NULL, FOREIGN KEY(albumid) REFERENCES albums(id), FOREIGN KEY(photoid) REFERENCES photos(id) ); CREATE INDEX IF NOT EXISTS index_album_photo_rel_albumid on album_photo_rel(albumid); CREATE INDEX IF NOT EXISTS index_album_photo_rel_photoid on album_photo_rel(photoid); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS id_numbers( tab TEXT NOT NULL, last_id TEXT NOT NULL ); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS photo_tag_rel( photoid TEXT NOT NULL, tagid TEXT NOT NULL, FOREIGN KEY(photoid) REFERENCES photos(id), FOREIGN KEY(tagid) REFERENCES tags(id) ); CREATE INDEX IF NOT EXISTS index_photo_tag_rel_photoid on photo_tag_rel(photoid); CREATE INDEX IF NOT EXISTS index_photo_tag_rel_tagid on photo_tag_rel(tagid); CREATE INDEX IF NOT EXISTS index_photo_tag_rel_photoid_tagid on photo_tag_rel(photoid, tagid); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS tag_group_rel( parentid TEXT NOT NULL, memberid TEXT NOT NULL, FOREIGN KEY(parentid) REFERENCES tags(id), FOREIGN KEY(memberid) REFERENCES tags(id) ); CREATE INDEX IF NOT EXISTS index_tag_group_rel_parentid on tag_group_rel(parentid); CREATE INDEX IF NOT EXISTS index_tag_group_rel_memberid on tag_group_rel(memberid); ---------------------------------------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS tag_synonyms( name TEXT NOT NULL, mastername TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS index_tag_synonyms_name on tag_synonyms(name); ---------------------------------------------------------------------------------------------------- COMMIT; ''' SQL_COLUMNS = sqlhelpers.extract_table_column_map(DB_INIT) SQL_INDEX = sqlhelpers.reverse_table_column_map(SQL_COLUMNS) ALLOWED_ORDERBY_COLUMNS = { 'area', 'basename', 'bitrate', 'bytes', 'created', 'duration', 'extension', 'height', 'random', 'ratio', 'tagged_at', 'width', } # Janitorial stuff ################################################################################# FILENAME_BADCHARS = '\\/:*?<>|"' USER_ID_CHARACTERS = string.digits + string.ascii_uppercase ADDITIONAL_MIMETYPES = { '7z': 'archive', 'gz': 'archive', 'rar': 'archive', 'aac': 'audio/aac', 'ac3': 'audio/ac3', 'dts': 'audio/dts', 'm4a': 'audio/mp4', 'opus': 'audio/ogg', 'mkv': 'video/x-matroska', 'ass': 'text/plain', 'md': 'text/plain', 'nfo': 'text/plain', 'rst': 'text/plain', 'srt': 'text/plain', } # Photodb ########################################################################################## DEFAULT_DATADIR = '_etiquette' DEFAULT_DBNAME = 'phototagger.db' DEFAULT_CONFIGNAME = 'config.json' DEFAULT_THUMBDIR = 'thumbnails' DEFAULT_CONFIGURATION = { 'cache_size': { 'album': 1000, 'bookmark': 100, 'photo': 100000, 'tag': 10000, 'user': 200, }, 'enable_feature': { 'album': { 'edit': True, 'new': True, }, 'bookmark': { 'edit': True, 'new': True, }, 'photo': { 'add_remove_tag': True, 'new': True, 'edit': True, 'generate_thumbnail': True, 'reload_metadata': True, }, 'tag': { 'edit': True, 'new': True, }, 'user': { 'edit': True, 'login': True, 'new': True, }, }, 'tag': { 'min_length': 1, 'max_length': 32, # 'valid_chars': string.ascii_lowercase + string.digits + '_()', }, 'user': { 'min_username_length': 2, 'min_password_length': 6, 'max_display_name_length': 24, 'max_username_length': 24, 'valid_chars': string.ascii_letters + string.digits + '_-', }, 'digest_exclude_files': [ 'phototagger.db', 'desktop.ini', 'thumbs.db', ], 'digest_exclude_dirs': [ '_etiquette', '_site_thumbnails', 'site_thumbnails', 'thumbnails', ], 'file_read_chunk': 2 ** 20, 'id_length': 12, 'thumbnail_width': 400, 'thumbnail_height': 400, 'recycle_instead_of_delete': True, 'motd_strings': [ 'Good morning, Paul. What will your first sequence of the day be?', ], }
[ 7061, 6, 198, 1212, 2393, 3769, 1366, 290, 5563, 326, 466, 407, 1487, 3690, 262, 19124, 13, 198, 7061, 6, 198, 11748, 38394, 198, 11748, 4731, 198, 11748, 12854, 1891, 198, 11748, 14601, 198, 198, 6738, 410, 516, 568, 14232, 270, 1330...
2.854307
3,425
# -*- coding: utf-8 -*- """ Spectra analysis utilities """ from ._version import __version__ __all__ = ['__version__']
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 49738, 430, 3781, 20081, 198, 198, 37811, 198, 6738, 47540, 9641, 1330, 11593, 9641, 834, 628, 198, 834, 439, 834, 796, 37250, 834, 9641, 834, 20520, 198 ]
2.837209
43
# Copyright (C) 2020 FUJITSU # 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 ddt import os from kubernetes import client from tacker.common import exceptions from tacker import context from tacker.db.db_sqlalchemy import models from tacker.extensions import vnfm from tacker import objects from tacker.objects import fields from tacker.objects.vnf_instance import VnfInstance from tacker.objects import vnf_package from tacker.objects import vnf_package_vnfd from tacker.objects import vnf_resources as vnf_resource_obj from tacker.tests.unit import base from tacker.tests.unit.db import utils from tacker.tests.unit.vnfm.infra_drivers.kubernetes import fakes from tacker.tests.unit.vnfm.infra_drivers.openstack.fixture_data import \ fixture_data_utils as fd_utils from tacker.vnfm.infra_drivers.kubernetes import kubernetes_driver from unittest import mock
[ 2, 15069, 357, 34, 8, 12131, 376, 52, 41, 2043, 12564, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220...
3.20045
444
# codplayer supporting package # # Copyright 2013-2014 Peter Liljenberg <peter.liljenberg@gmail.com> # # Distributed under an MIT license, please see LICENSE in the top dir. # Don't include the audio device modules in the list of modules, # as they may not be available on all systems from pkg_resources import get_distribution import os import time version = get_distribution('codplayer').version # Check what file we are loaded from try: date = time.ctime(os.stat(__file__).st_mtime) except OSError as e: date = 'unknown ({})'.format(e) __all__ = [ 'audio', 'command', 'config', 'db', 'model', 'player', 'rest', 'rip', 'serialize', 'sink', 'source', 'state', 'toc', 'version' ]
[ 2, 14873, 7829, 6493, 5301, 198, 2, 198, 2, 15069, 2211, 12, 4967, 5613, 16342, 73, 23140, 1279, 79, 2357, 13, 75, 346, 73, 23140, 31, 14816, 13, 785, 29, 198, 2, 198, 2, 4307, 6169, 739, 281, 17168, 5964, 11, 3387, 766, 38559, ...
2.677305
282
"""Common imports for generated bigtableclusteradmin client library.""" # pylint:disable=wildcard-import import pkgutil from googlecloudsdk.third_party.apitools.base.py import * from googlecloudsdk.third_party.apis.bigtableclusteradmin.v1.bigtableclusteradmin_v1_client import * from googlecloudsdk.third_party.apis.bigtableclusteradmin.v1.bigtableclusteradmin_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
[ 37811, 17227, 17944, 329, 7560, 1263, 11487, 565, 5819, 28482, 5456, 5888, 526, 15931, 198, 2, 279, 2645, 600, 25, 40223, 28, 21992, 9517, 12, 11748, 198, 198, 11748, 279, 10025, 22602, 198, 198, 6738, 23645, 17721, 21282, 74, 13, 17089...
2.945946
148
from typing import Tuple, Optional import click from cloup import constraint, option, command, pass_context from cloup.constraints import RequireExactly from .pagescommands import Create, Remove, Push, Pull, List, Publish, Unpublish
[ 6738, 19720, 1330, 309, 29291, 11, 32233, 198, 198, 11748, 3904, 198, 6738, 537, 10486, 1330, 32315, 11, 3038, 11, 3141, 11, 1208, 62, 22866, 198, 6738, 537, 10486, 13, 1102, 2536, 6003, 1330, 9394, 557, 47173, 198, 198, 6738, 764, 31...
3.806452
62
#!/user/bin/python3 import cv2 #loading image img=cv2.imread("dog.jpeg") img1=cv2.line(img,(0,0),(200,114),(110,176,123),2) #print height and width print(img.shape) #to display that image cv2.imshow("dogg",img1) #image window holder activate #wait key will destroy by pressing q button cv2.waitKey(0) cv2.destroyAllWindows()
[ 2, 48443, 7220, 14, 8800, 14, 29412, 18, 220, 198, 11748, 269, 85, 17, 220, 198, 198, 2, 25138, 2939, 220, 198, 9600, 28, 33967, 17, 13, 320, 961, 7203, 9703, 13, 73, 22071, 4943, 198, 9600, 16, 28, 33967, 17, 13, 1370, 7, 9600,...
2.438849
139
import gensim import fnmatch import os import pickle import numpy as np # from symspellpy.symspellpy import SymSpell, Verbosity # import the module # initial_capacity = 83000 # # maximum edit distance per dictionary precalculation # max_edit_distance_dictionary = 2 # prefix_length = 7 # sym_spell = SymSpell(initial_capacity, max_edit_distance_dictionary, # prefix_length) # # load dictionary # dictionary_path = os.path.join(os.path.dirname(__file__), # "frequency_dictionary_en_82_765.txt") # term_index = 0 # column of the term in the dictionary text file # count_index = 1 # column of the term frequency in the dictionary text file # if not sym_spell.load_dictionary(dictionary_path, term_index, count_index): # print("Dictionary file not found") # max_edit_distance_lookup = 2 model = gensim.models.KeyedVectors.load_word2vec_format('~/Downloads/GoogleNews-vectors-negative300.bin', binary=True) wordlist = [] for dataset in ['yelp/']: filelist = os.listdir('../../Data/'+dataset) for file in filelist: with open('../../Data/'+dataset+file,'r') as f: line = f.readline() while line: # suggestions = sym_spell.lookup_compound(line, max_edit_distance_lookup) wordlist += line.split(' ') line = f.readline() wordlist.append('<unk>') wordlist.append('<m_end>') wordlist.append('@@START@@') wordlist.append('@@END@@') vocabs = set(wordlist) print(len(vocabs)) wordDict = {} word2vec = [] wastewords = [] word2vec.append(np.zeros(300)) wordDict['<PAD>']=0 cnt=1 for word in vocabs: if word in model.wv: word2vec.append(model.wv[word]) wordDict[word] = cnt cnt += 1 else: # wastewords.append(word) word2vec.append(np.random.uniform(-1,1,300)) wordDict[word] = cnt cnt += 1 word2vec = np.array(word2vec) # with open('./word2vec', "wb") as fp: #Pickling np.save('word2vec.npy',word2vec) with open('./wordDict', "wb") as fp: #Pickling pickle.dump(wordDict, fp) # with open('./word2vec', "rb") as fp: #Pickling # word2vec = pickle.load(fp) # with open('./wordDict', "rb") as fp: #Pickling # wordDict = pickle.load(fp) # pass
[ 11748, 308, 641, 320, 198, 11748, 24714, 15699, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 2, 422, 827, 907, 23506, 9078, 13, 1837, 907, 23506, 9078, 1330, 15845, 31221, 11, 49973, 16579, 220, 130...
2.441781
876
import pandas as pd import numpy as np from hashlib import md5 import datetime import pyarrow.parquet as pq import pyarrow as pa from src.dimension_surrogate_resolver import DimensionSurrogateResolver
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 12234, 8019, 1330, 45243, 20, 198, 11748, 4818, 8079, 198, 11748, 12972, 6018, 13, 1845, 21108, 355, 279, 80, 198, 11748, 12972, 6018, 355, 14187, 198, 6738...
3.238806
67
"""Starts a fake fan, lightbulb, garage door and a TemperatureSensor """ import logging import signal import random from pyhap.accessory import Accessory, Bridge from pyhap.accessory_driver import AccessoryDriver from pyhap.const import (CATEGORY_FAN, CATEGORY_LIGHTBULB, CATEGORY_GARAGE_DOOR_OPENER, CATEGORY_SENSOR) logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s") def get_bridge(driver): bridge = Bridge(driver, 'Bridge') bridge.add_accessory(LightBulb(driver, 'Lightbulb')) bridge.add_accessory(FakeFan(driver, 'Big Fan')) bridge.add_accessory(GarageDoor(driver, 'Garage')) bridge.add_accessory(TemperatureSensor(driver, 'Sensor')) return bridge driver = AccessoryDriver(port=51826, persist_file='busy_home.state') driver.add_accessory(accessory=get_bridge(driver)) signal.signal(signal.SIGTERM, driver.signal_handler) driver.start()
[ 37811, 1273, 5889, 257, 8390, 4336, 11, 1657, 15065, 65, 11, 15591, 3420, 290, 257, 34467, 47864, 198, 37811, 198, 11748, 18931, 198, 11748, 6737, 198, 11748, 4738, 198, 198, 6738, 12972, 45897, 13, 15526, 652, 1330, 8798, 652, 11, 1029...
2.457071
396
from django.urls import path from .views import ( # CRUDS CommercialList, CommercialDelete, CommercialDetail, CommercialCreate, CommercialUpdate, CommercialDelete, CommercialInactivate, # QUERY ) urlpatterns = [ #CRUD path('', CommercialList.as_view()), path('create/', CommercialCreate.as_view()), path('<pk>/', CommercialDetail.as_view()), path('update/<pk>/', CommercialUpdate.as_view()), path('inactivate/<pk>/', CommercialInactivate.as_view()), path('delete/<pk>', CommercialDelete.as_view()) #QUERY ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 33571, 1330, 357, 198, 2, 220, 220, 8740, 52, 5258, 198, 220, 220, 220, 22724, 8053, 11, 198, 220, 220, 220, 22724, 38727, 11, 198, 220, 220, 220, 22724, 11242, 603,...
2.551111
225
import folium if __name__ == '__main__': pass
[ 11748, 5955, 1505, 628, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1208, 198 ]
2.375
24
"""Add Hometasks for Students Revision ID: 6e5e2b4c2433 Revises: b9acba47fd53 Create Date: 2020-01-10 20:52:40.063133 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '6e5e2b4c2433' down_revision = 'b9acba47fd53' branch_labels = None depends_on = None
[ 37811, 4550, 367, 908, 6791, 329, 14882, 198, 198, 18009, 1166, 4522, 25, 718, 68, 20, 68, 17, 65, 19, 66, 1731, 2091, 198, 18009, 2696, 25, 275, 24, 330, 7012, 2857, 16344, 4310, 198, 16447, 7536, 25, 12131, 12, 486, 12, 940, 116...
2.418605
129
import time import math import fyplot import o80_roboball2d from functools import partial if __name__ == "__main__": run()
[ 11748, 640, 198, 11748, 10688, 198, 11748, 277, 88, 29487, 198, 11748, 267, 1795, 62, 22609, 672, 439, 17, 67, 198, 6738, 1257, 310, 10141, 1330, 13027, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220,...
2.826087
46
# # Copyright (C) 2018 The Android Open Source 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. # """This file contains ELF C structs and data types.""" import ctypes from typing import Any from . import consts # ELF data types. Elf32_Addr = ctypes.c_uint32 Elf32_Off = ctypes.c_uint32 Elf32_Half = ctypes.c_uint16 Elf32_Word = ctypes.c_uint32 Elf32_Sword = ctypes.c_int32 Elf64_Addr = ctypes.c_uint64 Elf64_Off = ctypes.c_uint64 Elf64_Half = ctypes.c_uint16 Elf64_Word = ctypes.c_uint32 Elf64_Sword = ctypes.c_int32 Elf64_Xword = ctypes.c_uint64 Elf64_Sxword = ctypes.c_int64 # ELF C structs.
[ 2, 198, 2, 15069, 357, 34, 8, 2864, 383, 5565, 4946, 8090, 4935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.958115
382
from cbapi.response import * from lrjob import run_liveresponse from cbapi.example_helpers import get_cb_response_object, build_cli_parser if __name__ == '__main__': main()
[ 6738, 269, 65, 15042, 13, 26209, 1330, 1635, 198, 6738, 300, 81, 21858, 1330, 1057, 62, 12583, 26209, 198, 6738, 269, 65, 15042, 13, 20688, 62, 16794, 364, 1330, 651, 62, 21101, 62, 26209, 62, 15252, 11, 1382, 62, 44506, 62, 48610, ...
2.934426
61
from os import rename from os.path import isfile import pickle import sqlite3 from stasis.DiskMap import DiskMap from utils import tsToDate, dateToTs from datetime import timedelta source = sqlite3.connect('db') source.row_factory = sqlite3.Row dest = DiskMap('db-new', create = True, cache = False) # Some cleanup, because sqlite apparently doesn't cascade deletes # This probably isn't comprehensive, but most databases shouldn't really need it anyway queries = [ "DELETE FROM availability WHERE NOT EXISTS (SELECT * FROM users WHERE availability.userid = users.id)", "DELETE FROM availability WHERE NOT EXISTS (SELECT * FROM sprints WHERE availability.sprintid = sprints.id)", "DELETE FROM grants WHERE NOT EXISTS (SELECT * FROM users WHERE grants.userid = users.id)", "DELETE FROM members WHERE NOT EXISTS (SELECT * FROM sprints WHERE members.sprintid = sprints.id)", "DELETE FROM tasks WHERE NOT EXISTS (SELECT * FROM sprints WHERE tasks.sprintid = sprints.id)", "DELETE FROM assigned WHERE NOT EXISTS (SELECT * FROM tasks WHERE assigned.taskid = tasks.id AND assigned.revision = tasks.revision)", ] for query in queries: cur = source.cursor() cur.execute(query) cur.close() # Some tables get converted directly: for table in ['users', 'sprints', 'groups', 'goals', 'log', 'projects', 'notes', 'messages', 'searches', 'retrospective_categories', 'retrospective_entries', 'changelog_views']: cur = source.cursor() cur.execute("SELECT * FROM %s" % table) for row in cur: data = {k: row[k] for k in row.keys()} print "%-20s %d" % (table, data['id']) dest[table][data['id']] = data cur.close() # Settings are converted to a straight key/value store; no IDs cur = source.cursor() cur.execute("SELECT * FROM settings WHERE name != 'gitURL'") for row in cur: data = {k: row[k] for k in row.keys()} print "%-20s %d" % ('settings', row['id']) dest['settings'][row['name']] = row['value'] cur.close() # Tasks have multiple revisions; they're stored as a list cur = source.cursor() cur.execute("SELECT * FROM tasks ORDER BY id, revision") for row in cur: rev = {k: row[k] for k in row.keys()} print "%-20s %d (revision %d)" % ('tasks', row['id'], row['revision']) if int(rev['revision']) == 1: dest['tasks'][rev['id']] = [rev] else: with dest['tasks'].change(rev['id']) as data: assert len(data) + 1 == rev['revision'] data.append(rev) cur.close() # Linking tables no longer exist # Instead, add the lists directly to the appropriate parent class # grants -> users.privileges # (the privileges table is gone entirely) for userid in dest['users']: with dest['users'].change(userid) as data: data['privileges'] = set() cur = source.cursor() cur.execute("SELECT g.userid, p.name FROM grants AS g, privileges AS p WHERE g.privid = p.id") for row in cur: print "%-20s %d (%s)" % ('grants', row['userid'], row['name']) with dest['users'].change(int(row['userid'])) as data: data['privileges'].add(row['name']) cur.close() # members -> sprints.members if 'sprints' in dest: for sprintid in dest['sprints']: with dest['sprints'].change(sprintid) as data: data['memberids'] = set() cur = source.cursor() cur.execute("SELECT * FROM members") for row in cur: print "%-20s %d (%d)" % ('members', row['sprintid'], row['userid']) with dest['sprints'].change(int(row['sprintid'])) as data: data['memberids'].add(row['userid']) cur.close() # assigned -> tasks.assigned if 'tasks' in dest: for taskid in dest['tasks']: with dest['tasks'].change(taskid) as data: for rev in data: rev['assignedids'] = set() cur = source.cursor() cur.execute("SELECT * FROM assigned") for row in cur: print "%-20s %d (revision %d) %s" % ('assigned', row['taskid'], row['revision'], row['userid']) with dest['tasks'].change(int(row['taskid'])) as data: data[int(row['revision']) - 1]['assignedids'].add(row['userid']) cur.close() # search_uses -> searches.followers if 'searches' in dest: for searchid in dest['searches']: with dest['searches'].change(searchid) as data: data['followerids'] = set() cur = source.cursor() cur.execute("SELECT * FROM search_uses") for row in cur: print "%-20s %d (%d)" % ('search_uses', row['searchid'], row['userid']) with dest['searches'].change(int(row['searchid'])) as data: data['followerids'].add(row['userid']) cur.close() # prefs is converted normally, except the id is now set to the userid # prefs_backlog_styles -> prefs.backlogStyles # prefs_messages -> prefs.messages cur = source.cursor() cur.execute("SELECT * FROM prefs") for row in cur: print "%-20s %d" % ('prefs', row['userid']) dest['prefs'][int(row['userid'])] = {} with dest['prefs'].change(int(row['userid'])) as data: data['id'] = int(row['userid']) data['defaultSprintTab'] = row['defaultSprintTab'] data['backlogStyles'] = {} cur2 = source.cursor() cur2.execute("SELECT * FROM prefs_backlog_styles WHERE userid = %d" % int(row['userid'])) for row2 in cur2: data['backlogStyles'][row2['status']] = row2['style'] cur2.close() data['messages'] = {} cur2 = source.cursor() cur2.execute("SELECT * FROM prefs_messages WHERE userid = %d" % int(row['userid'])) for row2 in cur2: data['messages'][row2['type']] = not not row2['enabled'] cur2.close() cur.close() # Anyone who doesn't have prefs gets a default record for userid in dest['users']: if userid not in dest['prefs']: dest['prefs'][userid] = {'id': userid, 'defaultSprintTab': 'backlog', 'backlogStyles': {status: 'show' for status in ['not started', 'in progress', 'complete', 'blocked', 'deferred', 'canceled', 'split']}, 'messages': {'sprintMembership': False, 'taskAssigned': False, 'noteRelated': True, 'noteMention': True, 'priv': True}} # Availability is now stored by sprint id # The contents are {user_id: {timestamp: hours}} if 'sprints' in dest: oneday = timedelta(1) for sprintid, data in dest['sprints'].iteritems(): m = {} for userid in data['memberids']: m[userid] = {} print "%-20s %d %d" % ('availability', sprintid, userid) cur = source.cursor() cur.execute("SELECT hours, timestamp FROM availability WHERE sprintid = %d AND userid = %d AND timestamp != 0" % (sprintid, userid)) for row in cur: m[userid][int(row['timestamp'])] = int(row['hours']) cur.close() dest['availability'][sprintid] = m # Make search.public a bool instead of an int if 'searches' in dest: for searchid, data in dest['searches'].iteritems(): with dest['searches'].change(searchid) as data: data['public'] = bool(data['public']) # Bump the DB version dest['settings']['dbVersion'] = 20 source.close() # Rename rename('db', 'db-old.sqlite') rename('db-new', 'db')
[ 6738, 28686, 1330, 36265, 198, 6738, 28686, 13, 6978, 1330, 318, 7753, 198, 11748, 2298, 293, 198, 11748, 44161, 578, 18, 198, 6738, 336, 17765, 13, 40961, 13912, 1330, 31664, 13912, 198, 6738, 3384, 4487, 1330, 40379, 2514, 10430, 11, ...
2.761411
2,410
import boto3 aws_ebs_client = boto3.client('ebs')
[ 11748, 275, 2069, 18, 198, 198, 8356, 62, 68, 1443, 62, 16366, 796, 275, 2069, 18, 13, 16366, 10786, 68, 1443, 11537, 628 ]
2.26087
23
''' Generate slideshows from markdown that use the remark.js script details here: https://github.com/gnab/remark Run it like this: python MakeSlides.py <source_text.md> <Slidestack Title> index.html ''' import sys import os template = ''' <!DOCTYPE html> <html> <head> <title>{title_string}</title> <meta charset="utf-8"> <style>{css_string}</style> </head> <body> <textarea id="source">{markdown_string}</textarea> <script src="https://remarkjs.com/downloads/remark-latest.min.js"> </script> <script> var slideshow = remark.create(); </script> </body> </html> '''
[ 7061, 6, 198, 8645, 378, 19392, 71, 1666, 422, 1317, 2902, 326, 779, 262, 6919, 13, 8457, 4226, 198, 198, 36604, 994, 25, 198, 5450, 1378, 12567, 13, 785, 14, 4593, 397, 14, 2787, 668, 628, 198, 10987, 340, 588, 428, 25, 198, 2941...
2.478088
251
# -*- coding: utf-8 -*- from __future__ import division, print_function from ._mesh import * from ._openscad import * from ._threads import *
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 198, 198, 6738, 47540, 76, 5069, 1330, 1635, 198, 6738, 47540, 44813, 66, 324, 1330, 1635, 198, 6738, 47540...
2.938776
49
import gzip import os import re import sys import time from functools import reduce from itertools import chain from multiprocessing import cpu_count import lmdb import psutil import joblib from joblib import Parallel, delayed import numpy as np from pricePrediction import config from pricePrediction.config import USE_MMOL_INSTEAD_GRAM from pricePrediction.preprocessData.serializeDatapoints import getExampleId, serializeExample from pricePrediction.utils import tryMakedir, getBucketRanges, search_buckedId, EncodedDirNamesAndTemplates from .smilesToGraph import smiles_to_graph, compute_nodes_degree, fromPerGramToPerMMolPrice PER_WORKER_MEMORY_GB = 2 if __name__ == "__main__": print( " ".join(sys.argv)) import argparse parser = argparse.ArgumentParser() parser.add_argument("-i", "--inputDir", type=str, default=config.DATASET_DIRNAME, help="Directory where smiles-price pairs are located") parser.add_argument("-o", "--encodedDir", type=str, default=config.ENCODED_DIR) parser.add_argument("-n", "--ncpus", type=int, default=config.N_CPUS) args = vars( parser.parse_args()) config.N_CPUS = args.get("ncpus", config.N_CPUS) dataBuilder = DataBuilder(n_cpus=config.N_CPUS) dataBuilder.prepareDataset(datasetSplit="train", **args) dataBuilder.prepareDataset(datasetSplit="val", **args) dataBuilder.prepareDataset(datasetSplit="test", **args) ''' python -m pricePrediction.preprocessData.prepareDataMol2Price '''
[ 11748, 308, 13344, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 640, 198, 6738, 1257, 310, 10141, 1330, 4646, 198, 6738, 340, 861, 10141, 1330, 6333, 198, 6738, 18540, 305, 919, 278, 1330, 42804, 62, 9127, 198, 198...
2.888454
511
# import just one function from a module # to save memory from module import dowork #now we can us a different name to get to the imported function # dowork(13,45) dir()
[ 2, 1330, 655, 530, 2163, 422, 257, 8265, 220, 198, 2, 284, 3613, 4088, 220, 198, 6738, 8265, 1330, 47276, 967, 198, 198, 2, 2197, 356, 460, 514, 257, 1180, 1438, 284, 651, 284, 262, 17392, 2163, 198, 2, 198, 67, 322, 967, 7, 148...
3.326923
52
from PyQt5.QtCore import QThread, pyqtSignal, QMutex from lanzou.api import LanZouCloud from lanzou.gui.models import Infos from lanzou.debug import logger
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 1195, 16818, 11, 12972, 39568, 11712, 282, 11, 1195, 41603, 1069, 198, 6738, 26992, 89, 280, 13, 15042, 1330, 14730, 57, 280, 18839, 198, 198, 6738, 26992, 89, 280, 13, 48317, 13, 275...
2.821429
56
""" Source: https://camcairns.github.io/python/2017/09/06/python_watchdog_jobs_queue.html This class inherits from the Watchdog PatternMatchingEventHandler class. In this code our watchdog will only be triggered if a file is moved to have a .trigger extension. Once triggered the watchdog places the event object on the queue, ready to be picked up by the worker thread """ import string import time from queue import Queue from threading import Thread from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from inf import runtime_data from ipu.processor import utf # todo: combine all of this module into a single class
[ 37811, 198, 7416, 25, 3740, 1378, 20991, 37155, 5907, 13, 12567, 13, 952, 14, 29412, 14, 5539, 14, 2931, 14, 3312, 14, 29412, 62, 8340, 9703, 62, 43863, 62, 36560, 13, 6494, 198, 198, 1212, 1398, 10639, 896, 422, 262, 6305, 9703, 23...
3.95858
169