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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e3a049946807aa9e85077660df141dc38d9fa431
|
Python
|
jcmayoral/SEE-Project
|
/code/parameter_optimization.py
|
UTF-8
| 3,023
| 2.984375
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 5 11:23:37 2016
@author: jose
"""
import numpy as np
from scipy.optimize import minimize
def dF1(alphas, v, omega, v_hat, omega_hat, gamma_hat):
k = (alphas[0] * v**2 + alphas[1] * omega**2)
if k < 1e-100:
k = 1e-100
d = -0.5 * (v**2 / k - ((v - v_hat) * v**2) / (k**2))
return d
def dF2(alphas, v, omega, v_hat, omega_hat, gamma_hat):
k = (alphas[0] * v**2 + alphas[1] * omega**2)
if k < 1e-100:
k = 1e-100
d = -0.5 * (omega**2 / k - ((v - v_hat) * omega**2) / (k**2))
return d
def dF3(alphas, v, omega, v_hat, omega_hat, gamma_hat):
k = (alphas[2] * v**2 + alphas[3] * omega**2)
if k < 1e-100:
k = 1e-100
d = -0.5 * (v**2 / k - ((omega - omega_hat) * v**2) / (k**2))
return d
def dF4(alphas, v, omega, v_hat, omega_hat, gamma_hat):
k = (alphas[2] * v**2 + alphas[3] * omega**2)
if k < 1e-100:
k = 1e-100
d = -0.5 * (omega**2 / k - ((omega - omega_hat) * omega**2) / (k**2))
return d
def dF5(alphas, v, omega, v_hat, omega_hat, gamma_hat):
k = (alphas[4] * v**2 + alphas[5] * omega**2)
if k < 1e-100:
k = 1e-100
d = -0.5 * (v**2 / k - (gamma_hat * v**2) / (k**2))
return d
def dF6(alphas, v, omega, v_hat, omega_hat, gamma_hat):
k = (alphas[4] * v**2 + alphas[5] * omega**2)
if k < 1e-100:
k = 1e-100
d = -0.5 * (omega**2 / k - (gamma_hat * omega**2) / (k**2))
return d
def F(alphas, X):
s = 0.
for x in X:
k = (alphas[0] * x[0]**2 + alphas[1] * x[1]**2)
if k < 1e-100:
k = 1e-100
temp = -0.5 * (np.log(2 * np.pi) + np.log(k) + (x[0] - x[2]) / k)
k = (alphas[2] * x[0]**2 + alphas[3] * x[1]**2)
if k < 1e-100:
k = 1e-100
temp += -0.5 * (np.log(2 * np.pi) + np.log(k) + (x[1] - x[3]) / k)
k = (alphas[4] * x[0]**2 + alphas[5] * x[1]**2)
if k < 1e-100:
k = 1e-100
temp += -0.5 * (np.log(2 * np.pi) + np.log(k) + x[4] / k)
s += temp
return -1. * s
def F_prime(alphas, X):
d = np.zeros(len(alphas))
for i in xrange(len(alphas)):
s = 0.
if i == 0:
for x in X:
s += dF1(alphas, *x)
elif i == 1:
for x in X:
s += dF2(alphas, *x)
elif i == 2:
for x in X:
s += dF3(alphas, *x)
elif i == 3:
for x in X:
s += dF4(alphas, *x)
elif i == 4:
for x in X:
s += dF5(alphas, *x)
elif i == 5:
for x in X:
s += dF6(alphas, *x)
d[i] = s
return -1. * d
def optimise_parameters(data, init_alphas):
bounds = [(0., None), (0., None), (0., None), (0., None), (0., None), (0., None)]
r = minimize(F, init_alphas, args=(data,), method='L-BFGS-B', jac=F_prime, bounds=bounds, options={'disp': True})
alphas = r.x
return alphas
| true
|
8debb0a6a56ac596b24b638bb7df78191441c200
|
Python
|
YuJuncen/auto_sign
|
/src/SignClient.py
|
UTF-8
| 4,547
| 2.546875
| 3
|
[] |
no_license
|
from requests import post
from json import dumps, loads
from datetime import datetime as D
from sys import exc_info
from random import choice, random
from asyncio import sleep, run
from .Config import static_config as SConf
from .TokenFactory import AbstractTokenFactory
from .SignInfoServer import BaseSignInfoServer
from . import core_logger as log
from .DeviceInfo import DeviceInfo
from .SignServer import SignServer, csust_server
class SignClient(object):
"""
签到的控制器(Controllor)。
组合所有元素,并且最后发出签到请求。
```
__err_codes = {
0: "成功。",
1: "还没有到签到时间,如果强行签到的话可能会导致一些难以预测的后果。",
2: "服务器返回失败。",
3: "其它模块出现错误。",
4: "令牌错误,但是已经重新生成(不一定能生成有效令牌,具体取决于令牌工厂的力量)。"
}
```
"""
__err_codes = {
0: "成功。",
1: "还没有到签到时间,如果强行签到的话可能会导致一些难以预测的后果。",
2: "服务器返回失败。",
3: "其它模块出现错误。",
4: "令牌错误,但是已经重新生成(不一定能生成有效令牌,具体取决于令牌工厂的力量)。"
}
def __init__(self,
tfactory: AbstractTokenFactory,
dev: DeviceInfo,
infod: BaseSignInfoServer,
serv: SignServer = csust_server
):
self.__tfactory = tfactory
self.__server = serv
self.__dev = dev
self.__infod = infod
self.__token = self.__tfactory.make_token()
self.__sign_info = None
@property
def device(self):
"""
获得客户端的设备信息。
"""
return self.__dev
@property
def sign_info(self):
if self.__sign_info is None:
self.update_sign_info()
return self.__sign_info
def update_sign_info(self):
self.__sign_info, err = self.__infod.get_sign_info(self.__token)
if err != 0:
_, info = self.handle_with_data_getter_error(err)
raise RuntimeError(info)
log.debug(f"信息成功刷新。字段:{[k for k in self.__sign_info.keys()]}")
return 0
def auto_sign(self, force=False):
return run(self.async_auto_sign(force))
def handle_with_data_getter_error(self, err):
code, info = err
log.warning(f"获得信息的时候,出现了错误:{info}")
if code == 4:
self.__token = self.__tfactory.make_token()
return 4, self.__err_codes[4]
return 3, info
async def make_sign_data(self, bleChoicer: callable = choice):
"""
仅仅制造签到时所需要的请求数据(不包括 token),然后返回。
"""
datas = {
"bleId": bleChoicer([bled['bleId'] for bled in self.sign_info.get('bleinfoList')]),
"devUuid": self.__dev.device_uuid,
"osName": self.__dev.os_name,
"signId": self.sign_info.get("signId")
}
return datas
def check_time_is_vaild(self):
sign_info = self.sign_info
if (sign_info.get('sponsorStatus') == '0'):
log.warning('签到自己说它没有开始。')
log.info(f'签到启动时间:{sign_info.get("startTime")}。')
return False
return True
async def safety_delay(self):
delay_time = random() * 5 + 3
log.info(f"正在“搜索”蓝牙设备,预计用时 {delay_time}s。")
await sleep(delay_time)
async def async_auto_sign(self, force=False):
"""
usage:
** 自动签到。 **
args:
|name | usage |
|: ----- :|: ------ :|
|*force* | 不到时间也强制签到。|
return:
如果成功了,返回 None, 0。
否则,返回 context, (errcode, errinfo)。
"""
self.update_sign_info()
datas = await self.make_sign_data()
if not self.check_time_is_vaild():
if not force:
return datas, (1, self.__err_codes[1])
log.warning(f"强制在签到时间外签到。")
await self.safety_delay()
return self.__server.sign({
"header": {
"token": self.__token
},
"data": datas
})
| true
|
dc2044eaaf53e4d71c1236278eaf9e7daf48b7f2
|
Python
|
buddiman/alda2020
|
/sheet07/cocktails/cocktail.py
|
UTF-8
| 3,720
| 3.609375
| 4
|
[] |
no_license
|
'''
Christopher Höllriegl, Marvin Schmitt
Blatt 7 Aufgabe 1
'''
import json
import re
ignore = {'wasser', 'eiswürfel'}
#Aufgabe a)
# Read the recipes file and store the json object
# Finally... forgot to set utf-8 flag
with open('cocktails.json', encoding='utf-8') as data:
recipes = json.load(data)
def normalizeString(s):
'''
normalizes a string
:param s: string to normalize
:return: normalized string
'''
# remove things in brackets
s = s.split(" (")[0]
# make lowercase
s = s.lower()
# remove special characters with regex
re.sub(r"[^a-zA-Z0-9äüöÄÜÖß]+", ' ', s)
return s
def all_ingredients(recipes):
'''
Create a list of all ingredients
:param recipes: recipes
:return: list of ingredients
'''
ingredients = []
# for every cocktail in the recipes
for cocktail in recipes:
# go through every ingredient
for ingredient in recipes[cocktail]["ingredients"]:
ingredients.append(normalizeString(ingredient))
# use list as set because of duplicates
return list(set(ingredients))
#Aufgabe b)
def cocktails_inverse(recipes):
dictionary = {"":[]}
# create a list of all ingredients
ingredients = all_ingredients(recipes)
# now add every ingredient to the dictionary
for ingredient in ingredients:
dictionary.update({ingredient: []})
# add every cocktail to the ingredient if needed.
for cocktail in recipes:
name = cocktail
if contains_word(" ".join(recipes[cocktail]["ingredients"]).lower(), ingredient):
dictionary[ingredient].append(name)
return dictionary
# from stackoverflow because there are no 478 cocktails containing "ei"
def contains_word(s, w):
return (' ' + w + ' ') in (' ' + s + ' ')
def ingredient_count(inverse_recipes):
counts = {"": 0}
# count
for ingredient in inverse_recipes:
counts.update({ingredient: len(inverse_recipes[ingredient])})
return counts
#Aufgabe c)
#Wäre die Aufgabe nicht sinnvoller, wenn man mit der normalen Rezeptliste arbeitet anstatt der invertierten?
def possible_cocktails(inverse_recipes, available_ingredients):
possible_recipes = list()
for ingredient in available_ingredients:
ingredient = normalizeString(ingredient)
if ingredient in inverse_recipes:
for recipe in inverse_recipes[ingredient]:
if recipe not in possible_recipes:
possible_recipes.append(recipe)
for ingredient in inverse_recipes.keys():
if len(possible_recipes) == 0: break
if ingredient not in available_ingredients and ingredient not in ignore:
for recipe in inverse_recipes[ingredient]:
if recipe in possible_recipes:
possible_recipes.remove(recipe)
return possible_recipes
if __name__ == "__main__":
# Number of all ingredients
print("Number of ingredients overall: ", len(all_ingredients(recipes)))
# Print all ingredients
print(all_ingredients(recipes))
# instruction from the sheet
inverse_recipes = cocktails_inverse(recipes)
# dump the data as a json file
json.dump(inverse_recipes, open('cocktails_inverse.json', 'w', encoding='utf-8'))
# print the 15 most used ingredients
ingredients = ingredient_count(inverse_recipes)
print("\nIngredients in number of cocktails:")
n = 0
for item in sorted(ingredients, key=ingredients.get, reverse=True):
print(item, ingredients[item])
#if n < 15:
#print(item, ingredients[item])
#n += 1
possible_cocktails(inverse_recipes, {"Grapefruit", "Ribiselsirup", "Ananas"})
| true
|
b6705614a45ec82b6afc5c2c8e65c579f796d689
|
Python
|
zlouity/adventofcode2020
|
/03/day3b.py
|
UTF-8
| 530
| 3.296875
| 3
|
[] |
no_license
|
with open("day3.txt") as f:
array = []
for line in f.readlines():
array.append(line.strip())
def tree_counter(_array):
counter = 0
x =_array[0]
y =_array[1]
while y < len(array):
if array[y][x] =="#":
counter+=1
x = x+_array[0]
x = x%len(array[y])
y=y+_array[1]
return counter
items=[[1,1],[3,1],[5,1],[7,1],[1,2]]
multiply = 1
for thing in items:
multiply*=tree_counter(thing)
#print(tree_counter(thing))
print(multiply)
| true
|
1d92a5987221cc2c03d21017397c616ded4f5012
|
Python
|
jehunseo/Algorithm
|
/Baekjoon/17256.py
|
UTF-8
| 125
| 2.953125
| 3
|
[] |
no_license
|
a,b,c = [int(i) for i in input().split(' ')]
d,e,f = [int(i) for i in input().split(' ')]
print(f'{d - c} {e // b} {f - a}')
| true
|
e2fca4ac93a0fae10da3f40b86dee279fbaf43d0
|
Python
|
DustyHatz/CS50projects
|
/pset6/hello.py
|
UTF-8
| 185
| 4.03125
| 4
|
[] |
no_license
|
# This program takes in a users name and says hello to that person!
from cs50 import get_int, get_float, get_string
name = get_string("What is your name?\n")
print("hello, " + name)
| true
|
6dc2566580ad104129d96e9c9a3908537b91dfc8
|
Python
|
daniel-reich/ubiquitous-fiesta
|
/Y2AzE8m4n6RmqiSZh_21.py
|
UTF-8
| 67
| 3.109375
| 3
|
[] |
no_license
|
def reverse_list(num):
return [int(i) for i in str(num)][::-1]
| true
|
a3243e966545b34a2327f7b603dbcc7413be7a3d
|
Python
|
qiudebo/13learn
|
/code/matplotlib/aqy/aqy_lines_bars3.py
|
UTF-8
| 1,499
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'qiudebo'
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
plt.rcdefaults()
fig, ax = plt.subplots()
labels = (u"硕士以上", u"本科", u"大专", u"高中-中专", u"初中", u"小学")
x = (0.13, 0.22, 0.25, 0.18, 0.13, 0.10)
x1 = (-0.11, -0.19, -0.23, -0.20, -0.17, -0.10)
width = 0.35 # 条形图的宽度
y = np.arange(len(labels))
ax.barh(y, x, width, align='center', color='g', label=u'我的前半生')
ax.barh(y, x1, width, align='center', color='b', label=u'三生三世十里桃花')
ax.set_yticks(y + width/2)
ax.set_yticklabels(labels)
ax.invert_yaxis()
ax.set_xlabel('')
ax.set_title('')
# ax.yaxis.grid(True) # 水平网格
ax.xaxis.grid(True)
plt.xlim(-0.3, 0.3)
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
#ax.set_xticks(()) # 隐藏y轴
# 设置图例
# plt.legend(loc="lower right", bbox_to_anchor=[1, 0.95],shadow=True,
# ncol=1, title="Legend", fancybox=True)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=6)
# 去除样例周边的边框
# plt.legend(frameon=False)
ax.get_legend().get_title().set_color("red")
plt.show()
| true
|
67c79a08997fc1040e4f2144e6c6c0e01c80a727
|
Python
|
Deepak-Vengatesan/Skillrack-Daily-Challenge-Sloution
|
/15-6-2021.py
|
UTF-8
| 601
| 3.21875
| 3
|
[] |
no_license
|
R,C = map(int,input().split())
matrix = [list(map(int,input().split())) for row in range(R)]
N= int(input())
for row in range(0,R):
for col in range(0,C):
if N-col-1>=0 and N+col < C:
print(matrix[row][N-col-1]+matrix[row][N+col],end=" ")
elif N-col-1 >= 0:
print(matrix[row][N-col-1],end=" ")
elif N+col<C:
print(matrix[row][N+col],end=" ")
else:
break
print()
'''
3 5
1 2 3 4 5
2 4 6 8 2
10 20 30 40 50
4
3 5
1 2 3 4 5
4 8 6 7 9
10 20 30 45 55
2
3 5
1 2 3 4 5
2 4 6 8 2
10 20 30 40 50
5
'''
| true
|
365291e3b1f3a03ffd5062d6ee48fd51dbd234e7
|
Python
|
WangXin93/tianchi-fashionai-challenge
|
/TRAIN/view_data.py
|
UTF-8
| 4,453
| 2.53125
| 3
|
[] |
no_license
|
import torch
from torchvision import datasets, models, transforms
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import os
from PIL import Image
import matplotlib.pyplot as plt
import torchvision
import numpy as np
# import Augmentor
class FashionAttrsDataset(Dataset):
"""Fashion Attributes dataset."""
def __init__(self, csv_file, root_dir, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.fashion_frame = pd.read_csv(csv_file, names=['image', 'type','category'])
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.fashion_frame)
def __getitem__(self, idx):
img_name = os.path.join(self.root_dir,
self.fashion_frame.iloc[idx, 0])
# image = io.imread(img_name)
image = Image.open(img_name).convert('RGB')
category = self.fashion_frame.iloc[idx, 2]
# category = category[0] != ('y')
category = category.index('y')
if self.transform:
transformed_image = self.transform(image)
image = transforms.Resize((224,224))(image)
image = transforms.ToTensor()(image)
image = transforms.Normalize([0.63699209, 0.60060385, 0.59294991], [ 0.29762986, 0.30413315, 0.30129263])(image)
sample = {'image': image, 'category': category, 'transformed_image': transformed_image}
return sample
#p = Augmentor.Pipeline()
#p.rotate(probability=1.0, max_left_rotation=8, max_right_rotation=8)
#p.random_distortion(probability=1.0, grid_width=4, grid_height=4, magnitude=10)
data_transforms = {
'train': transforms.Compose([
# p.torch_transform(),
torchvision.transforms.RandomRotation(10),
torchvision.transforms.Resize((224, 224)),
torchvision.transforms.ColorJitter(brightness=32./255.,
contrast=0.5,
saturation=0.5,
hue=0.2),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.4, hue=0.4),
torchvision.transforms.ToTensor(),
transforms.Normalize([0.63699209, 0.60060385, 0.59294991], [ 0.29762986, 0.30413315, 0.30129263])
]),
'val': transforms.Compose([
torchvision.transforms.Resize((224,224)),
torchvision.transforms.ToTensor(),
transforms.Normalize([0.63699209, 0.60060385, 0.59294991], [ 0.29762986, 0.30413315, 0.30129263])
]),
}
csv_file = './data/fashionAI/neck_design_labels_train.csv'
root_dir = '/home/wangx/datasets/fashionAI/base/'
use_gpu = torch.cuda.is_available()
image_datasets = {x: FashionAttrsDataset(csv_file,
root_dir,
data_transforms[x])
for x in ['train', 'val']}
dataloaders = {x: DataLoader(image_datasets[x],
batch_size=16,
shuffle=True,
num_workers=4)
for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
def imshow(inp, ax, title=None):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.63699209, 0.60060385, 0.59294991])
std = np.array([0.29762986, 0.30413315, 0.30129263])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
ax.imshow(inp)
if title is not None:
ax.set_title(title)
#plt.pause(1) # pause a bit so that plots are updated
# Get a batch of training data
next_batch = next(iter(dataloaders['train']))
inputs, o_images, classes = next_batch['transformed_image'], next_batch['image'], next_batch['category']
classes = [str(i) for i in classes]
# Make a grid from batch
fig, axs = plt.subplots(2, 1, figsize=(16, 9))
axs[0].text(0, -5, ','.join(classes), fontsize=24)
out = torchvision.utils.make_grid(inputs)
imshow(out, axs[0], title='transformed images')
out = torchvision.utils.make_grid(o_images)
imshow(out, axs[1], title='original images')
plt.show()
| true
|
1b89b330bac9ecb13eddafb52899601f10ccd5e8
|
Python
|
jhli973/Projects
|
/filehandling/ReadFileFromSubfolder.py
|
UTF-8
| 1,678
| 3.453125
| 3
|
[] |
no_license
|
'''
Senario: Imagine we have houdreds of customer specific folders which hold package files.
Our mission is to check if two specific packages were created for each clients
This program is to find the specified files from any folder and return a
ordered dictionary of the foldername(ClientName):filename
'''
#Part one: read and process files with python
import os
import glob
import re
###1. give a path, don't add backslash to the end
path = raw_input("Please enteryour directory, otherwise use the default one.")
if path == '':
path = r'DirectoryPath'
###2. read all subfolder
#change the path to working directory
os.chdir(path)
##read only the subfolder name
#print [name for name in os.listdir(".") if os.path.isdir(name)]
subdirectories = [name for name in os.listdir(".") if os.path.isdir(name)]
##read the absolute subfolder name
#subdirectories = [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]
###3. select subfolder contains specific files and
# put the subfolder and filename into dictionary tbl_dict
tbl_dict = {}
dir_dict = {}
for subdir in subdirectories:
##cancatenate the path aand subdir
abssubdir = path + '\\' + subdir
#set the
os.chdir(abssubdir)
files = os.listdir(".") #return a list
##the following returns the a list of the absolute directory
for file in files:
#print file
if file == 'filename1.txt' or file == 'filename2.txt':
#print subdir, file
##insert into a dictionary
tbl_dict.setdefault(subdir, []).append(file)
dir_dict.setdefault(abssubdir, []).append(file)
#print the sorted dictionary according to the keys
for key, value in sorted(tbl_dict.items()):
print key, value
| true
|
744c093b1d6613503f03a4b4277c6803fc144ae9
|
Python
|
jaysurn/Leetcode_dailies
|
/Add_Two_Num.py
|
UTF-8
| 3,020
| 4.53125
| 5
|
[] |
no_license
|
# Goal : Return the sum of 2 postive integers stored as reverse linked lists
# Given : 2 linked lists of ints stored in reverse ( ex. 123 stored as 3->2->1 in list )
# Assumption : Lists' int value does not begin with 0
class Node: # Class definition for creating a Linkedlist
def __init__( self , data ):
self.data = data
self.next = None
def insert( L_list , data ): # Helper functon add a new node to a linkedlist
temp_node = Node ( data ) # New node created
if ( L_list == None ): # Create new linkedlist if doesn't exist and add new node
L_list = temp_node
else :
ptr = L_list # Pointer created to loop through node till you reach end
while ( ptr.next != None ):
ptr = ptr.next
ptr.next = temp_node # Add new node to end of linkedlist
return L_list
def print_L( L_list ): # Helper function to see the whole linkedlist
while ( L_list != None ):
print( L_list.data , end = " " )
L_list = L_list.next
print( "\n" )
return
def int_to_list( Integer ): # Helper function to convert ints used to linkedlists
L_list = None
for digit in reversed( Integer ):
L_list = insert( L_list , int( digit ) )
return L_list
def Add_Two_Num( list1 , list2 ): # Adds 2 lists and forms a new linkedlist with result stored in the same manner
carry = 0 # Used to perform math to see if a carry is needed to be added in the next addition
result_node = curr_node = Node( 0 ) # result_node and curr_node set to an empty node, result_node will stay at this root point while curr_node loops through lists
while list1 or list2 or carry: # while list1,list2,or the carry exists
if list1: # if list1 has another node, add data to carry and go to next node
carry += list1.data
list1 = list1.next
if list2:
carry += list2.data # if list2 has another node, add data to carry and go to next node
list2 = list2.next
curr_node.next = Node( carry % 10 ) # new node in result_node created from modular division forcing value to be between 0-9
curr_node = curr_node.next # go to next node
carry //= 10 # check if carry is greater than 10 using floor division to see if a carry-1 is needed for next addition
return result_node.next
def main():
int1 = "243" # User defined positive ints stored in reverse
int2 = "564"
list1 = int_to_list( int1 )
list2 = int_to_list( int2 )
print( "Adding lists {0} and {1}".format( int1 , int2 ) )
result_list = Add_Two_Num( list1 , list2 ) # Math performed here then prints on next line
print_L( result_list )
int3 = "2048" # User defined positives ints for testing ints of different lengths
int4 = "128"
list3 = int_to_list( int3 )
list4 = int_to_list( int4 )
print( "Adding lists {0} and {1}".format( int3 , int4 ) )
result_list = Add_Two_Num( list3, list4 ) # Math performed here then prints on next line
print_L( result_list )
main()
| true
|
7876e99a9af36d7e57ba6fef6f8822595a3c48c2
|
Python
|
me450722457/python_test
|
/test.py
|
UTF-8
| 345
| 3.09375
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
account = 'admin'
password = '123456'
user_account = input(str('Please input your account\n'))
user_password = input(str('Please input your password\n'))
if user_account == account:
if user_password == password:
print('success')
else:
print('password error')
else:
print('account error')
| true
|
d3ca57ef154ba5e774a9d152c4a5fabedb3cd951
|
Python
|
SamVyazemsky/otus
|
/PythonQA/Lesson16/perser_access_log.py
|
UTF-8
| 437
| 2.78125
| 3
|
[] |
no_license
|
import re
from collections import Counter
import json
def read_log(filename):
with open(filename) as f:
log = f.read()
ip_list = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', log)
return ip_list
def count_ip(ip_list):
count = Counter(ip_list)
return count
if __name__ == '__main__':
res = count_ip(read_log('access2.log'))
with open('res.json', 'w') as f:
json.dump(res, f)
| true
|
5aa7119e2387fe2d6d28a0ee62bf50386556a1d6
|
Python
|
henrytan0705/DS-A
|
/interview questions/twoSum.py
|
UTF-8
| 1,010
| 4.09375
| 4
|
[] |
no_license
|
# O(n log n) Time| O(1) Space
def twoNumberSum(array, targetSum):
# sort array in order
array.sort()
# track left and right elements with indexes
left_idx = 0
right_idx = len(array) - 1
while left_idx != right_idx:
left = array[left_idx]
right = array[right_idx]
# check if sum is equal to targetSum
# if sum is greater decrement right index
# else increment right index
if left + right == targetSum:
return [left, right]
elif left + right > targetSum:
right_idx -= 1
else:
left_idx += 1
# return empty array if no values add up
return []
# O(n) Time| O(n) Space
def twoNumberSum(array, targetSum):
# store values in object
values = {}
for num in array:
difference = targetSum - num
# check if difference currently exists in object
# else add current number into object
if difference in values:
return [num, difference]
else:
values[num] = True
# return empty array if no values add up
return []
| true
|
2f1b38ce8b3c1d2da522091bfa301516739ebd92
|
Python
|
anurag1212/Search-Algorithms
|
/Search Algos/DFS/dfs.py
|
UTF-8
| 1,286
| 2.765625
| 3
|
[] |
no_license
|
words = []
#newList=[]
for line in open('i2.txt'):
words.extend(line.split())
algo=words[0]
start=words[1]
goal=words[2]
live_lines=int(words[3])
ll=live_lines*3
graph1={}
#print words
def fill_graph():
for v in range(4,ll+4,3):
if(graph1.has_key(words[v])==False):
graph1[words[v]]=[words[v+1]]
elif(graph1.has_key(words[v])==True):
graph1[words[v]] = graph1.get(words[v], ()) + [words[v+1]]
for node in graph1.keys():
for node1 in graph1[node]:
if not graph1.has_key(node1):
graph1[node1]=[node1]
fill_graph()
print graph1
def dfs_path(graph, start, goal):
paths = []
stack = [(start, [start])]
while stack:
(vertex, path) = stack.pop(0)
vertices = graph1[vertex]
for x in path:
if x in vertices:
vertices.remove(x)
for next_vertex in vertices:
#print list(vertices)
new_path = path + [next_vertex]
if next_vertex == goal:
paths.append(new_path)
else:
stack.insert(0, (next_vertex, new_path))
return paths[-1]
print dfs_path(graph1, start, goal)
path = dfs_path(graph1, start, goal)
output = open("ou1.txt","w")
for i in range(0,len(path)):
output.write(path[i]+" "+str(i)+"\n")
| true
|
fb02f39486aafa860bf8df6c2976cc8db45d0c2c
|
Python
|
Serge45/MSVCAutoBuilder
|
/msbuilder.py
|
UTF-8
| 2,436
| 2.515625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import os, subprocess
class Msbuilder:
def __init__(self, \
sln_path = r".\\", \
prj_name = "", \
build_config = r"Release", \
devenv_path = ""):
self.possible_msbuild_path = []
self.msbuild_path = None
self.sln_path = sln_path
self.prj_name = prj_name
self.build_config = build_config
self.build_command = r'/Build'
if devenv_path != None:
if len(devenv_path):
self.possible_msbuild_path.append(devenv_path)
self.possible_msbuild_path.append(\
r"C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe")
for path in self.possible_msbuild_path:
if os.path.exists(path):
self.msbuild_path = path
break;
if self.msbuild_path == None:
raise Exception("devenv.exe not found.")
def build(self, rebuild = False):
if not os.path.isfile(self.msbuild_path):
raise Exception("devenv.exe not found.")
if rebuild:
self.build_command = r'/Rebuild'
arg1 = self.build_command
arg2 = self.build_config
arg3 = ""
arg4 = ""
arg5 = ""
arg6 = ""
if self.prj_name != None:
if len(self.prj_name):
arg3 = r'/project'
arg4 = self.prj_name
arg5 = r'/projectconfig'
arg6 = self.build_config
#Modify this line for git or delete it if you do not need update.
p = subprocess.call([r'svn', r'update', os.path.dirname(os.path.realpath(self.sln_path))])
if not p:
print 'Version updated.'
print 'Start building...'
print 'Build config: %s' %(self.build_config)
p = subprocess.call([self.msbuild_path, self.sln_path, arg1, arg2, arg3, \
arg4, arg5, arg6])
else:
print 'svn updating failed.'
return False
if not p:
print 'Build sucessfully.'
return True
else:
print "Build failed"
return False
#Example
if __name__ == '__main__':
msbuilder = Msbuilder(r'D:\projects\mp7600\mp7600.sln', r"MP7600Calibration", r'Release')
msbuilder.build(rebuild = False)
| true
|
77be83e2bc743cca9ecb8ecb7ba7e3a861f69d0b
|
Python
|
Flavio58it/Supervised-Product-Similarity
|
/test_model.py
|
UTF-8
| 1,299
| 2.828125
| 3
|
[] |
no_license
|
import numpy as np
from src.model import siamese_network
from src.common import Common
# ## Manual Testing ###############################################################
# Converts titles into embeddings arrays and allow the model to make a prediction #
###################################################################################
# Get the model architecture
model = siamese_network((Common.MAX_LEN, Common.EMBEDDING_SHAPE[0],))
model.summary()
# Load the model using the weights
model.load_weights('models/Softmax-LSTM-50-epochs.h5')
title_one = 'True Wireless Earbuds VANKYO X200 Bluetooth 5 0 Earbuds in Ear TWS Stereo Headphones Smart LED Display Charging Case IPX8 Waterproof 120H Playtime Built Mic Deep Bass Sports Work'
title_two = 'TOZO T10 Bluetooth 5 0 Wireless Earbuds Wireless Charging Case IPX8 Waterproof TWS Stereo Headphones Ear Built Mic Headset Premium Sound Deep Bass Sport Black'
title_one_arr = np.zeros((1, 42, 300))
title_two_arr = np.zeros((1, 42, 300))
title_one.lower()
title_two.lower()
for idx, word in enumerate(title_one.split(' ')):
title_one_arr[0, idx] = Common.fasttext_model[word]
for idx, word in enumerate(title_two.split(' ')):
title_two_arr[0, idx] = Common.fasttext_model[word]
print(model.predict([title_one_arr, title_two_arr]))
| true
|
81f4d65a3fefd7bdf5236b0eafea4a1a467dd563
|
Python
|
razmikarm/structures_in_python
|
/stack.py
|
UTF-8
| 1,116
| 3.609375
| 4
|
[] |
no_license
|
from __future__ import annotations
class Node:
def __init__(self, value):
self.__next = None
self.__value = value
@property
def value(self):
return self.__value
@value.setter
def value(self, value):
self.__value = value
@property
def next(self):
return self.__next
@next.setter
def next(self, node : Node):
self.__next = node
def __str__(self):
return str(self.value)
class Stack:
def __init__(self):
self.__peek = None
@property
def peek(self):
return self.__peek
@peek.setter
def peek(self, peek : Node):
self.__peek = peek
def pop(self):
self.peek = self.peek.next
def push(self, data):
new = Node(data)
new.next, self.peek = self.peek, new
def to_list(self):
as_list = []
current = self.peek
while current:
as_list.append(current.value)
current = current.next
return as_list
def __str__(self):
return ' <- '.join([str(val) for val in self.to_list()])
| true
|
e085c8bffb7023ac6a6356cbc059dc3ec3630050
|
Python
|
nizanshami/software_projet
|
/hw1/kmeans.py
|
UTF-8
| 4,213
| 3.578125
| 4
|
[] |
no_license
|
"""
Kmeans implementation in Python
Software Project ex. 1
Amit Elyasi
316291434
Nizan Shemi
206962912
"""
import sys
def Kmeans(k, max_iter=200):
data_points = read_data()
if not good_input(data_points, k):
return
centroids = data_points[:k]
for i in range(max_iter):
clusters = assign(data_points, centroids)
new_centroids = re_estimate(clusters)
if sorted(new_centroids) == sorted(centroids):
break
centroids = new_centroids
return centroids
def assign(data_points, centroids):
clusters = [[centroid] for centroid in centroids]
for point in data_points:
min_dst = distance(point, centroids[0])
closest_centroid_num = 0
for i,centroid in enumerate(centroids):
dst = distance(point, centroid)
if dst < min_dst:
min_dst = dst
closest_centroid_num = i
clusters[closest_centroid_num].append(point)
return clusters
def re_estimate(clusters):
new_centroids = []
for cluster in clusters:
cluster = cluster[0:]
new_centroids.append(average(cluster))
return new_centroids
def read_data():
vectors = []
while(True):
try:
for line in input().split("\n"):
vectors.append(toFloat(line.split(",")))
except EOFError:
break
return vectors
def toFloat(arr):
for i,str in enumerate(arr):
arr[i] = float(str)
return arr
def good_input(vectors, k):
dim = len(vectors[0])
for vector in vectors:
if len(vector) != dim:
print(f"INPUT ERROR:\nthe vector {vector} is {len(vector)} dimentional, different from the first vector dimention: {dim}")
return False
if len(vectors) < k:
print(f"INPUT ERROR:\nthere are less then k={k} data points")
return False
return True
def average(cluster):
dim = len(cluster[0])
avg = [0 for i in range(dim)]
cluster_size = len(cluster)
for point in cluster:
avg = vectors_sum(point, avg)
avg = scalar_div(avg, cluster_size)
return avg
def distance(vec1, vec2):
# if vec is scalar:
if type(vec2) in (int, float):
return abs(vec1-vec2)
if len(vec1) != len(vec2):
print("The vectors are not in the same length")
return -1
sum = 0
for i in range(len(vec1)):
sum += (vec1[i]-vec2[i])**2
return sum
def vectors_sum(vec1,vec2):
# if vec is scalar:
if type(vec1) in (int, float):
return vec1+vec2
if len(vec1) != len(vec2):
print("The vectors are not in the same length")
return -1
sum_vec = [0 for i in range(len(vec1))]
for i in range(len(vec1)):
sum_vec[i] = vec1[i] + vec2[i]
return sum_vec
def scalar_div(vec, x):
if x==0 :
print("you can't divide by zero")
return -1
# if vec is scalar:
if type(vec) in (int, float) :
return vec/x
for i in range(len(vec)):
vec[i] = vec[i]/x
return vec
def main():
try:
k = int(sys.argv[1])
if (k <= 0):
print("INPUT ERROR:\nk can't be <= 0")
return 1
except ValueError:
print("INPUT ERROR:\nk can't be a letter")
return 1
# algorithm
if len(sys.argv) >= 3:
try:
max_iter = int(sys.argv[2])
except ValueError:
print("INPUT ERROR:\nk can't be a letter")
return 1
if max_iter <= 0:
print("INPUT ERROR:\nmax iteration can't be <= 0")
return 1
centroids = Kmeans(k, max_iter=max_iter)
else:
centroids = Kmeans(k)
# print in the right format
for j,centroid in enumerate(centroids):
if j != 0:
print("\n", end="")
for i,coordinate in enumerate(centroid):
if i!=0 :
print(",", end="")
print("%.4f" % coordinate, end="")
if __name__ == "__main__":
main()
| true
|
5b8db511d50e8f2b37bc2ede8a107f534394e9eb
|
Python
|
zhjohn925/test_python
|
/TeachKidsPython/p00Spiral1.py
|
UTF-8
| 539
| 4.09375
| 4
|
[] |
no_license
|
import turtle
# https://docs.python.org/3.3/library/turtle.html?highlight=turtle
t1 = turtle.Turtle() # or use alias turtle.Pen()
t2 = turtle.Turtle()
t1.pencolor('blue')
t1.penup()
t1.setpos(100, 100)
t1.pendown()
t2.pencolor('pink')
for x in range(30):
t1.forward(x) # move forward x pixels
#t1.left(90) # turn left 90 degrees
#what happens if we try
t1.left(91)
# change forward() to circle()
t2.circle(x) # radius of x pixels
t2.left(90)
while True:
t1.hideturtle()
t2.hideturtle()
| true
|
499c334aaaf704c08661536b80f3bb9bfe23147e
|
Python
|
davidbrough1/TSP_Algorithms
|
/plot_points.py
|
UTF-8
| 1,814
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
# This file contains code used to generate plots from the trace and
# solution plots
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import csv
from os import listdir
from os.path import isfile, join
import sys
mypath = "/home/davinciwin/Algos/Amish_data"
output_path = "/home/davinciwin/Algos"
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
error = []
time = dict()
quality = sys.argv[1]
name = sys.argv[2]
optimum = int(sys.argv[3])
for i in range(len(onlyfiles)):
input_file_reader = csv.reader(
open(mypath + "/" + onlyfiles[i]), delimiter=',')
counter = 0
row_error = []
row_time = []
for row in input_file_reader:
temp_error = (int(row[1]) - optimum) / optimum
row_error.append((int(row[1]) - optimum) / optimum)
time[temp_error] = float(row[0])
# print row[1]
counter += 1
error.append(row_error)
# time.append(row_time)
# print error
# print row_error
storage_time = []
print len(error), len(row_error)
for row in error:
print row
for j in range(len(row)):
if(row[j] < float(quality)):
print row[j]
storage_time.append(time[row[j]])
break
storage_time.sort()
# print storage_time
output_file = open(output_path + "/" + "results" + "_" +
name + quality + str(optimum) + ".txt", 'w')
test = int(storage_time[0])
test_array = []
count_array = []
while(test < int(max(storage_time) + 2)):
count = 0
for m in range(len(storage_time)):
if(storage_time[m] < test):
count += 1
output_file.write(str(test) + "," + str(count / 10) + "\n")
test_array.append(test)
count_array.append(count / 10)
test += 1
plt.plot(test_array, count_array)
plt.show()
| true
|
520c09ef12ec0f5b6b81d720df46e0aebeab07b5
|
Python
|
sek788432/Electricity-Forecasting-DSAI-HW-2021
|
/code/prophet.py
|
UTF-8
| 846
| 2.859375
| 3
|
[] |
no_license
|
from fbprophet import Prophet
from matplotlib import pyplot as plt
from neuralprophet import NeuralProphet
def prophet(data):
m = Prophet(interval_width=0.95, daily_seasonality=True)
m.fit(data)
future = m.make_future_dataframe(periods=7, freq='D')
forecast = m.predict(future)
forecast.tail(7)
plot_prophet(forecast, m)
return forecast.iloc[-7:, -1].tolist()
def plot_prophet(forecast, m):
m.plot(forecast)
m.plot_components(forecast)
def neural_prophet(data):
m = NeuralProphet()
m.fit(data, freq='D', epochs=1000)
future = m.make_future_dataframe(data, periods=7)
forecast = m.predict(future)
plot_neural_prophet(forecast, m)
return forecast.iloc[:, 2].tolist()
def plot_neural_prophet(forecast, m):
m.plot(forecast)
m.plot_components(forecast)
| true
|
441a52daeda41951a059a786e4183bd3b99f0d30
|
Python
|
szazyczny/MIS3640
|
/Session04/quadratic.py
|
UTF-8
| 888
| 3.921875
| 4
|
[] |
no_license
|
#Define a function quadratic(a, b, c) to solve a quadratic equation: ax^2+bx+c=0
#Discriminant: b^2−4ac
def quadratic(a, b, c):
'''
return the two roots of a quadratic equation.
'''
d = (b ** 2 - 4 * a * c) ** 0.5 #use discriminant, 0.5 is exponent to get square root
x = (-b + d) / (2 * a) #solving for x
return x
print(quadratic(1, 6, 9))
print(quadratic(3, 4, 5))
# def quadratic(a, b, c):
# if :
# d = (b ** 2 - 4 * a * c) ** 0.5 #use discriminant, 0.5 is exponent to get square root
# x = (-b + d) / (2 * a) #solving for x
# return x
# else:
# print('No Real Number Solution')
# return None
#two ways to get math package
from math import sqrt #only asking for sqrt, cant use other tools from math module
sqrt(4)
import math #imports all math tools
math.sqrt(4)
math.floor(5.1)
math.pi
| true
|
18c0c2ccc40270968df3517afaa6157b26919846
|
Python
|
gharib85/toqito
|
/toqito/state_opt/unambiguous_state_exclusion.py
|
UTF-8
| 3,444
| 3.671875
| 4
|
[
"MIT"
] |
permissive
|
"""Unambiguous state exclusion."""
from typing import List
import cvxpy
import numpy as np
from .state_helper import __is_states_valid, __is_probs_valid
def unambiguous_state_exclusion(
states: List[np.ndarray], probs: List[float] = None
) -> float:
r"""
Compute probability of unambiguous state exclusion [BJOPUS14]_.
This function implements the following semidefinite program that provides the optimal
probability with which Bob can conduct quantum state exclusion.
.. math::
\begin{align*}
\text{maximize:} \quad & \sum_{i=0}^n \sum_{j=0}^n
\langle M_i, \rho_j \rangle \\
\text{subject to:} \quad & \sum_{i=0}^n M_i \leq \mathbb{I},\\
& \text{Tr}(\rho_i M_i) = 0,
\quad \quad \forall 1 \leq i \leq n, \\
& M_0, \ldots, M_n \geq 0
\end{align*}
Examples
==========
Consider the following two Bell states
.. math::
u_0 = \frac{1}{\sqrt{2}} \left( |00 \rangle + |11 \rangle \right) \\
u_1 = \frac{1}{\sqrt{2}} \left( |00 \rangle - |11 \rangle \right).
For the corresponding density matrices :math:`\rho_0 = u_0 u_0^*` and
:math:`\rho_1 = u_1 u_1^*`, we may construct a set
.. math::
\rho = \{\rho_0, \rho_1 \}
such that
.. math::
p = \{1/2, 1/2\}.
It is not possible to unambiguously exclude either of the two states. We can see that the result
of the function in :code:`toqito` yields a value of :math:`0` as the probability for this to
occur.
>>> from toqito.state_opt import unambiguous_state_exclusion
>>> from toqito.states import bell
>>> import numpy as np
>>> rho1 = bell(0) * bell(0).conj().T
>>> rho2 = bell(1) * bell(1).conj().T
>>>
>>> states = [rho1, rho2]
>>> probs = [1/2, 1/2]
>>>
>>> unambiguous_state_exclusion(states, probs)
-7.250173600116328e-18
References
==========
.. [BJOPUS14] "Conclusive exclusion of quantum states"
Somshubhro Bandyopadhyay, Rahul Jain, Jonathan Oppenheim,
Christopher Perry
Physical Review A 89.2 (2014): 022336.
arXiv:1306.4683
:return: The optimal probability with which Bob can guess the state he was
not given from `states` with certainty.
"""
obj_func = []
measurements = []
constraints = []
__is_states_valid(states)
if probs is None:
probs = [1 / len(states)] * len(states)
__is_probs_valid(probs)
dim_x, dim_y = states[0].shape
# The variable `states` is provided as a list of vectors. Transform them
# into density matrices.
if dim_y == 1:
for i, state_ket in enumerate(states):
states[i] = state_ket * state_ket.conj().T
for i, _ in enumerate(states):
measurements.append(cvxpy.Variable((dim_x, dim_x), PSD=True))
obj_func.append(probs[i] * cvxpy.trace(states[i].conj().T @ measurements[i]))
constraints.append(cvxpy.trace(states[i] @ measurements[i]) == 0)
constraints.append(sum(measurements) <= np.identity(dim_x))
if np.iscomplexobj(states[0]):
objective = cvxpy.Maximize(cvxpy.real(sum(obj_func)))
else:
objective = cvxpy.Maximize(sum(obj_func))
problem = cvxpy.Problem(objective, constraints)
sol_default = problem.solve()
return 1 / len(states) * sol_default
| true
|
fc5b4e10560be66e6173735da674dbb6cacc5615
|
Python
|
MaxConstruct/ClimateSample
|
/analysis/netcdf_util.py
|
UTF-8
| 3,195
| 2.71875
| 3
|
[] |
no_license
|
# Import libraries and set configuration
# os used for path and directory management
import os
# xarray, is the most important library, used for manipulate netCDF Dataset operation
from pathlib import Path
import xarray as xr
import numpy as np
# matplotlib for plotting Dataset. cartopy for various map projection
from distributed.deploy.old_ssh import bcolors
from matplotlib.axes import Axes
from cartopy.mpl.geoaxes import GeoAxes
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
# matplotlib setting
GeoAxes._pcolormesh_patched = Axes.pcolormesh
# %%
# Get country border for matplotlib
country_borders = cfeature.NaturalEarthFeature(
category='cultural',
name='admin_0_boundary_lines_land',
scale='50m',
facecolor='none')
# %%
def select_range(data, _min, _max):
"""
create boolean array for selecting data within specific range.
min <= data <= max
:param data: DataArray to be selected.
:param _min: min value
:param _max: max value
:return: boolean DataArray
"""
return (data >= _min) & (data <= _max)
def crop_dataset_from_bound(data, lon_bound, lat_bound, x_name='lon', y_name='lat'):
"""
Crop dataset in to specific lat & lon boundary
:param data: xarray.Dataset to be cropped
:param lon_bound: list that contain [min_lon, max_lon]
:param lat_bound: list that contain [min_lat, max_lat]
:return: cropped dataset as xarray.Dataset
"""
mask_lon = select_range(data[x_name], lon_bound[0], lon_bound[1])
mask_lat = select_range(data[y_name], lat_bound[0], lat_bound[1])
return data.isel(lat=mask_lat, lon=mask_lon, drop=False)
def plot(data: xr.DataArray, time=None, savefig=None, show=True, set_global=False, country_border=True, **kwargs):
"""
Quick plotting DataArray using PlateCarree as a projection
Example: plot(dataset['tasmax'])
:param data: DataArray to be plotted
:param time: Specific time index to be plot using xarray.DataArray.isec method.
Default is 0.
:param savefig: path of figure to being save. Default is None (not save figure).
:param show: Is showing graphic plot. Default is True.
:param set_global: Set plotting to show global map.
:param country_border: Is show country border on the plot. Default is True.
:param kwargs: keyword arg pass to xarray.DataArray.plot
:return: None
"""
ax = plt.axes(projection=ccrs.PlateCarree())
if time is None:
if 'time' in data.coords and data.time.shape != ():
data.isel(time=0).plot(ax=ax, **kwargs)
else:
data.plot(ax=ax, **kwargs)
else:
data.isel(time=time).plot(ax=ax, **kwargs)
if country_border:
ax.add_feature(country_borders, edgecolor='black')
if set_global:
ax.set_global()
ax.coastlines()
if savefig is not None:
plt.savefig(savefig)
if show:
plt.show()
plt.clf()
plt.close()
def select_year(ds, from_y, to_y):
return ds.sel(time=ds.time.dt.year.isin(np.arange(from_y, to_y + 1)))
def save_file(path: Path):
path.parent.mkdir(parents=True, exist_ok=True)
return path
| true
|
7227c471e01b92533fd45d035fd81bd5d6e98def
|
Python
|
Leir-Cruz/ED
|
/questionario_grafo/q4.py
|
UTF-8
| 867
| 3.375
| 3
|
[] |
no_license
|
class Vertex:
def __init__(self, key):
self.key = key
self.neighboors = {}
def addNeighboor(self, vertex):
self.neighboors[vertex.key] = Vertex(vertex)
class Graph:
def __init__(self):
self.vertList = {}
def addVertex(self, key):
newVextex = Vertex(key)
self.vertList[key] = newVextex
def existence(self, key):
return True if key in self.vertList else False
def getVertex(self,n):
return self.vertList[n] if n in self.vertList else None
myGraph = Graph()
for i in range(int(input())):
myInput = input().split()
myGraph.addVertex(myInput[0])
for item in myInput[2:]:
myGraph.addVertex(item)
myGraph.getVertex(myInput[0]).addNeighboor(myGraph.getVertex(item))
myGraph.getVertex(item).addNeighboor(myGraph.getVertex(myInput[0]))
| true
|
95a9e6a79e7db1e075d77eb7d51ee305d7809b46
|
Python
|
WANGLU2/WANGLU_CP1404practicals
|
/prac_03/convert_temps.py
|
UTF-8
| 369
| 3.875
| 4
|
[] |
no_license
|
def main():
out_file = open("temps_output.txt", "w")
in_file = open("temps_input.txt", "r")
for line in in_file:
Fahrenheit = float(line)
print(convert_fahrenheit_to_celsius(Fahrenheit), file=out_file)
in_file.close()
def convert_fahrenheit_to_celsius(Fahrenheit):
celsius = 5 / 9 * (Fahrenheit - 32)
return celsius
main()
| true
|
543bcc4c448c10a3f0e0faca19b41bbec3dd24b6
|
Python
|
abhi8893/tensorflow-developer-certificate-deeplearning-ai
|
/04-sequences-time-series-and-prediction/course-notebooks/utils.py
|
UTF-8
| 778
| 3.4375
| 3
|
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
def plot_series(time, series, format="-", start=0, end=None, label=None):
plt.plot(time[start:end], series[start:end], format, label=label)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(True)
def trend(time, slope=0):
return slope * time
def seasonal_pattern(season_time):
return np.where(season_time < 0.4,
np.cos(season_time * 2 * np.pi),
1 / np.exp(3 * season_time))
def seasonality(time, period, amplitude=1, phase=0):
season_time = ((time + phase) % period) / period
return amplitude * seasonal_pattern(season_time)
def noise(time, noise_level=1, seed=None):
rnd = np.random.RandomState(seed)
return rnd.randn(len(time)) * noise_level
| true
|
e3542802a904bc9fa329e32e486080492921d731
|
Python
|
WeichselRiver/database
|
/sqlalchemy_test.py
|
UTF-8
| 560
| 3.125
| 3
|
[] |
no_license
|
from sqlalchemy import create_engine
db_string = "postgresql://postgres:<pwd>@localhost:5432/postgres"
db = create_engine(db_string)
# Create
db.execute("CREATE TABLE IF NOT EXISTS films (title text, director text, year text)")
db.execute("INSERT INTO films (title, director, year) VALUES ('Doctor Strange', 'Scott Derrickson', '2016')")
# Read
result_set = db.execute("SELECT * FROM films")
for r in result_set:
print(r)
# Update
db.execute("UPDATE films SET title='Some2016Film' WHERE year='2016'")
# Delete
db.execute("DELETE FROM films WHERE year='2016'")
| true
|
af50b4006e89d70cff91a58eeac7669638e152c5
|
Python
|
sanxml/Conveyor-belt-grabbing-device
|
/code/main.py
|
UTF-8
| 2,073
| 2.515625
| 3
|
[] |
no_license
|
import cv2 as cv
import numpy as np
import serial
import time
from binascii import unhexlify
from crcmod import mkCrcFun
import picture_process
import control
camera=cv.VideoCapture(2)
ROI_rect = (150,0,640-150,480)
lower_green = np.array([35, 45, 0])
upper_green = np.array([100, 255, 255])
# control.coordinate_write(0, 100, -320)
# control.coordinate_write(0, 100, -380)
# control.coordinate_write(0, 100, -320)
# control.coordinate_write(0, -100, -320)
# control.coordinate_write(0, -100, -380)
# control.coordinate_write(0, 0, -320)
# control.coordinate_read()
P1 = [0, 100, -320, 90, 6, 1]
P2 = [0, 100, -380, 90, 6, 1]
P3 = [0, 100, -320, 90, 6, 1]
P4 = [0, -100, -320, 0, 6, 1]
P5 = [0, -100, -380, 0, 6, 1]
P6 = [0, -100, -320, 0, 6, 0]
P7 = [0, 0, -320, 0, 6, 0]
control.coordinate_write_seven(P1,P2,P3,P4,P5,P6,P7)
def main():
while(True):
ret ,img = camera.read()
# img = cv.resize(img, (480,360))
img_ROI = img[ROI_rect[1]:ROI_rect[1]+ROI_rect[3],ROI_rect[0]:ROI_rect[2]]
cv.line(img,(145,0),(145,480),(0,255,255),thickness=2) #画线
cv.line(img,(640-145,0),(640-145,480),(0,255,255),thickness=2)
img_hsv = cv.cvtColor(img_ROI, cv.COLOR_BGR2HSV) # 将图片转为灰度图
img_mask = cv.inRange(img_hsv, lower_green, upper_green) # 限定范围,转为二值化图片,这里只保留绿色分量
img_bin = cvbitwise_not(img_mask) #将图片反转,这里只保留除绿色的其他分量
img_bin = cv.GaussianBlur(img_bin,(5,5),0) #高斯模糊
kernel = cv.getStructuringElement(cv.MORPH_RECT,(7, 7)) #设置形态学运算所需要的卷积核
img_bin = cv.erode(img_bin,kernel) #腐蚀图像
img_bin = cv.dilate(img_bin,kernel) #膨胀图像
contours_list = picture_process.find_contours(img_ROI,img_bin)
cv.imshow("camera", img)
cv.imshow("img_bin", img_bin)
cv.imshow("img_ROI", img_ROI)
if(cv.waitKey(1)==27): #按下Esc键关闭窗口
break
camera.release()
| true
|
e8afe0c71f21cc2be8d1b7b146c8b99e33c9c0b8
|
Python
|
Michael-Python/w3_weekend_game_v3
|
/w3_homework_v3/app/models/player.py
|
UTF-8
| 117
| 2.84375
| 3
|
[] |
no_license
|
class Player:
def __init__(self, player, choice):
self.player = player
self.choice = choice
| true
|
c3886224ef132f059eb058f7398e32663cd7af81
|
Python
|
mohammedlutf/cg
|
/1.py
|
UTF-8
| 784
| 3.671875
| 4
|
[] |
no_license
|
import csv
print("the most specific hypothesis is :[000000]")
a=[]
print("the given training dataset \n")
with open('ws.csv','r') as csvfile:
reader=csv.reader(csvfile)
for row in reader:
a.append(row)
print(row)
num_attributes=len(a[0])-1
print("the initial value of hypothesis:\n")
hypothesis = ['0']*num_attributes
print (hypothesis)
for j in range (0,num_attributes):
hypothesis[j]=a[0][j]
print (hypothesis)
print("For finding maximum specific Hypothesis")
for i in range(0,len(a)):
if a[i][num_attributes]=='yes':
for j in range(0,num_attributes):
if a[i][j]!= hypothesis[j]:
hypothesis[j]='?'
print("For Learnig Example no",i,"the hypothesis is ",hypothesis)
print("The maximally specific hyptothesis for a given training Egs")
print(hypothesis)
| true
|
291a64696ae8595db81eac3fb012874f9b913f08
|
Python
|
tebeco/MyDemos
|
/Python/Demos/NumPyDemos/4/4-7.py
|
UTF-8
| 274
| 2.796875
| 3
|
[] |
no_license
|
#!/usr/bin/python
#-*-coding:utf-8-*-
import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
print student
print '###################################'
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
print a
| true
|
b92dc0b13cc7b327f3bbefc891e6be7aec456956
|
Python
|
Bazzzzzinga/Credit-Risk-Assessment
|
/Implementations/2.KNN/knn.py
|
UTF-8
| 1,274
| 2.828125
| 3
|
[] |
no_license
|
import os,csv,math
import numpy as np
from sklearn.metrics import classification_report
#Reading Data
csv_file_object = csv.reader(open('csvdataset.csv', 'rb'))
data=[]
for row in csv_file_object:
data.append(row)
data=np.array(data)
data=data[2::]
x=data[:,1:24]
y=data[:,24:25]
x=x[:,:].astype(np.float64)
x=(x-np.mean(x,axis=0))/np.std(x,axis=0)
y=y[:].astype(np.float64)
trainx=x[0:21000]
trainy=y[0:21000]
remainx=x[21000:len(x)]
remainy=y[21000:len(x)]
distance0=[]
distance1=[]
for j in range(len(remainx)):
d0=[]
d1=[]
print j
for i in range(len(trainx)):
temp=(np.square(trainx[i]-remainx[j])).sum()
if(trainy[i]==0):
d0.append(temp)
else:
d1.append(temp)
d0.sort()
d1.sort()
distance0.append(d0)
distance1.append(d1)
distance0=np.array(distance0)
distance1=np.array(distance1)
for i in range(1,51):
distance0[:,i:i+1]=distance0[:,i:i+1]+distance0[:,i-1:i]
distance1[:,i:i+1]=distance1[:,i:i+1]+distance1[:,i-1:i]
for i in range(0,50):
sum=0
a=np.ones((len(remainx),1))*2
for j in range(len(remainx)):
if(distance0[j][i]>distance1[j][i]):
a[j]=1
if(remainy[j]==1):
sum=sum+1
else:
a[j]=0
if(remainy[j]==0):
sum=sum+1
print "k = ",i+1," Accuracy = ",(sum*1.0)/len(remainy)
print classification_report(remainy,a)
| true
|
50a93efcf6e1ef6c5b453ed2b35424f0e3dc5d70
|
Python
|
Ciprianivan2015/2020_PYHTON_SORTING
|
/PY_numpy_sorting_20200403.py
|
UTF-8
| 1,955
| 3.078125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 3 19:14:47 2020
@author: Cipriandan
1. define list of sample size
2. for each element in the list_1: create random.normal()
3. for each element in the list_1
4. for each element in the list_of_sorting_algorithms
5. t0 = time.time()
6. sort( sample_Iter_n, method = sort_iter )
7. t1 = time.time()
8. tt = t1 - t0
9. add ( line to DataFrame )
......................... SORTING ................................
"""
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
import time
start_pw = 4
stop_pw = 6
pw = np.arange( start_pw, stop_pw + 1,1 )
arr_ss = np.power( [ 10 ] * ( stop_pw - start_pw + 1) , pw )
arr_ss = np.hstack( (arr_ss, np.multiply( [ 10**(stop_pw-1) ], range(2,91,1)) ) )
arr_ss = np.sort( arr_ss )
arr_sk = np.array(['quicksort','mergesort','heapsort'])
col_names_1 = [ 'sample_size' ,'value']
df_nums = pd.DataFrame( columns = col_names_1 )
col_names_2 = ['sort_type', 'sample_size', 'time_to_sort']
df_sort = pd.DataFrame( columns = col_names_2 )
big_sample_size = arr_ss[-1:]
the_values = np.random.normal( 0,1, big_sample_size ) * 1000
for iter_i in arr_ss:
for iter_k in arr_sk:
t0 = time.time()
np_temp = np.sort( the_values[- iter_i:],
kind = iter_k )
t1 = time.time()
tt = t1 - t0
df_temp = pd.DataFrame({ 'sort_type':iter_k, 'sample_size':iter_i, 'time_to_sort':tt },index = [0])
frames = [ df_sort, df_temp ]
df_sort = pd.concat( frames )
del np_temp
sns.set_style("darkgrid")
g = sns.FacetGrid( df_sort, hue = 'sort_type')
g = g.map(plt.scatter , 'sample_size','time_to_sort', marker='.')
g = g.map(plt.plot , 'sample_size','time_to_sort', marker='.', linestyle = ':').add_legend()
| true
|
e3d2fb72b04aa45fb993fc76ce6c660febf6180e
|
Python
|
john-Lyrics/John
|
/fibonachi.py
|
UTF-8
| 183
| 3.171875
| 3
|
[] |
no_license
|
def fib_rec(n):
if n<= 1 :
return n
else :
return fib_rec(n-1) + fib_rec(n-2)
print(fib_rec(10))
print(list(map(fib_rec, range(1,11))))
| true
|
511157a8663341e503408a2a3b88e8809413d8cf
|
Python
|
zurk/lookout-sdk-ml
|
/lookout/core/tests/test_metrics.py
|
UTF-8
| 6,267
| 2.828125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
import threading
import unittest
import requests
from lookout.core.metrics import ConfidentCounter, PreciseFloat, record_event
class MetricReader:
def __init__(self, port, addr="localhost"):
self.__is_running = False
self.__port = port
self.__addr = addr
self.__metrics = {}
self.__data = {}
@property
def port(self) -> int:
return self.__port
@property
def addr(self) -> str:
return self.__addr
@property
def metrics(self) -> dict:
return self.__metrics
@property
def data(self) -> dict:
return self.__data
def query_data(self, addr: str = None, port: int = None) -> str:
addr = self.addr if addr is None else addr
port = self.port if port is None else port
api_endpoint = "http://{}:{}".format(addr, port)
r = requests.get(url=api_endpoint)
if r.status_code == 200:
data = r.content.decode()
return data
raise ValueError(
"\nGot status code {} when querying the server."
" Reponse content: {}\n".format(r.status_code, r.content.decode()),
)
@staticmethod
def parse_response(data: str):
lines = data.split("\n")
def is_metric_line(line: str):
return not (line.startswith("#") or line.startswith("python") or line == "")
def parse_line(line):
try:
name, val = line.split(" ")
except ValueError:
return line, None
try:
val = float(val)
except ValueError:
pass
return name, val
raw_metrics = [l for l in lines if is_metric_line(l)]
metric_values = [parse_line(l) for l in raw_metrics]
metrics = {name: val for name, val in metric_values}
return metrics
def parse_data(self, addr: str = None, port: int = None):
decoded_response = self.query_data(addr=addr, port=port)
self.__data = self.parse_response(decoded_response)
self.__metrics = {
name: val for name, val in self.__data.items() if not name.startswith("process_")
}
def query_metrics(self, name: str):
return {k: v for k, v in self.metrics.items() if name in k}
def dummy_server():
from lookout.core.metrics import _prometheus_server as server
if server is None:
try:
record_event("start_server_hack", 8000)
except OSError as e:
raise e
from lookout.core.metrics import _prometheus_server as server
assert server is not None
return server
class TestConfidentCounter(unittest.TestCase):
def test_kahan_algorithm(self):
metric = ConfidentCounter("test_data_kahan", "running counters")
# why this number? https://en.wikipedia.org/wiki/Double-precision_floating-point_format
origin = brute_sum = 4503599627370496 # 4_503_599_627_370_496
metric += origin
val = 0.001
for _ in range(1000):
brute_sum += val
metric += val
metric_val = metric.collect()[0].samples[1].value
self.assertEqual(metric_val, origin + 1.)
self.assertNotEqual(brute_sum, origin + 1)
def test_get(self):
metric = ConfidentCounter("test_get_counter", "running counters")
metric += 10
self.assertEqual(metric._count.get(), 1)
self.assertEqual(metric._sum.get(), 10)
self.assertEqual(metric._sum_of_squares.get(), 100)
def test_set(self):
metric = ConfidentCounter("test_set_counter", "running counters")
metric._count.set(1)
metric._sum.set(10)
metric._sum_of_squares.set(100)
self.assertEqual(metric._count.get(), 1)
self.assertEqual(metric._sum.get(), 10)
self.assertEqual(metric._sum_of_squares.get(), 100)
def test_multithread(self):
x = PreciseFloat()
threads = []
def bump():
nonlocal x
for _ in range(1000):
x += 1
for _ in range(100):
t = threading.Thread(target=bump)
t.start()
threads.append(t)
for i in range(100):
threads[i].join()
self.assertEqual(x.get(), 100 * 1000)
class TestPrometheusServer(unittest.TestCase):
def setUp(self) -> None:
self.reader = MetricReader(8000)
self.server = dummy_server()
def test_attributes(self):
self.assertIsInstance(self.server.metrics, dict)
self.assertIsInstance(self.server.host, str)
self.assertIsInstance(self.server.port, int)
def test_filter_metric_name(self):
valid_name = "miau.gdb"
filtered = self.server._adjust_metric_name(name=valid_name)
self.assertEqual(filtered, "miau:gdb")
with self.assertRaises(ValueError):
invalid_name = "!AM!?wilto%."
self.server._adjust_metric_name(name=invalid_name)
# match = self.server._valid_name_regex.match(invalid_name)
# self.assertEqual(filtered, match)
def test_submit_rolling_stats(self):
name = "test_rolling_stats"
val = 4
self.server.submit_event(key=name, value=val)
val = 6
self.server.submit_event(key=name, value=val)
self.reader.parse_data()
self.assertTrue("{}_sum".format(name) in list(self.reader.metrics.keys()))
self.assertTrue("{}_count".format(name) in list(self.reader.metrics.keys()))
self.assertTrue(self.reader.metrics["{}_count".format(name)] == 2)
self.assertTrue(self.reader.metrics["{}_sum".format(name)] == 10)
self.assertTrue(self.reader.metrics["{}_sum_of_squares".format(name)] == 52)
class TestSubmitEvent(unittest.TestCase):
def setUp(self) -> None:
self.server = dummy_server()
self.reader = MetricReader(8000)
def test_send_new_scalar(self):
name = "a_float"
record_event(name, 3.1)
self.reader.parse_data()
self.assertTrue(self.reader.metrics["{}_sum".format(name)] == 3.1)
record_event(name, 5.1)
self.reader.parse_data()
self.assertTrue(self.reader.metrics["{}_sum".format(name)] == 8.2)
| true
|
90e9692d11ad2658f2681164d53440f21fcfcc09
|
Python
|
harry671003/coursera-algorithmic-toolbox
|
/week-2/euclidean-gcd.py
|
UTF-8
| 563
| 3.734375
| 4
|
[] |
no_license
|
def gcd(n1, n2):
# Swap numbers in case n1 < n2
if n1 < n2:
temp = n1
n1 = n2
n2 = temp
print("n1: %d | n2: %d" % (n1, n2))
if n2 == 0:
return n1
return gcd(n2, n1 % n2)
def main():
token = input('Enter 2 number: ')
(n1, n2) = token.split()
print('gcd(%s, %s) = %d' % (
n1,
n2,
gcd(
int(n1),
int(n2)
)
))
def test():
gcd(10**100000 + 234, 5 ** 4 + 3)
if __name__ == "__main__":
test()
| true
|
2ac640d2a8cd666eae373aebeb4a2a7e81133dba
|
Python
|
andreatrejod/TC101
|
/wsq10.py
|
UTF-8
| 1,035
| 4.21875
| 4
|
[] |
no_license
|
import statistics # Este módulo permite calcular operaciones estadísticas como las que necesitamos en este programa.
lista = [float(input("Please give me the first number: ")), float(input("Please give me the second number: ")),
float(input("Please give me the third number: ")), float(input("Please give me the fourth number: ")),
float(input("Please give me the fifth number: ")),float(input("Please give me the sixth number: ")),
float(input("Please give me the seventh number: ")),float(input("Please give me the eighth number: ")),
float(input("Please give me the nineth number: ")),float(input("Please give me the tenth number: "))]
promedio = statistics.mean(lista) #esta función permite encontrar el promedio
print("The average of your numbers is: {}".format(promedio))
suma = sum(lista)
print("The sum de of the numbers given by you is:{} ".format(suma))
std_des = statistics.stdev(lista)#esta función permite encontrar la desviación standard
print("The standard deviation of your numbers is: {}".format(std_des))
| true
|
397292fc6b253c856b13dda39e3531a87fac3da4
|
Python
|
Stargrazer82301/CAAPR
|
/CAAPR/CAAPR_AstroMagic/PTS/pts/magic/analysis/stars.py
|
UTF-8
| 5,138
| 2.765625
| 3
|
[
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter",
"MIT"
] |
permissive
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
## \package pts.magic.analysis.stars Contains functions for fitting stars.
# -----------------------------------------------------------------
# Ensure Python 3 functionality
from __future__ import absolute_import, division, print_function
# Import standard modules
import numpy as np
from scipy import ndimage
# Import the relevant PTS classes and modules
from ..tools import fitting, plotting, coordinates, cropping, regions
# -----------------------------------------------------------------
# THIS FUNCTION IS NOT USED ANYMORE, BUT CONTAINS UPSAMPLING CODE POTENTIALLY USEFUL LATER
def make_star_model(shape, data, annuli_mask, fit_mask, background_outer_sigmas, fit_sigmas,
model_name, upsample_factor=1.0, interpolate_background=True, sigma_clip_background=True, plot=False):
"""
This function ...
:param shape:
:param data:
:param annuli_mask:
:param fit_mask:
:param background_inner_sigmas:
:param background_outer_sigmas:
:param fit_sigmas:
:param upsample_factor:
:param interpolate_background:
:param sigma_clip_background:
:param plot:
:return:
"""
# Get the shape's parameters
x_center, y_center, x_radius, y_radius, _ = regions.ellipse_parameters(shape)
# Set the radii for cutting out the background box
radius = 0.5*(x_radius + y_radius)
x_radius_outer = background_outer_sigmas*x_radius
y_radius_outer = background_outer_sigmas*y_radius
# Cut out the background
background, x_min_back, x_max_back, y_min_back, y_max_back = cropping.crop(data, x_center, y_center, x_radius_outer, y_radius_outer)
# Cut out the mask for the background
background_mask = cropping.crop_check(annuli_mask, x_min_back, x_max_back, y_min_back, y_max_back)
# Set the radii for cutting out the box for fitting
x_radius_fitting = fit_sigmas*x_radius
y_radius_fitting = fit_sigmas*y_radius
# Cut out a box of selected frame around the star
star, x_min, x_max, y_min, y_max = cropping.crop(data, x_center, y_center, x_radius_fitting, y_radius_fitting)
# If the cropped region contains only one pixel row or column, a star model cannot be made
if star.shape[0] == 1 or star.shape[1] == 1: return False, shape, None, None
# Cut out the mask for fitting
star_mask = fit_mask[y_min:y_max, x_min:x_max]
# Estimate the background
background_mask_beforeclipping = np.copy(background_mask)
est_background, background_mask = estimate_background(background, background_mask, interpolate=interpolate_background, sigma_clip=sigma_clip_background)
# Crop the interpolated background to the frame of the box
star_background = cropping.crop_check(est_background, x_min-x_min_back, x_max-x_min_back, y_min-y_min_back, y_max-y_min_back)
# Calculate the relative coordinates of the center
x_center_rel, y_center_rel = coordinates.relative_coordinate(x_center, y_center, x_min, y_min)
# Fit the star
model_function = fitting.fit_2D_model(star, star_mask, star_background, model=model_name, x_center=x_center_rel,
y_center=y_center_rel, radius=radius, x_shift=x_min, y_shift=y_min,
upsample_factor=upsample_factor, pixel_deviation=0.5)
# Evaluate the model
evaluated_model = fitting.evaluate_model(model_function, x_min, x_max, y_min, y_max, x_delta=1.0/upsample_factor, y_delta=1.0/upsample_factor)
# Check for succesful fit
success = (np.isclose(model_function.x_stddev.value, x_radius, rtol=0.2) and np.isclose(model_function.y_stddev.value, y_radius, rtol=0.2))
if success:
if upsample_factor > 1.0: evaluated_model = ndimage.interpolation.zoom(evaluated_model, zoom=1.0/upsample_factor)
# Plot
if plot: plotting.plot_star_model(background=np.ma.masked_array(background,mask=background_mask_beforeclipping),
background_clipped=np.ma.masked_array(background,mask=background_mask),
est_background=est_background,
star=np.ma.masked_array(star,mask=star_mask),
est_background_star= star_background,
fitted_star=evaluated_model)
# Adjust the parameters of the shape to the model of this star
shape.coord_list[0] = model_function.x_mean.value
shape.coord_list[1] = model_function.y_mean.value
shape.coord_list[2] = model_function.x_stddev.value
shape.coord_list[3] = model_function.y_stddev.value
# Return ...
return success, shape, evaluated_model, (x_min, x_max, y_min, y_max)
# -----------------------------------------------------------------
| true
|
00317e414b485fd1f926a3681824e30046f76bd3
|
Python
|
rootUJ99/py-programs
|
/left_right_sum_difference.py
|
UTF-8
| 681
| 3.859375
| 4
|
[] |
no_license
|
'''
array = [1,2,4,5,1]
Find min difference of left and right sum of the array
e.g.
LS - RS
1 - 12 => 11
3 - 10 => 7
7 - 6 => 1
12 - 1 => 11
'''
def min_diff(sum, index, arr):
try:
print(sum)
if len(arr) > 1:
#if index > 0:
divider = len(arr) // index
left = min_diff(sum+arr[index], index+1,arr[:divider])
right =min_diff(sum+arr[divider], divider+1, arr[divider:])
print(left, right)
print(arr[index], arr[divider])
return
except IndexError:
return sum
if __name__ == '__main__':
array = [1,2,4,5,1]
result = min_diff(0, 1,array)
print(result)
| true
|
7482732b8e3c8e7d646fa81754f0458594d827cf
|
Python
|
MatteoLacki/logerman
|
/logerman/json_ops.py
|
UTF-8
| 362
| 2.984375
| 3
|
[] |
no_license
|
import json
from pathlib import Path
class PathlibFriendlyEncoder(json.JSONEncoder):
"""This helps to store the paths."""
def default(self, z):
if isinstance(z, Path):
return str(z.expanduser().resolve())
else:
return super().default(z)
def dump2json(obj):
return json.dumps(obj, cls=PathlibFriendlyEncoder)
| true
|
8360c745043095b3aee6168b863ac046c6b1184d
|
Python
|
Sumitsahu896/My_LeetCode_Solutions
|
/fibonacci-number/fibonacci-number.py
|
UTF-8
| 238
| 3.4375
| 3
|
[] |
no_license
|
class Solution:
def __init__(self):
self.dict = {0:0, 1:1}
def fib(self, n: int) -> int:
if n not in self.dict:
self.dict[n] = self.fib(n - 1) + self.fib(n - 2)
return self.dict[n]
| true
|
7daa2b63b32f1509dcb3ab8c78c9633fe98bafdc
|
Python
|
yopy0817/course-python
|
/day08/03def_return.py
|
UTF-8
| 719
| 4.25
| 4
|
[] |
no_license
|
# 함수의 반환 return
#매개 변수로 전달 받은 2개의 값의 합을 반환하는 함수.
def add(a, b) :
return a + b
result = add(10, 20)
print("10과 20의 합:", result)
#매개변수 까지의 합을 반환하는 함수.
def calSum(a) :
sum = 0
a = 1
while a <= 10 :
sum += a
a = a + 1
return sum
result = calSum(10)
print("1부터 10까지 합:", result)
#리스트의 반환
def func(a) :
"a까지 3의 배수만 리스트에 저장하고 반환"
result = []
i = 1
while i <= a :
if i % 3 == 0 :
result.append(i)
i = i + 1
return result
result = func(20)
print("20까지의 3의 배수:", result)
| true
|
4a2ca9f868a836715206e4e9db32bd178aad31de
|
Python
|
mcf-rocha/pyDEA
|
/pyDEA/core/gui_modules/custom_canvas_gui.py
|
UTF-8
| 435
| 2.765625
| 3
|
[
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
''' This module contains StyledCanvas class.
'''
from tkinter import Canvas
from pyDEA.core.utils.dea_utils import bg_color
class StyledCanvas(Canvas):
''' Implements Canvas object with a custom background colour.
Args:
parent (Tk object): parent of this widget.
'''
def __init__(self, parent, *args, **kw):
super().__init__(parent, *args, **kw)
self.configure(background=bg_color)
| true
|
ab60e1f5e4e2cffff6e5cad57e486b710ebf4bae
|
Python
|
yoshioH/readaloud-workout
|
/chunks/__init__.py
|
UTF-8
| 592
| 2.671875
| 3
|
[] |
no_license
|
# coding: utf-8
from enum import Enum
from abc import ABC
from abc import abstractmethod
from dataclasses import dataclass
class ChunkType(Enum):
READ_ALOUD = 0
QUESTION = 1
ANSWER = 2
@dataclass(frozen=True)
class Chunk:
type: ChunkType
text: str
class ChunkResource(ABC):
@abstractmethod
def generate(self) -> Chunk:
return Chunk(ChunkType.READ_ALOUD, 'Yaruki Max Orix!!')
def generate(chunk_generator:ChunkResource):
while True:
chunk = chunk_generator.generate()
if chunk is None:
break
yield chunk
| true
|
c6bfcc85d8e36d70b081308d416b0e9c873e1dd4
|
Python
|
VagishM6/JPG_to_PNG_Converter
|
/JPGtoPNGConverter.py
|
UTF-8
| 559
| 3.1875
| 3
|
[] |
no_license
|
import sys
import os
from PIL import Image, ImageFilter
# grab the first and second args from the user
image_folder = sys.argv[1]
output_folder = sys.argv[2]
# check if (new) folder exist/ if not create it
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# loop through the directory, then convert (image.type) to png
for filename in os.listdir(image_folder):
img = Image.open(f'{image_folder}{filename}')
clean_name = os.path.splitext(filename)[0]
img.save(f'{output_folder}{clean_name}.png','png')
print('all done!')
| true
|
c483144e38c7a9f48f751c0316d3ae1cd248f009
|
Python
|
danierubr/Exercicios-resolvidos
|
/URI/1548.py
|
UTF-8
| 299
| 3.6875
| 4
|
[] |
no_license
|
quant = int(input())
for v in range(quant):
alunos = int(input())
fila = list(map(int, input().split()))
filaordenada = sorted(fila, reverse=True)
cont = 0
for ind in range(0, len(fila)):
if fila[ind] == filaordenada[ind]:
cont += 1
print(cont)
| true
|
4cae91584955eb167a0db4f3f2f6e4a5534470e3
|
Python
|
lusiux/aoc2020
|
/11/main.py
|
UTF-8
| 5,453
| 3.5625
| 4
|
[
"MIT"
] |
permissive
|
import sys
sys.path.append('./')
import Helper
import copy
input_for_testing = """L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
"""
class Seatmap():
def __init__(self, lines):
self._read_input(lines)
def _read_input(self, lines):
self.height = len(lines)
self.width = len(lines[0])
self.map = [['.' for i in range(self.height+2)] for j in range(self.width+2)]
for index, line in enumerate(lines):
self._parse_line(line, index)
def _parse_line(self, line, index):
for char_index, char in enumerate(line):
self.map[char_index+1][index+1] = char
def get_height(self):
return self.height
def get_width(self):
return self.width
def get_adjacent_seats(self, x, y):
x += 1
y += 1
return [
self.map[x][y-1], # north
self.map[x+1][y-1], # north east
self.map[x+1][y], # east
self.map[x+1][y+1], # south east
self.map[x][y+1], # south
self.map[x-1][y+1], # south west
self.map[x-1][y], # west
self.map[x-1][y-1], # north west
]
def look_around_seat_at(self, x, y):
x += 1
y += 1
return [
self.get_next_seat_in_direction(x, y, 0, -1), # north
self.get_next_seat_in_direction(x, y, 1, -1), # north east
self.get_next_seat_in_direction(x, y, 1, 0), # east
self.get_next_seat_in_direction(x, y, 1, 1), # south east
self.get_next_seat_in_direction(x, y, 0, 1), # south
self.get_next_seat_in_direction(x, y, -1, 1), # south west
self.get_next_seat_in_direction(x, y, -1, 0), # west
self.get_next_seat_in_direction(x, y, -1, -1), # north west
]
def get_next_seat_in_direction(self, start_x, start_y, dx, dy):
next_x = start_x+dx
next_y = start_y+dy
# print(f"next in dir: ({start_x}, {start_y}): d({dx}, {dy}) = n({next_x}, {next_y})")
if (next_x < 0) or (next_x >= self.width+2) or (next_y < 0) or (next_y >= self.height+2):
return None
if self.map[next_x][next_y] == '.':
next_seat = self.get_next_seat_in_direction(next_x, next_y, dx, dy)
if next_seat == None:
return '.'
return next_seat
return self.map[next_x][next_y]
def get_seats_occupied_around_seat(self, x, y):
occupied = 0
seats = self.get_adjacent_seats(x, y)
for seat in seats:
if seat == '#':
occupied += 1
return occupied
def get_seats_occupied_around_seat_looking(self, x, y):
occupied = 0
seats = self.look_around_seat_at(x, y)
# print(f"({x},{y}: {seats}")
for seat in seats:
if seat == '#':
occupied += 1
return occupied
def get_seat_at(self, x, y):
return self.map[x+1][y+1]
def get_seats_free_around_seat(self, x, y):
occupied = 0
seats = self.get_adjacent_seats(x, y)
for seat in seats:
if seat == 'L':
occupied += 1
return occupied
def occupy_seat_at(self, x, y):
self.map[x+1][y+1] = "#"
def free_seat_at(self, x, y):
self.map[x+1][y+1] = "L"
def is_seat_free(self, x, y):
return self.map[x+1][y+1] == 'L'
def is_seat_occupied(self, x, y):
return self.map[x+1][y+1] == '#'
def print(self):
for x in range(1, self.width):
print(''.join(self.map[x]))
print()
def number_of_seats_occupied(self):
occupied = 0
for x in range(self.width+2):
occupied += self.map[x].count('#')
return occupied
def apply_rules(seats):
new_seats = copy.deepcopy(seats)
for x in range(seats.width):
for y in range(seats.height):
if seats.is_seat_free(x, y) and seats.get_seats_occupied_around_seat(x,y) == 0:
new_seats.occupy_seat_at(x, y)
elif seats.is_seat_occupied(x, y) and seats.get_seats_occupied_around_seat(x,y) >= 4:
new_seats.free_seat_at(x, y)
return new_seats
def apply_new_rules(seats):
new_seats = copy.deepcopy(seats)
for x in range(seats.width):
for y in range(seats.height):
occupied = seats.get_seats_occupied_around_seat_looking(x,y)
if seats.is_seat_free(x, y) and occupied == 0:
new_seats.occupy_seat_at(x, y)
elif seats.is_seat_occupied(x, y) and occupied >= 5:
new_seats.free_seat_at(x, y)
return new_seats
def answer_one(lines):
seats = Seatmap(lines)
while True:
new_seats = apply_rules(seats)
if new_seats.map == seats.map:
break
seats = new_seats
# seats.print()
return seats.number_of_seats_occupied()
def answer_two(lines):
seats = Seatmap(lines)
while True:
new_seats = apply_new_rules(seats)
if new_seats.map == seats.map:
break
seats = new_seats
# seats.print()
return seats.number_of_seats_occupied()
if __name__ == "__main__":
lines = Helper.read_input_with_delimiter('11/input', "\n")
print('Answer one: {}'.format(answer_one(lines)))
print('Answer two: {}'.format(answer_two(lines)))
| true
|
0b92001b2e32f67b798c7c7f0f1cf7de4f3ace44
|
Python
|
ZheHanLiang/UAGA_reconstruct
|
/UAGA/model.py
|
UTF-8
| 2,454
| 3.234375
| 3
|
[] |
no_license
|
##########################################################################
# @File: model.py
# @Author: Zhehan Liang
# @Date: 1/10/2020
# @Intro: GAN的模型函数,其中Discriminator是鉴别器,mapping是生成器
##########################################################################
import time
import torch
from torch import nn
# from .utils import
class Discriminator(nn.Module):
"""
鉴别器函数
"""
def __init__(self, params):
super(Discriminator, self).__init__()
# 传递params的参数
self.emb_dim = params.emb_dim
self.dis_layers = params.dis_layers
self.dis_hid_dim = params.dis_hid_dim
self.dis_dropout = params.dis_dropout
layers = [] # 初始化layers
for i in range(self.dis_layers + 1): # 依次往layers里面添加需要的网络层
input_dim = self.emb_dim if i==0 else self.dis_hid_dim
output_dim = 1 if i==self.dis_layers else self.dis_hid_dim
layers.append(nn.Linear(input_dim, output_dim)) # 往layers里面添加线性层,即全连接层
if i < self.dis_layers: # 最后一个线性层后面不添加LeakyReLU
layers.append(nn.LeakyReLU(0.2))
layers.append(nn.Dropout(self.dis_dropout))
layers.append(nn.Sigmoid()) # 最后一个线性层后不用LeakyReLU,用sigmoid
self.layers = nn.Sequential(*layers) # 把得到的layers传入构造器
def forward(self, x):
assert x.dim()==2, "Dimension of x is error!" # 校验输入x的维度是否符合要求
assert x.size(1)==self.emb_dim, "Length of x is error!" # 校验输入x第二维的size是否符合要求
return self.layers(x).view(-1) # .view()的作用和numpy中的.resize()类似
def build_model(params):
"""
构建GAN模型
"""
time_head = time.time() # 记录开始时间
# 初始化mapping,即生成器
mapping = nn.Linear(params.emb_dim, params.emb_dim, bias=False) # mapping设置为线性层
mapping.weight.data.copy_(torch.diag(torch.ones(params.emb_dim))) # 将mapping初始化为对角矩阵
# 初始化discriminator
discriminator = Discriminator(params)
# 初始化cuda
if params.cuda:
mapping.cuda()
discriminator.cuda()
time_tail = time.time() # 记录完成时间
print("Model has been built!\tTime: %.3f"%(time_tail-time_head))
return mapping, discriminator
| true
|
0a6cd3ac5c88cde947ddd6b7a4715d4d12b82d36
|
Python
|
MichalRybecky/Informatika
|
/ulohy/20.1.py
|
UTF-8
| 965
| 2.953125
| 3
|
[] |
no_license
|
import tkinter
c = tkinter.Canvas(height=200, width=1000, bg='black')
c.pack()
with open('stanice.txt', 'r') as file:
data = [x.strip() for x in file.readlines()]
def main():
global current, stanice
c.delete('all')
for stanica in stanice:
c.create_text(stanica[1], 100, anchor='w', text=stanica[0], fill='red', font='arial 100 bold')
stanica[1] -= 5
if stanica[1] == -len(stanica[0]) * 50:
stanice.append([data[current], 1000])
if stanica[1] >= -len(stanica[0]) * 50:
break
elif stanica[1] == -2000:
stanice.remove(stanica)
if len(stanice) >= 3:
stanice = [stanice[0], stanice[1]]
c.update()
c.after(10, main)
def hore(event):
global current
current += 1
if current == len(data) + 1:
current = 0
stanice.append([data[current], 1000])
current = 0
stanice = [[data[current], 1000]]
main()
c.bind('<1>', hore)
c.mainloop()
| true
|
e99c7b6e9c5e8b8562e72467d7877dc5255594c0
|
Python
|
ispastlibrary/Titan
|
/2015/AST1/vezbovni/anja/treci.py
|
UTF-8
| 69
| 2.875
| 3
|
[] |
no_license
|
S=0
for i in range(101):
S+=i
print("konacno resenje je: ", S)
| true
|
dcbe681f2dae5ee7c917f79691e2cd33b70940d2
|
Python
|
VigneshKarthigeyan/DS
|
/Linked_List/flat_multi_level_ll.py
|
UTF-8
| 970
| 3.578125
| 4
|
[] |
no_license
|
#Flatten a multilevel ll
class Node:
def __init__(self,val):
self.data=val
self.next=None
self.child=None
def printlist(head):
while head:
print(head.data,end=' ')
head=head.next
def flat(head):
tail=head
while tail.next:
tail=tail.next
temp=head
while temp!=tail:
if temp.child:
tail.next=temp.child
tmp=temp.child
while tmp.next:
tmp=tmp.next
tail=tmp
temp=temp.next
if __name__ == '__main__':
head=Node(10)
head.child=Node(70)
head.child.next=Node(80)
head.child.next.child=Node(100)
head.child.next.next=Node(90)
head.child.next.next.child=Node(110)
head.next=Node(20)
head.next.next=Node(30)
head.next.next.next=Node(40)
head.next.next.next.next=Node(50)
head.next.next.next.child=Node(120)
flat(head)
printlist(head)
| true
|
c81a5d5e79032cd7baf9a46d2979a58d34001413
|
Python
|
dansgithubuser/pdf-explorer
|
/pdf/_objects.py
|
UTF-8
| 2,955
| 2.921875
| 3
|
[] |
no_license
|
'''
This file makes page and section references to ISO 32000-1:2008.
Objects are documented in section 7.3 of ISO 32000-1:2008.
'''
import re
import pprint
import zlib
class Name:
escape_regex = re.compile('#([0-9a-fA-F]{2})')
def __init__(self, literal):
self.value = Name.escape_regex.sub(lambda m: chr(int(m.group(1), 16)), literal)
def __eq__(self, other):
if not isinstance(other, Name): return False
return self.value == other.value
def __repr__(self):
return '/{}'.format(self.value)
def to_json(self): return repr(self)
class Stream:
def __init__(self, dictionary, stream):
self.dictionary = dictionary
self.stream = stream
self.decoded = None
if not self.dictionary.get('Filter'):
self.decoded = self.stream
elif self.dictionary['Filter'] == Name('FlateDecode'): # p22 (7.4), p25 (7.4.4)
self.decoded = zlib.decompress(self.stream)
try: self.decoded.decode('utf-8')
except: pass
def __eq__(self, other):
if not isinstance(other, Stream): return False
return (self.dictionary, self.stream) == (other.dictionary, other.stream)
def __repr__(self):
return 'Stream({} {})'.format(pprint.pformat(self.dictionary), self.decoded or hash(self.stream))
def __getitem__(self, key):
return self.dictionary[key]
def __setitem__(self, key, value):
self.dictionary[key] = value
def __delitem__(self, key):
del self.dictionary[key]
def __contains__(self, item):
return item in self.dictionary
def to_json(self):
uniquifier = 'pdf_py_meta'
assert uniquifier not in self.dictionary
return dict(self.dictionary, **{
uniquifier: {'type': 'stream', 'decoded': self.decoded},
})
def get(self, key):
return self.dictionary.get(key)
class Ref:
def __init__(self, *args):
types = [type(i) for i in args]
if types == [str]:
self.object_number, self.generation_number = [int(i) for i in args[0].split()[:2]]
elif types == [int]:
self.object_number, self.generation_number = args[0], 0
elif types == [Ref]:
self.object_number, self.generation_number = args[0].object_number, args[0].generation_number
elif types == [int, int]:
self.object_number, self.generation_number = args
else:
raise Exception('invalid arguments {}'.format(args))
def __eq__(self, other):
if not isinstance(other, Ref): return False
return (self.object_number, self.generation_number) == (other.object_number, other.generation_number)
def __hash__(self):
return hash((self.object_number, self.generation_number))
def __repr__(self):
return '{} {}'.format(self.object_number, self.generation_number)
def to_json(self): return repr(self)
| true
|
f17160c31a9a3eac744b6b549ba49231afed5d7a
|
Python
|
batbeerman/hellogit
|
/qu2.py
|
UTF-8
| 131
| 3.1875
| 3
|
[] |
no_license
|
test_tup = 32,454,56,32,1,9,76
print('Max element of tuple is :',max(test_tup))
print('Min element of tuple is :',min(test_tup))
| true
|
e531d0b14eae818c79ff7770b49416d77c5ed4c1
|
Python
|
widelec9/codewars
|
/kata/python/5kyu/tongues.py
|
UTF-8
| 347
| 2.90625
| 3
|
[] |
no_license
|
def tongues(code):
v = 'aiyeou'
c = 'bkxznhdcwgpvjqtsrlmf'
out = ''
for i, ch in enumerate(code):
if ch.isalpha():
ch = v[(v.index(ch.lower()) + 3) % len(v)] if ch.lower() in v else c[(c.index(ch.lower()) + 10) % len(c)]
ch = ch.upper() if code[i].isupper() else ch
out += ch
return out
| true
|
b6ec1b528c3614b4a9e8cce5e0292d15dc77ec98
|
Python
|
sp5/c-exercises
|
/sort/testsort.py
|
UTF-8
| 157
| 3.140625
| 3
|
[] |
no_license
|
import sys
prev = 0
for line in sys.stdin:
cur = int(line)
if cur < prev:
print("EVIL SORT VERY BAD")
sys.exit(0)
prev = cur
| true
|
8177a65fddd055c711e994c0725fb27077ca1812
|
Python
|
peterpeng1993/learngit
|
/script/python/pygame入门9.py
|
UTF-8
| 1,867
| 3.1875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 29 20:26:31 2018
@author: asus
"""
import sys,pygame
from random import choice
class MyBallClass(pygame.sprite.Sprite):
def __init__(self,image_file,location,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load(image_file)
self.rect=self.image.get_rect()
self.rect.left, self.rect.top=location
self.speed=speed
def move(self):
self.rect=self.rect.move(self.speed)
if self.rect.left<0 or self.rect.right>width:
self.speed[0]=-self.speed[0]
if self.rect.top<0 or self.rect.bottom>height:
self.speed[1]=-self.speed[1]
def animate(group):
screen.fill([255,255,255])
for ball in group:
ball.move()
for ball in group:
group.remove(ball)
if pygame.sprite.spritecollide(ball,group,False):#检查球的碰撞
ball.speed[0]=-ball.speed[0]
ball.speed[1]=-ball.speed[1]
group.add(ball)
screen.blit(ball.image,ball.rect)
pygame.display.flip()
size=width,height=800,640
screen=pygame.display.set_mode(size)
screen.fill([255,255,255])
img_file='b_ball_rect.png'
clock=pygame.time.Clock()#创建Clock的实例
group=pygame.sprite.Group()
for row in range(0,2):
for column in range(0,2):
location=[column*180+10,row*180+10]
speed=[choice([-3,3]),choice([-3,3])]
ball=MyBallClass(img_file,location,speed)
group.add(ball)#把球加到群组中
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
frame_rate=clock.get_fps()#得到帧速率
print('frame rate =',frame_rate)
animate(group)
clock.tick(90)#控制帧速率
pygame.quit()
| true
|
0a33a5d574c1d8b6d889f75a4a2f3f001eb35af9
|
Python
|
swarren/advent-of-code-2020
|
/python/day20.py
|
UTF-8
| 1,601
| 2.859375
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
import functools
import operator
with open("../input/day20.txt") as f:
data = f.read().splitlines()
def s2i(s):
v = 0
for c in s:
v <<= 1
v |= ((c == '#') and 1 or 0)
return v
tiles = {}
tile = None
ln = 0
ts = 0
ls = 0
rs = 0
for l in data:
ln += 1
#print(ln, l)
if 'Tile' in l:
tile = int(l.split()[1][:-1])
#print(f' tile {tile}')
ln = -1
ls = ''
rs = ''
continue
if 0 <= ln <= 9:
ls = l[0] + ls
rs = rs + l[-1]
if ln == 0:
ts = l
t = s2i(ts)
tr = s2i(ts[::-1])
elif ln == 9:
bs = l
r = s2i(rs)
rr = s2i(rs[::-1])
b = s2i(bs[::-1])
br = s2i(bs)
lr = s2i(ls)
l = s2i(ls[::-1])
#print(tile, ts, rs, bs, ls)
#print(tile, t, l, b, r)
tiles[tile] = (t, tr, l, lr, b, br, r, rr)
#print(tiles)
# all_borders = [b for vs in tiles.values() for b in vs]
counts = {}
for tile, borders in tiles.items():
for b in borders:
counts[b] = counts.get(b, 0) + 1
#print(counts)
edge_tiles = []
corner_tiles = []
for tile, borders in tiles.items():
edge_sides = []
for i, border in enumerate(borders[::2]):
#print(f' {i} {border}')
if counts[border] == 1:
edge_sides.append(i)
#print(tile, edge_sides)
if edge_sides:
edge_tiles.append(tile)
if len(edge_sides) == 2:
corner_tiles.append(tile)
#print(edge_tiles)
#print(corner_tiles)
print(functools.reduce(operator.mul, corner_tiles, 1))
| true
|
f667647fe7156078432a23743802c0d629413ad6
|
Python
|
rajui67/learnpython
|
/python_code_exaples/collections/sets/union.py
|
UTF-8
| 1,026
| 4.09375
| 4
|
[] |
no_license
|
set1 = {1, 2, 3}
set2 = {1, 5}
print(set1 | set2)
print(set1.union(set2))
print(set2 | set1)
print(set2.union(set1))
# up until this point set1 and set2 remain unchanged. The operators and function return a new set
print(set1, set2)
set1 = {1,1,2,2,3}
set2 = {1,5}
# |= a shortcout operator. Essentially, set1 |= set2 works thus so:
# 1. executes set1 | set2 which creates a new anonymous set.
# 2. set1 = new set #set1 is modified such that its object-refence is the same as set2's object reference
set1 |= set2
print('short cut operator |=', set1)
#print(set1 |= set2) This generates an error. An assignment or shortcut operator cannot be used 'inline'.
# The assignment expression := can be used to assign a value . TUt works thus so:
# 1. Executes the set1 | set2 operation whcih creates a new set.
# 2. set1 = new set #set1 is modified such that its object-refence is the same as set2's object reference
# set1 is printed
set1 = {1,1,2,2,3}
set2 = {1,5}
print('Assingnment expression :=', set1 := set1 | set2)
| true
|
c47fc129c20863be802047f9abfef0fc4b38bf8d
|
Python
|
shilpakancharla/machine-learning-tutorials
|
/data_scraping/bing.py
|
UTF-8
| 1,723
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 10:45:31 2018
@author: shilpakancharla
"""
import urllib,urllib2
import re
from bs4 import BeautifulSoup
from datetime import datetime
def bing_grab(query):
t1 = datetime.now()
address = "http://www.bing.com/search?q=%s" % (urllib.quote_plus(query))
request = urllib2.Request(address, None, {'User-Agent':'Mosilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'})
urlfile = urllib2.urlopen(request)
page = urlfile.read()
soup = BeautifulSoup(page)
t2 = datetime.now()
linkdictionary = {}
# 'li' has two kinds of classed 'sa_wr wr_at' and 'sa_wr'
li = soup.find('li', attrs={'class': re.compile(r".*\bsa_wr\b.*")})
h3 = li.find('h3')
h31 = re.compile(r'<.*?>').sub('',str(h3)).replace('.','')
print h31
sLink = li.find('a')
slink1 = sLink['href']
print slink1
Cite = li.find('cite')
Cite1 = re.compile(r'<.*?>').sub('',str(Cite))
Cite2 = re.compile(r'&.*?;').sub(' ',str(Cite1))
print Cite2
# Rating = li.find('span', attrs={'class':'ssp_ylp'})
# print Rating
Info = li.find('ul', attrs={'class':'sp_pss'})
Info1 = re.compile(r'<.*?>').sub('',str(Info))
Info2 = re.compile(r'&.*?;').sub(' ',str(Info1))
print Info2
P = li.find('p')
P1 = re.compile(r'<.*?>').sub('',str(P))
P2 = re.compile(r'&.*?;').sub(' ',str(P1))
print P2
t3 = datetime.now()
print "Scraping Time is ", t2-t1
print "parsing time is ", t3-t2
return linkdictionary
return linkdictionary
if __name__ == '__main__':
links = bing_grab("tea station yelp")
| true
|
3a4efe163811aeb7c30ddf1e4e8bdde05cccdd1e
|
Python
|
weidler/RLaSpa
|
/src/gym_custom_tasks/envs/simplePathing.py
|
UTF-8
| 4,772
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
import copy
import numpy
import numpy as np
import gym
import torch
from gym import error, spaces, utils
from gym.utils import seeding
import platform
if 'rwth' in platform.uname().node.lower():
import matplotlib
matplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend.
import matplotlib.pyplot as plt
class SimplePathing(gym.Env):
BACKGROUND_PIXEL = 0
TARGET_PIXEL = 0.8
AGENT_PIXEL = 0.3
TRAIL_PIXEL = 0.1
PADDING = 3
DEFAULT_REWARD = -10
TARGET_REWARD = 10
def __init__(self, width: int, height: int, visual: bool):
if not (width > SimplePathing.PADDING * 2 and height > SimplePathing.PADDING * 2):
raise ValueError(
"Width and Height need to be larger than double the padding of the environment, hence > {0}.".format(
SimplePathing.PADDING * 2))
# ATTRIBUTES
self.width = width
self.height = height
self.action_space = gym.spaces.Discrete(4) # UP, RIGHT, DOWN, LEFT
self.observation_space = gym.spaces.Box(low=0, high=max((width, height)), dtype=numpy.uint8, shape=(2,))
if visual: self.observation_space = gym.spaces.Box(low=0, high=1, dtype=numpy.float16, shape=(width, height))
self.max_steps = (width*height) # Maybe reduce max_steps by dividing by 2?
self.steps = 0
self.visual = visual
# STATES
self.target_coords = [width - SimplePathing.PADDING, SimplePathing.PADDING]
self.start_state = [SimplePathing.PADDING, height - SimplePathing.PADDING]
self.current_state = self.start_state.copy()
# TRAIL
self.state_trail = []
self.show_breadcrumbs = True
# MAP
self.static_pixels = self._generate_static_pixels()
def __repr__(self):
representation = ""
if self.show_breadcrumbs:
view = self._get_current_view_with_trail()
else:
view = self._get_current_view()
for row in view:
representation += " ".join(map(str, row)) + "\n"
return representation
def _generate_static_pixels(self):
# static_map = [[SimplePathing.BACKGROUND_SYMBOL for _ in range(self.width)] for _ in range(self.height)]
# static_map[self.target_coords[1]][self.target_coords[0]] = SimplePathing.TARGET_SYMBOL
static_pixels = torch.zeros((self.height, self.width))
static_pixels[self.target_coords[1], self.target_coords[0]] = SimplePathing.TARGET_PIXEL
return static_pixels
def _get_current_view(self):
view = copy.deepcopy(self.static_pixels)
view[self.current_state[1], self.current_state[0]] = SimplePathing.AGENT_PIXEL
return view
def _get_current_view_with_trail(self):
view = self._get_current_view()
for step in range(-1, -len(self.state_trail), -1):
state = self.state_trail[step]
view[state[1], state[0]] = SimplePathing.TRAIL_PIXEL
return view
def step(self, action: int):
next_state = self.current_state.copy()
self.state_trail.append(self.current_state)
if action == 0:
next_state[1] = max(0, next_state[1] - 1)
elif action == 1:
next_state[0] = min(next_state[0] + 1, self.width - 1)
elif action == 2:
next_state[1] = min(next_state[1] + 1, self.height - 1)
elif action == 3:
next_state[0] = max(0, next_state[0] - 1)
reward = SimplePathing.DEFAULT_REWARD
self.steps += 1
done = self.steps >= self.max_steps
if next_state == self.target_coords:
reward = SimplePathing.TARGET_REWARD
done = True
self.current_state = next_state.copy()
if self.visual:
return self.get_pixelbased_representation(), reward, done, None
else:
return next_state, reward, done, None # returns None at pos 4 to match gym envs
def reset(self):
self.current_state = self.start_state.copy()
self.state_trail = []
self.steps = 0
if self.visual:
return self.get_pixelbased_representation()
else:
return self.current_state
def get_pixelbased_representation(self):
pixels = self.static_pixels.clone()
pixels[self.current_state[1], self.current_state[0]] = SimplePathing.AGENT_PIXEL
return pixels
def render(self, mode='human', close=False):
img = self.get_pixelbased_representation().cpu()
plt.clf()
plt.imshow(img, cmap="binary", origin="upper")
plt.gca().axes.get_xaxis().set_visible(False)
plt.gca().axes.get_yaxis().set_visible(False)
plt.draw()
plt.pause(0.001)
| true
|
7970f33425d471802dcc3751601fc0eb6cdb3925
|
Python
|
srinitude/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/2-matrix_divided.py
|
UTF-8
| 1,806
| 3.65625
| 4
|
[] |
no_license
|
#!/usr/bin/python3
"""Matrix Divided Module"""
def check_for_ints_and_floats(matrix):
"""Bad input"""
bad_input = "matrix must be a matrix (list of lists) of integers/floats"
flat_list = [i for sublist in matrix for i in sublist]
for i in flat_list:
if type(i) is not int and type(i) is not float:
raise TypeError(bad_input)
def make_sure_lists_are_same_length(matrix):
"""Same length"""
needed_length = len(matrix[0])
for i, sublist in enumerate(matrix):
if i == 0:
continue
list_length = len(sublist)
if list_length != needed_length:
raise TypeError("Each row of the matrix must have the same size")
def check_for_div_type(div):
"""Bad div type"""
if type(div) is not int and type(div) is not float:
raise TypeError("div must be a number")
def check_for_zero_division(div):
"""Zero division"""
if div == 0:
raise ZeroDivisionError("division by zero")
def number_of_lists(matrix):
"""Number of lists"""
count = 0
for sublist in matrix:
count += 1
return count
def matrix_divided(matrix, div):
"""Matrix divided"""
bad_input = "matrix must be a matrix (list of lists) of integers/floats"
if matrix is None:
raise TypeError(bad_input)
count = number_of_lists(matrix)
if count == 0:
return []
check_for_ints_and_floats(matrix)
make_sure_lists_are_same_length(matrix)
check_for_div_type(div)
check_for_zero_division(div)
new_matrix = []
for sublist in matrix:
new_list = list(map((lambda x: round(x / div, 2)), sublist))
new_matrix.append(new_list)
return new_matrix
if __name__ == "__main__":
import doctest
doctest.testfile("tests/2-matrix_divided.txt")
| true
|
fddfca3ddbb7e04ea6895479a101537f0fd5b1c8
|
Python
|
Ich1goSan/LeetcodeSolutions
|
/removeNthFromEnd.py
|
UTF-8
| 508
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def removeNthFromEnd(self, head, n):
if not head:
return None
if not head.next and n == 1:
return None
r = []
current = head
while current:
r.append(current)
current = current.next
r.pop(len(r)-n)
node = r[0]
r[0].next = None
r[-1].next = None
d = node
for i in range(1, len(r)):
d.next = r[i]
d = d.next
return node
| true
|
19b8735515f2dabddbd703545e944a816289245a
|
Python
|
Addikins/CIS164
|
/Unit12/CSVread.txt
|
UTF-8
| 130
| 2.59375
| 3
|
[] |
no_license
|
import csv
csv_file = open('cochise.csv')
csv_reader = csv.reader(csv_file)
csv_contents = list(csv_reader)
print(csv_contents)
| true
|
e912546e6bed4325be0adcd54f5761135f97867b
|
Python
|
sweec/leetcode-python
|
/src/NextPermutation.py
|
UTF-8
| 785
| 2.984375
| 3
|
[] |
no_license
|
class Solution:
# @param num, a list of integer
# @return a list of integer
def nextPermutation(self, num):
l = len(num)
for i in range(l-2, -1, -1):
if num[i] < num[i+1]:
index = l-1
for j in range(i+2, l):
if num[j] <= num[i]:
index = j-1
break
t = num[i]
num[i] = num[index]
num[index] = t
a, b = i+1, l-1
while a < b:
t = num[a]
num[a] = num[b]
num[b] = t
a += 1
b -= 1
return num
num.reverse()
return num
| true
|
37e10f39d8819bdd38e13ffe90a7b7bcd6306f40
|
Python
|
antman9914/CitiChatbot
|
/Aiml模板翻译/TranslateXml.py
|
UTF-8
| 4,961
| 2.703125
| 3
|
[] |
no_license
|
#作者:肖劲宇 李蕴琦
#用途:对aiml模板进行翻译
#时间:2019.7.3
from bs4 import BeautifulSoup
import requests
import string
import time
import hashlib
import json
import os
import random
#百度翻译api的url,以及appid和密钥
api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate"
my_appid = '20151113000005349'
cyber = 'osubCEzlGjzvw8qdQc41'
lower_case = list(string.ascii_lowercase)
num = 0
#请求百度翻译API进行翻译,返回Json格式请求
def requests_for_dst(word):
# init salt and final_sign
salt = str(time.time())[:10]
final_sign = str(my_appid) + word + salt + cyber
final_sign = hashlib.md5(final_sign.encode("utf-8")).hexdigest()
# 区别en,zh构造请求参数
if list(word)[0] in lower_case:
paramas = {
'q': word,
'from': 'en',
'to': 'zh',
'appid': '%s' % my_appid,
'salt': '%s' % salt,
'sign': '%s' % final_sign
}
my_url = api_url + '?appid=' + str(
my_appid) + '&q=' + word + '&from=' + 'en' + '&to=' + 'zh' + '&salt=' + salt + '&sign=' + final_sign
else:
paramas = {
'q': word,
'from': 'en',
'to': 'zh',
'appid': '%s' % my_appid,
'salt': '%s' % salt,
'sign': '%s' % final_sign
}
my_url = api_url + '?appid=' + str(
my_appid) + '&q=' + word + '&from=' + 'en' + '&to=' + 'zh' + '&salt=' + salt + '&sign=' + final_sign
response = requests.get(api_url, params=paramas).content
content = str(response, encoding="utf-8")
json_reads = json.loads(content)
try:
return json_reads['trans_result'][0]['dst']
except KeyError as e:
print("error")
return ""
def translate(word):
return requests_for_dst(word)
# import requests
# import bs4
# import shutil
# import urllib
# import re
# import os
# import xml.dom.minidom
# def getLogin(loginurl):
#
# # rs = requests.get(loginurl)
# # html = rs.text
# # with open('ai.xml', "wb") as f:
# # html = f.read()
# # print(html)
# # soup = BeautifulSoup(html, 'lxml')
# # text = soup.find_all('pattern')
# # print(text)
# # verifyurl = soup.find_all('img',id='captcha-img')[0]['src']
# # verifyurl = loginurl+verifyurl
# # print(verifyurl)
# # conn = urllib.request.urlopen(verifyurl)
# # path = "verifyimage.jpg"
# # with open(path, "wb") as f:
# # f.write(conn.read())
# getLogin('http://210.42.121.241')
#遍历XML标签标记的树结构,同时对字符串进行翻译
def tranverse(tag):
try:
for child in tag.children:
try:
c = child.children
tranverse(child)
except AttributeError:
chinese = translate(str(child))
print(chinese)
time.sleep(1.5)
if num % 10 == 0:
time.sleep(2)
child.replace_with(chinese)
except AttributeError:
return
#对xml里面的categories进行翻译
def xmlTranslate(src,dest):
with open(src, 'r') as infile:
xml = infile.read()
with open(dest,'a') as outfile:
soup = BeautifulSoup(xml, 'lxml')
xml = soup.find_all('category')
for item in xml:
item = str(item).replace('\n', '')
tag = BeautifulSoup(item, 'lxml').find_all('category')[0]
print(tag)
tranverse(tag)
print(tag)
outfile.write(str(tag))
outfile.write('\n')
# # outfile.close()
# # item = str(xml).replace('\n', '')
# # tag = BeautifulSoup(item, 'lxml').find_all('category')[0]
# # tranverse(tag)
#对文件夹里面的所有文件进行翻译
def TranslateAll(srcfolder,destfolder):
for root, dirs, files in os.walk(srcfolder):
for fn in files:
xmlTranslate(srcfolder+"/"+fn,destfolder+"/"+fn)
print(fn+" has been translated")
#对文件夹里面的aiml文件进行命名,改成txt文件
def rename(folder):
for parent, dirnames, filenames in os.walk(folder):
for filename in filenames:
newName=filename.split('.')[0]+'.'+'txt'
os.rename(os.path.join(parent, filename), os.path.join(parent, newName))
if __name__ == '__main__':
# xmlTranslate('ai.txt','ai-c.txt')
# rename('alice-e')
# rename('standard-e')
# tag = BeautifulSoup('<category><pattern>HAVE WHAT</pattern><template><srai>what do you have</srai></template></category>', 'lxml').find_all('category')[0]
# print(tag)
# tranverse(tag)
# print(tag)
#翻译alice-c文件夹里面的文件到alice-e
TranslateAll('alice-e','alice-c')
| true
|
aaea7fe7acc39c1c517311540de8d1fa44cc94c3
|
Python
|
onehours/python-crawler
|
/xiaoshuo-quanshuwang.com/get_book.py
|
UTF-8
| 1,447
| 2.84375
| 3
|
[] |
no_license
|
import requests
import time
from lxml import etree
from get_headers import getheaders
import sys
if len(sys.argv) == 1:
url = 'http://www.quanshuwang.com/book/174/174135'
else:
url = sys.argv[1]
if not url.startswith('http'):
print('请输入有效的url')
sys.exit(1)
def get_obj(url):
# headers = {
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
# }
headers = getheaders()
html = requests.get(url=url, headers=headers)
html.encoding = html.apparent_encoding
et_obj = etree.HTML(html.text)
return et_obj
main_text = get_obj(url)
book_name = main_text.xpath('//div[@class="chapName"]/strong/text()')[0]
print('本书名:{}'.format(book_name))
book_name = book_name + '.txt'
li_list = main_text.xpath('//div[@class="clearfix dirconone"]/li')
with open(book_name,'w',encoding='utf-8') as f:
for li in li_list:
url = li.xpath("./a/@href")[0]
title = li.xpath("./a/@title")[0]
print(title, url)
try:
detail_obj = get_obj(url)
text = detail_obj.xpath('//div[@id="content"]/text()')
except Exception as e:
print(e)
continue
text2 = ''.join(text).replace('\r\n\xa0\xa0\xa0\xa0','')
f.write(title + '\r\n')
f.write(text2 + '\r\n')
| true
|
279c4ba720b08aee015799dcc4db84177a828a4e
|
Python
|
mandub/project_2
|
/convolution.py
|
UTF-8
| 2,660
| 3.421875
| 3
|
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
def convolve(g, h):
"""
Convolves g with h, returns valid portion
:param g: image
:param h: filter
:return: result of convolution, shape=( max( len(g), len(h) ), max( len(g[0]), len(h[0]) ) )
result of convolution, shape=( max( len(g), len(h) ) - min( len(g), len(h) ) + 1,
max( len(g[0]), len(h[0]) ) - min( len(g[0]), len(h[0]) ) + 1 )
"""
out_m = max(len(g), len(h)) - min(len(g), len(h)) + 1
out_n = max(len(g[0]), len(h[0])) - min(len(g[0]), len(h[0])) + 1
out_array = np.zeros(shape=(out_m, out_n))
# Iterate over entire output image
for u in range(len(out_array)):
for v in range(len(out_array[u])):
# One-liner to do convolution
out_array[u][v] = np.sum(np.multiply(h, g[u: u + len(h), v: v + len(h[0])]))
return out_array
def _pad_input(pad_x, pad_y, g, padding_scheme='fill', fill_val=0):
if padding_scheme == 'fill':
v_buff = np.zeros(shape=(pad_x, len(g[0]))) + fill_val
g = np.vstack((v_buff, g, v_buff))
h_buff = np.zeros(shape=(len(g), pad_y)) + fill_val
g = np.hstack((h_buff, g, h_buff))
elif padding_scheme == 'nn':
v_buff = np.tile(np.zeros(shape=(1, len(g[0]))) + g[0], (pad_x, 1))
g = np.vstack((v_buff, g, v_buff))
# Have to do some transposition to get column vectors
h_buff = np.tile((np.zeros(shape=(len(g), 1)).T + g[:, 0]).T, (1, pad_y))
g = np.hstack((h_buff, g, h_buff))
# TODO: fill in diagonals?
elif padding_scheme == 'mirror':
raise NotImplementedError("Padding scheme {0} is not yet implemented".format(padding_scheme))
return g
def non_linear_convolve(g, filter_size):
# Calculate output shape
out_m = max(len(g), filter_size)
out_n = max(len(g[0]), filter_size)
# Calculate pad size
pad_x = filter_size - 1
pad_y = filter_size - 1
g = _pad_input(pad_x, pad_y, g)
out_array = np.empty(shape=(out_m, out_n), dtype=bool)
# Iterate over entire output image
for u in range(len(out_array)):
for v in range(len(out_array[u])):
# Calculate max in neighborhood
out_array[u][v] = np.equal(g[u + pad_x, v + pad_y], np.max(g[u: u + filter_size, v: v + filter_size]))
return out_array
def img_convolution(img_fname, img_filter):
img_color = plt.imread(img_fname)
img_gray = img_color.mean(axis=2) # Convert to greyscale
out = convolve(g=img_gray, h=img_filter)
# Plot
plt.imshow(img_gray, cmap='gray')
plt.show()
plt.imshow(out, cmap='gray')
plt.show()
| true
|
4f85b028c59999f4017254ba2d4f5e4c5fa308c4
|
Python
|
ealehman/mpi
|
/mandelbrot/mandelbrot_masterslave.py
|
UTF-8
| 2,016
| 2.859375
| 3
|
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
from mpi4py import MPI
from P4_serial import *
def slave(comm):
jobs = True
while jobs:
status = MPI.Status()
y = comm.recv(source=0, tag = MPI.ANY_TAG, status = status) #, status=status)
tag = status.Get_tag()
if tag >= 1024:
jobs = False
print 'slave received row: ' + str(tag)
#x = np.linspace(minX, maxX, width)
temp = []
for x in np.linspace(minX, maxX, width):
temp.append(mandelbrot(x,y))
comm.send(temp, dest = 0, tag = tag)
print 'slave sent row: ' + str(tag) #+ " values: " + str(temp)
return
def master(comm):
image = np.zeros([height,width], dtype=np.uint16)
count = 0
size = comm.Get_size()
#send as many rows as possible to processes
y = np.linspace(minY, maxY, height)
for p in range(1,size):
comm.send(y[count], dest = p, tag = count)
print 'master sent row: ' + str(count)
count += 1
#send next row to available slaves until there are no more rows left
while count < 1024:
status = MPI.Status()
t = comm.recv(source= MPI.ANY_SOURCE, tag = MPI.ANY_TAG, status = status) #, status=status)
n = status.Get_tag()
print 'master received row: ' + str(n)
source = status.Get_source()
image[n] = t
comm.send(y[count], dest = source, tag = count)
print 'master sent row: ' + str(count)
count += 1
return image
if __name__ == '__main__':
# Get MPI data
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
start_time = MPI.Wtime()
C = master(comm)
end_time = MPI.Wtime()
print "Time: %f secs" % (end_time - start_time)
plt.imsave('Mandelbrot.png', C, cmap='spectral')
plt.imshow(C, aspect='equal', cmap='spectral')
plt.show()
else:
slave(comm)
| true
|
54c0bd639845218533276a39cac3615371227147
|
Python
|
dantepsychedelico/sufproject
|
/socketServer/router.py
|
UTF-8
| 2,038
| 2.65625
| 3
|
[] |
no_license
|
import json, time
from Users import users
from mongoCtrl import mongoCtrl as mctrl
class router:
def __init__(self, socket):
""" every online user have one router object and used 'Ctrl' method to control request and response """
self.socket = socket
self.uid = None
self.__route = {
"new": self.newUser,
"online": self.updateSocket,
"newroom": self.newRoom,
"join": self.joinRoom,
"chat": self.chat
}
def Ctrl(self, reqBinary):
data = json.loads(reqBinary.decode())
method = data["method"]
if self.uid is None:
self.uid = data.get("uid")
res = self.__route[method](data)
res["method"] = method
if "status" not in res:
res["status"] = "ok"
return res
def newUser(self, data):
""" uid: userid; sid: security id """
self.uid = users.createUser(self.socket)
self.sid = int(time.time())
mctrl.signUp(self.uid, self.sid)
return {"uid": self.uid, "sid": hex(self.sid)[2:]}
def updateSocket(self, data):
""" update socket connection for the same user """
self.uid = data["uid"]
users.updateSocket(self.uid, self.socket)
return {"uid": self.uid}
def stopSocket(self):
""" remove the socket connection for the user """
users.removeSocket(self.uid)
def newRoom(self, data):
""" """
roomid, createtime = mctrl.newRoom(**data)
return {"roomid": roomid, "createtime": createtime}
def joinRoom(self, data):
res = mctrl.joinRoom(data["roomid"], self.uid)
return res
def chat(self, data):
members, time = mctrl.chatRoom(**data)
data["time"] = time
data["status"] = "getok"
for member in members:
if member!=self.uid:
users.sendSocket(member, data)
return {"uid": self.uid, "time": time, "status": "sendok"}
| true
|
a0af15dfdd0fbd612a46b33e14408c4b257a88b2
|
Python
|
AaruranLog/Analogies
|
/analogies/utils/word_entry.py
|
UTF-8
| 326
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
"""
Forms to capture text
"""
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class SimpleWordEntry(FlaskForm):
"""Simplest form to capture text"""
text = StringField('Text: ', validators=[DataRequired])
submit = SubmitField('Submit')
| true
|
25c85237687f297ded228521719eed1d72715d5b
|
Python
|
DaHuO/Supergraph
|
/codes/CodeJamCrawler/16_0_2/rchen8/revenge_of_the_pancakes.py
|
UTF-8
| 376
| 2.953125
| 3
|
[] |
no_license
|
file = open('revenge_of_the_pancakes.txt', 'r')
output = open('revenge_of_the_pancakes_out.txt', 'w')
t = int(file.readline())
for i in xrange(0, t):
s = file.readline()
count = 0
for j in xrange(0, len(s) - 2):
if s[j] != s[j + 1]:
count += 1
if s[-2] == '-':
count += 1
output.write('Case #' + str(i + 1) + ': ' + str(count) + '\n')
file.close()
output.close()
| true
|
1a45f311253331631bb052de98bdb1f6e00118ab
|
Python
|
vstarman/python_codes
|
/19day/02.jing_dong.py
|
UTF-8
| 1,556
| 3.03125
| 3
|
[] |
no_license
|
from pymysql import *
class JD(object):
def __init__(self):
# 创建数据库对象 和 数据库操作对象
self.qd_liu = connect(
host='localhost',
port=3306,
database='jd_market',
user='root',
password='mysql',
charset='utf8')
self.cursor = self.qd_liu.cursor()
@staticmethod
def print_menu():
"""打印功能菜单"""
print("----------------京东商城--------------")
print("1:显示所有商品")
print("2:下订单")
print("3:登陆")
print("4:注册")
print("5:退出")
return input("请输入功能编号:")
def run(self):
while True:
number = self.print_menu()
if number == "1":
self.show_all_goods()
elif number == "2":
self.order()
elif number == "3":
self.login()
elif number == "4":
self.register()
elif number == "5":
self.__quit__()
return
else:
print("输入功能序号有误,请重新输入...")
def show_all_goods(self):
pass
def order(self):
pass
def login(self):
pass
def register(self):
pass
def __quit__(self):
self.cursor.close()
self.qd_liu.close()
print("系统已登出...")
def main():
jd = JD()
jd.run()
if __name__ == '__main__':
main()
| true
|
291fb6c3d36dc89483af428cf73c99c1888f105c
|
Python
|
Aggraxis/killer-bot
|
/utilities.py
|
UTF-8
| 1,138
| 3.65625
| 4
|
[
"MIT"
] |
permissive
|
import csv
from random import randint
def listFiller(fileName):
with open (fileName) as csvfile:
reader = csv.DictReader(csvfile)
return (list(reader))
def compose_response(random_target):
# random_target is a dictionary, and the key names like
# 'CONTRACT_NUMBER' come from the header row in the CSV
# file. So if your spreadsheet has different headers,
# change this response string accordingly.
return (f"Contract # {random_target['CONTRACT_NUMBER']}\n" +
f"Name: {random_target['TARGET']}\n" +
f"Zone: {random_target['ZONE']}\n" +
f"{random_target['LEDGER_TEXT']}")
# I think everybody's dice bot uses this logic.
def roll(roll):
rolling = []
roll = roll.lower()
try:
for x in range(int(roll.split('d')[0])):
rolling.append(randint(1,int(roll.split('d')[1])))
return (f'You rolled {" ".join(str(x) for x in rolling)}, ' +
f'which has a total of {sum(rolling)}')
except Exception as err:
return f'The argument provided was not in XdY format. ex: 2d6'
| true
|
0eff68e3d52c755f6cedf473296a21905f03c92f
|
Python
|
Ogiwara-CostlierRain464/scikit-learning
|
/play.py
|
UTF-8
| 185
| 3.734375
| 4
|
[] |
no_license
|
for i in range(1, 101):
if i % 15 == 0:
print("WizzWuzz")
elif i % 3 == 0:
print("Wizz")
elif i % 5 == 0:
print("Wuzz")
else:
print(i)
| true
|
6fe2f20c583da091aa3bfd85562d65ab8762105c
|
Python
|
aig-upf/automated-programming-framework
|
/domains/other/blocks/gen-problem.py
|
UTF-8
| 1,175
| 2.53125
| 3
|
[] |
no_license
|
#! /usr/bin/env python
import sys,time,random
#**************************************#
# MAIN
#**************************************#
try:
nblocks = int(sys.argv[1])
except:
print "Usage:"
print sys.argv[0] + " <nblocks>"
sys.exit(-1)
str_problem=""
str_problem=str_problem + "(define (problem p"+str(nblocks)+"-"+time.strftime("%d%m%Y%H%M%S")+")\n"
str_problem=str_problem + " (:domain blocks)\n"
str_problem=str_problem + " (:objects "
for j in range(0,nblocks):
str_problem=str_problem + "b"+str(j+1)+" "
str_problem=str_problem + "- block "
str_problem=str_problem + ")\n"
str_problem=str_problem + " (:init "
str_problem=str_problem + "(clear b1) "
str_problem=str_problem + "(ontable b"+str(nblocks)+") "
for j in range(0,nblocks-1):
str_problem=str_problem + "(on b"+str(j+1)+" b"+str(j+2)+")"
str_problem=str_problem + "(empty) "
random.seed()
bgreen = random.randint(0,nblocks)
str_problem=str_problem + "(green b"+str(bgreen)+")"
str_problem=str_problem + ")\n"
str_problem=str_problem + " (:goal (and (have b"+str(bgreen)+"))))\n"
f_problem=open("new-problem.pddl","w")
f_problem.write(str_problem)
f_problem.close()
sys.exit(0)
| true
|
71de6ed5f999d4ec597a8ff5cf4f8a841b70766c
|
Python
|
rmorales87atx/cosc1336_fall12
|
/lab01/tip_tax_total.py
|
UTF-8
| 961
| 4.34375
| 4
|
[] |
no_license
|
# COSC 1336 Lab 1 Problem 1
# Robert Morales
#
# Test Case:
# The bill amount is $100.00. The tip is $15.00, tax is $7.00,
# total is $122.00.
#
# First probem is that input is not being correctly converted.
# Using 'float()' fixes this problem.
#
# Second problem is in the summation of the total; the bill
# total is bill + tip + tax. Changing the original "+ total"
# to "+ tax" fixes this.
#
# Third problem, in my opinion, is that the numbers are not properly
# formatted in the typical form that currency is written.
# Using "format()" fixes this. Adding sep='' to the print() calls also
# removes the extra space automatically placed after the currency symbol.
tip_percent = 0.15
tax_percent = 0.07
bill = float(input("Enter the bill amount: $"))
tip = bill * tip_percent
tax = bill * tax_percent
total = bill + tip + tax
print("Tip: $", format(tip, ",.2f"), sep='')
print("Tax: $", format(tax, ",.2f"), sep='')
print("Total: $", format(total, ",.2f"), sep='')
| true
|
6899d0950bea82651195cdea9c2c737af548730a
|
Python
|
park8989/python_example
|
/initial_code/dateExpressChange.py
|
UTF-8
| 636
| 3.890625
| 4
|
[] |
no_license
|
#! python3
# 日付表示方法を変える
import datetime
today1= datetime.date.today()
today2= "{0:%Y:%m:%d}".format(today1)
today3= "{0:%Y.%m.%d}".format(today1)
today4= "{0:%Y年%m月%d日}".format(today1)
today5= "{0:%Y년%m월%d일}".format(today1)
print(today1)
print(today2)
print(today3)
print(today4)
print(today5)
#曜日を付け加える
p = today1.weekday()
day_week = {0: '月', 1 : '火', 2: '水', 3: '木', 4: '金', 5: '土', 6: '日'} # pの変数が得られる数字と曜日を関連付ける
print(day_week[p]) #曜日を返す
today6= "{0:%Y年%m月%d日}({1})".format(today1, day_week[p])
print(today6)
| true
|
522536cd6e41e5af96eeec8119ede510758b5034
|
Python
|
nocproject/noc
|
/core/clickhouse/fields.py
|
UTF-8
| 10,912
| 2.59375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# ----------------------------------------------------------------------
# ClickHouse field types
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Python modules
from ast import literal_eval
from datetime import datetime
import itertools
import socket
import struct
from collections import defaultdict
class BaseField(object):
"""
BaseField class for ClickHouse structure
"""
FIELD_NUMBER = itertools.count()
db_type = None
default_value = ""
def __init__(self, default=None, description=None, low_cardinality=False):
"""
:param default: Default field value (if value not set)
:param description: Field description
"""
self.field_number = next(self.FIELD_NUMBER)
self.name = None
self.default = default or self.default_value
self.description = description
self.is_agg = False
self.low_cardinality = low_cardinality
def set_name(self, name):
"""
Set field name according to model
:param name: Field name
:return:
"""
self.name = name
def iter_create_sql(self):
"""
Yields (field name, db type) for all nested fields
:return:
"""
yield self.name, self.get_db_type()
def get_db_type(self, name=None):
"""
Return Field type. Use it in create query
:param name: Optional nested field name
:return:
"""
if self.low_cardinality:
return f"LowCardinality({self.db_type})"
return self.db_type
def get_displayed_type(self):
"""
Return Field type for external application
:return:
"""
return self.db_type
def apply_json(self, row_json, value):
"""
Append converted `value` to `row _json` dict
:param json: Row dict
:param value: Raw value
:return:
"""
row_json[self.name] = self.to_json(value)
def to_json(self, value):
"""
Convert `value` to JSON-serializeable format
:param value: Input value
:return: JSON-serializable value
"""
if value is None:
return self.default_value
return str(value)
def to_python(self, value):
"""
Use method when field convert to python object
:param value:
:return:
"""
return value
def get_select_sql(self):
return self.name
@staticmethod
def nested_path(name):
"""
Split nested path to field name and nested name
:param name: Nested field name
:return: (Field name, Nested name)
"""
name = name.strip("`")
if "." in name:
return name.split(".", 1)
return name, None
class StringField(BaseField):
db_type = "String"
default_value = ""
class DateField(BaseField):
db_type = "Date"
default_value = "0000-00-00"
def to_json(self, value):
if value is None:
return self.default_value
return value.strftime("%Y-%m-%d")
def to_python(self, value):
if not value or value == self.default_value or value == "1970-01-01":
return None
else:
return datetime.strptime(value, "%Y-%m-%d").date()
class DateTimeField(BaseField):
db_type = "DateTime"
default_value = "0000-00-00 00:00:00"
def to_json(self, value):
if value is None:
return self.default_value
return value.strftime("%Y-%m-%d %H:%M:%S")
def to_python(self, value):
if not value or value == self.default_value or value == "1970-01-01 00:00:00":
return None
else:
return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
class UInt8Field(BaseField):
db_type = "UInt8"
default_value = 0
def to_json(self, value):
if value is None:
return self.default_value
return int(value)
def to_python(self, value):
if not value:
return self.default_value
return int(value)
class UInt16Field(UInt8Field):
db_type = "UInt16"
class UInt32Field(UInt8Field):
db_type = "UInt32"
class UInt64Field(UInt8Field):
db_type = "UInt64"
class Int8Field(UInt8Field):
db_type = "Int8"
class Int16Field(UInt8Field):
db_type = "Int16"
class Int32Field(UInt8Field):
db_type = "Int32"
class Int64Field(UInt8Field):
db_type = "Int64"
class Float32Field(BaseField):
db_type = "Float32"
default_value = 0.0
def to_json(self, value):
if value is None:
return self.default_value
return float(value)
def to_python(self, value):
if not value:
return self.default_value
return float(value)
class Float64Field(Float32Field):
db_type = "Float64"
class BooleanField(UInt8Field):
def to_json(self, value):
return 1 if value else 0
def to_python(self, value):
if not value:
return False
return value == "1"
class ArrayField(BaseField):
def __init__(self, field_type, description=None):
super().__init__(description=description)
self.field_type = field_type
def to_json(self, value):
return [self.field_type.to_json(v) for v in value]
def get_db_type(self, name=None):
return f"Array({self.field_type.get_db_type()})"
def get_displayed_type(self):
return "Array(%s)" % self.field_type.get_db_type()
def to_python(self, value):
if not value or value == "[]":
return []
return [self.field_type.to_python(x.strip("'\" ")) for x in value[1:-1].split(",")]
class MaterializedField(BaseField):
def __init__(self, field_type, expression, description=None):
super().__init__(description=description, low_cardinality=True)
self.field_type = field_type
self.expression = expression
def get_db_type(self, name=None):
return f"LowCardinality({self.field_type.get_db_type()})"
def iter_create_sql(self):
yield self.name, f"{self.get_db_type()} MATERIALIZED {self.expression}"
class ReferenceField(BaseField):
db_type = "UInt64"
default_value = 0
SELF_REFERENCE = "self"
def __init__(self, dict_type, description=None, model=None, low_cardinality=False):
super().__init__(description=description, low_cardinality=low_cardinality)
self.is_self_reference = dict_type == self.SELF_REFERENCE
self.dict_type = dict_type
self.model = model
if self.low_cardinality:
self.db_type = "String"
def to_json(self, value):
if value is None:
return self.default_value
if self.low_cardinality:
return value
return value.bi_id
class IPv4Field(BaseField):
db_type = "UInt32"
def to_json(self, value):
"""
Convert IPv4 as integer
:param value:
:return:
"""
if value is None:
return 0
return struct.unpack("!I", socket.inet_aton(value))[0]
def to_python(self, value):
if value is None:
return "0"
return socket.inet_ntoa(struct.pack("!I", int(value)))
def get_displayed_type(self):
return "IPv4"
class IPv6Field(BaseField):
db_type = "UInt128"
def to_json(self, value):
"""
Convert IPv6 as integer
:param value:
:return:
"""
if value is None:
return 0
return struct.unpack("!I", socket.inet_aton(value))[0]
def to_python(self, value):
if value is None:
return "0"
return socket.inet_ntoa(struct.pack("!I", int(value)))
def get_displayed_type(self):
return "IPv6"
class AggregatedField(BaseField):
def __init__(self, expression, field_type, agg_function, params=None, description=None):
super().__init__(description=description)
self.field_type = field_type
self.agg_function = agg_function
self.expression = expression
self.params = params
def to_json(self, value):
return self.field_type.to_json(value)
def get_db_type(self, name=None):
return f"AggregateFunction({self.agg_function}, {self.agg_function.get_db_type(self.field_type)})"
def get_expression(self, combinator: str = None):
return self.agg_function.get_expression(self, combinator)
# return self.f_expr.format(p={"field": self.name, "function": function, "f_param": f_param})
# return "{p[function]}Merge({p[field]}_{p[function]})"
class MapField(BaseField):
def __init__(self, field_type, description=None):
super().__init__(description=description)
self.field_type = field_type
def to_json(self, value):
if not isinstance(value, dict):
raise ValueError("Value for Map Field Must be Dict")
return value
def get_db_type(self, name=None):
return f"Map(String, {self.field_type.get_db_type()})"
class NestedField(ArrayField):
db_type = "Nested"
def iter_create_sql(self):
for nested_field in self.field_type._meta.ordered_fields:
yield f"{self.name}.{nested_field.name}", self.get_db_type(nested_field.name)
def apply_json(self, row_json, value):
arrays = defaultdict(list)
for item in value:
row = {}
for f in item:
self.field_type._meta.fields[f].apply_json(row, item[f])
for nested_name in row:
full_name = "%s.%s" % (self.name, nested_name)
arrays[full_name] += [row[nested_name]]
row_json.update(arrays)
def get_db_type(self, name=None):
if name is None:
return "Nested (\n%s \n)" % self.field_type.get_create_sql()
return "Array(%s)" % self.field_type._meta.fields[name].get_db_type()
def get_displayed_type(self):
return "Nested (\n%s \n)" % self.field_type.get_create_sql()
def to_python(self, value):
if not value or value == "[]":
return []
value = literal_eval(value)
return [
{
f.name: f.to_python(v.strip("'"))
for f, v in (dict(zip(self.field_type._meta.ordered_fields, v)).items())
}
for v in value
]
def get_select_sql(self):
m = [
"toString(%s.%s[x])" % (self.name, f.name) for f in self.field_type._meta.ordered_fields
]
r = [
"arrayMap(x -> [%s], arrayEnumerate(%s.%s))"
% (",".join(m), self.name, self.field_type.get_pk_name())
]
return "".join(r)
| true
|
0cdfd467f31e9f092a60f613b7a4a636ce06790f
|
Python
|
qmnguyenw/python_py4e
|
/geeksforgeeks/python/python_all/80_10.py
|
UTF-8
| 2,301
| 3.734375
| 4
|
[] |
no_license
|
Python | Rear stray character String split
Sometimes, while working with Python Strings, we can have problem in which we
need to split a string. But sometimes, we can have a case in which we have
after splitting a blank space at rear end of list. This is usually not
desired. Lets discussed ways in which this can be avoided.
**Method #1 : Usingsplit() + rstrip()**
The combination of above functions can be used to solve this problem. In this,
we remove the stray character from the string before split(), to avoid the
empty string in split list.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Rear stray character String split
# Using split() + rstrip()
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using split() + rstrip()
res = test_str.rstrip(', ').split(', ')
# printing result
print("The evaluated result is : " + str(res))
---
__
__
**Output :**
The original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
**Method #2 : Usingsplit()**
The use of rstrip() can be avoided by passing additional arguments while
performing the split().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Rear stray character String split
# Using split()
# initializing string
test_str = 'gfg, is, best, '
# printing original string
print("The original string is : " + test_str)
# Rear stray character String split
# Using split()
res = test_str.split(', ')[0:-1]
# printing result
print("The evaluated result is : " + str(res))
---
__
__
**Output :**
The original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
| true
|
28cc67917715f6c9ede4590b4c3962532693bf83
|
Python
|
andrenasx/FEUP-MNUM
|
/Segundo Teste/2016T2/4.py
|
UTF-8
| 250
| 3.140625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 21:16:39 2019
@author: fmna
"""
def dyx(x,y):
return -0.25*(y-42)
def euler(T,t,tf,h):
while(t<tf):
T+=h*dyx(t,T)
t+=h
return T
#euler(10,5,5+2*0.4,0.4)
| true
|
6707e782bcb42b5bc6a72cd8282efdc575e2c2c7
|
Python
|
dcarrillo11/PHaDA
|
/features.py
|
UTF-8
| 2,011
| 3.0625
| 3
|
[] |
no_license
|
#PHaDA: features v1.0
#Daniel Carrillo Martin
import os
import shutil
from datetime import datetime
from subprocess import Popen,PIPE,call
from time import sleep
from Bio import SeqIO
def directorer(filequery,filesubject):
"""filequery: query fasta file
filesubject: subject fasta file
This functions creates the main directories used for the
script and make a copy of the fasta files into the
Data subdirectory."""
dt = datetime.now()
maindir = "PHaDA_"+dt.strftime("%Y-%m-%d_%H-%M-%S")
os.mkdir(maindir)
os.mkdir("%s/Data/" % maindir)
os.mkdir("%s/Results/" % maindir)
shutil.copy2(filequery, "./%s/Data/" % maindir)
shutil.copy2(filesubject, "./%s/Data/" % maindir)
os.chdir(maindir)
print("Directory %s has been created!" % maindir)
print("Results will be saved there.")
sleep(3)
def isfasta(filename):
""""filename: a file for creating a dictionary and testing.
This function check if the file introduced is a fasta file
while creating a dictionary of the fasta file. Returns the dictionary,
bul also True if filename is a fasta file. False if it is not."""
with open(filename, "r") as handle:
fastadict = SeqIO.to_dict(SeqIO.parse(handle, "fasta"))
if fastadict:
test = True
else:
test = False
return test,fastadict
def installcheck(command):
"""command = a bash command to check.
This function checks whether a bash package is installed or not.
Returns True if it is installed. False, if it is not."""
try:
Popen([command,"-h"], stderr=PIPE, stdout=PIPE)
return True
except:
return False
def setup():
for x in range(0,4):
print("> Checking everything is okay","."*x, end="\r")
sleep(0.5)
def header():
call("clear",shell=True)
print("\n -------------------")
print("\tPHaDA v1.0")
print(" -------------------")
print("> Daniel Carrillo, 2020 <\n")
| true
|
ae189caa08994b60d3490b83a17a690699c69f1e
|
Python
|
fedetft/tdmh
|
/experiments/scripts/old/extract_graph.py
|
UTF-8
| 704
| 2.859375
| 3
|
[] |
no_license
|
#!/usr/bin/python
import re
import sys
from graphviz import Graph
dot = Graph(name='Topology')
dot.graph_attr['rankdir'] = 'LR'
nodes = []
fname = (sys.argv[1][0: sys.argv[1].rindex(".")] if sys.argv[1].index(".") > 0 else sys.argv[1]) + '.pdf'
with open(sys.argv[1], 'r') as fin:
line = fin.readline()
while line:
node_a = int(line[1])
node_b = int(line[5])
if node_a not in nodes:
dot.node(str(node_a), str(node_a))
if node_b not in nodes:
dot.node(str(node_b), str(node_b))
m = re.search(r'([^ ]+) %$', line)
dot.edge(str(node_a), str(node_b), m.group(1) + "%")
line = fin.readline()
print dot.render(fname)
| true
|
75d596a1db2dc721cf6706059b6743a10f3827c7
|
Python
|
fherrmannsdoerfer/masterArbeit
|
/scriptsForPictures/compareSkellamVariance.py
|
UTF-8
| 2,686
| 2.828125
| 3
|
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plot
def doSkellam(data):
diffs=data[1:]-data[:-1]
meandiff = (diffs[0]-diffs[-1])/np.float(data.shape[0])
sig2 = np.sum((meandiff-diffs)**2)/(data.shape[0]-1)
return (meandiff+sig2)/2.
listvarvar = []
listvarskellam = []
listmeanskellam = []
listmeanvar=[]
for i in range(1,40):
print i
listvar =[]
listskellam = []
for j in range(200000):
data = np.random.poisson(i,200)
listvar.append(np.var(data))
listskellam.append(doSkellam(data))
listvarvar.append(np.var(listvar))
listvarskellam.append(np.var(listskellam))
listmeanskellam.append(np.mean(listskellam))
listmeanvar.append(np.mean(listvar))
plot.figure(1)
plot.plot(range(1,40), listvarvar, linewidth = 3, label="variance")
plot.plot(range(1,40), listvarskellam, linewidth = 3, label="Skellam")
x0=0
x1=40
y0=0
y1=40
dx = (x1-x0)/.8
dy = (y1-y0)/.8
xklein0=38
xklein1=39
yklein0=37.8
yklein1=39.2
plot.legend(loc = 'upper left', bbox_to_anchor = (0.1, 0.9), prop={'size':15})
plot.xlabel("mean of the simulated Poisson distribution", fontsize=15)
plot.ylabel("variance of the estimated mean", fontsize=15)
plot.tick_params(axis='both', labelsize=12)
plot.savefig('/home/herrmannsdoerfer/MasterArbeit/pictures/SkellamVarVar.png', dpi=300)
plot.figure(2)
plot.axes([0.1,0.1,.8,.8])
plot.plot(range(1,40), listmeanvar, linewidth = 3, label="variance")
plot.plot(range(1,40), listmeanskellam, linewidth = 3, label="Skellam")
plot.axis([x0,x1,y0,y1])
plot.plot([xklein0,xklein1,xklein1,xklein0,xklein0],[yklein0,yklein0,yklein1,yklein1,yklein0], color = [0,0,0])
plot.plot([xklein0,(0.2-0.1)*dx],[yklein0,(0.55-0.1)*dy], color = [0,0,0], linestyle = '--')
plot.plot([xklein0,(0.2-0.1)*dx],[yklein1,(0.55+0.3-0.1)*dy], color = [0,0,0], linestyle = '--')
plot.plot([xklein1,(0.2+0.3-0.1)*dx],[yklein0,(0.55-0.1)*dy], color = [0,0,0], linestyle = '--')
plot.plot([xklein1,(0.2+0.3-0.1)*dx],[yklein1,(0.55+0.3-0.1)*dy], color = [0,0,0], linestyle = '--')
plot.xlabel("mean of the simulated Poisson distribution", fontsize=15)
plot.ylabel("mean of the estimated mean", fontsize=15)
plot.tick_params(axis='both', labelsize=12)
plot.legend(loc = 'upper left', bbox_to_anchor = (0.6, 0.4), prop={'size':15})
plot.axes([0.2,0.55,.3,.3])
plot.plot(range(1,40), listmeanvar)
plot.plot(range(1,40), listmeanskellam)
plot.axis([xklein0,xklein1,yklein0,yklein1])
plot.xlabel("mean of the simulated Poisson distribution", fontsize=10)
plot.ylabel("mean of the estimated mean", fontsize=10)
plot.tick_params(axis='both', labelsize=12)
plot.savefig('/home/herrmannsdoerfer/MasterArbeit/pictures/SkellamVarMean.png', dpi=300)
| true
|
7655e51aa224f544226172a1c4c7be0f85fdd6ec
|
Python
|
paramita2302/algorithms
|
/iv/Strings/Palindrome.py
|
UTF-8
| 839
| 3.859375
| 4
|
[
"MIT"
] |
permissive
|
class Palindrome():
# @param A : string
# @return an integer
def isPalindrome(self, A):
n = len(A)
if len(A) < 2:
return 1
i = 0
j = n -1
while i < j:
if (A[i]).isalnum() and (A[j]).isalnum():
print((A[i]).lower())
print(A[j].lower())
if A[i].lower() == A[j].lower():
i = i + 1
j = j - 1
continue
else:
return 0
elif not (A[i]).isalnum():
i = i + 1
elif not (A[j]).isalnum():
j = j - 1
return 1
A = "A man, a plan, a canal: Panama"
# A = "race a car"
# # A = ""
# A = "a"
A = "abba"
A = "aba"
A = "Malayalam"
a = Palindrome()
print(a.isPalindrome(A))
| true
|
fac34e0cbc83b5acaebbbb2346201622afbef9b3
|
Python
|
wulinlw/leetcode_cn
|
/leetcode-vscode/92.反转链表-ii.py
|
UTF-8
| 2,076
| 3.828125
| 4
|
[] |
no_license
|
#
# @lc app=leetcode.cn id=92 lang=python3
#
# [92] 反转链表 II
#
# https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
#
# algorithms
# Medium (49.23%)
# Likes: 314
# Dislikes: 0
# Total Accepted: 38.3K
# Total Submissions: 77.5K
# Testcase Example: '[1,2,3,4,5]\n2\n4'
#
# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
#
# 说明:
# 1 ≤ m ≤ n ≤ 链表长度。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL, m = 2, n = 4
# 输出: 1->4->3->2->5->NULL
#
#
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def initlinklist(self, nums):
head = ListNode(nums[0])
re = head
for i in nums[1:]:
re.next = ListNode(i)
re = re.next
return head
def printlinklist(self, head):
re = []
while head:
re.append(head.val)
head = head.next
print(re)
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
successor = None
def reverseN(head, n):
nonlocal successor
if n==1:
# 记录第 n + 1 个节点
successor = head.next
return head
last = reverseN(head.next, n-1)
head.next.next = head
head.next = successor
return last
if m==1:
return reverseN(head, n)
head.next = self.reverseBetween(head.next, m-1, n-1)
return head
# 写出了翻转前n个元素的方法后,
# 翻转 m 到 n 的问题,和 m-1 到 n-1 的问题一样,都是区间翻转
# 那当 m==1 时,问题退化成了翻转前 n 个元素
# 递归就可以了
# head.next 在递归中接上翻转后到节点
# @lc code=end
nums = [1,2,3,4,5]
m = 2
n = 4
o = Solution()
head = o.initlinklist(nums)
o.printlinklist(head)
h = o.reverseBetween(head, m, n)
o.printlinklist(h)
| true
|
b99f0f7eb61850c527bc566cb41233ba9a114e11
|
Python
|
SWHarrison/CS-2.1-Trees-Sorting
|
/Code/tree_project/B_plus_tree.py
|
UTF-8
| 11,251
| 3.796875
| 4
|
[] |
no_license
|
class B_plus_tree_node:
def __init__(self, is_leaf = True):
self.keys = []
self.children = []
self.is_leaf = is_leaf
self.next_leaf = None
# currently unused and non-functional
def add_node(self, key, new_node):
for i in range(len(self.keys)):
if key < self.keys[i]:
#self.children[i] = new_node # change to insert at i
self.children = self.children[0:i] + [key] + self.children[i:]
return
self.children.append(new_node)
def __repr__(self):
return str(self.keys)
class B_plus_tree:
def __init__(self,order = 4):
self.root = None
self.size = 0
self.order = order
def is_empty(self):
return self.size == 0
def contains(self, item):
if self.is_empty():
return False
current_node = self.root
while current_node.is_leaf == False:
print(current_node)
child_index = 0
while child_index < len(current_node.keys) and item >= current_node.keys[child_index]:
print(item, " is greater than or equal to", current_node.keys[child_index])
child_index += 1
current_node = current_node.children[child_index]
print("current node is",current_node, "checking for", item)
print("current node leaf?", current_node.is_leaf)
return item in current_node.keys
def all_values(self):
to_return = []
current_node = self.root
while current_node.is_leaf == False:
current_node = current_node.children[0]
while current_node.next_leaf:
for item in current_node.keys:
to_return.append(item)
current_node = current_node.next_leaf
for item in current_node.keys:
to_return.append(item)
return to_return
def insert(self,item):
# empty tree creates root
if self.is_empty():
self.root = B_plus_tree_node()
self.root.keys.append(item)
self.size += 1
else:
current_node = self.root
eject = self._insert_helper(current_node, item)
self.size += 1
if eject != None:
self.root = B_plus_tree_node(False)
self.root.keys.append(eject[0])
self.root.children.append(eject[2])
self.root.children.append(eject[1])
print("new root is",self.root)
print("children are",self.root.children)
''' From Wikipedia B+ tree article
Perform a search to determine what bucket the new record should go into.
If the bucket is not full (at most b − 1) entries after the insertion), add the record.
Otherwise, before inserting the new record
split the bucket
original node has ⎡(L+1)/2⎤ items
new node has ⎣(L+1)/2⎦ items
Move ⎡(L+1)/2⎤-th key to the parent, and insert the new node to the parent.
Repeat until a parent is found that need not split.
If the root splits, treat it as if it has an empty parent and split as outline above.'''
def _insert_helper(self, current_node, item):
"""
Recursive helper function that adds new item to tree.
Always adds item to leaf node, then pushes middle value up if needed.
"""
if current_node.is_leaf:
print("current node is:",current_node)
current_node.keys.append(item)
keys = current_node.keys
index = len(keys) - 1
while index > 0 and keys[index] < keys[index - 1]:
print(item, "is smaller than",keys[index - 1])
print("swapping")
keys[index], keys[index - 1] = keys[index - 1], keys[index]
print(current_node)
index -= 1
# if number of keys is greater than maximum number of keys, eject middle key to parent
if len(keys) >= self.order:
print("current node full, ejecting")
print("current node before ejection:",current_node)
mid = len(keys) // 2
#eject = keys.pop(len(keys)//2)
eject = keys[mid]
print("ejecting",eject)
new_node = B_plus_tree_node()
new_node.keys = keys[mid:]
new_node.next_leaf = current_node.next_leaf
current_node.keys = keys[0:mid]
current_node.next_leaf = new_node
print("new node (right)",new_node)
print("old node (left)",current_node)
return (eject, new_node, current_node)
else:
return None
else:
child_index = len(current_node.keys)
for i in range(len(current_node.keys)):
print("item:",item,"key:",current_node.keys[i])
if item <= current_node.keys[i]:
print(item," is less than",current_node.keys[i])
child_index = i
break
print("child index is",child_index, "node will be",current_node.children[child_index])
child_node = current_node.children[child_index]
ejected_item = self._insert_helper(child_node, item)
if ejected_item == None:
return None
else:
print("ejected items",ejected_item)
print("current_node",current_node)
print("current_node children are", current_node.children)
to_add = ejected_item[0]
new_node = ejected_item[1]
old_node = ejected_item[2]
current_node.children.insert(child_index+1,new_node)
print("current_node children",current_node.children)
# should now handle next_leaf when at leaf level
#if old_node.is_leaf:
# old.node.next_leaf = new_node
current_node.keys.append(to_add)
keys = current_node.keys
index = len(keys) - 1
while index > 0 and keys[index] < keys[index - 1]:
keys[index], keys[index - 1] = keys[index - 1], keys[index]
index -= 1
# if number of keys is greater than maximum number of keys, eject middle key to parent
if len(keys) >= self.order:
print("current node full, ejecting")
print("current node before ejection:",current_node)
mid = len(keys) // 2
#eject = keys.pop(len(keys)//2)
eject = keys[mid]
print("ejecting*****",eject)
new_node = B_plus_tree_node(False)
new_node.keys = keys[mid+1:]
new_node.children = current_node.children[mid+1:]
current_node.keys = keys[0:mid]
current_node.children = current_node.children[0:mid+1]
print("new node (right)",new_node)
print("old node (left)",current_node)
return (eject, new_node, current_node)
else:
return None
def delete(self, item):
if self.is_empty():
raise ValueError("Tree is empty!")
else:
current_node = self.root
key_changes = self._delete_helper(current_node, item)
self.size -= 1
# first attempt at delete oh lawdy this sucks
'''
def _delete_helper(self, current_node, item):
if current_node.is_leaf:
removed = None
for i in range(len(current_node.keys)):
if current_node.keys[i] == item:
removed = current_node.keys.pop(i)
break
# no item removed, item not in tree
if removed == None:
print("value not found")
return (None, False)
#raise ValueError(item, "not in tree!")
else:
# check if work needs to be done to fix tree
if len(current_node.keys) == 0:
return (removed, True)
else:
return (removed, False)
else:
child_index = len(current_node.keys)
for i in range(len(current_node.keys)):
#print("item:",item,"key:",current_node.keys[i])
if item <= current_node.keys[i]:
#print(item," is less than",current_node.keys[i])
child_index = i
break
print("child index is",child_index, "node will be",current_node.children[child_index])
child_node = current_node.children[child_index]
returned_value = self._delete_helper(child_node, item)
if returned_value[1] == False:
if returned_value[0] in current_node.keys:
# need to change index keys in current_node to fix tree structure
print("why is this so hard")
return None
else:
if child_node.is_leaf:
# need to fix tree, start by checking siblings
left_sibling = current_node.children[child_index - 1] if child_index > 0 else None
if left_sibling:
if len(left_sibling.keys) >= 2:
# left sibling has enough to steal from
value = left_sibling.keys.pop()
child_node.keys.insert(0,value)
current_node.keys[child_index - 1] = value
return (removed, False)
right_sibling = current_node.children[child_index + 1] if child_index < len(current_node.children) - 1 else None
if right_sibling:
if len(right_sibling.keys) >= 2:
# left sibling has enough to steal from
value = right_sibling.keys.pop(0)
child_node.keys.append(value)
current_node.keys[child_index] = value
return (removed, False)
# no siblings can give value, merging necessary'''
def test_bptree():
tree = B_plus_tree(5)
items = [40,30,20,50,60,10,70,80,15,25,45,85]
for item in items:
print("inserting", item)
tree.insert(item)
print("root",tree.root)
print("children",len(tree.root.children))
for child in tree.root.children:
print(child)
print("children are",child.children)
for child2 in child.children:
print(child2)
print("next leaf is",child2.next_leaf)
print("next leaf is",child.next_leaf)
print("\n\n *********** DONE INSERTING")
print(tree.contains(60))
print(tree.contains(40))
print(tree.contains(75))
print(tree.all_values())
tree.delete(40)
if __name__ == '__main__':
test_bptree()
| true
|
b08f4fc892d2727a77ca5945e1e017bcd59c1ac4
|
Python
|
Orbedi/Daily-coding-problem
|
/Daily_coding_problem_2.py
|
UTF-8
| 1,519
| 4.59375
| 5
|
[] |
no_license
|
""" Problem:
Given an array of integers, return a new array such that each element at index i
of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can't use division?
"""
def product_of_each_element(list_):
result = [1] * len(list_)
for i, elem_i in enumerate(list_):
for j, elem_j in enumerate(list_):
if i != j:
result[i] *= elem_j
return result
# If there is a zero in the list, this method will not work correctly
def product_of_each_element_with_division(list_):
result = [1] * len(list_)
for i, elem in enumerate(list_[1::]): result[0] *= elem
for i in range(1, len(list_)):
result[i] = int((result[i-1] / list_[i]) * list_[i-1])
return result
def product_of_each_element_left_to_right(list_):
aux = 1
result = [1] * len(list_)
for i,elem in enumerate(list_):
result[i] = aux
aux *= elem
aux = 1
for i in range(len(list_)-1, -1, -1):
result[i] *= aux
aux *= list_[i]
return result
def main():
list_ = [2.5, 7.6, 1.2]
list_ = [3, 5, 2, 1, 6]
print(product_of_each_element(list_))
print(product_of_each_element_with_division(list_))
print(product_of_each_element_left_to_right(list_))
if __name__ == '__main__':
main()
| true
|
765fbb9f14447f829cdba2fc8a957a1512507a02
|
Python
|
chrismabdo/airport-python
|
/apps/weather.py
|
UTF-8
| 191
| 3.03125
| 3
|
[] |
no_license
|
import random
class Weather:
def __init__(self):
self.conditions = ["sunny", "overcast", "stormy"]
def weather_check(self):
return random.choice(self.conditions)
| true
|
5b5ad3ea5ad60085ceec65e5999aa5c98cf58fd8
|
Python
|
brennan6/DSCI551
|
/project_final/mysqlRanksConnector.py
|
UTF-8
| 868
| 2.640625
| 3
|
[] |
no_license
|
from mysql.connector import Error
import mysql.connector
import json
cnx = mysql.connector.connect(host = 'project-dsci551-ranks.c8u9e3pxnupz.us-east-1.rds.amazonaws.com',
user = 'mbrennan6', password = 'songdsci551', database = 'songRanks')
def pull_down_ranks():
""" (2) Pull down all of the necessary data from the Ranks MySQL Database in RDS """
global cnx
ranks_dict = {}
ranks_dict["ranks"] = []
cursor = cnx.cursor()
query = "select * from ranks;"
cursor.execute(query)
rows = cursor.fetchall()
for rank in rows:
ranks_dict["ranks"].append({"song": rank[0], "score": rank[1]})
return ranks_dict
def write_json_file(dict_ranks):
with open('ranks_data.json', 'w') as outfile:
json.dump(dict_ranks["ranks"], outfile)
ranks_d = pull_down_ranks()
write_json_file(ranks_d)
| true
|
07fa944369a136a34c5d1b9b20b56821eed2da03
|
Python
|
mylesmcleroy/planar-data-classifier
|
/planar_data_classifier.py
|
UTF-8
| 12,295
| 3.59375
| 4
|
[] |
no_license
|
# coding: utf-8
# Planar data classification with one hidden layer
# Packages
# - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.
# - [sklearn](http://scikit-learn.org/stable/) provides simple and efficient tools for data mining and data analysis.
# - [matplotlib](http://matplotlib.org) is a library for plotting graphs in Python.
# - test_cases provides some test examples to assess the correctness of these functions
# - planar_utils provide various useful functions used in this classifier
# Package imports
import numpy as np
import matplotlib.pyplot as plt
from test_cases import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
get_ipython().magic('matplotlib inline')
np.random.seed(1) # set a seed so that the results are consistent
# Dataset
X, Y = load_planar_dataset()
# Visualize the dataset using matplotlib.
# The data looks like a "flower" with some red (label y=0) and some blue (y=1) points.
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
# X - a numpy-array (matrix) that contains features (x1, x2)
# Y - a numpy-array (vector) that contains labels (red:0, blue:1).
# Verify X and Y
shape_X = X.shape
shape_Y = Y.shape
m = shape_Y[1] # training set size
print('The shape of X is: ' + str(shape_X))
print('The shape of Y is: ' + str(shape_Y))
print('I have m = %d training examples!' % (m))
# Logistic Regression
# Before building the neural network, first see how logistic regression performs on this problem.
# Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T);
# Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")
# Print accuracy
LR_predictions = clf.predict(X.T)
print('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
'% ' + "(percentage of correctly labelled datapoints)")
# The dataset is not linearly separable, so logistic regression doesn't perform well.
# Neural Network model
# The general methodology to build a Neural Network is to:
# 1. Define the neural network structure (# of input units, # of hidden units, etc).
# 2. Initialize the model's parameters
# 3. Loop:
# - Implement forward propagation
# - Compute loss
# - Implement backward propagation to get the gradients
# - Update parameters (gradient descent)
# Define neural network structure
def layer_sizes(X, Y):
"""
Arguments:
X -- input dataset of shape (input size, number of examples)
Y -- labels of shape (output size, number of examples)
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""
n_x = X.shape[0] # size of input layer
n_h = 4 # size of hidden layer
n_y = Y.shape[0] # size of output layer
return (n_x, n_h, n_y)
# Test layer_sizes
X_assess, Y_assess = layer_sizes_test_case()
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)
print("The size of the input layer is: n_x = " + str(n_x))
print("The size of the hidden layer is: n_h = " + str(n_h))
print("The size of the output layer is: n_y = " + str(n_y))
# Initialize the model's parameters
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
params -- python dictionary containing parameters:
W1 -- weight matrix of shape (n_h, n_x)
b1 -- bias vector of shape (n_h, 1)
W2 -- weight matrix of shape (n_y, n_h)
b2 -- bias vector of shape (n_y, 1)
"""
np.random.seed(2) # set up a seed so that output matches test cases
W1 = np.random.randn(n_h, n_x) * 0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h) * 0.01
b2 = np.zeros((n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
# Test initialize_parameters
n_x, n_h, n_y = initialize_parameters_test_case()
parameters = initialize_parameters(n_x, n_h, n_y)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
# One pass of forward prop
def forward_propagation(X, parameters):
"""
Argument:
X -- input data of size (n_x, m)
parameters -- Python dictionary containing parameters (output of initialization function)
Returns:
A2 -- sigmoid output of the second activation
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
"""
# Retrieve each parameter from the dictionary "parameters"
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
# Implement forward prop to calculate A2 (probabilities)
Z1 = np.dot(W1, X) + b1
A1 = np.tanh(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)
cache = {"Z1": Z1,
"A1": A1,
"Z2": Z2,
"A2": A2}
return A2, cache
# Test forward_propagation
X_assess, parameters = forward_propagation_test_case()
A2, cache = forward_propagation(X_assess, parameters)
print(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))
# Compute the value of the cost J(w, b).
def compute_cost(A2, Y, parameters):
"""
Computes the cross-entropy cost.
Arguments:
A2 -- sigmoid output of the second activation, of shape (1, # of examples)
Y -- "true" labels vector of shape (1, # of examples)
parameters -- Python dictionary containing parameters W1, b1, W2 and b2
Returns:
cost -- cross-entropy cost
"""
m = Y.shape[1] # number of examples
# Compute the cross-entropy cost
logprobs = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2))
cost = -np.sum(logprobs) / m
cost = np.squeeze(cost) # makes sure cost is the dimension we expect.
# E.g., turns [[17]] into 17
return cost
# Test compute_cost
A2, Y_assess, parameters = compute_cost_test_case()
print("cost = " + str(compute_cost(A2, Y_assess, parameters)))
# Backward prop using the cache computed during forward propagation.
def backward_propagation(parameters, cache, X, Y):
"""
Arguments:
parameters -- Python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
X -- input data of shape (2, # of examples)
Y -- "true" labels vector of shape (1, # of examples)
Returns:
grads -- python dictionary containing gradients with respect to different parameters
"""
m = X.shape[1]
# First, retrieve W1 and W2 from the dictionary "parameters".
W1 = parameters['W1']
W2 = parameters['W2']
# Retrieve also A1 and A2 from dictionary "cache".
A1 = cache['A1']
A2 = cache['A2']
# Backward propagation: calculate dW1, db1, dW2, db2.
dZ2 = A2 - Y
dW2 = 1/m * np.dot(dZ2, A1.T)
db2 = 1/m * np.sum(dZ2, axis=1, keepdims=True)
dZ1 = np.dot(W2.T, dZ2) * (1 - np.power(A1, 2))
dW1 = 1/m * np.dot(dZ1, X.T)
db1 = 1/m * np.sum(dZ1, axis=1, keepdims=True)
grads = {"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2}
return grads
# Test backward_propagation
parameters, cache, X_assess, Y_assess = backward_propagation_test_case()
grads = backward_propagation(parameters, cache, X_assess, Y_assess)
print("dW1 = "+ str(grads["dW1"]))
print("db1 = "+ str(grads["db1"]))
print("dW2 = "+ str(grads["dW2"]))
print("db2 = "+ str(grads["db2"]))
# Update parameters using gradient descent
def update_parameters(parameters, grads, learning_rate = 1.2):
"""
Updates parameters using the gradient descent update rule.
Arguments:
parameters -- Python dictionary containing parameters
grads -- Python dictionary containing gradients
Returns:
parameters -- Python dictionary containing updated parameters
"""
# Retrieve each parameter from the dictionary "parameters"
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
# Retrieve each gradient from the dictionary "grads"
dW1 = grads['dW1']
db1 = grads['db1']
dW2 = grads['dW2']
db2 = grads['db2']
# Update rule for each parameter
W1 -= learning_rate * dW1
b1 -= learning_rate * db1
W2 -= learning_rate * dW2
b2 -= learning_rate * db2
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
# Test update_parameters
parameters, grads = update_parameters_test_case()
parameters = update_parameters(parameters, grads)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
# Create neural network model using above functions
def nn_model(X, Y, n_h, num_iterations=10000, print_cost=False):
"""
Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of hidden layer
num_iterations -- # of iterations in gradient descent loop
print_cost -- if True, print cost every 1000 iterations
Returns:
parameters -- parameters learnt by the model.
"""
np.random.seed(3)
n_x = layer_sizes(X, Y)[0]
n_y = layer_sizes(X, Y)[2]
# Initialize parameters, then retrieve W1, b1, W2, b2.
parameters = initialize_parameters(n_x, n_h, n_y)
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
# Loop (gradient descent)
for i in range(num_iterations):
# Forward propagation.
A2, cache = forward_propagation(X, parameters)
# Cost function.
cost = compute_cost(A2, Y, parameters)
# Backpropagation.
grads = backward_propagation(parameters, cache, X, Y)
# Gradient descent parameter update.
parameters = update_parameters(parameters, grads)
# Print the cost every 1000 iterations
if print_cost and i % 1000 == 0:
print("Cost after iteration %i: %f" %(i, cost))
return parameters
# Test nn_model
X_assess, Y_assess = nn_model_test_case()
parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=True)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
# Predict using nn_model
def predict(parameters, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- Python dictionary containing parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of our model (red: 0 / blue: 1)
"""
# Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.
A2, cache = forward_propagation(X, parameters)
predictions = A2 >= 0.5
return predictions
# Test predict
parameters, X_assess = predict_test_case()
predictions = predict(parameters, X_assess)
print("predictions mean = " + str(np.mean(predictions)))
# Run the model and see how it performs on a planar dataset.
# Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations=10000, print_cost=True)
# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))
# Print accuracy
predictions = predict(parameters, X)
print('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')
| true
|
cf29797e76a030296d6e52e6cf545063b6b3bf60
|
Python
|
liuhanyu200/pygame
|
/8/8-9.py
|
UTF-8
| 174
| 2.859375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# coding:utf-8
def show_magicians(magicians):
for magician in magicians:
print(magician)
show_magicians(['gekongquwu', 'kongshoutaobailang', 'dianjujinghun'])
| true
|
031ed4581c78c49b3b3552a76ab014529852c95e
|
Python
|
Bassmann/deepsecurity
|
/python/computer-status.py
|
UTF-8
| 7,268
| 2.625
| 3
|
[] |
no_license
|
import json
import os
import sys
import warnings
import deepsecurity as api
from deepsecurity.rest import ApiException
from datetime import datetime
def format_for_csv(line_item):
"""Converts a list into a string of comma-separated values, ending with a newline character.
:param line_item: The list of lists to convert to a string of comma-spearated values
:return: A string that can be saved as a CSV file.
"""
csv_line = ""
for num, item in enumerate(line_item):
csv_line += str(item)
if num != (len(line_item) - 1):
csv_line += ";"
else:
csv_line += "\n"
return csv_line
# Setup
if not sys.warnoptions:
warnings.simplefilter("ignore")
# Get the DSM URL and API key from a JSON file
property_file = os.path.dirname(os.path.abspath(__file__)) + '/../properties.json'
with open(property_file) as raw_properties:
properties = json.load(raw_properties)
secret_key = properties['secretkey']
url = properties['url']
api_version = 'v1'
# Add DSM host information to the API client configuration
configuration = api.Configuration()
configuration.host = url
configuration.api_key['api-secret-key'] = secret_key
# Initialization
# Set Any Required Values
api_instance = api.ComputersApi(api.ApiClient(configuration))
# Add AV and IPS information
expand_options = api.Expand()
expand_options.add(api.Expand.computer_status)
expand_options.add(api.Expand.security_updates)
expand_options.add(api.Expand.intrusion_prevention)
expand_options.add(api.Expand.anti_malware)
expand_options.add(api.Expand.interfaces)
expand_options.add(api.Expand.azure_arm_virtual_machine_summary)
expand = expand_options.list()
overrides = False
# Set search criteria
search_criteria = api.SearchCriteria()
search_criteria.id_value = 0
search_criteria.id_test = "greater-than"
# Create a search filter with maximum returned items
page_size = 50
search_filter = api.SearchFilter()
search_filter.max_items = page_size
search_filter.search_criteria = [search_criteria]
# Add column titles to comma-separated values string
csv = "Host Name;Displayname;DNS Name;Agent version;Platform;IP Address;Agent Status;Agent Status Message;PolicyId;GroupId;Last Communication;Last Policy Sent;Last Policy Success;Update Status;AM Module State;AM Status;AM Status Message;AM Update Status;IPS Status;IPS Status Message\n"
try:
# Perform the search and do work on the results
print("Start reading computers")
while True:
computers = api_instance.search_computers(api_version, search_filter=search_filter, expand=expand, overrides=False)
num_found = len(computers.computers)
if num_found == 0:
print("No computers found.")
break
for computer in computers.computers:
# Module information to add to the CSV string
module_info = []
module_info.append(computer.host_name)
module_info.append(computer.display_name)
if computer.azure_arm_virtual_machine_summary:
module_info.append(computer.azure_arm_virtual_machine_summary.dns_name)
else:
module_info.append("None")
module_info.append(computer.agent_version)
module_info.append(computer.platform)
ips_list = []
if computer.interfaces:
for interface in computer.interfaces.interfaces:
if type(interface.ips) is list:
ips_list.append(", ".join(interface.ips))
if computer.azure_arm_virtual_machine_summary:
ips_list.append(computer.azure_arm_virtual_machine_summary.public_ip_address)
ips_list.append(computer.azure_arm_virtual_machine_summary.private_ip_address)
module_info.append(" ".join(ips_list))
module_info.append(computer.computer_status.agent_status)
agent_status_message = ' '.join(computer.computer_status.agent_status_messages)
module_info.append(agent_status_message)
module_info.append(computer.policy_id)
module_info.append(computer.group_id)
if computer.last_agent_communication:
posix_time = int(computer.last_agent_communication)/1000
last_comm = datetime.fromtimestamp(posix_time).isoformat()
else:
last_comm = None
if computer.last_send_policy_request:
posix_time = int(computer.last_send_policy_request)/1000
last_send = datetime.fromtimestamp(posix_time).isoformat()
else:
last_send = None
if computer.last_send_policy_success:
posix_time = int(computer.last_send_policy_success)/1000
last_success = datetime.fromtimestamp(posix_time).isoformat()
else:
last_success = None
module_info.append(last_comm)
module_info.append(last_send)
module_info.append(last_success)
if computer.security_updates:
update_status = "{} ({})".format(computer.security_updates.update_status.status,computer.security_updates.update_status.status_message)
else:
update_status = "No update status available"
module_info.append(update_status)
module_info.append(computer.anti_malware.state)
# Check that the computer has a an agent status
if computer.anti_malware.module_status:
am_agent_status = computer.anti_malware.module_status.agent_status
am_agent_status_message = computer.anti_malware.module_status.agent_status_message
else:
am_agent_status = None
am_agent_status_message = None
module_info.append(am_agent_status)
module_info.append(am_agent_status_message)
update_status = []
if computer.security_updates:
for am_update in computer.security_updates.anti_malware:
update_status.append(" {} ({} {})".format(am_update.name, am_update.version, am_update.latest))
module_info.append(''.join(update_status))
if computer.intrusion_prevention.module_status:
ips_agent_status = computer.intrusion_prevention.module_status.agent_status
else:
ips_agent_status = None
module_info.append(ips_agent_status)
module_info.append(computer.intrusion_prevention.module_status.agent_status_message)
# Add the module info to the CSV string
csv += format_for_csv(module_info)
# Get the ID of the last computer in the page and return it with the
# number of computers on the page
last_id = computers.computers[-1].id
search_criteria.id_value = last_id
print("Last ID: " + str(last_id), "Computers found: " + str(num_found))
if num_found != page_size:
break
with open("../output/computers.csv", "w") as text_file:
text_file.write(csv)
except ApiException as e:
print("An exception occurred when calling ComputersApi.list_computers: %s\n" % e)
| true
|
584bc2883fc95f60403141f029fab7a1b61ace20
|
Python
|
etmitchell/MTTime
|
/MTTime.py
|
UTF-8
| 2,004
| 3.28125
| 3
|
[] |
no_license
|
from datetime import datetime
import time
import Tkinter
def DateTimeInMagic(MEDITECH):
MEDITECH = float(long(MEDITECH))
MTTime = MEDITECH
if time.daylight == 1:
#Add the difference between UTC Daylight Savings and MEDITECH time (320734800 seconds)
MTTime += 320731200
else:
#Add the difference between UTC and MEDITECH time (320734800 seconds)
MTTime += 320734800
#1068915786 = 1/13/14 17:03:06 EST
#UTC time
d = datetime.utcfromtimestamp(MTTime)
#Calculate offset based off OS time UTC to EST offset
offset = datetime.now() - datetime.utcnow()
#Add offset to UTC
return d + offset
class TimeGUI(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entryVariable = Tkinter.StringVar()
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entryVariable.set(u"Enter time here.")
button = Tkinter.Button(self,text=u"Convert",
command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w",fg="white",bg="lightblue")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Time:")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
def OnButtonClick(self):
self.labelVariable.set(DateTimeInMagic(self.entryVariable.get()))
def OnPressEnter(self,event):
self.labelVariable.set(DateTimeInMagic(self.entryVariable.get()))
if __name__ == "__main__":
app = TimeGUI(None)
app.title('MEDITECH Time')
app.mainloop()
| true
|
a92c4d44866769a62a10908e3a1aaa0ae6fdb0c8
|
Python
|
shikha735/Programs
|
/Competitive Programming/IB_Strings_Reverse_String.py
|
UTF-8
| 422
| 3.75
| 4
|
[] |
no_license
|
# https://www.interviewbit.com/problems/reverse-the-string/
'''
Given an input string, reverse the string word by word.
Example:
Given s = "the sky is blue",
return "blue is sky the".
'''
class Solution:
# @param A : string
# @return string
def reverseWords(self, A):
li = A.split()
li.reverse()
str = ""
for i in li:
str = str + i + ' '
return str[:-1]
| true
|
0c855755ae66b018c20a0d7a2b57769e63a5f89f
|
Python
|
roquesrolando/holberton-system_engineering-devops
|
/0x15-api/3-dictionary_of_list_of_dictionaries.py
|
UTF-8
| 713
| 2.6875
| 3
|
[] |
no_license
|
#!/usr/bin/python3
"""Gather data from API"""
import json
import requests
import sys
if __name__ == "__main__":
info = {}
site = 'https://jsonplaceholder.typicode.com/'
user = requests.get(site + 'users').json()
for x in user:
ID = x.get('id')
dos = requests.get(site + 'todos?userId={}'.format(ID)).json()
name = x.get('username')
form = []
for i in dos:
task = {'task': i['title'],
'completed': i['completed'],
'username': name
}
form.append(task)
info[ID] = form
with open('todo_all_employees.json', 'w') as export:
json.dump(info, export)
| true
|
1979b6d72815c967bf012d65effed314ceafdf31
|
Python
|
dm-alexi/acmp
|
/0001_0100/0031/0031.py
|
UTF-8
| 352
| 3.09375
| 3
|
[] |
no_license
|
def derange(n):
return 1 if n == 0 else 0 if n == 1 else n * derange(n - 1) + (-1)**n
def c(n, k):
a = b = 1
while n > k:
a *= n
b *= n - k
n -= 1
return a // b
with open("input.txt", "r") as f, open("output.txt", "w") as q:
n, k = map(int, f.readline().split())
q.write(str(c(n, k) * derange(n - k)))
| true
|
4a80871374293318b3ecc2737f15a675731c4bc3
|
Python
|
iamshivamgoswami/Random-DSA-Questions
|
/task scheduler.py
|
UTF-8
| 746
| 2.859375
| 3
|
[] |
no_license
|
import collections
class Solution:
def leastInterval(self, tasks: List[str], k: int) -> int:
s = "".join(tasks)
c = collections.Counter(s)
stack = sorted(c.items(), key=lambda x: x[1])
char, count = stack.pop()
lst = [[char] for i in range(count)]
while stack and stack[-1][1] == count:
char, _ = stack.pop()
for l in lst:
l.append(char)
res = "".join(c * n for c, n in stack)
for i, c in enumerate(res):
lst[i % (len(lst) - 1)].append(c)
print(lst)
Count = 0
for l in lst[:-1]:
if len(l) <= k:
print(l)
Count += k - len(l) + 1
return Count + len(s)
| true
|