blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
065ed8e1883063a093f7825681b78b745794d1e3
Python
Usam95/CarND-Behavioral-Cloning-P3
/model.py
UTF-8
5,046
2.875
3
[ "MIT" ]
permissive
import os import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import keras from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D, Dropout, Flatten, Dense from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from imgaug import augmenters as iaa import cv2 import pandas as pd import ntpath import random import tensorflow as tf # This function reads in the data obtrained using simulator def readin_data(): datadir = "/Users/usam/Desktop/Data/" columns = ['center', 'left', 'right', 'steering', 'throttle', 'reverse', 'speed'] data = pd.read_csv(os.path.join(datadir, 'driving_log.csv'), names = columns) def path_leaf(path): head, tail = ntpath.split(path) return tail # This funtion edits the images pathes for easier working def split_path(): data['center'] = data['center'].apply(path_leaf) data['left'] = data['left'].apply(path_leaf) data['right'] = data['right'].apply(path_leaf) # This function balances the dataset and removes all samples # that are greater that threshold 400 def balance_dataset(): num_bins = 25 samples_per_bin = 400 remove_list = [] for j in range(num_bins): list_ = [] for i in range(len(data['steering'])): if data['steering'][i] >= bins[j] and data['steering'][i] <= bins[j+1]: list_.append(i) list_ = shuffle(list_) list_ = list_[samples_per_bin:] remove_list.extend(list_) print('removed:', len(remove_list)) data.drop(data.index[remove_list], inplace=True) print('remaining:', len(data)) # This function stores each image with corresponding steering angle def load_img_steering(datadir, df): image_path = [] steering = [] for i in range(len(data)): indexed_data = data.iloc[i] center, left, right = indexed_data[0], indexed_data[1], indexed_data[2] image_path.append(os.path.join(datadir, center.strip())) steering.append(float(indexed_data[3])) # left image append image_path.append(os.path.join(datadir,left.strip())) steering.append(float(indexed_data[3])+0.15) # right image append image_path.append(os.path.join(datadir,right.strip())) steering.append(float(indexed_data[3])-0.15) image_paths = np.asarray(image_path) steerings = np.asarray(steering) return image_paths, steerings def zoom(image): zoom = iaa.Affine(scale=(1, 1.3)) image = zoom.augment_image(image) return image def pan(image): pan = iaa.Affine(translate_percent= {"x" : (-0.1, 0.1), "y": (-0.1, 0.1)}) image = pan.augment_image(image) return image def img_random_brightness(image): brightness = iaa.Multiply((0.2, 1.2)) image = brightness.augment_image(image) return image def img_random_flip(image, steering_angle): image = cv2.flip(image,1) steering_angle = -steering_angle return image, steering_angle def random_augment(image, steering_angle): image = mpimg.imread(image) if np.random.rand() < 0.5: image = pan(image) if np.random.rand() < 0.5: image = zoom(image) if np.random.rand() < 0.5: image = img_random_brightness(image) if np.random.rand() < 0.5: image, steering_angle = img_random_flip(image, steering_angle) return image, steering_angle def img_preprocess(img): img = img[60:135,:,:] img = cv2.cvtColor(img, cv2.COLOR_RGB2YUV) img = cv2.GaussianBlur(img, (3, 3), 0) img = cv2.resize(img, (200, 66)) img = img/255 return img def batch_generator(image_paths, steering_ang, batch_size, istraining): while True: batch_img = [] batch_steering = [] for i in range(batch_size): random_index = random.randint(0, len(image_paths) - 1) if istraining: im, steering = random_augment(image_paths[random_index], steering_ang[random_index]) else: im = mpimg.imread(image_paths[random_index]) steering = steering_ang[random_index] im = img_preprocess(im) batch_img.append(im) batch_steering.append(steering) yield (np.asarray(batch_img), np.asarray(batch_steering)) def nvidia_model(): model = Sequential() model.add(Convolution2D(24, 5, 5, subsample=(2, 2), input_shape=(66, 200, 3), activation='elu')) model.add(Convolution2D(36, 5, 5, subsample=(2, 2), activation='elu')) model.add(Convolution2D(48, 5, 5, subsample=(2, 2), activation='elu')) model.add(Convolution2D(64, 3, 3, activation='elu')) model.add(Convolution2D(64, 3, 3, activation='elu')) # model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(100, activation = 'elu')) # model.add(Dropout(0.5)) model.add(Dense(50, activation = 'elu')) # model.add(Dropout(0.5)) model.add(Dense(10, activation = 'elu')) # model.add(Dropout(0.5)) model.add(Dense(1)) optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) model.compile(loss='mse', optimizer=optimizer) return model image_paths, steerings = load_img_steering(datadir + '/IMG', data) X_train, X_valid, y_train, y_valid = train_test_split(image_paths, steerings, test_size=0.2, random_state=6)
true
9aea7d955d13e6890f653f2df114b71c055c88bc
Python
wescran/advent-of-code-2019
/day2.py
UTF-8
1,175
3.25
3
[]
no_license
from pathlib import Path inputFile = Path("inputs/input-02-01.txt") # Part 1 splitFile = inputFile.read_text().split(",") data = [int(i) for i in splitFile] data[1], data[2] = 12, 2 num = 0 while num < len(data): if data[num] == 1: data[data[num+3]] = data[data[num+1]] + data[data[num+2]] elif data[num] == 2: data[data[num+3]] = data[data[num+1]] * data[data[num+2]] elif data[num] == 99: break num += 4 print(data[0]) # Part 2 splitFile = inputFile.read_text().split(",") data = [int(i) for i in splitFile] val = 19690720 for i in range(100): for j in range(100): new_data = list(data) new_data[1], new_data[2] = i, j num = 0 while num < len(data): if new_data[num] == 1: new_data[new_data[num+3]] = new_data[new_data[num+1]] + new_data[new_data[num+2]] elif new_data[num] == 2: new_data[new_data[num+3]] = new_data[new_data[num+1]] * new_data[new_data[num+2]] elif new_data[num] == 99: break num += 4 res = new_data[0] if res == val: print(100*i+j) break
true
75b568e3f074835d8b6b3031eb230a9ce8f48e4b
Python
margitantal68/featurelearning
/util/mlp.py
UTF-8
1,430
2.609375
3
[]
no_license
# MLP model import tensorflow.keras as keras import tensorflow as tf import numpy as np import time import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt def build_mlp(input_shape, nb_classes, file_path): input_layer = keras.layers.Input(input_shape) # flatten/reshape because when multivariate all should be on the same axis input_layer_flattened = keras.layers.Flatten()(input_layer) layer_1 = keras.layers.Dropout(0.1)(input_layer_flattened) layer_1 = keras.layers.Dense(512, activation='relu')(layer_1) layer_2 = keras.layers.Dropout(0.2)(layer_1) layer_2 = keras.layers.Dense(512, activation='relu')(layer_2) layer_3 = keras.layers.Dropout(0.2)(layer_2) layer_3 = keras.layers.Dense(512, activation='relu')(layer_3) output_layer = keras.layers.Dropout(0.3)(layer_3) output_layer = keras.layers.Dense(nb_classes, activation='softmax')(output_layer) model = keras.models.Model(inputs=input_layer, outputs=output_layer) model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.5, patience=200, min_lr=0.1) model_checkpoint = keras.callbacks.ModelCheckpoint(filepath=file_path, monitor='loss', save_best_only=True, verbose = 1) callbacks = [reduce_lr,model_checkpoint] return callbacks, model
true
16b3ef70337bee828f97962bcd8c81716a678ac7
Python
Z3Prover/z3
/scripts/pyg2hpp.py
UTF-8
1,100
2.8125
3
[ "MIT" ]
permissive
# - /usr/bin/env python """ Reads a pyg file and emits the corresponding C++ header file into the specified destination directory. """ import mk_genfile_common import argparse import logging import os import sys def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("pyg_file", help="pyg file") parser.add_argument("destination_dir", help="destination directory") pargs = parser.parse_args(args) if not os.path.exists(pargs.pyg_file): logging.error('"{}" does not exist'.format(pargs.pyg_file)) return 1 if not mk_genfile_common.check_dir_exists(pargs.destination_dir): return 1 pyg_full_path = os.path.abspath(pargs.pyg_file) destination_dir_full_path = os.path.abspath(pargs.destination_dir) logging.info('Using {}'.format(pyg_full_path)) output = mk_genfile_common.mk_hpp_from_pyg(pyg_full_path, destination_dir_full_path) logging.info('Generated "{}"'.format(output)) return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
true
893f11d6f7d41a77f94d9b366d1d7f55615030c9
Python
Kavita309/Severity-of-cyberbullying-across-SMPs
/Results/print_graphs_bar.py
UTF-8
637
3.515625
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 12:11:16 2019 @author: hp """ import matplotlib.pyplot as plt # x-coordinates of left sides of bars x = [1, 2, 3, 4] # Twitter embeddings y = [0.481, 0.419, 0.992, 0.848] tick_label = ['char', 'word', 'char-oversample', 'word-oversample'] # plotting a bar chart plt.bar(x, y, tick_label = tick_label, width = 0.2, color = ['purple']) # naming the x-axis plt.xlabel('Embedding Type') # naming the y-axis plt.ylabel('Precision for class High-Random Forest') # plot title plt.title('Embedding comparison!') # function to show the plot plt.show()
true
7a83b8a0a283e1aefbf42bb67c4651cc80062dd1
Python
djaney/genetic-agent
/agent.py
UTF-8
2,714
2.78125
3
[]
no_license
#!/usr/bin/python3 from evolution import Species import argparse import tornado.ioloop import tornado.web import json parser = argparse.ArgumentParser(description='Genetic algorithm agent') parser.add_argument('input', type=int) parser.add_argument('output', type=int) parser.add_argument('hidden', type=int) parser.add_argument('depth', type=int) parser.add_argument('--species', default=1) parser.add_argument('--population', default=10) parser.add_argument('--port', default=8888) agents = [] def get_json_body(handler): return json.loads(handler.request.body.decode('utf-8')) class AgentHandler(tornado.web.RequestHandler): def data_received(self, chunk): pass def set_default_headers(self): self.set_header('Content-Type', 'application/json') class ActHandler(AgentHandler): def post(self): data = get_json_body(self) if type(data) is not list: raise Exception("format must be[[agent_index, strain_index, [observations...]...]") res = [] for d in data: if type(d) is not list: raise Exception("format must be [[agent_index, strain_index, [observations...]...]") if type(d[0]) is not int: raise Exception("format must be [[agent_index, strain_index, [observations...]...]") if type(d[1]) is not int: raise Exception("format must be [[agent_index, strain_index, [observations...]...]") if type(d[2]) is not list: raise Exception("format must be [[agent_index, strain_index, [observations...]...]") action = agents[d[0]].act(d[2], d[1]) res.append([d[0], d[1], action.tolist()]) json_string = json.dumps(res) self.write(json_string) class RecHandler(AgentHandler): def post(self): data = get_json_body(self) res = [] for d in data: agent = agents[d[0]] agent.record(float(d[2]), d[1]) is_evolved = agent.is_ready_to_evolve() if is_evolved: agent.evolve() res.append([d[0], d[1], {'evolved': is_evolved}]) json_string = json.dumps(res) self.write(json_string) def make_app(): return tornado.web.Application([ (r"/act", ActHandler), (r"/rec", RecHandler), ]) def main(args): for _ in range(args.species): agents.append(Species(args.input, args.output, args.hidden, args.depth, strain_count=args.population)) agents[0].strains[0].summary() print('listening {}'.format(args.port)) app = make_app() app.listen(args.port) tornado.ioloop.IOLoop.current().start() main(parser.parse_args())
true
5683854aaab6d262c4a4e7a12ff47bdd89648c85
Python
AlexanPetrov/MovieGenres
/moviesPlot.py
UTF-8
227
2.921875
3
[]
no_license
from matplotlib import pyplot as plt totalNumberOfGenres = [1, 2, 3, 4, 5, 6, 7, 8, 9] numberMoviesPerGenere = [66, 128, 794, 10, 49, 18, 26, 272, 76573] plt.scatter(totalNumberOfGenres, numberMoviesPerGenere) plt.show();
true
860045a68465342f3dc5653493ec0a30d78cdfb5
Python
neilgall/pykanren
/pykanren/api.py
UTF-8
514
2.625
3
[]
no_license
from typing import Callable, Iterator, List from .goal import Goal from .term import Term from .microkanren import State def unify(lhs, rhs): def goal(state): return state.unify(lhs, rhs) return goal def disunify(lhs, rhs): def goal(state): return state.disunify(lhs, rhs) return goal def fresh(f: Callable[[Term], Goal]) -> Goal: def call(state: State) -> Iterator[State]: return state.with_new_var(f) return call def runGoal(goal: Goal) -> Iterator[State]: return goal(State())
true
d616475eac3003a201518e358715bfce8946ab2c
Python
JennyAlways/Python_Practice
/Py20190216/encrypt_some_messages_with_a_key.py
UTF-8
1,204
3.109375
3
[]
no_license
#!/usr/bin/python2.6 # -*- coding: utf-8 -*-key = 3 key=3 #加密 def encrypt(*messageTuple): mList = [] for message in messageTuple: letterList = list(message) encryptList = [] for i in range(len(letterList)): acsNum = ord (letterList[i]) acsNum = acsNum + key encryptList.append(chr (acsNum)) encryptMessage = "".join (encryptList) mList.append(encryptMessage) return mList #解密 def decrypt(encryptedMessage): rList = [] for eMessage in encryptedMessage: letterList = list(eMessage) decryptList = [] print eMessage for i in range(len(letterList)): acsNum = ord (letterList[i]) acsNum = acsNum - key decryptList.append(chr (acsNum)) decryptMessage = "".join (decryptList) rList.append(decryptMessage) return rList temp1 = encrypt("abc","123","cyljn","ryycyr","sk") print temp1 temp2 = decrypt(temp1) print temp2
true
7d42c1c653534a866da5dd4a438a12d03c9d181e
Python
FNSdev/webstore
/django/analytics/models.py
UTF-8
2,140
2.59375
3
[]
no_license
from django.db import models from django.core.validators import MaxValueValidator import datetime from user.models import CustomUser from core.models import Order class DataSample(models.Model): advertising_costs = models.DecimalField(max_digits=9, decimal_places=2, default=0) total_user_count = models.PositiveIntegerField(default=0) new_user_count = models.PositiveIntegerField(default=0) orders_count = models.PositiveIntegerField(default=0) used_coupone_count = models.PositiveIntegerField(default=0) average_discount = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(100)]) profit = models.DecimalField(max_digits=9, decimal_places=2, default=0) @staticmethod def prepare_sample(): args = {} date = datetime.datetime.now() date = date - datetime.timedelta(30) args['total_user_count'] = CustomUser.objects.count() args['new_user_count'] = CustomUser.objects.filter(date_joined__date__gt=date).count() orders = Order.objects.filter(date__date__gt=date) args['orders_count'] = orders.count() profit = 0 coupones = 0 discount = 0 for order in orders: if order.discount != 0: coupones += 1 discount += order.discount profit += order.total_price if coupones != 0: discount /= coupones args['used_coupone_count'] = coupones args['average_discount'] = discount args['profit'] = profit return args @staticmethod def get_data(): samples = DataSample.objects.all() x = [] y = [] for sample in samples: x_i, y_i = sample.get_sample_data() x.append(x_i) y.append(y_i) return x, y def get_sample_data(self): x = [ self.advertising_costs, self.total_user_count, self.new_user_count, self.orders_count, self.used_coupone_count, self.average_discount, ] y = self.profit return x, y
true
7abc6252ada1b99cc5fb14f9884eb32c6550786d
Python
golmschenk/sr-gan
/crowd/data.py
UTF-8
23,650
2.875
3
[]
no_license
""" Code for the crowd data dataset. """ import random from enum import Enum import scipy.misc import torch import numpy as np import torchvision from torch.utils.data import Dataset class CrowdDataset(Enum): """An enum to select the crowd dataset.""" ucf_cc_50 = 'UCF CC 50' ucf_qnrf = 'UCF QNRF' shanghai_tech = 'ShanghaiTech' world_expo = 'World Expo' class CrowdExample: """A class to represent all manner of crowd example data.""" image: np.ndarray or torch.Tensor label: np.ndarray or torch.Tensor or None roi: np.ndarray or torch.Tensor or None perspective: np.ndarray or torch.Tensor or None patch_center_y: int or None patch_center_x: int or None def __init__(self, image, label=None, roi=None, perspective=None, patch_center_y=None, patch_center_x=None, map_=None): self.image = image self.label = label self.roi = roi self.map = map_ self.perspective = perspective self.patch_center_y = patch_center_y self.patch_center_x = patch_center_x class NumpyArraysToTorchTensors: """ Converts from NumPy arrays of an example to Torch tensors. """ def __call__(self, example): """ :param example: A crowd example in NumPy. :type example: CrowdExample :return: The crowd example in Tensors. :rtype: CrowdExample """ example.image = example.image.transpose((2, 0, 1)) example.image = torch.tensor(example.image, dtype=torch.float32) if example.label is not None: example.label = torch.tensor(example.label, dtype=torch.float32) if example.map is not None: example.map = torch.tensor(example.map, dtype=torch.float32) if example.roi is not None: example.roi = torch.tensor(example.roi, dtype=torch.float32) if example.perspective is not None: example.perspective = torch.tensor(example.perspective, dtype=torch.float32) return example class Rescale: """ 2D rescaling of an example (when in NumPy HWC form). """ def __init__(self, scaled_size): self.scaled_size = scaled_size def __call__(self, example): """ :param example: A crowd example in NumPy. :type example: CrowdExample :return: The crowd example in Numpy with each of the arrays resized. :rtype: CrowdExample """ example.image = scipy.misc.imresize(example.image, self.scaled_size) original_label_sum = np.sum(example.label) example.label = scipy.misc.imresize(example.label, self.scaled_size, mode='F') if original_label_sum != 0: unnormalized_label_sum = np.sum(example.label) example.label = (example.label / unnormalized_label_sum) * original_label_sum example.roi = scipy.misc.imresize(example.roi, self.scaled_size, mode='F') > 0.5 example.map = scipy.misc.imresize(example.map, self.scaled_size, mode='F') return example class RandomHorizontalFlip: """ Randomly flips the example horizontally (when in NumPy HWC form). """ def __call__(self, example): """ :param example: A crowd example in NumPy. :type example: CrowdExample :return: The possibly flipped crowd example in Numpy. :rtype: CrowdExample """ if random.choice([True, False]): example.image = np.flip(example.image, axis=1).copy() example.label = np.flip(example.label, axis=1).copy() example.map = np.flip(example.map, axis=1).copy() if example.roi is not None: example.roi = np.flip(example.roi, axis=1).copy() if example.perspective is not None: example.perspective = np.flip(example.perspective, axis=1).copy() return example class NegativeOneToOneNormalizeImage: """ Normalizes a uint8 image to range -1 to 1. """ def __call__(self, example): """ :param example: A crowd example in NumPy with image from 0 to 255. :type example: CrowdExample :return: A crowd example in NumPy with image from -1 to 1. :rtype: CrowdExample """ example.image = (example.image.astype(np.float32) / (255 / 2)) - 1 return example class PatchAndRescale: """ Select a patch based on a position and rescale it based on the perspective map. """ def __init__(self, patch_size=128): self.patch_size = patch_size self.image_scaled_size = [self.patch_size, self.patch_size] self.label_scaled_size = [int(self.patch_size / 4), int(self.patch_size / 4)] def get_patch_for_position(self, example, y, x): """ Retrieves the patch for a given position. :param y: The y center of the patch. :type y: int :param x: The x center of the patch. :type x: int :param example: The full example with perspective to extract the patch from. :type example: CrowdExample :return: The patch. :rtype: CrowdExample """ patch_size_ = self.get_patch_size_for_position(example, y, x) half_patch_size = int(patch_size_ // 2) if y - half_patch_size < 0: example = self.pad_example(example, y_padding=(half_patch_size - y, 0)) y += half_patch_size - y if y + half_patch_size > example.label.shape[0]: example = self.pad_example(example, y_padding=(0, y + half_patch_size - example.label.shape[0])) if x - half_patch_size < 0: example = self.pad_example(example, x_padding=(half_patch_size - x, 0)) x += half_patch_size - x if x + half_patch_size > example.label.shape[1]: example = self.pad_example(example, x_padding=(0, x + half_patch_size - example.label.shape[1])) image_patch = example.image[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size, :] label_patch = example.label[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size] roi_patch = example.roi[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size] map_ = example.map[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size] return CrowdExample(image=image_patch, label=label_patch, roi=roi_patch, map_=map_) @staticmethod def get_patch_size_for_position(example, y, x): """ Gets the patch size for a 3x3 meter area based of the perspective and the position. :param example: The example with perspective information. :type example: CrowdExample :param x: The x position of the center of the patch. :type x: int :param y: The y position of the center of the patch. :type y: int :return: The patch size. :rtype: float """ pixels_per_meter = example.perspective[y, x] patch_size_ = 3 * pixels_per_meter return patch_size_ @staticmethod def pad_example(example, y_padding=(0, 0), x_padding=(0, 0)): """ Pads the example. :param example: The example to pad. :type example: CrowdExample :param y_padding: The amount to pad the y dimension. :type y_padding: (int, int) :param x_padding: The amount to pad the x dimension. :type x_padding: (int, int) :return: The padded example. :rtype: CrowdExample """ z_padding = (0, 0) image = np.pad(example.image, (y_padding, x_padding, z_padding), 'constant') label = np.pad(example.label, (y_padding, x_padding), 'constant') roi = np.pad(example.roi, (y_padding, x_padding), 'constant', constant_values=False) map_ = np.pad(example.map, (y_padding, x_padding), 'constant') return CrowdExample(image=image, label=label, roi=roi, map_=map_) def resize_patch(self, patch): """ :param patch: The patch to resize. :type patch: CrowdExample :return: The crowd example that is the resized patch. :rtype: CrowdExample """ image = scipy.misc.imresize(patch.image, self.image_scaled_size) original_label_sum = np.sum(patch.label) label = scipy.misc.imresize(patch.label, self.label_scaled_size, mode='F') unnormalized_label_sum = np.sum(label) if unnormalized_label_sum != 0: label = (label / unnormalized_label_sum) * original_label_sum roi = scipy.misc.imresize(patch.roi, self.label_scaled_size, mode='F') > 0.5 map_ = scipy.misc.imresize(patch.map, self.label_scaled_size, mode='F') return CrowdExample(image=image, label=label, roi=roi, map_=map_) class ExtractPatchForPositionAndRescale(PatchAndRescale): """ Given an example and a position, extracts the appropriate patch based on the perspective. """ def __call__(self, example_with_perspective, y, x): """ :param example_with_perspective: A crowd example with perspective. :type example_with_perspective: CrowdExample :return: A crowd example and the original patch size. :rtype: (CrowdExample, int) """ original_patch_size = self.get_patch_size_for_position(example_with_perspective, y, x) patch = self.get_patch_for_position(example_with_perspective, y, x) roi_image_patch = patch.image * np.expand_dims(patch.roi, axis=-1) patch = CrowdExample(image=roi_image_patch, label=patch.label * patch.roi, roi=patch.roi, map_=patch.map) example = self.resize_patch(patch) return example, original_patch_size class RandomlySelectPatchAndRescale(PatchAndRescale): """ Selects a patch of the example and resizes it based on the perspective map. """ def __call__(self, example): """ :param example: A crowd example with perspective. :type example: CrowdExample :return: A crowd example. :rtype: CrowdExample """ while True: y, x = self.select_random_position(example) patch = self.get_patch_for_position(example, y, x) if np.any(patch.roi): roi_image_patch = patch.image * np.expand_dims(patch.roi, axis=-1) patch = CrowdExample(image=roi_image_patch, label=patch.label * patch.roi, roi=patch.roi, map_=patch.map * patch.roi) example = self.resize_patch(patch) return example @staticmethod def select_random_position(example): """ Picks a random position in the full example. :param example: The full example with perspective. :type example: CrowdExample :return: The y and x positions chosen randomly. :rtype: (int, int) """ y = np.random.randint(example.label.shape[0]) x = np.random.randint(example.label.shape[1]) return y, x class RandomlySelectPathWithNoPerspectiveRescale(RandomlySelectPatchAndRescale): """A transformation to randomly select a patch.""" def get_patch_size_for_position(self, example, y, x): """ Always returns the patch size (overriding the super class) :param example: The example to extract the patch from. :type example: ExampleNew :param y: The y position of the center of the patch. :type y: int :param x: The x position of the center of the patch. :type x: int :return: The size of the patch to be extracted. :rtype: int """ return self.patch_size def resize_patch(self, patch): """ Resizes the label and roi of the patch. :param patch: The patch to resize. :type patch: CrowdExample :return: The crowd example that is the resized patch. :rtype: CrowdExample """ original_label_sum = np.sum(patch.label) label = scipy.misc.imresize(patch.label, self.label_scaled_size, mode='F') unnormalized_label_sum = np.sum(label) if unnormalized_label_sum != 0: label = (label / unnormalized_label_sum) * original_label_sum roi = scipy.misc.imresize(patch.roi, self.label_scaled_size, mode='F') > 0.5 map_ = scipy.misc.imresize(patch.map, self.label_scaled_size, mode='F') return CrowdExample(image=patch.image, label=label, roi=roi, map_=map_) class ExtractPatchForPositionNoPerspectiveRescale(PatchAndRescale): """Extracts the patch for a position.""" def __call__(self, example_with_perspective, y, x): original_patch_size = self.get_patch_size_for_position(example_with_perspective, y, x) patch = self.get_patch_for_position(example_with_perspective, y, x) roi_image_patch = patch.image * np.expand_dims(patch.roi, axis=-1) patch = CrowdExample(image=roi_image_patch, label=patch.label * patch.roi, roi=patch.roi, map_=patch.map * patch.roi) example = self.resize_patch(patch) return example, original_patch_size def get_patch_size_for_position(self, example, y, x): """ Always returns the patch size (overriding the super class) :param example: The example to extract the patch from. :type example: ExampleWithPerspective :param y: The y position of the center of the patch. :type y: int :param x: The x position of the center of the patch. :type x: int :return: The size of the patch to be extracted. :rtype: int """ return self.patch_size def resize_patch(self, patch): """ Resizes the label and roi of the patch. :param patch: The patch to resize. :type patch: CrowdExample :return: The crowd example that is the resized patch. :rtype: CrowdExample """ original_label_sum = np.sum(patch.label) label = scipy.misc.imresize(patch.label, self.label_scaled_size, mode='F') unnormalized_label_sum = np.sum(label) if unnormalized_label_sum != 0: label = (label / unnormalized_label_sum) * original_label_sum roi = scipy.misc.imresize(patch.roi, self.label_scaled_size, mode='F') > 0.5 perspective = scipy.misc.imresize(patch.perspective, self.label_scaled_size, mode='F') map_ = scipy.misc.imresize(patch.map, self.label_scaled_size, mode='F') return CrowdExample(image=patch.image, label=label, roi=roi, perspective=perspective, map_=map_) class ExtractPatch: """A transform to extract a patch from an example.""" def __init__(self, image_patch_size=128, label_patch_size=32, allow_padded=False): self.allow_padded = allow_padded self.image_patch_size = image_patch_size self.label_patch_size = label_patch_size def get_patch_for_position(self, example, y, x): """ Extracts a patch for a given position. :param example: The example to extract the patch from. :type example: CrowdExample :param y: The y position of the center of the patch. :type y: int :param x: The x position of the center of the patch. :type x: int :return: The patch. :rtype: CrowdExample """ half_patch_size = int(self.image_patch_size // 2) if self.allow_padded: if y - half_patch_size < 0: example = self.pad_example(example, y_padding=(half_patch_size - y, 0)) y += half_patch_size - y if y + half_patch_size > example.image.shape[0]: example = self.pad_example(example, y_padding=(0, y + half_patch_size - example.image.shape[0])) if x - half_patch_size < 0: example = self.pad_example(example, x_padding=(half_patch_size - x, 0)) x += half_patch_size - x if x + half_patch_size > example.image.shape[1]: example = self.pad_example(example, x_padding=(0, x + half_patch_size - example.image.shape[1])) else: assert half_patch_size <= y <= example.image.shape[0] - half_patch_size assert half_patch_size <= x <= example.image.shape[1] - half_patch_size image_patch = example.image[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size, :] if example.label is not None: label_patch = example.label[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size] else: label_patch = None if example.map is not None: map_patch = example.map[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size] else: map_patch = None if example.perspective is not None: perspective_patch = example.perspective[y - half_patch_size:y + half_patch_size, x - half_patch_size:x + half_patch_size] else: perspective_patch = None return CrowdExample(image=image_patch, label=label_patch, perspective=perspective_patch, map_=map_patch) @staticmethod def pad_example(example, y_padding=(0, 0), x_padding=(0, 0)): """ Pads the given example. :param example: The example to pad. :type example: CrowdExample :param y_padding: The amount to pad the y axis by. :type y_padding: (int, int) :param x_padding: The amount to pad the x axis by. :type x_padding: (int, int) :return: The padded example. :rtype: CrowdExample """ z_padding = (0, 0) image = np.pad(example.image, (y_padding, x_padding, z_padding), 'constant') if example.label is not None: label = np.pad(example.label, (y_padding, x_padding), 'constant') else: label = None if example.perspective is not None: perspective = np.pad(example.perspective, (y_padding, x_padding), 'edge') else: perspective = None if example.map is not None: map_ = np.pad(example.map, (y_padding, x_padding), 'constant') else: map_ = None return CrowdExample(image=image, label=label, perspective=perspective, map_=map_) def resize_label(self, patch): """ Resizes the label of a patch. :param patch: The patch. :type patch: CrowdExample :return: The patch with the resized label. :rtype: CrowdExample """ if self.label_patch_size == self.image_patch_size: return patch label_scaled_size = [self.label_patch_size, self.label_patch_size] if patch.label is not None: original_label_sum = np.sum(patch.label) label = scipy.misc.imresize(patch.label, label_scaled_size, mode='F') unnormalized_label_sum = np.sum(label) if unnormalized_label_sum != 0: label = (label / unnormalized_label_sum) * original_label_sum else: label = None if patch.map is not None: map_ = scipy.misc.imresize(patch.map, label_scaled_size, mode='F') else: map_ = None if patch.perspective is not None: perspective = scipy.misc.imresize(patch.perspective, label_scaled_size, mode='F') else: perspective = None return CrowdExample(image=patch.image, label=label, perspective=perspective, map_=map_) class ExtractPatchForPosition(ExtractPatch): """A transform to extract a patch for a give position.""" def __call__(self, example, y, x): patch = self.get_patch_for_position(example, y, x) example = self.resize_label(patch) return example class ExtractPatchForRandomPosition(ExtractPatch): """A transform to extract a patch for a random position.""" def __call__(self, example): y, x = self.select_random_position(example) patch = self.get_patch_for_position(example, y, x) example = self.resize_label(patch) return example def select_random_position(self, example): """ Selects a random position from the example. :param example: The example. :type example: CrowdExample :return: The patch. :rtype: CrowdExample """ if self.allow_padded: y = np.random.randint(example.label.shape[0]) x = np.random.randint(example.label.shape[1]) else: half_patch_size = int(self.image_patch_size // 2) y = np.random.randint(half_patch_size, example.label.shape[0] - half_patch_size + 1) x = np.random.randint(half_patch_size, example.label.shape[1] - half_patch_size + 1) return y, x class ImageSlidingWindowDataset(Dataset): """ Creates a database for a sliding window extraction of 1 full example (i.e. each of the patches of the full example). """ def __init__(self, full_example, image_patch_size=128, window_step_size=32): self.full_example = CrowdExample(image=full_example.image) # We don't need the label in this case. self.window_step_size = window_step_size self.image_patch_size = image_patch_size half_patch_size = int(self.image_patch_size // 2) self.y_positions = list(range(half_patch_size, self.full_example.image.shape[0] - half_patch_size + 1, self.window_step_size)) if self.full_example.image.shape[0] - half_patch_size > 0: self.y_positions = list(set(self.y_positions + [self.full_example.image.shape[0] - half_patch_size])) self.x_positions = list(range(half_patch_size, self.full_example.image.shape[1] - half_patch_size + 1, self.window_step_size)) if self.full_example.image.shape[1] - half_patch_size > 0: self.x_positions = list(set(self.x_positions + [self.full_example.image.shape[1] - half_patch_size])) self.positions_shape = np.array([len(self.y_positions), len(self.x_positions)]) self.length = self.positions_shape.prod() def __getitem__(self, index): """ :param index: The index within the entire dataset (the specific patch of the image). :type index: int :return: An example and label from the crowd dataset. :rtype: torch.Tensor, torch.Tensor """ extract_patch_transform = ExtractPatchForPosition(self.image_patch_size, allow_padded=True) # In case image is smaller than patch. test_transform = torchvision.transforms.Compose([NegativeOneToOneNormalizeImage(), NumpyArraysToTorchTensors()]) y_index, x_index = np.unravel_index(index, self.positions_shape) y = self.y_positions[y_index] x = self.x_positions[x_index] patch = extract_patch_transform(self.full_example, y, x) example = test_transform(patch) return example.image, x, y def __len__(self): return self.length
true
f522acceeab1f4d028b11264911aee2d1b3546d3
Python
arunkumar27-ank-tech/Hackerrank_PYTHON
/7.Collections/Solutions/piling-up.py
UTF-8
317
3.25
3
[]
no_license
for _ in range(int(input())): n,lst =int(input()), list(map(int,input().split())) if (sorted(lst)[-1]==lst[0]) or (sorted(lst)[-1]==lst[-1]): print("Yes") else: print("No") #lst1 = [2,3,4,5] ##lst2=[4,5,2,3] #if (lst1==sorted(lst2)): # print("yes") #else: # print("No")
true
21aeda5dfa80066fc2c64587bf67d8e840834367
Python
Time1996/python
/pythonPractice/44classwithobject.py
UTF-8
64
3.03125
3
[]
no_license
s = 'How are you?' l = s.split() dir(s) dir(l) print(s) print(l)
true
3d9d3f0f221dc1103b95192b8a65a4aace2bf652
Python
cges60809/DenseNet
/data_providers/Mnist.py
UTF-8
7,032
2.703125
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 3 16:45:13 2018 @author: islab """ import tempfile import os import pickle import random from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets from .base_provider import ImagesDataSet, DataProvider import numpy as np class selfDataSet(ImagesDataSet): def __init__(self, images, labels, n_classes, shuffle, normalization, augmentation): """ Args: images: 4D numpy array labels: 2D or 1D numpy array n_classes: `int`, number of cifar classes - 10 or 100 shuffle: `str` or None None: no any shuffling once_prior_train: shuffle train data only once prior train every_epoch: shuffle train data prior every epoch normalization: `str` or None None: no any normalization divide_255: divide all pixels by 255 divide_256: divide all pixels by 256 by_chanels: substract mean of every chanel and divide each chanel data by it's standart deviation augmentation: `bool` """ if shuffle is None: self.shuffle_every_epoch = False elif shuffle == 'once_prior_train': self.shuffle_every_epoch = False images, labels = self.shuffle_images_and_labels(images, labels) elif shuffle == 'every_epoch': self.shuffle_every_epoch = True else: raise Exception("Unknown type of shuffling") self.images = images self.labels = labels self.n_classes = n_classes self.augmentation = augmentation self.normalization = normalization self.images = self.normalize_images(images, self.normalization) self.start_new_epoch() def start_new_epoch(self): self._batch_counter = 0 if self.shuffle_every_epoch: images, labels = self.shuffle_images_and_labels( self.images, self.labels) else: images, labels = self.images, self.labels self.epoch_images = images self.epoch_labels = labels @property def num_examples(self): return self.labels.shape[0] def next_batch(self, batch_size): start = self._batch_counter * batch_size end = (self._batch_counter + 1) * batch_size self._batch_counter += 1 images_slice = self.epoch_images[start: end] labels_slice = self.epoch_labels[start: end] if images_slice.shape[0] != batch_size: self.start_new_epoch() return self.next_batch(batch_size) else: return images_slice, labels_slice class MNISTINDataProvider(DataProvider): """Abstract class for cifar readers""" def __init__(self, save_path=None, validation_set=None, validation_split=None, shuffle=None, normalization=None, one_hot=True, **kwargs): """ Args: save_path: `str` validation_set: `bool`. validation_split: `float` or None float: chunk of `train set` will be marked as `validation set`. None: if 'validation set' == True, `validation set` will be copy of `test set` shuffle: `str` or None None: no any shuffling once_prior_train: shuffle train data only once prior train every_epoch: shuffle train data prior every epoch normalization: `str` or None None: no any normalization divide_255: divide all pixels by 255 divide_256: divide all pixels by 256 by_chanels: substract mean of every chanel and divide each chanel data by it's standart deviation one_hot: `bool`, return lasels one hot encoded """ self._save_path = save_path self.one_hot = one_hot # add train and validations and test datasets data_dir = 'temp' mnist = read_data_sets(data_dir) trainimage = np.array([np.reshape(x, (28,28,1)) for x in mnist.train.images]) validationimage = np.array([np.reshape(x, (28,28,1)) for x in mnist.validation.images]) testimage = np.array([np.reshape(x, (28,28,1)) for x in mnist.test.images]) train_labels = mnist.train.labels validation_labels = mnist.validation.labels test_labels = mnist.test.labels #images, labels = self.read_cifar(train_fnames) if validation_set is not None: self.train = selfDataSet( images=trainimage, labels=self.label_convert(train_labels), n_classes=self.n_classes, shuffle=shuffle, normalization=normalization, augmentation=self.data_augmentation) self.validation = selfDataSet( images=validationimage, labels=self.label_convert(validation_labels), n_classes=self.n_classes, shuffle=shuffle, normalization=normalization, augmentation=self.data_augmentation) else: self.train = selfDataSet( images=trainimage, labels=self.label_convert(train_labels), n_classes=self.n_classes, shuffle=shuffle, normalization=normalization, augmentation=self.data_augmentation) # add test set self.test = selfDataSet( images=testimage, labels=self.label_convert(test_labels), shuffle=None, n_classes=self.n_classes, normalization=normalization, augmentation=False) if validation_set and not validation_split: self.validation = self.test @property def save_path(self): if self._save_path is None: self._save_path = os.path.join( tempfile.gettempdir(), 'Mnist%d' % self.n_classes) return self._save_path @property def data_shape(self): return (28, 28, 1) @property def n_classes(self): return self._n_classes def get_filenames(self, save_path): """Return two lists of train and test filenames for dataset""" raise NotImplementedError def label_convert(self, mnistlabel): label = np.zeros([mnistlabel.size,10]) for i in range(mnistlabel.size): label[i,mnistlabel[i]] = 1 return label class MNISTDataProvider(MNISTINDataProvider): _n_classes = 10 data_augmentation = False def get_filenames(self, save_path): sub_save_path = os.path.join(save_path, 'cifar-10-batches-py') train_filenames = [ os.path.join( sub_save_path, 'data_batch_%d' % i) for i in range(1, 6)] test_filenames = [os.path.join(sub_save_path, 'test_batch')] return train_filenames, test_filenames
true
588c5566784db04820cd9ee8b341dda9f1b47a9f
Python
tkhamvilai/SAFRAN_demo
/full_demo/execute_another_script.py
UTF-8
875
3.109375
3
[]
no_license
import RPi.GPIO as GPIO import subprocess import _thread import time GPIO.setmode(GPIO.BOARD) switch_button = 40 GPIO.setup(switch_button, GPIO.IN, pull_up_down = GPIO.PUD_UP) input_state = GPIO.input(switch_button) # Define a function for the thread def call_func(threadName, func_name): subprocess.call(['python', func_name]) def read_switch(threadName): while True: global input_state input_state = GPIO.input(switch_button) # Create two threads as follows try: _thread.start_new_thread( call_func, ("Thread-1", 'RGB_GPIO.py', ) ) _thread.start_new_thread( read_switch, ("Thread-2", ) ) except: print ("Error: unable to start thread") while True: if input_state == False: print('Button not Pressed') time.sleep(0.2) elif input_state == True: print('Button Pressed') time.sleep(0.2)
true
d673256a160cb1669e20887ff92b5cd288b22d04
Python
hugolu/learn-python
/programming-in-python/ch4.py
UTF-8
174
3.953125
4
[]
no_license
#!/usr/bin/env python # Chapter 4 - Control and Function # conditional branching num = 10 if num % 2 == 0: "{0} is even".format(num) else: "{0} is odd".format(num)
true
ccba07a20be0c997037223b01ae6972ec934823e
Python
linyuxuanlin/3D-print-library
/arduino有关/plen2机器人文件/PLEN2-master/arduino/sdk/UnitRunner/UnitRunner.py
UTF-8
1,300
2.515625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- import json, locale from datetime import datetime from argparse import ArgumentParser # Set global settings. # ============================================================================== locale.setlocale(locale.LC_ALL, 'jpn') # Application entry point. # ============================================================================== def main(args): with open('status.json', 'w') as fout: today = datetime.today() today_str = '%04d/%02d/%02d' % (today.year, today.month, today.day) status = {} status['test'] = { 'status': args.test, 'last': today_str if args.test else None } status['build'] = { 'status': args.build, 'last': today_str if args.build else None } json.dump(status, fout, sort_keys = True, indent = 4) # Purse command-line option(s). # ============================================================================== if __name__ == '__main__': arg_parser = ArgumentParser() arg_parser.add_argument( '-b', '--build', action = 'store_true', dest = 'build', default = False, help = 'Set to build "True".' ) arg_parser.add_argument( '-t', '--test', action = 'store_true', dest = 'test', default = False, help = 'Set to test "True".' ) args = arg_parser.parse_args() main(args)
true
0f0d48c3c9c6a973252b6be68d96c27cd4661d1a
Python
ctfer-Stao/ctf-sql
/sql.py
UTF-8
1,523
2.78125
3
[]
no_license
#python3 #by stao import requests import threading words=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`'] url='http://127.0.0.1/1.php?name=' result="________________________________________________________________________________________________" #replace function def replace_char(string,char,index): string = list(string) string[index] = char return ''.join(string) #to get result def brute_result(n,m): global result for i in range(n,m): for j in words: payload="1' or ascii(substr((select flag from flag),"+str(i)+",1))="+str(ord(j))+"--+" #print(payload) url1=url+payload r=requests.get(url=url1) if "stao" in r.text: print(j) result=replace_char(result,j,i-1) print(result) if __name__ == "__main__": length=60 #the length of result number=15 #the number of threads num=int(length/number) if(length % number ==0) else int(length/number)+1 #each threads's number #print(num) for i in range(0,number): print("thread_"+str(i+1)+"start.....") threading.Thread(target=brute_result, args=(i*num, (i+1)*num, )).start() #create and start thread
true
3784f826718395d355eaf9ba708a92eac132ca10
Python
juarezpaulino/coderemite
/problemsets/Codeforces/Python/A88.py
UTF-8
336
2.90625
3
[ "Apache-2.0" ]
permissive
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ c=['C','C#','D','D#','E','F','F#','G','G#','A','B','H'] x,y,z=sorted(map(c.index,input().split())) for _ in' '*3: a,b=(y+12-x)%12,(z+12-y)%12 if [a,b]==[4,3]: print('major') exit() if [a,b]==[3,4]: print('minor') exit() x,y,z=y,z,x print('strange')
true
b8420a1ff5d5b7a3652be08be3112da53f4e8003
Python
iamanobject/Lv-568.2.PythonCore
/HW_4/havrylyakyulia/Home_Work4_Task_3.py
UTF-8
286
3.796875
4
[]
no_license
num = int(input("Number:")) num_1 = 0 num_2 = 1 if num < 2: print("Not bad") else: print(num_1, end=' ') print(num_2, end=' ') for i in range(2, num): new_num = num_1 + num_2 num_1 = num_2 num_2 = new_num print(new_num, end=' ')
true
a1c10b1267e73049a941eed8e3db8911b40b14ff
Python
Svdvoort/PREDICT
/ImageFeatures/texture_features.py
UTF-8
2,048
2.609375
3
[ "Apache-2.0" ]
permissive
import numpy as np from skimage.feature import local_binary_pattern import pandas as pd import scipy.stats def get_LBP_features(image, mask, radius, N_points, method): feature_names = ['LBP_mean', 'LBP_std', 'LBP_median', 'LBP_kurtosis', 'LBP_skew', 'LBP_peak'] full_features = np.zeros([len(radius) * len(feature_names), 1]) full_feature_labels = list() mask = mask.flatten() for i_index, (i_radius, i_N_points) in enumerate(zip(radius, N_points)): LBP_image = np.zeros(image.shape) for i_slice in range(0, image.shape[2]): LBP_image[:, :, i_slice] = local_binary_pattern(image[:, :, i_slice], P=i_N_points, R=i_radius, method=method) LBP_image = LBP_image.flatten() LBP_tumor = LBP_image[mask] mean_val = np.mean(LBP_tumor) std_val = np.std(LBP_tumor) median_val = np.median(LBP_tumor) kurtosis_val = scipy.stats.kurtosis(LBP_tumor) skew_val = scipy.stats.skew(LBP_tumor) peak_val = np.bincount(LBP_tumor.astype(np.int))[1:-2].argmax() features = [mean_val, std_val, median_val, kurtosis_val, skew_val, peak_val] full_feature_start = i_index * len(feature_names) full_feature_end = (i_index + 1) * len(feature_names) full_features[full_feature_start:full_feature_end, 0] = np.asarray(features).ravel() cur_feature_names = [feature_name + '_R' + str(i_radius) + '_P' + str(i_N_points) for feature_name in feature_names] full_feature_labels.extend(cur_feature_names) features = dict(zip(full_feature_labels, full_features)) return features def get_texture_features(image, mask, texture_settings): LBP_features = get_LBP_features(image, mask, texture_settings['LBP']['radius'], texture_settings['LBP']['N_points'], texture_settings['LBP']['method']) texture_features = LBP_features texture_features = pd.Series(texture_features) return texture_features
true
f8d6cfa3c6399184b5cf3438b60a2b2068a656e7
Python
manishmcu/Google-Assistant-with-RaspberryPi
/pi_iot.py
UTF-8
2,063
2.734375
3
[]
no_license
import random import sys import time from Adafruit_IO import MQTTClient import requests ADAFRUIT_IO_KEY = 'aio_cEQk60uNwKank8nAXtPXP1Ps5LJ0' # Set to your Adafruit IO key. ADAFRUIT_IO_USERNAME = 'Debanik2000' # See https://accounts.adafruit.com # to find your username. # Set the URL of the physical dashboard to use. If running on the same Pi as # the dashboard server then keep this the default localhost:5000 value. If # modified make sure not to end in a slash! #DASHBOARD_URL = 'http://localhost:5000' # URL of the physical dashboard. # Don't end with a slash! # Define callback functions which will be called when certain events happen. def connected(client): print('Connected to Adafruit IO! Listening for feed') client.subscribe('Relay 1') client.subscribe('Relay 2') def disconnected(client): print('Disconnected from Adafruit IO!') sys.exit(1) def message(client, feed_id, status): print('Feed {0} received new value: {1}'.format(feed_id, status)) if feed_id == 'Relay 1': if status == "1": print("Bed light ON") else: print("Bed light OFF") if feed_id == 'Relay 2': if status == "1": print("Light ON") else: print("Light OFF") # requests.post('{0}/widgets/slider'.format(DASHBOARD_URL), data={'value': payload}) #elif feed_id == 'pi-dashboard-humidity': #requests.post('{0}/widgets/humidity'.format(DASHBOARD_URL), data={'value': payload}) # elif feed_id == 'pi-dashboard-temp': # requests.post('{0}/widgets/temp'.format(DASHBOARD_URL), data={'value': payload}) # Create an MQTT client instance. client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) # Setup the callback functions defined above. client.on_connect = connected client.on_disconnect = disconnected client.on_message = message client.connect() client.loop_blocking()
true
90e8887f0ecb7ae621b1c250fa99d2b98d1fdb71
Python
RickvBork/Programming-Project
/data_gen/gen_winners.py
UTF-8
1,324
3.125
3
[ "MIT", "BSD-3-Clause" ]
permissive
''' Make GET request for data ''' # Creates data used for the DataMaps Choropleth # import library import helpers as hlp import json from collections import Counter as count import os def gen_winners(): # move back one directory os.chdir("../data") test = [] winners = {} i = 0 # loop over seasons for season in range(1950, 2018): i += 1 print(i) season = str(season) # get json data for winning constructors and drivers URL = 'http://ergast.com/api/f1/' + season + '/results/1.json' races = hlp.get_data(URL)['RaceTable']['Races'] constructors = [] constructor_wins = [] winners[season] = [] # loop over races and append all constructors to list for race in races: constructor = race['Results'][0]['Constructor']['name'] # check if constructor has won already if constructor not in constructors: constructors.append(constructor) if constructor not in test: test.append(constructor) constructor_wins.append(constructor) for constructor in constructors: win_dict = {} win_dict['label'] = constructor win_dict['value'] = constructor_wins.count(constructor) winners[season].append(win_dict) # 44 unique winners as of 2017 with open('winners.json', 'w') as outfile: json.dump(winners, outfile) if __name__ == "__main__": gen_winners()
true
f1aa148e72dee24353aeaead19908d619721e60d
Python
BUCT-CS1808-SoftwareEngineering/MusemData_Collection_System
/museum/spiders/education60.py
UTF-8
975
2.515625
3
[]
no_license
import scrapy from museum.items import educationItem import json class Education60Spider(scrapy.Spider): name = 'education60' start_urls = [ "http://www.gzsmzmuseum.cn/list-19.html" ] def parse_content(self, response): educationName = response.xpath("//h2/text()").get() educationDescription = "".join("".join(response.xpath( "//div[@class='detail_text']//span/text()").getall()).split()) educationImageUrl = "http://www.gzsmzmuseum.cn/" + \ response.xpath( "//div[@class='detail_text']//img/@src").get().replace('../../../', '') print((educationName, educationImageUrl, educationDescription)) def parse(self, response): item = educationItem() item_list = response.xpath("//ul[@class='newsli']//a/@href").getall() for index, i in enumerate(item_list): yield scrapy.Request("http://www.gzsmzmuseum.cn/"+i, callback=self.parse_content)
true
ec31cf76940e93668843d6553d65a6e2e80b1d66
Python
rocketbot-cl/MongoDB
/__init__.py
UTF-8
4,498
2.640625
3
[ "MIT" ]
permissive
# coding: utf-8 """ Base para desarrollo de modulos externos. Para obtener el modulo/Funcion que se esta llamando: GetParams("module") Para obtener las variables enviadas desde formulario/comando Rocketbot: var = GetParams(variable) Las "variable" se define en forms del archivo package.json Para modificar la variable de Rocketbot: SetVar(Variable_Rocketbot, "dato") Para obtener una variable de Rocketbot: var = GetVar(Variable_Rocketbot) Para obtener la Opcion seleccionada: opcion = GetParams("option") Para instalar librerias se debe ingresar por terminal a la carpeta "libs" pip install <package> -t . """ base_path = tmp_global_obj["basepath"] cur_path = base_path + 'modules' + os.sep + 'MongoDB' + os.sep + 'libs' + os.sep sys.path.append(cur_path) from pymongo import MongoClient import pymongo from bson import ObjectId """ Obtengo el modulo que fueron invocados """ module = GetParams("module") global client if module == "connect": url = GetParams('url') client = MongoClient(url) if module == "getDatabases": result = GetParams("result") try: database_names = client.database_names() SetVar(result, database_names) except Exception as e: print("\x1B[" + "31;40mError\u2193\x1B[" + "0m") PrintException() raise e if module == "getCollections": database = GetParams("db") result = GetParams("result") try: collections = client[database].list_collection_names() SetVar(result, collections) except Exception as e: print("\x1B[" + "31;40mError\u2193\x1B[" + "0m") PrintException() raise e if module == "getDocuments": database = GetParams("db") collection = GetParams("collection") result = GetParams("result") try: collection = client[database][collection] documents = [] for document in collection.find(): doc = {key: str(value) for key, value in document.items()} documents.append(doc) SetVar(result, documents) except Exception as e: print("\x1B[" + "31;40mAn error occurred\u2193\x1B[" + "0m") PrintException() raise e if module == "createCollection": database = GetParams("db") collection = GetParams("collection") try: client[database].create_collection(collection) except Exception as e: print("\x1B[" + "31;40mError\u2193\x1B[" + "0m") PrintException() raise e if module == "createDocument": database = GetParams("db") collection = GetParams("collection") doc = GetParams("doc") result = GetParams("result") try: doc = eval(doc) doc_id = client[database][collection].insert_one(doc).inserted_id SetVar(result, doc_id) except Exception as e: print("\x1B[" + "31;40mError\u2193\x1B[" + "0m") PrintException() raise e if module == "findById": database = GetParams("db") collection = GetParams("collection") id_ = GetParams("id") result = GetParams("result") try: collection = client[database][collection] doc = collection.find_one({"_id": ObjectId(id_)}) doc = dict(doc.items()) SetVar(result, doc) except Exception as e: print("\x1B[" + "31;40mError\u2193\x1B[" + "0m") PrintException() raise e if module == "find": database = GetParams("db") collection = GetParams("collection") dic = GetParams("dict") result = GetParams("result") try: dic = eval(dic) collection = client[database][collection] docs = collection.find(dic) documents = [dict(doc.items()) for doc in docs] SetVar(result, documents) except Exception as e: print("\x1B[" + "31;40mError\u2193\x1B[" + "0m") PrintException() raise e if module == "findAndReplace": database = GetParams("db") collection = GetParams("collection") id_ = GetParams("id") new_document = GetParams("new") result = GetParams("result") try: collection = client[database][collection] new_document = eval(new_document) doc = collection.find_one_and_update({"_id": ObjectId(id_)}, {'$set': new_document}) response = True if doc else False SetVar(result, response) except Exception as e: print("\x1B[" + "31;40mError\u2193\x1B[" + "0m") PrintException() raise e
true
f6466b2813316bf0b376657cf861d77488e13e75
Python
Raniac/NEURO-LEARN
/env/lib/python3.6/site-packages/nibabel/tests/test_batteryrunners.py
UTF-8
6,176
2.671875
3
[ "Apache-2.0" ]
permissive
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Tests for BatteryRunner and Report objects ''' from six import StringIO import logging from ..batteryrunners import BatteryRunner, Report from ..testing import (assert_true, assert_false, assert_equal, assert_not_equal, assert_raises) # define some trivial functions as checks def chk1(obj, fix=False): rep = Report(KeyError) if 'testkey' in obj: return obj, rep rep.problem_level = 20 rep.problem_msg = 'no "testkey"' if fix: obj['testkey'] = 1 rep.fix_msg = 'added "testkey"' return obj, rep def chk2(obj, fix=False): # Can return different codes for different errors in same check rep = Report() try: ok = obj['testkey'] == 0 except KeyError: rep.problem_level = 20 rep.problem_msg = 'no "testkey"' rep.error = KeyError if fix: obj['testkey'] = 1 rep.fix_msg = 'added "testkey"' return obj, rep if ok: return obj, rep rep.problem_level = 10 rep.problem_msg = '"testkey" != 0' rep.error = ValueError if fix: rep.fix_msg = 'set "testkey" to 0' obj['testkey'] = 0 return obj, rep def chk_warn(obj, fix=False): rep = Report(KeyError) if not 'anotherkey' in obj: rep.problem_level = 30 rep.problem_msg = 'no "anotherkey"' if fix: obj['anotherkey'] = 'a string' rep.fix_msg = 'added "anotherkey"' return obj, rep def chk_error(obj, fix=False): rep = Report(KeyError) if not 'thirdkey' in obj: rep.problem_level = 40 rep.problem_msg = 'no "thirdkey"' if fix: obj['anotherkey'] = 'a string' rep.fix_msg = 'added "anotherkey"' return obj, rep def test_init_basic(): # With no args, raise assert_raises(TypeError, BatteryRunner) # Len returns number of checks battrun = BatteryRunner((chk1,)) assert_equal(len(battrun), 1) battrun = BatteryRunner((chk1, chk2)) assert_equal(len(battrun), 2) def test_init_report(): rep = Report() assert_equal(rep, Report(Exception, 0, '', '')) def test_report_strings(): rep = Report() assert_not_equal(rep.__str__(), '') assert_equal(rep.message, '') str_io = StringIO() rep.write_raise(str_io) assert_equal(str_io.getvalue(), '') rep = Report(ValueError, 20, 'msg', 'fix') rep.write_raise(str_io) assert_equal(str_io.getvalue(), '') rep.problem_level = 30 rep.write_raise(str_io) assert_equal(str_io.getvalue(), 'Level 30: msg; fix\n') str_io.truncate(0) str_io.seek(0) # No fix string, no fix message rep.fix_msg = '' rep.write_raise(str_io) assert_equal(str_io.getvalue(), 'Level 30: msg\n') rep.fix_msg = 'fix' str_io.truncate(0) str_io.seek(0) # If we drop the level, nothing goes to the log rep.problem_level = 20 rep.write_raise(str_io) assert_equal(str_io.getvalue(), '') # Unless we set the default log level in the call rep.write_raise(str_io, log_level=20) assert_equal(str_io.getvalue(), 'Level 20: msg; fix\n') str_io.truncate(0) str_io.seek(0) # If we set the error level down this low, we raise an error assert_raises(ValueError, rep.write_raise, str_io, 20) # But the log level wasn't low enough to do a log entry assert_equal(str_io.getvalue(), '') # Error still raised with lower log threshold, but now we do get a # log entry assert_raises(ValueError, rep.write_raise, str_io, 20, 20) assert_equal(str_io.getvalue(), 'Level 20: msg; fix\n') # If there's no error, we can't raise str_io.truncate(0) str_io.seek(0) rep.error = None rep.write_raise(str_io, 20) assert_equal(str_io.getvalue(), '') def test_logging(): rep = Report(ValueError, 20, 'msg', 'fix') str_io = StringIO() logger = logging.getLogger('test.logger') logger.setLevel(30) # defaultish level logger.addHandler(logging.StreamHandler(str_io)) rep.log_raise(logger) assert_equal(str_io.getvalue(), '') rep.problem_level = 30 rep.log_raise(logger) assert_equal(str_io.getvalue(), 'msg; fix\n') str_io.truncate(0) str_io.seek(0) def test_checks(): battrun = BatteryRunner((chk1,)) reports = battrun.check_only({}) assert_equal(reports[0], Report(KeyError, 20, 'no "testkey"', '')) obj, reports = battrun.check_fix({}) assert_equal(reports[0], Report(KeyError, 20, 'no "testkey"', 'added "testkey"')) assert_equal(obj, {'testkey': 1}) battrun = BatteryRunner((chk1, chk2)) reports = battrun.check_only({}) assert_equal(reports[0], Report(KeyError, 20, 'no "testkey"', '')) assert_equal(reports[1], Report(KeyError, 20, 'no "testkey"', '')) obj, reports = battrun.check_fix({}) # In the case of fix, the previous fix exposes a different error # Note, because obj is mutable, first and second point to modified # (and final) dictionary output_obj = {'testkey': 0} assert_equal(reports[0], Report(KeyError, 20, 'no "testkey"', 'added "testkey"')) assert_equal(reports[1], Report(ValueError, 10, '"testkey" != 0', 'set "testkey" to 0')) assert_equal(obj, output_obj)
true
f4089e53731a291ab14eecb8d17a320ba1600e33
Python
lexweg7/REU2020
/22Mg(alpha, proton)/dataprep.py
UTF-8
1,750
3.09375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[ ]: ''' This function produces voxel-grid downsampled 128x128 xy projections for 22Mg data ''' def downsample('my-file.h5','r'): #Read in h5 file in which each event is an individual key events = [] for i in hf.keys(): events.append(hf[i]) #Dimensions of AT-TPC detector DETECTOR_LENGTH = 1000.0 DETECTOR_RADIUS = 275.0 #Number of divisions along each dimension in the detector x_disc = 128 y_disc = 128 z_disc = 128 #z incriments z_inc = DETECTOR_LENGTH/z_disc #Make array for new data new_data = [] for i in range(len(events)): new_events = np.zeros(128*128*128) num_pts = 0 for point in events[i]: #Add up points in each bucket x_bucket = math.floor(((point[0]+DETECTOR_RADIUS)/(2*DETECTOR_RADIUS))*x_disc) y_bucket = math.floor(((point[1]+DETECTOR_RADIUS)/(2*DETECTOR_RADIUS))*y_disc) z_bucket = math.floor((point[2]/DETECTOR_LENGTH)*z_disc) #Determine ID of each bucket bucket_num = z_bucket*x_disc*y_disc + x_bucket + y_bucket*x_disc #Average z value within buckets avg_z = ((2*z_bucket+1)*z_inc)/2.0 #Associate the average z value with each bucket new_events[bucket_num] = avg_z num_pts += 1 #Reshape to be 128x128x128 matrix E = new_events.reshape((128,128,128)) #Flatten to be xy only E_2d = np.sum(E,axis=0) #Add to new dataset new_data.append(E_2d) #New dataset to numpy array new_data=np.array(new_data) return new_data
true
606246c85062d72cccde7e048a9fc8819e02e14e
Python
Vall-1996/bh_mass
/integrate.py
UTF-8
1,790
2.84375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 19 13:03:15 2020 @author: val """ import math import numpy as np def integral(k,u,o,a,b): t1=k*(np.sqrt(2.*np.pi)/2.)*o t2=math.erf((np.sqrt(2.)/2.)*(u-a)/o) t3=math.erf((np.sqrt(2.)/2.)*(u-b)/o) return t1*(t2-t3) #1E-17 erg/s/cm^2/Ang def distance(z): H0,WM,WV=71.0,0.27,0.75 h = H0/100. WR = 4.165E-5/(h*h) WK = 1-WM-WR-WV az = 1.0/(1+1.0*z) n=1000 DTT = 0.0 DCMR = 0.0 for i in range(n): a = az+(1-az)*(i+0.5)/n adot = np.sqrt(WK+(WM/a)+(WR/(a*a))+(WV*a*a)) DTT = DTT + 1./adot DCMR = DCMR + 1./(a*adot) DCMR = (1.-az)*DCMR/n ratio = 1.00 x = np.sqrt(np.abs(WK))*DCMR if x > 0.1: if WK > 0: ratio = 0.5*(np.exp(x)-np.exp(-x))/x else: ratio = np.sin(x)/x else: y = x*x if WK < 0: y = -y ratio = 1. + y/6. + y*y/120. DCMT = ratio*DCMR DA = az*DCMT DL = DA/(az*az) DL_Mpc = (299792.458/H0)*DL return DL_Mpc*3.08568e24 #cm def luminosity(z,k,u,o,a,b): DL=distance(z) I = integral(k,u,o,a,b) return 4*np.pi*(DL**2)*I #1E-17 erg/s def FWHM(u,o): return 2*2.99792458e5*(o/u) #km/s def log_mass_ratio(z,k,u,o,a,b,line): F = FWHM(u,o) L = luminosity(z,k,u,o,a,b) if line == "HA": k1=-32.33 k2=0.55 k3=2.06 elif line == "HB": k1=-32.48 k2=0.56 k3=2.0 else: print("Emission line not supported.") print("Supported lines: HA, HB") return None return k1+k2*np.log10(L)+k3*np.log10(F) #unitless z=0.198 k,u,o=6.2,6562.8,46.7 a,b=6425.0,6725.0 print(log_mass_ratio(z,k,u,o,a,b,"HA"))
true
0a618939ce0ccf03f208adcc66572d615f58c832
Python
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 10/R/R-10.7.py
UTF-8
404
2.53125
3
[]
no_license
#-*-coding: utf-8 -*- """ Our Position classes for lists and trees support the__eq__method so that two distinct position instances are considered equivalent if they refer to the same underlying node in a structure. For positions to be allowed as keys in a hash table, there must be a definition for the__hash__method that is consistent with this notion of equivalence. Provide such a__hash__ method. """
true
22f7d2bb7ea0c2eb805961562a2770340c1b31e1
Python
markosolopenko/python
/advent_of_code_2015/day_16/aunt_sue.py
UTF-8
2,485
3.109375
3
[]
no_license
import re unknown_aunt = {'children': '3', 'cats': '7', 'samoyeds': '2', 'pomeranians': '3', 'akitas': '0', 'vizslas': '0', 'goldfish': '5', 'trees': '3', 'cars': '2', 'perfumes': '1'} def parse_file(): file = open('day16.txt').read().split('\n') aunts = {} aunts_info = {} num = 1 for line in file: line = re.findall('[a-z]+: [0-9]+', line) aunts[str(num)] = aunts_info for i in line: i = i.split(': ') aunts_info[i[0]] = i[-1] num += 1 aunts_info = {} return aunts def add_full_info(): global unknown_aunt aunts_info = parse_file() for info in aunts_info: for key, value in unknown_aunt.items(): if key not in aunts_info[info]: aunts_info[info][key] = value return aunts_info def puzzle1(): nearest = {} count = 0 full_info = add_full_info() for info in full_info: for key, value in unknown_aunt.items(): if unknown_aunt[key] == full_info[info][key]: count += 1 nearest[info] = count count = 0 max_key = '' max_value = max(nearest.values()) for i in nearest: if nearest[i] == max_value: max_key = i break print(f'Puzzle1: {max_key}') def puzzle2(): nearest = {} count = 0 not_allowed = ['cats', 'pomeranians', 'trees', 'goldfish'] full_info = parse_file() for info in full_info: for key, value in unknown_aunt.items(): if key == 'cats' and key in full_info[info] and int(full_info[info][key]) > int(value): count += 1 elif key == 'trees' and key in full_info[info] and int(full_info[info][key]) > int(value): count += 1 elif key == 'pomeranians' and key in full_info[info] and int(full_info[info][key]) < int(value): count += 1 elif key == 'goldfish' and key in full_info[info] and int(full_info[info][key]) < int(value): count += 1 elif key not in not_allowed and key in full_info[info] and value == full_info[info][key]: count += 1 nearest[info] = count count = 0 max_key = '' max_value = max(nearest.values()) for i in nearest: if nearest[i] == max_value: max_key = i break print(f'Puzzle2: {max_key}') if __name__ == '__main__': puzzle1() puzzle2()
true
0aa3122d46d6638d334e379aaf4ce980a3dd617f
Python
yoganbye/Kirill-homework
/Part_1/Lesson_8/hw8_loto.py
UTF-8
7,271
3.703125
4
[]
no_license
#!/usr/bin/python3 # == Лото == # Правила игры в лото. # Игра ведется с помощью специальных карточек, на которых отмечены числа, # и фишек (бочонков) с цифрами. # Количество бочонков — 90 штук (с цифрами от 1 до 90). # Каждая карточка содержит 3 строки по 9 клеток. В каждой строке по 5 случайных цифр, # расположенных по возрастанию. Все цифры в карточке уникальны. Пример карточки: # -------------------------- # 9 43 62 74 90 # 2 27 75 78 82 # 41 56 63 76 86 # -------------------------- # В игре 2 игрока: пользователь и компьютер. Каждому в начале выдается # случайная карточка. # Каждый ход выбирается один случайный бочонок и выводится на экран. # Также выводятся карточка игрока и карточка компьютера. # Пользователю предлагается зачеркнуть цифру на карточке или продолжить. # Если игрок выбрал "зачеркнуть": # Если цифра есть на карточке - она зачеркивается и игра продолжается. # Если цифры на карточке нет - игрок проигрывает и игра завершается. # Если игрок выбрал "продолжить": # Если цифра есть на карточке - игрок проигрывает и игра завершается. # Если цифры на карточке нет - игра продолжается. # Побеждает тот, кто первый закроет все числа на своей карточке. # Пример одного хода: # Новый бочонок: 70 (осталось 76) # ------ Ваша карточка ----- # 6 7 49 57 58 # 14 26 - 78 85 # 23 33 38 48 71 # -------------------------- # -- Карточка компьютера --- # 7 11 - 14 87 # 16 49 55 77 88 # 15 20 - 76 - # -------------------------- # Зачеркнуть цифру? (y/n) # Подсказка: каждый следующий случайный бочонок из мешка удобно получать # с помощью функции-генератора. # Подсказка: для работы с псевдослучайными числами удобно использовать # модуль random: http://docs.python.org/3/library/random.html from random import randint def generate_unique_numbers(count, minbound, maxbound): if count > maxbound - minbound + 1: raise ValueError('Не верный параметр') ret = [] while len(ret) < count: new = randint(minbound, maxbound) if new not in ret: ret.append(new) return ret class Keg: __num = None def __init__(self): self.__num = randint(1, 90) @property def num(self): return self.__num def __str__(self): return str(self.__num) class Card: __rows = 3 __cols = 9 __nums_in_row = 5 __data = None __emptynum = 0 __crossednum = -1 def __init__(self): uniques_count = self.__nums_in_row * self.__rows uniques = generate_unique_numbers(uniques_count, 1, 90) self.__data = [] for i in range(0, self.__rows): tmp = sorted(uniques[self.__nums_in_row * i: self.__nums_in_row * (i + 1)]) empty_nums_count = self.__cols - self.__nums_in_row for j in range(0, empty_nums_count): index = randint(0, len(tmp)) tmp.insert(index, self.__emptynum) self.__data += tmp def __str__(self): delimiter = '--------------------------' ret = delimiter + '\n' for index, num in enumerate(self.__data): if num == self.__emptynum: ret += ' ' elif num == self.__crossednum: ret += ' -' elif num < 10: ret += f' {str(num)}' else: ret += str(num) if (index + 1) % self.__cols == 0: ret += '\n' else: ret += ' ' return ret + delimiter def __contains__(self, item): return item in self.__data def cross_num(self, num): for index, item in enumerate(self.__data): if item == num: self.__data[index] = self.__crossednum return raise ValueError(f'Номер карты: {num}') def closed(self) -> bool: return set(self.__data) == {self.__emptynum, self.__crossednum} class Game: __usercard = None __compcard = None __numkegs = 90 __kegs = [] __gameover = False def __init__(self): self.__usercard = Card() self.__compcard = Card() self.__kegs = generate_unique_numbers(self.__numkegs, 1, 90) def play_round(self) -> int: keg = self.__kegs.pop() print(f'Новый бочонок: {keg} (осталось {len(self.__kegs)})') print(f'----- Ваша карточка ------\n{self.__usercard}') print(f'-- Карточка компьютера ---\n{self.__compcard}') useranswer = input('Зачеркнуть цифру? (y/n)').lower().strip() if useranswer == 'y' and not keg in self.__usercard or \ useranswer != 'y' and keg in self.__usercard: return 2 if keg in self.__usercard: self.__usercard.cross_num(keg) if self.__usercard.closed(): return 1 if keg in self.__compcard: self.__compcard.cross_num(keg) if self.__compcard.closed(): return 2 return 0 if __name__ == '__main__': game = Game() while True: score = game.play_round() if score == 1: print('You win') break elif score == 2: print('You lose') break # class Cart: # __rows = 3 # __nums_in_row = 5 # __tab = ' ' # __delim = '--------------------------' # def __init__(self): # self.__card = [] # for _j in range(self.__rows): # a = [] # for _i in range(self.__nums_in_row): # num = randint(1, 91) # if not num in a: # a.append('%+2s' % (num)) # a.sort() # c = 0 # while c < 4: # pos = randint(0, len(a) + c) # a.insert(pos, ' ') # c += 1 # string = ' '.join(a) # self.__card.append(string) # def __str__(self): # a = f'{self.__card[0]}\n{self.__card[1]}\n{self.__card[2]}\n{self.__delim}' # return (a)
true
846e160d44d6e29d425edbe41b77d1602502003b
Python
sabihismail/cps-406-qix
/util/draw_util.py
UTF-8
2,803
3.28125
3
[]
no_license
import pygame def draw_rect(surface, colour, bounds, line_width=1): draw_rect_specific(surface, colour, bounds.x, bounds.y, bounds.width, bounds.height, line_width=line_width) def draw_rect_specific(surface, colour, x, y, width, height, line_width=1): lst = [ ((x, y), (x, y + height)), ((x, y), (x + width, y)), ((x, y + height), (x + width, y + height)), ((x + width, y), (x + width, y + height)) ] for elem in lst: pygame.draw.line(surface, colour, elem[0], elem[1], line_width) return lst def get_lines_by_rect_specific(x, y, width, height): lst = [ ((x, y), (x, y + height)), ((x, y + height), (x + width, y + height)), ((x + width, y + height), (x + width, y)), ((x + width, y), (x, y)) ] return lst def get_lines_by_rect(bounds): return get_lines_by_rect_specific(bounds.x, bounds.y, bounds.width, bounds.height) def to_vertices_list(lines): vertices = [a[0] for a in lines] vertices.append(lines[len(lines) - 1][1]) return vertices def to_line_list(vertices): lines = [] for i in range(len(vertices) - 1): lines.append((vertices[i], vertices[i+1])) return lines def lines_to_dict(lines): d = {} for line in lines: d[line[0]] = line[1] d[line[1]] = line[0] return d def vertices_to_dict(vertices): lines = to_line_list(vertices) d = {} for line in lines: a = d.get(line[0], []) a.append(line[1]) b = d.get(line[1], []) b.append(line[0]) d[line[0]] = a d[line[1]] = b return d def unique_vertices_to_dict(vertices): d = vertices_to_dict(vertices) for key, value in d.items(): lst = [x for x in value if x != key] lst = list(set(lst)) d[key] = lst return d # retrieved from https://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame def rotate_surface(outer_surface, inner_surface, pos, originPos, angle): w, h = inner_surface.get_size() box = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]] box_rotate = [p.rotate(angle) for p in box] min_box = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1]) max_box = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1]) pivot = pygame.math.Vector2(originPos[0], -originPos[1]) pivot_rotate = pivot.rotate(angle) pivot_move = pivot_rotate - pivot origin = (pos[0] - originPos[0] + min_box[0] - pivot_move[0], pos[1] - originPos[1] - max_box[1] + pivot_move[1]) rotated_surface = pygame.transform.rotate(inner_surface, angle) outer_surface.blit(rotated_surface, origin)
true
bd59d96cdf8d6c1ee934ec9235101777eb86849c
Python
jvasilakes/yall
/yall/utils.py
UTF-8
1,562
3.265625
3
[ "MIT" ]
permissive
import numpy as np import matplotlib.pyplot as plt # TODO: Reference the active learning challenge def compute_alc(aucs, normalize=True): ''' Compute the normalized Area under the Learning Curve (ALC) for a set of AUCs. param aucs: np.array of AUC values. param normalize: Whether to normalize the ALC, default: True. ''' alc = np.trapz(aucs, dx=1.0) if normalize is True: random_auc = np.repeat(0.5, aucs.shape[0]) A_random = np.trapz(random_auc, dx=1.0) max_auc = np.repeat(1.0, aucs.shape[0]) A_max = np.trapz(max_auc, dx=1.0) # Normalize the ALC alc = (alc - A_random) / (A_max - A_random) return alc def plot_learning_curve(aucs, L_init, L_end, title="ALC", eval_metric="auc", saveto=None): ''' Plots the learning curve for a set of AUCs. param aucs: np.array of AUC values. param L_init: The initial size of the labeled set. param L_end: The final size of the labeled set. param title: The title of this plot. param saveto: Filename to which to save this plot instead of showing it. ''' alc = compute_alc(aucs) draws = np.arange(L_init, L_end) plt.figure(figsize=(10, 5)) plt.plot(draws, aucs, linewidth=2) plt.xlabel("|L|", fontsize=15) plt.ylabel(eval_metric.upper(), fontsize=15) plt.title(title) plt.annotate(f"ALC: {alc:.4f}", xy=(0.8, 0.05), xycoords="axes fraction") if saveto is not None: plt.savefig(saveto) plt.close() else: plt.show()
true
19d71a70c9e149adbbba05ca4deb55f4d26ae189
Python
mifa031/hacking_problems
/web/suninatas07(34).py
UTF-8
952
2.609375
3
[]
no_license
from http import client import time #level7 문제에 접속 conn = client.HTTPConnection('suninatas.com',80) GET_headers={'Cookie': 'ASPSESSIONIDQQCQAAQS=MDOIJMNCGKDLIFAGHHECJICL'} GET_url = '/Part_one/web07/web07.asp' GET_body = '' conn.request('GET',GET_url,GET_body,GET_headers) conn.close() #YES버튼을 누른것과 같은 효과의 POST요청을 보냄 conn = client.HTTPConnection('suninatas.com',80) POST_headers={'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': 'ASPSESSIONIDQQCQAAQS=MDOIJMNCGKDLIFAGHHECJICL'} POST_url = '/Part_one/web07/web07_1.asp' POST_body = 'web07=Do+U+Like+girls%3F' conn.request('POST',POST_url,POST_body,POST_headers) #마지막 POST요청의 결과값을 받아옴. #문제에 접속하자마자 POST요청을 보냈으므로 인증키를 얻을 수 있다. res=conn.getresponse() resData=res.read() strRes = str(resData) print(strRes) conn.close()
true
03062222ac7541a125cd94f8460935fd767b4332
Python
guiraldelli/MSc
/haplotype_network/guiraldelli/master/mutation/algorithms.py
UTF-8
2,274
3.3125
3
[ "BSD-2-Clause" ]
permissive
from data import Mutation import pygraph.classes.graph def find_mutations(haplotypes): '''Given (a dictionary of) haplotypes, return a list (of Mutation) with mutational information about the haplotypes.''' mutations = list() tested_pairs = list() for haplotype in haplotypes.keys(): for other_haplotype in haplotypes.keys(): count = 0 if other_haplotype != haplotype: pair = set() pair.add(haplotype) pair.add(other_haplotype) if (pair not in tested_pairs): tested_pairs.append(pair) pair_info = Mutation() pair_info.haplotypes = pair for i in range(0,len(haplotypes[haplotype])): if haplotypes[haplotype][i] != haplotypes[other_haplotype][i]: count = count + 1 pair_info.differences.append(i) #print "(%s,%s): difference found on %dth index!" % (haplotype, other_haplotype, i) #print "(%s,%s): %d" % (haplotype, other_haplotype, count) pair_info.count = count mutations.append(pair_info) # HACK: do I need to delete the other data structures? del pair_info return mutations def mutational_network(mutations): '''Given (a list of) mutations, returns a haplotype network (graph) with mutational distances as edges' weight.''' network = pygraph.classes.graph.graph() for mutational_pair in mutations: # adding the haplotypes of the pair in the network as nodes for haplotype in mutational_pair.haplotypes: try: network.add_node(haplotype) except pygraph.classes.exceptions.AdditionError: pass # adding the edges with mutational distance as edge weight try: network.add_edge(tuple(mutational_pair.haplotypes), wt=mutational_pair.count) except pygraph.classes.exceptions.AdditionError: # TODO: must think what to do. May be I should update the edge weight if it is smaller than the existing one pass return network
true
2209e5d07bc968c63bf7633b8f23b4e03608e61e
Python
alexjaw/rnm
/rnm/service.py
UTF-8
2,112
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/python # # Classes for accesspoint and dhcp services import logging from subprocess import check_output, Popen, PIPE class Service: def __init__(self, service): self.service = service def _service_cmd(self, cmd): assert cmd in ['start', 'stop', 'status'], 'Not a valid service cmd' p = Popen(['sudo', 'service', self.service, cmd], stdout=PIPE, stderr=PIPE) # todo: should do with info from p.communicate() resp = p.communicate()[0].split('\n') rv = {'LSB': None, 'Loaded': None, 'Active': None} for line in resp: if '\xe2\x97\x8f' in line: rv['LSB'] = line.split(':')[1].strip() elif 'Loaded' in line: rv['Loaded'] = line.split(':')[1].strip() elif 'Active' in line: rv['Active'] = line.split(':')[1].strip() return rv def start(self): return self._service_cmd('start') def stop(self): return self._service_cmd('stop') def status(self): return self._service_cmd('status') class AccessPoint(Service): # todo: better handling of application paths setup_script = '/home/pi/rnm/scripts/setup_access_point.sh' def __init__(self): Service.__init__(self, 'hostapd') def setup(self): p = Popen(['sh', self.setup_script], stdout=PIPE, stderr=PIPE) return p.communicate()[0] class DHCP(Service): setup_script = '/home/pi/rnm/scripts/setup_dhcp.sh' def __init__(self): Service.__init__(self, 'udhcpd') def setup(self): p = Popen(['sh', self.setup_script], stdout=PIPE, stderr=PIPE) return p.communicate()[0] def test_me(): logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('------------- Starting test... -------------') ap = AccessPoint() dhcp = DHCP() resp = ap.status() logger.info(repr(resp)) resp = dhcp.status() logger.info(repr(resp)) logger.info('------------- Finished -------------') if __name__ == '__main__': test_me()
true
7ec4239b53edb3eebde0ce3a66ddc186160384e3
Python
huangkg8/Super-Hijacker
/src_v3/screen_factors/enemy.py
UTF-8
890
3.09375
3
[]
no_license
"""俊义完成""" import pygame as pg from pygame.sprite import Sprite class Enemy(Sprite): def __init__(self,sett,life,speed,time_limit): super().__init__() self.sett=sett self.life=life #生命值 self.speed=speed self.shoot_dir=180 self.time_limit=time_limit #hero可以驾驶的时限 self.jackedTime=None #被劫机的时间 self.moving_right=False self.moving_left=False self.moving_up=False self.moving_down=False def update(self): """移动或发射子弹""" pass def drawme(self): pass class Ordin_plane(Enemy): """使用bullet0""" def __init__(self,sett): super().__init__(sett, sett.ordinPlaneLife, sett.ordinPlaneSpeed, sett.ordinPlaneTimeLimit) class Multi_plane(Enemy): """使用bullet1""" pass class Missile_plane(Enemy): """使用bullet2""" pass class Tank(Enemy): pass
true
a4f7ccd51cf2496cc3535476e9269c9ae7c06ee4
Python
erantanen/my_blog
/code_snips/file_open.py
UTF-8
290
3.515625
4
[]
no_license
#! /usr/bin/env python """ example showing how to open a file and what to do with non strings """ with open("blah.txt", "w") as FH: FH.write("Space… the final frontier.") for elm in range(10): #elm has been cast to a string FH.write(str(elm) + "\n")
true
1146078f6a9c6a8d83d172b4e37e2dcdef392c1a
Python
juhtornr/LocalEGA
/src/lega/utils/checksum.py
UTF-8
1,795
3
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- import logging import hashlib from .exceptions import UnsupportedHashAlgorithm, CompanionNotFound LOG = logging.getLogger('utils') # Main map _DIGEST = { 'md5': hashlib.md5, 'sha256': hashlib.sha256, } def instanciate(algo): try: return (_DIGEST[algo])() except KeyError: raise UnsupportedHashAlgorithm(algo) def compute(f, m, bsize=8192): '''Computes the checksum of the bytes-like `f` using the message digest `m`.''' while True: data = f.read(bsize) if not data: break m.update(data) return m.hexdigest() def is_valid(filepath, digest, hashAlgo = 'md5'): '''Verify the integrity of a file against a hash value''' assert( isinstance(digest,str) ) m = instanciate(hashAlgo) with open(filepath, 'rb') as f: # Open the file in binary mode. No encoding dance. res = compute(f, m) LOG.debug('Calculated digest: '+res) LOG.debug(' Original digest: '+digest) return res == digest def get_from_companion(filepath): '''Attempts to read a companion file. For each supported algorithms, we check if a companion file exists. If so, we read its content and return it, along with the selected current algorithm. We exit at the first one found and raise a CompanionNotFound exception in case none worked. ''' for h in _DIGEST: companion = str(filepath) + '.' + h try: with open(companion, 'rt', encoding='utf-8') as f: return f.read(), h except OSError as e: # Not found, not readable, ... LOG.debug(f'Companion {companion}: {e!r}') # Check the next else: # no break statement was encountered raise CompanionNotFound(filepath)
true
797428412a1d2ae78a9dc5f787272c836c271d3d
Python
Deven-14/Python_Level_1
/decorator.py
UTF-8
486
3.390625
3
[]
no_license
from functools import wraps def decorator(func): @wraps(func) def print_args_value(*args, **kwargs): for ele in args: print(ele) for ele in kwargs.values(): print(ele) x = func(*args, **kwargs) return x return print_args_value @decorator def decorate(*args, **kwargs): print("Do some work") return "Completed" def main(): print(decorate(1, 2, c=3, d=4)) if __name__ == "__main__": main()
true
36e8c2c8e13fe292534da179e670aee044a6fb7a
Python
Vishruth-S/Hack-CP-DSA
/Hackerrank/No Idea!/Solution.py
UTF-8
1,246
4.0625
4
[ "MIT" ]
permissive
"""According to the question we need to maintain count of likes and dislikes such that from a set of numbers(Second line of input) if a particluar number exist in set A(Third line of input) then the happiness count will be 1, if it exist in (Forth line of input)B the happiness count will be -1 and if neither of the sets then the happiness count will remain unchanged. Here the First line of input dictates the number of entries in the COMPARING set(from which we will compare) and A and B (they both wil have same length).To keep the count of happiness we have created a variable count intialised to 0. """ x, y = map(int, input().split()) # x is length of storage and y is length of A, B storage = list() count = 0 storage = list(map(int, input().strip().split())) # map function converts all string input values into int A = set(map(int, input().strip().split())) B = set(map(int, input().strip().split())) for i in storage: if i in A: # if A then increment in count value count = count+1 if i in B: # if B then decrement in count value count = count-1 print(count)
true
28d991579468a891b9c15e79b3a205dcb2344613
Python
umunusb1/PythonMaterial
/python3/03_Language_Components/07_Conditional_Operations/e_celsius_to_fahrenheit_conversion.py
UTF-8
337
3.984375
4
[]
no_license
#!/usr/bin/python3 """ Purpose: Temperature Conversions - celsius to fahrenheit """ celsius = float(input('Enter temperature in celsius:')) # print(f'{celsius =}') farhenheit = (1.8 * celsius) + 32 # print(f'{farhenheit =}') print(f''' celsius : {round(celsius, 2)} farhenheit : {round(farhenheit, 2)} ''')
true
1129ca00f776ff04e16e114b1d917f0527fc32cd
Python
collopa/mcm
/model/radio.py
UTF-8
8,215
3.046875
3
[]
no_license
#!/usr/bin/python # Author: cbecker@g.hmc.edu #-----------------------------------------------------------------------# ''' TODO: import iono and ocean indices correctly, change MAIN! ''' #-----------------------------------------------------------------------# ''' Inputs: discrete signal vector as a function of time indices of refraction of ionosphere Angle of incidience (+ or - from parallel to Earth's surface) Distance to receiver Severity of Weather on a scale of 0-1, with 1 being the most intense Outputs: discrete signal vector as function of time SNR at each N value Where f(t) = \sum_{n=0}^{N} f_{n}(t), this file: -- decomposes the input signal into its Fourier components, f_{0_{n}}(t) --> f_{0_{n}}(w) -- for each component, f0n(w), it computes fn(w) according to Fresnel's equations and dispersive equations -- uses the inverse Fourier transform to recompose the output signal, f_{n}(w) --> f_{n}(t) Notes: -- Fresnel's equations require angle of incidence and indices of refraction of the two media. -- The dispersive equations require the conductivity of air. -- If angle of incidence is less than zero Earth's surface), odd N reflections are off of the ocean/land -- If angle of incidence is greater than zero, even N reflections are off of the ionosphere -- This model assumes Gaussian noise which accumulates over time, so a random, normal noise vector is added to the signal vector every so often. -- The frequency of white noise addition is dependent on weather conditions. (Weather conditions on a 0-1 scale) ''' import os import sys import numpy as numpy import math as math import constants as constants from ocean import * from operator import add factor = 1.0e4 c = 3e8 # speed of light def get_z(t, f0_t): z = numpy.empty(len(t)) for i in range(len(t)): zi = t[i] - math.arcsin(f0_t[i]) numpy.append(z, zi) return z def decompose(t, f0_t): max_time = max(t) ns = float(len(t)) # number of samples Fs = max_time/ns # sampling frequency min_freq = -ns/2 max_freq = ns/2 step_size = 1 k0 = range(int(min_freq*factor), int(max_freq*factor), int(step_size*factor)) k = map((lambda x: x/factor), k0) f0_k = numpy.fft.fft(f0_t) return [k, f0_k] def get_num_refl(angle_of_incidence, distance): d = distance z = constants.TxRx_height h = constants.iono_height a = angle_of_incidence N = math.floor(d * math.tan(a) / (h - z)) return N def calc_noise(weather_severity, N, array_length, f_t_real): sum_f_t = 0.0 for num in f_t_real: sum_f_t += num avg = sum_f_t/array_length base_stdev = array_length/100.0 wc = weather_severity + 0.1 # weather contribution Nc = math.sqrt(N) # Reflection number contribution stdev = base_stdev * wc * Nc noise = numpy.random.normal(avg, stdev, array_length) return noise def add_fresnel(iono_index_of_refr, ocean_index_of_refr, angle_of_incidence, k, f0_k, N): # Constants theta_I = angle_of_incidence theta_R = theta_I # By the law of reflection n1 = (constants.air_dielec_const)**2 n2_iono = iono_index_of_refr n2_ocean = ocean_index_of_refr # Determine multipliers, which determine the amplification of Fresnel effects if N % 2 == 0: iono_multiplier = N/2 ocean_multiplier = N/2 else: if theta_I > 0: iono_multiplier = (N - 1) / 2 + 1 ocean_multiplier = (N - 1) / 2 else: iono_multiplier = (N - 1) / 2 ocean_multiplier = (N - 1) / 2 + 1 refl_tup = ((n2_iono, iono_multiplier), (n2_ocean, ocean_multiplier)) # Compute Fresnel-modified signal f0_k_post_Fresnel = numpy.ones(len(k)) for n in range(len(k)): fn_k = f0_k[n] for tup in refl_tup: n2 = tup[0] m = tup[1] theta_T = numpy.arcsin(n1 * numpy.sin(theta_I) / n2) # By Snell's law # By Fresnel's equations: beta = n2/n1 alpha = numpy.cos(theta_T) / numpy.cos(theta_I) fn_k = (alpha - beta) / (alpha + beta) * fn_k # *m f0_k_post_Fresnel[n] = fn_k # Return the Fresnel-modified signal return f0_k_post_Fresnel def add_dispersion(z, t, k, f0_t, f0_k_post_Fresnel): sigma = constants.air_elec_cond f0_k_post_dispersion = numpy.ones(len(z)) omega = numpy.ones(len(k)) kappa = numpy.ones(len(k)) for i in range(len(k)): omega[i] = 2 * math.pi * k[i] # convert to angular frequency for n in range(len(k)): zn = z[n] wn = omega[n] if wn != 0: kappa_n = wn * math.sqrt(constants.epsilon_perm * constants.mu_perm / 2) \ * math.sqrt(1 \ + math.sqrt(1 \ + (constants.air_elec_cond/ constants.epsilon_perm / wn)**2)) fn_k = math.exp(-kappa_n * zn) * f0_k_post_Fresnel[n] else: kappa_n = 0 fn_k = f0_k_post_Fresnel[n] f0_k_post_dispersion[n] = fn_k kappa[n] = kappa_n return [kappa, f0_k_post_dispersion] def calc_SNR(kappa, z): SNR = [] for n in range(len(kappa)): arg = math.exp(2 * kappa[n] * z[n]) SNR.append(10 * math.log10(arg)) print SNR return SNR def calc_hops(SNR, N, kappa, z, f0_t): remainder = len(SNR) % N multiplier = (len(SNR) - remainder) / N Ns = [] max_hops = N for n in range(N+1): for i in range(multiplier): Ns.append(n) print Ns for s in range(len(SNR)): if SNR[len(SNR) - 1 - s] < 10: max_hops = Ns[s] break for n in range(len(Ns)): if Ns[n]>1: kappa_1 = kappa[n] z_1 = z[n] break og_strength = 10 * math.log10(max(f0_t)**2) strength = 10 * math.log10(math.exp(2 * kappa_1 * z_1)) return [max_hops, og_strength, strength] #-----------------------------------------------------------------------# if __name__ == '__main__': # Read in file arguments args = sys.argv[1:] iono_index_of_refr = float(args[0]) ocean_index_of_refr = float(args[1]) angle_of_incidence = math.radians(float(args[2])) # in degrees, we convert to radians distance = float(args[3])*1000 # distance on Earth's surface to be traveled in kilometers, we convert to meters weather_severity = float(args[4]) input_file = args[5] # input signal # Get input data from .csv # Decompose the input signal, f0_t, to it's Fourier components f0_k [z, t, f0_t] = numpy.genfromtxt(input_file, delimiter = ',') [k, f0_k] = decompose(t, f0_t) k_real = map((lambda x: numpy.real(x)), k) f0_k_real = map((lambda x: numpy.real(x)), f0_k) numpy.savetxt('FT_input_signal.csv', [k_real, f0_k_real], delimiter = ',', fmt='%1.3f') # Number of reflections N = get_num_refl(angle_of_incidence, distance) # For each f0_k, compute the output after Fresnel and dispersion f0_k_post_Fresnel = add_fresnel(iono_index_of_refr, ocean_index_of_refr, angle_of_incidence, k, f0_k, N) [kappa, f0_k_post_dispersion] = add_dispersion(z, t, k, f0_t, f0_k_post_Fresnel) f_k = f0_k_post_dispersion numpy.savetxt('FT_output_signal.csv', [k_real, f_k, kappa], delimiter = ',', fmt='%1.4e') # Compose output signal and add in accumulated noise # Export output data to .csv f_t_real = numpy.real(numpy.fft.ifft(f_k)) # Calculate noise vector to be added to output signal noise = calc_noise(weather_severity, N, len(t), f_t_real) f_t = map(add, f_t_real, noise) numpy.savetxt('radio_output.csv', (z, t, f_t), delimiter = ',', fmt='%1.3f') # Calculate SNR vector SNR = calc_SNR(kappa, z) # Calculate how many hops (a number leq N) for SNR leg 10dB # and calculate strength after 1 reflection [max_hops, og_strength, strength] = calc_hops(SNR, int(N), kappa, z, f0_t) print 'Number of Hops until SNR \leq 10dB: ', max_hops print 'Strength of original signal: ', og_strength, ' dB' print 'Strength of signal after 1st reflection: ', strength, ' dB'
true
99feef75c289f4c837b85acd35da46696e2b82d8
Python
Schroedingberg/EiP
/Sheet06/Test2.py
UTF-8
72
2.609375
3
[]
no_license
import numpy as np A = [2, -6, 2, -1] res = np.polyval(A,3) print(res)
true
40893d8240c5f82ae69cd0bfc2bd1fe03e17dca8
Python
mrzResearchArena/Intelligent-Elevator-System
/MainElevator.py
UTF-8
13,986
2.953125
3
[]
no_license
from random import uniform # uniform distribution import itertools # Combination import math # floor 0r celling import time # time counter global totalServed totalServed = 0 global up up = [] global down down = [] global upStop upStop = [] global downStop downStop = [] global currentLocation currentLocation = 1 global currentWeight currentWeight = 0.0 global elevatorDirection elevatorDirection = "up" global serverStatus serverStatus = "idle" # "busy" global N N = 6 def generateWeight(): p = uniform(0.0, 1.0) if 0.0 <= p < 0.10: instanceWeight = uniform(25, 30) elif 0.10 <= p < 0.20: instanceWeight = uniform(30, 50) elif 0.20 <= p < 0.60: instanceWeight = uniform(50, 70) elif 0.60 <= p < 0.85: instanceWeight = uniform(70, 90) elif 0.90 <= p < 0.95: instanceWeight = uniform(90, 100) else: instanceWeight = uniform(100, 120) return math.ceil(instanceWeight) def allPossibleCombination(elements): # 35% times no call # 65% times any calls p = uniform(0.0, 1.0) if p < 0.35: return [] else: value = list(itertools.product([0, 1], repeat=elements.__len__())) randomValue = math.floor(uniform(0.0, value.__len__())) select = value[randomValue] C = [] i = 0 while i < len(elements): if select[i] == 1: C.append(elements[i]) i = i + 1 return C def personCount(i, direction): value = uniform(0.0, 1.0) if direction == "up": if i == 1: if 0.00<= value < 0.20: return 0 elif 0.20 <= value < 0.40: return 1 elif 0.40 <= value < 0.60: return 2 elif 0.60 <= value < 0.80: return 3 elif 0.80 <= value < 0.90: return 4 elif 0.90 <= value < 0.95: return 5 else: return 6 elif i == 2: if 0.00 <= value < 0.30: return 1 elif 0.30 <= value < 0.40: return 2 elif 0.40 <= value < 0.60: return 3 elif 0.60 <= value < 0.80: return 4 elif 0.80 <= value < 0.90: return 5 elif 0.90 <= value < 0.95: return 6 else: return 0 elif i == 3: if 0.00 <= value < 0.40: return 1 elif 0.40 <= value < 0.60: return 2 elif 0.60 <= value < 0.80: return 3 elif 0.80 <= value < 0.85: return 4 elif 0.85 <= value < 0.90: return 5 elif 0.90 <= value < 0.95: return 6 else: return 0 elif i == 4: if 0.00 <= value < 0.60: return 1 elif 0.60 <= value < 0.75: return 2 elif 0.75 <= value < 0.80: return 3 elif 0.80 <= value < 0.85: return 4 elif 0.85 <= value < 0.90: return 5 elif 0.90 <= value < 0.95: return 6 else: return 0 elif i == 5: if 0.00 <= value < 0.60: return 0 elif 0.60 <= value < 0.75: return 1 elif 0.75 <= value < 0.80: return 2 elif 0.80 <= value < 0.85: return 3 elif 0.85 <= value < 0.90: return 4 elif 0.90 <= value < 0.95: return 5 else: return 6 else: if i == 6: if 0.0 <= value < 0.30: return 6 elif 0.30 <= value < .50: return 5 elif 0.50 <= value < .70: return 4 elif 0.70 <= value < .80: return 3 elif 0.80 <= value < .90: return 2 elif 0.90 <= value < 0.95: return 1 else: return 0 if i == 5: if 0.0 <= value < 0.30: return 6 elif 0.30 <= value < .50: return 5 elif 0.50 <= value < .70: return 4 elif 0.70 <= value < .80: return 3 elif 0.80 <= value < .90: return 2 elif 0.90 <= value < 0.95: return 1 else: return 0 if i == 4: if 0.0 <= value < 0.30: return 6 elif 0.30 <= value < .50: return 5 elif 0.50 <= value < .70: return 4 elif 0.70 <= value < .80: return 3 elif 0.80 <= value < .90: return 2 elif 0.90 <= value < 0.95: return 1 else: return 0 if i == 3: if 0.0 <= value < 0.10: return 6 elif 0.10 <= value < 0.20: return 5 elif 0.30 <= value < 0.40: return 4 elif 0.40 <= value < 0.75: return 3 elif 0.75 <= value < 0.85: return 2 elif 0.85 <= value < 0.90: return 1 else: return 0 if i == 2: if 0.0 <= value < 0.03: return 6 elif 0.03 <= value < 0.06: return 5 elif 0.06 <= value < 0.09: return 4 elif 0.09 <= value < 0.12: return 3 elif 0.12 <= value < 0.15: return 2 elif 0.15 <= value < 0.30: return 1 else: return 0 def settingUp(i): value = [] while i < 7: value.append(i) i = i + 1 return value def settingDown(i): value = [] while i > 0: value.append(i) i = i - 1 return value def process(): global up global down up.append([]) down.append([]) i = 1 while i < 6: value = settingUp(i + 1) up.append(value) i = i + 1 i = 6 while i > 0: value = settingDown(i - 1) down.append(value) i = i - 1 def ensureStop(): upStop.append(0) downStop.append(0) i = 1 while i < 7: upStop.append(0) downStop.append(0) i = i + 1 # class Node: # def __init__(self, weight, liftPosition): # self.weight = weight # self.liftPosition = liftPosition # # # def tuplePrac(): # runningCar = [] # # abc = Node(45, 6) # # # # runningCar.append( abc = Node(64, 11) ) # # runningCar.append( Node(56, 6) ) # # runningCar.append( Node(79,2) ) # i=0 # while i<3: # abc = Node(generateWeight(), 96) # runningCar.append(abc) # i = i+1 def intelligenceDistribution(currentLocation, elevatorDirection): p = uniform(0.0, 1.0) if elevatorDirection == "up": if currentLocation == 1: if 0.0 <= p <= 0.03: return 2 elif 0.04 <= p <= 0.34: return 3 elif 0.35 <= p <= 0.75: return 4 elif 0.76 <= p <= 0.95: return 5 else: return 6 elif currentLocation == 2: if 0.0 <= p <= 0.03: return 3 elif 0.04 <= p <= 0.54: return 4 elif 0.55 <= p <= 0.95: return 5 else: return 6 elif currentLocation == 3: if 0.0 <= p <= 0.05: return 4 elif 0.05 <= p <= 0.90: return 5 else: return 6 elif currentLocation == 4: if 0.0 <= p <= 0.05: return 5 else: return 6 else: return 6 # When elevatorDirection is down. else: if currentLocation == 6: if 0.0 <= p <= .67: return 1 elif 0.68 <= p <= 0.78: return 2 elif 0.79 <= p <= .88: return 3 elif 0.89 <= p <= .97: return 4 else: return 5 elif currentLocation == 5: if 0.0 <= p <= .67: return 1 elif 0.68 <= p <= 0.78: return 2 elif 0.79 <= p <= .95: return 3 else: return 4 elif currentLocation == 4: if 0.0 <= p <= .75: return 1 elif 0.76 <= p <= 0.95: return 2 else: return 3 elif currentLocation == 3: if 0.0 <= p <= .95: return 1 else: return 2 elif currentLocation == 2: return 1 def main(): process() ensureStop() min = int(input()) end = time.time() + 60.0 * min global N global currentLocation global elevatorDirection global currentWeight global serverStatus global totalServed serverStatus = "busy" while time.time() < end: runningCar = [] # This a carrying car. if elevatorDirection == "up": # person need to modify person = personCount(currentLocation, elevatorDirection) # Total person takes print("person = {}".format(person)) if person > 0: time.sleep(5.0) i = 0 while i < person: if currentWeight <= 550.0: # Maximum can carry upto 750.0, when up. liftPosition = intelligenceDistribution(currentLocation, elevatorDirection) print("liftPosition = {}".format(liftPosition)) upStop[liftPosition] = 1 weight = generateWeight() print("weight = {}".format(weight)) currentWeight = currentWeight + weight # Weight in increasing print("currentWeight = {}".format(currentWeight)) runningCar.append((weight, liftPosition)) # This is a tupple [ like class ] # Need to edit else: if currentWeight == 0: serverStatus = "idle" else: break i = i + 1 currentLocation += 1 time.sleep(1.5) # Takes 1.5 seconds for going next steps print("currentLocation = {}".format(currentLocation)) if upStop[currentLocation] == 1: time.sleep(5.0) for I in runningCar: if I[1] == currentLocation: weight -= I[0] runningCar.remove(I) totalServed += 1 print("totalServed = {}".format(totalServed)) # Special Checking ... elevatorDirection will change up to down. # N = 6 if currentLocation == N: elevatorDirection = "down" i=1 while i<=N: upStop[i] = 0 i += 1 # weight will be -> 0.0 # People can change decetion else: # person need to modify person = personCount(currentLocation, elevatorDirection) # Total person takes print("person = {}".format(person)) if person > 0: time.sleep(5.0) i = 0 while i < person: if currentWeight <= 550.0: # Maximum can carry upto 850.0, when down. liftPosition = intelligenceDistribution(currentLocation, elevatorDirection) print("liftPosition = {}".format(liftPosition)) downStop[liftPosition] = 1 weight = generateWeight() print("weight = {}".format(weight)) currentWeight = currentWeight + weight # Weight in increasing print("currentWeight = {}".format(currentWeight)) runningCar.append((weight, liftPosition)) # This is a tupple [ like class ] # Need to edit else: if currentWeight == 0: serverStatus = "idle" else: break i = i + 1 currentLocation -= 1 time.sleep(1.5) # Takes 1.5 seconds for going next steps print("currentLocation = {}".format(currentLocation)) if downStop[currentLocation] == 1: time.sleep(5.0) for I in runningCar: if I[1] == currentLocation: weight -= I[0] runningCar.remove(I) totalServed += 1 print("totalServed = {}".format(totalServed)) # Special Checking ... elevatorDirection will change up to down. # N = 6 if currentLocation == 1: elevatorDirection = "up" i = 1 while i <= N: downStop[i] = 0 i += 1 # weight will be -> 0.0 # People can change decetion print("Total people served {} within {} minute.".format(totalServed, min)) if __name__ == "__main__": main()
true
760b957bdf1830b75332d5f605990d515f91ca9c
Python
adibsxion19/CS1114
/Labs/lab12Pr5.py
UTF-8
1,283
3.46875
3
[]
no_license
#Aadiba Haque #4/24/2020 #Lab 12 Q5 def add_entry(contacts, name, number): if name not in contacts: if len(number) == 10: valid = True for num in number: if not num.isdigit(): valid = False if valid: contacts[name] = number def lookup(contacts, name): if name in contacts: return contact[name] else: print("Name not found") def print_all(contacts): for key in contacts: print(key, contacts[key],sep = '\t') def add_from_file(filename, contacts): try: file = open(filename, "r") except: print("File Not Found") for line in file: line = line.strip() lst_data = line.split(",") name = lst_data[0] name_lst = name.split(", ") temp = name_lst[0] name_lst[0] = name_lst[1] name_lst[1] = temp name = " ".join(name_lst) add_entry(contacts, name, lst_data[1]) file.close() def main(): contacts = {} filename = "us-senate.csv" name = "Mickey Mouse" number = "1234567890" add_from_file(filename, contacts) add_entry(contacts, name, number) lookup(contacts, name) print_all(contacts)
true
b57e5429edfc6a457a00d05dd8b282905b01fff8
Python
totalborons/LPTHW
/ex15.py
UTF-8
338
3.109375
3
[]
no_license
from sys import argv script, fileName = argv txt = open(fileName) print(f"Opening file {fileName}") print(txt.read()) # .read reads the whole file here and not the individual lines and no control over where and how to read.. # done now # have to pass txt extension in name else it wont work # read() reads all the lines in the file
true
261159262f4822fc3f8db5e0cf574d7d76186f3a
Python
SebBlin/p4
/some-tests/print-table.py
UTF-8
1,067
3.484375
3
[ "MIT" ]
permissive
# affichage d'une grille # voir https://en.wikipedia.org/wiki/Box-drawing_character#Unicode nbcol = 7 nbligne = 6 grille = [ [0,0,0,0,0,0,0], [0,0,0,0,0,0,0], [0,0,1,0,0,0,0], [0,0,1,0,0,0,0], [0,0,1,0,0,0,0], [0,0,1,2,2,2,0] ] pion = [' ', 'X', 'O'] def print_top_line(): print(u'\u250c', end = '') for _ in range(nbcol-1): print(u'\u2500\u252c', sep = '', end = '') print(u'\u2500\u2510') def print_mid_line_empty(tab_line): for i in range(nbcol): print(u'\u2502',pion[tab_line[i]], sep = '', end = '') print(u'\u2502') def print_mid_line_full(): print(u'\u251c', end = '') for _ in range(nbcol-1): print(u'\u2500\u253c', end = '') print(u'\u2500\u2524') def print_bottom_line(): print(u'\u2514', end = '') for _ in range(nbcol-1): print(u'\u2500\u2534', end = '') print(u'\u2500\u2518') print_top_line() for i in range(nbligne-1): print_mid_line_empty(grille[i]) print_mid_line_full() print_mid_line_empty(grille[nbligne-1]) print_bottom_line()
true
3361686119ad81a1c35919529dba737a79467f89
Python
ePlusPS/emr-workflow
/airflow_pipeline/readmission_tf_prob_to_likert.py
UTF-8
975
2.671875
3
[]
no_license
import pandas as pd from workflow_read_and_write import standard_read_from_db, standard_write_to_db def make_likert_column(df): likert_vals = [] for i, row in df.iterrows(): if row['keras_pred'] < 0.25: likert_vals.append('Very Unlikely Readmission') elif 0.25 <= row['keras_pred'] and row['keras_pred'] < 0.5: likert_vals.append('Unlikely Readmission') elif 0.5 <= row['keras_pred'] and row['keras_pred'] < 0.75: likert_vals.append('Likely Readmission') else: likert_vals.append('Very Likely Readmission') return likert_vals def convert_to_likert(): df_json_encoded = standard_read_from_db('readmission_tensorflow_predictions') df = pd.read_json(df_json_encoded.decode()) likert_values = make_likert_column(df) df['readmission_likert'] = likert_values df_json_encoded = df.to_json().encode() standard_write_to_db('readmission_likert', df_json_encoded)
true
24b96448014e8c1e6495439df7a422598a3354e8
Python
paullickman/aoc2020
/09/encoding.py
UTF-8
1,125
3.4375
3
[]
no_license
def sums(nums): for i in range(len(nums)): for j in range(len(nums)): if i != j: yield nums[i] + nums[j] class Encoding(): def __init__(self, filename, preamble): with open('09/' + filename) as f: self.nums = list(map(int, f.readlines())) self.len = len(self.nums) self.preamble = preamble def firstInvalid(self): i = self.preamble while i < self.len: if not(self.nums[i] in sums(self.nums[i-self.preamble:i])): return self.nums[i] i += 1 def search(self, target): for i in range(self.len - 2): sum = self.nums[i] j = i + 1 while j < self.len and sum < target: sum += self.nums[j] if sum == target: return min(self.nums[i:j+1]) + max(self.nums[i:j+1]) j += 1 e = Encoding('test.txt', 5) assert e.firstInvalid() == 127 assert e.search(127) == 62 e = Encoding('input.txt', 25) firstInvalid = e.firstInvalid() print(firstInvalid) print(e.search(firstInvalid))
true
92e42c766ac3c595bce51941e2d9d2349cc9c4ae
Python
jortis10/TimberPy
/timberman.py
UTF-8
1,186
2.765625
3
[]
no_license
import pygame class Timberman: def __init__(self): self.texture = pygame.image.load("Assets/timberman.png").convert_alpha() self.live = 1 self.x = 20 self.y = 512 self.action = 0 self.collide_y = 650 self.state = 0 #0 is left 1 is right def setTimberman(self): if self.action == 0: if self.state == 0: self.texture = pygame.image.load("Assets/timberman.png").convert_alpha() self.x = 110 elif self.state == 1: self.texture = self.texture = pygame.image.load("Assets/timberman.png").convert_alpha() self.texture = pygame.transform.flip(self.texture,True,False) self.x = 320 else: if self.state == 0: self.texture = pygame.image.load("Assets/timbermanaction.png").convert_alpha() self.x = 110 elif self.state == 1: self.texture = self.texture = pygame.image.load("Assets/timbermanaction.png").convert_alpha() self.texture = pygame.transform.flip(self.texture,True,False) self.x = 320
true
22d3e08ff0e9d350ec177d502fe5defa430146ec
Python
QuickTiger/PsMiss
/GetDataOfLake.py
UTF-8
570
2.640625
3
[]
no_license
#A simple scripts of Download data from TaiHu Lake import re import urllib.request f=open('data.txt','w') for i in range(60617-54291): n=i+54291 print(n) data_url="http://www.lakesci.csdb.cn/page/showItem.vpage?id=lakesci.csdb.cn.rgjc.zdhpszzdjc/"+str(n) s=urllib.request.urlopen(data_url) data=s.read().decode('utf-8') pattern=re.compile(r'(?<=6px;\" >)[\d.]+') #print(data) #print(pattern.search(data).group()) mm=pattern.findall(data) for item in mm: f.write(item+'\t') f.write('\n') f.close()
true
32fa67c5143475569df2038099b4bfe1d9ccde37
Python
cicihou/LearningProject
/leetcode-py/leetcode91.py
UTF-8
1,421
3.828125
4
[]
no_license
class Solution: def numDecodings(self, s: str) -> int: ''' method 1 memoize + recursion 如果都合法的时候,答案就是 fibbo(len(s)+1) 递归: 有多少个需要计算的值,我们可以假设取第一位或者取第二位数 base case: 当 length = 0 时,res = 1 当 s[k:] 的第一位是 0 是,表示这是一个无效的子串,所以也返回 0 res = func(length - 1) + func(length - 2) 注意 length - 2 需要判断有效性 time: O(n) space: O(n) 视频:https://www.youtube.com/watch?v=qli-JCrSwuk :param s: :return: ''' memo = {} n = len(s) def func(length): ''' k is start, length 是剩下的位数 :param string: :param length: :return: ''' if length in memo: return memo[length] if length == 0: return 1 k = n - length if s[k] == '0': return 0 res = func(length-1) if length >= 2 and int(s[k:k+2]) <= 26: # 判断有效性 res += func(length-2) memo[length] = res return res return func(n) ''' method 2 DP ''' # TODO
true
26c6f8211fec591940f5d043aa4cf9fd53ee0d21
Python
kkhaveabigdream/iot-device
/apps/tests/labs/Module02Test.py
UTF-8
2,832
2.734375
3
[]
no_license
""" Test class for all requisite Module02 functionality. Instructions: 1) Rename 'testSomething()' method such that 'Something' is specific to your needs; add others as needed, beginning each method with 'test...()'. 2) Add the '@Test' annotation to each new 'test...()' method you add. 3) Import the relevant modules and classes to support your tests. 4) Run this class as unit test app. 5) Include a screen shot of the report when you submit your assignment. Please note: While some example test cases may be provided, you must write your own for the class. """ import unittest from labs.common.ConfigUtil import ConfigUtil from labs.module02.TempSensorEmulatorTask import TempSensorEmulatorTask from labs.common.SensorData import SensorData class Module02Test(unittest.TestCase): """ Use this to setup your tests. This is where you may want to load configuration information (if needed), initialize class-scoped variables, create class-scoped instances of complex objects, initialize any requisite connections, etc. """ def setUp(self): self.config = ConfigUtil() self.config.loadConfig('../../../config/ConnectedDevicesConfig.props') self.tempsensor = TempSensorEmulatorTask() self.sensordata = SensorData() self.sensordata.addValue(10) self.sensordata.addValue(15) self.sensordata.addValue(20) self.sensordata.setName('Temperature') """ Use this to tear down any allocated resources after your tests are complete. This is where you may want to release connections, zero out any long-term data, etc. """ def tearDown(self): pass """ Place your comments describing the test here. """ def testloadConfig(self): self.assertTrue(self.config.loadConfig('../../../config/ConnectedDevicesConfig.props') ) def testhasConfigData(self): self.assertTrue(self.config.hasConfigData()) def testgetValue(self): self.assertEqual(self.config.getValue("smtp.cloud","port"), '465') def testgetSensorData(self): assert self.tempsensor.getSensorData()>0 and self.tempsensor.getSensorData()<30 def testgetAverageValue(self): assert self.sensordata.getAverageValue()>0 and self.sensordata.getAverageValue()<30 def testgetCount(self): self.assertEqual(self.sensordata.getCount(),3) def testgetCurrentValue(self): assert self.sensordata.getCurrentValue()>0 and self.sensordata.getCurrentValue()<30 def testMinValue(self): assert self.sensordata.getMinValue()>=0 and self.sensordata.getMinValue()<30 def testMaxValue(self): assert self.sensordata.getMaxValue()>0 and self.sensordata.getMaxValue()<30 def testName(self): self.assertEqual(self.sensordata.getName(), 'Temperature') if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
true
fd5761d363100f436c43d3c71115288eafad1c71
Python
AmrGNegm/Code-Wars
/Python/3- Jaden Casing Strings2.py
UTF-8
88
3.03125
3
[]
no_license
def toJadenCase(string): return ' '.join(i.capitalize() for i in string.split(" "))
true
9fd7585aa38c288df9178a6c0c3df6adb762d297
Python
weizhixiaoyi/text-similarity
/similarity.py
UTF-8
2,079
3.265625
3
[]
no_license
import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from scipy.linalg import norm def tf_cosine_similarity(str1, str2): """tf cosine similarity Parameters ---------- str1: string1 str2: string2 Returns ------- similarity """ s1, s2 = ' '.join(list(str1)), ' '.join(list(str2)) cv = CountVectorizer(tokenizer=lambda s: s.split()) corpus = [s1, s2] vectors = cv.fit_transform(corpus).toarray() tf_cos = np.dot(vectors[0], vectors[1]) / (norm(vectors[0]) * norm(vectors[1])) return tf_cos def tfidf_consine_similarity(str1, str2): """tfidf cosine similarity Parameters ---------- str1: string1 str2: string2 Returns ------- similarity """ s1, s2 = ' '.join(list(str1)), ' '.join(list(str2)) corpus = [s1, s2] cv = CountVectorizer(tokenizer=lambda s: s.split()) vector = cv.fit_transform(corpus).toarray() transform = TfidfTransformer() tfidf = transform.fit_transform(vector).toarray() vector1, vector2 = tfidf[0][::-1], tfidf[1][::-1] tfidf_cos = np.dot(vector1, vector2) / (norm(vector1) * norm(vector2)) return tfidf_cos def word_in_str_similarity(str1, str2): """tfidf cosine similarity Parameters ---------- str1: string1 str2: string2 Returns ------- similarity """ str1 = ''.join(set(str1.replace(' ', ''))) str2 = ''.join(set(str2.replace(' ', ''))) if len(str1) > len(str2): str1, str2 = str2, str1 common_word = 0 for i in range(0, len(str1)): if str1[i] in str2: common_word += 1 similarity = common_word / len(str2) return similarity if __name__ == '__main__': str1 = '车子进水了 怎么办' str2 = '车子进水了 怎么办 啊啊啊啊啊啊' ans1 = tf_cosine_similarity(str1, str2) ans2 = tfidf_consine_similarity(str1, str2) ans3 = word_in_str_similarity(str1, str2) print(ans1) print(ans2) print(ans3)
true
1dd819a78be2b0daf08be92d116632271094d9b0
Python
demetriushenry/opencv-python-samples
/obj_measurement.py
UTF-8
4,079
2.953125
3
[]
no_license
import sys import cv2 import numpy as np def reorder(points): new_points = np.zeros_like(points) points = points.reshape((4, 2)) add_point = points.sum(1) new_points[0] = points[np.argmin(add_point)] new_points[3] = points[np.argmax(add_point)] diff = np.diff(points, axis=1) new_points[1] = points[np.argmin(diff)] new_points[2] = points[np.argmax(diff)] return new_points def warp_img(img, points, w, h, pad=20): points = reorder(points) pts1 = np.float32(points) pts2 = np.float32([0, 0], [w, 0], [0, h], [w, h]) matrix = cv2.getPerspectiveTransform(pts1, pts2) img_warp = cv2.warpPerspective(img, matrix, (w, h)) img_warp = img_warp[ pad:img_warp.shape[0] - pad, pad:img_warp.shape[1] - pad ] return img_warp def find_distance(pts1, pts2): # using Pythagorean theorem return ((pts2[0] - pts1[0]) ** 2 + (pts2[1] - pts1[1]) ** 2) ** 0.5 def get_contours(img, thr1=100, thr2=100, show_cany=False, min_area=1000, filter=0, show_cnts=False): kernel = (5, 5) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, kernel, 1) canny = cv2.Canny(blur, thr1, thr2) kernel = np.ones((5, 5)) dilate = cv2.dilate(canny, kernel, iterations=3) erode = cv2.erode(dilate, kernel, iterations=2) if show_cany: cv2.imshow('Canny Image', erode) cnts, _ = cv2.findContours(erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) final_cnts = [] for i in cnts: area = cv2.contourArea(i) if area > min_area: perimeter = cv2.arcLength(i, True) approx = cv2.approxPolyDP(i, 0.02 * perimeter, True) bbox = cv2.boundingRect(approx) cnt = [len(approx), area, approx, bbox, i] if filter > 0: if len(approx) == filter: final_cnts.append(cnt) else: final_cnts.append(cnt) final_cnts = sorted(final_cnts, key=lambda x: x[1], reverse=True) if show_cnts: for cnt in final_cnts: color = (0, 0, 255) cv2.drawContours(img, cnt[4], -1, color, 3) return img, final_cnts def main(): scale = 3 A4_w = 210 * scale # mm A4_h = 297 * scale # mm path = 'images/A4-paper.jpeg' img = cv2.imread(path) img_cnts, cnts = get_contours(img, min_area=50000, filter=4) if len(cnts) != 0: print('entrou') biggest = cnts[0][2] img_warp = warp_img(img, biggest, A4_w, A4_h) img_cnts2, cnts2 = get_contours( img_warp, min_area=2000, filter=4, thr1=50, thr2=50, show_cnts=False ) if len(cnts) != 0: for obj in cnts2: cv2.polylines(img_cnts2, [obj[2]], True, (0, 255, 0), 2) nPoints = reorder(obj[2]) pts1 = nPoints[0][0] // scale pts2 = nPoints[1][0] // scale pts3 = nPoints[2][0] // scale nW = round((find_distance(pts1, pts2) / 10), 1) nH = round((find_distance(pts1, pts3) / 10), 1) cv2.arrowedLine(img_cnts2, (nPoints[0][0][0], nPoints[0][0][1]), (nPoints[1][0][0], nPoints[1][0][1]), (255, 0, 255), 3, 8, 0, 0.05) cv2.arrowedLine(img_cnts2, (nPoints[0][0][0], nPoints[0][0][1]), (nPoints[2][0][0], nPoints[2][0][1]), (255, 0, 255), 3, 8, 0, 0.05) x, y, w, h = obj[3] cv2.putText(img_cnts2, '{}cm'.format(nW), (x + 30, y - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5, (255, 0, 255), 2) cv2.putText(img_cnts2, '{}cm'.format(nH), (x - 70, y + h // 2), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5, (255, 0, 255), 2) cv2.imshow('A4', img_cnts2) img = cv2.resize(img, (0, 0), None, 0.5, 0.5) cv2.imshow('Original', img) cv2.waitKey(0) if __name__ == "__main__": sys.exit(main())
true
097b5f46bf9a6494f70d900e6aba59259a490d8e
Python
OneOverCosine/data_collections
/lists_and_tuples.py
UTF-8
1,076
4.40625
4
[]
no_license
# What is a list? # # Lists are commonly used to store related data shopping_list = ["bread", "chocolate", "avocados", "milk"] # print(shopping_list) # print(shopping_list[0]) # shopping_list[0] = "orange" # shopping_list.append("apple juice") # shopping_list.pop(0) # print(shopping_list) mixed_list = [1, 2, 3, "one", "two", "three"] # print(mixed_list) # weekdays_de = ("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag") # # weekdays_de[0] = "Monday" # causes an error # print(weekdays_de) # # This works, but probably isn't very useful as is # odd_items = [shopping_list, mixed_list, weekdays_de] # print(odd_items) # prompted by a question # tuple_of_lists = (shopping_list, mixed_list) # print(tuple_of_lists) # tuple_of_lists[0][1] = "M 'n Ms" # print(tuple_of_lists) # Using sets and frozen sets s_shopping_list = set(shopping_list) fs_shopping_list = frozenset(shopping_list) print(s_shopping_list) print(fs_shopping_list) s_shopping_list.add("pain au chocolat") #fs_shopping_list.add("pain au chocolat)") # throws an error print(s_shopping_list)
true
76c456e9e71dde3f83b2cb8d0be4fe5b09af9073
Python
melnikova12/Repository
/hw4/hw4.py
UTF-8
427
3.65625
4
[]
no_license
#вариант 1 - найти среднее число слов в строке with open("/Users/melnikovaarina/Desktop/stranger_things.txt", encoding="utf-8") as f: text = f.read() text = text.replace("\ufeff","") lines = text.splitlines() al = 0 st = 0 for x in lines: st += 1 length = len(x.split()) al += length print("Среднее число слов в строке: ", int(al/st))
true
79a7f8667fd6e05c3fc81161fc1be091fd202d79
Python
DanielFL0/Learning-Python
/exercise3-3.py
UTF-8
586
4.5625
5
[]
no_license
#3-3 Your own list; Think of your favorite mode of transportation, such as a motorcycle or a car, and make a list that stores several examples. Use your list to print a series of statements about these items, such as "I would like to own a Honda motorcycle." items = ['Porsche 911', 'Corvette Z06', 'Norton Commando 961', 'Jetski', 'Water Jetpack'] print("I would like to own a " + items[0]) print("My favorite car is the " + items[1]) print("My favorite motorcycle is the " + items[2]) print("I think it would be fun to ride a " + items[3]) print("I would like to own a " + items[4])
true
397745585418608cb2ed5ebe581b294e957aac15
Python
jelee0621/eon_hw
/train.py
UTF-8
5,881
3.015625
3
[]
no_license
import copy f = open("C:/Users/ADmin/Desktop/eonhw/TrainList.txt", 'r') TrainList=[] indlist = [] while True: tl = f.readline().split() TrainList.append(tl) if not tl: break f.close() del TrainList[0] del TrainList[len(TrainList)-1] modyTrainList = copy.deepcopy(TrainList) reservation_list = [] ind = None for i in range(20): #범위 20까지 del modyTrainList[i][2] modyTrainList[i][0] = modyTrainList[i][0].replace(":","") modyTrainList[i][0] = int(modyTrainList[i][0]) def close_time(mytime, time_list): #가까운 시간 찾기 a = mytime b = time_list.copy() real_time_list = [605,635,715,842] abs_list = [] for i in range(len(b)): abs_list.append(abs(a-b[i])) ind = abs_list.index(min(abs_list)) return real_time_list[ind] class TRAIN: def menu1(self): #기차 검색 , 예매 des_train = list(input("\n====== 원하는 시간(YY:MM), 출발역, 도착역, 열차종류 입력 ('빈칸'으로 구분) ======\n※ 뒤로가기 : 아무키 입력 ※\n※ 입력이 잘못되면 뒤로갑니다 ※\n입력 : ").split()) tmp_TrainList = copy.deepcopy(modyTrainList) for i in range(20): tmp_TrainList[i].pop() time_list = [365,395,435,522] tmp_mytime = int(des_train[0].replace(":","")) a, b = divmod(tmp_mytime, 100) #a,b 몫, 나머지 mytime = a*60+b des_train[0] = close_time(mytime, time_list) closed_T = [] for i in range(20): if tmp_TrainList[i] == des_train: closed_T = tmp_TrainList[i].copy() closed_T.append(TrainList[i][5]) ind = i print('\n===== 가장 가까운 시간의 기차 정보 =====\n| 시간 | 출발 | 도착 | 열차종류 | 잔여석 수 |') a, b = divmod(closed_T[0], 100) a = str(a) b = str(b) if int(b)//10 == 0: closed_T[0] = ''.join(['0', a, ':','0', b]) else: closed_T[0] = ''.join(['0', a, ':', b]) print('|', end=' ') for a in closed_T: print(a,end = ' | ') while True: reservation = input('\n해당 기차표를 예매하시겠습니까? [Y/N]\n입력 : ') if reservation == 'Y': if TrainList[ind][5] != '매진': reservation_list.append(TrainList[ind]) TrainList[ind][5] = int(TrainList[ind][5])-1 #예매를 완료하면 표를 하나 줄여나간다 print('\n예매가 완료되었습니다.') indlist.append(ind) if TrainList[ind][5] == 0: #남아있는 표의 수가 0이 되면 TrainList[ind][5] = '매진' #매진 break else: print('\n해당 표는 매진되었습니다. 초기메뉴로 돌아갑니다.') break elif reservation == 'N': #예매하지 않음 print('\n처음 화면으로 돌아갑니다.') break else: print('Y 또는 N을 입력해주세요.') return ind def menu2(self): #전체 기차리스트를 출력 print('\n= 기차 시간표 =','시간_출발_도착_열차종류_잔여좌석수','--',sep='\n') i = 0 while i < len(TrainList): a,b,c,d,e,f = TrainList[i] print(a,b,c,d,e,f) i += 1 def menu3(self): if ind == None: #예매내역 없음 print('\n예매된 기차가 없습니다.') elif reservation_list == []: print('\n예매된 기차가 없습니다.') else: print('\n[ 예매 완료 ]\n','======== 기차 정보 ========',sep='\n') i = 0 while i < len(reservation_list): a,b,c,d,e,f = reservation_list[i] print(a,b,c,d,e) #예약된 순번까지 하나씩 프린트 i += 1 cancle = input('\n예매를 취소하시겠습니까? [Y/N]\n※ 뒤로가기 : 아무키나 입력 ※\n입력 : ') if cancle == 'Y': if TrainList[indlist[len(indlist)-1]][5] == '매진': TrainList[indlist[len(indlist)-1]][5] = 1 reservation_list.pop() else: TrainList[indlist[len(indlist)-1]][5] = TrainList[indlist[len(indlist)-1]][5] + 1 #취소되어 표 증가 reservation_list.pop() indlist.pop() print('\n취소가 완료되었습니다.') else: print('\n처음 화면으로 돌아갑니다.') while True: print('\n======메뉴======') print('1. 빠른시간 기차 검색 및 예매') print('2. 전체 기차 리스트 출력') print('3. 나의 예매 현황 출력 및 예매 취소') print('4. 프로그램 종료') number = input("수를 입려해 주세요 ") train = TRAIN() try: if number == '1': ind = train.menu1() elif number == '2': train.menu2() elif number == '3': train.menu3() elif number == '4': print('프로그램을 종료합니다.') break elif number == '5': number = 5 print('최상위 메뉴입니다.') else: print('없는 메뉴 번호입니다.') except: print('처음 화면으로 돌아갑니다.')
true
2caf5525418d0e68462da3eb77c4d0a7dda0f8f0
Python
kxmdxhxx/Biometrics
/TrafficLight.py
UTF-8
411
2.5625
3
[]
no_license
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(3, GPIO.OUT) # Blue LED GPIO.output(3, GPIO.HIGH) time.sleep(2) GPIO.output(3, GPIO.LOW) GPIO.setup(5, GPIO.OUT) # Yellow LED GPIO.output(5, GPIO.HIGH) time.sleep(2) GPIO.output(5, GPIO.LOW) GPIO.setup(7, GPIO.OUT) # White LED GPIO.output(7, GPIO.HIGH) time.sleep(2) GPIO.output(7, GPIO.LOW) time.sleep(2) GPIO.cleanup()
true
4dbd7e8ee2e86524c6a148b807715f2fabe35d33
Python
brantseibert/diabetesMonitor
/human_body.py
UTF-8
850
3.234375
3
[]
no_license
import datetime import threading import time from food import Food from timezone import MST class HumanBody: def __init__(self): ## insulin usage variables self.carbs_on_board = [] self.clear = threading.Thread( target=self.clearOldCarbs ) self.clear.setDaemon(True) self.clear.start() ## Methods dealing with boluses def eat(self, start_time, carbs): self.carbs_on_board.append( Food(start_time,carbs) ) def getTotalCarbsOnBoard(self): total = 0 for meals in self.carbs_on_board: total += meals.getCarbs() return total def clearOldCarbs(self): while(True): current_time = datetime.datetime.now(MST()) old_meals = [] for meals in self.carbs_on_board: if( current_time > meals.getEndTime() ): old_meals.append(meals) for old in old_meals: self.carbs_on_board.remove(old) time.sleep(10)
true
0470a40bc835066890f68f867ecc6a453333ea84
Python
xaedes/OttoCar-PC
/src/ottocar_utils/scripts/ottocar_utils/window.py
UTF-8
1,562
2.765625
3
[]
no_license
#!/usr/bin/env python import rospy from ottocar_utils.measure_sample_rate import MeasureSampleRate import numpy as np class Window(object): """docstring for Window""" def __init__(self, window_size = 10, n_signals = 1): super(Window, self).__init__() self.window_size = window_size self.n_signals = n_signals # TODO rename signals to channels self._buffer = np.zeros(shape=(self.window_size, self.n_signals)) # internal buffer where data is stored self.pointer = 0 self.sample_rate = MeasureSampleRate(10,gain=0.5) def add_sample(self,signals): self.sample_rate.add_sample() if not self.is_full(): self._buffer[self.pointer] = signals self.pointer += 1 else: self._buffer = np.roll(self._buffer,-1,axis=0) self._buffer[-1] = signals def is_full(self): return self.pointer == self._buffer.shape[0] # the last window_size items def window(self): return self._buffer[-self.window_size:,:] def set_window_size(self,new_window_size): if new_window_size > self._buffer.shape[0]: # increase buffer # print self._buffer.shape # print np.zeros(shape=(new_window_size - self._buffer.shape[0],self.n_signals)).shape self._buffer = np.vstack([self._buffer, np.zeros(shape=(new_window_size - self._buffer.shape[0],self.n_signals))]) self.pointer = self._buffer.shape[0] - 1 self.window_size = new_window_size
true
e50e203efe195220c2117ef1849c048a24f59ebf
Python
17390089054/Python
/Python3WorkSpace/Unit6/iftest.py
UTF-8
2,405
3.25
3
[]
no_license
color='red' if color=='green': print("You have got 5 points\n") elif color=='yellow': print("You have got 10 points\n") else: print("You have got 15 points\n") #5-7 favorite_fruits=['banana','apple','orange'] if 'banana' in favorite_fruits: print("You really like bananas!\n") #5-7-1 request_toppings=[] if request_toppings: for request_topping in request_toppings: if request_topping == 'green paper': print("Sorry,We are out of green papers right now.") else: print("Adding "+request_topping +".") print("\n Finished making your pizza!") #test avaliable_toppings=['mushroom','olives','green papers','pepperoni','pineapple','extra cheese'] request_toppings=['mushroom','french fries','extra cheese'] for request_topping in request_toppings: if request_topping in avaliable_toppings: print("Adding "+request_topping+".") else: print("Sorry,We don't have "+request_topping+".") print("\nFinished making your pizza!\n") #5-8 users=['admin','root','mike','loser','lily'] for user in users: if user=='admin': print("Hello "+user+" would you like to see a status report?\n") else: print("Hello "+user+" thank you for your logging in again!\n") #5-9 users=[] if users: for user in users: if user=='admin': users.pop() print("Hello "+user+" would you like to see a status report?\n") else: users.pop() print("Hello "+user+" thank you for your logging in again!\n") else: print("We need to find some users\n") #5-10 current_users=['Mike','John','Lucy','Lily','Jenny'] new_users=['Mike','Lucy','kite','lucy','phton'] for user in new_users: if user in current_users or user.upper() in current_users or user.lower() in current_users or user.title() in current_users: print("The user "+user+" has existed!You have to input another user") else: print("The user "+user+" has not used!") #5-11 print("\n") numbers=[val for val in range(1,10)] for number in numbers: if number == 1: print("1st") elif number == 2: print("2nd") elif number == 3: print("3rd") else: print(str(number)+"th") print("\n")
true
ce29b5510bd003b165ea966aaaab7078e1439115
Python
arthur37231/bilibili-followers-checker
/database/base_handler.py
UTF-8
1,345
2.59375
3
[ "MIT" ]
permissive
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from .schema import Base class BaseHandler(object): _Session = None @staticmethod def _make_connection_url(**kwargs): host = kwargs.get('host') port = kwargs.get('port') user = kwargs.get('user') dbname = kwargs.get('db_name') password = kwargs.get('db_password') return f'postgresql://{user}:{password}@{host}:{port}/{dbname}' @staticmethod def create_connection(conf): _engine = create_engine(BaseHandler._make_connection_url(**conf)) BaseHandler._Session = sessionmaker(bind=_engine) # Define table Base.metadata.create_all(bind=_engine) def __init__(self, *args, **kwargs): self._session = None def update_obj(self, obj): self._session.add(obj) def __enter__(self): self.connect() def __exit__(self, exception_type, exception_value, traceback): self.disconnect() def connect(self): self._session = BaseHandler._Session() def disconnect(self, is_error=False): if self._session is not None: if not is_error: self._session.commit() self._session.close() self._session = None def commit(self): self._session.commit()
true
9f0ede206b2ab8c63b90e39aa37b6b99c6fbadb6
Python
CIgnacio-dev/Ejercicios-b-sicos-py
/if.py
UTF-8
471
3.609375
4
[]
no_license
import random aleatorios = [random.randint(1,6) for _ in range(2)] print(aleatorios) s=sum(aleatorios) print ('La suma de los números es', s) ask=int(input('¿Desea lanzar el dado otra vez? Ingresa 1 para Sí o cualquier otro número para No ')) if ask==1: aleatorios = [random.randint(1,6) for _ in range(2)] print(aleatorios) s=sum(aleatorios) print ('La suma de los números es', s) else: print('adiós')
true
1fc5abb3271d4f43bc63251c92b1561a35fa9834
Python
HenriTammo/OMIS
/tund8/htmlKirjutamine.py
UTF-8
231
2.578125
3
[]
no_license
file = open("tund8/näide.html", "w") ülemine = """<html> <head></head> <body><p>""" sisestus = input("ütle midagi") alumine = """</p></body> </html>""" file.write(ülemine) file.write(sisestus) file.write(alumine) file.close()
true
3a3c710e20ab634bfd7166018e4baed626d662d5
Python
jerrybelmonte/DataStructures-Python
/job_queue.py
UTF-8
1,092
3.515625
4
[ "MIT" ]
permissive
# Parallel Processing # Author: jerrybelmonte from collections import namedtuple from heapq import heapify, heappop, heappush AssignedJob = namedtuple('AssignedJob', ['worker', 'started_at']) def assign_jobs(n_workers: int, jobs: list): """ Uses n independent threads to process a given list of jobs. :param n_workers: number of threads :param jobs: list of job query times :return: list of ith thread and time started >>> assign_jobs(2, [1, 2, 3, 4, 5]) [(0, 0), (1, 0), (0, 1), (1, 2), (0, 4)] """ pq = [(0, w) for w in range(n_workers)] heapify(pq) result = [] for job in jobs: worker = heappop(pq) result.append(AssignedJob(worker[1], worker[0])) heappush(pq, (worker[0] + job, worker[1])) return result def main(): n_workers, n_jobs = map(int, input().split()) jobs = list(map(int, input().split())) assert len(jobs) == n_jobs assigned_jobs = assign_jobs(n_workers, jobs) for job in assigned_jobs: print(job.worker, job.started_at) if __name__ == "__main__": main()
true
820bee9427427240e2887854fd21b21bd0e9dbae
Python
farooq-teqniqly/py-workout
/kidslanguages.py
UTF-8
817
3.484375
3
[ "MIT" ]
permissive
from typing import Generator _vowels = ["a", "e", "i", "o", "u"] def _ensure_not_null(s: str): if s is None or len(s.strip()) == 0: raise ValueError("Input string cannot be None or empty.") def english_to_pig_latin(s: str) -> Generator[str, None, None]: _ensure_not_null(s) words = s.split(" ") for word in words: if word[0] in _vowels: yield word + "way" else: yield word[1:] + word[0] + "ay" def english_to_ubbi_dubbi(s: str) -> Generator[str, None, None]: _ensure_not_null(s) words = s.split(" ") for word in words: ubbi_dubbi = "" for letter in word: if letter in _vowels: ubbi_dubbi += "ub" + letter else: ubbi_dubbi += letter yield ubbi_dubbi
true
1d307241cfcd4a991166debf15d79c6923141759
Python
Annapoorneswarid/ANNAPOORNESWARI_D_RMCA_S1A
/Programming_Lab/27-01-2021/7a..py
UTF-8
461
3.203125
3
[]
no_license
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> >>> list1=[8,10,15,13,16,20,25,10,13,5,4,16] >>> list2=[16,4,5,13,10,25,20,16,13,15,10,8] >>> len1=len(list1) >>> len2=len(list2) >>> if len1==len2 : print('Both list have equal length') else: print('Both list doesnt have equal length') Both list have equal length >>>
true
bd8b0209ac769b080333c7138ac0e783a0b60472
Python
GabrielPenaU3F/confiabilidad-software
/src/data/data_formater.py
UTF-8
4,387
2.765625
3
[]
no_license
from abc import abstractmethod, ABC import numpy as np from src.data.formated_data import TTFFormatedData, FPDFormatedData from src.exceptions.exceptions import InvalidArgumentException class DataFormater(ABC): singleton = None @abstractmethod def give_format(self, data, optional_arguments): pass def determine_end_sample(self, data, end_sample_arg): default_end_sample = len(data.get_data()) if end_sample_arg + 1 > default_end_sample: raise InvalidArgumentException('The end sample must not exceed the length of the dataset') if 0 < end_sample_arg < default_end_sample: return end_sample_arg + 1 else: return default_end_sample def determine_initial_sample(self, data, initial_sample_arg): default_initial_sample = 0 n = len(data.get_data()) if 0 < initial_sample_arg < n - 1: return initial_sample_arg elif initial_sample_arg >= n: raise InvalidArgumentException('The initial sample must not exceed the length of the dataset') else: return default_initial_sample def determine_t0(self, times, t0_arg, start): t0 = 0 if t0_arg > t0: t0 = t0_arg elif start > 0: t0 = times[start - 1] return t0 def determine_format_parameters(self, data, optional_arguments): start = self.determine_initial_sample(data, optional_arguments.get_initial_sample()) end = self.determine_end_sample(data, optional_arguments.get_end_sample()) t0 = self.determine_t0(data.get_times(), optional_arguments.get_t0(), start) return start, end, t0 def format_times(self, times, t0): formated_times = list(np.copy(times)) formated_times.insert(0, t0) return formated_times def determine_stage_end_sample(self, data, end_t): times = data.get_times() for i in range(len(times)): if times[i] > end_t: return i - 1 return len(times) - 1 def determine_stage_initial_sample(self, data, initial_t): times = data.get_times() for i in range(len(times)): if times[i] >= initial_t: return i def determine_stage_t0(self, data, initial_t): times = list(np.copy(data.get_times())) times.insert(0, 0) for i in range(1, len(times)): if times[i] >= initial_t: return times[i - 1] @classmethod def slice_data(cls, start, end, *data_arrays): sliced = [] for data in data_arrays: if end == 0: sliced.append(list(np.copy(data))[start:]) else: sliced.append(list(np.copy(data))[start:end]) return sliced class TTFDataFormater(DataFormater): @classmethod def get_instance(cls): if cls.singleton is None: cls.singleton = TTFDataFormater() return cls.singleton def give_format(self, data, optional_arguments): start, end, t0 = self.determine_format_parameters(data, optional_arguments) sliced_ttf_original_data, sliced_cumulative_failures = DataFormater.\ slice_data(start, end, data.get_data(), data.get_cumulative_failures()) formated_ttf = self.format_times(sliced_ttf_original_data, t0) return TTFFormatedData(sliced_ttf_original_data, formated_ttf, sliced_cumulative_failures) def determine_stage_end_sample(self, data, end_t): ttfs = data.get_data() for i in range(len(ttfs)): if ttfs[i] > end_t: return i - 1 return len(ttfs) - 1 class FPDDataFormater(DataFormater): @classmethod def get_instance(cls): if cls.singleton is None: cls.singleton = FPDDataFormater() return cls.singleton def give_format(self, data, optional_arguments): start, end, t0 = self.determine_format_parameters(data, optional_arguments) sliced_original_times, sliced_cumulative_failures, sliced_fpd = DataFormater.\ slice_data(start, end, data.get_times(), data.get_cumulative_failures(), data.get_data()) formated_times = self.format_times(sliced_original_times, t0) return FPDFormatedData(sliced_original_times, formated_times, sliced_fpd, sliced_cumulative_failures)
true
643e34f549b4a59043c93c246f486d49f1fa5b86
Python
WTrygar/pp1
/02-ControlStructures/02-45.py
UTF-8
641
3.890625
4
[]
no_license
ilość = int(input("Podaj ilość liczb: ")) x = 2 spr = 0 if(ilość == 1): print("Liczby pierwsze: 2") elif(ilość == 2): print("Liczby pierwsze: 2 3") elif(ilość < 3): print("Liczby pierwsze: 2 3 5") else: x = 3 print("Liczby pierwsze: 2", end = " ") while ilość - 1 > 0: y = 2 while (y <= x ** (1/2)): if( x % y == 0): spr = 1 y = x else: y += 1 if spr == 0: print(x,end = " ") spr = 0 x += 2 ilość -= 1 else: x += 2 spr = 0
true
ad7460dfd8d8fd37fd8fb96b7f392063a00c2ed8
Python
PawelKowalskiGitHub/Clinical_Programming
/Validation of the eligibility process/Generate_files_in_Python/create_files.py
UTF-8
4,673
3.09375
3
[]
no_license
import random import pandas as pd import numpy as np country = [] site = [] subject = [] pi_assessment = [] pi_crit = [] pi_crit_num = [] cm_assessment = [] cm_desciption = [] rand_date = [] def database_generator(): global database country_id = input("Enter the country ID of the subject: ") country_text = str("country" + country_id) country.append(country_text) site_id = input("Enter the site ID of the subject: ") site_text = str("site" + site_id) site.append(site_text) subject_id = random.randint(0, 99) if subject_id < 10: subject_id = str("0" + str(subject_id)) subject_text = str("E" + country_id + site_id + str(subject_id)) while subject_text in subject: subject_id = random.randint(0, 99) if subject_id < 10: subject_id = str("0" + str(subject_id)) subject_text = str("E" + country_id + site_id + str(subject_id)) else: subject.append(subject_text) pi_assessment_text = "." while pi_assessment_text != "Eligible" and pi_assessment_text != "Ineligible" and pi_assessment_text != "": pi_assessment_text = input("Enter the PI assessment of subject eligibility (Eligible/Ineligible/nothing): ") if pi_assessment_text != "Eligible" and pi_assessment_text != "Inclusion" and pi_assessment_text != "": print("ATTENTION: You must type Eligible or Ineligible or press enter if nothing!") pi_assessment.append(pi_assessment_text) pi_crit_text = "." while pi_crit_text != "Exclusion" and pi_crit_text != "Inclusion" and pi_crit_text != "": pi_crit_text = input("Enter the assessment criterion according to the PI (Exclusion/Inclusion/nothing): ") if pi_crit_text != "Exclusion" and pi_crit_text != "Inclusion" and pi_crit_text != "": print("ATTENTION: You must type Exclusion or Inclusion or press enter if nothing!") pi_crit.append(pi_crit_text) pi_crit_num_text = input("Enter the number of criterion from PI about eligibility: ") pi_crit_num.append(pi_crit_num_text) cm_assessment_text = "." while cm_assessment_text != "Exclusion" and cm_assessment_text != "Inclusion" and cm_assessment_text != "": cm_assessment_text = input("Enter the CM assessment of subject eligibility (Exclusion/Inclusion/nothing): ") if cm_assessment_text != "Exclusion" and cm_assessment_text != "Inclusion" and cm_assessment_text != "": print("ATTENTION: You must type Exclusion or Inclusion or press enter if nothing!") cm_assessment.append(cm_assessment_text) cm_desciption_text = input("Enter the description from CM about eligibility criterion: ") cm_desciption.append(cm_desciption_text) rand_date_text = input("Enter the randomization date: ") rand_date.append(rand_date_text) #Create a Database database = pd.DataFrame({"subject": subject, "country": country, "site": site, "pi_assessment": pi_assessment, "pi_crit": pi_crit, "pi_crit_num": pi_crit_num, "cm_assessment": cm_assessment, "cm_desciption": cm_desciption, "rand_date": rand_date}) database.to_csv(r'/home/pawel/Pulpit/Programowanie/Python/Clinical Data Project/main_database.csv') return subject, country, site, pi_assessment, pi_crit, pi_crit_num, cm_assessment, cm_desciption, rand_date, database database_generator() # If you want to use a randomly generated database database = pd.read_csv (r'/home/pawel/Pulpit/Programowanie/Python/Clinical Data Project/data.csv') def creating_files(filename, columns=[], col_names = []): data = [] for i in columns: data.append(database[i]) df = pd.concat(data, axis=1, keys=col_names) df[i].replace('', np.nan, inplace=True) df.dropna(subset=[i], inplace=True) path = str(r'/home/pawel/Pulpit/Programowanie/Python/Clinical Data Project/' + filename + '.csv') return df.to_csv(path) creating_files('randomized', ['subject', 'rand_date'], ['subject', 'rand_date']) creating_files('country', ['country', 'site'], ['country', 'site']) creating_files('site', ['subject', 'site'], ['subject', 'site']) creating_files('assessment_of_pi', ['subject', 'pi_assessment'], ['subject', 'pi_assessment']) creating_files('criteria_of_pi', ['subject', 'pi_crit', 'pi_crit_num'], ['subject', 'pi_crit', 'pi_crit_num']) creating_files('assessment_of_cm', ['subject', 'cm_assessment', 'cm_desciption'], ['subject', 'cm_assessment', 'cm_desciption'])
true
96c8908d8e41094905f7233915f7c7244dc55a47
Python
benquick123/code-profiling
/code/batch-1/dn7/M-149.py
UTF-8
13,330
2.890625
3
[]
no_license
######################## # Za oceno 6 def lel(x, y, mine): k = 0 for w, q in mine: if w == x or w == (x - 1) or w == (x + 1): if q == y or q == (y - 1) or q == (y + 1): k = k + 1 return k def sosedov(x, y, mine): k = 0 for w, q in mine: if w == x or w == (x-1) or w == (x+1): if q == y or q == (y-1) or q == (y+1): if (w, q) != (x, y): k = k + 1 return k def najvec_sosedov(mine, s, v): g = (0, 0) m = 0 koord = [] for x in range(0, (s+1)): for y in range(0, (v+1)): koord.append((x, y)) for t ,z in koord: tsosedov = lel(t, z, mine) if tsosedov > m: g = (t, z) m = tsosedov return g def brez_sosedov(mine, s, v): m = set() koord = [] for x in range(0, (s)): for y in range(0, (v)): koord.append((x, y)) for t, z in koord: tsosedov = sosedov(t, z, mine) if tsosedov == 0: m.add((t, z)) return m def po_sosedih(mine, s, v): g = set() m = {} koord = [] for x in range(0, (s)): for y in range(0, (v)): koord.append((x, y)) for p in range((9)): g = set() for t, z in koord: if sosedov(t, z, mine) == p: g.add((t, z)) m.update({p: g}) return m ######################## # Za oceno 7 from math import* def razdalja_koordinat(x1, y1, x2, y2): x = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) return x pot = [(0, 0), (0, 3), (4, 3), (4, 2), (7, 2), (7, 3)] def dolzina_poti(pot): if pot == []: dolzinapoti = 0 else: dolzinapoti = 0 x1, y1 = pot[0] for x , y in pot: x2 = x y2 = y dolzinapoti = dolzinapoti + razdalja_koordinat(x1, y1, x2, y2) x1 = x2 y1 = y2 return dolzinapoti def varen_premik(x0, y0, x1, y1, mine): pot = [] if y0 == y1 and x0 == x1: pot.append((x0,x1)) if x0<x1: for x in range(x0,x1+1): pot.append((x,y0)) if x0 > x1: for x in range(x1,x0+1): pot.append((x,y0)) if y0 < y1: for y in range(y0,y1+1): pot.append((x0,y)) if y0 > y1: for y in range(y1,y0+1): pot.append((x0,y)) return not any([True for (x,y) in pot if (x,y) in mine]) def varna_pot(pot, mine): if len(pot) > 1: for (x,y),(x1,y1) in zip(pot,pot[1:]): if not varen_premik(x,y,x1,y1,mine): return False else: for premik in pot: if premik in mine: return False return True ######################## # Za oceno 8 def polje_v_mine(polje): """ Vrni koordinate min v podanem polju. Niz polje opisuje polje tako, da so vodoravne "vrstice" polja ločene s presledki. Prosta polja so označena z znako `.`, mine z `X`. Args: polje (str): polje Returns: mine (set of tuple of int): koordinate min s (int): širina polja v (int): višina polja. """ ######################## # Za oceno 9 # # Vse funkcije za oceno 6 in 7 morajo biti napisane v eni vrstici. ######################## # Za oceno 10 def preberi_pot(ukazi): """ Za podani seznam ukazov (glej navodila naloge) vrni pot. Args: ukazi (str): ukazi, napisani po vrsticah Returns: list of tuple of int: pot """ def zapisi_pot(pot): """ Za podano pot vrni seznam ukazov (glej navodila naloge). Args: pot (list of tuple of int): pot Returns: str: ukazi, napisani po vrsticah """ import unittest """ ...X.... .X....X. .XX..... ......X. """ mine1 = {(3, 0), (1, 1), (6, 1), (1, 2), (2, 2), (6, 3)} s1, v1 = 8, 4 """ ........ ........ ........ """ mine2 = set() s2, v2 = 8, 3 """ ...X...X.X....X. """ mine3 = {(3, 0), (7, 0), (9, 0), (14, 0)} s3, v3 = 16, 1 """ X """ mine4 = {(0, 0)} s4, v4 = 1, 1 """ X . . X . X . """ mine5 = {(0, 0), (0, 3), (0, 5)} s5, v5 = 1, 7 class Test06(unittest.TestCase): def test_01_sosedov(self): self.assertEqual(sosedov(2, 1, mine1), 4) self.assertEqual(sosedov(0, 3, mine1), 1) self.assertEqual(sosedov(4, 3, mine1), 0) self.assertEqual(sosedov(4, 2, mine1), 0) self.assertEqual(sosedov(0, 0, mine1), 1) self.assertEqual(sosedov(7, 0, mine1), 1) self.assertEqual(sosedov(3, 0, mine1), 0) self.assertEqual(sosedov(2, 2, mine2), 0) self.assertEqual(sosedov(0, 0, mine2), 0) self.assertEqual(sosedov(0, 0, mine2), 0) self.assertEqual(sosedov(0, 0, mine3), 0) self.assertEqual(sosedov(2, 0, mine3), 1) self.assertEqual(sosedov(3, 0, mine3), 0) self.assertEqual(sosedov(8, 0, mine3), 2) self.assertEqual(sosedov(0, 0, mine4), 0) self.assertEqual(sosedov(0, 0, mine5), 0) self.assertEqual(sosedov(0, 1, mine5), 1) self.assertEqual(sosedov(0, 2, mine5), 1) self.assertEqual(sosedov(0, 3, mine5), 0) self.assertEqual(sosedov(0, 4, mine5), 2) self.assertEqual(sosedov(0, 5, mine5), 0) self.assertEqual(sosedov(0, 6, mine5), 1) def test_02_najvec_sosedov(self): self.assertEqual(najvec_sosedov(mine1, s1, v1), (2, 1)) x, y = najvec_sosedov(mine2, s2, v2) self.assertTrue(0 <= x < s2) self.assertTrue(0 <= y < v2) self.assertEqual(najvec_sosedov(mine3, s3, v3), (8, 0)) self.assertEqual(najvec_sosedov(mine4, s4, v4), (0, 0)) self.assertEqual(najvec_sosedov(mine5, s5, v5), (0, 4)) def test_03_brez_sosedov(self): self.assertEqual(brez_sosedov(mine1, s1, v1), {(3, 0), (4, 2), (6, 1), (6, 3), (4, 3)}) self.assertEqual(brez_sosedov(mine2, s2, v2), {(x, y) for x in range(s2) for y in range(v2)}) self.assertEqual(brez_sosedov(mine3, s3, v3), {(x, 0) for x in (0, 1, 3, 5, 7, 9, 11, 12, 14)}) self.assertEqual(brez_sosedov(mine4, s4, v4), {(0, 0)}) self.assertEqual(brez_sosedov(mine5, s5, v5), {(0, 0), (0, 3), (0, 5)}) def test_04_po_sosedih(self): self.assertEqual(po_sosedih(mine1, s1, v1), {0: {(3, 0), (4, 2), (6, 1), (6, 3), (4, 3)}, 1: {(7, 3), (3, 2), (0, 0), (7, 0), (3, 3), (7, 1), (4, 0), (6, 0), (5, 0), (5, 3), (5, 1), (1, 0), (4, 1), (0, 3)}, 2: {(0, 1), (1, 2), (1, 3), (0, 2), (3, 1), (2, 0), (6, 2), (2, 3), (2, 2), (5, 2), (1, 1), (7, 2)}, 3: set(), 4: {(2, 1)}, 5: set(), 6: set(), 7: set(), 8: set()} ) prazen = dict.fromkeys(range(9), set()) prazen[0] = {(x, y) for x in range(s2) for y in range(v2)} self.assertEqual(po_sosedih(mine2, s2, v2), prazen) s = dict.fromkeys(range(9), set()) s.update({0: {(9, 0), (0, 0), (7, 0), (12, 0), (3, 0), (11, 0), (14, 0), (5, 0), (1, 0)}, 1: {(15, 0), (6, 0), (2, 0), (10, 0), (13, 0), (4, 0)}, 2: {(8, 0)}}) self.assertEqual(po_sosedih(mine3, s3, v3), s) s = dict.fromkeys(range(9), set()) s.update({0: {(9, 0), (0, 0), (7, 0), (12, 0), (3, 0), (11, 0), (14, 0), (5, 0), (1, 0)}, 1: {(15, 0), (6, 0), (2, 0), (10, 0), (13, 0), (4, 0)}, 2: {(8, 0)}}) self.assertEqual(po_sosedih(mine3, s3, v3), s) s = dict.fromkeys(range(9), set()) s[0] = {(0, 0)} self.assertEqual(po_sosedih(mine4, s4, v4), s) s = dict.fromkeys(range(9), set()) s.update({0: {(0, 3), (0, 0), (0, 5)}, 1: {(0, 1), (0, 6), (0, 2)}, 2: {(0, 4)}}) self.assertEqual(po_sosedih(mine5, s5, v5), s) class Test07(unittest.TestCase): def test_01_dolzina_poti(self): self.assertEqual(dolzina_poti([(7, 2), (7, 5)]), 3) self.assertEqual(dolzina_poti([(7, 5), (7, 2)]), 3) self.assertEqual(dolzina_poti([(7, 5), (4, 5)]), 3) self.assertEqual(dolzina_poti([(1, 5), (4, 5)]), 3) self.assertEqual( dolzina_poti([(0, 0), (0, 3), (4, 3), (4, 2), (7, 2), (7, 3)]), 3 + 4 + 1 + 3 + 1) self.assertEqual( dolzina_poti([(0, 3), (4, 3), (4, 2), (7, 2), (7, 3)]), 4 + 1 + 3 + 1) self.assertEqual( dolzina_poti([(0, 0), (0, 1), (3, 1)]), 1 + 3) self.assertEqual(dolzina_poti([(5, 3)]), 0) self.assertEqual(dolzina_poti([]), 0) """ ...X.... .X....X. .XX..... ......X. """ def test_02_varen_premik(self): self.assertTrue(varen_premik(3, 1, 3, 3, mine1)) self.assertTrue(varen_premik(3, 3, 3, 1, mine1)) self.assertTrue(varen_premik(4, 0, 7, 0, mine1)) self.assertTrue(varen_premik(7, 0, 4, 0, mine1)) self.assertTrue(varen_premik(2, 1, 5, 1, mine1)) self.assertTrue(varen_premik(5, 1, 2, 1, mine1)) self.assertFalse(varen_premik(2, 1, 6, 1, mine1)) self.assertFalse(varen_premik(6, 1, 2, 1, mine1)) self.assertFalse(varen_premik(1, 1, 5, 1, mine1)) self.assertFalse(varen_premik(5, 1, 1, 1, mine1)) self.assertFalse(varen_premik(0, 1, 4, 1, mine1)) self.assertFalse(varen_premik(4, 1, 0, 1, mine1)) self.assertFalse(varen_premik(2, 1, 2, 3, mine1)) self.assertFalse(varen_premik(2, 3, 2, 1, mine1)) self.assertFalse(varen_premik(2, 1, 2, 2, mine1)) self.assertFalse(varen_premik(2, 2, 2, 1, mine1)) self.assertFalse(varen_premik(2, 2, 2, 0, mine1)) self.assertFalse(varen_premik(2, 0, 2, 2, mine1)) self.assertFalse(varen_premik(1, 1, 1, 1, mine1)) """ ...X.... .X....X. .XX..... ......X. """ def test_03_varna_pot(self): self.assertTrue(varna_pot([(0, 0), (0, 3), (4, 3), (4, 2), (7, 2), (7, 3)], mine1)) self.assertTrue(varna_pot([(0, 3), (4, 3), (4, 2), (7, 2), (7, 3)], mine1)) self.assertTrue(varna_pot([(2, 1)], mine1)) self.assertTrue(varna_pot([], mine1)) self.assertFalse(varna_pot([(0, 0), (0, 1), (3, 1)], mine1)) self.assertFalse(varna_pot([(0, 0), (1, 0), (1, 3)], mine1)) self.assertFalse(varna_pot([(0, 0), (1, 0), (0, 0), (1, 0), (1, 3), (3, 3)], mine1)) self.assertFalse(varna_pot([(1, 1)], mine1)) class Test08(unittest.TestCase): def test_01_polje_v_mine(self): # Če si sledi več nizov, med katerimi ni ničesar, jih Python zlepi # ".X. " "..X" je isto kot ".X. ...". self.assertEqual(polje_v_mine("...X.... " ".X....X. " ".XX..... " "......X."), (mine1, s1, v1)) self.assertEqual(polje_v_mine("........ " "........ " "........"), (mine2, s2, v2)) self.assertEqual(polje_v_mine("...X...X.X....X."), (mine3, s3, v3)) self.assertEqual(polje_v_mine("X"), (mine4, s4, v4)) self.assertEqual(polje_v_mine("X " ". " ". " "X " ". " "X " "."), (mine5, s5, v5)) class Test10(unittest.TestCase): def test_01_preberi_pot(self): self.assertEqual( preberi_pot( """DESNO DESNO 3 LEVO 4 LEVO 1 DESNO 3 DESNO 1"""), [(0, 0), (0, 3), (4, 3), (4, 2), (7, 2), (7, 3)]) self.assertEqual( preberi_pot( """DESNO LEVO DESNO DESNO DESNO DESNO DESNO 3"""), [(0, 0), (3, 0)]) self.assertEqual( preberi_pot( """LEVO DESNO LEVO LEVO LEVO LEVO DESNO 3"""), [(0, 0), (3, 0)]) self.assertEqual( preberi_pot( """LEVO DESNO LEVO LEVO LEVO LEVO DESNO 3"""), [(0, 0), (3, 0)]) self.assertEqual( preberi_pot( """DESNO 3 DESNO 3 DESNO 3 DESNO 3"""), [(0, 0), (3, 0), (3, 3), (0, 3), (0, 0)]) self.assertEqual( preberi_pot( """DESNO 1 DESNO DESNO 1 LEVO LEVO 1 DESNO 3 LEVO 2 DESNO DESNO"""), [(0, 0), (1, 0), (0, 0), (1, 0), (1, 3), (3, 3)]) def test_02_zapisi_pot(self): pot = [(0, 0), (3, 0)] self.assertEqual(preberi_pot(zapisi_pot(pot)), pot) pot = [(0, 0), (3, 0), (3, 3)] self.assertEqual(preberi_pot(zapisi_pot(pot)), pot) pot = [(0, 0), (3, 0), (3, 3), (3, 5), (5, 5), (5, 1), (4, 1), (6, 1), (6, 8), (6, 3)] self.assertEqual(preberi_pot(zapisi_pot(pot)), pot) pot = [(0, 0), (0, 3), (4, 3), (4, 2), (7, 2), (7, 3)] self.assertEqual(preberi_pot(zapisi_pot(pot)), pot) if __name__ == "__main__": unittest.main()
true
c727e054d5b7db8dd945123b246db97602866c81
Python
nwgdegitHub/python3_learning
/14-字符串的常用方法之修改.py
UTF-8
1,422
4.5
4
[]
no_license
# str.replace(oldStr,newStr,count) mystr = " my name is Liu Wei,My age is 30, My name is LW " print(mystr.replace("name","name2",3)) print("split()分割 返回一个列表") print(mystr.split("is",2)) #前2个生效 print("join()合并列表里面的元素为一个大字符串") mylist = ["aa","bb","cc","dd"] print("...".join(mylist)) print("title()将字符串每个单词的首字母转成大写") print(mystr.title()) print("capitalize()将字符串首个单词的首字母转成大写") print(mystr.capitalize()) print("lower()将字符串中大写转小写") print(mystr.lower()) print("upper()将字符串中小写转大写") print(mystr.upper()) print("lstrip()删除左侧空白字符") print(mystr.lstrip()) print("rstrip()删除右侧空白字符") print(mystr.rstrip()) print("strip()删除开头结尾空白字符") print(mystr.strip()) print("str.ljust(length,char) 使左对齐 不够补齐") print(mystr.ljust(60,".")) print("str.rjust(length,char) 使右对齐 不够补齐") print(mystr.rjust(60,"*")) print("str.rjust(length,char) 使右对齐 不够补齐") print(mystr.rjust(60,"*")) print("str.center(length,char) 居中对齐 不够补齐 默认补齐空格") print(mystr.center(60,"*")) print(mystr.startswith(" my",0,100)) #在0~100范围内 是否以 my开头 print(mystr.endswith("my",0,100)) str2 = "123" print(str2.isalpha()) print(str2.isdigit()) print(str2.isalnum())
true
cb1ffd53ba14cf4a853b7b71224bba0e4e026474
Python
MikayelB/Learning_Python
/CS EX/sum_of_digits_with_function.py
UTF-8
207
3.8125
4
[]
no_license
def SumOfDigits(N): thesum = 0 while N != 0: thesum += N % 10 N = N // 10 return thesum def main(): N = int(input("Please input a number: ")) print(SumOfDigits(N)) main()
true
9bcf814f1e593d4e58838c0931c6bc90d08971c8
Python
BootcampersCollective/Coders-Workshop
/Contributors/BryanYunis/solutions/graphTransitiveClosure.py
UTF-8
387
3.125
3
[ "MIT" ]
permissive
def closure(graph): n = len(graph) reachable = [[0 for _ in range(n)] for _ in range(n)] for i, v in enumerate(graph): for neighbor in v: reachable[i][neighbor] = 1 for k in range(n): for i in range(n): for j in range(n): reachable[i][j] |= (reachable[i][k] and reachable[k][j]) return reachable
true
86528946014eb7f031010fe56e2c31afcad9dfdb
Python
luckyaddress/Python
/12_most_use_module.py
UTF-8
2,845
3.734375
4
[]
no_license
#-*- coding: utf-8 -*- # 使用中文註解,要加上上面那一行的編碼 # os模組 可以 刪除檔案 建立目錄 更名和刪除目錄 import os path = os.getcwd() # 取得現在工作目錄 print(path) print(os.listdir(path)) # 取得路徑下的檔案 和 目錄清單 # os.mkdir("os_module_test") # 建立新目錄 如果目錄已存在,會出現目錄同名無法建立的錯誤 # os.rename("os_module_test", "omt") # 更名現有目錄 # os.rmdir("omt") # 刪除目錄 # 建立檔案 刪除檔案 因為建立後刪除 同時只能完成一個動作,否則刪除會通知找不到檔案 #file = open("aa.txt", "w") #file.close() #print("建立檔案:", os.listdir(path)) # 先建立,方能測試刪除 # os.remove("aa.txt") # print("測試檔案", os.listdir(path)) # os.path模組:檢查檔案或目錄是否存在 files = (os.getcwd(), "loop_2.py") for f in files: print("該項目為 = " + str(f)) if os.path.exists(f): print("檔案或目錄存在") if os.path.isdir(f): print("該檔案是目錄") if os.path.isfile(f): print("該檔案是檔案") # 數學函數與亂數 import math 或者 random import random r1 = random.randint(1,20) print(str(r1)) list1 = ["apple", "orange", "strawberry", "juice", "roasted-beef"] r2 = random.choice(list1) # choice 在清單的資料型態中任意抽選一個 print(r2) # Python時間模組 time模組顯示時間與日期 calendar模組顯示月曆資料 import time time_1 = time.time() print(time_1) localtime = time.localtime(time_1) print("Year", localtime[0], "Month", localtime[1]) # 年月日時分秒 分別為: localtime[0]-[5] # calendar模組 顯示指定年份和月份資料(以月曆形式顯示) import calendar cal = calendar.month(2017,4) print(cal) # 精確表示浮點數 decimal模組 import decimal decimal.getcontext().prec = 7 # 指定小數點精確度 print(decimal.Decimal(7.6) + decimal.Decimal(8.7)) # 正規運算式 re模組 import re source_data = "my name is kao and email is ykk@gmail.com" match_string = re.search(r"([\w.-]+)@([A-Za-z0-9_.-]+)", source_data) # + 表示前面的字元可以被比較1次或多次 # + 要包在r後的""字串範圍內,否則連群組抓取都會無法正常使用 print(match_string.group()) # 群組抓取,上述的字串已經分割成群組 print(match_string.group(1)) print(match_string.group(2)) # re正規表達式的 findall()方法 --seacrh()只能找到一次,要找出所有符合的,要用findall() source_data2 = "my name is kao and email is ykk@gmail.com, your name is wakaki and email is wakaki@gmail.com" match_string2 = re.findall(r"([\w.-]+)@([A-Za-z0-9_.-]+)", source_data2) print(match_string2) # 會變成一個二維的list print(match_string2[0][0]) print(match_string2[0][1]) print(match_string2[1][0]) print(match_string2[1][1])
true
4f94d8afa3d64b2129fa0ebcdbfbe01a01224f47
Python
Aasthaengg/IBMdataset
/Python_codes/p03288/s807151610.py
UTF-8
417
2.828125
3
[]
no_license
def main(): from sys import stdin, setrecursionlimit setrecursionlimit(10**6) r = stdin.readline()[:-1] #n = int(stdin.readline()[:-1]) #r = [stdin.readline() for i in range(n)] #t = [int(stdin.readline()) for i in range(n)] r = int(r) if r < 1200: print('ABC') elif r < 2800: print('ARC') else: print('AGC') if __name__ == '__main__': main()
true
1c94dfe35fcf138fa1f98c42d96771b7d6a262ee
Python
savfod/d16
/mfesyuk/treug_serp.py
UTF-8
639
3.171875
3
[]
no_license
import turtle turtle.speed("fastest") def draw_levi(d, length): if d == 0: turtle.left(60) turtle.forward(length) turtle.right(120) turtle.forward(length) turtle.right(120) turtle.forward(length) else: turtle.left(60) turtle.forward(length / 2) turtle.right(120) turtle.forward(length / 2) turtle.left(120) turtle.forward(length / 2) turtle.left(120) turtle.forward(length / 2) turtle.right(120) turtle.forward(length / 2) turtle.right(120) turtle.forward(length / 2) turtle.forward(length / 2) turtle.right(120) turtle.forward(length / 2) turtle.forward(length / 2) draw_levi(4, 200) input()
true
97891293e640c04a7995decf972974350d38bfa3
Python
Data-Analytic-Research-Insight/kerastuner-tensorboard-logger
/kerastuner_tensorboard_logger/logger.py
UTF-8
3,195
2.6875
3
[ "MIT" ]
permissive
import os from typing import Any, Dict, Generator, List, Tuple, Union from datetime import timedelta, datetime import tensorflow as tf from kerastuner.engine.logger import Logger from tensorboard.plugins.hparams import api as hp_board def timedelta_to_hms(timedelta: timedelta) -> str: """(Deprecated) convert datetime.timedelta to string like '01h:15m:30s'""" tot_seconds = int(timedelta.total_seconds()) hours = tot_seconds // 3600 minutes = (tot_seconds % 3600) // 60 seconds = tot_seconds % 60 return f"{hours}h{minutes}m{seconds}s" class TensorBoardLogger(Logger): """tensorboard.plugins.hparams logger class. Create logger instance for tuner instance that inherit kerastuner.engine.base_tuner.BaseTuner. # Arguments: metrics: String or list of String, reports values for Tensorboard. logdir: String. Path to the log directory (relative) to be accessed by Tensorboard. overwrite: Bool, default `False`. If `False`, reloads an existing log directory of the same name if one is found. Otherwise, overwrites the log. """ def __init__( self, metrics: Union[str, List[str]] = ["acc"], logdir: str = "logs/", overwrite: bool = False, ): self.metrics = [metrics] if isinstance(metrics, str) else metrics self.logdir = logdir self.times: Dict[str, datetime] = dict() if overwrite and tf.io.gfile.exists(self.logdir): tf.io.gfile.rmtree(self.logdir) def register_tuner(self, tuner_state): """Informs the logger that a new search is starting.""" pass def register_trial(self, trial_id: str, trial_state: Dict[str, Any]): """Informs the logger that a new Trial is starting.""" pass def report_trial_state(self, trial_id: str, trial_state: Dict[str, Any]): """Gives the logger information about trial status.""" logdir = os.path.join(self.logdir, trial_id, "hparams") with tf.summary.create_file_writer(logdir).as_default(): hparams = self.parse_hparams(trial_state) hp_board.hparams( hparams, trial_id=trial_id ) # record the values used in this trial for target_metric, metric in self.parse_metrics(trial_state): tf.summary.scalar(target_metric, metric, step=1) def exit(self): pass def parse_hparams(self, trial_state: Dict[str, Any]) -> Dict[str, Any]: """use in tf.summary writer context""" hparams = trial_state.get("hyperparameters", {}).get("values", {}) return hparams def parse_metrics( self, trial_state: Dict[str, Any] ) -> Generator[Tuple[str, Union[int, float]], None, None]: """use in tf.summary writer context""" metrics = trial_state.get("metrics", {}).get("metrics", {}) for target_metric in self.metrics: metric = metrics.get(target_metric) if metric is None: continue metric = metric.get("observations", [{}])[0].get("value") if metric is None: continue yield target_metric, metric[0]
true
5dbb07fe8192e057d6540082c52c0501cf1826a5
Python
ZHAW-SPDR/SPDR
/experiments/sequencer/experiment2_plot.py
UTF-8
4,975
2.53125
3
[]
no_license
import pickle import os import sys import random import numpy as np from scipy.spatial.distance import pdist from scipy.interpolate import * import matplotlib.pyplot as plt import math np.random.seed(1337) random.seed(1337) SCALE_NOTSAME = False SCALE_SAME = True PICKLEFOLDER = 'data/pickles/' #PICKLE_NAME_STEM = 'TIMIT_R1_' #PICKLE_NAME_STEM = 'RT09_EDI_17_PHRASES_4_SPEAKERS_TIMIT_LSTM_01_' PICKLE_NAME_STEM = 'RT09_EDI_17_PHRASES_4_SPEAKERS_VOXCELEB_LSTM_01_' DSPICKLE = PICKLE_NAME_STEM+'dataset.pkl' PAIRPICKLE = PICKLE_NAME_STEM+'prodpairs.pkl' DIST_MET = 'cosine' dataset_pickle = os.path.join(PICKLEFOLDER, DSPICKLE) with open(dataset_pickle, 'rb') as pFile: dataset = pickle.load(pFile) #tmp_data = list([x for x in dataset[::12]]) tmp_data = list([x for x in dataset[::]]) random.shuffle(tmp_data) dataset = tmp_data pair_pickle = os.path.join(PICKLEFOLDER, PAIRPICKLE) if not os.path.isfile(pair_pickle): data = [(x, y) for x in dataset[:int(len(dataset)/2)] for y in dataset[int(len(dataset)/2):]] # join every item with every item with open(pair_pickle, 'wb') as pFile: pickle.dump(data, pFile) else: with open(pair_pickle, 'rb') as pFile: data = pickle.load(pFile) X = [] Y = [] for (ds0, ds1) in data: same_speaker = 1 if ds0[1] == ds1[1] else 0 if np.random.randint(low=0, high=8) == 1 or same_speaker == 1: X.append(pdist([ds0[0], ds1[0]], metric=DIST_MET)) Y.append(same_speaker) print('0:', Y.count(0), Y.count(0)/len(Y)) print('1:', Y.count(1), Y.count(1)/len(Y)) print('Max:', max(X)) print('Min:', min(X)) zeros = [i for i, x in enumerate(Y) if x == 0] if SCALE_NOTSAME: zeros = list([x for x in zeros[::15]]) else: zeros = list([x for x in zeros[::]]) ones = [i for i, x in enumerate(Y) if x == 1] if SCALE_SAME: ones = list([x for x in ones[::5]]) else: ones = list([x for x in ones[::]]) print('0:', len(zeros)) print('1:', len(ones)) dzeros = np.array(X)[zeros] dones = np.array(X)[ones] data = [dzeros, dones] print('Max 0:', max(dzeros)) print('Min 0:', min(dzeros)) print('Max 1:', max(dones)) print('Min 1:', min(dones)) plt.figure(figsize=(9,6)) plt.scatter(len(dzeros) * [0], dzeros, marker='.', label='Not same') plt.scatter(len(dones) * [1], dones, marker='.', label='Same') plt.xlim(-0.5,1.5) plt.ylim(0,1.5) plt.title('Distances') plt.ylabel('Distance') plt.legend() plt.savefig("./data/plots/experiment2_cutoff/%s%s_cutoff_distance.png" % (PICKLE_NAME_STEM, DIST_MET)) plt.close() plt.figure(figsize=(9,6)) plt.boxplot(data, labels=['Not same', 'Same']) plt.ylabel('Distance') plt.title('Distances Box Plot') plt.ylim(0,1.5) plt.savefig("./data/plots/experiment2_cutoff/%s%s_cutoff_distance_boxplot.png" % (PICKLE_NAME_STEM, DIST_MET)) plt.close() plt.figure(figsize=(9,6)) plt.title('Distribution') unique_zeros, counts_zeros = np.unique([round(x[0],2) for x in data[0]], return_counts=True) unique_ones, counts_ones = np.unique([round(x[0],2) for x in data[1]], return_counts=True) plt.fill_between(unique_zeros, counts_zeros, color='b', alpha=.5, interpolate=False) plt.fill_between(unique_ones, counts_ones, color='g', alpha=.5, interpolate=False) plt.legend(['Not same', 'Same']) plt.xlabel('Distance') plt.ylabel('Count') plt.xticks(np.linspace(0,1,21)) plt.xlim(0,1) plt.ylim(0,max(max(counts_zeros), max(counts_ones))) plt.savefig("./data/plots/experiment2_cutoff/%s%s_cutoff_distribution.png" % (PICKLE_NAME_STEM, DIST_MET)) plt.close() plt.figure(figsize=(9,6)) xs = np.linspace(0,1,300) poly_deg = 10 coefs_zeros = np.polyfit(unique_zeros, counts_zeros, poly_deg) coefs_ones = np.polyfit(unique_ones, counts_ones, poly_deg) ys_zeros = np.polyval(coefs_zeros, xs) ys_ones = np.polyval(coefs_ones, xs) # fix poly problems neg_zeros = 0 if [i for i,x in enumerate(ys_zeros) if x<0] == [] else [i for i,x in enumerate(ys_zeros) if x<0][0] neg_ones = 0 if [i for i,x in enumerate(ys_ones) if x<0] == [] else [i for i,x in enumerate(ys_ones) if x<0][0] ys_zeros = [0 if i <= neg_zeros else x for i, x in enumerate(ys_zeros)] ys_ones = [0 if i <= neg_ones else x for i, x in enumerate(ys_ones)] plt.fill_between(xs, ys_zeros, color='r', alpha=.5, interpolate=False) plt.fill_between(xs, ys_ones, color='y', alpha=.5, interpolate=False) plt.legend(['Not same', 'Same']) plt.xlabel('Distance') plt.title('Distribution Smoothed') plt.xticks(np.linspace(0,1,21)) plt.ylabel('Count') plt.xlim(0,1) plt.ylim(0,max(max(counts_zeros), max(counts_ones))) plt.savefig("./data/plots/experiment2_cutoff/%s%s_cutoff_distribution_smoothed.png" % (PICKLE_NAME_STEM, DIST_MET)) plt.close()
true
3e98c37d0acaee7bb5d08373e15e249d36573710
Python
hsydw/python
/초보자를 위한 파이썬 200제/084.py
UTF-8
250
3.5
4
[]
no_license
str1 = 'hello' str2 = '12345' str3 = 'hi123' str4 = '안녕' str5 = '안녕!' res1 = str1.isalpha() res2 = str2.isalpha() res3 = str3.isalpha() res4 = str4.isalpha() res5 = str5.isalpha() print(res1) print(res2) print(res3) print(res4) print(res5)
true
c3c4e24128a8239a8d679d52c8753dbcfb476c6f
Python
ckane/CS6065-Cloud-BigTableDemo
/tbl_demo.py
UTF-8
1,500
3.453125
3
[]
no_license
#!/usr/bin/python3 import sys big_table = {} # The data store col_names = ['row-id'] # An index of all column names # Start with a fixed column named row-id: print("Enter row-id, or just hit ENTER to stop adding data: ") while True: input_data = sys.stdin.readline().strip() if len(input_data) == 0: print("Nothing entered, ending data entry loop") break # Create a new row object, that's a dictionary, with one entry for # mandatory row-id row = {'row-id': input_data} print("Enter column name (just press ENTER to end row data entry): ") while True: # Get another input record colname = sys.stdin.readline().strip() if len(colname) == 0: print("Completed row '{0}'".format(row['row-id'])) big_table[row['row-id']] = row break print("Enter column value (just press ENTER for no value): ") input_data = sys.stdin.readline().strip() if len(input_data) > 0: row[colname] = input_data if colname not in col_names: col_names.append(colname) print("Enter column name (just press ENTER to end row data entry): ") print("Enter row-id, or just hit ENTER to stop adding data: ") print(big_table) print("\n" + '\t'.join(col_names)) for r in big_table: s = '' for c in col_names: if c in big_table[r]: s = s + big_table[r][c] + '\t' else: s = s + '\t' print(s)
true
d5ae08821aea0454b352c3f5a13ed1bb729c1caa
Python
nithyaradha/Python_Project
/Assignment_4.py
UTF-8
10,291
3.828125
4
[]
no_license
import math as m1 import time as t1 # Q(1): A Robot moves in a Plane starting from the origin point (0,0). The robot can move toward UP, DOWN, LEFT, RIGHT # Q(2): program for searching specific data from that list. def selection_sort(a_list): for i in range(len(a_list)): least = i for k in range(i + 1, len(a_list)): if a_list[k] < a_list[least]: least = k swap(a_list, least, i) def swap(a, x, y): temp = a[x] a[x] = a[y] a[y] = temp my_list = [5.76, 4.7, 25.3, 4.6, 32.4, 55.3, 52.3, 7.6, 7.3, 86.7, 43.5] print("\n\nQ(2):\nGiven List : ", my_list) selection_sort(my_list) print("Sorted List : ", my_list) # Q(3): program for such organization to find whether is it dark outside or not. def weather_update(localtime): if 6 < localtime < 20: print("It's Day OutSide") return else: print("It's Dark Outside") return local_time = t1.localtime().tm_hour print("\n\nQ(3): \nCurrent Time : %d:%d" % (t1.localtime().tm_hour, t1.localtime().tm_min)) weather_update(local_time) # Q(4): program to find distance between two locations when their latitude and longitudes are given. def distance_calculator(lat1, lon1, lat2, lon2): p = 0.017453292519943295 cal = 0.5 - m1.cos((lat2 - lat1) * p) / 2 + m1.cos(lat1 * p) * m1.cos(lat2 * p) * ( 1 - m1.cos((lon2 - lon1) * p)) / 2 earth_radius = 6371 radius = earth_radius * 2 distance = round(radius * m1.asin(m1.sqrt(cal)), 2) return distance lat_1 = 13.6 lon_1 = 15.6 lat_2 = 14.5 lon_2 = 17.3 print("\n\nQ(4):\nGiven Values For Distance\nLatitude 1 : %d\nLongitude 1 : %d\nLatitude 2 : %d\nLongitude 2 : %d" % ( lat_1, lon_1, lat_2, lon_2)) print("\nDistance Between Locations : %d km" % distance_calculator(lat_1, lon_1, lat_2, lon_2)) # Q(5): Bank system. with Options: cash withdraw, cash deposit, change password. with user Input print("\n\nQ(5):\n") account_name = "" deposit_amount = 0 created_password = "" def banking(): print("------------Apna Bank------------") print("Enter 0 For Create Account") print("Enter 1 For Cash Withdrawal") print("Enter 2 For Cash Deposit") print("Enter 3 For Change Password") print("Enter 4 For Account Information") print("Enter 5-9 For Banking Logout") print("---------------------------------") inp = int(input("\nEnter Your Option -: ")) print("\n") if inp == 0: create_account() return elif inp == 1: cash_withdraw() return elif inp == 2: cash_credit() return elif inp == 3: change_password() return elif inp == 4: account_information() return else: print("Logout From Banking") return def create_account(): print("---------Create Account---------") acc_name = input("Enter Your Name : ") dep_amt = int(input("Enter Deposit Amount : ")) pass_word = input("Enter Your Password : ") global account_name, deposit_amount, created_password account_name = acc_name deposit_amount = dep_amt created_password = pass_word print("\nAccount Created Successfully\n") print("---------------------------------") return banking() def cash_withdraw(): print("---------Cash Withdrawal---------") with_amt = int(input("Enter Withdrawal Amount : ")) global deposit_amount if with_amt < deposit_amount: deposit_amount = deposit_amount - with_amt print("\nCash Withdrawal Successfully\n") print("Current Balance is : %d\n" % deposit_amount) else: print("\nInsufficient Account Balance\n") print("---------------------------------") return banking() def cash_credit(): print("---------Cash Deposit---------") dep_amt = int(input("Enter Deposit Amount : ")) global deposit_amount deposit_amount = deposit_amount + dep_amt print("\nCash Deposit Successfully\n") print("Current Balance is : %d\n" % deposit_amount) print("-------------------------------") return banking() def change_password(): print("---------Change Password---------") global created_password chge_pass = input("Enter Old Password : ") if created_password == chge_pass: new_pass = input("Enter New Password : ") created_password = new_pass print("\nPassword Changed Successfully\n") else: print("\nWrong Password Try Again\n") print("----------------------------------") return banking() def account_information(): print("---------Account Information---------") global created_password, deposit_amount, account_name print("\nAccount Name : %s\nAccount Balance : %d\nAccount Password: %s\n" % ( account_name, deposit_amount, created_password)) print("-------------------------------------") return banking() banking() # Q(6): Divisible by 7 but are not a multiple of 5, between 2000 and 3200 in a comma-separated on a single line. print("\n\nQ(6):\n") inline = [] for x in range(2000, 3201): if (x % 7) == 0: y = x / 5.0 if (y % 5) != 0: inline.append(str(x)) print(",".join(inline)) # Q(7): compute the factorial of a given numbers. Use recursion to find it. print("\n\nQ(7):\n") def recursion_factorial(number): if number == 1: return number else: return number * recursion_factorial(number - 1) number_input = int(input("Enter a Number For Factorial : ")) print("The Factorial of %d is : %d" % (number_input, recursion_factorial(number_input))) # Q(8): calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] print("\n\nQ(8):\n") def square_root(i1, i2, i3): c = 50 h = 30 arg = [i1, i2, i3] out = [] for x1 in range(3): formula = (2 * c * arg[x1]) / h sqr_root = m1.sqrt(formula) output = int(sqr_root) out.append(output) print("Given Values for Square Roots : %d,%d,%d" % (arg[0], arg[1], arg[2])) print("Square Roots of Given Values : %d,%d,%d" % (out[0], out[1], out[2])) return na = [] number_input = input("Enter 3 Numbers with Comma For Square Root : ") spl_val = number_input.split(",") for xv in spl_val: gv = int(xv) na.append(gv) square_root(na[0], na[1], na[2]) # Q(9): calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] print("\n\nQ(9):\n") def array_dimensional(r, c): array_1 = [[i * j for j in range(c)] for i in range(r)] return array_1 row = int(input("Enter Rows Numbers : ")) col = int(input("Enter Column Numbers : ")) print(array_dimensional(row, col)) # Q(10): comma separated sequence of words, comma-separated sequence after sorting them alphabetically print("\n\nQ(10):\n") words_list = input("Enter Words, Comma Separated : ") words_list = words_list.split(",") words_list = sorted(words_list) print(",".join(words_list)) # Q(11): sequence of lines as input and prints the lines after all characters in the sentence capitalized. print("\n\nQ(11):\n") input_lines = [] print("Enter Words Sequence : ") while True: words_input = input("-: ") if not words_input: break input_lines.append(words_input.upper()) for x in input_lines: print(x) # Q(12): Remove all duplicate words and sort them alphanumerically. print("\n\nQ(12):\n") words_seq = input("Words Separated By WhiteSpace : ") seq_split = words_seq.split(' ') words_set = set(seq_split) seq_wd = ' '.join(sorted(words_set)) print("Removed Duplicate Words,Sorted : ", seq_wd) print("Given Paragraph : ", words_seq) # Q(13): sequence of comma separated 4 digit binary no. and check they are divisible by 5 or not print("\n\nQ(13):\n") def binary_conversion(binary_val): out_binary = [] bin_val = binary_val.split(",") num_val = [x1 for x1 in bin_val] for p in num_val: x1 = int(p, 2) if not x1 % 5: out_binary.append(p) out_put = ','.join(out_binary) return out_put inp_val = input("Enter 4 Digit Binary Values Comma Separated : ") print("Divisible By 5 or Not, Printing in Binary Number : ", binary_conversion(inp_val)) # Q(14): program that accepts a sentence and calculate the number of upper case letters and lower case letters print("\n\nQ(14):\n") def string_test(string_val): d = {"UPPER_CASE": 0, "LOWER_CASE": 0} for val in string_val: if val.isupper(): d["UPPER_CASE"] += 1 elif val.islower(): d["LOWER_CASE"] += 1 else: pass print("Given String : ", string_val) print("Uppercase Alphabets : ", d["UPPER_CASE"]) print("Lowercase Alphabets : ", d["LOWER_CASE"]) string_test(input("String Lower & Upper Case Count : ")) # Q(15): Examples of Fsum and Sum print("\n\nQ(15):\n") set_list = {1, 2, 3, 1.2} # set dict_list = {1: 1.2, 2: 2.1, 3: .1} # dictionary tuple_list = (1, 2, 3.0) # tuple list_list = [1, 0.2, 3] # list frozenset_list = frozenset([2, 1.3, 4]) # frozenset print("------------Fsum Examples For Python Data types-------------") print(" Fsum of Sets...... || ", m1.fsum(set_list), " || Data Type ||", type(set_list)) print(" Fsum of Dictionary || ", m1.fsum(dict_list.values()), " || Data Type ||", type(dict_list)) print(" Fsum of Tuples.... || ", m1.fsum(tuple_list), " || Data Type ||", type(tuple_list)) print(" Fsum of List...... || ", m1.fsum(list_list), " || Data Type ||", type(list_list)) print(" Fsum of FrozenSets || ", m1.fsum(frozenset_list), " || Data Type ||", type(frozenset_list)) print("------------------------------------------------------------") print("------------Sum Examples For Python Data types-------------") print(" Sum of Sets...... || ", sum(set_list), " || Data Type ||", type(set_list)) print(" Sum of Dictionary || ", sum(dict_list.values()), " || Data Type ||", type(dict_list)) print(" Sum of Tuples.... || ", sum(tuple_list), " || Data Type ||", type(tuple_list)) print(" Sum of List...... || ", sum(list_list), " || Data Type ||", type(list_list)) print(" Sum of FrozenSets || ", sum(frozenset_list), " || Data Type ||", type(frozenset_list)) print("-----------------------------------------------------------")
true
4d94ceaafeb15f6fba52a155dd90518ca63f377d
Python
tashakim/puzzles_python
/prodExceptSelf.py
UTF-8
1,050
3.25
3
[]
no_license
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: # two-pass # one-pass using division (division by zero) # left_product * right_product left, right = [1], [] left_prod = 1 for i in range(1, len(nums)): left_prod *= nums[i-1] left.append(left_prod) right_prod = 1 for i in reversed(range(len(nums)-1)): right_prod *= nums[i+1] right.append(right_prod) right.reverse() right.append(1) res = [0] * len(left) for i in range(len(left)): res[i] = left[i] * right[i] return res def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) res = [0] * n res[0] = 1 for i in range(1, n): res[i] = nums[i-1] * res[i-1] R = 1 for i in reversed(range(n)): res[i] *= R R *= nums[i] return res
true
346dd2fe2cf03233e8a1b4508e0e42e12901c0f3
Python
radomirbrkovic/algorithms
/matrices/shift-matrix-elements-k.py
UTF-8
624
4.5
4
[]
no_license
# Shift matrix elements row-wise by k https://www.geeksforgeeks.org/shift-matrix-elements-k/ def shiftMatrixByK(matrix, k): n = len(matrix) if k > n: print("Shifting is not possible") return j = 0 while j < n: for i in range(k,n): print("{}". format(matrix[j][i]), end=" ") for i in range(0, k): print ("{} " . format(matrix[j][i]), end=" ") print ("") j = j + 1 mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] k = 2 # Function call shiftMatrixByK(mat, k)
true
71682a991f8347986a375e53572f52238bc10358
Python
asyrul21/recode-beginner-python
/materials/week-2/src/solveTogether.py
UTF-8
480
4.40625
4
[]
no_license
print("I am in the correct directory!") # 1. Calculate area of triangle # area of triangle = (width * height) / 2 width = 5 height = 25 areaOfTriangle = (width * height) / 2 print("The area of the triangle is: " + str(areaOfTriangle)) # 2. Calculate the volume of cone # formula: pi * radius * radius * (height/3) # pi : 3.14159 pi = 3.14159 radius = 5 height = 12 volumeOfCone = pi * radius * radius * (height / 3) print("The volume of the cone is: " + str(volumeOfCone))
true
66195d6ee608ef9ace220246951911405d86a2f5
Python
morozzArt/news_classificator
/test.py
UTF-8
1,709
2.9375
3
[]
no_license
import math from common_line import convert themes = ('science', 'style', 'culture', 'life', 'economics', 'business', 'travel', 'forces', 'media', 'sport') def key_of_max(d): v = list(d.values()) k = list(d.keys()) return k[v.index(max(v))] def sum_theme(themes): sum = 0 for key, value in themes.items(): sum = sum + value return sum def classification(artical, dict_word, dict_theme_count, dict_theme_word): servive_word = ['без', 'в', 'до', 'для', 'за', 'из', 'к', 'над', 'о', 'об', 'под', 'пред', 'с', 'у', 'пред', 'про', 'от', 'на', 'и', 'или', 'но', 'без', 'во', 'по', 'со'] line = convert(artical) d = sum_theme(dict_theme_count) dc = 0 v = len(dict_word) probability = {} word_list = line.split() for i in themes: dc = dict_theme_count[i] res = 0 for word in word_list: if word in servive_word: continue if word in dict_word.keys(): wic = dict_word[word][i] else: wic = 0 res = res + math.log((wic + 1) / (v + dict_theme_word[i])) result = res + math.log(dc/d) probability.update({i: result}) return key_of_max(probability) def testing(tuple_from_train): dict_words = tuple_from_train[0] dict_theme_count = tuple_from_train[1] dict_theme_word = tuple_from_train[2] out = open('out.txt', 'w') with open('news_test.txt') as file_for_text: for line in file_for_text: them = classification(line, dict_words, dict_theme_count, dict_theme_word) out.write(them + '\n')
true
dffa024c19ead68de2a85fdf38b0145c1de304f4
Python
monorio/stweet
/stweet/mapper/user_dict_mapper.py
UTF-8
1,722
2.75
3
[ "MIT" ]
permissive
"""User - dict mapper.""" from copy import copy from typing import Dict from arrow import get as arrow_get from .util import simple_string_list_to_string, string_to_simple_string_list from ..model import User def user_to_flat_dict(self): """Method to prepare flat dict of tweet. Used in CSV serialization.""" dictionary = dict(self.__dict__) dictionary['pinned_tweet_ids_str'] = simple_string_list_to_string(dictionary['pinned_tweet_ids_str']) return dictionary def create_user_from_dict(dictionary: Dict[str, any]): """Method to create Tweet from dictionary.""" return User( arrow_get(dictionary['created_at']), str(dictionary['id_str']), str(dictionary['rest_id_str']), dictionary['default_profile'], dictionary['default_profile_image'], dictionary['description'], dictionary['favourites_count'], dictionary['followers_count'], dictionary['friends_count'], dictionary['has_custom_timelines'], dictionary['listed_count'], dictionary['location'], dictionary['media_count'], dictionary['name'], dictionary['pinned_tweet_ids_str'], dictionary['profile_banner_url'], dictionary['profile_image_url_https'], dictionary['protected'], dictionary['screen_name'], dictionary['statuses_count'], dictionary['verified'] ) def create_user_from_flat_dict(dictionary: Dict[str, any]) -> User: """Method to create Tweet from flat dictionary.""" dictionary = copy(dictionary) dictionary['pinned_tweet_ids_str'] = string_to_simple_string_list(dictionary['pinned_tweet_ids_str']) return create_user_from_dict(dictionary)
true
12d7388b4d744b805ddadb1297a7909a79794b6c
Python
Cooper-Grumman/mathematical_curves
/epi_circle.py
UTF-8
1,285
3.09375
3
[]
no_license
""" epi-cycle """ import numpy as np from matplotlib import pyplot as plt from matplotlib import animation theta_array = np.linspace(0, 2 * np.pi, 1000) def circle(x0, y0, r): return (r * np.cos(theta_array) + x0, r * np.sin(theta_array) + y0) fig = plt.figure() fig.set_size_inches(12, 12, True) ax = plt.axes(xlim=(-3, 6), ylim=(-3, 3)) ax.set_aspect('equal', 'datalim') Lines = [ax.plot([], [])[0] for _ in range(10)] Lines.append(ax.plot([], [], color='black')[0]) # trace line TraceLineData = [[], []] def update(frame_count=0): x_0 = 0 y_0 = 0 radius = 1 radius_factor = 0.75 for i in range(0, 10): circle_xy = circle(x_0, y_0, radius) Lines[i].set_data(*circle_xy) #plt.plot(*np.copy(circle_xy)) next_frame = int(frame_count * 2 * i % 1000) x_0, y_0 = circle_xy[0][next_frame], circle_xy[1][next_frame] if i == 9: TraceLineData[0].append(x_0) TraceLineData[1].append(y_0) Lines[i + 1].set_data(*TraceLineData) radius *= radius_factor return Lines anim = animation.FuncAnimation(fig, update, init_func=update, frames=999, interval=20, blit=True) #anim.save('basic_animation.mp4', fps=60, dpi=100) plt.show()
true
9300599e33dd187ecf74146243fe43734d05e373
Python
qian99/acm
/test.py
UTF-8
538
2.515625
3
[]
no_license
import os import sys def Run(Path, oldtype, newtype): allFile = os.listdir(Path) for file_name in allFile: currentdir = os.path.join(Path, file_name) if os.path.isdir(currentdir): Run(currentdir, oldtype, newtype) fname = os.path.splitext(file_name)[0] ftype = os.path.splitext(file_name)[1] if oldtype in ftype[1:]: #typecount[0] += 1 ftype = ftype.replace(oldtype, newtype) newname = os.path.join(Path, fname + ftype) os.rename(currentdir, newname) #print newname Run(".","txt", "cpp")
true
46bd4d6ea8af8706dd2edee0a6f1080ab7a737cc
Python
Jorza/python-useful-codes
/number_suffix.py
UTF-8
401
3.640625
4
[]
no_license
def number_suffix(number): number = str(round(number)) ones_digit = str(number)[-1] tens_digit = str(number)[-2] if tens_digit == '1': suffix = 'th' elif ones_digit == '1': suffix = 'st' elif ones_digit == '2': suffix = 'nd' elif ones_digit == '3': suffix = 'rd' else: suffix = 'th' return number + suffix
true
bfe8c346de3e5dc7967c4efae38314c7b3ccf263
Python
oscarcheng105/PAS_Python
/Calculator_Oscar.py
UTF-8
5,445
2.96875
3
[]
no_license
from tkinter import * import math cal = Tk() cal.title("Calculator") operator = "" text_Input = StringVar() def btnClick(numbers): global operator operator = operator + str(numbers) text_Input.set(operator) def btnClearDisplay(): global operator operator="" text_Input.set("") def allclear(): global operator global store operator = "" store = "" text_Input.set(operator) def delete(): global operator operator = operator[:len(operator)-1] text_Input.set(operator) def btnEqualsInput(): global operator sumup = str(eval(operator)) operator = sumup text_Input.set(operator) def btnSquareroot(): global operator operator = str(math.sqrt(eval(operator))) text_Input.set(operator) def percentage(): global operator operator = str(eval(operator+"/100")) text_Input.set(operator) def recall(): global operator global store operator = operator + store text_Input.set(operator) def storeup(): global operator global store store = operator def unstore(): global store store = "" def PositiveNegative(): global operator operator = str(eval("-"+str(eval(operator)))) text_Input.set(operator) txtDisplay = Entry(cal,font=('arial',20,'bold'), textvariable = text_Input, bd=1, insertwidth=5, bg="white", justify="right").grid(columnspan=5) #Numbers btn1=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='1',bg="white",command=lambda:btnClick(1)).grid(row=4,column=1) btn2=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='2', bg="white",command=lambda:btnClick(2)).grid(row=4,column=2) btn3=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='3', bg="white",command=lambda:btnClick(3)).grid(row=4,column=3) btn4=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='4', bg="white",command=lambda:btnClick(4)).grid(row=3,column=1) btn5=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='5', bg="white",command=lambda:btnClick(5)).grid(row=3,column=2) btn6=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='6', bg="white",command=lambda:btnClick(6)).grid(row=3,column=3) btn7=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='7', bg="white",command=lambda:btnClick(7)).grid(row=2,column=1) btn8=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='8', bg="white",command=lambda:btnClick(8)).grid(row=2,column=2) btn9=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='9', bg="white",command=lambda:btnClick(9)).grid(row=2,column=3) btn0=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='0', bg="white",command=lambda:btnClick(0)).grid(row=5,column=1) #Symbols period=Button(cal,padx=28,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='.', bg="white",command=lambda:btnClick(".")).grid(row=5,column=2) add=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='+', bg="white",command=lambda:btnClick("+")).grid(row=2,column=4) subtct=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='–', bg="white",command=lambda:btnClick("-")).grid(row=3,column=4) mtply=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='x', bg="white",command=lambda:btnClick("*")).grid(row=4,column=4) division=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='÷', bg="white",command=lambda:btnClick("/")).grid(row=5,column=4) p=Button(cal,padx=22,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='%', bg="white",command=lambda:percentage()).grid(row=1,column=2) equal=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='=', bg="white",command=lambda:btnEqualsInput()).grid(row=5,column=3) sqrt=Button(cal,padx=25,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='√', bg="white",command=lambda:btnSquareroot()).grid(row=1,column=1) clear=Button(cal,padx=31,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='C', bg="white",command=lambda:btnClearDisplay()).grid(row=4,column=0) r=Button(cal,padx=16,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='MRC', bg="white",command=lambda:recall()).grid(row=1,column=0) s=Button(cal,padx=24,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='M+', bg="white",command=lambda:storeup()).grid(row=2,column=0) u=Button(cal,padx=26,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='M-', bg="white",command=lambda:unstore()).grid(row=3,column=0) ac=Button(cal,padx=26,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='AC', bg="white",command=lambda:allclear()).grid(row=5,column=0) d=Button(cal,padx=16,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='Del', bg="white",command=lambda:delete()).grid(row=1,column=4) pn=Button(cal,padx=19,pady=20,bd=8,fg="black", font=('arial',20,'bold'), text='+/-', bg="white",command=lambda:PositiveNegative()).grid(row=1,column=3) cal.mainloop()
true
3ca45f19adf67638a9ebc427bf66e38aeaf348ba
Python
nitschmann/chuckjokes
/chuckjokes/joke.py
UTF-8
2,096
2.734375
3
[]
no_license
import chuckjokes.api.jokes as jokes_api from . import category from chuckjokes.db import Entity class Joke(Entity): __table__ = "jokes" __columns__ = ["api_id", "value"] __extra_attributes__ = ["categories"] __unique_columns__ = ["api_id"] __timestampes__ = True def save(self, check_uniqueness_conditions = True): super(Joke, self).save() self.__save_categories() return True @classmethod def random_from_api(cls, category = None): """Fetches a new joke from the API and return an instance""" joke = jokes_api.random(category) return cls(api_id=joke["id"], value=joke["value"], categories=joke["category"]) @classmethod def random_from_api_unique(cls, category = None, max_tries = 10): """ Same as cls.random_from_api with the difference that this method ensurces that the Joke was never read before. It is so long executed until the limit of max_tries is reached. """ joke = None i = 0 while i < max_tries: joke = cls.random_from_api(category=category) if cls.find_by("api_id", joke.api_id) is None: break else: i += 1 return joke def __save_categories(self): if type(self.categories) == list: for category_name in self.categories: c = category.Category.find_or_create_by_name(category_name) self.__save_categories_relation(category_id = c.id) def __save_categories_relation(self, category_id): cursor = self.db_client.connection.cursor() try: sql_query = """ INSERT INTO joke_categories(jokes_id,categories_id) SELECT ?, ? WHERE NOT EXISTS(SELECT 1 FROM joke_categories WHERE jokes_id = ? AND categories_id = ?); """ cursor.execute(sql_query, (self.id,category_id,self.id,category_id)) self.db_client.connection.commit() finally: cursor.close()
true
d4cb6095206862e22096dfba569dee7839dffb49
Python
ThomasOnline/Activite1
/quizpython.py
UTF-8
388
3.28125
3
[]
no_license
answer = input("Quel usage a principalement le language python? ") print("Tu as répondu", answer) if answer == "BDD": print("Tu as bien répondu a la question, Bravo.") elif answer == "robot": print("Tu as bien répondu a la question, Bravo") elif answer == "Web": print("Tu as bien répondu a la question, Bravo") else: print("Tu t'es trompé, recommence!")
true
2fa1a7bd8f51dc8f73d7e45cfbb673e539991e43
Python
rehmanali1337/music_bot
/models/plex.py
UTF-8
1,230
2.65625
3
[]
no_license
from plexapi.myplex import MyPlexAccount import plexapi import json class Plex: def __init__(self): f = open('config.json', 'r') self.config = json.load(f) try: self.account = MyPlexAccount(self.config.get( "PS_USERNAME"), self.config.get("PS_PASSWORD")) except plexapi.exceptions.Unauthorized: print('Email/Username/Password for Plex Account is incorrect!') exit() self.server = self.account.resource( self.config.get("SERVER_NAME")).connect() def sections(self): section = self.server.library.section('My Music') artist = section.get('Various Artists') tracks = artist.tracks() for track in tracks: url = track.getStreamURL() print(url) async def searchServer(self, query): results = self.server.search(query, mediatype='track') tracks = [track for track in results if isinstance( track, plexapi.audio.Track)] return tracks async def searchLibrary(self, section, title): res = self.server.library.search(title=title) return res if __name__ == "__main__": plex = Plex() plex.sections()
true
e6f24061fd11803c56009d140939a10ddd344f0b
Python
jorjich/HackBulgaria-Programming101
/count_substrings/solution.py
UTF-8
447
3.96875
4
[]
no_license
def count_substrings(haystack, needle): x = haystack.count(needle) return x def main(): print( count_substrings("This is a test string", "is") ) print( count_substrings("babababa", "baba") ) print( count_substrings("Python is an awesome language to program in!", "o") ) print( count_substrings("We have nothing in common!", "really?") ) print( count_substrings("This is this and that is this", "this") ) if __name__ == '__main__': main()
true
630f521d28e37ef3ec938938306c812e869eccd4
Python
Chrisebell24/Copulas
/tests/copulas/univariate/test_kde.py
UTF-8
6,096
2.859375
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `univariate` package.""" from unittest import TestCase import numpy as np import scipy from copulas.univariate.kde import KDEUnivariate from tests import compare_nested_dicts class TestKDEUnivariate(TestCase): def setup_norm(self): """set up the model to fit standard norm data.""" self.kde = KDEUnivariate() # use 42 as a fixed random seed np.random.seed(42) column = np.random.normal(0, 1, 1000) self.kde.fit(column) def test___init__(self): """On init, model are set to None.""" self.kde = KDEUnivariate() assert self.kde.model is None def test_fit(self): """On fit, kde model is instantiated with intance of gaussian_kde.""" self.kde = KDEUnivariate() data = [1, 2, 3, 4, 5] self.kde.fit(data) self.assertIsInstance(self.kde.model, scipy.stats.gaussian_kde) def test_fit_uniform(self): """On fit, kde model is instantiated with passed data.""" self.kde = KDEUnivariate() data = [1, 2, 3, 4, 5] self.kde.fit(data) assert self.kde.model def test_fit_empty_data(self): """If fitting kde model with empty data it will raise ValueError.""" self.kde = KDEUnivariate() with self.assertRaises(ValueError): self.kde.fit([]) def test_probability_density(self): """probability_density evaluates with the model.""" self.setup_norm() x = self.kde.probability_density(0.5) expected = 0.35206532676429952 self.assertAlmostEquals(x, expected, places=1) def test_cumulative_distribution(self): """cumulative_distribution evaluates with the model.""" self.setup_norm() x = self.kde.cumulative_distribution(0.5) expected = 0.69146246127401312 self.assertAlmostEquals(x, expected, places=1) def test_percent_point(self): """percent_point evaluates with the model.""" self.setup_norm() x = self.kde.percent_point(0.5) expected = 0.0 self.assertAlmostEquals(x, expected, places=1) def test_percent_point_invalid_value(self): """Evaluating an invalid value will raise ValueError.""" self.setup_norm() with self.assertRaises(ValueError): self.kde.percent_point(2) def test_from_dict(self): """From_dict sets the values of a dictionary as attributes of the instance.""" # Setup parameters = { 'fitted': True, 'd': 1, 'n': 10, 'dataset': [[ 0.4967141530112327, -0.13826430117118466, 0.6476885381006925, 1.5230298564080254, -0.23415337472333597, -0.23413695694918055, 1.5792128155073915, 0.7674347291529088, -0.4694743859349521, 0.5425600435859647 ]], 'covariance': [[0.2081069604419522]], 'factor': 0.6309573444801932, 'inv_cov': [[4.805221304834407]] } # Run distribution = KDEUnivariate.from_dict(parameters) # Check assert distribution.model.d == 1 assert distribution.model.n == 10 assert distribution.model.covariance == np.array([[0.2081069604419522]]) assert distribution.model.factor == 0.6309573444801932 assert distribution.model.inv_cov == np.array([[4.805221304834407]]) assert (distribution.model.dataset == np.array([[ 0.4967141530112327, -0.13826430117118466, 0.6476885381006925, 1.5230298564080254, -0.23415337472333597, -0.23413695694918055, 1.5792128155073915, 0.7674347291529088, -0.4694743859349521, 0.5425600435859647 ]])).all() def test_to_dict(self): """To_dict returns the defining parameters of a distribution in a dict.""" # Setup distribution = KDEUnivariate() column = np.array([[ 0.4967141530112327, -0.13826430117118466, 0.6476885381006925, 1.5230298564080254, -0.23415337472333597, -0.23413695694918055, 1.5792128155073915, 0.7674347291529088, -0.4694743859349521, 0.5425600435859647 ]]) distribution.fit(column) expected_result = { 'type': 'copulas.univariate.kde.KDEUnivariate', 'fitted': True, 'd': 1, 'n': 10, 'dataset': [[ 0.4967141530112327, -0.13826430117118466, 0.6476885381006925, 1.5230298564080254, -0.23415337472333597, -0.23413695694918055, 1.5792128155073915, 0.7674347291529088, -0.4694743859349521, 0.5425600435859647 ]], 'covariance': [[0.20810696044195218]], 'factor': 0.6309573444801932, 'inv_cov': [[4.805221304834407]] } # Run result = distribution.to_dict() # Check compare_nested_dicts(result, expected_result) def test_valid_serialization_unfit_model(self): """For a unfitted model to_dict and from_dict are opposites.""" # Setup instance = KDEUnivariate() # Run result = KDEUnivariate.from_dict(instance.to_dict()) # Check assert instance.to_dict() == result.to_dict() def test_valid_serialization_fit_model(self): """For a fitted model to_dict and from_dict are opposites.""" # Setup instance = KDEUnivariate() X = np.array([1, 2, 3, 4]) instance.fit(X) # Run result = KDEUnivariate.from_dict(instance.to_dict()) # Check assert instance.to_dict() == result.to_dict()
true