seq_id
stringlengths 7
11
| text
stringlengths 156
1.7M
| repo_name
stringlengths 7
125
| sub_path
stringlengths 4
132
| file_name
stringlengths 4
77
| file_ext
stringclasses 6
values | file_size_in_byte
int64 156
1.7M
| program_lang
stringclasses 1
value | lang
stringclasses 38
values | doc_type
stringclasses 1
value | stars
int64 0
24.2k
⌀ | dataset
stringclasses 1
value | pt
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|
30582813202
|
import random
def check(comp, user):
if comp == user:
return 0
if comp==0 and user==1:
return -1
if comp==1 and user==2:
return -1
if comp==2 and user==0:
return -1
return 1
comp = random.randint(0,2)
user = int(input("Enter 0 for Stone, 1 for Paper ad 2 for Scissor"))
print("You", user)
print("Computer", comp)
score = check(comp, user)
if score==0:
print("It is a draw")
elif score ==-1:
print("You lose")
else:
print("You win")
|
jatingupta05/StonePaperScissor
|
StonePaperScissor.py
|
StonePaperScissor.py
|
py
| 524 |
python
|
en
|
code
| 0 |
github-code
|
6
|
70082164988
|
from routersim.interface import LogicalInterface
from .messaging import FrameType
from .messaging import ICMPType, UnreachableType
from .mpls import MPLSPacket, PopStackOperation
from .observers import Event, EventType
from scapy.layers.inet import IP,ICMP,icmptypes
from copy import copy
import ipaddress
class ForwardingTable:
def __init__(self, event_manager, parent_logger):
self.fib = None
self.event_manager = event_manager
self.logger = parent_logger.getChild('forwarding')
def __str__(self):
return "Forwarding Table"
def set_fib(self, fib):
self.fib = fib
self.logger.debug("Installed new forwarding table")
def lookup_ip(self, ip_address):
as_network = ipaddress.ip_network(ip_address)
# ASSUMPTION: fib is sorted with highest prefix first
# so we should always arrive at something more specific first
# yes, this is very inefficient
if self.fib is None:
return None
for prefix in self.fib[FrameType.IPV4]:
if as_network.overlaps(prefix):
self.event_manager.observe(
Event(
EventType.FORWARDING,
self,
f"Identified forwarding entry for {ip_address}"
)
)
return [self.fib[FrameType.IPV4][prefix]]
return None
def lookup_label(self, label):
if self.fib is None:
return None
if self.fib is None or FrameType.MPLSU not in self.fib:
return None
return [self.fib[FrameType.MPLSU][str(label)]]
def print_fib(self):
print("** IPV4 FIB ***")
for prefix in self.fib[FrameType.IPV4]:
entry = self.fib[FrameType.IPV4][prefix]
print(f"{entry}")
print("")
print("** MPLS FIB ***")
for prefix in self.fib[FrameType.MPLSU]:
entry = self.fib[FrameType.MPLSU][prefix]
print(f"{entry}")
class PacketForwardingEngine():
def __init__(self, forwarding_table: ForwardingTable, router):
self.router = router
self.forwarding = forwarding_table
self.arp_cache = router.arp.cache
self.logger = router.logger.getChild("pfe")
# Intended for internal communications
def accept_frame(self, frame, dest_interface=None):
self.router.event_manager.observe(
Event(
EventType.PACKET_SEND,
self.router, f"PFE Sending {frame.type}", object=frame, target=dest_interface,
sub_type="LOCAL_SEND")
)
# parameter naming was confusing...
self.process_frame(frame, dest_interface=dest_interface, from_self=True)
def process_frame(self, frame, source_interface=None, from_self=False, dest_interface=None):
def process_ip(pdu, dest_interface=None):
if pdu.inspectable() and not from_self:
self.router.process_packet(source_interface, pdu)
return
# should be an IPPacket
potential_next_hops = self.forwarding.lookup_ip(
pdu.dst
)
if potential_next_hops is not None:
pdu.ttl -= 1
# TODO: Fire event?
hop_action = potential_next_hops[0]
self.logger.info(f"Will apply action {hop_action.action}")
if not isinstance(hop_action.action, str):
newpdu = hop_action.action.apply(pdu, self.router, self.router.event_manager)
self.logger.info(f"New pdu is {newpdu}")
if isinstance(newpdu, MPLSPacket):
hop_action.interface.phy.send(FrameType.MPLSU, newpdu)
else:
self.logger.warn("Didn't get back an MPLSPacket")
else:
if hop_action.action == 'FORWARD' or dest_interface is not None:
# TODO: If we know the dest_interface should we be blindly sending on it?
# I'm not too happy about this quite yet
# really the link between the RE and PFE is wonky
if dest_interface is None:
self.logger.debug(f"Using {potential_next_hops[0].interface} for {pdu}")
dest_interface = potential_next_hops[0].interface
self.logger.debug(f"Using {dest_interface} for {pdu} (potential NH: {potential_next_hops[0]}")
self.send_encapsulated(
potential_next_hops[0].next_hop_ip,
FrameType.IPV4,
pdu,
dest_interface
)
elif hop_action.action == 'CONTROL':
if from_self:
self.logger.error(f"Unexpectedly have frame from self we need to forward {pdu}")
raise Exception(f"Unexpectedly have frame from self we need to forward {pdu}")
self.router.process_packet(source_interface, pdu)
elif hop_action.action == 'REJECT' and source_interface is not None:
#print(f"Sending reject from {source_interface.name}:{source_interface.address().ip} to {pdu.source_ip}")
packet = IP(
dst=pdu.src,
src=source_interface.address().ip
) / ICMP(
type = ICMPType.DestinationUnreachable,
code=UnreachableType.NetworkUnreachable
) / (
pdu.dst,
pdu.src,
pdu.payload.payload # IRL its first 8 bytes
)
source_interface.send_ip(packet)
else:
self.logger.info(f"**** Have action {hop_action.action}")
else:
self.logger.warn("**** Need to issue ICMP UNREACHABLE")
pass
# send unreachable
pdu = copy(frame.pdu)
if frame.type == FrameType.IPV4:
self.logger.info("Calling process_ip")
process_ip(pdu, dest_interface)
# This means we're supposed to look at it
# special case of control plane...
elif frame.type == FrameType.ARP:
# So, dilemma: Here we PROBABLY want to make sure
# this only happens on switch interfaces?
# would is also happen on routed interfaces?
self.router.process_arp(source_interface, pdu)
# TODO: If we're switching, we also want to forward it!
elif frame.type == FrameType.CLNS:
self.router.process['isis'].process_pdu(source_interface, frame.pdu)
elif frame.type == FrameType.MPLSU:
# pdu should be an MPLSPacket
potential_next_hops = None
try:
potential_next_hops = self.forwarding.lookup_label(
pdu.label_stack[len(pdu.label_stack)-1]
)
except:
if pdu.label_stack[0] == '3':
newpdu = PopStackOperation().apply(pdu, self.router, event_manager=self.router.event_manager)
if isinstance(newpdu, IP):
process_ip(newpdu)
return
self.logger.warn(f"Unable to find {pdu.label_stack[0]}")
if potential_next_hops is not None:
fibentry = potential_next_hops[0]
newpdu = fibentry.action.apply(pdu,
self.router,
event_manager=self.router.event_manager)
if isinstance(newpdu, MPLSPacket):
fibentry.interface.parent.send(
FrameType.MPLSU, newpdu, logical=None)
elif isinstance(newpdu, IP):
fibentry.interface.send_ip(newpdu)
else:
print(f"Unknown de-encapsulated packet type!")
else:
self.logger.error(f"**** No action found for label {pdu.label_stack[0]}")
def send_encapsulated(self,
next_hop: ipaddress.IPv4Address,
type: FrameType,
packet,
interface: LogicalInterface):
if next_hop is None:
dest_ip = packet.dst
dest_ip_as_net = ipaddress.ip_network(f"{dest_ip}/32")
if interface.address().network.overlaps(dest_ip_as_net):
next_hop = dest_ip
else:
raise Exception("Valid IP is required")
hw_address = self.arp_cache[next_hop]
if hw_address is None:
# TODO: Drop it?
self.router.arp.request(next_hop, interface)
else:
interface.send(hw_address, type, packet)
|
jdewald/router-sim
|
routersim/forwarding.py
|
forwarding.py
|
py
| 9,267 |
python
|
en
|
code
| 5 |
github-code
|
6
|
38573517447
|
from brian2 import *
import math
import queue
numberGC = 10
defaultclock.dt = 0.01*second
gT = 0 # target gain. Should vary a bit depexnding on day of training.
pT = 0 # target phase shift.
unitlessErrorDelay = 0 # set the delay here so that the file prints right
errorDelay = unitlessErrorDelay*second
if errorDelay != 0:
delayQueue = queue.Queue(maxsize = int(errorDelay/defaultclock.dt))
startMVN = 1
for i in range(0,int(errorDelay/defaultclock.dt)):
delayQueue.put(startMVN) # fill the queue with initial values
Vdelayed = delayQueue.get() # get one of them, open
TauPG = 15*60*second
w = 0.6*(1/second) # rate at which the platform rotates.
vCF = 0
FiftyMinutesInTimeSteps = int(((second)/defaultclock.dt)*60*50)
## make the neuron groups
MF = NeuronGroup(1,'M = cos(t*w) : 1') # Cosine Function for the mossy fibers
GC = NeuronGroup(numberGC,model = '''G = cos((t*w) + x) : 1
x : 1''') # Some phase delays of the above function
for i in range(0, numberGC):
GC.x[i] = (i/numberGC)*math.pi*2 # makes it so that the delays are distributed evenly
PC = NeuronGroup(1,model = '''P : 1
V : 1''') # The functions are defined by the synapses later. P is the purkinje cell activity, V is MVN activity, which is sent back so that it cen be used for the weight calculation.
MVN = NeuronGroup(1,model = '''M : 1
P : 1
V = M - P : 1''')
## make the synapses
# Spg = Synapses(GC,PC,model='''P_post = Wpg*G_pre : 1 (summed)
# Wpg = x_pre : 1''')
if (errorDelay == 0):
Spg = Synapses(GC,PC,method='euler',model='''P_post = Wpg*G_pre : 1 (summed)
dWpg/dt = ((V_post - gT*cos(w*(t + pT)))*G_pre)/TauPG : 1/second''') # sums granule cell activity into the purkinje cell, as weights are applied.
else:
Spg = Synapses(GC,PC,method='euler',model='''P_post = Wpg*G_pre : 1 (summed)
dWpg/dt = ((Vdelayed - gT*cos(w*(t - errorDelay + pT)))*G_pre)/TauPG : 1/second''') # sums granule cell activity into the purkinje cell, as weights are applied. # Vpast[int(t/(defaultclock.dt*second))] -
Smv = Synapses(MF,MVN, model='''M_post = M_pre : 1 (summed)''') ## I made them summed because that makes it work.
Spv = Synapses(PC,MVN, model='''P_post = P_pre : 1 (summed)
V_pre = V_post : 1 (summed)''') ## I made them summed because that makes it work.
## connect the synapses
Spg.connect()
Smv.connect()
Spv.connect()
## create the state monitors
# You can flag these on or off to see the graphs they produce.
MF_state = StateMonitor(MF,'M',record=0)
#GC_state = StateMonitor(GC,'G',record=True)
Weight_state = StateMonitor(Spg,'Wpg',record=True)
PC_state = StateMonitor(PC,'P',record=0)
MVN_state = StateMonitor(MVN,'V',record=0)
## run the model
# They are set up like this to immitate the paradigm for the paper.
if errorDelay != 0:
for i in range(0,FiftyMinutesInTimeSteps):
run(defaultclock.dt)
#print(MVN_state.V[0])
#print(list(MVN_state.V[0])[-1])
Vpast = delayQueue.put(list(MVN_state.V[0])[-1])
Vdelayed = delayQueue.get()
#print(Vdelayed)
gT = -0.5
print("report")
for i in range(0,FiftyMinutesInTimeSteps):
run(defaultclock.dt)
Vpast = delayQueue.put(list(MVN_state.V[0])[-1])
Vdelayed = delayQueue.get()
gT = -1
print("report")
for i in range(0,FiftyMinutesInTimeSteps*2):
run(defaultclock.dt)
Vpast = delayQueue.put(list(MVN_state.V[0])[-1])
Vdelayed = delayQueue.get()
else:
run(FiftyMinutesInTimeSteps*second)
gT = -0.5
run(FiftyMinutesInTimeSteps*second)
gT = -1
run(FiftyMinutesInTimeSteps*2*second)
# gT = -0.5
#
# for i in range(0,5):
# run(0.1*second)
# gT = -1
#
# for i in range(0,10):
# run(0.1*second)
## plot results
if 'MF_state' in locals():
figure()
subplot(211)
plot(MF_state.t/ms,MF_state.M[0])
if 'GC_state' in locals():
for i in range(0, numberGC):
figure()
subplot(211)
plot(GC_state.t/ms,GC_state.G[i])
if 'Weight_state' in locals():
for i in range(0, numberGC):
figure()
# subplot(211)
plot(Weight_state.t/ms,Weight_state.Wpg[i])
if 'PC_state' in locals():
figure()
subplot(211)
plot(PC_state.t/ms,PC_state.P[0])
if 'MVN_state' in locals():
figure()
subplot(211)
plot(MVN_state.t/ms,-MVN_state.V[0])
xlabel('time')
ylabel('Eye movement')
show()
numpy.savetxt("MVN_state_" + str(unitlessErrorDelay) + ".csv", MVN_state.V[0], delimiter=",")
numpy.savetxt("MF_state_" + str(unitlessErrorDelay) + ".csv", MF_state.M[0], delimiter=",")
|
ThePerson2/CA6_Project
|
SMAE.py
|
SMAE.py
|
py
| 4,435 |
python
|
en
|
code
| 0 |
github-code
|
6
|
24650911393
|
import asyncio
import curses
import typing
from curses_tools import draw_frame
class Obstacle:
def __init__(
self,
row: int,
column: int,
rows_size: int = 1,
columns_size: int = 1,
uid: str | None = None,
) -> None:
self.row = row
self.column = column
self.rows_size = rows_size
self.columns_size = columns_size
self.uid = uid
def get_bounding_box_frame(self) -> str:
"""Get frame of bounding box
Returns:
Bounding box frame.
"""
# increment box size to compensate obstacle movement
rows, columns = self.rows_size + 1, self.columns_size + 1
return '\n'.join(_get_bounding_box_lines(rows, columns))
def get_bounding_box_corner_pos(self) -> tuple[int, int]:
"""Get left upper position of bounding box."""
return self.row - 1, self.column - 1
def dump_bounding_box(self) -> tuple[int, int, str]:
"""Get data for drawing the border of an obstacle."""
row, column = self.get_bounding_box_corner_pos()
return row, column, self.get_bounding_box_frame()
def has_collision(
self,
obj_corner_row: int,
obj_corner_column: int,
obj_size_rows: int = 1,
obj_size_columns: int = 1,
) -> bool:
"""Determine if collision has occurred.
Args:
obj_corner_row: Left upper obj corner row;
obj_corner_column: Left upper obj corner column;
obj_size_rows: Obj width;
obj_size_columns: Obj height.
"""
return has_collision(
(self.row, self.column),
(self.rows_size, self.columns_size),
(obj_corner_row, obj_corner_column),
(obj_size_rows, obj_size_columns),
)
def _get_bounding_box_lines(
rows: int,
columns: int,
) -> typing.Generator[str, None, None]:
"""Get line of bounding_box frame.
Args:
rows: Box width;
columns: Box height.
"""
yield ' ' + '-' * columns + ' '
for _ in range(rows):
yield '|' + ' ' * columns + '|'
yield ' ' + '-' * columns + ' '
async def show_obstacles(
canvas: curses.window,
obstacles: list[Obstacle],
) -> None:
"""Display bounding boxes of every obstacle in a list.
Args:
canvas: Main window;
obstacles: List of obstacles.
"""
while True:
boxes = [obstacle.dump_bounding_box() for obstacle in obstacles]
for row, column, frame in boxes:
draw_frame(canvas, row, column, frame)
await asyncio.sleep(0)
for row, column, frame in boxes:
draw_frame(canvas, row, column, frame, negative=True)
def _is_point_inside(
corner_row: int,
corner_column: int,
size_rows: int,
size_columns: int,
point_row: int,
point_row_column: int,
) -> bool:
"""Check if a point is inside a rectangle of a given size.
Args:
corner_row: Left upper rectangle row position;
corner_column: Left upper rectangle column position
size_rows: Rectangle width;
size_columns: Rectangle height;
point_row: Left upper point row position;
point_row_column: Left upper point column position;
"""
rows_flag = corner_row <= point_row < corner_row + size_rows
columns_flag = (
corner_column <= point_row_column < corner_column + size_columns
)
return rows_flag and columns_flag
def has_collision(
obstacle_corner: tuple[int, int],
obstacle_size: tuple[int, int],
obj_corner: tuple[int, int],
obj_size: tuple[int, int] = (1, 1),
) -> bool:
"""Determine if collision has occurred.
Args:
obstacle_corner: Left upper corner obstacle position;
obstacle_size: Obstacle size (width, height);
obj_corner: Left upper corner obj position;
obj_size: Obj size (width, height).
"""
opposite_obstacle_corner = (
obstacle_corner[0] + obstacle_size[0] - 1,
obstacle_corner[1] + obstacle_size[1] - 1,
)
opposite_obj_corner = (
obj_corner[0] + obj_size[0] - 1,
obj_corner[1] + obj_size[1] - 1,
)
return any(
[
_is_point_inside(
*obstacle_corner,
*obstacle_size,
*obj_corner,
),
_is_point_inside(
*obstacle_corner,
*obstacle_size,
*opposite_obj_corner,
),
_is_point_inside(
*obj_corner,
*obj_size,
*obstacle_corner,
),
_is_point_inside(
*obj_corner,
*obj_size,
*opposite_obstacle_corner,
),
]
)
|
Alex-Men-VL/space_game
|
src/obstacles.py
|
obstacles.py
|
py
| 4,841 |
python
|
en
|
code
| 0 |
github-code
|
6
|
22368252597
|
import os, sys
import numpy as np
import pandas as pd
import pickle
import argparse
from keras import backend
from keras.models import load_model
from keras.optimizers import *
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from model import *
from io_data import *
backend.set_image_dim_ordering('tf')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
parser = argparse.ArgumentParser()
parser.add_argument('--train', help='train data path')
parser.add_argument('--test', help='test data path')
parser.add_argument('-l', '--log', help='log path')
parser.add_argument('-m', '--model', help='model path')
parser.add_argument('-o', '--output', help='output path')
parser.add_argument('-s', '--sample', type=int, help='novel sample')
parser.add_argument('-e', '--evaluate', type=int, help='novel sample')
parser.add_argument('-r', '--randomseed', type=int, help='randomseed')
args = parser.parse_args()
log_path = args.log
model_path = args.model
train_path = args.train
test_path = args.test
sample = args.sample
output_path = args.output
evaluate = args.evaluate
randomseed = args.randomseed
width = 32
height= 32
channel = 3
n_batch = 100
epoch = 30
print('Read data')
np.random.seed(randomseed)
train_imgs, label, test_imgs = read_test(train_path, test_path, sample=sample)
height, width, channel = train_imgs.shape[1:]
# training imgs flip horizontally
model, cnn_model = Recognition()
model.load_weights(model_path)
train_imgs = cnn_model.predict(train_imgs)
test_imgs = cnn_model.predict(test_imgs)
T = train_imgs.shape[0]
train_imgs = np.reshape(train_imgs, (20, sample, -1))
train_imgs = np.mean(train_imgs, axis=1)
label = np.array([label[i*sample] for i in range(20)])
test_imgs = np.reshape(test_imgs, (test_imgs.shape[0], -1))
knc = KNeighborsClassifier(n_neighbors=1)
knc.fit(train_imgs, label)
predict1 = knc.predict(test_imgs)
pca = PCA(n_components=64)
pca.fit(np.vstack([train_imgs, test_imgs]))
train_pca = pca.transform(train_imgs)
test_pca = pca.transform(test_imgs)
knc = KNeighborsClassifier(n_neighbors=1)
knc.fit(train_pca, label)
predict2 = knc.predict(test_pca)
save_predict(predict1, os.path.join(output_path, str(sample)+'_knn_predict.csv'))
save_predict(predict2, os.path.join(output_path, str(sample)+'_PCA_knn_predict.csv'))
del model
|
tom6311tom6311/dlcv2018final
|
task2/knn/code/knn_test.py
|
knn_test.py
|
py
| 2,377 |
python
|
en
|
code
| 0 |
github-code
|
6
|
17875196708
|
#https://projecteuler.net/problem=5
#Smallest Multiple
def lcm(a, b):
if a > b:
n = a
else:
n = b
while not (n % a == 0) or not (n % b == 0):
n += 1
return n
n = 20
l = 1
for i in range(1, n+1):
l = lcm(l, i)
print(l)
|
SreenathSreekrishna/euler
|
python/p5.py
|
p5.py
|
py
| 257 |
python
|
en
|
code
| 0 |
github-code
|
6
|
18287710970
|
import random
def GetQuestions(sub,quesNum):
# Getting the questions inside a variable as a list
with open(sub,"r") as f:
unfilteredQuestion = f.readlines()
# Removing new line escape sequence from the list
filteredQuestions = []
for items in unfilteredQuestion:
if items[0:-1] == '':
continue
filteredQuestions.append(items[0:-1])
# Generating 10 random unique numbers
def generateRandNum():
endIndex = len(filteredQuestions) - 1
allRandNum = random.sample(range(0,endIndex),quesNum)
return allRandNum
allRandNum = []
finalQuestions = []
# Appending random 10 questions inside finalQuestion list
for items in generateRandNum():
finalQuestions.append(filteredQuestions[items])
return finalQuestions
|
CharanGeek/DPP_Generator
|
GettingQuestions.py
|
GettingQuestions.py
|
py
| 824 |
python
|
en
|
code
| 0 |
github-code
|
6
|
4534308606
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# REF [site] >> https://scrapy.org/
import scrapy
class BlogSpider(scrapy.Spider):
name = 'blogspider'
start_urls = ['https://blog.scrapinghub.com']
def parse(self, response):
for title in response.css('.post-header>h2'):
yield {'title': title.css('a ::text').get()}
for next_page in response.css('a.next-posts-link'):
yield response.follow(next_page, self.parse)
#--------------------------------------------------------------------
# Usage:
# scrapy runspider scrapy_test.py
#if '__main__' == __name__:
# main()
|
sangwook236/SWDT
|
sw_dev/python/ext/test/networking/scrapy_test.py
|
scrapy_test.py
|
py
| 581 |
python
|
en
|
code
| 17 |
github-code
|
6
|
3457609091
|
import RPi.GPIO as GPIO
import time
# ===== CONFIGURATIONS and FUNCTIONS ====
# ===== (Please, don't touch!) ==========
## ==== CARRIAGE CONFIGS ================
GPIO.setwarnings(False)
DIR1 = 20 # Direction GPIO Pin Mag
STEP1 = 21 # Step GPIO Pin Mag
DIR2 = 16 # Direction GPIO Pin Car
STEP2 = 12 # Step GPIO Pin Car
DIR3 = 6 # Direction GPIO Pin Lenta
STEP3 = 5 # Step GPIO Pin Lenta
DIR4 = 7 # Direction GPIO Pin Lift
STEP4 = 8 # Step GPIO Pin Lift
CW = 1 # Clockwise Rotation
CCW = 0 # Counterclockwise Rotation
SPR = 75 # Steps per Revolution (360 / 7.5) 328 - last
Servo = 17 #servo pin
in1 = 11 # GPIO pin led 1 last - 24
in2 = 9 # GPIO pin led 2 last - 23
in3 = 3 # GPIO pin led 1 last - 24
in4 = 4 # GPIO pin led 2 last - 23
End = False
Step = 0
StepMagnet = 0
StepMove = 0
place = 0
FirstHoarder = 2250
SecondHoarder = 1450
ThirdHoarder = 650
FourthHoarder = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(DIR1, GPIO.OUT)
GPIO.setup(STEP1, GPIO.OUT)
GPIO.output(DIR1, CW)
GPIO.setup(DIR2, GPIO.OUT)
GPIO.setup(STEP2, GPIO.OUT)
GPIO.output(DIR2, CW)
GPIO.setup(DIR3, GPIO.OUT)
GPIO.setup(STEP3, GPIO.OUT)
GPIO.output(DIR3, CW)
GPIO.setup(DIR4, GPIO.OUT)
GPIO.setup(STEP4, GPIO.OUT)
GPIO.output(DIR4, CW)
GPIO.setup(Servo, GPIO.OUT)
GPIO.setup(in1,GPIO.OUT)
GPIO.setup(in2,GPIO.OUT)
GPIO.output(in1,GPIO.LOW)
GPIO.output(in2,GPIO.LOW)
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
pwm=GPIO.PWM(Servo, 50)
MODE = (13, 19, 26) # Microstep Resolution GPIO Pins
GPIO.setup(MODE, GPIO.OUT)
RESOLUTION = {'Full': (0, 0, 0),
'Half': (1, 0, 0),
'1/4': (0, 1, 0),
'1/8': (1, 1, 0),
'1/16': (0, 0, 1),
'1/32': (1, 0, 1)}
GPIO.output(MODE, RESOLUTION['1/8'])
step_count = SPR * 32
delay = .0208 / 32
def MagnetFullDown():
global StepMagnet
while StepMagnet <= 7090:
GPIO.output(DIR1, CCW)
GPIO.output(STEP1, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP1, GPIO.LOW)
time.sleep(delay)
StepMagnet += 1
print('MagnetFullDown')
StepMagnet = 0
print(StepMagnet)
def MagnetHalfDown():
global StepMagnet
while StepMagnet <= 2000:
GPIO.output(DIR1, CCW)
GPIO.output(STEP1, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP1, GPIO.LOW)
time.sleep(delay)
StepMagnet += 1
print('MagnetHalfDown')
StepMagnet = 0
print(StepMagnet)
def MoveTo():
global Step
if Step > place:
while Step >= place:
GPIO.output(DIR4, CCW)
GPIO.output(STEP4, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP4, GPIO.LOW)
time.sleep(delay)
Step -= 1
else:
while Step <= place:
GPIO.output(DIR4, CW)
GPIO.output(STEP4, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP4, GPIO.LOW)
time.sleep(delay)
Step += 1
def ToFirstHoarder():
global FirstHoarder
global place
place = FirstHoarder
MoveTo()
print('ToFirstHoarder')
print(Step)
def ToSecondHoarder():
global SecondHoarder
global place
place = SecondHoarder
MoveTo()
print('ToSecondHoarder')
print(Step)
def ToThirdHoarder():
global ThirdHoarder
global place
place = ThirdHoarder
MoveTo()
print('ToThirdHoarder')
print(Step)
def ToFourthHoarder():
global FourthHoarder
global place
place = FourthHoarder
MoveTo()
print('ToFourthHoarder')
print(Step)
def LiftUp():
global End
global StepMove
while End == False:
LiftDown = GPIO.input(18)
GPIO.output(DIR3, CW)
GPIO.output(STEP3, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP3, GPIO.LOW)
time.sleep(delay)
StepMove += 1
if LiftDown == False:
print('LiftDown')
time.sleep(0.2)
End = True
End = False
StepMove = 0
print(StepMove)
def CarriageStart():
global End
global Step
while End == False:
CarriageStart = GPIO.input(23)
GPIO.output(DIR4, CW)
GPIO.output(STEP4, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP4, GPIO.LOW)
time.sleep(delay)
Step = Step + 1
if CarriageStart == False:
print('CarriageStart')
time.sleep(0.2)
End = True
End = False
print(Step)
def MagnetOn():
GPIO.output(in1,GPIO.HIGH)
GPIO.output(in2,GPIO.LOW)
def MagnetUp():
global End
global StepMagnet
while End == False:
MagnetUp = GPIO.input(25)
GPIO.output(DIR1, CW)
GPIO.output(STEP1, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP1, GPIO.LOW)
time.sleep(delay)
StepMagnet += 1
if MagnetUp == False:
print('MagnetUp')
time.sleep(0.2)
End = True
End = False
StepMagnet = 0
print(StepMagnet)
def LentaUp():
global StepMove
while StepMove <= 5000:
GPIO.output(DIR2, CW)
#for x in range(step_count):
GPIO.output(STEP2, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP2, GPIO.LOW)
time.sleep(delay)
StepMove += 1
print(StepMove)
StepMove = 0
def LiftDown():
global End
global StepMove
while End == False:
LiftUp = GPIO.input(27)
GPIO.output(DIR3, CCW)
#for x in range(step_count):
GPIO.output(STEP3, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP3, GPIO.LOW)
time.sleep(delay)
StepMove += 1
if LiftUp == False:
print('LiftUp')
time.sleep(0.2)
End = True
End = False
print(End)
print(StepMove)
StepMove = 0
def CarriageEnd():
global End
global Step
while End == False:
CarriageEnd = GPIO.input(22)
GPIO.output(DIR4, CCW)
#for x in range(step_count):
GPIO.output(STEP4, GPIO.HIGH)
time.sleep(delay)
GPIO.output(STEP4, GPIO.LOW)
time.sleep(delay)
Step = Step + 1
if CarriageEnd == False:
print('CarriageEnd')
time.sleep(0.2)
End = True
End = False
print(End)
print(Step)
Step = 0
def MagnetOff():
GPIO.output(in1,GPIO.LOW)
GPIO.output(in2,GPIO.LOW)
def Servo():
pwm.start(0)
global End
pwm.ChangeDutyCycle(5)
while End == False:
ServoForward = GPIO.input(10)
if ServoForward == False:
End = True
print('ServoForward')
End = False
pwm.ChangeDutyCycle(10)
while End == False:
ServoBackward = GPIO.input(24)
if ServoBackward == False:
End = True
print('ServoBackward')
End = False
print(End)
MagnetUp()
CarriageEnd()
CarriageStart()
MagnetUp()
MagnetFullDown()
MagnetOn()
MagnetUp()
ToFirstHoarder()
MagnetHalfDown()
MagnetOff()
MagnetUp()
Servo()
LiftDown()
LentaUp()
LiftUp()
GPIO.cleanup()
|
Mekek/NTI-ATC
|
фабрика/AiOi/facility.py
|
facility.py
|
py
| 7,522 |
python
|
en
|
code
| 0 |
github-code
|
6
|
16312750556
|
print('-'*30)
print('Kwik-E-Mart')
print('-'*30)
preçototal = thousand = menor = contador = 0
barato = ''
while True:
produto = str(input('Nome do Produto: '))
preço = float(input('preço R$: '))
preçototal += preço
contador += 1
if preço > 1000:
thousand += 1
if contador == 1 or preço < menor: # Simplificação
menor = preço
barato = produto
compra = ' '
while compra not in 'SN':
compra = str(input('Deseja continuar? [S/N]: ')).strip()[0].upper()
if compra == 'N':
break
print(f'{"Fim do programa":-^40}')
print(f'O valor da sua compra deu R${preço:.2f}')
print(f'Temos {thousand} produtos acima de R$1000.00 ')
print(f'O produto mais barato custa R${menor:.2f}')
|
igorfreits/Studies-Python
|
Curso-em-video/Mundo-2/AULA15-Interrompendo-repetições-while(break)/#070 - Estatísticas em produtos.py
|
#070 - Estatísticas em produtos.py
|
py
| 764 |
python
|
pt
|
code
| 1 |
github-code
|
6
|
33489134927
|
import sys
import os
fi = open(sys.argv[1], 'r')
fo = open(sys.argv[2], 'w')
vocab = {}
for line in fi:
u = line.split()[0]
v = line.split()[1]
vocab[u] = 1
vocab[v] = 1
for ent in vocab.keys():
fo.write(ent + '\n')
fi.close()
fo.close()
|
mnqu/REPEL
|
preprocess/entity.py
|
entity.py
|
py
| 245 |
python
|
en
|
code
| 26 |
github-code
|
6
|
37091838482
|
import RPi.GPIO as GPIO
from RF24 import *
import time
import spidev
GPIO.setmode(GPIO.BCM)
pipes = [0xe7e7e7e7e7, 0xc2c2c2c2c2]
radio = RF24(25,8)
radio.begin()
#radio.setPayloadSize(32)
radio.setChannel(0x60)
radio.setDataRate(RF24_2MBPS)
radio.setPALevel(RF24_PA_MIN)
radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()
while True:
ackPL = [1]
while not radio.available():
time.sleep(1/100)
receivedMessage =radio.read(radio.getDynamicPayloadSize())
print("Received: {}".format(receivedMessage))
print("Translating the receivedMessage into unicode characters...")
string = ""
for n in receivedMessage:
# Decode into standard unicode set
if (n >= 32 and n <= 126):
string += chr(n)
print(string)
radio.writeAckPayload(1, bytearray(ackPL))
print("Loaded payload reply of {}".format(ackPL))
|
julio-burgos/Rx_TX_RF24
|
Basic/recv.py
|
recv.py
|
py
| 983 |
python
|
en
|
code
| 1 |
github-code
|
6
|
33623583816
|
import arcpy
import traceback
import split_tool
name_mod = arcpy.GetParameterAsText(4)
output_file = "G:\\GIS\\Models_Tools\\Production\\EPModel\\tests\\testing\\test_zone\\ep_model_testing\\errors\\{0}_errors.txt".format(name_mod)
messages_file = "G:\\GIS\\Models_Tools\\Production\\EPModel\\tests\\testing\\test_zone\\ep_model_testing\\errors\\{0}_messages.txt".format(name_mod)
try:
final_message = split_tool.main()
with open(messages_file, "w+") as w_file:
w_file.write(final_message)
except:
with open(output_file, "w+") as w_file:
w_file.write(traceback.format_exc());
|
cwmat/ShapeSplitter
|
src/test_wrapper.py
|
test_wrapper.py
|
py
| 606 |
python
|
en
|
code
| 0 |
github-code
|
6
|
21632483915
|
# Вариант 29
# Дана строка, содержащая по крайней мере один символ пробела. Вывести подстроку,
# расположенную между первым и вторым пробелом исходной строки. Если строка
# содержит только один пробел, то вывести пустую строку.
a = input('Введите строку: ') # Ввод строки с клавиатуры
space_count = 0 # Счетчик количества пробелов
spaces = [] # Позиции пробелов
count = 0 # Счетчик итераций(для внесения позиции пробела в spaces)
new_string = '' # Новая строка, которая станет конечной
for i in a: # Цикл подсчета пробелов и внесения их позиций в spaces
count += 1
if i == ' ':
space_count += 1 # Использовал простой счетчик, а не a.count потому что count не вернет позиции пробелов,
spaces.append(count) # и все равно пришлось бы бегать циклом по строке
if space_count == 0: # Проверка количества пробелов
print('Нет пробелов!')
elif space_count == 1: # Проверка количества пробелов
print('')
else: # Проверка количества пробелов
new_string = a[spaces[0]:spaces[1]] # Присваивание значения переменной new_string
print(new_string) # Вывод конечной строки
|
Abyka12/Proj_1sem_Mogilko
|
PZ_7/PZ_7_2.py
|
PZ_7_2.py
|
py
| 1,715 |
python
|
ru
|
code
| 0 |
github-code
|
6
|
32129181331
|
import logging
import pandas as pd
from flask import Flask, request, jsonify
from data_preprocessing import process_data_for_training
import psycopg2
from psycopg2 import sql
# Create a Flask app
app = Flask(__name__)
app.logger.setLevel(logging.DEBUG)
app.logger.addHandler(logging.StreamHandler())
db_params = {
'dbname': 'app_db',
'user': 'app_user',
'password': 'password',
'host': 'db',
'port': '5432'
}
def fetch_warranty_data():
# Establish a connection to the database
connection = psycopg2.connect(**db_params)
cursor = connection.cursor()
# Build the dynamic SQL query
select_query = sql.SQL("SELECT * FROM api.claims")
cursor.execute(select_query)
rows = cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
warranty_df = pd.DataFrame(rows, columns=columns)
cursor.close()
connection.close()
return warranty_df
# Define the API endpoint for data preparation
@app.route("/train", methods=["POST"])
def train():
data = request.data.decode('utf-8')
warranty_data = fetch_warranty_data()
train(process_data_for_training(data, warranty_data))
return 'New model generated'
# Run the Flask app
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
|
evialina/automotive_diagnostic_recommender_system
|
training-service/script.py
|
script.py
|
py
| 1,290 |
python
|
en
|
code
| 0 |
github-code
|
6
|
72474633149
|
"""
~ working with data in text files ~
A common thing to do with Python is to process data files. You can use the built-in `csv` module to work with delimited text.
We'll open the files like this:
- inside a `with` block -- notice the indentation on subsequent lines
- in `r` ("read") mode
- as some_variable that gives you a handle to the file object
- with the newline argument set to a blank string
Inside the with block, we'll create a `csv.reader` object and hand it the file object variable as an argument.
You can then _iterate_ over the rows in the data file, with each row as a list of items in the row.
"""
import csv
with open('../data/lotto.csv', 'r', newline='') as infile:
reader = csv.reader(infile)
for row in reader:
county = row[0]
retailer = row[1]
address = row[2]
city = row[3]
date_claimed = row[4]
game = row[5]
amount = row[6]
claimant_name = row[7]
claimant_city = row[8]
claimant_state = row[9]
# print(city)
"""
You can also use a `csv.DictReader` object instead of a `csv.reader` object, which will treat each row as a dictionary instead of a list. The keys will be the items in the header row.
I like using `csv.DictReader` better because it's easier to keep track of where everything is.
"""
with open('../data/lotto.csv', 'r', newline='') as infile:
reader = csv.DictReader(infile)
for row in reader:
county = row['County']
retailer = row['Selling Retailer']
address = row['Business Address']
city = row['City']
date_claimed = row['Date Claimed']
game = row['Game']
amount = row['Prize Amount']
claimant_name = row["Primary Claimant's Name"]
claimant_city = row["Claimant's City"]
claimant_state = row['State']
# print(city)
"""
~ use conditional logic to filter data ~
"""
with open('../data/lotto.csv', 'r', newline='') as infile:
reader = csv.DictReader(infile)
for row in reader:
county = row['County']
retailer = row['Selling Retailer']
address = row['Business Address']
city = row['City']
date_claimed = row['Date Claimed']
game = row['Game']
amount = row['Prize Amount']
claimant_name = row["Primary Claimant's Name"]
claimant_city = row["Claimant's City"]
claimant_state = row['State']
if city.strip() == 'KINGSTON':
print(row)
"""
~ writing to a CSV ~
Unsurprisingly, you can also write to a CSV (use 'w' mode). The `csv.writer` object's `writerow()` method expects a list; the `csv.DictWriter`'s method expects a dictionary.
"""
# write lists
with open('test-writer.csv', 'w') as outfile:
writer = csv.writer(outfile)
headers = ['name', 'age', 'profession']
writer.writerow(headers)
journos = [
['Frank', 52, 'Reporter'],
['Sally', 37, 'Editor'],
['Pat', 41, 'Producer']
]
for journo in journos:
writer.writerow(journo)
# write dictionaries
# notice that you have to specify the headers when you
# create the `DictWriter` object -- you pass a list to
# the `fieldnames` keyword argument -- and they have
# to match exactly the keys in the dictionaries
# of the rows you're writing out
with open('test-dictwriter.csv', 'w') as outfile:
headers = ['name', 'age', 'profession']
writer = csv.DictWriter(outfile, fieldnames=headers)
writer.writeheader()
journos = [
{'name': 'Frank', 'age': 52, 'profession': 'Reporter'},
{'name': 'Sally', 'age': 37, 'profession': 'Editor'},
{'name': 'Pat', 'age': 41, 'profession': 'Producer'}
]
for journo in journos:
writer.writerow(journo)
"""
EXERCISES:
- Open the lotto.csv file and loop over the rows -- print only the records where the claimant's state is NY
- Create a couple of rows of data -- anything, doesn't matter -- and write them out to a CSV file
"""
|
cjwinchester/ire-2017-python-101
|
completed/1-data-files-completed.py
|
1-data-files-completed.py
|
py
| 3,991 |
python
|
en
|
code
| 2 |
github-code
|
6
|
74750167547
|
import torch
from transformers import T5ForConditionalGeneration, T5Tokenizer
import re
def title_generation(data):
print("[!] Server logs: Title generation has started")
text = data["content"]
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = T5ForConditionalGeneration.from_pretrained(
"Michau/t5-base-en-generate-headline"
)
tokenizer = T5Tokenizer.from_pretrained("Michau/t5-base-en-generate-headline")
model = model.to(device)
encoding = tokenizer.encode_plus(text, return_tensors="pt")
input_ids = encoding["input_ids"].to(device)
attention_masks = encoding["attention_mask"].to(device)
beam_outputs = model.generate(
input_ids=input_ids,
attention_mask=attention_masks,
max_length=64,
num_beams=3,
early_stopping=True,
)
result = tokenizer.decode(beam_outputs[0])
print("[!] Server logs: Title generation completed")
regex_pattern = r"(?<=<pad> )(.*)(?=</s>)"
result = re.search(regex_pattern, result).group(0)
data["title"] = result
return data
|
SVijayB/Gist
|
scripts/title_generation.py
|
title_generation.py
|
py
| 1,106 |
python
|
en
|
code
| 4 |
github-code
|
6
|
9634403295
|
''' Functions for computing energies of sets of auxiliaries.
'''
import numpy as np
from auxgf import util
def energy_2body_aux(gf, se, both_sides=False):
''' Calculates the two-body contribution to the electronic energy
using the auxiliary representation of the Green's function and
self-energy, according to the Galitskii-Migdal formula.
Parameters
----------
gf : Aux
auxiliary representation of Green's function
se : Aux
auxiliary representation of self-energy
both_sides : bool, optional
if True, calculate both halves of the functional and return
the mean, default False
Returns
-------
e2b : float
two-body contribution to electronic energy
'''
#TODO in C
if isinstance(se, (tuple, list)):
n = len(se)
if isinstance(gf, (tuple, list)):
return sum([energy_2body_aux(gf[i], se[i], both_sides=both_sides) for i in range(n)]) / n
else:
return sum([energy_2body_aux(gf, se[i], both_sides=both_sides) for i in range(n)]) / n
nphys = se.nphys
e2b = 0.0
for l in range(gf.nocc):
vxl = gf.v[:nphys,l]
vxk = se.v[:,se.nocc:]
dlk = 1.0 / (gf.e[l] - se.e[se.nocc:])
e2b += util.einsum('xk,yk,x,y,k->', vxk, vxk.conj(), vxl, vxl.conj(), dlk)
if both_sides:
for l in range(gf.nocc, gf.naux):
vxl = gf.v[:nphys,l]
vxk = se.v[:,:se.nocc]
dlk = -1.0 / (gf.e[l] - se.e[:se.nocc])
e2b += util.einsum('xk,yk,x,y,k->', vxk, vxk.conj(), vxl, vxl.conj(), dlk)
else:
e2b *= 2.0
return np.ravel(e2b.real)[0]
def energy_mp2_aux(mo, se, both_sides=False):
''' Calculates the two-body contribution to the electronic energy
using the MOs and the auxiliary representation of the
self-energy according the the MP2 form of the Galitskii-Migdal
formula.
Parameters
----------
mo : (n) ndarray
MO energies
se : Aux
auxiliary representation of self-energy
both_sides : bool, optional
if True, calculate both halves of the functional and return
the mean, default False
Returns
-------
e2b : float
two-body contribution to electronic energy
'''
if isinstance(se, (tuple, list)):
n = len(se)
if util.iter_depth(mo) == 2:
return sum([energy_mp2_aux(mo[i], se[i], both_sides=both_sides) for i in range(n)]) / n
else:
return sum([energy_mp2_aux(mo, se[i], both_sides=both_sides) for i in range(n)]) / n
nphys = se.nphys
occ = mo < se.chempot
vir = mo >= se.chempot
vxk = se.v_vir[occ]
dxk = 1.0 / util.outer_sum([mo[occ], -se.e_vir])
e2b = util.einsum('xk,xk,xk->', vxk, vxk.conj(), dxk)
if both_sides:
vxk = se.v_occ[vir]
dxk = -1.0 / util.outer_sum([mo[vir], -se.e_occ])
e2b += util.einsum('xk,xk,xk->', vxk, vxk.conj(), dxk)
e2b *= 0.5
return np.ravel(e2b.real)[0]
|
obackhouse/auxgf
|
auxgf/aux/energy.py
|
energy.py
|
py
| 3,055 |
python
|
en
|
code
| 3 |
github-code
|
6
|
30439578880
|
import networkx as nx
from networkx.generators.degree_seq import expected_degree_graph
# make a random graph of 500 nodes with expected degreees of 50
n = 500 # n nodes
p = 0.1
w = [p * n for i in range(n)] # w = p*n for all nodes
G = expected_degree_graph(w) # configuration model
print("Degree Histogram")
print("degree (#nodes) ****")
dh = nx.degree_histogram(G)
low = min(nx.degree(G))
for i in range(low, len(dh)):
bar = ''.join(dh[i] * ['*'])
print("%2s (%2s) %s" % (i, dh[i], bar))
|
oimichiu/NetworkX
|
graph/ex24.py
|
ex24.py
|
py
| 503 |
python
|
en
|
code
| 0 |
github-code
|
6
|
10769330374
|
"""my_first_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.shortcuts import render
from django.urls import include, path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView
)
from rest_framework import routers
from myapp.views.person import PersonViewSet
from myapp.views.user import UserViewSet, GroupViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
router.register(r'persons', PersonViewSet)
def index(request):
return render(request, 'index.html')
urlpatterns = [
path("", index, name='index'),
path("admin/", admin.site.urls),
path("api/", include(router.urls)),
path("myapp/", include("myapp.urls")),
path("accounts/", include("django.contrib.auth.urls")),
path("api-auth/", include("rest_framework.urls")),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]
|
shine-codestove/my_first_django
|
my_first_django/urls.py
|
urls.py
|
py
| 1,750 |
python
|
en
|
code
| 1 |
github-code
|
6
|
28237649684
|
import typing
import requests
from requests import Session
from zenora.errors import MissingAccess, AvatarError, InvalidSnowflake
# Request functions
def fetch(
url: str,
headers: typing.Dict[str, str],
params: typing.Dict[str, str] = {},
) -> typing.Dict:
r = requests.get(url=url, headers=headers, params=params)
r.raise_for_status()
return r.json()
def post(
url: str,
headers: typing.Dict[str, str],
params: typing.Dict[str, str] = {},
) -> typing.Dict:
r = requests.post(url=url, headers=headers, json=params)
r.raise_for_status()
return r.json()
def patch(
url: str,
headers: typing.Dict[str, str],
params: typing.Dict[str, str] = {},
) -> typing.Dict:
r = requests.patch(url=url, headers=headers, json=params)
r.raise_for_status()
return r.json()
def delete(
url: str,
headers: typing.Dict[str, str],
params: typing.Dict[str, str] = {},
) -> typing.Dict:
r = requests.delete(url=url, headers=headers, json=params)
r.raise_for_status()
return r
# Utility functions
def error_checker(data: typing.Dict) -> None:
if data.get("user_id") or data.get("channel_id"):
raise InvalidSnowflake(
data.get("user_id")[0]
if data.get("user_id") is not None
else data.get("channel_id")[0]
)
elif data.get("code"):
if data.get("code") == 50001:
raise MissingAccess(data.get("message"))
else:
raise InvalidSnowflake(data.get("message"))
elif data.get("avatar"):
if isinstance(data.get("avatar"), list):
raise AvatarError(data.get("avatar")[0])
def get_file(url):
# Downloading Image from link
r = requests.get(url=url, stream=True)
return r
|
StarrMan303/zenora
|
zenora/utils/helpers.py
|
helpers.py
|
py
| 1,778 |
python
|
en
|
code
| 0 |
github-code
|
6
|
37187209809
|
# solved by satyam kumar (reference https://www.youtube.com/watch?v=gBTe7lFR3vc)
# question link https://leetcode.com/problems/linked-list-cycle/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# x=[]
# # for empty linked list
# if head==None:
# return False
# while head.next!=None:
# # if cycle exists
# if head.next in x:
# return True
# # storing the address
# x.append(head.next)
# head=head.next
# return False
slow=head
fast=head
# while True:
# if slow==None or fast==None:
# return False
# try:
# slow=slow.next
# fast=fast.next.next
# except:
# return False
# if slow==fast:
# return True
while fast and fast.next:
slow=slow.next
fast=fast.next.next
if slow==fast:
return True
return False
|
saty035/DSA_Python
|
Linked List Cycle_leetcode/Linked List Cycle.py
|
Linked List Cycle.py
|
py
| 1,397 |
python
|
en
|
code
| 2 |
github-code
|
6
|
21797961836
|
# make a time series of instantaneous electric power consumption graph from a csv file
import csv
import glob
import re
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statistics import mean
# define variables
timestep = 0.01
def csv_to_graph(path):
data = pd.read_csv(path, index_col=0, skipinitialspace=True)
# comvert csv data to a list format data
current = np.array(data['current'].values.tolist())
# find the peak value from the list data
peak_value_index = np.argmax(current)
# extract useful values from arround the peak value
arround_peak_value = current[peak_value_index-100:peak_value_index+500]
# calucurate const value
const_value = arround_peak_value[len(arround_peak_value)-400:len(arround_peak_value)]
avg_const_value = round(mean(const_value),2)
text_avg_const_value = "mean const value = " + str(avg_const_value)
# make a time series graph
count = np.arange(0, len(arround_peak_value)/100, timestep)
plt.plot(count, arround_peak_value)
plt.xlim(0.0, 6.0)
plt.ylim(0.0, 10.0)
plt.xlabel('t [s]')
plt.ylabel('current [A]')
font_dict = dict(style="italic",
size=16)
bbox_dict = dict(facecolor="#ffffff",
edgecolor="#000000",
fill=True)
plt.text(2.5, 9, text_avg_const_value, font_dict, bbox=bbox_dict)
plt.grid()
plt.show()
def make_result_file(path):
# define variables
peak_value = []
mean_const_value = []
# make file list
file_list = glob.glob(path+'*.csv')
# extract the peak value and average const value of each file
# and append each value to the list
for file in file_list:
print(file)
data = pd.read_csv(file, index_col=0, skipinitialspace=True)
# comvert csv data to a list format data
current = np.array(data['current'].values.tolist())
# find the peak value from the list data
peak_value_index = np.argmax(current)
# extract useful values from arround the peak value
arround_peak_value = current[peak_value_index-100:peak_value_index+500]
# calucurate const value
const_value = arround_peak_value[len(arround_peak_value)-400:len(arround_peak_value)]
avg_const_value = round(mean(const_value),2)
# calcurate mean value of peak value and average const value
peak_value.append(np.max(current))
mean_const_value.append(avg_const_value)
# make a result file(write each value)
file_name = path + 'result.txt'
f = open(file_name, 'a')
for i in range(len(file_list)):
peak = peak_value[i]
const = mean_const_value[i]
f.write("FILE%s: Peak value: %s, Mean const value: %s \n" % (i, peak, const))
mean_peak = round(mean(peak_value),2)
mean_const = round(mean(mean_const_value),2)
f.write("Mean peak value: %s, Mean const value: %s\n" % (mean_peak, mean_const))
f.close()
# analyze the step down experiment data
def analyze_gradation_exp(file_list):
# import csv format file
for file in file_list:
data = pd.read_csv(file, index_col=0, skipinitialspace=True)
# comvert csv data to a list format data
current = np.array(data['current'].values.tolist())
# extract the peak value from the list data
peak_value_index = np.argmax(current)
start_index = peak_value_index
# clip the time series data by 1 sec
grad_data = []
for i in range(int(len(current[start_index:])/99)):
grad_data.append(current[start_index:start_index+99*i])
start_index = start_index + 99
# calcurate mean value of each data set
for data in grad_data:
mean_grad = mean(data)
print(mean_grad)
# write results on a text file
if __name__ == "__main__":
# import csv format file
"""
# useage: make a time series of power consumption graph
path = "test.csv"
csv_to_graph(path)
"""
# useage: make result files
path = 'C:/Users/is0232xf/OneDrive - 学校法人立命館/ソースコード/BIWAKO_unit_test/csv/diagonal/25%/'
make_result_file(path)
"""
files = os.listdir(path)
# get subdirectory list
files_dir = [f for f in files if os.path.isdir(os.path.join(path, f))]
for subdir in files_dir:
dir = path + subdir + '/'
make_result_file(dir)
"""
|
is0232xf/BIWAKO_unit_test
|
csv_to_graph.py
|
csv_to_graph.py
|
py
| 4,460 |
python
|
en
|
code
| 0 |
github-code
|
6
|
42095752382
|
import os, settings
from app import myApp
import uuid
from flask import request, render_template
from pdf_core import PdfHelper
from threading import Timer
@myApp.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# create a list with all pdf files
files = []
for uploadedFile in request.files.getlist('file'):
if allowed_file(uploadedFile.filename):
files.append(uploadedFile)
# join pdf files
pdfHelper = PdfHelper()
uniqueFilenamePath = os.path.join(settings.RESULT_PATH, str(uuid.uuid4()) + ".pdf")
pdfHelper.merge_pdfs(files, uniqueFilenamePath)
# remove the file after 10 min
t = Timer(60*10, delete, (uniqueFilenamePath,))
t.start();
# close the files
for uploadedFile in files:
uploadedFile.close()
return render_template('show_links.html', link=uniqueFilenamePath)
return render_template('index.html')
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in settings.ALLOWED_EXTENSIONS
def delete(dest):
if os.path.exists(dest):
os.remove(dest)
|
icruces/blog-PDFMerging
|
app/views.py
|
views.py
|
py
| 1,305 |
python
|
en
|
code
| 2 |
github-code
|
6
|
74416653309
|
# Ta stała globalna przechowuje procent kwoty
# wynagrodzenia przekazywany na fundusz emerytalny.
CONTRIBUTION_RATE = 0.05
def main():
gross_pay = float(input('Podaj kwotę wynagrodzenia: '))
bonus = float(input('Podaj kwotę premii: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
# Funkcja show_pay_contrib() pobiera argument w postaci
# kwoty wynagrodzenia i wyświetla obliczoną wysokość składki
# naliczoną dla podanego wynagrodzenia.
def show_pay_contrib(gross):
contrib = gross * CONTRIBUTION_RATE
print('Wysokość składki naliczona dla wynagrodzenia wynosi: ',
format(contrib, '.2f'),
sep='')
# Funkcja show_bonus_contrib() pobiera argument w postaci
# kwoty premii i wyświetla obliczoną wysokość składki
# naliczoną dla podanej premii.
def show_bonus_contrib(bonus):
contrib = bonus * CONTRIBUTION_RATE
print('Wysokość składki naliczona dla premii wynosi ',
format(contrib, '.2f'),
sep='')
# Wywołanie funkcji main().
main()
|
JeanneBM/Python
|
Owoce Programowania/R05/28. Retirement.py
|
28. Retirement.py
|
py
| 1,038 |
python
|
pl
|
code
| 0 |
github-code
|
6
|
6185400966
|
# codesignal level1 n2
def centuryFromYear(year):
return (year - 1) // 100 + 1
# tests
print('century from hear 1905: ',centuryFromYear(1905)) # expected 20
print('century from hear 1700: ',centuryFromYear(1700)) # expected 17
# codesignal level1 n3
def checkPalindrome(inputString):
length = len(inputString)
mid = length // 2
return inputString[:mid-1:-1] == inputString[:mid] if length%2 == 0 else inputString[:mid] == inputString[:mid:-1]
# tests
print('checkPalindrome: "aabaa", expected True is: ',checkPalindrome("aabaa"))
print('checkPalindrome: "abac", expected False is: ',checkPalindrome("abac"))
print('checkPalindrome: "a", expected True is: ',checkPalindrome("a"))
print('checkPalindrome: "abacaba", expected True is: ',checkPalindrome("abacaba"))
# codesignal level2 n1
def adjacentElementsProduct(inputArray):
result = 0
temp = 0
for i in range(len(inputArray)):
if i == 0:
continue
temp = inputArray[i-1] * inputArray[i]
if result == 0:
result = temp
else :
result = temp if temp > result else result
return result
# tests
print('max of two multiplied members in list: [3, 6, -2, -5, 7, 3] is 21 = ',adjacentElementsProduct([3, 6, -2, -5, 7, 3]))
print('max of two multiplied members in list: [5, 1, 2, 3, 1, 4] is 6 = ',adjacentElementsProduct([5, 1, 2, 3, 1, 4]))
# codesignal level2 n2 - polygon shape area calculator
def shapeArea(n):
return (n * n) + ((n - 1) * (n - 1))
# tests
print('polygon area of 2 squares is 5 = ',shapeArea(2))
print('polygon area of 7000 squares is 97986001 = ',shapeArea(7000))
# codesignal level2 n3 - find missing numbers count if list becomes sorted
def makeArrayConsecutive2(statues):
full = list( range( min(statues), max(statues) ) )
result = []
for i in range( 0, len(full) ):
if full[i] not in statues:
result.append( full[i] )
return len( result )
# tests
print('missing numbers count in list [6, 2, 3, 8] is 3 = ',makeArrayConsecutive2([6, 2, 3, 8]))
print('missing numbers count in list [6, 2, 10, 3, 15, 8] is 8 = ',makeArrayConsecutive2([6, 2, 10, 3, 15, 8]))
# codesignal level2 n4 - is it possible to get increasing sequence by removing only 1 member
def almostIncreasingSequence(sequence):
j = first_bad_pair(sequence)
if j == -1:
return True # List is increasing
if first_bad_pair(sequence[j - 1:j] + sequence[j + 1:]) == -1:
return True # Deleting earlier element makes increasing
if first_bad_pair(sequence[j:j + 1] + sequence[j + 2:]) == -1:
return True # Deleting later element makes increasing
return False
# additional function for l2 n2 - almostIncreasingSequence
def first_bad_pair(sequence):
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i + 1]:
return i
return -1
# tests
print('almostIncreasingSequence of [1, 3, 2, 1] is false = ',almostIncreasingSequence([1, 3, 2, 1]))
print('almostIncreasingSequence of [123, -17, -5, 1, 2, 3, 12, 43, 45] is true = ',almostIncreasingSequence([123, -17, -5, 1, 2, 3, 12, 43, 45]))
# codesignal level2 n5 - matrix of ghosts
def matrixElementsSum(matrix):
result = 0
ignore = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] > 0 and j not in ignore:
result += matrix[i][j]
elif matrix[i][j] == 0 and j not in ignore:
ignore.append(j)
return result
# tests
print('matrix of ghosts [[0,1,1,2],[0,5,0,0],[2,0,3,3]] sum is 9 = ',matrixElementsSum([[0,1,1,2],[0,5,0,0],[2,0,3,3]]))
print('matrix of ghosts [[4,0,1],[10,7,0],[0,0,0],[9,1,2]] sum is 15 = ',matrixElementsSum([[4,0,1],[10,7,0],[0,0,0],[9,1,2]]))
# codesignal level3 n1 - find longest string in list and how many have same length
def allLongestStrings(inputArray):
result = []
longest = max(inputArray, key=len)
length = len(longest)
for i in inputArray:
if len(i) == length:
result.append(i)
return result
# tests
print('all longest strings of ["aba","aa","ad","vcd","aba"] is ["aba","vcd","aba"] = ',allLongestStrings(["aba","aa","ad","vcd","aba"]))
print('all longest strings of ["abc","eeee","abcd","dcd"] is ["eeee","abcd"] = ',allLongestStrings(["abc","eeee","abcd","dcd"]))
# codesignal level3 n2
def commonCharacterCount(s1, s2):
result = 0
ignore = []
for i in s1:
for j in range(len(s2)):
if i == s2[j] and j not in ignore:
ignore.append(j)
result += 1
break
return result
# tests
print('commonCharacterCount of "aabcc" and "adcaa" is 3 = ',commonCharacterCount("aabcc","adcaa"))
print('commonCharacterCount of "zzzz" and "zzzzzzz" is 4 = ',commonCharacterCount("zzzz","zzzzzzz"))
print('commonCharacterCount of "abca" and "xyzbac" is 3 = ',commonCharacterCount("abca","xyzbac"))
# codesignal level3 n3 - lottery win when one half of matrix sum is equal to other half
def isLucky(n):
half = len(list(n)) // 2
sum1 = 0
sum2 = 0
for i in n[:half]:
sum1 += int(i)
for j in n[half:]:
sum2 += int(j)
return sum1 == sum2
# tests
print('the ticket with "134008" is lucky: true = ',isLucky('134008'))
print('the ticket with "239017" is lucky: false = ',isLucky('239017'))
# codesignal level3 n4 - sort low to high humans ignoring trees
def sortByHeight(a):
new = []
tmp = []
for v in a:
if v != -1:
tmp.append(v)
tmp.sort()
z = 0
for j,x in enumerate(a):
if x == -1:
new.insert(j, x)
else:
new.insert(j, tmp[z])
z += 1
return new
# tests
print('sorted: ',sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]))
print('sorted: ',sortByHeight([23, 54, -1, 43, 1, -1, -1, 77, -1, -1, -1, 3]))
# codesignal level3 n5 - invert string in parentheses
def reverseInParentheses(inputString):
stack = []
for x in inputString:
if x == ")":
tmp = ""
while stack[-1] != "(":
tmp += stack.pop()
stack.pop() # pop the (
for item in tmp:
stack.append(item)
else:
stack.append(x)
return "".join(stack)
# tests "(bar)"
print('==========\n1) inverted: ',reverseInParentheses("(bar)")) # expected "rab"
print('==========\n2) inverted: ',reverseInParentheses("foo(bar)baz")) # expected "foorabbaz"
print('==========\n3) inverted: ',reverseInParentheses("foo(bar)baz(blim)")) # expected "foorabbazmilb"
print('==========\n4) inverted: ',reverseInParentheses("foo(bar(baz))blim")) # expected "foobazrabblim"
# codesignal level4 n1 - alternating sums
def alternatingSums(a):
return [sum(a[::2]), sum(a[1::2])]
# tests
print('==========\n1) inverted: ',alternatingSums([50, 60, 60, 45, 70])) # expected [180, 105]
print('==========\n2) inverted: ',alternatingSums([100, 50])) # expected [100, 50]
print('==========\n3) inverted: ',alternatingSums([100, 50, 10, 20, 30, 40])) # expected [140, 110]
# codesignal level4 n2 - alternating sums
def addBorder(picture):
output = []
border = ""
for i in range(0,len(picture[0])+2):
border += "*"
output.append(border)
for i in range(0,len(picture)):
output.append("*"+picture[i]+"*")
output.append(border)
return output
# tests
print('==========\n1) bordered: ',addBorder(["abc","ded"])) # expected
print('==========\n2) bordered: ',addBorder(["a"])) # expected
# codesignal level4 n3 - similar when swapping at least 2 array members
def areSimilar(a, b):
if a == b: return True
not_same = []
tmp = b
for i,v in enumerate(a):
# when more than 2 elements values do not match
if len(not_same) > 2: return False # result is false
# when value of same index in both lists do not match
if v != b[i]: not_same.append(i) # remember the value that did not matched
if len(not_same) == 2:
tmp[not_same[1]], tmp[not_same[0]] = b[not_same[0]], b[not_same[1]]
print(f"a: {a}, b: {b}, tmp: {tmp}, not_same: {not_same}")
return True if tmp == a else False
return False
# tests
print('=========\n1) areSimilar is false =', areSimilar([1, 1, 4], [1, 2, 3]))
print('=========\n2) areSimilar is false =', areSimilar([1, 2, 2], [2, 1, 1]))
print('=========\n3) areSimilar false =', areSimilar([832, 998, 148, 570, 533, 561, 894, 147, 455, 279], [832, 570, 148, 998, 533, 561, 455, 147, 894, 279]))
# codesignal level4 n4 -
def arrayChange(inputArray):
sum = 0
q = inputArray[0]
for i in inputArray[1:]:
if i <= q:
sum += q-i+1
q = q+1
else:
q = i
return sum
# tests
print('=========\n1) arrayChange is 3 =', arrayChange([1, 1, 1]))
print('=========\n2) arrayChange is 5 =', arrayChange([-1000, 0, -2, 0]))
# codesignal level4 n5 -
def palindromeRearranging(inputString):
r = {}
for v in inputString:
if v not in r:
r[v] = 1
else:
r[v] += 1
count = [x for x in r if r[x] % 2]
if len(count) > 1:
return False
else:
return True
# tests
print('=========\n1) palindromeRearranging is true =', palindromeRearranging("aabb"))
print('=========\n2) palindromeRearranging is false =', palindromeRearranging("abca"))
# codesignal level5 n1 -
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
return True if yourLeft == friendsLeft and yourRight == friendsRight or yourLeft == friendsRight and yourRight == friendsLeft else False
# tests
print('=========\n1) areEquallyStrong is true =', areEquallyStrong(10, 15, 15, 10))
print('=========\n2) areEquallyStrong is false =', areEquallyStrong(15, 10, 15, 9))
# codesignal level5 n2 -
def arrayMaximalAdjacentDifference(inputArray):
diff = 0
tmp = inputArray[0]
for i in inputArray[1:]:
if tmp > i and diff < tmp - i:
diff = tmp - i
if tmp < i and diff < i - tmp:
diff = i - tmp
tmp = i
return diff
# tests
print('=========\n1) arrayMaximalAdjacentDifference is 2 =',
arrayMaximalAdjacentDifference([10, 11, 13]))
print('=========\n2) arrayMaximalAdjacentDifference is 0 =',
arrayMaximalAdjacentDifference([1, 1, 1, 1]))
print('=========\n3) arrayMaximalAdjacentDifference is 7 =',
arrayMaximalAdjacentDifference([-1, 4, 10, 3, -2]))
# codesignal level5 n3 -
def isIPv4Address(inputString):
splited = inputString.split('.')
if len(splited) != 4:
return False
for x in splited:
if x == '' or not x.isdigit() or int(x) < 0 or 255 < int(x):
return False
return True
# tests
print('=========\n1) isIPv4Address is true =', isIPv4Address("172.16.254.1"))
print('=========\n2) isIPv4Address is false =', isIPv4Address("172.316.254.1"))
print('=========\n3) isIPv4Address is false =', isIPv4Address(".254.255.0"))
# codesignal 22
def avoidObstacles(inputArray):
for i in range(1, max(inputArray)):
divs = any([x for x in inputArray if not x%i])
if not divs:
return i
return max(inputArray) + 1
# tests
print(avoidObstacles([5, 3, 6, 7, 9]))
print(avoidObstacles([2, 3]))
print(avoidObstacles([1, 4, 10, 6, 2]))
# codesignal 23
def pixel(matrix,i,j):
total = 0
for x in range(i - 1, i + 2):
for y in range(j - 1, j + 2):
total += matrix[x][y]
return total//9
def boxBlur(image):
sol = []
row = len(image)
col = len(image[0])
for i in range(1, row - 1):
temp = []
for j in range(1, col - 1):
temp.append(pixel(image, i, j))
sol.append(temp)
return sol
# tests
print(boxBlur([[1,1,1],
[1,7,1],
[1,1,1]]), 'result should be: [[1]]')
print(boxBlur([[36,0,18,9],
[27,54,9,0],
[81,63,72,45]]), 'result should be: [[40,30]]')
|
Venckus/tribeofai_workshop_class_e
|
study/codesignal_intro.py
|
codesignal_intro.py
|
py
| 11,981 |
python
|
en
|
code
| 0 |
github-code
|
6
|
26048697220
|
from sept.errors import OperatorNotFoundError, OperatorNameAlreadyExists
class OperatorManager(object):
def __init__(self):
super(OperatorManager, self).__init__()
self._cache = {}
from sept.builtin.operators import ALL_OPERATORS
for operator_klass in ALL_OPERATORS:
self._cache[operator_klass.name] = operator_klass
@property
def operators(self):
# Don't include the NULL operator
return sorted(
filter(lambda op: op._private is False, self._cache.values()),
key=lambda op: op.name,
)
def add_custom_operators(self, custom_operators, dont_overwrite=True):
for custom_operator in custom_operators:
if custom_operator.name in self._cache and dont_overwrite:
raise OperatorNameAlreadyExists(
"An Operator with the name {name} already exists as "
"{value}. If you wish to overwrite that value, make sure "
"you pass `dont_overwrite=True` when adding custom "
"operators.".format(
name=custom_operator.name,
value=self._cache[custom_operator.name],
)
)
self._cache[custom_operator.name] = custom_operator()
def getOperator(self, operator_name, args=None):
if operator_name in self._cache:
operator_klass = self._cache[operator_name]
return operator_klass.create(args)
raise OperatorNotFoundError(
"Could not find an Operator with the name {}".format(operator_name)
)
|
Ahuge/sept
|
sept/operator_manager.py
|
operator_manager.py
|
py
| 1,654 |
python
|
en
|
code
| 8 |
github-code
|
6
|
72940803068
|
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import os, requests, json
# python request examples
# https://www.pythonforbeginners.com/requests/using-requests-in-python
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
def restexample01():
github_url = "https://api.github.com/user/repos"
data = json.dumps({'name': 'test', 'description': 'some test repo'})
r = requests.post(github_url, data, auth=('user', '*****'))
print(r.json)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
restexample01()
print_hi("PyCharm. It's end of the code")
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
lean35/python101
|
main.py
|
main.py
|
py
| 915 |
python
|
en
|
code
| 0 |
github-code
|
6
|
70132131389
|
from typing import Tuple
from sqlalchemy import and_, desc
from quizard_backend import db
from quizard_backend.utils.exceptions import raise_not_found_exception
from quizard_backend.utils.transaction import in_transaction
def dict_to_filter_args(model, **kwargs):
"""
Convert a dictionary to Gino/SQLAlchemy's conditions for filtering.
Example:
A correct Gino's query is:
User.query.where(
and_(
User.role_id == 10,
User.location == "Singapore"
)
).gino.all()
The given `kwargs` is:
{
"role_id": 10,
"location": "Singapore",
}
This function unpacks the given dictionary `kwargs`
into `and_(*clauses)`.
"""
return (getattr(model, k) == v for k, v in kwargs.items())
async def get_one(model, **kwargs):
return (
await model.query.where(and_(*dict_to_filter_args(model, **kwargs)))
.limit(1)
.gino.first()
)
async def get_many(
model,
columns=None,
after_id=None,
limit=15,
in_column=None,
in_values=None,
order_by="internal_id",
descrease=False,
**kwargs,
):
# Get the `internal_id` value from the starting row
# And use it to query the next page of results
last_internal_id = 0
if after_id:
row_of_after_id = await model.query.where(model.id == after_id).gino.first()
if not row_of_after_id:
raise_not_found_exception(model, **kwargs)
last_internal_id = row_of_after_id.internal_id
# Get certain columns only
if columns:
query = db.select([*(getattr(model, column) for column in columns)])
else:
query = model.query
query = query.where(
and_(
*dict_to_filter_args(model, **kwargs),
model.internal_id < last_internal_id
if descrease and last_internal_id
else model.internal_id > last_internal_id,
getattr(model, in_column).in_(in_values)
if in_column and in_values
else True,
)
)
return (
await query.order_by(
desc(getattr(model, order_by)) if descrease else getattr(model, order_by)
)
.limit(limit)
.gino.all()
)
async def get_latest_quiz_attempts(model, user_id, limit=15, after_id=None, **kwargs):
# Get the `internal_id` value from the starting row
# And use it to query the next page of results
last_internal_id = 0
if after_id:
row_of_after_id = await model.query.where(model.id == after_id).gino.first()
if not row_of_after_id:
raise_not_found_exception(model, **kwargs)
last_internal_id = row_of_after_id.internal_id
return (
await db.status(
db.text(
"""SELECT * FROM (
SELECT DISTINCT ON (quiz_attempt.quiz_id, quiz_attempt.user_id)
quiz_attempt.quiz_id,
quiz_attempt.user_id,
quiz_attempt.is_finished,
quiz_attempt.internal_id
FROM quiz_attempt
WHERE quiz_attempt.user_id = :user_id {}
ORDER BY
quiz_attempt.quiz_id,
quiz_attempt.user_id,
quiz_attempt.internal_id DESC
) t
ORDER By t.internal_id DESC limit :limit;""".format(
"and quiz_attempt.internal_id < :last_internal_id"
if after_id
else ""
)
),
{"user_id": user_id, "limit": limit, "last_internal_id": last_internal_id},
)
)[1]
async def get_one_latest(model, **kwargs):
return (
await model.query.where(and_(*dict_to_filter_args(model, **kwargs)))
.order_by(desc(model.internal_id))
.limit(1)
.gino.first()
)
async def get_many_with_count_and_group_by(
model, *, columns, in_column=None, in_values=None
):
return (
await db.select(
[*[getattr(model, column) for column in columns], db.func.count()]
)
.where(
getattr(model, in_column).in_(in_values)
if in_column and in_values
else True
)
.group_by(*[getattr(model, column) for column in columns])
.gino.all()
)
@in_transaction
async def create_one(model, **kwargs):
return await model(**kwargs).create()
@in_transaction
async def update_one(row, **kwargs):
if not kwargs:
return row
await row.update(**kwargs).apply()
return row
@in_transaction
async def update_many(model, get_kwargs, update_kwargs):
status: Tuple[str, list] = await model.update.values(**update_kwargs).where(
and_(*and_(*dict_to_filter_args(model, **get_kwargs)))
).gino.status()
return status[0]
@in_transaction
async def delete_many(model, **kwargs):
status: Tuple[str, list] = await model.delete.where(
and_(*dict_to_filter_args(model, **kwargs))
).gino.status()
return status[0]
|
donjar/quizard
|
api/quizard_backend/utils/query.py
|
query.py
|
py
| 5,219 |
python
|
en
|
code
| 5 |
github-code
|
6
|
8255764779
|
from xadrez.tabuleiro.Cor import Cor
from xadrez.tabuleiro.Peca import Peca
from xadrez.tabuleiro.Posicao import Posicao
from xadrez.xadrez.Torre import Torre
class Rei(Peca):
def __init__(self, tab, cor, partida):
super().__init__(tab, cor)
self.partida = partida
def __str__(self):
return "R"
def podeMover(self, pos):
p = self.tabuleiro.peca(pos)
return p == None or p.cor != self.cor
def __crie_matriz(self, n_linhas, n_colunas):
matriz = []
valor = False
for _ in range(n_linhas):
linha = []
for _ in range(n_colunas):
linha += [valor]
matriz += [linha]
return matriz
def existeInimigo(self, pos):
p = self.tabuleiro.peca(pos)
return p != None and p.cor != self.cor
def testeTorreParaRoque(self, pos):
p = self.tabuleiro.peca(pos)
return p != None and isinstance(p, Torre) and p.cor != self.cor and p.qteMovimentos == 0
def movimentosPossiveis(self):
mat = self.__crie_matriz(self.tabuleiro.linhas, self.tabuleiro.colunas)
posicao = Posicao(0, 0)
# ESQUERDA
posicao.definirValores(self.posicao.linha, self.posicao.coluna - 1)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
# DIREITA
posicao.definirValores(self.posicao.linha, self.posicao.coluna + 1)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
# ACIMA
posicao.definirValores(self.posicao.linha - 1, self.posicao.coluna)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
# ABAIXO
posicao.definirValores(self.posicao.linha + 1, self.posicao.coluna - 1)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
# NO
posicao.definirValores(self.posicao.linha - 1, self.posicao.coluna - 1)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
# NE
posicao.definirValores(self.posicao.linha - 1, self.posicao.coluna + 1)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
# SE
posicao.definirValores(self.posicao.linha + 1, self.posicao.coluna + 1)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
# SO
posicao.definirValores(self.posicao.linha + 1, self.posicao.coluna - 1)
if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
mat[posicao.linha][posicao.coluna] = True
if (self.qteMovimentos == 0 and not self.partida.xeque):
posT1 = Posicao(self.posicao.linha, self.posicao.coluna + 3)
if (self.testeTorreParaRoque(posT1)):
p1 = Posicao(posicao.linha, posicao.coluna + 1)
p2 = Posicao(posicao.linha, posicao.coluna + 2)
if (self.tabuleiro.peca(p1) == None and self.tabuleiro.peca(p2) == None):
mat[posicao.linha][posicao.coluna + 2] = True
posT2 = Posicao(self.posicao.linha, self.posicao.coluna - 4)
if (self.testeTorreParaRoque(posT2)):
p1 = Posicao(posicao.linha, posicao.coluna - 1)
p2 = Posicao(posicao.linha, posicao.coluna - 2)
p3 = Posicao(posicao.linha, posicao.coluna - 3)
if (not any([self.tabuleiro.peca(p1), self.tabuleiro.peca(p2), self.tabuleiro.peca(p3)])):
mat[posicao.linha][posicao.coluna - 2] = True
return mat
|
josuelopes512/xadrez_python
|
xadrez/xadrez/Rei.py
|
Rei.py
|
py
| 4,027 |
python
|
pt
|
code
| 0 |
github-code
|
6
|
74199244988
|
from db import Mysql_Object
import tkinter as tk
import random as rd
import tkinter.messagebox as msgbox
class manage_page:
def __init__(self, master):
# 连接数据库
self.sql = Mysql_Object('localhost', 'root', '123456', 'parkinglot_management')
self.win = master
self.win.resizable(0, 0)
self.win.title('入场管理界面')
# 窗口居中
ww, wh = 800, 400
sw, sh = self.win.winfo_screenwidth(), self.win.winfo_screenheight()
x, y = (sw - ww) / 2, (sh - wh) / 2
self.win.geometry("%dx%d+%d+%d" % (ww, wh, x, y))
# 搭建存储文本框的frame
self.f1 = tk.Frame(self.win, width=ww - 20, height=wh - 80, bg="lightgreen")
self.f1.pack(padx=10, pady=10)
# 创建多行文本框
self.t1 = tk.Text(self.f1, width=ww - 40, height=21)
self.t1.pack(side="top", padx=10, pady=10)
lb = tk.Label(self.win, text="工号: ")
lb.pack(side="left", padx=10, anchor="nw")
show_free = tk.Label(self.win, text=self.get_id())
show_free.pack(side='left', padx=10, anchor='nw')
# var_num = tk.IntVar()
# e1 = tk.Entry(window, textvariable=var_num)
# e1.pack(side="left", padx=10, pady=10, anchor="sw")
lb2 = tk.Label(self.win, text='输入车牌:')
lb2.pack(side='left', padx=10, anchor='nw')
self.var_spot = tk.StringVar()
e_spot = tk.Entry(self.win, textvariable=self.var_spot, width=5)
e_spot.pack(side='left', padx=15, anchor='nw')
btn_cf = tk.Button(self.win, text="查看预约", command=self.search_reserve)
btn_cf.pack(side="left", padx=10, anchor="nw")
lb3 = tk.Label(self.win, text='选择车位:')
lb3.pack(side='left', padx=10, anchor='nw')
self.chosen_no = tk.IntVar()
e_spot = tk.Entry(self.win, textvariable=self.chosen_no, width=5)
e_spot.pack(side='left', padx=10, anchor='nw')
btn_sel = tk.Button(self.win, text="查询空闲车位", command=self.select_spot)
btn_sel.pack(side="left", padx=10, anchor="nw")
btn_cfs = tk.Button(self.win, text='确认车位', command=self.cf_spot)
btn_cfs.pack(side="left", padx=10, anchor="nw")
btn_del = tk.Button(self.win, text="通行", command=self.let_goin)
btn_exit = tk.Button(self.win, text="退出", command=self.win.destroy)
# 放置
btn_exit.pack(side="right", padx=10, pady=10, anchor="se")
btn_del.pack(side="right", pady=10, anchor="se")
#获取工号
def get_id(self):
msg = self.get_msg()[0].strip().strip("'")
return msg
# 查看空闲车位信息
def select_spot(self):
self.t1.delete(1.0, tk.END)
self.t1.insert(1.0, "车位号\t\t车辆标签\t\t车位类型\t\t占用状态\n")
msg = self.sql.select_sql("select * from parkingspot where Slabel='临时' and Sstate='未占用'")[1]
# print(msg)
for spot in msg:
self.t1.insert('end', "{}\t\t{}\t\t{}\t\t{}\n".format(spot[0], spot[1], spot[2], spot[3]))
#这里返回查询的预约记录
def search_reserve(self):
# print(self.var_spot)
msg = "select * from parkingspot where Cno='{}'".format(self.var_spot.get())
msg = self.sql.select_sql(msg)
self.t1.delete(1.0, tk.END)
self.t1.insert(1.0, "车位号\t\t车辆标签\t\t车位类型\t\t占用状态\t\t车牌号\t\t预约时间\t\t预约状态\n")
for msg in msg[1]:
self.t1.insert('end', "{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\n".format(msg[0], msg[1], msg[2], msg[3], msg[4], msg[5], msg[7]))
# 确认车位
def cf_spot(self):
msg = "update parkingspot set Sstate='占用', Cno='{}', Suse_time='{}' where Sno='{}'".format(self.var_spot.get(), self.get_randusetiem(), self.chosen_no.get())
self.sql.excute_sql(msg)
msgbox.showinfo(message="确认成功")
self.select_spot()
# 获得随机使用时间
def get_randusetiem(self):
return rd.randint(10, 300)
#这里实现通行
def let_goin(self):
#这里写入通行逻辑操作
msgbox.showinfo(message="车辆已入场")
def get_msg(self):
with open('current_user.text', 'r') as f:
msg = f.read().strip('(').strip(')').split(',')
# print(msg)
return msg
if __name__ == '__main__':
window = tk.Tk()
manage_page(window)
window.mainloop()
|
jmzdmj/ParkingLotSystem
|
ParkingLotSystem/managein_page.py
|
managein_page.py
|
py
| 4,638 |
python
|
en
|
code
| 0 |
github-code
|
6
|
1883488340
|
import sys
import pefile
import re
# Pega os headers de um executável
def get_headers(executable):
pe = pefile.PE(executable)
sections = []
for section in pe.sections:
sections.append(section.Name.decode('utf-8'))
return sections
# Pega os headers dos argumentos de entrada
sections1 = get_headers(sys.argv[1])
sections2 = get_headers(sys.argv[2])
# Imprime a intersecção entre as listas
commonSections = list(set(sections1).intersection(sections2))
print("Seções comuns: [", end="")
for i, section in enumerate(commonSections):
print("'{}'".format(section), end="")
if i < len(commonSections) - 1:
print(', ', end="")
print("]\n")
# Imprime a diferença da lista 1 para a lista 2
difference12 = list(set(sections1).difference(sections2))
print(re.sub(".*/", "", sys.argv[1]) + ": [", end="")
for i, section in enumerate(difference12):
print("'{}'".format(section), end="")
if i < len(difference12) - 1:
print(', ', end="")
print("]\n")
# Imprime a diferença da lista 2 para a lista 1
difference21 = list(set(sections2).difference(sections1))
print(re.sub(".*/", "", sys.argv[2]) + ": [", end="")
for i, section in enumerate(difference21):
print("'{}'".format(section), end="")
if i < len(difference21) - 1:
print(', ', end="")
print("]\n")
|
kkatzer/CDadosSeg
|
T2/Parte2/T2P2b.py
|
T2P2b.py
|
py
| 1,323 |
python
|
en
|
code
| 0 |
github-code
|
6
|
19167053066
|
"""
Common utilities for derp used by various classes.
"""
from collections import namedtuple
import cv2
from datetime import datetime
import heapq
import logging
import pathlib
import numpy as np
import os
import socket
import time
import yaml
import zmq
import capnp
import messages_capnp
Bbox = namedtuple("Bbox", ["x", "y", "w", "h"])
TOPICS = {
"camera": messages_capnp.Camera,
"controller": messages_capnp.Controller,
"action": messages_capnp.Action,
"imu": messages_capnp.Imu,
"quality": messages_capnp.Quality,
}
DERP_ROOT = pathlib.Path(os.environ["DERP_ROOT"])
MODEL_ROOT = DERP_ROOT / "models"
RECORDING_ROOT = DERP_ROOT / "recordings"
CONFIG_ROOT = DERP_ROOT / "config"
MSG_STEM = "/tmp/derp_"
def is_already_running(path):
""" For the given PID path check if the PID exists """
if isinstance(path, str):
path = pathlib.Path(path)
if not path.exists():
return False
with open(str(path)) as pid_file:
pid = int(pid_file.read())
try:
os.kill(pid, 0)
except OSError:
return False
return True
def write_pid(path):
with open(str(path), 'w') as pid_file:
pid_file.write(str(os.getpid()))
pid_file.flush()
def init_logger(name, recording_path, level=logging.INFO):
logger = logging.getLogger(name)
formatter = logging.Formatter('%(asctime)s %(levelname)-5s %(message)s')
fileHandler = logging.FileHandler(recording_path / ('%s.log' % name), mode='w')
fileHandler.setFormatter(formatter)
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(formatter)
logger.setLevel(level)
logger.addHandler(fileHandler)
logger.addHandler(streamHandler)
return logger
def make_recording_path():
date = datetime.utcfromtimestamp(time.time()).strftime("%Y%m%d-%H%M%S")
folder = RECORDING_ROOT / ("recording-%s-%s" % (date, socket.gethostname()))
folder.mkdir(parents=True)
return folder
def get_timestamp():
return int(time.time() * 1e9)
def publisher(path):
context = zmq.Context()
sock = context.socket(zmq.PUB)
sock.bind("ipc://" + path)
# sock.bind("tcp://*:%s" % port)
return context, sock
def subscriber(paths):
context = zmq.Context()
sock = context.socket(zmq.SUB)
# sock.connect("tcp://localhost:%s" % port)
for path in paths:
sock.connect("ipc://" + path)
sock.setsockopt(zmq.SUBSCRIBE, b"")
return context, sock
def topic_file_reader(folder, topic):
return open("%s/%s.bin" % (folder, topic), "rb")
def topic_exists(folder, topic):
path = folder / ("%s.bin" % topic)
return path.exists()
def topic_file_writer(folder, topic):
return open("%s/%s.bin" % (folder, topic), "wb")
def print_image_config(name, config):
""" Prints some useful variables about the camera for debugging purposes """
top = config["pitch"] + config["vfov"] / 2
bot = config["pitch"] - config["vfov"] / 2
left = config["yaw"] - config["hfov"] / 2
right = config["yaw"] + config["hfov"] / 2
hppd = config["width"] / config["hfov"]
vppd = config["height"] / config["vfov"]
print(
"%s top: %6.2f bot: %6.2f left: %6.2f right: %6.2f hppd: %5.1f vppd: %5.1f"
% (name, top, bot, left, right, hppd, vppd)
)
def get_patch_bbox(target_config, source_config):
"""
Gets a different sub-persepective given a smaller desired hfov/vfov and different yaw/pitch
"""
hfov_ratio = target_config["hfov"] / source_config["hfov"]
vfov_ratio = target_config["vfov"] / source_config["vfov"]
hfov_offset = source_config["yaw"] - target_config["yaw"]
vfov_offset = source_config["pitch"] - target_config["pitch"]
patch_width = int(source_config["width"] * hfov_ratio + 0.5)
patch_height = int(source_config["height"] * vfov_ratio + 0.5)
x_center = (source_config["width"] - patch_width) // 2
y_center = (source_config["height"] - patch_height) // 2
x_offset = int(hfov_offset / source_config["hfov"] * source_config["width"] + 0.5)
y_offset = int(vfov_offset / source_config["vfov"] * source_config["height"] + 0.5)
x = x_center + x_offset
y = y_center + y_offset
if (x >= 0 and x + patch_width <= source_config["width"] and
y >= 0 and y + patch_height <= source_config["height"]):
return Bbox(x, y, patch_width, patch_height)
return None
def crop(image, bbox):
""" Crops the Bbox(x,y,w,h) from the image. Copy indicates to copy of the ROI"s memory"""
return image[bbox.y : bbox.y + bbox.h, bbox.x : bbox.x + bbox.w]
def resize(image, size):
""" Resize the image to the target (w, h) """
is_larger = size[0] > image.shape[1] or size[1] > image.shape[0]
interpolation = cv2.INTER_LINEAR if is_larger else cv2.INTER_AREA
return cv2.resize(image, size, interpolation=interpolation)
def perturb(frame, camera_config, shift=0, rotate=0):
# Estimate how many pixels to rotate by, assuming fixed degrees per pixel
pixels_per_degree = camera_config["width"] / camera_config["hfov"]
# Figure out where the horizon is in the image
horizon_frac = ((camera_config["vfov"] / 2) + camera_config["pitch"]) / camera_config["vfov"]
# For each row in the frame shift/rotate it
indexs = np.arange(len(frame))
vertical_fracs = np.linspace(0, 1, len(frame))
# For each vertical line, apply shift/rotation rolls
for index, vertical_frac in zip(indexs, vertical_fracs):
magnitude = rotate * pixels_per_degree
if vertical_frac > horizon_frac:
ground_angle = (vertical_frac - horizon_frac) * camera_config["vfov"]
ground_distance = camera_config["z"] / np.tan(deg2rad(ground_angle))
ground_width = 2 * ground_distance * np.tan(deg2rad(camera_config["hfov"]) / 2)
magnitude += (shift / ground_width) * camera_config["width"]
magnitude = int(magnitude + 0.5 * np.sign(magnitude))
if magnitude > 0:
frame[index, magnitude:, :] = frame[index, : frame.shape[1] - magnitude]
frame[index, :magnitude, :] = 0
elif magnitude < 0:
frame[index, :magnitude, :] = frame[index, abs(magnitude) :]
frame[index, frame.shape[1] + magnitude :] = 0
return frame
def deg2rad(val):
return val * np.pi / 180
def rad2deg(val):
return val * 180 / np.pi
def load_image(path):
return cv2.imread(str(path))
def save_image(path, image):
return cv2.imwrite(str(path), image)
def load_config(config_path):
""" Load a configuration file, also reading any component configs """
with open(str(config_path)) as config_fd:
config = yaml.load(config_fd, Loader=yaml.FullLoader)
for component in config:
if isinstance(config[component], dict) and "path" in config[component]:
component_path = CONFIG_ROOT / config[component]["path"]
with open(str(component_path)) as component_fd:
component_config = yaml.load(component_fd, Loader=yaml.FullLoader)
component_config.update(config[component])
config[component] = component_config
if "name" not in config[component]:
config[component]["name"] = component_path.stem
if "name" not in config:
config["name"] = config_path.stem
return config
def dump_config(config, config_path):
""" Write a configuration file """
with open(str(config_path), 'w') as config_fd:
yaml.dump(config, config_fd)
def extract_latest(desired_times, source_times, source_values):
out = []
pos = 0
val = 0
for desired_time in desired_times:
while pos < len(source_times) and source_times[pos] < desired_time:
val = source_values[pos]
pos += 1
out.append(val)
return np.array(out)
def load_topics(folder):
if isinstance(folder, str):
folder = pathlib.Path(folder)
out = {}
for topic in TOPICS:
if not topic_exists(folder, topic):
continue
topic_fd = topic_file_reader(folder, topic)
out[topic] = [msg for msg in TOPICS[topic].read_multiple(topic_fd)]
topic_fd.close()
return out
def replay(topics):
heap = []
for topic in topics:
for msg in topics[topic]:
heapq.heappush(heap, [msg.publishNS, topic, msg])
while heap:
yield heapq.heappop(heap)
def decode_jpg(jpg):
return cv2.imdecode(np.frombuffer(jpg, np.uint8), cv2.IMREAD_COLOR)
def encode_jpg(image, quality):
return cv2.imencode(".jpg", image, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tostring()
def extract_car_actions(topics):
out = []
autonomous = False
speed_offset = 0
steer_offset = 0
for timestamp, topic, msg in replay(topics):
if topic == "controller":
autonomous = msg.isAutonomous
speed_offset = msg.speedOffset
steer_offset = msg.steerOffset
elif topic == "action":
if autonomous or msg.isManual:
out.append([timestamp, msg.speed + speed_offset, msg.steer + steer_offset])
if not out:
out.append([0, 0, 0])
return np.array(out)
|
notkarol/derplearning
|
derp/util.py
|
util.py
|
py
| 9,198 |
python
|
en
|
code
| 40 |
github-code
|
6
|
41815384400
|
from urllib import response
import requests
from pprint import pprint
from time import sleep
import os
from sqlalchemy import null
url = "http://10.0.1.10:8080"
# ------------------------ PRINT ------------------------
def menu():
os.system('clear') or None
print("-------------------:-------------------")
print("| 1 | Cadastrar Usuario |")
print("| 2 | Exibir Usuario |")
print("| 3 | Alterar Usuario |")
print("| 4 | Excluir Usuario |")
print("-------------------:-------------------")
print("| 5 | Cadastrar Projeto |")
print("| 6 | Exibir Projeto |")
print("| 7 | Alterar Projeto |")
print("| 8 | Excluir Projeto |")
print("-------------------:-------------------")
print("| 9 | SAIR |")
print("-------------------:-------------------")
def menu1():
os.system('clear') or None
print("-------------------:-------------------")
print("| 1 | Pessoa Física |")
print("| 2 | Pessoa Jurídica Sair[0] |")
print("-------------------:-------------------")
def menu2():
print("-------------------:-------------------")
print("| Deseja alterar? |")
print("| [1] Sim [2] Não |")
print("-------------------:-------------------")
def main():
opc = None
while opc != "9":
menu()
opc = input("Informe uma opcao: ")
if opc == "1": #Cadastrar Usuario
cadastroUser()
elif opc == "2": #Exibir Usuario
exibirUser()
elif opc == "3": #Alterar Usuario
alterarUser()
elif opc == "4": #Excluir Usuario
excluirUser()
elif opc == "5": #Cadastrar Projeto
cadastroProj()
elif opc == "6": #Exibir Projeto
exibirProj()
elif opc == "7": #Alterar Projeto
alterarProj()
elif opc == "8": #Excluir Projeto
excluirProj()
elif opc == "9":
exit()
input("Pressione ENTER para continuar!\n")
def jsonPrint(resp):
if resp.status_code == 200:
pprint(resp.json())
elif resp.status_code == 201:
print("deletado!")
print(resp)
else:
print(resp)
# ------------------------ USER ------------------------
def cadastroUser():
opc = None
while opc != 1 and opc != 2 and opc != 0:
menu1()
opc = input("Informe uma opcao: ")
if opc == "1": #Fisica
nome = input("Informe nome: ")
idade = input("Informe idade: ")
cpf = input("Informe cpf: ")
instEnsino = input("Informe Instuicao de ensino: ")
data = {"nome": nome, "idade": idade, "cpf": cpf, "instEnsino": instEnsino}
requests.post(f"{url}/fisica", json=data)
break
elif opc == "2": #Juridica
nome = input("Informe nome: ")
segmento = input("Informe segmento: ")
cnpj = input("Informe cnpj: ")
data = {"nome": nome, "segmento": segmento, "cnpj": cnpj}
requests.post(f"{url}/juridica", json=data)
break
elif opc == "0":
break
else:
print("Opção invalida!")
input("Pressione ENTER para continuar!\n")
def exibirUser():
opc = None
while opc != 1 and opc != 2 and opc != 0:
menu1()
opc = input("Informe uma opcao: ")
if opc == "1": #Fisica
cpf = input("Informe o cpf: ")
resp = requests.get(f"{url}/fisica/" + cpf)
jsonPrint(resp)
break
elif opc == "2": #Juridica
cnpj = input("Informe o cnpj: ")
resp = requests.get(f"{url}/juridica/" + cnpj)
jsonPrint(resp)
break
elif opc == "0":
break
else:
print("Opção invalida!")
input("Pressione ENTER para continuar!\n")
def alterarUser():
opc = None
while opc != 1 and opc != 2 and opc != 0:
menu1()
opc = input("Informe uma opcao: ")
if opc == "1": #Fisica
cpf = input("Informe o cpf: ")
resp = requests.get(f"{url}/fisica/" + cpf)
jsonPrint(resp)
menu2()
opc1 = input("Informe uma opcao: ")
if opc1 == "1":
nome = input("Informe nome: ")
idade = input("Informe idade: ")
instEnsino = input("Informe Instuicao de ensino: ")
data = {"nome": nome, "idade": idade, "cpf": cpf, "instEnsino": instEnsino}
requests.put(f"{url}/fisica/" + cpf, json=data)
else:
break
input("Pressione ENTER para continuar!\n")
elif opc == "2": #Juridica
cnpj = input("Informe o cnpj: ")
resp = requests.get(f"{url}/juridica/" + cnpj)
jsonPrint(resp)
menu2()
opc1 = input("Informe uma opcao: ")
if opc1 == "1":
nome = input("Informe nome: ")
segmento = input("Informe segmento: ")
data = {"nome": nome, "segmento": segmento, "cnpj": cnpj}
requests.put(f"{url}/juridica/" + cnpj, json=data)
else:
break
elif opc == "0":
break
else:
print("Opção invalida!")
input("Pressione ENTER para continuar!\n")
def excluirUser():
opc = None
while opc != 1 and opc != 2 and opc != 0:
menu1()
opc = input("Informe uma opcao: ")
if opc == "1":
cpf = input("Informe o cpf: ")
resp = requests.delete(f"{url}/fisica/" + cpf)
jsonPrint(resp)
elif opc == "2":
cnpj = input("Informe o cnpj: ")
resp = requests.delete(f"{url}/juridica/" + cnpj)
jsonPrint(resp)
elif opc == "0":
break
else:
print("Opção invalida!")
input("Pressione ENTER para continuar!\n")
# ------------------------ PROJETO ------------------------
def cadastroProj():
cpf = None
cnpj = None
nome = input("Informe nome: ")
segmento = input("Informe o segmento: ")
descricao = input("Informe a descrição: ")
opc = None
while opc != 1 and opc != 2 and opc != 0:
menu1()
opc = input("Informe uma opcao: ")
if opc == "1": #Fisica
cpf = input("Informe cpf: ")
cnpj = "-"
break
elif opc == "2": #Juridica
cnpj = input("Informe cnpj: ")
cpf = "-"
break
elif opc == "0":
break
else:
print("Opção invalida!")
input("Pressione ENTER para continuar!\n")
data = {"nome": nome, "segmento": segmento, "descricao": descricao, "cpf": cpf, "cnpj": cnpj}
requests.post(f"{url}/projeto", json=data)
def exibirProj():
nome = input("Nome do Projeto: ")
resp = requests.get(f"{url}/projeto/" + nome)
jsonPrint(resp)
def alterarProj():
opc = None
while opc != 1 and opc != 2 and opc != 0:
nome = input("Informe o nome: ")
resp = requests.get(f"{url}/projeto/" + nome)
jsonPrint(resp)
menu2()
opc = input("Informe uma opcao: ")
if opc == "1":
newname = input("Informe nome: ")
segmento = input("Informe o segmento: ")
descricao = input("Informe a descrição: ")
data = {"nome": newname, "segmento": segmento, "descricao": descricao}
requests.put(f"{url}/projeto/" + nome, json=data)
break
else:
break
def excluirProj():
nome = input("Informe o nome: ")
resp = requests.delete(f"{url}/projeto/" + nome)
jsonPrint(resp)
if __name__ == "__main__":
main()
|
hencabral/Python-BoxCode-API
|
cliente.py
|
cliente.py
|
py
| 8,346 |
python
|
pt
|
code
| 0 |
github-code
|
6
|
25182089444
|
# adapated from munch 2.5.0
from collections.abc import Mapping
class Munch(dict):
"""A dictionary that provides attribute-style access.
>>> b = Munch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Munch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True
A Munch is a subclass of dict; it supports all the methods a dict does...
>>> sorted(b.keys())
['foo', 'hello']
Including update()...
>>> b.update({ 'ponies': 'are pretty!' }, hello=42)
>>> print (repr(b))
Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
As well as iteration...
>>> sorted([ (k,b[k]) for k in b ])
[('foo', Munch({'lol': True})), ('hello', 42), ('ponies', 'are pretty!')]
And "splats".
>>> "The {knights} who say {ni}!".format(**Munch(knights='lolcats', ni='can haz'))
'The lolcats who say can haz!'
See unmunchify/Munch.toDict, munchify/Munch.fromDict for notes about conversion.
"""
def __init__(self, *args, **kwargs): # pylint: disable=super-init-not-called
self.update(*args, **kwargs)
# only called if k not found in normal places
def __getattr__(self, k):
"""Gets key if it exists, otherwise throws AttributeError.
nb. __getattr__ is only called if key is not found in normal places.
>>> b = Munch(bar='baz', lol={})
>>> b.foo
Traceback (most recent call last):
...
AttributeError: foo
>>> b.bar
'baz'
>>> getattr(b, 'bar')
'baz'
>>> b['bar']
'baz'
>>> b.lol is b['lol']
True
>>> b.lol is getattr(b, 'lol')
True
"""
try:
# Throws exception if not in prototype chain
return object.__getattribute__(self, k)
except AttributeError:
try:
return self[k]
except KeyError as exc:
raise AttributeError(k) from exc
def __setattr__(self, k, v):
"""Sets attribute k if it exists, otherwise sets key k. A KeyError
raised by set-item (only likely if you subclass Munch) will
propagate as an AttributeError instead.
>>> b = Munch(foo='bar', this_is='useful when subclassing')
>>> hasattr(b.values, '__call__')
True
>>> b.values = 'uh oh'
>>> b.values
'uh oh'
>>> b['values']
Traceback (most recent call last):
...
KeyError: 'values'
"""
try:
# Throws exception if not in prototype chain
object.__getattribute__(self, k)
except AttributeError:
try:
self[k] = v
except KeyError as exc:
raise AttributeError(k) from exc
else:
object.__setattr__(self, k, v)
def __delattr__(self, k):
"""Deletes attribute k if it exists, otherwise deletes key k. A KeyError
raised by deleting the key--such as when the key is missing--will
propagate as an AttributeError instead.
>>> b = Munch(lol=42)
>>> del b.lol
>>> b.lol
Traceback (most recent call last):
...
AttributeError: lol
"""
try:
# Throws exception if not in prototype chain
object.__getattribute__(self, k)
except AttributeError:
try:
del self[k]
except KeyError as exc:
raise AttributeError(k) from exc
else:
object.__delattr__(self, k)
def toDict(self):
"""Recursively converts a munch back into a dictionary.
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> sorted(b.toDict().items())
[('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')]
See unmunchify for more info.
"""
return unmunchify(self)
@property
def __dict__(self):
return self.toDict()
def __repr__(self):
"""Invertible* string-form of a Munch.
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> print (repr(b))
Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
>>> eval(repr(b))
Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
>>> with_spaces = Munch({1: 2, 'a b': 9, 'c': Munch({'simple': 5})})
>>> print (repr(with_spaces))
Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})
>>> eval(repr(with_spaces))
Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})
(*) Invertible so long as collection contents are each repr-invertible.
"""
return f"{self.__class__.__name__}({dict.__repr__(self)})"
def __dir__(self):
return list(self.keys())
def __getstate__(self):
"""Implement a serializable interface used for pickling.
See https://docs.python.org/3.6/library/pickle.html.
"""
return {k: v for k, v in self.items()}
def __setstate__(self, state):
"""Implement a serializable interface used for pickling.
See https://docs.python.org/3.6/library/pickle.html.
"""
self.clear()
self.update(state)
__members__ = __dir__ # for python2.x compatibility
@classmethod
def fromDict(cls, d):
"""Recursively transforms a dictionary into a Munch via copy.
>>> b = Munch.fromDict({'urmom': {'sez': {'what': 'what'}}})
>>> b.urmom.sez.what
'what'
See munchify for more info.
"""
return munchify(d, cls)
def copy(self):
return type(self).fromDict(self)
def update(self, *args, **kwargs):
"""
Override built-in method to call custom __setitem__ method that may
be defined in subclasses.
"""
for k, v in dict(*args, **kwargs).items():
self[k] = v
def get(self, k, d=None):
"""
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
"""
if k not in self:
return d
return self[k]
def setdefault(self, k, d=None):
"""
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
"""
if k not in self:
self[k] = d
return self[k]
def munchify(x):
"""Recursively transforms a dictionary into a Munch via copy.
>>> b = munchify({'urmom': {'sez': {'what': 'what'}}})
>>> b.urmom.sez.what
'what'
munchify can handle intermediary dicts, lists and tuples (as well as
their subclasses), but ymmv on custom datatypes.
>>> b = munchify({ 'lol': ('cats', {'hah':'i win again'}),
... 'hello': [{'french':'salut', 'german':'hallo'}] })
>>> b.hello[0].french
'salut'
>>> b.lol[1].hah
'i win again'
nb. As dicts are not hashable, they cannot be nested in sets/frozensets.
"""
# Munchify x, using `seen` to track object cycles
seen = dict()
def munchify_cycles(obj):
# If we've already begun munchifying obj, just return the already-created munchified obj
try:
return seen[id(obj)]
except KeyError:
pass
# Otherwise, first partly munchify obj (but without descending into any lists or dicts) and save that
seen[id(obj)] = partial = pre_munchify(obj)
# Then finish munchifying lists and dicts inside obj (reusing munchified obj if cycles are encountered)
return post_munchify(partial, obj)
def pre_munchify(obj):
# Here we return a skeleton of munchified obj, which is enough to save for later (in case
# we need to break cycles) but it needs to filled out in post_munchify
if isinstance(obj, Mapping):
return Munch({})
elif isinstance(obj, list):
return type(obj)()
elif isinstance(obj, tuple):
type_factory = getattr(obj, "_make", type(obj))
return type_factory(munchify_cycles(item) for item in obj)
else:
return obj
def post_munchify(partial, obj):
# Here we finish munchifying the parts of obj that were deferred by pre_munchify because they
# might be involved in a cycle
if isinstance(obj, Mapping):
partial.update((k, munchify_cycles(obj[k])) for k in obj.keys())
elif isinstance(obj, list):
partial.extend(munchify_cycles(item) for item in obj)
elif isinstance(obj, tuple):
for item_partial, item in zip(partial, obj):
post_munchify(item_partial, item)
return partial
return munchify_cycles(x)
def unmunchify(x):
"""Recursively converts a Munch into a dictionary.
>>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
>>> sorted(unmunchify(b).items())
[('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')]
unmunchify will handle intermediary dicts, lists and tuples (as well as
their subclasses), but ymmv on custom datatypes.
>>> b = Munch(foo=['bar', Munch(lol=True)], hello=42,
... ponies=('are pretty!', Munch(lies='are trouble!')))
>>> sorted(unmunchify(b).items()) #doctest: +NORMALIZE_WHITESPACE
[('foo', ['bar', {'lol': True}]), ('hello', 42), ('ponies', ('are pretty!', {'lies': 'are trouble!'}))]
nb. As dicts are not hashable, they cannot be nested in sets/frozensets.
"""
# Munchify x, using `seen` to track object cycles
seen = dict()
def unmunchify_cycles(obj):
# If we've already begun unmunchifying obj, just return the already-created unmunchified obj
try:
return seen[id(obj)]
except KeyError:
pass
# Otherwise, first partly unmunchify obj (but without descending into any lists or dicts) and save that
seen[id(obj)] = partial = pre_unmunchify(obj)
# Then finish unmunchifying lists and dicts inside obj (reusing unmunchified obj if cycles are encountered)
return post_unmunchify(partial, obj)
def pre_unmunchify(obj):
# Here we return a skeleton of unmunchified obj, which is enough to save for later (in case
# we need to break cycles) but it needs to filled out in post_unmunchify
if isinstance(obj, Mapping):
return dict()
elif isinstance(obj, list):
return type(obj)()
elif isinstance(obj, tuple):
type_factory = getattr(obj, "_make", type(obj))
return type_factory(unmunchify_cycles(item) for item in obj)
else:
return obj
def post_unmunchify(partial, obj):
# Here we finish unmunchifying the parts of obj that were deferred by pre_unmunchify because they
# might be involved in a cycle
if isinstance(obj, Mapping):
partial.update((k, unmunchify_cycles(obj[k])) for k in obj.keys())
elif isinstance(obj, list):
partial.extend(unmunchify_cycles(v) for v in obj)
elif isinstance(obj, tuple):
for value_partial, value in zip(partial, obj):
post_unmunchify(value_partial, value)
return partial
return unmunchify_cycles(x)
|
SAIL-Labs/AMICAL
|
amical/externals/munch/__init__.py
|
__init__.py
|
py
| 11,370 |
python
|
en
|
code
| 9 |
github-code
|
6
|
37568054562
|
# import libraries
import sys
import nltk
nltk.download(['punkt', 'wordnet', 'stopwords'])
import re
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline
import pickle
def load_data(database_filepath):
"""
Loads table from database as a Pandas Dataframe
and returns the following:
X -- feature dataset containing the messages to be
categorized
y -- label dataset containing the 36 categories that each
message is assigned to.
category_names -- list containing category names
Keyword arguments:
database_filepath -- filepath (including file name)
of the database containing the
messages and categories
"""
engine = create_engine('sqlite:///' + database_filepath)
df = pd.read_sql_table('messages_and_categories', engine)
X = df['message']
y = df.drop(columns=['id', 'message', 'original', 'genre'])
category_names = list(y.columns)
return X, y, category_names
def tokenize(text):
"""
Cleans, tokenizes, lemmatizes messages in preparation for
classification algorithm
1) finds and replaces urls with a placeholder
2) finds and replaces non alphanumeric characters with a space
3) removes stop words from tokenized messages
4) strips leading and trailing spaces and lowcases lemmatized
tokens
Keyword arguments:
text -- raw message that will be cleaned, tokenized
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
detected_urls = re.findall(url_regex, text)
for url in detected_urls:
text = text.replace(url, "urlplaceholder")
text = re.sub(r'\W+', ' ', text)
tokens = word_tokenize(text)
tokens = [t for t in tokens if t not in stopwords.words("english")]
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).lower().strip()
clean_tokens.append(clean_tok)
return clean_tokens
def build_model():
"""
Creates a pipeline and grid search for hyperparameter tuning
returns pipeline with the specified parameter search space
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(estimator=AdaBoostClassifier()))
])
# specify parameters for grid search
parameters = {
'vect__ngram_range': ((1, 1), (1, 2),(2,2)),
'tfidf__use_idf': (True, False),
'tfidf__norm': ('l1', 'l2'),
'clf__estimator__learning_rate': [0.1, 0.5],
'clf__estimator__n_estimators': [50, 60, 70]
}
# create grid search object
cv = GridSearchCV(pipeline, param_grid=parameters, verbose=216)
return cv
def evaluate_model(model, X_test, Y_test, category_names):
"""
Generates predicted values for test data based on
fit model. Outputs a classification report for each category.
Keyword arguments:
model -- fit model based on training data
X_test, Y_test -- message and target category values for testing
category_names -- list of possible categories for each message
"""
Y_pred = model.predict(X_test)
for i, label in enumerate(category_names):
print(category_names[i])
print(classification_report(Y_test[label], Y_pred[:,i]))
def save_model(model, model_filepath):
"""
Export the classifier to a pickle file
Keyword arguments:
model -- final model
model_filepath -- location and name of saved pickle file
"""
with open(model_filepath, 'wb') as model_filepath:
pickle.dump(model, model_filepath)
def main():
if len(sys.argv) == 3:
database_filepath, model_filepath = sys.argv[1:]
print('Loading data...\n DATABASE: {}'.format(database_filepath))
X, Y, category_names = load_data(database_filepath)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = 42)
print('Building model...')
model = build_model()
print('Training model...')
model.fit(X_train, Y_train)
print(model.best_score_)
print(model.best_params_)
print('Evaluating model...')
evaluate_model(model, X_test, Y_test, category_names)
print('Saving model...\n MODEL: {}'.format(model_filepath))
save_model(model, model_filepath)
print('Trained model saved!')
else:
print('Please provide the filepath of the disaster messages database '\
'as the first argument and the filepath of the pickle file to '\
'save the model to as the second argument. \n\nExample: python '\
'train_classifier.py ../data/DisasterResponse.db classifier.pkl')
if __name__ == '__main__':
main()
|
goitom/project_2_disaster_response
|
models/train_classifier.py
|
train_classifier.py
|
py
| 5,371 |
python
|
en
|
code
| 0 |
github-code
|
6
|
25546051885
|
import os
import json
import flask
from vrprot.alphafold_db_parser import AlphafoldDBParser
import vrprot
from . import map_uniprot
from . import settings as st
from . import util
from .classes import NodeTags as NT
def get_scales(uniprot_ids=[], mode=st.DEFAULT_MODE):
return vrprot.overview_util.get_scale(uniprot_ids, mode)
def run_pipeline(proteins: list, parser: AlphafoldDBParser = st.parser, **kwargs):
# create the output directory for the corresponding coloring mode if they do not exist
# output_dir = os.path.join(st._MAPS_PATH, parser.processing)
output_dir = os.path.join(st._MAPS_PATH)
parser.update_output_dir(output_dir)
# initialize the structures dictionary of the parser and check wether some processing files do already exist
parser.init_structures_dict(proteins)
for protein in proteins:
parser.update_existence(protein)
# run the batched process
try:
parser.fetch_pipeline(proteins, **kwargs)
# batch([parser.fetch_pdb, parser.pdb_pipeline], proteins, parser.batch_size)
except vrprot.exceptions.ChimeraXException as e:
return {"error": "ChimeraX could not be found. Is it installed?"}
result = get_scales(proteins, parser.processing)
# update the existence of the processed files
for protein in proteins:
parser.update_existence(protein)
return result
def fetch_from_request(request: flask.Request, parser: AlphafoldDBParser = st.parser):
# get information from request
pdb_id = request.args.get("id")
if pdb_id is None:
return {
"error": "No PDB ID provided.",
"example": f"{request.host}/vrprot/fetch?id=P69905",
}
# extract processing mode and alphafold version from request
parser = util.parse_request(parser, request)
# if mode is not part of the list of available modes, return an error
if isinstance(parser, dict):
return parser
# create a list of proteins to be processed
proteins = [pdb_id]
return fetch(proteins, parser)
def fetch(proteins: list[str], parser: AlphafoldDBParser = st.parser):
# run the batched process
parser.not_fetched = set()
parser.already_exists = set()
result = run_pipeline(proteins, parser)
# Try whether you can find an updated UniProt id
second_try = {}
if len(parser.not_fetched) > 0:
try:
mapped_ac = map_uniprot.main(
parser.not_fetched,
source_db=map_uniprot.Databases.uniprot_ac,
target_db=map_uniprot.Databases.uniprot,
)
for re in mapped_ac["results"]:
a, b = True, True
while a and b:
a = re.get("from")
b = re.get("to")
b = b.get("uniProtKBCrossReferences")
for entry in b:
if entry.get("database") == "AlphaFoldDB":
b = entry.get("id")
second_try[b] = a
if a in parser.not_fetched:
parser.not_fetched.remove(a)
break
break
result.update(run_pipeline(second_try, parser))
tmp = parser.not_fetched.copy()
for ac in tmp:
if ac in second_try:
parser.not_fetched.remove(ac)
parser.not_fetched.add(second_try[ac])
except Exception as e:
print(e)
return {
"not_fetched": list(parser.not_fetched),
"already_exists": list(parser.already_processed),
"results": result,
"alternative_ids": {v: k for k, v in second_try.items()},
}
def for_project(
project: str, request: flask.request, parser: AlphafoldDBParser = st.parser
):
# get information from request
if project is None:
return {"error": "No project provided."}
# extract processing mode and alphafold version from request
parser = util.parse_request(parser, request)
# if mode is not part of the list of available modes, return an error
if isinstance(parser, dict):
return parser
# extract node data from the projects nodes.json file
nodes_files = os.path.join(st._PROJECTS_PATH, project, "nodes.json")
if not os.path.isfile(nodes_files):
return {"error": "Project does not exist."}
with open(nodes_files, "r") as f:
nodes = json.load(f)["nodes"]
# extract the uniprot ids from the nodes
proteins = [",".join(node[NT.uniprot]) for node in nodes if node.get(NT.uniprot)]
# run the batched process
result = run_pipeline(proteins, parser, on_demand=False)
return {"not_fetched": list(parser.not_fetched), "results": result}
def fetch_list_from_request(
request: flask.Request, parser: AlphafoldDBParser = st.parser
):
# get information from request
pdb_ids = request.args.get("ids")
if pdb_ids is None:
return {
"error": "No PDB IDs provided.",
"example": f"http://{request.host}/vrprot/list?ids=P02655,At1g58602",
}
# extract processing mode and alphafold version from request
parser = util.parse_request(parser, request)
# if mode is not part of the list of available modes, return an error
if isinstance(parser, dict):
return parser
# create a list of proteins to be processed
proteins = [id for id in pdb_ids.split(",")]
return fetch_list(proteins, parser)
def fetch_list(proteins: list[str], parser: AlphafoldDBParser = st.parser):
# run the batched process
result = run_pipeline(proteins, parser, on_demand=False)
return {"not_fetched": list(parser.not_fetched), "results": result}
|
menchelab/ProteinStructureFetch
|
src/workflows.py
|
workflows.py
|
py
| 5,793 |
python
|
en
|
code
| 0 |
github-code
|
6
|
3235447487
|
from __future__ import annotations
from typing import TYPE_CHECKING
from avilla.core.context import Context
from avilla.core.event import RelationshipCreated, RelationshipDestroyed
from avilla.core.selector import Selector
from avilla.core.trait.context import EventParserRecorder
from cai.client.events.group import (
GroupLuckyCharacterChangedEvent,
GroupLuckyCharacterClosedEvent,
GroupLuckyCharacterInitEvent,
GroupLuckyCharacterNewEvent,
GroupLuckyCharacterOpenedEvent,
GroupMemberJoinedEvent,
GroupMemberLeaveEvent,
GroupMemberMutedEvent,
GroupMemberPermissionChangeEvent,
GroupMemberSpecialTitleChangedEvent,
GroupMemberUnMutedEvent,
GroupNameChangedEvent,
TransferGroupEvent,
)
if TYPE_CHECKING:
from ..account import CAIAccount
from ..protocol import CAIProtocol
event = EventParserRecorder["CAIProtocol", "CAIAccount"]
@event("GroupMemberJoinedEvent")
async def group_member_joined_event(
protocol: CAIProtocol, account: CAIAccount, raw: GroupMemberJoinedEvent
):
group = Selector().land(protocol.land.name).group(str(raw.group_id))
member = group.member(str(raw.uin))
context = Context(
account=account,
client=member,
endpoint=group,
scene=group,
selft=group.member(account.id),
)
return RelationshipCreated(context, member, group, context.self), context
@event("GroupMemberLeaveEvent")
async def group_member_leave_event(
protocol: CAIProtocol, account: CAIAccount, raw: GroupMemberLeaveEvent
):
group = Selector().land(protocol.land.name).group(str(raw.group_id))
member = group.member(str(raw.uin))
context = Context(
account=account,
client=member,
endpoint=group,
scene=group,
selft=group.member(account.id),
)
res = RelationshipDestroyed(context, member, group, context.self)
if raw.operator and raw.operator != raw.uin:
res.mediums.append(group.member(str(raw.operator)))
return res, context
|
RF-Tar-Railt/Avilla-CAI
|
avilla/cai/event/group.py
|
group.py
|
py
| 2,023 |
python
|
en
|
code
| 3 |
github-code
|
6
|
23750393543
|
"""
최적화 비중을 계산해주는 모듈
@author: Younghyun Kim
Created on 2021.10.05
"""
import numpy as np
import pandas as pd
import cvxpy as cp
import torch
from cvxpylayers.torch import CvxpyLayer
class ClassicOptimizer:
"""
Classic Optimizer
"""
def __init__(self, m=100,
buying_fee=0.01, selling_fee=0.01,
min_cash_rate=0.01):
"""
Initialization
Args:
m: big number
"""
self.m = m
self.buying_fee = buying_fee
self.selling_fee = selling_fee
self.min_cash_rate = min_cash_rate
def max_sr(self, returns, nonneg=True, adjust=True):
"""
Maximize Sharpe Ratio
Args:
returns: pd.DataFrame or np.array
Return:
weights: np.array(N)
"""
if isinstance(returns, pd.DataFrame):
returns = returns.values
creturns = returns * self.m
cov = np.cov(creturns.transpose())
cov = np.nan_to_num(cov)
mu = creturns.mean(0).reshape(-1)
mu_min = abs(mu.min())
if mu[mu > 0].shape[0] == 0:
mu += mu_min
mu = np.nan_to_num(mu)
weights = cp.Variable(returns.shape[1])
cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]), symmetric=True)
objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))
constraints = [mu.T @ weights >= 1]
if nonneg:
constraints.append(0 <= weights)
prob = cp.Problem(objective, constraints)
assert prob.is_dpp()
cov = torch.FloatTensor(cov.astype(float))
cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
variables=[weights])
weights, = cvxpylayer(cov)
if adjust:
weights = self.adjust_weights(weights)
return weights.numpy()
def min_var(self, returns):
"""
Minimum Variance Portfolio
Args:
returns: pd.DataFrame or np.array
Return:
weights: np.array(N)
"""
if isinstance(returns, pd.DataFrame):
returns = returns.values
creturns = returns * self.m
cov = np.cov(creturns.transpose())
cov = np.nan_to_num(cov)
weights = cp.Variable(returns.shape[1])
cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]),
symmetric=True)
objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))
constraints = [cp.sum(weights) == 1, 0 <= weights]
prob = cp.Problem(objective, constraints)
assert prob.is_dpp()
cov = torch.FloatTensor(cov.astype(float))
cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
variables=[weights])
weights, = cvxpylayer(cov)
return weights.numpy()
def max_div(self, returns, nonneg=True, adjust=True):
"""
Maximum Diversification Portfolio
Args:
returns: pd.DataFrame or np.array
Return:
weights: np.array(N)
"""
if isinstance(returns, pd.DataFrame):
returns = returns.values
creturns = returns * self.m
cov = np.cov(creturns.transpose())
cov = np.nan_to_num(cov)
sig = creturns.std(0).reshape(-1)
sig = np.nan_to_num(sig)
weights = cp.Variable(returns.shape[1])
cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]),
symmetric=True)
objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))
constraints = [sig.T @ weights >= 1]
if nonneg:
constraints.append(0 <= weights)
prob = cp.Problem(objective, constraints)
assert prob.is_dpp()
cov = torch.FloatTensor(cov.astype(float))
cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
variables=[weights])
weights, = cvxpylayer(cov)
if adjust:
weights = self.adjust_weights(weights)
return weights.numpy()
def mv_mean(self, returns):
"""
Mean-Variance Portfolio with min ret based on mean ret
Args:
returns: pd.DataFrame or np.array
Return:
weights: np.array(N)
"""
if isinstance(returns, pd.DataFrame):
returns = returns.values
creturns = returns * self.m
cov = np.cov(creturns.transpose())
cov = np.nan_to_num(cov)
weights = cp.Variable(returns.shape[1])
cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]),
symmetric=True)
mu = creturns.mean(0).reshape(-1)
mu_min = abs(mu.min())
if mu[mu > 0].shape[0] == 0:
mu += mu_min
mu = np.nan_to_num(mu)
mret = mu.mean().item()
objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))
constraints = [cp.sum(weights) == 1,
mu.T @ weights >= mret,
0 <= weights]
prob = cp.Problem(objective, constraints)
assert prob.is_dpp()
cov = torch.FloatTensor(cov.astype(float))
cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
variables=[weights])
weights, = cvxpylayer(cov)
return weights.numpy()
def pm_port(self, returns, topk=5, return_type='pct'):
"""
Price Momentum Equal Weight Portfolio with TopK
Args:
returns: pd.DataFrame or np.array
topk: top K
return_type: return type(log or pct)
Return:
weights: np.array(N)
"""
if isinstance(returns, pd.DataFrame):
returns = returns.values
if return_type == 'pct':
returns = np.log(returns + 1.)
crets = returns.sum(0)
crets = np.nan_to_num(crets)
crank = crets.argsort()
weights = np.zeros(returns.shape[1])
weights[crank[-topk:]] = 1. / topk
return weights
def lowvol_port(self, returns, topk=5):
"""
Lowvol Equal Weight Portfolio with TopK
Args:
returns: pd.DataFrame or np.array
topk: top K
Return:
weights: np.array(N)
"""
if isinstance(returns, pd.DataFrame):
returns = returns.values
sig = returns.std(0)
sig = np.nan_to_num(sig)
srank = sig.argsort()
weights = np.zeros(returns.shape[1])
weights[srank[:topk]] = 1. / topk
return weights
def ew_port(self, n):
"""
Equal Weight Portfolio with n assets
Args:
n: asset num
Return:
weights: np.array(n)
"""
weights = torch.ones(n) / n
return weights
def solve_amount(self, asset_prices, asset_embs, optimal_emb, wealth):
"""
Solving method for trading amounts
Args:
asset_prices: np.array 수량 계산에 필요한 자산 별 가격(1 X N)
asset_embs = np.array 자산 별 임베딩(N X M)
optimal_emb: 최적 포트폴리오 임베딩(1 X M)
wealth: 총 투자금
Return:
buying_amount: 종목 별 수량
prob_value: 최적과 최종 포트폴리오 거리(L2)
"""
wealth =\
wealth * (1. - max(self.buying_fee, self.selling_fee)) # 비용 고려
wealth = wealth * (1. - self.min_cash_rate) # 최소 보유 현금 고려
asset_embs_v = asset_embs.transpose() * asset_prices / wealth
asset_prices = asset_prices.reshape(-1)
buying_amount = cp.Variable(asset_prices.shape[0])
optimal_emb = optimal_emb.reshape(-1)
objective = cp.Minimize(self.m *
cp.sum_squares((asset_embs_v @ buying_amount)
- optimal_emb))
constraints = [buying_amount >= 0,
asset_prices.T @ buying_amount == wealth]
prob = cp.Problem(objective, constraints)
prob.solve()
buying_amount = np.round(buying_amount.value, 0)
return buying_amount, prob.value
def get_replicated_buying_amounts(self, closes, asset_embs, weights,
insts=['A069500', 'A229200',
'A114800', 'A251340'],
topk=10, wealth=50000000):
"""
closes: pd.Series 종목 별 종가(stock_num)
asset_embs: torch.tensor 종목 별 임베딩(1, stock_num, emb_dim)
weights: torch.tensor 종목 별 투자비중(1, stock_num)
insts: list 복제에 활용될 시장 ETF(default: K200, KQ150)
topk: 복제하기 위한 상위 종목 수
* closes, asset_embs, weights는 종목 별 순서가 일치해야함
Return:
amounts: pd.DataFrame 매수수량
aweights: pd.DataFrame 매수수량을 바탕으로 한 투자비중
value_est: closes를 바탕으로 계산한 총금액
prob_value: 임베딩 거리
"""
ins = []
for inst in insts:
ind = np.argwhere(closes.index == inst).item()
ins.append(ind)
ranks = weights.argsort(descending=True)
ranks = ranks.cpu().numpy().reshape(-1)
sel = np.unique(np.concatenate((ranks[:topk], ins), axis=-1))
optimal_emb = self.calc_optimal_emb(asset_embs, weights)
embs = asset_embs[0, sel].cpu().numpy()
optimal_emb = optimal_emb.view(-1, 1).cpu().numpy()
amounts, prob_value = self.solve_amount(closes.iloc[sel].values,
embs, optimal_emb, wealth)
amounts = pd.DataFrame(amounts.reshape(-1, 1),
index=closes.index[sel],
columns=['amounts'])
amounts = amounts[amounts['amounts'] > 0]
closes = pd.DataFrame(closes.values, index=closes.index, columns=amounts.columns)
value_est = (amounts.values.ravel() * closes.loc[amounts.index].values.ravel()).sum()
aweights = (amounts * closes.loc[amounts.index]) / value_est
return amounts, aweights, value_est, prob_value
def calc_optimal_emb(self, asset_embs, weights):
"""
calculate optimal embedding
Args:
asset_embs: torch.tensor
(batch_size, stock_num, emb_dim)
weights: torch.tensor
(batch_size, stock_num)
"""
optimal_emb = torch.matmul(weights, asset_embs)
return optimal_emb
def adjust_weights(self, weights):
"""
비중 조정
* nonneg일때,
weights /= weights.sum()
* weights[weights > 0].sum() > 0 일때,
weights /= weights[weights > 0].sum()
* weights[weights > 0].sum() < 0이고,
weights[weights < 0] != 0일때,
weights /= -weights[weights < 0].sum()
"""
if (weights != 0).sum() > 0:
weights = weights / abs(weights).max()
wpos_sum = weights[weights > 0].sum()
wneg_sum = -weights[weights < 0].sum()
if weights.sum() != 0:
weights /= max(wpos_sum, wneg_sum)
return weights
|
kimyoungh/singlemolt
|
statesman/classic_optimizer.py
|
classic_optimizer.py
|
py
| 11,771 |
python
|
en
|
code
| 0 |
github-code
|
6
|
35061353854
|
from tkinter import Button, Checkbutton, Entry, IntVar, Label, Tk
from tkinter import messagebox
from solve import Solver
q = Solver()
def show_plot():
if accur_entry.get().isdigit():
n = int(accur_entry.get())
else:
messagebox.showerror(message="put integer")
return
potential = pot.get()
if wave.get().isdigit():
number = int(wave.get())
else:
messagebox.showerror(message="put integer")
return
if spread.get().isdigit():
s = int(spread.get())
else:
messagebox.showerror(message="put integer")
return
if n != q.n or potential != q.pot or s != q.range:
print(accur_entry.get(), q.n)
print(potential, q.pot)
print(s, q.range)
q._init(n, potential, s)
if pp.get() == 1:
q.plopoten()
q.show()
if pi.get() == 1:
if ow.get() == 1:
for i in range(number):
q.plot(False, i)
else:
q.plot(False, number)
else:
if ow.get() == 1:
for i in range(number):
q.plot(True, i)
else:
q.plot(True, number)
q.show()
window = Tk()
window.title("stationary state grapher")
ow = IntVar()
pi = IntVar()
pp = IntVar()
window.config(padx=20, pady=20)
accur = Label(text="give number of grid points")
accur_entry = Entry()
accur_entry.insert(0, "2000")
pot_lab = Label(text="give potential")
wave_lab = Label(text="wave number ")
wave = Entry()
spread_lab = Label(text="give the bounded range ")
spread = Entry()
spread.insert(0, "100")
prob = Checkbutton(text="see probability ", variable=pi, onvalue=1, offvalue=0)
only_wave = Checkbutton(text="see all the waves upto that number", variable=ow, onvalue=1, offvalue=0)
plot = Button(text="show the plot", width=32, command=show_plot)
pot = Entry()
pot.focus()
potplot = Checkbutton(text="plot potential function ", variable=pp, onvalue=1, offvalue=0)
# grid
accur.grid(row=0, column=0)
accur_entry.grid(row=0, column=1)
pot_lab.grid(row=1, column=0)
pot.grid(row=1, column=1)
wave_lab.grid(row=3, column=0)
wave.grid(row=3, column=1)
spread_lab.grid(row=2, column=0)
spread.grid(row=2, column=1)
prob.grid(row=4, column=0, columnspan=2)
only_wave.grid(row=5, column=0, columnspan=2)
potplot.grid(row=6, column=0, columnspan=2)
plot.grid(row=7, column=0, columnspan=2)
window.mainloop()
|
shomarzzz/quantum-solver
|
gui.py
|
gui.py
|
py
| 2,469 |
python
|
en
|
code
| 0 |
github-code
|
6
|
39259262942
|
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
import speech_recognition as sr
from custom_if.srv import SendSentence
from functools import partial
import time
### Node class
class SpeechToText(Node):
def __init__(self):
super().__init__("stt_node")
self.get_logger().info("STT node is up.")
self.stt = sr.Recognizer()
# Methods
self.listen_to_user()
## Listen and write
def listen_to_user(self):
self.call_nlu("Welcome")
# Inner loop
while True:
with sr.Microphone() as source:
self.stt.adjust_for_ambient_noise(source, duration=0.2)
audio = self.stt.listen(source)
try:
sentence = "{0}".format(self.stt.recognize_google(audio, language="it-IT"))
if 'Marvin' in sentence.split(" "):
self.call_nlu(sentence)
except sr.UnknownValueError:
self.get_logger().warn("Waiting for a command.")
except sr.RequestError as e:
self.get_logger().error("STT Error; {0}".format(e))
# Definition of the client request to the TTS
def call_nlu(self, sentence):
client = self.create_client(SendSentence, "send_command")
while not client.wait_for_service(1.0):
self.get_logger().warn("Waiting for Server...")
request = SendSentence.Request()
request.sentence = sentence
future = client.call_async(request)
future.add_done_callback(partial(self.callback_call_nlu, sentence=sentence))
def callback_call_nlu(self, future, sentence):
try:
response = future.result()
self.get_logger().info(f"Request solved: {response}")
except Exception as e:
self.get_logger().error("Request failed.")
def main(args=None):
rclpy.init(args=args)
node = SpeechToText()
rclpy.spin(node)
rclpy.shutdown()
if __name__ == "__main__":
main()
|
Alessandro-Scarciglia/VoiceAssistant
|
speech_to_text/speech_to_text/speech_to_text.py
|
speech_to_text.py
|
py
| 1,732 |
python
|
en
|
code
| 0 |
github-code
|
6
|
22034975052
|
from lib2to3.pgen2 import token
from brownie import Test, accounts, interface
from eth_utils import to_wei
from web3 import Web3
def main():
deploy()
def deploy():
amount_in = Web3.toWei(1000000, "ether")
# DAI address
DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
# DAI whale
DAI_WHALE = "0xcffad3200574698b78f32232aa9d63eabd290703"
# WETH
WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
# WETH whale
WETH_WHALE = "0xeD1840223484483C0cb050E6fC344d1eBF0778a9"
print("===Transferring gas cost covers===")
# covering the transaction cost
# accounts[0].transfer(DAI_WHALE, "1 ether")
# accounts[0].transfer(WETH_WHALE, "1 ether")
tokenA = interface.IERC20(DAI)
tokenB = interface.IERC20(WETH)
print("===Transferring the tokenA and tokenB amounts from whales to account[0]===")
tokenA.transfer(accounts[0], Web3.toWei(2400, "ether"), {"from": DAI_WHALE})
tokenB.transfer(accounts[0], Web3.toWei(1, "ether"), {"from": WETH_WHALE})
contract = Test.deploy({"from": accounts[0]})
tokenA.approve(contract.address, Web3.toWei(2400, "ether"), {"from": accounts[0]})
tokenB.approve(contract.address, Web3.toWei(1, "ether"), {"from": accounts[0]})
print("Adding liquidity...")
tx = contract.addLiquidity(
DAI,
WETH,
Web3.toWei(2400, "ether"),
Web3.toWei(1, "ether"),
{"from": accounts[0]},
)
tx.wait(1)
print("Added Liquidity...")
for i in tx.events["Log"]:
print(i)
print("=== Removing Liquidity ===")
tx = contract.removeLiquidity(DAI, WETH, {"from": accounts[0]})
tx.wait(1)
for i in tx.events["Log"]:
print(i)
|
emrahsariboz/DeFi
|
uniswap/scripts/_deployAndAddLiquidity.py
|
_deployAndAddLiquidity.py
|
py
| 1,713 |
python
|
en
|
code
| 0 |
github-code
|
6
|
37272423624
|
import sys
from aspartix_parser import Apx_parser
import itertools
def conflict_free(arguments, attacks):
confl_free_sets = []
combs = []
for i in range(1, len(arguments) + 1):
els = [list(x) for x in itertools.combinations(arguments, i)]
combs.extend(els)
combs_sorted = [list(combs_sorted) for combs_sorted in combs][::-1]
# print("Combs: ", combs_sorted)
for i in combs_sorted:
att_count = 0
# print(i)
for att in attacks:
# print(att)
if set([str(att)[2], str(att)[4]]).issubset(set(i)) or any([i in item for item in
confl_free_sets]): # any(x in item for item in confl_free_sets for x in i):#(True if list(filter(lambda x:i in x,confl_free_sets)) else False):#(any([set(i).issubset(set(item)) in item for item in confl_free_sets])):
break
else:
att_count += 1
# print(att_count)
# if ((str(att)[2] and str(att)[4]) not in i) and (not any([i in item for item in confl_free_sets])):
# att_count += 1
# print(att_count)
if att_count == len(attacks):
confl_free_sets.append(i)
return confl_free_sets
def admissible(confl_free, attacks):
admissible_sets = []
for ext in confl_free:
count = 0
# print(ext)
for att in attacks:
if str(att)[4] not in ext:
count += 1
# print(att, count)
else:
# print(att, count)
for atr in attacks:
# print(att, atr, count, str(atr)[4], str(att)[2])
if (str(att)[2] == str(atr)[4]) and (str(atr)[2] in ext):
count += 1
# print(count)
if count == len(attacks):
admissible_sets.append(ext)
return admissible_sets
# def complete(admissible_sets, attacks):
# complete_ext = []
# for adm in admissible_sets:
# for att in attacks:
# if (str(att)[2] in adm) and
#
# return complete_ext
def preferred(admissible_sets):
preferred_exts = []
for adm in admissible_sets:
count = 0
# print(adm, count)
for adm_t in admissible_sets:
if set(adm).issubset(set(adm_t)) and adm_t != adm:
pass
else:
count += 1
# print(adm, adm_t, count)
if count == len(admissible_sets):
preferred_exts.append(adm)
return preferred_exts
def stable_extensions(stable_exts):
pass
if __name__ == '__main__':
filepath = 'example.apx'
if sys.argv[1:]:
filepath = sys.argv[1]
arguments = []
attacks = []
parser = Apx_parser(filepath)
arguments, attacks = parser.read_file()
parser.close()
print(arguments, attacks)
print("There are ", len(arguments), " arguments and ", len(attacks), " attacks.")
# print(str(attacks[0])[4])
confl_free = conflict_free(arguments, attacks)
print("Conflict free extensions: ", "[]", sorted(confl_free))
admissible_sets = admissible(confl_free, attacks)
print("Admissible extensions: ", "[]", sorted(admissible_sets))
# complete_ext = complete(admissible_sets, attacks)
preferred_exts = preferred(admissible_sets)
print("Preferred extensions: ", sorted(preferred_exts))
stable_exts = stable_extensions(preferred_exts)
print("Stable extensions: ", stable_exts)
|
Vladimyr23/aspartix_file_parsing_and_reasoning_with_args
|
Python_parser_and_reasoning_semantics/semantics.py
|
semantics.py
|
py
| 3,690 |
python
|
en
|
code
| 0 |
github-code
|
6
|
27672884251
|
from typing import Dict, Tuple
from copy import deepcopy
import torch
from config import tqc_config
from modules import Actor, TruncatedQuantileEnsembledCritic
class TQC:
def __init__(self,
cfg: tqc_config,
actor: Actor,
critic: TruncatedQuantileEnsembledCritic) -> None:
self.cfg = cfg
self.device = cfg.device
self.tau = cfg.tau
self.discount = cfg.discount
self.batch_size = cfg.batch_size
self.target_entropy = -float(actor.action_dim)
self.log_alpha = torch.tensor([0.0], dtype=torch.float32, device=self.device, requires_grad=True)
self.alpha_optimizer = torch.optim.AdamW([self.log_alpha], lr=cfg.alpha_lr)
self.alpha = self.log_alpha.exp().detach()
self.actor = actor.to(self.device)
self.actor_optim = torch.optim.AdamW(self.actor.parameters(), lr=cfg.actor_lr)
self.critic = critic.to(self.device)
self.critic_target = deepcopy(critic).to(self.device)
self.critic_optim = torch.optim.AdamW(self.critic.parameters(), lr=cfg.critic_lr)
self.quantiles_total = critic.num_critics * critic.num_quantiles
self.quantiles2drop = cfg.quantiles_to_drop_per_critic * cfg.num_critics
self.top = self.quantiles_total - self.quantiles2drop
huber_tau = torch.arange(self.cfg.num_quantiles, device=self.device).float() / self.top + 1 / (2 * self.top)
self.huber_tau = huber_tau[None, None, :, None]
self.total_iterations = 0
def train(self,
states: torch.Tensor,
actions: torch.Tensor,
rewards: torch.Tensor,
next_states: torch.Tensor,
dones: torch.Tensor) -> Dict[str, float]:
self.total_iterations += 1
# critic step
critic_loss = self.critic_loss(states, actions, rewards, next_states, dones)
self.critic_optim.zero_grad()
critic_loss.backward()
self.critic_optim.step()
# actor step
actor_loss, batch_entropy, qz_values = self.actor_loss(states)
self.actor_optim.zero_grad()
actor_loss.backward()
self.actor_optim.step()
# alpha step
alpha_loss = self.alpha_loss(states)
self.alpha_optimizer.zero_grad()
alpha_loss.backward()
self.alpha_optimizer.step()
self.alpha = self.log_alpha.exp().detach()
self.soft_critic_update()
return {
"critic_loss": critic_loss.item(),
"actor_loss": actor_loss.item(),
"actor_batch_entropy": batch_entropy,
"qz_values": qz_values,
"alpha": self.alpha.item(),
"alpha_loss": alpha_loss.item()
}
def actor_loss(self, states: torch.Tensor) -> Tuple[torch.Tensor, float, float]:
actions, log_prob = self.actor(states, need_log_prob=True)
qz_values = self.critic(states, actions).mean(dim=2).mean(dim=1, keepdim=True)
loss = self.alpha * log_prob - qz_values
batch_entropy = -log_prob.mean().item()
return loss.mean(), batch_entropy, qz_values.mean().item()
def critic_loss(self,
states: torch.Tensor,
actions: torch.Tensor,
rewards: torch.Tensor,
next_states: torch.Tensor,
dones: torch.Tensor) -> torch.Tensor:
with torch.no_grad():
next_actions, next_log_prob = self.actor(next_states, need_log_prob=True)
next_z = self.critic_target(next_states, next_actions)
sorted_next_z = torch.sort(next_z.reshape(self.batch_size, -1)).values
sorted_next_z_top = sorted_next_z[:, :self.top]
sorted_next_z_top = sorted_next_z_top - self.alpha * next_log_prob.unsqueeze(-1)
quantiles_target = rewards + self.discount * (1.0 - dones) * sorted_next_z_top
current_z = self.critic(states, actions)
loss = self.quantile_huber_loss(current_z, quantiles_target)
return loss
def quantile_huber_loss(self, quantiles: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
pairwise_diff = target[:, None, None, :] - quantiles[:, :, :, None]
abs_val = pairwise_diff.abs()
huber_loss = torch.where(abs_val > 1.0,
abs_val - 0.5,
pairwise_diff.pow(2) / 2)
loss = torch.abs(self.huber_tau - (pairwise_diff < 0).float()) * huber_loss
return loss.mean()
def alpha_loss(self, state: torch.Tensor) -> torch.Tensor:
with torch.no_grad():
action, log_prob = self.actor(state, need_log_prob=True)
loss = -self.log_alpha * (log_prob + self.target_entropy)
return loss.mean()
def soft_critic_update(self):
for param, tgt_param in zip(self.critic.parameters(), self.critic_target.parameters()):
tgt_param.data.copy_(self.tau * param.data + (1 - self.tau) * tgt_param.data)
|
zzmtsvv/rl_task
|
offline_tqc/tqc.py
|
tqc.py
|
py
| 5,082 |
python
|
en
|
code
| 8 |
github-code
|
6
|
41267353320
|
from tkinter import *
class JogoDaForca:
def __init__(self, master):
self.master = master
master.title("Jogo da Forca")
master.geometry("300x300")
# palavra secreta
self.palavra_secreta = "banana"
# letras adivinhadas
self.letras_adivinhadas = []
# número de tentativas
self.tentativas_restantes = 6
# widgets
self.lbl_palavra = Label(master, text=self.esconder_palavra())
self.lbl_palavra.pack()
self.lbl_letras_adivinhadas = Label(master, text=self.formatar_letras_adivinhadas())
self.lbl_letras_adivinhadas.pack()
self.lbl_tentativas = Label(master, text="Tentativas restantes: {}".format(self.tentativas_restantes))
self.lbl_tentativas.pack()
self.lbl_mensagem = Label(master, text="")
self.lbl_mensagem.pack()
self.ent_palpite = Entry(master)
self.ent_palpite.pack()
self.btn_adivinhar = Button(master, text="Adivinhar", command=self.adivinhar_letra)
self.btn_adivinhar.pack()
def esconder_palavra(self):
palavra_escondida = ""
for letra in self.palavra_secreta:
if letra in self.letras_adivinhadas:
palavra_escondida += letra
else:
palavra_escondida += "_"
return palavra_escondida
def formatar_letras_adivinhadas(self):
return "Letras adivinhadas: {}".format(", ".join(self.letras_adivinhadas))
def adivinhar_letra(self):
palpite = self.ent_palpite.get()
if len(palpite) != 1:
self.lbl_mensagem.configure(text="Por favor, digite uma letra de cada vez.")
return
if palpite in self.letras_adivinhadas:
self.lbl_mensagem.configure(text="Você já adivinhou essa letra.")
return
self.letras_adivinhadas.append(palpite)
if palpite not in self.palavra_secreta:
self.tentativas_restantes -= 1
self.lbl_tentativas.configure(text="Tentativas restantes: {}".format(self.tentativas_restantes))
if self.tentativas_restantes == 0:
self.lbl_mensagem.configure(text="Você perdeu!")
self.btn_adivinhar.configure(state=DISABLED)
return
if self.esconder_palavra() == self.palavra_secreta:
self.lbl_mensagem.configure(text="Você ganhou!")
self.btn_adivinhar.configure(state=DISABLED)
return
self.lbl_palavra.configure(text=self.esconder_palavra())
self.lbl_letras_adivinhadas.configure(text=self.formatar_letras_adivinhadas())
self.ent_palpite.delete(0, END)
def iniciar_jogo(self):
self.master.mainloop()
root = Tk()
jogo_da_forca = JogoDaForca(root)
jogo_da_forca.iniciar_jogo()
|
Matheus-A-Santana/Estudos
|
Aprendendo Python/jogo-da-forca.py
|
jogo-da-forca.py
|
py
| 2,829 |
python
|
pt
|
code
| 0 |
github-code
|
6
|
24072421464
|
"""
Parser.py
Used to parse URLs into a linked list of dictionaries.
"""
from bs4 import BeautifulSoup
import requests
import re
class Node: # pragma: no cover
"""
Creates a Node that contains data, and a next node
Data holds any object.
Next points to the next node, and should always be a node.
"""
def __init__(
self, data):
"""Initialize Node Class"""
self.data = data
self.next = None
class LinkedList: # pragma: no cover
"""
Creates a Linked List, with a head, and a tail.
Head only contains the first link in the list, and should be called at the
beginning of scan.
Tail only contains the last link in the list, and should not be called.
"""
def __init__(
self):
"""Initialize Linked List Class"""
self.head = None
self.tail = None
def add_list_item(
self, item):
"""Add an item to the Linked List"""
if not isinstance(item, Node):
item = Node(item)
if self.head is None:
self.head = item
elif self.tail.data == item:
return
else:
self.tail.next = item
self.tail = item
def parse_url_feed(
incoming) -> LinkedList:
"""
Receives either a list of URLs or a single URL, and returns a Linked
List of Dictionaries
"""
total_feed = LinkedList()
url_list = return_list(incoming)
for url_entry in url_list:
if not check_url(url_entry):
raise Exception("Invalid URL. Must Be a RSS Feed URL ending in "
".rss, .html, or .xml: " + url_entry)
parse_value = find_parser(url_entry)
response = requests.get(url_entry)
soup = BeautifulSoup(response.content, parse_value)
if soup.rss is not None:
feed = rss_parse(soup)
total_feed.add_list_item(feed)
elif soup.find_all(re.compile("atom.xml")) is not None:
feed = atom_parse(soup)
total_feed.add_list_item(feed)
return total_feed
def check_url(
url: str) -> bool:
"""Checks to see if the URL given is parseable"""
url = str(url)
if len(url) == 0:
return False
result1 = re.search("rss?", url)
result2 = re.search("xml?", url)
result3 = re.search("tml?", url)
result4 = re.search("feeds?", url)
if result1 is not None:
return True
elif result2 is not None:
return True
elif result3 is not None:
return True
elif result4 is not None:
return True
else:
return False
def find_parser(
response: str) -> str:
"""Checks to see which parser to use"""
if len(response) <= 3:
raise Exception("Invalid URL Length")
result = re.search("tml?", response)
if result is not None:
return "lxml"
else:
return "lxml-xml"
def return_list(
incoming) -> list:
"""
Checks to see if incoming is a String or a List. If a String, adds the
string to a list and returns.
"""
url_list = []
if isinstance(incoming, str):
url_list.append(incoming)
elif isinstance(incoming, list):
url_list = incoming
return url_list
def rss_parse(
soup: BeautifulSoup) -> LinkedList: # pragma: no cover
"""
When URL is an RSS feed, returns a linked list of dictionaries
containing the titles and links
"""
feed = LinkedList()
tag = soup.rss
tag = tag.channel
channel_dict = {"RSS_String": tag.title.string, "Link": tag.link.string}
feed.add_list_item(channel_dict)
for item in tag.find_all(re.compile("item?")):
feed_dict = {}
for title in item.find_all(re.compile("title?")):
for entry in title.find_all(string=True):
feed_dict["RSS_String"] = entry
feed_dict["RSS_String"] = truncate(feed_dict["RSS_String"])
for link in item.find_all(re.compile("link?")):
for entry in link.find_all(string=True):
feed_dict["Link"] = entry
feed.add_list_item(feed_dict)
return feed
def atom_parse(
soup: BeautifulSoup) -> LinkedList: # pragma: no cover
"""
When URL is an Atom feed, returns a linked list of dictionaries containing
the titles and links
"""
feed = LinkedList()
tag = soup.feed
for entry in tag.find_all("entry"):
feed_dict = {}
for title in entry.find_all("title"):
for string in title.find_all(string=True):
feed_dict["RSS_String"] = string
feed_dict["RSS_String"] = truncate(feed_dict["RSS_String"])
for link in entry.find_all(re.compile("link?")):
feed_dict["Link"] = link.get('href')
feed.add_list_item(feed_dict)
return feed
def truncate(
input_line: str) -> str:
"""
When a string is over 80 characters long, string is limited to 79
characters for readability in GUI window, An ellipsis (...) is added to
denote unseen text
"""
if len(input_line) >= 80:
input_line = input_line[0:79]
return input_line + "..."
else:
return input_line
|
Jhawk1196/CS3250PythonProject
|
src/parser.py
|
parser.py
|
py
| 5,232 |
python
|
en
|
code
| 0 |
github-code
|
6
|
31111113064
|
#https://leetcode.com/problems/palindrome-linked-list/
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def makeList(arr):
dummy = ListNode(0)
curr = dummy
for i in arr:
curr.next = ListNode(i)
curr = curr.next
return dummy.next
def traverse(head):
curr = head
while curr:
print (curr.val)
curr = curr.next
#space and time is O(N)
#def isPalindrome(self, head: ListNode) -> bool:
# vals = []
# while head:
# vals.append(head.val)
# head = head.next
# return vals == vals[::-1]
def pal(head):
slow = head
fast = head
if not head:
return True
#corner cases when len=1 or len=2
if head.next == None:
return True
elif head.next.next == None:
if head.val == head.next.val:
return True
else:
return False
#for lengths n>=3
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# head->node----->mid<------node<-revhead
prev = None
curr = slow
while curr:
nextt = curr.next
curr.next = prev
prev = curr
curr = nextt
revhead = prev
flag = True
while head and revhead:
if head.val != revhead.val:
flag = False
break
head = head.next
revhead = revhead.next
print(flag)
return flag
head = makeList([1,2,3,3,2,1])
pal(head)
|
sparsh-m/30days
|
d6_2.py
|
d6_2.py
|
py
| 1,321 |
python
|
en
|
code
| 0 |
github-code
|
6
|
25354214474
|
def repeatedString(s, n):
mul=n//len(s)
rem=n%len(s)
if rem>0:
rem_string=s[:rem]
s= list(s)
num=s.count('a')
num*=mul
if rem>0:
num+=rem_string.count('a')
|
nikjohn7/Coding-Challenges
|
Hackerrank/Python/4.py
|
4.py
|
py
| 199 |
python
|
en
|
code
| 4 |
github-code
|
6
|
39791046463
|
# -*- coding: utf-8 -*-
# @Author: ShuaiYang
# @Date: 2019-04-02 19:05:45
# @Last Modified by: ShuaiYang
# @Last Modified time: 2019-04-02 19:05:47
# -*- coding: utf-8 -*-
# @Author: ShuaiYang
# @Date: 2019-04-02 16:57:49
# @Last Modified by: ShuaiYang
# @Last Modified time: 2019-04-02 19:05:20
import tensorflow as tf
# 首先,创建一个TensorFlow常量=>2
const = tf.constant(2.0, name='const')
# 创建TensorFlow变量b和c
b = tf.Variable(2.0, name='b')
c = tf.Variable(1.0, dtype=tf.float32, name='c')
# 创建operation
d = tf.add(b, c, name='d')
e = tf.add(c, const, name='e')
a = tf.multiply(d, e, name='a')
# 1. 定义init operation
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
# 2. 运行init operation
sess.run(init_op)
# 计算
a_out = sess.run(a)
print("Variable a is {}".format(a_out))
|
yangshuai8318243/TensorflowTestCode
|
netTestCode/testVar.py
|
testVar.py
|
py
| 852 |
python
|
en
|
code
| 1 |
github-code
|
6
|
38041664142
|
import random
def cards():
cards_typs = [
["Card 2", 2],
["Card 3", 3],
["Card 4", 4],
["Card 5", 5],
["Card 6", 6],
["Card 7", 7],
["Card 8", 8],
["Card 9", 9],
["Card 10", 10],
["Valete", 10],
["Dama", 10],
["Rei", 10],
["ÁS", 11] # Adicionei o valor 11 para o ÁS
]
random_cards = random.randint(0, 12)
card_valor = cards_typs[random_cards]
return card_valor
def calcular_soma(cartas):
for valor in cards_do_usuario:
soma = sum(cards_do_usuario)
print("soma",soma)
return soma
cards_do_usuario = []
for i in range(0, 2):
card = cards()
nome_do_cartao = card[0] # Obtém o nome do cartão
valor_do_cartao = card[1] # Obtém o valor do cartão
cards_do_usuario.append((valor_do_cartao))
opecao = input("Você deseja jogar BLACKJACK? S/N").lower()
print("2 Cartas:")
for valor in cards_do_usuario:
print(f"{valor}")
if opecao == "s":
cont = 1
else:
cont = 0
while cont == 1:
hit = int(input("Puxar uma CARTA? (1 para HIT, 0 para parar)"))
if hit == 1:
card = cards() # Sorteie uma carta
valor_do_cartao = card[1]
cards_do_usuario.append((valor_do_cartao)) # Adiciona a carta à lista
print("Carta:")
for valor in cards_do_usuario:
print(f"{valor}")
soma_cartas = calcular_soma(cards_do_usuario)
print(f"Soma das cartas: {soma_cartas}")
if soma_cartas > 21:
print("Você Perdeu")
break # Saia do loop enquanto se a soma for maior que 21
if soma_cartas <= 21:
print("Você Ganhou")
break
if hit == 0:
cont = 0
soma = 0
# Exibir as cartas sorteadas
print("Cartas sorteadas:")
for valor in cards_do_usuario:
print(f"{valor}")
|
arthurksilva/blackjack
|
blackjack.py
|
blackjack.py
|
py
| 1,896 |
python
|
pt
|
code
| 0 |
github-code
|
6
|
3229327686
|
#!/usr/bin/python
### File Information ###
"""
Rejector
"""
__author__ = '[email protected]'
import os
import fnmatch
from config import Config
class Rejector:
""" Rejector:
1. Check whether conflicts happen.
2. Resolve conflicts automatically.
"""
CONFILCT_START = "<<<<<<<"
CONFLICT_MID = "======="
CONFILCT_END = ">>>>>>>"
def __init__(self, target):
self.mTarget = target
self.mConflictNum = 0
def getConflictNum(self):
if fnmatch.fnmatch(self.mTarget, "*.xml"):
self.resolveConflict()
else:
self.collectConflict()
return self.mConflictNum
def collectConflict(self):
""" Check whether conflict happen or not in the target
"""
self.mConflictNum = 0
top = 0
size = 0
# delLinesNumbers record the lines of conflicts
delLineNumbers = []
needToDel = False
targetFile = open(self.mTarget, "r+")
lineNum = 0
lines = targetFile.readlines()
for line in lines:
size = self.mConflictNum
if line.startswith(Rejector.CONFILCT_START):
top += 1
# Modify the conflict in the original
lines[lineNum] = "%s #Conflict %d\n" % (line.rstrip(), size)
self.mConflictNum += 1
#conflicts.append("#Conflict %d , start at line %d\n" % (size, lineNum))
#conflicts[size] += line
delLineNumbers.append(lineNum)
elif line.startswith(Rejector.CONFILCT_END):
# Modify the conflict in the original
lines[lineNum] = "%s #Conflict %d\n" % (line.rstrip(), size-top)
#conflicts[size-top] += line
#conflicts[size-top] += "#Conflict %d , end at line %d\n\n" % (size-top, lineNum)
delLineNumbers.append(lineNum)
needToDel = False
if top == 0: break;
top -= 1
else:
if top > 0:
#conflicts[size-top] += line
if line.startswith(Rejector.CONFLICT_MID):
# Modify the conflict in the original
#lines[lineNum] = "%s #Conflict %d\n" % (line.rstrip(), size-top)
needToDel = True
if needToDel:
delLineNumbers.append(lineNum)
lineNum += 1
# Create a reject file if conflict happen
if self.mConflictNum > 0:
rejFilename = Rejector.createReject(self.mTarget)
rejFile = open(rejFilename, "wb")
rejFile.writelines(lines)
rejFile.close()
# Remove conflict blocks, and write back target.
for lineNum in delLineNumbers[::-1]:
del lines[lineNum]
targetFile.seek(0)
targetFile.truncate()
targetFile.writelines(lines)
targetFile.close()
return self
@staticmethod
def createReject(target):
relTarget = os.path.relpath(target, Config.PRJ_ROOT)
rejFilename = os.path.join(Config.REJ_ROOT, relTarget)
dirname = os.path.dirname(rejFilename)
if not os.path.exists(dirname):
os.makedirs(dirname)
return rejFilename
def resolveConflict(self):
rejFileHandle = open(self.mTarget, "r+")
top = 0
lineNum = 0
delLineNumbers = []
needToDel = True
lines = rejFileHandle.readlines()
for line in lines:
if line.startswith(Rejector.CONFILCT_START):
top += 1
delLineNumbers.append(lineNum)
elif line.startswith(Rejector.CONFILCT_END):
top -= 1
delLineNumbers.append(lineNum)
needToDel = True
if top < 0: break;
else:
if top > 0:
if needToDel:
delLineNumbers.append(lineNum)
if line.startswith(Rejector.CONFLICT_MID):
needToDel = False
lineNum += 1
for lineNum in delLineNumbers[::-1]:
del lines[lineNum]
rejFileHandle.seek(0)
rejFileHandle.truncate()
rejFileHandle.writelines(lines)
rejFileHandle.close()
|
baidurom/tools
|
autopatch/rejector.py
|
rejector.py
|
py
| 4,416 |
python
|
en
|
code
| 12 |
github-code
|
6
|
21273783061
|
class Session:
def __init__(self, id, checkin_date, checkout_date):
self.id = id
self.checkin_date = checkin_date
self.checkout_date = checkout_date
class Reservation:
def __init__(self,reservationid,date_of_arrival= None ,date_of_departure = None ,customerid = None ,paymentid = None ,hotelid = None ,roomid = None ,reservation_charge = None ,rating = None):
self.reservationid = reservationid
self.date_of_arrival = date_of_arrival
self.date_of_departure = date_of_departure
self.customerid = customerid
self.paymentid = paymentid
self.hotelid = hotelid
self.roomid = roomid
self.reservation_charge = reservation_charge
self.rating = rating
def __str__(self) -> str:
return str(self.reservationid) + " " + self.date_of_arrival + " " + self.date_of_departure + " " + str(self.customerid) + " " + str(self.paymentid) + " " + str(self.hotelid) + " " + str(self.roomid) + " " + str(self.reservation_charge)
class Hotel:
def __init__(self, hotelId, name=None, street=None, zipcode=None, city=None, country=None, rating=None, rating_count=None):
self.hotelId = hotelId
self.name = name
self.street = street
self.zipcode = zipcode
self.city = city
self.country = country
self.rating = rating
self.rating_count = rating_count
self.rooms = 0
self.facilities = ""
self.image_location = ""
def set_rooms(self, rooms):
self.rooms = rooms
def add_facilities(self, facility_list):
for i in range(len(facility_list)):
if i > 0:
self.facilities += ', '
self.facilities += facility_list[i]
def __str__(self):
return self.name
class Room:
def __init__(self, room_type, bed_type, cost, discount,singleId = None):
self.roomId = []
self.room_type = room_type
self.bed_type = bed_type
self.cost = cost
self.discount = discount
self.facilities = ""
self.count = 1
self.singleId = singleId
def add_facilities(self, facility_list):
for i in range(len(facility_list)):
if i > 0:
self.facilities += ', '
self.facilities += facility_list[i]
def __str__(self):
return str(self.singleId) + " " + self.room_type
class Service:
def __init__(self, serviceId, service_type, service_subtype, cost,count = None):
self.serviceId = serviceId
self.service_type = service_type
self.service_subtype = service_subtype
self.cost = cost
self.count = count
if service_type == 'Food':
self.unit = 'serving'
else:
self.unit = 'hour'
|
zarif98sjs/innOcity
|
hotel/models.py
|
models.py
|
py
| 2,816 |
python
|
en
|
code
| 5 |
github-code
|
6
|
25847894028
|
import math
from autocad_session import channel
def extract_rectangles():
ret = []
cord_names = [f"{point}{value}" for point in ['a', 'b', 'c', 'd'] for value in ['x', 'y']]
for obj in channel.session.doc.ModelSpace:
# Test if it is a rectangle
if "Polyline" in obj.ObjectName and obj.Closed:
coordinates = obj.Coordinates
if len(coordinates) != 8:
continue
len_a = math.dist(coordinates[:2], coordinates[2:4])
len_b = math.dist(coordinates[2:4], coordinates[4:6])
if (
len_a == math.dist(coordinates[4:6], coordinates[6:8]) and
len_b == math.dist(coordinates[:2], coordinates[6:8])
):
cord_dict = {cord_names[i]: value for i, value in enumerate(coordinates)}
ret.append(
dict(
len_a=len_a,
len_b=len_b,
# Floating point conversion problems, not using obj.Area
area=len_a * len_b,
perimeter=2 * len_b + 2 * len_b,
**cord_dict,
)
)
return ret
|
akila122/pycad
|
actions/extract_rectangle.py
|
extract_rectangle.py
|
py
| 1,237 |
python
|
en
|
code
| 0 |
github-code
|
6
|
18308754842
|
from tempfile import gettempdir
import urllib.request
import platform
import zipfile
from os.path import join
from os import walk
pth = "https://github.com/AequilibraE/aequilibrae/releases/download/V0.6.0.post1/mod_spatialite-NG-win-amd64.zip"
outfolder = gettempdir()
dest_path = join(outfolder, "mod_spatialite-NG-win-amd64.zip")
urllib.request.urlretrieve(pth, dest_path)
fldr = join(outfolder, "temp_data")
zipfile.ZipFile(dest_path).extractall(fldr)
if "WINDOWS" in platform.platform().upper():
# We now set sqlite. Only needed in thge windows server in Github
plats = {
"x86": "https://sqlite.org/2020/sqlite-dll-win32-x86-3320100.zip",
"x64": "https://sqlite.org/2020/sqlite-dll-win64-x64-3320100.zip",
}
outfolder = "C:/"
zip_path64 = join(outfolder, "sqlite-dll-win64-x64-3320100.zip")
urllib.request.urlretrieve(plats["x64"], zip_path64)
zip_path86 = join(outfolder, "sqlite-dll-win32-x86-3320100.zip")
urllib.request.urlretrieve(plats["x86"], zip_path86)
root = "C:/hostedtoolcache/windows/Python/"
file = "sqlite3.dll"
for d, subD, f in walk(root):
if file in f:
if "x64" in d:
zipfile.ZipFile(zip_path64).extractall(d)
else:
zipfile.ZipFile(zip_path86).extractall(d)
print(f"Replaces {d}")
|
AequilibraE/aequilibrae
|
tests/setup_windows_spatialite.py
|
setup_windows_spatialite.py
|
py
| 1,347 |
python
|
en
|
code
| 140 |
github-code
|
6
|
18609666305
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from waveapi import events
from waveapi import model
from waveapi import robot
from pyactiveresource.activeresource import ActiveResource
import logging
import settings
CC_XMPP = 'cc:xmpp'
CC_TWITTER = 'cc:twitter'
logger = logging.getLogger('GAE_Robot')
logger.setLevel(logging.INFO)
class Notification(ActiveResource):
_site = settings.MPUB_SITE
### Webhooks start
def OnParticipantsChanged(properties, context):
"""Invoked when any participants have been added/removed."""
added = properties['participantsAdded']
for p in added:
if p != settings.ROBOT_NICK+'@appspot.com':
Notify(context, "Hi, " + p)
def OnRobotAdded(properties, context):
"""Invoked when the robot has been added."""
root_wavelet = context.GetRootWavelet()
root_wavelet.CreateBlip().GetDocument().SetText("Connected to XMPP...")
def OnBlipSubmitted(properties, context):
"""Invoked when new blip submitted."""
blip = context.GetBlipById(properties['blipId'])
doc = blip.GetDocument()
creator = blip.GetCreator()
text = doc.GetText()
try:
if creator in settings.ADMINS and text != '' and text !='cc:xmpp' and text !='cc:twitter':
if CC_XMPP in text:
text = text.replace('cc:xmpp','')
note = Notification({'escalation':10, 'body':text, 'recipients':{'recipient':[{'position':1,'channel':'gchat','address':settings.MPUB_XMPP}]}})
note.save()
if CC_TWITTER in text:
text = text.replace('cc:twitter','')
note = Notification({'escalation':10, 'body':text, 'recipients':{'recipient':[{'position':1,'channel':'twitter','address':settings.MPUB_TWITTER}]}})
note.save()
except:
logger.debug(context, 'Submit failed. (blip=%s)' % properties['blipId'])
pass
### Webhooks end
def Notify(context, message):
root_wavelet = context.GetRootWavelet()
root_wavelet.CreateBlip().GetDocument().SetText(message)
if __name__ == '__main__':
myRobot = robot.Robot(settings.ROBOT_NICK,
image_url='http://%s.appspot.com/assets/bot.png' % settings.ROBOT_NICK,
version='1',
profile_url='http://%s.appspot.com/' % settings.ROBOT_NICK)
myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
myRobot.Run(debug=settings.DEBUG)
|
zh/gae-robot
|
gaerobot.py
|
gaerobot.py
|
py
| 2,435 |
python
|
en
|
code
| 4 |
github-code
|
6
|
14676087381
|
nums = input().split()
print("Resumo dos Ímpares Positivos")
print()
cont = ""
soma = 0
for l in nums:
numero = int(l)
if l % "2" != "0"and l > "0":
soma += numero
cont += nums[l]
quant = len(cont)
if quant == 0:
print(f"Quantidade: {quant}")
print(f"Maior: Não existe")
print(f"menor: Não existe")
lista = list(cont)
maior = lista[0]
menor = lista[0]
for valor in lista:
if valor > maior:
maior = valor
if valor < menor:
menor = valor
print(f"Quantidade: {quant}")
print(f"Maior: {maior}")
print(f"Menor: {menor}")
print(soma)
|
lucas-santiagoo/Resumo-dos-mpares-Positivos
|
solucao.py
|
solucao.py
|
py
| 721 |
python
|
pt
|
code
| 0 |
github-code
|
6
|
14720838146
|
import torch
import torch.nn as nn
from collections import OrderedDict
from networks.reshape import Reshape
class ImageEncoder(nn.Module):
def __init__(self, input_channels, layers_channels, prefix, useMaxPool=False, addFlatten=False):
'''
If useMaxPool is set to True, Max pooling is used to reduce
the image dims instead of stride = 2.
'''
super(ImageEncoder, self).__init__()
layers = OrderedDict()
pr_ch = input_channels
stride = 1 if useMaxPool else 2
for i in range(len(layers_channels)):
layers[prefix + '_conv' + str(i)] = nn.Conv2d(in_channels=pr_ch,
out_channels=layers_channels[i],
kernel_size=3, stride=stride, padding=1)
layers[prefix + '_relu' + str(i)] = nn.ReLU()
if (useMaxPool):
layers[prefix + '_maxpool' + str(i)] = nn.MaxPool2d(2, stride=2)
pr_ch = layers_channels[i]
if addFlatten:
layers[prefix + '_flat'] = nn.Flatten()
self.net = nn.Sequential(layers)
def forward(self, data):
return self.net(data)
class ImageEncoderFlatInput(ImageEncoder):
def __init__(self, input_channels, layers_channels, prefix, useMaxPool=False, addFlatten=False):
super(ImageEncoderFlatInput, self).__init__(input_channels, layers_channels, prefix, useMaxPool, addFlatten)
self.reshapeInput = Reshape(-1, input_channels, 32, 32)
def forward(self, data):
return self.net(self.reshapeInput(data))
|
PradeepKadubandi/DemoPlanner
|
networks/imageencoder.py
|
imageencoder.py
|
py
| 1,593 |
python
|
en
|
code
| 0 |
github-code
|
6
|
3982882771
|
from time import time
import sys, argparse, heightfield, os, povray_writer, load_info, read_lidar, cameraUtils, calculate_tile
#/media/pablo/280F8D1D0A5B8545/TFG_files/cliente_local/
#/media/pablo/280F8D1D0A5B8545/TFG_files/strummerTFIU.github.io/
def tiles_to_render(c1, c2, zoom):
"""
Return the tiles needed to render the scene and the limit coordinates.
Normal test
>>> tiles_to_render((700000, 4600000), (702000, 4602000), 8)
((130, 122), (131, 123), (699452.3984375, 4600406.1953125), (704062.296875, 4595796.296875))
Over limit test
>>> tiles_to_render((700000, 4600000), (2702000, 4602000), 8)
('null', 'null', 'null', 'null')
"""
# Calculate tiles
tile1_x, tile1_y = calculate_tile.calculate_tile(c1[0], c1[1], zoom)
tile2_x, tile2_y = calculate_tile.calculate_tile(c2[0], c2[1], zoom)
if tile1_x == 'null' or tile1_y == 'null' or tile2_x == 'null' or tile2_y == 'null':
return ('null', 'null', 'null', 'null')
w_tiles = tile2_x - tile1_x + 1
h_tiles = tile2_y - tile1_y + 1
if w_tiles != h_tiles:
tile_max = max(w_tiles, h_tiles)
w_tiles = tile_max
h_tiles = tile_max
tile2_x = tile1_x + w_tiles - 1
tile2_y = tile1_y + h_tiles - 1
# Calculate new coordinates
c_nw = calculate_tile.calculate_coordinates(tile1_x, tile1_y, zoom)
c_se = calculate_tile.calculate_coordinates(tile2_x + 1, tile2_y + 1, zoom)
if c_nw == 'null' or c_se == 'null':
return('null', 'null', 'null', 'null')
return ((tile1_x, tile1_y), (tile2_x, tile2_y), c_nw, c_se)
def dir_view_tile(tile, dir_view, zoom):
"""
Transform north tile number to specified POV tile number.
>>> dir_view_tile((222, 111), 'E', 9)
(111, 289)
"""
if dir_view == 'S':
return calculate_tile.tile_to_south(tile, zoom)
elif dir_view == 'E':
return calculate_tile.tile_to_east(tile, zoom)
elif dir_view == 'W':
return calculate_tile.tile_to_west(tile, zoom)
else:
return tile
def render(tile1, tile2, c1, c2, dir_view, angle, result, lidar):
"""
Generate the POV-Ray file which represents the scene passed as parameters.
"""
# Apply a offset
off_c1_0 = 0
off_c1_1 = 0
off_c2_0 = 0
off_c2_1 = 0
if dir_view == 'N':
off_c1_1 = 500
off_c2_1 = -2500
elif dir_view == 'S':
off_c1_1 = 2500
off_c2_1 = -500
elif dir_view == 'E':
off_c1_0 = -2500
off_c2_0 = 500
else:
off_c1_0 = -500
off_c2_0 = 2500
# Find mdts and ortophotos and write heighfields info
mdt_list = load_info.find_mdt(c1[0] + off_c1_0, c1[1] + off_c1_1, c2[0] + off_c2_0, c2[1] + off_c2_1)
if len(mdt_list) == 0:
return ('null', 'null', 'null')
orto_list = load_info.find_orto(c1[0] + off_c1_0, c1[1] + off_c1_1, c2[0] + off_c2_0, c2[1] + off_c2_1, mdt_list)
areas_list = load_info.find_a_interest(c1[0], c1[1], c2[0], c2[1])
lidar_list = load_info.find_lidar(areas_list, c1, c2)
if len(orto_list) <= 10:
if lidar == True:
spheres = read_lidar.generate_spheres(lidar_list, areas_list, c1, c2)
else:
spheres = ""
# Create camera, heighfields and spheres
cam = cameraUtils.calculate_camera(c1, c2, angle, dir_view)
heightfields = povray_writer.write_heightfields(mdt_list, orto_list) # Generate a string which contain the heightfields to pov file.
# Generate povray file
tile_size_x = 256
tile_size_y = int(256 / cam.get_aspectRatio() + 0.5)
povray_writer.write_povray_file(cam, heightfields, spheres)
w_tiles = tile2[0] - tile1[0] + 1
h_tiles = tile2[1] - tile1[1] + 1
w = tile_size_x * w_tiles
h = tile_size_y * h_tiles
# Rendering using new povray file
print("Rendering " + result)
os.system('povray +Irender.pov +O' + result + ' -D +A -GA +W' + str(w) + ' +H' + str(h) + '> /dev/null 2>&1')
return (tile_size_x, tile_size_y, w_tiles)
else:
print("Error: The zone to render must be smaller (orto_list > 10). Try with other coordinates.")
def tessellation(result, tile1, tile_size_x, tile_size_y, w_tiles, zoom, dir_view, angle, dist_tile):
"""
Create tiles for a few zooms and give them a number.
"""
if dist_tile[-1] != "/":
dist_tile += "/"
print("Creating tiles from [" + str(tile1[0]) + ", " + str(tile1[1]) + "]...")
os.system("mkdir " + dist_tile + angle + '> /dev/null 2>&1')
os.system("mkdir " + dist_tile + angle + "/" + dir_view + '> /dev/null 2>&1')
os.system("mkdir " + dist_tile + angle + "/" + dir_view + "/" + str(zoom) + '> /dev/null 2>&1')
os.system("convert " + result + " -crop " + str(tile_size_x) + "x" + str(tile_size_y) + " -set filename:tile \"%[fx:page.x/"
+ str(tile_size_x) + "+" + str(tile1[0]) + "]_%[fx:page.y/" + str(tile_size_y) + "+" + str(tile1[1]) + "]\" +adjoin \""
+ dist_tile + angle + "/" + dir_view + "/" + str(zoom) + "/map_%[filename:tile].png\"")
count = int(zoom) - 8
aux_zoom = int(zoom) - 1
aux1_x = int(tile1[0] / 2)
aux1_y = int(tile1[1] / 2)
while(count > 0):
# -1 zoom lvl
w_tiles = w_tiles / 2
w = tile_size_x * w_tiles
h = tile_size_y * w_tiles
os.system("mkdir " + dist_tile + angle + "/" + dir_view + "/" + str(aux_zoom) + '> /dev/null 2>&1')
os.system("convert " + result + " -resize " + str(w) + "x" + str(h) + " " + result)
os.system("convert " + result + " -crop " + str(tile_size_x) + "x" + str(tile_size_y) + " -set filename:tile \"%[fx:page.x/"
+ str(tile_size_x) + "+" + str(aux1_x) + "]_%[fx:page.y/" + str(tile_size_y) + "+" + str(aux1_y) + "]\" +adjoin \""
+ dist_tile + angle + "/" + dir_view + "/" + str(aux_zoom) + "/map_%[filename:tile].png\"")
count -= 1
aux_zoom -= 1
aux1_x = aux1_x / 2
aux1_y = aux1_y / 2
os.system("rm " + result)
def main():
# Arguments
parser = argparse.ArgumentParser(description="First version of Pablo's TFG.")
parser.add_argument("mdt_directory", help="Directory of the MDT files to transform.")
parser.add_argument("png_directory", help="PNG files transformed destination directory.")
parser.add_argument("orto_directory", help="Ortophotos files directory.")
parser.add_argument("lidar_directory", help="Directory of LAZ files.")
parser.add_argument("dir_view", help="Direction of the view (only N, S, E or W).")
parser.add_argument("angle", help="Angle of the view (only 45 or 30).")
parser.add_argument("zoom", help="Zoom.")
parser.add_argument("--max_height", dest="max_height", type=int, default=2200, metavar="MAX_HEIGHT",
help="Max height transforming MDT files. Higher heights will be considered MAX_HEIGHT " +
"(default value = 2200)")
parser.add_argument("--renderAll", help="Render all available zones.", action="store_true")
parser.add_argument("--renderTiles", help="Render especified tiles.", action="store_true")
parser.add_argument("--transform", help="Transform all mdt in mdt_directory from .asc to .png.", action="store_true")
parser.add_argument("--load", help="Load info from mdts, pnoas and lidar files.", action="store_true")
parser.add_argument("--tile", help="Tessellation result/s.", action="store_true")
parser.add_argument("--deletePov", help="Delete povray file.", action="store_true")
parser.add_argument("--lidar", help="Activate LiDAR render.", action="store_true")
args = parser.parse_args()
if (args.angle == "30") or (args.angle == "45"):
if (args.dir_view == 'S') or (args.dir_view == 'N') or (args.dir_view == 'W') or (args.dir_view == 'E'):
t_exe_i = time()
if args.mdt_directory[-1] != "/":
args.mdt_directory += "/"
if args.png_directory[-1] != "/":
args.png_directory += "/"
if args.orto_directory[-1] != "/":
args.orto_directory += "/"
if args.lidar_directory[-1] != "/":
args.lidar_directory += "/"
# Transform to heightfield
if args.transform:
os.system('mkdir ' + args.png_directory)
for base, dirs, files in os.walk(args.mdt_directory):
for asc_file in files:
heightfield.transform_file_to_heightfield(args.mdt_directory + asc_file, args.png_directory
+ asc_file[:-4] + ".png", args.max_height)
# Load info data to file
if args.load:
load_info.load_info(args.png_directory, args.orto_directory, args.lidar_directory)
if args.tile:
dist_tile = input("Introduce tiles destination directory: ")
else:
os.system("mkdir result_dir")
dist_tile = "./result_dir/"
minX = 560000
maxX = 789000
minY = 4410000
maxY = 4745000
if args.renderTiles:
tile_init = input("Introduce tile number (x y) for upper left vertex: ").split()
tile_init = (int(tile_init[0]), int(tile_init[1]))
if tile_init[0] >= 0 and tile_init[0] <= (2 ** int(args.zoom) - 1) and tile_init[1] >= 0 or tile_init[1] <= (2 ** int(args.zoom) - 1):
tile_end = input("Introduce tile number (x,y) for bottom right vertex: ").split()
tile_end = (int(tile_end[0]), int(tile_end[1]))
if tile_end[0] >= 0 and tile_end[0] <= (2 ** int(args.zoom) - 1) and tile_end[1] >= 0 or tile_end[1] <= (2 ** int(args.zoom) - 1
and tile_end[0] >= tile_init[0] and tile_end[1] >= tile_init[1]):
result = "./result.png"
if args.dir_view == 'S':
tile_1 = calculate_tile.tile_from_south(tile_end, int(args.zoom))
tile_2 = calculate_tile.tile_from_south(tile_init, int(args.zoom))
elif args.dir_view == 'E':
tile_1_aux = calculate_tile.tile_from_east(tile_init, int(args.zoom))
tile_2_aux = calculate_tile.tile_from_east(tile_end, int(args.zoom))
tile_1 = (tile_2_aux[0], tile_1_aux[1])
tile_2 = (tile_1_aux[0], tile_2_aux[1])
elif args.dir_view == 'W':
tile_1_aux = calculate_tile.tile_from_west(tile_init, int(args.zoom))
tile_2_aux = calculate_tile.tile_from_west(tile_end, int(args.zoom))
tile_1 = (tile_1_aux[0], tile_2_aux[1])
tile_2 = (tile_2_aux[0], tile_1_aux[1])
else:
tile_1 = tile_init
tile_2 = tile_end
tile_1 = [x - 1 if x % 2 != 0 else x for x in tile_1]
tile_2 = [x - 1 if x % 2 == 0 else x for x in tile_2]
tile1_x = tile_1[0]
tile1_y = tile_1[1]
tile2_x = tile_2[0]
tile2_y = tile_2[1]
n_tiles = 2 ** (int(args.zoom) - 8)
print([tile1_x, tile1_y])
print([tile2_x, tile2_y])
while tile1_x % n_tiles != 0:
tile1_x -= 1
while tile1_y % n_tiles != 0:
tile1_y -= 1
while tile2_x % n_tiles == 0 and n_tiles != 1:
tile2_x -= 1
while tile2_x % n_tiles == 0 and n_tiles != 1:
tile2_x -= 1
print([tile1_x, tile1_y])
print([tile2_x, tile2_y])
x_number = 0
while(tile1_x + x_number <= tile2_x):
aux1_x = tile1_x + x_number
y_number = 0
while(tile1_y + y_number <= tile2_y):
aux1_y = tile1_y + y_number
c_nw = calculate_tile.calculate_coordinates(aux1_x, aux1_y, int(args.zoom))
c_se = calculate_tile.calculate_coordinates(aux1_x + n_tiles, aux1_y + n_tiles, int(args.zoom))
if c_nw == 'null' or c_se == 'null':
print("ERROR: Wrong tiles.")
else:
print("Rendering from tile [" + str(aux1_x) + ", " + str(aux1_y) + "] to [" + str(aux1_x + n_tiles - 1)
+ "," + str(aux1_y + n_tiles -1) + "] with coordinates from [" + str(c_nw[0]) + ", " + str(c_nw[1])
+ "] to [" + str(c_se[0]) + ", " + str(c_se[1]) + "].")
tile_size_x, tile_size_y, w_tiles = render((aux1_x, aux1_y), (aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), c_nw, c_se, args.dir_view, args.angle, result, args.lidar)
if tile_size_x == 'null' and tile_size_y == 'null':
print("ERROR: Nothing to render. Continuing...")
else:
if args.dir_view == 'S':
tile_init = calculate_tile.tile_to_south((aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), int(args.zoom))
elif args.dir_view == 'E':
tile1_aux = calculate_tile.tile_to_east((aux1_x, aux1_y), int(args.zoom))
tile2_aux = calculate_tile.tile_to_east((aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), int(args.zoom))
tile_init = (tile1_aux[0], tile2_aux[1])
elif args.dir_view == 'W':
tile1_aux = calculate_tile.tile_to_west((aux1_x, aux1_y), int(args.zoom))
tile2_aux = calculate_tile.tile_to_west((aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), int(args.zoom))
tile_init = (tile2_aux[0], tile1_aux[1])
else:
tile_init = (aux1_x, aux1_y)
tessellation(result, tile_init, tile_size_x, tile_size_y, w_tiles, args.zoom, args.dir_view, args.angle, dist_tile)
y_number += n_tiles
x_number += n_tiles
else:
print("ERROR: Introduce tiles correctly.")
else:
print("ERROR: Introduce tiles correctly.")
else:
if args.renderAll:
if int(args.zoom) > 7 and int(args.zoom) < 13:
iTile_z5_x = 9
iTile_z5_y = 8
fTile_z5_x = 26
fTile_z5_y = 25
tile1_x = iTile_z5_x * (2 ** (int(args.zoom) - 5))
tile1_y = iTile_z5_y * (2 ** (int(args.zoom) - 5))
tile2_x = fTile_z5_x * (2 ** (int(args.zoom) - 5))
tile2_y = fTile_z5_y * (2 ** (int(args.zoom) - 5))
#tile1_x = 672
result = "./result.png"
n_tiles = 2 ** (int(args.zoom) - 8)
x_number = 0
while(tile1_x + x_number <= tile2_x):
aux1_x = tile1_x + x_number
y_number = 0
while(tile1_y + y_number <= tile2_y):
aux1_y = tile1_y + y_number
c_nw = calculate_tile.calculate_coordinates(aux1_x, aux1_y, int(args.zoom))
c_se = calculate_tile.calculate_coordinates(aux1_x + n_tiles, aux1_y + n_tiles, int(args.zoom))
if c_nw == 'null' or c_se == 'null':
print("ERROR: Wrong tiles.")
else:
print("Rendering from tile [" + str(aux1_x) + ", " + str(aux1_y) + "] to [" + str(aux1_x + n_tiles - 1)
+ "," + str(aux1_y + n_tiles -1) + "] with coordinates from [" + str(c_nw[0]) + ", " + str(c_nw[1])
+ "] to [" + str(c_se[0]) + ", " + str(c_se[1]) + "].")
tile_size_x, tile_size_y, w_tiles = render((aux1_x, aux1_y), (aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), c_nw, c_se, args.dir_view, args.angle, result, args.lidar)
if tile_size_x == 'null' and tile_size_y == 'null':
print("ERROR: Nothing to render. Continuing...")
else:
if args.dir_view == 'S':
tile_init = calculate_tile.tile_to_south((aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), int(args.zoom))
elif args.dir_view == 'E':
tile1_aux = calculate_tile.tile_to_east((aux1_x, aux1_y), int(args.zoom))
tile2_aux = calculate_tile.tile_to_east((aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), int(args.zoom))
tile_init = (tile1_aux[0], tile2_aux[1])
elif args.dir_view == 'W':
tile1_aux = calculate_tile.tile_to_west((aux1_x, aux1_y), int(args.zoom))
tile2_aux = calculate_tile.tile_to_west((aux1_x + n_tiles - 1, aux1_y + n_tiles - 1), int(args.zoom))
tile_init = (tile2_aux[0], tile1_aux[1])
else:
tile_init = (aux1_x, aux1_y)
tessellation(result, tile_init, tile_size_x, tile_size_y, w_tiles, args.zoom, args.dir_view, args.angle, dist_tile)
y_number += n_tiles
x_number += n_tiles
else:
print("ERROR: zoom for --renderAll option must be 7 < z < 13.")
else:
# Ask for coordinates
coordinates = input("Introduce UTM X and Y coordinates, separated by a blank space and respecting the values min "
+ "and max for the coordinates, for upper left vertex (" + str(minX) + " <= X1 <= " + str(maxX) + " " + str(minY)
+ " <= Y1 <= " + str(maxY) + "): ")
coordinates1 = coordinates.split()
if (len(coordinates1) == 2 and float(coordinates1[0]) >= minX and float(coordinates1[0]) <= maxX and
float(coordinates1[1]) >= minY and float(coordinates1[1]) <= maxY):
coordinates = input("Introduce UTM X and Y coordinates, separated by a blank space and respecting the values min "
+ "and max for the coordinates, for bottom right vertex (" + coordinates1[0] + " <= X2 <= " + str(maxX) + " " + str(minY)
+ " <= Y2 <= " + coordinates1[1] + "): ")
coordinates2 = coordinates.split()
if (len(coordinates2) == 2 and float(coordinates2[0]) >= minX and float(coordinates2[0]) <= maxX and
float(coordinates2[1]) >= minY and float(coordinates2[1]) <= maxY and coordinates1[0] < coordinates2[0]
and coordinates1[1] > coordinates2[1]):
# Offset to adjust later during join process
coordinates1[0] = float(coordinates1[0])
coordinates2[0] = float(coordinates2[0])
coordinates1[1] = float(coordinates1[1])
coordinates2[1] = float(coordinates2[1])
result = "./result.png"
tile1, tile2, c_nw, c_se = tiles_to_render(coordinates1, coordinates2, int(args.zoom))
if tile_1 == 'null':
print("ERROR: Introduce UTM coordinates correctly.")
else:
if args.dir_view == 'S':
tile_init = calculate_tile.tile_to_south(tile2, int(args.zoom))
elif args.dir_view == 'E':
tile1_aux = calculate_tile.tile_to_east(tile1, int(args.zoom))
tile2_aux = calculate_tile.tile_to_east(tile2, int(args.zoom))
tile_init = (tile1_aux[0], tile2_aux[1])
elif args.dir_view == 'W':
tile1_aux = calculate_tile.tile_to_west(tile1, int(args.zoom))
tile2_aux = calculate_tile.tile_to_west(tile2, int(args.zoom))
tile_init = (tile2_aux[0], tile1_aux[1])
else:
tile_init = tile1
tile_size_x, tile_size_y, w_tiles = render(tile1, tile2, c_nw, c_se, args.dir_view, args.angle, result, args.lidar)
tessellation(result, tile_init, tile_size_x, tile_size_y, w_tiles, args.zoom, args.dir_view, args.angle, dist_tile)
print("DONE!")
else:
print("ERROR: Introduce UTM coordinates correctly.")
else:
print("ERROR: Introduce UTM coordinates correctly.")
if args.deletePov:
os.system('rm render.pov')
t_exe_f = time()
t_exe = t_exe_f - t_exe_i
print("Execution time: " + str(int(t_exe / 60)) + "min " + str(int(t_exe % 60)) + "s.")
else:
print("ERROR: dir_view must be N, S, W or E.")
else:
print("ERROR: angle must be 45 or 30.")
if __name__ == "__main__":
main()
|
strummerTFIU/TFG-IsometricMaps
|
src/main_program.py
|
main_program.py
|
py
| 18,332 |
python
|
en
|
code
| 0 |
github-code
|
6
|
34889766883
|
class Pitcher:
"""Class containing starting pitcher data"""
def __init__(self, pitcher_block=None, home_team=None):
self.pitcher_block = pitcher_block
self.home_team = home_team
self.player_name = None
self.player_id = None
self.player_handedness = None
self.pitcher_df = None
def set_pitcher_block(self, pitcher_block):
self.pitcher_block = pitcher_block
def set_home_team(self, home_team: bool):
self.home_team = home_team
def set_player_name(self):
self.player_name = self.pitcher_block.select(".starting-lineups__pitcher-name")[
int(self.home_team)
].a.get_text()
def set_player_id(self):
self.player_id = (
self.pitcher_block.select(".starting-lineups__pitcher-name")[int(self.home_team)]
.a["href"]
.split("-")[2]
)
def set_player_handedness(self):
self.player_handedness = (
self.pitcher_block.select(".starting-lineups__pitcher-pitch-hand")[int(self.home_team)]
.get_text()
.strip()
)
def set_batter_df(self):
if self.player_position != "P":
batter_data = {
"mlb_pitcher_name": self.player_name,
"mlb_pitcher_id": self.player_id,
"team_tricode": "",
"game_time": "",
"handedness": self.player_handedness,
"park": "",
"home_team": "",
"mlb_opp_team_tricode": "",
}
self.batter_df = pd.Series(batter_data).to_frame()
def set_vars(self):
self.set_player_name()
self.set_player_id()
self.set_player_handedness()
|
xzachx/mlb_data_scraper
|
mlb_data_scraper/pitcher.py
|
pitcher.py
|
py
| 1,752 |
python
|
en
|
code
| 0 |
github-code
|
6
|
25003790859
|
import math
from typing import Tuple
import tensorflow as tf
class ParityDataset(tf.keras.utils.Sequence):
def __init__(self, n_samples: int, n_elems: int = 64, batch_size: int = 128):
"""
Parameters
----------
n_samples : int
Number of samples.
n_elems : int, optional
Number of elements in the input vector.
The default is 64.
batch_size : int, optional
Batch size.
The default is 128.
"""
self.n_samples = n_samples
self.n_elems = n_elems
self.batch_size = batch_size
def __len__(self) -> int:
return int(math.floor(self.n_samples) / self.batch_size)
@tf.function
def __batch_generation(self) -> Tuple[tf.Tensor, tf.Tensor]:
X = []
Y = []
for _ in range(self.batch_size):
n_non_zero = tf.random.uniform((), 1, self.n_elems + 1, tf.int32)
x = tf.random.uniform((n_non_zero,), 0, 2, tf.int32) * 2 - 1
x = tf.concat(
[x, tf.zeros((self.n_elems - n_non_zero), dtype=tf.int32)], axis=0
)
x = tf.random.shuffle(x)
y = tf.math.reduce_sum(tf.cast(tf.equal(x, 1), tf.int32)) % 2
X.append(x)
Y.append(y)
X = tf.cast(tf.stack(X), tf.keras.backend.floatx())
Y = tf.cast(tf.stack(Y), tf.keras.backend.floatx())
return X, Y
def __getitem__(self, index: int) -> Tuple[tf.Tensor, tf.Tensor]:
batch_X, batch_Y = self.__batch_generation()
return batch_X, batch_Y
|
EMalagoli92/PonderNet-TensorFlow
|
pondernet_tensorflow/dataset/parity_dataset.py
|
parity_dataset.py
|
py
| 1,598 |
python
|
en
|
code
| 1 |
github-code
|
6
|
75092480826
|
from flint import acb
class DirichletSeries:
"""
Class represents Dirichlet series with given coefficients. Can be called with
various s values multiple times.
"""
def __init__(self, coefs):
"""
:param coefs: tuple of N series coefficients
"""
self.coefs = coefs
self.coefs_num = len(coefs)
def __call__(self, s) -> acb:
"""
Return the sum of this series given parameter s.
:param s: complex number
:return: complex value - sum of series in point s
"""
value = acb('0')
for i in range(self.coefs_num):
value += self.coefs[i] * acb(i + 1).pow(-s)
return value
|
Deimos-Apollon/Dzeta-project
|
src/dirichlet_series/dirichlet_series_class.py
|
dirichlet_series_class.py
|
py
| 703 |
python
|
en
|
code
| 1 |
github-code
|
6
|
2888676781
|
import numpy as np
from matplotlib import pyplot as plt
if __name__ == '__main__':
ch, time, date = np.genfromtxt("events220302_1d.dat", unpack=True,
dtype=(int, float, 'datetime64[ms]'))
mask1 = ch==1
mask2 = ch==2
time1 = time[mask1]
time2 = time[mask2]
date1 = date[mask1]
date2 = date[mask2]
limit = np.datetime64("2022-03-02T13")
fig, ax = plt.subplots(2,1, sharex=True)
ax[0].errorbar(date1[date1 < limit], time1[date1 < limit], fmt='.k', markersize=0.6)
ax[1].errorbar(date2[date2 < limit], time2[date2 < limit], fmt='.k', markersize=0.6)
ax[0].set_ylabel("FPGA timestamp [s]")
ax[1].set_ylabel("FPGA timestamp [s]")
ax[0].set_title("CHANNEL 1")
ax[1].set_title("CHANNEL 2")
ax[1].set_xlabel("Local time [dd hh:mm]")
plt.show()
|
brinus/Sciami_lab4
|
UNIX_vs_FPGA.py
|
UNIX_vs_FPGA.py
|
py
| 841 |
python
|
en
|
code
| 0 |
github-code
|
6
|
30513150384
|
import json
from .bx24.requests import Bitrix24
from .report.report_to_html import Report
from .params import TYPE_MERGE_FIELD
from.field_contacts_merge.data_update import FieldsContactsUpdate
from api_v1.models import Email, Contacts, Companies, Deals
bx24 = Bitrix24()
# добавление контакта в БД
def contacts_create(res_from_bx, lock):
for _, contacts in res_from_bx.items():
for contact in contacts:
emails = []
if "EMAIL" in contact:
emails = contact.pop("EMAIL")
# замена пустых значений на None
contact = replace_empty_value_with_none__in_dict(contact)
# сохранение контакта
lock.acquire()
contact_item, created = Contacts.objects.update_or_create(**contact)
lock.release()
if emails:
lock.acquire()
email_create(emails, contact_item)
lock.release()
# добавление EMAIL в БД
def email_create(emails, contact):
for email in emails:
# uniq_value = f"{email['VALUE']}{contact_name}" if email['VALUE'] and contact_name else None
Email.objects.update_or_create(VALUE=email['VALUE'], VALUE_TYPE=email['VALUE_TYPE'], contacts=contact)
# добавление компаний в БД
def companies_create(res_from_bx, lock):
for _, companies in res_from_bx.items():
for company in companies:
# сохранение компании
lock.acquire()
company_item, created = Companies.objects.update_or_create(**company)
lock.release()
# добавление сделок в БД
def deals_create(res_from_bx, lock):
for _, deals in res_from_bx.items():
for deal in deals:
# сохранение сделок
lock.acquire()
deal_item, created = Deals.objects.update_or_create(**deal)
lock.release()
# связывание записей таблиц контактов и компаний в БД
def company_bind_contact(res_from_bx, lock):
for id_company, contacts in res_from_bx.items():
for contact in contacts:
# сохранение компании
lock.acquire()
company_obj = Companies.objects.filter(ID=id_company).first()
contact_obj = Contacts.objects.filter(ID=contact['CONTACT_ID']).first()
if company_obj and contact_obj:
res = company_obj.contacts.add(contact_obj)
lock.release()
# связывание записей таблиц контактов и сделок в БД
def deal_bind_contact(res_from_bx, lock):
for id_deal, contacts in res_from_bx.items():
for contact in contacts:
lock.acquire()
deal_obj = Deals.objects.filter(ID=id_deal).first()
contact_obj = Contacts.objects.filter(ID=contact['CONTACT_ID']).first()
if deal_obj and contact_obj:
res = deal_obj.contacts.add(contact_obj)
lock.release()
# замена пустых значений в словаре на None
def replace_empty_value_with_none__in_dict(d):
for key in d:
if not d[key]:
d[key] = None
return d
# объединение контактов с переданным списком идентификаторов
def merge_contacts(ids, lock, report):
fields = get_fields_contact()
# список контактов (возвращает словарь {<id_контакта>: <данные>})
contacts = get_data_contacts(ids)
if not contacts:
return
# объединение значений полей
contacts_update = FieldsContactsUpdate(bx24, contacts)
# ID последнего созданного контакта
id_contact_last = contacts_update.get_id_max_date()
# ID компании для добавления в последний созданный контакт
companies = contacts_update.get_field_company_non_empty()
# ID сделок для добавления в последний созданный контакт
deals = contacts_update.get_field_deal_non_empty()
data = {}
for field, field_data in fields.items():
if field_data['isReadOnly'] is True:
continue
elif field in TYPE_MERGE_FIELD['max_length']:
data[field] = contacts_update.get_field_rule_max_length(field)
elif field in TYPE_MERGE_FIELD['concat_asc_date']:
data[field] = contacts_update.get_field_rule_concat_asc_date(field)
elif field in TYPE_MERGE_FIELD['concat_desc_date']:
data[field] = contacts_update.get_field_rule_concat_desc_date(field)
elif field_data['type'] == 'crm_multifield':
field_content = contacts_update.get_field_type_crm_multifield(field)
if field_content:
data[field] = field_content
elif field_data['type'] == 'file':
field_content = contacts_update.get_field_type_file(field)
if field_content:
data[field] = field_content
else:
field_content = contacts_update.get_field_non_empty(field)
if field_content:
data[field] = field_content
# обновление контакта
res_update_contact = update_data_contacts(id_contact_last, data)
# добавление компаний к контакту
res_add_companies = add_companies_to_contact(id_contact_last, companies)
# добавление сделок к контакту
res_add_deals = add_deals_to_contact(id_contact_last, deals)
if res_update_contact and res_add_companies and res_add_deals:
deals_obj = get_dealid_by_contacts(id_contact_last, ids, deals)
# добавление данных в отчет
lock.acquire()
report.add_fields(fields)
report.add(contacts, id_contact_last, data, companies, deals_obj)
lock.release()
del_companies_to_contact(ids, id_contact_last)
def get_dealid_by_contacts(id_contact_last, ids_contacts, deals):
deals_obj = {}
deals_contact_last = Deals.objects.filter(contacts=id_contact_last).values_list("ID", flat=True)
deals_obj["summary"] = deals + list(deals_contact_last)
for id_contact in ids_contacts:
deals_contact = Deals.objects.filter(contacts=id_contact).values_list("ID", flat=True)
deals_obj[str(id_contact)] = list(deals_contact)
return deals_obj
# удаление контактов
def del_companies_to_contact(ids_contacts, id_contact_last):
for id_contact in ids_contacts:
if int(id_contact) in [id_contact_last, int(id_contact_last)]:
continue
res_del = bx24.call(
'crm.contact.delete',
{'id': id_contact}
)
# добавляет компании к контакту
def add_companies_to_contact(id_contact, companies):
print('companies = ', companies)
if not companies:
return True
response = bx24.call(
'crm.contact.company.items.set',
{
'id': id_contact,
'items': [{'COMPANY_ID': company_id} for company_id in companies]
}
)
if 'result' not in response:
return
return response['result']
# добавляет контакта к сделке
def add_deals_to_contact(id_contact, deals):
if not deals:
return True
batch = {}
for deal_id in deals:
batch[deal_id] = f'crm.deal.contact.add?id={deal_id}&fields[CONTACT_ID]={id_contact}'
response = bx24.batch(batch)
if response and 'result' in response and 'result' in response['result']:
return response['result']['result']
# обновляет данные контакта
def update_data_contacts(id_contact, data):
response = bx24.call(
'crm.contact.update',
{
'id': id_contact,
'fields': {
**data,
},
'params': {"REGISTER_SONET_EVENT": "Y"}
}
)
if 'result' not in response:
return
return response['result']
# запрашивает данные контактов по id
def get_data_contacts(ids):
cmd = {}
for id_contact in ids:
cmd[id_contact] = f'crm.contact.get?id={id_contact}'
response = bx24.batch(cmd)
if 'result' not in response or 'result' not in response['result']:
return
return response['result']['result']
# запрашивает и возвращает список всех полей контакта
def get_fields_contact():
response_fields = bx24.call('crm.contact.fields', {})
if 'result' not in response_fields:
return
return response_fields['result']
# привязывает к сделке компанию полученную из первого связанного контакта - в Битрикс24
def add_company_in_deal(id_deal):
response = bx24.batch(
{
'deal': f'crm.deal.get?id={id_deal}',
'contacts': f'crm.deal.contact.items.get?id={id_deal}'
}
)
if 'result' not in response or 'result' not in response['result']:
# print('Ответ от биртикс не содержит поле "result"')
return 400, 'Ответ от биртикс не содержит поле "result"'
if 'deal' not in response['result']['result']:
# print('Ответ от биртикс не содержит поле "deal"')
return 400, 'Ответ от биртикс не содержит поле "deal"'
if 'contacts' not in response['result']['result']:
# print('Ответ от биртикс не содержит поле "contacts"')
return 400, 'Ответ от биртикс не содержит поле "contacts"'
deal = response['result']['result']['deal']
contacts = response['result']['result']['contacts']
company_id = deal.get('COMPANY_ID', None)
if (company_id and company_id != '0') or not contacts:
# print('В сделке присутствует связанная компания или отсутствуют контакты')
return 200, 'В сделке присутствует связанная компания или отсутствуют контакты'
contact_id = contacts[0].get('CONTACT_ID')
# Получение данных контакта по его id
response_contact = bx24.call(
'crm.contact.get',
{'id': contact_id}
)
if 'result' not in response_contact:
# print('Ответ на запрос "crm.contact.get" не содержит поле "result"')
return 400, 'Ответ на запрос "crm.contact.get" не содержит поле "result"'
contact = response_contact['result']
company_id = contact.get('COMPANY_ID', None)
if not company_id:
return 200, 'К контакту не привязана компания'
response_deal_update = bx24.call(
'crm.deal.update',
{
'id': id_deal,
'fields': {
'COMPANY_ID': company_id
}
}
)
return 200, 'Ok'
# def copy_timeline_and_activity():
# pass
# "crm.timeline.comment.list",
# {
# filter: {
# "ENTITY_ID": 10,
# "ENTITY_TYPE": "deal",
# },
# select: ["ID", "COMMENT ", "FILES"]
# },
#
# "crm.timeline.comment.add",
# {
# fields:
# {
# "ENTITY_ID": 10,
# "ENTITY_TYPE": "deal",
# "COMMENT": "New comment was added"
# }
# },
# "crm.activity.list",
# {
# order: {"ID": "DESC"},
# filter:
# {
# "OWNER_TYPE_ID": 3,
# "OWNER_ID": 102
# },
# select: ["*", "COMMUNICATIONS"]
# },
# "crm.activity.list",
# {
# order: {"ID": "DESC"},
# filter:
# {
# "OWNER_TYPE_ID": 3,
# "OWNER_ID": 102
# },
# select: ["*", "COMMUNICATIONS"]
# },
# OWNER_TYPE_ID - это
# {"ID": 1, "NAME": "Лид"},
# {"ID": 2, "NAME": "Сделка"},
# {"ID": 3, "NAME": "Контакт"},
# {"ID": 4, "NAME": "Компания"},
# {"ID": 7, "NAME": "Предложение"},
# {"ID": 5, "NAME": "Счёт"},
# {"ID": 8, "NAME": "Реквизиты"}
# OWNER_ID - это соответсnвенно ID сущности.
# crm.activity.binding.add({activityId: number, entityTypeId: number, entityId: number)
|
Oleg-Sl/Quorum_merge_contacts
|
merge_contacts/api_v1/service/handler.py
|
handler.py
|
py
| 12,833 |
python
|
ru
|
code
| 0 |
github-code
|
6
|
21299192914
|
"""Module to evaluate full pipeline on the validation set.
python evaluate.py
"""
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import glob
import numpy as np
import image_preprocessing
import cnn
import bayesian_network
import json
import pandas as pd
# class mapping
classes = {"Positive": 0, "Neutral": 1, "Negative": 2, "None": 3}
# function to classify an image
def classify_image(image_folder_path, image_name, real_label, cnn_model, bayesian_model, labels_list):
with open('val_labels.json', mode='r', encoding='utf-8') as f:
image_labels_dict = json.load(f)
labels = image_labels_dict[image_name]
# print("RadhaKrishna")
# print(labels)
# preprocess the image
image_preprocessing.preprocess(image_folder_path, image_name)
# get mean cnn predictions for the faces from the image
cnn_label, cnn_dict, faces_detected = cnn.predict_image(cnn_model, image_folder_path + "Aligned/", image_name)
# get the bayesian and bayesian + cnn predictions for the image
bayesian_label, bayesian_cnn_label, emotion_dict, emotion_cnn_dict = bayesian_network.inference(bayesian_model, labels_list, labels, cnn_label)
# print("Faces detected: " + str(faces_detected))
# print("Real Label: " + str(real_label))
# print("CNN Label: " + str(cnn_label))
# print("Bayesian Label: " + str(bayesian_label))
# print("Bayesian + CNN Label: " + str(bayesian_cnn_label))
return classes[real_label], classes[str(cnn_label)], classes[str(bayesian_label)], classes[str(bayesian_cnn_label)], faces_detected
# load the cnn model
cnn_model = cnn.load_model()
# load the bayesian model
bayesian_model, labels_list = bayesian_network.load_model()
# function to evaluate the pipeline on a given directory
def evaluate(image_folder_path, real_label):
# print("RadhaKrishna")
# get the count of total number of files in the directory
_, _, files = next(os.walk(image_folder_path))
file_count = len(files)-1
# list to store the predictions
predictions = []
# set count = 1
i = 1
# for each image in the directory
for file in sorted(glob.glob(image_folder_path + "*.jpg")):
# extract the image name
image_name = (file.split('/'))[-1]
print("Image: " + image_name)
print(str(i) + "/" + str(file_count))
# create a dict to store the image name and predictions
prediction = {"Image": image_name}
prediction["Actual"], prediction["CNN"], prediction["Bayesian"], prediction["Bayesian + CNN"], prediction["Faces Detected"] = classify_image(image_folder_path, image_name, real_label, cnn_model, bayesian_model, labels_list)
# append the dict to the list of predictions
predictions.append(prediction)
# increase the count
i+=1
# return the predictions list
return predictions
# class list
class_list = ['Positive', 'Neutral', 'Negative']
predictions_list = []
# for each class in the class list
for emotion_class in class_list:
# evaluate all the images in that folder
predictions = evaluate('input/val/' + emotion_class + '/', emotion_class)
# add the predictions to the predictions list
predictions_list += predictions
# create a pandas dataframe from the predictions list
df = pd.DataFrame(predictions_list)
# store the dataframe to a file
df.to_pickle('predictions')
|
samanyougarg/Group-Emotion-Recognition
|
evaluate.py
|
evaluate.py
|
py
| 3,390 |
python
|
en
|
code
| 43 |
github-code
|
6
|
23202639490
|
import struct
import socket
import sys
import ipaddress
import threading
import os
class client:
"""
Responsible for keeping track of the clients information
"""
def __init__(self, ip_address, ll_address):
"""
Initialises all variables needed
Constructor: __init___(self, ip_address, ll_address)
"""
self.ip_address = ip_address
self.ip_no_mask = ip_address.split("/")[0]
self.ll_address = ll_address
self.gateway = None
self.arpTable = {} #dictionary
self.MTU = 1500
self.id_counter = 0
def get_idCounter(self):
"""
get_idCounter(None) -> (Int)
Returns the current packet counter
"""
return self.id_counter
def set_idCounter(self, value):
"""
set_idCounter(value)
sets the packet id counter
"""
self.id_counter = value
def get_ip(self):
"""
get_ip(None) -> (string)
Gets the ip address without CIDR suffix
"""
return self.ip_no_mask
def get_MTU(self):
"""
get_MTU(None) -> (Int)
Returns the Maximum Transmission Unit
"""
return self.MTU
def set_MTU(self, value):
"""
set_MTU(None)
Sets the Maximum Transmission Unit for the network
"""
self.MTU = value
def get_llAddr(self):
"""
get_llAddr(None) -> (Int)
"""
return self.ll_address
#adds to the arp table
def addToArpTable(self, ip_address, ll_address):
"""
addToArpTable(ip_address, linklayer_address)
Adds to ARP Table
"""
self.arpTable[ip_address] = ll_address
def viewArpTable(self):
"""
viewArpTable(None)
Prints all entries within ARP table
"""
for key, value in self.arpTable.items():
print("Key: ", key, " Value: ", value)
def setGateway(self, ipaddress):
"""
setGateway(ipaddress)
Sets the Gateway IP Address
"""
self.gateway = ipaddress
def getGateway(self):
"""
getGateway(None) -> (String)
Returns the Gateway IP address : None if not set
"""
return self.gateway
def hasGateway(self):
"""
hasGateway(None) -> (Boolean)
Checks to see if Gateway has been set
Returns True if set else False
"""
if self.gateway == None:
return False
else:
return True
def hasMapping(self, ipaddr):
"""
hasMapping(ipaddr) -> (Boolean)
Checks to see if an IP address has a mapping to a Link Layer Address
Returns True if set else False
"""
if ipaddr in self.arpTable:
if self.arpTable.get(ipaddr) != None:
return True
return False
def get_link_layer_addr(self, ipaddress):
"""
get_link_layer_addr(ipaddress) -> (Int)
Returns Link layer address mapped to an IP address
"""
return self.arpTable.get(ipaddress)
def hasArpEntry(self, ipaddress):
"""
hasArpEntry(ipaddress) -> (Boolean)
Checks to see if an IP address has a mapping to a Link Layer Address
Returns True if set else False
Prints to console if 'No Arp entry found' if ARP table doesnt have a mapping
"""
if self.arpTable.get(ipaddress) != None:
return True
else:
print("No ARP entry found")
return False
def get_subnetId(self, CIDR_ipaddress):
"""
get_subnetId(CIDR_ipaddress) -> (IPv4Interface)
Returns Subnet ID
"""
return ipaddress.ip_interface(CIDR_ipaddress)
def same_subnet(self, other_ip_address):
"""
same_subnet(other_ip_address) -> (Boolean)
Compares two IP addresses to see if they are within the same subnet
"""
return ipaddress.IPv4Address(other_ip_address) >= ipaddress.ip_network(self.ip_address,strict=False).network_address and \
ipaddress.IPv4Address(other_ip_address) <= ipaddress.ip_network(self.ip_address,strict=False).broadcast_address
class IPv4_packet:
"""
Responsible for dealing with the packet creation when sending packets
to other clients
"""
def __init__(self, length, fid, flags, offset, src_ip, dst_ip, payload):
"""
Initialises all header information
Constructor: ___init___(self, length, fid, flags, offset, src_ip, dst_ip, payload)
"""
self.version = 0b0100
self.header_length = 0b0101
self.type_of_service = 0b00000000
self.total_length = length
self.identifier = fid
self.flags = flags
self.fragment_offset = offset
self.time_to_live = 0b00100000
self.protocol = 0b00000000
self.header_checksum = int(format(0b00, '016b'))
self.src_address = src_ip
self.dest_address = dst_ip
self.payload = payload.encode()
self.version_hLength_tos = ((self.version << 4) + self.header_length) << 8 + self.type_of_service
self.flags_fragoffset = (self.flags << 13) + self.fragment_offset
self.ttl_prot = ((self.time_to_live << 8) + self.protocol)
self.ip_header = struct.pack('! 6H', self.version_hLength_tos, self.total_length, self.identifier,\
self.flags_fragoffset, self.ttl_prot, self.header_checksum)
#print(type(self.ip_header), " - ", type(self.src_address)," - ", type(self.dest_address)," - ", type(self.payload))
self.packet = self.ip_header+self.src_address + self.dest_address + self.payload
def getPacket(self):
"""
getPacket(None) -> (Packet)
Returns the packet object
"""
return self.packet
def __bytes__(self):
"""
__bytes__(None) -> (Bytes)
Returns a bytes representation of the packet object
"""
return self.packet
def return_args(string):
"""
return_args(string) -> <List>
separates the arguments and returns them as a list
"""
args = string.split(' ',maxsplit=2)
if len(args) == 3:
if args[0]=="msg":
return (args[0].strip(),args[1].strip(),args[2],None) #msg ip data
elif args[0] == "arp" and args[1] == "set":
ip, port = args[2].split(" ")
return(args[0].strip(),args[1].strip(), ip.strip(), port.strip())
else:
return (args[0].strip(),args[1].strip(), args[2].strip(),None)
elif len(args) == 2:
return (args[0].strip(" "),args[1].strip(" "),None,None)
return (None,None,None,None)
def main():
"""
Main Function
"""
arp = client(str(sys.argv[1]),str(sys.argv[2]))
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(2)
port = int(arp.get_llAddr())
s.bind(('LOCALHOST',port))
global terminate
terminate = False;
thr = threading.Thread(target=receive_data, args=(s,))
thr.start()
while True:
#sys.stdout.flush()
arg1 = arg2 = arg3 = arg4 = "-1"
sys.stdout.write("> ")
command = input()
str(command)
arg1,arg2,arg3,arg4 = return_args(command)
if str(command) == "gw set " + str(arg3):
arp.setGateway(str(arg3))
elif str(command) == "gw get":
gway = arp.getGateway()
if gway == None:
print("None")
else:
print(gway)
elif str(command) == "arp set "+str(arg3)+" "+str(arg4):
arp.addToArpTable(str(arg3), int(arg4))
elif str(command) == "arp get "+ str(arg3):
ll_add = arp.get_link_layer_addr(str(arg3))
if ll_add != None:
print(ll_add)
else:
print("None")
elif str(command) == 'msg '+ str(arg2) +' '+str(arg3):
#see if ip is in same gateway
dstn_ip = str(arg2)
dstn_port = -1
message = str(arg3)
if arp.same_subnet(dstn_ip):
if arp.hasMapping(dstn_ip):
dstn_port = arp.get_link_layer_addr(dstn_ip)
send_msg(s,arp,dstn_ip,dstn_port,message[1:-1])
else:
print("No ARP entry found")
else:
#send to gateway
#Check if gateway is set
if arp.hasGateway():
dstn_port = arp.get_link_layer_addr(arp.getGateway())
send_msg(s,arp,dstn_ip,dstn_port,message[1:-1])
else:
print("No gateway found")
elif str(command) == "mtu set "+ str(arg3):
arp.set_MTU(int(arg3))
elif str(command) == "mtu get":
print(arp.get_MTU())
elif str(command) == "exit":
terminate = True
break
sys.stdout.flush()
#send message
def send_msg(s,arp_details, dest_ip,dest_port, msg):
"""
send_msg(socket, arp_details, dest_ip, dest_port, msg)
Responsible for sending a packet to another client
"""
source_ip = socket.inet_aton(arp_details.get_ip())
destination_ip = socket.inet_aton(dest_ip)
payload_size = arp_details.get_MTU() - 20 #MTU - IP Header
if len(msg) <= payload_size:
t = IPv4_packet(len(msg) + 20, arp_details.get_idCounter(), 0, 0, source_ip, destination_ip, msg)
ipv4_packet = bytes(t)
s.sendto(ipv4_packet,('LOCALHOST',dest_port))
else:
payload, payload_size = payloads_creator(arp_details, msg)
offsets = calc_frag_offsets(payload_size, len(msg))
for i in range(len(payload)): #amount of offsets
if i != len(payload) - 1:
#length, fid, flags, offset, src_ip, dst_ip, payload
packet = IPv4_packet(len(payload[i]) + 20, arp_details.get_idCounter(), 0b001, offsets[i], source_ip, destination_ip, payload[i])
bytes_packet = bytes(packet)
s.sendto(bytes_packet,('LOCALHOST',dest_port))
#print("i != offsets length: ", i)
else:
#print("i == offsets length: ", i)
packet = IPv4_packet(len(payload[i]) + 20, arp_details.get_idCounter(), 0b000, offsets[i], source_ip, destination_ip, payload[i])
bytes_packet = bytes(packet)
s.sendto(bytes_packet,('LOCALHOST',dest_port))
arp_details.set_idCounter(arp_details.get_idCounter() + 1)
return
def payloads_creator(arp_details, message):
"""
payloads_creator(arp_details, message)
Handles the creation of the payloads in respect to the
Maximum Transmission Unit of the clients network
"""
payloads = []
count = 0
mtu = arp_details.get_MTU()
payload_size = int((mtu - 20)/8) * 8 #divisible by 8
#print("payload size: ",payload_size)
#print(len(message))
while count <= len(message):
payloads.append(message[count:count + payload_size])
count = count + payload_size
#print(len(payloads))
#print("payloads length: ",len(payloads))
#print(payloads)
return payloads, payload_size
def calc_frag_offsets(max_payload_size, msg_size):
"""
calc_frag_offests(max_payload_size, msg_size) -> <List>
Creates a list of packet offsets for packet fragmentation
"""
#returns a list of offsets
offsets = []
if (msg_size) % (max_payload_size) == 0: # -20 because its only the data
offset_amount = (msg_size / max_payload_size)
for i in range(int(offset_amount - 1)):
offset = (i*(max_payload_size)/8)
offsets.append(int(offset))
else:
offset_amount = round((msg_size / (max_payload_size)+1))
for i in range(offset_amount):
offset = (i*(max_payload_size)/8)
offsets.append(int(offset))
return offsets
def receive_data(s):
"""
receive_data(s)
Responsible for handling the receiving of data received
from other clients
"""
#print(threading.current_thread().name)
packets = {}
while True:
try:
data, addr = s.recvfrom(1500)
packets, evaluate_flag = add_packet_to_dict(data, packets)
if evaluate_flag == 1:
evaluate_packets(packets)
packets = {}
except OSError as e:
if terminate == True:
break
def add_packet_to_dict(data, packets_dict):
"""
add_packet_to_dict(data, packets_dict) -> (Dict, Int)
Creates a dictionary with all packets / packet fragments
received
"""
eval_flag = 0
pLength, pid, flags_offset, protocol, source_ip = struct.unpack('! 2x 3H x B 2x 4s 4x ', data[:20])
offset = flags_offset & 0x1FFF
flags = flags_offset >> 13
protocol = format(int(protocol), '#04x')
source_ip = socket.inet_ntoa(bytes(source_ip))
key = source_ip+" " +str(pid)
if key in packets_dict:
packets_dict[key].append(data)
if flags == 0:
eval_flag = 1
else:
packets_dict[key] = [data]
if flags == 0:
eval_flag = 1
return packets_dict, eval_flag
def evaluate_packets(p_dict):
"""
evaluate_packets(p_dict)
evaluates the packets within the dictionary
and outputs the correct message depending on
protocol
"""
for key, value in p_dict.items(): #loop through dict items
source_ip = -1
protocol = -1
msg_list =[]
msg = ""
for v in value: # loop through each value at key
pLength, pid, flags_offset, protocol, source_ip = struct.unpack('! 2x 3H x B 2x 4s 4x ', v[:20])
offset = flags_offset & 0x1FFF
flags = flags_offset >> 13
source_ip = socket.inet_ntoa(bytes(source_ip))
msg = v[20:].decode()
protocol = format(int(protocol), '#04x')
msg_list.append(msg)
msg = msg.join(msg_list)
if protocol == "0x00":
print('\b\bMessage received from {}: "{}"'.format(source_ip, msg))
else:
print("\b\bMessage received from {} with protocol {}".format(source_ip, protocol))
print("> ", end='', flush=True)
return
if __name__ == '__main__':
main()
|
TSampey/COMS3200-Assign3
|
assign3.py
|
assign3.py
|
py
| 12,355 |
python
|
en
|
code
| 0 |
github-code
|
6
|
73529467707
|
import os.path
from sklearn import metrics
from torch import nn, optim
# noinspection PyUnresolvedReferences
from tests.pytest_helpers.data import dataloaders, image
# noinspection PyUnresolvedReferences
from tests.pytest_helpers.nn import sample_model
def test_fit(sample_model, dataloaders):
try:
model = sample_model(
nn.CrossEntropyLoss,
optim.Adam,
[(metrics.accuracy_score, {})]
)
model.fit(dataloaders)
except:
assert False
def test_prediction(sample_model, image):
_image = image('../sampleData/images/cat1.jpeg')
model = sample_model(nn.CrossEntropyLoss, optim.Adam, [(metrics.recall_score, {'average': 'macro'})])
predictions = model.predict(_image)
assert list(predictions.size()) == [1, 2]
def test_save(sample_model, dataloaders):
model = sample_model(
nn.CrossEntropyLoss,
optim.Adam,
[(metrics.accuracy_score, {})]
)
model.fit(dataloaders)
assert os.path.exists('./bestModel.pkl.tar')
|
default-303/easyTorch
|
tests/testUtils/test_trainer.py
|
test_trainer.py
|
py
| 1,039 |
python
|
en
|
code
| 2 |
github-code
|
6
|
27513864943
|
import copy
from timsconvert import *
def run_tims_converter(args):
# Load in input data.
logging.info(get_timestamp() + ':' + 'Loading input data...')
if not args['input'].endswith('.d'):
input_files = dot_d_detection(args['input'])
elif args['input'].endswith('.d'):
input_files = [args['input']]
# Convert each sample
for infile in input_files:
# Reset args.
run_args = copy.deepcopy(args)
# Set input file.
run_args['infile'] = infile
# Set output directory to default if not specified.
if run_args['outdir'] == '':
run_args['outdir'] = os.path.split(infile)[0]
# Make output filename the default filename if not specified.
if run_args['outfile'] == '':
run_args['outfile'] = os.path.splitext(os.path.split(infile)[-1])[0] + '.mzML'
logging.info(get_timestamp() + ':' + 'Reading file: ' + infile)
schema = schema_detection(infile)
# Log arguments.
for key, value in run_args.items():
logging.info(get_timestamp() + ':' + str(key) + ': ' + str(value))
if args['experiment'] == 'lc-tims-ms':
logging.info(get_timestamp() + ':' + 'Processing LC-TIMS-MS data...')
data = bruker_to_df(infile)
write_lcms_mzml(data, infile, run_args['outdir'], run_args['outfile'], run_args['centroid'],
run_args['ms2_only'], run_args['ms1_groupby'], run_args['encoding'],
run_args['ms2_keep_n_most_abundant_peaks'])
elif args['experiment'] == 'maldi-dd':
# Initialize Bruker DLL.
# Only initialize if converting MALDI data. LCMS data currently uses AlphaTims.
logging.info(get_timestamp() + ':' + 'Initialize Bruker .dll file...')
bruker_dll = init_bruker_dll(BRUKER_DLL_FILE_NAME)
logging.info(get_timestamp() + ':' + '.tsf file detected...')
logging.info(get_timestamp() + ':' + 'Processing MALDI dried droplet data...')
if run_args['maldi_output_file'] == 'individual':
if run_args['maldi_plate_map'] == '':
logging.info(get_timestamp() + ':' + 'Plate map is required for MALDI dried droplet data in '
'multiple file mode...')
logging.info(get_timestamp() + ':' + 'Exiting...')
sys.exit(1)
elif run_args['maldi_output_file'] == '':
logging.info(get_timestamp() + ':' + 'MALDI output file mode must be specified ("individual" or '
'"combined")...')
logging.info(get_timestamp() + ':' + 'Exiting...')
sys.exit(1)
data = tsf_data(infile, bruker_dll)
write_maldi_dd_mzml(data, run_args['infile'], run_args['outdir'], run_args['outfile'],
run_args['ms2_only'], run_args['ms1_groupby'], run_args['centroid'],
run_args['encoding'], run_args['maldi_output_file'], run_args['maldi_plate_map'])
elif args['experiment'] == 'maldi-tims-dd':
# Initialize Bruker DLL.
# Only initialize if converting MALDI data. LCMS data currently uses AlphaTims.
logging.info(get_timestamp() + ':' + 'Initialize Bruker .dll file...')
bruker_dll = init_bruker_dll(BRUKER_DLL_FILE_NAME)
logging.info(get_timestamp() + ':' + '.tdf file detected...')
logging.info(get_timestamp() + ':' + 'Processing MALDI-TIMS dried droplet data...')
if run_args['maldi_output_file'] == 'individual':
if run_args['maldi_plate_map'] == '':
logging.info(
get_timestamp() + ':' + 'Plate map is required for MALDI dried droplet data in '
'multiple file mode...')
logging.info(get_timestamp() + ':' + 'Exiting...')
sys.exit(1)
elif run_args['maldi_output_file'] == '':
logging.info(
get_timestamp() + ':' + 'MALDI output file mode must be specified ("individual" or '
'"combined")...')
logging.info(get_timestamp() + ':' + 'Exiting...')
sys.exit(1)
data = tdf_data(infile, bruker_dll)
write_maldi_dd_mzml(data, run_args['infile'], run_args['outdir'], run_args['outfile'],
run_args['ms2_only'], run_args['ms1_groupby'], run_args['centroid'],
run_args['encoding'], run_args['maldi_output_file'], run_args['maldi_plate_map'])
elif args['experiment'] == 'maldi-ims':
# Initialize Bruker DLL.
# Only initialize if converting MALDI data. LCMS data currently uses AlphaTims.
logging.info(get_timestamp() + ':' + 'Initialize Bruker .dll file...')
bruker_dll = init_bruker_dll(BRUKER_DLL_FILE_NAME)
logging.info(get_timestamp() + ':' + '.tsf file detected...')
logging.info(get_timestamp() + ':' + 'Processing MALDI imaging mass spectrometry data...')
data = tsf_data(infile, bruker_dll)
write_maldi_ims_imzml(data, run_args['outdir'], run_args['outfile'], 'frame', run_args['encoding'],
run_args['imzml_mode'], run_args['centroid'])
elif args['experiment'] == 'maldi-tims-ims':
# Initialize Bruker DLL.
# Only initialize if converting MALDI data. LCMS data currently uses AlphaTims.
logging.info(get_timestamp() + ':' + 'Initialize Bruker .dll file...')
bruker_dll = init_bruker_dll(BRUKER_DLL_FILE_NAME)
logging.info(get_timestamp() + ':' + '.tdf file detected...')
logging.info(get_timestamp() + ':' + 'Processing MALDI-TIMS imaging mass spectrometry data...')
data = tdf_data(infile, bruker_dll)
write_maldi_ims_imzml(data, run_args['outdir'], run_args['outfile'], 'frame', run_args['encoding'],
run_args['imzml_mode'], run_args['centroid'])
run_args.clear()
if __name__ == '__main__':
# Parse arguments.
arguments = get_args()
# Hardcode centroid to True. Current code does not support profile.
arguments['centroid'] = True
# Check arguments.
args_check(arguments)
arguments['version'] = '0.1.0'
# Initialize logger.
logname = 'log_' + get_timestamp() + '.log'
if arguments['outdir'] == '':
if os.path.isdir(arguments['input']):
logfile = os.path.join(arguments['input'], logname)
else:
logfile = os.path.split(arguments['input'])[0]
logfile = os.path.join(logfile, logname)
else:
logfile = os.path.join(arguments['outdir'], logname)
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(filename=logfile, level=logging.INFO)
if arguments['verbose']:
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logger = logging.getLogger(__name__)
# Run.
run_tims_converter(arguments)
|
orsburn/timsconvert
|
bin/run.py
|
run.py
|
py
| 7,351 |
python
|
en
|
code
| null |
github-code
|
6
|
74750230586
|
import os
import pathlib
import shutil
from datetime import datetime
from pathlib import Path
from my_logger_object import create_logger_object
def copy_component(component_kb_list, component_name, source_folder, target_folder):
# source_folder = r"C:\CodeRepos\GetOfficeKBs\Folder_Office2016_KBs\x64_msp"
# target_folder = r"C:\CodeRepos\GetOfficeKBs\Folder_Latest_KB_Numbers\x64_msp"
# component_name = ""
if not os.path.exists(target_folder):
os.makedirs(target_folder)
for root, dirs, files in os.walk(source_folder):
for file_name in files:
component_name_in_file = file_name.split("-")[0].strip()
if component_name == component_name_in_file:
soure_file_path = root + os.sep + file_name
target_file_path = target_folder + os.sep + file_name
kb_number_in_file = file_name.split("_")[1].strip()
if (component_name + "," + kb_number_in_file) not in component_kb_list:
component_kb_list.append(component_name + "," + kb_number_in_file)
if os.path.isfile(soure_file_path):
try:
shutil.copy(soure_file_path, target_file_path)
except:
logger.debug("exception")
current_script_folder = str(pathlib.Path(__file__).parent.absolute()) + os.sep
FILENAME = current_script_folder + "log_" + os.path.basename(__file__) + ".log"
logger = create_logger_object(FILENAME)
logger.info("The script starts running.")
logger.info("The script folder is " + current_script_folder)
component_list = []
try:
f = open(current_script_folder + "output_msp_file_name_for_specified_kb.txt", "r")
for line in f:
component_str = line.split(",")[-1].strip()
if component_str in component_list:
logger.info("Duplicate component number: " + component_str)
else:
component_list.append(component_str)
except Exception as ex:
logger.info("Encounter exception when loading expected kb list." + str(ex))
finally:
f.close()
logger.info(len(component_list))
component_list.sort()
component_list_file = current_script_folder + "output_non_dup_component.txt"
with open(component_list_file, "w") as f:
for item in component_list:
f.write("%s\n" % item)
time_now = formatted_date_time = datetime.now().strftime("%Y%m%d%H%M%S")
source_folder_x32 = r"C:\CodeRepos\GetOfficeKBs\Folder_Office2016_KBs\x86_msp"
target_folder_x32 = (
"C:\CodeRepos\GetOfficeKBs\Folder_Latest_KB_Numbers\\" + time_now + "_x86_msp"
)
source_folder_x64 = r"C:\CodeRepos\GetOfficeKBs\Folder_Office2016_KBs\x64_msp"
target_folder_x64 = (
"C:\CodeRepos\GetOfficeKBs\Folder_Latest_KB_Numbers\\" + time_now + "_x64_msp"
)
component_kb_list = []
for item in component_list:
logger.debug(item)
copy_component(component_kb_list, item, source_folder_x32, target_folder_x32)
copy_component(component_kb_list, item, source_folder_x64, target_folder_x64)
component_kb_list.sort()
component_kb_list_file = current_script_folder + "output_latest_kb_for_component.txt"
with open(component_kb_list_file, "w") as f:
for item in component_kb_list:
f.write("%s\n" % item)
logger.info("Please check output file: " + component_kb_list_file)
logger.info(f"Please check output folder: {target_folder_x32}")
logger.info(f"Please check output folder: {target_folder_x64}")
logger.info("The script ends.")
|
FullStackEngN/GetOfficeKBs
|
get_msp_file_for_specified_msp_list.py
|
get_msp_file_for_specified_msp_list.py
|
py
| 3,495 |
python
|
en
|
code
| 1 |
github-code
|
6
|
23196116357
|
import pyspark
import networkx as nx
import pandas as pd
from pyspark.sql.types import (
LongType,
StringType,
FloatType,
IntegerType,
DoubleType,
StructType,
StructField,
)
import pyspark.sql.functions as f
from pyspark.sql.functions import pandas_udf, PandasUDFType
from networkx.algorithms.centrality import (
eigenvector_centrality,
harmonic_centrality,
)
def eigencentrality(
sparkdf,
src="src",
dst="dst",
cluster_id_colname="cluster_id",
):
"""
Args:
sparkdf: imput edgelist Spark DataFrame
src: src column name
dst: dst column name
distance_colname: distance column name
cluster_id_colname: Graphframes-created connected components created cluster_id
Returns:
node_id:
eigen_centrality: eigenvector centrality of cluster cluster_id
cluster_id: cluster_id corresponding to the node_id
Eigenvector Centrality is an algorithm that measures the transitive influence or connectivity of nodes.
Eigenvector Centrality was proposed by Phillip Bonacich, in his 1986 paper Power and Centrality:
A Family of Measures.
It was the first of the centrality measures that considered the transitive importance of a node in a graph,
rather than only considering its direct importance.
Relationships to high-scoring nodes contribute more to the score of a node than connections to low-scoring nodes.
A high score means that a node is connected to other nodes that have high scores.
example input spark dataframe
|src|dst|weight|cluster_id|distance|
|---|---|------|----------|--------|
| f| d| 0.67| 0| 0.329|
| f| g| 0.34| 0| 0.659|
| b| c| 0.56|8589934592| 0.439|
| g| h| 0.99| 0| 0.010|
| a| b| 0.4|8589934592| 0.6|
| h| i| 0.5| 0| 0.5|
| h| j| 0.8| 0| 0.199|
| d| e| 0.84| 0| 0.160|
| e| f| 0.65| 0| 0.35|
example output spark dataframe
|node_id| eigen_centrality|cluster_id|
|-------|-------------------|----------|
| b | 0.707106690085642|8589934592|
| c | 0.5000000644180599|8589934592|
| a | 0.5000000644180599|8589934592|
| f | 0.5746147732828122| 0|
| d | 0.4584903903420785| 0|
| g |0.37778352393858183| 0|
| h |0.27663243805676946| 0|
| i |0.12277029263709134| 0|
| j |0.12277029263709134| 0|
| e | 0.4584903903420785| 0|
"""
ecschema = StructType(
[
StructField("node_id", StringType()),
StructField("eigen_centrality", DoubleType()),
StructField(cluster_id_colname, LongType()),
]
)
psrc = src
pdst = dst
@pandas_udf(ecschema, PandasUDFType.GROUPED_MAP)
def eigenc(pdf: pd.DataFrame) -> pd.DataFrame:
nxGraph = nx.Graph()
nxGraph = nx.from_pandas_edgelist(pdf, psrc, pdst)
ec = eigenvector_centrality(nxGraph, tol=1e-03)
out_df = (
pd.DataFrame.from_dict(ec, orient="index", columns=["eigen_centrality"])
.reset_index()
.rename(
columns={"index": "node_id", "eigen_centrality": "eigen_centrality"}
)
)
cluster_id = pdf[cluster_id_colname][0]
out_df[cluster_id_colname] = cluster_id
return out_df
out = sparkdf.groupby(cluster_id_colname).apply(eigenc)
return out
def harmoniccentrality(sparkdf, src="src", dst="dst", cluster_id_colname="cluster_id"):
"""
Args:
sparkdf: imput edgelist Spark DataFrame
src: src column name
dst: dst column name
distance_colname: distance column name
cluster_id_colname: Graphframes-created connected components created cluster_id
Returns:
node_id:
harmonic_centrality: Harmonic centrality of cluster cluster_id
cluster_id: cluster_id corresponding to the node_id
Harmonic centrality (also known as valued centrality) is a variant of closeness centrality, that was invented
to solve the problem the original formula had when dealing with unconnected graphs.
Harmonic centrality was proposed by Marchiori and Latora while trying to come up with a sensible notion of "average shortest path".
They suggested a different way of calculating the average distance to that used in the Closeness Centrality algorithm.
Rather than summing the distances of a node to all other nodes, the harmonic centrality algorithm sums the inverse of those distances.
This enables it deal with infinite values.
input spark dataframe:
|src|dst|weight|cluster_id|distance|
|---|---|------|----------|--------|
| f| d| 0.67| 0| 0.329|
| f| g| 0.34| 0| 0.659|
| b| c| 0.56|8589934592| 0.439|
| g| h| 0.99| 0| 0.010|
| a| b| 0.4|8589934592| 0.6|
| h| i| 0.5| 0| 0.5|
| h| j| 0.8| 0| 0.199|
| d| e| 0.84| 0| 0.160|
| e| f| 0.65| 0| 0.35|
output spark dataframe:
|node_id|harmonic_centrality|cluster_id|
|-------|-------------------|----------|
| b | 2.0|8589934592|
| c | 1.5|8589934592|
| a | 1.5|8589934592|
| f | 4.166666666666667| 0|
| d | 3.3333333333333335| 0|
| g | 4.0| 0|
| h | 4.166666666666667| 0|
| i | 2.8333333333333335| 0|
| j | 2.8333333333333335| 0|
| e | 3.3333333333333335| 0|
"""
hcschema = StructType(
[
StructField("node_id", StringType()),
StructField("harmonic_centrality", DoubleType()),
StructField(cluster_id_colname, LongType()),
]
)
psrc = src
pdst = dst
@pandas_udf(hcschema, PandasUDFType.GROUPED_MAP)
def harmc(pdf: pd.DataFrame) -> pd.DataFrame:
nxGraph = nx.Graph()
nxGraph = nx.from_pandas_edgelist(pdf, psrc, pdst)
hc = harmonic_centrality(nxGraph)
out_df = (
pd.DataFrame.from_dict(hc, orient="index", columns=["harmonic_centrality"])
.reset_index()
.rename(
columns={
"index": "node_id",
"harmonic_centrality": "harmonic_centrality",
}
)
)
cluster_id = pdf[cluster_id_colname][0]
out_df[cluster_id_colname] = cluster_id
return out_df
out = sparkdf.groupby(cluster_id_colname).apply(harmc)
return out
|
moj-analytical-services/splink_graph
|
splink_graph/node_metrics.py
|
node_metrics.py
|
py
| 6,877 |
python
|
en
|
code
| 6 |
github-code
|
6
|
13162464659
|
grammar = [
("S", ["P"]), # S -> P
("P", ["(", "P", ")"]), # P -> ( P )
("P", []), # P ->
]
tokens = ["(", "(", ")", ")"]
grammar2 = [
("P", ["S"]),
("S", ["S", "+", "M"]),
("S", ["M"]),
("M", ["M", "*", "T"]),
("M", ["T"]),
("T", ["1"]),
("T", ["2"]),
("T", ["3"]),
("T", ["4"]),
]
tokens2 = ["2", "+", "2", "*", "4"]
def addtochart(theset, index, elt):
if elt in theset[index]:
return False
else:
theset[index] = theset[index] + [elt]
return True
def closure(grammar, i, x, ab, cd, j):
next_states = [(cd[0], [], rule[1], i)
for rule in grammar if cd != [] and rule[0] == cd[0]]
return next_states
# 当没有return 或return后面没有返回值时 函数将自动返回None
def shift(tokens, i, x, ab, cd, j):
if cd != [] and tokens[i] == cd[0]:
return x, ab + [cd[0]], cd[1:], j
def reductions(chart, i, x, ab, cd, j):
return [(state[0], state[1] + [x], state[2][1:], state[3])
for state in chart[j]
if cd == [] and state[2] != [] and state[2][0] == x]
def parse(tokens, grammar):
tokens = tokens + ["end_of_input_marker"]
# because sometimes we need to look ahead, for example, for shifting
# to see if the input token matches what's there, and we don't want to
# walk off the end of a list.
chart = {}
start_rule = grammar[0]
for i in range(len(tokens) + 1):
chart[i] = []
# state encode : x -> ab . cd from j, ("x", ab, cd, j)
start_state = (start_rule[0], [], start_rule[1], 0)
chart[0] = [start_state]
# consider tokens in the input, and keep using closure, shifting, reduction
# until there aren't any more changes.
for i in range(len(tokens)):
while True:
changes = False
for state in chart[i]:
# State === x -> a b . c d , j
x = state[0]
ab = state[1]
cd = state[2]
j = state[3]
# Current State: x -> a b . c d, j
# Option 1 : For each grammar rule c -> p q r
# (where the c's match
# make a next state c -> . p q r , i
# We're about to start parsing a "c", but "c" may be something
# like "exp" with its own production rules. We'll bring those
# production rules in.
next_states = closure(grammar, i, x, ab, cd, j)
for next_state in next_states:
changes = addtochart(chart, i, next_state) or changes
# Current State : x -> a b . c d , j
# Option 2: If tokens[i] == c,
# make a next state x -> a b c . d , j
# in chart[i+1]
# We're looking for to parse token c next and the current
# token is exactly c ! Aren't we lucky! So we can parse over
# it and move to j + 1.
next_state = shift(tokens, i, x, ab, cd, j)
if next_state is not None:
any_changes = addtochart(chart, i+1, next_state) or any_changes
# Current State : x -> a b . c d , j
# Option 3 : If cd is [], the state is just x -> a b . , j
# for each p -> q . x r, l in chart[j]
# make a next state p -> q x . r, l
# in chart[i]
# We just finished parsing an "x" with this token,
# but that may have been a sub-step (like matching "exp -> 2"
# in "2+3"). We should update the higher-level rules as well.
next_states = reductions(chart, i, x, ab, cd, j)
for next_state in next_states:
changes = addtochart(chart, i, next_state) or changes
# repeating those three procedures until no more changes
if not changes:
break
for i in range(len(tokens)): # print out the chart
print("== chart " + str(i))
for state in chart[i]:
x = state[0]
ab = state[1]
cd = state[2]
j = state[3]
print(" " + x + " ->", end="")
for sym in ab:
print(" " + sym, end="")
print(" .", end="")
for sym in cd:
print(" " + sym, end="")
print(" from " + str(j))
accepting_state = (start_rule[0], start_rule[1], [], 0)
return accepting_state in chart[len(tokens) - 1]
result = parse(tokens, grammar)
print(result)
print(parse(tokens2, grammar2))
|
panmengguan/Udacity_CS262
|
Unit4/Parser_Earley.py
|
Parser_Earley.py
|
py
| 4,707 |
python
|
en
|
code
| 0 |
github-code
|
6
|
1065053262
|
'''Calculus Chapter of Hacking Math Class'''
from turtle import *
from algebra import setup, graph
from geometry2 import line,perpendicularLine, intersection
speed(0)
def f(x):
return -0.2*x**5 + 1.4*x**4+x**3-5*x**2-1.5*x + 3
def derivative(a):
'''Returns the derivative of a function at point x = a'''
dx = 0.00001 #the tiny "run"
dy = f(a + dx) - f(a)
return dy/dx
#print("Derivative of f(x) at 3 is ",derivative(3))
def newton(guess):
'''Approximates the roots of a
function using the derivative'''
for i in range(20):
new_guess = guess - f(guess)/derivative(guess)
guess = new_guess
print(new_guess)
#newton(1.5)
def newtonTurtle(guess):
setup()
graph(f)
pu()
goto(guess,0)
pd()
for i in range(5):
goto(guess,f(guess))
d=derivative(guess)
line2 = line(d,(guess,f(guess)))
goto(intersection(line2[0],line2[1],0,0))
new_guess = guess - f(guess)/derivative(guess)
guess = new_guess
#newtonTurtle(1.5)
def nint(f,startingx, endingx, number_of_rectangles):
'''returns the area under a function'''
sum_of_areas = 0 #running sum of the areas
#width of every rectangle:
width = (endingx - startingx) / number_of_rectangles
for i in range(number_of_rectangles):
height = f(startingx + i*width)
area_rect = width * height
sum_of_areas += area_rect
return sum_of_areas
def trapezoid(startingx, endingx,numberofTrapezoids):
'''Returns the area under a function
using Trapezoidal Method'''
width = (float(endingx) - float(startingx))/ numberofTrapezoids
area = 0
for i in range(numberofTrapezoids):
#backslash simply continues the code on the next line:
area1 = 0.5*width*(f(startingx + i*width)+\
f((startingx + i*width)+width))
area += area1
print(area)
def trap(f,startingx,width):
'''draws one trapezoid'''
pu() #pen up
speed(0) #fastest speed
setpos(startingx,0) #go to the starting x-coordinate
setheading(90) #face straight up
color("black","red")
pd() #put your pen down
begin_fill() #start filling in the trapezoid
height = f(xcor()) #height of the trapezoid
fd(height) #go to the top of the trapezoid
setpos(xcor()+width,f(xcor()+width)) # down the "slant"
sety(0) #straight down to the x-axis
setheading(0) #face right
end_fill() #stop filling the trapezoid
def trapezoid2(f,startingx, endingx,numberofTrapezoids):
'''Calculates area under function f between
startingx and endingx using trapezoids and graphs it'''
speed(0)
setup()
graph(f)
pu()
width = (float(endingx) - float(startingx))/ numberofTrapezoids
setpos(startingx,0)
pd()
area = 0
for i in range(numberofTrapezoids):
trap(f,xcor(),width) #draw a trapezoid
area1 = 0.5*width*(f(startingx + i*width)+f((startingx + \
i*width)+width))
area += area1 #update the running sum of the area
print(area)
trapezoid2(f,-1,2,10)
#Runge-Kutta Method for solving DEs
def deriv(x,y):
return x**2 + y**2
def rk4(x0,y0,h): #order 4
while x0 <= 1.0:
print(x0,y0)
# I changed the l's to m's
m1 = h*deriv(x0,y0)
m2 = h*deriv(x0 + h/2, y0 + m1/2)
m3 = h*deriv(x0 + h/2, y0 + m2/2)
m4 = h*deriv(x0 + h, y0 + m3)
#These are the values that are fed back into the function:
y0 = y0 + (1/6)*(m1 + 2*m2 + 2*m3 + m4)
x0 = x0 + h
exitonclick()
|
hackingmath/BayPIGgies-Talk
|
calculus.py
|
calculus.py
|
py
| 3,663 |
python
|
en
|
code
| 0 |
github-code
|
6
|
663159079
|
#! /usr/bin/env python
import pandas as pd
if __name__ == '__main__':
dataset = 'D3'
path = '/home/milan/workspace/strands_ws/src/battery_scheduler/data/csv_files/'
eb_f = path+'taskbased_overall_'+dataset+'_models.csv'
tb_f = path+'timebased_overall_'+dataset+'_models.csv'
c_f = path+'combined_overall_'+dataset+'_models.csv'
eb = pd.read_csv(eb_f)
tb = pd.read_csv(tb_f)
rew = []
u40 = []
time = []
for i in range(6):
rew.append(tb['rewards'][i])
time.append(tb['active_time'][i])
u40.append(tb['under40'][i])
rew.append(eb['rewards'][i])
time.append(eb['active_time'][i])
u40.append(eb['under40'][i])
for i in range(6,9):
rew.append(eb['rewards'][i])
time.append(eb['active_time'][i])
u40.append(eb['under40'][i])
df = pd.DataFrame(data=zip(rew, time, u40), columns =['rewards', 'active_time', 'under40'])
df.to_csv(c_f, header=True, index=False)
|
milanmt/Battery-Scheduler
|
src/analysis/combined_statistics.py
|
combined_statistics.py
|
py
| 991 |
python
|
en
|
code
| 0 |
github-code
|
6
|
5479668707
|
import argparse
import os, numpy as np
import os.path as osp
from multiprocessing import Process
import h5py
import json
os.environ["D4RL_SUPPRESS_IMPORT_ERROR"] = "1"
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
from maniskill2_learn.env import make_gym_env, ReplayMemory, import_env
from maniskill2_learn.utils.data import DictArray, GDict, f64_to_f32
from maniskill2_learn.utils.file import merge_h5_trajectory
from maniskill2_learn.utils.meta import get_total_memory, flush_print
from maniskill2_learn.utils.math import split_num
# from maniskill2_learn.utils.data import compress_f64
def auto_fix_wrong_name(traj):
if isinstance(traj, GDict):
traj = traj.memory
for key in traj:
if key in ["action", "reward", "done", "env_level", "next_env_level", "next_env_state", "env_state"]:
traj[key + "s"] = traj[key]
del traj[key]
return traj
tmp_folder_in_docker = "/tmp"
def render(env):
viewer = env.render()
def convert_state_representation(keys, args, worker_id, main_process_id):
input_dict = {
"env_name": args.env_name,
"unwrapped": False,
"obs_mode": args.obs_mode,
"obs_frame": args.obs_frame,
"reward_mode": args.reward_mode,
"control_mode": args.control_mode,
"n_points": args.n_points,
"n_goal_points": args.n_goal_points,
"camera_cfgs": {},
"render_mode": 'human',
}
if args.enable_seg:
input_dict["camera_cfgs"]["add_segmentation"] = True
with open(args.json_name, "r") as f:
json_file = json.load(f)
env_kwargs = json_file["env_info"]["env_kwargs"]
for k in input_dict:
env_kwargs.pop(k, None)
# update the environment creation args with the extra info from the json file, e.g., cabinet id & target link in OpenCabinetDrawer / Door
input_dict.update(env_kwargs)
env = make_gym_env(**input_dict)
assert hasattr(env, "get_obs"), f"env {env} does not contain get_obs"
reset_kwargs = {}
for d in json_file["episodes"]:
episode_id = d["episode_id"]
r_kwargs = d["reset_kwargs"]
reset_kwargs[episode_id] = r_kwargs
cnt = 0
output_file = osp.join(tmp_folder_in_docker, f"{worker_id}.h5")
output_h5 = h5py.File(output_file, "w")
input_h5 = h5py.File(args.traj_name, "r")
for j, key in enumerate(keys):
cur_episode_num = eval(key.split('_')[-1])
trajectory = GDict.from_hdf5(input_h5[key])
trajectory = auto_fix_wrong_name(trajectory)
print("Reset kwargs for the current trajectory:", reset_kwargs[cur_episode_num])
env.reset(**reset_kwargs[cur_episode_num])
all_env_states_present = ('env_states' in trajectory.keys())
if all_env_states_present:
length = trajectory['env_states'].shape[0] - 1
else:
assert 'env_init_state' in trajectory.keys()
length = trajectory['actions'].shape[0]
assert length == trajectory['actions'].shape[0] == trajectory['success'].shape[0]
replay = ReplayMemory(length)
next_obs = None
for i in range(length):
if all_env_states_present:
if next_obs is None:
env_state = trajectory["env_states"][i]
env.set_state(env_state)
obs = env.get_obs()
else:
obs = next_obs
_, reward, _, _, _ = env.step(trajectory["actions"][i])
# ^ We cannot directly get rewards when setting env_state.
# Instead, reward is only accurate after env.step(); otherwise e.g. grasp criterion will be inaccurate due to zero impulse
next_env_state = trajectory["env_states"][i + 1]
env.set_state(next_env_state)
next_obs = env.get_obs()
else:
if i == 0:
env.set_state(trajectory["env_init_state"])
if next_obs is None:
obs = env.get_obs()
else:
obs = next_obs
next_obs, reward, _, _, _ = env.step(trajectory["actions"][i])
item_i = {
"obs": obs,
"actions": trajectory["actions"][i],
"dones": trajectory["success"][i],
"episode_dones": False if i < length - 1 else True,
"rewards": reward,
}
if args.with_next:
item_i["next_obs"] = next_obs
item_i = GDict(item_i).f64_to_f32()
replay.push(item_i)
if args.render:
if args.debug:
print("reward", reward)
render(env)
if worker_id == 0:
flush_print(f"Convert Trajectory: completed {cnt + 1} / {len(keys)}; this trajectory has length {length}")
group = output_h5.create_group(f"traj_{cnt}")
cnt += 1
replay.to_hdf5(group, with_traj_index=False)
output_h5.close()
input_h5.close()
flush_print(f"Finish using {output_file}")
def parse_args():
parser = argparse.ArgumentParser(description="Generate visual observations of trajectories given environment states.")
# Configurations
parser.add_argument("--num-procs", default=1, type=int, help="Number of parallel processes to run")
parser.add_argument("--env-name", required=True, help="Environment name, e.g. PickCube-v0")
parser.add_argument("--traj-name", required=True, help="Input trajectory path, e.g. pickcube_pd_joint_delta_pos.h5")
parser.add_argument("--json-name", required=True, type=str,
help="""
Input json path, e.g. pickcube_pd_joint_delta_pos.json |
**Json file that contains reset_kwargs is required for properly rendering demonstrations.
This is because for environments using more than one assets, asset is different upon each environment reset,
and asset info is only contained in the json file, not in the trajectory file.
For environments that use a single asset with randomized dimensions, the seed info controls the specific dimension
used in a certain trajectory, and this info is only contained in the json file.**
""")
parser.add_argument("--output-name", required=True, help="Output trajectory path, e.g. pickcube_pd_joint_delta_pos_pcd.h5")
parser.add_argument("--max-num-traj", default=-1, type=int, help="Maximum number of trajectories to convert from input file")
parser.add_argument("--obs-mode", default="pointcloud", type=str, help="Observation mode")
parser.add_argument("--control-mode", default="pd_joint_delta_pos", type=str, help="Environment control Mode")
parser.add_argument("--reward-mode", default="dense", type=str, choices=["dense", "sparse"], help="Reward Mode (dense / sparse)")
parser.add_argument("--with-next", default=False, action="store_true", help="Add next_obs into the output file (for e.g. SAC+GAIL training)")
parser.add_argument("--render", default=False, action="store_true", help="Render the environment while generating demonstrations")
parser.add_argument("--debug", default=False, action="store_true", help="Debug print")
parser.add_argument("--force", default=False, action="store_true", help="Force-regenerate the output trajectory file")
# Extra observation args
parser.add_argument("--enable-seg", action='store_true', help="Enable ground truth segmentation")
# Specific point cloud generation args
parser.add_argument("--n-points", default=1200, type=int,
help="If obs_mode == 'pointcloud', the number of points to downsample from the original point cloud")
parser.add_argument("--n-goal-points", default=-1, type=int,
help="If obs_mode == 'pointcloud' and 'goal_pos' is returned from environment observations (in obs['extra']), \
then randomly sample this number of points near the goal to the returned point cloud. These points serve as helpful visual cue. -1 = disable")
parser.add_argument("--obs-frame", default="base", type=str, choices=["base", "world", "ee", "obj"],
help="If obs_mode == 'pointcloud', the observation frame (base/world/ee/obj) to transform the point cloud.")
args = parser.parse_args()
args.traj_name = osp.abspath(args.traj_name)
args.output_name = osp.abspath(args.output_name)
print(f"Obs mode: {args.obs_mode}; Control mode: {args.control_mode}")
if args.obs_mode == 'pointcloud':
print(f"Obs frame: {args.obs_frame}; n_points: {args.n_points}; n_goal_points: {args.n_goal_points}")
return args
def main():
os.makedirs(osp.dirname(args.output_name), exist_ok=True)
if osp.exists(args.output_name) and not args.force:
print(f"Trajectory generation for {args.env_name} with output path {args.output_name} has been completed!!")
return
with h5py.File(args.traj_name, "r+") as h5_file:
keys = sorted(h5_file.keys())
# remove empty "obs" key from the input h5 file
for key in keys:
_ = h5_file[key].pop('obs', None)
if args.max_num_traj < 0:
args.max_num_traj = len(keys)
args.max_num_traj = min(len(keys), args.max_num_traj)
args.num_procs = min(args.num_procs, args.max_num_traj)
keys = keys[: args.max_num_traj]
extra_args = ()
if args.num_procs > 1:
running_steps = split_num(len(keys), args.num_procs)[1]
flush_print(f"Num of trajs = {len(keys)}", f"Num of process = {args.num_procs}")
processes = []
from copy import deepcopy
for i, x in enumerate(running_steps):
p = Process(target=convert_state_representation, args=(
deepcopy(keys[:x]), args, i, os.getpid(), *extra_args))
keys = keys[x:]
processes.append(p)
p.start()
for p in processes:
p.join()
else:
running_steps = [len(keys)]
convert_state_representation(keys, args, 0, os.getpid(), *extra_args)
files = []
for worker_id in range(len(running_steps)):
tmp_h5 = osp.join(tmp_folder_in_docker, f"{worker_id}.h5")
files.append(tmp_h5)
from shutil import rmtree
rmtree(args.output_name, ignore_errors=True)
merge_h5_trajectory(files, args.output_name)
for file in files:
rmtree(file, ignore_errors=True)
print(f"Finish merging files to {args.output_name}")
if __name__ == "__main__":
args = parse_args()
main()
|
haosulab/ManiSkill2-Learn
|
tools/convert_state.py
|
convert_state.py
|
py
| 10,700 |
python
|
en
|
code
| 53 |
github-code
|
6
|
70098626428
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2, c = 0):
# base case checking
res = ListNode(0)
if not l1 and not l2: return res
elif not l1: return l2
elif not l2: return l1
else:
curr1, curr2, curr3, prev = l1, l2, res, res
# loop through until one linked list out
while curr1 and curr2:
c, curr3.val = self.add(curr1.val, curr2.val, c)
curr3.next = ListNode(0)
prev = curr3
curr3 = curr3.next
curr1 = curr1.next
curr2 = curr2.next
# after one linked list runs out continue on the remaining one
# case1: both runs out
if not curr1 and not curr2:
prev.next = None if c==0 else ListNode(c)
return res
elif not curr1:
while curr2:
c, curr3.val = self.add(0, curr2.val, c)
curr3.next = ListNode(0)
prev = curr3
curr3 = curr3.next
curr2 = curr2.next
else:
while curr1:
c, curr3.val = self.add(curr1.val, 0, c)
curr3.next = ListNode(0)
prev = curr3
curr3 = curr3.next
curr1 = curr1.next
prev.next = None if c==0 else ListNode(c)
return res
def add(self, n1, n2, c):
res = n1 + n2 + c
return res // 10, res % 10
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(5)
result = Solution().addTwoNumbers(l1, l2)
while result:
print(result.val)
result = result.next
# 7 0 8
|
alexmai123/AlgoTime
|
Leetcode_problem/LinkedList/LinkedListSum.py
|
LinkedListSum.py
|
py
| 1,626 |
python
|
en
|
code
| 1 |
github-code
|
6
|
23303525367
|
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
def kmeans():
data = \
pd.read_csv(
'2019-04-28xm_fish.csv',
names=['房源名称', '租赁种类', '房源类型', '房源户型', '房源面积', '房源楼层', '房源朝向', '装修等级', '房源地址', '行政区划', '房源租金', '所在小区', '房源描述', '更新时间'],
keep_default_na=False,
index_col=False
)
invalid_list = data.loc[data['房源面积'] == 0]
data = data.drop(index=invalid_list.index)
invalid_list2 = data.loc[data['房源租金'] > 20000]
data = data.drop(index=invalid_list2.index)
data1 = data.iloc[:, [4, 10]]
km = KMeans(n_clusters=2, max_iter=500)
cluster_result = km.fit(data1)
# print(cluster_result.inertia_)
y_pred = cluster_result.labels_
predict = km.predict(data1)
color = ['red', 'green', 'blue', 'black', 'orange']
predict = [color[i] for i in predict]
plt.scatter(data1['房源面积'], data1['房源租金'], c=predict)
silhouette = silhouette_score(data1, y_pred)
print(silhouette)
plt.show()
# # 尝试归纳户型与租金的关系
# data2 = data.iloc[:, [3, 10]]
# km_ = KMeans(n_clusters=2, max_iter=500)
# cluster_result_ = km_.fit(data2)
# # print(cluster_result.inertia_)
# y_pred_ = cluster_result.labels_
# predict_ = km.predict(data2)
#
# predict_ = [color[i] for i in predict_]
#
# plt.scatter(data2['房源面积'], data2['房源租金'], c=predict_)
# silhouette = silhouette_score(data2, y_pred_)
# print(silhouette)
# plt.show()
if __name__ == '__main__':
kmeans()
# kmeans对初始值的稳定性较差
# input_file = 'a.csv'
# output_file = 'out.csv'
#
# k = 3
# iteration = 500
# data = pd.read_csv(input_file, index_col='Id')
# data_zs = 1.0 * (data - data.mean()) / data.std()
#
# model = KMeans(n_clusters=k, n_jobs=2, max_iter=iteration)
# model.fit(data_zs)
#
# r1 = pd.Series(model.labels_).value_counts()
# r2 = pd.DataFrame(model.cluster_centers_)
# r = pd.concat([r2, r1], axis=1)
# r.columns = list(data.columns) + [u'类别数目']
# print(r)
#
# r = pd.concat([data, pd.Series(model.labels_, index=data.index)], axis=1)
# r.columns = list(data.columns) + [u'聚类类别']
# r.to_csv(output_file)
|
Joy1897/Spider_58
|
kmeans.py
|
kmeans.py
|
py
| 2,423 |
python
|
en
|
code
| 0 |
github-code
|
6
|
72060297789
|
from flask import render_template, Flask, request, jsonify, url_for, redirect
import requests
from flask_pymongo import PyMongo
import json
from Model import *
import time
def after_request(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
return response
global Username
global token
token = ""
app = Flask(__name__)
app.after_request(after_request)
app.config['MONGO_URI'] = 'mongodb://comp9900:[email protected]:61529/comp9900_2019'
mongo = PyMongo(app)
@app.route('/',methods=['GET', 'POST'])
def home_page():
return render_template("test.html"), 200
@app.route('/user',methods=['GET'])
def personalpage():
return render_template("Personalinfo.html"), 200
@app.route('/signout', methods=['POST'])
def signout():
global token
global Username
token = ''
Username = ''
return "ok"
@app.route('/login', methods=['GET'])
def login_check():
global token
if token == '':
return '0'
else:
return Username
@app.route('/login', methods=['POST'])
def login():
global token
global Username
global Password
Username = request.form["sign_in_account"]
Password = request.form["sign_in_password"]
url = "http://127.0.0.1:5000/anhao0522/client/v1/login?username={Username}&password={Password}".format(Username=Username,Password=Password)
response = requests.get(url, headers={"Accept": "application/json"})
data = response.json()
print(data)
print(Username)
if data['reply'] == "NU":
return "No_account"
elif data['reply'] == "NM":
return "Wrong_password"
else:
token = data['reply']
return "ok"
@app.route('/signup',methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
Username = request.form["account"]
Password1 = request.form["password_1"]
dict1 = {"customer_id": Username, "password": Password1, "first_name": "", "last_name": "", "address": "",
"email": "",
"birthday": "", "credit": 0, "contact_number": "", "gender": "", "account_type": False,
"host_order": [], "trip_order": [],
"properties": [], "new_message": [], "message_box": []}
url = "http://127.0.0.1:5000/anhao0522/client/v1/signup"
response = requests.post(url, headers={"Accept": "application/json"}, json=dict1)
if response.status_code == 400:
return "Account name exist"
else:
return "ok"
else:
pass
@app.route('/event', methods=['POST'])
def get_event():
location = request.form["location"]
yelp = Yelp()
result = yelp.search_events(location)["events"]
#result = yelp.search_restaurant("gym","kingsford")["businesses"]
return jsonify(result)
@app.route('/order_delete', methods=['POST'])
def order_delete():
global Username
global token
order_id = request.form["order_id"]
request_type = request.form["request_type"]
if request_type == '0':
url = f"http://127.0.0.1:5000/anhao0522/client/v1/user/{Username}/order"
url +=f"?order_id={order_id}"
response = requests.delete(url, headers={"auth_token": token})
elif request_type == '1':
url = f"http://127.0.0.1:5000/anhao0522/client/v1/landlord/{Username}/order"
url += f"?order_id={order_id}&cancel_order=false"
response = requests.delete(url, headers={"auth_token": token})
elif request_type == '2':
url = f"http://127.0.0.1:5000/anhao0522/client/v1/landlord/{Username}/order"
url += f"?order_id={order_id}&cancel_order=true"
response = requests.delete(url, headers={"auth_token": token})
if response.status_code == 401:
print("401")
return "timeout"
elif response.status_code == 200:
return "ok"
else:
return "Something wrong"
@app.route('/new_message_read', methods=['POST'])
def new_message_read():
global Username
global token
delete_new = request.form["delete_new"]
url = "http://127.0.0.1:5000/anhao0522/client/v1/messageBox"
body = {"mid": f"{Username}", "time": "", "text": delete_new}
response = requests.post(url, headers={"auth_token": token}, json=body)
if response.status_code == 401:
print("401")
return "timeout"
elif response.status_code == 200:
return "ok"
else:
return "Something wrong"
@app.route('/new_message', methods=['POST'])
def new_message():
global Username
global token
url = "http://127.0.0.1:5000/anhao0522/client/v1/messageBox"
send_to = request.form["send_to"]
message = request.form["message"]
message_time = request.form["message_time"]
body = {"mid":f"{Username}---{send_to}","time":message_time,"text":message}
response = requests.post(url, headers={"auth_token": token}, json=body)
if response.status_code == 401:
print("401")
return "timeout"
elif response.status_code == 200:
return "ok"
else:
return "Something wrong"
@app.route('/new_comment', methods=['POST'])
def new_comment():
global Username
global token
comment_pid = request.form["comment_pid"]
comment_text = request.form["comment_text"]
rating_num = request.form["rating_num"]
comment_oid = request.form["comment_oid"]
time = request.form["time"]
url = f"http://127.0.0.1:5000/anhao0522/client/v1/accommodation/room/{comment_pid}/comment?order_id={comment_oid}"
body = {
"commenter": Username,
"avg_mark": rating_num,
"cleanliness_mark": 0,
"facility_mark": 0,
"attitude_mark": 0,
"text": comment_text,
"reply": "",
"photo": [],
"date": time
}
response = requests.post(url, headers={"auth_token": token}, json=body)
if response.status_code == 401:
print("401")
return "timeout"
elif response.status_code == 201:
return "ok"
else:
return "Something wrong"
@app.route('/message_del', methods=['GET'])
def message_del():
AB = request.args["AB"]
print(AB)
url = f"http://127.0.0.1:5000/anhao0522/client/v1/messageBox?AB={AB}"
response = requests.delete(url, headers={"auth_token": token})
if response.status_code == 401:
print("401")
return "wrong"
elif response.status_code == 200:
return "ok"
else:
return "Something wrong"
@app.route('/personalinfo', methods=['GET'])
def personalinfo():
global Username
global token
url = "http://127.0.0.1:5000/anhao0522/client/v1/user/"
sign_in_account = request.args["sign_in_account"]
url = url + sign_in_account
print(url)
print(sign_in_account)
response = requests.get(url, headers={"auth_token": token})
print(response.json())
return jsonify(response.json())
@app.route('/chatbot_msg', methods=['POST'])
def chatbot_msg():
global Username
global token
message = request.form["message"]
url = "http://127.0.0.1:5000/anhao0522/client/v1/chatbot?"
url+=f"q={message}"
response = requests.post(url, headers={"auth_token": token})
return jsonify(response.json())
@app.route('/s/<location>/all')
def show_list(location):
if request.method == 'POST':
destination = location
num_persons = request.args["numpeople"]
arrive_date = request.args["checkin"]
departure_date = request.args["checkout"]
if destination != None and num_persons != None and arrive_date != None and departure_date != None:
url = "http://127.0.0.1:5000/anhao0522/client/v1/accommodation/all?" \
"location={location}&checkin={checkin}&checkout={checkout}&numberofpeople={num}&searchtype={type}".format()
pass
@app.route('/<id>/property_post')
def picture(id):
global Username
global token
if id != Username:
return redirect(url_for('home_page'))
return render_template('NewProperty.html', id=id)
@app.route('/<id>/post_done',methods=['GET','POST'])
def post_property(id):
global Username
global token
if id != Username:
return redirect(url_for('home_page'))
if request.method == 'POST':
#print(request.form)
#print(request.values.get('Pet'))
tmp_dic = {}
tmp_dic.setdefault('property_type',request.values['property_type'])
tmp_dic.setdefault('property_bedroom', request.values['property_bedroom'])
tmp_dic.setdefault('property_bathroom', request.values['property_bathroom'])
tmp_dic.setdefault('property_parking', request.values['property_parking'])
tmp_dic.setdefault('property_wifi', request.values['WIFI'])
tmp_dic.setdefault('property_air', request.values['Air_condition'])
tmp_dic.setdefault('property_cook', request.values['Cooking'])
tmp_dic.setdefault('property_pet', request.values['Pet'])
property_location = request.form['property_location'].lower()
property_suburb = request.form['property_suburb'].lower()
property_address = request.form['property_address']
property_size = request.form['property_size']
property_price = request.form['property_price']
property_max_people = request.form['property_max_people']
property_start = request.form['start_date']
property_end = request.form['end_date']
property_title = request.form['property_title']
property_description = request.form['property_description']
for key in tmp_dic:
if tmp_dic[key] == "YES":
tmp_dic[key] = True
elif tmp_dic[key] == "NO":
tmp_dic[key] = False
else:
continue
#print(tmp_dic)
photo_id = []
if 'upload' in request.files:
for file in request.files.getlist("upload"):
#print("file ", file, type(file), file.filename)
mongo.save_file(file.filename, file)
num_photo = str(int(time.time()))
photo_id.append(num_photo)
mongo.db.test.insert_one({'id': num_photo, 'photo_name': file.filename})
#for i in range(len(request.files.getlist('upload'))):
# photo = request.files.getlist('upload')
# print(photo.filename)
#mongo.save_file(photo.filename, photo)
#num_photo = str(int(time.time()))
#mongo.db.test.insert_one({'id': num_photo, 'photo_name': photo.filename})
#id = 'Cindy'
lis_db = list(mongo.db.property_collection.find())
t_id = lis_db[-1]['property_id']
#print(t_id)
url = "https://maps.google.com/maps/api/geocode/json?key=AIzaSyAANyBQ6ikIoa53iMdahFL99Bjt0oBmWpc&address={address}&sensor=false".format(
address=property_address)
data = requests.request("GET", url)
ddic_1 = data.json()['results'][0]['geometry']['location']
lng = ddic_1['lng']
lat = ddic_1['lat']
ava_time = get_date_list(property_start,property_end)
ava_time_l = []
for i in ava_time:
ava_time_dic = {}
ava_time_dic.setdefault('time',i)
ava_time_dic.setdefault('status',True)
ava_time_l.append(ava_time_dic)
post_data_dic = {}
post_data_dic.setdefault('customer_id',id)
post_data_dic.setdefault('property_id',t_id+1)
post_data_dic.setdefault('address',property_address)
post_data_dic.setdefault('longitude',float(lng))
post_data_dic.setdefault('latitude',float(lat))
post_data_dic.setdefault('price', float(property_price))
post_data_dic.setdefault('type',tmp_dic['property_type'])
post_data_dic.setdefault('size',float(property_size))
post_data_dic.setdefault('wifi', tmp_dic['property_wifi'])
post_data_dic.setdefault('air-condition',tmp_dic['property_air'])
post_data_dic.setdefault('cooking', tmp_dic['property_cook'])
post_data_dic.setdefault('pet',tmp_dic['property_pet'])
post_data_dic.setdefault('bed_room',int(tmp_dic['property_bedroom']))
post_data_dic.setdefault('bath_room',int(tmp_dic['property_bathroom']))
post_data_dic.setdefault('parking',int(tmp_dic['property_parking']))
post_data_dic.setdefault('location',property_location)
post_data_dic.setdefault('suburb',property_suburb)
post_data_dic.setdefault('maxium_people',int(property_max_people))
post_data_dic.setdefault('about_the_place',property_description)
post_data_dic.setdefault('title',property_title)
post_data_dic.setdefault('rating',0.0)
post_data_dic.setdefault('comments',[])
post_data_dic.setdefault('p_photo',photo_id)
post_data_dic.setdefault('discount',0.0)
post_data_dic.setdefault('available_time',ava_time_l)
url1 = "http://127.0.0.1:5000/anhao0522/client/v1/landlord/{customer_id}/properties".format(customer_id=id)
#print(token)
response = requests.post(url1,json=post_data_dic,headers={"auth_token": token})
#print(response)
return redirect(url_for('home_page'))
@app.route('/location_center', methods=['POST'])
def get_center():
if request.method == 'POST':
location_str = request.form['location_list']
print(location_str)
location_list = location_str.split(":")
print(location_list)
location_list_2 = []
for e in location_list:
location_list_2.append([float(e.split("/")[0]), float(e.split("/")[1])])
print(location_list_2)
reslut = center_geolocation(location_list_2)
return jsonify({"result": reslut})
@app.route('/file/<file_id>')
def file(file_id):
data = mongo.db.test.find_one_or_404({'id': file_id})
filename = data['photo_name']
return mongo.send_file(filename)
if __name__ == '__main__':
app.run(port=5200, debug=True)
|
xiechzh/Accomodation-Web-Portal
|
COMP9900_Proj/COMP9900_Proj.py
|
COMP9900_Proj.py
|
py
| 13,953 |
python
|
en
|
code
| 1 |
github-code
|
6
|
71567683388
|
import streamlit as st
import pandas as pd
@st.cache
def load_data():
data = pd.read_csv('data.csv', sep=';', encoding='latin1')
return data
data = load_data()
selected_country = st.selectbox("Select a Country", data['Country'])
col1, col2 = st.columns(2)
with col1:
coal_percent = st.slider("Coal %", 0.0, 100.0, 0.0, key="coal_slider")
gas_percent = st.slider("Gas %", 0.0, 100.0, 0.0, key="gas_slider")
oil_percent = st.slider("Oil %", 0.0, 100.0, 0.0, key="oil_slider")
hydro_percent = st.slider("Hydro %", 0.0, 100.0, 0.0, key="hydro_slider")
renewable_percent = st.slider("Renewable %", 0.0, 100.0, 0.0, key="renewable_slider")
nuclear_percent = st.slider("Nuclear %", 0.0, 100.0, 0.0, key="nuclear_slider")
with col2:
coal_percent_manual = st.number_input("Coal % (Manual Input)", 0.0, 100.0, 0.0, format="%.2f", key="coal_manual")
gas_percent_manual = st.number_input("Gas % (Manual Input)", 0.0, 100.0, 0.0, format="%.2f", key="gas_manual")
oil_percent_manual = st.number_input("Oil % (Manual Input)", 0.0, 100.0, 0.0, format="%.2f", key="oil_manual")
hydro_percent_manual = st.number_input("Hydro % (Manual Input)", 0.0, 100.0, 0.0, format="%.2f", key="hydro_manual")
renewable_percent_manual = st.number_input("Renewable % (Manual Input)", 0.0, 100.0, 0.0, format="%.2f", key="renewable_manual")
nuclear_percent_manual = st.number_input("Nuclear % (Manual Input)", 0.0, 100.0, 0.0, format="%.2f", key="nuclear_manual")
coal_percent_total = coal_percent_manual if coal_percent_manual else coal_percent
gas_percent_total = gas_percent_manual if gas_percent_manual else gas_percent
oil_percent_total = oil_percent_manual if oil_percent_manual else oil_percent
hydro_percent_total = hydro_percent_manual if hydro_percent_manual else hydro_percent
renewable_percent_total = renewable_percent_manual if renewable_percent_manual else renewable_percent
nuclear_percent_total = nuclear_percent_manual if nuclear_percent_manual else nuclear_percent
Overall_Emission = (coal_percent_total + gas_percent_total + oil_percent_total +
hydro_percent_total + renewable_percent_total + nuclear_percent_total)
coal_CO2 = data[data['Country'] == selected_country]["Coal"].values[0]
gas_CO2 = data[data['Country'] == selected_country]["Gas"].values[0]
oil_CO2 = data[data['Country'] == selected_country]["Oil"].values[0]
hydro_CO2 = data[data['Country'] == selected_country]["Hydro"].values[0]
renewable_CO2 = data[data['Country'] == selected_country]["Renewable"].values[0]
nuclear_CO2 = data[data['Country'] == selected_country]["Nuclear"].values[0]
kgCO2_result = ((coal_percent_total * coal_CO2 + gas_percent_total * gas_CO2 + oil_percent_total * oil_CO2 +
hydro_percent_total * hydro_CO2 + renewable_percent_total * renewable_CO2 +
nuclear_percent_total * nuclear_CO2) / 100000)
st.markdown("<div class='result-section'>", unsafe_allow_html=True)
st.write("Overall Emission %:", Overall_Emission)
st.write("CO2 Emissions (tons):", round(kgCO2_result, 2), "tons of CO2")
st.markdown("</div>", unsafe_allow_html=True)
|
sneha-4-22/Energy-Calculator
|
app.py
|
app.py
|
py
| 3,135 |
python
|
en
|
code
| 0 |
github-code
|
6
|
32623837320
|
from base_factor import BaseFactor
from data.data_module import DataModule
class PEFactor(BaseFactor):
def __init__(self):
BaseFactor.__init__(self,'pe')
def compute(self,begin_date,end_date):
print(self.name,flush=True)
dm =DataModule()
df_daily = dm.get_k_data()
print(df_daily)
if __name__ == '__main__':
pe = PEFactor()
pe.compute(None,None)
|
bowenzz/Quant-Trading-System
|
factor/pe_factor.py
|
pe_factor.py
|
py
| 403 |
python
|
en
|
code
| 0 |
github-code
|
6
|
23268800112
|
# Here we will conduct a A/B test
import math
from hypo_testing import normal_probability_two_sided
def estimated_parameter(n, N):
p = n / N
sigma = math.sqrt(p * N * (1- p))
return N * p, sigma
def a_b_test_statistics(n_a, N_a, n_b, N_b):
p_a, sigma_a = estimated_parameter(n_a, N_a)
p_b, sigma_b =estimated_parameter(n_b, N_b)
print(p_a, p_b, math.sqrt(sigma_a **2 + sigma_b ** 2))
return (p_a - p_b) / math.sqrt(sigma_a **2 + sigma_b ** 2)
z = abs(a_b_test_statistics(200, 1000, 180, 1000))
print(z)
probability = normal_probability_two_sided(-z, z)
print(probability)
|
shm4771/Data-Science-From-Scratch
|
src/hypothesis_testing/A_B_test.py
|
A_B_test.py
|
py
| 585 |
python
|
en
|
code
| 0 |
github-code
|
6
|
21003174437
|
# This code is in the Public Domain
# -----------------------------------------------------------------------------
# This source file is part of Python-Ogre
# For the latest info, see http://python-ogre.org/
#
# It is likely based on original code from OGRE and/or PyOgre
# For the latest info, see http://www.ogre3d.org/
#
# You may use this sample code for anything you like, it is not covered by the
# LGPL.
# -----------------------------------------------------------------------------
#
# 29 July 2008: Ensured that resources.cfg and plugins.cfg can exist in the parent directory
#
import sys
import os
import os.path
import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS
###import OgreRefApp
def getPluginPath():
""" Return the absolute path to a valid plugins.cfg file.
look in the current directory for plugins.cfg followed by plugins.cfg.nt|linux|mac
If not found look one directory up
"""
paths = [os.path.join(os.getcwd(), 'plugins.cfg'),
os.path.join(os.getcwd(), '..','plugins.cfg'),
]
if os.sys.platform == 'darwin':
paths.insert(1, os.path.join(os.getcwd(), 'plugins.cfg.mac'))
paths.append(os.path.join(os.getcwd(), '..', 'plugins.cfg.mac'))
else:
paths.insert(1,os.path.join(os.getcwd(), 'plugins.cfg.'+os.name))
paths.append(os.path.join(os.getcwd(), '..', 'plugins.cfg.'+os.name))
for path in paths:
if os.path.exists(path):
return path
sys.stderr.write("\n"
"** Warning: Unable to locate a suitable plugins.cfg file.\n"
"** Warning: Please check your ogre installation and copy a\n"
"** Warning: working plugins.cfg file to the current directory.\n\n")
raise ogre.Exception(0, "can't locate a suitable 'plugins' file", "")
# def isUnitTest():
# """Looks for a magic file to determine if we want to do a unittest"""
# paths = [os.path.join(os.getcwd(), 'unittest.now'),
# os.path.join(os.getcwd(), '..','unittest.now')]
# for path in paths:
# if os.path.exists(path):
# return True
# return False
def isUnitTest():
""" use an environment variable to define that we need to do unittesting"""
env = os.environ
if env.has_key ("PythonOgreUnitTestPath"):
return True
return False
def UnitTest_Duration():
return 5
def UnitTest_Screenshot():
if isUnitTest():
env = os.environ
path = env["PythonOgreUnitTestPath"]
parentpath = os.getcwd().split(os.path.sep)[-1] # get the last part of the parent directory
filename = parentpath+'.'+ sys.modules['__main__'].__file__.split('.')[0] # file name is parent.demo.xx
path = os.path.join ( path, filename )
return path
else:
return "test"
class Application(object):
"This class is the base for an Ogre application."
debugText=""
def __init__(self):
self.frameListener = None
self.root = None
self.camera = None
self.renderWindow = None
self.sceneManager = None
self.world = None
self.unittest = isUnitTest()
def __del__(self):
"Clear variables, this should not actually be needed."
del self.camera
del self.sceneManager
del self.frameListener
if self.world:
del self.world
del self.root
del self.renderWindow
def go(self):
"Starts the rendering loop."
if not self._setUp():
return
self.root.startRendering()
def goOneFrame(self):
"Starts the rendering loop. Show how to use the renderOneFrame Method"
if not self._setUp():
return
self.root.getRenderSystem()._initRenderTargets()
while True:
ogre.WindowEventUtilities().messagePump()
if not self.root.renderOneFrame():
break
def _setUp(self):
"""This sets up the ogre application, and returns false if the user
hits "cancel" in the dialog box."""
pluginFile = getPluginPath() ## option here to switch to manually loading file if it doesn't exist
if self.unittest:
if os.path.isfile('ogre.cfg'):
self.root = ogre.Root( pluginFile )
else:
self.root = ogre.Root( pluginFile, '../ogre.cfg')
else:
self.root = ogre.Root( pluginFile )
self.root.setFrameSmoothingPeriod (5.0)
self._setUpResources()
if not self._configure():
return False
self._chooseSceneManager()
self._createWorld()
self._createCamera()
self._createViewports()
ogre.TextureManager.getSingleton().setDefaultNumMipmaps (5)
self._createResourceListener()
self._loadResources()
self._createScene()
self._createFrameListener()
return True
def _setUpResources(self):
"""This sets up Ogre's resources, which are required to be in
resources.cfg."""
config = ogre.ConfigFile()
try:
config.load('resources.cfg')
except ogre.OgreFileNotFoundException:
try:
config.load('../resources.cfg')
except:
raise
except:
raise
seci = config.getSectionIterator()
while seci.hasMoreElements():
SectionName = seci.peekNextKey()
Section = seci.getNext()
for item in Section:
ogre.ResourceGroupManager.getSingleton().\
addResourceLocation(item.value, item.key, SectionName)
def _createResourceListener(self):
"""This method is here if you want to add a resource listener to check
the status of resources loading."""
pass
def _createWorld ( self ):
""" this should be overridden when supporting the OgreRefApp framework. Also note you
will have to override __createCamera"""
pass
def _loadResources(self):
"""This loads all initial resources. Redefine this if you do not want
to load all resources at startup."""
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
def _configure(self):
"""This shows the config dialog and creates the renderWindow."""
if not self.unittest: # we show this if not doing a unittest
carryOn = self.root.showConfigDialog()
else:
carryOn = self.root.restoreConfig()
if carryOn:
windowTitle = os.path.join( os.getcwd(), sys.argv[0])
if not windowTitle:
windotTitle = "Ogre Render Window"
self.renderWindow = self.root.initialise(True,windowTitle)
return carryOn
def _chooseSceneManager(self):
"""Chooses a default SceneManager."""
#typedef uint16 SceneTypeMask;
#md=ogre.SceneManagerMetaData()
#md.sceneTypeMask=ogre.ST_GENERIC
#print dir(self.root)
self.sceneManager = self.root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
def _createCamera(self):
"""Creates the camera."""
self.camera = self.sceneManager.createCamera('PlayerCam')
self.camera.setPosition(ogre.Vector3(0, 0, 500))
self.camera.lookAt(ogre.Vector3(0, 0, -300))
self.camera.NearClipDistance = 5
def _createViewports(self):
"""Creates the Viewport."""
## We want a single sampleframework so this work around is to support OgreRefApp Framework
## if using the RefApp camera is based upon World etc etc
try:
self.viewport = self.renderWindow.addViewport(self.camera.getRealCamera())
except AttributeError:
self.viewport = self.renderWindow.addViewport(self.camera)
self.viewport.BackgroundColour = ogre.ColourValue(0,0,0)
def _createScene(self):
"""Creates the scene. Override this with initial scene contents."""
pass
def _createFrameListener(self):
"""Creates the FrameListener."""
#,self.frameListener, self.frameListener.Mouse
self.frameListener = FrameListener(self.renderWindow, self.camera)
self.frameListener.unittest = self.unittest
self.frameListener.showDebugOverlay(True)
self.root.addFrameListener(self.frameListener)
class FrameListener(ogre.FrameListener, ogre.WindowEventListener):
"""A default frame listener, which takes care of basic mouse and keyboard
input."""
def __init__(self, renderWindow, camera, bufferedKeys = False, bufferedMouse = False, bufferedJoy = False):
ogre.FrameListener.__init__(self)
ogre.WindowEventListener.__init__(self)
self.camera = camera
self.renderWindow = renderWindow
self.statisticsOn = True
self.numScreenShots = 0
self.timeUntilNextToggle = 0
self.sceneDetailIndex = 0
self.moveScale = 0.0
self.rotationScale = 0.0
self.translateVector = ogre.Vector3(0.0,0.0,0.0)
self.filtering = ogre.TFO_BILINEAR
self.showDebugOverlay(True)
self.rotateSpeed = ogre.Degree(36)
self.moveSpeed = 100.0
self.rotationSpeed = 8.0
self.displayCameraDetails = False
self.bufferedKeys = bufferedKeys
self.bufferedMouse = bufferedMouse
self.rotationX = ogre.Degree(0.0)
self.rotationY = ogre.Degree(0.0)
self.bufferedJoy = bufferedJoy
self.shouldQuit = False # set to True to exit..
self.MenuMode = False # lets understand a simple menu function
self.unittest = isUnitTest()
self.unittest_duration = UnitTest_Duration() # seconds before screen shot a exit
# self.unittest_screenshot = sys.modules['__main__'].__file__.split('.')[0] # file name for unittest screenshot
self.unittest_screenshot = UnitTest_Screenshot()
## we can tell if we are using OgreRefapp based upon the camera class
if self.camera.__class__ == ogre.Camera:
self.RefAppEnable = False
else:
self.RefAppEnable = True
self._setupInput()
def __del__ (self ):
ogre.WindowEventUtilities.removeWindowEventListener(self.renderWindow, self)
self.windowClosed(self.renderWindow)
def _inputSystemParameters (self ):
""" ovreride to extend any OIS system parameters
"""
return []
def _setupInput(self):
# ignore buffered input
# FIXME: This should be fixed in C++ propbably
import platform
int64 = False
for bit in platform.architecture():
if '64' in bit:
int64 = True
if int64:
windowHnd = self.renderWindow.getCustomAttributeUnsignedLong("WINDOW")
else:
windowHnd = self.renderWindow.getCustomAttributeInt("WINDOW")
#
# Here is where we create the OIS input system using a helper function that takes python list of tuples
#
t= self._inputSystemParameters()
params = [("WINDOW",str(windowHnd))]
params.extend(t)
self.InputManager = OIS.createPythonInputSystem( params )
#
# an alternate way is to use a multimap which is exposed in ogre
#
# pl = ogre.SettingsMultiMap()
# windowHndStr = str(windowHnd)
# pl.insert("WINDOW", windowHndStr)
# for v in self._inputSystemParameters():
# pl.insert(v[0],v[1])
# im = OIS.InputManager.createInputSystem( pl )
#Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
self.Keyboard = self.InputManager.createInputObjectKeyboard( OIS.OISKeyboard, self.bufferedKeys )
self.Mouse = self.InputManager.createInputObjectMouse( OIS.OISMouse, self.bufferedMouse )
try:
self.Joy = self.InputManager.createInputObjectJoyStick( OIS.OISJoyStick, self.bufferedJoy )
except:
self.Joy = False
#
#Set initial mouse clipping size
self.windowResized(self.renderWindow)
self.showDebugOverlay(True)
#Register as a Window listener
ogre.WindowEventUtilities.addWindowEventListener(self.renderWindow, self);
def setMenuMode(self, mode):
self.MenuMode = mode
def _UpdateSimulation( self, frameEvent ):
# create a real version of this to update the simulation
pass
def windowResized (self, rw):
dummyint = 0
width, height, depth, left, top= rw.getMetrics(dummyint,dummyint,dummyint, dummyint, dummyint) # Note the wrapped function as default needs unsigned int's
ms = self.Mouse.getMouseState()
ms.width = width
ms.height = height
def windowClosed(self, rw):
#Only close for window that created OIS (mWindow)
if( rw == self.renderWindow ):
if( self.InputManager ):
self.InputManager.destroyInputObjectMouse( self.Mouse )
self.InputManager.destroyInputObjectKeyboard( self.Keyboard )
if self.Joy:
self.InputManager.destroyInputObjectJoyStick( self.Joy )
OIS.InputManager.destroyInputSystem(self.InputManager)
self.InputManager=None
## NOTE the in Ogre 1.6 (1.7) this is changed to frameRenderingQueued !!!
def frameRenderingQueued ( self, evt ):
if(self.renderWindow.isClosed() or self.shouldQuit ):
return False
if self.unittest:
self.unittest_duration -= evt.timeSinceLastFrame
if self.unittest_duration < 0:
self.renderWindow.writeContentsToFile(self.unittest_screenshot + '.jpg')
return False
##Need to capture/update each device - this will also trigger any listeners
self.Keyboard.capture()
self.Mouse.capture()
buffJ = True
if( self.Joy ):
self.Joy.capture()
buffJ = self.Joy.buffered()
##Check if one of the devices is not buffered
if not self.Mouse.buffered() or not self.Keyboard.buffered() or not buffJ :
## one of the input modes is immediate, so setup what is needed for immediate movement
if self.timeUntilNextToggle >= 0:
self.timeUntilNextToggle -= evt.timeSinceLastFrame
## Move about 100 units per second
self.moveScale = self.moveSpeed * evt.timeSinceLastFrame
## Take about 10 seconds for full rotation
self.rotScale = self.rotateSpeed * evt.timeSinceLastFrame
self.rotationX = ogre.Degree(0.0)
self.rotationY = ogre.Degree(0.0)
self.translateVector = ogre.Vector3().ZERO
##Check to see which device is not buffered, and handle it
if not self.Keyboard.buffered():
if not self._processUnbufferedKeyInput(evt):
return False
if not self.Mouse.buffered():
if not self._processUnbufferedMouseInput(evt):
return False
if not self.Mouse.buffered() or not self.Keyboard.buffered() or not buffJ:
self._moveCamera()
return True
# def frameStarted(self, frameEvent):
# return True
#
# if self.timeUntilNextToggle >= 0:
# self.timeUntilNextToggle -= frameEvent.timeSinceLastFrame
#
# if frameEvent.timeSinceLastFrame == 0:
# self.moveScale = 1
# self.rotationScale = 0.1
# else:
# self.moveScale = self.moveSpeed * frameEvent.timeSinceLastFrame
# self.rotationScale = self.rotationSpeed * frameEvent.timeSinceLastFrame
#
# self.rotationX = ogre.Degree(0.0)
# self.rotationY = ogre.Degree(0.0)
# self.translateVector = ogre.Vector3(0.0, 0.0, 0.0)
# if not self._processUnbufferedKeyInput(frameEvent):
# return False
#
# if not self.MenuMode: # if we are in Menu mode we don't move the camera..
# self._processUnbufferedMouseInput(frameEvent)
# self._moveCamera()
# # Perform simulation step only if using OgreRefApp. For simplicity create a function that simply does
# ### "OgreRefApp.World.getSingleton().simulationStep(frameEvent.timeSinceLastFrame)"
#
# if self.RefAppEnable:
# self._UpdateSimulation( frameEvent )
# return True
def frameEnded(self, frameEvent):
if self.statisticsOn:
self._updateStatistics()
return True
def showDebugOverlay(self, show):
"""Turns the debug overlay (frame statistics) on or off."""
overlay = ogre.OverlayManager.getSingleton().getByName('POCore/DebugOverlay')
if overlay is None:
self.statisticsOn = False
ogre.LogManager.getSingleton().logMessage( "ERROR in sf_OIS.py: Could not find overlay POCore/DebugOverlay" )
return
if show:
overlay.show()
else:
overlay.hide()
def _processUnbufferedKeyInput(self, frameEvent):
if self.Keyboard.isKeyDown(OIS.KC_A):
self.translateVector.x = -self.moveScale
if self.Keyboard.isKeyDown(OIS.KC_D):
self.translateVector.x = self.moveScale
if self.Keyboard.isKeyDown(OIS.KC_UP) or self.Keyboard.isKeyDown(OIS.KC_W):
self.translateVector.z = -self.moveScale
if self.Keyboard.isKeyDown(OIS.KC_DOWN) or self.Keyboard.isKeyDown(OIS.KC_S):
self.translateVector.z = self.moveScale
if self.Keyboard.isKeyDown(OIS.KC_PGUP):
self.translateVector.y = self.moveScale
if self.Keyboard.isKeyDown(OIS.KC_PGDOWN):
self.translateVector.y = - self.moveScale
if self.Keyboard.isKeyDown(OIS.KC_RIGHT):
self.rotationX = - self.rotationScale
if self.Keyboard.isKeyDown(OIS.KC_LEFT):
self.rotationX = self.rotationScale
if self.Keyboard.isKeyDown(OIS.KC_ESCAPE) or self.Keyboard.isKeyDown(OIS.KC_Q):
return False
if( self.Keyboard.isKeyDown(OIS.KC_F) and self.timeUntilNextToggle <= 0 ):
self.statisticsOn = not self.statisticsOn
self.showDebugOverlay(self.statisticsOn)
self.timeUntilNextToggle = 1
if self.Keyboard.isKeyDown(OIS.KC_T) and self.timeUntilNextToggle <= 0:
if self.filtering == ogre.TFO_BILINEAR:
self.filtering = ogre.TFO_TRILINEAR
self.Aniso = 1
elif self.filtering == ogre.TFO_TRILINEAR:
self.filtering = ogre.TFO_ANISOTROPIC
self.Aniso = 8
else:
self.filtering = ogre.TFO_BILINEAR
self.Aniso = 1
ogre.MaterialManager.getSingleton().setDefaultTextureFiltering(self.filtering)
ogre.MaterialManager.getSingleton().setDefaultAnisotropy(self.Aniso)
self.showDebugOverlay(self.statisticsOn)
self.timeUntilNextToggle = 1
if self.Keyboard.isKeyDown(OIS.KC_SYSRQ) and self.timeUntilNextToggle <= 0:
path = 'screenshot_%d.png' % self.numScreenShots
self.numScreenShots += 1
self.renderWindow.writeContentsToFile(path)
Application.debugText = 'screenshot taken: ' + path
self.timeUntilNextToggle = 0.5
if self.Keyboard.isKeyDown(OIS.KC_R) and self.timeUntilNextToggle <= 0:
detailsLevel = [ ogre.PM_SOLID,
ogre.PM_WIREFRAME,
ogre.PM_POINTS ]
self.sceneDetailIndex = (self.sceneDetailIndex + 1) % len(detailsLevel)
self.camera.polygonMode=detailsLevel[self.sceneDetailIndex]
self.timeUntilNextToggle = 0.5
if self.Keyboard.isKeyDown(OIS.KC_F) and self.timeUntilNextToggle <= 0:
self.statisticsOn = not self.statisticsOn
self.showDebugOverlay(self.statisticsOn)
self.timeUntilNextToggle = 1
if self.Keyboard.isKeyDown(OIS.KC_P) and self.timeUntilNextToggle <= 0:
self.displayCameraDetails = not self.displayCameraDetails
if not self.displayCameraDetails:
Application.debugText = ""
if self.displayCameraDetails:
# Print camera details
pos = self.camera.getDerivedPosition()
o = self.camera.getDerivedOrientation()
Application.debugText = "P: %.3f %.3f %.3f O: %.3f %.3f %.3f %.3f" \
% (pos.x,pos.y,pos.z, o.w,o.x,o.y,o.z)
return True
def _isToggleKeyDown(self, keyCode, toggleTime = 1.0):
if self.Keyboard.isKeyDown(keyCode)and self.timeUntilNextToggle <=0:
self.timeUntilNextToggle = toggleTime
return True
return False
def _isToggleMouseDown(self, Button, toggleTime = 1.0):
ms = self.Mouse.getMouseState()
if ms.buttonDown( Button ) and self.timeUntilNextToggle <=0:
self.timeUntilNextToggle = toggleTime
return True
return False
def _processUnbufferedMouseInput(self, frameEvent):
ms = self.Mouse.getMouseState()
if ms.buttonDown( OIS.MB_Right ):
self.translateVector.x += ms.X.rel * 0.13
self.translateVector.y -= ms.Y.rel * 0.13
else:
self.rotationX = ogre.Degree(- ms.X.rel * 0.13)
self.rotationY = ogre.Degree(- ms.Y.rel * 0.13)
return True
def _moveCamera(self):
self.camera.yaw(self.rotationX)
self.camera.pitch(self.rotationY)
# try:
# self.camera.translate(self.translateVector) # for using OgreRefApp
# except AttributeError:
self.camera.moveRelative(self.translateVector)
def _updateStatistics(self):
statistics = self.renderWindow
self._setGuiCaption('POCore/AverageFps', 'Avg FPS: %u' % statistics.getAverageFPS())
self._setGuiCaption('POCore/CurrFps', 'FPS: %u' % statistics.getLastFPS())
# self._setGuiCaption('POCore/BestFps',
# 'Best FPS: %f %d ms' % (statistics.getBestFPS(), statistics.getBestFrameTime()))
# self._setGuiCaption('POCore/WorstFps',
# 'Worst FPS: %f %d ms' % (statistics.getWorstFPS(), statistics.getWorstFrameTime()))
self._setGuiCaption('POCore/NumTris', 'Trianges: %u' % statistics.getTriangleCount())
self._setGuiCaption('POCore/NumBatches', 'Batches: %u' % statistics.batchCount)
self._setGuiCaption('POCore/DebugText', Application.debugText)
def _setGuiCaption(self, elementName, text):
element = ogre.OverlayManager.getSingleton().getOverlayElement(elementName, False)
##d=ogre.UTFString("hell0")
##element.setCaption(d)
#element.caption="hello"
#element.setCaption("help")
element.setCaption(text) # ogre.UTFString(text))
|
only-a-ptr/ror-toolkit
|
windows/ogre/renderer/OGRE/sf_OIS.py
|
sf_OIS.py
|
py
| 23,588 |
python
|
en
|
code
| 4 |
github-code
|
6
|
24200680597
|
from collections import Counter
class Solution:
def func(self, strings, K):
"""
Args:
strings: list[str]
K: int
"""
counter = Counter(strings)
counter_list = [(key, counter[key]) for key in counter]
# 频数大, 字母序小 -> 频数小, 字母序大
counter_list.sort(key=lambda x: [-x[1], x])
for i in range(K):
print(counter_list[i][0], counter_list[i][1])
counter_list.sort(key=lambda x: [x[1], x])
for i in range(K):
print(counter_list[i][0], counter_list[i][1])
if __name__ == "__main__":
N, K = list(map(int, input().split()))
strings = []
for _ in range(N):
strings.append(input())
Solution().func(strings, K)
|
AiZhanghan/Leetcode
|
秋招/腾讯/3.py
|
3.py
|
py
| 787 |
python
|
en
|
code
| 0 |
github-code
|
6
|
71353706429
|
# GMM implementation
# good resource http://www.rmki.kfki.hu/~banmi/elte/bishop_em.pdf
import numpy as np
from scipy import stats
import seaborn as sns
from random import shuffle, uniform
sns.set_style("white")
#Generate some data from 2 different distributions
x1 = np.linspace(start=-10, stop=10, num=1000)
x2 = np.linspace(start=5, stop=10, num=800)
y1 = stats.norm.pdf(x1, loc=3, scale=1.5)
y2 = stats.norm.pdf(x2, loc=0, scale=3)
#Put data in dataframe for better handling
x = list(x1)
x.extend(list(x2))
shuffle(x)
K = 2 #number of assumed distributions within the dataset
epsilon = 0.001 #tolerance change for log-likelihood
max_iter = 100
#gaussian pdf function
def G(datum, mu, sigma):
y = (1 / (np.sqrt((2 * np.pi) * sigma * sigma)) * np.exp(datum-mu)*(datum-mu)/(2*sigma*sigma))
return y
#compute log-likelihood
def L(X, N, mu, sigma, pi):
L = 0
for i in range(N):
Gk = 0
for k in range(K):
Gk += pi[k] * G(X[i], mu[k], sigma[k])
L += Gk
print(L)
return np.log(L)
def estimate_gmm(X, K, epsilon, max_iter):
N = len(X)
# assign random mean and variance to each distribution
mu, sigma = [uniform(0, 10) for _ in range(K)], [uniform(0, 10) for _ in range(K)]
# assign random probability to each distribution
pi = [uniform(0, 10) for _ in range(K)]
mu = [2, 0]
sigma = [1, 1]
current_loglike = np.inf
for _ in range(max_iter):
previous_loglike = current_loglike
#E step
mixture_affiliation_all_k = {}
for i in range(N):
parts = [pi[k] * G(X[i], mu[k], sigma[k]) for k in range(K)]
total = sum(parts)
for k in range(K):
mixture_affiliation_all_k[(i, k)] = parts[k] / total
#M step
mixture_affiliation_for_k = [sum(mixture_affiliation_all_k[(i, k)] for i in range(N)) for k in range(K)]
for k in range(K):
pi[k] = mixture_affiliation_for_k[k] / N
mu[k] = sum([mixture_affiliation_all_k[(i, k)] * X[i] for i in range(N)]) / mixture_affiliation_for_k[k]
sigma[k] = sum([mixture_affiliation_all_k[(i, k)] * (X[i] - mu[k]) ** 2 for i in range(N)]) / mixture_affiliation_for_k[k]
current_loglike = L(X, N, mu, sigma, pi)
if abs(previous_loglike - current_loglike) < epsilon:
print("break")
break
return mu, sigma, pi
print(estimate_gmm(x, K, epsilon, max_iter))
|
cristian904/GMMs
|
GMM.py
|
GMM.py
|
py
| 2,456 |
python
|
en
|
code
| 0 |
github-code
|
6
|
14570677084
|
###=========================================================###
### ###
### Create Boundary Condition(BC) ###
### ###
###=========================================================###
##-- Import library
import numpy as np
##-- F: Force
##-- U: Displacement
##-- Um: boolean index, i.e., 0-->x, 1-->y
##-- Kcal: [K] designed for solving matrix
def set_BC(K, node_BC, node_F, num_node, load):
##-- Copy of K for post calculation
Kcal = K.copy()
##-- node_BC: index of nodes, imposed of BC.
U = np.zeros(2*num_node.data)
Um = np.zeros(2*num_node.data, dtype="int64") + 1
Um[node_BC] = 0
Um = ( Um == 0 )
#print(Um)
##-- node_F: index of nodes, imposed of Load
F = np.zeros(2*num_node.data)
F[node_F] = load.data
#print(F)
##-- Prepare Matrix(K), considering BC
for i in node_BC:
Kcal[i, :] = 0.
Kcal[:, i] = 0.
Kcal[i, i] = 1.
return F, U, Um, Kcal
|
caron14/2D-FEM
|
mod_set_BC.py
|
mod_set_BC.py
|
py
| 1,077 |
python
|
en
|
code
| 0 |
github-code
|
6
|
17936071521
|
__author__ = 'gilles.drigout'
from proposal import *
from numpy import zeros, random
from numbapro import cuda
from numbapro.cudalib import curand
import math
import time
@cuda.autojit
def cu_one_block(x_start, y, omega, uniforms, result, size, chain_length):
i = cuda.grid(1)
if i < size:
result[i,0] = x_start
for t in range(1, chain_length):
x_prev = result[i, t-1]
acceptance_ratio = min(1, omega[t]*(1+x_prev**2)*math.exp(-0.5*x_prev**2))
if i*size + t*chain_length < N*N:
u = uniforms[i*size + t*chain_length]
if u < acceptance_ratio:
result[i, t] = y[t]
else:
result[i, t] = x_prev
class BlockIMH:
def __init__(self, chain_start, block_size, num_blocks, proposals, omegas):
self.chain_start = chain_start
self.block_size = block_size
self.num_blocks = num_blocks
self.chain_length = block_size * num_blocks
self.proposals = proposals
self.omegas = omegas
self.block_count = 0
self.block_start = chain_start
def iterate_block(self):
if self.block_count*self.block_size < self.chain_length:
proposals_block = self.proposals[self.block_count*self.block_size:(self.block_count+1)*self.block_size]
omegas_block = self.omegas[self.block_count*self.block_size:(self.block_count+1)*self.block_size]
block = Block(size=self.block_size, proposals=proposals_block, omegas=omegas_block, start=self.block_start)
block_values = block.compute_block()
# drawing random integer for next block start
rand_chain = random.random_integers(self.block_size-1)
self.block_start = block_values[-1][rand_chain]
self.block_count +=1
def iterate_all_chain(self):
while self.block_count*self.block_size < self.chain_length:
t0 = time.time()
self.iterate_block()
print(time.time()-t0)
class Block:
def __init__(self, size, proposals, omegas, start):
self.size = size
self.host_proposals = proposals
self.host_omegas = omegas
self.start = start
self.threads_per_block = 512
self.grid_dim = (self.size // self.threads_per_block)+ 1
def compute_block(self):
device_uniforms = curand.uniform(size=N*N, device=True)
host_results = zeros((self.size, self.size))
stream = cuda.stream()
device_proposals = cuda.to_device(self.host_proposals, stream=stream)
device_omegas = cuda.to_device(self.host_omegas, stream=stream)
device_results = cuda.device_array_like(host_results, stream=stream)
cu_one_block[self.grid_dim, self.threads_per_block, stream](self.start, device_proposals,
device_omegas, device_uniforms,
device_results, self.size, self.size)
device_results.copy_to_host(host_results, stream=stream)
stream.synchronize()
return host_results
@staticmethod
@cuda.autojit
def cu_block(x_start, y, omega, uniforms, result, size, chain_length):
i = cuda.grid(1)
if i < size:
result[i,0] = x_start
for t in range(1, chain_length):
x_prev = result[i, t-1]
acceptance_ratio = min(1, omega[t]*(1+x_prev**2)*math.exp(-0.5*x_prev**2))
if i*size + t*chain_length < N*N:
u = uniforms[i*size + t*chain_length]
if u < acceptance_ratio:
result[i, t] = y[t]
else:
result[i, t] = x_prev
if __name__ == '__main__':
N = 10000
t = ToyExample(N)
host_y = t.host_values
host_omega = t.host_omegas
imh = BlockIMH(chain_start=0, block_size=100, num_blocks=10, proposals=host_y, omegas=host_omega)
imh.iterate_all_chain()
|
Jingoo88/Projet-3A-2015
|
Kernel method/blockIMH.py
|
blockIMH.py
|
py
| 4,087 |
python
|
en
|
code
| 0 |
github-code
|
6
|
3547587015
|
import numpy as np
import tensorflow as tf
from structure_vgg import CNN
from datetime import datetime
import os
from tfrecord_reader import tfrecord_read
import config
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_string('dataset', 'dset1', 'Choose dset1 or dset2 for training, default dset1.')
tf.flags.DEFINE_string('checkpoint', None,
'Whether use a pre-trained checkpoint to continue training, default None.')
def main():
checkpoint_dir = 'checkpoints'
if FLAGS.checkpoint is not None:
checkpoint_path = os.path.join(checkpoint_dir, FLAGS.checkpoint.lstrip('checkpoints/'))
else:
current_time = datetime.now().strftime('%Y%m%d-%H%M')
checkpoint_path = os.path.join(checkpoint_dir, '{}'.format(current_time))
try:
os.makedirs(checkpoint_path)
except os.error:
print('Unable to make checkpoints direction: %s' % checkpoint_path)
model_save_path = os.path.join(checkpoint_path, 'model.ckpt')
cnn = CNN()
read_for_train = tfrecord_read(
FLAGS.dataset, config.batch_size, config.num_epochs, config.train_slice, training=True)
read_for_val = tfrecord_read(
FLAGS.dataset, config.batch_size, config.num_epochs, config.train_slice, training=False)
saver = tf.train.Saver()
print('Build session.')
tfconfig = tf.ConfigProto()
tfconfig.gpu_options.allow_growth = True
sess = tf.Session(config=tfconfig)
if FLAGS.checkpoint is not None:
print('Restore from pre-trained model.')
checkpoint = tf.train.get_checkpoint_state(checkpoint_path)
meta_graph_path = checkpoint.model_checkpoint_path + '.meta'
restore = tf.train.import_meta_graph(meta_graph_path)
restore.restore(sess, tf.train.latest_checkpoint(checkpoint_path))
step = int(meta_graph_path.split('-')[2].split('.')[0])
else:
print('Initialize.')
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
step = 0
epoch_pre = step * config.batch_size // config.file_num[FLAGS.dataset]
loss_list = []
accuracy_list = []
val_epoch_accuracies = []
# train_writer = tf.summary.FileWriter('log', sess.graph)
# summary_op = tf.summary.merge_all()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
print('Start training:')
while not coord.should_stop():
X_train_batch, y_train_batch = sess.run([read_for_train.X_batch, read_for_train.y_batch])
loss, train_batch_accuracy, _, lr = sess.run([cnn.loss, cnn.batch_accuracy, cnn.optimizer, cnn.learning_rate],
{cnn.X_inputs: X_train_batch, cnn.y_inputs: y_train_batch,
cnn.keep_prob: config.keep_prob, cnn.training: True})
loss_list.append(loss)
X_val_batch, y_val_batch = sess.run([read_for_val.X_batch, read_for_val.y_batch])
correct_pre_num, val_batch_accuracy = sess.run([cnn.correct_pre_num, cnn.batch_accuracy],
{cnn.X_inputs: X_val_batch, cnn.y_inputs: y_val_batch,
cnn.keep_prob: 1.0, cnn.training: False})
val_epoch_accuracies.append(val_batch_accuracy)
# train_writer.add_summary(summary, step)
# train_writer.flush(
epoch_cur = step * config.batch_size // config.file_num[FLAGS.dataset]
if epoch_cur > epoch_pre:
# val_epoch_accuracy = np.sum(correct_pre_nums) / ((step + 1) * config.batch_size)
val_epoch_accuracy = np.mean(val_epoch_accuracies)
accuracy_list.append(val_epoch_accuracy)
print('For epoch %i: val_epoch_accuracy = %.3f%%\n' %
(epoch_pre, val_epoch_accuracy * 100))
epoch_pre = epoch_cur
val_epoch_accuracies = []
if step % 10 == 0 and step > 0:
print('>> At step %i: loss = %.3f, train_batch_accuracy = %.3f%%' %
(step, loss, train_batch_accuracy * 100))
print(lr)
if step % 1000 == 0 and step > 0:
save_path = saver.save(sess, model_save_path, global_step=step)
print('Model saved in file: %s' % save_path)
step += 1
except KeyboardInterrupt:
print('Interrupted')
coord.request_stop()
except Exception as e:
coord.request_stop(e)
finally:
save_path = saver.save(sess, model_save_path, global_step=step)
print('Model saved in file: %s' % save_path)
coord.request_stop()
coord.join(threads)
sess.close()
if __name__ == '__main__':
main()
|
yikaiw/DL-hw2-CNN
|
main.py
|
main.py
|
py
| 4,806 |
python
|
en
|
code
| 0 |
github-code
|
6
|
38231691013
|
from django.shortcuts import render, get_object_or_404
from .models import Post, Group
def index(request):
posts = Post.objects.order_by('-pub_date')[:10]
title = 'Это главная страница проекта Yatube'
context = {
'posts': posts,
'title': title,
}
return render(request, 'posts/index.html', context)
def group_posts(request, slug):
group = get_object_or_404(Group, slug=slug)
posts = Post.objects.filter(group=group).order_by('-pub_date')[:10]
title = 'Лев Толстой – зеркало русской революции.'
context = {
'group': group,
'posts': posts,
'title': title,
}
return render(request, 'posts/group_list.html', context)
|
NikitaKorovykovskiy/Yatube_project
|
yatube/posts/views.py
|
views.py
|
py
| 762 |
python
|
en
|
code
| 0 |
github-code
|
6
|
71781170429
|
import cv2
# read your picture and store into variable "img"
img = cv2.imread('picture.jpg')
# scale image down 3 times
for i in range(3):
img = cv2.pyrDown(img)
# save scaled image
cv2.imwrite(f'picture_scaled_{i}.jpg', img)
|
yptheangel/opencv-starter-pack
|
python/basic/image_pyramid.py
|
image_pyramid.py
|
py
| 240 |
python
|
en
|
code
| 8 |
github-code
|
6
|
21806123410
|
import sys
def set_options(opt):
opt.tool_options("compiler_cxx")
def configure(conf):
conf.check_tool("compiler_cxx")
conf.check_tool("node_addon")
if sys.platform == 'darwin':
conf.env.append_value('LINKFLAGS', ['-framework','CoreMidi','-framework','CoreAudio','-framework','CoreFoundation'])
else:
conf.env.append_value('LINKFLAGS', ['-lasound', '-lpthread'])
def build(bld):
obj = bld.new_task_gen("cxx", "shlib", "node_addon")
obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall"]
if sys.platform == 'darwin':
obj.cxxflags.append("-D__MACOSX_CORE__")
else:
obj.cxxflags.append("-D__LINUX_ALSASEQ__")
obj.target = "midi"
obj.source = "src/node-midi.cpp"
|
sksmatt/NodeJS-Ableton-Piano
|
node_modules/midi/wscript
|
wscript
| 725 |
python
|
en
|
code
| 104 |
github-code
|
6
|
|
7886651161
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 18 21:42:00 2021
@author: fyy
"""
import scipy.stats as stats
import numpy as np
import random
import scipy.io as scio
import matplotlib.pyplot as plt
import math
dataFile = './_dat/val_dataset.mat'
ratio = 0.05
sample_num = 100 # 训练样本的大小
max_len = 250
min_len = 180
max_kn = 4
min_kn = 0
s_length = 200
def stable(maxLen,priValue):
priSeq = np.ones(maxLen)*priValue
return priSeq
def jitter(maxLen,priValue,priDev):
maxDevValue = priValue*priDev
lowerBound = priValue-maxDevValue
upperBound = priValue+maxDevValue
priSeq = np.random.randint(lowerBound,upperBound+1,maxLen)#lower<=x<upper
params = [priValue,priDev,maxDevValue]
return priSeq
#周期
def periodic(maxLen,priValue,ratio):
amp=priValue*ratio; #正弦幅度
freq=50; #正弦频率
sample = random.randint(2*freq,8*freq) #正弦采样率
fsample=400#正弦采样率
priDSSeq = np.zeros(maxLen)
for i in range(maxLen):
priDSSeq[i] = amp*math.sin(freq*i/fsample)+priValue#正弦PRI序列
#priDSSeq = priDSSeq[:maxLen] #截断
para = [priValue,ratio,sample]
return priDSSeq
#滑变
def sliding(maxLen,priValue,ratio):
priMax=priValue*ratio #pri最大值
pulseNum=random.randint(ratio,32) #pri点数
slidingStep=(priMax-priValue)/pulseNum; #滑变步长
slidingSeq = np.zeros(pulseNum+1)
for i in range(pulseNum+1):
#一个周期的滑变PRI序列
slidingSeq[i] = i*slidingStep + priValue
seqLen=len(slidingSeq);
cycleNum=math.ceil(maxLen/seqLen)#向上取整周期数
priDSSeq = np.tile(slidingSeq, cycleNum)#重复若干个周期
priDSSeq = priDSSeq[:maxLen] #截断
para = [priValue,ratio,priMax,pulseNum,slidingStep]
return priDSSeq
'''
import numpy as np
a = np.array([[1, 2, 0, 3, 0],
[4, 5, 0, 6, 0],
[7, 8, 0, 9, 0]])
idx = np.argwhere(np.all(a[..., :] == 0, axis=0))
a2 = np.delete(a, idx, axis=1)
'''
#参差 3-10
def stagger(maxLen,priValue,priNum):
seqLen=priNum #一个周期的脉组中脉冲数目
cycleNum=math.ceil(maxLen/seqLen) #周期数
priSeq = priValue
priSSeq=np.tile(priSeq,cycleNum)#重复若干周期
priSSeq=priSSeq[:maxLen]#截断
para = [priValue,priNum,cycleNum]
return priSSeq
def gen_func(m,maxLen):
if m==1:
return stable(maxLen)
elif m==2:
return jitter(maxLen)
elif m==3:
return periodic(maxLen)
elif m==4:
return sliding(maxLen)
elif m==5:
return stagger(maxLen)
else:
print("****error!****")
def solve(nums, x, y) :
if nums == []:
return False
if x>y:
(x,y) = (y,x)
for i in range(len(nums)):
if x<= nums[i] <= y:
return True
else:
continue
return False
def pri2toa(inputseq):
#mask = np.logical_not(inputseq)
mask = inputseq!=0
inputseq = inputseq[mask]
toa = np.zeros(len(inputseq)+1)
i = 0
while(i<len(inputseq)):
toa[i+1] = toa[i]+inputseq[i]
i = i+1
return toa
max_len = 250
def lostPul(inputseq,proportion,label,pattern):#缺失脉冲
# inputseq: 输入TOA序列
# proportion: 缺失百分比
# seqTOA: 缺失的TOA序列
# seqPRI: 缺失的PRI序列
lostPulseSeq=pri2toa(inputseq) #每个proportion下面的缺失脉冲TOA序列
lengthWorkModeSample=len(lostPulseSeq)
rand_num = math.floor(lengthWorkModeSample*proportion)
randomIndex=np.random.randint(0,lengthWorkModeSample,rand_num)#lower<=x<upper
randomIndex = sorted(randomIndex)
j=0
mask = label!=0
label = label[mask]
lostlabel = label*1 #单纯a = b 只是浅复制将a指向b
p = pattern*1
for i in range(len(randomIndex)):
while(j<len(label) and randomIndex[i]>=label[j]):
j = j+1
lostlabel[j:] = lostlabel[j:] - 1
lostPulseSeq=[i for num,i in enumerate(lostPulseSeq) if num not in randomIndex]
p =[i for num,i in enumerate(p) if num not in randomIndex]
p = np.array(p)
for i in range(len(randomIndex)):
p[randomIndex[i]-1-i] = 6
lostPulseSeq = np.array(lostPulseSeq)
seqPRI=lostPulseSeq[1:]-lostPulseSeq[:-1]
seqTOA=lostPulseSeq
z = np.zeros(max_len)
seqPRI = np.append(seqPRI,z)
p = np.append(p,z)
z = np.zeros(5)
lostlabel = np.append(lostlabel,z)
return seqPRI[:max_len],lostlabel[:5],p[:max_len]
def findpos(arr,x):
for i in range(len(arr)):
if arr[i]>x:
return i
return -1
def suprPul(inputseq,proportion,label,p):#虚警脉冲
# inputseq: 输入TOA序列
# proportion: 虚警百分比
# seqTOA: 虚警的TOA序列
# seqPRI: 虚警的PRI序列
# pw: 脉宽,脉冲串脉宽设置为5us
supPulseSeq=pri2toa(inputseq) #每个proportion下面的缺失脉冲TOA序列
lengthWorkModeSample=len(supPulseSeq)
tMax = math.floor(max(supPulseSeq))
randomNum = math.floor(lengthWorkModeSample*proportion)
randomTime=np.random.randint(0,tMax,randomNum)
randomTime = sorted(randomTime)
mask = label!=0
label = label[mask]
pattern = p*1
j = 0
for i in range(len(randomTime)):
pos = findpos(supPulseSeq,randomTime[i])
while(j<len(label) and label[j] < pos):
j = j+1
label[j:] = label[j:] + 1
supPulseSeq = np.insert(supPulseSeq, pos,randomTime[i])
pattern[pos-1] = 6
pattern = np.insert(pattern, pos,6)
randomIndex=[i for i,val in enumerate(supPulseSeq) if val in randomTime]
seqPRI=supPulseSeq[1:]-supPulseSeq[:-1]
seqTOA=supPulseSeq
z = np.zeros(max_len)
seqPRI = np.append(seqPRI,z)
z = np.zeros(5)
label = np.append(label,z)
return seqPRI[:max_len],label[:5],pattern[:max_len]
def meaErr(inputseq,stdPRI):
# inputseq: 输入TOA序列
# stdPRI: 测量误差的标准差
# seqTOA: 输出TOA序列
# seqPRI: 输出PRI序列
seqTOA=pri2toa(inputseq)
lengthWorkModeSample=len(seqTOA)
errGenarated = np.random.normal(0, stdPRI, lengthWorkModeSample)
#errGenarated=normrnd(0,stdPRI,[1,lengthWorkModeSample])
seqTOA=seqTOA+errGenarated
seqPRI=seqTOA[1:]-seqTOA[:-1]
return seqPRI[:max_len]
def indices(a,func):
#实现find函数
return [i for (i,val) in enumerate(a) if func(val)]
#a = [1 2 3 1 2 3]
#find = indices(a,lambda x:x>2) --> [2,5]
data = np.zeros((sample_num, max_len), dtype=np.float32)
label = np.zeros((sample_num, max_kn+1), dtype=np.int)
pattern = np.zeros((sample_num, max_kn+1), dtype=np.int)
p = np.zeros((sample_num, max_len), dtype=np.float32)
for i in range(sample_num):
#seq_len = random.randint(min_len,max_len)
seq_len = max_len
knum = random.randint(min_kn,max_kn)
k = []
for j in range(knum):
a = random.randint(25,s_length-25)
while solve(k,a-25,a+25):
a = random.randint(25,s_length-25)
k.append(a)
k.append(seq_len)
k = np.array(k)
k = sorted(k)
priValue = random.randint(10,20)*10
priDev = random.randint(10,20)/20
for j in range(knum+1):
label[i,j] = k[j]
module = 2
pattern[i,j] = module
flag = random.randint(1,3)
tempValue = priValue
tempDev = priDev
if flag == 1:#均值方差全变
while(tempValue==priValue):
tempValue = random.randint(10,20)*10
while(tempDev==priDev):
tempDev = random.randint(10,20)/20
elif flag == 2:#只变均值
while(tempValue==priValue):
tempValue = random.randint(10,20)*10
else:#只变均值
while(tempDev==priDev):
tempDev = random.randint(10,20)/20
priValue = tempValue
priDev = tempDev
if j==0:
data[i,:k[j]] = jitter(k[j],priValue,priDev)
p[i,:k[j]] = module
else:
data[i,k[j-1]:k[j]] = jitter(k[j]-k[j-1],priValue,priDev)
p[i,k[j-1]:k[j]] = module
d = data*1
l = label*1
result = np.zeros((sample_num, s_length), dtype=np.float32)
L = np.zeros((sample_num, s_length), dtype=np.float32)
'''
for i in range(sample_num):
d[i] =meaErr(data[i],1)
for i in range(sample_num):
d[i],l[i],p[i] = lostPul(data[i],0.1,l[i],p[i])#247.5
for i in range(sample_num):
d[i],l[i],p[i] = suprPul(data[i],0.05,l[i],p[i])#247.5
'''
d = d[:,:s_length]
p = p[:,:s_length]
for i in range(sample_num):
for j in range(max_kn+1):
if l[i,j]>=s_length:
l[i,j:] = 0
l[i,j] = s_length
break
for i in range(sample_num):
for j in range(max_kn+1):
if l[i,j] != s_length and l[i,j] != 0:
result[i,l[i,j]] = 1
L[i,l[i,j]] = 1
result[i,l[i,j]-1] = 0.8
result[i,l[i,j]+1] = 0.8
plt.plot(d[0])
# scio.savemat(dataFile, {'data':d,'label':result,'pattern':p,'L':L,'Y':d,'l_true':l})
|
Carty-Bao/BNPHMM
|
code/gen_new.py
|
gen_new.py
|
py
| 9,565 |
python
|
en
|
code
| 0 |
github-code
|
6
|
16104264799
|
import gatt
import numpy as np
import time
import datetime
class BLE(gatt.Device):
def __init__(self, Age, Height, Gender, Write, manager,mac_address):
super().__init__(manager = manager , mac_address = mac_address)
self.Age = Age
self.Height = Height
self.Gender = Gender
self.Write = Write
self.values = []
self.ReadStatus = False
self.Read = True
self.count = 0
self.manager = manager
def Write_Bytes(self, c):
#Write bytes to initiate communication
magicBytes = [0xac, 0x02, 0xf7, 0x00, 0x00, 0x00, 0xcc, 0xc3]
c.write_value(magicBytes)
#write 2nd bytes to server
magicBytes = [0xac, 0x02, 0xfa, 0x00, 0x00, 0x00, 0xcc, 0xc6]
c.write_value(magicBytes)
#Calculate offset for error checking bits
Offset = self.Age + self.Height - 56
#Sending Age and height with offset to server
magicBytes = [0xac, 0x02, 0xfb, 0x01, self.Age, self.Height, 0xcc, Offset]
c.write_value(magicBytes)
#time.sleep(1)
#Calculate offset for Present date
now = datetime.datetime.now()
#Write present date to server(scale)
Offset = (now.year-1799) + now.month + now.day
magicBytes = [0xac, 0x02, 0xfd, (now.year - 2000), now.month, now.day, 0xcc, Offset]
c.write_value(magicBytes)
#time.sleep(1)
#Calculate offset for time
now = datetime.datetime.now()
Offset = now.hour + now.minute
magicBytes = [0xac, 0x02, 0xfc, now.hour, now.minute, 56, 0xcc, Offset]
c.write_value(magicBytes)
#time.sleep(1)
magicBytes = [0xac, 0x02, 0xfe, 0x06, 0x00, 0x00, 0xcc, 0xd0]
c.write_value(magicBytes)
#time.sleep(0.6)
def body_composition(self):
#Weight of person shifting higher bit by 8bit position to left and or with lower bit to get 16bit value
weight = float(((self.values[0][12] << 8) | self.values[0][13]) / 10) #. kg
Fat = float (((self.values[0][18] << 8 ) | self.values[0][19])/ 10) #.%
Calorie = int((self.values[1][5] << 8) | self.values[1][6] ) #. kcal
bone_mass = float(((self.values[1][7] << 8 ) | self.values[1][8]) / 10 ) #. kg
water = float(((self.values[1][9] << 8) | self.values[1][10]) / 10) #.% body composition
MetabolicAge = int(self.values[1][11]) #In years
print ("Weight ===================>" + str(weight) +".Kg")
print ("Fat ======================>" + str(Fat) + "%")
print ("Calorie ==================>" + str(Calorie) + "Kcal")
print ("Bone_mass ================>" + str(bone_mass) + "Kg")
print ("Water ====================>" + str(water) + "%")
print ("MetabolicAge =============>" + str(MetabolicAge) + "years")
return {"Weight" : weight,
"Fat" : Fat,
"Calorie" : Calorie,
"BoneMass": bone_mass,
"Water" : water ,
"MAge" : MetabolicAge }
def services_resolved(self):
super().services_resolved()
for s in self.services:
if s.uuid == '0000ffb0-0000-1000-8000-00805f9b34fb': #services 0016
for c in s.characteristics:
if (c.uuid == '0000ffb1-0000-1000-8000-00805f9b34fb') and (self.Write == True): #char 0017
self.Write_Bytes (c)
self.Write = False
print(c)
#c.enable_notifications()
if c.uuid == '0000ffb2-0000-1000-8000-00805f9b34fb' and self.Read == True:
c.read_value()
c.enable_notifications()
print(c)
self.Read = False
def characteristic_value_updated(self, characteristic, value):
print("Firmware version:", value)
check = value[0] + value[1]
if check == 0:
self.ReadStatus = True
if len(value) == 20 and self.ReadStatus == True :
if self.count == 0:
self.values.append(value)
self.count = self.count + 1
else:
if value != self.values[0]:
self.values.append(value)
self.manager.stop()
|
sanbuddhacharyas/MEDICAL_CARE
|
source_code/BLE.py
|
BLE.py
|
py
| 4,518 |
python
|
en
|
code
| 0 |
github-code
|
6
|
35800840346
|
import unittest
import numpy as np
from numpy import linalg
from task import img_rescaled, img_array_transposed, U, s, Vt
class TestCase(unittest.TestCase):
def test_transpose(self):
np.testing.assert_array_equal(img_array_transposed, np.transpose(img_rescaled, (2, 0, 1)),
'The transposed array does not look right.')
def test_svd(self):
transposed_test = np.transpose(img_rescaled, (2, 0, 1))
U_test, s_test, Vt_test = linalg.svd(transposed_test)
np.testing.assert_array_equal(U, U_test,
'Your decomposition does not look right. Go back to "SVD on One Matrix" to refresh the topic.')
np.testing.assert_array_equal(s, s_test,
'Your decomposition does not look right. Go back to "SVD on One Matrix" to refresh the topic.')
np.testing.assert_array_equal(Vt, Vt_test,
'Your decomposition does not look right. Go back to "SVD on One Matrix" to refresh the topic.')
|
jetbrains-academy/Python-Libraries-NumPy
|
Projects/SVD/Applying to All Colors/tests/test_task.py
|
test_task.py
|
py
| 1,073 |
python
|
en
|
code
| 1 |
github-code
|
6
|
72473999867
|
from math import sqrt
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x1_list = []
x2_list = []
y_list = []
counter = 0
def show(x1_list, x2_list):
N = int(x1_list.__len__())
if (N <= 0):
return
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
x1_array = np.arange(min(x1_list) - 1, max(x1_list) + 1, 0.01)
x2_array = np.arange(min(x2_list) - 1, max(x2_list) + 1, 0.01)
#x1_array = np.arange(-6, 3, 0.1)
#x2_array = np.arange(-6, 6, 0.1)
x1_array, x2_array = np.meshgrid(x1_array, x2_array)
R = f(x1_array, x2_array)
ax = Axes3D(fig)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('f(x1,x2)')
ax.plot_surface(x1_array, x2_array, R, color='b', alpha=0.5)
x1_list2 = []
x2_list2 = []
f_list = []
ax.scatter(x1_list[0], x2_list[0], f(x1_list[0], x2_list[0]), c='black')
x1_list2.append(x1_list[0])
x2_list2.append(x2_list[0])
f_list.append(f(x1_list[0], x2_list[0]))
#print(x1_list[0], x2_list[0], f(x1_list[0], x2_list[0]))
for n in range(1, N):
ax.scatter(x1_list[n], x2_list[n], f(x1_list[n], x2_list[n]), c='red')
x1_list2.append(x1_list[n])
x2_list2.append(x2_list[n])
f_list.append(f(x1_list[n], x2_list[n]))
#print(x1_list[n], x2_list[n], f(x1_list[n], x2_list[n]))
ax.scatter(x1_list[N - 1], x2_list[N - 1], f(x1_list[N - 1], x2_list[N - 1]), c='green')
#print(x1_list[N - 1], x2_list[N - 1], f(x1_list[N - 1], x2_list[N - 1]))
ax.plot(x1_list2, x2_list2, f_list, color="black")
plt.show()
def f(x1, x2):
return 3*x1**4 - x1*x2 + x2**4 - 7*x1 - 8*x2 + 2
def f_x1(x1, x2):
return 12*x1**3 - x2 - 7
def f_x2(x1, x2):
return 4*x2**3 - x1 - 8
def gradient(x1, x2):
i = f_x1(x1, x2)
j = f_x2(x1, x2)
return [i, j]
def module_of_gradient(grad):
i = 0; j = 1
return sqrt(grad[i]**2 + grad[j]**2)
def dichotomy_mehod(a, b, epsilon, x1, x2, d1, d2):
x = (a + b) / 2
global counter
counter += 2
if (f(x1 + (x - epsilon)*d1, x2 + (x - epsilon)*d2) < f(x1 + (x + epsilon)*d1, x2 + (x + epsilon)*d2)):
b = x
else:
a = x
if(abs(b - a) >= 2 * epsilon):
return dichotomy_mehod(a, b, epsilon, x1, x2, d1, d2)
return x
def the_fletcher_reevse_method(x1, x2, e1, e2, M):
global counter
k = 0
d_prev = [0, 0]
grad_prev = 0
while True:
counter += 2
grad = gradient(x1, x2)
module_grad = module_of_gradient(grad)
if ((module_grad < e1) | (k >= M)):
return [(round(x1, round_num), round(x2, round_num), round(f(x1, x2), round_num)), k]
B = 0
if k % 2 == 1: B = module_of_gradient(grad)**2 / module_of_gradient(grad_prev)**2
d = [-grad[0] + B * d_prev[0], -grad[1] + B * d_prev[1]]
t = dichotomy_mehod(0, 0.1, e1, x1, x2, d[0], d[1])
x1_next = x1 + t * d[0]
x2_next = x2 + t * d[1]
x1_list.append(x1); x2_list.append(x2)
counter += 1
if ((sqrt(abs(x1_next - x1)**2 + abs(x2_next - x2)**2) <= e2)
& (abs(f(x1_next, x2_next) - f(x1, x2)) <= e2)):
return [(round(x1_next, round_num),
round(x2_next, round_num),
round(f(x1_next, x2_next), round_num)),
k]
x1 = x1_next; x2 = x2_next
d_prev = d; grad_prev = grad
k += 1
round_num = 3
x1 = -5
x2 = 3
e1 = 0.001
e2 = 0.001
M = 100
result = the_fletcher_reevse_method(x1, x2, e1, e2, M)
print(f"The Fletcher Reevse method: {result[0]}; count of iteractions = {result[1]}")
print('Count of compute function =', counter)
#show(x1_list, x2_list)
|
AlexSmirno/Learning
|
6 Семестр/Оптимизация/Lab_4_1.py
|
Lab_4_1.py
|
py
| 3,768 |
python
|
en
|
code
| 0 |
github-code
|
6
|
37056080424
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Simple univariate BLUP implementation for starting values estimation."""
import numpy as np
from scipy.optimize import minimize
def grad(sigmas: np.ndarray, y: np.ndarray, k: np.ndarray):
v = 1 / (sigmas[0] + sigmas[1] * k)
if np.any(v < 1e-12):
return [np.nan, np.nan]
yt = y * v
g = np.zeros(2)
g[0] = np.sum(yt ** 2) - np.sum(np.log(v))
g[1] = np.sum(yt * k * y) - np.sum(np.log(v ** 2 * k))
return g
def obj(sigmas: np.ndarray, y: np.ndarray, k: np.ndarray):
v = 1 / (sigmas[0] + sigmas[1] * k)
if np.any(v < 1e-8):
return np.nan
yt = y * v
return np.sum(yt * y) - np.sum(np.log(v))
def blup(y: np.ndarray, k: np.ndarray, p=0.8, maxiter=50):
"""
Calculate BLUP estimate for U of a single variable.
Parameters
----------
y : np.ndarray
Observations of a given variable.
k : np.ndarray
K matrix.
p : float, optional
Expected ratio of variable variance to random effect variance. Used for
starting values only. The default is 0.8.
maxiter : int, optional
Maximal number of iterations. Better not be too high or estimation
process could take noticable time in some cases. The default is 50.
Returns
-------
U
Random effects estimate (BLUP).
"""
v = np.var(y)
x0 = np.array([p * v, (1 - p) * v])
s = minimize(lambda x: obj(x, y, k), x0, jac=lambda x: grad(x, y, k),
method="SLSQP", options={'maxiter': maxiter},
bounds=([0, None], [0, None])
).x
v = 1 / (1 / s[0] + (1 / s[1]) * (1 / k))
return y * v / s[0], s
|
planplus/pysem
|
pysem/univariate_blup.py
|
univariate_blup.py
|
py
| 1,705 |
python
|
en
|
code
| 4 |
github-code
|
6
|
8257233523
|
# Use the environment variables DIANA_BROKER and DIANA_RESULT to attach the celery
# app to a message queue.
import os
from celery import Celery
app = Celery('diana')
app.conf.update(
result_expires = 3600,
task_serializer = "pickle",
accept_content = ["pickle"],
result_serializer = "pickle",
task_default_queue = 'default',
task_routes={'*.gpu': {'queue': 'gpu'}, # Only GPU boxes
'*.file': {'queue': 'file'} }, # Access to shared fs
include=['diana.star.tasks'],
broker_url=os.environ.get('DIANA_BROKER', "redis://localhost:6379/1"),
result_backend=os.environ.get('DIANA_RESULT', "redis://localhost:6379/2"),
timezone = 'America/New_York'
)
print(os.environ.get('DIANA_BROKER', "redis://localhost:6379/1"))
|
derekmerck/DIANA
|
packages/diana/diana/star/app.py
|
app.py
|
py
| 776 |
python
|
en
|
code
| 11 |
github-code
|
6
|
3337645854
|
import time
from pyspark import SparkContext,SparkConf
#-----------------------------------------------
#spark map reduce练习
def mymap(line):
return len(line)
#在spark中这样对数字进行叠加是不可行对 由于闭包机制,每一份机器上都单独有一份所引用都对象 应该使用saprk提供都累加器
nums_all=0
def test_foreach(nums):
global nums_all
nums_all+=nums
print(nums_all)
if __name__ == '__main__':
conf = SparkConf().setAppName('test').setMaster('local')
sc = SparkContext(conf=conf)
text_rdd=sc.textFile('./data/*.txt')
map_rdd=text_rdd.map(mymap)
#count=map_rdd.foreach(test_foreach)
# new_text_rdd=text_rdd.flatMap(lambda x:(x,'hahaha','xxxx'))
new_rdd=text_rdd.map(lambda line:line.split('\t'))
print(new_rdd.first())
time.sleep(10000)
# for i in map_rdd.take(5):
# print(i)
#rdd2 = sc.textFile('./data/sequence_file', ) # 读取一个目录下的文件 已文件名、内容的形式返回
#print(rdd2.first().encode('utf-8').decode())
|
zml1996/learn_record
|
learn_spark/test_spark2.py
|
test_spark2.py
|
py
| 1,066 |
python
|
fa
|
code
| 2 |
github-code
|
6
|
38633501754
|
def get_input():
done = False
while not done:
try:
points = int(input('How many points does the post have?: '))
if points > 0:
ratio = int(input('What is the percentage of users who upvoted the post?: '))
if ratio <= 100 and ratio > 50:
done = True
else:
print('{0}% is an invalid percentage.'.format(ratio))
else:
print('Reddit does not currently display negative scores.')
except ValueError:
print('Your values must be integers.')
return points, ratio
def reddit_votes(points, ratio):
votes = points / ((ratio / 50) - 1)
upvotes = votes * (ratio / 100)
downvotes = votes - upvotes
return round(upvotes) + round(downvotes), round(upvotes), round(downvotes)
def print_output(votes, upvotes, downvotes):
if votes == 1:
print(votes, 'vote.')
else:
print(votes, 'votes.')
if upvotes == 1:
print(upvotes, 'upvote.')
else:
print(upvotes, 'upvotes.')
if downvotes == 1:
print(downvotes, 'downvote.')
else:
print(downvotes, 'downvotes.')
def main():
points, ratio = get_input()
total_votes, upvotes, downvotes = reddit_votes(points, ratio)
print_output(total_votes, upvotes, downvotes)
main()
|
mthezeng/hello-world
|
redditvotes.py
|
redditvotes.py
|
py
| 1,372 |
python
|
en
|
code
| 0 |
github-code
|
6
|
12477690188
|
#!/ebio/abt1_share/toolkit_support1/sources/anaconda3/bin/python
import glob
import re
import pandas as pd
data_dir = '/tmp/global2/vikram/felix/master_thesis/data/alphafold/v2'
data_dir = '/Users/felixgabler/PycharmProjects/master_thesis/data/alphafold/v2'
def write_seq_to_file(accession: str, uniprot_id: str, seq_lines: str, existing_ids: set):
if len(uniprot_id) == 0 or uniprot_id not in existing_ids:
return
with open(f'{data_dir}/sequences/{uniprot_id}.fasta', 'w') as handle:
handle.write(accession + seq_lines)
def split_out_sequence_files():
uniprot_ids = set()
for proteome_file in glob.glob(f'{data_dir}/AA_scores/*.csv'):
ids = pd.read_csv(proteome_file, usecols=['uniprot_id'])['uniprot_id'].array
uniprot_ids = uniprot_ids.union(set(ids))
print(f'Creating sequence files for {len(uniprot_ids)} sequences')
with open(f'{data_dir}/sequences.fasta') as handle:
accession = ''
uniprot_id = ''
seq_lines = ''
for line in handle:
if line.startswith('>'):
write_seq_to_file(accession, uniprot_id, seq_lines, uniprot_ids)
accession = line
uniprot_id = re.search(r'AF-([A-Z0-9]+)-', line).group(1)
seq_lines = ''
else:
seq_lines += line
write_seq_to_file(accession, uniprot_id, seq_lines, uniprot_ids)
if __name__ == '__main__':
split_out_sequence_files()
|
felixgabler/master_thesis
|
bin/utils/split_sequences.py
|
split_sequences.py
|
py
| 1,472 |
python
|
en
|
code
| 0 |
github-code
|
6
|
71666200828
|
from django.contrib import admin
from .models import newdoc
class DocAdmin(admin.ModelAdmin):
fieldsets = [
(None, {"fields": ["title"]}),
("Date information", {"fields": ["created_time"]}),
(None, {"fields": ["modified_time"]}),
("Author information", {"fields": ["author"]}),
(None, {"fields": ["body"]})
]
list_filter = ["created_time"]
list_display = ('title', 'created_time', 'author')
search_fields = ["title"]
#class uploaded(admin.ModelAdmin):
# Register models here.
admin.site.register(newdoc, DocAdmin)
|
JarvisDong/Project-CGD
|
mysite/documents/admin.py
|
admin.py
|
py
| 652 |
python
|
en
|
code
| 0 |
github-code
|
6
|
664923791
|
#Import's
import random
#Variáveis
#Classes
guerreiro = [
#Nome(0) Vida(1)
'Guerreiro', 50,
#Ataque básico(2) dano(3)
'Corte de espada', 10,
#Ataque especial(4) dano(5)
'Lamina ardente', 20
]
arqueiro = [
#Nome(0) Vida(1)
'Arqueiro', 50,
#Ataque básico(2) dano(3)
'Flecha veloz', 10,
#Ataque especial(4) dano(5)
'Three shot', 20
]
mago = [
#Nome(0) Vida(1)
'Mago', 50,
#Ataque básico(2) Dano(3)
'Bola de fogo', 10,
#Ataque especial(4) Dano(5)
'Maldição', 20
]
oponente = [
#Nome(0) Vida(1)
'Sr.Maldade', 100,
#Ataque básico(2) Dano(3)
'Pedrada', 10,
#Ataque especial(4) Dano(5)
'Lamina de sangue', 20
]
#Funções
def escolher_classe():
try:
print("""
1. Guerreiro
2. Arqueiro
3. Mago
""")
classe = int(input('Escolha sua classe de acordo ao número.'))
except ValueError:
print("Somente números sao aceitos. Tente novamente.")
if classe != int():
print("Positivo")
if classe == 1 :
print("Sua classe é guerreiro")
elif classe == 2:
print("Sua classe é arqueiro")
elif classe == 3:
print("Sua classe é mago")
def batalha():
oponente = random.randint(1,20)
player = random.randint(1,20)
print(oponente)
print(player)
if oponente > player:
print("Você tomou dano!")
elif player > oponente:
print("Causou dano!")
else:
print("Dados iguiais! Relancando dados...")
batalha()
#Executando o programa
escolher_classe()
|
KancsSneed/Exercicios_python
|
Atividades/rpg.py
|
rpg.py
|
py
| 1,931 |
python
|
pt
|
code
| 0 |
github-code
|
6
|
26113491295
|
__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "06/03/2018"
from .. import qt
class BoxLayoutDockWidget(qt.QDockWidget):
"""QDockWidget adjusting its child widget QBoxLayout direction.
The child widget layout direction is set according to dock widget area.
The child widget MUST use a QBoxLayout
:param parent: See :class:`QDockWidget`
:param flags: See :class:`QDockWidget`
"""
def __init__(self, parent=None, flags=qt.Qt.Widget):
super(BoxLayoutDockWidget, self).__init__(parent, flags)
self._currentArea = qt.Qt.NoDockWidgetArea
self.dockLocationChanged.connect(self._dockLocationChanged)
self.topLevelChanged.connect(self._topLevelChanged)
def setWidget(self, widget):
"""Set the widget of this QDockWidget
See :meth:`QDockWidget.setWidget`
"""
super(BoxLayoutDockWidget, self).setWidget(widget)
# Update widget's layout direction
self._dockLocationChanged(self._currentArea)
def _dockLocationChanged(self, area):
self._currentArea = area
widget = self.widget()
if widget is not None:
layout = widget.layout()
if isinstance(layout, qt.QBoxLayout):
if area in (qt.Qt.LeftDockWidgetArea, qt.Qt.RightDockWidgetArea):
direction = qt.QBoxLayout.TopToBottom
else:
direction = qt.QBoxLayout.LeftToRight
layout.setDirection(direction)
self.resize(widget.minimumSize())
self.adjustSize()
def _topLevelChanged(self, topLevel):
widget = self.widget()
if widget is not None and topLevel:
layout = widget.layout()
if isinstance(layout, qt.QBoxLayout):
layout.setDirection(qt.QBoxLayout.LeftToRight)
self.resize(widget.minimumSize())
self.adjustSize()
def showEvent(self, event):
"""Make sure this dock widget is raised when it is shown.
This is useful for tabbed dock widgets.
"""
self.raise_()
|
silx-kit/silx
|
src/silx/gui/widgets/BoxLayoutDockWidget.py
|
BoxLayoutDockWidget.py
|
py
| 2,125 |
python
|
en
|
code
| 106 |
github-code
|
6
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.