blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2
values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107
values | src_encoding stringclasses 20
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 4 6.02M | extension stringclasses 78
values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9aeabf6744ed3a9ac5a1df44c5287b764fe258ac | 114d1ca95de41c3d1ae5aabeddcd5054b327973b | /socket_programs/client-google.py | 55126e853f68d5dbd82ce80009526dc1bcdd8541 | [] | no_license | sambapython/batch28_1 | 7e134ac0166f916ece16dc81f162e5c51af2d9f8 | ccd7ba382ecd148afad8d29c09839f43e6bc8c23 | refs/heads/master | 2021-01-21T19:09:03.026169 | 2017-06-25T07:55:44 | 2017-06-25T07:55:44 | 92,122,075 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 193 | py | import socket
try:
s=socket.socket()
host="www.google.com"
port=8888#443#80
s.connect((host,port))
print "connected successfully!!!"
except Exception as err:
print err
finally:
s.close() | [
"sambapython@gmail.com"
] | sambapython@gmail.com |
255899d627252f49a4ec7107aa90f27ae13ec583 | 41c004dfda3ebc92fba598a5ff9a219455fab50f | /tests/add_dummy_vertices_test.py | 56a7c46067ed9cb20a33584b8d7f5e26d74bca94 | [] | no_license | konstantin1998/graphRendering | 738686c773c7d4bde9ca359f99542c31fbb3601e | acee2e9a10c20f0069f781496108c0d5496b859d | refs/heads/master | 2023-04-04T08:15:45.310626 | 2021-04-11T09:13:22 | 2021-04-11T09:13:22 | 356,820,658 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,953 | py | from src.Node import Node
from src.add_dummy_vert import needs_dummy_vert, split_edge, assign_positions_for_dummy_vertices, \
add_dummy_vertices_and_edges
from src.assign_layer_positions import assign_layer_positions, group_by_levels
from src.assign_layers import assign_layers
from src.extract_nodes import extract_nodes
def assert_needs_dummy_vertex():
edge1 = {'source': '1', 'target': '4'}
edge2 = {'source': '1', 'target': '2'}
node_to_layer_map = {'1': 1, '4': 4, '2': 2}
return needs_dummy_vert(edge1, node_to_layer_map) and not needs_dummy_vert(edge2, node_to_layer_map)
def assert_split_edge_correctly():
edge = {'source': '1', 'target': '4'}
node_to_layer_map = {'1': 1, '4': 4}
counter = 1
nodes, edges, counter = split_edge(edge, node_to_layer_map, counter)
nodes.sort(key=lambda node: node.id)
edges.sort(key=lambda edge: edge['source'])
return counter == 3 and nodes[0].id == '2' and nodes[1].id == '3'\
and len(nodes) == 2\
and len(edges) == 3 \
and edges[0]['source'] == '1' and edges[0]['target'] == '2'\
and edges[1]['source'] == '2' and edges[1]['target'] == '3' \
and edges[2]['source'] == '3' and edges[2]['target'] == '4'
def assert_dummy_vertices_get_correct_positions():
nodes = [Node('0'), Node('1')]
nodes[0].layer = 1
nodes[0].pos_in_layer = 1
nodes[1].layer = 2
nodes[1].pos_in_layer = 2
dummy_vertices = [Node('2'), Node('3'), Node('4')]
dummy_vertices[0].layer = 1
dummy_vertices[1].layer = 2
dummy_vertices[2].layer = 2
assign_positions_for_dummy_vertices(nodes, dummy_vertices)
return dummy_vertices[0].pos_in_layer == 2 \
and dummy_vertices[1].pos_in_layer == 3\
and dummy_vertices[2].pos_in_layer == 4
def assert_add_dummy_vertices_correctly():
edges = [{'source': '0', 'target': '2'},
{'source': '0', 'target': '1'},
{'source': '0', 'target': '3'},
{'source': '1', 'target': '4'},
{'source': '4', 'target': '6'},
{'source': '6', 'target': '7'},
{'source': '3', 'target': '5'},
{'source': '5', 'target': '7'},
{'source': '2', 'target': '7'}]
nodes = extract_nodes(edges)
assign_layers(nodes, edges)
assign_layer_positions(nodes, edges)
add_dummy_vertices_and_edges(nodes, edges)
level_groups = group_by_levels(nodes)
should_be_true = True
for group in level_groups:
actual_positions = list(map(lambda node: node.pos_in_layer, group))
for position in actual_positions:
should_be_true = should_be_true and position >= 1
should_be_true = should_be_true and len(nodes) == 11 and len(edges) == 12
return should_be_true
assert assert_needs_dummy_vertex()
assert assert_split_edge_correctly()
assert assert_dummy_vertices_get_correct_positions()
assert assert_add_dummy_vertices_correctly()
| [
"galperin.15@yandex.ru"
] | galperin.15@yandex.ru |
57ebd085c128e22baf91b628599a8ce78537a5fa | 611ee093d73056012d97e8fcb9b506e8a8f40f9b | /examples/ROIExamples.py | 20c45e6b8d39f7222421d7fc2ca457bba40150f6 | [
"MIT"
] | permissive | LBeghini/GraphManipulation.py | b64978f128d2bba20f4aeb30ab7c681e35e0d5d6 | 74705eb19c241a203adb133116617287250578ca | refs/heads/master | 2023-04-22T18:46:23.710379 | 2021-05-09T23:28:01 | 2021-05-09T23:28:01 | 365,047,596 | 0 | 0 | null | 2021-05-08T03:06:26 | 2021-05-06T22:02:55 | Python | UTF-8 | Python | false | false | 4,653 | py | # -*- coding: utf-8 -*-
"""
Demonstrates a variety of uses for ROI. This class provides a user-adjustable
region of interest marker. It is possible to customize the layout and
function of the scale/rotate handles in very flexible ways.
"""
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
pg.setConfigOptions(imageAxisOrder='row-major')
## Create image to display
arr = np.ones((100, 100), dtype=float)
arr[45:55, 45:55] = 0
arr[25, :] = 5
arr[:, 25] = 5
arr[75, :] = 5
arr[:, 75] = 5
arr[50, :] = 10
arr[:, 50] = 10
arr += np.sin(np.linspace(0, 20, 100)).reshape(1, 100)
arr += np.random.normal(size=(100,100))
# add an arrow for asymmetry
arr[10, :50] = 10
arr[9:12, 44:48] = 10
arr[8:13, 44:46] = 10
## create GUI
app = pg.mkQApp("ROI Examples")
w = pg.GraphicsLayoutWidget(show=True, size=(1000,800), border=True)
w.setWindowTitle('pyqtgraph example: ROI Examples')
text = """Data Selection From Image.<br>\n
Drag an ROI or its handles to update the selected image.<br>
Hold CTRL while dragging to snap to pixel boundaries<br>
and 15-degree rotation angles.
"""
w1 = w.addLayout(row=0, col=0)
label1 = w1.addLabel(text, row=0, col=0)
v1a = w1.addViewBox(row=1, col=0, lockAspect=True)
v1b = w1.addViewBox(row=2, col=0, lockAspect=True)
img1a = pg.ImageItem(arr)
v1a.addItem(img1a)
img1b = pg.ImageItem()
v1b.addItem(img1b)
v1a.disableAutoRange('xy')
v1b.disableAutoRange('xy')
v1a.autoRange()
v1b.autoRange()
rois = []
rois.append(pg.RectROI([20, 20], [20, 20], pen=(0,9)))
rois[-1].addRotateHandle([1,0], [0.5, 0.5])
rois.append(pg.LineROI([0, 60], [20, 80], width=5, pen=(1,9)))
rois.append(pg.TriangleROI([80, 75], 20, pen=(5, 9)))
rois.append(pg.MultiRectROI([[20, 90], [50, 60], [60, 90]], width=5, pen=(2,9)))
rois.append(pg.EllipseROI([60, 10], [30, 20], pen=(3,9)))
rois.append(pg.CircleROI([80, 50], [20, 20], pen=(4,9)))
rois.append(pg.LineSegmentROI([[110, 50], [20, 20]], pen=(5,9)))
rois.append(pg.PolyLineROI([[80, 60], [90, 30], [60, 40]], pen=(6,9), closed=True))
def update(roi):
img1b.setImage(roi.getArrayRegion(arr, img1a), levels=(0, arr.max()))
v1b.autoRange()
for roi in rois:
roi.sigRegionChanged.connect(update)
v1a.addItem(roi)
update(rois[-1])
text = """User-Modifiable ROIs<br>
Click on a line segment to add a new handle.
Right click on a handle to remove.
"""
w2 = w.addLayout(row=0, col=1)
label2 = w2.addLabel(text, row=0, col=0)
v2a = w2.addViewBox(row=1, col=0, lockAspect=True)
r2a = pg.PolyLineROI([[0,0], [10,10], [10,30], [30,10]], closed=True)
v2a.addItem(r2a)
r2b = pg.PolyLineROI([[0,-20], [10,-10], [10,-30]], closed=False)
v2a.addItem(r2b)
v2a.disableAutoRange('xy')
#v2b.disableAutoRange('xy')
v2a.autoRange()
#v2b.autoRange()
text = """Building custom ROI types<Br>
ROIs can be built with a variety of different handle types<br>
that scale and rotate the roi around an arbitrary center location
"""
w3 = w.addLayout(row=1, col=0)
label3 = w3.addLabel(text, row=0, col=0)
v3 = w3.addViewBox(row=1, col=0, lockAspect=True)
r3a = pg.ROI([0,0], [10,10])
v3.addItem(r3a)
## handles scaling horizontally around center
r3a.addScaleHandle([1, 0.5], [0.5, 0.5])
r3a.addScaleHandle([0, 0.5], [0.5, 0.5])
## handles scaling vertically from opposite edge
r3a.addScaleHandle([0.5, 0], [0.5, 1])
r3a.addScaleHandle([0.5, 1], [0.5, 0])
## handles scaling both vertically and horizontally
r3a.addScaleHandle([1, 1], [0, 0])
r3a.addScaleHandle([0, 0], [1, 1])
r3b = pg.ROI([20,0], [10,10])
v3.addItem(r3b)
## handles rotating around center
r3b.addRotateHandle([1, 1], [0.5, 0.5])
r3b.addRotateHandle([0, 0], [0.5, 0.5])
## handles rotating around opposite corner
r3b.addRotateHandle([1, 0], [0, 1])
r3b.addRotateHandle([0, 1], [1, 0])
## handles rotating/scaling around center
r3b.addScaleRotateHandle([0, 0.5], [0.5, 0.5])
# handles rotating/scaling around arbitrary point
r3b.addScaleRotateHandle([0.3, 0], [0.9, 0.7])
v3.disableAutoRange('xy')
v3.autoRange()
text = """Transforming objects with ROI"""
w4 = w.addLayout(row=1, col=1)
label4 = w4.addLabel(text, row=0, col=0)
v4 = w4.addViewBox(row=1, col=0, lockAspect=True)
g = pg.GridItem()
v4.addItem(g)
r4 = pg.ROI([0,0], [100,100], resizable=False, removable=True)
r4.addRotateHandle([1,0], [0.5, 0.5])
r4.addRotateHandle([0,1], [0.5, 0.5])
img4 = pg.ImageItem(arr)
v4.addItem(r4)
img4.setParentItem(r4)
v4.disableAutoRange('xy')
v4.autoRange()
# Provide a callback to remove the ROI (and its children) when
# "remove" is selected from the context menu.
def remove():
v4.removeItem(r4)
r4.sigRemoveRequested.connect(remove)
if __name__ == '__main__':
pg.mkQApp().exec_()
| [
"45342038+Fabriciooml@users.noreply.github.com"
] | 45342038+Fabriciooml@users.noreply.github.com |
54f703e7aec4643c9a27e2009dd4269bbfb9a0ce | 10bbf25202548fc0bb30fb1d839f9a4177000109 | /Mixly0.998_WIN(7.9)/esp32Build/lib/workSpace/sdcard.py | 994bed6d09161d02847cbd928baaa4dbcb3d40bf | [] | no_license | sunnywirelss/sunnymaker-level1 | f4bdf0943682afbd38dd7fe7d50b5451da44a754 | 0550c8ffe268bdae26f4fdac4dfd55d375497a96 | refs/heads/master | 2020-05-23T12:56:26.619093 | 2019-05-15T07:20:59 | 2019-05-15T07:20:59 | 186,767,089 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,535 | py | """
MicroPython driver for SD cards using SPI bus.
Requires an SPI bus and a CS pin. Provides readblocks and writeblocks
methods so the device can be mounted as a filesystem.
Example usage on pyboard:
import pyb, sdcard, os
sd = sdcard.SDCard(pyb.SPI(1), pyb.Pin.board.X5)
pyb.mount(sd, '/sd2')
os.listdir('/')
Example usage on ESP8266:
import machine, sdcard, os
sd = sdcard.SDCard(machine.SPI(1), machine.Pin(15))
os.mount(sd, '/sd')
os.listdir('/')
"""
from micropython import const
import time
_CMD_TIMEOUT = const(100)
_R1_IDLE_STATE = const(1 << 0)
#R1_ERASE_RESET = const(1 << 1)
_R1_ILLEGAL_COMMAND = const(1 << 2)
#R1_COM_CRC_ERROR = const(1 << 3)
#R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
#R1_ADDRESS_ERROR = const(1 << 5)
#R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xfc)
_TOKEN_STOP_TRAN = const(0xfd)
_TOKEN_DATA = const(0xfe)
class SDCard:
def __init__(self, spi, cs):
self.spi = spi
self.cs = cs
self.cmdbuf = bytearray(6)
self.dummybuf = bytearray(512)
self.tokenbuf = bytearray(1)
for i in range(512):
self.dummybuf[i] = 0xff
self.dummybuf_memoryview = memoryview(self.dummybuf)
# initialise the card
self.init_card()
def init_spi(self, baudrate):
try:
master = self.spi.MASTER
except AttributeError:
# on ESP8266
self.spi.init(baudrate=baudrate, phase=0, polarity=0)
else:
# on pyboard
self.spi.init(master, baudrate=baudrate, phase=0, polarity=0)
def init_card(self):
# init CS pin
self.cs.init(self.cs.OUT, value=1)
# init SPI bus; use low data rate for initialisation
self.init_spi(100000)
# clock card at least 100 cycles with cs high
for i in range(16):
self.spi.write(b'\xff')
# CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts)
for _ in range(5):
if self.cmd(0, 0, 0x95) == _R1_IDLE_STATE:
break
else:
raise OSError("no SD card")
# CMD8: determine card version
r = self.cmd(8, 0x01aa, 0x87, 4)
if r == _R1_IDLE_STATE:
self.init_card_v2()
elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND):
self.init_card_v1()
else:
raise OSError("couldn't determine SD card version")
# get the number of sectors
# CMD9: response R2 (R1 byte + 16-byte block read)
if self.cmd(9, 0, 0, 0, False) != 0:
raise OSError("no response from SD card")
csd = bytearray(16)
self.readinto(csd)
if csd[0] & 0xc0 == 0x40: # CSD version 2.0
self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024
elif csd[0] & 0xc0 == 0x00: # CSD version 1.0 (old, <=2GB)
c_size = csd[6] & 0b11 | csd[7] << 2 | (csd[8] & 0b11000000) << 4
c_size_mult = ((csd[9] & 0b11) << 1) | csd[10] >> 7
self.sectors = (c_size + 1) * (2 ** (c_size_mult + 2))
else:
raise OSError("SD card CSD format not supported")
#print('sectors', self.sectors)
# CMD16: set block length to 512 bytes
if self.cmd(16, 512, 0) != 0:
raise OSError("can't set 512 block size")
# set to high data rate now that it's initialised
self.init_spi(1320000)
def init_card_v1(self):
for i in range(_CMD_TIMEOUT):
self.cmd(55, 0, 0)
if self.cmd(41, 0, 0) == 0:
self.cdv = 512
#print("[SDCard] v1 card")
return
raise OSError("timeout waiting for v1 card")
def init_card_v2(self):
for i in range(_CMD_TIMEOUT):
time.sleep_ms(50)
self.cmd(58, 0, 0, 4)
self.cmd(55, 0, 0)
if self.cmd(41, 0x40000000, 0) == 0:
self.cmd(58, 0, 0, 4)
self.cdv = 1
#print("[SDCard] v2 card")
return
raise OSError("timeout waiting for v2 card")
def cmd(self, cmd, arg, crc, final=0, release=True, skip1=False):
self.cs(0)
# create and send the command
buf = self.cmdbuf
buf[0] = 0x40 | cmd
buf[1] = arg >> 24
buf[2] = arg >> 16
buf[3] = arg >> 8
buf[4] = arg
buf[5] = crc
self.spi.write(buf)
if skip1:
self.spi.readinto(self.tokenbuf, 0xff)
# wait for the response (response[7] == 0)
for i in range(_CMD_TIMEOUT):
self.spi.readinto(self.tokenbuf, 0xff)
response = self.tokenbuf[0]
if not (response & 0x80):
# this could be a big-endian integer that we are getting here
for j in range(final):
self.spi.write(b'\xff')
if release:
self.cs(1)
self.spi.write(b'\xff')
return response
# timeout
self.cs(1)
self.spi.write(b'\xff')
return -1
def readinto(self, buf):
self.cs(0)
# read until start byte (0xff)
while True:
self.spi.readinto(self.tokenbuf, 0xff)
if self.tokenbuf[0] == _TOKEN_DATA:
break
# read data
mv = self.dummybuf_memoryview
if len(buf) != len(mv):
mv = mv[:len(buf)]
self.spi.write_readinto(mv, buf)
# read checksum
self.spi.write(b'\xff')
self.spi.write(b'\xff')
self.cs(1)
self.spi.write(b'\xff')
def write(self, token, buf):
self.cs(0)
# send: start of block, data, checksum
self.spi.read(1, token)
self.spi.write(buf)
self.spi.write(b'\xff')
self.spi.write(b'\xff')
# check the response
if (self.spi.read(1, 0xff)[0] & 0x1f) != 0x05:
self.cs(1)
self.spi.write(b'\xff')
return
# wait for write to finish
while self.spi.read(1, 0xff)[0] == 0:
pass
self.cs(1)
self.spi.write(b'\xff')
def write_token(self, token):
self.cs(0)
self.spi.read(1, token)
self.spi.write(b'\xff')
# wait for write to finish
while self.spi.read(1, 0xff)[0] == 0x00:
pass
self.cs(1)
self.spi.write(b'\xff')
def readblocks(self, block_num, buf):
nblocks = len(buf) // 512
assert nblocks and not len(buf) % 512, 'Buffer length is invalid'
if nblocks == 1:
# CMD17: set read address for single block
if self.cmd(17, block_num * self.cdv, 0, release=False) != 0:
# release the card
self.cs(1)
raise OSError(5) # EIO
# receive the data and release card
self.readinto(buf)
else:
# CMD18: set read address for multiple blocks
if self.cmd(18, block_num * self.cdv, 0, release=False) != 0:
# release the card
self.cs(1)
raise OSError(5) # EIO
offset = 0
mv = memoryview(buf)
while nblocks:
# receive the data and release card
self.readinto(mv[offset : offset + 512])
offset += 512
nblocks -= 1
if self.cmd(12, 0, 0xff, skip1=True):
raise OSError(5) # EIO
def writeblocks(self, block_num, buf):
nblocks, err = divmod(len(buf), 512)
assert nblocks and not err, 'Buffer length is invalid'
if nblocks == 1:
# CMD24: set write address for single block
if self.cmd(24, block_num * self.cdv, 0) != 0:
raise OSError(5) # EIO
# send the data
self.write(_TOKEN_DATA, buf)
else:
# CMD25: set write address for first block
if self.cmd(25, block_num * self.cdv, 0) != 0:
raise OSError(5) # EIO
# send the data
offset = 0
mv = memoryview(buf)
while nblocks:
self.write(_TOKEN_CMD25, mv[offset : offset + 512])
offset += 512
nblocks -= 1
self.write_token(_TOKEN_STOP_TRAN)
def ioctl(self, op, arg):
print('ioctl', op, arg)
if op == 4: # get number of blocks
return self.sectors | [
"3012156@qq.com"
] | 3012156@qq.com |
490c55ad131c7bd30c398d6e7252982230da5e41 | 80e82e68b726ab5a4519302a91af59492778d7ae | /OldStory/RealWorld/GenerateCorrectData.py | e945093eb50a23b03fe1635f6bceea8b291b24c6 | [] | no_license | TramsWang/StatisticalAnomalyDetection | d740277379280cb7c74ecdfdf7415e3873069dea | eeef6419c528db8b60cf1101769bc17e199ca0ae | refs/heads/master | 2022-03-27T07:15:14.569376 | 2019-12-09T12:34:23 | 2019-12-09T12:34:23 | 99,788,799 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 496 | py | import csv
import os
input_dir = "Old"
output_dir = "Correct"
if not os.path.exists(os.path.abspath(output_dir)):
os.makedirs(os.path.abspath(output_dir))
for i in range(325):
ifile = open("%s/%d.csv" % (input_dir, i), 'r')
ofile = open("%s/%d.csv" % (output_dir, i), 'w')
reader = csv.reader(ifile)
for row in reader:
hour = int(row[2].split(" ")[1].split(":")[0])
ofile.write("%s,%s,%d\n" % (row[0], row[1], hour))
ifile.close()
ofile.close()
| [
"babyfish92@163.com"
] | babyfish92@163.com |
2a598e63a93ed833b55c338b7cacf16e8708254b | 8e019d254b80df7a547d5a5b5096d79b68a75bc5 | /API-test/util/operation_cookie.py | f46c013ec79186f318b58d7a3b59ccc74dbef41f | [] | no_license | qiujiamin/pyprotest | 31ba39430a1b51e71439454ccaa179c8fab56afe | e8018c05c7f2c6243a34dba12e860a895e110b2b | refs/heads/master | 2020-06-25T17:02:50.074517 | 2019-07-29T03:23:23 | 2019-07-29T03:23:23 | 199,372,532 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 664 | py | #! /usr/bin/env/python
# -*- coding:utf-8 -*-
import requests
url = "http://m.imooc.com/passport/user/login"
data={
"username":"15019498582",
"password":"ssbx521qjm",
"verify":"",
"referer":"https://m.imooc.com"
}
res = requests.post(url,data).json()
response_url = res['data']['url'][0]
response_url = response_url+"&callback=jQuery210042712711583783314_1562582095923"
cookie = requests.get(response_url).cookies
# cookie = requests.utils.dict_from_cookiejar(cookie)
# print(cookie['apsid'])
url1 = "http://order.imooc.com/pay/submitorder?jsoncallback=jQuery210042712711583783314_1562582095923"
print(requests.get(url =url1,cookies =cookie).text) | [
"jiamin721@163.com"
] | jiamin721@163.com |
ef1445c1288bf27519a6da5cb0f747e4d2d35ead | 754f7519b1c2f5313f2f4a2c219179c99451f0aa | /network/migrations/0019_remove_tweet_imageurl.py | 7583ed064ad845d1f668378bf86871d6395a98b6 | [] | no_license | idoyudha/network | 3fe79f0a923de9f63d4c698c5b6e7f4896148cb3 | bba9fe1ab1a5e8dbd9cff273949c6dfbabeefeff | refs/heads/master | 2023-03-09T11:30:59.128079 | 2021-02-28T07:02:18 | 2021-02-28T07:02:18 | 338,763,254 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 325 | py | # Generated by Django 3.1.5 on 2021-02-27 15:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('network', '0018_tweet_imageurl'),
]
operations = [
migrations.RemoveField(
model_name='tweet',
name='imageURL',
),
]
| [
"idowidya.yudhatama@gmail.com"
] | idowidya.yudhatama@gmail.com |
47e1df725db295cd69be609dbdb43ecad4f21dce | 54aa2850f0ae5bee170e17f32ff74c46c6377e5a | /node_modules/ref/build/config.gypi | 50f93a3746dee067a7dd668a2b70e19ca52ff55a | [
"MIT"
] | permissive | yammigo/ElectronQQLogin | 034af4446398bb048f862dfd3bedb48ff2e0cb4e | d4f88e541d67c6cc651da8c728fa11e2a6e3cb31 | refs/heads/master | 2022-12-05T18:35:47.514345 | 2020-08-28T02:08:55 | 2020-08-28T02:08:55 | 290,927,622 | 0 | 0 | null | 2020-08-28T02:07:25 | 2020-08-28T02:07:24 | null | UTF-8 | Python | false | false | 2,435 | gypi | # Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": [],
"msbuild_toolset": "v141",
"msvs_windows_target_platform_version": "10.0.17134.0"
},
"variables": {
"asan": 0,
"coverage": "false",
"debug_devtools": "node",
"debug_http2": "false",
"debug_nghttp2": "false",
"force_dynamic_crt": 0,
"host_arch": "x64",
"icu_data_file": "icudt60l.dat",
"icu_data_in": "..\\..\\deps/icu-small\\source/data/in\\icudt60l.dat",
"icu_endianness": "l",
"icu_gyp_path": "tools/icu/icu-generic.gyp",
"icu_locales": "en,root",
"icu_path": "deps/icu-small",
"icu_small": "true",
"icu_ver_major": "60",
"node_byteorder": "little",
"node_enable_d8": "false",
"node_enable_v8_vtunejit": "false",
"node_install_npm": "true",
"node_module_version": 57,
"node_no_browser_globals": "false",
"node_prefix": "/usr/local",
"node_release_urlbase": "https://nodejs.org/download/release/",
"node_shared": "false",
"node_shared_cares": "false",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_nghttp2": "false",
"node_shared_openssl": "false",
"node_shared_zlib": "false",
"node_tag": "",
"node_use_bundled_v8": "true",
"node_use_dtrace": "false",
"node_use_etw": "true",
"node_use_lttng": "false",
"node_use_openssl": "true",
"node_use_perfctr": "true",
"node_use_v8_platform": "true",
"node_without_node_options": "false",
"openssl_fips": "",
"openssl_no_asm": 0,
"shlib_suffix": "so.57",
"target_arch": "x64",
"v8_enable_gdbjit": 0,
"v8_enable_i18n_support": 1,
"v8_enable_inspector": 1,
"v8_no_strict_aliasing": 1,
"v8_optimized_debug": 0,
"v8_promise_internal_field_count": 1,
"v8_random_seed": 0,
"v8_trace_maps": 0,
"v8_use_snapshot": "true",
"want_separate_host_toolset": 0,
"nodedir": "C:\\Users\\Starts2000\\.electron-gyp\\.node-gyp\\iojs-2.0.4",
"standalone_static_library": 1,
"msbuild_path": "d:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\MSBuild\\15.0\\Bin\\MSBuild.exe",
"target": "2.0.4",
"build_from_source": "true",
"disturl": "https://atom.io/download/electron",
"runtime": "electron"
}
}
| [
"starts_2000@qq.com"
] | starts_2000@qq.com |
44d579afa6e5e9c5333c88a3f31ec6230248c76b | b55a611912441a2cfdcfff228d1826acf4b41a1b | /Rind Ver 2.0/SE12_Visual/Creat_Line.py | f2addf5ca37d076b8242eea55265391ebe876309 | [] | no_license | AAAHQZ/2018SE_Group12 | 2439f60dc7bd6a7817f26d7bb51072664112bca2 | 07501fc4708a934a44c2d4e5fd502057322ef4b1 | refs/heads/master | 2021-06-05T18:50:22.919447 | 2020-02-27T04:52:18 | 2020-02-27T04:52:18 | 154,495,888 | 8 | 4 | null | 2019-03-07T06:29:31 | 2018-10-24T12:19:25 | Python | UTF-8 | Python | false | false | 2,820 | py | from pyecharts import Line
import sys
sys.path.append("..")
from SE12_Crawler import *
def GetData(year1, year2, year3):
year1_str=str(year1)
year2_str=str(year2)
year3_str=str(year3)
total_boxoffice1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
total_boxoffice2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
total_boxoffice3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# 读入文件
if __name__ == '__main__':
dataBase = wrappedSQL("../SE12_Data/movie.db")
else:
dataBase = wrappedSQL("./SE12_Data/movie.db")
# 从文件读取月份票房数据
for i in range(9):
dateValue = "Date like '"+year1_str+"-0"+str(i+1)+"%'"
lst1 = dataBase.SelData(Title='data', Value=dateValue)
for item in lst1:
total_boxoffice1[i] = total_boxoffice1[i] + float(item['BoxOffice'])
dateValue = "Date like '"+year2_str+"-0"+str(i+1)+"%'"
lst2 = dataBase.SelData(Title='data', Value=dateValue)
for item in lst2:
total_boxoffice2[i] = total_boxoffice2[i] + float(item['BoxOffice'])
dateValue = "Date like '"+year3_str+"-0"+str(i+1)+"%'"
lst3 = dataBase.SelData(Title='data', Value=dateValue)
for item in lst3:
total_boxoffice3[i] = total_boxoffice3[i] + float(item['BoxOffice'])
for i in range(9,12):
dateValue = "Date like '"+year1_str+"-"+str(i+1)+"%'"
lst1 = dataBase.SelData(Title='data', Value=dateValue)
for item in lst1:
total_boxoffice1[i] = total_boxoffice1[i] + float(item['BoxOffice'])
dateValue = "Date like '"+year2_str+"-"+str(i+1)+"%'"
lst2 = dataBase.SelData(Title='data', Value=dateValue)
for item in lst2:
total_boxoffice2[i] = total_boxoffice2[i] + float(item['BoxOffice'])
dateValue = "Date like '"+year3_str+"-"+str(i+1)+"%'"
lst3 = dataBase.SelData(Title='data', Value=dateValue)
for item in lst3:
total_boxoffice3[i] = total_boxoffice3[i] + float(item['BoxOffice'])
dataBase.CloseDB()
return [total_boxoffice1, total_boxoffice2, total_boxoffice3]
def DrawLine(year1, year2, year3, lst):
columns = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
line=Line("票房变化趋势",width=600,height=450)
line.add("%s" % year1, columns, lst[0], mark_point=["max","min"])
line.add("%s" % year2, columns, lst[1], mark_point=["max", "min"])
line.add("%s" % year3, columns, lst[2], mark_point=["max", "min"])
line.render("./SE12_Cache/Line.html")
return
def line(year1, year2, year3):
try:
lst = GetData(year1, year2, year3)
DrawLine(year1, year2, year3, lst)
return 1
except:
return 0
if __name__ == "__main__":
line(2016,2017,2018) | [
"huangquanzhe@126.com"
] | huangquanzhe@126.com |
02853a481890b16a00c4e706555ed16a9d1d4bf0 | d8f5f04ffb9e6748649cc6af47f4c02d30a6057e | /lib/fast_rcnn/train.py | bb283a41381e49e290818b012869d980b6caf8d9 | [] | no_license | taey16/faster_rcnn_online | 8b957a38ebf182ee91654e0a3bacfd86960b935d | 33a0e5208818a4c09a31bbf5c5ec5e2f18ac1d20 | refs/heads/master | 2020-04-05T14:07:41.777225 | 2016-05-20T05:26:13 | 2016-05-20T05:26:13 | 50,565,298 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,904 | py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Fast R-CNN network."""
import caffe
from fast_rcnn.config import cfg
from utils.timer import Timer
import numpy as np
import os
import sys
from caffe.proto import caffe_pb2
import google.protobuf as pb2
class SolverWrapper(object):
"""A simple wrapper around Caffe's solver.
This wrapper gives us control over he snapshotting process, which we
use to unnormalize the learned bounding-box regression weights.
"""
def __init__(self, solver_prototxt, loader, output_dir, pretrained_model = None):
self.output_dir = output_dir
if (cfg.TRAIN.HAS_RPN and cfg.TRAIN.BBOX_REG and
cfg.TRAIN.BBOX_NORMALIZE_TARGETS):
# RPN can only use precomputed normalization because there are no
# fixed statistics to compute a priori
assert cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED
if cfg.TRAIN.BBOX_REG:
self.bbox_means, self.bbox_stds = \
loader.get_bbox_regression_target_mean_and_std()
self.solver = caffe.SGDSolver(solver_prototxt)
if pretrained_model is not None:
print ('Loading pretrained model '
'weights from {:s}').format(pretrained_model)
#self.solver.net.copy_from(pretrained_model)
self.solver.net.copy_from(str(pretrained_model))
self.solver_param = caffe_pb2.SolverParameter()
with open(solver_prototxt, 'rt') as f:
pb2.text_format.Merge(f.read(), self.solver_param)
# add on-line data(image, roi) loader / regression target generator
# into ROIDataLayer
self.solver.net.layers[0].set_loader(loader)
sys.stdout.flush()
def snapshot(self):
"""Take a snapshot of the network after unnormalizing the learned
bounding-box regression weights. This enables easy use at test-time.
"""
net = self.solver.net
scale_bbox_params = (cfg.TRAIN.BBOX_REG and
cfg.TRAIN.BBOX_NORMALIZE_TARGETS and
net.params.has_key('bbox_pred'))
if scale_bbox_params:
# save original values
orig_0 = net.params['bbox_pred'][0].data.copy()
orig_1 = net.params['bbox_pred'][1].data.copy()
# scale and shift with bbox reg unnormalization; then save snapshot
#import pdb; pdb.set_trace()
net.params['bbox_pred'][0].data[...] = \
(net.params['bbox_pred'][0].data *
self.bbox_stds[:, np.newaxis])
net.params['bbox_pred'][1].data[...] = \
(net.params['bbox_pred'][1].data *
self.bbox_stds + self.bbox_means)
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
infix = ('_' + cfg.TRAIN.SNAPSHOT_INFIX
if cfg.TRAIN.SNAPSHOT_INFIX != '' else '')
filename = (self.solver_param.snapshot_prefix + infix +
'_iter_{:d}'.format(self.solver.iter) + '.caffemodel')
filename = os.path.join(self.output_dir, filename)
net.save(str(filename))
print 'Wrote snapshot to: {:s}'.format(filename)
sys.stdout.flush()
if scale_bbox_params:
# restore net to original state
net.params['bbox_pred'][0].data[...] = orig_0
net.params['bbox_pred'][1].data[...] = orig_1
return filename
def train_model(self, max_iters):
"""Network training loop."""
last_snapshot_iter = -1
timer = Timer()
model_paths = []
while self.solver.iter < max_iters:
# Make one SGD update
timer.tic()
self.solver.step(1)
timer.toc()
"""
if self.solver.iter % (10 * self.solver_param.display) == 0:
print 'speed: {:.3f}s / iter'.format(timer.average_time)
sys.stdout.flush()
"""
if self.solver.iter % cfg.TRAIN.SNAPSHOT_ITERS == 0:
last_snapshot_iter = self.solver.iter
model_paths.append(self.snapshot())
if last_snapshot_iter != self.solver.iter:
model_paths.append(self.snapshot())
return model_paths
def train_net(solver_prototxt, loader, output_dir,
pretrained_model=None, max_iters=10000000):
sw = SolverWrapper(solver_prototxt, loader, output_dir,
pretrained_model=pretrained_model)
print 'Solving...'; sys.stdout.flush()
model_paths = sw.train_model(max_iters)
print 'done'; sys.stdout.flush()
return model_paths
| [
"taey1600@gmail.com"
] | taey1600@gmail.com |
7dad892ddde8e941fd9311f9a56d7fa4e01acfc6 | 29b7ffefd538dd37bd047697f51c42c3e639492e | /blog/migrations/0001_initial.py | a8a40beb0803d381aabdad9db51d8e87564da0e8 | [] | no_license | 9groove9/myblog-project | 89f2b739fd3a440b4bc689609db19e4f1c534ba0 | 6ffc6a6f93a5121fb360b6639739732471114a6d | refs/heads/main | 2023-03-07T13:37:16.026202 | 2021-02-19T20:59:13 | 2021-02-19T20:59:13 | 340,437,494 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 673 | py | # Generated by Django 3.1.6 on 2021-02-19 20:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('post_title', models.CharField(max_length=100)),
('post_date', models.DateTimeField()),
('post_text', models.TextField()),
('post_image', models.ImageField(upload_to='post_images/')),
],
),
]
| [
"ztmpythonlearn@gmail.com"
] | ztmpythonlearn@gmail.com |
20038231742d8091d0fee588d16f9075d9b1651a | 7e516f4871cc06d9ceef6d373717667cde46c3b9 | /stubs/uasyncio/stream.py | 2e64de44ec58dc689882bd1804e15b6cbb871c12 | [
"MIT",
"Apache-2.0"
] | permissive | esbullington/cct | 1b39fbfbade97d5ff5346f3037e824c1dc851acd | 1a89d346c76236a9710177a208730584ecb65c02 | refs/heads/master | 2023-03-08T19:15:14.228556 | 2021-02-25T18:27:00 | 2021-02-25T18:27:00 | 330,801,755 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,388 | py | """
Module: 'uasyncio.stream' on micropython-esp32-1.13-274
"""
# MCU: {'ver': '1.13-274', 'port': 'esp32', 'arch': 'xtensawin', 'sysname': 'esp32', 'release': '1.13.0', 'name': 'micropython', 'mpy': 10757, 'version': '1.13.0', 'machine': 'ESP32 module with ESP32', 'build': '274', 'nodename': 'esp32', 'platform': 'esp32', 'family': 'micropython'}
# Stubber: 1.3.9
class Server:
''
_serve = None
def close():
pass
wait_closed = None
class Stream:
''
aclose = None
awrite = None
awritestr = None
def close():
pass
drain = None
def get_extra_info():
pass
read = None
readexactly = None
readline = None
wait_closed = None
def write():
pass
class StreamReader:
''
aclose = None
awrite = None
awritestr = None
def close():
pass
drain = None
def get_extra_info():
pass
read = None
readexactly = None
readline = None
wait_closed = None
def write():
pass
class StreamWriter:
''
aclose = None
awrite = None
awritestr = None
def close():
pass
drain = None
def get_extra_info():
pass
read = None
readexactly = None
readline = None
wait_closed = None
def write():
pass
core = None
open_connection = None
start_server = None
stream_awrite = None
| [
"eric.s.bullington@gmail.com"
] | eric.s.bullington@gmail.com |
4d31ad17b19df8ec73078f9c78f0d6f23f72b237 | 53ad8ad31c68536d25ceb98407d036bcf0536bec | /blog_project/venv/Scripts/easy_install-3.6-script.py | 4ed5e1089eac800ee285e12abd919d0370b42ed4 | [] | no_license | huolang1211/blog | a60c4c1fe8ac355155090aab06dbc407a4bd98bd | 2a09612e9c2d8322007fa312fb46b49f6646e9c2 | refs/heads/master | 2023-01-14T17:30:23.035174 | 2020-11-24T02:28:55 | 2020-11-24T02:28:55 | 315,465,008 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 444 | py | #!D:\untitled\blog_project\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install-3.6'
__requires__ = 'setuptools==39.1.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==39.1.0', 'console_scripts', 'easy_install-3.6')()
)
| [
"873049788@qq.com"
] | 873049788@qq.com |
6e933fb4c9a2ab94098a49f7970a2c8dde5794e2 | a916fc848c60de59c04ba39e6ad682ba49225c27 | /shop/settings.py | 5be881fa498f0ab29afa5dd0dd2cc0a9a2b1a723 | [] | no_license | Insake/osteriax | 881a1f7ed18d3b6f9f0073ec6092c08ed34ef27b | 31212897f1a72f9387ca5eecd2138ba1d0596435 | refs/heads/master | 2023-04-18T08:35:54.140666 | 2021-05-04T15:19:16 | 2021-05-04T15:19:16 | 364,255,554 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,380 | py | """
Django settings for shop project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-kw3@yquao8s^u1tz3+=zhrtq4e$+*!fla1+1(0t%uqvue65d^*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'shop.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'shop.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Bishkek'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# STATICFILES_DIRS = (
# os.path.join(BASE_DIR, 'static'),
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| [
"Insanbeksake@gmail.com"
] | Insanbeksake@gmail.com |
0f6d571215af68b5ffd6da4577d3a0961e7df0a3 | b6563a1c13c86d554f71389a6fe3e7fde3fc3b8a | /Wmass_direct_measurement_365GeV/Wmass2.py | 91ce9d9abc4f190cb1d85c0573b5da310b3de5f3 | [] | no_license | sofiane-lablack/Stage_M2_GitHub_test | 45092ec42153dd47d6820a64c672b6bac72aa675 | 7d4d24b251dd99b3aef24beaa5f94366277bcc97 | refs/heads/master | 2021-04-15T02:36:46.472308 | 2020-03-22T22:53:28 | 2020-03-22T22:53:28 | 249,287,765 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,936 | py | ''' Measurement of the W mass from the ee->WW decay from the direct reconstruction of the invariant
masses.
First step : compute the jets energy from the directions
Second step : find the jet pairs (chi2 minimization)
Third step : reconstructed invariant mass distribution and angle distribution
Save everything in root file'''
import sys
from ROOT import TFile, TH1F, TCanvas, gPad, TLegend, TH2F, gDirectory, TF1, TLorentzVector
import tools.histogram as histogram
from energy.energy import energy_from_direction, get_beta_matrix
import energy.rescaling_factors as rescaling_factors
from tools.tree_info import TreeInfo
from particles.jets import Jet
from particles.particle import Particle
from particles.dijets import Dijet
from pairing.dijetsPairs import DijetsPairs
from pairing.BestPair import BestPair
def gethists():
"""function to book all histograms and return as dictionary"""
histdict = {}
dijet = ['1', '2']
histdict["h_mass_sum"] = TH1F('h_mass_sum', 'Sum of computed mW', 120, 40, 120)
histdict["h_mass"] = TH1F('h_mass', 'Both computed mW', 120, 40, 120)
histdict["h_mass_true"] = TH1F('h_mass_true', 'Comparison between reconstructed mass and Mtrue', 200, -15, 15)
histdict["h_diffmW1_mW2"] = TH1F('h_|mw1-mw2|','Difference masse des 2 W',125,-5,120)
for djet in dijet:
histdict["h_angle_pair{}".format(djet)] = TH1F('h_angle_pair{}'.format(djet), 'Opening angle {}'.format(djet), 180, 0, 180)
histdict["h_mW{}".format(djet)] = TH1F('h_mW{}'.format(djet), 'mW {} dijet selected'.format(djet), 140, 20, 120)
histdict["h_mW{}_true".format(djet)] = TH1F("h_mW{}_true".format(djet), 'Comparison between reconstructed mass and Mtrue', 200, -15, 15)
histdict["h_mW1_mW2"] = TH2F('h_mW1_mW2', 'Larger mass versus Smaller', 120, 40, 120, 120, 40, 120)
return histdict
def check_content(tree):
'''If one jet is containing only photons -> Discarded'''
good_compo = True
compo_j1 = tree.get_jet_compo("jet1")
compo_j2 = tree.get_jet_compo("jet2")
compo_j3 = tree.get_jet_compo("jet3")
compo_j4 = tree.get_jet_compo("jet4")
# print compo_j1
result_j1 = [value for key, value in compo_j1.items() if key not in "22"]
result_j2 = [value for key, value in compo_j2.items() if key not in "22"]
result_j3 = [value for key, value in compo_j3.items() if key not in "22"]
result_j4 = [value for key, value in compo_j4.items() if key not in "22"]
# print 'result_j1 = ', result_j1
if all([v == 0 for v in result_j1]) or all([v == 0 for v in result_j2]\
or all([v == 0 for v in result_j3]) or all([v == 0 for v in result_j4])):
good_compo = False
return good_compo
def w_mass_hadronic(tree, ecm, m_w, histdict, reconstruction, reco_level, reco_type=''):
'''Run over the hadronic events and save the histograms'''
from_tree = TreeInfo()
sign={}
#eeqq
bkg1={}
#ZZqqll
bkg2={}
#ZZqqqq
bkg3={}
#WWqqll
bkg4={}
purete=[]
efficacite=[]
x=[]
#cut y34
# for i in range(0,101):
# j=i*0.001
# x.append(j)
# print x
# for index, value in enumerate(x):
# print value
#cut ejetcut
# for i in range(0,2):
# j=i*0.001
# x.append(j)
# print x
# print len(x)
#boucle sur les valeurs de cut
for iev, evt in enumerate(tree):
if iev%5000 == 0:
print("Processing events {} on {} ".format(iev, tree.GetEntries()))
# Object from_tree to access the rootfile information
from_tree.set_evt(evt, reco_level, reco_type)
# Discard event where one jet is containing only photons and/or no clustered particles
if from_tree.get_dim("jet") != 4:
continue
if not check_content(from_tree):
continue
#cut masses "similaires" des 2 W
#if abs(m_large-m_small)<13:
# continue
# cut y34
if from_tree.get_y34()<=0.001:
continue
#cut energy part chargees < 0.96 * energy jet
energyjet1 = from_tree.get_reco_jet1_e()
energyjet2 = from_tree.get_reco_jet2_e()
energyjet3 = from_tree.get_reco_jet3_e()
energyjet4 = from_tree.get_reco_jet4_e()
# partchargees=['11','13','211']
energypartchargeesjet1= from_tree.get_reco_jet1_11_e()+from_tree.get_reco_jet1_13_e()+from_tree.get_reco_jet1_211_e()
energypartchargeesjet2= from_tree.get_reco_jet2_11_e()+from_tree.get_reco_jet2_13_e()+from_tree.get_reco_jet2_211_e()
energypartchargeesjet3= from_tree.get_reco_jet3_11_e()+from_tree.get_reco_jet3_13_e()+from_tree.get_reco_jet3_211_e()
energypartchargeesjet4= from_tree.get_reco_jet4_11_e()+from_tree.get_reco_jet4_13_e()+from_tree.get_reco_jet4_211_e()
if energypartchargeesjet1 > 0.996 * energyjet1 or energypartchargeesjet2 > 0.996 * energyjet2 or energypartchargeesjet3 > 0.996 * energyjet3 or energypartchargeesjet4 > 0.996 * energyjet4:
continue
# Jets
pvec = []
for part in range(4):
njet = str("jet" + str(part + 1))
pvec.append(from_tree.get_p4(njet))
jets = [Jet() for i in range(from_tree.get_dim("jet"))]
# Direct reconstruction
if reconstruction == "direct":
for jid, jet in enumerate(jets):
jet.set_id(str("jet" + str(jid + 1)))
jet.set_mref(m_w)
jet.set_p4(pvec[jid])
# Energy Rescaling
else:
beta = get_beta_matrix(pvec)
energy = energy_from_direction(ecm, beta, from_tree.get_dim("jet"))
# discarded events with energy < 0 solutions (no physics)
if any(energy < 0):
continue
# Need to rescale the p4 matrix
p4_resc = rescaling_factors.rescale(pvec, rescaling_factors.factor(energy, pvec))
for jid, jet in enumerate(jets):
jet.set_id(str("jet" + str(jid + 1)))
jet.set_mref(m_w)
jet.set_p4(p4_resc[jid])
dijet = get_dijets_pairs(jets)
# If the pairing conditions are not full
if not dijet:
continue
#cut energie dijets similaires
diffedjets = return_edijets(dijet)
if diffedjets>=30:
continue
openingangledj1, openingangledj2 = return_opening_angle(dijet)
#if openingangledj1 <= 80 or openingangledj2 <= 80:
# continue
m_small, m_large = return_mass(dijet)
#cut sur la masse de mW2
#if m_large<=65 or m_small<40:
# continue
#fonction qui rempli les histos
fill_histograms(dijet, histdict)
#print Nbck
#file1.write(str(value)+' '+str(Nbck)+'\n')
def get_dijets_pairs(jets):
'''Find the jets pairing'''
# Dijets : compute the masses and the jet-jet angles
dijet12 = Dijet(jets[0], jets[1])
dijet34 = Dijet(jets[2], jets[3])
dijet13 = Dijet(jets[0], jets[2])
dijet24 = Dijet(jets[1], jets[3])
dijet14 = Dijet(jets[0], jets[3])
dijet23 = Dijet(jets[1], jets[2])
# Dijets pairs : compute the chi and the sum angles
dj_pair1 = DijetsPairs(dijet12, dijet34)
dj_pair2 = DijetsPairs(dijet13, dijet24)
dj_pair3 = DijetsPairs(dijet14, dijet23)
best_pair = BestPair(dj_pair1, dj_pair2, dj_pair3)
dijet_pair = best_pair.get_best_pair()
# if the pairing never satisfy the conditions -> discarded event
if dijet_pair == 0:
return 0
dijet_pair.compute()
return dijet_pair
def return_edijets(dijets):
dj_1 = dijets.get_dijet1()
dj_2 = dijets.get_dijet2()
dj1jet1 , dj1jet2 = dj_1.get_jets()
dj2jet1 , dj2jet2 = dj_2.get_jets()
energydj1jet1 = dj1jet1.get_E()
energydj1jet2 = dj1jet2.get_E()
energydj2jet1 = dj2jet1.get_E()
energydj2jet2 = dj2jet2.get_E()
energydj1 = energydj1jet1+energydj1jet2
energydj2 = energydj2jet1+energydj2jet2
diffedj = abs(energydj1-energydj2)
return diffedj
def return_opening_angle(dijets):
dj_1 = dijets.get_dijet1()
dj_2 = dijets.get_dijet2()
dj_1_angle = dj_1.get_angle()
dj_2_angle = dj_2.get_angle()
return dj_1_angle, dj_2_angle
def return_mass(dijets):
dj_1 = dijets.get_dijet1()
dj_2 = dijets.get_dijet2()
m_small = min(dj_1.get_mass(), dj_2.get_mass())
m_large = max(dj_1.get_mass(), dj_2.get_mass())
return m_small, m_large
def fill_histograms(dijets, histdict):
'''Function to fill all histograms'''
m_small, m_large = return_mass(dijets)
dj_1 = dijets.get_dijet1()
dj_2 = dijets.get_dijet2()
# histdict["h_diffmW1_mW2"].Fill(abs(m_large-m_small))
histdict["h_mW1"].Fill(m_small)
histdict["h_mW2"].Fill(m_large)
histdict["h_mass_sum"].Fill((m_small + m_large)/2)
histdict["h_mass"].Fill(m_small)
histdict["h_mass"].Fill(m_large)
#angular distribution between selected jets
a_small = min(dj_1.get_angle(), dj_2.get_angle())
a_large = max(dj_1.get_angle(), dj_2.get_angle())
histdict["h_angle_pair1"].Fill(a_small)
histdict["h_angle_pair2"].Fill(a_large)
def main():
'''Main function which can run the hadronic and the semi-leptonic decay. The study is selected
at the beginning with the parameters. Nothing should be changed in the function'''
#input and output file from runWmass.sh
fileinput2 = sys.argv[1]
fileoutput2 = sys.argv[2]
# parameters to choose the study
ecm = 162.6
m_w = 79.385
width = '2'
reconstruction = "direct"
reco_level = 'reco'
# NO NEED
reco_type = ''
FSI = 'BE'
# Analysis
histdict = gethists()
filename = fileinput2
print("Reading from file {}".format(filename))
rootfile = TFile(filename)
tree = rootfile.Get("events")
# output file
outdir = fileoutput2
print("Reading from file {} output file {}".format(filename,outdir))
# outdir = "./output/hadronic/FSI_study/shift/woTreatment/W_mass_{}_M{}_width{}".format(ecm, str(m_w)[:2], width)
# Function call
w_mass_hadronic(tree, ecm, m_w, histdict, reconstruction, reco_level, reco_type)
histogram.save_root_file(histdict, outdir)
if __name__ == '__main__':
main()
| [
"lablack.sofiane@hotmail.fr"
] | lablack.sofiane@hotmail.fr |
c59f4764cbfb8fbf791c758771b944e89cd8880f | 93dd86c8d0eceaee8276a5cafe8c0bfee2a315d3 | /python/paddle/distributed/fleet/runtime/runtime_base.py | 2e8bacfbc3b1ded58e63e8d9e93764a0c0090b91 | [
"Apache-2.0"
] | permissive | hutuxian/Paddle | f8b7693bccc6d56887164c1de0b6f6e91cffaae8 | a1b640bc66a5cc9583de503e7406aeba67565e8d | refs/heads/develop | 2023-08-29T19:36:45.382455 | 2020-09-09T09:19:07 | 2020-09-09T09:19:07 | 164,977,763 | 8 | 27 | Apache-2.0 | 2023-06-16T09:47:39 | 2019-01-10T02:50:31 | Python | UTF-8 | Python | false | false | 1,078 | py | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = []
class RuntimeBase(object):
def __init__(self):
pass
def _set_basic_info(self, context):
self.context = context
def _run_worker(self):
pass
def _init_server(self, *args, **kwargs):
pass
def _run_server(self):
pass
def _stop_worker(self):
pass
def _save_inference_model(self, *args, **kwargs):
pass
def _save_persistables(self, *args, **kwargs):
pass
| [
"noreply@github.com"
] | noreply@github.com |
4bd162536807c2b7995e0d578c83d3583163fbd6 | 6dd98781c61c3e5022beeb144daec2499a8f79ac | /scraper.py | 85d76c39e3df7a3466639af26568b2683a4927cd | [] | no_license | konelson/konelson-mta-project | 9c3a3586b7568fe672b96d9ff4c9e721fa0837ee | 47f1703fa0e4ff1c89cccab17eaf14cf431a0e86 | refs/heads/master | 2020-03-22T10:28:36.344761 | 2018-07-09T20:17:17 | 2018-07-09T20:17:17 | 139,905,252 | 0 | 1 | null | 2018-07-09T13:43:45 | 2018-07-05T22:07:56 | Jupyter Notebook | UTF-8 | Python | false | false | 607 | py | from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as bs4
# settings to initialize BeautifulSoup and open the website
site = 'http://startupguide.nyc/'
header = {'User-Agent': 'Mozilla/5.0'}
req = Request(site,headers = header)
page = urlopen(req)
# read the site and store all 'a' tags
soup = bs4(page, 'html.parser')
name_box = soup.find_all('a', target="_blank")
# function to write to file
def write_to_file(data):
with open('businesses.txt', 'a') as file:
file.write(data)
file.write('\n')
# we want first 116
for link in name_box:
write_to_file(link.get('href')) | [
"34700646+konelson@users.noreply.github.com"
] | 34700646+konelson@users.noreply.github.com |
9f150c61f67ff82f73226339ca249facc4a5b0e0 | a41a6fc6e3a48595b038b9b034ded147f4f8802a | /Python/OOP/DECORATORS/0.Even Parameters.py | 7ae7b86624c2a992cc2c2783be03054bca8374e6 | [] | no_license | SveetH/SoftUni | 329b0b6e40b9fb768b676262b89b1dcfcc908779 | fa7d2f0b1c13e9b8460b6c7137b9ee8751a76003 | refs/heads/main | 2023-07-09T19:07:02.314828 | 2021-08-23T13:30:07 | 2021-08-23T13:30:07 | 317,777,415 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 551 | py | def even_parameters(function):
def wrapper(*args):
for el in args:
if type(el) == int and el % 2 == 0:
continue
return "Please use only even numbers!"
return function(*args)
return wrapper
@even_parameters
def add(a, b):
return a + b
print(add(2, 4))
print(add("Peter", 1))
@even_parameters
def multiply(*nums):
result = 1
for num in nums:
result *= num
return result
print(multiply(2, 4, 6, 8))
print(multiply(2, 4, 9, 8))
| [
"noreply@github.com"
] | noreply@github.com |
ba177bad4f52ef36d45773777f5de56fa4add723 | 99ca7d7c1124c07b02879f807137ebaae708563a | /BasicAssignemnt/PracticeExamples.py | 757eacfc215b8994f5c6eeacb140c4d7c2ed6464 | [] | no_license | SShital/PythonAssignments | 2f5706deb4b352a9ea4ea56c5d499e50d6a92375 | 4c09e0b9f9618fdcc32750cf514df7fb983fdd77 | refs/heads/master | 2020-04-19T10:36:39.492874 | 2019-02-01T12:06:33 | 2019-02-01T12:06:33 | 168,145,188 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,676 | py | """
#Basic list
------------------------------------------------
my_list=[] #empty list
my_list1 = [1, 2, 3]
print my_list1
my_list2 = ["Hello", 1,4, "hiiii"]
print my_list2
--------------------------------
#***Nested list*****
--------------------------------------------
my_list3 = ["mouse", [8, 4, 6], ['a']]
my_list4 = [["cat","dog"], [8, 4, 6], ['a']]
print (my_list4[0][1])
print my_list4[1][0], my_list4[2]
---------------------------------------------------
#Negative index
------------------------------------------------
my_list5 = ['p', 'r', 'o', 'b', 'e']
print my_list5[-1]
print my_list5[-4]
-------------------------------
#Slicing list
my_list6 = ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
print my_list6[2:8] , my_list6[-4:-1], my_list6[:4], my_list6[:-1]
print my_list6[:]
#adding elements to the lists
odd = [1,2,3,4]
odd[0] = 5
print odd
odd[1:3] = [11, 12, 13]
print odd
#append and extend
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd.extend([9, 11, 13])
print(odd)
my_words=['s', 'h', 'i', 't','a','l']
my_words.extend("raut")
print my_words
odd = [1, 3, 5]
#Concatination
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
#Output: ["re", "re", "re"]
print "**" * 3
#delete or remove elements from a list
my_list7 = ['p','r','o','b','l','e','m']
del my_list7[0]
print my_list7
del my_list7[1:4]
print my_list7
#remove & pop operations:
my_list8 = ['p','r','o','b','l','e','m']
my_list8.remove('p')
print(my_list8)
# Output: 'o'
print(my_list8.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list8)
# Output: 'm'
print(my_list8.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list8)
#List Comprehension
pow2 = [2 ** x for x in range(10)]
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
pow3 =[]
for x in range(10):
pow2.append(2**x)
Even = sorted([x for x in range(20) if x % 2 == 0] , reverse=True)
print Even
#iterating through list
for fruit in ['apple','banana','mango']:
print("I like",fruit)
"""
#Handson on slicing
"""
a=[1,2,3,4,5,6,7,8,9]
print(a[::2])
a2=[1,2,3,4,5,6,7,8,9]
a2[::2]=10,20,30,40,50,60
print a2;
#error:ValueError: attempt to assign sequence of size 6 to extended slice of size 5
***************************8
a=[1,2,3,4,5]
print(a[3:0:-1])
*******************888
****************88888
def f(value, values):
v = 1
values[0] = 44
t = 3
v = [1, 2, 3]
f(t, v)
print(t, v[0])
**********************
-----------------------------------------------------------
arr = [[1, 2, 3, 4],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]]
for i in range(0, 4):
print(arr[i].pop())
# returns last index
-------------------------------------------
"""
| [
"shital.raut@harbingergroup.com"
] | shital.raut@harbingergroup.com |
a59798cc8945d4ce49e7159d0a1b836f68f13dc0 | 381cb785bde3cd261a1b6537c9330b2c02603ace | /Code/ppo-modularized/common.py | b2e205dcfb3bd4da6b9c57617b5222b5e9eb11cd | [] | no_license | LevineZhou/Deep-Reinforcement-Learning-DRL- | 07ec0d32d9fc4fb2cffd74c2a3ff9c05250b5b65 | 2f733862f344a5f1c186b1925cdd760d8c4587df | refs/heads/master | 2021-04-03T01:51:33.876810 | 2018-10-12T22:54:54 | 2018-10-12T22:54:54 | 124,354,233 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,222 | py | ## common utilities for deep reinforcement learning
import numpy as np
import torch
import time
from torch.distributions import Normal
from torch import Tensor
def get_reward_to_go(rewards:list, mask_n, gamma:float):
"""
Get reward to go for each timestep. Assume the rewards given are within one trajectory.
If you have multiple trajectories, call this function for each trajectory separately.
:param rewards: reward at each time step,
:param gamma: the discount factor gamma
:return: a list, at index t: the discounted reward-to-go q(s_t,a_t)
"""
T = len(rewards)
q = 0
q_n = []
for t in range(T-1,-1,-1): ## use a reverse for loop to reduce computation
q = rewards[t] + gamma*q * mask_n[t]
q_n.append(q)
q_n.reverse() ## need to call reverse
return q_n
def get_gae_advantage(rewards, values, mask_n, gamma, lam):
## i thnk this is gae advantage
tensor_type = type(rewards)
deltas = tensor_type(rewards.size(0), 1)
advantages = tensor_type(rewards.size(0), 1)
value_next_state = 0 ## value estimated from a value network, from t+1 timestep
adv_next_state = 0 ## advantage at time t+1
## final state's mask is 0, so final state's
for t in reversed(range(rewards.size(0))):
## here prev value means value of last iteration in this for loop
deltas[t] = rewards[t] + gamma * value_next_state * mask_n[t] - values[t]
advantages[t] = deltas[t] + gamma * lam * adv_next_state * mask_n[t]
value_next_state = values[t, 0]
adv_next_state = advantages[t, 0]
## values are the value network estimates, same as used in openai baseline implementation
value_net_target = values + advantages
## normalize advantage
advantages = (advantages - advantages.mean()) / advantages.std()
return advantages, value_net_target
def get_trajectories(env, policy_model, n_episode, episode_length):
"""
## get some trajectories (data)
:return: return a list of paths, and the average episode return
"""
paths = []
epoch_return = 0
episode_count = 0
for i_episode in range(n_episode):
episode_return = 0
episode_count += 1
obs_list = []
log_prob_list = []
action_list = []
reward_list = []
mask_list = []
observation = env.reset()
for t in range(episode_length):
# env.render()
obs_list.append(observation)
obs_tensor = torch.Tensor(observation).view(1,-1)
mu, log_sigma = policy_model(obs_tensor)
normal_dist = Normal(mu,log_sigma.exp())
action = normal_dist.sample()
action_list.append(action.reshape(-1))
## the log prob here is the log prob of taking the set of actions, so we take sum of log
## you can also take product of exp of log to get same results
log_prob = normal_dist.log_prob(action)
log_prob = torch.sum(log_prob)
log_prob_list.append(log_prob)
## make sure action is within env's specifics
action = torch.clamp(action, -1, 1).reshape(-1)
observation, reward, done, info = env.step(action.data.numpy())
if done:
mask_list.append(0) ## used in calculating advantage
else:
mask_list.append(1)
episode_return += reward
reward_list.append(reward)
if done:
break
epoch_return += episode_return
## now we have finished one episode, we now assign reward (all the data points in
## the same trajectory have the same reward)
path = {'obs':obs_list,'mask':mask_list, 'log_probs':log_prob_list, 'rewards':reward_list,'actions':action_list,'episode_return':episode_return}
paths.append(path)
return paths, epoch_return/n_episode
def get_tensors_from_paths(paths):
"""
given trajectories, this function helps you get everything into nxd tensor form, n is number of data point
you can also easily extract data using your own functions
:param paths:
:return:
"""
obs_n = []
log_prob_n = []
action_n = []
rewards_n = []
mask_n = []
for path in paths:
obs_n += path['obs']
log_prob_n += path['log_probs']
action_n += path['actions']
rewards_n += path['rewards']
mask_n += path['mask']
## convert each type of data into usable form
obs_n_tensor = Tensor(np.vstack(obs_n))
n_data = obs_n_tensor.shape[0]
## action probability of old policy
log_prob_n_old_tensor = torch.stack(log_prob_n).reshape(n_data,-1).detach()
action_n_tensor = torch.stack(action_n).detach()
rewards_n = Tensor(rewards_n).reshape(n_data,-1)
mask_n = Tensor(mask_n).reshape(n_data,-1)
return n_data, obs_n_tensor, log_prob_n_old_tensor, action_n_tensor, rewards_n, mask_n
#
# r = torch.Tensor([1,1,1,0]).reshape(-1,1)
# vst = torch.Tensor([2,2,2,0]).reshape(-1,1)
# vstn = torch.Tensor([3,3,3,0]).reshape(-1,1)
# gamma = 0.9
# lam = 0.9
#
# results = get_gae_advantage(r,vst,vstn,gamma,lam)
#
# print(results)
#
#
# def estimate_advantages(rewards, values, gamma, tau):
# ## i thnk this is gae advantage
# tensor_type = type(rewards)
# deltas = tensor_type(rewards.size(0), 1)
# advantages = tensor_type(rewards.size(0), 1)
#
# prev_value = 0
# prev_advantage = 0
# ## final state's mask is 0, so final state's
# for i in reversed(range(rewards.size(0))):
# ## here prev value means value of last iteration in this for loop
# deltas[i] = rewards[i] + gamma * prev_value * 1 - values[i]
# advantages[i] = deltas[i] + gamma * tau * prev_advantage * 1
#
# prev_value = values[i, 0]
# prev_advantage = advantages[i, 0]
# print('d2',deltas)
#
# ## values are the value network estimates, same as used in openai baseline implementation
# returns = values + advantages
# ## normalize advantage
# # advantages = (advantages - advantages.mean()) / advantages.std()
#
# return advantages
#
# results, _ = estimate_advantages(r, vst,gamma,lam)
# print(results) | [
"noreply@github.com"
] | noreply@github.com |
98e4d8bc25567926017f664b32295fec1b5026f4 | ef6229d281edecbea3faad37830cb1d452d03e5b | /ucsmsdk/mometa/storage/StorageLocalDiskConfigDef.py | d35bd2a160c55172b79f7ccacdd315218f552866 | [
"Apache-2.0"
] | permissive | anoop1984/python_sdk | 0809be78de32350acc40701d6207631322851010 | c4a226bad5e10ad233eda62bc8f6d66a5a82b651 | refs/heads/master | 2020-12-31T00:18:57.415950 | 2016-04-26T17:39:38 | 2016-04-26T17:39:38 | 57,148,449 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,393 | py | """This module contains the general information for StorageLocalDiskConfigDef ManagedObject."""
import sys, os
from ...ucsmo import ManagedObject
from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class StorageLocalDiskConfigDefConsts():
FLEX_FLASH_RAIDREPORTING_STATE_DISABLE = "disable"
FLEX_FLASH_RAIDREPORTING_STATE_ENABLE = "enable"
FLEX_FLASH_STATE_DISABLE = "disable"
FLEX_FLASH_STATE_ENABLE = "enable"
INT_ID_NONE = "none"
MODE_ANY_CONFIGURATION = "any-configuration"
MODE_BEST_EFFORT_MIRRORED = "best-effort-mirrored"
MODE_BEST_EFFORT_MIRRORED_STRIPED = "best-effort-mirrored-striped"
MODE_BEST_EFFORT_STRIPED = "best-effort-striped"
MODE_BEST_EFFORT_STRIPED_DUAL_PARITY = "best-effort-striped-dual-parity"
MODE_BEST_EFFORT_STRIPED_PARITY = "best-effort-striped-parity"
MODE_DUAL_DISK = "dual-disk"
MODE_NO_LOCAL_STORAGE = "no-local-storage"
MODE_NO_RAID = "no-raid"
MODE_RAID_MIRRORED = "raid-mirrored"
MODE_RAID_MIRRORED_STRIPED = "raid-mirrored-striped"
MODE_RAID_STRIPED = "raid-striped"
MODE_RAID_STRIPED_DUAL_PARITY = "raid-striped-dual-parity"
MODE_RAID_STRIPED_DUAL_PARITY_STRIPED = "raid-striped-dual-parity-striped"
MODE_RAID_STRIPED_PARITY = "raid-striped-parity"
MODE_RAID_STRIPED_PARITY_STRIPED = "raid-striped-parity-striped"
MODE_SINGLE_DISK = "single-disk"
POLICY_OWNER_LOCAL = "local"
POLICY_OWNER_PENDING_POLICY = "pending-policy"
POLICY_OWNER_POLICY = "policy"
PROTECT_CONFIG_FALSE = "false"
PROTECT_CONFIG_NO = "no"
PROTECT_CONFIG_TRUE = "true"
PROTECT_CONFIG_YES = "yes"
class StorageLocalDiskConfigDef(ManagedObject):
"""This is StorageLocalDiskConfigDef class."""
consts = StorageLocalDiskConfigDefConsts()
naming_props = set([])
mo_meta = MoMeta("StorageLocalDiskConfigDef", "storageLocalDiskConfigDef", "local-disk-config", VersionMeta.Version101e, "InputOutput", 0xfff, [], ["admin", "ls-compute", "ls-config", "ls-config-policy", "ls-server", "ls-storage", "ls-storage-policy"], [u'lsServer', u'lstorageDasScsiLun', u'storageController', u'storageFlexFlashController'], [u'storageLocalDiskPartition'], ["Add", "Get", "Remove", "Set"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version101e, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"descr": MoPropertyMeta("descr", "descr", "string", VersionMeta.Version101e, MoPropertyMeta.READ_WRITE, 0x4, None, None, r"""[ !#$%&\(\)\*\+,\-\./:;\?@\[\]_\{\|\}~a-zA-Z0-9]{0,256}""", [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version101e, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []),
"flex_flash_raid_reporting_state": MoPropertyMeta("flex_flash_raid_reporting_state", "flexFlashRAIDReportingState", "string", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, ["disable", "enable"], []),
"flex_flash_state": MoPropertyMeta("flex_flash_state", "flexFlashState", "string", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x20, None, None, None, ["disable", "enable"], []),
"int_id": MoPropertyMeta("int_id", "intId", "string", VersionMeta.Version101e, MoPropertyMeta.INTERNAL, None, None, None, None, ["none"], ["0-4294967295"]),
"mode": MoPropertyMeta("mode", "mode", "string", VersionMeta.Version101e, MoPropertyMeta.READ_WRITE, 0x40, None, None, None, ["any-configuration", "best-effort-mirrored", "best-effort-mirrored-striped", "best-effort-striped", "best-effort-striped-dual-parity", "best-effort-striped-parity", "dual-disk", "no-local-storage", "no-raid", "raid-mirrored", "raid-mirrored-striped", "raid-striped", "raid-striped-dual-parity", "raid-striped-dual-parity-striped", "raid-striped-parity", "raid-striped-parity-striped", "single-disk"], []),
"name": MoPropertyMeta("name", "name", "string", VersionMeta.Version101e, MoPropertyMeta.READ_WRITE, 0x80, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []),
"policy_level": MoPropertyMeta("policy_level", "policyLevel", "uint", VersionMeta.Version211a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []),
"policy_owner": MoPropertyMeta("policy_owner", "policyOwner", "string", VersionMeta.Version211a, MoPropertyMeta.READ_WRITE, 0x100, None, None, None, ["local", "pending-policy", "policy"], []),
"protect_config": MoPropertyMeta("protect_config", "protectConfig", "string", VersionMeta.Version131c, MoPropertyMeta.READ_WRITE, 0x200, None, None, None, ["false", "no", "true", "yes"], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version101e, MoPropertyMeta.READ_ONLY, 0x400, 0, 256, None, [], []),
"sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version101e, MoPropertyMeta.READ_WRITE, 0x800, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
}
prop_map = {
"childAction": "child_action",
"descr": "descr",
"dn": "dn",
"flexFlashRAIDReportingState": "flex_flash_raid_reporting_state",
"flexFlashState": "flex_flash_state",
"intId": "int_id",
"mode": "mode",
"name": "name",
"policyLevel": "policy_level",
"policyOwner": "policy_owner",
"protectConfig": "protect_config",
"rn": "rn",
"sacl": "sacl",
"status": "status",
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.descr = None
self.flex_flash_raid_reporting_state = None
self.flex_flash_state = None
self.int_id = None
self.mode = None
self.name = None
self.policy_level = None
self.policy_owner = None
self.protect_config = None
self.sacl = None
self.status = None
ManagedObject.__init__(self, "StorageLocalDiskConfigDef", parent_mo_or_dn, **kwargs)
| [
"test@cisco.com"
] | test@cisco.com |
c0161c62d686a01caae3fc2484079a133e848245 | 09f0d09032d1f47fb367a40a812b8773084ea970 | /catkin_ws/devel/lib/python2.7/dist-packages/fh_desc/__init__.py | d14a41243ed12d64e0c9517b844e10d950709fef | [] | no_license | AMahrous/Shell_application_project | 7f12a6907c0e0b9111a140e3015f32236853c4f0 | dfbeef6748487bf63d0d7b29131d09ac2cdb3bbd | refs/heads/main | 2023-08-25T00:29:26.304907 | 2021-10-16T11:54:08 | 2021-10-16T11:54:08 | 417,812,421 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,084 | py | # -*- coding: utf-8 -*-
# generated from catkin/cmake/template/__init__.py.in
# keep symbol table as clean as possible by deleting all unnecessary symbols
from os import path as os_path
from sys import path as sys_path
from pkgutil import extend_path
__extended_path = "/home/mahrous/catkin_ws/src/shadow_robot_smart_grasping_sandbox/smart_grasping_sandbox/fh_desc/scripts".split(";")
for p in reversed(__extended_path):
sys_path.insert(0, p)
del p
del sys_path
__path__ = extend_path(__path__, __name__)
del extend_path
__execfiles = []
for p in __extended_path:
src_init_file = os_path.join(p, __name__ + '.py')
if os_path.isfile(src_init_file):
__execfiles.append(src_init_file)
else:
src_init_file = os_path.join(p, __name__, '__init__.py')
if os_path.isfile(src_init_file):
__execfiles.append(src_init_file)
del src_init_file
del p
del os_path
del __extended_path
for __execfile in __execfiles:
with open(__execfile, 'r') as __fh:
exec(__fh.read())
del __fh
del __execfile
del __execfiles
| [
"a.mahrousmahmoud@gmail.com"
] | a.mahrousmahmoud@gmail.com |
fe2082eaf406a2b33d53cfd1ef5081a117d3bee9 | af822d03681f2965a3c3a0a1d1ef5a8c5e652ef8 | /project-macquarie.py | 3e4f05c5e28dc47f3fe3e93da4342a1851e547f1 | [] | no_license | thekomx/Project-Macquarie | 45d2fc99146819c20c23be80c3c0d1cd0181bff3 | c84212a2a44e483441a81ae76ca39e21a8694dea | refs/heads/main | 2023-02-12T14:55:03.962611 | 2021-01-14T15:43:59 | 2021-01-14T15:43:59 | 323,203,867 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 831 | py | import streamlit as st
from src import home_page, chart_page
from src.markdown_module import get_markdown
#--- Available Contents
page_home = 'HOME'
page_chart = 'Charts'
page_morningstar = 'MorningStar Dashboard'
page_about = 'About'
pages = (page_home, page_chart, page_morningstar, page_about)
def main():
#--- Add Logo to Sidebar
st.sidebar.markdown(get_markdown('logo.md'), unsafe_allow_html=True)
#--- Add Menu to Sidebar
page_selected = st.sidebar.radio('Navigation', pages)
if page_selected == page_chart:
chart_page.get_chart()
elif page_selected==page_morningstar:
st.write('This is MorningStar Dashboard Page!')
elif page_selected==page_about:
st.write('This is About Page!')
else: #--- HOME Page
home_page.home()
if __name__ == "__main__":
main() | [
"thekom@hotmail.com"
] | thekom@hotmail.com |
7c142a4451089570c92e22bf2bc93355742883ad | 7721ab79bd274bd2edd19888abe9bd3f24ad8722 | /Flask/loops/application.py | 749f79beca057001bb9311f99b0aa6e4c94b4977 | [] | no_license | bipinbohara/WEB | 041ad85139eddb2938a669ca298bea9b2562f183 | d774a9eac977a9ee281cbad405f6ed354ce946d7 | refs/heads/master | 2020-07-13T09:43:06.232756 | 2020-06-27T04:35:31 | 2020-06-27T04:35:31 | 205,058,651 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 280 | py | from flask import Flask, render_template
app = Flask(__name__, template_folder = '../loops')
@app.route("/")
def index():
names = ["Alice", "Bob", "Charlie","David"]
return render_template("index.html", names = names)
if __name__=="__main__":
app.run(debug = True)
| [
"bipinbohara90@gmail.com"
] | bipinbohara90@gmail.com |
d3853fcd1cd5bf521b3341243df31b4d683f81b7 | 0642334c9b3319de5bff8568de3dd8b16aef3b90 | /xpulearn/layers/activation.py | 44ed9fd929a283c76449407bbd5b6c752f3dc077 | [] | no_license | ysk24ok/xpu-learn | 85e7504383d6ad0534f57967304ebde923072217 | 48d9918b0fd20dae906937bc1d2c66bac6cd161f | refs/heads/master | 2021-06-10T23:18:36.794791 | 2018-09-04T08:44:04 | 2018-09-04T08:44:04 | 145,984,802 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,152 | py | from .base import Layer
from .. import xp
from ..functions import clip_before_exp
class Activation(Layer):
def __init__(self, activation):
super(Activation, self).__init__()
if activation == 'linear':
self.activation = LinearActivation()
elif activation == 'sigmoid':
self.activation = SigmoidActivation()
elif activation == 'softmax':
self.activation = SoftmaxActivation()
elif activation == 'tanh':
self.activation = TanhActivation()
elif activation == 'relu':
self.activation = ReLUActivation()
else:
msg = 'Invalid value for activation: {}'.format(activation)
raise ValueError(msg)
def forwardprop(self, X_in):
"""
Arguments:
X_in (numpy.ndarray or cupy.core.core.ndarray):
2D array of shape [batch size, #units of input-side layer]
Returns:
(numpy.ndarray or cupy.core.core.ndarray):
2D array of the same shape as `X_in`
"""
self.X_in = X_in
return self.activation.forwardprop(X_in)
def backprop(self, dout):
"""
Arguments:
dout (numpy.ndarray or cupy.core.core.ndarray):
2D array of shape [batch size, #units of output-side layer]
Returns:
(numpy.ndarray or cupy.core.core.ndarray):
2D array of the same shape as `dout`
"""
return dout * self.activation.backprop(self.X_in)
class BaseActivation(Layer):
pass
class LinearActivation(BaseActivation):
def forwardprop(self, X_in):
return X_in
def backprop(self, X_in):
return xp.ones_like(X_in)
class SigmoidActivation(BaseActivation):
def forwardprop(self, X_in):
X_in = clip_before_exp(-X_in, self.dtype)
self.X_out = 1 + xp.exp(X_in)
self.X_out **= -1
return self.X_out
def backprop(self, X_in):
X_out = self.X_out
if X_out is None:
X_out = self.forwardprop(X_in)
return X_out * (1 - X_out)
class SoftmaxActivation(BaseActivation):
def forwardprop(self, X_in):
# Avoid overflow encountered in exp
self.X_out = X_in - X_in.max(axis=1, keepdims=True)
self.X_out[...] = xp.exp(self.X_out)
self.X_out /= xp.sum(self.X_out, axis=1, keepdims=True)
return self.X_out
def backprop(self, X_in):
X_out = self.X_out
if X_out is None:
X_out = self.forwardprop(X_in)
return X_out * (1 - X_out)
class TanhActivation(BaseActivation):
def forwardprop(self, X_in):
self.X_out = xp.tanh(X_in)
return self.X_out
def backprop(self, X_in):
X_out = self.X_out
if X_out is None:
X_out = self.forwardprop(X_in)
return 1 - xp.square(X_out)
class ReLUActivation(BaseActivation):
def forwardprop(self, X_in):
self.X_out = xp.maximum(X_in, 0)
return self.X_out
def backprop(self, X_in):
dX = xp.zeros_like(X_in)
dX[self.X_out > 0.0] = 1.0
return dX
| [
"yusuke.nishioka.0713@gmail.com"
] | yusuke.nishioka.0713@gmail.com |
48076f210e09c1d9b1f27ddf11c4df678540506c | 4d38108af0a6b079407fc68c468ed3e5610493b3 | /server/users/migrations/0002_auto_20200706_1505.py | d4458499f6b1347a5ef2a6c49350853d44cb44cb | [] | no_license | Zhihao-de/kh_community | b8cfa640250b1be1ff5fdf9bb29690e8e4a73cb7 | d0b7fa82f923193581c9953874696ad829ec79a3 | refs/heads/main | 2023-03-14T20:11:00.480352 | 2021-03-12T09:50:18 | 2021-03-12T09:50:18 | 341,066,507 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,374 | py | # Generated by Django 3.0.3 on 2020-07-06 07:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='useraccountsmodel',
name='address',
),
migrations.RemoveField(
model_name='useraccountsmodel',
name='name',
),
migrations.RemoveField(
model_name='useraccountsmodel',
name='phone',
),
migrations.AddField(
model_name='useraccountsmodel',
name='amount',
field=models.DecimalField(decimal_places=2, default=0.0, max_digits=14, verbose_name='单位元'),
),
migrations.AddField(
model_name='useraccountsmodel',
name='flags',
field=models.SmallIntegerField(choices=[(0, '支出'), (1, '收入')], default=0, verbose_name='账目类别'),
preserve_default=False,
),
migrations.AddField(
model_name='useraccountsmodel',
name='user',
field=models.ForeignKey(default=4, on_delete=django.db.models.deletion.CASCADE, to='users.UserModel', verbose_name='关联用户'),
preserve_default=False,
),
]
| [
"lizhihao@iscas.ac.cn"
] | lizhihao@iscas.ac.cn |
8188cfc9148cac57fa8da8eaaa96f14f73b9c2c9 | 9bd75ca966e94f3da4d7fa47aa261e88718f749c | /rpc_server.py | fe0571a256bd9b478f58681f0aef88f2b17cae12 | [] | no_license | andys-cloud/rabbitmqexamps | 1416c162d279c763635db13a0ba92d90bac7e186 | 69af3daf16302be398b99a7a6e6622a8f6319b90 | refs/heads/master | 2020-12-24T15:40:04.095771 | 2014-11-19T15:12:39 | 2014-11-19T15:12:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 998 | py | '''
Created on 2014-11-19
@author: yunling
'''
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel=connection.channel()
channel.queue_declare(queue="rpc_queue")
def fib(n):
if n == 0:
return 0
elif n == 1 :
return 1
else :
return fib(n-1) + fib(n-2)
def on_request(ch,method,properties,body):
n = int(body)
response = fib(n)
print '[exec: fib(%r) = %r]' %(n,response)
ch.basic_publish(exchange='',
routing_key=properties.reply_to,
properties=pika.BasicProperties(
correlation_id = properties.correlation_id ),
body=str(response))
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request,
queue='rpc_queue',
no_ack=False)
print " [x] Awaiting RPC requests"
channel.start_consuming()
| [
"yunlingAndy@users.noreply.github.com"
] | yunlingAndy@users.noreply.github.com |
d24ca982c965aff4fa18928d2e74a6e984a804ca | 5e2a6c7d11481c4994e0e20f6cef3dad33969601 | /Automated_ECU_Test_Framework/Libs/com/can/xcp.py | 7abd6d771797445b2dada95cd7334b164165bdfc | [] | no_license | toolsh/PythonProjects | 5cc1401b4704d60b942a8ae2c581a6b22ad5b987 | 46477aea081d797b00187e8cb3719e7a01f9625a | refs/heads/master | 2023-03-18T15:23:01.719347 | 2019-02-13T09:19:21 | 2019-02-13T09:19:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 19,127 | py | '''
====================================================================
Library for working with XCP on CAN
(C) Copyright 2013 Lear Corporation
====================================================================
'''
__author__ = 'Jesus Fidalgo'
__version__ = '1.0.0'
__email__ = 'jfidalgo@lear.com'
'''
CHANGE LOG
==========
1.0.0 Inital version
'''
import sys
import time
try:
from xcp_cfg import *
except ImportError:
print 'Configuration file xcp_cfg.py not found.'
sys.exit()
class XCP():
'''
Class for sending & receiving XCP frames.
'''
########################### PRIVATE FUNCTIONS ###########################
def __init__(self):
'''
Description: Constructor
'''
# Public vars
self.log_file = XCP_LOGFILE
self.print_frames = True
self.response = []
# Private vars
self._ag = 1 # address granularity
self._rx_timer = 1.0
self._all_frames = []
self._resp_frames = []
def _write_frame(self, data):
'''
Description: Writes CAN frame in the bus, with data provided as parameter.
CAN ID is XCP_ID_RX, and DLC is the length of the data list parameter.
This function waits also for the reception, and stores and prints the Rx frame.
'''
if XCP_SEND_8_BYTES:
zeroes = [0]*(8-len(data))
data.extend(zeroes)
time_start = time.time()
time_elapsed = 0.0
self.write_xcp_frame(XCP_ID_RX, len(data), data)
fr = self.read_xcp_frame(XCP_ID_RX)
while fr == [] and time_elapsed < self._rx_timer:
time_elapsed = time.time() - time_start
fr = self.read_xcp_frame(XCP_ID_RX)
if fr != []:
self._all_frames.append(fr)
if self.print_frames == True:
self._print_frame(self._all_frames[-1])
else:
print 'Not possible to send XCP request to the bus. Is ECU powered and running?'
def _read_frame(self):
'''
Description: Reads XCP response frames in the bus. The function is blocking until a valid
XCP response is received. It also stores and prints the Rx frame.
'''
time_start = time.time()
time_elapsed = 0.0
fr = self.read_xcp_frame(XCP_ID_TX)
while fr == [] and time_elapsed < self._rx_timer:
time_elapsed = time.time() - time_start
fr = self.read_xcp_frame(XCP_ID_TX)
if fr != []:
self._all_frames.append(fr)
self._resp_frames.append(fr)
if self.print_frames == True:
self._print_frame(self._all_frames[-1])
else:
print 'Expecting a XCP response but nothing was received from the ECU. Is ECU running?\n'
return fr
def _frame_id(self, fr):
'''
Description: Returns frame identifier of frame 'fr'.
Parameter 'fr' is a frame with the struct: [id, dlc, time, [b0, b1, b2, b3, b4, b5, b6, b7]]
'''
return fr[0]
def _frame_data_list(self, fr):
'''
Description: Returns data list of frame 'fr', that is [b0, b1, b2, b3, b4, b5, b6, b7]
Parameter 'fr' is a frame with the struct: [id, dlc, time, [b0, b1, b2, b3, b4, b5, b6, b7]]
'''
return fr[3]
def _frame_data(self, fr, i):
'''
Description: Returns data byte 'i' of the diagnostics response frame 'fr'.
Parameter 'fr' is a frame with the struct: [id, dlc, time, [b0, b1, b2, b3, b4, b5, b6, b7]]
'''
return self._frame_data_list(fr)[i]
def _print_frame(self, fr):
'''
Description: Prints frame on screen, with the correct format.
Parameter 'fr' is a frame with the struct: [id, dlc, time, [b0, b1, b2, b3, b4, b5, b6, b7]]
'''
print self._format_frame(fr)
def _convert_data_to_str(self, data):
'''
Description: Formats CAN data bytes so CAN frames are stored in the logfile as in CANOE logfiles.
For example, integer 0x5a is returned as the string '5A'.
'''
temp_data = str(hex(data))
temp_data = temp_data.upper()
temp_data = temp_data.replace('0X','')
if len(temp_data) == 1:
temp_data = '0' + temp_data
return temp_data
def _format_frame(self, frame):
'''
Description: Formats CAN frames to be stored in the logfile similar as in CANOE logfiles.
Parameter 'frame' is a frame with the struct: [id, dlc, time, [b0, b1, b2, b3, b4, b5, b6, b7]]
'''
# Format the timestamp
temp_t = float(frame[2])
temp_t = temp_t / 1000000000.0
temp_t = '%.3f' % temp_t
temp_s = ' ' * (10 - len(temp_t)) + temp_t + ' '
# Format the CAN ID
temp_id = str(hex(frame[0]))
temp_id = temp_id.upper()
temp_id = temp_id.replace('L','')
temp_id = temp_id.replace('0X','')
# Format de data bytes
temp_s = temp_s + temp_id + ' '
dlc = frame[1]
for i in range(dlc):
temp_s += self._convert_data_to_str(frame[3][i]) + ' '
return temp_s
def req_info(self):
'''
Description: Returns a string with the latest request + response
Example:
xcp=XCP()
xcp.connect()
print xcp.req_info()
'''
str = '\n'
for i in range(self._req_log_idx_start, self._req_log_idx_end):
str = str + self._format_frame(self._all_frames[i]) + '\n'
return str
def connect(self):
'''
Description: Sends CONNECT XCP command.
Returns a list with the complete response
byte 0 0xFF
byte 1 RESOURCE
byte 2 COMM_MODE_BASIC
byte 3 MAX_CTO
byte 4..5 MAX_DTO
byte 6 XCP PROTOCOL LAYER VERSION
byte 7 XCP TRANSPORT LAYER VERSION
Example:
xcp.connect()
'''
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP CONNECT command'
self._write_frame([0xFF, 0x00])
fr = self._read_frame()
if fr != []:
if self.print_frames == True:
if self._frame_data(fr, 0) == 0xFF:
# Calculation of AG (adress granularity) as specified in page 46 XCP -Part 2- Protocol Layer Specification -1.0.pdf
self._ag = self._frame_data(fr, 2) & 0x06
if self._ag == 2:
self._ag = 4
else:
self._ag += 1
print ' Positive response'
print ' RESOURCE =', hex(self._frame_data(fr, 1))
print ' COM_MODE_BASIC =', hex(self._frame_data(fr, 2))
print ' MAX_CTO =', str(self._frame_data(fr, 3))
print ' MAX_DTO =', str(0x100 * self._frame_data(fr, 4) + self._frame_data(fr, 5))
print ' XCP PROTOCOL LAYER VERSION =', hex(self._frame_data(fr, 6))
print ' XCP TRANSPORT LAYER VERSION =', hex(self._frame_data(fr, 7)), '\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return self._frame_data_list(fr)
else:
return fr
def disconnect(self):
'''
Description: Sends DISCONNECT XCP command.
Returns a list with the complete response.
Example:
xcp.disconnect()
'''
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP DISCONNECT command'
self._write_frame([0xFE])
fr = self._read_frame()
if fr != []:
if self.print_frames == True:
if self._frame_data(fr, 0) == 0xFF:
print ' Positive response\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return self._frame_data_list(fr)
else:
return fr
def get_status(self):
'''
Description: Sends GET_STATUS XCP command.
Returns a list with the complete response
byte 0 0xFF
byte 1 Current session status
byte 2 Current resource protection status
byte 3 Reserved
byte 4..5 Session configuration id
byte 6..7 don't care
Example:
xcp.get_status()
'''
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP GET_STATUS command'
self._write_frame([0xFD])
fr = self._read_frame()
if fr != []:
if self.print_frames == True:
if self._frame_data(fr, 0) == 0xFF:
print ' Positive response'
print ' Current session status =', hex(self._frame_data(fr, 1))
print ' Current resource protection status =', hex(self._frame_data(fr, 2))
print ' Session configuration id =', hex(0x100 * self._frame_data(fr, 4) + self._frame_data(fr, 5)), '\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return self._frame_data_list(fr)
else:
return fr
def synch(self):
'''
Description: Sends SYNCH XCP command.
Returns a list with the complete response.
Example:
xcp.synch()
'''
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP SYNCH command'
self._write_frame([0xFC])
fr = self._read_frame()
if fr != []:
if self.print_frames == True:
if self._frame_data(fr, 0) == 0xFF:
print ' Positive response\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return self._frame_data_list(fr)
else:
return fr
def set_mta(self, address, address_ext=0x00):
'''
Description: Sends SET_MTA XCP command.
Parameter address contains the address to be set in MTA.
Returns a list with the complete response.
Example:
xcp.set_mta(0x40002C78)
'''
d0 = (0x000000FF & address)
d1 = (0x0000FF00 & address) >> 8
d2 = (0x00FF0000 & address) >> 16
d3 = (0xFF000000 & address) >> 24
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP SET_MTA command, MTA at address ' + hex(address).upper()
self._write_frame([0xF6, 0x00, 0x00, address_ext, d3, d2, d1, d0])
fr = self._read_frame()
if fr != []:
if self.print_frames == True:
if self._frame_data(fr, 0) == 0xFF:
print ' Positive response\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return self._frame_data_list(fr)
else:
return fr
def short_upload(self, data_elems, address, address_ext=0x00):
'''
Description: Sends SHORT_UPLOAD XCP command. This command is used for read a number of data elements 'data_elems' from address 'address'.
Each data element is a byte, word o dword depending on AG parameter sent by the ECU in CONNECT command.
Parameter data_elems contains the number of elements to be read.
Parameter address contains the address of the vars to be read.
Returns a list with the complete response.
byte 0 0xFF
byte 1..7 var contents
Example 1:
# if CONNECT command returned by the ECU contained AG=1 (byte access)
result = xcp.short_upload(1, 0x40003CBC)
print result[1]
Example 2:
# if CONNECT command returned by the ECU contained AG=2 (word access)
result = xcp.short_upload(1, 0x40003CBC)
print result[1:3]
Example 3:
# if CONNECT command returned by the ECU contained AG=4 (dword access)
result = xcp.short_upload(1, 0x40003CBC)
print result[1:5]
'''
d0 = (0x000000FF & address)
d1 = (0x0000FF00 & address) >> 8
d2 = (0x00FF0000 & address) >> 16
d3 = (0xFF000000 & address) >> 24
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP SHORT_UPLOAD command, ' + str(data_elems) + ' elems of ' + str(self._ag) + ' bytes size at address ' + hex(address).upper()
self._write_frame([0xF4, data_elems, 0x00, address_ext, d3, d2, d1, d0])
fr = self._read_frame()
if fr != []:
if self.print_frames == True:
if self._frame_data(fr, 0) == 0xFF:
print ' Positive response\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return self._frame_data_list(fr)
else:
return fr
def upload(self, data_elems):
'''
Description: Sends UPLOAD XCP command. This command, used together with SET_MTA command, is used
for reading large amounts of data that doesn't fit in one XCP frame.
A data block of number of data elements 'data_elems' will be read from MTA address.
Each data element is a byte, word o dword depending on AG parameter sent by the ECU in CONNECT command.
MTA is post-incremented by the ECU accordingly after each upload command.
Returns a list with the complete response.
Example:
# Let's read 10 bytes from address 0x40002C78
# First set MTA to the desired address to read data from
xcp.set_mta(0x40002C78)
# Read 10 bytes from address specified in MTA
resp = xcp.upload(10)
# If reading 10 bytes more, the ECU will get them from 0x40002C82 (0x40002C78 + 10)
# because the ECU has post-incremented MTA accordingly
resp = xcp.upload(10)
'''
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP UPLOAD command, ' + str(data_elems) + ' elems of ' + str(self._ag) + ' bytes'
self._write_frame([0xF5, data_elems])
n_bytes = data_elems * self._ag + 1 # +1 for counting byte 0 0xFF
if self._ag > 1:
n_bytes += 1
resp = []
while n_bytes > 0:
fr = self._read_frame()
resp.extend(self._frame_data_list(fr))
n_bytes -= len(self._frame_data_list(fr))
if resp != []:
if self.print_frames == True:
if resp[0] == 0xFF:
print ' Positive response\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return resp
else:
return resp
def download(self, data_elems, data):
'''
Description: Sends DOWNLOAD XCP command. This command, used together with SET_MTA command, is used
for writing small chunks of data.
A data block of number of data elements 'data_elems' will be written in the configured MTA address.
Each data element is a byte, word o dword depending on AG parameter sent by the ECU in CONNECT command.
Parameter 'data' contains a list of elements.
MTA is post-incremented by the ECU accordingly after each upload command.
Returns a list with the complete response.
Example:
# Let's write 2 bytes at address 0x40002C78
# First set MTA0 to the desired address to write data
xcp.set_mta(0x40002C78)
# If AG sent by the ECU in the CONNECT command is 1, writing 2 bytes would be:
xcp.download(2, [0x01, 0x02])
# MTA is automatically increased in 2 bytes, so we can continue writing data
xcp.dnload(4, [0x03, 0x04, 0x05, 0x06])
# If AG sent by the ECU in the CONNECT command is 2, writing 2 words would be:
xcp.download(2, [0x1122, 0x3344])
'''
if data_elems * self._ag > 6:
print 'XCP DOWNLOAD command in this library allows only to download data fitting in one CAN frame'
return []
# construct the request frame
wr_frame = [0xF0, data_elems]
if self._ag == 4:
wr_frame.append(4)
for item in data:
if self._ag == 1:
wr_frame.append(item)
elif self._ag == 2:
wr_frame.append((0xFF00 & item) >> 8)
wr_frame.append(0x00FF & item)
elif self._ag == 4:
wr_frame.append((0xFF000000 & item) >> 24)
wr_frame.append((0x00FF0000 & item) >> 16)
wr_frame.append((0x0000FF00 & item) >> 8)
wr_frame.append(0x000000FF & item)
self._req_log_idx_start = len(self._all_frames)
if self.print_frames == True:
print 'XCP DOWNLOAD command, ' + str(data_elems) + ' elements of ' + str(self._ag) + ' bytes'
self._write_frame(wr_frame)
fr = self._read_frame()
if fr != []:
if self.print_frames == True:
if self._frame_data(fr, 0) == 0xFF:
print ' Positive response\n'
else:
print ' Negative response\n'
self._req_log_idx_end = len(self._all_frames)
return self._frame_data_list(fr)
else:
return fr
def save_logfile(self):
'''
Description: Writes frames to the logfile.
Example:
xcp=XCP()
xcp.xonnect()
xcp.save_logfile()
'''
if self._all_frames != []:
f = open(self.log_file, 'w')
for item in self._all_frames:
f.writelines(self._format_frame(item) + '\n')
f.close()
| [
"32851286+PradeepSingh-Git@users.noreply.github.com"
] | 32851286+PradeepSingh-Git@users.noreply.github.com |
0af8578f30a04ba90055b2d1e37bb8447efb334b | 8897e5218a5b995a1010b4f0eab38e99a71e9782 | /tekstovni_vmesnik.py | d35145b610aab348ccaf89daf45a7450cc23c2ad | [
"MIT"
] | permissive | brinaribic/projektna_naloga | 5c0cf1a2668cc264ed12b481909f12350cede2c2 | 53a3677916bce840d71d44b3ad907ad1fab4de6f | refs/heads/master | 2022-12-06T02:01:58.961830 | 2020-08-29T11:35:41 | 2020-08-29T11:35:41 | 289,217,798 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,395 | py | from datetime import date
from model import Slascicar
LOGO = '''
_______ ___ _______ ______ ___ _ _______ _______ __ _ _______ ______
| || | | _ || | | | | || || || | | || || |
| _____|| | | |_| || _ || |_| || _ || _____|| |_| || ___|| _ |
| |_____ | | | || | | || _|| | | || |_____ | || |___ | | | |
|_____ || |___ | || |_| || |_ | |_| ||_____ || _ || ___|| |_| |
_____| || || _ || || _ || | _____| || | | || |___ | |
|_______||_______||__| |__||______| |___| |_||_______||_______||_| |__||_______||______|
'''
DATOTEKA_S_SLADICAMI = 'stanje.json'
try:
slascicar = Slascicar.nalozi_stanje(DATOTEKA_S_SLADICAMI)
except FileNotFoundError:
slascicar = Slascicar()
def logo(niz):
return f'\033[1;35m{niz}\033[0m'
def krepko(niz):
return f'\033[1m{niz}\033[0m'
def modro(niz):
return f'\033[1;94m{niz}\033[0m'
def rdece(niz):
return f'\033[1;91m{niz}\033[0m'
def vnesi_stevilo(pozdrav):
while True:
try:
stevilo = input(pozdrav)
return int(stevilo)
except ValueError:
print(f'Prosim, da vnesete stevilo!')
def izberi(seznam):
for indeks, (oznaka, _) in enumerate(seznam, 1):
print(f'{indeks}) {oznaka}')
while True:
izbira = vnesi_stevilo('> ')
if 1 <= izbira <= len(seznam):
_, element = seznam[izbira - 1]
return element
else:
print(f'Izberi stevilo med 1 in {len(seznam)}')
def prikaz_skupnega_dobicka(dobicek):
if dobicek > 0:
return f'{modro(dobicek)}€'
elif dobicek < 0:
return f'{rdece(dobicek)}€'
else:
return f'{dobicek}€'
def prikaz_sladice(sladica):
if sladica in slascicar.prodane_sladice():
return f'{modro(sladica)}'
else:
return f'{rdece(sladica)}'
def zacetna_stran():
print(logo(LOGO))
print ()
print(krepko('Dobrodošli v programu Sladkosned!'))
print()
print('Za izhod pritisnite Ctrl-C')
print(80 * '=')
def osnovne_meni():
while True:
try:
print(prikaz_sladic())
print(80 * '=')
print('Kaj bi radi naredili?')
print()
moznosti = [
('dodaj prodajo', dodaj_prodajo),
('dodaj strošek', dodaj_strosek),
('dodaj sladico', dodaj_sladico),
('poglej neprodane sladice', neprodane_sladice),
('prodaj sladico', prodaj_sladico),
('poglej vse sladice', vse_sladice),
('poglej stanje', stanje),
]
izbira = izberi(moznosti)
izbira()
print(80 * '=')
print()
input('Pritisnite Enter za shranjevanje in vrnitev v osnovni meni')
print(80 * '=')
slascicar.shrani_stanje(DATOTEKA_S_SLADICAMI)
except ValueError as e:
print(rdece(e.args[0]))
print(80 * '=')
except KeyboardInterrupt:
print()
print('Nasvidenje!')
break
def prikaz_sladic():
for sladica in slascicar.vse_sladice:
if sladica.prodaja.vrsta == 'neprodano':
print(f'{rdece(sladica.ime)}: {sladica.cena}€, dne {sladica.datum}, količina {sladica.kolicina}')
else:
print(f'{modro(sladica.ime)}: {sladica.cena}€, dne {sladica.datum}, količina {sladica.kolicina}')
print(f'Dobicek: {prikaz_skupnega_dobicka(slascicar.dobicek())}')
def dodaj_prodajo():
vrsta = input("Vnesite način prodaje sladice (npr. osebni prevzem,...), če sladica ni prodana vnesite 'neprodano'> ")
slascicar.dodaj_prodajo(vrsta)
def dodaj_strosek():
ime = input('Vnesite ime stroška (npr. sestavine, dodatni delavec, ...)> ')
znesek = vnesi_stevilo('znesek> ')
slascicar.dodaj_strosek(ime, znesek)
def dodaj_sladico():
print('Vnesite podatke o sladici:')
print()
ime = input('Ime sladice>')
datum = date.today()
cena = vnesi_stevilo('Prodajna cena>')
print('Izberite strošek:')
strosek = izberi_strosek(slascicar.vsi_stroski)
print("Izberite na kakšen način ste prodali sladico.")
prodaja = izberi_prodajo(slascicar.prodaje)
kolicina = vnesi_stevilo('Količina>')
slascicar.dodaj_sladico(ime, datum, cena, strosek, prodaja, kolicina)
print('Sladica uspešno dodana!')
def izberi_strosek(stroski):
return izberi([(strosek, strosek)for strosek in stroski],)
def izberi_prodajo(prodaje):
return izberi([(prodaja, prodaja)for prodaja in prodaje],)
def neprodane_sladice():
if len(slascicar.neprodane_sladice()) == 0:
raise ValueError('Vse sladice so že prodane!')
for sladica in slascicar.vse_sladice:
if sladica.prodaja.vrsta == 'neprodano':
print(f'{rdece(sladica.ime)}: {sladica.cena}€')
def izberi_neprodano_sladico(sladice):
return izberi([(sladica, sladica) for sladica in sladice])
def prodaj_sladico():
if len(slascicar.neprodane_sladice()) == 0:
raise ValueError('Vse sladice so že prodane!')
print('katero sladico bi prodali?')
sladica = izberi_neprodano_sladico(slascicar.neprodane_sladice())
print('Na kakšen način bi prodali sladico?')
nova_prodaja = izberi_prodajo(slascicar.prodaje)
kolicina = vnesi_stevilo('Koliko sladic bi prodali?>')
slascicar.prodaj_sladico(sladica, nova_prodaja, kolicina)
print('Uspešno ste prodali sladico!')
def vse_sladice():
for sladica in slascicar.vse_sladice:
if sladica.prodaja.vrsta == 'neprodano':
print(f'{rdece(sladica.ime)}: {sladica.cena}€, dne {sladica.datum}')
else:
print(f'{modro(sladica.ime)}: {sladica.cena}€, dne {sladica.datum}')
def stanje():
print(f'Skupni stroški so {slascicar.stroski_skupno()}€')
print(f'Vas dobiček je {prikaz_skupnega_dobicka(slascicar.dobicek())}')
print(f'Skupni prihodki so {slascicar.prihodki()}€')
print(f'Najpogostejša prodaja je {slascicar.najpogostejsa_prodaja()}')
print(f'Največji strošek je {slascicar.najvecji_stroski()}€')
print(f'Najdražja sladica je {prikaz_sladice(slascicar.najdrazja_sladica())}')
zacetna_stran()
osnovne_meni()
| [
"brinaribic19@gmail.com"
] | brinaribic19@gmail.com |
4351decb036d8072bdbfcd0c183b01bade4445e7 | 082c6d8f248257c8442bbef7412f9915ac4c33bd | /mlrun/api/api/endpoints/secrets.py | 875ae80681de74dfcb0fc81e1648b26c5a918c41 | [
"Apache-2.0"
] | permissive | eran-nussbaum/mlrun | 24e7db989b4eb03548f127ff26d36f77b1c82250 | 97209b27ccf3daf8f202a1a2bb1b01abd537ad70 | refs/heads/master | 2023-08-26T01:35:02.797712 | 2021-10-21T10:18:24 | 2021-10-21T10:18:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,928 | py | from http import HTTPStatus
from typing import List
import fastapi
from sqlalchemy.orm import Session
import mlrun.api.api.deps
import mlrun.api.crud
import mlrun.api.utils.auth.verifier
import mlrun.api.utils.singletons.project_member
import mlrun.errors
from mlrun.api import schemas
from mlrun.utils.vault import add_vault_user_secrets
router = fastapi.APIRouter()
@router.post("/projects/{project}/secrets", status_code=HTTPStatus.CREATED.value)
def store_project_secrets(
project: str,
secrets: schemas.SecretsData,
auth_info: mlrun.api.schemas.AuthInfo = fastapi.Depends(
mlrun.api.api.deps.authenticate_request
),
db_session: Session = fastapi.Depends(mlrun.api.api.deps.get_db_session),
):
# Doing a specific check for project existence, because we want to return 404 in the case of a project not
# existing, rather than returning a permission error, as it misleads the user. We don't even care for return
# value.
mlrun.api.utils.singletons.project_member.get_project_member().get_project(
db_session, project, auth_info.session
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.secret,
project,
secrets.provider,
mlrun.api.schemas.AuthorizationAction.create,
auth_info,
)
mlrun.api.crud.Secrets().store_secrets(project, secrets)
return fastapi.Response(status_code=HTTPStatus.CREATED.value)
@router.delete("/projects/{project}/secrets", status_code=HTTPStatus.NO_CONTENT.value)
def delete_project_secrets(
project: str,
provider: schemas.SecretProviderName,
secrets: List[str] = fastapi.Query(None, alias="secret"),
auth_info: mlrun.api.schemas.AuthInfo = fastapi.Depends(
mlrun.api.api.deps.authenticate_request
),
db_session: Session = fastapi.Depends(mlrun.api.api.deps.get_db_session),
):
mlrun.api.utils.singletons.project_member.get_project_member().get_project(
db_session, project, auth_info.session
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.secret,
project,
provider,
mlrun.api.schemas.AuthorizationAction.delete,
auth_info,
)
mlrun.api.crud.Secrets().delete_secrets(project, provider, secrets)
return fastapi.Response(status_code=HTTPStatus.NO_CONTENT.value)
@router.get("/projects/{project}/secret-keys", response_model=schemas.SecretKeysData)
def list_secret_keys(
project: str,
provider: schemas.SecretProviderName = schemas.SecretProviderName.vault,
token: str = fastapi.Header(None, alias=schemas.HeaderNames.secret_store_token),
auth_info: mlrun.api.schemas.AuthInfo = fastapi.Depends(
mlrun.api.api.deps.authenticate_request
),
db_session: Session = fastapi.Depends(mlrun.api.api.deps.get_db_session),
):
mlrun.api.utils.singletons.project_member.get_project_member().get_project(
db_session, project, auth_info.session
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.secret,
project,
provider,
mlrun.api.schemas.AuthorizationAction.read,
auth_info,
)
return mlrun.api.crud.Secrets().list_secret_keys(project, provider, token)
@router.get("/projects/{project}/secrets", response_model=schemas.SecretsData)
def list_secrets(
project: str,
secrets: List[str] = fastapi.Query(None, alias="secret"),
provider: schemas.SecretProviderName = schemas.SecretProviderName.vault,
token: str = fastapi.Header(None, alias=schemas.HeaderNames.secret_store_token),
auth_info: mlrun.api.schemas.AuthInfo = fastapi.Depends(
mlrun.api.api.deps.authenticate_request
),
db_session: Session = fastapi.Depends(mlrun.api.api.deps.get_db_session),
):
mlrun.api.utils.singletons.project_member.get_project_member().get_project(
db_session, project, auth_info.session
)
mlrun.api.utils.auth.verifier.AuthVerifier().query_project_resource_permissions(
mlrun.api.schemas.AuthorizationResourceTypes.secret,
project,
provider,
mlrun.api.schemas.AuthorizationAction.read,
auth_info,
)
return mlrun.api.crud.Secrets().list_secrets(project, provider, secrets, token)
@router.post("/user-secrets", status_code=HTTPStatus.CREATED.value)
def add_user_secrets(secrets: schemas.UserSecretCreationRequest,):
if secrets.provider != schemas.SecretProviderName.vault:
return fastapi.Response(
status_code=HTTPStatus.BAD_REQUEST.vault,
content=f"Invalid secrets provider {secrets.provider}",
)
add_vault_user_secrets(secrets.user, secrets.secrets)
return fastapi.Response(status_code=HTTPStatus.CREATED.value)
| [
"noreply@github.com"
] | noreply@github.com |
70e325da3949c956458a0c372fedb2c42aa873c5 | 628574233007517f0fde0b40317a68f6065f37ca | /Python/DjangoProjects/SurveyForm/SurveyForm/settings.py | 1c2cb2f17d14cc900f7c8391c0c603f57f8b5c5e | [] | no_license | carolynyen/DojoAssignments | 5a5d2df904bc2d650f945d09369a1d0ee5a316bc | a06ee21b968357e7bda77542d6a21b664a53136e | refs/heads/master | 2021-01-11T17:54:13.006990 | 2017-04-21T19:42:46 | 2017-04-21T19:42:46 | 79,866,508 | 0 | 4 | null | null | null | null | UTF-8 | Python | false | false | 3,131 | py | """
Django settings for SurveyForm project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=3#8-t=w@5^t#^3w)o4xwbrq@0uf)bpin4y^c%e8mt+_&)n8%x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'apps.surveyform',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'SurveyForm.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'SurveyForm.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
| [
"whitehawk6888@yahoo.com"
] | whitehawk6888@yahoo.com |
d4cbcfa95fad06e8d14954bfdccb2f13136a60d3 | f30b91db647dca1f77fffa4b7e26b6c6a68abbc6 | /6_kyu/Greatest Common Factor of an Array/python/test_solution.py | 748f17fd9c642882c5538a1f17670cd275df2e8b | [] | no_license | estraviz/codewars | 73caf95519eaac6f34962b8ade543bf4417df5b7 | 5f8685e883cb78381c528a0988f2b5cad6c129c2 | refs/heads/master | 2023-05-13T07:57:43.165290 | 2023-05-08T21:50:39 | 2023-05-08T21:50:39 | 159,744,593 | 10 | 55 | null | null | null | null | UTF-8 | Python | false | false | 442 | py | import pytest
from solution import greatest_common_factor
tests = [
([1, 8], 1),
([16, 4, 8], 4),
([46, 14, 20, 88], 2),
([468, 156, 806, 312, 442], 26),
([48, 99, 18], 3),
([32, 96, 120, 80], 8),
([91, 143, 234, 52], 13),
([171, 45, 297, 342], 9),
]
@pytest.mark.parametrize(
"seq, expected", tests
)
def test_greatest_common_factor(seq, expected):
assert greatest_common_factor(seq) == expected
| [
"javier.estraviz@gmail.com"
] | javier.estraviz@gmail.com |
806adbe21341eef6b01e1fe731fc872fa7cb112d | 31252d95232aacaee80b5b3d22cf8b66f05d24c6 | /8.AnomalyDetection_RecommenderSystem/machine-learning-ex8/ex8/selectThreshold.py | 49b530847bb4a727357032badf908a9836c3daba | [] | no_license | mrech/MachineLearning_AndrewNg | 54ae44824d5ae53c8faf3f4adeff76935d4f479a | 748a49ece69dae413b78f9de95b3fb483848ee59 | refs/heads/master | 2020-04-24T10:37:57.072292 | 2019-08-20T13:16:50 | 2019-08-20T13:16:50 | 171,899,951 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,680 | py | # SELECTTHRESHOLD Find the best threshold (epsilon) to use for selecting
# outliers
def selectThreshold(yval, pval):
'''
[bestEpsilon bestF1] = SELECTTHRESHOLD(yval, pval) finds the best
threshold to use for selecting outliers based on the results from a
validation set (pval) and the ground truth (yval).
'''
import numpy as np
bestEpsilon = 0
bestF1 = 0
stepsize = (max(pval) - min(pval)) / 1000
# Instructions: Compute the F1 score of choosing epsilon as the
# threshold and place the value in F1. The code at the
# end of the loop will compare the F1 score for this
# choice of epsilon and set it to be the best epsilon if
# it is better than the current choice of epsilon.
for epsilon in np.arange(min(pval), max(pval), stepsize):
# predict the anomaly
prediction = (pval < epsilon)
# calculate the F1 score
tp = sum((prediction == 1) & (yval.flatten() == 1).tolist())
fp = sum((prediction == 1) & (yval.flatten() == 0).tolist())
fn = sum((prediction == 0) & (yval.flatten() == 1).tolist())
# RuntimeWarning handling due to 0/0
# CASE: when the algorithm classify everyhting as NO ANOMALY
if tp == 0 & fp == 0:
F1 = 0
else:
prec = tp/(tp+fp)
rec = tp/(tp+fn)
F1 = (2*prec*rec)/(prec+rec)
if F1 > bestF1:
bestF1 = F1
bestEpsilon = epsilon
return bestEpsilon, bestF1 | [
"rivato.morena@gmail.com"
] | rivato.morena@gmail.com |
62c0c6d97ebf6469c69d1e7bc3d48d6490f1495a | 19a2f2091832866592a8a4a79c4648ba7c112776 | /collection/admin.py | a2f9f215b5813c8b956143efdeddd557ab27ac7e | [] | no_license | pierrepas/monSiteDjango | c7d58b2c1ad6c3b25822a53fabc16f3cdb493906 | 9f0530338340e63e57f4ae70cd5ef2cc30004373 | refs/heads/master | 2021-01-11T15:27:08.806379 | 2017-01-29T20:23:48 | 2017-01-29T20:23:48 | 80,346,483 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 325 | py |
from django.contrib import admin
# import your model
from collection.models import Chose
# set up automated slug creation
class ChoseAdmin(admin.ModelAdmin):
model = Chose
list_display = ('nom', 'description',)
prepopulated_fields = {'slug': ('nom',)}
# and register it
admin.site.register(Chose, ChoseAdmin)
| [
"pierrepas@yahoo.fr"
] | pierrepas@yahoo.fr |
da5a3d88ca31dcbf5ec1c210969b0c38fed32ecd | ed648425111d03f45de6d0354b0b2c80085dce6a | /PYCV/chapter7/car_sliding_windows.py | ced05e02891ce1f4cf20e559b5c6612490c0f09c | [] | no_license | CHINAPANDAGZX/PyProject | 71eb65d81ed4cb59aea7f0f96380c050229cedd3 | 640ab5d578973c76b02e46b669fa260335baf8eb | refs/heads/master | 2023-07-08T11:25:49.984658 | 2023-06-29T07:19:28 | 2023-06-29T07:19:28 | 142,262,907 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,835 | py | import cv2
import numpy as np
from car_detector.detector import car_detector, bow_features
from car_detector.pyramid import pyramid
from car_detector.non_maximum import non_max_suppression_fast as nms
from car_detector.sliding_window import sliding_window
import urllib
def in_range(number, test, thresh=0.2):
return abs(number - test) < thresh
test_image = "/home/d3athmast3r/dev/python/pycv/images/cars.jpg"
img_path = "/home/d3athmast3r/dev/python/pycv/images/test.jpg"
urllib.urlretrieve(test_image, img_path)
svm, extractor = car_detector()
detect = cv2.xfeatures2d.SIFT_create()
w, h = 100, 40
img = cv2.imread(img_path)
#img = cv2.imread(test_image)
rectangles = []
counter = 1
scaleFactor = 1.25
scale = 1
font = cv2.FONT_HERSHEY_PLAIN
for resized in pyramid(img, scaleFactor):
scale = float(img.shape[1]) / float(resized.shape[1])
for (x, y, roi) in sliding_window(resized, 20, (100, 40)):
if roi.shape[1] != w or roi.shape[0] != h:
continue
try:
bf = bow_features(roi, extractor, detect)
_, result = svm.predict(bf)
a, res = svm.predict(bf, flags=cv2.ml.STAT_MODEL_RAW_OUTPUT | cv2.ml.STAT_MODEL_UPDATE_MODEL)
print "Class: %d, Score: %f, a: %s" % (result[0][0], res[0][0], res)
score = res[0][0]
if result[0][0] == 1:
if score < -1.0:
rx, ry, rx2, ry2 = int(x * scale), int(y * scale), int((x+w) * scale), int((y+h) * scale)
rectangles.append([rx, ry, rx2, ry2, abs(score)])
except:
pass
counter += 1
windows = np.array(rectangles)
boxes = nms(windows, 0.25)
for (x, y, x2, y2, score) in boxes:
print x, y, x2, y2, score
cv2.rectangle(img, (int(x),int(y)),(int(x2), int(y2)),(0, 255, 0), 1)
cv2.putText(img, "%f" % score, (int(x),int(y)), font, 1, (0, 255, 0))
cv2.imshow("img", img)
cv2.waitKey(0)
| [
"493004728@qq.com"
] | 493004728@qq.com |
4e0849b75a3548a5b1bf0a796423db5b35b4cb11 | 226b82ee851e643a0d1235ac5991c19a8f4cb15a | /tesseract/show_grey.py | d9c78927783708d53c850926e4450a2239efc24e | [] | no_license | liuweier123/BrailleTab | 0b7ee831a2ec3055dd480d5cae8a63374891e2f1 | 8c8d4e6c84f9606a2164e52514fc4772d6539dcf | refs/heads/master | 2020-03-21T08:48:12.373336 | 2016-09-26T17:01:40 | 2016-09-26T17:01:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 180 | py | import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.imshow(image_gray, cmap=cm.gray) # 指明 cmap=cm.gray
plt.axis("off") # 去掉坐标轴
plt.show() # 显示图像 | [
"icaiyu0618@gmail.com"
] | icaiyu0618@gmail.com |
436b1d40d931864183e4790ee0b3374e829502cb | be24b5f37823125b2b901c0029175bfb2f25fb0e | /src/homework/homework12/win.py | 7f851ec0cfc578951966aaf3ea0a12716f2bc633 | [
"MIT"
] | permissive | acc-cosc-1336/cosc-1336-spring-2018-Miguelh1997 | 1bd75c51e72431037a46a1b3079d7695c41920ce | ac4b0405c4070758d0fc07458d4dca8a8a0313de | refs/heads/master | 2021-05-11T09:11:41.887630 | 2018-05-12T03:11:38 | 2018-05-12T03:11:38 | 118,070,058 | 0 | 1 | MIT | 2018-05-12T03:16:17 | 2018-01-19T03:13:02 | Python | UTF-8 | Python | false | false | 874 | py | from tkinter import Tk, Label, Button
from src.homework.homework12.converter import Converter
class Win(Tk):
def __init__(self):
self.miles = Converter()
Tk.__init__(self, None, None)
self.wm_title('Miles to Kilometers converter')
self.button_quit = Button(self,text='Quit', command=self.destroy).grid(row=2,column=3)
self.display_conversion_button = Button(self, text='Display Conversion',command=self.display_labels).grid(row=2,column=1)
self.mainloop()
def display_labels(self):
km = 100
self.label = Label(self, text='Km:' + str(km)).grid(row=0, column=1, sticky="w")
self.label = Label(self, text='Miles:' + str(self.miles.get_miles_from_km(km))).grid(row=1, column=1,
sticky="w")
| [
"noreply@github.com"
] | noreply@github.com |
583a94b618b96e5744d38335bbb758f418ae1723 | 7dffca52253cbc5bf6f8d1dd2061d1fc233f4ced | /create_mongo_srv_dply.py | a0060298e0750f8a32a1b384fe6cf8df9839fb40 | [] | no_license | Rahees9983/Create_mongo_db_srv_deploy | 8c38117502567f9573452c22c01960ca9dee052e | c8828ea214a2e36dab1372ff664d86753d55ec37 | refs/heads/master | 2020-10-01T18:20:53.954434 | 2019-12-12T12:06:40 | 2019-12-12T12:06:40 | 227,597,503 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,117 | py | from os import path
import os
import yaml
import subprocess
from kubernetes import client, config
import time
# creating mongo-namespace namespace
os.system("kubectl create namespace mongo-namespace")
def create_mongo_delploy():
config.load_kube_config()
with open(path.join(path.dirname(__file__), "mydb_deploy.yaml")) as f:
dep = yaml.safe_load(f)
k8s_apps_v1 = client.AppsV1Api()
resp = k8s_apps_v1.create_namespaced_deployment(
body=dep, namespace="mongo-namespace")
print("Deployment created. status='%s'" % resp.metadata.name)
def create_mongo_service():
config.load_kube_config()
with open(path.join(path.dirname(__file__), "mydb_service.yaml")) as f:
dep = yaml.safe_load(f)
k8s_apps_v1 = client.CoreV1Api()
# resp = k8s_apps_v1.create_namespaced_deployment(body=dep, namespace="default")
resp = k8s_apps_v1.create_namespaced_service(namespace="mongo-namespace", body=dep)
print("Deployment created. status='%s'" % resp.metadata.name)
create_mongo_delploy()
create_mongo_service() | [
"noreply@github.com"
] | noreply@github.com |
6fcdafef41b6d2ebcbd63cca3e0e3e887ec4adc4 | 5956bc0159e2c6501c4116f86d8527a3ca8c1bb8 | /gensimAssignment.py | b9ed59fb731f3bbcb72e2ded654b011362289c75 | [] | no_license | hanscjo/Gensim-assignment | 0f47648d65a331383ab8bd58f1244433e2af9d25 | f1f37daaf6c8c40b2813b32a5b79a4f526a2cb2e | refs/heads/main | 2023-04-04T13:47:06.270862 | 2021-04-24T10:39:01 | 2021-04-24T10:39:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,526 | py | import random
random.seed(123) #Step 1.0
import codecs
import re
from nltk.stem.porter import PorterStemmer
import gensim
f = codecs.open("pg3300.txt", "r", "utf-8") #Step 1.1
#!READ! I have documented the program, my problem-solving and my interpretations in the comments next to each line. Also, I have organized print-statements that represent all the useful data for the assignments, so running the file will neatly organize it.
paragraph = "" #Step 1.2 and 1.3, line 11-21
docPartition = [] #Remark 1 says to keep the original paragraphs
docPartitionWords = [] #So therefore we have this line for separated terms
for line in f: #Cycle through every line in the document
if line.isspace(): #If we reach a newline(where we separate by paragraphs)
if paragraph != "" and 'gutenberg' not in paragraph.lower(): #This if-statement is to make sure that we don't add empty lines as stand-alone paragraphs, as well as filtering out all instances of 'Gutenberg'
docPartition.append(paragraph)
paragraph = "" #Reset the constructed paragraph as it is time to construct a new one
else:
paragraph += line #Adding a line onto the given paragraph, constructing it until we reach an empty line to meet the if-condition above.
stemmer = PorterStemmer()
for p in range(0, len(docPartition)):
docPartitionWords.append(re.findall(r"[\w']+", docPartition[p].lower())) # Step 1.4 and 1.5, splits the paragraphs into a list of words in lower-case, without punctuation, using python regular expressions
for q in range(0, len(docPartition)):
for r in range(0, len(docPartitionWords[q])):
docPartitionWords[q][r] = stemmer.stem(docPartitionWords[q][r]) # Step 1.6, using the nltk library to stem each word in the file, saving some space in the corpus
f.close() #I'm not sure if this is necessary, but the program still ran, and I wanted to be on the safe side
c = codecs.open("common-english-words.txt", "r", "utf-8")
dictionary = gensim.corpora.Dictionary(docPartitionWords) #Step 2.1(listed twice in assignment), line 36-46
stop_ids = []
stopwords = []
for line in c:
stopwords = line.split(",") #Separating each stopword
stop_ids = [dictionary.token2id[stopword] for stopword in stopwords if stopword in dictionary.token2id] #Building a list of stopword-ids relating to the dictionary
dictionary.filter_tokens(stop_ids) #Filtering out stopwords through our list of stopword-ids
c.close()
bagsOfWords = [dictionary.doc2bow(word) for word in docPartitionWords] #Step 2.2, building a bag of words using gensim
tfidf_model = gensim.models.TfidfModel(bagsOfWords) #Step 3.1, using our previously saved list of paragraphs
tfidf_corpus = tfidf_model[bagsOfWords] #Step 3.2, applying a transformation to the vector
matrixSimilarity = gensim.similarities.MatrixSimilarity(bagsOfWords) #Step 3.3, constructing a MatrixSimiliarity object
lsi_model = gensim.models.LsiModel(tfidf_corpus, id2word=dictionary, num_topics=100) #Step 3.4, constructing a simliarity matrix for an LSI-model
lsi_corpus = lsi_model[tfidf_corpus]
lsiMatrixSimilarity = gensim.similarities.MatrixSimilarity(lsi_corpus)
print("Lsi-model topics for the corpus:")
print(lsi_model.show_topics()) #Step 3.5, topic interpretations to be typed as a program comment in the next line
#The first three topics seems to be about about the finances behind employing manual workers, likely construction workers or the like that work on land. It also seems to refer to historical customs regarding employment and payment.
queryString = "What is the function of money?" #Step 4.1, line 62-66. Repeating the procedure from earlier to preprocess the query and convert it into a BOW expression
query = re.findall(r"[\w']+", queryString.lower())
for j in range(0, len(query)):
query[j] = stemmer.stem(query[j])
query = dictionary.doc2bow(query)
queryTfIdf = tfidf_model[query] #Step 4.2. From the print-statements below, I deduced that the TF-IDF weights are (money: 0.31, function: 0.95)
print("\nTF-IDF weights:", queryTfIdf)
print("Found TF-IDF terms:")
print(dictionary[806])
print(dictionary[1130])
doc2similarity = enumerate(matrixSimilarity[queryTfIdf]) #Step 4.3, line 73-84. Applying the query to the matrix similarity calculation. My code, using the query 'How taxes influence Economics?' ommited paragraph 379, instead giving paragraph 1882, but it still kept paragraph 2003 and 2013
print("\nDocuments similarity with TF-IDF-model:")
print(sorted(doc2similarity, key=lambda kv: -kv[1])[:3]) #Sorting documents by similarity values
relevantParagraphs = [49, 676, 987] # The found paragraphs as indices
print("\nTF-IDF-model top 3 relevant paragraphs:") #The following lines is just truncating the paragraphs to 5 lines
for i in relevantParagraphs:
lines = docPartition[i].split("\n")
counter = 0
print("Paragraph:", i + 1)
for r in range(0, len(lines)):
if counter < 5:
print(lines[r])
counter += 1
print("\n")
queryLsi = lsi_model[queryTfIdf] #Step 4.4, through the rest of this file. In the previous step, testing the query 'How taxes influence Economics?' gave one wrong document representation, but the topics representation was correct here, being topics 3, 5 and 9
print("\nLsi-model topics:")
print(sorted(queryLsi, key=lambda kv: -abs(kv[1]))[:3]) #Sorting weights by absolute values"
topics = [4, 16, 61] # The found topics in indices
print("\nLsi-model top 3 relevant topics with terms:")
for topic in topics:
print("Topic:", topic)
print(lsi_model.show_topic(topic))
doc2similarity = enumerate(lsiMatrixSimilarity[queryLsi])
print("\nDocument similarity with Lsi-model:")
print(sorted(doc2similarity, key=lambda kv: -kv[1])[:3]) #Sorting documents by similarity values
relevantParagraphs = [987, 1002, 1003] # The found paragraphs as indices. We can see that paragraph index 987 is found again. This was also the case when trying the query 'How taxes influence Economics?', but sharing the "replaced" paragraph which I described earlier in the document
print("\nLsi-model top 3 relevant paragraphs:") #Parsing like with the TF-IDF-model
for k in relevantParagraphs:
lines = docPartition[k].split("\n")
counter = 0
print("Paragraph:", k + 1)
for s in range(0, len(lines)):
if counter < 5:
print(lines[s])
counter += 1
print("\n")
print("End of program")
| [
"noreply@github.com"
] | noreply@github.com |
b5856a92fb5f08c6cc16acb148094a51ccad7109 | 87143713666ccb28a5b5b72ac046ef003835fb02 | /whats_your_name.py | 5e97e60269320133fd20e2336c60849fd56a467f | [] | no_license | zodiacR/hackerrank_python | 3c76f457b697ee0a1bae7e1816f1ec0359f78c9e | 0104c96bf2eb8498981bc384cb87b2035523a4e7 | refs/heads/master | 2021-01-01T18:11:59.500877 | 2015-03-19T01:20:57 | 2015-03-19T01:20:57 | 32,257,049 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 121 | py | firstname = raw_input()
lastname = raw_input()
print "Hello %s %s! You just delved into python." % (firstname, lastname)
| [
"eminemhe@163.com"
] | eminemhe@163.com |
6b9d9cb08643c389b3521d474805c579b9985e06 | d6a152b8662af82ec604fa63c5c415dc6b59699b | /aeshin/settings.py | 70a75e24b58f9aa5ff4c1165e6113aeb7a401c45 | [] | no_license | rybesh/aeshin | 7cf433ba93309f49e2ff676c2d4568244f81ee52 | 292867a8b80031cacfce70c67387c656c3cb191b | refs/heads/master | 2023-08-19T00:17:40.042842 | 2023-08-17T17:47:55 | 2023-08-17T17:47:55 | 22,109,808 | 0 | 0 | null | 2023-09-05T14:05:34 | 2014-07-22T15:40:33 | Python | UTF-8 | Python | false | false | 5,121 | py | import os
import environ
from pathlib import Path
from django.db.models.query import QuerySet
# environment variables -------------------------------------------------------
BASE_DIR = Path(__file__).resolve().parent.parent
environ.Env.read_env(BASE_DIR / ".env")
env = environ.Env(DEBUG=(bool, False))
# typing ----------------------------------------------------------------------
QuerySet.__class_getitem__ = classmethod(
lambda cls, *args, **kwargs: cls # pyright: ignore
)
# database --------------------------------------------------------------------
DATABASES = {"default": env.db()}
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
# debugging -------------------------------------------------------------------
DEBUG = env("DEBUG")
TEMPLATE_DEBUG = False
# logging ---------------------------------------------------------------------
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"level": "INFO",
"class": "logging.StreamHandler",
},
"mail_admins": {
"level": "ERROR",
"class": "django.utils.log.AdminEmailHandler",
"include_html": False,
},
},
"loggers": {
"django": {
"handlers": ["console"],
"level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
},
"django.request": {
"handlers": ["mail_admins"],
"level": "ERROR",
},
},
}
# email -----------------------------------------------------------------------
ADMINS = (("Ryan Shaw", "rieyin@icloud.com"),)
MANAGERS = ADMINS
DEFAULT_FROM_EMAIL = "aeshin.org <no-reply@aeshin.org>"
SERVER_EMAIL = DEFAULT_FROM_EMAIL
EMAIL_HOST = "email-smtp.us-east-1.amazonaws.com"
EMAIL_HOST_USER = env("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# file uploads ----------------------------------------------------------------
MEDIA_ROOT = env.path("MEDIA_ROOT", default=BASE_DIR / "media/")
MEDIA_URL = "files/"
# globalization ---------------------------------------------------------------
LANGUAGE_CODE = "en-us"
TIME_ZONE = "US/Eastern"
USE_I18N = False
USE_TZ = True
# http ------------------------------------------------------------------------
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"aeshin.middleware.WWWRedirectMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
WSGI_APPLICATION = "aeshin.wsgi.application"
# models ----------------------------------------------------------------------
INSTALLED_APPS = (
"aeshin",
"shared",
"courses",
"files",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"whitenoise.runserver_nostatic",
"django.contrib.staticfiles",
"django.contrib.sites",
)
# security --------------------------------------------------------------------
SECRET_KEY = env("SECRET_KEY")
ALLOWED_HOSTS = [
".aeshin.org",
".localhost",
"127.0.0.1",
"[::1]",
"aeshin.fly.dev",
]
CSRF_TRUSTED_ORIGINS = [
"https://*.aeshin.org",
"https://aeshin.fly.dev",
]
# templates -------------------------------------------------------------------
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.template.context_processors.request",
]
},
}
]
# urls ------------------------------------------------------------------------
ROOT_URLCONF = "aeshin.urls"
# django.contrib.auth ---------------------------------------------------------
LOGIN_URL = "/login/"
LOGIN_REDIRECT_URL = "/loggedin/"
LOGOUT_URL = "/logout/"
# django.contrib.sites --------------------------------------------------------
SITE_ID = 1
# django.contrib.staticfiles --------------------------------------------------
STATIC_ROOT = BASE_DIR / "static"
STATIC_URL = "/static/"
STORAGES = {
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"
},
}
# shared ----------------------------------------------------------------------
ZOTERO_GROUP_ID = "51755"
| [
"ryanshaw@unc.edu"
] | ryanshaw@unc.edu |
f98fe3da7f86c17e31a52248b05b0bc2347779f1 | 8bc80c74bcabbf2de18c90d084d55734815ebf23 | /env/lib/python2.7/site-packages/kaa/metadata/games/core.py | 34e9c537eb3f0e420c08512735fabd963b2edda6 | [] | no_license | jpmunz/smartplayer | 18c8397ac8f822f67111608255d029d3594cc7b5 | 1a75e48dae55876f04718cfd594cfc6e43e5c966 | refs/heads/master | 2020-05-30T10:08:25.670517 | 2013-11-24T00:26:39 | 2013-11-24T00:26:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,499 | py | # -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# core.py - basic glames class
# -----------------------------------------------------------------------------
# $Id: core.py 2578 2007-03-21 19:49:31Z tack $
#
# -----------------------------------------------------------------------------
# kaa-Metadata - Media Metadata for Python
# Copyright (C) 2003-2006 Thomas Schueppel, Dirk Meyer
#
# First Edition: Thomas Schueppel <stain@acm.org>
# Maintainer: Dirk Meyer <dischi@freevo.org>
#
# Please see the file AUTHORS for a complete list of authors.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MER-
# CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# -----------------------------------------------------------------------------
from kaa.metadata.core import ParseError, Media, MEDIA_GAME
class Game(Media):
media = MEDIA_GAME
| [
"jp_137@hotmail.com"
] | jp_137@hotmail.com |
81057bf178af29a10d63013774898c5776e40e36 | f74495329b901b7e6db01c40484e9ca80ab3f98a | /torpedo/dialects/torpedo-vertica/run_test.py | dd67e5125e705853df24337b26e3c1ccf24174b2 | [
"MIT"
] | permissive | darKoram/torpedo | 38c82a2e0740d959753b849489d9953af9caff58 | fbda29225044e946465bae3782a3071d0d1a2fe3 | refs/heads/master | 2021-01-19T08:36:03.461984 | 2015-01-14T01:49:04 | 2015-01-14T01:49:04 | 28,483,957 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 428 | py | __author__ = 'kbroughton'
from sqlalchemy.dialects import registry
registry.register("vertica", "torpedo_vertica.pyodbc", "Vertica_pyodbc")
registry.register("vertica.pyodbc", "torpedo_vertica.pyodbc", "Vertica_pyodbc")
from torpedo.testing import runner
# use this in setup.py 'test_suite':
# test_suite="run_tests.setup_py_test"
def setup_py_test():
runner.setup_py_test()
if __name__ == '__main__':
runner.main() | [
"kesten.broughton@gmail.com"
] | kesten.broughton@gmail.com |
dec6855f23e4486a908005bdc9639176cf10c7b6 | 44020d9ad6598034be48fc21ee257d6b23064731 | /2.fact.py | 2f1b2461287a1e86c910f8f3f768d5d3fafc8559 | [] | no_license | Prasanth4u/Code-kata-BEGINNER | ddd3d45a6e07f6657c8224535649afe1b4178fa9 | 755270e04903df53526fe651bc438fb1be233a00 | refs/heads/master | 2021-10-06T11:19:50.788992 | 2021-09-28T05:12:33 | 2021-09-28T05:12:33 | 194,237,057 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 67 | py | num=int(input())
fu=1
for k in range(1,num+1):
fu=fu*k
print(fu)
| [
"noreply@github.com"
] | noreply@github.com |
f18064f11e7ff280cd49df7a883da12f57c367d4 | 1672ce2f69d73d071d76ca435dcfb0249a5b91ac | /packageML01/Practical21.py | 08edf0c6e64cdc081df35c0fad72867751013578 | [] | no_license | rishabhostwal7/Python | 661b2055bf67fc2691f1c45bca54179dd2b12a85 | 7af0088af271b55913cf58a582f5cb2c78100090 | refs/heads/master | 2020-06-08T12:36:47.752957 | 2019-06-24T08:41:26 | 2019-06-24T08:41:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 471 | py | #List
'''
a = list() #Used to make empty Array
print(a)
b = [] #Used to make empty Array
print(b)
#although the array is empty but all the functions related to it will be available like append(), index() etc..
a.append("Hello")
a.append(43)
print(a)
b.insert(1,33)
b.insert(4,45)
print(b)
'''
myList = list(range(1,11))
print(myList, type(myList)) # this is expanded view
myList = range(1,11)
print(myList) # this is compact view
| [
"noreply@github.com"
] | noreply@github.com |
a0c19df6701d9732f9a48f1f63fd52276f762f5d | d9493d0be13bd699529311e0f7a5e043ac0b9209 | /emojifier/settings.py | 98d2a71e218a1b2224c89158c18fc821e80c7a58 | [] | no_license | Aakashmangla2000/EmojiPredictor | fc9b50c1d850fa878edcb4229da587e589fdd4ab | 40a48cefdc96843e97e428d6fe658d209399b043 | refs/heads/master | 2022-12-16T02:05:11.653350 | 2020-09-15T19:58:36 | 2020-09-15T19:58:36 | 295,759,529 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,177 | py | """
Django settings for emojifier project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q2p*&orxo+88+jizk^=g&)(4k6lwl2f3pn!24=9ny$()ce=)u-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'*'
]
# Application definition
INSTALLED_APPS = [
# 'main',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'emojifier.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'emojifier.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
| [
"akkibaby90@yahoo.com"
] | akkibaby90@yahoo.com |
b5144f06cc3713139c312970808a6cb808893548 | 4b8649a76866f01f56600ed92990a3dab72fda88 | /migrations/versions/e6c127d4a2f8_posts_table.py | a25f4534ca1c5ee5420bdc123a953ff0009980d0 | [] | no_license | kakamband/Course-update-for-Heroku | b8127a1df79f8243ba00e111a53e1fa453c08bf1 | ca8728e44da24e72ca1b5b1328942b184a4548bb | refs/heads/main | 2023-02-06T03:55:20.378627 | 2020-12-30T10:41:26 | 2020-12-30T10:41:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,057 | py | """posts table
Revision ID: e6c127d4a2f8
Revises: 8c6ba432428e
Create Date: 2020-07-12 01:50:32.704470
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e6c127d4a2f8'
down_revision = '8c6ba432428e'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('post',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('body', sa.String(length=140), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_post_timestamp'), 'post', ['timestamp'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_post_timestamp'), table_name='post')
op.drop_table('post')
# ### end Alembic commands ###
| [
"64434778+Tu1026@users.noreply.github.com"
] | 64434778+Tu1026@users.noreply.github.com |
10acf3a449106406e736fd14d47a73863d04c8a5 | b16e1c10de55b34bb0216a01cd39dceb2e31cf93 | /ASNE.py | 0ac4dac7cfbc73f59948b98fd86fa3df70f9de57 | [] | no_license | wanggx1997/test | 5746b9b8069baecfe3bfcbbe92efa85f1a984385 | 99ee3c5efb18f148419917bd278adff697d4a893 | refs/heads/main | 2022-12-27T18:30:17.087049 | 2020-10-12T11:49:29 | 2020-10-12T11:49:29 | 303,265,233 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 51 | py | import torch
file numpy
hhhh
niubibuniubiaaaahdso
| [
"noreply@github.com"
] | noreply@github.com |
60a40d9fedcd8012982559b55dd2ba906414b7cf | 65d563496bdd0b83c63faeb8a7852664277a3e95 | /hot_cold.py | 1d24351c902f6cc74a17aa744220f9c14dd4452c | [] | no_license | Ziem0/RogueGame | b56fd5439bc9624ca0cb546f942728c85a98fdd0 | 061e1dad288765261a03a9ebaae691ead0ae9722 | refs/heads/master | 2021-05-14T07:48:33.938352 | 2018-01-04T15:39:30 | 2018-01-04T15:39:30 | 116,276,297 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,878 | py | import random
import os
import sys
import time
from update_inventory import inventory
from screens import *
def run_game():
random_digit = draw_digits()
print(random_digit)
random_digit_list = list(random_digit)
tries = 1
while True:
count_hot = 0
count_warm = 0
count_cold = 0
print('Guess #', tries)
digit_input = guess_digit()
digit_input_list = check_digit(digit_input, random_digit_list)
tries += 1
if inventory['bullets'] == 0:
os.system('clear')
game_over()
sys.exit()
if digit_input_list == random_digit_list:
os.system('clear')
win_game()
def draw_digits():
random_digit = range(100, 1000)
random_digit = str(random.choice(random_digit))
return random_digit
def guess_digit():
digit_input = 0
while True:
try:
digit_input = int(input("Guess digit: "))
except ValueError:
print("Try again. Enter 3 digits.")
continue
if len(str(digit_input)) != 3:
print("Try again. Enter 3 digits.")
continue
else:
break
return str(digit_input)
def check_digit(digit_input, random_digit_list):
count_hot = 0
count_warm = 0
count_cold = 0
digit_input_list = list(digit_input)
index_of_hot = []
for item in range(len(digit_input_list)):
if digit_input_list[item] == random_digit_list[item]:
count_hot += 1
index_of_hot.append(item)
list_to_check_warm = [0, 1, 2]
for i in range(len(index_of_hot)):
list_to_check_warm.remove(index_of_hot[i])
for i in list_to_check_warm:
if digit_input_list[i] in random_digit_list:
count_warm += 1
else:
count_cold += 1
if count_cold == 3:
print("Cold")
inventory['bullets'] -= 1
else:
print("Hot " * count_hot, " Warm " * count_warm)
inventory['bullets'] -= 1
print("bullets: {}".format(inventory['bullets']))
return digit_input_list
def game_over():
'''Print last highscores and game over'''
os.system('clear')
you_lost()
print ("\n\n\n\n\n\nLast highscores:\n")
highscores = open('score.txt').read()
print (highscores)
def win_game():
'''Save the winner score to txt file, print last highscores and print you are the master of thieves'''
os.system('clear')
you_won()
highscores = open('score.txt').read()
print ("\n\n\n\n\nLast highscores:\n" + highscores)
name = input('\n\n\nWhat is your name? ')
fh = open('score.txt', 'a')
fh.write('Name: ' + name + " ")
fh.write("Dollars: " + str(inventory['dollars']) + " \n")
fh.close()
print ('Your score has been added')
sys.exit()
| [
"andrzejewski.ziemo@gmail.com"
] | andrzejewski.ziemo@gmail.com |
19f6e67861ab134248e41bbd401e02c34aa98d27 | db6abec863b9d668388b2a731be3dcd5bb04d00e | /Automate the Boring Stuff/feelingLucky.py | dd52be91219855f0aed8d7bf1923b628633ec8fc | [] | no_license | mikitsuba/Python_Study | d65de5e2737798c36922416d42e1de23607d5be9 | 15e7bea56ec75228b6176f6880c40bd9d8c7be8b | refs/heads/master | 2021-04-13T04:27:01.058482 | 2020-05-05T05:26:20 | 2020-05-05T05:26:20 | 249,136,521 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 839 | py | #! /usr/bin/env python3
import sys
import requests
import webbrowser
import bs4
# 検索ワード
query = ' '.join(sys.argv[1:])
print('Googling "{}"...'.format(query))
query = '+'.join(sys.argv[1:])
# コマンドラインに入力した引数をjoinしてgoogle検索
res = requests.get('https://www.google.com/search?q=' + query)
# urlを正しく読み込めているかチェック
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
link_elems = soup.select('div.r a')
# 各結果をブラウザのタブで開く
num_open = min(5, len(link_elems)) # 開く結果の数を指定。検索結果の数と5の小さい方
for i in range(num_open):
print('Opening "https://wwww.google.com{}"...'.format(link_elems[i].get('href')))
webbrowser.open('https://wwww.google.com' + link_elems[i].get('href'))
| [
"mikitsuba@Tsubasas-iMac.local"
] | mikitsuba@Tsubasas-iMac.local |
6b481b75639a36ee3c439a151988f25c85d6cadd | 71b3766d0641361a52f62af263fe8efa90fccbab | /blog/views.py | 592ccebccef4e17cd3162123c7aec7c0189fc55e | [] | no_license | firchatn/Blog-Website | bd4859774fda9cccc60f4eaa4c322cbc0d80d487 | 04663501b442f51f14e0b5fdc1f188488172c455 | refs/heads/master | 2021-05-05T15:10:29.114072 | 2018-11-02T09:45:32 | 2018-11-02T09:45:32 | 103,161,430 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 983 | py | from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Article, Catecory
# Create your views here.
def index(request):
articless = Article.objects.all()
catecory = Catecory.objects.all()
page = request.GET.get('page')
cat = request.GET.get('cat')
if cat:
cat = Catecory.objects.get(name=cat)
articless = Article.objects.filter(catecory=cat)
paginator = Paginator(articless, 2) # Show 25 contacts per page
try:
article = paginator.page(page)
except PageNotAnInteger:
article = paginator.page(1)
except EmptyPage:
article = paginator.page(paginator.num_pages)
# TODO: admin valid article before add it to the blog
# article = Article.objects.filter(isreviewed=True)
toplast = Article.objects.all()[:3]
return render(request,'blog/index.html', {'article' : article , 'toplast' : toplast, 'catecory' : catecory })
def contact(request):
return render(request,'blog/contact.html') | [
"firaschaabencss@gmail.com"
] | firaschaabencss@gmail.com |
950a8fb5d1a3d7d8c0d157c492ea4e6fe1b4e665 | 31b8cc3ed4e694f1c507d52750d2da9afc7ebb3b | /hw2/client.py | f0ae8f687f22394a3a2e8233aff93e33e5124a5c | [] | no_license | frap129/CS351 | 6c3b247fbf113cc10d25ff6e8425a00f681f518d | b9f3b0d647b837fc90c728400eb7d92251aea0a5 | refs/heads/master | 2022-09-29T02:24:57.877978 | 2020-06-02T21:18:26 | 2020-06-02T21:18:26 | 255,609,517 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 872 | py | #!/usr/bin/python3
import sys
import socket
# Configurables
filePath = "example.txt"
serverIP = "54.235.47.119"
# Argument Parsing
if (len(sys.argv) >= 2):
filePath = sys.argv[1]
if (len(sys.argv) == 3):
serverIP = sys.argv[2]
# Constants
serverPort = 351 # CS-351, to be exact
fileSizeLimit = 1024
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
print("Connecting to " + serverIP + ":" + serverPort.__str__())
clientSocket.connect((serverIP, serverPort))
print("Connected!")
# Read File
print("Sending file...")
file = open(filePath, 'rb')
fileBuffer = file.read(fileSizeLimit)
# Send File
clientSocket.send(fileBuffer)
file.close()
# Get Server response
print(clientSocket.recv(fileSizeLimit).decode('utf-8'))
# Close connection
print("Closing connection")
clientSocket.shutdown(socket.SHUT_WR)
clientSocket.close()
| [
"joe@maples.dev"
] | joe@maples.dev |
efe34cb92a79af37bb8543e60c8e2e2406f2d995 | 544cfadc742536618168fc80a5bd81a35a5f2c99 | /tools/test/connectivity/acts_tests/tests/google/gnss/FlpTtffTest.py | 59b19b52f02ad880d66a9f081f34023770f3b823 | [] | no_license | ZYHGOD-1/Aosp11 | 0400619993b559bf4380db2da0addfa9cccd698d | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | refs/heads/main | 2023-04-21T20:13:54.629813 | 2021-05-22T05:28:21 | 2021-05-22T05:28:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,611 | py | #!/usr/bin/env python3.5
#
# Copyright 2019 - The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from acts import utils
from acts import asserts
from acts import signals
from acts.base_test import BaseTestClass
from acts.test_decorators import test_tracker_info
from acts.utils import get_current_epoch_time
from acts_contrib.test_utils.wifi.wifi_test_utils import wifi_toggle_state
from acts_contrib.test_utils.tel.tel_test_utils import start_qxdm_logger
from acts_contrib.test_utils.tel.tel_test_utils import stop_qxdm_logger
from acts_contrib.test_utils.tel.tel_test_utils import verify_internet_connection
from acts_contrib.test_utils.tel.tel_test_utils import abort_all_tests
from acts_contrib.test_utils.gnss.gnss_test_utils import get_baseband_and_gms_version
from acts_contrib.test_utils.gnss.gnss_test_utils import _init_device
from acts_contrib.test_utils.gnss.gnss_test_utils import check_location_service
from acts_contrib.test_utils.gnss.gnss_test_utils import clear_logd_gnss_qxdm_log
from acts_contrib.test_utils.gnss.gnss_test_utils import set_mobile_data
from acts_contrib.test_utils.gnss.gnss_test_utils import get_gnss_qxdm_log
from acts_contrib.test_utils.gnss.gnss_test_utils import set_wifi_and_bt_scanning
from acts_contrib.test_utils.gnss.gnss_test_utils import process_gnss_by_gtw_gpstool
from acts_contrib.test_utils.gnss.gnss_test_utils import start_ttff_by_gtw_gpstool
from acts_contrib.test_utils.gnss.gnss_test_utils import process_ttff_by_gtw_gpstool
from acts_contrib.test_utils.gnss.gnss_test_utils import check_ttff_data
from acts_contrib.test_utils.gnss.gnss_test_utils import set_attenuator_gnss_signal
from acts_contrib.test_utils.gnss.gnss_test_utils import connect_to_wifi_network
from acts_contrib.test_utils.gnss.gnss_test_utils import gnss_tracking_via_gtw_gpstool
from acts_contrib.test_utils.gnss.gnss_test_utils import parse_gtw_gpstool_log
from acts_contrib.test_utils.tel.tel_test_utils import start_adb_tcpdump
from acts_contrib.test_utils.tel.tel_test_utils import stop_adb_tcpdump
from acts_contrib.test_utils.tel.tel_test_utils import get_tcpdump_log
class FlpTtffTest(BaseTestClass):
""" FLP TTFF Tests"""
def setup_class(self):
super().setup_class()
self.ad = self.android_devices[0]
req_params = ["pixel_lab_network", "standalone_cs_criteria",
"qdsp6m_path", "flp_ttff_max_threshold",
"pixel_lab_location", "default_gnss_signal_attenuation",
"weak_gnss_signal_attenuation", "ttff_test_cycle",
"collect_logs"]
self.unpack_userparams(req_param_names=req_params)
self.ssid_map = {}
for network in self.pixel_lab_network:
SSID = network['SSID']
self.ssid_map[SSID] = network
if int(self.ad.adb.shell("settings get global airplane_mode_on")) != 0:
self.ad.log.info("Force airplane mode off")
force_airplane_mode(self.ad, False)
_init_device(self.ad)
def setup_test(self):
get_baseband_and_gms_version(self.ad)
if self.collect_logs:
clear_logd_gnss_qxdm_log(self.ad)
set_attenuator_gnss_signal(self.ad, self.attenuators,
self.default_gnss_signal_attenuation)
if not verify_internet_connection(self.ad.log, self.ad, retries=3,
expected_state=True):
raise signals.TestFailure("Fail to connect to LTE network.")
def teardown_test(self):
if self.collect_logs:
stop_qxdm_logger(self.ad)
stop_adb_tcpdump(self.ad)
set_attenuator_gnss_signal(self.ad, self.attenuators,
self.default_gnss_signal_attenuation)
if int(self.ad.adb.shell("settings get global mobile_data")) != 1:
set_mobile_data(self.ad, True)
if int(self.ad.adb.shell(
"settings get global wifi_scan_always_enabled")) != 1:
set_wifi_and_bt_scanning(self.ad, True)
if self.ad.droid.wifiCheckState():
wifi_toggle_state(self.ad, False)
def on_pass(self, test_name, begin_time):
if self.collect_logs:
self.ad.take_bug_report(test_name, begin_time)
get_gnss_qxdm_log(self.ad, self.qdsp6m_path)
get_tcpdump_log(self.ad, test_name, begin_time)
def on_fail(self, test_name, begin_time):
if self.collect_logs:
self.ad.take_bug_report(test_name, begin_time)
get_gnss_qxdm_log(self.ad, self.qdsp6m_path)
get_tcpdump_log(self.ad, test_name, begin_time)
""" Helper Functions """
def flp_ttff_hs_and_cs(self, criteria, location):
flp_results = []
ttff = {"hs": "Hot Start", "cs": "Cold Start"}
for mode in ttff.keys():
begin_time = get_current_epoch_time()
process_gnss_by_gtw_gpstool(
self.ad, self.standalone_cs_criteria, type="flp")
start_ttff_by_gtw_gpstool(
self.ad, ttff_mode=mode, iteration=self.ttff_test_cycle)
ttff_data = process_ttff_by_gtw_gpstool(
self.ad, begin_time, location, type="flp")
result = check_ttff_data(self.ad, ttff_data, ttff[mode], criteria)
flp_results.append(result)
asserts.assert_true(
all(flp_results), "FLP TTFF fails to reach designated criteria")
def start_qxdm_and_tcpdump_log(self):
"""Start QXDM and adb tcpdump if collect_logs is True."""
if self.collect_logs:
start_qxdm_logger(self.ad, get_current_epoch_time())
start_adb_tcpdump(self.ad)
""" Test Cases """
@test_tracker_info(uuid="c11ada6a-d7ad-4dc8-9d4a-0ae3cb9dfa8e")
def test_flp_one_hour_tracking(self):
"""Verify FLP tracking performance of position error.
Steps:
1. Launch GTW_GPSTool.
2. FLP tracking for 60 minutes.
Expected Results:
DUT could finish 60 minutes test and output track data.
"""
self.start_qxdm_and_tcpdump_log()
gnss_tracking_via_gtw_gpstool(self.ad, self.standalone_cs_criteria,
type="flp", testtime=60)
parse_gtw_gpstool_log(self.ad, self.pixel_lab_location, type="flp")
@test_tracker_info(uuid="8bc4e82d-fdce-4ee8-af8c-5e4a925b5360")
def test_flp_ttff_strong_signal_wifiscan_on_wifi_connect(self):
"""Verify FLP TTFF Hot Start and Cold Start under strong GNSS signals
with WiFi scanning on and connected.
Steps:
1. Enable WiFi scanning in location setting.
2. Connect to WiFi AP.
3. TTFF Hot Start for 10 iteration.
4. TTFF Cold Start for 10 iteration.
Expected Results:
Both FLP TTFF Hot Start and Cold Start results should be within
flp_ttff_max_threshold.
"""
self.start_qxdm_and_tcpdump_log()
set_wifi_and_bt_scanning(self.ad, True)
wifi_toggle_state(self.ad, True)
connect_to_wifi_network(
self.ad, self.ssid_map[self.pixel_lab_network[0]["SSID"]])
self.flp_ttff_hs_and_cs(self.flp_ttff_max_threshold,
self.pixel_lab_location)
@test_tracker_info(uuid="adc1a0c7-3635-420d-9481-0f5816c58334")
def test_flp_ttff_strong_signal_wifiscan_on_wifi_not_connect(self):
"""Verify FLP TTFF Hot Start and Cold Start under strong GNSS signals
with WiFi scanning on and not connected.
Steps:
1. Enable WiFi scanning in location setting.
2. WiFi is not connected.
3. TTFF Hot Start for 10 iteration.
4. TTFF Cold Start for 10 iteration.
Expected Results:
Both FLP TTFF Hot Start and Cold Start results should be within
flp_ttff_max_threshold.
"""
self.start_qxdm_and_tcpdump_log()
set_wifi_and_bt_scanning(self.ad, True)
self.flp_ttff_hs_and_cs(self.flp_ttff_max_threshold,
self.pixel_lab_location)
@test_tracker_info(uuid="3ec3cee2-b881-4c61-9df1-b6b81fcd4527")
def test_flp_ttff_strong_signal_wifiscan_off(self):
"""Verify FLP TTFF Hot Start and Cold Start with WiFi scanning OFF
under strong GNSS signals.
Steps:
1. Disable WiFi scanning in location setting.
2. TTFF Hot Start for 10 iteration.
3. TTFF Cold Start for 10 iteration.
Expected Results:
Both FLP TTFF Hot Start and Cold Start results should be within
flp_ttff_max_threshold.
"""
self.start_qxdm_and_tcpdump_log()
set_wifi_and_bt_scanning(self.ad, False)
self.flp_ttff_hs_and_cs(self.flp_ttff_max_threshold,
self.pixel_lab_location)
@test_tracker_info(uuid="03c0d34f-8312-48d5-8753-93b09151233a")
def test_flp_ttff_weak_signal_wifiscan_on_wifi_connect(self):
"""Verify FLP TTFF Hot Start and Cold Start under Weak GNSS signals
with WiFi scanning on and connected
Steps:
1. Set attenuation value to weak GNSS signal.
2. Enable WiFi scanning in location setting.
3. Connect to WiFi AP.
4. TTFF Hot Start for 10 iteration.
5. TTFF Cold Start for 10 iteration.
Expected Results:
Both FLP TTFF Hot Start and Cold Start results should be within
flp_ttff_max_threshold.
"""
set_attenuator_gnss_signal(self.ad, self.attenuators,
self.weak_gnss_signal_attenuation)
self.start_qxdm_and_tcpdump_log()
set_wifi_and_bt_scanning(self.ad, True)
wifi_toggle_state(self.ad, True)
connect_to_wifi_network(
self.ad, self.ssid_map[self.pixel_lab_network[0]["SSID"]])
self.flp_ttff_hs_and_cs(self.flp_ttff_max_threshold,
self.pixel_lab_location)
@test_tracker_info(uuid="13daf7b3-5ac5-4107-b3dc-a3a8b5589fed")
def test_flp_ttff_weak_signal_wifiscan_on_wifi_not_connect(self):
"""Verify FLP TTFF Hot Start and Cold Start under Weak GNSS signals
with WiFi scanning on and not connected.
Steps:
1. Set attenuation value to weak GNSS signal.
2. Enable WiFi scanning in location setting.
3. WiFi is not connected.
4. TTFF Hot Start for 10 iteration.
5. TTFF Cold Start for 10 iteration.
Expected Results:
Both FLP TTFF Hot Start and Cold Start results should be within
flp_ttff_max_threshold.
"""
set_attenuator_gnss_signal(self.ad, self.attenuators,
self.weak_gnss_signal_attenuation)
self.start_qxdm_and_tcpdump_log()
set_wifi_and_bt_scanning(self.ad, True)
self.flp_ttff_hs_and_cs(self.flp_ttff_max_threshold,
self.pixel_lab_location)
@test_tracker_info(uuid="1831f80f-099f-46d2-b484-f332046d5a4d")
def test_flp_ttff_weak_signal_wifiscan_off(self):
"""Verify FLP TTFF Hot Start and Cold Start with WiFi scanning OFF
under weak GNSS signals.
Steps:
1. Set attenuation value to weak GNSS signal.
2. Disable WiFi scanning in location setting.
3. TTFF Hot Start for 10 iteration.
4. TTFF Cold Start for 10 iteration.
Expected Results:
Both FLP TTFF Hot Start and Cold Start results should be within
flp_ttff_max_threshold.
"""
set_attenuator_gnss_signal(self.ad, self.attenuators,
self.weak_gnss_signal_attenuation)
self.start_qxdm_and_tcpdump_log()
set_wifi_and_bt_scanning(self.ad, False)
self.flp_ttff_hs_and_cs(self.flp_ttff_max_threshold,
self.pixel_lab_location)
| [
"rick_tan@qq.com"
] | rick_tan@qq.com |
03dd4d1ddaa82f1ed39556e626b5323b72cb8e7b | eac69a9709042f66a5a6a26992d05ddc9fe2508b | /python/sample/extension_usage.py | 6f1d70fae0146281dc9e14a8db704a928dcebe56 | [] | no_license | koalanlp/sample | 395aa557b674c5595aa072522178d8db2a4929f7 | 9fc9aceb7ec569d6ffa9dbea2e50ded9a081ae6e | refs/heads/master | 2022-12-20T05:32:45.695775 | 2019-12-13T06:43:45 | 2019-12-13T06:43:45 | 147,672,350 | 2 | 4 | null | 2022-12-08T20:53:30 | 2018-09-06T12:45:27 | Scala | UTF-8 | Python | false | false | 5,140 | py | from koalanlp.Util import initialize, finalize
from koalanlp import ExtUtil
initialize(CORE="LATEST")
# 한글 여부 확인
print("ExtUtil.isHangul('가') = %s" % (str(ExtUtil.isHangul('가')))) #: [True]
print("ExtUtil.isHangul('ㄱ') = %s" % (str(ExtUtil.isHangul('ㄱ')))) #: [True]
print("ExtUtil.isHangul('a') = %s" % (str(ExtUtil.isHangul('a')))) #: [False]
print("ExtUtil.isHangulEnding(\"갤럭시S는\") = %s" % (ExtUtil.isHangulEnding("갤럭시S는"))) #: True
print("ExtUtil.isHangulEnding(\"abc\") = %s" % (ExtUtil.isHangulEnding("abc"))) #: False
print("ExtUtil.isHangulEnding(\"보기 ㄱ\") = %s" % (ExtUtil.isHangulEnding("보기 ㄱ"))) #: True
print("ExtUtil.isCompleteHangul('가') = %s" % (ExtUtil.isCompleteHangul('가'))) #: [True]
print("ExtUtil.isCompleteHangul('ㄱ') = %s" % (ExtUtil.isCompleteHangul('ㄱ'))) #: [False]
print("ExtUtil.isCompleteHangul('a') = %s" % (ExtUtil.isCompleteHangul('a'))) #: [False]
# 종성으로 끝나는지 확인
print("ExtUtil.isJongsungEnding('각') = %s" % (ExtUtil.isJongsungEnding('각'))) #: True
print("ExtUtil.isJongsungEnding('가') = %s" % (ExtUtil.isJongsungEnding('가'))) #: False
print("ExtUtil.isJongsungEnding('m') = %s" % (ExtUtil.isJongsungEnding('m'))) #: False
# 초, 중, 종성 한글 자모 값으로 분해
print("ExtUtil.getChosung('가') = %s" % (ExtUtil.getChosung('가'))) #: 'ㄱ'에 해당하는 초성 문자 [\u1100]
print("ExtUtil.getJungsung('가') = %s" % (ExtUtil.getJungsung('가'))) #: 'ㅏ'에 해당하는 초성 문자 [\u1161]
print("ExtUtil.getJongsung('가') = %s" % (ExtUtil.getJongsung('가'))) #: [None]
print("ExtUtil.getJongsung('각') = %s" % (ExtUtil.getJongsung('각'))) #: 'ㄱ'에 해당하는 종성문자 [\u11A8]
print("ExtUtil.getChosung('ㄱ') = %s" % (ExtUtil.getChosung('ㄱ'))) #: [None]
print("ExtUtil.dissembleHangul('가') = %s" % (ExtUtil.dissembleHangul('가'))) #: '\u1100\u1161' (ᄀ ᅡ)
print("ExtUtil.dissembleHangul('각') = %s" % (ExtUtil.dissembleHangul('각'))) #: '\u1100\u1161\u11A8' (ᄀ ᅡ ᄀ)
print("ExtUtil.dissembleHangul(\"가각\") = %s" % (
ExtUtil.dissembleHangul("가각"))) #: "\u1100\u1161\u1100\u1161\u11A8" (문자 사이를 띄워서 표시하면: 'ᄀ ᅡ ᄀ ᅡ ᆨ')
# 종성 한글 자모값으로 변환
print("ExtUtil.ChoToJong['ㄵ'] = %s" % (ExtUtil.ChoToJong['ㄵ'])) #: \u11AC
# 한글 자모 범위에 속하는 초, 중, 종성인지 확인
print("ExtUtil.isChosungJamo('ㄱ') = %s" % (ExtUtil.isChosungJamo('ㄱ'))) #: [False]
print("ExtUtil.isChosungJamo('\u1100') = %s" % (ExtUtil.isChosungJamo('\u1100'))) #: [True]
print("ExtUtil.isJungsungJamo('ㅏ') = %s" % (ExtUtil.isJungsungJamo('ㅏ'))) #: [False]
print("ExtUtil.isJungsungJamo('\u1161') = %s" % (ExtUtil.isJungsungJamo('\u1161'))) #: [True]
print("ExtUtil.isJongsungJamo('ㄱ') = %s" % (ExtUtil.isJongsungJamo('ㄱ'))) #: [False]
print("ExtUtil.isJongsungJamo('\u11A8') = %s" % (ExtUtil.isJongsungJamo('\u11A8'))) #: [True]
# 한글 자모 결합
print("ExtUtil.assembleHangulTriple('\u1100', '\u1161', None) = %s" % (
ExtUtil.assembleHangulTriple('\u1100', '\u1161', None))) #: '가'
print("ExtUtil.assembleHangulTriple('\u1100', '\u1161', '\u11AB') = %s" % (
ExtUtil.assembleHangulTriple('\u1100', '\u1161', '\u11AB'))) #: '간'
print("ExtUtil.assembleHangul(\"\u1100\u1161\u1102\u1161\u11ab\") = %s" % (
ExtUtil.assembleHangul("\u1100\u1161\u1102\u1161\u11ab"))) #: "가난"
print("ExtUtil.assembleHangulTriple(jung='\u1161') = %s" % (ExtUtil.assembleHangulTriple(jung='\u1161'))) #: '아'
print("ExtUtil.assembleHangulTriple('\u1100', None, '\u11A8') = %s" % (
ExtUtil.assembleHangulTriple('\u1100', None, '\u11A8'))) #: '극'
print("ExtUtil.alphaToHangul(\"ABCD\") = %s" % (ExtUtil.alphaToHangul("ABCD"))) #: "에이비씨디"
print("ExtUtil.alphaToHangul(\"갤럭시S\") = %s" % (ExtUtil.alphaToHangul("갤럭시S"))) #: "갤럭시에스"
print("ExtUtil.alphaToHangul(\"cup\") = %s" % (ExtUtil.alphaToHangul("cup"))) #: "씨유피"
print("ExtUtil.isAlphaPronounced(\"에스비에스\") = %s" % (ExtUtil.isAlphaPronounced("에스비에스"))) #: True
print("ExtUtil.isAlphaPronounced(\"갤럭시에스\") = %s" % (ExtUtil.isAlphaPronounced("갤럭시에스"))) #: False
print("ExtUtil.hangulToAlpha(\"갤럭시에스\") = %s" % (ExtUtil.hangulToAlpha("갤럭시에스"))) #: "갤럭시S"
print("ExtUtil.hangulToAlpha(\"에이디에이치디\") = %s" % (ExtUtil.hangulToAlpha("에이디에이치디"))) #: "ADHD"
print("ExtUtil.isHanja('國') = %s" % (ExtUtil.isHanja('國'))) #: True
print("ExtUtil.isCJKHanja('國') = %s" % (ExtUtil.isCJKHanja('國'))) #: True
print("ExtUtil.hanjaToHangul(\"國篇\") = %s" % (ExtUtil.hanjaToHangul("國篇"))) #: "국편"
print("ExtUtil.hanjaToHangul(\"國篇은 오늘\") = %s" % (ExtUtil.hanjaToHangul("國篇은 오늘"))) #: "국편은 오늘"
print("ExtUtil.hanjaToHangul(\"300 兩의 돈\") = %s" % (ExtUtil.hanjaToHangul("300 兩의 돈"))) #: "300 냥의 돈"
print("ExtUtil.hanjaToHangul(\"樂園\") = %s" % (ExtUtil.hanjaToHangul("樂園"))) #: "낙원" (두음법칙)
finalize() | [
"cd4209@gmail.com"
] | cd4209@gmail.com |
47ac38c48ab6a0ffe276aa299b2b85a3c9afe994 | 1eba03a3a7b5f6133dfcbc7a0ab9c73f950a79d8 | /algorithms/137. Single Number II/main.py | 966d1c3f0ce2f52164f788ad395c5ee7fc2c6042 | [] | no_license | GTxx/leetcode | ab640cad726111a5fd78ecfbc02f75a61112bc2c | b7f85afe1c69f34f8c6025881224ae79042850d3 | refs/heads/master | 2021-06-15T18:43:41.358275 | 2021-05-08T08:15:05 | 2021-05-08T08:15:05 | 70,294,841 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 412 | py | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
x1 = 0
x2 = 0
for num in nums:
x2 ^= x1 & num
x1 ^= num
mask = ~(x1 & x2)
x2 &= mask
x1 &= mask
return x1
if __name__ == "__main__":
s = Solution()
print s.singleNumber([6,6,6,5]) | [
"xiongxiong1986@gmail.com"
] | xiongxiong1986@gmail.com |
af1990a9438f13257658b34ed98588888aa874d4 | 562d0885caee5682e32336c31ee0cb30cf29086e | /cogs/space.py | 82e0f4b8a8dcb034a8edc15ca0c6acf3147d0949 | [
"BSD-3-Clause"
] | permissive | Sgewux/discord_bot | 8e3e26b0d867fe267c568df0f55eccb296c48684 | bde7c587fc38f4eb0e80128519ffe57bdde84194 | refs/heads/master | 2023-06-14T14:07:07.841455 | 2021-07-13T23:00:50 | 2021-07-13T23:00:50 | 360,324,676 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,715 | py | import re
from discord.ext import commands
from cogs.bot_utilities.nasa_api import NasaApi
from cogs.bot_utilities.checks import CustomChecks
class SpaceCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._api = NasaApi()
@commands.command(pass_context=True, aliases=('APOD', 'apod'))
async def astronomy_picture_of_the_day(self, ctx):
"""Gives to the user the astronomy picture of the day"""
apod = self._api.get_apod()
if apod:
await ctx.send(f'Description 👨🚀:\n {apod[0]}\n {apod[1]}')
else:
await ctx.send('Something went wrong :(')
@commands.command(pass_context=True, aliases=('MRP', 'mrp'))
async def rover_photo(self, ctx):
"""Gives to the user a random photo taken by the mars rover"""
rover_photo = self._api.get_mars_rover_photo()
if rover_photo:
await ctx.message.reply(content=f'{rover_photo[0]}\nThis photo was taken in: {rover_photo[1]}\nCamera name: {rover_photo[2]}')
else:
await ctx.message.reply(content='Something went wrong :( \nPlease try again.')
@commands.command(pass_context=True, aliases=('MRPD', 'mrpd'))
async def rover_photo_by_date(self, ctx, *args):
"""Gives to the user a photo taken by the mars rover on a given date"""
date = '-'.join(args)
date_regex = re.compile(r'\d{4}-\d{1,2}-\d{1,2}')
if date_regex.search(date):
year, month, day = date.split('-')
if CustomChecks.is_valid_date(int(month), int(day), year=int(year)):
photo_url = self._api.get_rover_photo_by_date(date)
await ctx.message.reply(content=photo_url)
else:
await ctx.message.reply(content='That is an unexistent date.')
else:
await ctx.message.reply(content='That is not a date i\'m not dumb 😑')
| [
"sebasandroide05@gmail.com"
] | sebasandroide05@gmail.com |
675fabd4547dc5325753e8ebc150f81feeb3d8e0 | 474462e7f658ebf59033c170ef753eb96653622f | /Python/django/TimeDisplay/random_word/urls.py | d3ea6682a78a0886894b35a77d607262dde910b0 | [] | no_license | dathanwong/Dojo_Assignments | 33374e0c250293b39f92240ada3a5649892ce527 | 8347adf2d9606ae095be306c90c294303ef5574b | refs/heads/master | 2022-08-21T23:04:17.759342 | 2020-05-21T21:14:52 | 2020-05-21T21:14:52 | 259,776,556 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 205 | py | from django.urls import path
from . import views
urlpatterns = [
path('', views.random, name='home'),
path('/reset', views.reset, name='reset'),
path('/submit', views.submit, name='submit')
]
| [
"dathwo@outlook.com"
] | dathwo@outlook.com |
b453a974a15c7607874dfac71aada44e35b70b25 | da186f39159acc08346192f93b02d44fcf0cc20c | /scraper.py | 0edd80f78877992839476fa983d1f6f149f5cd64 | [] | no_license | bkurdasov/cened.it | 2f5eef1a75becf3b938772781d513139805ea5d4 | 44aa23f19c7dd6b2772e3df69959ea66aa10215a | refs/heads/master | 2020-05-20T07:16:10.410534 | 2015-04-13T11:16:53 | 2015-04-13T11:16:53 | 33,863,839 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,860 | py | import requests
from copy import copy
import re
import csv
from lxml.html import fromstring
def parse_doc(doc):
for item in doc.xpath('//tr[td[2][@valign and br]]'):
nome_cognome,titolo=item.xpath('td[2]/text()')
nome_cognome=nome_cognome.strip()
nome=nome_cognome.split(' ')[:-1]
nome=' '.join(nome)
cognome=nome_cognome.split(' ')[-1]
titolo=titolo.strip()[len('Titolo studio: '):]
telefono=item.xpath('td[4]/text()')[0]
email=item.xpath('td[5]/a/@href')[0][len('mailto:'):]
indirizzo=item.xpath('td[3]/text()')[0]
regexp=r"(?P<indirizzo>.*),\s(?P<cap>[\d\w]{1,})\s(?P<comune>[\w\s'\-`]+)\s\((?P<provincia>[\w\s'\-`]+)\),"
p=re.compile(regexp)
m=p.search(indirizzo)
if not m:
yield [titolo,nome,cognome,email,telefono,None,None,None,indirizzo]
indirizzo=m.group('indirizzo')
cap=m.group('cap')
comune=m.group('comune')
provincia=m.group('provincia')
yield [titolo,nome,cognome,email,telefono,comune,provincia,cap,indirizzo]
BASEURL='http://www.cened.it/mappa_certificatore?p_p_id=EXT_B80_MALO_INSTANCE_FNBN&p_p_lifecycle=0&p_p_state=normal&p_p_mode=view&p_p_col_id=colonna-2&p_p_col_pos=1&p_p_col_count=2&tabs1=Ricerca%20per%20provincia%20e%20comune%20o%20per%20nominativo'
s=requests.Session()
s.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0'})
r=s.get(BASEURL)
cookies=r.cookies
doc=fromstring(r.content)
XPATH='''//form/select/option'''
values=[]
for item in doc.xpath(XPATH):
if item.text!='...':
value=item.attrib.get('value') # same as item.text but just to be sure.
values.append(value)
with open('result.csv','wb') as outfile:
writer=csv.writer(outfile)
writer.writerow(['Titolo','Nome','Cognome','Email','Telefono','Comune','Provincia','CAP','Indirizzo'])
for value in values:
print "Processing provincia {:30}".format(value),
headers={'Referer': BASEURL,'Content-Type':'application/x-www-form-urlencoded'}
data={'malo.cityid':'',
'malo.cityname':'',
'malo.districtid':value,
'malo.districtname':value,
'malo.extprop1':'null',
'malo.extprop2':'null',
'malo.name':'',
'malo.searchtype':'provinceandcity',
'tabs1':'Ricerca per provincia e comune o per nominativo'}
pass
params={'_EXT_B80_MALO_INSTANCE_FNBN_struts_action':'/malo/view',
'_EXT_B80_MALO_INSTANCE_FNBN_tabs1':'Ricerca per provincia e comune o per nominativo',
'p_p_col_count':'2',
'p_p_col_id':'colonna-2',
'p_p_col_pos':'1',
'p_p_id':'EXT_B80_MALO_INSTANCE_FNBN',
'p_p_lifecycle':'0',
'p_p_mode':'view',
'p_p_state':'normal',}
r=s.post('http://www.cened.it/mappa_certificatore',params=params,data=data,headers=headers,cookies=cookies)
doc=fromstring(r.content)
for line in parse_doc(doc):
writer.writerow(map(lambda x:x.encode('utf-8'),line))
pagecount=doc.xpath('//div[@class="page-selector"]/text()')[-1]
pagecount=pagecount.strip().split('di ')[-1]
pagecount=int(pagecount)
print "pages:{:3}".format(pagecount),
for page in xrange(2,pagecount+1):
data_next=copy(data)
data_next['malo.actiontype']='PAGINATION'
data_next['malo.pgnum']=str(page)
data_next['malo.selpgnum']=str(page)
r=s.post('http://www.cened.it/mappa_certificatore',params=params,data=data_next,headers=headers,cookies=cookies)
doc=fromstring(r.content)
for line in parse_doc(doc):
writer.writerow(map(lambda x:x.encode('utf-8'),line))
print "done."
| [
"bkurdasov@gmail.com"
] | bkurdasov@gmail.com |
acf2f19b60551fb41b336692c118666604dfc749 | 06257eac9ad651fad7f7351843f369e54d415b05 | /AlphaBot.py | 2a499607b3da6ba16d1ee3f2ff4bdef1e77f98ec | [] | no_license | mtc-20/Alphabot | db6ccdee1ca14f2921cb2e10ed2e1f7f6e662ad3 | 6e56d46a193e492dfe118655ee419c94ad8acec5 | refs/heads/master | 2021-01-08T07:26:39.588944 | 2020-03-02T15:54:18 | 2020-03-02T15:54:18 | 241,955,521 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,397 | py | """
modified by mtc-20
"""
import RPi.GPIO as GPIO
import time
class AlphaBot(object):
def __init__(self,in1=12,in2=13,ena=6,in3=20,in4=21,enb=26,s1=27,s2=22):
self.IN1 = in1
self.IN2 = in2
self.IN3 = in3
self.IN4 = in4
self.ENA = ena
self.ENB = enb
self.S1 = 27
self.S2 = 22
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.IN1,GPIO.OUT)
GPIO.setup(self.IN2,GPIO.OUT)
GPIO.setup(self.IN3,GPIO.OUT)
GPIO.setup(self.IN4,GPIO.OUT)
GPIO.setup(self.ENA,GPIO.OUT)
GPIO.setup(self.ENB,GPIO.OUT)
GPIO.setup(self.S1,GPIO.OUT)
GPIO.setup(self.S2,GPIO.OUT)
self.stop()
self.PWMA = GPIO.PWM(self.ENA,500)
self.PWMB = GPIO.PWM(self.ENB,500)
self.PWMP = GPIO.PWM(self.S1,50)
self.PWMT = GPIO.PWM(self.S2,50)
self.PWMA.start(50)
self.PWMB.start(50)
## self.PWMP.start(10)
## self.PWMT.start(7)
## time.sleep(0.5)
self.servo_switch(True)
#self.PWMT.stop()
#self.PWMP.stop()
print('[Alpha_INFO]: Motors initialised')
def forward(self):
GPIO.output(self.IN1,GPIO.HIGH)
GPIO.output(self.IN2,GPIO.LOW)
GPIO.output(self.IN3,GPIO.LOW)
GPIO.output(self.IN4,GPIO.HIGH)
def stop(self):
GPIO.output(self.IN1,GPIO.LOW)
GPIO.output(self.IN2,GPIO.LOW)
GPIO.output(self.IN3,GPIO.LOW)
GPIO.output(self.IN4,GPIO.LOW)
def backward(self):
GPIO.output(self.IN1,GPIO.LOW)
GPIO.output(self.IN2,GPIO.HIGH)
GPIO.output(self.IN3,GPIO.HIGH)
GPIO.output(self.IN4,GPIO.LOW)
def left(self):
GPIO.output(self.IN1,GPIO.LOW)
GPIO.output(self.IN2,GPIO.LOW)
GPIO.output(self.IN3,GPIO.LOW)
GPIO.output(self.IN4,GPIO.HIGH)
def right(self):
GPIO.output(self.IN1,GPIO.HIGH)
GPIO.output(self.IN2,GPIO.LOW)
GPIO.output(self.IN3,GPIO.LOW)
GPIO.output(self.IN4,GPIO.LOW)
def setPWMA(self,value):
self.PWMA.ChangeDutyCycle(value)
def setPWMB(self,value):
self.PWMB.ChangeDutyCycle(value)
def setPWMP(self, angle):
assert angle in range(0,181)
value = (12.5/180.0)*angle + 3.5
#print(value)
self.PWMP.ChangeDutyCycle(value)
#self.PWMP.start(value)
print('Set Pan to {} deg'.format(angle))
time.sleep(1)
#self.PWMP.stop()
def setPWMT(self, angle):
assert angle in range(0,181)
value = (7.5/180)*angle + 2.5
#print(value)
#self.PWMT.start(value)
self.PWMT.ChangeDutyCycle(value)
print('Set Tilt to {} deg'.format(angle))
time.sleep(1)
#self.PWMT.stop()
def servo_switch(self, status):
if status:
self.PWMP.start(10)
self.PWMT.start(7)
time.sleep(2)
else:
print('[Alpha_INFO]: Switching off servos')
self.PWMP.stop()
self.PWMT.stop()
def setMotor(self, left, right):
if((right >= 0) and (right <= 100)):
GPIO.output(self.IN1,GPIO.HIGH)
GPIO.output(self.IN2,GPIO.LOW)
self.PWMA.ChangeDutyCycle(right)
elif((right < 0) and (right >= -100)):
GPIO.output(self.IN1,GPIO.LOW)
GPIO.output(self.IN2,GPIO.HIGH)
self.PWMA.ChangeDutyCycle(0 - right)
if((left >= 0) and (left <= 100)):
GPIO.output(self.IN3,GPIO.HIGH)
GPIO.output(self.IN4,GPIO.LOW)
self.PWMB.ChangeDutyCycle(left)
elif((left < 0) and (left >= -100)):
GPIO.output(self.IN3,GPIO.LOW)
GPIO.output(self.IN4,GPIO.HIGH)
self.PWMB.ChangeDutyCycle(0 - left)
if __name__ == '__main__':
Ab = AlphaBot()
time.sleep(2)
Ab.stop()
Ab.setPWMP(170)
Ab.setPWMT(160)
## Ab.servo_switch(False)
## time.sleep(5)
## print('Switching servos back on')
## Ab.servo_switch(True)
time.sleep(2)
print('New pose')
Ab.setPWMP(10)
GPIO.cleanup()
| [
"mamenthomas.c@gmail.com"
] | mamenthomas.c@gmail.com |
4ca2f6e5a50c697732e41ef7847d7a9e32d0c8ef | d83fde3c891f44014f5339572dc72ebf62c38663 | /_bin/google-cloud-sdk/.install/.backup/lib/surface/bigtable/clusters/list.py | 22a4d818ffea8110f2f7395f31ce3f059c5b9a3d | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | gyaresu/dotfiles | 047cc3ca70f4b405ba272856c69ee491a79d2ebe | e5e533b3a081b42e9492b228f308f6833b670cfe | refs/heads/master | 2022-11-24T01:12:49.435037 | 2022-11-01T16:58:13 | 2022-11-01T16:58:13 | 17,139,657 | 1 | 1 | null | 2020-07-25T14:11:43 | 2014-02-24T14:59:59 | Python | UTF-8 | Python | false | false | 2,944 | py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""bigtable clusters list command."""
from __future__ import absolute_import
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.bigtable import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.bigtable import arguments
from googlecloudsdk.core import resources
def _GetUriFunction(resource):
return resources.REGISTRY.ParseRelativeName(
resource.name,
collection='bigtableadmin.projects.instances.clusters').SelfLink()
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ListClusters(base.ListCommand):
"""List existing Bigtable clusters.
List existing Bigtable clusters.
## EXAMPLES
To list all clusters in an instance, run:
$ {command} --instances INSTANCE_NAME
To list all clusters in any of several instances, run:
$ {command} --instances INSTANCE_NAME1,INSTANCE_NAME2
"""
@staticmethod
def Args(parser):
"""Register flags for this command."""
arguments.AddInstancesResourceArg(parser, 'to list clusters for')
parser.display_info.AddFormat("""
table(
name.segment(3):sort=1:label=INSTANCE,
name.basename():sort=2:label=NAME,
location.basename():label=ZONE,
serveNodes:label=NODES,
defaultStorageType:label=STORAGE,
state
)
""")
parser.display_info.AddUriFunc(_GetUriFunction)
parser.display_info.AddCacheUpdater(arguments.InstanceCompleter)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Yields:
Some value that we want to have printed later.
"""
cli = util.GetAdminClient()
instance_refs = args.CONCEPTS.instances.Parse()
if not args.IsSpecified('instances'):
instance_refs = [util.GetInstanceRef('-')]
for instance_ref in instance_refs:
msg = (
util.GetAdminMessages()
.BigtableadminProjectsInstancesClustersListRequest(
parent=instance_ref.RelativeName()))
for cluster in list_pager.YieldFromList(
cli.projects_instances_clusters,
msg,
field='clusters',
batch_size_attribute=None):
yield cluster
| [
"me@gareth.codes"
] | me@gareth.codes |
a109f4af2496f8cf2193422014e3bebe1bfb2884 | efd81a5e287a398aaa5333e949d6ca40b1544053 | /config/52_niak_centrality/00_gen_group_mask.py | 0070a89bd229cbbe1bfd58a95fbcfb6571a9160d | [] | no_license | fitrialif/abide-1 | 82d80bf52cd9b36072985a1ddeacfb325791566e | 9ccc45f612a58dbc3cf5fa3b70c41bcfeabd8ddc | refs/heads/master | 2020-04-25T15:13:22.974634 | 2014-03-10T18:18:42 | 2014-03-10T18:18:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,892 | py | #!/usr/bin/env python
from __future__ import print_function
import os, yaml
from os import path as op
def run(cmd):
print(cmd)
os.system(cmd)
# First read in a quick pack file with all the paths
fn = "/home2/data/Projects/ABIDE_Initiative/CPAC/abide/config/50_niak/quick_pack_run1_nofilt_noglobal.yml"
subinfo = yaml.load(open(fn, 'r'))
# Second extract path to masks in standard space
masks = [ si['functional_brain_mask_to_standard']['run1'] for si in subinfo ]
for mask in masks:
if not op.exists(mask):
print("missing: %s" % mask)
# Third combine the masks
cmd = "fslmerge -t combined_masks.nii.gz %s" % ' '.join(masks)
print(cmd, file=open("tmp.cmd", "w")) # for some reason, running it directly doesn't work
run("bash tmp.cmd")
# Fourth get a 90% and 100% masks
odir = "/home2/data/Projects/ABIDE_Initiative/CPAC/abide/templates/masks"
cmd = "fslmaths combined_masks.nii.gz -Tmean -thr 0.9 -bin %s/mask_niak_90percent.nii.gz" % odir
run(cmd)
cmd = "fslmaths combined_masks.nii.gz -Tmean -thr 1 -bin %s/mask_niak_100percent.nii.gz" % odir
run(cmd)
# Fifth get the grey matter mask into the same space as niak's data
odir = "/home2/data/Projects/ABIDE_Initiative/CPAC/abide/templates/masks"
cmd = "cd %s; 3dresample -input MNI152_T1_GREY_3mm_25pc_mask.nii.gz -master mask_niak_90percent.nii.gz -prefix MNI152_T1_GREY_3mm_25pc_mask_niak.nii.gz -rmode NN" % odir
run(cmd)
# Fifth combine that mask with the grey matter
odir = "/home2/data/Projects/ABIDE_Initiative/CPAC/abide/templates/masks"
cmd = "cd %s; fslmaths %s -mas %s %s" % (odir, "mask_niak_90percent.nii.gz", "MNI152_T1_GREY_3mm_25pc_mask_niak.nii.gz", "mask_niak_90percent_gm.nii.gz")
run(cmd)
cmd = "cd %s; fslmaths %s -mas %s %s" % (odir, "mask_niak_100percent.nii.gz", "MNI152_T1_GREY_3mm_25pc_mask_niak.nii.gz", "mask_niak_100percent_gm.nii.gz")
run(cmd)
| [
"czarrar@gmail.com"
] | czarrar@gmail.com |
b5ab7ed1038dfa35dcccb15d875e28493f05dd3e | effe857fcf2ffeda5f0a8ff04d808ec2aa8d238e | /cs285/critics/bootstrapped_continuous_critic.py | 9a9d1b17aa9085a42a553813681bfbeb16b135e4 | [] | no_license | HuangYiduo14/cs285_project_ubereats | 740733d553fb86e4e05af9b6dc66adb9c39760c5 | 90d08f8d2c233f4fbdbd1647f1e74bc5aeaa5fb6 | refs/heads/master | 2023-02-07T13:47:28.996520 | 2020-12-25T18:35:23 | 2020-12-25T18:35:23 | 306,470,579 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,574 | py | #from .base_critic import BaseCritic
import torch
from torch import nn
from torch import optim
from cs285.envs.city import MAX_CAP, MAX_CAND_NUM
from cs285.infrastructure import pytorch_util as ptu
import numpy as np
class BootstrappedContinuousCritic(nn.Module):
"""
Notes on notation:
Prefixes and suffixes:
ob - observation
ac - action
_no - this tensor should have shape (batch self.size /n/, observation dim)
_na - this tensor should have shape (batch self.size /n/, action dim)
_n - this tensor should have shape (batch self.size /n/)
Note: batch self.size /n/ is defined at runtime.
is None
"""
def __init__(self, hparams):
super().__init__()
self.ob_dim = 3+2*MAX_CAP
self.ac_dim = 5
self.is_city = hparams['is_city']
self.size = hparams['size']
self.n_layers = hparams['n_layers']
self.learning_rate = hparams['learning_rate']
self.n_drivers = hparams['n_drivers']
self.shared_exp = hparams['shared_exp']
self.shared_exp_lambda = hparams['shared_exp_lambda']
# critic parameters
self.num_target_updates = hparams['num_target_updates']
self.num_grad_steps_per_target_update = hparams['num_grad_steps_per_target_update']
self.gamma = hparams['gamma']
self.critic_networks = []
self.losses = []
self.optimizers = []
for i in range(self.n_drivers):
self.critic_networks.append(ptu.build_mlp(
self.ob_dim,
1,
n_layers=self.n_layers,
size=self.size,
))
self.critic_networks[i].to(ptu.device)
self.losses.append(nn.MSELoss())
self.optimizers.append(optim.Adam(
self.critic_networks[i].parameters(),
self.learning_rate,
))
def forward(self, obs):
observations = obs[:,:,0:self.ob_dim]
rewards = []
for i in range(self.n_drivers):
rewards.append(self.critic_networks[i](observations[:,i,:]).squeeze(1))
return rewards
def shared_forward(self, obs):
if isinstance(obs, np.ndarray):
obs = ptu.from_numpy(obs)
observations = obs[:,:,0:self.ob_dim]
rewards = dict()
for i in range(self.n_drivers):
for k in range(self.n_drivers):
rewards[(i,k)] = self.critic_networks[i](observations[:,k,:]).squeeze(1)
return rewards
def forward_np(self, obs):
obs = ptu.from_numpy(obs)
predictions = self(obs)
results = np.array([ptu.to_numpy(predictions[i]) for i in range(self.n_drivers)])
return results.T
def check_map(self):
val_fun0 = np.zeros((10,10))
val_fun1 = np.zeros((10,10))
val_fun2 = np.zeros((10,10))
obs = []
for i in range(10):
for j in range(10):
this_obs = np.array([[[1,i,j,i,j]]])
result0 = self.forward_np(this_obs)
result0 = result0.squeeze()
result1 = self.forward_np(np.array([[[1,0,0,i,j]]]))
result1 = result1.squeeze()
result2 = self.forward_np(np.array([[[1,i,j,0,0]]]))
result2 = result2.squeeze()
val_fun0[i,j] = result0
val_fun1[i,j] = result1
val_fun2[i,j] = result2
return val_fun0, val_fun1, val_fun2
def update(self, ob_no, ac_na, next_ob_no, reward_n, terminal_n, action_distributions=None):
"""
Update the parameters of the critic.
let sum_of_path_lengths be the sum of the lengths of the paths sampled from
Agent.sample_trajectories
let num_paths be the number of paths sampled from Agent.sample_trajectories
arguments:
ob_no: shape: (sum_of_path_lengths, ob_dim)
next_ob_no: shape: (sum_of_path_lengths, ob_dim). The observation after taking one step forward
reward_n: length: sum_of_path_lengths. Each element in reward_n is a scalar containing
the reward for each timestep
terminal_n: length: sum_of_path_lengths. Each element in terminal_n is either 1 if the episode ended
at that timestep of 0 if the episode did not end
returns:
training loss
"""
# TODO: Implement the pseudocode below: do the following (
# self.num_grad_steps_per_target_update * self.num_target_updates)
# times:
# every self.num_grad_steps_per_target_update steps (which includes the
# first step), recompute the target values by
# a) calculating V(s') by querying the critic with next_ob_no
# b) and computing the target values as r(s, a) + gamma * V(s')
# every time, update this critic using the observations and targets
#
# HINT: don't forget to use terminal_n to cut off the V(s') (ie set it
# to 0) when a terminal state is reached
# HINT: make sure to squeeze the output of the critic_network to ensure
# that its dimensions match the reward
if isinstance(ac_na, np.ndarray):
ac_na = ptu.from_numpy(ac_na)
ac_na = ac_na.type(torch.int64)
if self.shared_exp:
for i in range(self.num_target_updates):
value_next = self.shared_forward(next_ob_no)
targets_d = dict()
for d1 in range(self.n_drivers):
for d2 in range(self.n_drivers):
targets_d[(d1,d2)] = ptu.from_numpy(reward_n[:,d2]+self.gamma*ptu.to_numpy(value_next[(d1,d2)]))
for j in range(self.num_grad_steps_per_target_update):
value_s = self.shared_forward(ptu.from_numpy(ob_no))
losses = []
for d1 in range(self.n_drivers):
this_loss = (targets_d[(d1,d1)]-value_s[(d1,d1)])**2
for d2 in range(self.n_drivers):
if d1 != d2:
this_loss = this_loss + self.shared_exp_lambda * \
torch.div(action_distributions[(d1,d2)].probs.gather(1,ac_na[:,d2][None].transpose(1,0)).squeeze().detach(),
action_distributions[(d2,d2)].probs.gather(1,ac_na[:,d2][None].transpose(1,0)).squeeze().detach()) *\
(targets_d[(d1,d2)]-value_s[(d1,d2)])**2
losses.append(this_loss.mean())
self.optimizers[d1].zero_grad()
losses[d1].backward(retain_graph=True)
self.optimizers[d1].step()
return losses[d1].item()
else:
for i in range(self.num_target_updates):
value_s_next = self.forward_np(next_ob_no)
value_s_next[terminal_n==1] = 0
targets_d = []
for d in range(self.n_drivers):
targets = reward_n[:, d] + self.gamma * value_s_next[:,d]
targets_d.append(ptu.from_numpy(targets))
for j in range(self.num_grad_steps_per_target_update):
value_s = self.forward(ptu.from_numpy(ob_no))
losses = []
for d in range(self.n_drivers):
losses.append(self.losses[d](targets_d[d], value_s[d]))
self.optimizers[d].zero_grad()
losses[d].backward()
self.optimizers[d].step()
return losses[d].item()
"""
import numpy as np
ob_dim = 3+2*MAX_CAP
ac_dim = 5
n_drivers = 3
hparams= dict()
hparams['ob_dim'] = ob_dim
hparams['ac_dim'] = ac_dim
hparams['is_city'] = True
hparams['size'] = 20
hparams['n_layers'] = 2
hparams['learning_rate'] = 1e-3
hparams['n_drivers']=n_drivers
# critic parameters
hparams['num_target_updates'] = 10
hparams['num_grad_steps_per_target_update'] = 10
hparams['gamma'] = 0.9
aa = BootstrappedContinuousCritic(hparams)
obs_lb_one_driver = [0, 0, 0] + [0 for _ in range(2 * MAX_CAP)] + \
[0, 0, 0, 0, 0] + [0, 0, 0, 0, 0]*MAX_CAND_NUM
obs = np.array([[obs_lb_one_driver for _ in range(n_drivers)] for _ in range(2)])
cc = aa.forward_np(obs)
aa.update(obs,0,obs,cc,np.array([False, False]))
"""
| [
"yiduo_huang@berkeley.edu"
] | yiduo_huang@berkeley.edu |
ac117659c866b8df2494d503bb8dadda0f9522a9 | 0740cb643e20d8765f0fb3fca335d4b7f69e5f13 | /blogapp/Blog_api/apps.py | 97b40e4102ae62d5ec99f51241a97cb57979b935 | [] | no_license | dannysax/blogapp | 7a079a1ed2d77fec25f797e75ee92274070fdfd6 | 6c61a200c3b4a228b013e8795ec792b1e9abb6cf | refs/heads/main | 2023-07-02T17:50:18.613548 | 2021-08-01T22:48:16 | 2021-08-01T22:48:16 | 391,302,080 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 147 | py | from django.apps import AppConfig
class BlogApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'Blog_api'
| [
"ugahdaniel1997@gmail.com"
] | ugahdaniel1997@gmail.com |
defc4662ad24bac7f0c94489f4d8762a7b00ea29 | be7bb6d0cbdb27d3ff72830dc9cce41b170b27fe | /0x08-python-more_classes/7-rectangle.py | 07b740b4b98861329278958ae69a395ba2671045 | [] | no_license | camagar/holbertonschool-higher_level_programming | 21a8e7c2a2ad07c694c5443e174bb70502f910c2 | 97dd2fade6fb64ac7d9c52e412c0b8c1b8dfc3de | refs/heads/master | 2023-04-07T21:38:00.071687 | 2021-04-14T02:11:42 | 2021-04-14T02:11:42 | 291,889,478 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,096 | py | #!/usr/bin/python3
"""create a class"""
class Rectangle(object):
"""define the rectangle class"""
number_of_instances = 0
print_symbol = "#"
def __init__(self, width=0, height=0):
self.width = width
self.height = height
Rectangle.number_of_instances += 1
@property
def width(self):
"""width"""
return self.__width
@property
def height(self):
"""height"""
return self.__height
@width.setter
def width(self, value):
"""width setter"""
if type(value) is not int:
raise TypeError('width must be an integer')
if value < 0:
raise ValueError('width must be >= 0')
self.__width = value
@height.setter
def height(self, value):
"""height setter"""
if type(value) is not int:
raise TypeError('height must be an integer')
if value < 0:
raise ValueError('height must be >= 0')
self.__height = value
def area(self):
"""area"""
a = self.__width * self.__height
return a
def perimeter(self):
"""Perimeter"""
if self.__width == 0 or self.__height == 0:
return 0
else:
p = (self.__width * 2) + (self.__height * 2)
return p
def __str__(self):
"""string method"""
print_rectangule = ""
if self.__width == 0 or self.__height == 0:
return print_rectangule
else:
for i in range(0, self.__height):
for j in range(0, self.__width):
print_rectangule += str(self.print_symbol)
if i != (self.__height - 1):
print_rectangule += "\n"
return print_rectangule
def __repr__(self):
"""representation"""
reptangle = 'Rectangle(' + str(self.__width) + ', ' +\
str(self.__height) + ')'
return (reptangle)
def __del__(self):
"""del instance"""
print("Bye rectangle...")
Rectangle.number_of_instances -= 1
| [
"mauriciogrestrepo@gmail.com"
] | mauriciogrestrepo@gmail.com |
13076cc89f145d403f16a2d4d64ea4e2d8b0a500 | 7a7c16973012f687b178b7a5332f59c02f3b1b47 | /Semestr 2/Cwiczenia 8/przyklad.py | 51091e984f16e133140fc0f0c63254d1c7ef5a07 | [] | no_license | BVGdragon1025/-wiczenia | 7808c4765ae6aa932654fd1cf07e055f21df1a00 | 058bb9bc8930c58013e53f6c801c77a904ac32ad | refs/heads/main | 2023-05-06T17:06:05.185327 | 2021-06-06T13:38:30 | 2021-06-06T13:38:30 | 317,488,793 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 479 | py | import os
import heapq
from timeit import default_timer as timer
# Sortowanie szybkie:
sort_list_1 = [4, 10, 11, 5, 73, 5, 1]
print(sort_list_1)
print("Sortowanie szybkie: ")
start = timer()
sort_list_1.sort()
end = timer()
print(sort_list_1)
print("Czas: ", end-start)
# Sortowanie Heap:
sort_list_2 = [4, 10, 11, 5, 73, 5, 1]
print(sort_list_2)
print("Heap Sort: ")
start2 = timer()
heapq.heapify(sort_list_2)
end2 = timer()
print(sort_list_2)
print("Czas: ", end2-start2)
| [
"72506695+BVGdragon1025@users.noreply.github.com"
] | 72506695+BVGdragon1025@users.noreply.github.com |
fc0f6eca62b787d0668d65da7d5f19e0a381172b | b049a4b0305300d61a5608fdbc16281d1370b4ad | /neethupython/identifiers/introd.py | d99c0918dcbcce9433f48f4f283a1e8f89f7651e | [] | no_license | sickgirl1999/project-python | 9f32814b0da0cf494f7058f1bb027437c26793ab | 01753cc2678fb6c18d4008209f870778a028ed8c | refs/heads/master | 2023-04-26T07:37:50.240868 | 2021-05-19T08:05:48 | 2021-05-19T08:05:48 | 368,791,588 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 448 | py | #identifiers=name
#eg=var name,fun name,class name
#variable=memory allocate
#variable name= value
#name="neethu"
#age=21 #name and age are the identifiers
#set of rules
#1num=10#1=follow alphabets or underscore to initilize
#_num=10
# num=10#2=remove unwanted space
#nummmmmmmmmmmmmmmm=10
#3= case sensitive
#Num=10
#print(Num)
#4=always use num
name="luminar technolab"
loc="kakkanad"
print(name,"located in ",loc)
print("company name is",name) | [
"gokul.neethu.31@gmail.com"
] | gokul.neethu.31@gmail.com |
60b9dd1666104ae3c2f4834c6daf99a7a32e8e4f | 8dd47e8dac6e1dda4774c21bfd15abda744db7ef | /learn/generators.py | 290d000de6dd3ea9a0ed4e1a612c47b814726048 | [] | no_license | domero2/Python | ef1d4bb89ea5bbeeb3e1492a6da12a04e1a97487 | 45780255764bb4ff09fd9a214503bbc63566fe24 | refs/heads/master | 2020-09-21T03:33:56.413525 | 2020-06-22T14:15:22 | 2020-06-22T14:15:22 | 224,666,659 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 177 | py | class Gen:
def __init__(self,n):
self.n = n
self.last = 0
def __next__(self):
return self.next()
def next(self):
rv = self.last **2 | [
"albi@MacBook-Pro-Apple.local"
] | albi@MacBook-Pro-Apple.local |
b5fe0daa284a32655bbfe2009edd17c1e08a32b0 | 8a585bbdc2194cd27967dc8ccb1b0d4106a0f440 | /enlaces/apps.py | 8f2a613f4010853f9cd8cf46e40d3ed2f6b90c66 | [] | no_license | dusanov/milienlaces | 4b93dd9329c1f3c37279810f3fcbcd2ab71e67a1 | 54174ad8dbb0c1f01695a010a89b6b9dd87c7ab3 | refs/heads/master | 2020-09-22T14:01:00.648290 | 2019-12-08T16:33:39 | 2019-12-08T16:33:39 | 225,230,650 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 89 | py | from django.apps import AppConfig
class EnlacesConfig(AppConfig):
name = 'enlaces'
| [
"hrandus@yahoo.com"
] | hrandus@yahoo.com |
590b0c9bf14cd522b7b8f7924a4d62083c4fc3e1 | b2f326a788d297eca1e372d99a1f44aad65cba99 | /DockerAnsibleCourse/02.Django-RestApi/src/todobackend/settings/release.py | 02a41a07bc060c6aaead5ec641ae5974c1115959 | [
"Unlicense"
] | permissive | vijayvepa/AnsibleExamples | fd06d24f88fd49f124a8f628b6dc7924df9d43af | 23a7ddc1c7e932b79cef3cc6ce9338207dbd6031 | refs/heads/master | 2022-12-23T14:55:43.458906 | 2019-10-16T13:54:09 | 2019-10-16T13:54:09 | 156,077,984 | 2 | 1 | null | 2022-12-10T06:43:23 | 2018-11-04T12:06:26 | JavaScript | UTF-8 | Python | false | false | 855 | py | from todobackend.settings.base import *
import os
# Disable debug
if os.environ.get('DEBUG'):
DEBUG = True
else:
DEBUG = False
# Must specify allowed-hosts when debug is disabled
ALLOWED_HOSTS = [os.environ.get('ALLOWED_HOSTS', '*')]
# Use mySQL
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ.get('MYSQL_DATABASE', 'todobackend'),
'USER': os.environ.get('MYSQL_USER', 'todo'),
'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'password'),
'HOST': os.environ.get('MYSQL_HOST', 'localhost'),
'PORT': os.environ.get('MYSQL_PORT', '3306')
}
}
# files served by web app
STATIC_ROOT = os.environ.get('STATIC_ROOT', '/var/www/todobackend/static')
# files or images uploaded to the web app
MEDIA_ROOT = os.environ.get('MEDIA_ROOT', '/var/www/todobackend/media')
| [
"vijay.vepakomma@philips.com"
] | vijay.vepakomma@philips.com |
4f9de2a06443a3664ac9505f6a14bd6e48781fc3 | 6c5a3a429e6f6ad03ad936064f61f1bb842f9d65 | /tifresi/pipelines/LJparams.py | 2d777386c6d91fdea4ac3cbbb0aa71f135883c40 | [
"MIT"
] | permissive | andimarafioti/tifresi | a3fc00eedf1fe6d48fc050b06e496fb48fbc1a53 | 245e4d76cb6ecebd3acc4e742fd152bf99493ce4 | refs/heads/master | 2023-04-13T00:40:14.317876 | 2023-04-05T12:27:54 | 2023-04-05T12:27:54 | 233,073,088 | 12 | 1 | MIT | 2023-04-05T12:27:55 | 2020-01-10T15:14:53 | Python | UTF-8 | Python | false | false | 1,044 | py | from tifresi.hparams import HParams
from tifresi.utils import downsample_tf_time
import librosa
import numpy as np
class LJParams(HParams):
# Signal parameters
sr = 22050 # Sampling frequency of the signal
M = 2*1024 # Ensure that the signal will be a multiple of M
# STFT parameters
stft_channels = 1024 # Number of frequency channels
hop_size = 256 # Hop size
use_truncated = True # use a truncated Gaussian
stft_dynamic_range_dB = 50 # dynamic range in dB for the STFT
normalize = True # Normalize STFT
# MEL parameters
n_mels = 80 # Number of mel frequency band
fmin = 0 # Minimum frequency for the MEL
fmax = None # Maximum frequency for the MEL (None -> Nyquist frequency)
reduction_rate = 2 # Reduction rate for the frequency channel
mel_dynamic_range_dB = 50 # dynamic range in dB for the MEL
mel_basis = librosa.filters.mel(sr=sr, n_fft=stft_channels, n_mels=n_mels, fmin=fmin, fmax=fmax)
mel_inverse_basis = np.linalg.pinv(mel_basis)
| [
"nperraud@users.noreply.github.com"
] | nperraud@users.noreply.github.com |
867eff0baf87adb40f05a69d0bcd8d449f0eda43 | d850f05e2f5cc5708cfc00470e7d5eedebff959e | /tasker/migrations/0011_auto_20200313_1627.py | eccba84544e54751a37cabfedc43f1cc30127a4c | [] | no_license | prauscher/troodle | 84e25549b26492359b2b35542db4ecd5d9bc1306 | f490f92cf6425a640836388281ce62937aa72ca5 | refs/heads/master | 2021-08-28T04:30:43.842934 | 2021-08-24T08:35:56 | 2021-08-24T08:35:56 | 218,851,153 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,978 | py | # Generated by Django 3.0.4 on 2020-03-13 16:27
from django.db import migrations, models
import django.db.models.deletion
def fill_participants(apps, schema_editor):
Participant = apps.get_model('tasker', 'Participant')
participants = {}
def _assure_nick(nick, board):
if nick not in participants:
p = Participant(nick=nick, board=board)
p.save()
participants[nick] = p.id
return participants[nick]
Handling = apps.get_model('tasker', 'Handling')
for handling in Handling.objects.all():
handling.editor = _assure_nick(handling.editor, handling.task.board)
handling.save()
Task = apps.get_model('tasker', 'Task')
for task in Task.objects.all():
if task.reserved_by:
task.reserved_by = _assure_nick(task.reserved_by, task.board)
task.save()
class Migration(migrations.Migration):
dependencies = [
('tasker', '0010_auto_20200121_1706'),
]
operations = [
migrations.CreateModel(
name='Participant',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nick', models.CharField(max_length=50, verbose_name='Nick')),
('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='participants', to='tasker.Board', verbose_name='Board')),
],
),
migrations.RunPython(fill_participants),
migrations.AlterField(
model_name='handling',
name='editor',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='tasker.Participant'),
),
migrations.AlterField(
model_name='task',
name='reserved_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='tasker.Participant'),
),
]
| [
"prauscher@prauscher.de"
] | prauscher@prauscher.de |
d0b739f2ff92a0d422aedbce7a2853ed409badb3 | 25e3e355af50ca416277c0b96a81bba01de777db | /authentication/views.py | 0eec30d82bea34ff6bf94860892d616de38fb7b0 | [] | no_license | JANATI-IDRISSI-Imad/logs | 1395462ce3b8e1d550d268fe20b543397ab8238a | f201b69cc681afcf07d27107944b117654948743 | refs/heads/master | 2022-10-19T06:57:20.485025 | 2020-06-14T11:24:51 | 2020-06-14T11:24:51 | 267,449,053 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,196 | py | from django.shortcuts import render, HttpResponse, redirect
from .models import User , Server , syslog
from django.contrib import messages
from scp import SCPClient
import paramiko
from mainapp.views import indextest
from django.contrib.sessions.backends.base import SessionBase
from django.core import serializers
from sysLog.views import tablesyslog
from datetime import datetime
# Create your views here.
def createSSHClient(server, port, user, password):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(server, port, user, password)
return client
def register(request):
if request.method=='POST':
user = User()
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.password = request.POST['password']
user.email = request.POST['email']
user.save()
return redirect("login")
else :
return render(request,"register.html")
def fromto(user):
tamps=[user.servers.count()]
i=0
for s in user.servers :
tamps[i]=s.host
i=i+1
return tamps
def login(request):
global user
user=User()
if request.method=='POST':
user.email = request.POST['email']
user.password = request.POST['password']
user = User.objects.get(email=user.email, password=user.password)
if user is None :
messages.info(request, 'Error')
return redirect("login")
else :
request.session['email'] = user.email
#request.session['serverstamps']= "fromto(user)"
return redirect(loginserver)
else:
return render(request,"login.html")
def loginserver(request):
#try:
#if user.is_authenticated :
if request.method=='POST':
server =Server()
server.host = request.POST['server']
server.port = request.POST['port']
server.user = request.POST['user']
server.password = request.POST['password']
src = "C:/log/syslog.1"
dst = "E:/4eme/exam/django/log/"
try :
ssh = createSSHClient(server.host, server.port, server.user, server.password)
scp = SCPClient(ssh.get_transport())
scp.get(src , dst)
user.servers.update()
request.session['server'] = server.host
#server.logs=Log()
if user.servers.count() == 0 :
user.servers.append(server)
else :
print(user.servers.count())
if user.servers.get(host=request.session['server']) == None :
user.servers.append(server)
setsyslog(request)
return redirect(tablesyslog)
except Exception as e :
messages.info(request,e)
return redirect("loginserver")
else:
return render(request,"loginserver.html")
import calendar
def getmount(mountstr):
j = 0
for i in calendar.month_abbr:
if i==mountstr :
return j
#print(j,'-',i)
j+=1
return j
def setsyslog(request):
file = open('E:/4eme/exam/django/log/syslog.1', "r")
lines = file. readlines()
file.close()
logs= user.servers.get(host=request.session['server']).syslogs
testlast=1
if logs.count()!=0 :
lastlog=logs[logs.count()-1]
testlast=0
#print(logs.last())
for line in lines :
tab=line.split()
l = syslog()
l.local = tab[3]
date_string=str(getmount(tab[0]))+" "+tab[1]+" "+ tab[2]
l.date = datetime.strptime(date_string, "%m %d %H:%M:%S")
if testlast ==0 :
if lastlog.date<l.date :
#l.date = tab[0]+" "+tab[1]+" "+ tab[2]
s=tab[4].split("[")
l.service = tab[4]
s=""
i=0
for s1 in tab :
if i>=5 :
s=s +s1+" "
i=i+1
l.message = s
user.servers.get(host=request.session['server']).syslogs.append(l)
else :
#print("imad")
s=tab[4].split("[")
l.service = tab[4]
s=""
i=0
for s1 in tab :
if i>=5 :
s=s +s1+" "
i=i+1
l.message = s
user.servers.get(host=request.session['server']).syslogs.append(l)
user.save()
def getUser():
return user | [
"imad.janati.idrissi@gmail.com"
] | imad.janati.idrissi@gmail.com |
947161cf9798787394cc329e5587c631591b37f9 | 0400507b04faf930dd5f289419d26cbde4881264 | /PrincipalComponentAnalysis/exercise01/com/bigblue/pca/exercise/2d/reduce1d.py | 1e3a5c17661ebc3e23eed167daebec2b0c9d53d5 | [] | no_license | mbbigblue/met-in-the-lake | 12ba53880fe334bee297d7a45f976ad9f4d7a6de | 7848fc460b41dec67c81f3321922b67a300b7b29 | refs/heads/master | 2020-04-12T02:46:14.375955 | 2019-04-22T18:34:02 | 2019-04-22T18:34:02 | 162,252,986 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,622 | py | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()
##1. Generate random data
rng = np.random.RandomState(1)
X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T
# Plot generated data
colors = list(np.random.choice(range(5), size=200))
plt.scatter(X[:, 0], X[:, 1], c=colors, alpha=0.8)
plt.axis('equal')
# ## 2. PCA estimation
# from sklearn.decomposition import PCA
#
# pca = PCA(n_components=2)
# pca.fit(X)
#
# print(pca.components_) # representing the directions of maximum variance in the data
# print(pca.explained_variance_) # The amount of variance explained by each of the selected components
#
#
# ## 3. Draw vector method
# def draw_vector(v0, v1, ax=None):
# ax = ax or plt.gca()
# arrowprops = dict(arrowstyle='->',
# linewidth=2,
# shrinkA=0, shrinkB=0)
# ax.annotate('', v1, v0, arrowprops=arrowprops)
#
#
# ## draw a chart
# plt.scatter(X[:, 0], X[:, 1], alpha=0.2)
# for length, vector in zip(pca.explained_variance_, pca.components_):
# v = vector * 3 * np.sqrt(length)
# draw_vector(pca.mean_, pca.mean_ + v)
# plt.axis('equal');
#
# ## 4. It's time for dimensionality reduction!
# pca = PCA(n_components=1)
# pca.fit(X)
# X_pca = pca.transform(X)
# print("original shape: ", X.shape)
# print("transformed shape:", X_pca.shape)
#
# ## 5. Inversion, getting back the data
# fig, (ax) = plt.subplots(1,1)
# X_new = pca.inverse_transform(X_pca)
# plt.scatter(X[:, 0], X[:, 1], c='black', alpha=0.4)
# plt.scatter(X_new[:, 0], X_new[:, 1],c='red', alpha=0.8)
# plt.axis('equal')
##show the chart
plt.show()
| [
"mbukowski@guidewire.com"
] | mbukowski@guidewire.com |
293e6bd66072132a12cedd42400a57c10f7c17eb | e4ce9037f02523eadcabec5e02f930aa0747c43c | /AccountsApp/migrations/0007_auto_20200414_1937.py | e5da2a73c0abfcd891fbcc445366d1fbb3a21ea2 | [] | no_license | gauravjiitb/InsaneApp | 92ce7c6dfa747e04f36c3a2a6b69acdfd0001feb | 3a8b66bf2e9b81bd5c868cb7224d581a1d1bac8a | refs/heads/master | 2021-05-18T01:03:38.078545 | 2020-04-18T10:58:43 | 2020-04-18T10:58:43 | 251,037,843 | 0 | 0 | null | 2020-03-29T13:35:54 | 2020-03-29T13:24:56 | null | UTF-8 | Python | false | false | 420 | py | # Generated by Django 3.0.4 on 2020-04-14 14:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AccountsApp', '0006_auto_20200414_1521'),
]
operations = [
migrations.AlterField(
model_name='transaction',
name='remarks',
field=models.CharField(blank=True, max_length=256, null=True),
),
]
| [
"gauravj.iitb@gmail.com"
] | gauravj.iitb@gmail.com |
a79e1144d9b58cfb11c8cf3bf7921f8bef2b2df3 | a0a3ecfaec5d02e9a1465faaf3d3ae19fdff1759 | /mandrill_inbound/mandrill_open.py | 5271e1f29e3b5bb815761baf1d7abd316b8c5ff4 | [
"MIT"
] | permissive | jongabriel/mandrill-inbound-python | 67269dfc314bf80784f6110f14c9b42c917afc1d | 23dd73adc964e38ba4996bdb3a2fd82ce380c765 | refs/heads/master | 2021-01-15T09:50:58.735189 | 2015-01-16T00:35:31 | 2015-01-16T00:35:31 | 29,317,939 | 0 | 0 | null | 2015-01-15T20:58:52 | 2015-01-15T20:58:52 | null | UTF-8 | Python | false | false | 4,247 | py | '''
Created on Jan 15, 2015
'''
from datetime import datetime
import json
class MandrillOpen(object):
'''
'source' is already json while 'json' is formatted as json.
'''
def __init__(self, *args, **kwargs):
if not kwargs.get('json') and not kwargs.get('source'):
raise Exception('Mandrill Inbound Error: you must \
provide json or source')
if kwargs.get('source'):
source = kwargs.get('source')
if source.startswith('mandrill_events='):
source = source.replace('mandrill_events=', '') #remove the non-json start
self.source = source
else:
the_json = kwargs.get('json')
if the_json.startswith('mandrill_events='):
the_json = the_json.replace('mandrill_events=', '') #remove the non-json start
self.source = json.loads(the_json)[0]
self.msg = self.source.get('msg')
if self.source['event'] != 'open':
raise Exception('Mandrill event not open')
@property
def opening_time(self):
"""
Date/time when the open occurred.
"""
return datetime.fromtimestamp(self.source.get('ts'))
@property
def opening_ts(self):
"""
UTC unix timestamp when the event occurred
"""
return self.source.get('ts')
@property
def user_agent(self):
'''
The user agent of the mail reader.
'''
return self.source.get('user_agent')
@property
def user_agent_type(self):
'''
The type of user agent (browser, Email Client, etc.)
'''
return self.source.get('user_agent_parsed').get('type')
@property
def user_agent_name(self):
'''
The name of user agent (Firefox, Chrome, Outlook)
'''
return self.source.get('user_agent_parsed').get('ua_name')
@property
def user_agent_version(self):
'''
The version of user agent
'''
return self.source.get('user_agent_parsed').get('ua_version')
@property
def user_agent_os_name(self):
'''
The name of the OS.
'''
return self.source.get('user_agent_parsed').get('os_name')
@property
def is_mobile(self):
'''
Was this email read on a mobile device?
'''
return self.source.get('user_agent_parsed').get('mobile')
@property
def opening_ip(self):
'''
The IP of the reading device.
'''
return self.source.get('ip')
@property
def location_country(self):
'''
The country where the email was read.
'''
return self.source.get('location').get('country')
@property
def location_region(self):
'''
The region or state where the email was read.
'''
return self.source.get('location').get('region')
@property
def location_city(self):
'''
The city where the email was read.
'''
return self.source.get('location').get('city')
@property
def location_lat_long(self):
'''
The (lat,long) where the email was read.
Returned as a tuple, (latitude, longitude).
'''
lat = self.source.get('location').get('latitude')
longitude = self.source.get('location').get('longitude')
return (lat, longitude)
@property
def email_id(self):
'''
The id of the Mandrill email.
'''
return self.msg.get('_id')
@property
def subject(self):
"""
The subject line of the message
"""
return self.msg.get('subject')
@property
def to(self):
"""
The email address of the opened email
"""
return self.msg.get('email')
@property
def sender(self):
'''
The email address of the sender.
'''
return self.msg.get('sender')
@property
def template(self):
'''
The template used for the email.
'''
return self.msg.get('template')
| [
"jgabriel.atx@gmail.com"
] | jgabriel.atx@gmail.com |
a92694bc85a9658e9906a9943a41b8b554e6f3f7 | c5e411b38751340ac0e47cf7bdde9ff7f635f339 | /user/migrations/0001_initial.py | f4f9f4eb722d64ffa1f3abd21660c86d798571ba | [] | no_license | shiny132/mysite | b88c311d76856b21077cd92bb122ff76c551e0c4 | 3b2e1c407dd3981dda3302f330f944158c3b63d7 | refs/heads/master | 2020-03-22T02:53:42.104287 | 2018-07-09T23:04:37 | 2018-07-09T23:04:37 | 139,398,235 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 668 | py | # Generated by Django 2.0.6 on 2018-06-29 05:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.CharField(max_length=200)),
('password', models.CharField(max_length=32)),
('name', models.CharField(max_length=10)),
('gender', models.CharField(max_length=10)),
],
),
]
| [
"shiny132@naver.com"
] | shiny132@naver.com |
1a084933a4396b2d4ac47a77e5b0c1463ab35b6f | 286a49d0360ee2eb718dd9a496be88555cef3227 | /229. 求众数 II.py | feeac888d4a69cfbebe04caeb6b8e78a73040e78 | [] | no_license | NaiveteYaYa/data-structrue | 0618ab6bb7accc99c40e39a3ca60bbc0a9723c2f | a376863c1a8e007efafd5c1ed84929a80321b1b9 | refs/heads/master | 2023-07-02T03:15:33.523855 | 2021-08-14T02:02:07 | 2021-08-14T02:02:07 | 395,857,543 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,043 | py | # -*- coding: utf-8 -*-
# @Time : 2020/4/2 14:20
# @Author : WuxieYaYa
"""
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
示例 1:
输入: [3,2,3]
输出: [3]
示例 2:
输入: [1,1,1,3,3,2,2,2]
输出: [1,2]
链接:https://leetcode-cn.com/problems/majority-element-ii
摩尔投票法的简单理解
与169. 多数元素的两点区别:
“多数”是指超过n/3,不是n/2,因此最多会有两个元素是众数,要建立两个candidate
题目没保证多数元素一定存在,所以最后要对candidate进行检验。因此整个流程分为两步:step1投票阶段,step2检验阶段。
算法核心:
对于候选者cand1和cand2:
如果投cand1,cand1加一票。
如果投cand2,cand2加一票。
如果投其他元素,cand1和cand2各减一票。
理解方法:
在169. 多数元素中,
如果candidate是多数元素,那么多数元素(>n/2)与其他元素之和(< n/2)对抗,一定赢。
如果candidate不是多数元素,那么该元素(< n/2)与多数元素和其他元素之和(>n/2)对抗,一定会被打败。
本题中,分为A``B``others三个阵营
如果此刻candidate是A和B,那么A(>n/3)与others(<n/3)对抗稳赢,B(>n/3)与others(<n/3)对抗稳赢。
如果此刻candidate是A和C(C来自others),那么B``C一定是对抗不了B的。
时间复杂度O(n),空间复杂度O(1)
作者:coldme-2
链接:https://leetcode-cn.com/problems/majority-element-ii/solution/mo-er-tou-piao-fa-de-jian-dan-li-jie-by-coldme-2/
"""
def majorityElement(nums):
# cand1, vote1 = None, 0
# cand2, vote2 = None, 0
# for i in range(len(nums)):
# if cand1 is None and cand2 != nums[i]:
# cand1 = nums[i]
# vote1 += 1
#
# elif cand2 is None and cand1 != nums[i]:
# cand2 = nums[i]
# vote2 += 1
#
# else:
# if cand1 == nums[i]:
# vote1 += 1
#
# elif cand2 == nums[i]:
# vote2 += 1
#
# else:
# vote1 -= 1
# vote2 -= 1
# if vote1 == 0:
# cand1 = None
# if vote2 == 0:
# cand2 = None
#
#
# vote1, vote2 = 0, 0
# for num in nums:
# if num == cand1:
# vote1 += 1
# if num == cand2:
# vote2 += 1
#
# ans = []
# if vote1> len(nums)//3:
# ans.append(cand1)
# if vote2 > len(nums)//3:
# ans.append(cand2)
#
# return ans
# 利用列表性质。
n = len(nums)
ans = []
for i in set(nums):
if nums.count(i) > n//3:
ans.append(i)
return ans
if __name__ == '__main__':
print(majorityElement([1,1,1,3,3,2,2,2]))
| [
"jgm247878528@.qq.com"
] | jgm247878528@.qq.com |
7a646e4ff9c4fbdfc86df4f374dc2c597cbac655 | f7caa651c21a9c6eee03e5bb74967880481fbe5f | /app/apps/notes/tests/tests_urls.py | d912c77fb778f420dd562f3d57cd0f5f1ccdfa19 | [
"MIT"
] | permissive | Capwell/practicum-app-profiles | f33bdaf575f97794c47eb1c6892d735c1257a9f5 | c3dbc4565f83300ec5e4cc25b434002690185e56 | refs/heads/main | 2023-03-01T19:56:47.689354 | 2021-02-02T05:25:45 | 2021-02-02T05:25:45 | 335,021,103 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,877 | py | from django.test import Client
from .fixtures import Settings
class ArticleURLTests(Settings):
def setUp(self):
self.authorized_client = Client()
self.authorized_client.force_login(ArticleURLTests.user_one)
# Common page
def test_home_url_exists_at_desired_location(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
# Autorized pages
def test_add_article_url_exists_at_desired_location(self):
response = self.authorized_client.get('/article/add/')
self.assertEqual(response.status_code, 200)
def test_articles_list_url_exists_at_desired_location_authorized(self):
response = self.authorized_client.get('/article/list/')
self.assertEqual(response.status_code, 200)
# Redirects for anonymous client
def test_add_article_url_redirect_anonymous_on_admin_login(self):
response = self.client.get('/article/add/', follow=True)
self.assertRedirects(
response, '/auth/login/?next=/article/add/')
def test_articles_list_url_redirect_anonymous_on_admin_login(self):
response = self.client.get('/article/list/', follow=True)
self.assertRedirects(
response, ('/auth/login/?next=/article/list/'))
def test_urls_uses_correct_template(self):
"""URL-адрес использует соответствующий шаблон."""
templates_url_names = {
'notes/home.html': '/',
'notes/add_article.html': '/article/add/',
'notes/articles_list.html': '/article/list/',
}
for template, url in templates_url_names.items():
with self.subTest(url=url):
response = self.authorized_client.get(url)
self.assertTemplateUsed(response, template)
| [
"proninc@yandex.ru"
] | proninc@yandex.ru |
9b4bfa3a8c824efe83f17773632977134e891853 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/40/usersdata/68/18502/submittedfiles/main.py | 9b3141f2cb1df838fab5b35110951b9ec577eca6 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,041 | py | # -*- coding: utf-8 -*-
from __future__ import division
import funcoes
#COMECE AQUI
def fatorial (m):
m_fat=1
for i in range (2,m+1,1):
m_fat=m_fat * i
return m_fat
m=int(input('Digite m:'))
e=input('Digite o epsilon para o cosseno:')
#DOUBLE CALCULA_VALOR_ABSOLUTO:
if m<0:
m=m*(-1)
#DOUBLE CALCULA_PI:
soma_pi=0
j=2
for i in range (0,m,1):
if i%2==0:
soma_pi=soma_pi+(4/(j*(j+1)*(j+2)))
else:
soma_pi=soma_pi-(4/(j*(j+1)*(j+2)))
j=j+2
pi=3+soma_pi
#DOUBLE CALCULA_CO_SENO:
soma_cosseno=0
i=1
j=2
#CHAMAR A SEGUNDA PARTE DA SOMA_COSSENO DE UMA VARIÁVEL:
'''
a= (((pi/5)**j)/fatorial(j)) e a repetição só iria acontecer enquanto a fosse menor ou igual a epsilon
'''
a=(((pi/5)**j)/fatorial (j))
while a>=e:
if i%2!=0:
soma_cosseno = soma_cosseno + a
else:
soma_cosseno = soma_cosseno - a
j=j+2
i=i+1
cosseno=1-soma_cosseno
#DOUBLE CALCULA_RAZAO_AUREA_:
razaoAurea= 2*cosseno
print('%.15f' %pi)
print('%.15f' %razaoAurea) | [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
37ceecc85d8bba20cdf64787fb4b0bb85cdcc5c8 | 9cfcfbd73d0f5f0c98bc6704e4faf93253b505d5 | /blogadmin/asgi.py | 87847bf0bf09d840633059f24dcdf9c93da6b90c | [] | no_license | Yashbontala/blogapp | 358943ac8a3350467b66211820666a14dae25c5b | 0edffb1f39cbcdd81350530fc0d7b308ea14b9a7 | refs/heads/main | 2023-04-19T08:20:14.151123 | 2021-05-08T17:52:02 | 2021-05-08T17:52:02 | 338,141,762 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 395 | py | """
ASGI config for blogadmin project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogadmin.settings')
application = get_asgi_application()
| [
"cse190001067@iiti.ac.in"
] | cse190001067@iiti.ac.in |
722c27df7fd700611dec028a8c6572f01c548438 | 6f23a5ba2426f456c8b17621f5a5d5b60b21cc67 | /app/core/migrations/0001_initial.py | 101a6e51baa12f8cc7c51615bec81cfc52f149fe | [
"MIT"
] | permissive | FernandoI7/recipe-app-api | fbde6a6b5633eebdaf5fe8983c4faf95d0819058 | 352b4fe811c19d083a71d7b45818ad360b08011e | refs/heads/master | 2021-09-26T22:46:09.717877 | 2021-06-14T13:43:07 | 2021-06-14T13:43:07 | 236,102,355 | 0 | 0 | null | 2021-09-22T18:28:06 | 2020-01-24T23:44:39 | Python | UTF-8 | Python | false | false | 1,700 | py | # Generated by Django 3.0.2 on 2020-01-25 01:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=80)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| [
"fernando.analista.si@gmail.com"
] | fernando.analista.si@gmail.com |
45f4f583d74140c6e4f7245c5c80667b711f9ede | 05cbe0cc96883ff1aa91a43d2c4e800040c09b83 | /Lesson 3/test/test_task_2.py | f1c52a77d0a7c41c18be815c345a0dac6dfb16bd | [] | no_license | volodin89/Artezio | 14740258dc2ed9adb5a614649ee43564d5d046e1 | 550520b846d6f532c804388f1a6d6bdac3796df6 | refs/heads/master | 2022-12-09T08:07:45.331375 | 2020-02-25T19:29:13 | 2020-02-25T19:29:13 | 236,572,594 | 0 | 0 | null | 2022-12-08T03:33:25 | 2020-01-27T19:17:51 | Python | UTF-8 | Python | false | false | 486 | py | import unittest
from task.task_2 import mul_and_sum
ARR = [15, 16, 17]
ARR.append(ARR)
class MyTestCase(unittest.TestCase):
def test_1(self):
self.assertEqual(mul_and_sum(1, 2, [3, 4, (5, 6, 0)], a=(10, 11), b=(3, 4, [5, 6, [7, 8], []])),
(75, 1596672000))
def test_2(self):
self.assertEqual(mul_and_sum(1, 2, ARR, [3, 4, (5, 6, 0)], a=(10, 11), b=(3, 4, [5, 6, [7, 8], []])), None)
if __name__ == '__main__':
unittest.main()
| [
"noreply@github.com"
] | noreply@github.com |
4ae63069c9db168ed2b353c07ca4be1860bdbf27 | a5bc1e504f39648b328d3a6ce957ca46fd3d890b | /PythonModulo1/ex031.py | 60689a63b9af3d3ef153ddccaf1121f5f03413ea | [
"MIT"
] | permissive | BossNX/ExerciciosDePython | 1b65e9da9f6dc3fcfc0a5495d9190934502ec868 | 27c79d284794f65f94d3a07de11429d665ec92da | refs/heads/main | 2023-02-13T10:39:34.072727 | 2021-01-16T01:15:26 | 2021-01-16T01:15:26 | 330,055,775 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | import emoji
dis = float(input('Qual é a distância da sua viagem? '))
if dis <= 200:
print('Você está prestes a começar uma viagem de {:.1f}Km.'.format(dis))
print('E o preço da sua passagem vai será de R${:.2f}'.format(dis * 0.50))
else:
print('Você está prestes a começar uma viagem de {:.1f}Km.'.format(dis))
print('E o preço da sua passagem será de R${:.2f}'.format(dis * 0.45))
print(emoji.emojize('Tenha uma boa viagem! :airplane:', use_aliases=True))
| [
"alcarvalho@nexusnx.com"
] | alcarvalho@nexusnx.com |
27a08eb30d71e7e87402e007bd2e80f8a737e78f | f745f3a48f17ca24080c37bc5aea4adb5f56a3d8 | /tubespbo/asgi.py | ad5760c2392267321114066c48e20bf51175609f | [] | no_license | andhikapp28/InventarisBarang | 36d659da1bd3e0fa5993528f55cf3c4dec119787 | 19181f230b411a3f3d79ad2a47c2113259eb9575 | refs/heads/main | 2023-07-25T14:33:01.110261 | 2021-09-09T01:48:22 | 2021-09-09T01:48:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | """
ASGI config for tubespbo project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tubespbo.settings')
application = get_asgi_application()
| [
"andhikapp28@gmail.com"
] | andhikapp28@gmail.com |
662c4c9164d7e51cdf66a14cd777870da9376bc0 | 76d7930fb7eed5ebcfb6e4e0ecd5887ad6d662bb | /LR9/LR9_1_Migranova.py | 396e001e471154ebf333d8464e7d68289f0dfa39 | [] | no_license | gulyash/AsyaPy | a486a26c166ede4c683228d1f72c4dd8e365d276 | 7d37726ddb2a7d9c91de091ec2a2ffe04a269231 | refs/heads/master | 2021-05-05T14:30:34.332839 | 2018-05-11T19:25:01 | 2018-05-11T19:25:01 | 105,151,828 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 587 | py | import sqlite3
import sys
db_file_path = sys.argv[1]
n = int(sys.argv[2])
conn = sqlite3.connect(db_file_path)
cursor = conn.cursor()
queries = [
"select model, speed, hdd from pc where price<50000;",
"select maker from product where type=\"printer\"",
"select model, ram, screen from laptop where price>23000",
"select * from printer where color=1",
"select model, speed, hdd from laptop where screen=13 and price<22000"
]
def run_query(query):
cursor.execute(query)
results = cursor.fetchall()
print(results)
run_query(queries[n])
conn.close()
| [
"rigdillinger@yandex.ru"
] | rigdillinger@yandex.ru |
2e4093e4080d4843f1d42bbaf61979a5c0a72d05 | 6349770545a11f6a06c2bbd1b1ed1852451f2a69 | /svm-training.py | f1306c0207bdb9bcadf62c8f3847372823f1232c | [] | no_license | satyamagni/Classification-of-steel-defects | f2e83a99048f6d30b43511dc1bd36723b3bdac88 | e16fd886c20a13dc8c60bd709d32445d09e28281 | refs/heads/master | 2023-06-25T17:59:57.823100 | 2021-07-19T18:08:35 | 2021-07-19T18:08:35 | 387,553,241 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,674 | py | #import timeit
#setup = '''
import numpy as np
from numpy.core.fromnumeric import argmin
import pandas as pd
from sklearn.svm import SVC
from sklearn import metrics
#'''
#my_code = '''
X = pd.read_csv("training-steel.csv", header = None)
Y = pd.read_csv("testing-steel.csv", header = None)
E = np.zeros(100)
#cross validation to determine gamma 'g'
for g in range(100):
err = np.zeros(4)
for b in range(4):
#centre and scaling (batch by batch, 4 batches for cross validation)
Xnp = X.to_numpy()
Xtesttemp = np.concatenate((Xnp[125*b:125*(b+1),:],Xnp[500+75*b:500+75*(b+1),:]))
Xctesttemp = Xtesttemp[:,27]
Xtraintemp = np.delete(Xnp,np.s_[125*b:125*(b+1)],0)
Xtraintemp = np.delete(Xtraintemp,np.s_[375+75*b:375+75*(b+1)],0)
Xctraintemp = Xtraintemp[:,27]
Xtraintemp = pd.DataFrame(Xtraintemp)
Xtesttemp = pd.DataFrame(Xtesttemp)
mu = np.mean(Xtraintemp)
Xtraintemp = Xtraintemp - mu
std = np.std(Xtraintemp)
Xtraintemp = Xtraintemp/std
Xtesttemp = Xtesttemp -mu
Xtesttemp = Xtesttemp/std
Xtraintemp = Xtraintemp.to_numpy()
Xtesttemp = Xtesttemp.to_numpy()
x=Xtraintemp[:,0:27]
y=Xtesttemp[:,0:27]
#model fitting
svm = SVC(kernel = 'rbf', gamma = (g+1)*0.01)
svm.fit(x,Xctraintemp)
Y_pred = svm.predict(y)
err[b] = sum(abs(Y_pred-Xctesttemp))
E[g] = np.sum(err)
#'''
#print (timeit.timeit(setup = setup, stmt = my_code, number = 1))
print(argmin(E)) | [
"satyamagnihotri97@gmail.com"
] | satyamagnihotri97@gmail.com |
891597ffbd86bd41f06525c3e177e644d99d3490 | dc2f5110c7620bb36465cc3d061a770a90f7bc36 | /EditHex/file.py | 3bda888ff9da80bdf5a97510eda19f7371b4522a | [] | no_license | 10121044100/HexEdit_test | e21ec9cf2b3c10dabe1980ad2b118f8d907fe0b7 | 1f150b62616e8177c7eda4c98ad9ef64344eec8e | refs/heads/master | 2020-03-19T07:11:33.788444 | 2018-06-13T07:33:13 | 2018-06-13T07:33:13 | 136,094,901 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | def read_file(file_name):
fd = open(file_name, "r")
data = fd.read()
fd.close()
return data
def write_file(file_name, data, isrewrite):
if isrewrite:
#unlink(file_name)
pass
with open(file_name, "w") as fd:
fd.write(data) | [
"ttm3246@gmail.com"
] | ttm3246@gmail.com |
912d1cc8bfd900d2efb1333cf76904f99bd70ae4 | e34cbf5fce48f661d08221c095750240dbd88caf | /python/day42_sqlalchemy/4.0.scoped_session.py | b723853a14b95b576bc03df5c3d1d10b7857df60 | [] | no_license | willianflasky/growup | 2f994b815b636e2582594375e90dbcb2aa37288e | 1db031a901e25bbe13f2d0db767cd28c76ac47f5 | refs/heads/master | 2023-01-04T13:13:14.191504 | 2020-01-12T08:11:41 | 2020-01-12T08:11:41 | 48,899,304 | 2 | 0 | null | 2022-12-26T19:46:22 | 2016-01-02T05:04:39 | C | UTF-8 | Python | false | false | 1,295 | py | #!/usr/bin/env python
# -*-coding:utf8-*-
# date: 2018/2/23 上午11:45
__author__ = "willian"
import time
import threading
import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship, scoped_session
from sqlalchemy import create_engine
from sqlalchemy.sql import text
engine = create_engine("mysql+pymysql://s6:s6@127.0.0.1:3306/s6", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
# 方式一: 由于无法提供线程共享功能,所以在开发时要注意,在每个线程中自己创建session.
# 自己具有操作数据库的 close commit execute...方法
# session = Session()
# session.close()
# 方式二: scoped_session 支持线程安全,为每个线程创建一个session
# - threading.Local
# - 唯一标识
# 源码剖析 第一步:command+单击
session = scoped_session(Session)
session.remove()
"""
session = scoped_session(Session)
session中两个值
1. self.session_factory
2. self.registry 中又有两个值, 加括号创建session
1> self.registry.self.session_factory(createfunc)
2> self.registry.self.registry(没有写错)
""" | [
"284607860@qq.com"
] | 284607860@qq.com |
915df08aef6b014649a2cfdf77fbeafcf063dc13 | ae76ec99494e64dc0ccced41063cd355d33b76fb | /InfrastructureLibs/CreateDeviceSession.py | 4316bbdcf14a9daf0f097acce45455b9432b2b0f | [] | no_license | tarunjain1986/Plivo | 242ea6fcbd0e54b96d4a36a1c3b467706a71471a | a12e1c907b44c578c4cfd12e08661ac9a4a6caa0 | refs/heads/master | 2021-01-12T15:19:10.332770 | 2016-10-24T09:49:45 | 2016-10-24T09:49:45 | 71,756,407 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,832 | py |
from appium import webdriver
from robot.libraries.BuiltIn import BuiltIn
import copy
from os.path import os
from selenium import webdriver
from selenium.webdriver.support.events import EventFiringWebDriver
from selenium.webdriver.support.events import AbstractEventListener
from robot.api import logger
from time import gmtime, strftime
class CreateDeviceSession:
'''
classdocs
Created on 22-Oct-2016
Creates instance of driver depending upon the input provided.
@author: tarunjain
'''
def openBrowser(self,device):
self.home_path = BuiltIn().get_variable_value("${globalTestBed}")["AutomationServer"]["HOME_PATH"]
self.reference = BuiltIn().get_variable_value("${references}")
self.Browser = BuiltIn().get_variable_value("${globalTestBed}")["DesktopBrowser"]["BROWSER"]
self.device = copy.deepcopy(self.reference)[device]
self.desired_caps = {}
logger.info("About to launch Browser")
if(self.Browser == "Firefox"):
self.driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.FIREFOX,command_executor='http://'+self.device["SELENIUMSERVERIP"]+':4444/wd/hub')
elif(self.Browser == "Chrome"):
self.driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.CHROME,command_executor='http://'+self.device["SELENIUMSERVERIP"]+':4444/wd/hub')
else:
self.driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.SAFARI,command_executor='http://'+self.device["SELENIUMSERVERIP"]+':4444/wd/hub')
logger.info("After launch Browser")
self.driver.implicitly_wait(10)
self.cur_session= {}
self.cur_session["session"] = self.driver
self.cur_session["properties"]= self.device
self.cur_session["guest"] = 1
self.driver = EventFiringWebDriver(self.driver, ScreenshotListener())
logger.info("Opening Url:" + self.device["URL"])
self.driver.get(self.device["URL"])
BuiltIn().set_global_variable("${cur_session}",self.cur_session)
BuiltIn().import_library(self.home_path+"/PageObjects/LoginPage.py")
def closeSession(self):
self.driver.quit()
class ScreenshotListener(AbstractEventListener):
def on_exception(self, exception, driver):
self.home_path = BuiltIn().get_variable_value("${globalTestBed}")["AutomationServer"]["HOME_PATH"]
self.driver = BuiltIn().get_variable_value("${cur_session}")["session"]
screenshot_name = BuiltIn().get_variable_value("${TEST NAME}") + strftime("%Y-%m-%d%H:%M:%S", gmtime()) +".png"
self.driver.get_screenshot_as_file(self.home_path + "/ScreenShots/" +screenshot_name)
logger.info("Screenshot saved as '%s'" % screenshot_name)
| [
"tarun.jain@urbanladder.com"
] | tarun.jain@urbanladder.com |
ff70c41058fbc39781806bc0112f697ccb29be21 | 9a4eb443ebb1ed7b2175bf9c8a9979009fbaa494 | /ops.py | 0baac7060e4065d4d50a4d2c21ea6d9624fa2567 | [] | no_license | jerrywiston/ExplorationRL | 96d774c243d908d171dc70b2383228ed9a0765eb | baa9a2881fb48ffed3300cfdb5c1d2fa00e5fb6f | refs/heads/master | 2020-05-10T00:24:09.856318 | 2019-04-16T12:26:07 | 2019-04-16T12:26:07 | 181,530,176 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,093 | py | import tensorflow as tf
import numpy as np
w_init = tf.contrib.layers.xavier_initializer()
b_init = tf.constant_initializer(0.1)
def bideconv2d(x, filters, kernel_size, strides, padding, activation, name):
shape_list = x.get_shape()
x_up = tf.image.resize_images(x, [shape_list[1]*strides[0], shape_list[2]*strides[1]], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
return tf.layers.conv2d(
x_up,
filters=filters,
kernel_size=kernel_size,
strides=(1,1),
padding=padding,
activation=activation,
kernel_initializer=w_init,
bias_initializer=b_init,
name=name)
def conv2d(x, filters, kernel_size, strides, padding, activation, name):
return tf.layers.conv2d(
x,
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
activation=activation,
kernel_initializer=w_init,
bias_initializer=b_init,
name=name)
def bn(x, training, name):
return tf.contrib.layers.batch_norm(
x,
decay=0.9,
updates_collections=None,
epsilon=1e-5,
scale=True,
is_training=training,
scope=name
)
def norm(x, norm_type, training, name='norm', G=16, esp=1e-5):
with tf.variable_scope('{}_{}_norm'.format(name,norm_type)):
if norm_type == 'none':
output = x
elif norm_type == 'batch':
output = tf.contrib.layers.batch_norm(
x, center=True, scale=True, decay=0.9,
is_training=training, updates_collections=None
)
elif norm_type == 'group':
# normalize
# tranpose: [bs, h, w, c] to [bs, c, h, w] following the paper
x = tf.transpose(x, [0, 3, 1, 2])
N, C, H, W = x.get_shape().as_list()
G = min(G, C)
print(name, x.get_shape().as_list(), x.shape)
x = tf.reshape(x, [-1, G, C // G, H, W])
mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True)
x = (x - mean) / tf.sqrt(var + esp)
# per channel gamma and beta
gamma = tf.get_variable('gamma', [C],
initializer=tf.constant_initializer(1.0))
beta = tf.get_variable('beta', [C],
initializer=tf.constant_initializer(0.0))
gamma = tf.reshape(gamma, [1, C, 1, 1])
beta = tf.reshape(beta, [1, C, 1, 1])
output = tf.reshape(x, [-1, C, H, W]) * gamma + beta
# tranpose: [bs, c, h, w, c] to [bs, h, w, c] following the paper
output = tf.transpose(output, [0, 2, 3, 1])
else:
raise NotImplementedError
return output
def fc(x, units, activation, name):
return tf.layers.dense(x, units, activation=activation, kernel_initializer=w_init, bias_initializer=b_init, name=name)
def lrelu(x, leak=0.2):
return tf.maximum(x, leak*x) | [
"dreamfantasy0@gmail.com"
] | dreamfantasy0@gmail.com |
59d6c24f2152d8345051f7f14a88cdfb6d9f8b71 | b221b5001fd086e8dc6ed7215c50ac642ebf7d87 | /transcribe.py | 2605e0fa8a9a44a9181673bc381f869b788cfd9a | [] | no_license | annitak/iot-journal | 14657d5f83f903ffa1863c3d15ecdedfaf6a08fc | d678b539d6440a98ec95e83e29c77e9d643a2efa | refs/heads/master | 2021-01-18T23:59:47.902820 | 2017-04-07T23:11:46 | 2017-04-07T23:11:46 | 72,824,943 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,036 | py | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Google Cloud Speech API sample application using the REST API for batch
processing."""
# [START import_libraries]
import argparse
import base64
import json
from googleapiclient import discovery
import httplib2
from oauth2client.client import GoogleCredentials
# [END import_libraries]
# [START authenticating]
DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?'
'version={apiVersion}')
# Application default credentials provided by env variable
# GOOGLE_APPLICATION_CREDENTIALS
def get_speech_service():
credentials = GoogleCredentials.get_application_default().create_scoped(
['https://www.googleapis.com/auth/cloud-platform'])
http = httplib2.Http()
credentials.authorize(http)
return discovery.build(
'speech', 'v1beta1', http=http, discoveryServiceUrl=DISCOVERY_URL)
# [END authenticating]
def main(speech_file):
"""Transcribe the given audio file.
Args:
speech_file: the name of the audio file.
"""
# [START construct_request]
with open(speech_file, 'rb') as speech:
# Base64 encode the binary audio file for inclusion in the JSON
# request.
speech_content = base64.b64encode(speech.read())
service = get_speech_service()
service_request = service.speech().syncrecognize(
body={
'config': {
# There are a bunch of config options you can specify. See
# https://goo.gl/KPZn97 for the full list.
'encoding': 'LINEAR16', # raw 16-bit signed LE samples
'sampleRate': 44100, # 44.1 khz
# See http://g.co/cloud/speech/docs/languages for a list of
# supported languages.
'languageCode': 'en-US', # a BCP-47 language tag
'maxAlternatives': 1, # return max of 1 alternatives
},
'audio': {
'content': speech_content.decode('UTF-8')
}
})
# [END construct_request]
# [START send_request]
response = service_request.execute()
print(json.dumps(response))
# [END send_request]
# [START run_application]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'speech_file', help='Full path of audio file to be recognized')
args = parser.parse_args()
main(args.speech_file)
# [END run_application]
| [
"noreply@github.com"
] | noreply@github.com |
5e8e3c2e021324492b3bddcc3682d341a0a778d6 | 4946fa19e840aafb7b3ed4ae159764af44c0ff34 | /pages/urls.py | fd2b01a536ecda7eb1db9d3615cd50bf4701a964 | [] | no_license | palmman/pedshop | c804be2fa8d1a7ce49c86c433a9bb00731146811 | 74aa002272e286e220e1e66fb701209ce9a055a6 | refs/heads/main | 2023-04-18T00:10:59.525763 | 2021-04-28T05:51:38 | 2021-04-28T05:51:38 | 362,352,612 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 383 | py | from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('shop', views.shop, name='shop'),
path('about', views.about, name='about'),
path('contact', views.contact, name='contact'),
path('<int:id>', views.product, name='product'),
path('category/<slug:pages_slug>/', views.shop, name='products_by_category'),
]
| [
"palm454555@hotmail.com"
] | palm454555@hotmail.com |
cc23ce4e71e80a4d08e3686b945fbebc6445f7c7 | 5bda2d41ba5e26af8e8df29d8965e19279106b24 | /deep_dss/__init__.py | e952939ca3975e87442cb72a3dc3392baf5bfd4b | [
"MIT"
] | permissive | adiraju21s/deep_dss | db1cf379c4a0ae6b05db58855a958cbb991e36fb | 360a08f5da38fdb7af9a8534702cc711b66a4343 | refs/heads/master | 2023-03-21T02:15:35.085429 | 2021-03-18T18:22:24 | 2021-03-18T18:22:24 | 278,965,591 | 0 | 0 | MIT | 2020-07-12T03:51:44 | 2020-07-12T00:44:24 | Python | UTF-8 | Python | false | false | 87 | py | __author__ = 'Sreyas Adiraju'
__email__ = 'adiraju21s@ncssm.edu'
__version__ = '0.1.0'
| [
"adiraju21s@ncssm.edu"
] | adiraju21s@ncssm.edu |
0d1dbedc820c68572b5dd505298b12664be1cb05 | f90b5735b5a3d04569a963586cc668ad5bae5ed0 | /scripts/strings/slicing.py | c580d3be5466cdaa1159ded279263176d5fa97b2 | [] | no_license | thaisvergani/arquivos_curso | 2c113b1656bbf7d774260ecbb7063060559b9233 | a3fa066a20d69c016a71dc5ffedc131ee3914a3c | refs/heads/master | 2021-09-10T04:40:48.572391 | 2018-03-21T02:25:27 | 2018-03-21T02:25:27 | 126,066,794 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | s = 'hello world'
# fatiando (incluindo inicio, excluindo o final)
s[1:4] # -> 'ell'
# a partir do início do índice
s[:4] # -> 'hell'
# a partir do final do índice
s[3:] # -> 'lo world'
# pode usar índice negativo também
s[2:-2] # -> 'llo wor'
# saltos
s[::2] # -> 'hlowrd'
s[1::2] # -> 'el ol'
# saltos negativos
s[::-1] # -> 'dlrow olleh'
| [
"thais.vergani1@gmail.com"
] | thais.vergani1@gmail.com |
ce7ea7ecafd00ae2635bc42169d0e0bc985cc884 | 1228b521ca4d82f8277112da42394ce49511c12d | /PVTX/PVStudy/python/TrackSplitterProducer_cff.py | 0a09bd058ad3b90d37d83d9d8160295d30739fdc | [] | no_license | sergojin/usercode | d9b0f8b6a31a9f127a4e3b8846fa50cfbfd6d6ff | d4ea548b03460ca49ca7ecf6a205bd705f8d624e | refs/heads/master | 2020-05-30T22:04:17.643972 | 2013-06-21T16:30:56 | 2013-06-21T16:30:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 100 | py | import FWCore.ParameterSet.Config as cms
from UserCode.PVStudy.TrackSplitterProducer_cfi import *
| [
""
] | |
36347c72287f1e86a3606556cf59a811c506c22d | 12be9a01f1231e5cc6ecbaabef965d8fbadbc171 | /Random_Files/animalsPy/main.py | b0fa9debd48074d436bd627757c8deebc881f156 | [] | no_license | SharanSMenon/Programming | f74b7d61ba64c9fb45f63d85b42454817a4ffd85 | fb262b0f3d5deffc8504023aa7d870d209953123 | refs/heads/master | 2020-03-18T00:45:05.214552 | 2018-08-09T21:34:44 | 2018-08-09T21:34:44 | 134,110,834 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 439 | py | from species import *
l = Lion("Matsumi", 12)
l.whoami();
l.eat()
l.getMType()
print("----")
t = Tiger("Puli", 13)
t.whoami();
t.eat()
t.getMType()
print("----")
e = Elephant("Ana", 47)
e.whoami();
e.eat()
e.getMType()
print("----")
h = Human("Mandan", 30)
h.whoami();
h.eat()
h.getMType()
print("----")
cr = Crocodile("Pumba", 69)
cr.whoami();
cr.eat()
cr.getMType()
print("----")
fr = Frog("Manny", 1)
fr.whoami();
fr.eat()
h.getMType()
| [
"sharansajivmenon@gmail.com"
] | sharansajivmenon@gmail.com |
fc5ba79ec6e95db83e771602a19129f81c081955 | 141c90d762260337eaccf1ce633351c56942d2ed | /gametest-master_tar/zoombie.py | b347e61e3ec6db532258a0e4073e27f5e2eb2899 | [] | no_license | silago/gametest | f8499875848d13bae662dfb2d8787b0d009ba589 | dc2620805f1708463268133512a9c4292f919f28 | refs/heads/master | 2021-01-10T19:43:50.250715 | 2014-01-13T04:26:42 | 2014-01-13T04:26:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,088 | py | import cocos
from math import sin,cos,radians, atan2, pi
import pyglet
from cocos.actions import *
from time import sleep
import threading
from classchar import *
from classman import *
from random import randint
def Zombiing(scene,victim):
if not getattr(scene,'zoombies',False):
scene.zoombies = []
z = Zoombie()
z.position = randint(-10,500),randint(10,20)*-1
#z.scale = float(randint(15,30))/100
z.scale = 1
z.victim = victim
z.hunt()
scene.zoombies.append(z)
scene.add(z,2)
scene.collision_manager.add(z)
class Zoombie(Char):
def __init__(self):
Char.__init__(self,'zoombie.png')
self.victim = False
self.position = 220,240
self.speed = 1
self.stepping_aside = False
#self.shape.collision_type=2
def move(self, some):
to_step = False
if self.parent.collision_manager.objs_colliding(self):
for i in self.parent.collision_manager.objs_colliding(self):
if i!=self and isinstance(i,Zoombie):
to_step = True
break
if (to_step): self.step_aside(i)
else: Char.move(self,some)
#else: pass
def step_aside(self,obj):
self.stepping_aside = True
x = (self.position[0]-obj.position[0])
y = (self.position[1]-obj.position[1])
self.do(MoveBy((x,y),2))
self.update_cshape()
def hit(self, target):
target.hurt()
def hunt(self):
if not self.victim:
print "nothing to hunt"
else:
self.schedule(self.look_to_victim)
#self.look_to_victim(False)
def die(self):
self.parent.score_text.element.text=str(int(self.parent.score_text.element.text)+1)
self.unschedule(self.look_to_victim)
self.parent.add(cocos.sprite.Sprite('zoombie_dead.png',self.position,randint(1,360),5,100),1)
#self.image = pyglet.image.load('zoombie_dead.png')
#for i in range((randint(1,2))):
Zombiing(self.parent,self.victim)
Char.die(self)
def look_to_victim(self,some):
a = list(self.position)
b = list(self.victim.position)
r = atan2(a[1] - b[1], a[0] - b[0]) / pi * 180
r = r + 90
r = r * -1
if (r<0): r+=360
r = (r-self.rotation)
self.turn(False,r)
self.move(False)
#print r
| [
"silago.nevermind@gmail.com"
] | silago.nevermind@gmail.com |
2a29dc528d6fecc104cb427a3bf075c0acb82089 | c2df9e04adec78e789d1fbdb0711c45e5b9263a7 | /venv/Lib/site-packages/matplotlib/patches.py | 9cbba65bbb9b007fbf470b1681f317385db6d8e6 | [
"MIT",
"BSD-3-Clause"
] | permissive | AdarshSai/Final_Project | 433009a2f416e894ee3be85cd9317cb8e8df5516 | f966834ca72dd232102ed500ef47ef2b3bdbed5b | refs/heads/main | 2023-01-23T12:21:41.342074 | 2020-11-19T22:24:15 | 2020-11-19T22:24:15 | 308,898,012 | 0 | 1 | MIT | 2020-11-19T22:24:17 | 2020-10-31T14:19:58 | Python | UTF-8 | Python | false | false | 153,320 | py | import contextlib
import functools
import inspect
import math
from numbers import Number
import textwrap
import numpy as np
import matplotlib as mpl
from . import artist, cbook, colors, docstring, lines as mlines, transforms
from .bezier import (
NonIntersectingPathException, get_cos_sin, get_intersection,
get_parallels, inside_circle, make_wedged_bezier2,
split_bezier_intersecting_with_closedpath, split_path_inout)
from .path import Path
@cbook._define_aliases({
"antialiased": ["aa"],
"edgecolor": ["ec"],
"facecolor": ["fc"],
"linestyle": ["ls"],
"linewidth": ["lw"],
})
class Patch(artist.Artist):
"""
A patch is a 2D artist with a face color and an edge color.
If any of *edgecolor*, *facecolor*, *linewidth*, or *antialiased*
are *None*, they default to their rc params setting.
"""
zorder = 1
validCap = mlines.Line2D.validCap
validJoin = mlines.Line2D.validJoin
# Whether to draw an edge by default. Set on a
# subclass-by-subclass basis.
_edge_default = False
def __init__(self,
edgecolor=None,
facecolor=None,
color=None,
linewidth=None,
linestyle=None,
antialiased=None,
hatch=None,
fill=True,
capstyle=None,
joinstyle=None,
**kwargs):
"""
The following kwarg properties are supported
%(Patch)s
"""
artist.Artist.__init__(self)
if linewidth is None:
linewidth = mpl.rcParams['patch.linewidth']
if linestyle is None:
linestyle = "solid"
if capstyle is None:
capstyle = 'butt'
if joinstyle is None:
joinstyle = 'miter'
if antialiased is None:
antialiased = mpl.rcParams['patch.antialiased']
self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color'])
self._fill = True # needed for set_facecolor call
if color is not None:
if edgecolor is not None or facecolor is not None:
cbook._warn_external(
"Setting the 'color' property will override "
"the edgecolor or facecolor properties.")
self.set_color(color)
else:
self.set_edgecolor(edgecolor)
self.set_facecolor(facecolor)
# unscaled dashes. Needed to scale dash patterns by lw
self._us_dashes = None
self._linewidth = 0
self.set_fill(fill)
self.set_linestyle(linestyle)
self.set_linewidth(linewidth)
self.set_antialiased(antialiased)
self.set_hatch(hatch)
self.set_capstyle(capstyle)
self.set_joinstyle(joinstyle)
if len(kwargs):
self.update(kwargs)
def get_verts(self):
"""
Return a copy of the vertices used in this patch.
If the patch contains Bezier curves, the curves will be interpolated by
line segments. To access the curves as curves, use `get_path`.
"""
trans = self.get_transform()
path = self.get_path()
polygons = path.to_polygons(trans)
if len(polygons):
return polygons[0]
return []
def _process_radius(self, radius):
if radius is not None:
return radius
if isinstance(self._picker, Number):
_radius = self._picker
else:
if self.get_edgecolor()[3] == 0:
_radius = 0
else:
_radius = self.get_linewidth()
return _radius
def contains(self, mouseevent, radius=None):
"""
Test whether the mouse event occurred in the patch.
Returns
-------
(bool, empty dict)
"""
inside, info = self._default_contains(mouseevent)
if inside is not None:
return inside, info
radius = self._process_radius(radius)
codes = self.get_path().codes
if codes is not None:
vertices = self.get_path().vertices
# if the current path is concatenated by multiple sub paths.
# get the indexes of the starting code(MOVETO) of all sub paths
idxs, = np.where(codes == Path.MOVETO)
# Don't split before the first MOVETO.
idxs = idxs[1:]
subpaths = map(
Path, np.split(vertices, idxs), np.split(codes, idxs))
else:
subpaths = [self.get_path()]
inside = any(
subpath.contains_point(
(mouseevent.x, mouseevent.y), self.get_transform(), radius)
for subpath in subpaths)
return inside, {}
def contains_point(self, point, radius=None):
"""
Return whether the given point is inside the patch.
Parameters
----------
point : (float, float)
The point (x, y) to check, in target coordinates of
``self.get_transform()``. These are display coordinates for patches
that are added to a figure or axes.
radius : float, optional
Add an additional margin on the patch in target coordinates of
``self.get_transform()``. See `.Path.contains_point` for further
details.
Returns
-------
bool
Notes
-----
The proper use of this method depends on the transform of the patch.
Isolated patches do not have a transform. In this case, the patch
creation coordinates and the point coordinates match. The following
example checks that the center of a circle is within the circle
>>> center = 0, 0
>>> c = Circle(center, radius=1)
>>> c.contains_point(center)
True
The convention of checking against the transformed patch stems from
the fact that this method is predominantly used to check if display
coordinates (e.g. from mouse events) are within the patch. If you want
to do the above check with data coordinates, you have to properly
transform them first:
>>> center = 0, 0
>>> c = Circle(center, radius=1)
>>> plt.gca().add_patch(c)
>>> transformed_center = c.get_transform().transform(center)
>>> c.contains_point(transformed_center)
True
"""
radius = self._process_radius(radius)
return self.get_path().contains_point(point,
self.get_transform(),
radius)
def contains_points(self, points, radius=None):
"""
Return whether the given points are inside the patch.
Parameters
----------
points : (N, 2) array
The points to check, in target coordinates of
``self.get_transform()``. These are display coordinates for patches
that are added to a figure or axes. Columns contain x and y values.
radius : float, optional
Add an additional margin on the patch in target coordinates of
``self.get_transform()``. See `.Path.contains_point` for further
details.
Returns
-------
length-N bool array
Notes
-----
The proper use of this method depends on the transform of the patch.
See the notes on `.Patch.contains_point`.
"""
radius = self._process_radius(radius)
return self.get_path().contains_points(points,
self.get_transform(),
radius)
def update_from(self, other):
# docstring inherited.
artist.Artist.update_from(self, other)
# For some properties we don't need or don't want to go through the
# getters/setters, so we just copy them directly.
self._edgecolor = other._edgecolor
self._facecolor = other._facecolor
self._original_edgecolor = other._original_edgecolor
self._original_facecolor = other._original_facecolor
self._fill = other._fill
self._hatch = other._hatch
self._hatch_color = other._hatch_color
# copy the unscaled dash pattern
self._us_dashes = other._us_dashes
self.set_linewidth(other._linewidth) # also sets dash properties
self.set_transform(other.get_data_transform())
# If the transform of other needs further initialization, then it will
# be the case for this artist too.
self._transformSet = other.is_transform_set()
def get_extents(self):
"""
Return the `Patch`'s axis-aligned extents as a `~.transforms.Bbox`.
"""
return self.get_path().get_extents(self.get_transform())
def get_transform(self):
"""Return the `~.transforms.Transform` applied to the `Patch`."""
return self.get_patch_transform() + artist.Artist.get_transform(self)
def get_data_transform(self):
"""
Return the `~.transforms.Transform` mapping data coordinates to
physical coordinates.
"""
return artist.Artist.get_transform(self)
def get_patch_transform(self):
"""
Return the `~.transforms.Transform` instance mapping patch coordinates
to data coordinates.
For example, one may define a patch of a circle which represents a
radius of 5 by providing coordinates for a unit circle, and a
transform which scales the coordinates (the patch coordinate) by 5.
"""
return transforms.IdentityTransform()
def get_antialiased(self):
"""Return whether antialiasing is used for drawing."""
return self._antialiased
def get_edgecolor(self):
"""Return the edge color."""
return self._edgecolor
def get_facecolor(self):
"""Return the face color."""
return self._facecolor
def get_linewidth(self):
"""Return the line width in points."""
return self._linewidth
def get_linestyle(self):
"""Return the linestyle."""
return self._linestyle
def set_antialiased(self, aa):
"""
Set whether to use antialiased rendering.
Parameters
----------
b : bool or None
"""
if aa is None:
aa = mpl.rcParams['patch.antialiased']
self._antialiased = aa
self.stale = True
def _set_edgecolor(self, color):
set_hatch_color = True
if color is None:
if (mpl.rcParams['patch.force_edgecolor'] or
not self._fill or self._edge_default):
color = mpl.rcParams['patch.edgecolor']
else:
color = 'none'
set_hatch_color = False
self._edgecolor = colors.to_rgba(color, self._alpha)
if set_hatch_color:
self._hatch_color = self._edgecolor
self.stale = True
def set_edgecolor(self, color):
"""
Set the patch edge color.
Parameters
----------
color : color or None or 'auto'
"""
self._original_edgecolor = color
self._set_edgecolor(color)
def _set_facecolor(self, color):
if color is None:
color = mpl.rcParams['patch.facecolor']
alpha = self._alpha if self._fill else 0
self._facecolor = colors.to_rgba(color, alpha)
self.stale = True
def set_facecolor(self, color):
"""
Set the patch face color.
Parameters
----------
color : color or None
"""
self._original_facecolor = color
self._set_facecolor(color)
def set_color(self, c):
"""
Set both the edgecolor and the facecolor.
Parameters
----------
c : color
See Also
--------
Patch.set_facecolor, Patch.set_edgecolor
For setting the edge or face color individually.
"""
self.set_facecolor(c)
self.set_edgecolor(c)
def set_alpha(self, alpha):
# docstring inherited
super().set_alpha(alpha)
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
# stale is already True
def set_linewidth(self, w):
"""
Set the patch linewidth in points.
Parameters
----------
w : float or None
"""
if w is None:
w = mpl.rcParams['patch.linewidth']
if w is None:
w = mpl.rcParams['axes.linewidth']
self._linewidth = float(w)
# scale the dash pattern by the linewidth
offset, ls = self._us_dashes
self._dashoffset, self._dashes = mlines._scale_dashes(
offset, ls, self._linewidth)
self.stale = True
def set_linestyle(self, ls):
"""
Set the patch linestyle.
=========================== =================
linestyle description
=========================== =================
``'-'`` or ``'solid'`` solid line
``'--'`` or ``'dashed'`` dashed line
``'-.'`` or ``'dashdot'`` dash-dotted line
``':'`` or ``'dotted'`` dotted line
=========================== =================
Alternatively a dash tuple of the following form can be provided::
(offset, onoffseq)
where ``onoffseq`` is an even length tuple of on and off ink in points.
Parameters
----------
ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
The line style.
"""
if ls is None:
ls = "solid"
self._linestyle = ls
# get the unscaled dash pattern
offset, ls = self._us_dashes = mlines._get_dash_pattern(ls)
# scale the dash pattern by the linewidth
self._dashoffset, self._dashes = mlines._scale_dashes(
offset, ls, self._linewidth)
self.stale = True
def set_fill(self, b):
"""
Set whether to fill the patch.
Parameters
----------
b : bool
"""
self._fill = bool(b)
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)
self.stale = True
def get_fill(self):
"""Return whether the patch is filled."""
return self._fill
# Make fill a property so as to preserve the long-standing
# but somewhat inconsistent behavior in which fill was an
# attribute.
fill = property(get_fill, set_fill)
def set_capstyle(self, s):
"""
Set the capstyle.
Parameters
----------
s : {'butt', 'round', 'projecting'}
"""
mpl.rcsetup.validate_capstyle(s)
self._capstyle = s
self.stale = True
def get_capstyle(self):
"""Return the capstyle."""
return self._capstyle
def set_joinstyle(self, s):
"""
Set the joinstyle.
Parameters
----------
s : {'miter', 'round', 'bevel'}
"""
mpl.rcsetup.validate_joinstyle(s)
self._joinstyle = s
self.stale = True
def get_joinstyle(self):
"""Return the joinstyle."""
return self._joinstyle
def set_hatch(self, hatch):
r"""
Set the hatching pattern.
*hatch* can be one of::
/ - diagonal hatching
\ - back diagonal
| - vertical
- - horizontal
+ - crossed
x - crossed diagonal
o - small circle
O - large circle
. - dots
* - stars
Letters can be combined, in which case all the specified
hatchings are done. If same letter repeats, it increases the
density of hatching of that pattern.
Hatching is supported in the PostScript, PDF, SVG and Agg
backends only.
Parameters
----------
hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
"""
self._hatch = hatch
self.stale = True
def get_hatch(self):
"""Return the hatching pattern."""
return self._hatch
@contextlib.contextmanager
def _bind_draw_path_function(self, renderer):
"""
``draw()`` helper factored out for sharing with `FancyArrowPatch`.
Yields a callable ``dp`` such that calling ``dp(*args, **kwargs)`` is
equivalent to calling ``renderer1.draw_path(gc, *args, **kwargs)``
where ``renderer1`` and ``gc`` have been suitably set from ``renderer``
and the artist's properties.
"""
renderer.open_group('patch', self.get_gid())
gc = renderer.new_gc()
gc.set_foreground(self._edgecolor, isRGBA=True)
lw = self._linewidth
if self._edgecolor[3] == 0:
lw = 0
gc.set_linewidth(lw)
gc.set_dashes(self._dashoffset, self._dashes)
gc.set_capstyle(self._capstyle)
gc.set_joinstyle(self._joinstyle)
gc.set_antialiased(self._antialiased)
self._set_gc_clip(gc)
gc.set_url(self._url)
gc.set_snap(self.get_snap())
gc.set_alpha(self._alpha)
if self._hatch:
gc.set_hatch(self._hatch)
gc.set_hatch_color(self._hatch_color)
if self.get_sketch_params() is not None:
gc.set_sketch_params(*self.get_sketch_params())
if self.get_path_effects():
from matplotlib.patheffects import PathEffectRenderer
renderer = PathEffectRenderer(self.get_path_effects(), renderer)
# In `with _bind_draw_path_function(renderer) as draw_path: ...`
# (in the implementations of `draw()` below), calls to `draw_path(...)`
# will occur as if they took place here with `gc` inserted as
# additional first argument.
yield functools.partial(renderer.draw_path, gc)
gc.restore()
renderer.close_group('patch')
self.stale = False
@artist.allow_rasterization
def draw(self, renderer):
# docstring inherited
if not self.get_visible():
return
# Patch has traditionally ignored the dashoffset.
with cbook._setattr_cm(self, _dashoffset=0), \
self._bind_draw_path_function(renderer) as draw_path:
path = self.get_path()
transform = self.get_transform()
tpath = transform.transform_path_non_affine(path)
affine = transform.get_affine()
draw_path(tpath, affine,
# Work around a bug in the PDF and SVG renderers, which
# do not draw the hatches if the facecolor is fully
# transparent, but do if it is None.
self._facecolor if self._facecolor[3] else None)
def get_path(self):
"""Return the path of this patch."""
raise NotImplementedError('Derived must override')
def get_window_extent(self, renderer=None):
return self.get_path().get_extents(self.get_transform())
def _convert_xy_units(self, xy):
"""Convert x and y units for a tuple (x, y)."""
x = self.convert_xunits(xy[0])
y = self.convert_yunits(xy[1])
return x, y
patchdoc = artist.kwdoc(Patch)
for k in ['Rectangle', 'Circle', 'RegularPolygon', 'Polygon', 'Wedge', 'Arrow',
'FancyArrow', 'CirclePolygon', 'Ellipse', 'Arc', 'FancyBboxPatch',
'Patch']:
docstring.interpd.update({k: patchdoc})
# define Patch.__init__ docstring after the class has been added to interpd
docstring.dedent_interpd(Patch.__init__)
class Shadow(Patch):
def __str__(self):
return "Shadow(%s)" % (str(self.patch))
@cbook._delete_parameter("3.3", "props")
@docstring.dedent_interpd
def __init__(self, patch, ox, oy, props=None, **kwargs):
"""
Create a shadow of the given *patch*.
By default, the shadow will have the same face color as the *patch*,
but darkened.
Parameters
----------
patch : `.Patch`
The patch to create the shadow for.
ox, oy : float
The shift of the shadow in data coordinates, scaled by a factor
of dpi/72.
props : dict
*deprecated (use kwargs instead)* Properties of the shadow patch.
**kwargs
Properties of the shadow patch. Supported keys are:
%(Patch)s
"""
Patch.__init__(self)
self.patch = patch
# Note: when removing props, we can directly pass kwargs to _update()
# and remove self._props
if props is None:
color = .3 * np.asarray(colors.to_rgb(self.patch.get_facecolor()))
props = {
'facecolor': color,
'edgecolor': color,
'alpha': 0.5,
}
self._props = {**props, **kwargs}
self._ox, self._oy = ox, oy
self._shadow_transform = transforms.Affine2D()
self._update()
props = cbook._deprecate_privatize_attribute("3.3")
def _update(self):
self.update_from(self.patch)
# Place the shadow patch directly behind the inherited patch.
self.set_zorder(np.nextafter(self.patch.zorder, -np.inf))
self.update(self._props)
def _update_transform(self, renderer):
ox = renderer.points_to_pixels(self._ox)
oy = renderer.points_to_pixels(self._oy)
self._shadow_transform.clear().translate(ox, oy)
def _get_ox(self):
return self._ox
def _set_ox(self, ox):
self._ox = ox
def _get_oy(self):
return self._oy
def _set_oy(self, oy):
self._oy = oy
def get_path(self):
return self.patch.get_path()
def get_patch_transform(self):
return self.patch.get_patch_transform() + self._shadow_transform
def draw(self, renderer):
self._update_transform(renderer)
Patch.draw(self, renderer)
class Rectangle(Patch):
"""
A rectangle defined via an anchor point *xy* and its *width* and *height*.
The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction
and from ``xy[1]`` to ``xy[1] + height`` in y-direction. ::
: +------------------+
: | |
: height |
: | |
: (xy)---- width -----+
One may picture *xy* as the bottom left corner, but which corner *xy* is
actually depends on the the direction of the axis and the sign of *width*
and *height*; e.g. *xy* would be the bottom right corner if the x-axis
was inverted or if *width* was negative.
"""
def __str__(self):
pars = self._x0, self._y0, self._width, self._height, self.angle
fmt = "Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0.0, **kwargs):
"""
Parameters
----------
xy : (float, float)
The anchor point.
width : float
Rectangle width.
height : float
Rectangle height.
angle : float, default: 0
Rotation in degrees anti-clockwise about *xy*.
Other Parameters
----------------
**kwargs : `.Patch` properties
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._x0 = xy[0]
self._y0 = xy[1]
self._width = width
self._height = height
self._x1 = self._x0 + self._width
self._y1 = self._y0 + self._height
self.angle = float(angle)
# Note: This cannot be calculated until this is added to an Axes
self._rect_transform = transforms.IdentityTransform()
def get_path(self):
"""Return the vertices of the rectangle."""
return Path.unit_rectangle()
def _update_patch_transform(self):
"""
Notes
-----
This cannot be called until after this has been added to an Axes,
otherwise unit conversion will fail. This makes it very important to
call the accessor method and not directly access the transformation
member variable.
"""
x0, y0, x1, y1 = self._convert_units()
bbox = transforms.Bbox.from_extents(x0, y0, x1, y1)
rot_trans = transforms.Affine2D()
rot_trans.rotate_deg_around(x0, y0, self.angle)
self._rect_transform = transforms.BboxTransformTo(bbox)
self._rect_transform += rot_trans
def _update_x1(self):
self._x1 = self._x0 + self._width
def _update_y1(self):
self._y1 = self._y0 + self._height
def _convert_units(self):
"""Convert bounds of the rectangle."""
x0 = self.convert_xunits(self._x0)
y0 = self.convert_yunits(self._y0)
x1 = self.convert_xunits(self._x1)
y1 = self.convert_yunits(self._y1)
return x0, y0, x1, y1
def get_patch_transform(self):
self._update_patch_transform()
return self._rect_transform
def get_x(self):
"""Return the left coordinate of the rectangle."""
return self._x0
def get_y(self):
"""Return the bottom coordinate of the rectangle."""
return self._y0
def get_xy(self):
"""Return the left and bottom coords of the rectangle as a tuple."""
return self._x0, self._y0
def get_width(self):
"""Return the width of the rectangle."""
return self._width
def get_height(self):
"""Return the height of the rectangle."""
return self._height
def set_x(self, x):
"""Set the left coordinate of the rectangle."""
self._x0 = x
self._update_x1()
self.stale = True
def set_y(self, y):
"""Set the bottom coordinate of the rectangle."""
self._y0 = y
self._update_y1()
self.stale = True
def set_xy(self, xy):
"""
Set the left and bottom coordinates of the rectangle.
Parameters
----------
xy : (float, float)
"""
self._x0, self._y0 = xy
self._update_x1()
self._update_y1()
self.stale = True
def set_width(self, w):
"""Set the width of the rectangle."""
self._width = w
self._update_x1()
self.stale = True
def set_height(self, h):
"""Set the height of the rectangle."""
self._height = h
self._update_y1()
self.stale = True
def set_bounds(self, *args):
"""
Set the bounds of the rectangle as *left*, *bottom*, *width*, *height*.
The values may be passed as separate parameters or as a tuple::
set_bounds(left, bottom, width, height)
set_bounds((left, bottom, width, height))
.. ACCEPTS: (left, bottom, width, height)
"""
if len(args) == 1:
l, b, w, h = args[0]
else:
l, b, w, h = args
self._x0 = l
self._y0 = b
self._width = w
self._height = h
self._update_x1()
self._update_y1()
self.stale = True
def get_bbox(self):
"""Return the `.Bbox`."""
x0, y0, x1, y1 = self._convert_units()
return transforms.Bbox.from_extents(x0, y0, x1, y1)
xy = property(get_xy, set_xy)
class RegularPolygon(Patch):
"""A regular polygon patch."""
def __str__(self):
s = "RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)"
return s % (self._xy[0], self._xy[1], self._numVertices, self._radius,
self._orientation)
@docstring.dedent_interpd
def __init__(self, xy, numVertices, radius=5, orientation=0,
**kwargs):
"""
Parameters
----------
xy : (float, float)
The center position.
numVertices : int
The number of vertices.
radius : float
The distance from the center to each of the vertices.
orientation : float
The polygon rotation angle (in radians).
**kwargs
`Patch` properties:
%(Patch)s
"""
self._xy = xy
self._numVertices = numVertices
self._orientation = orientation
self._radius = radius
self._path = Path.unit_regular_polygon(numVertices)
self._poly_transform = transforms.Affine2D()
self._update_transform()
Patch.__init__(self, **kwargs)
def _update_transform(self):
self._poly_transform.clear() \
.scale(self.radius) \
.rotate(self.orientation) \
.translate(*self.xy)
@property
def xy(self):
return self._xy
@xy.setter
def xy(self, xy):
self._xy = xy
self._update_transform()
@property
def orientation(self):
return self._orientation
@orientation.setter
def orientation(self, orientation):
self._orientation = orientation
self._update_transform()
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
self._radius = radius
self._update_transform()
@property
def numvertices(self):
return self._numVertices
@numvertices.setter
def numvertices(self, numVertices):
self._numVertices = numVertices
def get_path(self):
return self._path
def get_patch_transform(self):
self._update_transform()
return self._poly_transform
class PathPatch(Patch):
"""A general polycurve path patch."""
_edge_default = True
def __str__(self):
s = "PathPatch%d((%g, %g) ...)"
return s % (len(self._path.vertices), *tuple(self._path.vertices[0]))
@docstring.dedent_interpd
def __init__(self, path, **kwargs):
"""
*path* is a `~.path.Path` object.
Valid keyword arguments are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._path = path
def get_path(self):
return self._path
def set_path(self, path):
self._path = path
class Polygon(Patch):
"""A general polygon patch."""
def __str__(self):
s = "Polygon%d((%g, %g) ...)"
return s % (len(self._path.vertices), *tuple(self._path.vertices[0]))
@docstring.dedent_interpd
def __init__(self, xy, closed=True, **kwargs):
"""
*xy* is a numpy array with shape Nx2.
If *closed* is *True*, the polygon will be closed so the
starting and ending points are the same.
Valid keyword arguments are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._closed = closed
self.set_xy(xy)
def get_path(self):
"""Get the `.Path` of the polygon."""
return self._path
def get_closed(self):
"""Return whether the polygon is closed."""
return self._closed
def set_closed(self, closed):
"""
Set whether the polygon is closed.
Parameters
----------
closed : bool
True if the polygon is closed
"""
if self._closed == bool(closed):
return
self._closed = bool(closed)
self.set_xy(self.get_xy())
self.stale = True
def get_xy(self):
"""
Get the vertices of the path.
Returns
-------
(N, 2) numpy array
The coordinates of the vertices.
"""
return self._path.vertices
def set_xy(self, xy):
"""
Set the vertices of the polygon.
Parameters
----------
xy : (N, 2) array-like
The coordinates of the vertices.
Notes
-----
Unlike `~.path.Path`, we do not ignore the last input vertex. If the
polygon is meant to be closed, and the last point of the polygon is not
equal to the first, we assume that the user has not explicitly passed a
``CLOSEPOLY`` vertex, and add it ourselves.
"""
xy = np.asarray(xy)
nverts, _ = xy.shape
if self._closed:
# if the first and last vertex are the "same", then we assume that
# the user explicitly passed the CLOSEPOLY vertex. Otherwise, we
# have to append one since the last vertex will be "ignored" by
# Path
if nverts == 1 or nverts > 1 and (xy[0] != xy[-1]).any():
xy = np.concatenate([xy, [xy[0]]])
else:
# if we aren't closed, and the last vertex matches the first, then
# we assume we have an unecessary CLOSEPOLY vertex and remove it
if nverts > 2 and (xy[0] == xy[-1]).all():
xy = xy[:-1]
self._path = Path(xy, closed=self._closed)
self.stale = True
xy = property(get_xy, set_xy,
doc='The vertices of the path as (N, 2) numpy array.')
class Wedge(Patch):
"""Wedge shaped patch."""
def __str__(self):
pars = (self.center[0], self.center[1], self.r,
self.theta1, self.theta2, self.width)
fmt = "Wedge(center=(%g, %g), r=%g, theta1=%g, theta2=%g, width=%s)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, center, r, theta1, theta2, width=None, **kwargs):
"""
A wedge centered at *x*, *y* center with radius *r* that
sweeps *theta1* to *theta2* (in degrees). If *width* is given,
then a partial wedge is drawn from inner radius *r* - *width*
to outer radius *r*.
Valid keyword arguments are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self.center = center
self.r, self.width = r, width
self.theta1, self.theta2 = theta1, theta2
self._patch_transform = transforms.IdentityTransform()
self._recompute_path()
def _recompute_path(self):
# Inner and outer rings are connected unless the annulus is complete
if abs((self.theta2 - self.theta1) - 360) <= 1e-12:
theta1, theta2 = 0, 360
connector = Path.MOVETO
else:
theta1, theta2 = self.theta1, self.theta2
connector = Path.LINETO
# Form the outer ring
arc = Path.arc(theta1, theta2)
if self.width is not None:
# Partial annulus needs to draw the outer ring
# followed by a reversed and scaled inner ring
v1 = arc.vertices
v2 = arc.vertices[::-1] * (self.r - self.width) / self.r
v = np.vstack([v1, v2, v1[0, :], (0, 0)])
c = np.hstack([arc.codes, arc.codes, connector, Path.CLOSEPOLY])
c[len(arc.codes)] = connector
else:
# Wedge doesn't need an inner ring
v = np.vstack([arc.vertices, [(0, 0), arc.vertices[0, :], (0, 0)]])
c = np.hstack([arc.codes, [connector, connector, Path.CLOSEPOLY]])
# Shift and scale the wedge to the final location.
v *= self.r
v += np.asarray(self.center)
self._path = Path(v, c)
def set_center(self, center):
self._path = None
self.center = center
self.stale = True
def set_radius(self, radius):
self._path = None
self.r = radius
self.stale = True
def set_theta1(self, theta1):
self._path = None
self.theta1 = theta1
self.stale = True
def set_theta2(self, theta2):
self._path = None
self.theta2 = theta2
self.stale = True
def set_width(self, width):
self._path = None
self.width = width
self.stale = True
def get_path(self):
if self._path is None:
self._recompute_path()
return self._path
# COVERAGE NOTE: Not used internally or from examples
class Arrow(Patch):
"""An arrow patch."""
def __str__(self):
return "Arrow()"
_path = Path([[0.0, 0.1], [0.0, -0.1],
[0.8, -0.1], [0.8, -0.3],
[1.0, 0.0], [0.8, 0.3],
[0.8, 0.1], [0.0, 0.1]],
closed=True)
@docstring.dedent_interpd
def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
"""
Draws an arrow from (*x*, *y*) to (*x* + *dx*, *y* + *dy*).
The width of the arrow is scaled by *width*.
Parameters
----------
x : float
x coordinate of the arrow tail.
y : float
y coordinate of the arrow tail.
dx : float
Arrow length in the x direction.
dy : float
Arrow length in the y direction.
width : float, default: 1
Scale factor for the width of the arrow. With a default value of 1,
the tail width is 0.2 and head width is 0.6.
**kwargs
Keyword arguments control the `Patch` properties:
%(Patch)s
See Also
--------
FancyArrow
Patch that allows independent control of the head and tail
properties.
"""
super().__init__(**kwargs)
self._patch_transform = (
transforms.Affine2D()
.scale(np.hypot(dx, dy), width)
.rotate(np.arctan2(dy, dx))
.translate(x, y)
.frozen())
def get_path(self):
return self._path
def get_patch_transform(self):
return self._patch_transform
class FancyArrow(Polygon):
"""
Like Arrow, but lets you set head width and head height independently.
"""
_edge_default = True
def __str__(self):
return "FancyArrow()"
@docstring.dedent_interpd
def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False,
head_width=None, head_length=None, shape='full', overhang=0,
head_starts_at_zero=False, **kwargs):
"""
Parameters
----------
width: float, default: 0.001
Width of full arrow tail.
length_includes_head: bool, default: False
True if head is to be counted in calculating the length.
head_width: float or None, default: 3*width
Total width of the full arrow head.
head_length: float or None, default: 1.5*head_width
Length of arrow head.
shape: ['full', 'left', 'right'], default: 'full'
Draw the left-half, right-half, or full arrow.
overhang: float, default: 0
Fraction that the arrow is swept back (0 overhang means
triangular shape). Can be negative or greater than one.
head_starts_at_zero: bool, default: False
If True, the head starts being drawn at coordinate 0
instead of ending at coordinate 0.
**kwargs
`.Patch` properties:
%(Patch)s
"""
if head_width is None:
head_width = 3 * width
if head_length is None:
head_length = 1.5 * head_width
distance = np.hypot(dx, dy)
if length_includes_head:
length = distance
else:
length = distance + head_length
if not length:
verts = np.empty([0, 2]) # display nothing if empty
else:
# start by drawing horizontal arrow, point at (0, 0)
hw, hl, hs, lw = head_width, head_length, overhang, width
left_half_arrow = np.array([
[0.0, 0.0], # tip
[-hl, -hw / 2], # leftmost
[-hl * (1 - hs), -lw / 2], # meets stem
[-length, -lw / 2], # bottom left
[-length, 0],
])
# if we're not including the head, shift up by head length
if not length_includes_head:
left_half_arrow += [head_length, 0]
# if the head starts at 0, shift up by another head length
if head_starts_at_zero:
left_half_arrow += [head_length / 2, 0]
# figure out the shape, and complete accordingly
if shape == 'left':
coords = left_half_arrow
else:
right_half_arrow = left_half_arrow * [1, -1]
if shape == 'right':
coords = right_half_arrow
elif shape == 'full':
# The half-arrows contain the midpoint of the stem,
# which we can omit from the full arrow. Including it
# twice caused a problem with xpdf.
coords = np.concatenate([left_half_arrow[:-1],
right_half_arrow[-2::-1]])
else:
raise ValueError("Got unknown shape: %s" % shape)
if distance != 0:
cx = dx / distance
sx = dy / distance
else:
# Account for division by zero
cx, sx = 0, 1
M = [[cx, sx], [-sx, cx]]
verts = np.dot(coords, M) + (x + dx, y + dy)
super().__init__(verts, closed=True, **kwargs)
docstring.interpd.update(
FancyArrow="\n".join(inspect.getdoc(FancyArrow.__init__).splitlines()[2:]))
class CirclePolygon(RegularPolygon):
"""A polygon-approximation of a circle patch."""
def __str__(self):
s = "CirclePolygon((%g, %g), radius=%g, resolution=%d)"
return s % (self._xy[0], self._xy[1], self._radius, self._numVertices)
@docstring.dedent_interpd
def __init__(self, xy, radius=5,
resolution=20, # the number of vertices
** kwargs):
"""
Create a circle at *xy* = (*x*, *y*) with given *radius*.
This circle is approximated by a regular polygon with *resolution*
sides. For a smoother circle drawn with splines, see `Circle`.
Valid keyword arguments are:
%(Patch)s
"""
RegularPolygon.__init__(self, xy,
resolution,
radius,
orientation=0,
**kwargs)
class Ellipse(Patch):
"""A scale-free ellipse."""
def __str__(self):
pars = (self._center[0], self._center[1],
self.width, self.height, self.angle)
fmt = "Ellipse(xy=(%s, %s), width=%s, height=%s, angle=%s)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0, **kwargs):
"""
Parameters
----------
xy : (float, float)
xy coordinates of ellipse centre.
width : float
Total length (diameter) of horizontal axis.
height : float
Total length (diameter) of vertical axis.
angle : float, default: 0
Rotation in degrees anti-clockwise.
Notes
-----
Valid keyword arguments are:
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._center = xy
self._width, self._height = width, height
self._angle = angle
self._path = Path.unit_circle()
# Note: This cannot be calculated until this is added to an Axes
self._patch_transform = transforms.IdentityTransform()
def _recompute_transform(self):
"""
Notes
-----
This cannot be called until after this has been added to an Axes,
otherwise unit conversion will fail. This makes it very important to
call the accessor method and not directly access the transformation
member variable.
"""
center = (self.convert_xunits(self._center[0]),
self.convert_yunits(self._center[1]))
width = self.convert_xunits(self._width)
height = self.convert_yunits(self._height)
self._patch_transform = transforms.Affine2D() \
.scale(width * 0.5, height * 0.5) \
.rotate_deg(self.angle) \
.translate(*center)
def get_path(self):
"""Return the path of the ellipse."""
return self._path
def get_patch_transform(self):
self._recompute_transform()
return self._patch_transform
def set_center(self, xy):
"""
Set the center of the ellipse.
Parameters
----------
xy : (float, float)
"""
self._center = xy
self.stale = True
def get_center(self):
"""Return the center of the ellipse."""
return self._center
center = property(get_center, set_center)
def set_width(self, width):
"""
Set the width of the ellipse.
Parameters
----------
width : float
"""
self._width = width
self.stale = True
def get_width(self):
"""
Return the width of the ellipse.
"""
return self._width
width = property(get_width, set_width)
def set_height(self, height):
"""
Set the height of the ellipse.
Parameters
----------
height : float
"""
self._height = height
self.stale = True
def get_height(self):
"""Return the height of the ellipse."""
return self._height
height = property(get_height, set_height)
def set_angle(self, angle):
"""
Set the angle of the ellipse.
Parameters
----------
angle : float
"""
self._angle = angle
self.stale = True
def get_angle(self):
"""Return the angle of the ellipse."""
return self._angle
angle = property(get_angle, set_angle)
class Circle(Ellipse):
"""A circle patch."""
def __str__(self):
pars = self.center[0], self.center[1], self.radius
fmt = "Circle(xy=(%g, %g), radius=%g)"
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, radius=5, **kwargs):
"""
Create a true circle at center *xy* = (*x*, *y*) with given *radius*.
Unlike `CirclePolygon` which is a polygonal approximation, this uses
Bezier splines and is much closer to a scale-free circle.
Valid keyword arguments are:
%(Patch)s
"""
Ellipse.__init__(self, xy, radius * 2, radius * 2, **kwargs)
self.radius = radius
def set_radius(self, radius):
"""
Set the radius of the circle.
Parameters
----------
radius : float
"""
self.width = self.height = 2 * radius
self.stale = True
def get_radius(self):
"""Return the radius of the circle."""
return self.width / 2.
radius = property(get_radius, set_radius)
class Arc(Ellipse):
"""
An elliptical arc, i.e. a segment of an ellipse.
Due to internal optimizations, there are certain restrictions on using Arc:
- The arc cannot be filled.
- The arc must be used in an `~.axes.Axes` instance. It can not be added
directly to a `.Figure` because it is optimized to only render the
segments that are inside the axes bounding box with high resolution.
"""
def __str__(self):
pars = (self.center[0], self.center[1], self.width,
self.height, self.angle, self.theta1, self.theta2)
fmt = ("Arc(xy=(%g, %g), width=%g, "
"height=%g, angle=%g, theta1=%g, theta2=%g)")
return fmt % pars
@docstring.dedent_interpd
def __init__(self, xy, width, height, angle=0.0,
theta1=0.0, theta2=360.0, **kwargs):
"""
Parameters
----------
xy : (float, float)
The center of the ellipse.
width : float
The length of the horizontal axis.
height : float
The length of the vertical axis.
angle : float
Rotation of the ellipse in degrees (counterclockwise).
theta1, theta2 : float, default: 0, 360
Starting and ending angles of the arc in degrees. These values
are relative to *angle*, e.g. if *angle* = 45 and *theta1* = 90
the absolute starting angle is 135.
Default *theta1* = 0, *theta2* = 360, i.e. a complete ellipse.
The arc is drawn in the counterclockwise direction.
Angles greater than or equal to 360, or smaller than 0, are
represented by an equivalent angle in the range [0, 360), by
taking the input value mod 360.
Other Parameters
----------------
**kwargs : `.Patch` properties
Most `.Patch` properties are supported as keyword arguments,
with the exception of *fill* and *facecolor* because filling is
not supported.
%(Patch)s
"""
fill = kwargs.setdefault('fill', False)
if fill:
raise ValueError("Arc objects can not be filled")
Ellipse.__init__(self, xy, width, height, angle, **kwargs)
self.theta1 = theta1
self.theta2 = theta2
@artist.allow_rasterization
def draw(self, renderer):
"""
Draw the arc to the given *renderer*.
Notes
-----
Ellipses are normally drawn using an approximation that uses
eight cubic Bezier splines. The error of this approximation
is 1.89818e-6, according to this unverified source:
Lancaster, Don. *Approximating a Circle or an Ellipse Using
Four Bezier Cubic Splines.*
https://www.tinaja.com/glib/ellipse4.pdf
There is a use case where very large ellipses must be drawn
with very high accuracy, and it is too expensive to render the
entire ellipse with enough segments (either splines or line
segments). Therefore, in the case where either radius of the
ellipse is large enough that the error of the spline
approximation will be visible (greater than one pixel offset
from the ideal), a different technique is used.
In that case, only the visible parts of the ellipse are drawn,
with each visible arc using a fixed number of spline segments
(8). The algorithm proceeds as follows:
1. The points where the ellipse intersects the axes bounding
box are located. (This is done be performing an inverse
transformation on the axes bbox such that it is relative
to the unit circle -- this makes the intersection
calculation much easier than doing rotated ellipse
intersection directly).
This uses the "line intersecting a circle" algorithm from:
Vince, John. *Geometry for Computer Graphics: Formulae,
Examples & Proofs.* London: Springer-Verlag, 2005.
2. The angles of each of the intersection points are calculated.
3. Proceeding counterclockwise starting in the positive
x-direction, each of the visible arc-segments between the
pairs of vertices are drawn using the Bezier arc
approximation technique implemented in `.Path.arc`.
"""
if not hasattr(self, 'axes'):
raise RuntimeError('Arcs can only be used in Axes instances')
if not self.get_visible():
return
self._recompute_transform()
width = self.convert_xunits(self.width)
height = self.convert_yunits(self.height)
# If the width and height of ellipse are not equal, take into account
# stretching when calculating angles to draw between
def theta_stretch(theta, scale):
theta = np.deg2rad(theta)
x = np.cos(theta)
y = np.sin(theta)
stheta = np.rad2deg(np.arctan2(scale * y, x))
# arctan2 has the range [-pi, pi], we expect [0, 2*pi]
return (stheta + 360) % 360
theta1 = self.theta1
theta2 = self.theta2
if (
# if we need to stretch the angles because we are distorted
width != height
# and we are not doing a full circle.
#
# 0 and 360 do not exactly round-trip through the angle
# stretching (due to both float precision limitations and
# the difference between the range of arctan2 [-pi, pi] and
# this method [0, 360]) so avoid doing it if we don't have to.
and not (theta1 != theta2 and theta1 % 360 == theta2 % 360)
):
theta1 = theta_stretch(self.theta1, width / height)
theta2 = theta_stretch(self.theta2, width / height)
# Get width and height in pixels we need to use
# `self.get_data_transform` rather than `self.get_transform`
# because we want the transform from dataspace to the
# screen space to estimate how big the arc will be in physical
# units when rendered (the transform that we get via
# `self.get_transform()` goes from an idealized unit-radius
# space to screen space).
data_to_screen_trans = self.get_data_transform()
pwidth, pheight = (data_to_screen_trans.transform((width, height)) -
data_to_screen_trans.transform((0, 0)))
inv_error = (1.0 / 1.89818e-6) * 0.5
if pwidth < inv_error and pheight < inv_error:
self._path = Path.arc(theta1, theta2)
return Patch.draw(self, renderer)
def line_circle_intersect(x0, y0, x1, y1):
dx = x1 - x0
dy = y1 - y0
dr2 = dx * dx + dy * dy
D = x0 * y1 - x1 * y0
D2 = D * D
discrim = dr2 - D2
if discrim >= 0.0:
sign_dy = np.copysign(1, dy) # +/-1, never 0.
sqrt_discrim = np.sqrt(discrim)
return np.array(
[[(D * dy + sign_dy * dx * sqrt_discrim) / dr2,
(-D * dx + abs(dy) * sqrt_discrim) / dr2],
[(D * dy - sign_dy * dx * sqrt_discrim) / dr2,
(-D * dx - abs(dy) * sqrt_discrim) / dr2]])
else:
return np.empty((0, 2))
def segment_circle_intersect(x0, y0, x1, y1):
epsilon = 1e-9
if x1 < x0:
x0e, x1e = x1, x0
else:
x0e, x1e = x0, x1
if y1 < y0:
y0e, y1e = y1, y0
else:
y0e, y1e = y0, y1
xys = line_circle_intersect(x0, y0, x1, y1)
xs, ys = xys.T
return xys[
(x0e - epsilon < xs) & (xs < x1e + epsilon)
& (y0e - epsilon < ys) & (ys < y1e + epsilon)
]
# Transforms the axes box_path so that it is relative to the unit
# circle in the same way that it is relative to the desired ellipse.
box_path_transform = (transforms.BboxTransformTo(self.axes.bbox)
+ self.get_transform().inverted())
box_path = Path.unit_rectangle().transformed(box_path_transform)
thetas = set()
# For each of the point pairs, there is a line segment
for p0, p1 in zip(box_path.vertices[:-1], box_path.vertices[1:]):
xy = segment_circle_intersect(*p0, *p1)
x, y = xy.T
# arctan2 return [-pi, pi), the rest of our angles are in
# [0, 360], adjust as needed.
theta = (np.rad2deg(np.arctan2(y, x)) + 360) % 360
thetas.update(theta[(theta1 < theta) & (theta < theta2)])
thetas = sorted(thetas) + [theta2]
last_theta = theta1
theta1_rad = np.deg2rad(theta1)
inside = box_path.contains_point(
(np.cos(theta1_rad), np.sin(theta1_rad))
)
# save original path
path_original = self._path
for theta in thetas:
if inside:
self._path = Path.arc(last_theta, theta, 8)
Patch.draw(self, renderer)
inside = False
else:
inside = True
last_theta = theta
# restore original path
self._path = path_original
def bbox_artist(artist, renderer, props=None, fill=True):
"""
A debug function to draw a rectangle around the bounding
box returned by an artist's `.Artist.get_window_extent`
to test whether the artist is returning the correct bbox.
*props* is a dict of rectangle props with the additional property
'pad' that sets the padding around the bbox in points.
"""
if props is None:
props = {}
props = props.copy() # don't want to alter the pad externally
pad = props.pop('pad', 4)
pad = renderer.points_to_pixels(pad)
bbox = artist.get_window_extent(renderer)
r = Rectangle(
xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2),
width=bbox.width + pad, height=bbox.height + pad,
fill=fill, transform=transforms.IdentityTransform(), clip_on=False)
r.update(props)
r.draw(renderer)
def draw_bbox(bbox, renderer, color='k', trans=None):
"""
A debug function to draw a rectangle around the bounding
box returned by an artist's `.Artist.get_window_extent`
to test whether the artist is returning the correct bbox.
"""
r = Rectangle(xy=(bbox.x0, bbox.y0), width=bbox.width, height=bbox.height,
edgecolor=color, fill=False, clip_on=False)
if trans is not None:
r.set_transform(trans)
r.draw(renderer)
def _simpleprint_styles(_styles):
"""
A helper function for the _Style class. Given the dictionary of
{stylename: styleclass}, return a string rep of the list of keys.
Used to update the documentation.
"""
return "[{}]".format("|".join(map(" '{}' ".format, sorted(_styles))))
class _Style:
"""
A base class for the Styles. It is meant to be a container class,
where actual styles are declared as subclass of it, and it
provides some helper functions.
"""
def __new__(cls, stylename, **kw):
"""Return the instance of the subclass with the given style name."""
# The "class" should have the _style_list attribute, which is a mapping
# of style names to style classes.
_list = stylename.replace(" ", "").split(",")
_name = _list[0].lower()
try:
_cls = cls._style_list[_name]
except KeyError as err:
raise ValueError("Unknown style : %s" % stylename) from err
try:
_args_pair = [cs.split("=") for cs in _list[1:]]
_args = {k: float(v) for k, v in _args_pair}
except ValueError as err:
raise ValueError("Incorrect style argument : %s" %
stylename) from err
_args.update(kw)
return _cls(**_args)
@classmethod
def get_styles(cls):
"""Return a dictionary of available styles."""
return cls._style_list
@classmethod
def pprint_styles(cls):
"""Return the available styles as pretty-printed string."""
table = [('Class', 'Name', 'Attrs'),
*[(cls.__name__,
# Add backquotes, as - and | have special meaning in reST.
f'``{name}``',
# [1:-1] drops the surrounding parentheses.
str(inspect.signature(cls))[1:-1] or 'None')
for name, cls in sorted(cls._style_list.items())]]
# Convert to rst table.
col_len = [max(len(cell) for cell in column) for column in zip(*table)]
table_formatstr = ' '.join('=' * cl for cl in col_len)
rst_table = '\n'.join([
'',
table_formatstr,
' '.join(cell.ljust(cl) for cell, cl in zip(table[0], col_len)),
table_formatstr,
*[' '.join(cell.ljust(cl) for cell, cl in zip(row, col_len))
for row in table[1:]],
table_formatstr,
'',
])
return textwrap.indent(rst_table, prefix=' ' * 2)
@classmethod
def register(cls, name, style):
"""Register a new style."""
if not issubclass(style, cls._Base):
raise ValueError("%s must be a subclass of %s" % (style,
cls._Base))
cls._style_list[name] = style
def _register_style(style_list, cls=None, *, name=None):
"""Class decorator that stashes a class in a (style) dictionary."""
if cls is None:
return functools.partial(_register_style, style_list, name=name)
style_list[name or cls.__name__.lower()] = cls
return cls
class BoxStyle(_Style):
"""
`BoxStyle` is a container class which defines several
boxstyle classes, which are used for `FancyBboxPatch`.
A style object can be created as::
BoxStyle.Round(pad=0.2)
or::
BoxStyle("Round", pad=0.2)
or::
BoxStyle("Round, pad=0.2")
The following boxstyle classes are defined.
%(AvailableBoxstyles)s
An instance of any boxstyle class is an callable object,
whose call signature is::
__call__(self, x0, y0, width, height, mutation_size, aspect_ratio=1.)
and returns a `.Path` instance. *x0*, *y0*, *width* and
*height* specify the location and size of the box to be
drawn. *mutation_scale* determines the overall size of the
mutation (by which I mean the transformation of the rectangle to
the fancy box). *mutation_aspect* determines the aspect-ratio of
the mutation.
"""
_style_list = {}
class _Base:
"""
Abstract base class for styling of `.FancyBboxPatch`.
This class is not an artist itself. The `__call__` method returns the
`~matplotlib.path.Path` for outlining the fancy box. The actual drawing
is handled in `.FancyBboxPatch`.
Subclasses may only use parameters with default values in their
``__init__`` method because they must be able to be initialized
without arguments.
Subclasses must implement the `transmute` method. It receives the
enclosing rectangle *x0, y0, width, height* as well as the
*mutation_size*, which scales the outline properties such as padding.
It returns the outline of the fancy box as `.path.Path`.
"""
def transmute(self, x0, y0, width, height, mutation_size):
"""Return the `~.path.Path` outlining the given rectangle."""
raise NotImplementedError('Derived must override')
def __call__(self, x0, y0, width, height, mutation_size,
aspect_ratio=1.):
"""
Given the location and size of the box, return the path of
the box around it.
Parameters
----------
x0, y0, width, height : float
Location and size of the box.
mutation_size : float
A reference scale for the mutation.
aspect_ratio : float, default: 1
Aspect-ratio for the mutation.
Returns
-------
`~matplotlib.path.Path`
"""
# The __call__ method is a thin wrapper around the transmute method
# and takes care of the aspect.
if aspect_ratio is not None:
# Squeeze the given height by the aspect_ratio
y0, height = y0 / aspect_ratio, height / aspect_ratio
# call transmute method with squeezed height.
path = self.transmute(x0, y0, width, height, mutation_size)
vertices, codes = path.vertices, path.codes
# Restore the height
vertices[:, 1] = vertices[:, 1] * aspect_ratio
return Path(vertices, codes)
else:
return self.transmute(x0, y0, width, height, mutation_size)
@_register_style(_style_list)
class Square(_Base):
"""
A square box.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
def __init__(self, pad=0.3):
self.pad = pad
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
pad = mutation_size * self.pad
# width and height with padding added.
width, height = width + 2 * pad, height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
x1, y1 = x0 + width, y0 + height
return Path([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)],
closed=True)
@_register_style(_style_list)
class Circle(_Base):
"""
A circular box.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
def __init__(self, pad=0.3):
self.pad = pad
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
pad = mutation_size * self.pad
width, height = width + 2 * pad, height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
return Path.circle((x0 + width / 2, y0 + height / 2),
max(width, height) / 2)
@_register_style(_style_list)
class LArrow(_Base):
"""
A box in the shape of a left-pointing arrow.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
def __init__(self, pad=0.3):
self.pad = pad
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# width and height with padding added.
width, height = width + 2 * pad, height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad,
x1, y1 = x0 + width, y0 + height
dx = (y1 - y0) / 2
dxx = dx / 2
x0 = x0 + pad / 1.4 # adjust by ~sqrt(2)
return Path([(x0 + dxx, y0), (x1, y0), (x1, y1), (x0 + dxx, y1),
(x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
(x0 + dxx, y0 - dxx), # arrow
(x0 + dxx, y0), (x0 + dxx, y0)],
closed=True)
@_register_style(_style_list)
class RArrow(LArrow):
"""
A box in the shape of a right-pointing arrow.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
def __init__(self, pad=0.3):
super().__init__(pad)
def transmute(self, x0, y0, width, height, mutation_size):
p = BoxStyle.LArrow.transmute(self, x0, y0,
width, height, mutation_size)
p.vertices[:, 0] = 2 * x0 + width - p.vertices[:, 0]
return p
@_register_style(_style_list)
class DArrow(_Base):
"""
A box in the shape of a two-way arrow.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
"""
# This source is copied from LArrow,
# modified to add a right arrow to the bbox.
def __init__(self, pad=0.3):
self.pad = pad
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# width and height with padding added.
# The width is padded by the arrows, so we don't need to pad it.
height = height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
x1, y1 = x0 + width, y0 + height
dx = (y1 - y0) / 2
dxx = dx / 2
x0 = x0 + pad / 1.4 # adjust by ~sqrt(2)
return Path([(x0 + dxx, y0), (x1, y0), # bot-segment
(x1, y0 - dxx), (x1 + dx + dxx, y0 + dx),
(x1, y1 + dxx), # right-arrow
(x1, y1), (x0 + dxx, y1), # top-segment
(x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx),
(x0 + dxx, y0 - dxx), # left-arrow
(x0 + dxx, y0), (x0 + dxx, y0)], # close-poly
closed=True)
@_register_style(_style_list)
class Round(_Base):
"""
A box with round corners.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
rounding_size : float, default: *pad*
Radius of the corners.
"""
def __init__(self, pad=0.3, rounding_size=None):
self.pad = pad
self.rounding_size = rounding_size
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# size of the rounding corner
if self.rounding_size:
dr = mutation_size * self.rounding_size
else:
dr = pad
width, height = width + 2 * pad, height + 2 * pad
x0, y0 = x0 - pad, y0 - pad,
x1, y1 = x0 + width, y0 + height
# Round corners are implemented as quadratic Bezier, e.g.,
# [(x0, y0-dr), (x0, y0), (x0+dr, y0)] for lower left corner.
cp = [(x0 + dr, y0),
(x1 - dr, y0),
(x1, y0), (x1, y0 + dr),
(x1, y1 - dr),
(x1, y1), (x1 - dr, y1),
(x0 + dr, y1),
(x0, y1), (x0, y1 - dr),
(x0, y0 + dr),
(x0, y0), (x0 + dr, y0),
(x0 + dr, y0)]
com = [Path.MOVETO,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.LINETO,
Path.CURVE3, Path.CURVE3,
Path.CLOSEPOLY]
path = Path(cp, com)
return path
@_register_style(_style_list)
class Round4(_Base):
"""
A box with rounded edges.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
rounding_size : float, default: *pad*/2
Rounding of edges.
"""
def __init__(self, pad=0.3, rounding_size=None):
self.pad = pad
self.rounding_size = rounding_size
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# Rounding size; defaults to half of the padding.
if self.rounding_size:
dr = mutation_size * self.rounding_size
else:
dr = pad / 2.
width = width + 2 * pad - 2 * dr
height = height + 2 * pad - 2 * dr
x0, y0 = x0 - pad + dr, y0 - pad + dr,
x1, y1 = x0 + width, y0 + height
cp = [(x0, y0),
(x0 + dr, y0 - dr), (x1 - dr, y0 - dr), (x1, y0),
(x1 + dr, y0 + dr), (x1 + dr, y1 - dr), (x1, y1),
(x1 - dr, y1 + dr), (x0 + dr, y1 + dr), (x0, y1),
(x0 - dr, y1 - dr), (x0 - dr, y0 + dr), (x0, y0),
(x0, y0)]
com = [Path.MOVETO,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CURVE4, Path.CURVE4, Path.CURVE4,
Path.CLOSEPOLY]
path = Path(cp, com)
return path
@_register_style(_style_list)
class Sawtooth(_Base):
"""
A box with a sawtooth outline.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
tooth_size : float, default: *pad*/2
Size of the sawtooth.
"""
def __init__(self, pad=0.3, tooth_size=None):
self.pad = pad
self.tooth_size = tooth_size
super().__init__()
def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size):
# padding
pad = mutation_size * self.pad
# size of sawtooth
if self.tooth_size is None:
tooth_size = self.pad * .5 * mutation_size
else:
tooth_size = self.tooth_size * mutation_size
tooth_size2 = tooth_size / 2
width = width + 2 * pad - tooth_size
height = height + 2 * pad - tooth_size
# the sizes of the vertical and horizontal sawtooth are
# separately adjusted to fit the given box size.
dsx_n = int(round((width - tooth_size) / (tooth_size * 2))) * 2
dsx = (width - tooth_size) / dsx_n
dsy_n = int(round((height - tooth_size) / (tooth_size * 2))) * 2
dsy = (height - tooth_size) / dsy_n
x0, y0 = x0 - pad + tooth_size2, y0 - pad + tooth_size2
x1, y1 = x0 + width, y0 + height
bottom_saw_x = [
x0,
*(x0 + tooth_size2 + dsx * .5 * np.arange(dsx_n * 2)),
x1 - tooth_size2,
]
bottom_saw_y = [
y0,
*([y0 - tooth_size2, y0, y0 + tooth_size2, y0] * dsx_n),
y0 - tooth_size2,
]
right_saw_x = [
x1,
*([x1 + tooth_size2, x1, x1 - tooth_size2, x1] * dsx_n),
x1 + tooth_size2,
]
right_saw_y = [
y0,
*(y0 + tooth_size2 + dsy * .5 * np.arange(dsy_n * 2)),
y1 - tooth_size2,
]
top_saw_x = [
x1,
*(x1 - tooth_size2 - dsx * .5 * np.arange(dsx_n * 2)),
x0 + tooth_size2,
]
top_saw_y = [
y1,
*([y1 + tooth_size2, y1, y1 - tooth_size2, y1] * dsx_n),
y1 + tooth_size2,
]
left_saw_x = [
x0,
*([x0 - tooth_size2, x0, x0 + tooth_size2, x0] * dsy_n),
x0 - tooth_size2,
]
left_saw_y = [
y1,
*(y1 - tooth_size2 - dsy * .5 * np.arange(dsy_n * 2)),
y0 + tooth_size2,
]
saw_vertices = [*zip(bottom_saw_x, bottom_saw_y),
*zip(right_saw_x, right_saw_y),
*zip(top_saw_x, top_saw_y),
*zip(left_saw_x, left_saw_y),
(bottom_saw_x[0], bottom_saw_y[0])]
return saw_vertices
def transmute(self, x0, y0, width, height, mutation_size):
saw_vertices = self._get_sawtooth_vertices(x0, y0, width,
height, mutation_size)
path = Path(saw_vertices, closed=True)
return path
@_register_style(_style_list)
class Roundtooth(Sawtooth):
"""
A box with a rounded sawtooth outline.
Parameters
----------
pad : float, default: 0.3
The amount of padding around the original box.
tooth_size : float, default: *pad*/2
Size of the sawtooth.
"""
def __init__(self, pad=0.3, tooth_size=None):
super().__init__(pad, tooth_size)
def transmute(self, x0, y0, width, height, mutation_size):
saw_vertices = self._get_sawtooth_vertices(x0, y0,
width, height,
mutation_size)
# Add a trailing vertex to allow us to close the polygon correctly
saw_vertices = np.concatenate([saw_vertices, [saw_vertices[0]]])
codes = ([Path.MOVETO] +
[Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1)//2) +
[Path.CLOSEPOLY])
return Path(saw_vertices, codes)
class ConnectionStyle(_Style):
"""
`ConnectionStyle` is a container class which defines
several connectionstyle classes, which is used to create a path
between two points. These are mainly used with `FancyArrowPatch`.
A connectionstyle object can be either created as::
ConnectionStyle.Arc3(rad=0.2)
or::
ConnectionStyle("Arc3", rad=0.2)
or::
ConnectionStyle("Arc3, rad=0.2")
The following classes are defined
%(AvailableConnectorstyles)s
An instance of any connection style class is an callable object,
whose call signature is::
__call__(self, posA, posB,
patchA=None, patchB=None,
shrinkA=2., shrinkB=2.)
and it returns a `.Path` instance. *posA* and *posB* are
tuples of (x, y) coordinates of the two points to be
connected. *patchA* (or *patchB*) is given, the returned path is
clipped so that it start (or end) from the boundary of the
patch. The path is further shrunk by *shrinkA* (or *shrinkB*)
which is given in points.
"""
_style_list = {}
class _Base:
"""
A base class for connectionstyle classes. The subclass needs
to implement a *connect* method whose call signature is::
connect(posA, posB)
where posA and posB are tuples of x, y coordinates to be
connected. The method needs to return a path connecting two
points. This base class defines a __call__ method, and a few
helper methods.
"""
class SimpleEvent:
def __init__(self, xy):
self.x, self.y = xy
def _clip(self, path, patchA, patchB):
"""
Clip the path to the boundary of the patchA and patchB.
The starting point of the path needed to be inside of the
patchA and the end point inside the patch B. The *contains*
methods of each patch object is utilized to test if the point
is inside the path.
"""
if patchA:
def insideA(xy_display):
xy_event = ConnectionStyle._Base.SimpleEvent(xy_display)
return patchA.contains(xy_event)[0]
try:
left, right = split_path_inout(path, insideA)
except ValueError:
right = path
path = right
if patchB:
def insideB(xy_display):
xy_event = ConnectionStyle._Base.SimpleEvent(xy_display)
return patchB.contains(xy_event)[0]
try:
left, right = split_path_inout(path, insideB)
except ValueError:
left = path
path = left
return path
def _shrink(self, path, shrinkA, shrinkB):
"""
Shrink the path by fixed size (in points) with shrinkA and shrinkB.
"""
if shrinkA:
insideA = inside_circle(*path.vertices[0], shrinkA)
try:
left, path = split_path_inout(path, insideA)
except ValueError:
pass
if shrinkB:
insideB = inside_circle(*path.vertices[-1], shrinkB)
try:
path, right = split_path_inout(path, insideB)
except ValueError:
pass
return path
def __call__(self, posA, posB,
shrinkA=2., shrinkB=2., patchA=None, patchB=None):
"""
Call the *connect* method to create a path between *posA* and
*posB*; then clip and shrink the path.
"""
path = self.connect(posA, posB)
clipped_path = self._clip(path, patchA, patchB)
shrunk_path = self._shrink(clipped_path, shrinkA, shrinkB)
return shrunk_path
@_register_style(_style_list)
class Arc3(_Base):
"""
Creates a simple quadratic Bezier curve between two
points. The curve is created so that the middle control point
(C1) is located at the same distance from the start (C0) and
end points(C2) and the distance of the C1 to the line
connecting C0-C2 is *rad* times the distance of C0-C2.
"""
def __init__(self, rad=0.):
"""
*rad*
curvature of the curve.
"""
self.rad = rad
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2.
dx, dy = x2 - x1, y2 - y1
f = self.rad
cx, cy = x12 + f * dy, y12 - f * dx
vertices = [(x1, y1),
(cx, cy),
(x2, y2)]
codes = [Path.MOVETO,
Path.CURVE3,
Path.CURVE3]
return Path(vertices, codes)
@_register_style(_style_list)
class Angle3(_Base):
"""
Creates a simple quadratic Bezier curve between two
points. The middle control points is placed at the
intersecting point of two lines which cross the start and
end point, and have a slope of angleA and angleB, respectively.
"""
def __init__(self, angleA=90, angleB=0):
"""
*angleA*
starting angle of the path
*angleB*
ending angle of the path
"""
self.angleA = angleA
self.angleB = angleB
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
cosA = math.cos(math.radians(self.angleA))
sinA = math.sin(math.radians(self.angleA))
cosB = math.cos(math.radians(self.angleB))
sinB = math.sin(math.radians(self.angleB))
cx, cy = get_intersection(x1, y1, cosA, sinA,
x2, y2, cosB, sinB)
vertices = [(x1, y1), (cx, cy), (x2, y2)]
codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
return Path(vertices, codes)
@_register_style(_style_list)
class Angle(_Base):
"""
Creates a piecewise continuous quadratic Bezier path between
two points. The path has a one passing-through point placed at
the intersecting point of two lines which cross the start
and end point, and have a slope of angleA and angleB, respectively.
The connecting edges are rounded with *rad*.
"""
def __init__(self, angleA=90, angleB=0, rad=0.):
"""
*angleA*
starting angle of the path
*angleB*
ending angle of the path
*rad*
rounding radius of the edge
"""
self.angleA = angleA
self.angleB = angleB
self.rad = rad
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
cosA = math.cos(math.radians(self.angleA))
sinA = math.sin(math.radians(self.angleA))
cosB = math.cos(math.radians(self.angleB))
sinB = math.sin(math.radians(self.angleB))
cx, cy = get_intersection(x1, y1, cosA, sinA,
x2, y2, cosB, sinB)
vertices = [(x1, y1)]
codes = [Path.MOVETO]
if self.rad == 0.:
vertices.append((cx, cy))
codes.append(Path.LINETO)
else:
dx1, dy1 = x1 - cx, y1 - cy
d1 = np.hypot(dx1, dy1)
f1 = self.rad / d1
dx2, dy2 = x2 - cx, y2 - cy
d2 = np.hypot(dx2, dy2)
f2 = self.rad / d2
vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
(cx, cy),
(cx + dx2 * f2, cy + dy2 * f2)])
codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3])
vertices.append((x2, y2))
codes.append(Path.LINETO)
return Path(vertices, codes)
@_register_style(_style_list)
class Arc(_Base):
"""
Creates a piecewise continuous quadratic Bezier path between
two points. The path can have two passing-through points, a
point placed at the distance of armA and angle of angleA from
point A, another point with respect to point B. The edges are
rounded with *rad*.
"""
def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.):
"""
*angleA* :
starting angle of the path
*angleB* :
ending angle of the path
*armA* :
length of the starting arm
*armB* :
length of the ending arm
*rad* :
rounding radius of the edges
"""
self.angleA = angleA
self.angleB = angleB
self.armA = armA
self.armB = armB
self.rad = rad
def connect(self, posA, posB):
x1, y1 = posA
x2, y2 = posB
vertices = [(x1, y1)]
rounded = []
codes = [Path.MOVETO]
if self.armA:
cosA = math.cos(math.radians(self.angleA))
sinA = math.sin(math.radians(self.angleA))
# x_armA, y_armB
d = self.armA - self.rad
rounded.append((x1 + d * cosA, y1 + d * sinA))
d = self.armA
rounded.append((x1 + d * cosA, y1 + d * sinA))
if self.armB:
cosB = math.cos(math.radians(self.angleB))
sinB = math.sin(math.radians(self.angleB))
x_armB, y_armB = x2 + self.armB * cosB, y2 + self.armB * sinB
if rounded:
xp, yp = rounded[-1]
dx, dy = x_armB - xp, y_armB - yp
dd = (dx * dx + dy * dy) ** .5
rounded.append((xp + self.rad * dx / dd,
yp + self.rad * dy / dd))
vertices.extend(rounded)
codes.extend([Path.LINETO,
Path.CURVE3,
Path.CURVE3])
else:
xp, yp = vertices[-1]
dx, dy = x_armB - xp, y_armB - yp
dd = (dx * dx + dy * dy) ** .5
d = dd - self.rad
rounded = [(xp + d * dx / dd, yp + d * dy / dd),
(x_armB, y_armB)]
if rounded:
xp, yp = rounded[-1]
dx, dy = x2 - xp, y2 - yp
dd = (dx * dx + dy * dy) ** .5
rounded.append((xp + self.rad * dx / dd,
yp + self.rad * dy / dd))
vertices.extend(rounded)
codes.extend([Path.LINETO,
Path.CURVE3,
Path.CURVE3])
vertices.append((x2, y2))
codes.append(Path.LINETO)
return Path(vertices, codes)
@_register_style(_style_list)
class Bar(_Base):
"""
A line with *angle* between A and B with *armA* and
*armB*. One of the arms is extended so that they are connected in
a right angle. The length of armA is determined by (*armA*
+ *fraction* x AB distance). Same for armB.
"""
def __init__(self, armA=0., armB=0., fraction=0.3, angle=None):
"""
Parameters
----------
armA : float
minimum length of armA
armB : float
minimum length of armB
fraction : float
a fraction of the distance between two points that
will be added to armA and armB.
angle : float or None
angle of the connecting line (if None, parallel
to A and B)
"""
self.armA = armA
self.armB = armB
self.fraction = fraction
self.angle = angle
def connect(self, posA, posB):
x1, y1 = posA
x20, y20 = x2, y2 = posB
theta1 = math.atan2(y2 - y1, x2 - x1)
dx, dy = x2 - x1, y2 - y1
dd = (dx * dx + dy * dy) ** .5
ddx, ddy = dx / dd, dy / dd
armA, armB = self.armA, self.armB
if self.angle is not None:
theta0 = np.deg2rad(self.angle)
dtheta = theta1 - theta0
dl = dd * math.sin(dtheta)
dL = dd * math.cos(dtheta)
x2, y2 = x1 + dL * math.cos(theta0), y1 + dL * math.sin(theta0)
armB = armB - dl
# update
dx, dy = x2 - x1, y2 - y1
dd2 = (dx * dx + dy * dy) ** .5
ddx, ddy = dx / dd2, dy / dd2
arm = max(armA, armB)
f = self.fraction * dd + arm
cx1, cy1 = x1 + f * ddy, y1 - f * ddx
cx2, cy2 = x2 + f * ddy, y2 - f * ddx
vertices = [(x1, y1),
(cx1, cy1),
(cx2, cy2),
(x20, y20)]
codes = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO]
return Path(vertices, codes)
def _point_along_a_line(x0, y0, x1, y1, d):
"""
Return the point on the line connecting (*x0*, *y0*) -- (*x1*, *y1*) whose
distance from (*x0*, *y0*) is *d*.
"""
dx, dy = x0 - x1, y0 - y1
ff = d / (dx * dx + dy * dy) ** .5
x2, y2 = x0 - ff * dx, y0 - ff * dy
return x2, y2
class ArrowStyle(_Style):
"""
`ArrowStyle` is a container class which defines several
arrowstyle classes, which is used to create an arrow path along a
given path. These are mainly used with `FancyArrowPatch`.
A arrowstyle object can be either created as::
ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4)
or::
ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4)
or::
ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4")
The following classes are defined
%(AvailableArrowstyles)s
An instance of any arrow style class is a callable object,
whose call signature is::
__call__(self, path, mutation_size, linewidth, aspect_ratio=1.)
and it returns a tuple of a `.Path` instance and a boolean
value. *path* is a `.Path` instance along which the arrow
will be drawn. *mutation_size* and *aspect_ratio* have the same
meaning as in `BoxStyle`. *linewidth* is a line width to be
stroked. This is meant to be used to correct the location of the
head so that it does not overshoot the destination point, but not all
classes support it.
"""
_style_list = {}
class _Base:
"""
Arrow Transmuter Base class
ArrowTransmuterBase and its derivatives are used to make a fancy
arrow around a given path. The __call__ method returns a path
(which will be used to create a PathPatch instance) and a boolean
value indicating the path is open therefore is not fillable. This
class is not an artist and actual drawing of the fancy arrow is
done by the FancyArrowPatch class.
"""
# The derived classes are required to be able to be initialized
# w/o arguments, i.e., all its argument (except self) must have
# the default values.
@staticmethod
def ensure_quadratic_bezier(path):
"""
Some ArrowStyle class only works with a simple quadratic Bezier
curve (created with Arc3Connection or Angle3Connector). This static
method is to check if the provided path is a simple quadratic
Bezier curve and returns its control points if true.
"""
segments = list(path.iter_segments())
if (len(segments) != 2 or segments[0][1] != Path.MOVETO or
segments[1][1] != Path.CURVE3):
raise ValueError(
"'path' is not a valid quadratic Bezier curve")
return [*segments[0][0], *segments[1][0]]
def transmute(self, path, mutation_size, linewidth):
"""
The transmute method is the very core of the ArrowStyle class and
must be overridden in the subclasses. It receives the path object
along which the arrow will be drawn, and the mutation_size, with
which the arrow head etc. will be scaled. The linewidth may be
used to adjust the path so that it does not pass beyond the given
points. It returns a tuple of a Path instance and a boolean. The
boolean value indicate whether the path can be filled or not. The
return value can also be a list of paths and list of booleans of a
same length.
"""
raise NotImplementedError('Derived must override')
def __call__(self, path, mutation_size, linewidth,
aspect_ratio=1.):
"""
The __call__ method is a thin wrapper around the transmute method
and takes care of the aspect ratio.
"""
if aspect_ratio is not None:
# Squeeze the given height by the aspect_ratio
vertices = path.vertices / [1, aspect_ratio]
path_shrunk = Path(vertices, path.codes)
# call transmute method with squeezed height.
path_mutated, fillable = self.transmute(path_shrunk,
linewidth,
mutation_size)
if np.iterable(fillable):
path_list = []
for p in zip(path_mutated):
# Restore the height
path_list.append(
Path(p.vertices * [1, aspect_ratio], p.codes))
return path_list, fillable
else:
return path_mutated, fillable
else:
return self.transmute(path, mutation_size, linewidth)
class _Curve(_Base):
"""
A simple arrow which will work with any path instance. The
returned path is simply concatenation of the original path + at
most two paths representing the arrow head at the begin point and the
at the end point. The arrow heads can be either open or closed.
"""
def __init__(self, beginarrow=None, endarrow=None,
fillbegin=False, fillend=False,
head_length=.2, head_width=.1):
"""
The arrows are drawn if *beginarrow* and/or *endarrow* are
true. *head_length* and *head_width* determines the size
of the arrow relative to the *mutation scale*. The
arrowhead at the begin (or end) is closed if fillbegin (or
fillend) is True.
"""
self.beginarrow, self.endarrow = beginarrow, endarrow
self.head_length, self.head_width = head_length, head_width
self.fillbegin, self.fillend = fillbegin, fillend
super().__init__()
def _get_arrow_wedge(self, x0, y0, x1, y1,
head_dist, cos_t, sin_t, linewidth):
"""
Return the paths for arrow heads. Since arrow lines are
drawn with capstyle=projected, The arrow goes beyond the
desired point. This method also returns the amount of the path
to be shrunken so that it does not overshoot.
"""
# arrow from x0, y0 to x1, y1
dx, dy = x0 - x1, y0 - y1
cp_distance = np.hypot(dx, dy)
# pad_projected : amount of pad to account the
# overshooting of the projection of the wedge
pad_projected = (.5 * linewidth / sin_t)
# Account for division by zero
if cp_distance == 0:
cp_distance = 1
# apply pad for projected edge
ddx = pad_projected * dx / cp_distance
ddy = pad_projected * dy / cp_distance
# offset for arrow wedge
dx = dx / cp_distance * head_dist
dy = dy / cp_distance * head_dist
dx1, dy1 = cos_t * dx + sin_t * dy, -sin_t * dx + cos_t * dy
dx2, dy2 = cos_t * dx - sin_t * dy, sin_t * dx + cos_t * dy
vertices_arrow = [(x1 + ddx + dx1, y1 + ddy + dy1),
(x1 + ddx, y1 + ddy),
(x1 + ddx + dx2, y1 + ddy + dy2)]
codes_arrow = [Path.MOVETO,
Path.LINETO,
Path.LINETO]
return vertices_arrow, codes_arrow, ddx, ddy
def transmute(self, path, mutation_size, linewidth):
head_length = self.head_length * mutation_size
head_width = self.head_width * mutation_size
head_dist = np.hypot(head_length, head_width)
cos_t, sin_t = head_length / head_dist, head_width / head_dist
# begin arrow
x0, y0 = path.vertices[0]
x1, y1 = path.vertices[1]
# If there is no room for an arrow and a line, then skip the arrow
has_begin_arrow = self.beginarrow and (x0, y0) != (x1, y1)
verticesA, codesA, ddxA, ddyA = (
self._get_arrow_wedge(x1, y1, x0, y0,
head_dist, cos_t, sin_t, linewidth)
if has_begin_arrow
else ([], [], 0, 0)
)
# end arrow
x2, y2 = path.vertices[-2]
x3, y3 = path.vertices[-1]
# If there is no room for an arrow and a line, then skip the arrow
has_end_arrow = self.endarrow and (x2, y2) != (x3, y3)
verticesB, codesB, ddxB, ddyB = (
self._get_arrow_wedge(x2, y2, x3, y3,
head_dist, cos_t, sin_t, linewidth)
if has_end_arrow
else ([], [], 0, 0)
)
# This simple code will not work if ddx, ddy is greater than the
# separation between vertices.
_path = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)],
path.vertices[1:-1],
[(x3 + ddxB, y3 + ddyB)]]),
path.codes)]
_fillable = [False]
if has_begin_arrow:
if self.fillbegin:
p = np.concatenate([verticesA, [verticesA[0],
verticesA[0]], ])
c = np.concatenate([codesA, [Path.LINETO, Path.CLOSEPOLY]])
_path.append(Path(p, c))
_fillable.append(True)
else:
_path.append(Path(verticesA, codesA))
_fillable.append(False)
if has_end_arrow:
if self.fillend:
_fillable.append(True)
p = np.concatenate([verticesB, [verticesB[0],
verticesB[0]], ])
c = np.concatenate([codesB, [Path.LINETO, Path.CLOSEPOLY]])
_path.append(Path(p, c))
else:
_fillable.append(False)
_path.append(Path(verticesB, codesB))
return _path, _fillable
@_register_style(_style_list, name="-")
class Curve(_Curve):
"""A simple curve without any arrow head."""
def __init__(self):
super().__init__(beginarrow=False, endarrow=False)
@_register_style(_style_list, name="<-")
class CurveA(_Curve):
"""An arrow with a head at its begin point."""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head.
head_width : float, default: 0.2
Width of the arrow head.
"""
super().__init__(beginarrow=True, endarrow=False,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="->")
class CurveB(_Curve):
"""An arrow with a head at its end point."""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head.
head_width : float, default: 0.2
Width of the arrow head.
"""
super().__init__(beginarrow=False, endarrow=True,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="<->")
class CurveAB(_Curve):
"""An arrow with heads both at the begin and the end point."""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head.
head_width : float, default: 0.2
Width of the arrow head.
"""
super().__init__(beginarrow=True, endarrow=True,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="<|-")
class CurveFilledA(_Curve):
"""An arrow with filled triangle head at the begin."""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head.
head_width : float, default: 0.2
Width of the arrow head.
"""
super().__init__(beginarrow=True, endarrow=False,
fillbegin=True, fillend=False,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="-|>")
class CurveFilledB(_Curve):
"""An arrow with filled triangle head at the end."""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head.
head_width : float, default: 0.2
Width of the arrow head.
"""
super().__init__(beginarrow=False, endarrow=True,
fillbegin=False, fillend=True,
head_length=head_length, head_width=head_width)
@_register_style(_style_list, name="<|-|>")
class CurveFilledAB(_Curve):
"""An arrow with filled triangle heads at both ends."""
def __init__(self, head_length=.4, head_width=.2):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head.
head_width : float, default: 0.2
Width of the arrow head.
"""
super().__init__(beginarrow=True, endarrow=True,
fillbegin=True, fillend=True,
head_length=head_length, head_width=head_width)
class _Bracket(_Base):
def __init__(self, bracketA=None, bracketB=None,
widthA=1., widthB=1.,
lengthA=0.2, lengthB=0.2,
angleA=None, angleB=None,
scaleA=None, scaleB=None):
self.bracketA, self.bracketB = bracketA, bracketB
self.widthA, self.widthB = widthA, widthB
self.lengthA, self.lengthB = lengthA, lengthB
self.angleA, self.angleB = angleA, angleB
self.scaleA, self.scaleB = scaleA, scaleB
def _get_bracket(self, x0, y0,
cos_t, sin_t, width, length):
# arrow from x0, y0 to x1, y1
from matplotlib.bezier import get_normal_points
x1, y1, x2, y2 = get_normal_points(x0, y0, cos_t, sin_t, width)
dx, dy = length * cos_t, length * sin_t
vertices_arrow = [(x1 + dx, y1 + dy),
(x1, y1),
(x2, y2),
(x2 + dx, y2 + dy)]
codes_arrow = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO]
return vertices_arrow, codes_arrow
def transmute(self, path, mutation_size, linewidth):
if self.scaleA is None:
scaleA = mutation_size
else:
scaleA = self.scaleA
if self.scaleB is None:
scaleB = mutation_size
else:
scaleB = self.scaleB
vertices_list, codes_list = [], []
if self.bracketA:
x0, y0 = path.vertices[0]
x1, y1 = path.vertices[1]
cos_t, sin_t = get_cos_sin(x1, y1, x0, y0)
verticesA, codesA = self._get_bracket(x0, y0, cos_t, sin_t,
self.widthA * scaleA,
self.lengthA * scaleA)
vertices_list.append(verticesA)
codes_list.append(codesA)
vertices_list.append(path.vertices)
codes_list.append(path.codes)
if self.bracketB:
x0, y0 = path.vertices[-1]
x1, y1 = path.vertices[-2]
cos_t, sin_t = get_cos_sin(x1, y1, x0, y0)
verticesB, codesB = self._get_bracket(x0, y0, cos_t, sin_t,
self.widthB * scaleB,
self.lengthB * scaleB)
vertices_list.append(verticesB)
codes_list.append(codesB)
vertices = np.concatenate(vertices_list)
codes = np.concatenate(codes_list)
p = Path(vertices, codes)
return p, False
@_register_style(_style_list, name="]-[")
class BracketAB(_Bracket):
"""An arrow with outward square brackets at both ends."""
def __init__(self,
widthA=1., lengthA=0.2, angleA=None,
widthB=1., lengthB=0.2, angleB=None):
"""
Parameters
----------
widthA : float, default: 1.0
Width of the bracket.
lengthA : float, default: 0.2
Length of the bracket.
angleA : float, default: None
Angle between the bracket and the line.
widthB : float, default: 1.0
Width of the bracket.
lengthB : float, default: 0.2
Length of the bracket.
angleB : float, default: None
Angle between the bracket and the line.
"""
super().__init__(True, True,
widthA=widthA, lengthA=lengthA, angleA=angleA,
widthB=widthB, lengthB=lengthB, angleB=angleB)
@_register_style(_style_list, name="]-")
class BracketA(_Bracket):
"""An arrow with an outward square bracket at its start."""
def __init__(self, widthA=1., lengthA=0.2, angleA=None):
"""
Parameters
----------
widthA : float, default: 1.0
Width of the bracket.
lengthA : float, default: 0.2
Length of the bracket.
angleA : float, default: None
Angle between the bracket and the line.
"""
super().__init__(True, None,
widthA=widthA, lengthA=lengthA, angleA=angleA)
@_register_style(_style_list, name="-[")
class BracketB(_Bracket):
"""An arrow with an outward square bracket at its end."""
def __init__(self, widthB=1., lengthB=0.2, angleB=None):
"""
Parameters
----------
widthB : float, default: 1.0
Width of the bracket.
lengthB : float, default: 0.2
Length of the bracket.
angleB : float, default: None
Angle between the bracket and the line.
"""
super().__init__(None, True,
widthB=widthB, lengthB=lengthB, angleB=angleB)
@_register_style(_style_list, name="|-|")
class BarAB(_Bracket):
"""An arrow with vertical bars ``|`` at both ends."""
def __init__(self,
widthA=1., angleA=None,
widthB=1., angleB=None):
"""
Parameters
----------
widthA : float, default: 1.0
Width of the bracket.
angleA : float, default: None
Angle between the bracket and the line.
widthB : float, default: 1.0
Width of the bracket.
angleB : float, default: None
Angle between the bracket and the line.
"""
super().__init__(True, True,
widthA=widthA, lengthA=0, angleA=angleA,
widthB=widthB, lengthB=0, angleB=angleB)
@_register_style(_style_list)
class Simple(_Base):
"""A simple arrow. Only works with a quadratic Bezier curve."""
def __init__(self, head_length=.5, head_width=.5, tail_width=.2):
"""
Parameters
----------
head_length : float, default: 0.5
Length of the arrow head.
head_width : float, default: 0.5
Width of the arrow head.
tail_width : float, default: 0.2
Width of the arrow tail.
"""
self.head_length, self.head_width, self.tail_width = \
head_length, head_width, tail_width
super().__init__()
def transmute(self, path, mutation_size, linewidth):
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
# divide the path into a head and a tail
head_length = self.head_length * mutation_size
in_f = inside_circle(x2, y2, head_length)
arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
try:
arrow_out, arrow_in = \
split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
except NonIntersectingPathException:
# if this happens, make a straight line of the head_length
# long.
x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
arrow_in = [(x0, y0), (x1n, y1n), (x2, y2)]
arrow_out = None
# head
head_width = self.head_width * mutation_size
head_left, head_right = make_wedged_bezier2(arrow_in,
head_width / 2., wm=.5)
# tail
if arrow_out is not None:
tail_width = self.tail_width * mutation_size
tail_left, tail_right = get_parallels(arrow_out,
tail_width / 2.)
patch_path = [(Path.MOVETO, tail_right[0]),
(Path.CURVE3, tail_right[1]),
(Path.CURVE3, tail_right[2]),
(Path.LINETO, head_right[0]),
(Path.CURVE3, head_right[1]),
(Path.CURVE3, head_right[2]),
(Path.CURVE3, head_left[1]),
(Path.CURVE3, head_left[0]),
(Path.LINETO, tail_left[2]),
(Path.CURVE3, tail_left[1]),
(Path.CURVE3, tail_left[0]),
(Path.LINETO, tail_right[0]),
(Path.CLOSEPOLY, tail_right[0]),
]
else:
patch_path = [(Path.MOVETO, head_right[0]),
(Path.CURVE3, head_right[1]),
(Path.CURVE3, head_right[2]),
(Path.CURVE3, head_left[1]),
(Path.CURVE3, head_left[0]),
(Path.CLOSEPOLY, head_left[0]),
]
path = Path([p for c, p in patch_path], [c for c, p in patch_path])
return path, True
@_register_style(_style_list)
class Fancy(_Base):
"""A fancy arrow. Only works with a quadratic Bezier curve."""
def __init__(self, head_length=.4, head_width=.4, tail_width=.4):
"""
Parameters
----------
head_length : float, default: 0.4
Length of the arrow head.
head_width : float, default: 0.4
Width of the arrow head.
tail_width : float, default: 0.4
Width of the arrow tail.
"""
self.head_length, self.head_width, self.tail_width = \
head_length, head_width, tail_width
super().__init__()
def transmute(self, path, mutation_size, linewidth):
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
# divide the path into a head and a tail
head_length = self.head_length * mutation_size
arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
# path for head
in_f = inside_circle(x2, y2, head_length)
try:
path_out, path_in = split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
except NonIntersectingPathException:
# if this happens, make a straight line of the head_length
# long.
x0, y0 = _point_along_a_line(x2, y2, x1, y1, head_length)
x1n, y1n = 0.5 * (x0 + x2), 0.5 * (y0 + y2)
arrow_path = [(x0, y0), (x1n, y1n), (x2, y2)]
path_head = arrow_path
else:
path_head = path_in
# path for head
in_f = inside_circle(x2, y2, head_length * .8)
path_out, path_in = split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
path_tail = path_out
# head
head_width = self.head_width * mutation_size
head_l, head_r = make_wedged_bezier2(path_head,
head_width / 2.,
wm=.6)
# tail
tail_width = self.tail_width * mutation_size
tail_left, tail_right = make_wedged_bezier2(path_tail,
tail_width * .5,
w1=1., wm=0.6, w2=0.3)
# path for head
in_f = inside_circle(x0, y0, tail_width * .3)
path_in, path_out = split_bezier_intersecting_with_closedpath(
arrow_path, in_f, tolerance=0.01)
tail_start = path_in[-1]
head_right, head_left = head_r, head_l
patch_path = [(Path.MOVETO, tail_start),
(Path.LINETO, tail_right[0]),
(Path.CURVE3, tail_right[1]),
(Path.CURVE3, tail_right[2]),
(Path.LINETO, head_right[0]),
(Path.CURVE3, head_right[1]),
(Path.CURVE3, head_right[2]),
(Path.CURVE3, head_left[1]),
(Path.CURVE3, head_left[0]),
(Path.LINETO, tail_left[2]),
(Path.CURVE3, tail_left[1]),
(Path.CURVE3, tail_left[0]),
(Path.LINETO, tail_start),
(Path.CLOSEPOLY, tail_start),
]
path = Path([p for c, p in patch_path], [c for c, p in patch_path])
return path, True
@_register_style(_style_list)
class Wedge(_Base):
"""
Wedge(?) shape. Only works with a quadratic Bezier curve. The
begin point has a width of the tail_width and the end point has a
width of 0. At the middle, the width is shrink_factor*tail_width.
"""
def __init__(self, tail_width=.3, shrink_factor=0.5):
"""
Parameters
----------
tail_width : float, default: 0.3
Width of the tail.
shrink_factor : float, default: 0.5
Fraction of the arrow width at the middle point.
"""
self.tail_width = tail_width
self.shrink_factor = shrink_factor
super().__init__()
def transmute(self, path, mutation_size, linewidth):
x0, y0, x1, y1, x2, y2 = self.ensure_quadratic_bezier(path)
arrow_path = [(x0, y0), (x1, y1), (x2, y2)]
b_plus, b_minus = make_wedged_bezier2(
arrow_path,
self.tail_width * mutation_size / 2.,
wm=self.shrink_factor)
patch_path = [(Path.MOVETO, b_plus[0]),
(Path.CURVE3, b_plus[1]),
(Path.CURVE3, b_plus[2]),
(Path.LINETO, b_minus[2]),
(Path.CURVE3, b_minus[1]),
(Path.CURVE3, b_minus[0]),
(Path.CLOSEPOLY, b_minus[0]),
]
path = Path([p for c, p in patch_path], [c for c, p in patch_path])
return path, True
docstring.interpd.update(
AvailableBoxstyles=BoxStyle.pprint_styles(),
ListBoxstyles=_simpleprint_styles(BoxStyle._style_list),
AvailableArrowstyles=ArrowStyle.pprint_styles(),
AvailableConnectorstyles=ConnectionStyle.pprint_styles(),
)
docstring.dedent_interpd(BoxStyle)
docstring.dedent_interpd(ArrowStyle)
docstring.dedent_interpd(ConnectionStyle)
class FancyBboxPatch(Patch):
"""
A fancy box around a rectangle with lower left at *xy* = (*x*, *y*)
with specified width and height.
`.FancyBboxPatch` is similar to `.Rectangle`, but it draws a fancy box
around the rectangle. The transformation of the rectangle box to the
fancy box is delegated to the style classes defined in `.BoxStyle`.
"""
_edge_default = True
def __str__(self):
s = self.__class__.__name__ + "((%g, %g), width=%g, height=%g)"
return s % (self._x, self._y, self._width, self._height)
@docstring.dedent_interpd
def __init__(self, xy, width, height,
boxstyle="round",
bbox_transmuter=None,
mutation_scale=1.,
mutation_aspect=None,
**kwargs):
"""
Parameters
----------
xy : float, float
The lower left corner of the box.
width : float
The width of the box.
height : float
The height of the box.
boxstyle : str or `matplotlib.patches.BoxStyle`
The style of the fancy box. This can either be a `.BoxStyle`
instance or a string of the style name and optionally comma
seprarated attributes (e.g. "Round, pad=0.2"). This string is
passed to `.BoxStyle` to construct a `.BoxStyle` object. See
there for a full documentation.
The following box styles are available:
%(AvailableBoxstyles)s
mutation_scale : float, default: 1
Scaling factor applied to the attributes of the box style
(e.g. pad or rounding_size).
mutation_aspect : float, optional
The height of the rectangle will be squeezed by this value before
the mutation and the mutated box will be stretched by the inverse
of it. For example, this allows different horizontal and vertical
padding.
Other Parameters
----------------
**kwargs : `.Patch` properties
%(Patch)s
"""
Patch.__init__(self, **kwargs)
self._x = xy[0]
self._y = xy[1]
self._width = width
self._height = height
if boxstyle == "custom":
if bbox_transmuter is None:
raise ValueError("bbox_transmuter argument is needed with "
"custom boxstyle")
self._bbox_transmuter = bbox_transmuter
else:
self.set_boxstyle(boxstyle)
self._mutation_scale = mutation_scale
self._mutation_aspect = mutation_aspect
self.stale = True
@docstring.dedent_interpd
def set_boxstyle(self, boxstyle=None, **kwargs):
"""
Set the box style.
Most box styles can be further configured using attributes.
Attributes from the previous box style are not reused.
Without argument (or with ``boxstyle=None``), the available box styles
are returned as a human-readable string.
Parameters
----------
boxstyle : str
The name of the box style. Optionally, followed by a comma and a
comma-separated list of attributes. The attributes may
alternatively be passed separately as keyword arguments.
The following box styles are available:
%(AvailableBoxstyles)s
.. ACCEPTS: %(ListBoxstyles)s
**kwargs
Additional attributes for the box style. See the table above for
supported parameters.
Examples
--------
::
set_boxstyle("round,pad=0.2")
set_boxstyle("round", pad=0.2)
"""
if boxstyle is None:
return BoxStyle.pprint_styles()
if isinstance(boxstyle, BoxStyle._Base) or callable(boxstyle):
self._bbox_transmuter = boxstyle
else:
self._bbox_transmuter = BoxStyle(boxstyle, **kwargs)
self.stale = True
def set_mutation_scale(self, scale):
"""
Set the mutation scale.
Parameters
----------
scale : float
"""
self._mutation_scale = scale
self.stale = True
def get_mutation_scale(self):
"""Return the mutation scale."""
return self._mutation_scale
def set_mutation_aspect(self, aspect):
"""
Set the aspect ratio of the bbox mutation.
Parameters
----------
aspect : float
"""
self._mutation_aspect = aspect
self.stale = True
def get_mutation_aspect(self):
"""Return the aspect ratio of the bbox mutation."""
return self._mutation_aspect
def get_boxstyle(self):
"""Return the boxstyle object."""
return self._bbox_transmuter
def get_path(self):
"""Return the mutated path of the rectangle."""
_path = self.get_boxstyle()(self._x, self._y,
self._width, self._height,
self.get_mutation_scale(),
self.get_mutation_aspect())
return _path
# Following methods are borrowed from the Rectangle class.
def get_x(self):
"""Return the left coord of the rectangle."""
return self._x
def get_y(self):
"""Return the bottom coord of the rectangle."""
return self._y
def get_width(self):
"""Return the width of the rectangle."""
return self._width
def get_height(self):
"""Return the height of the rectangle."""
return self._height
def set_x(self, x):
"""
Set the left coord of the rectangle.
Parameters
----------
x : float
"""
self._x = x
self.stale = True
def set_y(self, y):
"""
Set the bottom coord of the rectangle.
Parameters
----------
y : float
"""
self._y = y
self.stale = True
def set_width(self, w):
"""
Set the rectangle width.
Parameters
----------
w : float
"""
self._width = w
self.stale = True
def set_height(self, h):
"""
Set the rectangle height.
Parameters
----------
h : float
"""
self._height = h
self.stale = True
def set_bounds(self, *args):
"""
Set the bounds of the rectangle.
Call signatures::
set_bounds(left, bottom, width, height)
set_bounds((left, bottom, width, height))
Parameters
----------
left, bottom : float
The coordinates of the bottom left corner of the rectangle.
width, height : float
The width/height of the rectangle.
"""
if len(args) == 1:
l, b, w, h = args[0]
else:
l, b, w, h = args
self._x = l
self._y = b
self._width = w
self._height = h
self.stale = True
def get_bbox(self):
"""Return the `.Bbox`."""
return transforms.Bbox.from_bounds(self._x, self._y,
self._width, self._height)
class FancyArrowPatch(Patch):
"""
A fancy arrow patch. It draws an arrow using the `ArrowStyle`.
The head and tail positions are fixed at the specified start and end points
of the arrow, but the size and shape (in display coordinates) of the arrow
does not change when the axis is moved or zoomed.
"""
_edge_default = True
def __str__(self):
if self._posA_posB is not None:
(x1, y1), (x2, y2) = self._posA_posB
return f"{type(self).__name__}(({x1:g}, {y1:g})->({x2:g}, {y2:g}))"
else:
return f"{type(self).__name__}({self._path_original})"
@docstring.dedent_interpd
def __init__(self, posA=None, posB=None,
path=None,
arrowstyle="simple",
connectionstyle="arc3",
patchA=None,
patchB=None,
shrinkA=2,
shrinkB=2,
mutation_scale=1,
mutation_aspect=None,
dpi_cor=1,
**kwargs):
"""
There are two ways for defining an arrow:
- If *posA* and *posB* are given, a path connecting two points is
created according to *connectionstyle*. The path will be
clipped with *patchA* and *patchB* and further shrunken by
*shrinkA* and *shrinkB*. An arrow is drawn along this
resulting path using the *arrowstyle* parameter.
- Alternatively if *path* is provided, an arrow is drawn along this
path and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored.
Parameters
----------
posA, posB : (float, float), default: None
(x, y) coordinates of arrow tail and arrow head respectively.
path : `~matplotlib.path.Path`, default: None
If provided, an arrow is drawn along this path and *patchA*,
*patchB*, *shrinkA*, and *shrinkB* are ignored.
arrowstyle : str or `.ArrowStyle`, default: 'simple'
The `.ArrowStyle` with which the fancy arrow is drawn. If a
string, it should be one of the available arrowstyle names, with
optional comma-separated attributes. The optional attributes are
meant to be scaled with the *mutation_scale*. The following arrow
styles are available:
%(AvailableArrowstyles)s
connectionstyle : str or `.ConnectionStyle` or None, optional, \
default: 'arc3'
The `.ConnectionStyle` with which *posA* and *posB* are connected.
If a string, it should be one of the available connectionstyle
names, with optional comma-separated attributes. The following
connection styles are available:
%(AvailableConnectorstyles)s
patchA, patchB : `.Patch`, default: None
Head and tail patches, respectively.
shrinkA, shrinkB : float, default: 2
Shrinking factor of the tail and head of the arrow respectively.
mutation_scale : float, default: 1
Value with which attributes of *arrowstyle* (e.g., *head_length*)
will be scaled.
mutation_aspect : None or float, default: None
The height of the rectangle will be squeezed by this value before
the mutation and the mutated box will be stretched by the inverse
of it.
dpi_cor : float, default: 1
dpi_cor is currently used for linewidth-related things and shrink
factor. Mutation scale is affected by this.
Other Parameters
----------------
**kwargs : `.Patch` properties, optional
Here is a list of available `.Patch` properties:
%(Patch)s
In contrast to other patches, the default ``capstyle`` and
``joinstyle`` for `FancyArrowPatch` are set to ``"round"``.
"""
# Traditionally, the cap- and joinstyle for FancyArrowPatch are round
kwargs.setdefault("joinstyle", "round")
kwargs.setdefault("capstyle", "round")
Patch.__init__(self, **kwargs)
if posA is not None and posB is not None and path is None:
self._posA_posB = [posA, posB]
if connectionstyle is None:
connectionstyle = "arc3"
self.set_connectionstyle(connectionstyle)
elif posA is None and posB is None and path is not None:
self._posA_posB = None
else:
raise ValueError("Either posA and posB, or path need to provided")
self.patchA = patchA
self.patchB = patchB
self.shrinkA = shrinkA
self.shrinkB = shrinkB
self._path_original = path
self.set_arrowstyle(arrowstyle)
self._mutation_scale = mutation_scale
self._mutation_aspect = mutation_aspect
self.set_dpi_cor(dpi_cor)
def set_dpi_cor(self, dpi_cor):
"""
dpi_cor is currently used for linewidth-related things and
shrink factor. Mutation scale is affected by this.
Parameters
----------
dpi_cor : float
"""
self._dpi_cor = dpi_cor
self.stale = True
def get_dpi_cor(self):
"""
dpi_cor is currently used for linewidth-related things and
shrink factor. Mutation scale is affected by this.
Returns
-------
scalar
"""
return self._dpi_cor
def set_positions(self, posA, posB):
"""
Set the begin and end positions of the connecting path.
Parameters
----------
posA, posB : None, tuple
(x, y) coordinates of arrow tail and arrow head respectively. If
`None` use current value.
"""
if posA is not None:
self._posA_posB[0] = posA
if posB is not None:
self._posA_posB[1] = posB
self.stale = True
def set_patchA(self, patchA):
"""
Set the tail patch.
Parameters
----------
patchA : `.patches.Patch`
"""
self.patchA = patchA
self.stale = True
def set_patchB(self, patchB):
"""
Set the head patch.
Parameters
----------
patchB : `.patches.Patch`
"""
self.patchB = patchB
self.stale = True
def set_connectionstyle(self, connectionstyle, **kw):
"""
Set the connection style. Old attributes are forgotten.
Parameters
----------
connectionstyle : str or `.ConnectionStyle` or None, optional
Can be a string with connectionstyle name with
optional comma-separated attributes, e.g.::
set_connectionstyle("arc,angleA=0,armA=30,rad=10")
Alternatively, the attributes can be provided as keywords, e.g.::
set_connectionstyle("arc", angleA=0,armA=30,rad=10)
Without any arguments (or with ``connectionstyle=None``), return
available styles as a list of strings.
"""
if connectionstyle is None:
return ConnectionStyle.pprint_styles()
if (isinstance(connectionstyle, ConnectionStyle._Base) or
callable(connectionstyle)):
self._connector = connectionstyle
else:
self._connector = ConnectionStyle(connectionstyle, **kw)
self.stale = True
def get_connectionstyle(self):
"""Return the `ConnectionStyle` used."""
return self._connector
def set_arrowstyle(self, arrowstyle=None, **kw):
"""
Set the arrow style. Old attributes are forgotten. Without arguments
(or with ``arrowstyle=None``) returns available box styles as a list of
strings.
Parameters
----------
arrowstyle : None or ArrowStyle or str, default: None
Can be a string with arrowstyle name with optional comma-separated
attributes, e.g.::
set_arrowstyle("Fancy,head_length=0.2")
Alternatively attributes can be provided as keywords, e.g.::
set_arrowstyle("fancy", head_length=0.2)
"""
if arrowstyle is None:
return ArrowStyle.pprint_styles()
if isinstance(arrowstyle, ArrowStyle._Base):
self._arrow_transmuter = arrowstyle
else:
self._arrow_transmuter = ArrowStyle(arrowstyle, **kw)
self.stale = True
def get_arrowstyle(self):
"""Return the arrowstyle object."""
return self._arrow_transmuter
def set_mutation_scale(self, scale):
"""
Set the mutation scale.
Parameters
----------
scale : float
"""
self._mutation_scale = scale
self.stale = True
def get_mutation_scale(self):
"""
Return the mutation scale.
Returns
-------
scalar
"""
return self._mutation_scale
def set_mutation_aspect(self, aspect):
"""
Set the aspect ratio of the bbox mutation.
Parameters
----------
aspect : float
"""
self._mutation_aspect = aspect
self.stale = True
def get_mutation_aspect(self):
"""Return the aspect ratio of the bbox mutation."""
return self._mutation_aspect
def get_path(self):
"""
Return the path of the arrow in the data coordinates. Use
get_path_in_displaycoord() method to retrieve the arrow path
in display coordinates.
"""
_path, fillable = self.get_path_in_displaycoord()
if np.iterable(fillable):
_path = Path.make_compound_path(*_path)
return self.get_transform().inverted().transform_path(_path)
def get_path_in_displaycoord(self):
"""Return the mutated path of the arrow in display coordinates."""
dpi_cor = self.get_dpi_cor()
if self._posA_posB is not None:
posA = self._convert_xy_units(self._posA_posB[0])
posB = self._convert_xy_units(self._posA_posB[1])
(posA, posB) = self.get_transform().transform((posA, posB))
_path = self.get_connectionstyle()(posA, posB,
patchA=self.patchA,
patchB=self.patchB,
shrinkA=self.shrinkA * dpi_cor,
shrinkB=self.shrinkB * dpi_cor
)
else:
_path = self.get_transform().transform_path(self._path_original)
_path, fillable = self.get_arrowstyle()(
_path,
self.get_mutation_scale() * dpi_cor,
self.get_linewidth() * dpi_cor,
self.get_mutation_aspect())
# if not fillable:
# self._fill = False
return _path, fillable
def draw(self, renderer):
if not self.get_visible():
return
with self._bind_draw_path_function(renderer) as draw_path:
# FIXME : dpi_cor is for the dpi-dependency of the linewidth. There
# could be room for improvement.
self.set_dpi_cor(renderer.points_to_pixels(1.))
path, fillable = self.get_path_in_displaycoord()
if not np.iterable(fillable):
path = [path]
fillable = [fillable]
affine = transforms.IdentityTransform()
for p, f in zip(path, fillable):
draw_path(
p, affine,
self._facecolor if f and self._facecolor[3] else None)
class ConnectionPatch(FancyArrowPatch):
"""A patch that connects two points (possibly in different axes)."""
def __str__(self):
return "ConnectionPatch((%g, %g), (%g, %g))" % \
(self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1])
@docstring.dedent_interpd
def __init__(self, xyA, xyB, coordsA, coordsB=None,
axesA=None, axesB=None,
arrowstyle="-",
connectionstyle="arc3",
patchA=None,
patchB=None,
shrinkA=0.,
shrinkB=0.,
mutation_scale=10.,
mutation_aspect=None,
clip_on=False,
dpi_cor=1.,
**kwargs):
"""
Connect point *xyA* in *coordsA* with point *xyB* in *coordsB*.
Valid keys are
=============== ======================================================
Key Description
=============== ======================================================
arrowstyle the arrow style
connectionstyle the connection style
relpos default is (0.5, 0.5)
patchA default is bounding box of the text
patchB default is None
shrinkA default is 2 points
shrinkB default is 2 points
mutation_scale default is text size (in points)
mutation_aspect default is 1.
? any key for `matplotlib.patches.PathPatch`
=============== ======================================================
*coordsA* and *coordsB* are strings that indicate the
coordinates of *xyA* and *xyB*.
================= ===================================================
Property Description
================= ===================================================
'figure points' points from the lower left corner of the figure
'figure pixels' pixels from the lower left corner of the figure
'figure fraction' 0, 0 is lower left of figure and 1, 1 is upper right
'axes points' points from lower left corner of axes
'axes pixels' pixels from lower left corner of axes
'axes fraction' 0, 0 is lower left of axes and 1, 1 is upper right
'data' use the coordinate system of the object being
annotated (default)
'offset points' offset (in points) from the *xy* value
'polar' you can specify *theta*, *r* for the annotation,
even in cartesian plots. Note that if you are using
a polar axes, you do not need to specify polar for
the coordinate system since that is the native
"data" coordinate system.
================= ===================================================
Alternatively they can be set to any valid
`~matplotlib.transforms.Transform`.
.. note::
Using `ConnectionPatch` across two `~.axes.Axes` instances
is not directly compatible with :doc:`constrained layout
</tutorials/intermediate/constrainedlayout_guide>`. Add the artist
directly to the `.Figure` instead of adding it to a specific Axes.
.. code-block:: default
fig, ax = plt.subplots(1, 2, constrained_layout=True)
con = ConnectionPatch(..., axesA=ax[0], axesB=ax[1])
fig.add_artist(con)
"""
if coordsB is None:
coordsB = coordsA
# we'll draw ourself after the artist we annotate by default
self.xy1 = xyA
self.xy2 = xyB
self.coords1 = coordsA
self.coords2 = coordsB
self.axesA = axesA
self.axesB = axesB
FancyArrowPatch.__init__(self,
posA=(0, 0), posB=(1, 1),
arrowstyle=arrowstyle,
connectionstyle=connectionstyle,
patchA=patchA,
patchB=patchB,
shrinkA=shrinkA,
shrinkB=shrinkB,
mutation_scale=mutation_scale,
mutation_aspect=mutation_aspect,
clip_on=clip_on,
dpi_cor=dpi_cor,
**kwargs)
# if True, draw annotation only if self.xy is inside the axes
self._annotation_clip = None
def _get_xy(self, xy, s, axes=None):
"""Calculate the pixel position of given point."""
s0 = s # For the error message, if needed.
if axes is None:
axes = self.axes
xy = np.array(xy)
if s in ["figure points", "axes points"]:
xy *= self.figure.dpi / 72
s = s.replace("points", "pixels")
elif s == "figure fraction":
s = self.figure.transFigure
elif s == "axes fraction":
s = axes.transAxes
x, y = xy
if s == 'data':
trans = axes.transData
x = float(self.convert_xunits(x))
y = float(self.convert_yunits(y))
return trans.transform((x, y))
elif s == 'offset points':
if self.xycoords == 'offset points': # prevent recursion
return self._get_xy(self.xy, 'data')
return (
self._get_xy(self.xy, self.xycoords) # converted data point
+ xy * self.figure.dpi / 72) # converted offset
elif s == 'polar':
theta, r = x, y
x = r * np.cos(theta)
y = r * np.sin(theta)
trans = axes.transData
return trans.transform((x, y))
elif s == 'figure pixels':
# pixels from the lower left corner of the figure
bb = self.figure.bbox
x = bb.x0 + x if x >= 0 else bb.x1 + x
y = bb.y0 + y if y >= 0 else bb.y1 + y
return x, y
elif s == 'axes pixels':
# pixels from the lower left corner of the axes
bb = axes.bbox
x = bb.x0 + x if x >= 0 else bb.x1 + x
y = bb.y0 + y if y >= 0 else bb.y1 + y
return x, y
elif isinstance(s, transforms.Transform):
return s.transform(xy)
else:
raise ValueError(f"{s0} is not a valid coordinate transformation")
def set_annotation_clip(self, b):
"""
Set the clipping behavior.
Parameters
----------
b : bool or None
- *False*: The annotation will always be drawn regardless of its
position.
- *True*: The annotation will only be drawn if ``self.xy`` is
inside the axes.
- *None*: The annotation will only be drawn if ``self.xy`` is
inside the axes and ``self.xycoords == "data"``.
"""
self._annotation_clip = b
self.stale = True
def get_annotation_clip(self):
"""
Return the clipping behavior.
See `.set_annotation_clip` for the meaning of the return value.
"""
return self._annotation_clip
def get_path_in_displaycoord(self):
"""Return the mutated path of the arrow in display coordinates."""
dpi_cor = self.get_dpi_cor()
posA = self._get_xy(self.xy1, self.coords1, self.axesA)
posB = self._get_xy(self.xy2, self.coords2, self.axesB)
path = self.get_connectionstyle()(
posA, posB,
patchA=self.patchA, patchB=self.patchB,
shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor,
)
path, fillable = self.get_arrowstyle()(
path,
self.get_mutation_scale() * dpi_cor,
self.get_linewidth() * dpi_cor,
self.get_mutation_aspect()
)
return path, fillable
def _check_xy(self, renderer):
"""Check whether the annotation needs to be drawn."""
b = self.get_annotation_clip()
if b or (b is None and self.coords1 == "data"):
xy_pixel = self._get_xy(self.xy1, self.coords1, self.axesA)
if self.axesA is None:
axes = self.axes
else:
axes = self.axesA
if not axes.contains_point(xy_pixel):
return False
if b or (b is None and self.coords2 == "data"):
xy_pixel = self._get_xy(self.xy2, self.coords2, self.axesB)
if self.axesB is None:
axes = self.axes
else:
axes = self.axesB
if not axes.contains_point(xy_pixel):
return False
return True
def draw(self, renderer):
if renderer is not None:
self._renderer = renderer
if not self.get_visible() or not self._check_xy(renderer):
return
FancyArrowPatch.draw(self, renderer)
| [
"adarshsaig@gmail.com"
] | adarshsaig@gmail.com |
96667febbdf8cf838139b3279b7909b587613445 | 806b22ddf02f3cb0dfbbb31d7c214f9d12f667fe | /testimonials/migrations/0004_auto_20180508_2155.py | 0d74be387a5ace84d117c2ac259f2f1154e6b102 | [] | no_license | vieiraa360/full_stack_project | 2adc81478963ca091d9f02ae2ecd34992f291657 | 2f6fc5bdd490302aa83ec6c896da390a06075fd9 | refs/heads/master | 2021-06-04T15:58:06.913176 | 2021-03-29T21:48:16 | 2021-03-29T21:48:16 | 130,612,621 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 782 | py | # Generated by Django 2.0.4 on 2018-05-08 21:55
from django.db import migrations, models
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('testimonials', '0003_auto_20180508_2148'),
]
operations = [
migrations.AddField(
model_name='testimonial',
name='image',
field=models.ImageField(blank=True, null=True, upload_to='img'),
),
migrations.AlterField(
model_name='testimonial',
name='text',
field=tinymce.models.HTMLField(verbose_name='content'),
),
migrations.AlterField(
model_name='testimonial',
name='title',
field=models.CharField(max_length=50, null=True),
),
]
| [
"vieiraa360@gmail.com"
] | vieiraa360@gmail.com |
e64cd491a7d101d10bda592a71e75d2c92d17b50 | 2cb1df9c728d15d88a01242c1c59774b71ba8c3b | /Bill Splitter/task/billsplitter.py | 1f809d188469b72a5f8c371c3e1595740fe4fccf | [] | no_license | okornoe/Bill_Splitter | 1bd198028a32c9ef7c23e115dcf6d6113e1c49c1 | d488a7291c630e66bfb94ff841ac67d8721ef3d0 | refs/heads/master | 2023-08-03T18:38:02.666120 | 2021-09-08T08:10:39 | 2021-09-08T08:10:39 | 404,264,905 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,274 | py | # write your code here
import random
guest_list = {}
guest_names = []
bill_amount = 0
print("Enter the number of friends joining (including you):")
num_of_friends = input()
if num_of_friends.isalpha() or int(num_of_friends) <= 0:
print("No one is joining for the party")
else:
print("Enter the name of every friend (including you), each on a new line:")
for num in range(int(num_of_friends)):
guest_names.append(input())
print("Enter the total bill value:")
bill_amount = float(input())
print("Do you want to use the \"Who is lucky?\"feature? Write Yes/No:")
lucky = input()
if lucky == "Yes":
bill_amount = (bill_amount / (len(guest_names) - 1))
lucky_guest = guest_names[random.randint(0, len(guest_names) - 1)]
print("{} is the lucky one!".format(lucky_guest))
print()
for num in range(int(num_of_friends)):
guest_list[guest_names[num]] = round(bill_amount, 2)
guest_list[lucky_guest] = 0
print(guest_list)
else:
bill_amount = bill_amount / len(guest_names)
print("No one is going to be lucky")
for num in range(int(num_of_friends)):
guest_list[guest_names[num]] = round(bill_amount, 2)
print(guest_list)
| [
"kelvin.okornoe@gmail.com"
] | kelvin.okornoe@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.