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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fb913b7811ba1b57fc21c9cd687750b839767ee0 | Python | 1715439636/professional-python3 | /正则表达式/2_基本正则表达式.py | UTF-8 | 5,159 | 3.90625 | 4 | [] | no_license | """
作者:文文
主要介绍一些基本的匹配规则
python版本:python3.5
"""
import re
"""1 字符组
使用方括号并在方括号内列出所有可能的字符从而表示一个字符组,一定要注意,它仅仅匹配一个字符
[Pp]:匹配大写P或者小写p
[A-Z]:匹配大写A到大写Z中任何一个
[^0-9]:在方括号中的^是取反字符(^还可以表示字符串的开始),表示匹配除0-9之外的字符
一些快捷方式
\w: 与任意单词字符匹配,python3中基本上与几乎任何语言的任意单词匹配,python2中至于英语单词字符匹配,但无论哪个版本,都会匹配数字、下划线或者连字符
\W: 匹配\w包含字符之外的所有字符
\d: 匹配数字字符,python3中,还与其他语言的数字字符匹配,在python2中,它只匹配[0-9]
\D: 匹配\d包含字符之外的所有字符
\s: 匹配空白字符,比如空格、tab、换行等
\S: 匹配\s包含字符之外的所有字符
\b: 匹配一个长度为0的字串,它仅仅在一个单词开始或结尾处匹配,也被称为词边界字符快捷方式
\B: 匹配不在单词开始或结束位置长度为0的子字符串,简单来说,使用\B表明这里不是一个单词的结束
字符串的开始与结束
^字符指定字符串的开始
$字符指定字符串的结束
任意字符
.字符表示任何单个字符,但是它仅仅只能出现在方括号字符组以外,如果出现在方括号里面,仅表示.字符这一个字符
"""
#output:<_sre.SRE_Match object; span=(0, 6), match='Python'>
print (re.search(r'[pP]ython','Python 3'))
#output:<_sre.SRE_Match object; span=(0, 6), match='python'>
print (re.search(r'[pP]ython','python 3'))
#output:<_sre.SRE_Match object; span=(0, 4), match='gray'>
print( re.search(r'gr[ae]y','gray'))
#output :None, 因为方括号仅仅匹配一个字符
print (re.search(r'gr[ae]y','graey'))
#output:<_sre.SRE_Match object; span=(0, 1), match='x'>
print (re.search(r'[a-zA-Z]','x'))
#output:<_sre.SRE_Match object; span=(0, 1), match='A'>
print (re.search(r'[^a-z]','A'))
#output:None
print (re.search(r'[^a-z]','b'))
#output : <_sre.SRE_Match object; span=(0, 4), match='cron'>
print (re.search(r'\bcron\b','cron'))
#output : None
print (re.search(r'\bcron\b','croner'))
#output : None
print (re.search(r'cron\B','cron'))
#output : <_sre.SRE_Match object; span=(0, 4), match='cron'>
print (re.search(r'cron\B','croner'))
#output : <_sre.SRE_Match object; span=(0, 1), match='P'>
print (re.search(r'\w','Python 3'))
#output : ['P', 'y', 't', 'h', 'o', 'n', '3']
print (re.findall(r'\w','Python 3'))
#output : None
print (re.search(r'^python','This code is in python'))
#output : <_sre.SRE_Match object; span=(0, 6), match='python'>
print (re.search(r'^python','python 3'))
#output : <_sre.SRE_Match object; span=(16, 22), match='python'>
print (re.search(r'python$','This code is in python'))
#output : None
print (re.search(r'python$','python 3'))
#output : <_sre.SRE_Match object; span=(0, 6), match='python'>
print (re.search(r'p.th.n','python 3'))
"""2 可选字符
目前为止,所有我们看到的正则表达式都是在正则表达式中的字符与被搜索的字符串中的字符保持1:1的关系,
然而有时,一个字符或许是可选的,比如有多种拼写方式的单词,如color 和 colour 都表示颜色
此时可以使用?指定一个字符、字符组或其他基本单元可选,即期望该字符、字符组或其他基本单元出现0次或者1次(这是?的第一个作用,出现在一个字符、字符组或其他基本单元后面时起作用)
"""
#output : <_sre.SRE_Match object; span=(15, 20), match='honor'>
print (re.search(r'honou?r','He served with honor and distinction.'))
#output : <_sre.SRE_Match object; span=(15, 21), match='honour'>
print (re.search(r'honou?r','He served with honour and distinction.'))
"""3 重复
有时你需要同样的字符或者字符组重复出现,或者出现0次或者1次
{N} : 表示一个字符、字符组或其他基本单元重复出现N次
{M,N} : 表示一个字符、字符组或其他基本单元重复出现M-N次,最少出现M次,最多出现N次,但尽可能匹配多的字符
{M,N}? : 表示一个字符、字符组或其他基本单元重复出现M-N次,但尽可能少的匹配字符(这是?的第二个作用,出现在重复之后,使其变为惰性匹配)
{M,}: 表示一个字符、字符组或其他基本单元重复出现至少M次,但没有上限
* : 代替{0,},表示一个字符、字符组或其他基本单元重复出现0次或多次
+ : 代替{1,},表示一个字符、字符组或其他基本单元重复出现1次或多次
"""
#output : <_sre.SRE_Match object; span=(0, 8), match='867-5309'>
print (re.search(r'[\d]{3}-[\d]{4}','867-5309 / Jenny'))
#output : <_sre.SRE_Match object; span=(0, 4), match='0323'>
print (re.search(r'[\d]{3,4}','0323'))
#惰性匹配, output : <_sre.SRE_Match object; span=(0, 3), match='032'>
print (re.search(r'[\d]{3,4}?','0323'))
#<_sre.SRE_Match object; span=(0, 4), match='1600'>
print (re.search(r'[\d]+','1600 Pennsylvania Ave.'))
| true |
3cfa95b74169bd26d6a365ea55c8f5d07910dd42 | Python | DAAB97/sales_data_project | /sales_data_project.py | UTF-8 | 4,613 | 3.140625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 03:33:03 2020
@author: abderrahman
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('C:/Users/abdo/Desktop/sales_data.csv')
#cleanning data
## detect unique values in the columns
for cat in df.columns:
print(cat a, df[cat].unique())
## replacing all unknown data from gender, age and child with null
df['gender'] = df.gender.replace('U', np.NaN)
df['age'] = df.age.replace('1_Unk', np.NaN)
df['child'] = df.child.replace('U', np.NaN)
df['child'] = df.child.replace('0', np.NaN)
##calculate the null valuesin each column
df.isnull().sum()
##Returns stacked bar plot
def category_stackedbar(df, category):
return pd.DataFrame(df.groupby(category).count()['flag'] / df.groupby(category).count()['flag'].sum() * 100).rename(columns={"flag": "%"}).T.plot(kind='bar', stacked=True);
category_stackedbar(df, 'house_owner');
df['house_owner'] = df['house_owner'].fillna(df.mode()['house_owner'][0])
for cat in df.columns:
print(cat, df[cat].unique())
df.isnull().sum()
category_stackedbar(df, 'age');
## drop column
df = df.dropna(subset=['age'])
category_stackedbar(df, 'child');
df = df.drop('child', axis=1)
category_stackedbar(df, 'marriage');
## replace null values with the mode
df['marriage'] = df['marriage'].fillna(df.mode()['marriage'][0])
##drop 2 columns
df = df.dropna(subset=['gender', 'education'])
df.isnull().sum()
## change specific values in columns
df['flag'] = df['flag'].apply(lambda value: 1 if value == 'Y' else 0)
df['online'] = df['online'].apply(lambda value: 1 if value == 'Y' else 0)
df['education'] = df['education'].apply(lambda value: int(value[0]) + 1)
df['age'] = df['age'].apply(lambda value: int(value[0]) - 1)
df['mortgage'] = df['mortgage'].apply(lambda value: int(value[0]))
## change fam_income into numbers
dict_fam_income_label = {}
for i, char in enumerate(sorted(df['fam_income'].unique().tolist())):
dict_fam_income_label[char] = i + 1
df['fam_income'] = df['fam_income'].apply(lambda value: dict_fam_income_label[value])
for cat in df.columns:
print(cat, df[cat].unique())
###############################################################define the model data frame
df.columns
df_model = df[['flag', 'gender', 'education', 'house_val', 'age', 'online', 'marriage', 'occupation', 'mortgage', 'house_owner',
'region', 'fam_income']]
df_dum = pd.get_dummies(df_model)
df_dum.head()
###############################################################
from sklearn.model_selection import train_test_split
X = df_dum.drop('flag', axis = 1)
y = df_dum.flag.values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.model_selection import cross_val_score
# LinearRegression model
lm = LinearRegression()
lm.fit(X_train, y_train)
np.mean(cross_val_score(lm, X_train, y_train, scoring='neg_mean_absolute_error', cv=3))
#Lasso model
lm_l = Lasso(alpha=0.01)
np.mean(cross_val_score(lm_l, X_train, y_train, scoring='neg_mean_absolute_error', cv=3))
alpha = []
error = []
for i in range(1,100):
alpha.append(i/100)
lm_l = Lasso(alpha=i/100)
error.append(np.mean(cross_val_score(lm_l, X_train, y_train, scoring='neg_mean_absolute_error', cv=3)))
plt.plot(alpha, error)
err = tuple(zip(alpha, error))
err
# random forest
from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor(random_state=42)
rf.fit(X_train, y_train)
#np.mean(cross_val_score(rf, X_train, y_train, scoring='neg_mean_absolute_error', cv=3))
## improve the random forest model with GridSearchCV
from sklearn.model_selection import GridSearchCV
parameters = {'n_estimators':range(10, 300, 10), 'criterion': ('mse', 'mae'), 'max_features': ('auto', 'sqrt', 'log2')}
gs = GridSearchCV(rf, parameters, scoring='neg_mean_absolute_error', cv=3)
gs.fit(X_train, y_train)
gs.best_score_
########################### Productionize the model with Flask
import pickle
pickl = {'model': rf}
pickle.dump(pickl, open( 'model_file' + ".p", "wb" ))
file_name = "model_file.p"
with open(file_name, 'rb') as pickled:
data = pickle.load(pickled)
model = data['model']
# model.predict(X_test.iloc[1, :].values.reshape(1, -1))
# X_test.iloc[1, :].values
| true |
34d393f6323ad80ecb13bb9085105af16c630e79 | Python | spaceplesiosaur/marauders_map_api | /marauders_map_api/views.py | UTF-8 | 2,836 | 2.546875 | 3 | [] | no_license | from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .models import Character, Connection
def _find_connection(x):
return Character.objects.get(name=x)
@csrf_exempt
def character_index(request):
# if request.method == "POST":
# # do the post stuff here
# pass
# elif request.method == "GET":
# pass
# elif request.method == "DELETE":
# pass
# else:
# return HttpResponse(status=405)
if request.method == "GET":
character_list = Character.objects.all()
output = json.dumps([c.as_JSON() for c in character_list])
return HttpResponse(output)
if request.method == "POST":
body = json.loads(request.body)
new_character = Character.objects.create(name=body["name"])
new_allies = [Connection.objects.create(from_character=new_character, to_character=_find_connection(a), is_ally=True) for a in body["allies"]]
new_enemies = [Connection.objects.create(from_character=new_character, to_character=_find_connection(e), is_enemy=True) for e in body["enemies"]]
output = json.dumps(new_character.as_JSON())
return HttpResponse(output)
return HttpResponse(status=405)
@csrf_exempt
def single_character(request, character_id):
# try:
# chosen_character = Character.objects.get(id=character_id)
# except Character.DoesNotExist:
# return HttpResponse(status=404)
if request.method == "GET":
chosen_character = get_object_or_404(Character, id=character_id)
output = json.dumps(chosen_character.as_JSON())
return HttpResponse(output)
if request.method == "PUT":
chosen_character = get_object_or_404(Character, id=character_id)
body = json.loads(request.body)
chosen_character.name = body["name"]
# chosen_character.allies = body["allies"]
# chosen_character.enemies = body["enemies"]
chosen_character.save()
new_allies = [Connection.objects.create(from_character=chosen_character, to_character=_find_connection(a), is_ally=True) for a in body["allies"]]
new_enemies = [Connection.objects.create(from_character=chosen_character, to_character=_find_connection(e), is_enemy=True) for e in body["enemies"]]
output = json.dumps(chosen_character.as_JSON())
return HttpResponse(output)
if request.method == "DELETE":
chosen_character = get_object_or_404(Character, id=character_id)
chosen_character.delete()
return HttpResponse(status=204)
return HttpResponse(status=405)
def location_index(request):
location_list = Location.objects.all()
output = json.dumps([l.as_JSON() for l in location_list])
return HttpResponse(output)
| true |
af9781f1f4ac126ac78909c2c86caefa1e3b6c45 | Python | embassynetwork/lovinglanguagebot | /loving.py | UTF-8 | 3,797 | 3 | 3 | [] | no_license | #!/usr/bin/env python
import os, sys, time, re, datetime
from slackclient import SlackClient
# get these tokens from slack or ask someone to give them to you.
# then `export LOVING_LANGUAGE_SLACK_TOKEN='xoxb-xxxxxxxxxxxxxxxxxxxxx'`
token = os.environ.get('LOVING_LANGUAGE_SLACK_TOKEN')
bot_id = os.environ.get('LOVING_LANGUAGE_BOT_ID')
if not token:
print('No token was set. Please set the environment variable LOVING_LANGUAGE_SLACK_TOKEN')
sys.exit()
client = SlackClient(token)
class LanguageBot:
class BotMode:
def __init__(self, name, method):
self.name = name
self.enabled = False
self.method = method
def __init__(self, client=None):
self.client = client
# TODO this would ideally be a queue of some kind
self.current_event = None
# all modes are initialized to False
self.modes = {
'posessional': self.BotMode(name='posessional', method=self.posessional),
'gender': self.BotMode(name='gender', method=self.gender),
'conditional': self.BotMode(name='conditional', method=self.conditional),
'eprime': self.BotMode(name='eprime', method=self.eprime)
}
self.bot_info()
def bot_info(self):
# show some basic bot info
# bot started at xxxx
# bot name
# bot channel membership
print('Bot started at %s' % datetime.datetime.now())
def enable(self, mode):
if self.modes.get(mode, None):
self.modes[mode].enabled = True
print('Bot mode \'%s\' was enabled' % mode)
return True
else:
return False
def new_incoming(self, incoming):
print('Received event:')
print(incoming)
for event in incoming:
self.current_event = event
if event.get('type', None) and event['type'] == 'message':
message = event.get('text', None)
if message:
self.process(message)
else:
print('there was no text in the message')
else:
print('--> event was not a message')
print('')
def process(self, message):
for name, mode in self.modes.items():
if mode.enabled:
mode.method(message)
def reply(self, response):
self.client.api_call(
"chat.postMessage",
channel=self.current_event['channel'],
text=response,
thread_ts=self.current_event['ts']
)
def posessional(self, message):
print('Mode "posessional" not yet implemented')
def gender(self, message):
print('gender mode: processing message')
# this regex looks for the keywords at the beginning or end of the
# text, or after or before any non-alphanumeric characters.
gender_terms = re.compile(r'(\W|^)(guys|dude|his|her|hers|she|he)(\W|$)')
if gender_terms.search(message):
# construct responses to gendered terms here
response = "Hello! I'm the loving language bot. We are conducting an experiment in non-gendered language. This bot will periodically suggest that you consider using alternate phrasing that is less gender-specific. This is one of those times. "
self.reply(response)
def conditional(self, message):
print('Mode "conditional" not yet implemented')
def eprime(self, message):
print('Mode "eprime" not yet implemented')
if client.rtm_connect():
langbot = LanguageBot(client)
langbot.enable('gender')
while True:
incoming = client.rtm_read()
if incoming:
langbot.new_incoming(incoming)
time.sleep(1)
else:
print("Connection Failed")
| true |
bf125b7d9e169395e478f6536c9798df720e1213 | Python | Aravind-Chowdary/Final_Project | /Rnd_wrds_eval.py | UTF-8 | 152 | 2.859375 | 3 | [] | no_license | from random import randrange
f = open("rands.txt", "w+")
num=10000
i=0
while i<num:
m=randrange(0,65536)
f.write('%d \n' %m)
i +=1
f.close() | true |
42dddc6f85a18db5ff650ab0eef495340931cedf | Python | PhanTheMinhChau/baitap | /bai13-3.py | UTF-8 | 793 | 2.765625 | 3 | [] | no_license | import os, random
add = os.getcwd()
a = float(input("nhập dung lượng giới hạn(1-1024MB): "))*1024
while ((a/1024)<1) or ((a/1024)>1024):
a = float(input("yêu cầu nhập lại (1-1024MB)"))*1024
n = int(a//1000) #số file
c = int((a%1000)*1024) #dung lượng file cuối(byte)
os.mkdir("thư mục chứa file")
for i in range(n):
os.chdir(add+"\\thư mục chứa file")
f = open("file"+str(i+1), "x")
f.write(''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz ') for i in range(1024000)))
f.close()
if c!=0:
os.chdir(add+"\\thư mục chứa file")
f = open("file"+str(i+2), "x")
f.write(''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz ') for i in range(c)))
f.close()
print("kết thúc")
| true |
2f8afd3728bbf53f23c8d7d96f7444e2fd5b89bb | Python | DannyRH27/RektCode | /Mocks/JAY/mock2.py | UTF-8 | 1,771 | 3.734375 | 4 | [] | no_license | '''/*
* LRU Cache
* LRU = > least recently used
* cache. generally, the more items something can store, the slower it is to retrieve items from it
* caches for memory: L1 and L2 cache(these are managed by your operating systeM)
* memory is much faster than disk
* LRU = > cache policy. this policy determines how we insert things into the cache and when we kick old stuff out
* always insert new things in , and bump out the least recently used item in the cache
* K = > V pairs
*/
'''
'''
use a dictionary where the key will be the key, value will the order in which
could have a tuple (key, value) as my_dict[key] and value will be the order in which it is in
I always need to keep track of least recently used aka oldest, I would need to update the ordering of the rest of the items in cache.
use doubly linked list to keep track of the order of the keys
At capacity
how can we get to keys in the middle of the doubly linked list quickly
'''
[0,1,2,3,4]
from collections import OrderedDict
class LRUCache(object):
def __init__(self, capacity, source):
self.capacity = capacity
self.source = source
self.dict = OrderedDict()
def get(key):
# IF ITS IN THE CACHE< JUST GIVE IT BACK TO THE USER, reorder cache
# IF NOT, get it from source. source.get(key)
# add to cache at top if not at capacity,
# otherwise, bump out least recently used
if key in self.dict:
val = self.dict[key]
del self.dict[key]
self.dict[key] = val
return val
val = source.get(key)
self.dict[key] = val
if len(self.dict > capacity):
OrderedDict.popitem(last=True)
return val
| true |
5b0b224e6a2735abc334a7b03a7ffd6c5511d0da | Python | calebxcaleb/Rendered-Cube | /rendered_cube.py | UTF-8 | 8,556 | 3.359375 | 3 | [] | no_license | from typing import Tuple, List
import pygame as pygame
from math import sin, cos, tan, pi, inf
class Cube:
"""Class for a cube (self explanatory)
"""
origin: Tuple[float, float, float]
points: List[Tuple[float, float, float]]
segments: list
rects: list
colour: Tuple[int, int, int]
length: int
def __init__(self, origin: Tuple[float, float, float]) -> None:
"""Initialize a new cube"""
self.origin = origin
self.points = [
(1.0, 1.0, 1.0),
(1.0, 1.0, -1.0),
(-1.0, 1.0, -1.0),
(-1.0, 1.0, 1.0),
(1.0, -1.0, 1.0),
(1.0, -1.0, -1.0),
(-1.0, -1.0, -1.0),
(-1.0, -1.0, 1.0),
]
self.segments = [
[self.points[0], self.points[1]],
[self.points[1], self.points[2]],
[self.points[2], self.points[3]],
[self.points[3], self.points[0]],
[self.points[4], self.points[5]],
[self.points[5], self.points[6]],
[self.points[6], self.points[7]],
[self.points[7], self.points[4]],
[self.points[0], self.points[4]],
[self.points[1], self.points[5]],
[self.points[2], self.points[6]],
[self.points[3], self.points[7]]
]
self.rects = [
(self.points[0], self.points[1], self.points[2], self.points[3]),
(self.points[0], self.points[1], self.points[5], self.points[4]),
(self.points[0], self.points[4], self.points[7], self.points[3]),
(self.points[2], self.points[3], self.points[7], self.points[6]),
(self.points[5], self.points[4], self.points[7], self.points[6]),
(self.points[1], self.points[2], self.points[6], self.points[5]),
]
self.colour = (0, 0, 0)
self.length = 40
self.multiply_points()
def multiply_points(self) -> None:
"""Multiply the points to the initial length
"""
for i in range(0, len(self.points)):
x = self.points[i][0]
y = self.points[i][1]
z = self.points[i][2]
self.points[i] = (
x * self.length,
y * self.length,
z * self.length
)
def draw_rects(self, screen: pygame.Surface) -> None:
"""Draw the line segments for the cube
"""
index = 0
average_list = []
average_dict = {}
for rect in self.rects:
average_list.append((rect[0][2] + rect[1][2] + rect[2][2] + rect[3][2]) / 4)
average_dict[average_list[index]] = rect
index += 1
average_list.sort(reverse=True)
for i in range(0, len(average_list)):
rect = average_dict[average_list[i]]
col = int((rect[0][2] + rect[1][2] + rect[2][2] + rect[3][2]) / 4 + 80)
col = max(col, 0)
col = min(col, 255)
col = 255 - col
colour = (col, col, col)
rectangle = ((self.to_world(rect[0])), self.to_world(rect[1]),
self.to_world(rect[2]), self.to_world(rect[3]))
pygame.draw.polygon(screen, colour, rectangle, 0)
def draw_segments(self, screen: pygame.Surface) -> None:
"""Draw the line segments for the cube
"""
for segment in self.segments:
col = int(min(segment[0][2], segment[1][2]) + 80)
col = max(col, 0)
col = min(col, 255)
col = 255 - col
colour = (col, col, col)
pygame.draw.line(screen, colour, self.to_world(segment[0]), self.to_world(segment[1]), 3)
def draw_points(self, screen: pygame.Surface) -> None:
"""Draw the points for the cube
"""
for point in self.points:
col = int(point[2] + 80)
col = max(col, 0)
col = min(col, 255)
col = 255 - col
colour = (col, col, col)
pygame.draw.circle(screen, colour, self.to_world(point), 5)
def update_segments(self) -> None:
"""Update segments to match the points
"""
self.segments = [
[self.points[0], self.points[1]],
[self.points[1], self.points[2]],
[self.points[2], self.points[3]],
[self.points[3], self.points[0]],
[self.points[4], self.points[5]],
[self.points[5], self.points[6]],
[self.points[6], self.points[7]],
[self.points[7], self.points[4]],
[self.points[0], self.points[4]],
[self.points[1], self.points[5]],
[self.points[2], self.points[6]],
[self.points[3], self.points[7]]
]
def update_rects(self) -> None:
"""Update segments to match the points
"""
self.rects = [
(self.points[0], self.points[1], self.points[2], self.points[3]),
(self.points[0], self.points[1], self.points[5], self.points[4]),
(self.points[0], self.points[4], self.points[7], self.points[3]),
(self.points[2], self.points[3], self.points[7], self.points[6]),
(self.points[5], self.points[4], self.points[7], self.points[6]),
(self.points[1], self.points[2], self.points[6], self.points[5]),
]
def to_world(self, point: Tuple[float, float, float]) -> Tuple[float, float]:
"""Return 2d point given a 3d point
"""
mult = -(point[2] - 160) / 80
new_point = (point[0] * mult + self.origin[0], point[1] * mult + self.origin[1])
return new_point
def rotate_around_x(self, theta: float):
"""Rotate the cube about the z-axis"""
for i in range(0, len(self.points)):
x = self.points[i][0]
y = self.points[i][1]
z = self.points[i][2]
self.points[i] = (
x,
y * cos(theta) - z * sin(theta),
y * sin(theta) + z * cos(theta)
)
self.update_segments()
self.update_rects()
def rotate_around_y(self, theta: float):
"""Rotate the cube about the z-axis"""
for i in range(0, len(self.points)):
x = self.points[i][0]
y = self.points[i][1]
z = self.points[i][2]
self.points[i] = (
x * cos(theta) + z * sin(theta),
y,
-x * sin(theta) + z * cos(theta)
)
self.update_segments()
self.update_rects()
def rotate_around_z(self, theta: float):
"""Rotate the cube about the z-axis"""
for i in range(0, len(self.points)):
x = self.points[i][0]
y = self.points[i][1]
z = self.points[i][2]
self.points[i] = (
x * cos(theta) - y * sin(theta),
x * sin(theta) + y * cos(theta),
z
)
self.update_segments()
self.update_rects()
def initialize_screen(screen_size: tuple[int, int]) -> pygame.Surface:
"""Initialize pygame and the display window.
allowed is a list of pygame event types that should be listened for while pygame is running.
"""
pygame.display.init()
pygame.font.init()
screen = pygame.display.set_mode(screen_size)
screen.fill((0, 0, 0))
pygame.display.flip()
pygame.event.clear()
pygame.event.set_blocked(None)
pygame.event.set_allowed([pygame.QUIT])
return screen
def run_sim() -> None:
"""Run simulation of 3d cube
"""
run = True
screen_width = 800
screen_height = 800
screen = initialize_screen((screen_width, screen_height))
cube = Cube((screen_width / 2, screen_height / 2, 0))
theta = pi / 6000
while run:
screen.fill((255, 255, 255))
# cube.draw_points(screen)
# cube.draw_segments(screen)
cube.draw_rects(screen)
cube.rotate_around_x(theta)
cube.rotate_around_y(theta)
cube.rotate_around_z(theta)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
if __name__ == "__main__":
run_sim()
| true |
ba26536f1c3c9cb1bb715ed013363f1141d35822 | Python | ghollingworth/garmin-data | /sleep-data.py | UTF-8 | 1,933 | 2.78125 | 3 | [
"BSD-2-Clause"
] | permissive | import json
# This code extracts the sleep data from the list of files and writes out as a CSV file
# To get the data from Garmin's website go to:
# https://www.garmin.com/en-GB/account/datamanagement/exportdata/
# They will send you an email containing a link to a zip file containing all the information
files = ['./DI_CONNECT/DI-Connect-Wellness/2018-02-01_2018-05-12_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2018-05-12_2018-08-20_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2018-08-20_2018-11-28_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2018-11-28_2019-03-08_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2019-03-08_2019-06-16_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2019-06-16_2019-09-24_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2019-09-24_2020-01-02_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2020-01-02_2020-04-11_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2020-04-11_2020-07-20_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2020-07-20_2020-10-28_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2020-10-28_2021-02-05_113293_sleepData.json',
'./DI_CONNECT/DI-Connect-Wellness/2021-02-05_2021-05-16_113293_sleepData.json']
csv = open('out.csv','wt')
csv.write("Date, Deep, Light, REM, Awake\n")
for i in files:
with open(i) as json_file:
data = json.load(json_file)
for en in data:
try:
date = en['sleepStartTimestampGMT']
deep = en['deepSleepSeconds']
light = en['lightSleepSeconds']
rem = en['remSleepSeconds']
awake = en['awakeSleepSeconds']
csv.write('{0}, {1}, {2}, {3}, {4}\n'.format(date,deep,light,rem,awake))
except(KeyError):
pass
| true |
96f4ff5df40c6d37b6cba08cc463fd1aeb27a0f1 | Python | rajkonkret/python-szkolenie | /pon_3_ex11.py | UTF-8 | 167 | 3.765625 | 4 | [] | no_license | def number_of_divisors(n):
counter = 0
for i in range(1,n+1):
if n%i == 0:
counter+=1
return counter
print(number_of_divisors(9240))
| true |
8b7a970ffaa0f3aa786347def3779be04b20fef0 | Python | bxg167/Automatic-Music-Composition | /Training/Functional Tests/tests_File_Playback.py | UTF-8 | 1,286 | 2.640625 | 3 | [] | no_license | import pickle
import uuid
from unittest import TestCase
import os
from Training.tflstm import NeuralNetwork
CURRENT_DIRECTORY = os.path.dirname(__file__)
EXISTING_RNN_FILE = CURRENT_DIRECTORY + "test.snapshot"
class PlaybackFunctionalTests(TestCase):
nn = NeuralNetwork()
# Will be changed to the correct number when the Playback class has been implemented
DEFAULT_NUMBER_OF_TIMESLICES = 300
# Case 4.1.3a
def test_timeslices_match_default_amount(self):
new_rcff = self.nn.sample('badfile')
self.assertEquals(self.DEFAULT_NUMBER_OF_TIMESLICES, len(new_rcff.body))
# Case 4.1.3b
def test_timeslices_match_custom_amount(self):
new_rcff = self.nn.sample('badfile', 5)
self.assertEquals(5, len(new_rcff.body))
# Case 4.1.4
def test_exception_raised_with_bad_file(self):
bad_snapshot = os.path.join(CURRENT_DIRECTORY, "Text.snapshot")
# If we try to create an rcff file with a bad snapshot, an exception should be raised.
with self.assertRaises(Exception):
self.nn.load(bad_snapshot)
if __name__ == '__main__':
t = PlaybackFunctionalTests()
t.test_timeslices_match_default_amount()
t.test_timeslices_match_custom_amount()
t.test_exception_raised_with_bad_file() | true |
d2b44b28c5ad4feb5089d5f646fff23e8ba402c6 | Python | DauMinhHoa/Save-code-here | /app.py | UTF-8 | 1,226 | 2.984375 | 3 | [] | no_license | from flask import Flask, render_template
app = Flask(__name__)
class Movie:
def __init__(self, title, img):
self.title = title
self.img = img
movie1 = Movie(' The girl next door',"https://upload.wikimedia.org/wikipedia/en/f/fc/Girl_Next_Door_movie.jpg")
movie2 = Movie(' panda',"http://eva-img.24hstatic.com/upload/2-2015/images/2015-05-11/1431312531-tac-hai-cua-mat-gau.jpg")
movie_list= [movie1,
movie2,
Movie('see summer',"https://theundercutmag.files.wordpress.com/2015/08/500-days-of-summer-500-days-of-summer-11124694-2559-1706.jpg")
]
@app.route('/')
def hello_world():
return 'Hello Beep World!'
@app.route('/c4e')
def hello_c4e():
return 'Hello Hoa!'
@app.route('/<name>')
def hello(name):
return('Hello'+ ' ' +name)
@app.route('/movie')
def get_movie():
return render_template('movie.html')
@app.route('/movie2')
def get_movie2():
return render_template('movie_2.html',
title = 'Civil war',img='http://media.comicbook.com/2016/04/civil-war-cap-tony-179110.jpg')
@app.route('/movies')
def movies():
return render_template("movies.html",movie_list=movie_list)
if __name__ == '__main__':
app.run()
| true |
f2c8cb041a54fea39a27eadebac2ef7f0d947704 | Python | art-vybor/labs | /optimization/lab5/doit.py | UTF-8 | 1,247 | 3.03125 | 3 | [] | no_license | from math import sin, sqrt
from random import random, uniform, randint
from copy import deepcopy
Np = 100 #population size
F = 1 #100 # weight
CR = random() # prop of sequence
M = 1000 #2000 # max num of population
#a, b, c = 0.5, 0.5, 0.5
#a, b, c = 1.0, 0.8, 1.0
a, b, c = 2.5, 1.0, 2.0
f = lambda (x1,x2): a*x1*sin(b*sqrt(abs(x1))) + x2*sin(c*sqrt(abs(x2)))
x_min = -500
x_max = 500
def normalize(x=None):
if x < x_min or x_max < x:
return uniform(x_min, x_max)
return x
def getXc1(incorrect_index):
Xabc = set()
while not len(Xabc) == 3:
index = randint(0, len(X)-1)
if index != incorrect_index:
Xabc.add(index)
i, j, k = list(Xabc)
Xa, Xb, Xc = X[i], X[j], X[k]
return [normalize(Xc[0] + F*(Xa[0]-Xb[0])), normalize(Xc[1] + F*(Xa[1]-Xb[1]))]
def getXs(Xc1, Xt):
Xs = deepcopy(Xc1)
if random() > CR:
Xs[0] = Xt[0]
return Xs
X = [[normalize(), normalize()] for _ in range(Np)]
m = 0
for _ in range(M):
X_new = []
for j in range(Np):
Xt = X[j]
Xs = getXs(getXc1(j), Xt)
X_new.append(Xs if f(Xs) < f(Xt) else Xt)
X = X_new
print 'a = %s, b = %s, c = %s' % (a,b,c)
print 'f = %s, x = %s' % min((f(x), x) for x in X) | true |
b83a27becb305ed3d723af15ec349c2a04b7def2 | Python | MomchilAngelov/Diploma_2015 | /old_stuff/snake.py | UTF-8 | 4,386 | 2.703125 | 3 | [] | no_license | import os
import time
import random
import threading
class catchInputFromKeyboard(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(this):
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
if c == "A":
global direction
if direction == 1:
continue
else:
direction = 1
elif c=="B":
global direction
if direction == 3:
continue
else:
direction = 3
elif c=="D":
global direction
if direction == 4:
continue
else:
direction = 4
elif c=="C":
global direction
if direction == 2:
continue
else:
direction = 2
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
class playField():
def __init__(self, arg1=8, arg2=8):
self.sizeOfPlayField = [arg1,arg2]
self.playfield = []
for i in range(0,arg1):
new = []
for j in range(0,arg2):
new.append(0)
self.playfield.append(new)
def printme(self):
os.system("clear")
for k in self.playfield:
print(k)
def createApple(self, snake):
counter=1
checker = [10,10]
while checker in snake.shape or counter==1:
counter+=1
number1 = random.randint(0,self.sizeOfPlayField[0]-1)
number2 = random.randint(0,self.sizeOfPlayField[1]-1)
checker = [number1, number2]
self.applex = number1
self.appley = number2
self.putThereApple(number1,number2,2)
def putThereApple(self, x, y, value):
self.playfield[x][y] = value
def clearField(self):
arg1 = self.sizeOfPlayField[0]
arg2 = self.sizeOfPlayField[1]
self.playfield = []
for i in range(0,arg1):
new = []
for j in range(0,arg2):
new.append(0)
self.playfield.append(new)
def draw(self, snake):
self.clearField()
self.putThereApple(self.applex, self.appley, 2)
for k in snake.shape:
self.playfield[k[1]][k[0]] = 1
self.printme()
class snake():
def __init__(self):
self.shape = []
post = [0,0]
self.shape.append(post)
post = [1,0]
self.shape.append(post)
post = [2,0]
self.shape.append(post)
# 1
# 4 2
# 3
def step(self, pf):
global direction
currpost = self.shape[-1]
if direction == 1:
mylist = [currpost[0],currpost[1]-1]
if mylist in self.shape:
global play
play = 0
self.shape.append(mylist)
if pf.playfield[mylist[1]][mylist[0]] == 2:
pf.createApple(self)
pf.draw(self)
else:
del self.shape[0]
pf.draw(self)
elif direction == 2:
mylist = [currpost[0]+1,currpost[1]]
if mylist in self.shape:
global play
play = 0
self.shape.append(mylist)
if pf.playfield[mylist[1]][mylist[0]] == 2:
pf.createApple(self)
pf.draw(self)
else:
del self.shape[0]
pf.draw(self)
elif direction == 3:
mylist = [currpost[0],currpost[1]+1]
if mylist in self.shape:
global play
play = 0
self.shape.append(mylist)
if pf.playfield[mylist[1]][mylist[0]] == 2:
pf.createApple(self)
pf.draw(self)
else:
del self.shape[0]
pf.draw(self)
else:
mylist = [currpost[0]-1,currpost[1]]
if mylist in self.shape:
global play
play = 0
self.shape.append(mylist)
if pf.playfield[mylist[1]][mylist[0]] == 2:
pf.createApple(self)
pf.draw(self)
else:
del self.shape[0]
pf.draw(self)
direction = 2
play = 1
pf = playField()
snake = snake()
keyboard = catchInputFromKeyboard()
keyboard.start()
pf.createApple(snake)
pf.draw(snake)
while play:
time.sleep(0.5)
snake.step(pf)
print("You lost ;-;") | true |
f73bc313778c9ef253d0475dbc2079ac733511b2 | Python | TwistingTwists/project-ias | /backend/pyq_scrapers/scrape_prelims.py | UTF-8 | 1,281 | 2.703125 | 3 | [] | no_license | import time
import json
from selenium import webdriver
from selenium.webdriver import ActionChains
data = {}
data["prelims"] = []
baseURL = "https://www.insightsonindia.com/2021/06/06/solve-upsc-previous-years-prelims-papers-2018/"
driver = webdriver.Chrome()
driver.get(baseURL)
time.sleep(15)
questions = driver.find_elements_by_class_name('wpProQuiz_question')
responses = driver.find_elements_by_class_name('wpProQuiz_response')
total_num = len(questions)
for i in range(total_num):
ques = questions[i]
response = responses[i]
prev_q = ques.find_element_by_class_name('wpProQuiz_question_text').text
options = []
for opt in ques.find_element_by_class_name('wpProQuiz_questionList').find_elements_by_tag_name('li'):
options.append(opt.text)
right_ans = ques.find_element_by_class_name('wpProQuiz_answerCorrect').text
explanation = response.find_element_by_class_name('wpProQuiz_incorrect').get_attribute('innerHTML')
# add to json
data["prelims"].append({
'question': prev_q,
'options': options,
'answer': right_ans,
'explanation': str(explanation)
})
print('--->',right_ans)
# empty options
options = []
with open('prelims2018.json', 'w') as f:
json.dump(data, f) | true |
f592d2e76bb7a3ee8a1035623bd425fe7c0e09ce | Python | anushamokashi/prgm | /rev_num.py | UTF-8 | 172 | 3.84375 | 4 | [] | no_license | '''x=input("enter the num")
reverse=0
while (x):
reverse = reverse * 10
reverse = reverse + x% 10
x=x/10
print(reverse)'''
num=input("enter the num")
print (num[::-1]) | true |
8176cf565af279ec737b7a1f725118da1f3a263e | Python | mechatroner/RBQL | /test/test_mad_max.py | UTF-8 | 3,251 | 2.6875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import unittest
import sys
import datetime
import os
PY3 = sys.version_info[0] == 3
#This module must be both python2 and python3 compatible
script_dir = os.path.dirname(os.path.abspath(__file__))
# Use insert instead of append to make sure that we are using local rbql here.
sys.path.insert(0, os.path.join(os.path.dirname(script_dir), 'rbql-py'))
import rbql
from rbql import rbql_engine
def get_mad_max():
return rbql_engine.compile_and_run(rbql_engine.RBQLContext(None, None, None), user_namespace=None, unit_test_mode=True)[0]
def get_mad_min():
return rbql_engine.compile_and_run(rbql_engine.RBQLContext(None, None, None), user_namespace=None, unit_test_mode=True)[1]
def get_mad_sum():
return rbql_engine.compile_and_run(rbql_engine.RBQLContext(None, None, None), user_namespace=None, unit_test_mode=True)[2]
class TestMadMax(unittest.TestCase):
def test_mad_max(self):
now = datetime.datetime.now()
self.assertEqual(7, get_mad_max()(7).value)
self.assertTrue(get_mad_max()(None).value == None)
self.assertTrue(get_mad_max()(now).value == now)
self.assertTrue(get_mad_max()('hello').value == 'hello')
self.assertTrue(get_mad_max()(0.6).value == 0.6)
self.assertTrue(get_mad_max()(4, 6) == 6)
self.assertTrue(get_mad_max()(4, 8, 6) == 8)
self.assertTrue(get_mad_max()(4, 8, 6, key=lambda v: -v) == 4)
if PY3:
self.assertTrue(get_mad_max()([], default=7) == 7)
self.assertTrue(get_mad_max()(['b', 'x', 'a'], default='m') == 'x')
with self.assertRaises(TypeError) as cm:
get_mad_max()(7, key=lambda v: v)
e = cm.exception
self.assertTrue(str(e).find('object is not iterable') != -1)
def test_mad_min(self):
now = datetime.datetime.now()
self.assertTrue(get_mad_min()(7).value == 7)
self.assertTrue(get_mad_min()(None).value == None)
self.assertTrue(get_mad_min()(now).value == now)
self.assertTrue(get_mad_min()('hello').value == 'hello')
self.assertTrue(get_mad_min()(0.6).value == 0.6)
self.assertTrue(get_mad_min()(4, 6) == 4)
self.assertTrue(get_mad_min()(4, 8, 6) == 4)
self.assertTrue(get_mad_min()(4, 8, 6, key=lambda v: -v) == 8)
if PY3:
self.assertTrue(get_mad_min()([], default=7) == 7)
self.assertTrue(get_mad_min()(['b', 'x', 'a'], default='m') == 'a')
with self.assertRaises(TypeError) as cm:
get_mad_min()(7, key=lambda v: v)
e = cm.exception
self.assertTrue(str(e).find('object is not iterable') != -1)
def test_mad_sum(self):
now = datetime.datetime.now()
self.assertTrue(get_mad_sum()(7).value == 7)
self.assertTrue(get_mad_sum()(None).value == None)
self.assertTrue(get_mad_sum()(now).value == now)
self.assertTrue(get_mad_sum()([1, 2, 3]) == 6)
self.assertTrue(get_mad_sum()([1, 2, 3], 2) == 8)
self.assertTrue(get_mad_sum()('hello').value == 'hello')
with self.assertRaises(TypeError) as cm:
get_mad_sum()(7, 8)
| true |
9b29c98b5f11b0078b45b9dfcade0e8dd31efe41 | Python | julpotter/College-Projects-and-code | /Computational_Physics/bifurcationdiagram.py | UTF-8 | 429 | 2.84375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 12:15:18 2018
bifurcationdiagram.py
@author: Julian
"""
import matplotlib.pyplot as plt
import numpy as np
r = 0.96
N = 1500
x = 0.5
xlist = []
rlist = []
for r in np.arange(0.75,1,0.0005):
x = 0.25
for i in range(N):
x = 4*r*x*(1-x)
if(i>1000):
xlist.append(x)
rlist.append(r)
plt.plot(rlist,xlist,'rx')
plt.show() | true |
be2d55c5604c64059bf0f300d778455625326fb9 | Python | frankzhuo/PJ_PREDICT_IMG | /api_invoice/dao/log_dao.py | UTF-8 | 1,333 | 2.671875 | 3 | [] | no_license | # -*-encoding:utf-8-*-
import api_invoice.config.db as db_config
table_name = "pe_log"
class PeLog:
def __init__(self, dict_row=None):
if dict_row:
self.id = dict_row.get("id")
self.created = dict_row.get("created")
self.modified = dict_row.get("modified")
self.content = dict_row.get("content")
self.type = dict_row.get("type")
self.level = dict_row.get("level")
self.data_id = dict_row.get("fk_data_id")
else:
self.id = None
self.created = None
self.modified = None
def insert(log):
sql = "INSERT INTO "+table_name+" (content,type,level,fk_data_id) VALUES (%s,%s,%s,%s)"
#print(sql)
db = db_config.get_db()
result =db.execute(sql, log.content, log.type, log.level,log.data_id)
return result
#机器识别处理来的数据
def info(content,type,data_id):
log(content,type,data_id,"INFO")
#未识别出来的数据
def error(content,type,data_id,):
log(content,type,data_id,"ERROR")
#不是用机器识别出来的数据
def warn(content,type,data_id):
log(content,type,data_id,"ERROR")
def log(content,type,data_id,level):
log = PeLog()
log.level=level
log.content=content
log.type=type
log.data_id=data_id
insert(log)
| true |
9b3ccc49c1eca939cc1d24b56cbecf91c03a4e57 | Python | xavierloos/python3-course | /Intermediate/Namespaces & Scope/global_scope.py | UTF-8 | 967 | 4.25 | 4 | [] | no_license | # 1.Take a look at the two functions defined. One function named print_avaliable() prints the number of gallons we have available for a specific color. The other function named print_all_colors_avaliable() simply prints all available colors!
# Ponder what might happen when we run the script and then run it to find out!
# 2.Whoops! Looks like we have an error with accessing paint_gallons_avaliable in our print_all_colors_avaliable() function. This is because the dictionary is locally scoped.
# Fix the issue by moving paint_gallons_avaliable into the global scope.
paint_gallons_avaliable = {
'red': 50,
'blue': 72,
'green': 99,
'yellow': 33
}
def print_avaliable(color):
print('There are ' +
str(paint_gallons_avaliable[color]) + ' gallons avaliable of ' + color + ' paint.')
def print_all_colors_avaliable():
for color in paint_gallons_avaliable:
print(color)
print_avaliable('red')
print_all_colors_avaliable()
| true |
b331263c6c06e7fc05200217c2c0c7493cfc400f | Python | Shikhar0907/Online-Quiz | /Handy_project/Test/api_test.py | UTF-8 | 993 | 2.609375 | 3 | [] | no_license | import requests
import pprint
import unittest
class test_api(unittest.TestCase):
def GetAPI_test(self):
URL = "http://localhost:8000/admin/search"
self.re = requests.get(URL)
data = self.re.json()
self.assertEqual(self.re.status_code,200)
def PostAPI_test(self):
URL = "http://localhost:8000/admin/create"
data = {'category':'mat','questions':'ques','choice1':1,'choice2':2,'choice3':3,'choice4':4,'answers':3}
self.re = requests.post(URL,data = data)
self.assertEqual(self.re.status_code,201)
def PutAPI_test(self):
URL = "http://localhost:8000/admin/18/update/"
data = {'category':'zat','questions':'ques','choice1':1,'choice2':2,'choice3':3,'choice4':4,'answers':3}
self.re = requests.put(URL,data=data)
self.assertEqual(self.re.status_code,200)
#test_api().GetAPI_test()
#test_api().PostAPI_test()
#test_api().PutAPI_test()
if __name__ == '__main__':
unittest.main()
| true |
305b269491b37b45e46d1c5a113795e5f0ca9496 | Python | NeoGlanding/python-masterclass | /02-program-flow/augmented-assignment.py | UTF-8 | 93 | 3.03125 | 3 | [] | no_license | number = 5
multiply = 8
answer = 0
for i in range(1, 9):
answer += number
print(answer) | true |
b292252b3143d8671a5a29de669a85861760248a | Python | panda3d/panda3d-docs | /programming/pandai/pathfinding/uneven-terrain.py | UTF-8 | 13,836 | 2.546875 | 3 | [] | no_license | # PandAI Author: Srinavin Nair
# Original Author: Ryan Myers
# Models: Jeff Styers, Reagan Heller
# Last Updated: 6/13/2005
#
# This tutorial provides an example of creating a character and having it walk
# around on uneven terrain, as well as implementing a fully rotatable camera.
# It uses PandAI pathfinding to move the character.
from direct.showbase.ShowBase import ShowBase
from panda3d.core import CollisionTraverser, CollisionNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
from panda3d.core import Filename
from panda3d.core import PandaNode, NodePath, TextNode
from panda3d.core import Vec3, BitMask32
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
from direct.task.Task import Task
from direct.showbase.DirectObject import DirectObject
import sys
import os
from panda3d.ai import *
base = ShowBase()
SPEED = 0.5
# Figure out what directory this program is in.
MYDIR = os.path.abspath(sys.path[0])
MYDIR = Filename.fromOsSpecific(MYDIR).getFullpath()
font = loader.loadFont("cmss12")
# Function to put instructions on the screen.
def addInstructions(pos, msg):
return OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), font=font,
pos=(-1.3, pos), align=TextNode.ALeft, scale=.05)
# Function to put title on the screen.
def addTitle(text):
return OnscreenText(text=text, style=1, fg=(1, 1, 1, 1), font=font,
pos=(1.3, -0.95), align=TextNode.ARight, scale=.07)
class World(DirectObject):
def __init__(self):
self.switchState = True
self.switchCam = False
self.path_no = 1
self.keyMap = {
"left": 0,
"right": 0,
"forward": 0,
"cam-left": 0,
"cam-right": 0
}
base.win.setClearColor((0, 0, 0, 1))
base.cam.setPosHpr(17.79, -87.64, 90.16, 38.66, 325.36, 0)
# Post the instructions
addTitle("Pandai Tutorial: Roaming Ralph (Walking on Uneven Terrain) "
"working with pathfinding")
addInstructions(0.95, "[ESC]: Quit")
addInstructions(0.90, "[Space - do Only once]: Start Pathfinding")
addInstructions(0.85, "[Enter]: Change camera view")
addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
addInstructions(0.70, "[A]: Rotate Camera Left")
addInstructions(0.65, "[S]: Rotate Camera Right")
# Set up the environment
#
# This environment model contains collision meshes. If you look
# in the egg file, you will see the following:
#
# <Collide> { Polyset keep descend }
#
# This tag causes the following mesh to be converted to a collision
# mesh -- a mesh which is optimized for collision, not rendering.
# It also keeps the original mesh, so there are now two copies ---
# one optimized for rendering, one for collisions.
self.environ = loader.loadModel("models/world")
self.environ.reparentTo(render)
self.environ.setPos(12, 0, 0)
self.box = loader.loadModel("models/box")
self.box.reparentTo(render)
self.box.setPos(-29.83, 0, 0)
self.box.setScale(1)
self.box1 = loader.loadModel("models/box")
self.box1.reparentTo(render)
self.box1.setPos(-51.14, -17.90, 0)
self.box1.setScale(1)
# Create the main character, Ralph
#ralphStartPos = self.environ.find("**/start_point").getPos()
ralphStartPos = Vec3(-98.64, -20.60, 0)
self.ralph = Actor("models/ralph",
{"run": "models/ralph-run",
"walk": "models/ralph-walk"})
self.ralph.reparentTo(render)
self.ralph.setScale(1)
self.ralph.setPos(ralphStartPos)
self.ralphai = Actor("models/ralph",
{"run": "models/ralph-run",
"walk": "models/ralph-walk"})
self.pointer = loader.loadModel("models/arrow")
self.pointer.setColor(1, 0, 0)
self.pointer.setPos(-7.5, -1.2, 0)
self.pointer.setScale(3)
self.pointer.reparentTo(render)
self.pointer1 = loader.loadModel("models/arrow")
self.pointer1.setColor(1, 0, 0)
self.pointer1.setPos(-98.64, -20.60, 0)
self.pointer1.setScale(3)
#self.pointer.reparentTo(render)
# Create a floater object. We use the "floater" as a temporary
# variable in a variety of calculations.
self.floater = NodePath(PandaNode("floater"))
self.floater.reparentTo(render)
# Accept the control keys for movement and rotation
self.accept("escape", sys.exit)
self.accept("enter", self.activateCam)
self.accept("arrow_left", self.setKey, ["left", 1])
self.accept("arrow_right", self.setKey, ["right", 1])
self.accept("arrow_up", self.setKey, ["forward", 1])
self.accept("a", self.setKey, ["cam-left", 1])
self.accept("s", self.setKey, ["cam-right", 1])
self.accept("arrow_left-up", self.setKey, ["left", 0])
self.accept("arrow_right-up", self.setKey, ["right", 0])
self.accept("arrow_up-up", self.setKey, ["forward", 0])
self.accept("a-up", self.setKey, ["cam-left", 0])
self.accept("s-up", self.setKey, ["cam-right", 0])
#taskMgr.add(self.move,"moveTask")
# Game state variables
self.isMoving = False
# Set up the camera
#base.disableMouse()
#base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)
# We will detect the height of the terrain by creating a collision
# ray and casting it downward toward the terrain. One ray will
# start above ralph's head, and the other will start above the camera.
# A ray may hit the terrain, or it may hit a rock or a tree. If it
# hits the terrain, we can detect the height. If it hits anything
# else, we rule that the move is illegal.
self.cTrav = CollisionTraverser()
self.ralphGroundRay = CollisionRay()
self.ralphGroundRay.setOrigin(0, 0, 1000)
self.ralphGroundRay.setDirection(0, 0, -1)
self.ralphGroundCol = CollisionNode('ralphRay')
self.ralphGroundCol.addSolid(self.ralphGroundRay)
self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
self.ralphGroundHandler = CollisionHandlerQueue()
self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
self.camGroundRay = CollisionRay()
self.camGroundRay.setOrigin(0, 0, 1000)
self.camGroundRay.setDirection(0, 0, -1)
self.camGroundCol = CollisionNode('camRay')
self.camGroundCol.addSolid(self.camGroundRay)
self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
self.camGroundHandler = CollisionHandlerQueue()
self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
# Uncomment this line to see the collision rays
#self.ralphGroundColNp.show()
#self.camGroundColNp.show()
#Uncomment this line to show a visual representation of the
#collisions occuring
#self.cTrav.showCollisions(render)
self.setAI()
def activateCam(self):
self.switchCam = not self.switchCam
if self.switchCam is True:
base.cam.setPosHpr(0, 0, 0, 0, 0, 0)
base.cam.reparentTo(self.ralph)
base.cam.setY(base.cam.getY() + 30)
base.cam.setZ(base.cam.getZ() + 10)
base.cam.setHpr(180, -15, 0)
else:
base.cam.reparentTo(render)
base.cam.setPosHpr(17.79, -87.64, 90.16, 38.66, 325.36, 0)
#base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
# Records the state of the arrow keys
def setKey(self, key, value):
self.keyMap[key] = value
# Accepts arrow keys to move either the player or the menu cursor,
# Also deals with grid checking and collision detection
def move(self):
# Get the time elapsed since last frame. We need this
# for framerate-independent movement.
elapsed = globalClock.getDt()
# If the camera-left key is pressed, move camera left.
# If the camera-right key is pressed, move camera right.
if self.switchState is False:
base.camera.lookAt(self.ralph)
if self.keyMap["cam-left"] != 0:
base.camera.setX(base.camera, -(elapsed * 20))
if self.keyMap["cam-right"] != 0:
base.camera.setX(base.camera, +(elapsed * 20))
# save ralph's initial position so that we can restore it,
# in case he falls off the map or runs into something.
startpos = self.ralph.getPos()
# If a move-key is pressed, move ralph in the specified direction.
if self.keyMap["left"] != 0:
self.ralph.setH(self.ralph.getH() + elapsed * 300)
if self.keyMap["right"] != 0:
self.ralph.setH(self.ralph.getH() - elapsed * 300)
if self.keyMap["forward"] != 0:
self.ralph.setY(self.ralph, -(elapsed * 25))
# If ralph is moving, loop the run animation.
# If he is standing still, stop the animation.
if self.keyMap["forward"] != 0 or self.keyMap["left"] != 0 or self.keyMap["right"] != 0:
if self.isMoving is False:
self.ralph.loop("run")
self.isMoving = True
else:
if self.isMoving:
self.ralph.stop()
self.ralph.pose("walk", 5)
self.isMoving = False
# If the camera is too far from ralph, move it closer.
# If the camera is too close to ralph, move it farther.
if self.switchState is False:
camvec = self.ralph.getPos() - base.camera.getPos()
camvec.setZ(0)
camdist = camvec.length()
camvec.normalize()
if camdist > 10.0:
base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10))
camdist = 10.0
if camdist < 5.0:
base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist))
camdist = 5.0
# Now check for collisions.
self.cTrav.traverse(render)
# Adjust ralph's Z coordinate. If ralph's ray hit terrain,
# update his Z. If it hit anything else, or didn't hit anything, put
# him back where he was last frame.
#print(self.ralphGroundHandler.getNumEntries())
entries = []
for i in range(self.ralphGroundHandler.getNumEntries()):
entry = self.ralphGroundHandler.getEntry(i)
entries.append(entry)
entries.sort(lambda x, y: cmp(y.getSurfacePoint(render).z,
x.getSurfacePoint(render).z))
if entries and entries[0].getIntoNode().getName() == "terrain":
self.ralph.setZ(entries[0].getSurfacePoint(render).z)
else:
self.ralph.setPos(startpos)
# Keep the camera at one foot above the terrain,
# or two feet above ralph, whichever is greater.
if self.switchState is False:
entries = []
for i in range(self.camGroundHandler.getNumEntries()):
entry = self.camGroundHandler.getEntry(i)
entries.append(entry)
entries.sort(lambda x, y: cmp(y.getSurfacePoint(render).z,
x.getSurfacePoint(render).z))
if entries and entries[0].getIntoNode().getName() == "terrain":
base.camera.setZ(entries[0].getSurfacePoint(render).z + 1.0)
if base.camera.getZ() < self.ralph.getZ() + 2.0:
base.camera.setZ(self.ralph.getZ() + 2.0)
# The camera should look in ralph's direction,
# but it should also try to stay horizontal, so look at
# a floater which hovers above ralph's head.
self.floater.setPos(self.ralph.getPos())
self.floater.setZ(self.ralph.getZ() + 2.0)
base.camera.setZ(base.camera.getZ())
base.camera.lookAt(self.floater)
self.ralph.setP(0)
return Task.cont
def setAI(self):
# Creating AI World
self.AIworld = AIWorld(render)
self.accept("space", self.setMove)
self.AIchar = AICharacter("ralph", self.ralph, 60, 0.05, 25)
self.AIworld.addAiChar(self.AIchar)
self.AIbehaviors = self.AIchar.getAiBehaviors()
self.AIbehaviors.initPathFind("models/navmesh.csv")
# AI World update
taskMgr.add(self.AIUpdate, "AIUpdate")
def setMove(self):
self.AIbehaviors.addStaticObstacle(self.box)
self.AIbehaviors.addStaticObstacle(self.box1)
self.AIbehaviors.pathFindTo(self.pointer)
self.ralph.loop("run")
# To update the AIWorld
def AIUpdate(self, task):
self.AIworld.update()
self.move()
if self.path_no == 1 and self.AIbehaviors.behaviorStatus("pathfollow") == "done":
self.path_no = 2
self.AIbehaviors.pathFindTo(self.pointer1, "addPath")
print("inside")
if self.path_no == 2 and self.AIbehaviors.behaviorStatus("pathfollow") == "done":
print("inside2")
self.path_no = 1
self.AIbehaviors.pathFindTo(self.pointer, "addPath")
return Task.cont
w = World()
base.run()
| true |
899f53dcea9befa0dea798fa7a9cb9b207f3832f | Python | jonathan-lai-the-science-guy/tdi-capstone-taxidata-analysis | /Scripts/griddifyNYCStreets.py | UTF-8 | 2,131 | 2.9375 | 3 | [] | no_license | import sys
sys.path.append('../Custom_Libraries')
# Initialize gridding object
import GridLib
gridObj = GridLib.BaseGrid(resolution=33)
# Initialize grid of variables
import numpy as np
X,Y = gridObj.getGridIndex()
minX,maxX = 0,len(X)-1
minY,maxY = 0,len(Y)-1
gridMap = np.zeros((len(X),len(Y))).astype(int)
shapeMap = np.zeros((len(X),len(Y))).astype(int)
# Define helper function to populate a map
def graph_processor(graph,i):
assert(isinstance(i,int))
nodes = graph.nodes(data=True)
edges = graph.edges(data=True)
addVar = 2**i
for ii in edges:
N1 = nodes[ii[0]]
N2 = nodes[ii[1]]
N1x,N1y = gridObj.griddify(N1['x'],N1['y'])
N2x,N2y = gridObj.griddify(N2['x'],N2['y'])
gX = np.linspace(N1x,N2x,1000).astype(int)
gY = np.linspace(N1y,N2y,1000).astype(int)
gY[np.where(gY > (maxY - 7))] = (maxY - 7)
gX[np.where(gX > (maxX - 7))] = (maxX - 7)
gY[np.where(gY < 7)] = 7
gX[np.where(gX < 7)] = 7
gridMap[gX,gY] = addVar
shapeMap[gX,gY] = addVar
for j in range(7):
shapeMap[gX+j,gY] = addVar
shapeMap[gX-j,gY] = addVar
shapeMap[gX,gY+j] = addVar
shapeMap[gX,gY-j] = addVar
import osmnx as ox
for i,boro in enumerate(['Manhattan County, New York',\
'Kings County, New York',\
'Queens County, New York',\
'Bronx County, New York',\
'Richmond County, New York',\
'Nassau County, New York',\
'Bergen County, New Jersey',\
'Hudson County, New Jersey',\
'Essex County, New Jersey',\
'Union County, New Jersey',\
'Passaic County, New Jersey'
]):
print('Processing:',i,boro)
graph = ox.graph_from_place('{:s}, USA'.format(boro), network_type='drive')
graph_processor(graph,i)
np.save('../Data/StreetMap.npy',gridMap)
np.save('../Data/BoroMap.npy',shapeMap)
| true |
9c2a39250dd8dd89c2eb66fb9972c0bbdb977f9f | Python | mrostomgharbi/Reinforcement-learning | /Connect4 game/Connect4/games/gamestate.py | UTF-8 | 5,556 | 3.53125 | 4 | [] | no_license | import copy
from games.board import Board
import os
class GameState:
"""
This class is developed to hold the intermediate data of the Game.
"""
def __init__(self, metadata, ai):
self._metadata = metadata
self._ai = ai
self._board = Board()
self.players_turn = self._metadata.player_goes_first
self._incoming_move = None
self._move_that_derived_this_state = None
self.winner = None
def __str__(self):
s = "State: "
for key, val in self.__dict__.items():
s += os.linesep + " " + key + ": " + str(val)
return s
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == "_ai":
setattr(result, k, v)
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def current_player_symbol(self):
"""
This function is developped to get the current player's symbol
"""
if self.players_turn:
return self._metadata.players_symbol
else:
return self._metadata.ai_symbol
def game_over(self):
"""
Output of this function is boolean.
It returns True if the game is over, False if it is not.
"""
there_is_a_winner, winner = self._board.four_in_a_row()
self.winner = winner
if len(self.possible_moves()) == 0:
there_is_a_winner = True
self.winner = ' '
return there_is_a_winner
def get_formatted_display(self):
"""
This function return the current state of the game after that the moves are done,
and so the player can see it.
"""
return str(self._board)
def get_next_input_request_str(self):
"""
Requests the column number from the player.
"""
return "Type column number : "
def get_winner(self):
"""
Returns the winner of the game or None if there is a draw.
"""
return self.winner
def info_valid(self, info):
"""
This function returns True if the players mouvement is valid.
Otherwise it displays a message.
"""
try:
item = int(info)
if not self._board.valid_move(item):
return False, "Please enter a valid column between 0 and 6 "\
"that isn't full."
else:
return True, ""
except ValueError:
return False, "Please enter a valid column between 0 and 6."
def needs_more_player_input(self):
"""
Returns True if the GameState object does not have enough
player input to decide an action for the player.
"""
return self._incoming_move is None
def possible_moves(self):
"""
This function returns a set of all possible legal actions.
"""
return [move for move in self._action_set() if self._board.valid_move(move)]
def set_next_input(self, info):
"""
This function puts into action the players move request only and only if its valid.
"""
assert(self.info_valid(info))
self._incoming_move = int(info)
def take_ai_turn(self):
"""
Now, it's time for the computer to play.
"""
move = self._ai.get_best_move(self, _evaluation_function)
self._board.place(move, self._metadata.ai_symbol)
self._move_that_derived_this_state = move
print('--------------------------------------------------------')
print('\n')
print('\n')
print('\nThe robot played its mark in column number : ', move)
self._incoming_move = None
self.players_turn = True
def take_turn(self, move):
"""
This function can be used to take a turn when the caller does
not know whose turn it is or does not want to worry about it.
"""
if self.players_turn:
self._board.place(move, self._metadata.player_symbol)
self.players_turn = False
else:
self._board.place(move, self._metadata.ai_symbol)
self.players_turn = True
self._move_that_derived_this_state = move
self._incoming_move = None
def take_player_turn(self):
"""
Takes the player's turn.
"""
move = self._incoming_move
self._board.place(move, self._metadata.player_symbol)
self._move_that_derived_this_state = move
self._incoming_move = None
self.players_turn = False
def _action_set(self):
"""
This function generates all possible 6 actions that the computer can play.
It does not care wether the action is valid or not.
"""
for c in range(7):
yield c
def _evaluation_function(state):
"""
This is the reward function.
If we ever make the last reward on this function lower, it will be harder to beat the computer.
"""
reward = 0
if state._metadata.ai_symbol == 'x' and state.winner == 'x':
reward = 1.0
elif state._metadata.ai_symbol == 'o' and state.winner == 'o':
reward = 1.0
elif state._metadata.ai_symbol == 'x' and state.winner == 'o':
reward = 0.0
elif state._metadata.ai_symbol == 'o' and state.winner == 'x':
reward = 0.0
else:
reward = 0.1
return reward
| true |
0f1cb667defb54400a71f2f5842555c8a31db51b | Python | tf-czu/gyrorad | /serial/reader.py | UTF-8 | 560 | 2.75 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
"""
Read serial COM port
usage:
./reader.py <com> <speed>
"""
import sys
import serial
import datetime
def reader( com ):
dt = datetime.datetime.now()
filename = "g" + dt.strftime("%y%m%d_%H%M%S.log")
f = open( filename, "wb" )
while True:
f.write( com.read(100) )
f.flush()
sys.stderr.write('.')
if __name__ == "__main__":
if len(sys.argv) < 3:
print __doc__
sys.exit(2)
reader( com = serial.Serial( sys.argv[1], int(sys.argv[2]) ) )
# vim: expandtab sw=4 ts=4
| true |
be645162f372f490b4550f373f0df6372f2ea338 | Python | hyteer/testing | /Python/Test/Web/reqPost.py | UTF-8 | 390 | 2.71875 | 3 | [] | no_license | # encoding: utf-8
str = '\u9a8c\u8bc1\u7801\u53d1\u9001\u6210\u529f\uff0c\u8bf7\u6ce8\u610f\u67e5\u6536'
str1 = bytes(b'\x31\x32\x61\x62').decode('ascii')
str2 = bytes(b'\x31\x32\x61\x62').decode('ascii')
str3 = bytes(b'\u9a8c\u8bc1\u7801\u53d1\u9001\u6210\u529f\uff0c\u8bf7\u6ce8\u610f\u67e5\u6536').decode('utf8')
print ord(u'\u9a8c')
ustr = str.encode('utf8',str)
print str3
print ustr
| true |
c9d2755ac0d235f268ec6f98a4d786cdc5247e91 | Python | thakureie/Python | /re_loop_compile.py | UTF-8 | 396 | 2.8125 | 3 | [] | no_license | #!/usr/bin/python
import re
def run_re():
pattern = "pDq"
re_obj = re.complie(pattern)
infile = open('large_re_file.txt', 'r')
match_count = 0
lines = 0
for line in infile:
match = re_obj
if match:
match_count += 1
lines += 1
retrun(lines, match_count)
if _name_ == "_main_":
lines, match_count = run_re()
print ('LINES::', lines)
print ('MATCHES::', match_count)
| true |
cd44a28b4aec2f269c158b46b979aa447e2da391 | Python | kskrueger/CS574 | /src/load.py | UTF-8 | 2,658 | 2.90625 | 3 | [] | no_license | import csv
import numpy as np
import datetime
def read_csv(path):
with open(path, 'r') as f:
csv_file = csv.reader(f)
lines = [line for line in csv_file]
return lines[1:] # exclude the headers
def process_orders(dataset):
orders_dict = {}
for order in dataset:
order_num, time, item = order
time_split = time.split("-")
time = "-".join(reversed(time_split))
if order_num in orders_dict:
if time in orders_dict[order_num]:
orders_dict[order_num][time].append(item)
else:
orders_dict[order_num][time] = [item]
else:
orders_dict[order_num] = {}
orders_dict[order_num][time] = [item]
return orders_dict
def process_daily(dataset):
daily_dict = {}
for order in dataset:
order_num, time, item = order
time_split = time.split("-")
time = "-".join(reversed(time_split))
if time in daily_dict:
if order_num in daily_dict[time]:
daily_dict[time][order_num].append(item)
else:
daily_dict[time][order_num] = [item]
else:
daily_dict[time] = {}
daily_dict[time][order_num] = [item]
return daily_dict
def process_daily_items(dataset):
daily_item_dict = {}
foods_list = set()
for order in dataset:
order_num, time, item = order
time_split = time.split("-")
time = "-".join(reversed(time_split))
if time in daily_item_dict:
if order_num in daily_item_dict[time]:
if item in daily_item_dict[time][order_num]:
daily_item_dict[time][order_num][item] += 1
else:
daily_item_dict[time][order_num][item] = 1
else:
daily_item_dict[time][order_num] = {}
daily_item_dict[time][order_num][item] = 1
else:
daily_item_dict[time] = {}
daily_item_dict[time][order_num] = {}
daily_item_dict[time][order_num][item] = 1
foods_list.add(item)
food_encodings = dict([(k, v) for v, k in enumerate(foods_list)])
days_list = sorted(daily_item_dict.keys())
day_encodings = dict([(k, v) for v, k in enumerate(days_list)])
day_item_sales = np.zeros((len(daily_item_dict.keys()), len(food_encodings)), dtype=int)
for k, v in daily_item_dict.items():
for order in v.values():
for i, val in order.items():
day_item_sales[day_encodings[k]][food_encodings[i]] += val
return day_item_sales, day_encodings, food_encodings
| true |
fdd49b4319eb4dde8f4306203b654093c8c9b65b | Python | jacksonwb/npuzzle | /src/check_solvable.py | UTF-8 | 1,334 | 2.828125 | 3 | [] | no_license | #! /usr/bin/env python3
# ---------------------------------------------------------------------------- #
# check_solvable.py #
# #
# By - jacksonwb #
# Created: Wednesday December 1969 4:00:00 pm #
# Modified: Saturday Aug 2019 1:04:04 pm #
# Modified By: jacksonwb #
# ---------------------------------------------------------------------------- #
def is_solvable(n, n_map, goal):
start = []
for row in n_map:
start += list(row)
finish = []
for row in goal:
finish += list(row)
inversion = 0
for i in range(n * n):
for j in range(i + 1, n * n):
if finish.index(start[i]) > finish.index(start[j]):
inversion += 1
start_zero_row = start.index(0) // n
start_zero_col = start.index(0) % n
finish_zero_row = finish.index(0) // n
finish_zero_col = finish.index(0) % n
zero_dif = abs(start_zero_row - finish_zero_row) + abs(start_zero_col - finish_zero_col)
if zero_dif % 2 == 0 and inversion % 2 == 0:
return True
if zero_dif % 2 == 1 and inversion % 2 == 1:
return True
return False
| true |
95bc28a3f745665b6498b0b0d330c003cda50c9f | Python | MarcoCompagnoni/python | /prove_iniziali/linear_regression_excel.py | UTF-8 | 1,934 | 2.671875 | 3 | [] | no_license | import pandas as pd
import numpy as np
from scipy import stats
import locale
locale.setlocale(locale.LC_ALL, '')
frames=[]
def main():
monitoraggio_vibrazioni = pd.read_excel('monitoraggio_vibrazioni_2.xlsx')
headers = list(monitoraggio_vibrazioni.columns.values)
for i in range(1, len(headers)):
machine = headers[i]
monitoraggio_vibrazioni.Time = pd.to_datetime(monitoraggio_vibrazioni.Time, format="%d-%b-%y %H:%M")
monitoraggio_vibrazioni['days_since'] = (monitoraggio_vibrazioni.Time - pd.to_datetime('2006-07-31 00:00') ).astype('timedelta64[D]')
monitoraggio_vibrazioni[machine] = pd.to_numeric(monitoraggio_vibrazioni[machine].str.replace(',','.'))
monitoraggio_vibrazioni['soglia'] = np.mean(monitoraggio_vibrazioni[machine])
slope, intercept, r_value, p_value, std_err = stats.linregress(monitoraggio_vibrazioni['days_since'],
monitoraggio_vibrazioni[machine])
monitoraggio_vibrazioni['trend'] = slope * monitoraggio_vibrazioni['days_since'] + intercept
data_frame = pd.DataFrame({'time': monitoraggio_vibrazioni['Time'],
'machine':machine,
'value': monitoraggio_vibrazioni[machine],
'trend': monitoraggio_vibrazioni['trend'],
'soglia': monitoraggio_vibrazioni['soglia'],
'coef': slope,
'p_value': p_value
})
frames.append(data_frame)
result = pd.concat(frames)
result.index = np.arange(0,len(result))
writer = pd.ExcelWriter('C:/users/marco.compagnoni/Desktop/Monitoraggio Apparecchiature/output.xlsx')
result.to_excel(writer,'Sheet1')
writer.save()
if __name__ == '__main__':
main()
| true |
5399b780f04e080d7fc4a65c84029c8ee6683bd9 | Python | microsoft/pgtoolsservice | /tests/integration/integration_tests.py | UTF-8 | 7,327 | 2.6875 | 3 | [
"MIT"
] | permissive | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
"""Module containing the logic to set up integration tests with a database connection"""
import functools
import json
import os
from typing import List
import uuid
import psycopg
def integration_test(min_version=None, max_version=None):
"""
Decorator used to indicate that a test is an integration test, giving it a connection
:param min_version: The minimum server version, as an integer, for running the test (e.g. 90600 for 9.6.0)
:param max_version: The maximum server version, as an integer, for running the test (e.g. 90600 for 9.6.0)
"""
# If the decorator is called without parentheses, the first argument will actually be the test function
test_function = None
if callable(min_version):
test_function = min_version
min_version = None
def integration_test_internal(test):
@functools.wraps(test)
def new_test(*args):
_ConnectionManager.current_test_is_integration_test = True
try:
_ConnectionManager.run_test(test, min_version, max_version, *args)
finally:
_ConnectionManager.current_test_is_integration_test = False
_ConnectionManager.drop_test_databases()
new_test.is_integration_test = True
new_test.__name__ = test.__name__
return new_test
return integration_test_internal if test_function is None else integration_test_internal(test_function)
def get_connection_details() -> dict:
"""
Get connection details that can be used in integration tests. These details are formatted as a
dictionary of key-value pairs that can be passed directly to psycopg.connect as parameters.
"""
return _ConnectionManager.get_test_connection_details()
def create_extra_test_database() -> str:
"""
Create an extra database for the current test and return its name. The database will
automatically be dropped at the end of the test.
"""
return _ConnectionManager.create_extra_database()
# Indicate that nose should not treat these functions as their own tests
integration_test.__test__ = False
create_extra_test_database.__test__ = False
class _ConnectionManager:
current_test_is_integration_test: bool = False
_maintenance_connections: List[psycopg.Connection] = []
_current_test_connection_detail_list: List[dict] = None
_in_progress_test_index: int = None
_extra_databases: List[str] = []
@classmethod
def get_test_connection_details(cls):
if not cls.current_test_is_integration_test or cls._in_progress_test_index is None:
raise RuntimeError('get_connection_details can only be called from tests with an integration_test decorator')
# Return a copy of the test connection details dictionary
return dict(cls._current_test_connection_detail_list[cls._in_progress_test_index])
@classmethod
def create_extra_database(cls) -> str:
maintenance_connection = cls._maintenance_connections[cls._in_progress_test_index]
db_name = 'test' + uuid.uuid4().hex
with maintenance_connection.cursor() as cursor:
cursor.execute('CREATE DATABASE ' + db_name)
cls._extra_databases.append(db_name)
return db_name
@classmethod
def run_test(cls, test, min_version, max_version, *args):
cls._create_test_databases()
needs_setup = False
for index, details in enumerate(cls._current_test_connection_detail_list):
cls._in_progress_test_index = index
server_version = cls._maintenance_connections[index].info.server_version
if min_version is not None and server_version < min_version or max_version is not None and server_version > max_version:
continue
try:
if needs_setup:
args[0].setUp()
test(*args)
args[0].tearDown()
needs_setup = True
except Exception as e:
host = details['host']
server_version = cls._maintenance_connections[index].info.server_version
raise RuntimeError(f'Test failed while executing on server {index + 1} (host: {host}, version: {server_version})') from e
@classmethod
def _open_maintenance_connections(cls):
config_list = cls._get_connection_configurations()
cls._maintenance_connections = []
cls._current_test_connection_detail_list = []
for config_dict in config_list:
connection = psycopg.connect(**config_dict)
cls._maintenance_connections.append(connection)
connection.autocommit = True
config_dict['dbname'] = None
cls._current_test_connection_detail_list.append(config_dict)
@staticmethod
def _get_connection_configurations() -> dict:
config_file_name = 'config.json'
current_folder = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(current_folder, config_file_name)
if not os.path.exists(config_path):
config_path += '.txt'
if not os.path.exists(config_path):
raise RuntimeError(f'No test config file found at {config_path}')
with open(config_path, encoding='utf-8-sig') as f:
json_content = f.read()
config_list = json.loads(json_content)
if not isinstance(config_list, list):
config_list = [config_list]
return config_list
@classmethod
def _create_test_databases(cls) -> None:
db_name = 'test' + uuid.uuid4().hex
if not cls._maintenance_connections:
cls._open_maintenance_connections()
for index, connection in enumerate(cls._maintenance_connections):
with connection.cursor() as cursor:
cursor.execute('CREATE DATABASE ' + db_name)
cls._current_test_connection_detail_list[index]['dbname'] = db_name
@classmethod
def drop_test_databases(cls) -> None:
if not cls._current_test_connection_detail_list:
return
for index, details in enumerate(cls._current_test_connection_detail_list):
try:
db_name = details['dbname']
with cls._maintenance_connections[index].cursor() as cursor:
cls._drop_database(db_name, cursor)
for extra_db_name in cls._extra_databases:
cls._drop_database(extra_db_name, cursor)
cls._extra_databases = []
except Exception:
pass
for details in cls._current_test_connection_detail_list:
details['dbname'] = None
@staticmethod
def _drop_database(db_name, cursor):
try:
cursor.execute('SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = (%s)', (db_name,))
cursor.execute('DROP DATABASE ' + db_name)
except Exception:
pass
| true |
3e141b55cd481afa939b917025f36e51cfdd18b3 | Python | michalstefanowski/api_petstore_test | /api_tests/pet_tests.py | UTF-8 | 2,009 | 2.640625 | 3 | [] | no_license | import pytest
from assertpy import assert_that
from ahm_service import PetstoreService
from models.models import PetStatus, PetDto
class TestPet:
# New pet to add
new_pet = PetDto(id=1, photo_urls=["test1", "test22"], status=PetStatus.AVAILABLE.value,
tags=[{"id": 666, "name": "elo"}], category={"id": 2, "name": "elo"}, name="nazwa")
# Edit new pet
updated_pet = PetDto(id=1, photo_urls=["test3", "test24"], status=PetStatus.AVAILABLE.value,
tags=[{"id": 666, "name": "elo"}, {"id": 1, "name": "sasad"}],
category={"id": 2, "name": "elo"},
name="nazwa1")
@pytest.mark.run(order=1)
def test_get_by_status(self):
# Given
service = PetstoreService()
# When
response = service.get_pet_by_status([PetStatus.SOLD.value, PetStatus.AVAILABLE.value])
# Then
assert_that(response).is_not_empty()
assert_that(all(isinstance(x, PetDto) for x in response)).is_true()
@pytest.mark.run(order=2)
def test_add_new_pet(self):
# Given
service = PetstoreService()
# When
response = service.post_new_pet(self.new_pet.to_dict())
# Then
assert_that(response).is_equal_to(self.new_pet)
@pytest.mark.run(order=3)
def test_update_existing_pet(self):
# Given
service = PetstoreService()
# When
response = service.put_existing_pet(self.updated_pet.to_dict())
search_results = service.get_pet_by_status([PetStatus.AVAILABLE.value])
# Then
assert_that(response).is_equal_to(self.updated_pet)
assert_that(self.new_pet not in search_results).is_true()
@pytest.mark.run(order=4)
def test_delete_existing_pet(self):
# Given
service = PetstoreService()
# When
response = service.delete_existing_pet(self.updated_pet.id)
# Then
assert_that(response).is_equal_to(200)
| true |
c94e4a78abb63632d362cc01ff342104ba1f72fb | Python | ciaranclear/enigma | /enigma/histogram/histogram.py | UTF-8 | 5,410 | 3.0625 | 3 | [] | no_license |
from typing import OrderedDict
class Histogram:
LETTERS = [chr(i) for i in range(65, 91)]
NUMBERS = [str(i) for i in range(10)]
def __init__(self, input_str, output_str):
self._input_str = input_str
self._output_str = output_str
self._alphanum_map = None
self._alpha_map = None
self._input_alpha_strings = None
self._input_alphanum_strings = None
self._output_strings = None
self._make_translation_maps()
self._make_character_bins()
self._fill_histogram_bins()
self.make_hist_string_dicts()
def __str__(self):
_str = ""
for i in range(31):
_str += self._input_alpha_strings[i]
_str += " "
_str += self._input_alphanum_strings[i]
_str += " "
_str += self._output_strings[i]
_str += '\n'
_str += '\n'
_str += " * = Full percent increment\n"
_str += " : = Greater than or equal to half of the percent increment\n"
_str += " . = Greater than 0 but less than half of the percent increment\n"
return _str
@staticmethod
def valid_character(character, filter):
try:
filter[character]
except KeyError:
msg = f"{character} is not a valid histogram character"
raise ValueError(msg)
else:
return filter[character]
def hist_string(self):
return self.__str__()
def make_hist_string_dicts(self):
self._input_alpha_strings = self.make_hist_string_dict(self._input_alpha_chars, "INPUT ALPHA CHARACTERS")
self._input_alphanum_strings = self.make_hist_string_dict(self._input_alphanum_chars, "INPUT ALPHANUM CHARACTERS")
self._output_strings = self.make_hist_string_dict(self._outp_alpha_chars, "OUTPUT ALPHA CHARACTERS")
def make_hist_string_dict(self, _dict, label):
bars = self.make_hist_bars(_dict)
return self._make_hist_lines(bars, label)
def make_hist_bars(self, _dict):
hist_bars = OrderedDict((c, "") for c in _dict)
for c in _dict:
percent = _dict[c]["PERCENT"]
_str = "{:.1f}".format(percent)
_str = "{:0>5}".format(_str)
_str = _str [::-1]
_str += '-'
_str += c
_str += '|'
_str += '-'
if percent == 0:
_str += f"{' '*19}"
else:
whole = int(percent // 1)
fract = percent % 1
if whole <= 10:
_str += f"{'*'*whole}"
if 0 < fract < 0.5:
_str += '.'
elif fract >= 0.5:
_str += ':'
elif whole > 10:
_str += f"{'*'*int((whole/(100/9))+10)}"
if 0 < percent%10 < 5:
_str += '.'
elif 5 <= percent%10:
_str += ':'
_str += c
_str = _str.ljust(29, ' ')
hist_bars[c] = _str
return hist_bars
def _make_hist_lines(self, _dict, x_axis_label):
y_axis = [
' |',' |',' |',' % |',
' |',' |',' |',' |',
' 0-|',' 1-|',' 2-|',' 3-|',
' 4-|',' 5-|',' 6-|',' 7-|',
' 8-|',' 9-|',' 10-|',' 20-|',
' 30-|',' 40-|',' 50-|',' 60-|',
' 70-|',' 80-|',' 90-|','100-|',
' % |'
]
lines= {i+2:y_axis[i] for i in range(len(y_axis))}
for i in range(len(y_axis)):
for j in _dict:
lines[i+2] += _dict[j][i]
lines[1] = f" -{'-'*len(_dict)}"
lines[0] = f" {x_axis_label.center(len(_dict), ' ')}"
return {abs(i-len(lines)+1) : lines[i] for i in range(len(lines))}
def _fill_histogram_bins(self):
self._fill_bins(self._input_str, self._input_alpha_chars, self._alpha_map)
self._fill_bins(self._input_str, self._input_alphanum_chars, self._alphanum_map)
self._fill_bins(self._output_str, self._outp_alpha_chars, self._alpha_map)
def _fill_bins(self, _str, bins, filter):
for char in _str:
char = char.upper()
char = self.valid_character(char, filter)
bins[char]["COUNT"] += 1
for char in bins:
count = bins[char]["COUNT"]
bins[char]["PERCENT"] = 100 * (float(count)/len(_str))
def _make_translation_maps(self):
"""
"""
self._alphanum_map = {str(n) : str(n) for n in range(10)}
for l in self.LETTERS:
self._alphanum_map[l] = l
self._alpha_map = {
'0':'P','1':'Q',
'2':'W','3':'E',
'4':'R','5':'T',
'6':'Z','7':'U',
'8':'I','9':'O'
}
for l in self.LETTERS:
self._alpha_map[l] = l
def _make_character_bins(self):
self._input_alpha_chars = {c:{"COUNT":0, "PERCENT":0} for c in self.LETTERS}
self._input_alphanum_chars = {c:{"COUNT":0, "PERCENT":0} for c in self.LETTERS}
self._outp_alpha_chars = {c:{"COUNT":0, "PERCENT":0}for c in self.LETTERS}
for num in self.NUMBERS:
self._input_alphanum_chars[num] = {"COUNT":0, "PERCENT":0}
| true |
ce4814297531077e542bbcc9cb5ec94703dcda98 | Python | svandiek/summa-farsi | /local/create_transcript_file.py | UTF-8 | 942 | 2.6875 | 3 | [] | no_license | #!/usr/bin/env python3
import argparse, sys
# parser = argparse.ArgumentParser(description='''Create file called 'text' with transcripts''')
# parser.add_argument('corpusdir', nargs='+', default=sys.stdin)
# args = parser.parse_args()
# corpus = args.corpusdir[0]
# print(corpus)
for folder in ["all", "train", "test"]:
utts = []
fname = 'data/' + folder + '/wav.scp'
with open(fname, encoding='utf-8', mode='r') as f:
for line in f:
line = line.strip().split('\t')
utts.append((line[0], line[1]))
fname = 'data/'+ folder + '/text'
with open(fname, encoding='utf-8', mode='w') as o:
for i in utts:
file = i[1].strip('.wav') + '.txt'
with open(file, encoding='windows-1256', mode='r') as f:
text = ''
for line in f:
if line:
#line = line.decode('windows-1256')
text = text + line
o.write(i[0])
o.write('\t')
o.write(text)
o.write('\n')
print("Done creating transcript files") | true |
74c53267349608f8c1cb8cdac420b31ec85d49c5 | Python | emmeowzing/meta | /plot.py | UTF-8 | 794 | 2.828125 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env python
# -*- coding: utf-8 -*-
""" Plot processed image data """
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from argparse import ArgumentParser
def plot(fname: str) -> None:
with Image.open(fname) as data:
data = np.array(data)
plt.figure(figsize=(9, 6), dpi=200)
plt.imshow(data, interpolation='none', cmap='gist_heat')
fig_name = fname.split('/')[-1] if '/' in fname else fname
print('fig_{0}'.format(fig_name))
plt.savefig('fig_{0}'.format(fig_name))
if __name__ == '__main__':
parser = ArgumentParser(description='** ' + __doc__)
parser.add_argument('inputfile', type=str, help='Input file name')
args = parser.parse_args()
del parser
plot(args.inputfile)
| true |
6211dbfaffd73563a72556fd82964b34aecaecda | Python | nsauzede/mys | /tests/test_errors.py | UTF-8 | 4,203 | 2.671875 | 3 | [
"MIT"
] | permissive | from .utils import TestCase
from .utils import build_and_test_module
class Test(TestCase):
def test_errors(self):
build_and_test_module('errors')
def test_bare_integer_in_try(self):
self.assert_transpile_raises(
'def foo():\n'
' try:\n'
' a\n'
' except:\n'
' pass\n',
' File "", line 3\n'
' a\n'
' ^\n'
"CompileError: bare name\n")
def test_bare_integer_in_except(self):
self.assert_transpile_raises(
'def foo():\n'
' try:\n'
' pass\n'
' except:\n'
' a\n',
' File "", line 5\n'
' a\n'
' ^\n'
"CompileError: bare name\n")
def test_try_except_different_variable_type_1(self):
self.assert_transpile_raises(
'def foo():\n'
' try:\n'
' x = 1\n'
' except:\n'
' x = ""\n'
' print(x)\n',
' File "", line 6\n'
' print(x)\n'
' ^\n'
"CompileError: undefined variable 'x'\n")
def test_try_except_different_variable_type_2(self):
self.assert_transpile_raises(
'def foo():\n'
' try:\n'
' x = 1\n'
' except GeneralError:\n'
' x = ""\n'
' except ValueError:\n'
' x = 2\n'
' print(x)\n',
' File "", line 8\n'
' print(x)\n'
' ^\n'
"CompileError: undefined variable 'x'\n")
def test_try_except_missing_branch(self):
self.assert_transpile_raises(
'def foo():\n'
' try:\n'
' x = 1\n'
' except GeneralError:\n'
' pass\n'
' except ValueError:\n'
' x = 2\n'
' print(x)\n',
' File "", line 8\n'
' print(x)\n'
' ^\n'
"CompileError: undefined variable 'x'\n")
def test_all_branches_different_variable_type_1(self):
self.assert_transpile_raises(
'def foo():\n'
' try:\n'
' if False:\n'
' x = 1\n'
' else:\n'
' x = 2\n'
' except GeneralError:\n'
' try:\n'
' x = 3\n'
' except:\n'
' if True:\n'
' x: u8 = 4\n'
' else:\n'
' x = 5\n'
' print(x)\n',
' File "", line 15\n'
' print(x)\n'
' ^\n'
"CompileError: undefined variable 'x'\n")
def test_missing_errors_in_raises(self):
self.assert_transpile_raises(
'@raises()\n'
'def foo():\n'
' pass\n',
' File "", line 1\n'
' @raises()\n'
' ^\n'
"CompileError: @raises requires at least one error\n")
def test_raise_not_an_error_1(self):
self.assert_transpile_raises(
'def foo():\n'
' try:\n'
' raise 1\n'
' except:\n'
' pass\n',
' File "", line 3\n'
' raise 1\n'
' ^\n'
"CompileError: errors must implement the Error trait\n")
def test_raise_not_an_error_2(self):
self.assert_transpile_raises(
'class Foo:\n'
' pass\n'
'def foo():\n'
' try:\n'
' raise Foo()\n'
' except Foo:\n'
' pass\n',
' File "", line 5\n'
' raise Foo()\n'
' ^\n'
"CompileError: errors must implement the Error trait\n")
| true |
7de3a9235571dfd7fe8c82982b12438b36048ce6 | Python | coldfix/pyval | /val.py | UTF-8 | 3,466 | 3.453125 | 3 | [] | no_license | #! /usr/bin/env python
# encoding: utf-8
"""
Show value of a fully-qualified symbol (in a module or builtins).
Usage:
pyval [-r | -j | -p | -f SPEC] [EXPR]...
Options:
-r, --repr Print `repr(obj)`
-j, --json Print `json.dumps(obj)`
-p, --pprint Print `pprint.pformat(obj)`
-f SPEC, --format SPEC Print `format(obj, SPEC)`
Examples:
$ pyval sys.platform
linux
$ pyval math.pi**2
9.869604401089358
$ pyval 'math.sin(math.pi/4)'
0.7071067811865475
$ pyval -f .3f math.pi
3.142
"""
__version__ = '0.0.5'
import ast
import argparse
class NameResolver(ast.NodeVisitor):
"""Resolve names within the given expression and updates ``locals`` with
the imported modules."""
def __init__(self, locals):
super(NameResolver, self).__init__()
self.locals = locals
def visit_Name(self, node):
resolve(node.id, self.locals)
def visit_Attribute(self, node):
parts = []
while isinstance(node, ast.Attribute):
parts.insert(0, node.attr)
node = node.value
if isinstance(node, ast.Name):
parts.insert(0, node.id)
resolve('.'.join(parts), self.locals)
else:
# We landed here due to an attribute access on some other
# expression (function call, literal, tuple, etc…), and must
# recurse in order to handle attributes or names within this
# subexpression:
self.visit(node)
def resolve(symbol, locals):
"""Resolve a fully-qualified name by importing modules as necessary."""
parts = symbol.split('.')
for i in range(len(parts)):
name = '.'.join(parts[:i+1])
try:
exec('import ' + name, locals, locals)
except ImportError:
break
def formatter(args):
"""Return formatter requested by the command line arguments."""
if args.repr:
return repr
elif args.json:
from json import dumps
return dumps
elif args.pprint:
from pprint import pformat
return pformat
elif args.format:
return lambda value: format(value, args.format)
else:
return str
def main(args=None):
"""Show the value for all given expressions."""
parser = argument_parser()
args = parser.parse_args()
fmt = formatter(args)
for expr in args.EXPRS:
locals = {}
NameResolver(locals).visit(ast.parse(expr))
value = eval(expr, locals)
print(fmt(value))
def argument_parser():
"""Create parser for this script's command line arguments."""
parser = argparse.ArgumentParser(
description='Show value of given expressions, resolving names as'
' necessary through module imports.')
parser.add_argument('--repr', '-r', action='store_true',
help='Print `repr(obj)`')
parser.add_argument('--json', '-j', action='store_true',
help='Print `json.dumps(obj)`')
parser.add_argument('--pprint', '-p', action='store_true',
help='Print `pformat(obj)`')
parser.add_argument('--format', '-f', metavar='SPEC',
help='Print `format(obj, SPEC)`')
parser.add_argument('EXPRS', nargs='+', help='Expressions to be evaluated')
return parser
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv[1:]))
| true |
cd73ec20d97bfff76e17120a49d48ef0d4542375 | Python | Francis009zhao/Quant_Transaction | /myQuant/python_version/extracting_data/excel_test.py | UTF-8 | 3,796 | 2.625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import xlsxwriter
# 生成excel文件
def generate_excel(expenses):
workbook = xlsxwriter.Workbook('./rec_data.xlsx')
worksheet = workbook.add_worksheet()
# 设定格式,等号左边格式名称自定义,字典中格式为指定选项
# bold:加粗,num_format:数字格式
bold_format = workbook.add_format({'bold': True})
# money_format = workbook.add_format({'num_format': '$#,##0'})
# date_format = workbook.add_format({'num_format': 'mmmm d yyyy'})
# 将二行二列设置宽度为15(从0开始)
worksheet.set_column(1, 1, 15)
# 用符号标记位置,例如:A列1行
worksheet.write('A1', 'sku_id', bold_format)
worksheet.write('B1', 'sku_title', bold_format)
worksheet.write('C1', 'id_1', bold_format)
worksheet.write('D1', 'id_1_doc', bold_format)
worksheet.write('E1', 'id_2_doc', bold_format)
worksheet.write('F1', 'id_2_doc', bold_format)
row = 1
col = 0
for item in (expenses):
# 使用write_string方法,指定数据格式写入数据
worksheet.write_string(row, col, str(item['sku_id']))
worksheet.write_string(row, col + 1, item['sku_title'])
worksheet.write_string(row, col + 2, str(item['id_1']))
worksheet.write_string(row, col + 3, item['id_1_doc'])
worksheet.write_string(row, col + 4, str(item['id_2']))
worksheet.write_string(row, col + 5, item['id_2_doc'])
row += 1
workbook.close()
if __name__ == '__main__':
rec_data = [{'sku_id': 2685373, 'id_1': 16161212, 'id_2': 23853166, 'id_2_doc': u'【分享/吐槽大会】宝宝发烧用退热贴真的有效吗?',
'sku_title': u'啾啾 CHUCHU 新宝宝水枕(适用年龄0岁以上)',
'id_1_doc': u'宝宝退热捷径,别忘了这些物理降温宝宝体内致热源刺激体温调节中枢导致产热增加、散热减少的症状即为发热。\n'},
{'sku_id': 2685373, 'id_1': 16161212, 'id_2': 23853166, 'id_2_doc': u'【分享/吐槽大会】宝宝发烧用退热贴真的有效吗?',
'sku_title': u'啾啾 CHUCHU 新宝宝水枕(适用年龄0岁以上)',
'id_1_doc': u'宝宝退热捷径,别忘了这些物理降温宝宝体内致热源刺激体温调节中枢导致产热增加、散热减少的症状即为发热。\n'},
{'sku_id': 2685373, 'id_1': 16161212, 'id_2': 23853166, 'id_2_doc': u'【分享/吐槽大会】宝宝发烧用退热贴真的有效吗?',
'sku_title': u'啾啾 CHUCHU 新宝宝水枕(适用年龄0岁以上)',
'id_1_doc': u'宝宝退热捷径,别忘了这些物理降温宝宝体内致热源刺激体温调节中枢导致产热增加、散热减少的症状即为发热。\n'},
{'sku_id': 2685373, 'id_1': 16161212, 'id_2': 23853166, 'id_2_doc': u'【分享/吐槽大会】宝宝发烧用退热贴真的有效吗?',
'sku_title': u'啾啾 CHUCHU 新宝宝水枕(适用年龄0岁以上)',
'id_1_doc': u'宝宝退热捷径,别忘了这些物理降温宝宝体内致热源刺激体温调节中枢导致产热增加、散热减少的症状即为发热。\n'},
{'sku_id': 2685373, 'id_1': 16161212, 'id_2': 23853166, 'id_2_doc': u'【分享/吐槽大会】宝宝发烧用退热贴真的有效吗?',
'sku_title': u'啾啾 CHUCHU 新宝宝水枕(适用年龄0岁以上)',
'id_1_doc': u'宝宝退热捷径,别忘了这些物理降温宝宝体内致热源刺激体温调节中枢导致产热增加、散热减少的症状即为发热。\n'}
]
generate_excel(rec_data) | true |
824aae66ba63a9d8ead00dfc80f3f200174b2736 | Python | GwiYeong/salt-modularize-tgt-diff | /parse_target.py | UTF-8 | 477 | 2.890625 | 3 | [] | no_license | def parse_target(target_expression):
'''Parse `target_expressing` splitting it into `engine`, `delimiter`,
`pattern` - returns a dict'''
match = TARGET_REX.match(target_expression)
if not match:
log.warning('Unable to parse target "{0}"'.format(target_expression))
ret = {
'engine': None,
'delimiter': None,
'pattern': target_expression,
}
else:
ret = match.groupdict()
return ret
| true |
230730bebb537442760310e706ed26dffc9af870 | Python | paulslevin/alloa | /tests/test_graph.py | UTF-8 | 18,606 | 2.765625 | 3 | [
"MIT"
] | permissive | import unittest
from collections import OrderedDict
import networkx as nx
from alloa.agents import Agent, Hierarchy
from alloa.costs import spa_cost
from alloa.graph import AgentNode, AllocationGraph
from alloa.utils.enums import GraphElement, Polarity
POSITIVE = Polarity.POSITIVE
NEGATIVE = Polarity.NEGATIVE
SOURCE = GraphElement.SOURCE
SINK = GraphElement.SINK
class TestAgentNode(unittest.TestCase):
def setUp(self):
self.hierarchy = Hierarchy(level=1)
self.agent = Agent(agent_id='1')
self.positive_node = AgentNode(agent=self.agent, polarity=POSITIVE)
self.negative_node = AgentNode(agent=self.agent, polarity=NEGATIVE)
def test___str__(self):
self.assertEqual(str(self.positive_node), 'AGENT_1(+)')
self.assertEqual(str(self.negative_node), 'AGENT_1(-)')
def test___hash__(self):
other_positive_node = AgentNode(agent=self.agent, polarity=POSITIVE)
self.assertEqual(hash(self.positive_node), hash(other_positive_node))
def test___eq__(self):
self.positive_node2 = AgentNode(agent=self.agent, polarity=POSITIVE)
self.assertEqual(self.positive_node, self.positive_node2)
self.negative_node2 = AgentNode(agent=self.agent, polarity=NEGATIVE)
self.assertEqual(self.negative_node, self.negative_node2)
def test___neq__(self):
self.assertNotEqual(self.positive_node, self.negative_node)
class TestAllocationGraph(unittest.TestCase):
"""Example from paper."""
def setUp(self):
self.cost = spa_cost
self.students = Hierarchy(level=1)
self.projects = Hierarchy(level=2)
self.supervisors = Hierarchy(level=3)
self.supervisor1 = Agent(
agent_id='1',
capacities=(1, 2),
name='Supervisor 1'
)
self.supervisor2 = Agent(
agent_id='2',
capacities=(0, 2),
name='Supervisor 2'
)
self.supervisor3 = Agent(
agent_id='3',
capacities=(0, 2),
name='Supervisor 3'
)
self.supervisor4 = Agent(
agent_id='4',
capacities=(0, 2),
name='Supervisor 4'
)
self.supervisors.agents = [
self.supervisor1,
self.supervisor2,
self.supervisor3,
self.supervisor4
]
self.project1 = Agent(
agent_id='5',
capacities=(0, 2),
preferences=[
[self.supervisor1, self.supervisor2]
],
name='Project 1'
)
self.project2 = Agent(
agent_id='6',
capacities=(0, 2),
preferences=[
[self.supervisor2, self.supervisor3],
[self.supervisor1, self.supervisor4]
],
name='Project 2'
)
self.projects.agents = [self.project1, self.project2]
self.student1 = Agent(
agent_id='7',
capacities=(0, 1),
preferences=[self.project1, self.project2],
name='Student 1'
)
self.student2 = Agent(
agent_id='8',
capacities=(0, 1),
preferences=[self.project2],
name='Student 2'
)
self.student3 = Agent(
agent_id='9',
capacities=(0, 1),
preferences=[self.project1, self.project2],
name='Student 3'
)
self.students.agents = [self.student1, self.student2, self.student3]
self.graph = AllocationGraph.with_edges(
hierarchies=[
self.students,
self.projects,
self.supervisors
],
cost=self.cost
)
self.source = self.graph.source
self.sink = self.graph.sink
self.example_flow = {
self.source: {
AgentNode(self.student1, POSITIVE): 1,
AgentNode(self.student2, POSITIVE): 1,
AgentNode(self.student3, POSITIVE): 1,
},
AgentNode(self.student1, POSITIVE): {
AgentNode(self.student1, NEGATIVE): 1
},
AgentNode(self.student2, POSITIVE): {
AgentNode(self.student2, NEGATIVE): 1
},
AgentNode(self.student3, POSITIVE): {
AgentNode(self.student3, NEGATIVE): 1
},
AgentNode(self.student1, NEGATIVE): {
AgentNode(self.project1, POSITIVE): 1,
AgentNode(self.project2, POSITIVE): 0
},
AgentNode(self.student2, NEGATIVE): {
AgentNode(self.project2, POSITIVE): 1
},
AgentNode(self.student3, NEGATIVE): {
AgentNode(self.project1, POSITIVE): 1,
AgentNode(self.project2, POSITIVE): 0
},
AgentNode(self.project1, POSITIVE): {
AgentNode(self.project1, NEGATIVE): 2
},
AgentNode(self.project2, POSITIVE): {
AgentNode(self.project2, NEGATIVE): 1
},
AgentNode(self.project1, NEGATIVE): {
AgentNode(self.supervisor1, POSITIVE): 1,
AgentNode(self.supervisor2, POSITIVE): 1
},
AgentNode(self.project2, NEGATIVE): {
AgentNode(self.supervisor1, POSITIVE): 0,
AgentNode(self.supervisor2, POSITIVE): 0,
AgentNode(self.supervisor3, POSITIVE): 1,
AgentNode(self.supervisor4, POSITIVE): 0
},
AgentNode(self.supervisor1, POSITIVE): {
AgentNode(self.supervisor1, NEGATIVE): 0
},
AgentNode(self.supervisor2, POSITIVE): {
AgentNode(self.supervisor2, NEGATIVE): 1
},
AgentNode(self.supervisor3, POSITIVE): {
AgentNode(self.supervisor3, NEGATIVE): 1
},
AgentNode(self.supervisor4, POSITIVE): {
AgentNode(self.supervisor4, NEGATIVE): 0
},
AgentNode(self.supervisor1, NEGATIVE): {
self.sink: 1
},
AgentNode(self.supervisor2, NEGATIVE): {
self.sink: 1
},
AgentNode(self.supervisor3, NEGATIVE): {
self.sink: 1
},
AgentNode(self.supervisor4, NEGATIVE): {
self.sink: 0
},
}
def test_hierarchies(self):
self.assertEqual(
self.graph.hierarchies,
[self.students, self.projects, self.supervisors]
)
def test_number_of_hierarchies(self):
self.assertEqual(self.graph.number_of_hierarchies, 3)
def test_first_level_agents(self):
self.assertEqual(
self.graph.first_level_agents,
[self.student1, self.student2, self.student3]
)
def test_last_level_agents(self):
self.assertEqual(
self.graph.last_level_agents,
[
self.supervisor1,
self.supervisor2,
self.supervisor3,
self.supervisor4
]
)
def test_min_upper_capacity_sum(self):
self.assertEqual(self.graph.min_upper_capacity_sum, 3)
def test_intermediate_hierarchies(self):
self.assertEqual(
self.graph.intermediate_hierarchies(0),
[self.students, self.projects]
)
self.assertEqual(
self.graph.intermediate_hierarchies(self.students.level),
[self.projects]
)
self.assertEqual(
self.graph.intermediate_hierarchies(self.projects.level), []
)
self.assertEqual(
self.graph.intermediate_hierarchies(self.supervisors.level), []
)
self.assertEqual(self.graph.intermediate_hierarchies(4), [])
def test_populate_edges_from_source(self):
self.graph.populate_edges_from_source()
positive_nodes = [
AgentNode(self.student1, POSITIVE),
AgentNode(self.student2, POSITIVE),
AgentNode(self.student3, POSITIVE)
]
expected = {p: {'weight': 256} for p in positive_nodes}
self.assertEqual(self.graph[self.source], expected)
def test_populate_edges_to_sink(self):
self.graph.populate_edges_to_sink()
negative_nodes = [
AgentNode(self.supervisor1, NEGATIVE),
AgentNode(self.supervisor2, NEGATIVE),
AgentNode(self.supervisor3, NEGATIVE),
AgentNode(self.supervisor3, NEGATIVE)
]
for n in negative_nodes:
self.assertEqual(self.graph[n], {self.sink: {'weight': 1}})
def test_glue_students_to_projects(self):
self.graph.glue(self.students)
self.assertFalse(
self.graph.has_edge(
AgentNode(self.student2, NEGATIVE),
AgentNode(self.project1, POSITIVE),
)
)
test_cases = [
(
AgentNode(self.student1, NEGATIVE),
AgentNode(self.project1, POSITIVE),
{'weight': 16}
),
(
AgentNode(self.student1, NEGATIVE),
AgentNode(self.project2, POSITIVE),
{'weight': 64}
),
(
AgentNode(self.student2, NEGATIVE),
AgentNode(self.project2, POSITIVE),
{'weight': 16}
),
(
AgentNode(self.student3, NEGATIVE),
AgentNode(self.project1, POSITIVE),
{'weight': 16}
),
(
AgentNode(self.student3, NEGATIVE),
AgentNode(self.project2, POSITIVE),
{'weight': 64}
),
]
for negative_node, positive_node, edge_data in test_cases:
self.assertEqual(
self.graph[negative_node][positive_node], edge_data
)
def test_glue_projects_to_supervisors(self):
self.graph.glue(self.projects)
self.assertFalse(
self.graph.has_edge(
AgentNode(self.project1, NEGATIVE),
AgentNode(self.supervisor3, POSITIVE),
),
)
self.assertFalse(
self.graph.has_edge(
AgentNode(self.project1, NEGATIVE),
AgentNode(self.supervisor4, POSITIVE),
),
)
test_cases = [
(
AgentNode(self.project1, NEGATIVE),
AgentNode(self.supervisor1, POSITIVE),
{'weight': 1}
),
(
AgentNode(self.project1, NEGATIVE),
AgentNode(self.supervisor2, POSITIVE),
{'weight': 1}
),
(
AgentNode(self.project2, NEGATIVE),
AgentNode(self.supervisor1, POSITIVE),
{'weight': 4}
),
(
AgentNode(self.project2, NEGATIVE),
AgentNode(self.supervisor2, POSITIVE),
{'weight': 1}
),
(
AgentNode(self.project2, NEGATIVE),
AgentNode(self.supervisor3, POSITIVE),
{'weight': 1}
),
(
AgentNode(self.project2, NEGATIVE),
AgentNode(self.supervisor4, POSITIVE),
{'weight': 4}
),
]
for negative_node, positive_node, edge_data in test_cases:
self.assertEqual(
self.graph[negative_node][positive_node],
edge_data
)
def test_graph_consists_of_agent_nodes(self):
self.graph.populate_all_edges()
self.assertEqual(len(self.graph.nodes), 20)
for node in self.graph.nodes:
self.assertIsInstance(node, AgentNode)
def test_compute_flow(self):
self.graph.populate_all_edges()
self.graph.compute_flow()
self.assertEqual(self.graph.flow_cost, 822)
self.assertEqual(self.graph.max_flow, 3)
def test_simplify_flow(self):
"""Use example flow from paper."""
# Make sure this flow satisfies the constraints.
self.graph.populate_all_edges()
self.assertEqual(nx.cost_of_flow(self.graph, self.example_flow), 822)
# Simplify the test flow.
self.graph.flow = self.example_flow
self.graph.simplify_flow()
expected = {
# Students 1 and 3 both get Project 1, and Student 2 gets Project 2.
self.student1: OrderedDict([(self.project1, 1)]),
self.student2: OrderedDict([(self.project2, 1)]),
self.student3: OrderedDict([(self.project1, 1)]),
# Project 1 has two students on it, and will be supervised by
# Supervisors 1 and 2. Supervisor 3 will supervise Project 2.
self.project1: OrderedDict([
(self.supervisor1, 1), (self.supervisor2, 1)
]),
self.project2: OrderedDict([
(self.supervisor3, 1)
]),
}
self.assertEqual(self.graph.simple_flow, expected)
def test_allocate(self):
self.graph.populate_all_edges()
self.graph.flow = self.example_flow
self.graph.simplify_flow()
self.graph.allocate()
# Every agent in this example got their first choice.
self.assertEqual(
self.graph.allocation,
{
self.student1: [
(self.project1, 1),
(self.supervisor1, 1),
],
self.student2: [
(self.project2, 1),
(self.supervisor3, 1),
],
self.student3: [
(self.project1, 1),
(self.supervisor2, 1),
],
}
)
def test_single_allocation(self):
self.graph.populate_all_edges()
self.graph.flow = self.example_flow
self.graph.simplify_flow()
flow = {
agent: dict(d) for agent, d in self.graph.simple_flow.items()
}
self.assertEqual(
self.graph.single_allocation(self.student1, flow),
[(self.project1, 1), (self.supervisor1, 1)]
)
self.assertEqual(
self.graph.single_allocation(self.student2, flow),
[(self.project2, 1), (self.supervisor3, 1)]
)
self.assertEqual(
self.graph.single_allocation(self.student3, flow),
[(self.project1, 1), (self.supervisor2, 1)]
)
def test_costs_zero_from_positive_to_negative_agent_nodes(self):
for agent in [
self.student1, self.student2, self.student3,
self.project1, self.project2,
self.supervisor1, self.supervisor2, self.supervisor3,
self.supervisor4
]:
self.assertEqual(
self.cost(
self.graph.positive_node(agent),
self.graph.negative_node(agent),
self.graph
),
0
)
def test_costs_from_source(self):
for agent in [self.student1, self.student2, self.student3]:
self.assertEqual(
self.cost(
self.source, self.graph.positive_node(agent), self.graph
),
256
)
def test_costs_to_sink(self):
for agent in [
self.supervisor1,
self.supervisor2,
self.supervisor3,
self.supervisor4
]:
self.assertEqual(
self.cost(
self.graph.negative_node(agent), self.sink, self.graph
),
1
)
def test_intermediate_costs(self):
self.assertEqual(
self.cost(
self.graph.negative_node(self.student1),
self.graph.positive_node(self.project1),
self.graph,
),
16
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.student1),
self.graph.positive_node(self.project2),
self.graph,
),
64
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.student2),
self.graph.positive_node(self.project2),
self.graph,
),
16
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.student3),
self.graph.positive_node(self.project1),
self.graph,
),
16
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.student3),
self.graph.positive_node(self.project2),
self.graph,
),
64
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.project1),
self.graph.positive_node(self.supervisor1),
self.graph,
),
1
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.project1),
self.graph.positive_node(self.supervisor2),
self.graph,
),
1
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.project2),
self.graph.positive_node(self.supervisor1),
self.graph,
),
4
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.project2),
self.graph.positive_node(self.supervisor2),
self.graph,
),
1
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.project2),
self.graph.positive_node(self.supervisor3),
self.graph,
),
1
)
self.assertEqual(
self.cost(
self.graph.negative_node(self.project2),
self.graph.positive_node(self.supervisor4),
self.graph,
),
4
)
| true |
bcc4a448a53a8138db8e30d8f5e5fb5ac5be5f05 | Python | xuanxuan03021/Crawler-Project | /12.qiutu.py | UTF-8 | 1,727 | 2.90625 | 3 | [] | no_license |
import urllib.request
import urllib.parse
import http.cookiejar
import ssl
import re
import os
import time
def download_image(content):
pattern=re.compile(r'<div class="thumb">.*?<img src="(.*?)".*?>.*?</div>',re.S)#正则表达式要一个一个严格的对上,要的用小括号扩起来,re.S在单航模式的时候.可以匹配换行符,再多行格式是不能匹配换行符
ret=pattern.findall(content)
print(ret)#列表格式
#便利列表,下载图片
for image in ret:
#处理图片的URL格式
image_src='https:'+image
#创建文件夹
dirname='qiutu'
if not os.path.exists(dirname):
os.mkdir(dirname)
filename=image_src.split('/')[-1]
filepath=dirname+'/'+filename
print('%s图片下载开始'%filename)
urllib.request.urlretrieve(image_src,filepath)
print('%s图片下载结束' % filename)
#发送请求,下载图片
ssl._create_default_https_context = ssl._create_unverified_context
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'
}
url='https://www.qiushibaike.com/pic/page/'
start_page=int(input('请输入起始页码'))
end_page=int(input('请输入结束页码'))
for page in range(start_page,end_page+1):
print('第%s页正在下载'%page)
url2=url+str(page)+'/'
print(url2)
request=urllib.request.Request(url=url2,headers=headers)
#发送请求对象
content=urllib.request.urlopen(request).read().decode()
#解析内容,提取所有的图片链接下载图片
download_image(content)
print('第%s页下载结束' % page)
time.sleep(2)
| true |
a932bfa11be3a8bdef49581a59ff780eaab4204d | Python | shardulparab97/Page-Rank | /processFile.py | UTF-8 | 8,192 | 2.765625 | 3 | [] | no_license | import os
import shutil
import sys
import numpy
import math
import random
import igraph
from scipy import sparse
from igraph import *
#store text file in a list
global rawTextData, rawTextDataCopy
rawTextData = []
rawTextDataCopy = []
global nodeList
nodeList = []
global deletedNodesList
deletedNodesList = []
global linkToNum
linkToNum = []
global processed_Data_Dictionary #,processed_Data_Dictionary_Copy
processed_Data_Dictionary = {}
processed_Data_Dictionary_Copy = {}
global rankedLinksList
rankedLinksList = []
plotNum = 1
layoutFlag = 1
layout = []
x=1
rankMatrix = []
'''
Check whether sum of column values of difference matrix, formed by subtracting
old rank matrix and new new rank matrix, is less than some threshold value.
'''
def checkConvergence(rankMatrix_old, rankMatrix_new):
subMatrix = rankMatrix_old - rankMatrix_new
sum = 0
for rankDif in subMatrix:
sum = sum + abs(rankDif[0])
if sum<0.001:
return False
else:
return True
'''
Read the nodes and their corresponding links from the data file.
Assign every node(URL) a unique integer.
Write the links (FromNode : ToNode in numeric format) to a separate file 'processedLinksData'
'''
def createNodeToNum(stringData):
with open(stringData) as fread:
linkNum=0
lineList = []
for line in fread:
lineList = line.split(' ')
lineList[1] = lineList[1].strip('\n')
if lineList[0] not in linkToNum:
linkToNum.append(lineList[0])
if lineList[1] not in linkToNum:
linkToNum.append(lineList[1])
with open('processedLinksData','a') as fwrite:
fwrite.write(str(linkToNum.index(lineList[0])) + ' ' + str(linkToNum.index(lineList[1])) + '\n')
#read the file line by line, and create rawTextdata 2D list
def createRawTextData():
with open('processedLinksData') as f:
lineList = []
for line in f:
lineList = line.split(' ')
lineList[1] = lineList[1].strip('\n')
rawTextData.append(lineList);
global rawTextDataCopy
rawTextDataCopy = rawTextData
#create processeddataDictionary, key: link, value: list of tolinks
def createProcessed_Data_dictionary():
tempList = []
global processed_Data_Dictionary_Copy
for tempList in rawTextData:
if tempList[0] not in processed_Data_Dictionary:
processed_Data_Dictionary[tempList[0]] = [tempList[1]]
else:
processed_Data_Dictionary[tempList[0]].append(tempList[1])
if tempList[0] not in nodeList:
nodeList.append(tempList[0])
if tempList[1] not in nodeList:
nodeList.append(tempList[1])
processed_Data_Dictionary_Copy = processed_Data_Dictionary
#process those nodes who have no toLinks
def handleLinks_with_No_ToNodes():
for node in nodeList:
if node not in processed_Data_Dictionary:
processed_Data_Dictionary[node] = []
#create the link matrix
def createLinkMatrix(matrixM):
for node in processed_Data_Dictionary:
numOfToLinks = len(processed_Data_Dictionary[node])
for toLink in processed_Data_Dictionary[node]:
matrixM[int(toLink)][int(node)] = 1/numOfToLinks
return matrixM
def performPowerIteration(matrixM,oldRankMatrix,newRankMatrix,teleportMatrix):
while checkConvergence(numpy.asarray(newRankMatrix.todense()),numpy.asarray(oldRankMatrix.todense())):
oldRankMatrix = newRankMatrix
newRankMatrix = (matrixM*oldRankMatrix) + teleportMatrix
visualisePageRank(numpy.asarray(newRankMatrix.todense()))
print(newRankMatrix)
return numpy.asarray(newRankMatrix.todense())
def visualisePageRank(newRankMatrix):
print(newRankMatrix)
g = Graph(directed=True)
global plotNum,deletedNodesList
nodeList.sort()
#create a color pallet
num_colors = 100
palette = RainbowPalette(n=num_colors)
color_list = []
for i in range(num_colors):
color_list.append(palette.get(i))
#Add node to plot
for node in nodeList:
if len(deletedNodesList)==0:
size = 10*60*newRankMatrix[int(node)][0]
g.add_vertex(name = node,color = color_list[int(size%98)],label = node, size = 10*60*newRankMatrix[int(node)][0])
elif node not in deletedNodesList:
size = 10*60*newRankMatrix[int(node)][0]
g.add_vertex(name = node,color = color_list[int(size%98)],label = node, size = 10*60*newRankMatrix[int(node)][0])
global layoutFlag
global layout
if layoutFlag==1:
layout = g.layout_lgl()
for l in layout:
print(l)
l[0] = l[0]/2
l[1] = l[1]/2
layout[0][0] = 0
layout[0][1] = 0
layoutFlag = 0
#add edges to plot
global x
for edge in rawTextData:
if len(deletedNodesList)==0 or edge[0] not in deletedNodesList and edge[1] not in deletedNodesList :
print(edge[0] + " " + edge[1])
g.add_edge(edge[0],edge[1])
plot(g,'Images/g'+str(x)+'.png',layout = layout,bbox =(656,364))
x = x + 1
plot(g,'Final_images/g'+str(plotNum)+'.png',layout = layout,bbox =(656,364))
plotNum = plotNum + 1
def rankVertices(newRankMatrix):
for linkVal in newRankMatrix:
i=0
maxVal=0
maxLinkNum=0
for linkVal in newRankMatrix:
if linkVal[0]>maxVal and linkToNum[i] not in rankedLinksList:
maxVal = linkVal[0]
maxLinkNum = i
i+=1
rankedLinksList.append(linkToNum[maxLinkNum])
def createGif(imageFolder,gifName):
image_files = os.listdir(imageFolder)
for i in range(0,len(image_files)):
image_files[i] = os.path.join(imageFolder,image_files[i])
image_files.sort()
import imageio
images = []
for filename in image_files:
images.append(imageio.imread(filename))
imageio.mimsave(gifName, images,duration=0.7)
def main(stringDataFile, newEdgeFlag, imageFolder1, imageFolder2):
global plotNum,layoutFlag,rankMatrix,processed_Data_Dictionary,rawTextData,rankedLinksList,nodeList,linkToNum
filelist = [ f for f in os.listdir('/home/subhadip/PageRankTester/Images/')]
for f in filelist:
os.remove(os.path.join('/home/subhadip/PageRankTester/Images/', f))
filelist = [ f for f in os.listdir('/home/subhadip/PageRankTester/Final_images/')]
for f in filelist:
os.remove(os.path.join('/home/subhadip/PageRankTester/Final_images/', f))
plotNum = 1
if newEdgeFlag == 0:
open('processedLinksData','w').close()
processed_Data_Dictionary = {}
rawTextData = []
linkToNum = []
rawTextData = []
nodeList = []
createNodeToNum(stringDataFile)
createRawTextData()
createProcessed_Data_dictionary()
handleLinks_with_No_ToNodes()
print(nodeList)
print(processed_Data_Dictionary)
rankedLinksList = []
ini_rank = 1/int(len(nodeList))
matrixM = numpy.zeros((int(len(nodeList)),int(len(nodeList))))
matrixM = createLinkMatrix(matrixM)
matrixM = 0.80*matrixM
matrixM = sparse.csr_matrix(matrixM)
#create rank vector
oldRankMatrix = numpy.zeros((int(len(nodeList)),1))
for r in oldRankMatrix:
r[0] = ini_rank
oldRankMatrix = sparse.csr_matrix(oldRankMatrix)
#create teleport matrix
teleportMatrix = numpy.zeros((int(len(nodeList)),1))
for t in teleportMatrix:
t[0] = 0.20*ini_rank
teleportMatrix = sparse.csr_matrix(teleportMatrix)
newRankMatrix = (matrixM*oldRankMatrix) + teleportMatrix
visualisePageRank(numpy.asarray(newRankMatrix.todense()))
newRankMatrix = performPowerIteration(matrixM,oldRankMatrix,newRankMatrix,teleportMatrix)
rankMatrix = newRankMatrix
visualisePageRank(newRankMatrix)
rankVertices(newRankMatrix)
#createGif(imageFolder1,'movie1.gif')
createGif(imageFolder2,'movie2.gif')
open('processedLinksData','w').close()
#main('stringData.txt',0,'/home/subhadip/PageRankTester/Images/','/home/subhadip/PageRankTester/Final_images/')
| true |
887d0785aaca44a5b55df5a2df6b1a9af68b814b | Python | garciparedes/jinete | /jinete/dispatchers/abc.py | UTF-8 | 1,259 | 2.890625 | 3 | [
"MIT"
] | permissive | """Abstract module which defines the high level scheduling during the process of optimization."""
from __future__ import (
annotations,
)
from abc import (
ABC,
abstractmethod,
)
from typing import (
TYPE_CHECKING,
)
from ..storers import (
NaiveStorer,
)
if TYPE_CHECKING:
from typing import Type
from ..loaders import Loader
from ..models import Result
from ..algorithms import Algorithm
from ..storers import Storer
class Dispatcher(ABC):
"""Dispatch the problem instances."""
def __init__(self, loader_cls: Type[Loader], algorithm_cls: Type[Algorithm], storer_cls: Type[Storer] = None):
"""Construct a new instance.
:param loader_cls: Loads problem instances.
:param algorithm_cls: Generates the solution for the problem instance.
:param storer_cls: Stores problem instances.
"""
if storer_cls is None:
storer_cls = NaiveStorer
self.loader_cls = loader_cls
self.algorithm_cls = algorithm_cls
self.storer_cls = storer_cls
@abstractmethod
def run(self) -> Result:
"""Start the execution of the dispatcher.
:return: A result object containing the generated solution.
"""
pass
| true |
a420d02c4b01f9f668d93b2907dce2a36a9e1efe | Python | xiaohongyang/python_project | /xhy_blog/test.py | UTF-8 | 3,300 | 2.65625 | 3 | [] | no_license | import tkinter as tk
from tkinter import *
import tkinter.messagebox
from urllib import *
import urllib.request
import json
from lib import *
import lib.LogTool
class MyCheckButton(tk.Frame) :
def __init__(self, master = None) :
super().__init__( master)
self.pack(expand = True)
self.master.title ("")
self.master.minsize(200,200)
self.var = tk.IntVar()
# cb = tk.Checkbutton(self, text="Show Title", variable = self.var, command = self.click)
# cb.place(x = 150, y = 150)
#cb.pack()
# cb.place(x=50, y=56)
self.init()
def click(self):
print('clicked')
print(self.var.get())
if self.var.get() == 1 :
self.master.title("CheckButton")
else :
self.master.title("")
def init(self):
l_username = tk.Label(self, text="用户名").grid(row=0)
entry_username = Entry(self, bd=1)
entry_username.grid(row=0, column=1)
l_password = Label(self, text="密码")
l_password.grid(row=1)
entry_password = Entry(self, show="*")
entry_password.grid(row=1, column=1)
self.entry_username = entry_username
self.entry_password = entry_password
btn_regist = Button(self, text="注册", command=self.register)
btn_regist.grid(row=2)
btn_submit = Button(self, text="登录", command=self.doLogin);
btn_submit.grid(row=2,column=2)
def doLogin(self):
username = self.entry_username.get()
password = self.entry_password.get()
if len(username) < 1 :
tk.messagebox.showinfo("提示:", "账号不能为空")
elif len(password) < 1 :
tk.messagebox.showinfo("提示:", "密码不能为空")
elif self.postLoginUser(username=username, password=password):
tk.messagebox.showinfo("提示:", "登录成功")
else :
message = self.message if hasattr(self, 'message') else "登录失败"
print(self.message)
tk.messagebox.showinfo("提示:", message)
def postLoginUser(self, username="", password=""):
result = False
loginUrl = 'http://laravel.54.com:5000/passwordToken?email=' + username + '&password=' + password
print(loginUrl)
try :
req = urllib.request.Request(loginUrl)
reqObj = urllib.request.urlopen(req)
apiContent = reqObj.read()
info = str(apiContent, encoding="utf-8")
info = json.loads(info)
print(info)
if info['status'] == 1 and len(info['data']) >0 :
result = True
else :
self.message = info['message']
lib.LogTool.LogTool.log(self.message)
except Exception as e:
self.message = str(e)
print(str(e))
lib.LogTool.LogTool.log(str(e))
return result
def register(self):
top = tk.Toplevel()
l_username = Label(top, text="用户名")
l_password = Label(top, text="密码")
entry_username = Entry(top)
entry_password = Entry(top)
l_username.grid(row=0)
entry_username.grid(row=0, column=1)
l_password.grid(row=1)
entry_password.grid(row=1, column=1)
top.entry_username = entry_username
btn_ok = Button(top, text="提交注册", command=lambda : self.doRegister(top))
btn_ok.grid(row=2)
top.grab_set()
#tk.messagebox.showinfo("username", "321")
def doRegister(self,master):
username = master.entry_username.get()
tk.messagebox.showinfo("hello","username %s" % username)
master.grab_set()
if __name__ == "__main__" :
root = tk.Tk()
app = MyCheckButton(master = root)
app.master.title("用户登录")
app.mainloop() | true |
3aa565e7301861b23f9cdcbd5dadec49db0ef84f | Python | groodt/99bottles-jmeter | /server.py | UTF-8 | 910 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python
import bottle
import simplejson
bottle.debug(True)
@bottle.post('/bottle')
def store_bottle():
# Extract values from JSON POST body
raw_json = bottle.request.body
json_string = ''.join(raw_json.readlines())
parsed_json = simplejson.loads(json_string)
(num_bottles, drink, date, thread) = (parsed_json['bottles'], parsed_json['drink'], \
parsed_json['date'], parsed_json['thread'])
# Print the "99 Bottles" song to the console. Correctly pluralise "bottle".
plural_bottles = "bottle" if (int(num_bottles)==1) else "bottles"
print("%s %s of %s on the wall. Date=%s Thread=%s" % (num_bottles, plural_bottles, \
drink, date, thread))
return "Cheers!"
# Run the server
bottle.run(server="paste", host='localhost', port=9999, reloader=True)
| true |
4f1a122339b67a1f997b5d683d1cfed2132b0eef | Python | hfrankst/python-text-rpg | /end_game.py | UTF-8 | 652 | 3.5 | 4 | [] | no_license |
def end_game_option():
'''Gives the player the option to restart the game or quit'''
print("\nGAME OVER\n")
print("Would you like to play again? (Y/N)")
player_input = input("> ")
if player_input == "Y" and player_input == "y":
elif player_input == "N" and player_input == "n":
pass
else:
if player_input != "Y" and player_input != "y" and player_input != "N" and player_input != "n":
while(player_input != "Y" and player_input != "y" and player_input != "N" and player_input != "n"):
print("\nPlease enter 'Y' or 'N'.\n")
print("\nGAME OVER\n")
print("Would you like to play again? (Y/N)")
player_input = input("> ")
| true |
644deb588b293f72801ebacb52102318c4844c37 | Python | mmikolajczak/recommendation_system_hetrec2011_movielens | /recommendations_system/data_preparation_scripts/generate_categories_vocabularies.py | UTF-8 | 1,623 | 2.703125 | 3 | [
"MIT"
] | permissive | import os
import os.path as osp
import pandas as pd
from recommendations_system.io_ import load_hetrec_to_df
from recommendations_system.io_._utils import flatten, is_iterable
HETREC_DATA_PATH = '../../data/hetrec2011-movielens-2k-v2'
OUTPUT_VOCABS_PATH = '../../data/generated_categories_vocabs'
def generate_categories_vocab_file(series, output_path, encoding='utf-8'):
if is_iterable(series.iloc[0]) and type(series.iloc[0]) != str:
series = pd.Series(flatten(series.tolist()))
unique = pd.unique(series).tolist()
with open(output_path, 'w', encoding=encoding) as f:
# vocab_file.txt should contain one line for each vocabulary element (src: tf docs)
for val in unique:
f.write(f'{val}\n')
def generate_hetrec_vocab_files(data_path, output_path, encoding='utf-8'):
os.makedirs(output_path, exist_ok=True)
hetrec_df = load_hetrec_to_df(data_path)
features_series = (hetrec_df['userID'], hetrec_df['movieID'], hetrec_df['actorID'], hetrec_df['country'],
hetrec_df['directorID'], hetrec_df['genre'], hetrec_df['location'])
out_files_names = tuple(f'{feature_name}_vocab.txt' for feature_name in ('users', 'movies', 'actors', 'countries',
'directors', 'genres', 'locations'))
for series, out_file_name in zip(features_series, out_files_names):
generate_categories_vocab_file(series, osp.join(output_path, out_file_name), encoding=encoding)
if __name__ == '__main__':
generate_hetrec_vocab_files(HETREC_DATA_PATH, OUTPUT_VOCABS_PATH)
| true |
c1d2a9eddfafdfa0403824b4a932b280e53171cb | Python | sandeepbaldawa/Programming-Concepts-Python | /data_structures/linked_lists/palindrome_check.py | UTF-8 | 577 | 4.3125 | 4 | [] | no_license |
Is Palindrome: Given a Linked List, determine if it is a Palindrome. For example, the following lists are palindromes:
A -> B -> C -> B -> A
A -> B -> B -> A
K -> A -> Y -> A -> K
Note: Can you do it with O(N) time and O(1) space? (Hint: Reverse a part of the list)
Solution 1:- We can create a new list in reversed order and then compare each node. The time and space are O(n).
Solution 2:- We can use a fast and slow pointer to get the center of the list, then reverse the second list and compare two sublists.
The time is O(n) and space is O(1).
| true |
1290868c833d5a90c9d64a8fa5fb774929bac912 | Python | sug5806/TIL | /Jupyter_Notebook_for_Python/2019-03-18 opxl/test.py | UTF-8 | 67 | 2.65625 | 3 | [
"MIT"
] | permissive | import sys
for arg in sys.argv:
print(arg, type(arg))
| true |
cba1b7f7b01120b89dc92926920b226fcd3ffa02 | Python | karelinas/adventofcode2019 | /day06/a.py | UTF-8 | 558 | 3.4375 | 3 | [] | no_license | import sys
def ancestor_count(graph, child):
parent = graph.get(child, None)
if not parent:
return 0
return 1 + ancestor_count(graph, parent)
def read_graph(iterator):
graph = {}
for line in iterator:
line = line.strip()
if not len(line):
continue
parent, child = line.split(')')
graph[child] = parent
return graph
if __name__ == '__main__':
graph = read_graph(sys.stdin)
orbit_count = sum((ancestor_count(graph, child) for child in graph.keys()))
print(orbit_count)
| true |
63bb0dd3a30d3edf5b752a856cca8ec0df2fd442 | Python | anaswara-97/python_project | /flow_of_control/looping/sum_upto_range.py | UTF-8 | 210 | 3.515625 | 4 | [] | no_license | num=int(input("enter the limit : "))
sum=0
# for i in range(num+1):
# sum=sum+i
# print("sum of first",num,"numbers :",sum)
i=0
while(i<=num):
sum+=i
i+=1
print("sum of first",num,"numbers :",sum)
| true |
27a7cb29c095ad358fff7131ce9e502e1e18fbd2 | Python | ELOHIMSUPREMES/hashtagcluster | /etl.py | UTF-8 | 2,286 | 2.734375 | 3 | [] | no_license | import tweepy
import json
from pprint import pprint as pp
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import scipy
from collections import Counter
from tweetutils import clean_tweet
class MyStreamListener(tweepy.StreamListener):
# tweetlist stores 100 tweets, tweetlistmaster stores all imported tweets
tweetlist = []
tweetcounter = 0
batchnumber = 0
def __init__(self, api=None, searchitem = None):
"""over ride the base _init_ method to accept a serach term parameter"""
self.api = api
self.searchterm = searchitem
def on_status(self, status):
"""we want to grab tweets in batches of 100 to send to the clustering algo, or maybe less than 100 or maybe more
also at this stage we want to have something to process the tweets."""
# clean the status, put in a list.
cleantweet = clean_tweet(status._json)
self.tweetlist.append(cleantweet)
self.tweetcounter += 1
if self.tweetcounter >= 100:
print self.searchterm, ' batch number ', self.batchnumber
# once 100 tweeets have been reached we do something. currently we write it to file, extract features, cluster and generate cluster information.
# reset the counters
self.tweetcounter = 0
# dump to datafile for now
f = open('data/current_data/{0}_batch{1}.txt'.format(self.searchterm, str(self.batchnumber)), 'w')
json.dump(self.tweetlist, f)
f.close()
# wipe the tweetlist
self.tweetlist = []
# increment batch couter.
self.batchnumber += 1
if __name__ == '__main__':
# load the API keys
with open('../keys.json', 'r') as fp:
keys = json.load(fp)
consumer_token = keys['APIkey']
consumer_secret = keys['APIsecret']
access_token = keys['AccessToken']
access_secret = keys['AccessTokenSecret']
# start a session with the twitter API
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_secret)
# create the API object
api = tweepy.API(auth)
# search term
hashTag = '#WorldTeachersDay'
print hashTag
# creating stream listener
SL = MyStreamListener(searchitem = hashTag)
# starting stream? maybe?
mystream = tweepy.Stream(auth = api.auth, listener = SL)
# filtering?
mystream.filter(track=[hashTag])
| true |
af2f03cfc42837b7331a32d79d339e0d69e34ecb | Python | danielzhang1998/xiaojiayu_lesson_coding | /python/lessons_coding/lesson74_tk_v1.py | UTF-8 | 875 | 2.765625 | 3 | [] | no_license | from tkinter import *
def doNothing():
label1 = Label(root, text="Doing nothing")
label1.pack()
root = Tk()
mainmenu = Menu(root)
root.config(menu=mainmenu)
filemenu = Menu(mainmenu)
mainmenu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New Project", command=doNothing)
filemenu.add_command(label="New", command=doNothing)
Submenu = Menu(mainmenu)
filemenu.add_cascade(label="Open", menu = Submenu)
Submenu.add_command(label = 'From local')
Submenu.add_command(label = 'From web')
Submenu.add_command(label = 'From OneDrive')
Submenu.add_command(label = 'From GitHub')
Submenu.add_command(label = 'Other')
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
editmenu=Menu(mainmenu)
mainmenu.add_cascade(label="Edit", menu=editmenu)
editmenu.add_command(label="Redo", command=doNothing)
root.mainloop() | true |
144c7ee2e3cda1835d59113c4550af9b4665f5a3 | Python | paty0504/Web-NguyenTThanh-C4E16 | /web1/app.py | UTF-8 | 1,031 | 2.953125 | 3 | [] | no_license | from flask import Flask, render_template
app = Flask(__name__)
@app.route('/') #tại địa chỉ server ==> trang chủ
def index():#function . Khi người dùng vào đường dẫn thì chạy hàm index
# post_title = 'THơ con ếch'
# post_content = '????'
# post_author = 'Thanh'
posts = [
{'title' : 'Tho con ech',
'content' : '???',
'gender' : 1,
'author' : 'Thanh',},
{ 'title' : 'Tho con coc',
'content' : '...',
'gender' : 1,
'author' : 'Thanh1',},
{'title' : 'Không biết làm thơ',
'content' : 'Chịu',
'gender' : 0,
'author' : 'Hồng Anh'
}
]
return render_template('index.html',posts=posts)
@app.route('/hello')
def hello():
return "Hello C4E 16"
@app.route('/sayhi/<name>/<age>')
def hi(name, age):
return "Hi " + name + "You're " + age
if __name__ == '__main__':
app.run( debug=True) #khi file này chạy trực tiếp thì chạy
#debug = True: mỗi lần sửa code thì tự động cập nhật lại
| true |
c069a307aaf80196b5dce8468752b3efa9bf0da5 | Python | alizkzm/BioinformaticsPractice | /Bio3.py | UTF-8 | 208 | 3.078125 | 3 | [] | no_license | from suffix_trees import STree
string = "GCGAGC"
suffixTree = STree.STree(string)
nodes = [string[i:] for i in range(len(string))]
out = [suffixTree.find(key) for key in sorted(nodes)]
print(out)
| true |
ea76c7b94c7c69ae628bed507d92375b113b28e4 | Python | lukebrawleysmith/Common-Function | /CommonFunctions.py | UTF-8 | 15,773 | 3.140625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 5 17:37:30 2016
@author: luksmi
"""
import pandas as pd
import numpy as np
import scipy
import math
import time
from functools import partial
def checkInteger(v, vName, isArray = False, lengthOne = True,
nonNegative = False, positive = False):
"""Checks if argument v is an integer.
Note that np.nan is considered a float, so nan cannot be in an integer array.
Args:
v (int):
vName (string): the name of v
isArray (boolean): if v should be an array
lengthOne (boolean): should v be of length one?
nonNegative (boolean): should v be nonNegative?
positive (boolean): is v restricted to be positive?
Returns nothing.
"""
# Error handling:
errorString = 'in checkInteger vName must be a float.'
assert isinstance(vName, str), errorString
errorString = 'in checkInteger isArray must be boolean.'
assert isinstance(isArray, bool), errorString
errorString = 'in checkInteger lengthOne must be boolean.'
assert isinstance(lengthOne, bool), errorString
errorString = 'in checkInteger nonNegative must be boolean.'
assert isinstance(nonNegative, bool), errorString
errorString = 'in checkInteger positive must be boolean.'
assert isinstance(positive, bool), errorString
if not isArray:
#assumes v is of length 1
errorString = vName + ' must contain integers.'
assert isinstance(v, int), errorString
if nonNegative:
errorString = vName + ' cannot be negative.'
assert v >= 0, errorString
if positive:
errorString = vName + ' cannot be nonNegative.'
assert v > 0, errorString
if isArray:
errorString = vName + ' must be a numpy array.'
assert isinstance(v, np.ndarray), errorString
errorString = vName + ' must contain integers.'
assert v.dtype == 'int64' or v.dtype == 'int32', errorString
if lengthOne:
errorString = vName + ' must be of length 1'
assert v.size == 1, errorString
if nonNegative:
errorString = vName + ' cannot contain negative values.'
assert v[v < 0].size == 0, errorString
if positive:
errorString = vName + ' cannot contain nonNegative values.'
assert v[v <= 0].size == 0, errorString
def checkFloat(v, vName, isArray = False, noMissing = True,
lengthOne = True, nonNegative = False, positive = False):
"""Checks if argument v is a float.
Note that np.nan is considered a float.
Args:
v (int):
vName (string): the name of v
isArray (boolean): if v should be an array
noMissing (boolean): if v should not contain missing
lengthOne (boolean): should v be of length one?
nonNegative (boolean): should v be nonNegative?
positive (boolean): is v restricted to be positive?
Returns nothing.
"""
# Error handling:
errorString = 'in checkFloat vName must be a float.'
assert isinstance(vName, str), errorString
errorString = 'in checkFloat isArray must be boolean.'
assert isinstance(isArray, bool), errorString
errorString = 'in checkFloat noMissing must be boolean.'
assert isinstance(noMissing, bool), errorString
errorString = 'in checkFloat lengthOne must be boolean.'
assert isinstance(lengthOne, bool), errorString
errorString = 'in checkFloat nonNegative must be boolean.'
assert isinstance(nonNegative, bool), errorString
errorString = 'in checkFloat positive must be boolean.'
assert isinstance(positive, bool), errorString
if not isArray:
#assumes v is of length 1
errorString = vName + ' must contain floats.'
assert isinstance(v, float), errorString
if noMissing:
errorString = vName + ' cannot be missing.'
assert not np.isnan(v), errorString
if nonNegative:
errorString = vName + ' cannot be negative.'
assert v >= 0.0, errorString
if positive:
errorString = vName + ' cannot be nonNegative.'
assert v > 0.0, errorString
if isArray:
errorString = vName + ' must be a numpy array.'
assert isinstance(v, np.ndarray), errorString
errorString = vName + ' must contain floats.'
assert v.dtype == 'float64' or v.dtype == 'float32', errorString
if noMissing:
errorString = vName + ' cannot contain missing values.'
assert not np.isnan(v).any(), errorString
if lengthOne:
errorString = vName + ' must be of length 1'
assert v.size == 1, errorString
if nonNegative:
errorString = vName + ' cannot contain negative values.'
assert v[v < 0.0].size == 0, errorString
if positive:
errorString = vName + ' cannot contain nonNegative values.'
assert v[v <= 0.0].size == 0, errorString
def checkUnitInterval(v, vName, isArray = False, noMissing = True,
lengthOne = True, equal = False):
"""Checks if argument v is in (0, 1) or [0, 1].
Args:
v (int):
vName (string): the name of v
isArray (boolean): if v should be an array
noMissing (boolean): if v should not contain missing
lengthOne (boolean): should v be of length one?
equal (boolean): [0, 1] is interval of interest
Returns nothing.
"""
# Error handling:
errorString = 'in checkFloat vName must be a float.'
assert isinstance(vName, str), errorString
errorString = 'in checkFloat isArray must be boolean.'
assert isinstance(isArray, bool), errorString
errorString = 'in checkFloat noMissing must be boolean.'
assert isinstance(noMissing, bool), errorString
errorString = 'in checkFloat lengthOne must be boolean.'
assert isinstance(lengthOne, bool), errorString
errorString = 'in checkFloat equal must be boolean.'
assert isinstance(equal, bool), errorString
if equal: positive = False
else: positive = True
checkFloat(v, vName, isArray, noMissing,
lengthOne, True, positive)
if equal:
errorString = vName + ' must contain elements less than or equal to 1.0.'
if isArray:
assert v[v > 1.0].size == 0, errorString
else:
errorString = vName + ' must be less than or equal to 1.0.'
assert v <= 1.0, errorString
else:
if isArray:
errorString = vName + ' must contain elements less than 1.0.'
assert v[v >= 1.0].size == 0, errorString
else:
errorString = vName + ' must be less than 1.0.'
assert v < 1.0, errorString
def invertSymmetricMatrix(v):
"""Inverts symmetric matrix v.
Args:
v : symmetric invertible matrix.
Returns:
vInv: inverse of v.
vInvLogDet: log determinant of vInv.
"""
# Error handling:
assert isinstance(v, np.ndarray), 'v must be a numpy array.'
vChol = scipy.linalg.cholesky(v).T
n = v.shape[0]
vInvLogDet = sum(math.log(vChol[i][i]) for i in range(n))
vInvLogDet *= -2.0
vCholInv = scipy.linalg.solve_triangular(vChol.T, b = np.identity(n))
vInv = vCholInv.dot(vCholInv.T)
return([vInv, vInvLogDet])
def makeAbsoluteDistance(timepoints):
"""Creates a matrix of absolute distances.
Args:
timepoints (np.ndarray): vector of length n.
Returns d, the n x n distance matrix.
"""
assert isinstance(timepoints, np.ndarray), 'timepoints must be a numpy array.'
assert len(timepoints.shape) == 1, 'timepoints must be a 1-dimensional array.'
n = timepoints.shape[0]
k = len(timepoints)
d1 = np.zeros(shape = (k, k))
d2 = np.zeros(shape = (k, k))
for i in range(k):
d1[:, i] = timepoints
d2[i, :] = timepoints
d = abs(d1 - d2)
return d
def bSpline(x, degree = 3, boundaryKnots = [0, 1], interiorKnots = None, intercept = False):
"""bSpline in loop.
Args:
x: points at which to evaluate the spline basis.
degree: spline degree (default cubic).
boundaryKnots:
noMissing (boolean): if v should not contain missing
lengthOne (boolean): should v be of length one?
equal (boolean): [0, 1] is interval of interest
Returns nothing.
"""
# Error handling:
assert isinstance(x, np.ndarray), 'x must be a numpy array.'
assert len(x.shape) == 1, 'if x has length greater than 1, x be a vector.'
checkInteger(degree, 'degree', positive = True)
assert isinstance(boundaryKnots, np.ndarray), 'boundaryKnots must be a numpy array.'
assert len(boundaryKnots) == 2, 'boundaryKnots must be of length 2.'
boundaryKnots = sorted(boundaryKnots)
if interiorKnots is None:
lenInteriorKnots = 0
knots = boundaryKnots
else:
assert isinstance(interiorKnots, np.ndarray), 'if not empty, interiorKnots must be a numpy array.'
interiorKnots = sorted(interiorKnots)
lenInteriorKnots = len(np.atleast_1d(interiorKnots))
assert np.min(interiorKnots) > boundaryKnots[0], 'boundaryKnots[0] must be smaller than all interiorKnots.'
assert np.max(interiorKnots) < boundaryKnots[1], 'boundaryKnots[1] must be larger than all interiorKnots.'
knots = np.concatenate([np.repeat(boundaryKnots[0], degree + 1), interiorKnots, np.repeat(boundaryKnots[1], degree + 1)], axis = 0)
errorString = 'in bSplineMatrix intercept must be boolean.'
assert isinstance(intercept, bool), errorString
#create function that evaluates bSpline for a scalar x
def bSplineScalar(x, degree, i, knots):
if(degree == 0):
if (knots[i] <= x) & (x < knots[i + 1]):
v = 1.0
else:
v = 0.0
else:
if((knots[degree + i] - knots[i]) == 0.0):
alpha1 = 0.0
else:
alpha1 = (x - knots[i]) / (knots[degree + i] - knots[i])
if((knots[degree + i + 1] - knots[i + 1]) == 0):
alpha2 = 0.0
else:
alpha2 = (knots[degree + i + 1] - x) / (knots[i + degree + 1] - knots[i + 1])
v = alpha1 * bSplineScalar(x, degree - 1, i, knots) + alpha2 * bSplineScalar(x, degree - 1, i + 1, knots)
return v
nColumnsB = lenInteriorKnots + degree + 1
xLength = len(np.atleast_1d(x))
vMat = np.zeros(shape = (xLength, nColumnsB))
for i in range(nColumnsB):
for j in range(xLength):
vMat[j, i] = bSplineScalar(x[j], degree, i, knots)
vMat[x == boundaryKnots[1], nColumnsB - 1] = 1.0
if not intercept:
vMat = vMat[:, 1:nColumnsB]
return vMat
def bSpline2(x, degree = 3, boundaryKnots = [0, 1], interiorKnots = None, intercept = False):
"""#vectorized bSpline.
Args:
x: points at which to evaluate the spline basis.
degree: spline degree (default cubic).
boundaryKnots:
noMissing (boolean): if v should not contain missing
lengthOne (boolean): should v be of length one?
equal (boolean): [0, 1] is interval of interest
Returns nothing.
"""
# Error handling:
assert isinstance(x, np.ndarray), 'x must be a numpy array.'
assert len(x.shape) == 1, 'if x has length greater than 1, x be a vector.'
checkInteger(degree, 'degree', positive = True)
assert isinstance(boundaryKnots, np.ndarray), 'boundaryKnots must be a numpy array.'
assert len(boundaryKnots) == 2, 'boundaryKnots must be of length 2.'
boundaryKnots = sorted(boundaryKnots)
if interiorKnots is None:
lenInteriorKnots = 0
knots = boundaryKnots
else:
assert isinstance(interiorKnots, np.ndarray), 'if not empty, interiorKnots must be a numpy array.'
interiorKnots = sorted(interiorKnots)
lenInteriorKnots = len(np.atleast_1d(interiorKnots))
assert np.min(interiorKnots) > boundaryKnots[0], 'boundaryKnots[0] must be smaller than all interiorKnots.'
assert np.max(interiorKnots) < boundaryKnots[1], 'boundaryKnots[1] must be larger than all interiorKnots.'
knots = np.concatenate([np.repeat(boundaryKnots[0], degree + 1), interiorKnots, np.repeat(boundaryKnots[1], degree + 1)], axis = 0)
errorString = 'in bSplineMatrix intercept must be boolean.'
assert isinstance(intercept, bool), errorString
#create function that evaluates bSpline for a scalar x
def bSplineScalar(x, degree, i, knots):
if(degree == 0):
if (knots[i] <= x) & (x < knots[i + 1]):
v = 1.0
else:
v = 0.0
else:
if((knots[degree + i] - knots[i]) == 0.0):
alpha1 = 0.0
else:
alpha1 = (x - knots[i]) / (knots[degree + i] - knots[i])
if((knots[degree + i + 1] - knots[i + 1]) == 0):
alpha2 = 0.0
else:
alpha2 = (knots[degree + i + 1] - x) / (knots[i + degree + 1] - knots[i + 1])
v = alpha1 * bSplineScalar(x, degree - 1, i, knots) + alpha2 * bSplineScalar(x, degree - 1, i + 1, knots)
return v
nColumnsB = lenInteriorKnots + degree + 1
vMat = np.zeros(shape = (len(np.atleast_1d(x)), nColumnsB))
for i in range(nColumnsB):
bSplineVector = partial(bSplineScalar, degree = degree, i = i, knots = knots)
bSplineVector2 = np.vectorize(bSplineVector)
vMat[:, i] = bSplineVector2(x)
vMat[x == boundaryKnots[1], nColumnsB - 1] = 1.0
if not intercept:
vMat = vMat[:, 1:nColumnsB]
return vMat
def bSpline3(x, degree = 3, boundaryKnots = [0, 1], interiorKnots = None, intercept = False):
"""List comprehension version.
Args:
x: points at which to evaluate the spline basis.
degree: spline degree (default cubic).
boundaryKnots:
noMissing (boolean): if v should not contain missing
lengthOne (boolean): should v be of length one?
equal (boolean): [0, 1] is interval of interest
Returns nothing.
"""
# Error handling:
assert isinstance(x, np.ndarray), 'x must be a numpy array.'
assert len(x.shape) == 1, 'if x has length greater than 1, x be a vector.'
checkInteger(degree, 'degree', positive = True)
assert isinstance(boundaryKnots, np.ndarray), 'boundaryKnots must be a numpy array.'
assert len(boundaryKnots) == 2, 'boundaryKnots must be of length 2.'
boundaryKnots = sorted(boundaryKnots)
if interiorKnots is None:
lenInteriorKnots = 0
knots = boundaryKnots
else:
assert isinstance(interiorKnots, np.ndarray), 'if not empty, interiorKnots must be a numpy array.'
interiorKnots = sorted(interiorKnots)
lenInteriorKnots = len(np.atleast_1d(interiorKnots))
assert np.min(interiorKnots) > boundaryKnots[0], 'boundaryKnots[0] must be smaller than all interiorKnots.'
assert np.max(interiorKnots) < boundaryKnots[1], 'boundaryKnots[1] must be larger than all interiorKnots.'
knots = np.concatenate([np.repeat(boundaryKnots[0], degree + 1), interiorKnots, np.repeat(boundaryKnots[1], degree + 1)], axis = 0)
errorString = 'in bSplineMatrix intercept must be boolean.'
assert isinstance(intercept, bool), errorString
#create function that evaluates bSpline for a scalar x
def bSplineScalar(x, degree, i, knots):
if(degree == 0):
if (knots[i] <= x) & (x < knots[i + 1]):
v = 1.0
else:
v = 0.0
else:
if((knots[degree + i] - knots[i]) == 0.0):
alpha1 = 0.0
else:
alpha1 = (x - knots[i]) / (knots[degree + i] - knots[i])
if((knots[degree + i + 1] - knots[i + 1]) == 0):
alpha2 = 0.0
else:
alpha2 = (knots[degree + i + 1] - x) / (knots[i + degree + 1] - knots[i + 1])
v = alpha1 * bSplineScalar(x, degree - 1, i, knots) + alpha2 * bSplineScalar(x, degree - 1, i + 1, knots)
return v
nColumnsB = lenInteriorKnots + degree + 1
xLength = len(np.atleast_1d(x))
vMat = np.zeros(shape = (xLength, nColumnsB))
for i in range(nColumnsB):
vMat[:, i] = [bSplineScalar(y, degree, i, knots) for y in x]
vMat[x == boundaryKnots[1], nColumnsB - 1] = 1.0
if not intercept:
vMat = vMat[:, 1:nColumnsB]
return vMat
| true |
4ec64acb41d68b5ef680173602b645996fe0de4a | Python | Hoodythree/LeetCode_By_Tag | /Data_Structure_and_Alogrithm/int_break.py | UTF-8 | 786 | 3.203125 | 3 | [] | no_license |
def integer_breaking(num):
dynamic_programming = [1 for i in range(num + 1)]
for i in range(1, num + 1):
if i % 2 == 1:
dynamic_programming[i] = dynamic_programming[i - 1]
else:
dynamic_programming[i] = dynamic_programming[i - 1] + dynamic_programming[i // 2]
return dynamic_programming[-1] % 10000000
def dfs(n,m):
if n==0:
return 1
elif m==0:
return 0
elif n==1 or m==1:
return 1
elif n<m:
return dfs(n,n)
elif n==m:
return dfs(n,m-1)+1
else:
return dfs(n,m-1)+dfs(n-m,m)
if __name__ == '__main__':
n = int(input())
res = []
for i in range(n):
x = int(input())
res.append(x)
for r in res:
print(dfs(r, r)) | true |
0a72507a13f67d6f0a6a8f616eb5da5aec4c6bb4 | Python | ngkavin/echoregions | /echoregions/plot/region_plot.py | UTF-8 | 3,292 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | import numpy as np
import pandas as pd
import os
from ..convert.utils import from_JSON
import matplotlib.pyplot as plt
class Regions2DPlotter():
"""Class for plotting Regions. Should only be used by `Regions2D`"""
def __init__(self, Regions2D):
self.Regions2D = Regions2D
def plot_region(self, region, offset=0):
"""Plot a region.
Parameters
----------
region : str
id of region to be plotted
offset : float
meters to offset the region depth by
Returns
-------
numpy arrays for the x and y points plotted
"""
points = np.array(self.Regions2D.convert_points(
self.get_points_from_region(region),
convert_time=True,
convert_range_edges=True,
offset=offset
))
points = self.close_region(points)
x = np.array(points[:, 0], dtype=np.datetime64)
y = points[:, 1]
plt.plot_date(x, y, marker='o', linestyle='dashed', color='r')
return x, y
def get_points_from_region(self, region, file=None):
"""Get a list of points from a given region.
Parameters
----------
region : str
id of region to be plotted
file : float
CSV or JSON file. If `None`, use `output_data`
Returns
-------
list of points from the given region
"""
if file is not None:
if file.upper().endswith('.CSV'):
if not os.path.isfile(file):
raise ValueError(f"{file} is not a valid CSV file.")
data = pd.read_csv(file)
region = data.loc[data['region_id'] == int(region)]
# Combine x and y points to get a list of points
return list(zip(region.x, region.y))
elif file.upper().endswith('.JSON'):
data = from_JSON(file)
points = list(data['regions'][str(region)]['points'].values())
else:
raise ValueError(f"{file} is not a CSV or JSON file")
# Pull region points from passed region dict
if isinstance(region, dict):
if 'points' in region:
points = list(region['points'].values())
else:
raise ValueError("Invalid region dictionary")
# Pull region points from parsed data
else:
region = str(region)
if region in self.Regions2D.output_data['regions']:
points = list(self.Regions2D.output_data['regions'][region]['points'].values())
else:
raise ValueError("{region} is not a valid region")
return [list(p) for p in points]
def close_region(self, points):
"""Close a region by appending the first point to end of the list of points.
Parameters
----------
points : list
list of points
Returns
-------
list of points where the first point is appended to the end
"""
is_array = True if isinstance(points, np.ndarray) else False
points = list(points)
points.append(points[0])
if is_array:
points = np.array(points)
return points
| true |
a0aa7003e074d8b660e81fd75f16689caf2a274c | Python | achrinza/np-csf02-answers | /PRG1/Assignment/1/test_adapter_manager.py | UTF-8 | 827 | 2.765625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | import pytest
from adapter import Adapter
from adapter_manager import AdapterManager
class DummyAdapter(Adapter):
ADAPTER_TITLE = "PytestDummyAdapter"
ADAPTER_TYPE = "DummyAdapter"
def __init__(self):
pass
def call(self, args, kwargs):
if len(args) > 0:
return args[0]
else:
return kwargs
class TestAdapterManager():
adapter_manager = AdapterManager()
def test_add_args(self):
self.adapter_manager.add(DummyAdapter)
assert self.adapter_manager.call("FOOBAR") == "FOOBAR"
def test_add_kwargs(self):
self.adapter_manager.add(DummyAdapter)
assert self.adapter_manager.call(FOO="BAR")["FOO"] == "BAR"
def test_flush(self):
self.adapter_manager.flush()
assert self.adapter_manager.call() is None
| true |
b3d152c3d77164cfb4fddc268cfa28526a619b59 | Python | Mattamorphic/Painter | /app/views/components/dialogs.py | UTF-8 | 4,905 | 3.015625 | 3 | [] | no_license | '''
Dialogs
Author:
Matthew Barber <mfmbarber@gmail.com>
'''
from app.lib.constants import Constants
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QLabel, QVBoxLayout, QSizePolicy
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QPixmap
class BaseDialog(QDialog):
'''
A helper class for creating dialogs
Args:
parent (class): The owner of this dialog
'''
def __init__(self, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.heading = QLabel()
self.subHeading = QLabel()
self.content = QLabel()
self.content.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.buttonBox = QDialogButtonBox()
layout = QVBoxLayout()
layout.addWidget(self.heading)
layout.addWidget(self.subHeading)
layout.addWidget(self.content)
layout.addWidget(self.buttonBox)
self.setLayout(layout)
def addButton(self, text: str, role, callback=None):
'''
Add a button with text, a role, and an optional callback
Args:
text (str): The text for the button
role (enum): An option from the wrapper enum Constants.DialogButtonRoles
callback (func): An optional callback to tie to the button
'''
if role not in Constants.DialogButtonRoles:
raise ValueError('Role must be one of Constants.DialogButtonRoles')
btn = self.buttonBox.addButton(text, role.value)
if callback:
btn.clicked.connect(callback)
def setHeading(self, text: str):
'''
Setter method for the heading label
Args:
text (str): Text for the main label
'''
self.heading.setText(text)
def setSubHeading(self, text: str):
'''
Setter method for the subheading label
Args:
text (str): Text for the sub label
'''
self.subHeading.setText(text)
def setContent(self, content):
if isinstance(content, str):
self.content.setText(str)
elif isinstance(content, QPixmap):
self.content.setPixmap(content)
def setTitle(self, text: str):
'''
Setter method for the dialog title
Args:
text (str): Text for the window title
'''
self.setWindowTitle(text)
def onAccept(self, callback):
'''
Human friendly wrapper for the button box accepted signal
Args:
callback (func): Slot to call
'''
self.buttonBox.accepted.connect(callback)
def onReject(self, callback):
'''
Human friendly wrapper for the button box regjected signal
Args:
callback (func): Slot to call
'''
self.buttonBox.rejected.connect(callback)
class AboutDialog(BaseDialog):
'''
About PyPainter dialog
'''
def __init__(self, parent=None):
super().__init__(parent)
self.setHeading('PyPainter')
self.setSubHeading('A PyPainter by Matt Barber')
self.setContent(QPixmap(Constants.IMAGES_LOCATION + "logo.png"))
self.setTitle("About PyPainter")
self.addButton('OK', Constants.DialogButtonRoles.ACCEPT)
self.onAccept(self.close)
class QuitDialog(BaseDialog):
'''
Dialog for handling quit
Args:
save (func): Callback for handling saving
'''
def __init__(self, save=None, parent=None):
super().__init__(parent)
self.setHeading('Quit PyPainter?')
self.save = save
self.initUnsaved() if save is not None else self.initQuit()
def initUnsaved(self):
'''
If there is a save callback, there is unsaved changes
'''
self.setSubHeading('Unsaved changes, do you want to save first')
self.addButton('Save', Constants.DialogButtonRoles.YES)
self.addButton('Cancel', Constants.DialogButtonRoles.NO)
self.addButton('Don\'t Save', Constants.DialogButtonRoles.DESTRUCTIVE,
self.quit)
self.onAccept(lambda: (self.save(), self.quit()))
self.onReject(self.close)
def initQuit(self):
'''
If there is not a save callback, then don't ask the user to save
'''
self.setSubHeading('Are you sure you want to quit?')
self.addButton('Quit', Constants.DialogButtonRoles.YES)
self.addButton('Cancel', Constants.DialogButtonRoles.NO)
self.onAccept(self.quit)
self.onReject(self.close)
def quit(self):
'''
A helper method to wrap the instance quitting
'''
QCoreApplication.instance().quit()
| true |
d04baf27bda0ce3fb71c7e372643141575d12949 | Python | pirate777333/My_Small_Projects | /P11.py | UTF-8 | 1,886 | 3.53125 | 4 | [] | no_license | import turtle
import random
wn = turtle.Screen()
wn.title("snake game")
wn.bgcolor("green")
wn.setup(width=600, height=600)
head = turtle.Turtle()
head.ht()
head.speed(1)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
head.write("press space to start", font=("Verdana",
20, "normal"),align='center')
#head.goto(300, 300)
#head.goto(0, 0)
def up():
head.setheading(90)
#head.forward(100)
def down():
head.setheading(270)
#head.forward(100)
def left():
head.setheading(180)
#head.forward(100)
def right():
head.setheading(0)
#head.forward(100)
turtle.listen()
turtle.onkey(up, "Up")
turtle.onkey(down, "Down")
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
def start():
head.clear()
head.showturtle()
leaf=turtle.Turtle()
leaf.color("red")
leaf.shape("turtle")
leaf.penup()
leaf.goto(random.randint(-290,290), random.randint(-290,290))
b=1
while True:
head.forward(10)
if head.position()[0]>=300 or head.position()[0]<=-300 or head.position()[1]>=300 or head.position()[1]<=-300:
break
if leaf.position()[0]-20<=head.position()[0]<=leaf.position()[0]+20 and leaf.position()[1]-20<=head.position()[1]<=leaf.position()[1]+20:
leaf.goto(random.randint(-290,290), random.randint(-290,290))
head.shapesize(stretch_len=b)
b+=1
wn = turtle.Screen()
wn.title("snake game")
wn.bgcolor("green")
wn.setup(width=600, height=600)
head.ht()
head.speed(0)
head.goto(0, 0)
head.write("game over", font=("Verdana",
20, "normal"),align='center')
turtle.onkey(start, "space")
turtle.mainloop()
| true |
611aae611cae0904fc337345096582252f57d4d2 | Python | fsch2/blockly | /demos/drawbot/drawbot.py | UTF-8 | 1,923 | 2.625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | import sys
import time
import serial
import streamexpect
global ser
global exp
ser = None
exp = None
TIMEOUT = 5.0
DELIM = '\r\n'
def drawbot_init(port):
global ser
global exp
# close, if port was openend before
try:
ser.close()
except:
pass
try:
ser = serial.Serial(port, baudrate=2400, timeout=0)
exp = streamexpect.wrap(ser)
except:
print("Unable to open '{}!'".format(port))
return
ser.write(b"get\r\n")
exp.expect_regex(b"([A-Z]+)\r\n", timeout=TIMEOUT)
def write_command(cmd, args=[]):
print(cmd, args)
global ser
ser.write(cmd.encode())
if args:
argsstr = ' '.join(map(str, map(int, args)))
ser.write(' '.encode())
ser.write(argsstr.encode())
ser.write(DELIM.encode())
def drawbot_command(cmd, args=[]):
global exp
write_command(cmd, args)
m = exp.expect_regex(b" - ([A-Z]+)\r\n", timeout=TIMEOUT)
if m.groups[0] != b"OK":
print("Command {}, arguments {} failed!".format(cmd, args))
def drawbot_command_response(cmd, args=[]):
global exp
write_command(cmd, args)
m = exp.expect_regex(b" - ([a-zA-Z0-9 ]+) - ([A-Z]+)\r\n", timeout=TIMEOUT)
if m.groups[1] != b"OK":
print("Command {}, arguments {} failed!".format(cmd, args))
return m.groups[0].decode().split()
def drawbot_delay(delaysecs):
print("Wait a few seconds", end="")
for i in range(int(delaysecs)):
print(".", end="")
sys.stdout.flush()
time.sleep(1)
print("")
if __name__ == "__main__":
drawbot_init('/dev/pts/9')
drawbot_command('goto', ['142', '57'])
drawbot_command('drop')
drawbot_command('goto', ['67', '217'])
drawbot_command('goto', ['807', '280'])
drawbot_delay(3.2)
drawbot_command('move', ['40', '40'])
drawbot_command('move', ['40', '-40'])
drawbot_command('move', ['-40', '-40'])
| true |
b6ec73aeffbaef1db43e981bc47841de8923700e | Python | zstumgoren/betterpython | /elex2/election_results.py | UTF-8 | 5,415 | 3.40625 | 3 | [
"MIT"
] | permissive | """
In this second pass at the election_results.py script,
we chop up the code into functions.
USAGE:
python election_results.py
OUTPUT:
summary_results.csv
"""
import csv
import urllib.request
from operator import itemgetter
from collections import defaultdict
# Primary function that orchestrates all steps in the pipeline
def main():
raw_data = 'fake_va_elec_results.csv'
summary_csv = 'summary_results.csv'
print("Downloading raw election data: {}".format(raw_data))
download_results(raw_data)
print("Cleaning data...")
results = parse_and_clean(raw_data)
print("Tallying votes and assigning winners...")
summarized_results = summarize(results)
print("Generating report: {}".format(summary_csv))
write_csv(summarized_results, summary_csv)
#### Helper Functions ####
### These funcs perform the major steps of our application ###
def download_results(path):
"""Download CSV of fake Virginia election results from GDocs"""
url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vR66f495XUWKbhP48Eh1PtQ9mN_pbHTh2m-nma9sv0banZSORUJKcugDNKFzuUBhJ5tcsUMN6moYAHb/pub?gid=0&single=true&output=csv"
urllib.request.urlretrieve(url, path)
def parse_and_clean(path):
"""Parse downloaded results file and perform various data clean-ups
RETURNS:
Nested dictionary keyed by race, then candidate.
Candidate value is an array of dicts containing county level results.
"""
# Create reader for ingesting CSV as array of dicts
reader = csv.DictReader(open(path, 'r'))
# Use defaultdict to automatically create non-existent keys with an empty dictionary as the default value.
# See https://docs.python.org/3.8/library/collections.html#collections.defaultdict
results = defaultdict(dict)
# Initial data clean-up
for row in reader:
# Parse name into first and last
row['last_name'], row['first_name'] = [name.strip() for name in row['candidate'].split(',')]
# Convert total votes to an integer
row['votes'] = int(row['votes'])
# Store county-level results by slugified office and district (if there is one),
# then by candidate party and raw name
race_key = row['office']
if row['district']:
race_key += "-%s" % row['district']
# Create unique candidate key from party and name, in case multiple candidates have same
cand_key = "-".join((row['party'], row['candidate']))
# Below, setdefault initializes empty dict and list for the respective keys if they don't already exist.
race = results[race_key]
race.setdefault(cand_key, []).append(row)
return results
def summarize(results):
"""Tally votes for Races and candidates and assign winner flag.
RETURNS:
Dictionary of results
"""
summary = defaultdict(dict)
for race_key, cand_results in results.items():
all_votes = 0
cands = []
for cand_key, results in cand_results.items():
# Populate a new candidate dict using one set of county results
cand = {
'first_name': results[0]['first_name'],
'last_name': results[0]['last_name'],
'party': results[0]['party'],
'winner': '',
}
# Calculate candidate total votes
cand_total_votes = sum([result['votes'] for result in results])
cand['votes'] = cand_total_votes
# Add cand totals to racewide vote count
all_votes += cand_total_votes
# And stash the candidate's data
cands.append(cand)
# sort cands from highest to lowest vote count
sorted_cands = sorted(cands, key=itemgetter('votes'), reverse=True)
# Determine winner, if any
first = sorted_cands[0]
second = sorted_cands[1]
if first['votes'] != second['votes']:
first['winner'] = 'X'
# Get race metadata from one set of results
result = list(cand_results.values())[0][0]
# Add results to output
summary[race_key] = {
'all_votes': all_votes,
'date': result['date'],
'office': result['office'],
'district': result['district'],
'candidates': sorted_cands,
}
return summary
def write_csv(summary, csv_path):
"""Generates CSV from summary election results data
USAGE:
write_summary(summary_dict, csv_path)
"""
with open(csv_path, 'w') as fh:
# Limit output to cleanly parsed, standardized values
fieldnames = [
'date',
'office',
'district',
'last_name',
'first_name',
'party',
'all_votes',
'votes',
'winner',
]
writer = csv.DictWriter(fh, fieldnames, extrasaction='ignore', quoting=csv.QUOTE_MINIMAL)
writer.writeheader()
for results in summary.values():
cands = results.pop('candidates')
for cand in cands:
results.update(cand)
writer.writerow(results)
# Q: What on earth is this __name__ == __main__ thing?
# A: Syntax that let's you execute a module as a script.
# http://docs.python.org/2/tutorial/modules.html#executing-modules-as-scripts
if __name__ == '__main__':
main()
| true |
8354ab0f4a8a982fcb2ead6d4b72768ae2f899ff | Python | deng-peng/Machine-Learning-Test | /scikit_learn/tf-idf_test/tf-idf-test2.py | UTF-8 | 2,944 | 2.984375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import codecs
import os
import jieba
import jieba.posseg as pseg
import sys
import string
from sklearn import feature_extraction
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
# 对文档进行分词处理
def seg_words(s, c):
# 保存分词结果的目录
sFilePath = './segfile'
if not os.path.exists(sFilePath):
os.mkdir(sFilePath)
# 对文档进行分词处理,采用默认模式
seg_list = jieba.cut(s, cut_all=True)
# 对空格,换行符进行处理
result = []
for seg in seg_list:
seg = ''.join(seg.split())
if seg != '' and seg != "\n" and seg != "\n\n" and seg != "nbsp":
result.append(seg)
# 将分词后的结果用空格隔开,保存至本地。比如"我来到北京清华大学",分词结果写入为:"我 来到 北京 清华大学"
f = codecs.open('{}/{}-seg.txt'.format(sFilePath, c), "w+", 'utf8')
f.write(' '.join(result))
f.close()
# 读取已分词好的文档,进行TF-IDF计算
def tf_idf():
path = './segfile'
corpus = []
for i in range(1, 21):
fname = '{}/{}-seg.txt'.format(path, i)
print fname
f = codecs.open(fname)
content = f.read()
f.close()
corpus.append(content)
vectorizer = CountVectorizer()
transformer = TfidfTransformer()
tfidf = transformer.fit_transform(vectorizer.fit_transform(corpus))
word = vectorizer.get_feature_names() # 所有文本的关键字
weight = tfidf.toarray() # 对应的tfidf矩阵
s_file_path = './tfidffile'
if not os.path.exists(s_file_path):
os.mkdir(s_file_path)
# 这里将每份文档词语的TF-IDF写入tfidffile文件夹中保存
for i in range(len(weight)):
f = codecs.open('{}/{}.txt'.format(s_file_path, i), 'w+', 'utf8')
for j in range(len(word)):
f.write(word[j] + " " + str(weight[i][j]) + "\r\n")
f.close()
def show_key_words():
path = './tfidffile'
for i in range(1, 21):
fname = '{}/{}.txt'.format(path, i)
f = codecs.open(fname)
res = {}
for line in f:
arr = line.split("\t")
res[arr[0]] = arr[1].strip()
f.close()
sorted_arr = sorted(res.items(), key=lambda item: item[1], reverse=True)
res_arr = sorted_arr[:10]
ps = []
for k, v in res_arr:
ps.append(k)
print ', '.join(ps)
if __name__ == "__main__":
# f = codecs.open('../../make_dict/assets/articles_0.txt', 'r', encoding='utf-8')
# count = 0
# jieba.set_dictionary('../../res/extra_dict/dict.txt.big')
# for line in f:
# count += 1
# if count > 20:
# exit()
# seg_words(line.strip(), count)
tf_idf()
show_key_words()
| true |
4b6247ce5fe6a6f4daeaf6601f40e41ea7a66ef6 | Python | MaxouSenpai/INFO-F-404-Scheduling_Project | /source/Timeline.py | UTF-8 | 1,745 | 3.390625 | 3 | [] | no_license | from source.Event import Event
class Timeline:
"""
Class that represents a timeline that can contain several events.
"""
def __init__(self, timeLimit):
"""
Construct the timeline.
:param timeLimit: the time limit
"""
self.timeLimit = timeLimit
self.cpuState = [Event(Event.Type.IDLE) for _ in range(timeLimit)]
self.release = [[] for _ in range(timeLimit + 1)]
self.deadline = [[] for _ in range(timeLimit + 1)]
def addEvent(self, event, time):
"""
Add an event at a specified time.
It adds the event only if the specified
time is in the range of the timeline.
:param event: the event
:param time: the time
"""
if time < self.timeLimit + 1:
if event.getType() == Event.Type.RELEASE:
self.release[time].append(event)
elif event.getType() == Event.Type.DEADLINE:
self.deadline[time].append(event)
elif time < self.timeLimit:
self.cpuState[time] = event
def asString(self):
"""
Return the timeline as a string.
"""
result = ""
for t in range(self.timeLimit + 1):
result += str(t) + " : "
current = []
if len(self.release[t]) > 0:
current.append(" and ".join(e.asString() for e in self.release[t]))
if len(self.deadline[t]) > 0:
current.append(" and ".join(e.asString() for e in self.deadline[t]))
if t < self.timeLimit:
current.append(self.cpuState[t].asString())
result += " || ".join(current)
result += "\n"
return result
| true |
1818edb8fe0b0870a54310f341b3168995b317df | Python | diegovds/PSO2017B | /T6-PSO/t6-dsantos.py | ISO-8859-1 | 4,544 | 3.328125 | 3 | [] | no_license | # Implementado por Diego Viana dos Santos
# Script em Python que retorna consultas JSON utilizando a API de previso do tempo Advisor da Climatempo.
# Aps o retorno das consultas realizada a exibio das informaes retornadas por meio da biblioteca grfica Tkinter.
#!/usr/bin/env python3
import json, requests
from tkinter import *
#token para acesso a api Advisor da Climatempo
token = "coloque_aqui_o_token"
#Classe que manipula os objetos Previso
class Previsao(object):
def __init__(self, data, temp_min, temp_max, desc):
self.__data = data
self.__temp_min = temp_min
self.__temp_max = temp_max
self.__desc = desc
def __repr__(self):
return "Dia: %s | Temperatua Minma: %sC | Temperatua Mxima: %sC | Descrio: %s" % (self.__data, self.__temp_min, self.__temp_max, self.__desc)
def get_data(self):
return self.__data
def get_temp_min(self):
return self.__temp_min
def get_temp_max(self):
return self.__temp_max
def get_desc(self):
return self.__desc
#Acesso a previso da cidade
def busca_previsao(cod):
url_previsao_atual = 'http://apiadvisor.climatempo.com.br/api/v1/weather/locale/' + str(int(cod)) + '/current?token=' + token
url_previsao = 'http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/' + str(int(cod)) + '/days/15?token=' + token
try:
res = requests.get(url_previsao, stream=True)
res1 = requests.get(url_previsao_atual, stream=True)
dados = json.loads(res.text)
dados1= json.loads(res1.text)
lb3["text"] = " "
lb3["bg"] = "green"
lb3["text"] = "Busca da previso realizada com sucesso!!!"
previsao_total = dados['data']
previsao_atual = dados1['data']
lista = []
for previsao_dia in previsao_total:
data = previsao_dia['date_br']
temp_min = previsao_dia['temperature']['min']
temp_max = previsao_dia['temperature']['max']
desc = previsao_dia['text_icon']['text']['phrase']['reduced']
a = Previsao(data, temp_min, temp_max, desc)
lista.append(a)
textArea.insert(INSERT, dados['name'] + ", " + dados['state'] + " | Temperatua Atual : " + str(float(previsao_atual['temperature'])) + "C | Descrio: " + previsao_atual['condition'])
textArea.insert(INSERT, "\n\n")
for l in lista:
textArea.insert(INSERT, l)
textArea.insert(INSERT, "\n")
textArea.insert(INSERT, "\n")
except requests.exceptions.RequestException as e:
lb3["text"] = " "
lb3["bg"] = "red"
lb3["text"] = "Ocorreu um problema durante a busca da previso do tempo!!!"
#Acesso ao id da cidade
def busca_id_cidade(cidade, estado):
url_cod = 'http://apiadvisor.climatempo.com.br/api/v1/locale/city?name=' + cidade + '&state=' + estado + '&token=' + token
try:
res = requests.get(url_cod, stream=True)
dados = json.loads(res.text)
if len(dados) == 1:
cod = dados[0]['id']
busca_previsao(cod)
else:
lb3["text"] = " "
lb3["bg"] = "red"
lb3["text"] = "Ocorreu um problema durante a busca do id da cidade!!!"
except requests.exceptions.RequestException as e:
lb3["text"] = " "
lb3["bg"] = "red"
lb3["text"] = "Ocorreu um problema durante a busca da previso do tempo!!!"
def bt_click():
cidade = ed1.get()
estado = ed2.get()
busca_id_cidade(cidade, estado)
#main
janela = Tk()
#Formato(Largura x Altura + distncia da esquerda da tela + distncia do topo da tela)
janela.geometry("1200x500+100+150")
janela.title("Previso do tempo")
janela["bg"] = "silver"
#Labels
lb0 = Label(janela, text = "Previso do tempo:", bg = "blue")
lb0.pack(side = TOP, fill = X)
lb1 = Label(janela, text = "Digite o nome da cidade:", bg = "silver")
lb1.place(x = 5, y = 20)
lb2 = Label(janela, text = "Digite a sigla do estado:", bg = "silver")
lb2.place(x = 500, y = 20)
lb3 = Label(janela, text = " ", bg = "silver")
lb3.place(x = 5, y = 60)
#Entrada de texto
ed1 = Entry(janela)
ed1.place(x = 165, y = 20)
ed2 = Entry(janela)
ed2.place(x = 660, y = 20)
#Boto
bt1 = Button(janela, text = "Buscar previso!", command = bt_click)
bt1.place(x = 1000, y = 20)
#rea de Texto
textArea = Text(janela, width = 169)
textArea.place(x = 5, y = 100)
#Inicializa a janela
janela.mainloop() | true |
6b825efdb96b6e441bcda56b9447b206e4a2da66 | Python | epaulz/Extra_Practice | /project_euler/p1.py | UTF-8 | 154 | 3.71875 | 4 | [] | no_license | num = 1000
sum = 0
for x in range(1,num):
if x % 3 == 0 or x % 5 == 0:
sum += x
print "The sum of multiples of 3 or 5 below %d is %d" % (num, sum)
| true |
1f7001a0e65e3fe54ae63b68cb9d74eed1fc620b | Python | DenisAzarenko777/Cook_book | /Cook_book(modified).py | UTF-8 | 4,186 | 3.125 | 3 | [] | no_license | from collections import Counter
def list_forming_function():
file = open("recipes.txt")
onlist = file.read().split("\n")
some_list3 = []
# Делаем список списков (разбиваю каждый элемент строки на отдельный сисок)
for line in onlist:
some_list2 = []
if line != '':
some_list2.append(line)
some_list3.append(some_list2)
# Список для того чтобы из него удобней было делать словарь (групирую по блюдам)
some_list4 = []
some_list5 = []
for line in some_list3:
if line:
some_list4 = some_list4 + line
else:
some_list5.append(some_list4)
some_list4 = []
Cook_dict = {}
Key_list = []
# Делаю промежуточный словарь в котором есть ключи(уже нормальные ключи) и в качестве значений ключей есть список продуктов к которому они относятся
for element in some_list5:
if element[0]:
key = element[0]
Key_list.append(key)
number = int(element[1])
lis = []
for i in range(2, number+2, 1):
lis.append(element[i])
Cook_dict[key] = Cook_dict.get(key, []) + [lis]
request_list2 = list()
request_list3 = list()
for element in Cook_dict.values():
for el in element:
for e in el:
request_list = e.split("|")
request_list2.append(request_list)
request_list3.append(request_list2)
request_list2 = []
someone_list = list()
sl = list()
for element in request_list3:
for el in element:
half_dict = {}
half_dict['ingredient_name'] = el[0]
half_dict['quantity'] = el[1]
half_dict['measure'] = el[2]
sl.append(half_dict)
someone_list.append(sl)
sl = []
finally_dict = {}
# объединение списка с ключами(название блюда) со списком в котором лежит список половинчатых словарей(список в котором словари сгруппированны по блюдам)
for k,v in zip(Key_list, someone_list):
finally_dict[k] = v
# Конечный словарь __________________________________________________________________________
return finally_dict
#----------------------------------------------------------------------------------------------------------
def get_shop_list_by_dishes(dishes, person_count):
dishes = dishes
person = person_count
dish_name = []
dish_ingr = []
finally_dict = list_forming_function()
for i in dishes:
for j,k in finally_dict.items():
if i == j:
for ingr in k:
dish_name.append(ingr["ingredient_name"])
for i in dishes:
counter= dishes.count(i)
for j,k in finally_dict.items():
if i == j:
for ingr in k:
dish_ingr.append(ingr['measure'])
dish_ingr.append(int(ingr['quantity']) * person * counter)
function_dict = {}
list_for_dish = []
list_for_dish2 = []
i = 1
j = 0
for element in dish_ingr:
dish_dict = {}
if i % 2 != 0:
dish_dict['quantity'] = element
i = i + 1
j = j + 1
list_for_dish.append(dish_dict)
else:
dish_dict['measure'] = element
i = i + 1
j = j + 1
list_for_dish.append(dish_dict)
if j % 2 == 0:
list_for_dish2.append(list_for_dish)
list_for_dish = []
function_dict = {}
for k,v in zip(dish_name, list_for_dish2):
function_dict[k] = v
print(function_dict)
print(list_forming_function())
get_shop_list_by_dishes(['Омлет','Омлет','Утка по-пекински', 'Омлет'], 2)
| true |
f0762d10e825ce6f60e22debd8df0d409485266d | Python | mrinisami/problems | /35.py | UTF-8 | 813 | 3.6875 | 4 | [] | no_license | def searchInsert(nums, target) -> int:
high_end = len(nums) - 1
low_end = 0
mid = (high_end + 1 - low_end) // 2
if target < nums[0]:
return 0
elif target > nums[high_end]:
return high_end + 1
while True:
if target == nums[mid]:
return mid
elif high_end == low_end:
return high_end
elif nums[high_end] == target:
return high_end
elif nums[low_end] == target:
return low_end
elif high_end == low_end + 1:
return low_end + 1
if target < nums[mid]:
high_end = mid
mid -= (high_end - low_end) // 2
if target > nums[mid]:
low_end = mid
mid += (high_end - low_end) // 2
#tests
print(searchInsert([1,3,5,6], 7))
| true |
3df53b92ee65cabd2ae214e11ed737a6b2a2beae | Python | samrithasudhagar/guvi | /108.py | UTF-8 | 135 | 2.78125 | 3 | [] | no_license | n,k=map(int,input().split())
l=list(map(int,input().split()))
s=sorted(l)
c=0
for i in range(0,len(s)):
c=c+1
if c==k:
print(s[i])
| true |
c55ed7cb4f63c482a4b8ef11f6ff2020e672c871 | Python | 24emmory/Python-Crash-Course | /listcomprehensioncube.py | UTF-8 | 171 | 3.46875 | 3 | [] | no_license | cubes = [number**3 for number in range(1,10)]
print(cubes)
#name of list, list brackets, expression to run generated numbers through, and then for loop to generate numbers | true |
86ef13f4af25efc7a25dc65c72389dee29cd946c | Python | shadowlurker/spline | /spline/lib/markdown.py | UTF-8 | 1,994 | 2.921875 | 3 | [
"MIT"
] | permissive | """Handles Markdown translation."""
from __future__ import absolute_import
import lxml.html
import lxml.html.clean
import markdown
markdown_extensions = []
def register_extension(extension):
"""Registers the given markdown extension.
This is global and permanent; use with care!
"""
if not extension in markdown_extensions:
markdown_extensions.append(extension)
def translate(raw_text, chrome=False):
"""Takes a unicode string of Markdown source. Returns HTML."""
# First translate the markdown
md = markdown.Markdown(
extensions=markdown_extensions,
output_format='xhtml1',
)
html = md.convert(raw_text)
# Then sanitize the HTML -- whitelisting only, thanks!
# Make this as conservative as possible to start. Might loosen it up a bit
# later.
fragment = lxml.html.fromstring(html)
if chrome:
# This is part of the site and is free to use whatever nonsense it wants
allow_tags = None
else:
# This is user content; beware!!
allow_tags = [
# Structure
'p', 'div', 'span', 'ul', 'ol', 'li',
# Tables
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
# Embedding
'a',
# Oldschool styling
'strong', 'b', 'em', 'i', 's', 'u',
]
cleaner = lxml.html.clean.Cleaner(
scripts = True,
javascript = True,
comments = True,
style = True,
links = True,
meta = True,
page_structure = True,
#processing_instuctions = True,
embedded = True,
frames = True,
forms = True,
annoying_tags = True,
safe_attrs_only = True,
remove_unknown_tags = False,
allow_tags = allow_tags,
)
cleaner(fragment)
# Autolink URLs
lxml.html.clean.autolink(fragment)
# And, done. Flatten the thing and return it
return lxml.html.tostring(fragment)
| true |
c560d026eff9b7b32b75b9bc1269b16cdfee8334 | Python | sushilovinfun/Scrapy | /2012 Second Semester/wikiitem/mfitem/spiders/test.py | UTF-8 | 1,031 | 2.578125 | 3 | [] | no_license | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from mfitem.items import MfitemItem
class MySpider(BaseSpider):
name = "wiki"
allowed_domains = ["en.wikipedia.org"]
start_urls = ["http://en.wikipedia.org/wiki/Archive"]
def parse(self, response):
hxs = HtmlXPathSelector(response)
titles = hxs.select("/html/body")
items = []
for titles in titles:
item = MfitemItem()
item ["title"] = titles.select("//div/h1/span/text()").extract()
item ["text"] = titles.select("//div[@id='mw-content-text']/p/text()").extract()
item ["menu"] = titles.select("//div/div/div/h2/span/text()").extract()
item ["links"] = titles.select("//a/@href").extract()
item ["subs"] = titles.select("/html/body/div/div/div/h3/span/text()").extract()
item ["thumbcaps"] = titles.select("/html/body/div/div/div/div/div/div/text()").extract()
items.append(item)
return items | true |
ccc3e18eb525e3c648d1beed75da5b80e2fd941f | Python | mackenziedott/Python | /charCreate.py | UTF-8 | 2,673 | 3.75 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon May 01 19:17:55 2017
@author: Mackenzie
"""
def charCreate():
classlist = ["Bard", "Fighter", "Wizard", "Druid", "Barbarian", "Cleric", "Warlock", "Sorceror", "Rogue", "Ranger", "Paladin"]
classIntrostring = '''
What class does your character want to be? Enter the following to select your class:
1: Bard
2: Fighter
3: Wizard
4: Druid
5: Barbarian
6: Cleric
7: Warlock
8: Sorceror
9: Rogue
10: Ranger
11: Paladin
'''
racelist = ["Human", "Human (Variant)", "Elf", "Half-Elf", "Half-Orc", "Dwarf", "Gnome", "Halfling", "Tiefling", "Dragonborn"]
raceIntroString = '''
What Race does your character want to be? Enter the following to select your race:
1: Human
2: Human (variant)
3: Elf
4: Half-Elf
5: Half-Orc
6: Dwarf
7: Gnome
8: Halfling
9: Tiefling
10: Dragonborn
'''
statDistributionString = '''
1: Strength
2: Dexterity
3: Constitution
4: Intelligence
5: Wisdom
6: Charisma
'''
fixedstatDistributionString = textwrap.dedent(statDistributionString).strip()
fixedraceIntroString = textwrap.dedent(fixedraceIntroString).strip()
StatList = [0,0,0,0,0,0]
fixedClassIntrostring = textwrap.dedent(classIntrostring).strip()
print fixedClassIntrostring
print("Time to make your character\n")
print("First step is Stat Distribution using standard distribution\n")
print(fixedstatDistributionString)
selstat1 = input("What stat do you want 15 in: ")
selstat1int = int(selsat1)
selstat2 = input("What stat do you want 14 in: ")
selstat2int = int(selsat2)
selstat3 = input("What stat do you want 13 in: ")
selstat3int = int(selsat3)
selstat4 = input("What stat do you want 12 in: ")
selstat4int = int(selsat4)
selstat5 = input("What stat do you want 10 in: ")
selstat5int = int(selsat5)
selstat6 = input("What stat do you want 8 in: ")
selstat6int = int(selsat6)
StatList(selstat1int) = 15
StatList(selstat2int) = 14
StatList(selstat3int) = 13
StatList(selstat4int) = 12
StatList(selstat5int) = 10
StatList(selstat6int) = 8
#Class Selction
print(classIntrostring)
selclass = input("Enter what class you want: ")
selclassint = int(selclass)
dclass = classlist(selclassint)
#Race Selction
print(raceIntroString)
selrace = input("Enter what Race you want: ")
selraceint = int(selrace)
name = input("what is your character's name? ")
drace = racelist(selraceint)
data = StatList.append([dclass, drace, name])
return [data]
| true |
1794c6de70ed9dbd4a4f139dfd6763c6d7a39050 | Python | lffranca/creme | /creme/datasets/elec2.py | UTF-8 | 1,674 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | from .. import stream
from . import base
class Elec2(base.FileDataset):
"""Electricity prices in New South Wales.
This data was collected from the Australian New South Wales Electricity Market. In this market,
prices are not fixed and are affected by demand and supply of the market. They are set every
five minutes. Electricity transfers to/from the neighboring state of Victoria were done to
alleviate fluctuations.
Parameters:
data_home: The directory where you wish to store the data.
verbose: Whether to indicate download progress or not.
References:
1. [SPLICE-2 Comparative Evaluation: Electricity Pricing](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.12.9405)
2. [DataHub description](https://datahub.io/machine-learning/electricity#readme)
"""
def __init__(self, data_home: str = None, verbose=False):
super().__init__(
n_samples=45_312,
n_features=8,
category=base.BINARY_CLF,
url='https://maxhalford.github.io/files/datasets/electricity.zip',
data_home=data_home,
verbose=verbose
)
def _stream_X_y(self, directory):
return stream.iter_csv(
f'{directory}/electricity.csv',
target='class',
converters={
'date': float,
'day': int,
'period': float,
'nswprice': float,
'nswdemand': float,
'vicprice': float,
'vicdemand': float,
'transfer': float,
'class': lambda x: x == 'UP'
}
)
| true |
e974749d0db97ec572c5b59e7cd86a232c2f1b4a | Python | acoltelli/Algorithms-DataStructures | /Ch1Solutions.py | UTF-8 | 2,680 | 3.53125 | 4 | [] | no_license | import random
import string
length= 12
randomString=''.join(random.choice(string.ascii_letters) for i in range(length))
randomString2=''.join(random.choice(string.ascii_letters) for i in range(length))
# CCI q1.1
def isCharUnique(str):
var=0
for i in str:
var+=1
count = str.count(i)
if count>1:
return False
break
elif var>=len(str):
return True
#CCI q1.3
def removeChar(str):
x=0
y=len(str)
for i in str:
x+=1
count = str.count(i)
if count>1:
var=str.replace(i, '',count-1)
str=var
if x==y:
return str
#CCI q1.4
def isAnagram(s1,s2):
a=list(s1)
b=list(s2)
a.sort()
b.sort()
if a==b:
return True
else:
return False
#CCI q1.5
def repl_(str):
var=str.replace(' ', '%20')
str=var
return var
def repl(str):
lst = list(str)
temp = list()
for i in lst:
if i == ' ':
i = '%20'
temp.append(i)
else:
temp.append(i)
return ''.join(temp)
#CCI q1.6
#rotate NxN matrix 90 degrees, clockwise
def rotateMatrixClockwise(originalMatrix):
newMatrix = [i[:] for i in originalMatrix]
length = len(originalMatrix[0])
for row in range(0,length):
for column in range(0,length):
newMatrix[column][length-(row+1)] = originalMatrix[row][column]
return newMatrix
#rotate 90 degrees, counterclockwise
def rotateMatrixCounterclockwise(originalMatrix):
newMatrix = [i[:] for i in originalMatrix]
length = len(originalMatrix[0])
for row in range(0,length):
for column in range(0,length):
newMatrix[length-(column+1)][row] = originalMatrix[row][column]
return newMatrix
# CCI 1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0
#TODO: refactor
zeros=[]
def locateZeros(matrix):
for row, rowElements in enumerate(matrix):
for column, colElements in enumerate(rowElements):
if colElements == 0:
zeros.append((row,column))
return zeros
def setZeros(matrix):
zeros=locateZeros(matrix)
for row, rowElements in enumerate(matrix):
for column, colElements in enumerate(rowElements):
if row in (i[0] for i in zeros) or column in (i[1] for i in zeros):
matrix[row][column] = 0
return matrix
#CCI q1.8
def isSubstring(str1, str2):
var=str1.find(str2)
#find: index if found, -1 otherwise
if var>-1:
return True
else:
return False
def isRotation(st1,st2):
str=st1+st1
if isSubstring(str,st2)==True:
return True
elif isSubstring(str,st2)==False:
return False
| true |
54dfa2146e313b2911f822700231f432376cdddc | Python | Alex92rus/ErrorDetectionProject | /classifier/class_util.py | UTF-8 | 4,150 | 3.21875 | 3 | [
"Apache-2.0"
] | permissive | from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# plotting functions
def create_confusion_matrix(data, predictions):
"""
Creates a confusion matrix that counts for each gold label how often it was labelled by what label
in the predictions.
Args:
data: a list of gold (x,y) pairs.
predictions: a list of y labels, same length and with matching order.
Returns:
a `defaultdict` that maps `(gold_label,guess_label)` pairs to their prediction counts.
"""
confusion = defaultdict(int)
for y_gold, y_guess in zip(data, predictions):
confusion[(y_gold, y_guess)] += 1
return confusion
def plot_confusion_matrix_dict(matrix_dict, rotation=45, outside_label=""):
labels = set([y for y, _ in matrix_dict.keys()] + [y for _, y in matrix_dict.keys()])
sorted_labels = sorted(labels)
matrix = np.zeros((len(sorted_labels), len(sorted_labels)))
for i1, y1 in enumerate(sorted_labels):
for i2, y2 in enumerate(sorted_labels):
if y1 != outside_label or y2 != outside_label:
matrix[i1, i2] = matrix_dict[y1, y2]
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.Blues)
plt.colorbar()
tick_marks = np.arange(len(sorted_labels))
plt.xticks(tick_marks, sorted_labels, rotation=rotation)
plt.yticks(tick_marks, sorted_labels)
plt.xlabel('predicted labels')
plt.ylabel('gold labels')
plt.tight_layout()
plt.show()
def full_evaluation_table(confusion_matrix):
"""
Produce a pandas data-frame with Precision, F1 and Recall for all labels.
Args:
confusion_matrix: the confusion matrix to calculate metrics from.
Returns:
a pandas Dataframe with one row per gold label, and one more row for the aggregate of all labels.
"""
labels = sorted(list({l for l, _ in confusion_matrix.keys()} | {l for _, l in confusion_matrix.keys()}))
gold_counts = defaultdict(int)
guess_counts = defaultdict(int)
for (gold_label, guess_label), count in confusion_matrix.items():
if gold_label != "None":
gold_counts[gold_label] += count
gold_counts["[All]"] += count
if guess_label != "None":
guess_counts[guess_label] += count
guess_counts["[All]"] += count
result_table = []
for label in labels:
if label != "None":
result_table.append((label, gold_counts[label], guess_counts[label], *evaluate(confusion_matrix, {label})))
result_table.append(("[All]", gold_counts["[All]"], guess_counts["[All]"], *evaluate(confusion_matrix)))
return pd.DataFrame(result_table, columns=('Label', 'Gold', 'Guess', 'Precision', 'Recall', 'F1'))
def evaluate(conf_matrix, label_filter=None):
"""
Evaluate Precision, Recall and F1 based on a confusion matrix as produced by `create_confusion_matrix`.
Args:
conf_matrix: a confusion matrix in form of a dictionary from `(gold_label,guess_label)` pairs to counts.
label_filter: a set of gold labels to consider. If set to `None` all labels are considered.
Returns:
Precision, Recall, F1 triple.
"""
tp = 0
tn = 0
fp = 0
fn = 0
for (gold, guess), count in conf_matrix.items():
if label_filter is None or gold in label_filter or guess in label_filter:
if gold == 'None' and guess != gold:
fp += count
elif gold == 'None' and guess == gold:
tn += count
elif gold != 'None' and guess == gold:
tp += count
elif gold != 'None' and guess == 'None':
fn += count
else: # both gold and guess are not-None, but different
fp += count if label_filter is None or guess in label_filter else 0
fn += count if label_filter is None or gold in label_filter else 0
prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
f1 = 2 * prec * recall / (prec + recall) if prec * recall > 0 else 0.0
return prec, recall, f1 | true |
3561bf14682c342614e571c55faf505369fbad0c | Python | Ujjawal-Indwar/Web-Scrape | /main.py | UTF-8 | 876 | 3.078125 | 3 | [] | no_license | import re
import requests
from bs4 import BeautifulSoup
from collections import Counter
url = "https://venturebeat.com/"
regex_url = url.replace(":","\:").replace("/","\/").replace(".","\.")
response = requests.get(url)
html = response.text
#print(response.text[:1000])
soup = BeautifulSoup(html, "html.parser")
links = soup.findAll("a")
news_urls = []
for link in links:
href = link.get("href")
if href and re.search("^" + regex_url + "[0-9]{4}\/[0-9]{2}\/[0-9]{2}", href):
news_urls.append(href)
all_nouns = []
#for url in news_urls[:20]:
for url in news_urls:
#print("Fetching{}".format(url))
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, "html.parser")
words = soup.text.split()
nouns = [word for word in words if re.search("^[A-Z][a-zA-Z]*",word)]
all_nouns += nouns
print(Counter(all_nouns).most_common(100)) | true |
9494a5c16066a6cf1728c9935e0df198a4e7a317 | Python | tenqaz/crazy_arithmetic | /leetcode/剑指offer/剑指 Offer 63. 股票的最大利润.py | UTF-8 | 827 | 3.734375 | 4 | [] | no_license | """
@author: zwf
@contact: zhengwenfeng37@gmail.com
@time: 2023/7/16 10:05
@desc:
"""
from typing import List
from math import inf
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
每次循环,将当前值与前面的最小值相减取得到当前最大的利润值,然后和前面的最大利润值去最大值。
再获取当前最小值。
时间复杂度: O(n)
控件复杂度: O(1)
Args:
prices:
Returns:
"""
max_profit = 0
min_price = inf
for price in prices:
max_profit = max(price - min_price, max_profit)
min_price = min(price, min_price)
return max_profit
if __name__ == '__main__':
print(Solution().maxProfit([7, 1, 5, 3, 6, 4]))
| true |
d1d36df5495ae78d443409881227bec52a74a06f | Python | FullteaR/naturalLanguageProcessing100Knock | /knock02.py | UTF-8 | 123 | 2.84375 | 3 | [] | no_license | patrol = "パトカー"
taxi = "タクシー"
result = ""
for p, t in zip(patrol, taxi):
result += p + t
print(result)
| true |
112907e3405c8c16a5dfe6bb065b72daf202b273 | Python | foundling/Flashcard | /__init__.py | UTF-8 | 5,712 | 3.09375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: <encoding name> -*-
# Flashcard
#
# A text-based, quiz-yourself application
# copyright (c) 2015 by Alex Ramsdell
import os, sys
from config import *
from store import Database
from quiz import QuizEngine
from helper_funcs import *
import headers
def main_menu(db):
clear_screen()
prompt('Current Card Set: %s' % (db.db_name.upper()),False)
prompt('Please Choose an Option from the Menu',False)
choices = [ 'Create a New Card Set',
'Load Card Set',
'Show Current Card Set',
'Add Cards to Current Card Set',
'Quiz Yourself\n',
'Info',
'Configuration & Settings',
'Quit'
]
response = prompt('\n'.join("({}) {}".format(n,v) for n,v in enumerate(choices, start=1)) + '\n')
if response in ['1']:
db = create_new_card_set(db)
elif response in ['2']:
db = load_card_set()
elif response in ['3']:
show_current_card_set(db)
elif response in ['4']:
add_to_existing_card_set(db)
elif response in ['5']:
quiz_yourself(db)
elif response in ['q','Q','8']:
sys.exit(0)
return main_menu(db)
def create_new_card_set(db, e=None):
clear_screen()
headers.new_card_set_header()
if e:
cardset_name = clean( prompt(e) )
else:
cardset_name = clean( prompt('Please Enter a NAME for your new Flashcard Set:\n\n') )
if db_exists(cardset_name): # file_exists default dir is db/
e = 'This card set already exists. Please Choose Another Name:\n'
return create_new_card_set(db, e)
else:
db.cur.close() #wrap up before rebinding to new db object
db.con.close()
db = Database(cardset_name)
response = prompt('\nCard Set "%s" created successfully.\n\nAdd cards now? [y/N]: ' % (cardset_name))
if response in ['y','Y']:
response = prompt('\nDo you want to add the cards\n\n(1) manually, or \n(2) or parse them from a structured file? ')
if response in ['1']:
load_cards_manually(db)
elif response in ['2']:
load_cards_from_file(db)
else:
error_msg = "ERROR: You didn't provide a valid name."
create_new_card_set(error_msg)
return db
# ACTIVATE CARD SET
def load_card_set(error_msg=None):
# should return a new database
clear_screen()
cardsets = [ (DB_DIR + f) for f in os.listdir(DB_PATH) if f.endswith('.db') ]
cardsets.sort(key=os.path.getctime)
if cardsets:
prompt('Please Choose a Cardset:', False)
print '\n'.join('({}) {}'.format(n,os.path.basename(v)) for n,v in enumerate(cardsets,start=1))
response = prompt()
if not response:
load_card_set('Please enter a valid number in the range of %d and %d' % (1,len(cardsets)))
response_index = int(response) - 1
cardset_name = os.path.basename(cardsets[response_index]).split('.db')[0]
db = Database(cardset_name)
if db.db_name:
prompt('Card Set Loaded!')
return db
else:
prompt('You have no Card Sets. Hit any Key to return to the main Menu')
# PUT NEW CARDS INTO DB, ONE BY ONE
def load_cards_manually(db):
clear_screen()
headers.load_cards_header()
front,back = None, None
while True:
prompt("Enter 'q' or 'Q' into either field to quit at any time",False)
front = prompt("FRONT: ")
if front in ['q','Q']:
break
back = prompt("BACK: ")
if back in ['q','Q']:
break
db.addCard(front,back)
# PARSE A FILE INTO CARDS
def load_cards_from_file(db):
clear_screen()
available_files = show_available_files(PARSE_FILES_DIR)
if available_files:
prompt('PLEASE CHOOSE FROM AVAILABLE FILES: \n',False)
for n,v in enumerate(available_files):
print "({}) {}".format(n,os.path.basename(v))
response = prompt('Your choice: ')
try:
index = int(response.strip())
available_files[index]
except IndexError:
print 'not a valid choice'
load_cards_from_file(db)
else:
headers.error_header('ERROR: No files available for parsing. \nMake sure to place your parsable files in:\n [ %s ]. \nPress any key to return to the MAIN MENU.')
prompt('\nERROR: No files available for parsing.\n\nMake sure to place your parsable files in:\n\n### %s ###.\n\nPress any key to return to the MAIN MENU.' % (os.path.dirname(PARSE_FILES_DIR)))
def show_current_card_set(db):
clear_screen()
headers.current_card_set_header()
prompt("Card Set: %s" % db.db_name.upper(),False)
print_cardset(db)
prompt('\nHit Any Key to Return to the Main Menu')
def add_to_existing_card_set(db):
clear_screen()
headers.load_cards_header()
front,back = None, None
while True:
prompt("Enter 'q' or 'Q' into either field to quit at any time",False)
front = prompt("FRONT: ")
if front in ['q','Q']:
break
back = prompt("BACK: ")
if back in ['q','Q']:
break
db.addCard(front,back)
def quiz_yourself(db,e=None):
clear_screen()
headers.quiz_header()
if e:
prompt(e,False)
cards = load_cards_into_memory(db)
quiz = QuizEngine(cards,db.db_name)
choices = ['Randomize Cards', 'Reverse Cards', 'Keep Current Card Order']
quiz_type = prompt( '\n'.join("({}) {}".format(num,val) for num, val in enumerate(choices, start=1)) )
if quiz_type in ['1','2','3']:
quiz.startQuiz(quiz_type)
elif quiz_type in ['q','Q']:
sys.exit(0)
else:
e = "That's Not a Valid Choice. (If you want to quit, enter 'q' or 'Q')"
return quiz_yourself(db,e)
def main(db):
while True:
db = main_menu(db)
if __name__ == '__main__':
clear_screen()
headers.title_page()
prompt()
db = Database() # flashcard is default db
main(db)
| true |
882f722f22327bd7da3c8466c2d314b406acafef | Python | Wesleyfsilva/Exercicios-python | /Ex23.py | UTF-8 | 527 | 3.796875 | 4 | [] | no_license | preco1 = float(input("Digite o preço do primeiro produto: "))
preco2 = float(input("Digite o preço do segundo produto: "))
preco3 = float(input("Digite o preço do terceiro produto: "))
if preco1 < preco2 and preco1 < preco3:
print("Voce deve comprar o primeiro produto,no valor de {:.2f}".format(preco1))
elif preco2 < preco1 and preco2 < preco3:
print("Voce deve comprar o segundo produto,no valor de {:.2f}".format(preco2))
else:
print("Voce deve comprar o terceiro produto,no valor de {:.2f}".format(preco3)) | true |
cafcbd66446c0edc5f9276c247a6020b38c90aa2 | Python | finzellt/novae | /utils/dates.py | UTF-8 | 799 | 2.8125 | 3 | [] | no_license | import re
__all__ = ['convert_date_UTC']
#works only for 1931-2030
def convert_date_UTC(date):
if re.match(r"\d(\d)?[/:\-]\d[/:\-]", date):
i = re.match(r"\d(\d)?[/:\-]", date).end()
date = date[:i] + "0" + date[i:]
if re.match(r"\d[/:\-]\d(\d)?[/:\-]", date):
date = "0" + date
year, month, day = "","",""
if re.match(r"\d\d[/:\-]\d\d[/:\-]\d\d(\d\d)?$", date):
year = date[6:] if re.match(r"\d\d[/:\-]\d\d[/:\-]\d\d\d\d$", date) else ("19" + date[6:] if int(date[6:]) > 30 else "20" + date[6:])
if int(date[3:5]) > 12:
day = date[3:5]
month = date[0:2]
else:
day = date[0:2]
month = date[3:5]
elif re.match(r"\d\d\d\d[/:\-]\d\d[/:\-]\d\d$", date):
return date
else:
raise ValueError("Not a valid date.")
return ""
return ("%s-%s-%s" %(year, month, day))
| true |
0bc010ff695739c1db7f53995572c06108aa4154 | Python | courses-learning/python-crash-course | /5-10_checking_usernames.py | UTF-8 | 478 | 3.84375 | 4 | [] | no_license | # Create a program that simulates how websites ensure all have unique usernames
def get_new():
new = input("Hello new user. Please enter your username: ").upper()
while new in usernames:
new = input("Sorry that username is taken. Please select another: ").upper()
return new
usernames = ["DAVID1664", "JOEW5", "NICOLA83P", "ADMIN", "LUKE22"]
new = get_new()
usernames.append(new)
print("\nList of current users:")
for user in usernames:
print(user)
| true |
ff52cae2d6b590f528bb620c6e9d017c455da73b | Python | vjimw/django-reportengine | /reportengine/filtercontrols.py | UTF-8 | 5,582 | 2.921875 | 3 | [
"BSD-2-Clause"
] | permissive | """Based loosely on admin filterspecs, these are more focused on delivering controls appropriate per field type
Different filter controls can be registered per field type. When assembling a set of filter controls, these field types will generate the appropriate set of fields. These controls will be based upon what is appropriate for that field. For instance, a datetimefield for filtering requires a start/end. A boolean field needs an "all", "true" or "false" in radio buttons.
"""
from django import forms
from django.db import models
from django.utils.translation import ugettext as _
# TODO build register and lookup functions
# TODO figure out how to manage filters and actual request params, which aren't always 1-to-1 (e.g. datetime)
class FilterControl(object):
filter_controls=[]
def __init__(self,field_name,label=None):
self.field_name=field_name
self.label=label
def get_fields(self):
if hasattr(self, 'choices'):
return {self.field_name:forms.ChoiceField(label=self.label or self.field_name,
required=False, choices=self.choices)}
else:
return {self.field_name:forms.CharField(label=self.label or self.field_name,required=False)}
# Pulled from django.contrib.admin.filterspecs
def register(cls, test, factory, datatype):
cls.filter_controls.append((test, factory, datatype))
register = classmethod(register)
def create_from_modelfield(cls, f, field_name, label=None):
# get choices for Foreign Key plus Char and Integer fields with choices set to change to and to populate select widget
if hasattr(f, 'get_choices'):
try:
cls.choices = f.get_choices()
except(AttributeError):
# all charfields have get_choices
# but if no choices are set, which is normally the case
# this error is thrown because Django assumes
# there is a foreign key relationship to follow
# there is not, so pass
pass
for test, factory, datatype in cls.filter_controls:
if test(f):
return factory(field_name,label)
create_from_modelfield = classmethod(create_from_modelfield)
def create_from_datatype(cls, datatype, field_name, label=None):
for test, factory, dt in cls.filter_controls:
if dt == datatype:
return factory(field_name,label)
create_from_datatype = classmethod(create_from_datatype)
FilterControl.register(lambda m: isinstance(m,models.CharField),FilterControl,"char")
FilterControl.register(lambda m: isinstance(m,models.IntegerField),FilterControl,"integer")
class DateTimeFilterControl(FilterControl):
def get_fields(self):
ln=self.label or self.field_name
start=forms.CharField(label=_("%s From")%ln,required=False,widget=forms.DateTimeInput(attrs={'class': 'vDateField'}))
end=forms.CharField(label=_("%s To")%ln,required=False,widget=forms.DateTimeInput(attrs={'class': 'vDateField'}))
return {"%s__gte"%self.field_name:start,"%s__lt"%self.field_name:end}
FilterControl.register(lambda m: isinstance(m,models.DateTimeField),DateTimeFilterControl,"datetime")
class BooleanFilterControl(FilterControl):
def get_fields(self):
return {self.field_name:forms.CharField(label=self.label or self.field_name,
required=False,widget=forms.Select(choices=(('','All'),('1','True'),('0','False'))),initial='A')}
FilterControl.register(lambda m: isinstance(m,models.BooleanField),BooleanFilterControl,"boolean")
class ForeignKeyFilterControl(FilterControl):
def get_fields(self):
return {self.field_name:forms.ChoiceField(label=self.label or self.field_name,
required=False, choices=self.choices)}
FilterControl.register(lambda m: isinstance(m,models.ForeignKey),ForeignKeyFilterControl,"foreignkey")
# TODO add a filter control that is not based on a field, but on a method that returns a query or data to filter by
class CustomMaskFilterControl(FilterControl):
# this is not a filter based on a field on the model in question; however it will be related to the field for filtering but have a number of subconditions
# Effectively a subreport used to the filter the larger report
def __init__(self, field_name, label=None):
self.field_name=field_name
self.label=label
def get_fields(self):
return {"%s__custom_mask"%self.field_name:forms.BooleanField(label=self.label or self.field_name, required=False)}
# TODO How do I register this one?
class StartsWithFilterControl(FilterControl):
def get_fields(self):
return {"%s__startswith"%self.field_name:forms.CharField(label=_("%s Starts With")%(self.label or self.field_name),
required=False)}
class ContainsFilterControl(FilterControl):
def get_fields(self):
return {"%s__icontains"%self.field_name:forms.CharField(label=_("%s Contains")%(self.label or self.field_name),
required=False)}
class ChoiceFilterControl(FilterControl):
def __init__(self, *args, **kwargs):
self.choices = kwargs.pop('choices', [])
self.initial = kwargs.pop('initial', None)
super(ChoiceFilterControl, self).__init__(*args, **kwargs)
def get_fields(self):
return {self.field_name: forms.ChoiceField(
choices=self.choices,
label=self.label or self.field_name,
required=False,
initial=self.initial,
)}
| true |
5aa43240fea7a7f93823a93f5b5b16cc3f771d17 | Python | assaultpunisher/Leet_Code | /Hard/Python 3/Trapping_Rain_Water(42).py | UTF-8 | 609 | 3.09375 | 3 | [
"MIT"
] | permissive | class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)
if n < 3:
return 0
l = height[0]
r = height[n-1]
i = 0
j = n - 1
res = 0
while i < j:
if r < l:
j -= 1
if height[j] < r:
res += r - height[j]
else:
r = height[j]
else:
i += 1
if height[i] < l:
res += l - height[i]
else:
l = height[i]
return res | true |
6509da4ce5d879991c133ab1a8184c282d3f36b9 | Python | adib1996/Neo4j_Graph_Generator | /read_data_module.py | UTF-8 | 793 | 2.828125 | 3 | [] | no_license | import os
import pandas as pd
def remove_quotes(x):
if x != "":
return x[1:-1]
else:
return x
def read_data(input_data_path, triplets_file_names):
for i in range(len(triplets_file_names)):
if i == 0:
data = pd.read_csv(os.path.join(input_data_path, triplets_file_names[i]), low_memory=False)
else:
data = pd.concat([data, pd.read_csv(os.path.join(input_data_path, triplets_file_names[i]), low_memory=False)])
# Making the missing values to empty strings
for col in list(data.columns):
data.loc[data[col].isnull(), col] = ""
# Checking whether Record Tag is present or not - if not create one
if 'Record Tag' not in list(data.columns):
data.loc[:, 'Record Tag'] = 'common'
return data
| true |
821543d71a482487e57c58df96093c4ef8be344a | Python | anushavajha/CottonPricePrediction | /cottonpriceprediction/Data Formatting Scripts/Districts_Markets.py | UTF-8 | 1,498 | 3.28125 | 3 | [] | no_license | import pandas as pd
df = pd.read_csv('CottonData.csv')
#Data Cleaning
df = df[df['Price'] > 0]
df = df[df['Price'] < 13000]
#DATE MERGING
df['Day']=df['Day'].apply(lambda x: '{0:0>2}'.format(x))
df['Month']=df['Month'].apply(lambda x: '{0:0>2}'.format(x))
df['Year'] = df['Year'].apply(str)
df['Day']=df['Day'].apply(str)
df['Month']=df['Month'].apply(str)
df['date'] = df['Year'].str.cat(df['Month'], sep ="-")
df['date'] = df['date'].str.cat(df['Day'], sep ="-")
df = df.drop(['Day', 'Month', "Year"], axis=1)
df_prop= pd.DataFrame()
df_prop['ds'] = pd.to_datetime(df["date"])
df_prop['y'] = df["Price"]
df_prop['State'] = df["State"]
df_prop['District'] = df["District"]
df_prop['Market'] = df["Market"]
# Encoding Categorical Columns
df_prop['State'] = df_prop['State'].astype('category')
df_prop['District'] = df_prop['District'].astype('category')
df_prop['Market'] = df_prop['Market'].astype('category')
df_prop['State_Code'] = df_prop['State'].cat.codes
df_prop['District_Code'] = df_prop['District'].cat.codes
df_prop['Market_Code'] = df_prop['Market'].cat.codes
#making dictionaries for categorical attributes
state_dict = pd.Series(df_prop.State_Code.values, index=df_prop.State).to_dict()
district_dict = pd.Series(df_prop.District_Code.values, index=df_prop.District).to_dict()
market_dict = pd.Series(df_prop.Market_Code.values, index=df_prop.Market).to_dict()
df_prop = df_prop.drop(['State', 'District', 'Market'], axis=1)
print(state_dict) | true |
073f212117191e2ffb980faf2cc2599c62edf4ac | Python | misohan/Udemy | /Test_udemy.py | UTF-8 | 1,419 | 4.53125 | 5 | [] | no_license | # numbers = 1, 2, 3, data type integer
# strings = "ahoj", data type string
# lists = [], can be changed
# tuples = (), can not be changed
# dictionary = {}, key values
multiplication = 2.005*50
print(multiplication)
divison = 401/4
print(divison)
exponent = 10.01249219725040309**2
print(exponent)
addition = 100+0.25
print(addition)
substraction = 100.5-0.25
print(substraction)
# What is the value of the expression 4 * (6 + 5)
# 44
first = 4 * (6 + 5)
print(first)
# What is the value of the expression 4 * 6 + 5
# 29
second = 4 * 6 + 5
print(second)
# What is the value of the expression 4 + 6 * 5
# 34
third = 4 + 6 * 5
print(third)
# What is the type of the result of the expression 3 + 1.5 + 4?
# expression = 8.5, it is a float
# Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below:
s0 = 'hello'
# Print out 'e' using indexing
print(s0[1])
# Reverse the string 'hello' using slicing:
s1 = 'hello'
# Reverse the string using slicing
print(s1[::-1])
# Given the string hello, give two methods of producing the letter 'o' using indexing.
s2 ='hello'
# Print out the 'o'
# Method 1:
print(s2[-1])
# Method 2:
print(s2[4])
# Build this list [0,0,0] two separate ways.
# Method 1:
# Method 2:
# Reassign 'hello' in this nested list to say 'goodbye' instead:
list3 = [1,2,[3,4,'hello']]
for i in list3:
list3[2][2] = 'goodbye'
print(list3)
| true |
aeb4cabfe56540e81b30486e919b04b61670874d | Python | usnistgov/xml_utils | /xml_utils/xsd_tree/operations/attribute.py | UTF-8 | 1,683 | 3.421875 | 3 | [
"BSD-3-Clause",
"MIT",
"NIST-Software"
] | permissive | """XSD Tree operations on attributes
"""
from xml_utils.xsd_tree.operations.namespaces import get_namespaces
from xml_utils.xsd_tree.operations.xpath import get_element_by_xpath
from xml_utils.xsd_tree.xsd_tree import XSDTree
def set_attribute(xsd_string, xpath, attribute, value):
"""Sets an attribute of an element
Args:
xsd_string:
xpath:
attribute:
value:
Returns:
"""
return _update_attribute(xsd_string, xpath, attribute, value)
def delete_attribute(xsd_string, xpath, attribute):
"""Deletes an attribute from an element
Args:
xsd_string:
xpath:
attribute:
Returns:
"""
return _update_attribute(xsd_string, xpath, attribute)
def _update_attribute(xsd_string, xpath, attribute, value=None):
"""Updates an attribute (sets the value or deletes)
Args:
xsd_string:
xpath: xpath of the element to update
attribute: name of the attribute to update
value: value of the attribute to set
Returns:
"""
# Build the XSD tree
xsd_tree = XSDTree.build_tree(xsd_string)
# Get namespaces
namespaces = get_namespaces(xsd_string)
# Get XSD element using its xpath
element = get_element_by_xpath(xsd_tree, xpath, namespaces)
# Add or update the attribute
if value is not None:
# Set element attribute with value
element.attrib[attribute] = value
else:
# Deletes attribute
if attribute in element.attrib:
del element.attrib[attribute]
# Converts XSD tree back to string
updated_xsd_string = XSDTree.tostring(xsd_tree)
return updated_xsd_string
| true |
d07f91a3a663fdfec96617503aa41f793d089053 | Python | DiegoVieiras/Python.io | /q14.py | UTF-8 | 837 | 3.875 | 4 | [] | no_license | #João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar
#o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes
#maior que o estabelecido pelo regulamento de pesca do estado de São Paulo
#(50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa
#que você faça um programa que leia a variável peso (peso de peixes) e calcule
#o excesso. Gravar na variável excesso a quantidade de quilos além do limite
#e na variável multa o valor da multa que João deverá pagar. Imprima os dados
#do programa com as mensagens adequadas.
peso = float(input("Qual o peso total do peixe que você pescou: "))
excesso = (peso - 50) * 4
if peso>50:
{
print("\nVocê vai pagar sobre o excesso: R$", round(excesso,2))
}
else:
print("\nNão tem custo sobre excesso! Tudo bem.")
| true |
e429f444714da278ce1ee9a41a6cfb9b4d61cd98 | Python | ritobanrc/RSACodebusters2019 | /substitution.py | UTF-8 | 437 | 2.984375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import random
from string import ascii_uppercase
from quote_file_mod import get_quote
def substitute(message):
new_alphabet = {l1: l2 for l1, l2 in zip(ascii_uppercase,
random.sample(ascii_uppercase, k=26))}
return ''.join(new_alphabet.get(l, l) for l in message.upper())
if __name__ == '__main__':
t = get_quote()
#print(t)
print(substitute(t))
| true |
71e1b107fe74d920ba9cae9c3ef8b2ee6a059e9a | Python | ZucchiniZe/squadbot | /cogs/misc.py | UTF-8 | 765 | 2.84375 | 3 | [] | no_license | import discord
from discord.ext import commands
class Misc:
"""Misc commands"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def msgcount(self, ctx):
"""Calculates the number of messages the caller has sent to the current channel"""
counter = 0
tmp = await self.bot.say('Calculating messages...')
async for log in self.bot.logs_from(ctx.message.channel, limit=1000):
if log.author == ctx.message.author:
counter += 1
await self.bot.edit_message(tmp, 'You have contributed {} messages to {} in the last 1000 messages.'.format(counter, ctx.message.channel.mention))
return True
def setup(bot):
bot.add_cog(Misc(bot))
| true |
c0b811897a44cab30836aee54b0637f1421e8dc9 | Python | AnimaShadows/advent2020 | /solutions/day_1/day_1_p_2.py | UTF-8 | 858 | 3.78125 | 4 | [] | no_license | #!/usr/bin/python3
from array import *
def populate():
puzzle_input = []
f = open("puzzle_input.txt", "r")
for line in f:
puzzle_input.append(int(line))
f.close()
#print (puzzle_input)
return puzzle_input
def product2020(puzzle_input):
for i in range (0, len(puzzle_input)):
for j in range (0, len(puzzle_input)):
for k in range (0, len(puzzle_input)):
if (puzzle_input[i] + puzzle_input[j] + puzzle_input[k] == 2020):
print("Found " + str(puzzle_input[i]) + " , " + str(puzzle_input[j]) + " and " + str(puzzle_input[k]) + " which add up to 2020")
return puzzle_input[i] * puzzle_input[j] * puzzle_input[k]
def main():
puzzle_input = populate()
product = product2020(puzzle_input)
print ("Product: " + str(product))
if __name__ == "__main__":
main()
| true |
fa6bf2a723601ba6acdcd43a95c33e1c47ec20ff | Python | tlouvart/Mater | /assets.py | UTF-8 | 731 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | import os
import pygame
# Assets
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
#config
WIN_NAME = "Mater"
WIN_RES = (1280,960)
WIN_VER = "1.0"
FPS = 20
# Sprite group
sprites_all = pygame.sprite.Group()
cars_all = pygame.sprite.Group()
blocks_all = pygame.sprite.Group()
class Block(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30,30))
self.image.fill((255,0,0))
self.rect = self.image.get_rect()
def createBlock(self, position):
print(position[0], position[1])
self.rect.x = position[0]
self.rect.y = position[1]
| true |
d459e751e78238363f11efb6b95afbd7f123f759 | Python | DIS-SIN/Asgard | /src/utils/logger/formatters.py | UTF-8 | 496 | 2.6875 | 3 | [
"MIT"
] | permissive |
from logging import Formatter
class SlackFormatter(Formatter):
def __init__(self, fmt = None, datefmt=None, style="%"):
if fmt is None and style == "%":
fmt = (
"LEVEL: %(levelname)s\n" +
"TIME: %(asctime)s\n" +
"FILENAMEL %(filename)s\n" +
"MODULE: %(module)s\n" +
"MESSAGES: %(message)s\n"
)
super().__init__(
fmt=fmt, datefmt=datefmt, style=style
) | true |
b740d2d98983ae316311e34927755ea52f03250f | Python | mvakkasoglu/PythonPractice | /identity_operators.py | UTF-8 | 421 | 4.875 | 5 | [] | no_license | # Identity operators are used to compare the objects, not if they are equal, but if they are actually the
# same object, with the same memory location:
x = 1
y = 1
if x is y: # same object
print("same object")
else:
print("not same object")
x = ["apple", "banana", "cherry"]
y = ["apple", "banana", "cherry"]
print(x is y) # false
print(x == y) # true
print(x[1] is y[1]) #true
print(x[1] == y[1]) #true
| true |
8dc03723990d967043c035dc6cc06eaddcbd60f1 | Python | ahungrynacho/project-in-os | /project3/tables.py | UTF-8 | 878 | 2.921875 | 3 | [] | no_license | class SegmentTableEntry(object):
def __init__(self, seg_index, PT_addr):
self.seg_index = seg_index
self.PT_addr = PT_addr # Page Table address
def __str__(self):
return "({}, {})".format(self.seg_index, self.PT_addr)
class PageTableEntry(object):
def __init__(self, page_index, seg_index, DP_addr):
self.page_index = page_index
self.seg_index = seg_index
self.DP_addr = DP_addr # Data Page address
def __str__(self):
return "({}, {}, {})".format(self.page_index, self.seg_index, self.DP_addr)
class VirtualAddress(object):
def __init__(self, op, virt_addr):
self.op = op # operation
self.virt_addr = virt_addr # contains s,p,w in as a 32-bit integer
def __str__(self):
return "({}, {})".format(self.op, self.virt_addr) | true |
ab2c1a261e1226eb83e4f8b9570ed07a74606f11 | Python | suraj-singh12/python-revision-track | /01-modules-cmnt-pip/01_04_print_dir_content.py | UTF-8 | 223 | 2.890625 | 3 | [] | no_license | '''
This program lists the contents of the directory mentioned by path variable
It uses os module to accomplish this
'''
import os
path = '/home/suraj/Documents/harry-python/01-modules-cmnt-pip/'
print(os.listdir(path))
| true |