import numpy as np
from typing import *
import scipy
from loompy import timestamp

class MemoryLoomLayer():
	"""
	A layer residing in memory (without a corresponding layer on disk), typically
	as part of a :class:`loompy.LoomView`. MemoryLoomLayer supports a subset of
	the operations suported for regular layers.
	"""
	def __init__(self, name: str, matrix: np.ndarray) -> None:
		self.name = name  #: Name of the layer
		self.shape = matrix.shape  #: Shape of the layer
		self.values = matrix

	def __getitem__(self, slice: Tuple[Union[int, slice], Union[int, slice]]) -> np.ndarray:
		return self.values[slice]

	def __setitem__(self, slice: Tuple[Union[int, slice], Union[int, slice]], data: np.ndarray) -> None:
		self.values[slice] = data

	def sparse(self, rows: np.ndarray, cols: np.ndarray) -> scipy.sparse.coo_matrix:
		"""
		Return the layer as :class:`scipy.sparse.coo_matrix`
		"""
		return scipy.sparse.coo_matrix(self.values[rows, :][:, cols])

	def permute(self, ordering: np.ndarray, *, axis: int) -> None:
		"""
		Permute the layer along an axis

		Args:
			axis: The axis to permute (0, permute the rows; 1, permute the columns)
			ordering: The permutation vector
		"""
		if axis == 0:
			self.values = self.values[ordering, :]
		elif axis == 1:
			self.values = self.values[:, ordering]
		else:
			raise ValueError("axis must be 0 or 1")

class LoomLayer():
	"""
	Represents a layer (matrix) of values in the loom file, which can be accessed by slicing.
	"""

	def __init__(self, name: str, ds: Any) -> None:
		self.ds = ds  #: The :class:`.LoomConnection` object this layer belongs to
		self.name = name  #: Name of the layer (str)
		self.shape = ds.shape  #: Shape of the layer, tuple of (n_rows, n_cols)
		self.dtype = ""  #: Datatype of the layer (str)
		if name == "":
			self.dtype = self.ds._file["/matrix"].dtype
		else:
			self.dtype = self.ds._file["/layers/" + self.name].dtype

	def last_modified(self) -> str:
		"""
		Return a compact ISO8601 timestamp (UTC timezone) indicating when the file was last modified

		Note: if the layer does not contain a timestamp, and the mode is 'r+', a new timestamp will be set and returned.
		Otherwise, the current time in UTC will be returned.
		"""
		if self.name == "":
			if "last_modified" in self.ds._file["/matrix"].attrs:
				return self.ds._file["/matrix"].attrs["last_modified"]
			elif self.ds._file.mode == 'r+':
				self.ds._file["/matrix"].attrs["last_modified"] = timestamp()
				self.ds._file.flush()
				return self.ds._file["/matrix"].attrs["last_modified"]

		if self.name != "":
			if "last_modified" in self.ds._file["/layers/" + self.name].attrs:
				return self.ds._file["/layers/" + self.name].attrs["last_modified"]
			elif self.ds._file.mode == 'r+':
				self.ds._file["/layers/" + self.name].attrs["last_modified"] = timestamp()
				self.ds._file.flush()
				return self.ds._file["/layers/" + self.name].attrs["last_modified"]

		return timestamp()

	def __getitem__(self, slice: Tuple[Union[int, slice], Union[int, slice]]) -> np.ndarray:
		if self.name == "":
			return self.ds._file['/matrix'].__getitem__(slice)
		return self.ds._file['/layers/' + self.name].__getitem__(slice)

	def __setitem__(self, slice: Tuple[Union[int, slice], Union[int, slice]], data: np.ndarray) -> None:
		if self.name == "":
			self.ds._file['/matrix'][slice] = data
			self.ds._file["/matrix"].attrs["last_modified"] = timestamp()
			self.ds._file.attrs["last_modified"] = timestamp()
			self.ds._file.flush()
		else:
			self.ds._file['/layers/' + self.name][slice] = data
			self.ds._file["/layers/" + self.name].attrs["last_modified"] = timestamp()
			self.ds._file.attrs["last_modified"] = timestamp()
			self.ds._file.flush()

	def sparse(self, rows: np.ndarray = None, cols: np.ndarray = None, dtype = None) -> scipy.sparse.coo_matrix:
		if rows is not None:
			if np.issubdtype(rows.dtype, np.bool_):
				rows = np.where(rows)[0]
		if cols is not None:
			if np.issubdtype(cols.dtype, np.bool_):
				cols = np.where(cols)[0]

		n_genes = self.ds.shape[0] if rows is None else rows.shape[0]
		n_cells = self.ds.shape[1] if cols is None else cols.shape[0]
		# Calculate sparse data length to be able to reserve proper sized arrays beforehand
		nnonzero = 0
		for (ix, selection, view) in self.ds.scan(items=cols, axis=1, layers=[self.name], what=["layers"], batch_size=4096):
			if rows is not None:
				vals = view.layers[self.name][rows, :]
			else:
				vals = view.layers[self.name][:, :]
			nnonzero += np.count_nonzero(vals)
		data = np.empty((nnonzero,), dtype=dtype) #(data: List[np.ndarray] = []
		row = np.empty((nnonzero,), dtype=('uint16' if self.ds.shape[0] < 2**16 else 'uint32')) #row : List[np.ndarray] = []
		col = np.empty((nnonzero,), dtype=('uint32' if self.ds.shape[1] < 2**32 else 'uint64')) #col: List[np.ndarray] = []
		i = 0
		ci = 0
		for (ix, selection, view) in self.ds.scan(items=cols, axis=1, layers=[self.name], what=["layers"], batch_size=4096):
			if rows is not None:
				vals = view.layers[self.name][rows, :]
			else:
				vals = view.layers[self.name][:, :]
			if dtype:
				vals = vals.astype(dtype)
			nonzeros = np.where(vals != 0)
			n = len(nonzeros[0])
			data[ci:ci+n] = vals[nonzeros] #data.append(vals[nonzeros])
			row[ci:ci+n] = nonzeros[0] #row.append(nonzeros[0])
			col[ci:ci+n] = (nonzeros[1]+i) #col.append(nonzeros[1] + i)
			ci += n
			i += selection.shape[0]
		return scipy.sparse.coo_matrix((data, (row, col)), shape=(n_genes, n_cells), dtype=dtype)
		#return scipy.sparse.coo_matrix((np.concatenate(data, dtype=dtype), (np.concatenate(row), np.concatenate(col))), shape=(n_genes, n_cells), dtype=dtype)

	def _resize(self, size: Tuple[int, int], axis: int = None) -> None:
		"""Resize the dataset, or the specified axis.

		The dataset must be stored in chunked format; it can be resized up to the "maximum shape" (keyword maxshape) specified at creation time.
		The rank of the dataset cannot be changed.
		"Size" should be a shape tuple, or if an axis is specified, an integer.

		BEWARE: This functions differently than the NumPy resize() method!
		The data is not "reshuffled" to fit in the new shape; each axis is grown or shrunk independently.
		The coordinates of existing data are fixed.
		"""
		if self.name == "":
			self.ds._file['/matrix'].resize(size, axis)
		else:
			self.ds._file['/layers/' + self.name].resize(size, axis)

	def map(self, f_list: List[Callable[[np.ndarray], int]], axis: int = 0, chunksize: int = 1000, selection: np.ndarray = None) -> List[np.ndarray]:
		"""
		Apply a function along an axis without loading the entire dataset in memory.

		Args:
			f_list (list of func):		Function(s) that takes a numpy ndarray as argument

			axis (int):		Axis along which to apply the function (0 = rows, 1 = columns)

			chunksize (int): Number of rows (columns) to load per chunk

			selection (array of bool): Columns (rows) to include

		Returns:
			numpy.ndarray result of function application

			If you supply a list of functions, the result will be a list of numpy arrays. This is more
			efficient than repeatedly calling map() one function at a time.
		"""
		if hasattr(f_list, '__call__'):
			raise ValueError("f_list must be a list of functions, not a function itself")

		result = []
		if axis == 0:
			rows_per_chunk = chunksize
			for i in range(len(f_list)):
				result.append(np.zeros(self.shape[0]))
			ix = 0
			while ix < self.shape[0]:
				rows_per_chunk = min(self.shape[0] - ix, rows_per_chunk)
				if selection is not None:
					chunk = self[ix:ix + rows_per_chunk, :][:, selection]
				else:
					chunk = self[ix:ix + rows_per_chunk, :]
				for i in range(len(f_list)):
					result[i][ix:ix + rows_per_chunk] = np.apply_along_axis(f_list[i], 1, chunk)
				ix = ix + rows_per_chunk
		elif axis == 1:
			cols_per_chunk = chunksize
			for i in range(len(f_list)):
				result.append(np.zeros(self.shape[1]))
			ix = 0
			while ix < self.shape[1]:
				cols_per_chunk = min(self.shape[1] - ix, cols_per_chunk)
				if selection is not None:
					chunk = self[:, ix:ix + cols_per_chunk][selection, :]
				else:
					chunk = self[:, ix:ix + cols_per_chunk]
				for i in range(len(f_list)):
					result[i][ix:ix + cols_per_chunk] = np.apply_along_axis(f_list[i], 0, chunk)
				ix = ix + cols_per_chunk
		return result

	def _permute(self, ordering: np.ndarray, *, axis: int) -> None:
		if self.name == "":
			obj = self.ds._file['/matrix']
		else:
			obj = self.ds._file['/layers/' + self.name]
		if axis == 0:
			chunksize = 5000
			start = 0
			while start < self.shape[1]:
				submatrix = obj[:, start:start + chunksize]
				obj[:, start:start + chunksize] = submatrix[ordering, :]
				start = start + chunksize
		elif axis == 1:
			chunksize = 100000000 // self.shape[1]
			start = 0
			while start < self.shape[0]:
				submatrix = obj[start:start + chunksize, :]
				obj[start:start + chunksize, :] = submatrix[:, ordering]
				start = start + chunksize
		else:
			raise ValueError("axis must be 0 or 1")


#Programa que genera las medidas de humedad del suelo del sensor.

import RPi.GPIO as GPIO #Libreria para utilizar las GPIO.
import time 		#Libreria para las funciones relacionadas al tiempo. (time)

#set out GPIO numberring to BCM
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#Definir los pines GPIO a usar.
channel =24 #Sensor de Humedad
motor = 25  #Bomba de agua
led1= 18    #Led Verde
led2 = 17   # Led Azul

#configuramos los pines GPIO como Input (entrada).
GPIO.setup(channel,GPIO.IN)
#configuramos los pines GPIO como Output (salida).
GPIO.setup(25,GPIO.OUT) #Bomba de Agua
GPIO.setup(18,GPIO.OUT) #Led Verde
GPIO.setup(17,GPIO.OUT) #Led Azul

#Funcion para obtener el valor digital.
def medirHumedad():
    valor = GPIO.input(24) #Entrada del sensor
    if valor == 0:
        print("Humedo") #Imprimir valores

    else:
        print("Seco") #Imprimir valores

    print("sensando humedad")

    if valor >0:
        GPIO.output(18, True) #Encender led Verde
        GPIO.output(25, True) #Encender bomba de agua
        GPIO.output(17, False) ## Apagar led azul
        print("Encendiendo bomba de agua")
        time.sleep (10)
        print("Apagando bomba de agua")

    elif not():
        GPIO.output(17, True) ## Encender led azul
        time.sleep(1) # Esperamos 1 segundo
        GPIO.output(17, False) ## Apagar led azul
        time.sleep(1) ## Esperamos 1 segundo

        GPIO.output(25, False) #Apagar bomba
        GPIO.output(18, False) #Apagar led Verde

    #Definir un ciclo infinito para medir la humedad cada 2 segundos.
while True:
    medirHumedad()
    time.sleep(2)

Sensor de humedad con bomba de agua/humedad3.0.py


class TicketHandler:

    def __init__(self):
        self.nextId = 0
        self.tickets = []

    def createTicket(data):
        ticketTuple = jsonToTuple(data)
        ticket = Ticket(self.nextId, ticketTuple.name,
                    ticketTuple.estimatedHours)
        self.tickets.append(ticket)
        self.nextId = self.nextId +1
    def readticket(ticketId):
        for ticket in self.tickets:
            if ticket.id == ticketId:
                return ticket
        return None
    def updateticket(data):
        ticketTuple = jsonToTuple(data)
        for ticket in tickets:
            if ticket.id == ticketTuple.id:
                ticket.name = ticketTuple.name
                ticket.estimatedHours = ticketTuple.estimatedHours
                ticket.spentHours = ticketTuple.spentHours
                return 1
        return None
    def deleteticket(ticketId):
        deleteId = -1
        for x in range(0,len(self.tickets)):
            if self.tickets[x].id == ticketId:
                deleteId = x
                break
        if deleteId > -1:
            return self.tickets.pop(deleteId)
        return None

    def jsonToTuple(self, data):
        x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
        return x


###
### Define a simple next_day procedure, that assumes
### every month has 30 days.
###
### For example:
###    next_day(1999, 12, 30) => (2000, 1, 1)
###    next_day(2013, 1, 30) => (2013, 2, 1)
###    next_day(2012, 12, 30) => (2013, 1, 1)  (even though December really has 31 days)
###

def next_day(year, month, day):
    """
    Returns the year, month, day of the next day.
    Simple version: assume every month has 30 days.
    """
    # YOUR CODE HERE
    if day + 1 <= 30:
        return year, month, day + 1
    day = (day + 1) % 30
    if month + 1 <= 12:
        return year, month + 1, day
    month = (month + 1) % 12
    year = year + 1
    return year, month, day

print(next_day(2012, 12, 30))  # => (2013, 1, 1)  (even though December really has 31 days)

# print next_day(1999, 12, 30)
# print next_day(2013, 1, 30) #=> (2013, 2, 1)
# Nice job! Test case next_day(2012, 1, 1) is correct!
# Nice job! Test case next_day(2012, 4, 30) is correct!
# Nice job! Test case next_day(2012, 12, 1) is correct!
# Nice job! Test case next_day(1999, 12, 30) is correct!
# Nice job! Test case next_day(2012, 12, 30) is correct!

Udacity/1 - Introduction/Problem Solving/U-ProblemSolving.py


import keras
from keras import layers
from keras import backend as K
import numpy as np

TRAIN_FILE = 'zip.train'
TEST_FILE = 'zip.test'

import numpy as np
X1 = np.loadtxt(TRAIN_FILE)
X2 = np.loadtxt(TEST_FILE)
X = np.vstack((X1, X2))

y = X[:, 0]
X = np.delete(X, 0, axis=1)

y[y != 1] = -1

from sklearn.decomposition import PCA
pca = PCA(n_components=2, svd_solver='full')
pca.fit(X)
X = pca.transform(X)

X = (X - np.min(X, axis = 0)) / (np.max(X, axis = 0) - np.min(X, axis = 0))

from sklearn.model_selection import train_test_split
X_test, X_train, y_test, y_train = train_test_split(X, y, test_size= 300 / X.shape[0])

model = keras.Sequential()
model.add(layers.Dense(10, activation= 'tanh'))
model.add(layers.Dense(1))

from keras.callbacks import EarlyStopping
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1)
model.compile('adam', 'mean_squared_error')
history = model.fit(X_train, y_train, validation_split = 1/6, epochs = 10000, verbose=2, callbacks = [es])

preds = model.predict(X_test)
preds[preds > 0] = 1
preds[preds < 0] = -1
from sklearn.metrics import accuracy_score
print(1-accuracy_score(y_test, preds))

import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c = y)
x1, x2 = np.mgrid[-5:5:0.01, -5:5:0.01]
y_hat = model.predict(np.c_[x1.ravel(), x2.ravel()]).reshape((x1.shape[0], x2.shape[0]))
plt.contour(x1, x2, y_hat, [0])
plt.show()


def solve(n,m):
    result=0
    while(n>=m):
        result+=int(n/m)
        n=int(n/m)+(n%m)
    return result
t=int(input())
while(t>0):
    n,m=map(int,input().split())
    print(solve(n,m))
    t-=1


from django import forms
from django.template.defaultfilters import force_escape
from baruwa.utils.regex import DOM_RE
import datetime, time
try:
    from django.forms.fields import email_re
    from django.forms.fields import ipv4_re
except ImportError:
    from django.core.validators import email_re
    from django.core.validators import ipv4_re

FILTER_ITEMS = (
    ('id','Message ID'),
    ('size','Size'),
    ('from_address','From Address'),
    ('from_domain', 'From Domain'),
    ('to_address','To Address'),
    ('to_domain','To Domain'),
    ('subject','Subject'),
    ('clientip','Received from'),
#    ('archive','Is Archived'),
    ('scaned', 'Was scanned'),
    ('spam','Is spam'),
    ('highspam','Is high spam'),
    ('saspam','Is SA spam'),
    ('rblspam','Is RBL listed'),
    ('whitelisted','Is whitelisted'),
    ('blacklisted','Is blacklisted'),
    ('sascore','SA score'),
    ('spamreport','Spam report'),
    ('virusinfected','Is virus infected'),
    ('nameinfected','Is name infected'),
    ('otherinfected','Is other infected'),
    ('date','Date'),
    ('time','Time'),
    ('headers','Headers'),
    ('isquarantined','Is quarantined'),
)

FILTER_BY = (
    (1,'is equal to'),
    (2,'is not equal to'),
    (3,'is greater than'),
    (4,'is less than'),
    (5,'contains'),
    (6,'does not contain'),
    (7,'matches regex'),
    (8,'does not match regex'),
    (9,'is null'),
    (10,'is not null'),
    (11,'is true'),
    (12,'is false'),
)

EMPTY_VALUES = (None, '')

BOOL_FIELDS = ["scaned", "spam", "highspam", "saspam", "rblspam",
    "whitelisted", "blacklisted", "virusinfected", "nameinfected",
    "otherinfected", "isquarantined"]
TEXT_FIELDS = ["id", "from_address", "from_domain", "to_address",
    "to_domain", "subject", "clientip", "spamreport", "headers"]
TIME_FIELDS = ["date","time"]
NUM_FIELDS = ["size", "sascore"]

BOOL_FILTER = [11, 12]
NUM_FILTER = [1, 2, 3, 4]
TEXT_FILTER = [1, 2, 5, 6, 7, 8, 9, 10]
TIME_FILTER = [1, 2, 3, 4]

def isnumeric(value):
    "Validate numeric values"
    return str(value).replace(".", "").replace("-", "").isdigit()

def to_dict(tuple_list):
    "Convert tuple to dictionary"
    dic = {}
    for val in tuple_list:
        dic[val[0]] = val[1]
    return dic

class FilterForm(forms.Form):
    "Filters form"
    filtered_field = forms.ChoiceField(choices=FILTER_ITEMS)
    filtered_by = forms.ChoiceField(choices=FILTER_BY)
    filtered_value = forms.CharField(required=False)

    def clean(self):
        "validate the form"
        cleaned_data = self.cleaned_data
        submited_field = cleaned_data.get('filtered_field')
        submited_by = int(cleaned_data.get('filtered_by'))
        submited_value = cleaned_data.get('filtered_value')
        if submited_by != 0:
            sbi = (submited_by - 1)
        else:
            sbi = submited_by

        if submited_field in BOOL_FIELDS:
            if not submited_by in BOOL_FILTER:
                filter_items = to_dict(list(FILTER_ITEMS))
                error_msg = "%s does not support the %s filter" % (
                    filter_items[submited_field],FILTER_BY[sbi][1])
                raise forms.ValidationError(error_msg)
        if submited_field in NUM_FIELDS:
            if not submited_by in NUM_FILTER:
                filter_items = to_dict(list(FILTER_ITEMS))
                error_msg = "%s does not support the %s filter" % (
                    filter_items[submited_field],FILTER_BY[sbi][1])
                raise forms.ValidationError(error_msg)
            if submited_value in EMPTY_VALUES:
                raise forms.ValidationError("Please supply a value to query")
            if not isnumeric(submited_value):
                raise forms.ValidationError("The value has to be numeric")
        if submited_field in TEXT_FIELDS:
            if not submited_by in TEXT_FILTER:
                filter_items = to_dict(list(FILTER_ITEMS))
                error_msg = "%s does not support the %s filter" % (
                    filter_items[submited_field],FILTER_BY[sbi][1])
                raise forms.ValidationError(error_msg)
            if submited_value in EMPTY_VALUES:
                raise forms.ValidationError("Please supply a value to query")
            if ( FILTER_BY[sbi][1] == 'is equal to' or FILTER_BY[sbi][1] == 'is not equal to' ):
                if (submited_field == 'from_address') or (
                    submited_field == 'to_address'):
                    if not email_re.match(submited_value.strip()):
                        raise forms.ValidationError(
                            '%s is not a valid e-mail address.'
                            % force_escape(submited_value))
                if (submited_field == 'from_domain') or (
                    submited_field == 'to_domain'):
                    if not DOM_RE.match(submited_value.strip()):
                        raise forms.ValidationError(
                            'Please provide a valid domain name')
                if submited_field == 'clientip':
                    if not ipv4_re.match(submited_value.strip()):
                        raise forms.ValidationError(
                            'Please provide a valid ipv4 address')
        if submited_field in TIME_FIELDS:
            if not submited_by in TIME_FILTER:
                filter_items = to_dict(list(FILTER_ITEMS))
                error_msg = "%s does not support the %s filter" % (
                    filter_items[submited_field],FILTER_BY[sbi][1])
                raise forms.ValidationError(error_msg)
            if submited_value in EMPTY_VALUES:
                raise forms.ValidationError("Please supply a value to query")
            if submited_field == 'date':
                try:
                    datetime.date(
                        *time.strptime(submited_value, '%Y-%m-%d')[:3])
                except ValueError:
                    raise forms.ValidationError(
                        'Please provide a valid date in YYYY-MM-DD format')
            if submited_field == 'time':
                try:
                    datetime.time(*time.strptime(submited_value, '%H:%M')[3:6])
                except ValueError:
                    raise forms.ValidationError(
                        'Please provide valid time in HH:MM format')

        return cleaned_data


from Data import Data
class Bt:
    def __init__(self , Matrix ,N , col, V , M,T=2):
        self.graph = Matrix
        self.m=M
        self.V=V
        self.T=T
        self.name=N
        self.cl=col

    def isSafe(self,graph, color):
        for i in range(self.V):
            for j in range(i, self.V):
                if graph[i][j]==1 and color[j]==color[i]:
                    return False
        return True

    def graphColoring(self,graph, m , i , color):
        if i==self.V:
            if self.isSafe(graph,color):
                self.printSolution(color)
                return True
            return False
        for j in range(1 , m+1):
            color[i]=j
            if self.graphColoring(graph , m , i+1 , color):
                return True
            color[i]=0
        return False

    def printSolution(self,color) :
        print("Solution Exists: Following are the assigned colors")
        for i in range(self.V):
            print(self.name[i]+" : "+self.cl[color[i]])

    def Start(self):
        color=list()
        for i in range(self.V):
            color.append(0)
        if not(self.graphColoring(self.graph,self.m,0,color)):
            print("Solution does not exist")


#Дана последовательность чисел.
# Получить список уникальных элементов заданной последовательности,
# список повторяемых и убрать дубликаты из заданной последовательности.
#Пример:
#[1, 2, 3, 5, 1, 5, 3, 10] => [2, 10] и [1, 3, 5] и [1, 2, 5, 3, 10]
import itertools

lst_input = input('Введите последовательность чисел :  ')
lst_number = [int(num)for num in lst_input.split()]
lst_not_doble = list(set(lst_number))
lst_sort = sorted(lst_number)
lst_unique = []
lst_repeat = []
for num, lst_num in itertools.groupby(lst_sort):
    if len(list(lst_num)) ==1:
        lst_unique.append(num)
    else:
        lst_repeat.append(num)
print(f'Исходная последовательность чисел:   {lst_number}')
print(f'Список неповторяющихся чисел:   {lst_unique}')
print(f'Список повторяющихся чисел последовательности:   {lst_repeat}')
print(f'Список без дублей:   {lst_not_doble}')


import logging.config

logging.config.fileConfig("logging.ini", disable_existing_loggers=False)

log = logging.getLogger(__name__)

log.debug('DEBUG message')
log.info('INFO message')
log.warning('WARNING message')
log.error('ERROR message')
log.critical('CRITICAL message')


# csv_handler.py
import pandas as pd
import matplotlib.pyplot as plt
from .models import CsvData

def process_csv(file):
    pdf = pd.read_csv('media/'+file)
    # Save data to CsvData model
    avg_price_by_year = pdf.groupby('year')['price'].mean()

    # Create a line chart to visualize the average price by year
    plt.figure(figsize=(8, 6))
    plt.plot(avg_price_by_year.index, avg_price_by_year.values, marker='o', color='b', linestyle='-', linewidth=2, markersize=8)
    plt.title('Average Price by Year')
    plt.xlabel('Year')
    plt.ylabel('Average Price')
    plt.title('Price by Year')
    chart_path = 'media/sample_chart.png'  # Save the chart as an image
    plt.savefig(chart_path)
    plt.close()
    return chart_path


from ..utils import Object

class Notification(Object):
    """
    Contains information about a notification

    Attributes:
        ID (:obj:`str`): ``Notification``

    Args:
        id (:obj:`int`):
            Unique persistent identifier of this notification
        date (:obj:`int`):
            Notification date
        is_silent (:obj:`bool`):
            True, if the notification was explicitly sent without sound
        type (:class:`telegram.api.types.NotificationType`):
            Notification type

    Returns:
        Notification

    Raises:
        :class:`telegram.Error`
    """
    ID = "notification"

    def __init__(self, id, date, is_silent, type, **kwargs):

        self.id = id  # int
        self.date = date  # int
        self.is_silent = is_silent  # bool
        self.type = type  # NotificationType

    @staticmethod
    def read(q: dict, *args) -> "Notification":
        id = q.get('id')
        date = q.get('date')
        is_silent = q.get('is_silent')
        type = Object.read(q.get('type'))
        return Notification(id, date, is_silent, type)


from bs4 import BeautifulSoup
import cfscrape
import shutil
import sys
import time
from random import randrange

def randomurlnums():
    urlnums = randrange(1,9999)
    if urlnums < 1000:
        while len(str(urlnums)) < 4:
            urlnums = '0'+str(urlnums)
    else:
        urlnums= str(urlnums)
    return urlnums
def randomurlletters():
    alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    first = alphabet[randrange(25)]
    second = alphabet[randrange(25)]
    letters = first+second
    return letters

# I sleep inside here because I got an ip banned by cloud flare )=

#this function just takes a url that links to a .png file and saves it in the same directory with given filename
#we have to do this through an http request because of cloudflare
def urlImg2File(url,filename):
    time.sleep(0.1)
    response = scraper.get(url,stream=True)
    #this is where the writing to file happens idk the specifics stolen from stack overflow
    with open(f'{filename}.png','wb') as out_file:
        shutil.copyfileobj(response.raw,out_file)
    del response
random = False
starturl = 'https://prnt.sc/'
if len(sys.argv) == 2 or len(sys.argv) == 1:
    print('random url')
    random = True
    urlnums = 0

    if len(sys.argv)==1:
        stop = 100
    else:
        stop = int(sys.argv[1])

else:

    letters = sys.argv[1]

    urlnums = sys.argv[2]

    #each time we run it goes for 100
    stop = int(urlnums) + int(sys.argv[3])

if(stop>=10000):
    print('start number too high for the amount of pictures you want')
    quit()
#The scraper has to emulate a browser so we have to create an instance of a nodejs server to do that cfscrape allows that and here
#the fake browser is created
scraper = cfscrape.create_scraper()

while int(urlnums) < stop:
    if not random:
        url = starturl + letters + urlnums
    else:
        url = starturl + randomurlletters() + randomurlnums()
    print(url)
    #sleep get url grab data feed it into beautiful soup so we can iterate over it better
    time.sleep(0.1)
    page = scraper.get(url)
    data = page.text

    soup = BeautifulSoup(data, 'html5lib')

    image = None
    #for every link we find with the img tag
    for link in soup.find_all('img'):
        #we check if starts with https://image which was gotten through source inspection of prnt.sc
        tempurl = str(link.get('src'))
        if tempurl.startswith('https://image'):
            #increment url number to bruteforce look
            urlnums = str(int(urlnums) + 1)
            #we save our found png with a file name so we can get back to it from the url.
            if not random:
                urlImg2File(tempurl,letters+urlnums)
            else:
                urlImg2File(tempurl,url[16:])
            break
    else:
        urlnums = str(int(urlnums) + 1)
        if random:
            stop+=1
    continue


import pandas as pd
import tweepy
from datetime import datetime

# twitter api credentials
ACCESS_TOKEN = 'XXXXXX'
ACCESS_SECRET = 'XXXXX'
CONSUMER_KEY = 'XXXXX'
CONSUMER_SECRET = 'XXXXX'

# Setup access to API
def connect_to_twitter_OAuth():
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)

    api = tweepy.API(auth, wait_on_rate_limit = True)
    return api

limit = 500
# Create API object
api = connect_to_twitter_OAuth()

print("try again")
tweets = []
# scraping 2000 tweets
for i in range(100):
    tweets.extend(api.user_timeline(
        screen_name = '@WilliamsRuto',
        include_rts = True,
        # keep full text
        tweet_mode = 'extended'

    ))

tweet_list = []
for tweet in tweets:
    text = tweet._json['full_text']

    refined_tweet = {
        'user': tweet.user.screen_name,
        'text' : text,
        'favorite_count': tweet.favorite_count,
        'retweet_count' : tweet.retweet_count,
        'create_at': tweet.created_at,
    }

    tweet_list.append(refined_tweet)

df = pd.DataFrame(tweet_list)

df.to_csv('william_ruto_tweets.csv')
print("done")

william = pd.read_csv("william_ruto_tweets.csv")
print(william.shape)


"""Create yaml files from bib files."""
import bibtexparser
from bibtexparser.bparser import BibTexParser
from bibtexparser.customization import author, convert_to_unicode
import yaml
import argparse
import os

def format_authors(list_of_authors, special_author):
    authors = ""
    num_authors = len(list_of_authors)
    for idx, author in enumerate(list_of_authors):
        last, first = author.split(", ")
        initials = "".join([x[0] + ". " for x in first.split(" ")])
        if idx <= (num_authors - 3):
            joining_string = ", "
        elif idx == (num_authors - 2):
            joining_string = " \& "
        else:
            joining_string = ""
        author_name = initials + last
        if author_name == special_author:
            author_name = r"\underline{" + author_name + "}"
        authors += author_name + joining_string
    return authors

def customizations(record):
    record = author(record)
    record = convert_to_unicode(record)
    return record

def format_entries(entries_dict, special_author):
    for k in entries_dict.keys():
        if "collaboration" not in entries_dict[k]:
            entries_dict[k]["author"] = format_authors(
                entries_dict[k]["author"], special_author)

def get_publication_dict_from_bib(bibfile, special_author):
    bib_file = open(bibfile, "r")
    parser = BibTexParser()
    parser.customization = customizations
    bib_database = bibtexparser.load(bib_file, parser=parser)
    bib_file.close()
    entries_dict = bib_database.entries_dict
    format_entries(entries_dict, special_author)
    return entries_dict

def get_publication_list_from_dict(pub_dict):
    publist = "\\begin{enumerate}\n"
    for k in pub_dict:
        d = data[k]
        if "collaboration" in d:
            d["author"] = d["collaboration"]
        p = "\\item "
        p += d["author"] + ", " + "``" + d["title"] + "\"" + ", "
        if "journal" in d:
            p += "\href{" + "https://doi.org/" + d["doi"] + "}{" + d["journal"] + "}" + ", "
            p += "{\\bfseries " + d["volume"] + "}" + ", " + d["pages"] + ", "
        p += "(" + d["year"] + "), "
        p += "\href{" + "https://arxiv.org/abs/" + d["eprint"] + "}{arXiv:" + d["eprint"] + " [" + d["primaryclass"] +"]}" + ", "
        publist += "\\end{enumerate}\n"


from ecsController import ecsController
import unittest
import logging

REGION = 'eu-west-2'
SEARCHTAG = 'DEVDAY'

class test_deleteState(unittest.TestCase):

    def test_delete(self):
        logger.info("-----Testing delete State method------")

        ecs = ecsController(REGION, SEARCHTAG)
        clustermap  =ecs.loadState()
        orig = len(clustermap)
        self.assertTrue(orig>0, msg="database should not have been empty")

        logger.info(f"******LOADED MAP > {clustermap} ")
        ecs._deleteState(clustermap)
        nomap = ecs.loadState()
        items = len(nomap)
        self.assertEqual(items,0,msg="there should be no items in the database")

        logger.info("restoring the database state")
        ecs.storeState(clustermap)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    logger =logging.getLogger()
    unittest.main()


import asyncio
import datetime
import io
import os
import re
import random
import signal
import sys

import discord
import pygame

from pgbot import commands, common, db, emotion, routine
from pgbot.utils import embed_utils, utils

async def _init():
    """
    Startup call helper for pygame bot
    """
    if not common.TEST_MODE:
        # when we are not in test mode, we want stout/stderr to appear on a console
        # in a discord channel
        sys.stdout = sys.stderr = common.stdout = io.StringIO()

    print("The PygameCommunityBot is now online!")
    print("Server(s):")

    for server in common.bot.guilds:
        prim = ""

        if common.guild is None and (
            common.GENERIC or server.id == common.ServerConstants.SERVER_ID
        ):
            prim = "| Primary Guild"
            common.guild = server

        print(" -", server.name, "| Number of channels:", len(server.channels), prim)
        if common.GENERIC:
            continue

        for channel in server.channels:
            if channel.id == common.ServerConstants.DB_CHANNEL_ID:
                common.db_channel = channel
                await db.init()
            elif channel.id == common.ServerConstants.LOG_CHANNEL_ID:
                common.log_channel = channel
            elif channel.id == common.ServerConstants.ARRIVALS_CHANNEL_ID:
                common.arrivals_channel = channel
            elif channel.id == common.ServerConstants.GUIDE_CHANNEL_ID:
                common.guide_channel = channel
            elif channel.id == common.ServerConstants.ROLES_CHANNEL_ID:
                common.roles_channel = channel
            elif channel.id == common.ServerConstants.ENTRIES_DISCUSSION_CHANNEL_ID:
                common.entries_discussion_channel = channel
            elif channel.id == common.ServerConstants.CONSOLE_CHANNEL_ID:
                common.console_channel = channel
            elif channel.id == common.ServerConstants.RULES_CHANNEL_ID:
                common.rules_channel = channel
            for key, value in common.ServerConstants.ENTRY_CHANNEL_IDS.items():
                if channel.id == value:
                    common.entry_channels[key] = channel

async def init():
    """
    Startup call helper for pygame bot
    """
    try:
        await _init()
    except Exception:
        # error happened in the first init sequence. report error to stdout/stderr
        # note that the chances of this happening are pretty slim, but you never know
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        raise

    routine.handle_console.start()
    routine.routine.start()

    if common.guild is None:
        raise RuntimeWarning(
            "Primary guild was not set. Some features of bot would not run as usual."
            " People running commands via DMs might face some problems"
        )

def format_entries_message(msg: discord.Message, entry_type: str):
    """
    Formats an entries message to be reposted in discussion channel
    """
    if entry_type != "":
        title = f"New {entry_type.lower()} in #{common.ZERO_SPACE}{common.entry_channels[entry_type].name}"
    else:
        title = ""

    attachments = ""
    if msg.attachments:
        for i, attachment in enumerate(msg.attachments):
            attachments += f" • [Link {i + 1}]({attachment.url})\n"
    else:
        attachments = "No attachments"

    desc = msg.content if msg.content else "No description provided."

    fields = [
        ["**Posted by**", msg.author.mention, True],
        ["**Original msg.**", f"[View]({msg.jump_url})", True],
        ["**Attachments**", attachments, True],
        ["**Description**", desc, True],
    ]
    return title, fields

def entry_message_validity_check(
    message: discord.Message, min_chars=32, max_chars=float("inf")
):
    """Checks if a message posted in a showcase channel for projects has the right format.

    Returns:
        bool: True/False
    """
    url_regex_pattern = r"(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])"
    # https://stackoverflow.com/a/6041965/14826938

    search_obj = re.search(
        url_regex_pattern, (message.content if message.content else "")
    )
    link_in_msg = bool(search_obj)
    first_link_str = search_obj.group() if link_in_msg else ""

    if (
        message.content
        and (link_in_msg and len(message.content) > len(first_link_str))
        and min_chars < len(message.content) < max_chars
    ):
        return True

    elif (message.content or message.reference) and message.attachments:
        return True

    return False

async def delete_bad_entry_and_warning(
    entry_msg: discord.Message, warn_msg: discord.Message, delay: float = 0.0
):
    """A function to pardon a bad entry message with a grace period. If this coroutine is not cancelled during the
    grace period specified in `delay` in seconds, it will delete both `entry_msg` and `warn_msg`, if possible.

    Args:
        entry_msg (discord.Message): [description]
        warn_msg (discord.Message): [description]
        delay (float, optional): [description]. Defaults to 0..
    """
    try:
        await asyncio.sleep(delay)  # allow cancelling during delay
    except asyncio.CancelledError:
        return

    try:
        await warn_msg.edit("Sorry, but your showcase entry will now be deleted.")
        await asyncio.sleep(0)
    except asyncio.CancelledError:
        pass

    finally:
        await entry_msg.delete()
        await warn_msg.delete()

async def member_join(member: discord.Member):
    """
    This function handles the greet message when a new member joins
    """
    if common.TEST_MODE or member.bot or common.GENERIC:
        # Do not greet people in test mode, or if a bot joins
        return

    greet = random.choice(common.BOT_WELCOME_MSG["greet"])
    check = random.choice(common.BOT_WELCOME_MSG["check"])

    grab = random.choice(common.BOT_WELCOME_MSG["grab"])
    end = random.choice(common.BOT_WELCOME_MSG["end"])

    # This function is called right when a member joins, even before the member
    # finishes the join screening. So we wait for that to happen and then send
    # the message. Wait for a maximum of six hours.
    for _ in range(10800):
        await asyncio.sleep(2)

        if not member.pending:
            # Don't use embed here, because pings would not work
            await common.arrivals_channel.send(
                f"{greet} {member.mention}! {check} "
                + f"{common.guide_channel.mention}{grab} "
                + f"{common.roles_channel.mention}{end}"
            )
            # new member joined, yaayyy, snek is happi
            await emotion.update("happy", 20)
            return

async def clean_db_member(member: discord.Member):
    """
    This function silently removes users from database messages
    """
    for table_name in ("stream", "reminders", "clock"):
        async with db.DiscordDB(table_name) as db_obj:
            data = db_obj.get({})
            if member.id in data:
                data.pop(member)
                db_obj.write(data)

async def message_delete(msg: discord.Message):
    """
    This function is called for every message deleted by user.
    """
    if msg.id in common.cmd_logs.keys():
        del common.cmd_logs[msg.id]

    elif msg.author.id == common.bot.user.id:
        for log in common.cmd_logs.keys():
            if common.cmd_logs[log].id is not None:
                if common.cmd_logs[log].id == msg.id:
                    del common.cmd_logs[log]
                    return

    if common.GENERIC or common.TEST_MODE:
        return

    if msg.channel in common.entry_channels.values():
        if (
            msg.channel.id == common.ServerConstants.ENTRY_CHANNEL_IDS["showcase"]
            and msg.id in common.entry_message_deletion_dict
        ):  # for case where user deletes their bad entry by themselves
            deletion_data_list = common.entry_message_deletion_dict[msg.id]
            deletion_task = deletion_data_list[0]
            if not deletion_task.done():
                deletion_task.cancel()
                try:
                    warn_msg = await msg.channel.fetch_message(
                        deletion_data_list[1]
                    )  # warning and entry message were already deleted
                    await warn_msg.delete()
                except discord.NotFound:
                    pass

            del common.entry_message_deletion_dict[msg.id]

        async for message in common.entries_discussion_channel.history(
            around=msg.created_at, limit=5
        ):
            try:
                link = message.embeds[0].fields[1].value
                if not isinstance(link, str):
                    continue

                if int(link.split("/")[6][:-1]) == msg.id:
                    await message.delete()
                    break

            except (IndexError, AttributeError):
                pass

async def message_edit(old: discord.Message, new: discord.Message):
    """
    This function is called for every message edited by user.
    """
    if new.content.startswith(common.PREFIX):
        try:
            if new.id in common.cmd_logs.keys():
                await commands.handle(new, common.cmd_logs[new.id])
        except discord.HTTPException:
            pass

    if common.GENERIC or common.TEST_MODE:
        return

    if new.channel in common.entry_channels.values():
        embed_repost_edited = False
        if new.channel.id == common.ServerConstants.ENTRY_CHANNEL_IDS["showcase"]:
            if not entry_message_validity_check(new):
                if new.id in common.entry_message_deletion_dict:
                    deletion_data_list = common.entry_message_deletion_dict[new.id]
                    deletion_task = deletion_data_list[0]
                    if deletion_task.done():
                        del common.entry_message_deletion_dict[new.id]
                    else:
                        try:
                            deletion_task.cancel()  # try to cancel deletion after noticing edit by sender
                            warn_msg = await new.channel.fetch_message(
                                deletion_data_list[1]
                            )
                            deletion_datetime = (
                                datetime.datetime.utcnow()
                                + datetime.timedelta(minutes=2)
                            )
                            await warn_msg.edit(
                                content=(
                                    "I noticed your edit, but: Your entry message must contain an attachment or a (Discord recognized) link to be valid."
                                    " If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."
                                    f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."
                                    f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."
                                    " If no changes are made, your entry message will be"
                                    f" deleted {utils.format_datetime(deletion_datetime, tformat='R')}."
                                )
                            )
                            common.entry_message_deletion_dict[new.id] = [
                                asyncio.create_task(
                                    delete_bad_entry_and_warning(
                                        new, warn_msg, delay=120
                                    )
                                ),
                                warn_msg.id,
                            ]
                        except discord.NotFound:  # cancelling didn't work, warning and entry message were already deleted
                            del common.entry_message_deletion_dict[new.id]

                else:  # an edit led to an invalid entry message from a valid one
                    deletion_datetime = datetime.datetime.utcnow() + datetime.timedelta(
                        minutes=2
                    )
                    warn_msg = await new.reply(
                        "Your entry message must contain an attachment or a (Discord recognized) link to be valid."
                        " If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."
                        f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."
                        f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."
                        " If no changes are made, your entry message will be"
                        f" deleted {utils.format_datetime(deletion_datetime, tformat='R')}."
                    )

                    common.entry_message_deletion_dict[new.id] = [
                        asyncio.create_task(
                            delete_bad_entry_and_warning(new, warn_msg, delay=120)
                        ),
                        warn_msg.id,
                    ]
                return

            elif (
                entry_message_validity_check(new)
                and new.id in common.entry_message_deletion_dict
            ):  # an invalid entry was corrected
                deletion_data_list = common.entry_message_deletion_dict[new.id]
                deletion_task = deletion_data_list[0]
                if not deletion_task.done():  # too late to do anything
                    try:
                        deletion_task.cancel()  # try to cancel deletion after noticing valid edit by sender
                        warn_msg = await new.channel.fetch_message(
                            deletion_data_list[1]
                        )
                        await warn_msg.delete()
                    except discord.NotFound:  # cancelling didn't work, warning and entry message were already deleted
                        pass
                del common.entry_message_deletion_dict[new.id]

        async for message in common.entries_discussion_channel.history(
            around=old.created_at, limit=5
        ):
            try:
                embed = message.embeds[0]
                link = embed.fields[1].value
                if not isinstance(link, str):
                    continue

                if int(link.split("/")[6][:-1]) == new.id:
                    _, fields = format_entries_message(new, "")
                    await embed_utils.edit(message, embed=embed, fields=fields)
                    embed_repost_edited = True
                    break

            except (IndexError, AttributeError):
                pass

        if not embed_repost_edited:
            if (datetime.datetime.utcnow() - old.created_at) < datetime.timedelta(
                minutes=5
            ):  # for new, recently corrected entry messages
                entry_type = "showcase"
                color = 0xFF8800

                title, fields = format_entries_message(new, entry_type)
                await embed_utils.send(
                    common.entries_discussion_channel,
                    title=title,
                    color=color,
                    fields=fields,
                )

async def raw_reaction_add(payload: discord.RawReactionActionEvent):
    """
    Helper to handle a raw reaction added on discord
    """

    # Try to fetch channel without API call first
    channel = common.bot.get_channel(payload.channel_id)
    if channel is None:
        try:
            channel = await common.bot.fetch_channel(payload.channel_id)
        except discord.HTTPException:
            return

    if not isinstance(channel, discord.TextChannel):
        return

    try:
        msg: discord.Message = await channel.fetch_message(payload.message_id)
    except discord.HTTPException:
        return

    if not msg.embeds or common.UNIQUE_POLL_MSG not in str(msg.embeds[0].footer.text):
        return

    for reaction in msg.reactions:
        async for user in reaction.users():
            if user.id == payload.user_id and not utils.is_emoji_equal(
                payload.emoji, reaction.emoji
            ):
                await reaction.remove(user)

async def handle_message(msg: discord.Message):
    """
    Handle a message posted by user
    """
    if msg.type == discord.MessageType.premium_guild_subscription:
        await emotion.server_boost(msg)

    if msg.content.startswith(common.PREFIX):
        ret = await commands.handle(msg)
        if ret is not None:
            common.cmd_logs[msg.id] = ret

        if len(common.cmd_logs) > 100:
            del common.cmd_logs[list(common.cmd_logs.keys())[0]]

        await emotion.update("bored", -10)

    elif not common.TEST_MODE:
        await emotion.check_bonk(msg)

        # Check for these specific messages, do not try to generalise, because we do not
        # want the bot spamming the bydariogamer quote
        # no_mentions = discord.AllowedMentions.none()
        # if unidecode.unidecode(msg.content.lower()) in common.DEAD_CHAT_TRIGGERS:
        #     # ded chat makes snek sad
        #     await msg.channel.send(
        #         "good." if await emotion.get("anger") >= 60 else common.BYDARIO_QUOTE,
        #         allowed_mentions=no_mentions,
        #     )
        #     await emotion.update("happy", -8)

        if common.GENERIC:
            return

        if msg.channel in common.entry_channels.values():

            if msg.channel.id == common.ServerConstants.ENTRY_CHANNEL_IDS["showcase"]:
                if not entry_message_validity_check(msg):
                    deletion_datetime = datetime.datetime.utcnow() + datetime.timedelta(
                        minutes=2
                    )
                    warn_msg = await msg.reply(
                        "Your entry message must contain an attachment or a (Discord recognized) link to be valid."
                        " If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."
                        f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."
                        f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."
                        " If no changes are made, your entry message will be"
                        f" deleted {utils.format_datetime(deletion_datetime, tformat='R')}."
                    )
                    common.entry_message_deletion_dict[msg.id] = [
                        asyncio.create_task(
                            delete_bad_entry_and_warning(msg, warn_msg, delay=120)
                        ),
                        warn_msg.id,
                    ]
                    return

                entry_type = "showcase"
                color = 0xFF8800
            else:
                entry_type = "resource"
                color = 0x0000AA

            title, fields = format_entries_message(msg, entry_type)
            await embed_utils.send(
                common.entries_discussion_channel,
                title=title,
                color=color,
                fields=fields,
            )
        elif (
            random.random() < await emotion.get("happy") / 200
            or msg.author.id == 683852333293109269
        ):
            await emotion.dad_joke(msg)

def cleanup(*_):
    """
    Call cleanup functions
    """
    common.bot.loop.run_until_complete(db.quit())
    common.bot.loop.run_until_complete(common.bot.close())
    common.bot.loop.close()

def run():
    """
    Does what discord.Client.run does, except, handles custom cleanup functions
    and pygame init
    """

    os.environ["SDL_VIDEODRIVER"] = "dummy"
    pygame.init()  # pylint: disable=no-member
    common.window = pygame.display.set_mode((1, 1))

    # use signal.signal to setup SIGTERM signal handler, runs after event loop
    # closes
    signal.signal(signal.SIGTERM, cleanup)

    try:
        common.bot.loop.run_until_complete(common.bot.start(common.TOKEN))

    except KeyboardInterrupt:
        # Silence keyboard interrupt traceback (it contains no useful info)
        pass

    finally:
        cleanup()


from siklu_api import *

if __name__ == '__main__':

    unit = SikluUnit('31.168.34.109', 'admin', 'admin', debug=False)
    unit.connect()
    for i in range(100):
        reply = ShowRSSI(unit).parse()
        rssi = int(reply[0])
        # ts = time.strftime('%d-%m-%Y %H:%M:%S.%f', time.localtime())
        ts = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
        print(f'{ts},{rssi}')


#!/usr/bin/env python
import rospy, math, time, csv
import numpy as np
from sensor_msgs.msg import LaserScan
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point

#This code was designed to track a single moving person, walking in a static environment
#using a Hokuyo lidar.

#In order for this method of tracking to work, the lidar must first scan the room without
#any movement to set the baseline for what isn't considered movement. After the first frame
#is acquired it will be used to visualize any change(ie the person being tracked)

#Rostopics
#Subscribed: /scan (LaserScan)
#Publishing: /visualization_marker (Marker)
#			 /visualization_marker2 (Marker)

numMsgs=0				#Keeps track of how many scan messages have been received
f1=[]					#The first scan frame on startup

#Thresholds
#!!!These values worked for our application but may need modified for yours!!!
movementThreshold=0.5	#How far should a point be from where it was in frame 1 before its considered a moving object (Helps filter out sensor noise)
legsThreshold=0.6		#How far away from the average of all moving points should a persons legs be (Helps filter out sensor noise)

#Publishers
pubMarker = rospy.Publisher('visualization_marker',Marker, queue_size=1000)#Publisher for moving points
pubMarker2 = rospy.Publisher('visualization_marker2',Marker, queue_size=1000)#Publisher for average of moving points

#Average moving position points
pt1=Point()
pt2=Point()

#Used to calculate speed of moving person
moveCnt=0
start=0
end=0
speedTotal=0
prevSpeed=0

#Used to calculate average frequency of recorded data
totalTimeBtwn=0
avgTimeBtwn=0
timeBtwnCnt=0

#CSV file for recording lidar data into
csvNumber='3'
outfile=open('lidarData' + csvNumber + '.csv','w')
writer = csv.writer(outfile)

#Input:  Point(), Point()
#		pt1 = The first Point()
#		pt2 = The second Point()
#Output: Distance from pt1 to pt2
def distanceTo(pt1,pt2):

	return math.hypot(pt1.x-pt2.x,pt1.y-pt2.y)

#Input: int, int, int, int, dbl, dbl
#		markerId = integer to represent a unique Marker()
#		r = integer to represent red color
#		g = integer to represent green color
#		b = integer to represent blue color
#		x = double to represent x position
#		y = integer to represent y position
#Output: Marker()
def makeMarker(markerId,r,g,b,x,y):
	marker = Marker()
	marker.header.frame_id = "laser"
	marker.lifetime = rospy.Duration(0.5)
	marker.id=markerId
	marker.type = marker.SPHERE
	marker.action = marker.ADD
	marker.scale.x = 0.1
	marker.scale.y = 0.1
	marker.scale.z = 0.1
	marker.color.a = 1.0
	marker.color.r = r
	marker.color.g = g
	marker.color.b = b
	marker.pose.position.x=x
	marker.pose.position.y=y
	return marker

# Input: int, int, int, int, Points[]
# 		markerId = integer to represent a unique Marker()
# 		r = integer to represent red color
# 		g = integer to represent green color
# 		b = integer to represent blue color
# 		pts = list of Points() to represent x and y positions
# Output: Marker()
def makeSphereList(markerId,r,g,b,pts):
	marker = Marker()
	marker.type = marker.SPHERE_LIST
	marker.action = marker.ADD
	marker.header.frame_id = "laser"
	marker.id=markerId
	marker.scale.x = 0.1
	marker.scale.y = 0.1
	marker.scale.z = 0.1
	marker.color.r = r
	marker.color.g = g
	marker.color.b = b
	marker.color.a = 1.0
	marker.lifetime = rospy.Duration(0.5)
	marker.points=pts
	return marker

#Input: LaserScan
#		data = LaserScan Data
#Output: None
def callback(data):
	global numMsgs, f1, movementThreshold, pubMarker, pubMarker2, moveCnt, pt1, pt2, start, end, speedTotal, totalTimeBtwn, timeBtwnCnt, writer ,legsThreshold, prevSpeed
	numMsgs+=1	 								#Keeps track of how many scan messages have been received
	if(numMsgs==1):
		f1=data.ranges 							#Grab the first frame on startup to use
	else:
		f2=data.ranges 							#Grab frames to compare to f1 to search for movement
		i=0
		positionsXY=[] 							#Points of movement in scan
		xTot=0 									#Total of all x movement positions
		yTot=0 									#Total of all y movement positions
		k=-1.65806281567 						#Lowest radian angle measurement of lidar
		for i in range(0,1520): 				#1521 is len(data.ranges)
			if(abs(f2[i]-f1[i])>movementThreshold):
				movePoint=Point() 				#Represent distance and angle as a point
				movePoint.x=f2[i]*(math.cos(k)) #Calculate x position
				movePoint.y=f2[i]*(math.sin(k))	#Calculate y position
				xTot+=movePoint.x
				yTot+=movePoint.y
				positionsXY.append(movePoint)
			k+=0.00218022723 					#Lidar range = -1.65806281567 to 1.65806281567
							 					#k = 2*1.65806281567/len(data.ranges)
		if(len(positionsXY)>0):					#Make sure that something is moving in the frame
			moveCnt+=1

			#Calculate the speed of the person in the frame
			#Take average of all moving points as the position of the person
			#Current average position - Previous average position
			#End time - Start time to determine how fast the distance between positions was traveled
			if(moveCnt==1):
				pt1.x = xTot/len(positionsXY)
				pt1.y = yTot/len(positionsXY)
				start=time.time()
				prevSpeed=0
			else:
				pt2.x=xTot/len(positionsXY)
				pt2.y=yTot/len(positionsXY)
				end=time.time()
				timeBtwn=end-start
				distanceBtwn=distanceTo(pt1,pt2)
				speed=distanceBtwn/timeBtwn
				print([end,(speed-prevSpeed)/timeBtwn])
				totalTimeBtwn+=timeBtwn
				timeBtwnCnt+=1
				speedTotal+=speed
				avgSpeed=(speedTotal/timeBtwnCnt)
				if(abs(speed-avgSpeed)<5): #Filter out large spikes in speed
					writer.writerow([end,math.sqrt(((speed-prevSpeed)/timeBtwn)**2)])
				pt1.x=pt2.x
				pt1.y=pt2.y
				start=time.time()
				prevSpeed=speed
			pubMarker2.publish(makeMarker(1,1,1,1,pt1.x,pt1.y))

			# Calculate what movement should be classified as
			# the legs based on the distance a moving point is
			# from the average movement point
			j=Point()
			legs=[]
			for j in positionsXY:
				if(distanceTo(j,pt1)<legsThreshold):
					legs.append(j)
			pubMarker.publish(makeSphereList(4,0,0,1,legs))

#Initialize node and subscriber
def mark():
	rospy.init_node('mark', anonymous=True)
	rospy.Subscriber('/scan', LaserScan, callback)
	rospy.spin()

	#Write what the average recording frequency was for the lidar data collected to a CSV (Used for syncronization)
	f=open('lidarFreq' + csvNumber + '.csv','w')
	w = csv.writer(f)
	w.writerow([totalTimeBtwn/timeBtwnCnt])

if __name__ == '__main__':
    mark()


auth_Creds = {"admin": "1234"}

async def VerifyRequest(user, pswd):
    if not((user in auth_Creds) and (auth_Creds[user] == pswd)):
        return {
            "status" : 401,
            "message" : "401 Unauthorized"
            }
    else:
        return {
            "status" : 200,
            "message" : "Access allowed"
            }


import __init__
import torch
from operations import *

class Cell(nn.Module):
    def __init__(self, genotype, C_prev_prev, C_prev, C):
        super(Cell, self).__init__()
        self.preprocess0 = MLP([C_prev_prev, C], 'relu', 'batch', bias=False)
        self.preprocess1 = MLP([C_prev, C], 'relu', 'batch', bias=False)

        op_names, indices = zip(*genotype.normal)
        concat = genotype.normal_concat
        self._compile(C, op_names, indices, concat)

    def _compile(self, C, op_names, indices, concat):
        assert len(op_names) == len(indices)
        self._steps = len(op_names) // 2
        self._concat = concat
        self.multiplier = len(concat)

        self._ops = nn.ModuleList()
        for name, index in zip(op_names, indices):
            op = OPS[name](C, 1, True)
            self._ops += [op]
        self._indices = indices

    def forward(self, s0, s1, edge_index, drop_prob):
        s0 = self.preprocess0(s0)
        s1 = self.preprocess1(s1)

        states = [s0, s1]
        for i in range(self._steps):
            h1 = states[self._indices[2 * i]]
            h2 = states[self._indices[2 * i + 1]]
            op1 = self._ops[2 * i]
            op2 = self._ops[2 * i + 1]
            h1 = op1(h1, edge_index)
            h2 = op2(h2, edge_index)
            if self.training and drop_prob > 0.:
                if not isinstance(op1, Identity):
                    h1 = drop_path(h1, drop_prob)
                if not isinstance(op2, Identity):
                    h2 = drop_path(h2, drop_prob)
            s = h1 + h2
            states += [s]
        return torch.cat([states[i] for i in self._concat], dim=1)

class AuxiliaryHeadPPI(nn.Module):

    def __init__(self, C, num_classes):
        super(AuxiliaryHeadPPI, self).__init__()
        self.features = nn.Sequential(
            MLP([C, 128, 768], 'relu', 'batch', bias=False)

        )
        self.classifier = nn.Linear(768, num_classes)

    def forward(self, x):
        x = self.features(x)
        x = self.classifier(x)
        return x

class NetworkPPI(nn.Module):

    def __init__(self, C, num_classes, layers, auxiliary, genotype, stem_multiplier=3, in_channels=3):
        super(NetworkPPI, self).__init__()
        self._layers = layers
        self._auxiliary = auxiliary
        self._in_channels = in_channels
        self.drop_path_prob = 0.

        C_curr = stem_multiplier * C
        self.stem = nn.Sequential(
            MLP([in_channels, C_curr], None, 'batch', bias=False),
        )

        C_prev_prev, C_prev, C_curr = C_curr, C_curr, C
        self.cells = nn.ModuleList()
        for i in range(layers):
            cell = Cell(genotype, C_prev_prev, C_prev, C_curr)
            self.cells += [cell]
            C_prev_prev, C_prev = C_prev, cell.multiplier * C_curr
            if i == 2 * layers // 3:
                C_to_auxiliary = C_prev

        if auxiliary:
            self.auxiliary_head = AuxiliaryHeadPPI(C_to_auxiliary, num_classes)
        self.global_pooling = nn.AdaptiveAvgPool1d(1)
        self.classifier = nn.Linear(C_prev + 1, num_classes)

    def forward(self, input):
        logits_aux = None
        x, edge_index = input.x, input.edge_index
        s0 = s1 = self.stem(x)
        for i, cell in enumerate(self.cells):
            s0, s1 = s1, cell(s0, s1, edge_index, self.drop_path_prob)
            if i == 2 * self._layers // 3:
                if self._auxiliary and self.training:
                    logits_aux = self.auxiliary_head(s1)
        out = self.global_pooling(s1.unsqueeze(0)).squeeze(0)
        logits = self.classifier(torch.cat((out, s1), dim=1))
        return logits, logits_aux

def drop_path(x, drop_prob):
    if drop_prob > 0.:
        keep_prob = 1. - drop_prob
        mask = torch.cuda.FloatTensor(x.size(0), 1).bernoulli_(keep_prob)
        x.div_(keep_prob)
        x.mul_(mask)
    return x


"""
【问题描述】
输入一组整数，从小到大排序后，输出排序结果。
【输入形式】
一行。一组用空格隔开的整数。
【输出形式】
一行。一组用一个空格隔开的整数，从小到大排列。
【样例输入】
9 8 7 6
【样例输出】
6 7 8 9
【提示】
用列表的sort方法。
"""
num = input().split()
list = []
for n in num:
    list.append(int(n))
list.sort()
print(" ".join(str(i) for i in list))


from functools import partial

import torch
import torch.nn as nn
from timm.models.helpers import build_model_with_cfg
from timm.models.layers import DropPath, trunc_normal_
from timm.models.registry import register_model
from timm.models.vision_transformer import Mlp, PatchEmbed
from timm.models.vision_transformer_hybrid import HybridEmbed

from ..layers import build_rpe, get_rpe_config

default_cfgs = {
    'deit_small_patch16_224_ctx_product_50_shared_qkv': {
        'url':
        'https://github.com/wkcn/iRPE-model-zoo/releases/download/1.0/deit_small_patch16_224_ctx_product_50_shared_qkv.pth'  # noqa
    },
    'deit_base_patch16_224_ctx_product_50_shared_qkv': {
        'url':
        'https://github.com/wkcn/iRPE-model-zoo/releases/download/1.0/deit_base_patch16_224_ctx_product_50_shared_qkv.pth'  # noqa
    }
}

class RPEAttention(nn.Module):
    """Attention with image relative position encoding."""
    def __init__(self,
                 dim,
                 num_heads=8,
                 qkv_bias=False,
                 qk_scale=None,
                 attn_drop=0.,
                 proj_drop=0.,
                 rpe_config=None):
        super().__init__()
        self.num_heads = num_heads
        head_dim = dim // num_heads
        # NOTE scale factor was wrong in my original version,
        # can set manually to be compat with prev weights
        self.scale = qk_scale or head_dim**-0.5

        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

        # image relative position encoding
        self.rpe_q, self.rpe_k, self.rpe_v = \
            build_rpe(rpe_config,
                      head_dim=head_dim,
                      num_heads=num_heads)

    def forward(self, x):
        B, N, C = x.shape
        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads,
                                  C // self.num_heads).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[
            2]  # make torchscript happy (cannot use tensor as tuple)

        q *= self.scale

        attn = (q @ k.transpose(-2, -1))

        # image relative position on keys
        if self.rpe_k is not None:
            attn += self.rpe_k(q)

        # image relative position on queries
        if self.rpe_q is not None:
            attn += self.rpe_q(k * self.scale).transpose(2, 3)

        attn = attn.softmax(dim=-1)
        attn = self.attn_drop(attn)

        out = attn @ v

        # image relative position on values
        if self.rpe_v is not None:
            out += self.rpe_v(attn)

        x = out.transpose(1, 2).reshape(B, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x

class RPEBlock(nn.Module):
    def __init__(self,
                 dim,
                 num_heads,
                 mlp_ratio=4.,
                 qkv_bias=False,
                 qk_scale=None,
                 drop=0.,
                 attn_drop=0.,
                 drop_path=0.,
                 act_layer=nn.GELU,
                 norm_layer=nn.LayerNorm,
                 rpe_config=None):
        super().__init__()
        self.norm1 = norm_layer(dim)
        self.attn = RPEAttention(dim,
                                 num_heads=num_heads,
                                 qkv_bias=qkv_bias,
                                 qk_scale=qk_scale,
                                 attn_drop=attn_drop,
                                 proj_drop=drop,
                                 rpe_config=rpe_config)
        # NOTE: drop path for stochastic depth,
        # we shall see if this is better than dropout here
        self.drop_path = DropPath(
            drop_path) if drop_path > 0. else nn.Identity()
        self.norm2 = norm_layer(dim)
        mlp_hidden_dim = int(dim * mlp_ratio)
        self.mlp = Mlp(in_features=dim,
                       hidden_features=mlp_hidden_dim,
                       act_layer=act_layer,
                       drop=drop)

    def forward(self, x):
        x = x + self.drop_path(self.attn(self.norm1(x)))
        x = x + self.drop_path(self.mlp(self.norm2(x)))
        return x

class VisionTransformer(nn.Module):
    """Vision Transformer with support for patch or hybrid CNN input stage and
    image relative position encoding."""
    def __init__(self,
                 img_size=224,
                 patch_size=16,
                 in_chans=3,
                 num_classes=1000,
                 embed_dim=768,
                 depth=12,
                 num_heads=12,
                 mlp_ratio=4.,
                 qkv_bias=False,
                 qk_scale=None,
                 drop_rate=0.,
                 attn_drop_rate=0.,
                 drop_path_rate=0.,
                 hybrid_backbone=None,
                 norm_layer=nn.LayerNorm,
                 rpe_config=None):
        super().__init__()
        self.num_classes = num_classes
        # num_features for consistency with other models
        self.num_features = self.embed_dim = embed_dim

        if hybrid_backbone is not None:
            self.patch_embed = HybridEmbed(hybrid_backbone,
                                           img_size=img_size,
                                           in_chans=in_chans,
                                           embed_dim=embed_dim)
        else:
            self.patch_embed = PatchEmbed(img_size=img_size,
                                          patch_size=patch_size,
                                          in_chans=in_chans,
                                          embed_dim=embed_dim)
        num_patches = self.patch_embed.num_patches

        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
        self.pos_embed = nn.Parameter(
            torch.zeros(1, num_patches + 1, embed_dim))
        self.pos_drop = nn.Dropout(p=drop_rate)

        # stochastic depth decay rule
        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
        self.blocks = nn.ModuleList([
            RPEBlock(dim=embed_dim,
                     num_heads=num_heads,
                     mlp_ratio=mlp_ratio,
                     qkv_bias=qkv_bias,
                     qk_scale=qk_scale,
                     drop=drop_rate,
                     attn_drop=attn_drop_rate,
                     drop_path=dpr[i],
                     norm_layer=norm_layer,
                     rpe_config=rpe_config) for i in range(depth)
        ])
        self.norm = norm_layer(embed_dim)

        # NOTE as per official impl, we could have a
        # pre-logits representation dense layer + tanh here
        # self.repr = nn.Linear(embed_dim, representation_size)
        # self.repr_act = nn.Tanh()

        # Classifier head
        self.head = nn.Linear(
            embed_dim, num_classes) if num_classes > 0 else nn.Identity()

        trunc_normal_(self.pos_embed, std=.02)
        trunc_normal_(self.cls_token, std=.02)
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear):
            trunc_normal_(m.weight, std=.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.LayerNorm):
            nn.init.constant_(m.bias, 0)
            nn.init.constant_(m.weight, 1.0)

    @torch.jit.ignore
    def no_weight_decay(self):
        return {'pos_embed', 'cls_token'}

    def get_classifier(self):
        return self.head

    def reset_classifier(self, num_classes, global_pool=''):
        self.num_classes = num_classes
        self.head = nn.Linear(
            self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()

    def forward_features(self, x):
        B = x.shape[0]
        x = self.patch_embed(x)

        cls_tokens = self.cls_token.expand(
            B, -1, -1)  # stole cls_tokens impl from Phil Wang, thanks
        x = torch.cat((cls_tokens, x), dim=1)
        x = x + self.pos_embed
        x = self.pos_drop(x)

        for blk in self.blocks:
            x = blk(x)

        x = self.norm(x)
        return x[:, 0]

    def forward(self, x):
        x = self.forward_features(x)
        x = self.head(x)
        return x

def _filter_fn(state_dict):
    state_dict = state_dict['model']
    return state_dict

def _irpe(arch, pretrained, **kwargs):
    model = build_model_with_cfg(VisionTransformer,
                                 arch,
                                 pretrained=pretrained,
                                 default_cfg=default_cfgs[arch],
                                 pretrained_filter_fn=_filter_fn,
                                 **kwargs)
    return model

@register_model
def deit_small_patch16_224_ctx_product_50_shared_qkv(pretrained=False,
                                                     **kwargs):
    rpe_config = get_rpe_config(
        ratio=1.9,
        method='product',
        mode='ctx',
        shared_head=True,
        skip=1,
        rpe_on='qkv',
    )
    return _irpe('deit_small_patch16_224_ctx_product_50_shared_qkv',
                 pretrained=pretrained,
                 rpe_config=rpe_config,
                 patch_size=16,
                 embed_dim=384,
                 depth=12,
                 num_heads=6,
                 mlp_ratio=4,
                 qkv_bias=True,
                 norm_layer=partial(nn.LayerNorm, eps=1e-6),
                 **kwargs)

@register_model
def deit_base_patch16_224_ctx_product_50_shared_qkv(pretrained=False,
                                                    **kwargs):
    rpe_config = get_rpe_config(
        ratio=1.9,
        method='product',
        mode='ctx',
        shared_head=True,
        skip=1,
        rpe_on='qkv',
    )
    return _irpe('deit_base_patch16_224_ctx_product_50_shared_qkv',
                 pretrained=pretrained,
                 rpe_config=rpe_config,
                 patch_size=16,
                 embed_dim=768,
                 depth=12,
                 num_heads=12,
                 mlp_ratio=4,
                 qkv_bias=True,
                 norm_layer=partial(nn.LayerNorm, eps=1e-6),
                 **kwargs)


from numba import njit
import numpy as np
from vectorbt.portfolio import nb as portfolio_nb
from vectorbt.portfolio.enums import SizeType

@njit
def order_func_nb(c, size, price, commperc, slippage):
    """Place an order (= element within group and row)."""
    # Get column index within group (if group starts at column 58 and current column is 59,
    # the column within group is 1, which can be used to get size)
    group_col = c.col - c.from_col
    return portfolio_nb.order_nb(
        size=size[group_col],
        price=price[c.i, c.col],
        size_type=SizeType.TargetAmount,
        fees=commperc,
        slippage=slippage,
        lock_cash=False,
        log=True,
    )


import numpy as np
import pandas as pd
from sklearn import *
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from reportlab import platypus
from reportlab.lib.styles import ParagraphStyle as PS
from reportlab.platypus import SimpleDocTemplate

import sqlite3
con = sqlite3.connect('concrete1')
training_data = np.genfromtxt('conc.csv', delimiter=',')
inputs = training_data[:,:-1]
outputs = training_data[:, -1]
training_inputs = inputs[:1000]
training_outputs = outputs[:1000]
testing_inputs = inputs[1000:]
testing_outputs = outputs[1000:]
classifier = DecisionTreeClassifier()
classifier.fit(training_inputs, training_outputs)
with con:
  cur = con.cursor()
  cur.execute('SELECT * FROM mainingr');
  result1 = cur.fetchall()
  for row in result1:
    s2 = int(row[0])
    s3 = int(row[1])
    s4 = int(row[2])
    s5 = int(row[3])
  cur.execute('SELECT * FROM otheringr');
  result2 = cur.fetchall()
  for row in result2:
    s1 = float(row[0])
    s6 = float(row[1])
    s7 = float(row[2])
    s8 = int(row[3])
result = str(" ")
testSet = [[s1,s2,s3,s4,s5,s6,s7,s8]]
test = pd.DataFrame(testSet)
predictions = classifier.predict(test)
if (int(predictions) ==0):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 1 to 10 MPa')+ "
"
elif (int(predictions) ==1):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 11 to 20 MPa')+ "
"
elif (int(predictions) ==2):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 21 to 30 MPa')+ "
"
elif (int(predictions) ==3):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 31 to 40 MPa')+ "
"
elif (int(predictions) ==4):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 41 to 50 MPa')+ "
"
elif (int(predictions) ==5):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 51 to 60 MPa')+ "
"
elif (int(predictions) ==6):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 61 to 70 MPa')+ "
"
elif (int(predictions) ==7):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 71 to 80 MPa')+ "
"
elif (int(predictions) ==8):
   result = result + str('Predicted compressive strength range of the given concrete mix is: 81 to 90 MPa')+ "
"
else:
   result = result + str('Predicted compressive strength range of the given concrete mix is: 91 to 100 MPa')+ "
"
items = []
items.append(platypus.Paragraph(result,PS('body')))
doc = SimpleDocTemplate('concrep.pdf')
doc.multiBuild(items)
print('Concrete Compressive Strength Report Successfully Generated')


import argparse
import csv
import random
import subprocess

#classes
class Users:
	def __init__( self, name, is_playing ):
		self.name = name
		self.is_playing = is_playing

class Robots:
	def __init__( self, name, hp, attack, defense, owner ):
		self.name = name
		self.hp = hp
		self.attack = attack
		self.defense = defense
		self.owner = owner

class Games:
	def __init__( self, player1, robot1, player2, robot2, winner = None ):
		self.player1 = player1
		self.robot1 = robot1
		self.player2 = player2
		self.robot2 = robot2
		self.winner = winner

#loaders
def load_users( user_file, use_aws ):
	user_list = []
	if use_aws == "aws":
		subprocess.run([ "aws", "s3", "cp", "s3://robot-battle-files/users.txt", user_file ])
	with open( user_file, 'r' ) as f:
		readcsv = csv.reader( f, delimiter=',' )
		for row in readcsv:
			user_list.append( Users( row[0], int(row[1]) ))
	return user_list

def load_robots( robot_file, use_aws ):
	robot_list = []
	if use_aws == "aws":
		subprocess.run([ "aws", "s3", "cp", "s3://robot-battle-files/robots.txt", robot_file ])
	with open( robot_file, 'r' ) as f:
		readCSV = csv.reader( f, delimiter=',' )
		for row in readCSV:
			robot_list.append( Robots( row[0], int(row[1]), int(row[2]), int(row[3]), row[4] ))
	return robot_list

def load_games( game_file, use_aws ):
	game_list = []
	if use_aws == "aws":
		subprocess.run([ "aws", "s3", "cp", "s3://robot-battle-files/games.txt", game_file ])
	with open( game_file, 'r' ) as f:
		readCSV = csv.reader( f, delimiter=',' )
		for row in readCSV:
			game_list.append( Games( row[0], row[1], row[2], row[3], row[4] ))
	return game_list

#save to file
def save_users( user_list, out_file, use_aws ):
	output = []
	with open( out_file, 'w' ) as f:
		writer = csv.writer(f)
		for user in user_list:
			output.append( user.name )
			output.append( user.is_playing )
			writer.writerow( output )
			output.clear()
	if use_aws == "aws":
		subprocess.run([ "aws", "s3", "cp", out_file, "s3://robot-battle-files/users.txt" ])

def save_robots( robot_list, out_file, use_aws ):
	output = []
	with open( out_file, 'w' ) as f:
		writer = csv.writer(f)
		for robot in robot_list:
			output.append( robot.name )
			output.append( robot.hp )
			output.append( robot.attack )
			output.append( robot.defense )
			output.append( robot.owner )
			writer.writerow( output )
			output.clear()
	if use_aws == "aws":
		subprocess.run([ "aws", "s3", "cp", out_file, "s3://robot-battle-files/robots.txt" ])

def save_games( game_list, out_file, use_aws ):
	output = []
	with open( out_file, 'w' ) as f:
		writer = csv.writer(f)
		for game in game_list:
			output.append( game.player1 )
			output.append( game.robot1 )
			output.append( game.player2 )
			output.append( game.robot2 )
			output.append( game.winner )
			writer.writerow( output )
			output.clear()
	if use_aws == "aws":
		subprocess.run([ "aws", "s3", "cp", out_file, "s3://robot-battle-files/games.txt" ])

#commands
def show_commands():
	print( "List of commands" )
	print( "0 - exit" )
	print( "1 - play" )
	print( "2 - game history" )
	print( "3 - user history" )
	print( "4 - robot history" )
	print( "5 - user's robots" )

def game_history( game_list, fetch_type = None, name = None ):
	print( "Player1, Robot1, Player2, Robot2, Winner" )
	for game in game_list:
		to_display = False
		if ( fetch_type == "user" and ( game.player1 == name or game.player2 == name ))   \
		   or ( fetch_type == "robot" and ( game.robot1 == name or game.robot2 == name )) \
		   or ( fetch_type is None ):
			to_display = True

		if to_display:
			print( game.player1, end = ', ' )
			print( game.robot1, end = ', ' )
			print( game.player2, end = ', ' )
			print( game.robot2, end = ', ' )
			if game.winner:
				print( game.winner )
			else:
				print( "Game in Progress" )

def get_robots( robot_list, name ):
	print( "Name, HP, Attack, Defense" )
	for robot in robot_list:
		if robot.owner == name:
			print( robot.name, end = ', ' )
			print( robot.hp, end = ', ' )
			print( robot.attack, end = ', ' )
			print( robot.defense )

def play( user_list, robot_list, game_list ):

	available_user_num = []
	print( "Available users:" )
	for idx, user in enumerate( user_list ):
		if user.is_playing == 0:
			print( str( idx ) + " " + user.name )
			available_user_num.append( idx )

	p1_num = -1
	r1_num = -1
	r1_hp = -1

	is_valid_user = False
	while not is_valid_user:
		user_num = int( input( "Input User Num:" ))
		if user_num in available_user_num:
			p1_num = user_num
			user_list[p1_num].is_playing = 1
			available_user_num.remove( p1_num )
			is_valid_user = True

			p1_robot_nums = []
			print( user_list[user_num].name + "'s robots:" )
			for idx, robot in enumerate( robot_list ):
				if robot.owner == user_list[p1_num].name:
					print( str( idx ) + " " + robot.name )
					p1_robot_nums.append( idx )

			is_valid_robot = False
			while not is_valid_robot:
				robot_num = int( input( "Choose the robot num:" ))
				if robot_num in p1_robot_nums:
					r1_num = robot_num
					r1_hp = robot_list[robot_num].hp
					is_valid_robot = True
				else:
					print( "Robot Num Invalid" )

		else:
			print( "User Not Available" )

	p2_num = random.choice( available_user_num )
	user_list[p2_num].is_playing = 1

	p2_robot_nums = []
	for idx, robot in enumerate( robot_list ):
		if robot.owner == user_list[p2_num].name:
			p2_robot_nums.append( idx )

	r2_num = random.choice( p2_robot_nums )
	r2_hp = robot_list[r2_num].hp

	game_num = len( game_list )
	game_list.append( Games( user_list[p1_num].name, robot_list[r1_num].name, \
						user_list[p2_num].name, robot_list[r2_num].name,None ))

	print( "Starting Battle..." )
	print( "Player 1: " + user_list[p1_num].name )
	print( "Robot 1: " + robot_list[r1_num].name )
	print( "Player 2: " + user_list[p2_num].name )
	print( "Robot 2: " + robot_list[r2_num].name )

	player_turn = random.randint( 1, 2 )
	while r1_hp > 0 and r2_hp > 0:
		if player_turn == 1:
			print( "Player 1's turn" )
			r2_hp -= robot_list[r1_num].attack - robot_list[r2_num].defense
			print( "Damage: " + str( robot_list[r1_num].attack ) + "-" + str( robot_list[r2_num].defense ))
			player_turn = 2
		else:
			print( "Player 2's turn" )
			r1_hp -= robot_list[r2_num].attack - robot_list[r1_num].defense
			print( "Damage: " + str( robot_list[r2_num].attack ) + "-" + str( robot_list[r1_num].defense ))
			player_turn = 1

	if r1_hp > 0:
		print( "Player 1 wins" )
		game_list[game_num].winner = user_list[p1_num].name
	else:
		print( "Player 2 wins" )
		game_list[game_num].winner = user_list[p2_num].name

	user_list[p1_num].is_playing = 0
	user_list[p2_num].is_playing = 0

def main(args):
	print("Robot Battle!")

	print( "Loading Users..." )
	user_list = load_users( args.user_file, args.use_aws )

	print( "Loading Robots..." )
	robot_list = load_robots( args.robot_file, args.use_aws )

	print( "Loading Games History..." )
	game_list = load_games( args.game_file, args.use_aws )

	show_commands()
	command = input( "Input command: " )
	while command != "0":
		if command == "1":
			play( user_list, robot_list, game_list)
		elif command == "2":
			game_history( game_list )
		elif command == "3":
			name = input( "User Name: " )
			game_history( game_list, "user", name )
		elif command == "4":
			name = input ( "Robot Name: " )
			game_history( game_list, "robot", name )
		elif command == "5":
			name = input ( "User Name: " )
			get_robots( robot_list, name )

		print()
		show_commands()
		command = input( "Input command: " )

	print( "Saving Users..." )
	save_users( user_list, args.user_file, args.use_aws )

	print( "Saving Robots..." )
	save_robots( robot_list, args.robot_file, args.use_aws )

	print( "Saving Games..." )
	save_games( game_list, args.game_file, args.use_aws )

if __name__ == "__main__":
	parser = argparse.ArgumentParser( description = "Robot Battle" )
	parser.add_argument( '--user_file', dest = "user_file", required = True )
	parser.add_argument( '--robot_file', dest = "robot_file", required = True )
	parser.add_argument( '--game_file', dest = "game_file", required = True )
	parser.add_argument( '--run_on', dest = "use_aws", default = "cmd" )

	args = parser.parse_args()

	main(args)


str1 = "千山鸟飞绝"
str2 = "万锦人踪灭"
str3 = "孤舟蓑笠翁"
str4 = "独钓寒江雪"
varse = [list(str1), list(str2), list(str3), list(str4)]
print("\n-- 横板 --\n")
for i in range(4):
    for j in range(5):
        if j == 4:
            print(varse[i][j])
        else:
            print(varse[i][j], end="")

varse.reverse()
print("\n-- 竖版 --\n")
for i in range(5):
    for j in range(4):
        if j == 3:
            print(varse[j][i])
        else:
            print(varse[j][i], end="")


#!/usr/bin/env python3

"""l_crypto.py: define CryptoTool for cryptography managment
Uses only bytes object that can be integrated in bytes-like object
These methods use openssl subprocess and temp files to sign, cypher and verify"""

import 		subprocess

from 		l_logging 			import 		log
from 		l_files 			import 		temp_file_name

ecdsaCurveName 							= "secp256k1"
privateKeyLength 						= 118
privateKeyOnlyLength 					= 32
privateKeyOnlyStartIndex 				= 7
publicKeyLength 						= 88
publicKeyOnlyLength 					= 64
publicKeyOnlyStartIndex 				= 24
publicKeyOnlyStartIndexInPrivateKey 	= 54
ecdsaHashName 							= "sha256"
standardHashName 						= "sha256"

class CryptoTool():

	def __new__(cls):
			log.error("CryptoTool must not be instanced", who="CryptoTool")

	def generate_private_key():
		cmd = ["openssl", "ecparam", "-name", ecdsaCurveName, "-genkey", "-outform", "DER", "-noout"]
		process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(result, error) = process.communicate()
		if error != b'':
			log.error(error.decode().replace("\n"," \\n "), who="CryptoTool")
		log.info("New private key generated", who="CryptoTool")
		return result

	def derive_public_key(privateKey):
		cmd = ["openssl", "ec", "-inform", "DER", "-outform", "DER", "-pubout"]
		process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		process.stdin.write(privateKey)
		(result, error) = process.communicate()
		if error != b'read EC key\nwriting EC key\n':
			log.error(error.decode().replace("\n"," \\n "), who="CryptoTool")
		log.info("Public key derivated", who="CryptoTool")
		return result

	def check_keys(privateKey, publicKey):
		return privateKey[publicKeyOnlyStartIndexInPrivateKey:publicKeyOnlyStartIndexInPrivateKey+publicKeyOnlyLength] == publicKey[publicKeyOnlyStartIndex:publicKeyOnlyStartIndex+publicKeyOnlyLength]

	def sign(*, m, k):

		# create key temp file
		keyFileName = temp_file_name()
		keyFile = open(keyFileName, 'wb')
		keyFile.write(k)
		keyFile.close()

		# sign message
		cmd = ["openssl", "dgst", "-"+ecdsaHashName, "-sign", keyFileName, "-keyform", "DER"]
		process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		process.stdin.write(m)
		(result, error) = process.communicate()
		if error != b'':
			log.error(error.decode().replace("\n"," \\n "), who="CryptoTool")

		# remove temp files
		subprocess.run(["rm", keyFileName])

		return result

	def verify(*, m, s, k):

		# create signature temp file
		signatureFileName = temp_file_name()
		signatureFile = open(signatureFileName, 'wb')
		signatureFile.write(s)
		signatureFile.close()

		# create key temp file
		keyFileName = temp_file_name()
		keyFile = open(keyFileName, 'wb')
		keyFile.write(k)
		keyFile.close()

		# verify signature
		cmd = ["openssl", "dgst", "-"+ecdsaHashName, "-verify", keyFileName, "-keyform", "DER", "-signature", signatureFileName]
		process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		process.stdin.write(m)
		(result, error) = process.communicate()
		#if error != b'':
		#	log.error(error.decode().replace("\n"," \\n "), who="CryptoTool")

		# remove temp files
		subprocess.run(["rm", signatureFileName, keyFileName])

		return "Verified OK" in result.decode()

	def prverify(*, m, s, k):
		log.error("prverify is not yet implemented", who="CryptoTool")

	def key_to_hex(key):
		if type(key) != bytes:
			raise TypeError("invalid type: '{}' instead 'bytes'".format(type(key).__name__))
		if   len(key) == privateKeyLength:
			return key[privateKeyOnlyStartIndex:privateKeyOnlyStartIndex+privateKeyOnlyLength].hex()
		elif len(key) == publicKeyLength:
			return key[publicKeyOnlyStartIndex:publicKeyOnlyStartIndex+publicKeyOnlyLength].hex()
		else:
			raise Exception("argument does not seem to be a key: wrong length")

	def hash(datas):
		cmd = ["openssl", "dgst", "-"+standardHashName]
		process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		process.stdin.write(datas)
		(result, error) = process.communicate()
		if error != b'':
			log.error(error.decode().replace("\n"," \\n "), who="CryptoTool")
		hexString = result.decode().split("= ")[1]    # select the string after the "= "
		hexString[:-1]                                # remove \n at the end
		return bytes.fromhex(hexString)


import enum
import logging

from aiohttp import web

from aiohttp.web_exceptions import (
    HTTPBadRequest, HTTPClientError
)
from aiohttp_swagger3.swagger_route import RequestValidationFailed

@enum.unique
class ApiErrorCode(enum.Enum):
    validation_error = 'validation_error'
    schema_validation_error = 'schema_validation_error'
    db_error = 'db_error'
    server_error = 'server_error'
    logical_error = 'logical_error'

class ApiBaseError(Exception):
    def __init__(self, error_code: ApiErrorCode, error_message: str, context: dict, http_status_code: int):
        self.status = 'error'
        self.error_code = error_code
        self.error_message = error_message
        if context is None:
            context = {}
        self.context = context
        self.http_status_code = http_status_code

    def as_dict(self) -> dict:
        data = {
            'status': self.status,
            'error_code': str(self.error_code.name),
            'error_message': self.error_message,
            'context': self.context
        }
        return data

@web.middleware
async def error_middleware(request: web.Request, handler) -> web.StreamResponse:
    try:
        return await handler(request)
    except RequestValidationFailed as e:
        err = ApiValidationError(
            error_message="Invalid params in body",
            error_code=ApiErrorCode.schema_validation_error,
            context=e.errors
        )
        return web.json_response(status=err.http_status_code, data=err.as_dict())
    except ApiBaseError as err:
        return web.json_response(status=err.http_status_code, data=err.as_dict())
    except HTTPBadRequest as e:
        err = ApiValidationError(
            error_message=str(e),
            context={'reason': e.reason}
        )
        return web.json_response(status=err.http_status_code, data=err.as_dict())
    except HTTPClientError:
        raise

    except Exception as e:
        logging.exception(f"Internal server error. Error: {e}")
        err = ApiInternalError(
            error_message='Internal server error',
            context={'Exception': str(e)}
        )
        return web.json_response(status=err.http_status_code, data=err.as_dict())

class ApiValidationError(ApiBaseError):
    def __init__(self, error_message: str, error_code: ApiErrorCode = ApiErrorCode.validation_error, context: dict=None):
        super(ApiValidationError, self).__init__(error_code, error_message, context, 400)

class ApiInternalError(ApiBaseError):
    def __init__(self, error_message: str, error_code: ApiErrorCode = ApiErrorCode.server_error, context: dict=None):
        super(ApiInternalError, self).__init__(error_code, error_message, context, 500)

class ApiLogicalError(ApiBaseError):
    def __init__(self, error_message: str, error_code: ApiErrorCode = ApiErrorCode.logical_error, context: dict=None):
        super(ApiLogicalError, self).__init__(error_code, error_message, context, 420)


import json
from datetime import timedelta

import structlog
from celery import shared_task
from django.apps import apps

from .celery import jbi_parse_buildinfo
from .celery import jbi_parse_hotfix
from .celery import process_result
from .conf import settings
from .utils import is_download_artifacts
from .utils import jenkins_get_artifact
from .utils import jenkins_get_build
from .utils import jenkins_get_console
from .utils import jenkins_get_env
from .utils import jenkins_remove_project_ppa
from tracker.conf import Tracker

logger = structlog.get_logger(__name__)

@shared_task(bind=True)
def jenkins_remove_project(self, jbi_id):
    JenkinsBuildInfo = apps.get_model("repoapi", "JenkinsBuildInfo")
    jbi = JenkinsBuildInfo.objects.get(id=jbi_id)
    structlog.contextvars.bind_contextvars(
        jbi=str(jbi),
        result=jbi.result,
        gerrit_eventtype=jbi.gerrit_eventtype,
    )
    if (
        jbi.jobname.endswith("-repos")
        and jbi.result == "SUCCESS"
        and jbi.gerrit_eventtype == "change-merged"
    ):
        try:
            jenkins_remove_project_ppa(jbi.param_ppa, jbi.source)
            logger.info("triggered job for removal")
        except FileNotFoundError as exc:
            logger.warn("source is not there yet, try again in 60 secs")
            raise self.retry(exc=exc, countdown=60)
    else:
        logger.info("skip removal")

@shared_task(ignore_result=True)
def jbi_get_artifact(jbi_id, jobname, buildnumber, artifact_info):
    path = jenkins_get_artifact(jobname, buildnumber, artifact_info)
    if path.name == settings.HOTFIX_ARTIFACT:
        if settings.TRACKER_PROVIDER == Tracker.NONE:
            logger.info("no tracker defined, skip hotfix management")
            return
        jbi_parse_hotfix.delay(jbi_id, str(path))

@shared_task(ignore_result=True)
def get_jbi_files(jbi_id, jobname, buildnumber):
    jenkins_get_console(jobname, buildnumber)
    path_envVars = jenkins_get_env(jobname, buildnumber)
    path_build = jenkins_get_build(jobname, buildnumber)
    jbi_parse_buildinfo.delay(jbi_id, str(path_build))
    if is_download_artifacts(jobname):
        with open(path_build) as data_file:
            data = json.load(data_file)
        logger.debug("job_info", data=data)
        for artifact in data["artifacts"]:
            jbi_get_artifact.delay(jbi_id, jobname, buildnumber, artifact)
    else:
        logger.debug("skip artifacts download")
    if jobname in settings.RELEASE_CHANGED_JOBS:
        process_result.delay(jbi_id, str(path_envVars))

@shared_task(ignore_result=True)
def jbi_purge(release, weeks):
    JenkinsBuildInfo = apps.get_model("repoapi", "JenkinsBuildInfo")
    JenkinsBuildInfo.objects.purge_release(release, timedelta(weeks=weeks))
    logger.info(f"purged release {release} jbi older than {weeks} weeks")


import time
from selenium import webdriver
import pymysql

conn =pymysql.connect(
    host='localhost',
    user='root',
    password='비밀번호',
    db='DB이름',
    charset='utf8'
)

cursor = conn.cursor()

driver = webdriver.Chrome('C:/chromedriver.exe')
driver.get('https://comic.naver.com/webtoon/list.nhn?titleId=729037&weekday=sun&page=1')
time.sleep(2)

titles = driver.find_elements_by_css_selector('td.title a')

for title in titles:
    print(title.text)
    SQL = "INSERT INTO `comments`(`title`, `url`) VALUES ('%s', '%s')" % (title.text, title.get_attribute('href'))
    cursor.execute(SQL)

conn.commit()

#The problem is that you are using find_element_by_xpath which return only one WebElement (which is not iterable), the find_elements_by_xpath return a list of WebElements.
#Solution: replace find_element_by_xpath with find_elements_by_xpath


# if.py

money = True

if money:
    print("택시를")
    print("타고")
    print("가라")

# --------------------------------------

money = 2000

if money >= 3000:
    print("택시를 타고 가라")
else:
    print("걸어 가라")

# --------------------------------------

money = 2000
card = True

if money > 3000 or card:
    print("택시를 타고 가라")
else:
    print("걸어 가라")

# --------------------------------------

pocket = ['paper', 'cellphone', 'money']

if 'money' in pocket:
    print("택시를 타고 가라")
else:
    print("걸어 가라")

# --------------------------------------

if 'card' not in pocket:
    print("걸아 가라")
else:
    print("버스를 타고 가라")

# --------------------------------------

pocket = ['paper', 'money', 'cellphone']

if 'money' in pocket:
    pass
else:
    print("카드를 꺼내라")

# --------------------------------------

pocket = ['paper', 'cellphone']
card = True

if 'money' in pocket:
    print("택시를 타고 가라")
elif 'card' in pocket:
    print("택시를 타고 가라")
else:
    print("걸어 가라")

# --------------------------------------

pocket = ['paper', 'money', 'cellphone']

if 'money' in pocket: pass
else: print("카드를 거내라")

# --------------------------------------

score = 65
if score >= 60:
    message = "success"
else:
    message = "failure"
print(message)

# --------------------------------------

score = 40
message = "success" if score >= 60 else "failure"
print(message)