seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18 values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1 value | lang stringclasses 93 values | doc_type stringclasses 1 value | stars int64 0 179k ⌀ | dataset stringclasses 3 values | pt stringclasses 78 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20606152072 | import psutil
from influxdb import InfluxDBClient
import time
client = InfluxDBClient(host='localhost', port=8086)
client.create_database('system')
measurement_name = 'system_data'
data_end_time = int(time.time() * 1000)
data = []
cpu_p, mem_p, disk_read, disk_write, net_sent_now, net_recv_now, temp, \
boot_time, net_sent_prev, net_recv_prev = \
0, 0, 0, 0, 0, 0, 0, 0, \
psutil.net_io_counters().bytes_sent, psutil.net_io_counters().bytes_recv
def get_system_data():
global cpu_p, mem_p, disk_write, disk_read, net_recv_now, net_sent_now,\
temp, boot_time, data_end_time
data_end_time = int(time.time() * 1000)
cpu_p = psutil.cpu_percent()
mem_p = psutil.virtual_memory().percent
disk_read = psutil.disk_io_counters().read_count
disk_write = psutil.disk_io_counters().write_count
net_sent_now = psutil.net_io_counters().bytes_sent
net_recv_now = psutil.net_io_counters().bytes_recv
temp = psutil.sensors_temperatures()['acpitz'][0].current
boot_time = psutil.boot_time()
data.append(
{
"measurement": "system_data",
"tags": {
"boot_time": boot_time
},
"fields": {
"cpu_percent": cpu_p,
"memory_percent": mem_p,
"disk_read": disk_read,
"disk_write": disk_write,
"net_sent": net_sent_now-net_sent_prev,
"net_received": net_recv_now-net_recv_prev,
"temperature": temp,
},
"time": data_end_time
}
)
client.write_points(data, database='system', time_precision='ms',
protocol='json')
def run(interval=1): # interval in seconds
global net_recv_prev, net_sent_prev
print("Script is running, press Ctrl+C to stop!")
while 1:
try:
get_system_data()
net_sent_prev = psutil.net_io_counters().bytes_sent
net_recv_prev = psutil.net_io_counters().bytes_recv
time.sleep(interval)
except KeyboardInterrupt:
quit()
except:
pass
run()
| rishabh-22/influxdb-scripts | system_data_insert.py | system_data_insert.py | py | 2,150 | python | en | code | 1 | github-code | 6 |
1993996230 | import pandas as pd
import seaborn as sns
pd.set_option('display.max_columns', None)
df = sns.load_dataset("titanic")
df.head()
# ? iloc: integer based selection
df.iloc[0:3] # ! select the first three elements 0 1 2 indexes
df.iloc[0,0] # select element in row zero column zero
#? loc: label based selection
df.loc[0:3] # ! selects 0 1 2 3 indexes
df.iloc[0:3]
df.iloc[0:3, 0:3] # this only works for integers, cannot take age or other str
df.loc[0:3, "age"]
col_names = ["age" , "embarked" , "alive"]
df.loc[0:3, col_names] | queciaa/Miuul_PythonProgrammingForDataScience | Pandas/007_loc_iloc.py | 007_loc_iloc.py | py | 535 | python | en | code | 0 | github-code | 6 |
38454000752 | from collections import defaultdict
def factorize(n):
if n == 1:
return 0
factor = defaultdict(int)
while True:
isPrime = True
for i in range(2, int(n**0.5)+1):
if n % i == 0:
factor[i] += 1
n = n // i
isPrime = False
break
if isPrime:
factor[n] += 1
break
return factor
while True:
L = list(map(int,input().split()))
if L == [0]:
break
x = 1
for i in range(0,len(L),2):
x *= L[i]**L[i+1]
x -= 1
D = factorize(x)
Factor = []
for i in D:
Factor.append((i,D[i]))
Factor.sort(reverse=True)
for i in Factor:
print(*i, end=" ")
print('')
| LightPotato99/baekjoon | math/prime/primeland.py | primeland.py | py | 766 | python | en | code | 0 | github-code | 6 |
70766859707 | from .base import (
ConfMeta,
UrlParse,
FileRealPath,
Integer,
Boolean,
String,
)
class WorkerConf(
name='worker',
file='conf/worker.ini',
metaclass=ConfMeta
):
max_concurrent: Integer(
tag='TextField',
title='最大并发量',
desc='限制载荷的最大并发量。inf表示不做限制。'
)
independent: Boolean(
title='独占线程',
desc='若开启则该负载将使用独立的线程进行处理,不与其他载荷共享处理线程。'
)
entrypoint: String(
title='处理器入口点',
disabled=True
)
__items__ = {
'async': Boolean(
tag='Switches',
title='异步类型',
desc='描述该载荷处理器属于异步处理还是同步处理。',
disabled=True,
)
} | ZSAIm/VideoCrawlerEngine | helper/conf/worker.py | worker.py | py | 862 | python | zh | code | 420 | github-code | 6 |
19194200622 | k, n = map(int, input().split())
arr = []
for i in range(k):
arr.append(int(input()))
start = 0
end = max(arr)
result = 0
while start <= end:
total = 0
mid = (start + end) // 2
for i in arr:
if i >= mid:
total += i // mid
if total < n:
end = mid - 1
else:
result = mid
start = mid + 1
print(result) | Sangmyung-ICPC-Team/YunJu | Baekjoon/1654.py | 1654.py | py | 372 | python | en | code | 0 | github-code | 6 |
6399955298 | # welcome to tweet-yeet – lets yeet those tweets!
from datetime import datetime, timedelta
import tweepy
if __name__ == "__main__":
# options
delete_tweets = True
deletes_favs = False
censor= True
days_to_keep = 7
censor_word = "word"
# api info
consumer_key = 'XXXXXXXX'
consumer_secret = 'XXXXXXXX'
access_token = 'XXXXXXXX'
access_token_secret = 'XXXXXXXX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# set cutoff date
cutoff_date = datetime.utcnow() - timedelta(days=days_to_keep)
# delete tweets
if delete_tweets:
timeline = tweepy.Cursor(api.user_timeline).items()
deletion_count = 0
for tweet in timeline:
if tweet.created_at < cutoff_date:
api.destroy_status(tweet.id)
deletion_count += 1
print(deletion_count, "tweets have been deleted.")
# delete favorites / retweets
if delete_favs:
favorites = tweepy.Cursor(api.favorites).items()
deletion_count = 0
for tweet in favorites:
if tweet.created_at < cutoff_date:
api.destroy_status(tweet.id)
deletion_count += 1
print(deletion_count, "favorites have been deleted.")
if censor:
favorites = tweepy.Cursor(api.favorites).items()
timeline = tweepy.Cursor(api.user_timeline).items()
for favorite in favorites:
if censor_word in favorite:
api.destroy_status(favorite.id)
for tweet in timeline:
if censor_word in tweet:
api.destroy_status(tweet.id)
print(censor_word, "is a bad word") | Malcolmms/tweet_yeet | main.py | main.py | py | 1,769 | python | en | code | 0 | github-code | 6 |
36849894613 | import tensorflow.compat.v1 as tf
print(tf.__version__)
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
from graphnnSiamese import graphnn
from utils import *
import os
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument('--device', type=str, default='0,1,2,3',
help='visible gpu device')
parser.add_argument('--use_device', type=str, default='/gpu:1',
help='used gpu device')
parser.add_argument('--fea_dim', type=int, default=76,
help='feature dimension')
parser.add_argument('--embed_dim', type=int, default=64,
help='embedding dimension')
parser.add_argument('--embed_depth', type=int, default=5,
help='embedding network depth')
parser.add_argument('--output_dim', type=int, default=64,
help='output layer dimension')
parser.add_argument('--iter_level', type=int, default=5,
help='iteration times')
parser.add_argument('--lr', type=float, default=1e-4,
help='learning rate')
parser.add_argument('--epoch', type=int, default=100,
help='epoch number')
parser.add_argument('--batch_size', type=int, default=128,
help='batch size')
# parser.add_argument('--load_path', type=str,
# default='../data/saved_model/graphnn_model_ghidra/saved_ghidra_model_best',
# help='path for model loading, "#LATEST#" for the latest checkpoint')
parser.add_argument('--load_path', type=str,
default='../data/saved_model/graphnn_model_ghidra_depth5/graphnn_model_ghidra_best',
help='path for model loading, "#LATEST#" for the latest checkpoint')
parser.add_argument('--log_path', type=str, default=None,
help='path for training log')
if __name__ == '__main__':
args = parser.parse_args()
args.dtype = tf.float32
print("=================================")
print(args)
print("=================================")
os.environ["CUDA_VISIBLE_DEVICES"]=args.device
Dtype = args.dtype
NODE_FEATURE_DIM = args.fea_dim
EMBED_DIM = args.embed_dim
EMBED_DEPTH = args.embed_depth
OUTPUT_DIM = args.output_dim
ITERATION_LEVEL = args.iter_level
LEARNING_RATE = args.lr
MAX_EPOCH = args.epoch
BATCH_SIZE = args.batch_size
LOAD_PATH = args.load_path
LOG_PATH = args.log_path
DEVICE = args.use_device
SHOW_FREQ = 1
TEST_FREQ = 1
SAVE_FREQ = 5
# DATA_FILE_NAME_VALID = '../data/validation_arm2non_arm_gemini_data/'
DATA_FILE_NAME_TRAIN_TEST = '../data/vector_deduplicate_ghidra_format_less_compilation_cases/train_test'
F_PATH_TRAIN_TEST = get_f_name(DATA_FILE_NAME_TRAIN_TEST)
FUNC_NAME_DICT_TRAIN_TEST = get_f_dict(F_PATH_TRAIN_TEST)
print("start reading data")
Gs_train_test, classes_train_test = read_graph(F_PATH_TRAIN_TEST, FUNC_NAME_DICT_TRAIN_TEST, NODE_FEATURE_DIM)
print("train and test ---- 8:2")
print("{} graphs, {} functions".format(len(Gs_train_test), len(classes_train_test)))
perm = np.random.permutation(len(classes_train_test))
Gs_train, classes_train, Gs_test, classes_test =\
partition_data(Gs_train_test, classes_train_test, [0.8, 0.2], perm)
print("Train: {} graphs, {} functions".format(
len(Gs_train), len(classes_train)))
print("Test: {} graphs, {} functions".format(
len(Gs_test), len(classes_test)))
print("valid")
DATA_FILE_NAME_VALID = '../data/vector_deduplicate_ghidra_format_less_compilation_cases/valid'
F_PATH_VALID = get_f_name(DATA_FILE_NAME_VALID)
FUNC_NAME_DICT_VALID = get_f_dict(F_PATH_VALID)
Gs_valid, classes_valid = read_graph(F_PATH_VALID, FUNC_NAME_DICT_VALID, NODE_FEATURE_DIM)
print("{} graphs, {} functions".format(len(Gs_valid), len(classes_valid)))
Gs_valid, classes_valid = partition_data(Gs_valid, classes_valid, [1], list(range(len(classes_valid))))
# Model
gnn = graphnn(
N_x = NODE_FEATURE_DIM,
Dtype = Dtype,
N_embed = EMBED_DIM,
depth_embed = EMBED_DEPTH,
N_o = OUTPUT_DIM,
ITER_LEVEL = ITERATION_LEVEL,
lr = LEARNING_RATE,
device = DEVICE
)
gnn.init(LOAD_PATH, LOG_PATH)
auc0, fpr0, tpr0, thres0 = get_auc_epoch_batch(gnn, Gs_train, classes_train,
BATCH_SIZE)
gnn.say("Initial training auc = {0} @ {1}".format(auc0, datetime.now()))
print(auc0)
print(max((1-fpr0+tpr0)/2))
index = np.argmax((1-fpr0+tpr0)/2)
print("index:", index)
print("fpr", fpr0[index])
print("tpr", tpr0[index])
print(thres0[index])
auc1, fpr1, tpr1, thres1 = get_auc_epoch_batch(gnn, Gs_test, classes_test,
BATCH_SIZE)
gnn.say("Initial testing auc = {0} @ {1}".format(auc1, datetime.now()))
print(auc1)
print(max((1-fpr1+tpr1)/2))
index = np.argmax(1-fpr1+tpr1)
print("index:", index)
print("fpr", fpr1[index])
print("tpr", tpr1[index])
print(thres1[index])
auc2, fpr2, tpr2, thres2 = get_auc_epoch_batch(gnn, Gs_valid, classes_valid,
BATCH_SIZE)
gnn.say("Initial validation auc = {0} @ {1}".format(auc2, datetime.now()))
print(auc2)
print(max((1-fpr2+tpr2)/2))
index = np.argmax((1-fpr2+tpr2)/2)
print("index:", index)
print("fpr", fpr2[index])
print("tpr", tpr2[index])
print(thres2[index])
plt.figure()
plt.title('ROC CURVE')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.plot(fpr1,tpr1,color='b')
plt.plot(fpr1, 1-fpr1+tpr1, color='b')
plt.plot(fpr2, tpr2,color='r')
plt.plot(fpr2, 1-fpr2+tpr2, color='r')
# plt.plot([0, 1], [0, 1], color='m', linestyle='--')
plt.savefig('auc_depth5.png') | DeepSoftwareAnalytics/LibDB | main/torch/get_threshold.py | get_threshold.py | py | 5,724 | python | en | code | 31 | github-code | 6 |
31452710852 | # from typing_extensions import Self
class Dog:
species = "Canis familiaris"
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
miles = Dog("Miles", 4, "Jack Russell Terrier")
buddy = Dog("Buddy", 9, "Dachshund")
jack = Dog("Jack", 3, "Bulldog")
jim = Dog("Jim", 5, "Bulldog")
for Dog in (miles,buddy,jack,jim):
print(f"{Dog.name} is {Dog.age} years old {Dog.breed} from breed")
| hiral2011/Pythonwork | dog.py | dog.py | py | 459 | python | en | code | 0 | github-code | 6 |
9766345042 | # Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.
"""
Dashboard that shows user groups with percentages
and recommended books
"""
from dash import dcc, html
import plotly.express as px
import pandas as pd
from dash.exceptions import PreventUpdate
from dash.dependencies import Input, Output
import requests
import dash_bootstrap_components as dbc
from app import app
"""
Importacion de datos
"""
# Casteamos el pd.read_json a un DataFrame
"""
Creacion de labels para los dropdowns
"""
# Label: valor que se muestra en el dropdowns
# value: valor que tendra el dropdown despues de seleccionar
"""
HTML
"""
layout = html.Div(
children=[
html.H1(children="UAQUE: Pertenencia de los usuarios"),
html.Div(
dcc.Dropdown(
id="users_id_pertenencia_dropdown",
value="50052490d474975ef40a67220d0491571630eca6",
clearable=False,
)
),
dbc.Spinner(children=[
html.Div(
id="user_name",
children="""
""",
),
dcc.Graph(
id="dewey_graph",
),
html.Div(
children=[
html.Ul(id="book_list", children=[html.Li(i) for i in []]),
],
),
]),
]
)
"""
Callbacks
Input: lo que cambiar. El primer valor es el id del item que cambia en el HTML. El segundo valor es child del item que cambia.
Output: item que cambia en reaccion. Lo mismo que arriba
Funcion debajo del callback es lo que controla el cambio. Las entradas de la funcion es el segundo valor
del input y el retorno es valor que va a tener el segundo argumento del output.
"""
# Cuando cambia el valor de busqueda, cambian las opciones que preesnta el dropdown.
@app.callback(
Output("users_id_pertenencia_dropdown", "options"),
Input("users_id_pertenencia_dropdown", "search_value"),
)
def update_options(search_value):
if not search_value:
raise PreventUpdate
# carga solo 50 resultados (no puede cargar los 40,000)
smartuj_endpoint: str = "localhost:8000/api"
uso_biblioteca: str = "suj-e-004"
DashboardPertenenciaUpdateOptions: str = "DashboardPertenenciaUtilsUpdateOptions"
url_pertenencia_update_options: str = (
"http://"
+ smartuj_endpoint
+ "/"
+ uso_biblioteca
+ "/"
+ DashboardPertenenciaUpdateOptions
)
users_id = requests.get(
url=url_pertenencia_update_options, params={"search_value": search_value}
)
users_id = users_id.json()
return users_id
# Cuando cambia el valor del dropdown cambia el nombre de usuario del titulo
@app.callback(
Output("user_name", "children"), [Input("users_id_pertenencia_dropdown", "value")]
)
def update_table_title(user_name):
result = "\n", str(user_name), "\n"
return result
# Cuando cambia el valor del dropdown, cambia la lista de libros
@app.callback(
Output("book_list", "children"), [Input("users_id_pertenencia_dropdown", "value")]
)
def update_book_list(dropdown_value):
smartuj_endpoint: str = "localhost:8000/api"
uso_biblioteca: str = "suj-e-004"
DashboardPertenenciaUpdateBookList: str = "DashboardPertenenciaUtilsUpdateBookList"
url_pertenencia_update_book_list: str = (
"http://"
+ smartuj_endpoint
+ "/"
+ uso_biblioteca
+ "/"
+ DashboardPertenenciaUpdateBookList
)
book_table = requests.get(
url=url_pertenencia_update_book_list, params={"dropdown_value": dropdown_value}
)
book_table = pd.DataFrame.from_dict(book_table.json())
book_list: list = []
# Creamos la lista de listas, tal como se muestra en <li> de mozilla
for i in range(len(book_table)):
book_list.append(html.Li(book_table["Titulo"].values[i]))
nested_list = html.Ul(
children=[
html.Li("Llave: " + str(book_table["Llave"].values[i])),
html.Li("Dewey: " + str(book_table["DeweyUnidad"].values[i])),
]
)
book_list.append(nested_list)
return book_list
# Cuando cambia el valor del dropdown, cambia la grafica
@app.callback(
Output("dewey_graph", "figure"), [Input("users_id_pertenencia_dropdown", "value")]
)
def update_graph(dropdown_value):
smartuj_endpoint: str = "localhost:8000/api"
uso_biblioteca: str = "suj-e-004"
dashboardGruposUtil: str = "DashboardPertenencia"
# Agrupamiento crear perfiles grupales http://{{smartuj-endpoint}}/{{perfil-grupal}}/model
url_pertenencia: str = (
"http://" + smartuj_endpoint + "/" + uso_biblioteca + "/" + dashboardGruposUtil
)
selected_row = requests.get(
url=url_pertenencia, params={"dropdown_value": dropdown_value}
)
selected_row = selected_row.json()
fig = px.bar(selected_row, hover_data=["value"])
# Estilo para la hoverinfo
fig.update_traces(hovertemplate="<b>Pertenencia: %{y:.2f}%</b><extra></extra>")
# Titulo de axis x
fig.update_xaxes(type="category", title_text="Deweys")
# Titulo de tabla
fig.update_yaxes(title_text="Pertenencia (%)")
# quitar legenda
fig.update_layout(showlegend=False)
return fig
| Johan-Ortegon-1/uaque | Dashboard/apps/dashboard_pertenencia.py | dashboard_pertenencia.py | py | 5,360 | python | es | code | 0 | github-code | 6 |
44426747556 | from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import connect_nodes_bi, wait_until
class MagicBytes(BitcoinTestFramework):
def set_test_params(self):
self._magicbyte='0a0b0c0d'
self.num_nodes = 2
self._extra_args_same = [['-magicbytes={}'.format(self._magicbyte)]]*self.num_nodes
self._extra_args_diff = [[],['-magicbytes={}'.format(self._magicbyte)]]
self.extra_args = self._extra_args_same
def setup_network(self):
self.setup_nodes()
connect_nodes_bi(self.nodes,0,1)
def setup_nodes(self):
self.add_nodes(self.num_nodes, self.extra_args, timewait=900)
self.start_nodes()
def _print_connections(self):
for i in range(self.num_nodes):
print("Node {} connections: {}".format(i, self.nodes[i].getconnectioncount()))
def run_test(self):
self.log.info("Testing connections with the same magicbytes")
wait_until(lambda: self.nodes[0].getconnectioncount() == 2)
wait_until(lambda: self.nodes[1].getconnectioncount() == 2)
self.log.info("Testing connections with different magicbytes")
self.extra_args = self._extra_args_diff
self.stop_nodes()
self.nodes.clear()
self.setup_network()
assert(self.nodes[0].getconnectioncount() == 0)
assert(self.nodes[1].getconnectioncount() == 0)
if __name__ == '__main__':
MagicBytes().main()
| bitcoin-sv/bitcoin-sv | test/functional/bsv-magicbytes.py | bsv-magicbytes.py | py | 1,466 | python | en | code | 597 | github-code | 6 |
1848378529 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
import pyperclip
import time
def copy_input(driver, xpath, input) :
pyperclip.copy(input)
driver.find_element_by_xpath(xpath).click()
ActionChains(driver).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()
time.sleep(1)
def goSuntable() :
driver = webdriver.Chrome()
url = 'https://google.com'
driver.get(url)
driver.find_element_by_css_selector('.gLFyf.gsfi').send_keys('썬 테이블')
driver.find_element_by_css_selector('.gLFyf.gsfi').send_keys(Keys.ENTER)
driver.find_element_by_css_selector('.LC20lb.DKV0Md').click()
driver.find_element_by_xpath("//div[@class='nav sub-menu sub_menu_hide v-menu-type1 menu-vertical row-cnt-3 row-cnt-mobile-3']/ul/li[@data-code='m202004152c81c6f5f4a24']/a").send_keys(Keys.ENTER)
driver.quit()
def goKkamdung() :
driver = webdriver.Chrome()
url = 'https://www.naver.com'
driver.get(url)
time.sleep(1)
copy_input(driver, "//input[@id='query']", "63빌딩 돌상")
time.sleep(1)
driver.find_element_by_xpath("//input[@id='query']").send_keys(Keys.ENTER)
time.sleep(1)
driver.find_element_by_xpath("//a[@href='https://blog.naver.com/kongminsook66']").click()
time.sleep(1)
driver.quit()
for i in range(10) :
goKkamdung() | SLT-DJH/selenium-test | test.py | test.py | py | 1,484 | python | en | code | 0 | github-code | 6 |
261136007 | #Crie uma função que receba o nome e o sobrenome de uma pessoa e retorne os dois nomes
# concatenados (nome completo)
#Ex.: envio André e envio Santana e a função retorna André Santana
def concatenarNome(nome : str, sobrenome : str):
return nome + " " + sobrenome
def main():
name = input("Digite o seu nome: ")
surName = input("Digite o seu sobrenome: ")
nomeCompleto = concatenarNome(name, surName)
print("O nome completo é: " + nomeCompleto)
print("O nome completo é: {}".format(nomeCompleto))
if __name__ == "__main__":
main()
| ALMSantana/Tecnicas-de-Programacao | 2021_2/221/Lista4/ex5.py | ex5.py | py | 575 | python | pt | code | 8 | github-code | 6 |
20362021082 | from rest_framework.decorators import api_view
from rest_framework.response import Response
from account.models import User
from store.models import Product
from django.contrib.auth.decorators import login_required
from account.authentication import create_access_token, create_refresh_token, decode_access_token, decode_refresh_token, JWTAuthentication
from rest_framework.authentication import get_authorization_header
from rest_framework.views import APIView
from rest_framework.exceptions import AuthenticationFailed
from rest_framework import status
from .models import Order, OrderItem, DiscountCode
from account.serializers import UserSerializer
from .serializers import OrderSerializers, OrderItemSerializers, DiscountCodeSerializers
import base64
class DiscountCodeCreateAPIView(APIView):
def get(self, request):
sale_code = request.GET.get("sale_code", "")
if not sale_code:
return Response({"error": "Sale code is required."}, status=status.HTTP_400_BAD_REQUEST)
try:
discount_code = DiscountCode.objects.get(name_code=sale_code)
serializer = DiscountCodeSerializers(discount_code)
return Response(serializer.data)
except DiscountCode.DoesNotExist:
return Response({"error": "Discount code not found."}, status=status.HTTP_404_NOT_FOUND)
def post(self, request):
serializer = DiscountCodeSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_order_item(pro, order, quantity, price):
order_Item = OrderItem(pro, order, quantity, price)
order_Item.save()
return order_Item
class OrderCodeCreateAPIView(APIView):
def post(self, request):
data = request.data
userAddress_id = data['userAddress_id']
if data['discount_code']:
discount_code = data['discount_id']
note = data['note']
proList = data.getlist('ProList')
quantity = data['quantity']
order_status = data['order_status']
payment_method = data['payment_method']
total_price = data['total_price']
serializer = OrderSerializers(data=data)
if (serializer.is_valid()):
order = serializer.save()
for pro in proList:
create_order_item(pro, order, pro.quantity, pro.price)
# class OrderAPIView(APIView):
# def get(self, request):
# auth = get_authorization_header(request).split()
# if auth and len(auth) == 2:
# token = auth[1].decode('utf-8')
# id = decode_access_token(token)
# user = User.objects.filter(pk=id).first()
# try:
# cart = Cart.objects.get(user=user)
# serializer = CartSerializers(instance=cart)
# # get cart item in cart:
# except Cart.DoesNotExist:
# cart = Cart.objects.create(user=user)
# serializer = CartSerializers(instance=cart)
# print(cart.quantity)
# cartItems = CartItem.objects.filter(cart=cart)
# itemSerializer = CartItemSerializers(instance=cartItems, many=True)
# listP = []
# for PItem in cartItems:
# p_name = PItem.product.product_name
# p_slug = PItem.product.slug
# p_price = PItem.product.price
# p_image = PItem.product.image
# print(str(p_image))
# p_invetory = PItem.product.inventory
# product = {
# 'product_name': p_name,
# 'slug': p_slug,
# 'price': p_price,
# 'image': str(p_image),
# 'inventory': p_invetory,
# 'quantity': PItem.quantity
# }
# listP.append(product)
# cart = {
# 'cart': serializer.data,
# 'item_cart': itemSerializer.data,
# 'list_product': listP,
# }
# return Response({"cart_detail": cart})
# raise AuthenticationFailed('Unauthenticated!')
| MTrungNghia/Gundam_web | BackEnd/GundamMTN/Orders/views.py | views.py | py | 4,330 | python | en | code | 0 | github-code | 6 |
74222296187 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
import requests
# For storing png files in memory
import io
# For generating GIF
import imageio
###########################################################
########## Globals....
###########################################################
# Top value to use in scale, 0 = mean + 2 std devs
max_value = 0
# Bottom value to use in scale, should be zero
min_value = 0
# SANDAG API Link
sd_api = "https://opendata.arcgis.com/datasets/854d7e48e3dc451aa93b9daf82789089_0.geojson"
# Zipcode shape file link
zip_shape_full = "https://github.com/mulroony/State-zip-code-GeoJSON/raw/master/ca_california_zip_codes_geo.min.json"
# File to write gif to. Leave blank to just render inline
# Probably won't work in this script...
gif_path = "/tmp/SD_Covid_cases.gif"
#gif_path = ""
# Select ColorMap: https://matplotlib.org/3.2.1/tutorials/colors/colormaps.html
color_map = 'YlOrRd'
###########################################################
###########################################################
r = requests.get(sd_api)
rd = [ _r['properties'] for _r in r.json()['features'] ]
case_df = pd.DataFrame(rd)
# Cleanup, reduce mem
del [r, rd]
known_zips = list(case_df['ziptext'].unique())
print("Zipcodes in data: %s"%(len(known_zips)))
# Got API link from: https://sdgis-sandag.opendata.arcgis.com/datasets/covid-19-statistics-by-zip-code
r = requests.get(zip_shape_full)
rd = r.json()
zip_shape_known = {}
zip_shape_known['type'] = rd['type']
zip_shape_known['features'] = []
for i in rd['features']:
if i['properties']['ZCTA5CE10'] in known_zips:
zip_shape_known['features'].append(i)
print("Found %s matching zip codes in shape file"%(len(zip_shape_known['features'])))
del [r, rd]
gdf = gpd.GeoDataFrame.from_features(zip_shape_known)
gdf.rename(columns={'ZCTA5CE10': 'zipcode'}, inplace=True)
gdf.set_index('zipcode',inplace=True)
# Drop time from date, not useful
case_df['date'] = case_df['updatedate'].apply(lambda x: x.split(" ")[0])
# Drop unused fields
case_df.drop(inplace=True, columns=['FID',
'zipcode_zip',
'created_date',
'updatedate',
'created_date',
'created_user',
'last_edited_date',
'last_edited_user',
'globalid'])
# Missing data becomes zeros
case_df.fillna(0, inplace=True)
# Rename column
case_df.rename(columns={'ziptext': 'zipcode'}, inplace=True)
# Drop duplicates, have seen some
case_df.drop_duplicates(subset=['zipcode','date'], inplace=True)
# Ugly, but creates table I want
case_df = case_df.groupby(['zipcode', 'date']).sum().unstack().fillna(0)
# End up with nested column name, remove it
case_df.columns = case_df.columns.droplevel()
# Create super list of all case values so we can get stats if we are going to use it
if max_value == 0:
_tmp_case_list = []
# Not necessary, but can't hurt
dates = sorted(case_df.columns.values)
# subtract tomorrow from today, and set that as the value for today. repeat, skipping last day...
for i in range(len(dates)-1):
today = dates[i]
tomorrow = dates[i+1]
case_df[today] = case_df[tomorrow] - case_df[today]
# #Uncomment to find all negative values. Happens due to adjusting the numbers, we handle it
# #Good to do though
# _tmp_df = case_df[today].apply(lambda x: x if x < -1 else None).dropna()
# if _tmp_df.values.size > 0:
# print("%s"%(today))
# print(_tmp_df)
if max_value == 0:
_tmp_case_list += list(case_df[today].values)
if max_value == 0:
_tmp_case_df = pd.DataFrame(_tmp_case_list)
max_value = int(_tmp_case_df.mean()[0] + (2 * _tmp_case_df.std()[0]))
print("max_value = %s"%(max_value))
# Limit values based on max / min
for i in dates[:-1]:
case_df[i] = case_df[i].apply(lambda x: min_value if x < min_value else x)
case_df[i] = case_df[i].apply(lambda x: max_value if x > max_value else x)
# Remove last day
case_df.drop(inplace=True, columns=[case_df.columns[-1]])
# ## Merge shape file with zipcodes gdf and case_df, create case_gdf
case_gdf = gdf.merge(case_df, left_on='zipcode', right_on='zipcode')
output_files = []
for idx in dates[:-1]:
# Create inmemory file
output_files.append(io.BytesIO())
fig = case_gdf.plot(cmap=color_map,
column=idx,
linewidth=0.8,
edgecolor='0.8',
vmax=int(max_value),
vmin=min_value,
legend=True,
figsize=(14,8))
fig.axis('off')
fig.annotate("Daily Cases COVID-19 : %s - %s"%(dates[0],dates[-2]),
xy=(.1, .9), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=20)
fig.annotate("""P. Mulrooney <mulroony@gmail.com>
* Upper case count limited to mean + 2 std devs
* Missing replaced with zeros
* Decreases between days set to zero
* https://sdgis-sandag.opendata.arcgis.com/datasets/covid-19-statistics-by-zip-code""",
xy=(.5, .1), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=8)
fig.annotate(idx,
xy=(0.1, .1), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=20)
fig.annotate(idx,
xy=(0.1, .1), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=20)
chart = fig.get_figure()
chart.savefig(output_files[-1], dpi=150)
plt.close('all')
output_files[-1].seek(0)
print("Generated %s in memory PNG files\n"%(len(output_files)))
images = []
for output_file in output_files:
images.append(imageio.imread(output_file))
if not gif_path:
gif_path = io.BytesIO()
imageio.mimsave(gif_path, images, format="gif", duration=0.75, loop=1)
| mulroony/SDCovidGIFMap | CovidMapFullMinimal.py | CovidMapFullMinimal.py | py | 6,244 | python | en | code | 0 | github-code | 6 |
14950903206 | # author: detoX
import glob
import numpy as np
import torch
import nibabel as nib
from PIL import Image
import nii_dataset
def main():
train_path = glob.glob("D:\\xuexi\\post-graduate\\py_projects\\ResNet-PET\\datasets\\Brain-PET\\Train\\*\\*")
test_path = glob.glob("D:\\xuexi\\post-graduate\\py_projects\\ResNet-PET\\datasets\\Brain-PET\\Test\\*")
count = 0
for path in train_path:
img = nib.load(path)
img = img.dataobj[:, :, :, 0]
idx = np.random.choice(range(img.shape[-1]), 50)
img = img[:, :, idx]
print(img.shape)
slice_img = img[:, :, 3]
# 由于原数据并不是图片,需要将图片归一化到[0, 1]区间,然后再放大到[0, 255]区间,因为灰度图片的亮度区间是0-255
slice_img = (slice_img / slice_img.max() * 255)
slice_img = Image.fromarray(slice_img)
if img.shape[0] != 128:
Image._show(slice_img)
else:
if count < 10:
Image._show(slice_img)
count += 1
# idx = np.random.choice(range(img.shape[-1]), 50)
# # idx.sort()
# img = img[:, :, idx]
# img = img.astype(np.float32)
def display_single_nii():
train_path = glob.glob("D:\\xuexi\\post-graduate\\py_projects\\ResNet-PET\\datasets\\Brain-PET\\Train\\*\\*")
test_path = glob.glob("D:\\xuexi\\post-graduate\\py_projects\\ResNet-PET\\datasets\\Brain-PET\\Test\\*")
for path in train_path:
img = nib.load(path)
img = img.dataobj[:, :, :, 0]
if img.shape[2] == 47:
# idx = np.random.choice(range(img.shape[-1]), 50)
# img = img[:, :, idx]
for s in range(47):
slice_img = img[:, :, s]
slice_img = (slice_img / slice_img.max() * 255).astype('uint8')
slice_img = Image.fromarray(slice_img)
# slice_img.show()
slice_img.save("./slice_imgs/nii_50/slice_{}.png".format(s))
break
# for i in range(50):
# slice_img = img[:, :, i]
# slice_img = (slice_img / slice_img.max() * 255)
# slice_img = Image.fromarray(slice_img)
# slice_img.show()
if __name__ == '__main__':
# main()
display_single_nii()
| Rah1m2/ResNet-PET | display_nii.py | display_nii.py | py | 2,266 | python | en | code | 0 | github-code | 6 |
34391533201 | f = open("命运.txt", "r", encoding="utf-8")
txt = f.read()
f.close()
d = {}
#sym = ",。、?:‘’”“!"
#for i in sym:
# if i in txt:
# txt = txt.replace(i, '')
txt = txt.replace("\n", "")
for i in txt:
d[i] = d.get(i, 0) + 1
ls = list(d.items())
ls.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
print("{}".format(ls[i][0]),end="") | Mr-Liu-CUG/python-NCRE2 | 1命运三问-问题2.py | 1命运三问-问题2.py | py | 389 | python | en | code | 1 | github-code | 6 |
12050806024 | """Setup the tilemap and the camera"""
import pygame as pg
from settings import TILESIZE, MAPSIZE, VIEWSIZE
from tile import Tile
class Camera():
"""A camera like"""
def __init__(self, width, height):
self.camera = pg.Rect(0, 0, width, height)
self.width = width
self.height = height
self.x = 0
self.y = 0
def apply(self, rect):
"""Update the pos of a rect
Args:
rect (Rect): the rect to move
Returns:
Rect
"""
return rect.move(self.camera.topleft)
def update(self):
"""Used to move the camera"""
keys = pg.key.get_pressed()
if keys[pg.K_i]:
self.y += TILESIZE
if keys[pg.K_k]:
self.y -= TILESIZE
if keys[pg.K_j]:
self.x += TILESIZE
if keys[pg.K_l]:
self.x -= TILESIZE
self.x = min(self.x, 0)
self.y = min(self.y, 0)
self.x = max(self.x, (VIEWSIZE - MAPSIZE) * TILESIZE)
self.y = max(self.y, (VIEWSIZE - MAPSIZE) * TILESIZE)
self.camera = pg.Rect(self.x, self.y, self.width, self.height)
def get_x(self):
"""Get the number of tile moved in x
Returns:
int
"""
return self.x // TILESIZE
def get_y(self):
"""Get the number of tile moved in y
Returns:
int
"""
return self.y // TILESIZE
| Barbapapazes/dungeons-dragons | map_editor/tilemap.py | tilemap.py | py | 1,448 | python | en | code | 1 | github-code | 6 |
724197866 |
from time import time
from flask import render_template, redirect, url_for, flash, make_response, current_app, request, abort
from flask.json import jsonify
from flask.ext.login import login_required, current_user
from etherpad_lite import EtherpadLiteClient
from . import main
from .forms import UserDefaultRoom
from .. import db, avatars, generator
from ..models import User, Room, RoomAuthorization, RoomPermissions, Widget, EventTypes, FileStorage
def get_available_rooms():
pass
@main.route('/')
def index():
return redirect(url_for('.home'))
@main.route('/home')
def home():
if not current_user.is_authenticated():
return redirect(url_for('auth.login'))
if current_user.guest:
return redirect(url_for('auth.logout'))
rs = Room.query.order_by('componentId').all()
form = UserDefaultRoom()
rc = [('0', 'None')]
rooms = []
my_rooms = []
for room in rs:
if room.ownerId == current_user.id:
my_rooms += [room]
rc += [(str(room.id), room.name)]
elif room.get_permissions(current_user):
rooms += [room]
rc += [(str(room.id), room.name)]
form.selectRoom.choices = rc
form.selectRoom.data = str(current_user.defaultRoomId)
if current_app.config['IA_ENABLED']:
return render_template('home_ia.html', my_rooms=my_rooms, rooms=rooms, User=User, form=form, avatar_url=avatar_url(current_user), current_user=current_user, current_app=current_app)
else:
return render_template('home.html', my_rooms=my_rooms, rooms=rooms, User=User, form=form, avatar_url=avatar_url(current_user), current_user=current_user, current_app=current_app)
@main.route("/set/room", methods=['POST'])
@login_required
def set_room():
form = UserDefaultRoom()
rs = Room.query.order_by('componentId').all()
rc = [('0', 'None')]
for room in rs:
if room.ownerId == current_user.id:
rc += [(str(room.id), room.name)]
elif room.get_permissions(current_user):
rc += [(str(room.id), room.name)]
form.selectRoom.choices = rc
if form.validate_on_submit():
if form.selectRoom.data == '0':
current_user.defaultRoomId = None
else:
current_user.defaultRoomId = form.selectRoom.data
db.session.commit()
return redirect(url_for('.home'))
else:
for form_error in form.errors:
for field_error in form[form_error].errors:
flash(form[form_error].label.text+" - "+field_error, 'error')
return redirect(url_for('.home'))
@main.route('/lobby')
def lobby():
if not current_user.is_authenticated():
return redirect(url_for('auth.login'))
if current_user.guest:
return redirect(url_for('auth.logout'))
rs = Room.query.all()
rooms = []
for room in rs:
if get_room_permissions(room, current_user):
rooms += [room]
return render_template('lobby.html', rooms=rooms, User=User)
@main.route('/room/<roomId>')
def room(roomId):
room = Room.query.filter_by(id=roomId).first()
if not current_user.is_authenticated():
if room.guest_permission():
return redirect(url_for('auth.guest_user', roomId=roomId))
return redirect(url_for('auth.login', next=url_for('.room', roomId=1)))
cl = room.events.filter_by(type=EventTypes.ROOM_CHAT).order_by('datetime').limit(20)
return render_template(room.component.template, room=room, chat=cl, current_user=current_user, current_app=current_app)
@login_required
@main.route('/upload_avatar', methods=['POST'])
def upload_avatar():
if 'avatar' in request.files:
filename = avatars.save(request.files['avatar'])
url = avatars.url(filename)
file = FileStorage(type='avatar', filename=current_user.email, url=url)
db.session.add(file)
db.session.commit()
return redirect(url_for('.home'))
def avatar_url(user):
file = FileStorage.query.filter_by(type='avatar', filename=current_user.email).first()
if file:
return file.url
else:
return url_for('.identicon', user_id=user.id)
@login_required
@main.route('/avatar/<user_id>')
def identicon(user_id):
user = User.query.filter_by(id=user_id).first()
identicon = generator.generate(user.email, 100, 100, output_format='png')
response = make_response(identicon)
response.headers["Content-Type"] = "image/png"
response.headers["Cache-Control"] = "public, max-age=43200"
return response
| compeit-open-source/dashboard | app/main/views.py | views.py | py | 4,544 | python | en | code | 1 | github-code | 6 |
43248987614 | import os
import itertools
import scipy.io
import scipy.stats as stt
import numpy as np
import matplotlib.pyplot as plt
from mou_model import MOU
_RES_DIR = 'model_parameter/'
_I_REST_RUN = 0
_I_NBACK_RUN = 1
_I_NO_TIMESHIFT = 0
_I_ONE_TIMESHIFT = 1
_SUBJECT_AXIS = 0
plt.close('all')
## Create a local folder to store results.
if not os.path.exists(_RES_DIR):
print('created directory:', _RES_DIR)
os.makedirs(_RES_DIR)
## Read in data and define constants.
fMRI_data_and_labels = scipy.io.loadmat('data/DATA_TASK_3DMOV_HP_CSF_WD.mat')
regionalized_preprocessed_fMRI_data = fMRI_data_and_labels['TASKEC'][0][0]
roi_labels = fMRI_data_and_labels['ROIlbls'][0]
rest_run_data = regionalized_preprocessed_fMRI_data['Rest']
n_back_run_data = regionalized_preprocessed_fMRI_data['nBack']
flanker_run_data = regionalized_preprocessed_fMRI_data['Flanker']
m_rotation_run_data = regionalized_preprocessed_fMRI_data['mRotation']
odd_man_out_run_data = regionalized_preprocessed_fMRI_data['OddManOut']
n_subjects = rest_run_data.shape[2]
n_runs = len(fMRI_data_and_labels['TASKEC'][0][0])
n_rois = rest_run_data.shape[1]
n_ts_samples = rest_run_data.shape[0]
# Structure data to match the format used at
# https://github.com/mb-BCA/notebooks_review2019/blob/master/1_MOUEC_Estimation.ipynb
# to enhance comparability.
filtered_ts_emp = np.zeros([n_subjects, n_runs, n_rois, n_ts_samples])
run = list(regionalized_preprocessed_fMRI_data.dtype.fields.keys())
for k in range(len(run)):
filtered_ts_emp[:, k, :, :] = np.transpose(
regionalized_preprocessed_fMRI_data[run[k]], (2, 1, 0))
## Calculate functional connectivity (BOLD covariances) [Q0 und Q1].
# time_shift = np.arange(4, dtype=float) # for autocovariance plots
time_shift = np.arange(2, dtype=float)
n_shifts = len(time_shift)
FC_emp = np.zeros([n_subjects, n_runs, n_shifts, n_rois, n_rois])
n_ts_span = n_ts_samples - n_shifts + 1
for i_subject in range(n_subjects):
for i_run in range(n_runs):
# Center the time series (around zero).
filtered_ts_emp[i_subject, i_run, :, :] -= \
np.outer(filtered_ts_emp[i_subject, i_run, :, :].mean(1),
np.ones([n_ts_samples]))
# Calculate covariances with various time shifts.
for i_shift in range(n_shifts):
FC_emp[i_subject, i_run, i_shift, :, :] = \
np.tensordot(filtered_ts_emp[i_subject, i_run, :,
0:n_ts_span],
filtered_ts_emp[i_subject, i_run, :,
i_shift:n_ts_span+i_shift],
axes=(1, 1)) / float(n_ts_span - 1)
rescale_FC_factor = (0.5 / FC_emp[:, _I_REST_RUN, _I_NO_TIMESHIFT, :,
:].diagonal(axis1=1, axis2=2).mean())
FC_emp *= rescale_FC_factor
# filtered_ts_emp /= np.sqrt(0.135) # Rescale to get the same order of magnitude for locale variability as in paper.
print('most of the FC values should be between 0 and 1')
print('mean FC0 value:', FC_emp[:, :, _I_NO_TIMESHIFT, :, :].mean(),
FC_emp.mean())
print('max FC0 value:', FC_emp[:, :, _I_NO_TIMESHIFT, :, :].max())
print('mean BOLD variance (diagonal of each FC0 matrix):',
FC_emp[:, :, _I_NO_TIMESHIFT, :, :].diagonal(axis1=2, axis2=3).mean())
print('rescaleFactor: ' + str(rescale_FC_factor))
# Show distibution of FC0 values.
plt.figure()
plt.hist(FC_emp[:, :, _I_NO_TIMESHIFT, :, :].flatten(),
bins=np.linspace(-1, 5, 30))
plt.xlabel('FC0 value', fontsize=14)
plt.ylabel('matrix element count', fontsize=14)
plt.title('distribution of FC0 values')
# Show FC0 averaged over subjects first run (rest).
plt.figure()
FC_avg_over_subj = FC_emp[:, _I_REST_RUN,
_I_NO_TIMESHIFT, :, :].mean(axis=_SUBJECT_AXIS)
plt.imshow(FC_avg_over_subj, origin='lower', cmap='Blues', vmax=1, vmin=0)
plt.colorbar()
plt.xlabel('target ROI', fontsize=14)
plt.ylabel('source ROI', fontsize=14)
plt.title('FC0 (functional connectivity with no time lag)')
# Show FC1 averaged over subjects first run (rest).
plt.figure()
FC_avg_over_subj = FC_emp[:, _I_REST_RUN,
_I_ONE_TIMESHIFT, :, :].mean(axis=_SUBJECT_AXIS)
plt.imshow(FC_avg_over_subj, origin='lower', cmap='Blues', vmax=1, vmin=0)
plt.colorbar()
plt.xlabel('target ROI', fontsize=14)
plt.ylabel('source ROI', fontsize=14)
plt.title('FC1 (functional connectivity with time lag 1TR)')
# Show the autocovariance for the first run (rest).
ac = FC_emp.diagonal(axis1=3, axis2=4)
plt.figure()
ac_avg_over_subj = np.log(np.maximum(ac[:, _I_REST_RUN, :, :].
mean(axis=_SUBJECT_AXIS), np.exp(-4.0)))
plt.plot(range(n_shifts), ac_avg_over_subj)
plt.xlabel('time lag', fontsize=14)
plt.ylabel('log autocovariance', fontsize=14)
plt.title('rest', fontsize=16)
plt.ylim((-3, 0))
plt.xlim((0, 3))
# Show the autocovariance for the 2nd run (nBack).
plt.figure()
ac_avg_over_subj = np.log(np.maximum(ac[:, _I_NBACK_RUN, :, :].
mean(axis=_SUBJECT_AXIS), np.exp(-3.1)))
plt.plot(range(n_shifts), ac_avg_over_subj)
plt.xlabel('time lag', fontsize=14)
plt.ylabel('log autocovariance', fontsize=14)
plt.title('nBack', fontsize=16)
plt.ylim((-3, 0))
plt.xlim((0, 3))
## Include structural connectivity.
# Load the binary structural connectivity matrix.
mask_EC = np.array(scipy.io.loadmat('data/BINARY_EC_MASK.mat')
['grouped_umcu50_60percent'], dtype=bool)
# Enforce hermispheric connections.
for i in range(int(n_rois/2)):
mask_EC[i, int(n_rois/2)+i] = True
mask_EC[int(n_rois/2)+i, i] = True
# Visualise the structural connectivity mask.
plt.figure()
plt.imshow(mask_EC, origin='lower')
plt.xlabel('target ROI', fontsize=14)
plt.ylabel('source ROI', fontsize=14)
plt.title('Mask for existing connections', fontsize=12)
## Calculate EC-matrix.
# Construct diagonal mask for input noise matrix
# (here, no input cross-correlation).
mask_Sigma = np.eye(n_rois, dtype=bool)
# Run the model optimization.
# Initialize the source arrays.
# Jacobian (off-diagonal elements = EC)
J_mod = np.zeros([n_subjects, n_runs, n_rois, n_rois])
# Local variance (input covariance matrix, chosen to be diagonal)
Sigma_mod = np.zeros([n_subjects, n_runs, n_rois, n_rois])
# Model error
dist_mod = np.zeros([n_subjects, n_runs])
# Approximation of variance about the fitted data (FC covariance matrices)
R2_mod = np.zeros([n_subjects, n_runs])
# Between-region EC matrix
C_mod = np.zeros([n_subjects, n_runs, n_rois, n_rois])
mou_model = MOU()
for i_subject in range(n_subjects):
for i_run in range(n_runs):
# Run the estimation of model parameters, for all sessions.
# All parameters/restrictions not explicitly passed, have the
# correct defaults in fit_LO@MOU.
mou_model.fit(filtered_ts_emp[i_subject, i_run, :, :].T,
mask_Sigma=mask_Sigma, mask_C=mask_EC)
# Organize the optimization results into arrays.
# Extract Jacobian of the model.
J_mod[i_subject, i_run, :, :] = mou_model.J
# Extract noise (auto-)covariance matrix.
Sigma_mod[i_subject, i_run, :, :] = mou_model.Sigma
# Extract the matrix distance between the empirical objective
# covariances and their model counterparts
# (normalized for each objective matrix).
dist_mod[i_subject, i_run] = mou_model.d_fit['distance']
# The squared Pearson correlation is taken as an approximation
# of the variance.
R2_mod[i_subject, i_run] = mou_model.d_fit['correlation']**2
# The between-region EC matrix of the model
C_mod[i_subject, i_run, :, :] = mou_model.get_C()
print('sub / run:', i_subject, i_run, ';\t model error, R2:',
dist_mod[i_subject, i_run], R2_mod[i_subject, i_run])
# Store the results in files.
np.save(_RES_DIR + 'FC_emp.npy',
FC_emp) # Empirical spatiotemporal FC
np.save(_RES_DIR + 'mask_EC.npy',
mask_EC) # Mask of optimized connections
np.save(_RES_DIR + 'mask_Sigma.npy',
mask_Sigma) # Mask of optimized Sigma elements
np.save(_RES_DIR + 'Sigma_mod.npy',
Sigma_mod) # Estimated Sigma matrices
np.save(_RES_DIR + 'dist_mod.npy',
dist_mod) # Model error
np.save(_RES_DIR + 'J_mod.npy',
J_mod) # Estimated Jacobian, EC + inverse time const. on diag.
print('\nFinished.')
# Plot C-matrix for resting state data.
plt.figure()
plt.imshow(C_mod[:, _I_REST_RUN, :, :].mean(axis=_SUBJECT_AXIS),
origin='lower', cmap='Reds')
plt.colorbar()
plt.xlabel('target ROI', fontsize=14)
plt.ylabel('source ROI', fontsize=14)
plt.title('effective connectivity C_{ij}')
plt.show()
## Calculate local variability for rich club and periphery.
mean_rc_var = np.zeros([n_runs])
mean_periph_var = np.zeros([n_runs])
conf_int_rc = np.zeros([n_runs, 2])
conf_int_periph = np.zeros([n_runs, 2])
# Create a 1D-mask for rich club regions.
mask_rc = np.zeros(n_rois, dtype=bool)
indexes_rich_club = [23, 26, 27, 57, 60, 61]
mask_rc[indexes_rich_club] = True
print('rich club regions: '
+ str(np.concatenate(roi_labels[indexes_rich_club]).tolist()))
for i_run in range(n_runs):
local_var = Sigma_mod[:, i_run, :, :].diagonal(axis1=1, axis2=2)
rc_var = local_var[:, mask_rc].mean(axis=1)
periph_var = local_var[:, ~mask_rc].mean(axis=1)
mean_rc_var[i_run] = rc_var.mean()
mean_periph_var[i_run] = periph_var.mean()
sigma_rc_var = rc_var.std(ddof=1)
sigma_periph_var = periph_var.std(ddof=1)
conf_int_rc[i_run, :] = stt.norm.interval(0.95,
loc=mean_rc_var[i_run],
scale=sigma_rc_var)
conf_int_periph[i_run, :] = stt.norm.interval(0.95,
loc=mean_periph_var[i_run],
scale=sigma_periph_var)
print('Mittel der lokalen Variabilität (rich club): ' + str(mean_rc_var))
print('Mittel der lokalen Variabilität (periphery): ' + str(mean_periph_var))
print('95% Konfidenz Interval (rich cluc): ' + str(conf_int_rc))
print('95% Konfidenz Interval (periphery): ' + str(conf_int_periph))
## Calculate the input-output ratio.
# Create a 2D-mask for rich club regions.
mask_inter_rc = np.zeros([n_rois, n_rois], dtype=bool)
# The entries on the diagonal of C are 0 anyway, so that they can be
# ignored when it comes to the mask:
# mask_inter_rc[indexes_rich_club, indexes_rich_club] = True
rc_ind_combin = np.array(list(itertools.permutations(indexes_rich_club, 2))).T
mask_inter_rc[rc_ind_combin[0], rc_ind_combin[1]] = True
mean_rc_io = np.zeros([n_runs])
mean_periph_io = np.zeros([n_runs])
for i_run in range(n_runs):
# Examine input-output ratio ignoring inter-rich-club connections.
no_rc_connections_C = C_mod[:, i_run, :, :]
no_rc_connections_C[:, mask_inter_rc] = 0
roi_input = no_rc_connections_C[:, :, :].sum(axis=1)
roi_output = no_rc_connections_C[:, :, :].sum(axis=2)
io_rc = (roi_input[:, mask_rc].sum(axis=1) /
roi_output[:, mask_rc].sum(axis=1))
io_periph = (roi_input[:, ~mask_rc].sum(axis=1) /
roi_output[:, ~mask_rc].sum(axis=1))
mean_rc_io[i_run] = io_rc.mean()
mean_periph_io[i_run] = io_periph.mean()
sigma_io_rc = io_rc.std(ddof=1)
sigma_io_periph = io_periph.std(ddof=1)
conf_int_rc[i_run, :] = stt.norm.interval(0.95,
loc=mean_rc_io[i_run],
scale=sigma_io_rc)
conf_int_periph[i_run, :] = stt.norm.interval(0.95,
loc=mean_periph_io[i_run],
scale=sigma_io_periph)
print('input-output ratio rich club: ', str(mean_rc_io))
print('input-output ratio periphery: ', str(mean_periph_io))
print('95% Konfidenz Interval (rich cluc): ' + str(conf_int_rc))
print('95% Konfidenz Interval (periphery): ' + str(conf_int_periph))
| bjoernkoehn21/Reproduce-results-from-Senden-paper | mou_ec_estimation.py | mou_ec_estimation.py | py | 12,115 | python | en | code | 0 | github-code | 6 |
26625562386 | """A Mailman newsletter subscription interface.
To use this plugin, enable the newsletter module and set the newsletter module and name settings
in the admin settings page.
"""
from django.utils.translation import ugettext as _
from Mailman import MailList, Errors
from models import Subscription
from livesettings import config_value
import logging
import sys
log = logging.getLogger('newsletter.mailman')
class UserDesc: pass
def is_subscribed(contact):
return Subscription.email_is_subscribed(contact.email)
def update_contact(contact, subscribe, attributes={}):
email = contact.email
current = Subscription.email_is_subscribed(email)
attributesChanged = False
sub = None
if attributes:
sub, created = Subscription.objects.get_or_create(email=email)
if created:
attributesChanged = True
else:
oldAttr = [(a.name,a.value) for a in sub.attributes.all()]
oldAttr.sort()
sub.update_attributes(attributes)
newAttr = [(a.name,a.value) for a in sub.attributes.all()]
newAttr.sort()
if not created:
attributesChanged = oldAttr != newAttr
if current == subscribe:
if subscribe:
if attributesChanged:
result = _("Updated subscription for %(email)s.")
else:
result = _("Already subscribed %(email)s.")
else:
result = _("Already removed %(email)s.")
else:
if not sub:
sub, created = Subscription.objects.get_or_create(email=email)
sub.subscribed = subscribe
sub.save()
if subscribe:
mailman_add(contact)
result = _("Subscribed: %(email)s")
else:
mailman_remove(contact)
result = _("Unsubscribed: %(email)s")
return result % { 'email' : email }
def mailman_add(contact, listname=None, send_welcome_msg=None, admin_notify=None):
"""Add a Satchmo contact to a mailman mailing list.
Parameters:
- `Contact`: A Satchmo Contact
- `listname`: the Mailman listname, defaulting to whatever you have set in settings.NEWSLETTER_NAME
- `send_welcome_msg`: True or False, defaulting to the list default
- `admin_notify`: True of False, defaulting to the list default
"""
mm, listname = _get_maillist(listname)
print >> sys.stderr, 'mailman adding %s to %s' % (contact.email, listname)
if send_welcome_msg is None:
send_welcome_msg = mm.send_welcome_msg
userdesc = UserDesc()
userdesc.fullname = contact.full_name
userdesc.address = contact.email
userdesc.digest = False
if mm.isMember(contact.email):
print >> sys.stderr, _('Already Subscribed: %s' % contact.email)
else:
try:
try:
mm.Lock()
mm.ApprovedAddMember(userdesc, send_welcome_msg, admin_notify)
mm.Save()
print >> sys.stderr, _('Subscribed: %(email)s') % { 'email' : contact.email }
except Errors.MMAlreadyAMember:
print >> sys.stderr, _('Already a member: %(email)s') % { 'email' : contact.email }
except Errors.MMBadEmailError:
if userdesc.address == '':
print >> sys.stderr, _('Bad/Invalid email address: blank line')
else:
print >> sys.stderr, _('Bad/Invalid email address: %(email)s') % { 'email' : contact.email }
except Errors.MMHostileAddress:
print >> sys.stderr, _('Hostile address (illegal characters): %(email)s') % { 'email' : contact.email }
finally:
mm.Unlock()
def mailman_remove(contact, listname=None, userack=None, admin_notify=None):
"""Remove a Satchmo contact from a Mailman mailing list
Parameters:
- `contact`: A Satchmo contact
- `listname`: the Mailman listname, defaulting to whatever you have set in settings.NEWSLETTER_NAME
- `userack`: True or False, whether to notify the user, defaulting to the list default
- `admin_notify`: True or False, defaulting to the list default
"""
mm, listname = _get_maillist(listname)
print >> sys.stderr, 'mailman removing %s from %s' % (contact.email, listname)
if mm.isMember(contact.email):
try:
mm.Lock()
mm.ApprovedDeleteMember(contact.email, 'satchmo_ext.newsletter', admin_notify, userack)
mm.Save()
finally:
mm.Unlock()
def _get_maillist(listname):
try:
if not listname:
listname = config_value('NEWSLETTER', 'NEWSLETTER_NAME')
if listname == "":
log.warn("NEWSLETTER_NAME not set in store settings")
raise NameError('No NEWSLETTER_NAME in settings')
return MailList.MailList(listname, lock=0), listname
except Errors.MMUnknownListError:
print >> sys.stderr, "Can't find the MailMan newsletter: %s" % listname
raise NameError('No such newsletter, "%s"' % listname)
| dokterbob/satchmo | satchmo/apps/satchmo_ext/newsletter/mailman.py | mailman.py | py | 5,119 | python | en | code | 30 | github-code | 6 |
35852151981 | #SERVO MOTOR
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
servo1 = GPIO.PWM(12, 50)
servo1.start(0)
print("2 seconds")
time.sleep(2)
print("rotating 180")
duty = 12
time.sleep(2)
print("turn back 90")
servo1.ChangeDutyCycle(7)
time.sleep(2)
print("turn back to 0")
servo1.ChangeDutyCycle(2)
time.sleep(0.5)
servo1.ChangeDutyCycle(0)
servo1.stop
GPIO.cleanup()
print("Done")
| aceyed/Automated-Pet-Feeder | servoMotorTest.py | servoMotorTest.py | py | 422 | python | en | code | 0 | github-code | 6 |
41767569580 | import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class LinearDynamicSystem:
def __init__(self, gamma, sigma):
self.gamma = gamma
self.sigma = sigma
self.log_p_x_history = []
self.pred_mu_history = []
self.mu_history = []
self.pred_mu_history = []
self.p_history = []
self.pred_p_history = []
def fit(self, observations, mu, p):
self._filter(observations, mu, p)
smoothed_mu_list = self._smoothing()
plt.plot(observations, label="Observation")
plt.plot(self.pred_mu_history, label="Predicted Latent Variable")
plt.plot(self.mu_history, label="Updated Latent Variable")
plt.plot(smoothed_mu_list, label="Smoothed Latent Variable")
plt.legend()
plt.show()
def _filter(self, observations, mu, p):
_mu, _p = mu, p
for i, obs in enumerate(observations):
pred_mu, pred_p, log_p_x = self._predict(_mu, _p, obs)
self.log_p_x_history.append(log_p_x)
_mu, _p = self._update(obs, pred_mu, pred_p)
self.pred_mu_history.append(pred_mu)
self.pred_p_history.append(pred_p)
self.mu_history.append(_mu)
self.p_history.append(_p)
print("Answer {}: ".format(i+1))
if i > 0:
print("predicted p.d.f. of latent variable: mu = {:.3f}, sigma = {:.3f}, joint_prob. = {:.3f}"
.format(pred_mu, pred_p, np.sum(self.log_p_x_history)))
print("log-scaled likelihood = {:.3f}, "
"updated p.d.f. of latent value: mu = {:.3f}, sigma = {:.3f}"
.format(log_p_x, _mu, _p))
def _predict(self, mu, p, obs):
pred_mu = mu
pred_p = p + self.gamma
log_p_x = norm.logpdf(x=obs, loc=pred_mu, scale=(pred_p + self.sigma))
return pred_mu, pred_p, log_p_x
def _kalman_gain(self, p, s):
return p / (p + s)
def _update(self, obs, mu, p):
k = self._kalman_gain(p, self.sigma)
new_mu = mu + k * (obs - mu)
new_p = (1 - k) * p
return new_mu, new_p
def _smoothing(self):
smoothed_mu_list = []
smoothed_p_list = []
last_smoothed_mu = self.mu_history[-1]
last_smoothed_p = self.p_history[-1]
smoothed_mu_list.append(last_smoothed_mu)
smoothed_p_list.append(last_smoothed_p)
for i in reversed(range(len(self.mu_history)-1)):
current_mu = self.mu_history[i]
pred_mu = self.pred_mu_history[i+1]
current_p = self.p_history[i]
pred_p = self.pred_p_history[i+1]
j = current_p / pred_p
last_smoothed_mu = current_mu + j * (last_smoothed_mu - pred_mu)
last_smoothed_p = current_p + j ** 2 * (last_smoothed_p - pred_p)
smoothed_mu_list.insert(0, last_smoothed_mu)
smoothed_p_list.insert(0, last_smoothed_p)
for mu, p in zip(smoothed_mu_list, smoothed_p_list):
print("smoothed μ = {:.3f}, smoothed P = {:.3f}".format(mu, p))
return smoothed_mu_list
def generate_observation(b):
return 10 * b + 20
STUDENT_ID = "2011039"
print("Your ID is {}".format(STUDENT_ID))
b_1, b_2, b_3, b_4 = [int(sid) for sid in STUDENT_ID[-4:]]
print("b_1 = {}, b_2 = {}, b_3 = {}, b_4 = {}".format(b_1, b_2, b_3, b_4))
INPUT_X = np.array([generate_observation(b) for b in [b_1, b_2, b_3, b_4]])
INIT_P = 50
INIT_MU = 200
INIT_GAMMA = 20
INIT_SIGMA = 10
print("initialized value...: X = {}, P_0 = {}, μ_0 = {}, Γ = {}, Σ = {}"
.format(INPUT_X, INIT_P, INIT_MU, INIT_GAMMA, INIT_SIGMA))
lds_model = LinearDynamicSystem(INIT_GAMMA, INIT_SIGMA)
lds_model.fit(INPUT_X, INIT_MU, INIT_P) | faabl/class_seq | seq4-2.py | seq4-2.py | py | 3,796 | python | en | code | 1 | github-code | 6 |
12978124343 | import sys
from pymongo import MongoClient,DESCENDING,ASCENDING
def get_rank(user_id):
client =MongoClient()
db = client.shiyanlou
contests = db.contests
#计算用户 user_id 的排名,总分数以及花费的总时间
#排名的计算方法:
# 1.找到user_id所对应的信息总和,即得分总数,用时总数
# 2.根据得到的得分与用时,对应排名规则,筛选出排名在该用户前的所有用户
# 3.对筛选结果进行计数,即可得到当前用户的排名
#匹配user_id对应的所有数据
pl_match = {'$match':{'user_id':user_id}}
#对这些数据进行求和
pl_group ={'$group':{
'_id':'$user_id',
'total_score':{'$sum':'$score'},
'total_time':{'$sum':'$submit_time'}
}}
user_info = contests.aggregate([pl_match,pl_group])
l = list(user_info)
#记录指定用户的信息
user_score=l[0]['total_score']
user_time=l[0]['total_time']
# print("id:%s,score:%s,time:%s"%(user_id,
# user_score,user_time))
if len(l) == 0:
return 0,0,0
#根据id对所有数据进行分组求和
p_group1 = {'$group':{'_id':'$user_id','total_score':{'$sum':'$score'},
'total_time':{'$sum':'$submit_time'}}}
#根据排名规则筛选符合排名在指定用户前面的所有数据
p_match = {'$match':{'$or':[
{'total_score':{'$gt':user_score}},
{'total_time':{'$lt':user_time},'total_score':user_score}
]}}
#对筛选结果进行计数
p_group2={'$group':{'_id':None,'count':{'$sum':1}}}
pipline=[p_group1,p_match,p_group2]
result =list(contests.aggregate(pipline))
#获得排名
if len(result)>0:
rank = result[0]['count'] + 1
else:
rank = 1
#依次返回排名,分数和时间,不能修改顺序
return rank,user_score,user_time
if __name__ == '__main__':
"""
1.判断参数格式是否符合要求
2.获取user_id 参数
"""
if len(sys.argv) != 2:
print("Parameter error.")
sys.exit(1)
user_id=sys.argv[1]
#根据用户ID获取用户排名,分数和时间
userdata = get_rank(int(user_id))
print(userdata)
| JockerMa/syl_challenge3 | getrank.py | getrank.py | py | 2,282 | python | zh | code | 0 | github-code | 6 |
25493333313 | import pandas as pd
import numpy as np
from card import Card
from enums import AttackType, Role, Element
class CardBridge:
"""Wraps a DataFrame of card records, returns Card instances"""
dic = {
np.nan: AttackType.NONE,
'none':AttackType.NONE,
'melee': AttackType.MELEE,
'ranged': AttackType.RANGED,
'magic': AttackType.MAGIC,
'summoner': Role.SUMMONER,
'monster': Role.MONSTER,
'fire': Element.FIRE,
'water': Element.WATER,
'earth': Element.EARTH,
'life': Element.LIFE,
'death': Element.DEATH,
'dragon': Element.DRAGON,
'neutral': Element.NEUTRAL,
}
df = pd.read_excel('cards.xlsx')
@staticmethod
def retrieve_ability_list(card_row):
ls = []
if card_row.Ability1 is not np.nan:
ls.append(card_row.Ability1)
if card_row.Ability2 is not np.nan:
ls.append(card_row.Ability2)
return ls
@classmethod
def card_from_row(cls, card_row):
try:
inst = Card(
card_row.Card,
cls.dic[card_row.Role],
cls.dic[card_row.Element],
card_row.ManaCost,
card_row.Dmg,
cls.dic[card_row.AttackType],
card_row.Speed,
card_row.Health,
card_row.Armor,
cls.retrieve_ability_list(card_row),
)
return inst
except KeyError as e:
print("Spreadsheet item is blank or invalid")
raise e
@classmethod
def card(cls, i):
if type(i) is int:
return cls.card_from_row(cls.df.iloc[i])
if type(i) is str:
for j in range(len(cls.df)):
if cls.df.Card[j] == i:
return cls.card_from_row(cls.df.iloc[j])
raise KeyError(f"{i} not found in any card name")
@classmethod
def collect(cls, card_names):
card_names_set = set(card_names)
unsorted_deck = {}
for i in range(len(cls.df)):
name = cls.df.Card[i]
if name in card_names_set:
unsorted_deck[name] = cls.card(i)
deck = []
for name in card_names:
deck.append(unsorted_deck[name])
return deck
@classmethod
def get_home_visitor(cls):
length = 16
home = [cls.card(x) for x in range(length // 2)]
visitor = [cls.card(x) for x in range(length // 2, length)]
return home, visitor | GuitarMusashi616/SplinterlandsAI | card_bridge.py | card_bridge.py | py | 2,564 | python | en | code | 5 | github-code | 6 |
7092756844 | #!/usr/bin/env python3
import ast
import astor
expr_l = """
for e in g.Edges():
e.dst["sum1"] += e.data123
for e in g.Edges():
e["data1"] = e.data2 / e.dst.sum1
"""
expr_l_ast = ast.parse(expr_l)
print(ast.dump(expr_l_ast))
def is_call_edges(call):
if isinstance(call, ast.Call):
f_func = call.func
if isinstance(f_func, ast.Attribute) and isinstance(
f_func.value, ast.Name
):
f_object = f_func.value.id
f_method = f_func.attr
if f_object == "g" and f_method == "Edges":
return True
return False
def dst_node_var(n, e):
if (
isinstance(n, ast.Subscript)
and isinstance(n.value, ast.Attribute)
and n.value.value.id == e
and n.value.attr == "dst"
):
return n.slice.value
if (
isinstance(n, ast.Attribute)
and isinstance(n.value, ast.Attribute)
and n.value.value.id == e
and n.value.attr == "dst"
):
return n.attr
else:
return None
global_vars = {}
for node in ast.walk(expr_l_ast):
if (
isinstance(node, ast.For)
and is_call_edges(node.iter)
and isinstance(node.target, ast.Name)
):
edge_var = node.target.id
if len(node.body) == 1:
body = node.body[0]
if isinstance(body, ast.AugAssign) and isinstance(
body.target, ast.Subscript
):
var_name = dst_node_var(body.target, edge_var)
if var_name is not None:
if (
isinstance(body.value, ast.Attribute)
and body.value.value.id == edge_var
and body.value.attr != var_name
):
global_vars[var_name] = [node]
body.target = ast.Name(id="n_var")
elif (
isinstance(body, ast.Assign)
and len(body.targets) == 1
and isinstance(body.targets[0], ast.Subscript)
):
assign_var = dst_node_var(body.targets[0], edge_var)
if assign_var not in global_vars:
if (
isinstance(body.value, ast.BinOp)
and isinstance(body.value.left, ast.Attribute)
and isinstance(body.value.right, ast.Attribute)
):
var_left = dst_node_var(body.value.left, edge_var)
var_right = dst_node_var(body.value.right, edge_var)
if var_left in global_vars:
global_vars[var_left].append(node)
body.value.left = ast.Name(id="n_var")
elif var_right in global_vars:
global_vars[var_right].append(node)
body.value.right = ast.Name(id="n_var")
for var, nodes in global_vars.items():
if len(nodes) == 2:
re_ast = ast.For(
target=ast.Name(id="n"),
iter=ast.Call(
func=ast.Attribute(value=ast.Name(id="g"), attr="Nodes"),
args=[],
keywords=[],
),
body=[
ast.Assign(
targets=[ast.Name(id="n_var")],
value=ast.Constant(value=0.0),
),
ast.For(
target=ast.Name(id="e"),
iter=ast.Call(
func=ast.Attribute(
value=ast.Name(id="n"), attr="incoming_edges"
),
args=[],
keywords=[],
),
body=nodes[0].body,
orelse=[],
),
ast.For(
target=ast.Name(id="e"),
iter=ast.Call(
func=ast.Attribute(
value=ast.Name(id="n"), attr="incoming_edges"
),
args=[],
keywords=[],
),
body=nodes[1].body,
orelse=[],
),
],
orelse=[],
)
expr_l_ast.body.append(re_ast)
expr_l_ast.body.remove(nodes[0])
expr_l_ast.body.remove(nodes[1])
print(astor.to_source(expr_l_ast))
| K-Wu/python_and_bash_playground | pyctor/astor_edge_loop_to_node_loop.py | astor_edge_loop_to_node_loop.py | py | 4,511 | python | en | code | 0 | github-code | 6 |
650674857 | #! /g/kreshuk/pape/Work/software/conda/miniconda3/envs/cluster_env37/bin/python
import os
import json
import luigi
from cluster_tools import MulticutSegmentationWorkflow
def initial_mc(max_jobs, max_threads, tmp_folder, target='slurm'):
n_scales = 1
input_path = '/g/kreshuk/data/FIB25/cutout.n5'
exp_path = './exp_data/exp_data.n5'
input_key = 'volumes/affinities'
ws_key = 'volumes/segmentation/watershed'
out_key = 'volumes/segmentation/multicut'
node_labels_key = 'node_labels/multicut'
configs = MulticutSegmentationWorkflow.get_config()
config_folder = './config'
if not os.path.exists(config_folder):
os.mkdir(config_folder)
shebang = "#! /g/kreshuk/pape/Work/software/conda/miniconda3/envs/cluster_env37/bin/python"
global_config = configs['global']
global_config.update({'shebang': shebang})
with open(os.path.join(config_folder, 'global.config'), 'w') as f:
json.dump(global_config, f)
ws_config = configs['watershed']
ws_config.update({'threshold': .3, 'apply_presmooth_2d': False,
'sigma_weights': 2., 'apply_dt_2d': False,
'sigma_seeds': 2., 'apply_ws_2d': False,
'two_pass': False, 'alpha': .85,
'halo': [25, 25, 25], 'time_limit': 90,
'mem_limit': 8, 'size_filter': 100,
'channel_begin': 0, 'channel_end': 3})
with open(os.path.join(config_folder, 'watershed.config'), 'w') as f:
json.dump(ws_config, f)
subprob_config = configs['solve_subproblems']
subprob_config.update({'weight_edges': True,
'threads_per_job': max_threads,
'time_limit': 180,
'mem_limit': 16})
with open(os.path.join(config_folder, 'solve_subproblems.config'), 'w') as f:
json.dump(subprob_config, f)
feat_config = configs['block_edge_features']
feat_config.update({'offsets': [[-1, 0, 0], [0, -1, 0], [0, 0, -1],
[-4, 0, 0], [0, -4, 0], [0, 0, -4]]})
with open(os.path.join(config_folder, 'block_edge_features.config'), 'w') as f:
json.dump(feat_config, f)
# set number of threads for sum jobs
beta = .5
tasks = ['merge_sub_graphs', 'merge_edge_features', 'probs_to_costs',
'reduce_problem']
for tt in tasks:
config = configs[tt]
config.update({'threads_per_job': max_threads,
'mem_limit': 64, 'time_limit': 260,
'weight_edges': True, 'beta': beta})
with open(os.path.join(config_folder, '%s.config' % tt), 'w') as f:
json.dump(config, f)
time_limit_solve = 24*60*60
config = configs['solve_global']
config.update({'threads_per_job': max_threads,
'mem_limit': 64, 'time_limit': time_limit_solve / 60 + 240,
'time_limit_solver': time_limit_solve})
with open(os.path.join(config_folder, 'solve_global.config'), 'w') as f:
json.dump(config, f)
task = MulticutSegmentationWorkflow(input_path=input_path, input_key=input_key,
ws_path=input_path, ws_key=ws_key,
problem_path=exp_path,
node_labels_key=node_labels_key,
output_path=input_path,
output_key=out_key,
n_scales=n_scales,
config_dir=config_folder,
tmp_folder=tmp_folder,
target=target,
max_jobs=max_jobs,
max_jobs_multicut=1,
skip_ws=False)
ret = luigi.build([task], local_scheduler=True)
assert ret, "Multicut segmentation failed"
if __name__ == '__main__':
# target = 'slurm'
target = 'local'
if target == 'slurm':
max_jobs = 300
max_threads = 8
else:
max_jobs = 64
max_threads = 16
tmp_folder = './tmp_mc'
initial_mc(max_jobs, max_threads, tmp_folder, target=target)
| constantinpape/cluster_tools | publications/leveraging_domain_knowledge/5_lifted_solver/initial_multicut.py | initial_multicut.py | py | 4,330 | python | en | code | 32 | github-code | 6 |
10423097781 | #-*- coding: utf-8 -*-
"""Provides functions for styling output in CLI applications.
.. moduleauthor:: Martí Congost <marti.congost@whads.com>
"""
import sys
from warnings import warn
from time import time
supported_platforms = ["linux"]
foreground_codes = {
"default": 39,
"white": 37,
"black": 30,
"red": 31,
"green": 32,
"brown": 33,
"blue": 34,
"violet": 35,
"turquoise": 36,
"light_gray": 37,
"dark_gray": 90,
"magenta": 91,
"bright_green": 92,
"yellow": 93,
"slate_blue": 94,
"pink": 95,
"cyan": 96,
}
background_codes = {
"default": 49,
"black": 48,
"red": 41,
"green": 42,
"brown": 43,
"blue": 44,
"violet": 45,
"turquoise": 46,
"light_gray": 47,
"dark_gray": 100,
"magenta": 101,
"bright_green": 102,
"yellow": 103,
"slate_blue": 104,
"pink": 105,
"cyan": 106,
"white": 107
}
style_codes = {
"normal": 0,
"bold": 1,
"underline": 4,
"inverted": 7,
"hidden": 8,
"strike_through": 9
}
supported_platform = (sys.platform in supported_platforms)
if supported_platform:
def styled(
string,
foreground = "default",
background = "default",
style = "normal"):
foreground_code = foreground_codes.get(foreground)
background_code = background_codes.get(background)
style_code = style_codes.get(style)
if foreground_code is None \
or background_codes is None \
or style_code is None:
warn(
"Can't print using the requested style: %s %s %s"
% (foreground, background, style)
)
return string
else:
return "\033[%d;%d;%dm%s\033[m" % (
style_code,
foreground_code,
background_code,
string
)
else:
def styled(string, foreground = None, background = None, style = None):
if not isinstance(string, str):
string = str(string)
return string
class ProgressBar(object):
width = 30
min_time_between_updates = 0.005
completed_char = "*"
completed_style = {"foreground": "bright_green"}
pending_char = "*"
pending_style = {"foreground": "dark_gray"}
def __init__(self, total_cycles, label = None, visible = True):
self.__first_iteration = True
self.__last_update = None
self.progress = 0
self.total_cycles = total_cycles
self.label = label
self.visible = visible
def __enter__(self):
self.update()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val is None:
self.finish()
def message(self, label):
self.label = label
self.update(force = True)
def update(self, cycles = 0, force = False):
if not self.visible:
return
self.progress += cycles
# Prevent flickering caused by too frequent updates
if not force and self.min_time_between_updates is not None:
now = time()
if (
self.__last_update is not None
and now - self.__last_update < self.min_time_between_updates
):
return False
self.__last_update = now
if supported_platform:
line = self.get_bar_string() + self.get_progress_string()
else:
line = self.get_progress_string()
label = self.label
if self.__first_iteration:
self.__first_iteration = False
else:
if supported_platform:
line = "\033[1A\033[K" + line
if label:
label = "\033[2A\033[K" + label + "\n"
if label:
print(label)
print(line)
sys.stdout.flush()
return True
def finish(self):
self.progress = self.total_cycles
self.update(force = True)
def get_bar_string(self):
if not self.total_cycles:
completed_width = 0
else:
completed_width = int(
self.width * (float(self.progress) / self.total_cycles)
)
return (
styled(
self.completed_char * completed_width,
**self.completed_style
)
+ styled(
self.pending_char * (self.width - completed_width),
**self.pending_style
)
)
def get_progress_string(self):
return " (%d / %d)" % (self.progress, self.total_cycles)
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--foreground", "-f",
help = "A subset of foreground colors to display")
parser.add_option("--background", "-b",
help = "A subset of background colors to display")
parser.add_option("--style", "-s",
help = "A subset of text styles to display")
options, args = parser.parse_args()
fg_list = (options.foreground.split(",")
if options.foreground
else foreground_codes)
bg_list = (options.background.split(",")
if options.background
else background_codes)
st_list = (options.style.split(",")
if options.style
else style_codes)
for fg in fg_list:
for bg in bg_list:
for st in st_list:
print(fg.ljust(15), bg.ljust(15), st.ljust(15), end=' ')
print(styled("Example text", fg, bg, st))
| marticongost/cocktail | cocktail/styled.py | styled.py | py | 5,595 | python | en | code | 0 | github-code | 6 |
33558200684 | '''https://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html'''
# Take two lists, say for example these two:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that contains only the elements that are common between the lists
# (without duplicates). Make sure your program works on two lists of different sizes.
# Extras:
# 1. Randomly generate two lists to test this
# 2. Write this in one line of Python (don’t worry if you can’t figure this out at this point
# -- we’ll get to it soon)
import random as ran
A = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def int_getter(thing: str) -> int :
while True :
num = input(f'Please enter {thing} >>> ')
if not num.isdigit() :
print('Please enter a number!')
continue
break
return int(num)
class RandomList(list) :
def __init__(self, low, high, length) :
super().__init__()
self.low = low
self.high = high
self.length = length
for _ in range(length) :
self.append(ran.randint(low, high))
def find_intersection(lst1:list[int], lst2:list[int]) -> list[int] :
return list(set(lst1).intersection(set(lst2))) # Single line, Extra #2
def selection_loop_for_rand_lists() -> list[RandomList[int]] :
list_nums = ('1', '2')
snippets = (
'the lower bound for list',
'the upper bound for list',
'the length for list'
)
random_lists = []
for str_num in list_nums :
list_info = []
for snippet in snippets :
list_info.append(int_getter(snippet + ' ' + str_num))
random_lists.append(RandomList(*list_info))
return random_lists
def main() :
# Main part
# return find_intersection(A,B)
# Extra #1
return find_intersection(*selection_loop_for_rand_lists())
# Extra #2
# See above at find_intersection() definition
if __name__ == '__main__' :
print(main())
| daneofmanythings/python_practice | 5_exercise.py | 5_exercise.py | py | 2,097 | python | en | code | 0 | github-code | 6 |
36689632480 | from __future__ import division
import re
import sys
import threading
import pyautogui
import pyperclip
import os
import speech_recognition as sr
from pywinauto import Application
import time
import openai
import win32com.client as wincl
#발급 받은 API 키 설정
OPENAI_API_KEY = "..."
# openai API 키 인증
openai.api_key = OPENAI_API_KEY
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r"..."
from google.cloud import speech
import pyaudio
from six.moves import queue
# Audio recording parameters
RATE = 20000 ## 음성인식 성능향상
CHUNK = int(RATE / 30) # 100ms ## 음성인식 성능향상
class MicrophoneStream(object):
"""Opens a recording stream as a generator yielding the audio chunks."""
def __init__(self, rate, chunk):
self._rate = rate
self._chunk = chunk
# Create a thread-safe buffer of audio data
self._buff = queue.Queue()
self.closed = True
def __enter__(self):
self._audio_interface = pyaudio.PyAudio()
self._audio_stream = self._audio_interface.open(
format=pyaudio.paInt16,
# The API currently only supports 1-channel (mono) audio
# https://goo.gl/z757pE
channels=1, rate=self._rate,
input=True, frames_per_buffer=self._chunk,
# Run the audio stream asynchronously to fill the buffer object.
# This is necessary so that the input device's buffer doesn't
# overflow while the calling thread makes network requests, etc.
stream_callback=self._fill_buffer,
)
self.closed = False
return self
def __exit__(self, type, value, traceback):
self._audio_stream.stop_stream()
self._audio_stream.close()
self.closed = True
# Signal the generator to terminate so that the client's
# streaming_recognize method will not block the process termination.
self._buff.put(None)
self._audio_interface.terminate()
def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
"""Continuously collect data from the audio stream, into the buffer."""
self._buff.put(in_data)
return None, pyaudio.paContinue
def generator(self):
while not self.closed:
# Use a blocking get() to ensure there's at least one chunk of
# data, and stop iteration if the chunk is None, indicating the
# end of the audio stream.
chunk = self._buff.get()
if chunk is None:
return
data = [chunk]
# Now consume whatever other data's still buffered.
while True:
try:
chunk = self._buff.get(block=False)
if chunk is None:
return
data.append(chunk)
except queue.Empty:
break
yield b''.join(data)
def type_text(text):
pyperclip.copy(text)
pyautogui.hotkey('ctrl', 'v')
# 기존 임포트 및 설정 코드 생략 ...
def speak(text, rate=1.0):
speak = wincl.Dispatch("SAPI.SpVoice")
speak.Rate = rate
speak.Speak(text)
waiting = False
def waiting_message():
global waiting
while waiting:
print("잠시만 기다려 주세요...")
speak("잠시만 기다려 주세요...")
time.sleep(1)
def is_windows_spoken():
global waiting
# 음성 인식 객체 생성
r = sr.Recognizer()
mic = sr.Microphone()
with mic as source:
r.adjust_for_ambient_noise(source)
messages = []
while True:
print("Listening...")
speak("음성인식 실행")
with mic as source:
r.non_blocking = True
audio = r.listen(source)
try:
text = r.recognize_google_cloud(audio, language='ko-KR')
if "윈도우" in text:
speak("네 말씀하세요.")
print("명령어를 말씀해주세요.")
return True
elif "입력" in text:
speak("잠시만 기다려주세요")
print("잠시만 기다려주세요")
return False
#gpt api 사용.
elif "검색" in text:
print("검색 질문을 말씀해주세요.")
speak("검색 질문을 말씀해주세요.")
with mic as source:
audio = r.listen(source)
waiting = True
waiting_thread = threading.Thread(target=waiting_message)
waiting_thread.start()
question = r.recognize_google_cloud(audio, language='ko-KR')
messages.append({"role": "user", "content": question})
answer = speech_to_gpt(messages)
waiting = False
waiting_thread.join()
print(f'GPT: {answer}')
messages.append({"role": "assistant", "content": answer})
type_text(answer)
#speak(answer)
elif "종료" in text:
speak("종료하겠습니다.")
sys.exit("Exiting")
else:
speak("다시 말씀해주세요.")
print("다시 말씀해주세요.")
except sr.UnknownValueError:
speak("다시 말씀해주세요.")
print("다시 말씀해주세요.")
except sr.WaitTimeoutError:
# 타임아웃 에러 발생 시 다시 음성 수집 시작
continue
def listen_print_loop(responses):
transcript = ""
final_transcript = ""
for response in responses:
if not response.results:
continue
result = response.results[0]
if not result.alternatives:
continue
transcript = result.alternatives[0].transcript
# 기존에 출력된 텍스트 지우기
sys.stdout.write("\033[F\033[K")
# 최종 결과만 출력하고 나머지는 저장
if result.is_final:
final_transcript += transcript + " "
print(final_transcript)
if re.search(r'\b(음성인식 꺼 줘|quit)\b', final_transcript, re.I):
speak("종료하겠습니다.")
sys.exit("Exiting")
if re.search(r'\b(음성인식 종료|quit)\b', final_transcript, re.I):
speak("종료하겠습니다.")
sys.exit("Exiting")
if "메모장" in final_transcript:
app = Application().start("notepad.exe")
time.sleep(0.5)
break
if "크롬" in final_transcript:
app = Application().start("C:\Program Files\Google\Chrome\Application\chrome.exe")
time.sleep(0.5)
break
if "한글" in final_transcript:
app = Application().start("C:\Program Files (x86)\HNC\Office 2022\HOffice120\Bin\Hwp.exe")
time.sleep(0.5)
break
if "검색" in final_transcript:
pyautogui.keyDown("ctrl")
pyautogui.press("f")
pyautogui.keyUp("ctrl")
time.sleep(0.5)
break
if "복사" in final_transcript:
pyautogui.keyDown("ctrl")
pyautogui.press("c")
pyautogui.keyUp("ctrl")
time.sleep(0.5)
break
if "붙여 넣기" in final_transcript:
pyautogui.keyDown("ctrl")
pyautogui.press("v")
pyautogui.keyUp("ctrl")
time.sleep(0.5)
break
if "뒤로 가기" in final_transcript:
pyautogui.keyDown("ctrl")
pyautogui.press("z")
pyautogui.keyUp("ctrl")
time.sleep(0.5)
break
if "닫기" in final_transcript:
pyautogui.keyDown("alt")
pyautogui.press("f4")
pyautogui.keyUp("alt")
time.sleep(0.5)
break
if "다음" in final_transcript:
pyautogui.press("space")
time.sleep(0.5)
break
if "나가기" in final_transcript:
pyautogui.press("esc")
time.sleep(0.5)
break
if "엔터" in final_transcript:
pyautogui.press("enter")
time.sleep(0.5)
break
# ------------------------------------------5/7
if "한글" in transcript:
pyautogui.press("hangul")
time.sleep(0.5)
break
if "영어" in transcript:
pyautogui.press("hangul")
time.sleep(0.5)
break
if "저장" in transcript:
pyautogui.hotkey('ctrl', 's')
time.sleep(0.5)
break
if "전체 선택" in transcript:
pyautogui.hotkey('ctrl', 'a')
time.sleep(0.5)
break
if "캡처" in transcript:
pyautogui.hotkey('shift', 'win', 's')
time.sleep(0.5)
break
if "캡스락" in transcript:
pyautogui.press("capslocck")
time.sleep(0.5)
break
if "자르기" in transcript:
pyautogui.hotkey('ctrl', 'x')
time.sleep(0.5)
break
# ------------------------------------------5/13
if "새로고침" in transcript:
pyautogui.press("f5")
time.sleep(0.5)
break
if "시작" in transcript:
pyautogui.press("f5")
time.sleep(0.5)
break
if "바탕화면" in transcript:
pyautogui.hotkey('win', 'd')
time.sleep(0.5)
break
if "최대화" in transcript:
pyautogui.hotkey('win', 'up')
time.sleep(0.5)
break
if "삭제" in transcript:
pyautogui.press("delete")
time.sleep(0.5)
break
if "실행" in transcript:
pyautogui.hotkey('ctrl', 'alt', 'f10')
time.sleep(0.5)
break
if "작업 관리자" in transcript:
pyautogui.hotkey('ctrl', 'shift', 'esc')
time.sleep(0.5)
break
final_transcript = ""
else:
sys.stdout.write(transcript + '\r')
sys.stdout.flush()
return final_transcript
def speech_to_text():
# create a recognizer instance
r = sr.Recognizer()
# use the system default microphone as the audio source
with sr.Microphone() as source:
print("Speak:")
# adjust for ambient noise
r.adjust_for_ambient_noise(source)
# listen for audio
audio = r.listen(source)
try:
# recognize speech using Google Speech Recognition
text = r.recognize_google(audio, language='ko-KR')
speak("입력하겠습니다.")
print("You said: " + text)
return text
except sr.WaitTimeoutError:
print("Listening timed out. Please try again.")
return None
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return None
def speech_to_gpt(messages):
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
chat_response = completion.choices[0].message.content
return chat_response
def main():
# See http://g.co/cloud/speech/docs/languages
# for a list of supported languages.
language_code = 'ko-KR' # a BCP-47 language tag
client = speech.SpeechClient()
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=RATE,
language_code=language_code)
streaming_config = speech.StreamingRecognitionConfig(
config=config,
interim_results=True)
while True:
windows_spoken = is_windows_spoken()
if windows_spoken:
end_time = time.time() + 5 # 5 seconds
while time.time() < end_time:
with MicrophoneStream(RATE, CHUNK) as stream:
audio_generator = stream.generator()
requests = (speech.StreamingRecognizeRequest(audio_content=content)
for content in audio_generator)
responses = client.streaming_recognize(streaming_config, requests)
listen_print_loop(responses)
break
elif not windows_spoken:
command = speech_to_text()
if command:
type_text(command)
else:
time.sleep(0.05)
if __name__ == '__main__':
main()
# [END speech_transcribe_streaming_mic]
| quswjdgns399/air_command | voicecommand_final.py | voicecommand_final.py | py | 13,739 | python | en | code | 0 | github-code | 6 |
26310660224 | from alarmageddon.publishing.hipchat import HipChatPublisher
from alarmageddon.result import Failure
from alarmageddon.result import Success
from alarmageddon.publishing.exceptions import PublishFailure
from alarmageddon.validations.validation import Validation, Priority
import pytest
#Successes aren't sent, so monkeypatch out post and then
#only failures should notice
@pytest.fixture
def no_post(monkeypatch):
monkeypatch.delattr("requests.post")
def new_publisher():
return HipChatPublisher(
api_end_point="fakeurl",
api_token="faketoken",
environment="UnitTest",
room_name="Alarmageddon")
def test_requires_api_end_point():
with pytest.raises(ValueError):
HipChatPublisher(api_end_point="",
api_token="faketoken",
environment="UnitTest",
room_name="Alarmageddon")
def test_requires_api_token():
with pytest.raises(ValueError):
HipChatPublisher(api_end_point="fakeurl",
api_token="",
environment="UnitTest",
room_name="Alarmageddon")
def test_requires_environment():
with pytest.raises(ValueError):
HipChatPublisher(api_end_point="fakeurl",
api_token="token",
environment="",
room_name="Alarmageddon")
def test_requires_room():
with pytest.raises(ValueError):
HipChatPublisher(api_end_point="fakeurl",
api_token="token",
environment="UnitTest",
room_name="")
def test_repr():
hipchat = new_publisher()
hipchat.__repr__()
def test_str():
hipchat = new_publisher()
str(hipchat)
def testSendSuccess(no_post, monkeypatch):
hipchat = new_publisher()
v = Validation("low", priority=Priority.LOW)
success = Success("bar", v)
hipchat.send(success)
def testSendFailure(no_post, monkeypatch):
hipchat = new_publisher()
v = Validation("low", priority=Priority.LOW)
failure = Failure("foo", v, "unable to frobnicate")
with pytest.raises(AttributeError):
hipchat.send(failure)
def test_publish_failure(httpserver):
httpserver.serve_content(code=300, headers={"content-type": "text/plain"},
content='{"mode":"NORMAL"}')
pub = HipChatPublisher(httpserver.url, "token", "env", "room")
v = Validation("low", priority=Priority.CRITICAL)
failure = Failure("bar", v, "message")
with pytest.raises(PublishFailure):
pub.send(failure)
| PearsonEducation/Alarmageddon | tests/publishing/test_hipchat.py | test_hipchat.py | py | 2,640 | python | en | code | 15 | github-code | 6 |
27089945038 | #=============================================================================================================#
# HOW TO RUN? #
# python3 chop_segments.py #
# Please provide LABEL, SEGMENT_LENGTH, OUTPUT_PATH, INPUT_FILE_TO_CHOP. #
#=============================================================================================================#
import csv
import sys
import nltk
from nltk import tokenize
#=============================================================================================================#
LABEL = 1
SEGMENT_LENGTH = 100
OUTPUT_PATH = "APPROPRIATE.CSV"
INPUT_FILE_TO_CHOP = "SAMPLE_INPUT_FILE.txt"
#=============================================================================================================#
#When we run the script for appropriate channels, we set the LABEL as 1 else we set it as 0 for inappropriate #
#=============================================================================================================#
visited = set()
## To ensure there are no duplicate video IDs
s = ""
cur = ""
prev = []
flag = 0
identifier = 0
#=============================================================================================================#
f = open(INPUT_FILE_TO_CHOP)
with open(OUTPUT_PATH, 'w') as csvfile:
fieldnames = ['','Unnamed: 0','Unnamed: 0.1','Transcript','ID','Label']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'': '', 'Unnamed: 0': 'Unnamed: 0', 'Unnamed: 0.1': 'Unnamed: 0.1', 'Transcript' : 'Transcript', 'ID' : 'VIDEO ID', 'Label' : 'Label'})
for line in f:
# Channel IDs are present in lines containing ||||
if("||||" in line):
continue
# Video IDs are present in lines containing ####
if("####" in line):
cur = line.strip()
if(flag == 1):
identifier +=1
text = s.strip()
groups = nltk.word_tokenize(text)
n_split_groups = []
while len(groups):
n_split_groups.append(' '.join(groups[:SEGMENT_LENGTH]))
groups = groups[SEGMENT_LENGTH:]
for part in n_split_groups:
writer.writerow({'': identifier, 'Unnamed: 0': identifier, 'Unnamed: 0.1': identifier, 'Transcript' : part, 'ID' : prev[1], 'Label' : LABEL })
print("PROCESSED VIDEO ID",str(prev[1]))
flag = 0
if("####" in line and (line.strip() not in visited)):
s = ""
flag = 1
visited.add(line.strip())
prev = cur.split("####")
if("####" not in line and flag == 1):
s += line.strip() + " "
if(flag == 1):
identifier +=1
text = s.strip()
groups = nltk.word_tokenize(text)
n_split_groups = []
while len(groups):
n_split_groups.append(' '.join(groups[:SEGMENT_LENGTH]))
groups = groups[SEGMENT_LENGTH:]
for part in n_split_groups:
writer.writerow({'': identifier, 'Unnamed: 0': identifier, 'Unnamed: 0.1': identifier, 'Transcript' : part, 'ID' : prev[1], 'Label' : LABEL })
#=============================================================================================================#
| STEELISI/Youtube-PG | chop_segments.py | chop_segments.py | py | 3,488 | python | en | code | 0 | github-code | 6 |
15619190553 | import numpy as np
import os
from PIL import Image
from PIL import ImageFont, ImageDraw
import time
import core.utils as utils
import core.v_detection as detect
import cv2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', type=str, default="./1.mp4", help="input video")
parser.add_argument('-o', type=str, default="./output.avi", help="input video")
args = parser.parse_args()
#videos
if __name__ == "__main__":
input = args.i
output = args.o
cap = cv2.VideoCapture(input)
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(args.o, cv2.VideoWriter_fourcc(
'M', 'J', 'P', 'G'), 25, (frame_width, frame_height))
while(True):
ret, image = cap.read()
if ret == True:
start = time.time()
bboxes = detect.vehicle_detection(image)
# print("bboxes: ", bboxes)
image = utils.draw_bbox(image, bboxes)
print("processing time: ", time.time() - start)
out.write(image)
cap.release()
out.release() | byq-luo/vehicle_detection-1 | video_clients.py | video_clients.py | py | 1,122 | python | en | code | 0 | github-code | 6 |
24594203458 | from database import db_setup
from pdf_parser import PdfParser
def main():
pdf_path = '/Users/mak/WebstormProjects/front/halykTEST/pdf_docs/attachment-2.pdf'
pdf_parser = PdfParser()
database = db_setup()
parsed_text = pdf_parser.parse_pdf(pdf_path)
database.save_pdf_data(pdf_path, parsed_text)
if __name__ == '__main__':
main()
| Danialkb/halyk_test | main.py | main.py | py | 360 | python | en | code | 0 | github-code | 6 |
34660089311 | import requests
from bs4 import BeautifulSoup
import csv
import os
URL = 'https://citaty.info/book/quotes'
HEADERS = {'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0',
'accept': '*/*'}
FILE_CSV = 'quotations_csv.csv'
def get_html(url, params=None):
r = requests.get(url, headers=HEADERS, params=params)
return r
def get_content(html):
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='node__content')
quotations = []
for item in items:
topic_tags = item.find('div', class_='node__topics')
if topic_tags:
topic_tags = topic_tags.get_text(', ')
else:
topic_tags = 'No tags'
quotations.append({
'autor': item.find('a', title='Автор цитаты').get_text(),
'book': item.find('a', title='Цитата из книги').get_text(),
'text_quotation': item.find('div', class_='field-item even last').get_text().replace('\xa0', ' ').replace('\n', ' '),
'topic_tags': topic_tags
})
print(*quotations, sep='\n')
save_file_csv(quotations, FILE_CSV)
os.startfile(FILE_CSV)
def save_file_csv (items, path):
with open(path, 'w', newline='') as file:
writer=csv.writer(file, delimiter=';')
writer.writerow(['Autor', 'Book', 'Quotation', 'Tags'])
for item in items:
writer.writerow([item['autor'], item['book'], item['text_quotation'], item['topic_tags']])
def parse():
html = get_html(URL)
if html.status_code == 200:
get_content(html.text)
else:
print('Error!')
parse() | isorokina012/course_work | course_paper.py | course_paper.py | py | 1,737 | python | en | code | 0 | github-code | 6 |
72947594108 | __author__ = "Balaji Sriram"
__version__ = "0.0.1"
__copyright__ = "Copyright 2018"
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Balaji Sriram"
__email__ = "balajisriram@gmail.com"
__status__ = "Production"
from .BehaviorProtocols import get_behavior_protocol_biogen
from .PhysiologyProtocols import get_phys_protocol_biogen
def get_protocol_from_name(name):
if name in ['orientation_tuning_biogen_08292018','ortune','short_duration_biogen_08292018','orsdp']:
return get_phys_protocol_biogen(name)
elif name in ['lick_for_reward_biogen_09142018','lfr',
'classical_conditioning_protocol_12022018','ccp',
'auditory_go_protocol_12192018','audgo',
'gratings_go_protocol_12202018','gratgo']:
return get_behavior_protocol_biogen(name)
else:
raise ValueError('unknown protocol name')
| balajisriram/bcore | bcore/Users/Biogen/__init__.py | __init__.py | py | 884 | python | en | code | 1 | github-code | 6 |
20660791350 | from franz.openrdf.connect import ag_connect
from franz.openrdf.query.query import QueryLanguage
from franz.openrdf.rio.rdfformat import RDFFormat
import os.path
#https://franz.com/agraph/support/documentation/current/python/tutorial/example003.html#
with ag_connect('Mythologie', host='localhost', port='10035',
user='Marc', password='marc') as conn:
print ("Total = %s triples" % (conn.size()))
query_string = "select ?g (count(?s) as ?tot) where {GRAPH ?g {?s ?p ?o}} group by ?g"
tuple_query = conn.prepareTupleQuery(QueryLanguage.SPARQL, query_string)
result = tuple_query.evaluate()
with result:
for binding_set in result:
g = binding_set.getValue("g")
tot = binding_set.getValue("tot")
print("GRAPH %s %s " % (g, tot))
DATA_DIR = 'data'
path0 = os.path.join(DATA_DIR, 'skos.rdf')
context0 = conn.createURI("http://www.w3.org/mythologie/skoscore")
path1 = os.path.join(DATA_DIR, 'mythologie.ttl')
context1 = conn.createURI("http://www.w3.org/mythologie/metamodel")
#conn.addData(event)
path2 = os.path.join(DATA_DIR, 'mythologie_god.json')
context2 = conn.createURI("http://www.w3.org/mythologie/gods")
path3 = os.path.join(DATA_DIR, 'mythologie_human.json')
context3 = conn.createURI("http://www.w3.org/mythologie/mortals")
path4 = os.path.join(DATA_DIR, 'mythologieTemple.json')
context4 = conn.createURI("http://www.w3.org/mythologie/temples")
path5 = os.path.join(DATA_DIR, 'mythologiePlants.json')
context5 = conn.createURI("http://www.w3.org/mythologie/plants")
path6 = os.path.join(DATA_DIR, 'mythologieGeo.json')
context6 = conn.createURI("http://www.w3.org/mythologie/geography")
path7 = os.path.join(DATA_DIR, 'mythologieCreatures.json')
context7 = conn.createURI("http://www.w3.org/mythologie/creatures")
path8 = os.path.join(DATA_DIR, 'mythologieAuthor.json')
context8 = conn.createURI("http://www.w3.org/mythologie/authors")
path9 = os.path.join(DATA_DIR, 'mythologieSymbol.json')
context9 = conn.createURI("http://www.w3.org/mythologie/symbols")
with ag_connect('Mythologie', host='localhost', port='10035',
user='Marc', password='marc', clear=True) as conn:
conn.addFile(path0, None, format=RDFFormat.RDFXML, context=context0)
conn.addFile(path1, None, format=RDFFormat.TURTLE, context=context1)
conn.addFile(path2, None, context=context2)
conn.addFile(path3, None, context=context3)
conn.addFile(path4, None, context=context4)
conn.addFile(path5, None, context=context5)
conn.addFile(path6, None, context=context6)
conn.addFile(path7, None, context=context7)
conn.addFile(path8, None, context=context8)
conn.addFile(path9, None, context=context9)
print('Metamodel triples (in {context}): {count}'.format(
count=conn.size(context1), context=context1))
print ("Total = %s triples" % (conn.size())) | MarcALieber/rdf_mythology | agMyth.py | agMyth.py | py | 2,845 | python | en | code | 1 | github-code | 6 |
70465798267 | import sys
from cx_Freeze import setup, Executable
target = Executable(script="Main_Program_Design.py",
base = "Win32GUI",
icon="Meat_Icon.ico")
setup(name="Meat Shop Management System",
version = "1.0",
description="A simple program that helps the owner compute the order of the clients.",
executables = [target])
| zEuS0390/python-meat-shop-management-system | setup.py | setup.py | py | 375 | python | en | code | 1 | github-code | 6 |
22083607555 |
#recursion for quick sort we take last element as pivot
def partionOfArray(lst,low,high):
print("\n")
print("partition array ",lst)
i = low - 1
lastIndex = lst[high]
for j in range(low,high):
if lst[j] < lastIndex:
i += 1
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
print("for loop",lst)
lst[i+1] , lst[high] = lst[high] , lst[i+1]
print("part value",i + 1)
return i + 1
def quickSort(lst, low , high):
if low < high:
part = partionOfArray(lst,low,high)
# print("partion value",part)
print("quickSort before ",lst)
quickSort(lst,low,part-1)
print("Left array ",lst)
quickSort(lst,part+1,high)
print("right array ",lst)
lst = [10, 7, 8, 9, 1, 5]
print("Before Sorting", lst)
length = len(lst)
low = 0
high = length - 1
quickSort(lst,low,high)
print("After Sorting", lst) | vamshipv/code-repo | 1 Daily Algo/quickSort.py | quickSort.py | py | 968 | python | en | code | 0 | github-code | 6 |
40411446541 | #!/usr/bin/env python3
"""
Name: example_ndfc_device_info.py
Description:
Retrieve various information about a device, given its
fabric_name and ip_address
"""
from ndfc_python.log import log
from ndfc_python.ndfc import NDFC
from ndfc_python.ndfc_credentials import NdfcCredentials
from ndfc_python.ndfc_device_info import NdfcDeviceInfo
nc = NdfcCredentials()
logger = log("ndfc_device_info", "INFO", "DEBUG")
ndfc = NDFC()
ndfc.logger = logger
ndfc.username = nc.username
ndfc.password = nc.password
ndfc.ip4 = nc.ndfc_ip
ndfc.login()
instance = NdfcDeviceInfo()
instance.ndfc = ndfc
instance.logger = logger
instance.fabric_name = "easy"
for ipv4 in ["172.22.150.102", "172.22.150.103"]:
instance.ip_address = ipv4
instance.refresh()
print(f"device: {instance.ip_address}")
print(f"fabric: {instance.fabric_name}")
print(f" name: {instance.logical_name}")
print(f" role: {instance.switch_role}")
print(f" db_id: {instance.switch_db_id}")
print(f" serial_number: {instance.serial_number}")
print(f" model: {instance.model}")
print(f" release: {instance.release}")
print(f" status: {instance.status}")
print(f" oper_status: {instance.oper_status}")
| allenrobel/ndfc-python | examples/device_info.py | device_info.py | py | 1,219 | python | en | code | 0 | github-code | 6 |
4785274840 | h,w = map(int,input().split())
l1 = []
for i in range(h):
l1.append(list(input()))
l2 = []
for i in range(h):
l2.append(list(input()))
l1 = list(map(list,zip(*l1)))
l2 = list(map(list,zip(*l2)))
l1.sort()
l2.sort()
if l1 == l2:
print("Yes")
else:
print("No") | K5h1n0/compe_prog_new | VirtualContest/adt_all_20231017_2/e (過去のabcのc問題から出題)/main.py | main.py | py | 274 | python | en | code | 0 | github-code | 6 |
11036108434 | import wx
import PropToolPanel
import CollisionToolPanel
import POIToolPanel
class ToolBrowser(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
self.notebook = wx.Notebook(self, -1)
self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onPageChanged, self.notebook)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.notebook, 1, wx.EXPAND)
self.SetSizer(sizer)
self.observers = []
self.selectedTool = None
self.selectedEditor = None
self.collisionToolPanel = CollisionToolPanel.CollisionToolPanel(self.notebook, -1)
#self.notebook.AddPage(self.collisionToolPanel, "Collision")
self.notebook.AddPage(self.collisionToolPanel, "Col")
self.poiToolPanel = POIToolPanel.POIToolPanel(self.notebook, -1)
self.notebook.AddPage(self.poiToolPanel, "POI")
self.propToolPanel = PropToolPanel.PropToolPanel(self.notebook, -1)
self.notebook.AddPage(self.propToolPanel, "Props")
def addObserver(self, observer): self.observers.append(observer)
def removeObserver(self, observer): self.observers.remove(observer)
def onPageChanged(self, event):
if self.selectedEditor and self.selectedTool:
self.selectedTool.detachFromEditor(self.selectedEditor)
self.selectedTool = self.notebook.GetPage(self.notebook.GetSelection())
if self.selectedEditor:
self.selectedTool.attachToEditor(self.selectedEditor)
self.selectedEditor.Refresh()
def onEditorChanged(self, editor):
if self.selectedEditor:
self.selectedTool.detachFromEditor(self.selectedEditor)
self.selectedEditor = editor
if editor:
self.selectedTool.attachToEditor(editor)
def _notify(self):
for observer in self.observers: observer(self)
| sdetwiler/pammo | editor/source/ToolBrowser.py | ToolBrowser.py | py | 1,872 | python | en | code | 0 | github-code | 6 |
4403084906 | import unittest
from pyunitreport import HTMLTestRunner
import parse_api_test_cases
import os
import time
from api_test_case import ApiTestCase
from parse_api_test_cases import TestCaseParser
import argparse
import logging
if __name__ == '__main__':
# Argument Parse
parser = argparse.ArgumentParser(
description='API Test Assistant, Help you to do api test.')
parser.add_argument(
'test_suite_name', help="Please add your test suite's path"
)
args = parser.parse_args()
test_suite_name = args.test_suite_name
# create log file
log_file__folder_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tests/log/')
if not os.path.exists(log_file__folder_path):
os.makedirs(log_file__folder_path)
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
test_log_file_path = os.path.join(log_file__folder_path, str(test_suite_name)+time_str+'.log')
logging.basicConfig(filename=test_log_file_path, level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filemode='w')
logging.info("=========Start test execution!========")
suite = unittest.TestSuite()
tcp = TestCaseParser(test_suite_name)
test_cases_list = tcp.get_test_case_list()
logging.info("Got est cases list of {test_suite_name}".format(test_suite_name=test_suite_name))
for test_case in test_cases_list:
ApiTestCase.runTest.__doc__ = test_case['name']
test = ApiTestCase(test_case)
suite.addTest(test)
logging.info("Added {tc_name} to test suite".format(tc_name=test_case['name']))
test_report_folder_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tests/reports/')
if not os.path.exists(test_report_folder_path):
os.makedirs(test_report_folder_path)
logging.info("Report Folder Created at {path}".format(path=test_report_folder_path))
else:
logging.info("Report Folder already exists at {path}".format(path=test_report_folder_path))
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
test_report_file_path = str(test_suite_name) + time_str
kwargs = {
"output": test_report_folder_path,
"report_name": test_report_file_path
}
runner = HTMLTestRunner(**kwargs)
runner.run(suite)
logging.info("Test suite execution done!")
| PengDongCd/ApiTestAssitant | api_test_assistant_main.py | api_test_assistant_main.py | py | 2,481 | python | en | code | 0 | github-code | 6 |
32584237829 | # #
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
card = dbc.Card(
[dbc.CardHeader("Header"), dbc.CardBody("Body", style={"height": 250})],
className="h-100",
)
graph_card = dbc.Card([dbc.CardHeader("Here's a graph"), dbc.CardBody([dcc.Graph()])])
app.layout = dbc.Container(
dbc.Row(
[
dbc.Col(
[
dbc.CardDeck([card] * 4),
html.H2("Here is some important information to highlight..."),
dbc.CardDeck([graph_card] * 2),
],
width=10,
),
dbc.Col(card, width=2),
]
),
fluid=True,
className="m-3",
)
if __name__ == "__main__":
app.run_server(debug=True)
| thigbee/dashBootstrapThemeExplorer | gallery/layout_template_1.py | layout_template_1.py | py | 890 | python | en | code | 0 | github-code | 6 |
72487367548 | from tkinter import *
from tkinter import messagebox
print("hello world");
print("hello world");
print("hello world");
print("hello world");
root = Tk()
root.title("Simple Calculator")
root.geometry("350x300")
root.resizeable(0,0)
root.configure(bg="#77526b")
equa = ""
equation = StringVar()
Calculation = Label(root, textvariable=equation, bg="#77526b", fg="#e6a4ff", font="Tahoma", justify=CENTER)
equation.set("Enter your expression")
Calculation.grid(columnspan=4)
def buttonPress(number):
global equa
equa = equa + str(number)
equation.set(equa)
def equalButtonPress():
try:
member = 0
global equa
total = str(eval(equa))
for char in total:
member += 1
if member > 20:
raise ValueError
equation.set(total)
equa = ""
except ZeroDivisionError:
messagebox.showwarning(title="Mathematic error", message="Division by Zero")
except ValueError:
messagebox.showerror(title="value Error", message="Too Big Number!")
except:
messagebox.showerror(title="Syntax error", message="an error occurd please try again")
def clearButtonPress():
global equa
equa = ""
equation.set("")
btn0 = Button(root, text="0", width=7, height=2, command=lambda: buttonPress(0), padx=2, pady=2, relief=RAISED,
bg="#e0b34a", font="Tahoma")
btn0.grid(row=4, column=1)
btn1 = Button(root, text="1", width=7, height=2, command=lambda: buttonPress(1), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn1.grid(row=1, column=0)
btn2 = Button(root, text="2", width=7, height=2, command=lambda: buttonPress(2), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn2.grid(row=1, column=1)
btn3 = Button(root, text="3", width=7, height=2, command=lambda: buttonPress(3), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn3.grid(row=1, column=2)
btn4 = Button(root, text="4", width=7, height=2, command=lambda: buttonPress(4), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn4.grid(row=2, column=0)
btn5 = Button(root, text="5", width=7, height=2, command=lambda: buttonPress(5), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn5.grid(row=2, column=1)
btn6 = Button(root, text="6", width=7, height=2, command=lambda: buttonPress(6), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn6.grid(row=2, column=2)
btn7 = Button(root, text="7", width=7, height=2, command=lambda: buttonPress(7), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn7.grid(row=3, column=0)
btn8 = Button(root, text="8", width=7, height=2, command=lambda: buttonPress(8), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn8.grid(row=3, column=1)
btn9 = Button(root, text="9", width=7, height=2, command=lambda: buttonPress(9), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
btn9.grid(row=3, column=2)
plus = Button(root, text="+", width=7, height=2, command=lambda: buttonPress('+'), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
plus.grid(row=1, column=3)
minus = Button(root, text="-", width=7, height=2, command=lambda: buttonPress('-'), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
minus.grid(row=2, column=3)
multiply = Button(root, text="×", width=7, height=2, command=lambda: buttonPress('*'), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
multiply.grid(row=3, column=3)
divide = Button(root, text="÷", width=7, height=2, command=lambda: buttonPress('/'), padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
divide.grid(row=4, column=3)
equal = Button(root, text="=", width=7, height=2, command=equalButtonPress, padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
equal.grid(row=4, column=2)
clear = Button(root, text="c", width=7, height=2, command=clearButtonPress, padx=2, pady=2, relief=RAISED,
font="Tahoma", bg="#e0b34a")
clear.grid(row=4, column=0)
root.mainloop()
| arshiaor/simpleCalculator | simpleCalculator.py | simpleCalculator.py | py | 4,195 | python | en | code | 1 | github-code | 6 |
35063056732 | from json import JSONDecoder, dumps
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView
from django.db.models import ObjectDoesNotExist
from api.models import Record, KeysToken, ChildRecord, User, UnregisteredRecord
from api.serializer import RecordSerializer, UserSerializer, ChildRecordSerializer
from serv.MRDApi import Cryptographer, NotValid
class Editor(APIView):
cryp = Cryptographer()
def put(self, req):
token = get_object_or_404(
KeysToken.objects.all(),
token=req.data['token'])
user = token.user
if token.is_valid():
token.update_activity()
user_data = req.data['usr']
errors = [None, None]
try:
errors[0] = self._update_user_data(user_data, user)
except NotValid:
return Response(status=400, data="lel")
if errors[0] != None:
return Response(status=400, data=errors[0])
record_data = req.data['rec']
try:
errors[1] = self._update_record_data(record_data, user)
except NotValid:
return Response(status=400)
if errors[1] != None:
return Response(status=400, data=errors[1])
return Response(status=200)
else:
return Response(status=401)
def _update_user_data(self, user_data, user):
unique_status, errors = self._unique_user_creds(user_data, user)
if unique_status:
usr_ser = UserSerializer(instance=user, data=user_data, partial=True)
if usr_ser.is_valid():
usr_ser.save()
else:
raise NotValid
if errors == None:
return None
return errors
def _update_record_data(self, record_data, user):
record = get_object_or_404(Record.objects.all(), owner=user)
unique_status, errors = self._unique_record_creds(record_data, record)
if unique_status:
rec_ser = RecordSerializer(
instance=record,
data=record_data,
partial=True)
if rec_ser.is_valid():
rec_ser.save()
else:
raise NotValid
if errors == None:
return None
return errors
def _unique_record_creds(self, record_data, record_instance):
record = None
errors = []
if 'serial_number' in record_data.keys():
try:
record = Record.objects.get(serial_number=record_data['serial_number'])
except ObjectDoesNotExist:
record = None
if record:
errors.append('serialNumberError')
try:
snum = record_data['serial_number']
unreg_rec = UnregisteredRecord.objects.get(serial_number=snum)
except ObjectDoesNotExist:
errors.append('noSuchRecord')
unreg_rec = None
if unreg_rec and unreg_rec.code == record_data['code']:
if not record or record == record_instance:
record_instance.serial_number = record_data['serial_number']
record_instance.save()
unreg_rec.delete()
return True, None
return False, errors
return True, None
def _unique_user_creds(self, user_data, user_instance):
user = None
errors = []
if 'username' in user_data.keys():
try:
user = User.objects.get(username=user_data['username'])
except ObjectDoesNotExist:
user = None
if user:
errors.append('usernameError')
if 'email' in user_data.keys():
try:
user = User.objects.get(email=user_data['email'])
except ObjectDoesNotExist:
user = None
if user:
errors.append('emailError')
if 'telephone' in user_data.keys():
try:
user = User.objects.get(telephone=user_data['telephone'])
except ObjectDoesNotExist:
user = None
if user:
errors.append('phoneError')
if 'email' in user_data.keys() or 'username' in user_data.keys() or 'telephone' in user_data.keys():
if user != user_instance and errors:
return False, errors
elif not user or user == user_instance:
return True, None
return True, None
class ChildEditor(APIView):
def put(self, req):
token = get_object_or_404(
KeysToken.objects.all(),
token=req.data['token'])
user = token.user
child_rec = get_object_or_404(
ChildRecord.objects.all(),
serial_number=req.data['id'])
if token.is_valid() and child_rec.parent == user:
data = req.data['data']
rec = ChildRecordSerializer(
instance=child_rec, data=data, partial=True)
if rec.is_valid():
rec.save()
parent_record = Record.objects.get(owner=user)
json_decoder = JSONDecoder()
children = json_decoder.decode(parent_record.children)
if rec.is_valid() and (
data['first_name'] or data['last_name'] or data['second_name']):
for each in children:
if each['serial_number'] == req.data['id']:
tmp = f'{rec.data["last_name"]} '
tmp += f'{rec.data["first_name"]} '
tmp += f'{rec.data["second_name"]}'
each['name'] = tmp
parent_record.children = dumps(
children, separators=(
',', ':'), ensure_ascii=False)
parent_record.save()
token.update_activity()
return Response(status=200)
else:
return Response(status=403)
| cann1neof/mrecord | backend/api/views/view_edit.py | view_edit.py | py | 6,173 | python | en | code | 1 | github-code | 6 |
27466136159 | # List
transports = ["airplane", "car", "ferry"]
modes = ["air", "ground", "water"]
# Lists contain simple data (index based item) and can be edited after being assigned.
# E.g. as transport types are not as limited as in this list, it can be updated by adding or removing.
# Let's create a couple of functions for adding and removing items, and use them.
print("\nLIST DATA TYPE")
print("--------------\n") # just for formatting the output in order to keep it clean
# Adding items to the list
def add_transport(): # first parameter is for the name, second one is for the mode of the transport
global transports
global modes
message = input("Do you want to ADD a new transport? [Type yes/no]: ").lower().strip()
# validating the input by lower-casing the letters and shrinking the spaces
if message == "yes":
name = input(" Insert the transport name: ")
if name in transports:
print("\n!!! This transport is already in the list\n")
add_transport()
else:
mode = input(" Insert the transportation mode: ")
transports.append(name) # append() method is used to add a new item
modes.append(mode)
print("\nSuccessfully added!")
print("--------------\n") # just for formatting the output in order to keep it clean
add_transport()
elif message == "no":
print("--------------\n") # just for formatting the output in order to keep it clean
return
else:
print("\n!!! Please, answer properly\n")
add_transport()
add_transport() # calling the function to add a new transport
# Removing items from the list
def remove_transport(): # receives an integer as an index
global transports
global modes
message = input("Do you want to REMOVE any transport? [Type yes/no]: ").lower().strip()
# validating the input by lower-casing the letters and shrinking the spaces
if message == "yes":
print("You have the transports below:")
for number, transport in enumerate(transports, 1): # looping the enumerated list to print the items
print("", str(number) + ")", transport)
removing_index = input("Insert the number of the transport you want to delete: ")
try: # trying to convert the input into integer
index = int(removing_index)
transports.pop(index - 1) # since enumeration has started with 1, we should subtract 1
modes.pop(index - 1)
print("\nSuccessfully removed!")
print("--------------\n") # just for formatting the output in order to keep it clean
remove_transport()
except ValueError:
print("\n!!! Please, insert only numbers\n")
remove_transport()
elif message == "no":
print("--------------\n") # just for formatting the output in order to keep it clean
return
else:
print("\n!!! Please, answer properly\n")
remove_transport()
remove_transport() # calling the function to remove an existing transport
# Check the type of the transport
# zip() can be used to merge relative items of two lists according to their index.
def check_transport():
global transports
global modes
message = input("Do you want to CHECK the mode of any transport? [Type yes/no]: ").lower().strip()
# validating the input by lower-casing the letters and shrinking the spaces
if message == "yes":
print("Choose a transport to check:")
for number, transport in enumerate(transports, 1):
print("", str(number) + ")", transport)
checking_index = input("Insert the number of the transport you want to check: ")
try:
index = int(checking_index)
print("\n", transports[index-1][0].upper() + transports[index-1][1:], "moves on the", modes[index-1] + ".")
print("--------------\n") # just for formatting the output in order to keep it clean
check_transport()
except ValueError:
print("\n!!! Please, insert only numbers!\n")
check_transport()
elif message == "no":
print("--------------\n") # just for formatting the output in order to keep it clean
print(" Thank you for using this app! Good bye!")
return
else:
print("\n!!! Please, answer properly!\n")
check_transport()
check_transport() # calling the function to check the mode af a transport
| 00009115/CSF.CW1.00009115 | lists/lists.py | lists.py | py | 4,519 | python | en | code | 1 | github-code | 6 |
38020552913 | # -*- coding: utf-8 -*-
"""
Created on Sun May 9 23:54:21 2021
@author: zacha
"""
import Customer
import Department
def main():
#Testing Customer class with inputs
nam = input("Enter Name: ")
stre = input("Enter Street: ")
cit = input("Enter City: ")
zipc = input("Enter Zip Code: ")
#Testing Department class with inputs
deptname = input("Enter Department Name: ")
deptnum = input("Enter Department Number: ")
descr = input("Enter Description: ")
deptid = input("Enter Department ID: ")
custo = Customer.Customer(nam,stre,cit,zipc)
dept = Department.department(deptname,deptnum,descr,deptid)
print("Data entered: ")
print("Customer name: ", custo.get_name())
print("Street name: ", custo.get_street())
print("Department name: ", dept.get_department_name())
print("Department number: ", dept.get_department_number())
main() | Bryan-Tuck/Shopping-System | ShoppingSystem/Tests/CustomerDeptIntegration.py | CustomerDeptIntegration.py | py | 932 | python | en | code | 0 | github-code | 6 |
22185534420 | import numpy as np
import pandas as pd
from collections import defaultdict
import matplotlib.pyplot as plt
from datetime import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
import os, sys
class SDAE(nn.Module):
def __init__(self, input_dim, hidden_dim, embed_dim):
super(SDAE, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.embed_dim = embed_dim
self.enc1 = nn.Linear(input_dim, hidden_dim)
self.enc2 = nn.Linear(hidden_dim, hidden_dim)
self.enc3 = nn.Linear(hidden_dim, embed_dim)
self.dec1 = nn.Linear(embed_dim, hidden_dim)
self.dec2 = nn.Linear(hidden_dim, hidden_dim)
self.dec3 = nn.Linear(hidden_dim, input_dim)
def forward(self, x):
x = F.relu(self.enc1(x))
x = F.relu(self.enc2(x))
latent = F.relu(self.enc3(x))
x = F.relu(self.dec1(latent))
x = F.relu(self.dec2(x))
x = self.dec3(x)
return latent, x
class CDL:
def __init__(self, train_imp, test_imp, input_dim, hidden_dim, dim_f, dataloader, seed, device, config):
self.dim_f = dim_f
self.user_num = train_imp.shape[0]
self.item_num = train_imp.shape[1]
self.input_dim = input_dim
self.R_tr = train_imp
self.R_tst = test_imp
self.C = np.where(self.R_tr > 0, 1, 0)
self.C_u = np.zeros((self.item_num, self.item_num))
self.C_i = np.zeros((self.user_num, self.user_num))
np.random.seed(seed)
self.X = np.random.standard_normal((self.user_num, dim_f))
self.Y = np.random.standard_normal((self.item_num, dim_f))
self.loss_tr = defaultdict(float)
self.loss_ae = defaultdict(float)
self.loss_tst = defaultdict(float)
self.ae = SDAE(input_dim=input_dim, hidden_dim=hidden_dim, embed_dim=dim_f).to(device)
self.optimizer = optim.Adam(self.ae.parameters(), lr=config.learning_rate, weight_decay=config.lambda_w)
self.dataloader = dataloader
self.lambda_u = config.lambda_u
self.lambda_w = config.lambda_w
self.lambda_v = config.lambda_v
self.lambda_n = config.lambda_n
self.device = device
self.config = config
def ae_train(self):
latent_np = np.zeros((self.item_num, self.dim_f))
loss_ae = []
for batch in self.dataloader:
y = batch['clean'].to(self.device)
x = batch['corrupt'].to(self.device)
idx = batch['idx']
latent, pred = self.ae(x)
latent_ = latent.detach().cpu().numpy()
latent_np[idx.numpy()] = latent_
loss = self.loss_fn(pred, y, idx.to(self.device), latent_)
loss.backward()
self.optimizer.step()
loss_ae.append(loss.item())
return latent_np, np.mean(loss_ae)
def fit(self):
start = datetime.now()
for epoch in range(self.config.epochs):
start_epoch = datetime.now()
self.ae.train()
self.latent_feat, self.loss_ae[epoch] = self.ae_train()
n = 0
for u in range(self.user_num):
yty = np.dot(self.Y.T, self.Y)
self.X[u, :] = self.update_user_vector(u, yty)
for i in range(self.item_num):
xtx = np.dot(self.X.T, self.X)
self.Y[i, :] = self.update_item_vector(i, xtx)
phat = self.scoring()
train_loss = self.evaluate(train_eval=True)
test_loss = self.evaluate(train_eval=False)
self.loss_tr[epoch] = train_loss
self.loss_tst[epoch] = test_loss
print(f'EPOCH {epoch+1} : TRAINING RANK {self.loss_tr[epoch]:.5f}, VALID RANK {self.loss_tst[epoch]:.5f}')
print(f'Time per one epoch {datetime.now() - start_epoch}')
end = datetime.now()
print(f'Training takes time {end-start}')
def scoring(self):
return np.dot(self.X, self.Y.T)
def update_user_vector(self, u, yty):
np.fill_diagonal(self.C_u, (self.C[u, :] - 1))
comp1 = yty
comp2 = np.dot(self.Y.T, self.C_u).dot(self.Y)
comp3 = np.identity(self.config.dim_f) * self.config.lambda_u
comp = np.linalg.inv(comp1 + comp2 + comp3)
self.C_u = self.C_u + np.identity(self.C_u.shape[0])
comp = np.dot(comp, self.Y.T).dot(self.C_u)
return np.dot(comp, self.R_tr[u, :])
def update_item_vector(self, i, xtx):
np.fill_diagonal(self.C_i, (self.C[:, i] - 1))
comp1 = xtx
comp2 = np.dot(self.X.T, self.C_i).dot(self.X)
comp3 = np.identity(self.config.dim_f) * self.config.lambda_v
comp = np.linalg.inv(comp1 + comp2 + comp3)
self.C_i = self.C_i + np.identity(self.C_i.shape[0])
comp4 = self.X.T.dot(self.C_i).dot(self.R_tr[:, i])
comp5 = self.lambda_v * self.latent_feat[i, :]
return np.dot(comp, comp4+comp5)
def loss_fn(self, pred, xc, idx, latent_feat):
X = torch.tensor(self.X).to(self.device)
Y = torch.tensor(self.Y).to(self.device)[idx, :]
R = torch.tensor(self.R_tr).float().to(self.device)[:, idx]
C = torch.tensor(self.C).float().to(self.device)[:, idx]
latent = torch.tensor(latent_feat).to(self.device)
comp1 = (X**2).sum(axis=1).sum() * self.lambda_u/2
comp2 = ((Y - latent)**2).sum(axis=1).sum() * self.lambda_v/2
comp3 = ((pred - xc)**2).sum(axis=1).sum() * self.lambda_n/2
comp4 = torch.sum((torch.mm(X, Y.T) - R)**2 * C/2)
return comp1+comp2+comp3+comp4
def evaluate(self, train_eval):
if train_eval:
R = self.R_tr
else:
R = self.R_tst
phat = self.scoring()
rank_mat = np.zeros(phat.shape)
for u in range(self.user_num):
pred_u = phat[u, :] * -1
rank = pred_u.argsort().argsort()
rank = rank / self.item_num
rank_mat[u, :] = rank
return np.sum(R * rank_mat) / np.sum(R) | yeonjun-in/GNN_Recsys_paper | rec/CDL/model.py | model.py | py | 6,259 | python | en | code | 1 | github-code | 6 |
31209322270 | from src.mappers.event_mapper import EventMapper
from src.domain.entities.event import Event
from src.mappers.person_mapper import PersonMapper
from src.repositories.entities.event import Event as DataEvent
from src.repositories.entities.participation import Participation as DataParticipation
class EventRepository(object):
def update(self, event: Event):
data = DataEvent.update(name=event.name, group_name=event.group_name, link=event.link,
local_date=event.local_date, local_time=event.local_time, status=event.status)\
.where(DataEvent.id == event.id)
data.execute()
return self.get_by_id(int(event.id))
def get_by_id(self, id: int):
data_event = DataEvent.select().where(DataEvent.id == id).first()
if data_event:
domain_event = EventMapper.data_to_domain(data_event)
data_participations = DataParticipation.select().where(DataParticipation.event == id)
domain_event.persons = [PersonMapper.data_to_domain(data_participation.person) for data_participation in data_participations]
return domain_event
def get_all(self):
data_events = DataEvent.select()
domain_events = [EventMapper.data_to_domain(data_event) for data_event in data_events]
for domain_event in domain_events:
data_participations = DataParticipation.select().where(DataParticipation.event == domain_event.id)
domain_event.persons = [PersonMapper.data_to_domain(data_participation.person) for data_participation in
data_participations]
return domain_events
def insert(self, event):
data = DataEvent.create(id=event.id, name=event.name, group_name=event.group_name, link=event.link,
local_date=event.local_date, local_time=event.local_time, status=event.status)
data.save()
return self.get_by_id(int(event.id))
| GDGPetropolis/backend-event-checkin | src/repositories/event_repository.py | event_repository.py | py | 1,989 | python | en | code | 0 | github-code | 6 |
21835729444 | ''' (c) 2008 by the GunGame Coding Team
Title: gg_elimination
Version: 5.0.498
Description: Players respawn after their killer is killed.
Originally for ES1.3 created by ichthys:
http://addons.eventscripts.com/addons/view/3972
'''
# ==============================================================================
# IMPORTS
# ==============================================================================
# EventScripts imports
import es
import gamethread
# Python imports
import time
# GunGame imports
import gungamelib
# ==============================================================================
# ADDON REGISTRATION
# ==============================================================================
# Register this addon with EventScripts
info = es.AddonInfo()
info.name = 'gg_elimination (for GunGame5)'
info.version = '5.0.498'
info.url = 'http://gungame5.com/'
info.basename = 'gungame/included_addons/gg_elimination'
info.author = 'GunGame Development Team'
# ==============================================================================
# GLOBALS
# ==============================================================================
# Set up variables for use throughout gg_elimination
dict_addonVars = {}
dict_addonVars['roundActive'] = 0
dict_addonVars['currentRound'] = 0
# Player Database
dict_playersEliminated = {}
# ==============================================================================
# GAME EVENTS
# ==============================================================================
def load():
# Register addon with gungamelib
gg_elimination = gungamelib.registerAddon('gg_elimination')
gg_elimination.setDisplayName('GG Elimination')
gg_elimination.loadTranslationFile()
# Add dependencies
gg_elimination.addDependency('gg_turbo', 1)
gg_elimination.addDependency('gg_dead_strip', 1)
gg_elimination.addDependency('gg_dissolver', 1)
gg_elimination.addDependency('gg_knife_elite', 0)
# Get userids of all connected players
for userid in es.getUseridList():
dict_playersEliminated[str(userid)] = []
def unload():
# Unregister this addon with gungamelib
gungamelib.unregisterAddon('gg_elimination')
def es_map_start(event_var):
global dict_addonVars
# Reset round tracking
dict_addonVars['roundActive'] = 0
dict_addonVars['currentRound'] = 0
def round_start(event_var):
# Round tracking
dict_addonVars['roundActive'] = 1
dict_addonVars['currentRound'] += 1
# Reset all eliminated player counters
for player in dict_playersEliminated:
dict_playersEliminated[player] = []
gungamelib.msg('gg_elimination', '#all', 'RoundInfo')
def round_end(event_var):
# Set round inactive
dict_addonVars['roundActive'] = 0
def player_activate(event_var):
userid = event_var['userid']
# Create player dictionary
dict_playersEliminated[userid] = []
def player_disconnect(event_var):
userid = event_var['userid']
# Remove diconnecting player from player dict
if userid in dict_playersEliminated:
respawnEliminated(userid, dict_addonVars['currentRound'])
del dict_playersEliminated[userid]
def player_death(event_var):
# Check to see if the round is active
if not dict_addonVars['roundActive']:
return
# Get userid and attacker userids
userid = event_var['userid']
attacker = event_var['attacker']
# Was suicide?
if userid == attacker or attacker == '0':
gamethread.delayed(5, respawnPlayer, (userid, dict_addonVars['currentRound']))
gungamelib.msg('gg_elimination', userid, 'SuicideAutoRespawn')
# Was a teamkill?
elif event_var['es_userteam'] == event_var['es_attackerteam']:
gamethread.delayed(5, respawnPlayer, (userid, dict_addonVars['currentRound']))
gungamelib.msg('gg_elimination', userid, 'TeamKillAutoRespawn')
# Was a normal death
else:
# Add victim to the attackers eliminated players
dict_playersEliminated[attacker].append(userid)
# Tell them they will respawn when their attacker dies
index = gungamelib.getPlayer(attacker)['index']
gungamelib.saytext2('gg_elimination', userid, index, 'RespawnWhenAttackerDies', {'attacker': event_var['es_attackername']})
# Check if victim had any Eliminated players
gamethread.delayed(1, respawnEliminated, (userid, dict_addonVars['currentRound']))
# ==============================================================================
# HELPER FUNCTIONS
# ==============================================================================
def respawnPlayer(userid, respawnRound):
# Make sure the round is active
if not dict_addonVars['roundActive']:
return
# Check if respawn was issued in the current round
if dict_addonVars['currentRound'] != respawnRound:
return
# Make sure the player is respawnable
if not respawnable(userid):
return
index = gungamelib.getPlayer(userid)['index']
# Tell everyone that they are respawning
gungamelib.saytext2('gg_elimination', '#all', index, 'RespawningPlayer', {'player': gungamelib.getPlayer(userid).name})
# Respawn player
gungamelib.respawn(userid)
def respawnEliminated(userid, respawnRound):
# Check if round is over
if not dict_addonVars['roundActive']:
return
# Check if respawn was issued in the current round
if dict_addonVars['currentRound'] != respawnRound:
return
# Check to make sure that the userid still exists in the dictionary
if userid not in dict_playersEliminated:
return
# Check the player has any eliminated players
if not dict_playersEliminated[userid]:
return
# Set variables
players = []
index = 0
# Respawn all victims eliminated players
for playerid in dict_playersEliminated[userid]:
# Make sure the player exists
if not respawnable(playerid):
continue
# Respawn player
gungamelib.respawn(playerid)
# Add to message format
players.append('\3%s\1' % gungamelib.getPlayer(playerid).name)
# Get index
if not index:
index = gungamelib.getPlayer(playerid)['index']
# Tell everyone that they are respawning
gungamelib.saytext2('gg_elimination', '#all', index, 'RespawningPlayer', {'player': ', '.join(players)})
# Clear victims eliminated player list
dict_playersEliminated[userid] = []
def respawnable(userid):
# Check if player is on a team (checks for existancy also)
if gungamelib.isSpectator(userid):
return False
# Make sure the player is alive
if not gungamelib.isDead(userid):
return False
return True
| GunGame-Dev-Team/GunGame-Python | addons/eventscripts/gungame/included_addons/gg_elimination/gg_elimination.py | gg_elimination.py | py | 7,149 | python | en | code | 1 | github-code | 6 |
71994778748 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Bernoulli
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
import random
import math
import sys
import os
torch.manual_seed(0)
class armax_model(nn.Module):
def __init__(self, no_of_glucose_inputs = 10, no_of_insulin_inputs = 10, no_of_meal_inputs = 10):
output_dim = 1
super(armax_model, self).__init__()
self.glucose_weights = nn.Parameter(torch.randn((no_of_glucose_inputs, output_dim)))
self.insulin_weights = nn.Parameter(torch.randn((no_of_insulin_inputs, output_dim)))
self.meal_weights = nn.Parameter(torch.randn((no_of_meal_inputs, output_dim)))
self.bias = nn.Parameter(torch.randn((output_dim,)))
def forward(self, glucose, insulin, meal):
glucose_term = torch.matmul(glucose, self.glucose_weights)
# Enforcing insulin having negative effects
insulin_term = torch.matmul(insulin, -torch.abs(self.insulin_weights))
meal_term = torch.matmul(meal, self.meal_weights)
y = glucose_term + insulin_term + meal_term
return y
def fit_model(all_states, all_controls, all_next_states, glucose_normalizer, insulin_normalizer, meal_normalizer, filename):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
episode_count = 100
batch_size = 64
model = armax_model().to(device)
learning_rate = 1e-3
# criterion = nn.SmoothL1Loss()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr = learning_rate)
all_train_states = np.concatenate((all_states['main']['train'], all_states['omega']['train']), axis=0)
all_train_controls = np.concatenate((all_controls['main']['train'], all_controls['omega']['train']), axis=0)
all_train_next_states = np.concatenate((all_next_states['main']['train'], all_next_states['omega']['train']), axis=0)
T = 10
num_datapoints = len(all_train_states)
for episode in range(episode_count):
number_of_batches = math.ceil(float(num_datapoints) / float(batch_size))
total_loss = 0.0
for batch_index in range(number_of_batches):
start = batch_index * batch_size
end = min(start + batch_size, num_datapoints)
loss_list = []
optimizer.zero_grad()
# for entry in range(start, end):
# glucose_input = all_train_states[entry, :T] * glucose_normalizer
# glucose_input = torch.from_numpy(glucose_input).float().to(device)
# insulin_input = all_train_states[entry, T:2*T] * insulin_normalizer
# insulin_input = torch.from_numpy(insulin_input).float().to(device)
# meal_input = all_train_states[entry, 2*T:3*T] * meal_normalizer
# meal_input = torch.from_numpy(meal_input).float().to(device)
# target = all_train_next_states[entry, :] * glucose_normalizer
# target = torch.from_numpy(target).float().to(device)
# prediction = model.forward(glucose_input, insulin_input, meal_input)
# loss = criterion(prediction, target).to(device)
# loss_list.append(loss)
# # Computing loss for tracking
# total_loss += loss.item()
glucose_input = all_train_states[start:end, :T] * glucose_normalizer
glucose_input = torch.from_numpy(glucose_input).float().to(device)
insulin_input = all_train_states[start:end, T:2*T] * insulin_normalizer
insulin_input = torch.from_numpy(insulin_input).float().to(device)
meal_input = all_train_states[start:end, 2*T:3*T] * meal_normalizer
meal_input = torch.from_numpy(meal_input).float().to(device)
target = all_train_next_states[start:end, :] * glucose_normalizer
target = torch.from_numpy(target).float().to(device)
prediction = model.forward(glucose_input, insulin_input, meal_input)
loss = criterion(prediction, target).to(device)
# Computing loss for tracking
total_loss += loss.item() * (end-start)
loss.backward()
optimizer.step()
print("At episode - ", episode, " avg loss computed - ", total_loss / float(len(all_train_states)))
if (episode+1)%10 == 0 or episode == 0:
test_loss = test_model(model, all_states, all_controls, all_next_states, glucose_normalizer, insulin_normalizer, meal_normalizer, T)
print("At episode - ", episode, " avg test loss computed - ", test_loss )
torch.save(model.state_dict(), filename)
return model
def test_model(model, all_states, all_controls, all_next_states, glucose_normalizer, insulin_normalizer, meal_normalizer, T):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
all_test_states = np.concatenate((all_states['main']['test'], all_states['omega']['test']), axis=0)
all_test_controls = np.concatenate((all_controls['main']['test'], all_controls['omega']['test']), axis=0)
all_test_next_states = np.concatenate((all_next_states['main']['test'], all_next_states['omega']['test']), axis=0)
total_loss = 0.0
for index in range(len(all_test_states)):
glucose_input = all_test_states[index, :T] * glucose_normalizer
glucose_input = torch.from_numpy(glucose_input).float().to(device)
insulin_input = all_test_states[index, T:2*T] * insulin_normalizer
insulin_input = torch.from_numpy(insulin_input).float().to(device)
meal_input = all_test_states[index, 2*T:3*T] * meal_normalizer
meal_input = torch.from_numpy(meal_input).float().to(device)
target = all_test_next_states[index, :] * glucose_normalizer
target = torch.from_numpy(target).float().to(device)
prediction = model.forward(glucose_input, insulin_input, meal_input)
prediction = prediction.cpu().detach().numpy()[0]
loss = abs( prediction - target)**2
total_loss += loss
avg_error = total_loss / float(len(all_test_states))
return avg_error.item()
def extract_state_dict():
filename = os.path.join("./networks/", "diabetes_armax_model.nt")
model = torch.load(filename)
torch.save(model.state_dict(), "./networks/diabetes_armax_model_state_dict.nt")
| kaustubhsridhar/Constrained_Models | AP/armax_model_on_reformatted_data.py | armax_model_on_reformatted_data.py | py | 6,454 | python | en | code | 15 | github-code | 6 |
19541081496 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
df = pd.read_csv('Franchise_Dataset.csv')
df.head()
X =df.iloc[:, 1:2].values
y =df.iloc[:, 2].values
model = RandomForestRegressor(n_estimators = 10, random_state = 0)
model.fit(X, y)
y_pred =model.predict([[6]])
print(y_pred)
X_grid_data = np.arange(min(X), max(X), 0.01)
X_grid_data = X_grid_data.reshape((len(X_grid_data), 1))
plt.scatter(X, y, color = 'red')
plt.plot(X_grid_data,model.predict(X_grid_data), color = 'blue')
plt.title('Random Forest Regression')
plt.xlabel('Counter Sales')
plt.ylabel('Net Profit')
plt.show() | flawlesscode254/Linear-Regression-Assignment | three.py | three.py | py | 657 | python | en | code | 0 | github-code | 6 |
45017283256 | try:
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '../lib'))
import os, errno
import logging # http://www.onlamp.com/pub/a/python/2005/06/02/logging.html
from logging import handlers
import argparse
#sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'pysunspec'))
from datetime import datetime, date, time, timedelta
# import jsonpickle # pip install jsonpickle
import json
from sit_logger import SitLogger
from sit_constants import SitConstants
#from sit_date_time import SitDateTime
except ImportError as l_err:
print("ImportError: {0}".format(l_err))
raise l_err
class SitJsonConf(object):
# CONSTANTS
# VARIABLES
_logger = None
_config_dir = None #Setted by init
_config_file = None #File name only
_config_data = None # Where json.dump are put
# FUNCTIONS DEFINITION
def __init__(self, a_config_file_name=SitConstants.SIT_JSON_DEFAULT_CONFIG_FILE_NAME):
"""
Initialize
"""
self._config_dir = SitConstants.DEFAULT_CONF_DIR
self._config_file = a_config_file_name
if not os.path.isdir(self._config_dir):
raise Exception('init->Config dir {} does not exist, sudo mkdir -m 777 {}'.format(self._config_dir, self._config_dir))
try:
self._logger = SitLogger().new_logger(__name__)
if __name__ == '__main__':
self.init_arg_parse()
self.read_config(self.configuration_file_path())
except OSError as l_e:
self._logger.warning("init-> OSError, probably rollingfileAppender:{}".format(l_e))
if l_e.errno != errno.ENOENT:
raise l_e
except Exception as l_e:
self._logger.error('Error in init: {}'.format(l_e))
raise l_e
def configuration_file_path(self):
"""
"""
l_res = os.path.join(self._config_dir, self._config_file)
return l_res
def read_config(self, a_config_file_path=None):
"""
puts into self._config_data json data
"""
if a_config_file_path is None:
l_config_file_path = self.configuration_file_path()
else:
l_config_file_path = a_config_file_path
with open(l_config_file_path, "r") as l_file:
self._config_data = json.load(l_file)
def item(self, a_key):
"""
returns value of given key exception if not found
"""
l_res = None
return l_res
# SCRIPT ARGUMENTS
def init_arg_parse(self):
"""
Parsing arguments
"""
self._logger.debug('init_arg_parse-> begin')
self._parser = argparse.ArgumentParser(description='Actions with sunspec through TCP')
self._add_arguments()
l_args = self._parser.parse_args()
self._args = l_args
def _add_arguments(self):
"""
Add arguments to parser (called by init_arg_parse())
"""
self._parser.add_argument('-v', '--verbose', help='increase output verbosity', action="store_true")
self._parser.add_argument('-u', '--update_leds_status', help='Updates led status according to spec', action="store_true")
self._parser.add_argument('-t', '--test', help='Runs test method', action="store_true")
#self._parser.add_argument('-u', '--base_url', help='NOT_IMPLEMENTED:Gives the base URL for requests actions', nargs='?', default=self.DEFAULT_BASE_URL)
l_required_named = self._parser.add_argument_group('required named arguments')
# l_required_named.add_argument('-i', '--host_ip', help='Host IP', nargs='?', required=True)
# l_required_named.add_argument('-u', '--slave_address', help='Slave address of modbus device', nargs='?', required=True)
l_required_named.add_argument('-m', '--host_mac', help='Host MAC', nargs='?', required=True)
# l_required_named.add_argument('-l', '--longitude', help='Longitude coordinate (beware timezone is set to Chile)', nargs='?', required=True)
# l_required_named.add_argument('-a', '--lattitude', help='Lattitude coordinate (beware timezone is set to Chile)', nargs='?', required=True)
# l_required_named.add_argument('-d', '--device_type', help='Device Type:' + ('|'.join(str(l) for l in self.DEVICE_TYPES_ARRAY)), nargs='?', required=True)
def execute_corresponding_args( self ):
"""
Parsing arguments and calling corresponding functions
"""
if self._args.verbose:
self._logger.setLevel(logging.DEBUG)
else:
self._logger.setLevel(logging.INFO)
if self._args.test:
self.test()
#if self._args.store_values:
# TEST
def test(self):
"""
Test function
"""
try:
self._logger.info("################# BEGIN #################")
self._logger.info("--> ************* device models *************: {}".format(l_d.models)) #Lists properties to be loaded with l_d.<property>.read() and then access them
except Exception as l_e:
self._logger.exception("Exception occured: {}".format(l_e))
print('Error: {}'.format(l_e))
self._logger.error('Error: {}'.format(l_e))
sys.exit(1)
#################### END CLASS ######################
def main():
"""
Main method
"""
#logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, filemode="a+", format="%(asctime)-15s %(levelname)-8s %(message)s")
logger = logging.getLogger(__name__)
try:
l_obj = SitJsonConf()
l_obj.execute_corresponding_args()
# l_id.test()
except KeyboardInterrupt:
logger.exception("Keyboard interruption")
except Exception as l_e:
logger.exception("Exception occured:{}".format(l_e))
raise l_e
#Call main if this script is executed
if __name__ == '__main__':
main()
| phgachoud/sty-pub-raspi-modbus-drivers | lib/sit_json_conf.py | sit_json_conf.py | py | 5,275 | python | en | code | 0 | github-code | 6 |
26774631311 | import pygame
from sys import exit
import numpy as np
import copy as cp
import math
import random as rd
import time
class GameState:
def __init__(self, board):
self.board = board
self.end=-1
self.children = []
self.parent = None
self.parentPlay = None # (play, movtype)
self.parentCell = None
self.numsimulation=0
self.mctsv=0
self.mctss=0
self.uct=0
def createChildren(self, player_id):
differentPlayBoards = []
for i in range(len(self.board)):
for j in range(len(self.board)):
if self.board[j][i] == player_id:
moves = get_moves(self, (i,j))
for mov in moves:
if moves[mov][0]:
newboard = cp.deepcopy(self.board)
play = (i+mov[0], j+mov[1])
if moves[mov][1] == 1: #movtype
newboard[play[1]][play[0]] = player_id
elif moves[mov][1] == 2:
newboard[play[1]][play[0]] = player_id
newboard[j][i] = 0
if newboard not in differentPlayBoards:
differentPlayBoards.append(newboard)
newboard = get_and_apply_adjacent(play, newboard, player_id)
newState = GameState(newboard)
newState.parentCell = (i,j)
newState.parentPlay = (play, moves[mov][1])
newState.parent = self
self.children.append(newState)
def evaluatePlay_mcts(game,board,play,cell,player):
s1=1
s2=0.4
s3=0.7
s4=0.4
soma=0
vec=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]
if play[1] == 1:
soma+=s3
for mov in vec:
if not (play[0][0]<1 or play[0][0]>len(game.board)-1-1 or play[0][1]<1 or play[0][1]>len(game.board)-1-1):
if board[play[0][0]+mov[0]][play[0][1]+mov[1]]==3-player:
soma+=s1
if board[play[0][0]+mov[0]][play[0][1]+mov[1]]==player:
soma+=s2
elif play[1] == 2:
for mov in vec:
if not (play[0][0]<1 or play[0][0]>len(game.board)-1-1 or play[0][1]<1 or play[0][1]>len(game.board)-1-1):
if board[play[0][1]+mov[1]][play[0][0]+mov[0]]==3-player:
soma+=s1
if board[play[0][1]+mov[1]][play[0][0]+mov[0]]==player:
soma+=s2
if not (cell[0]<1 or cell[0]>len(game.board)-1-1 or cell[1]<1 or cell[1]>len(game.board)-1-1):
if board[cell[1]+mov[1]][cell[0]+mov[0]]==player:
soma-=s4
return soma
def final_move(game,board,play,player): #### função que checka se o estado não tem children
#print(player,'final')
gamenp=np.array(board)
#print(gamenp,'nparray')
if np.count_nonzero(gamenp==(3-player))==0:
return (True,player)
if np.count_nonzero(gamenp==(player))==0:
return (True,3-player)
if np.count_nonzero(gamenp==0) != 0:
return (False,-1)
if np.count_nonzero(gamenp==0) == 0:
count_p=np.count_nonzero(gamenp==player)
count_o=np.count_nonzero(gamenp==(3-player))
if count_p > count_o:
return (True,player)
if count_o > count_p:
return (True,3-player)
return (True,0)
def evaluatePlay_minmax(game,board,play,cell,player,values): #### heurística para o minimax
s1=values[0]
s2=values[1]
s3=values[2]
s4=values[3]
soma=0
vec=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]
#print(player,'pre final')
final=final_move(game,board,play,player)
#print(final)
if final[0]: #### ver que tipo de fim é e retornar o valor
if final[1]==player:
return (math.inf)
if final[1]==3-player:
return (-math.inf)
if final[1]==0:
return 0
if play[1] == 1:
soma+=s3
for mov in vec:
if not (play[0][0]<1 or play[0][0]>len(game.board)-1-1 or play[0][1]<1 or play[0][1]>len(game.board)-1-1):
if board[play[0][0]+mov[0]][play[0][1]+mov[1]]==3-player:
soma+=s1
if board[play[0][0]+mov[0]][play[0][1]+mov[1]]==player:
soma+=s2
elif play[1] == 2:
for mov in vec:
if not (play[0][0]<1 or play[0][0]>len(game.board)-1-1 or play[0][1]<1 or play[0][1]>len(game.board)-1-1):
if board[play[0][1]+mov[1]][play[0][0]+mov[0]]==3-player:
soma+=s1
if board[play[0][1]+mov[1]][play[0][0]+mov[0]]==player:
soma+=s2
if not (cell[0]<1 or cell[0]>len(game.board)-1-1 or cell[1]<1 or cell[1]>len(game.board)-1-1):
if board[cell[1]+mov[1]][cell[0]+mov[0]]==player:
soma-=s4
return soma
def randomplay(game, player):
game.createChildren(player)
r = rd.randint(0,len(game.children)-1)
return game.children[r]
def implementar_montecarlos(game,player):
C=1.5
game.createChildren(player)
bestchildren=[]
Sbasic=100
for child in game.children:
childnp=np.array(child.board)
child.mctss=Sbasic*(1+0.1*(np.count_nonzero(childnp==player)))
child.mctsv=montecarlots(int(child.mctss),child,player)
child.numsimulation+=child.mctss
if len(bestchildren)<=5:
bestchildren.append(child)
else:
for bchild in bestchildren:
if child.mctsv>bchild.mctsv:
bestchildren.remove(bchild)
bestchildren.append(child)
for child in bestchildren:
child.mctsv+=montecarlots(int(child.mctss),child,player)
child.numsimulation+=child.mctss
bestchildren=[]
for child in game.children:
child.uct=child.mctsv+C*(math.sqrt(1/(child.numsimulation)))
if len(bestchildren)<=3:
bestchildren.append(child)
else:
for bchild in bestchildren:
if child.uct>bchild.uct:
bestchildren.remove(bchild)
bestchildren.append(child)
for child in bestchildren:
child.mctsv+=montecarlots(int((child.mctss)/2),child,player)
bestchildren=[]
for child in game.children:
if len(bestchildren)==0:
bestchildren.append(child)
else:
if child.mctsv>bestchildren[0].mctsv:
bestchildren.pop(0)
bestchildren.append(child)
return bestchildren[0]
def montecarlots(numSimulations, game,player):
gamenp=np.array(game.board)
E=np.count_nonzero(gamenp==player)-np.count_nonzero(gamenp==(3-player))
for i in range(numSimulations):
player_hid=player
board=cp.deepcopy(game.board)
while game.end == -1 and game.end<10:
if player_hid == 1:
game.createChildren(player_hid)
board = randomplay(game,player_hid) #para testar os algoritmos da AI é só trocar aqui a função pelo algoritmo desejado
game = GameState(board)
player_hid = switchPlayer(player_hid)
elif player_hid == 2:
game.createChildren(player_hid)
board = randomplay(game,player_hid) #igual ao comentario acima
game = GameState(board)
player_hid = switchPlayer(player_hid)
game.end = objective_testmcts(game, player_hid)
if game.end-10==player_hid:
E+=500
elif game.end-10==3-player_hid:
E-=500
elif game.end==player_hid:
E+=50
elif game.end==3-player_hid:
E-=50
return E
def greedy(game,player):
bestPlay = ([], -math.inf) #random tuple where the 2nd element holds the best play evaluation and the 1st holds its board
game.createChildren(player)
for state in game.children: #play[0] -> (i,j) || play][1] -> movType
board = cp.deepcopy(state.board)
value=evaluatePlay_mcts(state,board,state.parentPlay,state.parentCell,player)
if value > bestPlay[1]:
if state.parentPlay[1] == 1:
board[state.parentPlay[0][1]][state.parentPlay[0][0]] = player
elif state.parentPlay[1] == 2:
board[state.parentCell[1]][state.parentCell[0]] = 0
board[state.parentPlay[0][1]][state.parentPlay[0][0]] = player
board = get_and_apply_adjacent((state.parentPlay[0][0], state.parentPlay[0][1]), board, player)
bestPlay = (board, value)
return GameState(bestPlay[0])
def implement_minimax(game,player,playerAI):
max_depth = 5
absodepth=max_depth
result=minimaxabc(game,max_depth,absodepth,player,playerAI,-math.inf,math.inf)
newresult = result[0]
depth = result[2]
for _ in range(max_depth-depth-1):
newresult = newresult.parent
return newresult
def minimaxabc(game, max_depth,absodepth, player, playerAI, alpha, beta):
game.createChildren(player)
if max_depth==0 or game.children == []:
values = (1.0, 0.4, 0.7, 0.4)
board = cp.deepcopy(game.board)
#print(player,'pre evaluate')
value=(game,evaluatePlay_minmax(game,board,game.parentPlay,game.parentCell,player,values), max_depth)
#print(value[0].board,' ',value[1],'depth ',max_depth)
return value
if player == 3-playerAI:
value =(GameState([]), math.inf,absodepth)
for state in game.children:
evaluation = minimaxabc(state, max_depth - 1,absodepth, 3-player, playerAI, alpha, beta)
#print(evaluation[0].board,' ',evaluation[1],'minimizer maxdepth %d' % max_depth)
if evaluation[1]<value[1]:
value=evaluation
beta = min(beta, evaluation[1])
if beta <= alpha:
break
return value
value =(GameState([]), -math.inf,absodepth)
for state in game.children:
evaluation = minimaxabc(state, max_depth - 1,absodepth, 3-player, playerAI, alpha, beta)
#print(evaluation[0].board,' ',evaluation[1], 'maximizer maxdepth %d' % max_depth)
if evaluation[1]>value[1]:
value=evaluation
alpha = max(alpha, evaluation[1])
if beta <= alpha:
break
return value
#i=y and j=x : tuples are (y,x)
def get_moves(game,cell):
vect = [(1,0),(2,0),(1,1),(2,2),(1,-1),(2,-2),(-1,0),(-2,0),(-1,1),(-2,-2),(0,1),(0,2),(0,-1),(0,-2),(-1,-1),(-2,2)]
#moves é um dicionario onde a chave de cada elemento é uma lista com a validade do mov (True/False) no indice 0 e o tipo de movimento no indice 1
moves={}
for mov in vect:
play=(cell[0]+mov[0],cell[1]+mov[1])
if play[0]<0 or play[0]>len(game.board)-1 or play[1]<0 or play[1]>len(game.board)-1 or game.board[play[1]][play[0]]!=0:
moves[mov]=[False]
else:
moves[mov]=[True]
if 1 in mov or -1 in mov:
moves[mov].append(1)
elif 2 in mov or -2 in mov:
moves[mov].append(2)
return moves
#draws the board on screen
def drawBoard(game, screen):
n = len(game.board)
screen.fill((255,255,255)) #background branco
#desenha frame do tabuleiro
pygame.draw.line(screen, (0,0,0), (0,0), (800,0), 2)
pygame.draw.line(screen, (0,0,0), (0,0), (0,800), 2)
pygame.draw.line(screen, (0,0,0), (0,798), (800,798), 2)
pygame.draw.line(screen, (0,0,0), (798, 0), (798,800), 2)
#desenha linhas do tabuleiro
for i in range(1,n):
#linhas verticais
pygame.draw.line(screen, (0,0,0), (800*i/n,0), (800*i/n,800), 2)
#linhas horizontais
pygame.draw.line(screen, (0,0,0), (0,800*i/n), (800,800*i/n), 2)
def drawPieces(game, screen):
n = len(game.board)
for i in range(n):
for j in range(n):
#desenha peças do jogador 1
if game.board[j][i] == 1:
pygame.draw.circle(screen, (0,0,255), ((800*i/n)+800/(2*n), (800*j/n)+800/(2*n)), 800/(3*n))
#desenha peças do jogador 2
if game.board[j][i] == 2:
pygame.draw.circle(screen, (0,150,0), ((800*i/n)+800/(2*n), (800*j/n)+800/(2*n)), 800/(3*n))
#desenha quadrados onde não se pode jogar
if game.board[j][i] == 8:
pygame.draw.rect(screen, (0,0,0), (800*i/n, 800*j/n, 800/n + 1, 800/n + 1))
#mostrar o resultado do jogo graficamente
def drawResult(game, screen):
if game.end == -1:
return None
font = pygame.font.Font('freesansbold.ttf', 32)
pygame.draw.rect(screen, (0,0,0), (120, 240, 560, 320))
pygame.draw.rect(screen, (255,255,255), (140, 260, 520, 280))
if game.end == 0:
text = font.render("Empate!", True, (0,0,0))
elif game.end == 1:
text = font.render("Jogador 1 vence!", True, (0,0,255))
elif game.end == 2:
text = font.render("Jogador 2 vence!", True, (0,150,0))
text_rect = text.get_rect(center=(400, 400))
screen.blit(text, text_rect)
#return the coordinates of the mouse in the game window
def mousePos(game):
click = pygame.mouse.get_pos()
n = len(game.board)
i = int(click[0]*n/800)
j = int(click[1]*n/800)
coord=(i,j)
return coord
#shows the selected cell on screen
def showSelected(game, screen, coord, player_id):
n = len(game.board)
i=coord[0]
j=coord[1]
#selectedType é um dicionario onde cada elemento é um dos quadrados onde se pode jogar e cuja chave é o tipo de movimento
selectedType = {}
if game.board[j][i] == player_id:
#desenha as cell possiveis de se jogar do player id
if player_id == 1:
selectedCellRGB = (173,216,230) #azul claro
elif player_id == 2:
selectedCellRGB = (144,238,144) #verde claro
pygame.draw.rect(screen, selectedCellRGB, (800*i/n + 2, 800*j/n + 2, 800/n - 2 , 800/n - 2))
moves=get_moves(game,coord)
for mov in moves:
if moves[mov][0]:
play=(coord[0]+mov[0],coord[1]+mov[1])
selectedType[play] = moves[mov][1]
pygame.draw.rect(screen, selectedCellRGB, (800*play[0]/n + 2, 800*play[1]/n + 2, 800/n - 2 , 800/n - 2))
return selectedType
def get_and_apply_adjacent(targetCell, newBoard, player_id):
vectors = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]
#adjacent é um dicionario que vai ter como elemento cada cell que esta a volta da targetCell e cujos elementos sao True/False
#se essa cell tiver/não tiver uma peça do oponente
adjacent = {}
for vect in vectors:
play=(targetCell[0]+vect[0],targetCell[1]+vect[1])
if play[0]<0 or play[0]>len(newBoard)-1 or play[1]<0 or play[1]>len(newBoard)-1 or newBoard[play[1]][play[0]] != switchPlayer(player_id):
adjacent[vect] = False
else:
adjacent[vect] = True
for adj in adjacent:
if adjacent[adj]:
adjCell = (targetCell[0]+adj[0], targetCell[1]+adj[1])
newBoard[adjCell[1]][adjCell[0]] = player_id
return newBoard
def skip(game,player):
game.createChildren(player)
if len(game.children) == 0:
return True
return False
def objective_testmcts(game,player): #atualizar count
gamenp=np.array(game.board)
if np.count_nonzero(gamenp==0)==0:
if np.count_nonzero(gamenp==player)>np.count_nonzero(gamenp==(3-player)):
return player
if np.count_nonzero(gamenp==player)<np.count_nonzero(gamenp==(3-player)):
return 3-player
else:
return 0
if np.count_nonzero(gamenp==player)==0:
return (3-player+10)
for j in range(len(gamenp)):
for i in range(len(gamenp)):
if gamenp[j][i]==player:
if True in get_moves(game,(i,j)):
return -1
else:
return (3-player+10)
def objective_test(game,player): #atualizar count
gamenp=np.array(game.board)
if np.count_nonzero(gamenp==(3-player))==0:
return player
if np.count_nonzero(gamenp==0) != 0:
return -1
if np.count_nonzero(gamenp==0) == 0:
count_p=np.count_nonzero(gamenp==player)
count_o=np.count_nonzero(gamenp==(3-player))
if count_p > count_o:
return player
if count_o > count_p:
return (3-player)
return 0
def executeMov(game, initialCell, targetCell, selectedType, player_id):
newBoard = cp.deepcopy(game.board)
if targetCell in selectedType:
movType = selectedType[targetCell]
#movimento tipo 1
if movType == 1:
newBoard[targetCell[1]][targetCell[0]] = player_id
newBoard = get_and_apply_adjacent(targetCell, newBoard, player_id)
#movimento tipo 2
elif movType == 2:
newBoard[targetCell[1]][targetCell[0]] = player_id
newBoard[initialCell[1]][initialCell[0]] = 0
newBoard = get_and_apply_adjacent(targetCell, newBoard, player_id)
newGame = GameState(newBoard)
return newGame
def switchPlayer(player_id):
return 3-player_id
#game mode Human vs Human
def jogo_Humano_Humano(game, screen):
player_id = 1
clickState = False
while game.end==-1:
drawPieces(game, screen)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
exit()
#verificar se o jogador está cercado / não tem jogadas possiveis e tem de passar a jogada
if not skip(game,player_id):
#escolher a peca para jogar e as possiveis plays
if event.type == pygame.MOUSEBUTTONDOWN and clickState == False:
drawBoard(game, screen)
coord = mousePos(game)
selected = showSelected(game, screen, coord, player_id)
clickState = True
drawPieces(game, screen)
#fazer o movimento da jogada
elif event.type == pygame.MOUSEBUTTONDOWN and clickState == True:
targetCell = mousePos(game)
prevBoard = cp.deepcopy(game.board)
game = executeMov(game, coord, targetCell, selected, player_id)
if not (np.array_equal(prevBoard,game.board)):
player_id = switchPlayer(player_id)
clickState=False
drawBoard(game, screen)
drawPieces(game, screen)
else:
player_id = switchPlayer(player_id)
game.end = objective_test(game,player_id)
#to display the winner
while game.end != -1:
drawResult(game,screen)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.update()
pygame.display.update()
def jogo_Humano_AI(game, screen, algorithm):
player_id = 1
clickState = False
while game.end==-1:
drawPieces(game, screen)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
exit()
#verificar se o jogador está cercado / não tem jogadas possiveis e tem de passar a jogada
if not skip(game,player_id):
if player_id == 1:
#escolher a peca para jogar e as possiveis plays
if event.type == pygame.MOUSEBUTTONDOWN and clickState == False:
drawBoard(game, screen)
coord = mousePos(game)
selected = showSelected(game, screen, coord, player_id)
clickState = True
drawPieces(game, screen)
#fazer o movimento da jogada
elif event.type == pygame.MOUSEBUTTONDOWN and clickState == True:
targetCell = mousePos(game)
prevBoard = cp.deepcopy(game.board)
game = executeMov(game, coord, targetCell, selected, player_id)
if not (np.array_equal(prevBoard,game.board)):
player_id = switchPlayer(player_id)
clickState=False
drawBoard(game, screen)
drawPieces(game, screen)
else:
if algorithm == 1:
game = implement_minimax(game,player_id, player_id)
elif algorithm == 2:
game = implementar_montecarlos(game,player_id)
elif algorithm == 3:
game = greedy(game,player_id)
elif algorithm == 4:
game = randomplay(game, player_id)
drawBoard(game, screen)
drawPieces(game, screen)
player_id = 1
else:
player_id = switchPlayer(player_id)
game.end = objective_test(game,player_id)
#to display the winner
while game.end != -1:
drawResult(game,screen)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.update()
pygame.display.update()
#sets the game window
def setScreen():
width = 800
height = 800
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Ataxx")
return screen
#abre um ficheiro com um mapa do tabuleiro a ser usado no jogo e cria o estado/objeto inicial
def readBoard(ficheiro):
f = open(ficheiro, "r")
n = int(f.readline())
board = []
for i in range(n):
board.append(list(map(int, f.readline().split())))
f.close()
return GameState(board)
#pede ao user para escolher o tabuleiro que pretende usar
def chooseBoard():
#todos os ficheiros com tabuleiros devem ter nome do tipo "tabX.txt"
tableNum = input("Escolha o número do tabuleiro que quer usar para o jogo!\n1) 10x10\n2) 8x8\n3) 6x6\n4) 5x5\n5) 12x12\nTabuleiro: ")
table = "tab"+tableNum+".txt"
return table
def chooseMode():
mode = int(input("Escolha o modo de jogo!\n1) Humano vs Humano\n2) Humano vs AI\nModo: "))
return mode
def chooseAI():
algorithm=int(input("Escolha o seu adversário!\n1) Minimax\n2) MonteCarloTreeSearch **VT**\n3) Greedy\n4) Random Play\nModo: "))
return algorithm
def playMode(game, screen, mode,algorithm):
if mode == 1:
jogo_Humano_Humano(game, screen)
elif mode == 2:
jogo_Humano_AI(game,screen,algorithm)
def simulacao(numSimulations):
playerTurns = [1,2,1,1]
empate = 0
w1 = 0
comeutodas1 = 0
w2 = 0
comeutodas2 = 0
for i in range(numSimulations):
table = "tabSim" + str(i+1) + ".txt"
#table = "tabSim18.txt"
game = readBoard(table)
#player_id = playerTurns[i%4]
player_id = 1
while game.end == -1:
if not skip(game,player_id):
if player_id == 1:
game = greedy(game,player_id) #para testar os algoritmos da AI é só trocar aqui a função pelo algoritmo desejado
player_id = switchPlayer(player_id)
elif player_id == 2:
game = implement_minimax(game, player_id, player_id) #igual ao comentario acima
player_id = switchPlayer(player_id)
else:
player_id = switchPlayer(player_id)
game.end = objective_test(game, player_id)
print(i+1)
if game.end == 0:
empate += 1
elif game.end == 1:
w1 += 1
gamenp = np.array(game.board)
if np.count_nonzero(gamenp == 2) == 0:
comeutodas1 += 1
elif game.end == 2:
w2 += 1
gamenp = np.array(game.board)
if np.count_nonzero(gamenp == 1) == 0:
comeutodas2 += 1
with open("data.txt", "a") as data:
numbers = "%d %d %d %d\n" % (numSimulations, w1, w2, empate)
data.write(numbers)
print("Jogos: %d\nAI 1: %d (Jogos com todas as peças do oponente eliminadas: %d)\nAI 2: %d (Jogos com todas as peças do oponente eliminadas: %d)\nEmpate: %d\n" % (numSimulations, w1, comeutodas1, w2, comeutodas2, empate))
def main():
mode = chooseMode()
if mode==2:
algorithm=chooseAI()
else:
algorithm=0
table = chooseBoard()
pygame.init()
screen = setScreen()
game = readBoard(table)
drawBoard(game, screen)
playMode(game, screen, mode,algorithm)
start_time = time.time()
main()
#simulacao(100)
print("--- %.5f seconds ---" % (time.time() - start_time)) | ToniCardosooo/EIACD-Artificial-Intelligence-Project | ataxx.py | ataxx.py | py | 26,079 | python | en | code | 0 | github-code | 6 |
71477184508 | import sys
sys.stdin = open('input.txt')
def make_number(i, j, depth, ans):
global visited
if depth == 6:
if (depth, i, j, ans) not in visited:
visited[(depth, i, j, ans)] = 1
result.append(ans)
return
if (depth, i, j, ans) in visited:
return
else:
visited[(depth, i, j, ans)] = 1
for di, dj in ((0, 1), (0, -1), (1, 0), (-1, 0)):
ni, nj = i + di, j + dj
if 0 <= ni < 4 and 0 <= nj < 4:
make_number(ni, nj, depth+1, ans+data[ni][nj])
T = int(input())
for tc in range(1, 1+T):
data = [list(map(str, input().split())) for _ in range(4)]
result = []
# visited에다가 해당까지 온 값과 i,j값을 넣어준다.
visited = {}
# print(visited)
for i in range(4):
for j in range(4):
make_number(i, j, 0, data[i][j])
result = set(result)
print(f'#{tc}', len(result))
| YOONJAHYUN/Python | SWEA/14035_격자판의숫자이어붙이기/sol2.py | sol2.py | py | 948 | python | en | code | 2 | github-code | 6 |
14696724987 | import math
import sys
from typing import Iterable, Optional
import torch
from timm.data import Mixup
from timm.utils import accuracy
import util.misc as misc
import util.lr_sched as lr_sched
import numpy as np
from scipy.stats import spearmanr, pearsonr
def train_koniq_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
data_loader: Iterable, optimizer: torch.optim.Optimizer,
device: torch.device, epoch: int, loss_scaler=None, log_writer=None,
args=None):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
header = 'Epoch: [{}]'.format(epoch)
print_freq = 20
accum_iter = args.accum_iter
optimizer.zero_grad()
if log_writer is not None:
print('log_dir: {}'.format(log_writer.log_dir))
pred_epoch = []
labels_epoch = []
for data_iter_step, (samples, targets) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
# we use a per iteration (instead of per epoch) lr scheduler
if data_iter_step % accum_iter == 0:
lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
samples = samples.to(device, non_blocking=True)
targets = torch.squeeze(targets.type(torch.FloatTensor))
targets = targets.to(device, non_blocking=True)
with torch.cuda.amp.autocast():
outputs = model(samples)
loss = criterion(torch.squeeze(outputs), targets)
loss_value = loss.item()
if not math.isfinite(loss_value):
print("Loss is {}, stopping training".format(loss_value))
sys.exit(1)
loss /= accum_iter
loss_scaler(loss, optimizer, clip_grad=None,
parameters=model.parameters(), create_graph=False,
update_grad=(data_iter_step + 1) % accum_iter == 0)
if (data_iter_step + 1) % accum_iter == 0:
optimizer.zero_grad()
torch.cuda.synchronize()
metric_logger.update(loss=loss_value)
min_lr = 10.
max_lr = 0.
for group in optimizer.param_groups:
min_lr = min(min_lr, group["lr"])
max_lr = max(max_lr, group["lr"])
metric_logger.update(lr=max_lr)
pred =concat_all_gather(outputs)
labels =concat_all_gather(targets)
pred_batch_numpy = pred.data.cpu().numpy()
labels_batch_numpy = labels.data.cpu().numpy()
pred_epoch = np.append(pred_epoch, pred_batch_numpy)
labels_epoch = np.append(labels_epoch, labels_batch_numpy)
loss_value_reduce = misc.all_reduce_mean(loss_value)
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
""" We use epoch_1000x as the x-axis in tensorboard.
This calibrates different curves when batch size changes.
"""
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
log_writer.add_scalar('loss', loss_value_reduce, epoch_1000x)
log_writer.add_scalar('lr', max_lr, epoch_1000x)
rho_s, _ = spearmanr(np.squeeze(pred_epoch), np.squeeze(labels_epoch))
rho_p, _ = pearsonr(np.squeeze(pred_epoch), np.squeeze(labels_epoch))
print('*[train] epoch:%d / SROCC:%4f / PLCC:%4f' % (epoch+1, rho_s, rho_p))
# gather the stats from all processes
metric_logger.synchronize_between_processes()
print("Averaged stats:", metric_logger)
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
@torch.no_grad()
def evaluate_koniq(data_loader, model, device):
criterion = torch.nn.L1Loss()
metric_logger = misc.MetricLogger(delimiter=" ")
header = 'Test:'
# switch to evaluation mode
model.eval()
pred_epoch = []
labels_epoch = []
for batch in metric_logger.log_every(data_loader, 10, header):
images = batch[0]
target = batch[-1]
images = images.to(device, non_blocking=True)
targets = torch.squeeze(target.type(torch.FloatTensor))
targets = targets.to(device, non_blocking=True)
# compute output
with torch.cuda.amp.autocast():
output = model(images)
loss = criterion(torch.squeeze(output), targets)
pred =concat_all_gather(output)
labels =concat_all_gather(targets)
pred_batch_numpy = pred.data.cpu().numpy()
labels_batch_numpy = labels.data.cpu().numpy()
pred_epoch = np.append(pred_epoch, pred_batch_numpy)
labels_epoch = np.append(labels_epoch, labels_batch_numpy)
batch_size = images.shape[0]
metric_logger.update(loss=loss.item())
# gather the stats from all processes
metric_logger.synchronize_between_processes()
rho_s, _ = spearmanr(np.squeeze(pred_epoch), np.squeeze(labels_epoch))
rho_p, _ = pearsonr(np.squeeze(pred_epoch), np.squeeze(labels_epoch))
print('*[test] / SROCC:%4f / PLCC:%4f' % ( rho_s, rho_p))
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
# utils
@torch.no_grad()
def concat_all_gather(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
tensors_gather = [torch.ones_like(tensor)
for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
output = torch.cat(tensors_gather, dim=0)
return output
| wang3702/retina_mae | koniq/train_koniq_epoch.py | train_koniq_epoch.py | py | 5,602 | python | en | code | 1 | github-code | 6 |
36561155390 |
from src.Util.GeneralConfig import GeneralConfig
from src.FaceRecognition.FaceRecognition import FaceRecognition
from src.Camera.Camera import Camera
from src.TelegramBot.Bot import Bot
import threading
enviroment = "Development"
#Iniciando Las configuraciones generales
generalConfig = GeneralConfig(enviroment)
bot = Bot(generalConfig)
fr = FaceRecognition(generalConfig)
bot.set_faceRecognition(fr)
def camara():
cam = Camera(0,generalConfig)
bot.set_camera(cam)
cam.init_video()
while True:
key = input("t to take Picture:")
if key == "t": #Simula un boton de la raspberrypi
path = cam.take_picture()
bot.send_photo(path)
result = fr.recognize(path)
print(result)
print("_________________________________")
print("Personas reconocidas en la foto:")
for r in result:
if(r['isRecognized']):
texto = r['person']['name']
print("|_ {}".format(r['person']['name']))
else:
texto = "No reconocible"
print("|_ No reconocible")
bot.send_message(texto)
if key == "c":
cam.stop()
#t._stop()
#b._stop()
def botTest():
bot.run()
while True:
pass
t = threading.Thread(target=camara, name="Test")
b = threading.Thread(target=botTest, name="botTest")
if __name__ == '__main__':
b.start()
t.start() | portisk8/smartbell-python | SmartBell/main.py | main.py | py | 1,273 | python | en | code | 0 | github-code | 6 |
810754112 | from scipy import sparse
import time
import gradient
import vector_fields
def enforce_boundaries(phi, img_shape, dim):
# make sure we are inside the image
phi[:, 1] = phi[:, 1].clip(0, img_shape[1])
phi[:, 0] = phi[:, 0].clip(0, img_shape[0])
# 3d case
if dim == 3:
phi[:, 2] = phi[:, 2].clip(0, img_shape[2])
return phi
def integrate(x_0, kernels, alpha, c_sup, dim, steps = 10, compute_gradient = True):
start = time.time()
if (compute_gradient):
S_i = vector_fields.evaluation_matrix_blowup(kernels, x_0, c_sup, dim)
else:
S_i = vector_fields.evaluation_matrix(kernels, x_0, c_sup, dim)
#print("FE -- initial S_i ", (time.time() - start) / 60)
start = time.time()
V_i = vector_fields.make_V(S_i, alpha, dim)
#print("FE -- initial V_i ", (time.time() - start) / 60)
x_i = x_0
dphi_dalpha_i = sparse.csc_matrix((S_i.shape[0], S_i.shape[1]))
for i in range(steps):
if compute_gradient:
start = time.time()
dv_dphit_i = gradient.dv_dphit(x_i, kernels, alpha, c_sup, dim)
print("FE -- dv_dphi_i ", (time.time() - start) / 60)
start = time.time()
dphi_dalpha_i = gradient.next_dphi_dalpha(S_i, dv_dphit_i, dphi_dalpha_i, steps, dim)
print("FE -- dphi_dalpha_i ", (time.time() - start) / 60)
start = time.time()
# Make a step
x_i = x_i + V_i / steps
# Compute evaluatation matrix based on updated evaluation points
if (i < steps - 1):
if (compute_gradient):
S_i = vector_fields.evaluation_matrix_blowup(kernels, x_i, c_sup, dim)
else:
S_i = vector_fields.evaluation_matrix(kernels, x_i, c_sup, dim)
V_i = vector_fields.make_V(S_i, alpha, dim)
print("FE -- Euler step ", (time.time() - start) / 60)
# Enforce boundary conditions
img_shape = []
for d in range(dim):
img_shape.append(max(x_0[:, d]))
x_1 = enforce_boundaries(x_i, img_shape, dim)
if compute_gradient:
return x_1, dphi_dalpha_i
else:
return x_1
| polaschwoebel/NonLinearDataAugmentation | forward_euler.py | forward_euler.py | py | 2,149 | python | en | code | 2 | github-code | 6 |
5832109821 | """
Implementation based on:
https://www.kaggle.com/c/quora-question-pairs/discussion/33371
"""
import networkx as nx
import pandas as pd
def magic_feature_3_with_load():
train = pd.read_csv('../data/train.csv', encoding='utf-8')
test = pd.read_csv('../data/test.csv', encoding='utf-8')
return magic_feature_3(train, test)
def magic_feature_3(train_orig, test_orig):
cores_dict = pd.read_csv("../data/question_max_kcores.csv", index_col="qid").to_dict()["max_kcore"]
def gen_qid1_max_kcore(x):
return cores_dict[hash(x)]
def gen_qid2_max_kcore(x):
return cores_dict[hash(x)]
#def gen_max_kcore(row):
# return max(row["qid1_max_kcore"], row["qid2_max_kcore"])
train_orig.loc[:, "m3_qid1_max_kcore"] = train_orig.loc[:, 'question1'].apply(gen_qid1_max_kcore)
test_orig.loc[:, "m3_qid1_max_kcore"] = test_orig.loc[:, 'question1'].apply(gen_qid1_max_kcore)
train_orig.loc[:, "m3_qid2_max_kcore"] = train_orig.loc[:, 'question2'].apply(gen_qid2_max_kcore)
test_orig.loc[:, "m3_qid2_max_kcore"] = test_orig.loc[:, 'question2'].apply(gen_qid2_max_kcore)
#df_train["max_kcore"] = df_train.apply(gen_max_kcore, axis=1)
#df_test["max_kcore"] = df_test.apply(gen_max_kcore, axis=1)
return dict(train=train_orig.loc[:, ['m3_qid1_max_kcore', 'm3_qid2_max_kcore']],
test=test_orig.loc[:, ['m3_qid1_max_kcore', 'm3_qid2_max_kcore']])
def create_qid_dict(train_orig):
df_id1 = train_orig.loc[:, ["qid1", "question1"]].drop_duplicates(keep="first").copy().reset_index(drop=True)
df_id2 = train_orig.loc[:, ["qid2", "question2"]].drop_duplicates(keep="first").copy().reset_index(drop=True)
df_id1.columns = ["qid", "question"]
df_id2.columns = ["qid", "question"]
print(df_id1.shape, df_id2.shape)
df_id = pd.concat([df_id1, df_id2]).drop_duplicates(keep="first").reset_index(drop=True)
print(df_id1.shape, df_id2.shape, df_id.shape)
dict_questions = df_id.set_index('question').to_dict()
return dict_questions["qid"]
def get_id(question, dict_questions):
if question in dict_questions:
return dict_questions[question]
else:
new_id = len(dict_questions[question]) + 1
dict_questions[question] = new_id
return new_id, new_id
def run_kcore():
df_train = pd.read_csv("../data/train.csv", encoding='utf-8')
df_test = pd.read_csv("../data/test.csv", encoding='utf-8')
df_train.loc[:, 'qid1'] = df_train.loc[:, 'question1'].apply(hash)
df_train.loc[:, 'qid2'] = df_train.loc[:, 'question2'].apply(hash)
df_test.loc[:, 'qid1'] = df_test.loc[:, 'question1'].apply(hash)
df_test.loc[:, 'qid2'] = df_test.loc[:, 'question2'].apply(hash)
df_all = pd.concat([df_train.loc[:, ["qid1", "qid2"]],
df_test.loc[:, ["qid1", "qid2"]]], axis=0).reset_index(drop='index')
print("df_all.shape:", df_all.shape) # df_all.shape: (2750086, 2)
df = df_all
g = nx.Graph()
g.add_nodes_from(df.qid1)
edges = list(df.loc[:, ['qid1', 'qid2']].to_records(index=False))
g.add_edges_from(edges)
g.remove_edges_from(g.selfloop_edges())
print(len(set(df.qid1)), g.number_of_nodes()) # 4789604
print(len(df), g.number_of_edges()) # 2743365 (after self-edges)
df_output = pd.DataFrame(data=g.nodes(), columns=["qid"])
print("df_output.shape:", df_output.shape)
NB_CORES = 20
for k in range(2, NB_CORES + 1):
fieldname = "kcore{}".format(k)
print("fieldname = ", fieldname)
ck = nx.k_core(g, k=k).nodes()
print("len(ck) = ", len(ck))
df_output[fieldname] = 0
df_output.ix[df_output.qid.isin(ck), fieldname] = k
df_output.to_csv("../data/question_kcores.csv", index=None)
def run_kcore_max():
df_cores = pd.read_csv("../data/question_kcores.csv", index_col="qid")
df_cores.index.names = ["qid"]
df_cores.loc[:, 'max_kcore'] = df_cores.apply(lambda row: max(row), axis=1)
df_cores.loc[:, ['max_kcore']].to_csv("../data/question_max_kcores.csv") # with index
if __name__ == '__main__':
run_kcore()
run_kcore_max()
| ahara/kaggle_quora_question_pairs | magic_feature_3.py | magic_feature_3.py | py | 4,136 | python | en | code | 0 | github-code | 6 |
28879203989 | from Position import Position
from random import randint
from Animal import Animal
from copy import copy
class Turtle(Animal):
def __init__(self, world, position, strength=2):
super().__init__(world, position, 'dark green', 'Turtle', 1, strength, -1, 1)
def action(self):
chance_to_move = randint(1, 100)
if chance_to_move > 75:
super().action()
def collision(self, position):
organism_on_position = self.get_organism_on_board(position)
if organism_on_position is not None:
if organism_on_position.species == self.species:
self.multiply(organism_on_position)
else:
if not self.is_attack_repelled(organism_on_position):
organism_on_position.react_on_collision(self)
else:
message = self.species + ' repels ' + organism_on_position.species + \
' on (' + str(position.x) + ',' + str(position.y) + ')'
self.add_message_to_log(message)
else:
self.move(position)
def is_attack_repelled(self, opponent):
return opponent.strength < 5 and opponent.type == 'Animal'
def react_on_collision(self, attacker):
position = copy(self.position)
if not self.is_attack_repelled(attacker):
super().react_on_collision(attacker)
else:
message = self.species + ' repels ' + attacker.species + \
' in defense on (' + str(position.x) + ',' + str(position.y) + ')'
self.add_message_to_log(message)
| krzysztofzajaczkowski/world-simulator-python | Turtle.py | Turtle.py | py | 1,622 | python | en | code | 0 | github-code | 6 |
22702565799 | import logging
import random
import asyncio
import websockets
import pandas as pd
import numpy as np
import plotly.express as px
import traits
from alleles import *
pd.options.plotting.backend = "plotly"
#Fix population crash issue
#Work on save function, produce population/world snapshots
#Improve data visualization methods
#Improve color genetics complexity
#Balancing
logging.basicConfig(filename='debug1.txt',level=logging.DEBUG, filemode='w')
def shift_list(list):
item = None
if len(list) > 0:
item = list[0]
del list[0]
return item
class World:
def __init__(self):
self.resource_increment = 50
self.resource_cap = 500
self.reset()
def get_resources(self):
return self.resources
def increment(self):
logging.debug(f'Incrementing world. Resources: {self.resources} + {self.resource_increment} = {self.resources + self.resource_increment}.')
self.resources += self.resource_increment
if self.resources > self.resource_cap:
self.resources = self.resource_cap
logging.debug(f'Resource count set to cap: {self.resource_cap}')
def reset(self):
self.current_time = 0
self.resources = 500
class Population:
def __init__(self):
self.reset()
def find_by_id(self, id):
return self.items[id]
def filter_mature(self, minAge):
all_organisms = self.get_all()
by_age = []
for org in all_organisms:
if org.age >= minAge:
by_age.append(org)
return by_age
def addOrganism(self, organism):
self.items[organism.id] = organism
def nextId(self):
self.current_id = self.current_id + 1
return self.current_id
def get_all(self):
return list(self.items.values())
def reset(self):
self.items = {}
self.current_id = 0
self.info = {}
class Organism:
def __init__(self, alleles, traits, id):
self.id = id
self.alleles = alleles
self.traits = traits
self.age = 0
self.has_fed = True
self.mature_age = 2
self.max_age = 5
self.gender = random.randint(0,1)
for trait in traits:
trait.attach(self)
def __getattr__(self, name):
# return something when requesting an attribute that doesnt exist on this instance
return None
def could_breed(self):
return self.age >= self.mature_age
class SystemManager:
def time_advance(self, world):
world.current_time += 1
logging.debug(f'Time advanced to {world.current_time}')
def resource_distribute(self, pop, world):
fitness_list = sorted(pop.get_all(), key=lambda item: item.fitness, reverse = True)
for org in fitness_list:
if world.resources > 0:
org.has_fed = True
world.resources -= 1
else:
logging.debug(f'Organism {org.id} unfed.')
org.has_fed = False
def cull(self, pop):
for org in pop.get_all():
if org.age >= org.max_age or org.has_fed == False:
logging.debug(f'Culling Organism: {org.id}. Fed: {org.has_fed}. Age: {org.age}')
del pop.items[org.id]
def logPopulation(self, pop, report, world):
total_red = 0
total_green = 0
total_blue = 0
for organism in pop.items.values():
report.append(f'{world.current_time},{organism.id},{organism.age},{organism.r},{organism.g},{organism.b}')
total_red += organism.r
total_green += organism.g
total_blue += organism.b
pop_count = len(pop.get_all())
pop.info["average_red"] = 0
pop.info["average_green"] = 0
pop.info["average_blue"] = 0
if pop_count > 0:
pop.info["average_red"] = total_red/pop_count
pop.info["average_green"] = total_green/pop_count
pop.info["average_blue"] = total_blue/pop_count
def calcBreedScore(self, pop):
logging.debug("calcBreedScore called")
for organism in pop.items.values():
organism.breed_score = 100
organism.breed_score += organism.redness * -0.5 * 50
if organism.redness == 255:
organism.breed_score = 0
logging.debug("Pure red punished (breedScore)")
else:
pass
organism.breed_score += organism.blueness * 0.5 * 50
if organism.blueness == 255:
organism.breed_score = 0
logging.debug("Pure blue punished (breedScore)")
else:
pass
organism.breed_score += organism.greenness * 0 * 50
if organism.greenness == 255:
organism.breed_score = 0
logging.debug("Pure green punished (breedScore)")
else:
pass
random_num = random.randint(0,10)
if random_num > 7:
organism.breed_score += random.randint(0,25)
elif random_num < 3:
organism.breed_score -= random.randint(0,25)
else:
pass
#logging.debug(f'Organism {organism.id} breed_score: : {organism.breed_score}\n redness: {redness}, greenness: {greenness}, blueness: {blueness}')
def calcFitness(self, pop):
for organism in pop.items.values():
organism.fitness = 100
organism.fitness += organism.redness * 0.5 * 50
if organism.redness == 255:
organism.fitness = 0
logging.debug("Pure red punished (fitness)")
else:
pass
organism.fitness += organism.blueness * -0.5 * 50
if organism.blueness == 255:
organism.fitness = 0
logging.debug("Pure blue punished (fitness)")
else:
pass
organism.fitness += organism.greenness * 0 * 50
if organism.greenness == 255:
organism.fitness = 0
logging.debug("Pure green punished (fitness)")
else:
pass
random_num = random.randint(0,10)
if random_num > 7:
organism.fitness += random.randint(0,25)
elif random_num < 3:
organism.fitness -= random.randint(0,25)
else:
pass
#logging.debug(f'Organism {organism.id} fitness: : {organism.fitness}\n redness: {organism.redness}, greenness: {organism.greenness}, blueness: {organism.blueness}')
def selectPairs(self, pop):
logging.debug("selectPairs called")
males = []
females = []
for organism in pop.items.values():
logging.debug(f"selectPairs: organism could breed? {organism.could_breed()}")
if organism.could_breed():
if organism.gender == 0:
females.append(organism)
elif organism.gender == 1:
males.append(organism)
else:
logging.debug(f'UNEXPECTED GENDER VALUE: {organism.gender}')
logging.debug(f"{len(males)} males, {len(females)} females")
pairs = []
if len(males) >= 1:
def organism_to_string(org):
return str(org.id)
males = sorted(males, key=lambda item: item.breed_score, reverse = True)
females = sorted(females, key=lambda item: item.breed_score, reverse = True)
for male in males:
female0 = shift_list(females)
if (female0 is not None):
pairs.append([male, female0])
else:
break
female1 = shift_list(females)
if (female1 is not None):
pairs.append([male, female1])
else:
break
female2 = shift_list(females)
if (female2 is not None):
pairs.append([male, female2])
else:
break
return pairs
def mutate(self, organism):
global mutation_count
mutation_target = organism.alleles[random.randint(0, len(organism.alleles)-1)]
organism.alleles.remove(mutation_target)
possible_alleles = list(filter(lambda allele: allele.type == mutation_target.type, all_alleles))
possible_alleles.remove(mutation_target)
mutant_allele = possible_alleles[random.randint(0, len(possible_alleles)-1)]
organism.alleles.append(mutant_allele)
mutation_count += 1
logging.debug(f"Organism {organism.id} mutated. {mutation_target.name} -> {mutant_allele.name}.")
def breedPair(self, pair, pop):
logging.debug("breedPair called")
a = pair[0]
b = pair[1]
children_count = 2
trait_alleles_a = None
trait_alleles_b = None
both_alleles = None
child_alelles = []
child_traits = []
# we want to ensure that both parents have compatible traits and alleles for those traits
# For loop should take list of relevant alleles for each trait, shuffle them, give output.
# If either parent has a trait the other lacks, abort the whole function and move to next pair.
for trait in a.traits:
if not trait in b.traits:
logging.debug(f"Pairing rejected: Org {b.id} doesnt have trait {trait}")
return
for trait in b.traits:
if not trait in a.traits:
logging.debug(f"Pairing rejected: Org {a.id} doesnt have trait {trait}")
return
for trait in a.traits:
trait_alleles_a = list(filter(lambda allele: allele.type == trait.allele_type, a.alleles))
trait_alleles_b = list(filter(lambda allele: allele.type == trait.allele_type, b.alleles))
both_alleles = trait_alleles_a + trait_alleles_b
random.shuffle(both_alleles)
#logging.debug(f"both_alleles length: {len(both_alleles)}")
for allele in both_alleles[0:2]:
child_alelles.append(allele)
child_traits.append(trait)
child = Organism(child_alelles, child_traits, pop.nextId())
if random.randint(0,100) == 100:
self.mutate(child)
pop.addOrganism(child)
logging.debug(f"Org {child.id} created. Redness: {child.redness}, R: {child.r}. Greeness: {child.greenness}, G: {child.g}. Blueness: {child.blueness}, B: {child.b}.")
def incrementAge(self, pop):
for organism in pop.items.values():
organism.age += 1
def Update(self, pop, world):
# print("manager.Update called")
# A new breeding season
logging.debug(f"Population at start of timestep {world.current_time}: {len(pop.get_all())}")
self.calcFitness(pop)
self.resource_distribute(pop, world)
self.incrementAge(pop)
self.calcBreedScore(pop)
pairs = self.selectPairs(pop)
for pair in pairs:
self.breedPair(pair, pop)
self.cull(pop)
logging.debug(f"Population at end of timestep {world.current_time}: {len(pop.get_all())}")
world.increment()
self.time_advance(world)
report = []
population_report = ["time,population,average_red,average_green,average_blue"]
pop = Population()
manager = SystemManager()
world = World()
mutation_count = 0
def runSim(count):
while count > 0:
logging.debug(f"runSim, calling manager.Update")
manager.Update(pop, world)
manager.logPopulation(pop, report, world)
pop_count = len(pop.get_all())
population_report.append(f"{world.current_time},{pop_count}, {pop.info['average_red']},{pop.info['average_green']},{pop.info['average_blue']}")
output = open("output.csv", "wt")
for item in report:
output.write(f"{item}\n")
output.close()
output = open("population.csv", "wt")
for item in population_report:
output.write(f"{item}\n")
output.close()
count -= 1
return population_report
def resetSim():
initialize()
def initialize():
FirstOrg = Organism([Coloration_Green, Coloration_Blue], [traits.ColorationOne], pop.nextId())
SecondOrg = Organism([Coloration_Red, Coloration_Blue], [trait.ColorationOne], pop.nextId())
ThirdOrg = Organism([Coloration_Blue, Coloration_Blue], [trait.ColorationOne], pop.nextId())
FourthOrg = Organism([Coloration_Red, Coloration_Red], [trait.ColorationOne], pop.nextId())
FifthOrg = Organism([Coloration_Green, Coloration_Blue], [trait.ColorationOne], pop.nextId())
SixthOrg = Organism([Coloration_Red, Coloration_Green], [trait.ColorationOne], pop.nextId())
SeventhOrg = Organism([Coloration_Green, Coloration_Green], [traits.Coloration], pop.nextId())
FirstOrg.gender = 1
SecondOrg.gender = 0
initial_generation = [FirstOrg, SecondOrg, ThirdOrg, FourthOrg, FifthOrg, SixthOrg, SeventhOrg]
pop.reset()
world.reset()
report.clear()
population_report.clear()
population_report.append("time,population,average_red,average_green,average_blue")
report.append(f'Time,ID,Age,Red,Green,Blue')
for org in initial_generation:
pop.addOrganism(org)
def showColors():
color_frame = pd.read_csv('population.csv', usecols = ['time', 'average_red', 'average_green', 'average_blue'])
color_frame.plot(x='time', y=['average_blue','average_red','average_green']).show()
def showPop():
pop_frame = pd.read_csv('population.csv', usecols = ['time', 'population'])
pop_frame.plot(x='time', y=['population']).show()
async def main():
initialize()
# Start the websocket server and run forever waiting for requests
async with websockets.serve(handleRequest, "localhost", 8765):
await asyncio.Future() # run forever
async def handleRequest(websocket, path):
#reset command is causing an error, probably getting stuck somewhere in resetSim()
async for message in websocket:
parts = message.split(",")
command_name = parts[0]
logging.debug(f"Got websocket request")
if command_name == "getPop":
print("Population count request recieved")
await websocket.send(f"Population count: {len(pop.get_all())}")
print("Population count sent")
elif command_name == "runSim":
print(f"Incrementing simulation by t={parts[1]}")
runSim(int(parts[1]))
await websocket.send(f"Simulation incremented by t={parts[1]}")
elif command_name == "reset":
print("Reset command recieved")
resetSim()
print("Simulation reset")
await websocket.send("Simulation reset")
elif command_name == "showColors":
showColors()
await websocket.send("Ok")
elif command_name == "showPop":
showPop()
await websocket.send("Ok")
elif command_name == "showAll":
showPop()
showColors()
await websocket.send(f"Final population: {len(pop.get_all())}. Final time: {world.current_time}. Number of mutations: {mutation_count}.")
else:
await websocket.send("Unknown Command")
print(f"{message}")
if __name__ == "__main__":
asyncio.run(main())
| Adrian-Grey/EvoProject | evoBackend.py | evoBackend.py | py | 15,553 | python | en | code | 1 | github-code | 6 |
16326125244 | from typing import Dict
import json as _json
import datetime as _dt
def get_all_events() -> Dict:
with open("events.json", encoding='utf-8') as events_file:
data = _json.load(events_file)
return data
def get_all_month_events(month: str) -> Dict:
events = get_all_events()
month = month.lower()
try:
month_events = events[month]
return month_events
except KeyError:
return "This is not a month name"
def get_all_day_events(month: str, day: int) -> Dict:
events = get_all_events()
month = month.lower()
try:
day_events = events[month][str(day)] # Here, I passed day as a string becasue in our json, days are written in string format
return day_events
except KeyError:
return "This is not a valid input"
def get_all_today_events():
today = _dt.date.today()
month = today.strftime("%B")
return get_all_day_events(month, today.day)
| mysterious-shailendr/Web-Scraping-and-Fast-API | services.py | services.py | py | 948 | python | en | code | 2 | github-code | 6 |
74031521788 | from matplotlib import pyplot as plt
import numpy as np
import random
import utils
features = np.array([1,2,3,5,6,7])
labels = np.array([155, 197, 244, 356,407,448])
print(features)
print(labels)
utils.plot_points(features, labels)
# Feature cross / synthetic feature
def feature_cross(num_rooms, population):
room_per_person_feature = num_rooms / population
return room_per_person_feature
def simple_trick(base_price, price_per_room, num_rooms, price):
# select random learning rate
small_random_1 = random.random()*0.1
small_random_2 = random.random()*0.1
# calculate the prediction.
predicted_price = base_price + price_per_room*num_rooms
# check where the point is with respect to the line.
if price > predicted_price and num_rooms > 0:
# translate the line
price_per_room += small_random_1
# rotate the line
base_price += small_random_2
if price > predicted_price and num_rooms < 0:
price_per_room -= small_random_1
base_price += small_random_2
if price < predicted_price and num_rooms > 0:
price_per_room -= small_random_1
base_price -= small_random_2
if price < predicted_price and num_rooms < 0:
price_per_room -= small_random_1
base_price += small_random_2
return price_per_room, base_price
def absolute_trick(base_price, price_per_room, num_rooms, price, learning_rate):
predicted_price = base_price + price_per_room*num_rooms
if price > predicted_price:
price_per_room += learning_rate*num_rooms
base_price += learning_rate
else:
price_per_room -= learning_rate*num_rooms
base_price -= learning_rate
return price_per_room, base_price
def square_trick(base_price, price_per_room, num_rooms, price, learning_rate):
predicted_price = base_price + price_per_room*num_rooms
price_per_room += learning_rate*num_rooms*(price-predicted_price)
base_price += learning_rate*(price-predicted_price)
return price_per_room, base_price
# We set the random seed in order to always get the same results.
random.seed(0)
def linear_regression(features, labels, learning_rate=0.01, epochs = 1000):
price_per_room = random.random()
base_price = random.random()
for epoch in range(epochs):
# Uncomment any of the following lines to plot different epochs
if epoch == 1:
utils.draw_line(price_per_room, base_price, starting=0, ending=8)
elif epoch <= 10:
utils.draw_line(price_per_room, base_price, starting=0, ending=8)
elif epoch <= 50:
utils.draw_line(price_per_room, base_price, starting=0, ending=8)
elif epoch > 50:
utils.draw_line(price_per_room, base_price, starting=0, ending=8)
i = random.randint(0, len(features)-1)
num_rooms = features[i]
price = labels[i]
# Uncomment any of the 2 following lines to use a different trick
#price_per_room, base_price = absolute_trick(base_price,
price_per_room, base_price = square_trick(base_price,
price_per_room,
num_rooms,
price,
learning_rate=learning_rate)
utils.draw_line(price_per_room, base_price, 'black', starting=0, ending=8)
utils.plot_points(features, labels)
print('Price per room:', price_per_room)
print('Base price:', base_price)
return price_per_room, base_price
# This line is for the x-axis to appear in the figure
plt.ylim(0,500)
linear_regression(features, labels, learning_rate = 0.01, epochs = 1000)
# The root mean square error function
def rmse(labels, predictions):
n = len(labels)
differences = np.subtract(labels, predictions)
return np.sqrt(1.0/n * (np.dot(differences, differences))) | sithu/cmpe255-spring21 | lecture/regression/home-price.py | home-price.py | py | 3,939 | python | en | code | 1 | github-code | 6 |
3706334563 | from cgitb import reset
from flask import Flask, jsonify, request, render_template
import Crypto
import Crypto.Random
from Crypto.PublicKey import RSA
import binascii
from collections import OrderedDict
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
import webbrowser
class Transaction:
def __init__(self, sender_public_key, sender_private_key, recipient_public_key, amount):
self.sender_public_key = sender_public_key
self.sender_private_key = sender_private_key
self.recipient_public_key = recipient_public_key
self.amount = amount
#Function to convert transaction details to dictionary format
def to_dict(self):
return OrderedDict({
'sender_public_key' : self.sender_public_key,
'recipient_public_key' : self.recipient_public_key,
'amount' : self.amount
})
#Function to sign the transaction
def sign_transaction(self):
private_key = RSA.importKey(binascii.unhexlify(self.sender_private_key))
signer = PKCS1_v1_5.new(private_key)
hash = SHA.new(str(self.to_dict()).encode('utf8'))
return binascii.hexlify(signer.sign (hash)).decode('ascii')
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/make/transactions')
def make_transactions():
return render_template('make_transactions.html')
@app.route('/view/transactions')
def view_transactions():
return render_template('view_transactions.html')
#Public and private key pair generation for wallet
@app.route('/wallet/new')
def new_wallet():
random_gen = Crypto.Random.new().read
private_key = RSA.generate(1024, random_gen)
public_key = private_key.publickey()
response={
'private_key' : binascii.hexlify(private_key.export_key(format('DER'))).decode('ascii'),
'public_key' :binascii.hexlify(public_key.export_key(format('DER'))).decode('ascii')
}
return response
#Code to generate the transactions
@app.route('/generate/transactions', methods=['POST'])
def generate_transactions():
#Extract transaction details from form
sender_public_key = request.form['sender_public_key']
sender_private_key = request.form['sender_private_key']
recipient_public_key = request.form['recipient_public_key']
amount = request.form['amount']
#Make a Transaction object
transaction = Transaction(sender_public_key, sender_private_key, recipient_public_key, amount)
#Convert Transaction object into dictionary and sign it
response ={'transaction' : transaction.to_dict(),
'signature' : transaction.sign_transaction()}
return jsonify(response), 200
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-p', '--port', default = 8081, type = int, help ="Port to listen")
args = parser.parse_args()
port = args.port
#Open url in browser
webbrowser.open('http://127.0.0.1:'+str(port))
#Run flask app
app.run(host="0.0.0.0",port=port, debug=True) | LoneCannibal/Netherite2 | blockchain_client/client.py | client.py | py | 3,109 | python | en | code | 0 | github-code | 6 |
72166387389 | file = open('./3/3.txt', 'r')
input = file.readlines()
def get_letter_value(letter):
letter_value = ord(letter)
if letter_value < 97:
return letter_value - 38
return letter_value - 96
def get_matching_letter():
found_items = []
for rucksack in input:
item_count = len(rucksack)
for i in range((item_count // 2)):
if rucksack[i] in rucksack[item_count // 2:]:
found_items.append(get_letter_value(rucksack[i]))
break
return found_items
print(sum(get_matching_letter()))
| Haustgeirr/aoc-2022 | 3.py | 3.py | py | 569 | python | en | code | 0 | github-code | 6 |
27679932090 | """This module allows to interact with the user via the command line and processes
the input information.
"""
import os
import re
from inspect import getsourcefile
import numpy as np
import yaml
class CommandLineParser():
"""See documentation of the init method.
"""
def __init__(self) -> None:
"""This class allows to parse user input from the command line and validate
its syntax. Furthermore it allows to create the axes for the goniometer
from a specific user input format.
"""
self.parsed = {}
self._resources_path = os.path.abspath(getsourcefile(lambda: 0)).replace(
'command_line_interfaces/parser.py', 'resources/')
with open(f"{self._resources_path}user_input.yaml", 'r') as stream:
try:
self.input_options = yaml.safe_load(stream)
except yaml.YAMLError as error:
print(error)
# TODO sometimes e.g. for chi a trailing space is enough to fail the regex
self.validation_regex = {
'doi': None,
'layout': self._create_options_regex('layout'),
'facility': self._create_options_regex('facility'),
'beamline': None,
'rad_type': None,
"model" : None,
"location" : None,
"manufacturer" : self._create_options_regex('manufacturer'),
'principal_angle': r'\d{1,3}\Z',
'goniometer_axes' : r'((?:[^,]*,\s*(a|c),\s*)*[^,]*,\s*(a|c))\Z',
'change_goniometer_axes' : r'((?:[^,]*,\s*(a|c),\s*)*[^,]*,\s*(a|c))\Z',
'change_det_rot_axes' : r'((?:[^,]*,\s*(a|c),\s*)*[^,]*,\s*(a|c))\Z',
"two_theta_sense" : self._create_options_regex('two_theta_sense'),
'detector_axes' : r'((?:[^, ]*,\s*)*[^, ]+)\Z',
"chi_axis" : r'.*(?:\s+\d{1,3})\Z',
'kappa_axis': r'.*(((\s|,)(\s)*\d{1,3}){1,2})\Z', # capture something like kappa, 50, 50
'image_orientation': self._create_options_regex('image_orientation'),
'fast_direction': self._create_options_regex('fast_direction'),
'pixel_size': r'(\d+\.?\d*\Z)|(\d+\.?\d*,\s*\d+\.?\d*\Z)',
'array_dimension': r'(\d+(,\s*)\d+\Z)',
'filename': r'.*((\.h5)\Z|(\.cbf)\Z|(\.smv)\Z)',
'goniometer_rot_direction' : \
self._create_options_regex('goniometer_rot_direction'),
'frame_numbers': r'^\d+(,\s*\d+)*$',
'external_url': None,
'temperature': r'\d+\Z',
'keep_axes': self._create_options_regex('keep_axes'),
'url_not_reachable': self._create_options_regex('url_not_reachable'),
}
def request_input(self, label):
"""Request input from the user for the given label and the associated
information in the resources file.
Args:
label (str): the label that identifies the request
Returns:
str: the input from the user, validated
"""
while self.parsed.get(label) is None:
required = 'required' if self.input_options[label].get('required') \
else 'not required'
print(f"\n{self.input_options[label]['label']} ({required}):")
choices = ''
if self.input_options[label].get('options') is not None:
options = self.input_options[label]['options']
if self.input_options[label].get('abbreviate'):
options = [option + f' ({option[0]})' for option in options]
choices = '\n Choices: ' + ', '.join(options)
print(f"{self.input_options[label]['description']}".strip('\n') + choices)
self.parsed[label] = self._validated_user_input(label)
return self.parsed[label]
def parse_axis_string(self, axis_string):
"""Parse a string of form axis, sense, axis, sense...
Args:
axis_string (str): the axis string from the user input
Raises:
Exception: axis string is incorrect
Returns:
axes (list): a list containing the axis names
senses (list): a list containing the axis senses
"""
ax_str = [sub.strip() for sub in axis_string.split(',')]
if len(ax_str) % 2 != 0:
raise Exception("Axis string is incorrect: %axis_string")
axes = []
senses = []
for i in range(0, len(ax_str), 2):
axes.append(ax_str[i])
sense = ax_str[i+1].lower()
senses.append(sense)
return axes, senses
def make_goniometer_axes(self, goniometer_axes, kappa_info, chi_info):
"""Create the goniometer axes from the user input. The list of gonio axes
goes in order from top to bottom, meaning that the first "depends on"
the second and so forth. We assume a two theta axis.
The items we have to fill in are:
1. type -> rotation
2. depends_on -> next in list
3. equipment -> goniometer
4. vector -> almost always 1 0 0 (rotation about principal axis)
5. offset -> always [0 0 0] but needed for loop integrity
Note that our questions assume looking from above whereas imgCIF is
looking from below, so the sense of rotation is reversed.
Args:
goniometer_axes (tuple): a tuple of lists consisting of the axis names
and the senses of rotation
kappa_info (str): the parsed user input string for the kappa axis
chi_info (str): the parsed user input string for the chi axis
Returns:
dict: a dictionary containing the information about the goniometer axes
"""
axes, senses = goniometer_axes
axis_type = ["rotation" for _ in axes]
equip = ["goniometer" for _ in axes]
if kappa_info != '':
kappa_info = re.split(r',| ', kappa_info)
kappa_info = [info for info in kappa_info if info != '']
else:
kappa_info = ['']
if chi_info != '':
chi_info = re.split(r',| ', chi_info)
chi_info = [info for info in chi_info if info != '']
else:
chi_info = ['']
# Construct axis dependency chain
depends_on = []
depends_on += axes[1:]
depends_on.append('.')
# Remember the principal axis direction
principal = senses[-1]
# Create direction vectors
vector = []
offset = []
for (axis, sense) in zip(axes, senses):
rotfac = 1 if sense == principal else -1
if axis.lower() == kappa_info[0].lower():
kappa_vec = self._make_kappa_vector(kappa_info)
kappa_vec[0] *= rotfac
vector.append(kappa_vec)
elif axis.lower() == chi_info[0].lower():
vector.append(self._make_chi_vector(goniometer_axes, chi_info))
else:
vector.append([i * rotfac for i in [1, 0, 0]])
# TODO offset is always 0?
offset.append([0, 0, 0])
axes_dict = {
'axes' : goniometer_axes[0],
'axis_type' : axis_type,
'equip' : equip,
'depends_on' : depends_on,
'vector' : vector,
'offset' : offset,
}
return axes_dict
def make_detector_axes(self, det_trans_axes, det_rot_axes, principal_sense,
principal_angle, image_orientation, array_info,
scan_settings_info):
"""Add information concerning the detector axes. We define our own axis names,
with the detector distance being inserted when the data file is read. We
choose det_x to be in the horizontal direction, and det_y to be vertical.
We need to add:
1. type -> translation
2. depends_on -> x,y depend on translation
3. equipment -> detector
4. vector -> worked out from user-provided info
(5. offset -> beam centre, not added here)
Args:
principal_sense (str): the sense of the principal axis (a or c)
principal_angle (int): the orientation of the principal axis in
degree
image_orientation (str): the image orientation string, e.g. 'top left',...
two_theta_sense (str): the sense of the two theta axis (e.g. clockwise)
array_info (dict): information about the array
scan_setting_info (dict): information about the scan settings
Returns:
dict: a dictionary containing the information about the detector axes
"""
axis_id = ['dety', 'detx']
axis_type = ['translation', 'translation']
equip = ['detector', 'detector']
# Work out det_x and det_y
beam_x, beam_y = self._calculate_beam_centre(
array_info['array_dimension'], array_info['pixel_size'])
x_d, y_d, x_c, y_c = self._determine_detx_dety(
principal_angle, principal_sense, image_orientation, beam_x, beam_y)
vector = [y_d, x_d]
offset = [[0, 0, 0], [x_c, y_c, 0]]
# translational axes
axis_id += det_trans_axes
axis_type += ['translation' for _ in det_trans_axes]
equip += ['detector' for _ in det_trans_axes]
# TODO also for multiple axes correct?
# Detector translation always opposite to beam direction
vector += [[0, 0, -1] for _ in det_trans_axes]
# first_scan = sorted(scan_settings_info.keys())[0]
# first_scan_info = scan_settings_info[first_scan][0]
# z_offsets = [first_scan_info.get(axis) for axis in det_trans_axes]
# for z in z_offsets:
#TODO this sets unknown offsets to zero...
# z = z if z is not None else 0
# offset is zero and non zero in scans
offset.append([0, 0, 0])
# rotational axes
rot_axes, rot_senses = det_rot_axes
axis_id += rot_axes
axis_type += ['rotation' for _ in rot_axes]
equip += ['detector' for _ in rot_axes]
for idx, axis in enumerate(rot_axes):
rotsense = 1 if rot_senses[idx] == principal_sense else -1
vector.append([rotsense, 0, 0])
offset.append([0, 0, 0])
axis_id += ['gravity', 'source']
axis_type += ['.', '.']
equip += ['gravity', 'source']
gravity = self._determine_gravity(principal_angle, principal_sense)
vector += [gravity, [0, 0, 1]]
offset += [[0, 0, 0], [0, 0, 0]]
# the above ordering must reflect the stacking!
depends_on = axis_id[1:-(len(rot_axes)+1)] + ['.' for _ in range(len(rot_axes)+2)]
axes_dict = {
'axes' : axis_id,
'axis_type' : axis_type,
'equip' : equip,
'depends_on' : depends_on,
'vector' : vector,
'offset' : offset,
}
return axes_dict
def _validated_user_input(self, label):
"""Request an user input and validate the input according to an apppropriate
regular expression.
Args:
label (str): the label that identifies the request
"""
user_input = input(' >> ')
if self.validation_regex.get(label) is not None:
pattern = re.compile(
self.validation_regex[label])
parsed_input = pattern.match(user_input)
if parsed_input:
parsed_input = parsed_input.group(0)
else:
parsed_input = user_input
# required parameter, but either regex failed or no input was made if no regex
# is defined
if self.input_options[label].get('required') and parsed_input in [None, '']:
print(' ==> Could not interpret your input correctly! This input is required, \
please try again.')
parsed_input = None
# not required with defined regex, but no user input
elif not self.input_options[label].get('required') and user_input == '':
parsed_input = ''
# not required with defined regex, but user input
elif not self.input_options[label].get('required') and parsed_input is None:
print(' ==> Could not interpret your input correctly! Please try again.')
if parsed_input is not None:
print(f" ==> Your input was: {parsed_input}")
return parsed_input
def _make_kappa_vector(self, kappa_info):
"""Costruct the kappa vector out of the parsed information on kappa.
Args:
kappa_info (list): a list with name and rotation angle
Returns:
list: the components of the kappa vector
"""
if len(kappa_info) == 2:
kappa_info.append("0")
kapang = float(kappa_info[1])
kappoise = float(kappa_info[2])
# Now calculate direction of axis in X-Z plane assuming
# rotation of kappa is same as principal axis. There is no
# Y component as home position is always under beam path.
up_comp = np.cos(kapang)
across_comp = np.sin(kapang)
if kappoise == 0:
# is under incident beam collimator in X-Z plane
z_comp = -1 * across_comp
elif kappoise == 180:
z_comp = across_comp
return [up_comp, 0.0, z_comp]
def _make_chi_vector(self, goniometer_axes, chi_info):
"""Construct the chi vector out of the parsed information on chi.
Args:
goniometer_axes (tuple): a tuple of lists consisting of the axis names
and the senses of rotation
chi_info (list): a list with name and rotation angle
Returns:
list: the components of the chi vector
"""
axes, senses = goniometer_axes
axname = chi_info[0].lower()
rot = np.radians(-1 * float(chi_info[1]))
# Now turn this into an axis direction
# At the provided rotation, the chi axis is parallel to z. It is rotated
# by -chi_rot about omega to bring it to the start position. The sense
# of omega rotation is always about 1 0 0 by definition
axes_lowered = [axis.lower() for axis in axes]
ax_index = axes_lowered.index(axname)
chi_sense = senses[ax_index]
chi_beam_dir = np.array([0, 0, 1]) if chi_sense == "a" \
else np.array([0, 0, -1])
chi_rot = np.array([
[1.0, 0.0, 0.0],
[0.0, np.cos(rot), -np.sin(rot)],
[0.0, np.sin(rot), np.cos(rot)]
])
return list(np.dot(chi_rot, chi_beam_dir))
def _determine_gravity(self, principal_angle, principal_sense):
"""Determine the gravity vector.
Args:
principal_angle (str): the angle of the principal axis in degree
principal_sense (str): the sense of rotation of the principal axis
Returns:
list: the gavity vector
"""
angle = int(principal_angle) if principal_sense == "a" \
else int(principal_angle) + 180
if angle >= 360:
angle = angle - 360
if angle == 0:
gravity = [0, 1, 0] # spindle at 3 o'clock, rotating anticlockwise
elif angle == 90:
gravity = [1, 0, 0]
elif angle == 180:
gravity = [0, -1, 0]
else:
gravity = [-1, 0, 0]
return gravity
def _determine_detx_dety(self, principal_angle, principal_sense, corner,
beam_x, beam_y):
"""Determine direction of detx (horizontal) and dety (vertical) in
imgCIF coordinates.
Args:
principal_angle (str): the principal angle
principal_sense (str): the principal sense of the goniometer axes
corner (str): the orientation of the first pixel (e.g. 'top right')
beam_x (str): the beam center in x direction in mm
beam_y (str): the beam center in y direction in mm
Returns:
x_direction (list): the vector for the detector x direction
y_direction (list): the vector for the detector y direction
x_centre (float): the beamcentre in x direction
y_centre (float): the beamcentre in y direction
"""
# Start with basic value and then flip as necessary
x_direction = [-1, 0, 0] # spindle rotates anticlockwise at 0, top_left origin
y_direction = [0, 1, 0]
x_centre = beam_x
y_centre = -1 * beam_y
if corner == "top right":
x_direction = [i * -1 for i in x_direction]
x_centre = -1 * beam_x
elif corner == "bottom right":
x_direction = [i * -1 for i in x_direction]
y_direction = [i * -1 for i in y_direction]
x_centre *= -1
y_centre *= -1
elif corner == "bottom left":
y_direction = [i * -1 for i in y_direction]
y_centre *= -1
# The direction of the principal axis flips by 180 if the sense changes
angle = int(principal_angle) if principal_sense == "a" \
else int(principal_angle) + 180
if angle >= 360:
angle = angle - 360
if angle == 90:
temp = x_direction
temp_centre = x_centre
x_direction = y_direction
x_centre = y_centre
y_direction = [i * -1 for i in temp]
y_centre = temp_centre
elif angle == 180:
x_direction = [i * -1 for i in x_direction]
y_direction = [i * -1 for i in y_direction]
x_centre *= -1
y_centre *= -1
elif angle == 270:
temp = x_direction
temp_centre = x_centre
x_direction = [i * -1 for i in y_direction]
x_centre = -1 * y_centre
y_direction = temp
y_centre = temp_centre
return x_direction, y_direction, x_centre, y_centre
def _create_options_regex(self, label, case_insensitive=True):
"""Create a regular expression that matches only the options for the given
label.
Args:
label (str): the label that identifies the request
case_insensitive (bool, optional): Whether the regex should be case
insensitive. Defaults to True.
Returns:
regexp: regular expression formed by the options for the input label
"""
options = self.input_options[label].get('options')
if options is not None:
options_regex = r'|'.join(options)
if self.input_options[label].get('abbreviate'):
first_letters = [option[0] for option in options]
letters_regex = r'|'.join(first_letters)
options_regex += r'|' + letters_regex
options_regex = r'(' + options_regex + r')\Z'
if case_insensitive:
options_regex = r'(?i)' + options_regex
else:
options_regex = None
return options_regex
def _calculate_beam_centre(self, array_dimension, pixel_size):
"""The default beam centre is at the centre of the detector. We must
indicate this position in mm with the correct signs.
Args:
array_dimension (tuple): a tuple with the x and y dimension of the pixels
pixel_size (tuple): a tuple with the pixel sizes in x an y direction
Returns:
tuple: the x and y beam centre in mm
"""
dim_x, dim_y = array_dimension
pix_x, pix_y = pixel_size
return float(pix_x) * float(dim_x)/2, float(pix_y) * float(dim_y)/2
| COMCIFS/instrument-geometry-info | Tools/imgCIF_Creator/imgCIF_Creator/command_line_interfaces/parser.py | parser.py | py | 19,777 | python | en | code | 0 | github-code | 6 |
2015306414 | import re
from pyspark import SparkConf, SparkContext
def normalizeWords(text):
return re.compile(r'\W+', re.UNICODE).split(text.lower())
conf = SparkConf().setMaster("local").setAppName("WordCount")
sc = SparkContext(conf = conf)
input = sc.textFile("file:///sparkcourse/book.txt")
words = input.flatMap(normalizeWords)
# Note: Count by value creates a python object instead of a RDD hence .collect() not required to fetch the data
wordCounts = words.countByValue()
for word, count in wordCounts.items():
cleanWord = word.encode('ascii', 'ignore')
if (cleanWord):
print(cleanWord.decode() + " " + str(count))
| gdhruv80/Spark | word-count-better.py | word-count-better.py | py | 654 | python | en | code | 0 | github-code | 6 |
43943174399 | # M0_C9 - Sudoku Validator
import sys
import os
from typing import List
def validate(grid: List[List[int]]) -> bool:
"""Validates a given 2D list representing a completed Sudoku puzzle"""
# Write your code here
pass
##########################################
### DO NOT MODIFY CODE BELOW THIS LINE ###
##########################################
def load_puzzle(filename: str) -> List[List[int]]:
"""Reads a file containing a Sudoku puzzle into a 2D list"""
invalid_msg = 'error: invalid Sudoku puzzle supplied'
grid = []
try:
with open(filename) as fp:
for line in fp:
row = [int(num) for num in line.split()]
if len(row) != 9:
sys.exit(invalid_msg)
grid.append(row)
except IOError as e:
sys.exit(e)
if len(grid) != 9:
sys.exit(invalid_msg)
return grid
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: python3 sudoku_validator.py path/to/testfile.txt')
sys.exit()
grid = load_puzzle(sys.argv[1])
print(validate(grid))
| Static-Void-Academy/M0_C9 | sudoku_validator.py | sudoku_validator.py | py | 1,112 | python | en | code | 0 | github-code | 6 |
25354209094 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingSort function below.
def countingSort(arr):
m=max(arr)
res=[0]*(m+1)
for i in range(len(arr)):
res[arr[i]]+=1
ans=[]
for i in range(len(res)):
if res[i]>0:
temp=[i]*res[i]
ans.extend(temp)
return ans
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = countingSort(arr)
print(' '.join(map(str, result)))
| nikjohn7/Coding-Challenges | Hackerrank/Python/38.py | 38.py | py | 535 | python | en | code | 4 | github-code | 6 |
30536133746 | import importlib.util
import shutil
from pathlib import Path
from typing import List
import pandas as pd
import plotly.express as px
from bot_game import Bot
EXAMPLES_FOLDER = Path("examples")
DOWNLOAD_FOLDER = Path("downloads")
DOWNLOAD_FOLDER.mkdir(exist_ok=True)
def save_code_to_file(code: str, filename: str):
fpath = DOWNLOAD_FOLDER / f"{filename}.py"
with open(fpath, "w") as fh:
fh.write(code)
return fpath
def save_file(filename: str, filebytes: bytes):
fpath = DOWNLOAD_FOLDER / filename
with open(fpath, "wb") as fh:
fh.write(filebytes)
return fpath
def import_file(fpath: Path):
spec = importlib.util.spec_from_file_location(fpath.parts[-1], str(fpath))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def validate_file(fpath: Path):
m = import_file(fpath)
assert hasattr(m, "strategy"), "The file does not have a function called `strategy`"
assert callable(
m.strategy
), "The variable `strategy` is not callable! Is it a function?"
def build_all_bots() -> List[Bot]:
bots = []
for fp in DOWNLOAD_FOLDER.glob("*.py"):
bot = Bot(name=fp.stem)
m = import_file(fp)
bot.strategy_func = m.strategy
bots.append(bot)
return bots
def add_example_bots():
for fp in EXAMPLES_FOLDER.glob("*.py"):
shutil.copy(fp, DOWNLOAD_FOLDER / fp.parts[-1])
def plot_grand_prix_results(winnings, x_col="Bot", y_col="Races Won"):
podium_df = (
pd.Series(winnings, name=y_col)
.sort_values(ascending=False)
.rename_axis(x_col)
.reset_index()
)
fig = px.bar(podium_df, x=x_col, y=y_col, color=y_col)
return fig
def create_animation(df):
fig = px.scatter(
df.assign(
size=10,
),
x="position",
y="name",
animation_frame="round",
animation_group="name",
size="size",
color="name",
hover_data=["direction", "last_action", "action_order"],
hover_name="name",
range_x=[0, 10],
)
return fig
def delete_all_bots():
for fp in DOWNLOAD_FOLDER.glob("*.py"):
fp.unlink()
| gabrielecalvo/bot_game | util.py | util.py | py | 2,208 | python | en | code | 0 | github-code | 6 |
32146044826 | #
# @lc app=leetcode id=682 lang=python3
#
# [682] Baseball Game
#
# @lc code=start
class Solution:
def calPoints(self, ops: List[str]) -> int:
res = []
for i in ops:
if i == '+':
res.append(res[-1] + res[-2])
elif i == 'D':
res.append(res[-1]*2)
elif i == 'C':
res.pop()
else:
res.append(int(i))
return sum(res)
# @lc code=end
| rsvarma95/Leetcode | 682.baseball-game.py | 682.baseball-game.py | py | 471 | python | en | code | 0 | github-code | 6 |
7176843439 | from eth.exceptions import (
ReservedBytesInCode,
)
from eth.vm.forks.berlin.computation import (
BerlinComputation,
)
from ..london.constants import (
EIP3541_RESERVED_STARTING_BYTE,
)
from .opcodes import (
LONDON_OPCODES,
)
class LondonComputation(BerlinComputation):
"""
A class for all execution *message* computations in the ``London`` fork.
Inherits from :class:`~eth.vm.forks.berlin.BerlinComputation`
"""
opcodes = LONDON_OPCODES
@classmethod
def validate_contract_code(cls, contract_code: bytes) -> None:
super().validate_contract_code(contract_code)
if contract_code[:1] == EIP3541_RESERVED_STARTING_BYTE:
raise ReservedBytesInCode(
"Contract code begins with EIP3541 reserved byte '0xEF'."
)
| ethereum/py-evm | eth/vm/forks/london/computation.py | computation.py | py | 810 | python | en | code | 2,109 | github-code | 6 |
25225726686 | from read_the_maxfilename_for_sort import max_number
import requests
i = 1
temp_number = max_number()
def download(url):
global i
global temp_number
print('Processing {0} url:{1}'.format(i,url))
img = open('{}.jpg'.format(temp_number),'wb')
respone = requests.get(url, stream=True).content
img.write(respone)
i += 1
temp_number += 1
img.close() | HawkingLaugh/FC-Photo-Download | image_batch_download.py | image_batch_download.py | py | 382 | python | en | code | 0 | github-code | 6 |
13575734742 | import os
import numpy as np
import matplotlib
matplotlib.use('agg')
import xrt.runner as xrtrun
import xrt.plotter as xrtplot
import xrt.backends.raycing as raycing
from SKIF_NSTU_SCW import SKIFNSTU
from utilits.xrt_tools import crystal_focus
resol='mat'
E0 = 30000
subdir=rf"C:\Users\synchrotron\PycharmProjects\SKIF\SKIF_NSTU_SCW\results\{resol}\{E0}\R-R"
def define_plots(bl):
plots = []
scan_name = 'change-screen-%s' % (bl.bentLaueCylinder02.Rx)
if not os.path.exists(os.path.join(subdir, scan_name)):
os.mkdir(os.path.join(subdir, scan_name))
plots.append(xrtplot.XYCPlot(beam='screen03beamLocal01', title='Sample-XZ',
xaxis=xrtplot.XYCAxis(label='x', unit='mm', data=raycing.get_x),
yaxis=xrtplot.XYCAxis(label='z', unit='mm', data=raycing.get_z),
aspect='auto', saveName='Sample-XZ.png'
))
for plot in plots:
plot.saveName = os.path.join(subdir, scan_name,
plot.title + '-%sm' % bl.bentLaueCylinder02.Rx + '.png'
)
plot.persistentName = plot.saveName.replace('.png', f'.{resol}')
return plots
def define_plots_diver(bl):
plots = []
scan_name = 'diver-screen-'
if not os.path.exists(os.path.join(subdir, scan_name)):
os.mkdir(os.path.join(subdir, scan_name))
plots.append(xrtplot.XYCPlot(beam='screen02beamLocal01', title=f'{scan_name}',
xaxis=xrtplot.XYCAxis(label='x', unit='mm', data=raycing.get_x),
yaxis=xrtplot.XYCAxis(label=r'$x^{\prime}$', unit='', data=raycing.get_xprime),
aspect='auto', saveName=f'{scan_name}_Sample-XX.png'
))
for plot in plots:
plot.saveName = os.path.join(subdir,scan_name,
plot.title + '-%sm' % bl.bentLaueCylinder01.Rx + '.png'
)
plot.persistentName = plot.saveName.replace('.png', f'.pickle')
return plots
def change_screen(plts, bl):
scan_name = 'change-screen-%s' % (bl.bentLaueCylinder02.Rx)
d0=bl.screen03.center[1]
for dist in np.linspace(-500., 500., 50):
bl.screen03.center[1]=d0+dist
for plot in plts:
plot.xaxis.limits=None
plot.yaxis.limits = None
plot.caxis.limits = None
plot.saveName = os.path.join(subdir, scan_name,
plot.title + '_%s' % bl.screen03.center[1] + '.png'
)
plot.persistentName = plot.saveName.replace('png', f'{resol}')
yield
def main():
beamLine = SKIFNSTU()
diver=False
dist0=beamLine.bentLaueCylinder02 .center[1]
beamLine.align_energy(E0, 1000)
beamLine.alignE = E0
# for R in np.linspace(-2000., -500., 5):
# beamLine.bentLaueCylinder01.Rx = R
# beamLine.bentLaueCylinder02.Rx = R
# beamLine.bentLaueCylinder01.Ry = R/1.e6
# beamLine.bentLaueCylinder02.Ry = R/1.e6
# plots = define_plots(beamLine)
# scan = change_screen
# if (diver==False):
# beamLine.screen03.center[1] = dist0+crystal_focus(subdir +
# '\diver-screen-\diver-screen-' + '-%sm' % beamLine.bentLaueCylinder01.Rx + '.pickle')
# if diver:
# scan = None
# plots = define_plots_diver(beamLine)
#
#
# xrtrun.run_ray_tracing(
# plots=plots,
# backend=r"raycing",
# repeats=5,
# beamLine=beamLine,
# generator=scan,
# generatorArgs=[plots, beamLine]
# )
# beamLine.screen03.center[1]=dist0+10000
beamLine.glow()
if __name__ == '__main__':
main() | Kutkin-Oleg/SKIF | SKIF_NSTU_SCW/scans.py | scans.py | py | 3,966 | python | en | code | 0 | github-code | 6 |
14117180742 | # First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
# Specify the path where the file is residing
csvpath = os.path.join('Resources', 'election_data.csv')
# Declare variables and intialize
total_votes = 0
charles_votes = 0
diana_votes = 0
raymon_votes = 0
# Method 2: Improved Reading using CSV module
with open(csvpath) as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
print(csvreader)
# Read the header row first (skip this step if there is now header)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
# Read each row of data after the header
for row in csvreader:
print(row)
# Count the total votes in the dataset
total_votes = total_votes + 1
# candidates name is listed in row 2 of the dataset
candidate_name = row[2]
# count votes for each candidate
if "Charles Casper Stockham" == candidate_name:
charles_votes = charles_votes + 1
if "Diana DeGette" == candidate_name:
diana_votes = diana_votes + 1
if "Raymon Anthony Doane" == candidate_name:
raymon_votes = raymon_votes + 1
# Find percentage votes for each candidate
charles_percent = (charles_votes / total_votes) * 100
diana_percent = (diana_votes / total_votes) * 100
raymon_percent = (raymon_votes / total_votes) * 100
# To find the winner of the election, zip list together to form dictionary
if charles_votes > diana_votes and charles_votes > raymon_votes:
winner = "Charles Casper Stockham"
elif diana_votes > charles_votes and diana_votes > raymon_votes:
winner = "Diana DeGette"
else:
winner ="Raymon Anthony Doane"
# print to terminal
print("Election Results")
print("--------------------------------------")
print(f"Total Votes: {str(total_votes)}")
print("--------------------------------------")
print(f"Charles Casper Stockham: {charles_percent:.3f}% ({charles_votes})")
print(f"Diana DeGette: {diana_percent:.3f}% ({diana_votes})")
print(f"Raymon Anthony Doane: {raymon_percent:.3f}% ({raymon_votes})")
print("--------------------------------------")
print(f"Winner: {winner}")
print("--------------------------------------")
# write to file
# Specify the file to write to
output_path = os.path.join("Analysis", "election_result.txt")
# Open the file using "write" mode. Specify the variable to hold the contents
with open(output_path, 'w+') as file:
# Initialize writer
file.write(f"Election Results\n")
file.write("\n")
file.write(f"-----------------------------------\n")
file.write("\n")
file.write(f"Total Votes: {total_votes}\n")
file.write("\n")
file.write(f"-------------------------------------\n")
file.write("\n")
file.write(f"Charles Casper Stockham: {charles_percent:.3f}% ({charles_votes})\n")
file.write(f"Diana DeGette: {diana_percent:.3f}% ({diana_votes})\n")
file.write(f"Raymon Antony Doane: {raymon_percent:.3f}% ({raymon_votes})\n")
file.write(f"-------------------------------------\n")
file.write(f"Winner: {winner}\n")
file.write(f"-------------------------------------\n")
| Dailyneed/python-challenge | PyPoll/main.py | main.py | py | 3,426 | python | en | code | 0 | github-code | 6 |
27516283256 | import random
from discord.ext import commands
class Hive(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command(name='roll_dice',
help='<min> <max>')
async def roll_dice(self, ctx, min: int, max: int):
await ctx.send(random.randint(min, max))
def setup(bot):
bot.add_cog(Hive(bot))
| tintin10q/hive-discord-bot | commands/roll_dice.py | roll_dice.py | py | 394 | python | en | code | 0 | github-code | 6 |
21033229877 | """
All together
Demonstrate how you can build a quick and dirty framework with a bottle like
API.
Chick is the main application frame.
CapitalizeResponse is a middleware which you can use to wrap your application.
It stores session information, and it capitalizes all responses.
"""
def request_factory(env):
"""
Dynamically create a Request class with slots and read
only attributes
"""
class Request:
__slots__ = [k.replace(".", "_").lower() for k in env.keys()]
def __setattr__(self, name, value):
try:
getattr(self, name)
raise ValueError("Can't modify {}".format(name))
except AttributeError:
super().__setattr__(name, value)
request = Request()
for k, v in env.items():
setattr(request, k.replace(".", "_").lower(), v)
return request
class Chick:
"""
A WSGI Application framework with API inspired by Bottle and Flask.
There is No HTTPRequest Object and No HTTPResponse object.
Just barebone routing ...
"""
routes = {}
def __call__(self, environ, start_response):
try:
callback, method = self.routes.get(environ.get('PATH_INFO'))
except TypeError:
start_response('404 Not Found', [('Content-Type', 'text/plain')])
return [b'404 Not Found']
if method != environ.get('REQUEST_METHOD'):
start_response('405 Method Not Allowed',
[('Content-Type', 'text/plain')])
return [b'404 Method Not Allowed']
request = request_factory(environ)
response = callback(request)
start_response(response.status, response.content_type)
return (response.body.encode(),)
def add_route(self, path, wrapped, method):
self.routes[path] = (wrapped, method)
def get(self, path):
def decorator(wrapped):
self.add_route(path, wrapped, 'GET')
return wrapped
return decorator
def post(self, path):
def decorator(wrapped):
self.add_route(path, wrapped, 'POST')
return wrapped
return decorator
class Response:
__slots__ = ('body', 'status', 'content_type')
def __init__(self, body, status='200 OK',
content_type="text/plain"):
self.body = body
self.status = status
self.content_type = [('Content-Type', content_type)]
def __iter__(self):
return [self.body]
class CapitalizeResponseMiddleware:
"""
A middlerware that manipulates the response
"""
def __init__(self, app):
self.app = app
self.visits = 0 # state keeping made easier
def __call__(self, environ, start_response, *args, **kw):
self.visits += 1
response = self.app(environ, start_response)
response = [line.upper() for line in response]
response.append("\nYou visited {} times".format(self.visits).encode())
return response
chick = Chick()
@chick.get("/")
def index(request):
return Response("hello world!")
@chick.post("/input/")
def test_post(request):
return Response("")
@chick.get("/response/")
def response(request):
res = "".join("{}: {}\n".format(s, getattr(request, s))
for s in request.__slots__)
return Response("hello world!\n" + res)
capital_chick = CapitalizeResponseMiddleware(chick)
if __name__ == "__main__":
from wsgiref.simple_server import make_server
httpd = make_server('', 8000, capital_chick)
print("Serving on port 8000...")
# Serve until process is killed
httpd.serve_forever()
| oz123/advanced-python | examples/all_together/chick_w_request_response.py | chick_w_request_response.py | py | 3,678 | python | en | code | 9 | github-code | 6 |
28156175074 | import argparse
import sys
from pathlib import Path
from typing import List
import numpy as np
import torch
from thre3d_atom.modules.volumetric_model.volumetric_model import (
VolumetricModel,
VolumetricModelRenderingParameters,
)
from thre3d_atom.rendering.volumetric.voxels import (
GridLocation,
FeatureGrid,
VoxelSize,
)
from thre3d_atom.utils.constants import (
NUM_RGBA_CHANNELS,
)
from thre3d_atom.utils.imaging_utils import SceneBounds, CameraIntrinsics
def parse_arguments(args: List[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
"Converts Feature-Grid (+ mlp model) into an RGBA grid",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# fmt: off
# Required arguments
parser.add_argument("-i", "-m", "--model_path",
action="store", type=Path, required=True, help="path to the trained 3dSGDS model")
parser.add_argument("-o", "--output_dir",
action="store", type=Path, required=True, help="path to the output directory")
# fmt: on
parsed_args = parser.parse_args(args)
return parsed_args
## noinspection PyUnresolvedReferences
def main() -> None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
args = parse_arguments(sys.argv[1:])
# load the numpy model:
np_model = np.load(args.model_path, allow_pickle=True)
features = torch.from_numpy(np_model["grid"]).to(device=device)
grid_size = np_model["grid_size"]
grid_location = GridLocation(*np_model["grid_center"])
grid_dim = features.shape[:-1]
x_voxel_size = grid_size[0] / (grid_dim[0] - 1)
y_voxel_size = grid_size[1] / (grid_dim[1] - 1)
z_voxel_size = grid_size[2] / (grid_dim[2] - 1)
feature_grid = FeatureGrid(
features=features.permute(3, 0, 1, 2),
voxel_size=VoxelSize(x_voxel_size, y_voxel_size, z_voxel_size),
grid_location=grid_location,
tunable=True,
)
render_params = VolumetricModelRenderingParameters(
num_rays_chunk=1024,
num_points_chunk=65536,
num_samples_per_ray=256,
num_fine_samples_per_ray=0,
perturb_sampled_points=True,
density_noise_std=0.0,
)
vol_mod = VolumetricModel(
render_params=render_params,
grid_dims=grid_dim,
feature_dims=NUM_RGBA_CHANNELS,
grid_size=grid_size,
grid_center=grid_location,
device=device,
)
vol_mod.feature_grid = feature_grid
torch.save(
vol_mod.get_save_info(
extra_info={
"scene_bounds": SceneBounds(0.1, 2.5),
"camera_intrinsics": CameraIntrinsics(256, 256, 256),
"hemispherical_radius": 1.0,
}
),
f"{args.output_dir}/model_rgba.pth",
)
if __name__ == "__main__":
main()
| akanimax/3inGAN | projects/thre3ingan/experimental/create_vol_mod_from_npy.py | create_vol_mod_from_npy.py | py | 2,878 | python | en | code | 3 | github-code | 6 |
73017760828 | from rb_api.dto.two_mode_graph.article_keyword_dto import ArticleKeywordDTO
from rb_api.json_serialize import JsonSerialize
import json
class TopicEvolutionDTO(JsonSerialize):
def __init__(self):
self.wordList = []
self.yearList = []
def add_year(self, year: int) -> None:
self.yearList.append(year)
def add_keyword(self, value: str, score: float) -> None:
word_values = [word for word in self.wordList if word.value == value]
if word_values:
word_values[0].score_list.append(score) # there is only 1 word for value
return
keyword = ArticleKeywordDTO(value, "Keyword")
keyword.scoreList.append(score)
self.wordList.append(keyword)
def normalize(self):
for year_index, _ in enumerate(self.yearList):
maxim = max([word.score_list[year_index] for word in self.wordList])
if maxim > 0:
for word in self.wordList:
word.score_list[year_index] = word.score_list[year_index] / maxim
def serialize(self):
return json.dumps(self.__dict__)
| rwth-acis/readerbenchpyapi | rb_api/dto/two_mode_graph/topic_evolution_dto.py | topic_evolution_dto.py | py | 1,146 | python | en | code | 1 | github-code | 6 |
29585592655 | from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.dialects.sqlite import *
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from typing import List
from pydantic import BaseModel, constr
app = FastAPI()
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args = {"check_same_thread": False})
session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = session()
try:
yield db
finally:
db.close()
class Books(Base):
__tablename__ = 'book'
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String(50))
author = Column(String(50))
publisher = Column(String(50))
Base.metadata.create_all(bind=engine)
class Book(BaseModel):
id: int
title: str
author:str
publisher: str
class Config:
orm_mode = True
@app.post('/add_new', response_model=Book)
def add_book(b1: Book, db: Session = Depends(get_db)):
bk=Books(id=b1.id, title=b1.title, author=b1.author,
publisher=b1.publisher)
db.add(bk)
db.commit()
db.refresh(bk)
return Books(**b1.model_dump())
@app.get('/list', response_model=List[Book])
def get_books(db: Session = Depends(get_db)):
recs = db.query(Books).all()
return recs
@app.get("/book/{id}")
async def get_book(id: int, db: Session = Depends(get_db)):
return db.query(Books).filter(Books.id == id).first()
@app.put('/update/{id}', response_model=Book)
def update_book(id:int, book:Book, db: Session = Depends(get_db)):
b1 = db.query(Books).filter(Books.id == id).first()
b1.id=book.id
b1.title=book.title
b1.author=book.author
b1.publisher=book.publisher
db.commit()
return db.query(Books).filter(Books.id == id).first()
@app.delete("/delete{id}")
async def delete_book(id: int, db: Session = Depends(get_db)):
try:
db.query(Books).filter(Books.id == id).delete()
db.commit()
except Exception as e:
raise Exception(e)
return {"delete status": "success"}
| vdtheone/crud_fastapi | main.py | main.py | py | 2,199 | python | en | code | 0 | github-code | 6 |
23553579650 | import numpy as np
import pandas as pd
from scipy.io import loadmat
def glf(
mz: np.ndarray,
intens: np.ndarray,
delta_cts: float = 0.1,
delta_mz: float = 2000.0,
k: float = 7.0
) -> np.ndarray:
y1 = np.max(intens) * 0.02
y2 = (np.max(intens) - y1) * delta_cts
res = y1 + y2 / (1 + np.e ** (y2 * k / (mz - delta_mz)))
return res
def parse_database(database: np.ndarray, strain_precision = "full") -> pd.DataFrame:
prec = {"genus": 1, "species": 2, "full": 3}
num_entities = len(database)
mz, peaks, strain = [], [], []
for i in range(num_entities):
curr_entity = database[i][0]
for obs_id in range(len(curr_entity["tax"])):
observation = curr_entity[obs_id]
mz.append(observation["pik"][0])
peaks.append(observation["pik"][1])
st = observation["tax"][0]
st = st.split(" ")
st = " ".join(st[:prec[strain_precision]])
strain.append(st)
df = pd.DataFrame(columns=["Intens.", "m/z", "strain"], dtype="object")
df["Intens."] = peaks
df["m/z"] = mz
df["strain"] = strain
return df
def read_pkf(pkf_path: str, strain_precision: str = "full"):
data = loadmat(pkf_path)
database = data["C"]["dbs"][0]
df = parse_database(database, strain_precision)
return df
| Wimplex/AIJourney_AI4Bio_4th | source/utils/pkf.py | pkf.py | py | 1,351 | python | en | code | 0 | github-code | 6 |
22734703340 | # -*- coding: utf-8 -*-
import json
import os
import sys
import xbmc
import xbmcvfs
import xbmcaddon
import xbmcgui
import xbmcplugin
import pyxbmct
import requests
import io
import unicodedata
import re
import ast
import sqlite3
import shutil
import time
from medias import Media, TMDB
import medias
import zipfile
import threading
import datetime
from upNext import upnext_signal
import widget
from datetime import datetime
from datetime import timedelta
from bs4 import BeautifulSoup
try:
import iptv
vIPTV = True
except ImportError:
vIPTV = False
try:
# Python 3
from urllib.parse import parse_qsl
from util import *
except ImportError:
from urlparse import parse_qsl
try:
# Python 3
from urllib.parse import unquote, urlencode, quote
unichr = chr
except ImportError:
# Python 2
from urllib import unquote, urlencode, quote
try:
# Python 3
from html.parser import HTMLParser
except ImportError:
# Python 2
from HTMLParser import HTMLParser
pyVersion = sys.version_info.major
pyVersionM = sys.version_info.minor
if pyVersionM == 11:
import cryptPaste11 as cryptage
import scraperUPTO11 as scraperUPTO
elif pyVersionM == 8:
import cryptPaste8 as cryptage
import scraperUPTO8 as scraperUPTO
#import scraperUPTO
elif pyVersionM == 9:
import cryptPaste9 as cryptage
import scraperUPTO9 as scraperUPTO
elif pyVersionM == 10:
import cryptPaste10 as cryptage
import scraperUPTO10 as scraperUPTO
else:
notice(pyVersion)
notice(pyVersionM)
from cryptPaste import Crypt
from pastebin import Pastebin
from apiTraktHK import TraktHK
import createbdhk
import random
import uptobox
from strm import Strm, configureSTRM
import feninfo
try:
BDMEDIA = xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P/medias.bd')
BDMEDIANew = xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P/mediasNew.bd')
except: pass
import loadhk3
class FenInfo(pyxbmct.AddonFullWindow):
#def __init__(self, numId, title="", typM="film"):
def __init__(self, title=""):
"""Class constructor"""
# Call the base class' constructor.
self.numId = title.split("*")[0]
title = title.split("*")[1]
self.typM = "film"
super(FenInfo, self).__init__(title)
# Set width, height and the grid parameters
self.setGeometry(1250, 700, 50, 30)
self.setBackground(xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/png/fond.png'))
# Call set controls method
self.set_controls()
# Call set navigation method.
self.set_navigation()
# Connect Backspace button to close our addon.
self.connect(pyxbmct.ACTION_NAV_BACK, self.close)
def set_controls(self):
"""Set up UI controls"""
notice(self.numId)
self.colorMenu = '0xFFFFFFFF'
size = self.getTaille()
sql = "SELECT title, overview, year, genres, backdrop, popu, numId, poster, runtime, saga FROM filmsPub WHERE numId={}".format(self.numId)
liste = createbdhk.extractMedias(sql=sql)
try:
title, overview, year, genre, backdrop, popu, numId, poster, duration, saga = liste[0]
backdrop = "http://image.tmdb.org/t/p/" + size[1] + backdrop
poster = "http://image.tmdb.org/t/p/" + size[0] + poster
except:
return
#backdrop
#image = pyxbmct.Image(backdrop, colorDiffuse='0x22FFFFFF')
image = pyxbmct.Image(backdrop)
self.placeControl(image, 0, 7, rowspan=42, columnspan=23)
f = xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/png/fond.png')
fond = pyxbmct.Image(f)
self.placeControl(fond, 0, 0, rowspan=54, columnspan=30)
#f = xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/png/fond.png')
#fond = pyxbmct.Image(f)
#self.placeControl(fond, 0, 14, rowspan=25, columnspan=15)
logo = ""
#logo, clearart, banner = extractFanart(self.numId)
#urlFanart = "http://assets.fanart.tv/fanart/movie/"
#clearlogo ou title
if logo:
imageLogo = pyxbmct.Image(urlFanart + logo)
self.placeControl(imageLogo, 0, 0, rowspan=8, columnspan=7)
else:
label = pyxbmct.Label(title, font='font_MainMenu')
self.placeControl(label, 2, 0, columnspan=15)
#poster
#if clearart:
# imageClearart = pyxbmct.Image(urlFanart + clearart)
# self.placeControl(imageClearart, 35, 25, rowspan=12, columnspan=5)
#else:
#poster = pyxbmct.Image(poster)
#self.placeControl(poster, 29, 25, rowspan=24, columnspan=5)
"""
#menu
paramstring = self.links.split("*")
cr = cryptage.Crypt()
dictResos = cr.extractReso([(x.split("#")[0].split("@")[0], x.split("#")[0].split("@")[1]) for x in paramstring])
dictResos = {x.split("#")[0].split("@")[1]: dictResos[x.split("#")[0].split("@")[1]] if dictResos[x.split("#")[0].split("@")[1]] else x.split("#")[1] for x in paramstring}
self.paramstring = orderLiens(dictResos, paramstring)
tabRelease = [dictResos[x.split("#")[0].split("@")[1]][2] for i, x in enumerate(self.paramstring)]
self.tabNomLien = ["#%d [COLOR red][%s - %.2fGo][/COLOR] -- [Release: %s]" %(i + 1, dictResos[x.split("#")[0].split("@")[1]][0], (int(dictResos[x.split("#")[0].split("@")[1]][1]) / 1000000000.0), tabRelease[i]) for i, x in enumerate(self.paramstring)]
"""
#labelMenu = pyxbmct.Label('MENU', textColor=self.colorMenu)
#self.placeControl(labelMenu, 31, 0, columnspan=10)
self.menu = pyxbmct.List('font13', _itemHeight=30, _alignmentY=90)
self.placeControl(self.menu, 29, 0, rowspan=12, columnspan=30)
#, "Acteurs & Réalisateur"
self.menu.addItems(["[COLOR blue]Bande Annonce[/COLOR]", "[COLOR green]Links[/COLOR]", "Saga", "Suggestions", "Similaires", "Studio"])
#self.menu.addItems(self.tabNomLien)
self.connect(self.menu, lambda: self.listFunction(self.menu.getListItem(self.menu.getSelectedPosition()).getLabel()))
#overview
#labelSynop = pyxbmct.Label('SYNOPSIS', textColor=colorMenu)
#self.placeControl(labelSynop, 14, 0, columnspan=10)
self.synop = pyxbmct.TextBox('font13', textColor='0xFFFFFFFF')
self.placeControl(self.synop, 10, 0, rowspan=16, columnspan=18)
self.synop.setText("[COLOR green]SYNOPSIS: [/COLOR]" + overview)
self.synop.autoScroll(4000, 2000, 3000)
#============================================================================ ligne notation duree =========================================
ligneNot = 26
#duree
text = "0xFFFFFFFF"
current_time = datetime.now()
future_time = current_time + timedelta(minutes=duration)
heureFin = future_time.strftime('%H:%M')
label = pyxbmct.Label('%s %d mns (se termine à %s)' %(year, duration, heureFin), textColor=self.colorMenu)
self.placeControl(label, ligneNot, 0, columnspan=12)
#notation
label = pyxbmct.Label('%0.1f/10' %float(popu),textColor=self.colorMenu)
self.placeControl(label, ligneNot, 12, columnspan=12)
#self.slider = pyxbmct.Slider(orientation=xbmcgui.HORIZONTAL)
#self.placeControl(self.slider, ligneNot + 1, 14, pad_y=1, rowspan=2, columnspan=4)
#self.slider.setPercent(media.popu * 10)
"""
#play
p = 0
self.buttonLinks = pyxbmct.Button("Links")
self.placeControl(self.buttonLinks, 31, p, columnspan=3, rowspan=5)
self.connect(self.buttonLinks, self.buttonFx)
p += 3
self.buttonBa = pyxbmct.Button("Bande Annonce")
self.placeControl(self.buttonBa, 31, p, columnspan=3, rowspan=5)
p += 3
self.buttonSaga = pyxbmct.Button("Saga")
self.placeControl(self.buttonSaga, 31, p, columnspan=3, rowspan=5)
p += 3
self.buttonReco = pyxbmct.Button("Recommendations")
self.placeControl(self.buttonReco, 31, p, columnspan=3, rowspan=5)
p += 3
self.buttonSimi = pyxbmct.Button("Similaires")
self.placeControl(self.buttonSimi, 31, p, columnspan=3, rowspan=5)
p += 3
self.buttonStudio = pyxbmct.Button("Studio")
self.placeControl(self.buttonStudio, 31, p, columnspan=3, rowspan=5)
"""
#fav HK
self.radiobutton = pyxbmct.RadioButton("Ajouter Fav's HK", textColor=self.colorMenu)
self.placeControl(self.radiobutton, 26, 25, columnspan=5, rowspan=3)
self.connect(self.radiobutton, self.radio_update)
if ADDON.getSetting("bookonline") != "false":
listeM = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=movies" %(ADDON.getSetting("bookonline_site"), ADDON.getSetting("bookonline_name")))
listeM = [int(x) for x in listeM]
else:
listeM = list(widget.extractFavs())
if int(self.numId) in listeM:
self.radiobutton.setSelected(True)
self.radiobutton.setLabel("Retirer Fav's HK")
#=============================================================================================================================================
#genres
label = pyxbmct.FadeLabel()
self.placeControl(label, 26, 17, columnspan=5)
label.addLabel(genre)
# sagas
self.sagaOk = False
#sql = "SELECT s.title, s.poster, s.numId FROM saga AS s WHERE s.numId=(SELECT t.numIdSaga FROM sagaTitle AS t WHERE t.numId={})".format(self.numId)
#saga = extractMedias(sql=sql)
#notice(saga)
saga =0
if saga:
self.sagaOk = True
label = pyxbmct.Label("SAGA", textColor=self.colorMenu)
self.placeControl(label, 43, 22, columnspan=4)
if saga[0][1]:
imFoc = "http://image.tmdb.org/t/p/w92" + saga[0][1]
else:
imFoc = ""
txRea = saga[0][0]
self.bSaga = pyxbmct.Button(txRea, focusTexture=imFoc, noFocusTexture=imFoc, font="font10", focusedColor='0xFFFF0000', alignment=pyxbmct.ALIGN_CENTER, shadowColor='0xFF000000')
self.placeControl(self.bSaga, 40, 24, rowspan=10, columnspan=2)
self.connect(self.bSaga, lambda: self.affSaga(str(saga[0][2])))
self.setCasting()
# cast
#mdb = TMDB(__keyTMDB__)
#liste = mdb.castFilm(self.numId)
#notice(liste)
#label = pyxbmct.Label('REALISATEUR:',textColor=colorMenu)
#self.placeControl(label, 8, 0, columnspan=5)
#rea = ", ".join([x[0] for x in liste if x[1] == "Réalisateur"])
#label = pyxbmct.Label(rea)
#self.placeControl(label, 8, 4, columnspan=8)
#label = pyxbmct.Label('ACTEURS:',textColor=colorMenu)
#self.placeControl(label, 11, 0, columnspan=5)
#acteurs = ", ".join(["%s (%s)" %(x[0], x[1]) for x in liste if x[1] != "Réalisateur"][:3])
#label = pyxbmct.FadeLabel(font="font12")
#self.placeControl(label, 11, 4, columnspan=10)
#label.addLabel(acteurs)
def buttonFx(self):
sql = "SELECT GROUP_CONCAT(l.link, '*') FROM filmsPubLink as l WHERE l.numId={}".format(self.numId)
links = createbdhk.extractMedias(sql=sql, unique=1)[0]
#self.close()
#affLiens2({"u2p":self.numId, "lien": links})
#xbmc.executebuiltin('Dialog.Close(busydialog)')
#xbmc.executebuiltin("RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=afficheLiens&lien={}&u2p={})".format(links, self.numId), True)
#xbmc.executebuiltin("ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=afficheLiens&lien={}&u2p={},return)".format(links, self.numId))
#xbmc.executebuiltin("ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=playHK&lien=IBSfuEFS2%404U3iXKqCCQZq%231080.Multi.WEB&u2p=852830,return)")
#self.close()
def affSaga(self, numId):
showInfoNotification(numId)
mediasHK({"famille": "sagaListe", "u2p": numId})
self.close()
def getBa(self, params):
numId = params["u2p"]
typMedia = params["typM"]
mdb = TMDB(KEYTMDB)
tabBa = mdb.getNumIdBA(numId, typMedia)
if tabBa:
dialog = xbmcgui.Dialog()
selectedBa = dialog.select("Choix B.A", ["%s (%s)" %(x[0], x[1]) for x in tabBa], 0, 0)
if selectedBa != -1:
keyBa = tabBa[selectedBa][2]
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.youtube/?action=play_video&videoid={})".format(keyBa), True)
self.close()
def setCasting(self):
mdb = TMDB(KEYTMDB)
liste = mdb.castFilm(self.numId)
nbListe = len(liste)
posy = 0
self.tabCast = [None] * 20
self.tabCast2 = [None] * 20
for i, casting1 in enumerate(liste[:10]):
self.tabCast2[i] = casting1
if self.tabCast2[i][2]:
imFoc = "http://image.tmdb.org/t/p/w342" + self.tabCast2[i][2]
else:
imFoc = ""
txRea = "%s (%s)" %(self.tabCast2[i][0], self.tabCast2[i][1])
self.tabCast[i] = pyxbmct.Button(txRea, focusTexture=imFoc, noFocusTexture=imFoc, font="font10", focusedColor='0xFFFF0000', alignment=pyxbmct.ALIGN_CENTER, shadowColor='0xFF000000')
self.placeControl(self.tabCast[i], 38, posy, rowspan=15, columnspan=3)
self.connect(self.tabCast[i], lambda: self.affCastingFilmo(str(self.tabCast2[i][3])))
posy += 3
def affCastingFilmo(self, numId):
mediasHK({"famille": "cast", "u2p": numId})
self.close()
def getTaille(self):
dictSize = {"Basse": ("w185/", "w780/"),
"Moyenne": ("w342/", "w1280/"),
"Haute": ("w500/", "original/")}
v = ADDON.getSetting("images_sizes")
return dictSize[v]
def setAnimation(self, control):
# Set fade animation for all add-on window controls
control.setAnimations([('WindowOpen', 'effect=fade start=0 end=100 time=500',),
('WindowClose', 'effect=fade start=100 end=0 time=500',)])
def set_navigation(self):
"""Set up keyboard/remote navigation between controls."""
self.menu.controlUp(self.radiobutton)
if self.tabCast:
self.menu.controlDown(self.tabCast[0])
self.menu.controlLeft(self.tabCast[0])
self.radiobutton.controlUp(self.tabCast[0])
self.menu.controlRight(self.radiobutton)
self.radiobutton.controlRight(self.menu)
self.radiobutton.controlLeft(self.menu)
self.radiobutton.controlDown(self.menu)
self.setFocus(self.menu)
if self.tabCast:
for i in range(len([x for x in self.tabCast if x])):
self.tabCast[i].controlUp(self.menu)
self.tabCast[i].controlDown(self.radiobutton)
if (i + 1) < len([x for x in self.tabCast if x]):
self.tabCast[i].controlRight(self.tabCast[i + 1])
else:
if self.sagaOk:
self.tabCast[i].controlRight(self.bSaga)
if (i - 1) > -1:
self.tabCast[i].controlLeft(self.tabCast[i - 1])
def radio_update(self):
# Update radiobutton caption on toggle
#liste favs
if self.radiobutton.isSelected():
self.radiobutton.setLabel("Retirer Fav's HK")
gestionFavHK({"mode": "ajout", "u2p": self.numId, "typM": "movies"})
else:
self.radiobutton.setLabel("Ajouter Fav's HK")
gestionFavHK({"mode": "sup", "u2p": self.numId, "typM": "movies"})
def listFunction(self, tx):
#lsite fonction du menu
#self.close()
if "Bande" in tx:
self.getBa({"u2p": self.numId, "typM": "movie"})
elif "Links" in tx:
sql = "SELECT GROUP_CONCAT(l.link, '*') FROM filmsPubLink as l WHERE l.numId={}".format(self.numId)
links = createbdhk.extractMedias(sql=sql, unique=1)[0]
#affLiens2({"u2p": self.numId, "lien": links})
#xbmc.executebuiltin("ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=playHK&lien=IBSfuEFS2%404U3iXKqCCQZq%231080.Multi.WEB&u2p=852830,return)")
#xbmc.executebuiltin("ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=afficheLiens&lien={}&u2p={},return)".format(links, self.numId))
playMediaHK({"lien": "IBSfuEFS2@4U3iXKqCCQZq#1080.Multi.WEB", "u2p": "852830"})
elif "Simi" in tx:
loadSimReco2({"u2p": self.numId, "typ": "Similaires", "typM": "movie"})
elif "Sugg" in tx:
loadSimReco2({"u2p": self.numId, "typ": "Recommendations", "typM": "movie"})
class FenFilmDetail(pyxbmct.AddonDialogWindow):
def __init__(self, title='', numId="", links=""):
"""Class constructor"""
# Call the base class' constructor.
super(FenFilmDetail, self).__init__(title)
# Set width, height and the grid parameters
self.numId = numId
self.links = links
self.setGeometry(1000, 560, 50, 30)
# Call set controls method
self.set_controls()
# Call set navigation method.
self.set_navigation()
# Connect Backspace button to close our addon.
self.connect(pyxbmct.ACTION_NAV_BACK, self.close)
def set_controls(self):
"""Set up UI controls"""
self.colorMenu = '0xFFFFFFFF'
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId={}".format(self.numId)
movies = extractMedias(sql=sql)
media = Media("movie", *movies[0])
#backdrop
image = pyxbmct.Image(media.backdrop, colorDiffuse='0x22FFFFFF')
self.placeControl(image, 0, 0, rowspan=50, columnspan=30)
logo, clearart, banner = extractFanart(self.numId)
urlFanart = "http://assets.fanart.tv/fanart/movie/"
#clearlogo ou title
if logo:
imageLogo = pyxbmct.Image(urlFanart + logo)
self.placeControl(imageLogo, 0, 0, rowspan=8, columnspan=7)
else:
label = pyxbmct.Label(media.title, font='font_MainMenu')
self.placeControl(label, 2, 0, columnspan=15)
#poster
#if clearart:
# imageClearart = pyxbmct.Image(urlFanart + clearart)
# self.placeControl(imageClearart, 35, 25, rowspan=12, columnspan=5)
#else:
poster = pyxbmct.Image(media.poster)
self.placeControl(poster, 0, 25, rowspan=23, columnspan=5)
#menu
paramstring = self.links.split("*")
cr = cryptage.Crypt()
dictResos = cr.extractReso([(x.split("#")[0].split("@")[0], x.split("#")[0].split("@")[1]) for x in paramstring])
dictResos = {x.split("#")[0].split("@")[1]: dictResos[x.split("#")[0].split("@")[1]] if dictResos[x.split("#")[0].split("@")[1]] else x.split("#")[1] for x in paramstring}
self.paramstring = orderLiens(dictResos, paramstring)
tabRelease = [dictResos[x.split("#")[0].split("@")[1]][2] for i, x in enumerate(self.paramstring)]
self.tabNomLien = ["#%d [COLOR red][%s - %.2fGo][/COLOR] -- [Release: %s]" %(i + 1, dictResos[x.split("#")[0].split("@")[1]][0], (int(dictResos[x.split("#")[0].split("@")[1]][1]) / 1000000000.0), tabRelease[i]) for i, x in enumerate(self.paramstring)]
#labelMenu = pyxbmct.Label('MENU', textColor=self.colorMenu)
#self.placeControl(labelMenu, 31, 0, columnspan=10)
self.menu = pyxbmct.List('font13', _itemHeight=30)
self.placeControl(self.menu, 29, 0, rowspan=24, columnspan=25)
#, "Acteurs & Réalisateur"
#self.menu.addItems(["[COLOR blue]Bande Annonce[/COLOR]", "[COLOR green]Lire[/COLOR]", "Suggestions", "Similaires"])
self.menu.addItems(self.tabNomLien)
self.connect(self.menu, lambda: self.listFunction(self.menu.getListItem(self.menu.getSelectedPosition()).getLabel()))
#overview
#labelSynop = pyxbmct.Label('SYNOPSIS', textColor=colorMenu)
#self.placeControl(labelSynop, 14, 0, columnspan=10)
self.synop = pyxbmct.TextBox('font13', textColor='0xFFFFFFFF')
self.placeControl(self.synop, 10, 0, rowspan=16, columnspan=25)
self.synop.setText("[COLOR green]SYNOPSIS: [/COLOR]" + media.overview)
self.synop.autoScroll(1000, 2000, 3000)
#============================================================================ ligne notation duree =========================================
ligneNot = 26
#duree
text = "0xFFFFFFFF"
current_time = datetime.now()
future_time = current_time + timedelta(minutes=media.duration)
heureFin = future_time.strftime('%H:%M')
label = pyxbmct.Label('%s Durée: %d mns (se termine à %s)' %(media.year, media.duration, heureFin), textColor=self.colorMenu)
self.placeControl(label, ligneNot, 0, columnspan=12)
#notation
label = pyxbmct.Label('Note %0.1f/10' %float(media.popu),textColor=self.colorMenu)
self.placeControl(label, ligneNot, 12, columnspan=12)
#self.slider = pyxbmct.Slider(orientation=xbmcgui.HORIZONTAL)
#self.placeControl(self.slider, ligneNot + 1, 14, pad_y=1, rowspan=2, columnspan=4)
#self.slider.setPercent(media.popu * 10)
#fav HK
self.radiobutton = pyxbmct.RadioButton("Ajouter Fav's HK", textColor=self.colorMenu)
self.placeControl(self.radiobutton, 26, 20, columnspan=5, rowspan=3)
self.connect(self.radiobutton, self.radio_update)
if __addon__.getSetting("bookonline") != "false":
listeM = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=movies" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
listeM = [int(x) for x in listeM]
else:
listeM = list(widget.extractFavs())
if int(self.numId) in listeM:
self.radiobutton.setSelected(True)
self.radiobutton.setLabel("Retirer Fav's HK")
#=============================================================================================================================================
#genres
label = pyxbmct.Label(' GENRES')
self.placeControl(label, 23, 26, columnspan=3)
genres = [x.strip() for x in media.genre.split(",")]
x, y = 25, 25
for i, genre in enumerate(genres):
f = xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/png/genre/%s.png' %genre)
image = pyxbmct.Image(f)
pas = 9
self.placeControl(image, x, y, rowspan=pas, columnspan=3)
if i % 2:
x += (pas - 2)
y -= 2
else:
y += 2
if i == 3:
break
def set_navigation(self):
"""Set up keyboard/remote navigation between controls."""
self.menu.controlUp(self.radiobutton)
#self.menu.controlDown(self.tabCast[0])
#self.menu.controlLeft(self.tabCast[0])
#self.radiobutton.controlUp(self.tabCast[0])
self.menu.controlRight(self.radiobutton)
self.radiobutton.controlRight(self.menu)
self.radiobutton.controlLeft(self.menu)
self.radiobutton.controlDown(self.menu)
self.setFocus(self.menu)
def radio_update(self):
# Update radiobutton caption on toggle
#liste favs
if self.radiobutton.isSelected():
self.radiobutton.setLabel("Retirer Fav's HK")
gestionFavHK({"mode": "ajout", "u2p": self.numId, "typM": "movies"})
else:
self.radiobutton.setLabel("Ajouter Fav's HK")
gestionFavHK({"mode": "sup", "u2p": self.numId, "typM": "movies"})
def listFunction(self, tx):
#lsite fonction du menu
self.close()
link = self.paramstring[self.tabNomLien.index(tx)]
#showInfoNotification(link)
#
playMediaHK({"u2p":self.numId, "typM": "movies", "lien": link, "skin": "1"})
"""
if "Bande" in tx:
getBa({"u2p": self.numId, "typM": "movie"})
elif "Lire" in tx:
affLiens2({"u2p": self.numId, "lien": self.links})
elif "Simi" in tx:
loadSimReco2({"u2p": self.numId, "typ": "Similaires", "typM": "movie"})
elif "Sugg" in tx:
loadSimReco2({"u2p": self.numId, "typ": "Recommendations", "typM": "movie"})
elif "Act" in tx:
affCast2({"u2p": self.numId, "typM": "movie"})
"""
class replacement_stderr(sys.stderr.__class__):
def isatty(self): return False
sys.stderr.__class__ = replacement_stderr
def debug(content):
log(content, xbmc.LOGDEBUG)
def linkDownload1Fichier(key, linkUrl):
params = {
'url' : linkUrl,
'inline' : 0,
'cdn' : 0,
'restrict_ip': 0,
'no_ssl' : 0,
}
url = 'https://api.1fichier.com/v1/download/get_token.cgi'
r = requests.post(url, json=params, headers={'Authorization':'Bearer {}'.format(key),'Content-Type':'application/json'})
try:
o = r.json()
except JSONDecodeError:
pass
message = ""
url = ""
if 'status' in o:
if o['status'] != 'OK':
message = r.json()['message']
o['url'] = ""
return o["url"], message
else:
#key out => No such user
return url, message
def notice(content):
log(content, xbmc.LOGINFO)
def log(msg, level=xbmc.LOGINFO):
addon = xbmcaddon.Addon()
addonID = addon.getAddonInfo('id')
xbmc.log('%s: %s' % (addonID, msg), level)
def showInfoNotification(message):
xbmcgui.Dialog().notification("U2Pplay", message, xbmcgui.NOTIFICATION_INFO, 5000)
def showErrorNotification(message):
xbmcgui.Dialog().notification("U2Pplay", message,
xbmcgui.NOTIFICATION_ERROR, 5000)
def getkeyUpto():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
Apikey = addon.getSetting("keyupto")
return Apikey
def getkey1fichier():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
Apikey = addon.getSetting("key1fichier")
return Apikey
def getresos():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
resos = [addon.getSetting("resos")]
timing = addon.getSetting("autoplay_delay")
return resos, timing
"""
def getresosOld():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
resos = addon.getSetting("resos")
try:
resos, timing = resos.split("-")
resos = [x.strip() for x in resos.split("=")[1].split(",")]
timing = timing.split("=")[1]
except:
resos = ("720", "1080", "2160")
timing = 0
return resos, timing
"""
def getNbMedias():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
nb = addon.getSetting("nb_items")
return nb
def getOrderDefault():
dictTrie = {"Année": " ORDER BY m.year DESC",
"Titre": " ORDER BY m.title COLLATE NOCASE ASC",
"Popularité": " ORDER BY m.popu DESC",
"Date Release": " ORDER BY m.dateRelease DESC",
"Date Added": " ORDER BY m.id DESC"}
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
ordre = addon.getSetting("lists_orderby")
return dictTrie[ordre]
def getkeyTMDB():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
Apikey = addon.getSetting("apikey")
return Apikey
def getkeyAlldebrid():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
Apikey = addon.getSetting("keyalldebrid")
return Apikey
def getkeyRealdebrid():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
Apikey = addon.getSetting("keyrealdebrid")
return Apikey
def gestionBD(*argvs):
cnx = sqlite3.connect(xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/serie.db'))
cur = cnx.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS serie(
`id` INTEGER PRIMARY KEY,
numId TEXT,
title TEXT,
saison TEXT,
reso TEXT,
pos INTEGER,
UNIQUE (numId, title, saison))
""")
cnx.commit()
if argvs[0] == "update":
cur.execute("REPLACE INTO serie (numId, title, saison, reso, pos) VALUES (?, ?, ?, ?, ?)", argvs[1:])
cnx.commit()
return True
elif argvs[0] == "get":
cur.execute("SELECT reso FROM serie WHERE title=? AND saison=?", argvs[1:])
reso = cur.fetchone()
return reso
elif argvs[0] == "getHK":
cur.execute("SELECT reso FROM serie WHERE numId=? AND saison=?", argvs[1:])
reso = cur.fetchone()
return reso
elif argvs[0] == "last":
cur.execute("SELECT numId, title, saison, reso FROM serie ORDER BY id DESC LIMIT 1")
liste = cur.fetchone()
if liste:
return liste
else:
return ["", "", "", ""]
cur.close()
cnx.close()
'''
def detailsMediaOld(params):
notice(params)
paramstring = params["lien"].split("*")
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
if not typMedia:
xbmc.executebuiltin("Dialog.Close(busydialog)")
xbmc.sleep(500)
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
#typMedia = params["typM"]
numId = params["u2p"]
u2p = params["u2p"]
dialog = xbmcgui.Dialog()
if u2p and numId != "divers":
choix = ["Bande Annonce", "Lire", "Acteurs", "Similaires", "Recommendations"]
selected = dialog.select("Choix", choix, 0, 0)
if selected != -1:
if u2p and numId != "divers":
if "Bande Annonce" == choix[selected]:
mdb = TMDB(__keyTMDB__)
tabBa = mdb.getNumIdBA(numId, typMedia)
if tabBa:
selectedBa = dialog.select("Choix B.A", ["%s (%s)" %(x[0], x[1]) for x in tabBa], 0, 0)
if selectedBa != -1:
keyBa = tabBa[selectedBa][2]
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.youtube/?action=play_video&videoid={})".format(keyBa), True)
return
elif choix[selected] in ["Similaires", "Recommendations"]:
loadSimReco(numId, typMedia, choix[selected])
return
elif "Acteurs" == choix[selected]:
affCast(numId, typMedia)
elif "Lire" == choix[selected]:
cr = cryptage.Crypt()
dictResos = cr.extractReso([(x.split("#")[0].split("@")[0], x.split("#")[0].split("@")[1]) for x in paramstring])
dictResos = {x.split("#")[0].split("@")[1]: dictResos[x.split("#")[0].split("@")[1]] if dictResos[x.split("#")[0].split("@")[1]] else x.split("#")[1] for x in paramstring}
tabNomLien = ["Lien N° %d (%s - %.2fGo)" %(i + 1, dictResos[x.split("#")[0].split("@")[1]][0], (int(dictResos[x.split("#")[0].split("@")[1]][1]) / 1000000000.0)) for i, x in enumerate(paramstring)]
tabRelease = [dictResos[x.split("#")[0].split("@")[1]][2] for i, x in enumerate(paramstring)]
tabLiens = [(x, paramstring[i], tabRelease[i]) for i, x in enumerate(tabNomLien)]
affLiens(numId, typMedia, tabLiens)
'''
def getBa(params):
numId = params["u2p"]
typMedia = params["typM"]
mdb = TMDB(__keyTMDB__)
tabBa = mdb.getNumIdBA(numId, typMedia)
if tabBa:
dialog = xbmcgui.Dialog()
selectedBa = dialog.select("Choix B.A", ["%s (%s)" %(x[0], x[1]) for x in tabBa], 0, 0)
if selectedBa != -1:
keyBa = tabBa[selectedBa][2]
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.youtube/?action=play_video&videoid={})".format(keyBa), True)
def gestionMedia(params):
typMedia = params["typM"]
numId = params["u2p"]
if typMedia == "movie":
media = "movies"
else:
media = "tvshow"
dictA = {}
# on continue
listeView = widget.extractOC()
if int(numId) in listeView:
#categories.append(("Retirer fav's-HK", {"action": "fav", "mode": "sup", "u2p": numId, "typM": "movies"}))
dictA['Retirer de "On continue..."'] = (gestionoc, {"mode": "sup", "u2p": numId, "typM": media})
else:
dictA['Ajouter à "On continue..."'] = (gestionoc, {"mode": "ajout", "u2p": numId, "typM": media})
#categories.append(("Ajouter fav's-HK", {"action": "fav", "mode": "ajout", "u2p": numId, "typM": "movies"}))
#liste last view
if __addon__.getSetting("bookonline") != "false":
listeView = widget.responseSite("http://%s/requete.php?name=%s&type=view&media=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), typMedia))
listeView = [int(x) for x in listeView]
else:
listeView = list(widget.extractIdInVu(t=media))
if int(numId) in listeView:
dictA["Retirer de l'historique"] = (supView, {"u2p": numId, "typM": media})
#categories.append(("Retirer Last/View", {"action": "supView", "u2p": numId, "typM": "movies"}))
#liste favs
if __addon__.getSetting("bookonline") != "false":
listeM = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), media))
listeM = [int(x) for x in listeM]
else:
listeM = list(widget.extractFavs(t=media))
if int(numId) in listeM:
#categories.append(("Retirer fav's-HK", {"action": "fav", "mode": "sup", "u2p": numId, "typM": "movies"}))
dictA["Retirer des Favoris HK"] = (gestionFavHK, {"mode": "sup", "u2p": numId, "typM": media})
else:
dictA["Ajouter aux Favoris HK"] = (gestionFavHK, {"mode": "ajout", "u2p": numId, "typM": media})
#categories.append(("Ajouter fav's-HK", {"action": "fav", "mode": "ajout", "u2p": numId, "typM": "movies"}))
trk = actifTrakt()
if trk and typMedia == "movie":
dictA["Cocher Vu dans Trakt"] = (vuMovieTrakt, {"u2p": numId})
# listes vierge
liste = widget.getListesV(typMedia)
for l in liste:
listeV = widget.getListesVdetail(l, typMedia)
if int(numId) in listeV:
dictA["Retirer de %s" %l] = (gestionListeV, {"mode": "sup", "u2p": numId, "typM": typMedia, "nom": l})
else:
dictA["Ajouter à %s" %l] = (gestionListeV, {"mode": "ajout", "u2p": numId, "typM": typMedia, "nom": l})
dictA["Correction Certification"] = (correctCertif, {"u2p": numId, "typM": typMedia})
dictA['Vider Historique'] = (delView, {"typM": media})
dictA['Vider Favoris HK'] = (supFavHK, {"typM": media})
tab = list(dictA.keys())
dialog = xbmcgui.Dialog()
ret = dialog.contextmenu(tab)
if ret != -1:
argv = dictA[tab[ret]][1]
dictA[tab[ret]][0](argv)
def gestionListeV(params):
typMedia = params["typM"]
numId = params["u2p"]
mode = params["mode"]
nom = params["nom"]
widget.gestionListeVdetail(nom, numId, typMedia, mode)
def fenInfo(params):
u2p = params["u2p"]
title = ""
try:
typM = params["typm"]
except :
typM = "film"
#xbmc.executebuiltin('Dialog.Close(busydialog)')
#window = feninfo.FenInfo(title)
#window = FenInfo("%s*%s" %(u2p, title))
window = feninfo.FenInfo([u2p, title, typM])
# Show the created window.
window.doModal()
del window
#def detailsMedia(params):
# detailsMedia2(params)
# time.sleep(0.5)
# xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"back"},"id":1}')
# xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"back"},"id":1}')
# xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"back"},"id":1}')
#xbmc.executebuiltin('ReloadSkin')
# xbmc.executebuiltin("Input.Back")
# xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Input.Back", "id": 1}')
def detailsMedia(params):
notice("detailM")
notice(params)
if __addon__.getSetting("newfen") != "false":
typM = "movie"
title = ""
numId = params["u2p"]
#xbmc.executebuiltin('Dialog.Close(busydialog)')
#window = feninfo.FenInfo(title)
#window = FenInfo("%s*%s" %(u2p, title))
window = feninfo.FenInfo([numId, title, typM])
# Show the created window.
window.doModal()
del window
#xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
#xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"back"},"id":1}')
else:
try:
links = params["lien"]
except:
try:
if __addon__.getSetting("actifnewpaste") != "false":
sql = "SELECT GROUP_CONCAT(l.link, '*') FROM filmsPubLink as l WHERE l.numId={}".format(params["u2p"])
links = createbdhk.extractMedias(sql=sql, unique=1)[0]
else:
sql = "SELECT link FROM movieLink WHERE numId={}".format(params["u2p"])
links = extractMedias(sql=sql, unique=1)[0]
except:
return False
#typMedia = params["typM"]
typMedia = "movie"
numId = params["u2p"]
u2p = params["u2p"]
try:
sql = "SELECT title, overview, year, genre, backdrop, popu, numId, poster, runtime FROM movie WHERE numId={}".format(numId)
liste = extractMedias(sql=sql)
except:
liste = []
if liste:
title, overview, year, genre, backdrop, popu, numId, poster, runtime = liste[0]
else:
sql = "SELECT title, overview, year, genres, backdrop, popu, numId, poster, runtime FROM filmsPub WHERE numId={}".format(numId)
liste = createbdhk.extractMedias(sql=sql)
try:
title, overview, year, genre, backdrop, popu, numId, poster, runtime = liste[0]
except:
return
try: int(runtime)
except: runtime = 0
overview = "%s\nsynopsis: %s \nAnnée: %s\nGenre: %s\nNote: %.2f\nDurée: %.d mns" %(title, overview[:150] + "...", year, genre, popu, runtime)
#fnotice(overview)
xbmcplugin.setPluginCategory(__handle__, "Menu")
#xbmcplugin.setContent(__handle__, 'episodes')
xbmcplugin.setContent(__handle__, 'videos')
categories = [("[COLOR red]Bande Annonce[/COLOR]", {"action": "ba", "u2p": numId, "typM": typMedia}), ("[COLOR green]Lire[/COLOR]", {"action": "afficheLiens", "lien": links, "u2p": numId})]
"""
if __addon__.getSetting("actifnewpaste") != "false":
sql = "SELECT t.saga FROM filmsPub AS t WHERE t.numId={}".format(u2p)
saga = createbdhk.extractMedias(sql=sql, unique=1)
if saga and saga[0]:
categories += [("Saga", {"action": "mediasHKFilms", "famille": "sagaListe", "numIdSaga":saga[0]})]
elif __addon__.getSetting("actifhk") != "false":
sql = "SELECT s.title, s.poster, s.overview, s.numId FROM saga AS s WHERE s.numId=(SELECT t.numIdSaga FROM sagaTitle AS t WHERE t.numId={})".format(u2p)
saga = extractMedias(sql=sql)
if saga:
categories += [("Saga", {"action": "MenuFilm", "famille": "sagaListe", "numIdSaga": saga[0][3]})]
categories += [("Acteurs", {"action": "affActeurs", "u2p": numId, "typM": typMedia}),\
("Similaires", {"action": "suggest", "u2p": numId, "typ": "Similaires", "typM": typMedia}), ("Recommandations", {"action": "suggest", "u2p": numId, "typ": "Recommendations", "typM": typMedia})]
"""
#liste lastview
if __addon__.getSetting("bookonline") != "false":
listeView = widget.responseSite("http://%s/requete.php?name=%s&type=view&media=movie" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
listeView = [int(x) for x in listeView]
else:
listeView = list(widget.extractIdInVu(t="movies"))
if int(numId) in listeView:
categories.append(("Retirer Last/View", {"action": "supView", "u2p": numId, "typM": "movies"}))
#liste favs
if __addon__.getSetting("bookonline") != "false":
listeM = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=movies" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
listeM = [int(x) for x in listeM]
else:
listeM = list(widget.extractFavs(t="movies"))
if int(numId) in listeM:
categories.append(("Retirer fav's-HK", {"action": "fav", "mode": "sup", "u2p": numId, "typM": "movies"}))
else:
categories.append(("Ajouter fav's-HK", {"action": "fav", "mode": "ajout", "u2p": numId, "typM": "movies"}))
categories += [("Acteurs", {"action": "affActeurs", "u2p": numId, "typM": typMedia}),\
("Similaires", {"action": "suggest", "u2p": numId, "typ": "Similaires", "typM": typMedia}), ("Recommandations", {"action": "suggest", "u2p": numId, "typ": "Recommendations", "typM": typMedia})]
#fenetre information
categories.append(("Fenêtre Information", {"action": "feninfo", "u2p": numId, "typM": "movies", "title": title}))
for cat in categories:
if "Saga" in cat[0] and cat[1]["action"] == "MenuFilm":
lFinale = [saga[0][0], saga[0][2], year, genre, backdrop, popu, numId, saga[0][1]]
else:
lFinale = [title, overview, year, genre, backdrop, popu, numId, poster]
media = Media("menu", *lFinale)
media.typeMedia = typMedia
addDirectoryMenu(cat[0], isFolder=True, parameters=cat[1], media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
return
def addDirectoryMenu(name, isFolder=True, parameters={}, media="" ):
''' Add a list item to the XBMC UI.'''
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
li = xbmcgui.ListItem(label=name)
updateInfoTagVideo(li,media,False,False,False,False,False)
if "Saison" in name:
commands = []
commands.append(('[COLOR yellow]Gestion Vus/Non-Vus[/COLOR]', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=vuNonVu&saison=%d&u2p=%s&refresh=1)' %(media.saison, media.numId)))
li.addContextMenuItems(commands)
isWidget = xbmc.getInfoLabel('Container.PluginName')
if "U2P" not in isWidget:
li.setProperty('widgetEpisodes', 'true')
li.setProperty('vus', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=vuNonVu&saison=%d&u2p=%s&refresh=1)' %(media.saison, media.numId))
li.setArt({'icon': media.backdrop,
"thumb": media.poster,
'poster':media.poster,
'fanart': media.backdrop
})
url = sys.argv[0] + '?' + urlencode(parameters)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
def getEpisodesSaison(numId):
try:
if __addon__.getSetting("bookonline") != "false":
vus = widget.responseSite("http://%s/requete.php?name=%s&type=getvu" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
else:
vus = widget.getVu("tvshow")
except:
vus = []
vus = [("Saison %s" %x.split("-")[1].zfill(2), x.split("-")[2])for x in vus if x.split("-")[0] == str(numId)]
sql = "SELECT saison, episode FROM tvshowEpisodes WHERE numId={}".format(numId)
liste = extractMedias(sql=sql)
notice(liste)
dictSaisons = {}
for saison in list(set([x[0] for x in liste])):
nbTotal = len([x for x in liste if x[0] == saison])
nbVus = len([x for x in vus if x[0] == saison])
if nbVus == 0:
c = "red"
elif nbVus == nbTotal:
c = "green"
else:
c = "orange"
dictSaisons[saison] = (c, nbVus, nbTotal)
return dictSaisons
def detailsTV(params):
#notice(params)
#typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
#if not typMedia:
# xbmc.executebuiltin("Dialog.Close(busydialog)")
# xbmc.sleep(500)
# typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
#typMedia = params["typM"]
typMedia = "tvshow"
numId = params["u2p"]
u2p = params["u2p"]
if u2p and numId != "divers":
if "saison" in params.keys():
numSaison = params["saison"].zfill(2)
saisons = ["Saison %s" %numSaison]
else:
sql = "SELECT DISTINCT saison FROM tvshowEpisodes WHERE numId={}".format(numId)
saisons = extractMedias(sql=sql, unique=1)
dictSaisonsVU = getEpisodesSaison(u2p)
sql = "SELECT title, overview, year, genre, backdrop, popu, numId, poster, runtime FROM tvshow WHERE numId={}".format(numId)
liste = extractMedias(sql=sql)
if liste:
title, overview, year, genre, backdrop, popu, numId, poster, runtime = liste[0]
else:
return False
try: int(runtime)
except: runtime = 0
overview = "%s\nsynopsis: %s \nAnnée: %s\nGenre: %s\nNote: %.2f\nDurée: %d mns" %(title, overview[:150] + "...", year, genre, popu, runtime)
xbmcplugin.setPluginCategory(__handle__, "Menu")
xbmcplugin.setContent(__handle__, 'episodes')
choixsaisons = [("%s [COLOR %s](%d/%d)[/COLOR]" %(x, dictSaisonsVU[x][0], dictSaisonsVU[x][1], dictSaisonsVU[x][2]), {"action": "visuEpisodes", "u2p": numId, "saison": x}) for x in saisons]
categories = [("[COLOR red]Bande Annonce[/COLOR]", {"action": "ba", "u2p": numId, "typM": typMedia})] + choixsaisons + \
[("Acteurs", {"action": "affActeurs", "u2p": numId, "typM": typMedia}),\
("Similaires", {"action": "suggest", "u2p": numId, "typ": "Similaires","typM": typMedia}), \
("Recommandations", {"action": "suggest", "u2p": numId, "typ": "Recommendations", "typM": typMedia})]
#liste lastview
if __addon__.getSetting("bookonline") != "false":
listeView = widget.responseSite("http://%s/requete.php?name=%s&type=view&media=tv" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
listeView = [int(x) for x in listeView]
else:
listeView = list(widget.extractIdInVu(t="tvshow"))
if int(numId) in listeView:
categories.append(("Retirer Last/View", {"action": "supView", "u2p": numId, "typM": typMedia}))
#liste favs
if __addon__.getSetting("bookonline") != "false":
listeM = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=tvshow" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
listeM = [int(x) for x in listeM]
else:
listeM = list(widget.extractFavs(t="tvshow"))
if int(numId) in listeM:
categories.append(("Retirer fav's-HK", {"action": "fav", "mode": "sup", "u2p": numId, "typM": "tvshow"}))
else:
categories.append(("Ajouter fav's-HK", {"action": "fav", "mode": "ajout", "u2p": numId, "typM": "tvshow"}))
mdb = TMDB(__keyTMDB__)
dictSaisons = dict(mdb.serieNumIdSaison(u2p).items())
notice(dictSaisons)
for cat in categories:
lFinale = [title, overview, year, genre, backdrop, popu, numId, poster]
if "saison" in cat[1].keys():
numSaison = int(cat[1]["saison"].split(" ")[1])
try:
tab = dictSaisons[numSaison]
lFinale = [title, tab[2], year, genre, backdrop, popu, numId, tab[1]]
#lFinale = [tab[0], tab[2], year, genre, backdrop, popu, numId, tab[1]]
except Exception as e:
notice(str(e))
media = Media("menu", *lFinale)
if "saison" in cat[1].keys():
media.saison = numSaison
media.typeMedia = typMedia
addDirectoryMenu(cat[0], isFolder=True, parameters=cat[1], media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def suiteSerie():
try:
if __addon__.getSetting("bookonline") != "false":
listeVus = widget.responseSite("http://%s/requete.php?name=%s&type=getvu" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
else:
listeVus = widget.getVu("tvshow")
except:
listeVus = []
dictSerie = {}
for vu in listeVus:
vu = vu.split("-")
episode = int(vu[1].zfill(2) + vu[2].zfill(4))
if vu[0] in dictSerie.keys() and episode > dictSerie[vu[0]]:
dictSerie[vu[0]] = episode
else:
dictSerie[vu[0]] = episode
listeSerie = []
for numId, episodeVu in dictSerie.items():
sql = "SELECT ep.saison, ep.episode, (SELECT GROUP_CONCAT(l.link, '*') FROM episodes as l WHERE l.numId=ep.numId AND l.saison=ep.saison AND l.episode=ep.episode) FROM episodes as ep WHERE ep.numId={}".format(numId)
episodes = createbdhk.extractMedias(sql=sql)
episodes = sorted([(str(x[0]) + str(x[1]).zfill(4), x[2]) for x in episodes])
for (episode, lien) in episodes:
if int(episode) > episodeVu:
serie = [numId, "", "", lien]
sql = "SELECT title, overview, year, backdrop, popu FROM seriesPub WHERE numId={}".format(numId)
serie += createbdhk.extractMedias(sql=sql)[0]
serie += [int(episode[:-4]), int(int(episode[-4:])), 0]
listeSerie.append(serie)
#notice(serie)
break
xbmcplugin.setPluginCategory(__handle__, "Episodes")
xbmcplugin.setContent(__handle__, 'episodes')
for l in listeSerie[::-1]:
media = Media("episode", *l)
media.typeMedia = "episode"
media.numId = int(l[0])
addDirectoryEpisodes("%s ([COLOR white]S%sE%s[/COLOR])" %(media.title, str(media.saison).zfill(2), str(media.episode).zfill(2)), isFolder=False, parameters={"action": "playHK", "lien": media.link, "u2p": media.numId, "episode": media.episode, "saison": media.saison }, media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def normalizeNum(num):
s, e = num.split("E")
e = "%s%s" %("0" * (4 - len(e)), e)
return s + "E" + e
def affEpisodes2(params):
numId = params["u2p"]
saison = params["saison"]
typM = "episode"
xbmcplugin.setPluginCategory(__handle__, "Episodes")
xbmcplugin.setContent(__handle__, 'episodes')
sql = "SELECT * FROM tvshowEpisodes WHERE numId={} AND saison='{}'".format(numId, saison)
liste = extractMedias(sql=sql)
mdb = TMDB(__keyTMDB__)
tabEpisodes = mdb.saison(numId, saison.replace("Saison ", ""))
try:
if __addon__.getSetting("bookonline") != "false":
vus = widget.responseSite("http://%s/requete.php?name=%s&type=getvu" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
else:
vus = widget.getVu("tvshow")
except:
vus = []
liste = [(x[0], x[1], normalizeNum(x[2]), x[3]) for x in liste]
for l in sorted(liste, key=lambda x: x[-2]):
ep = "%d-%d-%d" %(int(l[0]), int(l[2].split("E")[0].replace("S", "")), int(l[2].split("E")[1]))
if ep in vus:
isVu = 1
else:
isVu = 0
try:
lFinale = list(l) + list([episode for episode in tabEpisodes if int(l[2].split("E")[1]) == episode[-1]][0])
except:
lFinale = list(l) + ["Episode", "Pas de synopsis ....", "", "", "", int(saison.replace("Saison ", "")) , int(l[2].split("E")[1])]
lFinale.append(isVu)
media = Media("episode", *lFinale)
media.typeMedia = typM
#notice(media.vu)
media.numId = int(numId)
addDirectoryEpisodes("E%d - %s" %(int(l[2].split("E")[1]), media.title ), isFolder=False, parameters={"action": "playHK", "lien": media.link, "u2p": media.numId, "episode": media.episode}, media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
'''
def affEpisodes(numId, saison):
typM = "episode"
xbmcplugin.setPluginCategory(__handle__, "Episodes")
xbmcplugin.setContent(__handle__, 'episodes')
sql = "SELECT * FROM tvshowEpisodes WHERE numId={} AND saison='{}'".format(numId, saison)
liste = extractMedias(sql=sql)
mdb = TMDB(__keyTMDB__)
tabEpisodes = mdb.saison(numId, saison.replace("Saison ", ""))
for l in liste:
try:
lFinale = list(l) + list([episode for episode in tabEpisodes if int(l[2].split("E")[1]) == episode[-1]][0])
except:
lFinale = list(l) + ["Episode", "Pas de synopsis ....", "", "", "", int(saison.replace("Saison ", "")) , int(l[2].split("E")[1])]
#notice(lFinale)
media = Media("episode", *lFinale)
media.typeMedia = typM
media.numId = int(numId)
addDirectoryEpisodes("%s" %(media.title), isFolder=False, parameters={"action": "playHK", "lien": media.link, "u2p": media.numId}, media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
'''
def addDirectoryEpisodes(name, isFolder=True, parameters={}, media="" ):
''' Add a list item to the XBMC UI.'''
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
li = xbmcgui.ListItem(label=("%s" %(name)))
#, "dbid": media.numId + 500000
#notice(media.episode)
updateInfoTagVideo(li,media,False,True,False,False,True)
li.setArt({'icon': media.backdrop,
"fanart": media.backdrop,
'thumb': media.backdrop})
li.setProperty('IsPlayable', 'true')
commands = []
commands.append(('[COLOR yellow]Gestion Vus/Non-Vus[/COLOR]', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=vuNonVu&saison=%d&u2p=%s&refresh=1)' %(media.saison, media.numId)))
li.addContextMenuItems(commands, replaceItems=False)
isWidget = xbmc.getInfoLabel('Container.PluginName')
if "U2P" not in isWidget:
li.setProperty('widgetEpisodes', 'true')
li.setProperty('vus', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=vuNonVu&saison=%d&u2p=%s&refresh=1)' %(media.saison, media.numId))
url = sys.argv[0] + '?' + urlencode(parameters)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
def getVerifLinks(numId, typM="movie"):
cr = Crypt()
sql = "SELECT link, release, taille FROM filmsPubLink WHERE numId={}".format(numId)
paramstring = []
liste = createbdhk.extractMedias(sql=sql)
for l in liste:
l = list(l)
if "Go" in l[2]:
l[2] = int(float(l[2].replace("Go", "")) * 1000000000)
else:
l[2] = int(float(l[2]))
paramstring.append(l)
linksDarkino = [x for x in paramstring if len(x[0]) == 12]
links = [x for x in paramstring if x not in linksDarkino]
dictLiensfichier = cr.extractLinks([x[0] for x in links])
links = [x for x in links if dictLiensfichier[x[0]]]
if linksDarkino:
linkOk, linkOut = cr.validLinkDark([x[0] for x in linksDarkino])
linksDarkino = [x for x in linksDarkino if x[0] not in linkOut]
links += linksDarkino
return links
def affLiens2(params):
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
if not typMedia:
xbmc.executebuiltin("Dialog.Close(busydialog)")
xbmc.sleep(500)
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
#paramstring = params["lien"].split("*")
numId = params["u2p"]
u2p = params["u2p"]
links = getVerifLinks(numId)
notice(links)
#[('6Ai4sfJOSD', '720.HDlight-Light.French', '1883287480')]
"""
tabLinkIn = [(x.split("#")[0].split("@")[0], x.split("#")[0].split("@")[1]) for x in paramstring]
#dictResos = cr.extractReso(tabLinkIn[:100])
dictResos = {}
for i in range(0, len(tabLinkIn), 100):
dictResos.update(cr.extractReso(tabLinkIn[i: i + 100]))
"""
#dictResos = {x.split("#")[0].split("@")[1]: dictResos[x.split("#")[0].split("@")[1]] if dictResos[x.split("#")[0].split("@")[1]] else x.split("#")[1] for x in paramstring}
#paramstring = orderLiens(dictResos, paramstring)
#tabNomLien = ["[COLOR %s]#%d[/COLOR]| %s - %.2fGo" %(colorLiens(dictResos[x.split("#")[0].split("@")[1]][0]), i + 1, dictResos[x.split("#")[0].split("@")[1]][0], (int(dictResos[x.split("#")[0].split("@")[1]][1]) / 1000000000.0)) for i, x in enumerate(paramstring)]
tabNomLien = ["[COLOR %s]#%d[/COLOR]| %s - %.2fGo" %(colorLiens(x[1]), i + 1, x[1], (int(x[2]) / 1000000000.0)) for i, x in enumerate(links)]
tabRelease = [x[1] for i, x in enumerate(links)]
tabLiens = [(x, links[i][0], tabRelease[i]) for i, x in enumerate(tabNomLien)]
notice(tabLiens)
affLiens(numId, "movie", tabLiens)
def affLiens(numId, typM, liste):
xbmcplugin.setPluginCategory(__handle__, "Liens")
xbmcplugin.setContent(__handle__, 'files')
try:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId={}".format(numId)
movie = extractMedias(sql=sql)
except:
movie = []
if not movie:
sql = "SELECT title, overview, year, poster, numId, genres, popu, backdrop, runtime, id FROM filmsPub WHERE numId={}".format(numId)
movie = createbdhk.extractMedias(sql=sql)
for l in liste:
l = list(l)
l += movie[0]
media = Media("lien", *l)
media.typeMedia = typM
if typM == "movie":
addDirectoryFilms("%s" %(l[0]), isFolder=False, parameters={"action": "playHK", "lien": media.link, "u2p": media.numId}, media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True, cacheToDisc=True)
def orderLiens(dictResos, paramstring):
tabLinks = []
tabLinks2 = []
taille = 5000000001
filtre = 0
if __addon__.getSetting("filtliens") != "false":
filtre = 1
for k, v in dictResos.items():
tabFiltre = []
link = [x for x in paramstring if k in x]
if filtre:
notice(v)
if re.search(r"1080", v[0], re.I) and (re.search(r"\.multi", v[0], re.I) or re.search(r"\.vf", v[0], re.I) or re.search(r"\.truefrench", v[0], re.I) or re.search(r"\.french", v[0], re.I)) and int(v[1]) < taille:
tabLinks.append(list(v) + [k] + link)
tabLinks2.append(list(v) + [k] + link)
else:
link = [x for x in paramstring if k in x]
tabLinks.append(list(v) + [k] + link)
if not tabLinks:
tabLinks = tabLinks2[:]
try:
return [x[-1] for x in sorted(tabLinks, key=lambda taille: taille[1], reverse=True)]
except:
return paramstring
def colorLiens(lien):
#for c in [("2160", "[COLOR fuchsia]2160[/COLOR]"), ("3D", "[COLOR yellow]3D[/COLOR]"),\
# ("1080", "[COLOR goldenrod]1080[/COLOR]"), ("720", "[COLOR seagreen]720[/COLOR]"), ("480", "[COLOR dodgerblue]480[/COLOR]")]:
# lien = lien.replace(c[0], c[1])
if "2160" in lien or re.search("4K", lien, re.I):
c = "red"
elif re.search("3D", lien, re.I):
c = "yellow"
elif "1080" in lien:
c = "fuchsia"
elif "720" in lien:
c = "seagreen"
elif "480" in lien:
c = "dodgerblue"
else:
c = "white"
return c
def getVerifLinksSerie(paramstring):
cr = Crypt()
sql = "SELECT link, release, taille FROM episodes WHERE link IN ('{}')".format("','".join(paramstring))
#notice(sql)
liste = createbdhk.extractMedias(sql=sql)
paramstring = []
for l in liste:
l = list(l)
if "Go" in l[2]:
l[2] = int(float(l[2].replace("Go", "")) * 1000000000)
elif "Mo" in l[2]:
l[2] = int(float(l[2].replace("Mo", "")) * 100000000)
else:
l[2] = int(float(l[2]))
paramstring.append(l)
linksDarkino = [x for x in paramstring if len(x[0]) == 12]
links = [x for x in paramstring if x not in linksDarkino]
dictLiensfichier = cr.extractLinks([x[0] for x in links])
links = [x for x in links if dictLiensfichier[x[0]]]
if linksDarkino:
linkOk, linkOut = cr.validLinkDark([x[0] for x in linksDarkino])
linksDarkino = [x for x in linksDarkino if x[0] not in linkOut]
links += linksDarkino
return links
def getParams(paramstring, u2p=0, saisonIn=1, suite=0):
result = {}
paramstring = paramstring.split("*")
# ===================================================================== resos ===========================================================
resos, timing = getresos()
histoReso = None
#cr = cryptage.Crypt()
#dictResos = cr.extractReso([(x.split("#")[0].split("@")[0], x.split("#")[0].split("@")[1]) for x in paramstring])
#dictResos = {x.split("#")[0].split("@")[1]: dictResos[x.split("#")[0].split("@")[1]] if dictResos[x.split("#")[0].split("@")[1]] else x.split("#")[1] for x in paramstring}
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
if not typMedia:
xbmc.executebuiltin("Dialog.Close(busydialog)")
xbmc.sleep(500)
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
#notice("type media " + typMedia)
#notice(xbmc.getInfoLabel('ListItem.DBID'))
#notice(xbmc.getInfoLabel('ListItem.DBTYPE'))
#numId = xbmc.getInfoLabel('ListItem.DBID')
if typMedia != "movie":
links = getVerifLinksSerie(paramstring)
#notice("links")
#notice(links)
paramstring = links
title = xbmc.getInfoLabel('ListItem.TVShowTitle')
saison = xbmc.getInfoLabel('ListItem.Season')
#notice("title " + xbmc.getInfoLabel('Player.Title'))
if xbmc.Player().isPlaying():
infoTag = xbmc.Player().getVideoInfoTag()
title = infoTag.getTVShowTitle()
saison = infoTag.getSeason()
#notice("serie" + title)
histoReso = None
if title:
idDB = xbmc.getInfoLabel('ListItem.DBID')
histoReso = gestionBD("get", title, saison)
#notice("histo %s" %histoReso)
else:
liste = gestionBD("last")
if liste:
idDB, title, saison, reso = liste
histoReso = (reso, )
pos = 0
if suite:
if histoReso and histoReso[0]:
resos = [histoReso[0]] + resos
timing = 2
if u2p:
timing = 0
numId = u2p
try:
for reso in resos:
#notice(reso)
for i, lien in enumerate(paramstring):
if reso in lien[1]:
pos = i
raise StopIteration
except StopIteration: pass
# ========================================================================================================================================
selected = 0
if len(paramstring) == 1:
if type(paramstring[0]) == str:
result['url'] = paramstring[0]
else:
result['url'] = paramstring[0][0]
else:
dialog = xbmcgui.Dialog()
#if u2p and numId != "divers":
# tabNomLien = ["Bande Annonce"]
#else:
# tabNomLien = []
"""
tabNomLien = []
paramstring = orderLiens(dictResos, paramstring)
#notice(paramstring)
try:
tabNomLien += ["#%d (%s - %.2fGo)" %(i + 1, dictResos[x.split("#")[0].split("@")[1]][0], (int(dictResos[x.split("#")[0].split("@")[1]][1]) / 1000000000.0)) for i, x in enumerate(paramstring)]
except:
tabNomLien += ["#%d (ind)" %(i + 1) for i, x in enumerate(paramstring)]
"""
tabNomLien = ["[COLOR %s]#%d[/COLOR]| %s - %.2fGo" %(colorLiens(x[1]), i + 1, x[1], (int(x[2]) / 1000000000.0)) for i, x in enumerate(paramstring)]
#if u2p and numId != "divers":
# tabNomLien += ["Casting", "Similaires", "Recommendations"]
selected = dialog.select("Choix lien", tabNomLien, int(timing) * 1000, pos)
if selected != -1:
if u2p and numId != "divers":
if "Bande Annonce" == tabNomLien[selected]:
mdb = TMDB(__keyTMDB__)
tabBa = mdb.getNumIdBA(numId, typMedia)
if tabBa:
selectedBa = dialog.select("Choix B.A", ["%s (%s)" %(x[0], x[1]) for x in tabBa], 0, 0)
if selectedBa != -1:
keyBa = tabBa[selectedBa][2]
xbmc.executebuiltin("RunPlugin(plugin://plugin.video.youtube/?action=play_video&videoid={})".format(keyBa), True)
return
elif tabNomLien[selected] in ["Similaires", "Recommendations"]:
loadSimReco(numId, typMedia, tabNomLien[selected])
return
else:
result['url'] = paramstring[selected][0]
reso = paramstring[selected][1]
else:
result['url'] = paramstring[selected][0]
reso = paramstring[selected][1]
else:
return
if typMedia != "movie":
if u2p:
gestionBD("update", u2p, title, saisonIn, reso, pos)
else:
if title:
gestionBD("update", idDB, title, saison, reso, pos)
# debridage
ApikeyAlldeb = getkeyAlldebrid()
ApikeyRealdeb = getkeyRealdebrid()
#ApikeyUpto = getkeyUpto()
Apikey1fichier = getkey1fichier()
validKey = False
cr = Crypt()
if len(result['url'].strip()) == 12:
urlLink = cr.urlBase + cr.cryptFile(result['url'].strip(), 0)
else:
urlLink = cr.url + "/?" + cr.cryptFile(result['url'], 0)
result['url'] = urlLink
if ApikeyAlldeb:
erreurs = ["AUTH_MISSING_AGENT", "AUTH_BAD_AGENT", "AUTH_MISSING_APIKEY", "AUTH_BAD_APIKEY"]
urlDedrid, status = cr.resolveLink(result['url'], ApikeyAlldeb)
if status in erreurs:
validKey = False
showInfoNotification("Key Alldebrid Out!")
#addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#addon.setSetting(id="keyalldebrid", value="")
else:
result['url'] = urlDedrid.strip()
validKey = True
if ApikeyRealdeb and not validKey:
urlDedrid, status = cr.resolveLink(result['url'], ApikeyRealdeb)
if status == "err":
showInfoNotification("Key Realdebrid Out!")
#addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#addon.setSetting(id="keyrealdebrid", value="")
else:
result['url'] = urlDedrid.strip()
validKey = True
if Apikey1fichier and not validKey:
urlDedrid, status = cr.resolveLink(result['url'], Apikey1fichier)
result['url'] = urlDedrid.strip()
#if status == 16:
# showInfoNotification("Key Uptobox Out!")
#addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#addon.setSetting(id="keyupto", value="")
if result['url'][:-4] in [".mkv", ".mp4"]:
title = unquote(result['url'][:-4].split("/")[-1])#, encoding='latin-1', errors='replace')
else:
title = unquote(result['url'].split("/")[-1])#, encoding='latin-1', errors='replace')
try:
title = unicode(title, "utf8", "replace")
except: pass
result["title"] = title
#notice(result)
return result
def delcompte(params):
link = params["lien"]
ApikeyUpto = getkeyUpto()
up = uptobox.Uptobox(ApikeyUpto)
up.deleteFile(link)
showInfoNotification("Delete Ok: %s" %link)
def addCompteUpto(params):
modeUp = __addon__.getSetting("modeadd")
link = params["lien"]
ApikeyUpto = getkeyUpto()
cr = cryptage.Crypt()
links = link.split("*")
if len(links) > 1:
choix = [x.split("#")[1] for x in links]
dialog = xbmcgui.Dialog()
d = dialog.select("Que veux tu ajouter?", choix)
if d != -1:
link = links[d]
else:
return
else:
link = links[0]
link = link.split("#")[0]
if modeUp == "alias":
filecode, status = cr.resolveLink(link.split("@")[0], link.split("@")[1], key=ApikeyUpto, addCompte=1)
else:
filecode, status = cr.resolveLink(link.split("@")[0], link.split("@")[1], key=ApikeyUpto, addCompte=2)
showInfoNotification("Upload Ok: %s" %filecode)
'''
def loadSimReco(numId, typM, recherche):
notice("typ demande " + recherche)
dictTyp = {"tvshow": "tv", "movie": "movie"}
mdb = TMDB(__keyTMDB__)
if recherche == "Similaires":
liste = mdb.suggReco(numId, dictTyp[typM], "similar")
elif recherche == "Recommendations":
liste = mdb.suggReco(numId, dictTyp[typM], "recommendations")
if typM == "movie":
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) FROM movie as m \
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu FROM tvshow as m \
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
movies = extractMedias(sql=sql)
affMovies(typM, movies)
'''
def loadSimReco2(params):
numId = params["u2p"]
recherche = params["typ"]
typM = xbmc.getInfoLabel('ListItem.DBTYPE')
if not typM:
xbmc.executebuiltin("Dialog.Close(busydialog)")
xbmc.sleep(500)
typM = xbmc.getInfoLabel('ListItem.DBTYPE')
if typM == "":
typM = params["typM"]
#notice("typ demande " + recherche + " typM" +typM)
dictTyp = {"tvshow": "tv", "movie": "movie", "episode": "tv"}
mdb = TMDB(__keyTMDB__)
if recherche == "Similaires":
liste = mdb.suggReco(numId, dictTyp[typM], "similar")
elif recherche == "Recommendations":
liste = mdb.suggReco(numId, dictTyp[typM], "recommendations")
if __addon__.getSetting("actifnewpaste") != "false":
if typM == "movie":
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genres, m.popu, (SELECT GROUP_CONCAT(l.link, '*') FROM filmsPubLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM filmsPub as m WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genres, m.popu, m.backdrop, m.runtime, m.id FROM seriesPub as m\
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
movies = createbdhk.extractMedias(sql=sql)
elif __addon__.getSetting("actifhk") != "false":
if typM == "movie":
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
movies = extractMedias(sql=sql)
affMovies(typM, movies[:-1])
def extractFanart(numId):
cnx = sqlite3.connect(__repAddon__ + "medias.bd")
cur = cnx.cursor()
sql = "SELECT logo, clearart, banner FROM movieFanart WHERE numId={}".format(numId)
cur.execute(sql)
liste = cur.fetchall()
cur.close()
cnx.close()
if liste:
logo, clearart, banner = liste[0]
else:
logo, clearart, banner = "", "", ""
return logo, clearart, banner
def extractMedias(limit=0, offset=1, sql="", unique=0):
cnx = sqlite3.connect(__repAddon__ + "medias.bd")
cur = cnx.cursor()
def normalizeTitle(tx):
#tx = re.sub(r''' {2,}''', ' ', re.sub(r''':|;|'|"|,''', ' ', tx))
tx = re.sub(r''':|;|'|"|,|\-''', ' ', tx)
tx = re.sub(r''' {2,}''', ' ', tx)
tx = str(tx).lower()
return unicodedata.normalize('NFD', tx).encode('ascii','ignore').decode("latin-1")
cnx.create_function("normalizeTitle", 1, normalizeTitle)
if sql:
cur.execute(sql)
if unique:
requete = [x[0] for x in cur.fetchall()]
else:
requete = cur.fetchall()
else:
if limit > 0:
cur.execute("SELECT title, overview, year, poster, link, numId FROM movie LIMIT %d OFFSET %d" %(limit, offset))
else:
cur.execute("SELECT title, overview, year, poster, link, numId FROM movie ORDER BY title COLLATE NOCASE ASC")
requete = cur.fetchall()
cur.close()
cnx.close()
return requete
def affAlldeb():
choix = [("Magnets", {"action":"magnets", "offset": 0}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Afficher les liens magnets"),
("History", {"action":"listeAll", "offset": 0, "typeL": "history"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Afficher les liens recents"),
("Sauvegarde", {"action":"listeAll", "offset": 0, "typeL": "links"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Afficher les liens sauvés"),]
xbmcplugin.setPluginCategory(__handle__, "Menu Alldebrid")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
isFolder = True
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affUpto():
choix = [("Recherche", {"action":"rechercheUpto", "offset": 0}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "Recherche dans le compte Uptobox\n --- ATTENTION ---\n c'est sur le nom du fichier!!!"),
("News", {"action":"newUpto", "offset": 0}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Afficher les derniéres nouveautés du compte Uptobox"),
("Racine", {"action": "loadUpto", "rep": "//", "offset": 0, "typM": "movie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Media a la racine du compte"),
("Mon Historique", {"action": "histoupto"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/Mon historique.png', "Suivi series, films Uptobox"),]
xbmcplugin.setPluginCategory(__handle__, "Menu Uptobox")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
liste = widget.extractRepUpto()
if liste:
for (nom, rep, typMedia) in liste:
if typMedia == "movie":
choix.append((nom, {"action": "loadUpto", "rep": rep, "offset": 0, "typM": typMedia}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', typMedia))
else:
choix.append((nom, {"action": "loadUptoSerie", "rep": rep, "offset": 0, "typM": typMedia}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', typMedia))
liste = widget.extractRepUptoPublic()
if liste:
for (nom, numHash, folder, typMedia) in liste:
choix.append((nom, {"action": "loadUptoP", "hash": numHash, "folder": folder, "offset": 0, "typM": typMedia}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', typMedia))
isFolder = True
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affTmdb():
liste = widget.extractListTMDB()
if liste:
xbmcplugin.setPluginCategory(__handle__, "Menu TMDB")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
choix = []
for (nom, typMedia) in liste:
if typMedia == "movie":
choix.append((nom, {"action":"MenuFilmHK", "famille": 'tmdb', "nom": nom}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', typMedia))
else:
choix.append((nom, {"action":"MenuSerieHK", "famille": 'tmdb', "nom": nom}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', typMedia))
isFolder = True
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affPastebin():
liste = widget.extractListPaste()
if liste:
xbmcplugin.setPluginCategory(__handle__, "Menu Liste Pastebin")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
choix = []
for (nom, typMedia) in liste:
if typMedia == "film":
choix.append((nom, {"action":"MenuFilm", "famille": 'paste', "nom": nom}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', typMedia))
else:
choix.append((nom, {"action":"MenuSerie", "famille": 'paste', "nom": nom, "t": typMedia}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', typMedia))
isFolder = True
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affTrakt():
xbmcplugin.setPluginCategory(__handle__, "Menu Trakt")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
choix = [("Listes", {"action":"MenuTrakt", "liste": "liste"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Listes personnelles"),
("Listes Liked", {"action":"MenuTrakt", "liste": "liked"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Listes que tu as aimées et likées"),
("Watchlist Film", {"action":"MenuTrakt", "cat": "wmovie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Tes envies de films a voir"),
("Watchlist Serie", {"action":"MenuTrakt", "cat": "wshow"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Tes envies de series a voir"),
("Recommendations Film", {"action":"MenuTrakt", "cat": "rmovie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Films pour toi"),
("Recommendations Serie", {"action":"MenuTrakt", "cat": "rshow"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Series pour toi"),
]
isFolder = True
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def ventilationHK():
xbmcplugin.setPluginCategory(__handle__, "Menu")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
choix = [
("Setting", {"action":"setting"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/setting.png', "Reglages U2P"),
("Setting Profils", {"action":"affProfils"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/profil.png', "Choix Profils"),
#("Il est frais mon poisson ....", {"action": "affNewsUpto", "offset": "0"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Dernieres news brut....."),
]
# bd hk
if __addon__.getSetting("actifhk") != "false":
choix += [("Films, Docu, concerts....", {"action":"MenuFilm"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/film1.png', "Bibliothéque de films, concerts, spectacles et documentaires"),
("Divers....", {"action":"MenuDivers"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Sports, Show TV, FANKAI, etc..."),
("Series & Animes", {"action":"MenuSerie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/series1.png', "Bibliothéque séries , animation & animes japonais"),
("Audio Book", {"action":"MenuAudio"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/book.png', "Bibliothéque livres audio"),
("Ma Recherche", {"action":"affSearch"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "type de recherche dispo"),]
# cretion bd avec les pastes pastebin
#if __addon__.getSetting("actiflocal") != "false":
# choix += [("Pastes Pastebin", {"action":"pastepastebin"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/pastebin.png', "DATABASE via num paste"),]
# creation avec repertoires crypté
if __addon__.getSetting("actifnewpaste") != "false":
choix += [("Médiathéque HK3", {"action":"menuRepCrypte"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/upto.png', "DATABASE new systéme"),]
# trakt
if __addon__.getSetting("traktperso") != "false":
userPass = [x[1] for x in widget.usersBookmark() if x[0] == __addon__.getSetting("profiltrakt")]
if ( __addon__.getSetting("bookonline") != "false" and userPass and __addon__.getSetting("bookonline_name") == userPass[0]) or __addon__.getSetting("bookonline") == "false":
choix.append(("Mon Trakt", {"action":"affTraktPerso"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/trakt.png', "ce qui est lié au compte Trakt perso"))
# mon contenu uptobox
if __addon__.getSetting("actifupto") != "false":
choix.append(("Mon Uptobox", {"action":"affUpto"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/upto.png', "accés à ton compte upto et publique"))
# liste tmdb
if __addon__.getSetting("actiftmdb") != "false":
choix.append(("Mon Movie-DB", {"action":"affTmdb"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/tmdb.png', "listes reconstituées avec TMDB"))
# liste pastebin d'apres un num de paste depuis hk
if __addon__.getSetting("actifpastebin") != "false":
choix.append(("Mon Pastebin", {"action":"affPastebin"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/pastebin.png', "listes reconstituées avec le(s) paste(s)"))
# mon alldeb
if __addon__.getSetting("actifalldeb") != "false":
choix.append(("Mon Alldebrid", {"action":"affAlldeb"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/alldebrid.png', "Accés liens du compte"))
#choix.append(("Mes Bandes Annonces", {"action":"affbaext"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Accés repo special Bande Annonce"))
isFolder = True
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
if "HK3" in name:
commands = []
commands.append(('[COLOR yellow]Details Mediathéque[/COLOR]', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=detailmediatheque)'))
li.addContextMenuItems(commands)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def traktHKventilation():
trk = TraktHK()
user = __addon__.getSetting("usertrakt")
if __addon__.getSetting("actifnewpaste") != "false":
sqlMovie = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genres, m.popu, (SELECT GROUP_CONCAT(l.link, '*') FROM filmsPubLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM filmsPub as m WHERE m.numId IN ({})"
sqlTvshow = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genres, m.popu, m.backdrop, m.runtime, m.id FROM seriesPub as m\
WHERE m.numId IN ({})"
fxExtract = createbdhk.extractMedias
elif __addon__.getSetting("actifhk") != "false":
sqlMovie = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId IN ({})"
sqlTvshow = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.numId IN ({})"
fxExtract = extractMedias
movies = None
if "cat" in __params__.keys():
cat = __params__["cat"]
#===========================================================================================================================================
if cat == "wmovie":
tabNumId = trk.getUserWatchlist(user, typM="movies")
tabNumId = [x for x in tabNumId if x]
movies = fxExtract(sql=sqlMovie.format(",".join([str(x) for x in tabNumId])))
typM = "movie"
#===========================================================================================================================================
elif cat == "wshow":
typM = "tvshow"
tabNumId = trk.getUserWatchlist(user, typM="shows")
tabNumId = [x for x in tabNumId if x]
movies = fxExtract(sql=sqlTvshow.format(",".join([str(x) for x in tabNumId])))
#===========================================================================================================================================
elif cat == "rmovie":
tabNumId = trk.recommendations(user, typM="movies")
tabNumId = [x for x in tabNumId if x]
movies = fxExtract(sql=sqlMovie.format(",".join([str(x) for x in tabNumId])))
typM = "movie"
#===========================================================================================================================================
elif cat == "rshow":
typM = "tvshow"
tabNumId = trk.recommendations(user, typM="shows")
tabNumId = [x for x in tabNumId if x]
movies = fxExtract(sql=sqlTvshow.format(",".join([str(x) for x in tabNumId])))
elif "numliste" in __params__.keys():
numliste = __params__["numliste"]
nb = int(__params__["nb"])
listeTR = trk.getListId([numliste, nb])
listeMovies = [liste["movie"]["ids"]["tmdb"] for liste in listeTR if liste["type"] == "movie"]
listeMovies = [x for x in listeMovies if x]
listeShows = [liste["show"]["ids"]["tmdb"] for liste in listeTR if liste["type"] == "show"]
listeShows = [x for x in listeShows if x]
if listeMovies and listeShows:
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Listes', 'Cette liste a 2 types de contenu, lequel afficher?', nolabel="Films", yeslabel="Series")
if not ret:
typM = "movie"
movies = fxExtract(sql=sqlMovie.format(",".join([str(x) for x in listeMovies])))
else:
typM = "tvshow"
movies = fxExtract(sql=sqlTvshow.format(",".join([str(x) for x in listeShows])))
elif listeMovies:
typM = "movie"
movies = fxExtract(sql=sqlMovie.format(",".join([str(x) for x in listeMovies])))
elif listeShows:
typM = "tvshow"
movies = fxExtract(sql=sqlTvshow.format(",".join([str(x) for x in listeShows])))
elif "liste" in __params__.keys():
if __params__["liste"] == "liste":
listes = trk.extractListsIdUser(user)
if __params__["liste"] == "liked":
listes = trk.getUserListsLikes(user)
choix = [(k, {"action":"MenuTrakt", "numliste":v[0], "nb": v[1]}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', k) for k, v in list(listes.values())[0].items()]
addCategorieMedia(choix)
if movies:
affMovies(typM, movies)
def diversHK():
if "groupe" in __params__.keys():
#title, overview, year, poster, link, numId
sql = "SELECT title, groupe||' ('||repo||')', '', '', 'divers', '', '', link, '', '' FROM divers WHERE repo='{}' AND groupe='{}' ORDER BY id DESC".format(__params__["repo"].replace("'", "''"), __params__["groupe"].replace("'", "''"))
movies = extractMedias(sql=sql)
#notice(movies)
affMovies("movie", movies)
elif "repo" in __params__.keys():
if __params__["repo"] == "adulte":
dialog = xbmcgui.Dialog()
d = dialog.input('Enter secret code', type=xbmcgui.INPUT_ALPHANUM, option=xbmcgui.ALPHANUM_HIDE_INPUT)
if d == "x2015x":
ok = True
else:
ok = False
else:
ok = True
if ok:
sql = "SELECT DISTINCT groupe FROM divers WHERE repo='{}' ORDER BY id DESC".format(__params__["repo"].replace("'", "''"))
listeRep = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuDivers", "repo":__params__["repo"], "groupe": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
else:
sql = "SELECT DISTINCT repo FROM divers"
listeRep = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuDivers", "repo":x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s.png' %x, x) for x in sorted(listeRep)]
addCategorieMedia(choix)
def mediasHK(params={}):
notice("params: " + str(params))
if params:
__params__["famille"] = params["famille"]
__params__["u2p"] = params["u2p"]
__params__["numIdSaga"] = params["u2p"]
typM = "movie"
try:
offset = int(__params__["offset"])
except:
offset = 0
try:
limit = int(__params__["limit"])
except:
limit = int(getNbMedias())
orderDefault = getOrderDefault()
year = datetime.today().year
lastYear = year - 1
if "famille" in __params__.keys():
movies = []
#====================================================================================================================================================================================
if __params__["famille"] in ["tmdb"]:
nom = __params__["nom"]
listeId = widget.recupTMDB(nom, "movie")
listeId = listeId[offset:]
tabMovies = []
for n in listeId:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
if len(tabMovies) == limit:
break
__params__["offset"] = offset
movies = tabMovies[:]
#====================================================================================================================================================================================
elif __params__["famille"] in ["paste"]:
nom = __params__["nom"]
listePaste = widget.recupPaste(nom, "film")
listeId = []
for paste in listePaste:
sql = "SELECT numId FROM paste WHERE numPaste='{}' ORDER BY id asc".format(paste)
listeId += [x[0] for x in extractMedias(sql=sql)]
listeId = listeId[offset:]
tabMovies = []
for n in listeId:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
if len(tabMovies) == limit:
break
__params__["offset"] = offset
movies = tabMovies[:]
#====================================================================================================================================================================================
elif __params__["famille"] in ["Last View", "Mon historique"]:
if __addon__.getSetting("bookonline") != "false":
liste = widget.responseSite("http://%s/requete.php?name=%s&type=view&media=movie" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
else:
liste = widget.bdHK(extract=1)
tabMovies = []
for n in liste:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
movies = tabMovies[:]
#sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
# WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
#movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] in ["Fav'S HK", "Mes favoris HK"]:
if __addon__.getSetting("bookonline") != "false":
notice("http://%s/requete.php?name=%s&type=favs&media=movies" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
liste = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=movies" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
else:
liste = widget.extractFavs("movies")
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
__params__["favs"] = __addon__.getSetting("bookonline_name")
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] in ["Last In", "Derniers Ajouts"]:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id FROM movie as m"\
+ " ORDER BY m.id DESC" + " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] in ["#Years/Last In", "Nouveautés par année"]:
#sql = "SELECT numId FROM movieFamille WHERE famille IN ('#Documentaires', '#Concerts', '#Spectacles')"
sql = "SELECT numId FROM movieFamille WHERE famille IN (SELECT o.nom FROM movieTypeFamille as o WHERE o.typFamille='out')"
tabNumId = extractMedias(sql=sql, unique=1)
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId NOT IN ({}) AND m.year!='' AND genre NOT LIKE '%%Documentaire%%' AND genre NOT LIKE '%%Animation%%' ORDER BY ".format(",".join([str(x) for x in tabNumId])) + " year DESC, id DESC"\
+ " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] in ["Nouveautés %d-%d" %(lastYear, year)]:
#sql = "SELECT numId FROM movieFamille WHERE famille IN ('#Documentaires', '#Concerts', '#Spectacles')"
sql = "SELECT numId FROM movieFamille WHERE famille IN (SELECT o.nom FROM movieTypeFamille as o WHERE o.typFamille='out')"
tabNumId = extractMedias(sql=sql, unique=1)
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId NOT IN ({}) AND m.year!='' AND m.year>={} AND genre NOT LIKE '%%Documentaire%%' AND genre NOT LIKE '%%Animation%%' ORDER BY ".format(",".join([str(x) for x in tabNumId]), lastYear) + " id DESC"\
+ " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] in ["#Notations", "Les mieux notés"]:
#sql = "SELECT numId FROM movieFamille WHERE famille IN ('#Documentaires', '#Concerts', '#Spectacles')"
sql = "SELECT numId FROM movieFamille WHERE famille IN (SELECT o.nom FROM movieTypeFamille as o WHERE o.typFamille='out')"
tabNumId = extractMedias(sql=sql, unique=1)
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId NOT IN ({}) AND m.year!='' AND genre NOT LIKE '%%Documentaire%%' AND genre NOT LIKE '%%Animation%%' AND m.popu>7 AND m.popu<9 AND m.votes>500 ORDER BY ".format(",".join([str(x) for x in tabNumId])) + " m.popu DESC"\
+ " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "cast":
mdb = TMDB(__keyTMDB__)
liste = mdb.person(__params__["u2p"])
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "Liste Aléatoire":
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id FROM movie as m ORDER BY RANDOM() LIMIT {}".format(getNbMedias())
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "Alpha(s)":
if "alpha" in __params__.keys():
alpha = __params__["alpha"]
else:
dialog = xbmcgui.Dialog()
alpha = dialog.input("ex: ram => tous les titres qui commencent par 'ram' \n(astuce le _ remplace tous caractéres)", type=xbmcgui.INPUT_ALPHANUM, defaultt="")
if len(alpha) > 0:
__params__["alpha"] = alpha
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.title LIKE {} ORDER BY title COLLATE NOCASE ASC".format("'" + str(alpha) + "%'") + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "Multi-Tri":
#sql = "SELECT numId FROM movieFamille WHERE famille IN ('#Documentaires', '#Concerts', '#Spectacles')"
sql = "SELECT numId FROM movieFamille WHERE famille IN (SELECT o.nom FROM movieTypeFamille as o WHERE o.typFamille='out')"
tabNumId = extractMedias(sql=sql, unique=1)
dictTri = {"Année puis Date entrée": "year DESC, id DESC", "Date entrée": "id DESC", "Année puis Ordre Alpha": "year DESC, title COLLATE NOCASE ASC", "Ordre Alpha A-Z": "title COLLATE NOCASE ASC",\
"Ordre Alpha Z-A": "title COLLATE NOCASE DESC"}
if "tri" in __params__.keys():
tri = int(__params__["tri"])
else:
dialog = xbmcgui.Dialog()
tri = dialog.select("Selectionner le tri", list(dictTri.keys()), 0, 0)
if tri != -1:
__params__["tri"] = str(tri)
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId NOT IN ({}) AND m.year!='' AND genre NOT LIKE '%%Documentaire%%' ORDER BY ".format(",".join([str(x) for x in tabNumId])) + dictTri[list(dictTri.keys())[tri]]\
+ " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] in ["Search", "Recherche"]:
dialog = xbmcgui.Dialog()
d = dialog.input("Recherche (mini 3 lettres)", type=xbmcgui.INPUT_ALPHANUM, defaultt="")
if len(d) > 2:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE normalizeTitle(m.title) LIKE normalizeTitle({}) ORDER BY title COLLATE NOCASE ASC".format("'%" + str(d).replace("'", "''") + "%'")
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] in ["Groupes Contrib", "Listes des contributeurs"]:
sql = "SELECT DISTINCT groupeParent FROM movieGroupe"
listeRep = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuFilm", "groupe": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Spécial Widget":
sql = "SELECT DISTINCT groupeParent FROM movieTrakt"
listeRep = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuFilm", "trakt": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Mes Widgets":
#notice(widget.extractListe())
listeRep = list(widget.extractListe())
choix = [(x, {"action":"MenuFilm", "widget": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Listes lecture":
listeRep = list(widget.getListesV("movie"))
choix = [(x, {"action":"MenuFilm", "listeV": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Listes Trakt":
listeRep = list(widget.getListesT("movie"))
listeRep = list(set([x[3] for x in listeRep]))
choix = [(x, {"action":"MenuFilm", "listeT": x, "typM": "movie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Sagas":
sql = "SELECT numId, title, overview, poster, poster FROM saga ORDER BY title"
movies = extractMedias(sql=sql)
typM = "saga"
#====================================================================================================================================================================================
elif __params__["famille"] == "sagaListe":
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId IN (SELECT f.numId FROM sagaTitle as f WHERE f.numIdSaga={})".format(__params__["numIdSaga"])
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "Année(s)":
if "an" in __params__.keys():
an = [int(x) for x in __params__["an"].split(":")]
else:
dialog = xbmcgui.Dialog()
d = dialog.input("Entrer Année => 2010 / Groupe d'années => 2010:2014", type=xbmcgui.INPUT_ALPHANUM)
if d:
an = d.split(":")
__params__["an"] = ":".join([str(x) for x in an])
if len(an) == 1:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.year={}".format(an[0]) + " ORDER BY m.year DESC, m.Title ASC" + " LIMIT {} OFFSET {}".format(limit, offset)
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.year>={} and m.year<={}".format(an[0], an[1]) + " ORDER BY m.year DESC, m.Title ASC" + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "Genre(s)":
mdb = TMDB(__keyTMDB__)
tabGenre = mdb.getGenre()
if "genre" in __params__.keys():
genres = [int(x) for x in __params__["genre"].split("*")]
else:
dialog = xbmcgui.Dialog()
genres = dialog.multiselect("Selectionner le/les genre(s)", tabGenre, preselect=[])
if genres:
__params__["genre"] = "*".join([str(x) for x in genres])
genresOk = " or ".join(["m.genre LIKE '%%%s%%'" %tabGenre[x] for x in genres])
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE " + genresOk + " ORDER BY m.id DESC" + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "genres":
rechGenre = __params__["typgenre"]
if '#' in rechGenre:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId IN (SELECT f.numId FROM movieFamille as f WHERE f.famille='{}')".format(rechGenre)\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.genre LIKE '%%{}%%' ORDER BY m.id DESC".format(rechGenre) + " LIMIT {} OFFSET {}".format( limit, offset)
movies = extractMedias(sql=sql)
#==================================================================================================================================================================================
elif __params__["famille"] == "Favoris":
pass
#====================================================================================================================================================================================
elif __params__["famille"] in ["Derniers Ajouts Films", "Les plus populaires TMDB/trakt", "#Film Last/In", "#Best TMDB-TRAKT"]:
dictCf ={"Derniers Ajouts Films": "#Films Last/In", "Les plus populaires TMDB/trakt": "#Best TMDB-TRAKT", "#Films Last/In": "#Films Last/In", "#Best TMDB-TRAKT": "#Best TMDB-TRAKT"}
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId IN (SELECT f.numId FROM movieFamille as f WHERE f.famille='{}')".format(dictCf[__params__["famille"]])\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
else:
#ORDER BY m.title COLLATE NOCASE ASC
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId IN (SELECT f.numId FROM movieFamille as f WHERE f.famille='{}')".format(__params__["famille"])\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
#sorted(movies, key=lambda x: x[-1], reverse=True)
affMovies(typM, movies, params=__params__)
if "groupe" in __params__.keys():
sql = "SELECT groupeFille FROM movieGroupe WHERE groupeParent='{}'".format(__params__["groupe"].replace("'", "''"))
listeRep = extractMedias(sql=sql, unique=1)
if len(listeRep) == 1 or not listeRep:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId IN (SELECT d.numId FROM movieGroupeDetail as d WHERE d.groupe='{}')".format(__params__["groupe"].replace("'", "''"))\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
affMovies(typM, movies, params=__params__)
else:
choix = [(x, {"action":"MenuFilm", "groupe": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
elif "listeT" in __params__.keys():
if "listeTfille" in __params__.keys():
liste = list(widget.getListesT("movie"))
liste = [(x[0], x[1], "movie") for x in liste if x[3] == __params__["listeT"] and x[4] == __params__["listeTfille"]][0]
trk = TraktHK()
tabNumId = trk.extractList(*liste)
tabNumId = [x for x in tabNumId if x]
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId IN ({})".format(",".join([str(x) for x in tabNumId]))
movies = extractMedias(sql=sql)
affMovies(typM, movies)
else:
listeRep = list(widget.getListesT("movie"))
listeRep = list(set([x[4] for x in listeRep if x[3] == __params__["listeT"]]))
choix = [(x, {"action":"MenuFilm", "listeT": __params__["listeT"], "listeTfille": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
elif "trakt" in __params__.keys():
sql = "SELECT groupeFille FROM movieTrakt WHERE groupeParent='{}'".format(__params__["trakt"].replace("'", "''"))
listeRep = extractMedias(sql=sql, unique=1)
if len(listeRep) == 1 or not listeRep:
if listeRep:
gr = listeRep[0].replace("'", "''")
else:
gr = __params__["trakt"].replace("'", "''")
tabMovies = []
sql = "SELECT d.numId FROM movieTraktDetail as d WHERE d.groupe='{}' ORDER BY d.id ASC".format(gr)
listeNumId = extractMedias(sql=sql, unique=1)
for n in listeNumId:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
__params__["offset"] = offset
affMovies(typM, tabMovies, params=__params__)
'''
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId), m.backdrop, m.runtime, m.id FROM movie as m \
WHERE m.numId IN (SELECT d.numId FROM movieTraktDetail as d WHERE d.groupe='{}' ORDER BY d.id ASC)".format(__params__["trakt"].replace("'", "''"))\
+ " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
affMovies(typM, movies, params=__params__)
'''
else:
choix = [(x, {"action":"MenuFilm", "trakt": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
elif "widget" in __params__.keys():
sql = widget.getListe(__params__["widget"])
movies = extractMedias(sql=sql)
affMovies(typM, movies)
elif "listeV" in __params__.keys():
tabNumId = widget.getListesVdetail(__params__["listeV"], "movie")
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId IN ({})".format(",".join([str(x) for x in tabNumId]))\
+ " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
affMovies(typM, movies)
elif "typfamille" in __params__.keys():
sql = "SELECT nom FROM movieTypeFamille WHERE typFamille='{}'".format(__params__["typfamille"])
listeRepData = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuFilm", "famille":x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s.png' %x, x) for x in listeRepData]
addCategorieMedia(choix)
else:
listeRep = ["Derniers Ajouts", "Derniers Ajouts Films", "Nouveautés par année", "Nouveautés %d-%d" %(lastYear, year), "Les mieux notés", "Les plus populaires TMDB/trakt", "Mon historique", "Mes favoris HK",\
"Listes des contributeurs", "Sagas", "Liste Aléatoire", "Spécial Widget", "Mes Widgets", "Listes lecture", "Listes Trakt"]
sql = "SELECT DISTINCT typFamille FROM movieTypeFamille"
listeRepData = [x for x in extractMedias(sql=sql, unique=1) if x not in ["filtre", "genre", "out"]]
choix = [(x, {"action":"MenuFilm", "famille":x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s.png' %x, x) for x in listeRep]
choix += [(x, {"action":"MenuFilm", "typfamille":x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s.png' %x, x) for x in listeRepData]
choix.append(("Filtres", {"action":"filtres", "typM": "movie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/Filtres.png', "Filtres"))
choix.append(("Genres", {"action":"genres", "typM": "movie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', "Genres"))
addCategorieMedia(choix)
def seriesHK():
typM = "tvshow"
try:
offset = int(__params__["offset"])
except:
offset = 0
try:
limit = int(__params__["limit"])
except:
limit = int(getNbMedias())
orderDefault = getOrderDefault()
xbmcgui.Window(10000).setProperty('nomFenetre', '')
if "famille" in __params__.keys():
movies = []
#====================================================================================================================================================================================
if __params__["famille"] in ["tmdb"]:
nom = __params__["nom"]
listeId = widget.recupTMDB(nom, "tv")
listeId = listeId[offset:]
tabMovies = []
for n in listeId:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
if len(tabMovies) == limit:
break
__params__["offset"] = offset
movies = tabMovies[:]
#====================================================================================================================================================================================
elif __params__["famille"] in ["paste"]:
nom = __params__["nom"]
t = __params__["t"]
listePaste = widget.recupPaste(nom, t)
listeId = []
for paste in listePaste:
sql = "SELECT numId FROM paste WHERE numPaste='{}' ORDER BY id asc".format(paste)
listeId += [x[0] for x in extractMedias(sql=sql)]
listeId = listeId[offset:]
tabMovies = []
for n in listeId:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
if len(tabMovies) == limit:
break
__params__["offset"] = offset
movies = tabMovies[:]
#===============================================================================================================================================================================
elif __params__["famille"] in ["Last View", "Mon historique"]:
if __addon__.getSetting("bookonline") != "false":
liste = widget.responseSite("http://%s/requete.php?name=%s&type=view&media=tv" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
else:
liste = widget.bdHK(extract=1, typM="tvshow")
tabMovies = []
for n in liste:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
movies = tabMovies[:]
#sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
# WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
#movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] in ["Fav'S HK", "Mes favoris HK"]:
if __addon__.getSetting("bookonline") != "false":
liste = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=tvshow" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name")))
else:
liste = widget.extractFavs("tvshow")
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
__params__["favs"] = __addon__.getSetting("bookonline_name")
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "Mes Widgets":
#notice(widget.extractListe("serie"))
listeRep = list(widget.extractListe("serie"))
choix = [(x, {"action":"MenuSerie", "widget": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Listes lecture":
listeRep = list(widget.getListesV("tvshow"))
choix = [(x, {"action":"MenuSerie", "listeV": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#===============================================================================================================================================================================
elif __params__["famille"] in ["Last In", "Derniers Ajouts"]:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m ORDER BY m.id DESC"\
+ " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] in ["#Years/Last In", "Nouveautés par année"]:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.genre NOT LIKE '%%Documentaire%%' AND m.genre NOT LIKE '%%Animation%%' AND m.genre NOT LIKE '%%Kids%%' ORDER BY " + " year DESC, id DESC"\
+ " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] == "Liste Aléatoire":
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m ORDER BY RANDOM() LIMIT 200 "
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "cast":
mdb = TMDB(__keyTMDB__)
liste = mdb.person(__params__["u2p"], typM="tvshow")
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m\
WHERE m.numId IN ({})".format(",".join([str(x) for x in liste]))
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] == "Alpha(s)":
if "alpha" in __params__.keys():
alpha = __params__["alpha"]
else:
dialog = xbmcgui.Dialog()
alpha = dialog.input("ex: ram => tous les titres qui commencent par 'ram' \n(astuce le _ remplace tous caractéres)", type=xbmcgui.INPUT_ALPHANUM, defaultt="")
if len(alpha) > 0:
__params__["alpha"] = alpha
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.title LIKE {} ORDER BY title COLLATE NOCASE ASC".format("'" + str(alpha) + "%'")\
+ " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] in ["Search", "Recherche"]:
dialog = xbmcgui.Dialog()
d = dialog.input("Recherche (mini 3 lettres)", type=xbmcgui.INPUT_ALPHANUM, defaultt="")
if len(d) > 2:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE normalizeTitle(m.title) LIKE normalizeTitle({}) ORDER BY title COLLATE NOCASE ASC".format("'%" + str(d).replace("'", "''") + "%'")
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] == "Multi-Tri":
dialog = xbmcgui.Dialog()
dictTri = {"Année puis Date entrée": "year DESC, id DESC", "Date entrée": "id DESC", "Année puis Ordre Alpha": "year DESC, title COLLATE NOCASE ASC", "Ordre Alpha A-Z": "title COLLATE NOCASE ASC",\
"Ordre Alpha Z-A": "title COLLATE NOCASE DESC"}
if "tri" in __params__.keys():
tri = int(__params__["tri"])
else:
dialog = xbmcgui.Dialog()
tri = dialog.select("Selectionner le tri", list(dictTri.keys()), 0, 0)
if tri != -1:
__params__["tri"] = str(tri)
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.genre NOT LIKE '%%Documentaire%%' ORDER BY " + dictTri[list(dictTri.keys())[tri]]\
+ " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] == "Année(s)":
if "an" in __params__.keys():
an = [int(x) for x in __params__["an"].split(":")]
else:
dialog = xbmcgui.Dialog()
d = dialog.input("Entrer Année => 2010 / Groupe d'années => 2010:2014", type=xbmcgui.INPUT_ALPHANUM)
if d:
an = d.split(":")
__params__["an"] = ":".join([str(x) for x in an])
if len(an) == 1:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.year={}".format(an[0]) + " LIMIT {} OFFSET {}".format(limit, offset)
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.year>={} and m.year<={}".format(an[0], an[1]) + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] == "Genre(s)":
mdb = TMDB(__keyTMDB__)
tabGenre = mdb.getGenre(typM="tv")
if "genre" in __params__.keys():
genres = [int(x) for x in __params__["genre"].split("*")]
else:
dialog = xbmcgui.Dialog()
genres = dialog.multiselect("Selectionner le/les genre(s)", tabGenre, preselect=[])
if genres:
__params__["genre"] = "*".join([str(x) for x in genres])
genresOk = " or ".join(["m.genre LIKE '%%%s%%'" %tabGenre[x] for x in genres])
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE " + genresOk + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
#====================================================================================================================================================================================
elif __params__["famille"] == "genres":
rechGenre = __params__["typgenre"]
if '#' in rechGenre:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.numId IN (SELECT f.numId FROM tvshowFamille as f WHERE f.famille='{}')".format(rechGenre)\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.genre LIKE '%%{}%%' ORDER BY m.id DESC".format(rechGenre) + " LIMIT {} OFFSET {}".format( limit, offset)
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] == "#Documentaires":
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.genre like '%%Documentaire%%'" \
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
#===============================================================================================================================================================================
elif __params__["famille"] in ["Groupes Contrib", "Listes des contributeurs"]:
sql = "SELECT DISTINCT groupeParent FROM tvshowGroupe"
listeRep = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuSerie", "groupe": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Listes Trakt":
listeRep = list(widget.getListesT("show"))
listeRep = list(set([x[3] for x in listeRep]))
choix = [(x, {"action":"MenuSerie", "listeT": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#====================================================================================================================================================================================
elif __params__["famille"] == "Spécial Widget":
sql = "SELECT DISTINCT groupeParent FROM tvshowTrakt"
listeRep = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuSerie", "trakt": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
elif __params__["famille"] in ["Derniers Ajouts Series", "Les plus populaires TMDB/trakt", "#Series", "#Best TMDB-TRAKT"]:
dictCf ={"Derniers Ajouts Series": "#Series", "Les plus populaires TMDB/trakt": "#Best TMDB-TRAKT", "#Series": "#Series", "#Best TMDB-TRAKT": "#Best TMDB-TRAKT"}
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.numId IN (SELECT f.numId FROM tvshowFamille as f WHERE f.famille='{}')".format(dictCf[__params__["famille"]])\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
else:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.numId IN (SELECT f.numId FROM tvshowFamille as f WHERE f.famille='{}')".format(__params__["famille"])\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
affMovies(typM, movies, params=__params__)
#===============================================================================================================================================================================
if "groupe" in __params__.keys():
sql = "SELECT groupeFille FROM tvshowGroupe WHERE groupeParent='{}'".format(__params__["groupe"].replace("'", "''"))
listeRep = extractMedias(sql=sql, unique=1)
if len(listeRep) == 1 or not listeRep:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
WHERE m.numId IN (SELECT d.numId FROM tvshowGroupeDetail as d WHERE d.groupe='{}')".format(__params__["groupe"].replace("'", "''"))\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
affMovies(typM, movies, params=__params__)
else:
choix = [(x, {"action":"MenuSerie", "groupe": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#===============================================================================================================================================================================
elif "listeT" in __params__.keys():
if "listeTfille" in __params__.keys():
liste = list(widget.getListesT("show"))
liste = [(x[0], x[1], "show") for x in liste if x[3] == __params__["listeT"] and x[4] == __params__["listeTfille"]][0]
trk = TraktHK()
tabNumId = trk.extractList(*liste)
tabNumId = [x for x in tabNumId if x]
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.numId IN ({})".format(",".join([str(x) for x in tabNumId]))
movies = extractMedias(sql=sql)
affMovies(typM, movies)
else:
listeRep = list(widget.getListesT("show"))
listeRep = list(set([x[4] for x in listeRep if x[3] == __params__["listeT"]]))
choix = [(x, {"action":"MenuSerie", "listeT": __params__["listeT"], "listeTfille": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#===============================================================================================================================================================================
elif "listeV" in __params__.keys():
tabNumId = widget.getListesVdetail(__params__["listeV"], "tvshow")
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.numId IN ({})".format(",".join([str(x) for x in tabNumId]))\
+ " LIMIT {} OFFSET {}".format(limit, offset)
__params__["offset"] = offset
movies = extractMedias(sql=sql)
affMovies(typM, movies)
#===============================================================================================================================================================================
elif "trakt" in __params__.keys():
sql = "SELECT groupeFille FROM tvshowTrakt WHERE groupeParent='{}'".format(__params__["trakt"].replace("'", "''"))
listeRep = extractMedias(sql=sql, unique=1)
if len(listeRep) == 1 or not listeRep:
if listeRep:
gr = listeRep[0].replace("'", "''")
else:
gr = __params__["trakt"].replace("'", "''")
tabMovies = []
sql = "SELECT d.numId FROM tvshowTraktDetail as d WHERE d.groupe='{}' ORDER BY d.id ASC".format(gr)
listeNumId = extractMedias(sql=sql, unique=1)
for n in listeNumId:
if n:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m \
WHERE m.numId={}".format(n)
movies = extractMedias(sql=sql)
if movies:
tabMovies.append(movies[0])
__params__["offset"] = offset
affMovies(typM, tabMovies, params=__params__)
'''
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.id FROM tvshow as m \
WHERE m.numId IN (SELECT d.numId FROM tvshowTraktDetail as d WHERE d.groupe='{}')".format(__params__["trakt"].replace("'", "''"))\
+ " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
affMovies(typM, movies, params=__params__)
'''
else:
choix = [(x, {"action":"MenuSerie", "trakt": x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s' %getImageWidget(x), x) for x in sorted(listeRep)]
addCategorieMedia(choix)
#===============================================================================================================================================================================
elif "widget" in __params__.keys():
sql = widget.getListe(__params__["widget"], "serie")
movies = extractMedias(sql=sql)
affMovies(typM, movies)
#===============================================================================================================================================================================
elif "typfamille" in __params__.keys():
sql = "SELECT nom FROM tvshowTypeFamille WHERE typFamille='{}'".format(__params__["typfamille"])
listeRepData = extractMedias(sql=sql, unique=1)
choix = [(x, {"action":"MenuSerie", "famille":x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s.png' %x, x) for x in listeRepData]
addCategorieMedia(choix)
#===============================================================================================================================================================================
elif "network" in __params__.keys():
if "namenetwork" in __params__.keys():
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE m.numId IN (SELECT f.numId FROM tvshowNetworkDetail as f WHERE f.network='{}')".format(__params__["namenetwork"])\
+ orderDefault + " LIMIT {} OFFSET {}".format(limit, offset)
movies = extractMedias(sql=sql)
__params__["offset"] = offset
#__params__["content"] = "images"
affMovies(typM, movies, params=__params__)
else:
sql = "SELECT network, poster FROM tvshowNetwork"
listeRepData = extractMedias(sql=sql)
choix = [(x[0], {"action":"MenuSerie", "network":"1", "namenetwork": x[0]}, "http://image.tmdb.org/t/p/w500%s" %x[1], x[0]) for x in listeRepData]
addCategorieMedia(choix)
#===============================================================================================================================================================================
else:
#sql = "SELECT DISTINCT famille FROM tvshowFamille"
#listeRep = extractMedias(sql=sql, unique=1)
sql = "SELECT DISTINCT typFamille FROM tvshowTypeFamille"
listeRepData = [x for x in extractMedias(sql=sql, unique=1) if x not in ["filtre", "genre", "out"]]
listeRep = []
for cat in ["Derniers Ajouts", "Derniers Ajouts Series", "Nouveautés par année", "Les plus populaires TMDB/trakt", "Mon historique", "Mes favoris HK", "Liste Aléatoire",\
"Listes lecture", "Listes Trakt", "Listes des contributeurs", "Spécial Widget", "Mes Widgets"]:
listeRep.append(cat)
choix = [("On continue....", {"action":"suiteSerie"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Liste des episodes des series en cours....")]
choix += [(x, {"action":"MenuSerie", "famille":x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s.png' %x, x) for x in listeRep]
choix += [(x, {"action":"MenuSerie", "typfamille":x}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s.png' %x, x) for x in listeRepData]
choix += [("Diffuseurs", {"action":"MenuSerie", "network":"1"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', "Diffuseur")]
choix.append(("Filtres", {"action":"filtres", "typM": "tvshow"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/Filtres.png', "Filtres"))
choix.append(("Genres", {"action":"genres", "typM": "tvshow"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', "Genres"))
addCategorieMedia(choix)
def getImageWidget(x):
if "Netflix" in x:
im = "netflix.jpg"
elif "Prime" in x:
im = "primevideo.jpg"
elif "CANAL" in x:
im = "canalplus.jpg"
elif "HBO" in x:
im = "hbomax.jpg"
elif "Disney" in x:
im = "disneyplus.jpg"
elif "Apple" in x:
im = "appletv.jpg"
elif "ARTE" in x:
im = "ARTE.jpg"
elif "SALTO" in x:
im = "salto.jpg"
else:
im = "groupe.png"
return im
def addCategorieMedia(choix):
dictChoix = {"Derniers Ajouts": "Liste des derniers, tous types, entrés dans pastebin (nouveauté ou pas, et update)", "Derniers Ajouts Films": "Liste ,uniquement ,films des derniers entrés dans pastebin (nouveauté ou pas, et update)",\
"Mon historique": "La liste de médias commencés ou la reprise est possible", "Liste Aléatoire": "Liste de médias sortis au hazard, quand tu ne sais pas quoi regarder",\
"Recherche": "ben recherche ..... (astuce le _ remplace n'importe quel caractére ex search => r_m donnera tous les titres qui contiennent ram, rom , rum etc... Interressant pour la recherche simultanées de 'e é è ê'",\
"Groupes Contrib": "Les groupes classés des conributeurs", "Les plus populaires TMDB/trakt": "Les mieux notés ou populaires chez movieDB et trakt",\
"Année(s)": "Recherche par années ex 2010 ou groupe d'années 2010:2013 => tous les medias 2010 2011 2012 2013", "Genre(s)": "vos genres préféres avec le multi choix ex choix sience-fiction et fantatisque => la liste gardera les 2 genres", \
"Alpha(s)": "liste suivant dont le titre commence pas la lettre choisie ou le debut du mot ex ram donnera tous les titres commencant par ram (astuce le _ remplace n'importe quel caractére",
"Filtres": "les filtres search, Alphanumérique, genres, Années etc.... Cela est fait sur ensemble des médias",
"Nouveautés par année": "Classement medias par ordre d'année ensuite par date entrée dans pastebin (Documentaires, concerts, spectacles, animations exclues)",
"Les mieux notés": "Classement notation descroissant > 7 et < 9", "Mes favoris HK": "liste de vos favoris"}
content = ""
try:
if "network" in choix[0][1].keys():
nomF = "Diffuseurs"
#content = "files"
else:
nomF = "Choix Gatégories"
except:
nomF = "Choix Gatégories"
xbmcplugin.setPluginCategory(__handle__, nomF)
if content:
xbmcplugin.setContent(__handle__, content)
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
isFolder = True
for ch in choix:
name, parameters, picture, texte = ch
if texte in dictChoix.keys():
texte = dictChoix[texte]
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
if "http" not in picture and not os.path.isfile(xbmcvfs.translatePath(picture)):
picture = 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png'
li.setArt({'thumb': picture,
#'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True, cacheToDisc=True)
def filtres(params):
typM = params["typM"]
dictChoix = {"Derniers Ajours": "Liste des derniers entrés dans pastebin (nouveautée ou pas)", "Last View": "La liste de médias commencés ou la reprise est possible", "Liste Aléatoire": "Liste de médias sortis au hazard, quand tu ne sais pas quoi regarder",\
"Search": "ben recherche ..... (astuce le _ remplace n'importe quel caractére ex search => r_m donnera tous les titres qui contiennent ram, rom , rum etc... Interressant pour la recherche simultanées de 'e é è ê'",\
"Groupes Contrib": "Les groupes classés des conributeurs",\
"Année(s)": "Recherche par années ex 2010 ou groupe d'années 2010:2013 => tous les medias 2010 2011 2012 2013", "Genre(s)": "vos genres préféres avec le multi choix ex choix sience-fiction et fantatisque => la liste gardera les 2 genres", \
"Alpha(s)": "liste suivant dont le titre commence pas la lettre choisie ou le debut du mot ex ram donnera tous les titres commencant par ram (astuce le _ remplace n'importe quel caractére"}
filtres = ["Année(s)" , "Recherche", "Genre(s)", "Alpha(s)", "Multi-Tri"]
xbmcplugin.setPluginCategory(__handle__, "Choix Filtres")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
isFolder = True
if typM == "movie":
sql = "SELECT nom FROM movieTypeFamille WHERE typFamille='filtre'"
liste = extractMedias(sql=sql)
liste = sorted([x[0] for x in liste])
filtres += liste
choix = [(x, {"action":"MenuFilm", "famille":x, "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in filtres]
else:
choix = [(x, {"action":"MenuSerie", "famille":x, "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in filtres]
for ch in sorted(choix):
name, parameters, picture, texte = ch
if texte in dictChoix.keys():
texte = dictChoix[texte]
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affSearch():
xbmcplugin.setPluginCategory(__handle__, "Recherches...")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
isFolder = True
if __addon__.getSetting("actifnewpaste") != "false":
choix = [("Recherche Films", {"action":"mediasHKFilms", "famille": "Search", "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
("Recherche Series", {"action":"mediasHKSeries", "famille": "Search", "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
("Recherche Globale", {"action": "affGlobalHK2"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
("Recherche Acteurs", {"action": "affSearchCast"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
]
else:
choix = [("Recherche Films", {"action":"MenuFilm", "famille": "Search", "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
("Recherche Series", {"action":"MenuSerie", "famille": "Search", "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
("Recherche Globale", {"action":"affGlobal"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
("Recherche Acteurs", {"action":"affSearchCast"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "ben recherche ....."),
("Recherche Uptobox", {"action":"rechercheUpto", "offset": 0}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/search.png', "Recherche compte uptobox"),
]
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affGlobal():
dictTyp = {"movie": "Film", "tvshow": "Serie"}
dialog = xbmcgui.Dialog()
d = dialog.input("Recherche (mini 3 lettres)", type=xbmcgui.INPUT_ALPHANUM, defaultt="")
if len(d) > 2:
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id \
FROM tvshow as m WHERE normalizeTitle(m.title) LIKE normalizeTitle({}) ORDER BY title COLLATE NOCASE ASC".format("'%" + str(d).replace("'", "''") + "%'")
tvshows = extractMedias(sql=sql)
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE normalizeTitle(m.title) LIKE normalizeTitle({}) ORDER BY title COLLATE NOCASE ASC".format("'%" + str(d).replace("'", "''") + "%'")
movies = extractMedias(sql=sql)
xbmcplugin.setContent(__handle__, 'movies')
for typM, medias in [("movie", movies), ("tvshow", tvshows)]:
try:
dictLogos, dictArt, dictLogosTMDB = logos(typM)
except:
dictLogos, dictArt, dictLogosTMDB = {}, {}, {}
i = 0
for i, media in enumerate(medias):
media = Media(typM, *media[:-1])
if typM == "movie":
urlFanart = "http://assets.fanart.tv/fanart/movie/"
else:
urlFanart = "http://assets.fanart.tv/fanart/tv/"
if int(media.numId) in dictLogos.keys():
media.clearlogo = urlFanart + dictLogos[int(media.numId)]
else:
if int(media.numId) in dictLogosTMDB.keys():
media.clearlogo = "http://image.tmdb.org/t/p/w300" + dictLogosTMDB[int(media.numId)]
else:
media.clearlogo = ""
if int(media.numId) in dictArt.keys():
media.clearart = urlFanart + dictArt[int(media.numId)]
else:
media.clearart = ""
media.title = "%s (%s)" %(media.title, dictTyp[typM])
if typM == "movie":
ok = addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": "detailM", "lien": media.link, "u2p": media.numId}, media=media)
else:
ok = addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": "detailT", "lien": media.link, "u2p": media.numId}, media=media)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_UNSORTED)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_VIDEO_YEAR)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_TITLE)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_VIDEO_RATING)
#xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_LABEL_IGNORE_FOLDERS, labelMask="Page Suivante")
if i == (int(getNbMedias()) -1):
addDirNext(params)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True, cacheToDisc=True)
def genres(params):
typM = params["typM"]
xbmcplugin.setPluginCategory(__handle__, "Choix Genres")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
isFolder = True
if typM == "movie":
mdb = TMDB(__keyTMDB__)
tabGenre = mdb.getGenre()
sql = "SELECT nom FROM movieTypeFamille WHERE typFamille='genre'"
liste = extractMedias(sql=sql)
tabGenre += sorted([x[0] for x in liste])
choix = [(x, {"action":"MenuFilm", "famille": "genres", "typgenre": x, "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in tabGenre]
else:
mdb = TMDB(__keyTMDB__)
tabGenre = mdb.getGenre(typM="tv")
sql = "SELECT nom FROM tvshowTypeFamille WHERE typFamille='genre'"
liste = extractMedias(sql=sql)
tabGenre += sorted([x[0] for x in liste])
choix = [(x, {"action":"MenuSerie", "famille": "genres", "typgenre": x, "offset": 0, "limit": int(getNbMedias())}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/groupe.png', x) for x in tabGenre]
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affSearchCast(params={}):
if "nom" in params.keys():
d = params["nom"].replace("recherche", "")
else:
dialog = xbmcgui.Dialog()
d = dialog.input("Recherche (mini 3 lettres)", type=xbmcgui.INPUT_ALPHANUM, defaultt="")
if len(d) > 2:
xbmcplugin.setPluginCategory(__handle__, "Acteurs")
xbmcplugin.setContent(__handle__, 'files')
mdb = TMDB(__keyTMDB__)
liste = mdb.searchPerson(d)
notice(liste)
for l in liste:
media = Media("cast", *l)
media.typeMedia = "movie"
if __addon__.getSetting("actifnewpaste") != "false":
addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action":"mediasHKFilms", "famille": "cast", "u2p": media.numId}, media=media)
else:
addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action":"MenuFilm", "famille": "cast", "u2p": media.numId}, media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def affCast2(params):
numId = params["u2p"]
typM = xbmc.getInfoLabel('ListItem.DBTYPE')
if not typM:
xbmc.executebuiltin("Dialog.Close(busydialog)")
xbmc.sleep(500)
typM = xbmc.getInfoLabel('ListItem.DBTYPE')
if typM == "":
typM = params["typM"]
xbmcplugin.setPluginCategory(__handle__, "Acteurs / Réalisateur")
xbmcplugin.setContent(__handle__, 'files')
mdb = TMDB(__keyTMDB__)
if typM == "movie":
liste = mdb.castFilm(numId)
if __addon__.getSetting("actifnewpaste") != "false":
menu = "mediasHKFilms"
elif __addon__.getSetting("actifhk") != "false":
menu = "MenuFilm"
else:
liste = mdb.castSerie(numId)
if __addon__.getSetting("actifnewpaste") != "false":
menu = "mediasHKSeries"
elif __addon__.getSetting("actifhk") != "false":
menu = "MenuSerie"
for l in liste:
media = Media("cast", *l)
media.typeMedia = typM
addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": menu, "famille": "cast", "u2p": media.numId}, media=media)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def addDirNext(params):
isFolder = True
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#notice("id addon " + str(addon.getAddonInfo("id")))
li = xbmcgui.ListItem(label="[COLOR red]Page Suivante[/COLOR]")
updateEmptyInfoTag(li)
li.setArt({
'thumb': 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/next.png',
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart'),
})
#commands = []
try:
params["offset"] = str(int(params["offset"]) + int(getNbMedias()))
except: pass
url = sys.argv[0] + '?' + urlencode(params)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
def audioHKOld():
movies = extractMedias(sql=sql)
affMovies("audiobook", movies)
def audioHK():
typM = "audioBook"
xbmcplugin.setPluginCategory(__handle__, "Livres Audio")
xbmcplugin.setContent(__handle__, 'movies')
sql = "SELECT auteur, titre, numId, description, poster, link, '' FROM audioBook ORDER BY id DESC"#auteur ASC, titre ASC "
movies = extractMedias(sql=sql)
for movie in movies:
media = Media("audiobook", *movie)
media.typeMedia = typM
addDirectoryEbook("%s" %(media.title), isFolder=False, parameters={"action": "playHK", "lien": media.link, "u2p": media.numId, "typMedia": media.typeMedia}, media=media)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_UNSORTED)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_TITLE)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def addDirectoryEbook(name, isFolder=True, parameters={}, media="" ):
''' Add a list item to the XBMC UI.'''
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
li = xbmcgui.ListItem(label=("%s" %(name)))
#Suppression du If qui faisait la meme chose...
updateInfoTagVideo(li,media,False,False,False,False,False)
li.setArt({'icon': media.backdrop, 'thumb': media.poster,})
li.setProperty('IsPlayable', 'true')
url = sys.argv[0] + '?' + urlencode(parameters)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
def logos(typM):
if typM == "movie":
#clearlogo clearart fanart
sql = "SELECT numId, logo, clearart FROM movieFanart"
logos = extractMedias(sql=sql)
dictLogos = {x[0]: x[1] for x in logos if x[1]}
dictArt = {x[0]: x[2] for x in logos if x[2]}
#clearlogo tmdb
sql = "SELECT numId, logo FROM movieTMDBlogo"
logos = extractMedias(sql=sql)
dictLogosTMDB = {x[0]: x[1] for x in logos}
else:
sql = "SELECT numId, logo, clearart FROM tvshowFanart"
logos = extractMedias(sql=sql)
dictLogos = {x[0]: x[1] for x in logos if x[1]}
dictArt = {x[0]: x[2] for x in logos if x[2]}
#clearlogo tmdb
sql = "SELECT numId, logo FROM tvshowTMDBlogo"
logos = extractMedias(sql=sql)
dictLogosTMDB = {x[0]: x[1] for x in logos}
return dictLogos, dictArt, dictLogosTMDB
def affMovies(typM, medias, params=""):
if params and "favs" in params.keys():
nom = widget.getProfil(params["favs"])
xbmcplugin.setPluginCategory(__handle__, "Favs: %s" %nom)
else:
xbmcplugin.setPluginCategory(__handle__, typM)
try:
if medias[0][4] == "divers":
xbmcplugin.setContent(__handle__, 'files')
elif typM == "movie":
xbmcplugin.setContent(__handle__, 'movies')
else:
xbmcplugin.setContent(__handle__, 'tvshows')
except:
xbmcplugin.setContent(__handle__, 'movies')
if __addon__.getSetting("actifhk") != "false":
dictLogos, dictArt, dictLogosTMDB = logos(typM)
else:
dictLogos, dictArt, dictLogosTMDB = {}, {}, {}
i = 0
for i, media in enumerate(medias):
try:
media = Media(typM, *media[:-1])
except:
media = Media(typM, *media)
if typM == "saga":
addDirectoryFilms(media.title, isFolder=True, parameters={"action":"MenuFilm", "famille": "sagaListe", "numIdSaga": media.numId}, media=media)
else:
if media.numId == "divers":
media.numId = 0
addDirectoryFilms("%s (%s)" %(media.title, media.year), isFolder=False, parameters={"action": "playHK", "lien": media.link, "u2p": media.numId}, media=media)
else:
if typM == "movie":
urlFanart = "http://assets.fanart.tv/fanart/movie/"
else:
urlFanart = "http://assets.fanart.tv/fanart/tv/"
if int(media.numId) in dictLogos.keys():
media.clearlogo = urlFanart + dictLogos[int(media.numId)]
else:
if int(media.numId) in dictLogosTMDB.keys():
media.clearlogo = "http://image.tmdb.org/t/p/w300" + dictLogosTMDB[int(media.numId)]
else:
media.clearlogo = ""
if int(media.numId) in dictArt.keys():
media.clearart = urlFanart + dictArt[int(media.numId)]
else:
media.clearart = ""
if typM == "movie":
ok = addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": "detailM", "lien": media.link, "u2p": media.numId}, media=media)
'''
if __addon__.getSetting("newfen") == "false":
ok = addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": "detailM", "lien": media.link, "u2p": media.numId}, media=media)
else:
ok = addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": "visuFenmovie", "lien": media.link, "u2p": media.numId, 'title': media.title}, media=media)
'''
elif typM == "audiobook":
ok = addDirectoryFilms(media.title, isFolder=True, parameters={"action": "play", "lien": media.link, "u2p": media.numId}, media=media)
else:
if __addon__.getSetting("actifnewpaste") != "false":
ok = addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": "affSaisonUptofoldercrypt", "u2p": media.numId}, media=media)
else:
ok = addDirectoryFilms("%s" %(media.title), isFolder=True, parameters={"action": "detailT", "lien": media.link, "u2p": media.numId}, media=media)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_UNSORTED)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_VIDEO_YEAR)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_TITLE)
xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_VIDEO_RATING)
#xbmcplugin.addSortMethod(__handle__, xbmcplugin.SORT_METHOD_LABEL_IGNORE_FOLDERS, labelMask="Page Suivante")
if i >= (int(getNbMedias())) - 1:
addDirNext(params)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True, cacheToDisc=True)
def addDirectoryFilms(name, isFolder=True, parameters={}, media="" ):
''' Add a list item to the XBMC UI.'''
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
li = xbmcgui.ListItem(label=name)
updateInfoTagVideo(li,media,True,False,True,False,False)
#liz.setPath("plugin://%s/play/%s" % (ADDON.getAddonInfo("id"),urllib.quote(url, safe='')) )
li.setArt({'icon': media.backdrop,
'thumb': media.poster,
'poster': media.poster,
#'icon': addon.getAddonInfo('icon'),
'fanart': media.backdrop})
if media.clearlogo :
li.setArt({'clearlogo': media.clearlogo})
if media.clearart :
li.setArt({'clearart': media.clearart})
commands = []
#commands.append(("Ajout Fav'S HK", 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=fav&mode=ajout&u2p=%s&typM=movies)' %media.numId, ))
commands.append(('[COLOR yellow]Bande Annonce[/COLOR]', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=ba&u2p=%s&typM=%s)' %(media.numId, media.typeMedia)))
if media.typeMedia == "movie":
#trk = actifTrakt()
#if trk and media.typeMedia == "movie":
# commands.append(('[COLOR yellow]Cocher Vu dans Trakt[/COLOR]', 'ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=vuMovieTrakt&u2p=%s,return)' %media.numId))
commands.append(('[COLOR yellow]Recherche[/COLOR]', 'ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=MenuFilm&famille=Search,return)'))
sch = 'ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=MenuFilm&famille=Search,return)'
else:
commands.append(('[COLOR yellow]Recherche[/COLOR]', 'ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=MenuSerie&famille=Search,return)'))
sch = 'ActivateWindow(10025,plugin://plugin.video.sendtokodiU2P/?action=MenuSerie&famille=Search,return)'
commands.append(('[COLOR yellow]Gestion[/COLOR]', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=gestionMedia&u2p=%s&typM=%s)'%(media.numId, media.typeMedia)))
commands.append(('[COLOR yellow]Choix Profil[/COLOR]', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=actifPm)'))
commands.append(('[COLOR yellow]Reload Skin[/COLOR]', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=rlk)'))
#commands.append(("[COLOR yellow]Refresh[/COLOR]", "Container.Refresh"))
li.addContextMenuItems(commands)
isWidget = xbmc.getInfoLabel('Container.PluginName')
if "U2P" not in isWidget:
li.setProperty('widget', 'true')
if media.typeMedia == "movie":
li.setProperty('widgetmovie', 'true')
li.setProperty('lire', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=visuFenmovie&u2p=%s&title=%s&lien=%s)' %(media.numId, media.title, media.link))
#li.setProperty('lire', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=playHK&u2p=%s&typM=%s&lien=%s)' %(media.numId, media.typeMedia, media.link))
li.setProperty('ba', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=ba&u2p=%s&typM=%s)' %(media.numId, media.typeMedia))
li.setProperty('gestion', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=gestionMedia&u2p=%s&typM=%s)'%(media.numId, media.typeMedia))
li.setProperty('search', sch)
li.setProperty('profil', 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=actifPm)')
li.setProperty("reloadSkin", 'RunPlugin(plugin://plugin.video.sendtokodiU2P/?action=rlk)')
#li.setProperty("Refresh", "Container.Refresh")
li.setProperty('IsPlayable', 'true')
url = sys.argv[0] + '?' + urlencode(parameters)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
def fenMovie(params):
#xbmcplugin.setPluginCategory(__handle__, "Choix Pbi2kodi")
#xbmcplugin.setContent(__handle__, 'files')
title = params["title"]
u2p = params["u2p"]
try:
links = params["lien"]
except :
links = ""
#dialog = xbmcgui.Dialog()
#ret = dialog.contextmenu(['Détails Informations HK', 'Lire', "Ajouter Fav's HK", "Retirer LastView"])
#notice(ret)
#if ret == 0:
window = FenFilmDetail(title=title, numId=u2p, links=links)
# Show the created window.
window.doModal()
del window
#elif ret == 1:
# affLiens2({"u2p": u2p, "lien": links})
#xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True, cacheToDisc=False)
def menuPbi():
xbmcplugin.setPluginCategory(__handle__, "Choix U2Pplay")
xbmcplugin.setContent(__handle__, 'files')
listeChoix = [("01. Médiathéques", {"action":"movies"}, "pastebin.png", "Mediathéque Pastebin"),
("02. Import DataBase", {"action":"bd"}, "strm.png", "Import DATEBASE"),
#("03. Création Listes", {"action":"createL"}, "debrid.png", "Création de liste Widget"),
#("04. Suppréssion Listes", {"action":"supL"}, "debrid.png", "Suppréssion de liste Widget"),
#("05. Création Listes lecture", {"action":"createLV"}, "debrid.png", "Création de liste lecture perso ou favoris"),
#("06. Suppréssion Listes lecture", {"action":"suppLV"}, "debrid.png", "Suppréssion de liste lecture perso ou favoris"),
#("07. Création Listes Trakt", {"action":"createLT"}, "debrid.png", "Importation et Création liste trakt"),
#("08. Suppréssion Listes/Groupe Trakt", {"action":"suppLT"}, "debrid.png", "Suppréssion liste/groupe trakt"),
#("09. Création Listes Paste(s)", {"action":"createLP"}, "liste.png", "Création liste avec index paste(s)"),
#("10. Suppréssion Listes Paste(s)", {"action":"suppLP"}, "liste.png", "Suppréssion liste avec index paste(s)"),
#("11. Création Listes TMDB", {"action":"createLTMDB"}, "liste.png", "Création liste avec numéro TMDB"),
#("12. Suppréssion Listes TMDB", {"action":"suppLTMDB"}, "liste.png", "Suppréssion liste TMDB"),
#("13. Création Accés Repertoire Uptobox", {"action":"createRUPTO"}, "liste.png", "Création Accés repertoire Uptobox"),
#("14. Création Accés Repertoire Publique Uptobox", {"action":"createRUPTOP"}, "liste.png", "Création Accés repertoire Publique Uptobox"),
]
# mon iptv
if __addon__.getSetting("iptv") != "false" and vIPTV:
listeChoix.append(("03. IPTV", {"action":"iptvLoad"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/iptv.png', "iptv"))
#strms
if __addon__.getSetting("actifStrm") != "false" and vIPTV:
listeChoix.append(("04. Import STRMS Maj", {"action":"strms"}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/liste.png', "Création strms via listes perso"))
listeChoix.append(("20. Import Config", {"action":"impHK"}, "debrid.png", "Importation d'un config prefaite via rentry"))
for choix in listeChoix:
addDirectoryItemLocal(choix[0], isFolder=True, parameters=choix[1], picture=choix[2], texte=choix[3])
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def addDirectoryItemLocal(name, isFolder=True, parameters={}, picture="", texte="" ):
''' Add a list item to the XBMC UI.'''
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li, name, texte)
#Overlay ne dispose de method sur le getVideoInfoTag ...
#li.setInfo('video', {"title": name, 'plot': texte, 'mediatype': 'video', "overlay": 6})
#'playcount':0, "status": "Continuing"
li.setArt({'thumb': 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/%s' %picture,
'icon': addon.getAddonInfo('icon'),
#'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
def selectOS():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
choixOs = ["WIN (D:\\kodiBase\\)", "LIBREELEC (/storage/downloads/Kodi/)", "ANDROID (/storage/emulated/0/kodiBase/)", "LINUX (/home/(user)/kodiBase/)", "XBOX (U:\\Users\\UserMgr0\\AppData\\Local\\Packages\\XBMCFoundation.Kodi_4n2hpmxwrvr6p\\LocalState\\userdata\\)", 'LOCAL', "Mon repertoire"]
dialogOS = xbmcgui.Dialog()
selectedOS = dialogOS.select("Choix OS", choixOs)
if selectedOS != -1:
if selectedOS == len(choixOs) - 1:
osVersion = addon.getSetting("osVersion")
dialogPaste = xbmcgui.Dialog()
d = dialogPaste.input("Repertoire STRM", type=xbmcgui.INPUT_ALPHANUM, defaultt=osVersion)
addon.setSetting(id="osVersion", value=d)
else:
addon.setSetting(id="osVersion", value=choixOs[selectedOS])
def configKeysApi():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
dictApi = {"Uptobox": ["keyupto", "Key Api Uptobox"], "Alldebrid": ["keyalldebrid", "Key Api Alldebrid"], "RealDebrid": ["keyrealdebrid", "Key Api RealDebrid"]}
choixApi = list(dictApi.keys())
dialogApi = xbmcgui.Dialog()
selectedApi = dialogApi.select("Choix Debrideurs", choixApi)
if selectedApi != -1:
key = addon.getSetting(dictApi[choixApi[selectedApi]][0])
d = dialogApi.input(dictApi[choixApi[selectedApi]][1], type=xbmcgui.INPUT_ALPHANUM, defaultt=key)
addon.setSetting(id=dictApi[choixApi[selectedApi]][0], value=d)
def makeStrmsOld(clear=0):
pDialog = xbmcgui.DialogProgress()
pDialog.create('Pbi2kodi', 'Extraction Paste... .')
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
osVersion = addon.getSetting("osVersion")
if "WIN" in osVersion:
repKodiName = "D:\\kodiBase\\"
elif "LIBREELEC" in osVersion:
repKodiName = "/storage/downloads/Kodi/"
elif "LINUX" in osVersion:
repKodiName = "/storage/downloads/Kodi/"
elif "ANDROID" in osVersion:
repKodiName = "/storage/emulated/0/kodiBase/"
elif "XBOX" in osVersion:
repKodiName = "U:\\Users\\UserMgr0\\AppData\\Local\\Packages\\XBMCFoundation.Kodi_4n2hpmxwrvr6p\\LocalState\\userdata\\"
else:
repKodiName = osVersion
lePaste = addon.getSetting("paste")
dictPaste = idPaste(lePaste)
for nomRep, tabPaste in dictPaste.items():
notice(nomRep)
paramPaste = {"tabIdPbi": tabPaste, "namePbi": 'test', "repKodiName": repKodiName, "clear": clear}
pbi = Pastebin(**paramPaste)
pbi.makeMovieNFO(pbi.dictFilmsPaste.values(), clear=clear, progress=pDialog, nomRep=nomRep)
pDialog.update(0, 'SERIES')
pbi.makeSerieNFO(pbi.dictSeriesPaste.values(), clear=clear, progress=pDialog, nomRep=nomRep)
pDialog.update(0, 'ANIMES')
pbi.makeAnimeNFO(pbi.dictAnimesPaste.values(), clear=clear, progress=pDialog, nomRep=nomRep)
pDialog.update(0, 'DIVERS')
pbi.makeDiversNFO(pbi.dictDiversPaste.values(), clear=clear, progress=pDialog, nomRep=nomRep)
showInfoNotification("strms créés!")
return True
def makeStrms(clear=0):
strmC = Strm(BDMEDIANew)
strmC.makeStrms(clear=clear)
showInfoNotification("strms créés!")
xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.Scan", "id": "1"}')
fNewSerie = xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/newserie.txt')
if os.path.exists(fNewSerie):
os.remove(fNewSerie)
return True
def idPaste(lePaste):
html_parser = HTMLParser()
motifAnotepad = r'.*<\s*div\s*class\s*=\s*"\s*plaintext\s*"\s*>(?P<txAnote>.+?)</div>.*'
rec = requests.get("https://anotepad.com/note/read/" + lePaste, timeout=3)
r = re.match(motifAnotepad, rec.text, re.MULTILINE|re.DOTALL|re.IGNORECASE)
tx = r.group("txAnote")
tx = html_parser.unescape(tx)
dictLignes = {x.split("=")[0].strip(): [y.strip() for y in x.split("=")[1].split(",")] for x in tx.splitlines() if x and x[0] != "#"}
return dictLignes
def editPaste():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
paste = addon.getSetting("paste")
dialogPaste = xbmcgui.Dialog()
d = dialogPaste.input("Num AnotePad Pastes", type=xbmcgui.INPUT_ALPHANUM, defaultt=paste)
addon.setSetting(id="paste", value=d)
def editNbThumbnails():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
paste = addon.getSetting("thumbnails")
dialogPaste = xbmcgui.Dialog()
d = dialogPaste.input("Nombre d'images THUMBNAILS conservées (0=illimité)", type=xbmcgui.INPUT_ALPHANUM, defaultt=paste)
addon.setSetting(id="thumbnails", value=d)
def editResos():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
paste = addon.getSetting("resos")
dialogPaste = xbmcgui.Dialog()
d = dialogPaste.input("resos prioritaire & timing", type=xbmcgui.INPUT_ALPHANUM, defaultt=paste)
addon.setSetting(id="resos", value=d)
def delTag(dataBaseKodi):
cnx = sqlite3.connect(dataBaseKodi)
cur = cnx.cursor()
cur.execute("DELETE FROM tag")
cur.execute("DELETE FROM tag_link")
cnx.commit()
cur.close()
cnx.close()
def creaGroupe():
showInfoNotification("Création groupes!")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
osVersion = addon.getSetting("osVersion")
lePaste = addon.getSetting("paste")
dictPaste = idPaste(lePaste)
delTag(__database__)
for nomRep, tabPaste in dictPaste.items():
pDialog2 = xbmcgui.DialogProgressBG()
pDialog2.create('Pbi2kodi', 'Création Groupes (%s)...' %nomRep)
#notice(nomRep)
paramPaste = {"tabIdPbi": tabPaste, "namePbi": 'test', "repKodiName": "", "clear": 0}
pbi = Pastebin(**paramPaste)
pbi.UpdateGroupe(pbi.dictGroupeFilms, __database__, progress= pDialog2, gr=nomRep)
#pDialog2.update(10, 'SERIES')
pbi.UpdateGroupe(pbi.dictGroupeSeries, __database__, mediaType="tvshow", progress= pDialog2, gr=nomRep)
pDialog2.close()
showInfoNotification("Groupes créés!")
def getTimeBookmark(numId, dataBaseKodi, typMedia):
cnx = sqlite3.connect(dataBaseKodi)
cur = cnx.cursor()
if typMedia == "movie":
sql = "SELECT timeInSeconds FROM bookmark WHERE idFile=(SELECT m.idFile FROM movie as m WHERE m.idMovie=%s)" %(numId)
else:
sql = "SELECT timeInSeconds FROM bookmark WHERE idFile=(SELECT m.idFile FROM episode as m WHERE m.idEpisode=%s)" %(numId)
cur.execute(sql)
seek = [x[0] for x in cur.fetchall() if x]
cur.close()
cnx.close()
if seek:
return seek[0]
else:
return 0
def getSeasonU2P(numId, dataBaseKodi , numEpisode):
cnx = sqlite3.connect(dataBaseKodi)
sql = "SELECT c18 FROM episode WHERE c19=(SELECT m.c19 FROM episode as m WHERE m.idEpisode=%s)" %(numId)
cur = cnx.cursor()
cur.execute(sql)
tabEpisodes = sorted([x[0] for x in cur.fetchall() if x])
cur.close()
cnx.close()
return tabEpisodes[int(numEpisode):]
def createListItemFromVideo(video):
try:
url = video['url']
title = video['title']
li = xbmcgui.ListItem(title, path=url)
if "episode" in video.keys():
updateMinimalInfoTagVideo(li,title,None, video['episode'],video['season'])
else:
updateMinimalInfoTagVideo(li,title)
except Exception as e:
notice("Service.py - createListItemFromVideo::createListItemFromVideo " + str(e))
return li
def getIDfile(f):
try:
cnx = sqlite3.connect(__database__)
cur = cnx.cursor()
sql = "SELECT idFile FROM files WHERE strFilename=? AND dateAdded IS NOT NULL"
cur.execute(sql, (f,))
return cur.fetchone()[0]
except Exception as e:
notice("get infos file " + str(e))
def prepareUpNext(title, numId, saison, episode):
#notice(episode)
if __addon__.getSetting("actifnewpaste") != "false":
link = uptobox.getLinkUpNext(numId, saison, int(episode) + 1)
elif __addon__.getSetting("actifhk") != "false":
sql = "SELECT link FROM tvshowEpisodes \
WHERE numId={} AND saison='Saison {}' AND episode=='S{}E{}'".format(numId, str(saison).zfill(2), str(saison).zfill(2), str(int(episode) + 1).zfill(2))
link = extractMedias(sql=sql, unique=1)
#notice(link)
next_info = {}
if link:
try:
mdb = TMDB(__keyTMDB__)
tabEpisodes = mdb.saison(numId, saison)
#['Épisode 1', 'Maud Bachelet semble vivre une vie parfaite ', '2022-01-10', '/jkV6JVxXIiDujhEyFreyEo5IxUe.jpg', 0.0, 1, 1]
if [x for x in tabEpisodes if x[-1] > int(episode)]:
next_info["current_episode"] = [dict([
("episodeid", x[-1]),
("tvshowid", 0),
("title", x[0]),
("art", {
'thumb': "http://image.tmdb.org/t/p/w500%s" %x[3],
'tvshow.clearart': "",
'tvshow.clearlogo': "",
'tvshow.fanart': "",
'tvshow.landscape': "http://image.tmdb.org/t/p/w500%s" %x[3],
'tvshow.poster': '',
}),
("season", x[-2]),
("episode", x[-1]),
("showtitle", title),
("plot", x[1]),
("rating", x[-3]), ("firstaired", x[2])]) for x in tabEpisodes if x[-1] == int(episode)][0]
next_info["next_episode"] = [dict([
("episodeid", x[-1]),
("tvshowid", 0),
("title", x[0]),
("art", {
'thumb': "http://image.tmdb.org/t/p/w500%s" %x[3],
'tvshow.clearart': "",
'tvshow.clearlogo': "",
'tvshow.fanart': "",
'tvshow.landscape': "http://image.tmdb.org/t/p/w500%s" %x[3],
'tvshow.poster': '',
}),
("season", x[-2]),
("episode", x[-1]),
("showtitle", title),
("plot", x[1]),
("rating", x[-3]), ("firstaired", x[2])]) for x in tabEpisodes if x[-1] == int(episode) + 1][0]
#plugin://plugin.video.sendtokodiU2P/?action=playHK&lien=7UM9cgSAc%40yqh47Hp6a6kW%23&u2p=154454
param = {"u2p": numId, 'action': "playHKEpisode", 'lien': link[0], "title": title, 'episode': int(episode) + 1, "saison": saison, "typMedia": "episode"}
urls = link[0].split("#")
url = sys.argv[0] + '?' + urlencode(param)
next_info["play_url"] = url
#next_info["notification_time"] = 70
#notice(next_info)
if next_info["next_episode"]:
notice(upnext_signal("plugin.video.sendtokodiU2P", next_info))
except: pass
def playEpisode(params):
#notice(params)
histoReso = gestionBD("getHK", params["u2p"], params["saison"])
if histoReso:
resoP = histoReso[0]
#notice(resoP)
tabreso = ["1080", "720", "2160", "480", "4K", '360']
reso = "1080"
for motif in tabreso:
ch = r'(\.)(%s)p?\.' %motif
r = re.search(ch, resoP, re.I)
if r:
reso = motif
#notice(reso)
if xbmc.Player().isPlaying():
tt = 0
for x in range(3):
tt = xbmc.Player().getTotalTime()
if tt:
break
time.sleep(0.1)
t = xbmc.Player().getTime()
if __addon__.getSetting("bookonline") != "false":
numEpisode = int(params["episode"]) - 1
widget.pushSite("http://%s/requete.php?name=%s&type=posserie&numid=%s&pos=%.3f&tt=%.3f&saison=%s&episode=%s"\
%(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], t, tt, params["saison"], str(numEpisode)))
else:
widget.bdHK(numId=params["u2p"], pos=t, tt=tt, typM="episode", saison=int(params["saison"]), episode=int(params["episode"]) - 1)
sql = "SELECT link, release FROM episodes WHERE numId={} AND saison={} AND episode={}".format(int(params["u2p"]), int(params["saison"]), int(params["episode"]))
liste = createbdhk.extractMedias(sql=sql)
params["lien"] = liste[0][0]
for link, release in liste:
if reso in release:
params["lien"] = link
break
param = {"u2p": params["u2p"], 'action': "playHK", 'lien': params["lien"], 'episode': params["episode"], "saison": params["saison"], "typMedia": "episode"}
#param = ["%s=%s" %(k, v) for k, v in param.items()]
#param = "&".join(param)
#notice(param)
#xbmc.executebuiltin("RunPlugin(plugin://plugin.video.sendtokodiU2P/?%s)" %param)
playMediaHK(param)
def mepInfos(numId):
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m WHERE m.numId={}".format(numId)
movies = extractMedias(sql=sql)
media = Media("movie", *movies[0])
logo, clearart, banner = extractFanart(numId)
urlFanart = "http://assets.fanart.tv/fanart/movie/"
li = xbmcgui.ListItem(label=media.title)
updateInfoTagVideo(li,media,True,False,True,False,False)
#liz.setPath("plugin://%s/play/%s" % (ADDON.getAddonInfo("id"),urllib.quote(url, safe='')) )
li.setArt({'icon': media.backdrop,
'thumb': media.poster,
'poster': media.poster,
'clearlogo': urlFanart,
'fanart': media.backdrop})
return li
def testCertification(numId, typMedia):
if __addon__.getSetting("bookonline") != "false":
try:
passwd = __addon__.getSetting("bookonline_name")
certificationUser = widget.getCertification(passwd)
if certificationUser[0] > 18:
return False
certificationCorrect = widget.recupCertif(numId, typMedia)
if not certificationCorrect:
if __addon__.getSetting("actifnewpaste") != "false":
if typMedia == "movie":
sql = "SELECT certif FROM filmsPub WHERE numId={}".format(numId)
else:
sql = "SELECT certif FROM seriesPub WHERE numId={}".format(numId)
certificationMedia = createbdhk.extractMedias(sql=sql, unique=1)
elif __addon__.getSetting("actifhk") != "false":
if typMedia == "movie":
sql = "SELECT certification FROM movieCertification WHERE numId={}".format(numId)
else:
sql = "SELECT certification FROM tvshowCertification WHERE numId={}".format(numId)
certificationMedia = extractMedias(sql=sql, unique=1)
else:
certificationMedia = [certificationCorrect]
if certificationMedia and isinstance(certificationMedia[0], int):
if certificationMedia[0] > certificationUser[0]:
showInfoNotification("tu es trop jeune .....")
return True
else:
if certificationUser[1] == 0:
if typMedia == "movie":
if __addon__.getSetting("actifnewpaste") != "false":
sql2 = "SELECT numId FROM filmsRepos WHERE famille='concert'"
concerts = createbdhk.extractMedias(sql=sql2)
concerts = [x[0] for x in concerts]
if int(numId) in concerts:
return False
elif __addon__.getSetting("actifhk") != "false":
sql2 = "SELECT numId FROM movieFamille WHERE famille='#Concerts'"
concerts = extractMedias(sql=sql2)
concerts = [x[0] for x in concerts]
if int(numId) in concerts:
return False
if certificationUser[0] > 11:
if __addon__.getSetting("actifnewpaste") != "false":
sql2 = "SELECT numId FROM filmsRepos WHERE famille='concert' or famille='spectacle' or famille='docu'"
autres = createbdhk.extractMedias(sql=sql2)
autres = [x[0] for x in autres]
if int(numId) in autres:
return False
elif __addon__.getSetting("actifhk") != "false":
sql2 = "SELECT numId FROM movieFamille WHERE famille='#Sports' or famille='#Spectacles'"
autres = extractMedias(sql=sql2)
autres = [x[0] for x in autres]
if int(numId) in autres:
return False
showInfoNotification("tu es trop jeune .....")
return True
return False
except:
return False
def nettHistoDB(bd):
cnx2 = sqlite3.connect(bd)
cur2 = cnx2.cursor()
try:
cur2.execute("SELECT (SELECT f.strFilename FROM files as f WHERE b.idFile=f.idFile) FROM bookmark as b")
except: pass
try:
[cur2.execute("DELETE FROM files WHERE strFilename=?", (x[0],)) for x in cur2.fetchall() if "playMediaUptobox&" not in x[0]]
except: pass
cnx2.commit()
cur2.close()
cnx2.close()
def playMediaHK(params):
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
if not typMedia:
xbmc.executebuiltin("Dialog.Close(busydialog)")
xbmc.sleep(500)
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
notice(typMedia)
numId = params["u2p"]
try:
typMedia = params["typMedia"]
except: pass
#======================================== certification ========================================
if testCertification(numId, typMedia):
return
#====================================== fin certif ============================================
if typMedia not in ["movie", "audioBook"]:
if "saison" in params.keys():
try:
title = params['title']
except:
title = ""
numEpisode = params['episode']
saison = params["saison"]
li = xbmcgui.ListItem()
media = MediaSp(**{"title": title, "episode": numEpisode, "season": saison, "numId": numId, "typMedia": typMedia})
updateInfoTagVideo2(li, media)
#xbmcgui.ListItem().setInfo('video', {"title": title, "episode": numEpisode, "season": saison})
else:
title = xbmc.getInfoLabel('ListItem.TVShowTitle')
saison = xbmc.getInfoLabel('ListItem.Season')
numEpisode = xbmc.getInfoLabel('ListItem.Episode')
if not numEpisode and 'episode' in params.keys():
numEpisode = params['episode']
#prepareUpNext(title, numId, saison, numEpisode)
else:
saison = 1
result = getParams(params['lien'], u2p=numId, saisonIn=saison)
#notice(result)
if result and "url" in result.keys():
if typMedia not in ["movie", "audioBook"]:
result["episode"] = numEpisode
result["season"] = saison
else:
result["episode"] = ""
result["season"] = ""
url = str(result['url'])
showInfoNotification("playing title " + result['title'])
try:
result['title'] = xbmc.getInfoLabel('ListItem.TITLE')
listIt = createListItemFromVideo(result)
if "skin" in params.keys():
li = mepInfos(params["u2p"])
xbmc.Player().play(url, li)
else:
xbmcplugin.setResolvedUrl(__handle__, True, listitem=listIt)
except Exception as e:
notice("playMediaHK - Erreur Play " + str(e))
threading.Thread(target=gestionThumbnails).start()
count = 0
time.sleep(2)
while not xbmc.Player().isPlaying():
count = count + 1
if count >= 20:
return
else:
time.sleep(1)
try:
trk = actifTrakt()
except:
trk = None
if numId != "divers" and str(numId) != "0":
if typMedia == "movie":
if __addon__.getSetting("bookonline") != "false":
#notice("http://%s/requete.php?name=%s&type=getpos&numid=%s&media=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], typMedia))
recupPos = widget.responseSite("http://%s/requete.php?name=%s&type=getpos&numid=%s&media=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], typMedia))
if recupPos:
seek = float(recupPos[0])
else:
seek = 0
else:
seek = widget.bdHK(sauve=0, numId=int(numId))
elif typMedia == "audioBook":
seek = 0
else:
if __addon__.getSetting("bookonline") != "false":
recupPos = widget.responseSite("http://%s/requete.php?name=%s&type=getpos&numid=%s&media=%s&saison=%s&episode=%s" \
%(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], typMedia, saison, numEpisode))
if recupPos:
seek = float(recupPos[0])
else:
seek = 0
else:
seek = widget.bdHK(sauve=0, numId=int(numId), typM=typMedia, saison=saison, episode=numEpisode)
else:
seek = 0
if seek > 0:
dialog = xbmcgui.Dialog()
resume = dialog.yesno('Play Video', 'Resume last position?')
#notice(seek)
if resume:
notice(xbmc.getInfoLabel('Player.Title'))
xbmc.Player().seekTime(int(seek))
else:
notice("delete")
okUpNext = True
tt = xbmc.Player().getTotalTime()
#web_pdb.set_trace()
notice("typeMedia " + typMedia)
# scrobble
try:
if trk and numId != "divers" and str(numId) != "0":
pos = 0.0
if typMedia == "movie":
trk.scrobble(title="", year=0, numId=numId, pos=pos, typM="movie", mode="start")
else:
trk.scrobble(title="", year=0, numId=numId, pos=pos, season=saison, number=numEpisode, typM="show", mode="start")
except: pass
t = 0
while xbmc.Player().isPlaying():
t = xbmc.Player().getTime()
#notice(t)
if tt == 0:
tt = xbmc.Player().getTotalTime()
time.sleep(1)
if t > 10 and okUpNext and typMedia not in ["movie", "audioBook"]:
try:
prepareUpNext(title, numId, saison, numEpisode)
okUpNext = False
except: pass
if t > 180 and numId != "divers" and str(numId) != "0":
if typMedia == "movie":
if __addon__.getSetting("bookonline") != "false":
widget.pushSite("http://%s/requete.php?name=%s&type=posmovie&numid=%s&pos=%.3f&tt=%.3f" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], t, tt))
else:
widget.bdHK(numId=numId, pos=t, tt=tt, typM=typMedia)
elif typMedia == "episode":
if __addon__.getSetting("bookonline") != "false":
requete = "http://%s/requete.php?name=%s&type=posserie&numid=%s&pos=%d&tt=%d&saison=%s&episode=%s"\
%(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], t, tt, saison, numEpisode)
widget.pushSite(requete)
if tt and (float(t) / float(tt) * 100.0) > 90.0:
#push on "on continue"
widget.gestOC(params["u2p"], "ajout")
scraperUPTO.extractEpisodesOnContinue()
#
p = {"name": __addon__.getSetting("bookonline_name"), "type": "vuepisodes", "numid": params["u2p"], "saison": saison, "episodes": numEpisode,"vu": "1"}
requete = "http://%s/requete.php" %__addon__.getSetting("bookonline_site") + '?' + urlencode(p)
widget.pushSite(requete)
else:
widget.bdHK(numId=numId, pos=t, tt=tt, typM=typMedia, saison=saison, episode=numEpisode)
#fin scrooble
try:
if trk and numId != "divers" and str(numId) != "0" and t :
try:
pos = t / tt * 100.0
except:
pos = 10.0
if typMedia == "movie":
trk.scrobble(title="", year=0, numId=numId, pos=pos, typM="movie", mode="stop")
else:
trk.scrobble(title="", year=0, numId=numId, pos=pos, season=saison, number=numEpisode, typM="show", mode="stop")
except: pass
nettHistoDB(__database__)
if os.path.isfile(xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/rskin.txt')) and __addon__.getSetting("rskin"):
time.sleep(5)
xbmc.executebuiltin('ReloadSkin')
time.sleep(0.05)
os.remove(xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/rskin.txt'))
return
def playMediaOld(params):
result = getParams(params['lien'])
if result and "url" in result.keys():
listIt = createListItemFromVideo(result)
xbmcplugin.setResolvedUrl(__handle__, True, listitem=listIt)
def playMedia(params):
typDB = "non auto"
try:
lastBD = os.path.normpath(os.path.join(__repAddon__, "lastDB.txt"))
if "autonome" in open(lastBD, "r").readline():
typDB = "auto"
except: pass
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
if not typMedia:
xbmc.executebuiltin("Dialog.Close(busydialog)")
xbmc.sleep(500)
typMedia = xbmc.getInfoLabel('ListItem.DBTYPE')
if typDB == "auto":
fPlay = sys.argv[0] + sys.argv[2]
if typMedia != "movie":
idfile= getIDfile(fPlay)
else:
idfile = xbmc.getInfoLabel('ListItem.DBID')
else:
idfile = xbmc.getInfoLabel('ListItem.DBID')
#notice("idFile " + str(idfile))
#notice(xbmc.getInfoLabel('ListItem.Episode'))
#notice(xbmc.getInfoLabel('ListItem.TvShowDBID'))
#notice(xbmc.getInfoLabel('ListItem.PercentPlayed'))
#notice(xbmc.getInfoLabel('ListItem.EndTimeResume'))
#notice("fin listem")
result = getParams(params['lien'])
if result and "url" in result.keys():
url = str(result['url'])
showInfoNotification("playing title " + result['title'])
notice("num id " + str(result))
notice("handle " + str(__handle__))
try:
listIt = createListItemFromVideo(result)
xbmcplugin.setResolvedUrl(__handle__, True, listitem=listIt)
#xbmc.Player().play(url, listIt)
#xbmc.executebuiltin('PlayMedia(%s)' %url)
except Exception as e:
notice("playMedia - Erreur Play " + str(e))
threading.Thread(target=gestionThumbnails).start()
count = 0
time.sleep(2)
while not xbmc.Player().isPlaying():
count = count + 1
if count >= 20:
return
else:
time.sleep(1)
try:
infoTag = xbmc.Player().getVideoInfoTag()
#notice(infoTag.getDbId())
#idfile = infoTag.getDbId()
notice("idFile " + str(idfile))
#notice(xbmc.Player().getPlayingFile())
#typMedia = infoTag.getMediaType()
#
seek = getTimeBookmark(idfile, __database__, typMedia)
except Exception as e:
xbmc.Player().pause
notice(str(e))
seek = 0
if seek > 0:
dialog = xbmcgui.Dialog()
resume = dialog.yesno('Play Video', 'Resume last position?')
if resume:
notice(xbmc.getInfoLabel('Player.Title'))
xbmc.Player().seekTime(int(seek))
#threading.Thread(target=correctionBookmark, args=(idfile, typMedia))
#importDatabase(debug=0)
#tx = testDatabase()
#if tx:
# showInfoNotification("New DataBase en ligne !!!")
#threading.Thread(target=importDatabase)
if typDB == "auto":
tt = xbmc.Player().getTotalTime()
while xbmc.Player().isPlaying():
t = xbmc.Player().getTime()
if tt == 0:
tt = xbmc.Player().getTotalTime()
#notice(t)
time.sleep(1)
notice(str(typMedia) + " " + str(idfile))
if t > 180:
correctionBookmark(idfile, t, tt, typMedia)
notice("ok")
return
def correctionBookmark(idfile, t, tt, typeM):
try:
cnx = sqlite3.connect(__database__)
cur = cnx.cursor()
notice(typeM)
if typeM == "movie":
cur.execute("SELECT idFile FROM movie WHERE idMovie=?", (idfile,))
#else:
# cur.execute("SELECT idFile FROM episode WHERE idEpisode=?", (idfile,))
idfile = cur.fetchone()[0]
notice("idefile " + str(idfile))
try:
delta = ((1 - t / tt) * 100)
except:
delta = 5
if delta < 4:
notice("del media bookmark")
cur.execute("DELETE FROM bookmark WHERE idFile=%s" %idfile)
cur.execute("UPDATE files SET playCount=1 WHERE idFile=%s" %idfile)
else:
cur.execute("SELECT idFile FROM bookmark WHERE idFile=?", (idfile,))
if cur.fetchone():
sql0 = "UPDATE bookmark SET timeInSeconds=? WHERE idFile=?"
cur.execute(sql0, (t, idfile,))
else:
sql0 = "REPLACE INTO bookmark (idFile, timeInSeconds, totalTimeInSeconds, thumbNailImage, player, playerState, type) VALUES(?, ?, ?, ?, ?, ?, ? )"
cur.execute(sql0, (idfile, t, tt, None, 'VideoPlayer', None, 1,))
cnx.commit()
cur.close()
cnx.close()
except Exception as e:
notice("insert bookmark " + str(e))
def majLink(dataBaseKodi):
lastBD = os.path.normpath(os.path.join(__repAddon__, "lastDB.txt"))
cnx = sqlite3.connect(dataBaseKodi)
cur = cnx.cursor()
if "autonome" not in open(lastBD, "r").readline():
dateTimeObj = datetime.datetime.now()
timestampStr = dateTimeObj.strftime("%Y-%m-%d %H:%M:%S")
oldRep = '/storage/emulated/0/kodibase'
#newRep = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/kodibase")
newRep, corr = cheminOs()
if newRep != "/storage/emulated/0/":
newRep = os.path.normpath(os.path.join(newRep, "kodibase"))
cur.execute("UPDATE path SET strPath = REPLACE(strPath, '%s', '%s')" % (oldRep, newRep))
cur.execute("UPDATE movie SET c22 = REPLACE(c22, '%s', '%s')" % (oldRep, newRep))
cur.execute("UPDATE episode SET c18 = REPLACE(c18, '%s', '%s')" % (oldRep, newRep))
#UPDATE art SET url = REPLACE(url,'smb://my_nas/old_share', 'smb://my_nas/new_share');
cur.execute("UPDATE tvshow SET c16 = REPLACE(c16, '%s', '%s')" % (oldRep, newRep))
cur.execute("UPDATE files SET strFilename = REPLACE(strFilename, '%s', '%s'), dateAdded='%s'" % (oldRep, newRep, timestampStr))
if corr:
cur.execute("UPDATE path SET strPath = REPLACE(strPath,'%s', '%s')" %("/", "\\"))
cur.execute("UPDATE episode SET c18 = REPLACE(c18,'%s', '%s')" %("/", "\\"))
cur.execute("UPDATE movie SET c22 = REPLACE(c22,'%s', '%s')" %("/", "\\"))
cur.execute("UPDATE tvshow SET c16 = REPLACE(c16,'%s', '%s')" %("/", "\\"))
cur.execute("UPDATE files SET strFilename = REPLACE(strFilename,'%s', '%s')" %("/", "\\"))
cnx.commit()
# ajout sources
with open(xbmcvfs.translatePath("special://home/userdata/sources.xml"), "r") as f:
txSources = f.read()
with open(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/fileSources.txt"), "r") as f:
tx = f.read()
dictSource = {x.split("=")[0]: x.split("=")[1] for x in tx.splitlines()}
source = """<source>
<name>{}</name>
<path pathversion="1">{}</path>
<allowsharing>true</allowsharing>
</source>\n"""
sources = ""
for k, v in dictSource.items():
depot = os.path.normpath(v.replace(oldRep, newRep))
if v.replace(oldRep, newRep) not in txSources:
sources += source.format(k, depot)
with open(xbmcvfs.translatePath("special://home/userdata/sources.xml"), "w") as f:
f.write(txSources.format(**{"sources":sources}))
cnx2 = sqlite3.connect(__database__)
cur2 = cnx2.cursor()
cur2.execute("SELECT * FROM bookmark")
bookmark = cur2.fetchall()
try:
cur.executemany("INSERT INTO bookmark VALUES(?, ?, ?, ?, ?, ?, ?, ?)", bookmark)
cnx.commit()
except: pass
cur2.execute("SELECT * FROM files WHERE (lastPlayed OR playCount) AND idfile<400000")
histoPlay = cur2.fetchall()
histoPlay = [(x[0], x[1], x[2], x[3] if x[3] and x[3] != 'None' else "", x[4] if x[4] and x[4] != 'None' else "", x[5]) for x in histoPlay]
#print(histoPlay)
for h in histoPlay:
cur.execute("UPDATE files set lastPlayed=?, playCount=? WHERE idFile=? AND idPath=?", (h[4], h[3], h[0], h[1], ))
cnx.commit()
cur2.execute("SELECT * FROM files WHERE idfile>400000")
histoPlay = cur2.fetchall()
for h in histoPlay:
cur.execute("INSERT INTO files VALUES(?, ?, ?, ?, ?, ?)", h)
cnx.commit()
cur.close()
cnx.close()
cur2.close()
cnx2.close()
def cheminOs():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
osVersion = addon.getSetting("osVersion")
corr = 0
if "WIN" in osVersion:
corr = 1
repKodiName = "D:\\kodiBase\\"
elif "LIBREELEC" in osVersion:
repKodiName = "/storage/downloads/"
elif "LINUX" in osVersion:
repKodiName = "/storage/downloads/"
elif "ANDROID" in osVersion:
repKodiName = "/storage/emulated/0/"
elif "XBOX" in osVersion:
corr = 1
repKodiName = "U:\\Users\\UserMgr0\\AppData\\Local\\Packages\\XBMCFoundation.Kodi_4n2hpmxwrvr6p\\LocalState\\userdata\\"
else:
corr = 1
repKodiName = osVersion
return repKodiName, corr
def get_size(rep):
total_size = 0
for dirpath, dirnames, filenames in os.walk(rep):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
def gestionThumbnails():
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
nbT = addon.getSetting("thumbnails")
try:
nbT = int(nbT)
except:
nbT = 0
if nbT > 0:
dbTexture = xbmcvfs.translatePath("special://home/userdata/Database/Textures13.db")
repThumb = xbmcvfs.translatePath("special://thumbnails")
cnx2 = sqlite3.connect(dbTexture)
cur2 = cnx2.cursor()
tabFiles = []
for dirpath, dirs, files in os.walk(repThumb):
for filename in files:
fname = os.path.normpath(os.path.join(dirpath,filename))
tabFiles.append(fname)
if len(tabFiles) > 7000:
tabFiles.sort(key=os.path.getmtime, reverse=True)
for f in tabFiles[7000:]:
head ,tail = os.path.split(f)
cur2.execute("SELECT id FROM texture WHERE cachedurl LIKE '{}'".format("%" + tail + "%"))
num = cur2.fetchone()
if num:
cur2.execute("DELETE FROM texture WHERE id=?", (num[0],))
cur2.execute("DELETE FROM sizes WHERE idtexture=?", (num[0],))
xbmcvfs.delete(f)
cnx2.commit()
cur2.close()
cnx2.close()
def extractNews(numVersion):
listeNews = []
if os.path.isfile(xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/u2pBD.bd')):
cnx = sqlite3.connect(xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/u2pBD.bd'))
cur = cnx.cursor()
cur.execute("SELECT strm FROM strms WHERE version>?", (numVersion,))
listeNews = [x[0] for x in cur.fetchall()]
cur.close()
cnx.close()
return listeNews
def testDatabase(typImport="full"):
ApikeyAlldeb = getkeyAlldebrid()
ApikeyRealdeb = getkeyRealdebrid()
ApikeyUpto = getkeyUpto()
cr = cryptage.Crypt()
repAddon = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/")
repStrm, _ = cheminOs()
if ApikeyUpto:
tx = cr.updateBD(repAddon, t=typImport, key=ApikeyUpto, typkey="upto")
elif ApikeyAlldeb:
tx = cr.updateBD(repAddon, t=typImport, key=ApikeyAlldeb, typkey="alldeb")
elif ApikeyRealdeb:
tx = cr.updateBD(repAddon, t=typImport, key=ApikeyRealdeb, typkey="realdeb")
return tx
"""
def mepAutoStart():
if not os.path.isfile(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/maj.txt")):
repStart = xbmcvfs.translatePath("special://home/addons/service.autoexec/")
repFileStart = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/maj/")
try:
os.mkdir(repStart)
except: pass
for f in os.listdir(repFileStart):
if not os.path.isfile(xbmcvfs.translatePath("special://home/addons/service.autoexec/%s" %f)):
xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/maj/%s" %f), xbmcvfs.translatePath("special://home/addons/service.autoexec/%s" %f))
open(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/maj.txt"), "w")
"""
def mepAutoStart2():
repStart = xbmcvfs.translatePath("special://home/addons/service.majhk/")
repFileStart = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/majhk/")
try:
os.mkdir(repStart)
except: pass
for f in os.listdir(repFileStart):
xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/majhk/%s" %f), xbmcvfs.translatePath("special://home/addons/service.majhk/%s" %f))
#for f in [x for x in os.listdir(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P")) if x[-4:] == ".pyc"]:
# xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/%s" %f), xbmcvfs.translatePath("special://home/addons/service.majhk/%s" %f))
xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/loadhk3.py"), xbmcvfs.translatePath("special://home/addons/service.majhk/loadhk3.py"))
xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "service.majhk", "enabled": true }}')
showInfoNotification("Mise place service Maj !!")
def mepAutoStart():
repStart = xbmcvfs.translatePath("special://home/addons/service.autoexec/")
repFileStart = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/maj/")
try:
os.mkdir(repStart)
except: pass
for f in os.listdir(repFileStart):
xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/maj/%s" %f), xbmcvfs.translatePath("special://home/addons/service.autoexec/%s" %f))
xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "service.autoexec", "enabled": true }}')
showInfoNotification("Mise place Maj au Restat Kodi !!")
def patchNextUp():
xbmcvfs.delete(xbmcvfs.translatePath("special://home/addons/service.upnext/resources/lib/monitor.py"))
xbmcvfs.delete(xbmcvfs.translatePath("special://home/addons/service.upnext/resources/lib/player.py"))
xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/nextup/monitor.py"), xbmcvfs.translatePath("special://home/addons/service.upnext/resources/lib/monitor.py"))
xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/nextup/player.py"), xbmcvfs.translatePath("special://home/addons/service.upnext/resources/lib/player.py"))
showInfoNotification("Patch ok, redemarrez KODI !!!!")
def majDatabase():
importDatabase(debug=0, maj=1)
def createFav():
if not os.path.isfile(os.path.normpath(os.path.join(__repAddon__, "fav.txt"))):
favBD = '''\n<favourite name="Import DataBase" thumb="special://home/addons/plugin.video.sendtokodiU2P/resources/png/database.png">PlayMedia("plugin://plugin.video.sendtokodiU2P/?action=bdauto")</favourite>'''
favMovies = '''<favourite name="Mediatheque HK" thumb="special://home/addons/plugin.video.sendtokodiU2P/resources/png/movies.png">ActivateWindow(10025,"plugin://plugin.video.sendtokodiU2P/?action=movies",return)</favourite>'''
try:
with io.open(xbmcvfs.translatePath("special://home/userdata/favourites.xml"), "r", encoding="utf-8") as f:
txFavs = f.read()
pos = txFavs.find("<favourites>")
pos += len("<favourites>")
txDeb = txFavs[:pos]
txFin = txFavs[pos:]
if favBD not in txFavs:
txDeb += "%s\n" %favBD
if os.path.isfile(os.path.normpath(os.path.join(__repAddon__, "medias.bd"))) and favMovies not in txFavs:
txDeb += favMovies
with io.open(xbmcvfs.translatePath("special://home/userdata/favourites.xml"), "w", encoding="utf-8") as f:
f.write(txDeb + txFin)
open(os.path.normpath(os.path.join(__repAddon__, "fav.txt")), "w")
except:
pass
#txFavs = ""
#txDeb = "<favourites>"
#txFin = "\n</favourites>"
def testHKdb():
cnx = sqlite3.connect(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/medias.bd"))
cur = cnx.cursor()
cur.execute("PRAGMA integrity_check")
result = cur.fetchone()[0]
cur.close()
cnx.close()
return result
def importDatabase(typImport="full", debug=1, maj=0):
repAddon = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/")
fDOWN = 0
tps = time.time()
a = time.time()
if typImport == "epg":
numRecup = __addon__.getSetting("epg")
elif typImport == "ba":
numRecup = __addon__.getSetting("numba")
fDOWN = 1
else:
if not __addon__.getSetting("numhk"):
dialog = xbmcgui.Dialog()
d = dialog.input("Num DB HK ex:zmdeo", type=xbmcgui.INPUT_ALPHANUM)
if d:
__addon__.setSetting("numhk", d)
else:
return
if maj:
numRecup = __addon__.getSetting("numhk")
else:
dictDB = {"HK-autonome": __addon__.getSetting("numhk"), "HK-autonome-forced": __addon__.getSetting("numhk"),
"skin": __addon__.getSetting("skinhk"), "Epg": __addon__.getSetting("epg")}
choixDB = sorted(list(dictDB.keys()))
dialogApi = xbmcgui.Dialog()
if typImport == "autonome":
choixDB = [x for x in choixDB if "HK" in x]
selectedDB = dialogApi.select("Choix DATABASE", choixDB)
if selectedDB != -1:
# debridage
numRecup = dictDB[choixDB[selectedDB]]
if debug:
showInfoNotification("Verif Update")
if "forced" in choixDB[selectedDB]:
fDOWN = 1
else:
return
ApikeyAlldeb, ApikeyRealdeb, ApikeyUpto = getkeyAlldebrid(), getkeyRealdebrid(), getkeyUpto()
cr = cryptage.Crypt()
repStrm, _ = cheminOs()
tx = False
if numRecup:
if ApikeyUpto and not tx:
tx = cr.updateBD(repAddon, key=ApikeyUpto, typkey="upto", numRentry=numRecup, forceDownload=fDOWN)
if ApikeyAlldeb and not tx:
tx = cr.updateBD(repAddon, key=ApikeyAlldeb, typkey="alldeb", numRentry=numRecup, forceDownload=fDOWN)
if ApikeyRealdeb and not tx:
tx = cr.updateBD(repAddon, key=ApikeyRealdeb, typkey="realdeb", numRentry=numRecup, forceDownload=fDOWN)
else:
if ApikeyUpto and not tx:
tx = cr.updateBD(repAddon, key=ApikeyUpto, typkey="upto", forceDownload=fDOWN)
if ApikeyAlldeb and not tx:
tx = cr.updateBD(repAddon, key=ApikeyAlldeb, typkey="alldeb", forceDownload=fDOWN)
if ApikeyRealdeb and not tx:
tx = cr.updateBD(repAddon, key=ApikeyRealdeb, typkey="realdeb", forceDownload=fDOWN)
notice("download %0.2f" %(time.time() - a))
a = time.time()
if tx:
if debug == 0:
showInfoNotification("Update DataBase en cours, wait ....")
pDialogBD2 = xbmcgui.DialogProgressBG()
pDialogBD2.create('U2Pplay', 'Update en cours')
try:
shutil.rmtree(os.path.normpath(os.path.join(repStrm, "xml")), ignore_errors=True)
except: pass
try:
shutil.rmtree(os.path.normpath(os.path.join(repStrm, "xsp")), ignore_errors=True)
except: pass
if os.path.isfile(os.path.normpath(os.path.join(repAddon, "version.txt"))):
shutil.move(os.path.normpath(os.path.join(repAddon, "version.txt")), os.path.normpath(os.path.join(repStrm, "version.txt")))
if os.path.isfile(os.path.normpath(os.path.join(repStrm, "version.txt"))):
numVersion = int(open(os.path.normpath(os.path.join(repStrm, "version.txt")), 'r').readline())
else:
numVersion = 0
with zipfile.ZipFile(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/MyVideos119-U2P.zip"), 'r') as zipObject:
try:
zipObject.extract("MyVideos119-U2P.db", repAddon)
dbIn = True
except:
dbIn = False
listOfFileNames = zipObject.namelist()
nbFiles = len(listOfFileNames)
try:
zipObject.extract("u2pBD.bd", xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/'))
listeNews = extractNews(numVersion)
for i, f in enumerate(listOfFileNames):
nbGroupe = int((i / float(nbFiles)) * 100.0)
pDialogBD2.update(nbGroupe, 'U2Pplay', message="verif STRMS")
if (numVersion == 0 and f[-5:] == ".strm") or f in listeNews:
zipObject.extract(f, repStrm)
elif f[-4:] in [".xml", ".xsp"]:
zipObject.extract(f, repAddon)
elif f in ["version.txt"]:
zipObject.extract(f, repStrm)
else:
if f in ["fileSources.txt", "sources.xml", "fichierDB.txt"] or f[-4:] in [".xml", ".xsp"]:
zipObject.extract(f, repAddon)
except:
try:
zipObject.extract("epg.bd", xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/'))
except: pass
try:
zipObject.extract("ba.db", xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P/'))
except: pass
try:
# extract db HK
bdOk = False
for nbImport in range(3):
zipObject.extract("medias.bd", xbmcvfs.translatePath('special://home/addons/plugin.video.sendtokodiU2P/resources/'))
time.sleep(0.2)
shutil.move(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/medias.bd"), xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/medias.bd"))
time.sleep(0.1)
if debug:
bdOk = True
break
else:
if testHKdb() == "ok":
#notice("nombre import: " + str(nbImport + 1))
bdOk = True
break
time.sleep(2)
if not bdOk:
showInfoNotification('Erreur database corrupt, faite un "Import manuel"')
except: pass
for i, f in enumerate(listOfFileNames):
nbGroupe = int((i / float(nbFiles)) * 100.0)
pDialogBD2.update(nbGroupe, 'U2Pplay', message="verif STRMS")
if f in ["fileSources.txt", "sources.xml", "fichierDB.txt"] or f[-4:] in [".xml", ".xsp", ".zip"]:
zipObject.extract(f, repAddon)
pDialogBD2.close()
if dbIn:
a = time.time()
showInfoNotification("Mise en place new database !!!")
notice("extraction %0.2f" %(time.time() - a))
try:
shutil.move(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/sources.xml"), xbmcvfs.translatePath("special://home/userdata/sources.xml"))
except: pass
majLink(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/MyVideos119-U2P.db"))
xbmcvfs.delete(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/MyVideos119-U2P.zip"))
shutil.move(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/MyVideos119-U2P.db"), __database__)
#xbmcvfs.delete(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/MyVideos119-U2P.db"))
try:
showInfoNotification("Update terminée (%d News)" %len(listeNews))
except:
showInfoNotification("Update terminée database-autonome (test)")
notice("maj DATABASE %0.2f" %(time.time() - a))
else:
xbmcvfs.delete(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/MyVideos119-U2P.zip"))
else:
if debug:
showInfoNotification("Pas d'update")
if debug:
showInfoNotification("Durée Update : %d s" %(time.time() - tps))
gestionThumbnails()
createFav()
time.sleep(0.5)
#xbmc.executebuiltin('ReloadSkin')
return
def delDATABASE():
xbmcvfs.copy(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/MyVideos119-U2P.db"), xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/MyVideos119.db"))
shutil.move(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/MyVideos119.db"), __database__)
showInfoNotification("DATAbase effacée , redemarrez KODI !!!!")
def supWidg():
liste = list(widget.extractListe("all"))
if liste:
dialog = xbmcgui.Dialog()
sups = dialog.multiselect("Liste(s) à supprimer", liste, preselect=[])
if sups:
listeSup = [liste[x] for x in sups]
#notice(listeSup)
widget.supListe(listeSup)
showInfoNotification("Liste(s) choisie(s) éffacée(s)")
def reloadSkin():
time.sleep(0.5)
xbmc.executebuiltin('ReloadSkin')
return
def actifProfil(params, menu=1):
passwd = params["passwd"]
__addon__.setSetting(id="bookonline_name", value=passwd)
#xbmc.executebuiltin("plugin://plugin.video.sendtokodiU2P/?action=movies',return)")
if menu:
ventilationHK()
else:
notice("reload skin")
reloadSkin()
def gestionVuSaison(params):
sql = "SELECT DISTINCT episode FROM episodes WHERE numId={} and saison={}".format(params["u2p"], params["saison"])
liste = createbdhk.extractMedias(sql=sql, unique=1)
liste = [("S{}E{}".format(params["saison"].zfill(2), str(x).zfill(4)), x) for x in liste]
#notice(liste)
liste = [x[0] for x in sorted(liste, key=lambda y: y[1])]
dialog = xbmcgui.Dialog()
choix = ["Aucun", "Tous", "Tous sauf"] + liste
selected = dialog.multiselect("Mettre en Vus", choix, preselect=[])
if selected:
if 0 in selected:
listeVu = []
listeNonVu = liste[:]
elif 1 in selected:
listeVu = liste[:]
listeNonVu = []
elif 2 in selected:
listeVu = [x for x in liste if x not in [liste[y - 3] for y in selected if y > 2]]
listeNonVu = [liste[y - 3] for y in selected if y > 2]
else:
listeNonVu = [x for x in liste if x not in [liste[y - 3] for y in selected if y > 2]]
listeVu = [liste[y - 3] for y in selected if y > 2]
#trakt
trk = actifTrakt()
if trk:
trk.gestionWatchedHistory(numId=[int(params["u2p"])], season=int(params["saison"]), number=[int(x.split("E")[1]) for x in listeVu], typM="show", mode="add")
trk.gestionWatchedHistory(numId=[int(params["u2p"])], season=int(params["saison"]), number=[int(x.split("E")[1]) for x in listeNonVu], typM="show", mode="remove")
if __addon__.getSetting("bookonline") != "false":
episodes = "*".join([str(int(x.split("E")[1])) for x in listeVu])
if episodes:
#notice("http://%s/requete.php?name=%s&type=vuepisodes&numid=%s&saison=%s&episodes=%s&vu=1"\
# %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], params["saison"], episodes))
widget.pushSite("http://%s/requete.php?name=%s&type=vuepisodes&numid=%s&saison=%s&episodes=%s&vu=1"\
%(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], params["saison"], episodes))
time.sleep(0.1)
episodes = "*".join([str(int(x.split("E")[1])) for x in listeNonVu])
if episodes:
#notice("http://%s/requete.php?name=%s&type=vuepisodes&numid=%s&saison=%s&episodes=%s&vu=0"\
# %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], params["saison"], episodes))
widget.pushSite("http://%s/requete.php?name=%s&type=vuepisodes&numid=%s&saison=%s&episodes=%s&vu=0"\
%(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["u2p"], params["saison"], episodes))
else:
for l in listeVu:
episode = int(l.split("E")[1])
widget.setVu(params["u2p"], int(params["saison"]), episode, 1, typM="tv")
for l in listeNonVu:
episode = int(l.split("E")[1])
widget.setVu(params["u2p"], int(params["saison"]), episode, 0, typM="tv")
if params["refresh"] == "1":
xbmc.executebuiltin("Container.Refresh")
def createListeV():
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Listes', 'Quel type de liste ?', nolabel="Films", yeslabel="Series")
if not ret:
media = "movie"
else:
media = "tvshow"
d = dialog.input("Nom de la liste", type=xbmcgui.INPUT_ALPHANUM)
if d:
widget.createListeV(d, media)
showInfoNotification("Création liste lecture: %s ok!!" %d)
def createListeT():
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Listes', 'Quel type de liste ?', nolabel="Films", yeslabel="Series")
if not ret:
media = "movie"
else:
media = "show"
trk = TraktHK()
trk.importListes(media)
def createWidg():
cnx = sqlite3.connect(xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P/bookmark.db'))
cur = cnx.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS listes(
`id` INTEGER PRIMARY KEY,
title TEXT,
sql TEXT,
type TEXT,
UNIQUE (title))
""")
cnx.commit()
dialogTuto = xbmcgui.Dialog()
dialogTuto.textviewer('Tuto', '''1ere fenêtre
tu choisis une liste soit "SERIES ", soit "FILMs"
2eme fenetre
tu choisis le contenu filtré ou pas
filtré => c'est sans les documentaires , les concerts, les spectacles et les animations
3eme fenêtre
FILTRES
cela sert a filtrer la bibliothéque en fonction de critéres
1) Genre(s)
ca te permet de choisir ta liste en fonction du genre
Par exemple tu veux les films horreur, tu selectionnes dans la liste "Horreur"
Tu peux aussi faire du multi-genres exemple: Horreur-Fantastique, même procédure mais tu selectionnes "horreur" et "Fantastique"
Tu valides par "OK
2) Année(s)
tu choisis ta liste avec le critére de la date du médias
Exemple tu veux tous les média de 2021
tu inscris simplement: 2021
si tu veux une liste par plage d'années
Exemple tu veux les medias des années de 2010 à 2019 (une decade)
tu inscris: 2010:2019
et tu valides par "OK"
3) Popularité
c'est un critére de notation, il s'emploie, pour un maximum d'efficacité, avec le critére "Votes" que l'on verra aprés
tu veux tous les medias donc la note est inférieur à 9
tu inscris: <9
tu veux par plage de notation
Exemple tu veux les medias qui ont une note supérieur à 4 et inférieur à 9.5
tu inscris: 4:9.5
On met un . a la place de la ,
4) Votes
c'est le nombre de votant pour obtenir la note "Popularité" vu juste avant
c'est un tandem avec "Popularité"
on va prendre un exemple
Un média peut connu qui recoit 2 votes , 1 à 9.5 et 1 à 10 (c'est plus frequent qu on ne le pense)
Il aura une note de 9.75 qui sera tres tres surfaite....
Pour eviter ce probléme , on indique un nombre de votants minimum
si on a mis en "Popularité" 4:9.5, on ajoute un nombre de votant minimum example de 500, et la on filtre bien les médias peu regardés donc peu notés
2 exemples
#je veux les films notés entre 3 et 9.5 mais aussi les anciens films (tmdb n'existait pas, donc pas forcément été beaucoup noté)
Popularité => 3:9.5
Votes => 200
200 me permet de filtrer les nanard....
#je veux les gros blockbusters, bien notés
Popularité => 6:9.5
Votes => 10000
la tu as les top....
5) Langue
tu choisis ta liste en fonction de la langue d'origine
exemple , les medias japonais, tu choisis "ja", Francais "fr" etc..
Dans "u2pplay-tutos" tu as tout le détail des langues => "lang_Liste.pdf"
Voila pour l'explication des Filtres , tu peux les mettre tous ou une partie c'est à ta convenance, tu peux créér et effacer des listes autant de fois que possible.
Entraines-toi , c'est un outil trés interressant et tu verras une fois compris, c'est trés trés simple
et c'est un belge qui te le dit ....
4éme Fenêtre
ORDRE DE TRI
4 choix
Alpha = par ordre alphabétique de A à Z
Date Added = par ordre d'arrivée ou de modification dans la mediathéque , c'est le dernier entré ou modifié qui sera en 1er
Popularity = par ordre de notation du plus grand vers le plus petit
Year = Par ordre d'année du média du plus récent au plus vieux
on peut mettre plusieurs tris, la priorité et l'ordre insertion des tris
en 1 tu choisis year
en 2 popularity
ordre se fera => tous les medias de 2022 classé par ordre de note ensuite 2021 classé par ordre de note etc ...
5éme fenêtre
Nombre Médias
le nombre de médias que va comporter ta liste
Il faut qu'il soit toujours inférieur à la pagination (500 par default)
ps: si ya des fautes, ca tombe bien ce n'est pas un concours d'orthographe...''')
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Listes', 'Quel type de liste ?', nolabel="Films", yeslabel="Series")
if not ret:
media = "film"
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, (SELECT l.link FROM movieLink as l WHERE l.numId=m.numId) , m.backdrop, m.runtime, m.id \
FROM movie as m "
tx1 = 'Films uniquement? (sans animation, documentaire, concert et spectacle)'
genreMedia = "movie"
else:
media = "serie"
genreMedia = "tv"
tx1 = 'Series uniquement? (sans animation, documentaire)'
sql = "SELECT m.title, m.overview, m.year, m.poster, m.numId, m.genre, m.popu, m.backdrop, m.runtime, m.id FROM tvshow as m "
dictFiltre = {}
tabOrder = []
dictOrder = {"Alpha": "Title ASC", "Date Added": "id DESC", "Popularity": "popu DESC", "Year": "year DESC", "Date Release": "dateRelease DESC", "Votes": "votes DESC"}
dialog = xbmcgui.Dialog()
tc = dialog.yesno('Contenu', tx1)
if tc:
if media == "film":
typContenu = widget.contenuFilm()
else:
typContenu = widget.contenuSerie()
else:
typContenu = ""
notice(typContenu)
ajoutGenre = 1
while ajoutGenre:
dialog = xbmcgui.Dialog()
choix = ["Genre(s)", "Année(s)", "Popularité", "Votes", "Langue"]#, "Resos", "Acteur", "Réalisateur", "Langue"]
selected = dialog.select("Filtres", choix)
if selected != -1:
filtre = choix[selected]
if "Genre" in filtre:
dictFiltre[filtre] = widget.genre(__keyTMDB__, genreMedia)
elif "Ann" in filtre:
dictFiltre[filtre] = widget.year()
elif "Popu" in filtre:
dictFiltre[filtre] = widget.popu()
elif "Votes" in filtre:
dictFiltre[filtre] = widget.votes()
elif "Langue" in filtre:
if genreMedia == "movie":
sqlang = "SELECT DISTINCT lang FROM filmsPub"
else:
sqlang = "SELECT DISTINCT lang FROM seriesPub"
liste = createbdhk.extractMedias(sql=sqlang, unique=1)
dictFiltre[filtre] = widget.langue(sorted(liste))
dialog = xbmcgui.Dialog()
ajout = dialog.yesno('Filtres', 'Ajout Filtre supplémentaire ?')
if not ajout:
while 1:
ajoutGenre = 0
choix = list(dictOrder.keys())
dialog = xbmcgui.Dialog()
selected = dialog.select("Choix ordre de tri (par defaut desc sauf Alpha)", choix)
if selected != -1:
if choix[selected] not in tabOrder:
tabOrder.append(choix[selected])
dialog = xbmcgui.Dialog()
ajout = dialog.yesno('Filtres', 'Ajout ordre supplémentaire ?')
if not ajout:
#if tabOrder[0] == "Alpha":
# sens = "ASC"
#else:
# sens = "DESC"
tri = " ORDER BY {}".format(",".join([dictOrder[x] for x in tabOrder]))
dialog = xbmcgui.Dialog()
d = dialog.numeric(0, 'Nombre Médias')
if int(d) == 0:
d = "40000"
elif int(d) < 25:
d = "25"
limit = " LIMIT %s" %d
sqladd = "WHERE " + typContenu
sqladd += " AND ".join([v for k, v in dictFiltre.items()])
sqladd += tri
sqladd += limit
sql += sqladd
notice(sql)
d = dialog.input("Nom de la liste", type=xbmcgui.INPUT_ALPHANUM)
if d:
if __addon__.getSetting("bookonline") != "false":
site = __addon__.getSetting("bookonline_site")
name = __addon__.getSetting("bookonline_name")
url = "http://{}/requete.php?type=insertlp&name={}&title={}&media={}&sql={}".format(site, name, d, media, quote(sql))
widget.pushSite(url)
cur.execute("REPLACE INTO listes (title, sql, type) VALUES (?, ?, ?)", (d, sql, media, ))
cnx.commit()
showInfoNotification("Création liste: %s ok!!" %d)
break
else:
break
else:
break
cur.close()
cnx.close()
def createRUPTO():
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Repertoire', 'Quel type de Repertoire?', nolabel="Films", yeslabel="Series")
if not ret:
genreMedia = "movie"
else:
genreMedia = "tvshow"
dialog = xbmcgui.Dialog()
nomRep = dialog.input("Nom du repertoire Upto (ex: //FilmNews)", type=xbmcgui.INPUT_ALPHANUM)
if nomRep:
nomListe = dialog.input("Nom Affichage HK ", type=xbmcgui.INPUT_ALPHANUM)
if nomListe:
widget.createRepUpto(nomListe, nomRep, genreMedia)
def createRUPTOP():
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Repertoire', 'Quel type de Repertoire?', nolabel="Films", yeslabel="Series")
if not ret:
genreMedia = "movie"
else:
genreMedia = "tvshow"
dialog = xbmcgui.Dialog()
hashRep = dialog.input("HASH repertoire", type=xbmcgui.INPUT_ALPHANUM)
if hashRep:
numRep = dialog.numeric(0, 'Numéro Repertoire')
if numRep:
nomListe = dialog.input("Nom Affichage HK ", type=xbmcgui.INPUT_ALPHANUM)
if nomListe:
widget.createRepUptoPublic(nomListe, hashRep, numRep, genreMedia)
def createLTMDB():
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Listes', 'Quel type de liste ?', nolabel="Films", yeslabel="Series")
if not ret:
genreMedia = "movie"
else:
genreMedia = "tv"
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Listes', 'Quel type de liste TMDB?', nolabel="Keyword", yeslabel="List")
if not ret:
typList = "Keyword"
else:
typList = "liste"
nomListe = dialog.input("Nom de la liste", type=xbmcgui.INPUT_ALPHANUM)
if nomListe:
if typList == "Keyword":
dialog = xbmcgui.Dialog()
liste = sorted(list(medias.keywords.keys()))
selected = dialog.select("Choix Keywords", liste)
if selected != -1:
d = medias.keywords[liste[selected]]
else:
d = ""
else:
d = dialog.numeric(0, 'Numéro Liste')
if d:
mdb = TMDB(__keyTMDB__)
if typList == "Keyword":
listId = [(nomListe, genreMedia, x) for x in mdb.listKeywords(d, typM=genreMedia)]
else:
listId = [(nomListe, genreMedia, x) for x in mdb.getList(d)]
widget.createListTMDB(listId)
showInfoNotification("Liste TMDB %s créé" %nomListe)
def createListeLP():
dialog = xbmcgui.Dialog()
choix = ["anime", "film", "serie"]
selected = dialog.select("Choix type Repo", choix)
if selected != -1:
typRepo = choix[selected]
dialog = xbmcgui.Dialog()
d = dialog.input("Nom de la liste", type=xbmcgui.INPUT_ALPHANUM)
if d:
sql = "SELECT DISTINCT(numPaste) FROM paste WHERE type='{}'".format(typRepo)
liste = sorted([x[0] for x in extractMedias(sql=sql)], key=lambda s: s.lower())
listeRepo = []
pos = 1
while 1:
dialog = xbmcgui.Dialog()
selected = dialog.select("Choix Num Paste", liste)
if selected != -1:
num = liste[selected]
listeRepo.append((d, num, pos, typRepo))
pos += 1
liste.pop(selected)
dialog = xbmcgui.Dialog()
ajout = dialog.yesno('Pastes', 'Ajouter un paste?')
if not ajout:
break
else:
break
if listeRepo:
widget.insertPaste(listeRepo)
showInfoNotification("Repo Pastes %s créé" %d)
def choixSkin():
try:
repListes = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/skin/")
dictRep = {"Config made in %s" %x: [x] for x in os.listdir(repListes)}
dialogApi = xbmcgui.Dialog()
choixRep = list(dictRep.keys())
selectedApi = dialogApi.select("Choix Contrib", choixRep)
if selectedApi != -1:
xbmcvfs.delete(xbmcvfs.translatePath("special://home/userdata/addon_data/script.skinshortcuts/"))
contrib = dictRep[choixRep[selectedApi]][0]
repConfig = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/skin/%s/" %contrib)
repDesti = xbmcvfs.translatePath("special://home/userdata/addon_data/")
filesConfig = os.listdir(repConfig)
dialog = xbmcgui.Dialog()
repos = dialog.select("Selectionner la config à installer", [x[:-4].replace("_", " ") for x in filesConfig], 0)
if repos != -1:
with zipfile.ZipFile(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/skin/%s/%s" %(contrib, filesConfig[repos])), 'r') as zipObject:
zipObject.extractall(repDesti)
xbmc.sleep(500)
xbmc.executebuiltin('ReloadSkin')
except:
showInfoNotification("Import skin à faire en 1er => import Database => skin ")
def delView(params):
if params["typM"] == "movies":
typM = "movie"
else:
typM = "tvshow2"
if __addon__.getSetting("bookonline") != "false":
listeView = widget.responseSite("http://%s/requete.php?name=%s&type=view&media=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), typM))
for l in listeView:
#notice("id {}, {}".format(l, params["typM"]))
#notice("http://%s/requete.php?name=%s&type=supview&media=%s&numid=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["typM"], l))
widget.pushSite("http://%s/requete.php?name=%s&type=supview&media=%s&numid=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["typM"], l))
time.sleep(0.1)
else:
listeView = list(widget.extractIdInVu(t=typM))
for l in listeView:
widget.supView(params["u2p"], params["typM"])
showInfoNotification("Vider historique ok!!")
def supView(params):
if __addon__.getSetting("bookonline") != "false":
notice("http://%s/requete.php?name=%s&type=supview&media=%s&numid=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["typM"], params["u2p"]))
widget.pushSite("http://%s/requete.php?name=%s&type=supview&media=%s&numid=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["typM"], params["u2p"]))
else:
widget.supView(params["u2p"], params["typM"])
showInfoNotification("Retrait Last/View ok!!")
def choixProfil(menu=0):
cnx = sqlite3.connect(xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P/bookmark.db'))
cur = cnx.cursor()
sql = "SELECT nom, pass FROM users"
cur.execute(sql)
liste = cur.fetchall()
cur.close()
cnx.close()
if not menu:
xbmcplugin.setPluginCategory(__handle__, "Choix Users")
xbmcplugin.setContent(__handle__, 'files')
for choix in liste:
addDirectoryItemLocal(choix[0], isFolder=True, parameters={"action":"actifP", "passwd": choix[1]}, picture="pastebin.png", texte="Profil à activer, mettre en favori pour un accés direct")
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
else:
dialog = xbmcgui.Dialog()
profil = dialog.select("Selectionner le profil à activer", [x[0] for x in liste])
if profil != -1:
actifProfil({"passwd": liste[profil][1]}, menu=0)
def suppProfil():
cnx = sqlite3.connect(xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P/bookmark.db'))
cur = cnx.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS users(
`id` INTEGER PRIMARY KEY,
nom TEXT,
pass TEXT,
UNIQUE (pass))
""")
cnx.commit()
sql = "SELECT nom, pass FROM users"
cur.execute(sql)
liste = cur.fetchall()
dialogApi = xbmcgui.Dialog()
selected = dialogApi.select("Profil à supprimer", [x[0] for x in liste])
if selected != -1:
sql = "DELETE FROM users WHERE nom=? AND pass=?"
cur.execute(sql, (liste[selected]))
cnx.commit()
sql = "DELETE FROM certification WHERE pass=?"
cur.execute(sql, (liste[selected][1],))
cnx.commit()
cur.close()
cnx.close()
def insertBookmarkHK(nom, passwd, certification, sans, debug=1):
cnx = sqlite3.connect(xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P/bookmark.db'))
cur = cnx.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS users(
`id` INTEGER PRIMARY KEY,
nom TEXT,
pass TEXT,
UNIQUE (pass))
""")
cnx.commit()
cur.execute("""CREATE TABLE IF NOT EXISTS certification(
pass TEXT,
certification INTEGER,
sans INTEGER,
UNIQUE (pass))
""")
cnx.commit()
try:
sql = "REPLACE INTO users (nom, pass) VALUES (?, ?)"
cur.execute(sql, (nom, passwd, ))
cnx.commit()
sql = "REPLACE INTO certification (pass, certification, sans) VALUES (?, ?, ?)"
cur.execute(sql, (passwd, certification, sans))
cnx.commit()
"""
params = {
'action': 'actifP',
'passwd': passwd
}
cmd = {
'jsonrpc': '2.0',
'method': 'Favourites.AddFavourite',
'params': {
'title': nom,
"thumbnail": xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/resources/png/profil.png"),
"type":"window",
"window":"videos",
"windowparameter": __url__ + '?' + urlencode(params)
},
'id': '1'
}
xbmc.executeJSONRPC(json.dumps(cmd))
"""
if debug:
showInfoNotification("User: %s créé!!" %nom)
except Exception as e:
#showInfoNotification(str(e))
showInfoNotification("ECHEC création User!!")
cur.close()
cnx.close()
def importConfigHK():
tabProfil = []
dictCertification = {"Familial":1, "10 ans": 12, "12 ans": 14, "16 ans": 17, "18 ans": 25, "10": 12, "12": 14, "16": 17, "18": 25, "familial":1}
dictSans = {"oui": 1, "non": 0, "Oui": 1, "Non": 0}
if __addon__.getSetting("rentry"):
d = __addon__.getSetting("rentry")
numTable, pos, paste = int(d[0]), int(d[1:3]), d[3:]
url = "https://rentry.co/%s/raw" %paste
dictImport = ast.literal_eval(requests.get(url).content.decode())
for nom, login, certification, autre in dictImport["bookmark"]:
#tabProfil.append("%s -- %s -- %s -- %s" %(nom, login, certification, autre))
insertBookmarkHK(nom, login, dictCertification[certification], dictSans[autre], debug=0)
try:
if dictImport["keyUpto"]:
keyUpto = widget.decryptKey(dictImport["keyUpto"], pos, numTable)
#showInfoNotification(keyUpto)
status, validite = testUptobox(keyUpto)
#tabProfil.append("Key Uptobox %s -- %s" % (status, validite))
__addon__.setSetting(id="keyupto", value=keyUpto)
except: pass
try:
if dictImport["keyAlldeb"]:
keyAlldeb = widget.decryptKey(dictImport["keyAlldeb"], pos, numTable)
#showInfoNotification(keyAlldeb)
status, validite = testAlldebrid(keyAlldeb)
#tabProfil.append("Key Alldebrid %s -- %s" % (status, validite))
__addon__.setSetting(id="keyalldebrid", value=keyAlldeb)
except: pass
try:
if dictImport["keyRealdeb"]:
keyRealdeb = widget.decryptKey(dictImport["keyRealdeb"], pos, numTable)
tabProfil.append("Key Realdebrid %s" % keyRealdeb)
__addon__.setSetting(id="keyrealdebrid", value=keyRealdeb)
except: pass
try:
if dictImport["keyTMDB"]:
keyTMDB = widget.decryptKey(dictImport["TMDB"], pos, numTable)
tabProfil.append("Key TMDB %s" % keyTMDB)
__addon__.setSetting(id="keyrealdebrid", value=keyTMDB)
except: pass
try:
if dictImport["client_id"]:
client_id = widget.decryptKey(dictImport["client_id"], pos, numTable)
tabProfil.append("Key Trakt Id %s" % client_id)
__addon__.setSetting(id="clientid", value=client_id)
except: pass
try:
if dictImport["client_secret"]:
client_secret = widget.decryptKey(dictImport["client_secret"], pos, numTable)
tabProfil.append("Key Trakt secret %s" % client_secret)
__addon__.setSetting(id="clientsecret", value=client_secret)
except: pass
try:
if dictImport["iptv"]:
for fournisseur, macs in dictImport["iptv"].items():
fournisseur, nom = fournisseur.split("=")
nbCompte = 0
for mac in macs:
nbCompte += iptv.importCompte(fournisseur.strip(), mac, nom.strip())
tabProfil.append("fournisseur %s\nNombre de comptes importés: %d" %(fournisseur, nbCompte))
except: pass
try:
if dictImport["client_secret"]:
client_secret = widget.decryptKey(dictImport["client_secret"], pos, numTable)
tabProfil.append("Key Trakt secret %s" % client_secret)
__addon__.setSetting(id="clientsecret", value=client_secret)
except: pass
dialog = xbmcgui.Dialog()
dialog.textviewer('Config', "\n".join(tabProfil))
def createPass():
tab = "0123456789AZERTYUIOPMLKJHGFDSQWXVCBN?!azertyuiopmlkjhgfdsqwxcvbn"
nb = random.randint(10, 20)
tx = ""
for i in range(nb):
tx += tab[random.randint(0, (len(tab) - 1))]
return tx
def ajoutProfil(initP=0):
dialog = xbmcgui.Dialog()
d = dialog.input("Mettre votre pseudo:", type=xbmcgui.INPUT_ALPHANUM)
if d:
nom = d
dialog = xbmcgui.Dialog()
d = dialog.input("Mettre ton pass (accés à ton bookmark,\nmettre un pass complexe!!!)", createPass(), type=xbmcgui.INPUT_ALPHANUM)
if d:
passwd = d
dictCertification = {"Familial":1, "10 ans": 12, "12 ans": 14, "16 ans": 17, "18 ans": 25}
choix = list(dictCertification.keys())
selected = dialog.select("Certification", choix)
if selected != -1:
certification = dictCertification[choix[selected]]
dialog = xbmcgui.Dialog()
tc = dialog.yesno('Certification', "Autoriser la lecture des titres sans certification ?")
notice("sans: " + str(tc))
if tc:
sans = 1
else:
sans = 0
insertBookmarkHK(nom, passwd, certification, sans)
if initP:
dialog = xbmcgui.Dialog()
tc = dialog.yesno('Profil', "Veux-tu activer Bookmark en ligne ? (favoris etc...)")
if tc:
__addon__.setSetting(id="bookonline", value="true")
actifProfil({"passwd": passwd}, menu=0)
else:
__addon__.setSetting(id="bookonline", value="false")
def affProfils():
liste = widget.usersBookmark()
xbmcplugin.setPluginCategory(__handle__, "Profils")
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
choix = [(x[0], {"action":"actifP", "passwd": x[1]}, 'special://home/addons/plugin.video.sendtokodiU2P/resources/png/profil.png', "Click pour activer") for x in liste ]
isFolder = True
for ch in sorted(choix):
name, parameters, picture, texte = ch
li = xbmcgui.ListItem(label=name)
updateMinimalInfoTagVideo(li,name,texte)
li.setArt({'thumb': picture,
'icon': addon.getAddonInfo('icon'),
'icon': addon.getAddonInfo('icon'),
'fanart': addon.getAddonInfo('fanart')})
url = sys.argv[0] + '?' + urlencode(parameters)
xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def actifTrakt():
trk = None
if __addon__.getSetting("traktperso") != "false":
if __addon__.getSetting("bookonline") != "false":
userPass = [x[1] for x in widget.usersBookmark() if x[0] == __addon__.getSetting("profiltrakt")]
if userPass and __addon__.getSetting("bookonline_name") == userPass[0]:
trk = TraktHK()
else:
trk = TraktHK()
return trk
def gestionoc(params):
if params["mode"] == "ajout":
widget.gestOC(params["u2p"], "ajout")
else:
widget.gestOC(params["u2p"], "supp")
return
def supFavHK(params):
if __addon__.getSetting("bookonline") != "false":
listeM = widget.responseSite("http://%s/requete.php?name=%s&type=favs&media=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["typM"]))
listeM = [int(x) for x in listeM]
else:
listeM = list(widget.extractFavs(t=media))
params["mode"] = "sup"
for numId in listeM:
params["u2p"] = numId
gestionFavHK(params)
time.sleep(0.1)
showInfoNotification("Vider Favoris HK")
def gestionFavHK(params):
trk = actifTrakt()
if params["mode"] == "ajout":
typAjout = "add"
if __addon__.getSetting("bookonline") != "false":
widget.pushSite("http://%s/requete.php?name=%s&type=infavs&media=%s&numid=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["typM"], params["u2p"]))
else:
widget.ajoutFavs(params["u2p"], params["typM"])
else:
typAjout = "remove"
if __addon__.getSetting("bookonline") != "false":
widget.pushSite("http://%s/requete.php?name=%s&type=supfavs&media=%s&numid=%s" %(__addon__.getSetting("bookonline_site"), __addon__.getSetting("bookonline_name"), params["typM"], params["u2p"]))
else:
widget.supFavs(params["u2p"], params["typM"])
if trk:
if params["typM"] == "movies":
trk.gestionWatchlist(numId=[int(params["u2p"])], typM="movie", mode=typAjout)
else:
trk.gestionWatchlist(numId=[int(params["u2p"])], typM="show", mode=typAjout)
return
def choixRepo():
repReposFilm = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/xml/movie/")
repCatFilm = xbmcvfs.translatePath("special://home/userdata/library/video/movies/")
filesRepo = os.listdir(repReposFilm)
try:
filesCat = os.listdir(repCatFilm)
except:
showInfoNotification("Installer Library Node Editor")
return
dialog = xbmcgui.Dialog()
repos = dialog.multiselect("Selectionner les repos à installer", [x[:-4].replace("_", " ") for x in filesRepo], preselect=[])
if repos:
[xbmcvfs.delete(repCatFilm + x) for x in filesRepo if x in filesCat]
for repo in repos:
shutil.copy(repReposFilm + filesRepo[repo], repCatFilm + filesRepo[repo])
xbmc.sleep(500)
xbmc.executebuiltin('ReloadSkin')
def choixliste():
repListes = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/xsp/")
dictRep = {"Listes intélligentes made in %s" %x: [x] for x in os.listdir(repListes)}
#dictApi = {"Uptobox": ["keyupto", "Key Api Uptobox"], "Alldebrid": ["keyalldebrid", "Key Api Alldebrid"], "RealDebrid": ["keyrealdebrid", "Key Api RealDebrid"]}
dialogApi = xbmcgui.Dialog()
choixRep = list(dictRep.keys())
selectedApi = dialogApi.select("Choix Contrib", choixRep)
if selectedApi != -1:
contrib = dictRep[choixRep[selectedApi]][0]
repReposFilm = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/xsp/%s/" %contrib)
repCatFilm = xbmcvfs.translatePath("special://home/userdata/playlists/video/")
filesRepo = os.listdir(repReposFilm)
filesCat = os.listdir(repCatFilm)
dialog = xbmcgui.Dialog()
repos = dialog.multiselect("Selectionner les listes à installer", ["Toutes les listes"] + [x[:-4].replace("_", " ") for x in filesRepo], preselect=[])
if repos:
[xbmcvfs.delete(repCatFilm + x) for x in filesRepo if x in filesCat]
if 0 in repos:
repos = range(len(filesRepo) - 1)
for repo in repos:
shutil.copy(repReposFilm + filesRepo[repo], repCatFilm + filesRepo[repo])
xbmc.sleep(500)
xbmc.executebuiltin('ReloadSkin')
def testUptobox(key):
url = 'https://%s/api/user/me?token=' %__addon__.getSetting("extupto") + key
headers = {'Accept': 'application/json'}
try:
data = requests.get(url, headers=headers).json()
status = data["message"]
validite = data["data"]["premium_expire"]
except:
status = "out"
validite = ""
return status, validite
def testAlldebrid(key):
url = 'https://api.alldebrid.com/v4/user?agent=myAppName&apikey=' + key
#try:
data = requests.get(url).json()
notice(data)
status = data["status"]
validate = data["data"]["user"]["premiumUntil"]
if int(validate) > 0:
validate = datetime.fromtimestamp(validate)
else:
validate = "Validation expirée"
#except:
# status = "out"
# validate = False
return status, validate
def assistant():
# key debrideurs
a = 0
while a < 5:
ApikeyAlldeb, ApikeyRealdeb, ApikeyUpto = getkeyAlldebrid(), getkeyRealdebrid(), getkeyUpto()
if not ApikeyUpto and not ApikeyRealdeb and not ApikeyAlldeb:
dialog = xbmcgui.Dialog()
resume = dialog.yesno('Config', 'As-tu un numéro de config?')
if resume:
dialog = xbmcgui.Dialog()
d = dialog.input("Num config", type=xbmcgui.INPUT_ALPHANUM)
if d:
__addon__.setSetting("rentry", d)
importConfigHK()
else:
configKeysApi()
else:
keyOk = False
if ApikeyAlldeb:
ok, validite = testAlldebrid(ApikeyAlldeb)
if ok == "success":
keyOk = True
showInfoNotification("Key Alldebrid Ok! expire: %s" %validite)
else:
showInfoNotification("Key Alldebrid out!")
__addon__.setSetting(id="keyalldebrid", value="")
if ApikeyUpto:
ok, validite = testUptobox(ApikeyUpto)
if ok == "Success":
keyOk = True
showInfoNotification("Key Upto ok! expire: %s" %validite)
else:
showInfoNotification("Key Upto out!")
__addon__.setSetting(id="keyupto", value="")
if ApikeyRealdeb:
keyOk = True
if keyOk:
break
a += 1
if keyOk:
if not __addon__.getSetting("numhk"):
dialog = xbmcgui.Dialog()
d = dialog.input("Num DB HK ex:zmdeo", type=xbmcgui.INPUT_ALPHANUM)
if d:
__addon__.setSetting("numhk", d)
else:
return False
importDatabase("autonome")
return True
else:
return False
def vuMovieTrakt(params):
numId = int(params["u2p"])
trk = actifTrakt()
trk.gestionWatchedHistory(numId=[numId], typM="movie", mode="add")
def correctCertif(params):
widget.correctCertif(params["u2p"], params["typM"])
def newUptoPublic(params):
folder = __addon__.getSetting("poissFolder")
hsh = __addon__.getSetting("poissHash")
sql = "SELECT DISTINCT typM FROM repos WHERE repo='poissonnerie' ORDER BY typM"
try:
tabFiles = uptobox.extractMedias(sql=sql, unique=1)
except:
tabFiles = []
xbmcplugin.setPluginCategory(__handle__, "Choix U2Pplay")
xbmcplugin.setContent(__handle__, 'files')
listeChoix = [(x, {"action":"AffCatPoiss", "offset":"0", "typM": x}, "liste.png", "Catégories %s de ma poissonerie !!"%x) for x in tabFiles]
listeChoix.append(("Update ou création", {"action":"insertrepo", "repo":"poissonnerie", "folder": folder, "hash": hsh}, "liste.png", "Création ou update de ma poissonnerie!!"))
listeChoix.append(("Recherche", {"action":"recherepo", "repo":"poissonnerie"}, "liste.png", "Recherche dans ma poissonnerie!!"))
listeChoix.append(("Vider la poissonnerie", {"action":"reinitPoissonnerie"}, "liste.png", "Vider la poissonnerie!!"))
for choix in listeChoix:
addDirectoryItemLocal(choix[0], isFolder=True, parameters=choix[1], picture=choix[2], texte=choix[3])
xbmcplugin.endOfDirectory(handle=__handle__, succeeded=True)
def recherRepo(params):
dialog = xbmcgui.Dialog()
d = dialog.input("Recherche (mini 3 lettres)", type=xbmcgui.INPUT_ALPHANUM, defaultt="")
if len(d) > 2:
sql = "SELECT DISTINCT nom, lien FROM repos WHERE repo='poissonnerie' AND (normalizeTitle(title) LIKE normalizeTitle({}) OR normalizeTitle(nom) LIKE normalizeTitle({}) ) ORDER BY id ASC"\
.format("'%" + str(d).replace("'", "''") + "%'", "'%" + str(d).replace("'", "''") + "%'")
tab = uptobox.extractMedias(sql=sql)
medias = uptobox.ventilationType(tab)
uptobox.affUptoboxNews("movie", [x[1:] for x in medias])
def newUptoPublic2(params):
limit = __addon__.getSetting("nbupto")
offset = int(params["offset"])
typM = params["typM"]
if typM == "film":
sql = "SELECT DISTINCT numId FROM repos WHERE repo='poissonnerie' AND typM='{}' ORDER BY id ASC LIMIT {} OFFSET {}".format(typM, limit, offset)
tab = uptobox.extractMedias(sql=sql, unique=1)
tabFiles = [(x, "*".join(uptobox.extractMedias(sql="SELECT lien FROM repos WHERE repo='poissonnerie' AND typM='{}' AND numId={}".format(typM, x), unique=1))) for x in tab]
medias = uptobox.getFilmsUptoNews(tabFiles)
uptobox.affUptoboxNews("movie", [x[1:] for x in medias], params, cr=1)
elif typM == "divers":
sql = "SELECT DISTINCT nom FROM repos WHERE repo='poissonnerie' AND typM='{}' ORDER BY id ASC LIMIT {} OFFSET {}".format(typM, limit, offset)
tab = uptobox.extractMedias(sql=sql, unique=1)
tabFiles = [(x, "*".join(uptobox.extractMedias(sql="SELECT lien FROM repos WHERE repo='poissonnerie' AND typM='{}' AND nom='{}'".format(typM, x.replace("'", "''")), unique=1))) for x in tab]
medias = [(0, x[0], "", 0, "", 0, "", "", x[1], "", 0, 0) for x in tabFiles]
uptobox.affUptoboxNews("movie", [x[1:] for x in medias], params, cr=1)
elif typM == "serie":
sql = "SELECT DISTINCT numId FROM repos WHERE repo='poissonnerie' AND typM='{}' ORDER BY id ASC LIMIT {} OFFSET {}".format(typM, limit, offset)
tab = uptobox.extractMedias(sql=sql, unique=1)
medias = uptobox.getSeriesUptoNews(tab)
uptobox.affUptoboxNewsSerie("movie", [x[1:] for x in medias], params,)
def affSaisonUptoPoiss(params):
numId = params["u2p"]
sql = "SELECT DISTINCT saison FROM repos WHERE repo='poissonnerie' AND numId={} and typM='serie' ORDER BY saison".format(numId)
tabFiles = uptobox.extractMedias(sql=sql, unique=1)
params["tabsaison"] = "*".join([str(x) for x in tabFiles])
uptobox.loadSaisonsUpto(params)
def visuEpisodesUptoPoiss(params):
numId = params["u2p"]
saison = params["saison"]
sql = "SELECT DISTINCT episode FROM repos WHERE repo='poissonnerie' AND typM='serie' AND saison={} AND numId={} ORDER BY episode".format(saison, numId)
tab = uptobox.extractMedias(sql=sql, unique=1)
tabFiles = [(x, "*".join(uptobox.extractMedias(sql="SELECT lien FROM repos WHERE repo='poissonnerie' AND typM='serie' AND numId={} AND saison={} AND episode={} "\
.format(numId, saison, x), unique=1))) for x in tab]
if "release" in params.keys():
uptobox.affEpisodesUptoPoiss(numId, saison, tabFiles, params["release"])
else:
uptobox.affEpisodesUptoPoissRelease(numId, saison, tabFiles)
def majHkcron():
threading.Thread(name="maj", target=scraperUPTO.majHkNewStart).start()
def intmajbann15():
#init addon
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#Change valeur
addon.setSetting(id="intmaj", value="15")
addon.setSetting(id="delaimaj", value="0")
#recup valeur intmaj
intmaj = addon.getSetting("intmaj")
#recup delaimaj
delaimaj = addon.getSetting("delaimaj")
# si vide
if intmaj:
dialog = xbmcgui.Dialog()
d = dialog.input("Intervalle des Maj en minutes: [0|5|15|30|45|60|120|240]", type=xbmcgui.INPUT_ALPHANUM)
if d:
intmaj = d
addon.setSetting(id="intmaj", value=d.strip())
else:
return
# si delaimaj vide
if delaimaj:
dialog = xbmcgui.Dialog()
d = dialog.input("Délai de la 1ère Maj en minutes: Au démarrage de Kodi", type=xbmcgui.INPUT_ALPHANUM)
if d:
delaimaj = d
addon.setSetting(id="delaimaj", value=d.strip())
else:
return
#notice(intmaj)
#notice(delaimaj)
showInfoNotification(intmaj + " " + delaimaj)
def rskin2():
#init addon
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#Change valeur
addon.setSetting(id="rskin", value="true")
def rskin3():
#init addon
addon = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#Change valeur
addon.setSetting(id="rskin", value="false")
def importBDhk3():
cr = Crypt()
filecode = __addon__.getSetting("numdatabase")
hebergDB = __addon__.getSetting("hebergdb")
if len(filecode) == 12:
link = cr.urlBase + filecode
else:
link = cr.url + "/?" + filecode
#notice(link)
ApikeyAlldeb = getkeyAlldebrid()
ApikeyRealdeb = getkeyRealdebrid()
Apikey1fichier = getkey1fichier()
ApikeyDarkibox = __addon__.getSetting("keydarkibox")
if ApikeyAlldeb:
linkD, ok = cr.resolveLink(link, ApikeyAlldeb)
else:
if hebergDB == "1Fichier":
linkD, ok = cr.resolveLink(link, Apikey1fichier)
else:
dictLiens = cr.debridDarkibox(link.split("/")[-1], ApikeyDarkibox)
linkD = dictLiens["o"][0]
#notice(linkD)
r = requests.get(linkD, timeout=3)
open(os.path.join(__repAddonData__, "combine.bd"), 'wb').write(r.content)
time.sleep(0.2)
loadhk3.joinBlocker()
showInfoNotification("import et fusion BD Ok...")
def gestiondbhk3():
cr = Crypt()
Apikey1fichier = getkey1fichier()
ApikeyDarkibox = __addon__.getSetting("keydarkibox")
hebergDB = __addon__.getSetting("hebergdb")
chemin = xbmcvfs.translatePath("special://home/userdata/addon_data/plugin.video.sendtokodiU2P/")
bd = "mediasNew.bd"
bdSauve = "mediasNewSauve.bd"
dialog = xbmcgui.Dialog()
ret = dialog.yesno('Gestion', 'Opération ?', nolabel="Sauvegarde", yeslabel="Restauration")
if not ret:
ret = dialog.yesno('Sauvegarde', 'type ?', nolabel="Local + 1fichier/darkibox", yeslabel="Local")
if not ret:
#compte
xbmcvfs.copy(os.path.join(chemin, bd), os.path.join(chemin, bdSauve))
if hebergDB == "1Fichier":
url = cr.upload1fichier(os.path.join(chemin, bd), Apikey1fichier)
numDB = url.split("?")[1].split("/")[-1]
else:
numDB = cr.uploadDarkibox(os.path.join(chemin, bd), ApikeyDarkibox)
#notice(numDB)
__addon__.setSetting(id="numdatabase", value=numDB)
showInfoNotification("Sauvegarde Ok...")
else:
xbmcvfs.copy(os.path.join(chemin, bd), os.path.join(chemin, bdSauve))
showInfoNotification("Sauvegarde Ok...")
else:
if os.path.isfile(os.path.join(chemin, bdSauve)):
xbmcvfs.copy(os.path.join(chemin, bdSauve), os.path.join(chemin, bd))
showInfoNotification("Restauration Ok...")
else:
showInfoNotification("Restauration Ko , fait sauvegarde avant...")
def detailmediatheque():
sql = "SELECT COUNT(*) FROM filmsPub"
nbFilms = createbdhk.extractMedias(sql=sql)
sql = "SELECT COUNT(*) FROM seriesPub"
nbSeries = createbdhk.extractMedias(sql=sql)
showInfoNotification("%d type film, %d type serie" %(nbFilms[0][0], nbSeries[0][0]))
def router(paramstring):
params = dict(parse_qsl(paramstring))
dictActions = {
# player
'play': (playMedia, params), 'playHK': (playMediaHK, params), 'playHKEpisode': (playEpisode, params),
# u2p local
'os': (selectOS, ""), 'apiConf': (configKeysApi, ""), 'clearStrms': (makeStrms, 1), 'ePaste': (editPaste, ""), 'groupe': (creaGroupe, ""),
# config kodi
'thmn': (editNbThumbnails, ""), 'resos': (editResos, ''), 'rlk': (reloadSkin, ""),
# database
'bd': (importDatabase, ""), 'bdauto': (importDatabase, "autonome"), 'maj': (majDatabase, ""), 'delDta': (delDATABASE, ""), 'patch': (patchNextUp, ""), 'bdepg': (importDatabase, "epg"),
# listes
'choixrepo': (choixRepo, ""), 'choixliste': (choixliste, ""), 'createL': (createWidg, ""), 'supL': (supWidg, ""), 'createLV': (createListeV, ""), 'createLT': (createListeT, ""),
'suppLV': (widget.suppListeTV, ""), 'suppLT': (widget.suppListeT, ""), "affTraktPerso": (affTrakt, ""), "createLP": (createListeLP, ""), "affPastebin": (affPastebin, ""),
'suppLP': (widget.suppListeLP, ""), "createLTMDB": (createLTMDB, ""), "affTmdb": (affTmdb, ""), "suppLTMDB": (widget.suppLTMDB, ""), "createRUPTO": (createRUPTO, ""),
"createRUPTOP": (createRUPTOP, ""), "suppLUPTO": (widget.suppLUPTO, ""),
# HK
'MenuFilm': (mediasHK, ""), 'MenuDivers': (diversHK, ""), 'MenuSerie': (seriesHK, ""), 'detailM': (detailsMedia, params), 'detailT': (detailsTV, params),
"afficheLiens": (affLiens2, params), "suggest": (loadSimReco2, params), "affActeurs": (affCast2, params), "ba": (getBa, params), "visuEpisodes": (affEpisodes2, params),
"filtres": (filtres, params), 'movies': (ventilationHK, ""), 'supView': (supView, params), 'fav': (gestionFavHK, params),
"visuFenmovie": (fenMovie, params), "genres": (genres, params), "impHK": (importConfigHK, ""), "gestionMedia": (gestionMedia, params), 'MenuTrakt': (traktHKventilation, ""),
"vuMovieTrakt": (vuMovieTrakt, params), "affSearch": (affSearch, ""), "affGlobal": (affGlobal, ""), "affSearchCast": (affSearchCast, ""),
"correctCertif": (correctCertif, params), "affUpto": (affUpto, ""), "loadUpto": (uptobox.loadUpto, params), "loadUptoP": (uptobox.loadUptoP, params), "newUpto": (uptobox.newUpto, params),
"playMediaUptobox": (uptobox.playMediaUptobox, params), "rechercheUpto": (uptobox.searchUpto, params), "loadUptoSerie": (uptobox.loadSeriesUpto, params), "affSaisonUpto": (uptobox.loadSaisonsUpto, params),
"visuEpisodesUpto": (uptobox.affEpisodesUpto, params), "affAlldeb": (affAlldeb, ""), "magnets": (uptobox.magnets, params), "histoupto": (uptobox.getHistoUpto, __database__),
"listeAll": (uptobox.listeAllded, params), "affNewsUpto": (newUptoPublic, params), "addcompte": (addCompteUpto, params), "AffCatPoiss": (newUptoPublic2, params), "affSaisonUptoPoiss": (affSaisonUptoPoiss, params),
"visuEpisodesUptoPoiss": (visuEpisodesUptoPoiss, params), "delcompte": (delcompte, params), "affdetailfilmpoiss": (uptobox.detailFilmPoiss, params), "cryptFolder": (scraperUPTO.cryptFolder, ""),
"affGlobalHK2": (createbdhk.affGlobal, ""), "feninfo": (fenInfo, params),
"delView": (delView, params), "supFavHK": (supFavHK, params),'MenuFilmHK': (createbdhk.mediasHKFilms, params), 'MenuSerieHK': (createbdhk.mediasHKSeries, params),
#strm
'strms': (makeStrms, ""), "strmSelectWidget" : (configureSTRM,""), 'strmsc': (makeStrms, 1),
#profils
'ajoutP': (ajoutProfil, ""), 'choixP': (choixProfil, ""), 'suppP': (suppProfil, ""), 'actifP': (actifProfil, params), 'actifPm': (choixProfil, 1), "affProfils":( affProfils, ""),
"assistant": (assistant, ""),
#audiobook
'MenuAudio':(audioHK, ""),
#skin
'choixskin': (choixSkin, ""),
# repo
"insertrepo": (scraperUPTO.createRepo, params), "recherepo": (recherRepo, params), "gestionMajRepSerie": (scraperUPTO.updateSeriesRepCR, ""), "gestionMajRep": (uptobox.majRepsFilms, ""),
"folderPubDetails": (createbdhk.detailsmenuRepCrypte, params), "folderPub": (uptobox.loadFoldersPub, params),"affFoldercryptDivers": (uptobox.loadFolderCryptDivers, params),
"reinitPoissonnerie": (scraperUPTO.reinitPoissonnerie, ''),
#pastebin
"pastepastebin": (createbdhk.menu, ""), "repopastebin": (createbdhk.createRepo, ""), "affRepoPaste": (createbdhk.affRepo, params), "affSaisonPastebin": (createbdhk.affSaisonPastebin, params),
"visuEpisodesPastebin": (createbdhk.visuEpisodesPastebin, params), "folderPastebin": (scraperUPTO.ajoutFoldercr, params), "menuPastebin": (createbdhk.menuPastebin, ""),
"menuRepCrypte": (createbdhk.menuRepCrypte, ""),
#newHK
"mediasHKFilms": (createbdhk.mediasHKFilms, params), "majHkNew": (scraperUPTO.majHkNew, ''), "genresHK": (createbdhk.genresHK, params), "mediasHKSeries": (createbdhk.mediasHKSeries, params),
"suiteSerieHK": (createbdhk.suiteSerie, params), "suiteSerieHK2": (createbdhk.suiteSerie2, ""), "lockRepHK": (uptobox.lockRep, params),
"tmdbSerie": (createbdhk.tmdbSerie, params), "majhkneww": (scraperUPTO.majHkNew, ''), "findf": (createbdhk.rechercheFilm, params), "findss": (createbdhk.rechercheSerie, params),
"findc": (affSearchCast, params), "mepautostart": (mepAutoStart, ""), "affbaext": (createbdhk.affbaext, ""), "affbacat": (createbdhk.affbacat, params), "playMediabaext": (uptobox.playMediabaext, params),
"affbacattmdb": (createbdhk.affbacattmdb, params), "updateba": (importDatabase, "ba"), "rskin2": (rskin2, ''), "rskin3": (rskin3, ''), "intmajbann15": (intmajbann15, ''), "majhkcron": (majHkcron, ''), "mepautostart2": (mepAutoStart2, ""),
#hk3
"loadhk3": (loadhk3.getLinks, ""), "resetBDhkNew":(loadhk3.resetBdFull, ""), "affSaisonUptofoldercrypt": (uptobox.loadSaisonsHK3, params), "visuEpisodesFolderCrypt": (uptobox.affEpisodesHK3, params),
"loaddbhk3": (importBDhk3, ""), "suiteSerie": (suiteSerie, ""), 'vuNonVu': (gestionVuSaison, params), "gestiondb": (gestiondbhk3, ""), "loadhk3v": (loadhk3.getLinks, 1), "detailmediatheque": (detailmediatheque, ""),
}
if vIPTV:
dictActionsIPTV = { "iptvLoad": (iptv.menu, ""), "affChaine": (iptv.affChaines, params), "playMediaIptv": (iptv.playMedia, params), "ajoutIPTV": (iptv.ajoutIPTV, ""), "loadF": (iptv.menuFournisseur, params),
"activemac": (iptv.activeMac, params), "gestfourn": (iptv.gestfourn, params), "lock": (iptv.lock, params), "affepgChann": (iptv.affepgChann, params), "mapepg": (iptv.mapEpg, params),
"gestFuseau": (iptv.gestFuseau, params), "getVod": (iptv.getVodSeries, params), "affVod": (iptv.affVod, params), "gestfournVod": (iptv.gestfournVod, params), "affEpisodes": (iptv.affEpisodes, params),
"retireriptv": (iptv.retireriptv, ""), "delDB": (iptv.removeDB, ""), "IPTVbank":(iptv.IPTVbank, ""), "addFavIptv": (iptv.addFavIptv, params), "IPTVfav": (iptv.IPTVfav, ""),
"iptvsupfav": (iptv.supfavIptv, params), "iptvdepfav": (iptv.iptvdepfav, params), "iptvreplay": (iptv.replay, params), "loadFX": (iptv.loadX, params), "affChainex": (iptv.affChainesx, params),
"fepgx": (iptv.forceMajEpgX, ""), "menus": (iptv.menuStalker, ""), "menux": (iptv.menuXtream, ""), "loadFTV": (iptv.load, params), "searchVod": (iptv.searchVod, params), "searchVodf": (iptv.searchVod2, params),
"loadXitv": (iptv.loadXitv, params), "loadXvod": (iptv.loadXvod, params), "affVodx": (iptv.affVodx, params)}
dictActions.update(dictActionsIPTV)
notice(len(dictActions))
if params:
fn = params['action']
if fn in dictActions.keys():
argv = dictActions[fn][1]
if argv:
dictActions[fn][0](argv)
else:
dictActions[fn][0]()
elif fn == 'setting':
xbmcaddon.Addon().openSettings()
else:
raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
else:
menuPbi()
if __name__ == '__main__':
nameExploit = sys.platform
__addon__ = xbmcaddon.Addon("plugin.video.sendtokodiU2P")
#notice(nameExploit)
# Get the plugin url in plugin:// notation.
__url__ = sys.argv[0]
# Get the plugin handle as an integer number.
__handle__ = int(sys.argv[1])
# database video kodi
bdKodis = ["MyVideos119.db", "MyVideos121.db", "MyVideos122.db", "MyVideos123.db"]
for bdKodi in bdKodis:
if os.path.isfile(xbmcvfs.translatePath("special://home/userdata/Database/%s" %bdKodi)):
__database__ = xbmcvfs.translatePath("special://home/userdata/Database/%s" %bdKodi)
#break
#Deprecated xbmc.translatePath. Moved to xbmcvfs.translatePath
__repAddon__ = xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/")
__repAddonData__ = xbmcvfs.translatePath("special://home/userdata/addon_data/plugin.video.sendtokodiU2P")
__keyTMDB__ = getkeyTMDB()
__params__ = dict(parse_qsl(sys.argv[2][1:]))
#
# assistant
"""
if __addon__.getSetting("actifhk") != "false":
if not os.path.exists(xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P')):
os.makedirs(xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.sendtokodiU2P'))
plusProfil = False
if not os.path.isfile(xbmcvfs.translatePath("special://home/addons/plugin.video.sendtokodiU2P/medias.bd")):
widget.initBookmark()
if assistant():
plusProfil = True
else:
sys.exit()
if plusProfil:
liste = widget.usersBookmark()
if not liste:
ajoutProfil(initP=1)
xbmcgui.Dialog().ok("Configuration" , "Config Ok !!\nUn petit merci aux contributeurs est toujours le bienvenu\nBon film....")
"""
if not os.path.isfile(__repAddon__ + "service.txt"):
with open(__repAddon__ + "service.txt", "w") as f:
mepAutoStart2()
createFav()
#notice(pyVersion)
#notice(pyVersionM)
#xbmc.executebuiltin("InstallFromZip")
#notice(sys.version_info)
#notice(__url__)
#notice(__handle__)
router(sys.argv[2][1:])
#Setting most video properties through ListItem.setInfo() is deprecated and might be removed in future Kodi versions. Please use the respective setter in InfoTagVideo. | osmoze06/repo.weebox | repo/plugin.video.sendtokodiU2P/service.py | service.py | py | 291,195 | python | en | code | 2 | github-code | 6 |
20827068322 | """
----------------
| [bini-tek] \\
----------------
By: [bini-tek]\\
Email: binitek.baltimore@gmail.com
Discord: Home of bini-tek (https://discord.gg/4GqDrH)
----------------
Version #: 001.
DATE: Jan/-3-2021.
----------------
---------------
| EXPLANATION |
---------------
The Nubian Dictionary.
----------------------
This program is based on the Lexicography work of Mr. Yousseff Sumbagh.
An interactive/digitized version of his Nubian Dictionary book.
This is the very first iteration of this project, hopefully it will be catalyst to more improved versions.
----------------
| CONTRIBUTORS |
----------------
Youssef Sumbagh: Lexicographer.
Asher Noor: coder.
50DD: coder.
"""
'''-------
IMPORTS
----------'''
from time import sleep
import re
'''-------
DEFINING THE FUNCTIONS
----------'''
'''/////////////////////////////////////////////////////////'''
"**************************"
"--- Main Menu Function ---"
"**************************"
def nd_mainMenu():
print("\n\n---------------------"
"\nThe Nubian Dictionary"
"\n---------------------"
"\nDigitized By: [bini-tek]\\\\"
"\nBased on the work of: Youssef Sumbagh"
"\nVersion #: 001"
"\n--------------\n"
"\nMain Menu"
"\n----------"
"\n[1]: Word Search"
"\n[2]: Days of The Week"
"\n[3]: Numbers"
"\n[4]: Credits"
"\n[5]: Exit")
# User Input w/ Validation
while True:
choice = input("\nPlease enter your option: ")
try:
choice = int(choice) # <-- to make sure an int was entered
except:
print("Please enter one of the above numeric choices.") # <-- if a letter or blank was entered
continue
if choice == 1:
TheDictionary() # <-- Word Search: The Dictionary Function
elif choice == 2:
nd_days() # <-- Days of The Week: The Days Function
elif choice == 3:
nd_numbers() # <-- Numbers: The Numbers function
elif choice == 4:
nd_credits() # <-- Credits: The Credits function
elif choice > 5:
print("Please choose between 1- 5: ") # <-- User choice validation
else:
outro()
"-- The End of Main Menu Function --"
'''/////////////////////////////////////////////////////////'''
"**************************"
"--- Mini Menu Function ---"
"**************************"
#-- This is a small menu appearing in some of the smaller functions.
def miniMenu():
# -- the menu options // back to menu // exit
print("\nMenu:"
"\n1- Main Menu"
"\n2- Exit")
# User Input w/ Validation
while True:
choice = input("\nPlease enter your option: ")
try:
choice = int(choice) # <-- to make sure an int was entered
except:
print("Please enter one of the above numeric choices.") # <-- if a letter was entered
continue
if choice == 1:
nd_mainMenu() # <-- The Main Menu function
elif choice > 3:
print("Please choose 1 or 2")
else:
outro() # <-- The Outro function
"-- The End of Mini Menu Function --"
'''/////////////////////////////////////////////////////////'''
"***********************************************"
"--- [ 1 ] : Word Search Dictionary Section ---"
"***********************************************"
# -- The Line Print Function
# If a single letter is entered, it will print out all words starting with that letter
def TheLinePrint(eng_word):
# Read the ND1 text file
# ----- To open the text file
open_text = open("nd-wordsearch.txt", "r")
# ----- To read the text file
read_text = open_text.readlines() # open_text.read()
# ---- test print
# print(read_text)
# Search for the word entered & Print that line
for line in read_text:
if re.match(eng_word, line):
print(line) # the .strip() will take out the \n between the lines.
# --------- End of The Line Print Function --------- #
# -- Creating the Dictionary from the nd-wordsearch text file.
def TheDictionary():
print("\n\t\t\t---------------"
"\n\t\t\t| Word Search | "
"\n\t\t\t---------------\n")
# -- Opening the File
f = open('nd-wordsearch.txt', 'r')
# -- Creating the empty dictionary
d = {}
# -- Populating the dictionary list from the nd-wordsearch text file.
for line in f:
x = line.split(" ") # // Split the words at the spaces
a = x[0] # // the KEY before the space
b = x[1], x[2] # // the VALUE after the space
c = len(b) # // to subtract the '\n' at the end
b = b[0:c] # // the new value starts at '0' and ends with 'c' calculation
d[a] = b # // combines the KEY to the VALUE
'# -- User Input / the English word'
eng_word = str(input("\nSearch For: ").lower())
'# -- To validate the User Input is a string.'
if eng_word.isalpha(): # -- if the input is a string
# -- The Search section
if len(eng_word) <= 1:
TheLinePrint(str(eng_word))
elif eng_word not in d: # -- if the word is not in the dictionary
print("ERROR: This is not a word, please try again \n")
TheDictionary() # -- recalling the function to get new User Input
else:
# -- Print from the dictionary list
print("The Two Dialects:"
"\n(K-D) Kinzeeya - Dungulaweea."
"\n(F-M) Fadeega - Mahaseeya.\n\n"
"\t(K-D) | (F-M) \n ", d[eng_word])
else: # -- if the input is NOT a string
print("ERROR: No numbers or special characters, please try again \n")
TheDictionary() # -- recalling the function to get new User Input
#-- To check if user wants to search another word
another_word = str(input("\nWould you like to search for another word? y/n: ").lower())
#-- User Validation
if another_word.isalpha():
#-- if YES
if another_word == 'y':
TheDictionary()
else:
nd_mainMenu() #-- calling the Main Menu function
else:
print("That was not an option"
"\nGoing back to the Main Menu, please wait.")
sleep(3)
nd_mainMenu() #-- calling the Main Menu function
# --------- End of The Dictionary Function --------- #
"-- The End of Word Seach Dictionary Section --"
'''/////////////////////////////////////////////////////////'''
"*****************************************"
"--- [ 2 ] : Days of The Week Section ---"
"*****************************************"
def nd_days():
#-- open & read the text file
f = open("nd-days.txt", "r")
#-- display the text file line by line
for x in f:
print(x.rstrip())
#-- close the file
f.close()
#-- Calling the mini menu
miniMenu()
"-- The End of Days of The Week Section --"
'''/////////////////////////////////////////////////////////'''
"*****************************************"
"--- [ 3 ] : Numbers Section ---"
"*****************************************"
def nd_numbers():
#-- open & read the text file
f = open("nd-numbers.txt", "r")
#-- display the text file line by line
for x in f:
print(x.rstrip())
#-- close the file
f.close()
# -- Calling the mini menu
miniMenu()
"-- The End of Numbers Section --"
'''/////////////////////////////////////////////////////////'''
"*****************************************"
"--- [ 4 ] : Credits Section ---"
"*****************************************"
def nd_credits():
print("\n-----------------------------------------"
"\nCredits for The Nubian Dictionary. "
"\n-----------------------------------------"
"\nLexicographer: Youssef Sumbagh (Sabbaj)."
"\nCoder: Asher Noor."
"\nCoder: 50DD."
"\nBrought to you by: [bini-tek]\\\\"
"\nEmail: binitek.baltimore@gmail.com"
"\nDiscord: Home of bini-tek (https://discord.gg/4GqDrH)."
"\n----------------------------------------")
# -- Calling the mini menu
miniMenu()
"-- The End of the Credits Section --"
'''/////////////////////////////////////////////////////////'''
"**************************"
"--- Outro Function ---"
"**************************"
def outro():
print("\nExiting Program, please wait.")
sleep(2)
print("\n-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-"
"\nBrought to you by: [bini-tek]\\\\"
"\nEmail: binitek.baltimore@gmail.com"
"\nDiscord: Home of bini-tek (https://discord.gg/4GqDrH)"
"\n-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-")
sleep(5)
exit()
'''-------
CALLING OF THE FUNCTIONS
----------'''
# Calling Main Menu - It calls all the others.
nd_mainMenu()
'''-------
END OF PROGRAM
----------''' | bini-tek/nubian-dictionary-v001 | nd_final.py | nd_final.py | py | 9,571 | python | en | code | 2 | github-code | 6 |
39674044871 | from kucoin.client import Trade
from kucoin.client import Market
import pandas as pd
from time import sleep
api_key = '60491b8da682810006e2f600'
api_secret = 'a79226df-55ce-43d0-b771-20746e338b67'
api_passphrase = 'algotrading101'
m_client = Market(url='https://api.kucoin.com')
client = Trade(api_key, api_secret, api_passphrase, is_sandbox=True)
while True:
try:
btc_old = m_client.get_ticker('BTC-USDT')
print('The price of BTC at {} is:'.format(pd.Timestamp.now()), btc_old['price'])
except Exception as e:
print(f'Error obtaining BTC data: {e}')
sleep(300)
try:
btc_new = m_client.get_ticker('BTC-USDT')
print('The price of BTC at {} is:'.format(pd.Timestamp.now()), btc_new['price'])
except Exception as e:
print(f'Error obtaining BTC data: {e}')
percent = (((float(btc_new['bestAsk']) - float(btc_old['bestAsk'])) * 100) / float(btc_old['bestAsk']))
if percent < 5:
print('The trade requirement was not satisfied. The percentage move is at ',percent)
continue
elif percent >= 5:
try:
order = client.create_market_order('ETH-USDT', 'buy', size='5')
print()
except Exception as e:
print(f'Error placing order: {e}')
sleep(2)
try:
check = client.get_order_details(orderId=order['orderId'])
print(check)
except Exception as e:
print(f'Error while checking order status: {e}')
if check['isActive'] == True:
print ('Order placed at {}'.format(pd.Timestamp.now()))
break
else:
print('Order was canceled {}'.format(pd.Timestamp.now()))
break
| briansegs/Kucoin-api-example- | example-2.py | example-2.py | py | 1,725 | python | en | code | 0 | github-code | 6 |
71452823867 | import os
import pandas as pd
import numpy as np
from keras.models import load_model
sample_submission = pd.read_csv('submissions/sample_submission.csv')
print(sample_submission['Class'])
band = ''
def preproc(X_all):
X_all[X_all == -np.inf] = -10
X_all[X_all > 1000] = 1000
X_all = np.swapaxes(X_all, 1, 2)
X_all = X_all.reshape(X_all.shape[0],X_all.shape[1],X_all.shape[2]*X_all.shape[3])
return X_all
model1 = load_model('models/LSTMSpectro/P1/test8-31-0.821.h5')
#model1 = load_model('models/CNNSpectro/P1/test1-18-0.877.h5')
X_s_1 = np.load('data/ffts/'+band+'test_1_new/X_new_s.npy')
X_s_1 = preproc(X_s_1)
preds1 = model1.predict_proba(X_s_1)[:,1]
print(preds1)
print(preds1.shape)
del X_s_1
del model1
model2 = load_model('models/LSTMSpectro/P2/test8-22-0.798.h5')
#model2 = load_model('models/CNNSpectro/P2/test1-19-0.747.h5')
X_s_2 = np.load('data/ffts/'+band+'test_2_new/X_new_s.npy')
X_s_2 = preproc(X_s_2)
preds2 = model2.predict_proba(X_s_2)[:,1]
print(preds2)
print(preds2.shape)
del X_s_2
del model2
model3 = load_model('models/LSTMSpectro/P3/test2.h5')
#model3 = load_model('models/CNNSpectro/P3/test1-27-0.658.h5')
X_s_3 = np.load('data/ffts/'+band+'test_3_new/X_new_s.npy')
X_s_3 = preproc(X_s_3)
preds3 = model3.predict_proba(X_s_3)[:,1]
print(preds3)
print(preds3.shape)
del X_s_3
del model3
preds_submission = np.concatenate((preds1,preds2,preds3))
print(preds_submission.shape)
sample_submission['Class'] = preds_submission
sample_submission.to_csv('submissions/LSTMSpectro882.csv', index=False)
#sample_submission.to_csv('submissions/CNNSpectro111.csv', index=False)
| Anmol6/kaggle-seizure-competition | make_sub.py | make_sub.py | py | 1,618 | python | en | code | 0 | github-code | 6 |
27374563291 | """Terrascript module example based on https://registry.terraform.io/modules/terraform-aws-modules/ec2-instance/aws/"""
import terrascript
import terrascript.provider
config = terrascript.Terrascript()
# AWS provider
config += terrascript.provider.aws(region="us-east-1")
# AWS EC2 module
config += terrascript.Module(
"ec2_cluster",
source="terraform-aws-modules/ec2-instance/aws",
version="~> 2.0",
name="my-cluster",
instance_count=5,
ami="ami-ebd02392",
instance_type="t2.micro",
key_name="user1",
monitoring=True,
vpc_security_group_ids=["sg-12345678"],
subnet_id="subnet-eddcdzz4",
)
| starhawking/python-terrascript | docs/tutorials/module1.py | module1.py | py | 638 | python | en | code | 511 | github-code | 6 |
74907691708 | # 2-D plot function for SODA TEMPERATURE
# YUE WANG
# Nov. 12st 2013
import numpy as np
import netCDF4
from mpl_toolkits.basemap import Basemap,cm
import matplotlib.pyplot as plt
def soda_plot(url,variable,llat, ulat, llon, rlon):
nc = netCDF4.Dataset(url)
var = nc.variables[variable][0,0,:,:]
lon = nc.variables['LON'][:]
lat = nc.variables['LAT'][:]
# setting up data into basemap with given projection
lons, lats = np.meshgrid(lon, lat)
fig = plt.figure(figsize=(16,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8])
m = Basemap(llcrnrlat=llat,urcrnrlat=ulat,\
llcrnrlon=llon,urcrnrlon=rlon,\
projection='mill',resolution = 'h',ax=ax)
x,y = m(lons, lats)
# drawing the map
m.fillcontinents(color='gray',lake_color='gray')
m.drawcoastlines(linewidth = 0.4)
m.drawparallels(np.arange(-90.,90.,15.), labels =[1,0,0,1],fontsize=10)
m.drawmeridians(np.arange(-180.,181.,40.),labels =[0,1,0,1],fontsize=10)
m.drawmapboundary()
# plotting data on the map
plt.contourf(x,y,var,cmap=cm.sstanom)
cb = plt.colorbar(orientation='horizontal')
cb.set_label(r'Sea Surface Temperature (deg C) Jan 1998',fontsize=14,style='italic')
plt.show()
#plt.savefig('SST_globeplot_Hw3.png')
'''url = 'http://sodaserver.tamu.edu:80/opendap/TEMP/SODA_2.3.1_01-01_python.cdf'
variable = 'TEMP'
#nino 3.4 region
llat = -5.
####Q: range of latitude: 0-360, do we need a loop? transfore the latidue
ulat = 5.
llon = -170.
rlon = -120.''' | yueewang/Python_Digitizer | soda_plot_function_2.py | soda_plot_function_2.py | py | 1,539 | python | en | code | 0 | github-code | 6 |
20844889575 | import tensorflow.compat.v1 as tf
import numpy as np
class Detector:
def __init__(self, model_path, gpu_memory_fraction=0.25, visible_device_list='0'):
"""
Arguments:
model_path: a string, path to a pb file.
gpu_memory_fraction: a float number.
visible_device_list: a string.
"""
with tf.gfile.GFile(model_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
graph = tf.Graph()
with graph.as_default():
tf.import_graph_def(graph_def, name='import')
self.input_image = graph.get_tensor_by_name('import/images:0')
output_names = [
'boxes', 'scores', 'num_boxes',
'keypoint_heatmaps', 'segmentation_masks',
'keypoint_scores', 'keypoint_positions'
]
self.output_ops = {n: graph.get_tensor_by_name(f'import/{n}:0') for n in output_names}
gpu_options = tf.GPUOptions(
per_process_gpu_memory_fraction=gpu_memory_fraction,
visible_device_list=visible_device_list
)
config_proto = tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)
self.sess = tf.Session(graph=graph, config=config_proto)
def __call__(self, image, score_threshold=0.05):
"""
Arguments:
image: a numpy uint8 array with shape [height, width, 3],
that represents a RGB image.
score_threshold: a float number.
"""
h, w, _ = image.shape
assert h % 128 == 0 and w % 128 == 0
feed_dict = {self.input_image: np.expand_dims(image, 0)}
outputs = self.sess.run(self.output_ops, feed_dict)
outputs.update({
n: v[0] for n, v in outputs.items()
if n not in ['keypoint_scores', 'keypoint_positions']
})
n = outputs['num_boxes']
to_keep = outputs['scores'][:n] > score_threshold
outputs['boxes'] = outputs['boxes'][:n][to_keep]
outputs['scores'] = outputs['scores'][:n][to_keep]
outputs['keypoint_positions'] = outputs['keypoint_positions'][to_keep]
outputs['keypoint_scores'] = outputs['keypoint_scores'][to_keep]
return outputs
| TropComplique/MultiPoseNet | inference/detector.py | detector.py | py | 2,270 | python | en | code | 9 | github-code | 6 |
4691442147 | from attrdict import AttrDict
from flask import Flask, request, jsonify, make_response
from semantic_selector.model.one_to_one import NNFullyConnectedModel
from semantic_selector.adapter.one_to_one import JSONInferenceAdapter
app = Flask(__name__)
model = None
@app.before_first_request
def startup():
global model
print("initializing model...")
model = NNFullyConnectedModel()
model.load()
@app.route("/api/inference", methods=['POST'])
def inference():
global model
if request.headers['Content-Type'] != 'application/json':
return make_response("Content-Type must be application/json", 400)
if "html" not in request.json.keys():
err_message = 'request body json must contain "html" attributes'
return make_response(err_message, 400)
target_tag = AttrDict({'html': request.json["html"]})
options = {'record': target_tag, 'dictionary': model.dictionary}
adapter = JSONInferenceAdapter(options)
estimated_topic = model.inference_html(adapter)
res = {"topic": estimated_topic}
return jsonify(res)
| cuhavp/semantic_selector | projects/bin/api.py | api.py | py | 1,079 | python | en | code | null | github-code | 6 |
16116517818 | import tools as t
import json
import requests
def get_wikipedia(title):
base_url = "https://de.wikipedia.org/w/api.php"
params = {
"action": "query",
"format": "json",
"prop": "extracts",
"exintro": True,
"titles": title
}
response = requests.get(base_url, params=params)
data = response.json()
if "query" in data:
pages = data["query"]["pages"]
for page_id, page_info in pages.items():
if page_id != "-1":
article_text = page_info["extract"]
t.his(title=title)
return t.clean_html(article_text)
else:
return None
return None
def get_moviedb(choice, keyword):
lan = t.config_var("moviedb", "lan")
print(lan)
choice = choice.lower()
print(choice)
keyword = keyword.replace(" ", "%20")
if keyword == "actor":
keyword = "person"
print(keyword)
url = f"https://api.themoviedb.org/3/search/{choice}?query={keyword}&include_adult=false&language={lan}&page=1"
print(url)
auth = frozenset(t.auth("AUTH"))
print(auth)
headers = {
"accept": "application/json",
"Authorization": auth
}
print(headers)
response = requests.get(url, headers=headers)
data = json.loads(response.text)
print(data)
get_moviedb("movie", "snowden")
| Paul-Tru/PyAssistant2 | api.py | api.py | py | 1,369 | python | en | code | 0 | github-code | 6 |
32019692905 | from subprocess import run
from pathlib import Path
import os
from rich.console import Console
from rich.markup import escape
from builtins import print as builtin_print
import shutil
if __name__ == "__main__":
console = Console(emoji=False)
def print(msg):
console.print(msg)
here = Path(__file__).parent.absolute()
for subitem in here.iterdir():
if not subitem.is_file() and "-" in subitem.name:
print(f"Building {subitem.name}")
sub_projects = [Path(i).parent for i in subitem.rglob("Makefile")]
for project in sub_projects:
print(f"\t- Building {project.name}")
result = run("make clean && make -r -j --output-sync=target --no-print-directory", cwd=project, shell=True, capture_output=True)
if result.returncode != 0:
print("[red]Failed![/red]\n")
print(escape(result.stderr.decode()))
exit(result.returncode)
print("Packaging...")
build_folder = Path(here) / "build"
for project in sub_projects:
dest = build_folder / Path(f"{subitem.name}/{project.name}/build")
dest.mkdir(exist_ok=True, parents=True)
for i in (project / "build").iterdir():
if i.is_file() and i.suffix == ".bin" and "_app" not in i.name:
print(f"Copying {i} to {dest}")
shutil.copy(i, dest)
if (project / "run.sh").exists():
dest = build_folder / Path(f"{subitem.name}/{project.name}")
shutil.copy(project / "run.sh", dest) | Analog-Devices-MSDK/refdes | .github/workflows/scripts/build.py | build.py | py | 1,733 | python | en | code | 14 | github-code | 6 |
26529440503 | from random import randint, seed
# returns best score and the best move of the board
#depth is a terminating condition
def alphabeta(newGame, game, alpha, beta,depth):
emp = newGame.getEmp()
if newGame.checkForWinner() == game.curPlayer:
return -1, 100
elif newGame.checkForWinner() == game.curPlayer % 2 + 1:
return -1, -100
elif not emp:
return -1, -5
bestMove = None
#if max is player
if newGame.curPlayer == game.curPlayer:
bestScore = -10000
for i in emp:
newGame.move(i)
#next level for searching the best move
newGame.curPlayer = newGame.curPlayer % 2 + 1
#terminates when depth=0
if depth!=0:
#alphabeta is called in the next level
result = alphabeta(newGame, game, alpha, beta,depth-1)
newGame.clearMove(i)
newGame.curPlayer = newGame.curPlayer % 2 + 1
#best move and best score is calculated for max player
if result[1] > bestScore:
bestScore = result[1]
bestMove = i
# alpha beta pruning
#alpha when max is the player
alpha = max(bestScore, alpha)
if beta <= alpha:
break
else:
#if min is the player
bestScore = 10000
for i in emp:
newGame.move(i)
#next level for searching the best move
newGame.curPlayer = newGame.curPlayer % 2 + 1
#terminates when depth=0
if depth!=0 :
#alphabeta is called in the next level
result = alphabeta(newGame, game, alpha, beta,depth-1)
newGame.clearMove(i)
newGame.curPlayer = newGame.curPlayer % 2 + 1
#best move and best score is calculated for min player
if result[1] < bestScore:
bestScore = result[1]
bestMove = i
# alpha beta pruning
#beta when min is the player
beta = min(bestScore, beta)
if beta <= alpha:
break
return bestMove, bestScore
#it is called when player selects alphabeta player
def playerAlphaBeta(game,depth):
newGame = game.getCopy()
#if alphabeta player starts first, choose any box randomly to minimize the time
if len(game.getEmp()) == 9:
seed()
myMove = [randint(0, 8), None]
else:
myMove = alphabeta(newGame, game, -float('inf'), float('inf'),depth)
#print(myMove[0]) is minimax move
#print(myMove[1]) is minimax score
#return minimax move
return myMove[0]
| rashigupta37/tic_tac_toe | playerAlphaBeta.py | playerAlphaBeta.py | py | 2,814 | python | en | code | 0 | github-code | 6 |
8939054368 | from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Map-related
url(r'^/?$', direct_to_template, {'template': 'pom/index.html'}),
url(r'^refresh/?$', 'pom.views.refresh_cache'),
url(r'^filtered/bldgs/?$', 'pom.views.get_filtered_bldgs'),
url(r'^filtered/data/bldg/(?P<bldg_code>\S+)/?$', 'pom.views.get_filtered_data_bldg'),
url(r'^filtered/data/all/?$', 'pom.views.get_filtered_data_all'),
url(r'^widget/search/resp/?$', 'pom.views.widget_search_resp'),
url(r'^widget/locations/setup/?$', 'pom.views.widget_locations_setup'),
(r'^login/?$', 'django_cas.views.login'),
(r'^logout/?$', 'django_cas.views.logout'),
#Admin
url(r'^admin/?$', 'django_cas.views.login', kwargs={'next_page': '/djadmin/'}),
(r'^djadmin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
| epkugelmass/USG-srv-dev | tigerapps/pom/urls.py | urls.py | py | 1,045 | python | en | code | null | github-code | 6 |
18015924174 | import cv2
import sys
import PyQt5.QtCore as QtCore
from PyQt5.QtCore import QTimer # Import QTimer from PyQt5
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFileDialog, QInputDialog
from PyQt5.QtGui import QImage, QPixmap
class TrackingApp(QWidget):
def __init__(self):
super().__init__()
self.tracker_type = ""
self.capture = None
self.tracker = None
self.timer = QTimer(self)
self.initUI()
def initUI(self):
self.setWindowTitle('Object Tracking App')
self.setGeometry(100, 100, 800, 600)
self.video_label = QLabel(self)
self.video_label.setAlignment(QtCore.Qt.AlignCenter)
self.select_button = QPushButton('Select Video', self)
self.select_button.clicked.connect(self.openVideo)
self.start_button = QPushButton('Start Tracking', self)
self.start_button.clicked.connect(self.startTracking)
self.layout = QVBoxLayout()
self.layout.addWidget(self.video_label)
self.layout.addWidget(self.select_button)
self.layout.addWidget(self.start_button)
self.setLayout(self.layout)
def openVideo(self):
options = QFileDialog.Options()
options |= QFileDialog.ReadOnly
video_path, _ = QFileDialog.getOpenFileName(self, 'Open Video File', '', 'Video Files (*.mp4 *.avi);;All Files (*)', options=options)
if video_path:
self.capture = cv2.VideoCapture(video_path)
def startTracking(self):
if self.capture is None:
return
self.tracker_type, ok = QInputDialog.getItem(self, 'Select Tracker Type', 'Choose Tracker Type:', ['1. MIL', '2. KCF', '3. CSRT'])
if ok:
if self.tracker_type == '1. MIL':
self.tracker = cv2.TrackerMIL_create()
elif self.tracker_type == '2. KCF':
self.tracker = cv2.TrackerKCF_create()
elif self.tracker_type == '3. CSRT':
self.tracker = cv2.TrackerCSRT_create()
else:
print("Invalid choice")
return
ret, frame = self.capture.read()
bbox = cv2.selectROI("Select Object to Track", frame)
self.tracker.init(frame, bbox)
self.timer.timeout.connect(self.trackObject)
self.timer.start(30) # Update every 30 milliseconds
def trackObject(self):
ret, frame = self.capture.read()
if not ret:
self.timer.stop()
return
success, bbox = self.tracker.update(frame)
if success:
(x, y, w, h) = tuple(map(int, bbox))
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Convert the OpenCV image to a QImage for displaying in the GUI
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
height, width, channel = frame_rgb.shape
bytes_per_line = 3 * width
q_img = QImage(frame_rgb.data, width, height, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(q_img)
self.video_label.setPixmap(pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
trackingApp = TrackingApp()
trackingApp.show()
sys.exit(app.exec_())
| kio7/smart_tech | Submission 2/Task_6/trackingGUI.py | trackingGUI.py | py | 3,282 | python | en | code | 0 | github-code | 6 |
19933423422 | import requests, zipfile, os, json, sqlite3
def get_manifest():
manifest_url = 'http://www.bungie.net/Platform/Destiny2/Manifest/'
print("Downloading Manifest from http://www.bungie.net/Platform/Destiny2/Manifest/...")
r = requests.get(manifest_url)
manifest = r.json()
mani_url = 'http://www.bungie.net'+manifest['Response']['mobileWorldContentPaths']['en']
#Download the file, write it to 'MANZIP'
r = requests.get(mani_url)
with open("MANZIP", "wb") as zip:
zip.write(r.content)
print("Download Complete!")
print("Unzipping contents...")
#Extract the file contents, rename the extracted file to 'Manifest.content'
with zipfile.ZipFile('MANZIP') as zip:
name = zip.namelist()
zip.extractall()
os.rename(name[0], 'Manifest.content')
os.remove('MANZIP')
print('Unzipped!')
def build_dict():
con = sqlite3.connect('manifest.content')
print('Connected to sqlite db')
cur = con.cursor()
cur.execute('SELECT json from DestinyInventoryItemDefinition')
print('Generating DestinyInventoryItemDefinition dictionary....')
items = cur.fetchall()
item_jsons = [json.loads(item[0]) for item in items]
item_dict = {}
for item in item_jsons:
if ( item['displayProperties']['name'] != "Classified" ):
if ( item['itemTypeDisplayName'] != None):
if ( item['itemTypeAndTierDisplayName'] ):
if ( "Exotic" in item['itemTypeAndTierDisplayName'] and "Intrinsic" not in item['itemTypeAndTierDisplayName']):
if ( item['displayProperties']['name'] ):
item_dict[item['displayProperties']['name']] = item['displayProperties']
item_dict[item['displayProperties']['name']]['type'] = item['itemTypeDisplayName']
item_dict[item['displayProperties']['name']]['tier'] = item['itemTypeAndTierDisplayName']
item_dict[item['displayProperties']['name']]['image'] = "https://www.bungie.net" + item['displayProperties']['icon']
item_dict[item['displayProperties']['name']]['active'] = "false"
try:
#item_dict[item['displayProperties']['name']]['class'] = item['quality']['infusionCategoryName']
item_dict[item['displayProperties']['name']]['class'] = item['classType']
except:
item_dict[item['displayProperties']['name']]['class'] = "null"
print('Dictionary Generated!')
return item_dict
def saveToJs(data):
weapons = []
armor = []
warlock = []
hunter = []
titan = []
weapon_ornaments = []
ships = []
emotes = []
vehicles = []
ghosts = []
ornaments = []
for item in list(data):
del(data[item]['icon'])
del(data[item]['hasIcon'])
if (data[item]['type'] == "Weapon Ornament"):
weapon_ornaments.append(data[item])
elif (data[item]['type'] == "Ship"):
ships.append(data[item])
elif (data[item]['type'] == "Emote"):
emotes.append(data[item])
elif (data[item]['type'] == "Vehicle"):
vehicles.append(data[item])
elif (data[item]['type'] == "Trait"):
del(data[item])
elif (data[item]['type'] == "Helmet"):
armor.append(data[item])
elif (data[item]['type'] == "Chest Armor"):
armor.append(data[item])
elif (data[item]['type'] == "Leg Armor"):
armor.append(data[item])
elif (data[item]['type'] == "Gauntlets"):
armor.append(data[item])
elif (data[item]['type'] == "Ghost Shell"):
ghosts.append(data[item])
elif ("Ornament" in data[item]['type']):
ornaments.append(data[item])
elif (data[item]['type'] == "Engram"):
del(data[item])
else:
weapons.append(data[item])
for piece in armor:
if (piece['class'] == 2):
warlock.append(piece)
elif (piece['class'] == 0):
titan.append(piece)
elif (piece['class'] == 1):
hunter.append(piece)
else:
print("This armor piece has an issue", end="")
print()
print(piece)
with open("ExampleData.js", "w") as text_file:
print("\nvar exoticHunterArmorList = ", file=text_file, end="")
print(hunter, file=text_file)
print("\nvar exoticTitanArmorList = ", file=text_file, end="")
print(titan, file=text_file)
print("\nvar exoticWarlockArmorList = ", file=text_file, end="")
print(warlock, file=text_file)
print("\nvar exoticWeaponList = ", file=text_file, end="")
print(weapons, file=text_file)
print("\nvar exoticVehicleList = ", file=text_file, end="")
print(vehicles, file=text_file)
print("\nvar exoticShipList = ", file=text_file, end="")
print(ships, file=text_file)
print("\nvar exoticEmoteList = ", file=text_file, end="")
print(emotes, file=text_file)
print("\nvar exoticGhostList = ", file=text_file, end="")
print(ghosts, file=text_file)
print("\nvar exoticOrnamentList = ", file=text_file, end="")
print(ornaments, file=text_file)
#print(len(data))
#print(data["Rat King"])
#from collections import Counter
print("Starting...")
if (os.path.isfile('ExampleData.js')):
print("Found existing data, overwriting...")
os.remove('ExampleData.js')
get_manifest()
all_data = build_dict()
os.remove('Manifest.content')
print("Formatting and saving to JavaScript file...")
saveToJs(all_data)
print("Done")
#print(len(all_data))
#print(all_data['Coldheart']['tier'])
#print("Exotic" in all_data['Coldheart']['tier'])
#print(not all_data['Raven Shard']['tier'])
| RyanGrant/RyanGrant.github.io | Python/Manifest.py | Manifest.py | py | 5,969 | python | en | code | 0 | github-code | 6 |
72302702267 | # Set the url configurations of address_book app
#
# (c) 2021 Dip Bhakta, Uttara, Dhaka
# email bhaktadip@gmail.com
# phone +8801725652782
from django.urls import path
app_name='address_book'
urlpatterns = [
]
| Dipbhakta007/ZSRecruitment | address_book/urls.py | urls.py | py | 219 | python | en | code | 0 | github-code | 6 |
29626198089 | import pygame
import pathlib
import random
img_path = pathlib.Path(__file__).parent / 'img'
class Locators(object):
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
screen_width = 800
screen_height = 600
random_speed = [1, -1]
rect_width = 40
rect_height = 40
img_path = pathlib.Path(__file__).parent / 'source' / 'img'
music_path = pathlib.Path(__file__).parent / 'source' / 'music'
all_coordinates = []
all_objects = pygame.sprite.Group()
all_data_dict = {}
class Object(pygame.sprite.Sprite):
def __init__(self, img, id, type_obj):
""" Constructor, create the image of the block. """
super().__init__()
image = pygame.image.load(img)
self.id = id
self.type = type_obj
self.image = pygame.transform.scale(image, (40, 40))
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = self.get_initial_points()
self.add_object_to_map(self.rect.x, self.rect.y)
self.speed_x = random.choice(Locators.random_speed)
self.speed_y = random.choice(Locators.random_speed)
def get_initial_points(self):
rect_x = 0
rect_y = 0
is_correct = False
while not is_correct:
rect_x = random.randint(20, Locators.screen_width - 20)
rect_y = random.randint(20, Locators.screen_height - 20)
is_correct = self.check_valid_point(rect_x, rect_y)
return rect_x, rect_y
def check_valid_point(self, x, y):
for i in range(y-20, y+20):
for j in range(x-20, x+20):
if Locators.all_coordinates[i][j] != 0:
return False
return True
def add_object_to_map(self, x, y):
for i in range(y-20, y+20):
for j in range(x-20, x+20):
Locators.all_coordinates[i][j] = self.id
def update(self):
print(f"{self.id} {self.type} {self.image}")
self.rect.x += self.speed_x
self.rect.y += self.speed_y
if self.rect.left < 0:
self.speed_x = abs(self.speed_x)
return
if self.rect.right > Locators.screen_width:
self.speed_x = abs(self.speed_x)*(-1)
return
if self.rect.top < 0:
self.speed_y = abs(self.speed_y)
return
if self.rect.bottom > Locators.screen_height:
self.speed_y = abs(self.speed_y)*(-1)
return
| aksaule-bagytzhanova/game | Objects.py | Objects.py | py | 2,501 | python | en | code | 0 | github-code | 6 |
38589291607 | import os
from django.conf import settings
from django.core.mail import EmailMessage
from .models import STATUS_TYPES
from smtplib import SMTPException
from django.core.mail import BadHeaderError
from python_http_client import exceptions
import logging
logger = logging.getLogger("django")
# admin emails (add more here)
NO_REPLY_EMAIL = settings.SENDGRID_NO_REPLY_EMAIL
ADMIN_EMAIL = settings.SENDGRID_ADMIN_EMAIL
# sendgrid templates for users
SENDGRID_TICKET_CREATED_TEMPLATE_ID_USER = settings.SENDGRID_TICKET_CREATED_TEMPLATE_ID_USER
SENDGRID_TICKET_DELETED_TEMPLATE_ID_USER = settings.SENDGRID_TICKET_DELETED_TEMPLATE_ID_USER
SENDGRID_TICKET_REJECTED_TEMPLATE_ID_USER = settings.SENDGRID_TICKET_REJECTED_TEMPLATE_ID_USER
SENDGRID_TICKET_UPDATED_TEMPLATE_ID_USER = settings.SENDGRID_TICKET_UPDATED_TEMPLATE_ID_USER
SENDGRID_BUCKET_CREATED_TEMPLATE_ID_USER = settings.SENDGRID_BUCKET_CREATED_TEMPLATE_ID_USER
# sendgrid templates for admins
SENDGRID_TICKET_CREATED_TEMPLATE_ID_ADMIN = settings.SENDGRID_TICKET_CREATED_TEMPLATE_ID_ADMIN
SENDGRID_TICKET_DELETED_TEMPLATE_ID_ADMIN = settings.SENDGRID_TICKET_DELETED_TEMPLATE_ID_ADMIN
SENDGRID_TICKET_UPDATED_TEMPLATE_ID_ADMIN = settings.SENDGRID_TICKET_UPDATED_TEMPLATE_ID_ADMIN
class Mail(EmailMessage):
def __init__(self, ticket, status):
ticket_url = os.environ.get("AZURE_SITES_URL")
logger.info("status = " + status)
# general dynamic data for all emails
dynamic_template_data = {
"name": ticket.name,
"study_name": ticket.study_name,
"ticket_url": f"{ticket_url}/{ticket.id}/update",
"ticket_status": status
}
# create email message object and fill in the details
# in tandem with the user's email
self.admin_email = EmailMessage(from_email=NO_REPLY_EMAIL)
self.admin_email.to = [ADMIN_EMAIL]
# create message
if status == "Created":
self.template_id = SENDGRID_TICKET_CREATED_TEMPLATE_ID_USER
self.admin_email.template_id = SENDGRID_TICKET_CREATED_TEMPLATE_ID_ADMIN
# attach other data here
# delete message
elif status == "Deleted":
self.template_id = SENDGRID_TICKET_DELETED_TEMPLATE_ID_USER
self.admin_email.template_id = SENDGRID_TICKET_DELETED_TEMPLATE_ID_ADMIN
# attach other data here
# rejected message: Data Intake Form Rejected
elif status == STATUS_TYPES[0]:
self.template_id = SENDGRID_TICKET_REJECTED_TEMPLATE_ID_USER
self.admin_email.template_id = SENDGRID_TICKET_UPDATED_TEMPLATE_ID_ADMIN
# attach rejected_reason
dynamic_template_data["rejected_reason"] = ticket.ticket_review_comment
# bucket created message: Awaiting Data Custodian Upload Start
elif status == STATUS_TYPES[3]:
self.template_id = SENDGRID_BUCKET_CREATED_TEMPLATE_ID_USER
self.admin_email.template_id = SENDGRID_TICKET_UPDATED_TEMPLATE_ID_ADMIN
# attach other data here
# data upload completed message: Awaiting Gen3 Acceptance
elif status == STATUS_TYPES[5]:
self.template_id = SENDGRID_TICKET_UPDATED_TEMPLATE_ID_USER
self.admin_email.template_id = SENDGRID_TICKET_UPDATED_TEMPLATE_ID_ADMIN
# attach other data here
# update message
else:
self.template_id = SENDGRID_TICKET_UPDATED_TEMPLATE_ID_USER
self.admin_email.template_id = SENDGRID_TICKET_UPDATED_TEMPLATE_ID_ADMIN
# attach ticket_status
self.admin_email.dynamic_template_data = dynamic_template_data
self.dynamic_template_data = dynamic_template_data
super().__init__(
from_email=NO_REPLY_EMAIL,
to=[ticket.email],
)
def send(self, fail_silently=False):
result = 0
# send emails out to the admin
try:
logger.info("Attempting to send admin email.")
self.admin_email.send(fail_silently)
logger.info("Attempting to send email data custodian email.")
result = super().send(fail_silently)
# SendGrid email error handling: https://github.com/sendgrid/sendgrid-python/blob/main/use_cases/error_handling.md
except BadHeaderError:
logger.error('Invalid header found for email.')
except SMTPException as e:
logger.error('SMTP exception when sending email: ' + e)
except exceptions.BadRequestsError as e:
logger.error('BadRequestsHeader for email.')
logger.error(e.body)
except:
logger.error("Mail Sending Failed for email to")
return result
| NimbusInformatics/bdcat-data-tracker | api/tracker/mail.py | mail.py | py | 4,796 | python | en | code | 3 | github-code | 6 |
23456341457 | class Stack:
def __init__(self):
self.stack = []
def push_s(self, data):
if data not in self.stack:
self.stack.append(data)
else:
pass
def pop_s(self):
if len(self.stack) <= 0:
print("The stack is empty")
else:
self.stack.pop()
def peek(self):
return self.stack[-1]
def show_all(self):
return self.stack
stack1 = Stack()
stack1.push_s(1)
stack1.push_s(2)
stack1.push_s(3)
stack1.push_s(1)
print(stack1.show_all())
# [1, 2, 3]
print(stack1.peek())
# 3
stack1.pop_s()
print(stack1.show_all())
# [1, 2]
stack1.pop_s()
stack1.pop_s()
stack1.pop_s()
# The stack is empty
print(stack1.show_all())
# []
| vifirsanova/100-days-of-code | day8/stack.py | stack.py | py | 727 | python | en | code | 1 | github-code | 6 |
20516636897 | from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import sys
import time
import json
import getopt
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
# Configure AWS IOT
thing_name = "medidor"
topic_consumo = "medidor/consumo"
topic_sms = "medidor/sms"
# Configure parameters
already_notificated = False
delay_s = 1
#Function measure current
def calculaConsumo():
sensor = 0
Consumo = 0
sensibilidade = 0.185
for num in range(0,1000):
sensor = mcp.read_adc(0) * (5 / 1023.0)
Consumo = Consumo + (sensor - 5) / sensibilidade
time.sleep(0.001)
Consumo = Consumo / 1000
return Consumo
# Custom Shadow callback
def customShadowCallback_Update(payload, responseStatus, token):
# payload is a JSON string ready to be parsed using json.loads(...)
# in both Py2.x and Py3.x
if responseStatus == "timeout":
print("Update request " + token + " time out!")
if responseStatus == "accepted":
payloadDict = json.loads(payload)
print("~~~~~~~~~~~~~~~~~~~~~~~")
print("Update request with token: " + token + " accepted!")
try:
print("property: " + str(payloadDict["state"]["reported"]))
except (Exception) as e:
print("property: " + str(payloadDict["state"]["desired"]))
print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
if responseStatus == "rejected":
print("Update request " + token + " rejected!")
# Usage
usageInfo = """Usage:
Use certificate based mutual authentication:
python medidor-iot-aws.py -e <endpoint> -r <rootCAFilePath> -c <certFilePath> -k <privateKeyFilePath>
Type "python medidor-iot-aws.py -h" for available options.
"""
# Help info
helpInfo = """-e, --endpoint
Your AWS IoT custom endpoint
-r, --rootCA
Root CA file path
-c, --cert
Certificate file path
-k, --key
Private key file path
-h, --help
Help information
"""
# Read in command-line parameters
host = ""
rootCAPath = ""
certificatePath = ""
privateKeyPath = ""
try:
opts, args = getopt.getopt(sys.argv[1:], "hwe:k:c:r:", ["help", "endpoint=", "key=","cert=","rootCA="])
if len(opts) == 0:
raise getopt.GetoptError("No input parameters!")
for opt, arg in opts:
if opt in ("-h", "--help"):
print(helpInfo)
exit(0)
if opt in ("-e", "--endpoint"):
host = arg
if opt in ("-r", "--rootCA"):
rootCAPath = arg
if opt in ("-c", "--cert"):
certificatePath = arg
if opt in ("-k", "--key"):
privateKeyPath = arg
except getopt.GetoptError:
print(usageInfo)
exit(1)
# Missing configuration notification
missingConfiguration = False
if not host:
print("Missing '-e' or '--endpoint'")
missingConfiguration = True
if not rootCAPath:
print("Missing '-r' or '--rootCA'")
missingConfiguration = True
if not certificatePath:
print("Missing '-c' or '--cert'")
missingConfiguration = True
if not privateKeyPath:
print("Missing '-k' or '--key'")
missingConfiguration = True
if missingConfiguration:
exit(2)
# Configure logging
"""
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
"""
# Custom MQTT message callback
def callbackLed(client, userdata, message):
global led_status
global already_notificated
result = json.loads(message.payload)
if(result["Consumo"] <= 0.1):
#print "Led on"
led_status = updateLed(True)
already_notificated = True
else:
#print "Led off"
led_status = updateLed(False)
already_notificated = False
# Init AWSIoTMQTTShadowClient
myShadowClient = None
myShadowClient = AWSIoTMQTTShadowClient("medidor")
myShadowClient.configureEndpoint(host, 8883)
myShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
myAWSIoTMQTTClient = myShadowClient.getMQTTConnection()
# AWSIoTMQTTShadowClient connection configuration
myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myShadowClient.configureConnectDisconnectTimeout(10) # 10 sec
myShadowClient.configureMQTTOperationTimeout(5) # 5 sec
# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
# Connect and subscribe to AWS IoT
# Connect to AWS IoT
myShadowClient.connect()
# Create a deviceShadow with persistent subscription
myDeviceShadow = myShadowClient.createShadowHandlerWithName(thing_name, True)
myAWSIoTMQTTClient.subscribe(topic_led, 1, callbackLed)
# Start Shadow
ConsumoShadow = 0
payloadShadow = ('"Consumo": "{0:0.1f}", "Notificated": "{1}"'.format(ConsumoShadow, already_notificated))
payloadShadow = '{"state":{ "desired": {'+payloadShadow+'}}}'
myDeviceShadow.shadowUpdate(payloadShadow, customShadowCallback_Update, 5)
# Publish to a topic in a loop forever
try:
while True:
# Read Current
ConsumoDC = calculaConsumo()
# Publish temperature
msg = ('"Consumo DC": "{0:0.01f}", "Notificated": "{1}"'.format(ConsumoDC, already_notificated))
msg = '{'+msg+'}'
myAWSIoTMQTTClient.publish(topic_consumo, msg, 1)
# Update Shadow
payloadShadow = ('"Consumo": "{0:0.1f}", "Notificated": "{1}"'.format(ConsumoDC, already_notificated))
payloadShadow = '{"state":{ "reported": {'+payloadShadow+'}}}'
myDeviceShadow.shadowUpdate(payloadShadow, customShadowCallback_Update, 5)
time.sleep(delay_s)
except KeyboardInterrupt:
pass
| chls84/TCC | Código Python/medidor-aws-iot.py | medidor-aws-iot.py | py | 6,262 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.