seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
39260413778
# import system modules import traceback import os import sys import errno import subprocess import time import signal import functools # import I/O modules import RPi.GPIO as GPIO import smbus2 import spidev # import utility modules import math import numpy as np import scipy.constants as const from dataclasses import dataclass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) @functools.wraps(func) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wrapper return decorator @dataclass class LidarConfig: # dimensions height: int = 80 width: int = 104 # not including header pixel Ndata: int = 2 Nlight: int = 12000 # timing T0_pulse: int = 8 Light_pulse: int = 7 VTX3_pulse: int = 28 ADC_delay: int = 1 light_offset: float = 0.5 extrst_pulse: int = 16384 frame_blank: int = 255 def generate_reg_map(self): light_offset_int = math.ceil(self.light_offset) light_offset_half = self.light_offset % 1 > 0 return ( (0x00, 0b11100011), # stop operation (0x07, 0b11000000), # unknown? (0x08, (self.extrst_pulse >> 8) & 0xFF), # ext_reset (0x09, (self.extrst_pulse) & 0xFF), (0x0A, (self.width >> 8) & 0xFF), # H_pixel_num (0x0B, (self.width) & 0xFF), (0x0C, (self.height >> 8) & 0xFF), # V_pixel_num (0x0D, (self.height) & 0xFF), (0x0E, 0x25), # HST_offset (0x0F, 0b10110111), # light_pattern (0x10, (self.frame_blank) & 0xFF), # frame blanking (0x11, (self.frame_blank >> 8) & 0xFF), (0x12, (self.ADC_delay) & 0x1F), # ADC_delay_cfg (0x13, (0b0100 << 4) | ((self.Nlight >> 16) & 0x0F)), # LV_delay, Nlight (0x14, (self.Nlight >> 8) & 0xFF), (0x15, (self.Nlight) & 0xFF), (0x16, (self.Ndata) & 0xFF), # Ndata (must be >1, otherwise only reset value is read and VTX won't trigger) (0x17, (self.T0_pulse) & 0xFF), # VTX1 (0x18, (self.T0_pulse) & 0xFF), # VTX2 (0x19, (self.VTX3_pulse >> 8) & 0xFF), # VTX3 (0x1A, (self.VTX3_pulse) & 0xFF), (0x1B, (self.Light_pulse) & 0xFF), # light_pulse_width (0x1D, light_offset_int & 0xFF), # light_pulse_offset (0x1F, (self.T0_pulse >> 1) & 0x7F), # P4_half_delay, P4_delay (0x20, (0b0 << 7) | ((light_offset_half << 6) & 0x40) | (0b1001)), # L/A, Light_pulse_half_delay, H_pixel_blanking # (0x21, 0x00), # T1 (linear only) # (0x22, 0x00), # PHIS (linear only) # (0x23, 0x00), # T2 (linear only) (0x24, 0b00001111), # timing signal enable: light/VTX1/VTX2/VTX3 (0x00, 0b11000011), # start clock divider (0x00, 0b10000011), # start clock (0x00, 0b00000011), # start timing gen ) class LidarControl: # physical width: int = int(104) # not including header pixel height: int = int(80) Ndata: int = int(2) T_0: float = 8 / 60 * 1e-6 # I/O i2c_dev = [] i2c_channel = 1 i2c_address_lidar = 0x2A spi_dev = [] spi_channel = 0 spi_device_MCU = 0 pin_sensor_rst_P = 4 pin_mcu_rst_N = 23 def __init__(self, config=LidarConfig()): self.width = config.width self.height = config.height self.Ndata = config.Ndata self.T_0 = config.T0_pulse / 60 * 1e-6 self.config = config def __del__(self): print("LiDAR clean up called.") try: self.spi_dev.close() GPIO.cleanup() except Exception as err: print("Fail to clean GPIO.") print(err) def connect_GPIO(self): GPIO.setmode(GPIO.BCM) def connect_sensor(self, i2c_ch=1, i2c_addr=0x2A, pin_sensor_rst=4): self.i2c_channel = i2c_ch self.i2c_address_lidar = i2c_addr self.pin_sensor_rst_P = pin_sensor_rst try: GPIO.setup(self.pin_sensor_rst_P, GPIO.OUT, initial=0) # sensor reset (P) except Exception as err: print("Error:", err) print("Sensor rst pin initialization failed!") raise RuntimeError("GPIO not available!") else: print("Sensor rst pin initialized.") try: i2c_sensor = smbus2.SMBus(self.i2c_channel) except FileNotFoundError as err: print("FileNotFoundError", err) if err.errno == 2: print("I2C not enabled. Check raspi-config.") raise RuntimeError("I2C bus not available!") except Exception as err: print("Error:", err) print("I2C initialization failed!") raise RuntimeError("I2C bus init failed!") else: print("I2C initialized.") self.i2c_dev = i2c_sensor def connect_MCU(self, spi_ch=0, spi_num=0, pin_mcu_rst=23): self.spi_channel = spi_ch self.spi_device_MCU = spi_num self.pin_mcu_rst_N = pin_mcu_rst try: GPIO.setup(self.pin_mcu_rst_N, GPIO.OUT, initial=1) # MCU reset (N) except Exception as err: print("Error:", err) print("MCU rst pin initialization failed!") raise RuntimeError("GPIO not available!") else: print("MCU rst pin initialized.") try: spi_mcu = spidev.SpiDev() spi_mcu.open(self.spi_channel, self.spi_device_MCU) except Exception as err: print("Error:", err) print("SPI initialization failed!") raise RuntimeError("SPI bus init failed!") else: spi_mcu.max_speed_hz = 5000000 spi_mcu.mode = 0b11 spi_mcu.bits_per_word = 8 spi_mcu.lsbfirst = False print(f"SPI initialized at {spi_mcu.max_speed_hz}Hz.") self.spi_dev = spi_mcu def reset_device(self, sensor=True, mcu=False): if sensor: GPIO.output(self.pin_sensor_rst_P, 1) if mcu: GPIO.output(self.pin_mcu_rst_N, 0) time.sleep(0.01) if sensor: GPIO.output(self.pin_sensor_rst_P, 0) if mcu: GPIO.output(self.pin_mcu_rst_N, 1) time.sleep(0.01) print("Devices reset.") @timeout(5) def load_MCU(self, binary_path="dvp2proc2spi_lnk.elf"): try: # specifically ask for dual-core reset-halt-run in openocd # otherwise core 1 will crash after boot (bug in openocd?) openocd_cmd = f"program {binary_path} verify; " + \ "reset halt; " + \ "rp2040.core1 arp_reset assert 0; " + \ "rp2040.core0 arp_reset assert 0; " + \ "exit" load_cmd = ["openocd", "-f", "interface/raspberrypi-swd.cfg", "-f", "target/rp2040.cfg", "-c", openocd_cmd] subprocess.run(load_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) except Exception as err: print("Error:", err) print("Load binary failed!") raise RuntimeError("MCU binary loading failed!") else: print("MCU binary loaded.") def setup_sensor(self): try: lidar_reg_map = self.config.generate_reg_map() # write regs and check step-by-step for instruction in lidar_reg_map: self.i2c_dev.write_byte_data(self.i2c_address_lidar, instruction[0], instruction[1]) if instruction[1] != self.i2c_dev.read_byte_data(self.i2c_address_lidar, instruction[0]): raise Exception(f"Register validation failed! @{instruction}") except OSError as err: print("OSError", err) if err.errno == 121: print("I2C: No response from device! Check wiring on GPIO2/3.") raise RuntimeError("I2C device not connected!") except Exception as err: print("Error:", err) print("I2C unknown error!") raise RuntimeError("I2C unknown error!") else: print("I2C data sent.") @timeout(10) def acquire_data(self): # [F1..F4] [VTX1,VTX2] [Y] [X] data = np.zeros((4, 2, self.height, self.width), dtype=np.int16) # progress info print(f" - Trigger Frame capture and SPI read.") # command MCU to start frame capturing time.sleep(0.01) # wait for MCU to flush FIFO self.spi_dev.writebytes([0x01]) # query frame state timeout_counter = 0 while True: frame_state = self.spi_dev.readbytes(1) time.sleep(0.01) # wait for MCU to flush FIFO if frame_state[0] == (0x11): break else: timeout_counter += 1 # re-trigger if there is a timeout (SPI command lost) if (timeout_counter > 250): timeout_counter = 0 self.spi_dev.writebytes([0x01]) print(f" - Re-trigger Frame capture.") # data transfering data_stream = np.zeros((4, self.height, 2 * (self.width + 1)), dtype=np.int16) for subframe in range(0, 4): for line in range(0, self.height): temp = self.spi_dev.readbytes(4 * (self.width + 1)) temp = np.array(temp, dtype=np.int16) data_stream[subframe, line, :] = (temp[1::2] << 8) | temp[0::2] data[:, 0, :, :] = data_stream[:, :, 2::2] data[:, 1, :, :] = data_stream[:, :, 3::2] data[[0, 2], :, :, :] = data[[2, 0], :, :, :] return data
ExplodingONC/Flash_LiDAR_Microscan
LidarControl.py
LidarControl.py
py
10,164
python
en
code
0
github-code
36
2820524990
from django.contrib import admin from .models import CalendarEvent, CalendarEventAttendee, UserCalendar class CalendarEventAttendeeInline(admin.TabularInline): model = CalendarEventAttendee extra = 0 autocomplete_fields = ( 'user', ) class UserCalendarInline(admin.TabularInline): model = UserCalendar extra = 0 readonly_fields = ( "uuid", ) @admin.register(CalendarEvent) class CalendarEvent(admin.ModelAdmin): inlines = ( CalendarEventAttendeeInline, ) autocomplete_fields = ( 'organizer', )
rimvydaszilinskas/organize-it
apps/calendars/admin.py
admin.py
py
584
python
en
code
0
github-code
36
28299895707
from train import get_model from torchvision import transforms from PIL import Image import matplotlib.pyplot as plt import torch import os from torchvision.models import resnet18, ResNet18_Weights import torch.nn as nn import numpy as np class Make_Test(nn.Module): def __init__(self, weight_path): super(Make_Test, self).__init__() self.transform = transforms.Compose([ transforms.Resize(size=(224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) self.model = get_model() self.model.load_state_dict(torch.load(weight_path)) self.d = { 0: 'cat', 1: 'dog' } def forward(self, image_path): image = plt.imread(image_path) image = Image.fromarray(image) image = self.transform(image).unsqueeze(0) self.model.eval() out = 0 if self.model(image).squeeze(-1).item() < 0.5 else 1 return self.d[out] def visuzalize_loss(): train_loss = np.load('Accuracy/test_losses.npy') train_acc = np.load('test1/test_accs.npy') plt.plot(train_loss) plt.plot(train_acc) plt.show() def visualize(mk_test, data_path): fig = plt.figure(figsize=(9, 9)) rows, cols = 4, 4 for i in range(1, rows * cols + 1): img = plt.imread(os.path.join("test1", data_path[i - 1])) label = mk_test(os.path.join("test1", data_path[i - 1])) fig.add_subplot(rows, cols, i) plt.imshow(img) plt.title(label) plt.axis(False) plt.show() if __name__ == '__main__': folder = "test1" cnt = 0 mk_test = Make_Test(r"E:\Python test Work\Hieu\Weight\model.pt") data_path = os.listdir(folder)[16:32] visualize(mk_test, data_path)
kienptitit/Dog_Cat_Classification
image_test.py
image_test.py
py
1,821
python
en
code
0
github-code
36
1243604019
from math import cos, pi, sin import pygame as pg from constants import consts as c from id_mapping import id_map from images import img as i from ui.game_ui import ui def move_player(keys_pressed): if keys_pressed[pg.K_UP] or keys_pressed[pg.K_w]: c.player_y -= c.player_speed * c.dt if c.player_y < 0: c.player_y = 0 if keys_pressed[pg.K_DOWN] or keys_pressed[pg.K_s]: c.player_y += c.player_speed * c.dt if c.player_y + c.sh > c.num_cells * c.cell_length: c.player_y = c.num_cells * c.cell_length - c.sh if keys_pressed[pg.K_LEFT] or keys_pressed[pg.K_a]: c.player_x -= c.player_speed * c.dt if c.player_x < 0: c.player_x = 0 if keys_pressed[pg.K_RIGHT] or keys_pressed[pg.K_d]: c.player_x += c.player_speed * c.dt if c.player_x + c.sw > c.num_cells * c.cell_length: c.player_x = c.num_cells * c.cell_length - c.sw def get_pointer_params(): mouse_x, mouse_y = pg.mouse.get_pos() cell_row = int((mouse_y + c.player_y) / c.cell_length) cell_col = int((mouse_x + c.player_x) / c.cell_length) cell_x = cell_col * c.cell_length - c.player_x + 2 cell_y = cell_row * c.cell_length - c.player_y + 2 return cell_row, cell_col, cell_x, cell_y def draw_action(cell_x, cell_y): pg.draw.circle(c.screen, c.action_color, (cell_x + c.cell_length // 2, cell_y + c.cell_length // 2), 4 * c.cell_length // 5, 2) if c.const_state == 1: c.screen.blit(i.images[id_map["conveyor"]][c.rot_state], (cell_x - 1, cell_y - 1)) ui.render_text("Place Conveyor: (L/R) to rotate") if c.const_state == 2: c.screen.blit(i.images[id_map["conveyor_underground"]][c.rot_state], (cell_x - 1, cell_y - 1)) translations = [(0, 1), (1, 0), (0, -1), (-1, 0)] x = cell_x + translations[c.rot_state][0] * c.ug_state * c.cell_length y = cell_y - translations[c.rot_state][1] * c.ug_state * c.cell_length c.screen.blit(i.images[id_map["conveyor_underground"]][c.rot_state + 4], (x, y)) pg.draw.circle(c.screen, c.action_color, (x + c.cell_length // 2, y + c.cell_length // 2), 4 * c.cell_length // 5, 2) ui.render_text("Place Underground Conveyor: (L/R) to rotate (Shift/Ctrl) to change length") elif c.const_state == 3: c.screen.blit(i.images[id_map["splitter"]][c.rot_state], (cell_x - 1, cell_y - 1)) translations = [[(-1, 1), (1, 1)], [(1, -1), (1, 1)], [(1, -1), (-1, -1)], [(-1, 1), (-1, -1)]] x1 = cell_x + translations[c.rot_state][0][0] * c.cell_length y1 = cell_y - translations[c.rot_state][0][1] * c.cell_length x2 = cell_x + translations[c.rot_state][1][0] * c.cell_length y2 = cell_y - translations[c.rot_state][1][1] * c.cell_length pg.draw.rect(c.screen, c.target_color, (x1, y1, c.cell_length, c.cell_length), 3) pg.draw.rect(c.screen, c.target_color, (x2, y2, c.cell_length, c.cell_length), 3) ui.render_text("Place Splitter: (L/R) to rotate") elif c.const_state == 4: c.screen.blit(i.images[id_map["arm"]], (cell_x - 1, cell_y - 1)) angle = ((1 - (c.rot_state + 2) % 4) * pi / 2) % (2 * pi) start_x = cell_x + c.cell_length // 2 start_y = cell_y + c.cell_length // 2 end_x = start_x + c.cell_length * cos(angle) end_y = start_y - c.cell_length * sin(angle) pg.draw.line(c.screen, c.arm_color, (start_x, start_y), (end_x, end_y), 2) draw_source(cell_x, cell_y, c.rot_state) draw_target(cell_x, cell_y, c.rot_state) ui.render_text("Place Arm: (L/R) to rotate") elif c.const_state == 5: c.screen.blit(i.images[id_map["mine"]], (cell_x - 1, cell_y - 1)) draw_target(cell_x, cell_y, c.rot_state) ui.render_text("Place Mine: (L/R) to rotate") elif c.const_state == 6: c.screen.blit(i.images[id_map["furnace"]], (cell_x - 1, cell_y - 1)) draw_target(cell_x, cell_y, c.rot_state) ui.render_text("Place Furnace: (L/R) to rotate") elif c.const_state == 7: c.screen.blit(i.images[id_map["factory"]], (cell_x - 1, cell_y - 1)) draw_target(cell_x, cell_y, c.rot_state) ui.render_text("Place Factory: (L/R) to rotate") def draw_target(cell_x, cell_y, state): translations = [(0, -1), (1, 0), (0, 1), (-1, 0)] x = cell_x + translations[state][0] * c.cell_length y = cell_y + translations[state][1] * c.cell_length pg.draw.rect(c.screen, c.target_color, (x, y, c.cell_length, c.cell_length), 3) def draw_source(source_x, source_y, state): translations = [(0, 1), (-1, 0), (0, -1), (1, 0)] x = source_x + translations[state][0] * c.cell_length y = source_y + translations[state][1] * c.cell_length pg.draw.rect(c.screen, c.source_color, (x, y, c.cell_length, c.cell_length), 3) def draw_gridlines(): for x in range(0, c.num_cells * c.cell_length, c.cell_length): pg.draw.line(c.screen, c.grid_color, (x - c.player_x, 0), (x - c.player_x, c.sh)) for y in range(0, c.num_cells * c.cell_length, c.cell_length): pg.draw.line(c.screen, c.grid_color, (0, y - c.player_y), (c.sw, y - c.player_y))
chanrt/py-factory
utils.py
utils.py
py
5,214
python
en
code
11
github-code
36
33517643066
from manimlib.imports import * #Visualización de Gráficas (Va después de Gráficas) def Range(in_val,end_val,step=1): return list(np.arange(in_val,end_val+step,step)) ### VISUALIZACIÓN DE GRÁFICAS (DIVIDO EN 3 CLASES, PERO ES UN SÓLO VIDEO) ### #EJEMPLO 1 R -> R# class Visualización_Gráficas_1(GraphScene,Scene): def setup(self): Scene.setup(self) GraphScene.setup(self) CONFIG = { "y_max" : 20, "y_min" : 0, "x_max" : 5, "x_min" : 0, "y_tick_frequency" : 1, "x_tick_frequency" : 1, "axes_color" : BLUE, "graph_origin" : np.array((-2.5,-3,0)) } def construct (self): titulo = TextMobject("Visualización de Gráficas").scale(1.5) text1_1 = TextMobject("Recordemos que dada una función") text1_2 = TexMobject(r"f:A \subset \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}",color=YELLOW).next_to(text1_1,DOWN) text1_3 = TextMobject("la gráfica de $f$ es subconjunto de ", "$\mathbb{R}^{n+m}$").next_to(text1_2,DOWN) text1_3[1].set_color(YELLOW) text1 = VGroup(text1_1,text1_2,text1_3).move_to(0.5*UP) funcion_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}").move_to(1*DOWN) funcion_2 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1,DOWN) funcion_3 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2,DOWN) funciones = VGroup(funcion_1,funcion_2,funcion_3) text3 = TextMobject("Ahora, veamos algunos ejemplos") text4_1 = TextMobject("Consideremos una recta $x=$ ", "$x_0$", ",").move_to(3.3*UP+2.5*RIGHT) text4_2 = TextMobject("¿qué pasa si ", "$x_0$", " pertenece al dominio de $f$?").next_to(text4_1,DOWN) text4_1[1].set_color(GREEN_E) text4_2[1].set_color(GREEN_E) text4 = VGroup(text4_1,text4_2).scale(0.8) text5 = TextMobject('''Cada recta intersecta a la gráfica\n en un sólo punto ''').move_to(3.3*UP+2.5*RIGHT).scale(0.8) text6 = TextMobject('''¿Qué pasará si $x_0$ no pertenece\n al dominio de $f$?''').move_to(3.3*UP+2.5*RIGHT).scale(0.8) #PRIMERA CAJA funciones.bg =SurroundingRectangle(funciones, buff = 0.8*SMALL_BUFF, color=WHITE) Caja = VGroup(funciones.bg,funciones) #CAJA UPPER LEFT PRE EJEMPLO funciones_copy_0 = funciones.copy().to_corner(UL) funciones_copy_0.bg = SurroundingRectangle(funciones_copy_0, buff = 0.8*SMALL_BUFF, color=WHITE) Caja_0 = VGroup(funciones_copy_0.bg,funciones_copy_0) #CAJA EJEMPLO 1 funcion_1_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}",color=YELLOW) funcion_2_1 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1_1,DOWN) funcion_3_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_1,DOWN) funciones_1 = VGroup(funcion_1_1,funcion_2_1,funcion_3_1).to_corner(UL) funciones_1.bg =SurroundingRectangle(funciones_1, buff = 0.8*SMALL_BUFF, color=WHITE) Caja_1 = VGroup(funciones_1.bg,funciones_1) #Texto ejemplo función ejemplo_1_1 = TexMobject(r"f(x)=x^{2}",color=YELLOW) ejemplo_1_2 = TexMobject(r"G_{f}:=\{(x,f(x))\in \mathbb{R}^{2}|x\in[0,4]\}",color=YELLOW).next_to(ejemplo_1_1,DOWN) ejemplo_1 = VGroup(ejemplo_1_1,ejemplo_1_2).move_to(2.8*UP+2*RIGHT) #OBJETOS PARA EJEMPLO 1 dot_1_1 = Dot().set_color(WHITE).move_to(np.array((1.1,-1.8,0))) dot_1_x1 = Dot().set_color(WHITE).move_to(np.array((1.1,-3,0))) dot_1_y1 = Dot().set_color(WHITE).move_to(np.array((-2.5,-1.8,0))) linea_1_x1 = DashedLine(dot_1_x1.get_top(),dot_1_1.get_bottom(),buff=0.1) linea_1_x1.set_color(WHITE) linea_1_y1 = DashedLine(dot_1_y1.get_right(),dot_1_1.get_left(),buff=0.1) linea_1_y1.set_color(WHITE) text_dot_1_x1 = TexMobject(r"x=2").move_to(dot_1_x1.get_bottom()+0.5*DOWN).scale(0.75) text_dot_1_y1 = TexMobject(r"f(2)=4").move_to(dot_1_y1.get_left()+1.2*LEFT).scale(0.75) text_dot_1_1 = TexMobject(r"(2,f(2))").move_to(dot_1_1.get_top()+0.4*UP+0.5*LEFT).scale(0.75) dot_1_2 = Dot().set_color(WHITE).move_to(np.array((2.9,-0.3,0))) dot_1_x2 = Dot().set_color(WHITE).move_to(np.array((2.9,-3,0))) dot_1_y2 = Dot().set_color(WHITE).move_to(np.array((-2.5,-0.3,0))) linea_1_x2 = DashedLine(dot_1_x2.get_top(),dot_1_2.get_bottom(),buff=0.1) linea_1_x2.set_color(WHITE) linea_1_y2 = DashedLine(dot_1_y2.get_right(),dot_1_2.get_left(),buff=0.1) linea_1_y2.set_color(WHITE) text_dot_1_x2 = TexMobject(r"x=3").move_to(dot_1_x2.get_bottom()+0.5*DOWN).scale(0.75) text_dot_1_y2 = TexMobject(r"f(3)=9").move_to(dot_1_y2.get_left()+1.2*LEFT).scale(0.75) text_dot_1_2 = TexMobject(r"(3,f(3))").move_to(dot_1_2.get_top()+0.4*UP+0.5*LEFT).scale(0.75) text_dots_1_1 = VGroup(text_dot_1_1,text_dot_1_2) text_dots_1_2 = TextMobject('''$(2,f(2))\\in G_{f}$ \n $(3,f(3))\\in G_{f}$''').to_edge(LEFT).scale(0.75) text_grafica_1 = TexMobject(r"G_{f}",color=YELLOW).move_to(ejemplo_1.get_bottom()+0.75*DOWN+3*RIGHT) ###Rectas verticales dot_dom_1 = Dot().set_color(GREEN_E).move_to((1.5,-3.0,0)) dot_dom_2 = Dot().set_color(GREEN_E).move_to((4,-3.0,0)) dot_func_1 = Dot().move_to((1.5,-1.5,0)) dot_func_2 = Dot().move_to((4,0.9,0)) linea_vert_1 = Line((1.5,-3.5,0),(1.5,1.5,0)).set_color(GREEN_E) linea_vert_2 = Line((4,-3.5,0),(4,1.5,0)).set_color(GREEN_E) RectVert = VGroup(dot_dom_1,dot_dom_2,dot_func_1,dot_func_2,linea_vert_1,linea_vert_2) #Secuencia de Animación self.play(Write(titulo)) self.wait(3) self.play(FadeOut(titulo)) self.play(Write(text1)) self.wait(9) self.play(FadeOut(text1)) self.play(Write(text3)) self.wait(3) self.play(Write(funciones)) self.wait(0.5) self.play(ShowCreation(funciones.bg)) self.wait(0.5) self.play(FadeOut(text3)) self.play(ReplacementTransform(Caja,Caja_0)) #EJEMPLO 1 self.play(ReplacementTransform(Caja_0,Caja_1)) self.setup_axes(animate=True) graph = self.get_graph(lambda x : x**2, color = YELLOW, x_min = 0, x_max = 4 ) self.play(FadeIn(ejemplo_1)) self.play(FadeIn(dot_1_1),FadeIn(dot_1_x1),FadeIn(text_dot_1_x1),FadeIn(dot_1_y1),FadeIn(text_dot_1_y1)) self.wait(2) self.play(ShowCreation(linea_1_x1),ShowCreation(linea_1_y1)) self.play(FadeIn(text_dot_1_1)) self.wait(2) self.play(FadeIn(dot_1_2),FadeIn(dot_1_x2),FadeIn(text_dot_1_x2),FadeIn(dot_1_y2),FadeIn(text_dot_1_y2)) self.wait(2) self.play(ShowCreation(linea_1_x2),ShowCreation(linea_1_y2)) self.play(FadeIn(text_dot_1_2)) self.wait(2) self.play(FadeOut(text_dot_1_x1),FadeOut(text_dot_1_x2),FadeOut(text_dot_1_y1),FadeOut(text_dot_1_y2)) self.play(ReplacementTransform(text_dots_1_1,text_dots_1_2)) self.wait(3) self.play(FadeOut(linea_1_x1),FadeOut(linea_1_x2),FadeOut(linea_1_y1),FadeOut(linea_1_y2),FadeOut(dot_1_x1),FadeOut(dot_1_x2),FadeOut(dot_1_y1),FadeOut(dot_1_y2)) self.play( ShowCreation(graph), run_time = 3 ) self.play(FadeIn(text_grafica_1)) self.wait() self.play(FadeOut(ejemplo_1),FadeOut(dot_1_1),FadeOut(dot_1_2),FadeOut(text_dots_1_2)) self.play(Write(text4)) self.wait(6.5) self.play(FadeIn(dot_dom_1)) self.play(ShowCreation(linea_vert_1)) self.play(FadeOut(text4)) self.play(FadeIn(text5)) self.wait(5) self.play(FadeIn(dot_func_1)) self.play(FadeIn(dot_dom_2)) self.play(ShowCreation(linea_vert_2)) self.play(FadeIn(dot_func_2)) self.wait(2.5) self.play(FadeOut(RectVert)) self.play(FadeOut(text5)) self.play(FadeIn(text6)) self.wait(7) self.play(FadeOut(text_grafica_1),FadeOut(self.axes),FadeOut(graph),FadeOut(text6)) #EJEMPLO 2 R^2 -> R# class Visualización_Gráficas_2(ThreeDScene,Scene): def setup(self): Scene.setup(self) ThreeDScene.setup(self) def acomodar_textos(self,objeto): self.add_fixed_in_frame_mobjects(objeto) self.play(Write(objeto)) def FadeOutWrite3D(self,objeto1,objeto2): self.play(FadeOut(objeto1)) self.acomodar_textos(objeto2) def punto3D(self): bola = ParametricSurface( lambda u, v: np.array([ 0.075*np.cos(v) * np.sin(u), 0.075*np.sin(v) * np.sin(u), 0.075*np.cos(u) ]),v_min=0,v_max=TAU,u_min=0.001,u_max=PI-0.001, resolution=(12,24),fill_opacity=1,stroke_color=GREEN_E,fill_color=GREEN_E) return bola def punto3D_2(self): bola = ParametricSurface( lambda u, v: np.array([ 0.075*np.cos(v) * np.sin(u), 0.075*np.sin(v) * np.sin(u), 0.075*np.cos(u) ]),v_min=0,v_max=TAU,u_min=0.001,u_max=PI-0.001, resolution=(12,24),fill_opacity=1,stroke_color=GOLD_E,fill_color=GOLD_E) return bola def construct(self): #Caja Ejemplo 1 (Para transición de cajas) funcion_1_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}",color=YELLOW) funcion_2_1 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1_1,DOWN) funcion_3_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_1,DOWN) funciones_1 = VGroup(funcion_1_1,funcion_2_1,funcion_3_1).to_corner(UL) funciones_1.bg =SurroundingRectangle(funciones_1, buff = 0.8*SMALL_BUFF, color=WHITE) Caja_1 = VGroup(funciones_1.bg,funciones_1) #CAJA EJEMPLO 2 funcion_1_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}") funcion_2_2 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}",color=YELLOW).next_to(funcion_1_2,DOWN) funcion_3_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_2,DOWN) funciones_2 = VGroup(funcion_1_2,funcion_2_2,funcion_3_2).to_corner(UL) funciones_2.bg =SurroundingRectangle(funciones_2, buff = 0.8*SMALL_BUFF, color=WHITE) Caja_2 = VGroup(funciones_2.bg,funciones_2) #EJEMPLO 2 ejemplo_2_1 = TexMobject(r"f(x,y)=\sin(x)\cos(y)",color=YELLOW) ejemplo_2_2 = TexMobject(r"G_{f}:=\{(x,y,f(x,y))\in \mathbb{R}^{3}|(x,y)\in A\}",color=YELLOW).next_to(ejemplo_2_1,DOWN) ejemplo_2 = VGroup(ejemplo_2_1,ejemplo_2_2).move_to(3.3*UP+3.6*RIGHT).scale(0.8) ###Líneas verticales text_1 = TextMobject("Consideremos una recta $(x,y,z)=($", "$x_0$",",","$y_0$","$,0)+\\alpha\\hat{z}$, con $\\alpha\\in\\mathbb{R}$").move_to(3.5*UP+2*RIGHT) text_1[1].set_color(GREEN_E) text_1[3].set_color(GREEN_E) text_1_1 = TextMobject("¿qué pasa si ", "$(x_0,y_0)$"," pertence al dominio de $f$?").next_to(text_1,DOWN) text_1_1[1].set_color(GREEN_E) text_1 = VGroup(text_1,text_1_1).scale(0.7) text_2 = TextMobject("La recta intersecta la gráfica en un sólo punto").move_to(3.3*UP+2*RIGHT).scale(0.6) text_3 = TextMobject("¿Qué pasará si ", "$(x_0,y_0)$"," no pertence al dominio de $f$?").move_to(3.3*UP+2*RIGHT).scale(0.6) text_3[1].set_color(GREEN_E) Superficie = ParametricSurface( lambda u, v: np.array([ u, v, np.sin(u)*np.cos(v) ]),v_min=-2.5,v_max=4,u_min=-3,u_max=5,checkerboard_colors=[GOLD_E,GOLD_E], resolution=(20, 50)) Superficie2 = ParametricSurface( lambda u, v: np.array([ u, v, np.sin(u)*np.cos(v) ]),v_min=-2.5,v_max=4,u_min=-3,u_max=5,checkerboard_colors=[GOLD_E,GOLD_E], resolution=(20, 50),fill_opacity=0.5) axes = ThreeDAxes(x_min=-3,x_max=6,y_min=-3,y_max=6,z_min=-3,z_max=3,num_axis_pieces=40) #Creo que es redundante lo del color=WHITE en los Dot, pero no importa dot_2_1 = Dot().set_color(RED).move_to(np.array((3*PI/2,2.5,0.8))) dot_2_x1 = Dot().set_color(WHITE).move_to(np.array((3*PI/2,0,0))) dot_2_y1 = Dot().set_color(WHITE).move_to(np.array((0,2.5,0))) dot_2_z1 = Dot().set_color(WHITE).move_to(np.array((0,0,0.8))) dot_2_xy1 = Dot().set_color(WHITE).move_to(np.array((3*PI/2,2.5,0))) linea_2_x1 = DashedLine(dot_2_x1.get_center(),dot_2_xy1.get_center(),buff=0.1,rate=0.25) linea_2_x1.set_color(WHITE) linea_2_y1 = DashedLine(dot_2_y1.get_center(),dot_2_xy1.get_center(),buff=0.1) linea_2_y1.set_color(WHITE) linea_2_z1 = DashedLine(dot_2_z1.get_center(),dot_2_1.get_center(),buff=0.1) linea_2_z1.set_color(WHITE) linea_2_xy1 = DashedLine(dot_2_xy1.get_center(),dot_2_1.get_center(),buff=0.1) linea_2_xy1.set_color(WHITE) text_dot_2_x1 = TexMobject(r"x=\frac{3\pi}{2}").move_to(dot_2_x1.get_top()+0.5*UP).scale(0.75) text_dot_2_y1 = TexMobject(r"y=2.5").move_to(dot_2_y1.get_left()+1*RIGHT).scale(0.75) text_dot_2_z1 = TexMobject(r"f(x,y)=0.8").move_to(dot_2_z1.get_left()+1.5*LEFT).scale(0.75) text_dot_2_1 = TexMobject(r"(x,y,f(x,y))",color=RED).move_to(dot_2_1.get_right()+0.8*UP).scale(0.75) text_dot_2_xy1 = TexMobject(r"(x,y)\in A").move_to(dot_2_xy1.get_top()+0.5*RIGHT+0.5*UP).scale(0.75) gpo_coordxy_2_1 = VGroup(text_dot_2_x1,text_dot_2_y1) gpo_coordxyz_2_1 = VGroup(text_dot_2_xy1, text_dot_2_z1) text_grafica_2 = TexMobject(r"G_{f}",color=GOLD_E).move_to(4.75*RIGHT+1*DOWN) ###Objetos Rectas dot_dom_1 = self.punto3D().move_to((PI/2,0,0)) dot_func_1 = self.punto3D_2().move_to((PI/2,0,1)) dot_dom_2 = self.punto3D().move_to((0,5,0)) linea_vert_1 = Line((PI/2,0,-3),(PI/2,0,3)).set_color(GREEN_E) linea_vert_2 = Line((0,5,-3),(0,5,3)).set_color(GREEN_E) RectVert = VGroup(dot_dom_1,dot_dom_2,dot_func_1,linea_vert_1) #EJEMPLO 2 self.add(Caja_1) self.wait(0.5) self.play(ReplacementTransform(Caja_1,Caja_2)) self.add_fixed_in_frame_mobjects(Caja_2) self.play(FadeIn(ejemplo_2)) self.add_fixed_in_frame_mobjects(ejemplo_2) self.set_camera_orientation(phi=55 * DEGREES,theta=-50*DEGREES,distance=50) self.play(ShowCreation(axes)) self.wait() self.play(FadeIn(dot_2_x1),FadeIn(text_dot_2_x1)) self.wait(1.5) self.play(FadeIn(dot_2_y1),FadeIn(text_dot_2_y1)) self.wait(1.5) self.play(FadeIn(dot_2_z1),FadeIn(text_dot_2_z1)) self.wait(1.5) self.begin_ambient_camera_rotation(rate=0.04) self.play(FadeIn(dot_2_xy1),ReplacementTransform(gpo_coordxy_2_1,text_dot_2_xy1)) self.play(FadeIn(linea_2_x1)) self.play(FadeIn(linea_2_y1)) self.play(FadeIn(dot_2_1)) self.play(FadeIn(linea_2_xy1),FadeIn(linea_2_z1)) self.wait(2) self.play(ReplacementTransform(gpo_coordxyz_2_1,text_dot_2_1)) self.wait(3.5) self.play(FadeOut(dot_2_xy1),FadeOut(dot_2_x1),FadeOut(dot_2_y1),FadeOut(dot_2_z1),FadeOut(linea_2_x1),FadeOut(linea_2_xy1),FadeOut(linea_2_y1),FadeOut(linea_2_z1),FadeOut(text_dot_2_1)) self.play(ShowCreation(Superficie)) self.add_fixed_in_frame_mobjects(text_grafica_2) self.wait(23) self.stop_ambient_camera_rotation() self.play(FadeOut(dot_2_1),FadeOut(text_grafica_2),FadeOut(ejemplo_2)) self.wait() self.acomodar_textos(text_1) self.wait(12) self.move_camera(phi=75 * DEGREES,theta=-50*DEGREES,distance=50,frame_center=[0,0,1]) self.play(ReplacementTransform(Superficie,Superficie2)) self.begin_ambient_camera_rotation(rate=0.04) self.play(FadeIn(dot_dom_1)) self.play(ShowCreation(linea_vert_1)) self.FadeOutWrite3D(text_1,text_2) self.play(FadeIn(dot_func_1)) self.wait(4.5) self.play(FadeOut(dot_dom_1),FadeOut(dot_func_1),FadeOut(linea_vert_1)) self.FadeOutWrite3D(text_2,text_3) self.wait(5) self.play(FadeIn(dot_dom_2)) self.wait(1.5) self.play(ShowCreation(linea_vert_2)) self.stop_ambient_camera_rotation self.wait(5) self.play(FadeOut(axes),FadeOut(Superficie2),FadeOut(text_3),FadeOut(dot_dom_2),FadeOut(linea_vert_2)) #EJEMPLO 3 R -> R^2# class Visualización_Gráficas_3(ThreeDScene,Scene): def setup(self): Scene.setup(self) ThreeDScene.setup(self) def FadeOutWrite3D(self,objeto1,objeto2): self.play(FadeOut(objeto1)) self.acomodar_textos(objeto2) def acomodar_textos(self,objeto): self.add_fixed_in_frame_mobjects(objeto) self.play(Write(objeto)) def construct(self): #CAJA EJEMPLO 2 funcion_1_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}") funcion_2_2 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}",color=YELLOW).next_to(funcion_1_2,DOWN) funcion_3_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_2,DOWN) funciones_2 = VGroup(funcion_1_2,funcion_2_2,funcion_3_2).to_corner(UL) funciones_2.bg =SurroundingRectangle(funciones_2, buff = 0.8*SMALL_BUFF, color=WHITE) Caja_2 = VGroup(funciones_2.bg,funciones_2) #Caja ejemplo 3 funcion_1_3 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}") funcion_2_3 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1_3,DOWN) funcion_3_3 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}",color=YELLOW).next_to(funcion_2_3,DOWN) funciones_3 = VGroup(funcion_1_3,funcion_2_3,funcion_3_3).to_corner(UL) funciones_3.bg =SurroundingRectangle(funciones_3, buff = 0.8*SMALL_BUFF, color=WHITE) Caja_3 = VGroup(funciones_3.bg,funciones_3) text_3 = TextMobject('''No es común en clase graficar funciones de $\\mathbb{R}\\rightarrow\\mathbb{R}^2$\n por la dificultad de hacer los dibujos en pizarrón''') text_4 = TextMobject('''Generalmente se trabaja con la imagen de la\n función, dibujando las curvas correspondientes\n en el plano del contradominio ''') text_5 = TextMobject('''En este y otros videos podemos usar\n la gráfica de este tipo de funciones ''') text_6 = TextMobject("Consideremos algunos puntos de la gráfica").move_to(3.3*UP+2*RIGHT).scale(0.8) text_7 = TextMobject('''Análogo a los casos anteriores, podemos tomar \n planos paralelos al plano $xy$''').move_to(3.3*UP+2*RIGHT).scale(0.8) text_8 = TextMobject('''La intersección de la gráfica con estos\n planos sólo puede ser un punto''').move_to(3.3*UP+2*RIGHT).scale(0.8) text_9 = TextMobject('''Si fuera más de un punto,\n $f$ no sería función''').move_to(3.3*UP+RIGHT).scale(0.8) text_10 = TextMobject('''Si la intersección fuera el vacío,\n el punto correspondiente en el eje t\n no sería parte del dominio ''').move_to(3.3*UP).scale(0.7) #EJEMPLO 3 ejemplo_3_1 = TexMobject(r"f(t)=\frac{t}{4\pi}(\cos(t),\sin(t))",color=YELLOW) ejemplo_3_2 = TexMobject(r"G_{f}:=\{(t,f(t))\in \mathbb{R}^{3}|t\in A\}",color=YELLOW).next_to(ejemplo_3_1,DOWN) ejemplo_3 = VGroup(ejemplo_3_1,ejemplo_3_2).move_to(3.2*UP).scale(0.65) ejemplo_3_10=ejemplo_3.copy().move_to(3.2*UP+4*RIGHT) #EJES axes_2 = ThreeDAxes(x_min=-3.5,x_max=3.2,y_min=-3.5,y_max=3.5,z_min=0,z_max=5*PI,num_axis_pieces= 30) #AQUÍ VAN TODAS LOS PLANOS, PUNTOS Y LA CURVA curva_1 = ParametricFunction( lambda u : np.array([ (u/(4*PI))*math.cos(u), (u/(4*PI))*math.sin(u), u ]),color=YELLOW,t_min=0,t_max=4*PI, ) plano_1 = ParametricSurface( lambda u, v: np.array([ u, v, PI/2 ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=BLUE_E,fill_opacity=0.25, resolution=(1, 1)) punto_1 = Dot(color=RED).move_to((0,1*1*PI/(8*PI),PI/2)) plano_2 = ParametricSurface( lambda u, v: np.array([ u, v, PI ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=TEAL_E,fill_opacity=0.25, resolution=(1, 1)) punto_2 = Dot(color=RED).move_to((-1*2*PI/(8*PI),0,PI)) plano_3 = ParametricSurface( lambda u, v: np.array([ u, v, 3*PI/2 ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=GREEN_E,fill_opacity=0.25, resolution=(1, 1)) punto_3 = Dot(color=RED).move_to((0,-1*3*PI/(8*PI),3*PI/2)) plano_4 = ParametricSurface( lambda u, v: np.array([ u, v, 2*PI ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=YELLOW_E,fill_opacity=0.25, resolution=(1, 1)) punto_4 = Dot(color=RED).move_to((1*4*PI/(8*PI),0,4*PI/2)) plano_5 = ParametricSurface( lambda u, v: np.array([ u, v, 5*PI/2 ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=GOLD_E,fill_opacity=0.25, resolution=(1, 1)) punto_5 = Dot(color=RED).move_to((0,1*5*PI/(8*PI),5*PI/2)) plano_6 = ParametricSurface( lambda u, v: np.array([ u, v, 3*PI ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=RED_E,fill_opacity=0.25, resolution=(1, 1)) punto_6 = Dot(color=RED).move_to((-1*6*PI/(8*PI),0,6*PI/2)) plano_7 = ParametricSurface( lambda u, v: np.array([ u, v, 7*PI/2 ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=MAROON_E,fill_opacity=0.25, resolution=(1, 1)) punto_7 = Dot(color=RED).move_to((0,-1*7*PI/(8*PI),7*PI/2)) plano_8 = ParametricSurface( lambda u, v: np.array([ u, v, 8*PI/2 ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=PURPLE_E,fill_opacity=0.25, resolution=(1, 1)) punto_8 = Dot(color=RED).move_to((1*8*PI/(8*PI),0,8*PI/2)) plano_9 = ParametricSurface( lambda u, v: np.array([ u, v, 9*PI/2 ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=PURPLE_E,fill_opacity=0.25, resolution=(1, 1)) planos = VGroup(plano_1,plano_2,plano_3,plano_4,plano_5,plano_6,plano_7,plano_8) puntos = VGroup(punto_1,punto_2,punto_3,punto_4,punto_5,punto_6,punto_7,punto_8) #Etiquetas ejes #POR EL MOVIMIENTO DE CÁMARA, TUVE QUE HACER VARIOS DEL MISMO eje_x_1 = TexMobject(r"x").scale(0.75).move_to((3.2,0.25,0)) eje_x_2 = TexMobject(r"x").scale(0.75).move_to((-2.6,1,0)) eje_x_3 = TexMobject(r"x").scale(0.75).move_to((-2.4,0.75,0)) eje_y_1 = TexMobject(r"y").scale(0.75).move_to((0.3,3.5,0)) eje_y_2 = TexMobject(r"y").scale(0.75).move_to((1,-3.3,0)) eje_y_3 = TexMobject(r"y").scale(0.75).move_to((1.3,-3.5,0)) eje_z_1 = TexMobject(r"t").scale(0.75).move_to((4.7,2,0)) eje_z_2 = TexMobject(r"t").scale(0.75).move_to((4.7,1.6,0)) ejes_1 = VGroup(eje_x_1,eje_y_1) ejes_2 = VGroup(eje_x_2,eje_y_2,eje_z_1) ejes_3 = VGroup(eje_x_3,eje_y_3,eje_z_2) #Etiquetas Planos text_plano_1 = TexMobject(r"t_1").move_to((-3.65,-3,0)).scale(0.75) text_plano_2 = TexMobject(r"t_2").move_to((-2.1,-2.4,0)).scale(0.75) text_plano_3 = TexMobject(r"t_3").move_to((-0.62,-1.9,0)).scale(0.75) text_planos_1 = VGroup(text_plano_1,text_plano_2,text_plano_3) text_plano_4 = TexMobject(r"t_4").move_to((0.7,-1.4 ,0)).scale(0.75) text_plano_5 = TexMobject(r"t_5").move_to((2,-1,0)).scale(0.75) text_plano_6 = TexMobject(r"t_6").move_to((3.15,-0.5,0)).scale(0.75) text_plano_7 = TexMobject(r"t_7").move_to((4.25,-0.05,0)).scale(0.75) text_plano_8 = TexMobject(r"t_8").move_to((5.2,0.4,0)).scale(0.75) text_planos_2 = VGroup(text_plano_4,text_plano_5,text_plano_6,text_plano_7,text_plano_8,text_plano_1,text_plano_2,text_plano_3) text_planos_i = TexMobject(r"\forall i, t_i \in A").move_to((4,-2.5,0)).scale(1.25) text_grafica_3 = TexMobject(r"G_{f}",color=YELLOW).move_to(eje_z_2.get_left()+2.5*LEFT) #EJEMPLO 3 self.add(Caja_2) self.wait(0.5) self.play(ReplacementTransform(Caja_2,Caja_3)) self.add_fixed_in_frame_mobjects(Caja_3) self.play(Write(text_3)) self.wait(9.5) self.play(FadeOut(text_3)) self.play(Write(text_4)) self.wait(8.5) self.play(FadeOut(text_4)) self.play(Write(text_5)) self.wait(7.2) self.play(FadeOut(text_5)) self.wait(0.5) self.play(FadeIn(ejemplo_3_10)) self.set_camera_orientation(phi=0) self.play(ShowCreation(axes_2),FadeIn(ejes_1)) self.wait(0.5) self.play(ShowCreation(curva_1)) self.wait(19) self.play(FadeOut(ejes_1),FadeOut(ejemplo_3_10)) self.move_camera(phi=142 * DEGREES,theta=55*DEGREES,gamma=-60*DEGREES,frame_center=(0.5,0,5),run_time=3) self.acomodar_textos(ejes_2) self.wait(2.5) self.acomodar_textos(text_6) self.wait(4) self.play(FadeOut(curva_1),FadeIn(puntos)) self.wait(0.5) self.play(FadeOut(ejes_2)) self.move_camera(phi=115*DEGREES,theta=32*DEGREES,gamma=-70*DEGREES,frame_center=(0,-0.1,6),run_time=2) self.wait() self.FadeOutWrite3D(text_6,text_7) self.wait(6.5) self.play(FadeIn(plano_1)) self.acomodar_textos(text_plano_1) self.acomodar_textos(text_planos_i) self.play(FadeIn(plano_2)) self.acomodar_textos(text_plano_2) self.FadeOutWrite3D(text_7,text_8) self.wait(6.5) self.play(FadeIn(plano_3)) self.acomodar_textos(text_plano_3) self.play(FadeIn(plano_4)) self.acomodar_textos(text_plano_4) self.FadeOutWrite3D(text_8,text_9) self.wait(5.7) self.play(FadeIn(plano_5)) self.acomodar_textos(text_plano_5) self.play(FadeIn(plano_6)) self.acomodar_textos(text_plano_6) self.FadeOutWrite3D(text_9,text_10) self.wait(8.75) self.play(FadeIn(plano_7)) self.acomodar_textos(text_plano_7) self.play(FadeIn(plano_8)) self.acomodar_textos(text_plano_8) self.play(FadeIn(plano_9)) self.play(ShowCreation(curva_1),run_time=2) self.wait(2) self.play(FadeOut(plano_9)) self.play(FadeOut(text_planos_2),FadeOut(text_planos_i),FadeOut(text_10)) self.move_camera(phi=142 * DEGREES,theta=55*DEGREES,gamma=-60*DEGREES,frame_center=(0,-0.8,5),run_time=2) self.acomodar_textos(ejes_3) self.wait(2.5) self.play(FadeOut(planos)) self.acomodar_textos(text_grafica_3) self.wait(3) self.play( *[FadeOut(mob)for mob in self.mobjects] ) self.wait()
animathica/calcanim
Límite y continuidad en funciones multivariable/visualizacion.py
visualizacion.py
py
28,718
python
es
code
19
github-code
36
36351466606
from flask import Blueprint, render_template, request import logging import functions loader_blueprint = Blueprint('loader_blueprint', __name__, template_folder="templates") logging.basicConfig(filename="basic.log") @loader_blueprint.route("/post") def post_page(): return render_template("post_form.html") @loader_blueprint.route("/uploaded", methods=['POST']) def uploaded_page(): try: content = request.form['content'] picture = request.files.get("picture") filename = picture.filename try: functions.check_extension(filename) except functions.NotAllowedExtension: return f"Данный формат файла не поддерживается" except IndexError: logging.exception("Ошибка загрузки") return f"Файл не отправлен" picture.save(f"./uploads/{filename}") pic_path = f"/uploads/{filename}" functions.save_data(pic_path, content) return render_template("post_uploaded.html", content=content, pic_path=pic_path) except PermissionError: logging.exception("Ошибка загрузки") return "Ошибка загрузки"
PetrGurev/Lesson_121_homework
loader/views.py
views.py
py
1,229
python
en
code
0
github-code
36
37421002377
#coding:utf-8 #用户输入摄氏温度 #接收用户输入 celsius = float(input("输入摄氏温度:")) #计算华氏温度 fahrenheit = (celsius*1.8) +32 print("%0.1f 摄氏温度转为华氏温度为%0.1f"%(celsius,fahrenheit)) """ #coding:utf-8 fahrenheit = float(input("输入华氏温度:")) celsius = (fahrenheit - 32)/1.8 print("%0.1f华氏温度转为摄氏温度为%0.1f" %(fahrenheit,celsius)) """
kanbujiandefengjing/python
python实例/℃to℉.py
℃to℉.py
py
437
python
zh
code
0
github-code
36
30740067431
#!/usr/bin/env python # -*- coding: utf-8 -*- import random class Lotery: """ this class is representing the process""" def __init__(self): self.ret__M = 0 self.res__M = 0 self.esp__M = 0 #retorno = step(process executou) - step(process exc = 0) def work(self, process): step = 0 inc = 0 ret = 0.0 res = 0.0 esp = 0.0 while len(process) > 0: end = 1; lst = [] for x in range(0, len(process), 1): if process[x].arr <= step: lst.append(x) i = random.randint(0, (len(lst)-1)) #print("random: "+str(i)) if process[lst[i]].start_exc < 0 : process[lst[i]].set_start_exc(step+1) res += (step - process[lst[i]].arr) if (process[lst[i]].exc == 1): process[lst[i]].dec_exc(1) step += 1 inc = 1 else: process[lst[i]].dec_exc(2) step += 2 inc = 2 if process[lst[i]].exc == 0: #print("processo: "+str(process[lst[i]].idt)+" Finalizou em "+str(step)) ret += (step - process[lst[i]].arr)+1 del process[lst[i]] for x in process: if x.arr <= step: if x.arr_aux%2 == 0 : esp += inc else: if inc == 2: esp += inc - x.arr_aux x.arr_to_pair() else: esp += inc else: for x in xrange(0,len(process)): if x != lst[i]: if process[x].arr <= step: if process[x].arr_aux%2 == 0 : esp += inc else: if inc == 2: esp += inc - process[x].arr_aux process[x].arr_to_pair() else: esp += inc return (ret, res, esp)
VictorCampelo/Operating-System-Algorithms
Process Sheduling/lotery.py
lotery.py
py
1,541
python
en
code
0
github-code
36
13168287871
import numpy as np import matplotlib from matplotlib import pyplot as plt plt.switch_backend('agg') import matplotlib.patches from scipy import stats import pandas as pd import math from mpi4py import MPI import sys import itertools import glob import os plt.ioff() design = str(sys.argv[1]) all_IDs = ['3600687', '7000550', '7200799', '7200645', '3704614', '7202003']#np.genfromtxt('../structures_files/metrics_structures.txt', dtype='str').tolist() nStructures = len(all_IDs) percentiles = np.arange(0, 100) os.chdir('../' + design) directories = glob.glob('CMIP*_*') directories.remove('CMIP3_070') os.chdir('../output_analysis') scenarios = len(directories) if design == 'CMIP_curtailment': sow = 27 else: sow = 1 idx = np.arange(2, sow*2+2, 2) historical = pd.read_csv('../structures_files/shortages.csv', index_col=0) def alpha(i, base=0.2): l = lambda x: x + base - x * base ar = [l(0)] for j in range(i): ar.append(l(ar[-1])) return ar[-1] def shortage_duration(sequence, threshold): cnt_shrt = [sequence[i] > threshold for i in range(len(sequence))] # Returns a list of True values when there's a shortage shrt_dur = [sum(1 for _ in group) for key, group in itertools.groupby(cnt_shrt) if key] # Counts groups of True values return shrt_dur def plotSDC(synthetic, histData, structure_name): n = 12 # Reshape historic data to a [no. years x no. months] matrix f_hist = np.reshape(histData, (int(np.size(histData) / n), n)) # Reshape to annual totals f_hist_totals = np.sum(f_hist, 1) # Calculate historical shortage duration curves F_hist = np.sort(f_hist_totals) # for inverse sorting add this at the end [::-1] # Reshape synthetic data # Create matrix of [no. years x no. months x no. samples] synthetic_global = np.zeros([int(len(histData) / n), n, scenarios * sow]) # Loop through every SOW and reshape to [no. years x no. months] for j in range(scenarios * sow): synthetic_global[:, :, j] = np.reshape(synthetic[:, j], (int(np.size(synthetic[:, j]) / n), n)) # Reshape to annual totals synthetic_global_totals = np.sum(synthetic_global, 1) p = np.arange(100, -10, -10) # Calculate synthetic shortage duration curves F_syn = np.empty([int(len(histData) / n), scenarios * sow]) F_syn[:] = np.NaN for j in range(scenarios * sow): F_syn[:, j] = np.sort(synthetic_global_totals[:, j]) # For each percentile of magnitude, calculate the percentile among the experiments ran perc_scores = np.zeros_like(F_syn) for m in range(int(len(histData) / n)): perc_scores[m, :] = [stats.percentileofscore(F_syn[m, :], j, 'rank') for j in F_syn[m, :]] P = np.arange(1., len(histData)/12 + 1) * 100 / (len(histData)/12) ylimit = np.max(F_syn) fig, (ax1) = plt.subplots(1, 1, figsize=(14.5, 8)) # ax1 handles = [] labels = [] color = '#000292' for i in range(len(p)): ax1.fill_between(P, np.min(F_syn[:, :], 1), np.percentile(F_syn[:, :], p[i], axis=1), color=color, alpha=0.1) ax1.plot(P, np.percentile(F_syn[:, :], p[i], axis=1), linewidth=0.5, color=color, alpha=0.3) handle = matplotlib.patches.Rectangle((0, 0), 1, 1, color=color, alpha=alpha(i, base=0.1)) handles.append(handle) label = "{:.0f} %".format(100 - p[i]) labels.append(label) #Plot 50th percentile line separately ax1.plot(P, np.percentile(F_syn[:, :], p[5], axis=1), linewidth=0.7, color=color, alpha=0.7, linestyle='dashed') ax1.plot(P, F_hist, c='black', linewidth=2, label='Historical record') ax1.set_ylim(0, ylimit) ax1.set_xlim(0, 100) ax1.legend(handles=handles, labels=labels, framealpha=1, fontsize=8, loc='upper left', title='Frequency in experiment', ncol=2) ax1.set_xlabel('Shortage magnitude percentile', fontsize=20) ax1.set_ylabel('Annual shortage (Million $m^3$)', fontsize=20) fig.suptitle('Shortage magnitudes for ' + structure_name, fontsize=16) plt.subplots_adjust(bottom=0.2) fig.savefig('../' + design + '/ShortagePercentileCurves/' + structure_name + '_' + design + '.svg') fig.savefig('../' + design + '/ShortagePercentileCurves/' + structure_name + '_' + design + '.png') fig.clf() # Begin parallel simulation comm = MPI.COMM_WORLD # Get the number of processors and the rank of processors rank = comm.rank nprocs = comm.size # Determine the chunk which each processor will neeed to do count = int(math.floor(nStructures / nprocs)) remainder = nStructures % nprocs # Use the processor rank to determine the chunk of work each processor will do if rank < remainder: start = rank * (count + 1) stop = start + count + 1 else: start = remainder * (count + 1) + (rank - remainder) * count stop = start + count for i in range(start, stop): histData = historical.loc[all_IDs[i]].values[-768:] * 1233.4818 / 1000000 synthetic = np.zeros([len(histData), scenarios * sow]) for j in range(scenarios): path = '../' + design + '/Infofiles/' + all_IDs[i] + '/' + all_IDs[i] + '_info_' + directories[j] + '.txt' data = np.loadtxt(path) synthetic[:, j * sow:j * sow + sow] = data[:, idx] * 1233.4818 / 1000000 plotSDC(synthetic, histData, all_IDs[i])
antonia-had/rival_framings_demand
output_analysis/shortage_duration_curves.py
shortage_duration_curves.py
py
5,340
python
en
code
0
github-code
36
34709810555
import random from scipy import linalg import numpy as np import scipy class Hill: def find_multiplicative_inverse(self, determinant, len_alfabeto): print(f"DETERMINANTE: {determinant}") for i in range(len_alfabeto): inverse = determinant * i if int(round(inverse % len_alfabeto, 1)) == 1: print( f"multiplicative_inverse:{i}\tlen_alfabeto:{len_alfabeto}") return i raise Exception("Não encontrado inverse multiplicative") def matrix_cofactor(self, matrix): try: determinant = np.linalg.det(matrix) if(determinant != 0): cofactor = None cofactor = np.linalg.inv(matrix).T * determinant # return cofactor matrix of the given matrix return cofactor else: raise Exception("singular matrix") except Exception as e: print("could not find cofactor matrix due to", e) def get_inverse(self, matriz, len_alfabeto): return matriz.I def mult_matrix(self, matriz1, matriz2, len_alfabeto): return matriz1 * matriz2 % len_alfabeto def normalize_text(self, text, len_matriz): len_text = len(text) resto = len_text % len_matriz if(resto != 0): for _ in range(len_matriz-resto): text = text+'o' pass else: pass # print(text) len_text = len(text) return text, len_text def one_matriz_convert(self, lenx, leny, alfabeto, text): arrays = [] for _ in range(lenx): row = [] for _ in range(leny): # print(text[0],alfabeto.index(text[0])); row.append(alfabeto.index(text[0])) text = text[1:] # print(text); pass arrays.append(row) local_matriz = np.array(arrays, dtype=np.float64) return local_matriz, text def convert_text_to_matrizes(self, text, shape, alfabeto): len_matriz = shape[0]*shape[1] text, len_text = self.normalize_text(text, len_matriz) num_natrizes = int(len_text/len_matriz) matrizes = [] for _ in range(num_natrizes): local_matriz, text = self.one_matriz_convert( shape[0], shape[1], alfabeto, text) matrizes.append(local_matriz) pass return matrizes def convert_matriz_to_text(self, matriz, alfabeto): text = '' for row in matriz.A: for col in row: text += alfabeto[int(col % len(alfabeto))] return text def encript(self, text, matriz, alfabeto): len_alfabeto = len(alfabeto) matrizes = self.convert_text_to_matrizes(text, matriz.shape, alfabeto) matriz_cripto = [] for matriz_text in matrizes: cripto = matriz_text * matriz matriz_cripto.append(cripto) cripto_text = '' for matriz_c in matriz_cripto: cripto_text += self.convert_matriz_to_text(matriz_c, alfabeto) return cripto_text def matrix_cofactor(self, matrix): return np.linalg.inv(matrix) * np.linalg.det(matrix) def get_adjungate_matrix(self, matriz, determinant): x = matriz.A c = [[i for i in range(3)] for j in range(3)] for i in range(3): for j in range(3): c[i][j] = (-1)*(i+j)*determinant def decript(self, cripto_text, matriz, alfabeto): print(cripto_text) cripto_text="syi" len_alfabeto = len(alfabeto) determinant = int(round(np.linalg.det(matriz), 1)) % len_alfabeto multiplicative_inverse = self.find_multiplicative_inverse( determinant, len_alfabeto) matriz_inv = np.conj(matriz).T cofactor = self.matrix_cofactor( matriz) % len_alfabeto invert_key_matrix = cofactor*multiplicative_inverse%len_alfabeto print( f"det:{determinant}\tinverse:{multiplicative_inverse}\tinv:{invert_key_matrix}\ncofactor:\n{cofactor}") matriz_inv = matriz_inv*multiplicative_inverse matrizes_cript = self.convert_text_to_matrizes( cripto_text, matriz.shape, alfabeto) matriz_decripto = [] for matriz_text in matrizes_cript: decripto = self.mult_matrix(matriz_text, invert_key_matrix, len_alfabeto) matriz_decripto.append(decripto) decripto_text = '' for matriz_d in matriz_decripto: decripto_text += self.convert_matriz_to_text(matriz_d, alfabeto) return decripto_text def testando_fatores_iniciais(alfabeto): hill = Hill() len_alfabeto = len(alfabeto) matriz2 = np.array([[2, 2], [14, 26]], dtype=np.float64) # print(f"Testando fatores Iniciais\n {'_'*100}") matriz = np.array([[9, 4], [5, 7]], dtype=np.float64) print(f"matriz: \n{matriz}") matriz_inv = hill.get_inverse(matriz, len(alfabeto)) print(f"Inversa:\n{matriz_inv}") print( f"Matriz e Inversa: \n{hill.mult_matrix(matriz, matriz_inv, len_alfabeto)}") print(f"Testando criptografia e decriptografia\n{'&'*100}") print(matriz2) cripto = hill.mult_matrix(matriz2, matriz, len_alfabeto) print(cripto) decripto = hill.mult_matrix(cripto, matriz_inv, len_alfabeto) print(decripto) return matriz_inv hill = Hill() alfabeto = 'abcdefghijklmnopqrstuvwxyz' if(__name__ == '__main__'): matriz = np.matrix([[1, 0, 2], [10, 20, 15], [0, 1, 2]], dtype=np.float64) chave = 'cabababababasdaba' text = input() text = text.replace(' ', '') text="ret" print(f"PLAIN_TEXT: {text}") cripto_text = hill.encript(text, matriz, alfabeto) matriz_inv = hill.get_inverse(matriz, len(alfabeto)) print(f"CRIPTED_TEXT: {cripto_text}") cripto_text ="syi" matriz = np.matrix([[0, 11, 15], [7, 0, 1], [4, 19, 0]], dtype=np.float64) print(f"Decriptando:") decripto_text = hill.decript(cripto_text, matriz, alfabeto) print(decripto_text)
andersoney/andersoney
criptografia/hills/hills.py
hills.py
py
6,232
python
pt
code
0
github-code
36
40306775358
import numpy as np import pandas as pd from collections import OrderedDict import matplotlib as mlt import matplotlib.pyplot as plt from scipy import optimize def get_data(): data = OrderedDict( amount_spent = [50, 10, 20, 5, 65, 70, 80, 81, 1], send_discount = [0, 1, 1, 1, 0, 0, 0, 0, 1] ) df = pd.DataFrame.from_dict(data) # creating a dataframe X = df['amount_spent'].astype('float').values # converting the type to 'float' y = df['send_discount'].astype('float').values # converting the type to 'float' return (X,y) # returning the X , y def get_theta(costFunction , X , y , iter = 400): options = {'maxiter':iter} # maximum number of iterations row , col = X.shape initial_theta = np.zeros(col) res = optimize.minimize( costFunction, initial_theta , (X,y), jac=True, method='TNC', options = options ) # the fun property of `OptimizeResult` object returns # the value of costFunction at optimized theta cost = res.fun # the optimized theta is in the x property theta = res.x return ( cost , theta ) def sigmoid(z): # convert input to a numpy array z = np.array(z) g = np.zeros(z.shape) g = 1 / (1 + np.exp(-z)) return g def costFunction(theta, X, y): m = y.size # number of training examples J = 0 grad = np.zeros(theta.shape) # h = sigmoid(X.dot(theta.T)) # sigmoid function J = (1 / m) * np.sum(-y.dot(np.log(h)) - (1 - y).dot(np.log(1 - h))) grad = (1 / m) * (h - y).dot(X) return J, grad def load_data(url): df=pd.read_csv(url,header=None); return ( df.iloc[:,:-1] , df.iloc[:,-1]) def run(): X , y = load_data('./marks.txt') ones = X[y==1] # features X where y == 1 zeros = X[y==0] # features X where y == 0 #X,y = get_data() row , col = X.shape # Add intercept term to X X = np.concatenate([np.ones((row, 1)), X], axis=1) (cost,theta)=get_theta(costFunction , X , y ) print('cost => {} , theta => {}'.format(cost,theta) ) #print(' x ',X[:,1:3]) # prints col 0 , 1 # calculate min of X - 2 , max of X + 2 x_treme = np.array([ np.min(X[:,1]) - 2 , np.max(X[:,1]) + 2 ]) # calculate y extreme #y_treme = (-1. / theta[2]) * ( theta[1] * x_treme + theta[0] ) y_treme = - (( np.dot(theta[1] ,x_treme) ) + theta[0] ) / theta[2] plt.plot(x_treme , y_treme) plt.scatter(ones[0],ones[1] , label="1's ") plt.scatter(zeros[0],zeros[1], label="0's ") plt.legend(loc="upper right") plt.show() if __name__ == "__main__": run()
guruprasaad123/ml_for_life
from_scratch/logistic_regression/Newtons method/optimize.py
optimize.py
py
2,692
python
en
code
4
github-code
36
1763129188
""" Implements a mixin for remote communication. """ import re import json import socket whitespace_re = re.compile(r"\s+") class RemoteActor: ENCODING = "utf-8" DECODER = json.JSONDecoder() def __init__(self, socket): """ Creates a new remote actor able to send and receive from the given socket :param socket: socket connection """ self.socket = socket self.buffer = "" def parse(self, clear_on_partial=False): print(self.buffer) try: decoded, end = self.DECODER.raw_decode(self.buffer) except ValueError: print(self.buffer, "va") return False, False, False if not isinstance(decoded, bool) and (isinstance(decoded, int) or isinstance(decoded, float)) and end == len(self.buffer): if clear_on_partial: self.buffer = self.buffer[end:] return True, False, decoded else: print(decoded, "blah") self.buffer = self.buffer[end:] return True, True, decoded def send(self, data): """ Sends the given JSON object to the socket :param data: JSON object """ encoded = json.dumps(data).encode(self.ENCODING) self.socket.send(encoded) def receive(self): """ Continuously receives bytes until a JSON object can be deserialized, at which point the deserialized object is returned. It is up to the caller to restrict the execution time. :return: deserialized JSON object """ data = bytes() while True: try: data += self.socket.recv(1) except socket.timeout: something, complete, decoded = self.parse(True) print(something, complete, decoded) if something: return decoded raise try: decoded = data.decode(self.ENCODING) self.buffer += decoded data = bytes() except UnicodeDecodeError: continue something, complete, decoded = self.parse() if something and complete: return decoded def receive_iterator(self): """ Continuously receives data and deserializes JSON objects as they come in """ while True: yield self.receive()
lukasberger/evolution-game
evolution/common/remote_actor_2.py
remote_actor_2.py
py
2,413
python
en
code
0
github-code
36
432875678
import numpy as np from torch.utils import data import torch as t import matplotlib.pyplot as plt import h5py from .utils.utils import mat2gray_nocrop, plot_img_with_labels import os import random import ipdb from .visualize_predictions import draw_label_img from scipy.ndimage import gaussian_filter import monai def torch_randint(max_v): return t.randint(max_v, (1, 1)).view(-1).numpy()[0] def torch_rand(size=1): return t.rand(size).numpy() def augmentation(img, mask): img = img.numpy() mask = mask.numpy() r = [torch_randint(2), torch_randint(2), torch_randint(4)] if r[0]: img = np.fliplr(img) mask = np.fliplr(mask) if r[1]: img = np.flipud(img) mask = np.flipud(mask) img = np.rot90(img, k=r[2]) mask = np.rot90(mask, k=r[2]) # min_v = (torch_rand() * 0.96) - 0.48 # max_v = 1 + (torch_rand() * 0.96) - 0.48 # for k in range(img.shape[-1]): # img[:, :, k] = mat2gray_nocrop(img[:, :, k], [min_v, max_v]) - 0.5 """ r = [torch_randint(2), torch_randint(2), torch_randint(4)] if r[0]: img = np.fliplr(img) mask = np.fliplr(mask) if r[1]: img = np.flipud(img) mask = np.flipud(mask) img = np.rot90(img, k=r[2]) mask = np.rot90(mask, k=r[2]) img = img.numpy() min_v = (torch_rand() * 0.96) - 0.48 max_v = 1 + (torch_rand() * 0.96) - 0.48 for k in range(img.shape[2]): img[:, :, k] = mat2gray_nocrop(img[:, :, k], [min_v, max_v]) - 0.5 """ """ tmp_img = t.cat([img, label_img], dim=-1) transforms = monai.transforms.Compose( monai.transforms.RandAxisFlipd(keys=["image"], prob=0.5), monai.transforms.RandRotate90d(keys=["image"], prob=0.5), monai.transforms.RandGridDistortiond( keys=["image"], prob=0.5, distort_limit=0.2 ), monai.transforms.OneOf( [ monai.transforms.RandShiftIntensityd( keys=["image"], prob=0.5, offsets=(0.1, 0.2) ), # monai.transforms.RandAdjustContrastd( # keys=["image"], prob=0.5, gamma=(1.5, 2.5) # ), # monai.transforms.RandHistogramShiftd(keys=["image"], prob=0.5), ] ), ) uba = transforms(dict(image=tmp_img)) img = uba["image"][:, :, :3] # print(f"{img.shape=}") label_img = uba["image"][:, :, -2:] # print(f"{label_img.shape=}") """ """ if t.rand(1)[0] > 0.5: img = t.flipud(img) label_img = t.flipud(label_img) if t.rand(1)[0] > 0.5: img = t.fliplr(img) label_img = t.fliplr(label_img) if t.rand(1)[0] > 0.5: ''' img = img + t.randn(img.shape) * 0.05 img = t.clamp(img, 0, 1) ''' if t.rand(1)[0] > 0.5: times = t.randint(4, (1,))[0] img = t.rot90(img, k=times) label_img = t.rot90(label_img, k=times) """ return t.from_numpy(img.copy()), t.from_numpy(mask.copy()) class FociDataset(data.Dataset): def __init__( self, *, hdf5_filename: str, filenames: tuple[str, ...], split: str, crop_size: tuple[int, int], out_len: int, ): self.hdf5_filename = hdf5_filename self.split = split self.crop_size = crop_size self.filenames = filenames self.out_len = out_len self.h5data = None def __len__(self): return len(self.filenames) def __getitem__(self, idx): if self.h5data is None: self.h5data = h5py.File(self.hdf5_filename, "r") filename = self.filenames[idx] img = t.from_numpy(self.h5data[filename + "_image"][...]).permute( 1, 2, 0 ) label = t.from_numpy(self.h5data[filename + "_label"][...]).permute( 1, 2, 0 ) in_size = img.shape out_size = self.crop_size if not self.split == "test": r = [ t.randint(in_size[i] - out_size[i], (1,))[0] for i in range(2) ] img = img[ r[0] : r[0] + out_size[0], r[1] : r[1] + out_size[1], :, ] label = label[ r[0] : r[0] + out_size[0], r[1] : r[1] + out_size[1], :, # TODO: check this. Why do I need to swap the order of the two indices??? ] if self.split == "train": img, label = augmentation(img, label) img = img.permute(2, 0, 1).float() label = label.permute(2, 0, 1).float() return img, label
SalamanderXing/dna_foci_detection
dna_foci_detection/data_loaders/foci/dataset.py
dataset.py
py
4,646
python
en
code
0
github-code
36
25418445648
#!/usr/bin/env python from utils.analysis import AbsMovingAvg, Threshold, Derivative from utils.chaser import Chaser import os import sys parentDir = os.path.dirname(os.getcwd()) sys.path.append(parentDir) def checkImport(lib): if not os.path.exists(os.path.join(parentDir, lib)): print("%s library not found." % lib) print("please clone github.com/andrewbooker/%s.git into %s" % (lib, parentDir)) exit() checkImport("mediautils") from mediautils.mididevices import UsbMidiDevices, MidiOut ## ===== composer ===== checkImport("compositionutils") from compositionutils.scale import Scale, Modes tonic = "C" mode = "aeolian" print(tonic, mode) noteSpan = 15 scale = Scale(noteSpan, tonic, Modes.named(mode)) class Consumer(): def __init__(self, midiOut): self.midiOut = midiOut self.note = 0 def on(self, velocity): self.note = scale.noteFrom(int(velocity * 100) % noteSpan) self.midiOut.note_on(self.note, int(26 + (velocity * 100)), 0) def off(self): self.midiOut.note_off(self.note, 0, 0) ## ===== midiDevices = UsbMidiDevices() midiOut = MidiOut(midiDevices) consumer = Consumer(midiOut.io) chaser = Chaser(consumer, 0.6, 0.2) import soundfile as sf infile = sys.argv[1] workingDir = os.path.dirname(infile) print("loading %s" % infile) (data, sampleRate) = sf.read(infile, dtype="float32") for s in range(len(data)): chaser.add(data[s]) del midiOut del midiDevices print("done")
andrewbooker/audiotomidi
scanWavFile.py
scanWavFile.py
py
1,495
python
en
code
1
github-code
36
28515039147
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.logger import logger from opus_core.resources import Resources from opus_core.storage_factory import StorageFactory from numpy import array import os class GenerateTestData(object): """ I don't think this is used anywhere """ def run(self, config, year, *args, **kwargs): """ """ logger.start_block('Starting GenerateTestData.run(...)') cache_dir_w_year = os.path.join(config['cache_directory'],year.__str__()) storage = StorageFactory().get_storage('flt_storage', storage_location = cache_dir_w_year ) storage.write_table(table_name = 'persons', table_data = {'person_id': array([1,2,3]), 'household_id': array([1,2,3]), 'job_id': array([4,5,6]) } ) storage.write_table(table_name = 'households', table_data = {'household_id': array([1,2,3]), 'building_id': array([1,2,3]), } ) storage.write_table(table_name = 'jobs', table_data = {'job_id': array([4,5,6]), 'building_id': array([4,5,6]), } ) storage.write_table(table_name = 'buildings', table_data = {'building_id': array([1,2,3,4,5,6]), 'parcel_id': array([1,2,3,4,5,6]), } ) storage.write_table(table_name = 'parcels', table_data = {'parcel_id': array([1,2,3,4,5,6]), 'x_coord_sp': array([1.,2.,3.,4.,5.,6.]), 'y_coord_sp': array([1.,2.,3.,4.,5.,6.]), 'zone_id': array([1,1,1,3,3,3]), } ) logger.end_block() # the following is needed, since it is called as "main" from the framework ... if __name__ == "__main__": try: import wingdbstub except: pass from optparse import OptionParser from opus_core.file_utilities import get_resources_from_file parser = OptionParser() parser.add_option("-r", "--resources", dest="resources_file_name", action="store", type="string", help="Name of file containing resources") parser.add_option("-y", "--year", dest="year", action="store", type="int", help="Year in which to 'run' the travel model") (options, args) = parser.parse_args() resources = Resources(get_resources_from_file(options.resources_file_name)) logger.enable_memory_logging() GenerateTestData().run(resources, options.year)
psrc/urbansim
opus_matsim/archive/tests/generate_test_data.py
generate_test_data.py
py
3,310
python
en
code
4
github-code
36
20871041067
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import logic UI_BOARD_SIZE = (8, 6) UI_BOARD_OFFSET = 0.25 UI_BOARD_CELL_COLORS = [(0,0,0,0.4), (0,0.9,1,0.7)] ''' UI front-end implementation ''' class Board: def __init__(self): # Create figure and axes self.fig, self.ax = plt.subplots(figsize=UI_BOARD_SIZE) # Board background color self.ax.set_facecolor((0,0,0,0.15)) # Hiding axes self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) # Scale axes self.ax.set_xlim([0,1]) self.ax.set_ylim([0,1]) self.ax.set_aspect('equal', adjustable='box') # Board cells self.patches = [] # Last board state - needed for differential update of board self.last_state = None # Connect to UI for mouse click event connection_id = self.fig.canvas.mpl_connect('button_press_event', self.on_click_cell) self.on_click_event_handler = None # Generation label self.lbl_generation = None # Next generation button axnext = plt.axes([0.45, 0.9, 0.2, 0.075]) self.bnext = plt.Button(axnext, 'Next', color=(0, 1, 0.7, 0.7), hovercolor=(0, 1, 0.7, 1)) self.bnext.label.set_fontsize(16) self.bnext.on_clicked(self.on_click_btn_next) # Reset button axreset = plt.axes([0.25, 0.9, 0.1, 0.075]) self.breset = plt.Button(axreset, 'Reset', color=(1, 0.2, 0, 0.7), hovercolor=(1, 0.2, 0, 1)) self.breset.label.set_fontsize(16) self.breset.on_clicked(self.on_click_btn_reset) def on_click_btn_next(self, event): if self.on_click_event_handler is None: raise ValueError self.on_click_event_handler(logic.EVENT_NEXT_CLICK) def on_click_btn_reset(self, event): if self.on_click_event_handler is None: raise ValueError self.on_click_event_handler(logic.EVENT_RESET_CLICK) def on_click_cell(self, event): if not event.inaxes == self.ax: return # Left mouse button click to change cell state if event.button == 1: x = int(np.floor((event.xdata - self.cell_margin[0]) / self.cell_width)) y = int(np.floor((event.ydata - self.cell_margin[1]) / self.cell_height)) if self.on_click_event_handler is None: raise ValueError self.on_click_event_handler(logic.EVENT_CELL_CLICK, data=(x, y)) def set_click_event_handler(self, handler): self.on_click_event_handler = handler def redraw_board(self, state): # Update cell size and margin self.cell_width = 1. / state.shape[0] self.cell_height = 1. / state.shape[1] self.cell_margin = (self.cell_width * 0.05, self.cell_height * 0.05) # Remove all previously drawn patches [p.remove() for p in reversed(self.ax.patches)] # Add new patches for x in range(state.shape[0]): for y in range(state.shape[1]): rect = patches.Rectangle((x*self.cell_height + self.cell_margin[1], y*self.cell_width + self.cell_margin[0]), self.cell_width*0.9, self.cell_height*0.9, fill=True, facecolor=UI_BOARD_CELL_COLORS[state[x, y]]) self.ax.add_patch(rect) self.patches = self.ax.patches # Update last state self.last_state = state.copy() plt.show() def redraw_ui_elements(self, generation=None): # UI elements, status, buttons if not generation is None: if not self.lbl_generation is None: self.lbl_generation.remove() self.lbl_generation = self.ax.annotate('%d' % generation, color='k', weight='bold', fontsize=16, ha='center', va='center', xy=(0.95, 1.08), xycoords=self.ax.transAxes, annotation_clip=False) def redraw(self, state, generation=None): # Redraw game board self.redraw_board(state) # UI elements, status, buttons if not generation is None: self.redraw_ui_elements(generation) def update(self, state, generation=None): # Redraw entire board if state dimension has changed if self.last_state is None or state.size != self.last_state.size: self.redraw(state, generation) # Update only those cells, that have changed since last state diff = np.subtract(state, self.last_state) changed_idx = list(zip(*diff.nonzero())) for xy in changed_idx: self.patches[xy[0] * state.shape[0] + xy[1]].set_facecolor(UI_BOARD_CELL_COLORS[state[xy[0], xy[1]]]) # Update last state self.last_state = state.copy() # UI elements, status, buttons if not generation is None: self.redraw_ui_elements(generation) plt.show()
manu-ho/game_of_life
board.py
board.py
py
5,007
python
en
code
0
github-code
36
72170355625
import pandas as pd import pickle from pathlib import Path def preprocess_test_df(test_clin_df, test_prot_df, test_pep_df, save_data=False): if 'upd23b_clinical_state_on_medication' in test_clin_df.columns: # drop the medication column test_clin_df = test_clin_df.drop(columns=['upd23b_clinical_state_on_medication']) # create a column with the UniProt and Peptide name combined test_pep_df['peptide_uniprot'] = test_pep_df['Peptide'] + '_'+ test_pep_df['UniProt'] # create a table with the visit_id as the index and the proteins or peptides as the feature and the abundance as the values train_prot_pivot = test_prot_df.pivot(index='visit_id', values='NPX', columns='UniProt') train_pep_pivot = test_pep_df.pivot(index='visit_id', values='PeptideAbundance', columns='peptide_uniprot') # combine the two tables on the visit_id full_prot_train_df = train_prot_pivot.join(train_pep_pivot) # fill nan with 0 full_prot_train_df = full_prot_train_df.fillna(0) full_train_df = test_clin_df.merge(full_prot_train_df, how='inner', left_on='visit_id', right_on='visit_id') full_train_df = full_train_df.sample(frac=1).reset_index(drop=True) return full_train_df test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test.csv') prot_test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test_proteins.csv') pep_test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test_peptides.csv') full_test_df = preprocess_test_df(test_df, prot_test_df, pep_test_df, save_data=False) updr = 'updrs_1' month = 0 for updr in ['updrs_1', 'updrs_2', 'updrs_3', 'updrs_4']: updr_df = full_test_df[full_test_df['updrs_test'] == updr] info_cols = ['visit_id', 'visit_month', 'patient_id', 'updrs_test', 'row_id', 'group_key'] updr_info = updr_df[info_cols] model_df = updr_df.drop(columns=info_cols) for month in [0, 6, 12, 24]: # Load the saved model from file model_path = Path('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/models/model_rf_reg_updrs_1_0.pkl') with open(model_path, 'rb') as f: rf_reg = pickle.load(f) # Use the imported model to make predictions y_pred = rfc.predict(model_df) target = 'updrs_4' train_df = pd.read_csv(f'~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/processed/train_{target}.csv') train_df.head()
dagartga/Boosted-Models-for-Parkinsons-Prediction
src/data/pred_pipeline.py
pred_pipeline.py
py
2,509
python
en
code
0
github-code
36
26255667961
""" Here I will read access tokens from txt file for safety """ import json class Token: def __init__(self): with open('tokens.json', 'r') as f: data = json.loads(f.readline()) self.community = data['comm_token'] self.user = data['usr_token'] self.comm_id = -167621445 self.usr_id = 491551942 if __name__=='__main__': t = Token()
maxikfu/community
auth.py
auth.py
py
393
python
en
code
0
github-code
36
86340516810
from openpyxl import load_workbook # from openpyxl.cell import Cell if __name__ == '__main__': wb = load_workbook('data/FINODAYS_Доп. материал для Почта Банк_Диалоги.xlsx') for sn in wb.sheetnames: print(sn) marks = [] for row in wb[sn]: if row[1].value == 'CLIENT': print(row[2].value) elif row[2].value.startswith('Оценка'): marks.append(row[2].value) print('Оценки:', *marks, end='\n' + '-' * 50 + '\n')
eivankin/finodays-2nd-stage
get_user_messages.py
get_user_messages.py
py
546
python
en
code
0
github-code
36
40689449383
with open("2021\Day_14\input.txt") as f: template = f.readline().strip() elements = {e.split()[0]:e.split()[-1] for e in f.read().splitlines() if e != ""} # # Example data # template = "NNCB" # elements = { # "CH": "B", # "HH": "N", # "CB": "H", # "NH": "C", # "HB": "C", # "HC": "B", # "HN": "C", # "NN": "C", # "BH": "H", # "NC": "B", # "NB": "B", # "BN": "B", # "BB": "N", # "BC": "B", # "CC": "N", # "CN": "C", # } steps = 10 for s in range(steps): temp = "" for t in range(len(template)-1): part = template[t:t+2] temp += part[0]+ elements[part] template = temp + template[-1] counts = dict.fromkeys(template,0) counts = {c:template.count(c) for c in counts.keys()} print(max(counts.values())-min(counts.values()))
furbank/AdventOf
2021/Day_14/part1.py
part1.py
py
823
python
en
code
0
github-code
36
5538635649
# drawing the Earth on equirectangular projection import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature import numpy import matplotlib.ticker as mticker fig = plt.figure(figsize=(64,32), frameon=False) ax = fig.add_subplot(1,1,1, projection=ccrs.PlateCarree(central_longitude=180)) ax.set_global() #ax.stock_img() #ax.coastlines(resolution='50m') ax.add_feature(cfeature.NaturalEarthFeature('physical', 'ocean', '50m', edgecolor='face', facecolor=cfeature.COLORS['water'])) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', edgecolor='face', facecolor=cfeature.COLORS['land'])) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'lakes', '50m', edgecolor='face', facecolor=cfeature.COLORS['water'])) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', '50m', edgecolor=cfeature.COLORS['water'], facecolor='none')) ax.add_feature(cfeature.NaturalEarthFeature('cultural', 'admin_0_countries', '50m', edgecolor='gray', facecolor='none')) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, linewidth=1, alpha=0.8) gl.xlocator = mticker.FixedLocator(list(range(0,361,60))) gl.ylocator = mticker.FixedLocator(list(range(-90,91,30))) plt.subplots_adjust(left=0, right=1, bottom=0, top=1) plt.savefig("earth-equirectanguler3.png", dpi=8192/64)
shuyo/xr
earth.py
earth.py
py
1,349
python
en
code
0
github-code
36
31063851875
from ..utils import Object class MessageReplyInfo(Object): """ Contains information about replies to a message Attributes: ID (:obj:`str`): ``MessageReplyInfo`` Args: reply_count (:obj:`int`): Number of times the message was directly or indirectly replied recent_replier_ids (List of :class:`telegram.api.types.MessageSender`): Identifiers of at most 3 recent repliers to the message; available in channels with a discussion supergroupThe users and chats are expected to be inaccessible: only their photo and name will be available last_read_inbox_message_id (:obj:`int`): Identifier of the last read incoming reply to the message last_read_outbox_message_id (:obj:`int`): Identifier of the last read outgoing reply to the message last_message_id (:obj:`int`): Identifier of the last reply to the message Returns: MessageReplyInfo Raises: :class:`telegram.Error` """ ID = "messageReplyInfo" def __init__(self, reply_count, recent_replier_ids, last_read_inbox_message_id, last_read_outbox_message_id, last_message_id, **kwargs): self.reply_count = reply_count # int self.recent_replier_ids = recent_replier_ids # list of MessageSender self.last_read_inbox_message_id = last_read_inbox_message_id # int self.last_read_outbox_message_id = last_read_outbox_message_id # int self.last_message_id = last_message_id # int @staticmethod def read(q: dict, *args) -> "MessageReplyInfo": reply_count = q.get('reply_count') recent_replier_ids = [Object.read(i) for i in q.get('recent_replier_ids', [])] last_read_inbox_message_id = q.get('last_read_inbox_message_id') last_read_outbox_message_id = q.get('last_read_outbox_message_id') last_message_id = q.get('last_message_id') return MessageReplyInfo(reply_count, recent_replier_ids, last_read_inbox_message_id, last_read_outbox_message_id, last_message_id)
iTeam-co/pytglib
pytglib/api/types/message_reply_info.py
message_reply_info.py
py
2,077
python
en
code
20
github-code
36
31352733665
# Import all the modules to determine the cofusion matrix import itertools import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import os # This function calculates the confusion matrix and visualizes it def plot_confusion_matrix(y_test, y_pred, file_path, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ Calculates and plots a confusion matrix from the given labels Parameters ---------- y_test: list Already given labels y_pred: Predictions made by the model file_path: str Name of the of the file where the results should be stored, together with a path nomralize: bool Whether the confusion matrix should ne bormalized title: str Whether the plot should have any special title cmap: plt.cm.* What cholor scheme should be used for plotting Returns ------- An image of confusion matrix """ cm = confusion_matrix(y_test, y_pred) np.set_printoptions(precision=2) classes_pred = [str(i) for i in np.unique(y_pred)] classes_test = [str(i) for i in np.unique(y_test)] classes = None if len(classes_pred)>len(classes_test): classes = classes_pred else: classes = classes_test # In case the confusion matrix should be normalized if normalize: t = cm.sum(axis=1)[:, np.newaxis] for i in t: if i[0] == 0: i[0] = 1 cm = cm.astype('float') / t plt.figure() plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() thresh = cm.max() / 2.0 plt.tight_layout() plt.xticks([], []) plt.yticks([], []) plt.ylabel('True label') plt.xlabel('Predicted label') plt.savefig("{}.png".format(file_path)) plt.close()
martinferianc/PatternRecognition-EIE4
Coursework 2/post_process.py
post_process.py
py
1,935
python
en
code
1
github-code
36
4313052823
import torch from gms_loss import * from PIL import Image from torchvision import transforms from gms_loss import MSGMS_Loss image_path_1= './lj_test_image/1118_visdon_HR_downsampling_2loss_visstyle/0_SR_x_1105_4.png' image_path_2 = './lj_test_image/1116_tcl_bright/6_SR_x_1105_4.png' img_ycbcr_1 = Image.open(image_path_1).convert('YCbCr') img_y_1, img_cb_1, img_cr_1 = img_ycbcr_1.split() img_ycbcr_2 = Image.open(image_path_2).convert('YCbCr') img_y_2, img_cb_2, img_cr_2 = img_ycbcr_2.split() img_y_1 = img_y_1.crop((0,0, 100, 200)) img_y_2 = img_y_2.crop((0,0, 100, 200)) transform = transforms.ToTensor() Ir = transform(img_y_1).unsqueeze(0) Ii = transform(img_y_2).unsqueeze(0) print(Ir.size()) # print(Ir.size()) loss = MSGMS_Loss() y = loss.forward(Ii, Ir) print(y)
JOY2020-Mh/SR_2.0
gsmd_LOSS/image_calculate_gmsd.py
image_calculate_gmsd.py
py
795
python
en
code
0
github-code
36
20219614528
# match close atoms in two moleculas by maximum weighted bipartite matching import numpy as np import logging # weights - numpy 2-dimensional array def wbm(weights): import pulp pulp.LpSolverDefault.msg = False prob = pulp.LpProblem("WBM_Problem", pulp.LpMinimize) m,n = weights.shape # print(m,n) from_nodes = np.arange(m); to_nodes = np.arange(n) # Create The Decision variables choices = pulp.LpVariable.dicts("e",(from_nodes, to_nodes), 0, 1, pulp.LpInteger) # Add the objective function prob += pulp.lpSum([weights[u][v] * choices[u][v] for u in from_nodes for v in to_nodes]), "Total weights of selected edges" # Constraint set ensuring that the total from/to each node # is less than its capacity (= 1) ind1 = np.argsort(weights[:,0].reshape(-1)) # print(ind1) ind2 = np.argsort(weights[0,:].reshape(-1)) if from_nodes.size >= to_nodes.size: for v in to_nodes: prob += pulp.lpSum([choices[u][v] for u in from_nodes]) == 1, "" for i in range(m): #if i < n//2: if i < 0: prob += pulp.lpSum([choices[from_nodes[ind1[i]]][v] for v in to_nodes]) == 1, "" else: prob += pulp.lpSum([choices[from_nodes[ind1[i]]][v] for v in to_nodes]) <= 1, "" else: for u in from_nodes: prob += pulp.lpSum([choices[u][v] for v in to_nodes]) == 1, "" for i in range(n): #if i < m//2: if i < 0: prob += pulp.lpSum([choices[u][to_nodes[ind2[i]]] for u in from_nodes]) == 1, "" else: prob += pulp.lpSum([choices[u][to_nodes[ind2[i]]] for u in from_nodes]) <= 1, "" # The problem is solved using PuLP's choice of Solver prob.solve() # The status of the solution is printed to the screen # print( "Status:", pulp.LpStatus[prob.status]) # Each of the variables is printed with it's resolved optimum value # for v in prob.variables(): # if v.varValue > 1e-3: # print(f'{v.name} = {v.varValue}') # print(f"Sum of wts of selected edges = {round(pulp.value(prob.objective), 4)}") # print selected edges selected_from = [v.name.split("_")[1] for v in prob.variables() if v.value() > 1e-3] selected_to = [v.name.split("_")[2] for v in prob.variables() if v.value() > 1e-3] selected_edges = [] resultInd = np.zeros(m, dtype='int32')-1 for su, sv in list(zip(selected_from, selected_to)): resultInd[int(su)] = int(sv) selected_edges.append((su, sv)) resultIndExtra = np.copy(resultInd) forget = np.setdiff1d(np.arange(n), selected_to) if forget.size>0: resultIndExtra = np.concatenate([resultIndExtra,forget]) return resultInd, resultIndExtra
gudasergey/pyFitIt
pyfitit/wbm.py
wbm.py
py
2,829
python
en
code
28
github-code
36
70744489704
import fileinput import glob import os import random import time import re from urllib.error import HTTPError from arghandler import ArgumentHandler, subcmd from google import search from subprocess import call from procurer import ultimate_guitar, lastfm, postulate_url from rules import rules, clean from songbook_converter import SongBook, wrap, header from writer import TexWriter, PdfWriter, FileWriter def url(keyword): searchterm = "site:ultimate-guitar.com chords " + keyword results = search(searchterm, stop=10) for url in results: if 'search' not in url: return url raise ArithmeticError import codecs def filter_existing(lines): keywords = set(x for x in lines if not find_file_for_keyword(x)) excluded = lines - keywords if excluded: print("Not adding some files ( use --force to override):") for item in excluded: print(item, find_file_for_keyword(item)) print("Still looking for") for item in keywords: print(item, find_file_for_keyword(item)) return keywords def addsongs(keywords): written = [] working = 1 for line in keywords: if not working: written.append(line) continue try: source = url(line) artist, title, blob = ultimate_guitar(source) FileWriter(artist, title, blob, directory='raw/', extension='txt').write() except HTTPError: working = 0 print("Google said fuck you") except Exception as e: print("Couldn't add " + line) print(e) written.append(line) return written def find_file_for_keyword(keyword): globs = (filename.split("\\")[-1][:-5] for filename in glob.glob('reviewed/**')) for filename in globs: if keyword.lower() in filename.lower(): return True if filename.lower() in keyword.lower(): return True return False @subcmd def edit(parser, context, args): matching_files = find_file_for_keyword("".join(args)) if len(matching_files) == 1: call(["texmaker", matching_files[0]]) @subcmd def add(parser, context, args): source = url(args) artist, title, blob = ultimate_guitar(source) FileWriter(artist, title, blob, directory='raw/', extension='txt').write() @subcmd def addfile(parser, context, args): lines = set(line.strip() for line in open(args[0])) keywords = lines added = addsongs(keywords) with open("written.txt", "w") as f: f.write("\n".join(added)) cleanraw(parser,context,()) def files(directory): for file in glob.glob(directory + "*"): with codecs.open(file, encoding='utf-8')as f: artist, title = os.path.split(file)[-1][:-4].split(" - ") song = f.read() yield artist, title, song @subcmd def maketex(parser, context, args=('clean',)): if not len(args): args=('clean',) for artist, title, blob in files(args[0] + "/"): converter = SongBook(artist, title, blob) latex = converter.produce_song() TexWriter(artist, title, latex, directory="library/").write() @subcmd def cleanraw(parser, context, args=('raw',)): if not len(args): args = ('raw',) for artist, title, blob in files(args[0] + "/"): blob = clean(blob) if not "[" in blob: blob = "[Instrumental]\n" + blob FileWriter(artist, title, blob, directory='clean/', extension='txt').write() for artist, title, blob in files("clean/"): blob = clean(blob) if not "[" in blob: blob = "[Instrumental]\n" + blob FileWriter(artist, title, blob, directory='clean/', extension='txt').write() @subcmd def makepdf(parser, context, args=('library',)): if not len(args): args=('library',) latex = (line for line in fileinput.input(glob.glob(args[0] + '/*.tex'), openhook=fileinput.hook_encoded("utf-8"))) latex = header() + wrap("document", "\n".join(latex)) print([(sym,ord(sym)) for sym in latex if ord(sym)>1000]) PdfWriter("Sebastian", "Songbook", latex).write() @subcmd def reviewtopdf(parser, context, args): print("Making tex") maketex(parser,context,('reviewed',)) print("Making pdf") makepdf(parser,context,args=('library',)) if __name__ == "__main__": handler = ArgumentHandler() handler.run()
arpheno/songbook
main.py
main.py
py
4,443
python
en
code
0
github-code
36
10302743850
import pandas as pd import numpy as np f = open("u.user", 'r') d = f.readlines() f.close() n = np.array(d) user_index = ["user id", "age", "gender", "occupation", "zip_code"] user = np.char.strip(n) user = np.char.split(user, '|', 4) user_df = pd.DataFrame(list(user), columns=user_index) user_df["user id"] = user_df["user id"].astype('int') f = open("u.data", 'r') d = f.readlines() f.close() n = np.array(d) data = np.char.strip(n) data = np.char.split(data, '\t') data_index = ["user id", "movie id", "rating", "timestamp"] data_df = pd.DataFrame(list(data), columns=data_index) for col in data_index: data_df[col] = data_df[col].astype('int') data_df = data_df.drop(['timestamp'], axis=1) f = open("u.item", 'r', encoding="ISO-8859-1") d = f.readlines() f.close() n = np.array(d) item_index = ['movie id', 'movie title', 'release date', 'video release date', 'IMDb URL', 'unknown', 'Action', 'Adventure', 'Animation', "Children's", 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy', 'Film-Noir', 'Horror ', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western'] item = np.char.strip(n) item = np.char.split(item, '|') item_df = pd.DataFrame(list(item), columns=item_index) #item_df["user id"] = item_df["user id"].astype('int') #item_df = item_df.drop(['release date'], axis=1) # 2-a top100 popular movies by all user # for i in range(1, 944): # user_dat = data_df[data_df.user_id == i] # user_dat = user_dat.sort_values(by=['rating'], ascending=False) # if len(user_dat) > 100: # user_dat = user_dat[:100] # 2-b # male = pd.DataFrame(columns=["user_id", "item_id", "rating"]) # female = pd.DataFrame(columns=["user_id", "item_id", "rating"]) # # for i in range(0, 100000): # u_i = data_df.iloc[i].user_id # user_r = user_df.loc[user_df.user_id == u_i] # gen = user_r.iloc[0]['gender'] # if gen == 'M': # male.loc[len(male)] = data_df.iloc[i] # else: # female.loc[len(female)] = data_df.iloc[i] #2-c occupation data_user = pd.merge(data_df[['user id', 'movie id', 'rating']], user_df[['user id', 'occupation']], on='user id') data_user.drop(columns=['user id'], inplace=True) data_user_item = pd.merge(data_user[['user id', 'movie id', 'rating']], item_df[['movie id', 'movie title']], on='movie id') data_user_item.drop(columns=['user id'], inplace=True) data_user_item_sorted = data_user_item.groupby(['occupation', 'movie title'], as_index=False)['rating'].mean().sort_values('rating', ascending=False) top_3_occ = data_user_item_sorted.groupby(['occupation']).head(3).sort_values(['occupation', 'movie title'], ascending=[True, True]).reset_index() top_3_occ.drop(['index'], axis=1, inplace=True)
MyuB/OpenSW_Exercise
hw_02/ml-100k/temp.py
temp.py
py
2,716
python
en
code
0
github-code
36
19924785078
input_value = { 'hired': { 'be': { 'to': { 'deserve': 'I' } } } } def reverse_nested_dict(input_value) : for first, second_layer in input_value.items(): for second, third_layer in second_layer.items(): for third, forth_layer in third_layer.items(): for forth, fifth in forth_layer.items(): output_value = {fifth:{forth:{third:{second:first}}}} return output_value output_value = reverse_nested_dict(input_value) # unittest import unittest class TestStringMethods(unittest.TestCase): def test_reverse(self): self.assertEqual(input_value, reverse_nested_dict(output_value)) if __name__ == '__main__': unittest.main()
LiviaChen/my_codes_record
Interview question for Python 3/Interview question for Python 3.py
Interview question for Python 3.py
py
745
python
en
code
0
github-code
36
30600682231
from django.dispatch import receiver from django.db.models.signals import post_save from expensense.models import Expense, ApprovalConditions from django.utils import timezone @receiver(post_save, sender=Expense) def auto_approve_expense(sender, instance, **kwargs): """ Method to auto approve expense requests """ # print('Auto Approved called') try: #query to get the manager and admin condition for the employee's team and company manager_condition = ApprovalConditions.objects.get(user__role = 'MNG', team = instance.user_id.team, company = instance.user_id.company) admin_condition = ApprovalConditions.objects.get(user__role = 'ADM', team = instance.user_id.team, company = instance.user_id.company) # approve the request if the expense amount is lesser than in approval # condition and is pending and the signature similarity is more than 80% if (manager_condition and (float(instance.amount) <= manager_condition.max_amount) and (int(instance.status)==Expense.pending) and (float(instance.similarity)>80)): # Auto approve for manager instance.manager_approved_at = timezone.now() instance.manager_auto_approved = True instance.status = Expense.manager_approved instance.save() manager_condition = None # approve the request if the expense amount is lesser than in approval # condition and is manager approved and the signature similarity is more than 80% elif (admin_condition and (int(instance.status) == Expense.manager_approved) and (float(instance.amount) <= admin_condition.max_amount) and float(instance.similarity)>80): # Auto approve for admin instance.admin_approved_at = timezone.now() instance.admin_auto_approved = True instance.status = Expense.admin_approved instance.save() admin_condition=None except ApprovalConditions.DoesNotExist: pass
praharsh05/ExpenSense
expensense_main/expensense/signals.py
signals.py
py
2,303
python
en
code
0
github-code
36
36955207429
import random, string import wiredtiger, wttest from helper import copy_wiredtiger_home from wtdataset import SimpleDataSet from wtscenario import filter_scenarios, make_scenarios # test_cursor12.py # Test cursor modify call class test_cursor12(wttest.WiredTigerTestCase): keyfmt = [ ('recno', dict(keyfmt='r')), ('string', dict(keyfmt='S')), ] valuefmt = [ ('item', dict(valuefmt='u')), ('string', dict(valuefmt='S')), ] types = [ ('file', dict(uri='file:modify')), ('lsm', dict(uri='lsm:modify')), ('table', dict(uri='table:modify')), ] # Skip record number keys with LSM. scenarios = filter_scenarios(make_scenarios(types, keyfmt, valuefmt), lambda name, d: not ('lsm' in d['uri'] and d['keyfmt'] == 'r')) # List with original value, final value, and modifications to get # there. list = [ { 'o' : 'ABCDEFGH', # no operation 'f' : 'ABCDEFGH', 'mods' : [['', 0, 0]] },{ 'o' : 'ABCDEFGH', # no operation with offset 'f' : 'ABCDEFGH', 'mods' : [['', 4, 0]] },{ 'o' : 'ABCDEFGH', # rewrite beginning 'f' : '--CDEFGH', 'mods' : [['--', 0, 2]] },{ 'o' : 'ABCDEFGH', # rewrite end 'f' : 'ABCDEF--', 'mods' : [['--', 6, 2]] },{ 'o' : 'ABCDEFGH', # append 'f' : 'ABCDEFGH--', 'mods' : [['--', 8, 2]] },{ 'o' : 'ABCDEFGH', # append with gap 'f' : 'ABCDEFGH --', 'mods' : [['--', 10, 2]] },{ 'o' : 'ABCDEFGH', # multiple replacements 'f' : 'A-C-E-G-', 'mods' : [['-', 1, 1], ['-', 3, 1], ['-', 5, 1], ['-', 7, 1]] },{ 'o' : 'ABCDEFGH', # multiple overlapping replacements 'f' : 'A-CDEFGH', 'mods' : [['+', 1, 1], ['+', 1, 1], ['+', 1, 1], ['-', 1, 1]] },{ 'o' : 'ABCDEFGH', # multiple overlapping gap replacements 'f' : 'ABCDEFGH --', 'mods' : [['+', 10, 1], ['+', 10, 1], ['+', 10, 1], ['--', 10, 2]] },{ 'o' : 'ABCDEFGH', # shrink beginning 'f' : '--EFGH', 'mods' : [['--', 0, 4]] },{ 'o' : 'ABCDEFGH', # shrink middle 'f' : 'AB--GH', 'mods' : [['--', 2, 4]] },{ 'o' : 'ABCDEFGH', # shrink end 'f' : 'ABCD--', 'mods' : [['--', 4, 4]] },{ 'o' : 'ABCDEFGH', # grow beginning 'f' : '--ABCDEFGH', 'mods' : [['--', 0, 0]] },{ 'o' : 'ABCDEFGH', # grow middle 'f' : 'ABCD--EFGH', 'mods' : [['--', 4, 0]] },{ 'o' : 'ABCDEFGH', # grow end 'f' : 'ABCDEFGH--', 'mods' : [['--', 8, 0]] },{ 'o' : 'ABCDEFGH', # discard beginning 'f' : 'EFGH', 'mods' : [['', 0, 4]] },{ 'o' : 'ABCDEFGH', # discard middle 'f' : 'ABGH', 'mods' : [['', 2, 4]] },{ 'o' : 'ABCDEFGH', # discard end 'f' : 'ABCD', 'mods' : [['', 4, 4]] },{ 'o' : 'ABCDEFGH', # discard everything 'f' : '', 'mods' : [['', 0, 8]] },{ 'o' : 'ABCDEFGH', # overlap the end and append 'f' : 'ABCDEF--XX', 'mods' : [['--XX', 6, 2]] },{ 'o' : 'ABCDEFGH', # overlap the end with incorrect size 'f' : 'ABCDEFG01234567', 'mods' : [['01234567', 7, 2000]] },{ # many updates 'o' : '-ABCDEFGHIJKLMNOPQRSTUVWXYZ-', 'f' : '-eeeeeeeeeeeeeeeeeeeeeeeeee-', 'mods' : [['a', 1, 1], ['a', 2, 1], ['a', 3, 1], ['a', 4, 1], ['a', 5, 1], ['a', 6, 1], ['a', 7, 1], ['a', 8, 1], ['a', 9, 1], ['a', 10, 1], ['a', 11, 1], ['a', 12, 1], ['a', 13, 1], ['a', 14, 1], ['a', 15, 1], ['a', 16, 1], ['a', 17, 1], ['a', 18, 1], ['a', 19, 1], ['a', 20, 1], ['a', 21, 1], ['a', 22, 1], ['a', 23, 1], ['a', 24, 1], ['a', 25, 1], ['a', 26, 1], ['b', 1, 1], ['b', 2, 1], ['b', 3, 1], ['b', 4, 1], ['b', 5, 1], ['b', 6, 1], ['b', 7, 1], ['b', 8, 1], ['b', 9, 1], ['b', 10, 1], ['b', 11, 1], ['b', 12, 1], ['b', 13, 1], ['b', 14, 1], ['b', 15, 1], ['b', 16, 1], ['b', 17, 1], ['b', 18, 1], ['b', 19, 1], ['b', 20, 1], ['b', 21, 1], ['b', 22, 1], ['b', 23, 1], ['b', 24, 1], ['b', 25, 1], ['b', 26, 1], ['c', 1, 1], ['c', 2, 1], ['c', 3, 1], ['c', 4, 1], ['c', 5, 1], ['c', 6, 1], ['c', 7, 1], ['c', 8, 1], ['c', 9, 1], ['c', 10, 1], ['c', 11, 1], ['c', 12, 1], ['c', 13, 1], ['c', 14, 1], ['c', 15, 1], ['c', 16, 1], ['c', 17, 1], ['c', 18, 1], ['c', 19, 1], ['c', 20, 1], ['c', 21, 1], ['c', 22, 1], ['c', 23, 1], ['c', 24, 1], ['c', 25, 1], ['c', 26, 1], ['d', 1, 1], ['d', 2, 1], ['d', 3, 1], ['d', 4, 1], ['d', 5, 1], ['d', 6, 1], ['d', 7, 1], ['d', 8, 1], ['d', 9, 1], ['d', 10, 1], ['d', 11, 1], ['d', 12, 1], ['d', 13, 1], ['d', 14, 1], ['d', 15, 1], ['d', 16, 1], ['d', 17, 1], ['d', 18, 1], ['d', 19, 1], ['d', 20, 1], ['d', 21, 1], ['d', 22, 1], ['d', 23, 1], ['d', 24, 1], ['d', 25, 1], ['d', 26, 1], ['e', 1, 1], ['e', 2, 1], ['e', 3, 1], ['e', 4, 1], ['e', 5, 1], ['e', 6, 1], ['e', 7, 1], ['e', 8, 1], ['e', 9, 1], ['e', 10, 1], ['e', 11, 1], ['e', 12, 1], ['e', 13, 1], ['e', 14, 1], ['e', 15, 1], ['e', 16, 1], ['e', 17, 1], ['e', 18, 1], ['e', 19, 1], ['e', 20, 1], ['e', 21, 1], ['e', 22, 1], ['e', 23, 1], ['e', 24, 1], ['e', 25, 1], ['e', 26, 1]] } ] def nulls_to_spaces(self, bytes_or_str): if self.valuefmt == 'u': # The value is binary return bytes_or_str.replace(b'\x00', b' ') else: # The value is a string return bytes_or_str.replace('\x00', ' ') # Convert a string to the correct type for the value. def make_value(self, s): if self.valuefmt == 'u': return bytes(s.encode()) else: return s def fix_mods(self, mods): if bytes != str and self.valuefmt == 'u': # In Python3, bytes and strings are independent types, and # the WiredTiger API needs bytes when the format calls for bytes. newmods = [] for mod in mods: # We need to check because we may converted some of the Modify # records already. if type(mod.data) == str: newmods.append(wiredtiger.Modify( self.make_value(mod.data), mod.offset, mod.size)) else: newmods.append(mod) mods = newmods return mods # Create a set of modified records and verify in-memory reads. def modify_load(self, ds, single): # For each test in the list: # set the original value, # apply modifications in order, # confirm the final state row = 10 c = ds.open_cursor() for i in self.list: c.set_key(ds.key(row)) c.set_value(self.make_value(i['o'])) self.assertEquals(c.update(), 0) c.reset() self.session.begin_transaction("isolation=snapshot") c.set_key(ds.key(row)) mods = [] for j in i['mods']: mod = wiredtiger.Modify(j[0], j[1], j[2]) mods.append(mod) mods = self.fix_mods(mods) self.assertEquals(c.modify(mods), 0) self.session.commit_transaction() c.reset() c.set_key(ds.key(row)) self.assertEquals(c.search(), 0) v = c.get_value() expect = self.make_value(i['f']) self.assertEquals(self.nulls_to_spaces(v), expect) if not single: row = row + 1 c.close() # Confirm the modified records are correct. def modify_confirm(self, ds, single): # For each test in the list: # confirm the final state is there. row = 10 c = ds.open_cursor() for i in self.list: c.set_key(ds.key(row)) self.assertEquals(c.search(), 0) v = c.get_value() expect = self.make_value(i['f']) self.assertEquals(self.nulls_to_spaces(v), expect) if not single: row = row + 1 c.close() # Smoke-test the modify API, anything other than an snapshot isolation fails. def test_modify_txn_api(self): ds = SimpleDataSet(self, self.uri, 100, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() c = ds.open_cursor() c.set_key(ds.key(10)) msg = '/not supported/' self.session.begin_transaction("isolation=read-uncommitted") mods = [] mods.append(wiredtiger.Modify('-', 1, 1)) self.assertRaisesWithMessage(wiredtiger.WiredTigerError, lambda: c.modify(mods), msg) self.session.rollback_transaction() self.session.begin_transaction("isolation=read-committed") mods = [] mods.append(wiredtiger.Modify('-', 1, 1)) self.assertRaisesWithMessage(wiredtiger.WiredTigerError, lambda: c.modify(mods), msg) self.session.rollback_transaction() # Smoke-test the modify API, operating on a group of records. def test_modify_smoke(self): ds = SimpleDataSet(self, self.uri, 100, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() self.modify_load(ds, False) # Smoke-test the modify API, operating on a single record def test_modify_smoke_single(self): ds = SimpleDataSet(self, self.uri, 100, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() self.modify_load(ds, True) # Smoke-test the modify API, closing and re-opening the database. def test_modify_smoke_reopen(self): ds = SimpleDataSet(self, self.uri, 100, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() self.modify_load(ds, False) # Flush to disk, forcing reconciliation. self.reopen_conn() self.modify_confirm(ds, False) # Smoke-test the modify API, recovering the database. def test_modify_smoke_recover(self): # Close the original database. self.conn.close() # Open a new database with logging configured. self.conn_config = \ 'log=(enabled=true),transaction_sync=(method=dsync,enabled)' self.conn = self.setUpConnectionOpen(".") self.session = self.setUpSessionOpen(self.conn) # Populate a database, and checkpoint it so it exists after recovery. ds = SimpleDataSet(self, self.uri, 100, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() self.session.checkpoint() self.modify_load(ds, False) # Crash and recover in a new directory. newdir = 'RESTART' copy_wiredtiger_home(self, '.', newdir) self.conn.close() self.conn = self.setUpConnectionOpen(newdir) self.session = self.setUpSessionOpen(self.conn) self.session.verify(self.uri) self.modify_confirm(ds, False) # Check that we can perform a large number of modifications to a record. @wttest.skip_for_hook("timestamp", "crashes on commit_transaction or connection close") # FIXME-WT-9809 def test_modify_many(self): ds = SimpleDataSet(self, self.uri, 20, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() c = ds.open_cursor() self.session.begin_transaction("isolation=snapshot") c.set_key(ds.key(10)) orig = self.make_value('abcdefghijklmnopqrstuvwxyz') c.set_value(orig) self.assertEquals(c.update(), 0) for i in range(0, 50000): new = self.make_value("".join([random.choice(string.digits) \ for i in range(5)])) orig = orig[:10] + new + orig[15:] mods = [] mod = wiredtiger.Modify(new, 10, 5) mods.append(mod) mods = self.fix_mods(mods) self.assertEquals(c.modify(mods), 0) self.session.commit_transaction() c.set_key(ds.key(10)) self.assertEquals(c.search(), 0) self.assertEquals(c.get_value(), orig) # Check that modify returns not-found after a delete. def test_modify_delete(self): ds = SimpleDataSet(self, self.uri, 20, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() c = ds.open_cursor() c.set_key(ds.key(10)) self.assertEquals(c.remove(), 0) self.session.begin_transaction("isolation=snapshot") mods = [] mod = wiredtiger.Modify('ABCD', 3, 3) mods.append(mod) mods = self.fix_mods(mods) c.set_key(ds.key(10)) self.assertEqual(c.modify(mods), wiredtiger.WT_NOTFOUND) self.session.commit_transaction() # Check that modify returns not-found when an insert is not yet committed # and after it's aborted. def test_modify_abort(self): ds = SimpleDataSet(self, self.uri, 20, key_format=self.keyfmt, value_format=self.valuefmt) ds.populate() # Start a transaction. self.session.begin_transaction("isolation=snapshot") # Insert a new record. c = ds.open_cursor() c.set_key(ds.key(30)) c.set_value(ds.value(30)) self.assertEquals(c.insert(), 0) # Test that we can successfully modify our own record. mods = [] mod = wiredtiger.Modify('ABCD', 3, 3) mods.append(mod) c.set_key(ds.key(30)) mods = self.fix_mods(mods) self.assertEqual(c.modify(mods), 0) # Test that another transaction cannot modify our uncommitted record. xs = self.conn.open_session() xc = ds.open_cursor(session = xs) xs.begin_transaction("isolation=snapshot") xc.set_key(ds.key(30)) xc.set_value(ds.value(30)) mods = [] mod = wiredtiger.Modify('ABCD', 3, 3) mods.append(mod) mods = self.fix_mods(mods) xc.set_key(ds.key(30)) self.assertEqual(xc.modify(mods), wiredtiger.WT_NOTFOUND) xs.rollback_transaction() # Rollback our transaction. self.session.rollback_transaction() # Test that we can't modify our aborted insert. self.session.begin_transaction("isolation=snapshot") mods = [] mod = wiredtiger.Modify('ABCD', 3, 3) mods.append(mod) mods = self.fix_mods(mods) c.set_key(ds.key(30)) self.assertEqual(c.modify(mods), wiredtiger.WT_NOTFOUND) self.session.rollback_transaction() if __name__ == '__main__': wttest.run()
mongodb/mongo
src/third_party/wiredtiger/test/suite/test_cursor12.py
test_cursor12.py
py
15,173
python
en
code
24,670
github-code
36
23048227631
#!/usr/bin/env python # coding: utf-8 # # 積み上げ棒グラフを作成する # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') from matplotlib import pyplot as plt import numpy as np #数値は適当 bar1 = [100, 50, 200] #積み上げ棒グラフの一段目 bar2 = [100, 200, 50] #積み上げ棒グラフの二段目 bar3 = [100, 250, 100] #積み上げ棒グラフの三段目 bar3_st = np.add(bar1, bar2).tolist() #bar3を積み上げる位置を指定しておく sample_labels = ['SampleA', 'SampleB', 'SampleC'] #データのラベルを指定 x = [0, 1, 2] #棒グラフを表示させるx軸座標を決めておく barwidth = 0.7 #棒グラフの幅を指定する。棒グラフのx軸座標を考慮して決める plt.figure() #Figureオブジェクトを作成 plt.bar(x, bar1, width=barwidth, label='class1') plt.bar(x, bar2, bottom=bar1, width=barwidth, label='class2') #bottomで2段目のデータを積み上げる位置を指定する plt.bar(x, bar3, bottom=bar3_st, width=barwidth, label='class3') #bottomで3段目のデータを積み上げる位置を指定する plt.xticks(x, sample_labels, fontweight='bold') #x軸のラベルを指定する #データラベルを棒グラフの中に追加したい場合は以下を追加する ax = plt.gca() #gca()現在の軸情報を取得(get current axis) handles, labels = ax.get_legend_handles_labels() #handles 線やマーカーを含んだオブジェクト labels 凡例に表示されるラベル plt.legend(handles[::-1], labels[::-1], loc='upper left', bbox_to_anchor=(1,1)) #handles[::-1], labels[::-1] 凡例を棒グラフの順番と合わせる for i in range(len(bar1)): ax.annotate(str(bar1[i]), xy=(x[i] - 0.1, (bar1[i] / 3)), color='white', fontweight='bold') for i in range(len(bar2)): ax.annotate(str(bar2[i]), xy=(x[i] - 0.1, (bar2[i] / 3) + bar1[i]), color='white', fontweight='bold') for i in range(len(bar3)): ax.annotate(str(bar3[i]), xy=(x[i] - 0.1, (bar3[i] / 3) + bar3_st[i]), color='white', fontweight='bold') plt.subplots_adjust(right=0.8) #凡例のために余白を広げる rightのdefaultは0.9 plt.title('BarPlot Test') plt.xlabel('Sample Name') plt.ylabel('count') plt.show() #plt.savefig('barplot.pdf') #pdfで出力する場合 #plt.savefig('barplot.svg',format='svg') #ベクター画像で出力する場合 plt.close() # **numpy**モジュール **add( )** # # ・配列の要素を足し算する。 # # <br> # # **numpy**モジュール **tolist( )** # # ・Numpy配列をリスト型に変換する。 # # <br> # # **pyplot**モジュール **gca( )** # # ・現在のAxesオブジェクトを取得する。 # # <br> # # **get_legend_handles_labels( )** # # ・handlerとlabelを取得する。handlerは線やマーカーを含んだオブジェクト。labelsは凡例に表示されるラベル(リスト型)。 # # ・Axesオブジェクト用 # # <br> # # **annotate(s, xy)** # # ・xyで指定した位置にsで指定した文字を出力する。 # # ・Axesオブジェクト用 # # <br> # # --- # ### 積み上げる段が多い場合に対応できるように、for文で処理する # In[2]: get_ipython().run_line_magic('matplotlib', 'inline') from matplotlib import pyplot as plt import numpy as np #数値は適当 bar1 = [100, 50, 200] #積み上げ棒グラフの一段目 bar2 = [100, 200, 50] #積み上げ棒グラフの二段目 bar3 = [100, 250, 100] #積み上げ棒グラフの三段目 bar_data = [bar1, bar2, bar3] sample_labels = ['SampleA', 'SampleB', 'SampleC'] #データのラベルを指定 group_labels = ['class1', 'class2', 'class3'] x = [0, 1, 2] #棒グラフを表示させるx軸座標を決めておく barwidth = 0.7 #棒グラフの幅を指定する。棒グラフのx軸座標を考慮して決める fig, ax = plt.subplots() #FigureオブジェクトとAxesオブジェクトを作成 bottom_position = np.zeros(len(bar_data)) #積み上げる位置を指定するため、積み上げる段数と同じ要素数(ここではbar_dataの要素数)の一次元配列を作成する for i in range(len(bar_data)): #一段ずつデータをaxオブジェクトに格納する ax.bar(x, bar_data[i], width=barwidth, bottom=bottom_position, label=group_labels[i]) for j in range(len(bar_data[i])): #annotateはx軸のポイントごとにデータを格納する必要がるので、for文を使う ax.annotate(str(bar_data[i][j]), xy=(x[j] - 0.1, (bar_data[i][j] / 3) + bottom_position.tolist()[j]), color='white', fontweight='bold') bottom_position = np.add(bar_data[i], bottom_position) ax.set_xticks(x) ax.set_xticklabels(sample_labels, fontweight='bold') #x軸のラベルを指定する handles, labels = ax.get_legend_handles_labels() #handles 線やマーカーを含んだオブジェクト labels 凡例に表示されるラベル ax.legend(handles[::-1], labels[::-1], loc='upper left', bbox_to_anchor=(1,1)) #handles[::-1], labels[::-1] 凡例を棒グラフの順番と合わせる fig.subplots_adjust(right=0.8) #凡例のために余白を広げる rightのdefaultは0.9 ax.set_title('BarPlot Test') ax.set_xlabel('Sample Name') ax.set_ylabel('Count') plt.show() #fig.savefig('barplot.pdf') #fig.savefig('barplot.svg',format='svg') plt.close() # **numpy**モジュール **zeros(shape)** # # ・要素0の配列を生成する。第一引数に配列のshapeを指定できる。
workskt/book
_build/jupyter_execute/python_plot_cumulativebar.py
python_plot_cumulativebar.py
py
5,462
python
ja
code
0
github-code
36
1141389329
from werkzeug.security import check_password_hash from db.SedmDb import SedmDB import datetime import os import json import re import pandas as pd import numpy as np import requests import glob import time from decimal import Decimal from bokeh.io import curdoc from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Label from bokeh.models import CDSView, GroupFilter from bokeh.models.tools import HoverTool from bokeh.models.ranges import Range1d from bokeh.models.axes import LinearAxis from bokeh.models.annotations import BoxAnnotation from bokeh.plotting import figure from bokeh.embed import components from astropy.time import Time import astropy.units as u from astropy.coordinates import EarthLocation, SkyCoord, AltAz, get_sun,\ get_moon from scheduler.scheduler import ScheduleNight pd.options.mode.chained_assignment = None # default='warn' superuser_list = ['SEDm_admin', 2, 20180523190352189] pd.set_option('display.max_colwidth', -1) request_values = ['id', 'object_id', 'marshal_id', 'user_id', 'allocation_id', 'exptime', 'priority', 'inidate', 'enddate', 'maxairmass', 'cadence', 'phasesamples', 'sampletolerance', 'filters', 'nexposures', 'obs_seq', 'status', 'creationdate', 'lastmodified', 'max_fwhm', 'min_moon_dist', 'max_moon_illum', 'max_cloud_cover', 'seq_repeats', 'seq_completed', 'last_obs_jd'] object_values = ['id', 'marshal_id', 'name', 'iauname', 'ra', 'dec', 'epoch', 'typedesig', 'magnitude'] """ request_form_values = ['request_id', 'object_id', 'marshal_id', 'user_id', 'allocation', 'ifu', 'ifu_use_mag', 'ab', 'rc', 'do_r', 'do_g', 'do_i', 'do_u', 'r_exptime', 'g_exptime', 'i_exptime', 'u_exptime', 'r_repeats', 'g_repeats', 'i_repeats', 'u_repeats', 'ifu_exptime', 'priority', 'inidate', 'rc_use_mag', 'enddate', 'maxairmass', 'status', 'max_fwhm', 'min_moon_dist', 'max_moon_illum', 'max_cloud_cover', 'seq_repeats', 'seq_completed'] """ request_form_values = ['request_id', 'object_id', 'marshal_id', 'user_id', 'allocation', 'ifu', 'ifu_use_mag', 'rc', 'do_r', 'do_g', 'do_i', 'do_u', 'r_exptime', 'g_exptime', 'i_exptime', 'u_exptime', 'r_repeats', 'g_repeats', 'i_repeats', 'u_repeats', 'ifu_exptime', 'priority', 'inidate', 'rc_use_mag', 'enddate', 'maxairmass', 'status', 'max_fwhm', 'min_moon_dist', 'max_moon_illum', 'max_cloud_cover', 'seq_repeats', 'seq_completed'] rc_filter_list = ['r', 'g', 'i', 'u'] schedule = ScheduleNight() # this all needs to go in some sort of config file instead of changing the # source code constantly computer = os.uname()[1] # a quick fix port = 0 host = 'none' if computer == 'pele': raw_dir = '/scr/rsw/sedm/raw/' phot_dir = '/scr/rsw/sedm/phot/' redux_dir = '/scr/rsw/sedm/data/redux/' new_phot_dir = '/scr/rsw/sedm/data/redux/phot/' status_dir = '/scr/rsw/' requests_dir = '/scr/rsw/' base_dir = '/scr/rsw/' host = 'pharos.caltech.edu' port = 5432 elif computer == 'pharos': raw_dir = '/scr2/sedm/raw/' phot_dir = '/scr2/sedm/phot/' new_phot_dir = '/scr2/sedmdrp/redux/phot/' redux_dir = '/scr2/sedmdrp/redux/' status_dir = '/scr2/sedm/raw/telstatus/' requests_dir = '/scr2/sedm/logs/requests/' host = 'localhost' base_dir = '/scr2/sedmdrp/' port = 5432 elif computer == 'minar': raw_dir = '/data/sedmdrp/raw/' phot_dir = '/data/sedmdrp/redux/phot/' new_phot_dir = '/data/sedmdrp/redux/phot/' redux_dir = '/data/sedmdrp/redux/' status_dir = '/data/sedmdrp/raw/telstatus/' requests_dir = '/data/sedmdrp/logs/requests/' host = 'localhost' base_dir = '/data/sedmdrp/' port = 5432 elif computer == 'ether': raw_dir = '/home/rsw/sedm_data/raw/' phot_dir = '/home/rsw/sedm/phot/' redux_dir = '/home/rsw/sedm_data/redux/' new_phot_dir = '/home/rsw/sedm_data/redux/phot/' requests_dir = '/home/rsw/' base_dir = '/home/rsw/sedm_data/' host = 'localhost' port = 22222 print(computer, port, host, "inputs") db = SedmDB(host=host, dbname='sedmdb', port=port) def get_from_users(user_id): return db.get_from_users(['id', 'username'], {'id': user_id}) def get_object_values(objid=None): try: objid = int(objid) except Exception as e: return {'error': str(e)} ret = db.get_from_object(values=object_values, where_dict={'id': int(objid)}) if not ret: return {'error': "No object found with that id number"} return make_dict_from_dbget(object_values, ret[0]) def get_object_info(name=None, ra=None, dec=None, radius=5, out_type='html'): """ :param radius: :param out_type: :param name: :param ra: :param dec: :return: """ # 1. Start by looking for objects by name or coordinates if name: ids = db.get_object_id_from_name(name) elif ra and dec: ids = db.get_objects_near(ra=ra, dec=dec, radius=radius) else: ids = None # 2. If no results return empty list and message if not ids: return {'message': 'No objects found with that name or coordinates', 'objects': False} # 3. If there are objects get a list of values for each match obj_list = [] for obj in ids: ret = db.get_from_object(values=object_values, where_dict={'id': obj[0]}) obj_list.append(ret[0]) # 4. Convert the list into the appropriate output if out_type == 'html': df = pd.DataFrame(obj_list, columns=object_values) df['Select'] = df['id'].apply(add_link) return {'message': df.to_html(escape=False, classes='table', index=False)} else: return obj_list def fancy_request_table(df): """ df: pandas dataframe intended for tables of requests from get_requests_for_user, ie with columns: ['allocation', 'object', 'RA', 'DEC', 'start date', 'end date', 'priority','status', 'lastmodified', 'UPDATE'] returns: IPython HTML object the html for df but with the following changes: -if 'RA' and 'Dec' mean it won't rise tonight, both fields are red -'name' column now has links to the growth marshal -table width is 100%, which is important for the fancy tables to display right -priority is a float to allow finer tuning of the scheduler """ def highlight_set(hrow, color='#ff9999'): """ makes 'RA' and 'DEC' fields highlighted if it won't get high when it's dark out meant for tables with both 'RA' and 'DEC' columns """ red = 'background-color: {}'.format(color) try: # peak at longitude-based midnight, approx best_ra = ((Time.now().mjd - 58382.) * 360/365.) # more than 8h from midnight if 180 - abs(180 - (best_ra - float(hrow['RA'])) % 360) > 120: return [red if i == 'RA' else '' for i in hrow.index.values] # red if it'll never go above ~40deg if hrow['DEC'] < -15.: return [red if i == 'DEC' else '' for i in hrow.index.values] else: return ['' for _ in hrow.index.values] except KeyError: return ['' for _ in hrow.index.values] def improve_obs_seq(li): """ takes a list like ['1ifu'], [180, 180, 180], etc and makes it take up less space and also be more human-readable """ try: if type(li[0]) == str: # ie it's an obs_seq for i, val in enumerate(li): if val[0] == '1': li[i] = val[1:] else: li[i] = val[1:] + ' x' + val[0] else: # ie exptime for i, val in enumerate(li): if all([j == val for j in li[i:]]) and i < len(li) - 1: # all the rest match, of which there's >1 li = li[:i] + ['{}ea'.format(val)] break else: li[i] = str(val) return ', '.join(li) except: return "ERROR,PARSING_THE_FILTER_STRING" df['status'] = [i.lower() for i in df['status']] df['allocation'] = [i.replace('2018A-', '').replace('2018B-', '') .replace('2019B-', '').replace('2021B-', '') .replace('2022A-', '') for i in df['allocation']] for col in ('obs_seq', 'exptime'): df[col] = [improve_obs_seq(i) for i in df[col]] styled = df.style\ .apply(highlight_set, axis=1)\ .format( {'object': '<a href="https://fritz.science/source/{0}">{0}</a>', 'RA': '{:.3f}', 'DEC': '{:.3f}', 'priority': '{:.1f}', 'start date': '{:%b %d}', 'end date': '{:%b %d}', 'lastmodified': '{:%b %d %H:%M}', 'UPDATE': '<a href="request?request_id={}">+</a>'})\ .set_table_styles([{'text-align': 'left'}])\ .set_table_attributes('style="width:100%" ' 'class="dataframe_fancy table ' 'table-striped nowrap"')\ .set_table_styles( [{'selector': '.row_heading', 'props': [('display', 'none')]}, {'selector': '.blank.level0', 'props': [('display', 'none')]}]) # this .replace() thing is super bad form but it's faster for now than # finding the right way return styled.render()\ .replace('RA</th>', '<a href="#" data-toggle="tooltip" ' 'title="red if peaks >8h from midnight">RA</a></th>')\ .replace('DEC</th>', '<a href="#" data-toggle="tooltip" ' 'title="red if peaks below 40deg">dec</a></th>') def get_homepage(userid, username): sedm_dict = {'enddate': datetime.datetime.utcnow() + datetime.timedelta(days=30), 'inidate': datetime.datetime.utcnow() - datetime.timedelta(days=7, hours=8)} # 1. Get a dataframe of all requests for the current user reqs = get_requests_for_user(userid, sedm_dict['inidate'], sedm_dict['enddate']) # organize requests into dataframes by whether they are completed or not complete = reqs[(reqs['status'] == 'COMPLETED') | (reqs['status'] == 'OBSERVED') | (reqs['status'] == 'OBSERVED')] active = reqs[(reqs['status'] == 'ACTIVE')] pending = reqs[(reqs['status'] == 'PENDING')] expired = reqs[(reqs['status'] == 'EXPIRED')] failed = reqs[(reqs['status'] == 'FAILED')] # retrieve information about the user's allocations ac = get_allocations_user(userid) # Create html tables sedm_dict['active'] = {'table': fancy_request_table(active), 'title': 'Active Request'} sedm_dict['pending'] = {'table': fancy_request_table(pending), 'title': 'Pending Requests'} sedm_dict['complete'] = {'table': fancy_request_table(complete), 'title': 'Completed Requests in the last 7 days'} sedm_dict['expired'] = {'table': fancy_request_table(expired), 'title': 'Expired Requests in the last 7 days'} sedm_dict['failed'] = {'table': fancy_request_table(failed), 'title': 'Failed Exposures in the last 7 days'} sedm_dict['allocations'] = { 'table': ac.to_html(escape=False, classes='table table-striped', index=False, col_space=10), 'title': 'Your Active Allocations'} sedm_dict['visibility'] = {'title': 'Visibilities for pending requests', 'url': '/visibility'} # Make a greeting statement sedm_dict['greeting'] = 'Hello %s!' % username return sedm_dict ############################################################################### # THIS SECTION HANDLES EXPIRED TARGETS. # # KEYWORD:EXPIRED # ############################################################################### def show_expired(days=7): """ :return: """ print(days) ############################################################################### # THIS SECTION HANDLES ALL THINGS RELATED TO THE SCHEDULER PAGE. # # KEYWORD:SCHEDULER # ############################################################################### def get_schedule(): """ :return: """ with open('static/scheduler/scheduler.html', 'r') as myfile: data = myfile.read().replace('\n', '') return {'scheduler': data} ############################################################################### # THIS SECTION HANDLES ALL THINGS RELATED TO THE REQUEST PAGE. # # KEYWORD:REQUEST # ############################################################################### def add_link(objid): return """<input type = "button" onclick = 'addValues("%s")' value = "Use" />""" % objid def get_request_page(userid, form1, content=None): req_dict = {} # Start by getting all the allocations the user can add targets under # Create a list for a select field on the request page alloc = get_allocations_user(userid) if alloc is None or len(alloc) == 0: choices = [(0, "You have no active allocations!")] else: choices = [z for z in zip(alloc['id'], alloc['allocation'])] choices.insert(0, (0, '------')) form1.allocation.choices = choices # if an object id is given or a request id, prepopulate the field if content: req_dict.update(populate_form(content, form1)) # Set the start date if one is not given if not form1.inidate.data: form1.inidate.data = datetime.datetime.today() if not form1.enddate.data: form1.enddate.data = datetime.datetime.today() + datetime.timedelta(2) # return req_dict, form1 def populate_form(content, form): """ :param content: :param form: :return: """ # We look to see if there is a request id to begin with because if so then # the object info will automatically be tied into that. If it is not in # there then we should start looking at other keywords. if 'request_id' in content: data = db.get_from_request(values=request_values, where_dict={'id': content['request_id'][0]}) ret_dict = make_dict_from_dbget(headers=request_values, data=data[0]) obj_dict = get_object_values(objid=ret_dict['object_id']) # Remove the identical id so as not to get confused del obj_dict['id'] del obj_dict['marshal_id'] ret_dict.update(obj_dict) ret_dict['request_id'] = content['request_id'][0] # I am setting a status_id because when I do # form.status.data = x['status'] # it doesn't set the proper select option. ret_dict['status_id'] = ret_dict['status'] ret_dict.update(parse_db_target_filters(ret_dict['obs_seq'], ret_dict['exptime'])) elif 'object_id' in content: ret_dict = get_object_values(objid=content['object_id'][0]) if 'error' in ret_dict: ret_dict['message'] = ret_dict['error'] else: ret_dict = {'message': "There was nothing to process"} # TODO: There has to be a better way to do this... if 'request_id' in ret_dict: form.request_id.data = ret_dict['request_id'] if 'object_id' in ret_dict: form.object_id.data = ret_dict['object_id'] if 'marshal_id' in ret_dict: form.marshal_id.data = ret_dict['marshal_id'] if 'allocation_id' in ret_dict: form.allocation_id.data = ret_dict['allocation_id'] form.allocation.data = str(ret_dict['allocation_id']) if 'ra' in ret_dict: form.obj_ra.data = ret_dict['ra'] if 'dec' in ret_dict: form.obj_dec.data = ret_dict['dec'] if 'epoch' in ret_dict: form.obj_epoch.data = ret_dict['epoch'] if 'magnitude' in ret_dict: form.obj_mag.data = ret_dict['magnitude'] if 'name' in ret_dict: form.obj_name.data = ret_dict['name'] if 'inidate' in ret_dict: form.inidate.data = ret_dict['inidate'] if 'enddate' in ret_dict: form.enddate.data = ret_dict['enddate'] if 'min_moon_distance' in ret_dict: form.min_moon_distance = ret_dict['min_moon_distance'] if 'priority' in ret_dict: form.priority.data = ret_dict['priority'] if 'maxairmass' in ret_dict: form.maxairmass.data = ret_dict['maxairmass'] if 'cadence' in ret_dict: form.cadence.data = ret_dict['cadence'] if 'phasesamples' in ret_dict: form.phasesamples.data = ret_dict['phasesamples'] if 'sampletolerance' in ret_dict: form.sampletolerance.data = ret_dict['sampletolerance'] if 'status_id' in ret_dict: form.status.data = ret_dict['status_id'] if 'max_fwhm' in ret_dict: form.max_fwhm.data = ret_dict['max_fwhm'] if 'seq_repeats' in ret_dict: if not ret_dict['seq_repeats']: form.seq_repeats.data = 1 else: form.seq_repeats.data = ret_dict['seq_repeats'] if 'seq_completed' in ret_dict: form.seq_repeats.data = ret_dict['seq_completed'] if 'max_moon_illum' in ret_dict: form.max_moon_illum.data = ret_dict['max_moon_illum'] if 'max_cloud_cover' in ret_dict: form.max_cloud_cover.data = ret_dict['max_cloud_cover'] if 'creationdate' in ret_dict: form.creationdate.data = ret_dict['creationdate'] if 'lastmodified' in ret_dict: form.lastmodified.data = ret_dict['lastmodified'] # if 'last_obs_jd' in ret_dict: # form.last_obs_jd.data = ret_dict['last_obs_jd'] if 'do_ifu' in ret_dict: form.ifu.data = ret_dict['do_ifu'] if 'ifu_exptime' in ret_dict: form.ifu_exptime.data = ret_dict['ifu_exptime'] #if 'ab' in ret_dict: # form.ab.data = ret_dict['ab'] if 'do_rc' in ret_dict: form.rc.data = ret_dict['do_rc'] if 'do_r' in ret_dict: form.do_r.data = ret_dict['do_r'] if 'do_i' in ret_dict: form.do_i.data = ret_dict['do_i'] if 'do_g' in ret_dict: form.do_g.data = ret_dict['do_g'] if 'do_u' in ret_dict: form.do_u.data = ret_dict['do_u'] if 'r_exptime' in ret_dict: form.r_exptime.data = ret_dict['r_exptime'] if 'g_exptime' in ret_dict: form.g_exptime.data = ret_dict['g_exptime'] if 'i_exptime' in ret_dict: form.i_exptime.data = ret_dict['i_exptime'] if 'u_exptime' in ret_dict: form.u_exptime.data = ret_dict['u_exptime'] if 'r_repeats' in ret_dict: form.r_repeats.data = ret_dict['r_repeats'] if 'r_repeats' in ret_dict: form.r_repeats.data = ret_dict['r_repeats'] if 'g_repeats' in ret_dict: form.g_repeats.data = ret_dict['g_repeats'] if 'i_repeats' in ret_dict: form.i_repeats.data = ret_dict['i_repeats'] if 'u_repeats' in ret_dict: form.u_repeats.data = ret_dict['u_repeats'] if 'seq_completed' in ret_dict: form.seq_completed.data = ret_dict['seq_completed'] return ret_dict def parse_db_target_filters(obs_seq, exptime): """ Parse database target scheme :param obs_seq: :param exptime: :return: """ # Prep the variables rc_filters = ['r', 'g', 'i', 'u'] return_dict = { 'do_ifu': False, 'ifu_exptime': 0, 'do_rc': False, 'do_r': False, 'r_exptime': 0, 'r_repeats': 1, 'do_g': False, 'g_exptime': 0, 'g_repeats': 1, 'do_i': False, 'i_exptime': 0, 'i_repeats': 1, 'do_u': False, 'u_exptime': 0, 'u_repeats': 1, } # 1. First we extract the filter sequence seq = list(obs_seq) exptime = list(exptime) # 2. Remove ifu observations first if they exist index = [i for i, s in enumerate(seq) if 'ifu' in s] if index: for j in index: seq.pop(j) return_dict['ifu_exptime'] = int(exptime.pop(j)) return_dict['do_ifu'] = True if return_dict['ifu_exptime'] == 0: return_dict['do_ifu'] = False # 3. If the seq list is empty then there is no photmetry follow-up # and we should exit if not seq: return return_dict # 4. If we are still here then we need to get the photometry sequence return_dict['do_rc'] = True for i in range(len(seq)): flt = seq[i][-1] flt_exptime = int(exptime[i]) flt_repeat = int(seq[i][:-1]) # 4a. After parsing the indivual elements we need to check that they are # valid values if flt in rc_filters: if 0 <= flt_exptime <= 1000: if 1 <= flt_repeat <= 100: return_dict['do_%s' % flt] = True return_dict['%s_exptime' % flt] = flt_exptime return_dict['%s_repeats' % flt] = flt_repeat else: continue return return_dict def add_object_to_db(content): """ :param content: :return: """ return_dict = {'message': ''} # Add the object to the database if content['obj_ra'] and content['obj_dec']: ra = content['obj_ra'] dec = content['obj_dec'] if ":" in ra or ":" in dec: c = SkyCoord(ra=ra, dec=dec, unit=(u.hourangle, u.deg)) ra = c.ra.degree dec = c.dec.degree if content['obj_epoch']: epoch = content['obj_epoch'] else: epoch = 2000 objdict = { 'name': content['obj_name'], 'ra': ra, 'dec': dec, 'typedesig': 'f', 'epoch': epoch, } if content['obj_mag']: objdict['magnitude'] = content['obj_mag'] objid, msg = db.add_object(objdict) if objid == -1: return_dict['message'] += msg + ('--For now I am going to ' 'assume that you want to ' 'use this object and will ' 'go ahead with the rest ' 'of the request--') objid = msg.split()[-1] else: return_dict['message'] = ("How am I suppose to add your request " "if you don't give me any coordinates--") objid = False return return_dict, objid def process_request_form(content, form, userid): """ :param content: :param userid: :param form: :return: """ request_dict = {} process_dict = {'message': ''} obs_seq_dict = {} alloc = get_allocations_user(int(userid)) if alloc is None or len(alloc) == 0: choices = [(0, "You have no active allocations!")] else: choices = [z for z in zip(alloc['id'], alloc['allocation'])] choices.insert(0, (0, '------')) form.allocation.choices = choices # 1. Let's start by making sure we have all the information needed for the # object id if 'object_id' in content and content['object_id']: objid = content['object_id'] else: message, objid = add_object_to_db(content) if not objid: return {**process_dict, **message}, form else: if 'message' in message: process_dict['message'] += message['message'] request_dict['object_id'] = int(objid) # 2. Now let's put together the request # by getting all the values into a dictionary """ obs_seq_key_list = ['ifu', 'rc', 'ab', 'do_r', 'do_i', 'do_u', 'do_g', 'r_repeats', 'g_repeats', 'i_repeats', 'u_repeats', 'r_exptime', 'g_exptime', 'i_exptime', 'u_exptime', 'ifu_use_mag', 'rc_use_mag', 'ifu_exptime'] """ obs_seq_key_list = ['ifu', 'rc', 'do_r', 'do_i', 'do_u', 'do_g', 'r_repeats', 'g_repeats', 'i_repeats', 'u_repeats', 'r_exptime', 'g_exptime', 'i_exptime', 'u_exptime', 'ifu_use_mag', 'rc_use_mag', 'ifu_exptime'] for key in request_form_values: try: # This should handle both the case when an object id has already # been added and when we had to generate a new one if key == 'object_id': pass # This case will handle new requests when a user id is not given elif key == 'user_id' and not content['user_id']: request_dict['user_id'] = userid elif key == 'allocation': request_dict['allocation_id'] = content[key] # This section should handle all the observation data such as if # we want ifu/rc follow-up and exposure times. Note that because # of the database format we must handle this data outside # the request dictionary. elif key in obs_seq_key_list: if key in content: obs_seq_dict[key] = content[key] else: obs_seq_dict[key] = False else: request_dict[key] = content[key] except Exception as e: print(str(e), key, 't') pass # print("I made it here") # 3. Now we need to create the obs_seq and exptime entries # We need to also make sure and add the object magnitude # to calculate exposure times if content['obj_mag']: obs_seq_dict['obj_mag'] = content['obj_mag'] else: obs_seq_dict['obj_mag'] = 17.5 filter_dict = (make_obs_seq(obs_seq_dict)) if 'ERROR' in filter_dict: process_dict['message'] += filter_dict['ERROR'] else: process_dict['message'] += filter_dict.pop("proc_message") request_dict = {**filter_dict, **request_dict} if 'request_id' in content and content['request_id']: request_dict['id'] = int(content['request_id']) request_dict.pop('request_id') for k, v in request_dict.items(): if not v: request_dict[k] = -1 # ret = db.update_request(request_dict) db.update_request(request_dict) else: # print("I AM HERE NOW") if 'request_id' in request_dict: request_dict.pop('request_id') request_dict['user_id'] = int(request_dict['user_id']) # print(request_dict) if 'external_id' in content: request_dict['external_id'] = content['external_id'] # ret = db.add_request(request_dict) db.add_request(request_dict) # print(ret) return process_dict, form def get_add_csv(user_id, form, content): """ :param user_id: :param form: :param content: :return: """ return {'test': 'test'}, form, user_id, content def process_add_csv(content, form, user_id): """ :param content: :param form: :param user_id: :return: """ return {'test': 'test'}, form, content, user_id def make_obs_seq(obs_seq_dict): """ :param obs_seq_dict: :return: """ filters_list = [] exptime_list = [] ret_dict = {"proc_message": ""} if isinstance(obs_seq_dict['ifu'], bool): if obs_seq_dict['ifu']: obs_seq_dict['ifu'] = 'y' else: obs_seq_dict['ifu'] = 'n' if isinstance(obs_seq_dict['rc'], bool): if obs_seq_dict['rc']: obs_seq_dict['rc'] = 'y' else: obs_seq_dict['rc'] = 'n' if obs_seq_dict['ifu'].lower() in ['y', 'yes', 'true']: # There may be case in the future where people want more than one IFU # at a time. In which case this code will need to be changed. if obs_seq_dict['ifu_use_mag']: if obs_seq_dict['ifu_exptime'] and \ int(obs_seq_dict['ifu_exptime']) > 0: ret_dict["proc_message"] += ("You should know that you " "supplied a non-zero value " "in the ifu exposure time " "field. However because you " "checked the use magnitude box " "I will be ignoring the supplied " "value.--") try: mag = float(obs_seq_dict['obj_mag']) if mag == 0: ret_dict['proc_message'] += ("I find it hard to believe " "that you really wanted to " "observe something zero " "magnitude. So I can't let " "this go through. Feel free" "to contact me and dispute " "this.--") ifu_exptime = False else: ifu_exptime = get_filter_exptime('ifu', mag) except Exception as e: ret_dict['proc_message'] += ("For some reason I couldn't " "process your magnitude. If you " "didn't add one then that is on " "you. Otherwise there is something" " wrong with this '%s' value. For" " the record here is the error " "message %s--" % (obs_seq_dict['obj_mag'], str(e))) ifu_exptime = False else: try: ifu_exptime = int(obs_seq_dict['ifu_exptime']) if 0 <= ifu_exptime <= 7200: pass else: ret_dict['proc_message'] += ("I don't know what you are " "trying to do but %s is not an" " acceptable IFU exposure " "time. It's either less than " " 0 or more than two hours.--" % str(ifu_exptime)) ifu_exptime = False except Exception as e: ret_dict['proc_message'] += ("There is something wrong with " "your exposure time value. '%s' " "is not a proper value. Here is " "the error message return: %s--" % (obs_seq_dict['ifu_exptime'], str(e))) ifu_exptime = False if ifu_exptime: filters_list.append("1ifu") exptime_list.append(str(ifu_exptime)) # print(obs_seq_dict) if obs_seq_dict['rc'].lower() in ['y', 'yes', 'true']: for flt in rc_filter_list: if obs_seq_dict['do_%s' % flt]: repeats = obs_seq_dict['%s_repeats' % flt] if 1 <= int(repeats) <= 100: pass else: ret_dict['proc_message'] += ("There is something wrong " "with the number of " "repeats you have " "requested. Forcing it to 1" "--") repeats = 1 if obs_seq_dict['rc_use_mag']: mag = obs_seq_dict['obj_mag'] exptime = get_filter_exptime(flt, mag) filters_list.append("%s%s" % (str(repeats), flt)) exptime_list.append(str(exptime)) else: exptime = int(obs_seq_dict['%s_exptime' % flt]) if 0 <= exptime <= 1000: pass else: ret_dict['proc_message'] += ("The exposure time (%s) " "you entered for filter " "(%s) makes no sense. If " "you entered something " "more than 10mins it is " "wasting time. Feel free " "to contact me to disput " "this--" % (str(exptime), flt)) exptime = False if exptime: filters_list.append("%s%s" % (str(repeats), flt)) exptime_list.append(str(exptime)) if not filters_list: ret_dict["ERROR"] = "NO FILTERS COULD BE DETERMINED" return ret_dict else: if len(filters_list) == len(exptime_list): ret_dict['obs_seq'] = '{%s}' % ','.join(filters_list) ret_dict['exptime'] = '{%s}' % ','.join(exptime_list) else: ret_dict["ERROR"] = ("Filter and exposure time list don't match " "%s : %s" % (','.join(filters_list), ','.join(exptime_list))) return ret_dict def get_allocations_user(user_id, return_type=''): res = db.execute_sql(""" SELECT a.id, a.designator, p.designator, g.designator, a.time_allocated, a.time_spent FROM allocation a, program p, groups g, usergroups ug WHERE a.program_id = p.id AND p.group_id = g.id AND g.id = ug.group_id AND a.active is True AND ug.user_id = %d""" % user_id) # create the dataframe and set the allocation names to be linked if return_type == 'list': data = [] for i in res: data.append(i[0]) else: data = pd.DataFrame(res, columns=['id', 'allocation', 'program', 'group', 'time allocated', 'time spent']) return data def get_requests_for_user(user_id, inidate=None, enddate=None): """ :param user_id: :param inidate: :param enddate: :return: """ if not inidate: inidate = datetime.datetime.utcnow() - datetime.timedelta(days=7, hours=8) if not enddate: enddate = datetime.datetime.utcnow() + datetime.timedelta(days=1) request_query = ("""SELECT a.designator, o.name, o.ra, o.dec, r.inidate, r.enddate, r.priority, r.status, r.lastmodified, r.obs_seq, r.exptime, r.id FROM request r, object o, allocation a WHERE o.id = r.object_id AND a.id = r.allocation_id AND ( r.enddate > DATE('%s') AND r.inidate <= DATE('%s') ) AND r.allocation_id IN (SELECT a.id FROM allocation a, groups g, usergroups ug, users u, program p WHERE ug.user_id = u.id AND ug.group_id = g.id AND u.id = %d AND p.group_id = g.id AND a.program_id = p.id ) ORDER BY r.lastmodified DESC;""" % (inidate, enddate, user_id)) data = db.execute_sql(request_query) data = pd.DataFrame(data, columns=['allocation', 'object', 'RA', 'DEC', 'start date', 'end date', 'priority', 'status', 'lastmodified', 'obs_seq', 'exptime', 'UPDATE']) if user_id in superuser_list: pass # data['UPDATE'] = data['UPDATE'].apply(convert_to_link) else: data.drop(columns=['RA', 'DEC']) return data def convert_to_link(reqid): return """http://pharos.caltech.edu/request?request_id=%s""" % reqid ############################################################################### # THIS SECTION HANDLES ALL THINGS RELATED TO THE OBJECT PAGE. # # KEYWORD:OBJECT # ############################################################################### def get_object(object_name, user_id): """ :param object_name: :param user_id: :return: """ if user_id: pass # 1. Start by getting the requested object objects = get_object_info(object_name, out_type='html') # 2. Check if there were and objects if not then go on if not objects: return {'message': 'Could not find any targets with that name under ' 'your allocation'} else: return {'message': objects['message']} ############################################################################### # THIS SECTION HANDLES ALL THINGS RELATED TO THE LOGIN PAGE. # # KEYWORD:LOGIN # ############################################################################### def check_login(username, password): """ :param username: :param password: :return: """ user_pass = db.get_from_users(['username', 'password', 'id'], {'username': username}) # print(user_pass) if not user_pass: return False, 'Incorrect username or password!' if check_password_hash(user_pass[0][1], password=password): return True, user_pass[0][2] else: return False, 'Incorrect username or password!!' def password_change(form, user_id): """ :param form: :param user_id: :return: """ # check for correct password and change if true password = form.password.data new_password = form.pass_new.data new_password_conf = form.pass_conf.data user_pass = db.get_from_users(['username', 'password', 'id'], {'id': user_id}) if not user_pass: return {'message': "User not found"} elif user_pass[0] == -1: message = user_pass[1] return {'message': message} elif check_password_hash(user_pass[0][1], password): if new_password == new_password_conf: db.update_user({'id': user_pass[0][2], 'password': new_password}) return {'message': 'Password Changed!'} else: message = "Incorrect username or password!" return {'message': message} ############################################################################### # THIS SECTION HANDLES ALL THINGS RELATED TO THE STATS PAGE. # # KEYWORD:STATS # ############################################################################### def get_project_stats(content, user_id=""): """ :param content: :param user_id: :return: """ # Start by getting all the allocations for a user if 'inidate' not in content: inidate = None else: inidate = content['inidate'] if 'enddate' not in content: enddate = None else: enddate = content['enddate'] data = get_allocation_stats(user_id, inidate=inidate, enddate=enddate) plots = plot_stats_allocation(data) script, div = components(plots) return {'script': script, 'div': div} def get_allocation_stats(user_id, inidate=None, enddate=None): """ Obtains a list of allocations that belong to the user and query the total allocated name and time spent for that allocation. If no user_id is provided, all active allocations are returned. """ if user_id is None: res = db.get_from_allocation(["designator", "time_allocated", "time_spent"], {"active": True}) df = pd.DataFrame(res, columns=["designator", "time_allocated", "time_spent"]) alloc_hours = np.array([ta.total_seconds() / 3600. for ta in df["time_allocated"]]) spent_hours = np.array([ts.total_seconds() / 3600. for ts in df["time_spent"]]) free_hours = alloc_hours - spent_hours free_hours[np.where(free_hours < 0)] = 0. df = df.assign(alloc_hours=alloc_hours, spent_hours=spent_hours, free_hours=free_hours) else: if inidate is None or enddate is None: res = db.execute_sql(""" SELECT a.designator, a.time_allocated, a.time_spent FROM allocation a, program p, groups g, usergroups ug WHERE a.program_id = p.id AND p.group_id = g.id AND g.id = ug.group_id AND a.active is True AND ug.user_id = %d""" % user_id) df = pd.DataFrame(res, columns=["designator", "time_allocated", "time_spent"]) alloc_hours = np.array([ta.total_seconds() / 3600. for ta in df["time_allocated"]]) spent_hours = np.array([ts.total_seconds() / 3600. for ts in df["time_spent"]]) free_hours = alloc_hours - spent_hours free_hours[np.where(free_hours < 0)] = 0. df = df.assign(alloc_hours=alloc_hours, spent_hours=spent_hours, free_hours=free_hours) else: res = db.execute_sql(""" SELECT DISTINCT a.id, a.designator, a.time_allocated FROM allocation a, program p, groups g, usergroups ug WHERE a.program_id = p.id AND p.group_id = g.id AND g.id = ug.group_id AND a.active is True AND ug.user_id = %d;""" % user_id) allocdes = [] spent_hours = [] alloc = [] for ais in res: spent = db.get_allocation_spent_time(ais[0], inidate, enddate) allocdes.append(ais[1]) spent_hours.append(int(spent) / 3600.) alloc.append(ais[2]) res = np.array([allocdes, alloc, spent_hours]) df = pd.DataFrame(res.T, columns=["designator", "time_allocated", "time_spent"]) alloc_hours = np.array([ta.total_seconds() / 3600. for ta in df["time_allocated"]]) free_hours = alloc_hours - spent_hours free_hours[np.where(free_hours < 0)] = 0. df = df.assign(alloc_hours=alloc_hours, spent_hours=spent_hours, free_hours=free_hours) df = df.sort_values(by=["alloc_hours"], ascending=False) alloc_names = df["designator"].values category = ["alloc_hours", "spent_hours", "free_hours"] data = {'allocations': alloc_names} for cat in category: data[cat] = df[cat] return data def plot_stats_allocation(data): """ Plots in the shape of bars the time available and spent for each active allocation. """ data = {key: np.nan_to_num(data[key]) for key in data} # Create the first plot with the allocation hours alloc_names = data['allocations'] categories = ["spent_hours", "free_hours"] colors = ["#e84d60", "darkgreen"] # "#c9d9d3" n_names = len(alloc_names) source = ColumnDataSource(data=data) p = figure(x_range=alloc_names, plot_height=420, plot_width=80 * 8, title="Time spent/available for SEDM allocations this term", toolbar_location=None, tools="") p.vbar_stack(categories, x='allocations', width=0.9, color=colors, source=source, legend=["Spent", "Available"]) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_right" p.legend.orientation = "horizontal" p.yaxis.axis_label = 'Hours' p.xaxis.major_label_orientation = 0.3 # Create the second plot with the % spent alloc_names = data['allocations'] percentage = (data["spent_hours"] / data["alloc_hours"]) * 100 colors = n_names * ['#084594'] '''for i, p in enumerate(percentage): if p<50: colors[i] = '#22A784' elif p>50 and p<75: colors[i] = '#FD9F6C' else: colors[i] = '#DD4968''' source = ColumnDataSource(data=dict(alloc_names=alloc_names, percentage=percentage, color=colors)) p2 = figure(x_range=alloc_names, y_range=(0, 100), plot_height=420, plot_width=80 * 8, title="Percentage of time spent", toolbar_location=None, tools="") p2.vbar(x='alloc_names', top='percentage', width=0.9, color='color', source=source) p2.xgrid.grid_line_color = None p2.legend.orientation = "horizontal" p2.legend.location = "top_center" p2.yaxis.axis_label = '% time spent' p2.xaxis.major_label_orientation = 0.3 # Create the pie charts pie_colors = 10 * ["red", "green", "blue", "orange", "yellow", 'lime', 'brown', 'cyan', 'magenta', 'olive', 'black', 'teal', 'gold', 'crimson', 'moccasin', 'greenyellow', 'navy', 'ivory', 'lightpink'] # First one with the time spent # define starts/ends for wedges from percentages of a circle percents_only = np.round(np.array(list(data["spent_hours"] / np.sum(data["spent_hours"]))) * 100, 1) percents = np.cumsum([0] + list(data["spent_hours"] / np.sum(data["spent_hours"]))) starts = [per * 2 * np.pi for per in percents[:-1]] ends = [per * 2 * np.pi for per in percents[1:]] p3 = figure(x_range=(-1, 2.5), y_range=(-1.1, 1.1), plot_height=420, plot_width=600, title="% spent") # Add individual wedges: for i in range(n_names): p3.wedge(x=0, y=0, radius=.9, start_angle=starts[i], end_angle=ends[i], color=pie_colors[i], legend="[{0}%] {1}".format(percents_only[i], alloc_names[i])) p3.xgrid.grid_line_color = None p3.ygrid.grid_line_color = None p3.legend.orientation = "vertical" p3.legend.location = "top_right" p3.legend.border_line_alpha = 0 p3.legend.background_fill_color = None p3.xaxis.visible = False p3.yaxis.visible = False # Second one with the time allocated # define starts/ends for wedges from percentages of a circle percents_only = np.round(np.array(list(data["alloc_hours"] / np.sum(data["alloc_hours"]))) * 100, 1) percents = np.cumsum([0] + list(data["alloc_hours"] / np.sum(data["alloc_hours"]))) starts = [per * 2 * np.pi for per in percents[:-1]] ends = [per * 2 * np.pi for per in percents[1:]] p4 = figure(x_range=(-1, 2.5), y_range=(-1.1, 1.1), plot_height=420, plot_width=600, title="% time allocated to each program") # Add individual wedges: for i in range(n_names): p4.wedge(x=0, y=0, radius=.9, start_angle=starts[i], end_angle=ends[i], color=pie_colors[i], legend="[{0}%] {1}".format(percents_only[i], alloc_names[i])) p4.xgrid.grid_line_color = None p4.ygrid.grid_line_color = None p4.legend.orientation = "vertical" p4.legend.location = "top_right" p4.legend.border_line_alpha = 0 p4.legend.background_fill_color = None p4.xaxis.visible = False p4.yaxis.visible = False layout = row(column(p, p2), column(p4, p3)) curdoc().add_root(layout) curdoc().title = "Allocation stats" return layout ############################################################################### # THIS SECTION HANDLES ALL THINGS RELATED TO THE VIEW_DATA PAGE. # # KEYWORD:VIEW_DATA # ############################################################################### def get_ab_what(obsdir): """get a pseudo what list for A/B cubes""" ablist = [] cubes = glob.glob(os.path.join(obsdir, "e3d_crr_b_ifu*.fits")) for e3df in cubes: # get root filename rute = '_'.join(e3df.split('/')[-1].split('_')[1:7]) # is this a standard single cube? crrf = glob.glob(os.path.join(obsdir, rute + '.fit*')) if len(crrf) > 0: continue fname = '_'.join(e3df.split('/')[-1].split('_')[3:7]) + '.fits' targ = e3df.split('/')[-1].split('_')[7].split('.fit')[0] ablist.append(" "+fname+" (1.000/0.1/1.0 s): " + targ + " [A]") return ablist def get_ifu_products(obsdir=None, user_id=None, obsdate="", show_finder=True, product_type='all', camera_type='ifu'): """ :param obsdir: :param user_id: :param obsdate: :param product_type: :param show_finder: :param camera_type: :return: """ # ifu_dict = {} if product_type: pass if camera_type: pass if not obsdate: obsdate = datetime.datetime.utcnow().strftime("%Y%m%d") else: obsdate = obsdate[0] if not obsdir: obsdir = '%s%s/' % (redux_dir, obsdate) else: obsdir = obsdir[0] # Look first to make sure there is a data directory. if not os.path.exists(obsdir): return {'message': 'No data directory could be located for %s UT' % os.path.basename(os.path.normpath(obsdir)), 'obsdate': obsdate} sedm_dict = {'obsdate': obsdate, 'sci_data': ''} # Now lets get the non-science products (i.e. calibrations) calib_dict = {'flat3d': os.path.join(obsdir, '%s_flat3d.png' % obsdate), 'wavesolution': os.path.join(obsdir, '%s_wavesolution' '_dispersionmap.png' % obsdate), 'cube_lambdarms': os.path.join(obsdir, 'cube_lambdarms.png'), 'cube_trace_sigma': os.path.join(obsdir, 'cube_trace_sigma.png')} # If a calibration frame doesn't exist then pop it out to avoid bad links # on the page remove_list = [] div_str = '' for k, v in calib_dict.items(): if not os.path.exists(v): remove_list.append(k) if remove_list: for i in remove_list: calib_dict.pop(i) # print(calib_dict, 'calib products') if user_id == 2: # SEDM_admin if os.path.exists(os.path.join(obsdir, 'report.txt')): ext_report = """<a href="http://pharos.caltech.edu/data_r/redux/{0}/report.txt">Extraction</a>""".format(obsdate) else: ext_report = "" if os.path.exists(os.path.join(obsdir, 'report_ztf_fritz.txt')): frz_report = """<a href="http://pharos.caltech.edu/data_r/redux/{0}/report_ztf_fritz.txt">Fritz</a>""".format(obsdate) else: frz_report = "" if os.path.exists(os.path.join(obsdir, 'report_ztf_growth.txt')): grw_report = """<a href="http://pharos.caltech.edu/data_r/redux/{0}/report_ztf_growth.txt">Growth</a>""".format(obsdate) else: grw_report = "" if os.path.exists(os.path.join(obsdir, 'what.txt')): wha_report = """<a href="http://pharos.caltech.edu/data_r/redux/{0}/what.txt" type="plain/text">What</a>""".format(obsdate) else: wha_report = "" div_str += """<div class="row">""" div_str += """<h4>Reports</h4>""" div_str += """{0} {1} {2} {3}""".format(ext_report, frz_report, grw_report, wha_report) div_str += "</div>" div_str += """<div class="row">""" div_str += """<h4>Calibrations</h4>""" for k, v in calib_dict.items(): impath = "/data/%s/%s" % (obsdate, os.path.basename(v)) impathlink = "/data/%s/%s" % (obsdate, os.path.basename(v.replace('.png', '.pdf'))) if not os.path.exists(impathlink): impathlink = impath div_str += """<div class="col-md-{0}"> <div class="thumbnail"> <a href="{1}"> <img src="{2}" width="{3}px" height="{4}px"> </a> </div> </div>""".format(2, impathlink, impath, 400, 400) div_str += "</div>" sedm_dict['sci_data'] += div_str # To get ifu products we first look to see if a what.list file has been # created. This way we will know which files to add to our dict and # whether the user has permissions to see the file if not os.path.exists(os.path.join(obsdir, 'what.list')): return {'message': 'Could not find summary file (what.list) for %s UT' % os.path.basename(os.path.normpath(obsdir))} # Go through the what list and return all non-calibration entries with open(os.path.join(obsdir, 'what.list')) as f: what_list = f.read().splitlines() if os.path.exists(os.path.join(obsdir, 'abpairs.tab')): what_list.extend(get_ab_what(obsdir)) what_list.sort() science_list = [] standard_list = [] for targ in what_list: if 'Calib' in targ: pass elif '[A]' in targ or '[B]' in targ or 'STD' in targ: science_list.append(targ) elif 'STD' in targ: pass # standard_list.append(targ) else: # There shouldn't be anything here but should put something in # later to verify this is the case pass # Now we go through and make sure the user is allowed to see this target show_list = [] if len(science_list) >= 1: allocation_id_list = get_allocations_user(user_id=user_id, return_type='list') for sci_targ in science_list: object_id = False target_requests = False # Start by pulling up all request that match the science target targ_name = sci_targ.split(':')[1].split()[0] if 'STD' not in targ_name: # 1. Get the object id object_ids = db.get_object_id_from_name(targ_name) if len(object_ids) == 1: object_id = object_ids[0][0] elif len(object_ids) > 1: # TODO what really needs to happen here is that we need to # TODO cont: find the id that is closest to the obsdate. # TODO cont: For now I am just going to use last added # print(object_ids) object_id = object_ids[-1][0] elif not object_ids and ('at' in targ_name.lower() or 'sn' in targ_name.lower()): # sometimes it's at 2018abc not at2018abc in the db targ_name = targ_name[:2] + ' ' + targ_name[2:] object_ids = db.get_object_id_from_name(targ_name) try: object_id = object_ids[-1][0] except IndexError: object_id = False # print("There was an error. You can't see this") # If we are not the admin then we need to check # if the user can see the object if user_id not in [2, 20200227202025683]: if object_id: target_requests = db.get_from_request( values=['allocation_id'], where_dict={'object_id': object_id, 'status': 'COMPLETED'}) if not target_requests: target_requests = db.get_from_request( values=['allocation_id'], where_dict={'object_id': object_id, 'status': 'OBSERVED'}) # print("Object id", object_id) # Right now I am only seeing if there exists a match between # allocations of all request. It's possible the request # could have been made by another group as another follow-up # and thus the user shouldn't be able to see it. This # should be able to be fixed once all request are listed in # the headers of the science images. for req in target_requests: # print(sci_targ, targ_name) # print(allocation_id_list, # "List of allocations this person can see") if req[0] in allocation_id_list: show_list.append((sci_targ, targ_name)) else: print("You can't see this at allocation id list") else: show_list.append((sci_targ, targ_name)) else: targ_name = sci_targ.split(':')[1].split()[0].replace('STD-', '') show_list.append((sci_targ, targ_name)) if len(standard_list) >= 1: for std_targ in standard_list: targ_name = std_targ.split(':')[1].split()[0].replace('STD-', '') show_list.append((std_targ, targ_name)) # We have our list of targets that we can be shown, now lets actually find # the files that we will show on the web page. To make this backwards # compatible I have to look for two types of files if len(show_list) >= 1: science_dict = {} count = 0 div_str = '' for targ in show_list: # print(targ) targ_params = targ[0].split() fits_file = targ_params[0].replace('.fits', '') name = targ[1] image_list = (glob.glob('%sifu_spaxels_*%s*.png' % (obsdir, fits_file)) + glob.glob('%simage_%s*.png' % (obsdir, name))) spec_list = (glob.glob('%s%s_SEDM.png' % (obsdir, name)) + glob.glob('%sspec_forcepsf*%s*.png' % (obsdir, fits_file)) + glob.glob('%sspec_auto*%s*.png' % (obsdir, fits_file))) e3d_list = (glob.glob('%se3d*%s*.fits' % (obsdir, fits_file))) spec_ascii_list = (glob.glob('%sspec_forcepsf*%s*.txt' % (obsdir, fits_file)) + glob.glob('%sspec_auto*%s*.txt' % (obsdir, fits_file))) fluxcals = (glob.glob('%sfluxcal_*%s*.fits' % (obsdir, fits_file))) if name not in science_dict: science_dict[name] = {'image_list': image_list, 'spec_list': spec_list, 'e3d_list': e3d_list, 'spec_ascii_list': spec_ascii_list, 'fluxcals': fluxcals} else: # We do this to handle cases where there are two or more of # the same object name science_dict[name+'_xRx_%s' % str(count)] = { 'image_list': image_list, 'spec_list': spec_list, 'e3d_list': e3d_list, 'spec_ascii_list': spec_ascii_list, 'fluxcals': fluxcals} count += 1 # Alright now we build the table that will show the spectra, image file # and classification. # count = 0 for obj, obj_data in science_dict.items(): if '_xRx_' in obj: obj = obj.split('_xRx_')[0] if 'ZTF' in obj: obj_link = ('<a href="https://fritz.science/source/' '%s">%s</a>' % (obj, obj)) div_str += """<div class="row">""" div_str += """<h4>%s</h4>""" % obj_link else: div_str += """<div class="row">""" div_str += """<h4>%s</h4>""" % obj if obj_data['e3d_list']: for j in obj_data['e3d_list']: impath = "/data/%s/%s" % (obsdate, os.path.basename(j)) div_str += ('<div class="col-md-{2}">' '<a href="%s">E3D File</a>' '</div>' % impath) if obj_data['spec_ascii_list']: for j in obj_data['spec_ascii_list']: impath = "/data/%s/%s" % (obsdate, os.path.basename(j)) div_str += ('<div class="col-md-{2}">' '<a href="%s">ASCII Spec File</a>' '</div>' % impath) if obj_data['fluxcals']: for j in obj_data['fluxcals']: impath = "/data/%s/%s" % (obsdate, os.path.basename(j)) div_str += ('<div class="col-md-{2}">' '<a href="%s">Flux calibration file</a>' '</div>' % impath) # ToDO: Grab data from somewhere to put in the meta data column if obj_data['image_list']: for i in obj_data['image_list']: impath = "/data/%s/%s" % (obsdate, os.path.basename(i)) impathlink = "/data/%s/%s" % ( obsdate, os.path.basename(i.replace('.png', '.pdf'))) if not os.path.exists(impathlink): impathlink = impath div_str += """<div class="col-md-{0}"> <div class="thumbnail"> <a href="{1}"> <img src="{2}" width="{3}px" height="{4}px"> </a> </div> </div>""".format(2, impathlink, impath, 400, 400) if show_finder: # Check if finders exists in redux directory and if not then # log at the old phot directory location path1 = os.path.join(redux_dir, obsdate, 'finders') path2 = os.path.join(phot_dir, obsdate, 'finders') if os.path.exists(path1): finder_path = path1 else: finder_path = path2 if os.path.exists(finder_path): finder_img = glob.glob(finder_path + '/*%s*.png' % obj) if finder_img: impathlink = "/data/%s/%s" % ( obsdate, os.path.basename(finder_img[-1])) div_str += """<div class="col-md-{0}"> <div class="thumbnail"> <a href="{1}"> <img src="{2}" width="{3}px" height="{4}px"> </a> </div> </div>""".format(4, impathlink, impathlink, 250, 250) if obj_data['spec_list']: for i in obj_data['spec_list']: impath = "/data/%s/%s" % (obsdate, os.path.basename(i)) impathlink = "/data/%s/%s" % ( obsdate, os.path.basename(i.replace('.png', '.pdf'))) if not os.path.exists(impathlink): impathlink = impath div_str += """<div class="col-lg-{0}"> <div class="thumbnail"> <a href="{1}"> <img src="{2}" width="{3}px" height="{4}px"> </a> </div> </div>""".format(4, impathlink, impath, 400, 400) div_str += "</div>" sedm_dict['sci_data'] += div_str return sedm_dict def get_rc_products(obsdate=None, product=None, user_id=None, camera_type='rc'): """ :param obsdate: :param product: :param user_id: :param camera_type: :return: """ if user_id: pass if camera_type: pass # print(product, 'product') raw_png_dir = ['acquisition', 'bias', 'dome', 'focus', 'guider_images', 'guider_movies', 'twilight', 'science_raw'] sedm_dict = {} if not obsdate: obsdate = datetime.datetime.utcnow().strftime("%Y%m%d") sedm_dict['obsdate'] = obsdate elif isinstance(obsdate, list): obsdate = obsdate[0] sedm_dict['obsdate'] = obsdate if not product: product = 'science' display_dict = {} ext = '*.png' sci_path = None if product.lower() == 'science': # print(new_phot_dir, obsdate) sci_path = os.path.join(new_phot_dir, obsdate, 'reduced', 'png') if not os.path.exists(sci_path): # print("Path doesn't exist", sci_path) sedm_dict['data'] = "No %s images found" % product elif product.lower() == 'acquisition': sci_path = os.path.join(new_phot_dir, obsdate, 'reduced', 'png') if not os.path.exists(sci_path): # print("Path doesn't exist", sci_path) sedm_dict['data'] = "No %s images found" % product elif product.lower() in raw_png_dir: # print(new_phot_dir, obsdate) if 'guider' in product.lower(): p_split = product.split("_") if p_split[-1] == 'movies': ext = '*.gif' product = 'guider' sci_path = os.path.join(new_phot_dir, obsdate, 'pngraw', product.lower().replace('_raw', '')) # print(sci_path, "Science path in alt") if not os.path.exists(sci_path): print("Path doesn't exist") # print("Looking in directory:", sci_path) find_path = os.path.join(sci_path, ext) # print(find_path, 'find_path') files = glob.glob(find_path) # print("Files found", files) for file in files: base_name = os.path.basename(file).replace(".png", "") if product.lower() == 'science' and 'ACQ' in base_name: continue elif product.lower() == 'science': filters = base_name.split("_") if filters[-1] == "0": objfilt = filters[-3] imgfilt = filters[-2] else: objfilt = filters[-2] imgfilt = filters[-1] if objfilt == imgfilt: if 'data' in display_dict: display_dict['data'].append(file) else: display_dict['data'] = [file] elif product.lower() == 'acquisition': if 'ACQ' not in base_name: continue elif "_r_r" not in base_name and "_NA_r" not in base_name: continue else: if 'data' in display_dict: display_dict['data'].append(file) else: display_dict['data'] = [file] else: if 'data' in display_dict: display_dict['data'].append(file) else: display_dict['data'] = [file] div_str = '' if user_id == 2: # SEDM_admin obsdir = os.path.join(new_phot_dir, obsdate) if os.path.exists(os.path.join(obsdir, 'rcwhat.txt')): wha_report = """<a href="http://pharos.caltech.edu/data_r/redux/phot/{0}/rcwhat.txt" type="plain/text">RCWhat</a>""".format(obsdate) div_str += """<div class="row">""" div_str += """<h4>{0}</h4>""".format(wha_report) div_str += "</div>" if 'data' in display_dict: count = 100 for fil in sorted(display_dict['data']): # fil = fil.replace(base_dir, '') impath = "/data_r/%s" % fil.replace(base_dir, '') if 'reduced' in fil: fits_suffix = '.fits' if os.path.exists(fil.replace('/png', '').replace('.png', '.fits.gz')): fits_suffix = '.fits.gz' fil = fil.replace(base_dir, '') impathlink = "/data_r/%s" % fil.replace('/png/', '/').replace( '.png', fits_suffix) elif 'pngraw' in fil and '.gif' not in fil: base_link = fil.replace(base_dir, '').split('/pngraw/')[0] fits_suffix = '.fits' png_suffix = '_all.png' if 'Bias' in fil or 'Flat' in fil: png_suffix = '.png' if os.path.exists( os.path.join( new_phot_dir, obsdate, os.path.basename(fil).replace(png_suffix, '.fits.gz'))): fits_suffix = '.fits.gz' fil = fil.replace(base_dir, '') impathlink = "/data_r/%s" % \ os.path.join(base_link, os.path.basename(fil).replace( png_suffix, fits_suffix)) else: impathlink = "/data_r/%s" % fil.replace(base_dir, '') div_str += """<div class="col-sm-4"><div class="card"> <a href="{1}?image={4}" data-toggle="lightbox" data-gallery="example-gallery"> <img style="width:300px" class="card-img-top" src="{1}?image{4}" alt="Card image"> </a> <div class="cardbody"> <h6 class="card-title">{2}</h6> <a href="http://pharos.caltech.edu{0}" class="btn btn-primary"> Download </a> </div> </div></div>""".format(impathlink, impath, os.path.basename(fil), impath, count) count += 1 div_str += '' sedm_dict['data'] = div_str else: sedm_dict['data'] = "No %s images found" % product # print(sedm_dict) return sedm_dict ############################################################################### # THIS SECTION HANDLES THE ACTIVE_VISIBILITIES PAGE. # # KEYWORD:VISIBILITIES #??? # ############################################################################### def get_pending_visibility(userid): sedm_dict = {'enddate': datetime.datetime.utcnow() + datetime.timedelta(days=1), 'inidate': datetime.datetime.utcnow() - datetime.timedelta(days=3, hours=8)} # 1. Get a dataframe of all requests for the current user reqs = get_requests_for_user(userid, sedm_dict['inidate'], sedm_dict['enddate']) # organize requests into dataframes by whether they are pending or not pending = reqs[(reqs['status'] == 'PENDING')] # retrieve information about the user's allocations # ac = get_allocations_user(userid) # Create html tables sedm_dict['pending'] = {'table': fancy_request_table(pending), 'title': 'Pending Requests'} sedm_dict['script'], sedm_dict['div'] = plot_visibility(userid, sedm_dict) return sedm_dict def plot_visibility(userid, sedm_dict, obsdate=None): """ plots visibilities for pending/active requests at the current date. Will be adapted to plot previous observations and arbitrary objects userid: user whose allocations will be shown in color with details. Others will be greyed out userid: <int> sedm_dict: <dict> should have ['active']['table'] and ['enddate'] and ['inidate'] obsdate: <str> YYYYMMDD if "None", will use current date returns: components of a bokeh figure with the appropriate plot """ allocpalette = ['#1f78b4', '#33a02c', '#e31a1c', '#ff7f00', '#6a3d9a', '#b15928', '#a6cee3', '#b2df8a', '#fb9a99', '#fdbf6f', '#cab2d6', '#ffff99'] reqs = get_requests_for_user(2, sedm_dict['inidate'], sedm_dict['enddate']) # admin active = reqs[(reqs['status'] == 'PENDING') | (reqs['status'] == 'ACTIVE')] # ['allocation', 'object', 'RA', 'DEC', 'start date', 'end date', # 'priority', 'status', 'lastmodified', 'obs_seq', 'exptime', 'UPDATE'] allowed_allocs = get_allocations_user(userid) active['allocation'].mask(~np.in1d(active['allocation'], allowed_allocs['allocation']), other='other', inplace=True) programs = {i['allocation']: i['program'] for _, i in allowed_allocs.iterrows()} programs['other'] = 'other' # this needs to be alphabetical for the legend to look correct active.sort_values('allocation') p = figure(plot_width=700, plot_height=500, toolbar_location='above', y_range=(0, 90), y_axis_location="right") # setup with axes, sun/moon, frames, background # TODO Dima says to never ever use SkyCoord in production code palomar_mountain = EarthLocation(lon=243.1361*u.deg, lat=33.3558*u.deg, height=1712*u.m) utcoffset = -7 * u.hour # Pacific Daylight Time # plotting a single object, or the pending objects in future if obsdate is None: time = (Time.now() - utcoffset).datetime # date is based on local time time = Time(datetime.datetime(time.year, time.month, time.day)) else: # past observations on a particular night time = Time(datetime.datetime(int(obsdate[:4]), int(obsdate[4:6]), int(obsdate[6:8]))) # all_requests = reqs[reqs['status'] == 'COMPLETED'] # all_requests = all_requests[time - 12 * u.hour # <= all_requests['startdate'] # < time + 12 * u.hour] midnight = time - utcoffset # 7am local time of correct date, midnight UTC delta_midnight = np.linspace(-8, 8, 500) * u.hour t = midnight + delta_midnight abstimes = np.asarray([i.datetime.strftime('%I:%M %p') for i in t + utcoffset]) frame = AltAz(obstime=t, location=palomar_mountain) sun_alt = get_sun(t).transform_to(frame).alt moon_alt = get_moon(t).transform_to(frame).alt # shading for nighttime and twilight dark_times = delta_midnight[sun_alt < 0].value twilit_times = delta_midnight[sun_alt < -18 * u.deg].value plotted_times = delta_midnight[sun_alt < 5 * u.deg].value twilight = BoxAnnotation(left=min(twilit_times), right=max(twilit_times), bottom=0, fill_alpha=0.15, fill_color='black', level='underlay') night = BoxAnnotation(left=min(dark_times), right=max(dark_times), bottom=0, fill_alpha=0.25, fill_color='black', level='underlay') earth = BoxAnnotation(top=0, fill_alpha=0.8, fill_color='sienna') p.add_layout(night) p.add_layout(twilight) p.add_layout(earth) # sun # p.line(delta_midnight, sun_alt, line_color='red', name="Sun", # legend='Sun', line_dash='dashed') # moon p.line(delta_midnight, moon_alt, line_color='yellow', line_dash='dashed', name="Moon", legend='Moon') # labels and axes p.title.text = "Visibility for %s UTC" % midnight p.xaxis.axis_label = "Hours from PDT Midnight" p.x_range.start = min(plotted_times) p.x_range.end = max(plotted_times) p.yaxis.axis_label = "Airmass" # primary airmass label on right airmasses = (1.01, 1.1, 1.25, 1.5, 2., 3., 6.) ticker = [90 - np.arccos(1./i) * 180/np.pi for i in airmasses] p.yaxis.ticker = ticker p.yaxis.major_label_overrides = {tick: str(airmasses[i]) for i, tick in enumerate(ticker)} # add supplementary alt label on left p.extra_y_ranges = {"altitude": Range1d(0, 90)} p.add_layout(LinearAxis(y_range_name="altitude", axis_label='Altitude [deg]'), 'left') ########################################################################## # adding data from the actual objects # objs = SkyCoord(np.array(ras, dtype=np.float), # np.array(decs, dtype=np.float), unit="deg") approx_midnight = int(Time.now().jd - .5) + .5 - utcoffset.value/24. palo_sin_lat = 0.549836545 palo_cos_lat = 0.835272275 palo_long = 243.1362 alloc_color = {} for i, val in allowed_allocs.iterrows(): alloc_color[val['allocation']] = allocpalette[i % len(allocpalette)] alloc_color['other'] = 'lightgray' tooltipped = [] # things with tooltips # make it #name when we get to bokeh 0.13 tooltips = [('obj', '@name'), ('time', '@abstime'), ('altitude', u"@alt\N{DEGREE SIGN}"), ('airmass', '@airmass')] for _, req in active.iterrows(): # iterrows doesn't preserve datatypes and turns ra, dec into decimals? req['ra'] = float(req['RA']) req['dec'] = float(req['DEC']) color = alloc_color[req['allocation']] # vvv I got this formula from some website for the navy # but forgot to copy the url alt = 180 / np.pi * np.arcsin(palo_cos_lat * np.cos(np.pi/180 * (palo_long - req['ra'] + 15 * (18.697374558 + 24.06570982 * (delta_midnight.value/24. + approx_midnight - 2451545)))) * np.cos(req['dec'] * np.pi/180) + palo_sin_lat * np.sin(req['dec'] * np.pi/180)) airmass = 1./np.cos((90 - alt) * np.pi/180) source = ColumnDataSource(dict(times=delta_midnight, alt=alt, airmass=airmass, abstime=abstimes, priority=np.full(len(t), int(req['priority'])), alloc=np.full(len(t), req['allocation'][6:]), name=np.full(len(abstimes), req['object']))) # delete the name when we get to bokeh 0.13 if len(active) == 1: # single object legend = req['object'] line_width = 5 else: legend = '{}'.format(programs[req['allocation']]) # tooltips += [('priority', '@priority'), # ('allocation', '@alloc')] # plot that highlights observed part of the night if req['status'] == 'COMPLETED': # full path of the night dotted = p.line('times', 'alt', color=color, source=source, line_dash='2 2', name=req['object'], line_width=1, legend=legend) # manually crop the source so only thick observed # part has tooltips endtime = req['lastmodified'] # TODO sometimes it's 2ifu or no ifu exptime = {req['obs_seq'][i]: req['exptime'][i] for i in range(len(req['obs_seq']))}['1ifu'] initime = endtime - exptime * u.second mask = np.logical_and( delta_midnight + midnight + utcoffset > initime, delta_midnight + midnight + utcoffset < endtime) source = ColumnDataSource(pd.DataFrame(source.data)[mask]) # all it changes is the line width line_width = int(req['priority'] + 3) else: line_width = int(req['priority']) path = p.line('times', 'alt', color=color, source=source, name=''.format(req['object']), line_width=line_width, legend=legend) if not req['allocation'] == 'other': tooltipped.append(path) p.legend.click_policy = 'hide' p.legend.location = 'bottom_right' p.add_tools(HoverTool(renderers=tooltipped, tooltips=tooltips)) curdoc().add_root(p) curdoc().title = 'Visibility plot' return components(p) ############################################################################### # THIS SECTION IS THE WEATHER STATS SECTION. # # KEYWORD:WEATHER_STATS # ############################################################################### def get_weather_stats(obsdate=None): message = "" if not obsdate: # get the weather stats statsfile, mydate = search_stats_file() if statsfile is not None and mydate is not None: stats_plot = plot_stats(statsfile, mydate) if stats_plot is None: message += " No statistics log found up to 100 days prior to" \ " today... Weather has been terrible lately!" script, div = None, None else: message += " Weather statistics for last opened day: %s" % ( os.path.basename(os.path.dirname(os.path.dirname( statsfile)))) script, div = components(stats_plot) else: script, div = None, None else: mydate_in = obsdate.replace("-", "") # Just making sure that we have only allowed digits in the date mydate = re.findall(r"(2\d{3}[0-1]\d[0-3]\d)", mydate_in) if len(mydate) == 0: message += "Incorrect format for the date! Your input is: %s." \ " Shall be YYYYMMDD. \n" % mydate_in script, div = "", "" else: mydate = mydate[0] message = "" statsfile, mydate_out = search_stats_file(mydate) stats_plot = plot_stats(statsfile, mydate) if not statsfile: message = message + "No statistics log found for the date %s." \ " Showing P18 data." % mydate script, div = components(stats_plot) else: stats_plot = plot_stats(statsfile, mydate) message = message + "Weather statistics for selected day: %s"\ % mydate script, div = components(stats_plot) return {'script': script, 'div': div, 'message': message} def search_stats_file(mydate=None): """ Returns the last stats file that is present in the system according to the present date. It also returns a message stating what date that was. """ # If the date is specified, we will try to locate the right file. # None will be returned if it does not exist. if mydate: s = os.path.join(phot_dir, mydate, "stats/stats.log") if os.path.exists(s): if os.path.getsize(s) > 0: return s, mydate else: return None, None else: s = os.path.join(new_phot_dir, mydate, "stats/stats.log") if os.path.exists(s): if os.path.getsize(s) > 0: return s, mydate else: return None, None return None, None else: curdate = datetime.datetime.utcnow() # Try to find the stat files up to 100 days before today's date. i = 0 while i < 100: newdate = curdate newdatedir = "%d%02d%02d" % (newdate.year, newdate.month, newdate.day) s = os.path.join(phot_dir, newdatedir, "stats/stats.log") s_new = os.path.join(new_phot_dir, newdatedir, "stats/stats.log") if os.path.exists(s): if os.path.getsize(s) > 0: return s, newdatedir # else: # return None, None elif os.path.exists(s_new): if os.path.getsize(s_new) > 0: return s_new, newdatedir # else: # return None, None i = i + 1 curdate -= datetime.timedelta(days=1) return None, None def load_p48seeing(obsdate): obtime, seeing = get_p18obsdata(obsdate) local_date = np.array(obtime) d = pd.DataFrame({'date': local_date, 'seeing': seeing}) return d def load_stats(statsfile='stats.log'): data = pd.read_csv(statsfile, header=None, names=['path', 'obj', 'jd', 'ns', 'fwhm', 'ellipticity', 'bkg', 'airmass', 'in_temp', 'imtype', 'out_temp', 'in_hum']) jds = data['jd'] t = Time(jds, format='jd', scale='utc') date = t.utc.datetime day_frac_diff = datetime.timedelta( np.ceil((datetime.datetime.now() - datetime.datetime.utcnow()).total_seconds()) / 3600 / 24) local_date = date + day_frac_diff data2 = data.assign(localdate=local_date) data2.set_index('localdate') return pd.DataFrame( {'date': data2['localdate'], 'ns': data2['ns'], 'fwhm': data2['fwhm'], 'ellipticity': data2['ellipticity'], 'bkg': data2['bkg'], 'airmass': data2['airmass'], 'in_temp': data2['in_temp'], 'imtype': data2['imtype'], 'out_temp': data2['out_temp'], 'in_hum': data2['in_hum']}) def plot_stats(statsfile, mydate): source = ColumnDataSource( data=dict(date=[], ns=[], fwhm=[], ellipticity=[], bkg=[], airmass=[], in_temp=[], imtype=[], out_temp=[], in_hum=[])) source_static = ColumnDataSource( data=dict(date=[], ns=[], fwhm=[], ellipticity=[], bkg=[], airmass=[], in_temp=[], imtype=[], out_temp=[], in_hum=[])) view_science = CDSView(source=source, filters=[GroupFilter(column_name='imtype', group='SCIENCE')]) view_acquisition = CDSView(source=source, filters=[GroupFilter(column_name='imtype', group='ACQUISITION')]) view_guider = CDSView(source=source, filters=[GroupFilter(column_name='imtype', group='GUIDER')]) view_focus = CDSView(source=source, filters=[GroupFilter(column_name='imtype', group='FOCUS')]) source_p48 = ColumnDataSource(data=dict(date=[], seeing=[])) def update(selected=None): if selected: pass if statsfile: data = load_stats(statsfile) source.data = source.from_df(data[['date', 'ns', 'fwhm', 'ellipticity', 'bkg', 'airmass', 'in_temp', 'imtype', 'out_temp', 'in_hum']]) source_static.data = source.data p48 = load_p48seeing(mydate) source_p48.data = source_p48.from_df(p48[['date', 'seeing']]) source_static_p48.data = source_p48.data source_static_p48 = ColumnDataSource(data=dict(date=[], seeing=[])) tools = 'pan,box_zoom,reset' p48seeing = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") p48seeing.circle('date', 'seeing', source=source_static_p48, color="black") p48seeing.title.text = "P18 seeing [arcsec]" if statsfile: ns = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") ns.line('date', 'ns', source=source_static) ns.circle('date', 'ns', size=1, source=source, color=None, selection_color="orange") ns.title.text = "Number of bright sources extracted" bkg = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") bkg.x_range = ns.x_range bkg.line('date', 'bkg', source=source_static) bkg.circle('date', 'bkg', size=1, source=source, color=None, selection_color="orange") bkg.title.text = "Background (counts)" temp = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") temp.x_range = ns.x_range temp.line('date', 'in_temp', source=source_static, color='blue', legend="Inside") temp.line('date', 'out_temp', source=source_static, color='green', legend="Outside") temp.circle('date', 'in_temp', size=1, source=source, color=None, selection_color="orange") temp.title.text = "Temperature [C]" fwhm = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") fwhm.x_range = ns.x_range fwhm.circle('date', 'fwhm', source=source_static, color="green", legend="Focus", view=view_focus) fwhm.circle('date', 'fwhm', source=source_static, color="red", legend="Science", view=view_science) fwhm.circle('date', 'fwhm', source=source_static, color="blue", legend="Acquisition", view=view_acquisition) fwhm.circle('date', 'fwhm', source=source_static, color="black", legend="Guider", view=view_guider) fwhm.circle('date', 'fwhm', size=1, source=source, color=None, selection_color="orange") fwhm.title.text = "P60 FWHM [arcsec]" airmass = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") airmass.x_range = ns.x_range airmass.line('date', 'airmass', source=source_static) airmass.circle('date', 'airmass', size=1, source=source, color=None, selection_color="orange") airmass.title.text = "Airmass" ellipticity = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") ellipticity.x_range = ns.x_range ellipticity.line('date', 'ellipticity', source=source_static) ellipticity.circle('date', 'ellipticity', size=1, source=source, color=None, selection_color="orange") ellipticity.title.text = "Ellipticity" humidity = figure(plot_width=425, plot_height=250, tools=tools, x_axis_type='datetime', active_drag="box_zoom") humidity.x_range = ns.x_range humidity.line('date', 'in_hum', source=source_static) humidity.circle('date', 'in_hum', size=1, source=source, color=None, selection_color="orange") humidity.title.text = "Inside Humidity [%]" p48seeing.x_range = ns.x_range left = column(fwhm, p48seeing, airmass) center = column(ellipticity, ns, bkg, ) right = column(temp, humidity) layout = row(left, center, right) else: layout = row(column(p48seeing)) # initialize update() curdoc().add_root(layout) curdoc().title = "Stats" return layout def plot_not_found_message(day): not_found = figure(plot_width=900, plot_height=450, x_range=[0, 900], y_range=[0, 450]) not_found.image(image=[np.zeros([900, 450]) + 0.1], x=0, y=0, dw=900, dh=450) citation = Label(x=50, y=225, x_units='screen', y_units='screen', text='No statistics found for today \n ' '(likely we were weathered out...)') not_found.add_layout(citation) not_found.title.text = "Statistics not found for day %s" % day layout = column(not_found) curdoc().add_root(layout) curdoc().title = "Stats not found" ############################################################################### # THIS SECTION IS A COMMON UTILITIES SECTION # # KEYWORD:UTILITIES # ############################################################################### def get_config_paths(): return dict(path={ 'path_archive': redux_dir, 'path_phot': phot_dir, 'path_redux_phot': new_phot_dir, 'path_raw': raw_dir, 'path_requests': requests_dir}) def get_marshal_id(marshal='growth', request_id=None): """ :param marshal: :param request_id: :return: """ try: request_id = int(request_id) except Exception as e: return {'error': str(e)} ret = db.get_from_request(values=['marshal_id', 'external_id'], where_dict={'id': request_id}) if not ret: return {'error': "No object found with that id number"} if marshal == 'growth': ret = make_dict_from_dbget(['marshal_id', 'external_id'], ret[0]) if isinstance(ret['marshal_id'], int) and ret['marshal_id'] <= 100: return {'error': "Request is not a valid growth marshal request"} elif isinstance(ret['marshal_id'], str): return {'error': ret['marshal_id']} elif not ret['marshal_id']: return {'error': ret['marshal_id']} elif ret['external_id'] == 2: return {'error': "Not a growth request"} else: return ret def get_user_observations(username, password, obsdate): """ :param username: :param password: :param obsdate: :return: """ # print(username, type(username)) ret = check_login(username, password) # print(ret) if not ret[0]: return {'message': "User name and password do not match"} user_id = ret[1] obsdir = os.path.join(redux_dir, obsdate) obsdir += '/' calib_files = ['Xe.fits', 'Hg.fits', 'Cd.fits', 'dome.fits', 'bkgd_dome.fits', 'e3d_dome.fits', '%s_Flat.fits' % obsdate] pkl_list = (glob.glob('%s*.pkl' % obsdir)) master_calib_list = [] for file in calib_files: if os.path.exists(os.path.join(obsdir, file)): master_calib_list.append(os.path.join(obsdir, file)) master_calib_list += pkl_list # print(master_calib_list, 'master') # Look first to make sure there is a data directory. if not obsdate: return {'message': 'No obsdate given in json request'} if not os.path.exists(obsdir): return {'message': 'No data directory could be located for %s UT' % os.path.basename(os.path.normpath(obsdir)), 'obsdate': obsdate} # sedm_dict = {'obsdate': obsdate, 'sci_data': ''} # Now lets get the non-science products (i.e. calibrations) calib_dict = {'flat3d': os.path.join(obsdir, '%s_flat3d.png' % obsdate), 'wavesolution': os.path.join(obsdir, '%s_wavesolution' '_dispersionmap.png' % obsdate), 'cube_lambdarms': os.path.join(obsdir, 'cube_lambdarms.png'), 'cube_trace_sigma': os.path.join(obsdir, 'cube_trace_sigma.png')} # If a calibration frame doesn't exist then pop it out to avoid bad links # on the page remove_list = [] data_list = [] for k, v in calib_dict.items(): if not os.path.exists(v): remove_list.append(k) if remove_list: for i in remove_list: calib_dict.pop(i) # print(calib_dict, 'calib products') for v in master_calib_list: impath = "/data/%s/%s" % (obsdate, os.path.basename(v)) data_list.append(impath) for k, v in calib_dict.items(): impath = "/data/%s/%s" % (obsdate, os.path.basename(v)) impathlink = "/data/%s/%s" % (obsdate, os.path.basename(v.replace('.png', '.pdf'))) if not os.path.exists(impathlink): impathlink = impath data_list.append(impathlink) # To get ifu products we first look to see if a what.list file has been # created. This way we will know which files to add to our dict and # whether the user has permissions to see the file if not os.path.exists(os.path.join(obsdir, 'what.list')): return {'message': 'Could not find summary file (what.list) for %s UT' % os.path.basename(os.path.normpath(obsdir))} # Go throught the what list and return all non-calibration entries with open(os.path.join(obsdir, 'what.list')) as f: what_list = f.read().splitlines() science_list = [] standard_list = [] for targ in what_list: if 'Calib' in targ: pass elif '[A]' in targ or '[B]' in targ or 'STD' in targ: science_list.append(targ) elif 'STD' in targ: standard_list.append(targ) else: # There shouldn't be anything here but should put something in # later to verify this is the case pass # Now we go through and make sure the user is allowed to see this target show_list = [] if len(science_list) >= 1: allocation_id_list = get_allocations_user(user_id=user_id, return_type='list') for sci_targ in science_list: # Start by pulling up all request that match the science target targ_name = sci_targ.split(':')[1].split()[0] if user_id == 2: show_list.append((sci_targ, targ_name)) continue if 'STD' not in targ_name: # 1. Get the object id object_ids = db.get_object_id_from_name(targ_name) object_id = None if len(object_ids) == 1: object_id = object_ids[0][0] elif len(object_ids) > 1: # TODO what really needs to happen here is that we need to # TODO find the id that is closest to the obsdate. # TODO For now I am just going to use last added # print(object_ids) object_id = object_ids[-1][0] elif not object_ids and ('at' in targ_name.lower() or 'sn' in targ_name.lower()): # sometimes it's at 2018abc not at2018abc in the db targ_name = targ_name[:2] + ' ' + targ_name[2:] object_ids = db.get_object_id_from_name(targ_name) try: object_id = object_ids[-1][0] except IndexError: print("There was an error. You can't see this") target_requests = db.get_from_request( values=['allocation_id'], where_dict={'object_id': object_id, 'status': 'COMPLETED'}) if not target_requests: target_requests = db.get_from_request( values=['allocation_id'], where_dict={'object_id': object_id, 'status': 'OBSERVED'}) # Right now I am only seeing if there exists a match between # allocations of all request. It's possible the request could # have been made by another group as another follow-up and thus # the user shouldn't be able to see it. This should be able to # be fixed once all request are listed in the headers of the # science images. for req in target_requests: if req[0] in allocation_id_list: show_list.append((sci_targ, targ_name)) else: print("You can't see this at target request") else: targ_name = sci_targ.split(':')[1].split()[0].replace('STD-', '') show_list.append((sci_targ, targ_name)) if len(standard_list) >= 1: for std_targ in standard_list: targ_name = std_targ.split(':')[1].split()[0].replace('STD-', '') show_list.append((std_targ, targ_name)) # We have our list of targets that we can be shown, now lets actually find # the files that we will show on the web page. To make this backwards # compatible I have to look for two types of files # print(show_list, "Show list") if len(show_list) >= 1: science_dict = {} count = 0 # div_str = '' for targ in show_list: # print(targ) targ_params = targ[0].split() fits_file = targ_params[0].replace('.fits', '') name = targ[1] # print(obsdir, fits_file) # print('%s%s_SEDM.png' % (obsdir, name)) # print('%sspec_forcepsf*%s*.png' % (obsdir,fits_file)) # print('%sspec_auto*%s*.png' % (obsdir, fits_file)) image_list = (glob.glob('%sifu_spaxels_*%s*.png' % (obsdir, fits_file)) + glob.glob('%simage_%s*.png' % (obsdir, name))) spec_list = (glob.glob('%s%s_SEDM.png' % (obsdir, name)) + glob.glob('%sspec_forcepsf*%s*.png' % (obsdir, fits_file)) + glob.glob('%sspec_auto*%s*.png' % (obsdir, fits_file))) spec_all_list = glob.glob("%sspec*%s*" % (obsdir, name)) e3d_list = (glob.glob('%se3d*%s*.fits' % (obsdir, fits_file))) spec_ascii_list = (glob.glob('%sspec_forcepsf*%s*.txt' % (obsdir, fits_file)) + glob.glob('%sspec_auto*%s*.txt' % (obsdir, fits_file))) fluxcals = (glob.glob('%sfluxcal_*%s*.fits' % (obsdir, fits_file))) background = (glob.glob('%sbkgd_crr_b_%s.fits' % (obsdir, fits_file))) astrom_list = (glob.glob('%sguider_crr_b_%s_astrom.fits' % (obsdir, fits_file))) if name not in science_dict: science_dict[name] = {'image_list': image_list, 'spec_list': spec_list, 'e3d_list': e3d_list, 'spec_ascii_list': spec_ascii_list, 'fluxcals': fluxcals, 'specall': spec_all_list, 'background': background, 'astrom': astrom_list} else: # We do this to handle cases where there are two or more of # the same object name science_dict[name+'_xRx_%s' % str(count)] = { 'image_list': image_list, 'spec_list': spec_list, 'e3d_list': e3d_list, 'spec_ascii_list': spec_ascii_list, 'fluxcals': fluxcals, 'specall': spec_all_list, 'background': background, 'astrom': astrom_list} count += 1 # Alright now we build the table that will show the spectra, image file # and classification. # count = 0 # print(science_dict) for obj, obj_data in science_dict.items(): if '_xRx_' in obj: obj = obj.split('_xRx_')[0] if obj_data['e3d_list']: for j in obj_data['specall']: if j.split('.')[-1] in ['fits', 'png', 'txt', 'pdf']: data_list.append("/data/%s/%s" % (obsdate, os.path.basename(j))) for j in obj_data['e3d_list']: data_list.append("/data/%s/%s" % (obsdate, os.path.basename(j))) if obj_data['spec_ascii_list']: for j in obj_data['spec_ascii_list']: data_list.append("/data/%s/%s" % (obsdate, os.path.basename(j))) if obj_data['fluxcals']: for j in obj_data['fluxcals']: data_list.append("/data/%s/%s" % (obsdate, os.path.basename(j))) if obj_data['background']: for j in obj_data['background']: data_list.append("/data/%s/%s" % (obsdate, os.path.basename(j))) if obj_data['astrom']: for j in obj_data['astrom']: data_list.append("/data/%s/%s" % (obsdate, os.path.basename(j))) # ToDO: Grab data from somewhere to put in the meta data column if obj_data['image_list']: for i in obj_data['image_list']: impath = "/data/%s/%s" % (obsdate, os.path.basename(i)) impathlink = "/data/%s/%s" % \ (obsdate, os.path.basename(i.replace('.png', '.pdf'))) if not os.path.exists(impathlink): impathlink = impath data_list.append(impathlink) # Check if finders exists in redux directory and if not then # log at the old phot directory location path1 = os.path.join(redux_dir, obsdate, 'finders') path2 = os.path.join(phot_dir, obsdate, 'finders') if os.path.exists(path1): finder_path = path1 else: finder_path = path2 if os.path.exists(finder_path): finder_img = glob.glob(finder_path + '/*%s*.png' % obj) if finder_img: data_list.append("/data/%s/%s" % (obsdate, os.path.basename(finder_img[-1]))) if obj_data['spec_list']: for i in obj_data['spec_list']: impath = "/data/%s/%s" % (obsdate, os.path.basename(i)) impathlink = "/data/%s/%s" % \ (obsdate, os.path.basename(i.replace('.png', '.pdf'))) if not os.path.exists(impathlink): impathlink = impath data_list.append(impathlink) return_dict = {'data': data_list} return return_dict def get_status(): """ :return: """ with open(status_dir+'telstatus.json') as json_file: try: data = json.load(json_file) except json.decoder.JSONDecodeError: print("JSON decode error, trying again") json_file.close() time.sleep(1) with open(status_dir + 'telstatus.json') as json_file2: try: data = json.load(json_file2) except json.decoder.JSONDecodeError: print("JSON decode error") data = {} try: rc_start_time = datetime.datetime.strptime(data['rc_LastStartTime'], '%Y-%m-%d %H:%M:%S.%f') rc_end_time = rc_start_time + datetime.timedelta( seconds=float(data['rc_ExposureTime'])) data['rc_EndExposureTime'] = rc_end_time.strftime("%Y-%m-%d %H:%M:%S") data['rc_LastStartTime'] = rc_start_time.strftime("%Y-%m-%d %H:%M:%S") except: data['rc_EndExposureTime'] = "NA" data['rc_LastStartTime'] = "NA" try: ifu_start_time = datetime.datetime.strptime(data['ifu_LastStartTime'], '%Y-%m-%d %H:%M:%S.%f') ifu_end_time = ifu_start_time + datetime.timedelta( seconds=float(data['ifu_ExposureTime'])) data['ifu_EndExposureTime'] = ifu_end_time.strftime("%Y-%m-%d %H:%M:%S") data['ifu_LastStartTime'] = ifu_start_time.strftime("%Y-%m-%d %H:%M:%S") except: data['ifu_EndExposureTime'] = "NA" data['ifu_LastStartTime'] = "NA" # print("Last IFU exp start time: %s" % data['ifu_LastStartTime']) return data def get_obstimes(): times = schedule.get_observing_times(return_type='json') times['sciTime'] = '#' return times def make_dict_from_dbget(headers, data, decimal_to_float=True): """ This function takes data from the returns of get_from_* returns and puts it in a dictionary form :param decimal_to_float: :param headers: list of db header names :param data: tuples :return: """ if len(headers) != len(data): return {'error': 'headers and data are not of equal lengths'} return_dict = {} for i in range(len(headers)): if decimal_to_float and isinstance(data[i], Decimal): return_dict[headers[i]] = float(data[i]) else: return_dict[headers[i]] = data[i] return return_dict def get_filter_exptime(obsfilter, mag): """ :param obsfilter: :param mag: :return: """ mag = float(mag) if mag > 18: ifu_exptime = 2250 r_exptime = 180 g_exptime = 180 i_exptime = 180 u_exptime = 300 elif 15 < mag < 18: ifu_exptime = 1800 r_exptime = 120 g_exptime = 120 i_exptime = 120 u_exptime = 300 elif 13 < mag < 15: ifu_exptime = 1200 r_exptime = 1 g_exptime = 1 i_exptime = 1 u_exptime = 30 elif 11 < mag < 13: ifu_exptime = 90 r_exptime = 10 g_exptime = 10 i_exptime = 10 u_exptime = 60 elif 10 < mag < 12: ifu_exptime = 300 r_exptime = 30 g_exptime = 30 i_exptime = 30 u_exptime = 60 elif 12 < mag < 13: ifu_exptime = 600 r_exptime = 60 g_exptime = 60 i_exptime = 60 u_exptime = 120 elif 13 < mag < 15: ifu_exptime = 900 r_exptime = 90 g_exptime = 90 i_exptime = 90 u_exptime = 180 else: ifu_exptime = 1800 r_exptime = 90 g_exptime = 90 i_exptime = 90 u_exptime = 90 if obsfilter == 'ifu': return str(ifu_exptime) elif obsfilter == 'r': return str(r_exptime) elif obsfilter == 'g': return str(g_exptime) elif obsfilter == 'i': return str(i_exptime) elif obsfilter == 'u': return str(u_exptime) else: return str(0) def get_p18obsdata(obsdate): """ :param obsdate: Must be in "Year-Month-Day" or "YYYYMMDD" format :return: List of dates and average seeing """ # 1. Create the URL to get the seeing for the requested night p18date = [] p18seeing = [] if not obsdate: f = datetime.datetime.strptime(obsdate, "%Y%m%d") - datetime.timedelta(days=1) obsd = datetime.datetime.strptime(obsdate, "%Y%m%d") elif "-" in obsdate: f = datetime.datetime.strptime(obsdate, "%Y-%m-%d") - datetime.timedelta(days=1) obsd = datetime.datetime.strptime(obsdate, "%Y-%m-%d") else: f = datetime.datetime.strptime(obsdate, "%Y%m%d") - datetime.timedelta(days=1) obsd = datetime.datetime.strptime(obsdate, "%Y%m%d") y, m, d = [f.strftime("%Y"), int(f.strftime("%m")), int(f.strftime("%d"))] p18obsdate = "%s-%s-%s" % (y, m, d) # 2. Get the data from the link page = requests.get( 'http://nera.palomar.caltech.edu/P18_seeing/seeing_log_%s.log' % p18obsdate) data = page.content.decode("ISO-8859-1") # 3. Split the page by newlines data = data.split('\n') # 4. Loop through the data and only use points that have # 4 or more seeing values to average for i in data: try: i = i.split() if len(i) > 5 and int(i[5]) > 4: d = '%s %s' % (i[1], i[0]) p18date.append(datetime.datetime.strptime(d, "%m/%d/%Y %H:%M:%S")) p18seeing.append(float(i[4])) except Exception as e: print(str(e)) obsd = obsd.replace(hour=7) return [obsd], [0] return p18date, p18seeing # if __name__ == "__main__": # x = get_ifu_products('/scr7/rsw/sedm/redux/20180827/', 189) # print(x)
scizen9/sedmpy
web/model.py
model.py
py
117,058
python
en
code
5
github-code
36
21877547543
from TeamCloud_Modul.Blockchain import Transaction import requests import json import os from TeamCloud_Modul.Node import Node from TeamCloud_Modul.json_parser import Message, JSON_Parser, get_checksum from cryptography.hazmat.primitives import serialization from requests.api import request from create_Keys import create_key class Agent: def __init__(self, name, debug=True): self.name = name self.url = "https://mastpamarkt.azurewebsites.net/" # Init paths self.filepath = os.path.dirname(os.path.abspath(__file__)) self.backup_path = self.filepath + "/backup.txt" self.public_key_path = self.filepath + "/public.pem" self.private_key_path = self.filepath + "/private.pem" self.json_parser = JSON_Parser() # Init public and private key if not (os.path.exists(self.public_key_path) and os.path.getsize(self.public_key_path) > 0 and os.path.exists(self.private_key_path) and os.path.getsize(self.private_key_path) > 0): create_key() print("Keys being created") with open(self.public_key_path, "rb") as key_file: pubkey = key_file.read() self.__public_key = serialization.load_pem_public_key(pubkey) with open(self.private_key_path, "rb") as key_file: self.__private_key = serialization.load_pem_private_key( key_file.read(), password=None, ) self.node = Node(name = name, private_key = self.__private_key, public_key = self.__public_key) # Init from Backup self.read_backup() self.registration(debug=debug) def print_chain(self, pretty=True): self.node.print_chain(pretty=pretty) def print_balance(self, all=False): self.node.print_balance(all=all) def print_quotes(self, product): self.node.print_quotes(product = product) def get_balance(self, all=False): return self.node.get_balance(all=all) def get_quotes(self, product): return self.node.get_quotes(product = product) def registration(self, debug=True): try: # Built Message pem = self.__public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) request_msg = Message(sender=self.name,receiver='Cloud',parser_type='type_default', message_type='default', payload={"user": self.name, "password": pem.decode('utf-8')},checksum='checksum') # Parse Message to JSON json_request_msg = self.json_parser.parse_message_to_dump(request_msg) # Request json_response_msg = requests.post(url=self.url + "/Registration/", json=json_request_msg).json() # Parse JSON to Message response_msg = self.json_parser.parse_dump_to_message(json_response_msg) # Sync Blockchain if response_msg.payload['status'] < 2: self.__sync_blockchain() info_handler={ 0:'[Info] Successfully registered', 1:'[Info] Successfully logged in', 2:'[Error] Name already exists. Choose another username', 3:'[Error] Registration failed', } if debug==True: print(info_handler.get(response_msg.payload['status'],"Error occured")) except Exception as e: if debug==True: print('[Error] Error occured. Registration call failed.') if debug==True: print(e) def send_cloud_missing_blocks(self): last_cloud_hash = self._get_last_cloud_hash() for idx, block in enumerate(self.node.blockchain.chain): if block.hash == last_cloud_hash: break payload = self.json_parser.parse_chain_to_dump(self.node.blockchain.chain[idx+1:]) request_msg = Message(sender=self.name, receiver='receiver', parser_type='type_default', message_type='block_msg', payload=payload, checksum=get_checksum(payload)) json_message = self.json_parser.parse_message_to_dump(request_msg) json_response_msg = requests.put(url=self.url + "/CloudInitialization/",json=json_message).json() return json_response_msg def _get_last_cloud_hash(self): json_response_msg = requests.get(url=self.url + "/CloudInitialization/").json() return json_response_msg def __sync_blockchain(self): ############################################# Get Header Message ############################################# start_hash, stop_hash = self.node.get_payload_for_get_headers_msg() payload = [start_hash, stop_hash] # Built Message request_msg = Message(sender=self.name, receiver='receiver', parser_type='type_default', message_type='get_headers_msg', payload=payload, checksum=get_checksum(payload)) # Parse Message to JSON json_request_msg = self.json_parser.parse_message_to_dump(request_msg) # Request json_response_msg = requests.post(url=self.url + "/Blockchain/", json=json_request_msg).json() # Parse JSON to Message response_msg = self.json_parser.parse_dump_to_message(json_response_msg) self.node.handle_incoming_message(response_msg) # workaround self.node.handle_incoming_message(response_msg) ############################################# Get Blocks Message ############################################# payload = self.node.get_payload_for_get_blocks_msg() request_msg = Message(sender=self.name, receiver='receiver', parser_type='type_default', message_type='get_blocks_msg', payload=payload, checksum=get_checksum(payload)) # Parse Message to JSON json_request_msg = self.json_parser.parse_message_to_dump(request_msg) # Request json_response_msg = requests.post(url=self.url + "/Blockchain/", json=json_request_msg).json() # Parse JSON to Message response_msg = self.json_parser.parse_dump_to_message(json_response_msg) self.node.handle_incoming_message(response_msg) # Update Backup self.write_backup() def quote(self, quote_list=[], debug=True): try: self.send_cloud_missing_blocks() payload = {"quote_list": quote_list} # Built Message request_msg = Message(sender=self.name,receiver='Cloud',parser_type='type_default', message_type='default', payload=payload,checksum='checksum') # Parse Message to JSON json_request_msg = self.json_parser.parse_message_to_dump(request_msg) # Request json_response_msg = requests.post(url=self.url + "/Quote/", json=json_request_msg).json() # Parse JSON to Message response_msg = self.json_parser.parse_dump_to_message(json_response_msg) info_handler={ 0:'[Info] Successfully Quote Call.', 1:'[Warning] Quotes List is Empty. Try later again.', 2:'[Warning] Quote Call failed. Syntax Error.', } if debug==True: print(info_handler.get(response_msg.payload['status'],"Error occured")) if response_msg.payload['status'] == 0: # Extract Response response = response_msg.payload['quotes']['List'] return {'Status': True, 'Response': response} except Exception as e: if debug==True: print('[Error] Error occured. Quote call failed.') if debug==True: print(e) return {'Status': False, 'Response': {}} def buy(self, product, quantity, debug=True): try: # Get Quote Data response_quote = self.quote([product], debug=debug) # Check Quote Call was successfully if response_quote["Status"] == True: payload = {"product": product, "quantity": quantity} signature = self.node.create_signature(payload) payload.update({'signature':signature}) # Built Message request_msg = Message(sender=self.name,receiver='Cloud',parser_type='type_default', message_type='default', payload=payload,checksum='checksum') # Parse Message to JSON json_request_msg = self.json_parser.parse_message_to_dump(request_msg) # Request json_response_msg = requests.post(url=self.url + "/Buy/", json=json_request_msg).json() # Parse JSON to Message response_msg = self.json_parser.parse_dump_to_message(json_response_msg) info_handler={ 0:'[Info] Transaction successfully.', 1:'[Warning] Buy Call failed caused by Quote.', 2:'[Warning] Buy Call failed. Validity check failed.', 3:'[Error] Signature comparison faced an issue.', 4:'[Error] Buy Call failed. Syntax Error.', } if debug==True: print(info_handler.get(response_msg.payload['status'],"Error occured")) if response_msg.payload['status'] == 0: # Sync Blockchain self.__sync_blockchain() return {'Status': True, 'Response': None} else: if debug==True: print("[Warning] Buy Call failed. Validity check failed.") return {'Status': False, 'Response': None} except Exception as e: if debug==True: print('[Error] Error occured. Buy call failed.') if debug==True: print(e) return {'Status': False, 'Response': None} def sell(self, product, quantity, debug=True): try: # Get Quote Data response_quote = self.quote([product], debug=debug) # Check Quote Call was successfully if response_quote["Status"] == True: payload = {"product": product, "quantity": quantity} signature = self.node.create_signature(payload) payload.update({'signature':signature}) # Built Message request_msg = Message(sender=self.name,receiver='Cloud',parser_type='type_default', message_type='default', payload=payload,checksum='checksum') # Parse Message to JSON json_request_msg = self.json_parser.parse_message_to_dump(request_msg) # Request json_response_msg = requests.post(url=self.url + "/Sell/", json=json_request_msg).json() # Parse JSON to Message response_msg = self.json_parser.parse_dump_to_message(json_response_msg) info_handler={ 0:'[Info] Transaction successfully.', 1:'[Warning] Sell Call failed caused by Quote.', 2:'[Warning] Sell Call failed. Validity check failed.', 3:'[Error] Signature comparison faced an issue.', 4:'[Error] Sell Call failed. Syntax Error.', } if debug==True: print(info_handler.get(response_msg.payload['status'],"Error occured")) if response_msg.payload['status'] == 0: # Sync Blockchain self.__sync_blockchain() return {'Status': True, 'Response': None} else: if debug==True: print("[Warning] Sell Call failed. Validity check failed.") return {'Status': False, 'Response': None} except Exception as e: if debug==True: print('[Error] Error occured. Sell call failed.') if debug==True: print(e) return {'Status': False, 'Response': None} def write_backup(self): # Check Text-File already Exists and isn't empty if os.path.exists(self.backup_path) and os.path.getsize(self.backup_path) > 0: os.remove(self.backup_path) json_obj = { "Name": self.name, "Blockchain": self.json_parser.parse_chain_to_dump(self.node.blockchain.chain) } with open(self.backup_path, "w") as f: json.dump(json_obj,f,indent=4) def read_backup(self): # Check Text-File already Exists and isn't empty if os.path.exists(self.backup_path) and os.path.getsize(self.backup_path) > 0: with open(self.backup_path, "r") as f: json_obj = json.loads(f.read()) self.node.blockchain.chain = self.json_parser.parse_dump_to_chain(json_obj["Blockchain"]) self.node.create_user_public_key_map() return True else: return False
Marcus11Dev/Blockchain_Lesson_Agent
agent.py
agent.py
py
13,436
python
en
code
0
github-code
36
12212813324
#!/usr/bin/env python ''' This is the parallel recursive solution to the Tower of Hanoi and is copied from the code written in the parallel/rebuilding-the-tower-of-hanoi/ page of www.drdobbs.com. The solution has been modified from drdobbs' solution to work with my limited knowledge of mpi4py. If you use the sleep() functionality to add some dead time into the loops - even a second will do - you'll start to see the computation time decrease as the number of processes increases. Currently the dead time is set to 2 seconds. The solution times for this dead time are: 1 proc 30.50s 2 procs 17.03s 4 procs 11.14s 8 procs 9.28s It's very hard to solve the problem in less than 12 seconds. I haven't been able to do it! ''' from mpi4py import MPI import sys import time import math import pickle comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() name = MPI.Get_processor_name() def tower(src, dest, temp, idx, offset, noofdiscs, plan): if (offset > 0): # Defines the level of recursion that we are at. It runs from 0 to # noofdiscs-1 throughout the calculation. level = noofdiscs - 2 - int(math.log(offset, 2)) # This if statement splits the processes in half at each level of # recursion until only one process is evaluating each 'branch'. # From there it evaluates all subsequent sub-branches and moves. if (rank % 2**(level+1) < 2**(level) and 2**(level) < size): # Recursively call tower again. This is the left branch, so # we SUBTRACT offset from idx. tower(src, temp, dest, idx-offset, offset/2, noofdiscs, plan); # Add some dead time here. time.sleep(2) # Adds the src and dest poles of move to the plan array. plan[idx-1][0] = src; plan[idx-1][1] = dest; elif (rank % 2**(level+1) >= 2**(level) and 2**(level) < size): # Add some dead time here. time.sleep(2) # Adds the src and dest poles of move to the plan array. plan[idx-1][0] = src; plan[idx-1][1] = dest; # Recursively call tower again. This is the right branch, so # we ADD offset to idx. tower(temp, dest, src, idx+offset, offset/2, noofdiscs, plan); else: # Recursively call tower again. This is the left branch, so # we SUBTRACT offset from idx. tower(src, temp, dest, idx-offset, offset/2, noofdiscs, plan); # Add some dead time here. time.sleep(2) # Adds the src and dest poles of move to the plan array. plan[idx-1][0] = src; plan[idx-1][1] = dest; # Recursively call tower again. This is the right branch, so # we ADD offset to idx. tower(temp, dest, src, idx+offset, offset/2, noofdiscs, plan); else: # Add some dead time here. time.sleep(2) # Once offset reaches zero the algorithm stops recursively calling # tower. Hence all that is left to do is populate the last elements # of the plan list. plan[idx-1][0] = src; plan[idx-1][1] = dest; return plan def main(): # Initialise the number of discs and the list for containing plan. # Initially it is populated with pairs of zeroes [0, 0], s.t. the number # of pairs is equal to the number of moves. #print "The number of processes is", size, "and this is process", rank noofdiscs = int(sys.argv[1]) plan_init = [] for i in range(0,2**noofdiscs-1): plan_init.append([0, 0]) # These two variables are used to keep track of the level of recursion # of the method. idx = 2**(noofdiscs - 1) offset = 2**(noofdiscs-2) # The plan - the set of moves that solves the tower of Hanoi problem - # is obtained by initialising the tower function, which recursively calls # ifself until the full solution is found. The solution will be # distributed across the processes used in the calculation. plan = tower(0, 2, 1, idx, offset, noofdiscs, plan_init) # Process 0 now gathers all the modified elements of data together into a # new list called allplans. allplans = comm.gather(plan,root=0) #print 'allplans:',allplans # The command gather has stuffed a bunch of mostly empty data lists into a # list. The first command essentially picks out all the non-trivial data # from each list returned from the processes and bundles it all into one # list, the solution. if rank == 0: plan=[max(i) for i in zip(*allplans)] #print 'master:',plan # We use pickle to make a moves file which we write the # plan list. We use pickle in main() to read the list again. outfile=open( "moves", "wb" ) pickle.dump(plan, outfile) main()
icluster/demos
hanoi/src/hanoi_soln_par.py
hanoi_soln_par.py
py
4,912
python
en
code
0
github-code
36
30075701833
# This file contains several global settings used across the rest of the scripts in the style # of a `startup.m` file in Matlab. I quite like this format, so I'll use it here as well :) # This is the location of the data on my computer # The data takes up about 24GB, so I store it on an # external hard drive # This is the default mount point for nemo (the file manager) DATA_LOCATION = "/run/media/jack/Seagate Portable Drive/Research/geogran2/" # The default number of frames to sample for in most Sampling.py methods DEFAULT_SAMPLE_LENGTH = 30 # This is the rate at which the force sensor took data FORCE_SENSOR_DT = .01
Jfeatherstone/FailurePrediction
geogran_old/toolbox/Settings.py
Settings.py
py
629
python
en
code
0
github-code
36
18896618824
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^johnjot/', include('johnjot.foo.urls')), (r'^api/', include('core.api.urls')), (r'^admin/', include(admin.site.urls)), )
maraca/JohnJot
core/urls.py
urls.py
py
329
python
en
code
4
github-code
36
20707090879
import os, time from Crypto.Random import get_random_bytes, random from lib.logger import * log = Logger() ''' This class handles the BLE Beacon Transmission (TX). Because after some time of BLE advertising, a restart of the BLE stack (hciconfig hci0 down / up) might be required, and because the pybleno class can't be shut down and restarted properly, the actual BLE handling has been placed in a separate python script "en_beacon.py". ''' class ENTxService: def __init__(self, bdaddr_rotation_interval_min_minutes, bdaddr_rotation_interval_max_minutes): self.random_bdaddr = bytes([0x00] * 6) self.bdaddr_rotation_interval_min_seconds = bdaddr_rotation_interval_min_minutes * 60 + 1 self.bdaddr_rotation_interval_max_seconds = bdaddr_rotation_interval_max_minutes * 60 - 1 if self.bdaddr_rotation_interval_max_seconds < self.bdaddr_rotation_interval_min_seconds: self.bdaddr_rotation_interval_max_seconds = self.bdaddr_rotation_interval_min_seconds self.bdaddr_next_rotation_seconds = 0 @staticmethod def get_current_unix_epoch_time_seconds(): return int(time.time()) @staticmethod def get_advertising_tx_power_level(): return 12 # in real life, this info should come from the BLE transmitter def roll_random_bdaddr(self): # Create a BLE random "Non-Resolvable Private Address", i.e. the two MSBs must be 0, and not all bits 0 or 1 while True: self.random_bdaddr = bytearray(get_random_bytes(6)) self.random_bdaddr[0] = self.random_bdaddr[0] & 0b00111111 self.random_bdaddr = bytes(self.random_bdaddr) if (self.random_bdaddr.hex() != "000000000000") and (self.random_bdaddr.hex() != "3fffffffffff"): break self.bdaddr_next_rotation_seconds = (self.get_current_unix_epoch_time_seconds() + random.randint(self.bdaddr_rotation_interval_min_seconds, self.bdaddr_rotation_interval_max_seconds)) def bdaddr_should_roll(self): return self.get_current_unix_epoch_time_seconds() >= self.bdaddr_next_rotation_seconds def start_beacon(self, rpi, aem): while True: if os.system("python3 en_beacon.py %s %s %s" % (rpi.hex(), aem.hex(), self.random_bdaddr.hex())) == 0: # return code 0 means: ok, advertising started. break log.log() log.log("ERROR: Could not start advertising! Timestamp: %s" % time.strftime("%H:%M:%S", time.localtime())) log.log() # try to recover: os.system("sudo hciconfig hci0 down; sudo hciconfig hci0 up") time.sleep(1) @staticmethod def stop_beacon(): os.system("sudo hciconfig hci0 down; sudo hciconfig hci0 up")
mh-/exposure-notification-ble-python
lib/en_tx_service.py
en_tx_service.py
py
2,883
python
en
code
28
github-code
36
71511379944
import math import random import collections import Artist import os LINE_LENGTH_MIN = 8 LINE_LENGTH_MAX = 12 EPSILON = 0.20 UNIGRAM_WEIGHT = 1 BIGRAM_WEIGHT = 10 TRIGRAM_WEIGHT = 100 # Preparatory code: Setting Up All Artists' N-grams # ------------------------------------------------- # Uni/bi/tri-grams from ALL of our artists are stored in /Data/unigrams.txt, # /Data/bigrams.txt, and /Data/trigrams.txt. We read these files and parse # them for later use in generate_one_line(). REPO_ROOT = os.popen("git rev-parse --show-toplevel").read().strip('\n') UNIVERSAL_UNIGRAMS = {} UNIVERSAL_BIGRAMS = {} UNIVERSAL_TRIGRAMS = {} f = open(REPO_ROOT + '/Data/unigrams.txt', 'r') line = f.readline() # Go through file, read each line of < word ... word || freq > and register it in the dict. while line != "": unigram = line.split('||')[0].strip() freq = int(line.split('||')[1].strip()) UNIVERSAL_UNIGRAMS[unigram] = freq line = f.readline() f = open(REPO_ROOT + '/Data/bigrams.txt', 'r') line = f.readline() # Go through file, read each line of < word ... word || freq > and register it in the dict. while line != "": gram = line.split('||')[0].strip().split() bigram = (gram[0], gram[1]) freq = int(line.split('||')[1].strip()) UNIVERSAL_BIGRAMS[bigram] = freq line = f.readline() f = open(REPO_ROOT + '/Data/trigrams.txt', 'r') line = f.readline() # Go through file, read each line of < word ... word || freq > and register it in the dict. while line != "": gram = line.split('||')[0].strip().split() trigram = (gram[0], gram[1], gram[2]) freq = int(line.split('||')[1].strip()) UNIVERSAL_TRIGRAMS[trigram] = freq line = f.readline() ################################################ # Function: Weighted Random Choice # -------------------------------- # Given a dictionary of the form element -> weight, selects an element # randomly based on distribution proportional to the weights. Weights can sum # up to be more than 1. def weightedRandomChoice(weightDict): weights = [] elems = [] for elem in weightDict: weights.append(weightDict[elem]) elems.append(elem) total = sum(weights) key = random.uniform(0, total) runningTotal = 0.0 chosenIndex = None for i in range(len(weights)): weight = weights[i] runningTotal += weight if runningTotal > key: chosenIndex = i return elems[chosenIndex] raise Exception('Should not reach here') # Helper: Get First Trigram # --------------------------- # Pick a random trigram under the Artist. # def get_first_trigram(artist, theme): weights = artist.trigrams for trigram in weights: weights[trigram] = weights[trigram]*TRIGRAM_WEIGHT*artist.theme_values[trigram][theme] \ + artist.bigrams[(trigram[0], trigram[1])]*BIGRAM_WEIGHT*artist.theme_values[(trigram[0], trigram[1])][theme] \ + artist.unigrams[trigram[0]]*artist.theme_values[trigram[0]][theme] weights[trigram] = math.log(weights[trigram] + 1.0) return weightedRandomChoice(weights) # Helper: Generate One Word # ------------------------- # Given the last 2 words, generate a next word based on the artist and the theme. # def generate_one_word(artist, first, second, theme): weights = {} for word in artist.unigrams: # Create independent uni, bi, tri-gram scores. trigram = (first, second, word) trigram_score = (artist.trigrams[trigram] if (trigram in artist.trigrams) else 0) * \ (artist.theme_values[trigram][theme] if (trigram in artist.theme_values) else 1) bigram = (second, word) bigram_score = (artist.bigrams[bigram] if (bigram in artist.bigrams) else 0) * \ (artist.theme_values[bigram][theme] if (bigram in artist.theme_values) else 1) unigram = word unigram_score = (artist.unigrams[unigram] if (unigram in artist.unigrams) else 0) * \ (artist.theme_values[unigram][theme] if (unigram in artist.theme_values) else 1) # If there is no trigram with (first, second, word) then DON'T include this word. # Continuing with a poor word will create a shitty lyric line. if trigram_score == 0: continue # This is the blender function to combine the three above. score = TRIGRAM_WEIGHT * math.log(trigram_score + 1.0) + BIGRAM_WEIGHT * math.log(bigram_score + 1.0) + UNIGRAM_WEIGHT * math.log(unigram_score + 1.0) weights[word] = score # NOTICE: This is going to have to chance once we implement external corpus epsilon, because a lot of sequences # of words will have no trigrams. # If we have NO words that will create a trigram next, then just end the line with !!END!!. if len(weights) == 0: return '!!END!!' return weightedRandomChoice(weights) # Helper: Generate One Word (Epsilon version) # ------------------------------------------- # Also generates one word, but from the UNIVERSAL grams data, not the artist-specific N-gram data. # def generate_one_word_epsilon(first, second): weights = {} for word in UNIVERSAL_UNIGRAMS: trigram = (first, second, word) trigram_score = UNIVERSAL_TRIGRAMS[trigram] if trigram in UNIVERSAL_TRIGRAMS else 0 bigram = (second, word) bigram_score = UNIVERSAL_BIGRAMS[bigram] if bigram in UNIVERSAL_BIGRAMS else 0 unigram = word unigram_score = UNIVERSAL_UNIGRAMS[unigram] # word must be in UNIVERSAL_UNIGRAMS. # If epsilon is activated, we need to be even safer: Do not pick next words not part of a trigram. if trigram_score == 0: continue score = TRIGRAM_WEIGHT * math.log(trigram_score + 1.0) + BIGRAM_WEIGHT * math.log(bigram_score + 1.0) + UNIGRAM_WEIGHT * math.log(unigram_score + 1.0) weights[word] = score * score # squared to bias toward higher-scored words, increase predictability to balance out extra randomness. # if there are no trigrams formed with (first, second, X), then return an END flag. This CAN happen. if len(weights) == 0: return '!!END!!' return weightedRandomChoice(weights) # Function: Generate One Line # --------------------------- # Generate one line of a song. Returned as a list of words. # def generate_one_line(artist, theme=1, epsilon=0.0): length_upper_bound = random.randint(LINE_LENGTH_MIN, LINE_LENGTH_MAX) first_trigram = get_first_trigram(artist, theme) line = [first_trigram[0], first_trigram[1], first_trigram[2]] first = first_trigram[1] second = first_trigram[2] for i in range(0, length_upper_bound - 3): # At a |epsilon| chance, we pick a word outside of our artist's corpus. if (random.random() < epsilon): next_word = generate_one_word_epsilon(first, second) # Other wise with |1-epsilon| chance, generate as usual with artist's corpus. else: next_word = generate_one_word(artist, first, second, theme) # Stop prematurely if '!!END!!' is received, because of reasons detailed in generate_one_word. if next_word == '!!END!!': break line.append(next_word) first = line[len(line)-2] second = line[len(line)-1] return line
ch-plattner/musical_croding
code/line_generator.py
line_generator.py
py
7,323
python
en
code
3
github-code
36
44255065901
trials = int(input()) input() for trial in range(trials): l = [] for i in range(8): l.append(list(input())) if trial!= trials-1: input() x = 0 y = 0 p = 2 for k in range(1,8): i = l[k] if '#' in i and i.count('#')==1: p = 1 elif '#' in i and i.count('#')==2: if p==1: x = k y = l[k-1].index('#')+1 p = 2 elif (p==2 or p==0 ) and x!=0 and y!=0: print(x,y) break
Ghanashyam-Bhat/CompetitiveProgramming
6-1-2022/3.py
3.py
py
532
python
en
code
1
github-code
36
35397910028
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import glob import os from textwrap import dedent import xml.dom.minidom as DOM import coverage from pants.backend.python.targets.python_library import PythonLibrary from pants.backend.python.targets.python_tests import PythonTests from pants.backend.python.test_builder import PythonTestBuilder from pants.base.build_file_aliases import BuildFileAliases from pants.util.contextutil import pushd, environment_as from pants_test.base_test import BaseTest class PythonTestBuilderTestBase(BaseTest): def run_tests(self, targets, args=None, fast=True, debug=False): test_builder = PythonTestBuilder(targets, args or [], fast=fast, debug=debug) with pushd(self.build_root): return test_builder.run() class PythonTestBuilderTestEmpty(PythonTestBuilderTestBase): def test_empty(self): self.assertEqual(0, self.run_tests(targets=[])) class PythonTestBuilderTest(PythonTestBuilderTestBase): @property def alias_groups(self): return BuildFileAliases.create( targets={ 'python_library': PythonLibrary, 'python_tests': PythonTests }) def setUp(self): super(PythonTestBuilderTest, self).setUp() self.create_file( 'lib/core.py', dedent(''' def one(): # line 1 return 1 # line 2 # line 3 # line 4 def two(): # line 5 return 2 # line 6 ''').strip()) self.add_to_build_file( 'lib', dedent(''' python_library( name='core', sources=[ 'core.py' ] ) ''')) self.create_file( 'tests/test_core_green.py', dedent(''' import unittest2 as unittest import core class CoreGreenTest(unittest.TestCase): def test_one(self): self.assertEqual(1, core.one()) ''')) self.create_file( 'tests/test_core_red.py', dedent(''' import core def test_two(): assert 1 == core.two() ''')) self.add_to_build_file( 'tests', dedent(''' python_tests( name='green', sources=[ 'test_core_green.py' ], dependencies=[ 'lib:core' ], coverage=[ 'core' ] ) python_tests( name='red', sources=[ 'test_core_red.py' ], dependencies=[ 'lib:core' ], coverage=[ 'core' ] ) python_tests( name='all', sources=[ 'test_core_green.py', 'test_core_red.py' ], dependencies=[ 'lib:core' ] ) python_tests( name='all-with-coverage', sources=[ 'test_core_green.py', 'test_core_red.py' ], dependencies=[ 'lib:core' ], coverage=[ 'core' ] ) ''')) self.green = self.target('tests:green') self.red = self.target('tests:red') self.all = self.target('tests:all') self.all_with_coverage = self.target('tests:all-with-coverage') def test_green(self): self.assertEqual(0, self.run_tests(targets=[self.green])) def test_red(self): self.assertEqual(1, self.run_tests(targets=[self.red])) def test_mixed(self): self.assertEqual(1, self.run_tests(targets=[self.green, self.red])) def test_junit_xml(self): # We expect xml of the following form: # <testsuite errors=[Ne] failures=[Nf] skips=[Ns] tests=[Nt] ...> # <testcase classname="..." name="..." .../> # <testcase classname="..." name="..." ...> # <failure ...>...</failure> # </testcase> # </testsuite> report_basedir = os.path.join(self.build_root, 'dist', 'junit') with environment_as(JUNIT_XML_BASE=report_basedir): self.assertEqual(1, self.run_tests(targets=[self.red, self.green])) files = glob.glob(os.path.join(report_basedir, '*.xml')) self.assertEqual(1, len(files)) junit_xml = files[0] with open(junit_xml) as fp: print(fp.read()) root = DOM.parse(junit_xml).documentElement self.assertEqual(2, len(root.childNodes)) self.assertEqual(2, int(root.getAttribute('tests'))) self.assertEqual(1, int(root.getAttribute('failures'))) self.assertEqual(0, int(root.getAttribute('errors'))) self.assertEqual(0, int(root.getAttribute('skips'))) children_by_test_name = dict((elem.getAttribute('name'), elem) for elem in root.childNodes) self.assertEqual(0, len(children_by_test_name['test_one'].childNodes)) self.assertEqual(1, len(children_by_test_name['test_two'].childNodes)) self.assertEqual('failure', children_by_test_name['test_two'].firstChild.nodeName) def coverage_data_file(self): return os.path.join(self.build_root, '.coverage') def load_coverage_data(self, path): data_file = self.coverage_data_file() self.assertTrue(os.path.isfile(data_file)) coverage_data = coverage.coverage(data_file=data_file) coverage_data.load() _, all_statements, not_run_statements, _ = coverage_data.analysis(path) return all_statements, not_run_statements def test_coverage_simple(self): self.assertFalse(os.path.isfile(self.coverage_data_file())) covered_file = os.path.join(self.build_root, 'lib', 'core.py') with environment_as(PANTS_PY_COVERAGE='1'): self.assertEqual(0, self.run_tests(targets=[self.green])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([6], not_run_statements) self.assertEqual(1, self.run_tests(targets=[self.red])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([2], not_run_statements) self.assertEqual(1, self.run_tests(targets=[self.green, self.red])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([], not_run_statements) # The all target has no coverage attribute and the code under test does not follow the # auto-discover pattern so we should get no coverage. self.assertEqual(1, self.run_tests(targets=[self.all])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([1, 2, 5, 6], not_run_statements) self.assertEqual(1, self.run_tests(targets=[self.all_with_coverage])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([], not_run_statements) def test_coverage_modules(self): self.assertFalse(os.path.isfile(self.coverage_data_file())) covered_file = os.path.join(self.build_root, 'lib', 'core.py') with environment_as(PANTS_PY_COVERAGE='modules:does_not_exist,nor_does_this'): # modules: should trump .coverage self.assertEqual(1, self.run_tests(targets=[self.green, self.red])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([1, 2, 5, 6], not_run_statements) with environment_as(PANTS_PY_COVERAGE='modules:core'): self.assertEqual(1, self.run_tests(targets=[self.all])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([], not_run_statements) def test_coverage_paths(self): self.assertFalse(os.path.isfile(self.coverage_data_file())) covered_file = os.path.join(self.build_root, 'lib', 'core.py') with environment_as(PANTS_PY_COVERAGE='paths:does_not_exist/,nor_does_this/'): # paths: should trump .coverage self.assertEqual(1, self.run_tests(targets=[self.green, self.red])) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([1, 2, 5, 6], not_run_statements) with environment_as(PANTS_PY_COVERAGE='paths:core.py'): self.assertEqual(1, self.run_tests(targets=[self.all], debug=True)) all_statements, not_run_statements = self.load_coverage_data(covered_file) self.assertEqual([1, 2, 5, 6], all_statements) self.assertEqual([], not_run_statements)
fakeNetflix/square-repo-pants
tests/python/pants_test/backend/python/test_test_builder.py
test_test_builder.py
py
8,998
python
en
code
0
github-code
36
33759274918
import json import codecs import sys if len(sys.argv) != 3: print('Usage: ' + sys.argv[0] + " <input json path> <output csv path>") exit() infilename = sys.argv[1] outfilename = sys.argv[2] sep = "|" out = open(outfilename, 'w') def processSource(sourceStr): source = sourceStr.lower() listOfAppleDevices = ["iphone", "ipad", "for ios", "for mac", "os x", "apple.com"] listOfAutoTools = ["ifttt", "dlvr.it", "hootsuite", "twitterfeed", "tweetbot", "twittbot", "roundteam", "hubspot", "socialoomph", "smqueue", "linkis.com", "tweet jukebox", "tweetsuite", "bufferapp", "thousandtweets", "postplanner", "manageflitter", "crowdfire"] listOfSocialPlatforms = ["facebook", "linkedin", "tumblr", "wordpress", "instagram", "pinterest"] listOfOtherMobile = ["windows phone", "mobile web", "for blackberry"] if "android" in source: return "android" for apple in listOfAppleDevices: if apple in source: return "appledevice" if "tweetdeck" in source: return "tweetdeck" if "twitter web client" in source: return "webclient" for soc in listOfSocialPlatforms: if soc in source: return "socialsite" for autoTool in listOfAutoTools: if autoTool in source: return "automated" for i in listOfOtherMobile: if i in source: return "othermobile" return "other" def isNiceRetweet(tweet): if 'retweeted_status' in tweet and tweet['retweeted_status'] != None: rts = tweet['retweeted_status'] if ('favorite_count' in rts and rts['favorite_count'] != None and 'retweet_count' in rts and rts['retweet_count'] != None and 'created_at' in rts and rts['created_at'] != None and 'source' in rts and rts['source'] != None and 'user' in rts and rts['user'] != None and 'followers_count' in rts['user'] and rts['user']['followers_count'] != None): return True return False def getRetweetedTweetId(tweet, isRetweet): if isRetweet: return tweet['retweeted_status']['id'] else: return None def getRetweetedTweetTime(tweet, isRetweet): if isRetweet: return tweet['retweeted_status']['created_at'] else: return None def getRetweetedTweetLikesNum(tweet, isRetweet): if isRetweet: return int(tweet['retweeted_status']['favorite_count']) else: return 0 def getRetweetedTweetRTNum(tweet, isRetweet): if isRetweet: return int(tweet['retweeted_status']['retweet_count']) else: return 0 def getRetweetedTweetSource(tweet, isRetweet): if isRetweet: rtstr = tweet['retweeted_status']['source'] return processSource(rtstr) else: return None def getRetweetedTweetAuthorFollowerCount(tweet, isRetweet): if isRetweet: rts = tweet['retweeted_status'] return rts['user']['followers_count'] else: return 0 def getLang(tweet): if 'lang' in tweet: return tweet['lang'] return None with open(infilename, 'r') as f: for line in f: tweet = json.loads(unicode(line.encode('utf-8'), 'utf-8')) if "source" in tweet.keys(): out.write(str(tweet['id']) + sep) out.write(str(tweet['created_at']) + sep) out.write(str(processSource(tweet['source'])) + sep) out.write(str(getLang(tweet)) + sep) isRetweet = isNiceRetweet(tweet) out.write(str(isRetweet) + sep) out.write(str(getRetweetedTweetId(tweet, isRetweet)) + sep) out.write(str(getRetweetedTweetTime(tweet, isRetweet)) + sep) out.write(str(getRetweetedTweetLikesNum(tweet, isRetweet)) + sep) out.write(str(getRetweetedTweetRTNum(tweet, isRetweet)) + sep) out.write(str(getRetweetedTweetSource(tweet, isRetweet)) + sep) out.write(str(getRetweetedTweetAuthorFollowerCount(tweet, isRetweet)) + sep) out.write(repr(str(tweet['text'].encode('utf-8')))) out.write("\n")
ador/trial
scripts/twitterJsonToCsv.py
twitterJsonToCsv.py
py
4,212
python
en
code
1
github-code
36
35872181243
__author__ = 'Dennis Qiu' from PIL import Image def de_steg(encrypted_file): f, e = encrypted_file.split('.') steg = Image.open(encrypted_file) out = Image.new('RGB', (steg.width,steg.height)) for x in range(steg.width): for y in range(steg.height): r, g, b = steg.getpixel((x, y)) rh, gh, bh = (r&0x0F)<<4, (g&0x0F)<<4, (b&0x0F)<<4 out.putpixel((x, y), (rh, gh, bh)) out.save(f+"hiddenImage.png") steg.show() out.show() def im_histogram(im='lowContrastBW.png'): default = Image.open(im) h = [] for i in range(256): h.append(0) for x in range (default.width): for y in range (default.height): p = default.getpixel((x, y)) h[p] += 1 default.show() print('List h:\n{}'.format(h)) default_copy2 = default.copy() size = default.width * default.height Lut = im_lut(h, size) for x in range (default.width): for y in range (default.height): p = default.getpixel((x, y)) default_copy2.putpixel((x, y), Lut[p]) default_copy2.show() def im_lut(list_h, size_n): lut = [] sum_h = 0 for i in range(256): sum_h += list_h[i] lut.append(int((255 / size_n) * sum_h)) print('List lut:\n{}'.format(lut)) return lut if __name__ == '__main__': encrypted = 'encrypted4bits.png encrypted4bits1.png encrypted4bits2.png encrypted4bits3.png'.split() for e in encrypted: de_steg(e) im_histogram()
denqiu/Python-ImageProcessing
image_steg.py
image_steg.py
py
1,570
python
en
code
0
github-code
36
73424753064
# -*- coding: utf-8 -*- from __future__ import print_function import os import re import json from importlib import import_module from inspect import stack from traceback import print_exc from urllib.parse import unquote from utils import * from config import * @retry(Exception, cdata='method={}'.format(stack()[0][3])) def provider_metadata(metafile='metadata.json'): fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) try: metadata = json.loads( open( '{}/{}'.format( VPN_PROFILES, metafile ) ).read() ) except Exception as e: print(repr(e)) if DEBUG: print_exc() metadata = dict() return metadata @retry(Exception, cdata='method={}'.format(stack()[0][3])) def load_provider_groups(): try: groups = provider_metadata()['provider_groups'] except Exception as e: print(repr(e)) if DEBUG: print_exc() groups = ['default'] return groups @retry(Exception, cdata='method={}'.format(stack()[0][3])) def load_affiliate_links(): try: links = provider_metadata()['affiliate_links'] except Exception as e: print(repr(e)) if DEBUG: print_exc() links = [] return links @retry(Exception, cdata='method={}'.format(stack()[0][3])) def affiliate_link(provider=None): fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) links = load_affiliate_links() try: link = [ el['link'] for el in links if el['provider'].lower() == provider.lower() ][0] except Exception as e: print(repr(e)) if DEBUG: print_exc() link = 'https://flashrouters.com' return link @retry(Exception, cdata='method={}'.format(stack()[0][3])) def provider_groups(): fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) try: groups = [ pg['name'] for pg in load_provider_groups() ] except Exception as e: print(repr(e)) if DEBUG: print_exc() groups.sort() return groups @retry(Exception, cdata='method={}'.format(stack()[0][3])) def providers_by_group(group='default'): group = unquote(group) fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) default_providers = [ d for d in next(os.walk(VPN_PROFILES))[1] if d not in ['.git'] ] try: providers = [ pg['value'] for pg in load_provider_groups() if group == pg['name'] ][0] if '*' in providers: providers = default_providers except Exception as e: print(repr(e)) if DEBUG: print_exc() providers = default_providers pass providers.sort() return providers @retry(Exception, cdata='method={}'.format(stack()[0][3])) def location_groups_by_provider(provider='VPNArea', metafile='METADATA.txt'): provider = unquote(provider) fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) try: mod = import_module(provider.lower()) p = mod.Provider() if '__disabled__' in dir(p): assert p.__disabled__ == False assert mod and 'Provider' in dir(mod) and 'get_location_groups' in dir(mod.Provider) location_groups = p.get_location_groups() assert location_groups return location_groups except: try: metadata = open( '{}/{}/{}'.format( VPN_PROFILES, provider, metafile ) ).read() except Exception as e: print(repr(e)) if DEBUG: print_exc() try: location_groups = [ ' '.join(x.split('.')[0].split()[1:]) for x in metadata.split('\n') if x.startswith('LOCATIONS') ] assert ''.join(location_groups) except Exception as e: print(repr(e)) if DEBUG: print_exc() location_groups = ['default'] location_groups.sort() return location_groups @retry(Exception, cdata='method={}'.format(stack()[0][3])) def locations_by_provider( provider='VPNArea', group='default', sort=None, lat=None, lon=None ): provider = unquote(provider) group = unquote(group) fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) try: mod = import_module(provider.lower()) p = mod.Provider() if '__disabled__' in dir(p): assert p.__disabled__ == False assert mod and 'Provider' in dir(mod) and 'get_locations' in dir(mod.Provider) locations = p.get_locations(group=group, sort=sort, lat=lat, lon=lon) assert locations if DEBUG: print("'locations='{}'".format(locations)) return locations except Exception as e: if DEBUG: print_exc() if group == 'default': locfile = 'LOCATIONS.txt' else: locfile = 'LOCATIONS {}.txt'.format(group) try: locdata = open( '{}/{}/{}'.format( VPN_PROFILES, provider, locfile ) ).read() locations = [ dict( zip( [ 'name', 'ipaddr', 'proto', 'port', 'extra' ], l.strip().split(',') ) ) for l in locdata.split('\n') if l ] for loc in locations: loc['value'] = loc['name'] except: locations = [ dict(zip(['name', 'value'], [f, f])) for f in next( os.walk( '{}/{}'.format( VPN_PROFILES, provider ) ) )[2] if f.split('.')[-1] == 'ovpn'] locations = sorted(locations, key=lambda k: k['name']) return locations @retry(Exception, cdata='method={}'.format(stack()[0][3])) def client_cert_required( provider='VPNArea', metafile='METADATA.txt', tmplfile='TEMPLATE.txt' ): provider = unquote(provider) fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) regex = re.compile('USERCERT|USERKEY') required = False try: metadata = open( '{}/{}/{}'.format( VPN_PROFILES, provider, metafile ) ).read() tmplfile = [ x for x in metadata.split('\n') if x.startswith('TEMPLATE') ][0] tmpl = open( '{}/{}/{}'.format( VPN_PROFILES, provider, tmplfile ) ).read() cert = get_user_cert_contents( metadata=metadata, provider=provider ) key = get_user_key_contents( metadata=metadata, provider=provider ) assert (not cert or not key) and bool(regex.search(tmpl)) required = True except Exception as e: print(repr(e)) if DEBUG: print_exc() return required @retry(Exception, cdata='method={}'.format(stack()[0][3])) def get_user_cert_contents(metadata=None, provider=None): try: provider = unquote(provider) certfile = [ x for x in metadata.split('\n') if x.startswith('user') and x.endswith('crt') ][0] cert = open( '{}/{}/{}'.format( VPN_PROFILES, provider, certfile ) ).read() except: cert = None return cert @retry(Exception, cdata='method={}'.format(stack()[0][3])) def get_user_key_contents(metadata=None, provider=None): key = None try: provider = unquote(provider) keyfile = [ x for x in metadata.split('\n') if x.startswith('user') and x.endswith('key') ][0] key = open( '{}/{}/{}'.format( VPN_PROFILES, provider, keyfile ) ).read() except: key = None return key @retry(Exception, cdata='method={}'.format(stack()[0][3])) def generate_ovpn_profile( provider='VPNArea', metafile='METADATA.txt', tmplfile='TEMPLATE.txt', group='default', name='USA - Los Angeles (UDP)' ): provider = unquote(provider) group = unquote(group) name = unquote(name) if DEBUG: print("provider='{}' group='{}' name='{}'".format( provider, group, name )) fetch_git_repo( dir=VPN_PROVIDERS_GIT_DIR, url=VPN_PROVIDERS_GIT_URL, tag=VPN_PROVIDERS_GIT_TAG ) try: metadata = open( '{}/{}/{}'.format( VPN_PROFILES, provider, metafile ) ).read() except: metadata = None try: tmplfile = [ x for x in metadata.split('\n') if x.startswith('TEMPLATE') ][0] tmpl = open( '{}/{}/{}'.format( VPN_PROFILES, provider, tmplfile ) ).read() except: tmpl = None try: cafile = [ x for x in metadata.split('\n') if x.startswith('ca') and x.endswith('crt') ][0] ca = open( '{}/{}/{}'.format( VPN_PROFILES, provider, cafile ) ).read() except: ca = None try: cert = get_user_cert_contents( metadata=metadata, provider=provider ) except: cert = None try: key = get_user_key_contents( metadata=metadata, provider=provider ) except: key = None try: tafile = [ x for x in metadata.split('\n') if x.startswith('ta') and x.endswith('key') ][0] ta = open( '{}/{}/{}'.format( VPN_PROFILES, provider, tafile ) ).read() except: ta = None try: crlfile = [ x for x in metadata.split('\n') if x.startswith('crl') and x.endswith('pem') ][0] crl = open( '{}/{}/{}'.format( VPN_PROFILES, provider, crlfile ) ).read() except: crl = None try: location = [ loc for loc in locations_by_provider( group=group, provider=provider ) if loc['name'] == name ][0] ipaddr = location['ipaddr'].strip() proto = location['proto'].strip() port = location['port'].strip() try: extras = [ dict( zip( ['key', 'value'], l ) ) for l in [ el.split('=') for el in location['extra'].split() ] ] if DEBUG: print('extras: {}'.format(extras)) except: extras = None except: if DEBUG: print_exc() # provider with .ovpn profiles (e.g. NordVPN and LimeVPN) if 'ipaddr' not in location.keys(): try: tmpl = open( '{}/{}/{}'.format( VPN_PROFILES, provider, location['name'] ) ).read() except: if DEBUG: print_exc() try: tmpl = tmpl.replace('#PROTO', proto) tmpl = tmpl.replace('#SERVPROT', proto) tmpl = tmpl.replace('#SERVER', ipaddr) tmpl = tmpl.replace('#PORT', port) except: if DEBUG: print_exc() # remove directives tmpl = tmpl.splitlines() try: for extra in extras: if extra['key'] == '#REMOVE': for val in [i for i in extra['value']]: tmpl = [ line for line in tmpl if not bool( re.search('^#REMOVE{}'.format(val), line) )] extras.remove(extra) for extra in extras: tmpl = [line.replace(extra['key'], extra['value']) for line in tmpl] except: if DEBUG: print_exc() tmpl = '\n'.join(tmpl) tmpl = tmpl.replace('#PATHuser.crt', '#USERCERT') tmpl = tmpl.replace('#PATHuser.key', '#USERKEY') tmpl = tmpl.replace('#PASS', '') if cert: tmpl = tmpl.replace( 'cert #USERCERT', '<cert>\n{}\n</cert>\n'.format( cert ) ) if key: tmpl = tmpl.replace( 'key #USERKEY', '<key>\n{}\n</key>\n'.format( key ) ) tmpl = tmpl.splitlines() # remove remaining tags regex = re.compile('^(#REMOVE\d{1})(.*)$') temp = list() for line in tmpl: if regex.search(line): temp.append(regex.search(line).groups()[1]) else: temp.append(line) tmpl = temp # de-compress tls-auth and key-direction regex = re.compile('^tls-auth #TLSKEY (\d{1})$') temp = list() for line in tmpl: if regex.search(line): temp.append('<tls-auth>\n{}\n</tls-auth>\n'.format(ta)) temp.append( 'key-direction {}\n'.format( regex.search(line).groups()[0] ) ) else: temp.append(line) tmpl = temp # in-line tls-key regex = re.compile('^tls-auth #TLSKEY$') temp = list() for line in tmpl: if regex.search(line): temp.append('<tls-auth>\n{}\n</tls-auth>\n'.format(ta)) else: temp.append(line) tmpl = temp # in-line all other keys temp = list() for line in tmpl: if line.split(' ')[0] in [ 'ca', 'crl-verify', 'tls-auth', 'key', 'cert' ]: fdata = None try: fdata = open( '{}/{}/{}'.format( VPN_PROFILES, provider, line.split(' ')[1].replace('"', '').replace("'", '') ) ).read() except Exception as e: if DEBUG: print_exc() temp.append(line) if fdata: temp.append( '<{}>\n{}\n</{}>\n'.format( line.split(' ')[0], fdata, line.split(' ')[0] ) ) else: temp.append(line) # remove superfluous directives for regex in ['^dev tun[\d]+']: tmpl = [line for line in tmpl if not bool(re.search(regex, line))] tmpl = '\n'.join(temp) # final sweep for providers with only one ca cert if ca: tmpl = tmpl.replace( 'ca #CERT', '<ca>\n{}\n</ca>\n'.format( ca ) ) if crl: tmpl = tmpl.replace( 'crl-verify #CRLVERIFY', '<crl-verify>\n{}\n</crl-verify>\n'.format(crl)) return '{}\n'.format( os.linesep.join( [ s for s in tmpl.splitlines() if s ] ) )
belodetek/unzoner-api
src/vpns.py
vpns.py
py
16,340
python
en
code
3
github-code
36
72738108584
#!/bin/python3 import os import sys import pathlib from amp_database import download_DRAMP def check_samplelist(samplelist, tools, path): if(samplelist==[]): print('<--sample-list> was not given, sample names will be inferred from directory names') for dirpath, subdirs, files in os.walk(path): for dir in subdirs: if (dir not in tools): samplelist.append(dir) return list(set(samplelist)) else: return samplelist def check_pathlist(filepaths, samplelist, fileending, path): if(filepaths==[]): print('<--path-list> was not given, paths to AMP-results-files will be inferred') for sample in samplelist: pathlist = [] for dirpath, subdirs, files in os.walk(path): for file in files: if ((sample in dirpath) and ((list(filter(file.endswith, fileending))!=[]))): pathlist.append(dirpath+'/'+file) filepaths.append(pathlist) return filepaths else: return filepaths def check_faa_path(faa_path, samplename): if(os.path.isdir(faa_path)): path_list = list(pathlib.Path(faa_path).rglob(f"*{samplename}*.faa")) if (len(path_list)>1): sys.exit(f'AMPcombi interrupted: There is more than one .faa file for {samplename} in the folder given with --faa_path') elif(not path_list): sys.exit(f'AMPcombi interrupted: There is no .faa file containing {samplename} in the folder given with --faa_path') return path_list[0] elif(os.path.isfile(faa_path)): return faa_path else: sys.exit(f'AMPcombi interrupted: The input given with --faa_path does not seem to be a valid directory or file. Please check.') def check_ref_database(database): if((database==None) and (not os.path.exists('amp_ref_database'))): print('<--AMP_database> was not given, the current DRAMP general-AMP database will be downloaded and used') database = 'amp_ref_database' os.makedirs(database, exist_ok=True) db = database download_DRAMP(db) return db elif ((not database==None)): if (os.path.exists(database)): db = database print(f'<--AMP_database> = ${db} is found and will be used') return db if (not os.path.exists(database)): sys.exit(f'Reference amp database path {database} does not exist, please check the path.') elif((database==None) and (os.path.exists('amp_ref_database'))): print('<--AMP_database> = DRAMP is already downloaded and will be reused') database = 'amp_ref_database' db = database return db def check_path(path): return os.path.exists(path) #returns True or False def check_directory_tree(path, tools, samplelist): print(f'Checking directory tree {path} for sub-directories \n ') # get first level of sub-directories, check if at least one is named by a tool-name subdirs_1 = [x for x in os.listdir(path) if x in tools] if (not subdirs_1): sys.exit(f'AMPcombi interrupted: First level sub-directories in {path} are not named by tool-names. Please check the directories names and the keys given in "--tooldict". \n ') else: print('First level sub-directories passed check.') # get second level of sub-directories, check if at least one is named by a sample-name subdirs_2 = [] for dir in subdirs_1: subdirs = [x for x in os.listdir(path+dir) if x in samplelist] if (subdirs): subdirs_2.append(subdirs) if (not subdirs_2): sys.exit(f'AMPcombi interrupted: Second level sub-directories in {path} are not named by sample-names. Please check the directories names and the names given as "--sample_list" \n ') else: print('Second level sub-directories passed check') print('Finished directory check') def check_input_complete(path, samplelist, filepaths, tools): # 1. Head folder does not exist and filepaths-list was not given if((not check_path(path)) and (not filepaths)): sys.exit('AMPcombi interrupted: Please provide the correct path to either the folder containing all amp files to be summarized (--amp_results) or the list of paths to the files (--path_list)') # 2. Head folder does not exist, filepaths-list was given but no samplelist elif((not check_path(path)) and (filepaths) and (not samplelist)): sys.exit('AMPcombi interrupted: Please provide a list of sample-names (--sample_list) in addition to --path_list') # 3. Head folder does not exist, filepaths- and samplelist are given: elif((not check_path(path)) and (not filepaths) and (not samplelist)): for file in filepaths: print(f'in check_input_complete the file in filepath is:') # 3.1. check if paths in filepath-list exist if(not check_path(file)): sys.exit(f'AMPcombi interrupted: The path {file} does not exist. Please check the --path_list input.') # 3.2. check if paths contain sample-names from samplelist if(not any(n in file for n in samplelist)): sys.exit(f'AMPcombi interrupted: The path {file} does not contain any of the sample-names given in --sample_list') # 4. Head folder and sample-list are given elif((check_path(path)) and (not samplelist)): check_directory_tree(path, tools, samplelist)
Darcy220606/AMPcombi
ampcombi/check_input.py
check_input.py
py
5,496
python
en
code
4
github-code
36
875238035
class Grade: def __init__(self, topic, mark, student_name): self.topic = topic self.mark = mark self.student_name = student_name def print_info(self): print("Topic", self.topic) print("Grade", self.mark) print("Student", self.student_name) return self def extra_points(self, percentage): current_grade = self.mark final_grade = current_grade * (percentage / 100) + current_grade self.mark = final_grade return self class Student: bootcamp = "Coding Dojo" list_students = [] # Constructor - constructing objects; written like a function def __init__(self, first_name, last_name, instructor, current_stack, mark): # Setting attributes, the variables that all instances of class will take on; accessible in the entire class self.first_name = first_name self.last_name = last_name self.instructor = instructor self.current_stack = current_stack self.grade = Grade(current_stack, mark, first_name) # Self is reference to the class itself # Creating a method; functions inside class, actions that object can perform def print_student_info(self): print("First name", self.first_name) print("Last name", self. last_name) print("Instructor", self.instructor) print("Current stack", self.current_stack) print("Grade", self.grade) Student.list_students.append(self) def full_name(self): return self.first_name + " " + self.last_name @classmethod def print_all_students(cls): # Refers to the entire class, cls has access to class attributes for student in cls.list_students: print(student.full_name(), student.current_stack) @classmethod def change_stack_name(cls, new_stack): for student in cls.list_students: student.current_stack = new_stack # for i in range(0, len(cls.list_students)): # cls.list_students[i].current_stack = new_stack @staticmethod # Functions defined within class that have no instance to instance/class attributes def add_two_numbers(num1, num2): return num1 + num2 alexander = Student("Alexander", "Miller", "Alfredo", "Python/Flask", 8.2) martha = Student("Martha", "Smith", "Amanda", "Web Fundamentals", 9.2) roger = Student("Roger", "Smith", "Tyler", "C#", 7.6) anna = Student("Anna", "Smith", "Nichole", "Java", 10.0) Student.print_all_students() Student.change_stack_name("MERN") Student.print_all_students() print(Student.add_two_numbers(20,30)) alexander.print_student_info() # Student.bootcamp = "The Coding Dojo" # print(alexander.bootcamp) # alexander = Student("Alexander", "Miller", "Alfredo", "Python/Flask") # Putting Student calls the constructor like a function # alexander.print_student_info() # print(f"{alexander.first_name}'s instructor is {alexander.instructor}") # martha = Student("Martha", "Smith", "Amanda", "Web Fundamentals") # martha.print_student_info() # print(f"{martha.first_name}'s instructor is {martha.instructor}") # name = alexander.full_name() # print(name)
jwaine44/ClassLecture
Student.py
Student.py
py
3,202
python
en
code
0
github-code
36
4810054439
from __future__ import (absolute_import, division, print_function, unicode_literals) import pygame from .shape import Shape from .arrow import Arrow from .line import Line from .label import Label class Pointer(Shape): def __init__(self, element, text, direction="ul.middle", color=(0, 0, 0), dist=20, arrow=True): lp, method = direction.split('.') o = getattr(element, method) p = list(o) if 'u' in lp: p[1] -= dist if 'l' in lp: p[0] -= dist if 'd' in lp: p[1] += dist if 'r' in lp: p[0] += dist self.label = Label(p, text, color=color, font_size=20) super(Pointer, self).__init__(self.label.rect.center, color) if arrow: self.arrow = Arrow(self.label.nearest(o), o, color=color) else: self.arrow = Line(self.label.nearest(o), o, color=color) def draw(self, screen): self.label.draw(screen) self.arrow.draw(screen)
JoaoFelipe/Data-Structures-Drawer
ds_drawer/shapes/pointer.py
pointer.py
py
1,056
python
en
code
0
github-code
36
28552898211
#-*-coding:utf-8-*- import argparse import pyspark from pyspark.sql.types import IntegerType from pyspark.sql.functions import * from generic_utils import execute_compute_stats def extract_tbau_documento(spark): columns = [ col("DOCU_DK").alias("DOAT_DOCU_DK"), col("DOCU_NR_EXTERNO").alias("DOAT_DOCU_NR_EXTERNO"), col("DOCU_NR_MP").alias("DOAT_DOCU_NR_MP"), col("DOCU_DT_CADASTRO").alias("DOAT_DOCU_DT_CADASTRO"), col("DOCU_DT_FATO").alias("DOAT_DOCU_DT_FATO"), col("DOCU_ORGI_ORGA_DK_RESPONSAVEL").alias("DOAT_ORGI_DK_RESPONSAVEL"), col("DOCU_ORGI_ORGA_DK_CARGA").alias("DOAT_ORGI_DK_CARGA"), col("DOCU_ORGA_DK_ORIGEM").alias("DOAT_ORGA_DK_ORIGEM"), col("DOCU_ORGE_ORGA_DK_DELEG_FATO").alias("DOAT_ORGE_DK_DELEG_FATO"), col("DOCU_ORGE_ORGA_DK_DELEG_ORIGEM").alias("DOAT_ORGE_DK_ORIGEM"), col("DOCU_ORGE_ORGA_DK_VARA").alias("DOAT_ORGE_DK_VARA"), col("DOCU_NR_DISTRIBUICAO").alias("DOAT_DOCU_NR_DISTRIBUICAO"), col("DOCU_DT_DISTRIBUICAO").alias("DOAT_DOCU_DT_DISTRIBUICAO"), col("DOCU_IN_DOCUMENTO_ELETRONICO").alias("DOAT_DOCU_IN_DOC_ELETRONICO"), col("DOCU_CLDC_DK").alias("DOAT_CLDC_DK"), col("NISI_DS_NIVEL_SIGILO").alias("DOAT_NISI_DS_NIVEL_SIGILO"), col("MATE_DESCRICAO").alias("DOAT_MATE_ATRIBUICAO_DOC"), col("TPDC_SIGLA").alias("DOAT_TPDC_SIGLA_DOC"), col("TPDC_DESCRICAO").alias("DOAT_TPDC_DS_DOCUMENTO"), col("DOAT_ORGAO_RESPONSAVEL"), col("DOAT_CRAAI_OR"), col("DOAT_COMARCA_OR"), col("DOAT_FORO_OR"), col("DOAT_ORGAO_TP_OR"), col("DOAT_ORGAO_A_E_OR"), col("DOAT_JUIZO_UNICO_OR"), col("DOAT_DT_INICIO_OR"), col("DOAT_DT_FIM_OR"), col("DOAT_DET_CRIACAO_OR"), col("DOAT_ORGAO_CARGA"), col("DOAT_CRAAI_CG"), col("DOAT_COMARCA_CG"), col("DOAT_ORGAO_TP_CG"), col("DOAT_ORGAO_A_E_CG"), col("DOAT_JUIZO_UNICO_CG"), col("DOAT_DT_FIM_CG"), col("DOAT_NM_ORGAO_EXTERNO"), col("TPOE_DESCRICAO").alias("DOAT_TP_ORGAO_EXTERNO"), col("DOAT_NM_DELEF_FATO"), col("DOAT_NM_DELEG_ORIGEM"), col("DOAT_NM_VARA"), col("TPST_DS_TP_SITUACAO").alias("DOAT_TPST_DS_TP_SITUACAO"), col("FSDC_DS_FASE").alias("DOAT_FSDC_DS_FASE"), col("cod_mgp").alias("DOAT_CD_CLASSE"), col("descricao").alias("DOAT_CLASSE"), col("hierarquia").alias("DOAT_CLASSE_HIERARQUIA"), col("DOAA_DT_ALTERACAO").alias("DOAT_DT_ALTERACAO"), ] documento = spark.table("%s.mcpr_documento" % options["schema_exadata"]).\ filter("DOCU_DT_CANCELAMENTO IS NULL") sigilo = spark.table("%s.mcpr_nivel_sigilo" % options["schema_exadata"]) materia = spark.table("%s.mprj_materia_mgp" % options["schema_exadata"]) tipo_doc = spark.table("%s.mcpr_tp_documento" % options["schema_exadata"]) alteracao = spark.table("%s.mcpr_documento_alteracao" % options["schema_exadata"]) sit_doc = spark.table("%s.mcpr_tp_situacao_documento" % options["schema_exadata"]) fase_doc = spark.table("%s.mcpr_fases_documento" % options["schema_exadata"]) orgao_origem = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([ col("ORGE_ORGA_DK").alias("ORG_EXT_ORIGEM_DK"), col("ORGE_TPOE_DK").alias("ORG_EXT_TPOE_DK"), col("ORGE_NM_ORGAO").alias("DOAT_NM_ORGAO_EXTERNO"), ]) orgao_dp_fato = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([ col("ORGE_ORGA_DK").alias("ORG_EXT_DP_FATO_DK"), col("ORGE_NM_ORGAO").alias("DOAT_NM_DELEF_FATO"), ]) orgao_dp_origem = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([ col("ORGE_ORGA_DK").alias("ORG_EXT_DP_ORIGEM_DK"), col("ORGE_NM_ORGAO").alias("DOAT_NM_DELEG_ORIGEM"), ]) orgao_vara = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([ col("ORGE_ORGA_DK").alias("ORG_EXT_VARA_DK"), col("ORGE_NM_ORGAO").alias("DOAT_NM_VARA"), ]) tp_orgao_ext = spark.table("%s.mprj_tp_orgao_ext" % options["schema_exadata"]) classe_doc = spark.table("%s.mmps_classe_docto" % options["schema_exadata_aux"]) local_resp = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"]).select([ col("ORLW_DK").alias("LOC_RESP_DK"), col("ORLW_ORGI_TPOR_DK").alias("LOC_RESP_TPOR_DK"), col("ORLW_ORGI_NM_ORGAO").alias("DOAT_ORGAO_RESPONSAVEL"), col("ORLW_REGI_NM_REGIAO").alias("DOAT_CRAAI_OR"), col("ORLW_CMRC_NM_COMARCA").alias("DOAT_COMARCA_OR"), col("ORLW_COFO_NM_FORO").alias("DOAT_FORO_OR"), col("ORLW_ORGI_IN_JUIZO_UNICO").alias("DOAT_JUIZO_UNICO_OR"), col("ORLW_ORGI_DT_INICIO").alias("DOAT_DT_INICIO_OR"), col("ORLW_ORGI_DT_FIM").alias("DOAT_DT_FIM_OR"), col("ORLW_ORGI_DET_CRIACAO").alias("DOAT_DET_CRIACAO_OR"), ]) local_carga = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"]).select([ col("ORLW_DK").alias("LOC_CARGA_DK"), col("ORLW_ORGI_TPOR_DK").alias("LOC_CARGA_TPOR_DK"), col("ORLW_ORGI_NM_ORGAO").alias("DOAT_ORGAO_CARGA"), col("ORLW_REGI_NM_REGIAO").alias("DOAT_CRAAI_CG"), col("ORLW_CMRC_NM_COMARCA").alias("DOAT_COMARCA_CG"), col("ORLW_ORGI_IN_JUIZO_UNICO").alias("DOAT_JUIZO_UNICO_CG"), col("ORLW_ORGI_DT_FIM").alias("DOAT_DT_FIM_CG"), ]) tp_local_resp = spark.table("%s.orgi_tp_orgao" % options["schema_exadata"]).select([ col("TPOR_DK").alias("TP_LOC_RESP_DK"), col("TPOR_DS_TP_ORGAO").alias("DOAT_ORGAO_TP_OR"), col("TPOR_CLASSIFICACAO").alias("DOAT_ORGAO_A_E_OR"), ]) tp_local_carga = spark.table("%s.orgi_tp_orgao" % options["schema_exadata"]).select([ col("TPOR_DK").alias("TP_LOC_CARGA_DK"), col("TPOR_DS_TP_ORGAO").alias("DOAT_ORGAO_TP_CG"), col("TPOR_CLASSIFICACAO").alias("DOAT_ORGAO_A_E_CG"), ]) doc_sigilo = documento.join(sigilo, documento.DOCU_NISI_DK == sigilo.NISI_DK, "left") doc_materia = doc_sigilo.join(materia, doc_sigilo.DOCU_MATE_DK == materia.MATE_DK, "left") doc_tipo = doc_materia.join(tipo_doc, doc_materia.DOCU_TPDC_DK == tipo_doc.TPDC_DK, "inner") # doc_tipo = doc_sigilo.join(tipo_doc, doc_sigilo.DOCU_TPDC_DK == tipo_doc.TPDC_DK, "inner") doc_alteracao = doc_tipo.join(alteracao, alteracao.DOAA_DOCU_DK == doc_tipo.DOCU_DK, "inner") doc_sit = doc_alteracao.join(sit_doc, doc_alteracao.DOCU_TPST_DK == sit_doc.TPST_DK, "left") # doc_sit = doc_tipo.join(sit_doc, doc_tipo.DOCU_TPST_DK == sit_doc.TPST_DK, "left") doc_fase = doc_sit.join(fase_doc, doc_sit.DOCU_FSDC_DK == fase_doc.FSDC_DK, "left") doc_origem = doc_fase.join(orgao_origem, doc_fase.DOCU_ORGA_DK_ORIGEM == orgao_origem.ORG_EXT_ORIGEM_DK, "left") doc_tp_ext = doc_origem.join(tp_orgao_ext, doc_origem.ORG_EXT_TPOE_DK == tp_orgao_ext.TPOE_DK , "left") doc_classe = doc_tp_ext.join(classe_doc, doc_tp_ext.DOCU_CLDC_DK == classe_doc.ID , "left") # doc_classe = doc_origem.join(classe_doc, doc_origem.DOCU_CLDC_DK == classe_doc.cldc_dk , "left") doc_loc_resp = doc_classe.join(local_resp, doc_classe.DOCU_ORGI_ORGA_DK_RESPONSAVEL == local_resp.LOC_RESP_DK , "left") doc_tp_loc_resp = doc_loc_resp.join(tp_local_resp, doc_loc_resp.LOC_RESP_TPOR_DK == tp_local_resp.TP_LOC_RESP_DK , "left") doc_loc_carga = doc_tp_loc_resp.join(local_carga, doc_tp_loc_resp.DOCU_ORGI_ORGA_DK_CARGA == local_carga.LOC_CARGA_DK , "left") doc_tp_carga_resp = doc_loc_carga.join(tp_local_carga, doc_loc_carga.LOC_CARGA_TPOR_DK == tp_local_carga.TP_LOC_CARGA_DK , "left") doc_dp_fato = doc_tp_carga_resp.join(orgao_dp_fato, doc_tp_carga_resp.DOCU_ORGE_ORGA_DK_DELEG_FATO == orgao_dp_fato.ORG_EXT_DP_FATO_DK, "left") doc_dp_origem = doc_dp_fato.join(orgao_dp_origem, doc_dp_fato.DOCU_ORGE_ORGA_DK_DELEG_ORIGEM == orgao_dp_origem.ORG_EXT_DP_ORIGEM_DK, "left") doc_dp_vara = doc_dp_origem.join(orgao_vara, doc_dp_origem.DOCU_ORGE_ORGA_DK_VARA == orgao_vara.ORG_EXT_VARA_DK, "left") return doc_dp_vara.select(columns) def extract_tbau_andamento(spark): columns = [ col("VIST_DOCU_DK").alias("DOAN_DOCU_DK"), col("VIST_DK").alias("DOAN_VIST_DK"), col("VIST_DT_ABERTURA_VISTA").alias("DOAN_VIST_DT_ABERTURA_VISTA"), col("VIST_ORGI_ORGA_DK").alias("DOAN_VIST_ORGI_DK"), col("ORLW_ORGI_NM_ORGAO").alias("DOAN_ORGAO_VISTA"), col("ORLW_REGI_NM_REGIAO").alias("DOAN_CRAAI_OV"), col("ORLW_CMRC_NM_COMARCA").alias("DOAN_COMARCA_OV"), col("ORLW_COFO_NM_FORO").alias("DOAN_FORO_OV"), col("TPOR_DS_TP_ORGAO").alias("DOAN_ORGAO_TP_OV"), col("TPOR_CLASSIFICACAO").alias("DOAN_ORGAO_A_E_OV"), col("ORLW_ORGI_IN_JUIZO_UNICO").alias("DOAN_JUIZO_UNICO_OV"), col("ORLW_ORGI_DT_INICIO").alias("DOAN_DT_INICIO_OV"), col("ORLW_ORGI_DT_FIM").alias("DOAN_DT_FIM_OV"), col("ORLW_ORGI_DET_CRIACAO").alias("DOAN_DET_CRIACAO_OV"), col("PESS_NM_PESSOA").alias("DOAN_PESS_NM_RESPONSAVEL_ANDAM"), col("PCAO_DK").alias("DOAN_PCAO_DK"), col("PCAO_DT_ANDAMENTO").alias("DOAN_PCAO_DT_ANDAMENTO"), col("STAO_DK").alias("DOAN_STAO_DK_SUB_ANDAMENTO"), col("STAO_TPPR_DK").alias("DOAN_TPPR_DK_ANDAMENTO"), col("TPPR_TPPR_DK").alias("DOAN_TPPR_TPPR_DK_PAI"), col("STAO_IN_RELATADO").alias("DOAN_STAO_IN_RELATADO"), col("TPPR_CD_TP_ANDAMENTO").alias("DOAN_TPPR_CD_TP_ANDAMENTO"), col("TPPR_DESCRICAO").alias("DOAN_TPPR_DS_ANDAMENTO"), col("HIERARQUIA").alias("DOAN_ANDAMENTO_HIERARQUIA"), col("TEMPO_ANDAMENTO").alias("DOAN_TEMPO") ] vista = spark.table("%s.mcpr_vista" % options["schema_exadata"]) pessoa = spark.table("%s.mcpr_pessoa" % options["schema_exadata"]) vista_resp = vista.join(pessoa, vista.VIST_PESF_PESS_DK_RESP_ANDAM == pessoa.PESS_DK, "left") andamento = spark.table("%s.mcpr_andamento" % options["schema_exadata"]) vista_andam = vista_resp.join( andamento, [ vista_resp.VIST_DK == andamento.PCAO_VIST_DK, andamento.PCAO_TPSA_DK == 2 ], "left" ).withColumn( 'TEMPO_ANDAMENTO', lit(datediff('PCAO_DT_ANDAMENTO', 'VIST_DT_ABERTURA_VISTA')).cast(IntegerType()) ) sub_andamento = spark.table("%s.mcpr_sub_andamento" % options["schema_exadata"]) vista_suba = vista_andam.join(sub_andamento, vista_andam.PCAO_DK == sub_andamento.STAO_PCAO_DK, "left") tipo_andamento = spark.table("%s.mcpr_tp_andamento" % options["schema_exadata"]) vista_tpand = vista_suba.join(tipo_andamento, vista_suba.STAO_TPPR_DK == tipo_andamento.TPPR_DK, "left") hier_andamento = spark.table("%s.mmps_tp_andamento" % options["schema_exadata_aux"]) vista_hrand = vista_tpand.join(hier_andamento, vista_tpand.TPPR_DK == hier_andamento.ID, "left") orgao_local = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"]) vista_orgao = vista_hrand.join(orgao_local, vista_hrand.VIST_ORGI_ORGA_DK == orgao_local.ORLW_DK, "left") tp_orgao = spark.table("%s.orgi_tp_orgao" % options["schema_exadata"]) vista_tp_orgao = vista_orgao.join(tp_orgao, vista_orgao.ORLW_ORGI_TPOR_DK == tp_orgao.TPOR_DK, "left") return vista_tp_orgao.select(columns) def extract_tbau_assunto(spark): columns = [ col("ASDO_DOCU_DK").alias("DASN_DOCU_DK"), col("ASDO_DK").alias("DASN_DK"), col("ASSU_TX_DISPOSITIVO_LEGAL").alias("DASN_TP_LEGAL"), col("ASSU_NM_ASSUNTO").alias("DASN_NM_ASSUNTO"), col("ASSU_CD_CNJ").alias("DASN_CD_CNJ"), col("ASSU_CD_ASSUNTO").alias("DASN_CD_ASSUNTO"), col("ASSU_DK").alias("DASN_ASSU_DK"), col("ASSU_ASSU_DK").alias("DASN_ASSU_ASSU_DK_PAI"), ] assunto_documento = spark.table("%s.mcpr_assunto_documento" % options["schema_exadata"]) assunto = spark.table("%s.mcpr_assunto" % options["schema_exadata"]) doc_assunto_join = assunto_documento.join(assunto, assunto_documento.ASDO_ASSU_DK == assunto.ASSU_DK, "inner") return doc_assunto_join.select(columns).distinct() def extract_tbau_movimentacao(spark): columns = [ col("ITEM_DOCU_DK").alias("DOMO_DOCU_DK"), col("ITEM_DK").alias("DOMO_ITEM_DK"), col("MOVI_DK").alias("DOMO_MOVIDK"), col("MOVI_ORGA_DK_ORIGEM").alias("DOMO_ORGA_ORIGEM_GUIA"), col("ORIG_NM_PESSOA").alias("DOMO_ORGI_ORIGEM_GUIA"), col("ORIG_IN_TP_PESSOA").alias("DOMO_TP_ORGI_ORIGEM"), col("MOVI_ORGA_DK_DESTINO").alias("DOMO_ORGA_DESTINO_GUIA"), col("DEST_NM_PESSOA").alias("DOMO_ORGI_DESTINO_GUIA"), col("DEST_IN_TP_PESSOA").alias("DOMO_TP_ORGI_DESTINO"), col("MOVI_DT_ENVIO_GUIA").alias("DOMO_MOVI_DT_ENVIO_GUIA"), col("MOVI_DT_RECEBIMENTO_GUIA").alias("DOMO_MOVI_DT_RECEBIMENTO_GUIA"), col("PCED_DS_PROCEDENCIA").alias("DOMO_DS_PROCEDENCIA_GUIA"), ] movimentacao = spark.table("%s.mcpr_movimentacao" % options["schema_exadata"]) item = spark.table("%s.mcpr_item_movimentacao" % options["schema_exadata"]) movi_item = movimentacao.join(item, item.ITEM_MOVI_DK == movimentacao.MOVI_DK, "inner") procedencia = spark.table("%s.mcpr_procedencia_documento" % options["schema_exadata"]) movi_proc = movi_item.join(procedencia, movi_item.MOVI_PCED_DK_PROCEDENCIA == procedencia.PCED_DK, "inner") destino = spark.table("%s.mcpr_pessoa" % options["schema_exadata"]).select([ col("PESS_DK").alias("DEST_DK"), col("PESS_NM_PESSOA").alias("DEST_NM_PESSOA"), col("PESS_IN_TP_PESSOA").alias("DEST_IN_TP_PESSOA"), ]) movi_destino = movi_proc.join(destino, movi_proc.MOVI_ORGA_DK_DESTINO == destino.DEST_DK, "inner") origem = spark.table("%s.mcpr_pessoa" % options["schema_exadata"]).select([ col("PESS_DK").alias("ORIG_DK"), col("PESS_NM_PESSOA").alias("ORIG_NM_PESSOA"), col("PESS_IN_TP_PESSOA").alias("ORIG_IN_TP_PESSOA"), ]) movi_origem = movi_destino.join(origem, movi_destino.MOVI_ORGA_DK_ORIGEM == origem.ORIG_DK, "inner") return movi_origem.filter("MOVI_DT_CANCELAMENTO IS NULL").select(columns).distinct() def extract_tbau_personagem(spark): sf1_columns = [ col("PESF_PESS_DK").alias("PESFDK"), col("PESF_SEXO").alias("SEX"), col("ESCO_DESCRICAO").alias("ESCOL"), col("ECIV_DESCRICAO").alias("ECIVIL"), col("CORP_DESCRICAO").alias("CPELE"), col("PESF_DT_NASC").alias("DT_NASC"), ] sf2_columns = [ col("ENPE_PESS_DK").alias("ENPEDK"), col("ENDC_CEP").alias("ECEP"), col("ECIDA"), col("EUFED"), col("EBAIR"), ] columns = [ col("PERS_PESS_DK").alias("DPSG_PERS_PESS_DK"), col("PERS_DOCU_DK").alias("DPSG_DOCU_DK"), col("PESS_NM_PESSOA").alias("DPSG_PESS_NM_PESSOA"), col("TPPE_DESCRICAO").alias("DPSG_TPPE_DESCRICAO"), col("TPAT_DS_AUTORIDADE").alias("DPSG_TPAT_DS_AUTORIDADE"), col("REND_DESCRICAO").alias("DPSG_REND_DESCRICAO"), col("PESS_IN_TP_PESSOA").alias("DPSG_PESS_IN_TP_PESSOA"), col("SEX").alias("DPSG_SEXO"), col("ESCOL").alias("DPSG_ESCOLARIDADE"), col("ECIVIL").alias("DPSG_ESTADO_CIVIL"), col("CPELE").alias("DPSG_COR_PELE"), col("DT_NASC").alias("DPSG_DT_NASCIMENTO"), col("ECEP").alias("DPSG_CEP_PERSONAGEM"), col("EBAIR").alias("DPSG_BAIRRO_PERSONAGEM"), col("ECIDA").alias("DPSG_CIDADE_PERSONAGEM"), col("EUFED").alias("DPSG_UF_PERSONAGEM"), ] pessoa_fisica = spark.table("%s.mcpr_pessoa_fisica" % options["schema_exadata"]) escolaridade = spark.table("%s.mcpr_escolaridade" % options["schema_exadata"]) pessoa_escolaridade = pessoa_fisica.join(escolaridade, pessoa_fisica.PESF_ESCO_DK == escolaridade.ESCO_DK, "left") estado_civil = spark.table("%s.mcpr_estado_civil" % options["schema_exadata"]) pessoa_estado_civil = pessoa_escolaridade.join(estado_civil, pessoa_escolaridade.PESF_ECIV_DK == estado_civil.ECIV_DK, "left") cor_pele = spark.table("%s.mcpr_cor_pele" % options["schema_exadata"]) pessoa_cor_pele = pessoa_estado_civil.join(cor_pele, pessoa_estado_civil.PESF_CORP_DK == cor_pele.CORP_DK, "left") sf1 = pessoa_cor_pele.select(sf1_columns).distinct() end_pes = spark.table("%s.mcpr_endereco_pessoa" % options["schema_exadata"]) endereco = spark.table("%s.mcpr_enderecos" % options["schema_exadata"]).select( ["ENDC_DK", "ENDC_BAIR_DK", "ENDC_NM_BAIRRO", "ENDC_CEP", "ENDC_CIDA_DK", "ENDC_NM_CIDADE", "ENDC_NM_ESTADO", "ENDC_UFED_DK"] ) endereco_pessoa = end_pes.join(endereco, end_pes.ENPE_ENDC_DK == endereco.ENDC_DK, "left") cidade = spark.table("%s.mprj_cidade" % options["schema_exadata"]) endereco_cidade = endereco_pessoa.join(cidade, endereco_pessoa.ENDC_CIDA_DK == cidade.CIDA_DK, "left") uf = spark.table("%s.mprj_uf" % options["schema_exadata"]) endereco_uf = endereco_cidade.join(uf, endereco_cidade.CIDA_UFED_DK == uf.UFED_DK, "left") bairro = spark.table("%s.mprj_bairro" % options["schema_exadata"]) endereco_bairro = endereco_uf.join( bairro, [ endereco_uf.ENDC_CIDA_DK == bairro.BAIR_CIDA_DK, endereco_uf.ENDC_BAIR_DK == bairro.BAIR_DK, ], "left" ).withColumn( 'ECIDA', coalesce( col('CIDA_NM_CIDADE'), col('ENDC_NM_CIDADE') ) ).withColumn( 'EUFED', coalesce( col('UFED_SIGLA'), col('ENDC_NM_ESTADO') ) ).withColumn( 'EBAIR', coalesce( col('BAIR_NM_BAIRRO'), col('ENDC_NM_BAIRRO') ) ) sf2 = endereco_bairro.select(sf2_columns).distinct() personagem = spark.table("%s.mcpr_personagem" % options["schema_exadata"]) tipo_personagem = spark.table("%s.mcpr_tp_personagem" % options["schema_exadata"]) personagem_tipo = personagem.join(tipo_personagem, personagem.PERS_TPPE_DK == tipo_personagem.TPPE_DK, "inner") pessoa = spark.table("%s.mcpr_pessoa" % options["schema_exadata"]) personagem_pessoa = personagem_tipo.join(pessoa, personagem_tipo.PERS_PESS_DK == pessoa.PESS_DK, "inner") tipo_autoridade = spark.table("%s.mcpr_tp_autoridade" % options["schema_exadata"]) personagem_autoridade = personagem_pessoa.join(tipo_autoridade, personagem_pessoa.PERS_TPAT_DK == tipo_autoridade.TPAT_DK, "left") perfil = spark.table("%s.mcpr_perfil" % options["schema_exadata"]) personagem_perfil = personagem_autoridade.join(perfil, personagem_autoridade.PERS_PESF_DK == perfil.PERF_PESF_PESS_DK, "left") renda = spark.table("%s.mcpr_faixa_renda" % options["schema_exadata"]) personagem_renda = personagem_perfil.join(renda, personagem_perfil.PERF_REND_DK == renda.REND_DK, "left") personagem_sf1 = personagem_renda.join( sf1, [ sf1.PESFDK == personagem_renda.PERS_PESS_DK, personagem_renda.PESS_IN_TP_PESSOA.isin(['I', 'J']) == False, ], "left" ) personagem_sf2 = personagem_sf1.join( sf2, [ sf2.ENPEDK == personagem_sf1.PERS_PESS_DK, personagem_sf1.PESS_IN_TP_PESSOA != 'I', ], "left" ) return personagem_sf2.filter("PERS_DT_FIM IS NULL").select(columns).distinct() def extract_tbau_consumo(spark): columns = [ col("cd_bem_servico").alias("tmat_cd_bem_servico"), col("ds_bem_generico").alias("tmat_ds_bem_generico"), col("nm_bem_servico").alias("tmat_nm_bem_servico"), col("ds_completa").alias("tmat_ds_completa"), col("mes_ano_consumo").alias("tmat_mes_ano_consumo"), col("orlw_dk").alias("tmat_orgi_dk"), col("orlw_orgi_nm_orgao").alias("tmat_orgi_nm_orgao"), col("orlw_cofo_nm_foro").alias("tmat_cofo_nm_foro"), col("orlw_cmrc_nm_comarca").alias("tmat_cmrc_nm_comarca"), col("orlw_regi_nm_regiao").alias("tmat_regi_nm_regiao"), col("sum_atendido").alias("tmat_qt_consumida"), col("sg_um").alias("tmat_sg_unidade_medida"), col("ds_um").alias("tmat_ds_unidade_medida"), col("sum_consumido").alias("tmat_vl_consumido"), ] pre_columns = [ col("cd_bem_servico"), col("ds_bem_generico"), col("nm_bem_servico"), col("ds_completa"), col("qt_atendido"), col("sg_um"), col("ds_um"), col("vl_consumido"), col("mes_ano_consumo"), col("orlw_dk"), col("orlw_orgi_nm_orgao"), col("orlw_cofo_nm_foro"), col("orlw_cmrc_nm_comarca"), col("orlw_regi_nm_regiao"), ] requisicao = spark.table("%s.asin_ax_v_requisicao_consulta" % options["schema_exadata_views"]).\ filter("CD_SITUACAO_REQ_ATUAL = '003'").\ filter("QT_ATENDIDO IS NOT NULL").\ withColumn("vl_consumido", col("vl_atendido")/100).\ withColumn("mes_ano_consumo", trunc("dt_situacao_req_atual", "month")) situacao = spark.table("%s.asin_ax_situacao_req" % options["schema_exadata_views"]) ua = spark.table("%s.asin_cr_ua" % options["schema_exadata_views"]).select(col("CD_UA").alias("ua_id")) servico = spark.table("%s.asin_cr_bem_servico" % options["schema_exadata_views"]).select([ col("CD_BEM_SERVICO").alias("servico_id"), col("CD_BEM_GENERICO"), col("nm_bem_servico"), col("ds_completa"), col("cd_um_elementar"), ]) generico = spark.table("%s.asin_cr_bem_generico" % options["schema_exadata_views"]).select([ col("CD_BEM_GENERICO").alias("generico_id"), col("ds_bem_generico"), ]) umed = spark.table("%s.asin_cr_um" % options["schema_exadata_views"]) orgao = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"]) sit_req = requisicao.join(situacao, requisicao.CD_SITUACAO_REQ_ATUAL == situacao.CD_SITUACAO_REQ, "inner") sit_ua = sit_req.join(ua, sit_req.CD_UA == ua.ua_id, "inner") sit_servico = sit_ua.join(servico, sit_ua.CD_BEM_SERVICO == servico.servico_id, "inner") sit_generico = sit_servico.join(generico, sit_servico.CD_BEM_GENERICO == generico.generico_id, "inner") sit_umed = sit_generico.join(umed, sit_generico.cd_um_elementar == umed.CD_UM, "inner") sit_orgao = sit_umed.join(orgao, sit_umed.CD_UA == orgao.ORLW_ORGI_CDORGAO, "inner").select(pre_columns) result = sit_orgao.groupBy( "cd_bem_servico", "ds_bem_generico", "nm_bem_servico", "ds_completa", "sg_um", "ds_um", "mes_ano_consumo", "orlw_dk", "orlw_orgi_nm_orgao", "orlw_cofo_nm_foro", "orlw_cmrc_nm_comarca", "orlw_regi_nm_regiao" ).sum("qt_atendido", "vl_consumido").\ withColumn("sum_atendido", col("sum(qt_atendido)")).\ withColumn("sum_consumido", col("sum(vl_consumido)")) return result.select(columns) def extract_tbau_endereco(spark): columns = [ col("EDOC_DOCU_DK").alias("DODR_DOCU_DK"), concat( col("TPLO_DS_LOGRADOURO"), lit(" "), col("ENDC_LOGRADOURO"), lit(" "), col("ENDC_NUMERO") ).alias("DODR_ENDERECO"), col("DODR_NM_BAIRRO"), col("ENDC_CEP").alias("DODR_CEP"), col("DODR_NM_CIDADE"), col("DODR_UFED"), ] doc_endereco = spark.table("%s.mcpr_endereco_documento" % options["schema_exadata"]) endereco = spark.table("%s.mcpr_enderecos" % options["schema_exadata"]).filter("ENDC_CIDA_DK IS NOT NULL") cidade = spark.table("%s.mprj_cidade" % options["schema_exadata"]) estado = spark.table("%s.mprj_uf" % options["schema_exadata"]) bairro = spark.table("%s.mprj_bairro" % options["schema_exadata"]) tipo_logradouro = spark.table("%s.mprj_tp_logradouro" % options["schema_exadata"]) end_documento = doc_endereco.join(endereco, doc_endereco.EDOC_ENDC_DK == endereco.ENDC_DK, "inner") end_cidade = end_documento.join(cidade, end_documento.ENDC_CIDA_DK == cidade.CIDA_DK, "left") end_estado = end_cidade.join(estado, end_cidade.CIDA_UFED_DK == estado.UFED_DK, "left") end_bairro = end_estado.join(bairro, [ end_estado.ENDC_CIDA_DK == bairro.BAIR_CIDA_DK, end_estado.ENDC_BAIR_DK == bairro.BAIR_DK, ], "left") end_tp_logradouro = end_bairro.join(tipo_logradouro, end_bairro.ENDC_TPLO_DK == tipo_logradouro.TPLO_DK, "left").\ withColumn( 'DODR_NM_BAIRRO', coalesce( col('BAIR_NM_BAIRRO'), col('ENDC_NM_BAIRRO') ) ).\ withColumn( 'DODR_NM_CIDADE', coalesce( col('CIDA_NM_CIDADE'), col('ENDC_NM_CIDADE') ) ).\ withColumn( 'DODR_UFED', coalesce( col('UFED_SIGLA'), col('ENDC_NM_ESTADO') ) ) return end_tp_logradouro.select(columns).distinct() def generate_tbau(spark, generator, schema, table_name): dataframe = generator(spark) full_table_name = "{}.{}".format(schema, table_name) dataframe.coalesce(20).write.format('parquet').saveAsTable(full_table_name, mode='overwrite') execute_compute_stats(full_table_name) print("{} gravada".format(table_name)) def execute_process(options): spark = pyspark.sql.session.SparkSession\ .builder\ .appName("tabelas_tbau")\ .enableHiveSupport()\ .getOrCreate() sc = spark.sparkContext schema_exadata_aux = options['schema_exadata_aux'] generate_tbau(spark, extract_tbau_documento, schema_exadata_aux, "tbau_documento") generate_tbau(spark, extract_tbau_andamento, schema_exadata_aux, "tbau_documento_andamento") generate_tbau(spark, extract_tbau_assunto, schema_exadata_aux, "tbau_documento_assunto") generate_tbau(spark, extract_tbau_movimentacao, schema_exadata_aux, "tbau_documento_movimentacao") generate_tbau(spark, extract_tbau_personagem, schema_exadata_aux, "tbau_documento_personagem") generate_tbau(spark, extract_tbau_consumo, schema_exadata_aux, "tbau_material_consumo") generate_tbau(spark, extract_tbau_endereco, schema_exadata_aux, "tbau_documento_endereco") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create tables tbau") parser.add_argument('-e','--schemaExadata', metavar='schemaExadata', type=str, help='') parser.add_argument('-a','--schemaExadataAux', metavar='schemaExadataAux', type=str, help='') parser.add_argument('-v','--schemaExadataViews', metavar='schemaExadataViews', type=str, help='') parser.add_argument('-i','--impalaHost', metavar='impalaHost', type=str, help='') parser.add_argument('-o','--impalaPort', metavar='impalaPort', type=str, help='') args = parser.parse_args() options = { 'schema_exadata': args.schemaExadata, 'schema_exadata_aux': args.schemaExadataAux, 'schema_exadata_views': args.schemaExadataViews, 'impala_host' : args.impalaHost, 'impala_port' : args.impalaPort } execute_process(options)
rhenanbartels/scripts-bda
extract_tbau/src/extractor.py
extractor.py
py
25,402
python
pt
code
0
github-code
36
41165253893
# -*- coding: utf-8 -*- ''' This file is part of Habitam. Habitam is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Habitam is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Habitam. If not, see <http://www.gnu.org/licenses/>. Created on Apr 21, 2013 @author: Stefan Guna ''' from django import forms from django.db.models.query_utils import Q from habitam.entities.models import AccountLink from habitam.financial.models import Account from habitam.ui.forms.generic import NewDocPaymentForm from django.forms.util import ErrorDict from django.utils.translation import ugettext as _ from django.forms.forms import NON_FIELD_ERRORS MONEY_TYPES = ( ('cash', _('bani lichizi')), ('bank', _(u'bancă')) ) TYPES = ( ('std', _('standard')), ('repairs', _('repairs')), ('rulment', _('rulment')), ('special', _('special')), ) class EditAccountForm(forms.ModelForm): money_type = forms.ChoiceField(label=_('Tip bani'), choices=MONEY_TYPES) type = forms.ChoiceField(label=_('Tip'), choices=TYPES) class Meta: model = Account fields = ('name', 'type', 'money_type') def __init__(self, *args, **kwargs): if 'building' in kwargs.keys(): self._building = kwargs['building'] del kwargs['building'] else: self._building = None del kwargs['user'] super(EditAccountForm, self).__init__(*args, **kwargs) if self.instance.type == 'penalties': del self.fields['type'] if self.instance.online_payments: del self.fields['money_type'] def save(self, commit=True): instance = super(EditAccountForm, self).save(commit=False) if commit: instance.save() if self._building != None: al = AccountLink.objects.create(holder=self._building, account=instance) al.save() return instance def add_form_error(self, error_message): if not self._errors: self._errors = ErrorDict() if not NON_FIELD_ERRORS in self._errors: self._errors[NON_FIELD_ERRORS] = self.error_class() self._errors[NON_FIELD_ERRORS].append(error_message) class NewFundTransfer(NewDocPaymentForm): dest_account = forms.ModelChoiceField(label=_(u'Destinație'), queryset=Account.objects.all()) def __init__(self, *args, **kwargs): building = kwargs['building'] account = kwargs['account'] del kwargs['building'] del kwargs['account'] del kwargs['user'] super(NewFundTransfer, self).__init__(*args, **kwargs) qdirect = Q(accountlink__holder=building) qparent = Q(accountlink__holder__parent=building) qbuilding_accounts = Q(qdirect | qparent) qbilled_direct = Q(collectingfund__billed=building) qbilled_parent = Q(collectingfund__billed__parent=building) qbilled = Q(qbilled_direct | qbilled_parent) qnotarchived = Q(~Q(collectingfund__archived=True) & qbilled) queryset = Account.objects.filter(Q(qbuilding_accounts | qnotarchived)) queryset = queryset.exclude(pk=account.id).exclude(type='penalties') self.fields['dest_account'].queryset = queryset
habitam/habitam-core
habitam/ui/forms/fund.py
fund.py
py
3,821
python
en
code
1
github-code
36
12366447292
import glob import os import shutil import tempfile import unittest from ample import constants from ample.testing import test_funcs from ample.util import ample_util, spicker @unittest.skip("unreliable test cases") @unittest.skipUnless(test_funcs.found_exe("spicker" + ample_util.EXE_EXT), "spicker exec missing") class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls.thisd = os.path.abspath(os.path.dirname(__file__)) cls.ample_share = constants.SHARE_DIR cls.testfiles_dir = os.path.join(cls.ample_share, 'testfiles') cls.tests_dir = tempfile.gettempdir() cls.spicker_exe = ample_util.find_exe('spicker' + ample_util.EXE_EXT) def test_spicker(self): mdir = os.path.join(self.testfiles_dir, "models") models = glob.glob(mdir + os.sep + "*.pdb") work_dir = os.path.join(self.tests_dir, "spicker") if os.path.isdir(work_dir): shutil.rmtree(work_dir) os.mkdir(work_dir) spickerer = spicker.Spickerer(spicker_exe=self.spicker_exe) spickerer.cluster(models, run_dir=work_dir) # This with spicker from ccp4 6.5.010 on osx 10.9.5 names = sorted([os.path.basename(m) for m in spickerer.results[0].models]) ref = [ '5_S_00000005.pdb', '4_S_00000005.pdb', '5_S_00000004.pdb', '4_S_00000002.pdb', '4_S_00000003.pdb', '3_S_00000006.pdb', '3_S_00000004.pdb', '2_S_00000005.pdb', '2_S_00000001.pdb', '3_S_00000003.pdb', '1_S_00000005.pdb', '1_S_00000002.pdb', '1_S_00000004.pdb', ] self.assertEqual(names, sorted(ref)) # seem to get different results on osx self.assertEqual(len(names), len(ref)) # Centroid of third cluster self.assertEqual( os.path.basename(spickerer.results[2].centroid), '5_S_00000006.pdb', "WARNING: Spicker might run differently on different operating systems", ) shutil.rmtree(work_dir) if __name__ == "__main__": unittest.main()
rigdenlab/ample
ample/util/tests/test_spicker.py
test_spicker.py
py
2,160
python
en
code
6
github-code
36
1252911352
class SmallestStringStartingFromLeaf(object): def smallestFromLeaf(self, root): self.ans = "~" def dfs(node, A): if node: A.append(chr(node.val + ord('a'))) if not node.left and not node.right: self.ans = min(self.ans, "".join(reversed(A))) dfs(node.left, A) dfs(node.right, A) A.pop() dfs(root, []) return self.ans class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None if __name__ == '__main__': a = SmallestStringStartingFromLeaf() t1 = TreeNode(0) t2 = TreeNode(1) t3 = TreeNode(2) t4 = TreeNode(3) t5 = TreeNode(4) t6 = TreeNode(3) t7 = TreeNode(4) t1.left = t2 t1.right = t3 t2.left = t4 t2.right = t5 t3.left = t6 t3.right = t7 a1 = TreeNode(25) a2 = TreeNode(1) a3 = TreeNode(3) a4 = TreeNode(1) a5 = TreeNode(3) a6 = TreeNode(0) a7 = TreeNode(2) a1.left = a2 a1.right = a3 a2.left = a4 a2.right = a5 a3.left = a6 a3.right = a7 print(a.smallestFromLeaf(t1)) print(a.smallestFromLeaf(a1))
lyk4411/untitled
beginPython/leetcode/SmallestStringStartingFromLeaf.py
SmallestStringStartingFromLeaf.py
py
1,227
python
en
code
0
github-code
36
8342129346
from django.http import request from django.http.response import HttpResponse from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from core.models import Medico, Hora, Cita, Paciente from core.forms import PacienteForm, HoraForm, MedicoForm, DisponibilidadForm, CitaForm from core.decorators import usuarios_permitiado, usuario_identificado from datetime import * # Create your views here. def home_page(request): context = {} return render(request,'pages/home.html', context) def toma_hora_page(request): context = {} if request.method == "POST": b = request.POST['especialidad'] return redirect('doctores_pages', pk=b) else: print("error") return render(request,'pages/tomar_hora.html', context) def doctores(request, pk): context = {} try: doctores = Medico.objects.filter(especialidad=pk) doc_list = [] startdate = date.today() enddate = startdate + timedelta(days=16) for doctor in doctores: horas = Hora.objects.filter(medico=doctor, disponible=True).filter(fecha__range=[startdate, enddate]) grouped = dict() for hora in horas: grouped.setdefault(hora.fecha, []).append(hora) obj = {"doctor": doctor, "horas": grouped} doc_list.append(obj) context['doctores'] = doc_list except: context['doctores'] = "sin doctores" context["horas"] = "sin horas" if request.method == "POST": pk = request.POST["hora"] return redirect('confirmacion_page', pk=pk) else: print("error") return render(request,'pages/docts.html', context) def confirmacion(request, pk): context = {} form = PacienteForm() hora = Hora.objects.get(id=pk) if request.method == 'POST': form = PacienteForm(request.POST) try: rut = request.POST["rut"] paciente = Paciente.objects.get(rut=rut) hora.disponible = False hora.save() Cita.objects.create( paciente = paciente, hora = hora ) return redirect('home_page') except: if form.is_valid(): paciente = form.save() hora.disponible = False hora.save() Cita.objects.create( paciente = paciente, hora = hora ) return redirect('home_page') else: print("error") else: print("error") context["form"] = form context["hora"] = hora return render(request, 'pages/conf.html', context) def cancelar_page(request): context = {} if request.method == 'POST': rut = request.POST['rut'] paciente = Paciente.objects.get(rut=rut) citas = Cita.objects.filter(paciente=paciente, habilitada=True) context["citas"] = citas else: print("error") return render(request, 'pages/cancel.html', context) def confirm_cancelar(request, pk): context = {} cita = Cita.objects.get(id=pk) context["cita"] = cita if request.method == 'POST': cita.habilitada = False cita.save() hora = Hora.objects.get(id=cita.hora.id) hora.disponible = True hora.save() else: print("error") return render(request, 'pages/conf_cancel.html', context) def login_page(request): context = {} if request.method == 'POST': username = request.POST.get("username") password = request.POST.get("password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home_page') else: print("error al indentificar") else: print("error") return render(request, 'pages/login.html', context) def logout_user(request): logout(request) return redirect('login_page') @login_required(login_url="login_page") @usuarios_permitiado(roles_permitidos=['secretaria']) def secretaria_page(request): context = {} return render(request, 'pages/secretaria.html', context) @login_required(login_url="login_page") @usuarios_permitiado(roles_permitidos=['secretaria']) def agregar_hora_page(request): context = {} form = HoraForm() context["form"] = form if request.method == 'POST': form = HoraForm(request.POST) if form.is_valid(): form.save() else: print("error") else: print("error") return render(request, 'pages/secretaria/agregar_hora.html', context) @login_required(login_url="login_page") @usuarios_permitiado(roles_permitidos=['secretaria']) def quitar_hora_page(request): context = {} try: doctores = Medico.objects.all() startdate = date.today() enddate = startdate + timedelta(days=16) doc_list = [] for doctor in doctores: horas = Hora.objects.filter(medico=doctor, disponible=True).filter(fecha__range=[startdate, enddate]) grouped = dict() for hora in horas: grouped.setdefault(hora.fecha, []).append(hora) obj = {"doctor": doctor, "horas": grouped} doc_list.append(obj) context['doctores'] = doc_list except: context['doctores'] = "sin doctores" context["horas"] = "sin horas" if request.method == 'POST': pk = request.POST["hora"] hora = Hora.objects.get(id=pk) hora.disponible = False hora.save() return redirect('secretaria_page') else: print("error") return render(request, 'pages/secretaria/quitar_hora.html', context) @login_required(login_url="login_page") @usuarios_permitiado(roles_permitidos=['secretaria']) def agregar_medico_page(request): context = {} form = MedicoForm() context["form"] = form if request.method == 'POST': form = MedicoForm(request.POST) if form.is_valid(): form.save() else: print("error") else: print("error") return render(request, 'pages/secretaria/agregar_medico.html', context) @login_required(login_url="login_page") @usuarios_permitiado(roles_permitidos=['secretaria']) def agregar_disponibilidad_page(request): context = {} form = DisponibilidadForm() context["form"] = form if request.method == 'POST': form = DisponibilidadForm(request.POST) if form.is_valid(): form.save() else: print("error") else: print("error") return render(request, 'pages/secretaria/agregar_disponibilidad.html', context) @login_required(login_url="login_page") @usuarios_permitiado(roles_permitidos=['secretaria']) def modificar_cita_page(request): context = {} citas = Cita.objects.filter(habilitada=True) context["citas"] = citas return render(request, 'pages/secretaria/modificar_hora.html', context) @login_required(login_url="login_page") @usuarios_permitiado(roles_permitidos=['secretaria']) def update_cita_page(request, pk): context = {} cita = Cita.objects.get(id=pk) form = CitaForm(instance=cita) context["form"] = form if request.method == 'POST': form = CitaForm(request.POST) if form.is_valid(): form.save() else: print("error") else: print("error") return render(request, 'pages/secretaria/update_cita.html', context)
felipe-quirozlara/arquit-proyect
arquitGalenos/pages/views.py
views.py
py
7,814
python
en
code
0
github-code
36
3903968215
#!/usr/bin/env python from __future__ import with_statement import logging import logging.handlers LOG_FILE_HDL = '/tmp/logging_example.out' mylogger = logging.getLogger("MyLogger") mylogger.setLevel(logging.DEBUG) ch_handler = logging.StreamHandler() ch_handler.setLevel(logging.DEBUG+1) mylogger.addHandler(ch_handler) handler = logging.handlers.TimedRotatingFileHandler( LOG_FILE_HDL, 'M', 1, backupCount=6) handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter("%(asctime)s--%(levelname)s--%(message)s")) mylogger.addHandler(handler) mylogger.log(logging.DEBUG+1, "begin") for i in range(20): mylogger.debug('count i = %d' % i) #handler.doRollover() mylogger.log(logging.INFO, "rolled") logging.shutdown()
bondgeek/pythonhacks
recipes/logger_example.py
logger_example.py
py
756
python
en
code
3
github-code
36
11612639350
# -*- coding:utf-8 -*- # ========================================== # author: ZiChen # mail: 1538185121@qq.com # time: 2021/05/03 # 歌词下载脚本 # ========================================== # 请求及数据处理库 import re from urllib import request import json import traceback import os # 本地API import QQMusicAPI # 本地QQ音乐API # 输出格式设置 from datetime import datetime version = '0.2.0' # 更新日志 # 2021/06/20 🔧更改程序架构,优化程序执行顺序, # 2021/06/19 🎵增加对QQ音乐单曲歌词下载支持 def urlProcessing(songUrl): ''' 将输入的歌曲链接进行处理得到想要的歌曲链接 songUrl 歌曲链接,如示例(网易云) ''' Log = '[{levelname}] - {funcName} - '.format(levelname='DEBUG', funcName='urlProcessing') Log_ERROR = '[{levelname}] - {funcName} - '.format(levelname='ERROR', funcName='urlProcessing') if type(songUrl) == list: # 如果传入的是列表,即需要下载的歌单歌曲 Type = 'PlayList_download' # 通过分析链接识别歌曲或歌单来源 elif type(songUrl) == str: # 2021/06/20 先判断是歌曲|歌单歌曲获取 Type = 'Song_PlayListCheck' if re.search(r'music.163.com/song', songUrl) != None: # 网易云单曲 Type = Type + '|Netease_Song' elif re.search(r'music.163.com/#/playlist|music.163.com/playlist', songUrl) != None: # 网易云歌单 Type = Type + '|Netease_PlayList_check' elif re.search(r'y.qq.com/n/ryqq/songDetail', songUrl) != None: # 2021/06/19 QQ音乐单曲 Type = Type + '|QQ_Music_Song' if Type.split('|')[0] == 'Song_PlayListCheck': # 2021/06/20 确认为歌曲|歌单歌曲获取 # 确认后获取歌曲所属平台做后续处理 Type = Type.split('|')[-1] if Type == 'QQ_Music_Song': # QQ音乐;调用本地API获取歌词及歌曲信息 print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'识别到QQ音乐歌曲') print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在处理链接...') # 2021/06/19 QQ音乐单曲的mid就在url的最后 songID = songUrl.split('/')[-1] print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'已获取歌曲id:%s' % songID) try: # 获得歌手名-歌曲名,用于歌词写入 print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在获取歌曲信息...') myjson_detail = QQMusicAPI.Details_GET(songID) # 从字典中获得歌曲的名字及作者/翻唱者 songName = myjson_detail['name'] # 由于作者/翻唱者可能有多个故使用列表存储,最后用join拼接即可 songAuthor = myjson_detail['ar'] # 由于作者/翻唱者之间用 / 隔开会导致文件命名时出错故将 / 替换成 , 但这样做也会使下载的歌曲文件 # 无法正确被播放器识别,暂时的解决方法是给出提示让用户自己去改名 if bool(re.search(r'[/]', songAuthor)) == True: print(str(datetime.today()).split(' ')[1].split( '.')[0]+Log_ERROR+'%s 【歌曲名称错误!下载歌词文件后请自行更改歌词文件名!】' % songAuthor) songAuthor = songAuthor.replace('/', ',') songDetail = '%s - %s' % (songAuthor, songName) print(str(datetime.today()).split(' ')[1].split( '.')[0]+Log+'已获取歌曲信息: %s\n' % songDetail) # 获得歌词文本 print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'发送请求中...') print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在处理接受的数据...') # 从字典中获得歌词文本 lyrics = QQMusicAPI.Lyrics_GET(songID)['lyric'] print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'数据处理完毕,已取得歌词文本√\n') print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在将歌词写入文件...') with open('./%s.lrc' % songDetail, 'w', encoding='utf-8') as f: f.write(lyrics) print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'已保存歌词文件√\n') # 随便返回个东西 return True except: traceback.print_exc() print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'错误!正在重试...\n') urlProcessing(songUrl) else: # QQ音乐无法通过get方法获得,得调用本地api获取 if Type == 'Netease_Song': # 网易云 patternID = re.compile(r'[id=]\d+[&]') # 查找数字 print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'识别到网易云音乐歌曲') songID = re.sub(r'[=]|[&]', '', patternID.findall(songUrl)[0]) # 网易云音乐歌词api neteaseApiUrl_lyric = 'https://zichen-cloud-music-api.vercel.app/lyric?id=%s&realIP=116.25.146.177' % songID # 网易云音乐歌曲信息api neteaseApiUrl_detail = 'https://zichen-cloud-music-api.vercel.app/song/detail?ids=%s' % songID try: # 获得歌手名-歌曲名,用于歌词写入 print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在获取歌曲信息...') if Type == 'Netease_Song': # 网易云 req_detail = request.Request(url=neteaseApiUrl_detail) res_detail = request.urlopen(req_detail) # 获取响应的json字符串 str_json_detail = res_detail.read().decode('utf-8') # 把json转换成字典 myjson_detail = json.loads(str_json_detail) # 从字典中获得歌曲的名字及作者/翻唱者 if Type == 'Netease_Song': # 网易云 songName = myjson_detail['songs'][0]['name'] # 由于作者/翻唱者可能有多个故使用列表存储,最后用join拼接即可 songAuthorLst = [] for i in myjson_detail['songs'][0]['ar']: songAuthorLst.append(i['name']) # 由于作者/翻唱者之间用 / 隔开会导致文件命名时出错故将 / 替换成 , 但这样做也会使下载的歌曲文件 # 无法正确被播放器识别,暂时的解决方法是给出提示让用户自己去改名 if bool(re.search(r'[/]', i['name'])) == True: print(str(datetime.today()).split(' ')[1].split( '.')[0]+Log_ERROR+'%s 【歌曲名称错误!下载歌词文件后请自行更改歌词文件名!】' % i['name']) songAuthor = re.sub( r'[/]', ',', ','.join(songAuthorLst)) songDetail = '%s - %s' % (songAuthor, songName) print(str(datetime.today()).split(' ')[1].split( '.')[0]+Log+'已获取歌曲信息: %s\n' % songDetail) # 获得歌词文本 print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'发送请求中...') if Type == 'Netease_Song': # 网易云 req_lyric = request.Request(url=neteaseApiUrl_lyric) res_lyric = request.urlopen(req_lyric) print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'已接收数据√') # 获取响应的json字符串 str_json_lyric = res_lyric.read().decode('utf-8') # 把json转换成字典 myjson_lyric = json.loads(str_json_lyric) print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在处理接受的数据...') # 从字典中获得歌词文本 if Type == 'Netease_Song': # 网易云 lyrics = myjson_lyric['lrc']['lyric'] print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'数据处理完毕,已取得歌词文本√\n') # print(lyrics+'\n') print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在将歌词写入文件...') with open('./%s.lrc' % songDetail, 'w', encoding='utf-8') as f: f.write(lyrics) print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'已保存歌词文件√\n') # 随便返回个东西 return True except: traceback.print_exc() print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'错误!正在重试...\n') urlProcessing(songUrl) elif Type == 'PlayList_check': # 歌单查看并返回歌单详情 try: if Type == 'Netease_Song': # 网易云 print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'识别到网易云音乐歌单') print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在处理链接...') patternID = re.compile(r'[id=]\d+[&]') # 查找数字 playListID = re.sub( r'[=]|[&]', '', patternID.findall(songUrl)[0]) print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'已获取歌单id:%s' % playListID) limit = 1001 # 歌单中歌曲信息获取数量限制 # 网易云音乐歌单详细信息api neteaseApiUrl_playList = 'https://zichen-cloud-music-api.vercel.app/playlist/detail?id=%s' % playListID print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在向:[%s] 获取歌单信息...' % neteaseApiUrl_playList) # 加标头 header = { "User-Agent": "mozilla/4.0 (compatible; MSIE 5.5; Windows NT)", } req_playList = request.Request( url=neteaseApiUrl_playList, headers=header) res_playList = request.urlopen(req_playList) # 获取响应的json字符串 str_json_playList = res_playList.read().decode('utf-8') # 把json转换成字典 myjson_playList = json.loads(str_json_playList) # 逐个获取歌单内的歌曲名及相应作者/翻唱者 songList = [] # 用于计数显示当前过程的数字 start_num = 0 total_num = len( myjson_playList["playlist"]["trackIds"]) # 总歌单歌曲数 # 根据大佬所述,未登录状态下无法获取歌单完整曲目,但trackIds是完整的,故获取trackIds后逐个请求,但此方法效率较低 for songTotal in myjson_playList["playlist"]["trackIds"]: songID = songTotal['id'] # 获得歌曲id # 网易云音乐歌词api neteaseApiUrl_lyric = 'https://zichen-cloud-music-api.vercel.app/lyric?id=%s&realIP=116.25.146.177' % songID # 网易云音乐歌曲信息api neteaseApiUrl_detail = 'https://zichen-cloud-music-api.vercel.app/song/detail?ids=%s' % songID req_detail = request.Request(url=neteaseApiUrl_detail) res_detail = request.urlopen(req_detail) # 获取响应的json字符串 str_json_detail = res_detail.read().decode('utf-8') # 把json转换成字典 myjson_detail = json.loads(str_json_detail) # 从字典中获得歌曲的名字及作者/翻唱者 # Tip:由于获取的歌曲名有\xa0不间断符号故使用join+split消除该符号 songName = "" .join( myjson_detail['songs'][0]['name'].split()) # 由于作者/翻唱者可能有多个故使用列表存储,最后用join拼接即可 songAuthorLst = [] for i in myjson_detail['songs'][0]['ar']: songAuthorLst.append(i['name']) # 由于作者/翻唱者之间用 / 隔开会导致文件命名时出错故将 / 替换成 , 但这样做也会使下载的歌曲文件 # 无法正确被播放器识别,暂时的解决方法是给出提示让用户自己去改名 if bool(re.search(r'[/]', i['name'])) == True: print(str(datetime.today()).split(' ')[1].split( '.')[0]+Log_ERROR+'%s 【歌曲名称错误!下载歌词文件后请自行更改歌词文件名!】' % i['name']) songAuthor = re.sub( r'[/]', ',', ','.join(songAuthorLst)) # 将 作者/翻唱者+歌曲名+歌曲ID 用元组形式存储并最终存储至列表中 # [(歌曲1),(歌曲2),...] songList.append([songAuthor, songName, str(songID)]) # 显示完成情况,用print覆盖打印 start_num += 1 print('\r歌单歌曲读取已完成(%s/%s)' % (start_num, total_num), end='') print('\n'+str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'已获取歌单信息√\n') for i in songList: print('%s - %s - ID:%s' % (i[0], i[1], i[2])) print('\n'+'-'*15) return songList except: # 错误重试 traceback.print_exc() print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'错误!正在重试...\n') urlProcessing(songUrl) elif Type == 'PlayList_download': # 歌单歌曲下载,传入的songID print(str(datetime.today()).split(' ')[ 1].split('.')[0]+Log+'正在启动批量下载模块...') # 用于计数显示当前过程的数字 start_num = 0 total_num = len(songUrl) # 总歌单歌曲数 # 先解包 for songLst in songUrl: songDetail = '%s - %s' % (songLst[0], songLst[1]) songID = songLst[2] # print('songID:%s' % songID) # print('songLst=%s\n' % songLst) start_num += 1 # 开始下载 # 网易云音乐歌词api neteaseApiUrl_lyric = 'https://zichen-cloud-music-api.vercel.app/lyric?id=%s&realIP=116.25.146.177' % songID # print(neteaseApiUrl_lyric) # 出错后会重新循环,跳过已经保存的文件,提升效率,避免重复请求 if os.path.exists('./%s.lrc' % songDetail) == True: pass else: try: # 获得歌词文本 req_lyric = request.Request(url=neteaseApiUrl_lyric) res_lyric = request.urlopen(req_lyric) # 获取响应的json字符串 str_json_lyric = res_lyric.read().decode('utf-8') # 把json转换成字典 myjson_lyric = json.loads(str_json_lyric) # 从字典中获得歌词文本 lyrics = myjson_lyric['lrc']['lyric'] with open('./%s.lrc' % songDetail, 'w', encoding='utf-8') as f: f.write(lyrics) print('\r已下载(%s/%s)' % (start_num, total_num), end='') if start_num == total_num: # 下载完提示 print('\n'+str(datetime.today()).split(' ') [1].split('.')[0]+Log+'歌单歌曲歌词下载完毕√') except: # traceback.print_exc() print(str(datetime.today()).split(' ') [1].split('.')[0]+Log+'{%s}下载错误!\n已跳过出错的歌曲链接\n' % songDetail) # 删除出错的元素 # print('songUrl=%s\n' % songUrl) del songUrl[start_num-1] # print('songUrl=%s\n' % songUrl) # print(type(songUrl)) if start_num == total_num: # 下载完提示 print('\n'+str(datetime.today()).split(' ') [1].split('.')[0]+Log+'歌单歌曲歌词下载完毕√') else: urlProcessing(songUrl)
Zichen3317/demo18-lyricsDownloader
fc_lyricsDownloader.py
fc_lyricsDownloader.py
py
17,698
python
en
code
0
github-code
36
25607520371
class Solution: def minDistance(self, word1: str, word2: str) -> int: r, c = len(word1), len(word2) dp=[[0]*(c+1) for i in range(r+1)] for i in range(1,r+1): for j in range(1,c+1): if word1[i-1] == word2[j-1]: dp[i][j] = 1 + dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) return r + c - 2*dp[-1][-1]
Nirmalkumarvs/programs
Dynamic programming/Delete Operation for Two Strings.py
Delete Operation for Two Strings.py
py
468
python
en
code
0
github-code
36
39400543792
import numpy as np; import cv2; #load image from file #cv2.imwrite('imageName.png', img); rgb_red_pos = 2; rgb_blue_pos = 0; rgb_green_pos = 1; img_1 = cv2.imread('red1.png',1); ##img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY); ##extract the red component image 1 red_only1 = np.int16( np.matrix(img_1[:,:,rgb_red_pos])) - np.int16( np.matrix(img_1[:,:,rgb_blue_pos])) - np.int16( np.matrix(img_1[:,:,rgb_green_pos])); red_only1 = np.uint8(red_only1); red_only1[red_only1 < 0] = 0; red_only1[red_only1 > 255] = 0; cv2.imshow('Image 1',red_only1); img_2 = cv2.imread('red1.png',1); ##img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY); ##extract the red component of image 2 red_only2 = np.int16( np.matrix(img_2[:,:,rgb_red_pos])) - np.int16( np.matrix(img_2[:,:,rgb_blue_pos])) - np.int16( np.matrix(img_2[:,:,rgb_green_pos])) red_only2 = np.uint8(red_only2); red_only2[red_only2 < 0] = 0; red_only2[red_only2 > 255] = 0; cv2.imshow('Image 2',red_only2); ##differences between two frames subtracted = np.int16(red_only1) - np.int16(red_only2); subtracted = np.uint8(subtracted); subtracted[subtracted < 0] = 0; subtracted[subtracted > 255] = 0; cv2.imshow('subtracted',subtracted); def calculateCenterOfMass(subtracted) : rows = np.shape(np.matrix(subtracted))[0]; cols = np.shape(np.matrix(subtracted))[1]; ##calculate the center of mass #np.sum() #0 for columns 1 for rows column_sums = np.matrix(np.sum(subtracted,0)); column_numbers = np.matrix(np.arange(cols)); column_mult = np.multiply(column_sums, column_numbers); total = np.sum(column_mult); #sum the total of the image matrix all_total = np.sum(np.sum(subtracted)); print('the column total is'+str(total)); print('the column all total is'+str(all_total)); #column location #col_location = total / all_total; return 0 if all_total == 0 else total / all_total; cofm = calculateCenterOfMass(subtracted); if(cofm == 0): print('no object detected '); else: print(' object detected '); if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
botchway44/computer-Vision
image diffrencing.py
image diffrencing.py
py
2,160
python
en
code
0
github-code
36
15019927918
# This is a sample Python script. import pandas as pd import csv from datetime import datetime import json import paho.mqtt.client as mqtt from itertools import count import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # Press Mayús+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. field_names = ['timestamp', 'id', 'heart', 'accelerometer'] def write_on_csv(json_missatge): with open('base_dades_didac.csv', 'a') as csv_file: dict_object = csv.DictWriter(csv_file, fieldnames=field_names) dt=datetime.now() ts = datetime.timestamp(dt) new_entry = {'timestamp': int(ts)} new_entry.update(json_missatge) print("\nEl missatge rebut es:",new_entry) dict_object.writerow(new_entry) def on_message(client, userdata, message): missatge_deco=str(message.payload.decode("utf-8")) print("el missatge es:",missatge_deco) #missatge = json.loads(missatge_deco) #write_on_csv(missatge) #print("message received ", str(message.payload.decode("utf-8"))) def subscribe_MQTT(): client = mqtt.Client('SoftwareLazo') client.on_message = on_message client.connect('test.mosquitto.org') client.subscribe('SensorDidacLazo') client.loop_forever() # Press the green button in the gutter to run the script. if __name__ == '__main__': subscribe_MQTT()
JordiLazo/embedded_and_ubiquitous_systems_103056
ReceiverMQTT/main.py
main.py
py
1,463
python
en
code
0
github-code
36
31064957465
from ..utils import Object class ThemeParameters(Object): """ Contains parameters of the application theme Attributes: ID (:obj:`str`): ``ThemeParameters`` Args: background_color (:obj:`int`): A color of the background in the RGB24 format secondary_background_color (:obj:`int`): A secondary color for the background in the RGB24 format text_color (:obj:`int`): A color of text in the RGB24 format hint_color (:obj:`int`): A color of hints in the RGB24 format link_color (:obj:`int`): A color of links in the RGB24 format button_color (:obj:`int`): A color of the buttons in the RGB24 format button_text_color (:obj:`int`): A color of text on the buttons in the RGB24 format Returns: ThemeParameters Raises: :class:`telegram.Error` """ ID = "themeParameters" def __init__(self, background_color, secondary_background_color, text_color, hint_color, link_color, button_color, button_text_color, **kwargs): self.background_color = background_color # int self.secondary_background_color = secondary_background_color # int self.text_color = text_color # int self.hint_color = hint_color # int self.link_color = link_color # int self.button_color = button_color # int self.button_text_color = button_text_color # int @staticmethod def read(q: dict, *args) -> "ThemeParameters": background_color = q.get('background_color') secondary_background_color = q.get('secondary_background_color') text_color = q.get('text_color') hint_color = q.get('hint_color') link_color = q.get('link_color') button_color = q.get('button_color') button_text_color = q.get('button_text_color') return ThemeParameters(background_color, secondary_background_color, text_color, hint_color, link_color, button_color, button_text_color)
iTeam-co/pytglib
pytglib/api/types/theme_parameters.py
theme_parameters.py
py
2,062
python
en
code
20
github-code
36
38264973809
import importlib from copy import deepcopy from os import path as osp from collections import OrderedDict from pyiqa.utils import get_root_logger, scandir from pyiqa.utils.registry import ARCH_REGISTRY from pyiqa.default_model_configs import DEFAULT_CONFIGS __all__ = ['build_network', 'create_metric'] # automatically scan and import arch modules for registry # scan all the files under the 'archs' folder and collect files ending with # '_arch.py' arch_folder = osp.dirname(osp.abspath(__file__)) arch_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(arch_folder) if v.endswith('_arch.py')] # import all the arch modules _arch_modules = [importlib.import_module(f'pyiqa.archs.{file_name}') for file_name in arch_filenames] def create_metric(metric_name, eval=True, **opt): net_opts = OrderedDict() if metric_name in DEFAULT_CONFIGS.keys(): # load default setting first default_opt = DEFAULT_CONFIGS[metric_name]['metric_opts'] net_opts.update(default_opt) # then update with custom setting net_opts.update(opt) network_type = net_opts.pop('type') net = ARCH_REGISTRY.get(network_type)(**net_opts) net.lower_better = DEFAULT_CONFIGS[metric_name].get('lower_better', False) if eval: net.eval() logger = get_root_logger() logger.info(f'Metric [{net.__class__.__name__}] is created.') return net def build_network(opt): opt = deepcopy(opt) network_type = opt.pop('type') net = ARCH_REGISTRY.get(network_type)(**opt) logger = get_root_logger() logger.info(f'Network [{net.__class__.__name__}] is created.') return net
Sskun04085/IQA_PyTorch
pyiqa/archs/__init__.py
__init__.py
py
1,637
python
en
code
0
github-code
36
25084775362
# This Golf class will be responsible for scraping the latest # Trump golf outing located on trumpgolfcount.com from bs4 import BeautifulSoup import requests import json import twitter import lxml import pyrebase def main(): get_latest_outing() def push_db(data): # db.child("time").push(data) db.child("time").child("-LCM0jw1YhB_MxPrN5RS").update({"timez" : data}) print("database has been updated: ", data) def get_latest_outing(): url = 'http://trumpgolfcount.com/displayoutings#tablecaption' req = requests.get(url) soup = BeautifulSoup(req.text, 'lxml') last_outing = soup.find_all('tr')[1] golf_info = [] for text in last_outing: if text.string == '\n': continue elif text.string == None: golf_info.append(text.a.string) golf_info.append(text.string) # make total time in hours and minutes # time = golf_info[11].split(":") # total_time = time[0] + " hours and " + time[1] + "minutes" print("============== template ==============") tweet = "Trump went golfing!" + "\n" + "Where: " + str(golf_info[3]) + "\n" + "When: " + str(golf_info[0]) + "- " + str(golf_info[1])+ "\n" + "Total visits to date: " + str(golf_info[9]) print(golf_info) print("======================================") is_new(str(golf_info[0]), tweet) def is_new(new, tweet): # we need the key to access the table print("accessing db . . .") oldkey = list(db.child("time").get().val())[0] print("db accessed. success!") old = db.child("time").get().val()[oldkey]['timez'] print("old: ", old) print("new: ", new) if old == new: print("Trump has not gone golfing yet.") else: print("Trump went golfing, tweet!") post_tweet(new, tweet) def post_tweet(new, text): print("posting tweet . . .") push_db(new) api.VerifyCredentials() api.PostUpdate(text) print(api.VerifyCredentials()) print("Tweet has been posted.") if __name__ == "__main__": main()
navonf/isTrumpGolfing
Golf.py
Golf.py
py
2,033
python
en
code
0
github-code
36
33540666683
"""HTTP Archive dataflow pipeline for generating HAR data on BigQuery.""" from __future__ import absolute_import import json import logging from copy import deepcopy from hashlib import sha256 import apache_beam as beam from modules import utils, constants, transformation # BigQuery can handle rows up to 100 MB. MAX_CONTENT_SIZE = 2 * 1024 * 1024 # Number of times to partition the requests tables. NUM_PARTITIONS = 4 def get_page(har): """Parses the page from a HAR object.""" if not har: return None page = har.get("log").get("pages")[0] url = page.get("_URL") metadata = get_metadata(har) if metadata: # The page URL from metadata is more accurate. # See https://github.com/HTTPArchive/data-pipeline/issues/48 url = metadata.get("tested_url", url) try: page = trim_page(page) payload_json = to_json(page) except Exception: logging.warning( 'Skipping pages payload for "%s": unable to stringify as JSON.' % url ) return None payload_size = len(payload_json) if payload_size > MAX_CONTENT_SIZE: logging.warning( 'Skipping pages payload for "%s": payload size (%s) exceeds the maximum content size of %s bytes.' % (url, payload_size, MAX_CONTENT_SIZE) ) return None return [ { "url": url, "payload": payload_json, "date": har["date"], "client": har["client"], "metadata": metadata, } ] def get_page_url(har): """Parses the page URL from a HAR object.""" page = get_page(har) if not page: logging.warning("Unable to get URL from page (see preceding warning).") return None return page[0].get("url") def get_metadata(har): page = har.get("log").get("pages")[0] metadata = page.get("_metadata") return metadata def is_home_page(mapped_har): if not mapped_har: return False metadata = mapped_har.get("metadata") if metadata and "crawl_depth" in metadata: return metadata.get("crawl_depth") == 0 # Only home pages have a crawl depth of 0. else: return True # legacy default def partition_step(har, num_partitions): """Returns a partition number based on the hashed HAR page URL""" if not har: logging.warning("Unable to partition step, null HAR.") return 0 page_url = get_page_url(har) if not page_url: logging.warning("Skipping HAR: unable to get page URL (see preceding warning).") return 0 _hash = hash_url(page_url) # shift partitions by one so the zero-th contains errors offset = 1 return (_hash % (num_partitions - 1)) + offset def get_requests(har): """Parses the requests from a HAR object.""" if not har: return None page_url = get_page_url(har) if not page_url: # The page_url field indirectly depends on the get_page function. # If the page data is unavailable for whatever reason, skip its requests. logging.warning( "Skipping requests payload: unable to get page URL (see preceding warning)." ) return None entries = har.get("log").get("entries") requests = [] for request in entries: request_url = request.get("_full_url") if not request_url: logging.warning('Skipping empty request URL for "%s"', page_url) continue try: payload = to_json(trim_request(request)) except Exception: logging.warning( 'Skipping requests payload for "%s": unable to stringify as JSON.' % request_url ) continue payload_size = len(payload) if payload_size > MAX_CONTENT_SIZE: logging.warning( 'Skipping requests payload for "%s": payload size (%s) exceeded maximum content size of %s bytes.' % (request_url, payload_size, MAX_CONTENT_SIZE) ) continue metadata = get_metadata(har) requests.append( { "page": page_url, "url": request_url, "payload": payload, "date": har["date"], "client": har["client"], "metadata": metadata, } ) return requests def trim_request(request): """Removes redundant fields from the request object.""" # Make a copy first so the response body can be used later. request = deepcopy(request) request.get("response").get("content").pop("text", None) return request def trim_page(page): """Removes unneeded fields from the page object.""" if not page: return None # Make a copy first so the data can be used later. page = deepcopy(page) page.pop("_parsed_css", None) return page def hash_url(url): """Hashes a given URL to a process-stable integer value.""" return int(sha256(url.encode("utf-8")).hexdigest(), 16) def get_response_bodies(har): """Parses response bodies from a HAR object.""" page_url = get_page_url(har) requests = har.get("log").get("entries") response_bodies = [] for request in requests: request_url = request.get("_full_url") body = None if request.get("response") and request.get("response").get("content"): body = request.get("response").get("content").get("text", None) if body is None: continue truncated = len(body) > MAX_CONTENT_SIZE if truncated: logging.warning( 'Truncating response body for "%s". Response body size %s exceeds limit %s.' % (request_url, len(body), MAX_CONTENT_SIZE) ) metadata = get_metadata(har) response_bodies.append( { "page": page_url, "url": request_url, "body": body[:MAX_CONTENT_SIZE], "truncated": truncated, "date": har["date"], "client": har["client"], "metadata": metadata, } ) return response_bodies def get_technologies(har): """Parses the technologies from a HAR object.""" if not har: return None page = har.get("log").get("pages")[0] page_url = page.get("_URL") app_names = page.get("_detected_apps", {}) categories = page.get("_detected", {}) metadata = get_metadata(har) # When there are no detected apps, it appears as an empty array. if isinstance(app_names, list): app_names = {} categories = {} app_map = {} app_list = [] for app, info_list in app_names.items(): if not info_list: continue # There may be multiple info values. Add each to the map. for info in info_list.split(","): app_id = "%s %s" % (app, info) if len(info) > 0 else app app_map[app_id] = app for category, apps in categories.items(): for app_id in apps.split(","): app = app_map.get(app_id) info = "" if app is None: app = app_id else: info = app_id[len(app):].strip() app_list.append( { "url": page_url, "category": category, "app": app, "info": info, "date": har["date"], "client": har["client"], "metadata": metadata, } ) return app_list def get_lighthouse_reports(har): """Parses Lighthouse results from a HAR object.""" if not har: return None report = har.get("_lighthouse") if not report: return None page_url = get_page_url(har) if not page_url: logging.warning( "Skipping lighthouse report: unable to get page URL (see preceding warning)." ) return None # Omit large UGC. report.get("audits").get("screenshot-thumbnails", {}).get("details", {}).pop( "items", None ) try: report_json = to_json(report) except Exception: logging.warning( 'Skipping Lighthouse report for "%s": unable to stringify as JSON.' % page_url ) return None report_size = len(report_json) if report_size > MAX_CONTENT_SIZE: logging.warning( 'Skipping Lighthouse report for "%s": Report size (%s) exceeded maximum content size of %s bytes.' % (page_url, report_size, MAX_CONTENT_SIZE) ) return None metadata = get_metadata(har) return [ { "url": page_url, "report": report_json, "date": har["date"], "client": har["client"], "metadata": metadata, } ] def get_parsed_css(har): """Extracts the parsed CSS custom metric from the HAR.""" if not har: return None page = har.get("log").get("pages")[0] page_url = get_page_url(har) if not page_url: logging.warning("Skipping parsed CSS, no page URL") return None metadata = get_metadata(har) if metadata: page_url = metadata.get("tested_url", page_url) is_root_page = True if metadata: is_root_page = metadata.get("crawl_depth") == 0 custom_metric = page.get("_parsed_css") if not custom_metric: logging.warning("No parsed CSS data for page %s", page_url) return None parsed_css = [] for entry in custom_metric: url = entry.get("url") ast = entry.get("ast") if url == 'inline': # Skip inline styles for now. They're special. continue try: ast_json = to_json(ast) except Exception: logging.warning( 'Unable to stringify parsed CSS to JSON for "%s".' % page_url ) continue parsed_css.append({ "date": har["date"], "client": har["client"], "page": page_url, "is_root_page": is_root_page, "url": url, "css": ast_json }) return parsed_css def to_json(obj): """Returns a JSON representation of the object. This method attempts to mirror the output of the legacy Java Dataflow pipeline. For the most part, the default `json.dumps` config does the trick, but there are a few settings to make it more consistent: - Omit whitespace between properties - Do not escape non-ASCII characters (preserve UTF-8) One difference between this Python implementation and the Java implementation is the way long numbers are handled. A Python-serialized JSON string might look like this: "timestamp":1551686646079.9998 while the Java-serialized string uses scientific notation: "timestamp":1.5516866460799998E12 Out of a sample of 200 actual request objects, this was the only difference between implementations. This can be considered an improvement. """ if not obj: raise ValueError return json.dumps(obj, separators=(",", ":"), ensure_ascii=False) def from_json(file_name, element): """Returns an object from the JSON representation.""" try: return [(file_name, json.loads(element))] except Exception as e: logging.error('Unable to parse file %s into JSON object "%s...": %s' % (file_name, element[:50], e)) return None def add_date_and_client(element): """Adds `date` and `client` attributes to facilitate BigQuery table routing""" if element is None: logging.error('Element is empty, skipping adding date and time') return None try: file_name, har = element date, client = utils.date_and_client_from_file_name(file_name) page = har.get("log").get("pages")[0] metadata = page.get("_metadata", {}) har.update( { "date": "{:%Y_%m_%d}".format(date), "client": metadata.get("layout", client).lower(), } ) return har except Exception as e: logging.error('Unable to add date and client "%s...": %s' % (element[:50], e)) return None class WriteNonSummaryToBigQuery(beam.PTransform): def __init__( self, partitions, dataset_pages, dataset_technologies, dataset_lighthouse, dataset_requests, dataset_response_bodies, dataset_parsed_css, dataset_pages_home_only, dataset_technologies_home_only, dataset_lighthouse_home_only, dataset_requests_home_only, dataset_response_bodies_home_only, dataset_parsed_css_home_only, label=None, **kwargs, ): # TODO(BEAM-6158): Revert the workaround once we can pickle super() on py3. # super().__init__(label) beam.PTransform.__init__(self) self.label = label self.partitions = partitions self.dataset_pages = dataset_pages self.dataset_technologies = dataset_technologies self.dataset_lighthouse = dataset_lighthouse self.dataset_requests = dataset_requests self.dataset_response_bodies = dataset_response_bodies self.dataset_parsed_css = dataset_parsed_css self.dataset_pages_home = dataset_pages_home_only self.dataset_technologies_home = dataset_technologies_home_only self.dataset_lighthouse_home = dataset_lighthouse_home_only self.dataset_requests_home = dataset_requests_home_only self.dataset_response_bodies_home = dataset_response_bodies_home_only self.dataset_parsed_css_home = dataset_parsed_css_home_only def _transform_and_write_partition( self, pcoll, name, index, fn, table_all, table_home, schema ): formatted_name = utils.title_case_beam_transform_name(name) all_rows = pcoll | f"Map{formatted_name}{index}" >> beam.FlatMap(fn) home_only_rows = all_rows | f"Filter{formatted_name}{index}" >> beam.Filter(is_home_page) home_only_rows | f"Write{formatted_name}Home{index}" >> transformation.WriteBigQuery( table=lambda row: utils.format_table_name(row, table_home), schema=schema, ) def expand(self, hars): # Add one to the number of partitions to use the zero-th partition for failures partitions = hars | beam.Partition(partition_step, self.partitions + 1) # log 0th elements (failures) partitions[0] | "LogPartitionFailures" >> beam.FlatMap( lambda e: logging.warning(f"Unable to partition record: {e}") ) # enumerate starting from 1 for idx in range(1, self.partitions + 1): self._transform_and_write_partition( pcoll=partitions[idx], name="pages", index=idx, fn=get_page, table_all=self.dataset_pages, table_home=self.dataset_pages_home, schema=constants.BIGQUERY["schemas"]["pages"], ) self._transform_and_write_partition( pcoll=partitions[idx], name="technologies", index=idx, fn=get_technologies, table_all=self.dataset_technologies, table_home=self.dataset_technologies_home, schema=constants.BIGQUERY["schemas"]["technologies"], ) self._transform_and_write_partition( pcoll=partitions[idx], name="lighthouse", index=idx, fn=get_lighthouse_reports, table_all=self.dataset_lighthouse, table_home=self.dataset_lighthouse_home, schema=constants.BIGQUERY["schemas"]["lighthouse"], ) self._transform_and_write_partition( pcoll=partitions[idx], name="requests", index=idx, fn=get_requests, table_all=self.dataset_requests, table_home=self.dataset_requests_home, schema=constants.BIGQUERY["schemas"]["requests"], ) self._transform_and_write_partition( pcoll=partitions[idx], name="response_bodies", index=idx, fn=get_response_bodies, table_all=self.dataset_response_bodies, table_home=self.dataset_response_bodies_home, schema=constants.BIGQUERY["schemas"]["response_bodies"], ) self._transform_and_write_partition( pcoll=partitions[idx], name="parsed_css", index=idx, fn=get_parsed_css, table_all=self.dataset_parsed_css, table_home=self.dataset_parsed_css_home, schema=constants.BIGQUERY["schemas"]["parsed_css"], )
HTTPArchive/data-pipeline
modules/non_summary_pipeline.py
non_summary_pipeline.py
py
17,297
python
en
code
3
github-code
36
5259209115
# import libraries import datetime from airflow import DAG from airflow.contrib.operators.emr_create_job_flow_operator import EmrCreateJobFlowOperator from airflow.contrib.operators.emr_add_steps_operator import EmrAddStepsOperator from airflow.contrib.sensors.emr_step_sensor import EmrStepSensor from airflow.contrib.operators.emr_terminate_job_flow_operator import EmrTerminateJobFlowOperator ################ # CONFIGURATIONS ################ # name of s3 bucket with scripts s3_bucket = "s3://dendcapstoneproject/" # initialize dag dag = DAG( "prepare-data-for-redshift", start_date=datetime.datetime.now()-datetime.timedelta(days=1), schedule_interval="@once" ) #################### # CREATE EMR CLUSTER #################### JOB_FLOW_OVERRIDES = { "Name": "capstone-emr", "LogUri": "s3://aws-logs-576946247943-us-west-2/elasticmapreduce/", "ReleaseLabel": "emr-6.5.0", "Applications": [{"Name": "Hadoop"}, {"Name": "Spark"}], "Configurations": [ { "Classification": "spark-env", "Configurations": [ { "Classification": "export", "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3"}, } ], } ], "Instances": { "InstanceGroups": [ { "Name": "Master node", "Market": "ON_DEMAND", "InstanceRole": "MASTER", "InstanceType": "m5.xlarge", "InstanceCount": 1, }, { "Name": "Core - 2", "Market": "ON_DEMAND", "InstanceRole": "CORE", "InstanceType": "m5.xlarge", "InstanceCount": 2, }, ], "KeepJobFlowAliveWhenNoSteps": True, "TerminationProtected": False, }, "JobFlowRole": "EMR_EC2_DefaultRole", "ServiceRole": "EMR_DefaultRole", } create_emr_cluster = EmrCreateJobFlowOperator( task_id="create_emr_cluster", job_flow_overrides=JOB_FLOW_OVERRIDES, aws_conn_id="aws_credentials", emr_conn_id="emr_default", dag=dag ) ############################ # IMMIGRATION DATA HANDLING ############################ # preprocess the immigration data prior to create fact and dimension tables preprocess_immigration_data = EmrAddStepsOperator( task_id="preprocess_immigration_data", job_flow_id="{{ task_instance.xcom_pull(task_ids='create_emr_cluster', key='return_value') }}", aws_conn_id="aws_credentials", steps=[{ "Name": "preprocess_immigration_data", "ActionOnFailure": "TERMINATE_CLUSTER", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--master", "yarn", "--packages", "saurfang:spark-sas7bdat:3.0.0-s_2.12", "--py-files", f"{s3_bucket}scripts/shared_spark_vars.py", f"{s3_bucket}scripts/immigration-data-preprocessing.py" ] } }], dag=dag ) # create the fact and dimension tables create_immigration_fact_dims = EmrAddStepsOperator( task_id="create_immigration_fact_dims", job_flow_id="{{ task_instance.xcom_pull(task_ids='create_emr_cluster', key='return_value') }}", aws_conn_id="aws_credentials", steps=[{ "Name": "create_immigration_fact_dims", "ActionOnFailure": "TERMINATE_CLUSTER", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--master", "yarn", "--py-files", f"{s3_bucket}scripts/shared_spark_vars.py", f"{s3_bucket}scripts/immigration-fact-and-dimension-creation.py" ] } }], dag=dag ) # watch the immigration data handling process watch_immigration_data_handling = EmrStepSensor( task_id="watch_immigration_data_handling", job_flow_id="{{ task_instance.xcom_pull('create_emr_cluster', key='return_value') }}", step_id="{{ task_instance.xcom_pull(task_ids='create_immigration_fact_dims', key='return_value')[0] }}", aws_conn_id="aws_credentials", dag=dag ) ############################ # DEMOGRAPHIC DATA HANDLING ############################ # preprocess the demographic data and create fact and dimension tables using it process_demographic_data = EmrAddStepsOperator( task_id="process_demographic_data", job_flow_id="{{ task_instance.xcom_pull(task_ids='create_emr_cluster', key='return_value') }}", aws_conn_id="aws_credentials", steps=[{ "Name": "process_demographic_data", "ActionOnFailure": "TERMINATE_CLUSTER", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--master", "yarn", "--py-files", f"{s3_bucket}scripts/shared_spark_vars.py", f"{s3_bucket}scripts/demographics-data-processing.py" ] } }], dag=dag ) # watch the demographic data handling process watch_demographic_data_handling = EmrStepSensor( task_id="watch_demographic_data_handling", job_flow_id="{{ task_instance.xcom_pull('create_emr_cluster', key='return_value') }}", step_id="{{ task_instance.xcom_pull(task_ids='process_demographic_data', key='return_value')[0] }}", aws_conn_id="aws_credentials", dag=dag ) ############################# # AIRPORT CODES DATA HANDLING ############################# # preprocess the airport data and create fact and dimension tables using it process_airport_data = EmrAddStepsOperator( task_id="process_airport_data", job_flow_id="{{ task_instance.xcom_pull(task_ids='create_emr_cluster', key='return_value') }}", aws_conn_id="aws_credentials", steps=[{ "Name": "process_airport_data", "ActionOnFailure": "TERMINATE_CLUSTER", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--master", "yarn", "--py-files", f"{s3_bucket}scripts/shared_spark_vars.py", f"{s3_bucket}scripts/airport-codes-processing.py" ] } }], dag=dag ) # watch the airport data handling process watch_airport_data_handling = EmrStepSensor( task_id="watch_airport_data_handling", job_flow_id="{{ task_instance.xcom_pull('create_emr_cluster', key='return_value') }}", step_id="{{ task_instance.xcom_pull(task_ids='process_airport_data', key='return_value')[0] }}", aws_conn_id="aws_credentials", dag=dag ) ########################### # TEMPERATURE DATA HANDLING ########################### # preprocess the temperature data and create fact and dimension tables using it process_temperature_data = EmrAddStepsOperator( task_id="process_temperature_data", job_flow_id="{{ task_instance.xcom_pull(task_ids='create_emr_cluster', key='return_value') }}", aws_conn_id="aws_credentials", steps=[{ "Name": "process_temperature_data", "ActionOnFailure": "TERMINATE_CLUSTER", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--master", "yarn", "--py-files", f"{s3_bucket}scripts/shared_spark_vars.py", f"{s3_bucket}scripts/temperature-data-processing.py" ] } }], dag=dag ) # watch the temperature data handling process watch_temperature_data_handling = EmrStepSensor( task_id="watch_temperature_data_handling", job_flow_id="{{ task_instance.xcom_pull('create_emr_cluster', key='return_value') }}", step_id="{{ task_instance.xcom_pull(task_ids='process_temperature_data', key='return_value')[0] }}", aws_conn_id="aws_credentials", dag=dag ) ##################### # TERMINATE CLUSTER #################### # terminate the EMR cluster terminate_emr_cluster = EmrTerminateJobFlowOperator( task_id="terminate_emr_cluster", job_flow_id="{{ task_instance.xcom_pull(task_ids='create_emr_cluster', key='return_value') }}", aws_conn_id="aws_default", dag=dag, ) ########### # JOB FLOW ########### create_emr_cluster >> preprocess_immigration_data >> create_immigration_fact_dims >> watch_immigration_data_handling create_emr_cluster >> process_airport_data >> watch_airport_data_handling create_emr_cluster >> process_demographic_data >> watch_demographic_data_handling [watch_airport_data_handling, watch_demographic_data_handling] >> process_temperature_data >> watch_temperature_data_handling [watch_immigration_data_handling, watch_temperature_data_handling] >> terminate_emr_cluster
stefanjaro/data-engineering-nanodegree-capstone-project
airflow/dags/prepare-data-for-redshift.py
prepare-data-for-redshift.py
py
8,900
python
en
code
0
github-code
36
71252887144
from datetime import datetime import glob import os import time import anim import threading print(datetime.timestamp(datetime.now())) class User: def __init__(self, name: str): self.name = name class Chat: def __init__(self, username: str, text: str, score: int = 0): self.author = User(username) self.body = text self.score = score # most_common = ['a', 'b', 'c'] # characters = anim.get_characters(most_common) # chats = [ # Chat('a', '안녕'), # Chat('b', '반가워'), # Chat('c', '안녕하세요.', score=-1) # ] # anim.comments_to_scene(chats, characters, output_filename="hello.mp4") from flask import Flask, request, jsonify, send_file app = Flask(__name__) @app.post('/generate') def generate(): chats = [] most_common = [] print(request.json) for c in request.json: chats.append(Chat(c['nickname'], c['content'])) # if not c['nickname'] in most_common: most_common.append(c['nickname']) characters = anim.get_characters(most_common) filename = f"outputs/{datetime.timestamp(datetime.now())}.mp4" anim.comments_to_scene(chats, characters, output_filename=filename) print("success") return send_file(filename, mimetype='video/mp4') def delete_every_10_min(): for f in glob.glob("outputs/*.mp4"): os.remove(f) time.sleep(600) delete_every_10_min() threading.Thread(target=delete_every_10_min) app.run('0.0.0.0', 5050)
ij5/ace-ainize
app.py
app.py
py
1,475
python
en
code
0
github-code
36
13186345837
def selection_sort(nums) : size = len(nums) for i in range(0 , size-1): min_pos = i for j in range (i+1 , size): if nums[j] < nums[min_pos] : min_pos = j if min_pos != i: nums[i] , nums[min_pos] = nums[min_pos] , nums[i] return nums sortValue = selection_sort([4,3,2,1,8,9,6]) print(sortValue)
Dulal-12/sortinga-Algorithm
sle.py
sle.py
py
372
python
en
code
0
github-code
36
11798416126
from math import log10 def calculate(balance, apr, payment): x = -0.33 apr = apr/100 w = 1-((1+(apr/365))**30) z = log10((1 + ((balance/payment)*w))) y = log10(1 + apr) months = divmod(((x * (z//y)) * 365), 12) return int(months[0]) balance = int(input("What is your balance? ")) apr = int(input("What is the APR on the card (as a percent)? ")) payment = int(input("What is the monthly payment you can make? ")) print("It will take you {} months to pay off this card.".format(calculate(balance, apr, payment)))
matryosh/Programming-Exercises
python/Chapter_5/months-to-payoff-credit.py
months-to-payoff-credit.py
py
543
python
en
code
0
github-code
36
6241263490
def btr(depth): global max_num num = int(''.join(nums)) if num in num_set: return else: num_set.add(num) if depth == n: num = int() if max_num < max(num_set): max_num = max(num_set) return for i in range(size): for j in range(i+1, size): temp = nums[i] nums[i] = nums[j] nums[j] = temp btr(depth+1) temp = nums[i] nums[i] = nums[j] nums[j] = temp T = int(input()) for i in range(1, T+1): nums, n = input().split() n = int(n) nums = list(nums) max_num = 0 size = len(nums) num_set = set() btr(0) print(f'#{i} {max_num}')
daehyun1023/Algorithm
python/swea/swea1244.py
swea1244.py
py
725
python
en
code
0
github-code
36
8368222279
from itertools import groupby def checkgroup(word): group = [key for key, item in groupby(word)] values =[(k, [i for i in range(len(word)) if word[i] == k]) for k in group] groupword = 0 for items in values: if items[1].__len__() == 0: groupword += 1 continue for index in range(1, items[1].__len__()): if items[1][index]-items[1][index-1] >1: groupword = 0 return groupword groupword += 1 return groupword count = int(input()) words = [input() for _ in range(count)] result = 0 for _ in words: groupcount = checkgroup(_) if groupcount != 0: result+=1 print(result)
hyelimchoi1223/Algorithm-Study
백준/[백준]1316 그룹 단어 체커/python.py
python.py
py
789
python
en
code
1
github-code
36
34545951895
'Chat room client' import threading import socket class chatRoomClient: ALIAS = "johnDoe" client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server = "127.0.0.1" port = 6969 encoding = "utf-8" def __init__(self, ip="127.0.0.1", port=6967): self.ALIAS = input("Choose an alias >>> ") self.ip = ip self.port = port self.client.connect((self.ip, self.port)) def client_recieve(self): while True: try: message = self.client.recv(2048).decode(self.encoding) if message == "alias??": self.client.send(self.ALIAS.encode(self.encoding)) else: print(message) except: print("Error!") self.client.close() break def client_send(self): while True: message = f"{self.ALIAS}: {input('')}" self.client.send(message.encode(self.encoding)) def start_client(self): rThread = threading.Thread(target=self.client_recieve) rThread.start() sThread = threading.Thread(target=self.client_send) sThread.start() if __name__ == "__main__": chatClient = chatRoomClient() chatClient.start_client()
MrMetrik/chatRoom
client/client2.py
client2.py
py
1,308
python
en
code
0
github-code
36
15775777498
from enum import Enum from dataclasses import dataclass class TokenType(Enum): NUMBER = 0 PLUS = 1 MINUS = 2 ASTERISK = 3 SLASH = 4 LPAR = 5 RPAR = 6 @dataclass class Token: type: TokenType value: str def __repr__(self) -> str: return f"({self.type.name}, '{self.value}')"
ricdip/py-math-interpreter
src/model/token.py
token.py
py
326
python
en
code
0
github-code
36
42498915540
from sequ_error import * # Converts an integer to a roman numeral def int_to_roman(input): try: if type(input) != type(1): raise FormatError("expected integer, got %s" % type(input)) if not 0 < input < 4000: raise FormatError("argument must be between 1 and 3999") except FormatError as e: print("sequ: " + e.message + " for type 'roman'") exit(1) ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I') result = "" for i in range(len(ints)): count = int(input / ints[i]) result += nums[i] * count input -= ints[i] * count return result # Converts roman numerals to integers def roman_to_int(input): try: if type(input) != type(""): raise FormatError("expected string, got %s" % type(input)) except FormatError as e: print("sequ: " + e.message + " for type 'roman'") exit(1) input = input.upper() nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I'] ints = [1000, 500, 100, 50, 10, 5, 1] places = [] for c in input: try: if not c in nums: raise FormatError('argument %s is not valid' % input) except FormatError as e: print("sequ: " + e.message + " for type 'roman'") exit(1) for i in range(len(input)): c = input[i] value = ints[nums.index(c)] # If the next place holds a larger number, this value is negative. try: nextvalue = ints[nums.index(input[i +1])] if nextvalue > value: value *= -1 except IndexError: # there is no next place. pass places.append(value) sum = 0 for n in places: sum += n # Easiest test for validity... try: if int_to_roman(sum) == input: return sum else: raise FormatError('argument %s is not valid' % input) except FormatError as e: print("sequ: " + e.message + " for type 'roman'") exit(1)
razanur37/sequ.py
sequ_roman.py
sequ_roman.py
py
2,135
python
en
code
1
github-code
36
31371160161
# 4- Напишите программу, которая будет преобразовывать десятичное число в двоичное. # Подумайте, как это можно решить с помощью рекурсии. # Пример: # 45 -> 101101 # 3 -> 11 # 2 -> 10 from function import CheckInputIntNumbers def binar_sys (number:int,list:list) -> int: """ Преобразовывает десятичное число в двоичное """ if number<1: return number else: list.append(int(int(number)%2)) binar_sys(int(int(number)/2),list) return int (number) number=input("Введите челое число : ") number=CheckInputIntNumbers(number) number=int(number) list=[] binar_sys(number,list) list.reverse() strOut="" for i in list: strOut=str(strOut)+str(i) print(f"{number} -> {strOut}")
AlexandrFeldsherov/lessonTreeSeminar
task004.py
task004.py
py
906
python
ru
code
0
github-code
36
18394317715
import sys import numpy as np import tiledb # Name of the array to create. array_name = "reading_dense_layouts" def create_array(): # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. dom = tiledb.Domain( tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), ) # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. schema = tiledb.ArraySchema( domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] ) # Create the (empty) array on disk. tiledb.DenseArray.create(array_name, schema) def write_array(): # Open the array and write to it. with tiledb.DenseArray(array_name, mode="w") as A: # NOTE: global writes are not currently supported in the Python API. # The following code will produce the same array as the corresponding # C++ example in the docs (which wrote in global order) data = np.array(([1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16])) A[:] = data def read_array(order): # Open the array and read from it. with tiledb.DenseArray(array_name, mode="r") as A: # Get non-empty domain print("Non-empty domain: {}".format(A.nonempty_domain())) # Slice only rows 1, 2 and cols 2, 3, 4. # NOTE: The `query` syntax is required to get the coordinates for # dense arrays and specify an order other than the default row-major data = A.query(attrs=["a"], order=order, coords=True)[1:3, 2:5] a_vals = data["a"] coords = np.asarray(list(zip(data["rows"], data["cols"]))) if order != "G" and a_vals.flags["F_CONTIGUOUS"]: print("NOTE: The following result array has col-major layout internally") if order != "G": for i in range(coords.shape[0]): for j in range(coords.shape[1]): print( "Cell {} has data {}".format( str(coords[i, j]), str(a_vals[i, j]) ) ) else: # When reading in global order, TileDB always returns a vector (1D array) for i in range(coords.shape[0]): print("Cell {} has data {}".format(str(coords[i]), str(a_vals[i]))) # Check if the array already exists. if tiledb.object_type(array_name) != "array": create_array() write_array() layout = "" if len(sys.argv) > 1: layout = sys.argv[1] order = "C" if layout == "col": order = "F" elif layout == "global": order = "G" else: order = "C" read_array(order)
TileDB-Inc/TileDB-Py
examples/reading_dense_layouts.py
reading_dense_layouts.py
py
2,729
python
en
code
165
github-code
36
37453777335
from .textbox import Textbox from engine.device import Device from engine.action import Action from typing import List from .clickable import BLUE, RED from numpy.random import randn as random from engine.player import Player from user_interface.show_money_textbox import Money_Textbox BACKSPACE: int = 8 ENTER: int = 13 MONEY: int = 0 class GameTextbox(Textbox): def __init__(self, x: int, y: int, width: int, height: int, title: str, Money_Textbox: Money_Textbox, player: Player): super(GameTextbox, self).__init__(x, y, width, height, title) self.random_number = int(random() * 10) self.tries = 0 self.Money_Textbox = Money_Textbox self.player = player def on_finish(self): print(self.random_number) if self.tries <= 3: selection = int(self.text) if selection < self.random_number: self.text += "; The number is higher" elif selection > self.random_number: self.text += "; The number is lower" else: self.text += "; Good job" self.player.money += 100 self.game_over() else: self.game_over() self.render() self.text = "" def game_over(self): self.text = 'game over' self.random_number = int(random() * 10) self.Money_Textbox.update_text() self.tries = 0
talacounts/game_of_life
user_interface/game_textbox.py
game_textbox.py
py
1,425
python
en
code
0
github-code
36
9169632462
# coding=utf-8 import os import sys import platform import subprocess import shutil Python = "python" if platform.system() == "Windows" else "python3" def executCommand(command): out = open(os.devnull, 'w') err = subprocess.STDOUT return subprocess.call(command, shell=True, stdout=out, stderr=err) def runScript(Script, Params): if os.system(Python + " " + Script + " " + Params) != 0: print("Unable to run " + Script) exit(255) def CopySelf(targetPath): if not os.path.exists(targetPath): shutil.copy() pass # python recheck if executCommand(Python + " --version") != 0: print("Make sure Python can be started from the command line (add path to `python.exe` to PATH on Windows)") exit(255) # cmake check if executCommand("cmake --version") != 0: print("No CMake") exit(255) # git check if executCommand("git --version") != 0: print("No Gits") exit(255) cwd = os.getcwd() runScript( os.path.join(cwd,"TMake","python", "bootstrap.py"), cwd) print("\nMonkey Initialize complete!\n")
Thenecromance/TMake
python/TLoader.py
TLoader.py
py
1,073
python
en
code
0
github-code
36
32417088655
import json from typing import Dict from influxdb_client import InfluxDBClient, Point, WritePrecision from influxdb_client.client.write_api import SYNCHRONOUS import pandas as pd import logging class InfluxDB: def __init__(self, local) -> None: # Create a config.json file and store your INFLUX token as a key value pair with open('config.json', 'r') as f: self.config = json.load(f) self.client = self.get_influxdb_client(local) self.write_api = self.client.write_api(write_options=SYNCHRONOUS) self.query_api = self.client.query_api() self.delete_api = self.client.delete_api() def get_influxdb_client(self, local=False): return InfluxDBClient( url="http://localhost:8086" if local else "https://us-east-1-1.aws.cloud2.influxdata.com", token=self.config['INFLUXDB_TOKEN_LOCAL'] if local else self.config['INFLUXDB'], org="pepe" ) def write_candles_to_influxdb( self, exchange, symbol: str, timeframe: str, candles: pd.DataFrame, bucket: str = "candles", ) -> None: if candles.empty: logging.warning(f"Skipping write to InfluxDB for {exchange} {symbol} {timeframe} as the DataFrame is empty.") return symbol = symbol.replace("/", "_") points = [] for record in candles.to_records(): point = Point("candle") \ .tag("exchange", exchange) \ .tag("symbol", symbol) \ .tag("timeframe", timeframe) \ .field("opens", record.opens) \ .field("highs", record.highs) \ .field("lows", record.lows) \ .field("closes", record.closes) \ .field("volumes", record.volumes) \ .time(record.dates, WritePrecision.MS) points.append(point) logging.info(f"Writing {len(candles['dates'])} candles to bucket: {bucket}, organization: 'pepe'") self.write_api.write(bucket, 'pepe', points) def read_candles_from_influxdb( self, exchange: str, symbol: str, timeframe: str, bucket="candles") -> Dict: symbol = symbol.replace("/", "_") query = f""" from(bucket: "{bucket}") |> range(start: -1000d) |> filter(fn: (r) => r["_measurement"] == "candle") |> filter(fn: (r) => r["exchange"] == "{exchange}") |> filter(fn: (r) => r["symbol"] == "{symbol}") |> filter(fn: (r) => r["timeframe"] == "{timeframe}") |> filter(fn: (r) => r["_field"] == "closes" or r["_field"] == "highs" or r["_field"] == "lows" or r["_field"] == "opens" or r["_field"] == "volumes") |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value") |> drop(columns: ["_start", "_stop"]) """ result = self.query_api.query_data_frame(query, 'pepe') logging.info(f"Found {len(result)} candles from bucket: {bucket}, organization: 'pepe', {exchange}, {symbol}, {timeframe}:") if result.empty: return pd.DataFrame(columns=["dates", "opens", "highs", "lows", "closes", "volumes"]) else: result = result.rename(columns={"_time": "dates"}) result = result.reindex(columns=["dates", "opens", "highs", "lows", "closes", "volumes"]) return result
pattty847/Crypto-Market-Watch
app/api/influx.py
influx.py
py
3,453
python
en
code
2
github-code
36
74087426982
import requests, datetime, csv from flask import Flask from flask import request, render_template response = requests.get("http://api.nbp.pl/api/exchangerates/tables/C?format=json") data_as_json= response.json() app = Flask(__name__) for item in data_as_json: only_rates = item.get('rates') current_date = item.get('effectiveDate') codes_list = [] for rate in only_rates: cc = rate['code'] codes_list.append(cc) with open('names.csv', 'w', encoding="utf-8", newline='') as csvfile: fieldnames = ['currency','code','bid','ask'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ';') writer.writeheader() for rate in only_rates: writer.writerow({'currency':rate.get('currency'),'code':rate.get('code'), 'bid':rate.get('bid'),'ask':rate.get('ask')}) @app.route('/calculator', methods=['GET', 'POST']) def rates_calculator(): if request.method == 'GET': print("We received GET") return render_template("calculator.html", codes_list=codes_list) elif request.method == 'POST': print("We received POST") if current_date != datetime.date.today(): response = requests.get("http://api.nbp.pl/api/exchangerates/tables/C?format=json") data_as_json= response.json() for item in data_as_json: only_rates = item.get('rates') d = request.form quantity_form=d.get('quantity') curr_selected_form=d.get('currencies') for rate in only_rates: if curr_selected_form ==rate.get('code'): result=float(rate.get('ask'))*float(quantity_form) print(result) return f'{quantity_form} {curr_selected_form} cost {result:0.2f} PLN.' if __name__ == "__main__": app.run(debug=True)
gorkamarlena/currency_calculator
app.py
app.py
py
1,803
python
en
code
0
github-code
36
34981855639
from flask import Flask, request, render_template from googlesearch import search app = Flask(__name__) def search_pdfs(query, num_results=5): search_results = [] try: for j in search(query + " filetype:pdf", num_results=num_results): search_results.append(j) return search_results except Exception as e: print(f"An error occurred: {str(e)}") return [] @app.route("/", methods=["GET", "POST"]) def index(): search_results = [] if request.method == "POST": search_query = request.form.get("query") search_results = search_pdfs(search_query, num_results=5) return render_template("index.html", search_results=search_results) if __name__ == "__main__": app.run(debug=True)
suryagowda/booksearcherr
booksearcher/app.py
app.py
py
764
python
en
code
0
github-code
36
32072082706
from flask import Flask, request, jsonify from sklearn.ensemble import GradientBoostingRegressor import pickle import matplotlib import joblib import pandas as pd from sklearn.preprocessing import LabelEncoder from load_data import ( get_binance_dataframe, get_bingx_dataframe, get_bitget_dataframe, get_tapbit_dataframe, ) modelGB = joblib.load("gradient_boosting_model.pkl") def predict(): exchanges = ["binance", "bitget", "bingx", "tapbit"] predictions = {} for exchange in exchanges: print(exchange) exchange_df = {} if exchange == "binance": exchange_df = get_binance_dataframe() elif exchange == "bitget": exchange_df = get_bitget_dataframe() elif exchange == "bingx": exchange_df = get_bingx_dataframe() elif exchange == "tapbit": exchange_df = get_tapbit_dataframe() X = exchange_df[["time", "volume", "high", "low", "open", "symbol"]] actual = exchange_df[["symbol", "close"]] print("actual data:", actual) y_pred = modelGB.predict(X) pd.options.display.float_format = "{:.4f}".format labels = exchange_df["symbol"].values.tolist() organized_predictions = {label: price for label, price in zip(labels, y_pred)} predictions[exchange] = organized_predictions merged_predictions = pd.DataFrame.from_dict( predictions[exchange], orient="index", columns=[f"predicted_{exchange}"] ) # Merge actual data with predictions based on symbol merged_predictions = merged_predictions.merge( actual, left_index=True, right_on="symbol", how="inner" ) merged_predictions.rename(columns={"close": f"actual_{exchange}"}, inplace=True) merged_predictions.set_index("symbol", inplace=True) # Calculate difference between predicted and actual values merged_predictions[f"diff_{exchange}"] = ( merged_predictions[f"predicted_{exchange}"] - merged_predictions[f"actual_{exchange}"] ) predictions[exchange] = merged_predictions result_df = pd.concat(predictions.values(), axis=1) print(result_df) return jsonify(result_df.to_dict()) predict()
PhatcharaNarinrat/adamas-arbitrage
prediction.py
prediction.py
py
2,279
python
en
code
0
github-code
36
20857572237
#https://leetcode.com/problems/pascals-triangle-ii/ class Solution: def getRow(self, rowIndex: int) -> List[int]: lis=[[1]] print(lis) for x in range(1,rowIndex+1): temp=lis[x-1] #we have temp temp.insert(0,0) temp.append(0) l=[] for i in range(0,len(temp)-1): l.append(temp[i]+temp[i+1]) lis.append(l) print(lis) return lis[-1]
manu-karenite/Problem-Solving
DP/pascalsTriangle.py
pascalsTriangle.py
py
482
python
en
code
0
github-code
36
44599845798
class Node: def __init__(self, data= None, next_node= None): self.data = data self.next_node = next_node class LinkedList: def __init__(self): self.head = None self.last_node= None def print_ll(self): ll_string = "" node = self.head if node is None: print(None) while node: ll_string += f" {str(node.data)} ->" node = node.next_node ll_string += " None" print(ll_string) def to_arr(self): arr = [] if self is None: return arr node = self.head while node: arr.append(node.data) node = node.next_node return arr def insert_beginning(self, data): if self.head is None: self.head = Node(data, None) self.last_node = self.head new_node = Node(data, self.head) self.head = new_node def insert_ending(self, data): if self.head is None: self.insert_beginning(data) # # if last node is None # if self.last_node is None: # print("last node is None") # node = self.head # # while node.next_node: # # print(f"at node: {node.data}") # # node = node.next_node # node.next_node = Node(data, None) # self.last_node = node.next_node # # if the last node is an existing node # else: self.last_node.next_node = Node(data, None) self.last_node = self.last_node.next_node def get_user_id(self, user_id): node = self.head while node: if node.data["id"] is int(user_id): return node.data node = node.next_node return None # ll3 = LinkedList() # ll3.insert_beginning("5") # ll3.insert_beginning("4") # ll3.insert_beginning("3") # ll3.insert_beginning("2") # ll3.insert_beginning("1") # ll3.insert_ending("6") # ll3.insert_ending("7") # ll3.print_ll()
ada-nai/fcc-ds-flask
linked_list.py
linked_list.py
py
2,052
python
en
code
0
github-code
36
27335304681
#!/usr/bin/python3 from Random import * import turtle import numpy import random import math r = Random(517 ,0 ,8999) scale = 10 def reset(x,y): root = turtle.getscreen()._root turtle.clear() root.withdraw() root.quit() def getDirection(): return r.random()%4 def draw(x, y): reset(None, None) root = turtle.getscreen()._root root.state('normal') turtle.speed(0) turtle.goto(x[0]*scale, y[0]*scale) turtle.pendown() for i in range(1, len(x)): turtle.goto(x[i]*scale, y[i]*scale) turtle.penup() turtle.onscreenclick(reset) def drawUnique(posList): reset(None, None) root = turtle.getscreen()._root root.state('normal') turtle.speed(0) turtle.goto(posList[0][0]*scale, posList[0][0]*scale) turtle.pendown() for i in range(1, len(posList)): turtle.goto(posList[i][0]*scale, posList[i][1]*scale) turtle.penup() turtle.onscreenclick(reset) def classique(): print("\nNombre de pas de la simulation ?") nSteps = int(input()) x = numpy.zeros(nSteps) y = numpy.zeros(nSteps) for i in range(1, nSteps): val = getDirection() if val == 0: #droite x[i] = x[i - 1] + 1 y[i] = y[i - 1] elif val == 1: #gauche x[i] = x[i - 1] - 1 y[i] = y[i - 1] elif val == 2: #haut x[i] = x[i - 1] y[i] = y[i - 1] + 1 else: #bas x[i] = x[i - 1] y[i] = y[i - 1] - 1 draw(x, y) def sansRetour(): print("\nNombre de pas de la simulation ?") nSteps = int(input()) x = numpy.zeros(nSteps) y = numpy.zeros(nSteps) previous = None for i in range(1, nSteps): val = getDirection() while True: if val == 0 and previous == 1: #going right from a left val = getDirection() elif val == 1 and previous == 0: #going left from a right val = getDirection() elif val == 2 and previous == 3: #going up from a down val = getDirection() elif val == 3 and previous == 2: #going down from a up val = getDirection() else: break previous = val if val == 0: #droite x[i] = x[i - 1] + 1 y[i] = y[i - 1] elif val == 1: #gauche x[i] = x[i - 1] - 1 y[i] = y[i - 1] elif val == 2: #haut x[i] = x[i - 1] y[i] = y[i - 1] + 1 elif val == 3: #bas x[i] = x[i - 1] y[i] = y[i - 1] - 1 draw(x, y) def passageUnique(): print("\nNombre de pas de la simulation ?") nSteps = int(input()) counter = 0 positions = [] x = numpy.zeros(nSteps) y = numpy.zeros(nSteps) positions.append((0, 0)) for i in range(1, nSteps): if counter >= nSteps: break while True: if counter >= nSteps: break val = getDirection() if val == 0: #droite x[i] = x[i - 1] + 1 y[i] = y[i - 1] elif val == 1: #gauche x[i] = x[i - 1] - 1 y[i] = y[i - 1] elif val == 2: #haut x[i] = x[i - 1] y[i] = y[i - 1] + 1 elif val == 3: #bas x[i] = x[i - 1] y[i] = y[i - 1] - 1 nextPos = (x[i], y[i]) counter += 1 if verifyPosition(nextPos, positions): break positions.append((x[i], y[i])) drawUnique(positions) def verifyPosition(nextPos, positions): for position in positions: if nextPos == position: return False return True def main(): # congruance lineaire multiplicatif => c=0 # a = 166 # m = 49 999 is prime # r = Random(517 ,0 ,8999) #r.setSeed(5) r.testKhi2() functions = { "c":classique, "s":sansRetour, "u":passageUnique, "q":exit } while True: print("\n\n/!\ --- Pour fermer la fenetre de simulation, cliquer au milieu à la fin (ne pas fermer via la croix)") print("\nType de marche aléatoire ?") print("\tClassique (c)") print("\tSans-retour (s)") print("\tPassage unique (u)") print("\tQuitter (q)") choice = input() #choice = "5" #for testing try: functions[choice]() except KeyError: print("Veuillez choisir une entree correcte") if __name__ == "__main__": main()
PapyRedstone/SimulationSystemesTP2
main.py
main.py
py
4,702
python
en
code
0
github-code
36
73335571623
import unittest from pathlib import Path from tempfile import TemporaryDirectory import pytest from tpk.hypervalidation.hyperparameter_search import ( run_model_cmd_parallel, run_study, ) from tpk.torch import TSMixerModel @pytest.mark.asyncio async def test_num_workers() -> None: results = await run_model_cmd_parallel("echo 1", num_executions=3) assert results == [1.0, 1.0, 1.0] @pytest.mark.asyncio async def test_malformed_return_value() -> None: with unittest.TestCase().assertRaises(ValueError) as _: await run_model_cmd_parallel("echo hi", num_executions=3) @pytest.mark.slow def test_run_study() -> None: with TemporaryDirectory() as dir: study_journal_path = Path(dir) run_study( model_cls=TSMixerModel, study_journal_path=study_journal_path, data_path=Path("data/m5"), study_name="test_study", n_trials=1, tests_per_trial=1, ) assert (study_journal_path / "journal.log").exists()
airtai/temporal-data-kit
tests/hypervalidation/test_hyperparameter_search.py
test_hyperparameter_search.py
py
1,039
python
en
code
2
github-code
36
19475555146
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.shortcuts import render, HttpResponse, redirect, get_object_or_404 from django.core.paginator import Paginator from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.http import JsonResponse, HttpResponseRedirect from .models import * import json import math from django.db.models import Q, Max, Min # Create your views here. def myAbout(me): try: about = About.objects.get(user=me) except : about = About.objects.create(user=me) return about @login_required(login_url='/accounts/login/') def home(request): allposts = Post.objects.all().order_by('-id') paginator = Paginator(allposts, 2) page_number = request.GET.get('page') post = paginator.get_page(page_number) aboutMe = myAbout(request.user) followingUserId = [] followingUser = aboutMe.following.all() for i in followingUser: followingUserId.append(i.id) randomUser = User.objects.all().exclude(id__in = followingUserId).exclude(id=request.user.id).order_by('?')[:5] #randomUser = list(randomUser.values()) randomUserList = [] for i in randomUser: l = {} l['id'] = i.id l['username'] = i.username aboutUser = myAbout(i) l['profilePicture'] = aboutUser.profilePicture.url randomFollower = aboutUser.followed_by.all().order_by('?').first() if request.user in aboutUser.following.all(): l['randomFollower'] = 'Follows you' elif randomFollower == None: l['randomFollower'] = 'New to Instagram' else: l['randomFollower'] = randomFollower.username randomUserList.append(l) storiesIdList = [] stories = Post.objects.all().order_by('?')[:7] for i in stories: aboutUser = About.objects.get(user=i.user).profilePicture i.userProfilePicture = aboutUser storiesIdList.append(i.id) return render(request, 'home.html', { 'home': True, 'post': post, 'aboutMe': aboutMe, 'randomUser': randomUserList, 'stories': stories, 'storiesIdList': storiesIdList, }) @login_required(login_url='/accounts/login/') def getMorePost(request): data = json.loads(request.body.decode("utf-8")) if request.method == 'POST': postId = data['postId'] post2 = Post.objects.exclude(id__in=postId).order_by('?')[:3]#[(page_number-1)*2:page_number*2] # for i in post2: # print(i.image.url) post = list(post2.values()) for i in post: user = User.objects.get(id=i['user_id']) i['userId'] = user.id i['userfullname'] = user.first_name+' '+user.last_name aboutUser = myAbout(user) i['userProfilePricture'] = aboutUser.profilePicture.url postt = Post.objects.get(id=i['id']) i['image'] = postt.image.url i['totallikes'] = postt.liked_by.count() if request.user in postt.liked_by.all(): i['isLiked'] = True else: i['isLiked'] = False comments = Comment.objects.filter(post=postt)[:2] comments2 = list(comments.values()) for ii in comments2: userfullname2 = User.objects.get(id=ii['user_id']).first_name ii['userfullname'] = userfullname2 i['comments'] = comments2 i['totalComments'] = Comment.objects.filter(post=postt).count() return JsonResponse({'response': post}) @login_required(login_url='/accounts/login/') def getMoreComments(request, pk): post = get_object_or_404(Post, pk=pk) page = json.loads(request.body.decode("utf-8"))['page'] page = int(page) - 1 comments = Comment.objects.filter(post=post)[5*page+2:5*(page+1)+2] comments2 = list(comments.values()) for ii in comments2: userfullname2 = User.objects.get(id=ii['user_id']).first_name ii['userfullname'] = userfullname2 return JsonResponse({'response': comments2}) @login_required(login_url='/accounts/login/') def likePost(request, pk): user = request.user try: post = get_object_or_404(Post, pk=pk) post.liked_by.add(user) if not Notification.objects.filter(user1=post.user, user2=user, topic='like', post=post).exists(): Notification.objects.create(user1=post.user, user2=user, topic='like', post=post) return JsonResponse({'response': 'liked'}) except: return JsonResponse({'response': '404'}) @login_required(login_url='/accounts/login/') def cancelLikePost(request, pk): user = request.user try: post = get_object_or_404(Post, pk=pk) post.liked_by.remove(user) if Notification.objects.filter(user1=post.user, user2=user, topic='like', post=post).exists(): Notification.objects.filter(user1=post.user, user2=user, topic='like', post=post).delete() return JsonResponse({'response': 'likeCanceled'}) except: return JsonResponse({'response': '404'}) @login_required(login_url='/accounts/login/') def addComment(request, pk): user = request.user post = get_object_or_404(Post, pk=pk) data = json.loads(request.body.decode("utf-8")) Comment.objects.create(user=user, post=post, body=data['body']) #create notification if not Notification.objects.filter(user1=post.user, user2=user, topic='comment', post=post).exists(): Notification.objects.create(user1=post.user, user2=user, topic='comment', post=post) return JsonResponse({'response': 'ok'}) @login_required(login_url='/accounts/login/') def message(request): me = request.user myAllMsg = Message.objects.filter(Q(sender = me)|Q(receiver = me)).order_by('-date') conversationList = [] for lastMsg in myAllMsg: if lastMsg.sender == me: if lastMsg.receiver not in conversationList: conversationList.append(lastMsg.receiver) else: if lastMsg.sender not in conversationList: conversationList.append(lastMsg.sender) conversationList2 = [] for i in conversationList: l = {} l['id'] = i.id l['username'] = i.username lm = Message.objects.filter(Q(sender = me, receiver = i)|Q(receiver = me, sender = i)).last() try: lmb = lm.body if len(lmb) > 50: lmb = lmb[:50] + '...' except: lmb = 'Sent an Image' l['lm'] = lmb user = User.objects.get(id = i.id) aboutUser = myAbout(user) l['profilePicture'] = aboutUser.profilePicture.url conversationList2.append(l) try: myChatList = About.objects.get(user=me) except: myChatList = About.objects.create(user=me) for i in myChatList.chatList.all(): if i not in conversationList: l = {} l['id'] = i.id l['username'] = i.username l['lm'] = 'Active 1 hour ago' user = User.objects.get(id = i.id) aboutUser = myAbout(user) l['profilePicture'] = aboutUser.profilePicture.url conversationList2.append(l) aboutMe = myAbout(request.user) return render(request, 'message.html', { 'message': True, 'conversationList': conversationList2, 'aboutMe': aboutMe, }) @login_required(login_url='/accounts/login/') def conversation(request, pk): page = json.loads(request.body.decode("utf-8"))['pageNo'] user1 = request.user.id user2 = User.objects.get(id=pk).id msg = Message.objects.filter(Q(receiver = user1, sender = user2)|Q(sender = user1, receiver = user2)).order_by('-date')[(page-1)*10:page*10]#.reverse() moreMessage = True if msg.count() == 0: moreMessage = False messages = list(msg.values()) return JsonResponse({'messages': messages, 'moreMessage': moreMessage}) @login_required(login_url='/accounts/login/') def sendMessage(request): sender = request.user try: data = json.loads(request.body.decode("utf-8")) receiverId = data['receiver'] receiver = User.objects.get(id=receiverId) body = data['body'] Message.objects.create(sender=sender, receiver=receiver, body=body) return JsonResponse({'response': 'sent'}) except: image = request.FILES.get('image') receiverId = request.POST.get('receiver') receiver = User.objects.get(id=receiverId) Message.objects.create(sender=sender, receiver=receiver, image=image) return JsonResponse({'response': 'sent'}) @login_required(login_url='/accounts/login/') def sendMessageFromStories(request): data = json.loads(request.body.decode("utf-8")) post = data['postId'] receiver = Post.objects.get(id=post).user #receiver = User.objects.get(id=receiverId) body = data['body'] sender = request.user Message.objects.create(sender=sender, receiver=receiver, body=body) return JsonResponse({'response': 'sent'}) @login_required(login_url='/accounts/login/') def explore(request): posts = Post.objects.all().order_by('?')[:12] for i in posts: i.totalLikes = i.liked_by.all().count() i.totalComments = Comment.objects.filter(post=i.id).count() try: data = json.loads(request.body.decode("utf-8"))['exploreItemId'] posts2 = Post.objects.all().exclude(id__in = data).order_by('?')[:12] noMoreExplorePost = False posts3 = list(posts2.values()) countPost = posts2.count() if countPost < 12: needMore = 12-countPost morePosts = Post.objects.all().order_by('?')[:needMore] posts3.append(list(morePosts.values())[0]) noMoreExplorePost = True for i in posts3: p = Post.objects.get(id=i['id']) i['totalLikes'] = p.liked_by.all().count() i['totalComments'] = Comment.objects.filter(post=p.id).count() i['image'] = p.image.url return JsonResponse({'posts': posts3, 'noMoreExplorePost': noMoreExplorePost}) except: pass # allPosts = list(posts.values()) # for i in allPosts: # comments = Comment.objects.filter(post = i['id']).count() # totalLikes = Post.objects.get(id=i['id']).liked_by.all().count() # i['totalLikes'] = totalLikes # i['totalComments'] = comments aboutMe = myAbout(request.user) return render(request, 'explore.html', { 'explore': True, 'posts': posts, 'aboutMe': aboutMe, }) @login_required(login_url='/accounts/login/') def exploreMore(request, pk): post = Post.objects.get(id=pk) post.totalLikes = post.liked_by.all().count() post.totalComments = Comment.objects.filter(post=pk).count() userAbout = myAbout(post.user) post.userProfilePicture = userAbout.profilePicture.url post.userId = post.user.id try: post.firstComment = Comment.objects.filter(post=pk)[:1][0] except : post.firstComment = False try: post.secondComment = Comment.objects.filter(post=pk)[1:2][0] except : post.secondComment = False #print(post.secondComment.values()) aboutMe = myAbout(request.user) followingUserId = [] followingUser = aboutMe.following.all() for i in followingUser: followingUserId.append(i.id) randomUser = User.objects.all().exclude(id__in = followingUserId).exclude(id=request.user.id).order_by('?')[:5] #randomUser = list(randomUser.values()) randomUserList = [] for i in randomUser: l = {} l['id'] = i.id l['username'] = i.username aboutUser = myAbout(i) l['profilePicture'] = aboutUser.profilePicture.url randomFollower = aboutUser.followed_by.all().order_by('?').first() if request.user in aboutUser.following.all(): l['randomFollower'] = 'Follows you' elif randomFollower == None: l['randomFollower'] = 'New to Instagram' else: l['randomFollower'] = randomFollower.username randomUserList.append(l) return render(request, 'exploremore.html', { 'p': post, 'aboutMe': aboutMe, 'randomUser': randomUserList, 'exploreMore': True, }) @login_required(login_url='/accounts/login/') def profile(request, pk): #myUsername = request.user.username user = User.objects.get(id=pk) aboutUser = myAbout(user) userPosts = Post.objects.filter(user=user).order_by('-date') # for i in userPosts: # i.image = i.image.url # i.totalLikes = i.liked_by.all().count() # print(i.liked_by.all().count()) # i.totalComments = Comment.objects.filter(post=i.id).count() # print(i.totalLikes) # print(userPosts.values()) posts = [] zero = 0 zero2 = 0 lenOfPosts = len(userPosts) userPosts = userPosts.values() isFollowing = False if request.user in aboutUser.followed_by.all(): isFollowing = True subListLen = math.ceil(lenOfPosts/3) while zero < subListLen: subList = [] while len(subList) < 3: try: subList.append(userPosts[zero2]) zero2 += 1 except : break posts.append(subList) zero += 1 for i in posts: for j in i: post = Post.objects.get(id=j['id']) j['image'] = post.image.url j['totalLikes'] = post.liked_by.all().count() j['totalComments'] = Comment.objects.filter(post=post).count() aboutMe = myAbout(request.user) totalPosts = Post.objects.filter(user=user).count() return render(request, 'profile.html',{ 'aboutMe': aboutMe, 'user': user, 'aboutUser': aboutUser, 'userPosts': posts, 'totalPosts': totalPosts, 'isFollowing': isFollowing, }) @login_required(login_url='/accounts/login/') def userPosts(request, pk): post = Post.objects.get(id=pk) post.totalLikes = post.liked_by.all().count() post.totalComments = Comment.objects.filter(post=pk).count() userAbout = myAbout(post.user) post.userProfilePicture = userAbout.profilePicture.url try: post.firstComment = Comment.objects.filter(post=pk)[:1][0] except : post.firstComment = False try: post.secondComment = Comment.objects.filter(post=pk)[1:2][0] except : post.secondComment = False #print(post.secondComment.values()) aboutMe = myAbout(request.user) followingUserId = [] followingUser = aboutMe.following.all() for i in followingUser: followingUserId.append(i.id) randomUser = User.objects.all().exclude(id__in = followingUserId).exclude(id=request.user.id).order_by('?')[:5] #randomUser = list(randomUser.values()) randomUserList = [] for i in randomUser: l = {} l['id'] = i.id l['username'] = i.username aboutUser = myAbout(i) l['profilePicture'] = aboutUser.profilePicture.url randomFollower = aboutUser.followed_by.all().order_by('?').first() if request.user in aboutUser.following.all(): l['randomFollower'] = 'Follows you' elif randomFollower == None: l['randomFollower'] = 'New to Instagram' else: l['randomFollower'] = randomFollower.username randomUserList.append(l) return render(request, 'userposts.html', { 'p': post, 'aboutMe': aboutMe, 'randomUser': randomUserList, 'exploreMore': True, }) @login_required(login_url='/accounts/login/') def getMoreUserPost(request): data = json.loads(request.body.decode("utf-8")) if request.method == 'POST': postId = data['postId'] post2 = Post.objects.filter(id__lt = postId[0], user = Post.objects.get(id=postId[0]).user).exclude(id__in=postId).order_by('-date')[:2]#[(page_number-1)*2:page_number*2] # for i in post2: # print(i.image.url) post = list(post2.values()) for i in post: user = User.objects.get(id=i['user_id']) i['userfullname'] = user.first_name+' '+user.last_name i['userId'] = user.id aboutUser = myAbout(user) i['userProfilePricture'] = aboutUser.profilePicture.url postt = Post.objects.get(id=i['id']) i['image'] = postt.image.url i['totallikes'] = postt.liked_by.count() if request.user in postt.liked_by.all(): i['isLiked'] = True else: i['isLiked'] = False comments = Comment.objects.filter(post=postt)[:2] comments2 = list(comments.values()) for ii in comments2: userfullname2 = User.objects.get(id=ii['user_id']).first_name ii['userfullname'] = userfullname2 i['comments'] = comments2 i['totalComments'] = Comment.objects.filter(post=postt).count() return JsonResponse({'response': post}) @login_required(login_url='/accounts/login/') def editProfile(request): aboutMe = myAbout(request.user) if request.method == 'POST': try: profilePicture = request.FILES['pp'] if request.user.about: currentPP = request.user.about.profilePicture if not currentPP.url == '/media/images/useravater.png': currentPP.delete(save=True) request.user.about.profilePicture=profilePicture request.user.about.save() except : pass username = request.POST['username'] if User.objects.filter(username=username).exists() and username != request.user.username: messages.error(request, 'This Username is already taken') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) if ' ' in username or len(username) < 1: messages.error(request, 'Invalid username') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) fullname = request.POST['fullName'] website = request.POST['website'] bio = request.POST['bio'] email = request.POST['email'] try: User.objects.filter(id=request.user.id).update(username=username, first_name = fullname, email=email) About.objects.filter(user=request.user).update(website=website, bio=bio) messages.success(request, 'Profile updated successfully.') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) except : messages.error(request, 'Can\'t update your profile') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return render(request, 'editprofile.html',{ 'aboutMe': aboutMe, }) @login_required(login_url='/accounts/login/') def uploadPhoto(request): #myUsername = request.user.username aboutMe = myAbout(request.user) return render(request, 'uploadphoto.html',{'aboutMe': aboutMe}) @login_required(login_url='/accounts/login/') def photoUploadHandler(request): user = request.user if request.method == 'POST': img = request.FILES['photo'] caption = request.POST['caption'] Post.objects.create(user=user, image=img, caption = caption) return redirect('/profile/'+str(request.user.id)) @login_required(login_url='/accounts/login/') def follow(request, pk): me = request.user user = User.objects.get(id=pk) aboutMe = myAbout(me) aboutUser = myAbout(user) aboutMe.following.add(user) aboutMe.chatList.add(user) aboutUser.followed_by.add(me) aboutUser.chatList.add(me) # Creating Notification if not Notification.objects.filter(user1 = user, user2=me, topic = 'follow').exists(): Notification.objects.create(user1 = user, user2=me, topic = 'follow') return JsonResponse({'response': 'ok'}) @login_required(login_url='/accounts/login/') def unfollow(request, pk): me = request.user user = User.objects.get(id=pk) aboutMe = myAbout(me) aboutUser = myAbout(user) aboutMe.following.remove(user) aboutMe.chatList.remove(user) aboutUser.followed_by.remove(me) aboutUser.chatList.remove(me) # deleting notification if Notification.objects.filter(user1 = user, user2=me, topic = 'follow').exists(): Notification.objects.filter(user1 = user, user2=me, topic = 'follow').delete() return JsonResponse({'response': 'ok'}) @login_required(login_url='/accounts/login/') def getNotifications(request): user1 = request.user n = Notification.objects.filter(user1=user1).order_by('-date')[:10] n = list(n.values()) for i in n: i['profilePicture'] = myAbout(User.objects.get(id=i['user2_id'])).profilePicture.url i['who'] = User.objects.get(id=i['user2_id']).username return JsonResponse({'response': n}) @login_required(login_url='/accounts/login/') def searchUser(request): name = json.loads(request.body.decode("utf-8"))['name'] users = User.objects.filter(Q(username__icontains = name) | Q(first_name__icontains = name))#.filter(first_name__icontains = name) users = list(users.values()) for i in users: del i['password'] del i['email'] del i['last_login'] del i['date_joined'] i['profilePicture'] = myAbout(User.objects.get(id=i['id'])).profilePicture.url return JsonResponse({'response': users}) def handleSignup(request): data = json.loads(request.body.decode("utf-8")) if request.method == 'POST': username = data['username'] email = data['email'] pass1 = data['pass1'] pass2 = data['pass2'] if len(username) < 1: return JsonResponse({'response':'Username can\'t be empty.'}) if ' ' in username: return JsonResponse({'response':'Username must contain letters, digits and @/./+/-/_ only.'}) if pass1!=pass2: return JsonResponse({'response':'The two password field didn\'t match.'}) if User.objects.filter(username=username).exists(): return JsonResponse({'response':'This username is already taken. Please try another one.'}) if len(pass1) < 4: return JsonResponse({'response':'Your password must contain at least 4 characters.'}) try: myuser = User.objects.create_user(username, email, pass1) myuser.first_name = data['fullname'] myuser.save() #messages.success(request, 'Your account created successfully.') except: return JsonResponse({'response':'Username must contain letters, digits and @/./+/-/_ only.'}) user = authenticate(username=username, password=pass1) if user is not None: login(request, user) #messages.success(request, 'You are Logged in.') return JsonResponse({'response':'ok'}) else: return HttpResponse('404 - Page Not Found') def handleLogin(request): data = json.loads(request.body.decode("utf-8")) if request.method == 'POST': username = data['username'] password = data['pass'] user = authenticate(username=username, password=password) if user is not None: login(request, user) #messages.success(request, 'You are now Logged in.') return JsonResponse({'response': 'ok'}) else: return JsonResponse({'response': 'Invalid username or password, please try again'}) else: return HttpResponse('404 - Page Not Found') def handleLogout(request): logout(request) #messages.warning(request, 'You are Logged out.') #return JsonResponse({'response': 'ok'}) return redirect(request.META['HTTP_REFERER'])
Asif-Biswas/instagram-clone
instagram2/views.py
views.py
py
24,038
python
en
code
1
github-code
36
72791854185
""" Tags: Arrays Pattern: Two-pointers Notes: We're making use of the two-pointer pattern and overwriting (swapping). - We use two pointers to swap the zeros with non-zero numbers, hence gradually pushing the zeros towards the end of the array. - The right pointer traverses the array without stopping, when it gets to an value equal to 0, it sets the left pointer to that position. - As the right pointer moves on, if it encoounters a number not equal to zero, we swap the values of the two pointers and increment the left pointer by one. - """ class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ negInf = float("-inf") left = negInf for right, num in enumerate(nums): if left == negInf and num == 0: left = right elif num != 0 and left != negInf: nums[right], nums[left] = nums[left], nums[right] left +=1
cs50victor/dsa
leetcode/283-move-zeroes.py
283-move-zeroes.py
py
1,045
python
en
code
0
github-code
36
21135616107
import subprocess, os, urllib, platform def get_value(input_data, key, default=False): """ Lấy giá trị key trong input_data. Nếu không có thì sẽ trả về: - False nếu không có default - default nếu có default """ try: return input_data[key] except: return default if default else False def remove_chars(input_string, chars_need_remove): # Loại bỏ các ký tự của chars_need_remove trong input_string result = "" for char in input_string: if char not in chars_need_remove: result += char return result def clear_file_name(file_name): # Loại bỏ các ký tự đặc biệt trong tên file invalid_chars = r"<>:\"/\|?*" new_name = remove_chars(file_name, invalid_chars) new_name = new_name.replace("\t", " ") return new_name def open_folder(folder_path): if os.path.exists(folder_path): system_platform = platform.system().lower() if system_platform == "darwin": # macOS subprocess.Popen(["open", folder_path]) elif system_platform == "windows": # Windows subprocess.Popen(["explorer", folder_path], shell=True) else: print(f"Hệ điều hành '{system_platform}' không được hỗ trợ.") else: print(f"Thư mục '{folder_path}' không tồn tại.") def save_file(url_file, folder_path, fle_name): # Lưu file về và mở folder_path urllib.request.urlretrieve( url_file, os.path.join(folder_path, fle_name), ) def get_path_full(sub_path): return os.path.join(os.path.join(os.path.dirname(__file__), "..", ""), sub_path)
nguyenxuanhoa493/LMS
API/until.py
until.py
py
1,775
python
vi
code
0
github-code
36
70323989225
#Menggambar graf dengan 8 nodes import matplotlib import networkx as nx import itertools G = nx.Graph() #Menambah node L = ['a','b','c','d','e','f','g','h'] G.add_nodes_from(L) ''' Kak ini kenapa nodesnya selalu kerandom ya? :( ''' #Menambah edge pairs = itertools.combinations(L,2) edges = list() for pair in pairs: edges.append(pair) for edge in edges: G.add_edge(*edge) #Menampilkan gambar nx.draw_circular(G, with_labels = True, edge_color='b') matplotlib.pyplot.show()
dionesiusap/matplotlib-networkx-example
graph.py
graph.py
py
515
python
en
code
0
github-code
36
24593161716
def summ(x, y): result = (x+y) return result # a = summ(15, 33) # print(a) def revers(lstr): revl = [] for element in lstr: element = element[::-1] revl.append(element) return revl # b = revers(["i want to become a python developer", "it will be hard", "i am learning"]) # print(b) def char(lstr): new_list = [] for element in lstr: if len(element) > 5: new_list.append(element) return new_list # c = char(["i want to become a python developer", "name", "it will be hard", "i am learning", "world", "world1"]) # print(c) def string_reg(string): up = 0 low = 0 for element in string: if element.isupper(): up += 1 elif element.islower(): low += 1 return low, up # d, e = string_reg("I Want To Become A Python Developer!!!") # print(d, e) def get_ranges(string): k = "" while len(string) > 1: if string[0] + 1 == string[1]: if len(k) == 0: k = k + str(string[0]) + "-" if len(k) != 0 and k[-1] == ",": k = k + str(string[0]) + "-" string = string[1:] else: if len(k) != 0 and k[-1] == "-": k = k + str(string[0]) + "," string = string[1:] else: k = k + str(string[0]) + "," string = string[1:] k = k + str(string[-1]) return k # f = get_ranges([-11, 2, 3, 6, 7, 8, 9]) # g = get_ranges([1, 2, 3, 6, 7, 8, 9, 11]) # h = get_ranges([1, 3, 6, 7, 8, 9, 10]) # j = get_ranges([-10, -7, -1]) # # print(f, type(f)) # print(g, type(g)) # print(h, type(h)) # print(j, type(j))
MikitaTsiarentsyeu/Md-PT1-69-23
Tasks/Stansky/Task5/Task 5.py
Task 5.py
py
1,708
python
en
code
0
github-code
36
23210851418
from config import Config import requests, json from app.models import news_article, news_source MOVIE_API_KEY = Config.API_KEY News_Article = news_article.Article News_Source = news_source.Source def configure_request(app): global api_key api_key = app.config['API_KEY'] def get_news(): request = requests.get('https://newsapi.org/v2/everything?q=all&apiKey={}' .format(MOVIE_API_KEY)) response = json.loads(request.content) news = [] for new in response['articles']: new = News_Article(new['source'], new['author'], new['title'], new['description'], new['urlToImage'], new['url'], new['publishedAt']) news.append(new) return news def get_news_sources(): request = requests.get('https://newsapi.org/v2/top-headlines/sources?apiKey={}' .format(MOVIE_API_KEY)) response = json.loads(request.content) news_sources = [] for source in response['sources']: source = News_Source(source['id'], source['name']) news_sources.append(source) return news_sources def get_news_from_source(source): request = requests.get('https://newsapi.org/v2/everything?q={}&apiKey={}'.format(source, MOVIE_API_KEY)) response = json.loads(request.content) news = [] for new in response['articles']: new = News_Article(new['source'], new['author'], new['title'], new['description'], new['urlToImage'], new['url'], new['publishedAt']) news.append(new) return news
Joshua-Barawa/news-app
app/requests.py
requests.py
py
1,570
python
en
code
1
github-code
36
36613114839
import os import enum # Folder projet interphone LOG_DIR = "src_backend/Repport/" # Information des trace d'erreur ERROR_TRACE_FILE_PATH = os.path.join(LOG_DIR, 'Error.trace') # Information des logs pour des log général LOG_FILENAME = "APP_Window.log" #Structure du code LOG_FORMAT = "%(asctime)s [%(levelname)s] - %(message)s" # Format du journal MAX_BYTES = 1024*1024 LOG_MAX_FILES = 4 class LogLevel(enum.Enum): INFO = "INFO" DEBUG = "DEBUG" ERROR = "ERROR" # Niveau de journalisation par défaut # Remplacez "DEBUG" par le niveau de votre choix DEFAULT_LOG_LEVEL = LogLevel.DEBUG # Reset MAX_AGE_DAYS = 2 # Définissez le nombre maximal de jours pour conserver les fichiers
ClemGRob/InterPhoneVisiaScan
src_backend/constants_log.py
constants_log.py
py
745
python
fr
code
0
github-code
36
70891405863
from flask import Flask, render_template, request from transformers import VisionEncoderDecoderModel, ViTFeatureExtractor, AutoTokenizer import torch from PIL import Image import io import base64 app = Flask(__name__) model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning") feature_extractor = ViTFeatureExtractor.from_pretrained("nlpconnect/vit-gpt2-image-captioning") tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) max_length = 16 num_beams = 4 gen_kwargs = {"max_length": max_length, "num_beams": num_beams} @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': # Check if a file was uploaded if 'image' not in request.files: return render_template('index.html', error='No image uploaded') file = request.files['image'] # Check if the file has a valid extension if file.filename == '': return render_template('index.html', error='No image selected') if file and allowed_file(file.filename): # Save the uploaded image file_path = 'uploads/' + file.filename file.save(file_path) # Generate captions using the uploaded image captions = predict_step([file_path]) # Display the image using PIL image = Image.open(file_path) image_data = io.BytesIO() image.save(image_data, format='PNG') image_base64 = base64.b64encode(image_data.getvalue()).decode('utf-8') return render_template('index.html', image=image_base64, captions=captions) else: return render_template('index.html', error='Invalid file type') return render_template('index.html') def allowed_file(filename): # Add the allowed image file extensions here ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def predict_step(image_paths): images = [] for image_path in image_paths: i_image = Image.open(image_path) if i_image.mode != "RGB": i_image = i_image.convert(mode="RGB") images.append(i_image) pixel_values = feature_extractor(images=images, return_tensors="pt").pixel_values pixel_values = pixel_values.to(device) output_ids = model.generate(pixel_values, num_return_sequences=3, **gen_kwargs) preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True) preds = [pred.strip() for pred in preds] return preds if __name__ == '__main__': app.run(debug=True)
AtchayaPraba/Listed-Inc-image-captioning
app.py
app.py
py
2,759
python
en
code
0
github-code
36
12315568695
import sys import time import numpy as np from numpy import matlib from Functions import constants from Functions.FDTD_Core_Ez import FDTD_Core_Ez from Functions.FDTD_Core_H import FDTD_Core_H np.set_printoptions(threshold=sys.maxsize) def FDTD_2D(prepared, Debye_model, phantom, antennas_setup, gaussian_source): ############################ eps_s = np.zeros((prepared.Imax, prepared.Jmax)) eps_inf = np.zeros((prepared.Imax, prepared.Jmax)) sigma_s = np.zeros((prepared.Imax, prepared.Jmax)) ############################ ############################ k = 0 for i in prepared.XBB: l = 0 for j in prepared.YBB: eps_inf[i, j] = Debye_model.Debye_Eps_Inf[k, l] eps_s[i, j] = Debye_model.Debye_Eps_Inf[k, l] + Debye_model.Debye_Eps_Delta[k, l] sigma_s[i, j] = Debye_model.Debye_Sigma_s[k, l] l = l + 1 k = k + 1 ############################ # Material Settings # # To the area that matches pml material we set dielectric properties of air, ############################ X_pml_min = min(prepared.XBB) X_pml_max = max(prepared.XBB) + 1 Y_pml_min = min(prepared.YBB) Y_pml_max = max(prepared.YBB) + 1 ############################ # Epsilon - Infinity # pml_area # Corners(Left and Up, Right and Down, Right and Up, Left and Down) #########-------------------######### #########-------------------######### #########-------------------######### #########-------------------######### # ------------------------------------- # ------------------------------------- # ------------------------------------- # ------------------------------------- #########-------------------######### #########-------------------######### #########-------------------######### #########-------------------######### eps_inf[0:X_pml_min, 0:Y_pml_min] = Debye_model.Debye_Eps_Inf[0, 0] eps_inf[X_pml_max::, Y_pml_max::] = Debye_model.Debye_Eps_Inf[-1, -1] eps_inf[0:X_pml_min, Y_pml_max::] = Debye_model.Debye_Eps_Inf[0, -1] eps_inf[X_pml_max::, 0:Y_pml_min] = Debye_model.Debye_Eps_Inf[-1, 0] # area betwwen two corners ##################################### ##################################### ##################################### ##################################### #########-------------------######### #########-------------------######### #########-------------------######### #########-------------------######### ##################################### ##################################### ##################################### ##################################### # x-direction eps_inf[prepared.XBB, 0:Y_pml_min] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Eps_Inf[:, 0], axis=1), 1, Y_pml_min) eps_inf[prepared.XBB, Y_pml_max::] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Eps_Inf[:, -1], axis=1), 1, prepared.Jmax - Y_pml_max) # y-direction eps_inf[0:X_pml_min, prepared.YBB] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Eps_Inf[0, :], axis=0), X_pml_min, 1) eps_inf[X_pml_max::, prepared.YBB] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Eps_Inf[-1, :], axis=0), prepared.Imax - X_pml_max, 1) ############################ # Epsilon - Sigma Eps_s = Debye_model.Debye_Eps_Inf + Debye_model.Debye_Eps_Delta # pml_area eps_s[0:X_pml_min, 0:Y_pml_min] = Eps_s[0, 0] eps_s[X_pml_max::, Y_pml_max::] = Eps_s[-1, -1] eps_s[0:X_pml_min, Y_pml_max::] = Eps_s[0, -1] eps_s[X_pml_max::, 0:Y_pml_min] = Eps_s[-1, 0] # x-direction eps_s[prepared.XBB, 0:Y_pml_min] = np.matlib.repmat(np.expand_dims(Eps_s[:, 0], axis=1), 1, Y_pml_min) eps_s[prepared.XBB, Y_pml_max::] = np.matlib.repmat(np.expand_dims(Eps_s[:, -1], axis=1), 1, prepared.Jmax - Y_pml_max) # y-direction eps_s[0:X_pml_min, prepared.YBB] = np.matlib.repmat(np.expand_dims(Eps_s[0, :], axis=0), X_pml_min, 1) eps_s[X_pml_max::, prepared.YBB] = np.matlib.repmat(np.expand_dims(Eps_s[-1, :], axis=0), prepared.Imax - X_pml_max, 1) ############################ # Sigma-S # pml_area sigma_s[0:X_pml_min, 0:Y_pml_min] = Debye_model.Debye_Sigma_s[0, 0] sigma_s[X_pml_max::, Y_pml_max::] = Debye_model.Debye_Sigma_s[-1, -1] sigma_s[0:X_pml_min, Y_pml_max::] = Debye_model.Debye_Sigma_s[0, -1] sigma_s[X_pml_max::, 0:Y_pml_min] = Debye_model.Debye_Sigma_s[-1, 0] # x-direction sigma_s[prepared.XBB, 0:Y_pml_min] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Sigma_s[:, 0], axis=1), 1, Y_pml_min) sigma_s[prepared.XBB, Y_pml_max::] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Sigma_s[:, -1], axis=1), 1, prepared.Jmax - Y_pml_max) # y-direction sigma_s[0:X_pml_min, prepared.YBB] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Sigma_s[0, :], axis=0), X_pml_min, 1) sigma_s[X_pml_max::, prepared.YBB] = np.matlib.repmat(np.expand_dims(Debye_model.Debye_Sigma_s[-1, :], axis=0), prepared.Imax - X_pml_max, 1) ################# # FILL IN UPDATING COEFFICIENTS ################ Kd = (2 * phantom.TauP - phantom.DeltaT) / (2 * phantom.TauP + phantom.DeltaT) Beta_d = (2 * constants.AIR_PERMITTIVITY * (eps_s - eps_inf) * phantom.DeltaT) / (2 * phantom.TauP + phantom.DeltaT) DA = 1.0 DB = (phantom.DeltaT / constants.AIR_PERMEABILITY) CA = (2 * constants.AIR_PERMITTIVITY * eps_inf - sigma_s * phantom.DeltaT + Beta_d) / ( 2 * constants.AIR_PERMITTIVITY * eps_inf + sigma_s * phantom.DeltaT + Beta_d) CA = CA[1:prepared.Imax - 1, 1:prepared.Jmax - 1] CB = 2 * phantom.DeltaT / (2 * constants.AIR_PERMITTIVITY * eps_inf + sigma_s * phantom.DeltaT + Beta_d) CB = CB[1:prepared.Imax - 1, 1: prepared.Jmax - 1] Beta_d = Beta_d[1:prepared.Imax - 1, 1: prepared.Jmax - 1] # for saving phasors inside FDTD observation bounding box numFreqs = 1 E_fields_rec_dom_mag = np.zeros((antennas_setup.NumberOfAntennas, prepared.bbSize, numFreqs)) E_fields_rec_dom_pha = np.zeros((antennas_setup.NumberOfAntennas, prepared.bbSize, numFreqs)) # for saving phasors at the antennas in FDTD antObs_data_test = np.zeros( (antennas_setup.NumberOfAntennas, antennas_setup.NumberOfAntennas, gaussian_source.timesteps)) # t_iE = [i for i in range(1,prepared.Imax)] # parameter for updating function E # t_jE = [i for i in range(1,prepared.Jmax)] # parameter for updating function E print("> Forward solver ... FDTD is running") start_timer = time.time() for antenna_source in range(antennas_setup.NumberOfAntennas): #for antenna_source in range(1): timer = time.time() ################## INITIALIZE VALUES FOR FIELDS ################## Ez = np.zeros((prepared.Imax, prepared.Jmax)) Hx = np.zeros((prepared.Imax - 1, prepared.Jmax - 1)) Hy = np.zeros((prepared.Imax - 1, prepared.Jmax - 1)) Jd = np.zeros((prepared.Imax - 2, prepared.Jmax - 2)) ################## CPML ################## psi_Ezx = np.zeros((prepared.Imax - 2, prepared.Jmax - 2)) psi_Ezy = np.zeros((prepared.Imax - 2, prepared.Jmax - 2)) psi_Hx = np.zeros((prepared.Imax - 1, prepared.Jmax - 1)) psi_Hy = np.zeros((prepared.Imax - 1, prepared.Jmax - 1)) ################## temp storage for saving data inside observation bounding box ################## temp_E_fields_imag = np.zeros((prepared.bbSize, numFreqs)) temp_E_fields_real = np.zeros((prepared.bbSize, numFreqs)) for i in range(gaussian_source.timesteps): #for i in range(7): Hx, Hy, psi_Hx, psi_Hy = FDTD_Core_H(Ez, DA, Hx, DB, psi_Hx, phantom.DeltaX, Hy, psi_Hy, prepared) Ez[1:prepared.Imax - 1, 1:prepared.Jmax - 1], Jd, psi_Ezx, psi_Ezy = FDTD_Core_Ez(Hy, Hx, CA, CB, Kd, Jd, prepared, Ez[1:prepared.Imax - 1, 1:prepared.Jmax - 1], psi_Ezx, phantom.DeltaX, psi_Ezy, Beta_d, phantom.DeltaT) ######### Source Update with pulse ######### Ez[int(antennas_setup.x_location[antenna_source]), int(antennas_setup.y_location[antenna_source])] = \ Ez[int(antennas_setup.x_location[antenna_source]), int(antennas_setup.y_location[antenna_source])] + \ gaussian_source.source[i] ######### observe field data at every obstime_ds timesteps ######### #bboxObs_data = Ez[tuple([prepared.bbox_exterior_mask_extend[0], prepared.bbox_exterior_mask_extend[1]])] for j in range(len(antennas_setup.x_location)): antObs_data_test[antenna_source, j, i] = Ez[antennas_setup.x_location[j], antennas_setup.y_location[j]] #print(antObs_data_test[antenna_source, j, i],end = ' ') # if(i==gaussian_source.timesteps-1): # print(antObs_data_test[antenna_source, j, i], end=' ') ######### Computing frequency - domain quantities by FFT ######### # temp_E_fields_imag = np.squeeze(temp_E_fields_imag) + bboxObs_data * math.sin( # 2 * math.pi * phantom.Center_Frequency * i * phantom.DeltaT) # temp_E_fields_real = np.squeeze(temp_E_fields_real) + bboxObs_data * math.cos( # 2 * math.pi * phantom.Center_Frequency * i * phantom.DeltaT) print("Antenna N.", antenna_source + 1, " runtime: ", time.time() - timer, " seconds") ######## convert observations to phasors and normalize by source ######## # temp_E_fields_imag = temp_E_fields_imag / (gaussian_source.timesteps / 2) # temp_E_fields_real = temp_E_fields_real / (gaussian_source.timesteps / 2) # # E_fields_rec_dom_mag[antenna_source, :, :] = np.expand_dims( # np.sqrt(np.power(temp_E_fields_imag, 2) + np.power(temp_E_fields_real, 2)), 1) / np.matlib.repmat( # gaussian_source.magnitude, prepared.bbSize, 1) # # E_fields_rec_dom_pha[antenna_source, :, :] = np.expand_dims( # -numpy.arctan2(temp_E_fields_imag, temp_E_fields_real), 1) - np.matlib.repmat(gaussian_source.phase, # prepared.bbSize, 1) # mag, pha = Fast_Fourier_Tranform(np.reshape(antObs_data_test, (antennas_setup.NumberOfAntennas ** 2, gaussian_source.timesteps)), phantom.Center_Frequency, phantom.DeltaT, gaussian_source.magnitude, gaussian_source.phase) # receivedFields_mag = np.reshape(mag, (antennas_setup.NumberOfAntennas, antennas_setup.NumberOfAntennas, numFreqs)) # receivedFields_pha = np.reshape(pha, (antennas_setup.NumberOfAntennas,antennas_setup.NumberOfAntennas, numFreqs)) print("> FDTD completed ... Total Running Time: ",time.time() - start_timer ," seconds") return antObs_data_test
philorfa/FDTD_2D
pythonProject/Functions/FDTD_2D.py
FDTD_2D.py
py
11,969
python
en
code
0
github-code
36
15589484398
import requests from lxml import etree import os '''if __name__=='__main__': try: url='https://pic.netbian.com/4kmeinv/' headers={'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'} response=requests.get(url=url,headers=headers) response.raise_for_status() response.encoding=response.apparent_encoding response_text=response.text print(response_text) except: print('网络连接异常')''' import requests from lxml import etree import os if __name__=='__main__': url='https://pic.netbian.com/4kmeinv/' headers={'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'} response=requests.get(url=url,headers=headers) #可以手动修改响应数据的编码格式 #response.encoding='gbk' page_text=response.text print(page_text) tree=etree.HTML(page_text) list_li=tree.xpath('//div[@class="slist"]//li') print(list_li) #创建一个文件夹 if not os.path.exists('./piclibs'): os.mkdir('./piclibs') for li in list_li: img_src='https://pic.netbian.com'+li.xpath('./a/img/@src')[0] img_name=li.xpath('./a/img/@alt')[0]+'.jpg' #通用处理中文乱码的方法(注意重新赋值) img_name=img_name.encode('iso-8859-1').decode('gbk') #print(img_name,img_src) #请求图片进行持久存储 img_data=requests.get(url=img_src,headers=headers).content img_path='piclibs/'+img_name with open(img_path,'wb') as fp: fp.write(img_data) print(img_name,'下载成功!')
BrotherIsHere/pythonProject
7.xpath解析案例-下载图片数据.py
7.xpath解析案例-下载图片数据.py
py
1,746
python
en
code
0
github-code
36
73739222823
# Milestone Project 2 - Blackjack Game """ In this milestone project you will be creating a Complete BlackJack Card Game in Python. Here are the requirements: You need to create a simple text-based BlackJack game The game needs to have one player versus an automated dealer. The player can stand or hit. The player must be able to pick their betting amount. You need to keep track of the player's total money. You need to alert the player of wins, losses, or busts, etc... And most importantly: You must use OOP and classes in some portion of your game. You can not just use functions in your game. Use classes to help you define the Deck and the Player's hand. To play a hand of Blackjack the following steps must be followed: 1. Create a deck of 52 cards 2. Shuffle the deck 3. Ask the Player for their bet 4. Make sure that the Player's bet does not exceed their available chips 5. Deal two cards to the Dealer and two cards to the Player 6. Show only one of the Dealer's cards, the other remains hidden 7. Show both of the Player's cards 8. Ask the Player if they wish to Hit, and take another card 9. If the Player's hand doesn't Bust (go over 21), ask if they'd like to Hit again. 10. If a Player Stands, play the Dealer's hand. The dealer will always Hit until the Dealer's value meets or exceeds 17 11. Determine the winner and adjust the Player's chips accordingly 12. Ask the Player if they'd like to play again Playing Cards A standard deck of playing cards has four suits (Hearts, Diamonds, Spades and Clubs) and thirteen ranks (2 through 10, then the face cards Jack, Queen, King and Ace) for a total of 52 cards per deck. Jacks, Queens and Kings all have a rank of 10. Aces have a rank of either 11 or 1 as needed to reach 21 without busting. As a starting point in your program, you may want to assign variables to store a list of suits, ranks, and then use a dictionary to map ranks to values. """ import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} playing = True class Card: """ A Card object really only needs two attributes: suit and rank. Consider adding a __str__ method that, when asked to print a Card, returns a string in the form "Two of Hearts" """ def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return f'{self.rank} of {self.suit}' class Deck: """ Here we might store 52 card objects in a list that can later be shuffled. First, though, we need to instantiate all 52 unique card objects and add them to our list. In addition to an __init__ method we'll want to add methods to shuffle our deck, and to deal out cards during game play. """ def __init__(self): self.deck = [] # start with an empty list for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) def __str__(self): deck_comp = '' for card in self.deck: deck_comp += '\n ' + card.__str__() return 'The deck has: ' + deck_comp def shuffle(self): random.shuffle(self.deck) def deal(self): single_card = self.deck.pop() return single_card class Hand: """ In addition to holding Card objects dealt from the Deck, the Hand class may be used to calculate the value of those cards using the values dictionary defined above. It may also need to adjust for the value of Aces when appropriate. """ def __init__(self): self.cards = [] # start with an empty list as we did in the Deck class self.value = 0 # start with zero value self.aces = 0 # add an attribute to keep track of aces def add_card(self, card): self.cards.append(card) # card passed in from Deck.deal() --> single Card(suit, rank) self.value += values[card.rank] # We use the rank of the card to call the value in the dictionary. if card.rank == 'Ace': # Track aces self.aces += 1 def adjust_for_ace(self): """ If total value is > 21 and I still have an ace, than change my ace to be a 1 instead of an 11. We use the self.aces integer number as a boolean. 0 is going to be False and 1,2,3... are going to be True. :return: """ while self.value > 21 and self.aces: self.value -= 10 # We adjust the ace. We reduce the value from 11 to 1. (11-10 = 1) self.aces -= 1 # We subtract 1 for the ace count. class Chips: """ In addition to decks of cards and hands, we need to keep track of a Player's starting chips, bets, and ongoing winnings. """ def __init__(self): self.total = 100 # This can be set to a default value or supplied by a user input self.bet = 0 def win_bet(self): self.total += self.bet def lose_bet(self): self.total -= self.bet def take_bet(chips): """ Function for taking bets. Check that a Player's bet can be covered by their available chips. :param chips: The amount of chips the player is going to bet. :return: """ while True: try: chips.bet = int(input('How many chips would you like to bet? ')) except ValueError: print('Sorry, a bet must be an integer!') else: if chips.bet > chips.total: print(f'Sorry, your bet can not exceed {chips.total}') else: break def hit(deck, hand): """ Function for taking hits. Either player can take hits until they bust. This function will be called during game play anytime a Player requests a hit, or a Dealer's hand is less than 17. We also could do: single_card = deck.deal() hand.add_card(single_card) hand.adjust_for_ace() :param deck: :param hand: :return: """ hand.add_card(deck.deal()) # Grabs a single card for the deck and added to the hand. hand.adjust_for_ace() # Checks for an ace adjustment. def hit_or_stand(deck, hand): """ Function prompting the Player to Hit or Stand. This function should accept the deck and the player's hand as arguments, and assign playing as a global variable. :param deck: :param hand: :return: """ global playing # to control an upcoming while loop while True: x = input("Would you like to hit or stand? Enter 'h' or 's' ") if x[0].lower() == 'h': hit(deck, hand) elif x[1].lower() == 's': print('Player stands. Dealer is playing.') playing = False else: print("Sorry, please enter 'h' or 's' only!") continue break def show_some(player, dealer): """ Function to display cards. When the game starts, and after each time Player takes a card, the dealer's first card is hidden and all of Player's cards are visible. :param player: :param dealer: :return: """ print("\nDEALER'S HAND:") print(' <card hidden>') print('', dealer.cards[1]) print("\nPLAYER'S HAND:", *player.cards, sep='\n ') def show_all(player, dealer): """ Function to display cards. At the end of the hand all cards are shown, and you may want to show each hand's total value. :param player: :param dealer: :return: """ print("\nDEALER'S HAND:", *dealer.cards, sep='\n ') print("DEALER'S HAND =", dealer.value) print("\nPLAYER'S HAND:", *player.cards, sep='\n ') print("PLAYER'S HAND =", player.value) def player_busts(player, dealer, chips): """ Functions to handle end of game scenarios. :param player: :param dealer: :param chips: :return: """ print('Player busts!') chips.lose_bet() def player_wins(player, dealer, chips): """ Functions to handle end of game scenarios. :param player: :param dealer: :param chips: :return: """ print('Player wins!') chips.win_bet() def dealer_busts(player, dealer, chips): """ Functions to handle end of game scenarios. :param player: :param dealer: :param chips: :return: """ print('Dealer busts!') chips.win_bet() def dealer_wins(player, dealer, chips): """ Functions to handle end of game scenarios. :param player: :param dealer: :param chips: :return: """ print('Dealer wins!') chips.lose_bet() def push(player, dealer): """ Functions to handle end of game scenarios. :param player: :param dealer: :return: """ print('Dealer and Player tie! It is a push.') while True: # Print an opening statement print('Welcome to BlackJack! Get as close to 21 as you can without going over!\n' 'Dealer hits until she reaches 17. Aces count as 1 or 11.') # Create & shuffle the deck, deal two cards to each player deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) # Set up the Player's chips player_chips = Chips() # Prompt the Player for their bet take_bet(player_chips) # Show cards (but keep one dealer card hidden) show_some(player_hand, dealer_hand) while playing: # recall this variable from our hit_or_stand function # Prompt for Player to Hit or Stand hit_or_stand(deck, player_hand) # Show cards (but keep one dealer card hidden) show_some(player_hand, dealer_hand) # If player's hand exceeds 21, run player_busts() and break out of loop if player_hand.value > 21: player_busts(player_hand, dealer_hand, player_chips) break # If Player hasn't busted, play Dealer's hand until Dealer reaches 17 if player_hand.value <= 21: while dealer_hand.value < 17: hit(deck, dealer_hand) # Show all cards show_all(player_hand, dealer_hand) # Run different winning scenarios if dealer_hand.value > 21: dealer_busts(player_hand, dealer_hand, player_chips) elif dealer_hand.value > player_hand.value: dealer_wins(player_hand, dealer_hand, player_chips) elif dealer_hand.value < player_hand.value: player_wins(player_hand, dealer_hand, player_chips) else: push(player_hand, dealer_hand) # Inform Player of their chips total print(f"Player's winnings stand at {player_chips.total}") # Ask to play again new_game = input("Would you like to play another hand?\nEnter Yes or No:") if new_game[0].lower() == 'y': playing = True continue else: print("Thank's for playing!") break break
TomasMantero/Milestone-Project-2-Blackjack-Game
milestone_project2_blackjack_game.py
milestone_project2_blackjack_game.py
py
11,595
python
en
code
0
github-code
36
25023256
import sys input = sys.stdin.readline def find(n): if n != city[n]: city[n] = find(city[n]) return city[n] return n def union(a, b): parent = find(a) child = find(b) if parent>child: parent, child = child, parent if parent != child: city[child] = parent n = int(input()) m = int(input()) city = list(range(n+1)) for i in range(1, n+1): edge = [0]+list(map(int, input().split())) for j in range(1, n+1): if edge[j]: union(i, j) trip = list(map(int, input().split())) # print(city) tmp = city[trip[0]] for i in range(1, m): if tmp != city[trip[i]]: print("NO") exit() print("YES")
kmgyu/baekJoonPractice
Graph/분리 집합/여행 가자.py
여행 가자.py
py
683
python
en
code
0
github-code
36
73498685865
class BankAccount: def __init__(self, int_rate=0.01, checking_balance=0, savings_balance=0): self.interest_rate = int_rate self.account_balance_checking = checking_balance self.account_balance_savings = savings_balance def deposit(self, acct_type, amount): if acct_type == "checking": self.account_balance_checking += amount elif acct_type == "savings": self.account_balance_savings += amount return self def withdraw(self, acct_type, amount): if acct_type == "checking": self.account_balance_checking -= amount if self.account_balance_checking < 0: print("Insufficient funds: Charging a $5 fee") self.account_balance_checking -= 5 elif acct_type == "savings": self.account_balance_savings -= amount if self.account_balance_savings < 0: print("Insufficient funds: Charging a $5 fee") self.account_balance_savings -= 5 return self def display_account_info(self, acct_type): if acct_type == "checking": print("Checking Balance: $", self.account_balance_checking) if acct_type == "savings": print("Savings Balance: $", self.account_balance_savings) return self def yield_interest(self, acct_type): if acct_type == "checking" and self.account_balance_checking > 0: self.account_balance_checking = self.account_balance_checking + (self.account_balance_checking * self.interest_rate) elif acct_type == "savings" and self.account_balance_savings > 0: self.account_balance_savings = self.account_balance_savings + (self.account_balance_savings * self.interest_rate) return self class User: def __init__(self,username,email_address,other_user): self.name = username self.email = email_address self.account = BankAccount(int_rate=0.02, checking_balance=0, savings_balance=0) self.other_user = other_user def make_deposit(self, acct_type, amount): if acct_type == "checking": self.account.deposit("checking", amount) elif acct_type == "savings": self.account.deposit("savings", amount) return self def make_withdrawal(self, acct_type, amount): if acct_type == "checking": self.account.withdraw("checking", amount) elif acct_type == "savings": self.account.withdraw("savings", amount) return self def display_user_balance(self, acct_type): if acct_type == "checking": print("user: ", self.name, self.account.display_account_info("checking")) elif acct_type == "savings": print("user: ", self.name, self.account.display_account_info("savings")) return self def transfer_money(self, acct_type, other_user_account, amount): if acct_type == "checking": self.account.withdraw("checking", amount) other_user_account.deposit("checking", amount) elif acct_type == "savings": self.account.withdraw("savings", amount) other_user_account.deposit("checking", amount) return self king = User("king jaffe joffer", "rullerofzamunda@comcast.net", "hakeem") king_account = BankAccount(0.05, 25000, 100000) print(king.name) king_account.deposit("savings", 25000).withdraw("checking", 500).withdraw("checking", 1500).withdraw("checking", 3500).display_account_info("savings").display_account_info("checking") hakeem = User("prince hakeem", "onlyjuicesandberries@yahoo.com", "king") print(hakeem.name) hakeem.make_deposit("checking", 250).make_withdrawal("checking", 50).transfer_money("savings", king_account, 100).display_user_balance("checking").display_user_balance("savings") print(king.name) king_account.display_account_info("checking")
carlamiles/users_with_bank_accounts.py
users_with_bank_accounts.py
users_with_bank_accounts.py
py
3,951
python
en
code
0
github-code
36
28231150156
#!/usr/bin/env python # -*- coding: utf-8 -*- import netCDF4 from utils import * def write_jules_overbank_props_1d(overbank_fn, overbank_maps, grid_dim_name): nco = netCDF4.Dataset(overbank_fn, 'w', format='NETCDF4') mask = LAND_FRAC > 0. nland = mask.sum() for key, value in overbank_maps.items(): overbank_maps[key] = value.transpose()[mask.transpose()] nco.createDimension(grid_dim_name, nland) var = nco.createVariable( 'logn_mean', 'f8', (grid_dim_name,), fill_value=F8_FILLVAL ) var.units = 'ln(m)' var.standard_name = 'logn_mean' var[:] = overbank_maps['logn_mean'] var = nco.createVariable( 'logn_stdev', 'f8', (grid_dim_name,), fill_value=F8_FILLVAL ) var.units = 'ln(m)' var.standard_name = 'logn_stdev' var[:] = overbank_maps['logn_stdev'] nco.close() def write_jules_overbank_props_2d(overbank_fn, overbank_maps, x_dim_name, y_dim_name): nco = netCDF4.Dataset(overbank_fn, 'w', format='NETCDF4') nco = add_lat_lon_dims_2d(nco, x_dim_name, y_dim_name) var = nco.createVariable( 'logn_mean', 'f8', (y_dim_name, x_dim_name), fill_value=F8_FILLVAL ) var.units = 'ln(m)' var.standard_name = 'logn_mean' var.grid_mapping = 'latitude_longitude' var[:] = overbank_maps['logn_mean'] var = nco.createVariable( 'logn_stdev', 'f8', (y_dim_name, x_dim_name), fill_value=F8_FILLVAL ) var.units = 'ln(m)' var.standard_name = 'logn_stdev' var.grid_mapping = 'latitude_longitude' var[:] = overbank_maps['logn_stdev'] nco.close() # def write_jules_overbank_props(overbank_fn, one_d=False): # # Read overbank properties: # logn_mean_ds = rasterio.open(os.environ['LOGN_MEAN_FN']) # logn_stdev_ds = rasterio.open(os.environ['LOGN_STDEV_FN']) # overbank_maps = {} # overbank_maps['logn_mean'] = logn_mean_ds.read(1, masked=False).squeeze() # overbank_maps['logn_stdev'] = logn_stdev_ds.read(1, masked=False).squeeze() # for var in overbank_maps.keys(): # arr = overbank_maps[var] # arr = np.ma.masked_array( # arr, # mask=np.broadcast_to( # np.logical_not(LAND_FRAC), # arr.shape # ), # dtype=np.float64, # fill_value=F8_FILLVAL # ) # overbank_maps[var] = arr # # Write netCDF: # if one_d: # write_jules_overbank_props_1d(overbank_fn, overbank_maps) # else: # write_jules_overbank_props_2d(overbank_fn, overbank_maps)
simonmoulds/jamr
src/python/write_jules_overbank_props.py
write_jules_overbank_props.py
py
2,611
python
en
code
0
github-code
36
7813600766
"""add region column for sample Create Date: 2021-04-05 17:09:26.078925 """ import enumtables # noqa: F401 import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "20210405_170924" down_revision = "20210401_211915" branch_labels = None depends_on = None def upgrade(): op.create_table( "region_types", sa.Column("item_id", sa.String(), nullable=False), sa.PrimaryKeyConstraint("item_id", name=op.f("pk_region_types")), schema="aspen", ) op.enum_insert( "region_types", [ "North America", "Oceania", "Asia", "Europe", "South America", "Africa", ], schema="aspen", ) op.add_column( "samples", sa.Column( "region", sa.String(), nullable=True, comment="This is the continent this sample was collected from.", ), schema="aspen", ) op.execute("""UPDATE aspen.samples SET region='North America'""") op.alter_column( "samples", "region", existing_type=sa.VARCHAR(), nullable=False, existing_comment="This is the continent this sample was collected from.", schema="aspen", ) op.create_foreign_key( op.f("fk_samples_region_region_types"), "samples", "region_types", ["region"], ["item_id"], source_schema="aspen", referent_schema="aspen", ) def downgrade(): op.drop_constraint( op.f("fk_samples_region_region_types"), "samples", schema="aspen", type_="foreignkey", ) op.drop_column("samples", "region", schema="aspen") op.drop_table("region_types", schema="aspen")
chanzuckerberg/czgenepi
src/backend/database_migrations/versions/20210405_170924_add_region_column_for_sample.py
20210405_170924_add_region_column_for_sample.py
py
1,818
python
en
code
11
github-code
36
37635298543
""" Reversing a list: Various methods of reversing a list : - by creating another list. - by updating the existing list. """ # Method1: using range function(iterating towards backward) property: #>> does not update the existing list L1 = [1,2,3,4] Reverselist = [] leng = len(L1)-1 for i in range(leng , -1 , -1): Reverselist.append(L1[i]) print(Reverselist) #Method2: using simple "while loop" #>> does not update the existing list L2 = [2,3,41,65] Reverselist1 = [] lengg = len(L2) -1 while lengg != -1: Reverselist1.append(L2[lengg]) lengg -=1 print(Reverselist1) #Method3 : Swapping the numbers (len(N//2)) #>> update the existing list List = [23 , 12, 11, 10 , 76] mid = len(List) // 2 initial = 0 last = -1 while (mid-1) > -1: temp = List[initial] List[initial] = List[last] List[last] = temp mid -= 1 last -=1 initial += 1 print(List) #Method4 : Using the reverse() # >> update the existing list L3 = [1 ,2,3,4] L3.reverse() print(L3) #Method5 : Using the reversed() #>> does not update the existing list. # create a reverse iterator for an existing list or sequence object. mylist = [11 ,2 , 233, 4] myreversedlist = [] for i in reversed(mylist): myreversedlist.append(i) print(myreversedlist) #or L4 = [22 , 12, 12, 123] Reversedlist = list(reversed(L4)) print(Reversedlist) #Method6 : using "slicing" concept mylist2 = [2 , 12, 4 , 15 , 16] print(mylist2[::-1]) #>>> Demerits : Reversing a list this way takes up a more memory compared to an in-place reversal # because it creates a (shallow) copy of the list. # And creating the copy requires allocating enough space to hold all of the existing elements. # The biggest downside to reversing a list with the slicing syntax is that # it uses a more advanced Python feature that some people would say is “arcane.” # “[::-1]” slicing syntax does not communicate clearly enough that it creates a reversed copy of the original list.
Anchals24/General-Basic-Programs
Reversing a list.py
Reversing a list.py
py
2,049
python
en
code
7
github-code
36
20968378807
# * 4. Задайте список из произвольных вещественных чисел, количество задаёт пользователь. # Напишите программу, которая найдёт разницу между максимальным # и минимальным значением дробной части элементов. # in # 5 # out # [5.16, 8.62, 6.57, 7.92, 9.22] # Min: 0.16, Max: 0.92. Difference: 0.76 # in # 3 # out # [9.26, 8.5, 1.14] # Min: 0.14, Max: 0.5. Difference: 0.36 import random #вызов модуля точечная аннотация k = int(input("enter amount numbers: ")) some_list = [round(random.uniform(-9.999, 10), 2) for some_list in range(k)] print(some_list) # генерирует новый список с числами от n до m # в количестве k def max_diff_min(my_list: list): num_max = num_min = (my_list[0]) % 1 for i in range(1, len(my_list)): num = round((my_list[i]) % 1, 2) if num > num_max: num_max = num elif num < num_min: num_min = num result = round(num_max - num_min, 2) print(f"Min: {num_min}, Max: {num_max}. Difference: {result}") return result max_diff_min(some_list)
Nadzeya25/Python_GB
seminar3_Python/home_work3_tester/task3_4.py
task3_4.py
py
1,320
python
ru
code
0
github-code
36
26424981939
#coding: utf-8 # # example 11.4 # import numpy as np from geothermal_md import * from matplotlib.pyplot import * from scipy.optimize import curve_fit # # donnees du probleme # gam = 0.5772157 M = np.loadtxt("..\\data\\pumping_test2.txt") t = M[:,0] # time in minutes sf = M[:,1] # drawndown in meters nt = len(sf) qo = 17 # heat transfer per metre rw = 12.2 # # # # first approach # Ti = 2.4 # m2/min Si = 0.004 rbi = 0.01 G_vect = np.vectorize(leaky_function) Si = 0.003 def s_theo(t,Tnew,Snew,rb): al = Tnew/Snew u = rw**2/(4*al*t) s = qo/(4*pi*Tnew)*G_vect(u,rb) return s # # rbi = 0.03 po = [Ti,Si,rbi] ni = 3 tn =t[ni:nt] sn = sf[ni:nt] params,resn = curve_fit(s_theo,tn,sn,po) Tn = params[0] Sn = params[1] rbn = params[2] print ('T = ',Tn,'m2/min') print('S = ',Sn) print('r/b = ',rbn) s1 = s_theo(t,Ti,Si,rbi) s2 = s_theo(t,Tn,Sn,rbn) alh = Tn/Sn u = rw**2/(4*alh*t) un = rw**2/(4*alh*tn) x = 1/u p1 = loglog(x, sf, label='Measured',color = 'black') p2 = loglog(x, s2, label='Curve fit',color = 'black', linestyle='none', marker='o') ll = legend() sizeOfFont = 14 fontProperties = {'weight' : 'bold', 'size' : sizeOfFont} a = gca() gx = xlabel('1/u') gy = ylabel('') setp(gx,'fontsize',15,'fontweight','bold') setp(gy,'fontsize',15,'fontweight','bold') setp(a,'yscale','log') setp(a,'xscale','log') nx = len(x) show()
LouisLamarche/Fundamentals-of-Geothermal-Heat-Pump-Systems
chapter11/Example11_4.py
Example11_4.py
py
1,363
python
en
code
1
github-code
36
28981485311
from tendrl.commons import flows from tendrl.monitoring_integration.flows.delete_resource_from_graphite import \ graphite_delete_utils class DeleteResourceFromGraphite(flows.BaseFlow): def run(self): super(DeleteResourceFromGraphite, self).run() integration_id = self.parameters.get("TendrlContext.integration_id") resource_name = str(self.parameters.get("Trigger.resource_name")) resource_type = str(self.parameters.get( "Trigger.resource_type")).lower() graphite_delete_utils.update_graphite( integration_id, resource_name, resource_type )
Tendrl/monitoring-integration
tendrl/monitoring_integration/flows/delete_resource_from_graphite/__init__.py
__init__.py
py
625
python
en
code
4
github-code
36