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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ff73d0310ab9c1f21cda851aadc62beea64d8412 | Python | antonfire/extremitypathfinder | /tests/helper_classes_test.py | UTF-8 | 2,284 | 2.5625 | 3 | [
"MIT"
] | permissive | import unittest
import numpy as np
import pytest
from helpers import proto_test_case
from extremitypathfinder.helper_classes import AngleRepresentation
class HelperClassesTest(unittest.TestCase):
def test_angle_repr(self):
with pytest.raises(ValueError):
AngleRepresentation(np.array([0.0, 0.0]))
#
# def quadrant_test_fct(input):
# np_2D_coord_vector = np.array(input)
# return AngleRepresentation(np_2D_coord_vector).quadrant
#
# data = [
# ([1.0, 0.0], 0.0),
# ([0.0, 1.0], 0.0),
# ([-1.0, 0.0], 1.0),
# ([0.0, -1.0], 3.0),
#
# ([2.0, 0.0], 0.0),
# ([0.0, 2.0], 0.0),
# ([-2.0, 0.0], 1.0),
# ([0.0, -2.0], 3.0),
#
# ([1.0, 1.0], 0.0),
# ([-1.0, 1.0], 1.0),
# ([-1.0, -1.0], 2.0),
# ([1.0, -1.0], 3.0),
#
# ([1.0, 0.00001], 0.0),
# ([0.00001, 1.0], 0.0),
# ([-1.0, 0.00001], 1.0),
# ([0.00001, -1.0], 3.0),
#
# ([1.0, -0.00001], 3.0),
# ([-0.00001, 1.0], 1.0),
# ([-1.0, -0.00001], 2.0),
# ([-0.00001, -1.0], 2.0),
# ]
#
# proto_test_case(data, quadrant_test_fct)
# TODO test:
# randomized
# every quadrant contains angle measures from 0.0 to 1.0
# angle %360!
# rep(p1) > rep(p2) <=> angle(p1) > angle(p2)
# rep(p1) = rep(p2) <=> angle(p1) = angle(p2)
# repr value in [0.0 : 4.0[
def value_test_fct(input):
np_2D_coord_vector = np.array(input)
return AngleRepresentation(np_2D_coord_vector).value
data = [
([1.0, 0.0], 0.0),
([0.0, 1.0], 1.0),
([-1.0, 0.0], 2.0),
([0.0, -1.0], 3.0),
([2.0, 0.0], 0.0),
([0.0, 2.0], 1.0),
([-2.0, 0.0], 2.0),
([0.0, -2.0], 3.0),
]
proto_test_case(data, value_test_fct)
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(HelperClassesTest)
unittest.TextTestRunner(verbosity=2).run(suite)
# unittest.main()
| true |
23ab9cadc23114ff65eaaecbe78cae3e01a6dfef | Python | gabriellaec/desoft-analise-exercicios | /backup/user_084/ch17_2020_03_11_10_46_16_588474.py | UTF-8 | 149 | 3 | 3 | [] | no_license | def eh_bissexto(x):
if x<==0:
return('esse ano nao existe')
elif x%4==0:
return('esse ano é bissexto')
else:
return('ano nao bissexto')
| true |
c030fc401a247da413b4bfc3b6708c10c34efd4c | Python | erikerlandson/htcondor | /src/condor_contrib/campus_factory/python-lib/campus_factory/util/ExternalCommands.py | UTF-8 | 2,065 | 2.8125 | 3 | [
"DOC",
"LicenseRef-scancode-unknown-license-reference",
"OpenSSL",
"Apache-2.0"
] | permissive | # File for running external commands
#
#
import logging
import os
from popen2 import Popen3
from select import select
def RunExternal(command, str_stdin=""):
"""Run an external command
@param command: String of the command to execute
@param stdin: String to put put in stdin
@return: (str(stdout), str(stderr)) of command
Returns the stdout and stderr
"""
logging.info("Running external command: %s" % command)
popen_inst = Popen3(command, True)
logging.debug("stdin = %s" % str_stdin)
str_stdout = str_stderr = ""
while 1:
read_from_child = -1
if not popen_inst.tochild.closed:
(rlist, wlist, xlist) = select([popen_inst.fromchild, popen_inst.childerr], \
[popen_inst.tochild], [])
else:
(rlist, wlist, xlist) = select([popen_inst.fromchild, popen_inst.childerr], [], [])
if popen_inst.fromchild in rlist:
tmpread = popen_inst.fromchild.read(4096)
read_from_child = len(tmpread)
str_stdout += tmpread
if popen_inst.childerr in rlist:
tmpread = popen_inst.childerr.read(4096)
read_from_child += len(tmpread)
str_stderr += tmpread
if popen_inst.tochild in wlist and len(str_stdin) > 0:
popen_inst.tochild.write(str_stdin[:min( [ len(str_stdin), 4096])])
str_stdin = str_stdin[min( [ len(str_stdin), 4096]):]
read_from_child += 1
elif popen_inst.tochild in wlist:
popen_inst.tochild.close()
#logging.debug("len(str_stdin) = %i, read_from_child = %i, rlist = %s, wlist = %s", len(str_stdin), read_from_child, rlist, wlist)
if popen_inst.poll() != -1 and len(str_stdin) == 0 and (read_from_child == -1 or read_from_child == 0):
break
logging.debug("Exit code: %i", popen_inst.wait())
logging.debug("stdout: %s", str_stdout)
logging.debug("strerr: %s", str_stderr)
return str_stdout, str_stderr
| true |
b5b0339a64d526c1d13527b13a661780543a0193 | Python | oxovu/NeuralNetwork | /ZeroLab/Programms/B_LogicalFunc.py | UTF-8 | 605 | 3.515625 | 4 | [] | no_license | def func(x1: int, x2: int, x3: int, x4: int, x5: int):
return x1 & x2 | x3 | x4 & x5
if __name__ == '__main__':
listX1 = []
listX2 = []
listY1 = []
listY2 = []
n = 1
print('Logical func = ', '\n')
print('Table of truth:\n')
print('number \t operands \t\t result')
for x1 in range(0, 2):
for x2 in range(0, 2):
for x3 in range(0, 2):
for x4 in range(0, 2):
for x5 in range(0, 2):
print(n, '\t\t', x1, x2, x3, x4, x5, '\t\t', func(x1, x2, x3, x4, x5))
n += 1
| true |
d06ff6166bfd124828ad229a992af6415f8956ea | Python | XKNX/xknx | /test/dpt_tests/dpt_scene_number_test.py | UTF-8 | 1,743 | 2.609375 | 3 | [
"MIT"
] | permissive | """Unit test for KNX scene number."""
import pytest
from xknx.dpt import DPTArray, DPTSceneNumber
from xknx.exceptions import ConversionError, CouldNotParseTelegram
class TestDPTSceneNumber:
"""Test class for KNX scaling value."""
@pytest.mark.parametrize(
("raw", "value"),
[
((0x31,), 50),
((0x3F,), 64),
((0x00,), 1),
],
)
def test_transcoder(self, raw, value):
"""Test parsing and streaming of DPTSceneNumber."""
assert DPTSceneNumber.to_knx(value) == DPTArray(raw)
assert DPTSceneNumber.from_knx(DPTArray(raw)) == value
def test_to_knx_min_exceeded(self):
"""Test parsing of DPTSceneNumber with wrong value (underflow)."""
with pytest.raises(ConversionError):
DPTSceneNumber.to_knx(DPTSceneNumber.value_min - 1)
def test_to_knx_max_exceeded(self):
"""Test parsing of DPTSceneNumber with wrong value (overflow)."""
with pytest.raises(ConversionError):
DPTSceneNumber.to_knx(DPTSceneNumber.value_max + 1)
def test_to_knx_wrong_parameter(self):
"""Test parsing of DPTSceneNumber with wrong value (string)."""
with pytest.raises(ConversionError):
DPTSceneNumber.to_knx("fnord")
def test_from_knx_wrong_parameter(self):
"""Test parsing of DPTSceneNumber with wrong value (3 byte array)."""
with pytest.raises(CouldNotParseTelegram):
DPTSceneNumber.from_knx(DPTArray((0x01, 0x02, 0x03)))
def test_from_knx_wrong_value(self):
"""Test parsing of DPTSceneNumber with value which exceeds limits."""
with pytest.raises(ConversionError):
DPTSceneNumber.from_knx(DPTArray((0x64,)))
| true |
6ee890d3ed11fa764414c38cb9d1d4de9491747c | Python | LiuhaiqinFudan/InvestorBeliefMarketEfficiency_HaiqinLiu | /2.MergeRemarks.py | UTF-8 | 1,725 | 3.046875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 16 20:34:58 2021
Merge Stock Forum data to get High Frequency Panel and construct Corpus
Input: RawData\个股股吧评论数据(scraped)
OutPut: allComments.xlsx, 包括股票代码(文件名,手动修改),经过清理的评论
@author: Haiqin
"""
import os
os.chdir(r"D:\Course2021Autumn\MachineLearningFintech\project")
import csv
corpus = []
for f in os.listdir("RawData"):
try:
csv_reader = csv.reader(open(".\\RawData\\"+f)) # 默认编码,不确定是哪种
for line in csv_reader:
if line[1] == "": # 漏爬评论样本剔除
pass
else:
line.append(f[:-4]) # 文件名改为股票代码
corpus.append(line)
except:
try:
csv_reader = csv.reader(open(".\\RawData\\",encoding = "utf8"))
for line in csv_reader:
if line[1] == "": # 漏爬评论样本剔除
pass
else:
line.append(f[:-4]) # 文件名改为股票代码
corpus.append(line)
except:
print("not readable: ", f)
with open('CleanData\\allComments.csv',"w", newline='') as csvfile:
spamwriter = csv.writer(csvfile)
spamwriter.writerows(corpus)
# 1st column: title; 2nd: views; 3rd: comments; 4th: stock code
# 然后拉wind公式(主体信用评级),保存为excel格式,去stata进一步定义NEGATIVE和POSITIVE及数据清洗
# 然后生成样本丢进sentiment analysis Github里去train
# 然后predict出来dummy为解释变量进行回归(需要merge m:1)
| true |
eeb84777028b9aead68056202692bb835968c38d | Python | Ivan-Kouznetsov/lucina_suite | /model/counted_collocation.py | UTF-8 | 156 | 2.84375 | 3 | [
"MIT"
] | permissive | class CountedCollocation:
def __init__(self, collocation: tuple, count: int):
self.collocation = collocation
self.count = count
| true |
3bf99a8584442a5ee08acec44b5a78526f1df8ea | Python | mohammadrezamzy/python_class | /mysql-driver.py | UTF-8 | 2,516 | 3.28125 | 3 | [] | no_license | '''
Python needs a MySQL driver to access the MySQL database, so first install it.
python -m pip install mysql-connector
'''
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user_class",
passwd="123456",
database="demodb"
)
# print(mydb)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE classdb")
mycursor.execute("SHOW DATABASES")
# mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
# mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
# mycursor.execute("CREATE TABLE customers1 (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
# ----------Insert a record
# sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
# val = ("John", "Highway 21")
# mycursor.execute(sql, val)
# ------insert multiple records
# sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
# val = [
# ('Peter', 'Lowstreet 4'),
# ('Amy', 'Apple st 652'),
# ('Hannah', 'Mountain 21'),
# ('Michael', 'Valley 345'),
# ('Sandy', 'Ocean blvd 2'),
# ('Betty', 'Green Grass 1'),
# ('Richard', 'Sky st 331'),
# ('Susan', 'One way 98'),
# ('Vicky', 'Yellow Garden 2'),
# ('Ben', 'Park Lane 38'),
# ('William', 'Central st 954'),
# ('Chuck', 'Main Road 989'),
# ('Viola', 'Sideway 1633')
# ]
# mycursor.executemany(sql, val)
# !!! Notice the statement: mydb.commit(). It is required to make the changes,
# otherwise no changes are made to the table.
# mydb.commit()
# print(mycursor.rowcount, "record(s) was inserted.")
# mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
# sql = "SELECT * FROM customers"
# sql = "SELECT * FROM customers LIMIT 4"
# sql = "SELECT * FROM customers LIMIT 3 OFFSET 2"
# sql = "SELECT name, address FROM customers"
# sql = "SELECT * FROM customers ORDER BY id DESC"
# mycursor.execute(sql)
# sql = "SELECT * FROM customers WHERE address = %s"
# sql = "DELETE FROM customers WHERE address = %s"
# sql = "UPDATE customers SET address = %s WHERE address = %s"
# val = ("Valley 345", "Canyon 123")
# sql = "DROP TABLE customers"
# sql = "DROP TABLE IF EXISTS customers"
# val = ("Yellow Garden 2", )
# val=()
# mycursor.execute(sql, val)
# mydb.commit()
# print(mycursor.rowcount, "record(s) was deleted.")
# We use the fetchall() method, which fetches all rows from the last executed statement.
# myresult = mycursor.fetchall()
# print(type(myresult))
# for x in myresult:
# print(x)
| true |
906bad9833dbc720e1b7b064712f1ed43b4d69e8 | Python | samconde/UnityMachineLearningForProjectButterfly | /MuJoCo/Tools/Models/arm/PPO/sb_PPO2.py | UTF-8 | 4,926 | 2.609375 | 3 | [
"MIT"
] | permissive | """
Stable baselines implementation of SAC applied to the ARM
"""
import os
#import mujoco_py
import gym
import numpy as np
import matplotlib.pyplot as plt
from arm_mjpy import arm_env_mj
from stable_baselines import SAC, DDPG
from stable_baselines.common.policies import MlpPolicy,MlpLnLstmPolicy
from stable_baselines.common.vec_env import SubprocVecEnv, DummyVecEnv
from stable_baselines.bench import Monitor
from stable_baselines.results_plotter import load_results, ts2xy
from stable_baselines.ppo2 import PPO2
#Multi
import threading
import multiprocessing
from multiprocessing import Pool, Process, TimeoutError
import time
import os
from itertools import product, repeat
###### Monitoring Training ######
best_mean_reward, n_steps = -np.inf, 0
n_cpu = 1
#Define a Callback function
def callback(_locals, _globals):
"""
Callback called at each step (DQN and others) or after n steps
(ACER or PPO2)
:param _locals: (dict)
:param_globals: (dict)
"""
global n_steps, best_mean_reward, log_dir
# print(n_steps)
#Print stats every 1000 calls
log_dir_t = log_dir + str(_locals['self'].log_num)
if(n_steps+1)%5==0:
#Evaluate policy performance
x,y = ts2xy(load_results(log_dir_t), 'timesteps')
if len(x) > 0:
mean_reward = np.nanmean(y[-100:])
print('Last 5 rewards',y[-5:])
print(x[-1], 'timesteps')
print("Best mean reward: {:.4f} - Last mean reward per episode:{:.4f}".format(best_mean_reward, mean_reward))
#Save the new best model compared to the old model
if mean_reward > best_mean_reward:
best_mean_reward = mean_reward
print("Saving new best model")
_locals['self'].save(log_dir_t + '/best_model.pk1')
n_steps +=1
return True
log_dir = "logs/log_lr3"
# log_num = 1
def train_ppo2(log_num, learning_rate):
global log_dir
log_dir_t = log_dir + str(log_num)
os.makedirs(log_dir_t, exist_ok=True)
envmj = []
# envmj = [arm_env_mj() for i in range(n_cpu - 1)]
env_m = arm_env_mj()
temp = Monitor(env_m, log_dir_t, allow_early_resets = True)
envmj.append(temp)
# env = SubprocVecEnv([lambda: i for i in envmj])
env = DummyVecEnv([lambda: i for i in envmj])
model = PPO2(MlpLnLstmPolicy, env, verbose=0,nminibatches=1,learning_rate=learning_rate)
model.log_num = log_num
print('Starting Learning')
model.learn(total_timesteps=10000000, callback = callback)
model.save(log_dir + "/ppo2")
#Create log dir
#Do multiprocessing
if __name__ == '__main__':
# make args for parallel process tasks (0th task gets arg1[0], arg2[0])
learning_rate = [.01,.008,.005,.002,.001,.0005,.0001]
log_num = range(len(learning_rate))
# arg2 = range(10)
#arg3...
# make as many workers as cpu cores on the machine
workers = multiprocessing.cpu_count()
with multiprocessing.Pool(processes=workers) as pool:
# give the workers a batch of tasks
# this blocks the program until tasks finished
results = pool.starmap(train_ppo2, zip(log_num, learning_rate))
print(results)
###### ARM environment ###############
# env = env.make()
# envmj.reset()
# model = HER('MlpPolicy', env, SAC, n_sampled_goal=4,
# goal_selection_strategy='future',
# verbose=1, buffer_size=int(1e6),
# learning_rate=1e-3,
# gamma=0.95, batch_size=256,
# policy_kwargs=dict(layers=[256, 256, 256]))
# model.save('ARM_SAC2')
###### Gym environment #####
#env = gym.make('Acrobot-v1')
# env = Monitor(env, log_dir, allow_early_resets = True)
#env = DummyVecEnv([lambda: env])
#model = PPO2(MlpPolicy, env, verbose = 1)
#model.learn(total_timesteps=20000, callback=callback)
#env.render()
########## Plotting helpers ##########
def movingAverage(values,window):
"""
Smooth values by doing a moving average
:param values: (numpy array)
:param window: (int)
:return: (numpy array)
"""
weights = np.repeat(1.0, window) / window
return np.convolve(values, weights, 'valid')
def plot_results(log_folder, title='Learning Curve'):
"""
Plot the results
:param log_folder: (str) the save location of the results to plot
:param title: (str) the title of the task to plot
"""
x, y = ts2xy(load_results(log_folder), 'timesteps')
y = movingAverage(y,window=50)
#Truncate x
x = x[len(x)-len(y):]
fig = plt.figure(title)
plt.plot(x,y)
plt.xlabel('Number of Timesteps')
plt.ylabel('Rewards')
plt.title(title + "Smoothed")
plt.show()
# plot_results(log_dir)
print('Done')
# print('Presenting Results!')
#
# obs = envmj.reset()
# envmj.set_viewer()
# while True:
# action, _states = model.predict(obs)
# obs, rewards, dones, info = env.step(action)
# envmj.viewer.render()
| true |
3fc97aef23483fbeb7d385a410fc6bc782962d49 | Python | jacobfitz99/proof2 | /python intermediate/serializacion.py | UTF-8 | 1,093 | 3.203125 | 3 | [] | no_license | import pickle
poema = """Cuantas veces, amor sin reconocer tu mirada, sin mirarte, centaura,
en regiones contrarias, en un mediodía quemante:
eras sólo el aroma de los cereales que amo.
Tal vez te vi, te supuse al pasar levantando una copa
en Angola, a la luz de la luna de Junio,
o eras tú la cintura de aquella guitarra
que toqué en las tinieblas y sonó como el mar desmedido.
Te amé sin que yo lo supiera, y busqué tu memoria.
En las casas vacías entré con linterna a robar tu retrato.
Pero yo ya sabía cómo era. De pronto
mientras ibas conmigo te toqué y se detuvo mi vida:
frente a mis ojos estabas, reinándome, y reinas.
Como hoguera en los bosques el fuego es tu reino."""
#Creamos el archivo binario
fichero_binario = open('poema.txt','wb')
pickle.dump(poema, fichero_binario) #lo convierte a binario
fichero_binario.close()
fichero = open('poema.txt','rb')
lista = pickle.load(fichero) #lo convierte de binario a normal
#print(lista)
import marshal
#serializar datos
archivoDump = marshal.dumps(poema)
print(archivoDump)
#descompirimir datos | true |
cbcbd5123e6944d6c79f1f2362d15ad08f6b43cb | Python | HanxianshengGame/EffectivePython | /2.2_了解如何在闭包里使用外围作用域中的变量.py | UTF-8 | 796 | 3.25 | 3 | [] | no_license | #!/usr/bin/env python27
# -*- coding: utf-8 -*-
# @Time : 2021/6/1 15:02
# @Author : handling
# @File : 2.2_了解如何在闭包里使用外围作用域中的变量.py
# @Software: PyCharm
def sort_priority(numbers, group):
found = [False]
def helper(x):
if x in group:
found[0] = True
return 0, x
return 1, x
numbers.sort(key=helper)
return found[0]
# 总结
# 1. 对于定义在某作用域的闭包来说, 它可以引用这些作用域的变量
# 2. 使用默认方式对闭包内的变量赋值,不会影响外围作用域的同名变量
# 3. 程序可以通过可变值(单个元素的列表)来实现与nonlocal语句相仿的机制
# 4. 除了那种比较简单的函数,尽量不适应 nonlocal
| true |
42a4c8dbbe5d4f689fe031645f9028375cafd2e7 | Python | monda00/hackerrank | /python/#30_the_minion_game.py | UTF-8 | 464 | 4.3125 | 4 | [] | no_license | '''
The Minion Game
'''
def minion_game(string):
vowels = 'AEIOU'
kevin = 0
stuart = 0
for i in range(len(string)):
if string[i] in vowels:
kevin += (len(string)-i)
else:
stuart += (len(string)-i)
if kevin > stuart:
print('Kevin ', kevin)
elif kevin < stuart:
print('Stuart ', stuart)
else:
print('Draw')
if __name__ == '__main__':
s = input()
minion_game(s)
| true |
f28aa33ac4221257f2017fa7abf11964473ec46f | Python | Marioegarcia/tuto_Flask | /app/views.py | UTF-8 | 1,443 | 2.796875 | 3 | [] | no_license | # Se importan Clases
from flask import Blueprint
#Se importan Funciones
from flask import render_template,request, flash
from .forms import LoginForm , RegisterForm
from .models import User
page = Blueprint('page', __name__)
@page.app_errorhandler(404)
def page_not_found(error):
return render_template('errors/404.html'), 404
#index
@page.route('/')
def index():
return render_template('index.html', title='Home')
#login
@page.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
print(form.username.data)
print(form.password.data)
print("Datos")
flash('Bienvenido ' + form.username.data)
return render_template('auth/login.html', title='login', form=form)
#Register
@page.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST':
if form.validate():
user = User.create_element(form.username.data, form.password.data, form.email.data)
flash("USER_CREATED")
print("usuario creado de forma exitosa")
print(user.id)
return render_template('auth/register.html', title='Registro',
form=form)
#About
@page.route('/about')
def about():
return render_template('about.html', title='About')
| true |
d243fdcdc349e07aff270a305125c528bced01b8 | Python | emarinhoss/projects_jupyter | /bnn/loss_equations.py | UTF-8 | 3,822 | 3.125 | 3 | [] | no_license | #!/bin/python
import numpy as np
from keras import backend as K
from tensorflow.contrib import distributions
# model - the trained classifier(C classes)
# where the last layer applies softmax
# X_data - a list of input data(size N)
# T - the number of monte carlo simulations to run
def montecarlo_prediction(model, X_data, T):
# shape: (T, N, C)
predictions = np.array([model.predict(X_data) for _ in range(T)])
# shape: (N, C)
prediction_means = np.mean(predictions, axis=0)
# shape: (N)
prediction_variances = np.apply_along_axis(predictive_entropy, axis=1, arr=prediction_means)
return (prediction_means, prediction_variances)
# prob - mean probability for each class(C)
def predictive_entropy(prob):
return -np.sum(np.log(prob) * prob)
# standard regression RMSE loss function
# N data points
# true - true values. Shape: (N)
# pred - predicted values. Shape: (N)
# returns - losses. Shape: (N)
def loss(true, pred):
return np.mean(np.square(pred - true))
# Bayesian regression loss function
# N data points
# true - true values. Shape: (N)
# pred - predicted values (mean, log(variance)). Shape: (N, 2)
# returns - losses. Shape: (N)
def loss_with_uncertainty(true, pred):
return np.mean((pred[:, :, 0] - true)**2. * np.exp(-pred[:, :, 1]) + pred[:, :, 1])
# standard categorical cross entropy
# N data points, C classes
# true - true values. Shape: (N, C)
# pred - predicted values. Shape: (N, C)
# returns - loss (N)
def categorical_cross_entropy(true, pred):
return np.sum(true * np.log(pred), axis=1)
# Bayesian categorical cross entropy.
# N data points, C classes, T monte carlo simulations
# true - true values. Shape: (N, C)
# pred_var - predicted logit values and variance. Shape: (N, C + 1)
# returns - loss (N,)
def bayesian_categorical_crossentropy(T, num_classes):
def bayesian_categorical_crossentropy_internal(true, pred_var):
# shape: (N,)
std = K.sqrt(pred_var[:, num_classes:])
# shape: (N,)
variance = pred_var[:, num_classes]
variance_depressor = K.exp(variance) - K.ones_like(variance)
# shape: (N, C)
pred = pred_var[:, 0:num_classes]
# shape: (N,)
undistorted_loss = K.categorical_crossentropy(pred, true, from_logits=True)
# shape: (T,)
iterable = K.variable(np.ones(T))
dist = distributions.Normal(loc=K.zeros_like(std), scale=std)
monte_carlo_results = K.map_fn(gaussian_categorical_crossentropy(true, pred, dist, undistorted_loss, num_classes), iterable, name='monte_carlo_results')
variance_loss = K.mean(monte_carlo_results, axis=0) * undistorted_loss
return variance_loss + undistorted_loss + variance_depressor
return bayesian_categorical_crossentropy_internal
# for a single monte carlo simulation,
# calculate categorical_crossentropy of
# predicted logit values plus gaussian
# noise vs true values.
# true - true values. Shape: (N, C)
# pred - predicted logit values. Shape: (N, C)
# dist - normal distribution to sample from. Shape: (N, C)
# undistorted_loss - the crossentropy loss without variance distortion. Shape: (N,)
# num_classes - the number of classes. C
# returns - total differences for all classes (N,)
def gaussian_categorical_crossentropy(true, pred, dist, undistorted_loss, num_classes):
def map_fn(i):
std_samples = K.transpose(dist.sample(num_classes))
distorted_loss = K.categorical_crossentropy(pred + std_samples, true, from_logits=True)
diff = undistorted_loss - distorted_loss
return -K.elu(diff)
return map_fn
class MonteCarloTestModel:
def __init__(self, C):
self.C = C
def predict(self, X_data):
return np.array([self._predict(data) for data in X_data])
def _predict(self, data):
return self.softmax([i for i in range(self.C)])
def softmax(self, predictions):
vals = np.exp(predictions)
return vals / np.sum(vals)
| true |
95226abc7834d81594c4fa4335a1a59a6a84bd9d | Python | mgoszcz/testifactory | /client/testifactory_api/test_execution.py | UTF-8 | 687 | 2.515625 | 3 | [] | no_license | from testifactory.client.testifactory_api.api_methods.api import get
from testifactory.client.server_url.url import URL
from testifactory.client.testifactory_api.test_execution_result import TestExecutionResult
class TestExecution:
def __init__(self, execution_id: int):
self._execution = get(f'{URL}/executions/{execution_id}')
self.id = self._execution.get('id')
self.name = self._execution.get('name')
self.results = self._get_results()
def _get_results(self):
results = []
for case_id, result in self._execution.get('results').items():
results.append(TestExecutionResult(case_id, result))
return results
| true |
05d748a8417b10681a21d9e26f9f825811322252 | Python | kz26/petpeeve | /kevin/cluster2D.py | UTF-8 | 2,555 | 2.875 | 3 | [] | no_license | #!/usr/bin/python
# Uses distance-based slice-by-slice hierarchical clustering to eliminate
# superfluous objects
import os, sys, dicom
import numpy as np
from scipy.cluster.hierarchy import fclusterdata
def read_slice(fn):
ds = dicom.read_file(fn)
objects = {}
for i in range(0, ds.pixel_array.shape[0]):
for j in range(0, ds.pixel_array.shape[1]):
if ds.pixel_array[i][j] == 0: continue
if ds.pixel_array[i][j] not in objects.keys():
objects[ds.pixel_array[i][j]] = []
objects[ds.pixel_array[i][j]].append((i, j))
return (objects, ds)
# obj must be a list
def findCentroid(obj):
dim = len(obj[0])
totals = np.zeros(2, float)
for point in obj:
for i in range(0, len(point)):
totals[i] += point[i]
return [int(round(x)) for x in list(totals / len(obj))]
def clusterObs(objs):
return fclusterdata(objs, 15, criterion='distance')
def findLargestObject(data, obj_ids):
return sorted([(x, len(data[x])) for x in obj_ids], key=lambda x: x[1])[-1][0]
def writeNewSlice(dcmf, keep_ids, fn, output_dir):
pxdata = dcmf.pixel_array
for i in range(0, pxdata.shape[0]):
for j in range(0, pxdata.shape[1]):
if pxdata[i][j] not in keep_ids:
pxdata[i][j] = 0
dcmf.PixelData = pxdata.tostring()
dcmf.save_as(os.path.join(output_dir, fn))
if __name__ == "__main__":
if len(sys.argv) != 3:
print "Usage: %s input_directory output_directory" % (sys.argv[0])
sys.exit(-1)
if not os.path.exists(sys.argv[2]):
os.mkdir(sys.argv[2])
for file in sorted(os.listdir(sys.argv[1])):
data = read_slice(os.path.join(sys.argv[1], file))
slice = data[0]
sys.stderr.write(file + "\n")
sys.stderr.write(" %s objects read\n" % (len(slice.keys())))
final_obj_ids = []
if len(slice.keys()) > 1:
centroids = []
for object in sorted(slice.keys()):
centroids.append(findCentroid(slice[object]))
clusters = clusterObs(centroids)
for clustnum in set(clusters):
member_ids = [sorted(slice.keys())[x] for x in range(0, len(clusters)) if clusters[x] == clustnum]
final_obj_ids.append(findLargestObject(slice, member_ids))
else:
final_obj_ids.append(slice.keys()[0])
sys.stderr.write(" %s objects kept\n" % (len(final_obj_ids)))
writeNewSlice(data[1], final_obj_ids, file, sys.argv[2])
| true |
d8a5096f3a8a13034f45ef34999560e80b4fd47b | Python | StephenNeville/BCS | /sample_code/func/square_func.py | UTF-8 | 197 | 4.09375 | 4 | [] | no_license | # A functional approach to squaring
# a list of numbers
nums = [1, 2, 3, 4, 5]
def sqr(nums): return nums ** 2
print(list(map(sqr, nums)))
# The output will be
# [1, 4, 16, 25, 49]
| true |
41c826749dc36e35ddedefbbb602ae3dbcd6d150 | Python | tsoijackson/CAUCI-Coin-Wars-with-SQLite | /assets/main.py | UTF-8 | 7,169 | 3.25 | 3 | [] | no_license |
import sqlite3
from collections import namedtuple
DB_FILE = "coinwars.db"
Player = namedtuple('Player', 'name points coins dollars')
def create_connection(db_file):
conn = sqlite3.connect(DB_FILE)
return conn
def create_table(conn: sqlite3):
command = ('CREATE TABLE IF NOT EXISTS coinwars_db('
'name TEXT PRIMARY KEY,'
'points REAL DEFAULT 0,'
'coins REAL DEFAULT 0,'
'dollars REAL DEFAULT 0)')
conn.cursor().execute(command)
def select_player_by_points(conn: sqlite3) -> [Player]:
result = []
command = ('Select * FROM coinwars_db ORDER BY points DESC, coins ASC;')
for i in conn.cursor().execute(command):
result.append(Player(i[0], "{:.2f}".format(float(i[1])), "{:.2f}".format(i[2]), "{:.2f}".format(i[3])))
return result
def name_exists(conn: sqlite3, name: str) -> bool:
player_list = select_player_by_points(conn)
for player in player_list:
if name == player.name:
return True
return False
def update_player(conn: sqlite3):
player_name = input("Enter Player Name: ").lower()
if not name_exists(conn, player_name):
print("Player Name does not Exist")
print()
return
coins = input("Enter Coins Amt: ")
try:
coins = float(coins)
except:
print("Incorrect Input. Please input a Number")
print()
return
dollars = input("Enter Dollars Amt: ")
try:
dollars = float(dollars)
except:
print("Incorrect Input. Please input a Number")
print()
return
points = coins - dollars
command = """
UPDATE coinwars_db
SET points = {}, coins = {}, dollars = {}
WHERE name = '{}';
""".format(points, coins, dollars, player_name)
conn.cursor().execute(command)
conn.commit()
print("Player Stats have been Updated!")
def update_all_players(conn: sqlite3):
player_list = select_player_by_points(conn)
try:
for player in player_list:
print("Current Player: " + str(player))
coins = input("Enter Coins Amt: ")
try:
coins = float(coins)
except:
print("Incorrect Input. Please input a Number")
print()
return
dollars = input("Enter Dollars Amt: ")
try:
dollars = float(dollars)
except:
print("Incorrect Input. Please input a Number")
print()
return
points = coins - dollars
command = """
UPDATE coinwars_db
SET points = {}, coins = {}, dollars = {}
WHERE name = '{}';
""".format(points, coins, dollars, player.name)
conn.cursor().execute(command)
conn.commit()
except:
print("Something went Wrong!:( Possibly wrong input. Operation unsuccessful and returning to Menu...")
return
def add_new_player(conn: sqlite3):
player_name = input("Enter Player Name to Add: ").lower()
if name_exists(conn, player_name):
print("Player name already in Database. Returning to Menu...")
print()
return
print("Adding New Player...")
command = ('INSERT INTO coinwars_db (name) VALUES (\'' + player_name + '\');')
conn.cursor().execute(command)
conn.commit()
print("New Player Sucessfully Added!")
print()
def remove_a_player(conn: sqlite3):
player_name = input("Enter Player Name to Remove: ").lower()
if not name_exists(conn, player_name):
print("Player Name does not Exist. Cannot remove Name. Returning to Menu...")
print()
return
command = ('DELETE FROM coinwars_db WHERE name = \'' + player_name + '\'')
conn.cursor().execute(command)
conn.commit()
def clear_all_players(conn: sqlite3):
print("Clearing all Players ...")
command = ('DROP TABLE coinwars_db')
conn.cursor().execute(command) #Drop current table
create_table(conn) #Create new table
print("All Players Cleared!")
print()
############### MENU / INTERFACE ###############
def print_welcome():
print("Welcome to CAUCI Coin Wars!")
print()
print("Coin Wars is a yearly fundraiser that CAUCI does every winter quarter.")
print("The goal of the fundraiser is to collect unwanted change and the")
print("player with most change wins, but the twist is that people can donate whole")
print("dollar bills to players to bring their score down to prevent them from winning!")
print()
print("Rules:")
print(" 1. Player placement is dependent on points")
print(" 2. Points = Coins - Dollars")
print(" 3. When updating coin/dollar amt, please format as XX.XX")
print(" Ex) $5 in coins/dollars means inputting 5 or 5.00")
print(" Ex) $3.81 in coins/dollars means inputting 3.81")
print()
def print_table(conn: sqlite3):
table = ""
border = " +------------+---------+---------+---------+" + '\n'
table += border
table += " |{:^12}|{:^9}|{:^9}|{:^9}|".format("Name", "Points", "Coins", "Dollars") + '\n'
table += border
player_list = select_player_by_points(conn)
for player in player_list:
table += " |{:^12}|{:^9}|{:^9}|{:^9}|".format(player.name, player.points, player.coins, player.dollars) + '\n'
table += border
print(table)
print()
def print_stats(conn: sqlite3):
amt_raised = 0
player_list = select_player_by_points(conn)
for player in player_list:
amt_raised += float(player.coins) + float(player.dollars)
print("{:19}: ${:.2f}".format("Current Amt Raised", amt_raised))
print()
def print_menu():
print("Coin Wars Menu: ")
print(" A. Update a Player's Coins & Dollars")
print(" B. Update all Players' Coins & Dollars")
print(" C. Add New Player")
print(" D. Remove a Player")
print(" E. Clear all Players")
print(" Q. Quit")
print()
def main_interface():
conn = create_connection(DB_FILE)
create_table(conn)
print_welcome()
response = None #initialize response
while response != "Q":
print_stats(conn)
print_table(conn)
print_menu()
response = input("Menu Choice: ").upper()
if response == "A":
update_player(conn)
elif response == "B":
update_all_players(conn)
elif response == "C":
add_new_player(conn)
elif response == "D":
remove_a_player(conn)
elif response == "E":
clear_all_players(conn)
elif response == "Q":
print("Exiting Menu ...")
conn.close()
pass
else:
print("Please Enter a Letter Choice on the Menu")
print()
continue
if __name__ == '__main__':
main_interface() | true |
3c811c004cf7b4c67473735835e70ca33e2ea8bf | Python | blaws/CoinDash | /Guardian.py | UTF-8 | 1,975 | 2.796875 | 3 | [] | no_license | # CoinDash
# blaws, amarti36
# Guardian.py
import pygame
from pygame.locals import *
from Platform import *
from threading import Lock
class Ground(pygame.sprite.Sprite):
def __init__(self, x = 0, y = 0):
self.rect = Rect(x, y, 120, 120) #self.rect.move(x, y)
self.xspeed = -5
self.yspeed = 0
def tick(self):
self.rect.move_ip(self.xspeed, self.yspeed)
class Guardian(pygame.sprite.Sprite):
def __init__(self, gs = None):
pygame.sprite.Sprite.__init__(self)
self.gs = gs
self.image = pygame.image.load("images/InvisiblePlatform.png")
self.rect = self.image.get_rect()
self.rect = self.rect.move(600, 230)
self.yspeed = 0
self.xspeed = 0
self.addplatform = False
self.counter = 0
self.lock = Lock()
def tick(self):
self.lock.acquire()
if self.gs.side == 1 and self.gs.playJumpSound:
self.gs.jumpSound.play()
self.gs.playJumpSound = False
if self.addplatform:
if self.counter <= 0:
self.gs.platforms.append(Platform(self.gs))
self.counter = self.rect.width/6
else:
self.counter -= 1
self.gs.newplatform = True
self.rect = self.rect.move(self.xspeed, self.yspeed)
self.lock.release()
def input(self, event):
if event.type is pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
self.move(event.key)
elif event.key == pygame.K_RETURN:
self.addplatform = True
self.counter = 0
elif event.type is pygame.KEYUP:
if event.key == pygame.K_DOWN or event.key == pygame.K_UP or event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
self.stopMove()
elif event.key == pygame.K_RETURN:
self.addplatform = False
def move(self, key):
if key == pygame.K_DOWN:
self.yspeed = 10
elif key == pygame.K_UP:
self.yspeed = -10
elif key == pygame.K_LEFT:
self.xspeed = -10
elif key == pygame.K_RIGHT:
self.xspeed = 10
def stopMove(self):
self.yspeed = 0
self.xspeed = 0
| true |
6401482a8805eb4839999f4547e58f2c5a19177b | Python | NotEnding/udaan_upload_aws | /UploadToS3.py | UTF-8 | 2,311 | 2.53125 | 3 | [] | no_license | #! /usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2019/7/5 上午9:12
import os, sys
import random
import time
from multiprocessing.pool import Pool
import requests
current_path = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(current_path)[0]
sys.path.append(rootPath)
from auxiliary.S3Connect import S3Connect
from settings import REDIS_CLIENT, AWS_S3_BUCKET_NAME
from auxiliary.AccessLog import Logger
logger = Logger().logger
# 上传任务函数
def upload2s3(dest_bucket_name, dest_object_name, image_url):
s3_conn = S3Connect()
# 判断object 是否已存在
is_exist = s3_conn.exist_object(dest_bucket_name, dest_object_name)
if is_exist:
# 已存在则跳过
logger.info('object {} already exists'.format(dest_object_name))
else:
# 不存在则进行上传
response = requests.get(url=image_url, timeout=30) # 获得bytes类型
if response.status_code == 200:
src_data = response.content # bytes
s3_conn.put_object(dest_bucket_name, dest_object_name, src_data)
else:
logger.info('{} 请求该图片地址失败'.format(image_url))
################################ 多进程 ###############################
if __name__ == "__main__":
t1 = time.time()
while True:
udaan_object_length = REDIS_CLIENT.scard('to_be_put_object')
logger.info('开始上传图片至S3,总计剩余 {} 张图片待上传'.format(str(udaan_object_length)))
if udaan_object_length != 0:
po = Pool(3) # 开启4个进程
for i in range(3): # 一次取4张图片上传
object_info = REDIS_CLIENT.spop('to_be_put_object')
if object_info:
object_infos = object_info.decode().split('&')
object_name, image_url = object_infos[0], object_infos[1]
po.apply_async(upload2s3, args=(AWS_S3_BUCKET_NAME, object_name, image_url))
else:
continue
time.sleep(random.random() * 2)
po.close()
po.join()
else:
logger.info('全部图片上传完成')
break
t2 = time.time()
logger.info('全部图片上传完成,总耗时:{} s'.format(str(t2 - t1)))
| true |
b23f16ec0adbc3892c8bce11c7a694541a13139e | Python | jos-h/Python_Exercises | /palindrome_pairs.py | UTF-8 | 14,868 | 3.265625 | 3 | [] | no_license | from pprint import pprint
def check_palindrome(temp_str):
return temp_str == temp_str[::-1]
def print_palindrome_pairs(words, distinct_indices):
temp_str = ''
dict_word_counts = {word: index for index, word in enumerate(words)}
for index, word in enumerate(words):
for each in dict_word_counts:
if check_palindrome(word + each) and index != dict_word_counts[each]:
distinct_indices.append([index, dict_word_counts[each]])
# for j in range(i + 1, len(words)):
# temp_str = words[i] + words[j]
# if check_palindrome(temp_str):
# distinct_indices.append([i, j])
# temp_str = words[j] + words[i]
# if check_palindrome(temp_str):
# distinct_indices.append([j, i])
pprint(distinct_indices)
def print_palindromePairs(words, distinct_indices=[]):
res = set()
if not words:
return [[]]
dict_word_counts = {word[::-1]: index for index, word in enumerate(words)}
for index, word in enumerate(words):
for j in range(len(word) + 1):
start = word[:j]
end = word[j:]
if check_palindrome(start) and end in dict_word_counts and index != dict_word_counts[end]:
res.add((dict_word_counts[end], index))
# distinct_indices.append([dict_word_counts[start[::-1]], index])
if check_palindrome(end) and start in dict_word_counts and index != dict_word_counts[start]:
res.add((index, dict_word_counts[start]))
# distinct_indices.append([index, dict_word_counts[end[::-1]]])
pprint(list(res))
# dict_word_count = {word: index for index, word in enumerate(words)}
# for index, word in enumerate(words):
# for j in range(0, len(word) + 1):
# a = word[:j]
# b = word[j:]
# if check_palindrome(a):
# if b[::-1] in dict_word_count and dict_word_count[b[::-1]] != index:
# distinct_indices.append([dict_word_count[b[::-1]], index])
# if check_palindrome(b):
# if a[::-1] in dict_word_count and dict_word_count[a[::-1]] != index:
# distinct_indices.append([index, dict_word_count[a[::-1]]])
# pprint(distinct_indices)
def main():
# words = ["abcd", "dcba", "lls", "s", "sssll"] # [[0,1],[1,0],[3,2],[2,4]]
# words = ["bat", "tab", "cat"] # [[0,1],[1,0]]
# words = ["abc", "sa", "xy", "as"] # [ [1,3], [3,1] ]
words = ["aehadfcgjd", "dggd", "fbaechf", "aeij", "afdjcffahef", "gji", "jghedhciggehhaf", "cjaibcjbbfdbcdbjhgi",
"eddaiadgagdg", "ihiidcjgbiib", "ehbagejabjj", "efedgbifcddici", "bhgdeccihicchhfbedhh", "hcggidd",
"fiahbdeceehh", "diicddbficeed", "fbbiicgib", "b", "ffjheahhgjefccedbj", "jajh", "cfbbdccjafdgfgci", "e",
"fjggcagbcehic", "hiah", "jegacfbhebffi", "caagbjdihcicijgbgbaj", "jicieafigddabcfcaic", "chhabfhiifid",
"jdbjiifadidh", "ejcbhgdafigf", "iejjjaibggdedfjaj", "bjefgieghii", "fejgcjjddecc", "hjje", "ihifgaagijge",
"eaaaeceaaeghegbi", "gageeafaijfij", "bd", "icicfcjieiajgjjaebha", "cbhgjaajiffej", "ggegc", "iciiie",
"ccjcjagcffcgcc", "ahagibgjfcdehjigge", "fcjbdjdhicchfh", "faficchahhiaedjfcbh", "gagigebeehjfeahfegf",
"feiffehcfjhef", "ejcije", "iggabc", "aagfjbbbeej", "eghdfcaaihcfjhfgehj", "fjcjfediddbd", "ihjed",
"ffigjdjjdaicdbdcjd", "jjdgchjgfbcjcdi", "jjgeijdjjefghhbibidj", "jhdfgafjiajhjgg", "bhdjdcjfihefiecaie",
"jcceg", "jgciiabjfeeifcfijia", "jgdbcgagigadeghbgfe", "bggchaeiiceigcifa", "eehfa", "jceaecbeghbhagga",
"hjbchidajafei", "dg", "jbabfgjcdibaibfie", "bhbae", "ehdfa", "jjfchiageajcbdddibjb", "aacccgfiddfg",
"ihjbffbdgbhd", "hei", "gaaabebdjbddggeecjf", "idjgaebj", "dfjfcjj", "fabfdhhfbdghf", "aehfjcafjfeddaad",
"bhccbfahdf", "cedidajihbecjddbgacd", "bicghjecceggdi", "hjegad", "dhfbjacdfhaeigbj", "jjiefjcajijfhicccg",
"a", "cigjh", "gc", "eagbaabh", "fce", "hhccihbjgcdjj", "gb", "ebi", "efgcadecaeihbae",
"edbbbhbicicahhegabcd", "aa", "dabijjafaae", "ddiifcbdh", "haihcheei", "ada", "jdfjefifijgdhji",
"gcfahaiifc", "hibgjd", "eaeighge", "hcehb", "chaejcdeih", "afajgejhjcdg", "ajgfedfgaiejbhcidh", "d",
"abjgiiahhcijfedggb", "hdgh", "dafbicjejihicd", "affchhbfadhbdjfa", "dgjfejfgecbafbc", "daechgce",
"jfbgfegdgchbheaiief", "aedacaafddcaeidccj", "bjijheeibeecaeg", "gjjfdeeid", "gafbaeh", "dbjcdcibeefaejeb",
"dbgaaicc", "fffjiejgaeebhje", "chfaeeecgjjiefhcja", "cgiihifbh", "hfghadagigahd", "aifjghhjddjig",
"eejehfifigdcf", "jacbaeahediaecigg", "adejhcbfgjjfbdaehicd", "faafihfbcdhdeh", "eadacabjabadgeii",
"hafhddadbehdajicij", "cjcifahe", "bgjchgdeffdg", "bfhhiaacdccfiejej", "aecfbb", "cdjbaiiabcicibb",
"ddaeiai", "cgfbeija", "ffiad", "dedbcbg", "ecafahehichagc", "dhaigigjbgijfag", "ffedfejfhd", "fijcbi",
"f", "gedchcbighdf", "ebhijggcdfacjhjcg", "gbia", "djidbdijdeciiadhh", "bbgiihfbfdbdjc",
"ddhiddbeaeeajijbgdc", "fghhhehba", "gedgjjcjdcegageebbdh", "ci", "idja", "ebadafbeccbhafgigdc",
"agcgejedaheabidifd", "fdfdbgfddciaaegdf", "ce", "bhhiciihfaehjhhjb", "ba", "afbejcgjdeiaah", "fefcbj",
"jbbfeiaechadafeg", "gg", "facihaif", "idjafcehhicecigfj", "df", "hidccjebheiffcih", "degdcjbgadjfahde",
"dacjbbejggjgcffa", "jiefichbgf", "cfddeb", "agcjchi", "de", "ghhjjfgihahaibdbcf", "edjbgd", "fig",
"aagdjgebcfbbfaebh", "ejjc", "eiejegjhcjgabiejdihe", "fjedcfddcebghagdfg", "igdec", "jfihddbcbjacighbdhfa",
"ggca", "idhbaiiieg", "idiec", "fajhdcfhegefdiggjg", "cfcjccbeccjjagi", "eai", "gbiehjiidcfiehf",
"adgachabh", "bidcj", "fjgejddfhffb", "cbfhheaabiej", "hhjibjdgih", "ifhc", "gbcfdgecdibha", "hgecddf",
"jgeaafgdebf", "ddgcbffh", "dbabahgjgah", "ijbhcf", "bgjbeddbcejch", "efdhffc", "ffcbfcecejjbbggdajj",
"cibehhdgedbjh", "chaggdiiiig", "ibdefjghjbbifdfhbd", "cfhhgebadj", "hfdcahffacbciciiij",
"iaheghddfgcfjejh", "gaehjbhdefgdgibcgghf", "dgiahjf", "cfcjedjgbeejhgeaag", "hjbihc", "egce",
"bjjbdjccibi", "fejhbegibjjb", "fbaahgcjbdfhhcjjedgb", "ibeddhjac", "cjiaciijaefe", "fggjibfieg",
"dgbeidfbgjiaih", "iffdgbhb", "ddahagbgh", "cejigjdhhfhfb", "gachicaaiacabbggea", "ccbibi",
"jidfaachibbijg", "afbcbdbaihiggjjh", "efbh", "ffgfghehji", "ifiibcjeggeff", "fjhhahiifiid", "dcfbghjfh",
"aicgcbegefjigci", "ggffagcejaeafjjgf", "dbgdif", "cabhfghcjjah", "fiie", "djhfhidebajchcb", "hhe",
"dbacbebfgjccf", "ebjfefbfjcaaicaab", "ii", "cjhfiaieaccfefjecf", "habii", "gajjgggg", "hbiccfhfcdgecdidb",
"jdjjjahaigcde", "hedfjhhgi", "hhjfg", "acchchgcb", "jhjgeidf", "eb", "gfbbgigja", "fidhhii",
"ebdagjfcedagb", "jjjhgcehijhefjjdgjec", "dcjad", "cedheeedjacj", "acgjfdee", "jcbabagjfgjhcfij",
"dcicabf", "fedejjheffidjagagedc", "cjbjbgjafgegbje", "gceb", "fcfaacbfjjfhbf", "bgcifffcbibjhbedecef",
"jbhefgf", "ie", "ifaahjjbc", "bgcjbbbbahgeiaebfj", "ijefggicbegbae", "iacefjadbefb", "edih",
"jjdcbdiidaajdjd", "c", "biaedbdagfgjibih", "jahacahhj", "ffee", "jacce", "ddggcijfbhhcgbid",
"cfedbfchdjjcjeggb", "ijdcfdaih", "aedfgfiadhac", "iajgaiedejgj", "gjehfiidahhcg", "afedihihhcbffaafg",
"caejibdfcacad", "fhafhcggb", "bdgehaehfheddgach", "jciig", "adhcdiicgbhdbh", "jfbeeefaddecccahiig",
"aabidegcj", "ifigacaif", "ejeadbdjeafa", "eaabfijajchggfiibchj", "fgejgcigjgihheiejf", "cgccdjchaa",
"igeihfjaiaeh", "gejhjeffaciegbdfib", "aaab", "gbgiaha", "bjaafffdefgiegadidha", "giffiabfdfebihjjcij",
"adhd", "gchfahg", "hai", "ijbbabicgdhhjaabhf", "gdhgdbb", "fddeg", "idcibjd", "gchehefigjhbcafgfe",
"iagcg", "hcciidhihcfaihhacab", "cdhgbheidi", "igi", "dacdcedda", "dbceabdfh", "gcb", "ah", "jcefahhabaf",
"bccjgfjfciihif", "ejigebcfeafa", "h", "chd", "jdgfieheehcacbibbbcd", "gigihdjfbbdi",
"cahjicihahfeiffjbggi", "adaii", "gigaggcb", "iggebfhhjciaejb", "cbbbihgf", "cfhbjgbjffejciidfbi",
"gegegij", "fegdfd", "dfeie", "i", "agajhaijafici", "hbgeh", "hfdfdjj", "jbgihjgdbhb", "beeiidefega",
"fhgaichjjidfchhcggf", "bcchhhbefad", "fdahjfebgdbjaicaaj", "bfihjidfggh", "aabbfdgcd", "fjhafciifgb",
"hidc", "aeccbghajg", "dhcff", "hebjfhjbgfhdfh", "acificadgjjcfbaha", "dajiccafjgbiijg",
"dahbdgbiihedjdegie", "fjjjgjjdab", "ehcgecjfhi", "cebhajji", "chbhahgbfigbaib", "hcedgdcicg", "cadcd",
"fciede", "ggdiheh", "aaehgajjh", "efaceafccgjegddg", "hjf", "aehdfdih", "hdeac", "ffcfb", "bbjghdhjafa",
"aafj", "hcijaegjhh", "jhdfjehdfgh", "bajcgffefjjjdfgjidee", "ebdhfbidgediaebbfj", "fcegafgcieg", "hif",
"bfjccefde", "jc", "djbjbdi", "bfifcgh", "jihjgg", "bdgbechfheefacjj", "dbhgaefbceg", "ibcbhihbbecjcgbcd",
"egef", "hfibdjjbfgb", "bbjjijdcbffg", "ehebj", "dbeagih", "egjiejgbgjgcejde", "fffghecbhcije",
"bfgbjejjbifdgb", "idbbjejejigafggjbah", "cbe", "jbgfiaighgfjfb", "bchhbjghdbfcbjcffjh", "chichbgbdgf",
"bgicedihegi", "abdjgjebfdbgaghjec", "ecfb", "aeieeefgeahjieead", "ejjibeihbbjhcacbif",
"gigfabfbidjigdibg", "chccicib", "gjgiedgahhdfeaj", "fibjjiebbgdibcghg", "gcaccbiii", "hhfbbijffgfjcej",
"icfcjeebjagjhefhaeif", "ffeeajdhdaeccj", "bcecjhdjidehhbcccae", "eeefh", "bjeadaaddfihbcfahfhe", "dccj",
"ieehjeigifj", "hacchebgcdcbgcdbhhh", "jeg", "degbjejaggfcbfggfbce", "aefdjfggjjeefbee", "ca", "dgbdeeh",
"jaeajdaee", "ebibgedfjiibbjahbfad", "jcgbicjdefi", "icegfabbfdbei", "jfhdhicc", "igageijigjccjghb",
"cjgeigfcddad", "cbhiadagggjeif", "hgbejfgaiabfcefjb", "adbigjjaijgihd", "jgcijhcfgebbiii", "iccec",
"adceichfcejabeeghjfj", "agedcdbda", "chfjiidjiab", "bcabhghigegfbh", "ih", "idaacijbdhcdaccbgj", "fi",
"eedcga", "gbececjcichfe", "eejcjjdiacja", "bhedjagbhaehiejbhid", "bhj", "fehbcbcdefihj", "icbifhdddjhh",
"ahdjfgchgci", "g", "ifa", "fcdbcefe", "hdd", "jefjaihgjjddgcbehad", "jhbi", "jdicgjhhjd", "gegdihbccgcbb",
"jeecichjcd", "ahe", "ahgaicdgfci", "bdcdadiagdgbi", "fejdbjbhic", "aic", "ahcadadcjhiagghbij", "dca",
"cacjjejfdjbjhibg", "ibicfaedbfcdbhjg", "gdjifgfbadjdbhjbiie", "cffgfdfabdhfchbbbbd", "heecj",
"icbfabgbihaghhdch", "bbgciagjadgajia", "jghj", "afdgegihghfdcbccda", "igfhfhecijabe", "hbaaahi",
"cidgagafhj", "ijeabfjjiaiaeegcga", "gbe", "jbjiicdbeggehcbhjdf", "cciihddhggjdjihbhj", "cfgbahbdb",
"jbahg", "eecjce", "bggdbjbdgegbhjfi", "dfbfeagbhfadbd", "jhcajdjefcdgefhjdea", "hcdcabaahgjjcgia",
"aaaaeggi", "egabjhaa", "aaafcidifejjededgcc", "ceacbedgdhfibgbcfj", "fjbejchhigcecfbie", "hibagcddghjgcj",
"jagegfjdcffdfcbiagcc", "ghacicaejjdcee", "jgcec", "did", "edaijdghcfcfaggbeccd", "jdfdhcbiigehfhhggjb",
"dfbfa", "bbh", "jegbhighafa", "hdbhb", "fhegijafbijb", "hdbciibibhcj", "gicjddbafgadgdh", "bjcfa",
"dcejeb", "cbjbebijc", "gjaihjbjcjahaebhdeb", "gahahcedbh", "hia", "ehedaheb", "cccb", "dijdfchc",
"cfcigjeddcbihhia", "ehfcfj", "adijbihcajhcd", "fhh", "dehdcb", "jibei", "feahbjehbidhfhc",
"headgfgagbeaghjb", "hcjj", "gbejadijcefdeidc", "jgjed", "bcciige", "eafihhbgd", "cfdgfh", "hfefddcb",
"ebhbfbhbcjehejidhgi", "cgejgaiiebdfhi", "fbjgicjjghgjdbd", "gidgiabcbhdh", "eaajhjhedfbch",
"aciigeajchjafcaigfc", "baihfdji", "aff", "fdehgjaie", "hfic", "ac", "dgccdbdidccagf", "ecii",
"badcchggehcfei", "hgcdagdbehfchjigjgef", "cejci", "fgbdbhabijcbg", "jcefcib", "ijcghbi", "jgbdjieccdj",
"jhibdcedajhjd", "bfj", "hh", "edabhgeffbhee", "hfddecfbbddchfj", "jajgfahadfhfaajgceed", "ji", "cgi",
"ijjbeahefacibajdhf", "jcfbch", "addfibhhdf", "dcecfdeaibeje", "ifiea", "bdhhdbfd", "cebbbfbeeaehdbahdih",
"aaci", "feb", "giedgdbjdcecghafic", "jhigcecb", "ibdcgbbda", "bhechgfij", "ggjiehhjgi", "iffafihe",
"chfec", "aabhce", "dhih", "cebcehbbfeeibj", "faceghabagdjdejbc", "jcejgfbbdbid", "ccdja", "hgiddiif",
"ahh", "cbcag", "beifib", "jdbbgjbagfhaiecje", "ihgbe", "gdhdgehjbe", "bahd", "fjgjhbjdjdf", "agacddiaea",
"cfagbjchfbgejbjcbia", "fgiffi", "caddidbhfadcafjgfijb", "dahaifgb", "jbedcadhcacbadfcha", "hceaaebjiijai",
"feife", "dgbaeffgfddabfha", "ihjjcjcfbjj", "jcdbjja", "hhggg", "jaej", "bcjfhf", "hfeccgf",
"fiehhebajjigajc", "dejid", "cfcgicdcbafej", "gahf", "j", "gieebagjiegg", "hegce", "gfghecdaecgffga",
"gaijefhi", "fajagegficghibhdae", "jcjghaib", "eiacaece", "ciicd", "fggbgjhfaf", "jifajcjedhiifga",
"chhejif", "efcdbeadcebjdfe", "ha", "cfidiahdeidbgd", "igbdbb", "eddaijgafhdb", "jacgfi", "fbgjihci",
"gcaegbgcac", "jagjbhdhadadbdcef", "edgahaej", "efabjjefiig", "dijhdgijcgfhfe", "fbabcigbhfbbcciagi",
"ibidjgfb", "giajhdcahiccaibbji", "bbjjibhgbdj", "hbdhjecihih", "fjfccige", "diebecfdebcje", "hg", "igij",
"cfjgeaabedgbb", "afgehhbhbe", "ij", "jecbgjffhbbihhjjeec", "af", "dbbgaed", "cjhiaic", "hhdcaegbgfhf",
"ihgejhiiaifi", "bhahiigjeeaehgggead", "hdbfhjbgdccd", "iedhgj", "baaefaiiec", "bdfcb",
"gibgjjcjhacgfehddigj", "hhgg", "hcifejid", "ghejafbjejba", "jecidjj", "acggchgigijhi",
"fbjgbeejgjjhfhjifd", "ieehcdafeaidfaeh", "fjeddiedcb", "bbca", "ea", "jhefgbhhcajce", "aghhe",
"hejhiidgbbfjeafd", "cafiggdiaegddbb", "echiii", "ehiafhhagigcc", "hbehjcgicee", "gdj", "fgh",
"bhjicjadcehcgbbe", "ffbdgafdijbibgfachei", "gbgdaajhei", "ghceeed", "dgejhcbgcgg", "fcchc",
"jchdajhhejbd", "jie", "idddbhhbhiijjde", "hchic", "ibjbdajegdcib", "fhjabhagaieahichcha", "bfcbecefg",
"iehej", "ifebddafdideeegj", "bhigafci", "ehageeaihhejehce", "jfd", "cehe", "hjgg", "aj",
"chdcddfdbchjadechaa", "dibdfagfheei", "aicdagfhbi", "agceg", "efeaaedfachgdjhcihai", "dicgjdiaf",
"bcjcffcbhegceibeb"]
words = ["abcd", "dcba", "lls", "s", "sssll"]
distinct_indices = list()
print_palindrome_pairs(words, distinct_indices)
print("********************************************************************8")
# optimized
print_palindromePairs(words)
if __name__ == '__main__':
main()
| true |
bd406bbed165ddecbc07a8dafd5e03e7d4850381 | Python | shrukerkar/ML-Fellowship | /PythonLibraries/PlotlyScatterPlot/LineAndScatterPlotForRandom100XAndYCoordinate.py | UTF-8 | 689 | 2.875 | 3 | [] | no_license |
# Write a program to draw line and scatter plots for random 100 x and y coordinates
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
plotly.tools.set_credentials_file(username='shrukerkar',api_key='Xz0m9hmG79qoKrR9kam6')
N=100
x_random=np.linspace(0,1,N)
y0_random=np.random.randn(N)+5
y1_random=np.random.randn(N)
y2_random=np.random.randn(N)-5
trace0=go.Scatter(x=x_random,y=y0_random,mode='markers',name='markers')
trace1=go.Scatter(x=x_random,y=y1_random,mode='lines+markers',name='lines+markers')
trace2=go.Scatter(x=x_random,y=y2_random,mode='lines',name='lines')
data=[trace0,trace1,trace2]
py.plot(data,filename='scatter-mode') | true |
ad531bbe8f7a189766ea90356542c4cbef19b25d | Python | gokuldevp/Amazon-automated-price-tracker | /main.py | UTF-8 | 1,609 | 2.78125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
from smtplib import SMTP
# ******************************************** SENDING MESSAGE *********************************************************
FROM = "from@gmail.com"
PASSWORD = "**********"
TO = "to@yahoo.com"
def send_mail():
"""function to send mail"""
server = SMTP("smtp.gmail.com", port=587)
server.starttls()
server.login(FROM, PASSWORD)
server.sendmail(from_addr=FROM,
to_addrs=TO,
msg=f"Subject:Amazon Price Alert!\n\n{text}\n{AMAZON_URL}")
server.close()
# ******************************************** getting data from the web site ******************************************
AMAZON_URL = "https://www.amazon.in/Acer-Swift-Display-Touchscreen-Notebook/dp/B08M41DHTV/ref=sr_1_22_sspa?dchild=1&keywords=laptop&qid=1616132314&sr=8-22-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzT05FNTVZUUs2MDkyJmVuY3J5cHRlZElkPUEwNzU4NzMxQVJENEdOVEwyNFVDJmVuY3J5cHRlZEFkSWQ9QTAwNzY2NzczTVNNRzJBTzJDR0lRJndpZGdldE5hbWU9c3BfYnRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ=="
HEADERS = {
"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8,ml;q=0.7",
"User-Agent": "Chrome/89.0.4389.90",
}
response = requests.get(url=AMAZON_URL, headers=HEADERS)
data = response.text
# ****************************************** using beautiful soup to scrape the data ***********************************
soup = BeautifulSoup(data, "html.parser")
product_name = soup.find("span", id="productTitle").string
product_price = soup.find("span", id="priceblock_ourprice").string
cost = product_price.strip().split()
text = f"{product_name.strip()}\nnow costs : Rs.{cost[1]}"
# ******************************************* sending mail to the phone ************************************************
send_mail()
| true |
7e6aeb127fd96db68d8fa979f99a77de0b7a40be | Python | Leyni/mycode | /acm/leetcode_0070.py | UTF-8 | 480 | 3.59375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
res = range(0, n + 2)
res[1] = 1
res[2] = 2
for i in range(3, n + 1):
res[i] = res[i - 1] + res[i - 2]
print (i, res[i])
return res[n]
# test data
case = [4,
]
# run
solution = Solution()
for (a) in case:
result = solution.climbStairs(a)
print (result)
| true |
1c76083e27e0e05f44f2d8f9f3d48d72acf1316e | Python | ambroziepaval/Number-Plate-Recognition | /tests.py | UTF-8 | 709 | 2.65625 | 3 | [] | no_license | from visionapi import vision
from lpdetection import number_plate_detection
from yolov3 import car_detection
import cv2
test_frame = cv2.imread("visionapi/test_frame.png")
test_car = cv2.imread("lpdetection/car.jpg")
# Integration Test: Vision API
# vision_api = vision.Vision()
# texts = vision_api.detect_texts(test_frame)
# print(texts)
# Integration Test: Number Plate Detection
# np_detection = number_plate_detection.NumberPlateDetection()
# number_images = np_detection.detect_number_plate_locations(test_car)
# print(len(number_images))
# Integration Test: YOLOv3 detection
yoloDetector = car_detection.YoloDetector()
detected_cars = yoloDetector.detect_cars(test_frame)
print(len(detected_cars))
| true |
ebc9cc5005b759c77785f7259f8912f72533db1d | Python | Deserve82/KK_Algorithm_Study | /Kangho/BOJ_3109.py | UTF-8 | 631 | 3.015625 | 3 | [] | no_license | movements = [(-1, 1), (0, 1), (1, 1)]
def re_dfs(x, y):
checker[x][y] = True
if y == C - 1:
return 1
for move_row, move_col in movements:
mr, mc = move_row + x, move_col + y
if 0 <= mr < R and 0 <= mc < C:
if not checker[mr][mc] and board[mr][mc] == '.':
v = re_dfs(mr, mc)
if v:
return v
return 0
R, C = map(int, input().split())
board = []
checker = [[False] * C for _ in range(R)]
answer = 0
wrong_answer = 0
for _ in range(R):
board.append(list(input()))
for i in range(R):
answer += re_dfs(i, 0)
print(answer)
| true |
42322286da82a0cf63b0535df1766565f9793d30 | Python | atobaum/Algorithm-problem-solving-book-code | /MATCHFIX.py | UTF-8 | 1,378 | 3.09375 | 3 | [] | no_license | # 2020.3.23
# p1005
from utils import parse
from FordFulkerson import networkFlow
def test():
inputs = """3
2 2
3 3
0 1
0 1
3 3
4 2 2
1 2
1 2
1 2
4 4
5 3 3 2
0 1
1 2
2 3
1 3"""
inputs = parse(inputs)
c, = inputs.pop()
for _ in range(c):
_, m = inputs.pop()
win = inputs.pop()
matches = []
for _ in range(m):
a, b = inputs.pop()
matches.append((a, b))
print(solve(win, matches))
def solve(win, matches):
n = len(win)
m = len(matches)
V = 2 + n + m
def canWinWith(totalWin):
if max(win[1:]) > totalWin:
return False
# 0: start, 1: sink
# 2+i: ith match
# 2+m+i: ith member
capacity = [[0]*V for _ in range(V)]
for idx, match in enumerate(matches):
capacity[0][2+idx] = 1
capacity[2+idx][2+m+match[0]] = 1
capacity[2+idx][2+m+match[1]] = 1
for idx, w in enumerate(win):
if idx == 0:
capacity[2+m+idx][1] = totalWin - w
else:
capacity[2+m+idx][1] = totalWin - 1 - w
res = networkFlow(capacity, 0, 1)
return res == m
totalWin = win[0]
for _ in range(len(matches) + 1):
if canWinWith(totalWin):
return totalWin
else:
totalWin += 1
return -1
test()
| true |
44bcda6aa83205065647e21228a29fc87c0b4802 | Python | LichAmnesia/LeetCode | /python/58.py | UTF-8 | 391 | 2.734375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# @Author: Lich_Amnesia
# @Email: alwaysxiaop@gmail.com
# @Date: 2016-09-18 23:20:43
# @Last Modified time: 2016-09-18 23:23:53
# @FileName: 58.py
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.split()
if len(s) < 1:
return 0
s = s[-1]
return len(s)
| true |
0b7a035c9278105693edc645ca71f41d7b40d780 | Python | jackysatpal/PythonAlgoKit | /leet-code/Easy/lastWordIn.py | UTF-8 | 1,063 | 3.75 | 4 | [] | no_license | class Solution(object):
def lengthOfLastWord(self, s):
last_word = get_last_word(s)
if not last_word:
return 0
return len(last_word) # This is trivially simple to implement
def get_last_word(string):
if not string:
return None
words = get_words(string)
if not words:
return None
return words[len(words) - 1]
def get_words(string):
if not string:
return []
buffer = ''
words = []
for char in string:
if char == ' ' and buffer: # Valid word detected
words.append(buffer)
buffer = ''
continue
elif char == ' ' and not buffer: # Not a valid word
continue
buffer += char
if buffer:
words.append(buffer)
return words
assert get_words('Hello world') == ['Hello', 'world']
assert get_words('one') == ['one']
assert get_words('') == []
assert get_words(None) == []
assert get_words(' ') == []
assert get_words(' ') == []
assert get_words(' Hello world') == ['Hello', 'world'] | true |
ad3e0ea5e96f4399415551cd8fc260441ea872b3 | Python | Python-Repository-Hub/Pine-Data-Tools | /lib/preprocess.py | UTF-8 | 2,543 | 3.453125 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env python3
"""
Preprocess csv data, line by line
-Reads from csv input_file, and writes to new csv output_file
Usage:
proprocess.py <input_file.csv> <output_file.csv> [<headers_present = 0>]
[<skip_missing_or_incorrect_data = 1>] [<default_value = 0>]
"""
import csv
import sys
def process_csv(input_file, output_file, headers_present=0,
skip_missing_or_incorrect_data=1, default_value=0):
pos_values = ['y','yes','positive','abnormal','male','m','t']
neg_values = ['n','no','negative','normal','female','f','none']
with open(input_file) as i, open(output_file, 'w') as o:
reader = csv.reader(i)
writer = csv.writer(o)
if headers_present:
new_headers = process_headers(next(reader))
writer.writerow(new_headers)
for line in reader:
processed_line = process_line(line, pos_values, neg_values,
skip_missing_or_incorrect_data,
default_value)
if processed_line: # if list not empty
writer.writerow(processed_line)
def process_headers(headers):
new_headers = []
for item in headers:
item = (item.strip().replace(" ", "_").replace("|", "_")
.replace(":", "_").replace("?", ""))
new_headers.append(item)
return new_headers
def process_line(line, pos_values, neg_values, skip_missing_or_incorrect_data=1,
default_value=0):
processed_line = []
for item in line:
item = item.strip().lower()
if item in pos_values:
item = 1
elif item in neg_values:
item = 0
else:
# this line is missing a data point
if skip_missing_or_incorrect_data:
# skip line
processed_line = []
break # return empty list
else:
item = default_value
processed_line.append(item)
return processed_line
if __name__ == '__main__':
input_file = sys.argv[1]
output_file = sys.argv[2]
headers_present = 0
skip_missing_or_incorrect_data = 1
default_value = 0
try:
headers_present = int(sys.argv[3])
skip_missing_or_incorrect_data = int(sys.argv[4])
default_value = int(sys.argv[5])
except IndexError:
pass
process_csv(input_file, output_file, headers_present,
skip_missing_or_incorrect_data, default_value)
| true |
870b9ed4d92f1909d2ec9d60cd454b93171ca625 | Python | divya-ai/hybrid-recommender-api | /utils/recommendations_helper.py | UTF-8 | 4,367 | 2.640625 | 3 | [] | no_license | from mongo import mongo
from db import db
from sqlalchemy import func, case
from models.movie import MovieModel
from models.genre import GenreModel
from models.user_rating import UserRatingModel
class RecommendationsHelper:
@staticmethod
def get_dict(ratings, take=10, skip=0):
return dict(ratings[skip:skip + take])
@staticmethod
def get_similarity_values(user_id, ratings, genres=None):
mongo_similarities = mongo.db.tfidf_similarities
rated_movies = RecommendationsHelper.get_user_rated_movies(user_id)
rated_movies = [item['movieId'] for item in rated_movies]
movies_similarities = dict()
if genres is not None:
genres_ids = genres.split(',')
movies = db.session.query(MovieModel.id) \
.join(MovieModel.genres)\
.filter(MovieModel.id.in_(rated_movies)) \
.filter(GenreModel.id.in_(genres_ids)) \
.group_by(MovieModel.id) \
.having(func.count(GenreModel.id) == len(genres_ids))\
.all()
rated_movies = [movie[0] for movie in movies]
for key, value in ratings.items():
similarities = mongo_similarities.find_one({'id': int(key)})
similarities = similarities['similarities']
similar_items = [item for item in similarities if item['id'] in rated_movies]
similarity = 0
if len(similar_items) > 0:
for item in similar_items:
if item['similarity'] > similarity:
similarity = item['similarity']
movies_similarities[key] = similarity
return movies_similarities
@staticmethod
def get_pairs(ratings, similarities, stats):
return [{
'id': key,
'rating': float(value),
'similarity': similarities[key],
'average_rating': stats[int(key)]['average_rating'],
'ratings_count': stats[int(key)]['count'],
'penalized': stats[int(key)]['penalized'],
} for key, value in ratings.items()]
@staticmethod
def get_user_row(user_id):
mongo_ratings = mongo.db.users_ratings
user_row = mongo_ratings.find_one({'id': user_id})
return user_row['ratings']
@staticmethod
def get_user_rated_movies(user_id):
rated_movies = db.session.query(UserRatingModel).filter_by(userId=user_id).all()
return [row.__dict__ for row in rated_movies]
@staticmethod
def get_user_movies(rated_movies, user_id, include_rated=False):
user_row = RecommendationsHelper.get_user_row(user_id)
if not include_rated:
for movie in rated_movies:
try:
del user_row[str(movie['movieId'])]
except:
print('Movie not found')
else:
penalized_movies = list(filter(lambda movie: movie['rating'] == 0, rated_movies))
for movie in penalized_movies:
try:
del user_row[str(movie['movieId'])]
except:
print('Movie not found')
return user_row
@staticmethod
def get_recommendations(ratings, take, skip, user_id, genres):
recommended_movies = RecommendationsHelper.get_dict(ratings, take, skip)
similarities = RecommendationsHelper.get_similarity_values(user_id, recommended_movies, genres)
stats = RecommendationsHelper.get_stats(recommended_movies.keys())
return RecommendationsHelper.get_pairs(recommended_movies, similarities, stats)
@staticmethod
def get_stats(items):
movies = db.session.query(
MovieModel.id,
func.count(UserRatingModel.id),
func.avg(UserRatingModel.rating),
func.sum(case([(UserRatingModel.rating == 0, 1)], else_=0))
) \
.join(UserRatingModel, isouter=True)\
.filter(MovieModel.id.in_(items)) \
.group_by(MovieModel.id) \
.all()
if len(movies) > 0:
movies = {movie[0]: {
'count': movie[1],
'average_rating': movie[2] if movie[2] is not None else 0,
'penalized': int(movie[3])
} for movie in movies}
return movies
| true |
6d85f1548d6f17ac35b4650450db1cc3ce951231 | Python | toddt/lyman | /lyman/tools/tests/test_graphutils.py | UTF-8 | 1,990 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | from nipype.testing import assert_equal, assert_true
from nipype import Workflow, Node, MapNode, IdentityInterface, DataGrabber
from .. import graphutils as gu
def make_simple_workflow():
wf = Workflow(name="test")
node1 = Node(IdentityInterface(fields=["foo"]), name="node1")
node2 = MapNode(IdentityInterface(fields=["foo"]),
name="node2", iterfield=["foo"])
node3 = Node(IdentityInterface(fields=["foo"]), name="node3")
wf.connect([
(node1, node2, [("foo", "foo")]),
(node2, node3, [("foo", "foo")]),
])
return wf, node1, node2, node3
def test_input_wrapper():
wf, node1, node2, node3 = make_simple_workflow()
s_list = ['s1', 's2']
s_node = gu.make_subject_source(s_list)
g_node = Node(DataGrabber(in_fields=["foo"],
out_fields=["bar"]),
name="g_node")
iw = gu.InputWrapper(wf, s_node, g_node, node1)
yield assert_equal, iw.wf, wf
yield assert_equal, iw.subj_node, s_node
yield assert_equal, iw.grab_node, g_node
yield assert_equal, iw.in_node, node1
iw.connect_inputs()
g = wf._graph
yield assert_true, s_node in g.nodes()
yield assert_true, g_node in g.nodes()
yield assert_true, (s_node, g_node) in g.edges()
def test_find_mapnodes():
wf = make_simple_workflow()[0]
mapnodes = gu.find_mapnodes(wf)
yield assert_equal, mapnodes, ["node2"]
def test_find_nested_workflows():
wf, node1, node2, node3 = make_simple_workflow()
inner_wf = make_simple_workflow()[0]
wf.connect(node3, "foo", inner_wf, "node1.foo"),
workflows = gu.find_nested_workflows(wf)
yield assert_equal, workflows, [inner_wf]
def test_make_subject_source():
subj_list = ['s1', 's2', 's3']
node = gu.make_subject_source(subj_list)
iterable_name, iterable_val = node.iterables
yield assert_equal, iterable_name, "subject_id"
yield assert_equal, iterable_val, subj_list
| true |
39006491f560964f7ef4e25ddc183fb9fdf48381 | Python | rafaelalvesferreira/rtl_data_scrapper | /R_5_7_1_IC.py | UTF-8 | 10,555 | 2.625 | 3 | [] | no_license | import time
import datetime
import os
import random
import logging
import shutil
from func_timeout import func_set_timeout
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
logging.basicConfig(level=logging.INFO,
filename='5-7-1-IC_Matinal.log',
format='%(asctime)s; %(levelname)s; %(message)s')
def Selecionar_Dropdowns(ic,
indicador,
campo,
nome_arquivo,
dia,
driver,
download_path,
branch_code):
'''
Seleciona os dropdowns de acordo com a lista informada.
'''
wait = WebDriverWait(driver, 20)
branchs = {'132000': 'CG', '61913': 'AQ', '85789': 'CB', '63785': 'CX'}
# ajustar a data
element_addr = '//*[@id="dtVisita"]'
wait.until(EC.element_to_be_clickable((By.XPATH, element_addr)))
element = driver.find_element_by_xpath(element_addr).send_keys(dia)
# clicar no dropdown Grupo de IC -> Jornada
element_addr = 'cdGrupoIc'
wait.until(EC.element_to_be_clickable((By.NAME, element_addr)))
select = Select(driver.find_element_by_name(element_addr))
select.select_by_index(ic)
time.sleep(2)
# clicar no dropdown Indicador -> PDV Letura GPS OK
element_addr = 'cdIc'
wait.until(EC.element_to_be_clickable((By.NAME, element_addr)))
select = Select(driver.find_element_by_name(element_addr))
select.select_by_index(indicador)
time.sleep(2)
# clicar no dropdown Indicador -> PDV Letura GPS OK
element_addr = 'cdCampo'
wait.until(EC.element_to_be_clickable((By.NAME, element_addr)))
select = Select(driver.find_element_by_name(element_addr))
select.select_by_index(campo)
time.sleep(2)
# clicar no botão exportar
element = driver.find_element_by_xpath('//*[@id="botExportar"]')
driver.execute_script("arguments[0].click();", element)
time.sleep(2)
loop_status = True
while loop_status:
for file in os.listdir(download_path):
if file.endswith(f'{branch_code}.csv'):
old_file = os.path.join(download_path, file)
new_file = os.path.join(
download_path,
f"{nome_arquivo}_{branchs.get(branch_code)}.csv")
os.rename(old_file, new_file)
loop_status = False
@func_set_timeout(300)
def Relatorio5_7_1_IC(branch, branch_code, login, password, lista, dia='D'):
"""
Função que automatiza a geração dos dados do relatório 3.16.1
variáveis de entrada:
Branch - número do branch de 1 a 4
Branch_code - código do branch no promax 132000, 61913, 85789, 63785
Login - Login do usuário no Promax
Password - Senha
retorna o arquivo csv baixado na pasta final_donwnload_path
"""
# Constantes utilizada
logging.info('5-7-1-IC-Inicio da rotina da filial %s', branch_code)
random.seed()
driver_path = 'chromedriver.exe'
day = str(datetime.datetime.now().date())
lastday = (datetime.date.today() - datetime.timedelta(days=1))
if lastday.strftime('%a') == 'Sun':
lastday = (datetime.date.today() - datetime.timedelta(days=2))
lastday = lastday.strftime('%d/%m/%Y').replace('/', '')
today = datetime.date.today().strftime('%d/%m/%Y').replace('/', '')
data = today
if dia == 'D-1':
data = lastday
final_data_path = os.path.join('C:\\Users',
os.getlogin(),
'Downloads',
day)
try:
# criar uma pasta para o download com nome aleatório
random_folder = str(random.randint(0, 1000))
download_path = os.path.join(final_data_path, random_folder)
os.makedirs(download_path)
logging.info('5-7-1-IC-%s', download_path)
# branch_code = branch_code_number
# branch = branch_number
chrome_Options = Options()
# chrome_Options.add_argument(f"user-data-dir={profile_path}")
chrome_Options.add_argument("--start-maximized")
chrome_Options.add_argument("--disable-popup-blocking")
chrome_Options.add_argument(
"--safebrowsing-disable-download-protection")
chrome_Options.add_argument('--disable-extensions')
chrome_Options.add_argument(
'--safebrowsing-disable-extension-blacklist')
chrome_Options.add_argument('--log-level=3')
chrome_Options.add_argument('--disable-extensions')
chrome_Options.add_argument('test-type')
chrome_Options.add_experimental_option('excludeSwitches',
['enable-logging'])
chrome_Options.add_experimental_option("prefs", {
"profile.default_content_settings.popups": 0,
"download.default_directory": download_path,
"download.prompt_for_download": False,
"safebrowsing.enabled": True,
"extensions_to_open": "inf"
})
driver = webdriver.Chrome(options=chrome_Options,
executable_path=driver_path)
driver.get('http://rotele.promaxcloud.com.br/pw/')
# mudar para o frame 'top'
driver.switch_to.frame(driver.find_element_by_name("top"))
# preencher usuário e senha na primeira página
driver.find_element_by_name('Usuario').send_keys(login)
driver.find_element_by_name('Senha').send_keys(password)
driver.find_element_by_name('cmdConfirma').click()
# selecionar a filial referente ao relatório
element_addr = '/html/body/form/table/tbody[1]/tr[3]/td[2]/select'
select = Select(driver.find_element_by_xpath(element_addr))
select.select_by_value(f"015000{branch}")
driver.find_element_by_name('cmdConfirma').click()
wait = WebDriverWait(driver, 20)
# testar os popups que aparecem no login, como são variáveis
# usaremos os blocos try except para tratar os erros
try:
wait.until(EC.alert_is_present())
except TimeoutException:
logging.warning('5-7-1-IC-Erro de popup 1')
else:
driver.switch_to.alert.accept()
try:
wait.until(EC.alert_is_present())
except TimeoutException:
logging.warning('5-7-1-IC-Erro de popup 2')
else:
driver.switch_to.alert.accept()
try:
wait.until(EC.alert_is_present())
except TimeoutException:
logging.warning('5-7-1-IC-Erro de popup 3')
else:
driver.switch_to.alert.accept()
try:
wait.until(EC.alert_is_present())
except TimeoutException:
logging.warning('5-7-1-Erro de popup 4')
else:
driver.switch_to.alert.accept()
# esperar o frame principal aparecer e mudar para ele
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID,
'iFrameMenu')))
# encontrar e clicar no menu novo siv
element_addr = '//*[@id="out2000000000t"]'
wait.until(EC.element_to_be_clickable((By.XPATH, element_addr)))
element = driver.find_element_by_xpath(element_addr)
driver.execute_script("arguments[0].click();", element)
# aguardar a janela abrir
# time.sleep(10)
wait.until(EC.number_of_windows_to_be(2))
driver.switch_to.window(driver.window_handles[1])
# encontrar e clicar no menu 5.7.1
time.sleep(3)
element_addr = '//*[@id="treeMenu"]/ul/li[4]/ul/li[7]/ul/li[1]/a'
wait.until(EC.invisibility_of_element_located((By.XPATH,
element_addr)))
element = driver.find_element_by_xpath(element_addr)
driver.execute_script("arguments[0].click();", element)
time.sleep(2)
# clicar na lista no nome do GV
element_addr = '//*[@id="listaEquipeVendas"]/ul/li[1]/a/ins[1]'
wait.until(EC.element_to_be_clickable((By.XPATH, element_addr)))
element = driver.find_element_by_xpath(element_addr)
driver.execute_script("arguments[0].click();", element)
logging.info('5-7-1-IC-IC_GPS - dia %s', today)
for item in lista:
Selecionar_Dropdowns(item[0],
item[1],
item[2],
item[3],
data,
driver,
download_path,
branch_code)
driver.switch_to.window(driver.window_handles[2])
driver.close()
driver.switch_to.window(driver.window_handles[1])
driver.close()
driver.switch_to.window(driver.window_handles[0])
driver.close()
except (TimeoutException,
NoSuchElementException,
StaleElementReferenceException,
WebDriverException) as error:
logging.warning('5-7-1-IC-%s', error)
with open(os.path.join(final_data_path,
f'5-7-1-IC-{branch_code}.fail'), 'w'):
pass
shutil.rmtree(download_path, ignore_errors=True)
for window in driver.window_handles:
driver.switch_to.window(window)
driver.close()
Relatorio5_7_1_IC(branch, branch_code, login, password, lista)
for root, dirs, files in os.walk(download_path):
for name in files:
old_file = os.path.join(root, name)
new_file = os.path.join(final_data_path, name)
os.rename(old_file, new_file)
shutil.rmtree(download_path, ignore_errors=True)
logging.info('5-7-1-IC-Final da rotina da filial %s', branch_code)
with open(os.path.join(final_data_path,
f'5-7-1-IC-{branch_code}.success'), 'w'):
pass
return
| true |
e3fac649e6f0c45ebd89b0580caf854a7e4c822d | Python | PJoyet/challenge_project | /scripts/challenge2/distance_servoing.py | UTF-8 | 1,505 | 2.71875 | 3 | [] | no_license | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""author: Pierre Joyet (3407684) - Marine CORNET (3531423) - Project ROS- M1 SAR 2020"""
import rospy
from geometry_msgs.msg import Twist
from challenge_project.msg import cardinal_direction
# Parameter initialization
pubTopicName = "/cmd_vel" # Motor command topic
subTopicName = "/lds_distance" # Lidar message topic
max_linear_speed = 0.22 # Maximum linear speed of the robot
max_angular_speed = 2.84 # Maximum angular speed of the robot
def set_speed(linear,angular):
# Publish the speed data
pub = rospy.Publisher(pubTopicName,Twist,queue_size=3)
twist = Twist()
if linear >= max_linear_speed:
linear = max_linear_speed
if angular >= max_angular_speed:
linear = max_angular_speed
twist.linear.x = linear
twist.angular.z = angular
pub.publish(twist)
def distance_servoing(lds):
l_s = rospy.get_param("/linear_scale")
d = rospy.get_param("/constant_distance")
if lds.N <=d+0.3: # if the front distance less than 0.6
delta = (lds.N-d)*0.6 # get distance from robot to desired position
if lds.N <= d: # if the front distance less than desired distance
set_speed(-l_s+delta,0.0) # set robot move backward
else :
set_speed(l_s+delta,0.0) # set robot move forward
else:
set_speed(0,0)
if __name__ == '__main__':
rospy.init_node('lds_distance-servoing')
rospy.Subscriber(subTopicName, cardinal_direction, distance_servoing)
rospy.spin() | true |
753ee19745e64c484d6608020621e6b3fb69bdcc | Python | reidac/AOC2020 | /day16b.py | UTF-8 | 3,314 | 2.9375 | 3 | [] | no_license | import re
if __name__=="__main__":
f = open("day16.txt")
range_dict = {}
error_rate = 0
my_ticket = None
valid_tickets = []
nearby_tickets_seen = False
for ln in f:
m = re.search('^(.*): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)',ln)
if m:
datum = m.group(1)
range1 = (int(m.group(2)),int(m.group(3)))
range2 = (int(m.group(4)),int(m.group(5)))
range_dict[datum] = [range1,range2]
# All ranges are specified before any tickets are seen.
m = re.search('nearby tickets:',ln)
if m:
nearby_tickets_seen = True
m = re.search('^(([0-9]+),)+[0-9]+',ln)
if m:
vals = list(map(int,re.findall('[0-9]+',ln)))
if not (nearby_tickets_seen):
my_ticket = vals
else:
t_valid = True
for v in vals:
v_valid = False
for rl in range_dict.values():
for rng in rl:
if (v>=rng[0]) and (v<=rng[1]):
v_valid = True
break
if v_valid:
break
if (t_valid) and not (v_valid):
t_valid = False
break
if t_valid: # Every entry fits in somewhere.
valid_tickets.append(list(vals))
# At this point, we have a list, valid_tickets, of tickets
# for which every number fits in to some range or other.
# Now figure out the slots.
nslots = len(my_ticket)
all_slots = set()
for k in range_dict.keys():
all_slots.add(k)
candidates = [all_slots.copy() for i in range(nslots)]
for tkt in valid_tickets:
for slot in range(len(tkt)):
removal_list = []
v = tkt[slot]
for cat in candidates[slot]:
rset = range_dict[cat]
if (((v<rset[0][0]) or (v>rset[0][1]))
and ((v<rset[1][0]) or (v>rset[1][1]))):
removal_list.append(cat)
for rm in removal_list:
candidates[slot].remove(rm)
# Now we have "reduced candidates" constrained by the ranges.
# We can reduce further by successive elimination.
resolved = set()
done = False
while not done:
# Find all the singletons we haven't seen before.
singletons = set()
for c in candidates:
if len(c)==1:
cc = c.copy() # Better way to do this? Want to preserve c.
cv = cc.pop()
if cv not in resolved:
singletons.add(cv)
if len(singletons)==0:
done = True
else:
for c in candidates:
if len(c)!=1:
for s in singletons:
c.discard(s)
resolved.update(singletons)
# OK, we have unique IDs for each slot.
res = 1
for i in range(len(candidates)):
for cv in candidates[i]: # Only one iteration.
if cv[0:9]=="departure":
res *= my_ticket[i]
print("Result: %d." % res)
| true |
c3b9d7eff1235613f806b600715878b3a3b70193 | Python | bigboss-pf/Hogwarts-hour | /homework_first/cal.py | UTF-8 | 288 | 2.625 | 3 | [] | no_license | """
~~~~~~~~~~~~~~~~~~~~~~~
author:hour
time:2020/12/11
E-mail:58166728@qq.com
~~~~~~~~~~~~~~~~~~~~~~~
"""
class Calculator():
def add(self,a,b):
return a+b
def sub(self,a,b):
return a-b
def mul(self,a,b):
return a*b
def div(self,a,b):
return a/b
| true |
c7cbcf16c864e660c8792219bd81800ff525fe41 | Python | hiteshkrypton/Python-Programs | /string.py | UTF-8 | 193 | 4.28125 | 4 | [] | no_license | # Python program to Print Characters in a String
str1 = input("Please Enter your Own String : ")
for i in range(len(str1)):
print("The Character at %d Index Position = %c" %(i, str1[i]))
| true |
46c2a93a42f433df6ba3a01716367dae65e515ce | Python | ankitbhatia8993/parkingservice_python | /src/manager/vehicle_parking_slot_manager.py | UTF-8 | 3,394 | 2.765625 | 3 | [] | no_license | from dao.cache import Cache
from dao.inmemory import VehicleParkingSlotDao
from entity.vehicle_parking_slot import VehicleParkingSlot
from manager.parking_slot_manager import ParkingSlotManager
from manager.vehicle_manager import VehicleManager
from messages.messages import SuccessMessages, ErrorMessages
class VehicleParkingSlotManager:
def __init__(self):
self.vehicle_parking_slot_dao = VehicleParkingSlotDao()
self.vehicle_manager = VehicleManager()
self.parking_slot_manager = ParkingSlotManager()
self.cache = Cache.get_instance()
def park(self, registration_number):
parked_vehicle = self.get_by_registration_number(registration_number, printing=False)
if parked_vehicle and parked_vehicle.enabled:
return None
parking_slot_id = self.cache.get_nearest_slot()
if parking_slot_id:
vehicle_parking_slot = VehicleParkingSlot(parking_slot_id, registration_number)
vehicle_parking_slot = self.vehicle_parking_slot_dao.create(vehicle_parking_slot)
self.cache.remove_slot(parking_slot_id)
print('Allocated slot number: %d' % vehicle_parking_slot.parking_slot_id)
return vehicle_parking_slot
else:
print('Sorry, parking lot is full')
return None
def leave(self, slot_number):
self.vehicle_parking_slot_dao.disable_vehicle_parking(slot_number)
self.cache.add_slot(slot_number)
print(SuccessMessages.LEAVE_PARKING_SLOT_SUCCESS % slot_number)
def get_status(self):
vehicle_parking_slots = self.vehicle_parking_slot_dao.get_occupied_slots()
print(SuccessMessages.STATUS_HEADER)
for vehicle_parking_slot in vehicle_parking_slots:
registration_number = vehicle_parking_slot.vehicle_registration_number
vehicle = self.vehicle_manager.get(registration_number)
print('%d %s %s' % (vehicle_parking_slot.parking_slot_id, registration_number, vehicle.color))
def get_slot_numbers_for_color(self, color):
vehicles = self.vehicle_manager.get_vehicles_by_color(color)
slot_numbers = []
for vehicle in vehicles:
vehicle_parking_slot = self.vehicle_parking_slot_dao.get_by_vehicle(vehicle.registration_number)
if vehicle_parking_slot:
slot_numbers.append(vehicle_parking_slot.parking_slot_id)
print(', '.join(map(lambda s: str(s), slot_numbers)))
return slot_numbers
def get_by_registration_number(self, registration_number, printing=True):
vehicle_parking_slot = self.vehicle_parking_slot_dao.get_by_vehicle(registration_number)
if printing and vehicle_parking_slot:
print(vehicle_parking_slot.parking_slot_id)
elif printing:
print(ErrorMessages.NOT_FOUND)
return vehicle_parking_slot
def get_available_slots(self):
vehicle_parking_slots = self.vehicle_parking_slot_dao.get_occupied_slots()
parking_slots = self.parking_slot_manager.get_all()
available_slots = []
for parking_slot in parking_slots:
intersection = list(filter(lambda entry: entry.parking_slot_id == parking_slot.id, vehicle_parking_slots))
if not intersection:
available_slots.append(parking_slot.id)
return available_slots
| true |
1850e9c998ced777e249dca102a1453164504049 | Python | piba941/Real-Time-Digit-Recognizer | /CNN_training.py | UTF-8 | 4,957 | 2.6875 | 3 | [] | no_license | import numpy as np
from keras.models import Sequential,load_model
from keras.layers import Dense , Conv2D, Dropout, Flatten, MaxPooling2D
from keras.utils import np_utils
from keras import regularizers
from keras.optimizers import Nadam
from keras.callbacks import ModelCheckpoint
import h5py
import os
import cv2
from sklearn.model_selection import train_test_split
# loading data from the path specified
def data_loader(path_train,path_test):
train_list=os.listdir(path_train)
# train_list contains mapped class names to interger labels
num_classes=len(train_list)
# creating empty lists of training and testing dataset
x_train=[]
y_train=[]
x_test=[]
y_test=[]
# Loading training data
for label,elem in enumerate(train_list):
path1=path_train+'/'+str(elem)
images=os.listdir(path1)
for elem2 in images:
path2=path1+'/'+str(elem2)
# Read the image form the directory
img = cv2.imread(path2)
# converting into grey scale
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img=img.reshape(28,28,1)
# Append image to the train data list
x_train.append(img)
# Append class-label corresponding to the image
y_train.append(str(label))
# Loading testing data
path1=path_test+'/'+str(elem)
images=os.listdir(path1)
for elem2 in images:
path2=path1+'/'+str(elem2)
# Read the image form the directory
img = cv2.imread(path2)
#converting into grey scale
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img=img.reshape(28,28,1)
# Append image to the test data list
x_test.append(img)
# Append class-label corresponding to the image
y_test.append(str(label))
# Converting lists into numpy arrays
x_train=np.asarray(x_train)
y_train=np.asarray(y_train)
x_test=np.asarray(x_test)
y_test=np.asarray(y_test)
return x_train,y_train,x_test,y_test
path_train='./Data/train'
path_test='./Data/test'
X_train,y_train,X_test,y_test=data_loader(path_train,path_test)
input_shape = (X_train.shape[1], X_train.shape[2],1 )
print(X_train.shape)
# forcing the precision of the pixel values to be 32 bit
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
# normalize inputs between 0-1
X_train = X_train / 255.
X_test = X_test / 255.
#converting labels into One-Hot encoding
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
#Splitting the trining data into training and validation
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
def model():
# create model
model = Sequential()
#We will add 2 Convolution layers with 32 filters of 3x3, keeping the padding as same
model.add(Conv2D(32, (3, 3), strides=(1, 1), padding = 'same' , input_shape = input_shape, activation = 'relu', kernel_initializer = 'glorot_uniform', kernel_regularizer = regularizers.l2(0.01)))
model.add(Conv2D(32, (3, 3), strides=(1, 1), padding = 'same', activation = 'relu', kernel_initializer = 'glorot_uniform', kernel_regularizer = regularizers.l2(0.01)))
#Pooling the feature map using a 2x2 pool filter
model.add(MaxPooling2D((2, 2), strides=(2, 2), padding = 'valid'))
#Adding 2 more Convolutional layers having 64 filters of 3x3
model.add(Conv2D(64, (3, 3), strides=(1, 1), padding = 'same', activation = 'relu', kernel_initializer = 'glorot_uniform', kernel_regularizer = regularizers.l2(0.01)))
model.add(Conv2D(64, (3, 3), strides=(1, 1), padding = 'same', activation = 'relu', kernel_initializer = 'glorot_uniform', kernel_regularizer = regularizers.l2(0.01)))
#Flatten the feature map
model.add(Flatten())
#Adding FC Layers
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.3))
#A softmax activation function is used on last layer to get probabilities
#allow one class of the 10 to be selected as the model's output
model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='Nadam', metrics=['accuracy'])
#model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
return model
model = model()
# Fit the model
#The model is fit over 10 epochs with updates every 200 images. The test data is used as the validation dataset
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=2, batch_size=200, verbose=1)
# saving the trained model
model.save('trained_model.h5')
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=1)
print(scores)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))
| true |
ce496380c8d890ed5dd1a4a193e28ff2c387d856 | Python | turky/sphinxcontrib-getstart-sphinx | /sphinxcontrib/getstart_sphinx/footnote_relocator.py | UTF-8 | 1,191 | 2.875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from docutils import nodes
from sphinx.transforms import SphinxTransform
class FootnoteVisitor(nodes.NodeVisitor):
def __init__(self, document):
self.footnotes = []
nodes.NodeVisitor.__init__(self, document)
def visit_section(self, node):
for footnote in self.footnotes:
footnote.parent.remove(footnote)
index = node.parent.index(node)
node.parent.insert(index, footnote)
self.footnotes = []
def depart_section(self, node):
for footnote in self.footnotes:
footnote.parent.remove(footnote)
node += footnote
self.footnotes = []
def visit_footnote(self, node):
self.footnotes.append(node)
raise nodes.SkipNode
def unknown_visit(self, node):
pass
def unknown_departure(self, node):
pass
class FootnoteReloactor(SphinxTransform):
"""文中に登場する脚注を章末に移動する。"""
default_priority = 100
def apply(self):
visitor = FootnoteVisitor(self.document)
self.document.walkabout(visitor)
def setup(app):
app.add_post_transform(FootnoteReloactor)
| true |
1dc57b4ce46dc4e2869d8cc0581950bc3678599a | Python | bloomfieldfong/Generador-de-Analizadores | /Aritmetica.py | UTF-8 | 1,453 | 3.1875 | 3 | [] | no_license | from automata import *
from scanner import *
#keywords
keywords =['while', 'do', 'if', 'switch']
#character
letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
letter = character(letter)
digit = "0123456789"
digit = character(digit)
tab = chr(9)
tab = character(tab)
eol = chr(10)
eol = character(eol)
#tokens
ident=letter+" (("+letter+"|"+digit+")*)"
number=digit+" (("+digit+")*)"
automata_keyword=[ident]
automata =[number]
charss =[ chr(9), chr(10)]
scanner(keywords, automata , automata_keyword, charss)
def Expr():
while(True):
Stat ("")
get(".")
return result
def Stat ():
value = 0
value = input()
value = Factor(value)
return result
def Expression( result):
result1 = 0
result2 = 0
result1 = Term(result1)
while(follow() == '+' or follow() == '-'):
if(follow()=='+'):
result2=Term(result2)
result1+=result2
elif(follow()=='-'):
result2=Term(result2)
result1-=result2
result=result1
return result
def Term( result):
result1 = 0
result2 = 0
result1 = Factor(result1)
while(follow() == '*' or follow() == '/'):
if(follow()=='*'):
result2=Factor(result2)
result1*=result2
elif(follow()=='/'):
result2=Factor(result2)
result1/=result2
result=result1
return result
def Factor( result):
signo=1
if follow() =="-":
signo = -1
## "("Expression( result)")")
result*=signo
return result
def Number( result):
result = int(value)
return result
| true |
4a32cdb4fd31957373d0712f35dc54d9baa49816 | Python | danielle20-meet/Meetyl1201819 | /game/ball.py | UTF-8 | 780 | 3.8125 | 4 | [] | no_license | from turtle import Turtle
import turtle
class Ball (Turtle):
def __init__(self, x, y, dx, dy, r, color):
Turtle.__init__(self)
self.penup()
self.goto(x, y)
self.dx = dx
self.dy = dy
self.r = r
self.shape("circle")
self.shapesize(r/10)
self.fillcolor(color)
def move(self, screen_width, screen_hei):
current_x = self.xcor()
current_y = self.ycor()
newx = current_x + self.dx
newy = current_y + self.dy
right_side = newx + self.r
left_side = newx - self.r
up_side = newy + self.r
down_side = newy - self.r
self.goto(newx, newy)
if right_side > screen_width:
self.dx = -self.dx
if left_side < -screen_width:
self.dx = -self.dx
if up_side > screen_hei:
self.dy = -self.dy
if down_side < -screen_hei:
self.dy = -self.dy
| true |
47d00848e2b0ff4670d23fbe35fc95c222cf9055 | Python | Tuxinet/webscraper2.0 | /scraper.py | UTF-8 | 3,503 | 2.703125 | 3 | [] | no_license | import robotparser
import socket
import sys
from time import sleep
from urllib import FancyURLopener
import urlparse
from bs4 import BeautifulSoup
import MySql
class myOpener(FancyURLopener, object):
version = 'Slow Web Crawler v0.1'
class Scraper():
def __init__(self, url, urlLimit, delay):
#self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#self.s.settimeout(3600)
#self.s.connect(("localhost", 1337))
self.sleeptime = delay
self.limit = urlLimit
self.url = url
self.db = MySql.Database("127.0.0.1", "pythondb", "pythonUser", "pythondb")
self.filename = self.url
self.urlfile = open(self.filename + '.txt', 'wb')
self.url = 'http://' + self.url
self.urls = [self.url]
self.counter = 0
self.rp = robotparser.RobotFileParser()
self.rp.set_url(self.url + '/robots.txt')
self.rp.read()
print 'Set robotparser url to:', self.url + '/robots.txt'
self.urlOpener = myOpener()
def setConnection(self, host, port):
try:
self.s.connect(host, port)
except:
print "Unable to connect to host"
sys.exit()
print "Connected to DatabaseHandler, waiting for task..."
def crawl(self):
while len(self.urls) > 0:
sleep(self.sleeptime)
self.getUrlFromDb()
try:
try:
htmltext = self.urlOpener.open(self.urls[0]).read()
print 'Opening:', self.urls[0]
except:
print "Something went wrong while opening the url:", self.urls[0]
self.soup = BeautifulSoup(htmltext)
self.urls.pop(0)
for tag in self.soup.findAll("a", href=True):
tag['href'] = urlparse.urljoin(self.url, tag['href'])
if self.url in tag['href'] and self.checkDB(tag['href']) != True and self.rp.can_fetch('*', tag['href']):
self.counter += 1
print 'Adding:', tag['href']
self.markVisited(tag['href'])
self.urlfile.write(tag['href'] + '\n')
self.addToDB(tag['href'])
if self.counter < self.limit:
self.urls.append(tag['href'])
except Exception, e:
print e
def getUrlFromDb(self):
q = '''
SELECT VISITED FROM pythondbtable
WHERE VISITED LIKE "1";
'''
response = self.db.query(q)
print response
def markVisited(self, url):
q = '''
INSERT INTO PYTHONDBTABLE (WEBSITE, URL, VISITED) VALUES ('%s', '%s', '%s');
''' % (self.url, url, '1')
def addToDB(self, url):
q = """
insert into pythondbtable (website, url) values ('%s', '%s');
""" % (self.url, url)
self.db.query(q)
def checkDB(self, url):
q = """
select url from pythondbtable where url like '%s';
""" % (url)
response = self.db.query(q)
if response:
return True
else:
return False
def __del__(self):
self.urlfile.close()
| true |
acccdd694e27129c9188138f4c074822d2fdadda | Python | pyro-team/bkt-toolbox | /features/bkt_excel/cells.py | UTF-8 | 82,745 | 2.625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
'''
Created on 2017-07-18
@author: Florian Stallmann
'''
from __future__ import absolute_import
# import System.Convert as Converter #required for convert to double
# import System.DateTime as DateTime #required for parse as date and time
from System import DateTime, Array
import bkt
import bkt.library.excel.helpers as xllib
import bkt.library.excel.constants as xlcon
import bkt.dotnet as dotnet
Forms = dotnet.import_forms() #required to copy text to clipboard
class CellsOps(object):
# hidden_columns = {}
# hidden_rows = {}
last_formula = "*100"
last_prepend = "ID-"
last_append = "...!?"
last_slice_pos = "2:"
last_slice_text = "/"
#regex match count
last_regex_match_pattern = r"([A-Z])\w+"
#regex split
last_regex_split_pattern = r"[;,\. ]+"
last_regex_split_mode = 0
#regex replace
last_regex_sub_pattern = r"\sand\s"
last_regex_sub_repl = r" & "
@staticmethod
def _set_hidden_name(key, sheet, rng):
try:
#sheet.Names(key).RefersToLocal = "=" + address
sheet.Names(key).RefersTo = rng
except:
#sheet.Names.Add(Name=key, RefersToLocal="=" + address, Visible=False)
sheet.Names.Add(Name=key, RefersTo=rng, Visible=False)
@staticmethod
def _get_hidden_name(key, sheet, delete=True):
try:
# rng = sheet.Names(key).RefersToRange -> Cuts off too long range strings, below method is better
addr = sheet.Names(key).RefersToLocal[1:]
pos = addr.find("!")+1
addr = addr.replace(addr[0:pos], "") #remove sheet names to support much longer range strings
if delete:
sheet.Names(key).Delete()
return sheet.Range(addr)
except:
return None
# @staticmethod
# def _del_hidden_name(key, sheet):
# try:
# name = sheet.Names(key).Delete()
# except:
# pass
@classmethod
def prepend_text(cls, cells, application):
input_text = bkt.ui.show_user_input("Text eingeben, der vor alle Zellen geschrieben werden soll. Existierende Formeln werden überschrieben und durch Werte ersetzt.\n\nMögliche Platzhalter: [counter], [row], [column].", "Text voranstellen", cls.last_prepend)
if not input_text:
return
if not xllib.confirm_no_undo(): return
cls.last_prepend = input_text
number_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
counter = 1
for cell in cells:
input_text_local = input_text.replace("[counter]", str(counter)).replace("[row]", str(cell.Row)).replace("[column]", str(cell.Column))
cell.Value = input_text_local + cell.Text
cell.NumberFormatLocal = number_format
counter += 1
@classmethod
def append_text(cls, cells, application):
input_text = bkt.ui.show_user_input("Text eingeben, der hinter alle Zellen geschrieben werden soll. Existierende Formeln werden überschrieben und durch Werte ersetzt.\n\nMögliche Platzhalter: [counter], [row], [column].", "Text anhängen", cls.last_append)
if not input_text:
return
if not xllib.confirm_no_undo(): return
cls.last_append = input_text
number_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
counter = 1
for cell in cells:
input_text_local = input_text.replace("[counter]", str(counter)).replace("[row]", str(cell.Row)).replace("[column]", str(cell.Column))
cell.Value = cell.Text + input_text_local
cell.NumberFormatLocal = number_format
counter += 1
@classmethod
def slice_text(cls, cells, application):
def _get_slicer(pos_text):
input_params = pos_text.strip(' \t\n\r[]').split(":")
#Extract single character
if len(input_params) == 1:
start = int(input_params[0])
stop = None if start < 0 else start + 1
#Extract string with start and stop
elif len(input_params) == 2:
start = 0 if not input_params[0] else int(input_params[0])
stop = None if not input_params[1] else int(input_params[1])
else:
raise ValueError('invalid number of parameters')
if stop is not None and ((start > 0 and stop > 0) or (start < 0 and stop < 0)) and start >= stop:
raise ValueError('no text remains as start is after stop')
return slice(start, stop)
preview_cell = application.ActiveCell
def _preview(sender, e):
try:
if text.Text == '':
txt_preview.Text = ''
else:
s = _get_slicer(text.Text)
txt_preview.Text = preview_cell.Text[s]
except:
txt_preview.Text = "FEHLER"
explanation = '''Start- und Stopp-Position zum Schneiden getrennt mit ":" eingeben. Ist keine Start-Position gegeben, wird diese auf 0 gesetzt. Ist keine Stopp-Position gegeben, wird diese bis Textende gesetzt. Eine negative Position bedeutet, dass diese vom Textende berechnet wird.
Beispiel für "ABCDEF":
[2:] = CDEF Entferne die beiden ersten Zeichen
[:2] = AB Entferne alles nach dem zweiten Zeichen
[-2:] = EF Entferne alles bis zum vorletzten Zeichen
[2:-2] = CD Entferne 2 Zeichen an Anfang und Ende'''
user_form = bkt.ui.UserInputBox(explanation, "Text anhand Position schneiden")
text = user_form._add_textbox("text", cls.last_slice_pos)
text.TextChanged += _preview
user_form._add_label("Vorschau für aktive Zelle:")
txt_preview = user_form._add_textbox("preview")
txt_preview.ReadOnly = True
_preview(None, None)
form_return = user_form.show()
if len(form_return) == 0 or form_return["text"] == '':
return
if not xllib.confirm_no_undo(): return
number_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
cls.last_slice_pos = form_return["text"]
try:
s = _get_slicer(form_return["text"])
except:
bkt.message("Ungültige Eingabe!")
return
for cell in cells:
cell.Value = cell.Text[s]
cell.NumberFormatLocal = number_format
@classmethod
def find_and_slice_text(cls, cells, application):
def _slice_text(initial_text, search_text, find_method, rslice):
pos = find_method(initial_text, search_text)
if pos == -1:
return initial_text
start = pos+len(search_text) if rslice else 0
stop = None if rslice else pos
s = slice(start, stop)
return initial_text[s]
preview_cell = application.ActiveCell
def _preview(sender, e):
try:
find_method = str.rfind if cb_rfind.Checked else str.find
txt_preview.Text = _slice_text(preview_cell.Text, text.Text, find_method, cb_rslice.Checked)
except:
txt_preview.Text = "FEHLER"
user_form = bkt.ui.UserInputBox("Gibt Zelleninhalt von Beginn bis zum eingegebenen Text zurück. Wird der Text nicht gefunden, bleibt der Zelleninhalt unverändert.", "Text anhand Zeichen schneiden")
text = user_form._add_textbox("text", cls.last_slice_text)
text.TextChanged += _preview
cb_rslice = user_form._add_checkbox("rslice", "Rechten Teil zurückgeben (ab eingegebenem Text bis Ende)")
cb_rslice.CheckedChanged += _preview
cb_rfind = user_form._add_checkbox("rfind", "Von rechts anfangen zu suchen")
cb_rfind.CheckedChanged += _preview
user_form._add_label("Vorschau für aktive Zelle:")
txt_preview = user_form._add_textbox("preview")
txt_preview.ReadOnly = True
_preview(None, None)
form_return = user_form.show()
if len(form_return) == 0 or form_return["text"] == '':
return
if not xllib.confirm_no_undo(): return
find_method = str.rfind if form_return["rfind"] else str.find
number_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
cls.last_slice_text = form_return["text"]
for cell in cells:
try:
cell.Value = _slice_text(cell.Text, form_return["text"], find_method, form_return["rslice"])
cell.NumberFormatLocal = number_format
except:
pass
@classmethod
def apply_formula(cls, cells, application):
from string import Template
dec_sep = application.International(xlcon.XlApplicationInternational["xlDecimalSeparator"])
active_cell = application.ActiveCell
preview_cell_format = active_cell.NumberFormatLocal
preview_cell_formula = active_cell.FormulaLocal.lstrip("=")
preview_cell_address = active_cell.AddressLocal(False, False)
try:
preview_cell_value = str(active_cell.Value2).replace('.', dec_sep)
except:
preview_cell_value = -2146826273 #"#Value!"
def _preview(sender, e):
try:
create_formulas = text.Text[0] == "="
formula = text.Text if create_formulas or "$cell" in text.Text else "$cell" + text.Text
template = Template(formula)
formula = template.safe_substitute({"cell": preview_cell_address, "cellvalue": preview_cell_value})
if create_formulas:
formula = template.safe_substitute({"cell": preview_cell_formula, "cellvalue": preview_cell_value})
# formula = formula.replace("[cell]", preview_cell_formula)
formula = formula[1:]
else:
formula = template.safe_substitute({"cell": preview_cell_address, "cellvalue": preview_cell_value})
# formula = formula.replace("[cell]", preview_cell_value)
# formula = formula.replace("[cell]", preview_cell_address)
# formula = template.safe_substitute({"cell": preview_cell_address, "cellvalue": preview_cell_value})
txt_preview.Text = "=" + formula
txt_preview2.Text = str(xllib.xls_evaluate(formula, dec_sep, preview_cell_format))
except:
txt_preview.Text = "FEHLER"
txt_preview2.Text = "FEHLER"
user_form = bkt.ui.UserInputBox("Hier kann eine Formel auf alle markierten Zellen angewendet werden. Soll der Zelleninhalt nicht am Anfang stehen, können Sie mit dem Platzhalter $cell und $cellvalue arbeiten. Standardmäßig wird der resultierende Wert eingefügt (sofern die Formel nicht fehlerhaft ist). Wenn Ihre Eingabe mit '=' beginnt, wird eine Formel erstellt. In der Auswahlbox finden Sie Beispiele für mögliche Eingaben.", "Formel anwenden")
text = user_form._add_combobox("formula", cls.last_formula, ["*100", "/100", "*(-1)", "+A1", "/SUMME(A1:A3)", "ABS($cell)", "RUNDEN($cell;2)", "ABRUNDEN($cell;2)", "AUFRUNDEN($cell;2)", "KÜRZEN($cell)", "1/$cell", "=($cell)*100", "GROSS(\"$cellvalue\")"])
text.TextChanged += _preview
user_form._add_checkbox("skip_existing_formulas", "Bestehende Formeln überspringen und nicht verändern")
user_form._add_label("Vorschau für aktive Zelle:")
txt_preview = user_form._add_textbox("preview")
txt_preview.ReadOnly = True
txt_preview2 = user_form._add_textbox("preview2")
txt_preview2.ReadOnly = True
_preview(None, None)
form_return = user_form.show()
if len(form_return) == 0:
return
if not xllib.confirm_no_undo(): return
err_counter = 0
formula = form_return["formula"]
cls.last_formula = formula
create_formulas = formula[0] == "="
formula = formula if create_formulas or "$cell" in formula else "($cell)" + formula
template = Template(formula)
for cell in cells:
if cell.Value2 is None or (cell.HasFormula and form_return["skip_existing_formulas"]):
continue
try:
cell_value = str(cell.Value2).replace('.', dec_sep)
except:
cell_value = -2146826273 #"#Value!"
# if cell.HasFormula and create_formulas:
# new_formula = formula.replace("[cell]", cell.FormulaLocal[1:])
# else:
# new_formula = formula.replace("[cell]", cell.FormulaLocal)
try:
if create_formulas:
if cell.HasFormula:
cell.FormulaLocal = template.safe_substitute({"cell": cell.FormulaLocal[1:], "cellvalue": cell_value})
else:
cell.FormulaLocal = template.safe_substitute({"cell": cell.FormulaLocal, "cellvalue": cell_value})
else:
new_formula = template.safe_substitute({"cell": cell.AddressLocal(False, False), "cellvalue": cell_value})
cell.FormulaLocal = application.Evaluate(new_formula)
# cell.FormulaLocal = "=" + new_formula
# #On error do not replace with int value of error
# if not application.WorksheetFunction.IsError(cell):
# cell.Value = cell.Value()
except:
err_counter += 1
cell.AddComment("Error applying formula")
#bkt.helpers.exception_as_message(str(cell.AddressLocal()))
if err_counter > 0:
bkt.message("Fehler! Formel war auf " + str(err_counter) + " Zelle(n) nicht anwendbar.")
@classmethod
def regex_match_count(cls, cells, application):
import re
from itertools import chain
preview_cell_value = application.ActiveCell.Text
def _get_flags():
flags=0
if ignorecase.Checked:
flags = re.IGNORECASE
return flags
def _do_regex(regex, string):
if regex.groups > 0:
return sum(res is not None for res in bkt.helpers.flatten(m.groups() for m in regex.finditer(string)))
else:
# return len(list(m.group() for m in regex.finditer(string)))
return len(list(regex.finditer(string)))
def _preview(sender, e):
try:
regex = re.compile(text.Text, _get_flags())
txt_preview.Text = str(_do_regex(regex, preview_cell_value))
except Exception as e:
txt_preview.Text = "FEHLER: " + str(e)
user_form = bkt.ui.UserInputBox("Hier kann ein regulärer Ausdruck in allen markierten Zellen gesucht und die Anzahl der Funde gezählt werden. In der Auswahlbox finden Sie Beispiele für mögliche Eingaben.", "RegEx anwenden")
text = user_form._add_combobox("regex", cls.last_regex_match_pattern, [r"[;,\. ]+", r"([A-Z])\w+", r"([+-]?[\d\.]+,*[0-9]*)", r"[\w\.-]+@[\w\.-]+\.\w{2,4}"])
text.TextChanged += _preview
ignorecase = user_form._add_checkbox("ignorecase", "Groß-/Kleinschreibung ignorieren")
ignorecase.CheckedChanged += _preview
user_form._add_label("Vorschau für aktive Zelle:")
txt_preview = user_form._add_textbox("preview")
txt_preview.ReadOnly = True
_preview(None, None)
form_return = user_form.show()
if len(form_return) == 0:
return
try:
regex = re.compile(form_return["regex"], _get_flags())
except Exception as e:
bkt.message("Fehler! RegEx kann nicht kompiliert werden: "+str(e))
return
if not xllib.confirm_no_undo(): return
err_counter = 0
cls.last_regex_match_pattern = form_return["regex"]
for cell in cells:
if cell.Value2 is None:
continue
try:
cell.Value = _do_regex(regex, cell.Text)
except:
err_counter += 1
#bkt.helpers.exception_as_message(str(cell.AddressLocal()))
if err_counter > 0:
bkt.message("Fehler! RegEx war auf " + str(err_counter) + " Zelle(n) nicht anwendbar.")
@classmethod
def regex_split_to_columns(cls, cells, application):
import re
from itertools import chain
preview_cell_value = application.ActiveCell.Text
def _get_flags():
flags=0
if ignorecase.Checked:
flags = re.IGNORECASE
return flags
def _get_mode():
for radio in mode_radios:
if radio.Checked:
return radio.Text
def _do_regex(regex, string, join=None):
current_mode = _get_mode()
if current_mode.startswith("Split"):
regex_result = regex.split(string)
else:
if regex.groups > 0:
regex_result = list(bkt.helpers.flatten(m.groups("") for m in regex.finditer(string)))
else:
regex_result = list(m.group() for m in regex.finditer(string))
if join is None:
return regex_result
else:
return join.join(res or "" for res in regex_result)
def _preview(sender, e):
try:
regex = re.compile(text.Text, _get_flags())
txt_preview.Text = _do_regex(regex, preview_cell_value, "\t")
except Exception as e:
txt_preview.Text = "FEHLER: " + str(e)
user_form = bkt.ui.UserInputBox("Hier kann ein regulärer Ausdruck auf alle markierten Zellen angewendet werden. In der Auswahlbox finden Sie Beispiele für mögliche Eingaben.", "RegEx anwenden")
text = user_form._add_combobox("regex", cls.last_regex_split_pattern, [r"[;,\. ]+", r"([A-Z])\w+", r"([+-]?[\d\.]+,*[0-9]*)", r"[\w\.-]+@[\w\.-]+\.\w{2,4}"])
text.TextChanged += _preview
ignorecase = user_form._add_checkbox("ignorecase", "Groß-/Kleinschreibung ignorieren")
ignorecase.CheckedChanged += _preview
radio_mode_values = ["Find: Aufteilung je RegEx Übereinstimmung", "Split: RegEx definiert Trennzeichen"]
_, mode_radios = user_form._add_radio_buttons("mode", "Modus", radio_mode_values, cls.last_regex_split_mode)
for radio in mode_radios:
radio.CheckedChanged += _preview
user_form._add_label("Vorschau für aktive Zelle (Gruppen mit Tabs getrennt):")
txt_preview = user_form._add_textbox("preview")
txt_preview.ReadOnly = True
_preview(None, None)
form_return = user_form.show()
if len(form_return) == 0:
return
try:
regex = re.compile(form_return["regex"], _get_flags())
except Exception as e:
bkt.message("Fehler! RegEx kann nicht kompiliert werden: "+str(e))
return
if not xllib.confirm_no_undo(): return
err_counter = 0
cls.last_regex_split_pattern = form_return["regex"]
cls.last_regex_split_mode = radio_mode_values.index(form_return["mode"])
for cell in cells:
if cell.Value2 is None:
continue
try:
values_split = _do_regex(regex, cell.Text)
values = Array.CreateInstance(object, 1, len(values_split))
for i,col in enumerate(values_split):
values[0,i] = col or ""
new_area = xllib.resize_areas([cell], cols=len(values_split))[0]
new_area.Value = values
except:
err_counter += 1
# bkt.helpers.exception_as_message(str(cell.AddressLocal()))
if err_counter > 0:
bkt.message("Fehler! RegEx war auf " + str(err_counter) + " Zelle(n) nicht anwendbar.")
@classmethod
def regex_replace(cls, cells, application):
import re
preview_cell_value = application.ActiveCell.Text
def _get_flags():
flags=0
if ignorecase.Checked:
flags = re.IGNORECASE
return flags
def _preview(sender, e):
try:
txt_preview.Text = re.sub(pattern.Text, repl.Text, preview_cell_value, flags=_get_flags())
except Exception as e:
txt_preview.Text = "FEHLER: " + str(e)
user_form = bkt.ui.UserInputBox("Hier kann ein regulärer Ausdruck in allen markierten Zellen gesucht und ersetzt werden. In der Auswahlbox finden Sie Beispiele für mögliche Eingaben.", "RegEx anwenden")
pattern = user_form._add_combobox("pattern", cls.last_regex_sub_pattern, [r"\sand\s", r" {2,}", r"([A-Z]+)/([a-z]+)"])
pattern.TextChanged += _preview
repl = user_form._add_combobox("repl", cls.last_regex_sub_repl, [r" & ", r" ", r"\2/\1"])
repl.TextChanged += _preview
ignorecase = user_form._add_checkbox("ignorecase", "Groß-/Kleinschreibung ignorieren")
ignorecase.CheckedChanged += _preview
user_form._add_label("Vorschau für aktive Zelle:")
txt_preview = user_form._add_textbox("preview")
txt_preview.ReadOnly = True
_preview(None, None)
form_return = user_form.show()
if len(form_return) == 0:
return
try:
regex_pattern = re.compile(form_return["pattern"], _get_flags())
except Exception as e:
bkt.message("Fehler! RegEx kann nicht kompiliert werden: "+str(e))
return
if not xllib.confirm_no_undo(): return
err_counter = 0
cls.last_regex_sub_pattern = form_return["pattern"]
cls.last_regex_sub_repl = form_return["repl"]
for cell in cells:
if cell.Value2 is None:
continue
try:
cell.Value = regex_pattern.sub(form_return["repl"], cell.Text)
except:
err_counter += 1
#bkt.helpers.exception_as_message(str(cell.AddressLocal()))
if err_counter > 0:
bkt.message("Fehler! RegEx war auf " + str(err_counter) + " Zelle(n) nicht anwendbar.")
@staticmethod
def merge_cells(selection, cells, join="\r\n"):
if not xllib.confirm_no_undo(): return
target_content = join.join([cell.Text for cell in cells])
selection.ClearContents()
selection.Cells[1].Value = target_content
# target_cell = next(cells)
# for cell in cells:
# target_cell.Value = target_cell.Value() + join + cell.Value()
# cell.Value = None
@staticmethod
def merge_area_rows(areas, join="\r\n"):
if not xllib.confirm_no_undo(): return
for area in areas:
values = Array.CreateInstance(object, 1, area.columns.count)
for i,col in enumerate(area.columns):
values[0,i] = join.join([cell.Text for cell in col.rows])
area.ClearContents()
area.Rows[1].Value = values
@staticmethod
def merge_area_cols(areas, join=", "):
if not xllib.confirm_no_undo(): return
for area in areas:
values = Array.CreateInstance(object, area.rows.count, 1)
for i,row in enumerate(area.rows):
values[i,0] = join.join([cell.Text for cell in row.columns])
area.ClearContents()
area.Columns[1].Value = values
@staticmethod
def split_to_cols(cells, sep=","):
if not xllib.confirm_no_undo(): return
for cell in cells:
values_split = cell.Text.split(sep)
values = Array.CreateInstance(object, 1, len(values_split))
for i,col in enumerate(values_split):
values[0,i] = col.strip()
new_area = xllib.resize_areas([cell], cols=len(values_split))[0]
new_area.Value = values
@staticmethod
def split_to_rows(cells, sep=None):
if not xllib.confirm_no_undo(): return
for cell in cells:
if sep is None:
values_split = cell.Text.splitlines()
else:
values_split = cell.Text.split(sep)
values = Array.CreateInstance(object, len(values_split), 1)
for i,row in enumerate(values_split):
values[i,0] = row.strip()
new_area = xllib.resize_areas([cell], rows=len(values_split))[0]
new_area.Value = values
@staticmethod
def formula_to_values(areas):
if not xllib.confirm_no_undo(): return
for area in areas:
area.Value = area.Value()
@staticmethod
def values_to_showntext(areas):
if not xllib.confirm_no_undo(): return
for area in areas:
for cell in iter(area.Cells):
if cell.Value2 is None:
continue
cell.Value = "'" + cell.Text
area.NumberFormat = "@" #Text
@staticmethod
def text_to_numbers(areas, application):
if not xllib.confirm_no_undo(): return
general_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
for area in areas:
#area.NumberFormatLocal = general_format
#area.Value = application.WorksheetFunction.NumberValue( area )
for cell in iter(area.Cells):
if cell.HasFormula or cell.Value2 is None:
continue
if cell.NumberFormat == "@": #Text
cell.NumberFormatLocal = general_format
try:
# cell.Value = Converter.ToDouble(cell.Value())
cell.Value = application.WorksheetFunction.NumberValue( cell )
except:
cell.Value = cell.Value()
@staticmethod
def numbers_to_text(areas):
if not xllib.confirm_no_undo(): return
for area in areas:
area.NumberFormat = "@" #Text
for cell in iter(area.Cells):
if cell.Value2 is None:
continue
cell.Value = "'" + cell.Text
@staticmethod
def text_to_datetime(areas, application):
if not xllib.confirm_no_undo(): return
general_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
for area in areas:
for cell in iter(area.Cells):
if cell.HasFormula or cell.Value2 is None or isinstance(cell.Value(), DateTime):
continue
if cell.NumberFormat == "@": #Text
cell.NumberFormatLocal = general_format
try:
cell.Value = DateTime.Parse( cell.Text )
except:
pass
@staticmethod
def text_to_formula(areas, application):
if not xllib.confirm_no_undo(): return
general_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
for area in areas:
#area.NumberFormatLocal = general_format
#area.FormulaLocal = area.Value()
for cell in iter(area.Cells):
if cell.Text[0] != "=":
continue
cell.NumberFormatLocal = general_format
cell.FormulaLocal = cell.Value()
@staticmethod
def formula_to_text(areas):
if not xllib.confirm_no_undo(): return
for area in areas:
#area.NumberFormat = "@" #Text
#area.Value = area.FormulaLocal
for cell in iter(area.Cells):
if not cell.HasFormula:
continue
cell.NumberFormat = "@" #Text
cell.Value = "'" + cell.FormulaLocal
@staticmethod
def formula_to_absolute(cells, application):
if not xllib.confirm_no_undo(): return
for cell in cells:
if cell.HasFormula:
cell.Formula = application.ConvertFormula(cell.Formula, 1, 1, 1) #xlA1, xlA1, xlAbsolute
@staticmethod
def formula_to_relative(cells, application):
if not xllib.confirm_no_undo(): return
for cell in cells:
if cell.HasFormula:
cell.Formula = application.ConvertFormula(cell.Formula, 1, 1, 4) #xlA1, xlA1, xlRelative
@staticmethod
def local_formula_to_english_text(cells):
if not xllib.confirm_no_undo(): return
for cell in cells:
if cell.HasFormula:
cell.Value = "'" + cell.Formula
@staticmethod
def english_text_to_local_formula(cells, application):
if not xllib.confirm_no_undo(): return
general_format = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
for cell in cells:
if cell.Text[0] != "=":
continue
cell.NumberFormatLocal = general_format
cell.Formula = cell.Value()
@staticmethod
def prohibit_duplicates(areas, application):
if not xllib.confirm_no_undo("Dies überschreibt bestehende Datenüberprüfungen und kann nicht rückgängig gemacht werden. Ausführen?"): return
for area in areas:
vali_form = "=COUNTIF(" + area.Address(True, True, 1) + "," + area.Cells(1).Address(False, False, 1) + ")=1" #xlA1
vali_form = xllib.formula_int2local(vali_form)
area.Validation.Delete()
area.Validation.Add(7, 1, 1, vali_form) #xlValidateCustom, xlValidAlertStop, xlBetween
#area.Validation.ShowError = True
#area.Validation.ErrorTitle = "Duplicate Value"
#area.Validation.ErrorMessage = "This value was already entered. All values must be unique. Please try again."
@staticmethod
def subtotal(application, selection, func="Sum"):
try:
selection = selection.SpecialCells(xlcon.XlCellType["xlCellTypeVisible"])
value = str( getattr(application.WorksheetFunction, func)(selection) )
#value = str(application.WorksheetFunction.Subtotal(xlcon.subtotalFunction[func], selection))
value = value.replace('.', application.International(xlcon.XlApplicationInternational["xlDecimalSeparator"]))
Forms.Clipboard.SetText(value)
except:
bkt.message('Fehler beim Kopieren!')
#bkt.message('Kopiert: ' + value)
@staticmethod
def enabled_subtotal(application, selection):
try:
#count number of cells that contain numbers
return application.WorksheetFunction.Count(selection) > 0
#application.WorksheetFunction.Subtotal(xlcon.subtotalFunction["AVG"], selection)
#return True
except:
return False
@staticmethod
def trim(application, areas):
if not xllib.confirm_no_undo(): return
for area in areas:
area.Value = application.WorksheetFunction.Trim(area)
@staticmethod
def clean(application, areas):
if not xllib.confirm_no_undo(): return
for area in areas:
area.Value = application.WorksheetFunction.Clean(area)
@staticmethod
def trim_python(application, cells):
if not xllib.confirm_no_undo(): return
for cell in cells:
cell.Value = cell.Text.strip()
@staticmethod
def fill_down(cells, application):
if not xllib.confirm_no_undo(): return
# to_be_filled = None
for cell in cells:
if cell.Row == 1:
continue
if cell.Value2 is None:
try:
cell.Value = cell.Offset(-1,0).MergeArea(1).Value()
# to_be_filled = xllib.range_union(to_be_filled, cell, application)
except:
pass
# if to_be_filled is not None:
# to_be_filled.FormulaR1C1 = "=R[-1]C"
# to_be_filled.Value = to_be_filled.Value()
# for area in areas:
# empty_cells = area.SpecialCells(4) #xlCellTypeBlanks
# empty_cells.FormulaR1C1 = "=R[-1]C"
# area.Value = area.Value()
@staticmethod
def undo_fill_down(cells, application):
if not xllib.confirm_no_undo(): return
to_be_deleted = None
for cell in cells:
if cell.Row == 1:
continue
try:
if cell.Value() == cell.Offset(-1,0).MergeArea(1).Value():
to_be_deleted = xllib.range_union(to_be_deleted, cell)
except:
pass
if to_be_deleted is not None:
to_be_deleted.Value = None
@classmethod
def toggle_hidden_columns(cls, sheet, application, selection):
area = sheet.UsedRange
#Restore hidden columns if sheet is the same
hidden_cols = cls._get_hidden_name("BKT_HIDDEN_COLS", sheet)
#if sheet.Name in cls.hidden_columns:
if hidden_cols is not None:
#sheet.Range(cls.hidden_columns[sheet.Name]).EntireColumn.Hidden = True
#del cls.hidden_columns[sheet.Name]
#sheet.Range(hidden_cols).EntireColumn.Hidden = True
hidden_cols.EntireColumn.Hidden = True
#cls._del_hidden_name("BKT_HIDDEN_COLS", sheet)
#Show hidden columns and store them
else:
#hidden_cols = None
for i in xrange(1,area.Columns.Count+1):
if area.Columns(i).EntireColumn.Hidden:
hidden_cols = xllib.range_union(hidden_cols, area.Columns(i).EntireColumn)
if hidden_cols is not None:
hidden_cols.EntireColumn.Hidden = False
#cls.hidden_columns[sheet.Name] = hidden_cols.AddressLocal(False, False)
#cls._set_hidden_name("BKT_HIDDEN_COLS", sheet, hidden_cols.AddressLocal(True, True))
cls._set_hidden_name("BKT_HIDDEN_COLS", sheet, hidden_cols)
#If entire rows are selected hide them
elif selection.Address() == selection.EntireColumn.Address():
selection.EntireColumn.Hidden = True
else:
bkt.message("Keine ausgeblendeten Spalten im genutzten Bereich gefunden.")
@classmethod
def toggle_hidden_rows(cls, sheet, application, selection):
area = sheet.UsedRange
#Restore hidden rows if sheet is the same
hidden_rows = cls._get_hidden_name("BKT_HIDDEN_ROWS", sheet)
#if sheet.Name in cls.hidden_rows:
if hidden_rows is not None:
#sheet.Range(cls.hidden_rows[sheet.Name]).EntireRow.Hidden = True
#del cls.hidden_rows[sheet.Name]
#sheet.Range(hidden_rows).EntireRow.Hidden = True
hidden_rows.EntireRow.Hidden = True
#cls._del_hidden_name("BKT_HIDDEN_ROWS", sheet)
#Show hidden rows and store them
else:
#hidden_rows = None
for i in xrange(1,area.Rows.Count+1):
if area.Rows(i).EntireRow.Hidden:
hidden_rows = xllib.range_union(hidden_rows, area.Rows(i).EntireRow)
if hidden_rows is not None:
hidden_rows.EntireRow.Hidden = False
#cls.hidden_rows[sheet.Name] = hidden_rows.AddressLocal(False, False)
#cls._set_hidden_name("BKT_HIDDEN_ROWS", sheet, hidden_rows.AddressLocal(True, True))
cls._set_hidden_name("BKT_HIDDEN_ROWS", sheet, hidden_rows)
#If entire rows are selected hide them
elif selection.Address() == selection.EntireRow.Address():
selection.EntireRow.Hidden = True
else:
bkt.message("Keine ausgeblendeten Zeilen im genutzten Bereich gefunden.")
@classmethod
def remove_hidden_cols(cls, sheet):
if not xllib.confirm_no_undo(): return
xllib.freeze_app()
deleted = 0
try:
area = sheet.UsedRange
for i in xrange(1,area.Columns.Count+1):
if area.Columns(i).EntireColumn.Hidden:
area.Columns(i).EntireColumn.Delete()
deleted += 1
finally:
xllib.unfreeze_app()
bkt.message("Es wurden %s Spalten gelöscht" % deleted)
@classmethod
def remove_hidden_rows(cls, sheet):
area = sheet.UsedRange
deleted = 0
for i in xrange(1,area.Rows.Count+1):
if area.Rows(i).EntireRow.Hidden:
area.Rows(i).EntireRow.Delete()
deleted += 1
bkt.message("Es wurden %s Zeilen gelöscht" % deleted)
@staticmethod
def show_all_cells(sheet):
sheet.Columns.EntireColumn.Hidden = False
sheet.Rows.EntireRow.Hidden = False
@staticmethod
def hide_unused_areas(sheet):
selection = xllib.get_unused_ranges(sheet)
for rng in selection:
rng.Hidden = True
@staticmethod
def paste_on_visible(application, sheet, cell, pasteType=xlcon.XlPasteType["xlPasteAll"]):
if not xllib.confirm_no_undo(): return
xllib.freeze_app(disable_display_alerts=True)
temporary_sheet = xllib.create_temp_sheet()
try:
temporary_sheet.Cells(cell.Row, cell.Column).PasteSpecial(pasteType)
rows = temporary_sheet.UsedRange.Rows.Count
cols = temporary_sheet.UsedRange.Columns.Count
### METHOD 1: COPY CELL BY CELL ###
#FIXME: cache area of visible columns once determined in first loop
# cur_cell = cell
# for i in range(1,rows+1):
# for j in range(1,cols+1):
# temporary_sheet.UsedRange.Cells(i, j).Copy()
# cur_cell.PasteSpecial(pasteType)
# if j < cols:
# cur_cell = xllib.get_next_visible_cell(cur_cell, 'right')
# if i < rows:
# cur_cell = sheet.Cells(cur_cell.Row, cell.Column)
# cur_cell = xllib.get_next_visible_cell(cur_cell, 'bottom')
# sheet.Range(cell, cur_cell).Select()
### METHOD 2: INSERT BLANKS AND PASTE USING SKIP BLANKS ###
i = cell.Row
rows_to_check = i+rows
while i <= rows_to_check:
if sheet.Cells(i,1).EntireRow.Hidden:
temporary_sheet.Cells(i,1).EntireRow.Insert()
rows_to_check += 1
i += 1
i = cell.Column
cols_to_check = i+cols
while i <= cols_to_check:
if sheet.Cells(1,i).EntireColumn.Hidden:
temporary_sheet.Cells(1,i).EntireColumn.Insert()
cols_to_check += 1
i += 1
temporary_sheet.UsedRange.Copy()
cell.PasteSpecial(pasteType, SkipBlanks=True)
except:
bkt.message("Sorry, etwas ist schiefgelaufen!?")
temporary_sheet.Delete()
xllib.unfreeze_app()
class Format(object):
@staticmethod
def hide_zero(cells, application, pressed):
if not xllib.confirm_no_undo(): return
for cell in cells:
if pressed:
formats = cell.NumberFormat.split(";")
formats = formats + ['']*(3-len(formats))
formats[2] = ''
cell.NumberFormat = ";".join(formats)
#cell.NumberFormat = '0;;;@'
else:
if cell.NumberFormat == '0;;;@':
cell.NumberFormatLocal = application.International(xlcon.XlApplicationInternational["xlGeneralFormatName"])
return
formats = cell.NumberFormat.split(";")
if len(formats) == 3:
del formats[2]
elif len(formats) >= 4:
#(.*) (.*),(0*).* (.*)
formats[2] = "0"
cell.NumberFormat = ";".join(formats)
@staticmethod
def hide_zero_pressed(cell):
formats = cell.NumberFormat.split(";")
return len(formats) >= 3 and formats[2] == ''
#return cell.NumberFormat == '0;;;@'
@staticmethod
def hide_zero_simple(cells, application):
if not xllib.confirm_no_undo(): return
for cell in cells:
cell.NumberFormat = '0;;;@'
@staticmethod
def number_in_thousand(cells):
if not xllib.confirm_no_undo(): return
#TODO: Make buttons smart: recognize number format and adjust it instead of replacing it
for cell in cells:
cell.NumberFormat = '_-* #.##0,0. "k"_-;-* #.##0,0. "k"_-;_-* "-"? "k"_-;_-@_-'
@staticmethod
def number_in_million(cells):
if not xllib.confirm_no_undo(): return
#TODO: Make buttons smart: recognize number format and adjust it instead of replacing it
for cell in cells:
cell.NumberFormat = '_-* #.##0,0.. "Mio."_-;-* #.##0,0.. "Mio."_-;_-* "-"? "Mio."_-;_-@_-'
@staticmethod
def merged_cells_to_center_across(cells):
if not xllib.confirm_no_undo(): return
for cell in cells:
if cell.MergeCells and cell.MergeArea.Rows.Count == 1 and cell.MergeArea.HorizontalAlignment == -4108: #xlCenter
area = cell.MergeArea
cell.MergeCells = False
area.HorizontalAlignment = 7 #xlCenterAcrossSelection
@staticmethod
def merged_cells_to_unmerged_filled(cells):
if not xllib.confirm_no_undo(): return
for cell in cells:
if cell.MergeCells:
area = cell.MergeArea
cell.MergeCells = False
if cell.HasFormula:
area.Formula = cell.Formula
else:
area.Value = cell.Value()
@staticmethod
def horiz_align(selection, alignment, pressed):
if not xllib.confirm_no_undo(): return
if not pressed:
selection.HorizontalAlignment = 1 #xlGeneral
else:
selection.HorizontalAlignment = alignment
@staticmethod
def horiz_align_pressed(selection, alignment):
return selection.HorizontalAlignment == alignment
zellen_inhalt_gruppe = bkt.ribbon.Group(
id="group_cell_contents",
label="Zellen-Inhalte",
image_mso="Formula",
children=[
bkt.ribbon.Button(
id = 'apply_formula',
label="Formel anwenden…",
show_label=True,
size='large',
image_mso='Formula',
supertip="Eine Formel auf alle ausgewählten Zellen anwenden.",
on_action=bkt.Callback(CellsOps.apply_formula, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(
id = 'apply_regex',
label="RegEx anwenden…",
show_label=True,
size='large',
image_mso='ApplyFilter',
supertip="Einen regulären Ausdruck auf alle ausgewählten Zellen anwenden.",
children=[
bkt.ribbon.Button(
id = 'regex_match',
label="Mit RegEx zählen/filtern",
supertip="Die Anzahl der Ergebnisse/Gruppen eines regulären Ausdrucks für ausgewählte Zellen in jeweilige Zelle schreiben.",
on_action=bkt.Callback(CellsOps.regex_match_count, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'regex_split',
label="Mit RegEx in Spalten aufteilen",
supertip="Alle Ergebnisse/Gruppen eines regulären Ausdrucks für ausgewählte Zellen in Spalten aufteilen.",
on_action=bkt.Callback(CellsOps.regex_split_to_columns, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'regex_replace',
label="Mit RegEx suchen und ersetzen",
supertip="Mit einem regulären Ausdruck in ausgewählten Zellen suchen und ersetzen.",
on_action=bkt.Callback(CellsOps.regex_replace, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
]
),
bkt.ribbon.Menu(
label="Textwerkzeuge",
show_label=True,
image_mso='FormControlEditBox',
screentip="Verschiedene Text-Manipulationen",
supertip="Text hinzufügen oder schneiden.",
children=[
bkt.ribbon.Button(
id = 'prepend_text',
label="Text voranstellen…",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Einen Text allen ausgewählten Zellen voranstellen.",
on_action=bkt.Callback(CellsOps.prepend_text, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'append_text',
label="Text anhängen…",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Einen Text allen ausgewählten Zellen anhängen.",
on_action=bkt.Callback(CellsOps.append_text, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
bkt.ribbon.Button(
id = 'slice_text',
label="Text anhand Position schneiden…",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Einen Text vorne oder hinten nach gegebener Position abschneiden.",
on_action=bkt.Callback(CellsOps.slice_text, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'find_and_slice_text',
label="Text anhand Zeichen schneiden…",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Einen Text vorne oder hinten nach gegebenem Zeichen abschneiden.",
on_action=bkt.Callback(CellsOps.find_and_slice_text, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
bkt.mso.control.ReplaceDialog(),
]
),
bkt.ribbon.SplitButton(
children=[
bkt.ribbon.Button(
id = 'formula_to_values',
label="Formeln zu Werten",
show_label=True,
image_mso='ShowFormulas',
supertip="Formeln in allen ausgewählten Zellen durch jeweilige Werte ersetzen. Zellen ohne Formeln bleiben unverändert.",
on_action=bkt.Callback(CellsOps.formula_to_values, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(children=[
bkt.ribbon.MenuSeparator(title="Werte/Text"),
bkt.ribbon.Button(
id = 'formula_to_values2',
label="Formeln zu Werten",
show_label=True,
image_mso='ShowFormulas',
supertip="Formeln in allen ausgewählten Zellen durch jeweilige Werte ersetzen. Zellen ohne Formeln bleiben unverändert.",
on_action=bkt.Callback(CellsOps.formula_to_values, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'values_to_showntext',
label="Zu angezeigtem Text",
show_label=True,
#image_mso='PasteTextOnly',
supertip="Werte in allen ausgewählten Zellen durch den tatsächlich angezeigten Text ersetzen. Dabei wird das Zellenformat auf 'Text' geändert.",
on_action=bkt.Callback(CellsOps.values_to_showntext, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(title="Zahlen/Daten"),
bkt.ribbon.Button(
id = 'numbers_to_text',
label="Zahlenwerte zu Text",
show_label=True,
#image_mso='PasteTextOnly',
supertip="Konvertiert numerische Werte (Zahlen, Datum, Zeit) in als Text gespeicherte Zahlen. Dabei wird das Zellenformat auf 'Text' geändert.",
on_action=bkt.Callback(CellsOps.numbers_to_text, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'text_to_numbers',
label="Text zu Zahlen",
show_label=True,
#image_mso='PasteValues',
supertip="Konvertiert als Text gespeicherte Zahlen in echte Zahlen. Dabei wird das Zellenformat auf 'Standard' geändert.",
on_action=bkt.Callback(CellsOps.text_to_numbers, areas=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'text_to_datetime',
label="Text zu Datum/Zeit",
show_label=True,
#image_mso='PasteTextOnly',
supertip="Konvertiert als Text gespeicherte Datum- und Zeitwerte in ein echtes Datum ggf. mit Uhrzeit. Dabei wird das Zellenformat auf 'Standard' geändert.",
on_action=bkt.Callback(CellsOps.text_to_datetime, areas=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(title="Formeln"),
bkt.ribbon.Button(
id = 'text_to_formula',
label="Text zu Formeln",
show_label=True,
#image_mso='PasteFormulas',
supertip="Konvertiert als Text gespeicherte Formeln in echte Formeln. Dabei wird das Zellenformat auf 'Standard' geändert.",
on_action=bkt.Callback(CellsOps.text_to_formula, areas=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'formula_to_text',
label="Formeln zu Text",
show_label=True,
#image_mso='PasteTextOnly',
supertip="Konvertiert Formeln in als Text gespeicherte Formeln. Dabei wird das Zellenformat auf 'Text' geändert. Zellen ohne Formeln bleiben unverändert.",
on_action=bkt.Callback(CellsOps.formula_to_text, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'formula_to_absolute',
label="Formeln A1 zu $A$1",
show_label=True,
#image_mso='PasteFormulas',
supertip="Konvertiert Referenzen in Formeln zu absoluten Referenzen.",
on_action=bkt.Callback(CellsOps.formula_to_absolute, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'formula_to_relative',
label="Formeln $A$1 zu A1",
show_label=True,
#image_mso='PasteFormulas',
supertip="Konvertiert Referenzen in Formeln zu relativen Referenzen.",
on_action=bkt.Callback(CellsOps.formula_to_relative, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
bkt.ribbon.Button(
id = 'eng_text_to_formula',
label="Englische Formeln zu Formeln",
show_label=True,
#image_mso='PasteFormulas',
supertip="Konvertiert als Text gespeicherte englische Formeln in echte Formeln. Dabei wird das Zellenformat auf 'Standard' geändert.",
on_action=bkt.Callback(CellsOps.english_text_to_local_formula, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'formula_to_eng_text',
label="Formeln zu englischen Formeln",
show_label=True,
#image_mso='PasteTextOnly',
supertip="Konvertiert Formeln in als Text gespeicherte englische Formeln. Dabei wird das Zellenformat auf 'Text' geändert. Zellen ohne Formeln bleiben unverändert.",
on_action=bkt.Callback(CellsOps.local_formula_to_english_text, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
])
]
),
bkt.ribbon.SplitButton(
children=[
bkt.ribbon.Button(
id = 'cells_trim',
label="Glätten (Trim)",
show_label=True,
image_mso='TextDirectionContext',
supertip="Entferne überflüssige Leerzeichen am Anfang oder Ende aller selektierten Zellen (wie Excel-Funktion GLÄTTEN).",
on_action=bkt.Callback(CellsOps.trim, application=True, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(children=[
bkt.ribbon.Button(
id = 'cells_trim2',
label="Glätten/Kürzen (Trim)",
show_label=True,
image_mso='TextDirectionContext',
supertip="Entferne überflüssige Leerzeichen am Anfang oder Ende aller selektierten Zellen (wie Excel-Funktion GLÄTTEN).",
on_action=bkt.Callback(CellsOps.trim, application=True, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'cells_trim_python',
label="Erweitertes Glätten/Kürzen (Trim)",
show_label=True,
# image_mso='TextDirectionContext',
supertip="Entferne überflüssige Leerzeichen am Anfang oder Ende aller selektierten Zellen mit Pythons Strip-Funktion.",
on_action=bkt.Callback(CellsOps.trim_python, application=True, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'cells_clean',
label="Säubern/Bereinigen (Clean)",
show_label=True,
#image_mso='TextDirectionContext',
supertip="Entferne nicht-druckbare Zeichen in allen selektierten Zellen (wie Excel-Funktion SÄUBERN).",
on_action=bkt.Callback(CellsOps.clean, application=True, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
])
]
),
bkt.ribbon.SplitButton(
children=[
bkt.ribbon.Button(
id = 'cells_fill_down',
label="Leere Zellen nach unten füllen",
show_label=True,
image_mso='FillDown',
supertip="Leere Zellen im selektierten Bereich mit jeweils gefüllter Zelle darüber füllen.",
on_action=bkt.Callback(CellsOps.fill_down, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(children=[
bkt.ribbon.Button(
id = 'cells_fill_down2',
label="Leere Zellen nach unten füllen",
show_label=True,
image_mso='FillDown',
supertip="Leere Zellen im selektierten Bereich mit jeweils gefüllter Zelle darüber füllen.",
on_action=bkt.Callback(CellsOps.fill_down, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'cells_undo_fill_down',
label="Nach unten gefüllte Zellen wieder leeren",
show_label=True,
image_mso='FillUp',
supertip="Sich wiederholende Zellenwerte löschen, sodass nur jeweils oberste Zelle gefüllt bleibt.",
on_action=bkt.Callback(CellsOps.undo_fill_down, cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
bkt.ribbon.Button(
id = 'cells_merge',
label="Alle Zell-Inhalte zusammenführen",
show_label=True,
# image_mso='FillUp',
supertip="Fügt alle Zellen in aktive Zelle getrennt mit Zeilenumbruch ein",
on_action=bkt.Callback(CellsOps.merge_cells, selection=True, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'cells_merge_cols',
label="Spaltenweise zusammenführen mit Komma",
show_label=True,
# image_mso='FillUp',
supertip="Fügt alle Spalten (je Selektionsbereich) in die erste Spalte getrennt mit Kommas ein",
on_action=bkt.Callback(CellsOps.merge_area_cols, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'cells_merge_rows',
label="Zeilenweise zusammenführen mit Umbruch",
show_label=True,
# image_mso='FillUp',
supertip="Fügt alle Zeilen (je Selektionsbereich) in erste Zeile getrennt mit Zeilenumbruch ein",
on_action=bkt.Callback(CellsOps.merge_area_rows, areas=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
bkt.ribbon.Button(
id = 'cells_split_cols',
label="Komma-getrennt in Spalten trennen",
show_label=True,
# image_mso='FillUp',
supertip="Zelleninhalte in Spalten für jedes Komma trennen",
on_action=bkt.Callback(CellsOps.split_to_cols, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'cells_split_rows',
label="Zeilenumbrüche in Zeilen trennen",
show_label=True,
# image_mso='FillUp',
supertip="Zelleninhalte in Zeilen für jeden Zeilenumbruch trennen",
on_action=bkt.Callback(CellsOps.split_to_rows, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
])
]
),
#TODO: Zellen mit gleichen Werten verbinden
#TODO: Zellen nicht mehr verbinden und Werte in einzelne Zellen füllen
bkt.ribbon.SplitButton(
get_enabled = bkt.Callback(CellsOps.enabled_subtotal, application=True, selection=True),
children=[
bkt.ribbon.Button(
id = 'selection_subtotal_sum',
label="Kopiere Summe markierter Zellen",
show_label=True,
image_mso='Copy',
supertip="Kopiere die Summe über die selektierten sichtbaren Zellen in die Zwischenablage.",
on_action=bkt.Callback(lambda application, selection: CellsOps.subtotal(application, selection), application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(children=[
bkt.ribbon.Button(
id = 'selection_subtotal_sum2',
label="Kopiere Summe markierter Zellen",
show_label=True,
image_mso='Copy',
supertip="Kopiere die Summe über die selektierten sichtbaren Zellen in die Zwischenablage.",
on_action=bkt.Callback(lambda application, selection: CellsOps.subtotal(application, selection), application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'selection_subtotal_avg',
label="Kopiere Mittelwert markierter Zellen",
show_label=True,
#image_mso='Copy',
supertip="Kopiere den Mittelwert über die selektierten sichtbaren Zellen in die Zwischenablage.",
on_action=bkt.Callback(lambda application, selection: CellsOps.subtotal(application, selection, "Average"), application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'selection_subtotal_min',
label="Kopiere Minimum markierter Zellen",
show_label=True,
#image_mso='Copy',
supertip="Kopiere das Minimum über die selektierten sichtbaren Zellen in die Zwischenablage.",
on_action=bkt.Callback(lambda application, selection: CellsOps.subtotal(application, selection, "Min"), application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'selection_subtotal_max',
label="Kopiere Maximum markierter Zellen",
show_label=True,
#image_mso='Copy',
supertip="Kopiere das Maximum über die selektierten sichtbaren Zellen in die Zwischenablage.",
on_action=bkt.Callback(lambda application, selection: CellsOps.subtotal(application, selection, "Max"), application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
])
]
),
bkt.ribbon.SplitButton(
get_enabled = bkt.Callback(lambda: Forms.Clipboard.ContainsText()),
children=[
bkt.ribbon.Button(
id = 'paste_on_visible_all',
label="Einfügen auf sichtbare Zellen",
show_label=True,
image_mso='PasteTableByOverwritingCells',
supertip="Fügt den Inhalt der Zwischenablage nur auf sichtbare Zellen ein. Ausgeblendete bzw. herausgefilterte Zellen werden übersprungen.",
on_action=bkt.Callback(CellsOps.paste_on_visible, application=True, sheet=True, cell=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(children=[
bkt.ribbon.Button(
id = 'paste_on_visible_all2',
label="Einfügen auf sichtbare Zellen",
show_label=True,
image_mso='PasteTableByOverwritingCells',
supertip="Fügt den Inhalt der Zwischenablage nur auf sichtbare Zellen ein. Ausgeblendete bzw. herausgefilterte Zellen werden übersprungen.",
on_action=bkt.Callback(CellsOps.paste_on_visible, application=True, sheet=True, cell=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'paste_on_visible_values',
label="Werte einfügen auf sichtbare Zellen",
show_label=True,
image_mso='PasteValues',
supertip="Fügt den Inhalt der Zwischenablage als Werte nur auf sichtbare Zellen ein. Ausgeblendete bzw. herausgefilterte Zellen werden übersprungen.",
on_action=bkt.Callback(lambda application, sheet, cell: CellsOps.paste_on_visible(application, sheet, cell, xlcon.XlPasteType["xlPasteValues"]), application=True, sheet=True, cell=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'paste_on_visible_formulas',
label="Formeln einfügen auf sichtbare Zellen",
show_label=True,
image_mso='PasteFormulas',
supertip="Fügt den Inhalt der Zwischenablage als Formeln nur auf sichtbare Zellen ein. Ausgeblendete bzw. herausgefilterte Zellen werden übersprungen.",
on_action=bkt.Callback(lambda application, sheet, cell: CellsOps.paste_on_visible(application, sheet, cell, xlcon.XlPasteType["xlPasteFormulas"]), application=True, sheet=True, cell=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
])
]
),
#TODO: Upper/Lower/Proper-Case
#TODO: Formatierung gezielt übertragen (Auswahl Zellenformat, Benutzerdefinierte Format., Datenvalidierung)
#TODO: Benutzerdefinierte Formatierung konsolidieren (wenn farbe und typ identisch, range_union)
#TODO: Unit/Currency Conversion
]
)
zellen_format_gruppe = bkt.ribbon.Group(
id="group_cell_formats",
label="Zellen-Formate",
image_mso="TableColumnsInsertLeftExcel",
children=[
bkt.ribbon.SplitButton(
size="large",
children=[
bkt.ribbon.Button(
id = 'toggle_hidden_columns',
label="Spalten ein/ausblenden",
show_label=True,
image_mso='TableColumnsInsertLeftExcel',
supertip="Alle ausgeblendeten Spalten zwischen aus- und einblenden umschalten.\n\nWenn keine ausgeblendeten Spalten zwischengespeichert bzw. im Blatt vorhanden sind, und Spalten markiert sind, werden diese ausgeblendet.",
on_action=bkt.Callback(CellsOps.toggle_hidden_columns, sheet=True, application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(children=[
bkt.ribbon.Button(
id = 'toggle_hidden_columns2',
label="Spalten ein/ausblenden",
show_label=True,
image_mso='TableColumnsInsertLeftExcel',
supertip="Alle ausgeblendeten Spalten zwischen aus- und einblenden umschalten.\n\nWenn keine ausgeblendeten Spalten zwischengespeichert bzw. im Blatt vorhanden sind, und Spalten markiert sind, werden diese ausgeblendet.",
on_action=bkt.Callback(CellsOps.toggle_hidden_columns, sheet=True, application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'toggle_hidden_rows',
label="Zeilen ein/ausblenden",
show_label=True,
image_mso='TableRowsInsertBelowExcel',
supertip="Alle ausgeblendeten Zeilen zwischen aus- und einblenden umschalten.\n\nWenn keine ausgeblendeten Zeilen zwischengespeichert bzw. im Blatt vorhanden sind, und Zeilen markiert sind, werden diese ausgeblendet.",
on_action=bkt.Callback(CellsOps.toggle_hidden_rows, sheet=True, application=True, selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
bkt.ribbon.Button(
id = 'show_all_cells',
label="Alle Spalten und Zeilen einblenden",
show_label=True,
#image_mso='TableInsertMultidiagonalCell',
supertip="Alle ausgeblendeten Spalten und Zeilen wieder einblenden.",
on_action=bkt.Callback(CellsOps.show_all_cells, sheet=True, require_worksheet=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'hide_unused_areas',
label="Ungenutzten Bereich ausblenden",
show_label=True,
#image_mso='ViewGridlinesToggleExcel',
supertip="Alle Spalten und Zeilen des nicht genutzten Bereichs ausblenden.",
on_action=bkt.Callback(CellsOps.hide_unused_areas, sheet=True, require_worksheet=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
bkt.ribbon.Button(
id = 'remove_hidden_cols',
label="Ausgeblendete Spalten löschen",
show_label=True,
#image_mso='TableInsertMultidiagonalCell',
supertip="Alle ausgeblendeten Spalten löschen.",
on_action=bkt.Callback(CellsOps.remove_hidden_cols, sheet=True, require_worksheet=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'remove_hidden_rows',
label="Ausgeblendete Zeilen löschen",
show_label=True,
#image_mso='TableInsertMultidiagonalCell',
supertip="Alle ausgeblendeten Zeilen löschen.",
on_action=bkt.Callback(CellsOps.remove_hidden_rows, sheet=True, require_worksheet=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
])
]
),
bkt.ribbon.Button(
id = 'prohibit_duplicates',
label="Duplikate verbieten",
show_label=True,
image_mso='DataValidation',
supertip="Verbietet Duplikate innerhalb der jeweils selektierten Bereiche über eine Datenüberprüfung. Bestehende Datenüberprüfungen werden dabei überschrieben.",
on_action=bkt.Callback(CellsOps.prohibit_duplicates, areas=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.SplitButton(
children=[
bkt.ribbon.ToggleButton(
id = 'hide_zero',
label="0 ein-/ausblenden",
show_label=True,
image='hide_zero',
screentip="Nullwerte verstecken",
supertip="Per Zellen-Format 0-Werte ausblenden und wieder einblenden. Dabei wird versucht, dass bestehende Zellen-Format zu erkennen und entsprechend anzupassen.",
on_toggle_action=bkt.Callback(Format.hide_zero, cells=True, application=True),
get_pressed=bkt.Callback(Format.hide_zero_pressed, cell=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Menu(children=[
bkt.ribbon.Button(
id = 'hide_zero_simple',
label="0-Werte verstecken",
show_label=True,
image='hide_zero',
screentip="Nullwerte verstecken",
supertip="Per Zellen-Format ('0;;;@') 0-Werte ausblenden. Bestehendes Zellen-Format wird überschrieben.",
on_action=bkt.Callback(lambda cells, application: Format.hide_zero_simple(cells, application), cells=True, application=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'number_in_thousand',
label="Tausender zu 0,0 k",
show_label=True,
image='number_in_thousand',
screentip="Tausenderbeträge übersichtlich darstellen",
supertip="Per Zellen-Format Tausenderbeträge als x,x k. anzeigen. Bestehendes Zellen-Format wird überschrieben.",
on_action=bkt.Callback(Format.number_in_thousand, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'number_in_million',
label="Mio.-Werte zu 0,0 M",
show_label=True,
image='number_in_million',
screentip="Millionenbeträge übersichtlich darstellen",
supertip="Per Zellen-Format Millionenbeträge als x,x Mio. anzeigen. Bestehendes Zellen-Format wird überschrieben.",
on_action=bkt.Callback(Format.number_in_million, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
)
]),
]
),
bkt.ribbon.Menu(
label="Zellen u. Ausrichtung",
show_label=True,
image_mso='AlignJustify',
screentip="Verbundene Zellen ersetzen und ungewöhnliche Textausrichtungen nutzen",
#supertip="Text hinzufügen oder schneiden.",
children=[
bkt.ribbon.Button(
id = 'merged_cells_to_center_across',
label="Verbundene Zellen ersetzen durch Über Auswahl zentrieren",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Ersetzt verbundene Zellen innerhalb der aktuellen Auswahl durch die horizontale Ausrichtung 'Über Auswahl zentrieren', sofern die verbundenen Zellen aus einer Zeile bestehen und bisher zentriert formatiert waren.",
on_action=bkt.Callback(Format.merged_cells_to_center_across, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.Button(
id = 'merged_cells_to_unmerged_filled',
label="Verbundene Zellen aufheben und Inhalte verteilen",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Hebt verbundene Zellen innerhalb der aktuellen Auswahl auf und fügt den ursprünglichen Zelleninhalt in alle Zellen ein.",
on_action=bkt.Callback(Format.merged_cells_to_unmerged_filled, cells=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.MenuSeparator(),
# bkt.mso.control.AlignJustify,
# bkt.mso.control.ParagraphDistributed,
bkt.ribbon.ToggleButton(
id = 'halign_justify',
label="Blocksatz",
show_label=True,
image_mso='AlignJustify',
supertip="Ausgewählte zellen als Blocksatz ausrichten.",
on_toggle_action=bkt.Callback(lambda selection, pressed: Format.horiz_align(selection, -4130, pressed), selection=True), #xlHAlignJustify
get_pressed=bkt.Callback(lambda selection: Format.horiz_align_pressed(selection, -4130), selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.ToggleButton(
id = 'halign_distributed',
label="Gleichmäßig verteilt",
show_label=True,
image_mso='ParagraphDistributed',
supertip="Ausgewählte zellen horizontal verteilt ausrichten (extremer Blocksatz).",
on_toggle_action=bkt.Callback(lambda selection, pressed: Format.horiz_align(selection, -4117, pressed), selection=True), #xlHAlignDistributed
get_pressed=bkt.Callback(lambda selection: Format.horiz_align_pressed(selection, -4117), selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.ToggleButton(
id = 'halign_centeracross',
label="Über Auswahl zentrieren",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Ausgewählte zellen 'Über Auswahl zentriert' ausrichten, d.h es werden verbundene Zellen simuliert.",
on_toggle_action=bkt.Callback(lambda selection, pressed: Format.horiz_align(selection, 7, pressed), selection=True), #xlHAlignCenterAcrossSelection
get_pressed=bkt.Callback(lambda selection: Format.horiz_align_pressed(selection, 7), selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
bkt.ribbon.ToggleButton(
id = 'halign_fill',
label="Ausfüllen (Text bis Ende wiederholen)",
show_label=True,
#image_mso='FormControlEditBox',
supertip="Ausgewählte zellen 'Ausfüllen', d.h. Zelleninhalt wird optisch wiederholt über die gesamte Zellenbreite.",
on_toggle_action=bkt.Callback(lambda selection, pressed: Format.horiz_align(selection, 5, pressed), selection=True), #xlHAlignFill
get_pressed=bkt.Callback(lambda selection: Format.horiz_align_pressed(selection, 5), selection=True),
get_enabled = bkt.CallbackTypes.get_enabled.dotnet_name,
),
]
),
bkt.ribbon.DialogBoxLauncher(idMso='CellAlignmentOptions')
]
)
comments_gruppe = bkt.ribbon.Group(
id="group_cell_comments",
label="Kommentare",
image_mso="ReviewNewComment",
children=[
bkt.mso.control.ReviewNewComment(size="large"),
bkt.ribbon.Box(box_style="horizontal", children=[
bkt.mso.control.ShapeChangeShapeGallery(),
bkt.mso.control.ShapeFillColorPicker(),
bkt.mso.control.ShapeOutlineColorPicker(),
]),
bkt.ribbon.Box(box_style="horizontal", children=[
bkt.mso.control.ReviewPreviousComment(),
bkt.mso.control.ReviewNextComment(show_label=True),
]),
bkt.ribbon.Box(box_style="horizontal", children=[
# bkt.mso.control.ReviewDeleteComment(),
# bkt.mso.control.ReviewShowOrHideComment(),
bkt.mso.control.ReviewShowAllComments(show_label=True, label="Alle an/aus"),
]),
bkt.ribbon.DialogBoxLauncher(idMso='ObjectFormatDialog')
]
) | true |
f1c22a9363765f7711a13f5792a0a1904cb20b52 | Python | vinicius-toshiyuki/Don | /Test/test.py | UTF-8 | 1,597 | 2.78125 | 3 | [] | no_license | import Widget.Manager as wm
from Widget import Io, Prompt
m = wm.Manager()
w1 = wm.Window(timeout=5, background='223322')
w2 = wm.Window(weight=2, background='443344')
f1 = wm.Frame(orientation='horizontal', background='130001')
w3 = wm.Window(background='223322')
w4 = wm.Window(background='443344', foreground='aa0000')
f1.addwidget(w3)
f1.addwidget(w4)
m.root.addwidget(w1)
m.root.addwidget(w2)
m.root.addwidget(f1)
m.background()
#w4.put('1 w4')
#w4.put('2 w4')
#w4.put('3 w4')
#w4.put('4 w4')
#w4.put('({},{}) {}x{}'.format(w4.column, w4.row, w4.height, w4.width))
Io.setraw()
Prompt.wprompt = w3
Prompt.winput = w4
a = Prompt.prompt('Opção', ('essa', 'outra', 'tres', 'quatro'))
w1.put(a)
#Io.output = w2
#Io.write('escreve: ')
#a = Io.read()
#Io.write('o que foi escrito é: ' + a + '\n')
#a = Io.read()
#while (txt := Io.read()) != 'fim':
# if txt == 'w1':
# Io.output = w1
# elif txt == 'w3':
# Io.output = w3
# elif txt == 'w4':
# Io.output = w4
# else:
# Io.output = w2
# Io.write('escrevendo na '+ txt +'\n')
# Io.output = w2
# Io.write('escreve: ')
#texto = Io.readshow(w1)
#w2.put(texto + ': ' )
#w2.put('entrada: ')
#back = 0
#while (c := Io.readchar()) != 'q':
# if c.isprintable():
# w1.put('{} -> {}'.format(c, ord(c)))
# w2.modify(lambda x: x + c)
# else:
# w1.put(ord(c))
# if ord(c) == 127:
# back += 1
# w2.modify(lambda x: x + '\b')
# w3.put(str(w2))
#w2.modify(lambda x: x[:-back] + ' ' * back if len(x) > back else x)
#w1.put('{} -> {} {}x{}'.format(c, ord(c), w1.height, w1.width))
Io.unsetraw()
m.die()
print('\033[2J\033[1;1H', end='')
print(a)
| true |
689d14fb36ca2d64fe0bcb14ee82d226c6ecb061 | Python | bboyrankingz/codejam | /adventofcode/day8/registers.py | UTF-8 | 1,242 | 3.171875 | 3 | [] | no_license | class Register(object):
def __init__(self, cache={}):
self.cache = cache
self.greatest = 0
def parse_modify(self, sequence):
chaine, modify, number = sequence.split(" ")
if not self.cache.get(chaine):
self.cache[chaine] = 0
if modify == "inc":
return chaine, int(number)
return chaine, -1 * int(number)
def parse_condition(self, sequence):
chaine, *to_eval = sequence.split(" ")
if not self.cache.get(chaine):
self.cache[chaine] = 0
return eval("{}{}".format(self.cache[chaine], " ".join(to_eval)))
def register(self, sequence):
modify, condition = sequence.split(" if ")
key, value = self.parse_modify(modify)
if self.parse_condition(condition):
self.cache[key] = self.cache[key] + value
if self.cache[key] > self.greatest:
self.greatest = self.cache[key]
return self.cache
if "__main__" in __name__:
registry = Register()
with open("puzzles") as input_file:
for sequence in input_file.readlines():
registry.register(sequence)
print(max([v for k, v in registry.cache.items()]))
print(registry.greatest)
| true |
4c1267fa0882d893a4d1efcc175977f6b92e2c76 | Python | sk0g/plant-classifier-v2 | /data_prep.py | UTF-8 | 5,817 | 3.109375 | 3 | [
"MIT"
] | permissive | #!/user/bin/env python3
import os
import sys
from random import shuffle
from shutil import copy
from matplotlib import pyplot
def deal_with_cultivars():
basedir = "./dataset"
folder_names = [f[0].split("/")[-1] for f in os.walk(basedir)]
# folder names: eg Beryl's Gem => Beryls Gem (breaks processing later on)
cultivar_folders_with_possessive_apostrophe = [f for f in folder_names if "'s " in f]
for cultivar in cultivar_folders_with_possessive_apostrophe:
os.rename(os.path.join(basedir, cultivar),
os.path.join(basedir, cultivar.replace("'s ", "s ")))
# cultivars with no species: eg Westringia 'Deep Purple'
# Either find the correct species, and then move all files to the species,
# Or delete the cultivar, as this would confuse the species classification
cultivar_folders_without_species = [(f, f.split("'")[:-1]) for f in folder_names if
f.count("'") >= 2 and # contains apostrophied name
len(f.split("'")[0].strip().split(" ")) == 1] # species name is missing
for (full_folder_name, breakdown) in cultivar_folders_without_species:
new_name = ""
for folder_to_check in folder_names:
if breakdown[1] in folder_to_check and \
folder_to_check != full_folder_name and \
full_folder_name.split(" ")[0] in folder_to_check:
new_name = folder_to_check
species_found = new_name != ""
current_path = os.path.join(basedir, full_folder_name)
if species_found: # Species found, move all files and delete folder
for root, dir, files in os.walk(current_path):
old_file_paths = [os.path.join(current_path, file_name) for file_name in files]
for file_path in old_file_paths:
os.rename(file_path, file_path.replace(full_folder_name, new_name))
else: # Species not found, delete images and delete folder
for root, dir, files in os.walk(current_path):
file_paths = [os.path.join(current_path, file_name) for file_name in files]
for file_path in file_paths:
os.remove(file_path)
os.rmdir(current_path)
# cultivars with species attached, should have cultivar data removed
cultivar_folders_remaining = [f for f in folder_names if
f.count("'") >= 2]
for cultivar_folder in cultivar_folders_remaining:
non_cultivar_species_exists = cultivar_folder.split("'")[0].strip() in folder_names
folder_path = os.path.join(basedir, cultivar_folder)
for _, _, files in os.walk(folder_path):
for f in files:
if non_cultivar_species_exists: # Move all files to non-cultivar species, delete folder
os.rename(
os.path.join(folder_path, f),
os.path.join(folder_path.split("'")[0].strip(), f))
else: # Remove all images, delete folder
os.remove(os.path.join(folder_path, f))
os.rmdir(folder_path)
def remove_small_folders():
"""
Folders too small (<3 examples) can't be split for training/validation/testing
Delete images in such folders, and then their folders
"""
basedir = "./dataset"
for root, dir, files in os.walk(basedir):
if root != basedir and len(files) < 3:
print(f"Folder to delete {root} {files}")
[os.remove(os.path.join(root, f)) for f in files]
os.rmdir(root)
print("Done")
def generate_split():
"""
Generate a split folder, in ../split-0/
Should contain the following folders: train|val|test
"""
basedir = "./dataset"
split_dir = "../split-0"
train_dir, val_dir, test_dir = [os.path.join(split_dir, c) for c in ["train", "val", "test"]]
[os.path.isdir(d) or os.mkdir(d) for d in [split_dir, train_dir, val_dir, test_dir]]
for root, dir, files in os.walk(basedir):
if root != basedir:
species_name = root.split("/")[-1]
for current_directory in [train_dir, val_dir, test_dir]:
if not os.path.isdir(os.path.join(current_directory, species_name)):
os.mkdir(os.path.join(current_directory, species_name))
# Allocate 15% each (or 1, whichever is higher) to test and val, then the rest to train
file_count = len(files)
file_paths = [os.path.join(root, f) for f in files]
test_and_val_count = max(1, round(file_count * .15))
shuffle(file_paths)
test_files = [file_paths.pop() for _ in range(test_and_val_count)]
val_files = [file_paths.pop() for _ in range(test_and_val_count)]
train_files = file_paths
[copy(test_file, test_file.replace(basedir, test_dir)).replace(".", "") for test_file in test_files]
[copy(val_file, val_file.replace(basedir, val_dir)).replace(".", "") for val_file in val_files]
[copy(train_file, train_file.replace(basedir, train_dir)).replace(".", "") for train_file in train_files]
def display_dataset_sizes():
sizes = []
for (root, dirs, files) in os.walk("./dataset/"):
sizes.append(len(files))
sizes.sort(reverse=True)
pyplot.plot([s for s in sizes if s > 20])
pyplot.ylabel("Samples")
pyplot.xlabel("Classes")
pyplot.show()
if __name__ == '__main__':
task = sys.argv[1]
if task == "cultivars":
deal_with_cultivars()
elif task == "delete-small":
remove_small_folders()
elif task == "split":
generate_split()
elif task == "graph-sizes":
display_dataset_sizes()
| true |
d1d016fa073aac60adddef36dfd2b30bdddff2b3 | Python | sandance/MyPractice | /1A/1A.py | UTF-8 | 81 | 2.90625 | 3 | [] | no_license | n,m,a=map(int,raw_input().split())
print -n/a*(-m/a)
#Ceiling of both n and m
| true |
b703be75d068397c70c2f1084775c1a9cd9984f0 | Python | ndwb/GreyWolfOptimiser_CoveragePathPlanning | /main.py | UTF-8 | 6,203 | 3.046875 | 3 | [] | no_license | import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import seaborn
import numpy as np
import time
import math
position_target = np.array([592,592])
position_Start = np.array([0,0])
numberOfWolves = 15
socialLearningNumber = 3
num_iter = 300
#This is a function to change the position of the target/prey and reset the iteration count.
def changePreyPosition(x_pos, y_pos):
global position_target
global i
position_target = np.array([x_pos,y_pos])
i=0
#Handling the mouse. This is used to track the mouse and update the position of prey accordingly.
class ClickChecker:
def __init__(self,preyPoint):
self.preyPoint = preyPoint
self.cid = preyPoint.figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
print(event.xdata, event.ydata)
changePreyPosition(event.xdata, event.ydata)
#Social learning number determines the number of wolves that the omegas learn from. In this case, it is 3 - alpha wolf, beta wolf and a gamma wolf
#This is used to calculate the constants that will be used throughout the program.
def calculateConstants(current_iter):
#a is a constant linearly decrease from 4 to 0. When a>1 exploration is preffered, and otherwise exploitation is preferred.
a = 4*(1 - current_iter/num_iter)*np.array([1,1])
# a = np.array([3,3])
r1 = np.random.rand(2)
# r1 = np.array([0.025,0.462])
r2 = np.random.rand(2)
# r2 = np.array([0.067,0.9])
return a, r1, r2
# print(position_target)
def calculateNewPosition(prey_position,currentPosition, current_iter, fitnessArray, isOmega):
#Omegas learn from the alpha beta and the delta. Their next position is determined by the next position of the these three wolves
#IsOmega - marker for each wolf that determines whether they are learning from the leaders or going behind the prey.
# scalingVector = np.array([1/20,1/20])
if(isOmega==True):
nextPosition = np.array([0.,0.])
for i in range(socialLearningNumber):
position = wolfPositions[fitnessArray[-(socialLearningNumber+1)][0],:]
a,r1,r2 = calculateConstants(current_iter)
A = 2*np.multiply(a,r1) - a
C = 2*r2
D = np.multiply(C,position) - currentPosition
# D = np.multiply(scalingVector,D)
nextPosition += (position - np.multiply(A,D))/socialLearningNumber
# print("Magnitude of nextPos", np.linalg.norm(nextPosition),"\n")
else:
a,r1,r2 = calculateConstants(current_iter)
A = 2*np.multiply(a,r1) - a
C = 2*r2
D = np.multiply(C,prey_position) - currentPosition
# D = np.multiply(scalingVector,D)
nextPosition = (prey_position - np.multiply(A,D))
#Vary the multiplication factor from 0.01 to 1 to observe different swarm behaviours.
# 0.01 - 0.1 gives movement similar to a swarm lead by an alpha, beta and delta
# whereas a multiplication factor in the range of 0.5 to 1 makes it work like an optimizer.
multiplicationFactor = 0.3
# buffer = currentPosition + multiplicationFactor*((nextPosition - currentPosition)/np.linalg.norm(nextPosition - currentPosition))
buffer = currentPosition + multiplicationFactor*(nextPosition - currentPosition)
return buffer
def fitnessFunction(currentPosition, wolfPositions,current_iter):
intraSwarmDistance = 0
# There is a fitness associated with the distance of each robot from other members of the swarm.
# This is decreased over the number of iterations to give more preference to encircling and attacking behaviours.
k_intraSwarmDistance =1 - (current_iter/num_iter)
#This would be varied in the simulation environment.Communication threshold penalizes the wolves if they move further
#away from each other than their communication ranges allow.
wolf_communicationThreshold = 10
for wolf in range(len(wolfPositions)):
print("currentPosition",np.linalg.norm(wolf - currentPosition))
intraSwarmDistance += wolf_communicationThreshold/np.linalg.norm(wolf - currentPosition)
#Higher individual coverage increases reward in the beginning, and is steadily decreased over iterations.
k_coverageIndividual = 1 - (current_iter/num_iter)
#This reward is increased over iterations.
k_distanceFromGoal = 1 + (current_iter/num_iter)
coverageIndividual = np.linalg.norm(position_Start - currentPosition)
distanceFromGoal = np.linalg.norm(position_target - currentPosition)
#total fitness
fitness = (k_coverageIndividual*coverageIndividual) + (k_intraSwarmDistance*intraSwarmDistance) - (k_distanceFromGoal*distanceFromGoal)
print(fitness)
return fitness
#Calculates the fitness for all the wolves.
def calculateBest(wolfPositions,current_iter):
fitnessArray = []
for i in range(len(wolfPositions)):
fitnessArray.append([i, fitnessFunction(wolfPositions[i,:],wolfPositions,current_iter)])
return fitnessArray
#initialization for starting position
x_coor = position_Start[0]+np.cos(np.linspace(0,2*math.pi,numberOfWolves))
y_coor = position_Start[1]+np.sin(np.linspace(0,2*math.pi,numberOfWolves))
wolfPositions = np.array([x_coor,y_coor])
wolfPositions = np.transpose(wolfPositions)
np.random.seed()
fig = plt.figure()
ax = fig.add_subplot(111)
prey, = ax.plot(position_target[0],position_target[1],'x')
mouse = ClickChecker(prey)
i = 0
# for i in range(num_iter):
while i in range(num_iter):
fitnessArray = calculateBest(wolfPositions,i)
fitnessArray = sorted(fitnessArray, key = lambda x: x[1])
#Create an array that sorts the wolves by their fitness.
#The last three elements are respectively the delta, beta and the alpha.
print("\nHighest Fitness Position", wolfPositions[fitnessArray[-1][0],:], "\t Score of fittest", fitnessArray[-1][1])
for f in range(len(fitnessArray)):
if(f<numberOfWolves - socialLearningNumber):
wolfPositions[fitnessArray[f][0],:] = calculateNewPosition(position_target,wolfPositions[f,:],i,fitnessArray,True)
else:
wolfPositions[fitnessArray[f][0],:] = calculateNewPosition(position_target,wolfPositions[f,:],i,fitnessArray,False)
plt.plot(position_target[0],position_target[1],'x')
for j in wolfPositions:
#If the robobts leave the plot, you may have to change the axes limits to get all of them inside the frame.
plt.axis([-2000,2000,-2000,2000])
plt.plot(j[0],j[1],'o')
plt.pause(0.01)
plt.clf()
print(i,"\n")
i+=1
plt.show() | true |
edd40de34688428d060366a9cb29029a49c1827c | Python | snejDev/ElementaryCodes | /DataStructures/Arrays/O(n).py | UTF-8 | 109 | 3.3125 | 3 | [] | no_license | a=['a','b','c','d','e']
a.pop(1) #O(n)
print(a)
a.insert(0,1) #O(n)
print(a)
| true |
4b28dcbd5b585280fbd41b044007a9929385f9cb | Python | Alagupreethi/python | /largest.py | UTF-8 | 170 | 3.109375 | 3 | [] | no_license | n1=int(input())
n2=int(input())
n3=int(input())
if((n1>n2)and(n1>n3)):
largest=n1
elif((n2>n1)and(n2>n3)):
largest=n2
else:
largest=n3
print(largest) | true |
1ff47bf487ec682e7f4e2fdf7b80602b3bea1fc3 | Python | marinakeu/uriexercises | /1010.py | UTF-8 | 1,521 | 4.53125 | 5 | [] | no_license | '''
Neste problema, deve-se ler o código de uma peça 1, o número de peças 1,
o valor unitário de cada peça 1, o código de uma peça 2, o número de
peças 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor
a ser pago.
Entrada
O arquivo de entrada contém duas linhas de dados. Em cada linha
haverá 3 valores, respectivamente dois inteiros e um valor com 2
casas decimais.
Saída
A saída deverá ser uma mensagem conforme o exemplo fornecido abaixo,
lembrando de deixar um espaço após os dois pontos e um espaço após
o "R$". O valor deverá ser apresentado com 2 casas após o ponto.
'''
'''
Solution 1
piece_one = input().split()
piece_two = input().split()
code_one = int(piece_one[0])
quantity_one = int(piece_one[1])
price_one = float(piece_one[2])
code_two = int(piece_two[0])
quantity_two = int(piece_two[1])
price_two = float(piece_two[2])
total = (quantity_one * price_one) + (quantity_two * price_two)
print("VALOR A PAGAR: R$ {}".format(format(total, '.2f')))
'''
'''
Solution 2
piece_one = input().split()
piece_two = input().split()
total = (int(piece_one[1]) * float(piece_one[2])) + (int(piece_two[1]) * float(piece_two[2]))
print("VALOR A PAGAR: R$ {}".format(format(total, '.2f')))
'''
# Solution 3
code1, quantity1, price1 = [item for item in input().split()]
code2, quantity2, price2 = [item for item in input().split()]
total = (int(quantity1) * float(price1)) + (int(quantity2) * float(price2))
print("VALOR A PAGAR: R$ {}".format(format(total, '.2f')))
| true |
c8e2d189089bb698e4149911573a4108ccc98a24 | Python | marianux/jupytest | /untitled1.py | UTF-8 | 2,429 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 29 14:49:03 2023
@author: mariano
"""
# Inicialización e importación de módulos
# Módulos externos
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as sig
# Ahora importamos las funciones de PyTC2
from pytc2.sistemas_lineales import analyze_sys, pretty_print_bicuad_omegayq, tf2sos_analog, pretty_print_SOS
from pytc2.general import print_subtitle
def sim_aprox(aproxs, orders2analyze, ripple, attenuation):
all_sys = []
filter_names = []
for (this_aprox, this_order, this_ripple, this_att) in zip(aproxs, orders2analyze, ripple, attenuation):
if this_aprox == 'Butterworth':
z,p,k = sig.buttap(this_order)
eps = np.sqrt( 10**(this_ripple/10) - 1 )
num, den = sig.zpk2tf(z,p,k)
num, den = sig.lp2lp(num, den, eps**(-1/this_order))
z,p,k = sig.tf2zpk(num, den)
elif this_aprox == 'Chebyshev1':
z,p,k = sig.cheb1ap(this_order, this_ripple)
elif this_aprox == 'Chebyshev2':
z,p,k = sig.cheb2ap(this_order, this_ripple)
elif this_aprox == 'Bessel':
z,p,k = sig.besselap(this_order, norm='delay')
elif this_aprox == 'Cauer':
z,p,k = sig.ellipap(this_order, this_ripple, this_att)
num, den = sig.zpk2tf(z,p,k)
all_sys.append(sig.TransferFunction(num,den))
this_label = this_aprox + '_ord_' + str(this_order) + '_rip_' + str(this_ripple)+ '_att_' + str(this_att)
print_subtitle(this_label)
# factorizamos en SOS's
this_sos = tf2sos_analog(num, den)
pretty_print_SOS(this_sos, mode='omegayq')
filter_names.append(this_label)
analyze_sys( all_sys, filter_names )
aprox_name = 'Butterworth'
#aprox_name = 'Chebyshev1'
#aprox_name = 'Chebyshev2'
#aprox_name = 'Bessel'
#aprox_name = 'Cauer'
# parametrizamos el orden para cada aproximación
orders2analyze = [2, 3, 4]
# Mismo requerimiento de ripple y atenuación
aproxs = [aprox_name] * len(orders2analyze)
ripple = [3] * len(orders2analyze) # dB \alpha_{max} <-- Sin parametrizar, lo dejo en Butterworth
attenuation = [40] * len(orders2analyze) # dB \alpha_{min} <-- Sin parametrizar, att fija
sim_aprox(aproxs, orders2analyze, ripple, attenuation)
| true |
efaea196685c18887bbe7774859c17b0dc393922 | Python | Harshilpatel134/cs5590_python_deep_learning | /lab 2/Scource/task4.py | UTF-8 | 643 | 3.453125 | 3 | [] | no_license | import numpy
l=[]
a=1
d=input("enter dimension 1, 2, 3:") ## geting no. of dimension from user
for i in range(0,int(d)): ## getting size of each dimension
l+=[int(input("enter size of "+ str(i+1) +" dimension:"))]
a=a*l[i]
l.reverse()
arr=numpy.random.randint(0,1000,a,int) ## creating random value in vector
arrr=arr.reshape(l) ## reshaping it to our requirement
print (arrr) ## printing vector
print ("max element in vector is:" + str(numpy.amax(arrr))) ## printing max element
arrr[numpy.argmax(arrr)]=100
print(arrr)
print("it has been replaced with 100")
| true |
ed6a5484e4e256787f20bacb72a7405f550fe85b | Python | Sheventon/DataMiningEducation | /PageRank/transiction_matrix.py | UTF-8 | 1,590 | 2.984375 | 3 | [] | no_license | class TransictionMatrix:
def __init__(self, global_nodes):
self.nodes = global_nodes
self.matrix = [[0] * (len(global_nodes) + 1) for i in range((len(global_nodes) + 1))]
self.dumping_factor = 0.85
self.vector = []
for element in range(len(self.nodes)):
self.vector.append(1 / len(self.nodes))
print(len(self.nodes))
print(len(self.vector))
self.fill_matrix()
def fill_matrix(self):
for key in self.nodes:
my_node = self.nodes.get(key)
count = float(len(my_node.children))
for i in range(len(my_node.children) - 1):
child_id = my_node.children[i].id
self.matrix[my_node.id][child_id] = self.dumping_factor / count
def multiply_matrix(self):
for k in range(20):
new_vector = self.vector
for i in range(len(self.matrix) - 1):
count = 0.0
for j in range(len(self.matrix[i]) - 1):
count += self.vector[j] * self.matrix[j][i]
new_vector[i] = count + (1 - self.dumping_factor) / len(new_vector)
self.vector = new_vector
page_rank_map = {}
for key in self.nodes:
node = self.nodes[key]
page_rank_map[node.link] = self.vector[node.id]
page_rank_map = {k: v for k, v in sorted(page_rank_map.items(),
key=lambda item: item[1],
reverse=True)}
return page_rank_map
| true |
2805b2597a997f30c442f36440419a08dea92a29 | Python | abhaysinh/Data-Camp | /Data Science for Everyone Track/19-Introduction to Shell/02- Manipulating data/08-How can I select columns from a file.py | UTF-8 | 896 | 3.890625 | 4 | [] | no_license | '''
How can I select columns from a file?
head and tail let you select rows from a text file. If you want to select columns, you can use the command cut. It has several options (use man cut to explore them), but the most common is something like:
cut -f 2-5,8 -d , values.csv
which means "select columns 2 through 5 and columns 8, using comma as the separator". cut uses -f (meaning "fields") to specify columns and -d (meaning "delimiter") to specify the separator. You need to specify the latter because some files may use spaces, tabs, or colons to separate columns.
What command will select the first column (containing dates) from the file spring.csv?
Instructions
50 XP
Possible Answers
cut -d , -f 1 seasonal/spring.csv
cut -d, -f1 seasonal/spring.csv
Either of the above.
Neither of the above, because -f must come before -d.
Answer : Either of the above.
''' | true |
a71258d77208cafbdad428a36b1a95983568c418 | Python | aarthisandhiya/aarthi | /23player.py | UTF-8 | 253 | 2.984375 | 3 | [] | no_license | m,n=map(int,input().split())
a=[int(m) for m in input().split()]
b=[int(n) for n in input().split()]
r=[]
for j in range(0,len(b)):
if b[j] in a:
print(max(a),end=" ")
else:
a.append(b[j])
print(max(a),end=" ")
| true |
6d9347d39d536591c14f2a11a268caa403fc835b | Python | SchizoDuckie/mega | /music_crawler/aliasCreator/wiki_loader.py | UTF-8 | 335 | 2.53125 | 3 | [] | no_license | import sqlite3
import re
import urllib3
from bs4 import BeautifulSoup
import datetime
import sys
import wikipediaapi
def wiki_crawler(target):
wiki_wiki = wikipediaapi.Wikipedia('zh-tw')
page_py = wiki_wiki.page(target)
print(page_py.title)
print(page_py.summary)
if __name__ == "__main__":
wiki_crawler("Nicki Minaj") | true |
f6ec81dd6c5239ee6ea412492ea98da2da423c4d | Python | therealcooperpark/Rosalind-Project | /algorithmic_heights/3SUM/solution.py | UTF-8 | 2,328 | 3.3125 | 3 | [] | no_license | #! /usr/bin/env python3
from argparse import ArgumentParser
def get_args():
parser = ArgumentParser()
parser.add_argument('input_file', help = 'rosalind input file')
parser.add_argument('output_file', help = 'output file for rosalind')
return parser.parse_args()
def parse_input(input_file):
'''
Parse input file into list of tuples
Each tuple has 2 lists, one negatives,
one positives
'''
arrays = []
with open(input_file, 'r') as file:
next(file)
for line in file:
negs = []
pos = []
idxs = {}
order = [int(num) for num in line.strip().split()]
for idx, num in enumerate(order):
idxs.setdefault(num, [])
idxs[num].append(idx)
if num < 0:
negs.append(num)
else:
pos.append(num)
arrays.append( (negs, pos, idxs) )
return arrays
def find_threesum(array):
'''
Find 3 numbers that sum to zero
'''
pos, neg, order = array[0], array[1], array[2]
# Get two numbers, try to find the third in the dict
for pos_num in pos:
for neg_num in neg:
leftover = pos_num + neg_num
try:
idx_3 = order[-leftover][0]
except KeyError:
continue
# Get index of other two numbers, sort and return them
idx_1 = order[pos_num][1] if pos_num == leftover else order[pos_num][0]
idx_2 = order[neg_num][1] if neg_num == leftover else order[neg_num][0]
idx_order = [idx_1, idx_2, idx_3]
idx_order.sort()
print('FOUND')
return [str(x+1) for x in idx_order]
# If all failed, return -1
print('FAILED')
return ['-1']
def write_output(answers, output_file):
'''
Write output file for rosalind
'''
with open(output_file, 'w') as file:
for answer in answers:
file.write(' '.join(answer) + '\n')
def main():
args = get_args()
arrays = parse_input(args.input_file)
answers = []
for x in arrays:
answers.append(find_threesum(x))
print('------------------------')
write_output(answers, args.output_file)
if __name__ == '__main__':
main()
| true |
3985ad6143249a9eb6ddce0077770121b6311522 | Python | anirudhshenoy/projectabc | /aggregator/models.py | UTF-8 | 1,502 | 2.609375 | 3 | [] | no_license | from django.db import models
class chapterDetail (models.Model):
GRADE_CHOICES = (
('5th', '5th'),
('6th', '6th'),
('7th', '7th'),
('8th', '8th'),
)
grade = models.CharField(
max_length=3,
choices=GRADE_CHOICES,
default='5th',
)
SUBJECT_CHOICES = (
('Science', 'Science'),
('Mathematics', 'Mathematics'),
('English', 'English'),
)
subject = models.CharField(
max_length=20,
choices=SUBJECT_CHOICES,
default='Science',
)
chapterTitle = models.CharField(max_length=300, default='Title')
chapterDescription = models.TextField(max_length=10000)
chapterNumber = models.CharField(max_length=2, default='NA')
def __str__(self):
return self.grade + '-' + self.subject + '-' + self.chapterTitle
class content (models.Model):
chapter = models.ForeignKey(chapterDetail, on_delete=models.CASCADE, default=1)
CONTENT_TYPE_CHOICES = (
('Video', 'Video'),
('Article', 'Article'),
('Other', 'Other'),
)
contentType = models.CharField(
max_length=10,
choices=CONTENT_TYPE_CHOICES,
default='Video',
)
contentLink = models.CharField(max_length=1000)
contentTitle = models.CharField(max_length=1000)
longDescription = models.TextField(max_length=10000)
shortDescription = models.TextField(max_length=10000)
def __str__(self):
return self.contentTitle
| true |
a5074b900cd51b708323cb1bdabaac9c38326475 | Python | deepick/marklogic-setup | /tests/test_integration.py | UTF-8 | 5,664 | 2.53125 | 3 | [] | no_license | """
tests application of CMA and trigger configs using curl.
using curl (rather then python requests) keeps HTTP requests
generic
"""
import unittest
import subprocess
import json
import time
import requests
from requests.auth import HTTPDigestAuth
import pytest
def check_resource_exists(test_cma_creds, test_rma_url, path):
"""utility function to check if MarkLogic resource exists using manage/v2"""
creds = test_cma_creds.split(":")
response = requests.get(
f"{test_rma_url}/{path}",
headers={"Accept": "application/json"},
auth=HTTPDigestAuth(creds[0], creds[1]),
)
return response.status_code == 200
def test_marklogic_is_accessible(test_marklogic_alive_url, test_cma_creds):
"""test for checking that marklogic is alive and accessible"""
creds = test_cma_creds.split(":")
response = requests.get(
f"{test_marklogic_alive_url}",
headers={"Accept": "application/json"},
auth=HTTPDigestAuth(creds[0], creds[1]),
)
assert response.status_code == 200
def test_curl_command_is_avail_can_access_marklogic(
command_curl, test_cma_url, test_cma_creds
):
"""curl command should be able to access test MarkLogic cluster"""
cmd = [
command_curl,
"--anyauth",
"--user",
test_cma_creds,
f"{test_cma_url}?format=json",
]
curl_result = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
assert curl_result.stdout is not None
assert curl_result.returncode == 0
def test_apply_cma_configuration_with_curl(
command_curl, test_cma_url, test_rma_url, test_cma_creds
):
"""create configuration and apply using curl"""
with open("etc/config.json", "r") as json_file:
data = json.load(json_file)
cmd = [
command_curl,
"--anyauth",
"--user",
test_cma_creds,
"-v",
"-H",
"Content-type: application/json",
"-d",
json.dumps(data),
f"{test_cma_url}?format=json",
]
curl_result = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
print(curl_result.returncode)
print(curl_result.stdout)
assert curl_result.returncode == 0
# we could introspect :8001/admin/v1/timestamp if cluster is quiescent
# but this should be enough on slower environments
time.sleep(5)
# sanity check resources have been created
# databases and forests exist
assert check_resource_exists(
test_cma_creds, test_rma_url, "databases/kerndaten-crawler-modules"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "forests/kerndaten-crawler-modules-1"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "databases/kerndaten-schemas"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "forests/kerndaten-schemas-1"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "databases/kerndaten-triggers"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "forests/kerndaten-triggers-1"
)
assert check_resource_exists(test_cma_creds, test_rma_url, "databases/kerndaten")
assert check_resource_exists(test_cma_creds, test_rma_url, "forests/kerndaten-1")
assert check_resource_exists(test_cma_creds, test_rma_url, "forests/kerndaten-2")
assert check_resource_exists(test_cma_creds, test_rma_url, "forests/kerndaten-3")
# privs exists
assert check_resource_exists(
test_cma_creds, test_rma_url, "privileges/kerndaten-uri?kind=uri"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "privileges/crawler-uri?kind=uri"
)
# user exists
assert check_resource_exists(
test_cma_creds, test_rma_url, "users/kerndaten-crawler"
)
# roles exists
assert check_resource_exists(test_cma_creds, test_rma_url, "roles/kerndaten-reader")
assert check_resource_exists(
test_cma_creds, test_rma_url, "roles/kerndaten-rest-reader"
)
assert check_resource_exists(test_cma_creds, test_rma_url, "roles/kerndaten-writer")
assert check_resource_exists(
test_cma_creds, test_rma_url, "roles/kerndaten-rest-writer"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "roles/kerndaten-crawler"
)
# servers exists
assert check_resource_exists(
test_cma_creds, test_rma_url, "servers/deepick-kerndaten?group-id=Default"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "servers/deepick-kerndaten.odbc?group-id=Default"
)
assert check_resource_exists(
test_cma_creds, test_rma_url, "servers/deepick-kerndaten.rest?group-id=Default"
)
def test_create_trigger_with_curl(command_curl, test_rma_url, test_cma_creds):
"""create configuration and apply using curl"""
with open("etc/trigger.json", "r") as json_file:
data = json.load(json_file)
cmd = [
command_curl,
"--anyauth",
"--user",
test_cma_creds,
"-v",
"-H",
"Content-type: application/json",
"-d",
json.dumps(data),
f"{test_rma_url}/databases/kerndaten/triggers?format=json",
]
curl_result = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
print(curl_result.returncode)
print(curl_result.stdout)
assert curl_result.returncode == 0
# sanity check trigger has been created
assert check_resource_exists(
test_cma_creds, test_rma_url, "databases/kerndaten/triggers/only-one-crawler"
)
if __name__ == "__main__":
unittest.main()
| true |
5d2ebf9b891360d74a4264c6fea9a36e748fc69b | Python | htl1126/leetcode | /1640.py | UTF-8 | 348 | 3.03125 | 3 | [] | no_license | # Ref: https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/918408/Python-5-lines-hashmap
class Solution:
def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
d = {p[0]: p for p in pieces}
ans = []
for n in arr:
ans += d.get(n, [])
return ans == arr
| true |
7cb2686af6a66b39c94aa182468251d7096988d9 | Python | nalangekrushna/comprinno_test | /10.py | UTF-8 | 234 | 3.71875 | 4 | [] | no_license | def get_gross_salary(salary) :
hra = 0
da = 0
if salary < 1500 :
hra = salary*.1
da = salary*0.9
else :
hra = 500
da = salary*0.98
return salary+hra+da
print(get_gross_salary(1312)) | true |
5af694d4d42afb33096f704b3c28b25eb734a540 | Python | Ronypea/GameOfLife | /GameOfLife.py | UTF-8 | 6,847 | 3.34375 | 3 | [] | no_license | import pygame
from pygame.locals import *
import random
from pprint import pprint as pp
import time
import pygame
from pygame.locals import *
import random
from pprint import pprint as pp
import time
class Cell:
def __init__(self, x, y):
self.state = 0
self.x = x
self.y = y
def is_alive(self):
return self.state
class CellList:
def __init__(self, nrow=1, ncol=1, filename=''):
self.nrow = nrow
self.ncol = ncol
self.filename = filename
self.i = 0
self.state = 0
if filename == '':
self.field = [[Cell(i, j) for i in range(self.ncol)] for j in range(self.nrow)]
else:
self.read_file()
def __iter__(self):
return self
def __next__(self):
if self.i < self.ncol * self.nrow:
res = self.field[(self.i) // self.ncol][(self.i) % self.ncol]
self.i += 1
return res
raise StopIteration()
pass
def __str__(self):
res = [[cell.state for cell in row] for row in self.field]
return str(res)
def read_file(self):
f = open(self.filename)
s = f.read()
f.close()
col = 0
self.nrow = 1
self.ncol = len(s[0:s.find('\n')])
while s.find('\n') != -1:
num = s.find('\n')
s = s[0:num] + s[num + 1:]
self.nrow += 1
self.field = [[Cell(i, j) for i in range(self.ncol)] for j in range(self.nrow)]
j = 0
for i in s:
self.field[j // self.ncol][j % self.ncol].state = int(i)
j += 1
class GameOfLife:
def __init__(self, width=640, height=480, cell_size=10, speed=0.1):
self.width = width
self.height = height
self.cell_size = cell_size
# Устанавливаем размер окна
self.screen_size = width, height
# Создание нового окна
self.screen = pygame.display.set_mode(self.screen_size)
# Вычисляем количество ячеек по вертикали и горизонтали
self.cell_width = self.width // self.cell_size
self.cell_height = self.height // self.cell_size
# Скорость протекания игры
self.speed = speed
def draw_grid(self):
# http://www.pygame.org/docs/ref/draw.html#pygame.draw.line
for x in range(0, self.width, self.cell_size):
pygame.draw.line(self.screen, pygame.Color('black'),
(x, 0), (x, self.height))
for y in range(0, self.height, self.cell_size):
pygame.draw.line(self.screen, pygame.Color('black'),
(0, y), (self.width, y))
def run(self):
pygame.init()
pygame.display.set_caption('Game of Life')
self.screen.fill(pygame.Color('white'))
self.field = self.cell_list(randomize=True)
running = True
count = 0
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
self.draw_grid()
self.draw_cell_list(self.field)
pygame.display.flip()
self.field = self.update_cell_list(self.field)
time.sleep(self.speed)
pygame.quit()
def cell_list(self, randomize=False):
"""
Создание списка клеток.
Клетка считается живой, если ее значение равно 1.
В противном случае клетка считается мертвой, то
есть ее значение равно 0.
Если параметр randomize = True, то создается список, где
каждая клетка может быть равновероятно живой или мертвой.
"""
if randomize:
cell_list = CellList(nrow=self.cell_height, ncol=self.cell_width)
for cell in cell_list:
cell.state = random.randint(0, 1)
return cell_list.field
def draw_cell_list(self, rects):
"""
Отображение списка клеток 'rects' с закрашиванием их в
соответствующе цвета
Rect - координаты прямоугольника в формате (x, y, длина стороны a, длина стороны b)
"""
for i in range(self.cell_height):
for j in range(self.cell_width):
if rects[i][j].state:
pygame.draw.rect(self.screen, pygame.Color('green'), (
j * self.cell_size + 1, i * self.cell_size + 1, self.cell_size - 1, self.cell_size - 1))
else:
pygame.draw.rect(self.screen, pygame.Color('white'), (
j * self.cell_size + 1, i * self.cell_size + 1, self.cell_size - 1, self.cell_size - 1))
def get_neighbours(self, cell):
"""
Вернуть список соседних клеток для клетки cell.
Соседними считаются клетки по горизонтали,
вертикали и диагоналям, то есть во всех
направлениях.
"""
x, y = cell
newX = x - 1
newY = y - 1
neigh = []
for i in range(3):
for j in range(3):
if (x == i + newX) and (y == j + newY):
continue
if (newX + i < 0) or (newY + j < 0):
continue
if (newX + i >= self.cell_height) or (newY + j >= self.cell_width):
continue
neigh.append(Cell(i + newX, j + newY))
return neigh
def nAlive(self, i, j, cell_list):
numAlive = 0
for k in self.get_neighbours((i, j)):
x, y = k.x, k.y
if cell_list[x][y].state == 1:
numAlive += 1
return numAlive
def update_cell_list(self, cell_list):
"""
Обновление состояния клеток
"""
newField = [[Cell(i, j) for j in range(self.cell_width)] for i in range(self.cell_height)]
numAlive = 0
for i in range(self.cell_height):
for j in range(self.cell_width):
if (cell_list[i][j].state == 0) and (self.nAlive(i, j, cell_list) == 3):
newField[i][j].state = 1
elif (cell_list[i][j].state == 1) and (self.nAlive(i, j, cell_list) in [2, 3]):
newField[i][j].state = 1
return newField
if __name__ == '__main__':
game = GameOfLife(700, 500, 50)
game.run() | true |
736b25d9dd6ccb8c04ea88d667c2c6ec69bf359c | Python | lyl0521/lesson-0426 | /lesson/day03/test.py | UTF-8 | 866 | 4.09375 | 4 | [] | no_license | # all()
print(all([0,1,2,3])) # False
print(all([1,2,3])) # True
print(all(['a','b','c',''])) # False
print(all(['a','b','c','d'])) #True
print(all(('a','b','c','d'))) #True
print(all(('a','b','','c'))) #False
print(all((0,1,2,3))) #False
print(all((1,2,3))) #True
print(all([])) # True empty list
print(all(())) # True empty tuple
# any()
# 如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true。
print(any(['a', 'b', 'c', 'd'])) #True
print(any(['a', 'b', '', 'd'])) #True
print(any([0, '', False])) #False
print(any(('a', 'b', 'c', 'd'))) #True
print(any(('a', 'b', '', 'd'))) #True
print(any((0, '', False))) #False
print(any([])) #True
print(any(())) #True
# bin()
# 返回整数的二进制表示
print(bin(int(10)))
print(bin(10))
| true |
29fc913c63388dec0691169a12d144c7518d2462 | Python | Mo0dy/Code4Fun | /Projects/MatrixAnimations/LangdonsAnt.py | UTF-8 | 1,348 | 2.734375 | 3 | [] | no_license | from Code4Fun.Utility.Vec2 import *
import numpy as np
import pygame as pg
from scipy.ndimage.filters import convolve
import random
directions = [Vec2(1, 0),
Vec2(0, 1),
Vec2(-1, 0),
Vec2(0, -1)]
dir_index = 0
def turn_right():
global dir_index
dir_index = (dir_index + 1) % 4
def turn_left():
global dir_index
dir_index = dir_index - 1
if dir_index < 0:
dir_index = 3
def flip():
global mat
mat[ant.x, ant.y] = not mat[ant.x, ant.y]
def move():
global ant
ant += directions[dir_index]
# out of bounds check and resolution
if ant.x >= mat.shape[0]:
ant.x = 0
elif ant.x < 0:
ant.x = mat.shape[0] - 1
elif ant.y >= mat.shape[1]:
ant.y = 0
elif ant.y < 0:
ant.y = mat.shape[1] - 1
def init(mat_shape):
global mat, ant
mat = np.zeros((mat_shape[0], mat_shape[1]))
# mat = (np.random.rand(mat_shape[0], mat_shape[1]) * 2).astype(int)
ant = Vec2(int(mat_shape[0] / 2), int(mat_shape[1] / 2))
def do_step():
global mat, ant
# white square
if mat[ant.x, ant.y]:
turn_right()
else:
turn_left()
flip()
move()
def update(content):
do_step()
content[:, :, 0] = mat * 255
content[:, :, 1] = mat * 255
content[:, :, 2] = mat * 255
| true |
f0639c22efd76e2a17f0b0d8c7d0f993ac3882e9 | Python | incolumepy-cursos/poop | /head_first_design_patterns/factory/abstract_factory/cheese.py | UTF-8 | 679 | 3.40625 | 3 | [
"MIT"
] | permissive | """
Notes:
- Each cheese has its own str representation
- Each ingredient is a product that is produced
by a Factory Method (create_cheese)
in the Abstract Factory (PizzaIngredientFactory)
See pizza_ingredient_factory.py
"""
from abc import ABC, abstractmethod
class Cheese(ABC):
@abstractmethod
def __str__(self) -> str:
raise NotImplementedError
class ParmesanCheese(Cheese):
def __str__(self) -> str:
return "Shredded Parmesan"
class ReggianoCheese(Cheese):
def __str__(self) -> str:
return "Reggiano Cheese"
class MozzarellaCheese(Cheese):
def __str__(self) -> str:
return "Shredded Mozzarella"
| true |
d68de8134ce962dcae70808832fcd50ca272ec42 | Python | Yarince/PythonProjects | /py_games/hangman_game/app_main.py | UTF-8 | 2,272 | 4.03125 | 4 | [] | no_license | class Hangman(object):
__lives = 10
__guesses = 0
__answer = ""
def __init__(self, lives):
self.__lives = lives
self.__answer, self.__word = self.start_up()
def run(self):
while True:
print("Lives = ", self.__lives)
if self.__lives <= 0:
print("AF!")
break
print("Word is = ", self.__word)
if self.__word == self.__answer:
print("Congratulations!\n"
"You had %d guesses" % self.__guesses)
if input("Want to play again? y/n:\n") == 'y':
self.__answer, self.__word = self.start_up()
continue
else:
break
guess = input("Guess:\n")
self.__guesses += 1
if len(guess) == 1:
self.__word = self.check_guess(self.__answer, guess, self.__word)
else:
if guess == self.__answer:
print("Congratulations!\n"
"You had %d guesses" % self.__guesses)
if input("Want to play again? y/n:\n") == 'y':
self.__answer, self.__word = self.start_up()
continue
else:
break
else:
print("Wrong guess. -3 lives!")
self.__lives -= 3
def check_guess(self, answer, guess, word):
if guess in answer:
i = 0
answer_list = list(answer)
while i < len(answer_list):
if answer_list[i] == guess:
word = self.change_letter(word, guess, i)
i += 1
else:
self.__lives -= 1
return word
def start_up(self):
self.__lives = 10
self.__guesses = 0
answer = input("What is the word to be guessed?\n")
word = '_' * answer.__len__()
return answer, word
@staticmethod
def change_letter(string, letter, index):
string_list = list(string)
string_list[index] = letter
return "".join(string_list)
class Main:
Hangman(10).run()
if __name__ == '__main__':
Main()
| true |
2017a3cfe307d892ce4ba8776f892a5d9ff24675 | Python | daniel-reich/ubiquitous-fiesta | /smLmHK89zNoeaDSZp_16.py | UTF-8 | 503 | 3.09375 | 3 | [] | no_license |
class Country:
def __init__(self, name, population, area):
self.name = name
self.population = population
self.area = area
self.pdens = population / area
self.is_big = self.population > 2.5 * 10**8 or self.area > 3*10**6
def compare_pd(self, other):
report_str = '%s has a %s population density than %s'
if self.pdens < other.pdens:
comp_str = 'smaller'
else:
comp_str = 'larger'
return report_str % (self.name, comp_str, other.name)
| true |
7677041d4c2245ef0bbda2db835edfff474b48e4 | Python | hemelroy/detekt | /viewimagewindow.py | UTF-8 | 1,933 | 2.53125 | 3 | [] | no_license | from PyQt5 import QtCore, QtGui, QtWidgets
class ImageWindow(object):
def setupUi(self, OtherWindow):
OtherWindow.setObjectName("OtherWindow")
OtherWindow.resize(1000, 1000)
self.centralwidget = QtWidgets.QWidget(OtherWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.defaultText = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(1, 1, 999, 999))
self.defaultText.setGeometry(QtCore.QRect(1, 1, 300, 300))
font = QtGui.QFont()
font.setPointSize(22)
self.defaultText.setFont(font)
self.defaultText.setObjectName("label2")
self.defaultText.setText("No image selected")
OtherWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(OtherWindow)
self.statusbar.setObjectName("statusbar")
OtherWindow.setStatusBar(self.statusbar)
self.retranslateUi(OtherWindow)
QtCore.QMetaObject.connectSlotsByName(OtherWindow)
def retranslateUi(self, OtherWindow):
_translate = QtCore.QCoreApplication.translate
OtherWindow.setWindowTitle(_translate("OtherWindow", "MainWindow"))
#self.label.setText(_translate("OtherWindow", "Welcome To This Window"))
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.defaultText.setAlignment(QtCore.Qt.AlignCenter)
#self.label.setPixmap(QtGui.QPixmap("images/birb.jpeg"))
def showImage(self, viewImgPath):
self.label.setPixmap(QtGui.QPixmap(viewImgPath))
if viewImgPath:
self.defaultText.hide()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
OtherWindow = QtWidgets.QMainWindow()
ui = ImageWindow()
ui.setupUi(OtherWindow)
OtherWindow.show()
sys.exit(app.exec_()) | true |
0a1eb720ab7a47246ef4e0a414de573e35a551d3 | Python | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/293/68196/submittedfiles/testes.py | UTF-8 | 92 | 2.65625 | 3 | [] | no_license | nome= input('Qual seu nome')
idade= input('Qual sua idade')
peso= input('Qual seu peso')
| true |
4d57768bc45a533d076349ad7fb786c7ff9b71c7 | Python | dumberdude/twitter-api | /app/models.py | UTF-8 | 174 | 2.671875 | 3 | [] | no_license | from datetime import datetime
class Tweet(object):
def __init__(self, msg):
self.id = None
self.text = msg
self.created_at = str(datetime.now())
| true |
8d3cc0e3396c621c0500e18d30c6158b7a7080dd | Python | Mahi/RPG-SP | /addons/source-python/plugins/rpg/skills/longjump/events.py | UTF-8 | 227 | 2.578125 | 3 | [] | no_license | def player_jump(player, skill, variables, **eargs):
v = player.velocity
multiplier = 1 + variables['velocity_multiplier_per_level'] * skill.level
v.x *= multiplier
v.y *= multiplier
player.base_velocity = v
| true |
45caf86edebc8d386cf863eb553e3fcfce94c496 | Python | zeusops/anniversary-banner | /banner/image/views.py | UTF-8 | 4,895 | 2.53125 | 3 | [] | no_license | from random import randint
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from PIL import Image, ImageDraw, ImageFont
from .models import BannerConfigEntry, Side, Team
TEAMS_PER_COLUMN = 5
TEAMS_LIMIT = TEAMS_PER_COLUMN * 3
WHITE = (229, 229, 229)
def _get_config(name):
config = BannerConfigEntry.objects.get(name=name)
return config.x1, config.y1, config.x2, config.y2, config.size
def _draw_images(images, target, debug=False):
for name, filename in images:
image = Image.open(filename, 'r').convert('RGBA')
x, y, w, h, _ = _get_config(name)
if w > 0 and h > 0:
image = image.resize((w, h))
target.paste(image, box=(x, y), mask=image)
if debug:
draw = ImageDraw.Draw(target)
draw.rectangle((x, y, x+image.width, y+image.height))
def _draw_points(target, side_left, side_right, debug=False):
font_points = ImageFont.truetype('font.otf', 55)
draw = ImageDraw.Draw(target)
logo_left = BannerConfigEntry.objects.get(name='logo_left')
logo_right = BannerConfigEntry.objects.get(name='logo_right')
logo_left_r = logo_left.x1 + logo_left.x2
points_middle = (
logo_left_r + ((logo_right.x1 - (logo_left_r)) / 2),
logo_left.y1 + (logo_left.y2 / 2)
)
# NOTE: The separator here is an en dash, not a minus
points_text = "{} – {}".format(side_left.points, side_right.points)
points_w, points_h = font_points.getsize(points_text)
points_corner = (
points_middle[0] - (points_w / 2),
points_middle[1] - (points_h / 2),
)
if debug:
draw.rectangle((
points_corner,
(points_corner[0]+points_w, points_corner[1]+points_h)))
draw.point(points_middle, fill='red')
draw.text(points_corner,
points_text,
font=font_points, align='center', fill=WHITE)
def _draw_leaderboard(target, debug=False):
draw = ImageDraw.Draw(target)
#draw.line((650, 50, 650, 350), fill=WHITE, width=2)
wx, wy, wrx, wry, _ = _get_config('wins')
nx, ny, nrx, nry, _ = _get_config('names')
font_leaderboard = ImageFont.truetype('DejaVuSans-Bold.ttf', 40)
font_headings = ImageFont.truetype('DejaVuSans-Bold.ttf', 18)
#draw.text((700, 50), "Top teams", font=font_leaderboard, fill=WHITE)
font_teams = ImageFont.truetype('DejaVuSans-Bold.ttf', 20)
teams = Team.objects.filter(side__active=True)[:TEAMS_LIMIT]
longest_name = ""
for team in teams:
if len(team.name) > len(longest_name):
longest_name = team.name
name_size = draw.textsize(longest_name, font_teams)
padding = name_size[0] + 70 + 20
#print(f"{padding=}")
#print(f"{longest_name=}")
team_chunks = _chunk_list(teams, TEAMS_PER_COLUMN)
for i, chunk in enumerate(team_chunks):
draw.text((wx + i * padding, wy), "points", fill='gray', font=font_headings, anchor="ls")
draw.text((nx + i * padding, ny), "name", fill='gray', font=font_headings)
for j, team in enumerate(chunk):
wins = str(team.points)
name = team.name
colour = team.side.colour
draw.text((wrx + i * padding, wry + j * 25), wins, fill=WHITE, font=font_teams)
draw.text((nrx + i * padding, nry + j * 25), name, fill=colour, font=font_teams)
def _chunk_list(iterable, chunk_size):
d = {}
for i, x in enumerate(iterable):
d.setdefault(i//chunk_size, []).append(x)
return(d.values())
def generate_banner(debug=False, rainbow=False):
sides = Side.objects.filter(active=True)
side_left = sides[0]
side_right = sides[1]
logos = [
('logo_main', 'media/image/logo_text_wide_resize.png'),
#('logo_left', side_left.logo),
#('logo_right', side_right.logo),
]
bgcolour = 'black'
if rainbow:
bgcolour = (randint(0, 255), randint(0, 255), randint(0, 255))
banner = Image.new('RGB', (1000, 400), color = bgcolour)
_draw_images(logos, banner, debug)
#_draw_points(banner, side_left, side_right, debug)
_draw_leaderboard(banner, debug)
return banner
@cache_page(15)
def banner(request):
debug = request.GET.get('debug', 'false') == "true"
rainbow = 'rainbow' in request.GET
img = generate_banner(debug, rainbow)
extension = request.path.split('.')[-1]
if extension == "jpg":
response = HttpResponse(content_type="image/jpeg")
img.save(response, 'jpeg')
elif extension == "png":
response = HttpResponse(content_type="image/png")
img.save(response, 'png')
return response
def index(request):
return HttpResponse('<html><head><meta http-equiv="refresh" content="60"></head><body><style>* { background: black; }</style><img src="/image/banner.jpg"></body></html>')
| true |
aa5d44a6be09a25c5faf93617cac19f3ae15b624 | Python | Kazhuu/movelister | /pythonpath/movelister/utils/alignment.py | UTF-8 | 222 | 2.546875 | 3 | [
"MIT"
] | permissive | from enum import Enum
class HorizontalAlignment(Enum):
STANDARD = 0
LEFT = 1
CENTER = 2
RIGHT = 3
BLOCK = 4
class VerticalAlignment(Enum):
STANDARD = 0
TOP = 1
CENTER = 2
BOTTOM = 3
| true |
fc01a3f5f9f02d38ba4766b174bafd02e6c0b85d | Python | citizenofathens/knowledge-graph-embedding | /KGE/ns_strategy.py | UTF-8 | 4,348 | 3.03125 | 3 | [] | no_license | import numpy as np
import tensorflow as tf
from .utils import ns_with_same_type
class NegativeSampler:
""" A base module for negative sampler.
"""
def __init__(self):
""" Initialized negative sampler
"""
raise NotImplementedError("subclass of NegativeSampler should implement __init__() to init class")
def __call__(self):
""" Confuct negative sampling
"""
raise NotImplementedError("subclass of NegativeSampler should implement __call__() to conduct negative sampling")
class UniformStrategy(NegativeSampler):
""" An implementation of uniform negative sampling
Uniform sampling is the most simple negative sampling strategy, usually is
the default setting of knowledge graph embedding models. It sample entities
from all entites with uniform distribution, and replaces either head or tail
entity.
"""
def __init__(self, sample_pool):
""" Initialize UniformStrategy negative sampler.
Parameters
----------
sample_pool : tf.Tensor
entities pool that used to sample.
"""
self.sample_pool = sample_pool
def __call__(self, X, negative_ratio, side):
""" perform negative sampling
Parameters
----------
X : tf.Tensor
positive triplets to be corrupt.
negative_ratio : int
number of negative sample.
side : str
corrup from which side, can be :code:`'h'` or :code:`'t'`
Returns
-------
tf.Tensor
sampling entities
"""
self.sample_pool = tf.cast(self.sample_pool, X.dtype)
sample_index = tf.random.uniform(
shape=[X.shape[0] * negative_ratio, 1],
minval=0, maxval=len(self.sample_pool), dtype=self.sample_pool.dtype
)
sample_entities = tf.gather_nd(self.sample_pool, sample_index)
return sample_entities
class TypedStrategy(NegativeSampler):
""" An implementation of typed negative sampling strategy.
Typed negative sampling consider the entities' type, for example, for the
positive triplet :math:`(MonaLisa, is\_in, Louvre)`, we may generate illogical
negative triplet such as :math:`(MonaLis, is\_in, DaVinci)`. So Typed negative
sampling strategy consider the type of entity to be corrupt, if we want
to replace *Louvre*, we only sample the entities which have same type
with *Louvre*.
.. caution::
When using :py:mod:`TypedStrategy <KGE.ns_strategy.TypedStrategy>`, :code:`metadata` should contains
key :code:`'ind2type'` to indicate the entities' type when calling
:py:func:`train() <KGE.models.base_model.BaseModel.KGEModel.train>`.
"""
def __init__(self, pool, metadata):
""" Initialize TypedStrategy negative sampler.
Parameters
----------
pool : :ref:`multiprocessing.pool.Pool <https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool>`
multiprocessing pool for parallel.
metadata : dict
metadata that store the entities' type information.
"""
self.pool = pool
self.metadata = metadata
def __call__(self, X, negative_ratio, side):
""" perform negative sampling
Parameters
----------
X : tf.Tensor
positive triplets to be corrupt.
negative_ratio : int
number of negative sample.
side : str
corrup from which side, can be :code:`'h'` or :code:`'t'`
Returns
-------
tf.Tensor
sampling entities
"""
from itertools import repeat
if side == "h":
ref_type = X[:, 0].numpy()
elif side == "t":
ref_type = X[:, 2].numpy()
if self.pool is not None:
sample_entities = self.pool.starmap(
ns_with_same_type,
zip(ref_type, repeat(self.metadata), repeat(negative_ratio))
)
else:
sample_entities = list(map(
lambda x: ns_with_same_type(x, self.metadata, negative_ratio),
ref_type
))
sample_entities = tf.constant(np.concatenate(sample_entities), dtype=X.dtype)
return sample_entities | true |
a230f53599de8f5c6bd17065bff56868e854edc6 | Python | MisterLenivec/studyPython | /stepic-python-programming/1-12_area-of-triangles.py | UTF-8 | 616 | 3.625 | 4 | [] | no_license | #Напишите программу, вычисляющую площадь треугольника по переданным длинам трёх его сторон по формуле Герона.
#На вход программе подаются целые числа, выводом программы должно являться вещественное число, соответствующее площади треугольника.
#Sample Input:
#3
#4
#5
#Sample Output: 6.0
a = int(input())
b = int(input())
c = int(input())
p = (a + b + c) / 2
s = (p *(p - a)*(p - b)*(p - c)) ** 0.5
print(s)
| true |
b1527254b1f3d00eaeedb6e95dfd4306d91ce088 | Python | Aasthaengg/IBMdataset | /Python_codes/p03001/s487504198.py | UTF-8 | 404 | 3.125 | 3 | [] | no_license | #
import sys
# sys.setrecursionlimit(100000)
def input():
return sys.stdin.readline().strip()
def input_int():
return int(input())
def input_int_list():
return [int(i) for i in input().split()]
def main():
w, h, x, y = input_int_list()
area = (w * h) / 2
bl = (w == 2 * x and h == 2 * y)
print(area, 1 if bl else 0)
return
if __name__ == "__main__":
main()
| true |
c74b80c5952b0436c284d3065cbbb859e349fa9b | Python | bsakari/Python-Lessons | /Lesson4/If_ElseStetement.py | UTF-8 | 240 | 3.84375 | 4 | [] | no_license | num1 = 10
num2 = 20
if num1<=num2:
print("Num1 is less or Equal to Num2")
else:
print("Num 2 is greater than Num1")
if num2<=num1:
print("Num 1 is greater than or Equal to Num2")
else:
print("Num2 is less or Equal to Num1") | true |
1f6f4b47c92967c485e043b62b2e2079f8c7b87c | Python | Tosin5S/GlobalAIHubPythonCourse | /Homeworks/day_5_Animals.py | UTF-8 | 1,465 | 4.15625 | 4 | [] | no_license | class Animals:
def __init__ (self, name = " ", colour = " ", type = " ", age = 0):
self.name = name
self.colour = colour
self.type = type
self.age = age
def setName(self,name):
self.name = name
def getName(self):
return self.name
def setColour(self,colour):
self.colour = colour
def setType(self,type):
self.type = type
def setAge(self,age):
self.age = age
def getAge(self):
return "{0} years".format(self.age)
def __str__(self):
return "{0} is a {1} {2} aged {3} years." .format(self.name, self.colour, self.type, self.age)
class Dogs(Animals):
def __init__ (self, name = " ", colour = " ", age = 0):
self.name = name
self.colour = colour
self.type = "Dog"
self.age = age
def setType(self, type):
print("{0} refuses to change type, it will always be a {1} in this Life." .format(self.name, self.type))
def setAge(self, age):
self.age = age
dog = Dogs("Lucky", "black", 6)
print(dog)
dog.setAge(10)
dog.getAge()
dog.setType("Cat")
dog.setName("Smart")
print(dog)
class Cats(Animals):
def setAge(self,age):
self.age = age
def getAge(self):
return"{0} years old." .format(self.age)
def __str__(self):
return("{0} is {1} years old {2} cat." .format(self.name, self.age, self.colour))
def say(self):
print("{0} says Meow, Meow, Meow!".format(self.name))
cat = Cats("Tussy","yellow",4)
print(cat)
cat.setAge(8)
print(cat.getAge())
print(cat)
cat.say()
| true |
f1951a5f9b8753e7a3fdca3e477e557467887ed6 | Python | hckmd/objects-database-examples | /queries/snippets/fetch_rows.py | UTF-8 | 151 | 3.328125 | 3 | [] | no_license | # Runs a SELECT query to retrieve rows from fruit table
cursor.execute('SELECT * FROM fruit')
rows = cursor.fetchall()
for row in rows:
print(row) | true |
06892767b3869dba2c81542a2c042a6b22540b6e | Python | lqiqiqi/self-driving | /Zmq_SUB1 (复件).py | UTF-8 | 911 | 2.546875 | 3 | [] | no_license | import zmq
import time
import sys
port = "5556"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
if len(sys.argv) > 2:
port1 = sys.argv[2]
int(port1)
# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)
print "Collecting updates from weather server..."
socket.connect ("tcp://localhost:%s" % port)
if len(sys.argv) > 2:
socket.connect ("tcp://localhost:%s" % port1)
# filter
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)
# Process 5 updates
total_value = 0
for update_nbr in range (5):
string = socket.recv()
topic, messagedata,pub_server_name = string.split()
total_value += int(messagedata)
print topic, messagedata,pub_server_name
print "Average messagedata value for topic '%s' was %dF" % (topicfilter, total_value / update_nbr)
| true |
7f2164206eabb13f28ffb23eb0ff471d8ba6d389 | Python | davidphan34/Gallery-Website-with-SQL | /mp3-77452669/viewImage.py | UTF-8 | 2,559 | 2.796875 | 3 | [] | no_license | #View Image python file
# - can view the Image Name and details
import pymysql
import cgi
db = pymysql.connect(host='localhost',
user='gallery',
passwd='eecs118',
db= 'gallery')
cur = db.cursor()
form = cgi.FieldStorage()
image_id_str = str(form.getvalue('image_id'))
sql="SELECT * FROM image NATURAL JOIN detail WHERE image_id=" + image_id_str #read from image natural joined with detail table
cur.execute(sql)
row = cur.fetchone()
image_title_pass = str(row[2]) #get title from tuple
image_link_pass = str(row[3]) #link
image_gallery_id_pass = str(row[4]) #gallery_id
detail_year_pass = str(row[6]) #year
detail_type_pass = str(row[7]) #type
detail_width_pass = str(row[8]) #width
detail_height_pass = str(row[9]) #height
detail_location_pass = str(row[10]) #location
detail_description_pass = str(row[11]) #description
detail_artist_id_pass = str(row[5]) #get artist id
sql="SELECT * FROM artist WHERE artist_id=" + detail_artist_id_pass
cur.execute(sql)
artist_row = cur.fetchone()
artist_name_pass = str(artist_row[1]) #get artist name
print("Content-Type: text/html") #HTML is following
print()
print("<html>")
print("<body>")
#link to go to 'Home'
print("<a href='77452669_index.py'>Home</a>")
#Click to go to 'Manage Image'
print('<form action="viewGallery.py">')
print('<button type="submit" name="gallery_id" value ="' + image_gallery_id_pass + '" class="btn-link">View Gallery</button>')
print('</form>')
print('<H1>Title: ' + image_title_pass + '</H1>') #Title
print('<img id="myimage" src=' + image_link_pass + ' width ="' + detail_width_pass + '" height ="' + detail_height_pass + '">') #setting up image values
print("<p>Image ID:" + str(form.getvalue('image_id')) + "</p>") #image ID
print('<p id="final_artist">Artist: ' + artist_name_pass + '</p>') #Artist
print('<p id="final_year">Year: ' + detail_year_pass + '</p>') #Year
print('<p id="final_location">Location: ' + detail_location_pass + '</p>') #Location
print('<p id="final_descrip">Brief Description: ' + detail_description_pass + '</p>') #Description
print('<form action="viewArtist.py">')
#put artist_id into cgi
print('<input id="artist_id" name="artist_id" type="hidden" value="' + detail_artist_id_pass + '">')
print('<input id="image_id" name="image_id" type="hidden" value="' + str(form.getvalue('image_id')) + '">')
print('<input type="submit" value="View more info about Artist" />') #Submit Button
print("</form>")
print("</body>")
print("</html>") | true |
de88fb7c7969b6da6a8ddd20684a91fe9ad828e9 | Python | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-9/Dice.py | UTF-8 | 1,390 | 4.78125 | 5 | [
"MIT"
] | permissive | """9-14. Dice:
The module random contains functions that generate random num-
bers in a variety of ways . The function randint() returns an integer in the
range you provide . The following code returns a number between 1 and 6:
from random import randint
x = randint(1, 6)
Make a class Die with one attribute called sides, which has a default
value of 6 . Write a method called roll_die() that prints a random number
between 1 and the number of sides the die has . Make a 6-sided die and roll
it 10 times .
Make a 10-sided die and a 20-sided die. Roll each die 10 times."""
from random import randint
class Dado():
def __init__(self, lados=6):
self.lados = lados
def TirarDado(self):
return randint(1, self.lados)
d6 = Dado()
resultados = []
for roll_num in range(10):
resultado = d6.TirarDado()
resultados.append(resultado)
print(f"\n10 tiradas con un dado de {6} lados:")
print(resultados)
d10 = Dado(lados=10)
resultados = []
for roll_num in range(10):
resultado = d10.TirarDado()
resultados.append(resultado)
print(f"\n10 tiradas con un dado de {10} lados:")
print(resultados)
d20 = Dado(lados=20)
resultados = []
for roll_num in range(10):
resultado = d20.TirarDado()
resultados.append(resultado)
print(f"\n10 tiradas con un dado de {20} lados:")
print(resultados) | true |
fd9df542d06863433784372507bb3326c8b8cb34 | Python | krrskl/chat | /app/views/estudiante.py | UTF-8 | 309 | 2.875 | 3 | [] | no_license | class Estudiante():
def __init__(self,nombre,fila,columna):
self.nombre = nombre
self.fila = fila
self.columna = columna
def getNombre(self):
return self.nombre
def getFila(self):
return self.fila
def getColumna(self):
return self.columna | true |
01f024bf4ed5da72292ba21e71e574826f5d44b3 | Python | P34br41n/Crypto | /OneTimePad.py | UTF-8 | 2,408 | 3.5 | 4 | [] | no_license | # output is binary ( 0bXXXXXXXX ), if you need a string
# look at hexlify and unhexlify in the binascii module
def otp(message, key):
if len(key) < len(message):
print("Key is too small")
return None
else:
crypt_msg = ''.join([bin(ord(a) ^ ord(b)) for a, b in zip(key, message)])
print(crypt_msg)
return crypt_msg
# Using otp key more than once is not a good idea and this is why:
# (m1 Xor key) Xor (m2 Xor key) = m1 Xor m2
# Note: anything outside [a-z][A-Z][0-9] isn't taken into account for this.
# For the knowledge:
# binary letter: a = 01100001; z = 01111010; A = 01000001; Z = 01011010.
# binary number: 0 = 00110000; 9 = 00111001.
# binary space = 00100000
# Fun part:
# a Xor space = A and A Xor space = a
# if m1 Xor m2 = 01XXXXXX <=> letter Xor (number or space)
# if m1 Xor m2 = 00XXXXXX <=> letter Xor letter OR number Xor (number or space)
# Note: a something Xored with itself will give 00000000
def Xor(m1, m2):
Xored = ""
size = max(len(m1), len(m2))
for x in range (0, size):
if m1[x] == m2[x]:
Xored += "0"
else:
Xored += "1"
return Xored
# This is assuming you only have 2 messages.
# If you have more you can cross match the "spaces" to get known letters.
def mtpcrack(message1, message2):
if len(message1) % 8 != 0 or len(message2) % 8 != 0:
print("Problem with messages")
return None
else:
Xored = Xor(message1, message2)
cutXor = [Xored[i:i+8] for i in range(0, len(Xored), 8)]
cutwords = []
tmpwords = ""
# Cut into words
for letter in cutXor:
tmpletter = int(letter,2)
if tmpletter > 63:
#This can be considered as "letter Xor space" most of the time
print("This letter should be: " + chr(int(letter,2) ^ ord(" ")))
print("(If this looks weird, then it's a number!)")
else:
print("Possible letters:")
# if A- or Z-a or z+ the letter is not correct
# <=> 90 < val < 97 or val < 65 or val > 122
possletters = ""
for val in range(97, 123):
tmp = val ^ tmpletter
if (tmp > 64 and tmp < 91) or (tmp > 96 and tmp < 123):
possletters += chr(tmp) + " "
print(possletters)
# No need to do 65-90 because it'll just give uppercase.
dump = input("Press enter for the next letter")
# Right here you could add a "check in a dictionary before printing"
# to know if the word exists or not.
# BUT complexity would explode -> O(26^l), l being the length of the word... | true |
15e8bc60ee23653b20e997a64fc712ef3b81d8e6 | Python | holomagnet/homeexercises | /python_functions - Ali Homework.py | UTF-8 | 4,078 | 4.59375 | 5 | [] | no_license |
# coding: utf-8
# <img src="http://imgur.com/1ZcRyrc.png" style="float: left; margin: 20px; height: 55px">
#
# ## Practise Python Functions
#
# ---
# ### Resources: potentially helpful functions
#
# * [Dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)
# * [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate)
# * [`len`](https://docs.python.org/3/library/functions.html#len)
# * [`int`](https://docs.python.org/3/library/functions.html#int)
# * [`list`](https://docs.python.org/3/library/functions.html#func-list)
# * [`reversed`](https://docs.python.org/3/library/functions.html#reversed)
# ---
#
# ### 1) Write a function that takes the length of a side of a square as an argument and returns the area of the square.
# In[4]:
# A:
side=5
areaofsquare=side**2
print(areaofsquare)
##Solution2
# Python Program - Calculate Area of Square
print("Enter 'x' for exit.");
side = input("Enter side length of Square: ");
if side == 'x':
exit();
else:
side_length = int(side);
area_square = side_length*side_length;
print("\nArea of Square =",area_square);
# ---
#
# ### 2) Write a function that takes the height and width of a triangle and returns the area.
# In[19]:
# A:
def area_rectangle (height, width):
area = height * width
print("Area of a Rectangle is: ", area)
area_rectangle(5, 10)
# ---
#
# ### 3) Write a function that takes a string as an argument and returns a tuple consisting of two elements:
# - **A list of all of the characters in the string.**
# - **A count of the number of characters in the string.**
# In[34]:
# A:
string="thisisastring"
print(list(string), len(string))
##solution 2
def stringargument (string):
stringargument=list(string)
return(stringargument, len(stringargument))
stringargument('thisisastring')
# ---
#
# ### 4) Write a function that takes two integers, passed as strings, and returns the sum, difference, and product as a tuple (with all values as integers).
# In[39]:
# A:
def function(x,y):
x=int(x)
y=int(y)
sum=(x+y)
difference=(x-y)
product=x*y
return(sum, difference, product)
tuple=function(2,3)
print(tuple)
# ---
#
# ### 5) Write a function that takes a list as the argument and returns a tuple consisting of two elements:
# - **A list with the items in reverse order.**
# - **A list of the items in the original list that have an odd index.**
# In[62]:
# A:
def listargument (list_a):
reverse=list(reversed(list_a))
oddlist=list_a[1::2]
return(reverse, oddlist)
listargument([1,2,3,4,5,6,7,8,9,10,12,14,16])
# In[63]:
##Q5 Solution 2
##solution2:
def listargument (list_a):
reverse=list(reversed(list_a))
oddlist=[]
for count, i in enumerate(list_a):
if count % 2==1:
oddlist.append(i)
return(reverse, oddlist)
listargument([1,2,3,4,5,6,7,8,9,10,12,14,16])
# ---
#
# ### Challenge: Write a function that returns the score for a word. A word's score is the sum of the scores of its letters. Each letter's score is equal to its position in the alphabet.
#
# So, for example:
#
# * A = 1, B = 2, C = 3, D = 4, E = 5
# * abe = 8 = (1 + 2 + 5)
#
#
# ***Hint 1:*** *The string library has a property, `ascii_lowercase`, that can save some typing here.*
#
# Nowadays, most of the `string` module's components are already built into Python. However, it still has several [constant values](https://docs.python.org/3/library/string.html#string-constants) that can be useful, including:
# ```python
# string.ascii_uppercase
# ```
#
# ***Hint 2:*** *you may want to use a `list`'s [`index` method](https://www.tutorialspoint.com/python3/list_index.htm)*
# In[1]:
import string
string.ascii_uppercase
# In[76]:
# A:
import string
letters_score=[]*len(string.ascii_lowercase)
score=letters.index(string.ascii_lowercase)
def word_score(word):
word = word.lower()
total = 0
for letter in word:
total += score[letters]
return total
word = 'ali'
word_score('ali')
| true |
44ff7a625bab06d367b3b378160527504b04f007 | Python | lzwhirstle/comp1531 | /lab02/password.py | UTF-8 | 1,867 | 4.03125 | 4 | [] | no_license | def check_password(password):
'''
Takes in a password, and returns a string based on the strength of that password.
The returned value should be:
* "Strong password", if at least 12 characters, contains at least one number, at least one uppercase letter, at least one lowercase letter.
* "Moderate password", if at least 8 characters, contains at least one number.
* "Poor password", for anything else
* "Horrible password", if the user enters "password", "iloveyou", or "123456"
'''
if password is "password" or password is "iloveyou" or password is "123456":
return "Horrible password"
len = 0
num = False
upper = False
lower = False
for l in password:
if l.isdigit():
num = True
if l.isupper():
upper = True
if l.islower():
lower = True
len += 1
if len >= 12 and num and upper and lower:
return "Strong password"
elif len >= 8 and num:
return "Moderate password"
else:
return "Poor password"
if __name__ == '__main__':
print(check_password("ihearttrimesters"))
#test for password.py
def test_password1():
assert check_password("iloveyou") == "Horrible password"
assert check_password("lol :)wsajdiloveyou435287") == "Moderate password"
assert check_password("LOL :)wsajdiloveyou435287") == "Strong password"
def test_password2():
assert check_password("QWERTYUIOPL,MNBVCXZASDFGHJK12345") == "Moderate password"
assert check_password("QWERTYUIOPL,MNBVCXZASDFGHJK12345abc") == "Strong password"
def test_password3():
assert check_password("9-0-'/.;]..[") == "Moderate password"
assert check_password("9-0-[") == "Poor password"
assert check_password("------*^%&$#^%@#*[") == "Poor password"
| true |
ec6d3af845d49d59e54942406461ce86a3ea94c3 | Python | goliksa/Python | /6.while-break.py | UTF-8 | 479 | 3.953125 | 4 | [] | no_license | def attempt (name):
print (name + ", how are you? \"good\" or \"bad\"" )
print('Enter you name')
input_name = input()
while True:
attempt(input_name)
mood = input()
if mood == 'good' or mood == 'bad' or mood == 'Good' or mood == 'Bad':
break
else:
print('It is should be \"good\" or \"bad\"' )
if mood == 'good' or mood == 'Good':
print('I glad to hear it!')
else:
print('I realy hop It\'ll be OK')
| true |
fc146253c963e729c6f4e6ff9ea381fd82904cd4 | Python | orbicube/battlebutt | /ext/roles.py | UTF-8 | 12,651 | 2.71875 | 3 | [] | no_license | import discord
from discord.ext import commands
from discord import app_commands
from typing import Optional, Literal
from random import randint
import aiosqlite
class Roles(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="color", description="Change your role color")
@app_commands.guild_only()
@app_commands.describe(
code="Hex code (e.g. #123ABC), \"current\", \"random\"")
async def color(self, interaction: discord.Interaction, code: str):
# Color or colour
c_word = await self.bot.tree.translator.translate(
"color", interaction.locale, app_commands.TranslationContext(
app_commands.TranslationContextLocation.other, None))
if not c_word:
c_word = "color"
# Tell them their current color
if code.lower() == "current":
if interaction.user.color == discord.Color.default():
await interaction.response.send_message(
f"You don't have a {c_word}.", ephemeral=True)
return
else:
color = str(interaction.user.color).upper()
await interaction.response.send_message(
f"Your {c_word} is {color}.", ephemeral=True)
return
# Grab user's unique role from DB
async with aiosqlite.connect("ext/data/roles.db") as db:
async with db.execute("""SELECT role_id FROM role_map
WHERE user_id=? AND guild_id=?""",
(interaction.user.id, interaction.guild_id)) as cursor:
role_id = await cursor.fetchone()
# If they don't have a 1:1 role in the DB, make one for them
if not role_id:
role = await interaction.guild.create_role(
name = interaction.user.name)
await interaction.user.add_roles(role)
role = await role.edit(
position=int(len(interaction.guild.roles)/2))
await db.execute('INSERT INTO role_map VALUES (?, ?, ?)',
(interaction.user.id, interaction.guild_id, role.id))
await db.commit()
else:
role = interaction.guild.get_role(role_id[0])
old_color = str(role.color).upper()
if code.lower() == "random":
# discord.Color.random() gives somewhat limited results
role = await role.edit(color=discord.Color.from_rgb(
randint(0,255), randint(0,255), randint(0,255)))
else:
# Make sure they entered a viable code
if not code.startswith("#"):
code = f"#{code}"
try:
new_color = discord.Color.from_str(code)
except ValueError:
await interaction.response.send_message(
"That wasn't a valid hex code.", ephemeral=True)
return
# Checking against invisible name combos (plus or minus 5)
if 49 <= new_color.r <= 49:
if 52 <= new_color.g <= 62:
if 58 <= new_color.b <= 68:
await interaction.response.send_message(
"I'm not letting you turn invisible.",
ephemeral=True)
return
role = await role.edit(color=new_color)
await interaction.response.send_message((
f"Your {c_word} has been changed from {old_color}"
f" to {str(role.color).upper()}."))
@app_commands.command()
@app_commands.guild_only()
async def role(self, interaction: discord.Interaction,
action: Literal["Add", "Remove", "List"],
role: Optional[discord.Role]):
""" Add, remove or list publicly available roles """
async with aiosqlite.connect("ext/data/roles.db") as db:
if action == "List":
# Grab all roles for given guild, list them all out
async with db.execute("""SELECT role_id FROM role_whitelist
WHERE guild_id=?""",
(interaction.guild.id,)) as cursor:
roles = await cursor.fetchall()
if roles:
roles = [interaction.guild.get_role(role[0]).mention for role in roles]
await interaction.response.send_message(
f"**Available roles**:\n\n{', '.join(roles)}",
ephemeral=True)
return
else:
await interaction.response.send_message(
"This server doesn't have any available roles.",
ephemeral=True)
return
else:
# If Add/Remove, need to specify role argument
if not role:
await interaction.response.send_message(
"You need to specify a role.", ephemeral=True)
return
# Check if role is whitelisted to be freely added
async with db.execute("""SELECT role_id FROM role_whitelist
WHERE guild_id=? AND role_id=?""",
(interaction.guild.id, role.id)) as cursor:
role_in_db = await cursor.fetchone()
if not role_in_db:
await interaction.response.send_message(
"That role isn't whitelisted.", ephemeral=True)
return
if action == "Add":
if role in interaction.user.roles:
await interaction.response.send_message(
"You already have that role.", ephemeral=True)
else:
await interaction.user.add_roles(role)
await interaction.response.send_message(
f"{role.mention} role granted.", ephemeral=True)
else:
if role not in interaction.user.roles:
await interaction.response.send_message(
"You don't have that role.", ephemeral=True)
else:
await interaction.user.remove_roles(role)
await interaction.response.send_message(
f"{role.mention} role removed.", ephemeral=True)
@commands.command(hidden=True)
@commands.is_owner()
async def rolemap_json(self, ctx):
# Uses a rolemap.json file keyed 'user_id': 'role_id' to map user roles
with open('ext/data/rolemap.json') as f:
data = json.load(f)
async with aiosqlite.connect("ext/data/roles.db") as db:
for user_id, role_id in data.items():
await db.execute('INSERT INTO role_map VALUES (?, ?, ?)',
(int(user_id), ctx.guild.id, int(role_id)))
await db.commit()
@commands.command(hidden=True)
@commands.is_owner()
async def map_role(self, ctx, user: discord.User, role: discord.Role):
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute('INSERT INTO role_map VALUES (?, ?, ?)',
(user.id, ctx.guild.id, role.id))
await db.commit()
@commands.command(hidden=True)
@commands.is_owner()
async def unmap_role(self, ctx, user: discord.User, role: discord.Role):
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute("""DELETE FROM role_map
WHERE user_id=? AND guild_id=? AND role_id=?""",
(user.id, ctx.guild.id, role.id))
await db.commit()
@commands.command(hidden=True)
@commands.is_owner()
async def list_mapped_roles(self, ctx, user: discord.User):
async with aiosqlite.connect("ext/data/roles.db") as db:
async with db.execute("""SELECT role_id FROM role_map
WHERE user_id=? AND guild_id=?""",
(user.id, ctx.guild.id)) as cursor:
roles = await cursor.fetchall()
if not roles:
await ctx.send("No mapped roles for {user.name}.")
else:
for role in roles:
await ctx.send(f"{ctx.guild.get_role(role[0]).name} ({role[0]}")
@app_commands.default_permissions(administrator=True)
@app_commands.checks.has_permissions(administrator=True)
@app_commands.command()
async def whitelist(self, interaction: discord.Interaction,
action: Literal["Add", "Remove"], role: discord.Role):
""" Add or remove a role to the whitelist. """
if action == "Add":
if role.permissions.administrator:
await interaction.response.send_message(
f"Can't whitelist a role that has admin priviliges.",
ephemeral=True)
return
elif role.id == interaction.guild.id:
await interaction.response.send_message(
f"Can't whitelist @everyone. It doesn't even do anything.",
ephemeral=True)
try:
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute('INSERT INTO role_whitelist VALUES (?, ?)',
(interaction.guild.id, role.id))
await db.commit()
except:
await interaction.response.send_message(
f"That role has already been added.",
ephemeral=True)
await interaction.response.send_message(
f"Added {role.name} to the role whitelist.")
else:
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute("""DELETE FROM role_whitelist
WHERE guild_id=? AND role_id=?""",
(interaction.guild.id, role.id))
await db.commit()
await interaction.response.send_message(
f"Removed {role.name} from the whitelist.")
@commands.Cog.listener("on_guild_role_update")
async def check_mentionable(self, before, after):
""" Change whitelist if mentionable status has changed """
if before.mentionable != after.mentionable:
if after.mentionable:
# Don't let people add admin roles to list
if after.permissions.administrator:
return
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute('INSERT INTO role_whitelist VALUES (?, ?)',
(after.guild.id, after.id))
await db.commit()
else:
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute("""DELETE FROM role_whitelist
WHERE guild_id=? AND role_id=?""",
(after.guild.id, after.id))
await db.commit()
@commands.Cog.listener("on_guild_role_delete")
async def clean_list(self, deleted_role):
""" If deleted role was mentionable, remove it from the list """
if deleted_role.mentionable:
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute("""DELETE FROM role_whitelist
WHERE guild_id=? AND role_id=?""",
(deleted_role.guild.id, deleted_role.id))
await db.commit()
@commands.command(hidden=True)
@commands.is_owner()
async def role_cleanup(self, ctx):
async with aiosqlite.connect("ext/data/roles.db") as db:
async with db.execute("""SELECT role_id FROM role_whitelist
WHERE guild_id=?""", (ctx.guild.id,)) as cursor:
roles = await cursor.fetchall()
for role in roles:
if not ctx.guild.get_role(role[0]):
await db.execute("""DELETE FROM role_whitelist
WHERE guild_id=? AND role_id=?""",
(ctx.guild.id, role[0]))
await db.commit()
await ctx.send(f"Deleted {role[0]}")
async def setup(bot):
async with aiosqlite.connect("ext/data/roles.db") as db:
await db.execute('CREATE TABLE IF NOT EXISTS role_map (user_id integer, guild_id integer, role_id integer, UNIQUE(user_id, guild_id))')
await db.execute('CREATE TABLE IF NOT EXISTS role_whitelist (guild_id integer, role_id integer, UNIQUE(guild_id, role_id))')
await db.commit()
await bot.add_cog(Roles(bot))
| true |
b5d64515a4761aedc3eb495a891f38575ad4fe54 | Python | MISabic/tweet-emotion-detection-dataset | /tweepy_streamer.py | UTF-8 | 2,599 | 2.515625 | 3 | [] | no_license | from tweepy import OAuthHandler, API
from excelWrite import *
from decouple import config
from tqdm import tqdm
import sys, os
try:
CONSUMER_KEY = config('CONSUMER_KEY')
CONSUMER_SECRET = config('CONSUMER_SECRET')
ACCESS_TOKEN = config('ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = config('ACCESS_TOKEN_SECRET')
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = API(auth)
except:
print('API key missing!')
quit()
def writeFile(excelFileName, tweetsListWithEmotion) :
print(len(tweetsListWithEmotion))
# for i in range(len(tweetsListWithEmotion)):
# print(tweetsListWithEmotion[i][0],' ',tweetsListWithEmotion[i][1])
xWrite = excelWrite(excelFileName)
xWrite.writeText(tweetsListWithEmotion)
def run(numberOfTweetsInAFile) :
numberOfTweetsInAFile = int(numberOfTweetsInAFile)
directory = os.path.dirname(os.path.abspath(__file__))
srcFileName = os.path.join(directory, 'Dataset/test.txt')
if not os.path.exists(directory + '/Tweets'):
os.makedirs(directory + '/Tweets')
file = open(srcFileName, "r", encoding="utf-8" ).readlines()
tweetIdEmotion = []
tweetsListWithEmotion = []
fileNum = 1
numberOfCheckedTweets = 0
numberOfTweetsFound = 0
for line in tqdm(file) :
tweetIdEmotion = line.split('\t')
numberOfCheckedTweets += 1
# print("Number Of Tweets Found :: ", numberOfTweetsFound)
try:
tweet = api.get_status(tweetIdEmotion[0])
tweetText = str(tweet.text)
record = (tweetText.strip(), tweetIdEmotion[1].strip())
tweetsListWithEmotion.append(record)
numberOfTweetsFound += 1
if (numberOfTweetsFound % numberOfTweetsInAFile) == 0 :
dstFileName = os.path.join(directory, 'Tweets/')
xWrite = excelWrite(dstFileName + str(fileNum) + '.xlsx')
xWrite.writeText(tweetsListWithEmotion)
keepRecord = open(directory + "/Record.txt", "a")
keepRecord.write("Number Of Checked Tweets IDs :: " + str(numberOfCheckedTweets) + "\n")
keepRecord.write("Number Of Tweets Found :: " + str(numberOfTweetsFound) + "\n\n")
keepRecord.close()
fileNum += 1
tweetIdEmotion = []
tweetsListWithEmotion = []
except:
pass
file.close()
if __name__ == "__main__":
run(sys.argv[1])
| true |
d7760e338d78f1fee52c4ce040b430dfbaf18d36 | Python | ankursharma319/python_misc | /misc_labs/lab8.py | UTF-8 | 2,191 | 3.78125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 04 11:32:15 2015
@author: Ankur
"""
import math
import pylab
from scipy.optimize import brentq
def f1(x):
"""
accepts an number x as input and returns
cos(2pi*x)*(e^(-x^2))
"""
return math.cos(2*math.pi*x)*math.exp(-(x**2))
def f2(x):
"""
accepts the number x as input and returns
ln(x+2.2)
"""
return math.log(x+2.2)
def f1minusf2(x):
return f1(x)-f2(x)
def positive_places(f, xs):
"""
takes as arguments some function f and a list of numbers xs
and returns a list of those-and-only-those elements x of xs
for which f(x) is strictly greater than zero
"""
return [f(x) for x in xs if f(x) > 0]
def reverse_dic(d):
"""
takes a dictionary d as the input argument and returns a
dictionary r. If the dictionary d has a key k and an associated
value v, then the dictionary r should have a key v and a value k
"""
n = {}
for k in d.keys():
n[d[k]] = k
return n
def create_plot_data(f, xmin, xmax, n):
"""
Returns a tuple (xs, ys) where xs and ys are two sequences,
each containing n numbers
"""
if n >= 2:
def xi(i):
return xmin + i*(xmax-xmin)/(n-1.0)
xs = [xi(i) for i in range(n)]
ys = [f(x) for x in xs]
return (xs, ys)
else:
return "n less than 2"
def myplot():
"""
computes f1(x) and plots f1(x) using 1001 points for
x ranging from -2 to +2. The function returns None.
"""
plotData = create_plot_data(f1, -2, 2, 1001)
pylab.plot(plotData[0], plotData[1], label="f1")
plotData = create_plot_data(f2, -2, 2, 1001)
pylab.plot(plotData[0], plotData[1], label="f2")
pylab.xlabel('x')
pylab.ylabel('y(x)')
pylab.legend(loc="upper left")
pylab.savefig("plot.png")
pylab.savefig("plot.pdf")
pylab.show()
return None
def find_cross():
"""
Returns the value x (approximately) for which
f1(x) = cos(2 * pi * x) * exp(-x * x) and f2(x) = log(x + 2.2)
have the same value.
We are only interested in the solution where x > 0
"""
return brentq(f1minusf2, a=0, b=0.5)
| true |
859bd059a9e229a07029c5077a7dbdb9bc0ca452 | Python | jonikmen/Librivox-Grabber | /Python/pandas.py | UTF-8 | 2,491 | 3 | 3 | [] | no_license |
import numpy as np
import pandas as pd
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neural_network import BernoulliRBM
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, Imputer
from patsy import dmatrices, dmatrix
#Print you can execute arbitrary python code
df_train = pd.read_csv("../input/train.csv", dtype={"Age": np.float64}, )
df_test = pd.read_csv("../input/test.csv", dtype={"Age": np.float64}, )
# Drop NaNs
df_train.dropna(subset=['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'], inplace=True)
#print("\n\nSummary statistics of training data")
#print(df_train.describe())
# Age imputation
df_train.loc[df_train['Age'].isnull(), 'Age'] = np.nanmedian(df_train['Age'])
df_test.loc[df_test['Age'].isnull(), 'Age'] = np.nanmedian(df_test['Age'])
# Training/testing array creation
y_train, X_train = dmatrices('Survived ~ Age + Sex + Pclass + SibSp + Parch + Embarked', df_train)
X_test = dmatrix('Age + Sex + Pclass + SibSp + Parch + Embarked', df_test)
# Creating processing pipelines with preprocessing. Hyperparameters selected using cross validation
steps1 = [('poly_features', PolynomialFeatures(3, interaction_only=True)),
('logistic', LogisticRegression(C=5555., max_iter=16, penalty='l2'))]
steps2 = [('rforest', RandomForestClassifier(min_samples_split=15, n_estimators=73, criterion='entropy'))]
pipeline1 = Pipeline(steps=steps1)
pipeline2 = Pipeline(steps=steps2)
# Logistic model with cubic features
pipeline1.fit(X_train, y_train.ravel())
print('Accuracy (Logistic Regression-Poly Features (cubic)): {:.4f}'.format(pipeline1.score(X_train, y_train.ravel())))
# Random forest with calibration
pipeline2.fit(X_train[:600], y_train[:600].ravel())
calibratedpipe2 = CalibratedClassifierCV(pipeline2, cv=3, method='sigmoid')
calibratedpipe2.fit(X_train[600:], y_train[600:].ravel())
print('Accuracy (Random Forest - Calibration): {:.4f}'.format(calibratedpipe2.score(X_train, y_train.ravel())))
# Create the output dataframe
output = pd.DataFrame(columns=['PassengerId', 'Survived'])
output['PassengerId'] = df_test['PassengerId']
# Predict the survivors and output csv
output['Survived'] = pipeline1.predict(X_test).astype(int)
output.to_csv('output.csv', index=False)
| true |
6bc12f0a49aa1c1b9ea82d0bfd50f225658caa67 | Python | JiXuanyuan/tensorflow_example | /example02_graph.py | UTF-8 | 1,021 | 3.46875 | 3 | [] | no_license | import tensorflow as tf
# graph 计算图
# 1.graph用来构建计算流程,不组织数据和运算
# 2.graph由节点和弧组成,对应tensor和operator
# 3.tensorflow提供了一个默认图,创建的节点默认加到该图
# ==============================================
# 1.使用默认的计算图
# 构建计算图
a1 = tf.constant(12, dtype=tf.float32, name="input1")
a2 = tf.constant(5, dtype=tf.float32, name="input2")
print(a1)
print(a2)
b5 = tf.add(a1, a2, name="add")
b6 = tf.subtract(a1, a2, name="sub")
b7 = tf.multiply(a1, a2, name="mul")
b8 = tf.divide(a1, a2, name="div")
print(b5)
print(b6)
print(b7)
print(b8)
# 获取默认图,返回一个图的序列化的GraphDef表示
print(tf.get_default_graph().as_graph_def())
# ==============================================
# 2.创建一个新图
g = tf.Graph()
with g.as_default():
# 构建计算图
c1 = tf.constant(3)
c2 = tf.constant(4)
d1 = c1 * c2
print(c1)
print(c2)
print(d1)
print(g.as_graph_def())
| true |
ffbf0b44f35365817f618c45e48bfb70277d83de | Python | sravanthi-kethireddy/LeetCode | /14 Patterns/excel.py | UTF-8 | 180 | 3.15625 | 3 | [] | no_license | def printChar(n):
# print(chr(n))
string = ''
while n >0:
n, i = divmod(n-1, 26)
n = n%26
print(n,i)
string = chr(65 + i) + string
return string
print(printChar(152)) | true |
c8722af2d8d0c31e29c05c0a7a972340ae75a5f9 | Python | Ashok-Mishra/python-samples | /python exercises/dek_program021.py | UTF-8 | 1,664 | 3.9375 | 4 | [
"Apache-2.0"
] | permissive | # !/user/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# A robot moves in a plane starting from the original point (0,0). The
# robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The
# trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# The numbers after the direction are steps.
# Please write a program to compute the distance from current
# position after a sequence of movement and original point.
# If the distance is a float, then just print the nearest integer.
# Example:
# If the following tuples are given as input to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# Then, the output of the program should be:
# 2
# Hints:
# n case of input data being supplied to the question, it should be
# assumed to be a console input.
import math
print 'Enter Input like UP 5, DOWN 4, LEFT 3, RIGHT 5 ..'
def main():
position = [0, 0]
while True:
input_value = raw_input()
position_value = input_value.split(' ')
if position_value[0].upper() == 'UP':
position[0] += int(position_value[1])
elif position_value[0].upper() == 'DOWN':
position[0] -= int(position_value[1])
elif position_value[0].upper() == 'LEFT':
position[1] -= int(position_value[1])
elif position_value[0].upper() == 'RIGHT':
position[1] += int(position_value[1])
elif not input_value:
break
else:
pass
print position[0], position[1]
print 'Current Position is :',
print int(round(math.sqrt(position[0] ** 2 + position[1] ** 2)))
if __name__ == '__main__':
main()
| true |
75a6406c87facc9cf241b90ae83a3d214278d9ea | Python | the-carpnter/codewars-level-7-kata | /sum_of_a_nested_list.py | UTF-8 | 165 | 2.9375 | 3 | [] | no_license | def sum_nested(lst):
if lst == []:
return 0
return lst[0] + sum_nested(lst[1:]) if type(lst[0]) is int else sum_nested(lst[0]) + sum_nested(lst[1:])
| true |
993d8cd024fecd53c8a6535a25ca67192ecff3d8 | Python | sakshi97/btp | /main.py | UTF-8 | 405 | 3.125 | 3 | [] | no_license | # File: Hello.py
# print(char['text'].encode('utf-8'))
import pdfplumber
with pdfplumber.open("./resume.pdf") as pdf:
dictionary={}
count=0
for page in pdf.pages:
for char in page.chars :
dictionary[count] = [char['text'],char['x0'],char['y0'],char['fontname'],char['size']]
count+=1
for x in range(0,count):
print(dictionary[x])
print(count)
| true |
6959a7e7b99be2fb768c800bac886893da0218e7 | Python | Lyxn/or-model | /model/optimize_constraint.py | UTF-8 | 4,099 | 2.796875 | 3 | [] | no_license | from ortools.linear_solver import pywraplp
from util import reduce
def print_solver(solver):
print('Number of variables = %d' % solver.NumVariables())
print('Number of constraints = %d' % solver.NumConstraints())
print("Optimal objective value = %f" % solver.Objective().Value())
def print_constraint(coefficients, rhs, fmt=lambda x: "%d" % x):
idx = 0
expr = "%s*x%d" % (fmt(coefficients[idx]), idx + 1)
for i in range(1, len(coefficients)):
a = coefficients[i]
if a >= 0:
expr += " + %s*x%d" % (fmt(a), i + 1)
elif a < 0:
expr += " - %s*x%d" % (fmt(-a), i + 1)
expr += " <= %s" % fmt(rhs)
print(expr)
def argsort(s):
return sorted(range(len(s)), key=lambda k: s[k], reverse=True)
def get_rev_idx(idxs):
num = len(idxs)
rev = [0] * num
for i in range(num):
rev[idxs[i]] = i
return rev
def optimize_constraint(coefficients, rhs):
num = len(coefficients)
sign = [1 if x > 1 else -1 for x in coefficients]
rhs_new = rhs - sum(x for x in coefficients if x < 0)
coef_new = [abs(x) for x in coefficients]
idxs = argsort(coef_new)
coef_sort = [coef_new[i] for i in idxs]
rev_idxs = get_rev_idx(idxs)
def recover_constraint(arr, a0):
coef_rev = [arr[i] for i in rev_idxs]
coef_rev = [coef_rev[i] * sign[i] for i in range(num)]
rhs_rev = a0 + sum(x for x in coef_rev if x < 0)
return coef_rev, rhs_rev
coef_opt, rhs_opt = reduce_coef(coef_sort, rhs_new)
coef_opt_rev, rhs_opt_rev = recover_constraint(coef_opt, rhs_opt)
print("positive ordered inequality")
print_constraint(coef_sort, rhs_new)
print_constraint(coef_opt, rhs_opt)
return coef_opt_rev, rhs_opt_rev
def reduce_coef(a, a0):
ceilings = reduce.find_ceilings(a, a0)
roofs = reduce.find_roofs(a, a0)
return solve_reduce_prob(len(a), ceilings, roofs, a0)
def solve_reduce_prob(num_var, ceilings, roofs, upper):
# Solver
solver = pywraplp.Solver('optimize_constraint',
pywraplp.Solver.CLP_LINEAR_PROGRAMMING)
# Variable
b = {}
for i in range(num_var):
b[i] = solver.NumVar(0, upper, "b_%d" % i)
b0 = solver.NumVar(0, upper, "b0")
# Constraint
for i in range(num_var - 1):
solver.Add(b[i] >= b[i + 1])
# ceilings
for ceiling in ceilings:
expr = sum(b[i] for i in ceiling) <= b0
solver.Add(expr)
# roofs
for roof in roofs:
expr = sum(b[i] for i in roof) >= b0 + 1
solver.Add(expr)
# Object
obj = sum(b[i] for i in range(num_var))
solver.Minimize(obj)
# Solve
def print_variable():
out_b0 = "b0:\t%d" % b0.solution_value()
print(out_b0)
out_bi = "bi:"
for i in range(num_var):
out_bi += "\t%d" % b[i].solution_value()
print(out_bi)
solver.Solve()
# print_solver(solver)
# print_variable()
rhs = b0.solution_value()
coef = [b[i].solution_value() for i in range(num_var)]
return coef, rhs
def run():
rhs = 37
coefficients = [9, 13, -14, 17, 13, -19, 23, 21]
# ceilings = [{1, 2, 3}, {1, 2, 4, 8}, {1, 2, 6, 7}, {1, 3, 5, 6}, {2, 3, 4, 6}, {2, 5, 6, 7, 8}]
# roofs = [{1, 2, 3, 8}, {1, 2, 5, 7}, {1, 3, 4, 7}, {1, 5, 6, 7, 8}, {2, 3, 4, 5}, {3, 4, 6, 7, 8}]
coef_opt, rhs_opt = optimize_constraint(coefficients, rhs)
print_constraint(coefficients, rhs)
print_constraint(coef_opt, rhs_opt)
def run1():
a0_list = [80, 96, 20, 36, 44, 48, 24]
ai_list = [
[8, 12, 13, 64, 22, 41],
[8, 12, 13, 75, 22, 41],
[3, 6, 4, 18, 6, 4],
[5, 10, 8, 32, 6, 12],
[5, 13, 8, 42, 6, 20],
[5, 13, 8, 48, 6, 20],
[3, 2, 4, 8, 8, 4],
]
num_ieq = len(a0_list)
for i in range(num_ieq):
a0 = a0_list[i]
ai = ai_list[i]
print("inequality %s" % i)
bi, b0 = optimize_constraint(ai, a0)
print_constraint(ai, a0)
print_constraint(bi, b0)
if __name__ == '__main__':
run1()
| true |
085ebea83373188fde159ded60cfc843f02f7337 | Python | LSaldyt/proofs | /3-26/problems/code | UTF-8 | 469 | 3.46875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import matplotlib.pyplot as plt
x = range(5)
y1 = x
y2 = [4, 3, 2, 1, 0]
bound_below = [0] * 5
bound_above = [4] * 5
plt.scatter(x, y1, label='strictly increasing, monotonic, bounded')
plt.scatter(x, y2, label='strictly decreasing, monotonic, bounded')
plt.plot(x, bound_below, label='lower bound')
plt.plot(x, bound_above, label='upper bound')
plt.title('5.5.12')
plt.xlabel('N')
plt.ylabel('A totally ordered set, A')
plt.legend()
plt.show()
| true |