seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
4758294095
from typing import Dict, Any import click from .root import cli #: Modules to import in interactive shell. SHELL_MODULES = dict( metric='gambit.metric', kmers='gambit.kmers', ) @cli.group( name='debug', hidden=True, ) def debug_group(): """Tools for debugging and testing.""" pass def make_shell_ns(ctx) -> Dict[str, Any]: """Make the user namespace for the shell command.""" from importlib import import_module ns = dict( click_ctx=ctx, ctx=ctx.obj, ) # Import modules into namespace for alias, name in SHELL_MODULES.items(): ns[alias] = import_module(name) return ns @debug_group.command() @click.option( '--ipython/--no-ipython', 'use_ipython', default=None, help='Use IPython instead of built-in Python REPL.', ) @click.pass_context def shell(ctx, use_ipython): """Start an interactive shell with application data and modules imported. Attempts to launch an IPython interactive interpreter if it is installed, otherwise falls back on standard Python REPL. """ from gambit.util.misc import is_importable if use_ipython is None: if is_importable('IPython'): use_ipython = True else: click.echo('IPython not available, defaulting to built-in Python REPL.', err=True) use_ipython = False ns = make_shell_ns(ctx) if use_ipython: from IPython import start_ipython start_ipython(argv=[], user_ns=ns) else: from code import interact interact(local=ns)
jlumpe/gambit
gambit/cli/debug.py
debug.py
py
1,417
python
en
code
16
github-code
6
38386651149
from network import WLAN import machine wlan = WLAN() #wlan.init(mode=WLAN.AP, ssid='hello world') #use the line below to apply a password wlan.init(mode=WLAN.AP, ssid="hi", auth=(WLAN.WPA2, "12345678")) print(wlan.ifconfig(id=1)) #id =1 signifies the AP interface wlan = WLAN(mode=WLAN.STA_AP) nets = wlan.scan() for net in nets: if net.ssid == 'LCD3': print('Network found!') wlan.connect(net.ssid, auth=(net.sec, '1cdunc0rd0ba'), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') pycom.rgbled(0x7f0000) break
MatiasRaya/IoT-PS
Ejemplos/WIFI/wifi_create.py
wifi_create.py
py
676
python
en
code
1
github-code
6
10383640973
import unittest import torch from executorch.backends.xnnpack.test.tester import Tester class TestSub(unittest.TestCase): class Sub(torch.nn.Module): def __init__(self): super().__init__() def forward(self, x, y): z = x - y return z def test_fp32_sub(self): inputs = (torch.randn((1, 3)), torch.randn((4, 3))) ( Tester(self.Sub(), inputs) .export() .check_count({"torch.ops.aten.sub.Tensor": 1}) .to_edge() .check_count({"executorch_exir_dialects_edge__ops_aten_sub_Tensor": 1}) .partition() .check_count({"torch.ops.higher_order.executorch_call_delegate": 1}) .check_not(["executorch_exir_dialects_edge__ops_aten_sub_Tensor"]) .to_executorch() .serialize() .run_method() .compare_outputs() )
pytorch/executorch
backends/xnnpack/test/ops/sub.py
sub.py
py
926
python
en
code
479
github-code
6
13321449104
from airflow.models import Variable from airflow.hooks.postgres_hook import PostgresHook from rock.utilities import safeget, get_delta_offset, find_supported_fields import requests class ContentItemCategory: def __init__(self, kwargs): self.kwargs = kwargs self.headers = { "Authorization-Token": Variable.get(kwargs["client"] + "_rock_token") } self.pg_connection = kwargs["client"] + "_apollos_postgres" self.pg_hook = PostgresHook( postgres_conn_id=self.pg_connection, keepalives=1, keepalives_idle=30, keepalives_interval=10, keepalives_count=5, ) def map_content_channel_to_category(self, obj): return { "created_at": self.kwargs["execution_date"], "updated_at": self.kwargs["execution_date"], "origin_id": obj["Id"], "origin_type": "rock", "apollos_type": "ContentChannel", "title": obj["Name"], } def set_content_item_category_query(self, obj): return """ UPDATE content_item SET content_item_category_id = (SELECT id FROM content_item_category WHERE origin_id = '{}') WHERE origin_id = '{}'; """.format( str(safeget(obj, "ContentChannel", "Id")), str(obj["Id"]) ) def run_attach_content_item_categories(self): fetched_all = False skip = 0 top = 10000 while not fetched_all: # Fetch people records from Rock. params = { "$top": top, "$skip": skip, "$expand": "ContentChannel", "$select": "Id,ContentChannel/Id", "$orderby": "ModifiedDateTime desc", } if not self.kwargs["do_backfill"]: params["$filter"] = get_delta_offset(self.kwargs) print(params) r = requests.get( f"{Variable.get(self.kwargs['client'] + '_rock_api')}/ContentChannelItems", params=params, headers=self.headers, ) rock_objects = r.json() if not isinstance(rock_objects, list): print(rock_objects) print("oh uh, we might have made a bad request") print("top: {top}") print("skip: {skip}") skip += top continue skip += top fetched_all = len(rock_objects) < top self.pg_hook.run( list(map(self.set_content_item_category_query, rock_objects)) ) def run_fetch_and_save_content_item_categories(self): fetched_all = False skip = 0 top = 10000 while not fetched_all: # Fetch people records from Rock. params = { "$top": top, "$skip": skip, # "$expand": "Photo", "$select": "Id,Name", "$orderby": "ModifiedDateTime desc", } if not self.kwargs["do_backfill"]: params[ "$filter" ] = f"ModifiedDateTime ge datetime'{self.kwargs['execution_date'].strftime('%Y-%m-%dT00:00')}' or ModifiedDateTime eq null" print(params) r = requests.get( f"{Variable.get(self.kwargs['client'] + '_rock_api')}/ContentChannels", params=params, headers=self.headers, ) rock_objects = r.json() if not isinstance(rock_objects, list): print(rock_objects) print("oh uh, we might have made a bad request") print("top: {top}") print("skip: {skip}") skip += top continue skip += top fetched_all = len(rock_objects) < top insert_data = list(map(self.map_content_channel_to_category, rock_objects)) content_to_insert, columns, constraint = find_supported_fields( pg_hook=self.pg_hook, table_name="content_item_category", insert_data=insert_data, ) self.pg_hook.insert_rows( "content_item_category", content_to_insert, columns, 0, True, replace_index=constraint, ) add_apollos_ids = """ UPDATE content_item_category SET apollos_id = apollos_type || ':' || id::varchar WHERE origin_type = 'rock' and apollos_id IS NULL """ self.pg_hook.run(add_apollos_ids) def fetch_and_save_content_item_categories(ds, *args, **kwargs): if "client" not in kwargs or kwargs["client"] is None: raise Exception("You must configure a client for this operator") Klass = ( # noqa N806 ContentItemCategory if "klass" not in kwargs else kwargs["klass"] ) category_task = Klass(kwargs) category_task.run_fetch_and_save_content_item_categories() def attach_content_item_categories(ds, *args, **kwargs): if "client" not in kwargs or kwargs["client"] is None: raise Exception("You must configure a client for this operator") Klass = ( # noqa N806 ContentItemCategory if "klass" not in kwargs else kwargs["klass"] ) category_task = Klass(kwargs) category_task.run_attach_content_item_categories()
CrossingsCommunityChurch/apollos-shovel
dags/rock/rock_content_item_categories.py
rock_content_item_categories.py
py
5,576
python
en
code
0
github-code
6
42385607904
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class ChowSortPipeline(object): def process_item(self, item, spider): if item['name']: item['name'] = item['name'][0].strip() item['votes'] = int(item['votes'][0].split()[0]) item['link'] = item['link'][0].strip() return item
jasonhellwig/Chowhound_Recipe_Sorter
chow_sort/pipelines.py
pipelines.py
py
480
python
en
code
1
github-code
6
13276332357
from pathlib import Path import os import pandas as pd from tensorboard.backend.event_processing.event_accumulator import EventAccumulator # extract the data and save them in a CSV file tb_path = Path("experiments") / "MPP" / "lohi" / "cdata" / "freesolv" / "lohi" / f"split_0" / "fold_0" / \ "model_0" tb_file = tb_path / list(sorted(filter( lambda x: str(x).startswith("events"), os.listdir(tb_path) )))[-1] print("File:", tb_file) ea = EventAccumulator(str(tb_file)) ea.Reload() for long, short in [("validation_", "val"), ("test_", "test")]: print([m for m in filter(lambda x: x.startswith(long), ea.Tags()["scalars"])]) for metric in filter(lambda x: x.startswith(long), ea.Tags()["scalars"]): print("metric", [e.value for e in ea.Scalars(metric)]) # dfs[short][f"{tech}_{metric}_split_{run}"] = [e.value for e in ea.Scalars(metric)] # print(df)
kalininalab/DataSAIL
experiments/MPP/check.py
check.py
py
891
python
en
code
4
github-code
6
40894632303
def sieve_of_Sundaram(n): k = (n - 2) // 2 #only check up to the upper limit number as divided by 2 primes = 2 integers_list = [True] * (k + 1) #initialize a a membership list to the above limit, defaulting to true for i in range(1, k + 1): #sets up a loop to from i and j (as equal) to to incrementing j against i j = i while i + j + 2 * i * j <= k: #start the loop that will end at condition here integers_list[i + j + 2 * i * j] = False #mark it j += 1 #increment j against i (so i remains the same untill the loop restarts) if n > 2: print(2, end=' ') for i in range(1, k + 1): if integers_list[i]: primes = primes + (2 * i + 1) #find prime by double and increment by 1, and add the running sum print(2 * i + 1, end=' ') print(primes) sieve_of_Sundaram(2000000)
jmpilot/Project-Euler
eu_10.py
eu_10.py
py
904
python
en
code
0
github-code
6
37946580665
from sklearn import tree from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score from sklearn.naive_bayes import GaussianNB import numpy as np # Data and labels # [Height, Weight ,Shoe Size] X = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40], [190, 90, 47], [175, 64, 39], [177, 70, 40], [159, 55, 37], [171, 75, 42], [181, 85, 43]] Y = ['male', 'male', 'female', 'female', 'male', 'male', 'female', 'female', 'female', 'male', 'male'] # Classifiers clf_tree = tree.DecisionTreeClassifier() clf_svm = SVC() clf_KNN = KNeighborsClassifier() clf_gaussian = GaussianNB() # Train the models clf_tree.fit(X, Y) clf_svm.fit(X, Y) clf_KNN.fit(X, Y) clf_gaussian.fit(X,Y) # Testing using the same data pred_tree = clf_tree.predict(X) acc_tree = accuracy_score(Y, pred_tree) * 100 print('Accuracy for DecisionTree: {}'.format(acc_tree)) pred_svm = clf_svm.predict(X) acc_svm = accuracy_score(Y, pred_svm) * 100 print('Accuracy for SVM: {}'.format(acc_svm)) pred_KNN = clf_KNN.predict(X) acc_KNN = accuracy_score(Y, pred_KNN) * 100 print('Accuracy for KNN: {}'.format(acc_KNN)) pred_gauss = clf_gaussian.predict(X) acc_gauss = accuracy_score(Y, pred_gauss) * 100 print('Accuracy for GaussianNB: {}'.format(acc_gauss)) # The best classifier from svm, per, KNN index = np.argmax([acc_tree,acc_svm, acc_KNN, acc_gauss]) classifiers = {0: 'Tree',1: 'SVM', 2: 'KNN', 3: 'GaussianNB'} print('Best gender classifier is {}'.format(classifiers[index]))
vjgpt/gender_classification
gender_classify.py
gender_classify.py
py
1,542
python
en
code
1
github-code
6
6166864226
# -*- coding: utf-8 -*- """ Created on Tue Jun 6 13:11:44 2017 @author: Francesco """ import serial import numpy as np import time PORT = "COM10" BAUD = 115200 port = serial.Serial(PORT,BAUD,timeout=1) START = 1 #BUNDLE SHAPE: |!|!|!|CH0_msb|CH0_lsb|ch1_msb|ch1_lsb|......|ch7_lsb|!|!|!| NUM_CHANNELS = 8 END_BUNDLE_BYTE = 3 BYTE_PER_CHANNEL = 2 #two bytes to represent int BUNDLE_LENGTH = NUM_CHANNELS*BYTE_PER_CHANNEL data = np.zeros(NUM_CHANNELS) graph_data = open('test_100Hz.txt','w') print("Gathering recordings for dataset") movement_time = 2 #2.5 seconds for each movement sample_time = 0.01 # 100Hz sample frequency num_samples = int(movement_time/sample_time) #num_samples = 300 counter = 0 while(START): try: #print("Flushing") #port.flushInput() movement = input("\n\ 0: wrist up\n\ 1: wrist down\n\ 2: wrist rotation out\n\ 3: wrist rotation inside\n\ 4: hand open\n\ 5: hand closed\n") if(movement == 's'): graph_data.close() print(port.inWaiting()) port.close() break #start communication, for some reason with utf-8 it works #start_time = time.time() elapsed = 0 counter = 0 starttime = time.time() while(elapsed < 2): port.write('s'.encode('utf-8')) a = port.read(END_BUNDLE_BYTE) #print(a) if(a.decode("raw_unicode_escape") == '!!!'): temp = port.read(BUNDLE_LENGTH) #unpack values and put them in "data" for channel in range(0,NUM_CHANNELS): value = (temp[channel*BYTE_PER_CHANNEL]<<8)|(temp[channel*BYTE_PER_CHANNEL + 1 ]) graph_data.write(str(value)) graph_data.write(',') #print(value) #start a new line in the file graph_data.write(movement+'\n') #wait the sample time to get a new value #time.sleep(sample_time) elapsed = time.time() - starttime #è allineato con l'if #perchè deve aumentare il counter solo quando scrive #counter += 1 #port.write('o'.encode('utf-8')) #print(port.inWaiting()) #write the separator between one movement and the other graph_data.write('-\n') #any character except 's' is ok to stop the communication #port.write('o'.encode('utf-8')) print("Movement Acquired - Elapsed Time: %d"%movement_time) except KeyboardInterrupt: print("Closing") port.close() graph_data.close() break
FrancesoM/UnlimitedHand-Learning
python_side/read_bytes_over_serial.py
read_bytes_over_serial.py
py
3,070
python
en
code
1
github-code
6
19638669363
import matplotlib.pylab as plt #import cv2 import numpy as np import scipy as sp from scipy.fftpack import fft, fftfreq, ifft, fft2, ifft2, fftshift, ifftshift arbol=plt.imread("arbol.png") #plt.imshow(arbol) #transformada base,altura=np.shape(arbol) trans = fft2(arbol) shi=fftshift(trans) grashi=np.abs(shi) fgraf=np.log(grashi) #grafica de la transformada se uso logaritmo para que se note mas plt.figure() plt.imshow(abs(fgraf), cmap='gray') plt.title("Transformada de Fourier") plt.savefig("quijanoSantiago_FT2D.pdf") #filtrarla, informacion sale de aprenderpython.net/transformada-de-fourier/ trans2 = fft2(arbol) shi2=fftshift(trans2) def borrar(shi2,abj,arr,izq,der): for i in range(np.shape(shi2)[0]): for j in range(np.shape(shi2)[1]): if (i<arr and i>abj and j<der and j>izq): shi2[i,j]=0 return shi2 def salvar(shi2,abj,arr,izq,der): for i in range(np.shape(shi2)[0]): for j in range(np.shape(shi2)[1]): if (i<arr and i>abj and j<der and j>izq): shi2[i,j]=shi2[i,j] else: shi2[i,j]=0 return shi2 #shi3=salvar(shi2,0,256,120,136) shi4=borrar(shi2,117,120,103,106) shi5=borrar(shi4,136,139,151,154) shi6=borrar(shi5,62,65,62,65) shi7=borrar(shi6,191,194,191,194) filGra=np.abs(shi7) graficarFil=np.log(filGra) filtra=ifftshift(shi7) invX2=ifft2(filtra) # #f2=fftshift(filtr[0]) #graf2=np.log(np.abs(f2)) plt.figure() plt.title("Transformada filtrada") plt.imshow(graficarFil, cmap='gray') plt.ylabel("frecuencia") plt.xlabel(" ") plt.colorbar() plt.savefig("quijanoSantiago_FT2D_filtrada.pdf") plt.figure() plt.title("Imagen despues de filtro") plt.imshow(abs(invX2)) plt.savefig("quijanoSantiago_Imagen_Filtrada.pdf") #plt.show() #######
saquijano/quijanoSantiagoHW3
Fourier2D.py
Fourier2D.py
py
1,691
python
en
code
0
github-code
6
41699189850
#!/usr/bin/python3 import socket #Creating socket object serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() #Host is the server IP port = 444 #Port to listen on #Binding to socket serversocket.bind((host, port)) #Starting TCP listener serversocket.listen(3) while True: #Starting the connection clientsocket, address = serversocket.accept() print("Recieved connection from %s ") % str(address) #Message after successful connection message = 'Server is connected' + "\r\n" clientsocket.send(message.encode('ascii')) clientsocket.close()
olivertepper/Python-Pentesting
TCP_Server.py
TCP_Server.py
py
616
python
en
code
0
github-code
6
72078430587
# %% from datetime import date import requests from json import dump, load # %% class Search: def __init__(self, keyword, url="http://localhost:8080/search", getResult=True): self.keyword = keyword self.url = url self.resultMax = 2 self.infoBoxMax = 1 if getResult: self.fullResult = self._search() self.result = self.extractRelevant() def html(self): params = {'q': self.keyword} res = requests.post(self.url, params) return res def test_search(self): params = {'q': self.keyword, 'format': 'json'} res = requests.post(self.url, params) return res def _search(self): params = {'q': self.keyword, 'format': 'json'} res = requests.post(self.url, params) return res.json() def refresh(self): self.fullResult = self._search() def extractRelevant(self): if not self.fullResult: self.refresh() res = self.extract() if len(res['results']) > self.resultMax: res['results'] = [res['results'][i] for i in range(2)] if len(res['infoboxes']) > self.infoBoxMax: res['infoboxes'] = [res['infoboxes'][i] for i in range(1)] return res def extractResult(self, res): keys = ['url', 'title', 'content', 'category'] return {k: res[k] for k in keys if k in res.keys()} def extactInfoBox(self, infoBox): keys = ['infoBox', 'id', 'content'] return {k: infoBox[k] for k in keys if k in infoBox.keys()} def extract(self): results = [self.extractResult(result) for result in self.fullResult['results']] answers = self.fullResult['answers'] infoboxes = [self.extactInfoBox(info) for info in self.fullResult['infoboxes']] suggestions = self.fullResult['suggestions'] return {'results': results, 'answers': answers, 'infoboxes': infoboxes, 'suggestions': suggestions} def log(self, result=True, fullResult=False, fileName="searchLog.json"): with open(fileName, 'a') as f: if result or fullResult: f.write(date.today().strftime("%d/%m/%Y %H:%M:%S") + "\n \n") if result: f.write("\n \nExtracted Results\n") dump(self.result, f, indent=4) if fullResult: f.write("\n \nFull Results\n") dump(self.result, f, indent=4) def writeToFile(content, fileName="sampleSearch.json"): with open(fileName, 'w') as f: dump(content, f, indent=4) def read(fileName="sampleSearch.json"): with open(fileName, "r") as f: return load(f)
arromaljj/FinalProjectArromal
backend/backend_core/search.py
search.py
py
2,723
python
en
code
0
github-code
6
74121185787
__topotests_file__ = "bgp_comm_list_delete/test_bgp_comm-list_delete.py" __topotests_gitrev__ = "4953ca977f3a5de8109ee6353ad07f816ca1774c" # pylint: disable=wildcard-import,unused-import,unused-wildcard-import from topotato.v1 import * @topology_fixture() def topology(topo): """ [ r1 ] | { s1 } | [ r2 ] """ topo.router("r1").lo_ip4.append("172.16.255.254/32") class Configs(FRRConfigs): routers = ["r1", "r2"] zebra = """ #% extends "boilerplate.conf" #% block main #% if router.name == 'r1' interface lo ip address {{ router.lo_ip4[0] }} ! #% endif #% for iface in router.ifaces interface {{ iface.ifname }} ip address {{ iface.ip4[0] }} ! #% endfor ip forwarding ! #% endblock """ bgpd = """ #% extends "boilerplate.conf" #% block main #% if router.name == 'r1' router bgp 65000 no bgp ebgp-requires-policy neighbor {{ routers.r2.ifaces[0].ip4[0].ip }} remote-as 65001 neighbor {{ routers.r2.ifaces[0].ip4[0].ip }} timers 3 10 address-family ipv4 unicast redistribute connected route-map r2-out exit-address-family ! route-map r2-out permit 10 set community 111:111 222:222 333:333 444:444 ! #% elif router.name == 'r2' router bgp 65001 no bgp ebgp-requires-policy neighbor {{ routers.r1.ifaces[0].ip4[0].ip }} remote-as 65000 neighbor {{ routers.r1.ifaces[0].ip4[0].ip }} timers 3 10 address-family ipv4 neighbor {{ routers.r1.ifaces[0].ip4[0].ip }} route-map r1-in in exit-address-family ! bgp community-list standard r1 permit 333:333 ! route-map r1-in permit 10 set comm-list r1 delete ! #% endif #% endblock """ class BGPCommListDeleteTest(TestBase, AutoFixture, topo=topology, configs=Configs): @topotatofunc def _bgp_converge_bgpstate(self, topo, r1, r2): expected = {str(r1.ifaces[0].ip4[0].ip): {"bgpState": "Established"}} yield from AssertVtysh.make( r2, "bgpd", f"show ip bgp neighbor { r1.ifaces[0].ip4[0].ip } json", maxwait=5.0, compare=expected, ) @topotatofunc def _bgp_converge_prefixCounter(self, topo, r1, r2): expected = { str(r1.ifaces[0].ip4[0].ip): { "addressFamilyInfo": {"ipv4Unicast": {"acceptedPrefixCounter": 2}} } } yield from AssertVtysh.make( r2, "bgpd", f"show ip bgp neighbor { r1.ifaces[0].ip4[0].ip } json", maxwait=5.0, compare=expected, ) @topotatofunc def _bgp_comm_list_delete(self, topo, r1, r2): expected = { "paths": [{"community": {"list": ["111:111", "222:222", "444:444"]}}] } yield from AssertVtysh.make( r2, "bgpd", f"show ip bgp { r1.lo_ip4[0] } json", maxwait=5.0, compare=expected, )
opensourcerouting/topotato
test_bgp_comm-list_delete.py
test_bgp_comm-list_delete.py
py
3,054
python
en
code
0
github-code
6
70283377149
import streamlit as st from collections import Counter import nltk from nltk.corpus import stopwords import torch from datasets import load_dataset import time import sys, os import logging from transformers import AutoTokenizer, AutoModel #custom packages sys.path.insert(1, os.getcwd()) from src import constant as my_constant from src import my_utils as my_utils from src import searcher as my_searcher st.set_page_config(layout="wide") st.title('Demo of Semantic Search on United Nations Administrative Instructions (AIs)') st.markdown(f"{my_constant.open_i}- Data: web scraped from UN Policy portal: https://policy.un.org/browse-by-source/30776{my_constant.close_i}") st.markdown(f"{my_constant.open_i}- Technology used: Sentence transformer model, FAISS (Facebook AI Similarity Search), YAKE (unsupervised model), Huggingface arrow dataset, and Selenium (dynamic web page scraping){my_constant.close_i}") #get configuration cfg = my_utils.get_configuration() search_cfg=cfg[my_constant.search_setting] log_dir = cfg.get('log_dir') #search config search_cfg = cfg[my_constant.search_setting] max_len = search_cfg.get(my_constant.max_doc_len) if search_cfg.get(my_constant.max_doc_len) else 800 #config device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") @st.cache_resource def load_data_model(): try: #load data search_ds_path = os.path.join(os.getcwd(), "data") #load from disk search_dataset = load_dataset('parquet', data_files=os.path.join(search_ds_path, 'embed_dataset.parquet'), split="train") if search_dataset is None: st.write("Ops sorry! failed to load data") raise Exception("Failed to load dataset!!") #add faiss index search_dataset.add_faiss_index(column=my_constant.embeddings) nltk.download('stopwords') time.sleep(.1) #load stop words stop_words = stopwords.words('english') st_wd = search_cfg.get(my_constant.stop_words) if st_wd: stop_words = stop_words + [str(s).strip().lower() for s in st_wd.split(my_constant.comma) if s] #load sentence model model_ckpt = "sentence-transformers/multi-qa-mpnet-base-dot-v1" sentence_tokenizer = AutoTokenizer.from_pretrained(model_ckpt, force_download=True ) sentence_model = AutoModel.from_pretrained(model_ckpt) if sentence_model is None: st.write(my_constant.abort_msg ) raise Exception(f'failed to load model') return { 'search_dataset': search_dataset, 'stop_words': Counter(stop_words), 'sentence_tokenizer': sentence_tokenizer, 'sentence_model': sentence_model, 'device': device } except Exception as e: logging.error(f'Home.load_data_model: {str(e)}') searcher_dict = load_data_model() try: with st.form('Search'): search_for = st.text_input('Search for:') num_recs = st.slider('Show only Top: ', min_value=1, max_value=50, value=20) submit = st.form_submit_button('Search') if submit:#run the search results, time_tkn = my_searcher.search_for_documents(search_for, searcher_dict, k=num_recs) st.markdown(f"{my_constant.open_i}Search took:{time_tkn}.{my_constant.close_i}") if len(results) > 0: my_searcher.print_streamlit_results(results) else: st.markdown(f'{my_constant.opening_tag}No documents found with specified critera.{my_constant.closing_tag}') st.markdown(f"{my_constant.open_i}{my_constant.score_defn}{my_constant.close_i}") except Exception as e: logging.error(f'{str(e)}')
geraldlab/semantic_search
Search.py
Search.py
py
3,971
python
en
code
0
github-code
6
36060705055
from config.log import log from central.servidor_central import servidor_central if __name__ == "__main__": log() # print('Informe o caminho do arquivo de configuração da sala 01:') # sala_01 = input() # print('Informe o caminho do arquivo de configuração da sala 02:') # sala_02 = input() sala_01 = 'src/json/sala_1.json' sala_02 = 'src/json/sala_2.json' servidor_central(sala_01, sala_02)
AntonioAldisio/FSE-2022-2-Trabalho-1
src/app_servidor_central.py
app_servidor_central.py
py
428
python
pt
code
0
github-code
6
16205876862
from typing import Any from xdsl.dialects import scf from xdsl.interpreter import ( Interpreter, InterpreterFunctions, PythonValues, ReturnedValues, impl, impl_terminator, register_impls, ) @register_impls class ScfFunctions(InterpreterFunctions): @impl(scf.If) def run_if(self, interpreter: Interpreter, op: scf.If, args: tuple[Any, ...]): (cond,) = args region = op.true_region if cond else op.false_region results = interpreter.run_ssacfg_region(region, ()) return results @impl(scf.For) def run_for( self, interpreter: Interpreter, op: scf.For, args: PythonValues ) -> PythonValues: lb, ub, step, *loop_args = args loop_args = tuple(loop_args) for i in range(lb, ub, step): loop_args = interpreter.run_ssacfg_region( op.body, (i, *loop_args), "for_loop" ) return loop_args @impl_terminator(scf.Yield) def run_br(self, interpreter: Interpreter, op: scf.Yield, args: tuple[Any, ...]): return ReturnedValues(args), ()
xdslproject/xdsl
xdsl/interpreters/scf.py
scf.py
py
1,102
python
en
code
133
github-code
6
20538164969
# https://leetcode.com/problems/count-and-say """ Time complexity:- O(2^n) Space Complexity:- O(n) """ class Solution: def countAndSay(self, n: int) -> str: # Base case: when n is 1, return "1" if n == 1: return "1" # Recursively calculate the (n-1)-th term of the count-and-say sequence temp = self.countAndSay(n - 1) res = "" val = temp[0] # Initialize the current value to the first character freq = 1 # Initialize the frequency of the current value to 1 # Iterate through the characters in the (n-1)-th term for i in range(1, len(temp)): if temp[i] == val: freq += 1 else: # Append the frequency and value of the previous group to the result res += str(freq) res += str(val) val = temp[i] # Update the current value freq = 1 # Reset the frequency for the new value # Append the frequency and value of the last group to the result res += str(freq) res += str(val) return res
Amit258012/100daysofcode
Day28/count_and_say.py
count_and_say.py
py
1,129
python
en
code
0
github-code
6
42415152108
PORT = 5000 TEMPLATE_DIR = 'chatroom/templates' SQL = dict( db_uri = 'postgres://{user}:{pasw}@{host}:{port}/{data}', heroku = dict( host = 'ec2-54-83-43-49.compute-1.amazonaws.com', port = '5432', user = 'qetxaijgzmpbzi', pasw = 'Y-c4N56681GgE3-stOTQJ7SN3Y', data = 'd53kkgjq3l22j5' ) )
activaigor/chatroom
chatroom/settings.py
settings.py
py
307
python
en
code
1
github-code
6
71879426428
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 4 13:55:34 2020 @author: Kangqi Fu """ from numpy import loadtxt, reshape from pylab import ioff import matplotlib.pyplot as plt from glob import glob import os ioff() fileNames = glob("./output/Solution*.dat") fileNames.sort() for fileName in fileNames: fig = plt.figure() ax = fig.add_subplot(111) f = open(fileName, "r") xCells = int(f.readline().split(":")[1]) yCells = int(f.readline().split(":")[1]) numGhostCells = int(f.readline().split(":")[1]) time = float(f.readline().split(":")[1]) cfl = float(f.readline().split(":")[1]) f.close() x, y, u = loadtxt(fileName, skiprows = 5, unpack=True) x = reshape(x, (xCells + 2 * numGhostCells, yCells + 2 * numGhostCells)) y = reshape(y, (xCells + 2 * numGhostCells, yCells + 2 * numGhostCells)) u = reshape(u, (xCells + 2 * numGhostCells, yCells + 2 * numGhostCells)) #ax.set_xlim(-1.5, 1.5) #ax.set_ylim(-0.1, 1.1) plt.contourf(x, y, u, 100, cmap='jet') #plt.contourf(x, y, u,100, cmap='ocean_r') plt.colorbar() ax.set_title("CFL = %5.2f"%cfl + ", Times = %5.3f"%time) fig.savefig(fileName.replace(".dat", ".png")) os.system("eog " + fileNames[0].replace(".dat",".png"))
KennyKangMPC/CS-759
final_project/scalarAdvection2D/plotAdv.py
plotAdv.py
py
1,290
python
en
code
4
github-code
6
24680896779
from fastapi import APIRouter, Depends, HTTPException, status, Request from typing import Union import requests from db.models import ENV, Session, get_db from db import schemas, crud from dependencies import utils import json router = APIRouter(prefix="/auth") @router.post("/login", response_model=schemas.TokenBase) async def login_user(user_data: schemas.UserLogin, db: Session = Depends(get_db)): try: data = { "username": user_data.username, "password": user_data.password } data = json.dumps(data, indent = 4) headers = {"Content-Type": "application/json"} proxies = {"http": ENV['URL_AUTH']} request_session = requests.post(ENV['URL_AUTH']+"/auth/login", data=data, headers=headers, proxies=proxies) response_token = request_session.json() return response_token # return schemas.TokenBase( # access_token = response["access_token"], # token_type = response["token_type"] # ) except: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) @router.get("/verify") async def verify_auth(request: Request): try: print("ENTRANDO A VERIFY BACKEND") token = request.headers.get('Authorization') headers = {"Content-Type": "application/json", "Authorization": token} proxies = {"http": ENV['URL_AUTH']} request_session = requests.get(ENV['URL_AUTH']+"/auth/verify", headers=headers, proxies=proxies) response = request_session.json() print(response) if response != {"detail": "Could not validate credentials"}: return response else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect token", headers={"WWW-Authenticate": "Bearer"}, ) except: return HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect token", headers={"WWW-Authenticate": "Bearer"}, )
CosasU-Edipizarro/iic2173-2022-1
backend/routers/auth.py
auth.py
py
2,205
python
en
code
0
github-code
6
22656015465
from model import common import torch import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn import functional as F import numpy as np def make_model(args, parent=False): return RCGB(args) class CGConv2d(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True): super(CGConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) # for convolutional layers with a kernel size of 1, just use traditional convolution if kernel_size == 1 or True: self.ind = True else: self.ind = False self.oc = out_channels self.ks = kernel_size # the target spatial size of the pooling layer ws = kernel_size self.avg_pool = nn.AdaptiveAvgPool2d((ws,ws)) # the dimension of the latent repsentation self.num_lat = int((kernel_size * kernel_size) / 2 + 1) # the context encoding module self.ce = nn.Linear(ws*ws, num_lat, False) self.ce_bn = nn.BatchNorm1d(in_channels) self.ci_bn2 = nn.BatchNorm1d(in_channels) # activation function is relu self.act = nn.ReLU(inplace=True) # the number of groups in the channel interacting module if in_channels // 16: self.g = 16 else: self.g = in_channels # the channel interacting module self.ci = nn.Linear(self.g, out_channels // (in_channels // self.g), bias=False) self.ci_bn = nn.BatchNorm1d(out_channels) # the gate decoding module self.gd = nn.Linear(num_lat, kernel_size * kernel_size, False) self.gd2 = nn.Linear(num_lat, kernel_size * kernel_size, False) # used to prrepare the input feature map to patches self.unfold = nn.Unfold(kernel_size, dilation, padding, stride) # sigmoid function self.sig = nn.Sigmoid() def forward(self, x): # for convolutional layers with a kernel size of 1, just use traditional convolution if self.ind: return F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups) else: b, c, h, w = x.size() weight = self.weight # allocate glbal information gl = self.avg_pool(x).view(b,c,-1) # context-encoding module out = self.ce(gl) # use different bn for the following two branches ce2 = out out = self.ce_bn(out) out = self.act(out) # gate decoding branch 1 out = self.gd(out) # channel interacting module if self.g >3: # grouped linear oc = self.ci(self.act(self.ci_bn2(ce2).\ view(b, c//self.g, self.g, -1).transpose(2,3))).transpose(2,3).contiguous() else: # linear layer for resnet.conv1 oc = self.ci(self.act(self.ci_bn2(ce2).transpose(2,1))).transpose(2,1).contiguous() oc = oc.view(b,self.oc,-1) oc = self.ci_bn(oc) oc = self.act(oc) # gate decoding branch 2 oc = self.gd2(oc) # produce gate out = self.sig(out.view(b, 1, c, self.ks, self.ks) + oc.view(b, self.oc, 1, self.ks, self.ks)) # unfolding input feature map to patches x_un = self.unfold(x) b, _, l = x_un.size() # gating out = (out * weight.unsqueeze(0)).view(b, self.oc, -1) # currently only handle square input and output return torch.matmul(out,x_un).view(b, self.oc, int(np.sqrt(l)), int(np.sqrt(l))) def gated_conv(in_channels, out_channels, kernel_size, bias=True): return CGConv2d(in_channels, out_channels, kernel_size=kernel_size, padding=(kernel_size//2), stride=1, bias=bias) ## Residual Channel Attention Block (RCAB) class RCAB(nn.Module): def __init__( self, conv, n_feat, kernel_size, reduction, bias=True, bn=False, act=nn.ReLU(True), res_scale=1): super(RCAB, self).__init__() modules_body = [] for i in range(2): modules_body.append(conv(n_feat, n_feat, kernel_size, bias=bias)) if bn: modules_body.append(nn.BatchNorm2d(n_feat)) if i == 0: modules_body.append(act) # Adding Context Gated Convolution instead of Channel Attention layer from RCAN modules_body.append(gated_conv(n_feat, n_feat, kernel_size, bias)) self.body = nn.Sequential(*modules_body) self.res_scale = res_scale def forward(self, x): res = self.body(x) #res = self.body(x).mul(self.res_scale) res += x return res ## Residual Group (RG) class ResidualGroup(nn.Module): def __init__(self, conv, n_feat, kernel_size, reduction, act, res_scale, n_resblocks): super(ResidualGroup, self).__init__() modules_body = [] modules_body = [ RCAB( conv, n_feat, kernel_size, reduction, bias=True, bn=False, act=nn.ReLU(True), res_scale=1) \ for _ in range(n_resblocks)] modules_body.append(conv(n_feat, n_feat, kernel_size)) self.body = nn.Sequential(*modules_body) def forward(self, x): res = self.body(x) res += x return res ## Residual Channel Attention Network (RCAN) class RCGB(nn.Module): def __init__(self, args, conv=common.default_conv): super(RCGB, self).__init__() n_resgroups = args.n_resgroups n_resblocks = args.n_resblocks n_feats = args.n_feats kernel_size = 3 reduction = args.reduction scale = args.scale[0] act = nn.ReLU(True) # RGB mean for DIV2K self.sub_mean = common.MeanShift(args.rgb_range) # define head module modules_head = [conv(args.n_colors, n_feats, kernel_size)] # define body module modules_body = [ ResidualGroup( conv, n_feats, kernel_size, reduction, act=act, res_scale=args.res_scale, n_resblocks=n_resblocks) \ for _ in range(n_resgroups)] modules_body.append(conv(n_feats, n_feats, kernel_size)) # define tail module modules_tail = [ common.Upsampler(conv, scale, n_feats, act=False), conv(n_feats, args.n_colors, kernel_size)] self.add_mean = common.MeanShift(args.rgb_range, sign=1) self.head = nn.Sequential(*modules_head) self.body = nn.Sequential(*modules_body) self.tail = nn.Sequential(*modules_tail) def forward(self, x): x = self.sub_mean(x) x = self.head(x) res = self.body(x) res += x x = self.tail(res) x = self.add_mean(x) return x def load_state_dict(self, state_dict, strict=False): own_state = self.state_dict() for name, param in state_dict.items(): if name in own_state: if isinstance(param, nn.Parameter): param = param.data try: own_state[name].copy_(param) except Exception: if name.find('tail') >= 0: print('Replace pre-trained upsampler to new one...') else: raise RuntimeError('While copying the parameter named {}, ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}.' .format(name, own_state[name].size(), param.size())) elif strict: if name.find('tail') == -1: raise KeyError('unexpected key "{}" in state_dict' .format(name)) if strict: missing = set(own_state.keys()) - set(state_dict.keys()) if len(missing) > 0: raise KeyError('missing keys in state_dict: "{}"'.format(missing))
akashpalrecha/superres-deformable
src/model/cgc_rcan.py
cgc_rcan.py
py
8,589
python
en
code
1
github-code
6
70267230269
import os import sys import time import config import traceback cur_dir = os.path.dirname(os.path.abspath(__file__)) #sys.path.append(os.path.join(cur_dir, "..", "epyk-ui")) from epyk.core.js import Imports from epyk.core.py import PyRest PyRest.TMP_PATH = config.OUTPUT_TEMPS Imports.STATIC_PATH = "./../../static" # To reduce the scope of filters to generate filter = None # 'sprint' # category = None # 'slides' # 'angular, vue' SUCCESS = 0 FAILURE = 0 def process_folder(folder, results, main_folder=None, out_path=config.OUTPUT_PATHS_LOCALS_HTML): """ :param folder: :param main_folder: :return: """ global SUCCESS, FAILURE start, count_scripts, count_run_scripts = time.time(), 0, 0 if main_folder is not None: if isinstance(main_folder, list): script_path = os.path.join(cur_dir, os.path.join(*main_folder), folder) main_folder = ".".join(main_folder) else: script_path = os.path.join(cur_dir, main_folder, folder) else: script_path = os.path.join(cur_dir, folder) for file in os.listdir(script_path): if file.endswith(".py") and file != "__init__.py": count_scripts += 1 if filter is not None and not filter in file: if main_folder is None: continue if main_folder is not None and not filter in folder: continue script_name = file[:-3] try: if main_folder is not None: if main_folder == 'interactives': config.OUT_FILENAME = script_name else: config.OUT_FILENAME = "%s_%s_%s" % (main_folder, folder, script_name) mod = __import__("%s.%s.%s" % (main_folder, folder, script_name), fromlist=['object']) else: config.OUT_FILENAME = "%s_%s" % (folder, script_name) mod = __import__("%s.%s" % (folder, script_name), fromlist=['object']) output = mod.page.outs.html_file(path=out_path, name=config.OUT_FILENAME) results.append(output) #results.append("%s.html" % os.path.join(config.OUTPUT_PATHS_LOCALS_HTML, config.OUT_FILENAME)) count_run_scripts += 1 SUCCESS += 1 except Exception as err: traceback.print_exception(*sys.exc_info()) print("Error with: %s" % file) FAILURE =+ 1 if filter is None: print("Processing %s (%s / %s reports) in %s seconds" % (folder, count_run_scripts, count_scripts, time.time() - start)) results = [] if category is None or category == 'locals': for folder in os.listdir(os.path.join(cur_dir, 'locals')): if folder == "webscrapping" and filter is None: continue if os.path.isdir(os.path.join(cur_dir, 'locals', folder)) and folder != '__pycache__': process_folder(folder, results, main_folder='locals') # Run other type of reports for cat in ['dashboards', 'slides']: if category is None or category == cat: if filter is None: print("") print("processing - %s" % cat) process_folder(cat, results, out_path=config.OUTPUT_PATHS_LOCALS_SLIDES if cat == 'slides' else config.OUTPUT_PATHS_LOCALS_HTML) # Run other type of reports for cat in ['websites']: if category is None or category == cat: if filter is None: print("") print("processing - %s" % cat) for folder in os.listdir(os.path.join(cur_dir, 'websites', 'templates')): if os.path.isdir(os.path.join(cur_dir, 'websites', 'templates', folder)) and folder != '__pycache__': process_folder(folder, results, main_folder=['websites', 'templates']) for cat in ['interactives']: if category is None or category == cat: if filter is None: print("") print("processing - %s" % cat) process_folder("reports", results, main_folder=cat, out_path=config.OUTPUT_PATHS_LOCALS_INTERACTIVE) if category in ['angular', 'vue']: web_frameworks = { 'angular': { 'out_path': config.ANGULAR_APP_PATH, 'folder': 'src/app/apps', 'auto_route': True}, 'vue': { 'out_path': config.VUE_APP_PATH, 'folder': 'src/views', 'auto_route': True}, 'local': { 'out_path': config.OUTPUT_PATHS_LOCALS_TS, 'folder': category, 'auto_route': False}, } for cat in ['angular']: script_path = os.path.join("web", cat) mod = __import__("web.%s.exports" % cat, fromlist=['object']) # if web_frameworks[category]['out_path'] is not None: paths = web_frameworks[category] else: paths = web_frameworks['local'] for script in mod.REPORTS: script_name = script[-1][:-3] py_script = __import__("%s.%s" % (".".join(script[:-1]), script_name), fromlist=['object']) py_script.page.outs.publish(server=category, app_path=paths['out_path'], selector=script_name, target_folder=paths['folder'], auto_route=paths['auto_route']) # if category is None or category == 'locals': # process_folder('websites', results) # process_folder('interactives', results) # process_folder('dashboards', results) # process_folder('web', results) if filter is not None or category is not None: if filter is None: print("") print("Reports location:") for report in results: print(report) print("") print("Success: %s" % SUCCESS) print("failure: %s" % FAILURE)
epykure/epyk-templates
PacthRunner.py
PacthRunner.py
py
5,254
python
en
code
17
github-code
6
42367832431
# -*- coding: utf-8 -*- class StringUtils: @staticmethod def truncate(result, max_bytes: int): str_bytes = str(result).encode('utf-8', 'ignore') str_bytes_len = len(str_bytes) if str_bytes_len > max_bytes: truncated_len = str_bytes_len - max_bytes str_for_logging = str_bytes[:max_bytes] \ .decode('utf-8', 'ignore') result = f'{str_for_logging} ... ' \ f'({truncated_len} bytes truncated)' return result
rashmi43/platform-engine
asyncy/utils/StringUtils.py
StringUtils.py
py
523
python
en
code
0
github-code
6
20331901079
""" Assignment 2 Csoport: 524/2 Név: Velican László Azonosító: vlim2099 Segéd függvények amelyek meghívódnak a szerverben/kliensben vagy máashol """ import sympy import random #Generál egy kártya paklit két jokerrel amik még egyáltalán nincsenek összekeverve def generateDeck (): deck = []; for i in range(1,55): deck.append(i); return deck #összekever egy paraméterként kapott kártya paklit def shuffleDeck (deck): n = len(deck) for i in range(n-1,0,-1): j = random.randint(0,i+1) deck[i],deck[j] = deck[j],deck[i] return deck #generál egy seed-et a Blum-Blum-Shub függvényhez def generateSeed (): p=-1; q=-1; start = 999999999; while (p==-1): x = sympy.nextprime(start); if(x % 4 == 3): p=x; start = x+1 while (q==-1): x = sympy.nextprime(start); if(x % 4 == 3): q=x; start = x+1 n=p*q s = random.randint(1, n-1) return s; #beolvas a condig fileból nevet és kulcsot def beolvasEncryptalas(): configFile = open("config", "r") dataFromFile = configFile.read().splitlines() if (dataFromFile[0]=="BlumBlumShub"): dataFromFile[1] = int(dataFromFile[1]) else: listaString = dataFromFile[1] if (listaString[0]=='[' and listaString[len(listaString)-1]==']'): listaString = listaString[1:-1] deckLista = listaString.split(", "); deckLista = [int(i) for i in deckLista] dataFromFile[1] = deckLista; return dataFromFile;
Laccer01/Kriptografia
assign3/auxiliaryFunctions.py
auxiliaryFunctions.py
py
1,590
python
hu
code
0
github-code
6
14755245936
# Escribir un programa que reciba una cadena de caracteres y devuelva un diccionario con cada palabra que contiene y su frecuencia. # Escribir otra función que reciba el diccionario generado con la función anterior y devuelva una tupla con la palabra más repetida y su frecuencia. def longitud_palabras (text): """Función que cuenta el número de veces que aparece cada palabra en un texto. Parámetros: - text: Es una cadena de caracteres. Devuelve: Un diccionario con pares palabra:frecuencia con las palabras contenidas en el texto y su frecuencia. """ texto = text.split() palabras = {} for i in texto: if i in palabras: palabras[i] += 1 else: palabras[i] = 1 return palabras def más_repetido(palabras): max_palabra = '' max_frecuencia= 0 for palabra, frecuencia in palabras.items(): if frecuencia > max_frecuencia: max_palabra = palabra max_frecuencia = frecuencia return max_palabra, max_frecuencia texto = 'Como quieres que te quiera si el que quiero que me quiera no me quiere como quiero que me quiera' print(longitud_palabras (texto)) print(más_repetido(longitud_palabras (texto)))
gonrodri18/Python
funciones/ejercicio11.py
ejercicio11.py
py
1,238
python
es
code
0
github-code
6
39007586537
import os import shutil from rich.prompt import Prompt from rich.table import Table from create_folder import create_folder def delete_user(console): path = "./user-docs" user_to_del = str() user_path = str() while True: os.system('clear') console.print(f"[red]So you want to delete a user? Does that make you feel powerful?[/red]\n") # https://www.youtube.com/watch?v=m6xukx6hloE users = sorted(os.listdir(path)) print_users_table(console, users, path) selected_row = Prompt.ask(f"\nWhich unforunate soul do you wish to delete?\nEnter the [cyan]row #[/cyan] to " f"be deleted") if selected_row.isnumeric(): selected_row = int(selected_row) if 0 < selected_row <= len(users): user_to_del = users[selected_row - 1] if "-deleted" not in user_to_del: break else: prompt = Prompt.ask(f"\n[yellow]That user has already been deleted[/yellow]. Enter [cyan]any[" f"/cyan] key to try again, or [cyan]Q[/cyan] to quit to menu") if prompt.lower() == "q": return else: Prompt.ask(f"\n[yellow]{selected_row}[/yellow], is not a valid entry. Enter [cyan]any[/cyan] key to try " f"again") # create deleted_users folder if it doesn't already exist deleted_path = "deleted-users" name_test = os.path.exists(deleted_path) if not name_test: create_folder(console, deleted_path) # create the user folder for the deleted user in the deleted_users folder deleted_path = "deleted-users" name_test = os.path.exists(deleted_path + "/" + user_to_del) if not name_test: create_folder(console, deleted_path + "/" + user_to_del) # move the user files from user-docs to deleted-users user_path = path + "/" + user_to_del deleted_user_path = deleted_path + "/" + user_to_del user_files = os.listdir(user_path) for file in user_files: shutil.move(user_path + "/" + file, deleted_user_path + "/" + file) # rename deleted user folder in user-docs shutil.move(user_path, user_path + "-deleted") # print updated table users = sorted(os.listdir(path)) os.system('clear') print_users_table(console, users, path) Prompt.ask(f"\nUser [yellow]{user_to_del}[/yellow] has been deleted. Enter [cyan]any[/cyan] key to return to menu") def print_users_table(console, users, path): table = Table(title=f"[cyan]All Users[/cyan]") table.add_column("Row") table.add_column("User Name") table.add_column("# of Files") for user in users: user_path = path + "/" + user table.add_row(str(users.index(user) + 1), user, str(len(os.listdir(user_path)))) console.print(table)
mcsadri/automation
automation/delete_user.py
delete_user.py
py
2,920
python
en
code
0
github-code
6
15056144032
"""Production settings and globals.""" import yaml from os import environ from os.path import dirname, join from common import * ########## JSON CONFIGURATION SERVICE_NAME = 'djangoapp' CONFIG_ROOT = environ.get('CONFIG_ROOT', dirname(SITE_ROOT)) with open(join(CONFIG_ROOT, SERVICE_NAME) + ".auth.yaml") as auth_file: AUTH_TOKENS = yaml.load(auth_file) with open(join(CONFIG_ROOT, SERVICE_NAME) + ".env.yaml") as env_file: ENV_TOKENS = yaml.load(env_file) ########## END JSON CONFIGURATION ########## EMAIL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = ENV_TOKENS.get('EMAIL_HOST', None) EMAIL_PORT = ENV_TOKENS.get('EMAIL_PORT', 587) EMAIL_HOST_PASSWORD = AUTH_TOKENS.get('EMAIL_HOST_PASSWORD', None) EMAIL_HOST_USER = AUTH_TOKENS.get('EMAIL_HOST_USER', None) EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME EMAIL_USE_TLS = True SERVER_EMAIL = ENV_TOKENS.get('SERVER_EMAIL', '[email protected]') ########## END EMAIL CONFIGURATION ########## DATABASE CONFIGURATION DATABASES = AUTH_TOKENS['DATABASES'] ########## END DATABASE CONFIGURATION ########## CACHE CONFIGURATION CACHES = AUTH_TOKENS['CACHES'] ########## END CACHE CONFIGURATION ########## CELERY CONFIGURATION # See: http://docs.celeryproject.org/en/latest/configuration.html#broker-transport # BROKER_TRANSPORT = 'amqplib' # Set this number to the amount of allowed concurrent connections on your AMQP # provider, divided by the amount of active workers you have. # For example, if you have the 'Little Lemur' CloudAMQP plan (their free tier), # they allow 3 concurrent connections. So if you run a single worker, you'd # want this number to be 3. If you had 3 workers running, you'd lower this # number to 1, since 3 workers each maintaining one open connection = 3 # connections total. # See: http://docs.celeryproject.org/en/latest/configuration.html#broker-pool-limit # BROKER_POOL_LIMIT = 3 # See: http://docs.celeryproject.org/en/latest/configuration.html#broker-connection-max-retries # BROKER_CONNECTION_MAX_RETRIES = 0 # See: http://docs.celeryproject.org/en/latest/configuration.html#broker-url # BROKER_URL = environ.get('RABBITMQ_URL') or environ.get('CLOUDAMQP_URL') # this should come from the auth.json # See: http://docs.celeryproject.org/en/latest/configuration.html#celery-result-backend # CELERY_RESULT_BACKEND = 'amqp' ########## END CELERY CONFIGURATION ########## STORAGE CONFIGURATION # See: http://django-storages.readthedocs.org/en/latest/index.html INSTALLED_APPS += ( 'storages', ) # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings DEFAULT_FILE_STORAGE = AUTH_TOKENS.get('STATICFILES_STORAGE', 'storages.backends.s3boto.S3BotoStorage') # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings # AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings AWS_ACCESS_KEY_ID = AUTH_TOKENS.get('AWS_ACCESS_KEY_ID', 'something') AWS_SECRET_ACCESS_KEY = AUTH_TOKENS.get('AWS_SECRET_ACCESS_KEY', 'secret') AWS_STORAGE_BUCKET_NAME = AUTH_TOKENS.get('AWS_STORAGE_BUCKET_NAME', 'your_bucket') AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False # AWS cache settings, don't change unless you know what you're doing: AWS_EXPIREY = 60 * 60 * 24 * 7 AWS_HEADERS = { 'Cache-Control': 'max-age=%d, s-maxage=%d, must-revalidate' % ( AWS_EXPIREY, AWS_EXPIREY ) } # Serving the files from S3 causes a No 'Access-Control-Allow-Origin' or problems with require and the /static/ path # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_ROOT = ENV_TOKENS.get('STATIC_ROOT', STATIC_ROOT) ########## END STORAGE CONFIGURATION ########## COMPRESSION CONFIGURATION COMPRESS_ENABLED = False # See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE COMPRESS_OFFLINE = True # See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_STORAGE COMPRESS_STORAGE = DEFAULT_FILE_STORAGE # See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_CSS_FILTERS COMPRESS_CSS_FILTERS += [ 'compressor.filters.cssmin.CSSMinFilter', ] # See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_JS_FILTERS COMPRESS_JS_FILTERS += [ 'compressor.filters.jsmin.JSMinFilter', ] ########## END COMPRESSION CONFIGURATION ########## SECRET CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = AUTH_TOKENS.get('SECRET_KEY', SECRET_KEY) ########## END SECRET CONFIGURATION ########## DOMAIN CONFIGURATION ALLOWED_HOSTS = ENV_TOKENS.get('ALLOWED_HOSTS', ['*']) ########## END DOMAIN CONFIGURATION
eduNEXT/django-example-app
app/settings/prod.py
prod.py
py
4,929
python
en
code
1
github-code
6
26115632417
import re from collections import Counter import configuration def count_requests_with_server_error(): regex = re.compile(r'\d+\.\d+\.\d+\..+[A-Z]{3,4} .+HTTP.+" 5.. \d+.+$', re.MULTILINE) with open(configuration.repo_root() + '/access.log', 'r') as file: ip = [match.split()[0] for match in re.findall(regex, file.read())] output = list( zip( Counter(ip).keys(), Counter(ip).values() ) ) output.sort( key=lambda elem: elem[1], reverse=True ) output = [ { 'ip_address': ip_address, 'count': count } for ip_address, count in output[:5] ] configuration.report_result( header='Clients with the highest amount of failed requests (code 5xx)', output=output, file_to_write='count_server_based_errors' ) count_requests_with_server_error()
sh4rkizz/2022-1-QAPYTHON-VK-A-Mahonin
homework5/py_scripts/clients_with_most_server_based_errors.py
clients_with_most_server_based_errors.py
py
993
python
en
code
0
github-code
6
25209339138
import RPi.GPIO as GPIO, time import sys import threading import queue stepPin = 10 dirPin = 12 enablePin = 8 count = 0 GPIO.setmode(GPIO.BOARD) GPIO.setup(stepPin, GPIO.OUT) #STEP GPIO.setup(dirPin, GPIO.OUT) #DIR GPIO.setup(enablePin, GPIO.OUT) #ENABLE GPIO.setup(37, GPIO.IN) #input GPIO.output(enablePin, True) p = GPIO.PWM(stepPin, 7000) def SpinMotor(dire): GPIO.output(enablePin, False) p.ChangeFrequency(500) GPIO.output(dirPin,dire) p.start(1) print("test") time.sleep(0.01) return True def runner(run_queue): running = False global count while True: try: speed = run_queue.get_nowait() if speed==0: running = False elif speed<0: running = True dire = 0 elif speed>0: running = True dire = 1 except queue.Empty: pass if(running): GPIO.output(dirPin,dire) GPIO.output(enablePin, False) GPIO.output(stepPin, True) time.sleep(abs(0.001/speed)) GPIO.output(stepPin, False) time.sleep(abs(0.001/speed)) count+=1 def SpinMotorSteps(steps): GPIO.output(enablePin, False) count = 0 while count < steps: GPIO.output(stepPin, True) time.sleep(0.001) GPIO.output(stepPin, False) time.sleep(0.001) count+=1 def testME(steps): count = 0 while count < steps: print("test") time.sleep(1) count+=1 run_queue = queue.Queue() threading.Thread(target=runner, args=(run_queue,)).start() while True: dir_input = input("Enter your dir: ") if dir_input == "F": SpinMotor(True) elif dir_input == "B": SpinMotor(False) elif dir_input == "test": motorSpins = threading.Thread(target=SpinMotorSteps,args=(10000,)) motorSpins.start() elif dir_input == "stop": p.stop() dir_input = "" elif dir_input == "SHOW": print(count) GPIO.output(enablePin, True) elif dir_input == "RUN1": run_queue.put(50) elif dir_input == "RUN2": run_queue.put(-10) elif dir_input == "NORUN": run_queue.put(0) elif dir_input == "shutdown": p.stop() GPIO.cleanup() break
YannickAaron/WebUIStepperMotorControl
old/test.py
test.py
py
2,378
python
en
code
0
github-code
6
38030608194
#!/usr/bin/env python3 import rclpy from crazyflie_msgs.msg import AttitudeCommand from .crazyradio.base_control_node import BaseControlNode import math def convert_thrust(in_: float): """ - converts scalar from 2.5 to 10 to range of 10001 to 60000 - returns 0 if in_ is 0 - returns int """ thrust_in = in_ if in_ <= 10 else 10 thrust_in = thrust_in - 2.5 if thrust_in > 2.5 else 0 thrust_in = 10001 + thrust_in * ((42000 - 10001) / (7.5)) if thrust_in != 0 else 0 return int(thrust_in) def radian_to_degree(in_: float): return float((in_ / (math.pi)) * 360) class AttitudeControlNode(BaseControlNode): _is_ready: bool """Is drone ready to accept attitude commands.""" def __init__(self): super().__init__() self._is_ready = False # +++ add callbacks self._synced_cf.cf.fully_connected.add_callback(self._fully_connected_motor_level) self._synced_cf.cf.disconnected.add_callback(self._disconnected) self._synced_cf.cf.connection_failed.add_callback(self._connection_failed) # +++ open link self._open_link() # +++ initialise subscription self.__initialize_subscription() def _fully_connected_motor_level(self, link_uri: str): super()._fully_connected(link_uri) self._motor_control.set_custom_callback(self._motor_level_control_callback) self._motor_control.disable_motor_control() def __initialize_subscription(self): # +++ subscribe to attitude commands self.subscription = self.create_subscription( AttitudeCommand, 'crazyflie/pid/attitude_controller', self.set_attitude_callback, 1) def set_attitude_callback(self, attitude_msg: AttitudeCommand): """ Set attitude """ thrust_in = convert_thrust(attitude_msg.thurst) if self._is_connected and self._is_ready: self.get_logger().debug('Received thrust: ' + str(attitude_msg.thurst)) self.get_logger().debug("Received pitch: " + str(attitude_msg.pitch)) self.get_logger().debug("Received roll: " + str(attitude_msg.roll)) self.get_logger().debug("Received yaw: " + str(attitude_msg.yaw)) self._synced_cf.cf.commander.send_setpoint( radian_to_degree(attitude_msg.pitch), radian_to_degree(attitude_msg.roll), radian_to_degree(attitude_msg.yaw), thrust_in) def _motor_level_control_callback(self, name: str, value: any): """ Called when motor level control is debugged """ self._is_ready = True self.get_logger().debug("motor level control callback: " + name + str(value)) def main(args=None): rclpy.init(args=args) node = AttitudeControlNode() try: rclpy.spin(node) finally: node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()
AlboAlby00/CrazyflieControllers
crazyflie_ros2_driver/crazyflie_ros2_driver/crazyflie_hw_attitude_driver.py
crazyflie_hw_attitude_driver.py
py
3,051
python
en
code
0
github-code
6
12791274360
# -*- coding: utf-8 -*- import requests import time import datetime import sys import boto3 from boto3.dynamodb.conditions import Key, Attr from botocore.exceptions import ClientError import json import telegram from PIL import Image from io import BytesIO import asyncio import re import os import top_holding bot_id = os.environ['BOT_ID'] chat_id = os.environ['CHAT_ID'] img_url = os.environ['IMG_URL'] bot = telegram.Bot(token=bot_id) def new_sticker_set(sticker_id): url = 'http://seekvectorlogo.com/wp-content/uploads/2019/10/ark-invest-etfs-vector-logo.png' web_im = requests.get(url).content im = Image.open( BytesIO(web_im) ) width = int(im.size[0]) height = int(im.size[1]) if width >= height: adjustHeight = int(512 / width * height) im_resize = im.resize((512, adjustHeight)) else: adjustWidth = int(512 / height * width) im_resize = im.resize((adjustWidth, 512)) filename = f"/tmp/{sticker_id}.png" im_resize.save(filename) try: bot.create_new_sticker_set( chat_id , f'{sticker_id}_by_Anson_bot' , f'{sticker_id} Trading Desk' , open(filename,'rb') , '📈' , timeout=20 ) except Exception as e: return False return True async def reSize(ticker,sticker_id,act): # Change Foreign Ticker regex = r"([0-9]{4,})([A-Z]{2,})" matches = re.findall(regex, ticker, re.MULTILINE) if matches: if matches[0][1] == 'JP': # Japan to Tokyo ticker = matches[0][0] + '.T' else: ticker = matches[0][0] + '.'+ matches[0][1] url = f'{img_url}?ticker={ticker}&t='+str(time.time()) web_im = requests.get(url).content im = Image.open( BytesIO(web_im) ) width = int(im.size[0]) height = int(im.size[1]) if width >= height: adjustHeight = int(512 / width * height) im_resize = im.resize((512, adjustHeight)) else: adjustWidth = int(512 / height * width) im_resize = im.resize((adjustWidth, 512)) filename = f"/tmp/{sticker_id}{ticker}.png" im_resize.save(filename) emoji = '📈' if act == 'Buy': emoji = '📈' else: emoji = '📉' bot.add_sticker_to_set( chat_id , f'{sticker_id}_by_Anson_bot' , open(filename,'rb') , emoji , timeout=20 ) # print('done') return True def main(sticker_id,ticker_list): # https://github.com/Sea-n/LINE-stickers/blob/master/index.js asyncio.set_event_loop(asyncio.new_event_loop()) tasks = [] loop = asyncio.get_event_loop() task = loop.create_task(reSize(sticker_id,sticker_id,'Buy')) tasks.append(task) for act in ticker_list: # ticker = SQ # sticker_id = ARKF # act = sell or buy for ticker in ticker_list[act]: task = loop.create_task(reSize(ticker,sticker_id,act)) tasks.append(task) if tasks: loop.run_until_complete(asyncio.wait(tasks)) loop.close() sticker_line = f"https://t.me/addstickers/{sticker_id}_by_Anson_bot" top_holding.holding_graph(sticker_id) bot.add_sticker_to_set( chat_id , f'{sticker_id}_by_Anson_bot' , open(f'/tmp/{sticker_id}_chart.png','rb') , '📈' , timeout=20 ) def get_old(sticker_id): try: sets = bot.get_sticker_set(name=f'{sticker_id}_by_Anson_bot') except Exception as e: return False return sets def clear_old(sticker_list): # Keep logo and delete others sticker_list = sticker_list['stickers'][1:] for stick in sticker_list: result = bot.delete_sticker_from_set(stick['file_id']) pass def lambda_handler(event, context): sticker_id = event['sticker_id'] sticker_list = event['sticker_list'] if not sticker_id: return {'statusCode': 400} old_list = get_old(sticker_id) if not old_list: new_sticker_set(sticker_id) else: clear_old(old_list) main(sticker_id,sticker_list) return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') }
EddieKuo723/ARK-Invest-Trading-Desk
ARK_Sticker_Set/lambda_function.py
lambda_function.py
py
4,404
python
en
code
1
github-code
6
6834567910
from typing import Optional, Tuple, Union import torch.nn as nn from diffusers.models import UNet2DConditionModel from diffusers.models.unet_2d_blocks import UNetMidBlock2DCrossAttn from diffusers.models.embeddings import Timesteps, TimestepEmbedding from diffusers.configuration_utils import register_to_config from blocks import get_down_block, get_up_block class VideoLDM(UNet2DConditionModel): @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock2D", # -> VideoLDMDownBlock "CrossAttnDownBlock2D", # -> VideoLDMDownBlock "CrossAttnDownBlock2D", # -> VideoLDMDownBlock "DownBlock2D", ), mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn", up_block_types: Tuple[str] = ( "UpBlock2D", "CrossAttnUpBlock2D", # -> VideoLDMUpBlock "CrossAttnUpBlock2D", # -> VideoLDMUpBlock "CrossAttnUpBlock2D", # -> VideoLDMUpBlock ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: Union[int, Tuple[int]] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: Union[int, Tuple[int]] = 1280, encoder_hid_dim: Optional[int] = None, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, addition_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", resnet_skip_time_act: bool = False, resnet_out_scale_factor: int = 1.0, time_embedding_type: str = "positional", time_embedding_dim: Optional[int] = None, time_embedding_act_fn: Optional[str] = None, timestep_post_act: Optional[str] = None, time_cond_proj_dim: Optional[int] = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, projection_class_embeddings_input_dim: Optional[int] = None, class_embeddings_concat: bool = False, mid_block_only_cross_attention: Optional[bool] = None, cross_attention_norm: Optional[str] = None, addition_embed_type_num_heads=64, ): super().__init__() self.sample_size = sample_size # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." ) if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types): raise ValueError( f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}." ) if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}." ) if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." ) if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): raise ValueError( f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." ) # input conv_in_padding = (conv_in_kernel - 1) // 2 self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding ) # time if time_embedding_type == "fourier": time_embed_dim = time_embedding_dim or block_out_channels[0] * 2 if time_embed_dim % 2 != 0: raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.") self.time_proj = GaussianFourierProjection( time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos ) timestep_input_dim = time_embed_dim elif time_embedding_type == "positional": time_embed_dim = time_embedding_dim or block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] else: raise ValueError( f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`." ) self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, post_act_fn=timestep_post_act, cond_proj_dim=time_cond_proj_dim, ) if encoder_hid_dim is not None: self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim) else: self.encoder_hid_proj = None # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) elif class_embed_type == "projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" ) # The projection `class_embed_type` is the same as the timestep `class_embed_type` except # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings # 2. it projects from an arbitrary input dimension. # # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. # As a result, `TimestepEmbedding` can be passed arbitrary vectors. self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif class_embed_type == "simple_projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" ) self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) else: self.class_embedding = None if addition_embed_type == "text": if encoder_hid_dim is not None: text_time_embedding_from_dim = encoder_hid_dim else: text_time_embedding_from_dim = cross_attention_dim self.add_embedding = TextTimeEmbedding( text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads ) elif addition_embed_type is not None: raise ValueError(f"addition_embed_type: {addition_embed_type} must be None or 'text'.") if time_embedding_act_fn is None: self.time_embed_act = None elif time_embedding_act_fn == "swish": self.time_embed_act = lambda x: F.silu(x) elif time_embedding_act_fn == "mish": self.time_embed_act = nn.Mish() elif time_embedding_act_fn == "silu": self.time_embed_act = nn.SiLU() elif time_embedding_act_fn == "gelu": self.time_embed_act = nn.GELU() else: raise ValueError(f"Unsupported activation function: {time_embedding_act_fn}") self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): if mid_block_only_cross_attention is None: mid_block_only_cross_attention = only_cross_attention only_cross_attention = [only_cross_attention] * len(down_block_types) if mid_block_only_cross_attention is None: mid_block_only_cross_attention = False if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block[i], in_channels=input_channel, out_channels=output_channel, temb_channels=blocks_time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim[i], attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock2DCrossAttn": self.mid_block = UNetMidBlock2DCrossAttn( in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim[-1], attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, ) elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn": self.mid_block = UNetMidBlock2DSimpleCrossAttn( in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, cross_attention_dim=cross_attention_dim[-1], attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, resnet_time_scale_shift=resnet_time_scale_shift, skip_time_act=resnet_skip_time_act, only_cross_attention=mid_block_only_cross_attention, cross_attention_norm=cross_attention_norm, ) elif mid_block_type is None: self.mid_block = None else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the images self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) reversed_layers_per_block = list(reversed(layers_per_block)) reversed_cross_attention_dim = list(reversed(cross_attention_dim)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=reversed_layers_per_block[i] + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=blocks_time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=reversed_cross_attention_dim[i], attn_num_head_channels=reversed_attention_head_dim[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out if norm_num_groups is not None: self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) if act_fn == "swish": self.conv_act = lambda x: F.silu(x) elif act_fn == "mish": self.conv_act = nn.Mish() elif act_fn == "silu": self.conv_act = nn.SiLU() elif act_fn == "gelu": self.conv_act = nn.GELU() else: raise ValueError(f"Unsupported activation function: {act_fn}") else: self.conv_norm_out = None self.conv_act = None conv_out_padding = (conv_out_kernel - 1) // 2 self.conv_out = nn.Conv2d( block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding )
srpkdyy/VideoLDM
videoldm.py
videoldm.py
py
16,886
python
en
code
76
github-code
6
34352982765
import cv2 #load pre trained data trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') #choose image to detect face in #img = cv2.imread('52-05.jpg') #img = cv2.imread('img2p.jpg') webcam = cv2.VideoCapture(1) #detect face in video #key = cv2.waitKey(1) #iterate over frames while True: successful_frame_read, frame = webcam.read() #get current frame #make it grayscale gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #cv2.waitKey(1) #detect faces face_coordinates = trained_face_data.detectMultiScale(gray_img) # print(face_coordinates) #draw rectangle around face for (x, y, w, h) in face_coordinates: cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 255, 0), 3) #show image cv2.imshow('face detector', frame) key = cv2.waitKey(1) #stop if q is pressed if key==81 or key ==113: break #release the videocapture object webcam.release() print('code completed')
mirethy/cl-python-opencv-facedetect
face.py
face.py
py
959
python
en
code
0
github-code
6
6187356527
#!/usr/bin/env python3 """ A function that uses the requests module to obtain the HTML content of a particular URL and return it """ import redis import requests from functools import wraps r = redis.Redis() def url_access_count(method): """ A decorator for the get_page function. """ @wraps(method) def wrapper(url): """wrap decorated function""" key = "cached:" + url cached_value = r.get(key) if cached_value: return cached_value.decode("utf-8") key_count = "count:" + url html_content = method(url) r.incr(key_count) r.set(key, html_content, ex=10) r.expire(key, 10) return html_content return wrapper @url_access_count def get_page(url: str) -> str: """ Obtain the HTML content, track the number of accesses, and cache the result with a 10-second expiration. """ results = requests.get(url) key_count = "count:" + url count = r.get(key_count).decode("utf-8") print(count) return results.text if __name__ == "__main__": get_page('http://google.com') print("OK")
Cyril-777/alx-backend-storage
0x02-redis_basic/web.py
web.py
py
1,141
python
en
code
0
github-code
6
25507482715
# Document : 1 HelloWorld.py # Created on: 13-07-2019, 06:05:07 PM # Author : Nivesh-GC # Udemy: Complete Python BootCamp # https://www.youtube.com/watch?v=DjEuROpsvp4 # Setting up a Python Development Environment in Atom print('Hello World of Atom') a = 50 b = 50 c = a + b d = type(c) print(d)
cnivesh009/udemy-python
1 HelloWorld.py
1 HelloWorld.py
py
302
python
en
code
0
github-code
6
24013644968
import warnings from dataclasses import dataclass from typing import List, Optional import keopscore import torch from pykeops.torch import Genred from falkon.mmv_ops.utils import _get_gpu_info, _start_wait_processes, create_output_mat from falkon.options import BaseOptions, FalkonOptions from falkon.utils import decide_cuda from falkon.utils.helpers import calc_gpu_block_sizes, sizeof_dtype from falkon.utils.stream_utils import sync_current_stream @dataclass(frozen=True) class ArgsFmmv: X1: torch.Tensor X2: torch.Tensor v: torch.Tensor other_vars: List[torch.Tensor] out: torch.Tensor gpu_ram: float backend: str function: callable def _decide_backend(opt: BaseOptions, num_dim: int) -> str: """Switch between CPU and GPU backend for KeOps""" if not decide_cuda(opt): return "CPU" else: return "GPU_1D" def _estimate_split(N, M, D, T, R, ds): """Estimate the splits along dimensions N and M for a MVM to fit in memory The operations consist of computing the product between a kernel matrix (from a N*D and a M*D matrix) and a 'vector' of shape M*T This typically requires storage of the input and output matrices, which occupies (M + N)*(D + T) memory locations plus some intermediate buffers to perform computations. TODO: It is not clear how much intermediate memory KeOps requires; the only thing that is certain is that it is quadratic in D. For now we sidestep this issue by using a smaller R than what is actually available in GPU memory. This function calculates the split along N and M into blocks of size n*m so that we can compute the kernel-vector product between such blocks and still fit in GPU memory. Parameters ----------- - N : int The first dimension of the kernel matrix - M : int The second dimension of the kernel matrix - D : int The data dimensionality - T : int The number of output columns - R : float The amount of memory available (in bytes) - ds : int The size in bytes of each element in the data matrices (e.g. 4 if the data is in single precision). Returns -------- - n : int The block size to be used along the first dimension - m : int The block size along the second dimension of the kernel matrix Raises ------- RuntimeError If the available memory `R` is insufficient to store even the smallest possible input matrices. This may happen if `D` is very large since we do not perform any splitting along `D`. Notes ------ We find 'good' values of M, N such that N*(D+T) + M*(D+T) <= R/ds """ R = R / ds # We have a linear equation in two variables (N, M) slope = -1 intercept = R / (D + T) slack_points = 10 # We try to pick a point at the edges such that only one kind of split # is necessary if N < intercept - 1: M = min(M, intercept + slope * N) elif M < intercept - 1: N = min(N, intercept + slope * M) else: # All points on the slope such that N, M > 0 are possible N = intercept - slack_points - 1 M = intercept + slope * N if N <= 0 or M <= 0: raise RuntimeError("Insufficient available GPU memory (available %.2fGB)" % (R * ds / 2**30)) return int(N), int(M) def _single_gpu_method(proc_idx, queue, device_id): a: ArgsFmmv = queue.get() backend = a.backend X1 = a.X1 X2 = a.X2 v = a.v oout = a.out other_vars = a.other_vars fn = a.function R = a.gpu_ram N, D = X1.shape M = X2.shape[0] T = v.shape[1] device = torch.device(f"cuda:{device_id}") # Second round of subdivision (only if necessary due to RAM constraints) n, m = _estimate_split(N, M, D, T, R, sizeof_dtype(X1.dtype)) other_vars_dev = [ov.to(device, copy=False) for ov in other_vars] out_ic = oout.device.index == device_id # Process the two rounds of splitting with a nested loop. with torch.cuda.device(device_id), torch.autograd.inference_mode(): for mi in range(0, M, m): ml = min(m, M - mi) if ml != M and mi > 0: # Then we must create a temporary output array out = torch.empty_like(oout) else: out = oout cX2 = X2[mi : mi + ml, :].to(device, copy=False) cv = v[mi : mi + ml, :].to(device, copy=False) for ni in range(0, N, n): nl = min(n, N - ni) cX1 = X1[ni : ni + nl, :].to(device, copy=False) cout = out[ni : ni + nl, :].to(device, copy=False) variables = [cX1, cX2, cv] + other_vars_dev fn(*variables, out=cout, device_id=device_id, backend=backend) if not out_ic: out[ni : ni + nl, :].copy_(cout) if ml != M and mi > 0: oout.add_(out) return oout def run_keops_mmv( X1: torch.Tensor, X2: torch.Tensor, v: torch.Tensor, other_vars: List[torch.Tensor], out: Optional[torch.Tensor], formula: str, aliases: List[str], axis: int, reduction: str = "Sum", opt: Optional[FalkonOptions] = None, ) -> torch.Tensor: if opt is None: opt = FalkonOptions() # Choose backend N, D = X1.shape T = v.shape[1] backend = _decide_backend(opt, D) data_devs = [X1.device, X2.device, v.device] if any(ddev.type == "cuda" for ddev in data_devs) and (not backend.startswith("GPU")): warnings.warn( "KeOps backend was chosen to be CPU, but GPU input tensors found. " "Defaulting to 'GPU_1D' backend. To force usage of the CPU backend, " "please pass CPU tensors; to avoid this warning if the GPU backend is " "desired, check your options (i.e. set 'use_cpu=False')." ) backend = "GPU_1D" differentiable = any([X1.requires_grad, X2.requires_grad, v.requires_grad] + [o.requires_grad for o in other_vars]) comp_dev_type = backend[:3].lower().replace("gpu", "cuda") # 'cpu' or 'cuda' keopscore.config.config.use_cuda = comp_dev_type == "cuda" # workaround for keops issue#248 out = create_output_mat( out, data_devs, is_sparse=False, shape=(N, T), dtype=X1.dtype, comp_dev_type=comp_dev_type, other_mat=X1, output_stride="C", ) rec_multVar_highdim = None if D > 100: rec_multVar_highdim = 1 fn = Genred( formula, aliases, reduction_op=reduction, axis=axis, dtype_acc=opt.keops_acc_dtype, sum_scheme=opt.keops_sum_scheme, rec_multVar_highdim=rec_multVar_highdim, ) if differentiable: # For differentiable inputs we don't split, since we don't know how to # split the backward pass. out = fn(X1, X2, v, *other_vars, out=out, backend=backend) elif comp_dev_type == "cpu" and all(ddev.type == "cpu" for ddev in data_devs): # incore CPU out = fn(X1, X2, v, *other_vars, out=out, backend=backend) elif comp_dev_type == "cuda" and all(ddev.type == "cuda" for ddev in data_devs): # incore CUDA device = data_devs[0] with torch.cuda.device(device): sync_current_stream(device) out = fn(X1, X2, v, *other_vars, out=out, backend=backend) else: # cpu data, gpu computations: out-of-core # slack should be high due to imprecise memory usage estimates for keops gpu_info = _get_gpu_info(opt, slack=opt.keops_memory_slack) block_sizes = calc_gpu_block_sizes(gpu_info, N) args = [] # Arguments passed to each subprocess for i, g in enumerate(gpu_info): # First round of subdivision bwidth = block_sizes[i + 1] - block_sizes[i] if bwidth <= 0: continue args.append( ( ArgsFmmv( X1=X1.narrow(0, block_sizes[i], bwidth), X2=X2, v=v, out=out.narrow(0, block_sizes[i], bwidth), other_vars=other_vars, function=fn, backend=backend, gpu_ram=g.usable_memory, ), g.Id, ) ) _start_wait_processes(_single_gpu_method, args) return out
FalkonML/falkon
falkon/mmv_ops/keops.py
keops.py
py
8,589
python
en
code
157
github-code
6
70374444349
import os import shutil import sys import pytest import torch from ivory.core.client import create_client @pytest.fixture(scope="module") def runs(): sys.path.insert(0, os.path.abspath("examples")) client = create_client(directory="examples") runs = [] for name in ["tensorflow", "nnabla", "torch2"]: run = client.create_run(name, epochs=5, batch_size=10, shuffle=False) runs.append(run) run_tf, run_nn, run_torch = runs run_nn.model.build( run_nn.trainer.loss, run_nn.datasets.train, run_nn.trainer.batch_size ) run_nn.optimizer.set_parameters(run_nn.model.parameters()) ws_tf = run_tf.model.weights ws_nn = run_nn.model.parameters().values() ws_torch = run_torch.model.parameters() for w_tf, w_nn, w_torch in zip(ws_tf, ws_nn, ws_torch): w_nn.data.data = w_tf.numpy() w_torch.data = torch.tensor(w_tf.numpy().T) yield dict(zip(["tf", "nn", "torch"], runs)) del sys.path[0] if os.path.exists("examples/mlruns"): shutil.rmtree("examples/mlruns")
daizutabi/ivory
tests/libs/conftest.py
conftest.py
py
1,061
python
en
code
0
github-code
6
26344548844
from unittest import TestCase import glob from lxml import etree class ValidationError(Exception): pass class TestSampleFileValidation(TestCase): def test_ukrdc_sample_files(self): # For each sample file for sample_path in glob.glob("sample_files/ukrdc/*.xml"): # Run as a subtest with self.subTest(msg=sample_path): # Open the schema and sample files for reading with open( "schema/ukrdc/UKRDC.xsd", "r", encoding="utf-8" ) as schema_file, open( sample_path, "r", encoding="utf-8" ) as sample_file: # Create a new schema object to track errors for this file xml_schema = etree.XMLSchema( etree.parse( schema_file, parser=None, ) ) # Try validating the sample file against the schema try: xml_doc = etree.parse(sample_file, None) xml_schema.assertValid(xml_doc) # Initially catch errors to allow reporting multiple issues in one file except etree.DocumentInvalid as e: tree = etree.ElementTree(xml_doc.getroot()) # Print all errors print("Validation error(s):") for error in xml_schema.error_log: print(" Line {}: {}".format(error.line, error.message)) for e in tree.xpath(".//*"): if error.line == e.sourceline: xml_path = tree.getpath(e) print(xml_path) break # Raise an exception to fail the test and report the full error list raise ValidationError( f"{len(xml_schema.error_log)} validation error(s) in {sample_path}. See full output above for details." ) from e
renalreg/resources
tests/test_sample_files.py
test_sample_files.py
py
2,213
python
en
code
0
github-code
6
11093803614
from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.first_view, name='first_view'), url(r'^uimage/$', views.uimage, name='uimage'), url(r'^dface/$', views.dface, name='dface'), url(r'^crop/$', views.crop, name='crop'), url(r'^backgroundsubtract/$', views.backgroundsubtract, name='backgroundsubtract'), url(r'^binarize/$', views.binarize, name='binarize'), url(r'^webcam/$', views.webcam, name='webcam'), url(r'^stream/$', views.stream, name='stream'), url(r'^capture/$', views.capture, name='capture'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
neemiasbsilva/django-api-computer-vision
pipeline/urls.py
urls.py
py
753
python
en
code
3
github-code
6
71877606587
from urllib.parse import quote_plus from bs4 import BeautifulSoup #selenium : web test에 사용되는 프레임워크, webdriver API를 통해 렌더링이 완료된 후의 DOM 결과물에 접근할 수 있음(브라우저 제어가 필요) #pip install selenium #직접 브라우저를 제어하기 때문에 header값 없이도 크롤링이 가능 #여기선 Chrome 사용 webdriver 설치 : https://chromedriver.chromium.org/downloads from selenium import webdriver baseUrl = 'https://www.google.com/search?q=' plusUrl = input('검색어 입력 : ') resultUrl = baseUrl + quote_plus(plusUrl) #chrome webDriver 위치가 현재 개발폴더 위치와 다르면 Chrome({경로})와 같이 사용 driver = webdriver.Chrome() #브라우저가 열리고 입력된 url로 이동 driver.get(resultUrl) html = driver.page_source soup = BeautifulSoup(html) #select로 가져올 경우 list형식으로 가져옴 r = soup.select('.r') for i in r: #list object의 경우엔 text를 가져올 수 없음, 텍스트를 불러오기 위해 select_on 사용 print(i.select_one('.LC20lb.DKV0Md').text) #print(i.select_one('.iUh30.bc').text) print(i.a.attrs['href'], '\n') driver.close()
BrokenMental/Python-Study
googleCrawl.py
googleCrawl.py
py
1,197
python
ko
code
0
github-code
6
22270481857
import Classes as Cls import scr.FormatFunctions as Format import scr.SamplePathClasses as PathCls import scr.FigureSupport as Figs import scr.StatisticalClasses as Stat import P1 as P1 alpha = P1.alpha #Find comparative outcome def get_compare(sim_output_fair, sim_output_unfair): increase = Stat.DifferenceStatIndp( name='Increase in Reward', x=sim_output_fair.get_rewards(), y_ref=sim_output_unfair.get_rewards() ) # estimate and CI estimate_CI = Format.format_estimate_interval( estimate=increase.get_mean(), interval=increase.get_t_CI(alpha=P1.alpha), deci=1 ) print("Average increase in survival time (years) and {:.{prec}%} confidence interval:".format(1 - P1.alpha, prec=0), estimate_CI)
etraskyoung/HPM573S18_Trask-Young_HW8
SteadySupport.py
SteadySupport.py
py
783
python
en
code
0
github-code
6
24618666253
from django.core.mail import send_mail from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Count from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.http import require_POST from django.views.generic import ListView from taggit.models import Tag from django.contrib.postgres.search import SearchVector from django.contrib import messages import djangoProject.settings from .forms import EmailPostForm, CommentForm, SearchForm from .models import Post class PostListView(ListView): """ Альтернативное представление списка постов """ # Вместо # определения атрибута queryset мы могли бы указать model=Post, и Django # сформировал бы для нас типовой набор запросов Post.objects.all() queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def post_list(request, tag_slug=None): post_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) post_list = post_list.filter(tags__in=[tag]) # создаем объект класс Paginator с числом объектов на 1 странице paginator = Paginator(post_list, 3) # вытягиваем значение параметра page из GET запроса, если он отсутствует, выставляем дефолтное 1 # MultiValueDict???? page_number = request.GET.get('page', 1) # получаем объекты для указанной страницы try: posts = paginator.page(page_number) except EmptyPage: posts = paginator.page(1) except PageNotAnInteger: posts = paginator.page(paginator.num_pages) print(posts.__dict__) return render(request, 'blog/post/list.html', {'posts': posts, 'tag': tag}) def post_detail(request, post, year, month, day): print('мы тут с ', request.user) post = get_object_or_404(Post, status=Post.Status.PUBLISHED, slug=post, publish__year=year, publish__month=month, publish__day=day) # Список активных комментариев к этому посту comments = post.comments.filter(active=True) # Форма для комментирования пользователями form = CommentForm() # список схожих постов # values_list возвращает кортеж со значением заданных полей post_tags_ids = post.tags.values_list('id', flat=True) # модификатор __in -- значение должно быть в указанном списке кортоже квересете similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) # annotate создает переменную в который хранит результат # агрегированного выражения над 'tag' # названием переменной выступает ключ -- same_tags similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4] return render(request, 'blog/post/details.html', {'post': post, 'comments': comments, 'form': form, 'similar_posts': similar_posts}) # представлени для 1)отображает изначальные данные на странице # 2)обработка представленных для валидации данных def post_share(request, post_id): # функция сокращенного доступа для извлечения поста с id==post_id post = get_object_or_404(Post, id=post_id, status=Post.Status.PUBLISHED) sent = False # 2) if request.method == "POST": # Когда пользователь заполняет форму и передает ее методом POST form = EmailPostForm(request.POST) if form.is_valid(): # форма снова прорисовывается в шаблоне, # включая переданные данные. Ошибки валидации будут отображены # в шаблоне. # в cd = dict в котором находятся данные из формы, # где ключи = названия формы и значение = содержание # form.cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. # # form.data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects). cd = form.cleaned_data # непосредственно отправка письма post_url = request.build_absolute_uri( post.get_absolute_url() ) subject = f"{cd['name']} recommends you read {post}" message = f"Mail send by {cd['email']}\n\n" \ f"Read {post.title} at {post_url}\n\n" \ f"{cd['name']}\'s comments: {cd['comments']}" send_mail(subject, message, djangoProject.settings.EMAIL_HOST_USER, [cd['to']]) sent = True # 1) else: # Указанный экземпляр формы # будет использоваться для отображения пустой формы в шаблоне form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) @require_POST def post_comment(request, post_id): post = get_object_or_404(Post, id=post_id, status=Post.Status.PUBLISHED) comment = None # Создается экземпляр формы, используя переданные на обработку POSTданные form = CommentForm(data=request.POST) if form.is_valid(): # Метод save() создает экземпляр модели, к которой форма привязана, # и сохраняет его в базе данных. Если вызывать его, используя commit=False, # то экземпляр модели создается, но не сохраняется в базе данных. Такой # подход позволяет видоизменять объект перед его окончательным сохранением. comment = form.save(commit=False) print(comment.__dict__) comment.post = post comment.save() return render(request, 'blog/post/comment.html', {'post': post, 'form': form, 'comment': comment}) def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): # cleaned_data -- словарь, который хранит информацию из формы, прошедшую валидацию query = form.cleaned_data['query'] results = Post.published.annotate(search=SearchVector('title', 'body') ).filter(search=query) return render(request, 'blog/post/search.html', {'form': form, 'query': query, 'results': results}) # создал вьюшку редирект на главную страницу если введен некорректный url def redir_to_main_page(request, id): messages.add_message(request, messages.INFO, 'you were redirected on main page') return redirect('blog:post_list')
VEIIEV/djangoProject_Blog
blog/views.py
views.py
py
8,614
python
ru
code
0
github-code
6
37300509850
import sqlite3, sys from pathlib import Path from . import Notes from tqdm import tqdm db_path = "database/xhs_tesla_notes.db" def fill(db_path=db_path): blank_query = "SELECT COUNT(*) FROM notes WHERE content is ''" try: conn = sqlite3.connect(db_path) cursor = conn.cursor() amount = cursor.execute("SELECT COUNT(*) FROM notes").fetchone()[0] blank_amount = cursor.execute(blank_query).fetchone()[0] print( f"There are {amount} notes in the database, {blank_amount} of them have blank content, blank rate is {blank_amount/amount}" ) blank_notes_query = cursor.execute(blank_query) notes_null_content = blank_notes_query.fetchall() # notes_null_content = [] for note in tqdm(notes_null_content): try: null_con = Notes.Note( note[0], note[1], note[2], note[3], note[4], note[5], note[10] ) print(f'Filling content for note with id {null_con.id}') content = null_con.get_content() # print(f"Obtained content: {content}") update_query = "UPDATE notes SET content = ? WHERE id = ?" cursor.execute(update_query, (content, null_con.id)) conn.commit() # print(f'Successfully filled content for note with id {null_con.id}') except Exception as inner_exc: print(f"Error processing note with id {note[0]}: {inner_exc}") New_blank_amount = cursor.execute(blank_query).fetchone()[0] print( f"{blank_amount-New_blank_amount} of them have been filled, blank_rate now is {New_blank_amount/amount} as {New_blank_amount} of {amount}" ) except Exception as outer_exc: print(f"Error connecting to the database: {outer_exc}") finally: conn.commit() conn.close()
Lucascuibu/xis_topic_py
ai_category/fill_blank.py
fill_blank.py
py
1,927
python
en
code
0
github-code
6
25208897980
from dataclasses import dataclass, asdict, field, make_dataclass from typing import List, Union, Any, Dict from enum import Enum from sigrok.core.classes import ConfigKey __all__ = [ "SrBlankState", "SrDeviceState", #"SrFileState", #"AnalogChannel", #"LogicChannel", ] colorsArray = [ '#fce94f', '#fcaf3e', '#e9b96e', '#8ae234', '#729fcf', '#ad7fa8', '#cf72c3', '#ef2929', '#edd400', '#f57900', '#c17d11', '#73d216', '#3465a4', '#75507b', '#a33496', '#cc0000', '#c4a000', '#ce5c00', '#8f5902', '#4e9a06', '#204a87', '#5c3566', '#87207a', '#a40000', '#16191a', '#2e3436', '#555753', '#888a8f', '#babdb6', '#d3d7cf', '#eeeeec', '#ffffff' ] def factory(data): return dict(x for x in data if x[1] is not None) def build_opts(opts: list): #NOTE: key, id, name, desc, keyName, caps data = [] for opt in opts: bases = [] opt_fields = [] if 'caps' in opt: if 'LIST' in opt['caps']: bases.append(ConfList) elif 'GET' in opt['caps']: bases.append(ConfValue) for k, v in opt.items(): opt_fields.append((k, type(v))) opt_fields.append( ('keyName', str)) keyName=ConfigKey.get(opt['key']).name SrOpt = make_dataclass(cls_name='SrOpt', fields=opt_fields, bases=tuple(bases)) srOpt = SrOpt(**opt, keyName = keyName) data.append( (keyName, srOpt) ) return data @dataclass class ConfValue: value: Any @dataclass class ConfList: values: List[Any] = field(default_factory=list) @dataclass class Channel: name: str text: str color: str enabled: bool index: int type: str def update(self, opts: Dict): for key, value in opts.items(): if hasattr(self, key): setattr(self, key, value) @dataclass class LogicChannel(Channel): traceHeight: int = 34 @dataclass class AnalogChannel(Channel): pVertDivs: int = 1 nVertDivs: int = 1 divHeight: int = 51 vRes: float = 20.0 autoranging: bool = True conversion: str = '' convThres: str = '' showTraces: str = '' class ChTypesEnum(Enum): analog = AnalogChannel logic = LogicChannel @dataclass class ChnlsContBase: def set(self, chOpts: List[Dict] ): result = [] for opts in chOpts: chName = opts.pop('chName', None) if hasattr(self, chName): attr = getattr(self, chName) attr.update(opts) result.append(chName) return result def get(self): data = asdict(self, dict_factory=factory) return data.values() def get_list(self): data = asdict(self, dict_factory=factory) return list( { item['type'] for item in data.values() }) @dataclass class OptsContBase: def set(self, opts: List[Dict] ): result = [] for item in opts: optName = item['keyName'] if hasattr(self, optName): attr = getattr(self, optName) attr.value = item['value'] result.append(optName) return result def get(self): return asdict(self, dict_factory=factory) def get_list(self): data = [ item['key'] for item in asdict(self).values() ] #list(asdict(self).values() return data def make_ch_container(channels: List[Dict]): fields = [] for i, item in enumerate(channels): chInst = ChTypesEnum[item['type']].value(**item, color= colorsArray[i], text=item['name']) fields.append( ( item['name'], chInst) ) ChnlsContainer = make_dataclass('ChnlsContainer', [ item[0] for item in fields], bases=tuple([ChnlsContBase]) ) data = ChnlsContainer(**{ item[0]: item[1] for item in fields}) return data def make_opts_container(opts: List[Dict]): fields = build_opts(opts) OptsContainer = make_dataclass('OptsContainer', [ item[0] for item in fields], bases=tuple([OptsContBase])) data = OptsContainer(**{ item[0]: item[1] for item in fields}) return data #----------------- STATE TYPES -----------------# @dataclass class SrBlankState: id: str name: str sourcename: str type: str = field(init=False) def __post_init__(self): self.type = "BLANK" def get(self): data = asdict(self, dict_factory=factory) return data def copy(self): return self.__class__(self.get()) @dataclass class SrDeviceState(SrBlankState): drvopts: Dict[ str, Any ] devopts: Dict[ str, Any ] channels: Dict[ str, Union[ AnalogChannel, LogicChannel ] ]#Any def __init__(self, id, name, sourcename, drvopts: List, devopts: List, channels: List[ChTypesEnum]): SrBlankState.__init__(self, id, name, sourcename) self.type = 'DEVICE' self.drvopts = make_opts_container(drvopts) self.devopts = make_opts_container(devopts) self.channels = make_ch_container(channels) def get(self): data = super().get() data['drvopts'] = self.drvopts.get_list() data['devopts'] = self.devopts.get_list() data['channels'] = self.channels.get_list() return data
drdbrr/webrok
pysigrok/srtypes.py
srtypes.py
py
5,361
python
en
code
2
github-code
6
34273049354
from flask import Flask from flask_cors import CORS from flask_marshmallow import Marshmallow from config import config from .main import main as main_blueprint ''' Application factory for application package. \ Delays creation of an app by moving it into a factory function that can be \ explicitly invoked from script and apply configuration changes. ''' cors = CORS( main_blueprint, origins=['http://127.0.0.1:4200', 'http://localhost:4200'], supports_credentials=True ) ma = Marshmallow() def create_app(config_name): app = Flask(__name__) # Importing configuration settings directly into app app.config.from_object(config[config_name]) config[config_name].init_app(app) # Initializing extensions after app is created cors.init_app(app) ma.init_app(app) # Manually creating app_context to access objects outside of view functions with app.app_context(): app.register_blueprint(main_blueprint, url_prefix='/daron') return app
daronphang/stock_app_backend
app/__init__.py
__init__.py
py
997
python
en
code
0
github-code
6
4534932686
#import mxnet.ndarray as nd from mxnet import nd from mxnet import autograd # REF [site] >> https://gluon-crash-course.mxnet.io/ndarray.html def ndarray_example(): a = nd.array(((1, 2, 3), (5, 6, 7))) b = nd.full((2, 3), 2.0) b.shape, b.size, b.dtype # Operations. x = nd.ones((2, 3)) y = nd.random.uniform(-1, 1, (2, 3)) x * y y.exp() nd.dot(x, y.T) # Indexing. y[1, 2] y[:, 1:3] y[:, 1:3] = 2 y[1:2, 0:2] = 4 # Converting between MXNet NDArray and NumPy. na = x.asnumpy() nd.array(na) # REF [site] >> https://gluon-crash-course.mxnet.io/autograd.html def autograd_example(): # When differentiating a function f(x)=2x2 with respect to parameter x. x = nd.array([[1, 2], [3, 4]]) x.attach_grad() # To let MXNet store y, so that we can compute gradients later, we need to put the definition inside a autograd.record() scope. with autograd.record(): y = 2 * x * x # Invoke back propagation (backprop). # When y has more than one entry, y.backward() is equivalent to y.sum().backward(). y.backward() print('x.grad =', x.grad) # Using Python control flows. def f(a): b = a * 2 while b.norm().asscalar() < 1000: b = b * 2 if b.sum().asscalar() >= 0: c = b[0] else: c = b[1] return c a = nd.random.uniform(shape=2) a.attach_grad() with autograd.record(): c = f(a) c.backward() def main(): ndarray_example() autograd_example() #--------------------------------------------------------------------- if '__main__' == __name__: main()
sangwook236/SWDT
sw_dev/python/rnd/test/machine_learning/mxnet/mxnet_basic.py
mxnet_basic.py
py
1,497
python
en
code
17
github-code
6
5519173983
import sys import logging import click import os sys.path.append('.') from src.classes import Dataset logger = logging.getLogger(__name__) @click.command() @click.option( '--n_images', default=10, help="Number of images per tissue" ) @click.option( '--n_tissues', default=6, help="Number of tissues with most numbers of samples" ) def main(n_images, n_tissues): os.makedirs('data/patches', exist_ok=True) logger.info('Initializing patches script') dataset = Dataset(n_images=n_images, n_tissues=n_tissues) dataset.get_patchcoordfiles() if __name__ == '__main__': logging.basicConfig( filename='logs/patches.log', level=logging.DEBUG, format=( "%(asctime)s | %(name)s | %(processName)s |" "%(levelname)s: %(message)s" ) ) main()
willgdjones/HistoVAE
scripts/patches.py
patches.py
py
825
python
en
code
10
github-code
6
33379210836
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('spurt', '0020_linkpost_scrape_token'), ] operations = [ migrations.RenameField( model_name='linkpost', old_name='pub_date', new_name='scraped_pub_date', ), ]
steezey/spurt
spurt/migrations/0021_auto_20150122_0128.py
0021_auto_20150122_0128.py
py
402
python
en
code
0
github-code
6
37957130845
from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.http import MediaFileUpload import subprocess import os from os.path import join path = os.getcwd() # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ # Backup the tweets subprocess.call(['tar -czvf tweet.tar.gz /usr/local/airflow/data/', '-1'], shell=True) creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. print (join(path,'dags/daglibs/token.pickle')) if os.path.exists(join(path,'dags/daglibs/token.pickle')): with open(join(path,'dags/daglibs/token.pickle'), 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(join(path, 'dags/daglibs/credentials.json'), SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(join(path,'dags/daglibs/token.pickle'), 'wb') as token: pickle.dump(creds, token) service = build('drive', 'v3', credentials=creds) # Call the Drive v3 API file_metadata = {'name': 'tweet.tar.gz'} media = MediaFileUpload('/usr/local/airflow/tweet.tar.gz', mimetype='*/*') file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print ("File ID: {}".format(file.get('id'))) if file.get('id'): return True return False if __name__ == '__main__': main()
vjgpt/twitter-pipeline
dags/daglibs/upload.py
upload.py
py
2,218
python
en
code
9
github-code
6
26528967131
import collections from oneview_redfish_toolkit.api.errors import \ OneViewRedfishException from oneview_redfish_toolkit.api.errors import \ OneViewRedfishResourceNotFoundException from oneview_redfish_toolkit.api.redfish_json_validator import \ RedfishJsonValidator from oneview_redfish_toolkit import config class RedfishError(RedfishJsonValidator): """Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against. """ SCHEMA_NAME = None def __init__(self, code, message): """Constructor Populates self.redfish with error message. """ super().__init__(self.SCHEMA_NAME) self.redfish["error"] = collections.OrderedDict() # Check if Code is a valid Code Error in the registry if code not in config.get_registry_dict()["Base"]["Messages"]: raise OneViewRedfishResourceNotFoundException( "Registry {} not found.".format(code) ) self.redfish["error"]["code"] = "Base.1.1." + code self.redfish["error"]["message"] = message self.redfish["error"]["@Message.ExtendedInfo"] = list() def add_extended_info( self, message_id, message_args=[], related_properties=[]): """Adds an item to ExtendedInfo list using values from DMTF registry Adds an item to ExtendedInfo list using the values for Message, Severity and Resolution from DMTF Base Registry. Parameters: message_id: Id of the message; oneOf the keys in Redfish Registry Messages message_args: List of string to replace markers on Redfish messages. Must have the same length as the number of % signs found in the registry Message field related_properties: Properties relates to this e error if necessary """ messages = config.get_registry_dict()["Base"]["Messages"] # Verify if message_id exists in registry try: severity = messages[message_id]["Severity"] except Exception: raise OneViewRedfishResourceNotFoundException( "Message id {} not found.".format(message_id) ) message = messages[message_id]["Message"] # Check if numbers of replacements and message_args length match replaces = message.count('%') replacements = len(message_args) if replaces != replacements: raise OneViewRedfishException( 'Message has {} replacements to be made but {} args ' 'where sent'.format(replaces, replacements) ) # Replacing the marks in the message. A better way to do this # is welcome. for i in range(replaces): message = message.replace('%' + str(i + 1), message_args[i]) # Construct the dict extended_info = collections.OrderedDict() extended_info["@odata.type"] = "#Message.v1_0_5.Message" extended_info["MessageId"] = "Base.1.1." + message_id extended_info["Message"] = message extended_info["RelatedProperties"] = related_properties extended_info["MessageArgs"] = message_args extended_info["Severity"] = severity extended_info["Resolution"] = messages[message_id]["Resolution"] # Append it to the list self.redfish["error"]["@Message.ExtendedInfo"].append(extended_info)
HewlettPackard/oneview-redfish-toolkit
oneview_redfish_toolkit/api/redfish_error.py
redfish_error.py
py
3,585
python
en
code
16
github-code
6
40687962293
import json import logging import threading import traceback from enum import Enum from typing import Any, Dict, List, Optional, Set, Tuple from lte.protos.policydb_pb2 import FlowMatch from magma.common.redis.client import get_default_client from magma.configuration.service_configs import load_service_config from magma.pipelined.qos.qos_meter_impl import MeterManager from magma.pipelined.qos.qos_tc_impl import TCManager, TrafficClass from magma.pipelined.qos.types import ( QosInfo, get_data, get_data_json, get_key, get_key_json, get_subscriber_data, get_subscriber_key, ) from magma.pipelined.qos.utils import QosStore from redis import ConnectionError # pylint: disable=redefined-builtin LOG = logging.getLogger("pipelined.qos.common") # LOG.setLevel(logging.DEBUG) def normalize_imsi(imsi: str) -> str: imsi = imsi.lower() if imsi.startswith("imsi"): imsi = imsi[4:] return imsi class QosImplType(Enum): LINUX_TC = "linux_tc" OVS_METER = "ovs_meter" @staticmethod def list(): return list(map(lambda t: t.value, QosImplType)) class SubscriberSession(object): def __init__(self, ip_addr: str): self.ip_addr = ip_addr self.ambr_ul = 0 self.ambr_ul_leaf = 0 self.ambr_dl = 0 self.ambr_dl_leaf = 0 self.rules: Set = set() def set_ambr(self, d: FlowMatch.Direction, root: int, leaf: int) -> None: if d == FlowMatch.UPLINK: self.ambr_ul = root self.ambr_ul_leaf = leaf else: self.ambr_dl = root self.ambr_dl_leaf = leaf def get_ambr(self, d: FlowMatch.Direction) -> int: if d == FlowMatch.UPLINK: return self.ambr_ul return self.ambr_dl def get_ambr_leaf(self, d: FlowMatch.Direction) -> int: if d == FlowMatch.UPLINK: return self.ambr_ul_leaf return self.ambr_dl_leaf class SubscriberState(object): """ Map subscriber -> sessions """ def __init__(self, imsi: str, qos_store: Dict): self.imsi = imsi self.rules: Dict = {} # rule -> qos handle self.sessions: Dict = {} # IP -> [sessions(ip, qos_argumets, rule_no), ...] self._redis_store = qos_store def check_empty(self) -> bool: return not self.rules and not self.sessions def get_or_create_session(self, ip_addr: str): session = self.sessions.get(ip_addr) if not session: session = SubscriberSession(ip_addr) self.sessions[ip_addr] = session return session def remove_session(self, ip_addr: str) -> None: del self.sessions[ip_addr] def find_session_with_rule(self, rule_num: int) -> Optional[SubscriberSession]: for session in self.sessions.values(): if rule_num in session.rules: return session return None def _update_rules_map( self, ip_addr: str, rule_num: int, d: FlowMatch.Direction, qos_data, ) -> None: if rule_num not in self.rules: self.rules[rule_num] = [] session = self.get_or_create_session(ip_addr) session.rules.add(rule_num) self.rules[rule_num].append((d, qos_data)) def update_rule( self, ip_addr: str, rule_num: int, d: FlowMatch.Direction, qos_handle: int, ambr: int, leaf: int, ) -> None: k = get_key_json(get_subscriber_key(self.imsi, ip_addr, rule_num, d)) qos_data = get_data_json(get_subscriber_data(qos_handle, ambr, leaf)) LOG.debug("Update: %s -> %s", k, qos_data) self._redis_store[k] = qos_data self._update_rules_map(ip_addr, rule_num, d, qos_data) def remove_rule(self, rule_num: int) -> None: session_with_rule = self.find_session_with_rule(rule_num) if session_with_rule: for (d, _) in self.rules[rule_num]: k = get_subscriber_key( self.imsi, session_with_rule.ip_addr, rule_num, d, ) if get_key_json(k) in self._redis_store: del self._redis_store[get_key_json(k)] session_with_rule.rules.remove(rule_num) del self.rules[rule_num] def find_rule(self, rule_num: int): return self.rules.get(rule_num) def get_all_rules(self) -> Dict[int, List[Tuple[Any, str]]]: return self.rules def get_all_empty_sessions(self) -> List: return [s for s in self.sessions.values() if not s.rules] def get_qos_handle(self, rule_num: int, direction: FlowMatch.Direction) -> int: rule = self.rules.get(rule_num) if rule: for d, qos_data in rule: if d == direction: _, qid, _, _ = get_data(qos_data) return qid return 0 class QosManager(object): """ Qos Manager -> add/remove subscriber qos """ def init_impl(self, datapath): """ Takese in datapath, and initializes appropriate QoS manager based on config """ if not self._qos_enabled: return if self._initialized: return try: impl_type = QosImplType(self._config["qos"]["impl"]) if impl_type == QosImplType.OVS_METER: self.impl = MeterManager(datapath, self._loop, self._config) else: self.impl = TCManager(datapath, self._config) self.setup() except ValueError: LOG.error("%s is not a valid qos impl type", impl_type) raise @classmethod def debug(cls, _, __, ___): config = load_service_config('pipelined') qos_impl_type = QosImplType(config["qos"]["impl"]) qos_store = QosStore(cls.__name__, client=get_default_client()) for k, v in qos_store.items(): _, imsi, ip_addr, rule_num, d = get_key(k) _, qid, ambr, leaf = get_data(v) print('imsi :', imsi) print('ip_addr :', ip_addr) print('rule_num :', rule_num) print('direction :', d) print('qos_handle:', qid) print('qos_handle_ambr:', ambr) print('qos_handle_ambr_leaf:', leaf) if qos_impl_type == QosImplType.OVS_METER: MeterManager.dump_meter_state(v) else: dev = config['nat_iface'] if d == FlowMatch.UPLINK else 'gtpu_sys_2152' print("Dev: ", dev) TrafficClass.dump_class_state(dev, qid) if leaf and leaf != qid: print("Leaf:") TrafficClass.dump_class_state(dev, leaf) if ambr: print("AMBR (parent):") TrafficClass.dump_class_state(dev, ambr) if qos_impl_type == QosImplType.LINUX_TC: dev = config['nat_iface'] print("Root stats for: ", dev) TrafficClass.dump_root_class_stats(dev) dev = 'gtpu_sys_2152' print("Root stats for: ", dev) TrafficClass.dump_root_class_stats(dev) def _is_redis_available(self): try: self._redis_store.client.ping() except ConnectionError: return False return True def __init__(self, loop, config, client=get_default_client()): self._initialized = False self._clean_restart = config["clean_restart"] self._subscriber_state = {} self._loop = loop self._redis_conn_retry_secs = 1 self._config = config # protect QoS object create and delete across a QoSManager Object. self._lock = threading.Lock() if 'qos' not in config.keys(): LOG.error("qos field not provided in config") return self._qos_enabled = config["qos"]["enable"] if not self._qos_enabled: return self._apn_ambr_enabled = config["qos"].get("apn_ambr_enabled", True) LOG.info("QoS: apn_ambr_enabled: %s", self._apn_ambr_enabled) self._redis_store = QosStore(self.__class__.__name__, client) self.impl = None def setup(self): with self._lock: if not self._qos_enabled: return if self._is_redis_available(): self._setupInternal() else: LOG.info( "failed to connect to redis..retrying in %d secs", self._redis_conn_retry_secs, ) self._loop.call_later(self._redis_conn_retry_secs, self.setup) def _setupInternal(self): if self._initialized: return if self._clean_restart: LOG.info("Qos Setup: clean start") self.impl.setup() self.impl.destroy() self._redis_store.clear() self._initialized = True else: # read existing state from qos_impl LOG.info("Qos Setup: recovering existing state") self.impl.setup() cur_qos_state, apn_qid_list = self.impl.read_all_state() LOG.debug("Initial qos_state -> %s", json.dumps(cur_qos_state, indent=1)) LOG.debug("apn_qid_list -> %s", apn_qid_list) LOG.debug("Redis state: %s", self._redis_store) try: # populate state from db in_store_qid = set() in_store_ambr_qid = set() purge_store_set = set() for rule, sub_data in self._redis_store.items(): _, qid, ambr, leaf = get_data(sub_data) if qid not in cur_qos_state: LOG.warning("missing qid: %s in TC", qid) purge_store_set.add(rule) continue if ambr and ambr != 0 and ambr not in cur_qos_state: purge_store_set.add(rule) LOG.warning("missing ambr class: %s of qid %d", ambr, qid) continue if leaf and leaf != 0 and leaf not in cur_qos_state: purge_store_set.add(rule) LOG.warning("missing leaf class: %s of qid %d", leaf, qid) continue if ambr: qid_state = cur_qos_state[qid] if qid_state['ambr_qid'] != ambr: purge_store_set.add(rule) LOG.warning("Inconsistent amber class: %s of qid %d", qid_state['ambr_qid'], ambr) continue in_store_qid.add(qid) if ambr: in_store_qid.add(ambr) in_store_ambr_qid.add(ambr) in_store_qid.add(leaf) _, imsi, ip_addr, rule_num, direction = get_key(rule) subscriber = self._get_or_create_subscriber(imsi) subscriber.update_rule(ip_addr, rule_num, direction, qid, ambr, leaf) session = subscriber.get_or_create_session(ip_addr) session.set_ambr(direction, ambr, leaf) # purge entries from qos_store for rule in purge_store_set: LOG.debug("purging qos_store entry %s", rule) del self._redis_store[rule] # purge unreferenced qos configs from system # Step 1. Delete child nodes lost_and_found_apn_list = set() for qos_handle in cur_qos_state: if qos_handle not in in_store_qid: if qos_handle in apn_qid_list: lost_and_found_apn_list.add(qos_handle) else: LOG.debug("removing qos_handle %d", qos_handle) self.impl.remove_qos( qos_handle, cur_qos_state[qos_handle]['direction'], recovery_mode=True, ) if len(lost_and_found_apn_list) > 0: # Step 2. delete qos ambr without any leaf nodes for qos_handle in lost_and_found_apn_list: if qos_handle not in in_store_ambr_qid: LOG.debug("removing apn qos_handle %d", qos_handle) self.impl.remove_qos( qos_handle, cur_qos_state[qos_handle]['direction'], recovery_mode=True, skip_filter=True, ) final_qos_state, _ = self.impl.read_all_state() LOG.info("final_qos_state -> %s", json.dumps(final_qos_state, indent=1)) LOG.info("final_redis state -> %s", self._redis_store) except Exception as e: # pylint: disable=broad-except # in case of any exception start clean slate LOG.error("error %s. restarting clean %s", e, traceback.format_exc()) self._clean_restart = True self._initialized = True def _get_or_create_subscriber(self, imsi): subscriber_state = self._subscriber_state.get(imsi) if not subscriber_state: subscriber_state = SubscriberState(imsi, self._redis_store) self._subscriber_state[imsi] = subscriber_state return subscriber_state def add_subscriber_qos( self, imsi: str, ip_addr: str, apn_ambr: int, units: str, rule_num: int, direction: FlowMatch.Direction, qos_info: QosInfo, cleanup_rule=None, ): with self._lock: if not self._qos_enabled or not self._initialized: LOG.debug("add_subscriber_qos: not enabled or initialized") return None, None, None LOG.debug( "adding qos for imsi %s rule_num %d direction %d apn_ambr %d, %s", imsi, rule_num, direction, apn_ambr, qos_info, ) imsi = normalize_imsi(imsi) # ip_addr identifies a specific subscriber session, each subscriber session # must be associated with a default bearer and can be associated with dedicated # bearers. APN AMBR specifies the aggregate max bit rate for a specific # subscriber across all the bearers. Queues for dedicated bearers will be # children of default bearer Queues. In case the dedicated bearers exceed the # rate, then they borrow from the default bearer queue subscriber_state = self._get_or_create_subscriber(imsi) qos_handle = subscriber_state.get_qos_handle(rule_num, direction) if qos_handle: LOG.debug( "qos exists for imsi %s rule_num %d direction %d", imsi, rule_num, direction, ) return self.impl.get_action_instruction(qos_handle) ambr_qos_handle_root = 0 ambr_qos_handle_leaf = 0 if self._apn_ambr_enabled and apn_ambr > 0: session = subscriber_state.get_or_create_session(ip_addr) ambr_qos_handle_root = session.get_ambr(direction) LOG.debug("existing root rec: ambr_qos_handle_root %d", ambr_qos_handle_root) if not ambr_qos_handle_root: ambr_qos_handle_root = self.impl.add_qos( direction, QosInfo(gbr=None, mbr=apn_ambr), cleanup_rule, units=units, skip_filter=True, ) if not ambr_qos_handle_root: LOG.error( 'Failed adding root ambr qos mbr %u direction %d', apn_ambr, direction, ) return None, None, None else: LOG.debug( 'Added root ambr qos mbr %u direction %d qos_handle %d ', apn_ambr, direction, ambr_qos_handle_root, ) ambr_qos_handle_leaf = session.get_ambr_leaf(direction) LOG.debug("existing leaf rec: ambr_qos_handle_leaf %d", ambr_qos_handle_leaf) if not ambr_qos_handle_leaf: ambr_qos_handle_leaf = self.impl.add_qos( direction, QosInfo(gbr=None, mbr=apn_ambr), cleanup_rule, units=units, parent=ambr_qos_handle_root, ) if ambr_qos_handle_leaf: session.set_ambr(direction, ambr_qos_handle_root, ambr_qos_handle_leaf) LOG.debug( 'Added ambr qos mbr %u direction %d qos_handle %d/%d ', apn_ambr, direction, ambr_qos_handle_root, ambr_qos_handle_leaf, ) else: LOG.error( 'Failed adding leaf ambr qos mbr %u direction %d', apn_ambr, direction, ) self.impl.remove_qos(ambr_qos_handle_root, direction, skip_filter=True) return None, None, None qos_handle = ambr_qos_handle_leaf if qos_info: qos_handle = self.impl.add_qos( direction, qos_info, cleanup_rule, units=units, parent=ambr_qos_handle_root, ) LOG.debug("Added ded brr handle: %d", qos_handle) if qos_handle: LOG.debug( 'Adding qos %s direction %d qos_handle %d ', qos_info, direction, qos_handle, ) else: LOG.error('Failed adding qos %s direction %d', qos_info, direction) return None, None, None if qos_handle: subscriber_state.update_rule( ip_addr, rule_num, direction, qos_handle, ambr_qos_handle_root, ambr_qos_handle_leaf, ) return self.impl.get_action_instruction(qos_handle) return None, None, None def remove_subscriber_qos(self, imsi: str = "", del_rule_num: int = -1): with self._lock: if not self._qos_enabled or not self._initialized: LOG.debug("remove_subscriber_qos: not enabled or initialized") return LOG.debug("removing Qos for imsi %s del_rule_num %d", imsi, del_rule_num) if not imsi: LOG.error('imsi %s invalid, failed removing', imsi) return imsi = normalize_imsi(imsi) subscriber_state = self._subscriber_state.get(imsi) if not subscriber_state: LOG.debug('imsi %s not found, nothing to remove ', imsi) return to_be_deleted_rules = set() qid_to_remove = {} qid_in_use = set() if del_rule_num == -1: # deleting all rules for the subscriber rules = subscriber_state.get_all_rules() for (rule_num, rule) in rules.items(): for (d, qos_data) in rule: _, qid, ambr, leaf = get_data(qos_data) if ambr != qid: qid_to_remove[qid] = d if leaf and leaf != qid: qid_to_remove[leaf] = d to_be_deleted_rules.add(rule_num) else: rule = subscriber_state.find_rule(del_rule_num) if rule: rules = subscriber_state.get_all_rules() for (rule_num, rule) in rules.items(): for (d, qos_data) in rule: _, qid, ambr, leaf = get_data(qos_data) if rule_num == del_rule_num: if ambr != qid: qid_to_remove[qid] = d if leaf and leaf != qid: qid_to_remove[leaf] = d else: qid_in_use.add(qid) LOG.debug("removing rule %s %s ", imsi, del_rule_num) to_be_deleted_rules.add(del_rule_num) else: LOG.debug("unable to find rule_num %d for imsi %s", del_rule_num, imsi) for (qid, d) in qid_to_remove.items(): if qid not in qid_in_use: self.impl.remove_qos(qid, d) for rule_num in to_be_deleted_rules: subscriber_state.remove_rule(rule_num) # purge sessions with no rules for session in subscriber_state.get_all_empty_sessions(): for d in (FlowMatch.UPLINK, FlowMatch.DOWNLINK): ambr_qos_handle = session.get_ambr(d) if ambr_qos_handle: LOG.debug("removing root ambr qos handle %d direction %d", ambr_qos_handle, d) self.impl.remove_qos(ambr_qos_handle, d, skip_filter=True) LOG.debug("purging session %s %s ", imsi, session.ip_addr) subscriber_state.remove_session(session.ip_addr) # purge subscriber state with no rules if subscriber_state.check_empty(): LOG.debug("purging subscriber state for %s, empty rules and sessions", imsi) del self._subscriber_state[imsi]
magma/magma
lte/gateway/python/magma/pipelined/qos/common.py
common.py
py
22,178
python
en
code
1,605
github-code
6
15418635020
# -*- coding: utf-8 -*- #!/usr/bin/env python3.5 from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import RegPeopleForm, RegUserForm def createuser(request): if request.method == "POST": uform = RegUserForm(data=request.POST) pform = RegPeopleForm(data=request.POST) if uform.is_valid() and pform.is_valid(): user = uform.save() people = pform.save(commit=False) people = user people.save() return HttpResponseRedirect('/') else: uform=RegUserForm() pform=RegPeopleForm() return render(request, 'registration/registration.html', {'uform': uform, 'pform': pform})
MyriamBel/testwork
Reg/views.py
views.py
py
725
python
en
code
0
github-code
6
9357978894
#!/usr/bin/env/python # coding: utf-8 # YouTube Data API Collector # Mat Morrison @mediaczar # Last updated: 2020-03-31 ''' Query the YouTube Data API for an individual channel URL or a file list of URLs. You may also specify which 'page' you'd like to start on (useful when the script breaks during a long data capture.) You _must_ supply a URL or file handle at the command line. Data collected: * publication date * title * description * duration (ISO8601 duration format - parsed with [isodate](https://pypi.python.org/pypi/isodate)) * view count * comment count * likes & dislikes To run it, you'll need: 1. a very basic knowledge of Python 2. some ability to install Python libraries (for legacy reasons, I'm using a somewhat non-standard library called [scraperwiki](https://pypi.python.org/pypi/scraperwiki) to save the data.) 3. (to read the output) some basic knowledge of SQL and [SQLite](https://www.sqlite.org/) (it comes as standard on OS X, and I use the excellent [Base 2](https://menial.co.uk/base/) to manage and query the files that this script produces.) 4. an API Key from the Google Developers site (get it here: [Google Developer Console](https://console.developers.google.com/)) - add to SET UP. Take care not to share this publicly. ''' import requests import json import scraperwiki import isodate import sys import argparse def get_file_contents(filename): """ Given a filename, return the contents of that file """ try: with open(filename, 'r') as f: # It's assumed our file contains a single line, # with our API key return f.read().strip() except FileNotFoundError: print("'%s' file not found" % filename) def load_data(request): x = json.loads(requests.get(request).text) return x def get_author(url): elements = url.split("/") elements = [i for i in elements if i] # remove 'None' values if len(elements) > 3: author = elements[3] print(author) if elements[2] == "channel": authortype = "id" elif elements[2] == "user": authortype = "forUsername" else: sys.exit('malformed URL: %s' % url) else: author = elements[2] authortype = "channel" return author, authortype def build_channel_request(author, authortype): part = 'snippet,contentDetails,statistics,id' field_items = ['snippet(title, publishedAt, description)', 'contentDetails/relatedPlaylists/uploads', 'statistics(subscriberCount,videoCount,viewCount)', 'id'] x = ('https://www.googleapis.com/youtube/v3/' + 'channels?part=' + part + '&fields=items(' + ','.join(field_items) + ')&' + authortype + '=' + author + '&key=' + API_key) return x def write_channel(json): channel = {} channel['id'] = json['items'][0]['id'] channel['title'] = title channel['uploads'] = uploadsId channel['subscriberCount'] = json['items'][0]['statistics']['subscriberCount'] channel['videoCount'] = json['items'][0]['statistics']['videoCount'] channel['publishedAt'] = json['items'][0]['snippet']['publishedAt'] channel['description'] = json['items'][0]['snippet']['description'] scraperwiki.sqlite.save(unique_keys=['id'], table_name='channel', data=channel) def initialise_playlist(uploadsId): part = 'snippet,contentDetails' field_items = ['snippet(title, publishedAt, description)', 'contentDetails(videoId, duration)', 'nextPageToken'] max_results = '50' x = ('https://www.googleapis.com/youtube/v3/' + 'playlistItems?playlistId=' + uploadsId + '&part=' + part + # '&fields=items(' + ','.join(field_items) + ')' + '&maxResults=' + max_results + '&key=' + API_key) return x print('getting channel data for: %s' % url) # log progress def gather_channel(url): global title global uploadsId author, authortype = get_author(url) API_request = build_channel_request(author, authortype) channel_data = load_data(API_request) # verify data in case bad url try: title = channel_data['items'][0]['snippet']['title'] except: print("bad URL") return # need following to get playlistId uploadsId = channel_data['items'][0]['contentDetails']['relatedPlaylists']['uploads'] write_channel(channel_data) print('...complete') # log progress # now create a list of the videos for that channel print('collecting uploads for: %s (playlist ID: %s)' % (title, uploadsId)) # log progress API_request_base = initialise_playlist(uploadsId) # test to see if a page has been submitted as a command line option if args.page: page_token = args.page[0] else: page_token = '' # loop through the playlist collecting video data gather_video_data(API_request_base, page_token) def gather_video_data(API_request_base, page_token): global videodata while True: paging_request = API_request_base + '&pageToken=' + page_token if page_token == '': print('gathering first page of %s' % title) else: print('gathering %s page %s' % (title, page_token)) videos = load_data(paging_request) vcount = 1 videodata = {} videodata['channel'] = title for video in videos['items']: write_video(video) if vcount > 1: # log progress print('\033[1A...completed ' + str(vcount)) # cursor up else: print('...completed ' + str(vcount)) vcount += 1 try: # log progress print('...gathering next page of videos') page_token = videos['nextPageToken'] except: print('...last page reached') page_token = '' break def write_video(json): videodata['videoId'] = json['contentDetails']['videoId'] videodata['title'] = json['snippet']['title'] videodata['publishedAt'] = json['snippet']['publishedAt'] videodata['description'] = json['snippet']['description'] video_request = ('https://www.googleapis.com/youtube/v3/' + 'videos?part=statistics,contentDetails&id=' + videodata['videoId'] + '&key=' + API_key) stats_json = load_data(video_request) for stat in ['viewCount', 'likeCount', 'dislikeCount', 'commentCount']: try: videodata[stat] = int(stats_json['items'][0]['statistics'][stat]) except: videodata[stat] = None duration = isodate.parse_duration(stats_json['items'][0]['contentDetails']['duration']).total_seconds() videodata['duration'] = duration scraperwiki.sqlite.save(unique_keys=['videoId'], table_name='videos', data=videodata) # SET UP # credentials API_key = get_file_contents("api_key") # obtain from Google Developer Console, store in api_key locally # parse arguments at command line parser = argparse.ArgumentParser(description="""Query the YouTube Data API for an individual channel URL or a file list of URLs. You may also specify which 'page' you'd like to start on (useful when the script breaks during a long data capture.) You *must* supply a URL or file handle at the command line.""") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-u", "--url", nargs=1, type=str, help="url of YouTube channel") group.add_argument("-f", "--file", nargs=1, type=str, help="file list of URLs") parser.add_argument("-p", "--page", nargs=1, type=str, help="page code") args = parser.parse_args() if args.file: f = open(args.file[0]) urls = [url.rstrip('\n') for url in f] f.close elif args.url: urls = args.url # iterate through the URLs collecting basic channel data for url in urls: print("gathering %s" % url) gather_channel(url)
DigitalWhiskey/youtube_collector
youtube_collector.py
youtube_collector.py
py
8,081
python
en
code
0
github-code
6
21097762911
""" Honk Settings. """ import environ from pathlib import Path from google.oauth2 import service_account env = environ.Env( # set casting, default value DEBUG=(bool, False), ) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR: Path = Path(__file__).resolve().parent.parent # reading .env files environ.Env.read_env(BASE_DIR / '.env') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY: str = env('SECRET_KEY') DEBUG: bool = env('DEBUG') ALLOWED_HOSTS: list[str] = ['localhost', '127.0.0.1', 'honk.rafaelmc.net'] CSRF_TRUSTED_ORIGINS: list[str] = ['https://honk.rafaelmc.net'] # Application definition INSTALLED_APPS: list[str] = [ 'circus.apps.CircusConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'rest_framework', 'rest_framework.authtoken', ] MIDDLEWARE: list[str] = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'honk.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'honk.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'sqlite_data' / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators VALIDATOR_PATH = 'django.contrib.auth.password_validation.' AUTH_PASSWORD_VALIDATORS = [ {'NAME': VALIDATOR_PATH + 'UserAttributeSimilarityValidator'}, {'NAME': VALIDATOR_PATH + 'MinimumLengthValidator'}, {'NAME': VALIDATOR_PATH + 'CommonPasswordValidator'}, {'NAME': VALIDATOR_PATH + 'NumericPasswordValidator'}, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_REDIRECT_URL = "/" STORAGES = { "default": {"BACKEND": "storages.backends.gcloud.GoogleCloudStorage"}, "staticfiles": { "BACKEND": "storages.backends.gcloud.GoogleCloudStorage" }, } # GOOGLE_APPLICATION_CREDENTIALS = GS_BUCKET_NAME = 'honkhonk' MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media" GS_CREDENTIALS = service_account.Credentials.from_service_account_file( f"{BASE_DIR}/gcp-honk-credentials.json" ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], }
rafamoreira/honk
honk-web/honk/settings.py
settings.py
py
3,860
python
en
code
0
github-code
6
24213199857
import pygame import serial import time import sys class GUI: def __init__(self): # screen pygame.init() self.screen = pygame.display.set_mode((350, 400)) self.DELTA = 40 self.wide_value = 7500 self.angle_y = 3890 self.angle_x = 1230 self.ser = serial.Serial('COM6', baudrate=9600, timeout=0.01) time.sleep(1) # creating buttons` button_up_surface = pygame.transform.scale(pygame.image.load("up.jpg"), (50, 50)) button_down_surface = pygame.transform.scale(pygame.image.load("down.jpg"), (50, 50)) button_right_surface = pygame.transform.scale(pygame.image.load("right.png"), (50, 50)) button_left_surface = pygame.transform.scale(pygame.image.load("left.jpg"), (50, 50)) button_wide_surface = pygame.transform.scale(pygame.image.load("wide.jpg"), (100, 50)) button_narrow_surface = pygame.transform.scale(pygame.image.load("narrow.png"), (100, 50)) self.button_up = Button(button_up_surface, 175, 50) self.button_down = Button(button_down_surface, 175, 150) self.button_right = Button(button_right_surface, 250, 100) self.button_left = Button(button_left_surface, 100, 100) self.button_wide = Button(button_wide_surface, 175, 225) self.button_narrow = Button(button_narrow_surface, 175, 280) def listen(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if self.button_down.checking_input(pygame.mouse.get_pos()): self.angle_y -= self.DELTA if self.angle_y >= 3880 else 0 self.ser.write((str(self.angle_y) + '\n').encode('utf-8')) elif self.button_up.checking_input(pygame.mouse.get_pos()): self.angle_y += self.DELTA if self.angle_y <= 4110 else 0 self.ser.write((str(self.angle_y) + '\n').encode('utf-8')) elif self.button_right.checking_input(pygame.mouse.get_pos()): self.angle_x -= self.DELTA if self.angle_x >= 1230 else 0 self.ser.write((str(self.angle_x) + '\n').encode('utf-8')) elif self.button_left.checking_input(pygame.mouse.get_pos()): self.angle_x += self.DELTA if self.angle_x <= 2230 else 0 self.ser.write((str(self.angle_x) + '\n').encode('utf-8')) elif self.button_wide.checking_input(pygame.mouse.get_pos()): # wider, from 1500 to 1750 self.ser.write((str(7750) + '\n').encode('utf-8')) time.sleep(0.2) self.ser.write((str(7500) + '\n').encode('utf-8')) elif self.button_narrow.checking_input(pygame.mouse.get_pos()): # wider, from 1280 to 1500 self.ser.write((str(7300) + '\n').encode('utf-8')) time.sleep(0.2) self.ser.write((str(7500) + '\n').encode('utf-8')) self.screen.fill("white") # updating buttons self.screen.fill("white") self.button_up.update(self.screen) self.button_down.update(self.screen) self.button_right.update(self.screen) self.button_left.update(self.screen) self.button_wide.update(self.screen) self.button_narrow.update(self.screen) pygame.display.update() def close_port(self): self.ser.close() class Button: def __init__(self, image, x_pos, y_pos): self.image = image self.x_pos = x_pos self.y_pos = y_pos self.rect = self.image.get_rect(center=(self.x_pos, self.y_pos)) def update(self, screen): screen.blit(self.image, self.rect) def checking_input(self, position): if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom): return True class Controller: def __init__(self): # controller pygame.init() pygame.joystick.init() self.controller = pygame.joystick.Joystick(0) self.DELTA = 35 self.angle_y = 3880 self.angle_x = 1230 self.controller.init() self.ser = serial.Serial('COM6', baudrate=9600, timeout=0.01) time.sleep(1) def listen(self): while True: pygame.event.get() if self.controller.get_button(1): # right self.angle_x -= self.DELTA if self.angle_x >= 1230 else 0 self.ser.write((str(self.angle_x) + '\n').encode('utf-8')) time.sleep(0.1) elif self.controller.get_button(2): # left self.angle_x += self.DELTA if self.angle_x <= 2230 else 0 self.ser.write((str(self.angle_x) + '\n').encode('utf-8')) time.sleep(0.1) elif self.controller.get_button(3): # up self.angle_y += self.DELTA if self.angle_y <= 4110 else 0 self.ser.write((str(self.angle_y) + '\n').encode('utf-8')) time.sleep(0.1) elif self.controller.get_button(0): self.angle_y -= self.DELTA if self.angle_y >= 3880 else 0 self.ser.write((str(self.angle_y) + '\n').encode('utf-8')) time.sleep(0.1) elif round(self.controller.get_axis(5), 2) != -1.0: # wider axis_data = round(self.controller.get_axis(5), 2) new_value = int(self.map_data(axis_data, -1.0, 1.0, 7500, 7750)) self.ser.write((str(new_value) + '\n').encode('utf-8')) time.sleep(0.1) elif round(self.controller.get_axis(4), 2) != -1.0: # narrower axis_data = round(self.controller.get_axis(4), 2) new_value = int(self.map_data(axis_data, -1.0, 1.0, 7500, 7280)) self.ser.write((str(new_value) + '\n').encode('utf-8')) time.sleep(0.1) def close_port(self): self.ser.close() def map_data(self, x, in_min, in_max, out_min, out_max): # converting one interval to another return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min if __name__ == "__main__": try: try: ps4 = Controller() ps4.listen() except KeyboardInterrupt: ps4.close_port() except pygame.error: try: gui = GUI() gui.listen() except KeyboardInterrupt: gui.close_port()
chinchilla2019/bebentos
main_and_pictures/main.py
main.py
py
7,165
python
en
code
0
github-code
6
17962113365
import sqlite3 as sql from datetime import date from model.classes import User, Country, Tasting def initCon() -> sql: """ Initialize connection :return connection: """ return sql.connect('../coffeeDB.db') def createCursor(con: sql.Connection) -> sql.Cursor: """ Creates cursor :param con: :return cursor: """ return con.cursor() class Insert: """Insert data into DB""" def __init__(self): self.__con = initCon() self.__cursor = createCursor(self.__con) def getCon(self) -> sql.Connection: return self.__con def getCursor(self) -> sql.Cursor: return self.__cursor def insertCountry(self, countryName) -> bool: pass def addUser(self, email: str, password: str, firstName: str, lastName: str, countryID: int) -> bool: """ Adds user to DB Checks if inputed data is valid through User class Checks if email has already been registered :param email: :param password: :param firstName: :param lastName: :param countryID: :return: """ ret = Retrieve() email = email.lower() # Email should be lowercase if ret.registeredEmail(email): raise ValueError("A user with this email has already been registered") User(0, email, password, firstName, lastName, countryID) cursor = self.getCursor() try: cursor.execute( """ INSERT INTO User (email, password, firstName, surname, countryID) VALUES (?, ?, ?, ?, ?) """, (email, password, firstName, lastName, countryID) ) self.getCon().commit() return True except Exception as e: return False def addTasting(self, tasteNotes: str, points: int, userID: int, roastedCoffeeID: int) -> bool: """ Adds a tasting created by the user :param tasteNotes: :param points: :param tastingDate: :param userID: :param roastedCoffeeID: :return: """ tastingDate = date.today() Tasting(0, tasteNotes, points, tastingDate, userID, roastedCoffeeID) # Checks if inputed data is valid cursor = self.getCursor() try: cursor.execute( """ INSERT INTO Tasting (tasteNotes, points, tastingDate, userID, roastedCoffeeID) VALUES (?, ?, ?, ?, ?) """, (tasteNotes, points, tastingDate, userID, roastedCoffeeID) ) self.getCon().commit() return True except Exception as e: return False class Retrieve: """Retrieve data from DB""" def __init__(self): self.__con = initCon() self.__cursor = createCursor(self.__con) def getCon(self) -> sql.Connection: return self.__con def getCursor(self) -> sql.Cursor: return self.__cursor def getUsers(self) -> list[User]: """ Retrieve all data from DB :return userList: """ userList = [] cursor = self.getCursor() for row in cursor.execute("SELECT * FROM User"): userID, email, password, firstName, surname, countryID = row userList.append(User(userID, email, password, firstName, surname, countryID)) self.getCon().commit() return userList def getCountries(self) -> list[Country]: """ Gets all countries :return countryList: """ countryList = [] cursor = self.getCursor() for row in cursor.execute("SELECT * FROM Country"): countryID, name = row countryList.append(Country(countryID, name)) self.getCon().commit() return countryList def getRoastedCoffees(self) -> list[dict]: """ Gets all roasted coffees added to the database :return: """ roastedCoffeeList = [] cursor = self.getCursor() query = """ SELECT RoastedCoffee.roastedCoffeeID, RoastedCoffee.name, CoffeeRoastery.name FROM RoastedCoffee INNER JOIN CoffeeRoastery on RoastedCoffee.roastaryID WHERE RoastedCoffee.roastaryID == CoffeeRoastery.roastaryID """ for row in cursor.execute(query): roastedCoffeeID, coffeeName, roasteryName = row result = { "roastedCoffeeID": roastedCoffeeID, "coffeeName": coffeeName, "roasteryName": roasteryName } roastedCoffeeList.append(result) self.getCon().commit() return roastedCoffeeList def getCoffeeByDescription(self, search: str) -> list[dict]: """ Returns all rows have a description or tastenote with the searchword that matches :param search: :return: """ cursor = self.getCursor() result = [] for row in cursor.execute( """ select distinct CoffeeRoastery.name, RoastedCoffee.name from Tasting inner join RoastedCoffee on Tasting.roastedCoffeeID inner join CoffeeRoastery on RoastedCoffee.roastaryID where Tasting.roastedCoffeeID == RoastedCoffee.roastedCoffeeID and RoastedCoffee.roastaryID == CoffeeRoastery.roastaryID and (Tasting.tasteNotes like ? or RoastedCoffee.description like ?) """, ("%" + search + "%", "%" + search + "%") ): roasteryName, coffeeName = row data = { "roasteryName": roasteryName, "coffeeName": coffeeName } result.append(data) self.getCon().commit() return result def getCoffeeByCountryAndProcessingMethod(self) -> list[dict]: """ Returns coffees from Rwanda or Colombia and are unwashed :return: """ cursor = self.getCursor() result = [] query = """ select CoffeeRoastery.name, RoastedCoffee.name from RoastedCoffee inner join CoffeeRoastery on RoastedCoffee.roastaryID == CoffeeRoastery.roastaryID inner join CoffeeParty on RoastedCoffee.coffeePartyID == CoffeeParty.coffeePartyID inner join Farm on CoffeeParty.producedFarmID == Farm.farmID inner join Region on Farm.regionID == Region.regionID inner join Country on Region.countryID == Country.countryID inner join ProcessingMethod on CoffeeParty.processingMethodID == ProcessingMethod.processingMethodID where (Country.name == "Rwanda" or Country.name == "Colombia") and ProcessingMethod.name != "Vasket" """ for row in cursor.execute(query): roasteryName, coffeeName = row data = { "roasteryName": roasteryName, "coffeeName": coffeeName } result.append(data) self.getCon().commit() return result def registeredEmail(self, email: str) -> bool: """ Checks if there are any equal emails in the DB :param email: :return bool: """ email = email.lower() cursor = self.getCursor() result = cursor.execute( """ SELECT * FROM User WHERE User.email = ? """, (email,) ).fetchall() self.getCon().commit() return len(result) > 0 def getCoffeeByValue(self) -> list[dict]: """ Gets a list off all coffees based on average score per 100 kroners :return: """ cursor = self.getCursor() result = [] query = """ select CoffeeRoastery.name, RoastedCoffee.name, RoastedCoffee.kiloPrice, (avg(distinct Tasting.points) / RoastedCoffee.kiloPrice) * 100 from Tasting inner join RoastedCoffee on Tasting.roastedCoffeeID inner join CoffeeRoastery on RoastedCoffee.roastaryID where Tasting.roastedCoffeeID == RoastedCoffee.roastedCoffeeID and CoffeeRoastery.roastaryID == RoastedCoffee.roastaryID group by Tasting.roastedCoffeeID order by (avg(distinct Tasting.points) / RoastedCoffee.kiloPrice) desc """ for row in cursor.execute(query): roasteryName, coffeeName, kiloPrice, score = row data = { "roasteryName": roasteryName, "coffeeName": coffeeName, "kiloPrice": kiloPrice, "score": score } result.append(data) self.getCon().commit() return result def getUniqueTastings(self) -> list[dict]: """ Returns a list off the number of unique coffees each user has tasted :return: """ cursor = self.getCursor() result = [] query = """ select User.firstName, User.surname, count(distinct Tasting.roastedCoffeeID) from Tasting inner join User on Tasting.userID where User.userID == Tasting.userID and date(Tasting.tastingDate) >= date("2022-01-01") and date(Tasting.tastingDate) < date("2023-01-01") group by Tasting.userID order by count(Tasting.roastedCoffeeID) desc """ for row in cursor.execute(query): firstName, surname, count = row data = { "firstName": firstName, "surname": surname, "count": count } result.append(data) self.getCon().commit() return result class Main(): def loginAndRegister(self): """ Allows user to login or register :return: """ userInput = str(input("Enter your email: ")) userInput = userInput.lower() ret = Retrieve() ins = Insert() if ret.registeredEmail(userInput): # If email is already in use users = ret.getUsers() password = str(input("Enter password: ")) user = list(filter(lambda row: row.getEmail() == userInput and row.getPassword() == password, users)) while len(user) == 0: print("Incorrect email and password. Try again!") email = str(input("Enter email: ")) password = str(input("Enter password: ")) user = list( filter(lambda row: row.getEmail() == email.lower() and row.getPassword() == password, users)) print("Logged in\n") return user[0] else: # If email is not in use email = userInput password = str(input("Enter a password: ")) firstName = str(input("Enter your first name: ")) surname = str(input("Enter your surname: ")) print("\nSelect a country from the list of countries") for row in ret.getCountries(): print(row.getName()) countryInput = str(input("\nEnter country: ")) country = list(filter(lambda row: row.getName() == countryInput, ret.getCountries())) while len(country) == 0: # This does not work properly countryInput = str(input("Could not find any matches. Enter a country: ")) country = list(filter(lambda row: row.getName() == countryInput, ret.getCountries())) country = country[0] ins.addUser(email, password, firstName, surname, country.getCountryID()) print("\nUser registered") return None def bh1(self): """ Userstory 1 :return: """ user = self.loginAndRegister() if not user: user = self.loginAndRegister() ret = Retrieve() ins = Insert() result = ret.getRoastedCoffees() roasteries = [] for row in result: if row["roasteryName"] not in roasteries: roasteries.append(row["roasteryName"]) print("Select a roastery from the list") for roastery in roasteries: print(f"\t=> {roastery}") userInput = str(input("\nEnter desired roastery: ")) roasteryMatches = list(filter(lambda row: row['roasteryName'] == userInput, result)) if len(roasteryMatches) == 0: print("No matches") return print(f"\nSelect a coffee from the roastery {userInput}") for row in roasteryMatches: print(f"\t=> {row['coffeeName']}") userInput = str(input("\nEnter desired coffee: ")) roastedCoffee = list(filter(lambda row: row['coffeeName'] == userInput, roasteryMatches)) if len(roastedCoffee) == 0: print("No matches") return roastedCoffee = roastedCoffee[0] userID = user.getUserID() roastedCoffeeID = roastedCoffee['roastedCoffeeID'] points = int(input("Enter points: ")) while not (0 <= points <= 10): points = int(input("Points has to be between 0 and 10. Enter points: ")) tasteNote = str(input("Enter taste note: ")) try: if ins.addTasting(tasteNote, points, userID, roastedCoffeeID): print("\nAdded tasting") else: print("\nFailed to add tasting") except Exception as e: print("Error:", e) def bh2(self): """ Userstory 2 :return: """ ret = Retrieve() result = ret.getUniqueTastings() for row in result: print(f"\t=> {row['firstName']} {row['surname']} has tasted {row['count']} unique coffees") def bh3(self): """ Userstory 3 :return: """ ret = Retrieve() result = ret.getCoffeeByValue() print("Here are the coffees that got the highest score compared to price\n") for row in result: print("\tRoastery Name:", row["roasteryName"]) print("\tCoffee name:", row["coffeeName"]) print("\tKilo price:", row["kiloPrice"]) print("\tScore (per 100 NOK):", round(row["score"], 2), "\n") def bh4(self): """ Userstory 4 :return: """ userInput = str(input("Enter searchword: ")) ret = Retrieve() result = ret.getCoffeeByDescription(userInput) if not userInput or len(result) == 0: print("\nNo matches") return else: print("\nReturned the following result(s):") for row in result: print(f"\t=> Roastery: {row['roasteryName']}\n\t=> Coffee: {row['coffeeName']}\n") def bh5(self): """ Userstory 5 :return: """ ret = Retrieve() result = ret.getCoffeeByCountryAndProcessingMethod() print("Showing unwashed coffees from Rwanda and Colombia: ") if len(result) == 0: print("No matches") else: for row in result: print("\t=> Roastery name:", row["roasteryName"]) print("\t=> Coffeename:", row["coffeeName"], "\n") main = Main() print("Userstory 1") main.bh1() print("\nUserstory 2") main.bh2() print("\nUserstory 3") main.bh3() print("\nUserstory 4") main.bh4() print("\nUserstory 5") main.bh5()
jathavaan/CoffeeDB
model/DBMS.py
DBMS.py
py
15,711
python
en
code
0
github-code
6
277437358
import torch import numpy as np from shapmagn.global_variable import DATASET_POOL from shapmagn.utils.obj_factory import partial_obj_factory # todo reformat the import style class DataManager(object): def __init__( self, ): """ the class for data management return a dict, each train/val/test/debug phase has its own dataloader """ self.data_path = None self.data_opt = None self.phases = [] def set_data_path(self, data_path): """ set data path :param data_path: :return: """ self.data_path = data_path def set_data_opt(self, data_opt): """ set data opt :param data_opt: :return: """ self.data_opt = data_opt def init_dataset_loader(self, transformed_dataset, batch_size): """ initialize the data loaders: set work number, set work type( shuffle for trainning, order for others) :param transformed_dataset: :param batch_size: the batch size of each iteration :return: dict of dataloaders for train|val|test|debug """ def _init_fn(worker_id): np.random.seed(12 + worker_id) num_workers_reg = { "train": 8, "val": 8, "test": 8, "debug": 4, } # {'train':0,'val':0,'test':0,'debug':0}#{'train':8,'val':4,'test':4,'debug':4} shuffle_list = {"train": True, "val": False, "test": False, "debug": False} batch_size = ( [batch_size] * 4 if not isinstance(batch_size, list) else batch_size ) batch_size = { "train": batch_size[0], "val": batch_size[1], "test": batch_size[2], "debug": batch_size[3], } dataloaders = { x: torch.utils.data.DataLoader( transformed_dataset[x], batch_size=batch_size[x], shuffle=shuffle_list[x], num_workers=num_workers_reg[x], worker_init_fn=_init_fn, pin_memory=True, ) for x in self.phases } return dataloaders def build_data_loaders(self, batch_size=20, is_train=True): """ build the data_loaders for the train phase and the test phase :param batch_size: the batch size for each iteration :param is_train: in train mode or not :return: dict of dataloaders for train phase or the test phase """ if is_train: self.phases = ["train", "val", "debug"] else: self.phases = ["test"] name = self.data_opt["name"] dataset_opt = self.data_opt[(name, {}, "settings for {} dataset".format(name))] assert name in DATASET_POOL, "{} not in dataset pool {}".format( name, DATASET_POOL ) if name!="custom_dataset": transformed_dataset = { phase: DATASET_POOL[name](self.data_path, dataset_opt, phase=phase) for phase in self.phases } else: transformed_dataset = { phase: partial_obj_factory(dataset_opt["name"])(self.data_path, dataset_opt, phase=phase) for phase in self.phases } dataloaders = self.init_dataset_loader(transformed_dataset, batch_size) dataloaders["data_size"] = { phase: len(dataloaders[phase]) for phase in self.phases } print("dataloader is ready") return dataloaders
uncbiag/shapmagn
shapmagn/datasets/data_manager.py
data_manager.py
py
3,588
python
en
code
94
github-code
6
32724214710
from setuptools import find_packages, setup VERSION = "0.1" INSTALL_REQUIRES = [ "alembic==1.9.4", "apischema==0.15.6", "asyncio==3.4.3", "configparser==5.3.0", "fastapi[all]==0.92.0", "psycopg2==2.9.1", "python-binance==1.0.16", "python-telegram-bot==20.0a2", "SQLAlchemy==1.4.37", ] setup( name="report-calculation", version=VERSION, python_requires=">=3.9.0", packages=find_packages(exclude=["tests"]), author="Daniel Ducuara", author_email="[email protected]", description="Get a report of my porfolio", include_package_data=True, entry_points={ "console_scripts": [ "report-calculation = report_calculation.main:main", # "console = report_calulation.main:console", ] }, install_requires=INSTALL_REQUIRES, extras_require={ "dev": [ "alembic==1.9.4", "bandit==1.7.0", "mypy==0.931", "pre-commit==3.1.0", "pylint==2.7.0", "black==22.10.0", "isort==5.10.1", "beautysh==6.2.1", "autoflake==1.7.7", ], "test": [ "pytest==6.2.4", "pytest-mock==3.6.1", "pytest-cov==2.12.1", "pytest-asyncio==0.15.1", ], }, )
DanielDucuara2018/report_calculation
setup.py
setup.py
py
1,329
python
en
code
0
github-code
6
73944509946
import os import numpy as np import cv2 from config import cfg from numpy.linalg import inv import sys class RawData(object): def __init__(self, use_raw = False): self.mapping_file = cfg.MAPPING_FILE self.rand_map = cfg.RAND_MAP self.path_prefix = "" self.ext = "" self.files_path_mapping = {} self.use_raw = use_raw self.train_val_list = cfg.TRAIN_VAL_LIST def get_trainval_mapping(self): trainval_list_dict = {} with open(self.train_val_list, 'r') as f: lines = f.read().splitlines() line_list = [[line, os.path.join(self.path_prefix, "%s" % (line)) + self.ext] for line in lines] trainval_list_dict = dict(line_list) return trainval_list_dict def get_paths_mapping(self): """ :return: frame_tag_mapping (key: frame_tag val: file_path) """ reverse_file_dict = {} with open(self.rand_map, "r") as f: line = f.read().splitlines()[0] for i, field in enumerate(line.split(',')): reverse_file_dict[int(field)] = os.path.join(self.path_prefix, "%06d" % (i)) + self.ext with open(self.mapping_file, "r") as f: lines = f.read().splitlines() lines_splitted = [line.split() for line in lines] frame_tag_lines = [('/'.join(line), index) for index, line in enumerate(lines_splitted)] frame_tag_map = {} for one_frame_tag_line in frame_tag_lines: frame_tag, index = one_frame_tag_line frame_tag_map[frame_tag] = reverse_file_dict[int(index) + 1] return frame_tag_map def get_tags(self): tags = [tag for tag in self.files_path_mapping] tags.sort() return tags class Image(RawData): def __init__(self, use_raw = False): RawData.__init__(self, use_raw) self.path_prefix = os.path.join(cfg.RAW_DATA_SETS_DIR, "data_object_image_2", "training", "image_2") self.ext = ".png" if use_raw: self.files_path_mapping= self.get_paths_mapping() else: self.files_path_mapping= self.get_trainval_mapping() def load(self, frame_tag): return cv2.imread(self.files_path_mapping[frame_tag]) class ObjectAnnotation(RawData): def __init__(self, use_raw = False): RawData.__init__(self, use_raw) self.path_prefix = os.path.join(cfg.RAW_DATA_SETS_DIR, "data_object_label_2", "training", "label_2") self.ext = ".txt" if use_raw: self.files_path_mapping= self.get_paths_mapping() else: self.files_path_mapping= self.get_trainval_mapping() def parseline(self, line): obj = type('object_annotation', (), {}) fields = line.split() obj.type, obj.trunc, obj.occlu = fields[0], float(fields[1]), float(fields[2]) obj.alpha, obj.left, obj.top, obj.right, obj.bottom = float(fields[3]), float(fields[4]), float(fields[5]), \ float(fields[6]), float(fields[7]) obj.h, obj.w, obj.l, obj.x, obj.y, obj.z, obj.rot_y = float(fields[8]), float(fields[9]), float(fields[10]), \ float(fields[11]), float(fields[12]), float(fields[13]), float(fields[14]) return obj def load(self, frame_tag): """ load object annotation file, including bounding box, and object label :param frame_tag: :return: """ annot_path = self.files_path_mapping[frame_tag] objs = [] with open(annot_path, 'r') as f: lines = f.read().splitlines() for line in lines: if not line: continue objs.append(self.parseline(line)) return objs class Calibration(RawData): def __init__(self, use_raw = False): RawData.__init__(self, use_raw) self.path_prefix = os.path.join(cfg.RAW_DATA_SETS_DIR, "data_object_calib", "training", "calib") self.ext = ".txt" if use_raw: self.files_path_mapping= self.get_paths_mapping() else: self.files_path_mapping= self.get_trainval_mapping() def load(self, frame_tag): """ load P2 (for rgb camera 2), R0_Rect, Tr_velo_to_cam, and compute the velo_to_rgb :param frame_tag: e.g.,2011_09_26/2011_09_26_drive_0009_sync/0000000021 :return: calibration matrix """ calib_file_path = self.files_path_mapping[frame_tag] obj = type('calib', (), {}) with open(calib_file_path, 'r') as f: lines = f.read().splitlines() for line in lines: if not line: continue fields = line.split(':') name, calib_str = fields[0], fields[1] calib_data = np.fromstring(calib_str, sep=' ', dtype=np.float32) if name == 'P2': obj.P2 = np.hstack((calib_data, [0, 0, 0, 1])).reshape(4, 4) elif name == 'R0_rect': obj.R0_rect = np.zeros((4, 4), dtype = calib_data.dtype) obj.R0_rect[:3, :3] = calib_data.reshape((3, 3)) obj.R0_rect[3, 3] = 1 elif name == 'Tr_velo_to_cam': obj.velo_to_cam = np.hstack((calib_data, [0, 0, 0, 1])).reshape(4, 4) obj.velo_to_rgb = np.dot(obj.P2, np.dot(obj.R0_rect, obj.velo_to_cam)) obj.cam_to_rgb = np.dot(obj.P2, obj.R0_rect) obj.cam_to_velo = inv(obj.velo_to_cam) return obj class Lidar(RawData): def __init__(self, use_raw = False): RawData.__init__(self, use_raw) self.path_prefix = os.path.join(cfg.RAW_DATA_SETS_DIR, "data_object_velodyne", "training", "velodyne") self.ext = ".bin" if use_raw: self.files_path_mapping= self.get_paths_mapping() else: self.files_path_mapping= self.get_trainval_mapping() def load(self, frame_tag): lidar =np.fromfile(self.files_path_mapping[frame_tag], np.float32) return lidar.reshape((-1, 4)) if __name__ == '__main__': pass
yzhou-saic/MV3D_Yang
src/raw_data_from_mapping.py
raw_data_from_mapping.py
py
6,272
python
en
code
2
github-code
6
40128531124
if 0: N = int(input()) Q = int(input()) queries = [] for i in range(Q): queries.append([int(x) for x in input().split()]) else: N = 100000 queries = [ [2, 1, 2], [4, 1, 2] ] * 10000 queries.append([4, 1, 2]) Q = len(queries) def reverseTime(x, y): # print(frm) for q in reversed(actions): f = q[0] if f == 3: x, y = y, x elif f == 1: i, j = q[1:] if x == i: x = j elif x == j: x = i elif f == 2: i, j = q[1:] if y == i: y = j elif y == j: y = i #print(N * (x - 1) + y - 1) actions = [] for t in range(Q): if queries[t][0] == 4: _f, i, j = queries[t] reverseTime(i, j) else: actions.append(queries[t])
nishio/atcoder
PAST3/i_old.py
i_old.py
py
889
python
en
code
1
github-code
6
17650834567
from Node import Node import copy class LinkedList: def __init__(self) -> None: self.HeadNode = None def Insert(self,NodeToInsert:Node): NodeToInsert.Next = self.HeadNode self.HeadNode = NodeToInsert def Search(self,Key): CurrentNode = self.HeadNode while CurrentNode != None and CurrentNode.Key != Key: CurrentNode = CurrentNode.Next return CurrentNode def printSelf(self): CurrentNode = self.HeadNode Output = "" while CurrentNode.Next != None: Output = Output + f"{CurrentNode} -> " CurrentNode = CurrentNode.Next Output = Output + f"{CurrentNode}" print(Output)
AbhinavPradeep/HashTableWithListChaining
LinkedList.py
LinkedList.py
py
717
python
en
code
0
github-code
6
36689801955
from ..nmf import (PreambleEndRecord, ViaRecord, VersionRecord, ModeRecord, KnownEncodingRecord, UpgradeRequestRecord, UpgradeResponseRecord, Record, register_types, SizedEnvelopedMessageRecord, PreambleAckRecord, EndRecord) from .gssapi import GSSAPIStream class NMFStream: def __init__(self, stream, url, server_name=None): self._inner = stream self._server_name = server_name self.url = url register_types() def preamble(self): data = [ VersionRecord(MajorVersion=1, MinorVersion=0), ModeRecord(Mode=2), ViaRecord(ViaLength=len(self.url), Via=self.url), KnownEncodingRecord(Encoding=8), ] self._inner.write(b''.join(d.to_bytes() for d in data)) if self._server_name: msg = UpgradeRequestRecord(UpgradeProtocolLength=21, UpgradeProtocol='application/negotiate').to_bytes() self._inner.write(msg) d = self._inner.read(1) if d != UpgradeResponseRecord().to_bytes(): raise IOError('Negotiate not supported') self._inner = GSSAPIStream(self._inner, self._server_name) self._inner.write(PreambleEndRecord().to_bytes()) if self._inner.read(1) != PreambleAckRecord().to_bytes(): raise IOError('Preamble end not acked') def write(self, data): msg = SizedEnvelopedMessageRecord(Size=len(data), Payload=data) self._inner.write(msg.to_bytes()) def read(self, count=None): if count: data = self._inner.read(count) s, msg = Record.parse(data) return data[s:msg.Size+s] else: msg = Record.parse_stream(self._inner) return msg.Payload def close(self): self._inner.write(EndRecord().to_bytes()) self._inner.close()
ernw/net.tcp-proxy
nettcp/stream/nmf.py
nmf.py
py
1,954
python
en
code
54
github-code
6
10158111328
from django.shortcuts import render, redirect from app14.models import ProductModel def openmainpage(request): if request.method == "POST": name = request.POST.get("product_name") price = request.POST.get("product_price") photo = request.FILES["product_photo"] ProductModel(name=name, price=price, photo=photo).save() return redirect('main') else: return render(request, 'main.html')
suchishree/django_assignment1
project14/app14/views.py
views.py
py
443
python
en
code
0
github-code
6
26043231137
import cv2 import pickle import numpy as np espacios = [] with open('prueba.pkl', 'rb') as file: espacios = pickle.load(file) video = cv2.VideoCapture('video.mp4') # Inicializar el contador de cuadros ocupados full = 0 # Inicializar el estado de cada cuadro estado = [False] * len(espacios) while True: check, img = video.read() imgBN = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) imgTH = cv2.adaptiveThreshold(imgBN, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 25, 16) imgMedian = cv2.medianBlur(imgTH, 5) kernel = np.ones((5, 5), np.int8) imgDil = cv2.dilate(imgMedian, kernel) for i, (x, y, w, h) in enumerate(espacios): espacio = imgDil[y:y+h, x:x+w] count = cv2.countNonZero(espacio) cv2.putText(img, str(count), (x, y+h-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1) cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) if count >= 600: if not estado[i]: full += 1 estado[i] = True # Cambié el color a azul para lugar ocupado cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) else: if estado[i]: full -= 1 estado[i] = False # Cuadro verde para lugar vacío cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) # Mostrar el número de cuadros ocupados en el texto texto = f"Personas: {full}" cv2.putText(img, texto, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2) cv2.imshow('video', img) cv2.waitKey(10)
Kinartb/CC431A_Grafica
PC1/PC1_TRABAJO/main.py
main.py
py
1,599
python
es
code
0
github-code
6
19772432260
#!/usr/bin/env python # coding: utf-8 # In[40]: import math import pandas as pd import numpy as np from pyspark.sql import SparkSession import pyspark.sql.functions as fc import json import requests spark = SparkSession.builder.config("spark.sql.warehouse.dir", "file:///C:/temp").appName("readCSV").getOrCreate() Data = spark.read.csv('Realtor_info.csv', header=True) Data1 = spark.read.csv('School_location1.csv', header=True) Data = Data.toPandas() Data1 = Data1.toPandas() def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km dlat = math.radians(lat2 - lat1) dlon = math.radians(lon2 - lon1) a = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = radius * c return d Data = Data.dropna() Data = Data.reset_index(drop=True) # In[41]: Data['Avg_sqft(PCode)'] = np.nan postal_codes = Data['postal_code'].tolist() postal_codes = list(set(postal_codes)) for postal in postal_codes: postal_values = Data[Data['postal_code'] == postal] sqfts = postal_values['sqft'].tolist() sqfts1 = [] for i in sqfts: try: s = int(''.join(filter(str.isdigit,i))) except: s = 0 sqfts1.append(s) if len(sqfts1) !=0 : avg = sum(sqfts1)/len(sqfts1) Data['Avg_sqft(PCode)'].loc[postal_values.index] = avg # In[46]: Distance = [] School = [] for i in range(len(Data)): distance1 = [] school1 = [] for j in range(len(Data1)): if Data['city'][i] == Data1['CITY'][j]: lat1 = (float(Data['lat'][i]),float((Data['lon'][i]))) lat2 = (float(Data1['LAT'][j]),float((Data1['LON'][j]))) dist = round(distance(lat1, lat2), 1) distance1.append(dist) school1.append(Data1['NAME'][j]) else: continue if len(distance1) !=0: Distance.append(max(distance1)) School.append(school1[distance1.index(max(distance1))]) else: Distance.append(10000) School.append('No-school') # In[45]: ''' Distance_1 = Distance School_1 = School print(Distance_1) print(School_1) Distance_1.extend(Distance) School_1.extend(School) ''' # In[49]: school_distinct = [] for i in Distance: if i < 10: school_distinct.append('Yes') else: school_distinct.append('No') # In[50]: Data['School_district'] = school_distinct Data['Nearly_school'] = School # In[59]: Data['Avg_price(PCode)'] = np.nan postal_codes = Data['postal_code'].tolist() for postal in postal_codes: postal_values = Data[Data['postal_code'] == postal] prices = postal_values['price'].tolist() prices1 = [] for j in prices: try: p = int(''.join(filter(str.isdigit,j))) except: p = 0 prices1.append(p) if len(prices1) !=0 : avg1 = sum(prices1)/len(prices1) Data['Avg_price(PCode)'].loc[postal_values.index] = avg1 # In[61]: Data.to_csv("Realtor_info1.csv", index=False, sep=',') with open('Realtor_info1.json', 'w') as f: f.write(Data.to_json(orient='records')) # In[62]: result = Data.to_json(orient="records") parsed = json.loads(result) data = json.dumps(parsed) url = 'https://house-9f5c0-default-rtdb.firebaseio.com/Realtor.json' response = requests.put(url,data) # In[58]:
Lucas0717/house-search
spark_py/process_distinct_school.py
process_distinct_school.py
py
3,500
python
en
code
0
github-code
6
42339522829
from gtts import gTTS import speech_recognition as sr import os import time import webbrowser r = sr.Recognizer() order = "what can i do for you?" tts = gTTS(order) tts.save("order.mp3") os.startfile(r"C:\Users\Yodi\PycharmProjects\try\order.mp3") time.sleep(3) arr = [["Paradise", "someone"], ["kZ2xL_Nuzag", "XsHWQdriEO8"]] with sr.Microphone() as source: print(order) audio = r.listen(source) try: text = r.recognize_google(audio) print("command: {}".format(text)) if any(word in "play music" for word in text): print("Music Option is Activated") songorder = "which coldplay song should i play?" tts = gTTS(songorder) tts.save("indonesia.mp3") os.startfile(r"C:\Users\Yodi\PycharmProjects\try\indonesia.mp3") time.sleep(3) try: print("mention the song") audio = r.listen(source) song = r.recognize_google(audio) print("Song Selected: {}".format(song)) for i in range(len(arr)): if song.lower() in arr[0][i]: song_url = arr[1][i] base_url = "https://www.youtube.com/watch?v=" main_url = base_url + song_url webbrowser.open(main_url, new=2) time.sleep(3) print("music option exit") except: print("sorry could not hear your request") except: print("sorry could not hear from you")
yodifm/SpeechRecognition
SR/main.py
main.py
py
1,657
python
en
code
0
github-code
6
6412275616
#====================================================================================== # Напишите программу, которая принимает на вход цифру, обозначающую день недели, # и проверяет, является ли этот день выходным. #====================================================================================== week = [1, 2, 3, 4, 5, 6, 7] input_number = int(input('Введите номер дня недели: ')) if input_number <= 7: for i in range(0, len(week), 1): if input_number == week[i]: if week[i] == 6 or week[i] == 7: print('Это выходной день') else: print('Это рабочий день') else: print('Такого дня в неделе нет')
screwupug/Python_GeekBrains
sem1/sem1_homework1.py
sem1_homework1.py
py
860
python
ru
code
0
github-code
6
43424744194
import os from aiohttp import web from cdtz import config LIST_TZ = [] def create_list_tz(): """Create list timezones. """ dir_zoneinfo = '/usr/share/zoneinfo' for dirpath, dirnames, filenames in os.walk(dir_zoneinfo): for file in filenames: filepath = os.path.join(dirpath, file) if open(filepath, 'rb').read(4) == b'TZif': filename = filepath.replace(f'{dir_zoneinfo}/', '') if filename not in ['Factory', 'localtime', 'posixrules', 'Riyadh8']: LIST_TZ.append(filename) LIST_TZ.sort() async def get_list_tz(request): """Returns list timezone. """ return web.json_response(LIST_TZ) async def main(): """The main entry point. """ app = web.Application() app.router.add_get('/tz/list_time_zones', get_list_tz) return app if __name__ == '__main__': create_list_tz() web.run_app(main(), host=config.HOST, port=config.PORT)
IrovoyVlad/cusdeb-tz
bin/server.py
server.py
py
967
python
en
code
0
github-code
6
18921275912
"""Test the codeclimate JSON formatter.""" from __future__ import annotations import json import os import pathlib import subprocess import sys from tempfile import NamedTemporaryFile import pytest from ansiblelint.errors import MatchError from ansiblelint.file_utils import Lintable from ansiblelint.formatters import SarifFormatter from ansiblelint.rules import AnsibleLintRule, RulesCollection class TestSarifFormatter: """Unit test for SarifFormatter.""" rule1 = AnsibleLintRule() rule2 = AnsibleLintRule() matches: list[MatchError] = [] formatter: SarifFormatter | None = None collection = RulesCollection() collection.register(rule1) collection.register(rule2) def setup_class(self) -> None: """Set up few MatchError objects.""" self.rule1.id = "TCF0001" self.rule1.severity = "VERY_HIGH" self.rule1.description = "This is the rule description." self.rule1.link = "https://rules/help#TCF0001" self.rule1.tags = ["tag1", "tag2"] self.rule2.id = "TCF0002" self.rule2.severity = "MEDIUM" self.rule2.link = "https://rules/help#TCF0002" self.rule2.tags = ["tag3", "tag4"] self.matches.extend( [ MatchError( message="message1", lineno=1, column=10, details="details1", lintable=Lintable("filename1.yml", content=""), rule=self.rule1, tag="yaml[test1]", ignored=False, ), MatchError( message="message2", lineno=2, details="", lintable=Lintable("filename2.yml", content=""), rule=self.rule1, tag="yaml[test2]", ignored=True, ), MatchError( message="message3", lineno=666, column=667, details="details3", lintable=Lintable("filename3.yml", content=""), rule=self.rule2, tag="yaml[test3]", ignored=False, ), ], ) self.formatter = SarifFormatter(pathlib.Path.cwd(), display_relative_path=True) def test_sarif_format_list(self) -> None: """Test if the return value is a string.""" assert isinstance(self.formatter, SarifFormatter) assert isinstance(self.formatter.format_result(self.matches), str) def test_sarif_result_is_json(self) -> None: """Test if returned string value is a JSON.""" assert isinstance(self.formatter, SarifFormatter) output = self.formatter.format_result(self.matches) json.loads(output) # https://github.com/ansible/ansible-navigator/issues/1490 assert "\n" not in output def test_sarif_single_match(self) -> None: """Test negative case. Only lists are allowed. Otherwise, a RuntimeError will be raised.""" assert isinstance(self.formatter, SarifFormatter) with pytest.raises(RuntimeError): self.formatter.format_result(self.matches[0]) # type: ignore[arg-type] def test_sarif_format(self) -> None: """Test if the return SARIF object contains the expected results.""" assert isinstance(self.formatter, SarifFormatter) sarif = json.loads(self.formatter.format_result(self.matches)) assert len(sarif["runs"][0]["results"]) == 3 for result in sarif["runs"][0]["results"]: # Ensure all reported entries have a level assert "level" in result # Ensure reported levels are either error or warning assert result["level"] in ("error", "warning") def test_validate_sarif_schema(self) -> None: """Test if the returned JSON is a valid SARIF report.""" assert isinstance(self.formatter, SarifFormatter) sarif = json.loads(self.formatter.format_result(self.matches)) assert sarif["$schema"] == SarifFormatter.SARIF_SCHEMA assert sarif["version"] == SarifFormatter.SARIF_SCHEMA_VERSION driver = sarif["runs"][0]["tool"]["driver"] assert driver["name"] == SarifFormatter.TOOL_NAME assert driver["informationUri"] == SarifFormatter.TOOL_URL rules = driver["rules"] assert len(rules) == 3 assert rules[0]["id"] == self.matches[0].tag assert rules[0]["name"] == self.matches[0].tag assert rules[0]["shortDescription"]["text"] == self.matches[0].message assert rules[0]["defaultConfiguration"][ "level" ] == SarifFormatter.get_sarif_rule_severity_level(self.matches[0].rule) assert rules[0]["help"]["text"] == self.matches[0].rule.description assert rules[0]["properties"]["tags"] == self.matches[0].rule.tags assert rules[0]["helpUri"] == self.matches[0].rule.url results = sarif["runs"][0]["results"] assert len(results) == 3 for i, result in enumerate(results): assert result["ruleId"] == self.matches[i].tag assert ( result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] == self.matches[i].filename ) assert ( result["locations"][0]["physicalLocation"]["artifactLocation"][ "uriBaseId" ] == SarifFormatter.BASE_URI_ID ) assert ( result["locations"][0]["physicalLocation"]["region"]["startLine"] == self.matches[i].lineno ) if self.matches[i].column: assert ( result["locations"][0]["physicalLocation"]["region"]["startColumn"] == self.matches[i].column ) else: assert ( "startColumn" not in result["locations"][0]["physicalLocation"]["region"] ) assert result["level"] == SarifFormatter.get_sarif_result_severity_level( self.matches[i], ) assert sarif["runs"][0]["originalUriBaseIds"][SarifFormatter.BASE_URI_ID]["uri"] assert results[0]["message"]["text"] == self.matches[0].details assert results[1]["message"]["text"] == self.matches[1].message def test_sarif_parsable_ignored() -> None: """Test that -p option does not alter SARIF format.""" cmd = [ sys.executable, "-m", "ansiblelint", "-v", "-p", ] file = "examples/playbooks/empty_playbook.yml" result = subprocess.run([*cmd, file], check=False) result2 = subprocess.run([*cmd, "-p", file], check=False) assert result.returncode == result2.returncode assert result.stdout == result2.stdout @pytest.mark.parametrize( ("file", "return_code"), ( pytest.param("examples/playbooks/valid.yml", 0, id="0"), pytest.param("playbook.yml", 2, id="1"), ), ) def test_sarif_file(file: str, return_code: int) -> None: """Test ability to dump sarif file (--sarif-file).""" with NamedTemporaryFile(mode="w", suffix=".sarif", prefix="output") as output_file: cmd = [ sys.executable, "-m", "ansiblelint", "--sarif-file", str(output_file.name), ] result = subprocess.run([*cmd, file], check=False, capture_output=True) assert result.returncode == return_code assert os.path.exists(output_file.name) # noqa: PTH110 assert pathlib.Path(output_file.name).stat().st_size > 0 @pytest.mark.parametrize( ("file", "return_code"), (pytest.param("examples/playbooks/valid.yml", 0, id="0"),), ) def test_sarif_file_creates_it_if_none_exists(file: str, return_code: int) -> None: """Test ability to create sarif file if none exists and dump output to it (--sarif-file).""" sarif_file_name = "test_output.sarif" cmd = [ sys.executable, "-m", "ansiblelint", "--sarif-file", sarif_file_name, ] result = subprocess.run([*cmd, file], check=False, capture_output=True) assert result.returncode == return_code assert os.path.exists(sarif_file_name) # noqa: PTH110 assert pathlib.Path(sarif_file_name).stat().st_size > 0 pathlib.Path.unlink(pathlib.Path(sarif_file_name))
ansible/ansible-lint
test/test_formatter_sarif.py
test_formatter_sarif.py
py
8,597
python
en
code
3,198
github-code
6
4306296022
import pandas as pd import numpy as np def inference_input_processing(df: pd.DataFrame) -> np.array: """ The input of the function is a dataframe with the corresponding columns: x1, x2, ..., x6, z, and the output is processed data input, ready to broadcast to model :param df: :return: """ # both tasks must be performed during inference df['mask_t1'], df['mask_t2'] = 1, 1 # ensure columns order df = df[['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'z', 'mask_t1', 'mask_t2']] return np.array(df.values.tolist()) def predict(input_data: np.array, model) -> None: input_df = pd.DataFrame(data=[input_data], columns=['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'z']) X = inference_input_processing(input_df) model.inference(X)
tarasevic-r/multi-task-learning
utils/data_processing.py
data_processing.py
py
770
python
en
code
0
github-code
6
3666745897
from flask import Flask, request from flask_cors import CORS from pingback import ping_urls app = Flask(__name__) cors = CORS(app, resources=r'/pingback/', methods=['POST']) @app.route('/pingback/', methods=['GET', 'POST']) def api(): if request.method == 'POST': try: if request.is_json: return handle_request(request.get_json()) else: return {"error": "Request not json"}, 400 except ValueError: return {"error": "Bad Request"}, 400 else: return {"error": "method don't support."}, 405 def handle_request(object): source_url = object["source_url"] target_url_list = object["target_url_list"] if isinstance(source_url, str) and isinstance(target_url_list, list): return ping_urls(source_url, target_url_list) else: raise ValueError if __name__ == '__main__': app.run(debug=True)
yingziwu/pingback
api.py
api.py
py
924
python
en
code
0
github-code
6
34825650741
from machine import Pin, Timer import time class SensorLinha: """Classe para controlar os sensores de linha""" # Pinos dos sensores de linha R_TCRT = 26 L_TCRT = 25 # Contagem para o debounce CONTAGEM = 10 def __init__(self): self.sensor_direita = Pin(self.R_TCRT, Pin.IN) self.sensor_esquerda = Pin(self.L_TCRT, Pin.IN) self.estado_direita = 0 self.estado_esquerda = 0 self.amostras_direita = self.CONTAGEM self.amostras_esquerda = self.CONTAGEM self.tim1 = Timer(1) self._init_timer() def _recebe_valores(self, t): if (self.sensor_direita.value() != self.estado_direita): # Se contagem = 0, debounce terminado self.amostras_direita -= 1 if (self.amostras_direita <= 0): self.estado_direita = self.sensor_direita.value() else: self.amostras_direita = self.CONTAGEM if (self.sensor_esquerda.value() != self.estado_esquerda): # Se contagem = 0, debounce terminado self.amostras_esquerda -= 1 if (self.amostras_esquerda <= 0): self.estado_esquerda = self.sensor_esquerda.value() else: self.amostras_esquerda = self.CONTAGEM def direita(self): return self.estado_direita def esquerda(self): return self.estado_esquerda def _init_timer(self, period_ms = 5): self.tim1.init(period=period_ms, mode=Timer.PERIODIC, callback=self._recebe_valores) if __name__ == '__main__': sensores = SensorLinha() while(1): time.sleep(0.5) print("ESTADO DIREITA = ", sensores.direita()) print("ESTADO ESQUERDA = ", sensores.esquerda())
NycolasAbreu/Buggy_TCC
Buggy/sensor_linha.py
sensor_linha.py
py
1,777
python
pt
code
0
github-code
6
40322657669
# i have created this file prajakta ... from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request,'index.html') def analyze(request): #get the text djtext=request.POST.get('text','default') #checkbox value removepunc=request.POST.get('removepunc','off') fullcaps=request.POST.get('fullcaps','off') newlineremover=request.POST.get('newlineremover','off') extraspaceremover = request.POST.get('extraspaceremover', 'off') charcount=request.POST.get('charcount', 'off') #check wich checkbox on if(len(djtext)==0): return render(request,'error.html') if (removepunc=="on"): analyzed="" punctuations = '''!()-[];:'"\,<>./?@#$%^&*_~''' for char in djtext: if char not in punctuations: analyzed=analyzed+char params={'purpose':'Removed Punctuations','analyzed_text':analyzed} djtext=analyzed #return render(request,'analyze.html',params) if (fullcaps=='on'): analyzed="" for char in djtext: analyzed = analyzed+char.upper() params = {'purpose': 'CHANGED STATEMENT IN UPPERCASE', 'analyzed_text': analyzed} djtext = analyzed #return render(request, 'analyze.html', params) if (newlineremover=='on'): analyzed = "" for char in djtext: if char !="\n" and char !="\r": analyzed = analyzed+char params = {'purpose': 'removed newline', 'analyzed_text': analyzed} djtext = analyzed if (extraspaceremover=='on'): analyzed = "" for index,char in enumerate(djtext): if djtext[index]==" " and djtext[index+1]==" " : pass else: analyzed = analyzed + char params = {'purpose': 'removed space', 'analyzed_text': analyzed} djtext = analyzed #return render(request, 'analyze.html', params) if (charcount=='on'): analyzed = 0 for char in djtext: if char != " ": analyzed=analyzed+1 params = {'purpose': 'Character counted are', 'analyzed_text': analyzed} djtext = analyzed if(charcount!="on" and extraspaceremover!="on" and removepunc!="on" and newlineremover!="on" and fullcaps!="on"): return render(request,'error.html') return render(request, 'analyze.html', params)
maneprajakta/textprox
harry/views.py
views.py
py
2,439
python
en
code
3
github-code
6
29979204168
import gensim from gensim.models import Word2Vec import gradio as gr # Load your trained Word2Vec model model = Word2Vec.load("word2vecsg2.model") def recommend_ingredients(*ingredients): # Filter out any None values from the ingredients ingredients = [i for i in ingredients if i] # Get most similar ingredients similar_ingredients = model.wv.most_similar(positive=ingredients, topn=8) # Format the output output = "\n".join([f"{ingredient}: %{round(similarity*100, 2)}" for ingredient, similarity in similar_ingredients]) return output # Get the vocabulary of the model and sort it alphabetically vocab = sorted(model.wv.index_to_key) # Allow user to select multiple ingredients ingredient_selections = [gr.inputs.Dropdown(choices=vocab, label=f"Ingredients {i+1}") for i in range(6)] # Create the interface iface = gr.Interface( fn=recommend_ingredients, inputs=ingredient_selections, outputs="text", title="Ingredient Recommender", description="Select up to 6 ingredients to get recommendations for similar ingredients.", layout="vertical" ) iface.launch()
egecandrsn/FoodPair.v0
app.py
app.py
py
1,134
python
en
code
0
github-code
6
70779220028
import os from accelerate.utils import is_tpu_available from ..dataset import FlattenDataset, ReprDataset from ..models import CachedS4, FlattenS4 from ..utils.trainer_utils import PredLoss, PredMetric from . import register_trainer from .base import Trainer @register_trainer("flatten_s4") class FlattenS4Trainer(Trainer): def __init__(self, args): assert not is_tpu_available(), "TPU is not supported for this task" super().__init__(args) self.dataset = FlattenDataset self.architecture = FlattenS4 self.criterion = PredLoss(self.args) self.metric = PredMetric(self.args) self.data_path = os.path.join( args.input_path, f"{args.pred_time}h", f"{args.src_data}.h5" ) @register_trainer("cached_s4") class CachedS4Trainer(Trainer): def __init__(self, args): assert not is_tpu_available(), "TPU is not supported for this task" super().__init__(args) self.dataset = ReprDataset self.architecture = CachedS4 self.criterion = PredLoss(self.args) self.metric = PredMetric(self.args) if args.encoded_dir: self.data_path = os.path.join( args.encoded_dir, f"{args.src_data}_encoded.h5" ) else: self.data_path = os.path.join( args.save_dir, args.pretrained, f"{args.src_data}_encoded.h5" )
starmpcc/REMed
src/trainer/s4.py
s4.py
py
1,418
python
en
code
8
github-code
6
39069895078
import time import serial import re from .haversine import haversine from threading import Thread from datetime import datetime, timedelta class Gps: def __init__(self, serial_port: str, timezone_hours: int = 0, serial_baudrate: int = 9600, round_number: int = 2): self.__serial = serial.Serial(serial_port, serial_baudrate) # self.file = open("aaa.txt", "a+") self._round_number = round_number self.__timezone_offset = timedelta(hours=timezone_hours) self.__quality = 0 # 0 not fixed / 1 standard GPS / 2 differential GPS / 3 estimated (DR) fix self.__speed = 0 # speed over ground km/h self.__altitude = 0 # altitude (m) self.__latitude = 0 self.__travelled_distance = 0 self.__longitude = 0 self.__satellites = 0 # number of satellites in use self.__time = 0 # UTC time hhmmss.ss self.__date = 0 # date in day, month, year format ddmmyy es. 091219 self.__pos_0 = ('', '') self._worker = Thread(target=self._run, daemon=False) self._worker.start() @property def fixed(self): return self.__quality != 0 @property def position(self): position = (self.latitude, self.longitude) return position @property def altitude(self): altitude = safe_cast(self.__altitude, float, .0) return altitude @property def latitude(self): latitude = safe_cast(self.__latitude, float, .0) return latitude @property def longitude(self): longitude = safe_cast(self.__longitude, float, .0) return longitude @property def speed(self): speed = safe_cast(self.__speed, float, .0) return round(speed, self._round_number) @property def satellites(self): satellites = safe_cast(self.__satellites, int, 0) return satellites @property def time(self): # UTC time hhmmss.ss p_hours = str(self.__time)[0:2] p_minutes = str(self.__time)[2:4] if isinstance(self.__time, str) else "00" p_seconds = str(self.__time)[4:6] if isinstance(self.__time, str) else "00" return '{}:{}:{}'.format(p_hours, p_minutes, p_seconds) @property def date(self): # date in day, month, year format ddmmyy es. 091219 self.__date = "010100" if self.__date == 0 else str(self.__date) p_day = self.__date[0:2] p_month = self.__date[2:4] p_year = self.__date[4:6] return '20{}-{}-{}'.format(p_year, p_month, p_day) @property def timestamp(self): # timestamp = '{} {}'.format(self.date, self.time) # utc = datetime.strptime(timestamp, '%y-%m-%d %H:%M:%S') # timestamp_f = utc + self.timezone_offset return '{} {}'.format(self.date, self.time) def distance(self, latitude: float, longitude: float): position_distance = (latitude, longitude) return round(haversine(self.position, position_distance), self._round_number) @property def travelled_distance(self): return round(self.__travelled_distance, self._round_number) def _run(self): last_print = time.monotonic() while True: try: # serial read line by line line = self.__serial.read_until('\n'.encode()).decode() # print(line) self.parse_line(line) except UnicodeDecodeError: print("Invalid line format") time.sleep(0.1) def parse_line(self, line: str): splitted_line = line.split(',') name = splitted_line[0] if re.match("^\$..GGA$", name): self.parse_xxGGA(splitted_line) elif re.match("^\$..GLL$", name): self.parse_xxGLL(splitted_line) elif re.match("^\$..RMC$", name): self.parse_xxRMC(splitted_line) elif re.match("^\$..VTG$", name): self.parse_xxVTG(splitted_line) def parse_xxGGA(self, line: list): if line.__len__() < 15: return self.__time = line[1] self.nmea_cord_to_decimal(line[3], line[5]) self.add_distance(self.latitude, self.longitude) self.__quality = line[6] self.__satellites = line[7] self.__altitude = line[9] def parse_xxGLL(self, line): if line.__len__() < 8: return self.nmea_cord_to_decimal(line[1], line[3]) def parse_xxRMC(self, line): if line.__len__() < 13: return self.__time = line[1] self.nmea_cord_to_decimal(line[3], line[5]) self.__date = line[9] def parse_xxVTG(self, line): if line.__len__() < 10: return self.__speed = line[7] @travelled_distance.setter def travelled_distance(self, value): self.__travelled_distance = value def add_distance(self, latitude, longitude): if self.fixed: pos_1 = (latitude, longitude) if longitude != '' and latitude != '' and self.__pos_0[0] != '' and self.__pos_0[1] != '': d = haversine(self.__pos_0, pos_1) if d > 1: self.__travelled_distance += d self.__pos_0 = pos_1 def nmea_cord_to_decimal(self, latitude, longitude): if not re.match("[0-9]{4}.[0-9]+", latitude) or not re.match("[0-9]{5}.[0-9]+", longitude): return self.__latitude = float(latitude[0:2]) + float(latitude[2:])/60 self.__longitude = float(longitude[0:3]) + float(longitude[3:])/60 def safe_cast(val, to_type, default=None): try: return to_type(val) except (ValueError, TypeError): return default
policumbent/bob
modules/gps/src/steGPS/gps.py
gps.py
py
5,732
python
en
code
4
github-code
6
5010903927
def multiplyMatrices(matrix1, matrix2): if checkIfMatrixIsValid(matrix1) == False: return None if checkIfMatrixIsValid(matrix2) == False: return None ROW1,COL1 = getMatrixSize(matrix1); ROW2,COL2 = getMatrixSize(matrix2); if COL1 != ROW2: # cannot multiply matrices that do not satisfy this condition return None # created resulting matrix below. myMatrix = [ [0] * COL2 for i in range(ROW1) ] # Below is code to populate the Matrix for i in range(ROW1): for j in range(COL2): myMatrix[i][j] = dotProduct( getRow(matrix1,i) , getColumn(matrix2, j) ) return myMatrix def dotProduct(row, column): if type(row) != list: return None if type(column) != list: return None if len(column) <= 0: return None if len(row) <= 0: return None if len(row) != len(column): return None sum = 0; for i in range(len(row)): sum += row[i] * column[i]; return sum def transposeMatrix(matrix): if checkIfMatrixIsValid(matrix) == False: return None ROW,COL = getMatrixSize(matrix); transMatrix = []; for i in range(COL): transMatrix.append( getColumn(matrix, i) ) return transMatrix def getColumn(matrix , columnIndex): if checkIfMatrixIsValid(matrix) == False: return [] ROW,COL = getMatrixSize(matrix) if columnIndex >= COL: return [] myCol = [] for i in matrix: myCol.append(i[columnIndex]) return myCol def getRow(matrix, rowIndex): if checkIfMatrixIsValid(matrix) == False: return [] ROW,COL = getMatrixSize(matrix) if rowIndex >= ROW: return [] return matrix[rowIndex] def getMatrixSize(matrix): if checkIfMatrixIsValid(matrix) == False: return [] return [ len(matrix) , len(matrix[0]) ] def checkIfMatrixIsValid(matrix): n_rows = len(matrix); for i in matrix: if type(i) != list: return False n_col1 = len(matrix[0]) for i in range(n_rows): if len(matrix[i]) != n_col1: return False return True
bishop1612/ECE364
Lab03/operationOnMats.py
operationOnMats.py
py
2,145
python
en
code
0
github-code
6
3019093477
def sumarValores(conj, ind): izq = conj[0] der = 0 for i in range(ind): izq += conj[i] print("izq", izq) for j in range(ind+1, len(conj)): der += conj[j] print("der", izq) return der, izq def esSolucion(conj, ind, tupla): if ind < len(tupla): return False else: suma = 0 for i in range(len(tupla)): suma += tupla[i]*conj[i] return suma == 0 def sumaVA(conj, ind, tupla): if esSolucion(conj, ind, tupla): esSol = True else: esSol = False if ind < len(tupla): tupla[ind] = -1 esSol, tupla = sumaVA(conj, ind+1, tupla) if not esSol: tupla[ind] = 1 esSol, tupla = sumaVA(conj, ind+1, tupla) if not esSol: tupla[ind] = 0 return esSol, tupla def imprimirSol(tupla,conjunto): print('Conjunto -1:',end='') for i in range(len(tupla)): if tupla[i] == -1: print(conjunto[i],end=' ') print() print('Conjunto 1:', end='') for i in range(len(tupla)): if tupla[i] == 1: print(conjunto[i], end=' ') print() #11.- Dado un conjunto de n enteros, necesitamos decidir si puede ser descompuesto en dos #subconjuntos disjuntos cuyos elementos sumen la misma cantidad. #PROGRAMA PRINCIPAL conjunto = [7, 2, 3, 4, 8] indiceActual = 0 tupla = [0] * len(conjunto) esSol, tupla = sumaVA(conjunto, indiceActual, tupla) if esSol: print('Se ha encontrado una solución y es:') imprimirSol(tupla,conjunto) else: print('No se ha encontrado una solución')
medranoGG/AlgorithmsPython
06.Backtracking/SumaSubconjuntoIgual.py
SumaSubconjuntoIgual.py
py
1,648
python
es
code
0
github-code
6
529377311
from email.Utils import formataddr from zope import interface, component from zope.app.component.hooks import getSite from zope.traversing.browser import absoluteURL from zojax.principal.profile.interfaces import IPersonalProfile message = u""" Your invitation code: %s Or use link %s """ class InvitationMail(object): def update(self): super(InvitationMail, self).update() context = self.context self.url = u'%s/join.html?invitationCode=%s'%( absoluteURL(getSite(), self.request), context.id) profile = IPersonalProfile(self.request.principal, None) if profile is not None and profile.email: self.addHeader(u'From', formataddr((profile.title, profile.email),)) self.addHeader(u'To', formataddr((context.name, context.principal),)) @property def subject(self): return self.context.subject def render(self): return self.context.message + message%(self.context.id, self.url)
Zojax/zojax.personal.invitation
src/zojax/personal/invitation/template.py
template.py
py
990
python
en
code
1
github-code
6
38810369305
import numpy as np from copy import deepcopy from .node import Node from .mesh import Mesh from .transform import Transform class Camera(Node): def __init__(self, focal_length, width, height, near_depth, far_depth, transform=Transform.none): super(Camera, self).__init__( mesh=Mesh(vertices=np.asarray([ # looking down z-axis [0, 0, 0], # center [0, 0, focal_length], # focus [width / 2.0, 0, focal_length], # right [0, height / 2.0, focal_length], # top ])), transform=transform) self.focal_length = focal_length self.width = width self.height = height self.near_depth = near_depth self.far_depth = far_depth self.camera_object = None # the most recent camera object produced by make def make(self): """ Returns a Vec3 -- the focal point of the camera, followed by an array of the four corners of the screen in counterclockwise order starting in the upper right, all with the transform applied. The fifth is the center. A reference to self is also attached. """ m = deepcopy(self.mesh) focus = m.pointer_to(0) center = m.pointer_to(1) right = m.pointer_to(2) top = m.pointer_to(3) # def camera_space_transform(mesh): # """Takes the scene mesh and returns a transform that takes # any scene coordinate to a camera coordinate.""" # return Transform(np.linalg.solve( # np.stack([ # mesh[center] - mesh[focus], # mesh[right] - mesh[focus], # mesh[top] - mesh[focus] # ]), # np.stack([ # self.mesh[1], # self.mesh[2], # self.mesh[3] # ]) # ), mesh[focus]) def convert_to_camera(mesh): """ Returns a mesh where each vertex has been flattened to an x, y coordinate in the camera plane and a distance w from the focus. """ vertices = mesh.vertices focus_to_center = mesh[center] - mesh[focus] focus_to_vectors = vertices - mesh[focus] distances = np.inner(focus_to_center, focus_to_center) / np.dot(focus_to_vectors, focus_to_center) in_plane = mesh[focus] + focus_to_vectors * distances[:, None] offsets = in_plane - mesh[center] x, y = mesh[right] - mesh[center], mesh[top] - mesh[center] # x, y = x / np.linalg.norm(x), y / np.linalg.norm(y) # normalize x and y x, y = x / np.inner(x, x), y / np.inner(y, y) # normalize x and y new_vertices = np.concatenate([np.dot(offsets, np.asarray([x, y]).T), np.reciprocal(distances)[:, None]], axis=1) return Mesh(new_vertices, mesh.faces, mesh.pointers) self.camera_object = { "convert_to_camera": convert_to_camera } return m.join(*(child.make() for child in self.children)).transformed_by(self.transform)
kaedenwile/Wile-Graphics
engine/camera.py
camera.py
py
3,234
python
en
code
18
github-code
6
29474328826
""" Hand-not-Hand creator """ """ this code is complete and ready to use """ import random import pandas as pd from sklearn.naive_bayes import MultinomialNB import helpers #utility funtcion to compute area of overlap def overlapping_area(detection_1, detection_2): x1_tl = detection_1[0] x2_tl = detection_2[0] x1_br = detection_1[0] + detection_1[3] x2_br = detection_2[0] + detection_2[3] y1_tl = detection_1[1] y2_tl = detection_2[1] y1_br = detection_1[1] + detection_1[4] y2_br = detection_2[1] + detection_2[4] # Calculate the overlapping Area x_overlap = max(0, min(x1_br, x2_br)-max(x1_tl, x2_tl)) y_overlap = max(0, min(y1_br, y2_br)-max(y1_tl, y2_tl)) overlap_area = x_overlap * y_overlap area_1 = detection_1[3] * detection_2[4] area_2 = detection_2[3] * detection_2[4] total_area = area_1 + area_2 - overlap_area return overlap_area / float(total_area) #loads data for binary classification (hand/not-hand) def load_binary_data(user_list, data_directory): data1,df = helpers.getHandSet(user_list, data_directory) # data 1 - actual images , df is actual bounding box # third return, i.e., z is a list of hog vecs, labels z = buildhandnothand_lis(df,data1) return data1,df,z[0],z[1] #Creates dataset for hand-not-hand classifier to train on #This function randomly generates bounding boxes #Return: hog vector of those cropped bounding boxes along with label #Label : 1 if hand ,0 otherwise def buildhandnothand_lis(frame,imgset): poslis =[] neglis =[] for nameimg in frame.image: tupl = frame[frame['image']==nameimg].values[0] x_tl = tupl[1] y_tl = tupl[2] side = tupl[5] conf = 0 dic = [0, 0] arg1 = [x_tl,y_tl,conf,side,side] poslis.append(helpers.convertToGrayToHOG(helpers.crop(imgset['Dataset/'+nameimg],x_tl,x_tl+side,y_tl,y_tl+side))) while dic[0] <= 1 or dic[1] < 1: x = random.randint(0,320-side) y = random.randint(0,240-side) crp = helpers.crop(imgset['Dataset/'+nameimg],x,x+side,y,y+side) hogv = helpers.convertToGrayToHOG(crp) arg2 = [x,y, conf, side, side] z = overlapping_area(arg1,arg2) if dic[0] <= 1 and z <= 0.5: neglis.append(hogv) dic[0] += 1 if dic[0]== 1: break label_1 = [1 for i in range(0,len(poslis)) ] label_0 = [0 for i in range(0,len(neglis))] label_1.extend(label_0) poslis.extend(neglis) return poslis,label_1 # Does hard negative mining and returns list of hog vectos , label list and no_of_false_positives after sliding def do_hardNegativeMining(cached_window,frame, imgset, model, step_x, step_y): lis = [] no_of_false_positives = 0 for nameimg in frame.image: tupl = frame[frame['image']==nameimg].values[0] x_tl = tupl[1] y_tl = tupl[2] side = tupl[5] conf = 0 dic = [0, 0] arg1 = [x_tl,y_tl,conf,side,side] for x in range(0,320-side,step_x): for y in range(0,240-side,step_y): arg2 = [x,y,conf,side,side] z = overlapping_area(arg1,arg2) prediction = model.predict([cached_window[str(nameimg)+str(x)+str(y)]])[0] if prediction == 1 and z<=0.5: lis.append(cached_window[str(nameimg)+str(x)+str(y)]) no_of_false_positives += 1 label = [0 for i in range(0,len(lis))] return lis,label, no_of_false_positives # Modifying to cache image values before hand so as to not redo that again and again def cacheSteps(imgset, frame ,step_x,step_y): # print "Cache-ing steps" list_dic_of_hogs = [] dic = {} i = 0 for img in frame.image: tupl = frame[frame['image']==img].values[0] x_tl = tupl[1] y_tl = tupl[2] side = tupl[5] conf = 0 i += 1 if i%10 == 0: print(i, " images cached") image = imgset['Dataset/'+img] for x in range(0,320-side,step_x): for y in range(0,240-side,step_y): dic[str(img+str(x)+str(y))]=helpers.convertToGrayToHOG(helpers.crop(image,x,x+side,y,y+side)) return dic def improve_Classifier_using_HNM(hog_list, label_list, frame, imgset, threshold=50, max_iterations=25): # frame - bounding boxes-df; yn_df - yes_or_no df # print "Performing HNM :" no_of_false_positives = 1000000 # Initialise to some random high value i = 0 step_x = 32 step_y = 24 mnb = MultinomialNB() cached_wind = cacheSteps(imgset, frame, step_x, step_y) while True: i += 1 model = mnb.partial_fit(hog_list, label_list, classes = [0,1]) ret = do_hardNegativeMining(cached_wind,frame, imgset, model, step_x=step_x, step_y=step_y) hog_list = ret[0] label_list = ret[1] no_of_false_positives = ret[2] if no_of_false_positives == 0: return model print("Iteration", i, "- No_of_false_positives:", no_of_false_positives) if no_of_false_positives <= threshold: return model if i>max_iterations: return model def trainHandDetector(train_list, threshold, max_iterations): imageset, boundbox, hog_list, label_list = load_binary_data(train_list, 'Dataset/') print('Binary data loaded') handDetector = improve_Classifier_using_HNM(hog_list, label_list, boundbox, imageset, threshold=threshold, max_iterations=max_iterations) print('Hand Detector Trained') return handDetector
tqiu8/asl-cv
train_hand_detector.py
train_hand_detector.py
py
5,815
python
en
code
0
github-code
6
35471156635
# -*- coding: utf-8 -*- from torch import cuda import transformers from transformers import AutoTokenizer from transformers import DataCollatorForTokenClassification, AutoConfig from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer from datasets import load_metric, Dataset import pandas as pd import numpy as np import re import argparse import csv import sys import time from os import path import json device = 'cuda' if cuda.is_available() else 'cpu' print(device) seed = 22 transformers.set_seed(seed) """ Models Used are: model_checkpoint = "dbmdz/bert-base-italian-uncased" -> italian model_checkpoint = "bert-base-uncased" -> english model_checkpoint = "camembert-base" -> french model_checkpoint = "GroNLP/bert-base-dutch-cased" -> dutch model_checkpoint = "deepset/gbert-base -> german model_checkpoint = "EMBEDDIA/sloberta-> slovene """ def sentence_num(row): sentenceNum = row['Sentence-Token'].split("-")[0] return sentenceNum def to_label_id(row, id_dict): label = row['Tag'] if label not in id_dict: label = 'O' labelId = id_dict[label] return labelId def to_clean_label(row): clean_tag = row['Tag'].replace("\\", "").replace("\_","_") clean_tag = clean_tag.split('|')[0] clean_tag = clean_tag.replace("B-I-", "B-") return clean_tag def replace_punctuation(row): """Error case in Italian: 'bianco', '-', 'gialliccio' -> 'bianco-gialliccio' Bert tokenizer uses also punctuations to separate the tokens along with the whitespaces, although we provide the sentences with is_split_into_words=True. Therefore, if there is a punctuation in a single word in a CONLL file we cannot 100% guarantee the exact same surface realization (necessary to decide on a single label for a single word) after classification for that specific word: e.g., bianco-gialliccio becomes 3 separate CONLL lines: 1) bianco 2) - 3) gialliccio Things could have been easier and faster if we were delivering simple sentences as output instead of the exact CONLL file structure given as input. """ word = row['Word'].strip() if len(word) > 1: word = re.sub(r'[^a-zA-Z0-9]', '', word) if word is None or word == "" or word == "nan": word = " " return word """The script will extract the label list from the data itself. Please be sure your data and labels are clean. 3 Labels: ['Smell_Word', 'Smell_Source', 'Quality'] 7 Labels: ['Smell_Word', 'Smell_Source', 'Quality', 'Location', 'Odour_Carrier', 'Evoked_Odorant', 'Time']""" def read_split_fold(split='train', fold="0", lang="english", label_dict=None): #change the path template as needed. path = 'data_{}/folds_{}_{}.tsv'.format(lang, fold, split) try: data = pd.read_csv(path, sep='\t', skip_blank_lines=True, encoding='utf-8', engine='python', quoting=csv.QUOTE_NONE, names=['Document', 'Sentence-Token', 'Chars', 'Word', 'Tag', 'Empty'], header=None) except: print(f"Cannot read the file {path}") if split == "train": sys.exit() return None, None time.sleep(5) data.drop('Empty', inplace=True, axis=1) #For the reusability purposes, we still extract the label ids from the training data. data['Tag'] = data.apply(lambda row: to_clean_label(row), axis=1) print("Number of tags: {}".format(len(data.Tag.unique()))) frequencies = data.Tag.value_counts() print(frequencies) if not label_dict: labels_to_ids = {k: v for v, k in enumerate(data.Tag.unique())} else: labels_to_ids = label_dict ids_to_labels = {v: k for v, k in enumerate(data.Tag.unique())} data = data.astype({"Word": str}) data['Word'] = data.apply(lambda row: replace_punctuation(row), axis=1) data['Tag'] = data.apply(lambda row: to_label_id(row, labels_to_ids), axis=1) data['Num'] = data.apply(lambda row: sentence_num(row), axis=1) # Important point is that we need unique document+Sentence-Token data = data.astype({"Num": int}) data.set_index(['Document', 'Num']) df = data.groupby(['Document', 'Num'])['Word'].apply(list) df2 = data.groupby(['Document', 'Num'])['Tag'].apply(list) mergeddf = pd.merge(df, df2, on=['Document', 'Num']) mergeddf.rename(columns={'Word': 'sentence', 'Tag': 'word_labels'}, inplace=True) print("Number of unique sentences: {}".format(len(mergeddf))) return mergeddf, labels_to_ids, ids_to_labels def tokenize_and_align_labels(examples, tokenizer, label_all_tokens=True): tokenized_inputs = tokenizer(examples["sentence"], max_length=512, truncation=True, is_split_into_words=True) labels = [] for i, label in enumerate(examples["word_labels"]): word_ids = tokenized_inputs.word_ids(batch_index=i) previous_word_idx = None label_ids = [] for word_idx in word_ids: # Special tokens have a word id that is None. We set the label to -100 so they are automatically # ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label[word_idx]) # For the other tokens in a word, we set the label to either the current label or -100, depending on # the label_all_tokens flag. else: label_ids.append(label[word_idx] if label_all_tokens else -100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputs def cn_hp_space(trial): return { "learning_rate": trial.suggest_categorical("learning_rate", [1e-5, 2e-5, 3e-5, 4e-5, 5e-5]), "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [4, 8]), "num_train_epochs": trial.suggest_int("num_train_epochs", 3, 10, log=True) } def main(): parser = argparse.ArgumentParser(description='Training with Folds') parser.add_argument("--lang", help="Languages: english,german, slovene, dutch, multilingual, french, italian", default="english") parser.add_argument("--fold", help="Fold Name", default="0") parser.add_argument("--hypsearch", help="Flag for Hyperparameter Search", action='store_true') parser.add_argument("--do_train", help="To train the model", action='store_true') parser.add_argument("--do_test", help="To test the model", action='store_true') parser.add_argument("--learning_rate", type=float, help="Learning Rate for training.", default=2e-5) parser.add_argument("--train_batch_size", type=int, help="Training batch size.", default=4) parser.add_argument("--train_epochs", type=int, help="Training epochs.", default=3) parser.add_argument("--model", action='store', default="bert-base-multilingual-uncased", help="Model Checkpoint to fine tune. If none is given, bert-base-multilingual-uncased will be used.") args = parser.parse_args() model_checkpoint = args.model fold = str(args.fold) language = str(args.lang).strip().lower() tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) assert isinstance(tokenizer, transformers.PreTrainedTokenizerFast) if language not in ['english', 'german', 'italian', 'slovene', 'dutch', 'french']: raise Exception(f"Language error: {language} is not among the project languages.") if args.do_train and args.hypsearch: raise Exception(f"Action error: Cannot do hyperparameter search and train in a single run. Please first run" f"hypsearch and with the parameters obtained as the best, run do_train.") config = AutoConfig.from_pretrained(model_checkpoint) labels_to_ids = config.label2id ids_to_labels = config.id2label def model_init(): m = AutoModelForTokenClassification.from_pretrained(model_checkpoint, config=config) m.to(device) return m if args.hypsearch or args.do_train: trn, labels_to_ids, ids_to_labels = read_split_fold(fold=fold, lang=language) train_dataset = Dataset.from_pandas(trn, split="train") val, _, _ = read_split_fold(fold=fold, lang=language, split="dev", label_dict=labels_to_ids) val_dataset = Dataset.from_pandas(val, split="validation") print(labels_to_ids) tokenized_train = train_dataset.map(lambda x: tokenize_and_align_labels(x, tokenizer), batched=True) tokenized_val = val_dataset.map(lambda x: tokenize_and_align_labels(x, tokenizer), batched=True) label_list = list(labels_to_ids.values()) config.label2id = labels_to_ids config.id2label = ids_to_labels config.num_labels = len(label_list) model_name = model_checkpoint.split("/")[-1] if args.hypsearch: tr_args = TrainingArguments( f"{model_name}-{language}-{fold}-hyp", evaluation_strategy="epoch", save_strategy="epoch", per_device_eval_batch_size=8, warmup_ratio=0.1, seed=22, weight_decay=0.01 ) elif args.do_train: tr_args = TrainingArguments( f"{model_name}-{language}-{fold}", evaluation_strategy="epoch", save_strategy="epoch", learning_rate=args.learning_rate, per_device_train_batch_size=args.train_batch_size, per_device_eval_batch_size=8, num_train_epochs=args.train_epochs, warmup_ratio=0.1, seed=22, weight_decay=0.01 ) data_collator = DataCollatorForTokenClassification(tokenizer) metric = load_metric("seqeval") def compute_metrics(p): predictions, labels = p predictions = np.argmax(predictions, axis=2) # Remove ignored index (special tokens) true_predictions = [ [ids_to_labels[p] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] true_labels = [ [ids_to_labels[l] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] results = metric.compute(predictions=true_predictions, references=true_labels) return { "precision": results["overall_precision"], "recall": results["overall_recall"], "f1": results["overall_f1"], "accuracy": results["overall_accuracy"], } if args.do_train or args.hypsearch: trainer = Trainer( model_init=model_init, args=tr_args, train_dataset=tokenized_train, eval_dataset=tokenized_val, data_collator=data_collator, tokenizer=tokenizer, compute_metrics=compute_metrics ) elif args.do_test: #for testing if path.exists(f"{model_checkpoint}/{language}-id2label.json"): ids_to_labels = json.load(open(f"{model_checkpoint}/{language}-id2label.json", "r")) ids_to_labels = {int(k): v for k, v in ids_to_labels.items()} labels_to_ids = {v: int(k) for k, v in ids_to_labels.items()} config.label2id = labels_to_ids config.id2label = ids_to_labels label_list = list(labels_to_ids.values()) config.num_labels = len(label_list) m = AutoModelForTokenClassification.from_pretrained(model_checkpoint, config=config) m.to(device) trainer = Trainer(m, data_collator=data_collator, tokenizer=tokenizer) if args.hypsearch: # hyperparam search with compute_metrics: default maximization is through the sum of all the metrics returned best_run = trainer.hyperparameter_search(n_trials=10, direction="maximize", hp_space=cn_hp_space) best_params = best_run.hyperparameters print(f"Best run is with the hyperparams:{best_params}. You either have to find the right run and checkpoint " f"from the models saved or retrain with the correct parameters: referring to " f"https://discuss.huggingface.co/t/accessing-model-after-training-with-hyper-parameter-search/20081") elif args.do_train: trainer.train() if args.do_test: print("TEST RESULTS") test, _, _ = read_split_fold(split="test", label_dict=labels_to_ids, lang=language, fold=fold) test_dataset = Dataset.from_pandas(test, split="test") tokenized_test = test_dataset.map(lambda x: tokenize_and_align_labels(x, tokenizer), batched=True) predictions, labels, _ = trainer.predict(tokenized_test) predictions = np.argmax(predictions, axis=2) true_predictions = [ [ids_to_labels[p] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] true_labels = [ [ids_to_labels[l] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] results = metric.compute(predictions=true_predictions, references=true_labels) print("\n") print(results) if __name__ == "__main__": main()
Odeuropa/wp3-information-extraction-system
SmellClassifier/training/train.py
train.py
py
13,483
python
en
code
2
github-code
6
74131023869
#!/usr/bin/python # Ce programme envoie la chaine 12345678 vers TTN # Importer les bibliothèques import serial import time # Définition des flags is_join = False # On peut joindre la carte is_exist = False # La carte Grove LoRa E5 a été détectée # Définition du timeout read_timeout = 0.2 # Créer l'instance pour gérer la carte via le port série lora = serial.Serial( port='/dev/serial0', baudrate=9600, bytesize=8, parity='N', timeout=1, stopbits=1, xonxoff=False, rtscts=False, dsrdtr=False ) def envoi_test_reponse(chaine_verif, timeout_ms, commande): startMillis = int(round(time.time() * 1000)) # Tester si la chaine à vérifier existe if chaine_verif == "": return 0 # Envoyer la commande fin_ligne = "\r\n" cmd = "%s%s" % (commande, fin_ligne) print ("Commande envoyée = ",cmd) lora.write(cmd.encode()) # Attendre la réponse reponse = "" quantity = lora.in_waiting # Lire la réponse de la carte jusqu'au timeout while int(round(time.time() * 1000)) - startMillis < timeout_ms: # Si on a des données if quantity > 0: # Les ajouter à la chaine réponse reponse += lora.read(quantity).decode('utf-8') print("Reponse1 de la carte : ", reponse) else: # Sinon attendre un moment time.sleep(read_timeout) # Regarder si on a des données reçues quantity = lora.in_waiting print("Reponse de la carte : ", reponse) # Tester si la chaine attendue existe if chaine_verif in reponse : print("La chaine réponse existe", reponse) return 1 else: return 0 # Configuration de la carte if envoi_test_reponse("+AT: OK", 1000,"AT"): # La carte a été détectée = passer à True is_exist = True # Configurer la carte envoi_test_reponse("+ID: AppEui", 1000,"AT+ID") envoi_test_reponse("+MODE: LWOTAA", 1000,"AT+MODE=LWOTAA") envoi_test_reponse("+DR: EU868", 1000,"AT+DR=EU868") envoi_test_reponse("+CH: NUM", 1000, "AT+CH=NUM,0-2") envoi_test_reponse("+KEY: APPKEY", 1000, "AT+KEY=APPKEY,\"6224041874374E3E85B93F635AB5E774\"") envoi_test_reponse("+CLASS: C", 1000, "AT+CLASS=A") envoi_test_reponse("+PORT: 8", 1000, "AT+PORT=8") # Joindre le réseau envoi_test_reponse("+JOIN: Network joined", 12000, "AT+JOIN") # Envoi d'une chaine de data pour test data = "AT+CMSGHEX=\"12345678\"" envoi_test_reponse("Done", 5000, data)
framboise314/Seeedstudio-Grove-E5-LoRa
programmes/lora-E5.py
lora-E5.py
py
2,569
python
fr
code
3
github-code
6
5131563876
from django.contrib.auth import get_user_model from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from .validators import validate_year NUMBER_OF_SYMBOLS = 20 User = get_user_model() class Category(models.Model): name = models.CharField( verbose_name='Название', max_length=256, db_index=True ) slug = models.SlugField( verbose_name='Slug', max_length=50, unique=True, db_index=True ) class Meta: ordering = ('name',) verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.name[:NUMBER_OF_SYMBOLS] class Genre(models.Model): name = models.CharField( verbose_name='Название', max_length=256, db_index=True ) slug = models.SlugField( verbose_name='Slug', max_length=50, unique=True, db_index=True ) class Meta: ordering = ('name',) verbose_name = 'Жанр' verbose_name_plural = 'Жанры' def __str__(self): return self.name[:NUMBER_OF_SYMBOLS] class Title(models.Model): name = models.CharField( verbose_name='Название', max_length=256, db_index=True ) year = models.IntegerField( verbose_name='Год выпуска', db_index=True, validators=[validate_year] ) description = models.TextField( verbose_name='Описание' ) genre = models.ManyToManyField( Genre, verbose_name='Жанр', related_name='titles' ) category = models.ForeignKey( Category, verbose_name='Категория', related_name='titles', on_delete=models.PROTECT ) class Meta: ordering = ('name',) verbose_name = 'Произведение' verbose_name_plural = 'Произведения' def __str__(self): return self.name[:NUMBER_OF_SYMBOLS] class Review(models.Model): text = models.TextField( verbose_name='Текст' ) author = models.ForeignKey( User, verbose_name='Автор', related_name='reviews', on_delete=models.CASCADE ) score = models.PositiveSmallIntegerField( verbose_name='Оценка', validators=[MinValueValidator(1), MaxValueValidator(10)], db_index=True ) pub_date = models.DateTimeField( verbose_name='Дата публикации', auto_now_add=True, db_index=True ) title = models.ForeignKey( Title, verbose_name='Произведение', related_name='reviews', on_delete=models.CASCADE ) class Meta: ordering = ('-pub_date',) verbose_name = 'Отзыв' verbose_name_plural = 'Отзывы' constraints = [ models.UniqueConstraint( fields=['title', 'author'], name='unique review' ) ] def __str__(self): return self.text[:NUMBER_OF_SYMBOLS] class Comments(models.Model): text = models.TextField( verbose_name='Текст' ) author = models.ForeignKey( User, verbose_name='Автор', related_name='comments', on_delete=models.CASCADE ) pub_date = models.DateTimeField( verbose_name='Дата публикации', auto_now_add=True, db_index=True ) review = models.ForeignKey( Review, verbose_name='Отзыв', related_name='comments', on_delete=models.CASCADE ) class Meta: ordering = ('-pub_date',) verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' def __str__(self): return self.text[:NUMBER_OF_SYMBOLS]
Toksi86/yamdb_final
api_yamdb/reviews/models.py
models.py
py
3,953
python
en
code
0
github-code
6
18573808607
from Utilities import say import Utilities import json import Room class Thing: """The basic class for all non-Room objects in the game""" def __init__(self, id, name): self.id = id self.name = name self.adjectives = [] self.alternate_names = [] # how the item should appear in a list. A book. An apple. A piece of cheese. self.list_name = "a " + name # Starting Location is a Room self.starting_location = None self.can_be_taken = False self.can_be_read = False self.can_be_dropped = False self.has_been_taken = False self.can_go = False self.has_contents = False self.clock = False self.can_be_opened = False self.can_receive = False self.has_dynamic_description = False self.is_listed = True self.is_accessible = True ## room or storage of current location self.current_location = None # Room self.description = "This is a thing." self.dynamic_description_text = "There is a thing." # Default Text for all messages self.msg_take_first = "You take the {}.".format(self.name) self.msg_take = "You take the {}.".format(self.name) self.msg_cannot_take = "You cannot take the {}.".format(self.name) self.msg_already_in_inventory = "You already have the {}.".format(self.name) self.msg_cannot_read = "There is nothing to read on the {}.".format(self.name) self.msg_cannot_be_opened = "The {} cannot be opened".format(self.name) self.msg_cannot_be_closed = "The {} cannot be closed".format(self.name) self.msg_drop = "You drop the {}.".format(self.name) self.msg_cannot_drop = "You cannot drop the {}".format(self.name) self.msg_cannot_go = "That is not a way you can go." self.msg_go = "You go that way." self.msg_cannot_pull = "You cannot pull that." self.msg_has_no_contents = "The {} can't store anything.".format(self.name) self.msg_cannot_look_in = "You cannot look in the {}".format(self.name) self.msg_nothing_happens = "Nothing happens" self.msg_cannot_eat = "You cannot eat that." self.msg_cannot_drink = "You cannot drink that." self.msg_cannot_play = "You cannot play that." self.msg_cannot_dance = "You cannot dance with that." self.msg_cannot_spray = "You cannot spray that." self.msg_cannot_talk = "You cannot talk to that." self.msg_cannot_sit = "You cannot sit there." def get_status(self, type): """returns the status of a thing in JSON format""" # Returns the appropriate export value based on whether value is a Room or Thing def get_export_value(value): if isinstance(value, Room.Room): return "<R:" + value.id + ">" elif isinstance(value, Thing): return "<T:" + value.id + ">" else: return value str_dict = self.__dict__.copy() # print ("str_dict before: " + str(str_dict)) for attr in str_dict: if isinstance(str_dict[attr], list): new_list = list() for x in str_dict[attr]: new_list.append(get_export_value(x)) str_dict[attr] = new_list elif isinstance(str_dict[attr], dict): new_dict = dict() for x in str_dict[attr]: new_dict[x] = get_export_value(str_dict[attr][x]) str_dict[attr] = new_dict else: str_dict[attr] = get_export_value(str_dict[attr]) # print ("str_dict after: " + str(str_dict)) ret_val = dict() ret_val["type"] = type ret_val["data"] = str_dict return json.dumps(ret_val) def set_status(self, status, thing_list, room_list): """uses the JSON data in status to update the thing""" # Returns the appropriate import value based on whether value is Room or Thing def get_import_value(value, thing_list, room_list): list = None if isinstance(value, str): if value.find("<R:") == 0: list = room_list elif value.find("<T:") == 0: list = thing_list if list is not None: id = value[3:(value.find(">"))] return list[id] return value status_obj = json.loads(status) for attr in status_obj: if isinstance(status_obj[attr], list): imp_val = list() for x in status_obj[attr]: imp_val.append(get_import_value(x, thing_list, room_list)) elif isinstance(status_obj[attr], dict): imp_val = dict() for i in status_obj[attr]: imp_val[i] = get_import_value(status_obj[attr][i], thing_list, room_list) else: imp_val = get_import_value(status_obj[attr], thing_list, room_list) setattr(self, attr, imp_val) def get_desc(self): """returns the description to be used when looking at the room""" return self.description def get_dynamic_description(self): """returns the description to be used when looking at the room""" return self.dynamic_description_text def get_list_name(self): return self.list_name # ACTION for look (and look at) def look(self, game, actionargs): cannot_see = False if game.player.current_room.id == "roomI": if not game.player.current_room.is_lit\ and self.name != "cobwebs": cannot_see = True if cannot_see: say("You don't see {}.".format(self.list_name)) say("But then again you can't really see much of anything...") else: say(self.get_desc()) def look_in(self, game, actionargs): say(self.msg_cannot_look_in) # ACTION for read def read(self, game, actionargs): if self.can_be_read: self.look(game, actionargs) else: say(self.msg_cannot_read) def open(self, game, actionargs): say(self.msg_cannot_be_opened) def close(self, game, actionargs): say(self.msg_cannot_be_closed) # ACTION for take def take(self, game, actionargs): if self.can_be_taken: if game.player.is_in_inventory(self): say(self.msg_already_in_inventory) else: game.player.take(self) if not self.has_been_taken: self.has_been_taken = True say(self.msg_take_first) else: say(self.msg_take) else: say(self.msg_cannot_take) # ACTION for "drop" def drop(self, game, actionargs): if self.can_be_dropped: say(self.msg_drop) # TODO make sure game function is used properly game.player.drop(self) else: say(self.msg_cannot_drop) def put_down(self, game, actionargs): self.drop(game, actionargs) def give_to(self, game, actionargs): if self.can_be_dropped: thing_to_receive = Utilities.find_by_name(actionargs["iobj"], game.thing_list) if thing_to_receive is game.thing_list["shiftyMan"]: say("The shifty man does not want the {}.".format(self.name)) elif thing_to_receive.can_receive: # TODO better define default action? say("") else: say("You cannot give anything to the {}".format(thing_to_receive.name)) else: say("You cannot give the {}.".format(self.name)) def go(self, game, actionargs): """Default response for "cannot go" """ say(self.msg_cannot_go) def put_in(self, game, actionargs): if not self.can_be_dropped: say(self.msg_cannot_drop) else: storage_object = Utilities.find_by_name(actionargs["iobj"], game.player.current_room.get_all_accessible_contents()) if storage_object == None: storage_object = Utilities.find_by_name(actionargs["iobj"],game.player.inventory) storage_object.receive_item(game, self, "in") def put_on(self, game, actionargs): if not self.can_be_dropped: say(self.msg_cannot_drop) else: storage_object = Utilities.find_by_name(actionargs["iobj"], game.player.current_room.get_all_accessible_contents()) if storage_object == None: storage_object = Utilities.find_by_name(actionargs["iobj"],game.player.inventory) storage_object.receive_item(game, self, "on") def pull(self, game, actionargs): say(self.msg_cannot_pull) def receive_item(self, game, item, prep): say("You can't put things {} the {}.".format(prep, self.name)) def use(self, game, actionargs): say(self.msg_nothing_happens) def dance(self, game, actionargs): say(self.msg_cannot_dance) def eat(self, game, actionargs): say(self.msg_cannot_eat) def drink(self, game, actionargs): say(self.msg_cannot_drink) def play(self, game, actionargs): say(self.msg_cannot_play) def spray(self, game, actionargs): say(self.msg_cannot_spray) def spray_with(self, game, actionargs): say(self.msg_cannot_spray) def talk(self, game, actionargs): say(self.msg_cannot_talk) def hit(self, game, actionargs): say(self.msg_nothing_happens) def sit(self, game, actionargs): say(self.msg_cannot_sit) # Special Functions def ram(self, game, actionargs): say(self.msg_nothing_happens) def kin(self, game, actionargs): say(self.msg_nothing_happens) def tic(self, game, actionargs): say(self.msg_nothing_happens) class Exit(Thing): """Class for object that transports the player to another room.""" def __init__(self, id, name): super().__init__(id, name) self.can_go = True self.is_listed = False self.destination = None # Room def go(self, game, actionargs): if self.can_go: say(self.msg_go) # TODO make sure game function is used properly game.player.go(self.destination) game.new_room = True else: say(self.msg_cannot_go) def use(self, game, actionargs): self.go(game, actionargs) def get_status(self, type=None): if type is None: type = "Exit" return super().get_status(type) class Door(Exit): """A special Exit, doors can be closed, locked, and unlocked""" def get_status(self, type=None): if type is None: type = "Door" return super().get_status(type) def open(self, game, actionargs): self.go(game, actionargs) class BlockedDoor(Door): def __init__(self, id, name): super().__init__(id, name) self.can_go = False self.locked = False self.msg_unlock = "The door is unlocked." self.msg_cannot_go = "You cannot go through the door." self.alt_msg_cannot_go = None self.msg_go = "You go through the door." def get_status(self): return super().get_status("BlockedDoor") def go(self, game, actionargs): if self.id == "clockRoomDoor": if game.room_list["roomJ"].shifty_man in game.room_list["roomJ"].contents\ and not self.can_go and self.alt_msg_cannot_go is not None: say(self.alt_msg_cannot_go) else: super().go(game, actionargs) else: super().go(game, actionargs) class MetaDoor(Door): def __init__(self, id, name): super().__init__(id, name) self.can_go = False self.locked = True self.num_lights = 0 self.msg_unlock = "The fifth and final orb along the top of the ornate door begins to glow. " \ "You hear clanging and whirring sounds as if some internal mechanism is " \ "operating inside the door." self.msg_cannot_go = "You try to open the door, but it will not budge." self.msg_go = "You approach the door, and with the slightest touch, it slowly swings open. " \ "You walk through." def get_status(self): return super().get_status("MetaDoor") def add_light(self): self.num_lights += 1 if self.num_lights == 5: say(self.msg_unlock) self.can_go = True self.locked = False elif self.num_lights == 1: say("One of the orbs along the top of the ornate door suddenly begins to glow bright white.") else: say("Another orb on the door begins to glow. Now {} of the five orbs are shining " "bright.".format(self.num_to_word(self.num_lights))) def num_to_word(self, num): """takes an integer 1 through 5 and returns it spelled out""" if num == 0: return "none" elif num == 1: return "one" elif num == 2: return "two" elif num == 3: return "three" elif num == 4: return "four" elif num == 5: return "five" def get_desc(self): description_text = "A towering ornate door. It is intricately decorated, and seems to be connected via " \ "various cords to the large computer. " if self.num_lights == 5: description_text += "All five orbs along the top of the door are glowing brightly." elif self.num_lights == 0: description_text += "There are five dark orbs along the top of the door." else: description_text += "There are five orbs along the top of the door, {} of which are " \ "glowing white.".format(self.num_to_word(self.num_lights)) say(description_text) # class Door(Exit): # is_lockable = False # is_locked = False # is_open = True # will_unlock = [] # message_unlocked = "The door is already unlocked." # message_locked = "The door is locked" # message_cant_unlock = "That can't unlock the door." # message_unlocked = "The door is unlocked." # message_not_lockable = "This door does not lock." # # def __init__(self, id, name): # self.id = id # self.name= name # self.adjectives = [] # self.alternate_names = [] # self.actions = {} # # def unlock(self, object_id): # if not self.is_lockable: # say(self.message_not_lockable) # elif not self.is_locked: # say(self.message_unlocked) # elif object not in self.will_unlock: # say(self.message_cant_unlock) # else: # say(self.message_unlocked) # self.is_locked = False # # def go(self): # if self.is_locked: # say(self.message_locked) # # class MultiKeyDoor(Door): # number_of_keys = 0 # keys_to_unlock = 5 # # # def get_description(self): # if # # class Item(Thing): """Takable, Dropable thing""" def __init__(self, id, name): super().__init__(id, name) self.can_be_taken = True self.can_be_dropped = True def get_status(self, type=None): if type is None: type = "Item" return super().get_status(type) class RubberDuck(Item): def __init__(self, id, name): super().__init__(id, name) def get_status(self, type=None): if type is None: type = "RubberDuck" return super().get_status(type) def give_to(self, game, actionargs): recipient = game.get_thing_by_name(actionargs["iobj"], False) if recipient is not game.thing_list["shiftyMan"]: recipient = Utilities.find_by_name(actionargs["iobj"], game.thing_list) if recipient.can_receive: say("The {} doesn't want the rubber duck.".format(recipient.name)) else: say("You cannot give anything to the {}".format(recipient.name)) else: door = game.thing_list["clockRoomDoor"] print(door.msg_unlock) door.locked = False door.can_go = True game.player.remove_from_inventory(self) class Book(Item): def __init__(self, id, name): super().__init__(id, name) self.can_be_read = True self.can_be_dropped = False self.msg_cannot_drop = "This book of documentation seems too important to leave behind." def get_status(self, type=None): if type is None: type = "Book" return super().get_status(type) def read(self, game, actionargs): if not game.player.is_in_inventory(self): say("You pick up the book, and flip through its pages.") game.player.current_room.remove_thing(self) game.player.add_to_inventory(self) else: say("You flip through the \"Tome of Documentation\"...") book_text = "<WRITTEN_TEXT>" book_text += "Notes on the " + game.player.current_room.name + "\n" book_text += game.player.current_room.documentation + "\n" at_least_one_func = False for func in game.player.special_functions.values(): if func["learned"] == True: if at_least_one_func == False: at_least_one_func = True book_text += "Special functions (used with 'call'): \n" book_text += func["name"].upper() + ": " + func["description"] + "\n" book_text += "</>" say(book_text) def open(self, game, actionargs): self.read(game, actionargs) class Cheese(Item): def __init__(self, id, name): super().__init__(id, name) self.msg_cannot_eat = "As you bring the cheese to your lips, the smell makes you gag." \ "You decide it isn't fit for human consumption." def get_status(self, type=None): if type is None: type = "Cheese" return super().get_status(type) def give_to(self, game, actionargs): thing_to_receive = Utilities.find_by_name(actionargs["iobj"], game.thing_list) if game.player.current_room.id == "roomI" and\ game.player.current_room.is_lit == False and\ thing_to_receive.id is not "cobwebs": print("You don't see {}.".format(thing_to_receive.list_name)) print("Then again you can't really see much of anything...") return if thing_to_receive is game.thing_list["hungryMouse"]: message = "As you hold out the cheese, the mosue's eyes widen. " \ "It snatches it from your hand, and runs to the opposite corner of the room. " \ "It begins nibbling away." say(message) self.mouse_eats_cheese(game, actionargs) else: thing_to_receive = Utilities.find_by_name(actionargs["iobj"], game.thing_list) if thing_to_receive.can_receive: say("The {} doesn't want the cheese.".format(thing_to_receive.name)) else: say("You cannot give anything to the {}".format(thing_to_receive.name)) def drop(self, game, actionargs): if game.player.current_room is game.room_list["roomD"]: message = "You drop the cheese, and the mouses's eyes widen. " \ "It quickly darts over, grabs the cheese, and runs to the opposite corner of the room. " \ "It begins nibbling away." say(message) self.mouse_eats_cheese(game, actionargs) else: Thing.drop(self, game, actionargs) def mouse_eats_cheese(self, game, actionargs): game.player.remove_from_inventory(self) game.room_list["roomD"].remove_thing(game.thing_list["hungryMouse"]) game.room_list["roomD"].add_thing(game.thing_list["eatingMouse"]) game.thing_list["lever"].become_reachable() class Ticket(Item): def __init__(self, id, name): super().__init__(id, name) self.dispensed = False def get_status(self, type=None): if type is None: type = "Ticket" return super().get_status(type) def take(self, game, actionargs): if not self.dispensed: say(self.msg_blocked) else: super().take(game, actionargs) def use(self, game, actionargs): accessible = game.player.current_room.get_all_accessible_contents() if game.thing_list["driverDaemon"] in accessible: args = actionargs.copy() args["iobj"] = "daemon" self.give_to(game, args) else: super().use(game, actionargs) def give_to(self, game, actionargs): thing_to_receive = game.get_thing_by_name(actionargs["iobj"], False) if thing_to_receive is game.thing_list["driverDaemon"]: message = "The DAEMON nods, takes your ticket, barely looking at you, and steps aside, granting access to the bus." say(message) self.grant_bus_access(game, actionargs) else: thing_to_receive = Utilities.find_by_name(actionargs["dobj"], game.thing_list) if thing_to_receive.can_receive: say("The {} doesn't want the ticket.".format(thing_to_receive.name)) else: say("You cannot give anything to the {}".format(thing_to_receive.name)) def grant_bus_access(self, game, actionargs): accessible = game.player.current_room.get_all_accessible_contents() if self in accessible: game.player.current_room.remove_thing(self) elif game.player.is_in_inventory(self): game.player.remove_from_inventory(self) game.room_list["roomG"].remove_thing(game.thing_list["busLocked"]) game.room_list["roomG"].add_thing(game.thing_list["bus"]) game.room_list["roomG"].bus = game.thing_list["bus"] class Key(Item): def __init__(self, id, name): super().__init__(id, name) self.msg_no_lock = "There is nothing to use the " + self.name + " with!" self.lock = None def get_status(self, type=None): if type is None: type = "Key" return super().get_status(type) def use(self, game, actionargs): # Determine if the applicable lock is accessible accessible = game.player.current_room.get_all_accessible_contents() if self.lock in accessible: args = actionargs.copy() args["iobj"] = self.lock.name self.put_in(game, args) else: say("There isn't anything that works with the " + self.name + "!") class Drink(Item): def __init__(self, id, name): super().__init__(id, name) def get_status(self, type=None): if type is None: type = "Drink" return super().get_status(type) def use(self, game, actionargs): self.drink(game, actionargs) def drink(self, game, actionargs): message = "You take a sip of the {}.".format(self.name) say(message) class Wine(Drink): def __init__(self, id, name): super().__init__(id, name) def get_status(self, type=None): if type is None: type = "Wine" return super().get_status(type) def drink(self, game, actionargs): if game.player.current_room is not game.room_list["roomE"] or game.thing_list["piano"].tip_received: super().drink(game, actionargs) else: say("You drink some wine and start to loosen up...") game.player.drunk = True class Newspaper(Item): def __init__(self, id, name): super().__init__(id, name) self.can_be_read = True def get_status(self, type=None): if type is None: type = "Newspaper" return super().get_status(type) #def read(self, game, actionargs): #COMMENTING THIS OUT, BECAUSE DESCRIPTION HAS CONTENT #contents = "The newspaper has an article about bugs." #say(contents) def open(self, game, actionargs): self.read(game, actionargs) class Debugger(Item): def __init__(self, id, name): super().__init__(id, name) self.can_be_sprayed = True def get_status(self, type=None): if type is None: type = "Debugger" return super().get_status(type) def spray(self, game, actionargs): say("You spray the Debugger in the air. Nothing happens.") class Feature(Thing): """Not-Takable, Not-Dropable thing""" def __init__(self, id, name): super().__init__(id, name) self.can_be_taken = False self.can_be_dropped = False self.msg_cannot_take = "The {} is fixed in place.".format(self.name) def get_status(self, type=None): if type is None: type = "Feature" return super().get_status(type) class Seat(Feature): def __init__(self, id, name): super().__init__(id, name) self.msg_sit = "You sit on the {}. After resting for some time "\ "on the comfortable {}, you get back up, ready "\ "to continue exploring.".format(self.name, self.name) def get_status(self, type=None): if type is None: type = "Seat" return super().get_status(type) def sit(self, game, actionargs): say(self.msg_sit) class Lock(Feature): def __init__(self, id, name): super().__init__(id, name) self.item_dispenser = False self.door_lock = False self.toggled = False self.controlled_exit = None self.open_exit = None self.key = None self.receive_preps = [] self.already_used_msg = "The " + self.name + " has already been used!" self.incompatible_msg = "The " + self.name + " can not receive that item!" self.msg_toggled = "" self.key_consumed = False def get_status(self, type=None): if type is None: type = "Lock" return super().get_status(type) def receive_item(self, game, item, prep): if prep in self.receive_preps: if self.toggled: say(self.already_used_msg) elif item == self.key: say("You put the {} {} the {}.".format(item.name, prep, self.name)) self.toggle(game) if self.key_consumed: accessible = game.player.current_room.get_all_accessible_contents() if item in accessible: game.player.current_room.remove_thing(item) elif game.player.is_in_inventory(item): game.player.remove_from_inventory(item) else: say("You can't put things {} the {}.".format(prep, self.name)) # use def use(self, game, actionargs): # Determine if the key is accessible in the Room or in the Player's inventory accessible = game.player.current_room.get_all_accessible_contents() if self.key in accessible or game.player.is_in_inventory(self.key): self.receive_item(game, self.key, "in") else: say("You don't have anything that works with the " + self.name + "!") def unlock_exit(self, game): # Find direction(s) of the Exit directions = list() for dir in game.player.current_room.exits: if game.player.current_room.exits[dir] == self.controlled_exit: directions.append(dir) # Remove the Exit from the current room game.player.current_room.remove_exit(self.controlled_exit) # Add the "opened" Exit to the current room in the directions of the previous Exit for dir in directions: game.player.current_room.add_exit(self.open_exit, dir) def toggle(self, game): if self.door_lock: self.unlock_exit(game) elif self.item_dispenser: self.dispense_item(game) self.toggled = True say(self.msg_toggled) def dispense_item(self, game): game.player.add_to_inventory(self.item) class Input(Feature): """A feature that you can input text into (like a keyboard) By default they have one correct answer which performs one function. """ def __init__(self, id, name): super().__init__(id, name) # True if the input only functions once self.one_time_use = True self.triggers_once = True # True if the correct answer has already been triggered self.triggered = False self.msg_prompt = "What do you input?" self.msg_yn_prompt = "Would you like to input something? (y/n)" self.answer = "ANSWER" self.msg_correct_answer = "Correct!" self.msg_incorrect_answer = "Nothing happens." self.msg_already_triggered = "Nothing happens." self.msg_already_used = "There is nothing left to use it for." def get_status(self, type=None): if type is None: type = "Input" return super().get_status(type) def look(self, game, actionargs): say(self.get_desc()) if not (self.one_time_use and self.triggered): yes_or_no = game.get_yn_answer(self.msg_yn_prompt) if yes_or_no: self.get_input(game, actionargs) def use(self, game, actionargs): say(self.get_desc()) self.get_input(game, actionargs) def get_input(self, game, actionargs): if self.one_time_use and self.triggered: say(self.msg_already_used) else: response = game.get_word_answer(self.msg_prompt, self.answer) if (response): if self.triggers_once and self.triggered: say(self.msg_already_triggered) else: self.triggered = True say(self.msg_correct_answer) self.carry_out_action(game, actionargs) else: say(self.msg_incorrect_answer) # This is the function called on a successful answer def carry_out_action(self, game, actionargs): print("[[default action...]]") class InputBalconyWindow(Input): """the class for the input device on the balcony that opens the window""" # This status function is not working on its own def get_status(self): return super().get_status("InputBalconyWindow") # This is the function called on a successful answer def carry_out_action(self, game, actionargs): # Open window... game.room_list["roomA"].remove_exit(game.thing_list["balconyWindowClosed"]) game.room_list["roomA"].add_exit(game.thing_list["balconyWindowOpen"], "north") if not game.player.is_in_inventory(game.thing_list["book"]): book_message = "The force of the window opening has left the book on the floor. " \ "Curious, you decide to pick it up." say(book_message) game.player.current_room.remove_thing(game.thing_list["book"]) game.player.add_to_inventory(game.thing_list["book"]) class InputPuzzle1(Input): """the class for the input device in puzzle 1""" def __init__(self, id, name): super().__init__(id, name) self.msg_prompt = "What do you input into the control panel?" self.answer = "gone" self.msg_correct_answer = \ "The Control Panel displays this message: \n" \ "<DIGITAL_TEXT>Crystals are gone, shutting down and switching to manual monitoring system.</>\n" \ "All of the monitors in the room turn off, and it is now pitch black. \n" \ "Your Documentation Tome begins to glow. Opening it, you see a new function appear: LED. " \ "To use this function, input \"call LED\". You try it, and the lights in the room turn back on." # "The light from the tome fades away, and the room is again completely dark." def get_status(self): return super().get_status("InputPuzzle1") def get_desc(self): if not self.triggered: desc = \ "The Control Panel has a large screen and a keyboard below it. On the screen is this message: \n" \ "<DIGITAL_TEXT>Error: Crystals have disappeared without a TRACE. " \ "Before turning offline, the monitoring system detected " \ "four distinct paths the crystals took: \n" \ "Path 1: FFFFF0 -> FFFF99 -> FF69B4 -> C19A6B -> 2A3439 -> 614051\n" \ "Path 2: FFFF99 -> FF69B4 -> C19A6B -> FFFFF0 -> FFFF99\n" \ "Path 3: 007FFF -> 800020 -> C19A6B -> FFFFF0\n" \ "Path 4: 800020 -> FFFF99 -> 228B22 -> 614051 -> 228B22 -> FF69B4 -> 007FFF\n" \ "Please input the current location of the crystals...</>" else: desc = "The control panel's screen is now blank." say(desc) # This is the function called on a successful answer def carry_out_action(self, game, actionargs): # learn function game.player.learn_function("led") game.player.current_room.remove_thing(game.thing_list["puzzle1MonitorsBroken"]) game.player.current_room.add_thing(game.thing_list["puzzle1MonitorsFixed"]) class InputPuzzle2(Input): """the class for the input device in puzzle 2""" def __init__(self, id, name): super().__init__(id, name) self.msg_prompt = "What do you type to complete the email?" self.answer = "alone" self.msg_correct_answer = \ "You type the final word and send the email. You feel better now that this apology " \ "has been sent to those who deserve to hear it. As you reflect on your bizarre adventure, " \ "and dream of being free of this tower, you wonder when you will next see your own family. " \ "Just then, your Tome of Documentation starts to get very warm. You open it and see a new function " \ "has appeared: KIN. You can use it by saying \"call KIN on _____\". It will reconnect something with " \ "it's relatives." self.msg_incorrect_answer = "You think harder, and realize that is not the right word to complete the email." def get_status(self): return super().get_status("InputPuzzle2") def get_desc(self): if not self.triggered: desc = "The computer is on, and on the screen it appears as though someone was composing an email. " \ "Here is what is says: \n" \ "<DIGITAL_TEXT>Dear family, \n" \ "I'm sorry for disrupting our relationship database. " \ "My actions have caught up to me. Now I must confess that my fears have become reality, " \ "for, now I am ...</> \n" \ "The email is missing a final word. What should you type before sending the email?" else: desc = "The computer's screen is now blank." say(desc) # This is the function called on a successful answer def carry_out_action(self, game, actionargs): # learn function game.player.learn_function("kin") class InputPuzzle3(Input): """the class for the input device in puzzle 3""" def __init__(self, id, name): super().__init__(id, name) self.msg_prompt = "What book do you search for?" self.answer = "hackers assets" self.msg_correct_answer = \ "After entering the book title, you hear a buzzing as a drone flys from behind the table. " \ "It zooms through the shelves before a small claw extends out and grasps a book. " \ "The drone clumsily delivers the book onto the table. You flip through \"Hackers Assets\" " \ "and learn about many tools for manipulating hardware and software. " \ "You discover that sometimes, the best answer is brute force. " \ "Just then your Tome of Documentation begins to thrash wildly. " \ "It falls on the table and opens, and you see a new function appear: RAM. " \ "This will apply a great force to something. " \ "To use it, say \"call RAM on _____\". The drone is startled, grabs the hackers book and flies away." self.msg_incorrect_answer = "The search comes up empty, there are no books by that name." def get_status(self): return super().get_status("InputPuzzle3") # This is the function called on a successful answer def carry_out_action(self, game, actionargs): # learn function game.player.learn_function("ram") def get_desc(self): if not self.triggered: desc = \ "This touchscreen is used to search for books in the library. " \ "Most are separated into two categories: <CLUE>hardware</> or <CLUE>software</>." else: desc = \ "This touchscreen is used to search for books in the library. " \ "A message comes up saying you have reached your maximum rentals." say(desc) class InputPuzzle4(Input): """the class for the input device in puzzle 3""" def __init__(self, id, name): super().__init__(id, name) self.msg_prompt = "What status do you enter?" self.answer = "bricked" self.msg_correct_answer = \ "The computer reads: \n" \ "<DIGITAL_TEXT>\"BRICKED\" status detected. Initializing troubleshooting procedure.</> \n" \ "Just then a small robot on wheels emerges from the computer! Startled, you jump back. " \ "The tiny robot rolls over towards a large plug which seems to be powering the entire system. " \ "With it's mechanical arms, it grabs the plug and yanks it from the wall. " \ "The processors and computer shut down, and all of the awful noises and smoke stop. " \ "After five seconds, the robot plugs the computer back in, and rolls back into the computer." \ "The computer screen reads: <DIGITAL_TEXT>Booting up...</>. It appears you've fixed the system! " \ "You suddenly feel a jolt, as if your Tome of Documentation just shocked you. " \ "Opening its pages you see a new function appear: TIC. This function will make a machine malfunction; " \ "to use it, say \"call TIC on _____\". " self.msg_incorrect_answer = "The computer reads: <DIGITAL_TEXT>You've entered an unknown status. " \ "Please enter correct status.</>" def get_status(self): return super().get_status("InputPuzzle4") # This is the function called on a successful answer def carry_out_action(self, game, actionargs): # learn function game.player.learn_function("tic") game.player.current_room.remove_thing(game.thing_list["puzzle4ProcessorsBroken"]) game.player.current_room.add_thing(game.thing_list["puzzle4ProcessorsFixed"]) def get_desc(self): if not self.triggered: desc = \ "This large computer seems to be controlling the whole mechanical system in this room. It has keyboard, " \ "and a large screen displaying this message: \n" \ "<DIGITAL_TEXT>ERROR! Processing system is malfunctioning. Must diagnose problem. " \ "Check error messages from processors, and input system status below to initiate troubleshooting." else: desc = \ "This large computer seems to be controlling the whole mechanical system in this room. It has keyboard, " \ "and a large screen displaying this message: \n" \ "<DIGITAL_TEXT>Booting up...</>" say(desc) class InputPuzzle5(Input): """the class for the input device in puzzle 5""" def __init__(self, id, name): super().__init__(id, name) self.msg_prompt = "What password do you enter?" self.answer = "finesse" self.msg_correct_answer = \ "The computer unlocks! looking at the monitor, it appears an online course was in progress, " \ "for increasing coordination. After skimming through a few pages, " \ "you notice your Tome of Documentation begin to vibrate. " \ "You open it up and see a new function has been added: PRO. " \ "To use it, say \"call PRO\". This will temporarilty increase your skill and dexterity. " \ "You exit the course and turn off the computer." self.msg_incorrect_answer = "You've entered the incorrect password." def get_status(self): return super().get_status("InputPuzzle5") # This is the function called on a successful answer def carry_out_action(self, game, actionargs): # learn function game.player.learn_function("pro") def get_desc(self): if not self.triggered: desc = \ "This is a fancy computer with a large monitor and a standard US QWERTY keyboard. " \ "The computer is on, but it appears to be stuck on a log-in screen. I" \ "t looks like there have been a few incorrect password attempts, " \ "and you can read them! What kind of security is that? " \ "Who ever previously tried to log in experienced <CLUE>off-by-one-errors</> " \ "with every key! The incorrect passwords were: \n" \ "<DIGITAL_TEXT>COMDEXS \nGUMWEED \nROBSZED \nTUBREAR</>\n" \ "You wonder what the actual password might be." else: desc = "The computer is turned off." say(desc) class MetaPuzzleInput(Input): """the class for the input device in the meta puzzle""" def __init__(self, id, name): super().__init__(id, name) self.msg_prompt = "What do you type?" self.msg_prompt2 = "What do you type?" self.answer = "pro ram kin tic led" self.answer2 = "geek" self.msg_correct_answer = \ "Correct! More text appears on the screen: \n" \ "<DIGITAL_TEXT>Now you should have learned something about yourself. What are you?</>" self.msg_correct_answer2 = \ "The Mother DAEMON looks at you and silently nods. She comes over and guides your hands on the keyboard. " \ "You press Control... then Alt... then Delete. Everything goes black.\n" \ "When you come to, you find yourself sitting in front of your computer at home. " \ "You have escaped the tower! And now you have a craving for cheese..." self.msg_incorrect_answer = "<DIGITAL_TEXT>Incorrect sequence.</>" self.msg_incorrect_answer2 = "<DIGITAL_TEXT>Incorrect. Look deeper.</>" self.description = \ "This computer is identical to your computer at home. It is displaying a simple message: \n" \ "<DIGITAL_TEXT>Enter in all five special functions (separated by spaces) in the correct order.</>" def get_status(self): return super().get_status("MetaPuzzleInput") # This is the function called on a successful answer def carry_out_action(self, game, actionargs): # learn function game.game_over = True game.end() def get_input(self, game, actionargs): response1 = game.get_word_answer(self.msg_prompt, self.answer) if (response1): say(self.msg_correct_answer) response2 = game.get_word_answer(self.msg_prompt2, self.answer2) if (response2): say(self.msg_correct_answer2) self.carry_out_action(game, actionargs) else: say(self.msg_incorrect_answer2) else: say(self.msg_incorrect_answer) class Sign(Feature): """Readable Feature""" def __init__(self, id, name): super().__init__(id, name) self.can_be_read = True def get_status(self): return super().get_status("Sign") class Lever(Feature): """Readable Feature""" def __init__(self, id, name): super().__init__(id, name) self.is_reachable = False def get_status(self): return super().get_status("Lever") def use(self, game, actionargs): self.pull(game, actionargs) def pull(self, game, actionargs): if self.is_reachable: lever_text = "You pull the lever. You hear a rumbling sound behind you and turn as a section of " \ "the west wall slides away, revealing a tunnel leading off to the west." say(lever_text) game.player.current_room.remove_exit(game.thing_list["secretWall"]) game.player.current_room.add_exit(game.thing_list["mousepadTunnel"], "west") else: say("You cannot reach the lever, the mouse is in the way.") def become_reachable(self): self.is_reachable = True def get_desc(self): if self.is_reachable: say("A large lever is attatched to the wall. It is not clear what it is connected to.") else: say("Some kind of lever is attached to the wall. You can't get a closer look with the mouse in the way.") class Computer(Feature): def __init__(self, id, name): super().__init__(id, name) self.key_items = ["floppyDisk", "cartridge", "tape", "cd", "flashdrive"] self.inserted_things = list() self.description_text = \ "This massive machine takes up most of the east wall. It is some sort of system of large rectangular devices all " \ "connected with various wires. There are lights blinking, and you hear whirring and clicking sounds. " \ "You can only assume it functions as some type of computer. " \ "There appears to be a handful of unique ports in the machine where something could be inserted." def get_status(self): return super().get_status("Computer") def receive_item(self, game, item, prep): if prep == "in": if item.id in self.key_items: game.player.remove_from_inventory(item) self.inserted_things.append(item) say("You find an appropriate looking place to insert the {} into the " "computer.".format(item.name, prep, self.name)) game.thing_list["lobbyOrnateDoor"].add_light() else: say("You can't find anywhere in the computer to put the {}.".format(item.name)) else: say("You can't put things {} the computer.".format(prep)) def get_desc(self): text = self.description_text if self.inserted_things: text += " You have inserted" text += Utilities.list_to_words([o.get_list_name() for o in self.inserted_things]) text += "." say(text) class Clock(Feature): """Readable Feature that can tell game time""" def __init__(self, id, name): super().__init__(id, name) self.can_be_read = True def get_status(self): return super().get_status("Clock") def look(self, game, actionargs): say("The time is <DIGITAL_TEXT>t=" + str(game.game_time) + "</>") class ComplexClock(Feature): """For the clock in the Clock Room""" def __init__(self, id, name): super().__init__(id, name) self.can_be_read = True def get_status(self, type=None): if type is None: type = "ComplexClock" return super().get_status(type) def look(self, game, actionargs): say(self.description) say("The time is <DIGITAL_TEXT>t=" + str(game.game_time) + "</>") class Piano(Feature): """Playable piano""" def __init__(self, id, name): super().__init__(id, name) self.tip_received = False self.daemon_summoned = False self.msg_good = "You play the piano. Thanks to the wine, you're really groovin'. It sounds good!" self.msg_great = "You play the piano. Thanks to the PRO effects, you're unstoppable! It sounds great!" self.msg_bad = "You play the piano, but you feel a little stiff. It doesn't sound great. Maybe you'll play better if you loosen up somehow..." def get_status(self, type=None): if type is None: type = "Piano" return super().get_status(type) def use(self, game, actionargs): self.play(game, actionargs) def play(self, game, actionargs): if game.player.pro: say(self.msg_great) self.play_great(game) elif game.player.drunk: say(self.msg_good) self.play_good(game) else: say(self.msg_bad) def play_good(self, game): if not self.tip_received: self.tip_received = True game.thing_list["tipJar"].add_item(game.thing_list["coin"]) print() say("You received a tip! A coin has appeared in the tip jar.") def play_great(self, game): self.play_good(game) if not self.daemon_summoned: self.daemon_summoned = True game.room_list["roomE"].add_thing(game.thing_list["DancingDaemon"]) print() say("Your playing has attracted one of the tower's DAEMONs!") say(game.thing_list["DancingDaemon"].description) class DancingDaemon(Feature): """Daemon that appears""" def __init__(self, id, name): super().__init__(id, name) self.floppy_received = False self.floppy = None self.msg_dance = "You dance with the DAEMON!" def get_status(self, type=None): if type is None: type = "DancingDaemon" return super().get_status(type) def dance(self, game, actionargs): say(self.msg_dance) if not self.floppy_received: message = "The DAEMON gives you a " + self.floppy.name + "!" game.player.add_to_inventory(self.floppy) self.floppy_received = True say(message) class Moth(Feature): """Moth holding the cartridge""" def __init__(self, id, name): super().__init__(id, name) self.floppy_received = False self.floppy = None self.been_sprayed = False self.msg_spray = "You spray the moth with the Debugger." self.msg_first_spray = "The moth flies into the opening, taking whatever is in its mouth with it " \ ", but leaving the door unguarded." self.msg_been_sprayed = "The moth flaps its wings in an attempt to get away." self.in_web = False self.msg_kin_not_in_web = "Hundreds of other moths appear. They appear to check on the "\ "giant moth before flying away." self.msg_kin_in_web = "Hundreds of other moths appear. They work to free the giant moth "\ "from the web. The giant moth comes loose from the web, dropping a "\ "cartridge in your hand before flying away with its family." def get_status(self, type=None): if type is None: type = "Moth" return super().get_status(type) def err_message(self, game): if game.player.current_room.id == "roomI" and\ game.player.current_room.is_lit == False: say("You don't see a moth.") say("But then again you don't really see much of anything...") return True else: return False def look(self, game, actionargs): if self.err_message(game): return self.get_desc(game) def get_desc(self, game): message = self.description message += " It seems to be calling out for help... but to who?" say(message) def spray(self, game, actionargs): if self.err_message(game): return has_debugger = False for item in game.player.inventory: if item.id == "debugger": has_debugger = True break if has_debugger: say(self.msg_spray) if self.been_sprayed: say(self.msg_been_sprayed) else: say(self.msg_first_spray) self.been_sprayed = True game.room_list["roomH"].remove_thing(self) game.room_list["roomI"].add_thing(self) game.room_list["roomI"].contains_moth = True self.in_web = True game.thing_list["webDoor"].can_go = True else: say("You don't have anything to spray the moth with.") def spray_with(self, game, actionargs): if self.err_message(game): return obj = Utilities.find_by_name(actionargs["iobj"], game.thing_list) if obj.id == "debugger": self.spray(game, actionargs) else: say("You cannot spray the moth with that.") def kin(self, game, actionargs): if self.err_message(game): return if not self.in_web: say(self.msg_kin_not_in_web) else: say(self.msg_kin_in_web) if not self.floppy_received: message = "You received a " + self.floppy.name + "!" game.player.add_to_inventory(self.floppy) self.floppy_received = True self.in_web = False game.room_list["roomI"].remove_thing(self) game.room_list["roomI"].contains_moth = False say(message) def look_in(self, game, actionargs): if not self.err_message(game): super().look_in(game, actionargs) def read(self, game, actionargs): if not self.err_message(game): super().read(game, actionargs) def open(self, game, actionargs): if not self.err_message(game): super().open(game, actionargs) def close(self, game, actionargs): if not self.err_message(game): super().close(game, actionargs) def take(self, game, actionargs): if not self.err_message(game): super().take(game, actionargs) def drop(self, game, actionargs): if not self.err_message(game): super().drop(game, actionargs) def put_down(self, game, actionargs): if not self.err_message(game): super().put_down(game, actionargs) def give_to(self, game, actionargs): if not self.err_message(game): super().give_to(game, actionargs) def go(self, game, actionargs): if not self.err_message(game): super().go(game, actionargs) def put_in(self, game, actionargs): if not self.err_message(game): super().receive_item(game, actionargs, "in") def put_on(self, game, actionargs): if not self.err_message(game): super().receive_item(game, actionargs, "on") def pull(self, game, actionargs): if not self.err_message(game): super().pull(game, actionargs) def receive_item(self, game, actionargs, prep): if not self.err_message(game): super().receive_item(game, actionargs, prep) def use(self, game, actionargs): if not self.err_message(game): super().use(game, actionargs) def dance(self, game, actionargs): if not self.err_message(game): super().dance(game, actionargs) def eat(self, game, actionargs): if not self.err_message(game): super().eat(game, actionargs) def drink(self, game, actionargs): if not self.err_message(game): super().drink(game, actionargs) def play(self, game, actionargs): if not self.err_message(game): super().play(game, actionargs) def talk(self, game, actionargs): if not self.err_message(game): super().talk(game, actionargs) def hit(self, game, actionargs): if not self.err_message(game): super().hit(game, actionargs) def ram(self, game, actionargs): if not self.err_message(game): super().ram(game, actionargs) def tic(self, game, actionargs): if not self.err_message(game): super().tic(game, actionargs) def sit(self, game, actionargs): if not self.err_message(game): super().sit(game, actionargs) class Tape(Item): def __init__(self, id, name): super().__init__(id, name) def get_status(self, type=None): if type is None: type = "Tape" return super().get_status(type) def err_message(self, game): if game.player.current_room.id == "roomI" and\ game.player.current_room.is_lit == False: say("You don't see a tape.") say("Then again you can't really see much of anything...") return True else: return False def spray(self, game, actionargs): if not self.err_message(game): super().spray(game, actionargs) def spray_with(self, game, actionargs): if not self.err_message(game): super().spray_with(game, actionargs) def look_in(self, game, actionargs): if not self.err_message(game): super().look_in(game, actionargs) def read(self, game, actionargs): if not self.err_message(game): super().read(game, actionargs) def open(self, game, actionargs): if not self.err_message(game): super().open(game, actionargs) def close(self, game, actionargs): if not self.err_message(game): super().close(game, actionargs) def take(self, game, actionargs): if not self.err_message(game): super().take(game, actionargs) def drop(self, game, actionargs): if not self.err_message(game): super().drop(game, actionargs) def put_down(self, game, actionargs): if not self.err_message(game): super().put_down(game, actionargs) def give_to(self, game, actionargs): if not self.err_message(game): super().give_to(game, actionargs) def go(self, game, actionargs): if not self.err_message(game): super().go(game, actionargs) def put_in(self, game, actionargs): if not self.err_message(game): super().receive_item(game, actionargs, "in") def put_on(self, game, actionargs): if not self.err_message(game): super().receive_item(game, actionargs, "on") def pull(self, game, actionargs): if not self.err_message(game): super().pull(game, actionargs) def receive_item(self, game, actionargs, prep): if not self.err_message(game): super().receive_item(game, actionargs, prep) def use(self, game, actionargs): if not self.err_message(game): super().use(game, actionargs) def dance(self, game, actionargs): if not self.err_message(game): super().dance(game, actionargs) def eat(self, game, actionargs): if not self.err_message(game): super().eat(game, actionargs) def drink(self, game, actionargs): if not self.err_message(game): super().drink(game, actionargs) def play(self, game, actionargs): if not self.err_message(game): super().play(game, actionargs) def talk(self, game, actionargs): if not self.err_message(game): super().talk(game, actionargs) def hit(self, game, actionargs): if not self.err_message(game): super().hit(game, actionargs) def ram(self, game, actionargs): if not self.err_message(game): super().ram(game, actionargs) def kin(self, game, actionargs): if not self.err_message(game): super().kin(game, actionargs) def tic(self, game, actionargs): if not self.err_message(game): super().tic(game, actionargs) def sit(self, game, actionargs): if not self.err_message(game): super().sit(game, actionargs) class ShiftyMan(Feature): def __init__(self, id, name): super().__init__(id, name) def get_status(self, type=None): if type is None: type = "ShiftyMan" return super().get_status(type) def talk(self, game, actionargs): say("<SPOKEN_TEXT>There are five DAEMONS in the Tower who stole some very important things from my computer:</>") say("<SPOKEN_TEXT>One likes to play pranks.</>") say("<SPOKEN_TEXT>One likes to dance - but only likes very fast music.</>") say("<SPOKEN_TEXT>One got a job as a bus driver.</>") say("<SPOKEN_TEXT>One has been hanging out with a spider.</>") say("<SPOKEN_TEXT>One is the Tower custodian, and keeps a strange pet.</>") class Spider(Feature): def __init__(self, id, name): super().__init__(id, name) self.msg_spray = "You spray the spider with the Debugger. "\ "The spider angrily lunges toward you, and "\ "you fall backwards, narrowly avoiding being bitten. " def get_status(self, type=None): if type is None: type = "Spider" return super().get_status(type) def err_message(self, game): if game.player.current_room.id == "roomI" and\ game.player.current_room.is_lit == False: say("You don't see a spider.") say("But then again you don't really see much of anything...") return True else: return False def spray(self, game, actionargs): if self.err_message(game): return has_debugger = False for item in game.player.inventory: if item.id == "debugger": has_debugger = True break if has_debugger: say(self.msg_spray) else: say("You don't have anything to spray the spider with.") def spray_with(self, game, actionargs): if self.err_message(game): return obj = Utilities.find_by_name(actionargs["iobj"], game.thing_list) if obj.id == "debugger": self.spray(game, actionargs) else: say("You cannot spray the spider with that.") def look_in(self, game, actionargs): if not self.err_message(game): super().look_in(game, actionargs) def read(self, game, actionargs): if not self.err_message(game): super().read(game, actionargs) def open(self, game, actionargs): if not self.err_message(game): super().open(game, actionargs) def close(self, game, actionargs): if not self.err_message(game): super().close(game, actionargs) def take(self, game, actionargs): if not self.err_message(game): super().take(game, actionargs) def drop(self, game, actionargs): if not self.err_message(game): super().drop(game, actionargs) def put_down(self, game, actionargs): if not self.err_message(game): super().put_down(game, actionargs) def give_to(self, game, actionargs): if not self.err_message(game): super().give_to(game, actionargs) def go(self, game, actionargs): if not self.err_message(game): super().go(game, actionargs) def put_in(self, game, actionargs): if not self.err_message(game): super().receive_item(game, actionargs, "in") def put_on(self, game, actionargs): if not self.err_message(game): super().receive_item(game, actionargs, "on") def pull(self, game, actionargs): if not self.err_message(game): super().pull(game, actionargs) def receive_item(self, game, actionargs, prep): if not self.err_message(game): super().receive_item(game, actionargs, prep) def use(self, game, actionargs): if not self.err_message(game): super().use(game, actionargs) def dance(self, game, actionargs): if not self.err_message(game): super().dance(game, actionargs) def eat(self, game, actionargs): if not self.err_message(game): super().eat(game, actionargs) def drink(self, game, actionargs): if not self.err_message(game): super().drink(game, actionargs) def play(self, game, actionargs): if not self.err_message(game): super().play(game, actionargs) def talk(self, game, actionargs): if not self.err_message(game): super().talk(game, actionargs) def hit(self, game, actionargs): if not self.err_message(game): super().hit(game, actionargs) def ram(self, game, actionargs): if not self.err_message(game): super().ram(game, actionargs) def kin(self, game, actionargs): if not self.err_message(game): super().kin(game, actionargs) def tic(self, game, actionargs): if not self.err_message(game): super().tic(game, actionargs) def sit(self, game, actionargs): if not self.err_message(game): super().tic(game, actionargs) class Fireplace(Feature): def __init__(self, id, name): super().__init__(id, name) self.look_in_msg = "You look in the fireplace, but "\ "you don't see anything other than the "\ "burning fire." def get_status(self, type=None): if type is None: type = "Fireplace" return super().get_status(type) def look_in(self, game, actionargs): say(self.look_in_msg) class Freezer(Feature): """Freezer that manipulates chunk of ice""" def __init__(self, id, name): super().__init__(id, name) self.is_malfunctioned = False def get_status(self, type=None): if type is None: type = "Freezer" return super().get_status(type) def tic(self, game, actionargs): if not self.is_malfunctioned: self.is_malfunctioned = True malfunction_text = \ "The freezer buzzes and groans. It begins to shake before finally turning off. " \ "The chunk of ice begins to drip, and then crack. Finally, the ice falls apart, and the laptop " \ "comes crashing down. The screen cracks and the frame gets severely bent upon impact. " \ "A flashdrive pops out and slides across the floor." say(malfunction_text) # laptop frozenLaptop -> brokenLaptop -> drop flash drive game.player.current_room.remove_thing(game.thing_list["frozenLaptop"]) game.player.current_room.add_thing(game.thing_list["brokenLaptop"]) game.player.current_room.add_thing(game.thing_list["flashdrive"]) else: say("Nothing happens.") def get_desc(self): if self.is_malfunctioned: desc_text = "This strange device is labeled as a \"<WRITTEN_TEXT>freezer</>\". " \ "It is turned off, and there is now a puddle of water next to it." else: desc_text = "This strange device is labeled as a \"<WRITTEN_TEXT>freezer</>\". " \ "Is is making a grumbling sound, and cold air is pouring from it. " \ "It is connected to a small platform on which is a chunk of ice. " \ "It seems to be keeping it frozen." say(desc_text) class MotherDaemon(Feature): def __init__(self, id, name): super().__init__(id, name) self.talk_msg = \ "<SPOKEN_TEXT>Greetings. I am the mother of the DAEMON's. " \ "You've arrived here <CLUE>due to motions<SPOKEN_TEXT> out of your control. " \ "It is surprising you have made it this far- a great <CLUE>application<SPOKEN_TEXT> of your skills. " \ "I hope you are <CLUE>quite pleased<SPOKEN_TEXT>. " \ "You may be upset, and you might think that revenge is a <CLUE>small dish<SPOKEN_TEXT> best served cold. " \ "But hopefully by now you have at least learned what you truly are...</>" def get_status(self, type=None): if type is None: type = "MotherDaemon" return super().get_status(type) def talk(self, game, actionargs): say(self.talk_msg) class Storage(Feature): """Thing that can store other things""" def __init__(self, id, name): super().__init__(id, name) self.has_contents = True self.contents = [] self.contents_accessible = True self.receive_preps = [] self.contents_accessible_iff_open = True self.can_be_opened = False self.is_open = True self.msg_already_opened = "The {} is already open.".format(self.name) self.msg_already_closed = "The {} is already closed.".format(self.name) self.msg_open = "You open the {}.".format(self.name) self.msg_close = "You close the {}.".format(self.name) self.msg_is_closed = "The {} is closed.".format(self.name) self.msg_look_in = "You look in the {}.".format(self.name) def get_status(self, type=None): if type is None: type = "Storage" return super().get_status(type) def receive_item(self, game, item, prep): if self.has_contents and prep in self.receive_preps: if self.can_be_opened and not self.is_open: say(self.msg_is_closed) else: game.player.remove_from_inventory(item) self.add_item(item) say("You put the {} {} the {}.".format(item.name, prep, self.name)) else: say("You can't put things {} the {}.".format(prep, self.name)) def add_item(self, item): self.contents.append(item) def remove_item(self, item): self.contents.remove(item) def list_contents(self): if self.receive_preps: prep = self.receive_preps[0] else: prep = "in" extra_sentence = "" # if contents is not empty it returns "True" if self.contents and self.contents_accessible: extra_sentence = "{} it you see".format(prep).capitalize() extra_sentence = " " + extra_sentence extra_sentence += Utilities.list_to_words([o.get_list_name() for o in self.contents]) extra_sentence += "." return extra_sentence def get_desc(self): desc_string = self.description desc_string += self.list_contents() say(desc_string) def get_list_name(self): list_string = self.list_name if self.receive_preps: prep = self.receive_preps[0] else: prep = "in" # if contents is not empty it returns "True" if self.contents and self.contents_accessible: list_string += " ({} which is".format(prep) list_string += Utilities.list_to_words([o.get_list_name() for o in self.contents]) list_string += ")" return list_string def open(self, game, actionargs): if not self.can_be_opened: say(self.msg_cannot_be_opened) else: if self.is_open: say(self.msg_already_opened) else: self.set_open() open_text = self.msg_open open_text += self.list_contents() say(open_text) def set_open(self): self.is_open = True if self.contents_accessible_iff_open: self.contents_accessible = True def close(self, game, actionargs): if not self.can_be_opened: say(self.msg_cannot_be_opened) else: if not self.is_open: say(self.msg_already_closed) else: self.set_closed() say(self.msg_close) def set_closed(self): self.is_open = False if self.contents_accessible_iff_open: self.contents_accessible = False def look_in(self, game, actionargs): if "in" not in self.receive_preps or not self.can_be_opened: say(self.msg_cannot_look_in) else: if self.is_open: look_text = self.msg_look_in look_text += self.list_contents() say(look_text) else: self.open(game, actionargs) class Container(Storage): """Things are stored IN the Container If the container is CLOSED things inside are NOT accessible. If the container is OPEN things inside ARE accessible EXAMPLES: Fridge, Chest """ def __init__(self, id, name): super().__init__(id, name) self.can_be_opened = True self.is_open = False self.receive_preps = ["in"] self.contents_accessible = False self.contents_accessible_iff_open = True def get_status(self, type=None): if type is None: type = "Container" return super().get_status(type) class Surface(Storage): """Things are stored ON the surface Things ARE accessible when on the surface EXAMPLES: Table, Shelf""" def __init__(self, id, name): super().__init__(id, name) self.can_be_opened = False self.receive_preps = ["on"] def get_status(self): return super().get_status("Surface") class VendingTerminal(Container): """Things are stored IN the Container If the container is CLOSED things inside are NOT accessible. If the container is OPEN things inside ARE accessible EXAMPLES: Fridge, Chest """ def __init__(self, id, name): super().__init__(id, name) self.can_receive = False self.can_be_opened = False self.is_open = True self.contents_accessible = True self.contents_accessible_iff_open = True self.is_listed = True self.dispensed = False self.ticket = None def get_status(self, type=None): if type is None: type = "VendingTerminal" return super().get_status(type) def hit(self, game, actionargs): if self.dispensed: super().hit(game, actionargs) else: say( "You give the vending terminal a smack, but it's not enough to dislodge the ticket. Maybe something with more force...") def ram(self, game, actionargs): say("You RAM the vending terminal with tremendous force.") if self.dispensed: super().ram(game, actionargs) else: self.ticket.dispensed = True self.ticket.description = self.ticket.alt_description self.dispensed = True self.description = self.alt_description say(self.msg_rammed) def receive_item(self, game, item, prep): say("You can't put things {} the {}.".format(prep, self.name)) class Bus(Container): """Not-Takable, Not-Dropable thing""" def __init__(self, id, name): super().__init__(id, name) self.can_be_taken = False self.can_be_dropped = False self.msg_cannot_take = "The {} is fixed in place.".format(self.name) def get_status(self, type=None): if type is None: type = "Bus" return super().get_status(type) def go(self, game, actionargs): say(self.msg_go) if game.thing_list["floppyDisk"] in self.contents: say("On your way out of the bus, you notice a floppy disk sitting on the driver's seat...") class Document(Item): """Takable, Dropable thing""" def __init__(self, id, name): super().__init__(id, name) self.file = "binary" def get_status(self, type=None): if type is None: type = "Document" return super().get_status(type) # ACTION for read def read(self, game, actionargs): file = open(self.file, "r") count = 0 if file.mode == 'r': str = file.read() str = str.split(" ") display_str = "" for x in str: display_str += x count += 1 if count % 10 == 0: say(display_str) display_str = "" if count % 100 == 0: ans = game.get_yn_answer("...Are you sure you want to keep reading? (y/n)") if not ans: say("That was... useful.") break if count % 1000 == 0: say("You stop reading in spite of yourself, lest you go mad...") break file.close()
LindseyL610/CS467-AdventureProject
Thing.py
Thing.py
py
66,406
python
en
code
0
github-code
6
37131271257
#!/usr/bin/env python #_*_coding:utf-8_*_ import numpy as np from sklearn.decomposition import PCA def pca(encodings, n_components = 2): encodings = np.array(encodings) data = encodings[:, 1:] shape = data.shape data = np.reshape(data, shape[0] * shape[1]) data = np.reshape([float(i) for i in data], shape) newData = PCA(n_components = n_components).fit_transform(data) pca = [] for i in range(len(data)): pca.append([encodings[i][0]] + list(newData[i])) return np.array(pca)
Superzchen/iFeature
clusters/pca.py
pca.py
py
505
python
en
code
152
github-code
6
36696903435
from typing import Dict, List from tips.framework.actions.sql_action import SqlAction from tips.framework.actions.sql_command import SQLCommand from tips.framework.metadata.additional_field import AdditionalField from tips.framework.metadata.table_metadata import TableMetaData from tips.framework.metadata.column_info import ColumnInfo from tips.framework.utils.sql_template import SQLTemplate from tips.framework.actions.clone_table_action import CloneTableAction from tips.framework.utils.globals import Globals class AppendAction(SqlAction): _source: str _target: str _whereClause: str _isOverwrite: bool _metadata: TableMetaData _binds: List[str] _additionalFields: List[AdditionalField] _isCreateTempTable: bool def __init__( self, source: str, target: str, whereClause: str, metadata: TableMetaData, binds: List[str], additionalFields: List[AdditionalField], isOverwrite: bool, isCreateTempTable: bool, ) -> None: self._source = source self._target = target self._whereClause = whereClause self._isOverwrite = isOverwrite self._metadata = metadata self._binds = binds self._additionalFields = additionalFields self._isCreateTempTable = isCreateTempTable def getBinds(self) -> List[str]: return self._binds def getCommands(self) -> List[object]: globalsInstance = Globals() cmd: List[object] = [] ## if temp table flag is set on metadata, than create a temp table with same name as target ## in same schema if ( self._isCreateTempTable and globalsInstance.isNotCalledFromNativeApp() ## Native apps don't allow create table or create temporary table privilege ): cmd.append( CloneTableAction( source=self._target, target=self._target, tableMetaData=self._metadata, isTempTable=True, ) ) commonColumns: List[ColumnInfo] = self._metadata.getCommonColumns( self._source, self._target ) fieldLists: Dict[str, List[str]] = self._metadata.getSelectAndFieldClauses( commonColumns, self._additionalFields ) selectClause: List[str] = fieldLists.get("SelectClause") fieldClause: List[str] = fieldLists.get("FieldClause") selectList = self._metadata.getCommaDelimited(selectClause) fieldList = self._metadata.getCommaDelimited(fieldClause) ## append quotes with bind variable cnt = 0 while True: cnt += 1 if ( (self._whereClause is not None and f":{cnt}" in self._whereClause) or (selectList is not None and f":{cnt}" in selectList) or (fieldList is not None and f":{cnt}" in fieldList) ): self._whereClause = ( self._whereClause.replace(f":{cnt}", f"':{cnt}'") if self._whereClause is not None else None ) selectList = ( selectList.replace(f":{cnt}", f"':{cnt}'") if selectList is not None else None ) fieldList = ( fieldList.replace(f":{cnt}", f"':{cnt}'") if fieldList is not None else None ) else: break cmdStr = SQLTemplate().getTemplate( sqlAction="insert", parameters={ "isOverwrite": self._isOverwrite, "target": self._target, "fieldList": fieldList, "selectList": selectList, "source": self._source, "whereClause": self._whereClause, }, ) cmd.append(SQLCommand(sqlCommand=cmdStr, sqlBinds=self.getBinds())) return cmd
ProjectiveGroupUK/tips-snowpark
tips/framework/actions/append_action.py
append_action.py
py
4,223
python
en
code
2
github-code
6
13969225316
import tweepy import math from io import open #consumer key, consumer secret, access token, access secret. ckey="x" csecret="x" atoken="x-x" asecret="x" auth = tweepy.OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) hashtag = 'dilma' result_type = 'recent' total = 350 iteracoes = int( math.ceil( total / 100.0 ) ) concatena = '' max_id = 0 for x in range(0, iteracoes): print ('Iteracao: ' + str(x+1) + ' de ' + str(iteracoes)) if max_id > 0: public_tweets = api.search(count='100', result_type=result_type, q=hashtag, max_id=max_id) #public_tweets = api.search(count='100', result_type=result_type, q=hashtag, until='2015-08-23', max_id=max_id) else: public_tweets = api.search(count='100', result_type=result_type, q=hashtag) for tweet in public_tweets: concatena += tweet.id_str + ': ' concatena += tweet.text.replace('\n', '') concatena += '\n' if max_id == 0 or tweet.id < max_id: max_id = (tweet.id - 1) with open("Output.txt", "w", encoding='utf-8') as text_file: text_file.write(concatena)
ZackStone/PUC_6_RI
Test/twitter_api_search_3.py
twitter_api_search_3.py
py
1,072
python
en
code
0
github-code
6
5503988928
# https://www.hackerrank.com/challenges/validating-named-email-addresses/problem import email.utils import re email_pattern = r'([a-zA-Z](\w|\d|_|-|[.])*)@([a-zA-Z])*[.]([a-zA-Z]{1,3})' def is_valid_email_address(person): email = person[1] return re.fullmatch(email_pattern, email) is not None people = [] n = int(input()) for _ in range(n): line = input() people.append(email.utils.parseaddr(line)) for element in (filter(is_valid_email_address, people)): print(email.utils.formataddr(element))
Nikit-370/HackerRank-Solution
Python/validating-parsing-email-address.py
validating-parsing-email-address.py
py
524
python
en
code
10
github-code
6
17763602061
''' UserList objects¶ This class acts as a wrapper around list objects. It is a useful base class for your own list-like classes which can inherit from them and override existing methods or add new ones. In this way, one can add new behaviors to lists. The need for this class has been partially supplanted by the ability to subclass directly from list; however, this class can be easier to work with because the underlying list is accessible as an attribute. class collections.UserList([list]) Class that simulates a list. The instance’s contents are kept in a regular list, which is accessible via the dataattribute of UserList instances. The instance’s contents are initially set to a copy of list, defaulting to the empty list []. list can be any iterable, for example a real Python list or a UserList object. In addition to supporting the methods and operations of mutable sequences, UserList instances provide the following attribute: data A real list object used to store the contents of the UserList class ''' ''' # Python program to demonstrate # userstring from collections import UserString d = 12344 # Creating an UserDict userS = UserString(d) print(userS.data) # Creating an empty UserDict userS = UserString("") print(userS.data) ''' # Python program to demonstrate # userstring from collections import UserString d = 12344 # Creating an UserDict userS = UserString(d) print(userS.data) # Creating an empty UserDict userS = UserString("") print(userS.data) ''' = RESTART: F:/python/python_programs/5competetive programming/collections module demo/userlist and usersting.py 12344 ''' # Python program to demonstrate # userstring from collections import UserString # Creating a Mutable String class Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to rmeove from # string def remove(self, s): self.data = self.data.replace(s, "") # Driver's code s1 = Mystring("Geeks") print("Original String:", s1.data) # Appending to string s1.append("s") print("String After Appending:", s1.data) # Removing from string s1.remove("e") print("String after Removing:", s1.data) ''' Original String: Geeks String After Appending: Geekss String after Removing: Gkss >>> '''
aparna0/competitive-programs
1collections module/userlist and usersting.py
userlist and usersting.py
py
2,368
python
en
code
0
github-code
6
45712336216
svenskord = ["katt", "bil", "buss", "apa"] facit =["cat", "car", "bus", "monkey"] engelskord = [" ", " ", " ", " "] y = int(0) for x in svenskord: print("skriv på engelska ordet " + x) engelskord [y] = input ("Engelska ") if facit [y] == engelskord [y]: print ("Rätt!") else: print ("fel") y=y+1
Svampen10/https---github.com-Svampen10-Coolkoder
First projects/glossor2.py
glossor2.py
py
352
python
no
code
0
github-code
6
21841418859
''' Jack Gallimore, Bucknell University, 2015 ''' import numpy def acf(series): n = len(series) data = numpy.asarray(series) mean = numpy.mean(data) c0 = numpy.sum((data - mean) ** 2) / float(n) def r(h): acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0 return round(acf_lag, 3) x = numpy.arange(n) # Avoiding lag 0 calculation acf_coeffs = map(r, x) return acf_coeffs
katelynallers/BD_HIGHRES
dreamZPT/acftest.py
acftest.py
py
449
python
en
code
0
github-code
6
19990663885
from django.conf.urls import url from . import views # 编写url尤其注意正则表达式匹配字符串的结尾,否则会引起冲突而达不到理想中的效果 urlpatterns = [ url(r'^$', views.index), url(r'^(\d+)/$', views.detail), url(r'^grades/$', views.grades), url(r'^students/$', views.students), url(r'^grades/(\d+)$', views.gradeStudents), url(r'^addstudent/$', views.addStudent) ]
Evanavevan/Django_Project
Project1/MyApp/urls.py
urls.py
py
427
python
en
code
0
github-code
6
70454780987
#Libraries---------------------------------------------------------------------- """ Dependencies and modules necessary for analytical functions to work """ #Cheminformatics import rdkit from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import Draw from rdkit.Chem.Draw import IPythonConsole from rdkit.Chem import Descriptors from rdkit.Chem import PandasTools from rdkit import DataStructs #Data processing import pandas as pd import matplotlib.pyplot as plt from matplotlib import gridspec # Clustering from scipy.cluster.hierarchy import dendrogram, linkage #Similarity analysis---------------------------------------------------------------------- def similarity_dendogram(data): """ Function takes the data file provided by the data_prep function and plots a dendogram based on compound similarity. Fingerprinting is based on Morgan fingerprints and similarity search is based on Tanimoto Similarity. #Input: data frame generated by data_prep function. #Output: dendogram and a data frame with similarity values. """ radius=2 nBits=1024 #generate fingerprints for database of compounds ECFP6_data = [AllChem.GetMorganFingerprintAsBitVect(mol,radius=radius, nBits=nBits) for mol in data['Rdkit_mol']] data["Morgan_fpt"]=ECFP6_data #build array with similarity scores length=len(ECFP6_data) array=pd.DataFrame(index=range(length),columns=range(length)) array.columns=list(data.CID) array.index=list(data.CID) linkage_array=np.empty(shape=(length,length)) for i in range(length): var1=list(data.CID)[i] mol1=list(data.Morgan_fpt)[i] for j in range(length): #calculate similarity var2=list(data.CID)[j] mol2=list(data.Morgan_fpt)[j] similarity=DataStructs.FingerprintSimilarity(mol1,mol2) array.iloc[i,j]=similarity linkage_array[i,j]=similarity linked = linkage(linkage_array,'single') labelList = list(data.CID) plt.figure(figsize=(8,15)) #Draw dendogram ax1=plt.subplot() plot=dendrogram(linked, orientation='left', labels=labelList, distance_sort='descending', show_leaf_counts=True) ax1.spines['left'].set_visible(False) ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) plt.title('Similarity clustering',fontsize=20,weight='bold') plt.tick_params ('both',width=2,labelsize=8) plt.tight_layout() plt.show() return (array)
AusteKan/Chemexpy
chemexpy/chemexpy/similarity_dendogram.py
similarity_dendogram.py
py
2,593
python
en
code
0
github-code
6
3981451688
''' Given a sorted list of numbers, change it into a balanced binary search tree. You can assume there will be no duplicate numbers in the list. Here's a starting point: ''' from collections import deque class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def __str__(self): # level-by-level pretty-printer nodes = deque([self]) answer = '' while len(nodes): node = nodes.popleft() if not node: continue answer += str(node.value) nodes.append(node.left) nodes.append(node.right) return answer def createBalancedBST(nums): index = len(nums) // 2 root_val = nums[index] root = Node(root_val) build_BST(nums[:index], root, 'left') build_BST(nums[index + 1:], root, 'right') return root def build_BST(nums, root, side): if len(nums) == 0: return index = len(nums) // 2 node_val = nums[index] node = Node(node_val) if side == 'left': root.left = node else: root.right = node build_BST(nums[:index], node, 'left') build_BST(nums[index + 1:], node, 'right') print(createBalancedBST([1, 2, 3, 4, 5, 6, 7])) # 4261357 # 4 # / \ # 2 6 #/ \ / \ #1 3 5 7
MateuszMazurkiewicz/CodeTrain
InterviewPro/2019.11.22/task.py
task.py
py
1,347
python
en
code
0
github-code
6
3307614760
# the idea is that we'll have a secret word that we store inside of our program and then the user # will interact with the program to try and guess the secret word # we want the user to be able to keep guessing what the secret word is until they finally get the word. secret_word = "hello" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False # while (guess != secret_word): # guess = input("Enter guess: ") # guess_count += 1 # print("You win!!!") while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 else: out_of_guesses = True # when we break this loop, there's going to be 2 possible scenarios. it's either the user guesses # the word correctly or the user runs out of guesses if out_of_guesses: print("You re out of guesses and you lost the game") else: print("You win!!")
Olayinka2020/ds_wkday_class
guess.py
guess.py
py
929
python
en
code
0
github-code
6
24535932614
LOBBYPORT = 16969 SERVERPORT = 8888 GAME_FILE_LOCATION = "tmp" DOLPHIN_PATH = "/Users/dpenning/Github/dolphin/gui_build/Binaries/Dolphin.app/Contents/MacOS/Dolphin" DEBUG = True GAME_CLASS_DEBUG = True GAME_NO_DOLPHIN = True BASE_URL = 'http://127.0.0.1:' + LOBBYPORT + "/" DEBUG_GAME_DICT = { "p1_stocks": 4, "p1_char": "Mewtwo", "p2_stocks": 0, "p2_char": "Roy", # placeholder for map, because dolphin cant sense map just yet "map": "None", }
dpenning/Sm4shed
SmashedLobby/config.py
config.py
py
454
python
en
code
2
github-code
6
34519324302
''' Pydantic Models ''' from datetime import datetime from typing import List, Optional from pydantic import BaseModel class User(BaseModel): id: int name = "Yebin Lee" signup_ts : Optional[datetime]=None friends: List[int]=[] external_data = { "id":"123", "signup_ts":"2017-06-01 12:22", "friends":[1, "2", b"3"], # int형만 인식 } user = User(**external_data) # external_data 객체의 전체 데이터 전달 print(user) print(user.id)
YebinLeee/fast-api
Study_FastAPI/pydantic_models.py
pydantic_models.py
py
481
python
en
code
0
github-code
6
21991351436
import rclpy from bitbots_moveit_bindings.libbitbots_moveit_bindings import initRos from rclpy.node import Node import random import os class AbstractRosOptimization: def __init__(self, robot_name, wandb=False): self.robot_name = robot_name self.wandb = wandb # need to init ROS for python and c++ code rclpy.init() initRos() # initialize node with unique name to avoid clashes when running the same optimization multiple times # needs to start with letter self.namespace = "anon_" + str(os.getpid()) + "_" + str(random.randint(0, 10000000)) + "_" self.node: Node = Node(self.namespace + "optimizer", allow_undeclared_parameters=True) # make all nodes use simulation time via /clock topic # actually not since we use direct python interfaces and the simulation runs in the same thread # self.node.set_parameters([rclpy.parameter.Parameter('use_sim_time', rclpy.Parameter.Type.BOOL, True)]) self.current_params = None self.sim = None def objective(self, trial): """ The actual optimization target for optuna. """ raise NotImplementedError()
bit-bots/parallel_parameter_search
parallel_parameter_search/abstract_ros_optimization.py
abstract_ros_optimization.py
py
1,196
python
en
code
2
github-code
6
20763005925
from datetime import datetime from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from aiogram.types import Message, CallbackQuery, LabeledPrice, PreCheckoutQuery, ContentType, ShippingQuery from data.config import PAYMENT_TOKEN from data.shop_config import IS_PREPAYMENT, CURRENCY, NEED_NAME, NEED_EMAIL, NEED_PHONE_NUMBER, NEED_SHIPPING_ADDRESS, \ RUSSIAN_POST_SHIPPING_OPTION, PICKUP_SHIPPING_OPTION from keyboards.inline.general import confirmation_cancel_kb from loader import dp, bot from states.ordering import Ordering from utils.db_api.api import db_api as db @dp.callback_query_handler(text="order", state='*') async def order(call: CallbackQuery, state: FSMContext): await confirm_address(call.message, state) @dp.message_handler(Text(ignore_case=True, contains=['оформить заказ']), state='*') async def confirm_address(message: Message, state: FSMContext): if not await db.count_cart(): await message.answer("Ваша корзина пуста!") return user = await db.get_current_user() cart = await db.get_cart_items_by_user(user.id) text = "===============ЗАКАЗ===============\n\n" to_pay = 0 prices = [] for record in cart: product = await db.get_product(record.product_id) text += f"{product.name} x {record.amount} \t\t\t\t\t {product.price * record.amount}р.\n" to_pay += product.price * record.amount prices.append( LabeledPrice(label=product.name + f" x {record.amount}", amount=product.price * record.amount * 100)) async with state.proxy() as data: data["prices"] = prices text += f"\nСумма: {to_pay}р.\n" \ f"Оформить заказ?" await message.answer(text, reply_markup=confirmation_cancel_kb) await Ordering.OrderConfirmation.set() @dp.callback_query_handler(text="yes", state=Ordering.OrderConfirmation) async def create_order(call: CallbackQuery, state: FSMContext): async with state.proxy() as data: prices = data["prices"] if IS_PREPAYMENT: await call.message.answer("Оплатите сумму заказа") await bot.send_invoice(chat_id=call.from_user.id, title=f"ЗАКАЗ ОТ {datetime.today()}", description='Или введите "Отмена"', payload=0, start_parameter=0, currency=CURRENCY, prices=prices, provider_token=PAYMENT_TOKEN, need_name=NEED_NAME, need_email=NEED_EMAIL, need_phone_number=NEED_PHONE_NUMBER, need_shipping_address=NEED_SHIPPING_ADDRESS, is_flexible=True) await Ordering.Payment.set() else: await db.create_order() await call.message.answer("Заказ оформлен!") await state.finish() @dp.pre_checkout_query_handler(lambda query: True, state=Ordering.Payment) async def checkout(query: PreCheckoutQuery): await bot.answer_pre_checkout_query(query.id, True) @dp.shipping_query_handler(lambda query: True, state=Ordering.Payment) async def process_shipping_query(query: ShippingQuery): await bot.answer_shipping_query(query.id, ok=True, shipping_options=[ RUSSIAN_POST_SHIPPING_OPTION, PICKUP_SHIPPING_OPTION]) @dp.message_handler(content_types=ContentType.SUCCESSFUL_PAYMENT, state=Ordering.Payment) async def proceed_successful_payment(message: Message, state: FSMContext): await db.create_order() await bot.send_message(chat_id=message.from_user.id, text="Спасибо за покупку!") await state.finish()
shehamane/kuriBot
src/handlers/users/ordering.py
ordering.py
py
3,797
python
en
code
0
github-code
6