id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
313089 | <reponame>hirmeos/metrics<filename>src/plugins/generic/generic.py
from generic.mount_point import GenericDataProvider
class GenericEventDataProvider(GenericDataProvider):
""" Data Provider class which inherits from GenericDataProvider.
It is used to fetch from a particular source and format it into a list of
dicts with the following keys:
It must provide a process method which has a Doi model instance passed
to it.
"""
def process(self, doi):
""" Retrieve and process the data.
Retrieve and process data from a source specific to this plugin. Must
return a list of dicts representing an event like a Facebook post
mention.
Parameters:
doi (Doi): A Doi model object we're getting events events for.
Returns:
list: Contains dicts representing the events, e.g.
[
{
# The id of the event, in the form of uuid4.
'external_id': '',
# An identifier for the source of the document.
'source_id': '',
# Where the event came from, ie twitter, facebook.
'source': '',
# A datetime when this event was created.
'created_at': '',
# The actual content of the document, could be a link.
'content': '',
# The actual DOI, which is the DOI passed into this method.
'doi': ''
}
]
"""
# this will fail to create an event, as external id is not in uuid form.
return [
{
'external_id': '',
'source_id': '',
'source': '',
'created_at': '',
'content': '',
'doi': '',
}
]
@staticmethod
def is_authorised(users, **kwargs):
""" An optional method that allows you to deny the use of this plugin.
It's based upon custom criteria. The most common recommended one
is to use user groups, and allow only users in a particular user
group to use the plugin. User groups are part of the standard Django
framework.
Parameters:
users (User): A User model queryset for all the users that
uploaded CSVs with the doi in it.
**kwargs: is an optional list of keyword params which may change
in the future, and any extra params will be documented
Returns:
True if authorised, False if not
"""
if users.filter(groups__name='generic'):
return True # Authorise the use of the plugin for the DOI.
return False # Not authorised to use this plugin for the DOI.
| StarcoderdataPython |
8184415 | import time
import spidev
import RPi.GPIO as GPIO
__version__ = '0.0.3'
class APA102():
def __init__(self, count=1, gpio_data=14, gpio_clock=15, gpio_cs=None, brightness=1.0, force_gpio=False, invert=False, spi_max_speed_hz=1000000):
"""Initialise an APA102 device.
Will use SPI if it's available on the specified data/clock pins.
:param pixel_count: Number of individual RGB LEDs
:param gpio_data: BCM pin for data
:param gpio_clock: BCM pin for clock
:param gpio_cs: BCM pin for chip-select
:param force_gpio: Specify true to force use of GPIO bitbanging
"""
self._gpio_clock = gpio_clock
self._gpio_data = gpio_data
self._gpio_cs = gpio_cs
self._invert = invert
if invert:
# TODO Add invert support for SPI
force_gpio = True
self._gpio = None
self._spi = None
self._brightness = brightness
self._sof_length = 4 # SOF bytes
self._eof_length = 4 # EOF bytes
buffer_length = count * 4
self._buf = []
for _ in range(self._sof_length):
self._buf.append(0b00000000)
self._buf += [0b11100000 | int(self._brightness * 31) for _ in range(buffer_length)]
for _ in range(self._eof_length):
self._buf.append(0b11111111)
if not force_gpio and gpio_data == 10 and gpio_clock == 11 and gpio_cs in (None, 7, 8):
cs_channel = 0
if gpio_cs is not None:
cs_channel = [8, 7].index(gpio_cs)
self._spi = spidev.SpiDev(0, cs_channel)
self._spi.max_speed_hz = spi_max_speed_hz
if gpio_cs is None:
self._spi.no_cs = True
self._gpio_cs = None
elif not force_gpio and gpio_data == 20 and gpio_clock == 21 and gpio_cs in (None, 18, 17, 16):
cs_channel = 0
if gpio_cs is not None:
cs_channel = [18, 17, 16].index(gpio_cs)
self._spi = spidev.SpiDev(0, cs_channel)
self._spi.max_speed_hz = spi_max_speed_hz
if gpio_cs is None:
self._spi.no_cs = True
self._gpio_cs = None
else:
self._gpio = GPIO
self._gpio.setmode(GPIO.BCM)
self._gpio.setwarnings(False)
self._gpio.setup(gpio_data, GPIO.OUT, initial=1 if self._invert else 0)
self._gpio.setup(gpio_clock, GPIO.OUT, initial=1 if self._invert else 0)
if self._gpio_cs is not None:
self._gpio.setup(self._gpio_cs, GPIO.OUT)
def _write_byte(self, byte):
for _ in range(8):
self._gpio.output(self._gpio_data, not (byte & 0x80) if self._invert else (byte & 0x80))
self._gpio.output(self._gpio_clock, 0 if self._invert else 1)
time.sleep(0)
byte <<= 1
self._gpio.output(self._gpio_clock, 1 if self._invert else 0)
time.sleep(0)
def set_pixel(self, x, r, g, b):
"""Set a single pixel
:param x: x index of pixel
:param r: amount of red (0 to 255)
:param g: amount of green (0 to 255)
:param b: amount of blue (0 to 255)
"""
offset = self._sof_length + (x * 4) + 1
self._buf[offset:offset + 3] = [b, g, r]
def set_brightness(self, x, brightness):
"""Set global brightness of a single pixel
:param x: x index of pixel
:param brightness: LED brightness (0.0 to 1.0)
"""
offset = self._sof_length + (x * 4)
self._buf[offset] = 0b11100000 | int(31 * brightness)
def show(self):
"""Display the buffer
Outputs the buffer to connected LEDs using either bitbanged GPIO or SPI.
"""
if self._gpio_cs is not None:
self._gpio.output(self._gpio_cs, 0)
if self._spi is not None:
self._spi.xfer3(self._buf)
else:
for byte in self._buf:
self._write_byte(byte)
if self._gpio_cs is not None:
self._gpio.output(self._gpio_cs, 1)
| StarcoderdataPython |
5041323 | """ The CONFIG object is created and exported once __at import time__
Calling CONFIG["KEY"] directly should be sufficient in most cases,
except when a config value has changed since importing CONFIG.
In that case, create_config_dict() can provide an updated config dict
Priority (highest to lowest):
1. Command line argument values
2. Environment variable values
3. Config file values in [defaults] section
4. DEFAULTS (see keys.py)
"""
from .config import create_config_dict, get_singleton
CONFIG = create_config_dict()
PG_HOST = get_singleton(CONFIG, "SG_ENGINE_HOST")
PG_PORT = get_singleton(CONFIG, "SG_ENGINE_PORT")
PG_DB = get_singleton(CONFIG, "SG_ENGINE_DB_NAME")
PG_USER = get_singleton(CONFIG, "SG_ENGINE_USER")
PG_PWD = get_singleton(CONFIG, "SG_ENGINE_PWD")
SPLITGRAPH_META_SCHEMA = get_singleton(CONFIG, "SG_META_SCHEMA")
SPLITGRAPH_API_SCHEMA = "splitgraph_api"
FDW_CLASS = get_singleton(CONFIG, "SG_FDW_CLASS")
SG_CMD_ASCII = get_singleton(CONFIG, "SG_CMD_ASCII") == "true"
REMOTES = list(CONFIG.get("remotes", []))
# This is a global variable that gets flipped to True by the Multicorn FDW class
# at startup. When we're running from within an engine as an FDW, we might need to use
# different connection parameters to connect to other engines. It's not trivial to detect
# whether we're running inside of an embedded Python otherwise and this variable needs to
# ultimately make it into all get_engine() constructors, so this is simpler than threading
# it through all calls that FDW makes.
IN_FDW = False
| StarcoderdataPython |
3482364 | import cv2
import numpy as np
def nothing(x):
pass
#img = cv2.imread('img.jpeg',-1)
cap=cv2.VideoCapture(0)
cv2.namedWindow('image')
cv2.resizeWindow('image',600,350)
#Creating trackbar
cv2.createTrackbar('lh','image',0,255,nothing)
cv2.createTrackbar('uh','image',0,255,nothing)
cv2.createTrackbar('ls','image',0,255,nothing)
cv2.createTrackbar('us','image',0,255,nothing)
cv2.createTrackbar('lv','image',0,255,nothing)
cv2.createTrackbar('uv','image',0,255,nothing)
#cv2.createTrackbar('switch','image',0,1,nothing)
#set track bar
cv2.setTrackbarPos('lh','image',0)
cv2.setTrackbarPos('uh','image',58)
cv2.setTrackbarPos('ls','image',45)
cv2.setTrackbarPos('us','image',255)
cv2.setTrackbarPos('lv','image',54)
cv2.setTrackbarPos('uv','image',168)
while True:
_,img=cap.read()
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#while 1 :
#reading trackbar
lh=cv2.getTrackbarPos('lh','image')
uh=cv2.getTrackbarPos('uh','image')
ls=cv2.getTrackbarPos('ls','image')
us=cv2.getTrackbarPos('us','image')
lv=cv2.getTrackbarPos('lv','image')
uv=cv2.getTrackbarPos('uv','image')
#switch = cv2.getTrackbarPos('switch','image')
l_r=np.array([lh,ls,lv])
u_r=np.array([uh,us,uv])
mask = cv2.inRange(hsv,l_r,u_r)
res=cv2.bitwise_and(img,img,mask=mask)
#blur
k=np.ones((15,15),np.float32)/225
s= cv2.filter2D(res,-1,k)
b= cv2.GaussianBlur(res,(15,15),0)
m= cv2.medianBlur(res,15)
bb =cv2.bilateralFilter(res , 15 , 75, 75)#useless
#morphology
k2= np.ones((5,5) , np.uint8)
e=cv2.erode(mask,k2,1)
d=cv2.dilate(mask,k2,1)
o=cv2.morphologyEx(mask,cv2.MORPH_OPEN,k2)
c=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,k2)
oc=cv2.morphologyEx(o,cv2.MORPH_CLOSE,k2)#same as close+open
#output
#cv2.imshow('img',img)
#cv2.imshow('mask',mask)
#cv2.waitKey(1000)
cv2.imshow('res',res)
#cv2.imshow('blur',s)
#cv2.imshow('Gblur',b)
#cv2.imshow('medblur',m)
#cv2.imshow('bilateralblur',bb)
#cv2.imshow('erode',e)
#cv2.imshow('dillate',d)
#cv2.imshow('openM',o)
#cv2.imshow('closeM',c)
#cv2.imshow('OnC_M',oc)
if cv2.waitKey(1) & 0xFF==ord('q'):
break
#cv2.waitKey(0)
cap.release()
cv2.destroyAllWindows()
| StarcoderdataPython |
12831213 | <gh_stars>1-10
from twisted.logger import FileLogObserver, FilteringLogObserver, globalLogPublisher, InvalidLogLevelError, \
Logger, LogLevel, LogLevelFilterPredicate
from twisted.python.logfile import DailyLogFile
from heufybot.bot import HeufyBot
from heufybot.utils.logutils import consoleLogObserver, logFormat
from signal import signal, SIGINT
import argparse
if __name__ == "__main__":
# Parse the command line arguments
parser = argparse.ArgumentParser(description="A modular Twisted IRC bot.")
parser.add_argument("-c", "--config", help="The configuration file to use", type=str, default="heufybot.yaml")
parser.add_argument("-f", "--logfile", help="The file the log will be written to", type=str, default="heufybot.log")
parser.add_argument("-l", "--loglevel", help="The logging level the bot will use", type=str, default="INFO")
options = parser.parse_args()
# Start the bot
heufybot = HeufyBot(options.config)
# Determine the logging level
logFilter = LogLevelFilterPredicate()
try:
logFilter.setLogLevelForNamespace("heufybot", LogLevel.levelWithName(options.loglevel.lower()))
invalidLogLevel = False
except InvalidLogLevelError:
logFilter.setLogLevelForNamespace("heufybot", LogLevel.info)
invalidLogLevel = True
# Set up logging
logFile = DailyLogFile("heufybot.log", "")
fileObserver = FileLogObserver(logFile, logFormat)
fileFilterObserver = FilteringLogObserver(fileObserver, (logFilter,))
consoleFilterObserver = FilteringLogObserver(consoleLogObserver, (logFilter,))
heufybot.log = Logger("heufybot")
globalLogPublisher.addObserver(fileFilterObserver)
globalLogPublisher.addObserver(consoleFilterObserver)
heufybot.log.info("Starting bot...")
# Yell at the user if they specified an invalid log level
if invalidLogLevel:
heufybot.log.warn("Picked up invalid log level {invalidLevel}, level has been set to INFO instead.",
invalidLevel=options.loglevel.lower())
signal(SIGINT, lambda signal, stack: heufybot.shutdown())
heufybot.startup()
| StarcoderdataPython |
8012331 | #!/usr/bin/env python
import argparse
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import operator
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.")
parser = argparse.ArgumentParser()
parser.add_argument(
"-c", "--controller", default="localhost", help='the controller address (default "localhost")',
)
parser.add_argument(
"-u", "--username", default="admin", help='the controller username (default("admin")',
)
parser.add_argument("-p", "--password", default="", help="the controller password")
parser.add_argument(
"-b", "--port", type=int, default=8443, help='the controller port (default "8443")',
)
parser.add_argument(
"-s", "--step", type=int, default=4, help="only reset every x units (default 4)",
)
parser.add_argument(
"-m", "--modulus", type=int, default=0, help="reset units starting with number (default 0)",
)
parser.add_argument(
"-t", "--type", default="uap", help='the type of device to reset (default "uap")',
)
parser.add_argument(
"-v", "--verify", type=str2bool, default=False, help="verify SSL requests",
)
parser.set_defaults(verify=False)
args = parser.parse_args()
if not args.verify:
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
base_url = "https://" + args.controller + ":" + str(args.port)
login_url = base_url + "/api/login"
login_data = {"username": args.username, "password": <PASSWORD>.password}
default_headers = {"Origin": base_url}
login_cookies = requests.post(login_url, json=login_data, headers=default_headers, verify=args.verify).cookies
sites = requests.get(
base_url + "/api/self/sites", cookies=login_cookies, headers=default_headers, verify=args.verify,
).json()
for site in sites["data"]:
site_name = site["name"]
device_list = sorted(
requests.get(
base_url + "/api/s/" + site_name + "/stat/device",
cookies=login_cookies,
headers=default_headers,
verify=args.verify,
).json()["data"],
key=lambda device: device["name"],
)
for device_index, device in enumerate(device_list):
if device["type"] == args.type and device_index % args.step == args.modulus:
requests.post(
base_url + "/api/s/" + site_name + "/cmd/devmgr",
cookies=login_cookies,
headers=default_headers,
json={"mac": device["mac"], "reboot_type": "soft", "cmd": "restart",},
verify=args.verify,
)
| StarcoderdataPython |
6562158 | from django.urls import path
from . import views
urlpatterns = [
path("", views.profile, name="profile"),
path("order_history/<order_number>", views.order_history, name="order_history"),
]
| StarcoderdataPython |
149899 | <gh_stars>10-100
# Generated by Django 3.1 on 2020-08-08 16:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="City",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=30, unique=True)),
("description", models.CharField(max_length=500)),
("slug", models.SlugField()),
],
options={"verbose_name_plural": "cities",},
),
]
| StarcoderdataPython |
130764 | <reponame>Paul-St-Young/QMC
#!/usr/bin/python
import h5py
import numpy as np
import matplotlib.pyplot as plt
import pandas
import argparse
from scipy.optimize import curve_fit
def gofrGrabber(h5file,myi,myj):
# get gofr list with label "gofr_ion0_myi_myj"
dr = 0.0
r = []
GR = []
f = h5py.File(h5file)
for name,quantity in f.items():
if name.startswith('gofr'):
g,p,i,j = name.split('_')
if i==str(myi) and j==str(myj):
dr = quantity.get("delta")[0]
maxr = quantity.get("cutoff")[0]
r = np.arange( int(maxr/dr) ) * dr
for k in range(len(r)):
r[k] += dr/2.0
# end for k
GR = quantity.get("value")[:]
# end if name.startswith
# end for name,quantity
f.close()
return r,dr,GR
# end def gofrGrabber
def normalize2PDF(r,dr,gr):
A = 0.0
for i in range(len(r)):
gr[i] *= 4*np.pi*r[i]*r[i]*dr
A += gr[i]*dr
# end for
for i in range(len(r)):
gr[i] /= A
# end for
# end def
def average(r,gr):
return sum(r*gr)/sum(gr)
# end def average
def get_start_and_end(gr,thres):
started = False
start = 0
end = len(gr)-1
for i in range(len(gr)):
if (not started) and gr[i]>thres:
started = True
start = i
# end if not started
if started and gr[i]<thres:
end = i
break
#end if started
# end for
return start,end
# end def
def mix(vgr,dgr,eps):
vstart, vend = get_start_and_end(vgr,eps)
dstart, dend = get_start_and_end(dgr,eps)
start = max(vstart,dstart)
end = min(vend,dend)
lnfix = list( np.zeros( min(vstart,start) ) )
if start > vstart:
lnfix += list( np.zeros(start-vstart) )
# end if
for i in range(start,end):
lnfix.append(dgr[i]/vgr[i])
# end i
lnfix += list( np.zeros(len(vgr)-end) )
return lnfix
# end def mix
def quick_fix(vgr,dgr,eps):
fixed_gr = []
for i in range(len(vgr)):
if vgr[i]>eps:
#fixed_gr.append(dgr[i]*dgr[i]/vgr[i])
fixed_gr.append(dgr[i]+dgr[i]-vgr[i])
else:
fixed_gr.append(dgr[i])
# end if
# end for
return fixed_gr
# end def quick_fix
def cut(r,f,r1,r2): # cut out a piece of f and pad with 0
cutgr = []
for i in range(len(r)):
if r[i]>r1 and r[i]<r2:
cutgr.append(f[i])
else:
cutgr.append(0)
# end if
# end for
return cutgr
# end def cut
def perform_quick_fix(r,vgr,dgr,thres=1e-2):
'''
mean_vgr = []
for i in range(0,len(vgr)-5,6):
mean_vgr.append( sum(vgr[i:i+6])/6. )
# end for i
vgr = mean_vgr[:]
'''
fixed_gr = quick_fix(vgr,dgr,thres)
normalize2PDF(r,dr,fixed_gr)
return r,fixed_gr
# end def perform_quick_fix
from scipy.interpolate import interp1d
def spline_quick_fix(r,vgr,dgr,thres=1e-2):
newr=np.arange( r[0],r[-1],(r[-1]-r[0])/(10*len(r)) )
svgr=interp1d(r,vgr,kind='cubic')(newr)
sdgr=interp1d(r,dgr,kind='cubic')(newr)
fixed_gr = quick_fix(svgr,sdgr,thres)
normalize2PDF(newr,newr[1]-newr[0],fixed_gr)
return newr,svgr,sdgr,fixed_gr
# end def spline_quick_fix
if __name__=="__main__":
parser = argparse.ArgumentParser(description='Use g(r) to fix wf')
parser.add_argument('VMC',type=str,help='h5 file containing VMC gofr')
parser.add_argument('DMC',type=str,help='h5 file containing VMC gofr')
parser.add_argument("-vw", "--VMCwindowSize", type=int, default=4000
, help="number of data points to take from the end of VMC" )
parser.add_argument("-dw", "--DMCwindowSize", type=int, default=500
, help="number of data points to take from the end of DMC" )
parser.add_argument("-t", "--threshold", type=float, default=1e-2
, help="threshold for small number, default 1e-2" )
args = parser.parse_args()
r,dr,VGR = gofrGrabber(args.VMC,'0','2')
vgr = VGR[len(VGR)-args.VMCwindowSize:].mean(axis=0)
normalize2PDF(r,dr,vgr)
r,dr,DGR = gofrGrabber(args.DMC,'0','2')
dgr = DGR[len(DGR)-args.DMCwindowSize:].mean(axis=0)
normalize2PDF(r,dr,dgr)
# ---- vgr,dgr now contain probability distributions
# quick fixed
r,fixed_gr = perform_quick_fix(r,vgr,dgr,args.threshold)
r,vgr,dgr,fixed_gr = spline_quick_fix(r,vgr,dgr,args.threshold)
print "fix int ", sum(fixed_gr*r)/sum(fixed_gr)
print sum(vgr)
print sum(dgr)
ar = np.array( [vgr,dgr,fixed_gr] )
df = pandas.DataFrame(ar.T,index=r,columns=["VMC","DMC","Fix"])
ax = df.plot(title=r"Probability Distribution of $r_{CH}$")
ax.set_xlabel(r"$r_{CH}$ (bohr)",fontsize=16)
ax.set_ylabel("P(r)",fontsize=16)
plt.show()
# end __main__
| StarcoderdataPython |
4857901 | <filename>Python Fundamentals/1. Basic Syntax, Conditional Statements and Loops/Exercise/07. Maximum Multiple.py
divisor = int(input())
bound = int(input())
max_multiplier = 0
for current_number in range(divisor + 1, bound + 1):
if current_number % divisor == 0:
max_multiplier = current_number
print(max_multiplier) | StarcoderdataPython |
4935219 | # GHC Codepath - Sandbox - 8
# Module SE101
#!/bin/python3
import math
import os
import random
import re
import sys
# Calculator to parse natural language and speak in natural language
# - Only given 2 operands and all operands < 100
# sample input:
# "add two and seven"
# "subtract six from four"
# sample output:
# "nine"
# "negative-two"
def nlp_calculator(command):
numbers = {
"one" : 1,
"two" : 2,
"three" : 3,
"four" : 4,
"five" : 5,
"six" : 6,
"seven" : 7,
"eight" : 8,
"nine" : 9,
"ten" : 10,
"eleven" : 11,
"twelve" : 12,
"thirteen" : 13,
"fourteen" : 14,
"fifteen" : 15,
"sixteen" : 16,
"seventeen" : 17,
"eighteen" : 18,
"nineteen" : 19,
"twenty" : 20,
"thirty" : 30,
"forty" : 40,
"fifty" : 50,
"sixty" : 60,
"seventy" : 70,
"eighty" : 80,
"ninety" : 90
}
operand_one = command.split()[1]
if "-" in operand_one:
temp = operand_one.split("-")
operand_one = numbers[temp[0]] + numbers[temp[1]]
else:
operand_one = numbers[operand_one]
operand_two = command.split()[3]
if "-" in operand_two:
temp = operand_two.split("-")
operand_two = numbers[temp[0]] + numbers[temp[1]]
else:
operand_two = numbers[operand_two]
operation = command.split()[0]
def add(a, b):
return a + b
def sub(a, b):
return b - a
def mul(a, b):
return a * b
def div(a, b):
return b // a
operations ={
"add" : add,
"subtract" : sub,
"multiply" : mul,
"divide" : div
}
num = operations[operation](operand_one, operand_two)
ans_string = ""
if num < 0:
ans_string += "negative-"
num *= -1
thousands = num // 1000
hundreds = (num // 100) % 10
tens = (num // 10) % 10
ones = num % 10
number = {}
for key, val in numbers.items():
number[val] = key
if num in number.keys():
return ans_string + number[num]
if thousands != 0:
ans_string += number[thousands] + "-thousand-"
if hundreds != 0:
ans_string += number[hundreds] + "-hundred-"
if tens != 0:
ans_string += number[tens * 10] + "-"
if ones != 0:
ans_string += number[ones]
return ans_string
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
command = input()
result = nlp_calculator(command)
fptr.write(result + '\n')
fptr.close()
| StarcoderdataPython |
10681 | <gh_stars>10-100
#!/usr/bin/env python3
# Copyright 2018 Brocade Communications Systems LLC. 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 also 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.
"""
:mod:`switch_configuration_show` - PyFOS util for configuring switch operation
********************************************************************************
The :mod:`switch_configuration_show` util provides for configuring switch \
operation.
This module is a stand-alone script that can be used to display switch
attributes.
* Input:
* -L=<login>: The login ID. If not provided, an interactive
prompt will request one.
* -P=<password>: The password. If not provided, an interactive
prompt will request one.
* -i=<IP address>: The IP address.
* -f=<VFID>: The VFID or -1 if VF is disabled. If unspecified,
a VFID of 128 is assumed.
* Output:
* The switch attributes in JSON format.
.. function:: show_switch_conf(session)
Example Usage of the Method::
ret = switch_configuration_show.show_switch_conf(session)
print (ret)
Details::
switch_conf_obj = switch_configuration()
result = switch_conf_obj.get(session)
return result
* Input:
:param session: The session returned by login.
* Output:
:rtype: A dictionary of return status matching the REST response.
*Use Cases*
1. Retrieve the configuration parameters of the switch.
"""
import sys
from pyfos import pyfos_auth
import pyfos.pyfos_brocade_fibrechannel_configuration as py_fc
from pyfos import pyfos_util
from pyfos.utils import brcd_util
switch = py_fc.switch_configuration
def show_switch_conf(session):
switch_conf_obj = switch()
result = switch_conf_obj.get(session)
return result
def main(argv):
filters = []
inputs = brcd_util.parse(argv, switch, filters)
session = brcd_util.getsession(inputs)
result = show_switch_conf(inputs['session'])
pyfos_util.response_print(result)
pyfos_auth.logout(session)
if __name__ == "__main__":
main(sys.argv[1:])
| StarcoderdataPython |
11250509 | <gh_stars>0
#Function to capture all the copyright notice from the license file
tag = Html tags!!
copy_right = None
copyright_list = []
is_copyright = False
def capture_copyright(tag, copy_right, copyright_list, is_copyright):
re_copyright = re.compile(r'copyright (\([Cc@]\)|\d+).*', re.IGNORECASE)
re_junk_copyright = re.compile('copyright.*\<YEAR\>.*', re.IGNORECASE)
if re_junk_copyright.search(tag.text) != None:
return ("", copyright_list, False)
if tag.text != " ":
found_copyright_notice = re_copyright.search(tag.text)
if found_copyright_notice != None and found_copyright_notice.group(0) not in copyright_list: #Re-test for multiple copyrights in the license file.
if len(tag.text) > 100: #If the copyright and license texts are text?!
is_lengthy_text = True
lengthy_text = tag.text
for line in lengthy_text.split("\n"):
copyright_notice_from_lengthy_text = re_copyright.search(line)
if copyright_notice_from_lengthy_text != None:
copy_right = copyright_notice_from_lengthy_text.group(0)
elif len(tag.text) > 30 and not (re_copyright.search(found_copyright_notice.group(0))): #For the plain copyright text from the license.
copy_right = ""
else:
copy_right = found_copyright_notice.group(0)
#if tag.text not in copyright_list and tag.text not in ["Copyright","copyright"]:
if copy_right != "" and re.sub('All Rights Reserved.',"", copy_right, flags=re.IGNORECASE) not in copyright_list:
copyright_list.append(re.sub('All Rights Reserved.',"", copy_right, flags=re.IGNORECASE))
is_copyright = True
return (copy_right, copyright_list, is_copyright)
#End of the function capture_copyright function.
| StarcoderdataPython |
1752174 | <gh_stars>0
"""
Definition of the Lorenz96 model.
Created on 2019-04-16-12-28
Author: <NAME>, <EMAIL>
Update with julia/numba implementations and refactored by David Greenberg 02-2020
"""
import sys
import numpy as np
from delfi.simulator.BaseSimulator import BaseSimulator
from scipy.integrate import solve_ivp
import warnings
from L96sim import L96_base
from L96sim.L96_base import f1, f2, J1, J1_init, f1_juliadef, f2_juliadef
def in_notebook():
"""
Returns ``True`` if the module is running in IPython kernel,
``False`` if in IPython shell or other Python shell.
"""
return 'ipykernel' in sys.modules
if in_notebook():
from tqdm import tqdm_notebook as tqdm
else:
from tqdm import tqdm
class L96OneSim(BaseSimulator):
def __init__(self, dim=1, noise_obs=0.1, K=36, seed=None, dt=0.001,
obs_times=None, obs_X=None):
if obs_times is None:
obs_times = [10.0]
obs_nsteps = np.unique([np.ceil(t / dt) for t in obs_times]).astype(int)
if obs_X is None:
obs_X = np.arange(0, K, 4)
else:
assert np.all(obs_X >= 0) and np.all(obs_X < K)
super().__init__(dim_param=dim, seed=seed)
self.noise_obs, self.K, self.obs_nsteps, self.obs_X, self.dt = noise_obs, K, obs_nsteps, obs_X, dt
if L96_base.julia_available:
self.f_juliadef = L96_base.Main.eval(f1_juliadef.format(K=K))
def gen_single(self, param, use_julia=True, use_juliadef=True, method='RK45'):
# method can be LSODA, BDF, Radau or RK45. used only when use_julia is False
assert param.ndim == 1 and param.size == 1
F = param[0]
X_init = F * (0.5 + self.rng.randn(self.K) * 1.0)
tspan = (0, self.obs_nsteps[-1] * self.dt)
n = X_init.size
dX_dt = np.empty(n, dtype=X_init.dtype)
df_dX = J1_init(n).astype(X_init.dtype) # initialize as a sparse matrix
def f(t, X):
return f1(X, F, dX_dt, n)
def J(t, X):
return J1(X, F, df_dX, n)
if use_julia:
assert L96_base.julia_available
if use_juliadef:
f_julia = self.f_juliadef
p = np.array([F], dtype=X_init.dtype)
problem = L96_base.de.ODEProblem(f_julia, X_init, tspan, p)
else:
def f_julia(X, p, t):
return f(t, X)
problem = L96_base.de.ODEProblem(f_julia, X_init, tspan)
self.sol = L96_base.de.solve(problem)
u = np.array(self.sol(self.obs_nsteps * self.dt))
return {'data': u[self.obs_X, :].T.reshape(-1)}
else:
opts = dict()
if method in ['Radau', 'BDF'] and not L96_base.numba_available: # numba doesn't work with sparse matrices
opts['jac'] = J
self.sol = solve_ivp(f, tspan, X_init, method=method,
max_step=0.1,
t_eval=self.obs_nsteps * self.dt, **opts)
return {'data': self.sol.y[self.obs_X, :].T.reshape(-1)}
class L96TwoSim(BaseSimulator):
def __init__(self, dim=4, noise_obs=0.1, K=36, J=10, seed=None, dt=0.001,
obs_times=None, obs_X=None):
if obs_times is None:
obs_times = [10.0]
obs_nsteps = np.unique([np.ceil(t / dt) for t in obs_times]).astype(int)
if obs_X is None:
obs_X = np.arange(0, K, 4)
else:
assert np.all(obs_X >= 0) and np.all(obs_X < K)
super().__init__(dim_param=dim, seed=seed)
self.noise_obs, self.K, self.J, self.obs_nsteps, self.obs_X, self.dt = noise_obs, K, J, obs_nsteps, obs_X, dt
obs_Y = np.zeros((K, J))
obs_Y[self.obs_X, :] = 1
self.obs_Y = np.where( obs_Y.flatten() )[0]
self.obs_X_and_Y = np.concatenate((self.obs_X, self.obs_Y + K))
if L96_base.julia_available:
self.f_juliadef = L96_base.Main.eval(f2_juliadef.format(K=K, J=J))
def gen_single(self, param, use_julia=True, use_juliadef=True, method='LSODA'):
# method can be LSODA, BDF, Radau or RK45. used only when use_julia is False
assert param.ndim == 1 and param.size == 4
F, h, b, c = param[0], param[1], param[2], np.exp(param[3])
X_init = self.rng.randn(self.K)
Y_init = self.rng.randn(self.K * self.J)
X_and_Y_init = np.concatenate((X_init, Y_init))
tspan = (0, self.obs_nsteps[-1] * self.dt)
dX_and_Y_dt = np.empty_like(X_and_Y_init)
def f(t, X_and_Y):
return f2(X_and_Y, F, h, b, c, dX_and_Y_dt, self.K, self.J)
if use_julia:
assert L96_base.julia_available
if use_juliadef:
f_julia = self.f_juliadef
p = np.array([F, h, b, c], dtype=X_and_Y_init.dtype)
problem = L96_base.de.ODEProblem(f_julia, X_and_Y_init, tspan, p)
else:
def f_julia(X_and_Y, p, t):
return f(t, X_and_Y)
problem = L96_base.de.ODEProblem(f_julia, X_and_Y_init, tspan)
self.sol = L96_base.de.solve(problem)
u = np.array(self.sol(self.obs_nsteps * self.dt))
obs_data = u[self.obs_X_and_Y, :]
else:
opts = dict()
# Jacobian not implented in python yet
#if method in ['Radau', 'BDF']:
# opts['jac'] = J
self.sol = solve_ivp(f, tspan, X_and_Y_init, method=method,
max_step=0.1,
t_eval=self.obs_nsteps * self.dt, **opts)
obs_data = self.sol.y[self.obs_X_and_Y, :]
obsx = obs_data[:len(self.obs_X), :].T.reshape(-1)
obsy = obs_data[len(self.obs_X):, :].T.reshape(-1)
return {'data': (obsx, obsy)}
| StarcoderdataPython |
82441 | <reponame>mrdulin/python-codelab<filename>src/stackoverflow/60539392/test_main.py
from main import my_func
import unittest
from unittest.mock import patch
class TestMain(unittest.TestCase):
@patch('main.MyClass')
def test_my_func(self, MockMyClass):
mock_my_class_instance = MockMyClass.return_value
my_func()
mock_my_class_instance.do_thing.assert_called_once()
if __name__ == '__main__':
unittest.main()
| StarcoderdataPython |
150748 | import tensorflow.keras
from tensorflow.keras import layers
import os
import matplotlib.pyplot as plt
from PIL import Image
#from numpy import asarray
import numpy as np
from tensorflow.keras import backend as K
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.models import load_model
from tensorflow.keras import preprocessing
from tensorflow.keras import backend as K
from tensorflow.keras import models
import tensorflow as tf
from config import *
from model import ProposedModel, getAssembledModel
tf.config.run_functions_eagerly(True)
config = tf.compat.v1.ConfigProto(gpu_options =
tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.8)
# device_count = {'GPU': 1}
)
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config)
tf.compat.v1.keras.backend.set_session(session)
def getHeatMap(image, encoded):
image_size = 224
# Load pre-trained Keras model and the image to classify
model = tf.keras.applications.vgg16.VGG16(include_top=False, weights="imagenet")
img_tensor = preprocessing.image.img_to_array(image)
img_tensor = np.expand_dims(img_tensor, axis=0)
img_tensor = preprocess_input(img_tensor)
conv_layer = model.get_layer("block5_conv3")
heatmap_model = encoded
with tf.GradientTape() as gtape:
conv_output = heatmap_model(tf.convert_to_tensor(img_tensor, dtype=tf.float32))
print(conv_output)
loss = predictions[:, np.argmax(predictions[0])]
grads = gtape.gradient(loss, conv_output)
pooled_grads = K.mean(grads, axis=(0, 1, 2))
heatmap = tf.reduce_mean(tf.multiply(pooled_grads, conv_output), axis=-1)
heatmap = np.maximum(heatmap, 0)
max_heat = np.max(heatmap)
if max_heat == 0:
max_heat = 1e-10
heatmap /= max_heat
print(heatmap.shape)
return heatmap
def getPatches(folder, isTraining, p):
patches = []
i_i = []
i_j = []
mean = 0
var = 10
sigma = var ** 0.5
act_size = 2240
gaussian = np.random.normal(mean, sigma, (act_size, act_size))
doChunking = False
index = 0
i2 = 1
for filename in os.listdir(folder):
if isTraining == True:
print(str(i2) + ", chunking training image '" + filename + "'")
else:
print(str(i2) + ", chunking test image '" + filename + "'")
i2 = i2 + 1
image = Image.open(folder + filename)
data = np.array(image)
if isTraining == True:
# adding Gaussian noise
if len(data.shape) == 2:
data = data + gaussian
else:
data[:, :, 0] = data[:, :, 0] + gaussian
data[:, :, 1] = data[:, :, 1] + gaussian
data[:, :, 2] = data[:, :, 2] + gaussian
data = data.astype('float32') / 255.
row, col,ch = data.shape
for i in range(row):
for j in range(col):
if (i+1)*p <= row and (j+1)*p <= col:
patch = data[(i)*p:(i+1)*p,(j)*p:(j+1)*p,:]
patches.append(patch)
i_i.append(i)
i_j.append(j)
if doChunking == True:
if index >= 10:
break
else:
index = index + 1
patches = np.array(patches)
return i_i, i_j, patches
def transferWeights(model1, model2):
for i in range(1,len(model1.layers)):
model2.layers[i].set_weights(model1.layers[i].get_weights())
return model2
autoencoder = getAssembledModel(p)
# ONE-TIME TRAINING
if doTraining == True:
_, _,x_train = getPatches(tr_folder, True, p)
_, _,x_valid = getPatches(te_folders[0], False, p) # using test dataset-1 for validation as well, it is user configurable
print(x_train.shape)
print(x_valid.shape)
autoencoder.fit(x_train, x_train,
epochs=200,
batch_size=16,
shuffle=True,
validation_data=(x_valid, x_valid))
autoencoder.save("model.tf")
else:
model1 = tf.keras.models.load_model("model.tf", compile=False)
autoencoder = transferWeights(model1, autoencoder)
# TESTING
for d in range(numDatasets):
i_i, i_j, x_test = getPatches(te_folders[d], False, p)
print(x_test.shape)
print("**********************Reconstructing Patches*******************")
decoded_imgs = []
l1, r1,c1,ch1 = x_test.shape
for i in range(l1):
decoded_imgs.append(autoencoder.predict(x_test[i].reshape(1, p, p, 3)))
decoded_imgs = np.array(decoded_imgs)
t, r, c, ch = x_test.shape
d_imgs = []
d_test = []
heatmaps = []
i = 0
j = 0
img = np.zeros((act_size, act_size, 3), dtype='float32')
img2 = np.zeros((act_size, act_size, 3), dtype='float32')
img3 = np.zeros((act_size, act_size, 3), dtype='float32')
print(decoded_imgs.shape)
row, col,ch = img.shape
print("**********************Stitching Images*******************")
for k in range(len(i_i)):
patch = decoded_imgs[k].reshape(p, p, 3);
i = i_i[k]
j = i_j[k]
img[(i)*p:(i+1)*p,(j)*p:(j+1)*p,:] = patch
# heatmap = getHeatMap(patch, keras.Model(input_img, encoded))
img3[i*p:(i+1)*p,j*p:(j+1)*p,:] = x_test[k].reshape(p, p, 3)-patch
patch = x_test[k].reshape(p, p, 3);
img2[i*p:(i+1)*p,j*p:(j+1)*p,:] = patch
if i == 9 and j == 9:
d_imgs.append(img)
img = np.zeros((act_size, act_size, 3), dtype='float32')
d_test.append(img2)
img2 = np.zeros((act_size, act_size, 3), dtype='float32')
heatmaps.append(img3)
img3 = np.zeros((act_size, act_size, 3), dtype='float32')
d_test = np.array(d_test)
d_imgs = np.array(d_imgs)
heatmaps = np.array(heatmaps)
print(d_imgs.shape)
print(d_test.shape)
t, r, c, ch = d_imgs.shape
m = d
folder = res_fake[m]
print("**********************Saving reconstructed images at " + folder + "*******************")
for i in range(t):
A = (255 * d_imgs[i].reshape(act_size, act_size, 3)).astype(np.uint8)
im = Image.fromarray(A)
newsize = (224, 224)
#im = im.resize(newsize)
#print(im.size)
# im.show()
im.save(folder + "Image" + str(i) + ".jpg")
t, r, c, ch = d_test.shape
folder = res_real[m]
print("**********************Saving real images at " + folder + "*******************")
for i in range(t):
A = (255 * d_test[i].reshape(act_size, act_size, 3)).astype(np.uint8)
im = Image.fromarray(A)
newsize = (224, 224)
# im = im.resize(newsize)
im.save(folder + "Image" + str(i) + ".jpg")
folder = res_disp[m]
print("**********************Saving disparity maps at " + folder + "*******************")
for i in range(t):
A = (255 * heatmaps[i].reshape(act_size, act_size, 3)).astype(np.uint8)
print("MSE: " + str(255*np.mean(heatmaps[i] * heatmaps[i])))
im = Image.fromarray(A)
newsize = (224, 224)
# im = im.resize(newsize)
im.save(folder + "Image" + str(i) + ".jpg")
# [Optional] Uncomment these line to plot results
# n = 9
# plt.figure(figsize=(20, 4))
# for i in range(1, n + 1):
# # Display original
# ax = plt.subplot(2, n, i)
# plt.gray()
# plt.imshow(d_test[i].reshape(act_size, act_size, 3))
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
# Display reconstruction
# ax = plt.subplot(2, n, i + n)
# plt.gray()
# plt.imshow(d_imgs[i].reshape(act_size, act_size, 3))
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
# plt.show()
| StarcoderdataPython |
4908667 | import psycopg2
import testing.postgresql
import pytest
import pandas as pd
from datetime import timedelta
import src.ooni.utils as ooni_utils
import src.ooni.types as ooni_types
import src.shared.types as shared_types
import src.shared.utils as shared_utils
# TODO make DRY with other test - test utils?
@pytest.fixture(scope='function')
def postgresdb(request):
'''Postgres testing mock'''
postgresql = testing.postgresql.Postgresql()
conn = psycopg2.connect(**postgresql.dsn())
cur = conn.cursor()
ooni_types.create_tables(cur, conn)
def teardown():
postgresql.stop()
request.addfinalizer(teardown)
return (cur, conn)
# def my_db_enabled_test (postgresdb):
# return
# def test_query_ooni():
# ms = ooni_utils.query_recent_measurements(max_queries=1)
# assert(len(ms) > 1)
# # should not error
# ooni_utils.get_blocking_type(ms[0])
# ms = ooni_utils.query_measurements_after(datetime.now(), max_queries=1)
def test_get_hostname():
assert(ooni_utils.get_hostname('http://daylight.berkeley.edu/cool-article') == 'daylight.berkeley.edu')
# def test_fetch_ip():
# hn = ooni_utils.get_hostname('https://berkeley.edu')
# maybe_ip = ooni_utils.fetch_ip_from_hostname(hn)
# # should not error
# IP(maybe_ip)
def test_ip_to_alpha2():
US_ip = '172.16.17.32'
NL_ip = '172.16.17.32'
alpha2 = ooni_utils.ip_to_alpha2(US_ip)
assert(str(alpha2) == 'US')
alpha2 = ooni_utils.ip_to_alpha2(NL_ip)
assert(str(alpha2) == 'NL')
def test_IPHostnameMapping():
my_ip = '172.16.58.3'
t = shared_utils.now()
# no error here
ooni_types.IPHostnameMapping(my_ip, 'wikipedia.org', t)
with pytest.raises(Exception):
# error here
ooni_types.IPHostnameMapping('xxx.xxx.xxx', 'wikipedia.org', t)
def test_retrieve_ip(postgresdb):
'''
lookup_ip when we know the result is n the cache.
'''
cur, conn = postgresdb
US_ip = '172.16.17.32'
NL_ip = '172.16.17.32'
t = shared_utils.now()
ooni_types.IPHostnameMapping(NL_ip, 'website.nl', t).write_to_db(cur, conn)
ooni_types.IPHostnameMapping(US_ip, 'website.us', t).write_to_db(cur, conn)
ip = ooni_utils.retrieve_ip(cur, 'website.nl')[1]
assert(ip == NL_ip)
ip = ooni_utils.retrieve_ip(cur, 'website.us')[1]
assert(ip == US_ip)
def test_cache_expiry(postgresdb):
# lookup ip when cache IS NOT VALID
cur, conn = postgresdb
my_ip = '162.00.00.01'
t = shared_utils.now() - timedelta(days=3)
mapping = ooni_types.IPHostnameMapping(my_ip, 'wikipedia.org', t)
mapping.write_to_db(cur, conn)
ip = ooni_utils.retrieve_cached_ip(cur, 'wikipedia.org')
# should fetch the real address and deliver me something other than my fake one.
assert(ip is None)
def test_url_to_alpha2(postgresdb):
# lookup ip when cache IS NOT VALID
cur, conn = postgresdb
# make a DB reading
US_ip = '172.16.58.3'
t = shared_utils.now()
mapping = ooni_types.IPHostnameMapping(US_ip, 'wikipedia.org', t)
mapping.write_to_db(cur, conn)
NL_ip = '172.16.17.32'
mapping = ooni_types.IPHostnameMapping(NL_ip, 'government.nl', t)
mapping.write_to_db(cur, conn)
# look it up
alpha2 = ooni_utils.url_to_alpha2(cur, conn, 'https://wikipedia.org/')
assert(str(alpha2) == 'US')
alpha2 = ooni_utils.url_to_alpha2(cur, conn, 'https://government.nl/')
assert(str(alpha2) == 'NL')
def test_tld_juris():
juris = ooni_utils.get_tld_jurisdiction('http://mycool.com.br')
assert(str(juris) == 'BR')
juris = ooni_utils.get_tld_jurisdiction('https://1.1.1.1/dns-query?dns=q80BAAABAAAAAAAAA3d3dwdleGFtcGxlA2NvbQAAAQAB')
assert(juris is None)
# tricky one! internationalized URL
juris = ooni_utils.get_tld_jurisdiction('http://xn--80aaifmgl1achx.xn--p1ai/')
assert(str(juris) == 'RU')
juris = ooni_utils.get_tld_jurisdiction('http://www.sansat.net:25461')
assert(str(juris) == 'US')
def test_is_in_future():
future = shared_utils.now() + timedelta(days=5)
assert(shared_utils.is_in_future(future) is True)
past = shared_utils.now() - timedelta(days=5)
assert(shared_utils.is_in_future(past) is False)
def test_get_latest_reading_time(postgresdb):
cur, conn = postgresdb
my_time = pd.Timestamp('2000-01-01 21:41:37+00:00')
dummy = ooni_types.OONIWebConnectivityTest(
'example',
shared_types.Alpha2('US'),
'example',
False,
False,
'example',
shared_types.Alpha2('US'),
shared_types.Alpha2('US'),
my_time
)
dummy.write_to_db(cur, conn)
most_recent_reading = ooni_utils.get_latest_reading_time(cur)
assert(most_recent_reading == my_time)
| StarcoderdataPython |
3354133 | <gh_stars>0
# Merge subchunks into single data.
from datetime import datetime
from pathlib import Path
import pandas as pd
import os
import glob
from tqdm import tqdm
import seaborn as sns
import matplotlib.pyplot as plt
from config import ELASPIC_RESULTS_FOLDER_PATH as ERFP
import logging
from log_script import ColorHandler
pd.set_option('display.max_columns', 10)
pd.set_option('display.width', 1000)
log = logging.Logger("debug_runner", level=logging.DEBUG)
log.addHandler(ColorHandler())
class ResultsMerger:
"""
There might be still duplicated entries once it is read by pandas.
"""
ELASPIC_RESULTS_FOLDER_PATH = os.path.join("..", ERFP)
def __init__(self, tcga):
log.info(f" --- Starting ResultsMerger for {tcga}.. --- ")
self.tcga = tcga
self.data_concated = self.concatenate_results()
self.type_counts = self.get_type_counts()
self.plot_type_distribution(self.data_concated)
core_data, interface_data = self.separate_core_interface()
self.core_data = core_data
self.interface_data = interface_data
# Handle core mutations
self.core_data_dropped = self.drop_duplicates(self.core_data)
# Handle interface mutations
self.interface_data_no_self_interactions = self.drop_self_interactions(self.interface_data)
self.interface_data_dropped = self.drop_duplicates(self.interface_data_no_self_interactions)
self.export(self.core_data_dropped, f"{self.tcga}_Core")
self.export(self.interface_data_dropped, f"{self.tcga}_Interface")
log.info("Results are merged and exported successfully.\n")
def concatenate_results(self):
"""
Concatenates result text files into single dataframe for given TCGA type.
"""
log.info("Concatenating the results ..")
result_dataframes = []
chunks_path = os.path.join(self.ELASPIC_RESULTS_FOLDER_PATH, self.tcga)
chunks = os.listdir(chunks_path)
num_data_combined = 0
log.debug("Reading the files ..")
for chunk in tqdm(chunks):
subchunks_path = os.path.join(self.ELASPIC_RESULTS_FOLDER_PATH, self.tcga, chunk, Path('*'))
for subchunk_path in glob.glob(subchunks_path):
# log.debug(f"reading {subchunk_path} ..")
subchunk_data = pd.read_table(subchunk_path, low_memory=False)
result_dataframes.append(subchunk_data)
num_data_combined += 1
log.debug('{} files are loaded.'.format(num_data_combined))
log.debug("Concatenating dataframes into single dataframe ..")
concated_data = pd.concat(result_dataframes).reset_index(drop=True)
# Drop entries where status is not 'done' (either 'err' or 'running'), i.e. keep only "done" entries.
concated_data = concated_data[concated_data["Status"] == "done"]
log.info("Datasets are concatenated.")
log.debug(f"concated_data.shape: {concated_data.shape}")
log.debug(f"First five rows in concated_data: \n{concated_data.head()}")
log.debug(f"Unique values in concated_data['Type']: {list(concated_data['Type'].unique())}")
return concated_data
def get_type_counts(self):
type_counts = pd.DataFrame({
f"{self.tcga}": self.data_concated["Type"].value_counts()
})
log.info(f"type_counts: \n{type_counts}")
return type_counts
@staticmethod
def get_entries_core(data):
core_data = data[data["Type"] == 'core'].reset_index(drop=True)
return core_data
@staticmethod
def get_entries_interface(data):
interface_data = data[data["Type"] == 'interface'].reset_index(drop=True)
return interface_data
def separate_core_interface(self):
"""Returns Core Data and Interface Data"""
log.debug("Separating Core and Interface entries ..")
core_data = self.get_entries_core(self.data_concated)
interface_data = self.get_entries_interface(self.data_concated)
log.debug(f"Core data dimensions: {core_data.shape}")
log.debug(
"Core data preview: \n{}\n".format(
core_data[["UniProt_ID", "Mutation", "Interactor_UniProt_ID"]].head(3)
)
)
log.debug(f"Interface data dimensions: {interface_data.shape}")
log.debug(
"Interface data preview: \n{}\n".format(
interface_data[["UniProt_ID", "Mutation", "Interactor_UniProt_ID"]].head(3)
)
)
return core_data, interface_data
@staticmethod
def drop_self_interactions(data):
"""
Entries whose UniProt_ID protein is the same (or isoform) as Interactor_UniProt_ID will be removed.
"""
log.debug("Dropping self interactions ..")
# Take the entries where UniProt_ID different than Interactor_UniProt_ID (dropping self and isoform)
data_dropped = data[
data["UniProt_ID"].apply(lambda x: x.split('-')[0]) != data["Interactor_UniProt_ID"].apply(lambda x: x.split('-')[0])
]
# Reset index of the dataframe to avoid any possible errors
data_dropped = data_dropped.reset_index(drop=True)
return data_dropped
@staticmethod
def drop_duplicates(data):
"""
Remove duplicated entries in the given dataframe.
"""
log.debug("Dropping duplicated entries ..")
# Size of dataframe before dropping duplicated entries.
log.debug(f"Size of dataframe before dropping duplicated entries: {data.shape}")
# Drop duplicates by keeping the 'first' one.
data = data.drop_duplicates(keep="first")
# Size of dataframe after dropping duplicated entries.
log.debug(f"Size of dataframe after dropping duplicated entries: {data.shape}")
# Reset index of the dataframe to avoid any possible errors
data.reset_index(drop=True, inplace=True)
return data
def export(self, data, data_name):
current_date = datetime.today().strftime('%Y-%m-%d')
filename = f"{data_name}_{current_date}.txt"
folder_path = os.path.join(self.ELASPIC_RESULTS_FOLDER_PATH, "Merged_Results")
Path(folder_path).mkdir(parents=True, exist_ok=True)
filepath = os.path.join(folder_path, filename)
if os.path.isfile(filepath):
raise FileExistsError("You have already exported predictions! Clear the folder.")
data.to_csv(filepath, sep='\t', index=False)
log.info(f"Data {filename} is exported in directory {filepath}.")
def plot_type_distribution(self, data):
plt.figure(figsize=(7, 5))
sns.set(style="white", font_scale=1.15) # white, dark, whitegrid, darkgrid, ticks
ax = sns.barplot(
x=data["Type"].value_counts().index,
y=data["Type"].value_counts(),
palette="vlag_r"
)
ax.set_title('Distribution of `Core` vs `Interface`\nin {}'.format(self.tcga)) # ch:s=-.2,r=.6, ocean
ax.set_xlabel('Type', fontsize=14)
ax.set_ylabel('Count', fontsize=14)
plt.show()
# 1. BRCA
# ResultsMerger(tcga="BRCA")
# 2. OV
# ResultsMerger(tcga="OV")
# 3. ESCA
# ResultsMerger(tcga="ESCA")
# 4. HNSC
# ResultsMerger(tcga="HNSC")
# 5. GBM
# ResultsMerger(tcga="GBM")
# # 6. BLCA
# ResultsMerger(tcga="BLCA")
# 7. COAD
# ResultsMerger(tcga="COAD")
| StarcoderdataPython |
12811541 | import code
import sys
from cleo import Command
BANNER = """Masonite Python {} Console
This interactive console has the following things imported:
container as 'app'
Type `exit()` to exit."""
class TinkerCommand(Command):
"""
Run a python shell with the container pre-loaded.
tinker
"""
def handle(self):
from wsgi import container
version = "{}.{}.{}".format(
sys.version_info.major,
sys.version_info.minor,
sys.version_info.micro
)
banner = BANNER.format(version)
code.interact(banner=banner, local={"app": container})
| StarcoderdataPython |
5110388 | <reponame>kolbt/whingdingdilly
'''
# This is an 80 character line #
PURPOSE: The intent of this file is to get out a few basic values as text files
File : Column 1 Column 2 Column 3 Column 4
gas_pa#_pb#_xa#.txt : time gas_A gas_B gas_total
dense_pa#_pb#_xa#.txt : time dense_A dense_B dense_total
lclust_pa#_pb#_xa#.txt : time l_clust
Designations Explained:
gas_A : number of A-type particles in gas phase
gas_B : number of B-type particles in gas phase
gas_total : total number of gaseous partilces
dense_A : number of A-type particles in dense phase
dense_B : number of B-type particles in dense phase
dense_total : total number of dense phase particles
l_clust : largest individual cluster
'''
import sys
pe_a = int(sys.argv[1]) # activity A
pe_b = int(sys.argv[2]) # activity B
part_perc_a = int(sys.argv[3]) # percentage A particles
part_frac_a = float(part_perc_a) / 100.0 # fraction A particles
hoomd_path = str(sys.argv[4]) # local path to hoomd-blue
gsd_path = str(sys.argv[5]) # local path to gsd
sys.path.append(hoomd_path) # ensure hoomd is in your python path
sys.path.append(gsd_path) # ensure gsd is in your python path
import hoomd
from hoomd import md
from hoomd import deprecated
import gsd
from gsd import hoomd
from gsd import pygsd
import freud
from freud import parallel
from freud import box
from freud import density
from freud import cluster
import numpy as np
from mypy import load_bar
def computeR(part1, part2):
return np.sqrt(((part2[0]-part1[0])**2)+((part2[1]-part1[1])**2))
# File to read from
in_file = "pa"+str(pe_a)+\
"_pb"+str(pe_b)+\
"_xa"+str(part_perc_a)+\
".gsd"
# File to write all data to
all_file = "all_pa"+str(pe_a)+\
"_pb"+str(pe_b)+\
"_xa"+str(part_perc_a)+\
".txt"
f = hoomd.open(name=in_file, mode='rb') # open gsd file with hoomd
dumps = f.__len__() # get number of timesteps dumped
start = 0 # gives first frame to read
end = dumps # gives last frame to read
end = 10
positions = np.zeros((end), dtype=np.ndarray) # array of positions
types = np.zeros((end), dtype=np.ndarray) # particle types
box_data = np.zeros((1), dtype=np.ndarray) # box dimensions
timesteps = np.zeros((end), dtype=np.float64) # timesteps
# Get relevant data from .gsd file
with hoomd.open(name=in_file, mode='rb') as t:
snap = t[0]
box_data = snap.configuration.box
for iii in range(start, end):
snap = t[iii] # snapshot of frame
types[iii] = snap.particles.typeid # get types
positions[iii] = snap.particles.position # get positions
timesteps[iii] = snap.configuration.step # get timestep
timesteps -= timesteps[0] # get rid of brownian run time
# Get number of each type of particle
part_num = len(types[0])
part_A = int(part_num * part_frac_a)
part_B = part_num - part_A
# Feed data into freud analysis software
l_box = box_data[0]
a_box = l_box * l_box
f_box = box.Box(Lx = l_box, Ly = l_box, is2D = True) # make freud box
my_clust = cluster.Cluster(box = f_box, # init cluster class
rcut = 1.0) # distance to search
c_props = cluster.ClusterProperties(box = f_box) # compute properties
# Parameters for sorting dense from dilute
min_size = 1000 # minimum cluster size
dist_min = 2.0 # bin density for avg d.p. density
f = open(all_file, 'w') # write file headings
f.write('Timestep'.center(10) + ' ' +\
'Gas_A'.center(10) + ' ' +\
'Gas_B'.center(10) + ' ' +\
'Gas_tot'.center(10) + ' ' +\
'Dense_A'.center(10) + ' ' +\
'Dense_B'.center(10) + ' ' +\
'Dense_tot'.center(10) + ' ' +\
'Lg_clust'.center(10) + ' ' +\
'DP_density'.center(10) + ' ' +\
'GP_density'.center(10) + '\n')
f.close()
# Create mesh
float_side = box_data[0] / 2.0
side = float((int(box_data[0])+1)) / 2
box_width = 2 # bin width
diameter = 1.0 # sigma
while side % box_width != 0: # must be divisible
side += 1 # make divisible by bin
spacer = int(side * 2 / (box_width * diameter)) # number of bins
mesh = np.zeros((spacer, spacer), dtype = np.ndarray) # array of each bin
reset_mesh = np.zeros_like(mesh) # zero out mesh
occ = 100 # max occupancy of bin
test_occ = np.zeros((occ, 4)) # occupation test index
for j in range(0, spacer):
for k in range(0, spacer):
mesh[j][k] = np.zeros_like(test_occ)
reset_mesh[j][k] = np.zeros_like(test_occ)
load_bar.printLoadBar(0, end-start, prefix = "Progress: ", suffix = "Complete")
for iii in range(start, end):
# Get data from arrays
pos = positions[iii]
typ = types[iii]
tst = timesteps[iii]
# Run freud computations
my_clust.computeClusters(pos) # feed in position
ids = my_clust.getClusterIdx() # get id of each cluster
c_props.computeProperties(pos, ids) # find cluster properties
clust_size = c_props.getClusterSizes() # find cluster sizes
# Querry array, that tells whether cluster ID is of sufficient size
q_clust = np.zeros((len(clust_size)), dtype = np.int)
clust_num = 0 # number of clusters
l_clust = 0 # largest cluster
for jjj in range(0, len(clust_size)):
if clust_size[jjj] > min_size:
q_clust[jjj] = 1
clust_num += 1
if clust_size[jjj] > l_clust:
l_clust = clust_size[jjj]
# Values to write out after computations are complete
dense_num = 0 # number of particles in dense phase
dense_A = 0 # number of A-particles in dense phase
dense_B = 0 # number of B-particles in dense phase
gas_num = 0 # number of particles in gas phase
gas_A = 0 # number of A-particles in gas phase
gas_B = 0 # number of B-particles in gas phase
dp_density = 0 # density of dense phase
gp_density = 0 # density of gas phase
for jjj in range(0, part_num):
# get the index of the mesh the particle belongs in
loc_x = int((pos[iii][0] + float_side) / (box_width * diameter))
loc_y = int((pos[iii][1] + float_side) / (box_width * diameter))
# place the particle in the first unoccupied space in this quadrant list
for s in range(1, occ): # index 0 holds number in bin
if mesh[loc_x][loc_y][s][3] == 0: # test occupancy
mesh[loc_x][loc_y][s][0] = pos[iii][0] # x coord
mesh[loc_x][loc_y][s][1] = pos[iii][1] # y coord
mesh[loc_x][loc_y][s][2] = iii # particle id
mesh[loc_x][loc_y][s][3] = 1 # occupied flag
break
if q_clust[ids[jjj]] == 1: # it's in the dense phase
dense_num += 1
if typ[jjj] == 0:
dense_A += 1
else:
dense_B += 1
else: # it's in the gas phase
gas_num += 1
if typ[jjj] == 0:
gas_A += 1
else:
gas_B += 1
for jjj in range(0, part_num):
if q_clust[ids[jjj]] == 1: # is in dense phase
# indices of particle's bin
loc_x = int((pos[iii][0] + float_side) / (box_width * diameter))
loc_y = int((pos[iii][1] + float_side) / (box_width * diameter))
# indices of surrounding bins
lft = loc_x - 1
rgt = loc_x + 1
bot = loc_y - 1
top = loc_y + 1
# Compute distance between particles
for lll in range(lft, rgt + 1): # left - right bins
for mmm in range(bot, top + 1): # bottom - top bins
if lll >= spacer:
lll -= spacer
if mmm >= spacer:
mmm -= spacer
for nnn in range(1, occ):
if mesh[lll][mmm][nnn][3] == 0:
break
else:
r = computeR(mesh[lll][mmm][nnn], pos[jjj])
if r < dist_min:
dp_density += 1
print(dp_density)
print(dense_num)
dp_density /= float(dense_num) # avg number in each bin
dp_density /= (np.pi * ((dist_min * diameter)**2)) # avg cluster density
a_clust = 0.0
if dp_density != 0:
a_clust = float(dense_num) / float(dp_density) # area of cluster
a_gas = a_box - a_clust # area of gas
gp_density = gas_num / a_gas # number density in gas
# Values have been set, write to text files
f = open(all_file, 'a')
f.write(('{0:.2f}'.format(tst*0.000001)).center(10) + ' ' +\
str(gas_A).center(10) + ' ' +\
str(gas_B).center(10) + ' ' +\
str(gas_num).center(10) + ' ' +\
str(dense_A).center(10) + ' ' +\
str(dense_B).center(10) + ' ' +\
str(dense_num).center(10) + ' ' +\
str(l_clust).center(10) + ' ' +\
'{0:.2f}'.format(dp_density).center(10) + ' ' +\
'{0:.2f}'.format(gp_density).center(10) + '\n')
f.close()
mesh = reset_mesh
load_bar.printLoadBar(iii, end-start,
prefix = "Progress: ", suffix = "Complete")
| StarcoderdataPython |
8181155 | #-*- coding: utf-8 -*-
from flask.ext import restful
class History(restful.Resource):
def get(self):
return {'open': 30, 'close': 40}
| StarcoderdataPython |
261665 | from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from django.core.paginator import Page
def list_inline_buttons(list_buttons):
markup = InlineKeyboardMarkup()
for name, callback_data in list_buttons:
button = InlineKeyboardButton(name, callback_data=callback_data)
markup.add(button)
return markup
def inline_carousel(object_id, count_objects,
callback_prefix='', callback_back_button=''):
"""
Будет генерировать клавиатуру для карусели
На вход получает id нового объекта,
массив всех объектов.
Возвращает клавиатуру, с кнопками
<- | номер_страницы | ->
назад
"""
markup = InlineKeyboardMarkup()
if object_id > 0:
callback_prev = f'{callback_prefix}_{object_id - 1}'
button_prev = InlineKeyboardButton('<-', callback_data=callback_prev)
markup.insert(button_prev)
button_page = InlineKeyboardButton(str(object_id + 1), callback_data='EMPTY_CALLBACK')
markup.insert(button_page)
if object_id + 1 < count_objects:
callback_next = f'{callback_prefix}_{object_id + 1}'
button_next = InlineKeyboardButton('->', callback_data=callback_next)
markup.insert(button_next)
back_button = InlineKeyboardButton('Назад', callback_data=callback_back_button)
markup.add(back_button)
return markup
def get_empty_markup(**kwargs):
return InlineKeyboardMarkup(**kwargs)
def inline_button(text, callback_data, markup=None):
if not markup:
markup = InlineKeyboardMarkup()
button = InlineKeyboardButton(text, callback_data=callback_data)
markup.add(button)
return markup
def inline_carousel_by_paginator(
markup: InlineKeyboardMarkup, page: Page,
callback_prefix: str, callback_back_button: str):
buttons = []
if page.has_previous():
callback_prev = callback_prefix + str(page.previous_page_number())
button_prev = InlineKeyboardButton('<-', callback_data=callback_prev)
buttons.append(button_prev)
button_page = InlineKeyboardButton(str(page.number), callback_data='EMPTY_CALLBACK')
buttons.append(button_page)
if page.has_next():
callback_next = callback_prefix + str(page.next_page_number())
button_next = InlineKeyboardButton('->', callback_data=callback_next)
buttons.append(button_next)
markup.row(*buttons)
back_button = InlineKeyboardButton('Назад', callback_data=callback_back_button)
markup.add(back_button)
return markup
| StarcoderdataPython |
1680615 | <gh_stars>1-10
# Generated by Django 3.1.2 on 2021-06-09 05:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0047_merge_20210609_0534'),
('core', '0047_merge_20210609_0531'),
]
operations = [
]
| StarcoderdataPython |
9653777 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""Benchmark script for ImageNet models on mobile GPU.
see README.md for the usage and results of this script.
"""
import argparse
import numpy as np
import tvm
from tvm.contrib.util import tempdir
import tvm.contrib.graph_runtime as runtime
from tvm import relay
from util import get_network, print_progress
def evaluate_network(network, target, target_host, dtype, repeat):
# connect to remote device
tracker = tvm.rpc.connect_tracker(args.host, args.port)
remote = tracker.request(args.rpc_key)
print_progress(network)
net, params, input_shape, output_shape = get_network(network, batch_size=1, dtype=dtype)
print_progress("%-20s building..." % network)
with relay.build_config(opt_level=3):
graph, lib, params = relay.build(
net, target=target, target_host=target_host, params=params)
tmp = tempdir()
if 'android' in str(target) or 'android' in str(target_host):
from tvm.contrib import ndk
filename = "%s.so" % network
lib.export_library(tmp.relpath(filename), ndk.create_shared)
else:
filename = "%s.tar" % network
lib.export_library(tmp.relpath(filename))
# upload library and params
print_progress("%-20s uploading..." % network)
ctx = remote.context(str(target), 0)
remote.upload(tmp.relpath(filename))
rlib = remote.load_module(filename)
module = runtime.create(graph, rlib, ctx)
data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))
module.set_input('data', data_tvm)
module.set_input(**params)
# evaluate
print_progress("%-20s evaluating..." % network)
ftimer = module.module.time_evaluator("run", ctx, number=1, repeat=repeat)
prof_res = np.array(ftimer().results) * 1000 # multiply 1000 for converting to millisecond
print("%-20s %-19s (%s)" % (network, "%.2f ms" % np.mean(prof_res), "%.2f ms" % np.std(prof_res)))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--network", type=str, choices=
['resnet-18', 'resnet-34', 'resnet-50',
'vgg-16', 'vgg-19', 'densenet-121', 'inception_v3',
'mobilenet', 'squeezenet_v1.0', 'squeezenet_v1.1'],
help='The name of neural network')
parser.add_argument("--model", type=str, choices=
['rk3399'], default='rk3399',
help="The model of the test device. If your device is not listed in "
"the choices list, pick the most similar one as argument.")
parser.add_argument("--host", type=str, default='localhost')
parser.add_argument("--port", type=int, default=9190)
parser.add_argument("--rpc-key", type=str, required=True)
parser.add_argument("--repeat", type=int, default=30)
parser.add_argument("--dtype", type=str, default='float32')
args = parser.parse_args()
if args.network is None:
networks = ['squeezenet_v1.1', 'mobilenet', 'resnet-18', 'vgg-16']
else:
networks = [args.network]
target = tvm.target.mali(model=args.model)
target_host = tvm.target.arm_cpu(model=args.model)
print("--------------------------------------------------")
print("%-20s %-20s" % ("Network Name", "Mean Inference Time (std dev)"))
print("--------------------------------------------------")
for network in networks:
evaluate_network(network, target, target_host, args.dtype, args.repeat)
| StarcoderdataPython |
1707526 | """
allow a user to enter URL's and receive information on the responsivness \
of that URL
"""
import sys
import urllib2
import json
import re
from constants import URL_REGEX
from constants import NEW_LINE
URL_FORMAT_PATTERN = re.compile(URL_REGEX)
def make_http_url_requests():
"""
for an entered URL, attempt to make a request and parse the response
keep looping until no inout is received
"""
try:
write_out("enter URL's to get info, to quit press return")
responses = {}
while True:
url_to_use = sys.stdin.readline()
if url_to_use == NEW_LINE or not url_to_use:
# no input data recieved from the user, we should exit
write_out("program exiting")
if responses:
responses_in_program = get_json_dump(responses)
sorted(responses_in_program)
write_out("count of responses by Status_code")
write_out(responses_in_program)
sys.exit(0)
# remove trailing newline character from user input data
url_to_use = url_to_use.rstrip()
write_out("{}URL entered: '{}'".format(NEW_LINE, url_to_use))
checked_data = get_checked_url(url_to_use)
# if the url is valid, we get no error data back
if not checked_data:
# valid URL; proceed to make request
checked_data = get_http_request_response_data(url_to_use)
# update the responses so far per status code
if checked_data.has_key('Status_code'):
update_responses(responses, checked_data['Status_code'])
json_data = get_json_dump(checked_data)
write_out(json_data)
except KeyboardInterrupt:
# we want to continue running our program
# we control how to end the program
pass
def get_checked_url(url_to_use):
"""
check the url is valid before makng any request
return error data if the URL is in fact malformed
"""
if not URL_FORMAT_PATTERN.match(url_to_use):
write_out("Url '{}', is invalid".format(url_to_use), False)
return get_error_data(url_to_use, "Invalid URL", True)
def get_json_dump(data):
"""
get dump of data as JSON
"""
return json.dumps(data, indent=4, separators=(',', ': '))
def update_responses(responses, data_key):
"""
update the statuses response number of URL request
"""
if responses.has_key(data_key):
responses[data_key] += 1
else:
responses[data_key] = 1
def write_out(some_string, is_std_out=True):
"""
helper function to write to std[out|err]
"""
if some_string:
formatted_string = "{}{}".format(some_string, NEW_LINE)
if not is_std_out:
sys.stderr.write(formatted_string)
else:
sys.stdout.write(formatted_string)
def get_error_data(url_used, message, is_error=False):
"""
get an error object if request returns an error response
"""
data = {}
data['Url'] = url_used
data_key = 'Error' if is_error else 'Status_code'
data[data_key] = message
return data
def get_response_content(response, response_info):
"""
get content from the request response
"""
data = {}
data['Url'] = response.geturl()
data['Status_code'] = response.getcode()
data['Content_length'] = response_info.getheader('content-length')
data['Date'] = response_info.getheader('Date')
return data
def get_http_request_response_data(url_to_use):
"""
get http request response data
"""
response = None
try:
request = urllib2.Request(url_to_use)
response = urllib2.urlopen(request, timeout=10)
response_info = response.info()
return get_response_content(response, response_info)
except Exception as exception:
return get_handled_exception_response_data(url_to_use, exception)
finally:
if response:
response.close()
def get_handled_exception_response_data(url_to_use, exception):
"""
handle specific HTTP, URL & common exceptions and return some data
"""
if isinstance(exception, urllib2.HTTPError):
write_out(
"Unable to reach '{}': {} returned"
.format(url_to_use, exception.code), False)
return get_error_data(url_to_use, exception.code)
elif isinstance(exception, urllib2.URLError):
write_out(
"Error attempting to reach '{}': {}".format(url_to_use,
str(exception.reason)), False)
return get_error_data(url_to_use, "Invalid URL", True)
else:
write_out(
"Error executing request to '{}': {}".format(url_to_use,
exception.message), False)
return get_error_data(url_to_use, exception.message, True)
if __name__ == '__main__':
"""
program entry-point
"""
make_http_url_requests()
| StarcoderdataPython |
3274551 | from abc import ABC
import torch_geometric as pyg
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch_geometric.nn as gnn
import torch_geometric.data as tgd
from torch_geometric.data import InMemoryDataset
import torch_geometric.utils as utils
from torch.autograd.function import Function
from scipy.io import loadmat
import numpy as np
class MultiTaskGNN(nn.Module, ABC):
def __init__(self, input_feat_dim, hidden_dim1, hidden_dim2, class_num, dropout):
super(MultiTaskGNN, self).__init__()
self.gc1 = gnn.GCNConv(input_feat_dim, hidden_dim1)
self.gc2 = gnn.GCNConv(hidden_dim1, hidden_dim2)
self.gc3 = gnn.GCNConv(hidden_dim1, hidden_dim2)
self.gc4 = gnn.GCNConv(hidden_dim1, hidden_dim1)
self.seq = nn.Sequential(
nn.ReLU(),
nn.Linear(hidden_dim1, class_num),
)
self.drop = dropout
self.dc = InnerProductDecoder(dropout, act=lambda x: x)
self.binact = StraightBin
def encode(self, features, edge_index, edge_weight=None):
# print(features, edge_index, edge_weight)
hidden1 = self.gc1(features, edge_index, edge_weight)
hidden1 = self.binact.apply(hidden1)
hidden2 = self.gc4(hidden1, edge_index, edge_weight)
return self.gc2(hidden1, edge_index, edge_weight), self.gc3(hidden1, edge_index, edge_weight), \
self.seq(hidden2)
def reparameterize(self, mu, logvar):
if self.training:
std = torch.exp(logvar)
eps = torch.randn_like(std)
return eps.mul(std).add_(mu)
else:
return mu
def forward(self, data: tgd.Data):
mu, logvar, classifer = self.encode(data.x, data.edge_index, data.edge_attr)
z = self.reparameterize(mu, logvar)
return self.dc(z), mu, logvar, classifer
class InnerProductDecoder(nn.Module, ABC):
"""Decoder for using inner product for prediction."""
def __init__(self, dropout, act=torch.sigmoid):
super(InnerProductDecoder, self).__init__()
self.dropout = dropout
self.act = act
def forward(self, z):
z = F.dropout(z, self.dropout, training=self.training)
adj = self.act(torch.mm(z, z.t()))
return adj
class KYXLDataset(InMemoryDataset):
def __init__(self, root, name, transform=None, pre_transform=None):
self.name = name
self.pre_filter = pre_transform
self.transform = transform
super(KYXLDataset, self).__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
def deal_with_mat(self):
"""
将.mat 转化为 [Data]
:return: DataList: [Data]
"""
print("dealing with mat...")
m = loadmat(self.raw_paths[0])
A = utils.from_scipy_sparse_matrix(m['network'])
att = torch.from_numpy(m['attributes'].todense().astype(np.float32))
y = torch.from_numpy(m['labels'].reshape(-1)).to(torch.long)
# 如果y最小值不是0,则认为idx从1开始
if int(torch.min(y)) != 0:
y -= 1
dt = tgd.Data(x=att, edge_index=A[0], edge_weight=A[1].to(torch.float32), y=y)
# print(dt)
return [dt]
@property
def raw_file_names(self):
return [self.name + ".mat"]
@property
def processed_file_names(self):
return [self.name]
def download(self):
# Download to `self.raw_dir`.
pass
def process(self):
# Read data into huge `Data` list.
# data_list = [...]
data_list = self.deal_with_mat()
if self.pre_filter is not None:
data_list = [data for data in data_list if self.pre_filter(data)]
if self.pre_transform is not None:
data_list = [self.pre_transform(data) for data in data_list]
data, slices = self.collate(data_list)
torch.save((data, slices), self.processed_paths[0])
class StraightBin(torch.autograd.Function):
@staticmethod
def forward(ctx, input) -> torch.tensor:
# ctx.save_for_backward(torch.abs(input))
return input.sign()
@staticmethod
def backward(ctx, grad_output):
# result, = ctx.saved_tensors
# return grad_output * result
return grad_output
class BinActive(torch.autograd.Function):
"""
Binarize the input activations and calculate the mean across channel dimension.
"""
@staticmethod
def forward(self, input):
self.save_for_backward(input)
input = input.sign()
return input
@staticmethod
def backward(self, grad_output):
input, = self.saved_tensors
grad_input = grad_output.clone()
grad_input[input.ge(1)] = 0
grad_input[input.le(-1)] = 0
return grad_input
class BinLinear(nn.Module): # change the name of BinConv2d
def __init__(self, input_num, output_num):
super(BinLinear, self).__init__()
self.layer_type = 'BinLinear'
self.alpha = 0.0
self.Linear = nn.Linear(input_num, output_num)
def forward(self, x):
x = self.Linear(x)
x = BinActive.apply(x)
return x
# TODO 完善BinarizeLinear
class BinarizeLinear(nn.Linear):
def __init__(self, input_num, output_num, trans=None):
super(BinarizeLinear, self).__init__(input_num, output_num)
if trans is None:
self.trans = StraightBin
else:
self.trans = trans
def forward(self, input):
w = self.trans.apply(self.weight)
out = F.linear(input, w, self.bias)
return out
class BinarizeFunction(Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input) # save input for backward pass
return torch.sign(input)
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
grad_input = input.clone()
grad_input[torch.abs(input) <= 1.] = 1.
grad_input[torch.abs(input) > 1.] = 0.
grad_input = grad_input * grad_output
return grad_input
class Binarization(nn.Module):
def __init__(self, _min=-1, _max=1, stochastic=False):
super(Binarization, self).__init__()
self.stochastic = stochastic
self.min = _min
self.max = _max
def forward(self, input):
return 0.5 * (BinarizeFunction.apply(input) * (self.max - self.min) + self.min + self.max)
class BinarizedLinear(nn.Linear):
def __init__(self, min_weight=-1, max_weight=1, *kargs, **kwargs):
super(BinarizedLinear, self).__init__(*kargs, **kwargs)
self.binarization = Binarization(_min=min_weight, _max=max_weight)
self.min_weight = min_weight
self.max_weight = max_weight
self.noise_on = False
self.noise_std = 0.2
self.noise = torch.normal(mean=0.0, std=torch.ones_like(self.weight.data) * self.noise_std)
def forward(self, input):
device_num = self.weight.get_device()
device = torch.device("cuda:%d" % device_num)
self.noise = self.noise.to(device)
self.weight.data = nn.functional.hardtanh_(self.weight.data)
if self.noise_on:
out = nn.functional.linear(input, self.binarization(self.weight) + self.noise, bias=self.bias)
else:
out = nn.functional.linear(input, self.binarization(self.weight),
bias=self.bias) # linear layer with binarized weights
return out
def quantize_accumulative_weigths(self):
self.weight.data = self.binarization(self.weight.data)
return
def set_noise_std(self, std=0.2):
self.noise_std = std
self.noise = torch.normal(mean=0.0, std=torch.ones_like(self.weight.data) * self.noise_std)
return
def set_noise(self, noise_on=True):
self.noise_on = noise_on
return
def calc_prop_grad(self, prob_rate=0):
with torch.no_grad():
tmp = torch.abs(self.weight.grad.data).add(1e-20).clone()
self.weight.grad.data.div_(tmp) # norm of grad values
# tmp = F.tanh(prob_rate*tmp).clone()
# tmp.mul_(prob_rate).pow_(2).mul_(-1).exp_().mul_(-1).add_(1) # 1 - exp(-x^2)
# tmp.mul_(prob_rate).mul_(-1).exp_().mul_(-1).add_(1) # 1 - exp(-x)
tmp.mul_(prob_rate).pow_(2).add_(1).reciprocal_().mul_(-1.).add_(1.) # 1 - 1/(1+x^2)
# print(tmp)
tmp = torch.bernoulli(tmp).clone()
self.weight.grad.data.mul_(tmp)
# self.weight.grad.mul_(0)
del tmp
# print(self.weight)
return
def add_bit_error(self, bit_error_rate=0):
probs = torch.ones_like(self.weight.data).mul_(1 - bit_error_rate) # switching probabilities
switching_tensor = torch.bernoulli(probs).mul(2.).add(-1.)
self.weight.data.mul_(switching_tensor)
return
| StarcoderdataPython |
8113695 | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
import os
strings = {
'platformbuildercreation.info': "Note: An environment called '{0}' has been "
"created in order to build your application. "
"This environment will not automatically be "
"terminated and it does have a cost associated "
"with it. Once your platform creation has "
"completed you can terminate this builder "
"environment using the command 'eb terminate'.",
'app.version_message': 'EB CLI',
'base.update_available': 'An update to the EB CLI is available. '
'Run "pip install --upgrade awsebcli" to '
'get the latest version.',
'base.info': 'Welcome to the Elastic Beanstalk Command Line Interface (EB CLI). \n'
'For more information on a specific command, type "eb {cmd} --help".',
'base.epilog': 'To get started type "eb init". Then type "eb create" and "eb open"',
'ebpbase.info': """Welcome to the Elastic Beanstalk Command Line Interface (EB CLI).
The "ebp" command is equivalent to "eb platform". It offers sub-commands for managing platforms.
We recommend that you use "eb platform" instead of "ebp".
For more information on a specific command, enter "eb platform {cmd} --help".
To get started, enter "eb platform init". Then enter "eb platform create".""",
'ebpbase.epilog': 'To get started type "ebp init". Then type "ebp create"',
'init.info': 'Initializes your directory with the EB CLI. Creates the application.',
'init.epilog': 'This command is safe when run in a previously initialized'
' directory. To re-initialize with different options, '
'use the -i option. Note this command cannot change the workspace type'
' of a directory that was already initialized.',
'init.dir.notexists': 'The specified directory {dir} does not exist. '
'Please ensure that you are specifying the proper directory.',
'init.platform_workspace_already_initialized': 'This directory is already initialized with '
'a platform workspace.',
'init.usingenvyamlplatform': 'Using platform specified in env.yaml: {platform}',
'create.info': 'Creates a new environment.',
'create.epilog': 'Type "--vpc." or "--database." for more VPC and database options.',
'create.missinggroup': 'A group name is required when creating multiple environments. '
'Please use the --group option.',
'create.sample_application_download_option': 'Do you want to download the sample '
'application into the current directory?',
'create.downloading_sample_application': 'Downloading sample application to the '
'current directory.',
'create.sample_application_download_complete': 'Download complete.',
'create.download_sample_app_choice_error': "'{choice}' is not a valid choice.",
'events.info': 'Gets recent events.',
'open.info': 'Opens the application URL in a browser.',
'console.info': 'Opens the environment in the AWS Elastic Beanstalk Management Console.',
'clone.info': 'Clones an environment.',
'clone.epilog': 'This command clones your environment and attempts to upgrade the '
'platform to the latest version.\n'
'To create a clone with the same platform version, use the '
'"--exact" option.',
'abort.info': 'Cancels an environment update or deployment.',
'use.info': 'Sets default environment.',
'health.info': 'Shows detailed environment health.',
'deploy.info': 'Deploys your source code to the environment.',
'platformcleanup.info': 'Terminates your platform builder environment.',
'platformset.version': 'Setting workspace platform version to:',
'platformset.newplatform': 'New platform "%s"',
'platformworkspaceshow.info': 'Displays details about platform resources.',
'platformshowversion.info': 'Displays metadata about your current custom platform version.',
'platformbuilderlogs.info': 'Retrieves logs from your platform builder environment.',
'platformlogs.info': 'Retrieves logs for your custom platform build event.',
'platformssh.info': 'SSH into your platform builder environment.',
'platformshowversion.epilog': 'Will display details about the current version if no version '
'is specified.',
'platformworkspacelist.info': 'Lists platform resources.',
'platformlistversions.info': 'Lists versions of the custom platform associated with this '
'workspace.',
'platformcreate.info': 'Creates platform resources.',
'platformcreateversion.info': 'Creates a new custom platform version.',
'platformcreateversion.epilog': 'Creates a new platform version. If no version is '
'specified then it will do a patch-increment based '
'on the most recent platform version. The version '
'and increment options are mutually exclusive.',
'platformcreateiamdescribeerror.info': "Insufficient IAM privileges. Unable to determine "
"if instance profile '{profile_name}' exists, assuming "
"that it exists.",
'platformdelete.info': 'Deletes platform resources.',
'platformdeleteversion.info': 'Deletes a custom platform version.',
'platformdeleteversion.epilog': 'You must explicitly select the version to delete.',
'platformdeletevalidation.error': 'Unable to delete platform version ({0}/{1}) because '
'it is being used by the following environments:\n '
'{2}\n'
'Please terminate or upgrade these environments before '
'trying to delete this platform.',
'platformdelete.events': 'Shows events for the current platform',
'platforminit.info': 'Initializes your directory with the EB CLI to create and manage '
'Platforms.\n'
'(Uninitialized or platform workspace only)',
'platforminit.epilog': 'This command is safe when run in a previously initialized'
' directory. To re-initialize with different options, '
'use the -i option. Note this command cannot change the workspace type'
' of a directory that was already initialized.',
'platforminit.application_workspace_already_initialized': 'This directory is already initialized with '
'an application workspace.',
'platforminit.noinstanceprofile': 'You are creating a workspace without an instance '
'profile. Without an instance profile you cannot create a '
'platform with a customized AMI. Use eb platform init -i '
'or -I to configure your instance profile.',
'platform.info': """Commands for managing platforms.
For more information on a specific command, enter "eb platform {cmd} --help".
To get started enter "eb platform init". Then enter "eb platform create".""",
'platformshow.info': """Shows information about current platform.
(application workspace only)""",
'platformlist.info': 'In a platform workspace, lists versions of the custom '
'platform associated with this workspace. You can reduce '
'the result set by using filters.\n'
'Elsewhere, shows a list of platforms for use with "eb init -p". '
'Enter "--verbose" to get the full platform name.',
'platformworkspaceselect.info': 'Selects platform resources to use for this workspace.',
'platformworkspaceselectversion.info': 'Selects the active custom platform '
'version to use for this workspace.',
'platformselect.info': """Selects a default platform.
(application workspace only)""",
'platformselect.epilog': 'This command is an alternative to "eb init -i" and '
'"eb init -p". It doesn\'t change the platform on any '
'existing environments.\n'
'To upgrade an environment\'s platform, enter:\n'
' eb upgrade',
'platformevents.info': 'Displays events for the custom platform associated with '
'this workspace.',
'upgrade.info': 'Updates the environment to the most recent platform version.',
'scale.info': 'Changes the number of running instances.',
'status.info': 'Gets environment information and status.',
'setenv.info': 'Sets environment variables.',
'setenv.epilog': 'Use this command to set environment variables by typing a space-separated '
'list of key=value pairs.\n'
'For example, to set HeapSize to 256m and Site_Url to mysite.elasticbeanstalk.com, '
'type:\n'
' eb setenv HeapSize=256m Site_Url=mysite.elasticbeanstalk.com\n'
'You can also remove environment variables by specifying no value. For example:\n'
' eb setenv HeapSize= Site_Url=\n'
'This removes the environment variables.',
'swap.info': 'Swaps two environment CNAMEs with each other.',
'config.epilog': 'Use this command to work with environment configuration settings. \n'
'To update your environment directly in an interactive editor, type:\n'
' eb config\n',
'config.notfound': 'Elastic Beanstalk could not find any saved configuration with the name '
'"{config-name}".',
'config.envyamlexists': 'It appears your environment is using an env.yaml file. Be aware that '
'a saved configuration will take precedence over the contents of your '
'env.yaml file when both are present.',
'list.info': 'Lists all environments.',
'terminate.info': 'Terminates the environment.',
'terminate.epilog': 'This command terminates the environment. To terminate the application and '
'everything in it, use the "--all" option.',
'config.info': "Modify an environment's configuration. Use subcommands to manage saved "
"configurations.",
'platformconfig.info': "Modify an platform's configuration. Use subcommands to manage saved "
"configurations.",
'ssh.info': 'Opens the SSH client to connect to an instance.',
'ssh.timeout_without_setup': 'You can only use the "--timeout" argument with the "--setup" '
'argument',
'printenv.info': 'Shows the environment variables.',
'local.info': 'Runs commands on your local machine.',
'local.printenv.info': 'Shows local environment variables.',
'local.run.info': 'Runs the Docker container on your local machine.',
'local.setenv.info': 'Sets local environment variables.',
'local.logs.info': 'Prints where logs are locally saved.',
'local.open.info': 'Opens the application URL in a browser.',
'local.status.info': 'Gets container information and status.',
'local.setenv.epilog': 'Use this command to set environment variables by typing a space-separated '
'list of key=value pairs.',
'create.sampleandlabel': 'You cannot use the "--sample" and "--version" options together.',
'create.singleandsize': 'You cannot use the "--single" and "--scale" options together.',
'create.single_and_elb_type': 'You cannot use the "--single" and "--elb-type" options together.',
'create.single_and_elbpublic_or_elb_subnet': 'You can\'t use the "--single" argument with the '
'"--vpc.elbsubnets" or "--vpc.elbpublic" arguments.',
'create.worker_and_incompatible_vpc_arguments': 'You can\'t use the "--tier worker" argument with '
'the "--vpc.publicip", "--vpc.elbsubnets", '
'or "--vpc.elbpublic" arguments.',
'create.appdoesntexist': 'The specified app {app_name} does not exist. Skipping.',
'create.missinggroupsuffix': 'The environment name specified in env.yaml ends with a \'+\', but no '
'group suffix was provided. Please pass the --env-group-suffix argument.',
'create.missing_plus_sign_in_group_name': 'The environment name specified in env.yaml does not end '
'with a \'+\', but a group suffix was provided. Please '
'add a trailing \'+\' to the environment name',
'ssh.instanceandnumber': 'You cannot use the "--instance" and "--number" options together.',
'terminate.noenv': 'To delete the application and all application versions, type "eb terminate '
'--all".',
'cred.prompt': 'You have not yet set up your credentials or your credentials are incorrect \n'
'You must provide your credentials.',
'prompt.invalid': 'You did not provide a valid value.',
'prompt.yes-or-no': 'Type either "Y" or "N".',
'app.description': 'Application created from the EB CLI using "eb init"',
'env.description': 'Environment created from the EB CLI using "eb create"',
'env.clonedescription': 'Environment cloned from {env-name} from the EB CLI using "eb clone"',
'template.description': 'Configuration created from the EB CLI using "eb config save".',
'env.exists': 'An environment with that name already exists.',
'sstacks.notfound': 'Elastic Beanstalk could not find any platforms. Ensure you have the '
'necessary permissions to access Elastic Beanstalk.',
'sstacks.notaversion': 'Elastic Beanstalk could not find any supported platforms for the '
'given version {version}.',
'timeout.error': "The EB CLI timed out after {timeout_in_minutes} minute(s). The operation "
"might still be running. To keep viewing events, run 'eb events -f'. To "
"set timeout duration, use '--timeout MINUTES'.",
'sc.notfound': 'Git is not set up for this project. EB CLI will deploy a .zip file of the '
'entire directory.',
'exit.platformworkspacenotsupported': 'This command is not supported outside Application workspaces.',
'exit.applicationworkspacenotsupported': 'This command is not supported outside Platform workspaces.',
'exit.notsetup': 'This directory has not been set up with the EB CLI\n'
'You must first run "eb init".',
'exit.noregion': 'The EB CLI cannot find a default region. Run "eb init" or use a specific '
'region by including the "--region" option with the command.',
'exit.platformworkspaceempty': 'The current directory does not contain any Platform '
'configuration files. Unable to create new Platform.',
'exit.invalidstate': 'The operation cannot be completed at this time due to a pending '
'operation. Try again later.',
'exit.argerror': 'There was an argument error in the given command',
'exit.invalidversion': 'Invalid version format. Only ARNs, version numbers, or '
'platform_name/version formats are accepted.',
'exit.no_pdf_file': 'Unable to create platform version. Your workspace does not have a Platform '
'Definition File, \'platform.yaml\', in the root directory.',
'exit.nosuchplatformversion': 'No such version exists for the current platform.',
'exit.nosuchplatform': 'No such platform exists.',
'branch.noenv': 'This branch does not have a default environment. You must either specify '
'an environment by typing '
'"eb {cmd} my-env-name" or set a default environment by typing "eb use my-env-name".',
'ssh.notpresent': 'SSH is not installed. You must install SSH before continuing.',
'ssh.filenotfound': 'The EB CLI cannot find your SSH key file for keyname "{key-name}".'
' Your SSH key file must be located in the .ssh folder in your home directory.',
'local.logs.location': 'Elastic Beanstalk will write logs locally to {location}',
'local.logs.lastlocation': 'Logs were most recently created {prettydate} and written to {location}',
'local.logs.symlink': 'Updated symlink at {symlink}',
'local.logs.nologs': 'There are currently no local logs.',
'setenv.invalidformat': 'You must use the format KEY=VALUE to set an environment variable. '
'Variables must start with a letter.',
'tags.invalidformat': 'You must provide a comma-separated list using the format name=value to set tags. '
'Tags may only contain letters, numbers, and the following '
'symbols: / _ . : + = - @',
'tags.max': 'Elastic Beanstalk supports a maximum of 50 tags.',
'deploy.invalidoptions': 'You cannot use the "--version" option with either the "--message" '
'or "--label" option.',
'init.getvarsfromoldeb': 'You previous used an earlier version of eb. Getting options from '
'.elasticbeanstalk/config.\n'
'Credentials will now be stored in ~/.aws/config',
'ssh.noip': 'This instance does not have a Public IP address. This is possibly because the '
'instance is terminating.',
'worker.cname': 'Worker tiers do not support a CNAME.',
'cname.unavailable': 'The CNAME prefix {cname} is already in use.',
'ssh.openingport': 'INFO: Attempting to open port 22.',
'ssh.portopen': 'INFO: SSH port 22 open.',
'ssh.notopening': 'Found source restriction on ssh port; not attempting to open. Use the '
'--force flag to force opening of the port.',
'ssh.closeport': 'INFO: Closed port 22 on ec2 instance security group.',
'ssh.uploaded': 'Uploaded SSH public key for "{keyname}" into EC2 for region {region}.',
'swap.unsupported': 'You must have at least 2 running environments to swap CNAMEs.',
'connection.error': 'Having trouble communicating with AWS. Please ensure the provided region '
'is correct and you have a working internet connection.',
'toomanyplatforms.error': 'You have reached your platform limit. Please consider deleting '
'failed platform versions, or versions that you no longer require.',
'sc.unstagedchanges': 'You have uncommitted changes.',
'sc.gitnotinstalled': 'Your project is using git, but git doesn\'t appear to be installed.\n'
'Have you added git to your PATH?',
'events.streamprompt': ' -- Events -- (safe to Ctrl+C)',
'events.unsafestreamprompt': ' -- Events -- (Ctrl+C will abort the deployment)',
'events.abortmessage': ' Use "eb abort" to cancel the command.',
'abort.noabortableenvs': 'There are no environments currently being updated.',
'local.unsupported': 'You can use "eb local" only with preconfigured, generic and multicontainer '
'Docker platforms.',
'local.dockernotpresent': 'You must install Docker version {docker-version} to continue. If '
'you are using Mac OS X, ensure you have boot2docker version '
'{boot2docker-version}. Currently, "eb local" does not support Windows.',
'local.filenotfound': 'The EB CLI cannot find Dockerfile or the Dockerrun.aws.json file in the '
'application root directory.',
'local.missingdockerrun': 'This environment requires a Dockerrun.aws.json file to run.',
'local.invaliddockerrunversion': 'The AWSEBDockerrunVersion key in the Dockerrun.aws.json file is '
'not valid or is not included.',
'local.missingdockerrunimage': 'The Dockerrun.aws.json file requires the Image key.',
'local.missingdockerrunports': 'The Dockerrun.aws.json file requires the Ports key.',
'local.missingdockerruncontainerport': 'The Dockerrun.aws.json file requires the ContainerPort field.',
'local.invalidjson': 'The Dockerrun.aws.json file is not in valid JSON format.',
'local.run.noportexposed': 'The Dockerfile must list ports to expose on the Docker container. Specify '
'at least one port, and then try again.',
'local.run.nobaseimg': 'The Dockerfile or Dockerrun.aws.json file does not specify a base image. '
'Specify a base image, and then try again.',
'local.run.socketperms': 'If you are on Ubuntu, ensure that you have added yourself into the Unix '
'docker group by running "sudo usermod -aG docker $USER" '
'and then log out and log back in.',
'local.open.nocontainer': 'Elastic Beanstalk did not detect a running Docker container. Ensure that '
'a container is running before you use "eb local open".',
'local.open.noexposedport': 'This container has no exposed host ports.',
'labs.info': 'Extra experimental commands.',
'quicklink.info': 'Generate a quick-launch link for your project.',
'quicklink.epilog': 'Applications and environments created from the quick link are accessible to your '
'account only. \n'
'To share the link with other accounts, you must explicitly grant those accounts '
'read access to your S3 application version .zip file.',
'download.info': 'Download Application Version.',
'convert-dockkerrun.info': 'Converts Dockerrun.aws.json from version 1 to version 2.',
'cleanup-versions.info': 'Cleans up old application versions.',
'setup-ssl.info': 'Sets up ssl on your environment.',
'region.china.credentials':
'To use the China (Beijing) region, account credentials unique to the '
'China (Beijing) region must be used.',
'deploy.notadirectory': 'The directory {module} does not exist.',
'deploy.modulemissingenvyaml':
'All specified modules require an env.yaml file.\n'
'The following modules are missing this file: {modules}',
'deploy.noenvname':
'No environment name was specified in env.yaml for module {module}. Unable to deploy.',
'compose.noenvyaml':
'The module {module} does not contain an env.yaml file. This module will be skipped.',
'compose.novalidmodules': 'No valid modules were found. No environments will be created.',
'instance.processes.health': '{healthy}/{total} processes healthy.',
'codesource.info': 'Configures the code source for the EB CLI to use by default.',
'codesource.localmsg': 'Default set to use local sources',
'restore.info': 'Restores a terminated environment.',
'restore.no_env': 'No terminated environments found.\nEnvironments are available for six weeks after '
'termination.',
'restore.displayheader': 'Select a terminated environment to restore',
'logs.info': 'Gets recent logs.',
'logs.epilog': 'This command displays the last 100 lines of logs. To retrieve '
'all logs, use the "--all" option.',
'logs.all_argument_and_zip_argument':
'You can\'t use the "--all" and "--zip" options together. '
'They are two different ways to retrieve logs.',
'logs.all_argument_and_instance_argument': 'You can\'t use "--instance" with "--all".',
'logs.invalid_cloudwatch_log_source_type': 'You can\'t specify the source type "all" for the '
'"--cloudwatch-log-source" option when retrieving logs. '
'Specify "instance" or "environment-health".',
'logs.cloudwatch_log_source_argument_and_log_group_argument':
'You cannot use the "--cloudwatch-logs" and "--cloudwatch-log-source" '
'options together.',
'logs.cloudwatch_log_source_argumnent_is_invalid_for_retrieval':
'Invalid CloudWatch Logs source type for retrieving logs: "{}". '
'Valid types: instance | environment-health',
'logs.cloudwatch_log_source_argumnent_is_invalid_for_enabling_streaming':
'Invalid CloudWatch Logs source type for setting log streaming: "{}". Valid '
'types: instance | environment-health | all',
'logs.cloudwatch_logs_argument_and_log_group_argument':
'You can\'t use the "--log-group" option when setting log streaming. You can '
'enable or disable all instance log group streaming and/or environment-health '
'streaming.',
'logs.cloudwatch_logs_argument_and_instance_argument':
'You can\'t use the "--instance" option when setting log streaming. You can '
'enable or disable instance log streaming for the entire environment and/or '
'environment-health streaming.',
'logs.cloudwatch_logs_argument_and_all_argument':
'You can\'t use the "--all" option when setting log streaming. This is an '
'output option for log retrieval commands.',
'logs.cloudwatch_logs_argument_and_zip_argument':
'You can\'t use the "--zip" option when setting log streaming. This is an '
'output option for log retrieval commands.',
'logs.health_and_instance_argument':
'You can\'t use the "--instance" option when retrieving environment-health '
'logs. The scope for these logs is the entire environment.',
'logs.environment_health_log_streaming_disabled':
'Can\'t retrieve environment-health logs for environment {}. '
'Environment-health log streaming is disabled.',
'logs.instance_log_streaming_disabled':
'Can\'t retrieve instance logs for environment {}. Instance '
'log streaming is disabled.',
'logs.location': 'Logs were saved to {location}',
'logs.log_group_and_environment_health_log_source':
'You can\'t use the "--log-group" option when retrieving environment-health '
'logs. These logs are in a specific, implied log group.',
'beanstalk-logs.badinstance':
'Can\'t find instance "{}" in the environment\'s instance logs on '
'CloudWatch Logs.',
'cloudwatch-setup.info': 'Create .ebextensions files necessary for setting up '
'CloudWatch used in logging instance deployment.',
'cloudwatch-setup.alreadysetup': 'CloudWatch file {filename} is already set up.',
'cloudwatch-setup.text': '.ebextensions created. In order to complete setup you '
'will need\n'
'to check in any changes, (if applicable) and run '
'"eb deploy".\n'
'You will also need the cloudwatch log permissions for '
'this IAM User\n'
'as well as for the environments instance profile.\n'
'For more information see: http://docs.aws.amazon.com/'
'elasticbeanstalk/latest/dg/AWSHowTo.cloudwatchlogs.html',
'cloudwatch-setup.removetext': 'Removed .ebextensions. In order to complete removal '
'you\n'
'will need to check in any changes, (if applicable) '
'an run\n'
'"eb deploy".',
'cloudwatch_log_streaming.not_setup': os.linesep.join([
'Could not find log group; CloudWatch log streaming might not enabled for this '
'environment.',
' - To enable instance log streaming, run "eb logs -cw enable".',
' - To enable health log streaming, run "eb logs -cw enable -cls '
'environment-health".',
' - To enable all the log streaming features, run "eb logs -cw '
'enable -cls all".',
]),
'cloudwatch_environment_health_log_streaming.enhanced_health_not_found':
'Enhanced health disabled. Could not setup health-transitions log streaming.',
'cloudwatch-logs.nostreams': 'Could not find any log streams with log group: {log_group}',
'cloudwatch_instance_log_streaming.enable':
'Enabling instance log streaming to CloudWatch for your environment',
'cloudwatch_instance_log_streaming.disable':
'Disabling instance log streaming to CloudWatch for your environment',
'cloudwatch_environment_health_log_streaming.enable':
'Enabling health transition log streaming to CloudWatch for your environment',
'cloudwatch_environment_health_log_streaming.disable':
'Disabling health transition log streaming to CloudWatch for your environment',
'cloudwatch-logs.link': 'After the environment is updated you can view your logs '
'by following the link:\n'
'https://console.aws.amazon.com/cloudwatch/home?region={region}'
'#logs:prefix=/aws/elasticbeanstalk/{env_name}/',
'cloudwatch-logs.bjslink': 'After the environment is updated you can view your '
'logs by following the link:\n'
'https://console.amazonaws.cn/cloudwatch/home?region={region}#'
'logs:prefix=/aws/elasticbeanstalk/{env_name}/',
'cloudwatch_instance_log_streaming.already_enabled':
'CloudWatch instance log streaming is already enabled for your environment',
'cloudwatch_environment_health_log_streaming.already_enabled':
'CloudWatch health transition log streaming is already enabled for your environment',
'cloudwatch_instance_log_streaming.already_disabled':
'CloudWatch logs are already disabled for your environment',
'cloudwatch_environment_health_log_streaming.already_disabled':
'CloudWatch health transition log streaming is already disabled for your environment',
'lifecycle.info': 'Modifying application version lifecycle policy',
'lifecycle.epilog': 'Use this command to work with application lifecycle '
'configuration settings. \n'
'To update your application directly in an interactive '
'editor, type:\n'
' eb appversion lifecycle\n',
'lifecycle.success': 'Successfully updated application version lifecycle '
'policy',
'lifecycle.updatenochanges': 'No changes made; exiting',
'lifecycle.invalidrole': 'Passed an invalid role: {role}, cannot update '
'application',
'lifecycle.invalidsyntax': 'The configuration settings you provided contain '
'an error; The lifecycle configuration will not be '
'updated',
'appversion.create': 'Creating application version archive "{version}".',
'appversion.none': 'The current directory does not contain any source code. '
'Elastic Beanstalk is launching the sample application instead.',
'appversion.processfailed': 'Pre-processing of application version {app_version} '
'has failed.',
'appversion.cannotdeploy': 'Some application versions failed to process. Unable '
'to continue deployment.',
'appversion.processtimeout': 'All application versions have not reached a "Processed" '
'state. Unable to continue with deployment.',
'appversion.info': 'Listing and managing application versions',
'appversion.delete.notfound': 'Application {} does not have Application Version {}.',
'appversion.delete.deployed': 'Cannot delete Application version {} as it is deployed '
'to Environments: {}',
'appversion.delete.none': 'You must specify an Application version label to delete an '
'Application version',
'appversion.attribute.failed': 'Application Version {app_version} has failed to '
'generate required attributes.',
'appversion.attribute.timeout': 'Application Versions did not generated the required '
'attributes. Unable to continue with deployment.',
'appversion.attribute.success': 'Found attributes for application version {app_version}',
'codecommit.nosc': 'Cannot setup CodeCommit because there is no Source Control setup, '
'continuing with initialization',
'codecommit.norepo': 'Repository does not exist in CodeCommit',
'codecommit.nobranch': 'Branch does not exist in CodeCommit',
'codecommit.badregion': 'AWS CodeCommit is not supported in this region; continuing '
'initialization without CodeCommit',
'codecommit.bad_source': 'Source argument must be of the form codecommit/repository-name/branch-name',
'codebuild.noheader': 'Beanstalk configuration header \'{header}\' is missing from '
'Buildspec file; will not use Beanstalk Code Build integration',
'codebuild.latestplatform': 'Buildspec file is present but no image is specified; '
'using latest image for selected platform: {platform}',
'exit.noplatform': 'This workspace is not configured with a platform. Please select '
'one using "eb platform use"',
'platformstatus.upgrade': 'A more recent version of this platform is available. Type '
'\'eb upgrade\' to uprade the platform version used by this environment.',
'platform.nobuilderenv': 'This workspace has not yet been associated with a builder environment. '
'One will be configured once you create a platform version.',
'codebuild.buildlogs': 'You can find logs for the CodeBuild build here: {logs_link}',
'tags.duplicate_across_delete_and_update_lists':
"A tag with the key '{0}' is specified for both '--delete' and '--update'. You can either "
"delete or update each tag in a single operation.",
'tags.duplicate_key_in_add_list': "A tag with the key '{0}' is specified more than once "
"for '--add'. You can add a tag key only once.",
'tags.duplicate_key_in_delete_list': "A tag with the key '{0}' is specified more than once "
"for '--delete'. You can delete a tag key only once.",
'tags.duplicate_key_in_update_list': "A tag with the key '{0}' is specified more than once "
"for '--update'. You can update a tag key only once.",
'tags.invalid_tag_key': "Tag key '{0}' has invalid characters. Only letters, numbers, white "
"space, and these characters are allowed: _ . : / + - @.",
'tags.invalid_tag_value': "Tag value '{0}' has invalid characters. Only letters, numbers, "
"white space, and these characters are allowed: _ . : / = + - @.",
'tags.list_with_other_arguments': "You can't specify the '--list' option with the '--add', "
"'--delete', or '--update' option.",
'tags.resource_tags_missing': "The response of the 'list_tags_for_resource' API call is "
"missing the 'ResourceTags' field.",
'tags.tag_keys_already_exist': "Tags with the following keys can't be added because they "
"already exist:",
'tags.tag_key_cant_be_blank': 'Tag key must not be blank.',
'tags.tag_value_cant_be_blank': 'Tag value must not be blank.',
'tags.tag_keys_dont_exist_for_deletion': "Tags with the following keys can't be deleted "
"because they don't exist:",
'tags.tag_keys_dont_exist_for_update': "Tags with the following keys can't be updated "
"because they don't exist:",
'tags.tag_key_max_length_exceeded': "Tag with the following key exceed length limit. Tag "
"keys can be up to 128 characters in length.",
'tags.tag_value_max_length_exceeded': "Tag with the following value exceed length limit. "
"Tag values can be up to 256 characters in length.",
'cloudformation.cannot_find_app_source_for_environment': 'Cannot find app source for environment'
}
prompts = {
'events.hanging': 'Streaming new events. Use CTRL+C to exit.',
'platform.validate': 'It appears you are using {platform}. Is this correct?',
'platform.prompt': 'Select a platform.',
'platform.prompt.withmodule': 'Select a platform for module: {module_name}.',
'platformssh.nokey': 'This platform builder is not set up for SSH. Use "eb platform '
'ssh --setup" to set up SSH for that environment.',
'sstack.version': 'Select a platform version.',
'init.selectdefaultenv': 'Select the default environment. \n'
'You can change this later by typing "eb use [environment_name]".',
'scale.switchtoloadbalance': 'The environment is currently a single-instance. Do you want'
' to change to a load-balancing environment?',
'scale.switchtoloadbalancewarn': 'If you choose yes, the environment and your application '
'will be temporarily unavailable.',
'cname.unavailable': 'The CNAME you provided is already in use.\n',
'cleanupbuilder.confirm': 'The platform builder environment "{env-name}" and all associated '
'instances will be terminated.',
'cleanupbuilder.validate': 'To confirm, type the environment name',
'cleanupplatform.confirm': 'Failed platform versions for "{platform-name}" will be removed.',
'cleanupplatform.validate': 'To confirm, type the platform name',
'cleanupplatform.validate-all': 'To confirm, type "all"',
'terminate.confirm': 'The environment "{env_name}" and all associated instances '
'will be terminated.',
'terminate.validate': 'To confirm, type the environment name',
'upgrade.validate': 'To continue, type the environment name',
'platformdelete.confirm': 'The platform "{platform-arn}" and all associated '
'resources will be deleted.',
'platformdelete.validate': 'To confirm, type the platform arn',
'delete.confirm': 'The application "{app_name}" and all its resources will '
'be deleted.\n'
'This application currently has the following:\n'
'Running environments: {env_num}\n'
'Configuration templates: {config_num}\n'
'Application versions: {version_num}\n',
'delete.validate': 'To confirm, type the application name',
'fileopen.error1': 'EB CLI cannot open the file using the editor {editor}.',
'update.invalidstate': 'The environment update cannot be complete at this time. '
'Try again later.',
'update.invalidsyntax': 'The configuration settings you provided contain an error. '
'The environment will not be updated.',
'ssh.setup': 'Do you want to set up SSH for your instances?',
'sstack.invalid': 'You specified a platform that is not valid.',
'sstack.invalidkey': 'The EB CLI cannot find a platform for key "{string}".',
'keypair.prompt': 'Select a keypair.',
'keypair.nameprompt': 'Type a keypair name.',
'tier.prompt': 'Select an environment tier.',
'terminate.nomatch': 'Names do not match. Exiting.',
'ssh.nokey': 'This environment is not set up for SSH. Use "eb ssh --setup" '
'to set up SSH for the environment.',
'ssh.setupwarn': 'You are about to setup SSH for environment "{env-name}". '
'If you continue, your existing instances will have to be '
'**terminated** and new instances will be created. '
'The environment will be temporarily unavailable.',
'rds.username': 'Enter an RDS DB username (default is "ebroot")',
'rds.password': 'Enter an RDS DB master password',
'vpc.id': 'Enter the VPC ID',
'vpc.publicip': 'Do you want to associate a public IP address?',
'vpc.ec2subnets': 'Enter a comma-separated list of Amazon EC2 subnets',
'vpc.elbsubnets': 'Enter a comma-separated list of Amazon ELB subnets',
'vpc.securitygroups': 'Enter a comma-separated list of Amazon VPC security groups',
'vpc.elbpublic': 'Do you want the load balancer to be public? (Select no for internal)',
'vpc.dbsubnets': 'Enter a comma-separated list of database subnets',
'logs.retrieving': 'Retrieving logs...',
'swap.envprompt': 'Select the environment with which you want to swap CNAMEs.',
'abort.envprompt': 'Select the environment you want to stop updating.',
'clone.latest': 'There is a newer version of the platform used by the environment '
'you are cloning.\n'
'Select the version of the platform that you want to use for the clone.',
'clone.latestwarn': 'Launching environment clone on most recent platform version. Override '
'this behavior by using the "--exact" option.',
'upgrade.altmessage':
'You can also change your platform version by typing "eb clone" and then "eb swap".',
'upgrade.singleinstance': 'This operation causes application downtime while Elastic '
'Beanstalk replaces the instance.',
'upgrade.norollingapply': 'Elastic Beanstalk will enable {0}-based rolling updates to avoid '
'application downtime while it replaces your instances. You may '
'cancel the upgrade after it has started by typing "eb abort". '
'To upgrade without rolling updates, type "eb upgrade --noroll".',
'upgrade.norollingforce': 'This operation causes application downtime while Elastic Beanstalk '
'replaces your instances.',
'upgrade.rollingupdate':
'This operation replaces your instances with minimal or zero '
'downtime. You may cancel the upgrade after it has started by typing "eb abort".',
'upgrade.infodialog': 'The environment "{0}" will be updated to use the most recent platform '
'version.',
'upgrade.alreadylatest': 'Environment already on most recent platform version.',
'upgrade.applyrolling': 'Enabling {0}-based rolling updates to environment.',
'create.dockerrunupgrade': 'Multicontainer Docker environments do not support the version number '
'of the Dockerrun.aws.json file that you provided. Type '
'"eb labs convert-dockerrun" to convert it to a newer format.',
'ecs.permissions': 'The Multi-container Docker platform requires additional ECS permissions. '
'Add the permissions to the aws-elasticbeanstalk-ec2-role or use your own '
'instance profile by typing "-ip {profile-name}".\n'
'For more information see: '
'https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/'
'create_deploy_docker_ecs.html#create_deploy_docker_ecs_role',
'create.servicerole.info': '2.0+ Platforms require a service role. We will attempt to create '
'one for you. You can specify your own role using the '
'--service-role option.',
'create.servicerole.view': 'Type "view" to see the policy, or just press ENTER to '
'continue',
'create.servicerole.required': '2.0+ Platforms require a service role. You can provide '
'one with --service-role option',
'create.servicerole.nopermissions': 'No permissions to create a role. '
'Create an IAM role called "{}" with appropriate '
'permissions to continue, or specify a role with '
'--service-role.\n'
'See http://docs.aws.amazon.com/elasticbeanstalk/latest/'
'dg/concepts-roles.html for more info.\n'
'Actual error: {}',
'general.pressenter': 'Press enter to continue',
'compose.groupname': 'Please enter the group name to be used',
'restore.prompt': 'Enter a environment # to restore. ESC to exit.',
'restore.selectedenv': '\n'
'Selected environment {env_id}\n'
'Application: {app}\n'
'Description: {desc}\n'
'CNAME: {cname}\n'
'Version: {version}\n'
'Platform: {platform}\n'
'Terminated: {dat_term}\n'
'Restore this environment? [y/n]\n',
'codesource.codesourceprompt': 'Select your codesource',
'appversion.redeploy.validate': 'Do you want to deploy a previous or '
'different version? (y/n)',
'appversion.redeploy.prompt': 'Select a version # to deploy (1 to {}).',
'appversion.redeploy.inprogress': 'Deploying version {}.',
'appversion.delete.validate': 'Do you want to delete the application '
'version with label: {}? (y/n)',
'appversion.delete.prompt': 'Select a version # to delete (1 to {}).',
'codecommit.usecc': 'Do you wish to continue with CodeCommit? (y/N) '
'(default is n)',
'codebuild.getplatform': 'Could not determine best image for buildspec '
'file please select from list.\n Current chosen '
'platform: {platform}',
'platforminit.ssh': 'Would you like to be able to log into your platform '
'packer environment?',
}
alerts = {
'platform.old': 'There is a newer version of the platform used by your '
'environment. You can upgrade your environment to the '
'most recent platform version by typing "eb upgrade".'
}
flag_text = {
'general.env': 'environment name',
'base.version': 'show application/version info',
'base.verbose': 'toggle verbose output',
'base.profile': 'use a specific profile from your credential file',
'base.region': 'use a specific region',
'general.timeout': 'timeout period in minutes',
'base.noverify': "don't verify AWS SSL certificates",
'clone.env': 'name of environment to clone',
'clone.name': 'desired name for environment clone',
'clone.cname': 'cname prefix',
'clone.scale': 'number of desired instances',
'clone.tags': 'a comma separated list of tags as key=value pairs',
'clone.nohang': 'return immediately, do not wait for clone to be completed',
'clone.exact': 'match the platform version of the original environment',
'config.nohang': 'return immediately, do not wait for config to be completed',
'config.codesource': 'configure the settings for which source the CLI will use '
'for your code.'
' Availables sources: {codecommit}. Available actions: '
'{enable, disable}',
'create.name': 'desired Environment name',
'create.cname': 'cname prefix',
'create.itype': 'instance type i.e. t1.micro',
'create.tier': 'environment tier type',
'create.platform': 'platform',
'create.single': 'environment will use a single instance with no load balancer',
'create.sample': 'use Sample Application',
'create.default': 'set as branches default environment',
'create.iprofile': 'EC2 Instance profile',
'create.servicerole': 'Service Role',
'create.version': 'version label to deploy',
'create.keyname': 'EC2 SSH KeyPair name',
'create.scale': 'number of desired instances',
'create.nohang': 'return immediately, do not wait for create to be completed',
'create.tags': 'a comma separated list of tags as key=value pairs',
'create.envvars': 'a comma-separated list of environment variables as key=value pairs',
'create.database': 'create a database',
'create.vpc': 'create environment inside a VPC',
'create.config': 'saved configuration name',
'create.group': 'group suffix',
'create.modules': 'a list of modules',
'create.elb_type': 'load balancer type',
'create.source': 'source of code to create from directly; example source_location/repo/branch',
'create.process': 'enable preprocessing of the application version',
'deploy.env': 'environment name',
'deploy.modules': 'modules to deploy',
'deploy.version': 'existing version label to deploy',
'deploy.label': 'label name which version will be given',
'deploy.message': 'description for version',
'deploy.nohang': 'return immediately, do not wait for deploy to be completed',
'deploy.staged': 'deploy files staged in git rather than the HEAD commit',
'deploy.group_suffix': 'group suffix',
'deploy.source': 'source of code to deploy directly; example source_location/repo/branch',
'deploy.process': 'enable preprocessing of the application version',
'platformevents.version': 'version to retrieve events for',
'events.follow': 'wait and continue to print events as they come',
'init.name': 'application name',
'init.platform': 'default Platform',
'init.keyname': 'default EC2 key name',
'init.interactive': 'force interactive mode',
'platformcreate.instanceprofile': 'the instance profile to use when creating AMIs '
'for custom platforms',
'ssh.keyname': 'EC2 key to use with ssh',
'init.module': 'module directory',
'init.source': 'source of code to set as default; example source_location/repo/branch',
'labs.cwl.remove': 'remove .ebextensions',
'list.all': 'show environments for all applications',
'local.run.envvars': 'a comma-separated list of environment variables as key=value pairs',
'local.run.hostport': 'the host port that is exposed and mapped to the container port',
'local.run.insecuressl': 'Allow insecure connections to the docker registry',
'local.setenv.vars': 'space-separated list in format: VAR_NAME=KEY',
'logs.all': 'retrieve all logs',
'logs.zip': 'retrieve all logs as .zip',
'logs.instance': 'retrieve logs only for this instance',
'logs.log-group': 'retrieve logs only for this log group',
'logs.stream': 'enable/disable log streaming to CloudWatch Logs',
'logs.environment': 'environment from which to download logs',
'logs.cloudwatch_logs': 'enable/disable log streaming to CloudWatch Logs',
'logs.cloudwatch_log_source': os.linesep.join(
[
'CloudWatch logs source to enable/disable or to retrieve',
'valid values:',
' with --cloudwatch-logs (enable/disable): instance | environment-health | all',
' without --cloudwatch-logs (retrieve): instance | environment-health',
]
),
'restore.env': 'The ID of the environment to restore',
'scale.number': 'number of desired instances',
'scale.force': 'skip confirmation prompt',
'setenv.vars': 'space-separated list in format: VAR_NAME=KEY',
'setenv.env': 'environment name',
'ssh.number': 'index of instance in list',
'ssh.instance': 'instance id',
'ssh.keepopen': 'keep port 22 open',
'ssh.command': 'Execute a shell command on the specified instance instead of starting '
'an SSH session.',
'ssh.custom': "Specify an SSH command to use instead of 'ssh -i keyfile'. Do not "
"include the remote user and hostname.",
'ssh.force': 'force port 22 open to 0.0.0.0',
'ssh.setup': 'setup SSH for the environment',
'ssh.timeout': "Specify the timeout period in minutes. Can only be used with the "
"'--setup' argument.",
'cleanup.resources': 'Valid values include (builder, versions, all). You can specify '
'"builder" to terminate the environment used to create this platform. '
'You can use "versions" to clean up platform versions in the Failed state',
'cleanup.force': 'skip confirmation prompt',
'platformdelete.force': 'skip confirmation prompt',
'platformdelete.cleanup': 'remove all platform versions in the "Failed" state',
'platformdelete.allplatforms': 'enables cleanup for all of your platforms.',
'terminate.force': 'skip confirmation prompt',
'terminate.all': 'terminate everything',
'terminate.nohang': 'return immediately, do not wait for terminate to be completed',
'terminate.ignorelinks': 'terminate even if environment is linked',
'platforminit.name': 'platform name',
'platformcreateversion.version': 'platform version',
'platformcreateversion.major': 'major version increment',
'platformcreateversion.minor': 'minor version increment',
'platformcreateversion.patch': 'patch version increment',
'platformcreateversion.vpc.id': 'specify id of VPC to launch Packer builder into',
'platformcreateversion.vpc.subnets': 'specify subnets to launch Packer builder into',
'platformcreateversion.vpc.publicip': 'associate public IPs to EC2 instances launched if specified',
'platformlogs.version': 'platform version to retrieve logs for',
'platformdeleteversion.version': 'platform version',
'platformshowversion.version': 'platform version',
'platformlist.all': """lists the versions of all platforms owned by your account
(platform workspace only)""",
'platformlist.status': """the status that you wish to filter on (Ready, Failed, Deleting, Creating)
(platform workspace only)
""",
'platformworkspace.platform': 'platform name',
'upgrade.noroll': 'do not enable rolling updates before upgrade',
'use.env': 'environment name',
'use.source': 'source of code to set as default; example source_location/repo/branch',
'use.repo': 'default code commit repository',
'use.branch': 'default code commit branch will use default repository if none is specified',
'swap.env': 'name of source environment',
'swap.name': 'name of destination environment',
'codesource.sourcename': 'name of the code source to set as default',
'appversion.delete': 'delete the specified application version',
'lifecycle.print': 'prints the current application version lifecycle policy',
'lifecycle.update': 'allows an inline update to a application version lifecycle policy',
'tags.add': 'create new environment tags provided as a comma-separated list of key=value pairs',
'tags.delete': 'delete existing environment tags provided as a comma-separated list of keys',
'tags.env': 'environment on which to perform tags operation',
'tags.info': 'Allows adding, deleting, updating, and listing of environment tags.',
'tags.list': 'lists all environment resource tags',
'tags.update': 'update existing environment tags provided as a comma-separated list of keys=value pairs',
}
responses = {
'event.completewitherrors': 'Create environment operation is complete, but with errors.',
'event.launched_environment': 'Launched environment',
'event.platform_ami_region_service_region_mismatch': 'Unmatched region for created AMI',
'event.platformdeletesuccess': 'Successfully deleted platform version',
'event.platformdeletefailed': 'Failed to delete platform version',
'event.platformcreatefailed': 'Failed to create platform version',
'event.platformcreatesuccess': 'Successfully created platform version',
'event.redmessage': 'Environment health has been set to RED',
'event.redtoyellowmessage': 'Environment health has transitioned '
'from YELLOW to RED',
'event.yellowmessage': 'Environment health has been set to YELLOW',
'event.greenmessage': 'Environment health has been set to GREEN',
'event.launchsuccess': 'Successfully launched environment:',
'event.launchbad': 'Create environment operation is complete, '
'but with errors',
'event.failedlaunch': 'Failed to launch environment.',
'event.faileddeploy': 'Failed to deploy application.',
'event.failedupdate': 'The environment was reverted to the previous configuration setting.',
'event.updatebad': 'Update environment operation is complete, but with errors.',
'event.updatefailed': 'Failed to deploy configuration.',
'git.norepository': 'Error: Not a git repository '
'(or any of the parent directories): .git',
'health.nodescribehealth': 'DescribeEnvironmentHealth is not supported.',
'env.updatesuccess': 'Environment update completed successfully.',
'env.configsuccess': 'Successfully deployed new configuration to environment.',
'env.cnamenotavailable': 'DNS name ([^ ]+) is not available.',
'env.nameexists': 'Environment [^ ]+ already exists.',
'app.deletesuccess': 'The application has been deleted successfully.',
'app.exists': 'Application {app-name} already exists.',
'app.notexists': 'No Application named {app-name} found.',
'logs.pulled': 'Pulled logs for environment instances.',
'logs.successtail': 'Successfully finished tailing',
'logs.successbundle': 'Successfully finished bundling',
'logs.fail': 'Failed to pull logs for environment instances.',
'env.terminated': 'terminateEnvironment completed successfully.',
'env.invalidstate': 'Environment named {env-name} is in an invalid state for this operation. '
'Must be Ready.',
'loadbalancer.notfound': 'There is no ACTIVE Load Balancer named',
'loadbalancer.targetgroup.notfound': 'Target group \'{tgarn}\' not found',
'ec2.sshalreadyopen': 'the specified rule "peer: 0.0.0.0/0, TCP, from port: 22, to port: 22,',
'swap.success': 'Completed swapping CNAMEs for environments',
'cfg.nameexists': 'Configuration Template {name} already exists.',
'create.noplatform': 'Unable to determine base for template pack (no solution stack)',
'create.ecsdockerrun1': 'ECS Application sourcebundle validation error: '
'Unsupported AWSEBDockerrunVersion:',
'appversion.finished': 'Finished processing application version',
'tags.tag_update_successful': 'Environment tag update completed successfully.',
'tags.no_tags_to_update': 'Environment tag update failed.',
'restore.norestore': 'Environment will not be restored',
}
git_ignore = [
'# Elastic Beanstalk Files',
'.elasticbeanstalk/*',
'!.elasticbeanstalk/*.cfg.yml',
'!.elasticbeanstalk/*.global.yml',
]
docker_ignore = git_ignore[:2] + ['.git', '.gitignore']
| StarcoderdataPython |
4847515 | <reponame>yishantao/DailyPractice<filename>Python/pandas/group_by.py
# -*- coding:utf-8 -*-
"""This module is used to test groupby"""
import numpy as np
import pandas as pd
data = pd.DataFrame(
{'name': ['zhangsan', 'zhangsan', 'lisi', 'lisi', 'zhangsan'], 'category': ['one', 'two', 'one', 'two', 'one'],
'number': [1, 2, 3, 4, 5], 'count': [6, 9, 2, 9, 3]})
# print(data)
# grouped = data['number'].groupby(data['name'])
# print(grouped)
# print(grouped.mean())
# years = np.array(['2017', '2018', '2017', '2018', '2018'])
# grouped = data['number'].groupby([years]).mean()
# print(grouped)
# print(data['number'].groupby('name').mean())
# print(data.groupby('name')['number'].mean())
# print(data.groupby('name').mean())
# print(data.groupby('name').size())
# for name, group in data.groupby('name'):
# print(name)
# print(group)
# for (name, category), group in data.groupby(['name', 'category']):
# print(name, category)
# print(group)
# print(dict(list(data.groupby('name')))['lisi'])
# print(dict(list(data.groupby([[1, 1, 2, 2]], axis=1)))[1])
# data.groupby('name')['number']
# data.groupby('name')[['number', 'count']]
#
# data['number'].groupby(data['name'])
# data[['number', 'count']].groupby(data['name'])
mapping = {'name': 'a', 'category': 'b', 'number': 'a', 'count': 'b'}
# print(data.groupby(mapping, axis=1).sum())
# map_series = pd.Series(mapping)
# print(data.groupby(map_series, axis=1).sum())
# data = pd.DataFrame(
# {'name': ['zhangsan', 'zhangsan', 'lisi', 'lisi', 'zhangsan'], 'category': ['one', 'two', 'one', 'two', 'one'],
# 'number': [1, 2, 3, 4, 5], 'count': [6, 9, 2, 9, 3]}, index=['a', 'b', 'aa', 'bb', 'cc'])
# print(data.groupby(len).sum())
# data.groupby([[1, 2, 3, 2, 3], len])
def peak_to_peak(arr):
return arr.max() - arr.min()
#
# print(data.groupby('name')['number'].agg(peak_to_peak))
# print(data.groupby('name')['number'].agg('mean'))
# print(data.groupby('name')['number'].agg(['mean', 'sum', peak_to_peak]))
# print(data.groupby('name')['number'].agg([('one', 'mean'), ('two', 'sum')]))
# print(data.groupby('name')['number', 'count'].agg([('one', 'mean'), ('two', 'sum')])['number'])
# print(data.groupby('name')['number', 'count'].agg({'number': [('one', 'min'), ('two', 'max')], 'count': 'sum'}))
# print(data.groupby('name', as_index=False)['number'].agg('mean'))
| StarcoderdataPython |
102891 | #!/usr/bin/python3
import argparse
import os
import subprocess
import tarfile
import tempfile
from pathlib import Path
from typing import List
parser = argparse.ArgumentParser(
description='Run k-core decomposition on hypergraphs in a TAR file and report decompositions with interesting cuts.')
parser.add_argument('tarfile', type=str,
help='Path to the tarfile containing the hypergraphs')
parser.add_argument('--bin', dest='bin', type=str,
help='Path to the `hkcore` binary. Otherwise this script will build it automatically.')
parser.add_argument('-o', dest='outdir', type=str,
help='Path for output files', required=True)
args = parser.parse_args()
TARFILE = os.path.join(os.getcwd(), args.tarfile)
PROJECT_ROOT = Path(__file__).cwd() / '..'
BINARY_PATH = None if args.bin is None else os.path.join(os.getcwd(), args.bin)
OUTPUT_PATH = Path(args.outdir)
if not OUTPUT_PATH.exists():
print('Error: output path does not exist')
exit(1)
class TarFileInfoIterator:
def __init__(self, tfile: tarfile.TarFile):
self._tfile = tfile
def __iter__(self) -> 'TarFileInfoIterator':
return self
def __next__(self) -> tarfile.TarInfo:
info = self._tfile.next()
if info is None:
raise StopIteration()
return info
with tarfile.open(TARFILE) as tf, tempfile.TemporaryDirectory() as tempdir:
olddir = os.getcwd()
os.chdir(tempdir)
# Setup project
if BINARY_PATH is None:
# TODO it is annoying to have to download googletest. Possible to avoid?
subprocess.Popen(['cmake', PROJECT_ROOT]).wait()
subprocess.Popen(['make', 'hkcore']).wait()
BINARY_PATH = './hkcore'
# Sort TarInfos so we can process them smallest to largest
tinfos: List[tarfile.TarInfo] = [
info for info in TarFileInfoIterator(tf) if info.isfile()]
tinfos.sort(key=lambda info: info.get_info()['size'])
for info in tinfos:
print(f'Extracting {info.name} for analysis...')
tf.extract(info)
p = subprocess.Popen([BINARY_PATH, info.name, os.path.join(olddir, OUTPUT_PATH)])
if p.wait() != 0:
print('Process exited with non-zero exit code')
print(f'Done with {info.name}')
subprocess.Popen(['ls']).wait()
print(f'Writing files to {OUTPUT_PATH}')
print('Done')
| StarcoderdataPython |
1738935 | """
Copyright 2013 <NAME>
This file is part of CVXPY.
CVXPY 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 3 of the License, or
(at your option) any later version.
CVXPY is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CVXPY. If not, see <http://www.gnu.org/licenses/>.
"""
import cvxpy.utilities as u
from cvxpy.expressions.expression import Expression
import cvxpy.lin_ops.lin_utils as lu
class Minimize(u.Canonical):
"""An optimization objective for minimization.
"""
NAME = "minimize"
def __init__(self, expr):
self._expr = Expression.cast_to_const(expr)
# Validate that the objective resolves to a scalar.
if self._expr.size != (1, 1):
raise Exception("The '%s' objective must resolve to a scalar."
% self.NAME)
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, repr(self._expr))
def __str__(self):
return ' '.join([self.NAME, self._expr.name()])
def canonicalize(self):
"""Pass on the target expression's objective and constraints.
"""
return self._expr.canonical_form
def variables(self):
"""Returns the variables in the objective.
"""
return self._expr.variables()
def parameters(self):
"""Returns the parameters in the objective.
"""
return self._expr.parameters()
def is_dcp(self):
"""The objective must be convex.
"""
return self._expr.is_convex()
@property
def value(self):
"""The value of the objective expression.
"""
return self._expr.value
@staticmethod
def primal_to_result(result):
"""The value of the objective given the solver primal value.
"""
return result
class Maximize(Minimize):
"""An optimization objective for maximization.
"""
NAME = "maximize"
def canonicalize(self):
"""Negates the target expression's objective.
"""
obj, constraints = super(Maximize, self).canonicalize()
return (lu.neg_expr(obj), constraints)
def is_dcp(self):
"""The objective must be concave.
"""
return self._expr.is_concave()
@staticmethod
def primal_to_result(result):
"""The value of the objective given the solver primal value.
"""
return -result
| StarcoderdataPython |
3261651 | """
This file is about how to load data from sklearn.
Library : sklearn
Moduale : datasets
Class : load_boston
Object : boston_data
data : Boston Data For House Prices
"""
# Import important libraries
from sklearn.datasets import load_boston
# Object of load_boston
boston_data = load_boston()
# Get X data and its information as shape, features, features_names and printing them
X = boston_data.data
X_shape = X.shape
feature_names = boston_data.feature_names
print('X Data is \n' , X[:10])
print('X shape is ' , X_shape)
print('X Features are \n' , feature_names)
# Get y data and its information as shape, features, features_names and printing them
y = boston_data.target
y_shape = y.shape
#target_names = boston_data.target_names
print('y Data is \n' , y[:10])
print('y shape is ' , y_shape)
#print('y Columns are \n' , target_names)
| StarcoderdataPython |
9695480 | from typing import Text
def good_phone(phone: Text) -> bool:
if not phone:
return False
if len(phone) != 13:
return False
if not phone.startswith("+375"):
return False
if not phone[4:].isdigit():
return False
return True
| StarcoderdataPython |
6662943 | <filename>raphael/app/modules/user/models.py<gh_stars>0
# encoding: utf-8
from __future__ import division, absolute_import, with_statement, print_function
import collections
from raphael.utils.dao.context import DBContext
from raphael.utils.dao import query
from raphael.utils import strings, cache, num, encrypt, time
class UserCacheById(cache.DBMemcached):
prefix = 'um_user'
@classmethod
def actual_save(cls, key, obj):
UserCacheByLoginid.flush_all()
super(UserCacheById, cls).actual_save(key, obj)
@classmethod
def actual_remove(cls, key):
obj = cls.get(key)
if obj and obj.get('loginid'):
UserCacheByLoginid.remove(obj.get('loginid'))
super(UserCacheById, cls).actual_remove(obj)
class UserCacheByLoginid(cache.DBMemcached):
"""
Do not use 'save' or 'remove' method in this class
"""
prefix = 'um_user'
index_key = 'loginid'
with_flush = True
def get_user_byid(oid):
return UserCacheById.get(oid)
def get_user_byloginid(logindid):
return UserCacheByLoginid.get(logindid)
def save_user(user):
UserCacheById.save_obj(user)
def find_users():
return DBContext().create_query("um_user", "1=1")
def delete_user(oid):
UserCacheById.remove(oid)
def make_password(password):
salt = strings.uuid()
return salt, encrypt.sha512(salt + password)
def check_user_password(user, password):
if user is not None:
if encrypt.sha512(user['salt'] + password) == user['password']:
return True
return False
class UserMenuCache(cache.AbstractMemcached):
prefix = 'mymenu'
with_flush = True
@classmethod
def actual_remove(cls, key):
pass
@classmethod
def actual_save(cls, key, obj):
pass
@classmethod
def actual_get(cls, user_id):
import copy
from operator import itemgetter
menus = []
ret = []
if get_user_byid(user_id) is not None:
my_menu_db = find_my_menu_db(user_id).order_by('name').fetch()
menus = copy.deepcopy(my_menu_db)
# serialize
for menu in menus:
if strings.is_blank(menu.get('parentid')):
menu['children'] = []
ret.append(menu)
for menu in menus:
if strings.is_not_blank(menu.get('parentid')):
for m in ret:
if m['id'] == menu['parentid']:
m['children'].append(menu)
for m in ret:
m['children'] = sorted(m['children'], key=itemgetter('sort'))
return sorted(ret, key=itemgetter('sort'))
def get_menu(oid):
context = DBContext()
return context.get("um_menu", oid)
def save_menu(menu):
assert isinstance(menu, dict)
context = DBContext()
context.save("um_menu", menu)
# clear my menu cache
UserMenuCache.flush_all()
def delete_menu(oid):
menu = get_menu(oid)
if menu is not None:
with DBContext() as ctx:
ctx.delete_byid("um_menu", oid)
# revise sort
ctx.execute('update um_menu set sort = sort - 1 where parentid = :parentid and sort > :sort', parentid=menu['parentid'], sort=menu['sort'])
# remove children
ctx.execute_delete('um_menu', 'parentid = :parentid', parentid=menu['id'])
# delete related auth
delete_auth_byidentity(oid, "UmMenu")
# clear my menu cache
UserMenuCache.flush_all()
def find_menu(**params):
sql = ['1=1']
cond = {}
if 'parentid' in params:
sql.append('parentid = :parentid')
cond['parentid'] = params['parentid']
if 'sort' in params:
sql.append('sort = :sort')
cond['sort'] = num.safe_int(params['sort'])
return DBContext().create_query("um_menu", ' and '.join(sql), **cond)
def move_menu(menu, operator):
with DBContext() as ctx:
changed = False
if operator == 'top':
if menu['sort'] != 1:
ctx.execute('update um_menu set sort = sort + 1 where parentid = :parentid and sort < :sort', parentid=menu['parentid'], sort=menu['sort'])
menu['sort'] = 1
changed = True
elif operator == 'up':
if menu['sort'] != 1:
ctx.execute('update um_menu set sort = sort + 1 where parentid = :parentid and sort = :sort', parentid=menu['parentid'], sort=menu['sort'] - 1)
menu['sort'] = menu['sort'] - 1
changed = True
elif operator == 'down':
if menu['sort'] != find_menu(parentid=menu['parentid']).count():
ctx.execute('update um_menu set sort = sort - 1 where parentid = :parentid and sort = :sort', parentid=menu['parentid'], sort=menu['sort'] + 1)
menu['sort'] = menu['sort'] + 1
changed = True
elif operator == 'bottom':
if menu['sort'] != find_menu(parentid=menu['parentid']).count():
ctx.execute('update um_menu set sort = sort - 1 where parentid = :parentid and sort > :sort', parentid=menu['parentid'], sort=menu['sort'])
menu['sort'] = find_menu(parentid=menu['parentid']).count()
changed = True
if changed:
ctx.save('um_menu', menu)
UserMenuCache.flush_all()
class UserFunctionCache(cache.AbstractMemcached):
@classmethod
def actual_remove(cls, key):
pass
@classmethod
def actual_save(cls, key, obj):
pass
@classmethod
def actual_get(cls, key):
sql = [
"select f.name from um_function f",
"right join (",
" select * from um_auth where sourceentity = 'UmFunction' and grantentity = 'UmUser' and grantid = :userid",
") a on f.id = a.sourceid"
]
funcs = DBContext().create_sql_query('\n'.join(sql), userid=key).fetch()
return [f.get('name') for f in funcs]
def get_function(oid):
context = DBContext()
return context.get("um_function", oid)
def save_function(obj):
UserFunctionCache.flush_all()
assert isinstance(obj, dict)
context = DBContext()
context.save("um_function", obj)
def delete_function(oid):
if oid is not None:
UserFunctionCache.flush_all()
context = DBContext()
context.delete_byid("um_function", oid)
# delete related auth
delete_auth_byidentity(oid, "UmFunction")
def find_functions(**params):
return DBContext().create_query("um_function", "1=1")
def get_auth(oid):
context = DBContext()
return context.get("um_auth", oid)
def find_auth(**params):
context = DBContext()
where = ['1=1']
argdict = {}
for attribute in 'sourceentity', 'sourceid', 'grantentity', 'grantid':
try:
value = params[attribute]
where.append('%s=:%s' % (attribute, attribute))
argdict[attribute] = value
except KeyError:
pass
for a in 'sourceentityin', 'sourceidin', 'grantentityin', 'grantidin':
try:
attribute = a[:-2]
values = params[a]
if not isinstance(values, collections.Iterable):
raise Exception('%s should be iterable', a)
where.append('%s in %s' % (attribute, query.escape_sequence(values)))
except KeyError:
pass
return context.create_query('um_auth', ' and '.join(where), **argdict)
def save_auth(auth):
assert isinstance(auth, dict)
context = DBContext()
context.save("um_auth", auth)
def get_auth_bydetail(source_id, source_entity, grant_id, grant_entity):
context = DBContext()
return context.create_query("um_auth", "sourceid=:sourceid and sourceentity=:sourceentity "
"and grantid=:grantid and grantentity=:grantentity",
sourceid=source_id, sourceentity=source_entity, grantid=grant_id,
grantentity=grant_entity
).first()
def delete_auth(oid):
if oid is not None:
context = DBContext()
context.delete_byid("um_auth", oid)
def delete_auth_byidentity(oid, entity):
context = DBContext()
context.execute_delete("um_auth", "(sourceid = :oid and sourceentity = :entity) or "
"(grantid = :oid and grantentity = :entity)",
oid=oid, entity=entity)
def find_menu_user_auth(menu_id):
context = DBContext()
sql_arr = [
"select u.id, u.loginid, u.name, a.id authid from um_user u",
"left join (",
" select id, grantid from um_auth",
" where sourceentity = :menuentity and sourceid = :menuid and grantentity = :userentity",
") a on u.id = a.grantid",
"where u.loginid <> 'admin'"
]
return context.create_sql_query("\n".join(sql_arr),
menuentity="UmMenu",
menuid=menu_id,
userentity="UmUser"
)
def find_my_menu(user_id):
return UserMenuCache.get(user_id)
def find_my_menu_db(user_id):
context = DBContext()
ret = []
user = get_user_byid(user_id)
if user is None:
return ret
if user["loginid"] == "admin":
return find_menu()
else:
sql = [
"select m.* from um_menu m",
"right join (",
" select * from um_auth where sourceentity = 'UmMenu' and grantentity = 'UmUser' and grantid = :userid",
") a on m.id = a.sourceid"
]
return context.create_sql_query("\n".join(sql), userid=user_id)
def find_function_user_auth(function_id):
context = DBContext()
sql_arr = [
"select u.id, u.loginid, u.name, a.id authid from um_user u",
"left join (",
" select id, grantid from um_auth",
" where sourceentity = :functionentity and sourceid = :functionid and grantentity = :userentity",
") a on u.id = a.grantid",
"where u.loginid <> 'admin'"
]
return context.create_sql_query("\n".join(sql_arr),
functionentity="UmFunction",
functionid=function_id,
userentity="UmUser"
)
def check_function_auth(user_id, *func_names):
user = get_user_byid(user_id)
if user is not None and user['loginid'] == 'admin':
return True
if len(func_names) == 0:
return True
user_funcs = UserFunctionCache.get(user_id)
# intersect
func_names_set = set(func_names)
inter = set(user_funcs) & func_names_set
return len(inter) == len(func_names_set)
def find_umsessions(**params):
sql_arr = ['1=1']
cond = {}
# token
try:
v = params['token']
sql_arr.append('token = :token')
cond['token'] = v
except KeyError:
pass
# user_id
try:
v = params['user_id']
sql_arr.append('user_id = :user_id')
cond['user_id'] = v
except KeyError:
pass
# expire_at
try:
v = params['gt_expire_at']
sql_arr.append('expire_at > :gt_expire_at')
cond['gt_expire_at'] = v
except KeyError:
pass
try:
v = params['lt_expire_at']
sql_arr.append('expire_at > :lt_expire_at')
cond['lt_expire_at'] = v
except KeyError:
pass
return DBContext().create_query('um_session', ' and '.join(sql_arr), **cond)
def get_umsession(oid):
return DBContext().get('um_session', oid)
def get_umsession_bytoken(token):
return find_umsessions(token=token, lt_expire_at=time.utcnow()).first()
def add_umsession(user_id, duration):
import datetime
token = strings.uuid()
DBContext().save('um_session', {
'token': token,
'user_id': user_id,
'expire_at': time.utcnow() + datetime.timedelta(seconds=duration),
})
return token
def verify_umsession(token):
return find_umsessions(token=token, lt_expire_at=time.utcnow()).count() > 0
def scrub_expired_umsessions():
DBContext().execute_delete('um_session', 'expire_at < :now', now=time.utcnow())
| StarcoderdataPython |
313464 | <reponame>dev-ciberc/ciberc-ca
import json
import os
import pandas as pd
class PingMerge:
def __init__(self, file_src, file_dst) -> None:
# --
# final dataframe compared and validated
self.data = None
# --
# contains the upload data of the files
self.file_src = file_src
self.file_dst = file_dst
self.data_src = None
self.data_dst = None
self.file_src_ext = None
self.file_dst_ext = None
# --
# dataframe with the source vrf
self.df_source = None
# --
# dataframe with the destination vrf
self.df_dest = None
# --
# columns for dataframe report baseline ping
self.columnsDataFrame = [
"src_device",
"src_ip_address",
"src_vrf",
"src_interface",
"src_mac",
"src_interface_ip_address",
"dst_device",
"dst_ip_address",
"dst_vrf",
"dst_interface",
"dst_mac",
"dst_interface_ip_address",
"initial_ping_percent",
"final_ping_percent",
"status"
]
self.BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# --
# load the files, source and destination
def loadFiles(self) -> None:
"""
load the files, source and destination
file_src: the source file vrf listing
file_dst: the destination file vrf listing
"""
# --
# load file source and identifier extension
file = open(self.file_src)
self.file_src_ext = os.path.splitext(self.file_src)[1]
if self.file_src_ext == '.json':
self.data_src = json.load(file)
else:
self.data_src = pd.read_excel(self.file_src)
# --
# load file destination and identifier extension
file_dst = open(self.file_dst)
self.file_dst_ext = os.path.splitext(self.file_dst)[1]
if self.file_dst_ext == '.json':
self.data_dst = json.load(file_dst)
else:
self.data_dst = pd.read_excel(self.file_dst)
def json_to_dataframe(self, data):
"""
json_to_dataframe:
data: the json data with the vrfs list
transform the json data to a dataframe
"""
columns = [
"device",
"source",
"ip_address",
"vrf",
"interface",
"mac",
"interface_ip_address",
"percent"
]
final_list = []
for key in data:
device = data[key]['data']
EC_DEVICE_NAME = device['name']
EC_DEVICE_HOSTNAME = device['hostname']
try:
EC_SOURCE = device['source']
except Exception:
EC_SOURCE = ''
# --
# listar las vrfs asignadas al equipo origen
# --
for vrf in device['list_vrf']:
EC_VRF_NAME = vrf['vrf_name']
if len(vrf['ips_arp']) > 0:
for ip in vrf["ips_arp"]:
EC_VRF_INTERFACE = ip['interface']
EC_VRF_MAC_ADDRESS = ip['mac']
EC_VRF_IP_ADDRESS = ip['ip_address']
try:
EC_VRF_PERCENT = ip["ping_arp"][0]['percent']
except Exception:
EC_VRF_PERCENT = ""
row = [
EC_DEVICE_NAME,
EC_SOURCE,
EC_DEVICE_HOSTNAME,
EC_VRF_NAME,
EC_VRF_INTERFACE,
EC_VRF_MAC_ADDRESS,
EC_VRF_IP_ADDRESS,
EC_VRF_PERCENT
]
final_list.append(row)
else:
row = [EC_DEVICE_NAME, EC_SOURCE,
EC_DEVICE_HOSTNAME, EC_VRF_NAME, "", "", "", ""]
final_list.append(row)
# --
# si el dispositivo no tiene vrfs asignadas
if len(device['list_vrf']) == 0:
row = [EC_DEVICE_NAME, EC_SOURCE,
EC_DEVICE_HOSTNAME, "", "", "", "", ""]
final_list.append(row)
return pd.DataFrame(final_list, columns=columns)
def excel_to_dataframe(self, data):
final_list = []
columns = [
"device",
"source",
"ip_address",
"vrf",
"interface",
"mac",
"interface_ip_address",
"percent"
]
for row in data.itertuples():
EC_DEVICE_NAME = row[1]
EC_SOURCE = row[2]
EC_DEVICE_HOSTNAME = row[3]
EC_VRF_NAME = row[4]
EC_VRF_INTERFACE = row[5]
EC_VRF_MAC_ADDRESS = row[6]
EC_VRF_IP_ADDRESS = row[7]
EC_VRF_PERCENT = row[8]
row = [
EC_DEVICE_NAME,
EC_SOURCE,
EC_DEVICE_HOSTNAME,
EC_VRF_NAME,
EC_VRF_INTERFACE,
EC_VRF_MAC_ADDRESS,
EC_VRF_IP_ADDRESS,
EC_VRF_PERCENT
]
final_list.append(row)
return pd.DataFrame(final_list, columns=columns)
# --
# return the data json/excel vrf to dataframe
def transform(self, data, ext):
if ext == ".json":
return self.json_to_dataframe(data)
else:
return self.excel_to_dataframe(data)
def createDataframeSourceOnly(self, origin, dest_device):
"""
createDataframeSourceOnly:
origin: the source device vrfs list
dest_device: the destination device vrfs list
when the source is validated against the
destination and exists only in the source
""" # noqa
df = pd.DataFrame(
[
[
origin.device,
origin.ip_address,
origin.vrf,
origin.interface,
origin.mac,
origin.interface_ip_address,
dest_device,
"",
"",
"",
"",
"",
int(origin.percent),
0,
origin.validate
]
],
columns=self.columnsDataFrame
)
return df
def createDataframeSourceDest(self, origin, dest):
"""
createDataframeSourceDest:
origin: the source device vrfs list
dest_device: the destination device vrfs list
when the destination is validated with the origin and both are found,
the ping percentage is validated
""" # noqa
df = pd.DataFrame(
[
[
origin.device.values[0],
origin.ip_address.values[0],
origin.vrf.values[0],
origin.interface.values[0],
origin.mac.values[0],
origin.interface_ip_address.values[0],
dest.device,
dest.ip_address,
dest.vrf,
dest.interface,
dest.mac,
dest.interface_ip_address,
int(origin.percent),
int(dest.percent),
dest.validate
]
],
columns=self.columnsDataFrame
)
return df
def createDataframeDestNew(self, dest, source_device):
"""
createDataframeDestNew:
origin: the source device vrfs list
dest_device: the destination device vrfs list
when the destination vrf does not exist in the source device,
it is cataloged as new
""" # noqa
df = pd.DataFrame(
[
[
source_device,
'',
'',
'',
'',
'',
dest.device,
dest.ip_address,
dest.vrf,
dest.interface,
dest.mac,
dest.interface_ip_address,
0,
int(dest.percent),
dest.validate
]
],
columns=self.columnsDataFrame
)
return df
def compareVrfs(self, dest, source) -> pd.DataFrame():
# --
# data frame que contendra la nueva estructura del reporte final baseline ping # noqa
data = pd.DataFrame(
columns=self.columnsDataFrame
)
# --
# lista de dispositivos agrupados por device, source
distinct_devices = \
dest.groupby(['device', 'source'])['device'].count()
for row in distinct_devices.index:
device = row[0]
source_device = row[1]
# --
# se filtran solo las vrfs del dispositivo origen
list_source_filter = source.loc[source['device'] == source_device]
# --
# se filtran solo las vrfs del dispositivo destino
list_dst_filter = dest.loc[dest['device'] == device]
# --
# listado de vrf del dispositivo destino
list_unique_vrf_dst = list_dst_filter['vrf'].unique()
# --
# listado de vrf del dispositivo origen
list_unique_vrf_src = list_source_filter['vrf'].unique()
# --
# listado completo de las vrfs de los dispositivos
union_vrfs = \
(set((list(list_unique_vrf_src) + list(list_unique_vrf_dst))))
# --
# las vrf que solo existen en el destino son categorizadas [nuevas = NEW] # noqa
# las vrf que existen en origen, destino con los mismos parametros con [OK] # noqa
# las vrf que existen en origin, destino con diferentes parametros con [FAIL] # noqa
for vrf in union_vrfs:
# --
# segun la vrf unica del destino se filtra la vrf del origen # noqa
list_vrf_source = list_source_filter.loc[list_source_filter['vrf'] == vrf] # noqa
# --
# segun la vrf unica del destino se filtra su propio dispositivo # noqa
list_vrf_dest = list_dst_filter.loc[list_dst_filter['vrf'] == vrf] # noqa
# --
# se buscan las vrf destino en el origen
for _, item in list_vrf_dest.iterrows():
vrf_item_source = list_vrf_source.loc[
(list_vrf_source['vrf'] == item.vrf)
& (list_vrf_source['interface'] == item.interface)
& (list_vrf_source['interface_ip_address'] == item.interface_ip_address) # noqa
] # noqa
if vrf_item_source.empty: # noqa
item['validate'] = 'NEW'
try:
data = pd.concat(
[data, self.createDataframeDestNew(item, source_device)]) # noqa
except Exception:
# si no hay datos en ambos data frame no es valido el # noqa
# catalogado como new (vacio)
pass
else:
if item.percent >= vrf_item_source.percent.values[0]:
item['validate'] = 'OK'
else:
item['validate'] = 'FAIL'
# se crea dataframe con la vrf destino, como la origen
data = pd.concat(
[data, self.createDataframeSourceDest(vrf_item_source, item)]) # noqa
# --
# El ultimo proceso es buscar todas las vrf origin que no existan en destino # noqa
for vrf_source in list_unique_vrf_src:
# --
# segun la vrf unica del origin se filtra asi misma
list_vrf_source = \
list_source_filter.loc[list_source_filter['vrf']
== vrf_source]
# --
# segun la vrf unica del origen se filtran las destino
list_vrf_dest = list_dst_filter.loc[list_dst_filter['vrf'] == vrf_source] # noqa
# --
# se buscan las vrf origen para que no existan en el destino
for _, item in list_vrf_source.iterrows():
vrf_item = list_vrf_dest.loc[
(list_vrf_dest['vrf'] == item.vrf)
& (list_vrf_dest['interface'] == item.interface)
& (list_vrf_dest['interface_ip_address'] == item.interface_ip_address) # noqa
] # noqa
if vrf_item.empty: # noqa
item['validate'] = 'FAIL'
data = pd.concat(
[data, self.createDataframeSourceOnly(item, device)]) # noqa
return data
def data_json(self):
# --
# se transforma el dataframe en un json
self.data.to_json(f'reporte_vrf.json', orient='records') # noqa
return self.data
def data_excel(self, file_name):
# --
# se transforma el dataframe en un excel
try:
self.data.to_excel(f'{file_name}.xlsx', index=False)
except Exception:
return False
return True
def run(self) -> None:
# --
# load the files, to precess
self.loadFiles()
# --
# transform the json vrf source to dataframe
self.df_source = self.transform(self.data_src, self.file_src_ext)
# --
# transform the json vrf destination to dataframe
self.df_dest = self.transform(self.data_dst, self.file_dst_ext)
# --
# compare the vrfs
self.data = self.compareVrfs(self.df_dest, self.df_source)
| StarcoderdataPython |
1856497 | <reponame>jovi521/swsw
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
import sys
import os
import time
from fy4a import FY4A_AGRI_L1
def create_img(file_path, geo_range, save_dir):
'''
file_path:需要解析的文件路径
geo_range:需要裁剪的区域范围和粒度,格式:最小纬度,最大纬度,最小经度,最大经度,粒度 例如:10, 54, 70, 140, 0.1
save_path:保存路径
'''
# 获得文件名
filename = file_path.split('\\')[-1]
# 从文件名中获得时间
start_time = filename.split('_')[-4]
# 将世界时转化为北京时
time_array = time.strptime(start_time, "%Y%m%d%H%M%S")
time_stamp = int(time.mktime(time_array)) + 8 * 3600
time_array = time.localtime(time_stamp)
other_style_time = time.strftime('%Y%m%d%H%M%S', time_array)
yyyyMMdd = other_style_time[0:8]
# 卫星类型
satellite_type = 'FY4A'
# 通道号
channel_number = 'Channel02'
# 读取文件,获得fy4a对象
fy4a_agri_l1 = FY4A_AGRI_L1(file_path)
# 选择通道和区域
fy4a_agri_l1.extract('Channel02', geo_range)
# 获得通道对象
channel12 = fy4a_agri_l1.channels['Channel02']
# 绘图
# 设置图片大小和dpi
# plt.subplot(1, 1, 1)
plt.figure(figsize=(10, 8), dpi=400)
lat_S, lat_N, lon_W, lon_E, step = eval(geo_range)
channel12 = np.array(channel12)
channel12 = np.flip(channel12, axis=0)
Basemap(projection='merc', llcrnrlat=lat_S, urcrnrlat=lat_N, \
llcrnrlon=lon_W, urcrnrlon=lon_E, lat_ts=5, resolution='c')
x = np.arange(lon_W, lon_E + 0.1, 0.1)
y = np.arange(lat_S, lat_N + 0.1, 0.1)
xx, yy = np.meshgrid(x, y)
plt.contourf(xx, yy, channel12, cmap='gray')
# plt.contourf(xx, yy, channel12)
# 去除边框
plt.axis('off')
img_name = '{}{}{}{}{}{}'.format('C002', '_', other_style_time, '_', satellite_type, '.png')
save_dir = '{}{}{}{}{}{}'.format(save_dir, satellite_type, '/', yyyyMMdd, '/', channel_number.upper())
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_path = '{}{}{}'.format(save_dir, '/', img_name)
plt.savefig(save_path, transparent=True, bbox_inches='tight', pad_inches=0)
if __name__ == '__main__':
file_path = sys.argv[1]
geo_range = sys.argv[2]
save_path = sys.argv[3]
# file_path = 'D:/Z_SATE_C_BAWX_20201217062328_P_FY4A-_AGRI--_N_DISK_1047E_L2-_LSE-_MULT_NOM_20201217060000_20201217061459_012KM_V0001.NC'
# color_dict = 'D:/color_dict.txt'
# geo_range = '10,54,70,140,0.1'
# save_path = 'D:/China.png'
# file_path = 'D:\\Data\\Z_SATE_C_BAWX_20210130084157_P_FY4A-_AGRI--_N_REGC_1047E_L1-_FDI-_MULT_NOM_20210130083418_20210130083835_4000M_V0001.HDF'
# geo_range = '10,54,70,140,0.1'
# save_path = 'D:/Data/satellite_parse/'
create_img(file_path,geo_range,save_path) | StarcoderdataPython |
88365 | import pandas as pd
import numpy as np
import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import OneHotEncoder
from sklearn.decomposition import PCA , TruncatedSVD
import joblib
from sklearn.manifold import TSNE
# import seaborn as sns
import matplotlib.pyplot as plt
class preprocessor() :
"""class to read the dataset and clean it for for furthur processsing
"""
def __init__(self , DATASET_PATH = '../data/dataset_' , from_file = True) :
"""constructor for the preprocessord class. It specifies the path to dataset
Parameters
----------
DATASET_PATH : str, optional
path to the dataset, by default 'data/dataset_' for all splitted files
"""
# If you want to use the single file i.e.DATASET_PATH = 'data/training.1600000.processed.noemoticon.csv'
# then self.df = self.read_dataset(DATASET_PATH, join_flag = False)
if(from_file == False) :
self.df = self.read_dataset(DATASET_PATH) # setter for the dataset
def read_dataset(self , DATASET_PATH , join_flag = True , ext = '.csv') :
"""function to extract the dataset (dataframe) from the specified file path
Parameters
----------
DATASET_PATH : string
path to dataset
join_flag : boolean
flag to indicate whether to extract data from splited files or a single file
ext : string
extenstion of splitted files (only to be used when join_flag = True), by default '.csv.'
Returns
-------
pandas dataframe
data extracted from file at specified path
"""
columns = [ 'target' , 'ID' , 'date' , 'flag' , 'user' , 'text' ] # naming the columns
if(join_flag) : # joining dataset
frames = [] # dataset was divided by 'split -C 20971520 -d training.1600000.processed.noemoticon.csv --additional-suffix=.csv dataset_' where 20971520 B = 20 MB
for i in range(12) :
frames.append(pd.read_csv(DATASET_PATH + str(i).zfill(2) + ext , encoding = "ISO-8859-1" , header=None , names=columns))
df = pd.concat(frames , ignore_index=True)
else :
df = pd.read_csv(DATASET_PATH , encoding = "ISO-8859-1" , header= None , names = columns)
df.loc[df['target'] == 4, 'target'] = 1 # changing the target value from 4 to 1
return df # returning dataset
def __get_day(self,x) :
"""function to tell the day (int) of tweat based upon date-time
Parameters
----------
x : string-like
Date-time of tweat
Returns
-------
int
number associated with the day i.e., (0: Monday, 1: Tuesday, 2: Wednessday, 3: Thursday, 4: Friday, 5: Saturday, 6: Sunday, -1: None)
"""
days = ['Mon' , 'Tue' , 'Wed' , 'Thu' , 'Fri' , 'Sat' , 'Sun']
d = x[:3] # sliciing the day string from date-time string
if(d in days) :
return days.index(d)
return -1 # -1 if day is not known
def get_user_resolved(self) :
"""function to make usefull feature out of user feature (which contain usernames)
We have appliad one-hot-encoding to extract the uniqueness and repeatition of a user.
Since the there were too many unique users (i.e. high dimensional data), hence dimension reduction is done
Returns
-------
numpy 2D array
Array contains resolved features of user column
"""
user_ndarr = self.df['user'].to_numpy().reshape(-1,1)
encoder = OneHotEncoder()
encoder = encoder.fit(user_ndarr)
hot_coded = encoder.transform(user_ndarr) # hot_coded is scipy.sparse.csr.csr_matrix, which is a memory efficent way of storing 1-hot-coded matrix
tsvd = TruncatedSVD(n_components= 50)
return tsvd.fit(hot_coded).transform(hot_coded)
# TODO : what to choose TVSD and PCA --> also add this docstring 'by using PCA'
# dim_red = PCA(n_components=2)
# dim_red.fit(hot_coded)
# return dim_red.transform(hot_coded)
def remove_pattern(self , text , pattern):
"""function to clean the tweats for furtur processing.
Here we are removing the specified pattern from text
Parameters
----------
text : string
the text of tweat
pattern : string
the pattern to be removed
Returns
-------
string
cleaned tweat
"""
r = re.findall(pattern,text) # finds the pattern i.e @user and puts it in a list for further task
for i in r:
text = re.sub(i,"",text)
return text
def preprocess(self , FILE_PATH = '../data/preprocessed') :
"""function to preprocess the dataframe and return dependent (X) and independent (y)
Parameters
----------
FILE_PATH : string
path to the pickle file
Returns
-------
X : numpy 2D array
it is the array of features
y : numpy 1D array
it is the array of labels
"""
try :
X , y = joblib.load(FILE_PATH)
print('Extracted from stored file')
except :
print('Preprocessing data')
day = self.df.date.apply(lambda x : self.__get_day(x))
self.df['date'] = pd.to_datetime(self.df['date'])
date = self.df.date.apply(lambda x : x.day)
month = self.df.date.apply(lambda x : x.month)
year = self.df.date.apply(lambda x : x.year)
time_in_minutes = self.df.date.apply(lambda x : x.minute + x.hour * 60)
usr = self.get_user_resolved()
self.df['Tidy_Tweets'] = np.vectorize(self.remove_pattern)(self.df['text'], "@[\w]*")
self.df['Tidy_Tweets'] = self.df['Tidy_Tweets'].str.replace("[^a-zA-Z#]", " ")
self.df['Tidy_Tweets'] = self.df['Tidy_Tweets'].apply(lambda x: ' '.join([w for w in x.split() if len(w)>3]))
# Bag of Words
bow_vectorizer = CountVectorizer(max_df=0.90, min_df=2, max_features=1000, stop_words='english')
# bag-of-words feature matrix
bow = bow_vectorizer.fit_transform(self.df['Tidy_Tweets'])
# df_bow = pd.DataFrame(bow.todense())
# train_bow = bow
tsvd = TruncatedSVD(n_components=200)
tweets_resolved = tsvd.fit_transform(bow)
usr = np.append(usr , tweets_resolved , axis=1)
X = pd.concat ([ day , date , month , year , time_in_minutes ] , axis = 1).to_numpy()
X = np.append(X,usr , axis=1)
# X = 1
y = self.df['target'].to_numpy()
joblib.dump((X,y) , FILE_PATH)
return X , y
class EDA() :
"""class to perform the exploratory data analysis on the data
"""
def scatter_plot(self, X, y):
"""function to apply tsne on the data to get reduce it to 2 dimension, and plot the resulted dimensions
Parameters
----------
X : Pandas dataframe
Dataframe of the preprocessed feature X
y : Pandas dataframe
Dataframe of the label for every corresponding datapoint in X
"""
tsvd = TruncatedSVD(n_components= 10)
X = tsvd.fit(X).transform(X)
print('starting TSNE')
NNfeatures = TSNE(n_components = 2).fit_transform(X)
print('ending TSNE')
self.__plot_cluster(NNfeatures , y , 'Scatter plot')
def __plot_cluster(self, X , y , title) :
"""function to plot the cluster with diffren colors associated with labels
Args:
X (numpy 2D array): It is the set of independent variable
y (numpy 1D aray): It is the dependent vaibale respective to X
"""
D1 = X[:,0] # extracting the dimension one
D2 = X[:,1] # extracting the dimension two
# print(D1.shape , D2.shape, y.shape)
plt.figure('Scatter plot')
plt.xlabel('D0')
plt.ylabel('D1')
a = plt.scatter(D1 , D2 , c = y) # ploting the scatter plot
plt.legend(*a.legend_elements(),loc = 'best')
plt.title(title)
# plt.show() # showing the plot
plt.savefig('../plot_images/'+title+'.png')
# def basic_info(self , ) :
# pass
# def
| StarcoderdataPython |
4826825 | <filename>tests/test_0341-parquet-reader-writer.py
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE
from __future__ import absolute_import
import sys
import os
import pytest
import numpy
import awkward1
pyarrow_parquet = pytest.importorskip("pyarrow.parquet")
def test_write_read(tmp_path):
array1 = awkward1.Array([[1, 2, 3], [], [4, 5], [], [], [6, 7, 8, 9]])
array2 = awkward1.repartition(array1, 2)
array3 = awkward1.Array(
[
{"x": 1, "y": 1.1},
{"x": 2, "y": 2.2},
{"x": 3, "y": 3.3},
{"x": 4, "y": 4.4},
{"x": 5, "y": 5.5},
{"x": 6, "y": 6.6},
{"x": 7, "y": 7.7},
{"x": 8, "y": 8.8},
{"x": 9, "y": 9.9},
]
)
array4 = awkward1.repartition(array3, 2)
awkward1.to_parquet(array1, os.path.join(tmp_path, "array1.parquet"))
awkward1.to_parquet(array2, os.path.join(tmp_path, "array2.parquet"))
awkward1.to_parquet(array3, os.path.join(tmp_path, "array3.parquet"))
awkward1.to_parquet(array4, os.path.join(tmp_path, "array4.parquet"))
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array1.parquet"))
) == awkward1.to_list(array1)
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array2.parquet"))
) == awkward1.to_list(array2)
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array3.parquet"))
) == awkward1.to_list(array3)
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array4.parquet"))
) == awkward1.to_list(array4)
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array1.parquet"), lazy=True)
) == awkward1.to_list(array1)
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array2.parquet"), lazy=True)
) == awkward1.to_list(array2)
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array3.parquet"), lazy=True)
) == awkward1.to_list(array3)
assert awkward1.to_list(
awkward1.from_parquet(os.path.join(tmp_path, "array4.parquet"), lazy=True)
) == awkward1.to_list(array4)
def test_explode(tmp_path):
array3 = awkward1.Array(
[
[{"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}, {"x": 3, "y": 3.3}],
[],
[{"x": 4, "y": 4.4}, {"x": 5, "y": 5.5}],
[],
[],
[
{"x": 6, "y": 6.6},
{"x": 7, "y": 7.7},
{"x": 8, "y": 8.8},
{"x": 9, "y": 9.9},
],
]
)
array4 = awkward1.repartition(array3, 2)
awkward1.to_parquet(array3, os.path.join(tmp_path, "array3.parquet"), explode_records=True)
awkward1.to_parquet(array4, os.path.join(tmp_path, "array4.parquet"), explode_records=True)
assert awkward1.from_parquet(os.path.join(tmp_path, "array3.parquet")) == [
{"x": [1, 2, 3], "y": [1.1, 2.2, 3.3]},
{"x": [], "y": []},
{"x": [4, 5], "y": [4.4, 5.5]},
{"x": [], "y": []},
{"x": [], "y": []},
{"x": [6, 7, 8, 9], "y": [6.6, 7.7, 8.8, 9.9]},
]
assert awkward1.from_parquet(os.path.join(tmp_path, "array4.parquet")) == [
{"x": [1, 2, 3], "y": [1.1, 2.2, 3.3]},
{"x": [], "y": []},
{"x": [4, 5], "y": [4.4, 5.5]},
{"x": [], "y": []},
{"x": [], "y": []},
{"x": [6, 7, 8, 9], "y": [6.6, 7.7, 8.8, 9.9]},
]
def test_oamap_samples():
assert awkward1.to_list(
awkward1.from_parquet("tests/samples/list-depths-simple.parquet")
) == [
{"list0": 1, "list1": [1]},
{"list0": 2, "list1": [1, 2]},
{"list0": 3, "list1": [1, 2, 3]},
{"list0": 4, "list1": [1, 2, 3, 4]},
{"list0": 5, "list1": [1, 2, 3, 4, 5]},
]
assert awkward1.to_list(
awkward1.from_parquet("tests/samples/nullable-record-primitives.parquet")
) == [
{
"u1": None,
"u4": 1,
"u8": None,
"f4": 1.100000023841858,
"f8": None,
"raw": b"one",
"utf8": "one",
},
{
"u1": 1,
"u4": None,
"u8": 2,
"f4": 2.200000047683716,
"f8": None,
"raw": None,
"utf8": None,
},
{
"u1": None,
"u4": None,
"u8": 3,
"f4": None,
"f8": None,
"raw": b"three",
"utf8": None,
},
{
"u1": 0,
"u4": None,
"u8": 4,
"f4": None,
"f8": 4.4,
"raw": None,
"utf8": None,
},
{
"u1": None,
"u4": 5,
"u8": None,
"f4": None,
"f8": 5.5,
"raw": None,
"utf8": "five",
},
]
assert awkward1.to_list(
awkward1.from_parquet("tests/samples/nullable-record-primitives-simple.parquet")
) == [
{"u4": None, "u8": 1},
{"u4": None, "u8": 2},
{"u4": None, "u8": 3},
{"u4": None, "u8": 4},
{"u4": None, "u8": 5},
]
assert awkward1.to_list(
awkward1.from_parquet("tests/samples/record-primitives.parquet")
) == [
{
"u1": 0,
"u4": 1,
"u8": 1,
"f4": 1.100000023841858,
"f8": 1.1,
"raw": b"one",
"utf8": "one",
},
{
"u1": 1,
"u4": 2,
"u8": 2,
"f4": 2.200000047683716,
"f8": 2.2,
"raw": b"two",
"utf8": "two",
},
{
"u1": 1,
"u4": 3,
"u8": 3,
"f4": 3.299999952316284,
"f8": 3.3,
"raw": b"three",
"utf8": "three",
},
{
"u1": 0,
"u4": 4,
"u8": 4,
"f4": 4.400000095367432,
"f8": 4.4,
"raw": b"four",
"utf8": "four",
},
{
"u1": 0,
"u4": 5,
"u8": 5,
"f4": 5.5,
"f8": 5.5,
"raw": b"five",
"utf8": "five",
},
]
# awkward1.to_list(awkward1.from_parquet("tests/samples/list-depths.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/list-depths-records-list.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/list-depths-records.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/list-depths-strings.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/list-lengths.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/nonnullable-depths.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/nullable-depths.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/nullable-list-depths.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/nullable-list-depths-records-list.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/nullable-list-depths-records.parquet"))
# awkward1.to_list(awkward1.from_parquet("tests/samples/nullable-list-depths-strings.parquet"))
# Arrow 2.0.0 broke this (or was it broken before?)
# assert awkward1.to_list(
# awkward1.from_parquet("tests/samples/nullable-levels.parquet")
# ) == [
# {"whatever": {"r0": {"r1": {"r2": {"r3": 1}}}}},
# {"whatever": {"r0": {"r1": {"r2": {"r3": None}}}}},
# {"whatever": {"r0": {"r1": {"r2": None}}}},
# {"whatever": {"r0": {"r1": None}}},
# {"whatever": {"r0": {"r1": None}}},
# {"whatever": {"r0": {"r1": None}}},
# {"whatever": {"r0": {"r1": {"r2": None}}}},
# {"whatever": {"r0": {"r1": {"r2": {"r3": None}}}}},
# {"whatever": {"r0": {"r1": {"r2": {"r3": 1}}}}},
# ]
| StarcoderdataPython |
9772064 | # %%
import pandas as pd
# %%
full_df = pd.read_csv("train/iris.csv")
# %%
sample = full_df.groupby("class").apply(lambda x: x.sample(n=10))
# %%
sample.drop(columns=["class"], inplace=True)
# %%
sample.to_json("test_batch_inference_input.jsonlines", orient="records", lines=True)
# %%
| StarcoderdataPython |
1621062 | from typing import List, Tuple
import pp
from pp.component import Component
@pp.autoname
def coupler_straight(
length: float = 10.0,
width: float = 0.5,
gap: float = 0.27,
layer: Tuple[int, int] = pp.LAYER.WG,
layers_cladding: List[Tuple[int, int]] = [pp.LAYER.WGCLAD],
cladding_offset: float = 3.0,
) -> Component:
""" straight coupled waveguides. Two multimode ports
.. plot::
:include-source:
import pp
c = pp.c.coupler_straight()
pp.plotgds(c)
"""
c = Component()
# Top path
c.add_polygon([(0, 0), (length, 0), (length, width), (0, width)], layer=layer)
y = width + gap
# Bottom path
c.add_polygon(
[(0, y), (length, y), (length, width + y), (0, width + y)], layer=layer
)
# One multimode port on each side
port_w = width * 2 + gap
c.add_port(name="W0", midpoint=[0, port_w / 2], width=port_w, orientation=180)
c.add_port(name="E0", midpoint=[length, port_w / 2], width=port_w, orientation=0)
c.width = width
c.length = length
# cladding
ymax = 2 * width + gap + cladding_offset
for layer_cladding in layers_cladding:
c.add_polygon(
[
(0, -cladding_offset),
(length, -cladding_offset),
(length, ymax),
(0, ymax),
],
layer=layer_cladding,
)
return c
@pp.autoname
def coupler_straight_biased(length=10, width=0.5, gap=0.27, layer=pp.LAYER.WG):
return coupler_straight(
width=pp.bias.width(width), gap=pp.bias.gap(gap), length=length, layer=layer
)
def _demo():
c = coupler_straight(gap=0.2)
pp.write_gds(c)
return c
if __name__ == "__main__":
# c = _demo()
c = coupler_straight_biased(width=0.5, gap=0.2)
pp.show(c)
| StarcoderdataPython |
12850893 | import os
import random
import numpy as np
import pandas as pd
def set_random_seed(seed=42):
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
def set_display_options():
pd.set_option("max_colwidth", 1000)
pd.set_option("max_rows", 50)
pd.set_option("max_columns", 100)
pd.options.display.float_format = "{:,.2f}".format
| StarcoderdataPython |
6403829 | from exapi.models_mappers.hitbtc.base.interface import IHitbtcBaseModelsMapper
from exapi.models_mappers.hitbtc.base.mapper import HitbtcBaseModelsMapper
| StarcoderdataPython |
3282286 | <filename>CmBoy.py
#!/usr/bin/env python3
import json
import argparse
from cm_boy.CmAlgo import CmAlgo
from cm_boy.CmBark import CmBark
from cm_boy.CmClient import CmClient
from cm_boy.CmFilter import CmFilter
from cm_boy.CmSession import CmSession
def main(forward_args=None):
"""
a good boy that first gets your account data, gets your stock processes each card and uploads the cards that have a new price.
"""
good_cm_boy = CmBoy(forward_args=forward_args)
good_cm_boy.come()
good_cm_boy.fetch()
good_cm_boy.chew()
good_cm_boy.put()
class CmBoy:
def __init__(self, forward_args=None):
with open("data/config.json", "r") as json_config:
self.config = json.load(json_config)
self.parser = argparse.ArgumentParser(description='This Boy handles all the cardmarket stuff, good boy!')
self._setup_parser(forward_args=forward_args)
self.cm_client = CmClient(self.config)
self.cm_filter = CmFilter(self.config)
self.cm_session = CmSession(self.config["urls"]["base_url"])
self.cm_algo = CmAlgo(self.config, self.args)
self.cm_bark = CmBark(self.args.quiet, self.args.outFile)
self.card_inventory = {}
def come(self):
success, reason, account_data = self.cm_client.get_account_data()
if success:
self.username = account_data["account"]["username"]
self.sell_count = account_data["account"]["sellCount"]
self.cm_bark.come(self.username)
self.config["listing_static_filter"]["seller_country"] = account_data["account"]["country"]
else:
raise ValueError("Could not get account data! Reason: {}".format(reason))
def fetch(self):
self.cm_bark.get_stock()
success, reason, self.card_inventory = self.cm_client.get_account_stock()
if success:
self.cm_filter.stock_filter(self.card_inventory)
self.cm_bark.stock_statistics(self.card_inventory)
else:
raise ValueError("Could not get card inventory! Reason: {}".format(reason))
def chew(self):
self.cm_bark.start_chew()
for card in self.card_inventory["article"]:
self.cm_bark.update_current_card(card)
parameter = self.cm_algo._parameter_for_card(card)
success, reason, listing = self.cm_client.get_card_listing(card["idProduct"], user_params=parameter)
if success:
self.cm_filter.prefilter(listing, card)
self.cm_algo.adjust_price(card, listing, self.sell_count, self.username)
else:
self.cm_bark.print_error("Could not get listings for card {}! Reason: {}".format(card["product"]["enName"], reason))
self.cm_bark.end_chew_message()
self.cm_bark.end_chew()
def put(self):
self.cm_bark.put_start_message(self.args.dryrun, self.cm_algo.list_of_cards_with_changed_prices)
if not self.args.dryrun:
for card in self.cm_algo.list_of_cards_with_changed_prices:
success, reason, listing = self.cm_client.put_card_price(card["card"])
if not success:
self.cm_bark.print_error("Could not upload card {}! Reason: {}".format(card["card"]["product"]["enName"], reason))
for card in self.cm_algo.list_of_cards_with_changed_prices:
self.cm_bark.price_update_statistic(card)
def _setup_parser(self, forward_args):
self.parser.add_argument("-d", "--dryrun", action="store_true", help="Do NOT upload the cards with adjusted prices.")
self.parser.add_argument("-q", "--quiet", action="store_true", help="Disable all output to the command line.")
self.parser.add_argument("-f", "--forcePriceSet", action="store_true", help="Regardless of the current position, update the prices.")
self.parser.add_argument("-o", "--outFile", nargs='?', const='', help="Absolute path to folder where log files are stored. If empty, log is stored in CmBoy's folder.")
if forward_args is None:
self.args = self.parser.parse_args()
else:
self.args = self.parser.parse_args(forward_args)
if __name__ == "__main__":
main()
| StarcoderdataPython |
5047748 | from typing import Dict
import argparse
import logging
from overrides import overrides
from allennlp.commands.subcommand import Subcommand
from allentune.commands.report import Report
from allentune.commands.search import Search
from allentune.commands.plot import Plot
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class ArgumentParserWithDefaults(argparse.ArgumentParser):
"""
Custom argument parser that will display the default value for an argument
in the help message.
"""
_action_defaults_to_ignore = {"help", "store_true", "store_false", "store_const"}
@staticmethod
def _is_empty_default(default):
if default is None:
return True
if isinstance(default, (str, list, tuple, set)):
return not bool(default)
return False
@overrides
def add_argument(self, *args, **kwargs):
# pylint: disable=arguments-differ
# Add default value to the help message when the default is meaningful.
default = kwargs.get("default")
if kwargs.get("action") not in self._action_defaults_to_ignore and not self._is_empty_default(default):
description = kwargs.get("help") or ""
kwargs["help"] = f"{description} (default = {default})"
super().add_argument(*args, **kwargs)
def main(prog: str = None) -> None:
"""
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``
codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't
work for them, unless you use the ``--include-package`` flag.
"""
# pylint: disable=dangerous-default-value
parser = ArgumentParserWithDefaults(description="Run AllenTune", usage='%(prog)s', prog=prog)
subparsers = parser.add_subparsers(title='Commands', metavar='')
subcommands = {
# Default commands
"search": Search(),
"report": Report(),
"plot": Plot()
}
for name, subcommand in subcommands.items():
subparser = subcommand.add_subparser(name, subparsers)
args = parser.parse_args()
# If a subparser is triggered, it adds its work as `args.func`.
# So if no such attribute has been added, no subparser was triggered,
# so give the user some help.
if 'func' in dir(args):
args.func(args)
else:
parser.print_help() | StarcoderdataPython |
4904148 | <reponame>Samuel-Melo890/Python-Desafios
print('='*8,'Tratando Vários Valores v1.0','='*8)
n = qn = s = 0
while n != 999:
n = int(input('Digite um número inteiro qualquer [999 é a condição de parada]: '))
if n != 999:
qn += 1
s += n
print('Você digitou {} números e o valor da soma entre eles foi de {}.'.format(qn, s))
| StarcoderdataPython |
8187961 | <gh_stars>10-100
import pickle
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from toontown.toonbase import TTLocalizer
class DistributedLeaderBoardAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedLeaderBoardAI')
def __init__(self, air, name, x, y, z, h, p, r):
DistributedObjectAI.__init__(self, air)
self.name = name
self.posHpr = (x, y, z, h, p, r)
self.records = {}
self.subscriptions = []
self.currentIndex = -1
def announceGenerate(self):
DistributedObjectAI.announceGenerate(self)
self.accept('UpdateRaceRecord', self.handleUpdateRaceRecord)
self.accept('GS_LeaderBoardSwap' + str(self.zoneId), self.updateDisplay)
def getName(self):
return self.name
def getPosHpr(self):
return self.posHpr
def subscribeTo(self, subscription):
self.records.setdefault(subscription[0], {})[subscription[1]] = [(x[0], x[3]) for x in
self.air.raceMgr.getRecords(subscription[0],
subscription[1])]
self.subscriptions.append(subscription)
def handleUpdateRaceRecord(self, record):
trackId, period = record
if trackId not in self.records:
return
self.records[trackId][period] = [(x[0], x[3]) for x in self.air.raceMgr.getRecords(trackId, period)]
def updateDisplay(self):
self.currentIndex += 1
if self.currentIndex >= len(self.subscriptions):
self.currentIndex = 0
trackName = TTLocalizer.KartRace_TrackNames[self.subscriptions[self.currentIndex][0]]
periodName = TTLocalizer.RecordPeriodStrings[self.subscriptions[self.currentIndex][1]]
leaderList = self.records[self.subscriptions[self.currentIndex][0]][self.subscriptions[self.currentIndex][1]]
self.sendUpdate('setDisplay', [pickle.dumps((trackName, periodName, leaderList))])
| StarcoderdataPython |
5008487 | ## @ingroupMethods-Noise-Fidelity_One-Noise_Tools
# print_airframe_output.py
#
# Created: Oct 2020, <NAME>
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import numpy as np
from SUAVE.Core import Units
## @ingroupMethods-Noise-Fidelity_One-Noise_Tools
def print_airframe_output(SAE_Airframe_Noise_Outputs):
"""This prints the airframe noise of a turbofan aircraft
Assumptions:
N/A
Inputs:
SAE_Airframe_Noise_Outputs - Airframe Noise Data Structure
Outputs:
N/A
Properties Used:
None
"""
tag = SAE_Airframe_Noise_Outputs.tag
filename = SAE_Airframe_Noise_Outputs.filename
velocity = SAE_Airframe_Noise_Outputs.velocity
nsteps = SAE_Airframe_Noise_Outputs.nsteps
time = SAE_Airframe_Noise_Outputs.time
altitude = SAE_Airframe_Noise_Outputs.altitude
M = SAE_Airframe_Noise_Outputs.M
angle = SAE_Airframe_Noise_Outputs.angle
distance_vector = SAE_Airframe_Noise_Outputs.distance_vector
PNLT_wing = SAE_Airframe_Noise_Outputs.PNLT_wing
phi = SAE_Airframe_Noise_Outputs.phi
PNLT_ht = SAE_Airframe_Noise_Outputs.PNLT_ht
PNLT_vt = SAE_Airframe_Noise_Outputs.PNLT_vt
PNLT_flap = SAE_Airframe_Noise_Outputs.PNLT_flap
PNLT_slat = SAE_Airframe_Noise_Outputs.PNLT_slat
PNLT_nose_landing_gear = SAE_Airframe_Noise_Outputs.PNLT_nose_landing_gear
PNLT_main_landing_gear = SAE_Airframe_Noise_Outputs.PNLT_main_landing_gear
PNLT_total = SAE_Airframe_Noise_Outputs.PNLT_total
SPLt_dBA_max = SAE_Airframe_Noise_Outputs.SPLt_dBA_max
nrange = SAE_Airframe_Noise_Outputs.nrange
frequency = SAE_Airframe_Noise_Outputs.frequency
EPNL_wing = SAE_Airframe_Noise_Outputs.EPNL_wing
EPNL_ht = SAE_Airframe_Noise_Outputs.EPNL_ht
EPNL_vt = SAE_Airframe_Noise_Outputs.EPNL_vt
EPNL_flap = SAE_Airframe_Noise_Outputs.EPNL_flap
EPNL_slat = SAE_Airframe_Noise_Outputs.EPNL_slat
EPNL_nose_landing_gear = SAE_Airframe_Noise_Outputs.EPNL_nose_landing_gear
EPNL_main_landing_gear = SAE_Airframe_Noise_Outputs.EPNL_main_landing_gear
EPNL_total = SAE_Airframe_Noise_Outputs.EPNL_total
SENEL_total = SAE_Airframe_Noise_Outputs.SENEL_total
SPL_total_history = SAE_Airframe_Noise_Outputs.SPL_total_history
SPLt_dBA_history = SAE_Airframe_Noise_Outputs.SPLt_dBA_history
# write header of file
if not filename:
filename = ('Noise_' + str(tag) + '.dat')
fid = open(filename,'w') # Open output file
fid.write('Reference speed = ')
fid.write(str('%2.2f' % (velocity/Units.kts))+' kts')
fid.write('\n')
fid.write('PNLT history')
fid.write('\n')
fid.write('time altitude Mach Polar_angle Azim_angle distance wing ht vt flap slat nose main total dBA')
fid.write('\n')
for id in range (0,nsteps):
fid.write(str('%2.2f' % time[id])+' ')
fid.write(str('%2.2f' % altitude[id])+' ')
fid.write(str('%2.2f' % M[id])+' ')
fid.write(str('%2.2f' % (angle[id]*180/np.pi))+' ')
fid.write(str('%2.2f' % (phi[id]*180/np.pi))+' ')
fid.write(str('%2.2f' % distance_vector[id])+' ')
fid.write(str('%2.2f' % PNLT_wing[id])+' ')
fid.write(str('%2.2f' % PNLT_ht[id])+' ')
fid.write(str('%2.2f' % PNLT_vt[id])+' ')
fid.write(str('%2.2f' % PNLT_flap[id])+' ')
fid.write(str('%2.2f' % PNLT_slat[id])+' ')
fid.write(str('%2.2f' % PNLT_nose_landing_gear[id])+' ')
fid.write(str('%2.2f' % PNLT_main_landing_gear[id])+' ')
fid.write(str('%2.2f' % PNLT_total[id])+' ')
fid.write(str('%2.2f' % SPLt_dBA_max[id])+' ')
fid.write('\n')
fid.write('\n')
fid.write('PNLT max = ')
fid.write(str('%2.2f' % (np.max(PNLT_total)))+' dB')
fid.write('\n')
fid.write('dBA max = ')
fid.write(str('%2.2f' % (np.max(SPLt_dBA_max)))+' dBA')
fid.write('\n')
fid.write('\n')
fid.write('EPNdB')
fid.write('\n')
fid.write('wing ht vt flap slat nose main total')
fid.write('\n')
fid.write(str('%2.2f' % EPNL_wing)+' ')
fid.write(str('%2.2f' % EPNL_ht)+' ')
fid.write(str('%2.2f' % EPNL_vt)+' ')
fid.write(str('%2.2f' % EPNL_flap)+' ')
fid.write(str('%2.2f' % EPNL_slat)+' ')
fid.write(str('%2.2f' % EPNL_nose_landing_gear)+' ')
fid.write(str('%2.2f' % EPNL_main_landing_gear)+' ')
fid.write(str('%2.2f' % EPNL_total)+' ')
fid.write('\n')
fid.write('SENEL = ')
fid.write(str('%2.2f' % SENEL_total)+' ')
fid.close
filename1 = ('History_Noise_' + str(tag) + '.dat')
fid = open(filename1,'w') # Open output file
fid.write('Reference speed = ')
fid.write(str('%2.2f' % (velocity/Units.kts))+' kts')
fid.write('\n')
fid.write('Sound Pressure Level for the Total Aircraft Noise')
fid.write('\n')
for nid in range (0,nrange):
fid.write('Polar angle = ' + str('%2.2f' % (angle[nid]*(180/np.pi))) + ' degrees' + '\n')
fid.write('f total SPL(dB) total SPL(dBA)' + '\n')
for id in range(0,24):
fid.write(str((frequency[id])) + ' ')
fid.write(str('%3.2f' % SPL_total_history[nid][id]) + ' ')
fid.write(str('%3.2f' % SPLt_dBA_history[nid][id]))
fid.write('\n')
fid.write('SPLmax (dB) = ')
fid.write(str('%3.2f' % (np.max(SPL_total_history[nid][:])))+' dB' + '\n')
fid.write('SPLmax (dBA) = ')
fid.write(str('%3.2f' % (np.max(SPLt_dBA_history[nid][:])))+' dB')
fid.write('\n')
fid.close
return | StarcoderdataPython |
5137801 | """
Created by howie.hu at 2022-01-21.
Description: 执行备份动作
- 文章备份命令: PIPENV_DOTENV_LOCATION=./pro.env pipenv run python src/backup/action.py
- 准备数据命令: PIPENV_DOTENV_LOCATION=./pro.env pipenv run python src/collector/collect_factory.py
Changelog: all notable changes to this file will be documented
"""
import time
from copy import deepcopy
from src.backup.backup_factory import backup_factory
from src.common.remote import send_get_request
from src.config import Config
from src.databases import MongodbManager
from src.databases.mongodb_tools import mongodb_find
from src.processor import processor_dict
from src.utils.log import LOGGER
def backup_doc(backup_config: dict):
"""对文章进行备份
Args:
backup_config (dict): 备份配置
"""
backup_list = backup_config["backup_list"]
query_days = backup_config.get("query_days", 2)
delta_time = backup_config.get("delta_time", 3)
init_config = backup_config.get("init_config", {})
after_get_content = backup_config.get("after_get_content", [])
if backup_list:
mongo_base = MongodbManager.get_mongo_base(mongodb_config=Config.MONGODB_CONFIG)
coll = mongo_base.get_collection(coll_name="liuli_articles")
cur_ts = int(time.time())
filter_dict = {
# 时间范围,除第一次外后面其实可以去掉
"doc_ts": {"$gte": cur_ts - (query_days * 24 * 60 * 60), "$lte": cur_ts}
}
db_res = mongodb_find(
coll_conn=coll,
filter_dict=filter_dict,
return_dict={
"_id": 0,
"doc_source": 1,
"doc_source_name": 1,
"doc_name": 1,
"doc_link": 1,
},
)
if db_res["status"]:
# 查找所有可备份文章
for each_data in db_res["info"]:
for each in backup_list:
# 每次备份休眠一定时间
time.sleep(delta_time)
backup_ins = backup_factory(
backup_type=each, init_config=init_config
)
# 获取原始文本内容
doc_link = each_data["doc_link"]
resp = send_get_request(url=doc_link)
doc_text = resp.text
# 执行获取文本后的钩子函数
for func_dict in after_get_content:
cur_func_dict = deepcopy(func_dict)
func_name = cur_func_dict.pop("func")
LOGGER.info(
"处理器(backup:after_get_content): {} 正在执行...".format(
func_name
)
)
cur_func_dict.update({"text": doc_text})
doc_text = processor_dict[func_name](**cur_func_dict)
# 进行保存动作
each_data["doc_text"] = doc_text
backup_ins.save(each_data)
else:
LOGGER.error(f"Backup 数据查询失败! {db_res['info']}")
else:
LOGGER.warn("Backup 未配置备份源!")
if __name__ == "__main__":
backup = {
"backup_list": ["github", "mongodb"],
# "backup_list": ["mongodb"],
"query_days": 7,
"delta_time": 1,
"init_config": {},
"after_get_content": [
{
"func": "str_replace",
"before_str": 'data-src="',
"after_str": 'src="https://images.weserv.nl/?url=',
}
],
}
backup_doc(backup)
| StarcoderdataPython |
83051 | <filename>apps/usuarios/models.py
# from django.db import models
# Create your models here.
# comentarios, sera un capo de texto mas relacion comentario a comentario
# los itens que pueden ser comentados tendran la llave foranea
# el delete no en casacada
| StarcoderdataPython |
1773228 | <reponame>TouchPal/guldan<filename>app/db.py<gh_stars>10-100
# -*- coding: utf-8 -*-
import contextlib
import logging
import random
from flask import request, g
from sqlalchemy import create_engine as sqlalchemy_create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from app import app, load_app_config
from app.exc import GulDanException
from stats import sys_stats
logger = logging.getLogger(__name__)
def model_base():
return declarative_base()
class RecycleField(object):
def __get__(self, instance, klass):
if instance is not None:
return int(random.uniform(0.75, 1) * instance._origin_recyle)
raise AttributeError
def patch_engine(engine):
pool = engine.pool
pool._origin_recyle = pool._recycle
del pool._recycle
setattr(pool.__class__, '_recycle', RecycleField())
return engine
def maintainance_check(session, flush_context, instances):
raise GulDanException().with_code(500).with_message(u"guldan维护中,禁止写入")
class DBManager(object):
def __init__(self, stats):
self.session_map = {}
self.create_sessions()
self.stats = stats
def create_sessions(self):
db_settings = load_app_config().DB_SETTINGS
for role, url in db_settings.items():
session_factory = self.create_single_session(url)
# event.listen(session_factory, "before_flush", maintainance_check)
self.session_map[role] = session_factory
@classmethod
def create_single_session(cls, url, scopefunc=None):
engine = sqlalchemy_create_engine(url,
pool_size=10,
max_overflow=70,
pool_recycle=1200
)
patched_engine = patch_engine(engine)
return scoped_session(
sessionmaker(
expire_on_commit=False,
bind=patched_engine
),
scopefunc=scopefunc
)
def get_session(self, name):
try:
if not name:
name = "master"
return self.session_map[name]
except KeyError:
raise KeyError('{} not created, check your DB_SETTINGS'.format(name))
except IndexError:
raise IndexError('cannot get names from DB_SETTINGS')
@contextlib.contextmanager
def session_ctx(self, bind=None):
DBSession = self.get_session(bind)
session = DBSession()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.expunge_all()
session.close()
DBSession.remove()
db_manager = DBManager(sys_stats)
| StarcoderdataPython |
8190391 | <reponame>ldbc/sigmod2014-pc-graphblas
from abc import ABC, abstractmethod
from collections import namedtuple
import logging
from loader.data_loader import DataLoader
Test = namedtuple('Test', ['inputs', 'expected_result'])
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)-5s %(message)s'))
log = logging.getLogger(__name__)
log.propagate = False
log.addHandler(handler)
log.setLevel(logging.INFO)
class QueryBase(ABC):
def __init__(self, data_dir, data_format, tests):
self.loader = DataLoader(data_dir, data_format)
self.tests = tests
self.benchmark_inputs = None
self.load_time = None
self.test_execution_times = []
@abstractmethod
def execute_query(self, params):
pass
@abstractmethod
def load_data(self):
pass
@abstractmethod
def format_result_string(self, result):
pass
def run_tests(self, query_implementation, mode='testing'):
# To run the tests of Q1 and Q4 with different search methods,
# change the default parameter in their execute_query function
all_tests = 0
failed_tests = 0
if mode is 'testing':
tests = self.tests
elif mode is 'benchmark':
tests = self.benchmark_inputs
else:
raise Exception('Invalid mode for executing tests. Valid options are: [testing, benchmark]')
# log.info(f'Running tests in {mode} mode')
for test in tests:
result = query_implementation(test.inputs)
test = test._replace(expected_result=self.format_result_string(test.expected_result))
if result == test.expected_result:
# log.info(f'Result: {result}')
# log.info(f'TEST PASSED')
# log.info('----------------------')
pass
else:
failed_tests += 1
# log.error(f'TEST FAILED: result: {result} expected result: {test.expected_result}')
all_tests += 1
if failed_tests == 0:
# log.info(f'ALL TESTS PASSED: {all_tests}')
return True
else:
# log.error(f'TESTS FAILED: {failed_tests}/{all_tests}')
return False
@abstractmethod
def init_tests(self):
pass
def init_benchmark_inputs(self, benchmark_tests):
self.benchmark_inputs = benchmark_tests
| StarcoderdataPython |
6507203 | <gh_stars>0
#Given an array and an integer k, rotate the array by k spaces. Do this without generating a new array and without using extra space.
#Here's an example and some starter code
def rotate_list(nums, k):
# Fill this in.
l = len(nums)
m = k%l
for i in range(m):
firstNum = nums[0]
for j in range(0, l-1):
nums[j] = nums[j+1]
nums[l-1] = firstNum
return nums
if __name__ == "__main__":
a = [1, 2, 3, 4, 5]
rotate_list(a, 2)
print(a)
# [3, 4, 5, 1, 2]
a = [1, 2, 3, 4, 5]
rotate_list(a, 6)
print(a) | StarcoderdataPython |
76642 | <gh_stars>1-10
from django.db import models
class Titleable(models.Model):
title = models.CharField(
verbose_name='Название',
max_length=200,
blank=True
)
class Meta:
abstract = True
class Textable(models.Model):
text = models.TextField(
verbose_name='Текст',
blank=True
)
class Meta:
abstract = True
class Emailable(models.Model):
email = models.EmailField(
verbose_name='Электронная почта'
)
class Meta:
abstract = True
class Phoneable(models.Model):
phone = models.CharField(
verbose_name='Контактный телефон',
max_length=50
)
class Meta:
abstract = True
| StarcoderdataPython |
289260 | from cloudshell.shell.core.driver_context import ResourceCommandContext, AutoLoadDetails, AutoLoadAttribute, \
AutoLoadResource
from collections import defaultdict
class LegacyUtils(object):
def __init__(self):
self._datamodel_clss_dict = self.__generate_datamodel_classes_dict()
def migrate_autoload_details(self, autoload_details, context):
model_name = context.resource.model
root_name = context.resource.name
root = self.__create_resource_from_datamodel(model_name, root_name)
attributes = self.__create_attributes_dict(autoload_details.attributes)
self.__attach_attributes_to_resource(attributes, '', root)
self.__build_sub_resoruces_hierarchy(root, autoload_details.resources, attributes)
return root
def __create_resource_from_datamodel(self, model_name, res_name):
return self._datamodel_clss_dict[model_name](res_name)
def __create_attributes_dict(self, attributes_lst):
d = defaultdict(list)
for attribute in attributes_lst:
d[attribute.relative_address].append(attribute)
return d
def __build_sub_resoruces_hierarchy(self, root, sub_resources, attributes):
d = defaultdict(list)
for resource in sub_resources:
splitted = resource.relative_address.split('/')
parent = '' if len(splitted) == 1 else resource.relative_address.rsplit('/', 1)[0]
rank = len(splitted)
d[rank].append((parent, resource))
self.__set_models_hierarchy_recursively(d, 1, root, '', attributes)
def __set_models_hierarchy_recursively(self, dict, rank, manipulated_resource, resource_relative_addr, attributes):
if rank not in dict: # validate if key exists
pass
for (parent, resource) in dict[rank]:
if parent == resource_relative_addr:
sub_resource = self.__create_resource_from_datamodel(
resource.model.replace(' ', ''),
resource.name)
self.__attach_attributes_to_resource(attributes, resource.relative_address, sub_resource)
manipulated_resource.add_sub_resource(
self.__slice_parent_from_relative_path(parent, resource.relative_address), sub_resource)
self.__set_models_hierarchy_recursively(
dict,
rank + 1,
sub_resource,
resource.relative_address,
attributes)
def __attach_attributes_to_resource(self, attributes, curr_relative_addr, resource):
for attribute in attributes[curr_relative_addr]:
setattr(resource, attribute.attribute_name.lower().replace(' ', '_'), attribute.attribute_value)
del attributes[curr_relative_addr]
def __slice_parent_from_relative_path(self, parent, relative_addr):
if parent is '':
return relative_addr
return relative_addr[len(parent) + 1:] # + 1 because we want to remove the seperator also
def __generate_datamodel_classes_dict(self):
return dict(self.__collect_generated_classes())
def __collect_generated_classes(self):
import sys, inspect
return inspect.getmembers(sys.modules[__name__], inspect.isclass)
class ApV2(object):
def __init__(self, name):
"""
"""
self.attributes = {}
self.resources = {}
self._cloudshell_model_name = 'ApV2'
self._name = name
def add_sub_resource(self, relative_path, sub_resource):
self.resources[relative_path] = sub_resource
@classmethod
def create_from_context(cls, context):
"""
Creates an instance of NXOS by given context
:param context: cloudshell.shell.core.driver_context.ResourceCommandContext
:type context: cloudshell.shell.core.driver_context.ResourceCommandContext
:return:
:rtype ApV2
"""
result = ApV2(name=context.resource.name)
for attr in context.resource.attributes:
result.attributes[attr] = context.resource.attributes[attr]
return result
def create_autoload_details(self, relative_path=''):
"""
:param relative_path:
:type relative_path: str
:return
"""
resources = [AutoLoadResource(model=self.resources[r].cloudshell_model_name,
name=self.resources[r].name,
relative_address=self._get_relative_path(r, relative_path))
for r in self.resources]
attributes = [AutoLoadAttribute(relative_path, a, self.attributes[a]) for a in self.attributes]
autoload_details = AutoLoadDetails(resources, attributes)
for r in self.resources:
curr_path = relative_path + '/' + r if relative_path else r
curr_auto_load_details = self.resources[r].create_autoload_details(curr_path)
autoload_details = self._merge_autoload_details(autoload_details, curr_auto_load_details)
return autoload_details
def _get_relative_path(self, child_path, parent_path):
"""
Combines relative path
:param child_path: Path of a model within it parent model, i.e 1
:type child_path: str
:param parent_path: Full path of parent model, i.e 1/1. Might be empty for root model
:type parent_path: str
:return: Combined path
:rtype str
"""
return parent_path + '/' + child_path if parent_path else child_path
@staticmethod
def _merge_autoload_details(autoload_details1, autoload_details2):
"""
Merges two instances of AutoLoadDetails into the first one
:param autoload_details1:
:type autoload_details1: AutoLoadDetails
:param autoload_details2:
:type autoload_details2: AutoLoadDetails
:return:
:rtype AutoLoadDetails
"""
for attribute in autoload_details2.attributes:
autoload_details1.attributes.append(attribute)
for resource in autoload_details2.resources:
autoload_details1.resources.append(resource)
return autoload_details1
@property
def cloudshell_model_name(self):
"""
Returns the name of the Cloudshell model
:return:
"""
return 'ApV2'
@property
def bands(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Bands'] if 'ApV2.Bands' in self.attributes else None
@bands.setter
def bands(self, value='dual-band'):
"""
:type value: str
"""
self.attributes['ApV2.Bands'] = value
@property
def radios(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Radios'] if 'ApV2.Radios' in self.attributes else None
@radios.setter
def radios(self, value='2.4Ghz (2x2)'):
"""
:type value: str
"""
self.attributes['ApV2.Radios'] = value
@property
def radio_2dot4ghz(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Radio 2dot4Ghz'] if 'ApV2.Radio 2dot4Ghz' in self.attributes else None
@radio_2dot4ghz.setter
def radio_2dot4ghz(self, value='(2x2)'):
"""
:type value: str
"""
self.attributes['ApV2.Radio 2dot4Ghz'] = value
@property
def radio_5ghz_1(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Radio 5Ghz 1'] if 'ApV2.Radio 5Ghz 1' in self.attributes else None
@radio_5ghz_1.setter
def radio_5ghz_1(self, value='(2x2)'):
"""
:type value: str
"""
self.attributes['ApV2.Radio 5Ghz 1'] = value
@property
def radio_5ghz_2(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Radio 5Ghz 2'] if 'ApV2.Radio 5Ghz 2' in self.attributes else None
@radio_5ghz_2.setter
def radio_5ghz_2(self, value='N/A'):
"""
:type value: str
"""
self.attributes['ApV2.Radio 5Ghz 2'] = value
@property
def model(self):
"""
:rtype: str
"""
return self.attributes['ApV2.model'] if 'ApV2.model' in self.attributes else None
@model.setter
def model(self, value):
"""
:type value: str
"""
self.attributes['ApV2.model'] = value
@property
def mode(self):
"""
:rtype: str
"""
return self.attributes['ApV2.mode'] if 'ApV2.mode' in self.attributes else None
@mode.setter
def mode(self, value='Wifi5'):
"""
:type value: str
"""
self.attributes['ApV2.mode'] = value
@property
def serial(self):
"""
:rtype: str
"""
return self.attributes['ApV2.serial'] if 'ApV2.serial' in self.attributes else None
@serial.setter
def serial(self, value):
"""
:type value: str
"""
self.attributes['ApV2.serial'] = value
@property
def jumphost(self):
"""
:rtype: bool
"""
return self.attributes['ApV2.jumphost'] if 'ApV2.jumphost' in self.attributes else None
@jumphost.setter
def jumphost(self, value):
"""
:type value: bool
"""
self.attributes['ApV2.jumphost'] = value
@property
def ip(self):
"""
:rtype: str
"""
return self.attributes['ApV2.ip'] if 'ApV2.ip' in self.attributes else None
@ip.setter
def ip(self, value):
"""
:type value: str
"""
self.attributes['ApV2.ip'] = value
@property
def jumphost_tty(self):
"""
:rtype: str
"""
return self.attributes['ApV2.jumphost_tty'] if 'ApV2.jumphost_tty' in self.attributes else None
@jumphost_tty.setter
def jumphost_tty(self, value='/dev/ttyAP1'):
"""
:type value: str
"""
self.attributes['ApV2.jumphost_tty'] = value
@property
def version(self):
"""
:rtype: str
"""
return self.attributes['ApV2.version'] if 'ApV2.version' in self.attributes else None
@version.setter
def version(self, value):
"""
:type value: str
"""
self.attributes['ApV2.version'] = value
@property
def port(self):
"""
:rtype: float
"""
return self.attributes['ApV2.port'] if 'ApV2.port' in self.attributes else None
@port.setter
def port(self, value='22'):
"""
:type value: float
"""
self.attributes['ApV2.port'] = value
@property
def uname(self):
"""
:rtype: str
"""
return self.attributes['ApV2.uname'] if 'ApV2.uname' in self.attributes else None
@uname.setter
def uname(self, value):
"""
:type value: str
"""
self.attributes['ApV2.uname'] = value
@property
def passkey(self):
"""
:rtype: string
"""
return self.attributes['ApV2.passkey'] if 'ApV2.passkey' in self.attributes else None
@passkey.setter
def passkey(self, value):
"""
:type value: string
"""
self.attributes['ApV2.passkey'] = value
@property
def pdu_host(self):
"""
:rtype: str
"""
return self.attributes['ApV2.PDU Host'] if 'ApV2.PDU Host' in self.attributes else None
@pdu_host.setter
def pdu_host(self, value):
"""
:type value: str
"""
self.attributes['ApV2.PDU Host'] = value
@property
def pdu_user(self):
"""
:rtype: str
"""
return self.attributes['ApV2.PDU User'] if 'ApV2.PDU User' in self.attributes else None
@pdu_user.setter
def pdu_user(self, value):
"""
:type value: str
"""
self.attributes['ApV2.PDU User'] = value
@property
def pdu_password(self):
"""
:rtype: string
"""
return self.attributes['ApV2.PDU Password'] if 'ApV2.PDU Password' in self.attributes else None
@pdu_password.setter
def pdu_password(self, value):
"""
:type value: string
"""
self.attributes['ApV2.PDU Password'] = value
@property
def pdu_port(self):
"""
:rtype: str
"""
return self.attributes['ApV2.PDU Port'] if 'ApV2.PDU Port' in self.attributes else None
@pdu_port.setter
def pdu_port(self, value):
"""
:type value: str
"""
self.attributes['ApV2.PDU Port'] = value
@property
def user(self):
"""
:rtype: str
"""
return self.attributes['ApV2.User'] if 'ApV2.User' in self.attributes else None
@user.setter
def user(self, value):
"""
User with administrative privileges
:type value: str
"""
self.attributes['ApV2.User'] = value
@property
def password(self):
"""
:rtype: string
"""
return self.attributes['ApV2.Password'] if 'ApV2.Password' in self.attributes else None
@password.setter
def password(self, value):
"""
:type value: string
"""
self.attributes['ApV2.Password'] = value
@property
def enable_password(self):
"""
:rtype: string
"""
return self.attributes['ApV2.Enable Password'] if 'ApV2.Enable Password' in self.attributes else None
@enable_password.setter
def enable_password(self, value):
"""
The enable password is required by some CLI protocols such as Telnet and is required according to the device configuration.
:type value: string
"""
self.attributes['ApV2.Enable Password'] = value
@property
def power_management(self):
"""
:rtype: bool
"""
return self.attributes['ApV2.Power Management'] if 'ApV2.Power Management' in self.attributes else None
@power_management.setter
def power_management(self, value=True):
"""
Used by the power management orchestration, if enabled, to determine whether to automatically manage the device power status. Enabled by default.
:type value: bool
"""
self.attributes['ApV2.Power Management'] = value
@property
def sessions_concurrency_limit(self):
"""
:rtype: float
"""
return self.attributes['ApV2.Sessions Concurrency Limit'] if 'ApV2.Sessions Concurrency Limit' in self.attributes else None
@sessions_concurrency_limit.setter
def sessions_concurrency_limit(self, value='1'):
"""
The maximum number of concurrent sessions that the driver will open to the device. Default is 1 (no concurrency).
:type value: float
"""
self.attributes['ApV2.Sessions Concurrency Limit'] = value
@property
def snmp_read_community(self):
"""
:rtype: string
"""
return self.attributes['ApV2.SNMP Read Community'] if 'ApV2.SNMP Read Community' in self.attributes else None
@snmp_read_community.setter
def snmp_read_community(self, value):
"""
The SNMP Read-Only Community String is like a password. It is sent along with each SNMP Get-Request and allows (or denies) access to device.
:type value: string
"""
self.attributes['ApV2.SNMP Read Community'] = value
@property
def snmp_write_community(self):
"""
:rtype: string
"""
return self.attributes['ApV2.SNMP Write Community'] if 'ApV2.SNMP Write Community' in self.attributes else None
@snmp_write_community.setter
def snmp_write_community(self, value):
"""
The SNMP Write Community String is like a password. It is sent along with each SNMP Set-Request and allows (or denies) chaning MIBs values.
:type value: string
"""
self.attributes['ApV2.SNMP Write Community'] = value
@property
def snmp_v3_user(self):
"""
:rtype: str
"""
return self.attributes['ApV2.SNMP V3 User'] if 'ApV2.SNMP V3 User' in self.attributes else None
@snmp_v3_user.setter
def snmp_v3_user(self, value):
"""
Relevant only in case SNMP V3 is in use.
:type value: str
"""
self.attributes['ApV2.SNMP V3 User'] = value
@property
def snmp_v3_password(self):
"""
:rtype: string
"""
return self.attributes['ApV2.SNMP V3 Password'] if 'ApV2.SNMP V3 Password' in self.attributes else None
@snmp_v3_password.setter
def snmp_v3_password(self, value):
"""
Relevant only in case SNMP V3 is in use.
:type value: string
"""
self.attributes['ApV2.SNMP V3 Password'] = value
@property
def snmp_v3_private_key(self):
"""
:rtype: str
"""
return self.attributes['ApV2.SNMP V3 Private Key'] if 'ApV2.SNMP V3 Private Key' in self.attributes else None
@snmp_v3_private_key.setter
def snmp_v3_private_key(self, value):
"""
Relevant only in case SNMP V3 is in use.
:type value: str
"""
self.attributes['ApV2.SNMP V3 Private Key'] = value
@property
def snmp_v3_authentication_protocol(self):
"""
:rtype: str
"""
return self.attributes['ApV2.SNMP V3 Authentication Protocol'] if 'ApV2.SNMP V3 Authentication Protocol' in self.attributes else None
@snmp_v3_authentication_protocol.setter
def snmp_v3_authentication_protocol(self, value='No Authentication Protocol'):
"""
Relevant only in case SNMP V3 is in use.
:type value: str
"""
self.attributes['ApV2.SNMP V3 Authentication Protocol'] = value
@property
def snmp_v3_privacy_protocol(self):
"""
:rtype: str
"""
return self.attributes['ApV2.SNMP V3 Privacy Protocol'] if 'ApV2.SNMP V3 Privacy Protocol' in self.attributes else None
@snmp_v3_privacy_protocol.setter
def snmp_v3_privacy_protocol(self, value='No Privacy Protocol'):
"""
Relevant only in case SNMP V3 is in use.
:type value: str
"""
self.attributes['ApV2.SNMP V3 Privacy Protocol'] = value
@property
def snmp_version(self):
"""
:rtype: str
"""
return self.attributes['ApV2.SNMP Version'] if 'ApV2.SNMP Version' in self.attributes else None
@snmp_version.setter
def snmp_version(self, value=''):
"""
The version of SNMP to use. Possible values are v1, v2c and v3.
:type value: str
"""
self.attributes['ApV2.SNMP Version'] = value
@property
def enable_snmp(self):
"""
:rtype: bool
"""
return self.attributes['ApV2.Enable SNMP'] if 'ApV2.Enable SNMP' in self.attributes else None
@enable_snmp.setter
def enable_snmp(self, value=True):
"""
If set to True and SNMP isn???t enabled yet in the device the Shell will automatically enable SNMP in the device when Autoload command is called. SNMP must be enabled on the device for the Autoload command to run successfully. True by default.
:type value: bool
"""
self.attributes['ApV2.Enable SNMP'] = value
@property
def disable_snmp(self):
"""
:rtype: bool
"""
return self.attributes['ApV2.Disable SNMP'] if 'ApV2.Disable SNMP' in self.attributes else None
@disable_snmp.setter
def disable_snmp(self, value=False):
"""
If set to True SNMP will be disabled automatically by the Shell after the Autoload command execution is completed. False by default.
:type value: bool
"""
self.attributes['ApV2.Disable SNMP'] = value
@property
def console_server_ip_address(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Console Server IP Address'] if 'ApV2.Console Server IP Address' in self.attributes else None
@console_server_ip_address.setter
def console_server_ip_address(self, value):
"""
The IP address of the console server, in IPv4 format.
:type value: str
"""
self.attributes['ApV2.Console Server IP Address'] = value
@property
def console_user(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Console User'] if 'ApV2.Console User' in self.attributes else None
@console_user.setter
def console_user(self, value):
"""
:type value: str
"""
self.attributes['ApV2.Console User'] = value
@property
def console_port(self):
"""
:rtype: float
"""
return self.attributes['ApV2.Console Port'] if 'ApV2.Console Port' in self.attributes else None
@console_port.setter
def console_port(self, value):
"""
The port on the console server, usually TCP port, which the device is associated with.
:type value: float
"""
self.attributes['ApV2.Console Port'] = value
@property
def console_password(self):
"""
:rtype: string
"""
return self.attributes['ApV2.Console Password'] if 'ApV2.Console Password' in self.attributes else None
@console_password.setter
def console_password(self, value):
"""
:type value: string
"""
self.attributes['ApV2.Console Password'] = value
@property
def cli_connection_type(self):
"""
:rtype: str
"""
return self.attributes['ApV2.CLI Connection Type'] if 'ApV2.CLI Connection Type' in self.attributes else None
@cli_connection_type.setter
def cli_connection_type(self, value='Auto'):
"""
The CLI connection type that will be used by the driver. Possible values are Auto, Console, SSH, Telnet and TCP. If Auto is selected the driver will choose the available connection type automatically. Default value is Auto.
:type value: str
"""
self.attributes['ApV2.CLI Connection Type'] = value
@property
def cli_tcp_port(self):
"""
:rtype: float
"""
return self.attributes['ApV2.CLI TCP Port'] if 'ApV2.CLI TCP Port' in self.attributes else None
@cli_tcp_port.setter
def cli_tcp_port(self, value):
"""
TCP Port to user for CLI connection. If kept empty a default CLI port will be used based on the chosen protocol, for example Telnet will use port 23.
:type value: float
"""
self.attributes['ApV2.CLI TCP Port'] = value
@property
def backup_location(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Backup Location'] if 'ApV2.Backup Location' in self.attributes else None
@backup_location.setter
def backup_location(self, value):
"""
Used by the save/restore orchestration to determine where backups should be saved.
:type value: str
"""
self.attributes['ApV2.Backup Location'] = value
@property
def backup_type(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Backup Type'] if 'ApV2.Backup Type' in self.attributes else None
@backup_type.setter
def backup_type(self, value='File System'):
"""
Supported protocols for saving and restoring of configuration and firmware files. Possible values are 'File System' 'FTP' and 'TFTP'. Default value is 'File System'.
:type value: str
"""
self.attributes['ApV2.Backup Type'] = value
@property
def backup_user(self):
"""
:rtype: str
"""
return self.attributes['ApV2.Backup User'] if 'ApV2.Backup User' in self.attributes else None
@backup_user.setter
def backup_user(self, value):
"""
Username for the storage server used for saving and restoring of configuration and firmware files.
:type value: str
"""
self.attributes['ApV2.Backup User'] = value
@property
def backup_password(self):
"""
:rtype: string
"""
return self.attributes['ApV2.Backup Password'] if 'ApV2.Backup Password' in self.attributes else None
@backup_password.setter
def backup_password(self, value):
"""
Password for the storage server used for saving and restoring of configuration and firmware files.
:type value: string
"""
self.attributes['ApV2.Backup Password'] = value
@property
def name(self):
"""
:rtype: str
"""
return self._name
@name.setter
def name(self, value):
"""
:type value: str
"""
self._name = value
@property
def cloudshell_model_name(self):
"""
:rtype: str
"""
return self._cloudshell_model_name
@cloudshell_model_name.setter
def cloudshell_model_name(self, value):
"""
:type value: str
"""
self._cloudshell_model_name = value
@property
def system_name(self):
"""
:rtype: str
"""
return self.attributes['CS_GenericResource.System Name'] if 'CS_GenericResource.System Name' in self.attributes else None
@system_name.setter
def system_name(self, value):
"""
A unique identifier for the device, if exists in the device terminal/os.
:type value: str
"""
self.attributes['CS_GenericResource.System Name'] = value
@property
def vendor(self):
"""
:rtype: str
"""
return self.attributes['CS_GenericResource.Vendor'] if 'CS_GenericResource.Vendor' in self.attributes else None
@vendor.setter
def vendor(self, value=''):
"""
The name of the device manufacture.
:type value: str
"""
self.attributes['CS_GenericResource.Vendor'] = value
@property
def contact_name(self):
"""
:rtype: str
"""
return self.attributes['CS_GenericResource.Contact Name'] if 'CS_GenericResource.Contact Name' in self.attributes else None
@contact_name.setter
def contact_name(self, value):
"""
The name of a contact registered in the device.
:type value: str
"""
self.attributes['CS_GenericResource.Contact Name'] = value
@property
def location(self):
"""
:rtype: str
"""
return self.attributes['CS_GenericResource.Location'] if 'CS_GenericResource.Location' in self.attributes else None
@location.setter
def location(self, value=''):
"""
The device physical location identifier. For example Lab1/Floor2/Row5/Slot4.
:type value: str
"""
self.attributes['CS_GenericResource.Location'] = value
@property
def model(self):
"""
:rtype: str
"""
return self.attributes['CS_GenericResource.Model'] if 'CS_GenericResource.Model' in self.attributes else None
@model.setter
def model(self, value=''):
"""
The device model. This information is typically used for abstract resource filtering.
:type value: str
"""
self.attributes['CS_GenericResource.Model'] = value
@property
def model_name(self):
"""
:rtype: str
"""
return self.attributes['CS_GenericResource.Model Name'] if 'CS_GenericResource.Model Name' in self.attributes else None
@model_name.setter
def model_name(self, value=''):
"""
The catalog name of the device model. This attribute will be displayed in CloudShell instead of the CloudShell model.
:type value: str
"""
self.attributes['CS_GenericResource.Model Name'] = value
class ResourcePort(object):
def __init__(self, name):
"""
"""
self.attributes = {}
self.resources = {}
self._cloudshell_model_name = 'ApV2.ResourcePort'
self._name = name
def add_sub_resource(self, relative_path, sub_resource):
self.resources[relative_path] = sub_resource
@classmethod
def create_from_context(cls, context):
"""
Creates an instance of NXOS by given context
:param context: cloudshell.shell.core.driver_context.ResourceCommandContext
:type context: cloudshell.shell.core.driver_context.ResourceCommandContext
:return:
:rtype ResourcePort
"""
result = ResourcePort(name=context.resource.name)
for attr in context.resource.attributes:
result.attributes[attr] = context.resource.attributes[attr]
return result
def create_autoload_details(self, relative_path=''):
"""
:param relative_path:
:type relative_path: str
:return
"""
resources = [AutoLoadResource(model=self.resources[r].cloudshell_model_name,
name=self.resources[r].name,
relative_address=self._get_relative_path(r, relative_path))
for r in self.resources]
attributes = [AutoLoadAttribute(relative_path, a, self.attributes[a]) for a in self.attributes]
autoload_details = AutoLoadDetails(resources, attributes)
for r in self.resources:
curr_path = relative_path + '/' + r if relative_path else r
curr_auto_load_details = self.resources[r].create_autoload_details(curr_path)
autoload_details = self._merge_autoload_details(autoload_details, curr_auto_load_details)
return autoload_details
def _get_relative_path(self, child_path, parent_path):
"""
Combines relative path
:param child_path: Path of a model within it parent model, i.e 1
:type child_path: str
:param parent_path: Full path of parent model, i.e 1/1. Might be empty for root model
:type parent_path: str
:return: Combined path
:rtype str
"""
return parent_path + '/' + child_path if parent_path else child_path
@staticmethod
def _merge_autoload_details(autoload_details1, autoload_details2):
"""
Merges two instances of AutoLoadDetails into the first one
:param autoload_details1:
:type autoload_details1: AutoLoadDetails
:param autoload_details2:
:type autoload_details2: AutoLoadDetails
:return:
:rtype AutoLoadDetails
"""
for attribute in autoload_details2.attributes:
autoload_details1.attributes.append(attribute)
for resource in autoload_details2.resources:
autoload_details1.resources.append(resource)
return autoload_details1
@property
def cloudshell_model_name(self):
"""
Returns the name of the Cloudshell model
:return:
"""
return 'ResourcePort'
@property
def mac_address(self):
"""
:rtype: str
"""
return self.attributes['ApV2.ResourcePort.MAC Address'] if 'ApV2.ResourcePort.MAC Address' in self.attributes else None
@mac_address.setter
def mac_address(self, value=''):
"""
:type value: str
"""
self.attributes['ApV2.ResourcePort.MAC Address'] = value
@property
def ipv4_address(self):
"""
:rtype: str
"""
return self.attributes['ApV2.ResourcePort.IPv4 Address'] if 'ApV2.ResourcePort.IPv4 Address' in self.attributes else None
@ipv4_address.setter
def ipv4_address(self, value):
"""
:type value: str
"""
self.attributes['ApV2.ResourcePort.IPv4 Address'] = value
@property
def ipv6_address(self):
"""
:rtype: str
"""
return self.attributes['ApV2.ResourcePort.IPv6 Address'] if 'ApV2.ResourcePort.IPv6 Address' in self.attributes else None
@ipv6_address.setter
def ipv6_address(self, value):
"""
:type value: str
"""
self.attributes['ApV2.ResourcePort.IPv6 Address'] = value
@property
def port_speed(self):
"""
:rtype: str
"""
return self.attributes['ApV2.ResourcePort.Port Speed'] if 'ApV2.ResourcePort.Port Speed' in self.attributes else None
@port_speed.setter
def port_speed(self, value):
"""
The port speed (e.g 10Gb/s, 40Gb/s, 100Mb/s)
:type value: str
"""
self.attributes['ApV2.ResourcePort.Port Speed'] = value
@property
def name(self):
"""
:rtype: str
"""
return self._name
@name.setter
def name(self, value):
"""
:type value: str
"""
self._name = value
@property
def cloudshell_model_name(self):
"""
:rtype: str
"""
return self._cloudshell_model_name
@cloudshell_model_name.setter
def cloudshell_model_name(self, value):
"""
:type value: str
"""
self._cloudshell_model_name = value
@property
def model_name(self):
"""
:rtype: str
"""
return self.attributes['CS_Port.Model Name'] if 'CS_Port.Model Name' in self.attributes else None
@model_name.setter
def model_name(self, value=''):
"""
The catalog name of the device model. This attribute will be displayed in CloudShell instead of the CloudShell model.
:type value: str
"""
self.attributes['CS_Port.Model Name'] = value
class GenericPowerPort(object):
def __init__(self, name):
"""
"""
self.attributes = {}
self.resources = {}
self._cloudshell_model_name = 'ApV2.GenericPowerPort'
self._name = name
def add_sub_resource(self, relative_path, sub_resource):
self.resources[relative_path] = sub_resource
@classmethod
def create_from_context(cls, context):
"""
Creates an instance of NXOS by given context
:param context: cloudshell.shell.core.driver_context.ResourceCommandContext
:type context: cloudshell.shell.core.driver_context.ResourceCommandContext
:return:
:rtype GenericPowerPort
"""
result = GenericPowerPort(name=context.resource.name)
for attr in context.resource.attributes:
result.attributes[attr] = context.resource.attributes[attr]
return result
def create_autoload_details(self, relative_path=''):
"""
:param relative_path:
:type relative_path: str
:return
"""
resources = [AutoLoadResource(model=self.resources[r].cloudshell_model_name,
name=self.resources[r].name,
relative_address=self._get_relative_path(r, relative_path))
for r in self.resources]
attributes = [AutoLoadAttribute(relative_path, a, self.attributes[a]) for a in self.attributes]
autoload_details = AutoLoadDetails(resources, attributes)
for r in self.resources:
curr_path = relative_path + '/' + r if relative_path else r
curr_auto_load_details = self.resources[r].create_autoload_details(curr_path)
autoload_details = self._merge_autoload_details(autoload_details, curr_auto_load_details)
return autoload_details
def _get_relative_path(self, child_path, parent_path):
"""
Combines relative path
:param child_path: Path of a model within it parent model, i.e 1
:type child_path: str
:param parent_path: Full path of parent model, i.e 1/1. Might be empty for root model
:type parent_path: str
:return: Combined path
:rtype str
"""
return parent_path + '/' + child_path if parent_path else child_path
@staticmethod
def _merge_autoload_details(autoload_details1, autoload_details2):
"""
Merges two instances of AutoLoadDetails into the first one
:param autoload_details1:
:type autoload_details1: AutoLoadDetails
:param autoload_details2:
:type autoload_details2: AutoLoadDetails
:return:
:rtype AutoLoadDetails
"""
for attribute in autoload_details2.attributes:
autoload_details1.attributes.append(attribute)
for resource in autoload_details2.resources:
autoload_details1.resources.append(resource)
return autoload_details1
@property
def cloudshell_model_name(self):
"""
Returns the name of the Cloudshell model
:return:
"""
return 'GenericPowerPort'
@property
def model(self):
"""
:rtype: str
"""
return self.attributes['ApV2.GenericPowerPort.Model'] if 'ApV2.GenericPowerPort.Model' in self.attributes else None
@model.setter
def model(self, value):
"""
The device model. This information is typically used for abstract resource filtering.
:type value: str
"""
self.attributes['ApV2.GenericPowerPort.Model'] = value
@property
def serial_number(self):
"""
:rtype: str
"""
return self.attributes['ApV2.GenericPowerPort.Serial Number'] if 'ApV2.GenericPowerPort.Serial Number' in self.attributes else None
@serial_number.setter
def serial_number(self, value):
"""
:type value: str
"""
self.attributes['ApV2.GenericPowerPort.Serial Number'] = value
@property
def version(self):
"""
:rtype: str
"""
return self.attributes['ApV2.GenericPowerPort.Version'] if 'ApV2.GenericPowerPort.Version' in self.attributes else None
@version.setter
def version(self, value):
"""
The firmware version of the resource.
:type value: str
"""
self.attributes['ApV2.GenericPowerPort.Version'] = value
@property
def port_description(self):
"""
:rtype: str
"""
return self.attributes['ApV2.GenericPowerPort.Port Description'] if 'ApV2.GenericPowerPort.Port Description' in self.attributes else None
@port_description.setter
def port_description(self, value):
"""
The description of the port as configured in the device.
:type value: str
"""
self.attributes['ApV2.GenericPowerPort.Port Description'] = value
@property
def name(self):
"""
:rtype: str
"""
return self._name
@name.setter
def name(self, value):
"""
:type value: str
"""
self._name = value
@property
def cloudshell_model_name(self):
"""
:rtype: str
"""
return self._cloudshell_model_name
@cloudshell_model_name.setter
def cloudshell_model_name(self, value):
"""
:type value: str
"""
self._cloudshell_model_name = value
@property
def model_name(self):
"""
:rtype: str
"""
return self.attributes['CS_PowerPort.Model Name'] if 'CS_PowerPort.Model Name' in self.attributes else None
@model_name.setter
def model_name(self, value=''):
"""
The catalog name of the device model. This attribute will be displayed in CloudShell instead of the CloudShell model.
:type value: str
"""
self.attributes['CS_PowerPort.Model Name'] = value
| StarcoderdataPython |
3553156 | <filename>seedsource_core/django/seedsource/management/commands/populate_climate_data.py
import os
import numpy
import pyproj
from django.core.management.base import BaseCommand
from django.db import transaction
from ncdjango.models import Service, Variable
from netCDF4 import Dataset
from trefoil.geometry.bbox import BBox
from trefoil.render.renderers.stretched import StretchedRenderer
from trefoil.utilities.color import Color
from ..constants import PERIODS
VARS = (
"MAT",
"MWMT",
"MCMT",
"TD",
"MAP",
"MSP",
"AHM",
"SHM",
"DD_0",
"DD5",
"DD_18",
"bFFP",
"FFP",
"PAS",
"EMT",
"EXT",
"Eref",
"CMD",
"PPT_sm",
"eFFP",
"Tave_wt",
"Tave_sm",
"PPT_wt",
"Tmin_sp",
)
WGS84 = "+proj=latlong +datum=WGS84 +no_defs"
class Command(BaseCommand):
help = (
"Populates a region's services with a DEM and ClimateNA clipped to the region."
)
def add_arguments(self, parser):
parser.add_argument("region_name", nargs=1, type=str)
def handle(self, region_name, *args, **options):
name = region_name[0]
from django.conf import settings
BASE_DIR = settings.NC_SERVICE_DATA_ROOT
# determine extent and lat/lon variable names from DEM
dem_path = os.path.join(BASE_DIR, "regions", name, "{}_dem.nc".format(name))
with Dataset(dem_path, "r") as ds:
dims = ds.dimensions.keys()
lat = "lat" if "lat" in dims else "latitude"
lon = "lon" if "lon" in dims else "longitude"
l = float(ds.variables[lon][:].min())
b = float(ds.variables[lat][:].min())
r = float(ds.variables[lon][:].max())
t = float(ds.variables[lat][:].max())
extent = BBox((l, b, r, t), projection=pyproj.Proj(WGS84))
# Generate DEM service
with transaction.atomic():
print("Adding {}".format(name))
print("---")
print("elevation")
service_name = "{}_dem".format(name)
if Service.objects.filter(name__iexact=service_name).exists():
print("{} already exists, skipping.".format(service_name))
else:
dem_service = Service.objects.create(
name=service_name,
data_path="regions/{name}/{name}_dem.nc".format(name=name),
projection=WGS84,
full_extent=extent,
initial_extent=extent,
)
with Dataset(dem_path, "r") as ds:
v_min = numpy.nanmin(ds.variables["elevation"][:]).item()
v_max = numpy.nanmax(ds.variables["elevation"][:]).item()
renderer = StretchedRenderer(
[(v_min, Color(0, 0, 0)), (v_max, Color(255, 255, 255))]
)
Variable.objects.create(
service=dem_service,
index=0,
variable="elevation",
projection=WGS84,
x_dimension=lon,
y_dimension=lat,
name="elevation",
renderer=renderer,
full_extent=extent,
)
# Generate ClimateNA services
with transaction.atomic():
for year in PERIODS:
print("")
print(year)
print("---")
for var in VARS:
print(var)
service_name = "{}_{}Y_{}".format(name, year, var)
if not Service.objects.filter(name__iexact=service_name).exists():
data_path = (
"regions/{name}/{year}Y/{name}_{year}Y_{var}.nc".format(
name=name, year=year, var=var
)
)
if not os.path.exists(os.path.join(BASE_DIR, data_path)):
print("{} does not exist, skipping.".format(service_name))
continue
service = Service.objects.create(
name=service_name,
data_path=data_path,
projection=WGS84,
full_extent=extent,
initial_extent=extent,
)
with Dataset(
os.path.join(BASE_DIR, service.data_path), "r"
) as ds:
dims = ds.dimensions.keys()
lat = "lat" if "lat" in dims else "latitude"
lon = "lon" if "lon" in dims else "longitude"
v_min = numpy.nanmin(ds.variables[var][:]).item()
v_max = numpy.nanmax(ds.variables[var][:]).item()
renderer = StretchedRenderer(
[(v_min, Color(0, 0, 0)), (v_max, Color(255, 255, 255))]
)
variable = Variable.objects.create(
service=service,
index=0,
variable=var,
projection=WGS84,
x_dimension=lon,
y_dimension=lat,
name=var,
renderer=renderer,
full_extent=extent,
)
else:
print("{} already exists, skipping.".format(service_name))
| StarcoderdataPython |
298590 | import os
import json
import numpy as np
import pandas as pd
save_as_csv = False
print_latex = True
def print_scores(model_desc: dict) -> None:
return " ".join(
[f"{key}@{k}={model_desc[key][i][1]}" for key in ("hit", "ndcg") for i, k in enumerate(model_desc['ks'])])
def print_mean(models: list) -> str:
ret = ""
for key in ("hit", "ndcg"):
for i, k in enumerate([1, 5, 10]):
metric = 0
for m in models:
metric += m[key][i][1]
metric /= len(models)
ret += f"{key}@{k}={metric} "
return ret
def get_mean_and_std(models: list, std: bool = True, get_top_5: bool = True) -> dict:
if get_top_5:
models = models[:5]
mean_calc = {
'hit': [],
'ndcg': []
}
k_values = np.array(models[0]['hit'])[:, 0]
for model in models:
mean_calc['hit'].append(model['hit'])
mean_calc['ndcg'].append(model['ndcg'])
for metric in ['hit', 'ndcg']:
metric_array = np.array(mean_calc[metric])
means = np.mean(metric_array[:, :, 1], axis=0)
if not std:
mean_calc[metric] = [[idx, str(round(mean * 100, 1))] for idx, mean in zip(k_values, means)]
else:
std_devs = np.std(metric_array[:, :, 1], axis=0)
mean_calc[metric] = [[idx, str(round(mean * 100, 1)) + "±" + str(round(std * 100, 1))]
for idx, mean, std in zip(k_values, means, std_devs)]
return mean_calc
def get_eval_dict(file_path: str = "data/journal_runs/results.json",
sort_key: str = "val_hit",
data_dirs: list = ("data/files-n10", "data/files-n5"),
verbose: int = 1,
std_dev: bool = True) -> dict:
def check(curr_dict: dict) -> bool:
return curr_dict['task'] == task and curr_dict['data_dir'] == data_dir
with open(file_path, "r", encoding='utf-8') as f:
tmp = f.readlines()
tmp = [json.loads(x) for x in tmp]
eval_dict = {}
for data_dir in data_dirs:
eval_dict[data_dir] = {}
for task in ["new", "existing"]:
if verbose:
print("-" * 30 + data_dir + " " + task + "-" * 30)
curr_best_models = {}
curr = [x for x in tmp if check(x)]
# Baselines
for baseline in ["majority", "author_majority", "graph"]:
baseline_config = [x for x in curr if check(x) and "model" in x and baseline in x["model"]]
if verbose:
print(baseline.replace("_", " ").title() + " " + str(len(baseline_config)))
if len(baseline_config) > 0:
if verbose:
print(print_mean(baseline_config[:5]))
mean = get_mean_and_std(baseline_config, std=std_dev)
curr_best_models[baseline] = mean
else:
curr_best_models[baseline] = {"hit": [[1, "---"], [5, "---"], [10, "---"]],
"ndcg": [[1, "---"], [5, "---"], [10, "---"]]}
if verbose:
print("Having ", len(curr), "models. Baselines are ", curr_best_models.items())
# other models
for model_type in ["og_model", "bucket_embedding", "paper_embedding", "pretrained_author_embedding",
"paper_author_embedding", "weighted_embedding", "seq-model", "nova_model", "cobert_model"]:
if model_type == "seq-model" or model_type == "nova_model" or model_type == "cobert_model":
current = sorted([x for x in curr if model_type in x and x[model_type]],
key=lambda x: x[sort_key][0][1], reverse=True)
elif model_type == "weighted_embedding":
current = sorted([x for x in curr if model_type in x and x[model_type] and not x["seq-model"]],
key=lambda x: x[sort_key][0][1], reverse=True)
elif model_type == "paper_author_embedding":
current = sorted([x for x in curr if "og_model" in x and x["pretrained_author_embedding"] and
x["paper_embedding"] and not x["seq-model"] and not x["weighted_embedding"]],
key=lambda x: x[sort_key][0][1], reverse=True)
elif model_type == "pretrained_author_embedding":
current = sorted([x for x in curr if "og_model" in x and x["pretrained_author_embedding"]
and not x["paper_embedding"] and not x["seq-model"]
and not x["weighted_embedding"]],
key=lambda x: x[sort_key][0][1], reverse=True)
elif model_type == "paper_embedding":
current = sorted([x for x in curr if "og_model" in x and x["paper_embedding"]
and not x["pretrained_author_embedding"] and not x["seq-model"]
and not x["weighted_embedding"]],
key=lambda x: x[sort_key][0][1], reverse=True)
elif model_type == "bucket_embedding":
current = sorted([x for x in curr if model_type in x and x[model_type]],
key=lambda x: x[sort_key][0][1], reverse=True)
else: # orig
current = sorted([x for x in curr if model_type in x and x[model_type] and not x["seq-model"]
and not x["weighted_embedding"]], key=lambda x: x[sort_key][0][1], reverse=True)
if verbose:
print(f"{model_type.replace('_', ' ').title()}: {len(current)}")
if len(current) > 0:
if verbose:
print(print_mean(current[:5]))
for i in range(min(5, len(current))):
print(current[i]['id'])
print([(x, current[i][x]) for x in ['hit', 'ndcg', 'val_hit', 'val_ndcg']])
mean = get_mean_and_std(current, std=std_dev)
curr_best_models[model_type] = mean
else:
print("Fail.")
eval_dict[data_dir][task] = curr_best_models
return eval_dict
def print_main_table(eval_dict: dict) -> None:
print()
for data_dir, tasks in eval_dict.items():
for task_name, results in tasks.items():
curr = {"models": ["Majority", "Majority (Author)", "Graph", "BERT4Rec", "CoBERT", "CoBERT-W", "CoBERT-Seq"]}
curr.update({x[0]: [results['majority'][x[1]][x[2]][1],
results['author_majority'][x[1]][x[2]][1],
results['graph'][x[1]][x[2]][1],
results['og_model'][x[1]][x[2]][1],
results['paper_author_embedding'][x[1]][x[2]][1],
results['weighted_embedding'][x[1]][x[2]][1],
results['seq-model'][x[1]][x[2]][1] if 'seq-model' in results else "---"] for x in
[["Acc.", "hit", 0], ["Hit@5", "hit", 1], ["Hit@10", "hit", 2], ["NDCG@5", "ndcg", 1],
["NDCG@10", "ndcg", 2]]})
df = pd.DataFrame(curr)
# print(df)
print(df.to_latex(index=False, caption=data_dir.split("/")[1].split("-")[1] + "-" + task_name, label="tab:" + data_dir.split("/")[1].split("-")[1] + "-" + task_name))
def print_ablation_study(eval_dict: dict, models: list, dataset: str, task: str) -> None:
curr = eval_dict[dataset][task]
df_dict = {"models": ["No ACE, PCE & PPE", "No ACE & PCE", "No PCE", "No ACE", "CoBERT"]}
for k, v in curr.items():
if k in models:
print(k, ": ", v)
print()
for metric in [("Acc.", 'hit', 0), ("Hit@5", "hit", 1), ("Hit@10", "hit", 2), ("NCDG@5", "ndcg", 1), ("NCDG@10", "ndcg", 2)]:
curr_list = []
for model in models:
curr_list.append(curr[model][metric[1]][metric[2]][1])
df_dict[metric[0]] = curr_list
df = pd.DataFrame(df_dict)
dataset_name = "PlosOne" if "medline" in dataset else "AI"
dataset_size = "$n=5$" if "n5" in dataset else "$n=10$"
task_name = "any" if task == "ranking" else "new"
print(df.to_latex(index=False, caption="Ablation study based on the " + dataset_name + " dataset with " +
dataset_size + " in the predicting " + task_name + " collaborator task.",
label="tab:" + dataset_name + "-" + dataset_size.replace("$", "").replace("=", "") + "-" + task_name))
def analyse_embedding_weights(path_to_file: str) -> None:
from collections import namedtuple
from util.factory import get_model
import torch
import os
with open(os.path.join(path_to_file, "config.json"), 'r', encoding='utf-8') as f:
config = json.load(f)
args = namedtuple('Struct', config.keys())(*config.values())
model = get_model(args)
model.load_state_dict(torch.load(os.path.join(path_to_file, "model.pt"), map_location=torch.device('cpu')))
for name, param in model.named_parameters():
if param.requires_grad and name == "embedding.embedding_weights":
print(name, ":", param.data)
if __name__ == '__main__':
print_main = True
print_ablation = False
analyse_weights = False
eval_dict = get_eval_dict(file_path=os.path.join("data", "journal_runs", "results_new.json"),
data_dirs=[os.path.join("data", "files-n5-ai-temporal")], verbose=True)
if print_main:
print_main_table(eval_dict=eval_dict)
if print_ablation:
for data in ["data/files-n5", "data/files-n10", "data/files-n5-medline", "data/files-n10-medline"]:
for task in ["existing", "new"]:
print_ablation_study(eval_dict=eval_dict, dataset=data, task=task,
models=["og_model", "bucket_embedding", "pretrained_author_embedding",
"paper_embedding", "paper_author_embedding"])
if analyse_weights:
print("Weights: Token, Author, Position")
for file in ["9c08458b1f42", "404a4045ac29", "35c9013b868a"]: # PlosOne - AI
analyse_embedding_weights(path_to_file=os.path.join("data", "runs", file))
| StarcoderdataPython |
5038617 | <filename>scripts/analysis/submit.py
#!/usr/bin/env python
import os
import sys
import subprocess
from datetime import datetime
from datetime import timedelta
import time
import time
year=2014
month=9
count=0
for month in range(7,11):
for day in xrange(31):
day += 1
start=datetime(year, month, day)
#end = datetime(2013, 12, 1)
end = start + timedelta(days=1)
idx = 0
while start < end:
tomorrow = start + timedelta(days=1)
args = ["qsub", "-l", "h_rt=4:00:00", "-pe", "pe_8", "8", "-l", "ram.c=5G", "-wd", os.environ['BSCRATCH'], "procHunter.sh", start.strftime("%Y-%m-%d"), tomorrow.strftime("%Y-%m-%d"), "%s/garbage/processes%s" % (os.environ["GSCRATCH"], start.strftime("%Y%m%d")), "asdf", "asdf"]
print args
subprocess.call(args)
start += timedelta(days=1)
idx += 1
count += 1
if count == 30:
time.sleep(15)
count = 0
| StarcoderdataPython |
9659198 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Title : PyRogue feb Module
#-----------------------------------------------------------------------------
# File : _feb.py
# Created : 2017-02-15
# Last update: 2017-02-15
#-----------------------------------------------------------------------------
# Description:
# PyRogue Feb Module
#-----------------------------------------------------------------------------
# This file is part of the 'LSST Firmware'. It is subject to
# the license terms in the LICENSE.txt file found in the top-level directory
# of this distribution and at:
# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
# No part of the 'LSST Firmware', including this file, may be
# copied, modified, propagated, or distributed except according to the terms
# contained in the LICENSE.txt file.
#-----------------------------------------------------------------------------
import rogue
import pyrogue as pr
import pyrogue.interfaces.simulation
import pyrogue.protocols
import surf.axi as axi
import surf.devices.micron as micron
import surf.xilinx as xilinx
AXIL_STRIDE = 0x40000
AXIL_OFFSETS = [x*AXIL_STRIDE for x in range(10)]
class LsstPwrCtrlCore(pr.Device):
def __init__(self,
expand = False,
offset = 0x0,
**kwargs):
super().__init__(
expand = expand,
offset = 0x0, # This module assume offset 0x0
**kwargs)
self.add(axi.AxiVersion(
offset = AXIL_OFFSETS[7],
expand = False,
))
self.add(xilinx.Xadc(
offset = AXIL_OFFSETS[8],
expand = False,
))
self.add(micron.AxiMicronN25Q(
offset = AXIL_OFFSETS[9],
addrMode = False, # Assume 24-bit address support only
hidden = True,
))
self.add(pr.RemoteVariable(
name = 'LSST_PWR_CORE_VERSION_C',
description = 'See LsstPwrCtrlPkg.vhd for definitions',
offset = AXIL_OFFSETS[7] + 0x400, # 0x1C0400
base = pr.UInt,
mode = 'RO',
))
self.add(pr.RemoteVariable(
name = 'BOARD_ID',
description = 'eFuse[7:0] value',
offset = AXIL_OFFSETS[7] + 0x404, # 0x1C0404
base = pr.UInt,
bitSize = 8,
mode = 'RO',
))
self.add(pr.RemoteVariable(
name = 'NUM_LANE_G',
description = 'Number of Ethernet lanes',
offset = AXIL_OFFSETS[7] + 0x408, # 0x1C0408
base = pr.UInt,
mode = 'RO',
))
class LsstPwrCtrlRoot(pr.Root):
def __init__(self,
hwEmu = False,
sim = False,
rssiEn = False,
ip = '192.168.1.10',
**kwargs):
super().__init__(**kwargs)
# Check if emulating the GUI interface
if (hwEmu):
# Create emulated hardware interface
print ("Running in Hardware Emulation Mode")
self.srp = pyrogue.interfaces.simulation.MemEmulate()
else:
# Create srp interface
self.srp = rogue.protocols.srp.SrpV3()
if sim:
dest = pyrogue.interfaces.simulation.StreamSim(host='localhost', dest=0, uid=0, ssi=True)
pyrogue.streamConnectBiDir(self.srp, dest)
else:
# Check for RSSI
if (rssiEn):
# UDP + RSSI
udp = pyrogue.protocols.UdpRssiPack( host=ip, port=8192, size=1500 )
# Connect the SRPv3 to tDest = 0x0
pyrogue.streamConnectBiDir(self.srp, udp.application(dest=0x0) )
else:
# UDP only
udp = rogue.protocols.udp.Client( ip, 8192, 1500 )
# Connect the SRPv3 to UDP
pyrogue.streamConnectBiDir(self.srp, udp )
| StarcoderdataPython |
6499179 | # Copyright 2017 Scalyr Inc.
#
# 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.
# ------------------------------------------------------------------------
#
# author: <NAME> <<EMAIL>>
from __future__ import unicode_literals
from __future__ import absolute_import
__author__ = "<EMAIL>"
from scalyr_agent.compat import custom_defaultdict as defaultdict
from scalyr_agent.builtin_monitors.linux_process_metrics import (
ProcessMonitor,
Metric,
ProcessList,
)
from scalyr_agent.test_base import ScalyrTestCase
import scalyr_agent.scalyr_logging as scalyr_logging
from scalyr_agent.scalyr_monitor import MonitorInformation
from six.moves import range
class MetricInformationTestCase(ScalyrTestCase):
def test_define_metric_metric_units(self):
# Verify all the metrics have the correct type defined
monitor_info = MonitorInformation.get_monitor_info(
"scalyr_agent.builtin_monitors.linux_process_metrics"
)
metrics = monitor_info.metrics
self.assertEqual(len(metrics), 14)
disk_requests_metrics = [
m for m in metrics if m.metric_name == "app.disk.requests"
]
self.assertEqual(len(disk_requests_metrics), 2)
self.assertEqual(disk_requests_metrics[0].unit, None)
self.assertEqual(disk_requests_metrics[1].unit, None)
class TestMetricClass(ScalyrTestCase):
def test_metric_as_object_key(self):
"""
This protects against a bug introduced in v2.0.47 whereby the Metric object didn't implement __hash__ and
__eq__ dunder methods. Metric is repeatedly used as a key during linux process metrics generation.
Without those dunder methods, the key/val is never replaced and the dictionary keeps growing.
(Reference AGENT-142)
"""
dd = {}
for x in range(1000):
dd[Metric("name1a", "name1b")] = x
dd[Metric("name2a", "name2b")] = x
dd[Metric("name3a", "name3b")] = x
dd[Metric("name4a", "name4b")] = x
dd[Metric("name5a", "name5b")] = x
self.assertEqual(len(dd), 5)
self.assertEqual(dd[Metric("name1a", "name1b")], 999)
self.assertEqual(dd[Metric("name2a", "name2b")], 999)
self.assertEqual(dd[Metric("name3a", "name3b")], 999)
self.assertEqual(dd[Metric("name4a", "name4b")], 999)
self.assertEqual(dd[Metric("name5a", "name5b")], 999)
dd = {}
for x in range(1000):
dd[Metric("name1a", "name1b")] = 1
dd[Metric("name2a", "name2b")] = 1
dd[Metric("name3a", "name3b")] = 1
dd[Metric("name4a", "name4b")] = 1
dd[Metric("name5a", "name5b")] = 1
self.assertEqual(len(dd), 5)
self.assertEqual(dd[Metric("name1a", "name1b")], 1)
self.assertEqual(dd[Metric("name2a", "name2b")], 1)
self.assertEqual(dd[Metric("name3a", "name3b")], 1)
self.assertEqual(dd[Metric("name4a", "name4b")], 1)
self.assertEqual(dd[Metric("name5a", "name5b")], 1)
def test_basic_namedtuple_access(self):
m = Metric("abc", 123)
# Ensure name and type fields are present
self.assertEquals(m.name, "abc")
self.assertEquals(m.type, 123)
# Non-existent
self.assertRaises(AttributeError, lambda: m.asdf) # pylint: disable=no-member
# Ensure cannot mutate
def mutate():
m.name = "mutated value"
self.assertRaises(AttributeError, lambda: mutate())
class TestProcessMonitorInitialize(ScalyrTestCase):
def setUp(self):
super(TestProcessMonitorInitialize, self).setUp()
self.config_commandline = {
"module": "scalyr_agent.builtin_monitors.linux_process_metrics",
"id": "myapp",
"commandline": ".foo.*",
}
def test_initialize_monitor(self):
monitor = ProcessMonitor(
self.config_commandline, scalyr_logging.getLogger("syslog_monitor[test]")
)
self.assertEqual(monitor._ProcessMonitor__metrics_history, defaultdict(dict))
self.assertEqual(monitor._ProcessMonitor__aggregated_metrics, {})
class TestProcessMonitorRecordMetrics(ScalyrTestCase):
"""
Tests the record_metrics method of ProcessMonitor class
"""
def setUp(self):
super(TestProcessMonitorRecordMetrics, self).setUp()
self.config_commandline = {
"module": "scalyr_agent.builtin_monitors.linux_process_metrics",
"id": "myapp",
"commandline": ".foo.*",
}
self.monitor = ProcessMonitor(
self.config_commandline, scalyr_logging.getLogger("syslog_monitor[test]")
)
def test_empty_metrics(self):
self.monitor.record_metrics(666, {})
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, defaultdict(dict)
)
def test_single_process_single_epoch(self):
metric = Metric("fakemetric", "faketype")
metrics = {metric: 21}
self.monitor.record_metrics(555, metrics)
expected_history = {555: {metric: [21]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {})
def test_single_process_multiple_epochs(self):
metric = Metric("fakemetric", "faketype")
# epoch 1
self.monitor.record_metrics(777, {metric: 1.2})
expected_history = {777: {metric: [1.2]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {})
# epoch 2
self.monitor.record_metrics(777, {metric: 1.9})
expected_history = {777: {metric: [1.2, 1.9]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {})
def test_multi_process_single_epoch(self):
metric1 = Metric("fakemetric1", "faketype1")
metric2 = Metric("fakemetric2", "faketype2")
self.monitor.record_metrics(111, {metric1: 1.2})
self.monitor.record_metrics(222, {metric2: 2.87})
expected_history = {111: {metric1: [1.2]}, 222: {metric2: [2.87]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {})
def test_multi_process_multi_epochs(self):
metric1 = Metric("fakemetric1", "faketype1")
metric2 = Metric("fakemetric2", "faketype2")
# epoch 1
self.monitor.record_metrics(111, {metric1: 1.2})
self.monitor.record_metrics(222, {metric2: 2.87})
expected_history = {111: {metric1: [1.2]}, 222: {metric2: [2.87]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {})
# epoch 2
self.monitor.record_metrics(111, {metric1: 1.6})
self.monitor.record_metrics(222, {metric2: 2.92})
expected_history = {111: {metric1: [1.2, 1.6]}, 222: {metric2: [2.87, 2.92]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {})
class TestProcessListUtility(ScalyrTestCase):
def setUp(self):
super(TestProcessListUtility, self).setUp()
self.ps = ProcessList()
def test_no_process(self):
# override
self.ps.parent_to_children_map = defaultdict(list)
self.ps.processes = []
self.assertEqual(self.ps.get_child_processes("bad pid"), [])
self.assertEqual(self.ps.get_matches_commandline(".*"), [])
self.assertEqual(self.ps.get_matches_commandline_with_children(".*"), [])
def test_single_process_no_children(self):
# override
# process id 0 is basically no process. PID 1 is the main process of a terminal
self.ps.processes = [
{"pid": 2, "ppid": 1, "cmd": "python hello.py"},
{"pid": 1, "ppid": 0, "cmd": "/bin/bash"},
]
self.ps.parent_to_children_map = defaultdict(list)
self.ps.parent_to_children_map[1] = [2]
self.ps.parent_to_children_map[0] = [1]
self.assertEqual(self.ps.get_child_processes("bad pid"), [])
self.assertEqual(self.ps.get_child_processes(1), [2])
# positive match
self.assertEqual(set(self.ps.get_matches_commandline(".*")), set([1, 2]))
self.assertEqual(self.ps.get_matches_commandline(".*bash.*"), [1])
self.assertEqual(self.ps.get_matches_commandline(".*py.*"), [2])
self.assertEqual(
set(self.ps.get_matches_commandline_with_children(".*")), set([1, 2])
)
def test_single_process_with_children(self):
# override
# process id 0 is basically no process. PID 1 is the main process of a terminal
self.ps.processes = [
{"pid": 2, "ppid": 1, "cmd": "python hello.py"},
{"pid": 3, "ppid": 2, "cmd": "sleep 2"},
{"pid": 1, "ppid": 0, "cmd": "/bin/bash"},
]
self.ps.parent_to_children_map = defaultdict(list)
self.ps.parent_to_children_map[1] = [2]
self.ps.parent_to_children_map[2] = [3]
self.ps.parent_to_children_map[0] = [1]
self.assertEqual(self.ps.get_child_processes("bad pid"), [])
self.assertEqual(set(self.ps.get_child_processes(1)), set([2, 3]))
self.assertEqual(self.ps.get_child_processes(2), [3])
# positive match
self.assertEqual(set(self.ps.get_matches_commandline(".*")), set([1, 2, 3]))
self.assertEqual(self.ps.get_matches_commandline(".*bash.*"), [1])
self.assertEqual(self.ps.get_matches_commandline(".*py.*"), [2])
self.assertEqual(
set(self.ps.get_matches_commandline_with_children(".*")), set([1, 2, 3])
)
def test_multiple_processes_with_children(self):
# override
# process id 0 is basically no process. PID 1 is the main process of a terminal
self.ps.processes = [
{"pid": 2, "ppid": 1, "cmd": "python hello.py"},
{"pid": 3, "ppid": 2, "cmd": "sleep 2"},
{"pid": 1, "ppid": 0, "cmd": "/bin/bash"},
{"pid": 4, "ppid": 0, "cmd": "sleep 10000"},
]
self.ps.parent_to_children_map = defaultdict(list)
self.ps.parent_to_children_map[1] = [2]
self.ps.parent_to_children_map[2] = [3]
self.ps.parent_to_children_map[0] = [1, 4]
self.assertEqual(self.ps.get_child_processes("bad pid"), [])
self.assertEqual(set(self.ps.get_child_processes(1)), set([2, 3]))
self.assertEqual(self.ps.get_child_processes(2), [3])
# positive match
self.assertEqual(set(self.ps.get_matches_commandline(".*")), set([1, 2, 3, 4]))
self.assertEqual(self.ps.get_matches_commandline(".*bash.*"), [1])
self.assertEqual(self.ps.get_matches_commandline(".*py.*"), [2])
self.assertEqual(
set(self.ps.get_matches_commandline_with_children(".*")), set([1, 2, 3, 4])
)
class TestProcessMonitorRunningTotal(ScalyrTestCase):
"""
Tests the calculations of the running totals of the metrics.
"""
def setUp(self):
super(TestProcessMonitorRunningTotal, self).setUp()
self.config_commandline = {
"module": "scalyr_agent.builtin_monitors.linux_process_metrics",
"id": "myapp",
"commandline": ".foo.*",
}
self.monitor = ProcessMonitor(
self.config_commandline, scalyr_logging.getLogger("syslog_monitor[test]")
)
def test_no_history(self):
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {})
def test_single_process_single_epoch(self):
metric = Metric("fakemetric", "faketype")
metrics = {metric: 21}
self.monitor.record_metrics(555, metrics)
self.monitor._ProcessMonitor__pids = [555]
self.monitor._calculate_aggregated_metrics()
expected_history = {555: {metric: [21]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {metric: 21})
def test_single_process_multiple_epoch(self):
metric = Metric("fakemetric", "faketype")
# epoch 1
metrics = {metric: 21}
self.monitor.record_metrics(555, metrics)
self.monitor._ProcessMonitor__pids = [555]
self.monitor._calculate_aggregated_metrics()
expected_history = {555: {metric: [21]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {metric: 21})
# epoch 2
# before epoch 2, the reset is called for absolute metrics
self.monitor._reset_absolute_metrics()
metrics = {metric: 21.5}
self.monitor.record_metrics(555, metrics)
self.monitor._ProcessMonitor__pids = [555]
self.monitor._calculate_aggregated_metrics()
expected_history = {555: {metric: [21, 21.5]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics, {metric: 21.5}
)
def test_multiple_process_multiple_epochs(self):
metric1 = Metric("fakemetric1", "faketype1")
metric2 = Metric("fakemetric2", "faketype2")
# epoch 1
metrics1 = {metric1: 21}
metrics2 = {metric2: 100.0}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [21]}, 2: {metric2: [100.0]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: 21, metric2: 100.0},
)
# epoch 2
# before epoch 2, the reset is called for absolute metrics
self.monitor._reset_absolute_metrics()
metrics1 = {metric1: 21.11}
metrics2 = {metric2: 100.11}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [21, 21.11]}, 2: {metric2: [100.0, 100.11]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: 21.11, metric2: 100.11},
)
def test_multiple_process_multiple_epochs_cumulative_metrics(self):
metric1 = Metric("app.cpu", "system")
# epoch 1
metrics1 = {metric1: 20}
metrics2 = {metric1: 40}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [20]}, 2: {metric1: [40]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {metric1: 0})
# epoch 2
# before epoch 2, the reset is called for absolute metrics
self.monitor._reset_absolute_metrics()
metrics1 = {metric1: 22}
metrics2 = {metric1: 44}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [20, 22]}, 2: {metric1: [40, 44]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: (22 - 20) + (44 - 40)},
)
# epoch 3
self.monitor._reset_absolute_metrics()
metrics1 = {metric1: 25}
metrics2 = {metric1: 48}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
# we only keep the last 2 historical values
expected_history = {1: {metric1: [22, 25]}, 2: {metric1: [44, 48]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: (22 - 20) + (44 - 40) + (25 - 22) + (48 - 44)},
)
def test_multiple_process_multiple_epochs_cumulative_metrics_one_process_death(
self,
):
"""
Same as test_multiple_process_multiple_epochs_cumulative_metrics
but one process dies after epoch 2
"""
metric1 = Metric("app.cpu", "system")
# epoch 1
metrics1 = {metric1: 21}
metrics2 = {metric1: 100.0}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [21]}, 2: {metric1: [100.0]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {metric1: 0})
# epoch 2
# before epoch 2, the reset is called for absolute metrics
self.monitor._reset_absolute_metrics()
metrics1 = {metric1: 30.1}
metrics2 = {metric1: 100.2}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [21, 30.1]}, 2: {metric1: [100.0, 100.2]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: (30.1 - 21) + (100.2 - 100.0)},
)
# epoch 3
self.monitor._reset_absolute_metrics()
metrics1 = {metric1: 26.0}
metrics2 = {metric1: 103}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
# Process 1 dies.. boom
self.monitor._ProcessMonitor__pids = [2]
self.monitor._calculate_aggregated_metrics()
# we only keep the last 2 historical values
expected_history = {1: {metric1: [30.1, 26.0]}, 2: {metric1: [100.2, 103]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: (30.1 - 21) + (100.2 - 100.0) + (103 - 100.2)},
)
def test_multiple_process_multiple_epochs_cumulative_metrics_all_process_death(
self,
):
"""
Same as test_multiple_process_multiple_epochs_cumulative_metrics_one_process_death
but all processes die after epoch 2
"""
metric1 = Metric("app.cpu", "system")
# epoch 1
metrics1 = {metric1: 20}
metrics2 = {metric1: 40}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [20]}, 2: {metric1: [40]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(self.monitor._ProcessMonitor__aggregated_metrics, {metric1: 0})
# epoch 2
# before epoch 2, the reset is called for absolute metrics
self.monitor._reset_absolute_metrics()
metrics1 = {metric1: 25}
metrics2 = {metric1: 46}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
self.monitor._ProcessMonitor__pids = [1, 2]
self.monitor._calculate_aggregated_metrics()
expected_history = {1: {metric1: [20, 25]}, 2: {metric1: [40, 46]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: (25 - 20) + (46 - 40)},
)
# epoch 3
self.monitor._reset_absolute_metrics()
metrics1 = {metric1: 23}
metrics2 = {metric1: 43}
self.monitor.record_metrics(1, metrics1)
self.monitor.record_metrics(2, metrics2)
# Process 1 and 2 die.. boom
# we should ensure the total running value for metric doesn't go down.
self.monitor._ProcessMonitor__pids = []
self.monitor._calculate_aggregated_metrics()
# we only keep the last 2 historical values
expected_history = {1: {metric1: [25, 23]}, 2: {metric1: [46, 43]}}
self.assertEqual(
self.monitor._ProcessMonitor__metrics_history, expected_history
)
self.assertEqual(
self.monitor._ProcessMonitor__aggregated_metrics,
{metric1: (25 - 20) + (46 - 40)},
)
| StarcoderdataPython |
8058495 | <filename>nSum.py
"""
You are given an array of n integers and a number k. Determine whether there is a pair
of elements in the array that sums to exactly k. For example, given the array [1, 3, 7] and
k = 8, the answer is “yes,” but given k = 6 the answer is “no.”
Ex)
---------------------------------------------------------------------------------------------
arr = [1, 3, 7] ; k = 8
=> 1 + 7 == 8 => return [0, 2] => return "yes"
arr = [1, 3, 7] ; k = 6
=> return "no"
---------------------------------------------------------------------------------------------
Time: O(n^2) where n is len(arr)
Space: O(1)
- bruteforce look at all pairs
Time: O(n) - one pass
Space: O(n) - hashmap (take advantage of the constant time look up that dict gives us)
- hashmap
Extended: consider threeSum variant....
Time: O(n^3) where n is len(arr)
Space: O(1)
- bruteforce look at all pairs
Time: O(n^2) - quadratic
Space: O(n) - hashmap (take advantage of the constant time look up that dict gives us)
- hashmap
"""
from typing import List
class Solution:
def slowTwoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0, len(nums)-1):
for j in range(i+1, len(nums)):
if (target == nums[i] + nums[j]):
return [i, j]
return []
def fastTwoSumUnordered(self, nums: List[int], target: int) -> List[int]: # assumes unordered input
_dict = {} # init dict
for i in range(0, len(nums)): # iterate over array and add num[i] to map
comp = target - nums[i] # compute complement
if (comp in _dict): # if complement has been cached, return it
return [_dict[comp], i]
_dict[nums[i]] = i
return False
def fastTwoSumOrdered(self, nums: List[int], target: int) -> List[int]: # assumes ordered input
l, r = 0, len(nums)-1
while (l<r):
curSum = nums[l] + nums[r]
if (curSum > target): # we desire a smaller sum
r -= 1
elif (curSum < target): # we desire a larger sum
l += 1
else:
return [l, r]
def slowThreeSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0, len(nums)-2):
for j in range(i+1, len(nums)-1):
for k in range(j+1, len(nums)):
if (target == nums[i] + nums[j] + nums[k]):
return [i, j, k]
return []
def fastThreeSumUnsorted(self, nums: List[int], target: int) -> List[int]:
# We can reduce 3SUM to 2SUM: a + b + c = k => a + b = k - c = l
arr = []
nums.sort() # efficient sort
for c in range(1, len(nums)-2):
if (c == 0 or (c > 0 and nums[c] != nums[c-1])):
l, r = c+1, len(nums)-1
while (l<r):
curSum = nums[l] + nums[r] + nums[c]
if (curSum < target): # we desire a smaller sum
l += 1
elif (curSum > target): # we desire a larger sum
r -= 1
else:
arr.append([nums[c], nums[l], nums[r]])
while (l < r and nums[l] == nums[l+1]): l+=1
while (l < r and nums[r] == nums[r-1]): r-=1
l+=1
r-=1
return arr
obj = Solution()
print(obj.fastThreeSumUnsorted([-1,0,1,2,-1,-4], 0)) | StarcoderdataPython |
5054610 | <filename>pandas/reset_dataframe_index.py
original_df = original_df.set_index("序号")
| StarcoderdataPython |
5031436 | <filename>models/modules/rnlu.py
import torch
from torch.autograd.function import InplaceFunction
from torch.autograd import Variable
import torch.nn as nn
import math
class BiReLUFunction(InplaceFunction):
@classmethod
def forward(cls, ctx, input, inplace=False):
if input.size(1) % 2 != 0:
raise RuntimeError("dimension 1 of input must be multiple of 2, "
"but got {}".format(input.size(1)))
ctx.inplace = inplace
if ctx.inplace:
ctx.mark_dirty(input)
output = input
else:
output = input.clone()
pos, neg = output.chunk(2, dim=1)
pos.clamp_(min=0)
neg.clamp_(max=0)
# scale = (pos - neg).view(pos.size(0), -1).mean(1).div_(2)
# output.
ctx.save_for_backward(output)
return output
@staticmethod
def backward(ctx, grad_output):
output, = ctx.saved_variables
grad_input = grad_output.masked_fill(output.eq(0), 0)
return grad_input, None
def birelu(x, inplace=False):
return BiReLUFunction().apply(x, inplace)
class BiReLU(nn.Module):
"""docstring for BiReLU."""
def __init__(self, inplace=False):
super(BiReLU, self).__init__()
self.inplace = inplace
def forward(self, inputs):
return birelu(inputs, inplace=self.inplace)
def binorm(x, shift=0, scale_fix=(2 / math.pi) ** 0.5):
pos, neg = (x + shift).split(2, dim=1)
scale = (pos - neg).view(pos.size(0), -1).mean(1).div_(2) * scale_fix
return x / scale
def _mean(p, dim):
"""Computes the mean over all dimensions except dim"""
if dim is None:
return p.mean()
elif dim == 0:
output_size = (p.size(0),) + (1,) * (p.dim() - 1)
return p.contiguous().view(p.size(0), -1).mean(dim=1).view(*output_size)
elif dim == p.dim() - 1:
output_size = (1,) * (p.dim() - 1) + (p.size(-1),)
return p.contiguous().view(-1, p.size(-1)).mean(dim=0).view(*output_size)
else:
return _mean(p.transpose(0, dim), 0).transpose(0, dim)
def rnlu(x, inplace=False, shift=0, scale_fix=(math.pi / 2) ** 0.5):
x = birelu(x, inplace=inplace)
pos, neg = (x + shift).chunk(2, dim=1)
# scale = torch.cat((_mean(pos, 1), -_mean(neg, 1)), 1) * scale_fix + 1e-5
scale = (pos - neg).view(pos.size(0), -1).mean(1) * scale_fix + 1e-8
return x / scale.view(scale.size(0), *([1] * (x.dim() - 1)))
class RnLU(nn.Module):
"""docstring for RnLU."""
def __init__(self, inplace=False):
super(RnLU, self).__init__()
self.inplace = inplace
def forward(self, x):
return rnlu(x, inplace=self.inplace)
# output.
if __name__ == "__main__":
x = Variable(torch.randn(2, 16, 5, 5).cuda(), requires_grad=True)
output = rnlu(x)
output.sum().backward()
| StarcoderdataPython |
11265196 | <reponame>sunlightlabs/foodtrucks
#!/bin/python
import re
import sys
transformations = {
re.compile(r'l\'?enfant', re.I): lambda complete, extracted: len(extracted.strip())>0 and extracted + " S.W." or "L'Enfant Plaza Metro",
re.compile(r'mcpherson', re.I): lambda complete, extracted: len(extracted.strip())>0 and extracted + " N.W." or "McPherson Square",
re.compile(r'ballston', re.I): lambda complete, extracted: len(extracted.strip())==0 and "Ballston Metro" or extracted,
re.compile(r'tomorrow', re.I): lambda complete, extracted: "",
}
whitelist = "(dupont|u st|farragut|gallery pl|union station|L'Enfant|McPherson)"
numbered = "(1st|2nd|3rd|[0-9]+(th)?)"
street = "(((new\s|north\s|south\s|west\s)?\w+)( ave| st)?|%(numbered)s)" % {'numbered': numbered}
cross_street = "((%(numbered)s ?((and)|&) ?%(street)s)|(%(street)s ?((and)|&) ?%(numbered)s))" % {'street': street, 'numbered': numbered}
# >>>>>>> 68f1336cd91c9a119be9b52ae35a2793f5a23fb1
exact = "([0-9]+ \w+ (ave|st))"
address = '(((%(street)s between )?%(cross)s)|%(exact)s|%(whitelist)s)' % \
{'street': street, 'cross': cross_street, 'exact': exact, 'whitelist': whitelist}
quadrant = re.compile(r'\s([NS])\.?([WE])\.?($|\W)')
exp = re.compile(address, re.I)
def extract(line):
# TODO: remove hardcoded 'washington, dc' suffix from upstream function
match = exp.search(line)
quadrant_match = quadrant.search(line)
m = None
if match:
m = match
quadrant_string = ""
if quadrant_match:
quadrant_string = " %s.%s." % (quadrant_match.group(1), quadrant_match.group(2))
extracted_text = ""
if m is not None:
extracted_text = m.group(1)
for (regex, xform) in transformations.items():
if regex.search(line) is not None:
extracted_text = xform(line, extracted_text)
if len(extracted_text)>0:
return extracted_text + quadrant_string
else:
return None
if __name__ == '__main__':
matched = list()
unmatched = list()
for line in sys.stdin:
match = extract(line)
if match:
matched.append("%s <--- %s" % (match, line.strip()))
else:
unmatched.append(line.strip())
print "%d lines matched:" % len(matched)
for line in matched:
print line
print "\n%d lines not matched:" % len(unmatched)
for line in unmatched:
print line
| StarcoderdataPython |
6491756 | """
-------------------------------------------------------------------------
AIOpening - __init__.py
Defines all RL algorithms that live in aiopening
created: 2017/09/01 in PyCharm
(c) 2017 Sven - ducandu GmbH
-------------------------------------------------------------------------
"""
from .a3c import A3C
from .base import Algorithm
| StarcoderdataPython |
12861744 | from suppy.utils.stats_constants import DIVERGENCE, TYPE
from typing import Any, Dict
from suppy.simulator.atomics.atomic import Atomic
class DivergenceAtomic(Atomic):
def __init__(self, uid: str, seh, name: str):
Atomic.__init__(self, uid, seh, name, 0, 0)
def get_stats(self) -> Dict[str, Any]:
stats = Atomic.get_stats(self)
stats[TYPE] = DIVERGENCE
return stats
def _all_output_clear(self) -> bool:
for output_stream in self._output_streams:
if not output_stream.has_input:
return True
return False
def _do_process(self) -> None:
resource = self._loaded_input[0]
for output_stream in self._output_streams:
if not output_stream.has_input:
output_stream.try_load(resource)
return | StarcoderdataPython |
3553800 | <filename>exoplanet-ml/astronet/ops/testing.py
# Copyright 2018 The Exoplanet ML Authors.
#
# 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.
"""TensorFlow utilities for unit tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def fake_features(feature_spec, batch_size):
"""Creates random numpy arrays representing input features for unit testing.
Args:
feature_spec: Dictionary containing the feature specifications.
batch_size: Integer batch size.
Returns:
Dictionary containing "time_series_features" and "aux_features". Each is a
dictionary of named numpy arrays of shape [batch_size, length].
"""
features = {"time_series_features": {}, "aux_features": {}}
for name, spec in feature_spec.items():
ftype = "time_series_features" if spec["is_time_series"] else "aux_features"
features[ftype][name] = np.random.random([batch_size, spec["length"]])
return features
def fake_labels(output_dim, batch_size):
"""Creates a radom numpy array representing labels for unit testing.
Args:
output_dim: Number of output units in the classification model.
batch_size: Integer batch size.
Returns:
Numpy array of shape [batch_size].
"""
# Binary classification is denoted by output_dim == 1. In that case there are
# 2 label classes even though there is only 1 output prediction by the model.
# Otherwise, the classification task is multi-labeled with output_dim classes.
num_labels = 2 if output_dim == 1 else output_dim
return np.random.randint(num_labels, size=batch_size)
| StarcoderdataPython |
6514823 | from django.contrib import admin
from .models import Qusetion, Choice
# Register your models here.
class QusetionAdmin(admin.ModelAdmin):
list_display = ('number', 'content')
class ChoiceAdmin(admin.ModelAdmin):
list_display = ('question', 'content', 'score')
admin.site.register(Qusetion, QusetionAdmin)
admin.site.register(Choice, ChoiceAdmin) | StarcoderdataPython |
1947196 | <filename>tests/test_radionet.py
import unittest
from mopidy_radionet.radionet import RadioNetClient
class RadioNetClientTest(unittest.TestCase):
def test_get_api_key(self):
radionet = RadioNetClient()
radionet.get_api_key()
self.assertIsNotNone(radionet.api_key)
def test_get_top_stations(self):
radionet = RadioNetClient()
radionet.get_top_stations()
self.assertGreater(len(radionet.top_stations), 0)
def test_get_local_stations(self):
radionet = RadioNetClient()
radionet.get_local_stations()
self.assertGreater(len(radionet.local_stations), 0)
def test_do_search(self):
radionet = RadioNetClient()
radionet.do_search("radio ram")
self.assertGreater(len(radionet.search_results), 0)
def test_get_favorites(self):
test_favorites = ("Rock Antenne", "radio ram")
radionet = RadioNetClient()
radionet.set_favorites(test_favorites)
radionet.get_favorites()
self.assertEqual(len(radionet.favorite_stations), len(test_favorites))
if __name__ == "__main__":
unittest.main()
| StarcoderdataPython |
1846312 | from sandbox_42 import app
app.run(host='127.0.0.1', debug=True)
| StarcoderdataPython |
3433325 | class OutOfCoreArray(object):
def __init__(self, array_opener):
self.array_opener = array_opener
def __getitem__(self, item):
with self.array_opener.open_array(mode="r") as a:
return a[item]
def __setitem__(self, item, value):
with self.array_opener.open_array(mode="a") as a:
a[item] = value
return
@property
def shape(self):
with self.array_opener.open_array(mode="r") as a:
return a.shape
@property
def dtype(self):
with self.array_opener.open_array(mode="r") as a:
return a.dtype
| StarcoderdataPython |
184637 | # Generated from STIXPattern.g4 by ANTLR 4.9.2
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\28")
buf.write("\u01f8\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")
buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")
buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")
buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")
buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")
buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64")
buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:")
buf.write("\3\2\3\2\3\2\3\2\7\2z\n\2\f\2\16\2}\13\2\5\2\177\n\2\3")
buf.write("\3\5\3\u0082\n\3\3\3\3\3\3\3\7\3\u0087\n\3\f\3\16\3\u008a")
buf.write("\13\3\5\3\u008c\n\3\3\4\3\4\7\4\u0090\n\4\f\4\16\4\u0093")
buf.write("\13\4\3\4\3\4\6\4\u0097\n\4\r\4\16\4\u0098\3\5\5\5\u009c")
buf.write("\n\5\3\5\7\5\u009f\n\5\f\5\16\5\u00a2\13\5\3\5\3\5\6\5")
buf.write("\u00a6\n\5\r\5\16\5\u00a7\3\6\3\6\3\6\7\6\u00ad\n\6\f")
buf.write("\6\16\6\u00b0\13\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\7\3\7")
buf.write("\7\7\u00bb\n\7\f\7\16\7\u00be\13\7\3\7\3\7\3\7\3\7\3\7")
buf.write("\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\5\7\u00d1")
buf.write("\n\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b\7\b\u00db\n\b\f\b")
buf.write("\16\b\u00de\13\b\3\b\3\b\3\t\3\t\5\t\u00e4\n\t\3\n\3\n")
buf.write("\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\5\n\u00f1\n\n\3\n")
buf.write("\3\n\3\n\3\n\3\n\3\n\3\n\5\n\u00fa\n\n\3\n\3\n\3\n\3\n")
buf.write("\3\n\5\n\u0101\n\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\5\n")
buf.write("\u010b\n\n\3\n\3\n\6\n\u010f\n\n\r\n\16\n\u0110\5\n\u0113")
buf.write("\n\n\3\n\3\n\3\n\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\r\3")
buf.write("\r\3\r\3\r\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16")
buf.write("\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20")
buf.write("\3\20\3\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\21\3\21")
buf.write("\3\21\3\21\3\21\3\21\3\22\3\22\3\22\3\22\3\22\3\22\3\22")
buf.write("\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\24\3\24")
buf.write("\3\24\3\24\3\24\3\25\3\25\3\25\3\26\3\26\3\26\3\26\3\26")
buf.write("\3\26\3\27\3\27\3\27\3\27\3\27\3\30\3\30\3\30\3\30\3\30")
buf.write("\3\30\3\30\3\30\3\31\3\31\3\31\3\31\3\31\3\32\3\32\3\32")
buf.write("\3\32\3\32\3\32\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\34")
buf.write("\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\35\3\35\3\35\3\35")
buf.write("\3\35\3\35\3\36\3\36\7\36\u0193\n\36\f\36\16\36\u0196")
buf.write("\13\36\3\37\3\37\7\37\u019a\n\37\f\37\16\37\u019d\13\37")
buf.write("\3 \3 \3 \5 \u01a2\n \3!\3!\3!\3!\5!\u01a8\n!\3\"\3\"")
buf.write("\3#\3#\3#\3$\3$\3%\3%\3%\3&\3&\3\'\3\'\3(\3(\3)\3)\3*")
buf.write("\3*\3+\3+\3,\3,\3-\3-\3.\3.\3/\3/\3\60\3\60\3\61\3\61")
buf.write("\3\62\3\62\3\63\3\63\3\64\3\64\3\65\3\65\3\65\3\66\3\66")
buf.write("\3\67\6\67\u01d8\n\67\r\67\16\67\u01d9\3\67\3\67\38\3")
buf.write("8\38\38\78\u01e2\n8\f8\168\u01e5\138\38\38\38\38\38\3")
buf.write("9\39\39\39\79\u01f0\n9\f9\169\u01f3\139\39\39\3:\3:\3")
buf.write("\u01e3\2;\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25")
buf.write("\f\27\r\31\16\33\17\35\20\37\21!\22#\23%\24\'\25)\26+")
buf.write("\27-\30/\31\61\32\63\33\65\34\67\359\36;\37= ?!A\"C#E")
buf.write("$G%I&K\'M(O)Q*S+U,W-Y.[/]\60_\61a\62c\63e\64g\2i\2k\2")
buf.write("m\65o\66q\67s8\3\2\21\3\2\63;\3\2\62;\4\2))^^\3\2\62\64")
buf.write("\3\2\63\64\3\2\62\63\3\2\62\65\3\2\62\67\5\2C\\aac|\6")
buf.write("\2\62;C\\aac|\7\2//\62;C\\aac|\5\2\62;CHch\6\2--\61;C")
buf.write("\\c|\f\2\13\17\"\"\u0087\u0087\u00a2\u00a2\u1682\u1682")
buf.write("\u2002\u200c\u202a\u202b\u2031\u2031\u2061\u2061\u3002")
buf.write("\u3002\4\2\f\f\17\17\2\u0214\2\3\3\2\2\2\2\5\3\2\2\2\2")
buf.write("\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3")
buf.write("\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2")
buf.write("\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2")
buf.write("\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2")
buf.write("\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63")
buf.write("\3\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2")
buf.write("\2\2=\3\2\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2")
buf.write("\2\2\2G\3\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3")
buf.write("\2\2\2\2Q\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y")
buf.write("\3\2\2\2\2[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2")
buf.write("c\3\2\2\2\2e\3\2\2\2\2m\3\2\2\2\2o\3\2\2\2\2q\3\2\2\2")
buf.write("\2s\3\2\2\2\3u\3\2\2\2\5\u0081\3\2\2\2\7\u008d\3\2\2\2")
buf.write("\t\u009b\3\2\2\2\13\u00a9\3\2\2\2\r\u00b3\3\2\2\2\17\u00d4")
buf.write("\3\2\2\2\21\u00e3\3\2\2\2\23\u00e5\3\2\2\2\25\u0117\3")
buf.write("\2\2\2\27\u011b\3\2\2\2\31\u011e\3\2\2\2\33\u0122\3\2")
buf.write("\2\2\35\u012d\3\2\2\2\37\u0132\3\2\2\2!\u013a\3\2\2\2")
buf.write("#\u0145\3\2\2\2%\u014e\3\2\2\2\'\u0155\3\2\2\2)\u015a")
buf.write("\3\2\2\2+\u015d\3\2\2\2-\u0163\3\2\2\2/\u0168\3\2\2\2")
buf.write("\61\u0170\3\2\2\2\63\u0175\3\2\2\2\65\u017b\3\2\2\2\67")
buf.write("\u0182\3\2\2\29\u018a\3\2\2\2;\u0190\3\2\2\2=\u0197\3")
buf.write("\2\2\2?\u01a1\3\2\2\2A\u01a7\3\2\2\2C\u01a9\3\2\2\2E\u01ab")
buf.write("\3\2\2\2G\u01ae\3\2\2\2I\u01b0\3\2\2\2K\u01b3\3\2\2\2")
buf.write("M\u01b5\3\2\2\2O\u01b7\3\2\2\2Q\u01b9\3\2\2\2S\u01bb\3")
buf.write("\2\2\2U\u01bd\3\2\2\2W\u01bf\3\2\2\2Y\u01c1\3\2\2\2[\u01c3")
buf.write("\3\2\2\2]\u01c5\3\2\2\2_\u01c7\3\2\2\2a\u01c9\3\2\2\2")
buf.write("c\u01cb\3\2\2\2e\u01cd\3\2\2\2g\u01cf\3\2\2\2i\u01d1\3")
buf.write("\2\2\2k\u01d4\3\2\2\2m\u01d7\3\2\2\2o\u01dd\3\2\2\2q\u01eb")
buf.write("\3\2\2\2s\u01f6\3\2\2\2u~\7/\2\2v\177\7\62\2\2w{\t\2\2")
buf.write("\2xz\t\3\2\2yx\3\2\2\2z}\3\2\2\2{y\3\2\2\2{|\3\2\2\2|")
buf.write("\177\3\2\2\2}{\3\2\2\2~v\3\2\2\2~w\3\2\2\2\177\4\3\2\2")
buf.write("\2\u0080\u0082\7-\2\2\u0081\u0080\3\2\2\2\u0081\u0082")
buf.write("\3\2\2\2\u0082\u008b\3\2\2\2\u0083\u008c\7\62\2\2\u0084")
buf.write("\u0088\t\2\2\2\u0085\u0087\t\3\2\2\u0086\u0085\3\2\2\2")
buf.write("\u0087\u008a\3\2\2\2\u0088\u0086\3\2\2\2\u0088\u0089\3")
buf.write("\2\2\2\u0089\u008c\3\2\2\2\u008a\u0088\3\2\2\2\u008b\u0083")
buf.write("\3\2\2\2\u008b\u0084\3\2\2\2\u008c\6\3\2\2\2\u008d\u0091")
buf.write("\7/\2\2\u008e\u0090\t\3\2\2\u008f\u008e\3\2\2\2\u0090")
buf.write("\u0093\3\2\2\2\u0091\u008f\3\2\2\2\u0091\u0092\3\2\2\2")
buf.write("\u0092\u0094\3\2\2\2\u0093\u0091\3\2\2\2\u0094\u0096\7")
buf.write("\60\2\2\u0095\u0097\t\3\2\2\u0096\u0095\3\2\2\2\u0097")
buf.write("\u0098\3\2\2\2\u0098\u0096\3\2\2\2\u0098\u0099\3\2\2\2")
buf.write("\u0099\b\3\2\2\2\u009a\u009c\7-\2\2\u009b\u009a\3\2\2")
buf.write("\2\u009b\u009c\3\2\2\2\u009c\u00a0\3\2\2\2\u009d\u009f")
buf.write("\t\3\2\2\u009e\u009d\3\2\2\2\u009f\u00a2\3\2\2\2\u00a0")
buf.write("\u009e\3\2\2\2\u00a0\u00a1\3\2\2\2\u00a1\u00a3\3\2\2\2")
buf.write("\u00a2\u00a0\3\2\2\2\u00a3\u00a5\7\60\2\2\u00a4\u00a6")
buf.write("\t\3\2\2\u00a5\u00a4\3\2\2\2\u00a6\u00a7\3\2\2\2\u00a7")
buf.write("\u00a5\3\2\2\2\u00a7\u00a8\3\2\2\2\u00a8\n\3\2\2\2\u00a9")
buf.write("\u00aa\7j\2\2\u00aa\u00ae\5K&\2\u00ab\u00ad\5i\65\2\u00ac")
buf.write("\u00ab\3\2\2\2\u00ad\u00b0\3\2\2\2\u00ae\u00ac\3\2\2\2")
buf.write("\u00ae\u00af\3\2\2\2\u00af\u00b1\3\2\2\2\u00b0\u00ae\3")
buf.write("\2\2\2\u00b1\u00b2\5K&\2\u00b2\f\3\2\2\2\u00b3\u00b4\7")
buf.write("d\2\2\u00b4\u00bc\5K&\2\u00b5\u00b6\5k\66\2\u00b6\u00b7")
buf.write("\5k\66\2\u00b7\u00b8\5k\66\2\u00b8\u00b9\5k\66\2\u00b9")
buf.write("\u00bb\3\2\2\2\u00ba\u00b5\3\2\2\2\u00bb\u00be\3\2\2\2")
buf.write("\u00bc\u00ba\3\2\2\2\u00bc\u00bd\3\2\2\2\u00bd\u00d0\3")
buf.write("\2\2\2\u00be\u00bc\3\2\2\2\u00bf\u00c0\5k\66\2\u00c0\u00c1")
buf.write("\5k\66\2\u00c1\u00c2\5k\66\2\u00c2\u00c3\5k\66\2\u00c3")
buf.write("\u00d1\3\2\2\2\u00c4\u00c5\5k\66\2\u00c5\u00c6\5k\66\2")
buf.write("\u00c6\u00c7\5k\66\2\u00c7\u00c8\3\2\2\2\u00c8\u00c9\7")
buf.write("?\2\2\u00c9\u00d1\3\2\2\2\u00ca\u00cb\5k\66\2\u00cb\u00cc")
buf.write("\5k\66\2\u00cc\u00cd\3\2\2\2\u00cd\u00ce\7?\2\2\u00ce")
buf.write("\u00cf\7?\2\2\u00cf\u00d1\3\2\2\2\u00d0\u00bf\3\2\2\2")
buf.write("\u00d0\u00c4\3\2\2\2\u00d0\u00ca\3\2\2\2\u00d1\u00d2\3")
buf.write("\2\2\2\u00d2\u00d3\5K&\2\u00d3\16\3\2\2\2\u00d4\u00dc")
buf.write("\5K&\2\u00d5\u00db\n\4\2\2\u00d6\u00d7\7^\2\2\u00d7\u00db")
buf.write("\7)\2\2\u00d8\u00d9\7^\2\2\u00d9\u00db\7^\2\2\u00da\u00d5")
buf.write("\3\2\2\2\u00da\u00d6\3\2\2\2\u00da\u00d8\3\2\2\2\u00db")
buf.write("\u00de\3\2\2\2\u00dc\u00da\3\2\2\2\u00dc\u00dd\3\2\2\2")
buf.write("\u00dd\u00df\3\2\2\2\u00de\u00dc\3\2\2\2\u00df\u00e0\5")
buf.write("K&\2\u00e0\20\3\2\2\2\u00e1\u00e4\5\61\31\2\u00e2\u00e4")
buf.write("\5\63\32\2\u00e3\u00e1\3\2\2\2\u00e3\u00e2\3\2\2\2\u00e4")
buf.write("\22\3\2\2\2\u00e5\u00e6\7v\2\2\u00e6\u00e7\5K&\2\u00e7")
buf.write("\u00e8\t\3\2\2\u00e8\u00e9\t\3\2\2\u00e9\u00ea\t\3\2\2")
buf.write("\u00ea\u00eb\t\3\2\2\u00eb\u00f0\5]/\2\u00ec\u00ed\7\62")
buf.write("\2\2\u00ed\u00f1\t\2\2\2\u00ee\u00ef\7\63\2\2\u00ef\u00f1")
buf.write("\t\5\2\2\u00f0\u00ec\3\2\2\2\u00f0\u00ee\3\2\2\2\u00f1")
buf.write("\u00f2\3\2\2\2\u00f2\u00f9\5]/\2\u00f3\u00f4\7\62\2\2")
buf.write("\u00f4\u00fa\t\2\2\2\u00f5\u00f6\t\6\2\2\u00f6\u00fa\t")
buf.write("\3\2\2\u00f7\u00f8\7\65\2\2\u00f8\u00fa\t\7\2\2\u00f9")
buf.write("\u00f3\3\2\2\2\u00f9\u00f5\3\2\2\2\u00f9\u00f7\3\2\2\2")
buf.write("\u00fa\u00fb\3\2\2\2\u00fb\u0100\7V\2\2\u00fc\u00fd\t")
buf.write("\7\2\2\u00fd\u0101\t\3\2\2\u00fe\u00ff\7\64\2\2\u00ff")
buf.write("\u0101\t\b\2\2\u0100\u00fc\3\2\2\2\u0100\u00fe\3\2\2\2")
buf.write("\u0101\u0102\3\2\2\2\u0102\u0103\5M\'\2\u0103\u0104\t")
buf.write("\t\2\2\u0104\u0105\t\3\2\2\u0105\u010a\5M\'\2\u0106\u0107")
buf.write("\t\t\2\2\u0107\u010b\t\3\2\2\u0108\u0109\78\2\2\u0109")
buf.write("\u010b\7\62\2\2\u010a\u0106\3\2\2\2\u010a\u0108\3\2\2")
buf.write("\2\u010b\u0112\3\2\2\2\u010c\u010e\5O(\2\u010d\u010f\t")
buf.write("\3\2\2\u010e\u010d\3\2\2\2\u010f\u0110\3\2\2\2\u0110\u010e")
buf.write("\3\2\2\2\u0110\u0111\3\2\2\2\u0111\u0113\3\2\2\2\u0112")
buf.write("\u010c\3\2\2\2\u0112\u0113\3\2\2\2\u0113\u0114\3\2\2\2")
buf.write("\u0114\u0115\7\\\2\2\u0115\u0116\5K&\2\u0116\24\3\2\2")
buf.write("\2\u0117\u0118\7C\2\2\u0118\u0119\7P\2\2\u0119\u011a\7")
buf.write("F\2\2\u011a\26\3\2\2\2\u011b\u011c\7Q\2\2\u011c\u011d")
buf.write("\7T\2\2\u011d\30\3\2\2\2\u011e\u011f\7P\2\2\u011f\u0120")
buf.write("\7Q\2\2\u0120\u0121\7V\2\2\u0121\32\3\2\2\2\u0122\u0123")
buf.write("\7H\2\2\u0123\u0124\7Q\2\2\u0124\u0125\7N\2\2\u0125\u0126")
buf.write("\7N\2\2\u0126\u0127\7Q\2\2\u0127\u0128\7Y\2\2\u0128\u0129")
buf.write("\7G\2\2\u0129\u012a\7F\2\2\u012a\u012b\7D\2\2\u012b\u012c")
buf.write("\7[\2\2\u012c\34\3\2\2\2\u012d\u012e\7N\2\2\u012e\u012f")
buf.write("\7K\2\2\u012f\u0130\7M\2\2\u0130\u0131\7G\2\2\u0131\36")
buf.write("\3\2\2\2\u0132\u0133\7O\2\2\u0133\u0134\7C\2\2\u0134\u0135")
buf.write("\7V\2\2\u0135\u0136\7E\2\2\u0136\u0137\7J\2\2\u0137\u0138")
buf.write("\7G\2\2\u0138\u0139\7U\2\2\u0139 \3\2\2\2\u013a\u013b")
buf.write("\7K\2\2\u013b\u013c\7U\2\2\u013c\u013d\7U\2\2\u013d\u013e")
buf.write("\7W\2\2\u013e\u013f\7R\2\2\u013f\u0140\7G\2\2\u0140\u0141")
buf.write("\7T\2\2\u0141\u0142\7U\2\2\u0142\u0143\7G\2\2\u0143\u0144")
buf.write("\7V\2\2\u0144\"\3\2\2\2\u0145\u0146\7K\2\2\u0146\u0147")
buf.write("\7U\2\2\u0147\u0148\7U\2\2\u0148\u0149\7W\2\2\u0149\u014a")
buf.write("\7D\2\2\u014a\u014b\7U\2\2\u014b\u014c\7G\2\2\u014c\u014d")
buf.write("\7V\2\2\u014d$\3\2\2\2\u014e\u014f\7G\2\2\u014f\u0150")
buf.write("\7Z\2\2\u0150\u0151\7K\2\2\u0151\u0152\7U\2\2\u0152\u0153")
buf.write("\7V\2\2\u0153\u0154\7U\2\2\u0154&\3\2\2\2\u0155\u0156")
buf.write("\7N\2\2\u0156\u0157\7C\2\2\u0157\u0158\7U\2\2\u0158\u0159")
buf.write("\7V\2\2\u0159(\3\2\2\2\u015a\u015b\7K\2\2\u015b\u015c")
buf.write("\7P\2\2\u015c*\3\2\2\2\u015d\u015e\7U\2\2\u015e\u015f")
buf.write("\7V\2\2\u015f\u0160\7C\2\2\u0160\u0161\7T\2\2\u0161\u0162")
buf.write("\7V\2\2\u0162,\3\2\2\2\u0163\u0164\7U\2\2\u0164\u0165")
buf.write("\7V\2\2\u0165\u0166\7Q\2\2\u0166\u0167\7R\2\2\u0167.\3")
buf.write("\2\2\2\u0168\u0169\7U\2\2\u0169\u016a\7G\2\2\u016a\u016b")
buf.write("\7E\2\2\u016b\u016c\7Q\2\2\u016c\u016d\7P\2\2\u016d\u016e")
buf.write("\7F\2\2\u016e\u016f\7U\2\2\u016f\60\3\2\2\2\u0170\u0171")
buf.write("\7v\2\2\u0171\u0172\7t\2\2\u0172\u0173\7w\2\2\u0173\u0174")
buf.write("\7g\2\2\u0174\62\3\2\2\2\u0175\u0176\7h\2\2\u0176\u0177")
buf.write("\7c\2\2\u0177\u0178\7n\2\2\u0178\u0179\7u\2\2\u0179\u017a")
buf.write("\7g\2\2\u017a\64\3\2\2\2\u017b\u017c\7Y\2\2\u017c\u017d")
buf.write("\7K\2\2\u017d\u017e\7V\2\2\u017e\u017f\7J\2\2\u017f\u0180")
buf.write("\7K\2\2\u0180\u0181\7P\2\2\u0181\66\3\2\2\2\u0182\u0183")
buf.write("\7T\2\2\u0183\u0184\7G\2\2\u0184\u0185\7R\2\2\u0185\u0186")
buf.write("\7G\2\2\u0186\u0187\7C\2\2\u0187\u0188\7V\2\2\u0188\u0189")
buf.write("\7U\2\2\u01898\3\2\2\2\u018a\u018b\7V\2\2\u018b\u018c")
buf.write("\7K\2\2\u018c\u018d\7O\2\2\u018d\u018e\7G\2\2\u018e\u018f")
buf.write("\7U\2\2\u018f:\3\2\2\2\u0190\u0194\t\n\2\2\u0191\u0193")
buf.write("\t\13\2\2\u0192\u0191\3\2\2\2\u0193\u0196\3\2\2\2\u0194")
buf.write("\u0192\3\2\2\2\u0194\u0195\3\2\2\2\u0195<\3\2\2\2\u0196")
buf.write("\u0194\3\2\2\2\u0197\u019b\t\n\2\2\u0198\u019a\t\f\2\2")
buf.write("\u0199\u0198\3\2\2\2\u019a\u019d\3\2\2\2\u019b\u0199\3")
buf.write("\2\2\2\u019b\u019c\3\2\2\2\u019c>\3\2\2\2\u019d\u019b")
buf.write("\3\2\2\2\u019e\u01a2\7?\2\2\u019f\u01a0\7?\2\2\u01a0\u01a2")
buf.write("\7?\2\2\u01a1\u019e\3\2\2\2\u01a1\u019f\3\2\2\2\u01a2")
buf.write("@\3\2\2\2\u01a3\u01a4\7#\2\2\u01a4\u01a8\7?\2\2\u01a5")
buf.write("\u01a6\7>\2\2\u01a6\u01a8\7@\2\2\u01a7\u01a3\3\2\2\2\u01a7")
buf.write("\u01a5\3\2\2\2\u01a8B\3\2\2\2\u01a9\u01aa\7>\2\2\u01aa")
buf.write("D\3\2\2\2\u01ab\u01ac\7>\2\2\u01ac\u01ad\7?\2\2\u01ad")
buf.write("F\3\2\2\2\u01ae\u01af\7@\2\2\u01afH\3\2\2\2\u01b0\u01b1")
buf.write("\7@\2\2\u01b1\u01b2\7?\2\2\u01b2J\3\2\2\2\u01b3\u01b4")
buf.write("\7)\2\2\u01b4L\3\2\2\2\u01b5\u01b6\7<\2\2\u01b6N\3\2\2")
buf.write("\2\u01b7\u01b8\7\60\2\2\u01b8P\3\2\2\2\u01b9\u01ba\7.")
buf.write("\2\2\u01baR\3\2\2\2\u01bb\u01bc\7+\2\2\u01bcT\3\2\2\2")
buf.write("\u01bd\u01be\7*\2\2\u01beV\3\2\2\2\u01bf\u01c0\7_\2\2")
buf.write("\u01c0X\3\2\2\2\u01c1\u01c2\7]\2\2\u01c2Z\3\2\2\2\u01c3")
buf.write("\u01c4\7-\2\2\u01c4\\\3\2\2\2\u01c5\u01c6\5_\60\2\u01c6")
buf.write("^\3\2\2\2\u01c7\u01c8\7/\2\2\u01c8`\3\2\2\2\u01c9\u01ca")
buf.write("\7`\2\2\u01cab\3\2\2\2\u01cb\u01cc\7\61\2\2\u01ccd\3\2")
buf.write("\2\2\u01cd\u01ce\7,\2\2\u01cef\3\2\2\2\u01cf\u01d0\t\r")
buf.write("\2\2\u01d0h\3\2\2\2\u01d1\u01d2\5g\64\2\u01d2\u01d3\5")
buf.write("g\64\2\u01d3j\3\2\2\2\u01d4\u01d5\t\16\2\2\u01d5l\3\2")
buf.write("\2\2\u01d6\u01d8\t\17\2\2\u01d7\u01d6\3\2\2\2\u01d8\u01d9")
buf.write("\3\2\2\2\u01d9\u01d7\3\2\2\2\u01d9\u01da\3\2\2\2\u01da")
buf.write("\u01db\3\2\2\2\u01db\u01dc\b\67\2\2\u01dcn\3\2\2\2\u01dd")
buf.write("\u01de\7\61\2\2\u01de\u01df\7,\2\2\u01df\u01e3\3\2\2\2")
buf.write("\u01e0\u01e2\13\2\2\2\u01e1\u01e0\3\2\2\2\u01e2\u01e5")
buf.write("\3\2\2\2\u01e3\u01e4\3\2\2\2\u01e3\u01e1\3\2\2\2\u01e4")
buf.write("\u01e6\3\2\2\2\u01e5\u01e3\3\2\2\2\u01e6\u01e7\7,\2\2")
buf.write("\u01e7\u01e8\7\61\2\2\u01e8\u01e9\3\2\2\2\u01e9\u01ea")
buf.write("\b8\2\2\u01eap\3\2\2\2\u01eb\u01ec\7\61\2\2\u01ec\u01ed")
buf.write("\7\61\2\2\u01ed\u01f1\3\2\2\2\u01ee\u01f0\n\20\2\2\u01ef")
buf.write("\u01ee\3\2\2\2\u01f0\u01f3\3\2\2\2\u01f1\u01ef\3\2\2\2")
buf.write("\u01f1\u01f2\3\2\2\2\u01f2\u01f4\3\2\2\2\u01f3\u01f1\3")
buf.write("\2\2\2\u01f4\u01f5\b9\2\2\u01f5r\3\2\2\2\u01f6\u01f7\13")
buf.write("\2\2\2\u01f7t\3\2\2\2 \2{~\u0081\u0088\u008b\u0091\u0098")
buf.write("\u009b\u00a0\u00a7\u00ae\u00bc\u00d0\u00da\u00dc\u00e3")
buf.write("\u00f0\u00f9\u0100\u010a\u0110\u0112\u0194\u019b\u01a1")
buf.write("\u01a7\u01d9\u01e3\u01f1\3\b\2\2")
return buf.getvalue()
class STIXPatternLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
IntNegLiteral = 1
IntPosLiteral = 2
FloatNegLiteral = 3
FloatPosLiteral = 4
HexLiteral = 5
BinaryLiteral = 6
StringLiteral = 7
BoolLiteral = 8
TimestampLiteral = 9
AND = 10
OR = 11
NOT = 12
FOLLOWEDBY = 13
LIKE = 14
MATCHES = 15
ISSUPERSET = 16
ISSUBSET = 17
EXISTS = 18
LAST = 19
IN = 20
START = 21
STOP = 22
SECONDS = 23
TRUE = 24
FALSE = 25
WITHIN = 26
REPEATS = 27
TIMES = 28
IdentifierWithoutHyphen = 29
IdentifierWithHyphen = 30
EQ = 31
NEQ = 32
LT = 33
LE = 34
GT = 35
GE = 36
QUOTE = 37
COLON = 38
DOT = 39
COMMA = 40
RPAREN = 41
LPAREN = 42
RBRACK = 43
LBRACK = 44
PLUS = 45
HYPHEN = 46
MINUS = 47
POWER_OP = 48
DIVIDE = 49
ASTERISK = 50
WS = 51
COMMENT = 52
LINE_COMMENT = 53
InvalidCharacter = 54
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'AND'", "'OR'", "'NOT'", "'FOLLOWEDBY'", "'LIKE'", "'MATCHES'",
"'ISSUPERSET'", "'ISSUBSET'", "'EXISTS'", "'LAST'", "'IN'",
"'START'", "'STOP'", "'SECONDS'", "'true'", "'false'", "'WITHIN'",
"'REPEATS'", "'TIMES'", "'<'", "'<='", "'>'", "'>='", "'''",
"':'", "'.'", "','", "')'", "'('", "']'", "'['", "'+'", "'-'",
"'^'", "'/'", "'*'" ]
symbolicNames = [ "<INVALID>",
"IntNegLiteral", "IntPosLiteral", "FloatNegLiteral", "FloatPosLiteral",
"HexLiteral", "BinaryLiteral", "StringLiteral", "BoolLiteral",
"TimestampLiteral", "AND", "OR", "NOT", "FOLLOWEDBY", "LIKE",
"MATCHES", "ISSUPERSET", "ISSUBSET", "EXISTS", "LAST", "IN",
"START", "STOP", "SECONDS", "TRUE", "FALSE", "WITHIN", "REPEATS",
"TIMES", "IdentifierWithoutHyphen", "IdentifierWithHyphen",
"EQ", "NEQ", "LT", "LE", "GT", "GE", "QUOTE", "COLON", "DOT",
"COMMA", "RPAREN", "LPAREN", "RBRACK", "LBRACK", "PLUS", "HYPHEN",
"MINUS", "POWER_OP", "DIVIDE", "ASTERISK", "WS", "COMMENT",
"LINE_COMMENT", "InvalidCharacter" ]
ruleNames = [ "IntNegLiteral", "IntPosLiteral", "FloatNegLiteral", "FloatPosLiteral",
"HexLiteral", "BinaryLiteral", "StringLiteral", "BoolLiteral",
"TimestampLiteral", "AND", "OR", "NOT", "FOLLOWEDBY",
"LIKE", "MATCHES", "ISSUPERSET", "ISSUBSET", "EXISTS",
"LAST", "IN", "START", "STOP", "SECONDS", "TRUE", "FALSE",
"WITHIN", "REPEATS", "TIMES", "IdentifierWithoutHyphen",
"IdentifierWithHyphen", "EQ", "NEQ", "LT", "LE", "GT",
"GE", "QUOTE", "COLON", "DOT", "COMMA", "RPAREN", "LPAREN",
"RBRACK", "LBRACK", "PLUS", "HYPHEN", "MINUS", "POWER_OP",
"DIVIDE", "ASTERISK", "HexDigit", "TwoHexDigits", "Base64Char",
"WS", "COMMENT", "LINE_COMMENT", "InvalidCharacter" ]
grammarFileName = "STIXPattern.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.9.2")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
| StarcoderdataPython |
8159967 | import theading
class stats():
"""
"""
def __init__(self, github):
self.github = github
self.process()
self.kick_off = 1
self.last_limit = 5000
def process(self):
self.calculate_kickoff()
threading.Timer(self.kick_off, self.process).start()
def calculate_kickoff(self):
pass | StarcoderdataPython |
376259 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-09 13:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('omniforms', '0002_omniformsaveinstancehandler'),
]
operations = [
migrations.AlterModelOptions(
name='omniformemailhandler',
options={'verbose_name': 'Send Email'},
),
migrations.AlterModelOptions(
name='omniformsaveinstancehandler',
options={'verbose_name': 'Save Data'},
),
migrations.AlterField(
model_name='omnimodelform',
name='content_type',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='contenttypes.ContentType'),
),
]
| StarcoderdataPython |
1901811 | <filename>tasker/encoder/compressor/dummy.py<gh_stars>0
from . import _compressor
class Compressor(
_compressor.Compressor,
):
name = 'dummy'
@staticmethod
def compress(
data,
):
compressed_object = data
return compressed_object
@staticmethod
def decompress(
data,
):
decompressed_object = data
return decompressed_object
| StarcoderdataPython |
6557512 | from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from .models import UserFav
from apps.users.serializers import UserSerializer
class UserFavSerializer(serializers.ModelSerializer):
"""用户收藏的序列化函数"""
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
class Meta:
model = UserFav
validators = [
UniqueTogetherValidator(
queryset=UserFav.objects.all(),
fields=('user', 'article'),
message="已经收藏"
)
]
fields = ('user', 'article', 'id')
| StarcoderdataPython |
3502798 | <reponame>mndarren/Speedup-Work-Lib<gh_stars>0
#!/usr/bin/env python
"""
.. current_module:: simple_log.py
.. created_by:: <NAME>
.. created_on:: 04/25/2021
This python script is a simple log.
"""
import sys
from datetime import datetime
from inspect import getframeinfo, stack
TIME_FORMAT = '%m/%d/%Y %H:%M:%S'
class SimpleLog:
"""
Basic log class
"""
start_time = ''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def start_log(self):
"""print out start time"""
self.start_time = datetime.now()
self.print_log(f"Starting program: {getframeinfo(stack()[1][0]).filename}")
self.break_section()
def print_log(self, msg=''):
"""
Print out the log message
:param msg: Log message
"""
caller = getframeinfo(stack()[1][0])
sys.stdout.write(f"[{self._curr_time()}][{caller.function} - {caller.lineno}]: {msg}\n")
def stop_log(self):
"""print out duration time"""
duration = datetime.now() - self.start_time
self.break_section()
self.print_log(f"Done to spend time: {str(duration)}")
def _curr_time(self):
"""
return: current time
"""
return datetime.now().strftime(TIME_FORMAT)
def break_section(self):
"""
:return: break section lines
"""
sys.stdout.write(f"{'-' * 120}\n")
| StarcoderdataPython |
6612909 | """Flight category by hour"""
import datetime
import numpy as np
import pytz
from pandas.io.sql import read_sql
import matplotlib.colors as mpcolors
from matplotlib.patches import Rectangle
from pyiem.plot.use_agg import plt
from pyiem.util import get_autoplot_context, get_dbconn, utc
from pyiem.exceptions import NoDataFound
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['cache'] = 86400
desc['description'] = """This chart summarizes Flight Category by hour
and day of a given month. In the case of multiple observations for a
given hour, the worst category is plotted.
<table class="table table-condensed table-bordered">
<thead><tr><th>code</th><th>Label</th><th>Description</th></tr></thead>
<tbody>
<tr><td>Unknown</td><td>Unknown</td><td>No report or missing visibility for
that hour</td></tr>
<tr><td>VFR</td><td>Visual Flight Rules</td><td>
Ceiling >3000' AGL and visibility >5 statutes miles (green)</td></tr>
<tr><td>MVFR</td><td>Marginal Visual Flight Rules</td><td>
1000-3000' ceilings and/or 3-5 statute miles, inclusive (blue)</td></tr>
<tr><td>IFR</td><td>Instrument Fight Rules</td><td>
500 - <1000' ceilings and/or 1 to <3 statute miles (red)</td></tr>
<tr><td>LIFR</td><td>Low Instrument Flight Rules</td><td>
< 500' AGL ceilings and/or < 1 mile (magenta)</td></tr>
</tbody>
</table>
</tbody>
</table>
"""
today = datetime.date.today()
desc['arguments'] = [
dict(type='zstation', name='zstation', default='DSM',
label='Select Station:', network='IA_ASOS'),
dict(type='month', name='month', label='Select Month:',
default=today.month),
dict(type='year', name='year', label='Select Year:',
default=today.year, min=1970),
]
return desc
def plotter(fdict):
""" Go """
pgconn = get_dbconn('asos')
ctx = get_autoplot_context(fdict, get_description())
station = ctx['zstation']
year = ctx['year']
month = ctx['month']
tzname = ctx['_nt'].sts[station]['tzname']
tzinfo = pytz.timezone(tzname)
# Figure out the 1rst and last of this month in the local time zone
sts = utc(year, month, 3)
sts = sts.astimezone(tzinfo).replace(day=1, hour=0, minute=0)
ets = (sts + datetime.timedelta(days=35)).replace(day=1)
days = (ets-sts).days
data = np.zeros((24, days))
df = read_sql("""
SELECT valid at time zone %s as ts,
skyc1, skyc2, skyc3, skyc4, skyl1, skyl2, skyl3, skyl4,
vsby
from alldata where station = %s and valid BETWEEN %s and %s
and vsby is not null and report_type = 2
ORDER by valid ASC
""", pgconn, params=(tzname, station, sts, ets), index_col=None)
if df.empty:
raise NoDataFound("No database entries found for station, sorry!")
# 0 Unknown
# 1 VFR: Ceiling >3000' AGL and visibility >5 statutes miles (green)
# 2 MVFR: 1000-3000' and/or 3-5 statute miles, inclusive (blue)
# 3 IFR: 500 - <1000' and/or 1 to <3 statute miles (red)
# 4 LIFR: < 500' AGL and/or < 1 mile (magenta)
lookup = {4: 'LIFR', 3: 'IFR', 2: 'MVFR', 1: 'VFR', 0: 'UNKNOWN'}
conds = []
for _, row in df.iterrows():
x = row['ts'].day - 1
y = row['ts'].hour
val = 1
level = 100000 # arb high number
coverages = [row['skyc1'], row['skyc2'], row['skyc3'], row['skyc4']]
if 'OVC' in coverages:
idx = coverages.index('OVC')
level = [row['skyl1'], row['skyl2'], row['skyl3'], row['skyl4']
][idx]
if level < 500 or row['vsby'] < 1:
val = 4
elif (level < 1000 and level >= 500) or row['vsby'] < 3:
val = 3
elif (level < 3000 and level >= 1000) or row['vsby'] < 5:
val = 2
elif level >= 3000 and row['vsby'] >= 5:
val = 1
else:
val = 0
data[y, x] = max(data[y, x], val)
conds.append(lookup[val])
# print row['ts'], y, x, val, data[y, x], level, row['vsby']
df['flstatus'] = conds
(fig, ax) = plt.subplots(1, 1, figsize=(8, 6))
ax.set_facecolor('skyblue')
ax.set_title(('[%s] %s %s Flight Category\n'
'based on Hourly METAR Cloud Amount/Level'
' and Visibility Reports'
) % (station, ctx['_nt'].sts[station]['name'],
sts.strftime("%b %Y")))
colors = ['#EEEEEE', 'green', 'blue', 'red', 'magenta']
cmap = mpcolors.ListedColormap(colors)
norm = mpcolors.BoundaryNorm(boundaries=range(6), ncolors=5)
ax.imshow(np.flipud(data), aspect='auto', extent=[0.5, days + 0.5, -0.5,
23.5],
cmap=cmap, interpolation='nearest', norm=norm)
ax.set_yticks(range(0, 24, 3))
ax.set_yticklabels(['Mid', '3 AM', '6 AM', '9 AM', 'Noon',
'3 PM', '6 PM', '9 PM'])
ax.set_xticks(range(1, days+1))
ax.set_ylabel("Hour of Local Day (%s)" % (tzname, ))
ax.set_xlabel("Day of %s" % (sts.strftime("%b %Y"),))
rects = []
for color in colors:
rects.append(Rectangle((0, 0), 1, 1, fc=color))
ax.grid(True)
# Shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
box.width, box.height * 0.9])
ax.legend(rects, ['Unknown', 'VFR', 'MVFR', "IFR", "LIFR"],
loc='upper center', fontsize=14,
bbox_to_anchor=(0.5, -0.09), fancybox=True, shadow=True, ncol=5)
return fig, df
if __name__ == '__main__':
plotter(dict(station='DSM', year=2009, month=1, network='IA_ASOS'))
| StarcoderdataPython |
1820353 | <reponame>nukemberg/git2elastic<filename>git2elastic/__init__.py
# MIT license, see LICENSE.txt
import click
import git
import elasticsearch, elasticsearch.helpers
import pkg_resources
import json
import os.path
import itertools
import hashlib
from collections import defaultdict
def default_es_mappings():
resource_package = __name__
resource_path = 'mapping.json'
return pkg_resources.resource_string(resource_package, resource_path)
def infer_repo_name(path):
return os.path.split(os.path.abspath(path))[1]
@click.command()
@click.option('--repo-name', help='Git repo name', default=None)
@click.option('--es-index', help='ElasticSearch index name', required=True)
@click.option('--branch', '-b', help='Branch to index', default='master')
@click.option('--since', '-s', help='When to start reading the git log', default='1970-01-01')
@click.option('--es-url', help='ElasticSearch endpoint', default='http://localhost:9200/')
@click.option('--es-mappings', help='ElasticSearch index mapping', type=click.File(), default=None)
@click.option('--es-basic-auth', help='ElasticSearch basic authentication (username:password)', default=None)
@click.option('--es-ssl-insecure', help='ElasticSearch SSL without certificate validation', is_flag=True)
@click.argument('path', default='.', type=click.Path(exists=True, dir_okay=True, file_okay=False, resolve_path=True))
def git2elastic(repo_name, es_index, branch, since, es_url, es_mappings, es_basic_auth, es_ssl_insecure, path):
es_mappings = json.load(es_mappings) if es_mappings else json.loads(default_es_mappings())
repo_name = repo_name if repo_name else infer_repo_name(path)
es_config = {}
if es_basic_auth:
es_config['http_auth'] = es_basic_auth.split(':')
if es_ssl_insecure:
es_config['verify_certs'] = False
es = elasticsearch.Elasticsearch([es_url], **es_config)
es.indices.create(es_index, es_mappings, ignore=[400])
index(es, repo_name, es_index, git_log(path, branch, since))
def index(es, repo_name, index_name, commits):
elasticsearch.helpers.bulk(
es,
gen_docs(repo_name, commits),
index=index_name,
doc_type='_doc'
)
def gen_docs(repo_name, commits):
for commit in commits:
yield {
'_id': commit.hexsha,
'type': 'commit',
'repo': repo_name,
'sha': commit.hexsha,
'author': {
'name': commit.author.name,
'email': commit.author.email
},
'message': commit.message,
'summary': commit.summary,
'commit_type': commit.type,
'date': commit.authored_datetime.isoformat(),
'commit_stats': commit.stats.total,
'files': list(map(str, commit.stats.files.keys())),
'merge': len(commit.parents) > 1
}
for file, stats in commit.stats.files.items():
s = stats.copy()
s.update({
'_id': commit.hexsha + '-' + hashlib.sha1(file.encode()).hexdigest(),
'type': 'file_stats',
'commit': commit.hexsha,
'path': file,
'file_stats': stats,
'repo': repo_name,
'date': commit.authored_datetime.isoformat(),
'author': {
'name': commit.author.name,
'email': commit.author.email
}
})
yield s
def git_log(repo_path, branch, since):
repo = git.Repo(repo_path)
return repo.iter_commits(branch, since=since)
if __name__ == '__main__':
git2elastic()
| StarcoderdataPython |
1657761 | import pytest
import numpy as np
from fri.model.ordinal_regression import ordinal_scores as score
@pytest.fixture()
def data():
y = np.array([0, 1, 2, 3])
return y
@pytest.fixture()
def imb_data():
y = np.array([0, 1, 2, 2, 2, 2])
return y
def reverse_label(y):
y = np.copy(y)
return np.flip(y[:], axis=0)
def swap_first_last(y):
y = np.copy(y)
y[[0, -1]] = y[[-1, 0]]
return y
@pytest.mark.parametrize("error", ["mze", "mae", "mmae"])
def test_ordinal_score(error, data):
score_perfect = score(data, data, error_type=error)
score_mixed = score(data, swap_first_last(data), error_type=error)
score_worst = score(data, reverse_label(data), error_type=error)
assert score_perfect > score_mixed
assert score_mixed > score_worst
assert score_perfect == 1
def test_score_imbalanced(data, imb_data):
score_mae = score(data, swap_first_last(data), error_type="mae")
score_mmae = score(data, swap_first_last(data), error_type="mmae")
assert score_mae == score_mmae
score_mae = score(imb_data, swap_first_last(imb_data), error_type="mae")
score_mmae = score(imb_data, swap_first_last(imb_data), error_type="mmae")
assert score_mae != score_mmae
| StarcoderdataPython |
150891 | """
Defines types and operations related to MINC files.
"""
from dataclasses import dataclass
from os import PathLike
from typing import Literal, TypeVar, Generic, Optional
from civet.bases import DataFile
from civet.extraction.kernels import ngh_count_kernel
_M = TypeVar('_M', bound='GenericMinc')
_V = TypeVar('_V', bound='GenericMinc')
@dataclass(frozen=True)
class GenericMinc(DataFile[_M], Generic[_M]):
preferred_suffix = '.mnc'
def mincresample(self, like_volume: _V) -> _V:
def command(output):
return (
'mincresample', '-clobber', '-quiet',
'-like', like_volume, self, output
)
return like_volume.create_command(command)
def reshape255(self) -> 'GenericMask':
def command(output):
return (
'mincreshape', '-quiet', '-clobber', '-unsigned', '-byte',
'-image_range', '0', '255', '-valid_range', '0', '255',
self, output
)
return GenericMask(self).create_command(command)
def resamplef64(self, *extra_flags: str) -> 'GenericFloatMinc':
def command(output):
return 'mincresample', '-quiet', '-double', *extra_flags, self, output
return GenericFloatMinc(self).create_command(command)
_MA = TypeVar('_MA', bound='GenericMask')
class GenericMask(GenericMinc[_MA], Generic[_MA]):
def dilate_volume(self, dilation_value: int, neighbors: Literal[6, 26], n_dilations: int) -> _MA:
def command(output):
return (
'dilate_volume', self, output,
str(dilation_value), str(neighbors), str(n_dilations)
)
return self.create_command(command)
def minccalc_u8(self, expression: str, *other_volumes: 'GenericMask') -> _MA:
def command(output):
return (
'minccalc', '-clobber', '-quiet',
'-unsigned', '-byte',
'-expression', expression,
self, *other_volumes, output
)
return self.create_command(command)
def mincdefrag(self, label: int, stencil: Literal[6, 19, 27], max_connect: Optional[int] = None) -> _MA:
def command(output):
cmd = ['mincdefrag', self, output, str(label), str(stencil)]
if max_connect is not None:
cmd.append(str(max_connect))
return cmd
return self.create_command(command)
def reshape_bbox(self) -> _MA:
def command(output):
return 'mincreshape_bbox_helper', self, output
return self.create_command(command)
def mincmorph_convolve_u8(self, kernel: str | PathLike = ngh_count_kernel) -> _MA:
def command(output):
return (
'mincmorph',
'-unsigned', '-byte',
'-convolve',
'-kernel', kernel,
self, output
)
return self.create_command(command)
class Mask(GenericMask['Mask']):
"""
A `Mask` represents a volume (`.mnc`) with discrete intensities (segmentation volume or brain mask).
"""
pass
_F = TypeVar('_F', bound='GenericFloatMinc')
class GenericFloatMinc(GenericMinc[_F], Generic[_F]):
def mincblur(self, fwhm: float) -> _F:
# result is not a binary mask, it has float values in [0, 1],
# maybe define a unique type?
def command(output):
return 'mincblur_correct_name.sh', '-quiet', '-fwhm', str(fwhm), self, output
return self.create_command(command)
class FloatMinc(GenericFloatMinc['FloatMinc']):
pass
| StarcoderdataPython |
3433680 | #-*- coding: utf-8 -*-
from __future__ import print_function, division
"""
Pytorch useful tools.
"""
import torch
import os
import errno
import numpy as np
def save_checkpoint(net, best_perf, directory, file_name):
print('---------- SAVING MODEL ----------')
if not os.path.isdir(directory):
os.makedirs(directory)
checkpoint_file = os.path.join(directory, file_name + '.weights')
torch.save(net.state_dict(), checkpoint_file)
print('Model Saved as:', checkpoint_file)
with open (directory+'results.txt','w') as fp:
fp.write(str(round(100*best_perf, 3))+'\n')
def load_checkpoint(model_file):
if os.path.isfile(model_file):
print("=> loading model '{}'".format(model_file))
checkpoint = torch.load(model_file)
return checkpoint
else:
print("=> no model found at '{}'".format(model_file))
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), model_file)
def get_num_classes(args):
data_path = args.data_path
if args.dataset == 'context':
classes_file = data_path+'/Context/classes.txt'
else:
classes_file = data_path+'/Drink_Bottle/classes.txt'
num_classes = sum(1 for line in open(classes_file))
return num_classes
def get_weight_criterion(dataset):
if dataset == 'context':
weights = [1, 1, 2.2, 1, 1, 1, 1, 1, 4.5, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2.2, 1.5, 1, 1, 1, 1]
elif dataset =='bottles':
weights = [1, 1, 1, 1, 2, 1.5, 1.5, 1, 1.5, 1, 1, 1.5, 1, 1, 1, 1.5, 1, 1, 1, 1]
return weights
def get_embedding_size(embedding):
if embedding == 'w2vec' or embedding == 'fasttext' or embedding == 'glove':
embedding_size = 300
elif embedding =='bert':
embedding_size = 30522
elif embedding == 'phoc':
embedding_size = 604
elif embedding == 'fisher':
embedding_size = 38400
return embedding_size | StarcoderdataPython |
6614550 | #import necessary packages
from mrcnn.config import Config
from mrcnn import model as modellib
from mrcnn import visualize
import numpy as np
import colorsys
import argparse
import imutils
import random
import cv2
import os
#construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-w", "--weights", required=True, help="path to Mask R-CNN model weights pre-trained on COCO")
ap.add_argument("-l", "--labels", required=True, help="path to class labels file")
ap.add_argument("-i", "--image", required=True, help="path to input image to apply Mask R-CNN to")
args = vars(ap.parse_args())
#load the class label names from disk, one label per line
CLASS_NAMES = open(args["labels"]).read().strip().split("\n")
#generate random (but visually distinct) colors for each class label
#thanks to matterport mask r-cnn for the method
hsv = [(i/len(CLASS_NAMES), 1, 1.0) for i in range(len(CLASS_NAMES))]
COLORS = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.seed(42)
random.shuffle(COLORS)
#lets construct our simple config class
class SimpleConfig(Config):
#give the configuration a recognizable name
NAME = "coco_inference"
#set the number of GPUs to use along with the number of images per GPU
GPU_COUNT = 1
IMAGES_PER_GPU = 1
#number of classes
NUM_CLASSES = len(CLASS_NAMES)
#initialize the inference configuration
config = SimpleConfig()
#initialize the mask r-cnn model for inference and then load the weights
print("[INFO] loading Mask R-CNN model....")
model = modellib.MaskRCNN(mode="inference", config=config, model_dir=os.getcwd())
model.load_weights(args["weights"], by_name=True)
#load the input image, convert it from BGR to RGB channel ordering and resize the image
image = cv2.imread(args['image'])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = imutils.resize(image, width=512)
#perform the forward pass of the network to obtain the results
print('[INFO] making predictions with Mask R-CNN...')
r = model.detect([image], verbose=1)[0]
#loop over of the detected object's bounding boxes and masks
for i in range(0, r["rois"].shape[0]):
#extract the class Id and mask for the current detection then grab the color to visualize the mask (in BGR format)
classID = r["class_ids"][i]
mask = r["masks"][:, :, i]
color = COLORS[classID][::-1]
#visualize the pixel-wise mask of the object
image = visualize.apply_mask(image, mask, color, alpha=0.5)
#convert the image back to BGR so we can use OpenCV's drawing functions
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
#loop over the predicted scores and class labels
for i in range(0, len(r["scores"])):
#extract the bounding box information, classId, label, predicted scores, visualization color
(startY, startX, endY, endX) = r["rois"][i]
classID = r["class_ids"][i]
label = CLASS_NAMES[classID]
score = r["scores"][i]
color = [int(c) for c in np.array(COLORS[classID])* 255]
#draw the bounding box, class labels, and scores of the object
cv2.rectangle(image, (startX, startY), (endX, endY), color, 2)
text = "{}:{:.3f}".format(label, score)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.putText(image, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
#show the output image
cv2.imshow("Output", image)
cv2.waitKey()
| StarcoderdataPython |
1997056 | <filename>udemy-data-structures-and-algorithms/14-linked-lists/14.5_linked_list_nth_to_last_node.py
'''
Write a function that takes a head node and an integer value n and then
returns the nth to last node in the linked list.
'''
from nose.tools import assert_equal
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def nth_to_last_node(n, head):
left = head
right = head
# Set right pointer at n nodes away from head
for i in range(n - 1):
# Check for edge case of not having enough nodes!
if not right.next:
raise LookupError("Error: n is larger than the linked list.")
# Otherwise, we can set the block
right = right.next
# Move the block down the linked list
while right.next:
left = left.next
right = right.next
# Now returns left pointer, its at the nth to last element:
return left
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
e = Node(5)
a.next = b
b.next = c
c.next = d
d.next = e
class TestNLast(object):
def test(self, sol):
assert_equal(sol(2, a), d)
print('ALL TEST CASES PASSED')
# Run tests
t = TestNLast()
t.test(nth_to_last_node)
| StarcoderdataPython |
3254312 | <filename>Telstra_Messaging/api/authentication_api.py<gh_stars>10-100
# coding: utf-8
"""
Telstra Messaging API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 2.2.10
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from Telstra_Messaging.api_client import ApiClient
from Telstra_Messaging.exceptions import (
ApiTypeError,
ApiValueError
)
class AuthenticationApi(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def auth_token(self, client_id, client_secret, grant_type, **kwargs): # noqa: E501
"""Generate OAuth2 token # noqa: E501
To generate an OAuth2 Authentication token, pass through your `Client key` and `Client secret` that you received when you registered for the **API Free Trial** Product. The grant_type should be left as `client_credentials` and the scope as `NSMS`. The token will expire in one hour. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.auth_token(client_id, client_secret, grant_type, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str client_id: (required)
:param str client_secret: (required)
:param str grant_type: (required)
:param str scope: NSMS
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: OAuthResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.auth_token_with_http_info(client_id, client_secret, grant_type, **kwargs) # noqa: E501
def auth_token_with_http_info(self, client_id, client_secret, grant_type, **kwargs): # noqa: E501
"""Generate OAuth2 token # noqa: E501
To generate an OAuth2 Authentication token, pass through your `Client key` and `Client secret` that you received when you registered for the **API Free Trial** Product. The grant_type should be left as `client_credentials` and the scope as `NSMS`. The token will expire in one hour. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.auth_token_with_http_info(client_id, client_secret, grant_type, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str client_id: (required)
:param str client_secret: (required)
:param str grant_type: (required)
:param str scope: NSMS
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(OAuthResponse, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ['client_id', 'client_secret', 'grant_type', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method auth_token" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'client_id' is set
if self.api_client.client_side_validation and ('client_id' not in local_var_params or # noqa: E501
local_var_params['client_id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `client_id` when calling `auth_token`") # noqa: E501
# verify the required parameter 'client_secret' is set
if self.api_client.client_side_validation and ('client_secret' not in local_var_params or # noqa: E501
local_var_params['client_secret'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `client_secret` when calling `auth_token`") # noqa: E501
# verify the required parameter 'grant_type' is set
if self.api_client.client_side_validation and ('grant_type' not in local_var_params or # noqa: E501
local_var_params['grant_type'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `grant_type` when calling `auth_token`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
if 'client_id' in local_var_params:
form_params.append(('client_id', local_var_params['client_id'])) # noqa: E501
if 'client_secret' in local_var_params:
form_params.append(('client_secret', local_var_params['client_secret'])) # noqa: E501
if 'grant_type' in local_var_params:
form_params.append(('grant_type', local_var_params['grant_type'])) # noqa: E501
if 'scope' in local_var_params:
form_params.append(('scope', local_var_params['scope'])) # noqa: E501
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/x-www-form-urlencoded']) # noqa: E501
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/oauth/token', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='OAuthResponse', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
| StarcoderdataPython |
1633757 | class Solution:
def XXX(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
i = 0
j = 0
while (i < (n-1)/2 ):
j = 0
while (j < n/2 ):
tmp = matrix[i][j]
matrix[i][j] = matrix[n-j-1][i]
matrix[n-j-1][i] = matrix[n-i-1][n-j-1]
matrix[n-i-1][n-j-1] = matrix[j][n-i-1]
matrix[j][n-i-1] = tmp
j += 1
i += 1
| StarcoderdataPython |
224337 | <filename>manage.py
from flask_script import Manager, Server
from app import create_app, db
from app.models import User, Pitch, Comment
from flask_migrate import Migrate, MigrateCommand
# Creating app instance
app = create_app('production')
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('server', Server)
manager.add_command('db', MigrateCommand)
@manager.command
def test():
'''
Run the unit tests
'''
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@manager.shell
def make_shell_context():
return dict(app=app, db=db, User=User, Pitch=Pitch, Comment=Comment)
if __name__ == "__main__":
manager.run() | StarcoderdataPython |
3458419 | # Generated by Django 2.1.2 on 2019-10-03 18:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0089_merge_20190930_1519'),
('core', '0089_auto_20191003_1836'),
]
operations = [
]
| StarcoderdataPython |
12866441 | <gh_stars>10-100
#!/usr/bin/env python
"""
CLI tool to runs various tasks related to QA.
"""
import os
import time
from pathlib import Path
import sys
import traceback
import json
import yaml
import uuid
import datetime
import click
from .run import RunContext
from .runners import runners, Job, JobGroup
from .runners.lsf import LsfPriority
from .conventions import batch_dir, batch_dir, make_batch_dir, make_batch_conf_dir, make_hash
from .conventions import serialize_config, deserialize_config, get_settings
from .utils import PathType, entrypoint_module, load_tuning_search
from .utils import save_outputs_manifest, total_storage
from .utils import redirect_std_streams
from .utils import getenvs
from .api import url_to_dir, print_url
from .api import get_outputs, notify_qa_database, serialize_paths
from .iterators import iter_inputs, iter_parameters
from .config import config_has_error, ignore_config_errors
from .config import project, project_root, subproject, config
from .config import default_batches_files, get_default_database, default_batch_label, default_platform
from .config import get_default_configuration, default_input_type
from .config import commit_id, outputs_commit, artifacts_commit, root_qatools, artifacts_commit_root, outputs_commit_root
from .config import user, is_ci, on_windows
@click.group()
@click.pass_context
@click.option('--platform', default=default_platform)
@click.option('--configuration', '--config', '-c', 'configurations', multiple=True, help="Will be passed to the run function")
@click.option('--label', '-l', default=default_batch_label, help="Gives tuning experiments a name.")
@click.option('--tuning', default=None, help="Extra parameters for tuning (JSON)")
@click.option('--tuning-filepath', type=PathType(), default=None, help="File with extra parameters for tuning")
@click.option('--dryrun', is_flag=True, help="Only show the commands that would be executed")
@click.option('--share', is_flag=True, help="Show outputs in QA-Board, doesn't just save them locally.")
@click.option('--database', type=PathType(), help="Input database location")
@click.option('--type', 'input_type', default=default_input_type, help="How we define inputs")
@click.option('--offline', is_flag=True, help="Do not notify QA-Board about run statuses.")
def qa(ctx, platform, configurations, label, tuning, tuning_filepath, dryrun, share, database, input_type, offline):
"""Entrypoint to running your algo, launching batchs..."""
# We want all paths to be relative to top-most qaboard.yaml
# it should be located at the root of the git repository
if config_has_error and not ignore_config_errors:
click.secho('Please fix the error(s) above in qaboard.yaml', fg='red', err=True, bold=True)
exit(1)
# Click passes `ctx.obj` to downstream commands, we can use it as a scratchpad
# http://click.pocoo.org/6/complex/
ctx.obj = {}
will_show_help = '-h' in sys.argv or '--help' in sys.argv
noop_command = 'get' in sys.argv or 'init' in sys.argv
if root_qatools and root_qatools != Path().resolve() and not will_show_help and not noop_command:
ctx.obj['previous_cwd'] = os.getcwd()
click.echo(click.style("Working directory changed to: ", fg='blue') + click.style(str(root_qatools), fg='blue', bold=True), err=True)
os.chdir(root_qatools)
# We want open permissions on outputs and artifacts
# it makes collaboration among mutliple users / automated tools so much easier...
os.umask(0)
ctx.obj['project'] = project
ctx.obj['project_root'] = project_root
ctx.obj['subproject'] = subproject
ctx.obj['HOST'] = os.environ.get('HOST', os.environ.get('HOSTNAME'))
ctx.obj['user'] = user
ctx.obj['dryrun'] = dryrun
ctx.obj['share'] = share
ctx.obj['offline'] = offline
ctx.obj['outputs_commit'] = outputs_commit
ctx.obj['artifacts_commit'] = artifacts_commit
# Note: to support multiple databases per project,
# either use / as database, or somehow we need to hash the db in the output path.
ctx.obj['raw_batch_label'] = label
ctx.obj['batch_label'] = label if not share else f"@{user}| {label}"
ctx.obj['platform'] = platform
ctx.obj['input_type'] = input_type
ctx.obj['inputs_settings'] = get_settings(input_type, config)
ctx.obj['database'] = database if database else get_default_database(ctx.obj['inputs_settings'])
# configuration singular is for backward compatibility to a time where there was a single str config
ctx.obj['configuration'] = ':'.join(configurations) if configurations else get_default_configuration(ctx.obj['inputs_settings'])
# we should refactor the str configuration away completly, and do a much simpler parsing, like
# deserialize_config = lambda configurations: return [maybe_json_loads(c) for c in configurations]
ctx.obj['configurations'] = deserialize_config(ctx.obj['configuration'])
ctx.obj['extra_parameters'] = {}
if tuning:
ctx.obj['extra_parameters'] = json.loads(tuning)
elif tuning_filepath:
ctx.obj['tuning_filepath'] = tuning_filepath
with tuning_filepath.open('r') as f:
if tuning_filepath.suffix == '.yaml':
ctx.obj['extra_parameters'] = yaml.load(f, Loader=yaml.SafeLoader)
elif tuning_filepath.suffix == '.cde':
from cde import Config
ctx.obj['extra_parameters'] = Config.loads(f.read()).asdict()
else:
ctx.obj['extra_parameters'] = json.load(f)
# batch runs will override this since batches may have different configurations
ctx.obj['batch_conf_dir'] = make_batch_conf_dir(outputs_commit, ctx.obj['batch_label'], platform, ctx.obj['configurations'], ctx.obj['extra_parameters'], share)
ctx.obj['batch_dir'] = make_batch_dir(outputs_commit, ctx.obj['batch_label'], platform, ctx.obj['configurations'], ctx.obj['extra_parameters'], share)
# For convenience, we allow users to change environment variables using {ENV: {VAR: value}}
# in configurations or tuning parameters
environment_variables = {}
for c in ctx.obj['configurations']:
if not isinstance(c, dict): continue
if 'ENV' in c: environment_variables.update(c['ENV'])
if 'ENV' in ctx.obj['extra_parameters']:
environment_variables.update(ctx.obj['extra_parameters']['ENV'])
os.environ.update(environment_variables)
# we manage stripping ansi color codes ourselfs since we redirect std streams
# to both the original stream and a log file
ctx.color = True
# colors in log files colors will be interpreted in the UIs
ctx.obj['color'] = is_ci or share
@qa.command()
@click.option('-i', '--input', 'input_path', type=PathType(), help='Path of the input/recording/test we should work on, relative to the database directory.')
@click.option('-o', '--output', 'output_path', type=PathType(), default=None, help='Custom output directory path. If not provided, defaults to ctx.obj["batch_conf_dir"] / input_path.with_suffix('')')
@click.argument('variable')
@click.pass_context
def get(ctx, input_path, output_path, variable):
"""Prints the value of the requested variable. Mostly useful for debug."""
try:
output_directory = ctx.obj['batch_conf_dir'] / input_path.with_suffix('') if not output_path else output_path
except:
pass
from .config import outputs_commit, commit_branch, artifacts_branch_root
# backward compatibility
if variable == "branch_ci_dir":
variable = "artifacts_branch_root"
if variable == "commit_ci_dir":
variable = "outputs_commit"
locals().update(globals())
locals().update(ctx.obj)
if variable in locals():
print(locals().get(variable))
else:
click.secho(f"Could not find {variable}", err=True, fg='red')
exit(1)
@qa.command(context_settings=dict(
ignore_unknown_options=True,
allow_interspersed_args=False,
))
@click.pass_context
@click.option('-i', '--input', 'input_path', required=True, type=PathType(), help='Path of the input/recording/test we should work on, relative to the database directory.')
@click.option('-o', '--output', 'output_path', type=PathType(), default=None, help='Custom output directory path. If not provided, defaults to ctx.obj["batch_conf_dir"] / input_path.with_suffix('')')
@click.option('--keep-previous', is_flag=True, help="Don't clean previous outputs before the run.")
@click.option('--no-postprocess', is_flag=True, help="Don't do the postprocessing.")
@click.option('--save-manifests-in-database', is_flag=True, help="Save the input and outputs manifests in the database.")
@click.argument('forwarded_args', nargs=-1, type=click.UNPROCESSED)
def run(ctx, input_path, output_path, keep_previous, no_postprocess, forwarded_args, save_manifests_in_database):
"""
Runs over a given input/recording/test and computes various success metrics and outputs.
"""
run_context = RunContext.from_click_run_context(ctx, config)
# Usually we want to remove any files already present in the output directory.
# It avoids issues with remaining state... This said,
# In some cases users want to debug long, multi-stepped runs, for which they have their own caching
if not keep_previous:
import shutil
shutil.rmtree(run_context.output_dir, ignore_errors=True)
run_context.output_dir.mkdir(parents=True, exist_ok=True)
with (run_context.output_dir / 'run.json').open('w') as f:
json.dump({
# run_context.database is always made absolute, we keep it relative if given so
"database": str(ctx.obj["database"]),
"input_path": str(run_context.rel_input_path),
"input_type": run_context.type,
"configurations": run_context.configurations,
"extra_parameters": run_context.extra_parameters,
"platform": run_context.platform,
}, f, sort_keys=True, indent=2, separators=(',', ': '))
# Without this, we can only log runs from `qa batch`, on linux, via LSF
# this redirect is not 100% perfect, we don't get stdout from C calls
# if not 'LSB_JOBID' in os.environ: # When using LSF, we usally already have incremental logs
with redirect_std_streams(run_context.output_dir / 'log.txt', color=ctx.obj['color']):
# Help reproduce qa runs with something copy-pastable in the logs
if is_ci:
from shlex import quote
click.secho(' '.join(['qa', *map(quote, sys.argv[1:])]), fg='cyan', bold=True)
click.echo(click.style("Outputs: ", fg='cyan') + click.style(str(run_context.output_dir), fg='cyan', bold=True), err=True)
print_url(ctx)
if not ctx.obj['offline']:
notify_qa_database(**ctx.obj, is_pending=True, is_running=True)
start = time.time()
cwd = os.getcwd()
try:
runtime_metrics = entrypoint_module(config).run(run_context)
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
click.secho(f'[ERROR] Your `run` function raised an exception: {e}', fg='red', bold=True)
try:
exc_type, exc_value, exc_traceback = sys.exc_info()
click.secho(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)), fg='red')
except Exception as e: # debug strange stale file errors, ideally remove this...
print(f"ERROR: {e}")
runtime_metrics = {'is_failed': True}
if not runtime_metrics:
click.secho('[WARNING] Your `run` function should return a dict with a least {"is_failed": False}', fg='yellow')
runtime_metrics = {"is_failed": False}
if not isinstance(runtime_metrics, dict):
click.secho(f'[ERROR] Your `run` function did not return a dict, but {runtime_metrics}', fg='red', bold=True)
runtime_metrics = {'is_failed': True}
runtime_metrics['compute_time'] = time.time() - start
# avoid issues if code in run() changes cwd
if os.getcwd() != cwd:
os.chdir(cwd)
metrics = postprocess_(runtime_metrics, run_context, skip=no_postprocess or runtime_metrics['is_failed'], save_manifests_in_database=save_manifests_in_database)
if not metrics:
metrics = runtime_metrics
if metrics['is_failed']:
click.secho('[ERROR] The run has failed.', fg='red', err=True)
click.secho(str(metrics), fg='red', bold=True)
exit(1)
else:
click.secho(str(metrics), fg='green')
def postprocess_(runtime_metrics, run_context, skip=False, save_manifests_in_database=False):
"""Computes computes various success metrics and outputs."""
from .utils import file_info
try:
if not skip:
try:
entrypoint_postprocess = entrypoint_module(config).postprocess
except:
metrics = runtime_metrics
else:
metrics = entrypoint_postprocess(runtime_metrics, run_context)
else:
metrics = runtime_metrics
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
# TODO: in case of import error because postprocess was not defined, just ignore it...?
# TODO: we should provide a default postprocess function, that reads metrics.json and returns {**previous, **runtime_metrics}
exc_type, exc_value, exc_traceback = sys.exc_info()
click.secho(f'[ERROR] Your `postprocess` function raised an exception:', fg='red', bold=True)
click.secho(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)), fg='red')
metrics = {**runtime_metrics, 'is_failed': True}
if 'is_failed' not in metrics:
click.secho("[Warning] The result of the `postprocess` function misses a key `is_failed` (bool)", fg='yellow')
metrics['is_failed'] = False
if (run_context.output_dir / 'metrics.json').exists():
with (run_context.output_dir / 'metrics.json').open('r') as f:
previous_metrics = json.load(f)
metrics = {
**previous_metrics,
**metrics,
}
with (run_context.output_dir / 'metrics.json').open('w') as f:
json.dump(metrics, f, sort_keys=True, indent=2, separators=(',', ': '))
# To help identify if input files change, we compute and save some metadata.
if is_ci or save_manifests_in_database:
manifest_inputs = run_context.obj.get('manifest-inputs', [run_context.input_path])
input_files = {}
for manifest_input in manifest_inputs:
manifest_input = Path(manifest_input)
if manifest_input.is_dir():
for idx, path in enumerate(manifest_input.rglob('*')):
if idx >= 200:
break
if not path.is_file():
continue
input_files[path.as_posix()] = file_info(path, config=config)
elif manifest_input.is_file():
input_files.update({manifest_input.as_posix(): file_info(manifest_input, config=config)})
with (run_context.output_dir / 'manifest.inputs.json').open('w') as f:
json.dump(input_files, f, indent=2)
outputs_manifest = save_outputs_manifest(run_context.output_dir, config=config)
output_data = {
'storage': total_storage(outputs_manifest),
}
if save_manifests_in_database:
if run_context.input_path.is_file():
click.secho('WARNING: saving the manifests in the database is only implemented for inputs that are *folders*.', fg='yellow', err=True)
else:
from .utils import copy
copy(run_context.output_dir / 'manifest.inputs.json', run_context.input_path / 'manifest.inputs.json')
copy(run_context.output_dir / 'manifest.outputs.json', run_context.input_path / 'manifest.outputs.json')
if not run_context.obj.get('offline') and not run_context.obj.get('dryrun'):
notify_qa_database(**run_context.obj, metrics=metrics, data=output_data, is_pending=False, is_running=False)
return metrics
@qa.command(context_settings=dict(
ignore_unknown_options=True,
))
@click.pass_context
@click.option('-i', '--input', 'input_path', required=True, type=PathType(), help='Path of the input/recording/test we should work on, relative to the database directory.')
@click.option('-o', '--output', 'output_path', type=PathType(), default=None, help='Custom output directory path. If not provided, defaults to ctx.obj["batch_conf_dir"] / input_path.with_suffix('')')
@click.argument('forwarded_args', nargs=-1, type=click.UNPROCESSED)
def postprocess(ctx, input_path, output_path, forwarded_args):
"""Run only the post-processing, assuming results already exist."""
run_context = RunContext.from_click_run_context(ctx, config)
with redirect_std_streams(run_context.output_dir / 'log.txt', color=ctx.obj['color']):
click.echo(click.style("Outputs: ", fg='cyan') + click.style(str(run_context.output_dir), fg='cyan', bold=True), err=True)
print_url(ctx)
metrics = postprocess_({}, run_context)
if metrics['is_failed']:
click.secho('[ERROR] The run has failed.', fg='red', err=True, bold=True)
click.secho(str(metrics), fg='red')
else:
click.secho(str(metrics), fg='green')
@qa.command(context_settings=dict(
ignore_unknown_options=True,
))
@click.pass_context
@click.option('-i', '--input', 'input_path', required=True, type=PathType(), help='Path of the input/recording/test we should work on, relative to the database directory.')
@click.option('-o', '--output', 'output_path', type=PathType(), default=None, help='Custom output directory path. If not provided, defaults to ctx.obj["batch_conf_dir"] / input_path.with_suffix('')')
def sync(ctx, input_path, output_path):
"""Updates the database metrics using metrics.json"""
run_context = RunContext.from_click_run_context(ctx, config)
if (run_context.output_dir / 'metrics.json').exists():
with (run_context.output_dir / 'metrics.json').open('r') as f:
metrics = json.load(f)
notify_qa_database(**ctx.obj, metrics=metrics, is_pending=False, is_running=False)
click.secho(str(metrics), fg='green')
@qa.command(context_settings=dict(
ignore_unknown_options=True,
))
@click.pass_context
@click.option('--output-id', 'output_id', help='Custom output directory path. If not provided, defaults to ctx.obj["batch_conf_dir"] / input_path.with_suffix('')')
def wait(ctx, output_id):
from .api import get_output
while True:
output = get_output(output_id)
click.secho("...waiting")
if output["is_pending"]:
time.sleep(5)
continue
break
exit(0 if not output["is_failed"] else 1)
runners_config = config.get('runners', {})
if 'default' in runners_config:
default_runner = runners_config['default']
else:
task_runners = [r for r in runners_config if r not in ['default', 'local']]
default_runner = task_runners[0] if task_runners else 'local'
lsf_config = config['lsf'] if 'lsf' in config else config.get('runners', {}).get('lsf', {})
if 'lsf' in config:
default_runner = 'lsf'
if default_runner == 'lsf' and os.name=='nt':
default_runner = 'local'
local_config = config.get('runners', {}).get('local', {})
@qa.command(context_settings=dict(
ignore_unknown_options=True,
))
@click.option('--batch', '-b', 'batches', multiple=True, help="We run over all inputs+configs+database in those batches")
@click.option('--batches-file', 'batches_files', type=PathType(), default=default_batches_files, multiple=True, help="YAML files listing batches of inputs+configs+database.")
@click.option('--tuning-search', 'tuning_search_dict', help='string containing JSON describing the tuning parameters to explore')
@click.option('--tuning-search-file', type=PathType(), default=None, help='tuning file describing the tuning parameters to explore')
@click.option('--no-wait', is_flag=True, help="If true, returns as soon as the jobs are sent, otherwise waits for completion.")
@click.option('--list', 'list_contexts', is_flag=True, help="Print as JSON details about each run we would do.")
@click.option('--list-output-dirs', is_flag=True, help="Only print the prefixes for the results of each batch we run on.")
@click.option('--list-inputs', is_flag=True, help="Print to stdout a JSON with a list of the inputs we would call qa run on.")
@click.option('--runner', default=default_runner, help="Run runs locally or using a task queue like Celery, LSF...")
@click.option('--local-concurrency', default=os.environ.get('QA_BATCH_CONCURRENCY', local_config.get('concurrency')), type=int, help="joblib's n_jobs: 0=unlimited, 2=2 at a time, -1=#cpu-1")
@click.option('--lsf-threads', default=lsf_config.get('threads', 0), type=int, help="restrict number of lsf threads to use. 0=no restriction")
@click.option('--lsf-memory', default=lsf_config.get('memory', 0), help="restrict memory (MB) to use. 0=no restriction")
@click.option('--lsf-queue', default=lsf_config.get('queue'), help="LSF queue (-q)")
@click.option('--lsf-fast-queue', default=lsf_config.get('fast_queue', lsf_config.get('queue')), help="Fast LSF queue, for interactive jobs")
@click.option('--lsf-resources', default=lsf_config.get('resources', None), help="LSF resources restrictions (-R)")
@click.option('--lsf-priority', default=lsf_config.get('priority', 0), type=int, help="LSF priority (-sp)")
@click.option('--action-on-existing', default=config.get('outputs', {}).get('action_on_existing', "run"), help="When there are already finished successful runs, whether to do run / postprocess (only) / sync (re-use results) / skip")
@click.option('--action-on-pending', default=config.get('outputs', {}).get('action_on_pending', "wait"), help="When there are already pending runs, whether to do wait (then run) / sync (use those runs' results) / skip (don't run) / continue (run as usual, can cause races)")
@click.option('--prefix-outputs-path', type=PathType(), default=None, help='Custom prefix for the outputs; they will be at $prefix/$output_path')
@click.argument('forwarded_args', nargs=-1, type=click.UNPROCESSED)
@click.pass_context
def batch(ctx, batches, batches_files, tuning_search_dict, tuning_search_file, no_wait, list_contexts, list_output_dirs, list_inputs, runner, local_concurrency, lsf_threads, lsf_memory, lsf_queue, lsf_fast_queue, lsf_resources, lsf_priority, action_on_existing, action_on_pending, prefix_outputs_path, forwarded_args):
"""Run on all the inputs/tests/recordings in a given batch using the LSF cluster."""
if not batches_files:
click.secho(f'WARNING: Could not find how to identify input tests.', fg='red', err=True, bold=True)
click.secho(f'Consider adding to qaboard.yaml somelike like:\n```\ninputs:\n batches: batches.yaml\n```', fg='red', err=True)
click.secho(f'Where batches.yaml is formatted like in http://qa-docs/docs/batches-running-on-multiple-inputs', fg='red', err=True)
return
if not batches:
if not len(forwarded_args):
click.secho(f'ERROR: you must provide a batch', fg='red', err=True, bold=True)
click.secho(f'Use either `qa batch BATCH`, or `qa batch --batch BATCH_2 --batch BATCH_2`', fg='red', err=True)
exit(1)
single_batch, *forwarded_args = forwarded_args
batches = [single_batch]
print_url(ctx)
existing_outputs = get_outputs(ctx.obj)
command_id = str(uuid.uuid4()) # unique IDs for triggered runs makes it easier to wait/cancel them
os.environ['QA_BATCH']= 'true' # triggered runs will be less verbose than with just `qa run`
os.environ['QA_BATCHES_FILES'] = json.dumps([str(b) for b in batches_files])
dryrun = ctx.obj['dryrun'] or list_output_dirs or list_inputs or list_contexts
should_notify_qa_database = (is_ci or ctx.obj['share']) and not (dryrun or ctx.obj['offline'])
if should_notify_qa_database:
command_data = {
"command_created_at_datetime": datetime.datetime.utcnow().isoformat(),
"argv": sys.argv,
"runner": runner,
**ctx.obj,
}
job_url = getenvs(('BUILD_URL', 'CI_JOB_URL', 'CIRCLE_BUILD_URL', 'TRAVIS_BUILD_WEB_URL')) # jenkins, gitlabCI, cirlceCI, travisCI
if job_url:
command_data['job_url'] = job_url
if not os.environ.get('QA_BATCH_COMMAND_HIDE_LOGS'):
notify_qa_database(object_type='batch', command={command_id: command_data}, **ctx.obj)
tuning_search, filetype = load_tuning_search(tuning_search_dict, tuning_search_file)
default_runner_options = {
"type": runner,
"command_id": command_id,
}
# Each runner should add what it cares about...
# TODO: Having --runner-X prefixes makes it all a mess, but still the help text is useful
# TODO: It would be nice to generate the CLI help depending on the runner that's choosen, then we could use
if runner == 'lsf':
default_runner_options.update({
"project": lsf_config.get('project', str(project) if project else "qaboard"),
"max_threads": lsf_threads,
"max_memory": lsf_memory,
'resources': lsf_resources,
"queue": lsf_queue,
"fast_queue": lsf_fast_queue,
"user": ctx.obj['user'],
})
if runner == "local":
default_runner_options["concurrency"] = local_concurrency
if runner == 'local' or runner == 'celery':
default_runner_options["cwd"] = ctx.obj['previous_cwd'] if 'previous_cwd' in ctx.obj else os.getcwd()
jobs = JobGroup(job_options=default_runner_options)
inputs_iter = iter_inputs(batches, batches_files, ctx.obj['database'], ctx.obj['configurations'], ctx.obj['platform'], default_runner_options, config, ctx.obj['inputs_settings'])
for run_context in inputs_iter:
input_configuration_str = serialize_config(run_context.configurations)
for tuning_file, tuning_hash, tuning_params in iter_parameters(tuning_search, filetype=filetype, extra_parameters=ctx.obj['extra_parameters']):
if not prefix_outputs_path:
batch_conf_dir = make_batch_conf_dir(
outputs_commit,
ctx.obj["batch_label"],
run_context.platform,
run_context.configurations,
tuning_params,
ctx.obj['share']
)
else:
batch_conf_dir = outputs_commit / prefix_outputs_path
if tuning_file:
batch_conf_dir = batch_conf_dir / Path(tuning_file).stem
from qaboard.conventions import slugify_hash
input_dir = run_context.rel_input_path.with_suffix('')
if len(input_dir.as_posix()) > 90:
input_dir = Path(slugify_hash(input_dir.as_posix(), maxlength=90))
run_context.output_dir = batch_conf_dir / input_dir
if forwarded_args:
run_forwarded_args = [a for a in forwarded_args if not a in ("--keep-previous", "--no-postprocess", "--save-manifests-in-database")]
if run_forwarded_args:
run_context.extra_parameters = {"forwarded_args": run_forwarded_args, **tuning_params}
else:
run_context.extra_parameters = tuning_params
else:
run_context.extra_parameters = tuning_params
if list_output_dirs:
print(run_context.output_dir)
break
if list_inputs:
print(run_context.input_path)
break
matching_existing_outputs = [o for o in existing_outputs.values() if url_to_dir(o['output_dir_url']) == run_context.output_dir]
matching_existing_output = matching_existing_outputs[0] if matching_existing_outputs else None # at most 1, garanteed by database constaints
is_pending = matching_existing_output['is_pending'] if matching_existing_output else False
is_failed = matching_existing_output['is_failed'] if matching_existing_output else run_context.is_failed()
ran_before = True if matching_existing_output else run_context.ran()
should_run = not is_pending and (action_on_existing=='run' or is_failed or not ran_before)
if not should_run and action_on_existing=='skip':
continue
if is_pending and action_on_pending == 'skip':
continue
if not forwarded_args:
forwarded_args_cli = None
else:
if not on_windows:
# FIXME: we assume no single quotes...
forwarded_args_cli = ' '.join(f"'{a}'" for a in forwarded_args)
else:
from .compat import escaped_for_cli
forwarded_args_cli = ' '.join(escaped_for_cli(a) for a in forwarded_args)
if input_configuration_str == get_default_configuration(ctx.obj['inputs_settings']):
configuration_cli = None
else:
# We can't use --config, or "-c A -c B" until we ensure all clients updated a version supporting it
if not on_windows:
configuration = input_configuration_str.replace("'", "'\"'\"'") # support single-quotes
configuration_cli = f"--configuration '{configuration}'"
else:
from .compat import escaped_for_cli
configuration_cli = f'--configuration {escaped_for_cli(input_configuration_str)}'
# We could serialize properly the run_context/runner_options, and e.g. call "qa --pickled-cli" and use the CLI command below just for logs...
args = [
f"qa",
f'--share' if ctx.obj["share"] else None,
f'--offline' if ctx.obj['offline'] else None,
f'--label "{ctx.obj["raw_batch_label"]}"' if ctx.obj["raw_batch_label"] != default_batch_label else None,
f'--platform "{run_context.platform}"' if run_context.platform != default_platform else None, # TODO: make it customizable in batches
f'--type "{run_context.type}"' if run_context.type != default_input_type else None,
f'--database "{run_context.database.as_posix()}"' if run_context.database != get_default_database(ctx.obj['inputs_settings']) else None,
configuration_cli,
f'--tuning-filepath "{tuning_file}"' if tuning_params else None,
'run' if should_run else action_on_existing,
f'--input "{run_context.rel_input_path}"',
f'--output "{run_context.output_dir}"' if prefix_outputs_path else None,
forwarded_args_cli if forwarded_args_cli else None,
]
command = ' '.join([arg for arg in args if arg is not None])
click.secho(command, fg='cyan', err=True)
click.secho(f" {run_context.output_dir if run_context.output_dir.is_absolute else run_context.output_dir.relative_to(subproject)}", fg='blue', err=True)
import re
if 'QA_TESTING' in os.environ:
# we want to make sure we test the current code
command = re.sub('^qa', 'python -m qaboard', command)
if str(subproject) != '.':
command = f"cd {subproject} && {command}"
run_context.command = command
run_context.job_options['command_id'] = command_id
job = Job(run_context)
if should_notify_qa_database and not is_pending:
# TODO: accumulate and send all at once to avoid 100s of requests?
db_output = notify_qa_database(**{
**ctx.obj,
**run_context.obj, # for now we don't want to worry about backward compatibility, and input_path being abs vs relative...
"is_pending": True,
})
if db_output: # Note: the ID is already in the matching job above
job.id = db_output["id"]
if is_pending:
wait_command = f"qa wait --output-id {matching_existing_output['id']}"
if action_on_pending=="sync":
job.id = matching_existing_output['id']
job.run_context.command = wait_command
elif action_on_pending=="wait":
job.run_context.command = f"{wait_command} || {job.run_context.command}"
else:
assert action_on_pending=="continue"
jobs.append(job)
if list_contexts:
print(json.dumps([serialize_paths(j.run_context.asdict()) for j in jobs], indent=2))
return
if not dryrun:
is_failed = jobs.start(
blocking=not no_wait,
qa_context=ctx.obj,
)
from .gitlab import gitlab_token, update_gitlab_status
if gitlab_token and jobs and is_ci and 'QABOARD_TUNING' not in os.environ:
update_gitlab_status(commit_id, 'failed' if is_failed else 'success', ctx.obj["batch_label"], f"{len(jobs)} results")
if is_failed and not no_wait:
del os.environ['QA_BATCH'] # restore verbosity
print_url(ctx, status="failure")
exit(1)
@qa.command()
# Do we want this? we could simply use groups not defined in qatools.yaml:artifacts as paths
@click.option('--file', '-f', 'files', multiple=True, help="Save specific files instead of artifacts indicated by yaml file")
@click.option('--exclude', 'excluded_groups', multiple=True, help="Exclude specific artifact groups")
# Do we use this? yes in the API, but let's deprecate and remove for other uses...
@click.option('--out', '-o', 'artifacts_path', default='', help="Path to save artifacts in case of specified files")
@click.argument('groups', nargs=-1, type=click.UNPROCESSED, default=None)
@click.pass_context
def save_artifacts(ctx, files, excluded_groups, artifacts_path, groups):
"""Save the results at a standard location"""
import filecmp
from .config import is_in_git_repo, qatools_config_paths
from .utils import copy, file_info
from .compat import cased_path
click.secho(f"Saving artifacts in: {artifacts_commit}", bold=True, underline=True)
artifacts = {}
if files:
artifacts = {f"__{f}": {"glob": f} for f in files}
else:
if 'artifacts' not in config:
config['artifacts'] = {}
# We support both qaboard.yaml and qaboard.yaml for backward compatibility with SIRC's projects
# Default artifacts
config['artifacts']['__qaboard.yaml'] = {"glob": ['qaboard.yaml', 'qatools.yaml']}
config['artifacts']['__qatools'] = {"glob": ['qatools/*', 'qa/*']}
# Handle sub-projects
config['artifacts']['__sub-qaboard.yaml'] = {"glob": [str(p.relative_to(root_qatools).parent / 'qaboard.yaml') for p in qatools_config_paths]}
config['artifacts']['__sub-qaboard.yaml'] = {"glob": [str(p.relative_to(root_qatools).parent / 'qatools.yaml') for p in qatools_config_paths]}
config['artifacts']['__metrics.yaml'] = {"glob": config.get('outputs', {}).get('metrics')}
config['artifacts']['__batches.yaml'] = {"glob": default_batches_files}
config['artifacts']['__envrc'] = {"glob": ['.envrc', '**/*.envrc']}
if groups:
if excluded_groups:
groups = [g for g in groups if g not in excluded_groups]
artifacts = {g: config['artifacts'][g] for g in groups if g in config['artifacts'].keys()}
else:
artifacts = config['artifacts']
if 'QA_VERBOSE_VERBOSE' in os.environ: print(artifacts)
if not is_in_git_repo:
click.secho(
"You are not in a git repository, maybe in an artifacts folder. `save_artifacts` is unavailable.",
fg='yellow', dim=True)
exit(1)
for artifact_name, artifact_config in artifacts.items():
click.secho(f'Saving artifacts: {artifact_name}', bold=True)
manifest_path = artifacts_commit / 'manifests' / f'{artifact_name}.json'
manifest_path.parent.mkdir(parents=True, exist_ok=True)
if manifest_path.exists():
with manifest_path.open() as f:
try:
manifest = json.load(f)
except:
manifest = {}
else:
manifest = {}
nb_files = 0
globs = artifact_config.get('glob')
if not isinstance(globs, list):
globs = [globs]
for g in globs:
if not g: continue
for path in Path('.').glob(g):
path = cased_path(path)
if not path.is_file():
continue
if artifacts_path:
destination = artifacts_commit_root / artifacts_path / path
else:
destination = artifacts_commit_root / path
if 'QA_VERBOSE_VERBOSE' in os.environ: print(destination)
if destination.exists() and filecmp.cmp(str(path), str(destination), shallow=True):
# when working on subprojects, the artifact might be copied already,
# but manifests are saved per-subproject
if path.as_posix() not in manifest:
manifest[path.as_posix()] = file_info(path, config=config)
continue
if 'QA_VERBOSE' in os.environ or ctx.obj['dryrun']:
click.secho(str(path), dim=True)
if not ctx.obj['dryrun']:
copy(path, destination)
manifest[path.as_posix()] = file_info(path, config=config)
if not ctx.obj['dryrun']:
with manifest_path.open('w') as f:
json.dump(manifest, f)
if nb_files > 0:
click.secho(f"{nb_files} files copied")
if os.name == "nt" and not ctx.obj['dryrun']:
# [Samsung-SIRC specific]
print("... Fixing linux file permissions")
try:
# Windows does not set file permissions correctly on the shared storage,
# it does not respect umask 0: files are not world-writable.
# Trying to each_file.chmod(0o777) does not work either
# The only option is to make the call from linux.
# We could save a list of paths and chmod them with their parent directories...
# but to make things faster to code, we just "ssh linux chmod everything"
# from qaboard.compat import windows_to_linux_path
# # We can assume SSH to be present on Windows10
# ssh = f"ssh -i \\\\networkdrive\\home\\{user}\\.ssh\\id_rsa -oStrictHostKeyChecking=no"
# chmod = f'{ssh} {user}@{user}-srv \'chmod -R 777 "{windows_to_linux_path(artifacts_commit)}"\''
# print(chmod)
# os.system(chmod)
pass
except Exception as e:
print(f'WARNING: {e}')
# if the commit was deleted, this notification will mark it as good again
notify_qa_database(object_type='commit', **ctx.obj)
@qa.command()
@click.pass_context
@click.option('--batch', '-b', 'batches', required=True, multiple=True, help="Only check bit-accuracy for this batch of inputs+configs+database.")
@click.option('--batches-file', 'batches_files', type=PathType(), default=default_batches_files, multiple=True, help="YAML file listing batches of inputs+config+database selected from the database.")
def check_bit_accuracy_manifest(ctx, batches, batches_files):
"""
Checks the bit accuracy of the results in the current ouput directory
versus the latest commit on origin/develop.
"""
from .bit_accuracy import is_bit_accurate
commit_dir = outputs_commit if is_ci else Path()
all_bit_accurate = True
nb_compared = 0
for run_context in iter_inputs(batches, batches_files, ctx.obj['database'], ctx.obj['configurations'], default_platform, {}, config, ctx.obj['inputs_settings']):
nb_compared += 1
if run_context.input_path.is_file():
click.secho('ERROR: check_bit_accuracy_manifest only works for inputs that are folders', fg='red', err=True)
# otherwise the manifest is at
# * input_path.parent / 'manifest.json' in the database
# * input_path.with_suffix('') / 'manifest.json' in the results
# # reference_output_directory = run_context.input_path if run_context.input_path.is_folder() else run_context.input_path.parent
exit(1)
batch_conf_dir = make_batch_conf_dir(Path(), ctx.obj['batch_label'], ctx.obj["platform"], run_context.configurations, ctx.obj['extra_parameters'], ctx.obj['share'])
input_is_bit_accurate = is_bit_accurate(commit_dir / batch_conf_dir, run_context.database, [run_context.rel_input_path])
all_bit_accurate = all_bit_accurate and input_is_bit_accurate
if not all_bit_accurate:
click.secho("\nError: you are not bit-accurate versus the manifest.", fg='red', underline=True, bold=True)
click.secho("Reminder: the manifest lists the expected inputs/outputs for each test. It acts as an explicit gatekeeper against changes", fg='red', dim=True)
if not run_context.database.is_absolute():
click.secho("If that's what you wanted, update and commit all manifests.", fg='red')
# click.secho("If that's what you wanted, update all manifests using:", fg='red')
# click.secho("$ qa batch * --save-manifests-in-database", fg='red')
# click.secho("$ git add # your changes", fg='red')
# click.secho("$ git commit # now retry your CI", fg='red')
else:
click.secho("To update the manifests for all tests, run:", fg='red')
click.secho("$ qa batch --save-manifests --batch *", fg='red')
exit(1)
if not nb_compared:
click.secho("\nWARNING: Nothing was compared! It's not likely to be what you expected...", fg='yellow', underline=True, bold=True)
@qa.command()
@click.pass_context
@click.option(
"--reference",
default=config.get('project', {}).get('reference_branch', 'master'),
help="Branch, tag or commit used as reference."
)
@click.option('--batch', '-b', 'batches', multiple=True, help="Only check bit-accuracy for those batches of inputs+configs+database.")
@click.option('--batches-file', 'batches_files', type=PathType(), default=default_batches_files, multiple=True, help="YAML file listing batches of inputs+config+database selected from the database.")
@click.option('--reference-platform', help="Compare against a difference platform.")
def check_bit_accuracy(ctx, reference, batches, batches_files, reference_platform):
"""
Checks the bit accuracy of the results in the current ouput directory
versus the latest commit on origin/develop.
"""
from .config import is_in_git_repo, commit_branch, is_ci, outputs_project_root, repo_root
from .bit_accuracy import is_bit_accurate
from .gitlab import lastest_successful_ci_commit
from .conventions import get_commit_dirs
from .git import latest_commit, git_show, git_parents
if not is_in_git_repo:
click.secho("You are not in a git repository, maybe in an artifacts folder. `check_bit_accuracy` is unavailable.", fg='yellow', dim=True)
exit(1)
if is_ci and commit_branch == reference:
click.secho(f'We are on branch {reference}', fg='cyan', bold=True, err=True)
click.secho(f"Comparing bit-accuracy against this commit's ({commit_id[:8]}) parents.", fg='cyan', bold=True, err=True)
# It will work until we try to rebase merge requests.
# We really should use Gitlab' API (or our database) to ask about previous pipelines on the branch
reference_commits = git_parents(commit_id)
else:
click.secho(f'Comparing bit-accuracy versus the latest remote commit of {reference}', fg='cyan', bold=True, err=True)
reference_commits = [latest_commit(reference)]
click.secho(f"{commit_id[:8]} versus {reference_commits}.", fg='cyan', err=True)
# This where the new results are located
commit_dir = outputs_commit_root if is_ci else Path()
if not batches:
output_directories = list(p.parent.relative_to(commit_dir) for p in (commit_dir / subproject / 'output').rglob('manifest.outputs.json'))
else:
output_directories = []
for run_context in iter_inputs(batches, batches_files, ctx.obj['database'], ctx.obj['configurations'], default_platform, {}, config, ctx.obj['inputs_settings']):
batch_conf_dir = make_batch_conf_dir(subproject, ctx.obj['batch_label'], ctx.obj["platform"], run_context.configurations, ctx.obj["extra_parameters"], ctx.obj['share'])
input_path = run_context.input_path.relative_to(run_context.database)
output_directory = batch_conf_dir / input_path.with_suffix('')
output_directories.append(output_directory)
for reference_commit in reference_commits:
# if the reference commit is pending or failed, we wait or maybe pick a parent
reference_commit = lastest_successful_ci_commit(reference_commit)
click.secho(f'Current directory : {commit_dir}', fg='cyan', bold=True, err=True)
reference_rootproject_ci_dir = outputs_project_root / get_commit_dirs(reference_commit, repo_root)
click.secho(f"Reference directory: {reference_rootproject_ci_dir}", fg='cyan', bold=True, err=True)
all_bit_accurate = True
for o in output_directories:
all_bit_accurate = is_bit_accurate(commit_dir, reference_rootproject_ci_dir, [o], reference_platform) and all_bit_accurate
if not all_bit_accurate:
click.secho(f"\nERROR: results are not bit-accurate to {reference_commits}.", bg='red', bold=True)
if is_ci:
click.secho(f"\nTo investigate, go to", fg='red', underline=True)
for reference_commit in reference_commits:
click.secho(f"https://qa/{project.as_posix()}/commit/{commit_id}?reference={reference_commit}&selected_views=bit_accuracy", fg='red')
exit(1)
from .optimize import optimize
qa.add_command(optimize)
# TODO: split more...
# from .bit_accuracy import check_bit_accuracy, check_bit_accuracy_manifest
# qa.add_command(check_bit_accuracy)
# qa.add_command(check_bit_accuracy_manifest)
@qa.command()
@click.pass_context
def init(ctx):
"""Provide a sample qaboard.yaml configuration."""
from .init import qa_init
qa_init(ctx)
def main():
from .compat import ensure_cli_backward_compatibility
ensure_cli_backward_compatibility()
qa(obj={}, auto_envvar_prefix='QA')
if __name__ == '__main__':
main()
| StarcoderdataPython |
6478517 | #!/usr/bin/env python
# coding=utf-8
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import csv
import os
import re
import xlsxwriter
import datetime
# from lib.data_change_Time import data_change_Time
# from lib.txt_To_xlsx import txt_To_xlsx
import glob
import sys
# def MergeTxt_sim(start, end, workdir, var):
# start = datetime.datetime.strptime(start, '%Y-%m-%d')
# end = datetime.datetime.strptime(end, '%Y-%m-%d')
# # start -= datetime.timedelta(days=1)
# # end += datetime.timedelta(days=1)
# filetimes = []
# while (start <= end):
# filetime = start.strftime('%Y-%m-%d')
# filetimes.append(filetime)
# start += datetime.timedelta(days=1)
# newfile = 'wrfout_d04_'+filetimes[0]+'_'+filetimes[-1]+'_'+var+'.txt'
# outputFile = open(workdir+'\\'+newfile,"a+")
# for i in range(0,len(filetimes)):
# inputFile = open("D:\\bokai\\python\\python-code\\氣象性能評估工具V3\\data\\sim\\"+var+"\\wrfout_d04_"+filetimes[i]+"_"+var+".txt")
# outputFile.write(inputFile.read())
# return newfile
def MergeTxt_sim(start, end, workdir, rootdir, var):
start = datetime.datetime.strptime(start, '%Y-%m-%d')
end = datetime.datetime.strptime(end, '%Y-%m-%d')
# start -= datetime.timedelta(days=1)
# end += datetime.timedelta(days=1)
filetimes = []
while (start <= end):
filetime = start.strftime('%Y-%m-%d')
filetimes.append(filetime)
start += datetime.timedelta(days=1)
newfile = 'wrfout_d04_'+filetimes[0]+'_'+filetimes[-1]+'_'+var+'.txt'
outputFile = open(workdir+'\\'+newfile, "a+")
for i in range(0, len(filetimes)):
# inputFile = open(rootpath+"\\data\\sim\\"+var+"\\wrfout_d04_"+filetimes[i]+"_"+var+".txt")
inputFile = open(rootdir+"Sim\\" +
var+"\\wrfout_d04_"+filetimes[i]+"_"+var+".txt")
outputFile.write(inputFile.read())
return newfile
def raw_MergeTxt_sim():
start = datetime.datetime.strptime('2016-06-01', '%Y-%m-%d')
end = datetime.datetime.strptime('2016-06-30', '%Y-%m-%d')
while (start <= end):
filetime = start.strftime('%Y-%m-%d')
outputFile = open(
'D:\\bokai\\python\\python-code\\氣象性能評估工具V3\\data\\sim\\WD\\wrfout_d04_'+filetime+'_WD.txt', "a+")
for txtFile in (glob.glob('D:\\bokai\\python\\python-code\\氣象性能評估工具V3\\data\\sim\\wrfout_d04_'+filetime+'*.txt')):
inputFile = open(txtFile)
outputFile.write(inputFile.read())
start += datetime.timedelta(days=1)
# outputFile = open('D:\\bokai\\python\\python-code\\氣象性能評估工具\\data\\newsim\\wrfout_d04_2016-06-30_00_00_00.txt',"a+")
# for txtFile in glob.glob('D:\\bokai\\python\\python-code\\氣象性能評估工具\\data\\sim\\wrfout_d04_2016-06-30*.txt'):
# inputFile = open(txtFile)
# outputFile.write(inputFile.read())
| StarcoderdataPython |
4938824 | <gh_stars>0
import shutil
import os
import stat
import pathlib
"""
Additional Help
stat.S_IRWXU -- mask for file owner permissions
stat.S_IRWXG -- mask for file group permissions
stat.S_IROTH -- others have read permissions
stat.S_IXOTH -- others have exicute permissions
"""
def ensure_dir_permissions(path):
path = pathlib.Path(path)
if not path.parent.exists():
ensure_dir_permissions(path=path.parent.absolute())
if not path.is_dir():
print('creating with permissions:')
path.mkdir()
try:
shutil.chown(str(path), group='lab')
os.chmod(str(path), stat.S_IRWXU | stat.S_IRWXG)
except PermissionError:
print(
"WARNING: It was not possible to change the permission to the following files: \n"
+ path + "\n")
print('made outpath: {p}'.format(p=path))
def change_file_permissions(file_path):
if not isinstance(file_path, pathlib.Path):
file_path = pathlib.Path(file_path)
if not file_path.is_file():
print('path does not exist')
return
try:
shutil.chown(str(file_path), group='lab')
os.chmod(str(file_path), stat.S_IRWXU | stat.S_IRWXG)
except:
print(
"WARNING: It was not possible to change the permission to the following files: \n"
+ str(file_path))
def remove_dir(rm_dir):
if not isinstance(rm_dir, pathlib.Path):
rm_dir = pathlib.Path(rm_dir)
if rm_dir.is_dir():
print('removing:', rm_dir)
shutil.rmtree(str(rm_dir))
def copy_file(input_path, output_path):
ensure_dir_permissions(path=output_path.parent)
shutil.copy(str(input_path), str(output_path))
change_file_permissions(output_path)
| StarcoderdataPython |
1784493 | <filename>regalloc/testmain.py
from regalloc import regalloc
from codegen import codegen
import json
import argparse
import sys
REG_PREFIX = "r_"
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='register allocation for bril json format')
parser.add_argument("--stats", action="store_true", help="print var to reg mapping instead of code generation")
parser.add_argument("--num", type=int, default=3, help="number of registers")
args = parser.parse_args()
bril = json.load(sys.stdin)
regs = [REG_PREFIX+'%02d'%(i+1) for i in range(args.num)]
for func in bril['functions']:
regmap,colored,spilled = regalloc(func['instrs'], regs)
print('%s {' % func['name'])
codegen(func['instrs'], regmap)
print('}')
| StarcoderdataPython |
11339006 | <filename>chippy/instructions.py
import random
class Opcode(object):
"""CHIP8 / SCHIP opcode datatype.
Opcodes are 16-bit ints and are generally of the form:
'GXYN', 'GXNN' or 'GNNN'; where
G : 4-bit opcode group id,
X, Y : 4-bit register ids,
NN : 8-bit constant,
NNN: 12-bit address.
Parameters
----------
code : int or str
A two-byte (16-bit) opcode.
"""
_SYNUM = 4 # Total number of symbols in opcode
_SYLENGTH = 4 # Length of opcode symbol in bits
def __init__(self, code):
base = 16
if isinstance(code, str):
code = int(code, base)
assert (code < base**self._SYNUM) and (code >= 0), \
"OPCODE must range between '0000'--'FFFF'."
self.code = code
@classmethod
def from_pair(cls, left_int, right_int):
return cls((left_int << cls._SYLENGTH * 2) | right_int)
def _extract_symbol(self, shift, length):
mask = 2 ** (length * Opcode._SYLENGTH) - 1
shift = Opcode._SYLENGTH * shift
return (self.code >> shift) & mask
def as_str(self):
shifts = range(Opcode._SYNUM)
hex_syms = ['{:1x}'.format(self._extract_symbol(s, 1)) for s in shifts]
return ''.join(hex_syms).upper()[::-1]
def generate_masks(self):
# Mask opcodes for decoding
str_code = '_' + self.as_str()
return set([
str_code,
str_code[:2] + 'M' + str_code[3:],
str_code[:2] + 'MM' + str_code[4],
str_code[:2] + 'MMM',
str_code[:4] + 'M',
])
@property
def G(self):
return self._extract_symbol(shift=3, length=1)
@property
def X(self):
return self._extract_symbol(shift=2, length=1)
@property
def Y(self):
return self._extract_symbol(shift=1, length=1)
@property
def N(self):
return self._extract_symbol(shift=0, length=1)
@property
def NN(self):
return self._extract_symbol(shift=0, length=2)
@property
def NNN(self):
return self._extract_symbol(shift=0, length=3)
class InstructionSet(object):
def __init__(self, opcode):
self.opcode = opcode
def execute(self, machine):
opcode_masks = self.opcode.generate_masks()
ins_id = opcode_masks.intersection(set(dir(self)))
fun = self.__getattribute__(ins_id.pop()) if ins_id else self._NOP
return fun(machine)
# ===== INSTRUCTIONS ==================================================== #
def _00CM(self, machine): # 00CN
machine.gfx.scroll('down', self.opcode.N)
def _00FB(self, machine): # 00FB
machine.gfx.scroll('right', 4)
def _00FC(self, machine): # 00FC
machine.gfx.scroll('left', 4)
def _00FD(self, machine): # 00FD
machine.keyboard.set_exit()
def _00FE(self, machine): # 00FE
machine.gfx.set_resolution('low')
def _00FF(self, machine): # 00FF
machine.gfx.set_resolution('high')
def _00E0(self, machine): # 00E0
machine.gfx.clear()
def _00EE(self, machine): # 00EE
machine.pc = machine.stack.pop()
def _1MMM(self, machine): # 1NNN
machine.pc = self.opcode.NNN
def _2MMM(self, machine): # 2NNN
machine.stack.append(machine.pc)
machine.pc = self.opcode.NNN
def _3MMM(self, machine): # 3XNN
if machine.V[self.opcode.X] == self.opcode.NN:
machine.pc += 2
def _4MMM(self, machine): # 4XNN
if machine.V[self.opcode.X] != self.opcode.NN:
machine.pc += 2
def _5MMM(self, machine): # 5XY0
if machine.V[self.opcode.X] == machine.V[self.opcode.Y]:
machine.pc += 2
def _6MMM(self, machine): # 6XNN
machine.V[self.opcode.X] = self.opcode.NN
def _7MMM(self, machine): # 7XNN
machine.V[self.opcode.X] += self.opcode.NN
def _8MM0(self, machine): # 8XY0
machine.V[self.opcode.X] = machine.V[self.opcode.Y]
def _8MM1(self, machine): # 8XY1
machine.V[self.opcode.X] |= machine.V[self.opcode.Y]
machine.V[0xF] = 0
def _8MM2(self, machine): # 8XY2
machine.V[self.opcode.X] &= machine.V[self.opcode.Y]
machine.V[0xF] = 0
def _8MM3(self, machine): # 8XY3
machine.V[self.opcode.X] ^= machine.V[self.opcode.Y]
machine.V[0xF] = 0
def _8MM4(self, machine): # 8XY4
vf_check = machine.V[self.opcode.Y] > (0xFF - machine.V[self.opcode.X])
if vf_check:
machine.V[0xF] = 1
overflow = (0xFF - machine.V[self.opcode.Y]) + 1
machine.V[self.opcode.X] -= overflow
else:
machine.V[0xF] = 0
machine.V[self.opcode.X] += machine.V[self.opcode.Y]
def _8MM5(self, machine): # 8XY5
vf_check = machine.V[self.opcode.X] < machine.V[self.opcode.Y]
if vf_check:
machine.V[0xF] = 0
overflow = (0xFF - machine.V[self.opcode.Y]) + 1
machine.V[self.opcode.X] += overflow
else:
machine.V[0xF] = 1
machine.V[self.opcode.X] -= machine.V[self.opcode.Y]
def _8MM6(self, machine): # 8XY6
machine.V[0xF] = machine.V[self.opcode.X] & 0x1
machine.V[self.opcode.X] >>= 1
def _8MM7(self, machine): # 8XY7
vf_check = machine.V[self.opcode.Y] < machine.V[self.opcode.X]
if vf_check:
machine.V[0xF] = 0
overflow = (0xFF - machine.V[self.opcode.X]) + 1
machine.V[self.opcode.X] = machine.V[self.opcode.Y] + overflow
else:
machine.V[0xF] = 1
machine.V[self.opcode.X] = (
machine.V[self.opcode.Y] - machine.V[self.opcode.X]
)
def _8MME(self, machine): # 8XYE
machine.V[0xF] = machine.V[self.opcode.X] >> 7
machine.V[self.opcode.X] <<= 1
def _9MMM(self, machine): # 9XY0
if machine.V[self.opcode.X] != machine.V[self.opcode.Y]:
machine.pc += 2
def _AMMM(self, machine): # ANNN
machine.I = self.opcode.NNN
def _BMMM(self, machine): # BNNN
machine.pc = machine.V[0x0] + self.opcode.NNN
def _CMMM(self, machine): # CXNN
machine.V[self.opcode.X] = random.randint(0, 255) & self.opcode.NN
def _DMMM(self, machine): # DXYN
N = self.opcode.N if self.opcode.N > 0 else 2 * machine.gfx.MAX_HEIGHT
img = machine.memory[machine.I:machine.I + N]
machine.gfx.draw_sprite(
img, machine.V[self.opcode.X], machine.V[self.opcode.Y]
)
machine.V[0xF] = 1 if machine.gfx.collision_flag else 0
def _EM9E(self, machine): # EX9E
if machine.keyboard.state[machine.V[self.opcode.X]] == 1:
machine.pc += 2
def _EMA1(self, machine): # EXA1
if machine.keyboard.state[machine.V[self.opcode.X]] == 0:
machine.pc += 2
def _FM07(self, machine): # FX07
machine.V[self.opcode.X] = machine.delay_timer
def _FM0A(self, machine): # FX0A
machine.V[self.opcode.X] = machine.keyboard.get_active_key()
def _FM15(self, machine): # FX15
machine.delay_timer = machine.V[self.opcode.X]
def _FM18(self, machine): # FX18
machine.sound_timer = machine.V[self.opcode.X]
def _FM1E(self, machine): # FX1E
vf_check = machine.I > (0xFFF - machine.V[self.opcode.X])
if vf_check:
machine.V[0xF] = 1
overflow = (0xFFF - machine.V[self.opcode.X]) + 1
machine.I -= overflow
else:
machine.V[0xF] = 0
machine.I += machine.V[self.opcode.X]
def _FM29(self, machine): # FX29
machine.I = machine.V[self.opcode.X] * 0x5
# Note: sprites are stored as 4x5 hex font characters (0-F)
def _FM30(self, machine): # FX29
machine.I = machine.V[self.opcode.X] * 0xA + 16 * 0x5
def _FM33(self, machine): # FX33
machine.memory[machine.I] = machine.V[self.opcode.X] // 100
machine.memory[machine.I + 1] = (machine.V[self.opcode.X] // 10) % 10
machine.memory[machine.I + 2] = (machine.V[self.opcode.X] % 100) % 10
def _FM55(self, machine): # FX55
reg_range = slice(0, self.opcode.X + 1)
mem_range = slice(machine.I, machine.I + self.opcode.X + 1)
machine.memory[mem_range] = machine.V[reg_range]
def _FM65(self, machine): # FX65
reg_range = slice(0, self.opcode.X + 1)
mem_range = slice(machine.I, machine.I + self.opcode.X + 1)
machine.V[reg_range] = machine.memory[mem_range]
def _NOP(self, machine): # Unknown Code
print("Unknown code: {}".format(self.opcode.as_str()))
print("Calling PC: {}".format(machine.pc - 2))
| StarcoderdataPython |
4920727 | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from enduse.stockobjects import Equipment, RampEfficiency, EndUse, Building
from enduse.stockturnover import BuildingModel
from enduse.oedi_tools import LoadProfiles
res_oedi_puma = {
"segment": "resstock",
"weather_type": "tmy3",
"state": "WA",
"puma_code": "g53011606",
"bldg_types": ["single-family_detached"],
}
print("Pulling resstock")
oedi_sf_scl = LoadProfiles(**res_oedi_puma)
oedi_sf_scl_df = oedi_sf_scl.load_profiles["single-family_detached"]
agg_cols = [
"out.electricity.cooling.energy_consumption",
"out.electricity.heating.energy_consumption",
"out.electricity.heating_supplement.energy_consumption",
]
oedi_sf_scl_df_norm = (
oedi_sf_scl_df.set_index(
oedi_sf_scl_df["timestamp"] - pd.Timedelta(hours=3, minutes=15)
)
.filter(agg_cols)
.resample("H")
.mean()
)
oedi_sf_scl_df_norm["resistence_heating"] = oedi_sf_scl_df_norm[agg_cols[-2:]].sum(
axis=1
)
oedi_sf_scl_df_norm["heat_pump"] = oedi_sf_scl_df_norm[agg_cols].sum(axis=1)
oedi_sf_scl_df_norm = oedi_sf_scl_df_norm.transform(lambda x: x / x.sum())
equipment = []
equipment.append(
{
"equipment_label": "Standard Electric Furnace HSPF = 1",
"efficiency_level": 1,
"start_year": 2022,
"end_year": 2041,
"efficiency_share": np.linspace(1, 1, 20).tolist(),
"consumption": np.linspace(13312, 13312, 20).tolist(),
"useful_life": np.linspace(15, 15, 20).tolist(),
}
)
equipment.append(
{
"equipment_label": "Install Ductless Heat Pump in House with Existing FAF - HZ1",
"efficiency_level": 2,
"start_year": 2022,
"end_year": 2041,
"efficiency_share": np.linspace(0, 0, 20).tolist(),
"consumption": np.linspace(8500, 8500, 20).tolist(),
"useful_life": np.linspace(18, 18, 20).tolist(),
}
)
equipment_parsed = [Equipment(**i) for i in equipment]
ramp = {
"ramp_label": "Forced Air Furnance to Heat Pump Upgrade",
"ramp_equipment": [equipment_parsed[1]],
}
ramp_parsed = RampEfficiency(**ramp)
end_use = {
"end_use_label": "Heat Central",
"equipment": equipment_parsed,
"ramp_efficiency": ramp_parsed,
"saturation": np.linspace(0.50, 0.50, 20).tolist(),
"fuel_share": np.linspace(0.05, 0.05, 20).tolist(),
}
end_use_parsed = [EndUse(**end_use)]
building = {
"building_label": "Single Family",
"end_uses": end_use_parsed,
"building_stock": np.linspace(200000, 200000, 20).tolist(),
}
building_parsed = Building(**building)
stock_turnover = BuildingModel(building_parsed)
x = stock_turnover.model["consumption"].values[0]
y = oedi_sf_scl_df_norm[["resistence_heating", "heat_pump"]].values
z = stock_turnover.model["equipment_stock"].values[0]
cons_shaped = np.einsum("ij,ki->ijk", x, y)
cons_shaped_df = pd.DataFrame(
cons_shaped.reshape(
(cons_shaped.shape[0], cons_shaped.shape[1] * cons_shaped.shape[2])
).T
)
reindex = pd.date_range(start="2022-01-01 00", end="2041-12-31 23", freq="H")
cons_shaped_df = cons_shaped_df.set_index(
reindex[~((reindex.month == 2) & (reindex.day == 29))]
)
cons_shaped_df = cons_shaped_df.rename(columns={0: "Electric Furnance", 1: "Heat Pump"})
stock_turnover_df = stock_turnover.to_dataframe().pivot(
index="year", columns="efficiency_label", values=["equipment_stock", "consumption"]
)
stock_turnover_df.index = pd.to_datetime(stock_turnover_df.index, format="%Y")
# stock turnover graphic
fig, axs = plt.subplots(ncols=2, figsize=(14, 4), sharey=False)
# equipment count subplot
axs[0].plot(
stock_turnover_df["equipment_stock"].sum(axis=1),
color="#FFBE0B",
lw=2,
label="Electric Resistence Space Heat",
)
axs[0].fill_between(
stock_turnover_df.index,
stock_turnover_df["equipment_stock"][
"Install Ductless Heat Pump in House with Existing FAF - HZ1"
],
stock_turnover_df["equipment_stock"].sum(axis=1),
color="#FFBE0B",
alpha=0.10,
)
axs[0].plot(
stock_turnover_df["equipment_stock"][
"Install Ductless Heat Pump in House with Existing FAF - HZ1"
],
color="#3A86FF",
lw=2,
label="Heat Pump",
)
axs[0].fill_between(
stock_turnover_df.index,
stock_turnover_df["equipment_stock"][
"Install Ductless Heat Pump in House with Existing FAF - HZ1"
],
color="#3A86FF",
alpha=0.10,
)
# annual consumption subplot
axs[1].plot(
stock_turnover_df["consumption"].sum(axis=1) / 1000 / 8760,
color="#FFBE0B",
lw=2,
label="Electric Resistence Space Heat",
)
axs[1].fill_between(
stock_turnover_df.index,
stock_turnover_df["consumption"][
"Install Ductless Heat Pump in House with Existing FAF - HZ1"
]
/ 1000
/ 8760,
stock_turnover_df["consumption"].sum(axis=1) / 1000 / 8760,
color="#FFBE0B",
alpha=0.10,
)
axs[1].plot(
stock_turnover_df["consumption"][
"Install Ductless Heat Pump in House with Existing FAF - HZ1"
]
/ 1000
/ 8760,
color="#3A86FF",
lw=2,
label="Heat Pump",
)
axs[1].fill_between(
stock_turnover_df.index,
stock_turnover_df["consumption"][
"Install Ductless Heat Pump in House with Existing FAF - HZ1"
]
/ 1000
/ 8760,
color="#3A86FF",
alpha=0.10,
)
for ax in axs:
# axis formatting
ax.tick_params(color="grey", labelcolor="grey")
ax.yaxis.set_ticks_position("none")
ax.spines["top"].set_edgecolor("lightgrey")
ax.spines["bottom"].set_edgecolor("lightgrey")
ax.spines["left"].set_edgecolor("lightgrey")
ax.spines["right"].set_edgecolor("lightgrey")
axs[0].set_ylabel("Equipment Counts", size=10, color="grey")
axs[1].set_ylabel("Annual Consumption (aMW)", size=10, color="grey")
legend = axs[1].legend(loc="upper right", frameon=False)
for text in legend.get_texts():
text.set_color("grey")
text.set_size(10)
fig.tight_layout()
# create load shape graphic
fig, axs = plt.subplots(ncols=3, figsize=(14, 4), sharey=True)
for ax, year in zip(axs, ["2022", "2030", "2040"]):
ax.set_title(f"Aggregate Load Shape: {year}", size=10, color="grey")
ax.plot(
cons_shaped_df.loc[year].sum(axis=1) / 1000,
color="#FFBE0B",
alpha=0.75,
label="Electric Resistence Space Heat",
)
ax.plot(
cons_shaped_df.loc[year]["Heat Pump"] / 1000,
color="#3A86FF",
alpha=0.75,
label="Heat Pump",
)
# axis formatting
ax.tick_params(color="grey", labelcolor="grey")
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks_position("none")
ax.spines["top"].set_edgecolor("lightgrey")
ax.spines["bottom"].set_edgecolor("lightgrey")
ax.spines["left"].set_edgecolor("lightgrey")
ax.spines["right"].set_edgecolor("lightgrey")
ax.set_xlabel("Hour of Year (8760)", size=10, color="grey")
# formatting
# axs[2].legend(frameon=False)
axs[0].set_ylabel("Hourly Load (MWh)", size=10, color="grey")
legend = axs[2].legend(loc="upper left", frameon=False)
for text in legend.get_texts():
text.set_color("grey")
text.set_size(10)
fig.tight_layout()
# to save fig with high dpi
# fig.savefig("./some/dir/graphic_name.png", dpi=300)
| StarcoderdataPython |
9683155 | """A collection of policy networks."""
import numpy as np
import tensorflow as tf
import sonnet as snt
class Policy(object):
"""The base class for policy networks.
Policy parameters are allowed to be functions of other policies. To keep
track of such dependencies, each policy stores a list of parent policies on
which it depends. To make an action or update a policy with a non-empty
list of dependencies, we need to ensure that all parent placeholders are
fed-in with appropriate values.
"""
def __init__(self, ob_size, num_actions, prev=None):
self.ob_size = ob_size
self.num_actions = num_actions
self._root = self
self._parents = tuple()
if prev is not None:
self._root = prev.root
self._parents = prev.parents + (prev, )
self._params = []
self._opponents = None
def build(self, scope, reuse=None):
raise NotImplementedError
@property
def opponents(self):
return self._opponents
@opponents.setter
def opponents(self, opponents):
self._opponents = opponents
@property
def parameters(self):
raise NotImplementedError
@property
def parents(self):
return self._parents
@property
def root(self):
return self._root
def get_feed_list(self, trace):
obs, acs, rets, values, infos = trace
aa = np.asarray([info['available_actions'] for info in infos])
feed_list = [
(self.obs_ph, obs),
(self.acs_ph, acs),
(self.rets_ph, rets),
(self.values_ph, values),
(self.avail_acs_ph, aa)
]
return feed_list
def act(self, ob, info, sess, parent_feed_list=[]):
aa = info['available_actions']
feed_list = [(self.obs_ph, [ob]), (self.avail_acs_ph, [aa])] + \
parent_feed_list
ac = sess.run(self.action, feed_dict=dict(feed_list))
return ac
def predict(self, ob, sess, parent_feed_list=[]):
feed_list = [(self.obs_ph, [ob])] + parent_feed_list
vpred = sess.run(self.vpred, feed_dict=dict(feed_list))
return vpred
@property
def parameters(self):
return self._params
class SimplePolicy(Policy):
"""A single layer network that maps states to action probabilities."""
def build(self, scope, reuse=None):
self.scope = scope
with tf.variable_scope(scope, reuse=reuse):
# Placeholders
self.acs_ph = tf.placeholder(
shape=[None, None], dtype=tf.int32, name="acs")
self.obs_ph = tf.placeholder(
shape=[None, None, self.ob_size], dtype=tf.float32, name="obs")
self.rets_ph = tf.placeholder(
shape=[None, None], dtype=tf.float32, name="rets")
self.avail_acs_ph = tf.placeholder(
shape=[None, None, self.num_actions],
dtype=tf.int32,
name="avail_acs")
self.values_ph = tf.placeholder(
shape=[None, None], dtype=tf.float32, name="target_values")
self.gamma_ph = tf.placeholder(
shape=[1, 1], dtype=tf.float32, name="gamma_ph")
self.discount = tf.cumprod(
self.gamma_ph * tf.ones_like(self.rets_ph),
axis=0, exclusive=True, name="discount")
with tf.variable_scope("policy", reuse=reuse):
pol_lin = snt.Linear(1, use_bias=False)
logits = snt.BatchApply(pol_lin)(self.obs_ph)
pol_params = [pol_lin.w]
# logits, pol_params = Linear3D(1)(self.obs_ph)
logits = tf.concat([logits, tf.zeros_like(logits)], -1)
# Mask out unavailable actions
# MA: Not sure how that affects the gradients. Maybe better for
# the environment to mask out the actions?
mask = -9999999 * tf.ones_like(logits)
logits = tf.where(
tf.equal(self.avail_acs_ph, 1), x=logits, y=mask)
# Log probs and actions
self.log_pi = tf.nn.log_softmax(logits)
self.acs_onehot = tf.one_hot(
self.acs_ph, self.num_actions, dtype=tf.float32)
self.log_pi_acs = tf.reduce_sum(
tf.multiply(self.log_pi, self.acs_onehot), axis=-1)
self.log_pi_acs_cumsum = tf.cumsum(self.log_pi_acs, axis=0)
self.action = tf.squeeze(tf.multinomial(
tf.reshape(self.log_pi, shape=(-1, self.num_actions)), 1))
# Value
with tf.variable_scope("value", reuse=reuse):
val_lin = snt.Linear(1, use_bias=True)
self.vpred = snt.BatchApply(val_lin)(self.obs_ph)
self.vpred = tf.squeeze(self.vpred)
val_params = [val_lin.w, val_lin.b]
# Parameters
self._params += pol_params + val_params
class MLPPolicy(Policy):
"""A feed-forward network with one or multiple hidden layers."""
def __init__(self, ob_size, num_actions, hidden_sizes=[16], prev=None):
super(MLPPolicy, self).__init__(ob_size, num_actions, prev=prev)
self.hidden_sizes = hidden_sizes
def build(self, scope, reuse=None):
self.scope = scope
with tf.variable_scope(scope, reuse=reuse):
# Placeholders
self.acs_ph = tf.placeholder(
shape=[None, None], dtype=tf.int32)
self.obs_ph = tf.placeholder(
shape=[None, None, self.ob_size], dtype=tf.float32)
self.rets_ph = tf.placeholder(
shape=[None, None], dtype=tf.float32)
self.avail_acs_ph = tf.placeholder(
shape=[None, None, self.num_actions], dtype=tf.int32)
self.values_ph = tf.placeholder(
shape=[None, None], dtype=tf.float32, name="target_values")
self.gamma_ph = tf.placeholder(
shape=[1, 1], dtype=tf.float32, name="gamma_ph")
self.discount = tf.cumprod(
self.gamma_ph * tf.ones_like(self.rets_ph),
axis=0, exclusive=True, name="discount")
with tf.variable_scope("policy", reuse=reuse):
# Hidden layers
pol_params = []
last = self.obs_ph
for i, units in enumerate(self.hidden_sizes):
pol_lin = snt.Linear(units, name="h_%d" % i)
last = snt.BatchApply(pol_lin)(last)
last = tf.nn.relu(last)
pol_params += [pol_lin.w, pol_lin.b]
pol_lin = snt.Linear(self.num_actions)
logits = snt.BatchApply(pol_lin)(last)
pol_params += [pol_lin.w, pol_lin.b]
# Mask out unavailable actions
# MA: Not sure how that affects the gradients. Maybe better for
# the environment to mask out the actions?
mask = -9999999 * tf.ones_like(logits)
logits = tf.where(
tf.equal(self.avail_acs_ph, 1), x=logits, y=mask)
# Log probs and actions
self.log_pi = tf.nn.log_softmax(logits)
self.acs_onehot = tf.one_hot(
self.acs_ph, self.num_actions, dtype=tf.float32)
self.log_pi_acs = tf.reduce_sum(
tf.multiply(self.log_pi, self.acs_onehot), axis=-1)
self.log_pi_acs_cumsum = tf.cumsum(self.log_pi_acs, axis=0)
self.action = tf.squeeze(tf.multinomial(
tf.reshape(self.log_pi, shape=(-1, self.num_actions)), 1))
# Value
with tf.variable_scope("value", reuse=reuse):
val_params = []
last = self.obs_ph
for i, units in enumerate(self.hidden_sizes):
val_lin = snt.Linear(units, name="h_%d" % i)
last = snt.BatchApply(val_lin)(last)
last = tf.nn.relu(last)
val_params += [val_lin.w, val_lin.b]
val_lin = snt.Linear(1)
self.vpred = snt.BatchApply(val_lin)(last)
self.vpred = tf.squeeze(self.vpred)
val_params += [val_lin.w, val_lin.b]
# Parameters
self._params += pol_params + val_params
class RecurrentPolicy(Policy):
"""A recurrent network with one or multiple hidden layers."""
def __init__(self, ob_size, num_actions, hidden_sizes=[16], prev=None):
super(MLPPolicy, self).__init__(ob_size, num_actions, prev=prev)
self.hidden_sizes = hidden_sizes
def build(self, scope, reuse=None):
self.scope = scope
with tf.variable_scope(scope, reuse=reuse):
# Placeholders
self.acs_ph = tf.placeholder(
shape=[None, None], dtype=tf.int32)
self.obs_ph = tf.placeholder(
shape=[None, None, self.ob_size], dtype=tf.float32)
self.rets_ph = tf.placeholder(
shape=[None, None], dtype=tf.float32)
self.avail_acs_ph = tf.placeholder(
shape=[None, None, self.num_actions], dtype=tf.int32)
self.values_ph = tf.placeholder(
shape=[None, None], dtype=tf.float32, name="target_values")
self.gamma_ph = tf.placeholder(
shape=[1, 1], dtype=tf.float32, name="gamma_ph")
self.discount = tf.cumprod(
self.gamma_ph * tf.ones_like(self.rets_ph),
axis=0, exclusive=True, name="discount")
with tf.variable_scope("policy", reuse=reuse):
# Hidden layers
pol_params = []
last = self.obs_ph
for i, units in enumerate(self.hidden_sizes):
pol_lin = snt.Linear(units, name="h_%d" % i)
last = snt.BatchApply(pol_lin)(last)
last = tf.nn.relu(last)
pol_params += [pol_lin.w, pol_lin.b]
pol_lin = snt.Linear(self.num_actions)
logits = snt.BatchApply(pol_lin)(last)
pol_params += [pol_lin.w, pol_lin.b]
# Mask out unavailable actions
# MA: Not sure how that affects the gradients. Maybe better for
# the environment to mask out the actions?
mask = -9999999 * tf.ones_like(logits)
logits = tf.where(
tf.equal(self.avail_acs_ph, 1), x=logits, y=mask)
# Log probs and actions
self.log_pi = tf.nn.log_softmax(logits)
self.acs_onehot = tf.one_hot(
self.acs_ph, self.num_actions, dtype=tf.float32)
self.log_pi_acs = tf.reduce_sum(
tf.multiply(self.log_pi, self.acs_onehot), axis=-1)
self.log_pi_acs_cumsum = tf.cumsum(self.log_pi_acs, axis=0)
self.action = tf.squeeze(tf.multinomial(
tf.reshape(self.log_pi, shape=(-1, self.num_actions)), 1))
# Value
with tf.variable_scope("value", reuse=reuse):
val_params = []
last = self.obs_ph
for i, units in enumerate(self.hidden_sizes):
val_lin = snt.Linear(units, name="h_%d" % i)
last = snt.BatchApply(val_lin)(last)
last = tf.nn.relu(last)
val_params += [val_lin.w, val_lin.b]
val_lin = snt.Linear(1)
self.vpred = snt.BatchApply(val_lin)(last)
self.vpred = tf.squeeze(self.vpred)
val_params += [val_lin.w, val_lin.b]
# Parameters
self._params += pol_params + val_params
| StarcoderdataPython |
5021915 | <filename>Model Development/parameters.py<gh_stars>0
#################################################
# parameter file for St. Anna project
################################################
import numpy as np
from sklearn.model_selection import ParameterGrid
from ml_classes import ModelDevelopment
from dataclasses import dataclass, field, InitVar
from typing import Any, List, Dict, Set
import sys
import json
@dataclass
class Parameters:
"""Class to hold the parameters for model development
"""
##############################################
# set below parameters based on experiment
##############################################
# the dataset (Knee or Hip)
DATA_TYPE : str = 'Hip'
# what are we predicting (Diagnosis or Treatment)
PREDICTION_TYPE : str = 'Treatment'
# whether we are evaluating on validation or test set
VALIDATION_OR_TEST = "test"
# the labels that we are predicting
labels = ['Conservative', 'Surgical']
# which models are we evaluating?
MODELS = ['knn', 'dt', 'rf', 'adaboost', 'svm', 'gb', 'nn']
# do we compute confidence intervals (True or False) MUST ALWAYS BE FALSE WHEN CALLING PIPELINE
COMPUTE_CONFIDENCE_INTERVALS : bool = False
# the amount of cross-validation folds
CV_FOLDS : int = 3
# how often do we repeat cv
N_REPEATS : int = 10
# is it a multiclass problem? (True or False)
MULTICLASS = True
# how often do we repeat a single feature importance method
N_ROUNDS = 5
# top n features to plot for feature importance scores
FI_TOP_N = 10
# analyze the errors of the models or not
ERROR_ANALYSIS : bool = False
##############################################################
# preprocessing, evaluation strategy, and sampling options
##############################################################
# choose one of both:
# normalize the data or not
NORMALIZE_DATA : bool = True
# do we standardize the data (True or False)
STANDARDIZE_DATA : bool = False
# apply PCA to the data or not
PCA_DATA : bool = False
# the amount of variance to be explained by PCA if you choose to apply PCA
PCA_VARIANCE : float = 0.6
# add polynomial features to the data or not
POLY_DATA : bool = False
# the exponent to raise the features to if you choose to add polynomial features
AMT_POLY : Any = 2
# power the data or not
POWER_DATA : bool = False
# the sampling method to use (one of 'under', 'over', 'smote', 'smotetomek', 'both')
SAMPLING_METHOD : str = 'under'
# the sampling strategy to apply
UNDERSAMPLE_STRATEGY : Any = 'majority'
OVERSAMPLE_STRATEGY : Any = 'minority'
# choose one of both:
# use the One vs One or One vs Rest multiclass strategy
OVO : bool = False
OVR : bool = False
CC : bool = False
def __post_init__(self):
"""Initialise the grid for optimization of the parameters
"""
self.optimization_options = {
# variable ENTER WHAT YOU WANT
'SAMPLING_METHOD' : [None, 'under', 'over', 'smote', 'smotetomek'],
'UNDERSAMPLE_STRATEGY' : [None] + ['majority'],
'OVERSAMPLE_STRATEGY' : [None] + ['minority'],
'OVO' : [ False],
'OVR' : [True, False],
'CC' : [True, False],
'POLY_DATA' : [False],
'POWER_DATA' : [False],
'AMT_POLY' : [None],
'STANDARDIZE_DATA' : [True],
'NORMALIZE_DATA' : [False],
'PCA_DATA' : [False],
# The amount of variance to be explained by PCA
'PCA_VARIANCE' : [None],
# the parameter below are always the same, do not change
# the dataset (Knee or Hip)
'DATA_TYPE' : [self.DATA_TYPE],
# what are we predicting (Diagnosis or Treatment)
'PREDICTION_TYPE' : [self.PREDICTION_TYPE],
# which models are we evaluating?
'MODELS' : [self.MODELS],
# do we compute confidence intervals (True or False)
'COMPUTE_CONFIDENCE_INTERVALS' : [self.COMPUTE_CONFIDENCE_INTERVALS],
# do we standardize the data (True or False)
'STANDARDIZE_DATA' : [self.STANDARDIZE_DATA],
# the amount of cross-validation folds
'CV_FOLDS' : [self.CV_FOLDS],
# how often do we repeat cv
'N_REPEATS' : [self.N_REPEATS],
# is it a multiclass problem? (True or False)
'MULTICLASS' : [self.MULTICLASS],
# are we training or are we fitting the final models
'TRAINING' : [self.VALIDATION_OR_TEST],
# how often do we repeat a single feature importance method
'N_ROUNDS' : [self.N_ROUNDS],
'FI_TOP_N' : [self.FI_TOP_N]
}
# make a grid of the optimization options
self.param_grid = list(ParameterGrid(self.optimization_options))
# filter invalid combinations from the grid
self.filter_param_grid()
def filter_param_grid(self):
"""Filter invalid parameter combinations from the optimization grid
"""
filtered_grid = []
for params in self.param_grid:
if params['SAMPLING_METHOD'] != 'under' and params['UNDERSAMPLE_STRATEGY'] != None:
continue
if params['SAMPLING_METHOD'] != 'over' and params['OVERSAMPLE_STRATEGY'] != None:
continue
if params['SAMPLING_METHOD'] == 'over' and params['OVERSAMPLE_STRATEGY'] == None:
continue
if params['SAMPLING_METHOD'] == 'under' and params['UNDERSAMPLE_STRATEGY'] == None:
continue
if params['PCA_VARIANCE'] != None:
if params['PCA_DATA'] == False and params['PCA_VARIANCE'] > 0.4:
continue
if params['STANDARDIZE_DATA'] == True and params['NORMALIZE_DATA'] == True:
continue
if params['OVO'] == True and params['OVR'] == True:
continue
if params['OVO'] == True and params['CC'] == False:
continue
if params['POLY_DATA'] == False and params['AMT_POLY'] != None:
continue
if params['POLY_DATA'] == True and params['AMT_POLY'] == None:
continue
filtered_grid.append(params)
self.param_grid = filtered_grid
def optimize(self, data, model=['rf']):
"""Find the best combination of parameter values
Args:
data (class instance): The data to use for optimization
model (list, optional): Models for which to optimize parameter values. Defaults to ['rf'].
Returns:
dict: best combination of parameter values
"""
# placeholders for best metric scores
current_best_AUC = 0
current_best_balanced_accuracy = 0
# for each unique combination of parameters in the grid
for i, params in enumerate(self.param_grid):
print(f'Evaluating #{i} out of {len(self.param_grid)} parameter configurations')
# set the parameters to the combination of parameters
self.update(params)
# retrieve the parameters in dictionary form
params = DotDict(self.dict_from_class())
# delete unnecessary stuff
del params.optimization_options
del params.param_grid
# make sure to add the name of the model
params.MODELS = model
# instantiate model development class
ML = ModelDevelopment(data, params)
# evaluate the combination of parameter values
if self.VALIDATION_OR_TEST == "validation":
ML.cross_validate_all_models()
else:
ML.tts_finalize()
# retrieve the model and it's metric scores
trained_model = ML.model_list.models[0]
new_AUC = trained_model.results.mean_auc
new_balanced_accuracy = trained_model.results.mean_balanced_accuracy
# if the AUC is better than the current best AUC
if new_AUC > current_best_AUC:
print(f'Improvement! The best AUC is now {new_AUC}')
# set current best AUC to new AUC
current_best_AUC = new_AUC
# store the param values
best_params_AUC = params
# if the balanced accuracy is better than the current best balanced accuracy:
if new_balanced_accuracy > current_best_balanced_accuracy:
print(f'Improvement! The best balanced accuracy is now {new_balanced_accuracy}')
# set the current best ba to the new ba
current_best_balanced_accuracy = new_balanced_accuracy
# store the param values
best_params_balanced_accuracy = params
# if both the AUC and ba are better than the current best scores
if new_AUC >= current_best_AUC and new_balanced_accuracy >= current_best_balanced_accuracy:
print(f'Ultimate improvement! The best combo is now {new_AUC}, {new_balanced_accuracy} ')
# set the current best scores to the new scores
current_best_AUC = new_AUC
current_best_balanced_accuracy = new_balanced_accuracy
# store the params
best_params_combo = params
best_params_AUC = params
best_params_balanced_accuracy = params
print('========================================================')
print(f'Finished \n Best auc : {current_best_AUC}, Best ba: {current_best_balanced_accuracy} \n Best params : {best_params_combo}')
# set parameters in instance to best found parameters
self.update(best_params_balanced_accuracy)
# store the best found parameter value combinations to json
with open(f'Results/Params/basic_params_combo_{self.DATA_TYPE}_{self.PREDICTION_TYPE}_{model[0]}_{self.TEST_OR_FINAL}.json', 'w') as fp:
json.dump(best_params_combo, fp, cls=NpEncoder)
with open(f'Results/Params/basic_params_AUC_{self.DATA_TYPE}_{self.PREDICTION_TYPE}_{model[0]}_{self.TEST_OR_FINAL}.json', 'w') as fp:
json.dump(best_params_AUC, fp, cls=NpEncoder)
with open(f'Results/Params/basic_params_balanced_accuracy_{self.DATA_TYPE}_{self.PREDICTION_TYPE}_{model[0]}_{self.TEST_OR_FINAL}.json', 'w') as fp:
json.dump(best_params_balanced_accuracy, fp, cls=NpEncoder)
# return the best parameter value combination and metric scores
return best_params_combo, best_params_AUC, best_params_balanced_accuracy
def update(self,newdata):
for key, value in newdata.items():
setattr(self, key, value)
def dict_from_class(self):
return vars(self)
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
class DotDict(dict):
"""dot.notation access to dictionary attributes"""
def __getattr__(*args):
val = dict.get(*args)
return DotDict(val) if type(val) is dict else val
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
parameters = Parameters()
| StarcoderdataPython |
1825680 | <reponame>michellemark/html2ans
import pytest
from html2ans.parsers.text import ListParser
parser = ListParser()
@pytest.fixture(params=[
'<ol></ol>',
'<ul></ul>',
])
def valid_list_tag(request):
return request.param
def test_empty(make_tag):
tag = make_tag('<ol></ol>', 'ol')
assert not parser.parse(tag).output.get('items')
tag = make_tag('<ul></ul>', 'ul')
assert not parser.parse(tag).output.get('items')
def test_is_applicable(valid_list_tag, make_tag):
tag = make_tag('<ol></ol>', 'ol')
assert parser.is_applicable(tag)
tag = make_tag('<ul></ul>', 'ul')
assert parser.is_applicable(tag)
def test_nested_list(make_tag):
tag = make_tag(
'<ol><li><ul><li><p>level two item</p></li></ul></li><li><p>level one item</p></li></ol>',
'ol')
parsed = parser.parse(tag).output
assert parsed.get('type') == 'list'
assert parsed.get('list_type') == 'ordered'
assert parsed.get('items') == [
{
'items': [
{
'content': '<p>level two item</p>',
'type': 'text'
}
],
'list_type': 'unordered',
'type': 'list'
},
{
'content': '<p>level one item</p>',
'type': 'text'
}
]
def test_complex_list(make_tag):
tag = make_tag('<ul><li>Post Reports, '
'<a href="/podcast/">a daily podcast</a> '
'from The Washington Post.</li>'
'<li><ol><li>Unparalleled reporting.</li>'
'<li>Expert insight.</li></ol>'
'<li>Clear analysis.</li></ul>', 'ul')
parsed = parser.parse(tag).output
assert parsed.get('type') == 'list'
assert parsed.get('list_type') == 'unordered'
list_items = parsed.get("items")
assert len(list_items) == 3
assert list_items[0].get("type") == "text"
assert list_items[0].get("content") == 'Post Reports, ' \
'<a href="/podcast/">a daily podcast</a> ' \
'from The Washington Post.'
assert list_items[1].get("type") == "list"
assert list_items[1].get("list_type") == "ordered"
assert len(list_items[1].get("items")) == 2
assert list_items[1].get("items")[0].get("type") == "text"
assert list_items[2].get("type") == "text"
def test_basic_list(make_tag):
tag = make_tag(
'<ol><li>Item one</li><li>Item two</li></a></li></ol>', 'ol')
parsed = parser.parse(tag).output
assert parsed.get('type') == 'list'
assert parsed.get('list_type') == 'ordered'
assert parsed.get('items') == [
{
'type': 'text',
'content': 'Item one'
},
{
'type': 'text',
'content': 'Item two'
}
]
def test_empty_list(make_tag):
tag = make_tag(
'<ol><li></li><li></li></ol>', 'ol')
parsed = parser.parse(tag).output
assert parsed.get('type') == 'list'
assert parsed.get('list_type') == 'ordered'
assert parsed.get('items') == []
| StarcoderdataPython |
3390145 | # Generated by Django 3.0.1 on 2019-12-29 14:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('WebAXEL', '0009_auto_20191229_1505'),
]
operations = [
migrations.AddField(
model_name='document',
name='description',
field=models.TextField(blank=True, null=True),
),
]
| StarcoderdataPython |
281809 | from bs4 import BeautifulSoup
import time
import requests
from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponse
from django.views import View
from django.views.generic.edit import CreateView, DeleteView
from scraper.models import Serie
BASE_URL = "http://fmovies.to"
class Index(View):
def get(self, request):
return render(request, 'index.html')
# Display the list of tracked series with their stored info.
class Tracker(View):
def get(self, request):
series = Serie.objects.all().order_by('name')
return render(request, 'tracker.html', {'cont': series})
class Add_Series(CreateView):
model = Serie
fields = ['name', 'season']
def form_valid(self, form):
self.object = form.save(commit = False)
# Format spaces with '+'.
s_name = form.cleaned_data["name"].replace(' ', '+') + '+' + str(form.cleaned_data["season"])
s_name = s_name.replace('+1', '') if s_name.endswith('+1') else s_name
# Get info for new Entry and scrape required info.
ep = get_last_ep(s_name)
self.object.episode_link = ep["episode_link"]
self.object.episode_num = ep["episode_num"]
self.object.save()
return super().form_valid(form)
# Change to use Ajax so page isn't refreshed and update DOM with jQuery.
class Update_Series(View):
def post(self, request, pk):
t = Serie.objects.get(pk = pk)
name = (str(t.name) + ' ' + str(t.season)).replace(' ', '+')
dt = get_last_ep(name)
t.episode_link = dt["episode_link"]
t.episode_num = dt["episode_num"]
t.save()
return redirect('scraper:tracker')
# Change to use Ajax so page isn't refreshed and update Dom with jQuery.
class Delete_Series(DeleteView):
model = Serie
def get_success_url(self):
return reverse('scraper:tracker')
# AJAX search box.
class Search_Series(View):
def get(self, request):
search_text = ''
return redirect('scraper:tracker')
def post(self, request):
search_text = request.POST['search_text']
# Empty search box.
if search_text == '':
series = Serie.objects.all()
else:
series = Serie.objects.filter(name__contains = search_text)
return render(request, 'seriesList-Template.html', {'cont': series})
# Request to scrape tracked series and display results
class Scraper(View):
def get(self, request):
s = list(Serie.objects.all().values('name', 'season'))
s = ['{0}+{1}'.format(x['name'], str(x['season'])) for x in s]
s = [t.replace(' ', '+').replace('0', '+', 1) \
if not t.endswith('0') else t.replace(' ', '+') for t in s]
s = [t.replace('+1', '') if t.endswith('+1') else t for t in s]
cont = generate_content_dictionary(s)
# Update database entries or create new ones.
for k, v in cont.items():
try:
t = Serie.objects.get(name = v["name"])
t.episode_link = v["episode_link"]
t.episode_num = v["episode_num"]
t.season = v["season"]
t.save()
except Serie.DoesNotExist:
tmp = Serie(name = v["name"], episode_link = v["episode_link"],
episode_num = v["episode_num"], season = v["season"])
tmp.save()
return redirect('scraper:tracker')
class Latest_Movies(View):
def get(self, request):
return render(request, 'latest-movies.html')
##################################################
################ Scraping Logic ##################
##################################################
def get_last_ep(series_name):
#prettify name
season = '1'
name = series_name
if '+' in series_name:
name, season = series_name.rsplit('+', 1)
name = name.capitalize()
if '+' in name:
name = name.replace('+', ' ')
#Scrape series url (For season)
payload = {'keyword': series_name}
r = requests.get('{0}/filter?sort=type%5B%5D%3Dseries&type%5B%5D=series'.format(BASE_URL), params = payload)
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find("a", class_ = "poster")
result = result.get('href')
#Scrape last episode
r2 = requests.get('{0}{1}'.format(BASE_URL, result))
soup2 = BeautifulSoup(r2.text, 'html.parser')
episodes = soup2.select("ul.episodes.range.active")[0]
last_episode_link = episodes.find_all("a")[-1].get('href')
last_episode_num = episodes.find_all("a")[-1].text
time.sleep(5)
return {"name": name, "episode_num": last_episode_num,
"episode_link": '{0}{1}'.format(BASE_URL,last_episode_link),
"season": season,
}
# Generate Json-Like response dict for the templates.
def generate_content_dictionary(series):
content = {}
for s in series:
tmp = get_last_ep(s)
content[tmp['name']] = tmp
return content
| StarcoderdataPython |
6514854 | def index_power(array: list, n: int) -> int:
try:
return pow(array[n], n);
except IndexError:
return -1; | StarcoderdataPython |
221240 | <filename>gertrude/cogs/games/game_cog.py
import discord
import logging
from .tictactoe import Tictactoe
from .rps import Rockpaperscissors
from .dice import Dice
from discord.ext.commands import Bot, Cog
from discord.ext import commands
log = logging.getLogger(__name__)
class Game(Cog):
def __init__(self, bot: Bot):
self.bot = bot
@commands.command(
name="tictactoe",
description="Start a tictactoe with someone",
brief="Start a tictactoe with someone",
aliases=['tic', 'tac', 'toe'],
)
async def tictactoe_command(self, ctx, user: discord.Member):
await Tictactoe(self.bot, ctx, user).play()
@commands.command(
name="rockpaperscissors",
description="Play rock paper scissors",
brief="Play rock paper scissors",
aliases=['rps'],
)
async def rps_command(self, ctx, user: discord.Member):
await Rockpaperscissors(self.bot, ctx, user).play()
@commands.command(
name="dice",
description="Roll a dice",
brief="Roll a dice",
)
async def dice_command(self, ctx, dice: str):
await Dice(self.bot, ctx, dice).play()
def setup(bot: Bot):
bot.add_cog(Game(bot))
| StarcoderdataPython |
3233391 | <filename>awsSchema/dynamodb.py
# AUTOGENERATED! DO NOT EDIT! File to edit: dynamodb.ipynb (unless otherwise specified).
__all__ = []
# Cell
#export
from dataclasses import field
from dataclasses import dataclass, field
from dataclasses_json import dataclass_json, Undefined | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.