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
22634264076
side=[] for x in range(0,3): a=int(input(f"Enter side{x+1}: ")) side.append(a) if side[2]+side[1]>side[0] and side[0]+side[2]>side[1] and side[0]+side[1]>side[2]: print("This is a Prefect Triangle") else: print("Thius is Not a triangle")
arironman/MSU-Python
ex-7/25.py
25.py
py
270
python
en
code
0
github-code
6
34215736207
import logging import os import gzip import filetype import multiprocessing as mp import pandas as pd from moonstone.normalization.reads.read_downsize import DownsizePair logger = logging.getLogger(__name__) def pair_up(seq_files_info): paired_list = [] query = None for key in seq_files_info: if key not in paired_list: # Any one pairs should generate ONLY one loop. query = seq_files_info[key][0] # set the query to the header of the sequence file file_counter = 0 # Confirm that we find two files fwd_reads_file = None # reset the file results rev_reads_file = None for key_a in seq_files_info: # Loop through again to find the matching header if query in seq_files_info[key_a][0]: # If the headers match it is either forward or reverse reads. if seq_files_info[key_a][1] == '1': fwd_reads_file = key_a file_counter += 1 if seq_files_info[key_a][1] == '2': rev_reads_file = key_a file_counter += 1 if fwd_reads_file and rev_reads_file: logger.info('\nForward file = %s\nReverse file = %s' % (fwd_reads_file, rev_reads_file)) paired_list.append(fwd_reads_file) paired_list.append(rev_reads_file) logger.info(f'List of Paired Reads Files:\n{paired_list}') return paired_list def plot_reads(file_info_dict): logger.info('Generating plot of number of reads') # generate a dataframe from the file information dictionary # to include filename as the index files: list = [] reads: list = [] for key in file_info_dict: files.append(key) reads.append(file_info_dict[key][2]) df = pd.DataFrame(index=files, data=reads, columns=['reads']) return df class DownsizeDir: """Used to downsize all reads in a given directory to the same number of reads. Reads are downsized by random selection of raw reads generating a subset from which alpha diversity can be calculated. Note that removal of data, while useful for diversity assessment, is no longer considered good practice. https://doi.org/10.1371/journal.pcbi.1003531 """ def __init__(self, n=1000, processes=1, seed=62375, in_dir='./', out_dir=''): logger.info(f'Starting instance of {__class__.__name__} in {__name__}.') self.in_dir = in_dir self.downsize_to = n self.seed = seed if out_dir: self.out_dir = out_dir else: self.out_dir = in_dir + 'downsized/' logger.info('No output directory specified.\nCreating default: %s ' % self.out_dir) if not os.path.exists(self.out_dir): os.mkdir(self.out_dir) else: logger.info('Looks like %s exists.' % self.out_dir) if processes > mp.cpu_count(): logger.warning('Number of requested processes [%i] is greater that the number of system CPUs [%i]' % (processes, mp.cpu_count())) self.processes = mp.cpu_count() logger.info('Number of processes set to maximum number of detected CPUs [%i].' % self.processes) else: self.processes = processes logger.info('Number of processes set to %i ' % self.processes) def detect_seq_reads(self): """The provided directory might contain files that are not sequence reads. This module attempts to identify ONLY files with sequence data.""" logger.info(f'Detecting sequence files in {self.in_dir}') seq_files = [f for f in os.listdir(self.in_dir) if os.path.isfile(self.in_dir + f)] logger.info(f'List of Sequencing Files Found:\n{seq_files}') return seq_files def read_info(self, seq_file): """Gather information on the number of reads for each of the sequence reads in the given directory. Number of reads can be plotted or reported. Files names and headers are used to match pairs. Both compressed and gzipped files are accepted. Function returns a dictionary where the filename is the key and the value is a list of information: {file: [header, F/R, Number of reads, format]} # e.g. {'forward.fastq': ['@A00709:44:HYG57DSXX:2:1101:10737:1266', '1', 100257, 'Uncompressed/FASTQ']""" seq_files_info = {} detect_type = filetype.guess(self.in_dir + seq_file) if detect_type: if detect_type.mime == 'application/gzip': logger.info('Detected gzipped file for %s' % seq_file) file = gzip.open(self.in_dir + seq_file, 'r') read_num = sum(1 for _ in gzip.open(self.in_dir + seq_file)) // 4 header = file.readline().decode().split(' ')[0] file.seek(0, 0) pair = file.readline().decode().split(' ')[1][0] file.close() seq_files_info[seq_file] = [header, pair, read_num, detect_type.mime] return seq_files_info if not detect_type: logger.info('Assuming uncompressed fastq file for %s' % seq_file) file = open(self.in_dir + seq_file, 'r') read_num = sum(1 for _ in open(self.in_dir + seq_file)) // 4 header = file.readline().split(' ')[0] file.seek(0, 0) pair = file.readline().split(' ')[1][0] file.close() seq_files_info[seq_file] = [header, pair, read_num, 'Uncompressed/FASTQ'] return seq_files_info def down_dir_pair(self): files_to_downsize = self.detect_seq_reads() logging.info('Found %i files.' % len(files_to_downsize)) '''This is a quick but efficient multiprocessing implementation to handle retrieving information from files in the target directory. The Pool is created, the number of workers = the class 'processes' attribute. Results are expected as a dictionary, so the resulting 'list of dictionaries' is converted with handy dict comprehension. ''' with mp.Pool(processes=self.processes) as pool: results = pool.map(self.read_info, files_to_downsize, chunksize=1) file_info_dict = {k: v for result in results for k, v in result.items()} list_to_downsize = pair_up(file_info_dict) worker_parameters = [] for k in range(len(list_to_downsize)//2): # number of files divided by 2: one instance per pair worker_parameters.append({'raw_file_f': list_to_downsize[k * 2], 'raw_file_r': list_to_downsize[k * 2 + 1], 'read_info': file_info_dict[list_to_downsize[k * 2]], 'in_dir': self.in_dir, 'out_dir': self.out_dir, 'n': self.downsize_to }) with mp.Pool(processes=self.processes) as pool: check = pool.map(self.instantiate, worker_parameters, chunksize=1) # noqa logger.info('Done!') def instantiate(self, wp): logger.info('Instantiating with parameters: %s' % wp) instance = DownsizePair(**wp) instance.downsize_pair()
motleystate/moonstone
moonstone/normalization/reads/downsize_dir.py
downsize_dir.py
py
7,336
python
en
code
0
github-code
6
12153147067
import matplotlib.pyplot as plt import numpy as np with open('scores.txt', 'r') as f: scores = f.read().splitlines() scores = list(map(int, scores)) mean = [] max_list = [] for i,j in enumerate(scores): if i % 1000 == 0: mean.append(np.average(scores[i:i+1000])) max_list.append(max(scores[i:i+1000])) episode = range(len(mean)) plt.ylabel('episode scores') plt.xlabel('training episodes') plt.yticks(np.arange(min(mean), max(mean)+1, 5000)) plt.title('mean scores') plt.plot(episode, mean) plt.show() plt.ylabel('episode scores') plt.xlabel('training episodes') plt.yticks(np.arange(min(max_list), max(max_list)+1, 10000)) plt.title('max scores') plt.plot(episode, max_list) plt.show()
Mike-Teng/Deep_Learning
lab/lab2/plot.py
plot.py
py
798
python
en
code
0
github-code
6
29188042884
""" Problem Statement A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S. Example: Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} """ from typing import List def was_visited(value): return value < 0 def was_not_visited(value): return value >= 0 class Solution: @classmethod def array_nesting(cls, nums: List[int]) -> int: result = 0 for index, _ in enumerate(nums): if was_visited(nums[index]): continue else: next_pos = nums[index] count = 0 while was_not_visited(nums[next_pos]): actual_pos = next_pos next_pos = nums[next_pos] count += 1 nums[actual_pos] = -1 result = count if count > result else result return result
walterjgsp/algorithms
Python/problems/problem_0008_array_nesting.py
problem_0008_array_nesting.py
py
1,388
python
en
code
6
github-code
6
31734423723
import sqlite3 class sqlcommands: def Open(self): if self.bOpen is False: self.conn = sqlite3.connect(self.db) self.curs = self.conn.cursor() self.bOpen = True return True def __init__(self, table): self.db = './~newsqlcommands.sqlt3' self.conn = None self.curs = None self.bOpen = False self.fields = None self.table_name = table def CreateTable(self): sqlCommand = f"""CREATE TABLE if not EXISTS {self.table_name} ( EntryNumber INTEGER PRIMARY KEY, TimeIn TEXT, DateIn TEXT, TimeOut TEXT, DateOut TEXT);""" self.curs.execute(sqlCommand) def NewIn(self, field): if self.bOpen: self.curs.execute(f"INSERT INTO {self.table_name} (DateIn, TimeIn) VALUES (date('now', 'localtime'), '{field}');") self.conn.commit() self.fields = field return True return False def NewOut(self, field): if self.bOpen: self.curs.execute(f"UPDATE {self.table_name} SET DateOut = date('now', 'localtime'), TimeOut = '{field}' WHERE TimeIn = '{self.fields}';") self.conn.commit() return True return False def FillMissing(self, time_out, date_out, ifempty): if self.bOpen: self.curs.execute(f"UPDATE {self.table_name} SET DateOut = '{date_out}', TimeOut = '{time_out}' WHERE TimeIn = '{ifempty}';") self.conn.commit() return True return False def GetAll(self): self.curs.execute("SELECT TimeIn, TimeOut FROM " + self.table_name + ";") ans = self.curs.fetchall() return ans def GetLast(self): self.curs.execute(f"SELECT TimeIn FROM {self.table_name} WHERE ROWID IN ( SELECT max( ROWID ) FROM {self.table_name});") nochar = "!@,(){}[]' " naked = "" self.fields = self.curs.fetchone() for each in self.fields: for char in nochar: each = str(each).replace(char,"") naked = naked + each self.fields = naked return self.fields def GetSome(self, count): self.curs.execute("SELECT * FROM " + self.table_name + " ORDER BY DateIn LIMIT 5 OFFSET %s" % count + ";") ans = self.curs.fetchall() return ans def GetPrimary(self): self.curs.execute("SELECT TimeIn FROM " + self.table_name + ";") ans = self.curs.fetchall() return ans def CountDateIn(self): self.curs.execute("SELECT COUNT(DateIn) FROM " + self.table_name + ";") ans = self.curs.fetchone() return ans def DelTable(self): if self.bOpen: self.curs.execute("DROP TABLE IF EXISTS " + self.table_name + ";") return True return False def GetOne(self, TimeIn, inout): if self.bOpen: if inout == "TimeIn": self.curs.execute(f"Select DateIn from {self.table_name} where {inout} = '{TimeIn}';") else: self.curs.execute(f"Select DateOut from {self.table_name} where {inout} = '{TimeIn}';") Lalist = self.curs.fetchone() self.curs.execute(f"Select {inout} from {self.table_name} where {inout} = '{TimeIn}';") Lelist = self.curs.fetchone() self.curs.execute(f"SELECT TimeIn FROM {self.table_name} WHERE TimeOut is null;") saved = self.curs.fetchone() return Lelist, Lalist, saved return None def DelEm(self, TimeIns): if self.bOpen: if len(TimeIns) != 0: self.curs.execute("DELETE from " + self.table_name + " where " + " or ".join(("TimeIn = " + str(n) for n in TimeIns))) self.conn.commit() return True return False def UpdateOne(self, new, time, oldday, oldtime, inout): if self.bOpen: if inout == "TimeIn": self.curs.execute(f"UPDATE {self.table_name} SET DateIn = '{new} ', {inout} = '{time}' WHERE DateIn = '{oldday}' and {inout} = '{oldtime}';") else: self.curs.execute(f"UPDATE {self.table_name} SET DateOut = '{new} ', {inout} = '{time}' WHERE DateOut = '{oldday}' and {inout} = '{oldtime}';") self.conn.commit() return True return False def DelOne(self, TimeIn): if self.bOpen: self.curs.execute("DELETE from " + self.table_name + " where TimeIn = '" + TimeIn + "';") return True return False def End(self): if self.bOpen: self.conn.commit() self.bOpen = False return True
Loondas/PythonGameTimer
GameTimer/cgi-bin/newsqlcommands.py
newsqlcommands.py
py
4,718
python
en
code
0
github-code
6
72652196027
from Core import Core class IN: def __init__(self): self.identifier = "" def parse(self, S): #should not output anything unless error case if S.currentToken() == Core.INPUT: S.nextToken() else: print("ERROR: Token should be 'input'") quit() if S.currentToken() == Core.ID: self.identifier = S.getID() S.nextToken() else: print("ERROR: Token should be an 'id'") quit() if S.currentToken() != Core.SEMICOLON: print("ERROR: Token should be ';'") quit() S.nextToken() def print(self, numIndents): print(("\t" * numIndents) + "input ", end = '') print(self.identifier + ";")
hm0416/CSE-3341
Project1/IN.py
IN.py
py
768
python
en
code
1
github-code
6
27413490238
def reversedInt(num: int) -> int: result = 0 while num: lastDigit = num % 10 result = result * 10 + lastDigit if result < -2 ** 31 or result > 2 ** 31: return 0 num //=10 return result print(reversedInt(1534236469)) print(reversedInt(2147483641))
irvandindaprakoso/online-test-py
LeetCode/reverseInt.py
reverseInt.py
py
316
python
en
code
0
github-code
6
28888632365
import sys import os import subprocess #### SETTINGS #### CC = "gcc" DEFAULT_INCLUDES = [ "stdio.h", "stdbool.h", "stdlib.h", "unistd.h", "string.h", ] TRY_USE_BAT = True #### -------- #### # This marker is used to remove any included code from the output, # and only display the expanded macros given as the first argument to this program. # Preproc seems to delete comments and defines, a global constant seems remain untouched. # There should be no need to modify this. MARKER = "const int PREPROC_CONTENT_MARKER = 69420;" def error(message): print(f"\n{sys.argv[0]}: {message}") sys.exit(1) def get_includes(): if len(sys.argv) < 3: print(f"Using default includes: {DEFAULT_INCLUDES}") includes = DEFAULT_INCLUDES else: includes = [] for i in range(2, len(sys.argv)): includes.append(sys.argv[i]) result = [] for include in includes: result.append("-include") result.append(include) return result def run_preprocessor(): arg_input = f"\n{MARKER}\n{sys.argv[1]}" arg_includes = get_includes() compiler_command = [CC, "-E", "-"] compiler_command.extend(arg_includes) try: return subprocess.check_output( compiler_command, input=str.encode(arg_input) ).decode("UTF-8") except: error("Failed to run preprocessor.") def clean_output(raw): stripped_marker = MARKER.strip() result = "" has_found_marker = False for line in iter(raw.splitlines()): if has_found_marker: result = result + line if line.strip() == stripped_marker: has_found_marker = True return result def display_with_bat(cleaned): try: subprocess.run( ["bat", "--language", "cpp"], input=str.encode(cleaned)) return True except: return False def main(): if len(sys.argv) < 2: error("Invalid arguments. Expected:\n" + "preproc <code to preprocess> (Uses a default set of includes)\n" + "preproc <code to preprocess> <any number of headers to include>") preprocessor_output = run_preprocessor() cleaned = clean_output(preprocessor_output) if TRY_USE_BAT == False or display_with_bat(cleaned) == False: print(cleaned) sys.exit(0) if __name__ == "__main__": main()
mrchip42k/preprocessor-util
preproc.py
preproc.py
py
2,139
python
en
code
0
github-code
6
21550234357
#!/usr/bin/env python3 """ Main file for program """ import parser, sys, setup, functions import time FOLDERS = { "result": "Result", "finished": "Finished", "unfinished": "Unfinished", "video": "Video", "unsorted": "Unsorted" } def main(): """ Main function. """ options = parser.parse_options() command = options["known_args"]["command"] if command == "setup": setup.setup_folders(FOLDERS) elif command == "clean": setup.remove_folder(FOLDERS["result"]) elif command == "start": start_time = time.time() functions.start_sort(FOLDERS) print("--- %s seconds ---" % (time.time() - start_time)) elif command == "scan": print("\n### Available folders ###\n") functions.present_folders(FOLDERS) sys.exit() if __name__ == "__main__": main()
lewenhagen/fileSorter
main.py
main.py
py
861
python
en
code
0
github-code
6
26213424744
from hw2.datasets.train import TrainDataset from hw2.models.base import Model from hw2.models.catboost_model import CatBoostModel from hw2.models.embeddings_model import EmbeddingModel import numpy as np class CombinedModel(Model): def __init__(self, loss_function: str, iterations: int, embedding_dim: int, task_type: str, random_state: int, verbose: bool = True): super().__init__(random_state, verbose) self._catboost_model = CatBoostModel(loss_function, iterations, task_type, random_state, verbose) self._embedding_model = EmbeddingModel(embedding_dim, random_state, verbose) def _add_scores(self, dataset: TrainDataset): scores = self._embedding_model.predict(dataset) dataset.add_features("emb_score", scores) def _drop_scores(self, dataset: TrainDataset): dataset.drop_features("emb_score") def fit(self, dataset: TrainDataset) -> "CombinedModel": self._embedding_model.fit(dataset) self._add_scores(dataset) self._catboost_model.fit(dataset) self._drop_scores(dataset) return self def predict(self, dataset: TrainDataset) -> np.ndarray: self._add_scores(dataset) pred = self._catboost_model.predict(dataset) self._drop_scores(dataset) return pred
Sushentsev/recommendation-systems
hw2/models/combined_model.py
combined_model.py
py
1,319
python
en
code
0
github-code
6
19208567957
''' Helps the user calculate the price that they should charge the customer ''' def tax(): #Checks if the user is from ontario or not location = input("Are you shopping from Ontario? Enter Y or N: ") #Makes the user input a tax rate if they are not from ontario if location == "n" or location == "N": taxRate = input("Enter the tax of your state or province as a percentage: ") #Gives the user the default rate of 13 percent if they are from ontario if location == "y" or location == "Y": taxRate = "13" #Gets some information from the user to help us calculate the final price price = float(input("Enter the price of the item: ")) age = int(input("Enter your age: ")) member = input("Are you a member of this store? Enter Y or N: ") #Gives the customer a discount if they fulfill all the proper conditions if (age < 18 or age >= 65) and (member == "y" or member == "Y"): price = price * 0.85 return str(round((price * float("1." + taxRate)),2)) #prints out the final price that the user will need to pay print("The total cost with tax for your order is " + tax())
kelvincaoyx/UTEA-PYTHON
Week 2/PythonUnitTwoPractice/shop.py
shop.py
py
1,160
python
en
code
0
github-code
6
32681042902
import numpy as np from .BaseNB import BaseNaiveBayes # 高斯贝叶斯 class GaussianNaiveBayes(BaseNaiveBayes): # 训练 def fit(self, X: np.ndarray, y: np.ndarray): """ X: train dataset, shape = (n_samples, n_features) y: target, shape = (n_samples, ) """ # 计算 y 的先验概率 y_prior_proba = [] self.classes_ = np.unique(y) for c in self.classes_: c_count = (y == c).sum() y_prior_proba.append(c_count / np.size(y)) self._y_prior_proba = np.array(y_prior_proba) # 计算连续变量 x 的高斯分布参数 features = X.shape[1] self._theta = np.zeros((np.size(self.classes_), features)) self._sigma = np.zeros((np.size(self.classes_), features)) for i in range(np.size(self.classes_)): x_c = X[y == self.classes_[i]] self._theta[i, :] = np.mean(x_c, axis=0) self._sigma[i, :] = np.var(x_c, axis=0) return self def _joint_log_likelihood(self, X: np.ndarray): jll = [] for i in range(np.size(self.classes_)): log_prior = np.log(self._y_prior_proba[i]) # 高斯公式取对数 x_given_y = - 0.5 * np.sum(np.log(2. * np.pi * self._sigma[i, :])) x_given_y -= 0.5 * np.sum(((X - self._theta[i, :]) ** 2) / (self._sigma[i, :]), axis=1) jll.append(log_prior + x_given_y) jll = np.array(jll).T return jll def __repr__(self): return "<GaussianNaiveBayes>" if __name__ == "__main__": from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB test = np.array([[1, 'S'], [1, 'M'], [1, 'M'], [1, 'S'], [1, 'S'], [2, 'S'], [2, 'M'], [2, 'M'], [2, 'L'], [2, 'L'], [3, 'L'], [3, 'M'], [3, 'M'], [3, 'L'], [3, 'L']]) iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) gnb = GaussianNaiveBayes().fit(X_train, y_train) log_proba = gnb.predict_log_proba(X_test) proba = gnb.predict_proba(X_test) y_pred = gnb.predict(X_test) print(accuracy_score(y_test, y_pred))
HuipengXu/Statistical-learning-method
naive_bayes/GaussianNB.py
GaussianNB.py
py
2,327
python
en
code
7
github-code
6
21884536797
"""Calculate the expected detection rates for apertif.""" import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from frbpoppy import CosmicPopulation, Survey, SurveyPopulation, hist from tests.convenience import plot_aa_style, rel_path from alpha_real import EXPECTED, poisson_interval N_DAYS = 1 # Not used in eventual result SCALE_TO = 'parkes-htru' pop = CosmicPopulation.complex(n_srcs=1e5, n_days=N_DAYS) pop.generate() apertif = Survey('wsrt-apertif', n_days=N_DAYS) apertif.set_beam(model='apertif_real') if SCALE_TO == 'parkes-htru': htru = Survey('parkes-htru', n_days=N_DAYS) htru.set_beam(model='parkes') if SCALE_TO == 'askap': askap = Survey('askap-fly', n_days=N_DAYS) askap.set_beam(model='gaussian', n_sidelobes=0.5) days_per_frbs = [] for i in tqdm(range(2000), desc='Survey Run'): apertif_pop = SurveyPopulation(pop, apertif, mute=True) if SCALE_TO == 'parkes-htru': htru_pop = SurveyPopulation(pop, htru, mute=True) n_frbs_htru = EXPECTED['parkes-htru'][0] n_days_htru = EXPECTED['parkes-htru'][1] scaled_n_days = n_days_htru*(htru_pop.source_rate.det / n_frbs_htru) if SCALE_TO == 'askap': askap_pop = SurveyPopulation(pop, askap, mute=True) n_frbs_askap = EXPECTED['askap-fly'][0] n_days_askap = EXPECTED['askap-fly'][1] scaled_n_days = n_days_askap*(askap_pop.source_rate.det / n_frbs_askap) days_per_frb = scaled_n_days / apertif_pop.source_rate.det # print(f'{days_per_frb} days per frb') days_per_frbs.append(days_per_frb) days_per_frbs = np.array(days_per_frbs) mean = np.mean(days_per_frbs) std = np.std(days_per_frbs) poisson_std = poisson_interval(mean) print(f'Mean rate for apertif is {mean}') print(f'Standard deviation of {std}') # Plot rates, values = hist(days_per_frbs, bin_type='lin') plot_aa_style() plt.step(rates, values, where='mid') plt.xlabel(f'Apertif days per burst scaled to {SCALE_TO}') plt.savefig(rel_path('./plots/rate_apertif_dist.pdf'))
TRASAL/frbpoppy
tests/rates/apertif_dist.py
apertif_dist.py
py
2,026
python
en
code
26
github-code
6
6264519181
import matplotlib.pyplot as plt class Drawer(): def __init__(self,y_pred, y_test, target_names,X_test,eigenfaces): self.y_pred=y_pred self.y_test=y_test self.target_names=target_names self.X_test=X_test self.eigenfaces=eigenfaces def plot_gallery(self,images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1) plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray) plt.title(titles[i], size=12) plt.xticks(()) plt.yticks(()) # plot the result of the prediction on a portion of the test set # def title(self): # pred_name = self.target_names[self.y_pred[self.i]].rsplit(' ', 1)[-1] # true_name = self.target_names[self.y_test[self.i]].rsplit(' ', 1)[-1] # return 'predicted: %s\ntrue: %s' % (pred_name, true_name) def show(self,h,w): prediction_titles = [] for i in range(self.y_pred.shape[0]): pred_name = self.target_names[self.y_pred[i]].rsplit(' ', 1)[-1] true_name = self.target_names[self.y_test[i]].rsplit(' ', 1)[-1] prediction_titles.append('predicted: %s\ntrue: %s' % (pred_name, true_name)) self.plot_gallery(self.X_test, prediction_titles, h, w) # plot the gallery of the most significative eigenfaces eigenface_titles = ["eigenface %d" % i for i in range(self.eigenfaces.shape[0])] self.plot_gallery(self.eigenfaces, eigenface_titles, h, w) plt.show()
bartekskrabacz/python_project
src/python_project/Drawer.py
Drawer.py
py
1,774
python
en
code
0
github-code
6
5456868264
print("\n Bem-vindo ao menu de gerenciamento!\n") esc = int(input('Digite 1 para criar um ônibus: ')) class Onibus: def __init__(self, nome, parada, motorista, fiscal): self.nome = nome self.parada = parada self.motorista = motorista self.fiscal = fiscal def __str__(self): return f" Nome do ônibus: {self.nome} \ \n Rota: {self.parada} \ \n Motorista: {self.motorista} \ \n Fiscal: {self.fiscal}" class Motorista: def __init__(self, nomeMot, idade, cpf): self.nomeMot = nomeMot self.idade = idade self.cpf = cpf def __str__(self): return f" Nome do motorista: {self.nomeMot} \ \n Idade: {self.idade} \ \n CPF: {self.cpf} " class Fiscal: def __init__(self, nomeFis, idade, cpf): self.nomeFis = nomeFis self.idade = idade self.cpf = cpf def __str__(self): return f" Nome do fiscal: {self.nomeFis} \ \n Idade: {self.idade} \ \n CPF: {self.cpf} " loop1 = True loop2 = False ListaOnibus = [] ListaMotoristas = [] ListaFiscais = [] while loop1 == True: while loop2 == True: print('\n O que deseja fazer agora?\ \n 1 - Criar um ônibus \ \n 2 - Mostrar ônibus \ \n 3 - Alterar dados do motorista\ \n 4 - Alterar dados do fiscal\ \n 5 - Alterar rota do ônibus\ \n 6 - Deletar ônibus \n') esc = int(input('Escolha uma das opções para continuar: ')) loop2 = False if (esc == 1): #Criar um ônibus com ponto de parada, motorista e fiscal, #assigna motorista e fiscal ao ônibus e adicona ponto de parada. nome = str(input('Nome do ônibus: ')) parada = str(input('Parada do ônibus:')) motorista = str(input('Nome do motorista: ')) fiscal = str(input('Nome do fiscal: ')) onb = Onibus(nome, parada, motorista, fiscal) ListaOnibus.append(onb) print('\n Ônibus criado!') loop2 = True if (esc == 2): #Mostra o ônibus, sua rota, seu motorista e seu fiscal print('\n Informações do ônibus', onb.nome, ':\n') for item in ListaOnibus: print(item) tamanho = len(ListaOnibus) if tamanho == 0: print('Não há nenhum ônibus cadastrado.') loop2 = True if (esc == 3): #Altera dados do Motorista onb = Onibus(nome, parada, motorista, fiscal) print('\n O motirsta do ônibus', onb.nome, 'é o: ', onb.motorista) print('\n') nomeMot = onb.motorista idade = str(input('Idade do motorista:')) cpf = str(input('CPF: ')) print('\n') mot = Motorista(nomeMot, idade, cpf) ListaMotoristas.append(mot) for item in ListaMotoristas: print(item) print('\n Os dados do motorista', onb.motorista, 'foram alterados!') loop2 = True if (esc == 4): #Altera dados do Fiscal onb = Onibus(nome, parada, motorista, fiscal) print('O fiscal do ônibus:', onb.nome, 'é o: ', onb.fiscal) print('\n') nomeFis = onb.fiscal idade = str(input('Idade do fiscal:')) cpf = str(input('CPF: ')) print('\n') fis = Fiscal(nomeFis, idade, cpf) ListaFiscais.append(fis) for item in ListaFiscais: print(item) print('\n Os dados do fiscal foram alterados!') loop2 = True if (esc == 5): #Altera rota do ônibus onb = Onibus(nome, parada, motorista, fiscal) print('\n O ponto de parada do ônibus', onb.nome, 'é: ', onb.parada) print('\n') NovaParada = str(input('Nova parada:')) print('\n') onb.parada = NovaParada print('Local de parada atualizado para: ', onb.parada, '.') loop2 = True if (esc == 6): #Deleta ônibus ListaOnibus.clear() print('O ônibus foi deletado') loop2 = True
nand5a/Entrega-02
Entrega-02.py
Entrega-02.py
py
4,204
python
pt
code
0
github-code
6
42168409282
from typing import List class Solution: def optimalArray(self, n : int, ar : List[int]) -> List[int]: # code here res = [] half, full = 0, 0 for i in range(n): full += ar[i] if i&1: res.append(full - 2*half) else: half += ar[i//2] res.append(full - 2*half + ar[i//2]) return res; #{ # Driver Code Starts class IntArray: def __init__(self) -> None: pass def Input(self,n): arr=[int(i) for i in input().strip().split()]#array input return arr def Print(self,arr): for i in arr: print(i,end=" ") print() if __name__=="__main__": t = int(input()) for _ in range(t): n = int(input()) a=IntArray().Input(n) obj = Solution() res = obj.optimalArray(n, a) IntArray().Print(res) # } Driver Code Ends
shane-Coder/DailyCode
Optimal Array - GFG/optimal-array.py
optimal-array.py
py
1,007
python
en
code
0
github-code
6
9224654424
# Usage # python scripts/collect_pickle_states.py -i PICKLE_DATA_PATH import argparse import numpy as np import tqdm import structs def collect_stats(args): data = structs.load(args.input_path) sample_count = [] for key in tqdm.tqdm(data): sample_count.append(data[key]['rst'].shape[0]) values, counts = np.unique(sample_count, return_counts=True) value_counts_pairs = list(zip(values, counts)) for (value, count) in value_counts_pairs: print('{} has {} predictions with counts {}'.format(args.input_path, value, count)) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-i', '--input-path', help='Input pickle file to read') args = parser.parse_args() collect_stats(args) if __name__ == '__main__': main()
Tsinghua-MARS-Lab/InterSim
simulator/prediction/M2I/guilded_m_pred/scripts/collect_pickle_stats.py
collect_pickle_stats.py
py
816
python
en
code
119
github-code
6
12950721382
import matplotlib.pyplot as plt import numpy as np import scipy.optimize as spy from . import AstroLib_Basic as AL_BF ################################################################################ # CREATE BODY WITH ITS CHARACTERISTICS ################################################################################ class Spacecraft: """ Spacecraft class: create spacecraft with its mass and propulsion parameters """ def __init__(self, *args, **kwargs): """ Constructor: input the main characteristics INPUTS: ADDITIONAL INPUTS: Isp: specific impulse m_dry: dry mass of the spacecraft T: thrust of the spacecraft g0: acceleration of gravity """ # Propulsive parameters self.Isp = kwargs.get('Isp', 3100) self.m_dry = kwargs.get('m_dry', 747) self.T = kwargs.get('T', 90e-3) self.g0 = kwargs.get('g0', AL_BF.g0) def MassChange(self, m, deltav): """ MassChange: change (decrease) mass of the spacecraft when an impulse is applied INPUTS: m: current mass of the spacecraft (fuel+drymass) deltav: magnitude of the impulse applied OUTPUTS: mf: final mass """ mf = m * np.exp( -deltav/(self.g0 * self.Isp) ) return mf def MassChangeInverse(self, m, deltav): """ MassChangeInverse: change (increase) the mass to obtain the mass of the spacecraft before an impulse was applied IMPUTS: m: current mass of the spacecraft (fuel+drymass) deltav: magnitude of the impulse applied OUTPUTS: mi: final mass """ mi = m/np.exp( -deltav /(self.g0 * self.Isp) ) return mi class Body: """ Body: contains the main characteristics of a celestial body. """ def __init__(self, name, color = 'black', Mass = 0, radius = 0, *args, **kwargs): """ Constructor: INPUTS: name: name of the body. ADDITIONAL INPUTS: Mass: mass of the body radius: radius of the body color: color to plot the body mu = gravitational parameter of the body. If it is not given, it is calculated as G*Mass orb: orbit of the body. Orbit is an object. """ self.name = name self.R = radius self.M = Mass self.color = color #if mu it is not given, it is calculated with the mass: self.mu = kwargs.get('mu', self.M * AL_BF.ConstantsBook().G) # Orbit of the body: self.orb = kwargs.get('orbit', 'No information of the orbit') def addOrbit(self, orbit): """ addOrbit: include an orbit to the body INPUTS: orbit: orbit object """ self.orb = orbit ################################################################################ # CREATE ORBIT AND ITS CHARACTERISTICS # Valid for an elliptical orbit. Application of the 2 Body Problem. ################################################################################ class CircularOrbit: """ CircularOrbit: creation of a circular object around a central body. """ def __init__(self, a, CentralBody, *args, **kwargs): """ Constructor: INPUTS: a: semi-major axis of the orbit. Same as the radius of the orbit. CentralBody: central body about which the orbit is performed. ADDITIONAL INPUTS: Body: body object that is orbitting. """ self.a = a self.CentralBody = CentralBody self.Body = kwargs.get('Body', 'Unknown') # Mean motion, period of the orbit self.n = np.sqrt(self.CentralBody.mu / self.a**3) self.T = 2*np.pi / self.n #Review Kepler 2000: not working class BodyOrbit: """ BodyOrbit: creation of an orbit object around a central body. Contains the main characteristics of an ELLIPTICAL orbit. Application of the 2 Body problem. """ def __init__(self, x, typeParam, Body, *args, **kwargs): """ Constructor: INPUTS: x: Two main cases are possible: Keplerian elements as inputs: a: semi-major axis (m) e: eccentricity of the orbit i: inclination of the orbit RAAN: right ascension of the ascending node omega: argument of the periapsis M: mean anomaly units: 'deg' indicates that the angles have to be transformed to radians Cartesian elements: x,y,z,xdot,ydot,zdot: position and velocity at a given time typeParam: 'Keplerian_J2000': x is a matrix with: row 0: Keplerian elements at J2000 row 1: centennial rates of change of those elements row 2: date in Julian centuries 'Keplerian': to use Keplerian parameters as inputs 'Cartesian': to use Cartesian parameters as inputs Body: central Body of the orbit ADDITIONAL INPUTS: unitsI: units of the angles of x: 'rad' or 'deg' """ self.CentralBody = Body ###################################### #### Case 1: Keplerian Elements J2000 + centennial rates ###################################### # Obtain Keplerian elements at a given date (in Julian Centuries) units_input = kwargs.get('unitsI', 'rad') if typeParam == 'Keplerian_J2000': a,e,i,L,varpi,RAAN = x[0,:] + x[1,:]*x[2,0] omega = varpi - RAAN M = L - varpi ###################################### #### Case 1: Keplerian Elements given ###################################### elif typeParam == 'Keplerian': self.a,self.e,self.i,self.RAAN,self.omega,self.M = x if typeParam == 'Keplerian' or typeParam == 'Keplerian_J2000': if units_input == 'deg': #Operations are done in radians [self.i,self.RAAN,self.omega,self.M] = [AL_BF.deg2rad(angle) \ for angle in [self.i,self.RAAN,self.omega,self.M]] #Obtain the eccentric and true anomaly self.theta, self.E, self.M = Kepler(self.M, self.e,'Mean') #Obtain the cartesian coordinates x = self.Kepl2Cart() self.r = x[0:3] self.v = x[3:] self.h = np.cross(self.r, self.v) ###################################### #### Case 3: Cartesian Elements given" ###################################### elif typeParam == 'Cartesian': state = x #in m and m/s self.r = state[0:3] # position vector self.v = state[3:] # velocity vector self.r_mag = np.linalg.norm(self.r) # magnitude of the position vector self.v_mag = np.linalg.norm(self.v) # magnitude of the velocity vector self.h = np.cross(self.r, self.v) self.h_mag = np.linalg.norm(self.h) self.N = np.cross(np.array([0,0,1]),self.h) self.N_mag = np.linalg.norm(self.N) #Keplerian elements #semi-major axis. Negative if e>1: self.a = 1 / (2/self.r_mag-self.v_mag**2/Body.mu) #eccentricity vector: self.e_vec = np.cross(self.v,self.h)/Body.mu - self.r/self.r_mag self.e = np.linalg.norm(self.e_vec) #eccentricity of the orbit self.i = np.arccos(self.h[2]/self.h_mag) #inclination of the orbit N_xy = np.sqrt(self.N[0]**2 + self.N[1]**2) if N_xy == 0.: self.RAAN = 0 else: #right ascension of the ascending node: self.RAAN = np.arctan2(self.N[1]/N_xy , self.N[0]/N_xy) if self.e == 0.0 or self.N_mag == 0.0: self.omega = 0.0 else: #argument of the perihelium: self.omega = np.arccos(np.dot(self.e_vec/self.e , self.N/self.N_mag)) if (np.dot(np.cross(self.N/self.N_mag , self.e_vec),self.h)) <= 0: self.omega = -self.omega if self.r_mag == 0.0 or self.e == 0.0: self.theta = 0.0 else: #true anomaly: self.theta = np.arccos(np.dot(self.r/self.r_mag , self.e_vec/self.e)) if (np.dot(np.cross(self.e_vec,self.r),self.h)) <= 0: self.theta = -self.theta if self.e < 1: #Mean anomaly: self.theta, self.E, self.M = Kepler(self.theta,self.e,'True') else: #Mean anomaly: self.theta, self.E, self.M = Keplerh(self.theta,self.e,'True') else: print('Warning: Specify the type of elements') ###################################### ## More parameters of the orbit ###################################### #Create a vector with all the keplerian elements self.KeplerElem = np.array([self.a,self.e,self.i,self.RAAN,self.omega,self.M]) self.KeplerElem_deg = np.zeros(6) self.KeplerElem_deg[0:2] = [self.a,self.e] for item, angle in enumerate([self.i,self.RAAN,self.omega,self.M]): self.KeplerElem_deg[2+item] = AL_BF.rad2deg(angle) #Mean motion, period of the orbit self.n = np.sqrt(Body.mu/self.a**3) self.T = 2*np.pi * np.sqrt(self.a**3/Body.mu) #Geometry of the elliptic trajectory self.p = self.a * (1-self.e**2) self.rp = self.a * (1-self.e) self.ra = self.a * (1+self.e) self.b = self.a * np.sqrt(1-self.e**2) def Kepl2Cart(self, *args, **kwargs): """ Kepl2Cart: transform from Keplerian elements to cartesian coordinates. INPUTS: ADDITIONAL INPUTS: givenElements: option to input a vector to be transformed. If false, the elements from the class are used. OUTPUTS: [x,y,z,xdot,ydot,zdot]: state of the body given by its position and velocity vectors. """ givenElements = kwargs.get('givenElements', 'False') if type(givenElements) != str: [a,e,i,RAAN,omega,M,theta] = givenElements else: [a,e,i,RAAN,omega,M,theta] = np.array([self.a,self.e,self.i, \ self.RAAN,self.omega,self.M,self.theta]) l1 = np.cos(RAAN)*np.cos(omega) - np.sin(RAAN)*np.sin(omega)*np.cos(i) l2 = -np.cos(RAAN)*np.sin(omega) - np.sin(RAAN)*np.cos(omega)*np.cos(i) m1 = np.sin(RAAN)*np.cos(omega) + np.cos(RAAN)*np.sin(omega)*np.cos(i) m2 = -np.sin(RAAN)*np.sin(omega) + np.cos(RAAN)*np.cos(omega)*np.cos(i) n1 = np.sin(omega)*np.sin(i) n2 = np.cos(omega)*np.sin(i) #magnitude of the angular momentum: H = np.sqrt(self.CentralBody.mu*a*(1-e**2)) #magnitude of the position vector at a given moment: r = a*(1-e*np.cos(self.E)) #Position vector x = l1*r*np.cos(theta) + l2*r*np.sin(theta) y = m1*r*np.cos(theta) + m2*r*np.sin(theta) z = n1*r*np.cos(theta) + n2*r*np.sin(theta) #Velocity vector xdot = self.CentralBody.mu/H * (-l1*np.sin(theta) + l2*(e+np.cos(theta))) ydot = self.CentralBody.mu/H * (-m1*np.sin(theta) + m2*(e+np.cos(theta))) zdot = self.CentralBody.mu/H * (-n1*np.sin(theta) + n2*(e+np.cos(theta))) return [x,y,z,xdot,ydot,zdot] def Propagation(self, t, typeParam, *args, **kwargs): """ Propagation: propagate the mean anomaly M in time. INPUTS: t: time in seconds at which the position wants to be known with respect to the given state in the init typeParam: type fo the elements: "Keplerian", "Cartesian". OUTPUTS: M: new mean anomaly """ self.M += self.n*t # Propagate in time self.M = AL_BF.correctAngle(self.M, 'rad') # Correct for more than 306deg if self.e < 1: self.theta, self.E, self.M = Kepler(self.M, self.e,'Mean') else: self.theta, self.E, self.M = Keplerh(self.M, self.e,'Mean') # self.theta = Kepler(self.M, self.e,'Mean')[0] x = np.array([self.a,self.e,self.i,self.RAAN,self.omega,self.M,self.theta]) if typeParam == 'Keplerian': return x else: #Obtain the cartesian coordinates x = self.Kepl2Cart(givenElements = x) return x def atPeriapsis(self): """ atPeriapsis: find the radius of the periapsis, velocity at periapsis and time since passage through periapsis """ self.rp, self.vp = VisVivaEq(self.CentralBody, self.a, r = self.rp) self.tp = self.M / self.n # time since passage through periapsis # def solveKeplerUniversal(self, Xi, x_add): # [t, alpha] = x_add # self.atPeriapsis() # r0 = self.rp # vr0 = self.vp # t0 = self.tp # f = - np.sqrt(self.CentralBody.mu) * (t + t0) + \ # r0*vr0 / np.sqrt(self.CentralBody.mu) * Xi**2 * Stumpff_C(alpha* Xi**2) +\ # (1 - alpha* r0) * Xi**3 * Stumpff_S( alpha* Xi**2) +\ # r0 * Xi # return f # def PropagationUniversal(self, t, typeParam, *args, **kwargs): # """ # Propagation: propagate the mean anomaly M in time. Valid for ellipses, # hyperbola, parabola # Inputs: # t: time in seconds at which the position wants to be known with # respect to the given state in the init # Outputs: # M: new mean anomaly # """ # # Find value of XI: universal anomaly # alpha = 1/self.a # Xi_0 = np.sqrt(self.CentralBody.mu) * abs(alpha) * t # Xi = spy.fsolve(self.solveKeplerUniversal, Xi_0, args = [t, alpha, ]) def PlotOrbit(self): """ PlotOrbit: plot the relative position of the planets at a given date for each one INPUTS: Body: central Body OUTPUTS: xEl_E: x coordinate of the ellipse that represents the orbit yEl_E: y coordinate of the ellipse that represents the orbit """ # Plot ellipse xEllipse = np.linspace(-self.a,self.a, num = 2500) yPos = np.sqrt(self.b**2*(1-xEllipse**2/self.a**2)) yNeg = -np.sqrt(self.b**2*(1-xEllipse**2/self.a**2)) xEl_E = np.append(xEllipse,xEllipse[::-1]) xEl_E -= self.a*self.e*np.ones(len(xEl_E)) yEl_E = np.append(yPos,yNeg) # # Rotate ellipse # ELL0=np.zeros((len(xEl_E0),3)) #Ellipse coordinates # ELL0[:,0] = xEl_E0 # ELL0[:,1] = yEl_E0 # Q, nan,nan = transforMatrix(x,(x[4]-x[3])*np.pi/180,[0,0,0],[0,0,0]) # ELL = np.dot(ELL0,np.transpose(Q)) # xEl_E = ELL[:,0] # yEl_E = ELL[:,1] fig, ax = plt.subplots(1,1, figsize = (9,8)) # Plot orbit plt.plot(xEl_E,yEl_E,color = 'black',linestyle = '--') # Plot ellipse # Plot line from planet to the Sun: plt.plot([self.r[0],0],[self.r[1],0],color = 'black') plt.plot(self.r[0],self.r[1], marker = "o",markersize = 20, \ color = 'black', alpha = 0.5,label = 'Position') # Plot planet plt.plot(0, 0, Markersize = 695508/15000, color= self.CentralBody.color,\ marker="o") plt.title('2D Trajectory',size = 22) plt.axis("equal") # plt.xticks(np.arange(-3e11, 3e11, 1.0e11)) # plt.yticks(np.arange(-3e11, 3e11, 1.0e11)) plt.xlabel('(m)',size = 25) plt.ylabel('(m)',size = 25) plt.tick_params(axis ='both', which='major', labelsize = 15) plt.tick_params(axis ='both', which='minor', labelsize = 15) text = ax.xaxis.get_offset_text() text.set_size(15) # text = ax.yaxis.get_offset_text() text.set_size(15) # # lgnd = plt.legend(bbox_to_anchor=(0.5, 0), loc='lower left',ncol=2, \ # mode="expand", borderaxespad=0.,fontsize=16) # lgnd.legendHandles[0]._legmarker.set_markersize(20) # plt.savefig("_%i.png"%i,dpi=200,bbox_inches='tight') plt.show() ################################################################################ # STUMPFF FUNCTIONS ################################################################################ def Stumpff_C(z): """ Stumpff_C: Stumpff function C for the propagation with universal variables INPUTS: z: Stumpff variable OUTPUTS: f: value of the function """ if z > 0: f = ( 1 - np.cos(np.sqrt(z)) ) / z elif z == 0: f = 1/2 else: f = ( np.cosh(np.sqrt(-z)) - 1 ) / (-z) return f def Stumpff_S(z): """ Stumpff_S: Stumpff function S for the propagation with universal variables INPUTS: z: Stumpff variable OUTPUTS: f: value of the function """ if z > 0: f = ( np.sqrt(z) - np.sin(np.sqrt(z)) ) / z**(3/2) elif z == 0: f = 1/6 else: f = ( np.sinh(np.sqrt(-z)) - np.sqrt(-z) ) / (-z)**(3/2) return f ################################################################################ # PROPAGATE ALONG ORBIT FG PARAMS ################################################################################ def fgSolveE(E,x): """ fgSolveE: solve Kepler's equation to obtain the Eccentric anomaly INPUTS: E: initial guess of the eccentric anomaly x: arguments to put in the equation x[0]: E0. Initial eccentric anomaly of the spacecraft x[1]: M0. Initial mean nomaly of the spacecraft x[2]: M. Current mean anomaly of the spacecraft x[3]: e. Eccentricity of the orbit x[4]: a. Semi-major axis of the propagation orbit x[5]: SV. State vector of the planet. [x,y,z,vx,vy,vz,m0,ind] x: position in the x axis y: position in the y axis z: position in the z ais vx : velocity in the x axis vy : velocity in the y axis vz : velocity in the z axis m0: mass at that point ind: indicator to know if there is an impulse OUTPUTS: f: function to solve """ [E0,M0,M,e,a,SV,mu] = x r = np.linalg.norm(SV[0:3]) sigma0 = np.dot(SV[0:3],SV[3:6])/np.sqrt(mu) # Value to put in next equation # Modified Kepler's equation: f = E-E0-(1-r/a)*np.sin(E-E0)+sigma0/np.sqrt(a)*(1-np.cos(E-E0))-(M-M0) # for the case in which we are not in perigee return f def fgPropagate(orbit,SV,t): """ fgPropagate: propagate the mean anomaly M in time. INPUTS: param: list of parameters. [a,e,E0,nu0,M0,n] E0: previous eccentric anomaly nu0: previous true anomaly M0: previous mean anomaly n: proper motion SV: state vector at the previous point [x,y,z,vx,vy,vz,m0,ind] x: position in the x axis y: position in the y axis z: position in the z ais vx : velocity in the x axis vy : velocity in the y axis vz : velocity in the z axis t: difference in time from the previous point OUTPUTS: E: new eccentric anomaly M: new mean anomaly """ M = orbit.M + orbit.n * t E = spy.fsolve(fgSolveE, orbit.E, [orbit.E, orbit.M, M, orbit.e, orbit.a, \ SV, orbit.Body.mu]) # Obtain new E E = float(E) return [E,M] def fgSV(orbit,param,t): """ fgSV: obtain new state vector from the previous one and the parameters of the orbit. INPUTS: SV0: state vector at the previous point [x,y,z,vx,vy,vz,m,ind] x: position in the x axis y: position in the y axis z: position in the z ais vx: velocity in the x axis vy: velocity in the y axis vz: velocity in the z axis m: mass at that point ind: indicator to know if there is an impulse param: parameters of the point of the propagation paramF: parametrs of the next point of the propagation a: semi-major axis of the propagation orbit e: eccentricity of the propagation orbit E: new eccentric anomaly nu: new true anomaly M: new mean anomaly n: proper motion t: difference in time from the previous time OUTPUTS: SV: new state vector """ E0 = orbit.E E = param[0] r0 = np.linalg.norm(orbit.r) # f and g coefficients sigma0 = np.dot(orbit.r,orbit.v)/np.sqrt(orbit.Body.mu) f = 1 - orbit.a / r0*(1-np.cos(E-E0)) g = (orbit.a * sigma0 * (1-np.cos(E-E0)) + r0 * np.sqrt(orbit.a) * \ np.sin(E-E0)) / np.sqrt(orbit.Body.mu) #New position SV = np.zeros(6) SV[0:3] = f*orbit.r + g*orbit.v r = np.linalg.norm(SV[0:3]) #f',g' ff = -np.sqrt(orbit.Body.mu * orbit.a) / (r*r0)*(np.sin(E-E0)) gg = 1 - orbit.a / r *(1-np.cos(E-E0)) #New velocity SV[3:6] = ff*orbit.r + gg*orbit.v return SV ################################################################################ # MORE ################################################################################ def VisVivaEq(Body,a,*args,**kwargs): """ VisVivaEq: obtain position from velocity or vice versa with the vis viva or energy equation. INPUTS: Body: body around which the orbit is performed a: semi-major axis of the orbit **kwargs: r: magnitude of the position vector v: magnitude of the velocity vector OUTPUTS: r: magnitude of the position vector v: magnitude of the velocity vector """ r = kwargs.get('r', None) v = kwargs.get('v', None) if r == None and v != None: #v is given r = Body.mu / (Body.mu/(2*a)+v**2/2) elif r != None and v == None: #r is given v = 2*np.sqrt(-Body.mu/(2*a) + Body.mu/r) else: print('Warning: Not enough arguments or too many arguments given') return r,v def KeplerSolve(E0, x): """ Kepler: function to solve Kepler's equation knowing the mean anomaly. To obtain the eccentric anomaly. INPUTS: E0: initial guess of the solution x: vector containing other parameters of the equation: x[0]: Mean anomaly (rad) x[1]: Eccentricity OUTPUTS: F: function to solve (rad) """ #Parametrs of the equation M = x[0] e = x[1] #Equation to solve F = E0-e*np.sin(E0)-M F = AL_BF.correctAngle(F, 'rad') return F def Kepler(angle,e,name): """ Kepler: function to calculate true, eccentric and mean anomaly given one of them and the eccentricity of the orbit. INPUTS: angle: initial angle known. It can be any of the three mentioned e: eccentricity of the orbit (magnitude) name: specify which the initial angle given is: 'Mean': mean anomaly 'True': true anomaly 'Eccentric': eccentric anomaly OUTPUTS: theta: true anomaly E: eccentric anomaly M: mean anomaly """ if name == 'Mean': M = angle E = spy.fsolve(KeplerSolve,M,[M,e]) #Solve Kepler's equation E = E[0] theta = 2*np.arctan(np.sqrt((1+e)/(1-e))*np.tan(E/2)) #Calculate true anomaly # if abs(theta) >= 2*np.pi: #Correction in case is higher than 360 # a = theta//(2*np.pi) # theta = theta-2*np.pi*a return(theta,E,M) elif name == 'Eccentric': E = angle # Calculate true anomaly theta = 2*np.arctan(np.sqrt((1+e)/(1-e))*np.tan(E/2)) M = E-e*np.sin(E) #Kepler's equation return(theta,E,M) elif name == 'True': theta = angle # Calculate eccentric anomaly: E = 2*np.arctan(np.sqrt((1-e)/(1+e))*np.tan(theta/2)) M = E-e*np.sin(E) #Kepler's equation return(theta,E,M) else: print('Warning: Include a valid name for the angle given') def KeplerhSolve(E0, x): """ Kepler: function to solve Kepler's equation knowing the mean anomaly. To obtain the eccentric anomaly. INPUTS: E0: initial guess of the solution x: vector containing other parameters of the equation: x[0]: Mean anomaly (rad) x[1]: Eccentricity OUTPUTS: F: function to solve (rad) """ #Parametrs of the equation M = x[0] e = x[1] #Equation to solve F = e*np.sinh(E0) - E0- M F = AL_BF.correctAngle(F, 'rad') return F def Keplerh(angle, e, name): """ Keplerh: function to calculate true, eccentric and mean anomaly given one of them and the eccentricity of the orbit. For an orbit of e >= 1 INPUTS: angle: initial angle known. It can be any of the three mentioned e: eccentricity of the orbit (magnitude) name: specify which the initial angle given is: 'Mean': mean anomaly 'True': true anomaly 'Eccentric': eccentric anomaly OUTPUTS: theta: true anomaly E: eccentric anomaly M: mean anomaly """ print("Hyperbola") if name == 'Mean': M = angle E = spy.fsolve(KeplerhSolve, M, [M,e]) #Solve Kepler's equation E = E[0] theta = 2*np.arctan( np.sqrt( (e+1) / (e-1) ) * np.tan(E/2) ) return(theta, E, M) elif name == 'Eccentric': E = angle # Calculate true anomaly: theta = 2 * np.arctan( np.sqrt( (e+1) / (e-1) ) * np.tan(E/2) ) M = e * np.sinh(E) - E #Kepler's equation return(theta, E, M) elif name == 'True': theta = angle # Calculate eccentric anomaly: E = 2 * np.arctanh( np.sqrt( (e-1) / (e+1) ) * np.tan(theta/2) ) M = e * np.sinh(E) - E #Kepler's equation return(theta, E, M) else: print('Warning: Include a valid name for the angle given')
veronicasaz/AstrodynamicsScripts
AstroLib_2BP.py
AstroLib_2BP.py
py
26,889
python
en
code
1
github-code
6
42860322967
# # # Font Lato https://fonts.google.com/specimen/Lato # https://opengameart.org/content/4-chiptunes-adventure # # scanlines less mem ## https://www.reddit.com/r/pygame/comments/6yk6zk/least_memory_intensive_way_to_implement_scanlines/ # Not used: # Audio Voices by MadamVicious (https://freesound.org/people/MadamVicious/sounds/238641) # # @todo turn this into "kawaii clock" game for github? # @todo refactor 'em all ... # @todo spritesheet # @todo create the wordle game -> no words, winning/losing # @todo scope of the game -> intro/menu/options/languages? # # # OMG refactor me # Particles List-> got better :) # ✔ Lock -> Class # Typing sounds? # easingFunc # naming conventions # moving in update, for exp. "scrollX" # ✔ handleInput # ✔ fix assets colors -> indicator # ✔ Window Icon # ✔ Delete/Replace Letters # init methode # ✔ gameOver -> Transition back to the startscreen # check "glitch" performance on raspi # intro with "fake" loading screen or fade in effect for the main menu # compare diff screens to find design errors - like missing shadows # create a short docu # - show the "drawn" hierarchy # clean up the assets and upload them # escape key back to menu and on the second press exit the game # turn debug on/off -> log printing # create /utils/ folder for texture atlas and effect editor # juicify the effects/animations -> intro? "special effects" on the first start? # # # 'BUGS' # ✔ word to short -> index out of bounds # ✔ Lock on the title screen is not bouncing after winning # ✔ overlapping background # multiple letters are displayed wrong -> "lllll" four orange and one green -> correct -> one green # # # Unclear: # Easings -why "wrong" values # # # # import itertools import random import pygame from easing_functions import easing from background import Background from gamestate_manager import GamestateManager from letter import Letter from lock import Lock from part_confetti import create_confetti from particle import Particle from phrase import Phrase from screen_game import ScreenGame from screen_menu import ScreenMenu from screen_over import ScreenOver from screen_transition import ScreenTransitions from settings import Settings from sky import Sky from scanline import Scanline from glitch import Glitch from dataclasses import dataclass @dataclass class WordleGame: # init # Setup Pygame / Display pygame.init() manager = GamestateManager() settings = Settings() pygame.display.set_caption(settings.str_title) particles_new = [] particles_confetti = [] # surfaceOrg = pygame.display.set_mode((927, 750), pygame.HWSURFACE) surfaceOrg = pygame.display.set_mode((settings.screen_width, settings.screen_height), pygame.HWSURFACE) lock = Lock() pygame_icon = pygame.image.load('tex/icon.png') pygame.display.set_icon(pygame_icon) # surfaceOrg = pygame.display.set_mode((0,0), pygame.FULLSCREEN) surfaceOrg.fill(color=(255, 66, 112)) surface = surfaceOrg.copy() surface.fill(color=(255, 66, 112)) TexBg = pygame.image.load('tex/tiles/bg_fields.png').convert_alpha() TexBgSky = pygame.image.load('tex/bg_sky.png').convert_alpha() TexBgScroll = pygame.image.load('tex/bg2.png').convert_alpha() TexLock2 = pygame.image.load('tex/lock/lock2.png').convert_alpha() TexLockShine = pygame.image.load('tex/tiles/lock_shine.png').convert_alpha() TexLockShine2 = pygame.image.load('tex/tiles/lock_shine_2.png').convert_alpha() TexScanline = pygame.image.load('tex/scanline.png').convert_alpha() TexScanline2 = pygame.image.load('tex/scanline2.png').convert_alpha() TexScanlineOverlaySkull = pygame.image.load('tex/scanline_overlay_skull.png').convert_alpha() TexStartscreen = pygame.image.load('tex/startscreen.png').convert_alpha() TexStartscreenLock = pygame.image.load('tex/lock/startscreen_lock.png').convert_alpha() TexWordTileYellow = pygame.image.load('tex/tiles/tile_yellow.png').convert_alpha() TexWordTileGreen = pygame.image.load('tex/tiles/tile_green.png').convert_alpha() TexWordTileGrey = pygame.image.load('tex/tiles/tile_grey.png').convert_alpha() TexWordTileGrey2 = pygame.image.load('tex/tiles/tile_grey2.png').convert_alpha() TexWordTileDefault = pygame.image.load('tex/tiles/tile_default.png').convert_alpha() TexTileIndicatorGreen = pygame.image.load('tex/tiles/indicator_green.png').convert_alpha() TexTileIndicatorGrey = pygame.image.load('tex/tiles/indicator_grey.png').convert_alpha() TexTileIndicatorYellow = pygame.image.load('tex/tiles/indicator_yellow.png').convert_alpha() TexTileIndicatorDefault = pygame.image.load('tex/tiles/indicator_default.png').convert_alpha() TexTileFlash1 = pygame.image.load('tex/tiles/tile_flash_1.png').convert_alpha() background = Background(TexBgScroll) skies = Sky(TexBgSky) phrase = Phrase(settings.str_title_waving) screen_menu = ScreenMenu(TexStartscreen, TexStartscreenLock) # screen_game = ScreenGame() screen_over = ScreenOver() screen_transition = ScreenTransitions() dt=0 # SOUNDS sound_enabled = False if sound_enabled: snd_hit_1 = pygame.mixer.Sound('../snd/1.mp3') snd_hit_2 = pygame.mixer.Sound('../snd/2.mp3') snd_hit_3 = pygame.mixer.Sound('../snd/3.mp3') snd_hit_4 = pygame.mixer.Sound('../snd/4.mp3') snd_hit_5 = pygame.mixer.Sound('../snd/5.mp3') hit_sounds = [snd_hit_1, snd_hit_2, snd_hit_3, snd_hit_4, snd_hit_5] def gen_smoke(self, x, y): self.particles_new.extend(Particle.generate_smoke_list_white( x, y, 60, color="#fafafa")) def show_hit_screen(self): self.settings.offsetShake = self.shake() self.settings.showScanlines = not self.settings.showScanlines self.settings.scanlineTimer = 10 self.settings.scanlineEffectTimer = 450 self.settings.glitch_enabled = True def shoot_confetti(self): self.particles_confetti.extend(create_confetti()) def show_lose_screen(self): print("show lose") self.settings.init_over_screen() self.screen_over = ScreenOver(4) self.manager.set_gamestate(4) def show_win_screen(self): self.settings.hero_replacement_showIntro = True self.lock.bar_popup = True self.settings.won = True self.settings.win_timer = 1900 # confetti # shoot_confetti() # self.settings.show_blend_screen = True if self.lock.bar_popup: self.lock.eyes_flash_timer = 150 # # Seperate the gameLogic into its own class # def checkGuess(self, current_guess): print(f"guesses_count: {self.settings.guesses_count}") print(f"currentPosition: {self.settings.currentPosition}") tmpLen = len(self.settings.guesses) print(f"tmpLen: {tmpLen}") self.settings.checkedGuess = True GOAL = self.settings.goal_word # useless variable :) if self.sound_enabled: self.snd_hit_2.play() check_won = True for i in range(5): # lock the letter current_guess[i].locked = True # gen smoke self.gen_smoke(current_guess[i].x, current_guess[i].y) lower = current_guess[i].key if current_guess[i].key in GOAL: if lower == GOAL[i]: current_guess[i].flash = i * -1 current_guess[i].flash_timer = 0 current_guess[i].tile = self.TexWordTileGreen self.settings.indicator[lower] = self.TexTileIndicatorGreen else: current_guess[i].tile = self.TexWordTileYellow self.settings.indicator[lower] = self.TexTileIndicatorYellow check_won = False else: current_guess[i].fontcolor = "#ebe8da" current_guess[i].tile = self.TexWordTileGrey self.settings.indicator[lower] = self.TexTileIndicatorGrey check_won = False if check_won: self.show_win_screen() else: if self.settings.guesses_count >= 3: self.show_lose_screen() self.show_hit_screen() self.settings.glitch_flip = not self.settings.glitch_flip self.settings.currentPosition = 0 self.settings.guesses_count += 1 # LINE += 1 # https://stackoverflow.com/questions/23633339/pygame-shaking-window-when-loosing-lifes # slightly modified # def shake(self, hori=False, times=5, power=10): s = -1 for _ in range(0, times): for x in range(power, 0, 2): if hori: yield x * s, x * s else: yield 0, x * s for x in range(0, power, 2): if hori: yield x * s, x * s else: yield 0, x * s s *= -1 while True: yield 0, 0 def change_indicators(self, guess): self.settings.usedLetters.append(guess) def init_indicators(self, settings): for i in range(3): for let in settings.alphabet[i]: settings.indicator.update({let: self.TexTileIndicatorDefault}) scanline = Scanline(settings.screen_width, settings.screen_height) glitch = Glitch(settings.screen_width, settings.screen_height, TexScanlineOverlaySkull) def add_new_letter(self, key_pressed): x = 465 + (self.settings.currentPosition * 67) y = 47 + (self.settings.guesses_count * 79) letter = Letter(key_pressed, (x, y), self.TexWordTileDefault) self.settings.guesses[self.settings.guesses_count].append(letter) self.settings.currentPosition += 1 def add_new_letter_effects(self): self.settings.offsetShake = self.shake() self.lock.eyes_blink_timer = 60 self.lock.flash = True self.lock.eyes_flash_timer = 20 x = 455 + (self.settings.currentPosition * 67) y = 100 + (self.settings.guesses_count * 80) self.particles_new.extend(Particle.generate_smoke_list( x, y, 80, )) def handle_input(self, events): for event in events: if event.type == pygame.KEYDOWN: if self.manager.gamestate == 1: if self.sound_enabled: # snd_typing.play() pass key_pressed = event.unicode.upper() if key_pressed in self.settings.alphabet_sorted: if len(self.settings.guesses[self.settings.guesses_count]) <= 4: self.add_new_letter(key_pressed) self.add_new_letter_effects() elif event.key == pygame.K_BACKSPACE: print("Please dont crash") if len(self.settings.guesses[self.settings.guesses_count]) >= 1: print(len(self.settings.guesses[self.settings.guesses_count])) self.settings.guesses[self.settings.guesses_count].pop() self.settings.currentPosition -= 1 elif event.key == pygame.K_RETURN: self.settings.offsetShake = self.shake(power=8, times=5) if len(self.settings.guesses[self.settings.guesses_count]) == 5: print("over 5!") if len(self.settings.guesses[self.settings.guesses_count]) == 5: self.checkGuess(self.settings.guesses[self.settings.guesses_count]) elif event.key == pygame.K_ESCAPE: # running = False self.manager.set_gamestate(0) self.screen_menu = ScreenMenu(self.TexStartscreen, self.TexStartscreenLock) else: if event.key == pygame.K_SPACE: print("Space") # shoot_confetti() self.manager.set_gamestate(2) screen_game = ScreenGame() # if sound_enabled: # pygame.mixer.music.load('music/stage.mp3') # pygame.mixer.music.play(-1, 0.0) elif event.key == pygame.K_ESCAPE: self.settings.game_is_running = False # gamestate_mgr.gamestate = 0 if event.type == pygame.QUIT: self.settings.game_is_running = False if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos print(f"Mouse x: {x} y:{y}") def draw_letters(self): for guess in self.settings.guesses: for letter in guess: letter.update(self.dt, self.settings.easing_frame) letter.draw(self.surface, self.settings, self.TexTileFlash1) def draw_indicators(self): # own class ! y_offset = 0 if self.settings.hero_replacement_showIntro: self.settings.hero_replacement_y_offset_indicator += self.dt * 2 y_offset = self.settings.hero_replacement_y_offset_indicator offset = 0 self.settings.indication_easing_amount = self.settings.easingFunction(self.settings.easing_frame * 0.01) self.settings.indication_easing_amount = min(1, self.settings.indication_easing_amount) self.settings.indication_y_bounce = ( self.settings.indication_easing_end_pos - self.settings.indication_easing_start_pos) * self.settings.indication_easing_amount for i in range(3): spacer = 0 y_offset += 5 if i == 1: offset = 23 elif i == 2: offset = 73 for letter in self.settings.alphabet[i]: x = 222 + offset + (spacer * 49) y = 1000 + y_offset + (i * 50) # + 545 spacer += 1 tempRect = (x, y + self.settings.indication_y_bounce, 42, 42) if not self.settings.indicator[letter] == self.TexTileIndicatorDefault: text_surface = self.settings.font_small.render(letter, True, "#ebe8da") else: text_surface = self.settings.font_small.render(letter, True, "#304059") textRect = text_surface.get_rect(center=(x + 21, self.settings.indication_y_bounce + y + 18)) self.surface.blit(self.settings.indicator[letter], tempRect) self.surface.blit(text_surface, textRect) def update_particles(self, dt): for part in itertools.chain(self.particles_new, self.particles_confetti): if part.isActive: part.update(dt) self.remove_particles() # how to refactor me? itertools chain? def remove_particles(self): for part in self.particles_new: if not part.isActive: self.particles_new.remove(part) for part in self.particles_confetti: if not part.isActive: self.particles_confetti.remove(part) # move me into screen_game def update_scanlines(self, dt): if self.settings.showScanlines: self.settings.scanlineTimer -= dt / 2 self.settings.scanlineEffectTimer -= dt / 2 if self.settings.scanlineEffectTimer < 0: self.settings.showScanlines = False self.settings.glitch_enabled = False if self.settings.scanlineTimer < 0: self.settings.scanlinesFlash = not self.settings.scanlinesFlash self.settings.scanlineTimer = 10 def update_movement(self, dt): self.background.update(dt) self.skies.update(dt) self.update_particles(dt) self.update_scanlines(dt) self.screen_transition.update(dt, self.settings, self.manager.gamestate) self.screen_menu.update(dt, self.manager.gamestate) if self.settings.won: # rename me -> wait for screen_to_end ? self.settings.win_timer -= dt self.settings.show_blend_screen = True if self.screen_transition.radius > 1050: self.settings.won = False # reset 'em all self.lock = Lock() self.phrase.x_pos = 150 self.screen_menu = ScreenMenu(self.TexStartscreen, self.TexStartscreenLock) self.manager.set_gamestate(3) self.screen_over = ScreenOver(3) self.particles_confetti.extend(create_confetti()) if self.settings.currentPosition <= 4: self.lock.update_lock_shine_pos(self.settings.currentPosition * 67, self.settings.guesses_count * 80) def draw_background(self): self.background.draw(self.surface) self.skies.draw(self.surface) self.surface.blit(self.scanline.surface, (0, 0)) def draw_gamefield(self): self.surface.blit(self.TexBg, (self.settings.gamefield_pos_x, 0)) def draw_particles(self): for part in itertools.chain(self.particles_new, self.particles_confetti): if part.isActive: part.draw(self.surface) def draw_scanlines(self): if self.settings.showScanlines: if self.settings.scanlinesFlash: self.surface.blit(self.TexScanline, (0, 0)) else: self.surface.blit(self.TexScanline2, (0, 0)) def update_easing_game_screen(self): # mixture of lock & gamefield easing :( easing_amount = self.settings.easingFunction(self.settings.easing_frame * 0.01) easing_amount = min(1, easing_amount) self.settings.easing_frame += 1 # end - start pos gamefield_easing_x = (930 - 0) * easing_amount self.settings.gamefield_pos_x = 930 - gamefield_easing_x def show_highlight_current_field(self): if self.settings.currentPosition <= 4: if self.lock.shineTime and self.settings.gamefield_pos_x == 0: self.surface.blit(self.TexLockShine, (self.lock.TexLockShine_x, self.lock.TexLockShine_y)) def load_sounds(self): if self.sound_enabled: snd_hit_1 = pygame.mixer.Sound('sounds/hit_1.mp3') snd_hit_2 = pygame.mixer.Sound('sounds/hit_2.mp3') snd_typing = pygame.mixer.Sound('sounds/typing.mp3') pygame.mixer.music.load('music/menu.mp3') pygame.mixer.music.play(-1, 0.0) def draw_screen_game(self): self.draw_gamefield() # confetti behind the hero banner for con in self.particles_confetti: con.draw(self.surface) self.lock.draw(self.surface, self.lock.bar_popup_offset) self.draw_indicators() # optimize me self.draw_letters() def draw_screen_win_lose(self, dt): self.screen_over.update(dt) self.settings.flip_update(dt) self.screen_over.draw(self.surface, self.settings.blink, self.settings.flip) if self.manager.gamestate == 4: # don't like the way the offsetting is handled self.surface.blit(self.settings.lose_surface, (540, 554 + (self.screen_over.y * -1))) for con in self.particles_confetti: con.draw(self.surface) def create_new_game(self): self.init_indicators(self.settings) self.manager.new_game(self.settings) # refactor me! def reset_game(self): # called when ever menu is loaded, resets all objects self.manager.set_gamestate(0) self.lock = Lock() self.settings.hero_replacement_showIntro = False self.settings.hero_replacement_y_offset_indicator = 0 self.settings.gamefield_pos_x = 930 # gamefield reset to spawn outside of the viewport self.settings.easing_frame = 0 self.screen_menu = ScreenMenu(self.TexStartscreen, self.TexStartscreenLock) def start_game(self): self.init_indicators(self.settings) print("starting game") while self.settings.game_is_running: dt = self.settings.clock.tick(60) # print(clock.get_fps()) # START UPDATE self.update_movement(dt) if self.manager.gamestate == 1: self.update_easing_game_screen() self.lock.update(dt) elif self.manager.gamestate == 2: if self.screen_menu.startscreen_y_lock < -1000: self.create_new_game() # START DRAWING self.draw_background() if self.manager.gamestate == 1: self.draw_screen_game() self.show_highlight_current_field() elif self.manager.gamestate == 3 or self.manager.gamestate == 4: self.draw_screen_win_lose(dt) if not self.screen_over.change_to_next_screen: self.reset_game() else: # if gamestate is menu or transition self.screen_menu.draw(self.surface) self.phrase.draw(self.surface, self.screen_menu.startscreen_y, self.settings) self.draw_particles() self.draw_scanlines() self.surfaceOrg.blit(self.surface, next(self.settings.offsetShake)) self.glitch.draw(self.surfaceOrg, self.settings.glitch_enabled, self.settings.glitch_flip) self.screen_transition.draw(self.surfaceOrg, self.settings) pygame.display.update() self.handle_input(pygame.event.get()) pygame.quit() print("DONE") # easy todo # the colors - correct names -> put them in inkscape on the color scheme # next try # global are killing it if __name__ == '__main__': wordle = WordleGame() wordle.start_game()
Sprachmensch/wordle_clone
wordle.py
wordle.py
py
22,197
python
en
code
0
github-code
6
30500996966
# ---------------------------------J.A.R.V.I.S.---------------------------------- import datetime import pyttsx3 import speech_recognition as sr import __name__ import comtypes.client # ----------------------------------------------------------------------------- engine = pyttsx3.init("sapi5") voices = engine.getProperty("voices") engine.setProperty('voice', voices[0].id) def speak(audio): """This function is used to speak the text""" engine.say(audio) engine.runAndWait() def wishMe(): """This function is used to wish me """ hour = int(datetime.datetime.now().hour) if hour >= 0 and hour < 12: speak('Good Morning!') elif hour >= 12 and hour < 18: speak('Good Afternoon!') else: speak('Good Evening!') speak("I am JARVIS Sir. Please tell me how may I help you") def takeCommand(): """This function in used to take microphone input fron the user and return string""" r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing...") query = r.recognize_google(audio, language='en-in') print(f"User said: {query}\n") except Exception: # print(e) print("Say that again please...") return "None" return query if __name__ != '__main__': pass else: wishMe() query = takeCommand().lower()
ArcTix-09/codes
python/J.A.R.V.I.S..py
J.A.R.V.I.S..py
py
1,509
python
en
code
1
github-code
6
8328914063
from DataInit import * from AuxiliaryFunctions import * # Initialize the map of game. listOfCountries, NACountries, SACountries, CACountries, EUCountries, AFRCountries, ASIACountries, OCECountries = initCountryStruct() # Initialize the list of possible colors. listOfColors = ["Green", "Yellow", "Blue", "White", "Black", "Red"] # Initialize an empty list for the players listOfPlayers = [] # Initiliaze the modifiers snow = False tailwind = False crisis = False extra_reinforcements = False open_borders = False closed_borders = False rest = False globalSituations = [snow, tailwind, crisis, extra_reinforcements, open_borders, closed_borders, rest] # Let's ask how many players are going to play while True: numberOfPlayers = int(input("How many players are going to play? ")) if numberOfPlayers > 6: print("Too many players") else: break # Let's ask how many BOTS are going to play while True: numberOfBots = int(input("How many BOTS do you want to add to the game? ")) if numberOfBots > 6 - numberOfPlayers: print("Too many BOTS") else: break # Calculate how many countries each player start with amountOfInitialCountries = int(len(listOfCountries) / (numberOfPlayers + numberOfBots)) amountOfExtraCountries = len(listOfCountries) % (numberOfPlayers + numberOfBots) print("Each player will start with {} countries".format(amountOfInitialCountries)) for i in range(numberOfPlayers): name = input("What is the name of player {}? ".format(i + 1)) while True: color = input("What color do you want to use? ") if color not in listOfColors: print("Wrong color") else: break listOfColors.remove(color) player = Player(name, color) print("Which countries are you starting with? ") initPlayerCountries(player, amountOfInitialCountries, listOfCountries) # Now, let's setup the bots for i in range(numberOfBots): name = "BOT_{}".format(i) color = listOfColors[0] listOfColors.remove(listOfColors[0]) bot = Player(name, color) print("Which countries is BOT_{} starting with?".format(i)) initPlayerCountries(bot, amountOfInitialCountries, listOfCountries) bot.convertToBOT() listOfPlayers.append(bot) # Raffle the extra countries. if amountOfExtraCountries != 0: raffleExtraCountries(listOfCountries, amountOfExtraCountries, listOfPlayers) # Now we define each player mission selectMission(listOfPlayers) # Establish the first turn order of players firstTurn(listOfPlayers) sorted(listOfPlayers, key=lambda player_turn: player.turn) # First turn of reinforcements for p in listOfPlayers: reinforceCountries(p, 8) for p in listOfPlayers: reinforceCountries(p, 4) # Begin the game while True: pickSituationCard(globalSituations) for p in listOfPlayers: if not p.human: i = 0 # TODO: Develop BOT Intelligence else: conquered = attackPhase(p, listOfCountries) regroupPhase(p, listOfCountries) if conquered: withdrawCard(p, listOfCountries) nextTurn(listOfPlayers)
MacMullen/TegBOT
main.py
main.py
py
3,249
python
en
code
0
github-code
6
20921339256
from clustering_algorithms.spectral_clustering import * from clustering_algorithms.louvain import * from clustering_algorithms.paris import * from dendrogram_manager.homogeneous_cut_slicer import * from dendrogram_manager.heterogeneous_cut_slicer import * from dendrogram_manager.distance_slicer import * from experiments.flat_clustering_experiments_manager import * SAVE_PLOTS = True LOAD_RESULTS = True SAVE_RESULTS = True directory_results = "/home/sharp/Documents/Graphs/Graph_Clustering/Results/" results_file_name = "ppm" n_samples = 10 # List of tested algorihtms: # - Spectral clustering # - Louvain # - Paris + homogenegeous cut # - Paris + heterogeneous cut # - Paris + distance cut + Louvain # - Paris + distance cut + Louvain + spectral def paris_homogeneous(G): D = paris(G) best_cut, best_score = best_homogeneous_cut(D) clusters = clustering_from_homogeneous_cut(D, best_cut) return clusters def paris_heterogeneous(G): D = paris(G) best_cut, best_score = best_heterogeneous_cut(D) clusters = clustering_from_heterogeneous_cut(D, best_cut) return clusters def paris_louvain(G): D = paris(G) best_dist, best_score = best_distance(D) clusters = louvain(G, 1/float(best_dist)) return clusters def paris_louvain_spectral_clustering(G): n_clusters = len(paris_louvain(G)) clusters = spectral_clustering(G, n_clusters=n_clusters) return clusters algorithms = [('Spectral Clustering - (25)', lambda G: spectral_clustering(G, n_clusters=25)), ('Spectral Clustering - (50)', lambda G: spectral_clustering(G, n_clusters=50)), ('Spectral Clustering - (75)', lambda G: spectral_clustering(G, n_clusters=75)), ('Louvain', louvain), ('Paris+homogeneous cut', paris_homogeneous), ('Paris+heterogeneous cut', paris_heterogeneous), ('Paris+Louvain', paris_louvain), ('Paris+Louvain+Spectral', paris_louvain_spectral_clustering)] # print('Experiment: number of blocks') # make_n_blocks_experiment(algorithms, range_n_blocks=range(10, 101, 10), block_size=10, d_in=5., d_out=1., n_samples=10, score=lambda true, pred: AMI(true, pred), # SAVE_PLOTS=SAVE_PLOTS, LOAD_RESULTS=LOAD_RESULTS, SAVE_RESULTS=SAVE_RESULTS, directory_results=directory_results, results_file_name=results_file_name) # # # print('Experiment: internal/external degree') # make_degree_in_out_experiment(algorithms, d_in=5., range_d_out=np.linspace(1, 20, num=10), n_blocks=50, block_size=10, n_samples=10, score=lambda true, pred: AMI(true, pred), # SAVE_PLOTS=SAVE_PLOTS, LOAD_RESULTS=LOAD_RESULTS, SAVE_RESULTS=SAVE_RESULTS, directory_results=directory_results, results_file_name=results_file_name) # # print('Experiment: block size heterogeneity') # make_block_size_het_experiment(algorithms, range_param=np.linspace(1., 3., num=10), range_block_size=range(10, 100), n_blocks=50, p_in=.5, p_out=.01, n_samples=10, score=lambda true, pred: AMI(true, pred), # SAVE_PLOTS=SAVE_PLOTS, LOAD_RESULTS=LOAD_RESULTS, SAVE_RESULTS=SAVE_RESULTS, directory_results=directory_results, results_file_name=results_file_name) # # print('Experiment: block size ratio') # make_block_size_ratio_experiment(algorithms, range_ratio=range(1, 11), big_block_size=100, graph_size=600, p_in=.5, p_out=.01, n_samples=10, score=lambda true, pred: AMI(true, pred), # SAVE_PLOTS=SAVE_PLOTS, LOAD_RESULTS=LOAD_RESULTS, SAVE_RESULTS=SAVE_RESULTS, directory_results=directory_results, results_file_name=results_file_name) print('Experiment: size of blocks') make_block_size_experiment(algorithms, range_block_size=range(10, 101, 10), n_blocks=50, d_in=5., d_out=1., n_samples=10, score=lambda true, pred: AMI(true, pred), SAVE_PLOTS=SAVE_PLOTS, LOAD_RESULTS=LOAD_RESULTS, SAVE_RESULTS=SAVE_RESULTS, directory_results=directory_results, results_file_name=results_file_name)
sharpenb/Multi-Scale-Modularity-Graph-Clustering
Scripts/ppm_experiments.py
ppm_experiments.py
py
4,027
python
en
code
2
github-code
6
35903985700
def carga_numeros(n): total=int(0) lista=list() porcentaje=int(0) ultimo_digito=int(0) n_menor=int(0) menores_7=str("Si") while n!=0: total+=1 if n%2==0: porcentaje+=1 # a) Determinar el porcentaje que cantidad de números pares representa en la cantidad total de números ingresados. if n%10==4 or n%10==5: ultimo_digito+=1 # b) Determinar cuántos de los números ingresados tenían su último dígito igual a 4 o igual a 5. if n%3==0: if total==1 or n<n_menor: n_menor=n # c) Determinar el menor de los números ingresados que sean divisibles por 3. lista.append(int(n)) n=int(input("Introduzca otro numero: ")) for num in lista: #Determinar si la secuencia estaba formada sólo por números menores de 7 if num>7: menores_7="No" porcentaje= (porcentaje*100)/total #determino el procentaje #muetro resultados por pantalla print(f"El porcentaje de numeros pares sobre los {total} numeros ingresados es de {round(porcentaje, 2)}%.") print(f"La cantidad de números ingresados que tenían su último dígito igual a 4 o igual a 5 es de {ultimo_digito}.") print(f"El menor numero divisible por 3 ingresado es {n_menor}") print(f"La secuencia estaba formada solo por numeros menores de 7? {menores_7}") carga_numeros(int(input("Introduzca un numero (si introduce 0, se cancela la carga de numeros): ")))
UrielMaceri/Python-Principiante
guia 5/ejercicio2.py
ejercicio2.py
py
1,458
python
es
code
0
github-code
6
14365099168
# -*- coding: utf-8 -*- """ Created on Sat Oct 17 20:55:15 2020 @author: Emmanuel """ def unique(list1): # intilize a null list unique_list = [] # traverse for all elements for x in list1: # check if exists in unique_list or not if x not in unique_list: unique_list.append(x) # print list for x in unique_list: print (x) nombrearchivo = r'C:\Temp\dtsxsql\total.sql' contenido=[] with open(nombrearchivo) as fin: contenido = [ linea.strip().split(' ') for linea in fin ] Local = [] for r in contenido: for x in r : Local.append(x) unique(Local)
avefenix798/Ejemplos
Buscar Palabra en Query.py
Buscar Palabra en Query.py
py
677
python
en
code
0
github-code
6
37686877312
# declare dictionary banner = {} # fill dictionary banner['os'] = 'Ubuntu Server 13.04' banner['server'] = 'ProFTPd 1.3.4' banner['up'] = 315.5 banner[200] = 'OK' print(banner) # iterate through dictionary for key, value in banner.items(): print(key, value) # delete item based on key del banner['up'] print(banner)
studiawan/network-programming
bab01/dictionary.py
dictionary.py
py
327
python
en
code
10
github-code
6
19528126460
# coding=utf-8 from __future__ import division from design.MainData import MainData from canvas import * from algorithm import * from PyQt5.QtCore import Qt from PyQt5.QtGui import (QIcon, QFont) from PyQt5.QtWidgets import (qApp, QAction, QComboBox, QDesktopWidget, QFileDialog, QGridLayout, QInputDialog, QRadioButton, QLabel, QLCDNumber, QMainWindow, QMessageBox, QPushButton, QSpinBox, QTableWidget, QTableWidgetItem, QTabWidget, QTextEdit, QToolTip, QWidget) # noinspection PyNonAsciiChar class App(QMainWindow, MainData): """ @ """ # noinspection PyArgumentList,PyMissingConstructor def __init__(self): # noinspection PyCompatibility QMainWindow.__init__(self) # noinspection PyCallByClass,PyTypeChecker QToolTip.setFont(QFont('SansSerif', 10)) self.setGeometry(100, 100, 900, 550) qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) self.setWindowTitle('MathDemo') self.setWindowIcon(QIcon('python.png')) self.setWindowFlags(Qt.WindowStaysOnTopHint) self.actionLoad() self.menuBarLoad() ############################################# # set current image that you are operating. # ############################################# self.currentImage = "" self.rainImage() self.statusBar().showMessage('Ready') self.show() def actionLoad(self): """ set MainData.action """ self.action["showOpenDialog"] = QAction('Open File', self) self.action["showOpenDialog"].setIcon(QIcon('open.png')) self.action["showOpenDialog"].setShortcut('Ctrl+O') self.action["showOpenDialog"].setStatusTip('Open File') self.action["showOpenDialog"].triggered.connect(self.showOpenDialog) self.action["qApp.quit"] = QAction('Exit application', self) self.action["qApp.quit"].setIcon(QIcon('exit.jpg')) self.action["qApp.quit"].setShortcut('Ctrl+Q') self.action["qApp.quit"].setStatusTip('Exit application') self.action["qApp.quit"].triggered.connect(qApp.quit) self.action["orthogonalTableImage"] = QAction('Orthogonal Table', self) self.action["orthogonalTableImage"].setIcon(QIcon('numpy_logo.jpg')) self.action["orthogonalTableImage"].setShortcut('Ctrl+T') self.action["orthogonalTableImage"].setStatusTip('Orthogonal Table') self.action["orthogonalTableImage"].triggered.connect(self.orthogonalTableImage) self.action["convexHullImage"] = QAction('Convex Hull', self) self.action["convexHullImage"].setIcon(QIcon('numpy_logo.jpg')) self.action["convexHullImage"].setShortcut('Ctrl+C') self.action["convexHullImage"].setStatusTip('Convex Hull') self.action["convexHullImage"].triggered.connect(self.convexHullImage) self.action["gravitationalSystemImage"] = QAction('Gravitational System', self) self.action["gravitationalSystemImage"].setIcon(QIcon('scipy_logo.jpg')) self.action["gravitationalSystemImage"].setShortcut('Ctrl+G') self.action["gravitationalSystemImage"].setStatusTip('Gravitational System') self.action["gravitationalSystemImage"].triggered.connect(self.gravitationalSystemImage) self.action["analyticFunctionImage"] = QAction('Analytic Function', self) self.action["analyticFunctionImage"].setIcon(QIcon('numpy_logo.jpg')) self.action["analyticFunctionImage"].setShortcut('Ctrl+A') self.action["analyticFunctionImage"].setStatusTip('Analytic Function') self.action["analyticFunctionImage"].triggered.connect(self.analyticFunctionImage) self.action["sourceCodeImage"] = QAction('Source Code', self) self.action["sourceCodeImage"].setShortcut('F2') self.action["sourceCodeImage"].setStatusTip('Source Code') self.action["sourceCodeImage"].triggered.connect(self.sourceCodeImage) def menuBarLoad(self): """ set MainWindow.menuBar """ self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(self.action["showOpenDialog"]) fileMenu.addAction(self.action["qApp.quit"]) statisticsMenu = menubar.addMenu('&Statistics') statisticsMenu.addAction(self.action["orthogonalTableImage"]) statisticsMenu = menubar.addMenu('&Geometry') statisticsMenu.addAction(self.action["convexHullImage"]) statisticsMenu = menubar.addMenu('&Ode') statisticsMenu.addAction(self.action["gravitationalSystemImage"]) statisticsMenu = menubar.addMenu('&Complex') statisticsMenu.addAction(self.action["analyticFunctionImage"]) statisticsMenu = menubar.addMenu('&Help') statisticsMenu.addAction(self.action["sourceCodeImage"]) def controlLayout(self, layout=None, name=None, var=None, position=None, signal=None): """ control layout :param layout: GridLayout = QGridLayout() :param name: name of control, name is a string :param var: var is a dict :param position: position is a list with 4 numeric :param signal: signal function """ if name == "QLabel": # var = {"text": [string]} for j in range(0, len(position)): self.control[name].append(QLabel(var["text"][j])) self.control[name][-1].setAlignment(Qt.AlignCenter) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) if name == "QTabWidget": # var = {"text": [[string]], "widget": [[PyQt5.QtWidgets.QWidget]]} for j in range(0, len(position)): self.control[name].append(QTabWidget()) for k in range(0, len(var["text"][j])): self.control[name][-1].addTab(var["widget"][j][k], self.tr(var["text"][j][k])) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) if name == "QPushButton": # var = {"text": [string]} for j in range(0, len(position)): self.control[name].append(QPushButton(var["text"][j])) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) if signal is not None: self.control[name][-1].clicked.connect(signal) if name == "QTextEdit": # var = {"text": [[string]]} for j in range(0, len(position)): self.control[name].append(QTextEdit()) if len(var["text"]) != 0: if len(var["text"][j]) != 0: for line in var["text"][j]: self.control[name][-1].append(line) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) if name == "QRadioButton": # var = {"text": [string], "isChecked": [bool]} for j in range(0, len(position)): self.control[name].append(QRadioButton(var["text"][j])) self.control[name][-1].setChecked(var["isChecked"][j]) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) if signal is not None: self.control[name][-1].clicked.connect(signal) if name == "QComboBox": # var = {"itemText": [[string]], "currentIndex": [int]} for j in range(0, len(position)): self.control[name].append(QComboBox()) self.control[name][-1].addItems(var["itemText"][j]) if len(var["currentIndex"]) != 0: self.control[name][-1].setCurrentIndex(var["currentIndex"][j]) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) if signal is not None: self.control[name][-1].currentIndexChanged.connect(signal) if name == "QSpinBox": # var = {"range": [[int, int]], "singleStep": [int], "prefix": [string], "suffix": [string], "value": [int]} for j in range(0, len(position)): self.control[name].append(QSpinBox()) self.control[name][-1].setRange(var["range"][j][0], var["range"][j][1]) self.control[name][-1].setSingleStep(var["singleStep"][j]) if len(var["prefix"]) != 0: if len(var["prefix"][j]) != 0: self.control[name][-1].setPrefix(var["prefix"][j]) if len(var["suffix"]) != 0: if len(var["suffix"][j]) != 0: self.control[name][-1].setSuffix(var["suffix"][j]) self.control[name][-1].setValue(var["value"][j]) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) if signal is not None: self.control[name][-1].valueChanged.connect(signal) if name == "QTableWidget": # var = {"headerLabels": [[string]], "data": [numpy.array]} for i in range(0, len(position)): self.control[name].append(QTableWidget(1, 1)) if len(var["headerLabels"]) != 0: if len(var["headerLabels"][i]) != 0: self.control[name][-1].setColumnCount(len(var["headerLabels"][i])) self.control[name][-1].setHorizontalHeaderLabels(var["headerLabels"][i]) if len(var["data"]) != 0: if len(var["data"][i]) != 0: row, column = var["data"][i].shape self.control[name][-1].setRowCount(row) self.control[name][-1].setColumnCount(column) for j in range(0, row): for k in range(0, column): newItem = QTableWidgetItem(str(var["data"][i][j][k])) self.control[name][-1].setItem(j, k, newItem) self.control[name][-1].resizeColumnsToContents() # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[i][0], position[i][1], position[i][2], position[i][3]) if name == "QLCDNumber": # var = {"value": [int]} for j in range(0, len(position)): self.control[name].append(QLCDNumber(self)) if len(var["value"]) != 0: if len(var["value"][j]) != 0: self.control[name][-1].display(var["value"][j]) else: self.control[name][-1].display(0) # noinspection PyArgumentList layout.addWidget(self.control[name][-1], position[j][0], position[j][1], position[j][2], position[j][3]) def imageRead(self, imageName=None): """ load data into current page, or write data from current page. """ if len(self.control["QRadioButton"]) != 0: length = len(self.control["QRadioButton"]) for j in range(0, length): isChecked = self.controlData[imageName]["QRadioButton"]["isChecked"][j] self.control["QRadioButton"][j].setChecked(isChecked) if len(self.control["QComboBox"]) != 0: pass if len(self.control["QComboBox"]) != 0: length = len(self.control["QComboBox"]) for j in range(0, length): currentIndex = self.controlData[imageName]["QComboBox"]["currentIndex"][j] self.control["QComboBox"][j].setCurrentIndex(currentIndex) if len(self.control["QSpinBox"]) != 0: length = len(self.control["QSpinBox"]) for j in range(0, length): value = self.controlData[imageName]["QSpinBox"]["value"][j] self.control["QSpinBox"][j].setValue(value) if len(self.control["QTableWidget"]) != 0: length = len(self.control["QTableWidget"]) for i in range(0, length): data = self.controlData[imageName]["QTableWidget"]["data"][i] row, column = data.shape self.control["QTableWidget"][i].setRowCount(row) self.control["QTableWidget"][i].setColumnCount(column) for j in range(0, row): for k in range(0, column): newItem = QTableWidgetItem(str(data[j][k])) self.control["QTableWidget"][i].setItem(j, k, newItem) self.control["QTableWidget"][i].resizeColumnsToContents() if len(self.control["QLCDNumber"]) != 0: length = len(self.control["QLCDNumber"]) for j in range(0, length): value = self.controlData[imageName]["QLCDNumber"]["value"][j] self.control["QLCDNumber"][j].display(value) def rainImage(self): """ @ """ self.currentImage = "rainImage" self.controlClear() layout = QGridLayout() layout.setSpacing(10) # noinspection PyArgumentList widget = QWidget() self.canvas["rainImage"] = RainCanvas(parent=widget) layout.addWidget(self.canvas["rainImage"]) widget.setLayout(layout) self.setCentralWidget(widget) def orthogonalTableImage(self): """ layout and initialization data """ ########################## # layout of current page # ########################## self.currentImage = "orthogonalTableImage" self.controlClear() layout = QGridLayout() layout.setSpacing(10) text = ['水平数', '重复次数', '实验次数', '因素数'] position = [[0, 0, 1, 1], [0, 2, 1, 1], [0, 4, 1, 1], [0, 6, 1, 1]] self.controlLayout(layout=layout, name="QLabel", var={"text": text}, position=position, signal=None) itemText = [list(map(str, range(2, 10))), list(map(str, range(0, 10)))] position = [[0, 1, 1, 1], [0, 3, 1, 1]] self.controlLayout(layout=layout, name="QComboBox", var={"itemText": itemText, "currentIndex": []}, position=position, signal=self.orthogonalTableImageSignal) position = [[0, 5, 1, 1], [0, 7, 1, 1]] self.controlLayout(layout=layout, name="QLCDNumber", var={"value": []}, position=position, signal=None) # noinspection PyArgumentList widget = [[QWidget(), QWidget()]] for j in range(0, 2): widgetLayout = QGridLayout() position = [[0, 0, 1, 1]] self.controlLayout(layout=widgetLayout, name="QTableWidget", var={"headerLabels": [], "data": []}, position=position, signal=None) widget[0][j].setLayout(widgetLayout) text = [["Table", "Title"]] position = [[1, 0, 1, 8]] self.controlLayout(layout=layout, name="QTabWidget", var={"text": text, "widget": widget}, position=position, signal=None) # noinspection PyArgumentList widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) ########################################################################### # initialization self.controlData["orthogonalTableImage"] then refresh it # # refresh self.control["orthogonalTableImage"] # ########################################################################### if "orthogonalTableImage" not in self.controlData: self.addFrame("orthogonalTableImage") self.orthogonalTableImageSignal() else: for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.orthogonalTableImageSignal) self.imageRead(imageName="orthogonalTableImage") for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.orthogonalTableImageSignal) self.statusBar().showMessage('Ready') def orthogonalTableImageSignal(self): """ respond of current page(orthogonalTableImage), then write data into MainData.controlData """ self.statusBar().showMessage('Starting generate table and title...') ########################################################### # initialization self.controlData["orthogonalTableImage"] # ########################################################### imageName = "orthogonalTableImage" self.controlDataClear(imageName) #################################################### # refresh self.controlData["orthogonalTableImage"] # #################################################### for j in range(0, len(self.control["QComboBox"])): itemText = list() for k in range(0, self.control["QComboBox"][j].count()): itemText.append(self.control["QComboBox"][j].itemText(k)) self.controlData[imageName]["QComboBox"]["itemText"].append(itemText) currentIndex = self.control["QComboBox"][j].currentIndex() self.controlData[imageName]["QComboBox"]["currentIndex"].append(currentIndex) level = int(self.control["QComboBox"][0].currentText()) time = int(self.control["QComboBox"][1].currentText()) obj = OrthogonalTableMap(level, time) row, column = obj.table.shape self.controlData[imageName]["QLCDNumber"]["value"].append(row) self.controlData[imageName]["QLCDNumber"]["value"].append(column) self.controlData[imageName]["QTableWidget"]["data"].append(obj.table) self.controlData[imageName]["QTableWidget"]["data"].append(obj.title) self.controlData[imageName]["save"] = [level, time, obj.table, obj.title] ################################################ # refresh self.control["orthogonalTableImage"] # ################################################ for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.orthogonalTableImageSignal) self.imageRead(imageName=imageName) for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.orthogonalTableImageSignal) if obj.error == 1: self.statusBar().showMessage('Unable to generate title.') else: self.statusBar().showMessage('Table and title generated.') def gravitationalSystemImage(self): """ layout and initialization data """ ########################## # layout of current page # ########################## self.currentImage = "gravitationalSystemImage" self.controlClear() layout = QGridLayout() layout.setSpacing(10) text = ['长度单位', '时间单位', '质量单位', '电量单位', '质点类型', '质点个数', '动画时长', '总帧数', '播放速率', '坐标轴标签', '视角', '速度矢量', '加速度矢量'] position = [[0, 0, 1, 1], [0, 1, 1, 1], [0, 2, 1, 1], [0, 3, 1, 1], [0, 4, 1, 1], [0, 5, 1, 1], [0, 6, 1, 1], [2, 0, 1, 1], [2, 1, 1, 1], [2, 2, 1, 1], [2, 3, 1, 1], [2, 4, 1, 1], [2, 5, 1, 1]] self.controlLayout(layout=layout, name="QLabel", var={"text": text}, position=position, signal=None) itemText = [['ly', 'km', 'm', 'mm', 'nm'], ['year', 'day', 's', 'ms', 'μs'], ['kg', '太阳(1.99+e30kg)', '质子(1.7-e27kg)', '电子(9.1-e31kg)'], ['C', 'e(1.6-e19C)'], ['天体-天体', '电荷-电荷', '自定义-自定义'], list(map(str, range(2, 10))), list(map(str, range(5, 65, 5))), ['100', '1000', '10000', '100000'], ['显示', '隐藏'], ['静止', '旋转'], ['隐藏速度矢量', '显示当前速度矢量', '显示所有速度矢量'], ['隐藏加速度矢量', '显示当前加速度矢量', '显示所有加速度矢量']] currentIndex = [2, 2, 0, 0, 2, 1, 2, 2, 0, 1, 1, 1] position = [[1, 0, 1, 1], [1, 1, 1, 1], [1, 2, 1, 1], [1, 3, 1, 1], [1, 4, 1, 1], [1, 5, 1, 1], [1, 6, 1, 1], [3, 0, 1, 1], [3, 2, 1, 1], [3, 3, 1, 1], [3, 4, 1, 1], [3, 5, 1, 1]] self.controlLayout(layout=layout, name="QComboBox", var={"itemText": itemText, "currentIndex": currentIndex}, position=position, signal=self.gravitationalSystemImageSignal) var = {"range": [[1, 1000]], "singleStep": [1], "prefix": ['X '], "suffix": [" 倍"], "value": [100]} position = [[3, 1, 1, 1]] self.controlLayout(layout=layout, name="QSpinBox", var=var, position=position, signal=self.gravitationalSystemImageSignal) text = ['启用调试单位'] isChecked = [True] position = [[2, 6, 1, 1]] self.controlLayout(layout=layout, name="QRadioButton", var={"text": text, "isChecked": isChecked}, position=position, signal=self.gravitationalSystemImageSignal) text = ['播放动画'] position = [[3, 6, 1, 1]] self.controlLayout(layout=layout, name="QPushButton", var={"text": text}, position=position, signal=self.gravitationalSystemImageDraw) # noinspection PyArgumentList widget = [[QWidget(), QWidget()]] name = ["QTableWidget", "QTextEdit"] var = [{"headerLabels": [["mass", "electricity", "X-coordinate", "Y-coordinate", "Z-coordinate", "X-velocity", "Y-velocity", "Z-velocity"]], "data": [numpy.array([[1, 0, 1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 0, 0, 0, 1], [1, -1, 0, 0, 1, 1, 0, 0]])]}, {"text": [["yes", "no"]]}] for j in range(0, 2): widgetLayout = QGridLayout() position = [[0, 0, 1, 1]] self.controlLayout(layout=widgetLayout, name=name[j], var=var[j], position=position, signal=None) widget[0][j].setLayout(widgetLayout) text = [["Initial Condition", "Note"]] position = [[4, 0, 1, 7]] self.controlLayout(layout=layout, name="QTabWidget", var={"text": text, "widget": widget}, position=position, signal=None) # noinspection PyArgumentList widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) ############################################################################### # initialization self.controlData["gravitationalSystemImage"] then refresh it # # refresh self.control["gravitationalSystemImage"] # ############################################################################### if "gravitationalSystemImage" not in self.controlData: self.addFrame("gravitationalSystemImage") self.gravitationalSystemImageSignal() else: for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QSpinBox"])): self.control["QSpinBox"][j].valueChanged.disconnect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QRadioButton"])): self.control["QRadioButton"][j].clicked.disconnect(self.gravitationalSystemImageSignal) self.imageRead(imageName="gravitationalSystemImage") for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QSpinBox"])): self.control["QSpinBox"][j].valueChanged.connect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QRadioButton"])): self.control["QRadioButton"][j].clicked.connect(self.gravitationalSystemImageSignal) self.statusBar().showMessage('Ready') def gravitationalSystemImageSignal(self): """ respond of current page(gravitationalSystemImage), then write data into MainData.dataClasses """ self.statusBar().showMessage('Saving Page data...') ############################################################### # initialization self.controlData["gravitationalSystemImage"] # ############################################################### imageName = "gravitationalSystemImage" self.controlDataClear(imageName) ######################################################## # refresh self.controlData["gravitationalSystemImage"] # ######################################################## for j in range(0, len(self.control["QComboBox"])): itemText = list() for k in range(0, self.control["QComboBox"][j].count()): itemText.append(self.control["QComboBox"][j].itemText(k)) self.controlData[imageName]["QComboBox"]["itemText"].append(itemText) currentIndex = self.control["QComboBox"][j].currentIndex() self.controlData[imageName]["QComboBox"]["currentIndex"].append(currentIndex) for i in range(0, len(self.control["QTableWidget"])): currentRow = self.control["QTableWidget"][i].rowCount() row = int(self.control["QComboBox"][5].currentText()) column = self.control["QTableWidget"][i].columnCount() data = numpy.zeros((row, column), dtype=numpy.float64) for j in range(0, row): for k in range(0, column): if j < currentRow: # noinspection PyBroadException try: data[j][k] = float(self.control["QTableWidget"][i].item(j, k).text()) except: data[j][k] = 0 self.controlData[imageName]["QTableWidget"]["data"].append(data) for j in range(0, len(self.control["QSpinBox"])): value = self.control["QSpinBox"][j].value() self.controlData[imageName]["QSpinBox"]["value"].append(value) for j in range(0, len(self.control["QRadioButton"])): isChecked = self.control["QRadioButton"][j].isChecked() self.controlData[imageName]["QRadioButton"]["isChecked"].append(isChecked) #################################################### # refresh self.control["gravitationalSystemImage"] # #################################################### for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QSpinBox"])): self.control["QSpinBox"][j].valueChanged.disconnect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QRadioButton"])): self.control["QRadioButton"][j].clicked.disconnect(self.gravitationalSystemImageSignal) self.imageRead(imageName="gravitationalSystemImage") for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QSpinBox"])): self.control["QSpinBox"][j].valueChanged.connect(self.gravitationalSystemImageSignal) for j in range(0, len(self.control["QRadioButton"])): self.control["QRadioButton"][j].clicked.connect(self.gravitationalSystemImageSignal) self.statusBar().showMessage('Page data Saved.') def gravitationalSystemImageDraw(self): """ Draw animation of solution of ordinary differential equations """ ######################################################## # refresh self.controlData["gravitationalSystemImage"] # ######################################################## self.gravitationalSystemImageSignal() self.statusBar().showMessage('Start to solving the ordinary differential equations...') ##################################################### # get parameters of ordinary differential equations # ##################################################### imageName = "gravitationalSystemImage" aniArg = self.controlData[imageName]["QComboBox"]["currentIndex"][8:] data = self.controlData[imageName]["QTableWidget"]["data"][0] mass = data[:, 0] for j in range(0, len(mass)): if mass[j] < 0 or mass[j] == 0: self.statusBar().showMessage('mass[%d] must be positive.' % j) return electric = numpy.abs(data[:, 1]) electricType = numpy.sign(data[:, 1]) cood = data[:, 2:5] coodCheck = numpy.dot(cood, cood.T) for j in range(0, len(mass)): for k in range(j, len(mass)): if (coodCheck[j, j] + coodCheck[k, k]) == 2 * coodCheck[j, k] and j != k: self.statusBar().showMessage('point[%d] and point[%d] share the same coordinate.' % (j, k)) return vel = data[:, 5:] if self.controlData[imageName]["QRadioButton"]["isChecked"][0]: GUnit = 1 KUnit = 1 else: lenUnitMap = {0: 9.46 * 10 ** 15, 1: 1000, 2: 1, 3: 0.001, 4: 10 ** (-9)} lenUnit = lenUnitMap[self.controlData[imageName]["QComboBox"]["currentIndex"][0]] timeUnitMap = {0: 3.1536 * 10 ** 7, 1: 86400, 2: 1, 3: 0.001, 4: 10 ** (-6)} timeUnit = timeUnitMap[self.controlData[imageName]["QComboBox"]["currentIndex"][1]] massUnitMap = {0: 1, 1: 1.99 * 10 ** 30, 2: 1.7 * 10 ** (-27), 3: 9.1 * 10 ** (-31)} massUnit = massUnitMap[self.controlData[imageName]["QComboBox"]["currentIndex"][2]] electricUnitMap = {0: 1, 1: 1.6 * 10 ** (-19)} electricUnit = electricUnitMap[self.controlData[imageName]["QComboBox"]["currentIndex"][3]] GUnit = 6.67408 * 10 ** (-11) * massUnit * timeUnit ** 2 / lenUnit ** 3 KUnit = 8.987 * 10 ** 9 * electricUnit ** 2 * timeUnit ** 2 / lenUnit ** 3 / massUnit timeLength = int(self.control["QComboBox"][6].currentText()) nodeNumber = int(self.control["QComboBox"][7].currentText()) t = numpy.arange(0, timeLength, timeLength / nodeNumber) aniSpeed = self.controlData[imageName]["QSpinBox"]["value"][0] ######################################################## # draw the solution of ordinary differential equations # ######################################################## self.controlClear() layout = QGridLayout() layout.setSpacing(10) # noinspection PyArgumentList widget = QWidget() self.canvas["gravitationalSystemImage"] = GravitationCanvas(aniArg, mass, electric, electricType, cood, vel, GUnit, KUnit, t, aniSpeed, parent=widget) self.controlData[imageName]["save"] = [mass, electric, electricType, cood, vel, GUnit, KUnit, t, self.canvas["gravitationalSystemImage"].track, self.canvas["gravitationalSystemImage"].vector, self.canvas["gravitationalSystemImage"].acc] layout.addWidget(self.canvas["gravitationalSystemImage"]) widget.setLayout(layout) self.setCentralWidget(widget) self.statusBar().showMessage('Ready') def convexHullImage(self): """ layout and initialization data """ ########################## # layout of current page # ########################## self.currentImage = "convexHullImage" self.controlClear() layout = QGridLayout() layout.setSpacing(10) text = ['空间维数', '散点个数', '查看迭代步数'] position = [[0, 0, 1, 1], [0, 2, 1, 1], [0, 4, 1, 1]] self.controlLayout(layout=layout, name="QLabel", var={"text": text}, position=position, signal=None) itemText = [list(map(str, range(2, 15))), list(map(str, range(3, 50))), ["-complete-"] + list(map(str, range(1, 9)))] currentIndex = [1, 6, 0] position = [[0, 1, 1, 1], [0, 3, 1, 1], [0, 5, 1, 1]] self.controlLayout(layout=layout, name="QComboBox", var={"itemText": itemText, "currentIndex": currentIndex}, position=position, signal=self.convexHullImageSignal) text = ['随机生成散点集'] position = [[0, 6, 1, 1]] self.controlLayout(layout=layout, name="QPushButton", var={"text": text}, position=position, signal=self.convexHullImageRandom) # noinspection PyArgumentList widget = [[QWidget(), QWidget(), QWidget()]] matrixLayout = QGridLayout() matrix = [numpy.array([[6, 0, 9, 9, 6, 6, 2, 0, 6], [5, 7, 2, 6, 7, 3, 7, 4, 4], [8, 3, 2, 5, 0, 0, 7, 6, 5]])] self.controlLayout(layout=matrixLayout, name="QTableWidget", var={"headerLabels": [], "data": matrix}, position=[[0, 0, 1, 1]], signal=None) widget[0][0].setLayout(matrixLayout) patches_listLayout = QGridLayout() patches_list = [numpy.array([[4, 2, 6, 0, 1, 1, 0, 0, 2, 5, 5, 5], [6, 4, 0, 6, 6, 7, 2, 7, 5, 2, 1, 7], [3, 3, 3, 7, 4, 6, 3, 2, 4, 7, 4, 1]])] self.controlLayout(layout=patches_listLayout, name="QTableWidget", var={"headerLabels": [], "data": patches_list}, position=[[0, 0, 1, 1]], signal=None) widget[0][1].setLayout(patches_listLayout) canvasLayout = QGridLayout() self.canvas["convexHullImage"] = ConvexHullCanvas(matrix[0], patches_list, parent=widget[0][2]) canvasLayout.addWidget(self.canvas["convexHullImage"]) widget[0][2].setLayout(canvasLayout) text = [["Points", "Patches", "Convex Hull 3D"]] position = [[1, 0, 1, 7]] self.controlLayout(layout=layout, name="QTabWidget", var={"text": text, "widget": widget}, position=position, signal=None) # noinspection PyArgumentList widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) ###################################################################### # initialization self.controlData["convexHullImage"] then refresh it # # refresh self.control["convexHullImage"] # ###################################################################### if "convexHullImage" not in self.controlData: self.addFrame("convexHullImage") self.convexHullImageSignal() else: for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.convexHullImageSignal) self.imageRead(imageName="convexHullImage") for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.convexHullImageSignal) self.statusBar().showMessage('Ready') def convexHullImageSignal(self): """ respond of current page(convexHullImage), then write data into MainData.controlData """ self.statusBar().showMessage('Setting patches...') ###################################################### # initialization self.controlData["convexHullImage"] # ###################################################### imageName = "convexHullImage" self.controlDataClear(imageName) ############################################### # refresh self.controlData["convexHullImage"] # ############################################### m = int(self.control["QComboBox"][0].itemText(self.control["QComboBox"][0].currentIndex())) n = int(self.control["QComboBox"][1].itemText(self.control["QComboBox"][1].currentIndex())) if m < n: pass else: self.statusBar().showMessage('The number of points should be more than dimension.') return list(map(str, range(4, 50))) for j in range(0, len(self.control["QComboBox"])): itemText = list() for k in range(0, self.control["QComboBox"][j].count()): itemText.append(self.control["QComboBox"][j].itemText(k)) self.controlData[imageName]["QComboBox"]["itemText"].append(itemText) currentIndex = self.control["QComboBox"][j].currentIndex() self.controlData[imageName]["QComboBox"]["currentIndex"].append(currentIndex) row = int(self.control["QComboBox"][0].currentText()) column = int(self.control["QComboBox"][1].currentText()) currentRow = self.control["QTableWidget"][0].rowCount() currentColumn = self.control["QTableWidget"][0].columnCount() matrix = numpy.zeros((row, column), dtype=numpy.float64) for j in range(0, row): for k in range(0, column): if j < currentRow and k < currentColumn: # noinspection PyBroadException try: matrix[j][k] = float(self.control["QTableWidget"][0].item(j, k).text()) except: matrix[j][k] = 0 self.controlData[imageName]["QTableWidget"]["data"].append(matrix) obj = ConvexHullMap(matrix=matrix) obj.complete() patches = numpy.array(obj.patches).T self.controlData[imageName]["QTableWidget"]["data"].append(patches) self.controlData[imageName]["save"] = [matrix, patches] ############## # draw image # ############## if int(self.control["QComboBox"][0].currentText()) == 3: self.canvas[imageName].canvasData["matrix"] = matrix if self.control["QComboBox"][2].currentIndex() == 0: self.canvas[imageName].canvasData["patches_list"] = [obj.patches] else: new_obj = ConvexHullMap(matrix=matrix) self.canvas[imageName].canvasData["patches_list"] = [copy.deepcopy(new_obj.patches)] for j in range(0, int(self.control["QComboBox"][2].currentText())): new_obj.classify_points() if new_obj.next_points.count(None) == len(new_obj.next_points): break new_obj.expand_patches() self.canvas[imageName].canvasData["patches_list"].append(copy.deepcopy(new_obj.patches)) self.canvas[imageName].fig.clf() self.canvas[imageName].axes = axes3d.Axes3D(self.canvas[imageName].fig) self.canvas[imageName].complete_draw() self.canvas[imageName].fig.canvas.draw() ########################################### # refresh self.control["convexHullImage"] # ########################################### for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.convexHullImageSignal) self.imageRead(imageName=imageName) for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.convexHullImageSignal) self.statusBar().showMessage('End of setting title.') def convexHullImageRandom(self): """ Reset coordinates of scattered point set """ ############################################### # refresh self.controlData["convexHullImage"] # ############################################### self.statusBar().showMessage('Start to resetting coordinates of scattered points...') ######################################### # get parameters of scattered point set # ######################################### imageName = "convexHullImage" n = int(self.control["QComboBox"][0].currentText()) m = int(self.control["QComboBox"][1].currentText()) matrix = numpy.random.random_integers(low=0, high=10, size=(n, m)) self.controlData[imageName]["QTableWidget"]["data"][0] = matrix self.controlData[imageName]["save"][0] = matrix self.imageRead(imageName=imageName) self.convexHullImageSignal() self.statusBar().showMessage('End of resetting coordinates of scattered points.') def analyticFunctionImage(self): """ layout and initialization data """ ########################## # layout of current page # ########################## self.currentImage = "analyticFunctionImage" self.controlClear() layout = QGridLayout() layout.setSpacing(10) text = ['次方数', '拉伸系数', '辐角'] position = [[0, 0, 1, 1], [0, 2, 1, 1], [0, 4, 1, 1]] self.controlLayout(layout=layout, name="QLabel", var={"text": text}, position=position, signal=None) itemText = [list(map(str, range(1, 20)))] position = [[0, 1, 1, 1]] self.controlLayout(layout=layout, name="QComboBox", var={"itemText": itemText, "currentIndex": []}, position=position, signal=self.analyticFunctionImageSignal) var = {"range": [[1, 100], [-180, 180]], "singleStep": [1, 1], "prefix": [], "suffix": ['*0.1', '*pi/180'], "value": [10, 0]} position = [[0, 3, 1, 1], [0, 5, 1, 1]] self.controlLayout(layout=layout, name="QSpinBox", var=var, position=position, signal=self.analyticFunctionImageSignal) text = [['%f*e**(i*%f)*z**%d + z = 1' % (1, 1, 0)]] # noinspection PyArgumentList widget = [[QWidget()]] position = [[1, 0, 1, 6]] widgetLayout = QGridLayout() self.canvas["analyticFunctionImage"] = AnalyticFunctionCanvas(1, 1, 0, parent=widget[0][0]) widgetLayout.addWidget(self.canvas["analyticFunctionImage"]) widget[0][0].setLayout(widgetLayout) self.controlLayout(layout=layout, name="QTabWidget", var={"text": text, "widget": widget}, position=position, signal=None) # noinspection PyArgumentList widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) ############################################################################ # initialization self.controlData["analyticFunctionImage"] then refresh it # # refresh self.control["analyticFunctionImage"] # ############################################################################ if "analyticFunctionImage" not in self.controlData: self.addFrame("analyticFunctionImage") self.analyticFunctionImageSignal() else: for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.analyticFunctionImageSignal) for j in range(0, len(self.control["QSpinBox"])): self.control["QSpinBox"][j].valueChanged.disconnect(self.analyticFunctionImageSignal) self.imageRead(imageName="analyticFunctionImage") for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.analyticFunctionImageSignal) for j in range(0, len(self.control["QSpinBox"])): self.control["QSpinBox"][j].valueChanged.disconnect(self.analyticFunctionImageSignal) self.statusBar().showMessage('Ready') def analyticFunctionImageSignal(self): """ respond of current page(analyticFunctionImage), then write data into MainData.controlData """ self.statusBar().showMessage('Starting draw image...') ############################################################ # initialization self.controlData["analyticFunctionImage"] # ############################################################ imageName = "analyticFunctionImage" self.controlDataClear(imageName) ##################################################### # refresh self.controlData["analyticFunctionImage"] # ##################################################### for j in range(0, len(self.control["QComboBox"])): itemText = list() for k in range(0, self.control["QComboBox"][j].count()): itemText.append(self.control["QComboBox"][j].itemText(k)) self.controlData[imageName]["QComboBox"]["itemText"].append(itemText) currentIndex = self.control["QComboBox"][j].currentIndex() self.controlData[imageName]["QComboBox"]["currentIndex"].append(currentIndex) for j in range(0, len(self.control["QSpinBox"])): value = self.control["QSpinBox"][j].value() self.controlData[imageName]["QSpinBox"]["value"].append(value) ############## # draw image # ############## self.canvas[imageName].n = self.controlData[imageName]["QComboBox"]["currentIndex"][0] + 1 self.canvas[imageName].r = self.controlData[imageName]["QSpinBox"]["value"][0] * 0.1 self.canvas[imageName].t = self.controlData[imageName]["QSpinBox"]["value"][1] * math.pi / 180 text = '%f*e**(i*%f)*z**%d + z = 1' % (self.canvas[imageName].n, self.canvas[imageName].r, self.canvas[imageName].t) self.control["QTabWidget"][0].setTabText(0, text) self.canvas[imageName].fig.clf() self.canvas[imageName].axes = self.canvas[imageName].fig.add_subplot(111) self.canvas[imageName].axes.grid(True) self.canvas[imageName].complete_draw() self.canvas[imageName].fig.canvas.draw() ################################################ # refresh self.control["analyticFunctionImage"] # ################################################ for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.disconnect(self.analyticFunctionImageSignal) self.imageRead(imageName=imageName) for j in range(0, len(self.control["QComboBox"])): self.control["QComboBox"][j].currentIndexChanged.connect(self.analyticFunctionImageSignal) self.statusBar().showMessage('Image is drawn.') @staticmethod def sourceCodeImage(): """ @ """ pass def keyPressEvent(self, event): """ :param event: :return: """ if event.key() == Qt.Key_Escape: try: if self.currentImage == "rainImage": self.orthogonalTableImage() elif self.currentImage == "orthogonalTableImage": pass elif self.currentImage == "convexHullImage": pass elif self.currentImage == "gravitationalSystemImage": self.gravitationalSystemImage() elif self.currentImage == "analyticFunctionImage": pass except KeyError: self.startImage() self.statusBar().showMessage('Esc is pressed!') def showOpenDialog(self): """ @ """ # noinspection PyCallByClass,SpellCheckingInspection fname = QFileDialog.getOpenFileName(self, 'Open file', '/home') # if fname[0]: # # noinspection PyArgumentEqualDefault # f = open(fname[0], 'r') # with f: # data = f.read() # self.textEdit.setText(data) def buttonClicked(self): """ @ """ sender = self.sender() self.statusBar().showMessage(sender.text() + ' was pressed') # noinspection PyCallByClass,PyTypeChecker QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') def closeEvent(self, event): """ @ """ # noinspection PyCallByClass,PyTypeChecker reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore()
zhaicao/pythonWorkspace
Pyqt5Practice/design/app.py
app.py
py
50,611
python
en
code
0
github-code
6
34199991642
#!/usr/bin/env python from PyQt4 import QtGui, QtCore from item import Item class DescItem(Item): def __init__(self, scene, x, y, parent): self.text = "" self.scale = 1.0 self.color = QtCore.Qt.gray self.hover_color = QtCore.Qt.white super(DescItem, self).__init__(scene, x, y, parent=parent) def boundingRect(self): if not self.scene(): return QtCore.QRectF() font = QtGui.QFont(self.default_font, self.get_font_size(self.scale)) metrics = QtGui.QFontMetrics(font) return QtCore.QRectF( metrics.boundingRect( QtCore.QRect( 0, 0, 10000, 10000), QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop | QtCore.Qt.TextWordWrap, self.text)) def set_content(self, text, scale=1.0, color=None, hover_color=None): self.prepareGeometryChange() self.scale = scale self.text = text if color: self.color = color if hover_color: self.hover_color = hover_color self.update() def paint(self, painter, option, widget): if not self.scene(): return painter.setClipRect(option.exposedRect) painter.setRenderHint(QtGui.QPainter.Antialiasing) if self.parentItem() and self.parentItem().hover: painter.setBrush(self.hover_color) painter.setPen(self.hover_color) else: painter.setBrush(self.color) painter.setPen(self.color) font = QtGui.QFont(self.default_font, self.get_font_size(self.scale)) painter.setFont(font) painter.drawText(self.boundingRect(), QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop | QtCore.Qt.TextWordWrap, self.text)
robofit/arcor
art_projected_gui/src/art_projected_gui/items/desc_item.py
desc_item.py
py
1,879
python
en
code
9
github-code
6
7552302996
# Covid Resistant Husky 3 - ADA price prediction # import pip to install necessary libraries import math import pip pip.main(['install', 'python-binance', 'pandas', 'scikit-learn', 'matplotlib', 'keras', 'tensorflow', 'plotly', 'mplfinance']) from keras.losses import mean_squared_error from matplotlib.dates import date2num # import the necessary libraries import config from binance.client import Client import pandas as pd from sklearn.preprocessing import MinMaxScaler import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM, Dropout, GRU import matplotlib.pyplot as plt import plotly.graph_objects as go import talib from sklearn.metrics import r2_score from mplfinance.original_flavor import candlestick_ohlc # function call to split the data for training and test def train_test_split(df, test_size=0.2): # split the data into 80 and 20 split_row = len(df) - int(len(df) * test_size) # train data contains 80% of data train_data = df.iloc[:split_row] # test data contains 20% of the data test_data = df.iloc[split_row:] return train_data, test_data # function to calcualte MACD, MA10,MA30 and RSI def get_indicators(data2): # Get MACD data2["macd"], data2["macd_signal"], data2["macd_hist"] = talib.MACD(data2['Close']) # Get MA10 and MA30 data2["ma10"] = talib.MA(data2["Close"], timeperiod=10) data2["ma30"] = talib.MA(data2["Close"], timeperiod=30) # Get RSI data2["rsi"] = talib.RSI(data2["Close"]) return data2 # function call to initialise the RNN - GRU model def Model_Initialisation_GRU(X_train, mod): model = Sequential() # Layer 1 model.add(mod(70, activation='relu', return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2]))) # Dropout is set to 20% model.add(Dropout(0.2)) # Layer 2 model.add(mod(80, activation='relu')) # Dropout is set to 20% model.add(Dropout(0.2)) model.add(Dense(units=1)) print(model.summary()) return model # function call to initialise the RNN -LSTM model def Model_Initialisation_LSTM(X_train, mod): model = Sequential() # Layer 1 model.add(mod(300, activation='relu', return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2]))) # Dropout is set to 20% model.add(Dropout(0.2)) # Layer 2 model.add(mod(300, activation='relu')) # Dropout is set to 20% model.add(Dropout(0.2)) model.add(Dense(units=1)) print(model.summary()) return model # function call to plot the RSI, MACD, MA10 and MA30 def plot_chart(data, n, ticker): # Filter number of observations to plot data = data.iloc[-n:] # Create figure and set axes for subplots fig = plt.figure() fig.set_size_inches((30, 20)) ax_candle = fig.add_axes((0, 0.72, 1, 0.32)) ax_macd = fig.add_axes((0, 0.48, 1, 0.2), sharex=ax_candle) ax_rsi = fig.add_axes((0, 0.24, 1, 0.2), sharex=ax_candle) ax_vol = fig.add_axes((0, 0, 1, 0.2), sharex=ax_candle) # Format x-axis ticks as dates ax_candle.xaxis_date() # Get nested list of date, open, high, low and close prices ohlc = [] for date, row in data.iterrows(): openp, highp, lowp, closep = row[:4] ohlc.append([date2num(date), openp, highp, lowp, closep]) # Plot candlestick chart ax_candle.plot(data.index, data["ma10"], label="MA10") ax_candle.plot(data.index, data["ma30"], label="MA30") candlestick_ohlc(ax_candle, ohlc, colorup="g", colordown="r", width=0.8) ax_candle.legend() # Plot MACD ax_macd.plot(data.index, data["macd"], label="macd") ax_macd.bar(data.index, data["macd_hist"] * 3, label="hist") ax_macd.plot(data.index, data["macd_signal"], label="signal") ax_macd.legend() # Plot RSI # Above 70% = overbought, below 30% = oversold ax_rsi.set_ylabel("(%)") ax_rsi.plot(data.index, [70] * len(data.index), label="overbought") ax_rsi.plot(data.index, [30] * len(data.index), label="oversold") ax_rsi.plot(data.index, data["rsi"], label="rsi") ax_rsi.legend() # Show volume in millions ax_vol.bar(data.index, data["Volume"] / 1000000) ax_vol.set_ylabel("(Million)") # Save the chart as PNG fig.savefig(ticker + ".png", bbox_inches="tight") plt.show() # function call to train and predict the close values def fit_model(train_set, test_set, X_train, y_train, model, scaler, model_name): model.compile(loss='mse', optimizer='adam') # fit the model with the training data model.fit(X_train, y_train, epochs=50, batch_size=32, shuffle=False) # storing the training data train_set = pd.DataFrame(train_set, columns=['Open', 'High', 'Low', 'Close', 'Volume']) # specifying the window as 10 past_10_days = train_set.tail(10) df = past_10_days.append(test_set, ignore_index=True) print(df.head()) # transforming the data inputs = scaler.transform(df) print(inputs) X_test = [] y_test = [] for i in range(10, inputs.shape[0]): X_test.append(inputs[i - 10:i]) y_test.append(inputs[i, 0]) # converting the data into array X_test, y_test = np.array(X_test), np.array(y_test) print(X_test.shape, y_test.shape) # predicting the close value on test data y_pred = model.predict(X_test) print(y_pred, y_test) # performing inverse of scalar transformation to get the actual value arr = scaler.scale_ scale = 1 / arr[0] print(scale) y_pred = y_pred * scale y_test = y_test * scale # calculates the r2 value print("R2 score", round(r2_score(y_test, y_pred) * 100, 2)) # calculates the RMSE value for training data trainScore = math.sqrt(mean_squared_error(y_train[0], y_pred[:, 0])) print('Train Score: %.2f RMSE' % (trainScore)) # calculates the RMSE value for test data testScore = math.sqrt(mean_squared_error(y_test[0], y_pred[:, 0])) print('Test Score: %.2f RMSE' % (testScore)) # plotting the graph to show predicted vs test value of the models plt.figure(figsize=(14, 5)) plt.plot(y_test, color='red', label='ADA Price') plt.plot(y_pred, color='blue', label='Predicted ADA Price') plt.title('ADA Price Prediction') plt.xlabel('Time (in Hours)') plt.ylabel('ADA Price') plt.legend() plt.show() # function to call to initialise the models and call the model to predict the data def Model_Prediction(df): # split the data into 80:20 for training and testing train_set, test_set = train_test_split(data, test_size=0.2) scaler = MinMaxScaler() # transforming the data using Min, Max scaler train_set = scaler.fit_transform(train_set) print(train_set) # specifiying the window size as 10 and values are stored accordingly in train data X_train = [] y_train = [] for i in range(10, train_set.shape[0]): X_train.append(train_set[i - 10:i]) y_train.append(train_set[i, 0]) # converting the train data into array X_train, y_train = np.array(X_train), np.array(y_train) print(X_train.shape) # initialising RNN - GRU model model_GRU = Model_Initialisation_GRU(X_train, GRU) # initialising RNN - LSTM model_LSTM = Model_Initialisation_LSTM(X_train, LSTM) # training the LSTM model and predicting the close value fit_model(train_set, test_set, X_train, y_train, model_LSTM, scaler, 'LSTM') # training the GRU model and predicting the close value fit_model(train_set, test_set, X_train, y_train, model_GRU, scaler, 'GRU') # Function call to plot the candelstick chart def CandleStickChart(data): # using TA lib library for recognising the patterns in data candle_names = talib.get_function_groups()['Pattern Recognition'] # Plotting the candelstick data fig = go.Figure(data=[go.Candlestick(x=data.index, open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'])]) fig.update_layout(title='ADA price over the time', yaxis_title='Price') fig.show() # function to plot log10 close price of ADA def LogReturnsPlot(data): # calculates log10 of close price of ADA change = pd.DataFrame(data['Close']).apply(lambda x: np.log(x) - np.log(x.shift(1))) print(change) # plots the graph fig = go.Figure([go.Scatter(x=change.index, y=change['Close'])]) fig.update_layout(title='log10 value of Closing price', xaxis_title='log10') fig.show() # function call to download the dataset def get_ADA_BinanceAPI(): # connecting to the Binance API to fetch the data client = Client(config.binance_API, config.binance_Secret) # downloading the ADA data from Binance API for 1 day interval, 500 entries. ADA = client.get_klines(symbol='ADAUSDT', interval=Client.KLINE_INTERVAL_1DAY, limit=500) # converting the data into Dataframe and assigning columns ADA = pd.DataFrame(ADA, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore']) # converting the open time column to datetime type ADA['Open time'] = pd.to_datetime(ADA['Open time'], unit='ms') # formatting the data in ascending order of time ADA.sort_values(by=['Open time'], inplace=True, ascending=True) # setting time column as index ADA.set_index('Open time', inplace=True) # converting the variables into float type ADA['Open'] = ADA['Open'].astype(float) ADA['High'] = ADA['High'].astype(float) ADA['Low'] = ADA['Low'].astype(float) ADA['Close'] = ADA['Close'].astype(float) ADA['Volume'] = ADA['Volume'].astype(float) # the 5 variables are used to predict close and are stored as dataframe and returned data = pd.DataFrame(ADA[['Open', 'High', 'Low', 'Close', 'Volume']]) print(data.head(15)) return data # main function if __name__ == '__main__': # function to download the data from Binance API data = get_ADA_BinanceAPI() # Function to plot log10 close price LogReturnsPlot(data) # fucntion call to calculate MACD, RSI, MA10 and MA30 data2 = data.copy() data2 = get_indicators(data2) # fucntion call to plot MACD, RSI, MA10 and MA30 plot_chart(data2, 150, "PLOTS") # function to plot the candelstick chart CandleStickChart(data) # model to predict the close price of ADA Model_Prediction(data)
aayushi1903/Cryptocurrency-project
main2.py
main2.py
py
10,855
python
en
code
0
github-code
6
10881296356
import unittest from pathlib import Path from tests import CdsTestMixin from . import CDSCase class DumpTest(CdsTestMixin, unittest.TestCase): def test_trace_json(self): with CDSCase(self, self.NAME_LIST, self.TEST_ARCHIVE) as cds: cds.run_trace('import json') cds.verify_files(check_archive=False) cds.verify(lambda _: self.assertIn( 'json', [line.strip() for line in Path(self.NAME_LIST).read_text().split('\n')])) def test_dump_archive_from_list_json(self): with open(self.NAME_LIST, 'w') as f: print('json', file=f) with CDSCase(self, self.NAME_LIST, self.TEST_ARCHIVE, clear_list=False) as cds: cds.run_dump()
alibaba/code-data-share-for-python
tests/test_cds/test_dump.py
test_dump.py
py
745
python
en
code
38
github-code
6
30338122797
from collections import deque def bfs(graph, start): queue = deque([start]) #방문할 노드를 넣어두는 곳 visited = [] #방문한 노드들 while queue: v = queue.popleft() print(v, end=" ") if v not in visited: visited.append(v) queue += graph[v] return visited graph = [ [], [2,3,8], [1,7], [1,4,5], [3,5], [3,4], [7], [2,6,8], [1,7] ] print(bfs(graph, 1))
minju7346/CordingTest
bfs_test2.py
bfs_test2.py
py
472
python
en
code
0
github-code
6
171090943
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from rp_ui_harness import RequestPolicyTestCase class TestBeforeAllOtherTests(RequestPolicyTestCase): def test_gecko_log(self): error_lines = self.gecko_log.get_error_lines_before_first_test() if len(error_lines) != 0: self.fail( "Found " + str(len(error_lines)) + " error lines before " + "the first test! First error line: " + str(error_lines[0]))
RequestPolicyContinued/requestpolicy
tests/marionette/tests-special/test_before_all_other_tests.py
test_before_all_other_tests.py
py
617
python
en
code
253
github-code
6
74326542907
import datetime import jsonlines # Appends json to a jsonl file def append_to_jsonl(timeline, file_path): print("Writing contents to jsonl...") # Sort major events array by timestamp sorted_timeline = sorted(timeline, key=lambda event: int(event['date'])) # Pretty print JSON of human datetime for event in sorted_timeline: date = datetime.datetime.fromtimestamp(int(event['date'])/1000).strftime('%c') event['date_pretty'] = date # print(f"[{date}] {event['name']} ({len(event['citationIds'])})") with jsonlines.open(file_path, mode='a') as writer: for item in sorted_timeline: writer.write(item)
jeromechoo/gpt-for-you
helpers/write.py
write.py
py
618
python
en
code
4
github-code
6
8670584413
import cv2 import cvzone from cvzone.PoseModule import PoseDetector import numpy as np cap = cv2.VideoCapture(1) detector = PoseDetector() per = 0 a1 = 0 color = (0,0,255) situps = 0 dir = 0 while True: __ , img = cap.read() #assert isinstance(img, object) img = detector.findPose(img) lmlist, bbox = detector.findPosition(img,False) assert isinstance(lmlist, object) if lmlist: a1 = detector.findAngle(img,24,26,28) per = np.interp(a1,(75,160),(100,0)) bar_value = np.interp(a1,(75,160),(15,15+300)) # print(per) cv2.rectangle(img,(580,int(bar_value)),(580 + 20,15 + 350),color,cv2.FILLED) cv2.rectangle(img,(580,15),(580 + 20,15 + 350),(0,0,0),3) cvzone.putTextRect(img,f'{int(per)} %',(575,410),1.2,2,colorT=(),colorR=color,border=3,colorB=()) if per ==100: if dir == 0: situps += 0.5 dir = 1 color = (0,255,0) elif per == 0: if dir == 1: situps += 0.5 dir = 0 color = (0,255,0) else: color = (0,0,255) #print(situps) cvzone.putTextRect(img,f'SIT UPS : {str(int(situps))}',(30,30),2,2,colorT=(),colorR=(255,0,0),border=3,colorB=()) cv2.imshow('Situps Counter', img) if cv2.waitKey(1) == ord('q'): break
adirastogi235/PUSH-UP-COUNTER
main.py
main.py
py
1,392
python
en
code
0
github-code
6
43622986430
# -*- coding: utf-8 -*- import html from gi.repository import Gtk from mcomix.preferences import config class MessageDialogRemember(Gtk.MessageDialog): __slots__ = ('__dialog_id', '__choices', '__remember_checkbox') def __init__(self): """ Creates a dialog window. """ super().__init__() self.set_modal(True) #: Unique dialog identifier (for storing 'Do not ask again') self.__dialog_id = None #: List of response IDs that should be remembered self.__choices = [] self.__remember_checkbox = Gtk.CheckButton(label='Do not ask again.') self.__remember_checkbox.set_no_show_all(True) self.__remember_checkbox.set_can_focus(False) self.get_message_area().pack_end(self.__remember_checkbox, True, True, 6) self.set_default_response(Gtk.ResponseType.OK) def set_text(self, primary: str, secondary: str = None): """ Formats the dialog's text fields. :param primary: Main text. :param secondary: Descriptive text """ self.set_markup(f'<span weight="bold" size="larger">{html.escape(primary)}</span>') if secondary: self.format_secondary_markup(html.escape(secondary)) def should_remember_choice(self): """ :returns: True when the dialog choice should be remembered """ return self.__remember_checkbox.get_active() def set_should_remember_choice(self, dialog_id: str, choices: tuple): """ This method enables the 'Do not ask again' checkbox. :param dialog_id: Unique identifier for the dialog (a string). :param choices: List of response IDs that should be remembered """ self.__remember_checkbox.show() self.__dialog_id = dialog_id self.__choices = [int(choice) for choice in choices] def run(self): """ Makes the dialog visible and waits for a result. Also destroys the dialog after the result has been returned """ if self.__dialog_id in config['STORED_DIALOG_CHOICES']: self.destroy() return config['STORED_DIALOG_CHOICES'][self.__dialog_id] self.show_all() # Prevent checkbox from grabbing focus by only enabling it after show self.__remember_checkbox.set_can_focus(True) result = super().run() if self.should_remember_choice() and int(result) in self.__choices: config['STORED_DIALOG_CHOICES'][self.__dialog_id] = int(result) self.destroy() return result
thermitegod/mcomix-lite
mcomix/message_dialog/remember.py
remember.py
py
2,610
python
en
code
2
github-code
6
37211599965
import numpy as np import torch # # np.argwhere的用法 # a=np.zeros((4,3), dtype=np.uint32) # b=np.argwhere(np.zeros((4,3), dtype=np.uint32) == 0) # print(a) # print(b) # print(type(b),b.shape) # # reshape的用法,torch和numpy都有类似的用法 # a = torch.arange(4.) # print(a.shape) # a=torch.reshape(a, (2, 2)) # print(a.shape) # b = torch.rand(4,4,2) # print(b.shape) # b=torch.reshape(b, (-1,2)) # print(b.shape) # # np.arange和np.linspace的一点比较 # print(np.arange(-6, 6, 2)) # I_r_grid_x = (np.arange(-6, 6, 2) + 1.0) / 6 # I_r_grid_y = (np.arange(-6, 6, 2) + 1.0) / 6 # print(I_r_grid_x) # print(I_r_grid_y) # I_r_grid_x=np.linspace(-1,1,6) # print(I_r_grid_x) # # np.concatenate用法 # a = np.concatenate([np.zeros((1, 3)), np.ones((1, 9))], axis=1) # print(a) # # np.fill_diagonal用法 # hat_C=5*np.ones((4,4)) # np.fill_diagonal(hat_C, 1) # print(hat_C) # 参考点生成 # xs = torch.linspace(0, 1020, steps=61) # ys = torch.linspace(0, 1020, steps=61) # x, y = torch.meshgrid(xs, ys, indexing='xy') # P = torch.dstack([x, y]) # print(P) # 归一化测试 # 只有当requires_grad=True时,讨论叶张量才有意义 batch_pt = torch.ones((4, 2, 31, 31), requires_grad=True) batch_pt_norm = batch_pt / 992 batch_pt_norm.sum().backward() print(batch_pt_norm.max()) print("OK") # 赋值测试 a,b,c,d=0,0,0,0 print(a,b,c,d)
hanquansanren/unified_doctransformer
simple_test/unit_test.py
unit_test.py
py
1,371
python
en
code
1
github-code
6
43581170385
from django.shortcuts import render from .models import * from django.http import HttpResponse import json from rest_framework import generics from .serializers import * # Create your views here. def dashboard(request): return render(request,"dashboard.html") def department(request): #department_list = Department.objects.all() department_list = Department.objects.raw('SELECT * FROM emp_department') return render(request,'departments.html',{'department_list':department_list}) def manage_departments(request): department = {} if request.method == 'GET': data = request.GET id = '' if 'id' in data: id= data['id'] print(id) if id.isnumeric() and int(id) > 0: department = Department.objects.raw(f'SELECT * FROM emp_department WHERE emp_department.id = {id}')[0] #department = Department.objects.filter(pk=id).first() print(department) context = { 'department' : department } return render(request, 'manage_department.html',context) def save_department(request): data = request.POST resp = {'status':'failed'} try: if (data['id']).isnumeric() and int(data['id']) > 0 : d_name=data['name'] d_id=data['id'] #save_department = Department.objects.filter(id = data['id']).update(department=data['name']) q=f'UPDATE emp_department SET department = \'{d_name}\' WHERE emp_department.id = {d_id}' Department.objects.raw(q)[:] else: d_name=data['name'] q=f'INSERT INTO emp_department (department) VALUES (\'{d_name}\') RETURNING emp_department.id' Department.objects.raw(q)[:] #save_department = Department(department=data['name']) resp['status'] = 'success' except Exception as e: print(e) resp['status'] = 'success' return HttpResponse(json.dumps(resp), content_type="application/json") def delete_department(request): data = request.POST resp = {'status':''} try: d_id=data['id'] resp['status'] = 'success' Department.objects.raw(f'DELETE FROM emp_department WHERE emp_department.id = {d_id}')[:] #Department.objects.filter(id = data['id']).delete() except: resp['status'] = 'success' return HttpResponse(json.dumps(resp), content_type="application/json") def employee(request): #employee_list = Employee.objects.all() employee_list =Employee.objects.raw('SELECT * FROM emp_employee') return render(request,'employees.html',{'employee_list':employee_list}) def view_employee(request): employee = {} if request.method == 'GET': data = request.GET id = '' if 'id' in data: id= data['id'] if id.isnumeric() and int(id) > 0: employee = Employee.objects.raw(f'SELECT * FROM emp_employee WHERE emp_employee.id = {id}')[0] #employee = Employee.objects.filter(pk=id).first() context = { 'employee' : employee, } return render(request, 'view_employee.html',context) def manage_employees(request): employee = {} #departments = Department.objects.all() departments =Department.objects.raw('SELECT * FROM emp_department') if request.method == 'GET': data = request.GET id = '' if 'id' in data: id= data['id'] if id.isnumeric() and int(id) > 0: employee = Employee.objects.raw(f'SELECT * FROM emp_employee WHERE emp_employee.id = {id}')[0] #employee = Employee.objects.filter(id=id).first() context = { 'employee' : employee, 'departments' : departments, } return render(request, 'manage_employee.html',context) def save_employee(request): data = request.POST resp = {'status':'failed'} print(data) if (data['id']).isnumeric() and int(data['id']) > 0: check = Employee.objects.filter(pk = data['id']) if check: d_id=data['department_id'] e_id=data['id'] name=data['firstname'] salary=data['salary'] #dept = Department.objects.filter(id=data['department_id']).first() q=f'UPDATE emp_employee SET name = \'{name}\', department_id = {d_id}, salary = {salary} WHERE emp_employee.id = {e_id}' Employee.objects.raw(q)[:] #Employee.objects.filter(id = data['id']).update(name = data['firstname'],department = dept,salary = data['salary']) resp['status'] = 'success' else: try: d_id=data['department_id'] e_id=data['id'] name=data['firstname'] salary=data['salary'] # dept = Department.objects.filter(id=data['department_id']).first() # save_employee = Employee(name = data['firstname'],department= dept,salary = data['salary']) # save_employee.save() q=f'INSERT INTO emp_employee (name, salary, department_id) VALUES (\'{name}\', {salary}, {d_id}) RETURNING emp_employee.id' Employee.objects.raw(q)[:] resp['status'] = 'success' except Exception as e: resp['status'] = 'success' print(e) return HttpResponse(json.dumps(resp), content_type="application/json") def delete_employee(request): data = request.POST resp = {'status':''} try: #Employee.objects.filter(pk = data['id']).delete() e_id=data['id'] Employee.objects.raw(f'DELETE FROM emp_employee WHERE emp_employee.id= {e_id}')[:] resp['status'] = 'success' except: resp['status'] = 'success' return HttpResponse(json.dumps(resp), content_type="application/json") def task(request): #task_list = Task.objects.all() task_list =Task.objects.raw('SELECT * FROM emp_task') return render(request,'task.html',{'task_list':task_list}) def view_task(request): task = {} if request.method == 'GET': data = request.GET id = '' if 'id' in data: id= data['id'] print("aaaa",id) if id.isnumeric() and int(id) > 0: #task = Task.objects.filter(pk=id).first() task=Task.objects.raw(f'SELECT * FROM emp_task WHERE emp_task.id = {id}')[0] context = { 'task' : task, } return render(request, 'view_task.html',context) def manage_task(request): task = {} status = ["ACCEPTED","COMPLETED"] if request.method == 'GET': data = request.GET id = '' if 'id' in data: id= data['id'] if id.isnumeric() and int(id) > 0: #task = Task.objects.filter(id=id).first() task=Task.objects.raw(f'SELECT * FROM emp_task WHERE emp_task.id = {id}')[0] context = { 'task' : task, 'status' : status, } return render(request, 'manage_task.html',context) def save_task(request): data = request.POST resp = {'statuss':'failed'} try: if (data['id']).isnumeric() and int(data['id']) > 0 : t_id=data['id'] t_name=data['id'] t_status=data['status'] #save_task = Task.objects.filter(pk = data['id']).update(t_name=data['id'],status=data['status']) q=f'UPDATE emp_task SET t_name = \'{t_name}\', status = \'{t_status}\' WHERE emp_task.id = {t_id}' Task.objects.raw(q)[:] resp['statuss'] = 'success' except: resp['statuss'] = 'success' return HttpResponse(json.dumps(resp), content_type="application/json") def delete_task(request): data = request.POST resp = {'status':''} try: #Task.objects.filter(id = data['id']).delete() t_id=data['id'] Task.objects.raw(f'DELETE FROM emp_task WHERE emp_task.id = {t_id}')[:] resp['status'] = 'success' except: resp['status'] = 'success' return HttpResponse(json.dumps(resp), content_type="application/json") def add_new_task(request): status = ["ACCEPTED","COMPLETED"] #employee = Employee.objects.all() employee =Employee.objects.raw('SELECT * FROM emp_employee') context = { 'employee' : employee, 'status' : status, } return render(request, 'add_new_task.html',context) def save_new_task(request): data = request.POST resp = {'status':''} try: # emp=Employee.objects.get(pk=data['employee_id']) # Task(employee=emp,t_name=data['task_name'],status=data['status_id']).save() e_id=data['employee_id'] t_name=data['task_name'] t_status=data['status_id'] q=f'INSERT INTO emp_task (employee_id, t_name, status) VALUES ({e_id}, \'{t_name}\', \'{t_status}\') RETURNING emp_task.id' Task.objects.raw(q)[:] resp['status'] = 'success' except: resp['status'] = 'success' return HttpResponse(json.dumps(resp), content_type="application/json") def signle_emp(request): emp=Employee.objects.all() return render(request,"single.html",{"emp":emp}) def emp_task(request): task = {} if request.method == 'GET': data = request.GET id = '' if 'id' in data: id= data['id'] print("aaaa",id) if id.isnumeric() and int(id) > 0: #task = Task.objects.filter(pk=id).first() task=Task.objects.raw(f'SELECT * FROM emp_task WHERE emp_task.id = {id}')[0] context = { 'task' : task, } return render(request, 'single.html',context) ############################################################################################################## class DepartmentList(generics.ListAPIView): queryset = Department.objects.raw('SELECT * FROM emp_department') serializer_class = DepartmentSerializer class DepartmentCreate(generics.CreateAPIView): queryset = Department.objects.raw('SELECT * FROM emp_department') serializer_class = DepartmentSerializer class DepartmentRetrieve(generics.RetrieveAPIView): queryset = Department.objects.raw('SELECT * FROM emp_department') serializer_class = DepartmentSerializer class DepartmentUpdate(generics.UpdateAPIView): queryset = Department.objects.raw('SELECT * FROM emp_department') serializer_class = DepartmentSerializer class DepartmentDestroy(generics.DestroyAPIView): queryset = Department.objects.raw('SELECT * FROM emp_department') serializer_class = DepartmentSerializer class EmployeeList(generics.ListAPIView): queryset = Employee.objects.raw('SELECT * FROM emp_employee') serializer_class = EmployeeSerializer class EmployeeCreate(generics.CreateAPIView): queryset = Employee.objects.raw('SELECT * FROM emp_employee') serializer_class = EmployeeSerializer class EmployeeRetrieve(generics.RetrieveAPIView): queryset = Employee.objects.raw('SELECT * FROM emp_employee') serializer_class = EmployeeSerializer class EmployeeUpdate(generics.UpdateAPIView): queryset = Employee.objects.raw('SELECT * FROM emp_employee') serializer_class = EmployeeSerializer class EmployeeDestroy(generics.DestroyAPIView): queryset = Employee.objects.raw('SELECT * FROM emp_employee') serializer_class = EmployeeSerializer class TaskList(generics.ListAPIView): queryset = Task.objects.raw('SELECT * FROM emp_task') serializer_class = TaskSerializer class TaskCreate(generics.CreateAPIView): queryset = Task.objects.raw('SELECT * FROM emp_task') serializer_class = TaskSerializer class TaskRetrieve(generics.RetrieveAPIView): queryset = Task.objects.raw('SELECT * FROM emp_task') serializer_class = TaskSerializer class TaskUpdate(generics.UpdateAPIView): queryset = Task.objects.raw('SELECT * FROM emp_task') serializer_class = TaskSerializer class TaskDestroy(generics.DestroyAPIView): queryset = Task.objects.raw('SELECT * FROM emp_task') serializer_class = TaskSerializer
sanjaymehar/employee_management_system
emp/views.py
views.py
py
12,083
python
en
code
0
github-code
6
6507125015
from django.db import models from applications.locations.models import Location class Schedule(models.Model): id = models.BigAutoField( primary_key=True, verbose_name='Id Horario' ) location = models.ForeignKey( Location, verbose_name='Sede', null=False, on_delete=models.CASCADE ) begin_validity = models.DateField( verbose_name='Inicio de vigencia' ) end_validity = models.DateField( verbose_name='Fin vigencia' ) class Meta: verbose_name='Horario' verbose_name_plural='Horarios' def __str__(self): return '{0} - {1}'.format(self.id, self.location) class Schedule_Day(models.Model): WEEKDAY = 'WD' SATURDAY = 'SA' SUNDAY = 'SU' HOLIDAY = 'HO' DAYS_CHOICES = [ ( WEEKDAY, 'Lunes a Viernes' ), ( SATURDAY, 'Sábado' ), ( SUNDAY, 'Domingo' ), ( HOLIDAY, 'Festivo' ) ] schedule = models.ForeignKey( Schedule, related_name='day_type', verbose_name='Id Horario', on_delete=models.CASCADE ) daytype = models.CharField( verbose_name='Tipo de Día', max_length=2, choices=DAYS_CHOICES, default=WEEKDAY ) is_open = models.BooleanField( verbose_name='¿Está abierto?', default=False ) class Meta: verbose_name='Día horario' verbose_name_plural='Días horario' unique_together = ['schedule','daytype'] def __str__(self): return '{0} - {1}'.format(self.schedule, self.daytype) def get_daytype(self,weekday: int): if weekday >= 1 and weekday <= 5: return self.WEEKDAY elif weekday == 6: return self.SATURDAY elif weekday == 7: return self.SUNDAY class Schedule_Slot(models.Model): schedule_day = models.ForeignKey( Schedule_Day, related_name='timeslot', verbose_name='Día', on_delete=models.CASCADE ) slot = models.IntegerField( verbose_name='Slot' ) starttime = models.TimeField( verbose_name='Hora Inicio' ) endtime = models.TimeField( verbose_name='Hora Fin' ) class Meta: verbose_name = 'Bloque horario' verbose_name_plural = 'Bloques horario' unique_together = ['schedule_day','slot'] ordering = ['slot'] def __str__(self): return '{0} : {1} - {2}'.format( self.schedule_day, self.starttime, self.endtime )
chpenaf/DotSportsBackend
applications/schedule/models.py
models.py
py
2,611
python
en
code
0
github-code
6
74519748667
import pyautogui from random import random import pyscreenshot as ImageGrab import math import cv2 as cv from utilities import inventory as inv from utilities.core import get_bounding_rect_from_pts def get_pickup_rects(o_img, cnts): # returns bounding rect(s) of item(s) to pickup items = [] line_pts = [] for c in cnts: # compute the center of each contour M = cv.moments(c) if M["m00"] != 0: cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) line_pts.append((cX, cY)) # cv.rectangle(output,(minx,miny),(maxx,maxy),(0,255,255),2) maxslope = 0 item_split_indices = [0] for x in range(1, len(line_pts) - 2): x1, y1 = (line_pts[x - 1]) x2, y2 = (line_pts[x]) if (x2 - x1) != 0: m = (y2 - y1) / (x2 - x1) if m > maxslope: maxslope = m if (m <= 0.05) and (m >= -0.05): cv.line(o_img, line_pts[x - 1], line_pts[x], (0, 255, 255), 2) else: # split lines based on slope and dist # print(item_split_indices) # print(math.dist((x1,y1),(x2,y2))) if (math.dist((x1, y1), (x2, y2))) >= 40 and x != 1: item_split_indices.append(x) if len(item_split_indices) == 1: rect = get_bounding_rect_from_pts(line_pts[1:len(line_pts)]) if rect not in items: items.append(rect) elif (len(item_split_indices) > 1): for i in range(0, len(item_split_indices) - 1): if i == 0: rect = get_bounding_rect_from_pts(line_pts[1:item_split_indices[i + 1]]) elif (i + 1 <= len(item_split_indices) + 1): rect = get_bounding_rect_from_pts(line_pts[item_split_indices[i]:item_split_indices[i + 1]]) if rect not in items: items.append(rect) for item in items: cv.rectangle(o_img, item[0], item[1], (0, 0, 255), 1) return items def bury_bones(min_bone_count): inv_img, bones = inv.get_item_rects(inv.get_icon(526)) inv_img2, big_bones = inv.get_item_rects(inv.get_icon(532)) if len(bones) + len(big_bones) > min_bone_count: for rect in bones: rect[0] pt = ((rect[0][0] + 625 + rect[1][0] + 625) / 2, (rect[0][1] + 485 + rect[1][1] + 485) / 2) pyautogui.moveTo(pt) pyautogui.click(clicks=1, interval=random() * 3, button='left') for rect in big_bones: rect[0] pt = ((rect[0][0] + 625 + rect[1][0] + 625) / 2, (rect[0][1] + 485 + rect[1][1] + 485) / 2) pyautogui.moveTo(pt) pyautogui.click(clicks=1, interval=random() * 3, button='left') def start(targets, items, players, target_mask, selected): combat_img = ImageGrab.grab(bbox=[10, 50, 140, 69]) enemy_name = pytesseract.image_to_string(combat_img) for name in marked_enemy_names: if enemy_name != None: if similar(enemy_name, name) > 0.7: enemy_name = name min_dist = 3000 other_players_target = None for r in targets: for p in players: dist = math.sqrt(math.pow(r[0] - p[0][0], 2) + math.pow(r[1] - p[0][1], 2)) if p in items: players.remove(p) if dist < 200: if r in targets: if (dist < min_dist): if r[2] > 30: other_players_target = r targets.remove(r) continue if r[2] > 10 and r in targets: cv.rectangle(target_mask, (r[0], r[1]), (r[0] + r[2], r[1] + r[3]), (0, 255, 255), 2) if other_players_target is not None: if len(players) >= 1: if players[0] not in items: cv.line(target_mask, (other_players_target[0], other_players_target[1]), (players[0][0][0], players[0][0][1]), (0, 255, 255), 2) cv.rectangle(target_mask, (other_players_target[0], other_players_target[1]), ( other_players_target[0] + other_players_target[2], other_players_target[1] + other_players_target[3]), (0, 40, 255), 2) if random() > 0.95: bury_bones(0) if enemy_name not in marked_enemy_names: if len(items) >= 1: # item pickup item = items[0] min = item[0] max = item[1] pyautogui.moveTo((min[0] + max[0]) / 2, ((min[1] + max[1]) / 2) + 10) pyautogui.click(clicks=2, interval=random(), button='left') elif len(rects[4]) > 0: # need combat panel screengrab and imagetotext # if in combat dont move cursor or click # if selected != targets[0]: selected = targets[0] pyautogui.moveTo((selected[0] + selected[2] / 2), (selected[1] + selected[3] / 2)) pyautogui.click(button='left', clicks=1, interval=random())
009988b/2007scape-bot-functions
skills/combat.py
combat.py
py
5,029
python
en
code
0
github-code
6
30864499352
import numpy as np n=np.genfromtxt('matrix1.csv',delimiter=',') import numpy as ap a=ap.genfromtxt('inmat.csv',delimiter=' ') import numpy as bp b=bp.genfromtxt('outmat.csv',delimiter=' ') k=n[:,0:7] k1=n[:,8:83] p=[sum(k[i]) for i in range(83)] p1=[sum(k1[i]) for i in range(83)] cluster1=[] cluster2=[] cluster3=[] cluster4=[] for i in range(len(p)): if p1[i]<=5*p[i] and a[i]<=3 and b[i]<=3: cluster1.append(i) elif p1[i]<=6*p[i] and a[i]<=3 and b[i]<=3: cluster2.append(i) elif p1[i]<=7*p[i] and a[i]<=3 and b[i]<=3: cluster3.append(i) else: cluster4.append(i) len(cluster1) len(cluster2) len(cluster3) len(cluster4) print("cluster1") cluster1 print("cluster2") cluster2 print("cluster3") cluster3 print("cluster4") cluster4
mdaksamvk/drug-target-identification-clustering-and-local-resistance-analysis
cluster_analysis.py
cluster_analysis.py
py
801
python
en
code
1
github-code
6
6259690746
from enum import Enum import numpy as np from collections import deque import bisect from numpy.core.numeric import array_equal from graphics import GraphWin, Text, Point, Rectangle, Circle, Line, Polygon, update, color_rgb # +-------+ # | 16 17 | # | 18 19 | # +-------+-------+-------+-------+ # | 12 13 | 0 1 | 4 5 | 8 9 | # | 14 15 | 2 3 | 6 7 | 10 11 | # +-------+-------+-------+-------+ # | 20 21 | # | 22 23 | # +-------+ # # 0 -> blue 1 -> white 2 -> green 3 -> yellow 4 -> red 5 -> orange CELL_SIZE = 60 # Size in pixels of each square cell in the GUI (20 x 12 cells) NUM_CELLS = (20, 12) # Size of the GUI in terms of cells (columns, rows) CUBE_COLORS = [color_rgb(0, 0, 200), color_rgb(230, 230, 230), color_rgb(0, 200, 0), color_rgb(255, 255, 50), color_rgb(220, 30, 30), color_rgb(255, 150, 30)] SQUARE_POS = [(11, 4), (12, 4), (11, 5), (12, 5), (14, 4), (15, 4), (14, 5), (15, 5), (17, 4), (18, 4), (17, 5), (18, 5), (8, 4), (9, 4), (8, 5), (9, 5), (11, 1), (12, 1), (11, 2), (12, 2), (11, 7), (12, 7), (11, 8), (12, 8)] SURFACE_LABELS = ['FRONT', 'RIGHT', 'BACK', 'LEFT', 'TOP', 'BOTTOM'] LABEL_POS = [(11.5, 3.2), (14.5, 3.2), (17.5, 3.2), (8.5, 3.2), (11.5, 0.2), (11.5, 6.2)] LINE_COLOR = color_rgb(255, 255, 255) BUTTON_COLOR = color_rgb(70, 70, 70) HISTORY_COLOR = color_rgb(0, 0, 0) SCORE_COLOR = color_rgb(200, 200, 200) HISTORY_ORIGIN_X = 7 MOVE_EFFECTS = np.array([ [ 2, 0, 3, 1, 18, 5, 19, 7, 8, 9, 10, 11, 12, 20, 14, 21, 16, 17, 15, 13, 6, 4, 22, 23], [ 3, 2, 1, 0, 15, 5, 13, 7, 8, 9, 10, 11, 12, 6, 14, 4, 16, 17, 21, 20, 19, 18, 22, 23], [ 1, 3, 0, 2, 21, 5, 20, 7, 8, 9, 10, 11, 12, 19, 14, 18, 16, 17, 4, 6, 13, 15, 22, 23], [16, 1, 18, 3, 4, 5, 6, 7, 8, 22, 10, 20, 14, 12, 15, 13, 11, 17, 9, 19, 0, 21, 2, 23], [11, 1, 9, 3, 4, 5, 6, 7, 8, 2, 10, 0, 15, 14, 13, 12, 20, 17, 22, 19, 16, 21, 18, 23], [20, 1, 22, 3, 4, 5, 6, 7, 8, 18, 10, 16, 13, 15, 12, 14, 0, 17, 2, 19, 11, 21, 9, 23], [ 4, 5, 2, 3, 8, 9, 6, 7, 12, 13, 10, 11, 0, 1, 14, 15, 18, 16, 19, 17, 20, 21, 22, 23], [ 8, 9, 2, 3, 12, 13, 6, 7, 0, 1, 10, 11, 4, 5, 14, 15, 19, 18, 17, 16, 20, 21, 22, 23], [12, 13, 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 17, 19, 16, 18, 20, 21, 22, 23]], dtype=np.uint8) AXES = ['FRONT', 'LEFT', 'TOP'] ROTATIONS = ['CW', '180', 'CCW'] MOVE_COLORS = [color_rgb(0, 50, 50), color_rgb(0, 100, 100), color_rgb(0, 150, 150), color_rgb(50, 50, 0), color_rgb(70, 70, 0), color_rgb(90, 90, 0), color_rgb(50, 0, 50), color_rgb(100, 0, 100), color_rgb(150, 0, 150)] OPPOSING_SURFACES = [2, 3, 0, 1, 5, 4] neighbor_x1 = np.array([0, 2, 8, 10, 16, 18, 20, 22], dtype=np.int) neighbor_x2 = np.array([1, 3, 9, 11, 17, 19, 21, 23], dtype = np.int) neighbor_y1 = np.array([0, 1, 4, 5, 8, 9, 12, 13], dtype=np.int) neighbor_y2 = np.array([2, 3, 6, 7, 10, 11, 14, 15], dtype = np.int) neighbor_z1 = np.array([4, 6, 12, 14, 16, 17, 20, 21], dtype=np.int) neighbor_z2 = np.array([5, 7, 13, 15, 18, 19, 22, 23], dtype = np.int) neighbor1 = np.array([0, 0, 1, 2, 4, 4, 5, 6, 8, 8, 9, 10, 12, 12, 13, 14, 16, 16, 17, 18, 20, 20, 21, 22], dtype=np.int) neighbor2 = np.array([1, 2, 3, 3, 5, 6, 7, 7, 9, 10, 11, 11, 13, 14, 15, 15, 17, 18, 19, 19, 21, 22, 23, 23], dtype = np.int) start_state_9_moves = np.array([0, 1, 4, 0, 4, 2, 1, 0, 5, 4, 5, 5, 1, 3, 1, 2, 2, 3, 4, 0, 3, 5, 2, 3], dtype=np.uint8) #start_state_x = np.array([0, 1, 4, 0, 4, 2, 1, 0, 5, 4, 5, 5, 1, 3, 1, 2, 2, 3, 4, 0, 3, 5, 2, 3], dtype=np.uint8) start_state_x = np.array([0, 2, 3, 4, 1, 2, 2, 0, 3, 1, 3, 1, 0, 5, 0, 2, 5, 4, 3, 5, 5, 1, 4, 4], dtype=np.uint8) start_state_easy = np.array([1, 1, 0, 0, 2, 2, 1, 1, 3, 3, 2, 2, 0, 0, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5], dtype=np.uint8) start_state_11_moves = np.array([0, 0, 0, 0, 3, 3, 3, 1, 2, 2, 2, 2, 3, 1, 1, 1, 4, 5, 5, 5, 4, 4, 4, 5], dtype=np.uint8) perfect_state = np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5], dtype=np.uint8) class HistoryEntry(object): __slots__ = ['operation', 'new_state', 'new_score'] #start_state = perfect_state.copy() start_state = start_state_9_moves.copy() goal_state = [] def coords(x_cell, y_cell, center=False): return Point(int(min(NUM_CELLS[0] * CELL_SIZE - 1, (x_cell + 0.5 * center) * CELL_SIZE)), int((y_cell + 0.5 * center) * CELL_SIZE)) def draw_square(x, y, col): r = Rectangle(coords(x, y), coords(x + 1, y + 1)) r.setFill(col) r.setWidth(1) r.setOutline(LINE_COLOR) r.draw(win) def draw_button(x, y, col=LINE_COLOR, dict_entry=(-1, -1)): global button_dict button_dict[x, y] = dict_entry draw_square(x, y, col) def draw_text(x, y, text, col=LINE_COLOR, text_size = 12): t = Text(coords(x, y, center=True), text) t.setFace('arial') t.setSize(int(CELL_SIZE / 60.0 * text_size)) t.setTextColor(col) t.draw(win) def draw_transition_button(x, y, operation, draw_in_history=False): if draw_in_history: button_dict_entry = ('history_jump', x - HISTORY_ORIGIN_X) else: button_dict_entry = operation if operation[0] == 'make_move': draw_button(x, y, MOVE_COLORS[operation[1]], button_dict_entry) draw_text(x, y - 0.2, AXES[operation[1] // 3]) draw_text(x, y + 0.2, ROTATIONS[operation[1] % 3]) elif operation[0] == 'cube_edit': draw_button(x, y, BUTTON_COLOR, button_dict_entry) draw_text(x, y - 0.2, 'CUBE') draw_text(x, y + 0.2, 'EDIT') elif operation[0] == 'start_state': draw_button(x, y, BUTTON_COLOR, button_dict_entry) draw_text(x, y - 0.2, 'START') draw_text(x, y + 0.2, 'STATE') elif operation[0] == 'perfect_state': draw_button(x, y, BUTTON_COLOR, button_dict_entry) draw_text(x, y - 0.2, 'PERFECT', text_size=9) draw_text(x, y + 0.2, 'STATE') else: draw_button(x, y, color_rgb(0, 0, 0), button_dict_entry) def display_GUI(): win.delete('all') for y in range(3): for x in range(3): draw_transition_button(2 * x + 1, 2 * y + 1, ('make_move', 3 * y + x)) for sq in range(len(SQUARE_POS)): draw_button(SQUARE_POS[sq][0], SQUARE_POS[sq][1], CUBE_COLORS[curr_state[sq]], ('cube_edit', sq)) for i in range(6): draw_text(LABEL_POS[i][0], LABEL_POS[i][1], SURFACE_LABELS[i]) draw_button(1, 8, BUTTON_COLOR, ('solve', 0)) draw_button(2, 8, BUTTON_COLOR, ('solve', 0)) draw_button(3, 8, BUTTON_COLOR, ('solve', 0)) r = Rectangle(coords(1, 8), coords(4, 9)) r.setFill(BUTTON_COLOR) r.setWidth(1) r.setOutline(LINE_COLOR) r.draw(win) draw_text(2, 8, 'SOLVE !', LINE_COLOR, 20) draw_button(HISTORY_ORIGIN_X - 1, 8, HISTORY_COLOR, ('history_jump', -1)) draw_text(HISTORY_ORIGIN_X - 1, 7.7, 'BACK', text_size=8) p = Polygon([coords(HISTORY_ORIGIN_X - 0.8, 8.6), coords(HISTORY_ORIGIN_X - 0.2, 8.3), coords(HISTORY_ORIGIN_X - 0.2, 8.9)]) p.setFill(BUTTON_COLOR) p.setWidth(1) p.setOutline(LINE_COLOR) p.draw(win) draw_button(HISTORY_ORIGIN_X, 8, HISTORY_COLOR, ('history_jump', 1)) draw_text(HISTORY_ORIGIN_X, 7.7, 'FWD', text_size=8) p = Polygon([coords(HISTORY_ORIGIN_X + 0.8, 8.6), coords(HISTORY_ORIGIN_X + 0.2, 8.3), coords(HISTORY_ORIGIN_X + 0.2, 8.9)]) p.setFill(BUTTON_COLOR) p.setWidth(1) p.setOutline(LINE_COLOR) p.draw(win) for x in range(NUM_CELLS[0]): history_index = history_pointer + x - HISTORY_ORIGIN_X if history_index >= 0 and history_index < len(history) - 1: operation = history[history_index + 1].operation else: operation = ('', 0) draw_transition_button(x, 10, operation, draw_in_history=True) if history_index >= 0 and history_index < len(history): sc = history[history_index].new_score sc_color = SCORE_COLOR if sc == 0: sc_color = LINE_COLOR draw_text(x - 0.5, 10.8, '%.1f'%(sc)) l = Line(coords(HISTORY_ORIGIN_X, 8), coords(HISTORY_ORIGIN_X, 11)) l.setWidth(3) l.setFill(LINE_COLOR) l.draw(win) draw_transition_button(15, 1, ('start_state', 0)) draw_transition_button(17, 1, ('perfect_state', 0)) draw_button(15, 8, BUTTON_COLOR, ('random_move', 0)) draw_text(15, 7.8, 'RANDOM', text_size=10) draw_text(15, 8.2, 'MOVE') draw_button(17, 8, BUTTON_COLOR, ('quit', 0)) draw_text(17, 8, 'QUIT') update() # Get cell coordinates of the button clicked by the user def get_clicked_button(): while True: clickPos = win.getMouse() cell_x = int(clickPos.x / CELL_SIZE) cell_y = int(clickPos.y / CELL_SIZE) if cell_x >= 0 and cell_x < NUM_CELLS[0] and cell_y >= 0 and cell_y < NUM_CELLS[1]: return (cell_x, cell_y) class analyze: def __init__(self, state, goal): self.h = 0 self.state = state self.goal = goal # self.h = self.calcHam() self.s_cu_1 = (state[0],state[13], state[18]) self.s_cu_2 = (state[1], state[4], state[19]) self.s_cu_3 = (state[2], state[15], state[20]) self.s_cu_4 = (state[3], state[6], state[21]) self.s_cu_5 = (state[8], state[12], state[17]) self.s_cu_6 = (state[9], state[7], state[16]) self.s_cu_7 = (state[10], state[7], state[23]) self.s_cu_8 = (state[11], state[14], state[22]) self.g_cu_1 = (goal[0],goal[13], goal[18]) self.g_cu_2 = (goal[1], goal[4], goal[19]) self.g_cu_3 = (goal[2], goal[15], goal[20]) self.g_cu_4 = (goal[3], goal[6], goal[21]) self.g_cu_5 = (goal[8], goal[12], goal[17]) self.g_cu_6 = (goal[9], goal[7], goal[16]) self.g_cu_7 = (goal[10], goal[7], goal[23]) self.g_cu_8 = (goal[11], goal[22], goal[14]) self.m = self.calcMan() self.h = self.calcHam() self.m += self.h #self.h = self.calcHam() def calcHam(self): h = 0 for i in range(len(self.state)): if self.state[i] == self.goal[i]: h += 1 return h def calcMan(self): m = self.calcMiniCube(self.s_cu_1, self.g_cu_1) m += self.calcMiniCube(self.s_cu_2, self.g_cu_2) m += self.calcMiniCube(self.s_cu_3, self.g_cu_3) m += self.calcMiniCube(self.s_cu_4, self.g_cu_4) m += self.calcMiniCube(self.s_cu_5, self.g_cu_5) m += self.calcMiniCube(self.s_cu_6, self.g_cu_6) m += self.calcMiniCube(self.s_cu_7, self.g_cu_7) m += self.calcMiniCube(self.s_cu_8, self.g_cu_8) return m def calcMiniCube(self, s_cube, g_cube): i = 0 i += s_cube[0] + g_cube[0] i += s_cube[1] + g_cube[1] i += s_cube[2] + g_cube[2] return i """ I don't know, can you run. Let's do this. We know that the vector has 8 cubes (tuples) """ def can_you_run(self): m = 0 m += self.calcMiniCube(self.g_cu_1, self.s_cu_1) m += self.calcMiniCube(self.g_cu_2, self.s_cu_2) m += self.calcMiniCube(self.g_cu_3, self.s_cu_3) m += self.calcMiniCube(self.g_cu_4, self.s_cu_4) m += self.calcMiniCube(self.g_cu_5, self.s_cu_5) m += self.calcMiniCube(self.g_cu_6, self.s_cu_6) m += self.calcMiniCube(self.g_cu_7, self.s_cu_7) m += self.calcMiniCube(self.g_cu_8, self.s_cu_8) # def can_you_say_run(self): # # for def get_h_prime(state, goal): if np.array_equal(state, goal): return 0 else: h = analyze(state, goal).h return h def expand_rubik(last_move, state, goal): if last_move == -1: move_range = range(0, 9) elif last_move < 3: move_range = range(3, 9) elif last_move < 6: move_range = [0, 1, 2, 6, 7, 8] else: move_range = range(0, 6) new_nodes = [] for move in move_range: new_state = state[MOVE_EFFECTS[move]] h_prime = get_h_prime(new_state, goal) new_nodes += [(move, new_state, h_prime)] return new_nodes def a_star(start, goal, expand): open_nodes = deque([(-1, start.tobytes())]) # For each node on the OPEN list, keep its f'-score and a key for looking up its path from the start state (root) counter = 0 node_dictionary = {start.tobytes(): []} while open_nodes: last_score, state_code = open_nodes.popleft() move_seq = node_dictionary[state_code] # Associate every state encountered with the shortest path to reach it (that we have found so far) state = np.frombuffer(state_code, dtype=np.uint8) if len(move_seq) == 0: last_move = -1 else: last_move = move_seq[-1] new_nodes = expand(last_move, state, goal) new_node_depth = len(move_seq) + 1 counter += 1 if counter % 1000 == 0: print('Iterations: %d, nodes in list: %d, winner node depth: %d, score: %f'%(counter, len(open_nodes), new_node_depth, last_score)) for (new_move, new_state, h_prime) in new_nodes: if h_prime == 0: return move_seq + [new_move] new_state_code = new_state.tobytes() if not (new_state_code in node_dictionary) or len(node_dictionary[new_state_code]) > new_node_depth: node_dictionary[new_state_code] = move_seq + [new_move] f_prime = new_node_depth + h_prime # We now need to keep f' rather than h' on open_node_scores for correct sorting bisect.insort_left(open_nodes, (f_prime, new_state_code)) return [] def rubik_solver(): set_goal_state(curr_state) solution_moves = a_star(curr_state, goal_state, expand_rubik) return solution_moves def set_goal_state(curr_state): global goal_state goal_state = np.zeros(24, dtype=np.uint8) goal_state[4:8] = curr_state[7] goal_state[8:12] = curr_state[10] goal_state[20:24] = curr_state[23] goal_state[12:16] = OPPOSING_SURFACES[curr_state[7]] goal_state[0:4] = OPPOSING_SURFACES[curr_state[10]] goal_state[16:20] = OPPOSING_SURFACES[curr_state[23]] win = GraphWin("Rubik's 2x2x2 Cube Lab for Mad Computer Scientists", NUM_CELLS[0] * CELL_SIZE, NUM_CELLS[1] * CELL_SIZE, autoflush=False) win.setBackground('black') curr_state = start_state.copy() set_goal_state(curr_state) initial_history = HistoryEntry() initial_history.operation = ('', 0) initial_history.new_state = start_state.copy() initial_history.new_score = get_h_prime(start_state, goal_state) history = [initial_history] history_pointer = 0 button_dict = dict() while True: display_GUI() x, y = get_clicked_button() if (x, y) in button_dict: expand_history = False action = button_dict[(x, y)][0] param = button_dict[(x, y)][1] if action == 'quit': break elif action == 'solve': if get_h_prime(curr_state, goal_state) > 0: solution = rubik_solver() expand_history = True elif action == 'history_jump': if history_pointer + param >= 0 and history_pointer + param < len(history): history_pointer += param curr_state = history[history_pointer].new_state elif action == 'cube_edit': curr_state[param] = (curr_state[param] + 1) % 6 expand_history = True elif action == 'start_state': curr_state = start_state.copy() expand_history = True elif action == 'perfect_state': curr_state = perfect_state.copy() expand_history = True elif action == 'random_move': action = 'make_move' param = np.random.randint(9) if action == 'make_move': curr_state = curr_state[MOVE_EFFECTS[param]] expand_history = True set_goal_state(curr_state) if expand_history: if history_pointer < len(history) - 1: history = history[:history_pointer + 1] if action == 'cube_edit' and history[history_pointer].operation[0] == 'cube_edit': history[history_pointer].new_state = curr_state.copy() history[history_pointer].new_score = get_h_prime(curr_state, goal_state) elif action == 'solve': temp_state = curr_state.copy() for move in solution: temp_state = temp_state[MOVE_EFFECTS[move]] new_entry = HistoryEntry() new_entry.operation = ('make_move', move) new_entry.new_state = temp_state.copy() new_entry.new_score = get_h_prime(temp_state, goal_state) history.append(new_entry) else: new_entry = HistoryEntry() new_entry.operation = (action, param) new_entry.new_state = curr_state.copy() new_entry.new_score = get_h_prime(curr_state, goal_state) history.append(new_entry) history_pointer += 1 win.close()
danemo01/CS470
HW4/rubik_lab_assignment_4.py
rubik_lab_assignment_4.py
py
17,458
python
en
code
0
github-code
6
9765699442
def linear_search(array, item): # It returns the index if the item is in the list or None if isn't for i in range(len(array)): if array[i] == item: return i return None ### Worse case is the size list, therefore 0(N), linear function ### Interaction with user bellow array1 = [1,2,3,4,6,7,8,9,10,11,12,13,14,15,15] item = int(input('What is the number that are you searching for?')) result = linear_search(array1, item) if result is None: print("This number wasn't found") else: print(f'This number index is: {result}')
joaocarvoli/datastructures-ufc
in-python/3.sort-and-search-algorithms/linear_search.py
linear_search.py
py
572
python
en
code
0
github-code
6
10976102669
import numpy as np import matplotlib.pyplot as plt def linear_LS(xi, yi): a = np.empty(2) n = xi.shape[0] c0 = np.sum(xi) c1 = np.sum(xi ** 2) c2 = np.sum(yi) c3 = np.sum(xi * yi) a[0] = (c0*c3 - c1*c2) / (c0*c0 - n*c1) a[1] = (c0*c2 - n*c3) / (c0*c0 - n*c1) return a def parabolic_LS(xi, yi): n = xi.shape[0] x1 = np.sum(xi) x2 = np.sum(xi ** 2) x3 = np.sum(xi ** 3) x4 = np.sum(xi ** 4) y1 = np.sum(yi) x1y1 = np.sum(xi * yi) x2y1 = np.sum(xi**2 * yi) A_mat = np.array([[n, x1, x2], [x1, x2, x3], [x2, x3, x4]]) b_vec = np.array([y1, x1y1, x2y1]) a_vec = np.linalg.solve(A_mat, b_vec) return a_vec def sketch(x, y, flag): if flag == 1: name = "linear" else: name = "parabolic" plt.plot(x, y, label=name) plt.xlabel("x") plt.ylabel("T") plt.grid() plt.legend() def scatter(x, y): plt.scatter(x, y, label="data", color="black") plt.xlabel("x") plt.ylabel("T") plt.grid() plt.legend() def main(): distance = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]) temperature = np.array([14.6, 18.5, 36.6, 30.8, 59.2, 60.1, 62.2, 79.4, 99.9]) scatter(distance, temperature) x_plot = np.linspace(0, 10, 100) coef = linear_LS(distance, temperature) y_plot = coef[0] + coef[1]*x_plot print(coef) sketch(x_plot, y_plot, 1) x_plot = np.linspace(0, 10, 100) coef = parabolic_LS(distance, temperature) y_plot = coef[0] + coef[1]*x_plot + coef[2]*x_plot**2 print(coef) sketch(x_plot, y_plot, 2) plt.show() if __name__ == '__main__': main() input("请按任意键以继续......")
LiBingbin/Computational_Physics
PythonProject/hw04/hw04_t2.py
hw04_t2.py
py
1,781
python
en
code
0
github-code
6
3045998741
from fastapi import HTTPException, status from app.v1.model.user_model import User as UserModel from app.v1.schema import user_schema from app.v1.service.auth_service import get_password_hash from app.v1.service import registered_developers_service from app.v1.schema.registered_developers_schema import RegisteredDeveloper from app.v1.schema.validation_fk_schema import ValidationFk def create_user(user: user_schema.UserRegister): get_user = UserModel.filter((UserModel.email == user.email) | (UserModel.username == user.username)).first() if get_user: msg = "Email already registered" if get_user.username == user.username: msg = "Username already registered" raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=msg, ) # developer db_user = UserModel( email = user.email, username = user.username, password = get_password_hash(user.password), is_admin = False, is_manager = False, is_developer = True, ) db_user.save() return user_schema.User( id=db_user.id, email=db_user.email, username= db_user.username, is_admin= db_user.is_admin, is_manager=db_user.is_manager, is_developer=db_user.is_developer, ) def admin_create_user(user: user_schema.AdminRegisterUsers): get_user = UserModel.filter((UserModel.email == user.email) | (UserModel.username == user.username)).first() if get_user: msg = "Email already registered" if get_user.username == user.username: msg = "Username already registered" raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=msg, ) # developer db_user = UserModel( email = user.email, username = user.username, password = get_password_hash(user.password), is_admin = user.is_admin, is_manager = user.is_manager, is_developer = user.is_developer, ) db_user.save() return user_schema.User( id=db_user.id, email=db_user.email, username= db_user.username, is_admin= db_user.is_admin, is_manager=db_user.is_manager, is_developer=db_user.is_developer, ) def update_user(user_id:int,update_user:user_schema.AdminRegisterUsers): user=UserModel.filter(UserModel.id == user_id).first() if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="user not found" ) get_same_email = update_user.email == user.email get_same_username=update_user.username == user.username if not get_same_username: get_user = UserModel.filter(UserModel.username == update_user.username).first() if get_user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Username already registered in another user" ) if not get_same_email: get_user = UserModel.filter(UserModel.email == update_user.email).first() if get_user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered in another user" ) # developer db_user = UserModel( id=user_id, email = update_user.email, username = update_user.username, password = get_password_hash(update_user.password), is_admin = update_user.is_admin, is_manager = update_user.is_manager, is_developer = update_user.is_developer, ) db_user.save() return user_schema.User( id=db_user.id, email=db_user.email, username= db_user.username, is_admin= db_user.is_admin, is_manager=db_user.is_manager, is_developer=db_user.is_developer, ) def get_users(): users = UserModel.filter((UserModel.username != '')) list_users = [] for user in users: list_users.append( user_schema.User( id=user.id, email=user.email, username= user.username, is_admin= user.is_admin, is_manager=user.is_manager, is_developer=user.is_developer, ) ) return list_users def get_user(user_id: int): user = UserModel.filter(UserModel.id == user_id).first() if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="user not found" ) return user_schema.User( id=user.id, email=user.email, username= user.username, is_admin= user.is_admin, is_manager=user.is_manager, is_developer=user.is_developer, ) def check_user_as_fk(user_id:int): user = UserModel.filter(UserModel.id == user_id).first() if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="user not found" ) registered_developer = registered_developers_service.get_registered_developer_by_user_id(user_id) #print(registered_developer) if registered_developer: return ValidationFk( table_name="registered_developer", list_registers=registered_developer ) else: return ValidationFk( table_name="registered_developer", list_registers=False, ) def update_role_user(user_id: int,roles: user_schema.UpdateRoles): user = UserModel.filter(UserModel.id == user_id).first() if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="user not found" ) user.is_manager=roles.is_manager user.is_admin=roles.is_admin user.is_developer=roles.is_developer user.save() return user_schema.User( id=user.id, email=user.email, username= user.username, is_admin= user.is_admin, is_manager=user.is_manager, is_developer=user.is_developer, ) def update_password(user_id: int,password_update:user_schema.UpdatePassword): user = UserModel.filter(UserModel.id == user_id).first() if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="user not found" ) user.password=get_password_hash(password_update.password) user.save() return user_schema.User( id=user.id, email=user.email, username= user.username, is_admin= user.is_admin, is_manager=user.is_manager, is_developer=user.is_developer, ) def delete_user(user_id: int,current_user_id:int): if user_id == current_user_id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="cannot delete current user" ) else: user = UserModel.filter(UserModel.id == user_id).first() if not user: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="user not found" ) ValidationFk = check_user_as_fk(user_id) #print(ValidationFk) if ValidationFk: if isinstance(ValidationFk.list_registers,RegisteredDeveloper): registered_developer = ValidationFk.list_registers try: registered_developers_service.delete_registered_developer(registered_developer.id) except: print(f"registered developer {registered_developer} was not deleted") user.delete_instance()
marianamartineza/kunaisoft-database-CRUD-fastapi
app/v1/service/user_service.py
user_service.py
py
7,752
python
en
code
0
github-code
6
22966971345
# -*- coding: utf-8 -*- """ Created on Sun Jul 12 05:51:48 2020 @author: Souhardya """ class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def push(self,new_data): new_node=Node(new_data) new_node.next=self.head self.head=new_node def PrintNthFromLast(self,n): length=0 temp=self.head while temp!=None: length=length +1 temp=temp.next if n>length: print('List Out of Index') else: temp=self.head for i in range(length-n): temp=temp.next return (temp.data) ll = LinkedList() ll.push(20) ll.push(4) ll.push(15) ll.push(35) print(ll.PrintNthFromLast(3))
souhardya1/Single-LinkedList-in-python
Print Nth item from last in Single Linked List.py
Print Nth item from last in Single Linked List.py
py
857
python
en
code
0
github-code
6
34416507045
from setuptools import setup, find_packages with open('requirements.txt') as f: reqs = f.read().split() with open('README.md') as f: readme = f.read() setup( name='trackthenews', version='0.1.9.1', description='Monitor RSS feeds for keywords and act on matching results. A special project of the Freedom of the Press Foundation.', long_description=readme, long_description_content_type='text/markdown', install_requires=reqs, author='Ben Jay (original by Parker Higgins at [email protected])', author_email='[email protected]', url='https://github.com/freedomofpress/trackthenews', entry_points={ 'console_scripts': ['trackthenews=trackthenews:main'] }, package_data={ 'trackthenews': ['fonts/*'] }, include_package_data=True, license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6'], packages=find_packages(exclude=('ttnconfig',)) )
fakebenjay/trackthenews-lefty
setup.py
setup.py
py
1,096
python
en
code
0
github-code
6
13442681959
# -*- coding: utf-8 -*- """Module containing network adapter for socket (asyncore.dispacher).""" import logging import socket import struct import asyncore from collections import deque from .. import connection, server, client from .._utils import lazyproperty _logger = logging.getLogger(__name__) _connect_struct = struct.Struct('!I') class Dispacher(asyncore.dispatcher, object): pass class Connection(connection.Connection, Dispacher): # maximum amount of data received / sent at once recv_buffer_size = 4096 def __init__(self, parent, socket, message_factory, *args, **kwargs): super(Connection, self).__init__( parent, socket, message_factory, socket, None, * args, **kwargs) #self.send_queue = deque() self.send_buffer = bytearray() #self.recv_buffer = bytearray(b'\0' * self.recv_buffer_size) def _send_data(self, data, **kwargs): self.send_buffer.extend(data) self._send_part() # def _send_data2(self, data, **kwargs): # if len(self.send_buffer) == 0: # self.send_buffer = data # else: # self.send_queue.append(data) # self._send_part() def handle_write(self): self._send_part() def _send_part(self): try: num_sent = asyncore.dispatcher.send(self, self.send_buffer) except socket.error: self.handle_error() return self.send_buffer = self.send_buffer[num_sent:] def writable(self): return (not self.connected) or len(self.send_buffer) def handle_read(self): data = self.recv(self.recv_buffer_size) if data: self._receive(data) # def handle_read2(self): # # tinkering with dispatcher internal variables, # # because it doesn't support socket.recv_into # try: # num_rcvd = self.socket.recv_into(self.recv_buffer) # if not num_rcvd: # self.handle_close() # else: # self._receive(self.recv_buffer[:num_rcvd]) # except socket.error, why: # if why.args[0] in asyncore._DISCONNECTED: # self.handle_close() # else: # self.handle_error() # return def handle_connect(self): self._connect() def handle_close(self): self._disconnect() self.close() def log_info(self, message, type='info'): return getattr(_logger, type)(message) def disconnect(self, *args): self._disconnect() self.close() @lazyproperty def address(self): return self.socket.getpeername() class Server(server.Server, Dispacher): connection = Connection def __init__(self, host='', port=0, conn_limit=4, handler=None, message_factory=None, *args, **kwargs): super(Server, self).__init__( host, port, conn_limit, handler, message_factory, None, None, *args, **kwargs) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # disable Nagle buffering algorithm self.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.set_reuse_addr() self.bind((host, port)) self.listen(conn_limit) def _create_connection(self, socket, message_factory): connection = Connection(self, socket, message_factory) return connection, socket.fileno() def handle_accept(self): pair = self.accept() if pair is not None: sock, addr = pair # TODO: sth better? sock.settimeout(0.5) # enable blocking read with 0.5s timeout try: data = sock.recv(4) # wait for hash data mf_hash = _connect_struct.unpack(data)[0] sock.setblocking(0) # disable blocking read if self._accept(sock, addr, mf_hash): return # end if hash is correct except socket.timeout: _logger.info('Connection with %s refused, MessageFactory' ' hash not received', addr) sock.shutdown(socket.SHUT_RDWR) sock.close() def update(self, timeout=0): asyncore.loop(timeout / 1000.0, False, None, 1) @lazyproperty def address(self): return self.socket.getsockname() class Client(client.Client): def __init__(self, conn_limit=0, *args, **kwargs): super(Client, self).__init__(*args, **kwargs) self._sock_cnt = 0 def _create_connection(self, host, port, message_factory, **kwargs): connection = Connection(self, None, message_factory) connection.create_socket(socket.AF_INET, socket.SOCK_STREAM) # disable Nagle buffering algorithm connection.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) connection.connect((host, port)) connection._send_data(_connect_struct.pack(message_factory.get_hash())) return connection, connection.socket.fileno() def update(self, timeout=0): asyncore.poll(timeout / 1000.0, self.conn_map)
Occuliner/ThisHackishMess
extern_modules/pygnetic/network/socket_adapter.py
socket_adapter.py
py
5,296
python
en
code
2
github-code
6
46057888236
# -*- coding: utf-8 -*- import logging import datetime import pytz __all__ = ['timezones'] logger = logging.getLogger('django') def is_standard_time(time_zone, date_time): try: dst_delta = time_zone.dst(date_time, is_dst=False) except TypeError: dst_delta = time_zone.dst(date_time) return dst_delta == datetime.timedelta(0) def utc_offset(time_zone, fixed_dt=None): tz = pytz.timezone(time_zone) now = fixed_dt or datetime.datetime.now() for __ in range(72): if is_standard_time(time_zone=tz, date_time=now): break now += datetime.timedelta(days=30) else: logger.warning( 'Standard Time not found for %s, will use DST.' % time_zone) return tz.localize(now, is_dst=False).strftime('%z') def offset_to_int(offset): assert offset[0] in ('-', '+') sign, hour, minutes = offset[0], offset[1:3], offset[3:5] utc_offset_int = int(hour) + int(minutes) / 100 if sign == '-': utc_offset_int *= -1 return utc_offset_int def timezones_by_offset(): return sorted( ((utc_offset(tz), tz) for tz in pytz.common_timezones), key=lambda x: (offset_to_int(x[0]), x[1])) def timezone_format(time_zone, offset): zone_parts = time_zone.split('/') zone = zone_parts[0] if len(zone_parts) > 1: zone_label = ', '.join(zone_parts[1:]).replace('_', ' ') else: zone_label = zone return zone, '(UTC{}) {}'.format(offset, zone_label) def timezones(): """ Result format:: [ ("Africa", [ ("Africa/Abidjan", "(UTC...) Abidjan"), ("Africa/Accra", "(UTC...) Accra"), #... ]), ("America", [ ("America/Argentina/Buenos_Aires", "(UTC...) Argentina, Buenos Aires"), #... ]), #... ] """ timezones_cache = {} for offset, time_zone in timezones_by_offset(): zone, pretty_time_zone = timezone_format(time_zone, offset) (timezones_cache .setdefault(zone, []) .append((time_zone, pretty_time_zone))) return sorted( timezones_cache.items(), key=lambda x: x[0])
nitely/Spirit
spirit/core/utils/timezone.py
timezone.py
py
2,280
python
en
code
1,153
github-code
6
7192437436
import datetime import hashlib import json import yaml import flask.json import shutil import subprocess import uuid import zipfile import click import os from flask.cli import AppGroup import requests from sqlalchemy.orm import load_only from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.exc import IntegrityError from algoliasearch import algoliasearch from .utils import id_generator, algolia_app from .models import Category, db, App, Developer, Release, CompanionApp, Binary, AssetCollection, LockerEntry, UserLike from .pbw import PBW, release_from_pbw from .s3 import upload_pbw, upload_asset from .settings import config if config['ALGOLIA_ADMIN_API_KEY']: algolia_client = algoliasearch.Client(config['ALGOLIA_APP_ID'], config['ALGOLIA_ADMIN_API_KEY']) algolia_index = algolia_client.init_index(config['ALGOLIA_INDEX']) else: algolia_index = None apps = AppGroup('apps') @apps.command('import-home') @click.argument('home_type') def import_categories(home_type): result = requests.get(f'https://api2.getpebble.com/v2/home/{home_type}') categories = result.json()['categories'] for category in categories: obj = Category(id=category['id'], name=category['name'], slug=category['slug'], icon=category.get('icon', {}).get('88x88', None), colour=category['color'], banner_apps=[], is_visible=True, app_type='watchface' if home_type == 'faces' else 'watchapp') db.session.add(obj) print(f"Added category: {obj.name} ({obj.id})") db.session.commit() def fetch_apps(url): while url is not None: print(f"Fetching {url}...") content = requests.get(url).json() for app in content['data']: yield app url = content.get('links', {}).get('nextPage', None) def parse_datetime(string: str) -> datetime.datetime: t = datetime.datetime.strptime(string.split('.', 1)[0], '%Y-%m-%dT%H:%M:%S') t = t.replace(tzinfo=datetime.timezone.utc) return t def fetch_file(url, destination): if os.path.exists(destination): return subprocess.check_call(["wget", url, "-O", destination]) @apps.command('fix-capabilities') def fix_caps(): for pbw_path in os.listdir('pbws'): release_id = pbw_path[:-4] try: pbw = PBW(f'pbws/{pbw_path}', 'aplite') caps = [x for x in pbw.get_capabilities() if x != ''] except (KeyError, zipfile.BadZipFile): print("Invalid PBW!?") continue try: release = Release.query.filter_by(id=release_id).one() except NoResultFound: print("PBW with no release: {release_id}") continue print(f"{release.id}: {release.capabilities} -> {caps}") release.capabilities = caps db.session.commit() @apps.command('import-apps') @click.argument('app_type') def import_apps(app_type): for app in fetch_apps(f"https://api2.getpebble.com/v2/apps/collection/all/{app_type}?hardware=basalt&filter_hardware=false&limit=100"): try: dev = Developer.query.filter_by(id=app['developer_id']).one() except NoResultFound: dev = Developer(id=app['developer_id'], name=app['author']) db.session.add(dev) if App.query.filter_by(id=app['id']).count() > 0: continue print(f"Adding app: {app['title']} ({app.get('uuid')}, {app['id']})...") release = app.get('latest_release') if release: filename = f"pbws/{release['id']}.pbw" if not os.path.exists(filename): try: fetch_file(release['pbw_file'], filename) except subprocess.CalledProcessError: print("Failed to grab pbw.") continue try: PBW(filename, 'aplite') except zipfile.BadZipFile: print("Bad PBW!") os.unlink(filename) continue else: filename = None app_obj = App( id=app['id'], app_uuid=app.get('uuid'), category_id=app['category_id'], companions={ k: CompanionApp( icon=fix_image_url(v['icon']), name=v['name'], url=v['url'], platform=k, pebblekit3=(v['pebblekit_version'] == '3'), ) for k, v in app['companions'].items() if v is not None }, created_at=parse_datetime(app['created_at']), developer=dev, hearts=app['hearts'], releases=[ *([Release( id=release['id'], js_md5=release.get('js_md5', None), has_pbw=True, capabilities=app['capabilities'] or [], published_date=parse_datetime(release['published_date']), release_notes=release['release_notes'], version=release.get('version'), compatibility=[ k for k, v in app['compatibility'].items() if v['supported'] and k not in ('android', 'ios') ], is_published=True, )] if release else []), *[Release( id=id_generator.generate(), has_pbw=False, published_date=parse_datetime(log['published_date']), version=log.get('version', ''), release_notes=log['release_notes'] ) for log in app['changelog'] if log.get('version', '') != release.get('version', '')] ], icon_large=fix_image_url((app.get('list_image') or {}).get('144x144') or ''), icon_small=fix_image_url((app.get('icon_image') or {}).get('48x48') or ''), published_date=app.get('published_date', release['published_date'] if release else None), source=app['source'] or None, title=app['title'], type=app['type'], website=app['website'] or None, ) db.session.add(app_obj) done = set() for platform in (app_obj.releases[0].compatibility if len(app_obj.releases) > 0 else ['aplite', 'basalt', 'chalk', 'diorite', 'emery']): r = requests.get(f"https://api2.getpebble.com/v2/apps/id/{app_obj.id}?hardware={platform}") r.raise_for_status() data = r.json()['data'][0] if data['screenshot_hardware'] not in done: done.add(data['screenshot_hardware']) else: continue collection = AssetCollection(app=app_obj, platform=data['screenshot_hardware'], description=data.get('description', ''), screenshots=[fix_image_url(next(iter(x.values()))) for x in data['screenshot_images']], headers=[fix_image_url(next(iter(x.values()))) for x in data['header_images']] if data.get('header_images') else [], banner=None) db.session.add(collection) if filename: for platform in ['aplite', 'basalt', 'chalk', 'diorite', 'emery']: pbw = PBW(filename, platform) if not pbw.has_platform: continue metadata = pbw.get_app_metadata() binary = Binary(release_id=release['id'], platform=platform, sdk_major=metadata['sdk_version_major'], sdk_minor=metadata['sdk_version_minor'], process_info_flags=metadata['flags'], icon_resource_id=metadata['icon_resource_id']) db.session.add(binary) db.session.commit() category_map = { 'Notifications': '5261a8fb3b773043d5000001', 'Health & Fitness': '5261a8fb3b773043d5000004', 'Remotes': '5261a8fb3b773043d5000008', 'Daily': '5261a8fb3b773043d500000c', 'Tools & Utilities': '5261a8fb3b773043d500000f', 'Games': '5261a8fb3b773043d5000012', 'Index': '527509e36526cda2d4000019', 'Faces': '528d3ef2dc7b5f580700000a', 'GetSomeApps': '52ccee3151a80d28e100003e', } mimetype_map = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', } def fix_image_url(url): if url == '': return '' identifier = url.split('/file/')[1].split('/convert')[0] s = requests.get(url, stream=True) # content_type = s.headers['Content-Type'] # if content_type not in mimetype_map: # print(f"Skipping unknown content-type {content_type}.") # return None with open(f'images/{identifier}', 'wb') as f: shutil.copyfileobj(s.raw, f) return identifier def import_app_from_locker(locker_app): print(f"Adding missing app {locker_app['title']}...") if locker_app['developer']['id'] is None: locker_app['developer']['id'] = id_generator.generate() try: dev = Developer.query.filter_by(id=locker_app['developer']['id']).one() except NoResultFound: dev = Developer(id=locker_app['developer']['id'], name=locker_app['developer']['name']) db.session.add(dev) release = locker_app.get('pbw') if release: filename = f"pbws/{release['release_id']}.pbw" if not os.path.exists(filename): with requests.get(release['file'], stream=True) as r: if r.status_code != 200: print(f"FAILED to download pbw.") return False with open(filename, 'wb') as f: shutil.copyfileobj(r.raw, f) try: if PBW(filename, 'aplite').zip.testzip() is not None: raise zipfile.BadZipFile except zipfile.BadZipFile: print("Bad PBW!") os.unlink(filename) return False else: filename = None created_at = datetime.datetime.utcfromtimestamp(int(locker_app['id'][:8], 16)).replace(tzinfo=datetime.timezone.utc) portal_info = requests.get(f"https://dev-portal.getpebble.com/api/applications/{locker_app['id']}") if portal_info.status_code != 200: print("Couldn't get dev portal info for app; skipping.") return None portal_info = portal_info.json()['applications'][0] app = App( id=locker_app['id'], app_uuid=locker_app['uuid'], asset_collections={x['name']: AssetCollection( platform=x['name'], description=x.get('description'), screenshots=[fix_image_url(x['images']['screenshot'])], headers=[], banner=None ) for x in locker_app['hardware_platforms']}, category_id=category_map[locker_app['category']], companions={ k: CompanionApp( icon=v['icon'], name=v['name'], url=v['url'], platform=k, pebblekit3=(v['pebblekit_version'] == '3'), ) for k, v in locker_app['companions'].items() if v is not None }, collections=[], created_at=created_at, developer=dev, hearts=locker_app['hearts'], icon_small=fix_image_url(portal_info['icon_image']), icon_large=fix_image_url(portal_info['list_image']), published_date=created_at, releases=[], source=None, title=locker_app['title'], type=locker_app['type'], website=None, visible=False, ) db.session.add(app) if filename: pbw = PBW(filename, 'aplite') js_md5 = None if pbw.has_javascript: with pbw.zip.open('pebble-js-app.js', 'r') as f: js_md5 = hashlib.md5(f.read()).hexdigest() release_obj = Release( id=release['release_id'], app_id=locker_app['id'], has_pbw=True, capabilities=pbw.get_capabilities(), js_md5=js_md5, published_date=created_at, release_notes=None, compatibility=[k for k, v in locker_app['compatibility'].items() if v['supported'] and k not in ('android', 'ios')], is_published=True, ) db.session.add(release_obj) for platform in ['aplite', 'basalt', 'chalk', 'diorite', 'emery']: pbw = PBW(filename, platform) if not pbw.has_platform: continue metadata = pbw.get_app_metadata() binary = Binary(release=release_obj, platform=platform, sdk_major=metadata['sdk_version_major'], sdk_minor=metadata['sdk_version_minor'], process_info_flags=metadata['flags'], icon_resource_id=metadata['icon_resource_id']) db.session.add(binary) db.session.commit() return app @apps.command('import-lockers') def import_lockers(): with open('users.txt') as f: processed = set() missing = set() for entry in f: uid, token = entry.strip().split() uid = int(uid) print(f"user {uid}...") url = "https://appstore-api.getpebble.com/v2/locker" entries = [] total_entries = 0 while url is not None: result = requests.get(url, headers={'Authorization': f"Bearer {token}"}) if result.status_code != 200: print(f"Skipping bad user: {uid}") app_ids = [x['id'] for x in result.json()['applications']] existing = {x.id: x for x in App.query.filter(App.id.in_(app_ids))} total_entries += len(app_ids) for app in result.json()['applications']: if app['id'] not in existing: if app['id'] not in missing: added = import_app_from_locker(app) if added is None: missing.add(app['id']) else: added = None if not added: print("Skipping bad app...") continue else: existing[added.id] = added if app['id'] not in processed: existing[app['id']].timeline_enabled = app['is_timeline_enabled'] processed.add(app['id']) entries.append(LockerEntry(app_id=app['id'], user_token=app.get('user_token'), user_id=uid)) url = result.json()['nextPageURL'] db.session.add_all(entries) db.session.commit() print(f"Added {len(existing)} of {total_entries} apps.") print("done.") @apps.command('import-likes') def import_likes(): known_apps = set(x.id for x in App.query.options(load_only('id'))) with open('users.txt') as f: for entry in f: uid, token = entry.strip().split() uid = int(uid) print(f"Importing user {uid}...") dev_portal = requests.get('https://dev-portal.getpebble.com/api/users/me', headers={'Authorization': f"Bearer {token}"}) if dev_portal.status_code != 200: print(f"Skipping user {uid}: dev portal didn't load: {dev_portal.status_code}.") continue voted = set(dev_portal.json()['users'][0]['voted_ids']) db.session.add_all(UserLike(user_id=uid, app_id=x) for x in voted if x in known_apps) db.session.commit() print(f"Imported {len(voted)} likes.") print("Done.") @apps.command('generate-index') def generate_index(): apps = App.query.order_by(App.id) result = [] for app in apps: result.append(algolia_app(app)) print(flask.json.dumps(result, indent=2)) @apps.command('update-patched-release') @click.argument('new_pbw') @click.argument('patchlvl') def update_patched_release(new_pbw, patchlvl): release_id = os.path.basename(new_pbw).split('.')[0] release_old = Release.query.filter_by(id=release_id).one() if release_old.version is None: newvers = patchlvl else: newvers = f"{release_old.version}-{patchlvl}" release_new = release_from_pbw(release_old.app, new_pbw, release_notes = "Automatic maintenance patch from Rebble.", published_date = datetime.datetime.utcnow(), version = newvers, compatibility = release_old.compatibility) print(f"Uploading new version {newvers} of {release_old.app.id} ({release_old.app.title})...") upload_pbw(release_new, new_pbw) db.session.commit() @apps.command('new-release') @click.argument('pbw_file') @click.argument('release_notes') def new_release(pbw_file, release_notes): pbw = PBW(pbw_file, 'aplite') with pbw.zip.open('appinfo.json') as f: j = json.load(f) uuid = j['uuid'] version = j['versionLabel'] app = App.query.filter_by(app_uuid = uuid).one() release_old = Release.query.filter_by(app = app).order_by(Release.published_date.desc()).limit(1).one() print(f"Previous version {release_old.version}, new version {version}, release notes {release_old.release_notes}") if version == release_old.version: version = f"{version}-rbl" release_new = release_from_pbw(app, pbw_file, release_notes = release_notes, published_date = datetime.datetime.utcnow(), version = version, compatibility = release_old.compatibility) print(f"Uploading new version {version} of {release_old.app.id} ({release_old.app.title})...") upload_pbw(release_new, pbw_file) db.session.commit() @apps.command('new-app') @click.argument('conf') def new_app(conf): params = yaml.load(open(conf, "r")) def path(base): return f"{os.path.dirname(conf)}/{base}" pbw_file = params['pbw_file'] pbw = PBW(path(pbw_file), 'aplite') with pbw.zip.open('appinfo.json') as f: appinfo = json.load(f) if App.query.filter(App.app_uuid == appinfo['uuid']).count() > 0: raise ValueError("app already exists!") if 'developer_id' in params: developer = Developer.query.filter(Developer.id == params['developer_id']).one() else: developer = Developer(id = id_generator.generate(), name = appinfo['companyName']) db.session.add(developer) print(f"Created developer {developer.id}") if 'header' in params: header_asset = upload_asset(path(params['header'])) else: header_asset = None app_obj = App( id = id_generator.generate(), app_uuid = appinfo['uuid'], asset_collections = { x['name']: AssetCollection( platform=x['name'], description=params['description'], screenshots=[upload_asset(path(s)) for s in x['screenshots']], headers = [header_asset] if header_asset else [], banner = None ) for x in params['assets']}, category_id = category_map[params['category']], companions = {}, # companions not supported yet created_at = datetime.datetime.utcnow(), developer = developer, hearts = 0, releases = [], icon_large = upload_asset(path(params['large_icon'])), icon_small = upload_asset(path(params['small_icon'])) if 'small_icon' in params else '', source = params['source'], title = params['title'], type = params['type'], timeline_enabled = False, website = params['website'] ) db.session.add(app_obj) print(f"Created app {app_obj.id}") release = release_from_pbw(app_obj, path(pbw_file), release_notes = params['release_notes'], published_date = datetime.datetime.utcnow(), version = appinfo['versionLabel'], compatibility = appinfo.get('targetPlatforms', [ 'aplite', 'basalt', 'diorite', 'emery' ])) print(f"Created release {release.id}") upload_pbw(release, path(pbw_file)) db.session.commit() if algolia_index: algolia_index.partial_update_objects([algolia_app(app_obj)], { 'createIfNotExists': True }) @apps.command('update-app') @click.argument('appid') @click.argument('conf') def update_app(appid, conf): params = yaml.load(open(conf, "r")) def path(base): return f"{os.path.dirname(conf)}/{base}" pbw_file = params['pbw_file'] pbw = PBW(path(pbw_file), 'aplite') with pbw.zip.open('appinfo.json') as f: appinfo = json.load(f) if 'header' in params: header_asset = upload_asset(path(params['header'])) else: header_asset = None app_obj = App.query.filter(App.id == appid).one() app_obj.asset_collections = {} app_obj.asset_collections = { x['name']: AssetCollection( platform=x['name'], description=params['description'], screenshots=[upload_asset(path(s)) for s in x['screenshots']], headers = [header_asset] if header_asset else [], banner = None ) for x in params['assets'] } app_obj.icon_large = upload_asset(path(params['large_icon'])), app_obj.icon_small = upload_asset(path(params['small_icon'])) if 'small_icon' in params else '', app_obj.source = params['source'], app_obj.title = params['title'], app_obj.website = params['website'] print(f"Updated app {app_obj.id}") release = release_from_pbw(app_obj, path(pbw_file), release_notes = params['release_notes'], published_date = datetime.datetime.utcnow(), version = appinfo['versionLabel'], compatibility = appinfo['targetPlatforms']) print(f"Created release {release.id}") upload_pbw(release, path(pbw_file)) db.session.commit() if algolia_index: algolia_index.partial_update_objects([algolia_app(app_obj)], { 'createIfNotExists': True }) def init_app(app): app.cli.add_command(apps)
pebble-dev/rebble-appstore-api
appstore/commands.py
commands.py
py
22,680
python
en
code
13
github-code
6
2228623411
''' module to load yolov5* model from the ultralytics/yolov5 repo ''' import torch from src.core.logger import logger def load_model(model_repo: str = "ultralytics/yolov5", model_name: str = "yolov5s6"): """ It loads the YOLOv5s model from the PyTorch Hub :return: A model """ try: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") _model = torch.hub.load(model_repo, model_name, device=device) _model_agnostic = True # NMS class-agnostic _model.amp = True # enable Automatic Mixed Precision (NMS) for inference return _model except Exception as e: logger.debug("Exception Caught: {}".format(e)) finally: logger.info(f"[{model_repo}] {model_name} loaded with AMP [Device: {device}]") model = load_model()
TYH71/gradio-ml-skeleton
src/model/yolov5.py
yolov5.py
py
814
python
en
code
0
github-code
6
9307549467
from logger import logger from io import StringIO, BytesIO # python3; python2: BytesIO from datetime import datetime import boto3 def s3_client_init(): client = boto3.client('s3') return client def dataframe_to_s3(s3_client, input_datafame, bucket_name, format='parquet'): logger.info(f"Writing {format} file.") current_timestamp = datetime.now().strftime('%Y_%m_%d__%H_%M_%S_%f') if format == 'parquet': out_buffer = BytesIO() input_datafame.to_parquet(out_buffer, index=False) elif format == 'csv': out_buffer = StringIO() input_datafame.to_parquet(out_buffer, index=False) file_path = f"tweets/cleansed_tweets/{current_timestamp}/{current_timestamp}__cleansed_tweets.parquet" s3_client.put_object(Bucket=bucket_name, Key=file_path, Body=out_buffer.getvalue()) logger.info(f"Parquet file written at S3 location: {file_path}")
caiolauro/flix-twitter-data-elt
twitter_api/s3_writer.py
s3_writer.py
py
945
python
en
code
0
github-code
6
1802990089
''' Simple calculator functions Lucas 09.05.2021 ''' import colorama # adds two numbers def add(x, y): return x + y # subtracts two numbers def subtract(x, y): return x - y # multiplies two numbers def multiply(x, y): return x * y # divides two numbers def divide(x, y): return x / y while (True): for i in range(30): print("") print("") print(colorama.Fore.GREEN+" ██████╗ █████╗ ██╗ ██████╗██╗ ██╗██╗ █████╗ ████████╗ ██████╗ ██████╗ ") print("██╔════╝██╔══██╗██║ ██╔════╝██║ ██║██║ ██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗") print("██║ ███████║██║ ██║ ██║ ██║██║ ███████║ ██║ ██║ ██║██████╔╝") print("██║ ██╔══██║██║ ██║ ██║ ██║██║ ██╔══██║ ██║ ██║ ██║██╔══██╗") print("╚██████╗██║ ██║███████╗╚██████╗╚██████╔╝███████╗██║ ██║ ██║ ╚██████╔╝██║ ██║") print(" ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝") print("") z1 = input(colorama.Fore.CYAN+"Enter your first number : ") calc = input("Enter your operator(+ - / *): ") z2 = input("Enter your second number: ") if z1 == "end" or z2 == "end" or calc == "end": break try: z1_cast = float(z1) except ValueError: print(colorama.Fore.RED+"Your first number is not a number") if calc != "+" and calc != "-" and calc != "/" and calc != "*": print(colorama.Fore.RED+"Your operator is not valid") try: z2_cast = float(z2) except ValueError: print(colorama.Fore.RED+"Your second number is not a number") if calc == "+": print(colorama.Fore.CYAN+z1, " ", calc, " ", z2, " = ", add(float(z1), float(z2))) elif calc == "-": print(colorama.Fore.CYAN+z1, " ", calc, " ", z2, " = ", subtract(float(z1), float(z2))) elif calc == "/": print(colorama.Fore.CYAN+z1, " ", calc, " ", z2, " = ", divide(float(z1), float(z2))) elif calc == "*": print(colorama.Fore.CYAN+z1, " ", calc, " ", z2, " = ", multiply(float(z1), float(z2))) print("") input(colorama.Fore.WHITE+"Press enter to continue...")
TheLucas777/Python_HTLAnichstasse
programme/calc_functions.py
calc_functions.py
py
2,893
python
en
code
1
github-code
6
38957829610
from socketio.namespace import BaseNamespace from socketio.sdjango import namespace from csvapp.pubsub import subscribe, unsubscribe @namespace('/csv') class CSVNamespace(BaseNamespace): def disconnect(self, *args, **kwargs): super(CSVNamespace, self).disconnect(*args, **kwargs) unsubscribe( 'csvapp.user.{}'.format(self.request.user.id), self.subscribe_handler) def recv_connect(self): if self.request.user.is_authenticated(): subscribe( 'csvapp.user.{}'.format(self.request.user.id), self.subscribe_handler) else: self.disconnect() def subscribe_handler(self, data): if 'event_name' in data: if data['event_name'] == 'document': self.emit('document', data['data']) elif data['event_name'] == 'sorteddocument': self.emit('sorteddocument', data['data'])
iamjem/django-csvapp
project/csvapp/sockets.py
sockets.py
py
947
python
en
code
0
github-code
6
41382929279
from typing import Callable from dataclasses import dataclass import pandas as pd from hvac import Quantity from hvac.fluids import HumidAir from hvac.climate import ClimateData from hvac.climate.sun.solar_time import time_from_decimal_hour from ..core import ( ExteriorBuildingElement, InteriorBuildingElement, InternalHeatGain, OnOffSchedule, TemperatureSchedule, ConstructionAssembly, ThermalNetwork, ThermalStorageNode, ZoneAirNode, ThermalNetworkSolver ) from . import VentilationZone Q_ = Quantity @dataclass class InternalThermalMass: A: Quantity R: Quantity C: Quantity class Ventilation: def __init__(self): self.space: Space | None = None self.vz: VentilationZone | None = None self.n_min: float = 0.0 self.V_open: float = 0.0 self.V_ATD_d: float = 0.0 self.V_sup: float = 0.0 self.V_trf: float = 0.0 self.V_exh: float = 0.0 self.V_comb: float = 0.0 self.T_sup: TemperatureSchedule | None = None self.T_trf: TemperatureSchedule | None = None self.Tdb_ext: TemperatureSchedule | None = None self.Twb_ext: TemperatureSchedule | None = None @classmethod def create( cls, space: 'Space', ventilation_zone: 'VentilationZone', n_min: Quantity = Q_(0.5, '1 / hr'), V_open: Quantity = Q_(0.0, 'm ** 3 / hr'), V_ATD_d: Quantity = Q_(0.0, 'm ** 3 / hr'), V_sup: Quantity = Q_(0.0, 'm ** 3 / hr'), V_trf: Quantity = Q_(0.0, 'm ** 3 / hr'), V_exh: Quantity = Q_(0.0, 'm ** 3 / hr'), V_comb: Quantity = Q_(0.0, 'm ** 3 / hr'), T_sup: TemperatureSchedule | None = None, T_trf: TemperatureSchedule | None = None, ) -> 'Ventilation': obj = cls() obj.space = space obj.vz = ventilation_zone obj.vz.add_space(space) obj.n_min = n_min.to('1 / hr').m obj.V_open = V_open.to('m ** 3 / hr').m obj.V_ATD_d = V_ATD_d.to('m ** 3 / hr').m obj.V_sup = V_sup.to('m ** 3 / hr').m obj.V_trf = V_trf.to('m ** 3 / hr').m obj.V_exh = V_exh.to('m ** 3 / hr').m obj.V_comb = V_comb.to('m ** 3 / hr').m obj.T_sup = T_sup or space.climate_data.Tdb_ext obj.T_trf = T_trf obj.Tdb_ext = space.climate_data.Tdb_ext obj.Twb_ext = space.climate_data.Twb_ext return obj @property def V_leak_ATD(self) -> float: """ External airflow rate into the space through leakages and ATDs. (EN 12831-1 eq. 19: the leakage airflow rate into the ventilation zone is divided among the spaces according to their envelope surface area and the airflow rate through ATDs into the ventilation zone is divided among the spaces according to their design airflow rate through ATDs). """ try: return ( self.vz.V_leak * (self.space.envelope_area.to('m ** 2').m / self.vz.A_env) + self.vz.V_ATD * (self.V_ATD_d / self.vz.V_ATD_d) ) except ZeroDivisionError: try: return self.vz.V_leak * (self.space.envelope_area.to('m ** 2').m / self.vz.A_env) except ZeroDivisionError: return 0.0 @property def V_env(self) -> float: """ External airflow rate into the space through the envelope. (EN 12831-1 eq. 18) """ try: V_env = ( (self.vz.V_inf_add / self.vz.V_env) * min(self.vz.V_env, self.V_leak_ATD * self.vz.f_dir) ) V_env += ( (self.vz.V_env - self.vz.V_inf_add) / self.vz.V_env * self.V_leak_ATD ) except ZeroDivisionError: return float('nan') else: return V_env @property def V_tech(self) -> float: """ Technical airflow rate into the space. (EN 12831-1 eq. 23) """ return max(self.V_sup + self.V_trf, self.V_exh + self.V_comb) @property def V_min(self) -> float: """ Minimum required airflow rate of the space that needs to be ensured in order to maintain an appropriate level of air hygiene. (EN 12831-1 eq. 33) """ return self.n_min * self.space.volume.to('m ** 3').m @property def V_outdoor(self) -> Quantity: """ Volume flow rate of outdoor air that enters the space. """ V_outside = max(self.V_env + self.V_open, self.V_min - self.V_tech) return Q_(V_outside, 'm ** 3 / hr') def Q_ven_sen(self, t: float, T_int: float) -> float: """ Sensible infiltration/ventilation load of the space. (EN 12831-1 eq. 17) """ VT_inf = ( max(self.V_env + self.V_open, self.V_min - self.V_tech) * (self.Tdb_ext(t) - T_int) ) VT_sup = self.V_sup * (self.T_sup(t) - T_int) if self.T_trf: VT_trf = self.V_trf * (self.T_trf(t) - T_int) else: VT_trf = 0.0 Q_ven = 0.34 * (VT_inf + VT_sup + VT_trf) # see EN 12831-1 B.2.8. return Q_ven def Q_ven_lat(self, t: float) -> float: """ Latent infiltration/ventilation load of the space (Principles of Heating, Ventilation, and Air Conditioning in Buildings, Chapter 10.5). """ h_o = HumidAir( Tdb=Q_(self.Tdb_ext(t), 'degC'), Twb=Q_(self.Twb_ext(t), 'degC') ).h.to('J / kg').m h_x = HumidAir( Tdb=Q_(self.Tdb_ext(t), 'degC'), RH=self.space.RH_int ).h.to('J / kg').m rho_o = HumidAir( Tdb=Q_(self.Tdb_ext(t), 'degC'), Twb=Q_(self.Twb_ext(t), 'degC') ).rho.to('kg / m ** 3').m V_inf = max(self.V_env + self.V_open, self.V_min - self.V_tech) / 3600.0 # m³/s Q_ven_lat = rho_o * V_inf * (h_o - h_x) return Q_ven_lat class Space: def __init__(self): self.ID: str = '' self.height: Quantity | None = None self.width: Quantity | None = None self.length: Quantity | None = None self.ventilation_zone: VentilationZone | None = None self.ventilation: Ventilation | None = None self.climate_data: ClimateData | None = None self.T_int_fun: Callable[[float], float] | None = None self.cooling_schedule: OnOffSchedule | None = None self.RH_int: Quantity | None = None self.ext_building_elements: dict[str, ExteriorBuildingElement] = {} self.int_building_elements: dict[str, InteriorBuildingElement] = {} self.int_heat_gains: dict[str, InternalHeatGain] = {} self.int_thermal_mass: InternalThermalMass | None = None self.dt_hr: float = 1.0 self.n_cycles: int = 6 self._hbm: HeatBalanceMethod | None = None self.Q_input_fun: Callable[[float, float | None], float] | None = None @classmethod def create( cls, ID: str, height: Quantity, width: Quantity, length: Quantity, climate_data: ClimateData, T_int_fun: Callable[[float], float], RH_int: Quantity = Q_(50, 'pct'), cooling_schedule: OnOffSchedule | None = None ) -> 'Space': """ Create a space. Parameters ---------- ID: Name of the space. height: Height of the space (vertical dimension). width: Width of the space (1st horizontal dimension). length: Length of the space (2nd horizontal dimension). climate_data: Instance of `ClimateData`, containing the relevant climatic data for the "design day". T_int_fun: Function that takes the time t in seconds from 00:00:00 and returns the setpoint space air temperature at that time. Can also be an instance of class `TemperatureSchedule`. RH_int: Design value for the relative humidity in the space (used to calculate the latent ventilation load). cooling_schedule: Function that takes the time t in seconds from 00:00:00 and returns a boolean to indicate if the cooling system is ON (True) or OFF (False). Can also be an instance of class `OnOffSchedule`. """ space = cls() space.ID = ID space.height = height space.width = width space.length = length space.climate_data = climate_data space.T_int_fun = T_int_fun space.RH_int = RH_int # default internal thermal mass space.int_thermal_mass = InternalThermalMass( A=2 * space.floor_area, R=Q_(1 / 25 + 0.1, 'm ** 2 * K / W'), C=Q_(200, 'kJ / (m ** 2 * K)') ) space.cooling_schedule = cooling_schedule return space def add_ext_building_element( self, ID: str, azimuth: Quantity, tilt: Quantity, width: Quantity, height: Quantity, construction_assembly: ConstructionAssembly, F_rad: float = 0.46, surface_absorptance: Quantity | None = None, surface_color: str = 'dark-colored' ) -> ExteriorBuildingElement: """ Add an exterior building element to the space (exterior wall, roof) Parameters ---------- ID: Name for the building element. azimuth: Azimuth angle of the building element. tilt: Tilt angle of the building element. width: The width of the building element. height: The height or length of the building element. construction_assembly: The construction assembly that describes the construction of the building element. F_rad: Fraction of conductive heat flow that is transferred by radiation to the interior thermal mass of the space. Default is 0.46 (see ASHRAE Fundamentals 2017, Ch. 18, Table 14). surface_absorptance: default None The solar absorptivity of the exterior surface (see ASHRAE Fundamentals 2017, Ch. 18, Table 15). surface_color: ['dark-colored', 'light-colored'] Alternative for setting `surface_absorptance` explicitly. """ ebe = ExteriorBuildingElement.create( ID=ID, azimuth=azimuth, tilt=tilt, width=width, height=height, climate_data=self.climate_data, construction_assembly=construction_assembly, T_int_fun=self.T_int_fun, F_rad=F_rad, surface_absorptance=surface_absorptance, surface_color=surface_color ) self.ext_building_elements[ebe.ID] = ebe return ebe def add_int_building_element( self, ID: str, width: Quantity, height: Quantity, construction_assembly: Quantity, T_adj_fun: Callable[[float], float], F_rad: float = 0.46 ) -> InteriorBuildingElement: """ Add interior building element to the space. Parameters ---------- ID: Name for the building element. width: The width of the building element. height: The height or length of the building element. construction_assembly: The construction assembly that describes the construction of the building element. T_adj_fun: Function that takes the time t in seconds from 00:00:00 and returns the temperature of the adjacent space at that time. Can also be an instance of class `TemperatureSchedule`. F_rad: Fraction of conductive heat flow that is transferred by radiation to the interior thermal mass of the space. Default is 0.46 (see ASHRAE Fundamentals 2017, Ch. 18, Table 14). """ ibe = InteriorBuildingElement.create( ID=ID, width=width, height=height, construction_assembly=construction_assembly, T_adj_fun=T_adj_fun, F_rad=F_rad ) self.int_building_elements[ibe.ID] = ibe return ibe def add_internal_heat_gain(self, ihg: InternalHeatGain) -> None: """ Add internal heat gain to the space (see classes `EquipmentHeatGain`, `LightingHeatGain`, and `PeopleHeatGain` in subpackage `core.internal_heat_gains`). """ self.int_heat_gains[ihg.ID] = ihg def add_internal_thermal_mass( self, A: Quantity, R: Quantity, C: Quantity ) -> None: """ Add thermal mass to the space interior. Parameters ---------- A: Surface area of the internal thermal mass R: Thermal unit resistance between thermal mass and space air. It is the sum of convective heat transfer resistance and that of any floor surfaces such as carpeting. The convective heat transfer coefficient for the interior of buildings is 25 W/(m².K). The thermal resistance of carpeting ranges from about 0.1 to 0.4 m².K/W [Principles of Heating, Ventilation and Air Conditioning in Buildings, p. 276]. C: The capacitance of the internal thermal mass. This is an aggregate value of capacitance that takes into account storage in the floor, ceiling, partitions, and furnishings. It is in the range of 100 to 300 kJ/(m².K) of floor area [Principles of Heating, Ventilation and Air Conditioning in Buildings, p. 276]. """ self.int_thermal_mass = InternalThermalMass(A, R, C) def add_ventilation( self, ventilation_zone: VentilationZone, n_min: Quantity = Q_(0.5, '1 / hr'), V_open: Quantity = Q_(0.0, 'm ** 3 / hr'), V_ATD_d: Quantity = Q_(0.0, 'm ** 3 / hr'), V_sup: Quantity = Q_(0.0, 'm ** 3 / hr'), V_trf: Quantity = Q_(0.0, 'm ** 3 / hr'), V_exh: Quantity = Q_(0.0, 'm ** 3 / hr'), V_comb: Quantity = Q_(0.0, 'm ** 3 / hr'), T_sup: TemperatureSchedule | None = None, T_trf: TemperatureSchedule | None = None ) -> None: """ Add ventilation to the space. Parameters ---------- ventilation_zone: The ventilation zone the space belongs to. n_min: Minimum air change rate required for the space for reasons of air quality/hygiene and comfort (NBN EN 12831-1, B.2.10 - Table B.7). Default value applies to permanent dwelling areas (living rooms, offices) and a ceiling height less than 3 m. V_open: Quantity, optional External air volume flow rate into the space through large openings (NBN EN 12831-1, Annex G). V_ATD_d: Design air volume flow rate of the ATDs in the room (NBN EN 12831-1, B.2.12). Only relevant if ATDs are used for ventilation. V_sup: Supply air volume flow rate from the ventilation system into the space. V_trf: Transfer air volume flow rate into the space from adjacent spaces. V_exh: Exhaust ventilation air volume flow rate from the space. V_comb: Air volume flow rate exhausted from the space that has not been included in the exhaust air volume flow of the ventilation system (typically, but not necessarily, combustion air if an open flue heater is present in the heated space). T_sup: Temperature of the ventilation supply air after passing heat recovery (see NBN EN 12831-1 §6.3.3.7) or after passive pre-cooling. Any temperature fall by active pre-cooling, which requires power from a cooling machine, shall not be taken into account (ventilation load is not a space load in that case). T_trf: Temperature of the transfer air volume flow into the space from another space. In case the room height of the other space is less than 4 m, it is equal to the internal design temperature of the other space; otherwise, it is equal to mean air temperature of the other space (see NBN EN 12831-1 §6.3.8.3). """ self.ventilation = Ventilation.create( space=self, ventilation_zone=ventilation_zone, n_min=n_min, V_open=V_open, V_ATD_d=V_ATD_d, V_sup=V_sup, V_trf=V_trf, V_exh=V_exh, V_comb=V_comb, T_sup=T_sup, T_trf=T_trf ) @property def envelope_area(self) -> Quantity: """ Returns the area of the exterior building elements that surround the space. """ if self.ext_building_elements: A_env = sum( ebe.area_gross for ebe in self.ext_building_elements.values() ) else: A_env = Q_(0.0, 'm ** 2') return A_env @property def floor_area(self) -> Quantity: """ Returns the floor area of the space. """ return self.width * self.length @property def volume(self) -> Quantity: """ Returns the space volume. """ return self.floor_area * self.height def get_heat_gains(self, unit: str = 'W') -> pd.DataFrame: """ Returns the heat gains into the space. The default unit is Watts ('W'). """ if self._hbm is None: self._hbm = HeatBalanceMethod(self, self.dt_hr, self.n_cycles) df = self._hbm.get_heat_gains(unit) return df def get_thermal_storage_heat_flows( self, T_unit: str = 'degC', Q_unit: str = 'W' ) -> pd.DataFrame: """ Returns the thermal mass temperature, the heat flow into the thermal mass, the heat flow out of the thermal mass, and the heat being stored in the thermal mass. """ if self._hbm is None: self._hbm = HeatBalanceMethod(self, self.dt_hr, self.n_cycles) df = self._hbm.get_thermal_storage_heat_flows(T_unit, Q_unit) return df def get_space_air_temperatures( self, unit: str = 'degC' ) -> pd.DataFrame: """ Returns the space air temperature. """ if self._hbm is None: self._hbm = HeatBalanceMethod(self, self.dt_hr, self.n_cycles) df = self._hbm.get_space_air_temperatures(unit) return df class ThermalNetworkBuilder: """Builds the thermal network of the space.""" @classmethod def build(cls, space: Space) -> tuple[ThermalNetwork, ThermalNetwork]: # thermal network when cooling ON (space air temperature known) nodes_cooling_on = [] int_surf_node_indices = [] for ebe in space.ext_building_elements.values(): cls._modify_int_surf_node(ebe) nodes_cooling_on.extend(ebe.thermal_network.nodes) int_surf_node_indices.append(len(nodes_cooling_on) - 1) tsn = cls._create_thermal_storage_node(space) nodes_cooling_on.append(tsn) tnw_cooling_on = ThermalNetwork(nodes_cooling_on, int_surf_node_indices) # thermal network when cooling is OFF (space air temperature unknown) nodes_cooling_off = [node for node in nodes_cooling_on] zan = cls._create_zone_air_node(space) nodes_cooling_off.insert(-1, zan) tnw_cooling_off = ThermalNetwork(nodes_cooling_off, int_surf_node_indices) return tnw_cooling_on, tnw_cooling_off @staticmethod def _modify_int_surf_node(ebe) -> None: int_surf_node = ebe.thermal_network.nodes[-1] R_surf_film = int_surf_node.R[-1] R_rad = R_surf_film / ebe.F_rad R_conv = R_surf_film / (1.0 - ebe.F_rad) int_surf_node.R = [int_surf_node.R[0], R_conv, R_rad] @classmethod def _create_thermal_storage_node(cls, space: Space) -> ThermalStorageNode: int_surf_nodes = [ ebe.thermal_network.nodes[-1] for ebe in space.ext_building_elements.values() ] R = [Q_(isn.R_unit[-1], 'm ** 2 * K / W') for isn in int_surf_nodes] R.append(space.int_thermal_mass.R) int_thermal_mass_node = ThermalStorageNode( ID='internal thermal mass', R_unit_lst=R, C=space.int_thermal_mass.C, A=space.int_thermal_mass.A, T_input=space.T_int_fun, Q_input=cls._get_tsn_Q_input_fun(space), windows=cls._get_windows(space), int_building_elements=list(space.int_building_elements.values()), ext_doors=cls._get_ext_doors(space), int_doors=cls._get_int_doors(space) ) return int_thermal_mass_node @classmethod def _get_tsn_Q_input_fun(cls, space: Space) -> Callable[[float], float]: windows = cls._get_windows(space) ext_doors = cls._get_ext_doors(space) int_doors = cls._get_int_doors(space) def _Q_input(t: float, T_int: float | None = None) -> float: """ Get the radiative heat gain at time t in seconds from 00:00:00 from windows, interior building elements, doors and internal heat gains (people, equipment, lightning). """ T_int = T_int if T_int is not None else space.T_int_fun(t) Q_rad_wnd = sum( wnd.get_conductive_heat_gain(t, T_int)['rad'] for wnd in windows ) Q_rad_wnd += sum( wnd.get_solar_heat_gain(t)['rad'] for wnd in windows ) Q_rad_ibe = sum( ibe.get_conductive_heat_gain(t, T_int)['rad'] for ibe in space.int_building_elements.values() ) Q_rad_idr = sum( door.get_conductive_heat_gain(t, T_int)['rad'] for door in int_doors ) Q_rad_edr = sum( door.get_conductive_heat_gain(t, T_int)['rad'] for door in ext_doors ) Q_rad_ihg = sum( int_heat_gain.Q_sen(t)['rad'] for int_heat_gain in space.int_heat_gains.values() ) Q_rad = Q_rad_wnd + Q_rad_ibe + Q_rad_idr + Q_rad_edr + Q_rad_ihg return Q_rad return _Q_input @classmethod def _create_zone_air_node(cls, space: Space) -> ZoneAirNode: int_surf_nodes = [ ebe.thermal_network.nodes[-1] for ebe in space.ext_building_elements.values() ] R = [Q_(isn.R_unit[-1], 'm ** 2 * K / W') for isn in int_surf_nodes] R.append(space.int_thermal_mass.R) zan = ZoneAirNode( ID='zone air node', R_unit_lst=R, Q_input=space.Q_input_fun, windows=cls._get_windows(space), int_building_elements=list(space.int_building_elements.values()), ext_doors=cls._get_ext_doors(space), int_doors=cls._get_int_doors(space) ) return zan @staticmethod def _get_windows(space: Space): windows = [ window for ebe in space.ext_building_elements.values() for window in ebe.windows.values() if ebe.windows ] return windows @staticmethod def _get_ext_doors(space: Space): ext_doors = [ door for ebe in space.ext_building_elements.values() for door in ebe.doors.values() if ebe.doors ] return ext_doors @staticmethod def _get_int_doors(space: Space): int_doors = [ door for ibe in space.int_building_elements.values() for door in ibe.doors.values() if ibe.doors ] return int_doors class HeatBalanceMethod: def __init__( self, space: Space, dt_hr: float = 1.0, n_cycles: int = 6 ): self.space = space tnw_cooling_on, tnw_cooling_off = ThermalNetworkBuilder.build(space) self._thermal_network = ThermalNetworkSolver.solve( thermal_networks=(tnw_cooling_on, tnw_cooling_off), cooling_schedule=space.cooling_schedule, dt_hr=dt_hr, n_cycles=n_cycles ) self._dt = dt_hr * 3600 def _calculate_conv_ext_build_elem_gain(self, k: int, T_nodes: list[float]) -> float: """ Calculate heat flow from exterior building elements to space air at time index k """ Q_env = 0.0 if self.space.cooling_schedule is None: # cooling always ON T_int = self.space.T_int_fun(k * self._dt) else: # cooling may be ON or OFF depending on the cooling schedule T_int = T_nodes[-2] for i in self._thermal_network.int_surf_node_indices: T_isn = T_nodes[i] R_conv = self._thermal_network.nodes[i].R[1] Q_env += (T_isn - T_int) / R_conv return Q_env def _calculate_conv_therm_mass_gain(self, k: int, T_nodes: list[float]) -> float: """ Calculate heat flow from interior thermal mass to space air at time index k """ T_itm = T_nodes[-1] if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(k * self._dt) else: T_int = T_nodes[-2] R_conv = self._thermal_network.nodes[-1].R[-1] Q = (T_itm - T_int) / R_conv return Q def _calculate_conv_window_gain(self, k: int, T_nodes: list[float]) -> float: """ Calculate heat flow from windows to space air at time index k. """ windows = [ window for ebe in self.space.ext_building_elements.values() for window in ebe.windows.values() if ebe.windows ] Q_conv_sol = sum( window.get_solar_heat_gain(k * self._dt)['conv'] for window in windows ) if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(k * self._dt) else: T_int = T_nodes[-2] Q_conv_cond = sum( window.get_conductive_heat_gain(k * self._dt, T_int)['conv'] for window in windows ) Q = Q_conv_sol + Q_conv_cond return Q def _calculate_conv_int_build_elem_gain(self, k: int, T_nodes: list[float]) -> float: """ Calculate heat flow from interior building elements to space air at time index k """ if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(k * self._dt) else: T_int = T_nodes[-2] Q = sum( ibe.get_conductive_heat_gain(k * self._dt, T_int)['conv'] for ibe in self.space.int_building_elements.values() ) return Q def _calculate_conv_int_door_gain(self, k: int, T_nodes: list[float]) -> float: """ Calculate heat flow from interior doors to space air at time index k. """ doors = [ door for ibe in self.space.int_building_elements.values() for door in ibe.doors.values() if ibe.doors ] if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(k * self._dt) else: T_int = T_nodes[-2] Q = sum( door.get_conductive_heat_gain(k * self._dt, T_int)['conv'] for door in doors ) return Q def _calculate_conv_ext_door_gain(self, k: int, T_nodes: list[float]) -> float: """ Calculate heat flow from exterior doors to space air at time index k. """ doors = [ door for ebe in self.space.ext_building_elements.values() for door in ebe.doors.values() if ebe.doors ] if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(k * self._dt) else: T_int = T_nodes[-2] Q = sum( door.get_conductive_heat_gain(k * self._dt, T_int)['conv'] for door in doors ) return Q def _calculate_conv_int_heat_gain(self, k: int) -> float: """ Calculate heat flow from internal heat gains to space air at time index k. """ Q = sum( ihg.Q_sen(k * self._dt)['conv'] for ihg in self.space.int_heat_gains.values() ) return Q def _calculate_lat_int_heat_gain(self, k: int) -> float: """ Calculate latent internal heat gains to space air at time index k. """ Q = sum( ihg.Q_lat(k * self._dt) for ihg in self.space.int_heat_gains.values() ) return Q def _calculate_sen_vent_gain(self, k: int, T_nodes: list[float]) -> float: """ Calculate sensible heat gain to space air at time index k. """ if self.space.ventilation is not None: if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(k * self._dt) else: T_int = T_nodes[-2] Q = self.space.ventilation.Q_ven_sen(k * self._dt, T_int) return Q return 0.0 def _calculate_lat_vent_gain(self, k: int) -> float: if self.space.ventilation is not None: Q = self.space.ventilation.Q_ven_lat(k * self._dt) return Q return 0.0 def _calculate_thermal_storage_heat_flows( self, k: int, T_nodes: list[float] ) -> tuple[float, ...]: """ Calculate heat flow into internal thermal mass, heat stored in internal thermal mass and heat flow out from internal thermal mass at time index k. """ # heat flow from exterior building elements into internal thermal mass # at time index k Q_rad_ext = 0.0 T_itm = T_nodes[-1] for i in self._thermal_network.int_surf_node_indices: T_isn = T_nodes[i] R_rad = self._thermal_network.nodes[i].R[-1] Q_rad_ext += (T_isn - T_itm) / R_rad # heat flow from windows, doors and interior building elements into # internal thermal mass at time index k if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(k * self._dt) else: T_int = T_nodes[-2] Q_rad_other = self._thermal_network.nodes[-1].Q_input(k * self._dt, T_int) Q_in = Q_rad_ext + Q_rad_other # heat flow from internal thermal mass to space air at time index k T_int = self.space.T_int_fun(k * self._dt) R_itm = self._thermal_network.nodes[-1].R[-1] Q_out = (T_itm - T_int) / R_itm # heat stored in internal thermal mass at time index k Q_sto = Q_in - Q_out return T_itm, Q_in, Q_out, Q_sto def get_heat_gains(self, unit: str = 'W') -> pd.DataFrame: """ Get Pandas `DataFrame` object with the heat gains to the space air and the cooling load of the space at each time moment of the design day in the measuring unit asked (default unit is Watts, 'W'). """ Q_gains = { 'time': [], 'Q_conv_ext': [], 'Q_conv_int': [], 'Q_conv_itm': [], 'Q_conv_wnd': [], 'Q_conv_ihg': [], 'Q_sen_vent': [], 'Q_sen_load': [], 'Q_lat_ihg': [], 'Q_lat_vent': [], 'Q_lat_load': [] } # noinspection PyProtectedMember for k, T_nodes in enumerate(self._thermal_network._T_node_table): Q_gains['time'].append(time_from_decimal_hour(k * self._dt / 3600)) # heat flow from exterior building elements to space air at time # index k Q_gains['Q_conv_ext'].append( Q_( self._calculate_conv_ext_build_elem_gain(k, T_nodes) + self._calculate_conv_ext_door_gain(k, T_nodes), 'W' ).to(unit).m ) # heat flow from interior building elements to space air at time # index k Q_gains['Q_conv_int'].append( Q_( self._calculate_conv_int_build_elem_gain(k, T_nodes) + self._calculate_conv_int_door_gain(k, T_nodes), 'W' ).to(unit).m ) # heat flow from internal thermal mass to space air at time # index k Q_gains['Q_conv_itm'].append( Q_( self._calculate_conv_therm_mass_gain(k, T_nodes), 'W' ).to(unit).m ) # heat flow from windows to space air at time index k Q_gains['Q_conv_wnd'].append( Q_( self._calculate_conv_window_gain(k, T_nodes), 'W' ).to(unit).m ) # heat flow from internal heat gains to space air at time index k Q_gains['Q_conv_ihg'].append( Q_( self._calculate_conv_int_heat_gain(k), 'W' ).to(unit).m ) # heat flow from ventilation to space air at time index k Q_gains['Q_sen_vent'].append( Q_( self._calculate_sen_vent_gain(k, T_nodes), 'W' ).to(unit).m ) # sensible cooling load of space air at time index k Q_gains['Q_sen_load'].append( Q_gains['Q_conv_ext'][-1] + Q_gains['Q_conv_int'][-1] + Q_gains['Q_conv_itm'][-1] + Q_gains['Q_conv_wnd'][-1] + Q_gains['Q_conv_ihg'][-1] + Q_gains['Q_sen_vent'][-1] ) # latent heat transfer from internal heat gains to space air at # time index k Q_gains['Q_lat_ihg'].append( Q_( self._calculate_lat_int_heat_gain(k), 'W' ).to(unit).m ) # latent heat transfer from ventilation to space air at time index # k Q_gains['Q_lat_vent'].append( Q_( self._calculate_lat_vent_gain(k), 'W' ).to(unit).m ) # latent cooling load of space air at time index k Q_gains['Q_lat_load'].append( Q_gains['Q_lat_ihg'][-1] + Q_gains['Q_lat_vent'][-1] ) Q_gains = pd.DataFrame(Q_gains) Q_gains['Q_tot_load'] = Q_gains['Q_sen_load'] + Q_gains['Q_lat_load'] return Q_gains def get_thermal_storage_heat_flows( self, T_unit: str = 'degC', Q_unit: str = 'W' ) -> pd.DataFrame: Q_therm_storage = { 'time': [], 'T_itm': [], 'Q_in': [], 'Q_out': [], 'Q_sto': [] } # noinspection PyProtectedMember for k, T_nodes in enumerate(self._thermal_network._T_node_table): tup = self._calculate_thermal_storage_heat_flows(k, T_nodes) Q_therm_storage['time'].append( time_from_decimal_hour(k * self._dt / 3600) ) Q_therm_storage['T_itm'].append( Q_(tup[0], 'degC').to(T_unit).m ) Q_therm_storage['Q_in'].append( Q_(tup[1], 'W').to(Q_unit).m ) Q_therm_storage['Q_out'].append( Q_(tup[2], 'W').to(Q_unit).m ) Q_therm_storage['Q_sto'].append( Q_(tup[3], 'W').to(Q_unit).m ) Q_therm_storage = pd.DataFrame(Q_therm_storage) return Q_therm_storage def get_space_air_temperatures( self, unit: str = 'degC' ) -> pd.DataFrame: d = { 'time': [], 'T_int': [] } # noinspection PyProtectedMember for k, T_nodes in enumerate(self._thermal_network._T_node_table): t = k * self._dt if self.space.cooling_schedule is None: T_int = self.space.T_int_fun(t) else: T_int = T_nodes[-2] d['time'].append(time_from_decimal_hour(t / 3600)) d['T_int'].append(Q_(T_int, 'degC').to(unit).m) df = pd.DataFrame(d) return df
TomLXXVI/HVAC
hvac/cooling_load_calc/building/space.py
space.py
py
37,323
python
en
code
8
github-code
6
23929041781
# Asyncio Python 3.7+ package comparision with Javascript async # by default operates in single thread and CPU core # and schedules tasks as coroutines to run in an event loop import asyncio #import requests incompatible because does not return awaitable tasks # pyenv exec pip install aiohttp import aiohttp from aiohttp import ClientSession # generator based coroutines removed since 3.10 # @asyncio.coroutine # def worker(name, timeout_secs): # yield asyncio.sleep(timeout_secs) async def worker(name: str, timeout_secs: int) -> str | Exception: if (timeout_secs < 0): raise Exception("bad job") print(name, " start job") # do something else in event loop while working for timeout secs await asyncio.sleep(timeout_secs) print(name, " end job") return "good job" async def fetch_html(url: str, session: ClientSession, **kwargs) -> str: """GET request wrapper to fetch page HTML. kwargs are passed to `session.request()`. """ resp = await session.request(method="GET", url=url, **kwargs) resp.raise_for_status() print("Got response [%s] for URL: %s", resp.status, url) html = await resp.text() return html async def main() -> None: results = await asyncio.gather( worker("Fast", 1), worker("Avg", 2.5), worker("Slow", 4), worker("Fail", -1), return_exceptions=True) print(results) try: results2 = await asyncio.gather( worker("Fail", -1), worker("Good", 1), return_exceptions=False) print(results2) except Exception as e: print("caught exception ", e) async with ClientSession() as session: result3 = await fetch_html("http://ip.jsontest.com/", session) print(result3) # possible to get default event loop instance but not usually needed #loop = asyncio.get_event_loop() #try: # loop.run_until_complete(main()) #finally: # loop.close() if __name__ == "__main__": import time s = time.perf_counter() asyncio.run(main(), debug=True) elapsed = time.perf_counter() - s print(f"{__file__} executed in {elapsed:0.2f} seconds.")
simonc312/today-i-learned
Apache Spark/python/AsyncIO.py
AsyncIO.py
py
2,148
python
en
code
0
github-code
6
4487190452
""" Exam task 2 Binary Tree """ from collections import deque from queue import Queue class BinatyTree: """ Binary tree class with basic functional Version with tree as node with data, left and right children """ def __init__(self, data) -> None: """ Init root with default left and right as None """ self.data = data self.left_child = None self.right_child = None def get_root(self): """ Return root data """ return self.data def set_root(self, value) -> None: """ Set root data as value """ self.data = value def add_left(self, item) -> None: """ Add the lefy child to the root. Left child of the new node is old tree's right child """ new_subtree = BinatyTree(item) new_subtree.left_child = self.get_left() self.left_child = new_subtree def add_right(self, item) -> None: """ Add the right child to the root. Right child of the new node is old tree's right child """ new_subtree = BinatyTree(item) new_subtree.right_child = self.get_right() self.right_child = new_subtree def get_right(self): """ Return right child of the tree """ return self.right_child def get_left(self): """ Return left child of the tree """ return self.left_child def is_leaf(self): """ Check if self Node is leaf """ return self.get_left() is None and self.get_right() is None def inorder(self) -> list: """ Return list with tree vertices data visited in inorder travelsal """ result = [] def recurse(root): """ Helper function to add nodes """ if root.left_child is not None: recurse(root.left_child) result.append(root.data) if root.right_child is not None: recurse(root.right_child) recurse(self) return result def right_most(self) -> list: """ Return list with rightmost nodes for each level (starts from the root) """ # Set initial values node_queue = Queue() node_queue.put(self) rightmost = [] while not node_queue.empty(): # get number of elements on current level num_node_on_level = node_queue.qsize() # iterate through items on one level for i in range(num_node_on_level): current = node_queue.get() # it is the most right item if i == num_node_on_level - 1: rightmost.append(current.data) # add children nodes to the queue if current.left_child is not None: node_queue.put(current.left_child) if current.right_child is not None: node_queue.put(current.right_child) return rightmost def leaf_paths(self) -> list: """ Return list with leaf path to the root """ # init starting values child_parent_dict = {} paths = [] nodes_stack = deque() nodes_stack.append(self) while nodes_stack: current = nodes_stack.pop() # if current is a leaf find its root path if current.is_leaf(): curr_value = current.data paths.append([curr_value]) while curr_value in child_parent_dict: curr_value = child_parent_dict[curr_value] paths[-1].append(curr_value) else: # Append children nodes to the stack # add child-parent pairs to the dictionary. if current.right_child is not None: nodes_stack.append(current.get_right()) child_parent_dict[current.right_child.data] = current.data if current.left_child is not None: nodes_stack.append(current.left_child) child_parent_dict[current.left_child.data] = current.data return paths
sviat-l/FP_Labs
Exam/Binary tree/binary_tree.py
binary_tree.py
py
4,297
python
en
code
0
github-code
6
31127621657
import numpy as np import sys import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.batchnorm = nn.BatchNorm2d(3, affine=False) self.pad2 = nn.ConstantPad2d(2, 0) self.pad1 = nn.ConstantPad2d(1, 0) self.conv1 = nn.Conv2d(3, 32, 3) self.conv2 = nn.Conv2d(32, 64, 3) self.conv3 = nn.Conv2d(64, 32, 3) self.conv4 = nn.Conv2d(32, 16, 3) self.conv5 = nn.Conv2d(16, 1, 5) def forward(self, x): x = self.batchnorm(x.float()) x = self.pad1(F.relu(self.conv1(x))) x = self.pad1(F.relu(self.conv2(x))) x = self.pad1(F.relu(self.conv3(x))) x = self.pad1(F.relu(self.conv4(x))) x = self.pad2(F.relu(self.conv5(x))) x = x.view(-1, 225) return x def toTripleBoard(board, side): curBoard = np.zeros(shape=(3, 15, 15), dtype=np.float) blackBoard = np.zeros(shape=(15, 15), dtype=np.float) whiteBoard = np.zeros(shape=(15, 15), dtype=np.float) if side == 1: blackTurnBoard = np.ones(shape=(15, 15), dtype=np.float) else: blackTurnBoard = -np.ones(shape=(15, 15), dtype=np.float) curBoard[0,:] = blackTurnBoard for i in range(15): for j in range(15): if board[i, j] == 1: blackBoard[i, j] = 1 if board[i, j] == -1: whiteBoard[i, j] = -1 curBoard[1,:] = blackBoard curBoard[2,:] = whiteBoard return curBoard def isGg(board, color): if color == 0: size = 4 else: size = -4 for i in range(15): for j in range(10): if board[i, j] + board[i, j + 1] + board[i, j + 2] + board[i, j + 3] + board[i, j + 4] == size: for k in range(5): if board[i, j + k] == 0: return i, j + k for i in range(10): for j in range(15): if board[i, j] + board[i + 1, j] + board[i + 2, j] + board[i + 3, j] + board[i + 4, j] == size: for k in range(5): if board[i + k, j] == 0: return i + k, j for i in range(10): for j in range(10): if board[i, j] + board[i + 1, j + 1] + board[i + 2, j + 2] + board[i + 3, j + 3] + board[i + 4, j + 4] == size: for k in range(5): if board[i + k, j + k] == 0: return i + k, j + k for i in range(5, 15): for j in range(10): if board[i, j] + board[i - 1, j + 1] + board[i - 2, j + 2] + board[i - 3, j + 3] + board[i - 4, j + 4] == size: for k in range(5): if board[i - k, j + k] == 0: return i - k, j + k return (-1, -1) def toTurn(turn): letter = ord(turn[0]) - ord('a') num = int(turn[1:]) - 1 return letter, num def to_move(pos): return idx2chr[pos[0]] + str(pos[1] + 1) def to_pos(move): return chr2idx[move[0]], int(move[1:]) - 1 if __name__ == "__main__": device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") torch.backends.cudnn.benchmark = True idx2chr = 'abcdefghjklmnop' chr2idx = {letter: pos for pos, letter in enumerate(idx2chr)} net = Net() net = net.to(device) net.load_state_dict(torch.load("finalNN.txt")) while True: gameStr = sys.stdin.readline()#input()# if not gameStr: break gameStr = gameStr.strip().split() curBoard = np.zeros(shape=(15, 15), dtype=np.float) for i in range(len(gameStr)): x, y = to_pos(gameStr[i]) if i % 2 == 0: curBoard[x, y] = 1 else: curBoard[x, y] = -1 color = len(gameStr) % 2 board = toTripleBoard(curBoard, color) with torch.no_grad(): outputs = net(torch.unsqueeze(torch.from_numpy(board), 0)) _, netTurn = torch.max(outputs, 1) netTurn = int(netTurn) turnX, turnY = netTurn // 15, netTurn % 15 while curBoard[turnX, turnY] != 0: outputs[netTurn] = 0 _, netTurn = torch.max(outputs, 1) netTurn = int(netTurn) turnX, turnY = netTurn // 15, netTurn % 15 ggTest = isGg(curBoard, color) if ggTest != (-1, -1): turnX, turnY = ggTest myTurn = to_move((turnX, turnY)) sys.stdout.write(myTurn + '\n') sys.stdout.flush()
peinrules/Darin
GAME.py
GAME.py
py
4,427
python
en
code
0
github-code
6
39647933037
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Author : Amir Shokri # github link : https://github.com/amirshnll/Wine # dataset link : http://archive.ics.uci.edu/ml/datasets/Wine # email : [email protected] # In[8]: import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn import metrics # In[9]: col_names = ['class', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', ' Nonflavanoid phenols','Proanthocyanins','Color intensity','Hue','OD280/OD315 of diluted wines','Proline'] wine =pd.read_csv("wine.csv",header=None, names=col_names) # In[10]: wine.head() # In[11]: inputs =wine.drop('class',axis='columns') target =wine['class'] target # In[13]: input_train,input_test,target_train,target_test=train_test_split(inputs,target,test_size=0.3,random_state=1) # In[14]: clf =DecisionTreeClassifier() clf =clf.fit(input_train,target_train) y_pred = clf.predict(input_test) # In[15]: print ("Accuracy:",metrics.accuracy_score(target_test,y_pred)) # In[ ]:
semnan-university-ai/Wine
tree3.py
tree3.py
py
1,118
python
en
code
1
github-code
6
26471134751
import unittest from util.tests.reusable import compare_speed from solution.batch2.problem30 import * class DigitFifthPowers(unittest.TestCase): def test_all_but_upper(self): expected = [ [153, 370, 371, 407], [1634, 8208, 9474], [4150, 4151, 54748, 92727, 93084, 194_979] ] for n in range(3, 6): self.assertListEqual(expected[n - 3], digit_nth_powers_brute(n)) self.assertListEqual(expected[n - 3], digit_nth_powers_builtin(n)) def test_digit_nth_powers_speed(self): n = 6 expected = [548_834] solutions = { "Brute": [digit_nth_powers_brute, n], "Built-in": [digit_nth_powers_builtin, n] } results = compare_speed(solutions) self.assertTrue(all(expected == actual for actual in results.values())) if __name__ == '__main__': unittest.main()
bog-walk/project-euler-python
test/batch2/test_problem30.py
test_problem30.py
py
914
python
en
code
0
github-code
6
72908437948
from odoo import models, fields, api, _ from odoo.exceptions import ValidationError import logging _logger = logging.getLogger(__name__) class StudentTranscript(models.TransientModel): _name = "student.transcript" _description = "Student Transcript" from_date = fields.Date( 'From Date', required=True, default=lambda self: fields.Date.today()) to_date = fields.Date( 'To Date', required=True, default=lambda self: fields.Date.today()) course_id = fields.Many2one('op.course', 'Course', required=True, default=lambda self: self._get_default_course()) batch_id = fields.Many2one( 'op.batch', 'Term', required=True, default=lambda self: self._get_default_batch()) semester_id = fields.Many2one('pm.semester', 'Semester') final = fields.Boolean('Final Transcript') def _get_default_batch(self): student_id = self.env.context.get('active_id', False) student_course = self.env['op.student.course'].search([('student_id', '=', student_id), ('p_active', '=', True)], limit=1) return student_course.batch_id.id def _get_default_course(self): student_id = self.env.context.get('active_id', False) student_course = self.env['op.student.course'].search([('student_id', '=', student_id), ('p_active', '=', True)], limit=1) return student_course.course_id.id def print_report(self): student_id = self.env.context.get('active_id', False) order = self.semester_id.semester_order is_internship = self.semester_id.is_internship if self.semester_id: print("self.semester_id.start_date") semester_start_date = self.semester_id.start_date.strftime('%d/%m/%Y') semester_end_date = self.semester_id.end_date.strftime('%d/%m/%Y') else: semester_start_date = '' semester_end_date = '' res = { "student_id": student_id, "semester_order": order, "semester_start_date": semester_start_date, "semester_end_date": semester_end_date, "course_id": self.course_id.id, "batch_id": self.batch_id.id, "semester_id": self.semester_id.id, "is_final": self.final } if self.final: print("check validation") internship_semester_count = self.env['pm.semester'].search_count([('batch_id', '=', self.batch_id.id), ('is_internship', '=', True)]) normal_semester_count = self.env['pm.semester'].search_count([('batch_id', '=', self.batch_id.id), ('is_internship', '=', False)]) student_internship_count = self.env['op.placement.offer'].search_count([('student_id', '=', student_id), ('batch_id', '=', self.batch_id.id), ('p_completed', '=', True)]) mark_sheets_count = self.env['pm.semester.marksheet.register'].search_count( [('batch_id', '=', self.batch_id.id), ('semester_id.is_internship', '=', False), ('state', '=', 'validated')]) _logger.info("---------------*****************************---------------") _logger.info('internship_semester_count %s', internship_semester_count) _logger.info('normal_semester_count %s', normal_semester_count) _logger.info('student_internship_count %s', student_internship_count) _logger.info('mark_sheets_count %s', mark_sheets_count) # if internship_semester_count != student_internship_count: # raise ValidationError( # "Internship hasn't finished yet. Please completed before generating transcript") if normal_semester_count != mark_sheets_count: raise ValidationError("Please validate semester result before generating transcript") return self.env.ref( 'pm_students.action_get_report_transcript') \ .report_action(self, data=res) elif is_internship: print('internshpip') count = self.env['op.placement.offer'].search_count( [('student_id', '=', student_id), ('semester_id', '=', self.semester_id.id), ('p_completed', '=', True)]) if count <= 0: raise ValidationError("Internship hasn't finised yet. Please completed before generating transcript") else: return self.env.ref( 'pm_students.action_get_report_transcript') \ .report_action(self, data=res) else: print("check validation") count = self.env['pm.semester.marksheet.register'].search_count( [('semester_id', '=', self.semester_id.id), ('state', '=', 'validated')]) if count <= 0: raise ValidationError("Please validate semester result before generating transcript") else: return self.env.ref( 'pm_students.action_get_report_transcript') \ .report_action(self, data=res)
mrrtmob/odoo_acac
local-addon/pm_general/wizards/student_transcript_wizard.py
student_transcript_wizard.py
py
5,635
python
en
code
0
github-code
6
74473926906
from django.shortcuts import render, redirect from .models import Diary from datetime import datetime import pytz import json diary_dict = {} response ={} def index(request): diary_dict = Diary.objects.all().values() if 'user_login' in request.session: response['user_name'] = request.session['user_login'] response['user_npm'] = request.session['kode_identitas'] response['author'] = "Arga Ghulam Ahmad" response['diary_dict'] = convert_queryset_into_json(diary_dict) response['button_logout_session'] = True return render(request, 'to_do_list.html', response) else: html = 'lab_9/session/login.html' return render(request, html, response) def add_activity(request): try: if request.method == 'POST': date = datetime.strptime(request.POST['date'], '%Y-%m-%dT%H:%M') Diary.objects.create(date=date.replace(tzinfo=pytz.UTC), activity=request.POST['activity']) return redirect('/lab-3/') except ValueError: pass finally: return redirect('/lab-3/') def convert_queryset_into_json(queryset): ret_val = [] for data in queryset: ret_val.append(data) return ret_val
argaghulamahmad/ppw-lab-arga
lab_3/views.py
views.py
py
1,230
python
en
code
0
github-code
6
10862291387
import glob import numpy as np from parsebook import Book import bookNBC def getData(loveBooksPath, horrorBooksPath): loveBooks = [] horrorBooks = [] lovefiles = glob.glob(loveBooksPath) for file in lovefiles: book = Book(file,"love") loveBooks.append(book) horrorfiles = glob.glob(horrorBooksPath) for file in horrorfiles: book = Book(file,"horror") horrorBooks.append(book) words = ["rose", "man", "like", "miss", "love", "smiles","around","hell", "something", "horror", "blood", "saw"] loveValues = Book.get_counts(loveBooks, words) horrorValues = Book.get_counts(horrorBooks, words) numattributes=len(words) loveData = np.insert(loveValues, numattributes, values=0, axis=1) horrorData = np.insert(horrorValues, numattributes, values=1, axis=1) data = [] data = np.concatenate((loveData, horrorData), axis=0) return numattributes, data
AndresGutierrez01/GenreSortingSystem
getData.py
getData.py
py
943
python
en
code
2
github-code
6
5412752271
""" Python script to scrape a web page for all email addresses """ from bs4 import BeautifulSoup import requests import requests.exceptions from urllib.parse import urlsplit import re url1 = "http://www.rit.edu/gccis/computingsecurity/people-categories/faculty" url2 = "https://www.rit.edu/its/about/staff" # a set of crawled emails emails = set() # get url's content print("Processing %s" % url2) response = requests.get(url2) # extract all email addresses and add them into the resulting set # regex for normally formatted emails. ex: [email protected] email_normal = set(re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", response.text, re.I)) emails.update(email_normal) # regex for emails formatted with a [dot]. ex: ahadsheriff@gmail[dot]com email_dot = set(re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\[dot\][A-Za-z]{2,4}", response.text, re.I)) emails.update(email_dot) # regex for emails formatted with [at] and [dot]. ex: ahadsheriff[at]gmail[dot]com email_at_dot = set(re.findall(r"[A-Za-z0-9._%+-]+\[at\][A-Za-z0-9.-]+\[dot\][A-Za-z]{2,4}", response.text, re.I)) emails.update(email_at_dot) print(emails)
ahadsheriff/security_suite
pentest_suite/beautiful_soup/email_regex/email_regex.py
email_regex.py
py
1,136
python
en
code
1
github-code
6
74537470908
import numpy as np import cv2 # 단일 채널 생성 및 초기화 m1 = np.full((3, 6), 10, np.uint8) m2 = np.full((3, 6), 50, np.uint8) m_mask = np.zeros(m1.shape, np.uint8) # 마스크 생성 m_mask[:, 3:] = 1 # 관심영역을 지정한 후, 1을 할당 m_add1 = cv2.add(m1, m2) # 행렬 덧셈 m_add2 = cv2.add(m1, m2, mask=m_mask) # 관심영역만 덧셈, 관심영역이 아닌 부분은 0 # 행렬 나눗셈 수행 m_div1 = cv2.divide(m1, m2) # 소수 부분 보존 위한 형변환 m1 = m1.astype(np.float32) m2 = np.float32(m2) m_div2 = cv2.divide(m1, m2) titles = ['m1', 'm2', 'm_mask', 'm_add1', 'm_add2', 'm_div1', 'm_div2'] for title in titles: print("[%s] = \n%s \n" % (title, eval(title)))
binlee52/OpenCV-python
ch05/04.arithmethic_op.py
04.arithmethic_op.py
py
772
python
ko
code
1
github-code
6
6812515285
import logging from scrim_bot.core.role import Role, RoleIsInvalid logger = logging.getLogger(__name__) class Player: """ Represents a player taking part in inhouse games """ _id: int _name: str roles: list[Role] elo: float summoner_name: str def __init__(self, _id: int, name: str, roles: list[str] = None, elo: float = None, summoner_name: str = None): self._id = _id self._name = name self.roles = [] self.elo = elo self.summoner_name = summoner_name if roles is not None: self.addRoles(roles) def __eq__(self, other): if isinstance(other, Player): return self.id == other.id return False def __name__(self, other): return not self.__eq__(other) def addRole(self, role: str): validated_role = Role.validateRole(role) if validated_role == Role.INVALID: logger.error(f"Role {role} is invalid") raise RoleIsInvalid(role) if validated_role in self.roles: logger.error(f"Role {validated_role.name} is already registered") return logger.info(f"Role {validated_role.name} has been registered") self.roles.append(validated_role) def addRoles(self, role_list: list[str]): for role in role_list: self.addRole(role) def removeRole(self, role: str): validated_role = Role.validateRole(role) if validated_role == Role.INVALID: logger.error(f"Role {role} is invalid") raise RoleIsInvalid(role) if validated_role not in self.roles: logger.error(f"Role {validated_role.name} is not registered") return logger.info(f"Role {validated_role} has been removed") self.roles.remove(validated_role) def removeRoles(self, role_list: list[str]): for role in role_list: self.removeRole(role) def getRoles(self): return [role.name for role in self.roles] @property def id(self): return self._id @property def name(self): return self._name # Encoding Player() object for MongoDB queries def encode_player(self): return {"_id": self._id, "name": self._name, "roles": self.getRoles(), "elo": self.elo, "summoner_name": self.summoner_name}
isvladu/inhouse-bot-lol
scrim_bot/core/player.py
player.py
py
2,392
python
en
code
0
github-code
6
12307666054
"""Utility script to be used to cleanup the notebooks before git commit This a mix from @minrk's various gists. """ import time import sys import os import io try: from queue import Empty except: # Python 2 backward compat from Queue import Empty try: from ipyparallel import Client except ImportError: # Backward compat prior to IPython / Jupyter split from IPython.parallel import Client try: import nbformat except ImportError: # Backward compat prior to IPython / Jupyter split from IPython import nbformat try: from jupyter_client.manager import KernelManager except ImportError: # Backward compat prior to IPython / Jupyter split from IPython.kernel import KernelManager def remove_outputs(nb): """Remove the outputs from a notebook""" if hasattr(nb, 'worksheets'): # nobody uses more than 1 worksheet ws = nb.worksheets[0] else: # no more worksheet level in new format ws = nb for cell in ws.cells: if cell.cell_type == 'code': cell.outputs = [] if 'prompt_number' in cell: del cell['prompt_number'] if 'execution_count' in cell: # notebook format v4 cell['execution_count'] = None def remove_signature(nb): """Remove the signature from a notebook""" if 'signature' in nb.metadata: del nb.metadata['signature'] def run_cell(kc, cell, timeout=300): if not hasattr(cell, 'input'): return [], False kc.execute(cell.input) # wait for finish, maximum 5min by default reply = kc.get_shell_msg(timeout=timeout)['content'] if reply['status'] == 'error': failed = True print("\nFAILURE:") print(cell.input) print('-----') print("raised:") print('\n'.join(reply['traceback'])) else: failed = False # Collect the outputs of the cell execution outs = [] while True: try: msg = kc.get_iopub_msg(timeout=0.2) except Empty: break msg_type = msg['msg_type'] if msg_type in ('status', 'pyin', 'execute_input'): continue elif msg_type == 'clear_output': outs = [] continue content = msg['content'] # IPython 3 writes pyerr/pyout in the notebook format but uses # error/execute_result in the message spec. This does the translation # needed for tests to pass with IPython 3 notebook3_format_conversions = { 'error': 'pyerr', 'execute_result': 'pyout' } msg_type = notebook3_format_conversions.get(msg_type, msg_type) out = nbformat.NotebookNode(output_type=msg_type) if 'execution_count' in content: cell['prompt_number'] = content['execution_count'] out.prompt_number = content['execution_count'] if msg_type == 'stream': out.stream = content['name'] # in msgspec 5, this is name, text # in msgspec 4, this is name, data if 'text' in content: out.text = content['text'] else: out.text = content['data'] elif msg_type in ('display_data', 'pyout'): for mime, data in content['data'].items(): attr = mime.split('/')[-1].lower() # this gets most right, but fix svg+html, plain attr = attr.replace('+xml', '').replace('plain', 'text') setattr(out, attr, data) elif msg_type == 'pyerr': out.ename = content['ename'] out.evalue = content['evalue'] out.traceback = content['traceback'] else: print("unhandled iopub msg: %s" % msg_type) outs.append(out) # Special handling of ipcluster restarts if '!ipcluster stop' in cell.input: # wait some time for cluster commands to complete for i in range(10): try: if len(Client()) == 0: break except OSError: pass sys.stdout.write("@") sys.stdout.flush() time.sleep(5) if '!ipcluster start' in cell.input: # wait some time for cluster commands to complete for i in range(10): try: if len(Client()) > 0: break except OSError: pass sys.stdout.write("#") sys.stdout.flush() time.sleep(5) return outs, failed def run_notebook(nb): km = KernelManager() km.start_kernel(stderr=open(os.devnull, 'w')) kc = km.client() kc.start_channels() try: kc.wait_for_ready() except AttributeError: # IPython < 3 kc.kernel_info() while True: msg = kc.get_shell_msg(block=True, timeout=30) if msg['msg_type'] == 'kernel_info_reply': break # Flush IOPub channel while True: try: msg = kc.get_iopub_msg(block=True, timeout=0.2) except Empty: break # simple ping: kc.execute("pass") kc.get_shell_msg() cells = 0 failures = 0 if hasattr(nb, 'worksheets'): # nobody uses more than 1 worksheet ws = nb.worksheets[0] else: # no more worksheet level in new format ws = nb for cell in ws.cells: if cell.cell_type != 'code': continue outputs, failed = run_cell(kc, cell) cell.outputs = outputs cell['prompt_number'] = cells failures += failed cells += 1 sys.stdout.write('.') sys.stdout.flush() print() print("ran %3i cells" % cells) if failures: print(" %3i cells raised exceptions" % failures) kc.stop_channels() km.shutdown_kernel() del km def process_notebook_file(fname, action='clean', output_fname=None): print("Performing '{}' on: {}".format(action, fname)) orig_wd = os.getcwd() # XXX: Ugly hack to preserve backward compat for now cmd = ('ipython nbconvert --to notebook --nbformat 3' ' --output="%s" "%s"') % (fname, fname) os.system(cmd) with io.open(fname, 'r') as f: nb = nbformat.read(f, nbformat.NO_CONVERT) if action == 'check': os.chdir(os.path.dirname(fname)) run_notebook(nb) remove_outputs(nb) remove_signature(nb) elif action == 'render': os.chdir(os.path.dirname(fname)) run_notebook(nb) else: # Clean by default remove_outputs(nb) remove_signature(nb) os.chdir(orig_wd) if output_fname is None: output_fname = fname with io.open(output_fname, 'w') as f: nb = nbformat.write(nb, f, nbformat.NO_CONVERT) if __name__ == '__main__': # TODO: use argparse instead args = sys.argv[1:] targets = [t for t in args if not t.startswith('--')] action = 'check' if '--check' in args else 'clean' action = 'render' if '--render' in args else action rendered_folder = os.path.join(os.path.dirname(__file__), 'rendered_notebooks') if not os.path.exists(rendered_folder): os.makedirs(rendered_folder) if not targets: targets = [os.path.join(os.path.dirname(__file__), 'notebooks')] for target in targets: if os.path.isdir(target): fnames = [os.path.abspath(os.path.join(target, f)) for f in sorted(os.listdir(target)) if f.endswith('.ipynb')] else: fnames = [target] for fname in fnames: if action == 'render': output_fname = os.path.join(rendered_folder, os.path.basename(fname)) else: output_fname = fname process_notebook_file(fname, action=action, output_fname=output_fname)
ogrisel/parallel_ml_tutorial
ipynbhelper.py
ipynbhelper.py
py
8,087
python
en
code
1,592
github-code
6
30160884075
# Write an action print, To debug: print("Debug messages", file=sys.stderr) import sys import math def available_neighboors(grid, r, c): res = [] for cor in ((r+1, c),(r-1, c), (r, c+1), (r, c-1)): if grid[cor[0]][cor[1]] != '#': res.append((cor[0],cor[1])) return res def calculate_next_direction(r, c, nr, nc): if nr - r > 0: return 'DOWN' elif nr - r < 0 : return 'UP' elif nc - c > 0: return 'RIGHT' else: return 'LEFT' def bfs(initial_coordinates, grid, goal): dic_parents = {} memory = set() queue = [] queue.append(initial_coordinates) memory.add(initial_coordinates) while len(queue) > 0: r,c = queue.pop(0) for rn, cn in available_neighboors(grid, r, c): if (rn, cn) not in memory: dic_parents[(rn, cn)] = (r, c) if grid[rn][cn]==goal: while (rn, cn) in dic_parents: (rnew, cnew) = dic_parents[(rn, cn)] if (rnew, cnew) == initial_coordinates: return rn,cn else: (rn,cn) = (rnew,cnew) memory.add((rn, cn)) queue.append((rn, cn)) print("BFS did not found goal", file=sys.stderr) return (-1,-1) # H: number of rows. # W: number of columns. # a: number of rounds between the time the alarm countdown is activated and the time the alarm goes off. H, W, a = [int(i) for i in input().split()] goals = (s for s in ['C','T']) goal = '?' # game loop while True: # kr: row where Kirk is located. # kc: column where Kirk is located. kr, kc = [int(i) for i in input().split()] grid = list([input() for _ in range(H)]) nr, nc = bfs((kr,kc), grid, goal) if (nr, nc) ==(-1,-1): goal = next(goals) nr, nc = bfs((kr,kc), grid, goal) print(f'goal : {goal}', file=sys.stderr) print(f'Kirk : {kr},{kc}', file=sys.stderr) print(f'Go to :{nr}{nc}', file=sys.stderr) direction = calculate_next_direction(kr,kc, nr,nc) print(direction)
PierreMsy/CodeGames
CodinGame/Maze.py
Maze.py
py
2,183
python
en
code
0
github-code
6
21097703844
from invenio.ext.sqlalchemy import db domain = 'BBMRI' # display_name = 'Biobanking and BioMolecular Resources Research Infrastructure' display_name = 'Biomedical Research' table_name = 'BBMRI' image = 'domain-bbmri.png' kind = 'project' domaindesc = 'Biomedical research data.' fields = [ { 'name': 'study_id', 'col_type': db.String(256), 'display_text': 'Study ID', 'description': 'The unique ID or acronym for the study', 'required': False }, { 'name': 'study_name', 'col_type': db.String(256), 'display_text': 'Study name', 'description': 'The name of the study in English', 'required': False }, { 'name': 'study_description', 'col_type': db.String(256), 'display_text': 'Study Description', 'description': 'A description of the study aim', 'required': False }, { 'name': 'principal_investigator', 'col_type': db.String(256), 'display_text': 'Principal Investigator', 'description': 'The name of the person responsible for the study or the principal investigator', 'required': False }, { 'name': 'study_design', 'col_type': db.String(256), 'display_text': 'Study design', 'data_provide': 'select', 'cardinality': 'n', 'description': 'The type of study. Can be one or several of the following values.', 'data_source': ['Case-control', 'Cohort', 'Cross-sectional', 'Longitudinal', 'Twin-study', 'Quality control', 'Population-based', 'Other'], 'required': False }, { 'name': 'disease', 'col_type': db.String(256), 'display_text': 'Disease', 'description': 'The disease of main interest in the sample collection, if any. Can be several values MIABIS-21', 'required': False }, { 'name': 'categories_of_data_collected', 'col_type': db.String(256), 'display_text': 'Categories of data collected', 'description': 'The type of data collected in the study, and if biological samples are part of the study. ' 'Can be one or several of the following values: ' 'Biological samples, Register data, Survey data, ' 'Physiological measurements, Imaging data, Medical records, Other', 'data_provide': 'select', 'cardinality': 'n', 'data_source': ['Biological samples', 'Register data', 'Survey data', 'Physiological measurements', 'Imaging data', 'Medical records', 'Other'], 'required': False }, { 'name': 'planned_sampled_individuals', 'col_type': db.String(256), 'display_text': 'Planned sampled individuals', 'description': 'Number of individuals with biological samples planned for the study', 'required': False }, { 'name': 'planned_total_individuals', 'col_type': db.String(256), 'display_text': 'Planned total individuals', 'description': 'Total number of individuals planned for the study with or without biological samples', 'required': False }, { 'name': 'sex', 'col_type': db.String(256), 'display_text': 'Sex', 'description': 'The sex of the study participants. Can be several of the following values: Female, Male, Other', 'data_provide': 'select', 'cardinality': 'n', 'data_source': ['Female', 'Male', 'Other'], 'required': False }, { 'name': 'age_interval', 'col_type': db.String(256), 'display_text': 'Age interval', 'description': 'Age interval of youngest to oldest study participant, for example 40-80', 'required': False }, { 'name': 'material_type', 'col_type': db.String(256), 'display_text': 'Material type', 'description': 'The nature of the biological samples that are included in the study, if any. ' 'Can be one or several of the following values: ' 'Whole blood, Plasma, Serum, Urine, Saliva, CSF, DNA, RNA, Tissue, Faeces, Other', 'data_provide': 'select', 'cardinality': 'n', 'data_source': ['Whole blood', 'Plasma', 'Serum', 'Urine', 'Saliva', 'CSF', 'DNA', 'RNA', 'Tissue', 'Faeces', 'Other'], 'required': False }, ]
cjhak/b2share
invenio/b2share/modules/b2deposit/b2share_model/metadata/bbmri_metadata_config.py
bbmri_metadata_config.py
py
4,523
python
en
code
null
github-code
6
10035856253
"""Training script for End-to-end visuomotor controllers.""" import argparse import os from stat import ST_CTIME import shutil import re import json import pprint import tensorflow as tf from data.geeco_gym import pickplace_input_fn from models.e2evmc.estimator import e2evmc_model_fn, goal_e2evmc_model_fn from models.e2evmc.params import create_e2evmc_config from models.e2evmc.utils import save_model_config, load_model_config from utils.runscript import save_run_command # ---------- command line arguments ---------- ARGPARSER = argparse.ArgumentParser(description='Train E2E VMC.') # --- directory parameters ARGPARSER.add_argument( '--dataset_dir', type=str, default='../data/gym-pick-pad2-cube2-v4', help='The path to the dataset (needs to conform with gym_provider).') ARGPARSER.add_argument( '--split_name', type=str, default='default', help='The name of the data split to be used.') ARGPARSER.add_argument( '--model_dir', type=str, default='../tmp/models/geeco-f', help='The directory where the model will be stored.') # --- model parameters ARGPARSER.add_argument( '--observation_format', type=str, default='rgb', help='Observation data to be used (sets img_channels): rgb | rgbd.') ARGPARSER.add_argument( '--control_mode', type=str, default='cartesian', help='Control mode of the robot: cartesian | velocity.') ARGPARSER.add_argument( '--goal_condition', type=str, default='none', help='Conditioning mode of the reflex. Options are: none | target. \ none = no goal provided, unconditional reflex \ target = target image provided, conditional reflex') ARGPARSER.add_argument( '--window_size', type=int, default=4, help='The number of frames to process before making prediction.') ARGPARSER.add_argument( '--dim_h_lstm', type=int, default=128, help='Hidden state dimension of the LSTM.') ARGPARSER.add_argument( '--dim_h_fc', type=int, default=128, help='Output dimension of the LSTM (before decoding heads).') ARGPARSER.add_argument( '--dim_s_obs', type=int, default=256, help='Output dimension of the observation encoding.') ARGPARSER.add_argument( '--dim_s_dyn', type=int, default=256, help='Output dimension of the dynamics encoding.') ARGPARSER.add_argument( '--dim_s_diff', type=int, default=256, help='Output dimension of the target difference encoding.') ARGPARSER.add_argument( '--proc_obs', type=str, default='sequence', help='The processing type of the frame buffer: sequence | dynimg') ARGPARSER.add_argument( '--proc_tgt', type=str, default='constant', help='The processing type of the target frame: constant | residual | dyndiff') ARGPARSER.add_argument( '--l2_regularizer', type=float, default=0.0, help='The weight of the L2 weight regularizer. Zero disables weight regularization.') ARGPARSER.add_argument( '--lambda_aux', type=float, default=1.0, help='The weight of the auxiliary pose prediction losses. Zero disables them.') # --- data parameters ARGPARSER.add_argument( '--data_encoding', type=str, default='v4', help='Version of the data encoding. Available: v1 | v2 | v3 | v4') # --- training parameters ARGPARSER.add_argument( '--lr', type=float, default=1e-4, help='The learning rate of the ADAM solver.') ARGPARSER.add_argument( '--train_epochs', type=int, default=10, help='The number of epochs to train.') # --- snapshot management ARGPARSER.add_argument( '--ckpt_steps', type=int, default=10000, help='Number of steps between checkpoint saves.') ARGPARSER.add_argument( '--num_last_ckpt', type=int, default=2, help='Number of last snapshots to keep.') ARGPARSER.add_argument( '--num_best_ckpt', type=int, default=5, help='Number of best performing snapshots to keep.') # --- memory management ARGPARSER.add_argument( '--batch_size', type=int, default=32, help='The number of data points per batch. Each data points contains \ `window_size` number of annotated frames as well as a tensor containing \ the target commands.') ARGPARSER.add_argument( '--memcap', type=float, default=0.8, help='Maximum fraction of memory to allocate per GPU.') ARGPARSER.add_argument( '--num_threads', type=int, default=4, help='How many parallel threads to run for data fetching.') ARGPARSER.add_argument( '--prefetch_size', type=int, default=4, help='How many batches to prefetch.') ARGPARSER.add_argument( '--shuffle_buffer', type=int, default=64, help='Number of shuffled examples to draw minibatch from.') # --- logging ARGPARSER.add_argument( '--log_steps', type=int, default=1000, help='Global steps between log output.') ARGPARSER.add_argument( '--debug', default=False, action='store_true', help="Enables debugging mode for more verbose logging and tensorboard \ output.") ARGPARSER.add_argument( '--initial_eval', default=False, action='store_true', help="Runs an evaluation before the first training iteration.") # ---------- constants ---------- _OBSERVATION_FORMAT_TO_CHANNELS = { 'rgb' : 3, 'rgbd' : 4, } _GOAL_CONDITION_TO_MODEL = { # cond -> (model_fn, model_scope) 'none' : (e2evmc_model_fn, 'VMC'), 'target' : (goal_e2evmc_model_fn, 'GoalVMC'), } # ---------- helper_fn ---------- # TODO: refactor into general training utils def _export_snapshot(model_dir, eval_results, num_best_ckpt): """ Manages `num_best_ckpt` snapshots of the best performing models according to eval_results['loss'] in <model_dir>/snapshots/ """ # --- directory setup snapshots_dir = os.path.join(model_dir, 'snapshots') os.makedirs(snapshots_dir, exist_ok=True) # --- snapshot index snapshot_index_file = os.path.join(snapshots_dir, 'snapshot_index.json') if os.path.exists(snapshot_index_file): # load snapshot index with open(snapshot_index_file, 'r') as fp: snapshot_index = json.load(fp) else: # create new snapshot index snapshot_index = {} # <snapshot_name> -> {step, loss, dir} print(">>> Current snapshot index contains %d entries." % len(snapshot_index)) # DEBUG # --- get latest runcmd, config, step and loss ckpt_name = os.path.basename(tf.train.latest_checkpoint(model_dir)) step = int(re.search(r'\d+', ckpt_name).group(0)) loss = float(eval_results['loss']) runcmd_files = [fn for fn in os.listdir(model_dir) if fn.endswith('runcmd.json')] runcmd_files = [os.path.join(model_dir, fn) for fn in runcmd_files] runcmd_files = [(fn, os.stat(fn)[ST_CTIME]) for fn in runcmd_files] runcmd_files.sort(key=lambda t: t[1]) # sort by creation date asc runcmd_path = runcmd_files[-1][0] # get latest ending in _runcmd.json config_files = [fn for fn in os.listdir(model_dir) if fn.endswith('config.json')] config_files = [os.path.join(model_dir, fn) for fn in config_files] config_files = [(fn, os.stat(fn)[ST_CTIME]) for fn in config_files] config_files.sort(key=lambda t: t[1]) # sort by creation date asc config_path = config_files[-1][0] # get latest ending in _config.json # --- export current checkpoint to <model_dir>/snapshots/<ckpt_name> ckpt_dir = os.path.join(snapshots_dir, ckpt_name) os.makedirs(ckpt_dir, exist_ok=True) for cfg_fn in [runcmd_path, config_path]: # copy configs shutil.copy(src=cfg_fn, dst=ckpt_dir) for ckpt_fn in [fn for fn in os.listdir(model_dir) if fn.startswith(ckpt_name)]: # checkpoint files shutil.copy(src=os.path.join(model_dir, ckpt_fn), dst=ckpt_dir) with open(os.path.join(ckpt_dir, 'checkpoint'), 'w') as fp: # create checkpoint header fp.write("model_checkpoint_path: \"%s\"\n" % ckpt_name) print(">>> Exported current checkpoint (step=%d; loss=%.06f) to %s." % (step, loss, ckpt_dir)) # DEBUG pprint.pprint(os.listdir(ckpt_dir)) # DEBUG # --- update index snapshot_index[ckpt_name] = { 'step' : step, 'loss' : loss, 'dir' : ckpt_dir, } # --- gc worst snapshot, if save slots are exceeded if len(snapshot_index) > num_best_ckpt: ckpt_by_loss = list(snapshot_index.items()) ckpt_by_loss.sort(key=lambda t: t[1]['loss']) worst_ckpt, _ = ckpt_by_loss[-1] # get worst checkpoint name worst_ckpt_dir = snapshot_index[worst_ckpt]['dir'] shutil.rmtree(worst_ckpt_dir) worst_info = snapshot_index.pop(worst_ckpt) print(">>> Removed worst snapshot (step=%d; loss=%.06f): %s" % \ (worst_info['step'], worst_info['loss'], worst_info['dir'])) # DEBUG # --- save snapshot index pprint.pprint(snapshot_index) # DEBUG with open(snapshot_index_file, 'w') as fp: json.dump(snapshot_index, fp, indent=2, sort_keys=True) print(">>> Saved snapshot index: %s" % snapshot_index_file) return ckpt_dir # ---------- main ---------- def main(args): """Executes the model training.""" # --- directory setup os.makedirs(name=args.model_dir, exist_ok=True) # --- run command run_cmd_path = save_run_command(argparser=ARGPARSER, run_dir=args.model_dir) # --- run config gpu_options = tf.GPUOptions( allow_growth=True, per_process_gpu_memory_fraction=args.memcap) sess_config = tf.ConfigProto(gpu_options=gpu_options) run_config = tf.estimator.RunConfig( session_config=sess_config, save_checkpoints_steps=args.ckpt_steps, keep_checkpoint_max=args.num_last_ckpt) # --- model config, TODO: refactor config CLI interface, loading and merging into model utils config_name = 'e2evmc_config' # TODO: add config name CLI parameter config_fn = "%s.json" % (config_name, ) config_path = os.path.join(args.model_dir, config_fn) if os.path.exists(config_path): # load model config from previous run custom_params = load_model_config(args.model_dir, config_name) e2evmc_config = create_e2evmc_config(custom_params) print(">>> Loaded existing model config from %s" % (config_path, )) else: # create new model config from CLI parameters custom_params = { 'img_channels' : _OBSERVATION_FORMAT_TO_CHANNELS[args.observation_format], 'control_mode' : args.control_mode, 'window_size' : args.window_size, 'dim_h_lstm' : args.dim_h_lstm, 'dim_h_fc' : args.dim_h_fc, 'dim_s_obs' : args.dim_s_obs, 'dim_s_dyn' : args.dim_s_dyn, 'dim_s_diff' : args.dim_s_diff, 'proc_obs' : args.proc_obs, 'proc_tgt' : args.proc_tgt, 'l2_regularizer' : args.l2_regularizer, 'lambda_aux' : args.lambda_aux, 'batch_size' : args.batch_size, 'lr' : args.lr, } e2evmc_config = create_e2evmc_config(custom_params) save_model_config(e2evmc_config._asdict(), args.model_dir, config_name) print(">>> Saved model config to %s" % (config_path, )) # --- estimator setup estimator_params = { 'e2evmc_config' : e2evmc_config, 'log_steps' : args.log_steps, 'debug' : args.debug, } model_fn, model_scope = _GOAL_CONDITION_TO_MODEL[args.goal_condition] estimator = tf.estimator.Estimator( model_fn=model_fn, model_dir=args.model_dir, config=run_config, params=estimator_params) # --- data pipeline input_fn = lambda estimator_mode: pickplace_input_fn( dataset_dir=args.dataset_dir, split_name=args.split_name, mode=estimator_mode, encoding=args.data_encoding, window_size=e2evmc_config.window_size, fetch_target=(args.goal_condition == 'target'), shuffle_buffer=args.shuffle_buffer, batch_size=args.batch_size, num_epochs=1, num_threads=args.num_threads, prefetch_size=args.prefetch_size, seed=None) train_input = lambda: input_fn(estimator_mode='train') eval_input = lambda: input_fn(estimator_mode='eval') # --- extended init if args.initial_eval: eval_results = estimator.evaluate(input_fn=eval_input) # _export_snapshot(args.model_dir, eval_results, args.num_best_ckpt) # --- main training loop for epoch_id in range(args.train_epochs): estimator.train(input_fn=train_input) eval_results = estimator.evaluate(input_fn=eval_input) _export_snapshot(args.model_dir, eval_results, args.num_best_ckpt) if __name__ == '__main__': print(">>> Training E2E VMC.") PARSED_ARGS, UNPARSED_ARGS = ARGPARSER.parse_known_args() print(">>> PARSED ARGV:") pprint.pprint(PARSED_ARGS) print(">>> UNPARSED ARGV:") pprint.pprint(UNPARSED_ARGS) tf.logging.set_verbosity(tf.logging.INFO) main(PARSED_ARGS)
ogroth/geeco
scripts/train_e2evmc.py
train_e2evmc.py
py
12,436
python
en
code
7
github-code
6
18625152569
import os import json import requests from bs4 import BeautifulSoup from datetime import datetime as dt import pandas as pd from __common__ import user_choice def __load_json__(file): """ """ try: with open(file) as rf: data = json.load(rf) return data except: return {} def __get_links__(url, base_url): """ """ r = requests.get(url) soup = BeautifulSoup(r.text) link_dict = {} ignore = ['[To Parent Directory]', 'DUPLICATE'] for link in soup.findAll('a'): if link.text in ignore : pass else: link_dict[link.text] = base_url+link.get('href') return link_dict def __gen_file_name__(data_keys, resource_type): """ """ if resource_type == 'Archive': i = -1 else: i = -2 name = set(map(lambda x: '-'.join(x.split('_')[:i]).lower(), data_keys)) name = list(name) if len(name) > 1: print("More than one file type detected!") return None else: if resource_type == 'Archive': name = '-'.join([name[0],resource_type.lower()]) else: name = name[0] return name + '.csv' def __gen_tracker_df__(data_files, data_keys, resource_type): """ """ if resource_type == 'Archive': timestamp = pd.to_datetime(list(map(lambda x: x.split('_')[-1][:-4], data_keys))) version = resource_type else: timestamp = pd.to_datetime(list(map(lambda x: x.split('_')[-2], data_keys))) version = list(map(lambda x: 'V'+x.split('_')[-1][:-4], data_keys)) data_dict = { 'TIMESTAMP': timestamp, 'VERSION': version, 'DOWNLOADED': False, 'DOWNLOAD_DATE': pd.to_datetime('19000101'), 'URL': list(data_files.values()) } return pd.DataFrame(data_dict) def __merge_trackers__(old_df, new_df): """ Add anything from new_df that is not in old_df already """ merge_cols = ['TIMESTAMP', 'VERSION'] old_temp = old_df.copy()[merge_cols] new_temp = new_df.copy()[merge_cols] merge_df = pd.merge(old_temp, new_temp, on=merge_cols, how='outer', indicator=True) # rows no longer in CURRENT NEM reports old_rows = merge_df[merge_df["_merge"]=="left_only"] old_rows = old_rows[merge_cols].merge(old_df, on=merge_cols) # keep only old rows that have been downloaded # else they need to extracted from ARCHIVE or older records old_rows = old_rows[old_rows.DOWNLOADED] # for common rows, must keep old_df records com_rows = merge_df[merge_df["_merge"]=="both"] com_rows = com_rows[merge_cols].merge(old_df, on=merge_cols) # for new rows, use latest records new_rows = merge_df[merge_df["_merge"]=="right_only"] new_rows = new_rows[merge_cols].merge(new_df, on=merge_cols) return pd.concat([old_rows, com_rows, new_rows], ignore_index=True) class NEM_tracker: """ Class object for tracking various resources on NEM website. Can potentially be extended to other websites too. """ def __init__(self, data_dir, base_url="http://nemweb.com.au"): """ """ self.data_dir = data_dir self.base_url = base_url self.resource_path = os.path.join(data_dir, 'resources.json') self.resources = __load_json__(self.resource_path) self.selected_resource = None self.tracker_dir = os.path.join(data_dir, 'resource_trackers') if os.path.isdir(self.tracker_dir): pass else: os.makedirs(self.tracker_dir) def resources_report(self): """ """ for k, v in self.resources.items(): print('\n%s\nLast update: %s'%(k, v['last_update'])) def update_resource(self, resource): """ """ url = self.base_url + resource data_files = __get_links__(url, self.base_url) data_keys = list(data_files.keys()) resource_type = resource.split('/')[2] file_name = __gen_file_name__(data_keys, resource_type) self.resources[resource] = { 'url': url, 'type': resource_type, 'tracker_file': file_name, 'last_update': dt.now().strftime('%Y-%m-%d-%H:%M:%S') } with open(self.resource_path, 'w') as wf: json.dump(self.resources, wf) new_df = __gen_tracker_df__(data_files, data_keys, resource_type) file_path = os.path.join(self.tracker_dir, file_name) if file_name in os.listdir(self.tracker_dir): old_df = pd.read_csv(file_path, parse_dates=[ 'TIMESTAMP', 'DOWNLOAD_DATE' ]) tracker_df = __merge_trackers__(old_df, new_df) else: tracker_df = new_df tracker_df.to_csv(file_path, index=False) def add_resources(self, resources): """ For adding new resources. Resources must be specified as the relative URL path from the domain to the directory where all relevant data files are stored. E.g. /Reports/Current/Next_Day_Intermittent_DS/ """ if type(resources) is not list: resources = [resources] else: pass for resource in resources: self.update_resource(resource) def bulk_update(self): """ For updating existing resources. """ for resource in self.resources.keys(): self.update_resource(resource) def select_resource(self, resource=None): """ Select a resource for further processing. """ d = {} if resource is None: res_list = self.resources.keys() name = user_choice(res_list) else: name = resource d['name'] = name tracker_file = self.resources[name]['tracker_file'] d['tracker_path'] = os.path.join(self.tracker_dir, tracker_file) d['resource_dir'] = os.path.join(self.data_dir, tracker_file[:-4]) self.selected_resource = d
robbie-manolache/energy-market-analysis
nemtel/tracker.py
tracker.py
py
6,567
python
en
code
0
github-code
6
41061175651
import numpy as np import torch import torch.nn.functional as F import torch.nn as nn import os import cv2 as cv def rgb2gray(rgb): ''' Transforms frame into a grayscale Args: rgb (numpy array) : numpy array grayscaled ''' r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2] gray = 0.2989 * r + 0.5870 * g + 0.1140 * b return gray def transform_frame(frame, n): ''' Transform the size of the frame. Note that the frame should be shaped M*M*3 (square) Args: frame (numpy array) : shaped M*M*3 n (int) : new size of the frame (n*n*3) Returns: frame (torch tensor) : shaped n*n*3 ''' shape = frame.shape assert len(shape) == 3 assert shape[0] == shape[1] and shape[2] == 3 color0 = frame[:,:,0] color1 = frame[:,:,1] color2 = frame[:,:,2] current_frame = np.array([color0, color1, color2]) batch = torch.from_numpy(current_frame).unsqueeze(0) batch = F.interpolate(batch.float(), (n, n)) small_frame = batch.squeeze(0) #print(small_frame.permute(1,2,0).shape) return small_frame.permute(1,2,0) #return -small_frame[0,:,:].unsqueeze(dim = -1) def discount_rewards(r, gamma): ''' Discounted sum of the rewards : r_t + gamma * r_{t+1} + gamma^2 * r_{t+2} ... Args: r (list) : List of rewards returned by the environment gamma (float) : discount factor Return: dr (float) : discounted sum of the rewards ''' discounted_r = torch.zeros_like(r) running_add = 0 for t in reversed(range(0, r.size(-1))): running_add = running_add * gamma + r[t] discounted_r[t] = running_add return discounted_r class PrintLayer(nn.Module): ''' Print layer shapes inside a sequential structure ''' def __init__(self): super(PrintLayer, self).__init__() def forward(self, x): # Do your print / debug stuff here print(x.shape) return x def listdir_nohidden(path): ''' Extension to os.listdir to ignore files starting with '.' or '_' ''' for f in os.listdir(path): if not (f.startswith('.') or f.startswith('_')): yield f def render_video(path): ''' Renders a video provided as a path. Args: path (numpy array, compressed format) : array of frames ''' # TODO: support for compressed format video = np.load(path) for frame in video: cv.imshsow("", frame) cv.waitKey(33)
ylajaaski/reinforcement_env
src/utils.py
utils.py
py
2,534
python
en
code
0
github-code
6
32610163975
from mercurial import archival, cmdutil, commands, extensions, filemerge, hg, \ httprepo, localrepo, merge, sshrepo, sshserver, wireproto from mercurial.i18n import _ from mercurial.hgweb import hgweb_mod, protocol, webcommands from mercurial.subrepo import hgsubrepo import overrides import proto def uisetup(ui): # Disable auto-status for some commands which assume that all # files in the result are under Mercurial's control entry = extensions.wrapcommand(commands.table, 'add', overrides.overrideadd) addopt = [('', 'large', None, _('add as largefile')), ('', 'normal', None, _('add as normal file')), ('', 'lfsize', '', _('add all files above this size ' '(in megabytes) as largefiles ' '(default: 10)'))] entry[1].extend(addopt) entry = extensions.wrapcommand(commands.table, 'addremove', overrides.overrideaddremove) entry = extensions.wrapcommand(commands.table, 'remove', overrides.overrideremove) entry = extensions.wrapcommand(commands.table, 'forget', overrides.overrideforget) # Subrepos call status function entry = extensions.wrapcommand(commands.table, 'status', overrides.overridestatus) entry = extensions.wrapfunction(hgsubrepo, 'status', overrides.overridestatusfn) entry = extensions.wrapcommand(commands.table, 'log', overrides.overridelog) entry = extensions.wrapcommand(commands.table, 'rollback', overrides.overriderollback) entry = extensions.wrapcommand(commands.table, 'verify', overrides.overrideverify) verifyopt = [('', 'large', None, _('verify largefiles')), ('', 'lfa', None, _('verify all revisions of largefiles not just current')), ('', 'lfc', None, _('verify largefile contents not just existence'))] entry[1].extend(verifyopt) entry = extensions.wrapcommand(commands.table, 'outgoing', overrides.overrideoutgoing) outgoingopt = [('', 'large', None, _('display outgoing largefiles'))] entry[1].extend(outgoingopt) entry = extensions.wrapcommand(commands.table, 'summary', overrides.overridesummary) summaryopt = [('', 'large', None, _('display outgoing largefiles'))] entry[1].extend(summaryopt) entry = extensions.wrapcommand(commands.table, 'update', overrides.overrideupdate) entry = extensions.wrapcommand(commands.table, 'pull', overrides.overridepull) entry = extensions.wrapcommand(commands.table, 'cat', overrides.overridecat) entry = extensions.wrapfunction(merge, '_checkunknownfile', overrides.overridecheckunknownfile) entry = extensions.wrapfunction(merge, 'manifestmerge', overrides.overridemanifestmerge) entry = extensions.wrapfunction(filemerge, 'filemerge', overrides.overridefilemerge) entry = extensions.wrapfunction(cmdutil, 'copy', overrides.overridecopy) # Summary calls dirty on the subrepos entry = extensions.wrapfunction(hgsubrepo, 'dirty', overrides.overridedirty) # Backout calls revert so we need to override both the command and the # function entry = extensions.wrapcommand(commands.table, 'revert', overrides.overriderevert) entry = extensions.wrapfunction(commands, 'revert', overrides.overriderevert) # clone uses hg._update instead of hg.update even though they are the # same function... so wrap both of them) extensions.wrapfunction(hg, 'update', overrides.hgupdate) extensions.wrapfunction(hg, '_update', overrides.hgupdate) extensions.wrapfunction(hg, 'clean', overrides.hgclean) extensions.wrapfunction(hg, 'merge', overrides.hgmerge) extensions.wrapfunction(archival, 'archive', overrides.overridearchive) extensions.wrapfunction(cmdutil, 'bailifchanged', overrides.overridebailifchanged) # create the new wireproto commands ... wireproto.commands['putlfile'] = (proto.putlfile, 'sha') wireproto.commands['getlfile'] = (proto.getlfile, 'sha') wireproto.commands['statlfile'] = (proto.statlfile, 'sha') # ... and wrap some existing ones wireproto.commands['capabilities'] = (proto.capabilities, '') wireproto.commands['heads'] = (proto.heads, '') wireproto.commands['lheads'] = (wireproto.heads, '') # make putlfile behave the same as push and {get,stat}lfile behave # the same as pull w.r.t. permissions checks hgweb_mod.perms['putlfile'] = 'push' hgweb_mod.perms['getlfile'] = 'pull' hgweb_mod.perms['statlfile'] = 'pull' extensions.wrapfunction(webcommands, 'decodepath', overrides.decodepath) # the hello wireproto command uses wireproto.capabilities, so it won't see # our largefiles capability unless we replace the actual function as well. proto.capabilitiesorig = wireproto.capabilities wireproto.capabilities = proto.capabilities # these let us reject non-largefiles clients and make them display # our error messages protocol.webproto.refuseclient = proto.webprotorefuseclient sshserver.sshserver.refuseclient = proto.sshprotorefuseclient # can't do this in reposetup because it needs to have happened before # wirerepo.__init__ is called proto.ssholdcallstream = sshrepo.sshrepository._callstream proto.httpoldcallstream = httprepo.httprepository._callstream sshrepo.sshrepository._callstream = proto.sshrepocallstream httprepo.httprepository._callstream = proto.httprepocallstream # don't die on seeing a repo with the largefiles requirement localrepo.localrepository.supported |= set(['largefiles']) # override some extensions' stuff as well for name, module in extensions.extensions(): if name == 'fetch': extensions.wrapcommand(getattr(module, 'cmdtable'), 'fetch', overrides.overridefetch) if name == 'purge': extensions.wrapcommand(getattr(module, 'cmdtable'), 'purge', overrides.overridepurge) if name == 'rebase': extensions.wrapcommand(getattr(module, 'cmdtable'), 'rebase', overrides.overriderebase) if name == 'transplant': extensions.wrapcommand(getattr(module, 'cmdtable'), 'transplant', overrides.overridetransplant)
Anderson-Lab/Learn2Mine-Main
galaxy-dist/eggs/mercurial-2.2.3-py2.7-macosx-10.6-intel-ucs2.egg/hgext/largefiles/uisetup.py
uisetup.py
py
6,985
python
en
code
2
github-code
6
74363302909
#!/usr/bin/python3 ''' A simple matrix module ''' def matrix_divided(matrix, div): ''' A function that divides all elements of a matrix ''' error_msg = 'matrix must be a matrix (list of lists) of integers/floats' if not all( isinstance(row, list) and all( isinstance(element, (int, float)) for element in row ) for row in matrix ): raise TypeError(error_msg) row_sizes = set(len(row) for row in matrix) if len(row_sizes) > 1: raise TypeError('Each row of the matrix must have the same size') if not isinstance(div, (int, float)): raise TypeError('div must be a number') if div == 0: raise ZeroDivisionError('division by zero') result_matrix = [] for row in matrix: new_row = [round(element / div, 2) for element in row] result_matrix.append(new_row) return result_matrix
ugwujustine/alx-higher_level_programming
0x07-python-test_driven_development/2-matrix_divided.py
2-matrix_divided.py
py
922
python
en
code
0
github-code
6
73732952507
#!/usr/bin/env python import requests import base64 import random import sys def getPicText_bdOcr(pic_binary, type_index = 1): ''' 利用百度 ocr 接口识别文字 pic_binary 是图片文件的二进制数据 type_index 是百度提供的识别类型 0 表示一般识别, 1 表示精准识别 如果成功,则返回识别出的文字字符串 如果出错,则返回错误信息 ''' # 获取 appid 的 cookie cookie = requests.get('http://ai.baidu.com/tech/ocr/general').headers["Set-Cookie"] baiduid_cookie = cookie[:cookie.find(';')] # 准备头部 headers = { 'Cookie': baiduid_cookie, 'Referer': "http://ai.baidu.com/tech/ocr/general" } # 准备数据 post_type_l = ['general_location' , 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate'] if type_index is None: post_type = post_type_l[random.randint(0, len(post_type_l) - 1)] # 两个类型随机选个类型 else: post_type = post_type_l[type_index] post_data = { 'type': post_type, 'detect_direction': 'false', 'image_url': None, 'image': 'data:image/jpeg;base64,' + base64.b64encode(pic_binary).decode('utf-8'), 'language_type': 'CHN_ENG' } # 发送 post 请求 response = requests.post('http://ai.baidu.com/aidemo', data = post_data, headers = headers) # 解析请求结果 response_json = response.json() errno = response_json['errno'] if errno != 0: return '我这边出错啦!' + response_json['msg'] data = response_json['data'] words_result_num = data['words_result_num'] words_result = data['words_result'] result = '' for w in words_result: result += w['words'] + '\n' return result.strip() if __name__ == '__main__': # 检查参数长度 if len(sys.argv) < 2: sys.stderr.write('缺少文件位置参数\n') exit(1) pic_binary = open(sys.argv[1], 'rb').read() print(getPicText_bdOcr(pic_binary, 1))
fkxxyz/fkxxyz-wechatRequestHandler
baiduOcr.py
baiduOcr.py
py
2,061
python
en
code
0
github-code
6
1970824683
class elevator(): #defining elevator characteristics def __init__(self, currentFloor = 1, serviceMode = False, maxHeight = 20, minHeight = 1): self.currentFloor = currentFloor self.inServiceMode = serviceMode self.maxHeight = maxHeight self.minHeight = minHeight def goToFloor(self, move): #method that moves elevator if move >= self.minHeight and move <= self.maxHeight: #checks movement range if self.inServiceMode == False: #checks mode self.currentFloor = move print("The elevator moved to " + str(self.currentFloor) + ".") else: print("Elevator in service mode.") else: print("Floor out of range.") def __str__(self): #returns elevator information if(self.inServiceMode): return "SERVICE MODE: The elevator is in service on floor " + str(self.currentFloor) + "." else: return "The elevator is on floor " + str(self.currentFloor) + "." class smartElevator(elevator): #Smart elevator characteristics def __init__(self, currentFloor = 1, serviceMode = False, maxHeight = 20, minHeight = 1): super().__init__(currentFloor, serviceMode) def goToFloor(self, move): #method moves and shows elevator moving if move >= self.minHeight and move <= self.maxHeight: #checks movement range if self.inServiceMode == False: #checks mode if self.currentFloor != move: while self.currentFloor != move: if self.currentFloor < move: self.currentFloor += 1 print(self.currentFloor) elif self.currentFloor > move: self.currentFloor -= 1 print(self.currentFloor) print("The elevator moved to floor " + str(self.currentFloor) + ".") elif self.currentFloor == move: self.currentFloor = move else: print("SERVICE MODE: Elevator in service mode on floor" + self.currentFloor + ".") else: print("Floor out of range.") #running elevator print("Elevator:") print() elevator = elevator() print(elevator) elevator.goToFloor(7) print(elevator) elevator.goToFloor(7) elevator.goToFloor(-4) elevator.inServiceMode = True print(elevator) elevator.goToFloor(6) elevator.goToFloor(21) elevator.inServiceMode = False elevator.goToFloor(20) print(elevator) print() #running smartElevator print("Smart Elevator:") print() smartElevator = smartElevator() print(smartElevator) smartElevator.goToFloor(7) print(smartElevator) smartElevator.goToFloor(3) smartElevator.goToFloor(3)
brentmm/elevator
main.py
main.py
py
2,525
python
en
code
0
github-code
6
12526917301
#! /usr/bin/env/python 3.1 # # handle the transformation of the scanner results files. # use MOT as transformattor # author: Andreas Wagner # from AnalyzeToolConfig import AnalyzeToolConfig import os.path import py_common class TransformTool(object): def __init__(self, config): self.config = config def transformResultForScanner(self, scanner, tmpDataDir): outputFolder = os.path.dirname(scanner.outputFile) execCMD = "java -jar "+self.config.motJar+" -input:"+outputFolder+" -meta:"+self.config.motMeta+"\\"+scanner.motMetaFile+" -output:"+tmpDataDir+scanner.name+".csv" py_common.run_commands([execCMD], True) def transformResults(self): cfg = self.config ccppScannerList = cfg.getCCppScannerList() javaScannerList = cfg.getJavaScannerList() if(len(ccppScannerList)>0): for scanner in ccppScannerList: self.transformResultForScanner(scanner, cfg.tmpCppDataPath) if(len(javaScannerList) >0): for scanner in javaScannerList: self.transformResultForScanner(scanner, cfg.tmpJavaDataPath) if __name__ == '__main__': cfg = AnalyzeToolConfig('config.cfg') tool = TransformTool(cfg) tool.transformResults()
devandi/AnalyzeTool
TransformTool.py
TransformTool.py
py
1,322
python
en
code
4
github-code
6
25229791277
import pandas as pd from sklearn.metrics.pairwise import linear_kernel from scipy.io import mmwrite, mmread import pickle from gensim.models import Word2Vec # 데이터 가져오기 df_reviews = pd.read_csv('./naver_crawling_data/naver_cleaned_reviews.csv') Tfidf_matrix = mmread('./naver_models/Tfidf_book_review.mtx').tocsr() with open('./naver_models/tfidf.pickle', 'rb') as f: Tfidf = pickle.load(f) def getRecommendation(cosine_sim): simScore = list(enumerate(cosine_sim[-1])) simScore = sorted(simScore, key=lambda x:x[1], reverse=True) simScore = simScore[1:11] bookidx = [i[0] for i in simScore] recBookList = df_reviews.iloc[bookidx] return recBookList embedding_model = Word2Vec.load('./naver_models/Word2VecModel_naver.model') key_word = '감동' sentence = [key_word] * 11 sim_word = embedding_model.wv.most_similar(key_word, topn=10) words = [] for word, _ in sim_word: # 앞에는 단어, 뒤에는 유사도 words.append(word) print(words) for i, word in enumerate(words): sentence += [word] * (10-i) sentence = ' '.join(sentence) # print(sentence) sentence_vec = Tfidf.transform([sentence]) cosine_sim = linear_kernel(sentence_vec, Tfidf_matrix) recommendation = getRecommendation(cosine_sim) print(recommendation['titles'])
sealamen/project_03_book_curator
07_book_recommendation.py
07_book_recommendation.py
py
1,305
python
en
code
0
github-code
6
75096001788
def filterTags(attrs): tags = {} if attrs["SURFACE"] == "Gravel": tags["surface"] = "gravel" elif attrs["SURFACE"] == "Unpaved": tags["surface"] = "unpaved" elif attrs["SURFACE"] == "Paved": tags["surface"] = "paved" if attrs["TRAIL_NAME"]: tags["name"] = attrs["TRAIL_NAME"] if attrs["CLASS_TYPE"] == "Path": tags["highway"] = "path" elif attrs["CLASS_TYPE"] == "Cycle Track": tags["highway"] = "cycleway" elif attrs["SURFACE"] == "Service Road": tags["highway"] = "service" tags["bicycle"] = "yes" if attrs["CLASS_TYPE"] == "Lane": tags["cycleway"] = "lane" elif attrs["CLASS_TYPE"] == "Bike Route (Shared Roadway)": tags["cycleway"] = "shared_lane" elif attrs["CLASS_TYPE"] == "Bike Boulevard": tags["bicycle"] = "designated" return tags
impiaaa/SV-OSM
translations/bike.py
bike.py
py
898
python
en
code
1
github-code
6
37560479588
a1 = 0x31 ## (1) a2 = 0x31 ## (1) a3 = 0x38 ## (8) a4 = 0x30 ## (0) b1 = 0x2B ## (-) (+)0x2B (-)0x2D b2 = 0x30 ## (0) b3 = 0x30 ## (0) b4 = 0x35 ## (5) #print(chr(a)) def solarAsciitoInt(s1,s2,s3,s4): solarStr = chr(s1) + chr(s2)+chr(s3) + chr(s4) soloarInt = int(solarStr) #print(soloarInt) return soloarInt solarRadition = solarAsciitoInt(a1,a2,a3,a4) print(solarRadition) print(type(solarRadition)) def temperAsciitoFloat(t1, t2, t3, t4): temperStr = chr(t1) + chr(t2)+chr(t3) +"."+ chr(t4) temperFloat = float(temperStr) #print(soloarInt) return temperFloat def humidityAsciitoFloat(h1, h2, h3): humidityStr = chr(h1) + chr(h2)+"."+ chr(h3) humidityFloat = float(humidityStr) #print(soloarInt) return humidityFloat flt = temperAsciitoFloat(b1,b2,b3,b4) print(flt) print(type(flt)) flt2 = humidityAsciitoFloat(b2,b3,b4) print(flt2) print(type(flt2))
CoKap-ASL-DEV/ModBusRTUoverTCP
test2.py
test2.py
py
928
python
en
code
0
github-code
6
25005216625
import io import typing import random import discord import operator import datetime from config import config from discord.ext import commands from util.paginator import Pages from util.converter import CaseInsensitiveRole, PoliticalParty, CaseInsensitiveMember class Misc(commands.Cog, name="Miscellaneous"): """Miscellaneous commands. Some useful, some not.""" def __init__(self, bot): self.bot = bot self.cached_sorted_veterans_on_democraciv = [] @commands.Cog.listener(name="on_member_join") async def original_join_position_listener(self, member): if member.guild.id != self.bot.democraciv_guild_object.id: return joined_on = member.joined_at or datetime.datetime.utcnow() await self.bot.db.execute("INSERT INTO original_join_dates (member, join_date) " "VALUES ($1, $2) ON CONFLICT DO NOTHING", member.id, joined_on) async def get_member_join_date(self, member: discord.Member) -> datetime.datetime: if member.guild.id == self.bot.democraciv_guild_object.id: original_date = await self.bot.db.fetchval("SELECT join_date FROM original_join_dates WHERE member = $1", member.id) if original_date is not None: return original_date return member.joined_at async def get_member_join_position(self, user, members: list): if user.guild.id == self.bot.democraciv_guild_object.id: original_position = await self.bot.db.fetchval("SELECT join_position FROM original_join_dates " "WHERE member = $1", user.id) all_members = await self.bot.db.fetchval("SELECT max(join_position) FROM original_join_dates") if original_position: return original_position, all_members joins = tuple(sorted(members, key=operator.attrgetter("joined_at"))) if None in joins: return None, None for key, elem in enumerate(joins): if elem == user: return key + 1, len(members) return None, None @commands.command(name='whois') @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) @commands.guild_only() async def whois(self, ctx, *, member: typing.Union[discord.Member, CaseInsensitiveMember, discord.Role, CaseInsensitiveRole, PoliticalParty] = None): """Get detailed information about a member of this server **Example:** `-whois` `-whois Jonas - u/Jovanos` `-whois @DerJonas` `-whois DerJonas` `-whois deRjoNAS` `-whois DerJonas#8109` """ def _get_roles(roles): string = '' for role in roles[::-1]: if not role.is_default(): string += f'{role.mention}, ' if string == '': return '-' else: return string[:-2] # Thanks to: # https://github.com/Der-Eddy/discord_bot # https://github.com/Rapptz/RoboDanny/ if isinstance(member, discord.Role): return await self.role_info(ctx, member) elif isinstance(member, PoliticalParty): return await self.role_info(ctx, member.role) member = member or ctx.author join_pos, max_members = await self.get_member_join_position(member, ctx.guild.members) embed = self.bot.embeds.embed_builder(title="User Information", description="") embed.add_field(name="User", value=f"{member} {member.mention}", inline=False) embed.add_field(name="ID", value=member.id, inline=False) embed.add_field(name='Discord Registration', value=f'{member.created_at.strftime("%B %d, %Y")}', inline=True) embed.add_field(name='Joined', value=f'{(await self.get_member_join_date(member)).strftime("%B %d, %Y")}', inline=True) embed.add_field(name='Join Position', value=f"{join_pos}/{max_members}", inline=True) embed.add_field(name=f'Roles ({len(member.roles) - 1})', value=_get_roles(member.roles), inline=False) embed.set_thumbnail(url=member.avatar_url_as(static_format="png")) await ctx.send(embed=embed) @whois.error async def whois_error(self, ctx, error): if isinstance(error, commands.BadUnionArgument): return @commands.command(name='avatar') @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) @commands.guild_only() async def avatar(self, ctx, *, member: typing.Union[discord.Member, CaseInsensitiveMember] = None): """Get a members's avatar in detail **Example:** `-avatar` `-avatar @DerJonas` `-avatar DerJonas` `-avatar DerJonas#8109` """ member = member or ctx.author avatar_png: discord.Asset = member.avatar_url_as(static_format="png", size=4096) embed = self.bot.embeds.embed_builder(title=f"{member.display_name}'s Avatar", description=f"[Link]({avatar_png})", has_footer=False) embed.set_image(url=str(avatar_png)) await ctx.send(embed=embed) @avatar.error async def avatar_error(self, ctx, error): if isinstance(error, commands.BadUnionArgument): return @staticmethod def get_spotify_connection(member: discord.Member): if len(member.activities) > 0: for act in member.activities: if act.type == discord.ActivityType.listening: return act return None @commands.command(name='spotify') @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) @commands.guild_only() async def spotify(self, ctx, *, member: typing.Union[discord.Member, CaseInsensitiveMember] = None): """See what someone is listening to on Spotify **Example:** `-spotify` `-spotify @DerJonas` `-spotify DerJonas` `-spotify DerJonas#8109` """ member = member or ctx.author member_spotify = self.get_spotify_connection(member) if member_spotify is None: return await ctx.send(":x: That person is either not listening to something on Spotify right now, " "or I just can't detect it.") pretty_artists = ', '.join(member_spotify.artists) embed = self.bot.embeds.embed_builder(title=f"{config.SPOTIFY_LOGO} {member.name} on Spotify", description="", has_footer=False, colour=0x2F3136, footer=f"Use `{ctx.prefix}lyrics` to get lyrics" f" for a song!") embed.add_field(name="Song", value=f"[{member_spotify.title}](https://open.spotify.com/" f"track/{member_spotify.track_id})", inline=False) embed.add_field(name="Artist(s)", value=pretty_artists, inline=True) embed.add_field(name="Album", value=member_spotify.album, inline=True) embed.set_thumbnail(url=member_spotify.album_cover_url) await ctx.send(embed=embed) @spotify.error async def spotify_error(self, ctx, error): if isinstance(error, commands.BadUnionArgument): return @commands.command(name='veterans') @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) @commands.guild_only() async def veterans(self, ctx): """List the first 15 members who joined this server""" sorted_first_15_members = [] # As veterans rarely change, use a cached version of sorted list if exists if ctx.guild.id == self.bot.democraciv_guild_object.id: if len(self.cached_sorted_veterans_on_democraciv) >= 2: sorted_first_15_members = self.cached_sorted_veterans_on_democraciv else: vets = await self.bot.db.fetch("SELECT member, join_position FROM original_join_dates WHERE " "join_position <= 15 ORDER BY join_position") for record in vets: member = self.bot.get_user(record['member']) sorted_first_15_members.append((member, record['join_position'])) self.cached_sorted_veterans_on_democraciv = sorted_first_15_members # If cache is empty OR ctx not on democraciv guild, calculate & sort again else: async with ctx.typing(): guild_members_without_bots = [member for member in ctx.guild.members if not member.bot] first_15_members = [] # Veterans can only be human, exclude bot accounts for member in guild_members_without_bots: join_position, max_members = await self.get_member_join_position(member, guild_members_without_bots) if join_position <= 15: first_15_members.append((member, join_position)) # Sort by join position sorted_first_15_members = sorted(first_15_members, key=lambda x: x[1]) # Save to cache if democraciv guild. This should only be done once in the bot's life cycle. if ctx.guild.id == self.bot.democraciv_guild_object.id: self.cached_sorted_veterans_on_democraciv = sorted_first_15_members # Send veterans message = "These are the first 15 people who joined this server.\nBot accounts are not counted.\n\n" for veteran in sorted_first_15_members: message += f"{veteran[1]}. {str(veteran[0])}\n" embed = self.bot.embeds.embed_builder(title=f"Veterans of {ctx.guild.name}", description=message) await ctx.send(embed=embed) @commands.command() @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) async def lyrics(self, ctx, *, query: str = None): """Find lyrics for a song **Usage:** `-lyrics` to get the lyrics to the song you're currently listening to on Spotify `-lyrics <query>` to search for lyrics that match your query """ if query is None: now_playing = self.get_spotify_connection(ctx.author) if now_playing is None: return await ctx.send(":x: You either have to give me something to search for or listen to a song" " on Spotify!") query = f"{now_playing.title} {' '.join(now_playing.artists)}" if len(query) < 3: return await ctx.send(":x: The query has to be more than 3 characters!") async with ctx.typing(): async with self.bot.session.get(f"https://some-random-api.ml/lyrics?title={query}") as response: if response.status == 200: lyrics = await response.json() else: return await ctx.send(f":x: Couldn't find anything that matches `{query}`.") try: lyrics['lyrics'] = lyrics['lyrics'].replace("[", "**[").replace("]", "]**") if len(lyrics['lyrics']) <= 2048: embed = self.bot.embeds.embed_builder(title=f"{lyrics['title']} by {lyrics['author']}", description=lyrics['lyrics'], colour=0x2F3136) embed.url = lyrics['links']['genius'] embed.set_thumbnail(url=lyrics['thumbnail']['genius']) return await ctx.send(embed=embed) pages = Pages(ctx=ctx, entries=lyrics['lyrics'].splitlines(), show_entry_count=False, title=f"{lyrics['title']} by {lyrics['author']}", show_index=False, title_url=lyrics['links']['genius'], thumbnail=lyrics['thumbnail']['genius'], per_page=20, colour=0x2F3136, show_amount_of_pages=True) except KeyError: return await ctx.send(f":x: Couldn't find anything that matches `{query}`.") await pages.paginate() @commands.command(name="tinyurl", aliases=["tiny"]) @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) async def tinyurl(self, ctx, url: str): """Shorten a link with tinyurl""" if len(url) <= 3: await ctx.send(":x: That doesn't look like a valid URL.") return tiny_url = await self.bot.laws.post_to_tinyurl(url) if tiny_url is None: return await ctx.send(":x: tinyurl.com returned an error, try again in a few minutes.") await ctx.send(f"<{tiny_url}>") @commands.command(name='whohas', aliases=['roleinfo']) @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) @commands.guild_only() async def whohas(self, ctx, *, role: typing.Union[discord.Role, CaseInsensitiveRole, PoliticalParty]): """Detailed information about a role""" if isinstance(role, PoliticalParty): role = role.role await self.role_info(ctx, role) async def role_info(self, ctx, role: discord.Role): if role is None: return await ctx.send(":x: `role` is neither a role on this server, nor on the Democraciv server.") if role.guild.id != ctx.guild.id: description = ":warning: This role is from the Democraciv server, not from this one!" role_name = role.name else: description = "" role_name = f"{role.name} {role.mention}" embed = self.bot.embeds.embed_builder(title="Role Information", description=description, colour=role.colour, has_footer=False) embed.add_field(name="Role", value=role_name, inline=False) embed.add_field(name="ID", value=role.id, inline=False) embed.add_field(name="Created on", value=role.created_at.strftime("%B %d, %Y"), inline=True) embed.add_field(name="Colour", value=str(role.colour), inline=True) embed.add_field(name=f"Members ({len(role.members)})", value=', '.join([member.mention for member in role.members]) or '-', inline=False) await ctx.send(embed=embed) @commands.command(name='random') @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) async def random(self, ctx, *arg): """Get a random number or make the bot choose between something **Example:** `-random` will choose a random number between 1 and 100 `-random 6` will choose a random number between 1 and 6 `-random 50 200` will choose a random number between 50 and 200 `-random coin` will choose Heads or Tails `-random choice "England" "Rome"` will choose between England and Rome """ """ MIT License Copyright (c) 2016 - 2018 Eduard Nikoleisen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ if not arg: start = 1 end = 100 elif arg[0].lower() in ('flip', 'coin', 'coinflip'): coin = ['Heads', 'Tails'] return await ctx.send(f':arrows_counterclockwise: **{random.choice(coin)}**') elif arg[0].lower() == 'choice': choices = list(arg) choices.pop(0) return await ctx.send(f':tada: The winner is: `{random.choice(choices)}`') elif len(arg) == 1: start = 1 try: end = int(arg[0]) except ValueError: raise commands.BadArgument() elif len(arg) == 2: try: start = int(arg[0]) end = int(arg[1]) except ValueError: raise commands.BadArgument() else: start = 1 end = 100 await ctx.send( f'**:arrows_counterclockwise:** Random number ({start} - {end}): **{random.randint(start, end)}**') @commands.command(name='vibecheck', hidden=True) @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) @commands.guild_only() async def vibecheck(self, ctx, *, member: typing.Union[discord.Member, CaseInsensitiveMember] = None): """vibecheck""" member = member or ctx.author not_vibing = [ 'https://i.kym-cdn.com/entries/icons/mobile/000/031/163/Screen_Shot_2019-09-16_at_10.22.26_AM.jpg', 'https://t6.rbxcdn.com/e92c5706e16411bdb1aeaa23e268c4aa', 'https://s3.amazonaws.com/media.thecrimson.com/photos/2019/11/18/194724_1341037.png', 'https://i.kym-cdn.com/photos/images/newsfeed/001/574/493/3ab.jpg', 'https://i.imgflip.com/3ebtvt.jpg', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT814jrNuqJsaVVHGqWw_0snlcysLN5fLpocEYrx6hzkgXYx7RV5w&s', 'https://i.redd.it/qajwen1dpcn31.png', 'https://pl.scdn.co/images/pl/default/8b3875b1f9c2a05ebc96df0fb4404265246bc4bb', 'https://img.buzzfeed.com/buzzfeed-static/static/2019-10/7/15/asset/c5dd65974640/sub-buzz-521-1570462442-1.png?downsize=700:*&output-format=auto&output-quality=auto', 'https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/12132fe4-1709-4287-9dcc-4ee9fc252a01/ddk55pz-bf72cab3-2b9e-474e-94a8-00e5f53d2baf.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcLzEyMTMyZmU0LTE3MDktNDI4Ny05ZGNjLTRlZTlmYzI1MmEwMVwvZGRrNTVwei1iZjcyY2FiMy0yYjllLTQ3NGUtOTRhOC0wMGU1ZjUzZDJiYWYuanBnIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.Sb6Axu0O6iZ3YmZJHg5wRe-r41iLnWVqa_ddWrtbQlo', 'https://pbs.twimg.com/media/EHgYHjOX4AAuv6s.jpg', 'https://pbs.twimg.com/media/EGTsxzaUwAAuBLG?format=jpg&name=900x900', 'https://66.media.tumblr.com/c2fc65d9f8614dbd9bb7378983e0598e/tumblr_pxw332rEmZ1yom1s3o1_1280.png' ] vibing = ['https://i.redd.it/ax6jb6lhdah31.jpg', 'https://i.redd.it/3a6nr5b3u4x31.png', 'https://i.kym-cdn.com/photos/images/original/001/599/028/bf3.jpg', 'https://i.redd.it/p4e6a65i3bw31.jpg', 'https://media.makeameme.org/created/congratulations-you-have-61e05e0d4b.jpg'] passed = bool(random.getrandbits(1)) if passed: image = random.choice(vibing) pretty = "passed" else: image = random.choice(not_vibing) pretty = "not passed" embed = self.bot.embeds.embed_builder(title=":flushed: Vibe Check", description=f"{member.mention} " f"has **{pretty}** " f"the vibe check!") embed.set_image(url=image) await ctx.send(embed=embed) @vibecheck.error async def vibecheck_error(self, ctx, error): if isinstance(error, commands.BadArgument): return @commands.command(hidden=True, aliases=['doggo', 'doggos']) @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) async def dog(self, ctx): """Just for Tay: A random image of a dog""" """The MIT License (MIT) Copyright (c) 2015 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" async with self.bot.session.get('https://random.dog/woof') as resp: if resp.status != 200: return await ctx.send(':x: No dog found :(') filename = await resp.text() url = f'https://random.dog/{filename}' filesize = ctx.guild.filesize_limit if ctx.guild else 8388608 if filename.endswith(('.mp4', '.webm')): async with ctx.typing(): async with self.bot.session.get(url) as other: if other.status != 200: return await ctx.send(':x: Could not download dog video :(') if int(other.headers['Content-Length']) >= filesize: return await ctx.send(f':x: Video was too big to upload, watch it here instead: {url}') fp = io.BytesIO(await other.read()) await ctx.send(file=discord.File(fp, filename=filename)) else: embed = self.bot.embeds.embed_builder(title="Random Dog", description="", has_footer=False) embed.set_image(url=url) embed.set_footer(text="Just for Taylor.") await ctx.send(embed=embed) @commands.command(name="cat", hidden=True) @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) async def cat(self, ctx): """A random cat""" """The MIT License (MIT) Copyright (c) 2015 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" async with self.bot.session.get('https://api.thecatapi.com/v1/images/search') as response: if response.status != 200: return await ctx.send(':x: No cat found :(') js = await resp.json() embed = self.bot.embeds.embed_builder(title="Random Cat", description="", has_footer=False) embed.set_image(url=js[0]['url']) await ctx.send(embed=embed) @commands.command(name='invite') @commands.cooldown(1, config.BOT_COMMAND_COOLDOWN, commands.BucketType.user) async def invite(self, ctx): """Get an active invite link to this server""" invite = await ctx.channel.create_invite(max_age=0, unique=False) await ctx.send(invite.url) def setup(bot): bot.add_cog(Misc(bot))
DENE-dev/dene-dev
RQ1-data/exp2/114-jonasbohmann@democraciv-discord-bot-ae9b0558588ef6313477cfd58732ceec738dd706/module/misc.py
misc.py
py
25,789
python
en
code
0
github-code
6
73891294909
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # feature: 30天内加速度;创业板,中小板,白马 import re import json import requests import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm import statsmodels.formula.api as smf import statsmodels.graphics.api as smg import time headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': '_ga=GA1.2.390769919.1552150985; _gid=GA1.2.102441312.1552150985; qgqp_b_id=f69f83447752be0b46753cdc52717be8; st_pvi=53068450450300; st_sp=2019-03-10%2002%3A14%3A31; st_inirUrl=http%3A%2F%2Fm.data.eastmoney.com%2Fhsgt%2Findex.html; st_si=93379072515284; _gat=1', 'DNT': '1', 'Host': 'dcfm.eastmoney.com', 'If-Modified-Since': 'Sat, 09 Mar 2019 20:06:00 GMT', 'If-None-Match': "8788d883b3d6d41:0", 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'} def colours(font): # if type(font) == str: if float(re.compile(r'-?\d+\.*\d*').findall(str(font))[0]) >= 0: return "\033[0;31m{}\033[0m".format(font) else: return "\033[0;32m{}\033[0m".format(font) def mainland_hk_pipe_last(): r = requests.get( r'https://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=P.(x),(x),(x)|0000011|3990012|3990012,0000011,HSI5,BK07071,MK01461,MK01441,BK08041&sty=SHSTD|SZSTD|FCSHSTR&st=z&sr=&p=&ps=&cb=&js=result51858295({result:[(x)]})&token=1942f5da9b46b069953c873404aad4b5&callback=result51858295&_='+str(round(time.time() * 1000)), headers=headers) html = str(r.text) html_splited = html[html.find('{'):len(html)-1].split('","') # print(html_splited) # print(" ") # print(html_splited[0]) # print(html_splited[0][html_splited[0].find('["')+2:-1 ]) temp = html_splited[0][html_splited[0].find('["')+2:-1].split(',') print("hk-hu pipe | hk in: " + colours(temp[0]) + ", shanghai in: " + colours(temp[6])) # print(html_splited[1]) temp = html_splited[1].split(',') print("hk-sz pipe | hk in: " + colours(temp[0]) + ", shenzhen in: " + colours(temp[6])) def hk_to_mainland_1d(): url = r'https://ff.eastmoney.com/EM_CapitalFlowInterface/api/js?id=north&type=EFR&rtntype=2&acces_token=1942f5da9b46b069953c873404aad4b5&js=result10043862({result:[(x)]})&callback=result10043862&_='+str(round(time.time() * 1000)) r = requests.get(url, headers=headers) # print(r.text) html = str(r.text) html_splited = html[html.find('{'):len(html)-1].split('","') # print(html_splited) shanghaiIn = [] shenzhenIn = [] for key, tradeVolPerMinute in enumerate(html_splited): if key == 0: temp = tradeVolPerMinute[tradeVolPerMinute.find( '"')+1:-1].split(',') # print(temp) if temp[1].strip() != '': shanghaiIn.append(temp[1]) shenzhenIn.append(temp[2]) elif key == len(html_splited)-1: temp = tradeVolPerMinute[0:tradeVolPerMinute.find( '"')-1].split(',') # print(temp) if temp[1].strip() != '': shanghaiIn.append(temp[1]) shenzhenIn.append(temp[2]) else: # print(tradeVolPerMinute.split(',')) if tradeVolPerMinute.split(',')[1].strip() != '': shanghaiIn.append(tradeVolPerMinute.split(',')[1]) shenzhenIn.append(tradeVolPerMinute.split(',')[2]) # print(shanghaiIn) # print(shenzhenIn) # x = np.array([2, 3, 4, 5, 6, 7, 8, 9]) x = np.arange(0, len(shanghaiIn)) # xx = pd.DataFrame({"k": x}) # yy = pd.Series([20, 33, 44, 55, 66, 77, 88, 105]) # 口算都知道斜率是11,最终方程是y=11x yy = np.asarray(shanghaiIn, dtype="float64") sz_y = np.asarray(shenzhenIn, dtype="float64") X = sm.add_constant(x) model = sm.OLS(yy, X) sz_model = sm.OLS(sz_y, X) sh_results = model.fit() sz_results = sz_model.fit() print("shanghai <- hk [1d] | coef_const: " + str(round(sh_results.params[0], 4)) + ", x1: "+colours(round(sh_results.params[1], 4))) print("shenzhen <- hk [1d] | coef_const: " + str(round(sz_results.params[0], 4)) + ", x1: "+colours(round(sz_results.params[1], 4))) # print("\033[1;37;40m\tHello World\033[0m") # print(sh_results.summary()) # y_fitted = sh_results.fittedvalues # sz_y_fitted = sz_results.fittedvalues # plt.figure(1) # fig, ax = plt.subplots(figsize=(8, 6)) # ax.plot(x, yy, 'o', label='data') # ax.plot(x, y_fitted, 'r--.', label='OLS') # ax.legend(loc='best') # plt.figure(2) # fig, ax = plt.subplots(figsize=(8, 6)) # ax.plot(x, sz_y, 'o', label='data') # ax.plot(x, sz_y_fitted, 'r--.', label='OLS') # ax.legend(loc='best') # plt.show() def hk_to_mainland_several_d(): hk_to_shenzhen_10d('shanghai') hk_to_shenzhen_10d('shenzhen') hk_to_shenzhen_10d('shanghai', 30) hk_to_shenzhen_10d('shenzhen', 30) def hk_to_shenzhen_10d(stock_exchange, days=10): if stock_exchange == 'shenzhen': url = r'https://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?js=({IsSuccess:%271%27,result:(x)})&ps='+str(days) + \ '&p=1&sr=-1&st=DetailDate&callback=result31360562&type=HSGTHIS&token=70f12f2f4f091e459a279469fe49eca5&filter=(MarketType%3D3)&rt=51765885&page=1&pagesize=10&_='+str(round(time.time() * 1000)) else: url = r'https://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?js=({IsSuccess:%271%27,result:(x)})&ps='+str(days) + \ '&p=1&sr=-1&st=DetailDate&callback=result18465975&type=HSGTHIS&token=70f12f2f4f091e459a279469fe49eca5&filter=(MarketType%3D1)&rt=51772229&page=1&pagesize=10&_='+str(round(time.time() * 1000)) r = requests.get(url, headers=headers) html = str(r.text) # print(html) html_splited = html[html.find('result:[{')+9:len(html)-1].split('},{') # print(html_splited) hk_mainland_7d = {} list_drzjlr = [] # 当日资金流入 for key, tradePerDay in enumerate(html_splited): for detail in tradePerDay.split(','): # print(detail.split(':', 1)) if detail.split(':', 1)[0].replace('"', '') == "DetailDate": date = detail.split(':', 1)[1].replace('"', '').split('T')[0] hk_mainland_7d[date] = {} elif detail.split(':', 1)[0].replace('"', '') == "DRZJLR": hk_mainland_7d[date]['DRZJLR'] = detail.split(':', 1)[ 1].replace('"', '') list_drzjlr.append(detail.split(':', 1)[1].replace('"', '')) # print(hk_mainland_7d) # print(list_drzjlr) # print(list_drzjlr[::-1]) foo_x = np.arange(0, len(list_drzjlr)) foo_y = np.asarray(list_drzjlr[::-1], dtype="float64") d10_X = sm.add_constant(foo_x) foo_model = sm.OLS(foo_y, d10_X) foo_results = foo_model.fit() # print(foo_results.params) print(stock_exchange+" <- hk ["+ str(days) +"d] | coef_const: " + str(round(foo_results.params[0]/100, 4)) + ", x1: "+colours(round(foo_results.params[1]/100, 4))) d10_y_fitted = foo_results.fittedvalues plt.figure(1) fig, ax = plt.subplots(figsize=(8, 6)) x = np.arange(0, len(foo_y)) ax.plot(x, foo_y, 'o', label='data') ax.plot(x, d10_y_fitted, 'r--.', label='OLS') ax.legend(loc='best') plt.show() if __name__ == '__main__': mainland_hk_pipe_last() hk_to_mainland_1d() hk_to_mainland_several_d()
SoyM/fin
test.py
test.py
py
7,933
python
en
code
0
github-code
6
39963956930
"""======================================================================== File Name : python_project.py File Description : This file illustrate usage of oops concept of python, iterates as many times as the user input search the given keyword in input file and create file if match found File created on : 26 February, 2021 Author : Arpita A Kulkarni PS Number : 99003757 contact info : [email protected] ============================================================================""" import re import os """-----------------------------SUPER CLASS---------------------------""" class Firstclass: def __init__(self): # constructor class to read no of keywords # it also read input file # flag is to check for exception self.flag = True string_name = "enter no of keywords to search:\n" self.no_of_keyword = input(string_name) while self.flag: if self.no_of_keyword.isdigit(): self.flag = False else: self.no_of_keyword = input("Error.! accept only +ve integer\n") # function to read file from input txt def function_read(self): # opens input file in read mode and reads the file self.file_name = open("input.txt", 'r') self.file_read_input = self.file_name.read() # declare count to count total keyword occurred class Secondclass(Firstclass): # second class is inherited from firstclass def search_write_function(self): Firstclass.function_read(self) # loop executes no of times keyword want to search for ii in range(int(self.no_of_keyword)): # user input takes keyword user_input = input("Enter the Keyword:\n") # split the input file into tuple input_split = self.file_read_input.split() # remove all character in tuple splited = re.split(r'\W+', str(input_split)) # output file format as per user input filename = "{}.txt".format(user_input) file_output = open(filename, 'w') count = 0 for i in range(len(splited)): # match the given keyword in the input file if re.fullmatch(user_input, splited[i], re.M | re.I): if user_input.isalnum() or user_input.isdigit() or \ user_input.isalpha(): string = "The keyword is {0} {1} {2}\n" txt1 = string.format(splited[i - 1], splited[i], splited[i + 1]) # if match found write file_output.write(txt1) count += 1 if count != 0: file_output.write("Total count:" + str(count)) file_output.close() if count == 0: print("Entered Keyword not found in the file\n") if os.path.isfile(filename): os.remove(filename) # ask user input to iterate # oject of second class created s_object = Secondclass() # call search write function to do the task s_object.search_write_function() s_object.file_name.close()
99003757/Python_Mini_Project
python_project.py
python_project.py
py
3,417
python
en
code
0
github-code
6
22497784287
from flask_app.config.mysqlconnection import connectToMySQL from flask import flash class Recipe: db = "login_and_registration" # db should = your schema def __init__(self, data): self.id = data['id'] self.names = data['names'] self.descriptions = data['descriptions'] self.instructions = data['instructions'] self.under_thirty = data['under_thirty'] self.created_at = data['created_at'] self.updated_at = data['updated_at'] self.users_id = data['users_id'] @classmethod def create(cls, data): query = "INSERT INTO recipes (names, descriptions, instructions, under_thirty, users_id) VALUES (%(names)s, %(descriptions)s, %(instructions)s, %(under_thirty)s, %(users_id)s)" results = connectToMySQL( cls.db).query_db(query, data) return results @classmethod def get_all(cls, data): query = "SELECT * FROM recipes WHERE users_id = %(id)s" results = connectToMySQL(cls.db).query_db(query, data) list = [] for row in results: list.append(cls(row)) return list @classmethod def get_one(cls, data): query = "SELECT * FROM recipes WHERE recipes.id = %(id)s;" results = connectToMySQL( cls.db).query_db(query, data) this_recipe = cls(results[0]) return this_recipe @classmethod def update(cls, data): query = "UPDATE recipes SET names= %(names)s, descriptions= %(descriptions)s, instructions= %(instructions)s, instructions= %(instructions)s, under_thirty= %(under_thirty)s, date_made= %(date_made)s WHERE id = %(id)s" results = connectToMySQL(cls.db).query_db(query, data) return results @classmethod def delete(cls, data): query = "DELETE FROM recipes WHERE id=%(id)s" results = connectToMySQL(cls.db).query_db(query, data) return results @classmethod def update(cls, data): query = "UPDATE recipes SET (names, descriptions, instructions, under_thirty) VALUES (%(names)s, %(descriptions)s, %(instructions)s, %(under_thirty)s)" results = connectToMySQL(cls.db).query_db(query, data) return results @ staticmethod def validate_recipe(recipe): is_valid = True if len(recipe['names']) < 3: flash("Name has to be 3 characters long!", "recipe") is_valid = False if len(recipe['descriptions']) < 3: flash("Description has to be 3 characters long!", "recipe") is_valid = False if len(recipe['instructions']) < 3: flash("Instructions has to be 3 characters long!", "recipe") is_valid = False if len(recipe['date_made']) == "": flash("Must enter date", "recipe") is_valid = False return is_valid
tsu112/login_and_registration
flask_app/models/recipe.py
recipe.py
py
2,869
python
en
code
0
github-code
6
19237958892
import os from war3structs.storage import MPQ from .common import PipeTransformer from ..liquid import Liquid class MapExtractorPipe(PipeTransformer): def gate(self, build, liquid): map_liquids = [] map_path = os.path.join(build['etcdir'], 'temp%s' % liquid.name) # Begin by writing the liquid's contents to disk liquid.write_to(map_path) # Create folder to extract map files to map_dir = os.path.join(build['etcdir'], 'temp%s' % liquid.stem) os.makedirs(map_dir) # Open the result as an MPQ and extract files map_mpq = MPQ(map_path) for found_file in map_mpq.find('*'): try: out_path = os.path.join(map_dir, found_file.filename) found_file.extract(out_path) map_liquids.append(Liquid(out_path)) except Exception: pass map_mpq.close() return map_liquids
sides/war3archiver
war3archiver/transformers/maps.py
maps.py
py
856
python
en
code
0
github-code
6
29122533365
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 1 12:24:24 2018 @author: omer mirza """ import math as m def f(x): return m.cos(x) - x def f1(x): return x**3 -2*x**2 - 5 def f2(x): return x**3 + 3*x**2 -1 def f3(x): return x - m.cos(x) def f4(x): return x -.8 -.2*m.sin(x) def weak(x): return (1/x) -2 ##This code solves for the equation using the secent method using the specified equations above def omer_sec(p0, p1, tol, maxit): for i in range(maxit): print(str(i) + ' | ' +str(f(p0)) + ' | ' + str (p0) + ' | ' +str(p1) ) if(p0)== 0: print('The solution is ' + str(p1)) return p1 p = p1 - (f(p1) * (p1-p0)) / (f(p1) - f(p0)) p0 = p1 p1 = p print('No solution was found') return p1 def omer_sec1(p0, p1, tol, maxit): for i in range(maxit): print(str(i) + ' | ' +str(f1(p0)) + ' | ' + str (p0) + ' | ' +str(p1) ) if(p0)== 0: print('The solution is ' + str(p1)) return p1 p = p1 - (f1(p1) * (p1-p0)) / (f1(p1) - f1(p0)) p0 = p1 p1 = p print('No solution was found') return p1 def omer_sec2(p0, p1, tol, maxit): for i in range(maxit): print(str(i) + ' | ' +str(f2(p0)) + ' | ' + str (p0) + ' | ' +str(p1) ) if(p0)== 0: print('The solution is ' + str(p1)) return p1 p = p1 - (f2(p1) * (p1-p0)) / (f2(p1) - f2(p0)) p0 = p1 p1 = p print('No solution was found') return p1 def omer_sec3(p0, p1, tol, maxit): for i in range(maxit): print(str(i) + ' | ' +str(f3(p0)) + ' | ' + str (p0) + ' | ' +str(p1) ) if(p0)== 0: print('The solution is ' + str(p1)) return p1 p = p1 - (f3(p1) * (p1-p0)) / (f3(p1) - f3(p0)) p0 = p1 p1 = p print('No solution was found') return p1 def omer_sec4(p0, p1, tol, maxit): for i in range(maxit): print(str(i) + ' | ' +str(f4(p0)) + ' | ' + str (p0) + ' | ' +str(p1) ) if(p0)== 0: print('The solution is ' + str(p1)) return p1 p = p1 - (f4(p1) * (p1-p0)) / (f4(p1) - f4(p0)) p0 = p1 p1 = p print('No solution was found') return p1 def omer_sec_weak(p0, p1, tol, maxit): for i in range(maxit): print(str(i) + ' | ' +str(weak(p0)) + ' | ' + str (p0) + ' | ' +str(p1) ) if(p0)== 0: print('The solution is ' + str(p1)) return p1 p = p1 - (weak(p1) * (p1-p0)) / (weak(p1) - weak(p0)) p0 = p1 p1 = p print('No solution was found') return p1 #The following code executes with the specified values in the book omer_sec(.5, m.pi/4, 0.000001, 6) print('***********') omer_sec1(1,4,0.000001, 6) print('***********') omer_sec2(-3,-2,0.000001, 6) print('***********') omer_sec3(0,m.pi/2,0.000001, 6) print('***********') omer_sec4(0,m.pi/2,0.000001, 6) print('***********') omer_sec_weak(1,1.2,0.000001, 100) print('***********') omer_sec_weak(1.4,1.45,0.000001, 100) # I have been running into the divide by zero error if I use too many itterations # something to note with secent method is that you do not have to find the derivative of the function at every step #not the case with newton's method
omermirza556/NumericalPrograms
secant_omirza14.py
secant_omirza14.py
py
3,344
python
en
code
0
github-code
6
73741438266
import tonos_ts4.ts4 as ts4 eq = ts4.eq # Initialize TS4 by specifying where the artifacts of the used contracts are located # verbose: toggle to print additional execution info # Инициализировать TS4, указав, где находятся артефакты используемых контрактов # verbose: переключить на печать дополнительной информации о выполнении ts4.init('contracts/', verbose = True) # The address of a non-existing contract # Адрес несуществующего контракта empty_account = ts4.Address('0:c4a31362f0dd98a8cc9282c2f19358c888dfce460d93adb395fa138d61ae5069') # Check balance of non-existing address # Проверить баланс несуществующего адреса assert eq(None, ts4.get_balance(empty_account)) default_balance = 100 * ts4.GRAM # Deploy the contract # Развернуть контракт tut08 = ts4.BaseContract('tutorial08', {}) # Сheck balance of the deployed contract. There are 100 grams by default # Проверить баланс развернутого контракта. По умолчанию 100 грамм tut08.ensure_balance(default_balance) # Another way to check the balance of contract # Еще один способ проверить баланс контракта assert eq(default_balance, tut08.balance)
baerelektro/TestSuite4
tutorials/tutorial08_balance.py
tutorial08_balance.py
py
1,403
python
ru
code
0
github-code
6
22007528984
# def calculator(n1, n2): # return n1 + n2 # # returnVAL = calculator(10, 20) # print(returnVAL) # calculator = lambda n1, n2: n1 + n2 # 함수 선언과 같음 # # returnVAL = calculator(10, 20) # print(f'returnVAL: {returnVAL}') triangle = lambda n1, n2: n1 * n2 / 2 square = lambda n1, n2: n1 * n2 circle = lambda r: r * r * 3.14 width = int(input('가로 길이 입력: ')) height = int(input('세로 길이 입력: ')) radius = int(input('반지름 길이 입력: ')) triangleVal = triangle(width, height) squareVal = square(width, height) circleVal = circle(radius) print(f'삼각형 넓이 : {triangleVal}') print(f'사각형 넓이 : {squareVal}') print(f'워 넓이 : {circleVal}')
bobdongeun/bobcoding
pythonProject/5_008/fun.py
fun.py
py
702
python
ko
code
0
github-code
6
5648119133
import sys from typing import List, Optional, Tuple import unittest def all_construct(target_string: str, strings: List[str], memo=None) -> List[List[str]]: # Memo. if memo is None: memo = {} if target_string in memo: return memo[target_string] # Base case. if len(target_string) == 0: return [[]] # Count the number of solutions. memo[target_string] = [] for string in strings: length_is_ok = len(string) <= len(target_string) match_at_start = target_string[:len(string)] == string if length_is_ok and match_at_start: remainder = target_string[len(string):] solution = all_construct(remainder, strings, memo) if len(solution) > 0: solution = [[string, *s] for s in solution] memo[target_string].extend(solution) return memo[target_string] class SolutionTest(unittest.TestCase): def test_solution(self): sys.setrecursionlimit(10000) fixtures = [ ( ("abcdef", ["ab", "abc", "cd", "def", "abcd"]), [["abc", "def"]], ), ( ("abcdef", ["ab", "abc", "cd", "def", "abcd", "ef", "c"]), [ ["ab", "cd", "ef"], ["abc", "def"], ["ab", "c", "def"], ["abcd", "ef"], ], ), ( ("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"]), [], ), ( ("", ["cat", "dog", "mouse"]), [[]], ), ( ("purple", ["purp", "p", "ur", "le", "purpl"]), [["purp", "le"], ["p", "ur", "p", "le"]], ), ] def contains(solution, target): for s in solution: try: self.assertEqual(s, target) return True except AssertionError: pass return False for inputs, output in fixtures: solution = all_construct(*inputs) self.assertEqual(len(output), len(solution)) for target in output: self.assertTrue(contains(solution, target), f"solution does not contain {target}\n\nSolution: {solution}")
bradtreloar/freeCodeCamp_DP_problems
problems/memoized/all_construct.py
all_construct.py
py
2,426
python
en
code
0
github-code
6
39242617287
from torch import nn import torch from models.cotnet import CotLayer class ChannelAttention(nn.Module): def __init__(self,in_channels,reduction=16): super(ChannelAttention,self).__init__() self.attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels,in_channels//reduction,1,bias=False), nn.Conv2d(in_channels//reduction,in_channels,1,bias=False), nn.Sigmoid() ) def forward(self,input): return input*self.attention(input) class BasciConv(nn.Module): def __init__(self,in_channels,out_channels,stride=2): super(BasciConv,self).__init__() self.conv1 = nn.Conv2d(in_channels,out_channels,3,stride,1) self.conv2 = nn.Conv2d(out_channels,out_channels,3,1,1) self.relu = nn.LeakyReLU(inplace=True) self.channel_att = ChannelAttention(out_channels) def forward(self,input): out = self.conv1(input) out = self.relu(out) out = self.conv2(out) out = self.channel_att(out) out = self.relu(out) return out class UpConv(nn.Module): def __init__(self,in_channels,out_channels): super(UpConv,self).__init__() self.pixelshuffle= nn.PixelShuffle(2) self.conv = nn.Conv2d(in_channels,out_channels,3,1,1) self.relu = nn.LeakyReLU(inplace=True) def forward(self,input): out = self.pixelshuffle(input) out = self.relu(out) out = self.conv(out) out = self.relu(out) return out class CotBlock(nn.Module): def __init__(self,ratio,channels): super(CotBlock,self).__init__() self.down1 = BasciConv(ratio,channels[0],stride=1) self.cot1 = nn.Sequential( nn.Conv2d(ratio,channels[0],3,1,1,bias=False), CotLayer(channels[0],3), nn.Conv2d(channels[0],channels[0],1,1,bias=False) ) self.down2 = BasciConv(channels[0]*2,channels[1]) self.cot2 = nn.Sequential( nn.Conv2d(channels[0]*2,channels[1],3,2,1,bias=False), CotLayer(channels[1],3), nn.Conv2d(channels[1],channels[1],1,1,bias=False) ) self.down3 = BasciConv(channels[1]*2,channels[2]) self.cot3 = nn.Sequential( nn.Conv2d(channels[1]*2,channels[2],3,2,1,bias=False), CotLayer(channels[2],3), nn.Conv2d(channels[2],channels[2],1,1,bias=False) ) self.conv1x1_list = nn.ModuleList( nn.Conv2d(channels[i]*2,channels[i],1,1) for i in range(len(channels)-1) ) self.conv3x3_list = nn.ModuleList( nn.Conv2d(channels[i]*2,channels[i],3,1,1) for i in range(len(channels)-1) ) self.up2 = UpConv(channels[2]*2//4,channels[1]) self.up1 = UpConv(channels[1]//4,channels[0]) self.conv = nn.Conv2d(channels[0],ratio,3,1,1) self.act = nn.Tanh() def forward(self,input): down1 = self.down1(input) cot1 = self.cot1(input) down1 = torch.cat([down1,cot1],dim=1) down2 = self.down2(down1) cot2 = self.cot2(down1) down2 = torch.cat([down2,cot2],dim=1) down3 = self.down3(down2) cot3 = self.cot3(down2) down3 = torch.cat([down3,cot3],dim=1) up2 = self.up2(down3) down2_conv = self.conv1x1_list[1](down2) up2_conv = self.conv3x3_list[1](torch.cat([up2,down2_conv],dim=1)) up1 = self.up1(up2_conv) down1_conv = self.conv1x1_list[0](down1) up1_conv = self.conv3x3_list[0](torch.cat([up1,down1_conv],dim=1)) out = self.conv(up1_conv) out = self.act(out) out = input+out return out
ucaswangls/GAP-CCoT
models/basicblock.py
basicblock.py
py
3,737
python
en
code
9
github-code
6
12700629432
import sys import heapq INF = int(1e9) def input(): return sys.stdin.readline().rstrip() def extractHackingResults(results): hacked_computer, max_hacking_time = 0, 0 for hacking_time in results: if hacking_time not in [None, INF]: hacked_computer += 1 max_hacking_time = max(max_hacking_time, hacking_time) return hacked_computer, max_hacking_time def getDijkstraHackingTime(number_of_computers, connections, first_hacked_computer): hacking_times = [None] + [INF] * number_of_computers hacking_times[first_hacked_computer] = 0 Q = [(0, first_hacked_computer)] while Q: _, present_computer = heapq.heappop(Q) for adj_computer, adj_hacking_time in connections[present_computer]: if hacking_times[adj_computer] > hacking_times[present_computer] + adj_hacking_time: hacking_times[adj_computer] = hacking_times[present_computer] + \ adj_hacking_time heapq.heappush(Q, (hacking_times[adj_computer], adj_computer)) return hacking_times def assignComputerConnections(): number_of_computers, dependencies, first_hacked_computer = map( int, input().split()) connections = {computer: [] for computer in range(1, number_of_computers + 1)} for _ in range(dependencies): to_computer, from_computer, hacking_time = map(int, input().split()) connections[from_computer].append((to_computer, hacking_time)) return number_of_computers, connections, first_hacked_computer def main(): for _ in range(int(input())): number_of_computers, connections, first_hacked_computer = assignComputerConnections() results = getDijkstraHackingTime( number_of_computers, connections, first_hacked_computer) print(*extractHackingResults(results)) main()
MinChoi0129/Algorithm_Problems
BOJ_Problems/10282.py
10282.py
py
1,875
python
en
code
2
github-code
6
32249755158
import streamlit as st import altair as altc import pandas as pd import numpy as np import os, urllib from PIL import Image import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, BatchNormalization, Activation, Dense, Dropout,UpSampling2D,Conv2DTranspose from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import MaxPooling2D from tensorflow.keras.layers import concatenate, add import plotly.express as px from u_net import build_unet st.cache(allow_output_mutation=True) def load_model(): H = 768 #to keep the original ratio W = 1152 num_classes = 23 model = build_unet((H,W, 3), num_classes) model.load_weights('unet(w)_44.h5') return model def main(): class_dict = pd.read_csv('class_dict_seg.csv') cla= [] for iteration in range(24): cla.append(list(class_dict.iloc[iteration][1:])) model = load_model() st.sidebar.header("Upload an Image File") uploaded_file = st.sidebar.file_uploader("") if uploaded_file is not None: st.sidebar.success('Image uploaded successfully') image = Image.open(uploaded_file) image= image.resize((1152,768)) arr = np.array(image) x = arr.reshape((1,768,1152,3)) plt.imshow(image) plt.axis("off") plt.show() plt.savefig('WC.jpg') img= Image.open("WC.jpg") st.header("Input Image") st.image(img) x = x/255 p = model.predict(x)[0] p = np.argmax(p, axis=-1) l = np.zeros(shape = (768, 1152,3),dtype = np.uint8) v = [] for i in range(768) : for j in range(1152) : k = p[i,j] v.append(cla[k]) l[i,j,:] = cla[k] plt.imshow(l) plt.savefig('se.jpg') img= Image.open("se.jpg") st.header("Segmented Image") st.image(img) # fig = px.imshow(img) # fig.show() if __name__=='__main__': main()
ajayjalluri/Drone-Data-Image-Segmentatation
app.py
app.py
py
2,166
python
en
code
0
github-code
6
15505226126
# Author: Lane Moseley # Description: This file demonstrates the usage of the custom logistic regression # module implemented in the ML library. # Resources Used: # Fish Dataset: # Included with the project, but also available from Kaggle: # https://www.kaggle.com/aungpyaeap/fish-market # Iris Dataset: # https://archive.ics.uci.edu/ml/datasets/iris # https://gist.github.com/curran/a08a1080b88344b0c8a7 # Logistic Regression Using scikit-learn: # https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html import matplotlib.pyplot as plt from ML import LogisticRegression, plot_decision_regions import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression as skLogisticRegression from sklearn.metrics import classification_report def main(): # IRIS DATASET ############################################################# df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None) # Extract the first 100 labels y = df.iloc[0:100, 4].values # Convert the labels to either 1 or 0 y = np.where(y == 'Iris-setosa', 0, 1) # Extract features from dataset [sepal_length, petal_length] X = df.iloc[0:100, [0, 2]].values # plot variables title = 'Iris Dataset' xlabel = 'Sepal Length [cm]' ylabel = 'Petal Length [cm]' # Plot what we have so far # Plot labels plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Plot the setosa data plt.scatter(X[:50, 0], X[:50, 1], color='red', marker='o', label='setosa') # Plot the versicolor data plt.scatter(X[50:100, 0], X[50:100, 1], color='blue', marker='x', label='versicolor') # Setup the plot legend plt.legend(loc='upper left') # Display the plot plt.show() # scikit-learn logistic regression skLR = skLogisticRegression() skLR.fit(X, y) # plot the decision regions and display metrics to the console plot_decision_regions(X, y, skLR, resolution=0.1, x_label=xlabel, y_label=ylabel, title=title + "\nscikit-learn Logistic Regression Model") print(title + "\nscikit-learn Logistic Regression Model") print(classification_report(y, skLR.predict(X))) # ML.py logistic regression mlLR = LogisticRegression(learning_rate=0.05, iterations=25) mlLR.fit(X, y) # plot the decision regions and display metrics to the console plot_decision_regions(X, y, mlLR, resolution=0.1, x_label=xlabel, y_label=ylabel, title=title + "\nML.py Logistic Regression Model") print(title + "\nML.py Logistic Regression Model") print(classification_report(y, mlLR.predict(X))) # FISH DATASET ############################################################# df = pd.read_csv('./Fish.csv') df = df.drop(df.index[0:61]) # Parkki rows df = df.drop(df.index[11:84]) # Smelt rows # Extract the data for Parkki and Smelt fish y = df.iloc[:, 0].values # Convert the labels to either 0 or 1 y = np.where(y == 'Parkki', 0, 1) # Extract features from dataset [weight, length] X = df.iloc[:, [2, 1]].values # plot variables title = 'Fish Dataset' xlabel = 'Length [cm]' ylabel = 'Weight [g]' # Plot what we have so far # Plot labels plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Plot the Parkki data plt.scatter(X[:11, 0], X[:11, 1], color='red', marker='o', label='Parkki') # Plot the Smelt data plt.scatter(X[11:, 0], X[11:, 1], color='blue', marker='x', label='Smelt') # Setup the plot legend plt.legend(loc='upper left') # Display the plot plt.show() # scikit-learn logistic regression skLR = skLogisticRegression() skLR.fit(X, y) # plot the decision regions and display metrics to the console plot_decision_regions(X, y, skLR, resolution=0.1, x_label=xlabel, y_label=ylabel, title=title + "\nscikit-learn Logistic Regression Model") print(title + "\nscikit-learn Logistic Regression Model") print(classification_report(y, skLR.predict(X))) # ML.py logistic regression mlLR = LogisticRegression(learning_rate=0.01, iterations=10) mlLR.fit(X, y) # plot the decision regions and display metrics to the console plot_decision_regions(X, y, mlLR, resolution=0.1, x_label=xlabel, y_label=ylabel, title=title + "\nML.py Logistic Regression Model") print(title + "\nML.py Logistic Regression Model") print(classification_report(y, mlLR.predict(X))) if __name__ == "__main__": main()
lanemoseley/ml-library
logisticRegression.py
logisticRegression.py
py
4,735
python
en
code
0
github-code
6
34435689503
#lucratividade x produtividade # a seguir voce vera uma analise de lucro x produtividade# lucro_primeira = float(input('digite seu lucro na primeira loja')) lucro_segunda = float(input('digite seu lucro na segunda loja')) lucro_terceira = float(input('digite seu lucro na terceira loja')) lucro_quarta = float(input('digite seu lucro na quarta loja')) lucro = lucro_primeira + lucro_segunda + lucro_terceira + lucro_quarta produçao_primeira = float(input('digite sua produçao na primeira loja')) produçao_segunda = float(input('digite sua produçao na segunda loja')) produçao_terceira = float(input('digite sua produçao na terceira loja')) produçao_quarta = float(input('digite sua produçao na quarta loja')) produçao = produçao_primeira + produçao_segunda + produçao_terceira + produçao_quarta #há sempre uma diferença entre renda líquida e renda bruta,á diferença se dá pela existencia de despesas variança = produçao - lucro renda_líquida = produçao - variança lucro_estimado1 = 1000000 #este valor é uma estimativa de um aumento da produção e\ou numero de vendas baseado no controle de estoque lucro_estimado2 = 750000 #o valor deste é o valor médio calculado á partir do ultimos 4 meses do ano da loja if(renda_líquida > lucro_estimado1): print('sua renda esta sendo positiva tendo margem de crescimento') elif (renda_líquida >= lucro_estimado2): print('sua renda sem encontra em uma moderada margem de crescimento') elif (renda_líquida < lucro_estimado2 ): print('suas vendas e sua produtividade estão em massiva queda') renda = 'a sua renda líquida final é de %.2f ' % (renda_líquida) print(renda) despesas = 'vc gastou %.2f em despesas'% (variança) print(despesas) Bruta = 'sua Renda bruta é de %.2f ' % ( produçao) print(Bruta) dispesa_extra = float(input('digite o valor das despesas extras cujo débito foi incluido mas não catalogado')) RendaXdespesa = variança - dispesa_extra Rendaxdespesa1 = 'Suas despesas casuais menos sua despesas extras deste mês é de %.2f ' % ( RendaXdespesa) print(Rendaxdespesa1) pergunta1 = input(('o Resultado foi satisfátorio')) if(pergunta1 == 'nao' and 'NAO'): print('elabore novos métodos, estratégias de para a operação') else: print('sua loja esta em constante crescimento parabéns')
gamiel075/py
estudov5.py
estudov5.py
py
2,343
python
pt
code
0
github-code
6
32461455469
import re import os datafolder = "./data/" def processObjdump(case: str) -> None: folder = datafolder + case input = case + "-armv8m.objdump" output = case + "Objdump.txt" inPath = os.path.join(folder, input) outPath = os.path.join(folder, output) with open(outPath, 'w') as w: with open(inPath, 'r') as r: lines = r.readlines() n = len(lines) for i in range(n): line = lines[i] if re.match("^\S{8} \<\S*\>", line): w.writelines(line.strip(":\n") + "\n") if i == n - 1 and re.match("^ *\S*:", line) and line[8] == ":": start = re.search("^ *\S", line).span()[1] w.writelines("0" * start + line[start : 8] + " <__endFunctionMap__>\n") def processInst(case: str): folder = datafolder + case input = "instLog_" + case + "_ori.txt" output = "instLog_" + case + ".txt" inPath = os.path.join(folder, input) outPath = os.path.join(folder, output) with open(outPath, 'w') as w: with open(inPath, 'r') as r: for line in r.readlines(): if re.search(" INST_COUNT=\S* ", line): instCountSpan = re.search(" INST_COUNT=\S* ", line).span() intsCount = line[instCountSpan[0] + 14: instCountSpan[1] - 1] pcSpan = re.search(" PC=\S ", line).span() pc = line[pcSpan[0] + 6: pcSpan[1] - 1] w.writelines("0" * (8 - len(pc)) + pc + " " + intsCount + "\n") processObjdump("quicksort") processInst("quicksort")
kakack/function-tracer
initialDemo/ProcessFile.py
ProcessFile.py
py
1,625
python
en
code
0
github-code
6
26627014986
from django.db import models from livesettings import config_value_safe, config_choice_values, SettingNotSet def shipping_choices(): try: return config_choice_values('SHIPPING','MODULES') except SettingNotSet: return () class ShippingChoiceCharField(models.CharField): def __init__(self, choices="__DYNAMIC__", *args, **kwargs): if choices == "__DYNAMIC__": kwargs['choices'] = shipping_choices() super(ShippingChoiceCharField, self).__init__(*args, **kwargs) try: # South introspection rules for our custom field. from south.modelsinspector import add_introspection_rules, matching_details # get the kwargs for a Field instance # we're using Field, as CharField doesn't change __init__() _args, kwargs = matching_details(models.Field()) add_introspection_rules([( (ShippingChoiceCharField, ), [], kwargs, )], ['shipping\.fields']) except ImportError: pass
dokterbob/satchmo
satchmo/apps/shipping/fields.py
fields.py
py
977
python
en
code
30
github-code
6
37751980621
import sys helpText = '''This tool is used to extract text from a file, summarize it using OpenAI's LLM model, and print/save it to a file. Supported file types: TXT, PDF, CSV, MD, JSON.''' helpText += '\nCommand-Line args required: -f filePath\nOptional Command-Line args: -start startingPageNum -end endingPageNum -d dstFile' def extractArgs(): length = len(sys.argv) if length < 2: print(helpText) exit() fileName = '' startPage = 1 endPage = -1 dstName = '' for i in range(1, length-1): if sys.argv[i] == '-f': fileName = sys.argv[i+1] if sys.argv[i] == '-start': startPage = int(sys.argv[i+1]) if sys.argv[i] == '-end': endPage = int(sys.argv[i+1]) if sys.argv[i] == '-d': dstName = sys.argv[i+1] if fileName == '': print("Error, no file path provided") exit return fileName, dstName, startPage, endPage # extracts the required
cglavin50/pdf-summarizer-cli
handlers/cliHandler.py
cliHandler.py
py
1,031
python
en
code
0
github-code
6
42197969651
from django.urls import path from .views import ( InvitiHome, InvitoDetailView, InvitoCreateView, InvitoUpdateView, InvitoDeleteView, InvitiUtente, PrenotazioniUtente, InvitoPartecipa, InvitiGenere, InvitoRimuoviPartecipa, InvitiFilterView, GeneriFilterView, About ) #app_name = 'inviti' urlpatterns = [ # /inviti/ path('', InvitiHome.as_view(), name='inviti-home'), # /inviti/nuovo path('nuovo/', InvitoCreateView.as_view(), name='invito-create'), # /inviti/filtra path('filtra/', InvitiFilterView.as_view(), name='inviti-filter'), # /inviti/about/ path('about/', About.as_view(), name='inviti-about'), # /inviti/invito/<id_invito> path('invito/<int:pk>/', InvitoDetailView.as_view(), name='invito-detail'), # /inviti/invito/<id_invito>/partecipa path('invito/<int:pk>/partecipa/', InvitoPartecipa.as_view(), name='invito-partecipa'), # /inviti/invito/<id_invito>/rimuovi_partecipa path('invito/<int:pk>/rimuovi_partecipa/', InvitoRimuoviPartecipa.as_view(), name='invito-rimuouvi-partecipa'), # /inviti/invito/<id_invito>/update path('invito/<int:pk>/update/', InvitoUpdateView.as_view(), name='invito-update'), # /inviti/invito/<id_invito>/delete path('invito/<int:pk>/delete/', InvitoDeleteView.as_view(), name='invito-delete'), # /inviti/utente/<username> path('utente/<str:username>', InvitiUtente.as_view(), name='inviti-utente'), # /inviti/utente/<username>/prenotazioni path('utente/<str:username>/prenotazioni', PrenotazioniUtente.as_view(), name='prenotazioni-utente'), # /inviti/generi path('generi/', GeneriFilterView.as_view(), name='generi-filter'), # /inviti/genere/<genere> path('genere/<str:genere>', InvitiGenere.as_view(), name='inviti-genere'), ]
lucacasarotti/CineDate
inviti/urls.py
urls.py
py
1,830
python
it
code
0
github-code
6
30138218135
# !/usr/local/python/bin/python # -*- coding: utf-8 -*- # (C) Wu Dong, 2020 # All rights reserved # @Author: 'Wu Dong <[email protected]>' # @Time: '2020-03-19 10:49' """ 演示 pre-request 框架如何使用长度校验,仅针对字符串有效 """ from flask import Flask from pre_request import pre, Rule app = Flask(__name__) app.config["TESTING"] = True client = app.test_client() # 指定email=True,此时框架会自动判断用户入参是否符合email正则 length_params = { "params": Rule(gt=2, lt=4) } @app.route("/length", methods=["GET", "POST"]) @pre.catch(length_params) def example_length_handler(params): return str(params) def example_length_filter(): """ 演示字符串长度验证 """ resp = client.get("/length", data={ "params": "abc" }) print(resp.data) resp = client.get("/length", data={ "params": "a" }) print(resp.data) resp = client.get("/length", data={ "params": "abcde" }) print(resp.data) if __name__ == "__main__": example_length_filter()
Eastwu5788/pre-request
examples/example_filter/example_length.py
example_length.py
py
1,070
python
en
code
55
github-code
6
35787180481
from starlette.responses import JSONResponse, FileResponse from starlette.background import BackgroundTasks from fastapi import APIRouter #, Form, File, UploadFile # from model.classification_pylon.predict import main as pylon_predict # from model.covid19_admission.predict_admission import main as covid_predict import shutil import subprocess import time import traceback from datetime import datetime from pydantic import BaseModel from typing import Optional import os # import json router = APIRouter() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMP_DIR = os.path.join(BASE_DIR, 'resources', 'temp') # record not optional? class InferData(BaseModel): model_name: str acc_no: str record: Optional[str] = None def remove_file(path): if os.path.exists(path): shutil.rmtree(path) print('Finish clearing temporary file') # inference @router.post("/", status_code=200) async def infer(inferData: InferData, background_tasks: BackgroundTasks = BackgroundTasks()): model_name = inferData.model_name acc_no = inferData.acc_no record = inferData.record now = datetime.now().strftime("%H%M%S%f") file_dir = os.path.join(TEMP_DIR, "{}_{}_{}".format(model_name, acc_no, now)) # remove directory after finish process background_tasks.add_task(remove_file, file_dir) try: start_time = time.time() subprocess.run(["python", os.path.join(BASE_DIR, "pacs_connection", "dicom_function.py"), "-f", "infer", "-a", acc_no, "-m", model_name, "-s", now, "-d", record]) if os.path.exists(os.path.join(file_dir, 'success.txt')): shutil.make_archive(os.path.join(file_dir, acc_no), 'zip', root_dir=os.path.join(file_dir, 'result'), ) print(f"Inference end time: {time.time() - start_time :.2f} seconds") return FileResponse(os.path.join(file_dir, acc_no + '.zip'), status_code=200) elif os.path.exists(os.path.join(file_dir, 'fail.txt')): message = "error" with open(os.path.join(file_dir, 'fail.txt'), "r") as f: message = f.readline() print('[Error]', message) return JSONResponse(content={"success": False, "message": message}, status_code=500) except Exception as e: print(traceback.format_exc()) # print(e) return JSONResponse(content={"success": False, "message": e}, status_code=500)
mmkanta/fl-webapp-model
api/infer.py
infer.py
py
2,542
python
en
code
0
github-code
6
74309695227
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.title("Turtle Race") screen.setup(width=600, height=600) screen.tracer(0) myplayer = Player() cars = CarManager() score = Scoreboard() screen.listen() screen.onkey(myplayer.move, "Up") game_is_on = True while game_is_on: time.sleep(0.1) cars.create() cars.move() for car in cars.mycars: if myplayer.distance(car) < 20: score.game_over() game_is_on = False if myplayer.ycor() > 280: score.increase_level() myplayer.reset_game() cars.move_increment() screen.update() screen.exitonclick()
shuklaritvik06/PythonProjects
Day - 23/main.py
main.py
py
726
python
en
code
0
github-code
6
40592577580
from collections import Counter import operator st=input() k=int(input()) omap=Counter(st) a=sorted(omap.items(),key=operator.itemgetter(1)) i=0 while k>0 and i<len(a): if a[i][1]<=k: k-=a[i][1] del omap[a[i][0]] else: omap[a[i][0]]-=k k=0 i+=1 print(len(omap)) ans="" for i in st: if i in omap: ans+=i omap[i]-=1 if omap[i]==0: del omap[i] #print(len(omap)) print(ans)
ku-nal/Codeforces
codeforces/102/C.py
C.py
py
479
python
en
code
3
github-code
6