code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python3
import argparse
import hashlib
import json
import re
import signal
import subprocess
import sys
import time
import urllib.request
DEFAULT_SERVER_HOSTNAME = "127.0.0.1"
DEFAULT_SERVER_PORT = 6878
SERVER_POLL_TIME = 2
SERVER_STATUS_STREAM_ACTIVE = "dl"
def exit_error(message):
print(f"Error: {message}", file=sys.stderr)
sys.exit(1)
class WatchSigint:
_sent = None
def __init__(self):
if WatchSigint._sent is None:
# install handler
WatchSigint._sent = False
signal.signal(signal.SIGINT, self._handler)
def _handler(self, signal, frame):
# Ctrl-C (SIGINT) sent to process
WatchSigint._sent = True
def sent(self):
return WatchSigint._sent
def read_arguments():
# create parser
parser = argparse.ArgumentParser(
description="Instructs server to commence a given program ID. "
"Will optionally execute a local media player once playback has started."
)
parser.add_argument(
"--ace-stream-pid", help="program ID to stream", metavar="HASH", required=True
)
parser.add_argument("--player", help="media player to execute once stream active")
parser.add_argument(
"--progress",
action="store_true",
help=f"continue to output stream statistics (connected peers/transfer rates) every {SERVER_POLL_TIME} seconds",
)
parser.add_argument(
"--server",
default=DEFAULT_SERVER_HOSTNAME,
help="server hostname, defaults to %(default)s",
metavar="HOSTNAME",
)
parser.add_argument(
"--port",
default=DEFAULT_SERVER_PORT,
help="server HTTP API port, defaults to %(default)s",
)
arg_list = parser.parse_args()
if not re.search(r"^[a-f0-9]{40}$", arg_list.ace_stream_pid):
exit_error(f"invalid stream program ID of [{arg_list.ace_stream_pid}] given")
# return arguments
return (
arg_list.ace_stream_pid,
arg_list.player,
arg_list.progress,
arg_list.server,
arg_list.port,
)
def api_request(url):
response = urllib.request.urlopen(url)
return json.load(response).get("response", {})
def start_stream(server_hostname, server_port, stream_pid):
# build stream UID from PID
stream_uid = hashlib.sha1(stream_pid.encode()).hexdigest()
# call API to commence stream
response = api_request(
f"http://{server_hostname}:{server_port}/ace/getstream?format=json&sid={stream_uid}&id={stream_pid}"
)
# return statistics API endpoint and HTTP video stream URLs
return (response["stat_url"], response["playback_url"])
def stream_stats_message(response):
return (
f'Peers: {response.get("peers", 0)} // '
f'Down: {response.get("speed_down", 0)}KB // '
f'Up: {response.get("speed_up", 0)}KB'
)
def await_playback(watch_sigint, statistics_url):
while True:
response = api_request(statistics_url)
if response.get("status") == SERVER_STATUS_STREAM_ACTIVE:
# stream is ready
print("Ready!\n")
return True
if watch_sigint.sent():
# user sent SIGINT, exit now
print("\nExit!")
return False
# pause and check again
print(f"Waiting... [{stream_stats_message(response)}]")
time.sleep(SERVER_POLL_TIME)
def execute_media_player(media_player_bin, playback_url):
subprocess.Popen(
media_player_bin.split() + [playback_url],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
def stream_progress(watch_sigint, statistics_url):
print("")
while True:
print(f"Streaming... [{stream_stats_message(api_request(statistics_url))}]")
if watch_sigint.sent():
# user sent SIGINT, exit now
print("\nExit!")
return
time.sleep(SERVER_POLL_TIME)
def main():
# read CLI arguments
(
stream_pid,
media_player_bin,
progress_follow,
server_hostname,
server_port,
) = read_arguments()
# create Ctrl-C watcher
watch_sigint = WatchSigint()
print(f"Connecting to program ID [{stream_pid}]")
statistics_url, playback_url = start_stream(
server_hostname, server_port, stream_pid
)
print("Awaiting successful connection to stream")
if not await_playback(watch_sigint, statistics_url):
# exit early
return
print(f"Playback available at [{playback_url}]")
if media_player_bin is not None:
print("Starting media player...")
execute_media_player(media_player_bin, playback_url)
if progress_follow:
stream_progress(watch_sigint, statistics_url)
if __name__ == "__main__":
main()
| [
"signal.signal",
"argparse.ArgumentParser",
"time.sleep",
"sys.exit",
"json.load",
"re.search"
] | [((356, 367), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (364, 367), False, 'import sys\n'), ((819, 988), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Instructs server to commence a given program ID. Will optionally execute a local media player once playback has started."""'}), "(description=\n 'Instructs server to commence a given program ID. Will optionally execute a local media player once playback has started.'\n )\n", (842, 988), False, 'import argparse\n'), ((1789, 1841), 're.search', 're.search', (['"""^[a-f0-9]{40}$"""', 'arg_list.ace_stream_pid'], {}), "('^[a-f0-9]{40}$', arg_list.ace_stream_pid)\n", (1798, 1841), False, 'import re\n'), ((3391, 3419), 'time.sleep', 'time.sleep', (['SERVER_POLL_TIME'], {}), '(SERVER_POLL_TIME)\n', (3401, 3419), False, 'import time\n'), ((3922, 3950), 'time.sleep', 'time.sleep', (['SERVER_POLL_TIME'], {}), '(SERVER_POLL_TIME)\n', (3932, 3950), False, 'import time\n'), ((549, 592), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'self._handler'], {}), '(signal.SIGINT, self._handler)\n', (562, 592), False, 'import signal\n'), ((2184, 2203), 'json.load', 'json.load', (['response'], {}), '(response)\n', (2193, 2203), False, 'import json\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 13:10:41 2018
@author: crius
"""
import Hamiltonians as H
import numpy as np
import tools as t
import spintensor as st
import spinops as so
import time
import Expand as ex
from matplotlib import pyplot as plt
exp = np.exp
N = 8
nlegs = 4
S = 0.5
c = np.sqrt(2)
Jcurr=0
J1=1
J2=1
Htot = H.nlegHeisenberg.blockH(N,S,nlegs,c,Js = [1,1],gamma =[0.0, 4.0],full='True')
Hfull = sum(Htot).todense()
eigs, vecs = np.linalg.eigh(Hfull)
Eigvecs = np.asarray(vecs.T)
print(list(eigs))
Envecs = []
for vc in Eigvecs:
A = ex.Expand(vc,S,N,Jcurr)
Envecs.append(A)
statelist = t.Statelist(N,S)
Statevecs = []
for state in statelist:
vec = []
up = [1,0]
down = [0,1]
for i in state:
if i == 0:
vec.append(down)
elif i ==1:
vec.append(up)
Basestate = ''.join(map(str,state))
B = [Basestate,vec[0]]#initializes state so that tensor product can be preformed
for i in range(len(vec)-1):
D = np.kron(B[1],vec[i+1])
B[1] = D
Statevecs.append((B[0],B[1]))
####
Basestates = dict(Statevecs)
#print(Basestates)
BS = Basestates['11001100']
s = so.sz(S)
print(t.exval(BS,BS,Hfull))
#####
k=1
Op = so.SziOp(N,S,k,full='True')
def getkey(m,n):
key = str((2**m)*(2*n + 1) -1)
return(key)
Coeff = []
for i,vec1 in enumerate(Eigvecs):
for j,vec2 in enumerate(Eigvecs):
co = (getkey(i,j),vec2@BS*t.exval(BS,vec1,Op))
Coeff.append(co)
Coeffs = dict(Coeff)
####
Coeff1 = []
for i1,vec1 in enumerate(Eigvecs) :
for j1,vec2 in enumerate(Eigvecs):
c1 = Coeffs[getkey(i1,j1)]
co1 = t.exval(vec1,vec2,Op)*c1
E1 = (getkey(i1,j1),co1)
Coeff1.append(E1)
Coeffs1 = dict(Coeff1)
#print(Coeffs)
######
times = np.linspace(0.0,1,10)
#times = [0, 1/9, 2/9,3/9,4/9,5/9,6/9,7/9,8/9,1]
#print(times)
timeEx = []
for tim in times:
#print(tim)
start = time.time()
ex = []
for i,eig1 in enumerate(eigs):
for j,eig2 in enumerate(eigs):
C = Coeffs1[getkey(i,j)]
#F = t.timeEv(tim,eig1,eig2,C)
F = C*np.cos(tim*(eig2-eig1))#
ex.append(F)
timeEx.append(sum(ex))
stop = time.time()
print(stop-start)
print(timeEx)
plt.plot(times,timeEx) | [
"tools.Statelist",
"numpy.sqrt",
"Expand.append",
"spinops.SziOp",
"matplotlib.pyplot.plot",
"numpy.asarray",
"numpy.kron",
"numpy.linspace",
"Expand.Expand",
"tools.exval",
"Hamiltonians.nlegHeisenberg.blockH",
"numpy.linalg.eigh",
"numpy.cos",
"time.time",
"spinops.sz"
] | [((306, 316), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (313, 316), True, 'import numpy as np\n'), ((343, 429), 'Hamiltonians.nlegHeisenberg.blockH', 'H.nlegHeisenberg.blockH', (['N', 'S', 'nlegs', 'c'], {'Js': '[1, 1]', 'gamma': '[0.0, 4.0]', 'full': '"""True"""'}), "(N, S, nlegs, c, Js=[1, 1], gamma=[0.0, 4.0], full=\n 'True')\n", (366, 429), True, 'import Hamiltonians as H\n'), ((463, 484), 'numpy.linalg.eigh', 'np.linalg.eigh', (['Hfull'], {}), '(Hfull)\n', (477, 484), True, 'import numpy as np\n'), ((495, 513), 'numpy.asarray', 'np.asarray', (['vecs.T'], {}), '(vecs.T)\n', (505, 513), True, 'import numpy as np\n'), ((643, 660), 'tools.Statelist', 't.Statelist', (['N', 'S'], {}), '(N, S)\n', (654, 660), True, 'import tools as t\n'), ((1225, 1233), 'spinops.sz', 'so.sz', (['S'], {}), '(S)\n', (1230, 1233), True, 'import spinops as so\n'), ((1278, 1308), 'spinops.SziOp', 'so.SziOp', (['N', 'S', 'k'], {'full': '"""True"""'}), "(N, S, k, full='True')\n", (1286, 1308), True, 'import spinops as so\n'), ((1890, 1913), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1)', '(10)'], {}), '(0.0, 1, 10)\n', (1901, 1913), True, 'import numpy as np\n'), ((2414, 2437), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'timeEx'], {}), '(times, timeEx)\n', (2422, 2437), True, 'from matplotlib import pyplot as plt\n'), ((571, 597), 'Expand.Expand', 'ex.Expand', (['vc', 'S', 'N', 'Jcurr'], {}), '(vc, S, N, Jcurr)\n', (580, 597), True, 'import Expand as ex\n'), ((1240, 1262), 'tools.exval', 't.exval', (['BS', 'BS', 'Hfull'], {}), '(BS, BS, Hfull)\n', (1247, 1262), True, 'import tools as t\n'), ((2034, 2045), 'time.time', 'time.time', ([], {}), '()\n', (2043, 2045), False, 'import time\n'), ((2360, 2371), 'time.time', 'time.time', ([], {}), '()\n', (2369, 2371), False, 'import time\n'), ((1051, 1076), 'numpy.kron', 'np.kron', (['B[1]', 'vec[i + 1]'], {}), '(B[1], vec[i + 1])\n', (1058, 1076), True, 'import numpy as np\n'), ((1735, 1758), 'tools.exval', 't.exval', (['vec1', 'vec2', 'Op'], {}), '(vec1, vec2, Op)\n', (1742, 1758), True, 'import tools as t\n'), ((2297, 2309), 'Expand.append', 'ex.append', (['F'], {}), '(F)\n', (2306, 2309), True, 'import Expand as ex\n'), ((1507, 1528), 'tools.exval', 't.exval', (['BS', 'vec1', 'Op'], {}), '(BS, vec1, Op)\n', (1514, 1528), True, 'import tools as t\n'), ((2260, 2287), 'numpy.cos', 'np.cos', (['(tim * (eig2 - eig1))'], {}), '(tim * (eig2 - eig1))\n', (2266, 2287), True, 'import numpy as np\n')] |
import pandas as pd
from pandas import Timestamp
import hillmaker
file_stopdata = '../data/unit_stop_log_Experiment1_Scenario138_Rep17.csv'
scenario_name = 'log_unitocc_test_5'
in_fld_name = 'EnteredTS'
out_fld_name = 'ExitedTS'
cat_fld_name = 'Unit'
start_analysis = '12/12/2015 00:00'
end_analysis = '12/19/2021 00:00'
# Optional inputs
tot_fld_name = 'OBTot'
bin_size_mins = 5
excludecats = ['Obs']
df = pd.read_csv(file_stopdata)
basedate = Timestamp('20150215 00:00:00')
df['EnteredTS'] = df.apply(lambda row:
Timestamp(round((basedate + pd.DateOffset(hours=row['Entered'])).value, -9)), axis=1)
df['ExitedTS'] = df.apply(lambda row:
Timestamp(round((basedate + pd.DateOffset(hours=row['Exited'])).value,-9)), axis=1)
# Filter input data by included included categories
df = df[df[cat_fld_name].isin(excludecats) == False]
hillmaker.make_hills(scenario_name, df, in_fld_name, out_fld_name,
start_analysis, end_analysis, cat_fld_name,
total_str=tot_fld_name, bin_size_minutes=bin_size_mins,
nonstationary_stats=False,
export_path='.',
cat_to_exclude=excludecats, verbose=1)
| [
"pandas.Timestamp",
"hillmaker.make_hills",
"pandas.DateOffset",
"pandas.read_csv"
] | [((412, 438), 'pandas.read_csv', 'pd.read_csv', (['file_stopdata'], {}), '(file_stopdata)\n', (423, 438), True, 'import pandas as pd\n'), ((450, 480), 'pandas.Timestamp', 'Timestamp', (['"""20150215 00:00:00"""'], {}), "('20150215 00:00:00')\n", (459, 480), False, 'from pandas import Timestamp\n'), ((891, 1153), 'hillmaker.make_hills', 'hillmaker.make_hills', (['scenario_name', 'df', 'in_fld_name', 'out_fld_name', 'start_analysis', 'end_analysis', 'cat_fld_name'], {'total_str': 'tot_fld_name', 'bin_size_minutes': 'bin_size_mins', 'nonstationary_stats': '(False)', 'export_path': '"""."""', 'cat_to_exclude': 'excludecats', 'verbose': '(1)'}), "(scenario_name, df, in_fld_name, out_fld_name,\n start_analysis, end_analysis, cat_fld_name, total_str=tot_fld_name,\n bin_size_minutes=bin_size_mins, nonstationary_stats=False, export_path=\n '.', cat_to_exclude=excludecats, verbose=1)\n", (911, 1153), False, 'import hillmaker\n'), ((575, 610), 'pandas.DateOffset', 'pd.DateOffset', ([], {'hours': "row['Entered']"}), "(hours=row['Entered'])\n", (588, 610), True, 'import pandas as pd\n'), ((727, 761), 'pandas.DateOffset', 'pd.DateOffset', ([], {'hours': "row['Exited']"}), "(hours=row['Exited'])\n", (740, 761), True, 'import pandas as pd\n')] |
import pandas as pd
import numpy as np
def augment(data):
data['MalePercent'] = (data['MaleLowerQuartile'] +
data['MaleLowerMiddleQuartile'] + data['MaleUpperMiddleQuartile'] +
data['MaleTopQuartile']) * .25
data['FemalePercent'] = (data['FemaleLowerQuartile'] + data['FemaleLowerMiddleQuartile'] +
data['FemaleUpperMiddleQuartile'] + data['FemaleTopQuartile']
) * .25
data['WorkforceGenderSkew'] = data['MalePercent'] - data['FemalePercent']
data['PercMaleWorkforceInTopQuartile'] = data['MaleTopQuartile'] / data['MalePercent'] * .25
data['PercMaleWorkforceInUpperMiddleQuartile'] = data['MaleUpperMiddleQuartile'] / data['MalePercent'] * .25
data['PercMaleWorkforceInLowerMiddleQuartile'] = data['MaleLowerMiddleQuartile'] / data['MalePercent'] * .25
data['PercMaleWorkforceInLowerQuartile'] = data['MaleLowerQuartile'] / data['MalePercent'] * .25
data['PercFemaleWorkforceInTopQuartile'] = data['FemaleTopQuartile'] / data['FemalePercent'] * .25
data['PercFemaleWorkforceInUpperMiddleQuartile'] = data['FemaleUpperMiddleQuartile'] / data['FemalePercent'] * .25
data['PercFemaleWorkforceInLowerMiddleQuartile'] = data['FemaleLowerMiddleQuartile'] / data['FemalePercent'] * .25
data['PercFemaleWorkforceInLowerQuartile'] = data['FemaleLowerQuartile'] / data['FemalePercent'] * .25
data['RepresentationInTopQuartileSkew'] = data['PercMaleWorkforceInTopQuartile'] - data[
'PercFemaleWorkforceInTopQuartile']
data['RepresentationInUpperMiddleQuartileSkew'] = data['PercMaleWorkforceInUpperMiddleQuartile'] - data[
'PercFemaleWorkforceInUpperMiddleQuartile']
data['RepresentationInLowerMiddleQuartileSkew'] = data['PercMaleWorkforceInLowerMiddleQuartile'] - data[
'PercFemaleWorkforceInLowerMiddleQuartile']
data['RepresentationInLowerQuartileSkew'] = data['PercMaleWorkforceInLowerQuartile'] - data[
'PercFemaleWorkforceInLowerQuartile']
data['BonusGenderSkew'] = data['MaleBonusPercent'] - data['FemaleBonusPercent']
return data
def main():
df = pd.read_csv('data/ukgov-gpg-full-section-split.csv')
df = augment(df)
df.to_csv('data/ukgov-gpg-all-clean-with-features.csv', index=False)
if __name__ == "__main__":
main()
| [
"pandas.read_csv"
] | [((2170, 2222), 'pandas.read_csv', 'pd.read_csv', (['"""data/ukgov-gpg-full-section-split.csv"""'], {}), "('data/ukgov-gpg-full-section-split.csv')\n", (2181, 2222), True, 'import pandas as pd\n')] |
#!/usr/bin/env python
import os
from typing import List, Union
_PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def _remove_files(files: Union[List[str], str]) -> None:
"""
Removes the list of files provided.
:param files: list of filepath to remove
:type files: Union[List[str], str]
"""
if not isinstance(files, list):
files = [files]
for filepath in files:
os.remove(os.path.join(_PROJECT_DIRECTORY, filepath))
if __name__ == "__main__":
if "{{ cookiecutter.create_author_file }}" != "y":
_remove_files("AUTHORS.md")
if "{{ cookiecutter.use_docker }}" != "y":
_remove_files([
".dockerignore",
"docker-compose.yml",
"Dockerfile",
])
if "Not open source" == "{{ cookiecutter.open_source_license }}":
_remove_files("LICENSE")
| [
"os.path.realpath",
"os.path.join"
] | [((86, 118), 'os.path.realpath', 'os.path.realpath', (['os.path.curdir'], {}), '(os.path.curdir)\n', (102, 118), False, 'import os\n'), ((424, 466), 'os.path.join', 'os.path.join', (['_PROJECT_DIRECTORY', 'filepath'], {}), '(_PROJECT_DIRECTORY, filepath)\n', (436, 466), False, 'import os\n')] |
import json
import channels.layers
from asgiref.sync import async_to_sync
from django.conf import settings
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.views.generic import TemplateView, CreateView, UpdateView, RedirectView
from .models import *
from .forms import *
def AccountView(request):
context = {
'accountuser': request.user,
}
return render(request, 'user/profile.html', context=context)
class ProfileChangeView(UpdateView):
form_class = ProfileChangeForm
template_name = 'user/profile-change.html'
def get_object(self, queryset=None):
return self.request.user
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({
'accountuser': self.request.user,
})
return context
def get_success_url(self):
url = reverse('profile')
return url
| [
"django.shortcuts.render",
"django.urls.reverse"
] | [((526, 579), 'django.shortcuts.render', 'render', (['request', '"""user/profile.html"""'], {'context': 'context'}), "(request, 'user/profile.html', context=context)\n", (532, 579), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1024, 1042), 'django.urls.reverse', 'reverse', (['"""profile"""'], {}), "('profile')\n", (1031, 1042), False, 'from django.urls import reverse, reverse_lazy\n')] |
# /usr/bin/python3
import logging
import sched
import signal
import sys
import time
from functools import partial
import watchdog.events
import watchdog.observers
from watchdog.observers.polling import PollingObserver as PollingObserver
from GlobusTransfer import GlobusTransfer
from .args import Args
from .handler import Handler
from .log import logger, set_debug, set_gt_debug
def main(argv):
args = Args(sys.argv[1:])
# now that logging is setup log our settings
args.log_settings()
src_path = args.path
# Did we ask for debug?
if args.debug:
set_debug()
if args.globus_debug:
set_gt_debug()
# using globus, init to prompt for endpoiont activation etc
GlobusTransfer(args.source, args.destination, args.destination_dir, src_path)
event_handler = Handler(args)
if args.prepopulate:
event_handler.prepopulate()
# observer = watchdog.observers.Observer()
observer = PollingObserver()
observer.schedule(event_handler, path=src_path, recursive=True)
# setup signal handler
def dump_status(event_handler, signalNumber, frame, details=False):
"""Dump the Handler() status when USR1 is recived."""
event_handler.status(details=details)
signal.signal(signal.SIGUSR1, partial(dump_status, event_handler))
signal.signal(signal.SIGUSR2, partial(dump_status, event_handler, details=True))
observer.start()
s = sched.scheduler(time.time, time.sleep)
logger.info("Starting Main Event Loop")
try:
while True:
logger.info(
f"Starting iteration {event_handler.iteration} will sleep {args.sleep} seconds"
)
s.enter(
args.sleep,
1,
event_handler.new_iteration,
argument=(args.dwell_time,),
)
s.run()
except KeyboardInterrupt:
observer.stop()
observer.join()
| [
"sched.scheduler",
"GlobusTransfer.GlobusTransfer",
"functools.partial",
"watchdog.observers.polling.PollingObserver"
] | [((720, 797), 'GlobusTransfer.GlobusTransfer', 'GlobusTransfer', (['args.source', 'args.destination', 'args.destination_dir', 'src_path'], {}), '(args.source, args.destination, args.destination_dir, src_path)\n', (734, 797), False, 'from GlobusTransfer import GlobusTransfer\n'), ((958, 975), 'watchdog.observers.polling.PollingObserver', 'PollingObserver', ([], {}), '()\n', (973, 975), True, 'from watchdog.observers.polling import PollingObserver as PollingObserver\n'), ((1439, 1477), 'sched.scheduler', 'sched.scheduler', (['time.time', 'time.sleep'], {}), '(time.time, time.sleep)\n', (1454, 1477), False, 'import sched\n'), ((1287, 1322), 'functools.partial', 'partial', (['dump_status', 'event_handler'], {}), '(dump_status, event_handler)\n', (1294, 1322), False, 'from functools import partial\n'), ((1358, 1407), 'functools.partial', 'partial', (['dump_status', 'event_handler'], {'details': '(True)'}), '(dump_status, event_handler, details=True)\n', (1365, 1407), False, 'from functools import partial\n')] |
import argparse
import os
import sys
import torch
from torch import nn, optim
from torch.optim import optimizer
from torchvision import datasets, models, transforms
parser = argparse.ArgumentParser(description="Trains a neural network")
parser.add_argument('data_dir', metavar='dir', type=str,
help="Directory to the dataset to be trained on")
parser.add_argument("--save_dir", dest="save_dir", default=".",
type=str, help="Directory to save checkpoints")
parser.add_argument("--arg", dest="arch", default="vgg16",
type=str, help="Pretrained architecture to use")
parser.add_argument("--learning_rate", dest="learning_rate",
default=0.001, type=float, help="Learning rate to use")
parser.add_argument("--hidden_units", dest="hidden_units",
type=int, default=512, help="Number of hidden units to use")
parser.add_argument("--epochs", dest="epochs", type=int,
default=5, help="Number of epochs to train model")
parser.add_argument("--gpu", dest="gpu", action="store_true", help="Use GPU?")
args = parser.parse_args()
data_dir = args.data_dir
save_dir = args.save_dir
arch = args.arch
learning_rate = args.learning_rate
hidden_units = args.hidden_units
epochs = args.epochs
gpu = args.gpu
device = torch.device("cuda" if gpu and torch.cuda.is_available() else "cpu")
def build_model(arch, hidden_units):
if arch == "alexnet":
model = models.alexnet(pretrained=True)
in_features = model.classifier[1].in_features
classifier_name = "classifier"
elif arch == "vgg11":
model = models.vgg11(pretrained=True)
in_features = model.classifier[0].in_features
classifier_name = "classifier"
elif arch == "vgg13":
model = models.vgg13(pretrained=True)
in_features = model.classifier[0].in_features
classifier_name = "classifier"
elif arch == "vgg16":
model = models.vgg16(pretrained=True)
in_features = model.classifier[0].in_features
classifier_name = "classifier"
elif arch == "vgg19":
model = models.vgg19(pretrained=True)
in_features = model.classifier[0].in_features
classifier_name = "classifier"
elif arch == "resnet18":
model = models.resnet18(pretrained=True)
in_features = model.fc.in_features
classifier_name = "fc"
elif arch == "resnet34":
model = models.resnet34(pretrained=True)
in_features = model.fc.in_features
classifier_name = "fc"
elif arch == "resnet50":
model = models.resnet50(pretrained=True)
in_features = model.fc.in_features
classifier_name = "fc"
elif arch == "resnet101":
model = models.resnet101(pretrained=True)
in_features = model.fc.in_features
classifier_name = "fc"
elif arch == "resnet152":
model = models.resnet152(pretrained=True)
in_features = model.fc.in_features
classifier_name = "fc"
elif arch == "densenet121":
model = models.densenet121(pretrained=True)
in_features = model.classifier.in_features
classifier_name = "classifier"
elif arch == "densenet169":
model = models.densenet169(pretrained=True)
in_features = model.classifier.in_features
classifier_name = "classifier"
elif arch == "densenet201":
model = models.densenet201(pretrained=True)
in_features = model.classifier.in_features
classifier_name = "classifier"
elif arch == "densenet161":
model = models.densenet161(pretrained=True)
in_features = model.classifier.in_features
classifier_name = "classifier"
else:
print(f"Error: Unknown architecture: {arch}")
sys.exit()
# Freeze parameters
for param in model.parameters():
param.requires_grad = False
# Define classifier
classifier = nn.Sequential(
nn.Linear(in_features, hidden_units),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(hidden_units, hidden_units),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(hidden_units, 102),
nn.LogSoftmax(dim=1)
)
if classifier_name == "classifier":
model.classifier = classifier
optimizer = optim.Adam(model.classifier.parameters(), lr=learning_rate)
elif classifier_name == "fc":
model.fc = classifier
optimizer = optim.Adam(model.fc.parameters(), lr=learning_rate)
return model, optimizer
def train_model(model, epochs, dataloaders, optimizer, criterion):
steps = 0
running_loss = 0
print_every = 20
model.to(device)
for epoch in range(epochs):
for images, labels in dataloaders["train"]:
steps += 1
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
logps = model(images)
loss = criterion(logps, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % print_every == 0:
model.eval()
test_loss = 0
accuracy = 0
for images, labels in dataloaders["valid"]:
images, labels = images.to(device), labels.to(device)
logps = model(images)
loss = criterion(logps, labels)
test_loss += loss.item()
ps = torch.exp(logps)
_, top_class = ps.topk(1, dim=1)
equality = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equality.type(torch.FloatTensor)).item()
print(f"Epoch: {epoch+1}/{epochs} ",
f"Training Loss: {running_loss/print_every:.3f} ",
f"Validation Loss: {test_loss/len(dataloaders['valid']):.3f} ",
f"Validation Accuracy: {accuracy/len(dataloaders['valid']):.3f}")
running_loss = 0
model.train()
def generate_data(dir):
train_dir = os.path.join(dir, "train")
valid_dir = os.path.join(dir, "valid")
test_dir = os.path.join(dir, "test")
data_transforms = {
"train": transforms.Compose([
transforms.RandomRotation(30),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
]),
"valid": transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
]),
"test": transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
}
# Load the datasets with ImageFolder
image_datasets = {
"train": datasets.ImageFolder(train_dir, transform=data_transforms["train"]),
"valid": datasets.ImageFolder(valid_dir, transform=data_transforms["valid"]),
"test": datasets.ImageFolder(test_dir, transform=data_transforms["test"])
}
# Using the image datasets and the trainforms, define the dataloaders
dataloaders = {
"train": torch.utils.data.DataLoader(image_datasets["train"], batch_size=64, shuffle=True),
"valid": torch.utils.data.DataLoader(image_datasets["valid"], batch_size=64, shuffle=True),
"test": torch.utils.data.DataLoader(image_datasets["test"], batch_size=64, shuffle=True)
}
return data_transforms, image_datasets, dataloaders
def save_model(save_dir, model, image_datasets):
model.class_to_idx = image_datasets["train"].class_to_idx
checkpoint = {
"input_size": 25088,
"output_size": 102,
"classifier": model.classifier,
"state_dict": model.state_dict(),
"class_to_idx": model.class_to_idx,
"arch": arch
# "optimizer": optimizer.state_dict(),
# "epochs": epochs,
}
torch.save(checkpoint, os.path.join(save_dir, "checkpoint.pth"))
if __name__ == "__main__":
print("--------LOADING DATA--------")
_, image_datasets, dataloaders = generate_data(data_dir)
print("Data loaded successfully")
print("--------BUILDIING MODEL--------")
model, optimizer = build_model(arch, hidden_units)
print("Model successfully built")
criterion = nn.NLLLoss()
print("--------TRAINING MODEL--------")
print(f"Training model with {epochs} epochs")
train_model(model, epochs, dataloaders, optimizer, criterion)
print("Model successfully trained")
print("--------SAVING MODEL--------")
save_model(save_dir, model, image_datasets)
print(f"Model saved to {os.path.join(save_dir, 'checkpoint.pth')}")
| [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torchvision.models.vgg19",
"torchvision.models.densenet161",
"torch.optim.optimizer.step",
"torchvision.models.resnet18",
"torch.exp",
"torch.cuda.is_available",
"torchvision.models.densenet121",
"sys.exit",
"torchvision.models.vgg11",
"argparse.ArgumentPa... | [((176, 238), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Trains a neural network"""'}), "(description='Trains a neural network')\n", (199, 238), False, 'import argparse\n'), ((6130, 6156), 'os.path.join', 'os.path.join', (['dir', '"""train"""'], {}), "(dir, 'train')\n", (6142, 6156), False, 'import os\n'), ((6173, 6199), 'os.path.join', 'os.path.join', (['dir', '"""valid"""'], {}), "(dir, 'valid')\n", (6185, 6199), False, 'import os\n'), ((6215, 6240), 'os.path.join', 'os.path.join', (['dir', '"""test"""'], {}), "(dir, 'test')\n", (6227, 6240), False, 'import os\n'), ((8742, 8754), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (8752, 8754), False, 'from torch import nn, optim\n'), ((1469, 1500), 'torchvision.models.alexnet', 'models.alexnet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1483, 1500), False, 'from torchvision import datasets, models, transforms\n'), ((3960, 3996), 'torch.nn.Linear', 'nn.Linear', (['in_features', 'hidden_units'], {}), '(in_features, hidden_units)\n', (3969, 3996), False, 'from torch import nn, optim\n'), ((4006, 4015), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4013, 4015), False, 'from torch import nn, optim\n'), ((4025, 4042), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)'}), '(p=0.2)\n', (4035, 4042), False, 'from torch import nn, optim\n'), ((4052, 4089), 'torch.nn.Linear', 'nn.Linear', (['hidden_units', 'hidden_units'], {}), '(hidden_units, hidden_units)\n', (4061, 4089), False, 'from torch import nn, optim\n'), ((4099, 4108), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4106, 4108), False, 'from torch import nn, optim\n'), ((4118, 4135), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)'}), '(p=0.2)\n', (4128, 4135), False, 'from torch import nn, optim\n'), ((4145, 4173), 'torch.nn.Linear', 'nn.Linear', (['hidden_units', '(102)'], {}), '(hidden_units, 102)\n', (4154, 4173), False, 'from torch import nn, optim\n'), ((4183, 4203), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', ([], {'dim': '(1)'}), '(dim=1)\n', (4196, 4203), False, 'from torch import nn, optim\n'), ((7231, 7298), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['train_dir'], {'transform': "data_transforms['train']"}), "(train_dir, transform=data_transforms['train'])\n", (7251, 7298), False, 'from torchvision import datasets, models, transforms\n'), ((7317, 7384), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['valid_dir'], {'transform': "data_transforms['valid']"}), "(valid_dir, transform=data_transforms['valid'])\n", (7337, 7384), False, 'from torchvision import datasets, models, transforms\n'), ((7402, 7467), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['test_dir'], {'transform': "data_transforms['test']"}), "(test_dir, transform=data_transforms['test'])\n", (7422, 7467), False, 'from torchvision import datasets, models, transforms\n'), ((7586, 7672), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (["image_datasets['train']"], {'batch_size': '(64)', 'shuffle': '(True)'}), "(image_datasets['train'], batch_size=64, shuffle\n =True)\n", (7613, 7672), False, 'import torch\n'), ((7686, 7772), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (["image_datasets['valid']"], {'batch_size': '(64)', 'shuffle': '(True)'}), "(image_datasets['valid'], batch_size=64, shuffle\n =True)\n", (7713, 7772), False, 'import torch\n'), ((7785, 7870), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (["image_datasets['test']"], {'batch_size': '(64)', 'shuffle': '(True)'}), "(image_datasets['test'], batch_size=64, shuffle=True\n )\n", (7812, 7870), False, 'import torch\n'), ((8374, 8414), 'os.path.join', 'os.path.join', (['save_dir', '"""checkpoint.pth"""'], {}), "(save_dir, 'checkpoint.pth')\n", (8386, 8414), False, 'import os\n'), ((1350, 1375), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1373, 1375), False, 'import torch\n'), ((1636, 1665), 'torchvision.models.vgg11', 'models.vgg11', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1648, 1665), False, 'from torchvision import datasets, models, transforms\n'), ((4866, 4887), 'torch.optim.optimizer.zero_grad', 'optimizer.zero_grad', ([], {}), '()\n', (4885, 4887), False, 'from torch.optim import optimizer\n'), ((5007, 5023), 'torch.optim.optimizer.step', 'optimizer.step', ([], {}), '()\n', (5021, 5023), False, 'from torch.optim import optimizer\n'), ((1801, 1830), 'torchvision.models.vgg13', 'models.vgg13', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1813, 1830), False, 'from torchvision import datasets, models, transforms\n'), ((6315, 6344), 'torchvision.transforms.RandomRotation', 'transforms.RandomRotation', (['(30)'], {}), '(30)\n', (6340, 6344), False, 'from torchvision import datasets, models, transforms\n'), ((6358, 6391), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['(224)'], {}), '(224)\n', (6386, 6391), False, 'from torchvision import datasets, models, transforms\n'), ((6405, 6438), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (6436, 6438), False, 'from torchvision import datasets, models, transforms\n'), ((6452, 6473), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (6471, 6473), False, 'from torchvision import datasets, models, transforms\n'), ((6487, 6553), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (6507, 6553), False, 'from torchvision import datasets, models, transforms\n'), ((6649, 6671), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (6666, 6671), False, 'from torchvision import datasets, models, transforms\n'), ((6685, 6711), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (6706, 6711), False, 'from torchvision import datasets, models, transforms\n'), ((6725, 6746), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (6744, 6746), False, 'from torchvision import datasets, models, transforms\n'), ((6760, 6826), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (6780, 6826), False, 'from torchvision import datasets, models, transforms\n'), ((6921, 6943), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (6938, 6943), False, 'from torchvision import datasets, models, transforms\n'), ((6957, 6983), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (6978, 6983), False, 'from torchvision import datasets, models, transforms\n'), ((6997, 7018), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (7016, 7018), False, 'from torchvision import datasets, models, transforms\n'), ((7032, 7098), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (7052, 7098), False, 'from torchvision import datasets, models, transforms\n'), ((9075, 9115), 'os.path.join', 'os.path.join', (['save_dir', '"""checkpoint.pth"""'], {}), "(save_dir, 'checkpoint.pth')\n", (9087, 9115), False, 'import os\n'), ((1966, 1995), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1978, 1995), False, 'from torchvision import datasets, models, transforms\n'), ((5496, 5512), 'torch.exp', 'torch.exp', (['logps'], {}), '(logps)\n', (5505, 5512), False, 'import torch\n'), ((2131, 2160), 'torchvision.models.vgg19', 'models.vgg19', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2143, 2160), False, 'from torchvision import datasets, models, transforms\n'), ((2299, 2331), 'torchvision.models.resnet18', 'models.resnet18', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2314, 2331), False, 'from torchvision import datasets, models, transforms\n'), ((2451, 2483), 'torchvision.models.resnet34', 'models.resnet34', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2466, 2483), False, 'from torchvision import datasets, models, transforms\n'), ((2603, 2635), 'torchvision.models.resnet50', 'models.resnet50', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2618, 2635), False, 'from torchvision import datasets, models, transforms\n'), ((2756, 2789), 'torchvision.models.resnet101', 'models.resnet101', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2772, 2789), False, 'from torchvision import datasets, models, transforms\n'), ((2910, 2943), 'torchvision.models.resnet152', 'models.resnet152', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (2926, 2943), False, 'from torchvision import datasets, models, transforms\n'), ((3066, 3101), 'torchvision.models.densenet121', 'models.densenet121', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (3084, 3101), False, 'from torchvision import datasets, models, transforms\n'), ((3240, 3275), 'torchvision.models.densenet169', 'models.densenet169', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (3258, 3275), False, 'from torchvision import datasets, models, transforms\n'), ((3414, 3449), 'torchvision.models.densenet201', 'models.densenet201', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (3432, 3449), False, 'from torchvision import datasets, models, transforms\n'), ((3588, 3623), 'torchvision.models.densenet161', 'models.densenet161', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (3606, 3623), False, 'from torchvision import datasets, models, transforms\n'), ((3786, 3796), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3794, 3796), False, 'import sys\n')] |
# Ejercicio 04
import time
import matplotlib.pyplot as plt
# Algoritmo
def binarySearch(numbers, n):
numElements = len(numbers)
if(numElements == 1):
return (n == numbers[0])
mitad = numElements // 2
if(numbers[mitad] == n):
return True
elif (n < numbers[mitad]):
return binarySearch(numbers[0:mitad],n)
else:
return binarySearch(numbers[mitad:len(numbers)],n)
# Retorna lo que tardo el algoritmo
def getTimeBinarySearch(numbers, n):
tic = time.perf_counter()
binarySearch(numbers, n)
toc = time.perf_counter()
return (toc - tic)
def createGraph(max, sal):
# numbers = list(range(max+1,0,-1)) # Solo creamos una lista, para todos los casos
x = [] # datos para el grafico, en el eje x
y = [] # Datos para el grafico en el eje Y
for i in range(0,max,sal): # recorremos con que datos trabajaremos
x.append(i+1)
lista = list(range(0, (i+1)*2,2))
time = round(getTimeBinarySearch(lista,3),4) # Siempre buscamos el numero 3
y.append(time)
print(x) # depurar
print(y) # depurar
fig, ax = plt.subplots() # Create a figure containing a single axes.
ax.plot(x, y) # Plot some data on the axes.
plt.show()
def main(numrArreglo=50000, numSalto=50):
createGraph(numrArreglo, numSalto) # recomendacion
__main__ = main() | [
"matplotlib.pyplot.subplots",
"time.perf_counter",
"matplotlib.pyplot.show"
] | [((515, 534), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (532, 534), False, 'import time\n'), ((574, 593), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (591, 593), False, 'import time\n'), ((1146, 1160), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1158, 1160), True, 'import matplotlib.pyplot as plt\n'), ((1259, 1269), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1267, 1269), True, 'import matplotlib.pyplot as plt\n')] |
# Generated by Django 2.2.4 on 2020-06-29 10:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import jsonfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='OTPStatic',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token', models.CharField(max_length=16)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='otp_statics', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='OTPDevice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(blank=True, max_length=80)),
('otp_type', models.CharField(choices=[('hotp', 'HOTP'), ('totp', 'TOTP'), ('webauthn', 'WebAuthn')], max_length=24)),
('destination_type', models.CharField(choices=[('sms', 'SMS'), ('call', 'Call'), ('email', 'Email'), ('device', 'Generator device')], max_length=24)),
('destination_value', models.CharField(blank=True, max_length=80)),
('data', jsonfield.fields.JSONField(blank=True, default=dict)),
('counter', models.BigIntegerField(default=0, help_text='The next counter value to expect.')),
('last_use_at', models.DateTimeField(blank=True, null=True)),
('is_active', models.BooleanField(default=False)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='otp_devices', to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.BigIntegerField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((271, 328), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (302, 328), False, 'from django.db import migrations, models\n'), ((462, 555), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (478, 555), False, 'from django.db import migrations, models\n'), ((580, 611), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(16)'}), '(max_length=16)\n', (596, 611), False, 'from django.db import migrations, models\n'), ((639, 763), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""otp_statics"""', 'to': 'settings.AUTH_USER_MODEL'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='otp_statics', to=settings.AUTH_USER_MODEL)\n", (656, 763), False, 'from django.db import migrations, models\n'), ((893, 986), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (909, 986), False, 'from django.db import migrations, models\n'), ((1011, 1054), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)'}), '(blank=True, max_length=80)\n', (1027, 1054), False, 'from django.db import migrations, models\n'), ((1086, 1193), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('hotp', 'HOTP'), ('totp', 'TOTP'), ('webauthn', 'WebAuthn')]", 'max_length': '(24)'}), "(choices=[('hotp', 'HOTP'), ('totp', 'TOTP'), ('webauthn',\n 'WebAuthn')], max_length=24)\n", (1102, 1193), False, 'from django.db import migrations, models\n'), ((1229, 1360), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('sms', 'SMS'), ('call', 'Call'), ('email', 'Email'), ('device',\n 'Generator device')]", 'max_length': '(24)'}), "(choices=[('sms', 'SMS'), ('call', 'Call'), ('email',\n 'Email'), ('device', 'Generator device')], max_length=24)\n", (1245, 1360), False, 'from django.db import migrations, models\n'), ((1397, 1440), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(80)'}), '(blank=True, max_length=80)\n', (1413, 1440), False, 'from django.db import migrations, models\n'), ((1551, 1636), 'django.db.models.BigIntegerField', 'models.BigIntegerField', ([], {'default': '(0)', 'help_text': '"""The next counter value to expect."""'}), "(default=0, help_text='The next counter value to expect.'\n )\n", (1573, 1636), False, 'from django.db import migrations, models\n'), ((1666, 1709), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1686, 1709), False, 'from django.db import migrations, models\n'), ((1742, 1776), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1761, 1776), False, 'from django.db import migrations, models\n'), ((1810, 1845), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (1830, 1845), False, 'from django.db import migrations, models\n'), ((1879, 1918), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (1899, 1918), False, 'from django.db import migrations, models\n'), ((1946, 2070), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""otp_devices"""', 'to': 'settings.AUTH_USER_MODEL'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='otp_devices', to=settings.AUTH_USER_MODEL)\n", (1963, 2070), False, 'from django.db import migrations, models\n')] |
from os import getenv
from dataclasses import dataclass
from collections import ChainMap
from dotenv import load_dotenv
from bot.structs import CaseInsensitiveDict
load_dotenv()
MY_NAME = "LPUBeltbot"
MY_REDDIT_PW = getenv("BELTBOT_REDDIT_PW")
MY_REDDIT_CLIENT_ID = getenv("BELTBOT_REDDIT_CID")
MY_REDDIT_SECRET = getenv("BELTBOT_REDDIT_KEY")
USER_AGENT = "LPUBeltbot_v0.1.1"
TOKEN = getenv("BELTBOT_TOKEN")
SUBREDDIT = "lockpicking"
STANDARD_BELTS = CaseInsensitiveDict(
**{
"white": {
"name": "White Belt",
"flair_text": "White Belt Picker :WhiteBelt:",
"css_class": "whitebelt",
},
"yellow": {
"name": "Yellow Belt",
"flair_text": "Yellow Belt Picker :YellowBelt:",
"css_class": "yellowbelt",
},
"orange": {
"name": "Orange Belt",
"flair_text": "Orange Belt Picker :OrangeBelt:",
"css_class": "orangebelt",
},
"green": {
"name": "Green Belt",
"flair_text": "Green Belt Picker :GreenBelt:",
"css_class": "greenbelt",
},
"blue": {
"name": "Blue Belt",
"flair_text": "Blue Belt Picker :BlueBelt:",
"css_class": "bluebelt",
},
"purple": {
"name": "Purple Belt",
"flair_text": "Purple Belt Picker :PurpleBelt:",
"css_class": "purplebelt",
},
"brown": {
"name": "Brown Belt",
"flair_text": "Brown Belt Picker :BrownBelt:",
"css_class": "brownbelt",
},
"red": {
"name": "<NAME>",
"flair_text": "Red Belt Picker :RedBelt:",
"css_class": "redbelt",
},
"black": {
"name": "<NAME>",
"flair_text": "Black Belt Picker :BlackBelt:",
"css_class": "blackbelt",
},
}
)
ADDON_BELTS = CaseInsensitiveDict(
**{
"1st": {"name": "1st Dan", "flair_text": "Black Belt 1st Dan :BlackBelt:", "css_class":"1stDan"},
"2nd": {"name": "<NAME>", "flair_text": "Black Belt 2nd Dan :BlackBelt:", "css_class": "2ndDan"},
"3rd": {"name": "3rd Dan", "flair_text": "Black Belt 3rd Dan :BlackBelt:", "css_class": "3rdDan"},
"4th": {"name": "4th Dan", "flair_text": "Black Belt 4th Dan :BlackBelt:", "css_class": "4thDan"},
"5th": {"name": "<NAME>", "flair_text": "Black Belt 5th Dan :BlackBelt:", "css_class": "5thDan"},
"6th": {"name": "6th Dan", "flair_text": "Black Belt 6th Dan :BlackBelt:", "css_class": "6thDan"},
"7th": {"name": "<NAME>", "flair_text": "Black Belt 7th Dan :BlackBelt:", "css_class": "7thDan"},
"8th": {"name": "8th Dan", "flair_text": "Black Belt 8th Dan :BlackBelt:", "css_class": "8thDan"},
"9th": {"name": "9th Dan", "flair_text": "Black Belt 9th Dan :BlackBelt:", "css_class": "9thDan"},
"10th": {"name": "10th Dan", "flair_text": "Black Belt 10th Dan :BlackBelt:", "css_class": "10thDan"},
"11th": {"name": "11th Dan", "flair_text": "Black Belt 11th Dan :BlackBelt:", "css_class": "11thDan"},
"12th": {"name": "12th Dan", "flair_text": "Black Belt 12th Dan :BlackBelt:", "css_class": "12thDan"},
"13th": {"name": "13th Dan", "flair_text": "Black Belt 13th Dan :BlackBelt:", "css_class": "13thDan"},
"14th": {"name": "14th Dan", "flair_text": "Black Belt 14th Dan :BlackBelt:", "css_class": "14thDan"},
"15th": {"name": "15th Dan", "flair_text": "Black Belt 15th Dan :BlackBelt:", "css_class": "15thDan"},
"16th": {"name": "16th Dan", "flair_text": "Black Belt 16th Dan :BlackBelt:", "css_class": "16thDan"},
"17th": {"name": "17th Dan", "flair_text": "Black Belt 17th Dan :BlackBelt:", "css_class": "17thDan"},
"18th": {"name": "18th Dan", "flair_text": "Black Belt 18th Dan :BlackBelt:", "css_class": "18thDan"},
"19th": {"name": "19th Dan", "flair_text": "Black Belt 19th Dan :BlackBelt:", "css_class": "19thDan"},
"20th": {"name": "20th Dan", "flair_text": "Black Belt 20th Dan :BlackBelt:", "css_class": "20thDan"},
}
)
NON_BELTS = CaseInsensitiveDict(
**{
"HoF": {"name": "<NAME>ame", "flair_text": None, "css_class": None},
}
)
ALL_BELTS = ChainMap(STANDARD_BELTS, ADDON_BELTS, NON_BELTS)
BELT_ROLE_NAMES = [v["name"] for v in reversed(list(ALL_BELTS.values()))]
STANDARD_BELT_NAMES = [v["name"] for v in reversed(list(STANDARD_BELTS.values()))]
ADDON_BELT_NAMES = [v["name"] for v in reversed(list(ADDON_BELTS.values()))]
NON_BELT_NAMES = [v["name"] for v in reversed(list(ALL_BELTS.values()))]
HUMAN_READABLE_BELTS = ", ".join([belt for belt in reversed(list(ALL_BELTS))])
| [
"bot.structs.CaseInsensitiveDict",
"collections.ChainMap",
"os.getenv",
"dotenv.load_dotenv"
] | [((168, 181), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (179, 181), False, 'from dotenv import load_dotenv\n'), ((223, 250), 'os.getenv', 'getenv', (['"""BELTBOT_REDDIT_PW"""'], {}), "('BELTBOT_REDDIT_PW')\n", (229, 250), False, 'from os import getenv\n'), ((274, 302), 'os.getenv', 'getenv', (['"""BELTBOT_REDDIT_CID"""'], {}), "('BELTBOT_REDDIT_CID')\n", (280, 302), False, 'from os import getenv\n'), ((323, 351), 'os.getenv', 'getenv', (['"""BELTBOT_REDDIT_KEY"""'], {}), "('BELTBOT_REDDIT_KEY')\n", (329, 351), False, 'from os import getenv\n'), ((395, 418), 'os.getenv', 'getenv', (['"""BELTBOT_TOKEN"""'], {}), "('BELTBOT_TOKEN')\n", (401, 418), False, 'from os import getenv\n'), ((464, 1494), 'bot.structs.CaseInsensitiveDict', 'CaseInsensitiveDict', ([], {}), "(**{'white': {'name': 'White Belt', 'flair_text':\n 'White Belt Picker :WhiteBelt:', 'css_class': 'whitebelt'}, 'yellow': {\n 'name': 'Yellow Belt', 'flair_text': 'Yellow Belt Picker :YellowBelt:',\n 'css_class': 'yellowbelt'}, 'orange': {'name': 'Orange Belt',\n 'flair_text': 'Orange Belt Picker :OrangeBelt:', 'css_class':\n 'orangebelt'}, 'green': {'name': 'Green Belt', 'flair_text':\n 'Green Belt Picker :GreenBelt:', 'css_class': 'greenbelt'}, 'blue': {\n 'name': 'Blue Belt', 'flair_text': 'Blue Belt Picker :BlueBelt:',\n 'css_class': 'bluebelt'}, 'purple': {'name': 'Purple Belt',\n 'flair_text': 'Purple Belt Picker :PurpleBelt:', 'css_class':\n 'purplebelt'}, 'brown': {'name': 'Brown Belt', 'flair_text':\n 'Brown Belt Picker :BrownBelt:', 'css_class': 'brownbelt'}, 'red': {\n 'name': '<NAME>', 'flair_text': 'Red Belt Picker :RedBelt:',\n 'css_class': 'redbelt'}, 'black': {'name': '<NAME>', 'flair_text':\n 'Black Belt Picker :BlackBelt:', 'css_class': 'blackbelt'}})\n", (483, 1494), False, 'from bot.structs import CaseInsensitiveDict\n'), ((1959, 4133), 'bot.structs.CaseInsensitiveDict', 'CaseInsensitiveDict', ([], {}), "(**{'1st': {'name': '1st Dan', 'flair_text':\n 'Black Belt 1st Dan :BlackBelt:', 'css_class': '1stDan'}, '2nd': {\n 'name': '<NAME>', 'flair_text': 'Black Belt 2nd Dan :BlackBelt:',\n 'css_class': '2ndDan'}, '3rd': {'name': '3rd Dan', 'flair_text':\n 'Black Belt 3rd Dan :BlackBelt:', 'css_class': '3rdDan'}, '4th': {\n 'name': '4th Dan', 'flair_text': 'Black Belt 4th Dan :BlackBelt:',\n 'css_class': '4thDan'}, '5th': {'name': '<NAME>', 'flair_text':\n 'Black Belt 5th Dan :BlackBelt:', 'css_class': '5thDan'}, '6th': {\n 'name': '6th Dan', 'flair_text': 'Black Belt 6th Dan :BlackBelt:',\n 'css_class': '6thDan'}, '7th': {'name': '<NAME>', 'flair_text':\n 'Black Belt 7th Dan :BlackBelt:', 'css_class': '7thDan'}, '8th': {\n 'name': '8th Dan', 'flair_text': 'Black Belt 8th Dan :BlackBelt:',\n 'css_class': '8thDan'}, '9th': {'name': '9th Dan', 'flair_text':\n 'Black Belt 9th Dan :BlackBelt:', 'css_class': '9thDan'}, '10th': {\n 'name': '10th Dan', 'flair_text': 'Black Belt 10th Dan :BlackBelt:',\n 'css_class': '10thDan'}, '11th': {'name': '11th Dan', 'flair_text':\n 'Black Belt 11th Dan :BlackBelt:', 'css_class': '11thDan'}, '12th': {\n 'name': '12th Dan', 'flair_text': 'Black Belt 12th Dan :BlackBelt:',\n 'css_class': '12thDan'}, '13th': {'name': '13th Dan', 'flair_text':\n 'Black Belt 13th Dan :BlackBelt:', 'css_class': '13thDan'}, '14th': {\n 'name': '14th Dan', 'flair_text': 'Black Belt 14th Dan :BlackBelt:',\n 'css_class': '14thDan'}, '15th': {'name': '15th Dan', 'flair_text':\n 'Black Belt 15th Dan :BlackBelt:', 'css_class': '15thDan'}, '16th': {\n 'name': '16th Dan', 'flair_text': 'Black Belt 16th Dan :BlackBelt:',\n 'css_class': '16thDan'}, '17th': {'name': '17th Dan', 'flair_text':\n 'Black Belt 17th Dan :BlackBelt:', 'css_class': '17thDan'}, '18th': {\n 'name': '18th Dan', 'flair_text': 'Black Belt 18th Dan :BlackBelt:',\n 'css_class': '18thDan'}, '19th': {'name': '19th Dan', 'flair_text':\n 'Black Belt 19th Dan :BlackBelt:', 'css_class': '19thDan'}, '20th': {\n 'name': '20th Dan', 'flair_text': 'Black Belt 20th Dan :BlackBelt:',\n 'css_class': '20thDan'}})\n", (1978, 4133), False, 'from bot.structs import CaseInsensitiveDict\n'), ((4179, 4275), 'bot.structs.CaseInsensitiveDict', 'CaseInsensitiveDict', ([], {}), "(**{'HoF': {'name': '<NAME>ame', 'flair_text': None,\n 'css_class': None}})\n", (4198, 4275), False, 'from bot.structs import CaseInsensitiveDict\n'), ((4306, 4354), 'collections.ChainMap', 'ChainMap', (['STANDARD_BELTS', 'ADDON_BELTS', 'NON_BELTS'], {}), '(STANDARD_BELTS, ADDON_BELTS, NON_BELTS)\n', (4314, 4354), False, 'from collections import ChainMap\n')] |
import mnist
import numpy as np
from PIL import Image
from conv import Conv3x3
from maxpool import MaxPool2
from softmax import Softmax
train_images = mnist.train_images()[:100]
train_labels = mnist.train_labels()[:100]
test_images = mnist.test_images()[:1000]
test_labels = mnist.test_labels()[:1000]
conv = Conv3x3(8)
pool = MaxPool2()
softmax = Softmax(13 * 13 * 8, 10)
def forward(image, label):
out = conv.forward((image / 255) - 0.5)
out = pool.forward(out)
out = softmax.forward(out)
loss = -np.log(out[label])
acc = 1 if np.argmax(out) == label else 0
return out, loss, acc
def train(image, label, lr=.005):
out, loss, acc = forward(image, label)
gradient = np.zeros(10)
gradient[label] = -1 / out[label]
gradient = softmax.backprop(gradient, lr)
gradient = pool.backprop(gradient)
gradient = conv.backprop(gradient, lr)
return out, loss, acc
def start_training():
loss = 0
num_correct = 0
for i, (image, label) in enumerate(zip(train_images, train_labels)):
if i % 100 == 99:
print(
f'[Step {i + 1}] Past 100 steps: Average loss {loss / 100}. Accuracy: {num_correct}%'
)
loss = 0
num_correct = 0
_, l, acc = train(image, label)
loss += l
num_correct += acc
def test(image, label):
np_image = np.array(image)
result, loss, acc = train(np_image, label)
return result.tolist()
| [
"softmax.Softmax",
"mnist.test_labels",
"mnist.train_images",
"numpy.log",
"numpy.argmax",
"mnist.test_images",
"numpy.array",
"numpy.zeros",
"conv.Conv3x3",
"maxpool.MaxPool2",
"mnist.train_labels"
] | [((311, 321), 'conv.Conv3x3', 'Conv3x3', (['(8)'], {}), '(8)\n', (318, 321), False, 'from conv import Conv3x3\n'), ((329, 339), 'maxpool.MaxPool2', 'MaxPool2', ([], {}), '()\n', (337, 339), False, 'from maxpool import MaxPool2\n'), ((350, 374), 'softmax.Softmax', 'Softmax', (['(13 * 13 * 8)', '(10)'], {}), '(13 * 13 * 8, 10)\n', (357, 374), False, 'from softmax import Softmax\n'), ((152, 172), 'mnist.train_images', 'mnist.train_images', ([], {}), '()\n', (170, 172), False, 'import mnist\n'), ((194, 214), 'mnist.train_labels', 'mnist.train_labels', ([], {}), '()\n', (212, 214), False, 'import mnist\n'), ((235, 254), 'mnist.test_images', 'mnist.test_images', ([], {}), '()\n', (252, 254), False, 'import mnist\n'), ((276, 295), 'mnist.test_labels', 'mnist.test_labels', ([], {}), '()\n', (293, 295), False, 'import mnist\n'), ((689, 701), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (697, 701), True, 'import numpy as np\n'), ((1294, 1309), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (1302, 1309), True, 'import numpy as np\n'), ((511, 529), 'numpy.log', 'np.log', (['out[label]'], {}), '(out[label])\n', (517, 529), True, 'import numpy as np\n'), ((543, 557), 'numpy.argmax', 'np.argmax', (['out'], {}), '(out)\n', (552, 557), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
:author: T8840
:tag: Thinking is a good thing!
纸上得来终觉浅,绝知此事要躬行!
:description:
1.部署相关信息来自于nacos配置
{
"server_info": {
"host": "10.201.5.161",
"port":22,
"user" : "user",
"password": "password"
},
"deploy_configCenter": {
"project_name": "configCenter",
"process_name": "configCenter",
"container_name": "configCenter",
"project_deploy_path": "/usr/testProject/configCenter/",
"project_dev_path": "../configCenter",
"project_git_path": "<EMAIL>/configCenter.git",
"local_temp_path":"/deploy_temp",
"remote_temp_path":"/usr/testProject/deploy_temp/"
}
}
2.由于远程Linux服务器与git项目处于不同网段不能直接拉取代码,故依赖于本地主机作为中转从git下拉代码打包后上传到Linux服务器
2.1
"""
import os
import json
import arrow
import zipfile
import pathlib
import paramiko
import platform
import subprocess
import requests
def isWindows():
return True if "Windows" in platform.system() else False
def isLinux():
return True if "Linux" in platform.system() else False
def getInfo():
try:
info = requests.get("http://10.201.7.185:8848/nacos/v1/cs/configs?dataId=deploy_124&group=DEFAULT_GROUP&tenant=89362432-5255-497e-8e94-cb77d46cb1a9")
return json.loads(info.text)
except Exception:
raise ConnectionRefusedError
class Deploy(object):
def __init__(self):
self.server_info = getInfo()["server_info"]
self.deploy_info = getInfo()["deploy_configCenter"]
self.projectName = "".join(
[self.deploy_info["project_name"] if self.deploy_info["project_name"] else "projectName", arrow.now().format("MMDDHHmmss"), ".zip"]
)
self.backupName = "".join(
[self.deploy_info["project_name"] if self.deploy_info["project_name"] else "projectName", arrow.now().format("MMDDHHmm"), ".bak"]
)
self.nowPath = pathlib.Path.cwd()
self.sshObj = self.connectSrv()
def connectSrv(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(self.server_info['host'], 22, self.server_info['user'], self.server_info['password'])
except paramiko.SSHException as e:
print("服务器连接失败,报错{error}".format(error=e))
return ssh
def runRemoteCmd(self, cmd):
"""
执行远程命令
:return:
"""
print(f"runRemoteCmd执行命令 {repr(cmd)}")
errorFlag = False
ouput = ""
try:
stdin, stdout, stderr = self.sshObj.exec_command(cmd)
ouput = stdout.readlines()
errorMsg = stderr.readlines()
if errorMsg:
errorFlag = True
ouput = errorMsg
print("命令执行失败~")
print(errorMsg)
except Exception as e:
print("命令执行异常~")
print(e)
return errorFlag, ouput
def cloneProject(self, projectGitPath, tempPath):
"""从Git拉取项目到本地或远程目录"""
subprocess.call(
["git", "clone", "--recurse-submodule", "--depth", "1", "-b", "master", str(projectGitPath), str(tempPath)]
)
def localCleaner(self, path):
"""在Windows系统清除临时文件"""
tempPath = pathlib.Path(path).absolute()
try:
print(tempPath)
os.system("rd /s/q {path}".format(path=tempPath))
except Exception as e:
print(e)
def deleteFiles(self, tempPath):
"""删除git中与部署无关文件"""
try:
gitPath = pathlib.Path(tempPath).absolute().joinpath(pathlib.Path(".git"))
print("删除 %s" % gitPath)
os.system("rd /s/q {path}".format(path=gitPath))
except Exception as e:
print(e)
def zipOnWin(self, tempPath):
"""在Windows系统针对git下拉的代码进行打包"""
# 指定zip文件保存的完整路径
fullProjectZip = pathlib.Path(tempPath).parent.joinpath(pathlib.Path(self.projectName))
print(f"fullProjectZip = {fullProjectZip}")
projectZip = zipfile.ZipFile(str(fullProjectZip), "w")
# 项目目录为缓存路径 直接打包项目下文件,与FinTesterPlatform不太一样
project = pathlib.Path(tempPath)
print(f"project = {project}")
with projectZip:
for filePath in project.rglob("*"):
# 参数1为文件完整路径 参数2为打包进zip之后的路径
projectZip.write(
filePath,
str(filePath)
.replace(str(pathlib.Path(self.deploy_info['local_temp_path']).absolute()), "")
.replace("\\" + self.deploy_info['project_name'], ""),
)
def zipOnLinux(self, filePath, zipPath):
"""在Linux将原有代码进行备份打包"""
zipCmd = f"tar -zcPf {zipPath} {filePath}"
errFlag, ouput = self.runRemoteCmd(zipCmd)
if not errFlag:
print(ouput)
print("压缩原始版本文件完成~")
else:
print("压缩原始版本文件失败~")
print(ouput)
def upload(self, localFilePath, remoteFilePath):
"""从Windows系统上传文件到Linux系统"""
# localFilePath remoteFilePath 一定是带文件名的完整路径!!!
srvConnect = paramiko.Transport((self.server_info['host'], 22))
try:
srvConnect.connect(username=self.server_info['user'], password=self.server_info['password'])
print("连接服务器:{hostName}".format(hostName=self.server_info['host']))
sftp = paramiko.SFTPClient.from_transport(srvConnect)
print(
"开始上传文件,本地完整路径:{localFilePath}\n远程完整路径:{remoteFilePath}".format(
localFilePath=localFilePath, remoteFilePath=remoteFilePath
)
)
sftp.put(localFilePath, remoteFilePath)
srvConnect.close()
print("文件上传成功!")
except ValueError as e:
print("文件上传失败!")
print(e)
def remoteCleaner(self, path):
"""在Linux清除临时文件"""
countCmd = f"cd {path} && ls -l |grep {self.deploy_info['project_name']} | wc -l"
fileNum = 0
errFlag, output = self.runRemoteCmd(countCmd)
if not errFlag:
print("执行文件统计命令成功!")
fileNum = int(output[0])
else:
print(f"执行文件统计命令失败! output = {output}")
if fileNum and fileNum >= 5:
print(f"文件数量{fileNum} 开始清理!")
cleanCmd = f"cd {path} && ls -lrt | grep -v 'total' | grep {self.deploy_info['project_name']} | head -n {fileNum-3} | awk '{{print$9}}' | xargs rm"
errFlag, output = self.runRemoteCmd(cleanCmd)
if not errFlag:
print("执行文件清理命令成功!")
else:
print(f"执行文件清理命令失败! output = {output}")
else:
print(f"文件数量{fileNum} 跳过清理!")
def backup(self, backupPath, originPath):
backupName = self.deploy_info['project_name'] + "_bak" + arrow.now().format("MMDDHHmmss") + ".tar.gz"
zipPath = backupPath + backupName
print(f"远程备份路径为: {zipPath}")
self.zipOnLinux(originPath, zipPath)
return backupName
def unzipFile(self, zipFile):
unzipFileCmd = f"cd {self.deploy_info['remote_temp_path'] } && unzip -o {zipFile} -d {self.deploy_info['project_deploy_path']}"
errMsg, output = self.runRemoteCmd(unzipFileCmd)
if not errMsg:
print("解压缩文件完成~")
else:
print(f"解压缩文件失败~ errMsg = {output}")
def restartContainer(self, sshObj=None):
"""重启容器"""
restartCmd = f"sudo docker restart {self.deploy_info['container_name']}"
errMsg, output = self.runRemoteCmd(restartCmd)
if not errMsg:
print("重启项目完成~")
else:
print(f"重启项目失败~ errMsg = {output}")
def doDeploy(self):
"""主流程"""
print("自动部署开始~ \nstep0: 清理本地缓存文件")
self.localCleaner(self.deploy_info['local_temp_path'])
print("step1: 本地拉取gitlab最新代码~ ")
tempPath = pathlib.Path(self.deploy_info['local_temp_path']).absolute().joinpath(pathlib.Path(self.deploy_info["project_name"]))
print(f"缓存路径为: {tempPath}")
self.cloneProject(self.deploy_info['project_git_path'], str(tempPath))
print("step2: 删除一些部署无关的文件~")
self.deleteFiles(tempPath)
print("step3: 打包拉取到的gitlab最新代码~")
self.zipOnWin(tempPath)
print("step4: 远程执行代码备份")
self.backup(self.deploy_info['remote_temp_path'], self.deploy_info['project_deploy_path'])
print("step5: 上传代码至服务器~")
self.upload(
pathlib.Path(self.deploy_info['local_temp_path']).absolute().joinpath(self.projectName), self.deploy_info['remote_temp_path'] + self.projectName
)
print("step6: 执行部署动作")
# 解压文件
self.unzipFile(self.projectName)
# 重启容器
self.restartContainer()
print("项目部署完成!")
print("附加步骤 清理远程多余缓存文件!")
self.remoteCleaner(self.deploy_info['remote_temp_path'])
print("完成!")
if __name__ == "__main__":
de = Deploy()
de.doDeploy()
| [
"paramiko.SFTPClient.from_transport",
"json.loads",
"pathlib.Path",
"pathlib.Path.cwd",
"paramiko.AutoAddPolicy",
"arrow.now",
"paramiko.Transport",
"requests.get",
"platform.system",
"paramiko.SSHClient"
] | [((1362, 1514), 'requests.get', 'requests.get', (['"""http://10.201.7.185:8848/nacos/v1/cs/configs?dataId=deploy_124&group=DEFAULT_GROUP&tenant=89362432-5255-497e-8e94-cb77d46cb1a9"""'], {}), "(\n 'http://10.201.7.185:8848/nacos/v1/cs/configs?dataId=deploy_124&group=DEFAULT_GROUP&tenant=89362432-5255-497e-8e94-cb77d46cb1a9'\n )\n", (1374, 1514), False, 'import requests\n'), ((1520, 1541), 'json.loads', 'json.loads', (['info.text'], {}), '(info.text)\n', (1530, 1541), False, 'import json\n'), ((2160, 2178), 'pathlib.Path.cwd', 'pathlib.Path.cwd', ([], {}), '()\n', (2176, 2178), False, 'import pathlib\n'), ((2260, 2280), 'paramiko.SSHClient', 'paramiko.SSHClient', ([], {}), '()\n', (2278, 2280), False, 'import paramiko\n'), ((4406, 4428), 'pathlib.Path', 'pathlib.Path', (['tempPath'], {}), '(tempPath)\n', (4418, 4428), False, 'import pathlib\n'), ((5377, 5427), 'paramiko.Transport', 'paramiko.Transport', (["(self.server_info['host'], 22)"], {}), "((self.server_info['host'], 22))\n", (5395, 5427), False, 'import paramiko\n'), ((1218, 1235), 'platform.system', 'platform.system', ([], {}), '()\n', (1233, 1235), False, 'import platform\n'), ((1293, 1310), 'platform.system', 'platform.system', ([], {}), '()\n', (1308, 1310), False, 'import platform\n'), ((2321, 2345), 'paramiko.AutoAddPolicy', 'paramiko.AutoAddPolicy', ([], {}), '()\n', (2343, 2345), False, 'import paramiko\n'), ((4188, 4218), 'pathlib.Path', 'pathlib.Path', (['self.projectName'], {}), '(self.projectName)\n', (4200, 4218), False, 'import pathlib\n'), ((5645, 5691), 'paramiko.SFTPClient.from_transport', 'paramiko.SFTPClient.from_transport', (['srvConnect'], {}), '(srvConnect)\n', (5679, 5691), False, 'import paramiko\n'), ((8222, 8268), 'pathlib.Path', 'pathlib.Path', (["self.deploy_info['project_name']"], {}), "(self.deploy_info['project_name'])\n", (8234, 8268), False, 'import pathlib\n'), ((3524, 3542), 'pathlib.Path', 'pathlib.Path', (['path'], {}), '(path)\n', (3536, 3542), False, 'import pathlib\n'), ((3853, 3873), 'pathlib.Path', 'pathlib.Path', (['""".git"""'], {}), "('.git')\n", (3865, 3873), False, 'import pathlib\n'), ((4149, 4171), 'pathlib.Path', 'pathlib.Path', (['tempPath'], {}), '(tempPath)\n', (4161, 4171), False, 'import pathlib\n'), ((1898, 1909), 'arrow.now', 'arrow.now', ([], {}), '()\n', (1907, 1909), False, 'import arrow\n'), ((2087, 2098), 'arrow.now', 'arrow.now', ([], {}), '()\n', (2096, 2098), False, 'import arrow\n'), ((7089, 7100), 'arrow.now', 'arrow.now', ([], {}), '()\n', (7098, 7100), False, 'import arrow\n'), ((8152, 8201), 'pathlib.Path', 'pathlib.Path', (["self.deploy_info['local_temp_path']"], {}), "(self.deploy_info['local_temp_path'])\n", (8164, 8201), False, 'import pathlib\n'), ((3810, 3832), 'pathlib.Path', 'pathlib.Path', (['tempPath'], {}), '(tempPath)\n', (3822, 3832), False, 'import pathlib\n'), ((8731, 8780), 'pathlib.Path', 'pathlib.Path', (["self.deploy_info['local_temp_path']"], {}), "(self.deploy_info['local_temp_path'])\n", (8743, 8780), False, 'import pathlib\n'), ((4716, 4765), 'pathlib.Path', 'pathlib.Path', (["self.deploy_info['local_temp_path']"], {}), "(self.deploy_info['local_temp_path'])\n", (4728, 4765), False, 'import pathlib\n')] |
# -*- coding: utf-8 -*-
"""
Functions for plotting reliability diagrams: smooths of simulated vs observed
outcomes on the y-axis against predicted probabilities on the x-axis.
"""
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sbn
from .plot_utils import _label_despine_save_and_show_plot
from .smoothers import ContinuousSmoother, DiscreteSmoother, SmoothPlotter
from .utils import progress
try:
# in Python 3 range returns an iterator instead of list
# to maintain backwards compatibility use "old" version of range
from past.builtins import range
except ImportError:
pass
# Set the plotting style
sbn.set_style("darkgrid")
def _check_reliability_args(probs, choices, partitions, sim_y):
"""
Ensures `probs` is a 1D or 2D ndarray, that `choices` is a 1D ndarray, that
`partitions` is an int, and that `sim_y` is a ndarray of the same shape as
`probs` or None.
"""
if not isinstance(probs, np.ndarray):
msg = "`probs` MUST be an ndarray."
raise ValueError(msg)
if probs.ndim not in [1, 2]:
msg = "probs` MUST be a 1D or 2D ndarray."
raise ValueError(msg)
if not isinstance(choices, np.ndarray):
msg = "`choices` MUST be an ndarray."
raise ValueError(msg)
if choices.ndim != 1:
msg = "`choices` MUST be a 1D ndarray."
raise ValueError(msg)
if not isinstance(partitions, int):
msg = "`partitions` MUST be an int."
raise ValueError(msg)
if not isinstance(sim_y, np.ndarray) and sim_y is not None:
msg = "`sim_y` MUST be an ndarray or None."
raise ValueError(msg)
sim_to_prob_conditions = probs.ndim != 1 and sim_y.shape != probs.shape
if sim_y is not None and sim_to_prob_conditions:
msg = (
"`sim_y` MUST have the same shape as `probs` if "
"`probs.shape[1] != 1`."
)
raise ValueError(msg)
return None
def add_ref_line(ax, ref_label="Perfect Calibration"):
"""
Plots a diagonal line to show perfectly calibrated probabilities.
Parameters
----------
ax : matplotlib Axes instance
The Axes that the reference line should be plotted on.
ref_label : str, optional.
The label to be applied to the reference line that is drawn.
Returns
-------
None. `ax` is modified in place: the line is plotted and the label added.
"""
# Determine the maximum value of the x-axis or y-axis
max_ref_val = max(ax.get_xlim()[1], ax.get_ylim()[1])
min_ref_val = max(ax.get_xlim()[0], ax.get_ylim()[0])
# Determine the values to use to plot the reference line
ref_vals = np.linspace(min_ref_val, max_ref_val, num=100)
# Plot the reference line as a black dashed line
ax.plot(ref_vals, ref_vals, "k--", label=ref_label)
return None
def plot_smoothed_reliability(
probs,
choices,
discrete=True,
partitions=10,
n_estimators=50,
min_samples_leaf=10,
random_state=None,
line_color="#1f78b4",
line_label="Observed vs Predicted",
alpha=None,
sim_y=None,
sim_line_color="#a6cee3",
sim_label="Simulated vs Predicted",
sim_alpha=0.5,
x_label="Mean Predicted Probability",
y_label="Binned\nEmpirical\nProbability",
title=None,
fontsize=12,
ref_line=True,
figsize=(5, 3),
fig_and_ax=None,
legend=True,
progress_bar=True,
show=True,
output_file=None,
dpi=500,
):
"""
Creates a binned reliability plot based on the given probability
predictions and the given observed outcomes.
Parameters
----------
probs : 1D or 2D ndarray.
Each element should be in [0, 1]. There should be 1 column for each
set of predicted probabilities. These will be plotted on the x-axis.
choices : 1D ndarray.
Each element should be either a zero or a one. Elements should denote
whether the alternative corresponding to the given row was chosen or
not. A 'one' corresponds to a an outcome of 'success'.
discrete : bool, optional.
Determines whether discrete smoothing (i.e. binning) will be used or
whether continuous binning via Extremely Randomized Trees will be used.
Default is to use discrete binning, so `discrete == True`.
partitions : positive int, optional.
Denotes the number of partitions to split one's data into for binning.
Only used if `discrete is True`. Default == 10.
n_estimators : positive int, optional.
Determines the number of trees in the ensemble of Extremely Randomized
Trees that is used to do continuous smoothing. This parameter controls
how smooth one's resulting estimate is. The more estimators the
smoother one's estimated relationship and the lower the variance in
that estimated relationship. This kwarg is only used if `discrete is
False`. Default == 50.
min_samples_leaf : positive int, optional.
Determines the minimum number of observations allowed in a leaf node in
any tree in the ensemble. This parameter is conceptually equivalent to
the bandwidth parameter in a kernel density estimator. This kwarg is
only used if `discrete is False`. Default == 10.
random_state : positive int, or None, optional.
Denotes the random seed to be used when constructing the ensemble of
Extremely Randomized Trees. This kwarg is only used if `discrete is
False`. Default is None.
line_color : valid matplotlib color, optional.
Determines the color that is used to plot the predicted probabilities
versus the observed choices. Default is `'#1f78b4'`.
line_label : str or None, optional.
Denotes the label to be used for the lines relating the predicted
probabilities and the binned, empirical probabilities. Default is
'Observed vs Predicted'.
alpha : positive float in [0.0, 1.0], or `None`, optional.
Determines the opacity of the observed data drawn on the plot.
0.0 == transparent and 1.0 == opaque. Default == 1.0.
sim_y : 2D ndarray or None, optional.
Denotes the choices that were simulated based on `probs`. If passed,
`sim_y.shape` MUST equal `probs.shape` in order to ensure that lines
are plotted for the predicted probabilities versus simulated choices.
This kwarg is useful because it shows one the reference distribution of
predicted probabilities versus choices that actually come from one's
postulated model.
sim_line_color : valid matplotlib color, optional.
Determines the color that is used to plot the predicted probabilities
versus the simulated choices. Default is `'#a6cee3'`.
sim_line_label : str, or None, optional.
Denotes the label to be used for the lines relating the predicted
probabilities and the binned, empirical probabilities based on the
simulated choices. Default is 'Simulated vs Predicted'.
sim_alpha : positive float in [0.0, 1.0], or `None`, optional.
Determines the opacity of the simulated reliability curves.
0.0 == transparent and 1.0 == opaque. Default == 0.5.
x_label, y_label : str, optional.
Denotes the label for the x-axis and y-axis, respectively. Defaults are
'Mean Predicted Probability' and 'Binned\nEmpirical\nProbability' for
the x-axis and y-axis, respectively.
title : str, or None, optional.
Denotes the title to be displayed for the plot. Default is None.
fontsize : int or None, optional.
The fontsize to be used in the plot. Default is 12.
ref_line : bool, optional.
Determines whether a diagonal line, y = x, will be plotted to show the
expected relationship. Default is True.
figsize : 2-tuple of positive ints.
Determines the size of the created figure. Default == (5, 3).
fig_and_ax : list of matplotlib figure and axis, or `None`, optional.
Determines whether a new figure will be created for the plot or whether
the plot will be drawn on existing axes. If None, a new figure will be
created. Default is `None`.
legend : bool, optional.
Determines whether a legend is printed for the plot. Default == True.
progress_bar : bool, optional.
Determines whether a progress bar is displayed while making the plot.
Default == True.
show : bool, optional.
Determines whether the figure is shown after plotting is complete.
Default == True.
output_file : str, or None, optional.
Denotes the relative or absolute filepath (including the file format)
that is to be used to save the plot. If None, the plot will not be
saved to file. Default is None.
dpi : positive int, optional.
Denotes the number of 'dots per inch' for the saved figure. Will only
be used if `output_file is not None`. Default == 500.
Returns
-------
None.
"""
# Perform some basic argument checking
_check_reliability_args(probs, choices, partitions, sim_y)
# Make probs 2D if necessary
probs = probs[:, None] if probs.ndim == 1 else probs
# Create the figure and axes if need be
if fig_and_ax is None:
fig, ax = plt.subplots(1, figsize=figsize)
fig_and_ax = [fig, ax]
else:
fig, ax = fig_and_ax
# Create the progressbar iterator if desired
if progress_bar and sim_y is not None:
description = "Plotting" if sim_y is None else "Plotting Simulations"
sim_iterator = progress(range(sim_y.shape[1]), desc=description)
else:
sim_iterator = range(probs.shape[1])
# Create the desired smoother
if discrete:
smoother = DiscreteSmoother(
num_obs=probs.shape[0], partitions=partitions
)
else:
smoother = ContinuousSmoother(
n_estimators=n_estimators,
min_samples_leaf=min_samples_leaf,
random_state=random_state,
)
# Create the plotter that will plot single smooth curves
plotter = SmoothPlotter(smoother=smoother, ax=ax)
# Create helper functions
def get_current_probs(col):
"""
Fetches the current probabilities when plotting the reliability curves.
"""
current = probs[:, 0] if probs.shape[1] == 1 else probs[:, col]
return current
# Plot the simulated reliability curves, if desired
if sim_y is not None:
for i in sim_iterator:
current_label = sim_label if i == 0 else None
plotter.plot(
get_current_probs(i),
sim_y[:, i],
label=current_label,
color=sim_line_color,
alpha=sim_alpha,
sort=True,
)
# Create the progressbar iterator if desired
if progress_bar:
prob_iterator = progress(range(probs.shape[1]), desc="Plotting")
else:
prob_iterator = range(probs.shape[1])
# Make the 'true' reliability plots
for col in prob_iterator:
plotter.plot(
get_current_probs(col),
choices,
label=line_label,
color=line_color,
alpha=alpha,
sort=True,
)
# Create the reference line if desired
if ref_line:
add_ref_line(ax)
# Make the legend, if desired
if legend:
ax.legend(loc="best", fontsize=fontsize)
# Take care of boilerplate plotting necessities
_label_despine_save_and_show_plot(
x_label=x_label,
y_label=y_label,
fig_and_ax=fig_and_ax,
fontsize=fontsize,
y_rot=0,
y_pad=40,
title=title,
output_file=output_file,
show=show,
dpi=dpi,
)
return None
| [
"seaborn.set_style",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"past.builtins.range"
] | [((681, 706), 'seaborn.set_style', 'sbn.set_style', (['"""darkgrid"""'], {}), "('darkgrid')\n", (694, 706), True, 'import seaborn as sbn\n'), ((2708, 2754), 'numpy.linspace', 'np.linspace', (['min_ref_val', 'max_ref_val'], {'num': '(100)'}), '(min_ref_val, max_ref_val, num=100)\n', (2719, 2754), True, 'import numpy as np\n'), ((9365, 9397), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {'figsize': 'figsize'}), '(1, figsize=figsize)\n', (9377, 9397), True, 'import matplotlib.pyplot as plt\n'), ((9745, 9766), 'past.builtins.range', 'range', (['probs.shape[1]'], {}), '(probs.shape[1])\n', (9750, 9766), False, 'from past.builtins import range\n'), ((11078, 11099), 'past.builtins.range', 'range', (['probs.shape[1]'], {}), '(probs.shape[1])\n', (11083, 11099), False, 'from past.builtins import range\n'), ((9671, 9692), 'past.builtins.range', 'range', (['sim_y.shape[1]'], {}), '(sim_y.shape[1])\n', (9676, 9692), False, 'from past.builtins import range\n'), ((11004, 11025), 'past.builtins.range', 'range', (['probs.shape[1]'], {}), '(probs.shape[1])\n', (11009, 11025), False, 'from past.builtins import range\n')] |
"""
An AWS Lambda function used to run periodic background jobs on ECS.
The complication with running these tasks is that we need to run them on
the same version of the Docker image that the web servers are currently
running on.
"""
import logging
import boto3
from utils import env_list, env_param
# Logging setup is done by Lambda
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Initialize clients for the required services.
ecs = boto3.client('ecs')
def handler(event, context):
"""
The entry point into the lambda function.
This function finds the version of the Docker image running a
specific service on a specific ECS cluster and then launches a new
task on the same ECS cluster running an overridden version of the
same Docker image.
Args:
event:
A dictionary containing information provided when the
function was invoked.
context:
An unknown object containing additional context for the
request.
Returns:
A dictionary containing a response code and status message.
"""
# The name of the ECS cluster running the existing API task.
cluster = env_param('CLUSTER')
# The name of the service running on the cluster whose image should
# be used to run the background jobs.
service = env_param('SERVICE')
# The name of the container within the service to override.
container_name = env_param('CONTAINER_NAME')
# A list of security group IDs that the migration task should be
# placed in.
security_groups = env_list('SECURITY_GROUPS')
# A list of subnet IDs corresponding to the subnets the migration
# task may be placed in.
subnet_ids = env_list('SUBNETS')
logger.info('Beginning process of running background tasks.')
logger.info(
'Searching cluster "%s" for "%s" service...',
cluster,
service,
)
logger.info(
'Task to be executed with security groups %s in subnets %s',
security_groups,
subnet_ids,
)
# The first step is to describe the service so we can get access to
# the task definition being used.
services_info = ecs.describe_services(cluster=cluster, services=[service])
assert len(services_info['services']) == 1, (
'Received multiple services. Aborting!'
)
logger.info('Received information about "%s" service.', service)
service_info = services_info['services'][0]
task_definition_arn = service_info['taskDefinition']
logger.info(
'ARN of task definition from service is %s',
task_definition_arn,
)
# Pull roles from task definition information. We run the background
# task with the same roles that the API web server tasks normally
# run under.
task_definition = ecs.describe_task_definition(
taskDefinition=task_definition_arn,
)
execution_role = task_definition['taskDefinition']['executionRoleArn']
task_role = task_definition['taskDefinition']['taskRoleArn']
logger.info(
'Will execute task with role %s as role %s',
task_role,
execution_role,
)
# Using the parameters we have pulled from the previous steps, we
# launch what is essentially a modified version of the webserver
# task that performs the tasks required to migrate between versions
# of the codebase.
ecs.run_task(
cluster=cluster,
launchType='FARGATE',
overrides={
'containerOverrides': [
{
'command': ['background-jobs'],
'name': container_name,
},
],
# The role used by the ECS agent.
'executionRoleArn': execution_role,
# The role our code runs under.
'taskRoleArn': task_role,
},
networkConfiguration={
'awsvpcConfiguration': {
# Need to assign a public IP so the image can be pulled.
'assignPublicIp': 'ENABLED',
'securityGroups': security_groups,
'subnets': subnet_ids,
},
},
taskDefinition=task_definition_arn,
)
return {
'body': 'Success',
'statusCode': 200
}
| [
"logging.getLogger",
"utils.env_param",
"boto3.client",
"utils.env_list"
] | [((348, 375), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (365, 375), False, 'import logging\n'), ((461, 480), 'boto3.client', 'boto3.client', (['"""ecs"""'], {}), "('ecs')\n", (473, 480), False, 'import boto3\n'), ((1198, 1218), 'utils.env_param', 'env_param', (['"""CLUSTER"""'], {}), "('CLUSTER')\n", (1207, 1218), False, 'from utils import env_list, env_param\n'), ((1347, 1367), 'utils.env_param', 'env_param', (['"""SERVICE"""'], {}), "('SERVICE')\n", (1356, 1367), False, 'from utils import env_list, env_param\n'), ((1453, 1480), 'utils.env_param', 'env_param', (['"""CONTAINER_NAME"""'], {}), "('CONTAINER_NAME')\n", (1462, 1480), False, 'from utils import env_list, env_param\n'), ((1590, 1617), 'utils.env_list', 'env_list', (['"""SECURITY_GROUPS"""'], {}), "('SECURITY_GROUPS')\n", (1598, 1617), False, 'from utils import env_list, env_param\n'), ((1735, 1754), 'utils.env_list', 'env_list', (['"""SUBNETS"""'], {}), "('SUBNETS')\n", (1743, 1754), False, 'from utils import env_list, env_param\n')] |
#! python3
# -*- coding: utf-8 -*-
import os
from pypeapp import execute, Logger
from pype.hosts.resolve.utils import get_resolve_module
log = Logger().get_logger("Resolve")
CURRENT_DIR = os.getenv("RESOLVE_UTILITY_SCRIPTS_DIR", "")
python_dir = os.getenv("PYTHON36_RESOLVE")
python_exe = os.path.normpath(
os.path.join(python_dir, "python.exe")
)
resolve = get_resolve_module()
PM = resolve.GetProjectManager()
P = PM.GetCurrentProject()
log.info(P.GetName())
# ______________________________________________________
# testing subprocessing Scripts
testing_py = os.path.join(CURRENT_DIR, "ResolvePageSwitcher.py")
testing_py = os.path.normpath(testing_py)
log.info(f"Testing path to script: `{testing_py}`")
returncode = execute(
[python_exe, os.path.normpath(testing_py)],
env=dict(os.environ)
)
# Check if output file exists
if returncode != 0:
log.error("Executing failed!")
| [
"os.getenv",
"pype.hosts.resolve.utils.get_resolve_module",
"os.path.join",
"os.path.normpath",
"pypeapp.Logger"
] | [((190, 234), 'os.getenv', 'os.getenv', (['"""RESOLVE_UTILITY_SCRIPTS_DIR"""', '""""""'], {}), "('RESOLVE_UTILITY_SCRIPTS_DIR', '')\n", (199, 234), False, 'import os\n'), ((248, 277), 'os.getenv', 'os.getenv', (['"""PYTHON36_RESOLVE"""'], {}), "('PYTHON36_RESOLVE')\n", (257, 277), False, 'import os\n'), ((365, 385), 'pype.hosts.resolve.utils.get_resolve_module', 'get_resolve_module', ([], {}), '()\n', (383, 385), False, 'from pype.hosts.resolve.utils import get_resolve_module\n'), ((573, 624), 'os.path.join', 'os.path.join', (['CURRENT_DIR', '"""ResolvePageSwitcher.py"""'], {}), "(CURRENT_DIR, 'ResolvePageSwitcher.py')\n", (585, 624), False, 'import os\n'), ((638, 666), 'os.path.normpath', 'os.path.normpath', (['testing_py'], {}), '(testing_py)\n', (654, 666), False, 'import os\n'), ((313, 351), 'os.path.join', 'os.path.join', (['python_dir', '"""python.exe"""'], {}), "(python_dir, 'python.exe')\n", (325, 351), False, 'import os\n'), ((144, 152), 'pypeapp.Logger', 'Logger', ([], {}), '()\n', (150, 152), False, 'from pypeapp import execute, Logger\n'), ((759, 787), 'os.path.normpath', 'os.path.normpath', (['testing_py'], {}), '(testing_py)\n', (775, 787), False, 'import os\n')] |
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
from libs.modules.FuseBlock import MakeFB
from .resnet_dilation import resnet50, resnet101, Bottleneck, conv1x1
BN_MOMENTUM = 0.1
logger = logging.getLogger(__name__)
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class _ConvBatchNormReLU(nn.Sequential):
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
relu=True,
):
super(_ConvBatchNormReLU, self).__init__()
self.add_module(
"conv",
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=False,
),
)
self.add_module(
"bn",
nn.BatchNorm2d(out_channels),
)
if relu:
self.add_module("relu", nn.ReLU(inplace=True))
def forward(self, x):
return super(_ConvBatchNormReLU, self).forward(x)
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=(0, 0), dilation=1):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_planes, out_planes,
kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=False)
self.bn = nn.BatchNorm2d(out_planes)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
return x
class _DenseDecoder(nn.Module):
def __init__(self, reduce_channel, n_classes):
super(_DenseDecoder, self).__init__()
# Decoder
self.decoder = nn.Sequential(
OrderedDict(
[
("conv1", _ConvBatchNormReLU(128, 256, 3, 1, 1, 1)), # 换成短连接残差块
("conv2", nn.Conv2d(256, n_classes, kernel_size=1)),
]
)
)
self.refine4_3 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.refine4_2 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.refine4_1 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.refine3_2 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.refine3_1 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.refine2_1 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.conv_cat_block4 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.conv_cat_block3 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.conv_cat_block2 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.conv_cat_block1 = _ConvBatchNormReLU(reduce_channel, reduce_channel, 3, 1, 1, 1)
self.fuse_sal = _ConvBatchNormReLU(reduce_channel * 4, 128, 3, 1, 1, 1)
def seg_conv(self, block3, block4):
bu1 = block3 + self.refine4_3(block4)
# bu1 = F.interpolate(x, size=block2.shape[2:], mode="bilinear", align_corners=False)
return bu1
def seg_conv2(self, block2, block4, bu1):
block4 = F.interpolate(block4, size=block2.shape[2:], mode="bilinear", align_corners=True)
bu1 = F.interpolate(bu1, size=block2.shape[2:], mode="bilinear", align_corners=True)
bu2 = block2 + self.refine3_2(bu1) + self.refine4_2(block4)
# bu2 = F.interpolate(x, size=block1.shape[2:], mode="bilinear", align_corners=False)
return bu2
def seg_conv3(self, block1, block4, bu1, bu2):
# bu1_2 = F.interpolate(bu1, size=block1.shape[2:], mode="bilinear", align_corners=False)
block4_1 = F.interpolate(block4, size=block1.shape[2:], mode="bilinear", align_corners=True)
bu2_1 = F.interpolate(bu2, size=block1.shape[2:], mode="bilinear", align_corners=True)
bu1_1 = F.interpolate(bu1, size=block1.shape[2:], mode="bilinear", align_corners=True)
# x = torch.cat((block1, bu2), dim=1)
bu3 = block1 + self.refine2_1(bu2_1) + self.refine3_1(bu1_1) + self.refine4_1(block4_1)
return bu3, block4_1, bu2_1, bu1_1
def segment(self, bu3, block4_1, bu2_1, bu1_1, shape):
agg = torch.cat((self.conv_cat_block1(bu3), self.conv_cat_block2(bu2_1), self.conv_cat_block3(bu1_1),
self.conv_cat_block4(block4_1)), dim=1)
sal = self.fuse_sal(agg)
sal = self.decoder(sal)
sal = F.interpolate(sal, size=shape, mode="bilinear", align_corners=True)
# sal= self.decoder(sal)
return sal
def forward(self, block1, block2, block3, block4, x):
bu1 = self.seg_conv(block3, block4)
bu2 = self.seg_conv2(block2, block4, bu1)
bu3, block4_1, bu2_1, bu1_1 = self.seg_conv3(block1, block4, bu1, bu2)
seg = self.segment(bu3, block4_1, bu2_1, bu1_1, x.shape[2:])
# return seg, E_sup, E_att, bu1_res
return seg
class _ASPPModule(nn.Module):
"""Atrous Spatial Pyramid Pooling with image pool"""
def __init__(self, in_channels, out_channels, output_stride):
super(_ASPPModule, self).__init__()
if output_stride == 8:
pyramids = [12, 24, 36]
elif output_stride == 16:
pyramids = [6, 12, 18]
self.stages = nn.Module()
self.stages.add_module(
"c0", _ConvBatchNormReLU(in_channels, out_channels, 1, 1, 0, 1)
)
for i, (dilation, padding) in enumerate(zip(pyramids, pyramids)):
self.stages.add_module(
"c{}".format(i + 1),
_ConvBatchNormReLU(in_channels, out_channels, 3, 1, padding, dilation),
)
self.imagepool = nn.Sequential(
OrderedDict(
[
("pool", nn.AdaptiveAvgPool2d((1,1))),
("conv", _ConvBatchNormReLU(in_channels, out_channels, 1, 1, 0, 1)),
]
)
)
self.fire = nn.Sequential(
OrderedDict(
[
("conv", _ConvBatchNormReLU(out_channels * 5, out_channels, 3, 1, 1, 1)),
("dropout", nn.Dropout2d(0.1))
]
)
)
def forward(self, x):
h = self.imagepool(x)
h = [F.interpolate(h, size=x.shape[2:], mode="bilinear", align_corners=False)]
for stage in self.stages.children():
h += [stage(x)]
h = torch.cat(h, dim=1)
h = self.fire(h)
return h
class DCFNet_backbone(nn.Module):
def __init__(self, cfg, output_stride, input_channels=3, pretrained=False):
super(DCFNet_backbone, self).__init__()
self.os = output_stride
self.resnet = resnet101(pretrained=pretrained, output_stride=output_stride, input_channels=input_channels)
self.aspp = _ASPPModule(2048, 256, output_stride)
self.DenseDecoder = _DenseDecoder(reduce_channel=128, n_classes=1)
# stage3----> stage4
self.stage4_cfg = cfg['stage4_cfg']
self.stage4 = self._make_stage(self.stage4_cfg)
if pretrained:
for key in self.state_dict():
if 'resnet' not in key:
self.init_layer(key)
def init_layer(self, key):
if key.split('.')[-1] == 'weight':
if 'conv' in key:
if self.state_dict()[key].ndimension() >= 2:
nn.init.kaiming_normal_(self.state_dict()[key], mode='fan_out', nonlinearity='relu')
elif 'bn' in key:
self.state_dict()[key][...] = 1
elif key.split('.')[-1] == 'bias':
self.state_dict()[key][...] = 0.001
def feat_conv(self, x):
x_list = []
block0 = self.resnet.conv1(x)
block0 = self.resnet.bn1(block0)
block0 = self.resnet.relu(block0)
block0 = self.resnet.maxpool(block0)
block1 = self.resnet.layer1(block0)
x_list.append(block1)
block2 = self.resnet.layer2(block1)
x_list.append(block2)
block3 = self.resnet.layer3(block2)
x_list.append(block3)
block4 = self.resnet.layer4(block3)
# if self.os == 16:
# block4 = F.upsample(block4, scale_factor=2, mode='bilinear', align_corners=False)
block4 = self.aspp(block4)
x_list.append(block4)
return block1, block2, block3, block4, x_list
def _make_stage(self, layer_config, multi_scale_output=True):
num_branches = layer_config['NUM_BRANCHES']
num_blocks = layer_config['NUM_BLOCKS']
num_channels = layer_config['NUM_CHANNELS']
modules = []
modules.append(
MakeFB(
num_branches,
num_blocks,
num_channels,
multi_scale_output
)
)
return nn.Sequential(*modules)
def forward(self, x):
block1, block2, block3, block4, x_list = self.feat_conv(x)
y_list = self.stage4(x_list)
seg = self.DenseDecoder(y_list[0], y_list[1], y_list[2], y_list[3], x)
return F.sigmoid(seg)
| [
"logging.getLogger",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Sequential",
"torch.nn.Dropout2d",
"torch.nn.functional.sigmoid",
"torch.nn.Conv2d",
"torch.nn.Module",
"torch.nn.functional.interpolate",
"torch.nn.AdaptiveAvgPool2d",
"libs.modules.FuseBlock.MakeFB",
"torch.cat"
] | [((259, 286), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (276, 286), False, 'import logging\n'), ((385, 474), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_planes', 'out_planes'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': '(1)', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=3, stride=stride, padding=1,\n bias=False)\n', (394, 474), True, 'import torch.nn as nn\n'), ((1546, 1670), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_planes', 'out_planes'], {'kernel_size': 'kernel_size', 'stride': 'stride', 'padding': 'padding', 'dilation': 'dilation', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=False)\n', (1555, 1670), True, 'import torch.nn as nn\n'), ((1745, 1771), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['out_planes'], {}), '(out_planes)\n', (1759, 1771), True, 'import torch.nn as nn\n'), ((1792, 1813), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1799, 1813), True, 'import torch.nn as nn\n'), ((3589, 3675), 'torch.nn.functional.interpolate', 'F.interpolate', (['block4'], {'size': 'block2.shape[2:]', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(block4, size=block2.shape[2:], mode='bilinear', align_corners\n =True)\n", (3602, 3675), True, 'import torch.nn.functional as F\n'), ((3685, 3763), 'torch.nn.functional.interpolate', 'F.interpolate', (['bu1'], {'size': 'block2.shape[2:]', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(bu1, size=block2.shape[2:], mode='bilinear', align_corners=True)\n", (3698, 3763), True, 'import torch.nn.functional as F\n'), ((4115, 4201), 'torch.nn.functional.interpolate', 'F.interpolate', (['block4'], {'size': 'block1.shape[2:]', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(block4, size=block1.shape[2:], mode='bilinear', align_corners\n =True)\n", (4128, 4201), True, 'import torch.nn.functional as F\n'), ((4213, 4291), 'torch.nn.functional.interpolate', 'F.interpolate', (['bu2'], {'size': 'block1.shape[2:]', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(bu2, size=block1.shape[2:], mode='bilinear', align_corners=True)\n", (4226, 4291), True, 'import torch.nn.functional as F\n'), ((4308, 4386), 'torch.nn.functional.interpolate', 'F.interpolate', (['bu1'], {'size': 'block1.shape[2:]', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(bu1, size=block1.shape[2:], mode='bilinear', align_corners=True)\n", (4321, 4386), True, 'import torch.nn.functional as F\n'), ((4887, 4954), 'torch.nn.functional.interpolate', 'F.interpolate', (['sal'], {'size': 'shape', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(sal, size=shape, mode='bilinear', align_corners=True)\n", (4900, 4954), True, 'import torch.nn.functional as F\n'), ((5729, 5740), 'torch.nn.Module', 'nn.Module', ([], {}), '()\n', (5738, 5740), True, 'import torch.nn as nn\n'), ((6875, 6894), 'torch.cat', 'torch.cat', (['h'], {'dim': '(1)'}), '(h, dim=1)\n', (6884, 6894), False, 'import torch\n'), ((9272, 9295), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (9285, 9295), True, 'import torch.nn as nn\n'), ((9524, 9538), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['seg'], {}), '(seg)\n', (9533, 9538), True, 'import torch.nn.functional as F\n'), ((807, 961), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': 'in_channels', 'out_channels': 'out_channels', 'kernel_size': 'kernel_size', 'stride': 'stride', 'padding': 'padding', 'dilation': 'dilation', 'bias': '(False)'}), '(in_channels=in_channels, out_channels=out_channels, kernel_size=\n kernel_size, stride=stride, padding=padding, dilation=dilation, bias=False)\n', (816, 961), True, 'import torch.nn as nn\n'), ((1150, 1178), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['out_channels'], {}), '(out_channels)\n', (1164, 1178), True, 'import torch.nn as nn\n'), ((6716, 6788), 'torch.nn.functional.interpolate', 'F.interpolate', (['h'], {'size': 'x.shape[2:]', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(h, size=x.shape[2:], mode='bilinear', align_corners=False)\n", (6729, 6788), True, 'import torch.nn.functional as F\n'), ((9102, 9168), 'libs.modules.FuseBlock.MakeFB', 'MakeFB', (['num_branches', 'num_blocks', 'num_channels', 'multi_scale_output'], {}), '(num_branches, num_blocks, num_channels, multi_scale_output)\n', (9108, 9168), False, 'from libs.modules.FuseBlock import MakeFB\n'), ((1244, 1265), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1251, 1265), True, 'import torch.nn as nn\n'), ((2254, 2294), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', 'n_classes'], {'kernel_size': '(1)'}), '(256, n_classes, kernel_size=1)\n', (2263, 2294), True, 'import torch.nn as nn\n'), ((6220, 6248), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (6240, 6248), True, 'import torch.nn as nn\n'), ((6585, 6602), 'torch.nn.Dropout2d', 'nn.Dropout2d', (['(0.1)'], {}), '(0.1)\n', (6597, 6602), True, 'import torch.nn as nn\n')] |
# -*- coding: utf-8 -*-
"""
@author : <NAME>
@github : https://github.com/tianpangji
@software : PyCharm
@file : crud.py
@create : 2020/12/9 20:44
"""
from django.contrib.contenttypes.models import ContentType
from easyaudit.models import CRUDEvent
from rest_framework import serializers
class CRUDSerializer(serializers.ModelSerializer):
event_type_display = serializers.SerializerMethodField()
datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
username = serializers.SerializerMethodField()
content_type_display = serializers.SerializerMethodField()
class Meta:
model = CRUDEvent
fields = ['id', 'event_type_display', 'datetime', 'username', 'content_type_display', 'object_id',
'changed_fields']
def get_event_type_display(self, obj):
return obj.get_event_type_display()
def get_username(self, obj):
try:
username = obj.user.username
except AttributeError:
username = '未知'
return username
def get_content_type_display(self, obj):
content_type = ContentType.objects.get(id=obj.content_type_id)
return content_type.app_label + '.' + content_type.model
def to_representation(self, instance):
ret = super().to_representation(instance)
if ret.get('changed_fields') == 'null':
ret['changed_fields'] = ''
return ret
| [
"rest_framework.serializers.DateTimeField",
"rest_framework.serializers.SerializerMethodField",
"django.contrib.contenttypes.models.ContentType.objects.get"
] | [((376, 411), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (409, 411), False, 'from rest_framework import serializers\n'), ((427, 496), 'rest_framework.serializers.DateTimeField', 'serializers.DateTimeField', ([], {'format': '"""%Y-%m-%d %H:%M:%S"""', 'read_only': '(True)'}), "(format='%Y-%m-%d %H:%M:%S', read_only=True)\n", (452, 496), False, 'from rest_framework import serializers\n'), ((512, 547), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (545, 547), False, 'from rest_framework import serializers\n'), ((575, 610), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (608, 610), False, 'from rest_framework import serializers\n'), ((1125, 1172), 'django.contrib.contenttypes.models.ContentType.objects.get', 'ContentType.objects.get', ([], {'id': 'obj.content_type_id'}), '(id=obj.content_type_id)\n', (1148, 1172), False, 'from django.contrib.contenttypes.models import ContentType\n')] |
"""
ICMP(Internet Control Message Protocol) - Echo Request:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0|0|0|0|0|0|0|0|0|0|1|1|1|1|1|1|1|1|1|1|2|2|2|2|2|2|2|2|2|2|3|3|
|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 8 | Code = 0 | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Time Stamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
ICMP(Internet Control Message Protocol) - Echo Reply:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0|0|0|0|0|0|0|0|0|0|1|1|1|1|1|1|1|1|1|1|2|2|2|2|2|2|2|2|2|2|3|3|
|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 0 | Code = 0 | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Time Stamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
"""
import time
import socket
import struct
import random
def setIcmpEchoRquestPacket(seqNum = 0):
Type = 8
Code = 0
Identifier = 0
SequenceNumber = seqNum
TimeStamp = int(time.time())
Payload = bytes([i for i in range(0, 48)])
prePacket = struct.pack('!BBHHHLL48s', Type, Code, 0, Identifier, SequenceNumber, TimeStamp, 0, Payload)
Sum = 0
for i in range(0, len(prePacket), 2):
Sum += ((prePacket[i] << 8) | prePacket[i + 1])
Checksum = 0xFFFF - (((Sum & 0xFFFF0000) >> 16) + (Sum & 0xFFFF))
return struct.pack('!BBHHHLL48s', Type, Code, Checksum, Identifier, SequenceNumber, TimeStamp, 0, Payload)
def getIcmpEchoReplyPacket(packet, t1, t2):
Checksum = 0
for i in range(0, len(packet), 2):
Checksum += (packet[i] << 8) + packet[i + 1]
Checksum = ((Checksum & 0xFFFF0000) >> 16) + (Checksum & 0xFFFF)
if Checksum == 0xFFFF:
print('%4d.%06dms TTL = %03d SeqNum = %05d' % ((t2 - t1) * 1000, (t2 - t1) * 1000000000 % 1000000, packet[8], (packet[26] << 8) + packet[27]))
else:
print('Checksum Error!')
seqNum = 0
dstIP = 'www.baidu.com'
print('Try to ping %s (%s)' % (dstIP, socket.gethostbyname(dstIP)))
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.settimeout(5)
r = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
r.settimeout(5)
s.sendto(setIcmpEchoRquestPacket(seqNum), (dstIP, 80))
t1 = time.time()
packet = r.recvfrom(1024)
t2 = time.time()
getIcmpEchoReplyPacket(packet[0], t1, t2)
seqNum = (seqNum + 1) & 0xFFF
time.sleep(1)
except socket.timeout:
print('Timeout')
except KeyboardInterrupt:
exit() | [
"socket.gethostbyname",
"socket.socket",
"time.sleep",
"struct.pack",
"time.time"
] | [((1971, 2067), 'struct.pack', 'struct.pack', (['"""!BBHHHLL48s"""', 'Type', 'Code', '(0)', 'Identifier', 'SequenceNumber', 'TimeStamp', '(0)', 'Payload'], {}), "('!BBHHHLL48s', Type, Code, 0, Identifier, SequenceNumber,\n TimeStamp, 0, Payload)\n", (1982, 2067), False, 'import struct\n'), ((2257, 2360), 'struct.pack', 'struct.pack', (['"""!BBHHHLL48s"""', 'Type', 'Code', 'Checksum', 'Identifier', 'SequenceNumber', 'TimeStamp', '(0)', 'Payload'], {}), "('!BBHHHLL48s', Type, Code, Checksum, Identifier, SequenceNumber,\n TimeStamp, 0, Payload)\n", (2268, 2360), False, 'import struct\n'), ((1895, 1906), 'time.time', 'time.time', ([], {}), '()\n', (1904, 1906), False, 'import time\n'), ((2941, 3008), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_RAW', 'socket.IPPROTO_ICMP'], {}), '(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)\n', (2954, 3008), False, 'import socket\n'), ((3045, 3112), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_RAW', 'socket.IPPROTO_ICMP'], {}), '(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)\n', (3058, 3112), False, 'import socket\n'), ((3213, 3224), 'time.time', 'time.time', ([], {}), '()\n', (3222, 3224), False, 'import time\n'), ((3272, 3283), 'time.time', 'time.time', ([], {}), '()\n', (3281, 3283), False, 'import time\n'), ((3380, 3393), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3390, 3393), False, 'import time\n'), ((2878, 2905), 'socket.gethostbyname', 'socket.gethostbyname', (['dstIP'], {}), '(dstIP)\n', (2898, 2905), False, 'import socket\n')] |
import random
from model.contact import Contact
from model.group import Group
def test_to_delete_contact_from_group(app, db ,check_ui):
app.group.open_groups_page()
if len(db.get_group_list()) == 0:
app.group.create()
app.group.fill_group_form(Group(name='group for adding of contact'))
app.group.submit_group_creation()
app.group.open_groups_page()
group_list = app.group.get_group_list()
group = random.choice(group_list)
group_id = int(group.id)
contacts_in_group = app.group.looking_contacts_in_selected_group(group_id)
if contacts_in_group is None:
main_contacts_list = app.contacts.get_contacts_list()
if main_contacts_list is None:
if app.contacts.Count() == 0:
app.contacts.New_contact_form()
app.contacts.Filling_information_form(
Contact(first_name="<NAME>", last_name="<NAME>", address="Novgorod",
home_phone="21323", work_phone="2393", mobile_phone="24234324", fax='7777',
mail_1="<EMAIL>", mail_2='<EMAIL>', mail_3="<EMAIL>"))
app.contacts.Submit_new_contact_creation()
app.contacts.Open_home_page()
return main_contacts_list
contact=random.choice(main_contacts_list)
id = int(contact.id)
app.group.adding_contact_to_any_group(id)
return contacts_in_group
contacts_in_group = app.group.looking_contacts_in_selected_group(group_id)
contact_in_group = random.choice(contacts_in_group)
id = contact_in_group.id
app.group.deleting_contact_from_group(group, id)
new_contact_list_in_selected_group = app.contacts.get_contacts_in_selected_group(group_id)
assert len(contacts_in_group) - 1 == len(new_contact_list_in_selected_group)
assert contact_in_group not in new_contact_list_in_selected_group
bd_contacts_for_selected_group = db.get_contacts_list_for_selected_group(group_id)
if check_ui:
assert sorted(new_contact_list_in_selected_group, key=Contact.id_or_max) == \
sorted(app.contacts.get_contacts_in_selected_group(group_id),
key=Contact.id_or_max)
assert sorted(new_contact_list_in_selected_group, key=Contact.id_or_max) == \
sorted(bd_contacts_for_selected_group, key=Contact.id_or_max)
| [
"model.group.Group",
"random.choice",
"model.contact.Contact"
] | [((443, 468), 'random.choice', 'random.choice', (['group_list'], {}), '(group_list)\n', (456, 468), False, 'import random\n'), ((1540, 1572), 'random.choice', 'random.choice', (['contacts_in_group'], {}), '(contacts_in_group)\n', (1553, 1572), False, 'import random\n'), ((1292, 1325), 'random.choice', 'random.choice', (['main_contacts_list'], {}), '(main_contacts_list)\n', (1305, 1325), False, 'import random\n'), ((269, 310), 'model.group.Group', 'Group', ([], {'name': '"""group for adding of contact"""'}), "(name='group for adding of contact')\n", (274, 310), False, 'from model.group import Group\n'), ((877, 1084), 'model.contact.Contact', 'Contact', ([], {'first_name': '"""<NAME>"""', 'last_name': '"""<NAME>"""', 'address': '"""Novgorod"""', 'home_phone': '"""21323"""', 'work_phone': '"""2393"""', 'mobile_phone': '"""24234324"""', 'fax': '"""7777"""', 'mail_1': '"""<EMAIL>"""', 'mail_2': '"""<EMAIL>"""', 'mail_3': '"""<EMAIL>"""'}), "(first_name='<NAME>', last_name='<NAME>', address='Novgorod',\n home_phone='21323', work_phone='2393', mobile_phone='24234324', fax=\n '7777', mail_1='<EMAIL>', mail_2='<EMAIL>', mail_3='<EMAIL>')\n", (884, 1084), False, 'from model.contact import Contact\n')] |
import gzip
import logging
import logging.handlers
import os
from cStringIO import StringIO as IO
from spreads.vendor.huey import SqliteHuey
from spreads.vendor.huey.consumer import Consumer
from spreads.vendor.pathlib import Path
from flask import Flask, request
from spreads.plugin import (HookPlugin, SubcommandHookMixin, PluginOption,
get_devices)
from spreads.util import add_argument_from_option
app = Flask('spreadsplug.web', static_url_path='', static_folder='./client',
template_folder='./client')
task_queue = None
import web
import persistence
logger = logging.getLogger('spreadsplug.web')
try:
# Most reliable way to get IP address, requires third-party package with
# C extension
import netifaces
def get_ip_address():
try:
iface = next(dev for dev in netifaces.interfaces()
if 'wlan' in dev or 'eth' in dev
or dev.startswith('br'))
except StopIteration:
return None
addresses = netifaces.ifaddresses(iface)
if netifaces.AF_INET in addresses:
return addresses[netifaces.AF_INET][0]['addr']
except ImportError:
# Solution with built-ins, not as reliable
import socket
def get_ip_address():
try:
return next(
ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("127."))
except StopIteration:
return None
class WebCommands(HookPlugin, SubcommandHookMixin):
@classmethod
def add_command_parser(cls, rootparser):
cmdparser = rootparser.add_parser(
'web', help="Start the web interface")
cmdparser.set_defaults(subcommand=run_server)
for key, option in cls.configuration_template().iteritems():
try:
add_argument_from_option('web', key, option, cmdparser)
except:
continue
@classmethod
def configuration_template(cls):
return {
'mode': PluginOption(
value=["full", "scanner", "processor"],
docstring="Mode to run server in",
selectable=True),
'debug': PluginOption(
value=False,
docstring="Run server in debugging mode",
selectable=False),
'project_dir': PluginOption(
value=u"~/scans",
docstring="Directory for project folders",
selectable=False),
'database': PluginOption(
value=u"~/.config/spreads/workflows.db",
docstring="Path to application database file",
selectable=False),
'postprocessing_server': PluginOption(
value=u"", # Cannot be None because of type deduction in
# option parser
docstring="Address of the postprocessing server",
selectable=False),
'standalone_device': PluginOption(
value=False,
docstring="Server runs on a standalone device dedicated to "
"scanning (e.g. 'spreadpi').",
selectable=False)
}
@app.after_request
def gzip_response(response):
accept_encoding = request.headers.get('Accept-Encoding', '')
if 'gzip' not in accept_encoding.lower():
return response
response.direct_passthrough = False
skip_compress = (response.status_code < 200 or
response.status_code >= 300 or
response.mimetype.startswith("image/") or
response.mimetype == "application/zip" or
'Content-Encoding' in response.headers)
if skip_compress:
return response
gzip_buffer = IO()
gzip_file = gzip.GzipFile(mode='wb',
fileobj=gzip_buffer)
gzip_file.write(response.data)
gzip_file.close()
response.data = gzip_buffer.getvalue()
response.headers['Content-Encoding'] = 'gzip'
response.headers['Vary'] = 'Accept-Encoding'
response.headers['Content-Length'] = len(response.data)
return response
def setup_app(config):
mode = config['web']['mode'].get()
logger.debug("Starting scanning station server in \"{0}\" mode"
.format(mode))
db_path = Path(config['web']['database'].get()).expanduser()
project_dir = os.path.expanduser(config['web']['project_dir'].get())
if not os.path.exists(project_dir):
os.mkdir(project_dir)
app.config['DEBUG'] = config['web']['debug'].get()
app.config['mode'] = mode
app.config['database'] = db_path
app.config['base_path'] = project_dir
app.config['default_config'] = config
app.config['standalone'] = config['web']['standalone_device'].get()
if mode == 'scanner':
app.config['postproc_server'] = (
config['web']['postprocessing_server'].get())
def setup_logging(config):
# Add in-memory log handler
memoryhandler = logging.handlers.BufferingHandler(1024*10)
memoryhandler.setLevel(logging.DEBUG)
logger.root.addHandler(memoryhandler)
logging.getLogger('huey.consumer').setLevel(logging.INFO)
(logging.getLogger('huey.consumer.ConsumerThread')
.setLevel(logging.INFO))
def run_server(config):
setup_app(config)
setup_logging(config)
# Initialize huey task queue
global task_queue
db_location = os.path.join(config.config_dir(), 'queue.db')
task_queue = SqliteHuey(location=db_location)
consumer = Consumer(task_queue)
ip_address = get_ip_address()
if (app.config['standalone'] and ip_address
and config['driver'].get() in ['chdkcamera', 'a2200']):
# Display the address of the web interface on the camera displays
try:
for cam in get_devices(config):
cam.show_textbox(
"\n You can now access the web interface at:"
"\n\n\n http://{0}:5000".format(ip_address))
except:
logger.warn("No devices could be found at startup.")
# Start task consumer
consumer.start()
try:
import waitress
# NOTE: We spin up this obscene number of threads since we have
# some long-polling going on, which will always block
# one worker thread.
waitress.serve(app, port=5000, threads=16)
finally:
consumer.shutdown()
if app.config['DEBUG']:
logger.info("Waiting for remaining connections to close...")
| [
"logging.getLogger",
"os.path.exists",
"spreads.util.add_argument_from_option",
"cStringIO.StringIO",
"flask.Flask",
"logging.handlers.BufferingHandler",
"spreads.vendor.huey.SqliteHuey",
"spreads.vendor.huey.consumer.Consumer",
"netifaces.ifaddresses",
"gzip.GzipFile",
"waitress.serve",
"os.m... | [((439, 541), 'flask.Flask', 'Flask', (['"""spreadsplug.web"""'], {'static_url_path': '""""""', 'static_folder': '"""./client"""', 'template_folder': '"""./client"""'}), "('spreadsplug.web', static_url_path='', static_folder='./client',\n template_folder='./client')\n", (444, 541), False, 'from flask import Flask, request\n'), ((608, 644), 'logging.getLogger', 'logging.getLogger', (['"""spreadsplug.web"""'], {}), "('spreadsplug.web')\n", (625, 644), False, 'import logging\n'), ((3340, 3382), 'flask.request.headers.get', 'request.headers.get', (['"""Accept-Encoding"""', '""""""'], {}), "('Accept-Encoding', '')\n", (3359, 3382), False, 'from flask import Flask, request\n'), ((3849, 3853), 'cStringIO.StringIO', 'IO', ([], {}), '()\n', (3851, 3853), True, 'from cStringIO import StringIO as IO\n'), ((3870, 3915), 'gzip.GzipFile', 'gzip.GzipFile', ([], {'mode': '"""wb"""', 'fileobj': 'gzip_buffer'}), "(mode='wb', fileobj=gzip_buffer)\n", (3883, 3915), False, 'import gzip\n'), ((5086, 5130), 'logging.handlers.BufferingHandler', 'logging.handlers.BufferingHandler', (['(1024 * 10)'], {}), '(1024 * 10)\n', (5119, 5130), False, 'import logging\n'), ((5579, 5611), 'spreads.vendor.huey.SqliteHuey', 'SqliteHuey', ([], {'location': 'db_location'}), '(location=db_location)\n', (5589, 5611), False, 'from spreads.vendor.huey import SqliteHuey\n'), ((5627, 5647), 'spreads.vendor.huey.consumer.Consumer', 'Consumer', (['task_queue'], {}), '(task_queue)\n', (5635, 5647), False, 'from spreads.vendor.huey.consumer import Consumer\n'), ((1052, 1080), 'netifaces.ifaddresses', 'netifaces.ifaddresses', (['iface'], {}), '(iface)\n', (1073, 1080), False, 'import netifaces\n'), ((4540, 4567), 'os.path.exists', 'os.path.exists', (['project_dir'], {}), '(project_dir)\n', (4554, 4567), False, 'import os\n'), ((4577, 4598), 'os.mkdir', 'os.mkdir', (['project_dir'], {}), '(project_dir)\n', (4585, 4598), False, 'import os\n'), ((6451, 6493), 'waitress.serve', 'waitress.serve', (['app'], {'port': '(5000)', 'threads': '(16)'}), '(app, port=5000, threads=16)\n', (6465, 6493), False, 'import waitress\n'), ((2070, 2179), 'spreads.plugin.PluginOption', 'PluginOption', ([], {'value': "['full', 'scanner', 'processor']", 'docstring': '"""Mode to run server in"""', 'selectable': '(True)'}), "(value=['full', 'scanner', 'processor'], docstring=\n 'Mode to run server in', selectable=True)\n", (2082, 2179), False, 'from spreads.plugin import HookPlugin, SubcommandHookMixin, PluginOption, get_devices\n'), ((2246, 2335), 'spreads.plugin.PluginOption', 'PluginOption', ([], {'value': '(False)', 'docstring': '"""Run server in debugging mode"""', 'selectable': '(False)'}), "(value=False, docstring='Run server in debugging mode',\n selectable=False)\n", (2258, 2335), False, 'from spreads.plugin import HookPlugin, SubcommandHookMixin, PluginOption, get_devices\n'), ((2409, 2504), 'spreads.plugin.PluginOption', 'PluginOption', ([], {'value': 'u"""~/scans"""', 'docstring': '"""Directory for project folders"""', 'selectable': '(False)'}), "(value=u'~/scans', docstring='Directory for project folders',\n selectable=False)\n", (2421, 2504), False, 'from spreads.plugin import HookPlugin, SubcommandHookMixin, PluginOption, get_devices\n'), ((2575, 2698), 'spreads.plugin.PluginOption', 'PluginOption', ([], {'value': 'u"""~/.config/spreads/workflows.db"""', 'docstring': '"""Path to application database file"""', 'selectable': '(False)'}), "(value=u'~/.config/spreads/workflows.db', docstring=\n 'Path to application database file', selectable=False)\n", (2587, 2698), False, 'from spreads.plugin import HookPlugin, SubcommandHookMixin, PluginOption, get_devices\n'), ((2781, 2876), 'spreads.plugin.PluginOption', 'PluginOption', ([], {'value': 'u""""""', 'docstring': '"""Address of the postprocessing server"""', 'selectable': '(False)'}), "(value=u'', docstring='Address of the postprocessing server',\n selectable=False)\n", (2793, 2876), False, 'from spreads.plugin import HookPlugin, SubcommandHookMixin, PluginOption, get_devices\n'), ((3047, 3189), 'spreads.plugin.PluginOption', 'PluginOption', ([], {'value': '(False)', 'docstring': '"""Server runs on a standalone device dedicated to scanning (e.g. \'spreadpi\')."""', 'selectable': '(False)'}), '(value=False, docstring=\n "Server runs on a standalone device dedicated to scanning (e.g. \'spreadpi\')."\n , selectable=False)\n', (3059, 3189), False, 'from spreads.plugin import HookPlugin, SubcommandHookMixin, PluginOption, get_devices\n'), ((5218, 5252), 'logging.getLogger', 'logging.getLogger', (['"""huey.consumer"""'], {}), "('huey.consumer')\n", (5235, 5252), False, 'import logging\n'), ((5281, 5330), 'logging.getLogger', 'logging.getLogger', (['"""huey.consumer.ConsumerThread"""'], {}), "('huey.consumer.ConsumerThread')\n", (5298, 5330), False, 'import logging\n'), ((5909, 5928), 'spreads.plugin.get_devices', 'get_devices', (['config'], {}), '(config)\n', (5920, 5928), False, 'from spreads.plugin import HookPlugin, SubcommandHookMixin, PluginOption, get_devices\n'), ((1877, 1932), 'spreads.util.add_argument_from_option', 'add_argument_from_option', (['"""web"""', 'key', 'option', 'cmdparser'], {}), "('web', key, option, cmdparser)\n", (1901, 1932), False, 'from spreads.util import add_argument_from_option\n'), ((847, 869), 'netifaces.interfaces', 'netifaces.interfaces', ([], {}), '()\n', (867, 869), False, 'import netifaces\n'), ((1386, 1406), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (1404, 1406), False, 'import socket\n')] |
"""A tool to convert annotation files created with CVAT into ground-truth style images
for machine learning. The initial code was copied from:
https://gist.github.com/cheind/9850e35bb08cfe12500942fb8b55531f
originally written for a similar purpose for the tool BeaverDam (which produces json),
and was then adapted for use with CVAT (which produces xml).
"""
import cv2
import xml.etree.ElementTree as ET
import numpy as np
from tqdm import tqdm
# Create a list of BGR colours stored as 3-tuples of uint_8s
colours = [
[255, 0, 0], # Blue
[0, 255, 0], # Green
[0, 0, 255], # Red
[0, 255, 255], # Yellow
[255, 255, 0], # Cyan
[255, 0, 255], # Magenta
[192, 192, 192], # Silver
[0, 0, 128], # Maroon
[0, 128, 128], # Olive
[0, 165, 255], # Orange
]
def draw_annotations(video, annotations, display=False):
tree = ET.parse(args.ann)
root = tree.getroot()
# Create a list of 'track' nodes that are children of the root
tracks = [child for child in root if child.tag == "track"]
# Read the video in as a video object
cap = cv2.VideoCapture(args.video)
# Get a rough count of the number of frames in the video
rough_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Find the name/path of the video, without file type
name_index = -1
while args.video[name_index] != ".":
name_index -= 1
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*"DIVX")
framerate = cap.get(cv2.CAP_PROP_FPS)
(width, height) = (
int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
)
out = cv2.VideoWriter(
args.video[:name_index] + "_annotated.avi", fourcc, framerate, (width, height)
)
for frame_count in tqdm(range(rough_frame_count)):
# Read the next frame of the video
ret, frame = cap.read()
if not ret:
# Video is done, so break out of the loop
break
# Loop over the track objects. For all that have an annotation for this frame,
# draw a corresponding rectangle with a colour from the colours list
for track in tracks:
# Check that this track has any box nodes left
if len(track) > 0:
# Since the nodes are sorted by frame number, we only have to check the first one
box = track[0]
if int(box.attrib["frame"]) == frame_count:
# Draw the rectangle described by this 'box' node on this frame
# Cast the coordinates to floats, then to ints,
# as the cv2.rectangle function cannot handle float pixel values
# And int(str) cannot handle float strings
x_tl = int(float(box.attrib["xtl"]))
y_tl = int(float(box.attrib["ytl"]))
x_br = int(float(box.attrib["xbr"]))
y_br = int(float(box.attrib["ybr"]))
cv2.rectangle(
frame,
(x_tl, y_tl),
(x_br, y_br),
colours[int(track.attrib["id"]) % len(colours)],
2,
-1,
)
# delete this box from the track,so we can keep
# only checking the first box in the future
track.remove(box)
# Write the frame with boxes
out.write(frame)
# Display the resulting frame
if display:
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
frame_count += 1
# Keep going, as the frame count is not necessarily accurate so we might not be done
while True:
# Read the next frame of the video
ret, frame = cap.read()
if not ret:
# Video is done, so break out of the loop
break
# Loop over the track objects. For all that have an annotation for this frame,
# draw a corresponding rectangle with a colour from the colours list
for track in tracks:
# Check that this track has any box nodes left
if len(track) > 0:
# Since the nodes are sorted by frame number,
# we only have to check the first one
box = track[0]
if int(box.attrib["frame"]) == frame_count:
# Draw the rectangle described by this 'box' node on this frame
# Cast the coordinates to floats, then to ints,
# as the cv2.rectangle function cannot handle float pixel values
# And int(str) cannot handle float strings
x_tl = int(float(box.attrib["xtl"]))
y_tl = int(float(box.attrib["ytl"]))
x_br = int(float(box.attrib["xbr"]))
y_br = int(float(box.attrib["ybr"]))
cv2.rectangle(
frame,
(x_tl, y_tl),
(x_br, y_br),
colours[int(track.attrib["id"]) % len(colours)],
2,
-1,
)
# delete this box from the track,so we can keep
# only checking the first box in the future
track.remove(box)
# Write the frame with boxes
out.write(frame)
# Display the resulting frame
if display:
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
frame_count += 1
# Release everything
cap.release()
out.release()
cv2.destroyAllWindows()
def draw_groundtruth(video, annotations, display=False):
tree = ET.parse(args.ann)
root = tree.getroot()
# Create a list of 'track' nodes that are children of the root
tracks = [child for child in root if child.tag == "track"]
# Read the video in as a video object
cap = cv2.VideoCapture(args.video)
# Get a rough count of the number of frames in the video
rough_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Find the name/path of the video, without file type
name_index = -1
while args.video[name_index] != ".":
name_index -= 1
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*"DIVX")
framerate = cap.get(cv2.CAP_PROP_FPS)
(width, height) = (
int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
)
out = cv2.VideoWriter(
args.video[:name_index] + "_groundtruth.avi",
fourcc,
framerate,
(width, height),
0,
)
blank_frame = np.zeros((height, width), dtype=np.uint8)
for frame_count in tqdm(range(rough_frame_count)):
# Copy a new blank frame
frame = np.copy(blank_frame)
# Read the next frame but discard it, to check if the video is done yet
ret, _ = cap.read()
if not ret:
# Video is done, so break out of the loop
break
# Loop over the track objects. For all that have an annotation for this frame,
# draw a corresponding rectangle with a colour from the colours list
for track in tracks:
# Check that this track has any box nodes left
if len(track) > 0:
# Since the nodes are sorted by frame number,
# we only have to check the first one
box = track[0]
if int(box.attrib["frame"]) == frame_count:
# Draw the rectangle described by this 'box' node on this frame
# Cast the coordinates to floats, then to ints,
# as the cv2.rectangle function cannot handle float pixel values
# And int(str) cannot handle float strings
x_tl = int(float(box.attrib["xtl"]))
y_tl = int(float(box.attrib["ytl"]))
x_br = int(float(box.attrib["xbr"]))
y_br = int(float(box.attrib["ybr"]))
cv2.rectangle(frame, (x_tl, y_tl), (x_br, y_br), 255, cv2.FILLED)
# delete this box from the track, so we can keep
# only checking the first box in the future
track.remove(box)
# Write the frame with boxes
# Convert to BGR so video can be properly saved
# frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
out.write(frame)
# Display the resulting frame
if display:
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
frame_count += 1
# Keep going, as the frame count is not necessarily accurate so we might not be done
while True:
# Copy a new blank frame
frame = np.copy(blank_frame)
# Read the next frame but discard it, to check if the video is done yet
ret, og_frame = cap.read()
if not ret:
# Video is done, so break out of the loop
break
# Loop over the track objects. For all that have an annotation for this frame,
# draw a corresponding rectangle with a colour from the colours list
for track in tracks:
# Check that this track has any box nodes left
if len(track) > 0:
# Since the nodes are sorted by frame number, we only have to check the first one
box = track[0]
if int(box.attrib["frame"]) == frame_count:
# Draw the rectangle described by this 'box' node on this frame
# Cast the coordinates to floats, then to ints,
# as the cv2.rectangle function cannot handle float pixel values
# And int(str) cannot handle float strings
x_tl = int(float(box.attrib["xtl"]))
y_tl = int(float(box.attrib["ytl"]))
x_br = int(float(box.attrib["xbr"]))
y_br = int(float(box.attrib["ybr"]))
cv2.rectangle(frame, (x_tl, y_tl), (x_br, y_br), 255, cv2.FILLED)
# delete this box from the track, so we can keep
# only checking the first box in the future
track.remove(box)
# Write the frame with boxes
out.write(frame)
# Display the resulting frame
if display:
cv2.imshow("frame", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
frame_count += 1
# Release everything
cap.release()
out.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Draw annotations, either on original videos or as ground-truth saliency maps"
)
parser.add_argument(
"--folder",
"-f",
dest="folder",
help="Folder containing input files. Video and annotation file names must match exactly, with videos as .mp4 or .avi, and annotations as .xml",
required=False,
)
parser.add_argument(
"--video", "-vid", dest="video", help="Input video file", required=False
)
parser.add_argument(
"--annotation", "-ann", dest="ann", help="Dense annotation file", required=False
)
parser.add_argument(
"--bounding_boxes",
"-bb",
dest="drawing_function",
action="store_const",
const=draw_annotations,
default=draw_groundtruth,
)
parser.add_argument("--verbose", "-v", dest="verbose", action="store_true")
args = parser.parse_args()
# Check that either folder was given, or if not then both video and ann was given
if args.folder == None and (args.video == None or args.ann == None):
print(
"Error: invalid inputs given. Either -folder, or both -video and -ann must be specified."
)
if args.folder != None:
# Read all files in the folder and call the appropriate function on each
# video/annotation pair found
# TODO: implement
pass
else:
# Draw bounding boxes on the original video, or ground-truth saliency maps,
# depending on if -bb was specified
args.drawing_function(args.video, args.ann, args.verbose)
| [
"cv2.rectangle",
"numpy.copy",
"xml.etree.ElementTree.parse",
"argparse.ArgumentParser",
"cv2.VideoWriter",
"cv2.imshow",
"numpy.zeros",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.VideoWriter_fourcc",
"cv2.waitKey"
] | [((873, 891), 'xml.etree.ElementTree.parse', 'ET.parse', (['args.ann'], {}), '(args.ann)\n', (881, 891), True, 'import xml.etree.ElementTree as ET\n'), ((1101, 1129), 'cv2.VideoCapture', 'cv2.VideoCapture', (['args.video'], {}), '(args.video)\n', (1117, 1129), False, 'import cv2\n'), ((1464, 1495), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'DIVX'"], {}), "(*'DIVX')\n", (1486, 1495), False, 'import cv2\n'), ((1675, 1774), 'cv2.VideoWriter', 'cv2.VideoWriter', (["(args.video[:name_index] + '_annotated.avi')", 'fourcc', 'framerate', '(width, height)'], {}), "(args.video[:name_index] + '_annotated.avi', fourcc,\n framerate, (width, height))\n", (1690, 1774), False, 'import cv2\n'), ((5807, 5830), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5828, 5830), False, 'import cv2\n'), ((5901, 5919), 'xml.etree.ElementTree.parse', 'ET.parse', (['args.ann'], {}), '(args.ann)\n', (5909, 5919), True, 'import xml.etree.ElementTree as ET\n'), ((6129, 6157), 'cv2.VideoCapture', 'cv2.VideoCapture', (['args.video'], {}), '(args.video)\n', (6145, 6157), False, 'import cv2\n'), ((6492, 6523), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'DIVX'"], {}), "(*'DIVX')\n", (6514, 6523), False, 'import cv2\n'), ((6703, 6807), 'cv2.VideoWriter', 'cv2.VideoWriter', (["(args.video[:name_index] + '_groundtruth.avi')", 'fourcc', 'framerate', '(width, height)', '(0)'], {}), "(args.video[:name_index] + '_groundtruth.avi', fourcc,\n framerate, (width, height), 0)\n", (6718, 6807), False, 'import cv2\n'), ((6870, 6911), 'numpy.zeros', 'np.zeros', (['(height, width)'], {'dtype': 'np.uint8'}), '((height, width), dtype=np.uint8)\n', (6878, 6911), True, 'import numpy as np\n'), ((10851, 10874), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (10872, 10874), False, 'import cv2\n'), ((10938, 11063), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Draw annotations, either on original videos or as ground-truth saliency maps"""'}), "(description=\n 'Draw annotations, either on original videos or as ground-truth saliency maps'\n )\n", (10961, 11063), False, 'import argparse\n'), ((7017, 7037), 'numpy.copy', 'np.copy', (['blank_frame'], {}), '(blank_frame)\n', (7024, 7037), True, 'import numpy as np\n'), ((9041, 9061), 'numpy.copy', 'np.copy', (['blank_frame'], {}), '(blank_frame)\n', (9048, 9061), True, 'import numpy as np\n'), ((3604, 3630), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (3614, 3630), False, 'import cv2\n'), ((5616, 5642), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (5626, 5642), False, 'import cv2\n'), ((8761, 8787), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (8771, 8787), False, 'import cv2\n'), ((10660, 10686), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (10670, 10686), False, 'import cv2\n'), ((3646, 3660), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3657, 3660), False, 'import cv2\n'), ((5658, 5672), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (5669, 5672), False, 'import cv2\n'), ((8277, 8342), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x_tl, y_tl)', '(x_br, y_br)', '(255)', 'cv2.FILLED'], {}), '(frame, (x_tl, y_tl), (x_br, y_br), 255, cv2.FILLED)\n', (8290, 8342), False, 'import cv2\n'), ((8803, 8817), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (8814, 8817), False, 'import cv2\n'), ((10290, 10355), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x_tl, y_tl)', '(x_br, y_br)', '(255)', 'cv2.FILLED'], {}), '(frame, (x_tl, y_tl), (x_br, y_br), 255, cv2.FILLED)\n', (10303, 10355), False, 'import cv2\n'), ((10702, 10716), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (10713, 10716), False, 'import cv2\n')] |
import time
from selenium import webdriver
from lxml import etree
driver = webdriver.PhantomJS(executable_path='./phantomjs-2.1.1-macosx/bin/phantomjs')
# 获取第一页的数据
def get_html():
url = "https://detail.tmall.com/item.htm?id=531993957001&skuId=3609796167425&user_id=268451883&cat_id=2&is_b=1&rn=71b9b0aeb233411c4f59fe8c610bc34b"
driver.get(url)
time.sleep(5)
driver.execute_script('window.scrollBy(0,3000)')
time.sleep(2)
driver.execute_script('window.scrollBy(0,5000)')
time.sleep(2)
# 累计评价
btnNext = driver.find_element_by_xpath('//*[@id="J_TabBar"]/li[3]/a')
btnNext.click()
html = driver.page_source
return html
def get_comments(html):
source = etree.HTML(html)
commens = source.xpath("//*[@id='J_TabBar']/li[3]/a/em/text()")
print('评论数:', commens)
# 将评论转为int类型
commens = (int(commens[0]) / 20) + 1
# 获取到总评论
print('评论数:', int(commens))
return int(commens)
def parse_html(html):
html = etree.HTML(html)
commentlist = html.xpath("//*[@class='rate-grid']/table/tbody")
for comment in commentlist:
# 评论
vercomment = comment.xpath(
"./tr/td[@class='tm-col-master']/div[@class='tm-rate-content']/div[@class='tm-rate-fulltxt']/text()")
# 机器类型
verphone = comment.xpath("./tr/td[@class='col-meta']/div[@class='rate-sku']/p[@title]/text()")
print(vercomment)
print(verphone)
# 用户(头尾各一个字,中间用****代替)
veruser = comment.xpath("./tr/td[@class='col-author']/div[@class='rate-user-info']/text()")
print(veruser)
def next_button_work(num):
if num != 0:
driver.execute_script('window.scrollBy(0,3000)')
time.sleep(2)
try:
driver.find_element_by_css_selector('#J_Reviews > div > div.rate-page > div > a:last-child').click()
except Exception as e:
print(e)
time.sleep(2)
driver.execute_script('window.scrollBy(0,3000)')
time.sleep(2)
driver.execute_script('window.scrollBy(0,5000)')
time.sleep(2)
html = driver.page_source
parse_html(html)
def selenuim_work(html):
parse_html(html)
next_button_work(1)
pass
def gettotalpagecomments(comments):
html = get_html()
for i in range(0, comments):
selenuim_work(html)
data = get_html()
# 得到评论
commens = get_comments(data)
# 根据评论内容进行遍历
gettotalpagecomments(commens)
| [
"selenium.webdriver.PhantomJS",
"lxml.etree.HTML",
"time.sleep"
] | [((76, 153), 'selenium.webdriver.PhantomJS', 'webdriver.PhantomJS', ([], {'executable_path': '"""./phantomjs-2.1.1-macosx/bin/phantomjs"""'}), "(executable_path='./phantomjs-2.1.1-macosx/bin/phantomjs')\n", (95, 153), False, 'from selenium import webdriver\n'), ((359, 372), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (369, 372), False, 'import time\n'), ((430, 443), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (440, 443), False, 'import time\n'), ((501, 514), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (511, 514), False, 'import time\n'), ((706, 722), 'lxml.etree.HTML', 'etree.HTML', (['html'], {}), '(html)\n', (716, 722), False, 'from lxml import etree\n'), ((980, 996), 'lxml.etree.HTML', 'etree.HTML', (['html'], {}), '(html)\n', (990, 996), False, 'from lxml import etree\n'), ((1693, 1706), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1703, 1706), False, 'import time\n'), ((1894, 1907), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1904, 1907), False, 'import time\n'), ((1973, 1986), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1983, 1986), False, 'import time\n'), ((2052, 2065), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (2062, 2065), False, 'import time\n')] |
"""
"""
from flask import Flask
import os
import json
from molder import db, site
def create_app(instance_path=None, test_config=None):
"""
Create and configure the molder Flask application.
Parameters
----------
instance_path : :class:`str`, optional
Path to the instance directory of the application.
test_config : :class:`dict`, optional
App config parameters used during testing.
Returns
-------
:class:`flask.Flask`
The application object.
"""
app = Flask(__name__,
instance_path=instance_path,
instance_relative_config=True)
if test_config is None:
# Load default config values.
app.config.from_object('molder.default_settings')
# Load the instance config, if it exists, when not testing.
app.config.from_pyfile('config.py', silent=True)
else:
# Load the test config passed in.
app.config.update(test_config)
# Ensure the instance folder exists.
if not os.path.exists(app.instance_path):
os.makedirs(app.instance_path)
# Load database.json and shared.json into memory.
with app.open_resource('database/database.json') as f:
app.mols = json.loads(f.read().decode('ascii'))
with app.open_resource('database/shared.json') as f:
app.shared_mols = set(json.loads(f.read().decode('ascii')))
# Create the database if it does not yet exist.
db.init_app(app)
# Apply the molder blueprint to the app.
app.register_blueprint(site.bp)
return app
| [
"os.path.exists",
"molder.db.init_app",
"os.makedirs",
"flask.Flask"
] | [((532, 607), 'flask.Flask', 'Flask', (['__name__'], {'instance_path': 'instance_path', 'instance_relative_config': '(True)'}), '(__name__, instance_path=instance_path, instance_relative_config=True)\n', (537, 607), False, 'from flask import Flask\n'), ((1460, 1476), 'molder.db.init_app', 'db.init_app', (['app'], {}), '(app)\n', (1471, 1476), False, 'from molder import db, site\n'), ((1034, 1067), 'os.path.exists', 'os.path.exists', (['app.instance_path'], {}), '(app.instance_path)\n', (1048, 1067), False, 'import os\n'), ((1077, 1107), 'os.makedirs', 'os.makedirs', (['app.instance_path'], {}), '(app.instance_path)\n', (1088, 1107), False, 'import os\n')] |
from PIL import Image, ImageDraw, ImageFont
from urllib.request import urlopen
from textwrap import wrap
import os
BOLD_FONT_URL = "https://cdn.jsdelivr.net/gh/spoqa/spoqa-han-sans@latest/Subset/SpoqaHanSansNeo/SpoqaHanSansNeo-Bold.ttf"
LIGHT_FONT_URL = "https://cdn.jsdelivr.net/gh/spoqa/spoqa-han-sans@latest/Subset/SpoqaHanSansNeo/SpoqaHanSansNeo-Regular.ttf"
OPENGRAPH_SIZE = (1200, 600)
OFFSET_X = 180
OFFSET_Y = 90
WHITE = "#fff"
BLACK = "#333"
GRAY = "#777"
BLOG_NAME = "Null Space"
DEFAULT_INFO_TEXT = "a blog by sp301415"
POSTPATH = "../_posts"
titlefont = ImageFont.truetype(urlopen(BOLD_FONT_URL), size=80)
infofont = ImageFont.truetype(urlopen(LIGHT_FONT_URL), size=40)
if not os.path.exists("../assets/ogimg"):
os.mkdir("../assets/ogimg")
for filename in os.listdir(POSTPATH):
if not filename.endswith(".md"):
continue
# Make image
img = Image.new("RGB", OPENGRAPH_SIZE, color=WHITE)
res = ImageDraw.Draw(img)
# Generate text to write
text = ""
with open(POSTPATH + "/" + filename, "r") as f:
for line in f.readlines():
if line.startswith("title"):
text = line[line.find(":") + 1 :].strip()
break
titlelines = wrap(text, width=15)
titleheight = 0
for line in titlelines:
titleheight += titlefont.getsize(line)[1]
for line in titlelines[:-1]:
titleheight += titlefont.getsize(line)[1] * 0.2
infoheight = infofont.getsize(BLOG_NAME)[1]
# Upper margin: OFFSET_Y, Lower margin: OFFSET_Y + infoheight
# Center text accordingly.
middle = (OFFSET_Y + (OPENGRAPH_SIZE[1] - OFFSET_Y)) / 2 - infoheight
titlepos = middle - titleheight / 2
y = titlepos
for line in titlelines:
res.text((OFFSET_X, y), line, font=titlefont, fill=BLACK)
y += titlefont.getsize(line)[1] * 1.2
res.text(
(OFFSET_X, OPENGRAPH_SIZE[1] - OFFSET_Y - infoheight),
BLOG_NAME,
font=infofont,
fill=GRAY,
)
filename = filename.strip(".md")
filename = "-".join(filename.split("-")[3:])
img.save(f"../assets/ogimg/{filename}.jpg")
# Generate Default image.
img = Image.new("RGB", OPENGRAPH_SIZE, color=WHITE)
res = ImageDraw.Draw(img)
titleheight = titlefont.getsize(BLOG_NAME)[1]
infoheight = infofont.getsize(DEFAULT_INFO_TEXT)[1]
middle = (OFFSET_Y + (OPENGRAPH_SIZE[1] - OFFSET_Y)) / 2 - infoheight
titlepos = middle - titleheight / 2
res.text((OFFSET_X, titlepos), BLOG_NAME, font=titlefont, fill=BLACK)
res.text(
(OFFSET_X, OPENGRAPH_SIZE[1] - OFFSET_Y - infoheight),
DEFAULT_INFO_TEXT,
font=infofont,
fill=GRAY,
)
img.save(f"../assets/ogimg/default.jpg")
| [
"os.path.exists",
"os.listdir",
"PIL.Image.new",
"PIL.ImageDraw.Draw",
"os.mkdir",
"textwrap.wrap",
"urllib.request.urlopen"
] | [((780, 800), 'os.listdir', 'os.listdir', (['POSTPATH'], {}), '(POSTPATH)\n', (790, 800), False, 'import os\n'), ((2170, 2215), 'PIL.Image.new', 'Image.new', (['"""RGB"""', 'OPENGRAPH_SIZE'], {'color': 'WHITE'}), "('RGB', OPENGRAPH_SIZE, color=WHITE)\n", (2179, 2215), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2222, 2241), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (2236, 2241), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((591, 613), 'urllib.request.urlopen', 'urlopen', (['BOLD_FONT_URL'], {}), '(BOLD_FONT_URL)\n', (598, 613), False, 'from urllib.request import urlopen\n'), ((654, 677), 'urllib.request.urlopen', 'urlopen', (['LIGHT_FONT_URL'], {}), '(LIGHT_FONT_URL)\n', (661, 677), False, 'from urllib.request import urlopen\n'), ((696, 729), 'os.path.exists', 'os.path.exists', (['"""../assets/ogimg"""'], {}), "('../assets/ogimg')\n", (710, 729), False, 'import os\n'), ((735, 762), 'os.mkdir', 'os.mkdir', (['"""../assets/ogimg"""'], {}), "('../assets/ogimg')\n", (743, 762), False, 'import os\n'), ((884, 929), 'PIL.Image.new', 'Image.new', (['"""RGB"""', 'OPENGRAPH_SIZE'], {'color': 'WHITE'}), "('RGB', OPENGRAPH_SIZE, color=WHITE)\n", (893, 929), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((940, 959), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (954, 959), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1230, 1250), 'textwrap.wrap', 'wrap', (['text'], {'width': '(15)'}), '(text, width=15)\n', (1234, 1250), False, 'from textwrap import wrap\n')] |
import os
import yaml
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
dir_path = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture()
def AnsibleDefaults():
with open(os.path.join(dir_path, './../../../defaults/main.yml'), 'r') as stream:
return yaml.load(stream)
@pytest.fixture()
def AnsiblePlaybook():
with open(os.path.join(dir_path, './../playbook.yml'), 'r') as stream:
return yaml.load(stream)
@pytest.mark.parametrize('minio_bin_var', [
'minio_server_bin',
'minio_client_bin',
])
def test_minio_installed(host, AnsibleDefaults, minio_bin_var):
f = host.file(AnsibleDefaults[minio_bin_var])
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
assert oct(f.mode) == '0o755'
def test_minio_server_data_directory(host, AnsibleDefaults, AnsiblePlaybook):
playbpook = AnsiblePlaybook[0]
for role in playbpook['roles']:
layoutName = role['vars']['minio_layout']
datadir = "/var/lib/minio-{}".format(layoutName)
d = host.file(datadir)
assert d.is_directory
assert d.exists
assert d.user == AnsibleDefaults['minio_user']
assert d.group == AnsibleDefaults['minio_group']
assert oct(d.mode) == '0o750'
def test_minio_server_webservers(host, AnsibleDefaults):
for layoutName in AnsibleDefaults['minio_layouts'].keys():
server_addr = AnsibleDefaults['minio_layouts'][layoutName]['server_addr']
addr = "tcp://127.0.0.1{}".format(server_addr)
host.socket(addr).is_listening
| [
"os.path.join",
"yaml.load",
"pytest.mark.parametrize",
"pytest.fixture",
"os.path.abspath"
] | [((257, 273), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (271, 273), False, 'import pytest\n'), ((418, 434), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (432, 434), False, 'import pytest\n'), ((569, 655), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""minio_bin_var"""', "['minio_server_bin', 'minio_client_bin']"], {}), "('minio_bin_var', ['minio_server_bin',\n 'minio_client_bin'])\n", (592, 655), False, 'import pytest\n'), ((227, 252), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (242, 252), False, 'import os\n'), ((398, 415), 'yaml.load', 'yaml.load', (['stream'], {}), '(stream)\n', (407, 415), False, 'import yaml\n'), ((548, 565), 'yaml.load', 'yaml.load', (['stream'], {}), '(stream)\n', (557, 565), False, 'import yaml\n'), ((311, 365), 'os.path.join', 'os.path.join', (['dir_path', '"""./../../../defaults/main.yml"""'], {}), "(dir_path, './../../../defaults/main.yml')\n", (323, 365), False, 'import os\n'), ((472, 515), 'os.path.join', 'os.path.join', (['dir_path', '"""./../playbook.yml"""'], {}), "(dir_path, './../playbook.yml')\n", (484, 515), False, 'import os\n')] |
"""
resourceview.py
Contains administrative views for working with resources.
"""
from datetime import date
from admin_helpers import *
from sqlalchemy import or_, not_, func
from flask import current_app, redirect, flash, request, url_for
from flask.ext.admin import BaseView, expose
from flask.ext.admin.actions import action
from flask.ext.admin.contrib.sqla import ModelView
from wtforms import DecimalField, validators
import geopy
from geopy.exc import *
from remedy.rad.models import Resource, Category
from remedy.rad.geocoder import Geocoder
class ResourceView(AdminAuthMixin, ModelView):
"""
An administrative view for working with resources.
"""
column_list = ('name', 'organization',
'address', 'url',
'source', 'last_updated')
column_default_sort = 'name'
column_searchable_list = ('name','description','organization','notes',)
column_filters = ('visible','source','npi','date_verified',)
form_excluded_columns = ('date_created', 'last_updated',
'category_text', 'reviews')
create_template = 'admin/resource_create.html'
edit_template = 'admin/resource_edit.html'
column_labels = dict(npi='NPI', url='URL')
column_descriptions = dict(npi='The National Provider Identifier (NPI) of the resource.',
hours='The hours of operation for the resource.',
source='The source of the resource\'s information.',
notes='Administrative notes for the resource, not visible to end users.',
date_verified='The date the resource was last verified by an administrator.')
def scaffold_form(self):
"""
Scaffolds the creation/editing form so that the latitude
and longitude fields are optional, but can still be set
by the Google Places API integration.
"""
form_class = super(ResourceView, self).scaffold_form()
# Override the latitude/longitude fields to be optional
form_class.latitude = DecimalField(validators=[validators.Optional()])
form_class.longitude = DecimalField(validators=[validators.Optional()])
return form_class
@action('togglevisible',
'Toggle Visibility',
'Are you sure you wish to toggle visibility for the selected resources?')
def action_togglevisible(self, ids):
"""
Attempts to toggle visibility for each of the specified resources.
Args:
ids: The list of resource IDs, indicating which resources
should have their visibility toggled.
"""
# Load all resources by the set of IDs
target_resources = self.get_query().filter(self.model.id.in_(ids)).all()
# Build a list of all the results
results = []
if len(target_resources) > 0:
for resource in target_resources:
# Build a helpful message string to use for messages.
resource_str = 'resource #' + str(resource.id) + ' (' + resource.name + ')'
visible_status = ''
try:
if not resource.visible:
resource.visible = True
visible_status = ' as visible'
else:
resource.visible = False
visible_status = ' as not visible'
except Exception as ex:
results.append('Error changing ' + resource_str + ': ' + str(ex))
else:
results.append('Marked ' + resource_str + visible_status + '.')
# Save our changes.
self.session.commit()
else:
results.append('No resources were selected.')
# Flash the results of everything
flash("\n".join(msg for msg in results))
@action('markverified',
'Mark Verified',
'Are you sure you wish to mark the selected resources as verified?')
def action_markverified(self, ids):
"""
Attempts to mark each of the specified resources as verified
on the current date.
Args:
ids: The list of resource IDs, indicating which resources
should be marked as verified.
"""
# Load all resources by the set of IDs
target_resources = self.get_query().filter(self.model.id.in_(ids)).all()
# Build a list of all the results
results = []
if len(target_resources) > 0:
for resource in target_resources:
# Build a helpful message string to use for messages.
resource_str = 'resource #' + str(resource.id) + ' (' + resource.name + ')'
try:
resource.date_verified = date.today()
except Exception as ex:
results.append('Error changing ' + resource_str + ': ' + str(ex))
else:
results.append('Marked ' + resource_str + ' as verified.')
# Save our changes.
self.session.commit()
else:
results.append('No resources were selected.')
# Flash the results of everything
flash("\n".join(msg for msg in results))
@action('assigncategories', 'Assign Categories')
def action_assigncategories(self, ids):
"""
Sets up a redirection action for mass-assigning categories
to the specified resources.
Args:
ids: The list of resource IDs that should be updated.
"""
return redirect(url_for('resourcecategoryassignview.index', ids=ids))
def __init__(self, session, **kwargs):
super(ResourceView, self).__init__(Resource, session, **kwargs)
class ResourceRequiringGeocodingView(ResourceView):
"""
An administrative view for working with resources that need geocoding.
"""
column_list = ('name', 'organization', 'address', 'source')
# Disable model creation/deletion
can_create = False
can_delete = False
def get_query(self):
"""
Returns the query for the model type.
Returns:
The query for the model type.
"""
query = self.session.query(self.model)
return self.prepare_geocode_query(query)
def get_count_query(self):
"""
Returns the count query for the model type.
Returns:
The count query for the model type.
"""
query = self.session.query(func.count('*')).select_from(self.model)
return self.prepare_geocode_query(query)
def prepare_geocode_query(self, query):
"""
Prepares the provided query by ensuring that
all relevant geocoding-related filters have been applied.
Args:
query: The query to update.
Returns:
The updated query.
"""
# Ensure an address is defined
query = query.filter(self.model.address != None)
query = query.filter(self.model.address != '')
# Ensure at least one geocoding field is missing
query = query.filter(or_(self.model.latitude == None,
self.model.longitude == None))
return query
@action('geocode',
'Geocode')
def action_geocode(self, ids):
"""
Attempts to geocode each of the specified resources.
Args:
ids: The list of resource IDs, indicating which resources
should be geocoded.
"""
# Load all resources by the set of IDs
target_resources = self.get_query().filter(self.model.id.in_(ids)).all()
# Build a list of all the results
results = []
if len(target_resources) > 0:
# Set up the geocoder, and then try to geocode each resource
geocoder = Geocoder(api_key=current_app.config.get('MAPS_SERVER_KEY'))
for resource in target_resources:
# Build a helpful message string to use for errors.
resource_str = 'resource #' + str(resource.id) + ' (' + resource.name + ')'
try:
geocoder.geocode(resource)
except geopy.exc.GeopyError as gpex:
# Handle Geopy errors separately
exc_type = ''
# Attempt to infer some extra information based on the exception type
if isinstance(gpex, geopy.exc.GeocoderQuotaExceeded):
exc_type = 'quota exceeded'
elif isinstance(gpex, geopy.exc.GeocoderAuthenticationFailure):
exc_type = 'authentication failure'
elif isinstance(gpex, geopy.exc.GeocoderInsufficientPrivileges):
exc_type = 'insufficient privileges'
elif isinstance(gpex, geopy.exc.GeocoderUnavailable):
exc_type = 'server unavailable'
elif isinstance(gpex, geopy.exc.GeocoderTimedOut):
exc_type = 'timed out'
elif isinstance(gpex, geopy.exc.GeocoderQueryError):
exc_type = 'query error'
if len(exc_type) > 0:
exc_type = '(' + exc_type + ') '
results.append('Error geocoding ' + resource_str + ': ' + exc_type + str(gpex))
except Exception as ex:
results.append('Error geocoding ' + resource_str + ': ' + str(ex))
else:
results.append('Geocoded ' + resource_str + '.')
# Save our changes.
self.session.commit()
else:
results.append('No resources were selected.')
# Flash the results of everything
flash("\n".join(msg for msg in results))
@action('removeaddress',
'Remove Address',
'Are you sure you wish to remove address information from the selected resources?')
def action_remove_address(self, ids):
"""
Attempts to remove address information from each of the specified resources.
Args:
ids: The list of resource IDs, indicating which resources
should have address information stripped.
"""
# Load all resources by the set of IDs
target_resources = self.get_query().filter(self.model.id.in_(ids)).all()
# Build a list of all the results
results = []
if len(target_resources) > 0:
for resource in target_resources:
# Build a helpful message string to use for errors.
resource_str = 'resource #' + str(resource.id) + ' (' + resource.name + ')'
try:
resource.address = None
resource.latitude = None
resource.longitude = None
resource.location = None
except Exception as ex:
results.append('Error updating ' + resource_str + ': ' + str(ex))
else:
results.append('Removed address information from ' + resource_str + '.')
# Save our changes.
self.session.commit()
else:
results.append('No resources were selected.')
# Flash the results of everything
flash("\n".join(msg for msg in results))
def __init__(self, session, **kwargs):
# Because we're invoking the ResourceView constructor,
# we don't need to pass in the ResourceModel.
super(ResourceRequiringGeocodingView, self).__init__(session, **kwargs)
class ResourceRequiringCategoriesView(ResourceView):
"""
An administrative view for working with resources that need categories.
"""
column_list = ('name', 'organization', 'address', 'source')
# Disable model creation/deletion
can_create = False
can_delete = False
def get_query(self):
"""
Returns the query for the model type.
Returns:
The query for the model type.
"""
query = self.session.query(self.model)
return self.prepare_category_query(query)
def get_count_query(self):
"""
Returns the count query for the model type.
Returns:
The count query for the model type.
"""
query = self.session.query(func.count('*')).select_from(self.model)
return self.prepare_category_query(query)
def prepare_category_query(self, query):
"""
Prepares the provided query by ensuring that
filtering out resources with categories has been applied.
Args:
query: The query to update.
Returns:
The updated query.
"""
# Ensure there are no categories defined
query = query.filter(not_(self.model.categories.any()))
return query
def __init__(self, session, **kwargs):
# Because we're invoking the ResourceView constructor,
# we don't need to pass in the ResourceModel.
super(ResourceRequiringCategoriesView, self).__init__(session, **kwargs)
class ResourceCategoryAssignView(AdminAuthMixin, BaseView):
"""
The view for mass-assigning resources to categories.
"""
# Not visible in the menu.
def is_visible(self):
return False
@expose('/', methods=['GET', 'POST'])
def index(self):
"""
A view for mass-assigning resources to categories.
"""
# Load all resources by the set of IDs
target_resources = Resource.query.filter(Resource.id.in_(request.args.getlist('ids')))
target_resources = target_resources.order_by(Resource.name.asc()).all()
# Make sure we have some, and go back to the resources
# view (for assigning categories) if we don't.
if len(target_resources) == 0:
flash('At least one resource must be selected.')
return redirect(url_for('category-resourceview.index_view'))
if request.method == 'GET':
# Get all categories
available_categories = Category.query.order_by(Category.name.asc())
available_categories = available_categories.all()
# Return the view for assigning categories
return self.render('admin/resource_assign_categories.html',
ids = request.args.getlist('ids'),
resources = target_resources,
categories = available_categories)
else:
# Get the selected categories - use request.form,
# not request.args
target_categories = Category.query.filter(Category.id.in_(request.form.getlist('categories'))).all()
if len(target_categories) > 0:
# Build a list of all the results
results = []
for resource in target_resources:
# Build a helpful message string to use for resources.
resource_str = 'resource #' + str(resource.id) + ' (' + resource.name + ')'
try:
# Assign all categories
for category in target_categories:
# Make sure we're not double-adding
if not category in resource.categories:
resource.categories.append(category)
except Exception as ex:
results.append('Error updating ' + resource_str + ': ' + str(ex))
else:
results.append('Updated ' + resource_str + '.')
# Save our changes.
self.session.commit()
# Flash the results of everything
flash("\n".join(msg for msg in results))
else:
flash('At least one category must be selected.')
return redirect(url_for('category-resourceview.index_view'))
def __init__(self, session, **kwargs):
self.session = session
super(ResourceCategoryAssignView, self).__init__(**kwargs)
class ResourceRequiringNpiView(ResourceView):
"""
An administrative view for working with resources that need NPI values.
"""
# Disable model creation/deletion
can_create = False
can_delete = False
def get_query(self):
"""
Returns the query for the model type.
Returns:
The query for the model type.
"""
query = self.session.query(self.model)
return self.prepare_npi_query(query)
def get_count_query(self):
"""
Returns the count query for the model type.
Returns:
The count query for the model type.
"""
query = self.session.query(func.count('*')).select_from(self.model)
return self.prepare_npi_query(query)
def prepare_npi_query(self, query):
"""
Prepares the provided query by ensuring that
filtering out resources with NPIs has been applied.
Args:
query: The query to update.
Returns:
The updated query.
"""
# Ensure that an NPI is missing
query = query.filter(or_(self.model.npi == None,
self.model.npi == ''))
return query
def __init__(self, session, **kwargs):
# Because we're invoking the ResourceView constructor,
# we don't need to pass in the ResourceModel.
super(ResourceRequiringNpiView, self).__init__(session, **kwargs)
| [
"sqlalchemy.func.count",
"flask.ext.admin.expose",
"flask.flash",
"flask.request.form.getlist",
"flask.ext.admin.actions.action",
"flask.url_for",
"flask.request.args.getlist",
"remedy.rad.models.Category.name.asc",
"wtforms.validators.Optional",
"remedy.rad.models.Resource.name.asc",
"datetime.... | [((2137, 2259), 'flask.ext.admin.actions.action', 'action', (['"""togglevisible"""', '"""Toggle Visibility"""', '"""Are you sure you wish to toggle visibility for the selected resources?"""'], {}), "('togglevisible', 'Toggle Visibility',\n 'Are you sure you wish to toggle visibility for the selected resources?')\n", (2143, 2259), False, 'from flask.ext.admin.actions import action\n'), ((3803, 3915), 'flask.ext.admin.actions.action', 'action', (['"""markverified"""', '"""Mark Verified"""', '"""Are you sure you wish to mark the selected resources as verified?"""'], {}), "('markverified', 'Mark Verified',\n 'Are you sure you wish to mark the selected resources as verified?')\n", (3809, 3915), False, 'from flask.ext.admin.actions import action\n'), ((5208, 5255), 'flask.ext.admin.actions.action', 'action', (['"""assigncategories"""', '"""Assign Categories"""'], {}), "('assigncategories', 'Assign Categories')\n", (5214, 5255), False, 'from flask.ext.admin.actions import action\n'), ((7181, 7209), 'flask.ext.admin.actions.action', 'action', (['"""geocode"""', '"""Geocode"""'], {}), "('geocode', 'Geocode')\n", (7187, 7209), False, 'from flask.ext.admin.actions import action\n'), ((9854, 9988), 'flask.ext.admin.actions.action', 'action', (['"""removeaddress"""', '"""Remove Address"""', '"""Are you sure you wish to remove address information from the selected resources?"""'], {}), "('removeaddress', 'Remove Address',\n 'Are you sure you wish to remove address information from the selected resources?'\n )\n", (9860, 9988), False, 'from flask.ext.admin.actions import action\n'), ((13382, 13418), 'flask.ext.admin.expose', 'expose', (['"""/"""'], {'methods': "['GET', 'POST']"}), "('/', methods=['GET', 'POST'])\n", (13388, 13418), False, 'from flask.ext.admin import BaseView, expose\n'), ((5532, 5584), 'flask.url_for', 'url_for', (['"""resourcecategoryassignview.index"""'], {'ids': 'ids'}), "('resourcecategoryassignview.index', ids=ids)\n", (5539, 5584), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((7077, 7139), 'sqlalchemy.or_', 'or_', (['(self.model.latitude == None)', '(self.model.longitude == None)'], {}), '(self.model.latitude == None, self.model.longitude == None)\n', (7080, 7139), False, 'from sqlalchemy import or_, not_, func\n'), ((13915, 13963), 'flask.flash', 'flash', (['"""At least one resource must be selected."""'], {}), "('At least one resource must be selected.')\n", (13920, 13963), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((17284, 17333), 'sqlalchemy.or_', 'or_', (['(self.model.npi == None)', "(self.model.npi == '')"], {}), "(self.model.npi == None, self.model.npi == '')\n", (17287, 17333), False, 'from sqlalchemy import or_, not_, func\n'), ((13635, 13662), 'flask.request.args.getlist', 'request.args.getlist', (['"""ids"""'], {}), "('ids')\n", (13655, 13662), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((13992, 14035), 'flask.url_for', 'url_for', (['"""category-resourceview.index_view"""'], {}), "('category-resourceview.index_view')\n", (13999, 14035), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((14174, 14193), 'remedy.rad.models.Category.name.asc', 'Category.name.asc', ([], {}), '()\n', (14191, 14193), False, 'from remedy.rad.models import Resource, Category\n'), ((15900, 15948), 'flask.flash', 'flash', (['"""At least one category must be selected."""'], {}), "('At least one category must be selected.')\n", (15905, 15948), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((15978, 16021), 'flask.url_for', 'url_for', (['"""category-resourceview.index_view"""'], {}), "('category-resourceview.index_view')\n", (15985, 16021), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((2000, 2021), 'wtforms.validators.Optional', 'validators.Optional', ([], {}), '()\n', (2019, 2021), False, 'from wtforms import DecimalField, validators\n'), ((2080, 2101), 'wtforms.validators.Optional', 'validators.Optional', ([], {}), '()\n', (2099, 2101), False, 'from wtforms import DecimalField, validators\n'), ((4730, 4742), 'datetime.date.today', 'date.today', ([], {}), '()\n', (4740, 4742), False, 'from datetime import date\n'), ((6457, 6472), 'sqlalchemy.func.count', 'func.count', (['"""*"""'], {}), "('*')\n", (6467, 6472), False, 'from sqlalchemy import or_, not_, func\n'), ((7805, 7846), 'flask.current_app.config.get', 'current_app.config.get', (['"""MAPS_SERVER_KEY"""'], {}), "('MAPS_SERVER_KEY')\n", (7827, 7846), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((12402, 12417), 'sqlalchemy.func.count', 'func.count', (['"""*"""'], {}), "('*')\n", (12412, 12417), False, 'from sqlalchemy import or_, not_, func\n'), ((13718, 13737), 'remedy.rad.models.Resource.name.asc', 'Resource.name.asc', ([], {}), '()\n', (13735, 13737), False, 'from remedy.rad.models import Resource, Category\n'), ((14407, 14434), 'flask.request.args.getlist', 'request.args.getlist', (['"""ids"""'], {}), "('ids')\n", (14427, 14434), False, 'from flask import current_app, redirect, flash, request, url_for\n'), ((16847, 16862), 'sqlalchemy.func.count', 'func.count', (['"""*"""'], {}), "('*')\n", (16857, 16862), False, 'from sqlalchemy import or_, not_, func\n'), ((14710, 14744), 'flask.request.form.getlist', 'request.form.getlist', (['"""categories"""'], {}), "('categories')\n", (14730, 14744), False, 'from flask import current_app, redirect, flash, request, url_for\n')] |
from typing import List
import tensorflow as tf
from tensorflow.keras.layers import Embedding, Layer, LSTM, Input
from src.features.preprocessing import get_embedding, get_text_vectorization
from src.models.embedding_model import EmbeddingModel
class LSTMModel(EmbeddingModel):
def __init__(self):
super().__init__()
self._embedding = get_embedding()
self._text_vectorization = get_text_vectorization()
self._trainable_layers = [
Input(shape=(1,), dtype=tf.string),
LSTM()
]
@property
def embedding(self) -> Embedding:
return self._embedding
@property
def trainable_layers(self) -> List[Layer]:
return self._trainable_layers
| [
"src.features.preprocessing.get_embedding",
"src.features.preprocessing.get_text_vectorization",
"tensorflow.keras.layers.LSTM",
"tensorflow.keras.layers.Input"
] | [((360, 375), 'src.features.preprocessing.get_embedding', 'get_embedding', ([], {}), '()\n', (373, 375), False, 'from src.features.preprocessing import get_embedding, get_text_vectorization\n'), ((411, 435), 'src.features.preprocessing.get_text_vectorization', 'get_text_vectorization', ([], {}), '()\n', (433, 435), False, 'from src.features.preprocessing import get_embedding, get_text_vectorization\n'), ((484, 518), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(1,)', 'dtype': 'tf.string'}), '(shape=(1,), dtype=tf.string)\n', (489, 518), False, 'from tensorflow.keras.layers import Embedding, Layer, LSTM, Input\n'), ((532, 538), 'tensorflow.keras.layers.LSTM', 'LSTM', ([], {}), '()\n', (536, 538), False, 'from tensorflow.keras.layers import Embedding, Layer, LSTM, Input\n')] |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'GetDedicatedVmHostResult',
'AwaitableGetDedicatedVmHostResult',
'get_dedicated_vm_host',
]
@pulumi.output_type
class GetDedicatedVmHostResult:
"""
A collection of values returned by getDedicatedVmHost.
"""
def __init__(__self__, availability_domain=None, compartment_id=None, dedicated_vm_host_id=None, dedicated_vm_host_shape=None, defined_tags=None, display_name=None, fault_domain=None, freeform_tags=None, id=None, remaining_memory_in_gbs=None, remaining_ocpus=None, state=None, time_created=None, total_memory_in_gbs=None, total_ocpus=None):
if availability_domain and not isinstance(availability_domain, str):
raise TypeError("Expected argument 'availability_domain' to be a str")
pulumi.set(__self__, "availability_domain", availability_domain)
if compartment_id and not isinstance(compartment_id, str):
raise TypeError("Expected argument 'compartment_id' to be a str")
pulumi.set(__self__, "compartment_id", compartment_id)
if dedicated_vm_host_id and not isinstance(dedicated_vm_host_id, str):
raise TypeError("Expected argument 'dedicated_vm_host_id' to be a str")
pulumi.set(__self__, "dedicated_vm_host_id", dedicated_vm_host_id)
if dedicated_vm_host_shape and not isinstance(dedicated_vm_host_shape, str):
raise TypeError("Expected argument 'dedicated_vm_host_shape' to be a str")
pulumi.set(__self__, "dedicated_vm_host_shape", dedicated_vm_host_shape)
if defined_tags and not isinstance(defined_tags, dict):
raise TypeError("Expected argument 'defined_tags' to be a dict")
pulumi.set(__self__, "defined_tags", defined_tags)
if display_name and not isinstance(display_name, str):
raise TypeError("Expected argument 'display_name' to be a str")
pulumi.set(__self__, "display_name", display_name)
if fault_domain and not isinstance(fault_domain, str):
raise TypeError("Expected argument 'fault_domain' to be a str")
pulumi.set(__self__, "fault_domain", fault_domain)
if freeform_tags and not isinstance(freeform_tags, dict):
raise TypeError("Expected argument 'freeform_tags' to be a dict")
pulumi.set(__self__, "freeform_tags", freeform_tags)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if remaining_memory_in_gbs and not isinstance(remaining_memory_in_gbs, float):
raise TypeError("Expected argument 'remaining_memory_in_gbs' to be a float")
pulumi.set(__self__, "remaining_memory_in_gbs", remaining_memory_in_gbs)
if remaining_ocpus and not isinstance(remaining_ocpus, float):
raise TypeError("Expected argument 'remaining_ocpus' to be a float")
pulumi.set(__self__, "remaining_ocpus", remaining_ocpus)
if state and not isinstance(state, str):
raise TypeError("Expected argument 'state' to be a str")
pulumi.set(__self__, "state", state)
if time_created and not isinstance(time_created, str):
raise TypeError("Expected argument 'time_created' to be a str")
pulumi.set(__self__, "time_created", time_created)
if total_memory_in_gbs and not isinstance(total_memory_in_gbs, float):
raise TypeError("Expected argument 'total_memory_in_gbs' to be a float")
pulumi.set(__self__, "total_memory_in_gbs", total_memory_in_gbs)
if total_ocpus and not isinstance(total_ocpus, float):
raise TypeError("Expected argument 'total_ocpus' to be a float")
pulumi.set(__self__, "total_ocpus", total_ocpus)
@property
@pulumi.getter(name="availabilityDomain")
def availability_domain(self) -> str:
"""
The availability domain the dedicated virtual machine host is running in. Example: `Uocm:PHX-AD-1`
"""
return pulumi.get(self, "availability_domain")
@property
@pulumi.getter(name="compartmentId")
def compartment_id(self) -> str:
"""
The OCID of the compartment that contains the dedicated virtual machine host.
"""
return pulumi.get(self, "compartment_id")
@property
@pulumi.getter(name="dedicatedVmHostId")
def dedicated_vm_host_id(self) -> str:
return pulumi.get(self, "dedicated_vm_host_id")
@property
@pulumi.getter(name="dedicatedVmHostShape")
def dedicated_vm_host_shape(self) -> str:
"""
The dedicated virtual machine host shape. The shape determines the number of CPUs and other resources available for VMs.
"""
return pulumi.get(self, "dedicated_vm_host_shape")
@property
@pulumi.getter(name="definedTags")
def defined_tags(self) -> Mapping[str, Any]:
"""
Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Operations.CostCenter": "42"}`
"""
return pulumi.get(self, "defined_tags")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
A user-friendly name. Does not have to be unique, and it's changeable. Avoid entering confidential information. Example: `My Dedicated Vm Host`
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter(name="faultDomain")
def fault_domain(self) -> str:
"""
The fault domain for the dedicated virtual machine host's assigned instances. For more information, see [Fault Domains](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/regions.htm#fault).
"""
return pulumi.get(self, "fault_domain")
@property
@pulumi.getter(name="freeformTags")
def freeform_tags(self) -> Mapping[str, Any]:
"""
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}`
"""
return pulumi.get(self, "freeform_tags")
@property
@pulumi.getter
def id(self) -> str:
"""
The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the dedicated VM host.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="remainingMemoryInGbs")
def remaining_memory_in_gbs(self) -> float:
"""
The current available memory of the dedicated VM host, in GBs.
"""
return pulumi.get(self, "remaining_memory_in_gbs")
@property
@pulumi.getter(name="remainingOcpus")
def remaining_ocpus(self) -> float:
"""
The current available OCPUs of the dedicated VM host.
"""
return pulumi.get(self, "remaining_ocpus")
@property
@pulumi.getter
def state(self) -> str:
"""
The current state of the dedicated VM host.
"""
return pulumi.get(self, "state")
@property
@pulumi.getter(name="timeCreated")
def time_created(self) -> str:
"""
The date and time the dedicated VM host was created, in the format defined by [RFC3339](https://tools.ietf.org/html/rfc3339). Example: `2016-08-25T21:10:29.600Z`
"""
return pulumi.get(self, "time_created")
@property
@pulumi.getter(name="totalMemoryInGbs")
def total_memory_in_gbs(self) -> float:
"""
The current total memory of the dedicated VM host, in GBs.
"""
return pulumi.get(self, "total_memory_in_gbs")
@property
@pulumi.getter(name="totalOcpus")
def total_ocpus(self) -> float:
"""
The current total OCPUs of the dedicated VM host.
"""
return pulumi.get(self, "total_ocpus")
class AwaitableGetDedicatedVmHostResult(GetDedicatedVmHostResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetDedicatedVmHostResult(
availability_domain=self.availability_domain,
compartment_id=self.compartment_id,
dedicated_vm_host_id=self.dedicated_vm_host_id,
dedicated_vm_host_shape=self.dedicated_vm_host_shape,
defined_tags=self.defined_tags,
display_name=self.display_name,
fault_domain=self.fault_domain,
freeform_tags=self.freeform_tags,
id=self.id,
remaining_memory_in_gbs=self.remaining_memory_in_gbs,
remaining_ocpus=self.remaining_ocpus,
state=self.state,
time_created=self.time_created,
total_memory_in_gbs=self.total_memory_in_gbs,
total_ocpus=self.total_ocpus)
def get_dedicated_vm_host(dedicated_vm_host_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDedicatedVmHostResult:
"""
This data source provides details about a specific Dedicated Vm Host resource in Oracle Cloud Infrastructure Core service.
Gets information about the specified dedicated virtual machine host.
## Example Usage
```python
import pulumi
import pulumi_oci as oci
test_dedicated_vm_host = oci.core.get_dedicated_vm_host(dedicated_vm_host_id=oci_core_dedicated_vm_host["test_dedicated_vm_host"]["id"])
```
:param str dedicated_vm_host_id: The OCID of the dedicated VM host.
"""
__args__ = dict()
__args__['dedicatedVmHostId'] = dedicated_vm_host_id
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('oci:core/getDedicatedVmHost:getDedicatedVmHost', __args__, opts=opts, typ=GetDedicatedVmHostResult).value
return AwaitableGetDedicatedVmHostResult(
availability_domain=__ret__.availability_domain,
compartment_id=__ret__.compartment_id,
dedicated_vm_host_id=__ret__.dedicated_vm_host_id,
dedicated_vm_host_shape=__ret__.dedicated_vm_host_shape,
defined_tags=__ret__.defined_tags,
display_name=__ret__.display_name,
fault_domain=__ret__.fault_domain,
freeform_tags=__ret__.freeform_tags,
id=__ret__.id,
remaining_memory_in_gbs=__ret__.remaining_memory_in_gbs,
remaining_ocpus=__ret__.remaining_ocpus,
state=__ret__.state,
time_created=__ret__.time_created,
total_memory_in_gbs=__ret__.total_memory_in_gbs,
total_ocpus=__ret__.total_ocpus)
| [
"pulumi.get",
"pulumi.getter",
"pulumi.set",
"pulumi.InvokeOptions",
"pulumi.runtime.invoke"
] | [((4092, 4132), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""availabilityDomain"""'}), "(name='availabilityDomain')\n", (4105, 4132), False, 'import pulumi\n'), ((4382, 4417), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""compartmentId"""'}), "(name='compartmentId')\n", (4395, 4417), False, 'import pulumi\n'), ((4635, 4674), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""dedicatedVmHostId"""'}), "(name='dedicatedVmHostId')\n", (4648, 4674), False, 'import pulumi\n'), ((4794, 4836), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""dedicatedVmHostShape"""'}), "(name='dedicatedVmHostShape')\n", (4807, 4836), False, 'import pulumi\n'), ((5115, 5148), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""definedTags"""'}), "(name='definedTags')\n", (5128, 5148), False, 'import pulumi\n'), ((5545, 5578), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""displayName"""'}), "(name='displayName')\n", (5558, 5578), False, 'import pulumi\n'), ((5859, 5892), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""faultDomain"""'}), "(name='faultDomain')\n", (5872, 5892), False, 'import pulumi\n'), ((6228, 6262), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""freeformTags"""'}), "(name='freeformTags')\n", (6241, 6262), False, 'import pulumi\n'), ((6931, 6973), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""remainingMemoryInGbs"""'}), "(name='remainingMemoryInGbs')\n", (6944, 6973), False, 'import pulumi\n'), ((7196, 7232), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""remainingOcpus"""'}), "(name='remainingOcpus')\n", (7209, 7232), False, 'import pulumi\n'), ((7609, 7642), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""timeCreated"""'}), "(name='timeCreated')\n", (7622, 7642), False, 'import pulumi\n'), ((7941, 7979), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""totalMemoryInGbs"""'}), "(name='totalMemoryInGbs')\n", (7954, 7979), False, 'import pulumi\n'), ((8190, 8222), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""totalOcpus"""'}), "(name='totalOcpus')\n", (8203, 8222), False, 'import pulumi\n'), ((1090, 1154), 'pulumi.set', 'pulumi.set', (['__self__', '"""availability_domain"""', 'availability_domain'], {}), "(__self__, 'availability_domain', availability_domain)\n", (1100, 1154), False, 'import pulumi\n'), ((1308, 1362), 'pulumi.set', 'pulumi.set', (['__self__', '"""compartment_id"""', 'compartment_id'], {}), "(__self__, 'compartment_id', compartment_id)\n", (1318, 1362), False, 'import pulumi\n'), ((1534, 1600), 'pulumi.set', 'pulumi.set', (['__self__', '"""dedicated_vm_host_id"""', 'dedicated_vm_host_id'], {}), "(__self__, 'dedicated_vm_host_id', dedicated_vm_host_id)\n", (1544, 1600), False, 'import pulumi\n'), ((1781, 1853), 'pulumi.set', 'pulumi.set', (['__self__', '"""dedicated_vm_host_shape"""', 'dedicated_vm_host_shape'], {}), "(__self__, 'dedicated_vm_host_shape', dedicated_vm_host_shape)\n", (1791, 1853), False, 'import pulumi\n'), ((2003, 2053), 'pulumi.set', 'pulumi.set', (['__self__', '"""defined_tags"""', 'defined_tags'], {}), "(__self__, 'defined_tags', defined_tags)\n", (2013, 2053), False, 'import pulumi\n'), ((2201, 2251), 'pulumi.set', 'pulumi.set', (['__self__', '"""display_name"""', 'display_name'], {}), "(__self__, 'display_name', display_name)\n", (2211, 2251), False, 'import pulumi\n'), ((2399, 2449), 'pulumi.set', 'pulumi.set', (['__self__', '"""fault_domain"""', 'fault_domain'], {}), "(__self__, 'fault_domain', fault_domain)\n", (2409, 2449), False, 'import pulumi\n'), ((2602, 2654), 'pulumi.set', 'pulumi.set', (['__self__', '"""freeform_tags"""', 'freeform_tags'], {}), "(__self__, 'freeform_tags', freeform_tags)\n", (2612, 2654), False, 'import pulumi\n'), ((2772, 2802), 'pulumi.set', 'pulumi.set', (['__self__', '"""id"""', 'id'], {}), "(__self__, 'id', id)\n", (2782, 2802), False, 'import pulumi\n'), ((2987, 3059), 'pulumi.set', 'pulumi.set', (['__self__', '"""remaining_memory_in_gbs"""', 'remaining_memory_in_gbs'], {}), "(__self__, 'remaining_memory_in_gbs', remaining_memory_in_gbs)\n", (2997, 3059), False, 'import pulumi\n'), ((3220, 3276), 'pulumi.set', 'pulumi.set', (['__self__', '"""remaining_ocpus"""', 'remaining_ocpus'], {}), "(__self__, 'remaining_ocpus', remaining_ocpus)\n", (3230, 3276), False, 'import pulumi\n'), ((3403, 3439), 'pulumi.set', 'pulumi.set', (['__self__', '"""state"""', 'state'], {}), "(__self__, 'state', state)\n", (3413, 3439), False, 'import pulumi\n'), ((3587, 3637), 'pulumi.set', 'pulumi.set', (['__self__', '"""time_created"""', 'time_created'], {}), "(__self__, 'time_created', time_created)\n", (3597, 3637), False, 'import pulumi\n'), ((3810, 3874), 'pulumi.set', 'pulumi.set', (['__self__', '"""total_memory_in_gbs"""', 'total_memory_in_gbs'], {}), "(__self__, 'total_memory_in_gbs', total_memory_in_gbs)\n", (3820, 3874), False, 'import pulumi\n'), ((4023, 4071), 'pulumi.set', 'pulumi.set', (['__self__', '"""total_ocpus"""', 'total_ocpus'], {}), "(__self__, 'total_ocpus', total_ocpus)\n", (4033, 4071), False, 'import pulumi\n'), ((4322, 4361), 'pulumi.get', 'pulumi.get', (['self', '"""availability_domain"""'], {}), "(self, 'availability_domain')\n", (4332, 4361), False, 'import pulumi\n'), ((4580, 4614), 'pulumi.get', 'pulumi.get', (['self', '"""compartment_id"""'], {}), "(self, 'compartment_id')\n", (4590, 4614), False, 'import pulumi\n'), ((4733, 4773), 'pulumi.get', 'pulumi.get', (['self', '"""dedicated_vm_host_id"""'], {}), "(self, 'dedicated_vm_host_id')\n", (4743, 4773), False, 'import pulumi\n'), ((5051, 5094), 'pulumi.get', 'pulumi.get', (['self', '"""dedicated_vm_host_shape"""'], {}), "(self, 'dedicated_vm_host_shape')\n", (5061, 5094), False, 'import pulumi\n'), ((5492, 5524), 'pulumi.get', 'pulumi.get', (['self', '"""defined_tags"""'], {}), "(self, 'defined_tags')\n", (5502, 5524), False, 'import pulumi\n'), ((5806, 5838), 'pulumi.get', 'pulumi.get', (['self', '"""display_name"""'], {}), "(self, 'display_name')\n", (5816, 5838), False, 'import pulumi\n'), ((6175, 6207), 'pulumi.get', 'pulumi.get', (['self', '"""fault_domain"""'], {}), "(self, 'fault_domain')\n", (6185, 6207), False, 'import pulumi\n'), ((6634, 6667), 'pulumi.get', 'pulumi.get', (['self', '"""freeform_tags"""'], {}), "(self, 'freeform_tags')\n", (6644, 6667), False, 'import pulumi\n'), ((6888, 6910), 'pulumi.get', 'pulumi.get', (['self', '"""id"""'], {}), "(self, 'id')\n", (6898, 6910), False, 'import pulumi\n'), ((7132, 7175), 'pulumi.get', 'pulumi.get', (['self', '"""remaining_memory_in_gbs"""'], {}), "(self, 'remaining_memory_in_gbs')\n", (7142, 7175), False, 'import pulumi\n'), ((7374, 7409), 'pulumi.get', 'pulumi.get', (['self', '"""remaining_ocpus"""'], {}), "(self, 'remaining_ocpus')\n", (7384, 7409), False, 'import pulumi\n'), ((7563, 7588), 'pulumi.get', 'pulumi.get', (['self', '"""state"""'], {}), "(self, 'state')\n", (7573, 7588), False, 'import pulumi\n'), ((7888, 7920), 'pulumi.get', 'pulumi.get', (['self', '"""time_created"""'], {}), "(self, 'time_created')\n", (7898, 7920), False, 'import pulumi\n'), ((8130, 8169), 'pulumi.get', 'pulumi.get', (['self', '"""total_memory_in_gbs"""'], {}), "(self, 'total_memory_in_gbs')\n", (8140, 8169), False, 'import pulumi\n'), ((8356, 8387), 'pulumi.get', 'pulumi.get', (['self', '"""total_ocpus"""'], {}), "(self, 'total_ocpus')\n", (8366, 8387), False, 'import pulumi\n'), ((10151, 10173), 'pulumi.InvokeOptions', 'pulumi.InvokeOptions', ([], {}), '()\n', (10171, 10173), False, 'import pulumi\n'), ((10265, 10391), 'pulumi.runtime.invoke', 'pulumi.runtime.invoke', (['"""oci:core/getDedicatedVmHost:getDedicatedVmHost"""', '__args__'], {'opts': 'opts', 'typ': 'GetDedicatedVmHostResult'}), "('oci:core/getDedicatedVmHost:getDedicatedVmHost',\n __args__, opts=opts, typ=GetDedicatedVmHostResult)\n", (10286, 10391), False, 'import pulumi\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 07:33:30 2018
@author: aaronpenne
"""
import os
import pandas as pd
import numpy as np
code_dir = os.path.dirname(__file__) # Returns full path of this script
data_dir = os.path.join(code_dir, 'data')
output_dir = os.path.join(code_dir, 'output')
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
df = pd.read_excel(os.path.join(data_dir, '2010.xlsx'))
# Thanks to colorbrewer2.org
colors = ['#ffffcc','#d9f0a3','#addd8e','#78c679','#41ab5d','#238443','#005a32']
total_max = 1000
bins = np.linspace(0, total_max, len(colors))
year = 2010
cols = [('TOTRATE', 'Concentration of 236 Religious Groups'),
('CATHRATE', 'Catholic'),
('MSLMRATE', 'Muslim')]
for col, name in cols:
with open(os.path.join(data_dir, 'county_map.svg'), 'r') as f:
svg = f.readlines()
idx = [i for i, s in enumerate(svg) if '<style' in s or '</style' in s]
svg_top = svg[:idx[0]+1]
svg_bot = svg[idx[1]:]
default = [s for s in svg[idx[0]:idx[1]] if '.counties' in s or '.State_' in s or '.separator' in s]
style = []
for val, fips in zip(df[col], df['FIPS']):
color = colors[0]
if val > bins[0]:
color = colors[1]
if val > bins[1]:
color = colors[2]
if val > bins[2]:
color = colors[3]
if val > bins[3]:
color = colors[4]
if val > bins[4]:
color = colors[5]
if val > bins[5]:
color = colors[6]
style.append('.c{:05} {{fill:{}}}\n'.format(fips, color))
# Annotation styles
style.append('.title { font: 20px monospace; }')
style.append('.subtitle { font: 15px monospace; }')
style.append('.annotation { font: 10px monospace; }')
# Annotations
svg_bot.insert(1, '<text text-anchor="middle" x="660" y="20" class="title">{} in {}</text>'.format(name, year))
svg_bot.insert(1, '<text text-anchor="middle" x="660" y="40" class="subtitle">Adherents per 1000 people</text>'.format(name))
svg_bot.insert(1, '<text text-anchor="middle" x="660" y="605" class="annotation">Association of Religion Data Archives</text>')
svg_bot.insert(1, '<text text-anchor="middle" x="660" y="615" class="annotation"><NAME> © 2018</text>')
# Legend
x = 600
y = 550
w = 15
h = 15
for i, color in enumerate(colors):
svg_bot.insert(1, '<rect x="{}" y="{}" width="{}" height="{}" fill="{}"/>'.format(x+i*w, y, w, h, color))
svg_bot.insert(1, '<text text-anchor="middle" x="660" y="540" class="annotation">Adherents/1000 people</text>')
svg_bot.insert(1, '<text x="{}" y="{}" class="annotation">{}</text>'.format(x-10, y+10, 0))
svg_bot.insert(1, '<text x="{}" y="{}" class="annotation">{}</text>'.format(x+i*w+20, y+10, total_max))
out = svg_top + default + style + svg_bot
with open(os.path.join(output_dir, name + '.svg'), 'w+') as f:
f.writelines(out) | [
"os.path.dirname",
"os.path.isdir",
"os.path.join",
"os.mkdir"
] | [((174, 199), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (189, 199), False, 'import os\n'), ((247, 277), 'os.path.join', 'os.path.join', (['code_dir', '"""data"""'], {}), "(code_dir, 'data')\n", (259, 277), False, 'import os\n'), ((291, 323), 'os.path.join', 'os.path.join', (['code_dir', '"""output"""'], {}), "(code_dir, 'output')\n", (303, 323), False, 'import os\n'), ((331, 356), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (344, 356), False, 'import os\n'), ((362, 382), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (370, 382), False, 'import os\n'), ((407, 442), 'os.path.join', 'os.path.join', (['data_dir', '"""2010.xlsx"""'], {}), "(data_dir, '2010.xlsx')\n", (419, 442), False, 'import os\n'), ((794, 834), 'os.path.join', 'os.path.join', (['data_dir', '"""county_map.svg"""'], {}), "(data_dir, 'county_map.svg')\n", (806, 834), False, 'import os\n'), ((2932, 2971), 'os.path.join', 'os.path.join', (['output_dir', "(name + '.svg')"], {}), "(output_dir, name + '.svg')\n", (2944, 2971), False, 'import os\n')] |
import os
import tempfile
import pytest
import numpy as np
try:
import h5py
except ImportError:
h5py = None
from msl.io import read, HDF5Writer, JSONWriter
from msl.io.readers import HDF5Reader
from helper import read_sample, roots_equal
@pytest.mark.skipif(h5py is None, reason='h5py not installed')
def test_read_write_convert():
root1 = read_sample('hdf5_sample.h5')
# write as HDF5 then read
writer = HDF5Writer(tempfile.gettempdir() + '/msl-hdf5-writer-temp.h5')
writer.write(root=root1, mode='w')
root2 = read(writer.file)
assert root2.file == writer.file
assert roots_equal(root1, root2)
os.remove(writer.file)
# convert to JSON then back to HDF5
json_writer = JSONWriter(tempfile.gettempdir() + '/msl-json-writer-temp.json')
json_writer.write(root=root1, mode='w')
root_json = read(json_writer.file)
assert root_json.file == json_writer.file
assert roots_equal(root1, root_json)
os.remove(json_writer.file)
writer2 = HDF5Writer(tempfile.gettempdir() + '/msl-hdf5-writer-temp2.h5')
writer2.write(root=root_json, mode='w')
root3 = read(writer2.file)
assert root3.file == writer2.file
assert roots_equal(root1, root3)
os.remove(writer2.file)
for root in [root1, root2, root3]:
assert isinstance(root, HDF5Reader)
for key, value in root.items():
k, v = str(key), str(value)
k, v = repr(key), repr(value)
order = ['D0', 'G0', 'G1A', 'D1', 'G1B', 'D2', 'D3', 'G2']
for i, key in enumerate(root.keys()):
assert os.path.basename(key) == order[i]
assert len(root.metadata) == 3
assert root.metadata['version_h5py'] == '2.8.0'
assert root.metadata.version_hdf5 == '1.10.2'
assert root.metadata['date_created'] == '2018-08-28 15:16:43.904990'
assert 'D0' in root
assert 'G0' in root
d0 = root['D0']
assert root.is_dataset(d0)
assert d0.shape == (10, 4)
assert d0.dtype.str == '<f4'
assert len(d0.metadata) == 2
assert d0.metadata['temperature'] == 21.2
assert d0.metadata.temperature_units == 'deg C'
g0 = root.G0
assert root.is_group(g0)
assert len(g0.metadata) == 1
assert all(g0.metadata['count'] == [1, 2, 3, 4, 5])
assert 'G1A' in g0
assert 'G1B' in g0
g1a = g0['G1A']
assert root.is_group(g1a)
assert len(g1a.metadata) == 2
assert g1a.metadata['one'] == 1
assert g1a.metadata['a'] == 'A'
g1b = g0['G1B']
assert root.is_group(g1b)
assert len(g1b.metadata) == 2
assert g1b.metadata['one'] == 1
assert g1b.metadata['b'] == 'B'
assert 'D1' in g0['G1A']
d1 = root.G0.G1A.D1
assert root.is_dataset(d1)
assert len(d1.metadata) == 0
assert d1.shape == (3, 3)
assert d1.dtype.str == '<f8'
assert 'D2' in g1b
assert 'D3' in g0.G1B
assert 'G2' in root.G0.G1B
d2 = g1b['D2']
assert root.is_dataset(d2)
assert len(d2.metadata) == 2
assert d2.metadata['voltage'] == 132.4
assert d2.metadata['voltage_units'] == 'uV'
assert d2.shape == (10,)
assert d2.dtype.str == '<i4'
assert d2[3] == 90
d3 = g1b.D3
assert root.is_dataset(d3)
assert len(d3.metadata) == 0
assert d3.shape == (10,)
assert d3.dtype.str == '<i4'
assert d3[7] == 51
g2 = root.G0.G1B.G2
assert root.is_group(g2)
assert len(g2.metadata) == 1
assert g2.metadata['hello'] == 'world'
@pytest.mark.skipif(h5py is None, reason='h5py not installed')
def test_raises():
root = read_sample('hdf5_sample.h5')
writer = HDF5Writer()
assert writer.file is None
# no file was specified
with pytest.raises(ValueError, match=r'must specify a file'):
writer.write(root=root)
# root must be a Root object
with pytest.raises(TypeError, match=r'Root'):
writer.write(file='whatever', root=list(root.datasets())[0])
with pytest.raises(TypeError, match=r'Root'):
writer.write(file='whatever', root=list(root.groups())[0])
with pytest.raises(TypeError, match=r'Root'):
writer.write(file='whatever', root='Root')
# cannot overwrite a file by default
file = tempfile.gettempdir() + '/msl-hdf5-writer-temp.h5'
with open(file, mode='wt') as fp:
fp.write('Hi')
with pytest.raises(OSError, match=r'File exists'):
writer.write(file=file, root=root)
with pytest.raises(OSError, match=r'File exists'):
writer.write(file=file, root=root, mode='x')
with pytest.raises(OSError, match=r'File exists'):
writer.write(file=file, root=root, mode='w-')
# invalid mode
for m in ['r', 'b', 'w+b']:
with pytest.raises(ValueError, match=r'Invalid mode'):
writer.write(file=file, root=root, mode=m)
# r+ is a valid mode, but the file must already exist
with pytest.raises(OSError, match=r'File does not exist'):
writer.write(file='does_not.exist', root=root, mode='r+')
# by specifying the proper mode one can overwrite a file
writer.write(file=file, root=root, mode='w')
assert roots_equal(root, read(file))
writer.write(file=file, root=root, mode='a')
assert roots_equal(root, read(file))
writer.write(file=file, root=root, mode='r+')
assert roots_equal(root, read(file))
os.remove(file)
@pytest.mark.skipif(h5py is None, reason='h5py not installed')
def test_numpy_unicode_dtype():
writer = HDF5Writer()
writer.add_metadata(wide_chars=np.array(['1', '-4e+99', 'True'], dtype='<U6'))
writer.create_dataset('wide_chars', data=np.random.random(100).reshape(4, 25).astype('<U32'))
file = tempfile.gettempdir() + '/msl-hdf5-writer-temp.h5'
writer.save(file, mode='w')
root = read(file)
assert np.array_equal(root.metadata.wide_chars, writer.metadata.wide_chars)
# the following array_equal assertion fails so we iterate over all elements instead
# assert np.array_equal(root.wide_chars.astype('<U32'), writer.wide_chars)
for a, b in zip(root.wide_chars.astype('<U32').flatten(), writer.wide_chars.flatten()):
assert a == b
os.remove(file)
| [
"helper.read_sample",
"numpy.random.random",
"msl.io.read",
"msl.io.HDF5Writer",
"numpy.array",
"numpy.array_equal",
"pytest.raises",
"tempfile.gettempdir",
"pytest.mark.skipif",
"os.path.basename",
"helper.roots_equal",
"os.remove"
] | [((252, 313), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(h5py is None)'], {'reason': '"""h5py not installed"""'}), "(h5py is None, reason='h5py not installed')\n", (270, 313), False, 'import pytest\n'), ((3668, 3729), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(h5py is None)'], {'reason': '"""h5py not installed"""'}), "(h5py is None, reason='h5py not installed')\n", (3686, 3729), False, 'import pytest\n'), ((5540, 5601), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(h5py is None)'], {'reason': '"""h5py not installed"""'}), "(h5py is None, reason='h5py not installed')\n", (5558, 5601), False, 'import pytest\n'), ((357, 386), 'helper.read_sample', 'read_sample', (['"""hdf5_sample.h5"""'], {}), "('hdf5_sample.h5')\n", (368, 386), False, 'from helper import read_sample, roots_equal\n'), ((545, 562), 'msl.io.read', 'read', (['writer.file'], {}), '(writer.file)\n', (549, 562), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((611, 636), 'helper.roots_equal', 'roots_equal', (['root1', 'root2'], {}), '(root1, root2)\n', (622, 636), False, 'from helper import read_sample, roots_equal\n'), ((641, 663), 'os.remove', 'os.remove', (['writer.file'], {}), '(writer.file)\n', (650, 663), False, 'import os\n'), ((848, 870), 'msl.io.read', 'read', (['json_writer.file'], {}), '(json_writer.file)\n', (852, 870), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((928, 957), 'helper.roots_equal', 'roots_equal', (['root1', 'root_json'], {}), '(root1, root_json)\n', (939, 957), False, 'from helper import read_sample, roots_equal\n'), ((962, 989), 'os.remove', 'os.remove', (['json_writer.file'], {}), '(json_writer.file)\n', (971, 989), False, 'import os\n'), ((1124, 1142), 'msl.io.read', 'read', (['writer2.file'], {}), '(writer2.file)\n', (1128, 1142), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((1192, 1217), 'helper.roots_equal', 'roots_equal', (['root1', 'root3'], {}), '(root1, root3)\n', (1203, 1217), False, 'from helper import read_sample, roots_equal\n'), ((1222, 1245), 'os.remove', 'os.remove', (['writer2.file'], {}), '(writer2.file)\n', (1231, 1245), False, 'import os\n'), ((3760, 3789), 'helper.read_sample', 'read_sample', (['"""hdf5_sample.h5"""'], {}), "('hdf5_sample.h5')\n", (3771, 3789), False, 'from helper import read_sample, roots_equal\n'), ((3804, 3816), 'msl.io.HDF5Writer', 'HDF5Writer', ([], {}), '()\n', (3814, 3816), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((5521, 5536), 'os.remove', 'os.remove', (['file'], {}), '(file)\n', (5530, 5536), False, 'import os\n'), ((5647, 5659), 'msl.io.HDF5Writer', 'HDF5Writer', ([], {}), '()\n', (5657, 5659), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((5948, 5958), 'msl.io.read', 'read', (['file'], {}), '(file)\n', (5952, 5958), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((5970, 6038), 'numpy.array_equal', 'np.array_equal', (['root.metadata.wide_chars', 'writer.metadata.wide_chars'], {}), '(root.metadata.wide_chars, writer.metadata.wide_chars)\n', (5984, 6038), True, 'import numpy as np\n'), ((6326, 6341), 'os.remove', 'os.remove', (['file'], {}), '(file)\n', (6335, 6341), False, 'import os\n'), ((3886, 3940), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""must specify a file"""'}), "(ValueError, match='must specify a file')\n", (3899, 3940), False, 'import pytest\n'), ((4018, 4056), 'pytest.raises', 'pytest.raises', (['TypeError'], {'match': '"""Root"""'}), "(TypeError, match='Root')\n", (4031, 4056), False, 'import pytest\n'), ((4137, 4175), 'pytest.raises', 'pytest.raises', (['TypeError'], {'match': '"""Root"""'}), "(TypeError, match='Root')\n", (4150, 4175), False, 'import pytest\n'), ((4254, 4292), 'pytest.raises', 'pytest.raises', (['TypeError'], {'match': '"""Root"""'}), "(TypeError, match='Root')\n", (4267, 4292), False, 'import pytest\n'), ((4399, 4420), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (4418, 4420), False, 'import tempfile\n'), ((4520, 4563), 'pytest.raises', 'pytest.raises', (['OSError'], {'match': '"""File exists"""'}), "(OSError, match='File exists')\n", (4533, 4563), False, 'import pytest\n'), ((4618, 4661), 'pytest.raises', 'pytest.raises', (['OSError'], {'match': '"""File exists"""'}), "(OSError, match='File exists')\n", (4631, 4661), False, 'import pytest\n'), ((4726, 4769), 'pytest.raises', 'pytest.raises', (['OSError'], {'match': '"""File exists"""'}), "(OSError, match='File exists')\n", (4739, 4769), False, 'import pytest\n'), ((5064, 5115), 'pytest.raises', 'pytest.raises', (['OSError'], {'match': '"""File does not exist"""'}), "(OSError, match='File does not exist')\n", (5077, 5115), False, 'import pytest\n'), ((5324, 5334), 'msl.io.read', 'read', (['file'], {}), '(file)\n', (5328, 5334), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((5414, 5424), 'msl.io.read', 'read', (['file'], {}), '(file)\n', (5418, 5424), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((5505, 5515), 'msl.io.read', 'read', (['file'], {}), '(file)\n', (5509, 5515), False, 'from msl.io import read, HDF5Writer, JSONWriter\n'), ((5853, 5874), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (5872, 5874), False, 'import tempfile\n'), ((442, 463), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (461, 463), False, 'import tempfile\n'), ((734, 755), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (753, 755), False, 'import tempfile\n'), ((1015, 1036), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (1034, 1036), False, 'import tempfile\n'), ((4891, 4938), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Invalid mode"""'}), "(ValueError, match='Invalid mode')\n", (4904, 4938), False, 'import pytest\n'), ((5695, 5741), 'numpy.array', 'np.array', (["['1', '-4e+99', 'True']"], {'dtype': '"""<U6"""'}), "(['1', '-4e+99', 'True'], dtype='<U6')\n", (5703, 5741), True, 'import numpy as np\n'), ((1586, 1607), 'os.path.basename', 'os.path.basename', (['key'], {}), '(key)\n', (1602, 1607), False, 'import os\n'), ((5788, 5809), 'numpy.random.random', 'np.random.random', (['(100)'], {}), '(100)\n', (5804, 5809), True, 'import numpy as np\n')] |
import logging
import tkinter as tk
class CalibrationMsgBox():
"""
The message box class.
"""
MESSAGES = [
'Turn the steering wheel fully LEFT and press x.',
'Turn the steering wheel fully RIGHT and press x.',
'Make sure the throttle is fully DEPRESSED and press x.',
'Make sure the throttle is fully PRESSED and press x.',
'Make sure the break is fully DEPRESSED and press x.',
'Make sure the break is fully PRESSED and press x.',
]
def __init__(self, root, *args, **kwargs):
"""
Contructor.
Params:
root: The application root.
msg: The message box initial message.
buttons: The buttons to display.
"""
self._msgIdx = 0
self._logger = logging.getLogger('CALIB_MSG')
topWidth = 1000
topHeight = 100
topPosX = int((root.winfo_width() / 2) - topWidth / 2)
topPosY = int((root.winfo_height() / 2) - topHeight / 2)
self._top = tk.Toplevel(root)
self._top.title("Controller Calibration")
self._top.geometry(f"{topWidth}x{topHeight}+{topPosX}+{topPosY}")
self._top.grab_set()
self._msg = tk.StringVar(self._top)
self._msg.set(self.MESSAGES[self._msgIdx])
self._msgLabel = tk.Label(self._top, textvariable=self._msg)
self._msgLabel.place(x=500, y=50, anchor='center')
def update_msg(self):
"""
Update the message box message.
"""
self._logger.debug('updating message')
self._msgIdx += 1
if self._msgIdx == len(self.MESSAGES):
self._top.destroy()
self._logger.debug(f"new msg: {self.MESSAGES[self._msgIdx]}")
self._msg.set(self.MESSAGES[self._msgIdx])
| [
"logging.getLogger",
"tkinter.StringVar",
"tkinter.Toplevel",
"tkinter.Label"
] | [((811, 841), 'logging.getLogger', 'logging.getLogger', (['"""CALIB_MSG"""'], {}), "('CALIB_MSG')\n", (828, 841), False, 'import logging\n'), ((1039, 1056), 'tkinter.Toplevel', 'tk.Toplevel', (['root'], {}), '(root)\n', (1050, 1056), True, 'import tkinter as tk\n'), ((1230, 1253), 'tkinter.StringVar', 'tk.StringVar', (['self._top'], {}), '(self._top)\n', (1242, 1253), True, 'import tkinter as tk\n'), ((1330, 1373), 'tkinter.Label', 'tk.Label', (['self._top'], {'textvariable': 'self._msg'}), '(self._top, textvariable=self._msg)\n', (1338, 1373), True, 'import tkinter as tk\n')] |
import numpy as np
from ringity.classes.diagram import PersistenceDiagram
def read_pdiagram(fname, **kwargs):
"""
Wrapper for numpy.genfromtxt.
"""
return PersistenceDiagram(np.genfromtxt(fname, **kwargs))
def write_pdiagram(dgm, fname, **kwargs):
"""
Wrapper for numpy.savetxt.
"""
array = np.array(dgm)
np.savetxt(fname, array, **kwargs) | [
"numpy.array",
"numpy.genfromtxt",
"numpy.savetxt"
] | [((329, 342), 'numpy.array', 'np.array', (['dgm'], {}), '(dgm)\n', (337, 342), True, 'import numpy as np\n'), ((347, 381), 'numpy.savetxt', 'np.savetxt', (['fname', 'array'], {}), '(fname, array, **kwargs)\n', (357, 381), True, 'import numpy as np\n'), ((191, 221), 'numpy.genfromtxt', 'np.genfromtxt', (['fname'], {}), '(fname, **kwargs)\n', (204, 221), True, 'import numpy as np\n')] |
import functools
import os
from argparse import ArgumentParser
import networkx
import numpy as np
from visualize import heatmap
class MatchingClustering(object):
def __init__(self, n_clusters):
self.n_clusters = n_clusters
def fit_predict(self, X):
total = len(X)
grouping = [{i} for i in range(total)]
while len(grouping) > self.n_clusters:
gx = networkx.Graph()
gx.add_nodes_from(list(range(len(grouping))))
for i in range(len(grouping)):
for j in range(i + 1, len(grouping)):
w = sum([X[x][y] + 1 for x in grouping[i] for y in grouping[j]])
gx.add_edge(i, j, weight=w + 1)
ret = networkx.algorithms.max_weight_matching(gx, maxcardinality=True)
ret = sorted(list(ret))
new_grouping = [grouping[a] | grouping[b] for a, b in ret]
grouping = new_grouping
if len(grouping) != self.n_clusters:
raise ValueError("Cannot satisfy need: splitting to {} clusters.".format(self.n_clusters))
ret = np.zeros(total, dtype=np.int)
for i, g in enumerate(grouping):
ret[list(g)] = i
return ret
def main():
parser = ArgumentParser()
parser.add_argument("dir", type=str)
parser.add_argument("--num_classes", default=2, type=int)
args = parser.parse_args()
cor_matrix = np.loadtxt(os.path.join(args.dir, "corr_heatmap.txt"))
grouping = np.loadtxt(os.path.join(args.dir, "group_info.txt"), dtype=np.int)
group_number = np.max(grouping) + 1
result_grouping = np.zeros(len(grouping), dtype=np.int)
base = 0
for i in sorted(list(range(group_number)), key=lambda d: np.sum(grouping == d)):
cur_index = np.where(grouping == i)[0]
cor_matrix_grp = cor_matrix[cur_index][:, cur_index]
# print(cor_matrix_grp)
model = MatchingClustering(n_clusters=args.num_classes)
if len(cur_index) < args.num_classes:
result_grouping[cur_index] = np.arange(len(cur_index)) + base
print("Group {}: Too small")
base += len(cur_index)
else:
predict = model.fit_predict(1 - cor_matrix_grp)
print("Group {}: {}".format(i, predict.tolist()))
for j in range(args.num_classes):
result_grouping[cur_index[predict == j]] = base + j
base += args.num_classes
heatmap(cor_matrix_grp, filepath=os.path.join("debug", "heatmap_{}".format(i)))
print(result_grouping.tolist())
if __name__ == "__main__":
main()
| [
"networkx.algorithms.max_weight_matching",
"argparse.ArgumentParser",
"numpy.where",
"os.path.join",
"networkx.Graph",
"numpy.max",
"numpy.sum",
"numpy.zeros"
] | [((1247, 1263), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (1261, 1263), False, 'from argparse import ArgumentParser\n'), ((1101, 1130), 'numpy.zeros', 'np.zeros', (['total'], {'dtype': 'np.int'}), '(total, dtype=np.int)\n', (1109, 1130), True, 'import numpy as np\n'), ((1428, 1470), 'os.path.join', 'os.path.join', (['args.dir', '"""corr_heatmap.txt"""'], {}), "(args.dir, 'corr_heatmap.txt')\n", (1440, 1470), False, 'import os\n'), ((1498, 1538), 'os.path.join', 'os.path.join', (['args.dir', '"""group_info.txt"""'], {}), "(args.dir, 'group_info.txt')\n", (1510, 1538), False, 'import os\n'), ((1573, 1589), 'numpy.max', 'np.max', (['grouping'], {}), '(grouping)\n', (1579, 1589), True, 'import numpy as np\n'), ((404, 420), 'networkx.Graph', 'networkx.Graph', ([], {}), '()\n', (418, 420), False, 'import networkx\n'), ((731, 795), 'networkx.algorithms.max_weight_matching', 'networkx.algorithms.max_weight_matching', (['gx'], {'maxcardinality': '(True)'}), '(gx, maxcardinality=True)\n', (770, 795), False, 'import networkx\n'), ((1773, 1796), 'numpy.where', 'np.where', (['(grouping == i)'], {}), '(grouping == i)\n', (1781, 1796), True, 'import numpy as np\n'), ((1729, 1750), 'numpy.sum', 'np.sum', (['(grouping == d)'], {}), '(grouping == d)\n', (1735, 1750), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from sfdc_cli.package_xml import PackageXml
command_name = os.path.basename(__file__).split('.', 1)[0].replace("_", ":")
def register(parser, subparsers, **kwargs):
def handler(args):
if args.scandir and args.savedir and args.name and args.apiversion:
PackageXml(project_dir=".").buildFromDir(
scandir=args.scandir,
savepath=args.savedir,
filename=args.name,
api_version=args.apiversion)
else:
print(parser.parse_args([command_name, '--help']))
subcommand = subparsers.add_parser(command_name,
help='see `%s -h`' % command_name)
subcommand.add_argument('-s',
'--scandir',
type=str,
help='save directory',
required=False,
default="src")
subcommand.add_argument('-d',
'--savedir',
type=str,
help='save directory',
required=False,
default=".")
subcommand.add_argument('-n',
'--name',
type=str,
help='filename, default package.xml',
default="package.xml",
required=False)
subcommand.add_argument('-v',
'--apiversion',
type=str,
help='api version, default 47.0',
default="47.0",
required=False)
subcommand.set_defaults(handler=handler)
| [
"os.path.basename",
"sfdc_cli.package_xml.PackageXml"
] | [((116, 142), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (132, 142), False, 'import os\n'), ((337, 364), 'sfdc_cli.package_xml.PackageXml', 'PackageXml', ([], {'project_dir': '"""."""'}), "(project_dir='.')\n", (347, 364), False, 'from sfdc_cli.package_xml import PackageXml\n')] |
from django.conf.urls import url
from basic_app import views
# SET THE NAMESPACE!
app_name = 'basic_app'
urlpatterns=[
url(r'^register/$',views.register,name='register'),
url(r'^user_login/$',views.user_login,name='user_login'),
url(r'^add/$',views.add,name='add'),
url(r'^bookadd/$',views.bookadd,name='bookadd'),
url(r'^bookremove/$',views.bookremove,name='bookremove'),
#url(r'^bookmarks/$',views.bookmarks,name='bookmarks'),
url(r'^index2/$',views.index2,name='news'),
url(r'^summary/$',views.process,name='process'),
url(r'^browse/$',views.browse,name='browse'),
url(r'^show/$',views.show,name='show'),
url(r'^remove/$',views.remove,name='remove'),
url(r'^(?P<id>[\w-]+)/$',views.fire,name='fire'),
url(r'^(?P<id>[\w-]+)/bookmarks$',views.bookmarks,name='bookmarks'),
url(r'^test2/$',views.featured,name='featured'),
]
| [
"django.conf.urls.url"
] | [((125, 176), 'django.conf.urls.url', 'url', (['"""^register/$"""', 'views.register'], {'name': '"""register"""'}), "('^register/$', views.register, name='register')\n", (128, 176), False, 'from django.conf.urls import url\n'), ((181, 238), 'django.conf.urls.url', 'url', (['"""^user_login/$"""', 'views.user_login'], {'name': '"""user_login"""'}), "('^user_login/$', views.user_login, name='user_login')\n", (184, 238), False, 'from django.conf.urls import url\n'), ((243, 279), 'django.conf.urls.url', 'url', (['"""^add/$"""', 'views.add'], {'name': '"""add"""'}), "('^add/$', views.add, name='add')\n", (246, 279), False, 'from django.conf.urls import url\n'), ((284, 332), 'django.conf.urls.url', 'url', (['"""^bookadd/$"""', 'views.bookadd'], {'name': '"""bookadd"""'}), "('^bookadd/$', views.bookadd, name='bookadd')\n", (287, 332), False, 'from django.conf.urls import url\n'), ((337, 394), 'django.conf.urls.url', 'url', (['"""^bookremove/$"""', 'views.bookremove'], {'name': '"""bookremove"""'}), "('^bookremove/$', views.bookremove, name='bookremove')\n", (340, 394), False, 'from django.conf.urls import url\n'), ((459, 502), 'django.conf.urls.url', 'url', (['"""^index2/$"""', 'views.index2'], {'name': '"""news"""'}), "('^index2/$', views.index2, name='news')\n", (462, 502), False, 'from django.conf.urls import url\n'), ((507, 555), 'django.conf.urls.url', 'url', (['"""^summary/$"""', 'views.process'], {'name': '"""process"""'}), "('^summary/$', views.process, name='process')\n", (510, 555), False, 'from django.conf.urls import url\n'), ((560, 605), 'django.conf.urls.url', 'url', (['"""^browse/$"""', 'views.browse'], {'name': '"""browse"""'}), "('^browse/$', views.browse, name='browse')\n", (563, 605), False, 'from django.conf.urls import url\n'), ((610, 649), 'django.conf.urls.url', 'url', (['"""^show/$"""', 'views.show'], {'name': '"""show"""'}), "('^show/$', views.show, name='show')\n", (613, 649), False, 'from django.conf.urls import url\n'), ((654, 699), 'django.conf.urls.url', 'url', (['"""^remove/$"""', 'views.remove'], {'name': '"""remove"""'}), "('^remove/$', views.remove, name='remove')\n", (657, 699), False, 'from django.conf.urls import url\n'), ((704, 754), 'django.conf.urls.url', 'url', (['"""^(?P<id>[\\\\w-]+)/$"""', 'views.fire'], {'name': '"""fire"""'}), "('^(?P<id>[\\\\w-]+)/$', views.fire, name='fire')\n", (707, 754), False, 'from django.conf.urls import url\n'), ((758, 827), 'django.conf.urls.url', 'url', (['"""^(?P<id>[\\\\w-]+)/bookmarks$"""', 'views.bookmarks'], {'name': '"""bookmarks"""'}), "('^(?P<id>[\\\\w-]+)/bookmarks$', views.bookmarks, name='bookmarks')\n", (761, 827), False, 'from django.conf.urls import url\n'), ((831, 879), 'django.conf.urls.url', 'url', (['"""^test2/$"""', 'views.featured'], {'name': '"""featured"""'}), "('^test2/$', views.featured, name='featured')\n", (834, 879), False, 'from django.conf.urls import url\n')] |
# _*_ coding: utf-8 _*_
"""
Implementation of quick sort algorithm.
Reference:
[1] https://runestone.academy/runestone/books/published/pythonds/SortSearch/TheQuickSort.html
Author: <NAME>
"""
from typing import List
def _quick_sort(nums: List[int], li: int, ri: int) -> None:
if li >= ri:
return
split_point = _partition(nums, li, ri)
_quick_sort(nums, li, split_point - 1)
_quick_sort(nums, split_point + 1, ri)
def _partition(nums: List[int], li: int, ri: int) -> int:
pivot_value = nums[li]
left_mark, right_mark = li + 1, ri
done = False
while not done:
while left_mark <= right_mark and nums[left_mark] <= pivot_value:
left_mark += 1
while left_mark <= right_mark and nums[right_mark] >= pivot_value:
right_mark -= 1
if right_mark < left_mark:
done = True
else:
tmp = nums[left_mark]
nums[left_mark] = nums[right_mark]
nums[right_mark] = tmp
tmp = nums[li]
nums[li] = nums[right_mark]
nums[right_mark] = tmp
return right_mark
class QuickSort:
@staticmethod
def quick_sort(nums: List[int]) -> None:
_quick_sort(nums, 0, len(nums) - 1)
if __name__ == "__main__":
from time import time
n = 300
nums = [i for i in range(1, n + 1)]
t0 = time()
QuickSort.quick_sort(nums)
print("[INFO] Done in %.4f seconds" % (time() - t0))
| [
"time.time"
] | [((1341, 1347), 'time.time', 'time', ([], {}), '()\n', (1345, 1347), False, 'from time import time\n'), ((1422, 1428), 'time.time', 'time', ([], {}), '()\n', (1426, 1428), False, 'from time import time\n')] |
#!/usr/bin/env python
"""Command-line interface for skyviewbot"""
# ASTERICS-OBELICS Good Coding Practices (skyviewbot.py)
# <NAME> (<EMAIL>), with suggestions from <NAME>
import sys
from .functions import skyviewbot
from argparse import ArgumentParser, RawTextHelpFormatter
def main(*function_args):
"""Command-line interface to skyviewbot
Args:
List[str]: arguments (typically sys.argv[1:])
Returns:
bool: True if succeeded, False if not
"""
parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
parser.add_argument('field', help='Field, e.g. "M101" or "255.2,1" (if it contains a comma, '
'it\'s interpreted as coordinates, otherwise fed to CDS)')
parser.add_argument('msg', help="Message to accompany the post on Slack")
parser.add_argument('-f', '--fits-name',
default=None,
type=str,
action="store",
help='Specify name of a custom fits file to use as input instead of Skyview (default: %(default)s)')
parser.add_argument('-i', '--slack-id',
default=None,
type=str,
help='Your Slack ID (default: %(default)s)')
parser.add_argument('-s', '--survey',
default='DSS',
type=str,
help="Survey name, e.g. 'DSS' (default: %(default)s)")
parser.add_argument('-r', '--radius',
default=1.,
type=float,
help="Radius (default: %(default)s)")
parser.add_argument('-c', '--colormap',
default="viridis",
type=str,
help="Colormap (default: %(default)s)")
parser.add_argument('-d', '--dry-run',
default=False,
action='store_true',
help='Dry run: make image, do not post to google and slack (default: %(default)s')
args = parser.parse_args(*function_args)
if not args.slack_id:
print('You should use your Slack ID before posting!')
return False
retval = skyviewbot(args.slack_id, args.field, args.fits_name, args.msg, args.survey,
args.radius, args.colormap, dry_run=args.dry_run)
if retval:
print("SkyViewBot posted to Slack successfully")
else:
print("Some error happened in SkyViewBot")
return retval
if __name__ == '__main__':
main(sys.argv[1:])
| [
"argparse.ArgumentParser"
] | [((496, 548), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'formatter_class': 'RawTextHelpFormatter'}), '(formatter_class=RawTextHelpFormatter)\n', (510, 548), False, 'from argparse import ArgumentParser, RawTextHelpFormatter\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 14:39:08 2020
@author: ravi
"""
import scipy.io as scio
import scipy.io.wavfile as scwav
import numpy as np
import joblib
import pyworld as pw
import os
import warnings
warnings.filterwarnings('ignore')
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from glob import glob
from extract_fold_data_hparams import Hparams
from feat_utils import normalize_wav, preprocess_contour
dict_target_emo = {'neutral_angry':['angry', 'neu-ang'], \
'neutral_happy':['happy', 'neu-hap'], \
'neutral_sad':['sad', 'neu-sad']}
def _process_wavs(wav_src, wav_tar, args):
"""
Utterance level features for context expansion
"""
utt_f0_src = list()
utt_f0_tar = list()
utt_ec_src = list()
utt_ec_tar = list()
utt_mfc_src = list()
utt_mfc_tar = list()
try:
src_wav = scwav.read(wav_src)
src = np.asarray(src_wav[1], np.float64)
tar_wav = scwav.read(wav_tar)
tar = np.asarray(tar_wav[1], np.float64)
src = normalize_wav(src, floor=-1, ceil=1)
tar = normalize_wav(tar, floor=-1, ceil=1)
f0_src, t_src = pw.harvest(src, args.fs, frame_period=int(1000*args.win_len))
src_straight = pw.cheaptrick(src, f0_src, t_src, args.fs)
f0_tar, t_tar = pw.harvest(tar, args.fs,frame_period=int(1000*args.win_len))
tar_straight = pw.cheaptrick(tar, f0_tar, t_tar, args.fs)
src_mfc = pw.code_spectral_envelope(src_straight, args.fs, args.n_mels)
tar_mfc = pw.code_spectral_envelope(tar_straight, args.fs, args.n_mels)
ec_src = np.sum(src_mfc, axis=1)
ec_tar = np.sum(tar_mfc, axis=1)
f0_src = preprocess_contour(f0_src)
f0_tar = preprocess_contour(f0_tar)
ec_src = preprocess_contour(ec_src)
ec_tar = preprocess_contour(ec_tar)
f0_src = f0_src.reshape(-1,1)
f0_tar = f0_tar.reshape(-1,1)
ec_src = ec_src.reshape(-1,1)
ec_tar = ec_tar.reshape(-1,1)
min_length = min([len(f0_src), len(f0_tar)])
if min_length<args.frame_len:
return None, None, None, None, None, None, None
else:
for sample in range(args.n_samplings):
start = np.random.randint(0, min_length-args.frame_len+1)
end = start + args.frame_len
utt_f0_src.append(f0_src[start:end,:])
utt_f0_tar.append(f0_tar[start:end,:])
utt_ec_src.append(ec_src[start:end,:])
utt_ec_tar.append(ec_tar[start:end,:])
utt_mfc_src.append(src_mfc[start:end,:])
utt_mfc_tar.append(tar_mfc[start:end,:])
return utt_mfc_src, utt_mfc_tar, utt_f0_src, utt_f0_tar, \
utt_ec_src, utt_ec_tar, int(os.path.basename(wav_src)[:-4])
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print(message)
return None, None, None, None, None, None, None
def extract_features(args):
target = dict_target_emo[args.emo_pair][0]
speaker_file_info = joblib.load('/home/ravi/Downloads/Emo-Conv/speaker_file_info.pkl')
speaker_info = speaker_file_info[args.emo_pair]
test_speaker_female = speaker_info[args.fold - 1]
test_speaker_male = speaker_info[5 + args.fold - 1]
test_file_idx = [i for i in range(test_speaker_female[0], test_speaker_female[1]+1)]
test_file_idx += [i for i in range(test_speaker_male[0], test_speaker_male[1]+1)]
src_files = sorted(glob(os.path.join(args.data_folder, 'neutral', '*.wav')))
tar_files = sorted(glob(os.path.join(args.data_folder, target, '*.wav')))
train_f0_src = list()
train_f0_tar = list()
train_ec_src = list()
train_ec_tar = list()
train_mfc_src = list()
train_mfc_tar = list()
valid_f0_src = list()
valid_f0_tar = list()
valid_ec_src = list()
valid_ec_tar = list()
valid_mfc_src = list()
valid_mfc_tar = list()
test_f0_src = list()
test_f0_tar = list()
test_ec_src = list()
test_ec_tar = list()
test_mfc_src = list()
test_mfc_tar = list()
train_files = list()
valid_files = list()
test_files = list()
executor = ProcessPoolExecutor(max_workers=6)
futures = []
for (s,t) in zip(src_files, tar_files):
print("Processing: {0}".format(s))
futures.append(executor.submit(partial(_process_wavs, s, t,
args=args)))
results = [future.result() for future in tqdm(futures)]
for i in range(len(results)):
result = results[i]
mfc_src = result[0]
mfc_tar = result[1]
f0_src = result[2]
f0_tar = result[3]
ec_src = result[4]
ec_tar = result[5]
file_idx= result[6]
# mfc_src, mfc_tar, f0_src, \
# f0_tar, ec_src, ec_tar, file_idx = _process_wavs(s,t,args)
if mfc_src:
if file_idx in test_file_idx:
test_mfc_src.append(mfc_src)
test_mfc_tar.append(mfc_tar)
test_f0_src.append(f0_src)
test_f0_tar.append(f0_tar)
test_ec_src.append(ec_src)
test_ec_tar.append(ec_tar)
test_files.append(int(os.path.basename(s)[:-4]))
else:
if np.random.rand()<args.eval_size:
valid_mfc_src.append(mfc_src)
valid_mfc_tar.append(mfc_tar)
valid_f0_src.append(f0_src)
valid_f0_tar.append(f0_tar)
valid_ec_src.append(ec_src)
valid_ec_tar.append(ec_tar)
valid_files.append(int(os.path.basename(s)[:-4]))
else:
train_mfc_src.append(mfc_src)
train_mfc_tar.append(mfc_tar)
train_f0_src.append(f0_src)
train_f0_tar.append(f0_tar)
train_ec_src.append(ec_src)
train_ec_tar.append(ec_tar)
train_files.append(int(os.path.basename(s)[:-4]))
data_dict = {
'train_mfc_feat_src':np.asarray(train_mfc_src, np.float32),
'train_mfc_feat_tar':np.asarray(train_mfc_tar, np.float32),
'train_f0_feat_src':np.asarray(train_f0_src, np.float32),
'train_f0_feat_tar':np.asarray(train_f0_tar, np.float32),
'train_ec_feat_src':np.asarray(train_ec_src, np.float32),
'train_ec_feat_tar':np.asarray(train_ec_tar, np.float32),
'valid_mfc_feat_src':np.asarray(valid_mfc_src, np.float32),
'valid_mfc_feat_tar':np.asarray(valid_mfc_tar, np.float32),
'valid_f0_feat_src':np.asarray(valid_f0_src, np.float32),
'valid_f0_feat_tar':np.asarray(valid_f0_tar, np.float32),
'valid_ec_feat_src':np.asarray(valid_ec_src, np.float32),
'valid_ec_feat_tar':np.asarray(valid_ec_tar, np.float32),
'test_mfc_feat_src':np.asarray(test_mfc_src, np.float32),
'test_mfc_feat_tar':np.asarray(test_mfc_tar, np.float32),
'test_f0_feat_src':np.asarray(test_f0_src, np.float32),
'test_f0_feat_tar':np.asarray(test_f0_tar, np.float32),
'test_ec_feat_src':np.asarray(test_ec_src, np.float32),
'test_ec_feat_tar':np.asarray(test_ec_tar, np.float32),
'train_files':np.reshape(np.array(train_files), (-1,1)),
'valid_files':np.reshape(np.array(valid_files), (-1,1)),
'test_files':np.reshape(np.array(test_files), (-1,1))
}
return data_dict
if __name__ == '__main__':
hparams = Hparams()
parser = hparams.parser
hp = parser.parse_args()
hp.data_folder = '/home/ravi/Downloads/Emo-Conv/neutral-sad/all_above_0.5'
hp.emo_pair = 'neutral_sad'
for i in range(1, 6):
hp.fold = i
data_dict = extract_features(hp)
scio.savemat('/home/ravi/Desktop/neu-sad_fold_{0}.mat'.format(i), data_dict)
del data_dict | [
"feat_utils.preprocess_contour",
"numpy.random.rand",
"pyworld.code_spectral_envelope",
"pyworld.cheaptrick",
"tqdm.tqdm",
"numpy.asarray",
"extract_fold_data_hparams.Hparams",
"os.path.join",
"numpy.sum",
"numpy.array",
"numpy.random.randint",
"scipy.io.wavfile.read",
"functools.partial",
... | [((244, 277), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (267, 277), False, 'import warnings\n'), ((3408, 3474), 'joblib.load', 'joblib.load', (['"""/home/ravi/Downloads/Emo-Conv/speaker_file_info.pkl"""'], {}), "('/home/ravi/Downloads/Emo-Conv/speaker_file_info.pkl')\n", (3419, 3474), False, 'import joblib\n'), ((4563, 4597), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': '(6)'}), '(max_workers=6)\n', (4582, 4597), False, 'from concurrent.futures import ProcessPoolExecutor\n'), ((8058, 8067), 'extract_fold_data_hparams.Hparams', 'Hparams', ([], {}), '()\n', (8065, 8067), False, 'from extract_fold_data_hparams import Hparams\n'), ((1018, 1037), 'scipy.io.wavfile.read', 'scwav.read', (['wav_src'], {}), '(wav_src)\n', (1028, 1037), True, 'import scipy.io.wavfile as scwav\n'), ((1052, 1086), 'numpy.asarray', 'np.asarray', (['src_wav[1]', 'np.float64'], {}), '(src_wav[1], np.float64)\n', (1062, 1086), True, 'import numpy as np\n'), ((1106, 1125), 'scipy.io.wavfile.read', 'scwav.read', (['wav_tar'], {}), '(wav_tar)\n', (1116, 1125), True, 'import scipy.io.wavfile as scwav\n'), ((1140, 1174), 'numpy.asarray', 'np.asarray', (['tar_wav[1]', 'np.float64'], {}), '(tar_wav[1], np.float64)\n', (1150, 1174), True, 'import numpy as np\n'), ((1198, 1234), 'feat_utils.normalize_wav', 'normalize_wav', (['src'], {'floor': '(-1)', 'ceil': '(1)'}), '(src, floor=-1, ceil=1)\n', (1211, 1234), False, 'from feat_utils import normalize_wav, preprocess_contour\n'), ((1249, 1285), 'feat_utils.normalize_wav', 'normalize_wav', (['tar'], {'floor': '(-1)', 'ceil': '(1)'}), '(tar, floor=-1, ceil=1)\n', (1262, 1285), False, 'from feat_utils import normalize_wav, preprocess_contour\n'), ((1401, 1443), 'pyworld.cheaptrick', 'pw.cheaptrick', (['src', 'f0_src', 't_src', 'args.fs'], {}), '(src, f0_src, t_src, args.fs)\n', (1414, 1443), True, 'import pyworld as pw\n'), ((1558, 1600), 'pyworld.cheaptrick', 'pw.cheaptrick', (['tar', 'f0_tar', 't_tar', 'args.fs'], {}), '(tar, f0_tar, t_tar, args.fs)\n', (1571, 1600), True, 'import pyworld as pw\n'), ((1620, 1681), 'pyworld.code_spectral_envelope', 'pw.code_spectral_envelope', (['src_straight', 'args.fs', 'args.n_mels'], {}), '(src_straight, args.fs, args.n_mels)\n', (1645, 1681), True, 'import pyworld as pw\n'), ((1700, 1761), 'pyworld.code_spectral_envelope', 'pw.code_spectral_envelope', (['tar_straight', 'args.fs', 'args.n_mels'], {}), '(tar_straight, args.fs, args.n_mels)\n', (1725, 1761), True, 'import pyworld as pw\n'), ((1780, 1803), 'numpy.sum', 'np.sum', (['src_mfc'], {'axis': '(1)'}), '(src_mfc, axis=1)\n', (1786, 1803), True, 'import numpy as np\n'), ((1821, 1844), 'numpy.sum', 'np.sum', (['tar_mfc'], {'axis': '(1)'}), '(tar_mfc, axis=1)\n', (1827, 1844), True, 'import numpy as np\n'), ((1871, 1897), 'feat_utils.preprocess_contour', 'preprocess_contour', (['f0_src'], {}), '(f0_src)\n', (1889, 1897), False, 'from feat_utils import normalize_wav, preprocess_contour\n'), ((1915, 1941), 'feat_utils.preprocess_contour', 'preprocess_contour', (['f0_tar'], {}), '(f0_tar)\n', (1933, 1941), False, 'from feat_utils import normalize_wav, preprocess_contour\n'), ((1960, 1986), 'feat_utils.preprocess_contour', 'preprocess_contour', (['ec_src'], {}), '(ec_src)\n', (1978, 1986), False, 'from feat_utils import normalize_wav, preprocess_contour\n'), ((2004, 2030), 'feat_utils.preprocess_contour', 'preprocess_contour', (['ec_tar'], {}), '(ec_tar)\n', (2022, 2030), False, 'from feat_utils import normalize_wav, preprocess_contour\n'), ((6544, 6581), 'numpy.asarray', 'np.asarray', (['train_mfc_src', 'np.float32'], {}), '(train_mfc_src, np.float32)\n', (6554, 6581), True, 'import numpy as np\n'), ((6617, 6654), 'numpy.asarray', 'np.asarray', (['train_mfc_tar', 'np.float32'], {}), '(train_mfc_tar, np.float32)\n', (6627, 6654), True, 'import numpy as np\n'), ((6688, 6724), 'numpy.asarray', 'np.asarray', (['train_f0_src', 'np.float32'], {}), '(train_f0_src, np.float32)\n', (6698, 6724), True, 'import numpy as np\n'), ((6758, 6794), 'numpy.asarray', 'np.asarray', (['train_f0_tar', 'np.float32'], {}), '(train_f0_tar, np.float32)\n', (6768, 6794), True, 'import numpy as np\n'), ((6828, 6864), 'numpy.asarray', 'np.asarray', (['train_ec_src', 'np.float32'], {}), '(train_ec_src, np.float32)\n', (6838, 6864), True, 'import numpy as np\n'), ((6898, 6934), 'numpy.asarray', 'np.asarray', (['train_ec_tar', 'np.float32'], {}), '(train_ec_tar, np.float32)\n', (6908, 6934), True, 'import numpy as np\n'), ((6969, 7006), 'numpy.asarray', 'np.asarray', (['valid_mfc_src', 'np.float32'], {}), '(valid_mfc_src, np.float32)\n', (6979, 7006), True, 'import numpy as np\n'), ((7042, 7079), 'numpy.asarray', 'np.asarray', (['valid_mfc_tar', 'np.float32'], {}), '(valid_mfc_tar, np.float32)\n', (7052, 7079), True, 'import numpy as np\n'), ((7113, 7149), 'numpy.asarray', 'np.asarray', (['valid_f0_src', 'np.float32'], {}), '(valid_f0_src, np.float32)\n', (7123, 7149), True, 'import numpy as np\n'), ((7183, 7219), 'numpy.asarray', 'np.asarray', (['valid_f0_tar', 'np.float32'], {}), '(valid_f0_tar, np.float32)\n', (7193, 7219), True, 'import numpy as np\n'), ((7253, 7289), 'numpy.asarray', 'np.asarray', (['valid_ec_src', 'np.float32'], {}), '(valid_ec_src, np.float32)\n', (7263, 7289), True, 'import numpy as np\n'), ((7323, 7359), 'numpy.asarray', 'np.asarray', (['valid_ec_tar', 'np.float32'], {}), '(valid_ec_tar, np.float32)\n', (7333, 7359), True, 'import numpy as np\n'), ((7393, 7429), 'numpy.asarray', 'np.asarray', (['test_mfc_src', 'np.float32'], {}), '(test_mfc_src, np.float32)\n', (7403, 7429), True, 'import numpy as np\n'), ((7464, 7500), 'numpy.asarray', 'np.asarray', (['test_mfc_tar', 'np.float32'], {}), '(test_mfc_tar, np.float32)\n', (7474, 7500), True, 'import numpy as np\n'), ((7533, 7568), 'numpy.asarray', 'np.asarray', (['test_f0_src', 'np.float32'], {}), '(test_f0_src, np.float32)\n', (7543, 7568), True, 'import numpy as np\n'), ((7601, 7636), 'numpy.asarray', 'np.asarray', (['test_f0_tar', 'np.float32'], {}), '(test_f0_tar, np.float32)\n', (7611, 7636), True, 'import numpy as np\n'), ((7669, 7704), 'numpy.asarray', 'np.asarray', (['test_ec_src', 'np.float32'], {}), '(test_ec_src, np.float32)\n', (7679, 7704), True, 'import numpy as np\n'), ((7737, 7772), 'numpy.asarray', 'np.asarray', (['test_ec_tar', 'np.float32'], {}), '(test_ec_tar, np.float32)\n', (7747, 7772), True, 'import numpy as np\n'), ((3850, 3900), 'os.path.join', 'os.path.join', (['args.data_folder', '"""neutral"""', '"""*.wav"""'], {}), "(args.data_folder, 'neutral', '*.wav')\n", (3862, 3900), False, 'import os\n'), ((3931, 3978), 'os.path.join', 'os.path.join', (['args.data_folder', 'target', '"""*.wav"""'], {}), "(args.data_folder, target, '*.wav')\n", (3943, 3978), False, 'import os\n'), ((4886, 4899), 'tqdm.tqdm', 'tqdm', (['futures'], {}), '(futures)\n', (4890, 4899), False, 'from tqdm import tqdm\n'), ((7811, 7832), 'numpy.array', 'np.array', (['train_files'], {}), '(train_files)\n', (7819, 7832), True, 'import numpy as np\n'), ((7881, 7902), 'numpy.array', 'np.array', (['valid_files'], {}), '(valid_files)\n', (7889, 7902), True, 'import numpy as np\n'), ((7950, 7970), 'numpy.array', 'np.array', (['test_files'], {}), '(test_files)\n', (7958, 7970), True, 'import numpy as np\n'), ((2434, 2487), 'numpy.random.randint', 'np.random.randint', (['(0)', '(min_length - args.frame_len + 1)'], {}), '(0, min_length - args.frame_len + 1)\n', (2451, 2487), True, 'import numpy as np\n'), ((4746, 4785), 'functools.partial', 'partial', (['_process_wavs', 's', 't'], {'args': 'args'}), '(_process_wavs, s, t, args=args)\n', (4753, 4785), False, 'from functools import partial\n'), ((3030, 3055), 'os.path.basename', 'os.path.basename', (['wav_src'], {}), '(wav_src)\n', (3046, 3055), False, 'import os\n'), ((5709, 5725), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (5723, 5725), True, 'import numpy as np\n'), ((5645, 5664), 'os.path.basename', 'os.path.basename', (['s'], {}), '(s)\n', (5661, 5664), False, 'import os\n'), ((6077, 6096), 'os.path.basename', 'os.path.basename', (['s'], {}), '(s)\n', (6093, 6096), False, 'import os\n'), ((6461, 6480), 'os.path.basename', 'os.path.basename', (['s'], {}), '(s)\n', (6477, 6480), False, 'import os\n')] |
import numpy as np
import cv2
import errno
# set environment variable
import os
os.environ['OPENCV_IO_ENABLE_JASPER']= 'TRUE' # allows JPEG2000 format
# path of this file
det_path = os.path.split(os.path.abspath(__file__))[0] + '/'
class DimensionError(Exception):
"""
raised when the image does not meet the required
maximum dimensions of 1024 x 1024.
"""
def __init__(self, h, w):
message = "Image is too big " + str((h, w))
message += "; max allowed size is (1024, 1024)"
super(DimensionError, self).__init__(message)
def detect_largest_face(in_path, out_path=None, min_conf=0.8):
"""
Detects largest face using the DNN face detection algorithm
from cv2 library.
Args:
in_path (str): path of the input image file
out_path (str, optional): path of the cropped image file. Defaults to None
min_conf (float, optional): threshold confidence to detect face. Defaults to 0.8
Returns:
bounding_box: an 2x2 array of two (x,y) coordinates
for top left and bottom right of the bounding box
"""
# check input file path
if not os.path.isfile(in_path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), in_path)
# check output file path
if out_path:
try:
with open(out_path, 'w') as f:
pass
except OSError:
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), out_path)
# read file
img = cv2.imread(in_path)
# check image dimensions
h, w = img.shape[:2]
if h > 1024 or w > 1024:
raise DimensionError(h, w)
# detect faces using DNN algorithm from cv2
net = cv2.dnn.readNetFromCaffe(
det_path + "models/deploy.prototxt",
det_path + "models/res10_300x300_ssd_iter_140000.caffemodel"
)
rgb_mean = np.mean(img, axis=(0, 1)) # mean rgb values to remove effects of illumination
blob = cv2.dnn.blobFromImage(cv2.resize(img, (300,300)), 1.0, (300, 300), rgb_mean)
net.setInput(blob)
faces = net.forward()
# get the most confident faces
conf_faces = np.array(list(filter(lambda x: x[2] > min_conf, faces[0, 0])))
# check if any faces exist
assert len(conf_faces) > 0, "No faces found!"
# get the largest face
first_face = 0 # let first face be biggest face
first_box = conf_faces[first_face, 3:7] * np.array([w, h, w, h])
sx, sy, ex, ey = first_box.astype("int")
for i in range(1, conf_faces.shape[0]):
box = conf_faces[i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
if (endX - startX)*(endY - startY) > (ex - sx)*(ey - sy):
sx, sy, ex, ey = startX, startY, endX, endY
# save the crop
if out_path:
largest_crop = img[sy:ey, sx:ex]
saved_file = cv2.imwrite(out_path, largest_crop)
# return the largest bounding box
bounding_box = [(sx, sy), (ex, ey)]
return bounding_box | [
"numpy.mean",
"cv2.imwrite",
"os.strerror",
"cv2.dnn.readNetFromCaffe",
"os.path.isfile",
"numpy.array",
"os.path.abspath",
"cv2.resize",
"cv2.imread"
] | [((1585, 1604), 'cv2.imread', 'cv2.imread', (['in_path'], {}), '(in_path)\n', (1595, 1604), False, 'import cv2\n'), ((1783, 1910), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (["(det_path + 'models/deploy.prototxt')", "(det_path + 'models/res10_300x300_ssd_iter_140000.caffemodel')"], {}), "(det_path + 'models/deploy.prototxt', det_path +\n 'models/res10_300x300_ssd_iter_140000.caffemodel')\n", (1807, 1910), False, 'import cv2\n'), ((1949, 1974), 'numpy.mean', 'np.mean', (['img'], {'axis': '(0, 1)'}), '(img, axis=(0, 1))\n', (1956, 1974), True, 'import numpy as np\n'), ((1203, 1226), 'os.path.isfile', 'os.path.isfile', (['in_path'], {}), '(in_path)\n', (1217, 1226), False, 'import os\n'), ((2060, 2087), 'cv2.resize', 'cv2.resize', (['img', '(300, 300)'], {}), '(img, (300, 300))\n', (2070, 2087), False, 'import cv2\n'), ((2488, 2510), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (2496, 2510), True, 'import numpy as np\n'), ((2947, 2982), 'cv2.imwrite', 'cv2.imwrite', (['out_path', 'largest_crop'], {}), '(out_path, largest_crop)\n', (2958, 2982), False, 'import cv2\n'), ((200, 225), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (215, 225), False, 'import os\n'), ((1274, 1299), 'os.strerror', 'os.strerror', (['errno.ENOENT'], {}), '(errno.ENOENT)\n', (1285, 1299), False, 'import os\n'), ((2636, 2658), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (2644, 2658), True, 'import numpy as np\n'), ((1521, 1546), 'os.strerror', 'os.strerror', (['errno.ENOENT'], {}), '(errno.ENOENT)\n', (1532, 1546), False, 'import os\n')] |
#
# Connects to SlideRule server at provided url and prints log messages
# generated on server to local terminal
#
import sys
import logging
from sliderule import sliderule
from sliderule import icesat2
###############################################################################
# GLOBAL CODE
###############################################################################
# configure logging
logging.basicConfig(level=logging.INFO)
###############################################################################
# MAIN
###############################################################################
if __name__ == '__main__':
# Override server URL from command line
url = ["127.0.0.1"]
if len(sys.argv) > 1:
url = sys.argv[1]
# Override duration to maintain connection
duration = 30 # seconds
if len(sys.argv) > 2:
duration = int(sys.argv[2])
# Override event type
event_type = "LOG"
if len(sys.argv) > 3:
event_type = sys.argv[3]
# Override event level
event_level = "INFO"
if len(sys.argv) > 4:
event_level = sys.argv[4]
# Bypass service discovery if url supplied
if len(sys.argv) > 5:
if sys.argv[5] == "bypass":
url = [url]
# Initialize ICESat2/SlideRule Package
icesat2.init(url, True)
# Build Logging Request
rqst = {
"type": event_type,
"level" : event_level,
"duration": duration
}
# Retrieve logs
rsps = sliderule.source("event", rqst, stream=True)
| [
"logging.basicConfig",
"sliderule.icesat2.init",
"sliderule.sliderule.source"
] | [((401, 440), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (420, 440), False, 'import logging\n'), ((1300, 1323), 'sliderule.icesat2.init', 'icesat2.init', (['url', '(True)'], {}), '(url, True)\n', (1312, 1323), False, 'from sliderule import icesat2\n'), ((1493, 1537), 'sliderule.sliderule.source', 'sliderule.source', (['"""event"""', 'rqst'], {'stream': '(True)'}), "('event', rqst, stream=True)\n", (1509, 1537), False, 'from sliderule import sliderule\n')] |
import setuptools
requirements = [
'docopt',
'numpy',
'pyzmq'
]
console_scripts = [
'lambda_client=lambda_scope.zmq.client:main',
'lambda_forwarder=lambda_scope.zmq.forwarder:main',
'lambda_hub=lambda_scope.devices.hub_relay:main',
'lambda_publisher=lambda_scope.zmq.publisher:main',
'lambda_server=lambda_scope.zmq.server:main',
'lambda_subscriber=lambda_scope.zmq.subscriber:main',
'lambda_logger=lambda_scope.devices.logger:main',
'lambda_dragonfly=lambda_scope.devices.dragonfly:main',
'lambda_acquisition_board=lambda_scope.devices.acquisition_board:main',
'lambda_displayer=lambda_scope.devices.displayer:main',
'lambda_data_hub=lambda_scope.devices.data_hub:main',
'lambda_stage_data_hub=lambda_scope.devices.stage_data_hub:main',
'lambda_writer=lambda_scope.devices.writer:main',
'lambda_processor=lambda_scope.devices.processor:main',
'lambda_commands=lambda_scope.devices.commands:main',
'lambda_zaber=lambda_scope.devices.zaber:main',
'lambda_stage_tracker=lambda_scope.devices.stage_tracker:main',
'lambda_valve_control=lambda_scope.devices.valve_control:main',
'lambda_microfluidic=lambda_scope.devices.microfluidic:main',
'lambda_app=lambda_scope.devices.app:main',
'lambda_stage=lambda_scope.system.stage:main',
'lambda=lambda_scope.system.lambda:main'
]
setuptools.setup(
name="lambda_scope",
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="Software to operate the customized imaging system, lambda.",
url="https://github.com/venkatachalamlab/lambda",
project_urls={
"Bug Tracker": "https://github.com/venkatachalamlab/lambda/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: Microsoft :: Windows :: Windows 10",
],
entry_points={
'console_scripts': console_scripts
},
install_requires=requirements,
packages=['lambda_scope'],
python_requires=">=3.6",
)
| [
"setuptools.setup"
] | [((1373, 2002), 'setuptools.setup', 'setuptools.setup', ([], {'name': '"""lambda_scope"""', 'version': '"""0.0.1"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'description': '"""Software to operate the customized imaging system, lambda."""', 'url': '"""https://github.com/venkatachalamlab/lambda"""', 'project_urls': "{'Bug Tracker': 'https://github.com/venkatachalamlab/lambda/issues'}", 'classifiers': "['Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: Microsoft :: Windows :: Windows 10']", 'entry_points': "{'console_scripts': console_scripts}", 'install_requires': 'requirements', 'packages': "['lambda_scope']", 'python_requires': '""">=3.6"""'}), "(name='lambda_scope', version='0.0.1', author='<NAME>',\n author_email='<EMAIL>', description=\n 'Software to operate the customized imaging system, lambda.', url=\n 'https://github.com/venkatachalamlab/lambda', project_urls={\n 'Bug Tracker': 'https://github.com/venkatachalamlab/lambda/issues'},\n classifiers=['Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: Microsoft :: Windows :: Windows 10'], entry_points\n ={'console_scripts': console_scripts}, install_requires=requirements,\n packages=['lambda_scope'], python_requires='>=3.6')\n", (1389, 2002), False, 'import setuptools\n')] |
"""
NCL_coneff_16.py
================
This script illustrates the following concepts:
- Showing features of the new color display model
- Using a NCL colormap with levels to assign a color palette to contours
- Drawing partially transparent filled contours
See following URLs to see the reproduced NCL plot & script:
- Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/coneff_16.ncl
- Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/coneff_16_1_lg.png
"""
###############################################################################
# Import packages:
import numpy as np
import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import geocat.datafiles as gdf
from geocat.viz import cmaps as gvcmaps
from geocat.viz import util as gvutil
###############################################################################
# Read in data:
# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get('netcdf_files/uv300.nc'))
U = ds.U[1, :, :]
###############################################################################
# Plot:
# Generate figure (set its size (width, height) in inches)
plt.figure(figsize=(14, 7))
# Generate axes, using Cartopy
projection = ccrs.PlateCarree()
ax = plt.axes(projection=projection)
# Use global map and draw coastlines
ax.set_global()
ax.coastlines()
# Import an NCL colormap
newcmp = gvcmaps.BlueYellowRed
# Contourf-plot data (for filled contours)
# Note, min-max contour levels are hard-coded. contourf's automatic contour value selector produces fractional values.
p = U.plot.contourf(ax=ax,
vmin=-16.0,
vmax=44,
levels=16,
cmap=newcmp,
add_colorbar=False,
transform=projection,
extend='neither')
# Add horizontal colorbar
cbar = plt.colorbar(p, orientation='horizontal', shrink=0.5)
cbar.ax.tick_params(labelsize=14)
cbar.set_ticks(np.linspace(-12, 40, 14))
# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(ax,
xticks=np.linspace(-180, 180, 13),
yticks=np.linspace(-90, 90, 7))
# Use geocat.viz.util convenience function to make plots look like NCL plots by using latitude, longitude tick labels
gvutil.add_lat_lon_ticklabels(ax)
# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax, labelsize=12)
# Use geocat.viz.util convenience function to add titles to left and right of the plot axis.
gvutil.set_titles_and_labels(ax,
maintitle="Color contours mask filled land",
lefttitle=U.long_name,
lefttitlefontsize=16,
righttitle=U.units,
righttitlefontsize=16,
xlabel="",
ylabel="")
# Show the plot
plt.show()
| [
"geocat.datafiles.get",
"geocat.viz.util.add_major_minor_ticks",
"matplotlib.pyplot.colorbar",
"cartopy.crs.PlateCarree",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.pyplot.axes",
"geocat.viz.util.add_lat_lon_ticklabels",
"geocat.viz.util.set_titles_and_labels",
"matplotlib.pyplot.sh... | [((1221, 1248), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(14, 7)'}), '(figsize=(14, 7))\n', (1231, 1248), True, 'import matplotlib.pyplot as plt\n'), ((1294, 1312), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (1310, 1312), True, 'import cartopy.crs as ccrs\n'), ((1318, 1349), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': 'projection'}), '(projection=projection)\n', (1326, 1349), True, 'import matplotlib.pyplot as plt\n'), ((1946, 1999), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['p'], {'orientation': '"""horizontal"""', 'shrink': '(0.5)'}), "(p, orientation='horizontal', shrink=0.5)\n", (1958, 1999), True, 'import matplotlib.pyplot as plt\n'), ((2432, 2465), 'geocat.viz.util.add_lat_lon_ticklabels', 'gvutil.add_lat_lon_ticklabels', (['ax'], {}), '(ax)\n', (2461, 2465), True, 'from geocat.viz import util as gvutil\n'), ((2544, 2590), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax'], {'labelsize': '(12)'}), '(ax, labelsize=12)\n', (2572, 2590), True, 'from geocat.viz import util as gvutil\n'), ((2685, 2886), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax'], {'maintitle': '"""Color contours mask filled land"""', 'lefttitle': 'U.long_name', 'lefttitlefontsize': '(16)', 'righttitle': 'U.units', 'righttitlefontsize': '(16)', 'xlabel': '""""""', 'ylabel': '""""""'}), "(ax, maintitle=\n 'Color contours mask filled land', lefttitle=U.long_name,\n lefttitlefontsize=16, righttitle=U.units, righttitlefontsize=16, xlabel\n ='', ylabel='')\n", (2713, 2886), True, 'from geocat.viz import util as gvutil\n'), ((3093, 3103), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3101, 3103), True, 'import matplotlib.pyplot as plt\n'), ((1020, 1052), 'geocat.datafiles.get', 'gdf.get', (['"""netcdf_files/uv300.nc"""'], {}), "('netcdf_files/uv300.nc')\n", (1027, 1052), True, 'import geocat.datafiles as gdf\n'), ((2049, 2073), 'numpy.linspace', 'np.linspace', (['(-12)', '(40)', '(14)'], {}), '(-12, 40, 14)\n', (2060, 2073), True, 'import numpy as np\n'), ((2220, 2246), 'numpy.linspace', 'np.linspace', (['(-180)', '(180)', '(13)'], {}), '(-180, 180, 13)\n', (2231, 2246), True, 'import numpy as np\n'), ((2288, 2311), 'numpy.linspace', 'np.linspace', (['(-90)', '(90)', '(7)'], {}), '(-90, 90, 7)\n', (2299, 2311), True, 'import numpy as np\n')] |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///gosts.db')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
#по идеи это все надо вынестии в __init__ файл
class Gost(Base):
__tablename__ = 'gosts'
id = Column(Integer, primary_key=True)
name = Column(String)
description = Column(String)
def __str__(self):
return self.name | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.create_engine",
"sqlalchemy.Column",
"sqlalchemy.ext.declarative.declarative_base"
] | [((247, 282), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///gosts.db"""'], {}), "('sqlite:///gosts.db')\n", (260, 282), False, 'from sqlalchemy import create_engine\n'), ((293, 318), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'bind': 'engine'}), '(bind=engine)\n', (305, 318), False, 'from sqlalchemy.orm import sessionmaker\n'), ((346, 364), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (362, 364), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((468, 501), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (474, 501), False, 'from sqlalchemy import Column, Integer, String\n'), ((513, 527), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (519, 527), False, 'from sqlalchemy import Column, Integer, String\n'), ((546, 560), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (552, 560), False, 'from sqlalchemy import Column, Integer, String\n')] |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = '<NAME>'
import re
from functools import lru_cache
import numpy as np
import pandas as pd
from .reaction import Reaction
from .metabolite import Metabolite
from ..optim.optim import FBAOptimizer, TFBAOptimizer, ETFBAOptimizer
from .pdict import PrettyDict
class Model():
'''
Attributes
metabolites: PrettyDict
metabolite ID => Metabolite
reactions: PrettyDict
reaction ID => Reaction
end_metabolites: PrettyDict
metabolite ID => Metabolite, initial substrates or final products of the model
stoichiometric_matrix: DataFrame
stoichiometric matrix, rows are metabolites, columns are forward reactions
total_stoichiometric_matrix: DataFrame
stoichiometric matrix, rows are metabolites, columns are total (forward and backward) reactions
'''
def __init__(self, name = None):
'''
Parameters
name: str
model name
'''
self.name = name
self._metabolites = PrettyDict()
self._reactions = PrettyDict()
self._end_metabolites = PrettyDict()
self._stoichiometric_matrix = pd.DataFrame()
self._total_stoichiometric_matrix = pd.DataFrame()
@staticmethod
def _float(string):
return np.nan if string == '' else float(string)
def read_from_excel(self, filename):
'''
Parameters
filename: str
path of excel file with fields:
Enzyme, Substrates, Products, Sub Kms (mM), Pro Kms (mM),
Fwd kcat (1/s), Bwd kcat (1/s), MW (kDa) and ΔrG'm (kJ/mol)
'''
modelData = pd.read_excel(filename, header = 0, index_col = 0, comment = '#').fillna('').astype(str)
for rxnid, rowInfos in modelData.iterrows():
subsStr, prosStr, rev, subkms, prokms, fkcat, bkcat, mw, dgpm = rowInfos
fkcat = self._float(fkcat)
bkcat = self._float(bkcat)
rev = float(rev)
mw = self._float(mw)
dgpm = self._float(dgpm)
rxn = Reaction(rxnid, forward_kcat = fkcat, backward_kcat = bkcat, reversible = bool(rev),
molecular_weight = mw, standard_deltaG = dgpm)
if re.search(r'biomass', prosStr, flags = re.I):
rxn.is_biomass_formation = True
if re.match(r'^[\w\._]+\.o$', subsStr) or re.match(r'^[\w\._]+\.o$', prosStr):
rxn.is_exchange = True
subStrLst = subsStr.split(';')
subkmLst = subkms.split(';')
if len(subStrLst) != len(subkmLst) and not rxn.is_biomass_formation:
raise ValueError('the number of subtrates in %s does not match the number of subtrate Km values' % rxnid)
proStrLst = prosStr.split(';')
prokmLst = prokms.split(';')
if len(proStrLst) != len(prokmLst) and not rxn.is_biomass_formation:
raise ValueError('the number of products in %s does not match the number of product Km values' % rxnid)
for idx, subStr in enumerate(subStrLst):
coe_sub = subStr.split()
if len(coe_sub) == 1:
coe, subid = 1.0, coe_sub[0]
else:
coe, subid = coe_sub
sub = self._metabolites.setdefault(subid, Metabolite(subid))
sub.coes[rxnid] = float(coe)
if rxn.is_biomass_formation or rxn.is_exchange:
sub.kms[rxnid] = None
else:
sub.kms[rxnid] = self._float(subkmLst[idx])
rxn.substrates[subid] = sub
for idx, proStr in enumerate(proStrLst):
coe_pro = proStr.split()
if len(coe_pro) == 1:
coe, proid = 1.0, coe_pro[0]
else:
coe, proid = coe_pro
pro = self._metabolites.setdefault(proid, Metabolite(proid))
pro.coes[rxnid] = float(coe)
if rxn.is_biomass_formation or rxn.is_exchange:
pro.kms[rxnid] = None
else:
pro.kms[rxnid] = self._float(prokmLst[idx])
rxn.products[proid] = pro
self._reactions[rxnid] = rxn
@property
def metabolites(self):
if len(self._metabolites) == 0:
raise AttributeError('no metabolite found, model empty')
else:
return self._metabolites
@property
def reactions(self):
if len(self._reactions) == 0:
raise AttributeError('no reaction found, model empty')
else:
return self._reactions
@lru_cache()
def _get_stoichiometric_matrix(self):
stoyMat = pd.DataFrame(0, index = sorted(self._metabolites), columns = sorted(self._reactions))
for rxnid in self.reactions:
for metabid in self.reactions[rxnid].substrates:
stoyMat.loc[metabid, rxnid] = -self.reactions[rxnid].substrates[metabid].coe
for metabid in self.reactions[rxnid].products:
stoyMat.loc[metabid, rxnid] = self.reactions[rxnid].products[metabid].coe
return stoyMat
@property
def stoichiometric_matrix(self):
if len(self._metabolites) == 0 and len(self._reactions) == 0:
raise AttributeError('no metabolite or reaction found, model empty')
if self._stoichiometric_matrix.empty:
self._stoichiometric_matrix = self._get_stoichiometric_matrix()
return self._stoichiometric_matrix
@lru_cache()
def _get_total_stoichiometric_matrix(self):
cols = ['']*len(self._reactions)*2
cols[::2] = [r+'_f' for r in sorted(self._reactions)]
cols[1::2] = [r+'_b' for r in sorted(self._reactions)]
stoyExtMat = pd.DataFrame(0, index = sorted(self._metabolites), columns = cols)
for rxnid in self.reactions:
for metabid in self.reactions[rxnid].substrates:
coe = self.reactions[rxnid].substrates[metabid].coe
stoyExtMat.loc[metabid, rxnid+'_f'] = -coe
stoyExtMat.loc[metabid, rxnid+'_b'] = coe
for metabid in self.reactions[rxnid].products:
coe = self.reactions[rxnid].products[metabid].coe
stoyExtMat.loc[metabid, rxnid+'_f'] = coe
stoyExtMat.loc[metabid, rxnid+'_b'] = -coe
return stoyExtMat
@property
def total_stoichiometric_matrix(self):
if len(self._metabolites) == 0 and len(self._reactions) == 0:
raise AttributeError('no metabolite or reaction found, model empty')
if self._total_stoichiometric_matrix.empty:
self._total_stoichiometric_matrix = self._get_total_stoichiometric_matrix()
return self._total_stoichiometric_matrix
@lru_cache()
def _get_end_metabolites(self):
endsDict = PrettyDict()
for metabid, row in self.stoichiometric_matrix.iterrows():
if row[row!=0].size == 1:
endsDict[metabid] = self.metabolites[metabid]
return endsDict
@property
def end_metabolites(self):
if len(self._end_metabolites) == 0: # there should be at least one end metabolite in the model
self._end_metabolites = self._get_end_metabolites()
return self._end_metabolites
def optimize(self, kind, *, objective, direction = 'max', flux_bounds = (-100, 100), conc_bounds = None,
preset_fluxes = None, preset_concs = None, irr_reactions = None, excluded_concs = None,
excluded_mb = None, excluded_thmd = None, included_epc = None, use_fba_results = None):
'''
Parameters
kind: str
kind of optimization to perform:
'fba', flux balance analysis with mass balance constraints only;
'tfba', flux balance analysis with both mass balance and thermodynamics constraints;
'etfba', flux balance analysis with mass balance, thermodynamics and enzyme protein cost constraints
objective: dict,
reaction ID => coefficient in the objective expression, e.g., {'r1': 2, 'r2': -1} defines the expression
"2*r1 - 1*r2", objective forms the complete objective expression in 'fba' and 'tfba', and the denominator
of objective expression in 'etfba'
direction: str
direction of optimization:
'max', maximize;
'min', minimize,
tunable in 'fba' and 'tfba', the argument is ignored in 'etfba' because the objective is
enzyme_protein_cost/objective_flux or enzyme_protein_cost which will always be optimized in minimizing direction
flux_bounds: tuple
lower and upper bounds of metabolic flux in mmol/gCDW/h, valid in 'fba', 'tfba' and 'etfba'
conc_bounds: tuple
lower and upper bounds of metabolite concentration in mM, valid in 'tfba' and 'etfba'
preset_fluxes: dict
rxnid => float, fixed metabolic fluxes, valid in 'fba', 'tfba' and 'etfba'
preset_concs: dict
metabid => float, fixed metabolite concentrations, e.g., substrate concentrations in media,
valid in 'tfba' and 'etfba'
irr_reactions: list of reaction ID
irreversible reactions, backward flux will be set to 0. reversibilities set by irr_reactions will
overwrite those set in file. valid in 'fba', 'tfba' and 'etfba'
excluded_concs: list of metabolite ID
metabolite concentrations excluded from optimization, valid in 'tfba' and 'etfba'
excluded_mb: list of metabolite ID
metabolites excluded from mass balance constraints, valid in 'fba', 'tfba' and 'etfba'
initial substrates and final products are excludeded in any case
excluded_thmd: list of reaction ID
reactions excluded from thermodynamics constraints, valid in 'tfba' and 'etfba'
reactions without available standard deltaG' are excluded in any case
included_epc: list of reaction ID
reactions included in enzyme protein cost constraints, valid only in 'etfba'
if kinetic parameters of Km, kcat and M.W. are not available for included reactions, default values will be used
use_fba_results: bool
if True, enzyme_protein_cost will be minimized with precomputed fluxes by FBA;
if False, enzyme_protein_cost/objective_flux will be minimized with variable fluxes, valid only in 'etfba'
'''
if kind.lower() == 'fba':
if conc_bounds is not None:
raise TypeError('FBA model does not accept conc_bounds argument')
if preset_concs is not None:
raise TypeError('FBA model does not accept preset_concs argument')
if excluded_concs is not None:
raise TypeError('FBA model does not accept excluded_concs argument')
if excluded_thmd is not None:
raise TypeError('FBA model does not accept excluded_thmd argument')
if included_epc is not None:
raise TypeError('FBA model does not accept included_epc argument')
if use_fba_results is not None:
raise TypeError('FBA model does not accept use_fba_results argument')
return FBAOptimizer(self, objective, direction, flux_bounds, preset_fluxes, irr_reactions, excluded_mb)
if kind.lower() == 'tfba':
if conc_bounds is None:
conc_bounds = (0.001, 10)
if included_epc is not None:
raise TypeError('TFBA model does not accept included_epc argument')
if use_fba_results is not None:
raise TypeError('FBA model does not accept use_fba_results argument')
return TFBAOptimizer(self, objective, direction, flux_bounds, conc_bounds, preset_fluxes, preset_concs,
irr_reactions, excluded_concs, excluded_mb, excluded_thmd)
if kind.lower() == 'etfba':
if conc_bounds is None:
conc_bounds = (0.001, 10)
if included_epc is None:
raise TypeError('included_epc argument should be set for ETFBA')
if use_fba_results is None:
use_fba_results = False
return ETFBAOptimizer(self, objective, direction, flux_bounds, conc_bounds, preset_fluxes, preset_concs,
irr_reactions, excluded_concs, excluded_mb, excluded_thmd, included_epc, use_fba_results)
def __repr__(self):
if len(self._metabolites) != 0 and len(self._reactions) != 0:
return 'model %s with %s reactions and %s metabolites' % (self.name if self.name else 'unknown',
len(self._reactions), len(self._metabolites))
else:
return 'model %s not constructed' % self.name if self.name else 'unknown'
| [
"re.match",
"pandas.read_excel",
"pandas.DataFrame",
"functools.lru_cache",
"re.search"
] | [((4031, 4042), 'functools.lru_cache', 'lru_cache', ([], {}), '()\n', (4040, 4042), False, 'from functools import lru_cache\n'), ((4854, 4865), 'functools.lru_cache', 'lru_cache', ([], {}), '()\n', (4863, 4865), False, 'from functools import lru_cache\n'), ((5988, 5999), 'functools.lru_cache', 'lru_cache', ([], {}), '()\n', (5997, 5999), False, 'from functools import lru_cache\n'), ((1085, 1099), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1097, 1099), True, 'import pandas as pd\n'), ((1138, 1152), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1150, 1152), True, 'import pandas as pd\n'), ((2022, 2063), 're.search', 're.search', (['"""biomass"""', 'prosStr'], {'flags': 're.I'}), "('biomass', prosStr, flags=re.I)\n", (2031, 2063), False, 'import re\n'), ((2115, 2152), 're.match', 're.match', (['"""^[\\\\w\\\\._]+\\\\.o$"""', 'subsStr'], {}), "('^[\\\\w\\\\._]+\\\\.o$', subsStr)\n", (2123, 2152), False, 'import re\n'), ((2154, 2191), 're.match', 're.match', (['"""^[\\\\w\\\\._]+\\\\.o$"""', 'prosStr'], {}), "('^[\\\\w\\\\._]+\\\\.o$', prosStr)\n", (2162, 2191), False, 'import re\n'), ((1511, 1570), 'pandas.read_excel', 'pd.read_excel', (['filename'], {'header': '(0)', 'index_col': '(0)', 'comment': '"""#"""'}), "(filename, header=0, index_col=0, comment='#')\n", (1524, 1570), True, 'import pandas as pd\n')] |
"""File with only WriteMessage class."""
import curses
class WriteMessage:
def __init__(self, history_file=False):
"""
Write data to the pad.
Parameters
----------
n_line: int
number of line of the pad
n_col: int
number of column of the pad
uly: int
upper left y
ulx: int
upper lef x
lry: int
lower right y
lrx: int
lower right x
Returns
-------
:class:WriteMessage
"""
curses.start_color()
if curses.has_colors(): # pylint: disable=no-member
self._curses_color = True
curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # pylint: disable=no-member
curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) # pylint: disable=no-member
curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) # pylint: disable=no-member
else:
self._curses_color = False
self._history = []; self._is_history_file = history_file
def update_loc(self, n_line, n_col, uly, ulx, lry, lrx, history_file=False):
self._max_line = n_line; self._n_col = n_col
self._uly = uly; self._ulx = ulx
self._lry = lry; self._lrx = lrx
self.re_init()
def re_init(self):
self._pad = curses.newpad(self._max_line, self._n_col) # pylint: disable=no-member
self._pad.keypad(True)
self._pad.refresh(0,0, self._uly,self._ulx, self._lry, self._lrx)
self._counter = 0; self._y = 0
for data in self._history:
data[0](*[data[x] for x in range(1, len(data))], history=False)
self.pad_refresh()
def write_new_message(self, author, message, history=True):
"""
Write a message publish by an user.
Parameters
----------
author: str
The author of the message.
message: str
The message to write.
history: [Optional] bool
Add the message to record history or not.
"""
if self._counter >= self._max_line*2/3:
self.re_init()
list_message = self.split_large_text(f"{author} : {message}")
for msg in list_message:
self._pad.addstr(self._counter,0, msg)
self._counter += 1; self._y += 1
self.pad_refresh()
if history:
self.add_to_history((self.write_new_message, author, message))
def write_ping_message(self, author, message, history=True):
"""
Write a ping message publish by an user.
Parameters
----------
author: str
The author of the message.
message: str
The message to write.
history: [Optional] bool
Add the message to record history or not.
"""
if self._counter >= self._max_line*2/3:
self.re_init()
list_message = self.split_large_text(f"!!--> {author} : {message}")
for msg in list_message:
if self._curses_color:
self._pad.addstr(self._counter,0, msg, curses.color_pair(2)) # pylint: disable=no-member
else:
self._pad.addstr(self._counter,0, msg)
self._counter += 1; self._y += 1
self.pad_refresh()
if history:
self.add_to_history((self.write_ping_message, author, message))
def write_system_message(self, data, history=True):
"""
Write a system message (in red).
Parameters
----------
data: str
The data to write.
"""
if self._counter >= self._max_line*2/3:
self.re_init()
list_message = self.split_large_text(data)
for msg in list_message:
if self._curses_color:
self._pad.addstr(self._counter,0, msg, curses.color_pair(1)) # pylint: disable=no-member
else:
self._pad.addstr(self._counter,0, msg)
self._counter += 1; self._y += 1
self.pad_refresh()
if history:
self.add_to_history((self.write_system_message, data))
def write_signal_message(self, *args, history=True):
"""
Write signal message (with green color)
Parameters
----------
*args : *str
All arg that you want.
history: [Optional] bool
Add the message to record history or not.
"""
if self._counter >= self._max_line*2/3:
self.re_init()
message = " ".join(args)
list_message = self.split_large_text(message)
for msg in list_message:
if self._curses_color:
self._pad.addstr(self._counter,0, msg, curses.color_pair(3)) # pylint: disable=no-member
else:
self._pad.addstr(self._counter,0, msg)
self._counter += 1; self._y += 1
self.pad_refresh()
if history:
self.add_to_history((self.write_signal_message, *args))
def write_start_up_message(self, pseudo):
"""
Write the start up message.
Parameters
----------
pseudo: str
The user pseudo.
"""
pseudo = pseudo[:-10] + "#" + pseudo[-10:]
self.write_system_message("Connection réalisée avec succès")
self.write_system_message("Voici ton pseudo : ")
if self._curses_color:
self._pad.addstr(1,19, pseudo, curses.color_pair(2)) # pylint: disable=no-member
else:
self._pad.addstr(1,19, pseudo)
self.write_system_message("Voir les différentes commandes possibles : /help")
self.write_system_message("Voici une liste de racourcis clavier :")
self.write_system_message("Ctrl+h = Backspace = supprime le caractere arriere")
self.write_system_message("Ctrl+G = envoyé un message")
self.write_signal_message("Si vous modifiez la taille de la fenetre, envoyez un message blanc (ctrl+G)")
self.pad_refresh()
def PadUP(self, nb):
"""
Go up in history message.
Parameters
----------
nb: int
The number to up.
"""
if self._y - nb <= 0:
self._y = (self._lry - self._uly) + 2
else:
self._y -= nb
self.pad_refresh()
def PadDOWN(self, nb):
"""
Go down in history message.
Parameters
----------
nn: int
The number to down.
"""
if self._y + nb >= self._counter:
self._y = self._counter
else:
self._y += nb
self.pad_refresh()
def pad_refresh(self):
"""Refresh pad screen to be in the right position self._y."""
if self._y <= (self._lry - self._uly) - 1:
self._pad.refresh(0,0, self._uly,self._ulx, self._lry,self._lrx)
else:
pos_y = self._y - (self._lry - self._uly) + 1
self._pad.refresh(pos_y,0, self._uly,self._ulx, self._lry,self._lrx)
def add_to_history(self, data):
"""
Get a trace of the last message.
Parameters
----------
data: Any
Data to record
"""
if len(self._history) > self._max_line*(1/4):
del self._history[0]
self._history.append(data)
if self._is_history_file:
with open("assets/document/data/history.txt", "a") as fd:
fd.write("\n"+" ".join(data[1:]))
@staticmethod
def split_large_text(data):
"""
Split text to fit in the window.
Parameters
----------
data: str
The whole data to write.
Returns
-------
list
List of split message.
"""
if len(data) >= curses.COLS: # pylint: disable=no-member
l_data = []
while len(data) >= curses.COLS: # pylint: disable=no-member
l_data.append(data[:curses.COLS-1]) # pylint: disable=no-member
data = data[curses.COLS-1:] # pylint: disable=no-member
l_data.append(data[:curses.COLS-1]) # pylint: disable=no-member
data = data[curses.COLS-1:] # pylint: disable=no-member
else:
l_data = [data]
return l_data
| [
"curses.color_pair",
"curses.start_color",
"curses.init_pair",
"curses.has_colors",
"curses.newpad"
] | [((598, 618), 'curses.start_color', 'curses.start_color', ([], {}), '()\n', (616, 618), False, 'import curses\n'), ((631, 650), 'curses.has_colors', 'curses.has_colors', ([], {}), '()\n', (648, 650), False, 'import curses\n'), ((1436, 1478), 'curses.newpad', 'curses.newpad', (['self._max_line', 'self._n_col'], {}), '(self._max_line, self._n_col)\n', (1449, 1478), False, 'import curses\n'), ((732, 790), 'curses.init_pair', 'curses.init_pair', (['(1)', 'curses.COLOR_CYAN', 'curses.COLOR_BLACK'], {}), '(1, curses.COLOR_CYAN, curses.COLOR_BLACK)\n', (748, 790), False, 'import curses\n'), ((832, 892), 'curses.init_pair', 'curses.init_pair', (['(2)', 'curses.COLOR_YELLOW', 'curses.COLOR_BLACK'], {}), '(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n', (848, 892), False, 'import curses\n'), ((934, 993), 'curses.init_pair', 'curses.init_pair', (['(3)', 'curses.COLOR_GREEN', 'curses.COLOR_BLACK'], {}), '(3, curses.COLOR_GREEN, curses.COLOR_BLACK)\n', (950, 993), False, 'import curses\n'), ((5704, 5724), 'curses.color_pair', 'curses.color_pair', (['(2)'], {}), '(2)\n', (5721, 5724), False, 'import curses\n'), ((3268, 3288), 'curses.color_pair', 'curses.color_pair', (['(2)'], {}), '(2)\n', (3285, 3288), False, 'import curses\n'), ((4044, 4064), 'curses.color_pair', 'curses.color_pair', (['(1)'], {}), '(1)\n', (4061, 4064), False, 'import curses\n'), ((4952, 4972), 'curses.color_pair', 'curses.color_pair', (['(3)'], {}), '(3)\n', (4969, 4972), False, 'import curses\n')] |
import matplotlib.pyplot as plt
from string import ascii_uppercase
def countSpecific(_path, _letter):
_letter = _letter.strip().upper()
file = open(_path, 'rb')
text = str(file.read())
return text.count(_letter) + text.count(_letter.lower())
def countAll(_path):
file = open(_path, "rb")
text = str(file.read())
letters = dict.fromkeys(ascii_uppercase, 0)
for char in text:
if char.isalpha():
letters[char.upper()]+=1
return letters
path = input("What file would you like to use? (text.txt) ")
D = countAll("src\\Other\\" + path)
# D = D | countAll("src\\Other\\" + path)
# S = {k: v for k, v in sorted(D.items(), key=lambda item: item[1])}
print(D)
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show() | [
"matplotlib.pyplot.show"
] | [((811, 821), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (819, 821), True, 'import matplotlib.pyplot as plt\n')] |
import requests
import pytest
from apistar import TestClient
from api.web.support import Status
from tests.markers import smoke
@pytest.fixture(scope="module")
def response(client: TestClient) -> requests.Response:
return client.get("/api")
@smoke
def test_get_vehicles_status(response: requests.Response) -> None:
assert response.status_code == Status.SUCCESS.code
@smoke
def test_vehicles_count(response: requests.Response) -> None:
assert len(response.json()) == 1000
@smoke
def test_vehicles_is_list(response: requests.Response) -> None:
assert type(response.json()) is list
@smoke
def test_get_first_vehicle(response: requests.Response) -> None:
assert response.json()[0] == {
"id_": 1,
"manufacturer": "Mazda",
"model": "RX-8",
"year": 2006,
"vin": "JTJBARBZ2F2356837",
}
@smoke
def test_last_vehicle_id(response: requests.Response) -> None:
assert response.json()[-1]["id_"] == 1000
| [
"pytest.fixture"
] | [((131, 161), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (145, 161), False, 'import pytest\n')] |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter
filepath = '/Users/huangjiaming/Documents/developer/ETreeLearning/res/losses/delay_etree.txt'
x = []
num = 0
with open(filepath) as fp:
for line in fp:
c = list(map(int, line.split()))
x = c
print(np.mean(x), np.std(x))
fig,(ax0,ax1) = plt.subplots(nrows=2,figsize=(9,6))
# pdf概率分布图
ax0.hist(x, 100, normed=1, histtype='bar', facecolor='blue', edgecolor="black", alpha=0.9)
ax0.set_title('')
ax0.set_xlabel('Delay / ms')
ax0.set_ylabel('Percent')
#cdf累计概率函数
ax1.hist(x,100,normed=1,histtype='bar',facecolor='red', edgecolor="black", alpha=0.9,cumulative=True,rwidth=0.8)
ax1.set_title("cdf")
ax1.set_xlabel('Delay / ms')
ax1.set_ylabel('Percent')
fig.subplots_adjust(hspace=0.4)
plt.savefig('./reports/20200301/delay_etree_100_nodes', dpi=600) | [
"numpy.mean",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"numpy.std"
] | [((360, 397), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'figsize': '(9, 6)'}), '(nrows=2, figsize=(9, 6))\n', (372, 397), True, 'import matplotlib.pyplot as plt\n'), ((853, 917), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./reports/20200301/delay_etree_100_nodes"""'], {'dpi': '(600)'}), "('./reports/20200301/delay_etree_100_nodes', dpi=600)\n", (864, 917), True, 'import matplotlib.pyplot as plt\n'), ((317, 327), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (324, 327), True, 'import numpy as np\n'), ((329, 338), 'numpy.std', 'np.std', (['x'], {}), '(x)\n', (335, 338), True, 'import numpy as np\n')] |
from flask_restx import reqparse
from db_plugins.db.sql import models
columns = []
for c in models.Object.__table__.columns:
columns.append(str(c).split(".")[1])
for c in models.Probability.__table__.columns:
columns.append(str(c).split(".")[1])
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 reqparse.ArgumentTypeError("Boolean value expected.")
def create_parsers(classifiers=None, classes=None):
filter_parser = reqparse.RequestParser()
filter_parser.add_argument(
"oid",
type=str,
dest="oid",
location="args",
help="Object id",
action="append",
)
filter_parser.add_argument(
"classifier",
type=str,
dest="classifier",
location="args",
help="classifier name",
choices=classifiers,
)
filter_parser.add_argument(
"classifier_version",
type=str,
dest="classifier_version",
location="args",
help="classifier version",
)
filter_parser.add_argument(
"class",
type=str,
dest="class",
location="args",
help="class name",
choices=classes,
)
filter_parser.add_argument(
"ranking",
type=int,
dest="ranking",
location="args",
help="Class ordering by probability from highest to lowest. (Default 1)",
)
filter_parser.add_argument(
"ndet",
type=int,
dest="ndet",
location="args",
help="Range of detections.",
action="append",
)
filter_parser.add_argument(
"probability",
type=float,
dest="probability",
location="args",
help="Minimum probability.",
)
filter_parser.add_argument(
"firstmjd",
type=float,
dest="firstmjd",
location="args",
help="First detection date range in mjd.",
action="append",
)
filter_parser.add_argument(
"lastmjd",
type=float,
dest="lastmjd",
location="args",
help="Last detection date range in mjd.",
action="append",
)
conesearch_parser = reqparse.RequestParser()
conesearch_parser.add_argument(
"ra",
type=float,
dest="ra",
location="args",
help="Ra in degrees for conesearch.",
)
conesearch_parser.add_argument(
"dec",
type=float,
dest="dec",
location="args",
help="Dec in degrees for conesearch.",
)
conesearch_parser.add_argument(
"radius",
type=float,
dest="radius",
location="args",
help="Radius in arcsec for conesearch. (Default: 30 arcsec)",
)
pagination_parser = reqparse.RequestParser()
pagination_parser.add_argument(
"page",
default=1,
type=int,
dest="page",
location="args",
help="Page or offset to retrieve.",
)
pagination_parser.add_argument(
"page_size",
default=10,
type=int,
dest="page_size",
location="args",
help="Number of objects to retrieve in each page.",
)
pagination_parser.add_argument(
"count",
type=str2bool,
default=False,
dest="count",
location="args",
help="Whether to count total objects or not.",
)
order_parser = reqparse.RequestParser()
order_parser.add_argument(
"order_by",
type=str,
dest="order_by",
location="args",
help="Column used for ordering",
choices=columns,
)
order_parser.add_argument(
"order_mode",
type=str,
dest="order_mode",
location="args",
choices=["ASC", "DESC"],
help="Ordering could be ascendent or descendent",
)
return filter_parser, conesearch_parser, order_parser, pagination_parser
| [
"flask_restx.reqparse.RequestParser",
"flask_restx.reqparse.ArgumentTypeError"
] | [((619, 643), 'flask_restx.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (641, 643), False, 'from flask_restx import reqparse\n'), ((2341, 2365), 'flask_restx.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (2363, 2365), False, 'from flask_restx import reqparse\n'), ((2923, 2947), 'flask_restx.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (2945, 2947), False, 'from flask_restx import reqparse\n'), ((3571, 3595), 'flask_restx.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (3593, 3595), False, 'from flask_restx import reqparse\n'), ((490, 543), 'flask_restx.reqparse.ArgumentTypeError', 'reqparse.ArgumentTypeError', (['"""Boolean value expected."""'], {}), "('Boolean value expected.')\n", (516, 543), False, 'from flask_restx import reqparse\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 25 15:06:45 2019
@author: garci
"""
import matplotlib.pyplot as plt
import numpy as np
import csv
import xlwings as xw
import pandas
import os
'''MAKE X-Y PLOTS WITH 2-COLUMN FILES
<NAME>, 2019 '''
'''lastRow credit: answered Sep 14 '16 at 11:39 - Stefan
https://stackoverflow.com/questions/33418119/xlwings-function-to-find-the-last-row-with-data'''
def lastRow(idx, workbook, col=1):
""" Find the last row in the worksheet that contains data.
idx: Specifies the worksheet to select. Starts counting from zero.
workbook: Specifies the workbook
col: The column in which to look for the last cell containing data.
"""
ws = workbook.sheets[idx]
lwr_r_cell = ws.cells.last_cell # lower right cell
lwr_row = lwr_r_cell.row # row of the lower right cell
lwr_cell = ws.range((lwr_row, col)) # change to your specified column
if lwr_cell.value is None:
lwr_cell = lwr_cell.end('up') # go up untill you hit a non-empty cell
return lwr_cell.row
import time
'''MAKE AN XY PLOT FOR A SINGLE EXCEL FILE (SPECIFY FOLDER PATH AND FILE NAME)'''
def readxl(path,file,sheet='Sheet1'):
book = xw.Book(path+file)
x=book.sheets[sheet].range('A1:A'+str(lastRow(sheet,book))).value
y=book.sheets[sheet].range('B1:B'+str(lastRow(sheet,book))).value
pltitle=book.sheets[sheet].range('I1').value
# y=(y-np.min(y))*627.509
book.close()
plt.figure()
plt.plot(x,y)
# plt.xlim(4,1.7)
plt.title(pltitle)
# plt.xlabel('')
# print(end)
plt.savefig(str(int(time.time())))
'''MAKE AN XY PLOT WITH TWO INDEPENDENT VARS (Y AND Z) FOR A SINGLE EXCEL FILE
(SPECIFY FOLDER PATH AND FILE NAME)'''
def readxl2(path,file,sheet='Sheet1'):
book = xw.Book(path+file)
x=book.sheets[sheet].range('A1:A'+str(lastRow(sheet,book))).value
y=book.sheets[sheet].range('B1:B'+str(lastRow(sheet,book))).value
z=book.sheets[sheet].range('C1:C'+str(lastRow(sheet,book))).value
pltitle = book.sheets[sheet].range('I1').value
label1 = book.sheets[sheet].range('I2').value
label2 = book.sheets[sheet].range('I3').value
book.close()
plt.figure()
plt.plot(x,y,label = label1)
plt.plot(x,z,label = label2)
plt.title(pltitle)
plt.xlabel('time')
plt.savefig(file+'.png')
plt.legend()
def readxlCG(path,file,sheet='Sheet1'):
book = xw.Book(path+file)
x=book.sheets[sheet].range('B2:B'+str(lastRow(sheet,book))).value
y=book.sheets[sheet].range('D2:D'+str(lastRow(sheet,book))).value
x2=book.sheets[sheet].range('F2:F'+str(lastRow(sheet,book))).value
y2=book.sheets[sheet].range('H2:H'+str(lastRow(sheet,book))).value
# pltitle = book.sheets[sheet].range('I1').value
# label1 = book.sheets[sheet].range('I2').value
# label2 = book.sheets[sheet].range('I3').value
book.close()
plt.figure()
plt.plot(x,y,'o',label = 'no CG')
plt.plot(x2,y2,'o',label = 'CG')
# plt.title(pltitle)
# plt.xlabel('time')
# plt.savefig(file+'.png')
plt.legend()
'MAKE XY PLOTS FOR ALL TAB DELIMITED FILES IN A FOLDER (SPECIFY FOLDER PATH)'
def writetab_bulk(path):
asps = []
for root, dirs, files in os.walk(path):
for file in files:
if not file.endswith('.xlsx') and not file.endswith('.csv')\
and not file.endswith('.png') and not file.endswith('.txt')\
and not file.endswith('.xls'):
asps.append(file)
print(asps)
index=1
for file in asps:
df= pandas.read_fwf(path+file,header=None,infer_nrows=10000)
xdim, ydim = df.shape[0], df.shape[1]
if xdim > 1 and ydim == 2:
df.columns =['a','b']
print(file,index)
# print(df)
plt.figure()
plt.plot(df['a'],df['b'])
plt.title(file)
plt.xlabel('time / ps')
plt.savefig(file+'.png')
# plt.close()
index+=1
# return df
'(optional): create function with directory path (keep uncommented if unaware)'
#from proc_out_key import pathkey
#path = pathkey()
'''COMMAND SECTION (INPUT)'''
'MAKE XY PLOTS FOR ALL TAB DELIMITED FILES IN A FOLDER (SPECIFY FOLDER PATH)'
#path = r'C:\Users\***\file_folder/'
#df=writetab_bulk(path)
'''MAKE AN XY PLOT FOR A SINGLE EXCEL FILE (SPECIFY FOLDER PATH AND FILE NAME)'''
#path = r'C:\Users\***\file_folder/'
#file = '**.xlsx'
#writexl(path,file) | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"os.walk",
"matplotlib.pyplot.figure",
"time.time",
"matplotlib.pyplot.title",
"xlwings.Book",
"pandas.read_fwf",
"matplotlib.pyplot.legend"
] | [((1217, 1237), 'xlwings.Book', 'xw.Book', (['(path + file)'], {}), '(path + file)\n', (1224, 1237), True, 'import xlwings as xw\n'), ((1480, 1492), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1490, 1492), True, 'import matplotlib.pyplot as plt\n'), ((1497, 1511), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (1505, 1511), True, 'import matplotlib.pyplot as plt\n'), ((1536, 1554), 'matplotlib.pyplot.title', 'plt.title', (['pltitle'], {}), '(pltitle)\n', (1545, 1554), True, 'import matplotlib.pyplot as plt\n'), ((1811, 1831), 'xlwings.Book', 'xw.Book', (['(path + file)'], {}), '(path + file)\n', (1818, 1831), True, 'import xlwings as xw\n'), ((2217, 2229), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2227, 2229), True, 'import matplotlib.pyplot as plt\n'), ((2234, 2262), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'label': 'label1'}), '(x, y, label=label1)\n', (2242, 2262), True, 'import matplotlib.pyplot as plt\n'), ((2267, 2295), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'z'], {'label': 'label2'}), '(x, z, label=label2)\n', (2275, 2295), True, 'import matplotlib.pyplot as plt\n'), ((2301, 2319), 'matplotlib.pyplot.title', 'plt.title', (['pltitle'], {}), '(pltitle)\n', (2310, 2319), True, 'import matplotlib.pyplot as plt\n'), ((2324, 2342), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time"""'], {}), "('time')\n", (2334, 2342), True, 'import matplotlib.pyplot as plt\n'), ((2347, 2373), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file + '.png')"], {}), "(file + '.png')\n", (2358, 2373), True, 'import matplotlib.pyplot as plt\n'), ((2376, 2388), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2386, 2388), True, 'import matplotlib.pyplot as plt\n'), ((2442, 2462), 'xlwings.Book', 'xw.Book', (['(path + file)'], {}), '(path + file)\n', (2449, 2462), True, 'import xlwings as xw\n'), ((2923, 2935), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2933, 2935), True, 'import matplotlib.pyplot as plt\n'), ((2940, 2974), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""o"""'], {'label': '"""no CG"""'}), "(x, y, 'o', label='no CG')\n", (2948, 2974), True, 'import matplotlib.pyplot as plt\n'), ((2978, 3011), 'matplotlib.pyplot.plot', 'plt.plot', (['x2', 'y2', '"""o"""'], {'label': '"""CG"""'}), "(x2, y2, 'o', label='CG')\n", (2986, 3011), True, 'import matplotlib.pyplot as plt\n'), ((3094, 3106), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3104, 3106), True, 'import matplotlib.pyplot as plt\n'), ((3255, 3268), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (3262, 3268), False, 'import os\n'), ((3587, 3647), 'pandas.read_fwf', 'pandas.read_fwf', (['(path + file)'], {'header': 'None', 'infer_nrows': '(10000)'}), '(path + file, header=None, infer_nrows=10000)\n', (3602, 3647), False, 'import pandas\n'), ((3847, 3859), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3857, 3859), True, 'import matplotlib.pyplot as plt\n'), ((3872, 3898), 'matplotlib.pyplot.plot', 'plt.plot', (["df['a']", "df['b']"], {}), "(df['a'], df['b'])\n", (3880, 3898), True, 'import matplotlib.pyplot as plt\n'), ((3910, 3925), 'matplotlib.pyplot.title', 'plt.title', (['file'], {}), '(file)\n', (3919, 3925), True, 'import matplotlib.pyplot as plt\n'), ((3938, 3963), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time / ps"""'], {}), "('time / ps')\n", (3948, 3963), True, 'import matplotlib.pyplot as plt\n'), ((3976, 4002), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file + '.png')"], {}), "(file + '.png')\n", (3987, 4002), True, 'import matplotlib.pyplot as plt\n'), ((1615, 1626), 'time.time', 'time.time', ([], {}), '()\n', (1624, 1626), False, 'import time\n')] |
import urllib
from bs4 import BeautifulSoup
print ("Collecting data from IMDb charts....\n\n\n")
print ("The current top 15 IMDB movies are the following: \n\n")
response = urllib.request.urlopen("http://www.imdb.com/chart/top")
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
mytd = soup.findAll("td", {"class":"titleColumn"})
for titles in mytd[:15]:
print (titles.find('a').text)
print ("\n\nThank you for using IMDB script ...")
| [
"bs4.BeautifulSoup",
"urllib.request.urlopen"
] | [((174, 229), 'urllib.request.urlopen', 'urllib.request.urlopen', (['"""http://www.imdb.com/chart/top"""'], {}), "('http://www.imdb.com/chart/top')\n", (196, 229), False, 'import urllib\n'), ((260, 294), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (273, 294), False, 'from bs4 import BeautifulSoup\n')] |
from django.urls import path
import mainapp.views as mainapp
app_name = "mainapp"
urlpatterns = [
path("", mainapp.product, name="index"),
path("<int:pk>/", mainapp.product, name="category"),
path("<int:pk>/page/<int:page>/", mainapp.product, name="page"),
path("product/<int:pk>/", mainapp.product_page, name="product"),
]
| [
"django.urls.path"
] | [((106, 145), 'django.urls.path', 'path', (['""""""', 'mainapp.product'], {'name': '"""index"""'}), "('', mainapp.product, name='index')\n", (110, 145), False, 'from django.urls import path\n'), ((151, 202), 'django.urls.path', 'path', (['"""<int:pk>/"""', 'mainapp.product'], {'name': '"""category"""'}), "('<int:pk>/', mainapp.product, name='category')\n", (155, 202), False, 'from django.urls import path\n'), ((208, 271), 'django.urls.path', 'path', (['"""<int:pk>/page/<int:page>/"""', 'mainapp.product'], {'name': '"""page"""'}), "('<int:pk>/page/<int:page>/', mainapp.product, name='page')\n", (212, 271), False, 'from django.urls import path\n'), ((277, 340), 'django.urls.path', 'path', (['"""product/<int:pk>/"""', 'mainapp.product_page'], {'name': '"""product"""'}), "('product/<int:pk>/', mainapp.product_page, name='product')\n", (281, 340), False, 'from django.urls import path\n')] |
import datetime
import os
import random
import time
import requests
from lxml import etree
from selenium import webdriver
# import config
import threading
# import numpy as np
mUA_list = [
'Mozilla/5.0 (iPhone; CPU iPhone OS 11_2_1 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0 Mobile/15C153 Safari/604.1',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;',
'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
'User-Agent, Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)'
]
pcUA = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'
mWidth = 1440
mHeight = 2000
PIXEL_RATIO = 3.0
mobileEmulation = {"deviceMetrics": {"width": mWidth, "height": mHeight, "pixelRatio": PIXEL_RATIO},
} # "userAgent": random.choice(pcUA)
def create_chrome():
ops = webdriver.ChromeOptions()
ops.add_experimental_option('mobileEmulation', mobileEmulation)
# ops.add_argument('--headless')
# ops.add_argument('--disable-gpu')
web = webdriver.Chrome(chrome_options=ops)
web.set_page_load_timeout(10)
web.set_script_timeout(10)
web.set_window_size(mWidth, mHeight)
return web
driver = create_chrome()
driver.maximize_window()
driver.get(
'https://detail.tmall.com/item.htm?id=584865383924&skuId=3951416717001&areaId=110100&user_id=902218705&cat_id=2&is_b=1&rn=289a6a85d6f5c3ca9cb4ea875d191f90&on_comment=1')
time.sleep(2)
# print(driver.get_cookies())
time.sleep(20)
print(driver.page_source)
| [
"selenium.webdriver.Chrome",
"selenium.webdriver.ChromeOptions",
"time.sleep"
] | [((1617, 1630), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1627, 1630), False, 'import time\n'), ((1661, 1675), 'time.sleep', 'time.sleep', (['(20)'], {}), '(20)\n', (1671, 1675), False, 'import time\n'), ((1037, 1062), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (1060, 1062), False, 'from selenium import webdriver\n'), ((1219, 1255), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {'chrome_options': 'ops'}), '(chrome_options=ops)\n', (1235, 1255), False, 'from selenium import webdriver\n')] |
import os
import random
import string
import json
from django.core.management import BaseCommand
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, <NAME>"
__licence__ = "BSD 2-Clause Licence"
__version__ = "1.0"
__email__ = "<EMAIL>"
class Command(BaseCommand):
def is_valid_file(self, file):
if not os.path.isfile(file):
self.stdout.write("File not found or path is invalid!")
exit(1)
else:
return open(file, 'r+') # return open file handlei
@staticmethod
def generate_new_key():
return ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation)
for _ in range(50)])
def add_arguments(self, parser):
parser.add_argument('-f', '--file', type=str, dest='file',
default=str(os.path.join(os.path.expanduser("~"), '.config/helpdesk/config.json')))
def update_key(self):
with self.file as f:
settings = json.loads(f.read())
settings["secret_key"] = self.generate_new_key()
f.seek(0)
f.write(json.dumps(settings, indent=2))
f.truncate()
def handle(self, *args, **options):
self.file = self.is_valid_file(options['file'])
self.update_key()
| [
"os.path.isfile",
"json.dumps",
"random.SystemRandom",
"os.path.expanduser"
] | [((322, 342), 'os.path.isfile', 'os.path.isfile', (['file'], {}), '(file)\n', (336, 342), False, 'import os\n'), ((1136, 1166), 'json.dumps', 'json.dumps', (['settings'], {'indent': '(2)'}), '(settings, indent=2)\n', (1146, 1166), False, 'import json\n'), ((581, 602), 'random.SystemRandom', 'random.SystemRandom', ([], {}), '()\n', (600, 602), False, 'import random\n'), ((872, 895), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (890, 895), False, 'import os\n')] |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField, SelectField
from wtforms.validators import Required
class PitchForm(FlaskForm):
title = StringField('Pitch title',validators=[Required()])
category = SelectField('Pitch category', choices=[('Motivational', 'Motivational'), ('Famous', 'Famous'), ('Despair', 'Despair')], validators=[Required()])
description = TextAreaField('Pitch description', validators=[Required()])
submit = SubmitField('Submit')
class UpdateProfile(FlaskForm):
bio = TextAreaField('Tell us about you.',validators = [Required()])
submit = SubmitField('Submit')
class Commentform(FlaskForm):
description = TextAreaField('Comment description', validators=[Required()])
submit = SubmitField('Submit')
class Upvoteform(FlaskForm):
submit1 = SubmitField('Upvote (+)')
class Downvoteform(FlaskForm):
submit2 = SubmitField('Downvote (-)') | [
"wtforms.validators.Required",
"wtforms.SubmitField"
] | [((487, 508), 'wtforms.SubmitField', 'SubmitField', (['"""Submit"""'], {}), "('Submit')\n", (498, 508), False, 'from wtforms import StringField, TextAreaField, SubmitField, SelectField\n'), ((627, 648), 'wtforms.SubmitField', 'SubmitField', (['"""Submit"""'], {}), "('Submit')\n", (638, 648), False, 'from wtforms import StringField, TextAreaField, SubmitField, SelectField\n'), ((773, 794), 'wtforms.SubmitField', 'SubmitField', (['"""Submit"""'], {}), "('Submit')\n", (784, 794), False, 'from wtforms import StringField, TextAreaField, SubmitField, SelectField\n'), ((839, 864), 'wtforms.SubmitField', 'SubmitField', (['"""Upvote (+)"""'], {}), "('Upvote (+)')\n", (850, 864), False, 'from wtforms import StringField, TextAreaField, SubmitField, SelectField\n'), ((911, 938), 'wtforms.SubmitField', 'SubmitField', (['"""Downvote (-)"""'], {}), "('Downvote (-)')\n", (922, 938), False, 'from wtforms import StringField, TextAreaField, SubmitField, SelectField\n'), ((223, 233), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (231, 233), False, 'from wtforms.validators import Required\n'), ((383, 393), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (391, 393), False, 'from wtforms.validators import Required\n'), ((461, 471), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (469, 471), False, 'from wtforms.validators import Required\n'), ((601, 611), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (609, 611), False, 'from wtforms.validators import Required\n'), ((747, 757), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (755, 757), False, 'from wtforms.validators import Required\n')] |
#!/usr/bin/env python
# Copyright 2016 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
import json
import urllib
import boto3
from PIL import Image
from PIL.ExifTags import TAGS
resized_dir = '/images/resized'
thumb_dir = '/images/thumbs'
input_bucket_name = os.environ['s3InputBucket']
output_bucket_name = os.environ['s3OutputBucket']
sqsqueue_name = os.environ['SQSBatchQueue']
aws_region = os.environ['AWSRegion']
s3 = boto3.client('s3', region_name=aws_region)
sqs = boto3.resource('sqs', region_name=aws_region)
def create_dirs():
for dirs in [resized_dir, thumb_dir]:
if not os.path.exists(dirs):
os.makedirs(dirs)
def process_images():
"""Process the image
No real error handling in this sample code. In case of error we'll put
the message back in the queue and make it visable again. It will end up in
the dead letter queue after five failed attempts.
"""
for message in get_messages_from_sqs():
try:
message_content = json.loads(message.body)
image = urllib.unquote_plus(message_content
['Records'][0]['s3']['object']
['key']).encode('utf-8')
s3.download_file(input_bucket_name, image, image)
resize_image(image)
upload_image(image)
cleanup_files(image)
except:
message.change_visibility(VisibilityTimeout=0)
continue
else:
message.delete()
def cleanup_files(image):
os.remove(image)
os.remove(resized_dir + '/' + image)
os.remove(thumb_dir + '/' + image)
def upload_image(image):
s3.upload_file(resized_dir + '/' + image,
output_bucket_name, 'resized/' + image)
s3.upload_file(thumb_dir + '/' + image,
output_bucket_name, 'thumbs/' + image)
def get_messages_from_sqs():
results = []
queue = sqs.get_queue_by_name(QueueName=sqsqueue_name)
for message in queue.receive_messages(VisibilityTimeout=120,
WaitTimeSeconds=20,
MaxNumberOfMessages=10):
results.append(message)
return(results)
def resize_image(image):
img = Image.open(image)
exif = img._getexif()
if exif is not None:
for tag, value in exif.items():
decoded = TAGS.get(tag, tag)
if decoded == 'Orientation':
if value == 3:
img = img.rotate(180)
if value == 6:
img = img.rotate(270)
if value == 8:
img = img.rotate(90)
img.thumbnail((1024, 768), Image.ANTIALIAS)
try:
img.save(resized_dir + '/' + image, 'JPEG', quality=100)
except IOError as e:
print("Unable to save resized image")
img.thumbnail((192, 192), Image.ANTIALIAS)
try:
img.save(thumb_dir + '/' + image, 'JPEG')
except IOError as e:
print("Unable to save thumbnail")
def main():
create_dirs()
while True:
process_images()
if __name__ == "__main__":
main()
| [
"os.path.exists",
"json.loads",
"PIL.Image.open",
"boto3.client",
"urllib.unquote_plus",
"os.makedirs",
"PIL.ExifTags.TAGS.get",
"boto3.resource",
"os.remove"
] | [((936, 978), 'boto3.client', 'boto3.client', (['"""s3"""'], {'region_name': 'aws_region'}), "('s3', region_name=aws_region)\n", (948, 978), False, 'import boto3\n'), ((985, 1030), 'boto3.resource', 'boto3.resource', (['"""sqs"""'], {'region_name': 'aws_region'}), "('sqs', region_name=aws_region)\n", (999, 1030), False, 'import boto3\n'), ((2062, 2078), 'os.remove', 'os.remove', (['image'], {}), '(image)\n', (2071, 2078), False, 'import os\n'), ((2083, 2119), 'os.remove', 'os.remove', (["(resized_dir + '/' + image)"], {}), "(resized_dir + '/' + image)\n", (2092, 2119), False, 'import os\n'), ((2124, 2158), 'os.remove', 'os.remove', (["(thumb_dir + '/' + image)"], {}), "(thumb_dir + '/' + image)\n", (2133, 2158), False, 'import os\n'), ((2783, 2800), 'PIL.Image.open', 'Image.open', (['image'], {}), '(image)\n', (2793, 2800), False, 'from PIL import Image\n'), ((1109, 1129), 'os.path.exists', 'os.path.exists', (['dirs'], {}), '(dirs)\n', (1123, 1129), False, 'import os\n'), ((1143, 1160), 'os.makedirs', 'os.makedirs', (['dirs'], {}), '(dirs)\n', (1154, 1160), False, 'import os\n'), ((1515, 1539), 'json.loads', 'json.loads', (['message.body'], {}), '(message.body)\n', (1525, 1539), False, 'import json\n'), ((2914, 2932), 'PIL.ExifTags.TAGS.get', 'TAGS.get', (['tag', 'tag'], {}), '(tag, tag)\n', (2922, 2932), False, 'from PIL.ExifTags import TAGS\n'), ((1560, 1633), 'urllib.unquote_plus', 'urllib.unquote_plus', (["message_content['Records'][0]['s3']['object']['key']"], {}), "(message_content['Records'][0]['s3']['object']['key'])\n", (1579, 1633), False, 'import urllib\n')] |
from dash_extensions.enrich import Dash
from _app.layout import serve_layout
from _app.callback import register_callbacks
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(prevent_initial_callbacks=True,
external_stylesheets=external_stylesheets
)
register_callbacks(app)
app.layout = serve_layout()
if __name__ == '__main__':
app.run_server(debug=True) | [
"_app.callback.register_callbacks",
"_app.layout.serve_layout",
"dash_extensions.enrich.Dash"
] | [((203, 282), 'dash_extensions.enrich.Dash', 'Dash', ([], {'prevent_initial_callbacks': '(True)', 'external_stylesheets': 'external_stylesheets'}), '(prevent_initial_callbacks=True, external_stylesheets=external_stylesheets)\n', (207, 282), False, 'from dash_extensions.enrich import Dash\n'), ((310, 333), '_app.callback.register_callbacks', 'register_callbacks', (['app'], {}), '(app)\n', (328, 333), False, 'from _app.callback import register_callbacks\n'), ((348, 362), '_app.layout.serve_layout', 'serve_layout', ([], {}), '()\n', (360, 362), False, 'from _app.layout import serve_layout\n')] |
import TestCase
from testcase_generation.Response.default import defaultTestCase
import Constants
def defaultMediaTypeTestCase():
testcase = defaultTestCase()
# Request
testcase.request.method = 'GET'
# Response
testcase.response.status_code = 200
testcase.response.expect_body = True
return testcase
def testCaseMediaType_html():
testcase = defaultMediaTypeTestCase()
testcase.name = 'MediaType_html'
testcase.request.target = '/MediaType/sample.html'
testcase.response.headers['Content-Type'] = 'text/html'
with open(Constants.SERVER_ROOT + '/Method/MediaType/sample.html', 'rb') as f:
testcase.response.body = f.read()
testcase.response.headers['content-length'] = str(len(testcase.response.body))
return testcase
def testCaseMediaType_txt():
testcase = defaultMediaTypeTestCase()
testcase.name = 'MediaType_txt'
testcase.request.target = '/MediaType/sample.txt'
testcase.response.headers['Content-Type'] = 'text/plain;charset=UTF-8'
with open(Constants.SERVER_ROOT + '/Method/MediaType/sample.txt', 'rb') as f:
testcase.response.body = f.read()
testcase.response.headers['content-length'] = str(len(testcase.response.body))
return testcase
def testCaseMediaType_png():
testcase = defaultMediaTypeTestCase()
testcase.name = 'MediaType_png'
testcase.request.target = '/MediaType/sample.png'
testcase.response.headers['Content-Type'] = 'image/png'
with open(Constants.SERVER_ROOT + '/Method/MediaType/sample.png', 'rb') as f:
testcase.response.body = f.read()
testcase.response.headers['content-length'] = str(len(testcase.response.body))
return testcase
def testCaseMediaType_jpeg():
testcase = defaultMediaTypeTestCase()
testcase.name = 'MediaType_png'
testcase.request.target = '/MediaType/sample.jpeg'
testcase.response.headers['Content-Type'] = 'image/jpeg'
with open(Constants.SERVER_ROOT + '/Method/MediaType/sample.jpeg', 'rb') as f:
testcase.response.body = f.read()
testcase.response.headers['content-length'] = str(len(testcase.response.body))
return testcase
def testCaseMediaType_sh():
testcase = defaultMediaTypeTestCase()
testcase.name = 'MediaType_sh'
testcase.request.target = '/MediaType/sample.sh'
testcase.response.headers['Content-Type'] = 'application/x-sh'
with open(Constants.SERVER_ROOT + '/Method/MediaType/sample.sh', 'rb') as f:
testcase.response.body = f.read()
testcase.response.headers['content-length'] = str(len(testcase.response.body))
return testcase
| [
"testcase_generation.Response.default.defaultTestCase"
] | [((143, 160), 'testcase_generation.Response.default.defaultTestCase', 'defaultTestCase', ([], {}), '()\n', (158, 160), False, 'from testcase_generation.Response.default import defaultTestCase\n')] |
import numpy as np
from typing import List, Tuple
class InterfaceSolver():
"""
Informal interface for solving class needed to interact with rubiks
environment.
"""
def __init__(self, depth:int, possible_moves: List[str]) -> None:
"""
Will be passed depth, i.e. number of backwards turns cube has been
randomly shuffled from solved.
Additionally will be passed the list of acceptable moves that should
be returned by the get_action method. Can be upper or lower case
characters but must be in possible_moves. Each character corresponds to
a face of the cube, upper case is a clockwise turn, lower case is
counter clockwise, will be passed as all upper case.
"""
pass
def get_name(self) -> str:
"""
Each solver will have an associated button in the GUI, this text will
be what is displayed on the button.
"""
def clear(self) -> None:
"""
Will be called before every fresh solve. Can use to reset any necessary
parameters.
"""
pass
def get_action(self, cube_state:np.array) -> Tuple[str,bool]:
"""
Will be passed cube state as a 6x3x3 np.array, where the first index
represents the 6 sides of the cube, and the 2nd and 3rd index form a
3x3 table representing each of the 9 faces on one side of the cube. Each
entry has an integer value {0,5} representing a color. A solved cube is
when for each side, each 3x3 matrix only contains one value. Can assume
cube_state results from taking previous action on previous cube_state.
Must return character from possible_moves passed in init, can be upper
or lower case as described above.
Also must return boolean value indicating if solver is terminating
(True), or not (False). If terminating can either provide action and it
will be executed and then terminate, or can pass action as None, and
solving will be terminated without any action.
"""
pass
def find_shortest_path(node_1,node_2):
"""
Given two nodes indicated by a string of their move sequence from the start
node (forward moves only), this method returns the shortest move sequence
from node_1 to node_2.
"""
# Change to lists
node_1 = list(node_1)
node_1_common = node_1.copy()
node_2 = list(node_2)
node_2_common = node_2.copy()
# Get length of smaller
small_length = min(len(node_1),len(node_2))
# get to smallest common parent node
for i in range(small_length):
if (node_1[i] == node_2[i]):
# then pop because they are the same
node_1_common.pop(0)
node_2_common.pop(0)
else:
# as soon as this isn't true cant get any closer parent node
break
# Now generate path by reversing path to node_1, and follow path to node_2
shortest_path = [x.lower() for x in node_1_common[::-1]]
shortest_path.extend(node_2_common)
return shortest_path
class DepthFirstSearch(InterfaceSolver):
"""
Implements a depth first search algorithm bounded by depth provided.
"""
def __init__(self, depth, possible_moves):
self.depth = depth
self.possible_moves = possible_moves
def get_name(self):
return "DFS"
def depth_first_search(self,current_move,depth):
# If past max depth just retun
if depth < 0:
return
# Otherwise append move to list (or if empty/starting do nothing)
if not len(current_move) == 0:
self.moves_to_make.append(current_move)
# Now go through each possible move/node from here recursively
for m in self.possible_moves:
self.depth_first_search(m,depth-1)
# Now before return, undo current move
if not len(current_move) == 0:
self.moves_to_make.append(current_move.lower())
return
def clear(self):
"""
Because depth bounded and possible moves do not change, can pre-compute
all actions, and then will terminate via main if solved, or here if out
of pre-computed moves.
"""
# Make list of all moves using recursive depth first search
self.moves_to_make = []
self.depth_first_search("",self.depth)
# Reverse string so that popping is constant time
self.moves_to_make.reverse()
def get_action(self, cube_state):
"""
If only one move left provide last action and terminate, otherwise,
pop
Get action based off current index, increment index, and return
"""
terminating = False
if len(self.moves_to_make) == 1:
terminating = True
return self.moves_to_make.pop(), terminating
class BreadthFirstSearch(InterfaceSolver):
"""
Implements a breadth first search algorithm bounded by depth provided.
"""
def __init__(self, depth, possible_moves):
self.depth = depth
self.possible_moves = possible_moves
def get_name(self):
return "BFS"
def clear(self):
"""
Because depth bounded and possible moves do not change, can pre-compute
all actions, and then will terminate via main if solved, or here if out
of pre-computed moves.
"""
# Simulating going through and popping from list below, but just pop and
# append to main list which will be used in action.
save_moves_to_make = []
track_moves_to_make = []
track_moves_to_make.extend(self.possible_moves)
save_moves_to_make.extend(self.possible_moves)
while len(track_moves_to_make) > 0:
# Get next move
next_move = track_moves_to_make.pop(0)
# Now go through neighbors of this next_move/node
for m in self.possible_moves:
to_append = next_move+m
if len(to_append) > self.depth:
continue
else:
track_moves_to_make.append(to_append)
save_moves_to_make.append(to_append)
# Now make completed move list using shortest path between each
self.moves_to_make = []
for i in range(len(save_moves_to_make)):
if i ==0:
self.moves_to_make.append(save_moves_to_make[0])
else:
self.moves_to_make.extend(find_shortest_path(save_moves_to_make[i-1],save_moves_to_make[i]))
# Reverse string so that popping is constant time
self.moves_to_make.reverse()
def get_action(self, cube_state):
"""
If only one move left provide last action and terminate, otherwise,
pop
Get action based off current index, increment index, and return
"""
terminating = False
if len(self.moves_to_make) == 1:
terminating = True
return self.moves_to_make.pop(), terminating
class BestFirstSearch(InterfaceSolver):
"""
Implements a best first search algorithm bounded by depth provided.
Here the metric is used is percentage complete.
For each side the number of squares with the same color as the center is
computed. This metric is summed for each side anid is divide by the total
number of cube faces.
"""
def __init__(self, depth, possible_moves):
self.depth = depth
self.possible_moves = possible_moves
def get_name(self):
return "BestFS"
def clear(self):
self.cube_state_move = []
self.cube_state_values = []
self.actions = []
self.possible_moves_for_node = []
self.last_action = ""
self.move_queue = []
self.previous_node = ""
def get_value(self,cube_state):
total_equal = 0
total = cube_state.size
for i in range(6):
center_val = cube_state[i,1,1]
total_equal += np.sum(cube_state[i,:,:]==center_val)
return float(total_equal)/total
def get_action_nodes(self, cube_state):
"""
Method to actually select next nodes given known values.
"""
# 1. Get value of current cube_state, and append state and value, and nodes_moved_to
self.cube_state_values.append(self.get_value(cube_state))
self.cube_state_move.append(self.last_action)
self.possible_moves_for_node.append(self.possible_moves.copy())
if len(self.actions) == 0:
self.actions.append("")
# 2. Now find best current state
ranked_idx = np.argsort(np.array(self.cube_state_values))[::-1]
next_move = None
for idx in ranked_idx:
# If no more possible moves, just continue, if have move make it and break
if len(self.possible_moves_for_node[idx]) == 0 or len(self.cube_state_move[idx])==self.depth:
continue
else:
next_move = self.cube_state_move[idx] + self.possible_moves_for_node[idx].pop()
break
# 3. If next_move is still none, terminate, no more moves to make
if next_move is None:
return None
# 4. Otherwise, save action and return
self.last_action = next_move
return next_move
def get_action(self,cube_state):
"""
Need wrapper method for node selection to process transitions between
nodes.
"""
terminating = False
# 1. If move queue empty, calculate next node using method, find path and append
if len(self.move_queue) == 0:
next_node = self.get_action_nodes(cube_state)
if next_node is None:
self.move_queue.append(None)
terminating = True
else:
node_path = find_shortest_path(self.previous_node,next_node)
self.move_queue.extend(node_path)
self.previous_node = next_node
# 2. Set previous node, pop and take action
return self.move_queue.pop(0), terminating
#
| [
"numpy.sum",
"numpy.array"
] | [((8033, 8074), 'numpy.sum', 'np.sum', (['(cube_state[i, :, :] == center_val)'], {}), '(cube_state[i, :, :] == center_val)\n', (8039, 8074), True, 'import numpy as np\n'), ((8674, 8706), 'numpy.array', 'np.array', (['self.cube_state_values'], {}), '(self.cube_state_values)\n', (8682, 8706), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.common.by import By
class TestLuckyApp:
"""E2E integration tests class."""
def setup_method(self, method):
options = webdriver.FirefoxOptions()
self.driver = webdriver.Remote('http://firefoxdriver:4444/wd/hub', options=options)
self.driver.set_window_size(1936, 1056)
self.driver.get("http://proxy")
def teardown_method(self, method):
self.driver.quit()
def test_frontend_app(self):
"""Test landing page of fronted app."""
element = self.driver.find_element(By.ID, 'recommendation')
assert element.text == "Pink Flody - Pulse"
self.driver.save_screenshot("/app/tmp/pyshot1.png")
def test_movie_app(self):
"""Test backend app(s)."""
# Click recomendation button.
element = self.driver.find_element(By.ID, 'btn-recommend-movie')
element.click()
# Check if new recomendation appeard on the webpage.
element = self.driver.find_element(By.ID, 'recommendation')
assert element.text != "Pink Flody - Pulse"
self.driver.save_screenshot("/app/tmp/pyshot2.png")
def test_music_app(self):
"""Test backend app(s)."""
# Click recomendation button.
element = self.driver.find_element(By.ID, 'btn-recommend-music')
element.click()
# Check if new recomendation appeard on the webpage.
element = self.driver.find_element(By.ID, 'recommendation')
assert element.text != "Pink Flody - Pulse"
self.driver.save_screenshot("/app/tmp/pyshot3.png")
| [
"selenium.webdriver.FirefoxOptions",
"selenium.webdriver.Remote"
] | [((215, 241), 'selenium.webdriver.FirefoxOptions', 'webdriver.FirefoxOptions', ([], {}), '()\n', (239, 241), False, 'from selenium import webdriver\n'), ((264, 333), 'selenium.webdriver.Remote', 'webdriver.Remote', (['"""http://firefoxdriver:4444/wd/hub"""'], {'options': 'options'}), "('http://firefoxdriver:4444/wd/hub', options=options)\n", (280, 333), False, 'from selenium import webdriver\n')] |
from uuid import UUID
from datetime import datetime
def uuid_from_string(string):
return UUID('{s}'.format(s=string))
def format_timestamp(string):
if isinstance(string, str):
return datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%fZ')
if isinstance(string, datetime):
return string
| [
"datetime.datetime.strptime"
] | [((203, 253), 'datetime.datetime.strptime', 'datetime.strptime', (['string', '"""%Y-%m-%dT%H:%M:%S.%fZ"""'], {}), "(string, '%Y-%m-%dT%H:%M:%S.%fZ')\n", (220, 253), False, 'from datetime import datetime\n')] |
import time
def factorial(n):
fact = 1
for x in range(2, n+1):
fact = fact * x
return fact
# Timing function
start = time.time()
factorial(400000)
end = time.time()
print('Operation done in {} seconds'.format(end - start))
| [
"time.time"
] | [((139, 150), 'time.time', 'time.time', ([], {}), '()\n', (148, 150), False, 'import time\n'), ((175, 186), 'time.time', 'time.time', ([], {}), '()\n', (184, 186), False, 'import time\n')] |
"""
==========================================================================
MeshNetworkCL_test.py
==========================================================================
Test for NetworkCL
Author : <NAME>
Date : May 19, 2019
"""
import pytest
from pymtl3_net.meshnet.MeshNetworkCL import MeshNetworkCL
from pymtl3_net.ocnlib.ifcs.packets import mk_mesh_pkt
from pymtl3_net.ocnlib.ifcs.positions import mk_mesh_pos
from pymtl3_net.ocnlib.utils import run_sim
from pymtl3_net.ocnlib.test.net_sinks import TestNetSinkCL
from pymtl3 import *
from pymtl3.stdlib.test_utils import mk_test_case_table
from pymtl3.stdlib.test_utils.test_srcs import TestSrcCL
from pymtl3_net.router.InputUnitCL import InputUnitCL
#-------------------------------------------------------------------------
# TestHarness
#-------------------------------------------------------------------------
class TestHarness( Component ):
def construct( s, PktType, ncols, nrows,
src_msgs, sink_msgs,
src_initial, src_interval,
sink_initial, sink_interval ):
s.nrouters = ncols * nrows
MeshPos = mk_mesh_pos( ncols, nrows )
match_func = lambda a, b : a==b
s.dut = MeshNetworkCL( PktType, MeshPos, ncols, nrows, 0 )
s.srcs = [ TestSrcCL( PktType, src_msgs[i], src_initial, src_interval )
for i in range( s.nrouters ) ]
s.sinks = [ TestNetSinkCL( PktType, sink_msgs[i], sink_initial, sink_interval, match_func=match_func)
for i in range( s.nrouters ) ]
# Connections
for i in range ( s.nrouters ):
s.srcs[i].send //= s.dut.recv[i]
s.dut.send[i] //= s.sinks[i].recv
def done( s ):
srcs_done = 1
sinks_done = 1
for i in range( s.nrouters ):
if s.srcs[i].done() == 0:
srcs_done = 0
for i in range( s.nrouters ):
if s.sinks[i].done() == 0:
sinks_done = 0
return srcs_done and sinks_done
def line_trace( s ):
return s.dut.line_trace()
#-------------------------------------------------------------------------
# Helper functions
#-------------------------------------------------------------------------
def mk_src_sink_msgs( PktType, msgs, ncols, nrows ):
nrouters = ncols * nrows
src_msgs = [ [] for _ in range( nrouters ) ]
sink_msgs = [ [] for _ in range( nrouters ) ]
for msg in msgs:
src_x, src_y, dst_x, dst_y, opq, payload = msg
src_id = src_y * ncols + src_x
sink_id = dst_y * ncols + dst_x
src_msgs [ src_id ] .append( PktType(*msg) )
sink_msgs[ sink_id ].append( PktType(*msg) )
return src_msgs, sink_msgs
def mk_pkt_list( PktType, lst ):
ret = []
for m in lst:
src_x, src_y, dst_x, dst_y, opq, payload = m[0], m[1], m[2], m[3], m[4], m[5]
ret.append( PktType( src_x, src_y, dst_x, dst_y, opq, payload ) )
return ret
#-------------------------------------------------------------------------
# Test cases
#-------------------------------------------------------------------------
simple_2x2 = [
# src_x src_y dst_x dst_y opq payload
( 0, 0, 0, 1, 0x00, 0x0010 ),
( 1, 0, 1, 1, 0x01, 0x0020 ),
]
simple_4x4 = [
# src_x src_y dst_x dst_y opq payload
( 0, 0, 0, 1, 0x00, 0x0010 ),
( 1, 0, 1, 1, 0x01, 0x0020 ),
( 3, 2, 1, 1, 0x02, 0x0020 ),
( 1, 0, 1, 1, 0x03, 0x0020 ),
( 1, 3, 2, 1, 0x04, 0x0020 ),
( 3, 3, 1, 0, 0x05, 0x0020 ),
]
simple_8x8 = [
# src_x src_y dst_x dst_y opq payload
( 0, 0, 0, 1, 0x00, 0x0010 ),
( 1, 0, 1, 1, 0x01, 0x0020 ),
( 3, 2, 1, 1, 0x02, 0x0020 ),
( 1, 0, 1, 1, 0x03, 0x0020 ),
( 1, 3, 2, 1, 0x04, 0x0020 ),
( 3, 5, 1, 0, 0x05, 0x0020 ),
]
#-------------------------------------------------------------------------
# test case table
#-------------------------------------------------------------------------
test_case_table = mk_test_case_table([
( "msg_list wid ht src_init src_intv sink_init sink_intv"),
["simple2x2", simple_2x2, 2, 2, 0, 0, 0, 0 ],
["simple4x4", simple_4x4, 4, 4, 0, 0, 0, 0 ],
["simple8x8", simple_8x8, 8, 8, 0, 0, 0, 0 ],
])
#-------------------------------------------------------------------------
# run test
#-------------------------------------------------------------------------
@pytest.mark.parametrize( **test_case_table )
def test_mesh_simple( test_params ):
PktType = mk_mesh_pkt( ncols=test_params.wid,
nrows=test_params.ht, vc=1 )
src_msgs, sink_msgs = mk_src_sink_msgs( PktType, test_params.msg_list,
test_params.wid, test_params.ht )
th = TestHarness(
PktType,
test_params.wid,
test_params.ht,
src_msgs,
sink_msgs,
test_params.src_init,
test_params.src_intv,
test_params.sink_init,
test_params.sink_intv,
)
run_sim( th )
| [
"pymtl3_net.ocnlib.utils.run_sim",
"pymtl3_net.meshnet.MeshNetworkCL.MeshNetworkCL",
"pymtl3_net.ocnlib.ifcs.positions.mk_mesh_pos",
"pymtl3_net.ocnlib.ifcs.packets.mk_mesh_pkt",
"pytest.mark.parametrize",
"pymtl3.stdlib.test_utils.test_srcs.TestSrcCL",
"pymtl3_net.ocnlib.test.net_sinks.TestNetSinkCL",
... | [((4006, 4237), 'pymtl3.stdlib.test_utils.mk_test_case_table', 'mk_test_case_table', (["['msg_list wid ht src_init src_intv sink_init sink_intv', ['simple2x2',\n simple_2x2, 2, 2, 0, 0, 0, 0], ['simple4x4', simple_4x4, 4, 4, 0, 0, 0,\n 0], ['simple8x8', simple_8x8, 8, 8, 0, 0, 0, 0]]"], {}), "([\n 'msg_list wid ht src_init src_intv sink_init sink_intv', [\n 'simple2x2', simple_2x2, 2, 2, 0, 0, 0, 0], ['simple4x4', simple_4x4, 4,\n 4, 0, 0, 0, 0], ['simple8x8', simple_8x8, 8, 8, 0, 0, 0, 0]])\n", (4024, 4237), False, 'from pymtl3.stdlib.test_utils import mk_test_case_table\n'), ((4506, 4548), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ([], {}), '(**test_case_table)\n', (4529, 4548), False, 'import pytest\n'), ((4600, 4662), 'pymtl3_net.ocnlib.ifcs.packets.mk_mesh_pkt', 'mk_mesh_pkt', ([], {'ncols': 'test_params.wid', 'nrows': 'test_params.ht', 'vc': '(1)'}), '(ncols=test_params.wid, nrows=test_params.ht, vc=1)\n', (4611, 4662), False, 'from pymtl3_net.ocnlib.ifcs.packets import mk_mesh_pkt\n'), ((5055, 5066), 'pymtl3_net.ocnlib.utils.run_sim', 'run_sim', (['th'], {}), '(th)\n', (5062, 5066), False, 'from pymtl3_net.ocnlib.utils import run_sim\n'), ((1134, 1159), 'pymtl3_net.ocnlib.ifcs.positions.mk_mesh_pos', 'mk_mesh_pos', (['ncols', 'nrows'], {}), '(ncols, nrows)\n', (1145, 1159), False, 'from pymtl3_net.ocnlib.ifcs.positions import mk_mesh_pos\n'), ((1210, 1258), 'pymtl3_net.meshnet.MeshNetworkCL.MeshNetworkCL', 'MeshNetworkCL', (['PktType', 'MeshPos', 'ncols', 'nrows', '(0)'], {}), '(PktType, MeshPos, ncols, nrows, 0)\n', (1223, 1258), False, 'from pymtl3_net.meshnet.MeshNetworkCL import MeshNetworkCL\n'), ((1278, 1336), 'pymtl3.stdlib.test_utils.test_srcs.TestSrcCL', 'TestSrcCL', (['PktType', 'src_msgs[i]', 'src_initial', 'src_interval'], {}), '(PktType, src_msgs[i], src_initial, src_interval)\n', (1287, 1336), False, 'from pymtl3.stdlib.test_utils.test_srcs import TestSrcCL\n'), ((1405, 1497), 'pymtl3_net.ocnlib.test.net_sinks.TestNetSinkCL', 'TestNetSinkCL', (['PktType', 'sink_msgs[i]', 'sink_initial', 'sink_interval'], {'match_func': 'match_func'}), '(PktType, sink_msgs[i], sink_initial, sink_interval,\n match_func=match_func)\n', (1418, 1497), False, 'from pymtl3_net.ocnlib.test.net_sinks import TestNetSinkCL\n')] |
import os
# Helpers
def read_asset(*paths):
dirname = os.path.dirname(__file__)
return open(os.path.join(dirname, "assets", *paths)).read().strip()
# General
VERSION = read_asset("VERSION")
| [
"os.path.dirname",
"os.path.join"
] | [((62, 87), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (77, 87), False, 'import os\n'), ((104, 143), 'os.path.join', 'os.path.join', (['dirname', '"""assets"""', '*paths'], {}), "(dirname, 'assets', *paths)\n", (116, 143), False, 'import os\n')] |
import sys
from glob import glob
from serial import Serial, SerialException
import numpy as np
BAUD_RATE = 9600
PORT = 'COM5'
READ_TIMEOUT = 1
LOWER_BOUND = 0.01
UPPER_BOUND = 0.4
class SerialCommunication():
""" Manages the communication and sends the data to the Arduino """
def __init__(self):
self._serial_channel = Serial()
self._serial_channel.port = PORT
self._serial_channel.baudrate = BAUD_RATE
@property
def baudrate(self):
return self._serial_channel.baudrate
@baudrate.setter
def baudrate(self, new_baudrate):
if not self._serial_channel.is_open:
self._serial_channel.baudrate = new_baudrate
else:
raise Exception("Close connection before changing baudrate")
@property
def port(self):
return self._serial_channel.port
@port.setter
def set_port(self, new_port):
if not self._serial_channel.is_open:
self._serial_channel.port = new_port
else:
raise Exception("Close connection before changing port")
def get_available_serial_ports(self):
""" Returns a list of all ports that can be opened """
if self._serial_channel.is_open:
raise Exception("Close connection before")
result = []
for port in self._list_all_possibles_ports():
try:
Serial(port).close()
result.append(port)
except (OSError, SerialException):
pass
return result
def establish_communication(self):
"""
Enables the communication with the arduino with the latest parameters
Throws a SerialException is it cannot connect to port
"""
try:
self._serial_channel.open()
except SerialException as error:
print("Error when connecting to serial %s port" % (self._serial_channel.port))
raise(SerialException)
def send_data(self, data):
""" prints feedback data from the arduino and sends the new data """
if self._is_data_available():
print(("Reading : ", self._read_bytes(len(data))))
data = [x[1] for x in data]
if self._is_data_valid(data):
value_to_send = self._get_clipped_signals(data)
print(('Sending', value_to_send))
try:
self._serial_channel.write(bytearray(value_to_send))
except SerialTimeoutException as e:
print('Error when sending data to microcontroller:' + str(e))
def close_communication(self):
self._serial_channel.close()
def _list_all_possibles_ports(self):
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
return ports
def _read_bytes(self, nb_bytes=1):
bytes_received = []
for _ in range(nb_bytes):
bytes_received.append(self._serial_channel.read(1))
return [ord(byte) for byte in bytes_received if byte]
def _is_data_available(self):
return self._serial_channel is not None and self._serial_channel.is_open and self._serial_channel.in_waiting
def _is_data_valid(self, data):
return self._serial_channel is not None and self._serial_channel.is_open and not np.any(np.isnan(data))
def _get_clipped_signals(self, signals):
clipped_list = np.clip(signals, LOWER_BOUND, UPPER_BOUND)
return [int(255 * (x - LOWER_BOUND)/(UPPER_BOUND - LOWER_BOUND)) for x in clipped_list]
| [
"numpy.clip",
"sys.platform.startswith",
"serial.Serial",
"numpy.isnan",
"glob.glob"
] | [((342, 350), 'serial.Serial', 'Serial', ([], {}), '()\n', (348, 350), False, 'from serial import Serial, SerialException\n'), ((2715, 2745), 'sys.platform.startswith', 'sys.platform.startswith', (['"""win"""'], {}), "('win')\n", (2738, 2745), False, 'import sys\n'), ((3799, 3841), 'numpy.clip', 'np.clip', (['signals', 'LOWER_BOUND', 'UPPER_BOUND'], {}), '(signals, LOWER_BOUND, UPPER_BOUND)\n', (3806, 3841), True, 'import numpy as np\n'), ((2820, 2852), 'sys.platform.startswith', 'sys.platform.startswith', (['"""linux"""'], {}), "('linux')\n", (2843, 2852), False, 'import sys\n'), ((2856, 2889), 'sys.platform.startswith', 'sys.platform.startswith', (['"""cygwin"""'], {}), "('cygwin')\n", (2879, 2889), False, 'import sys\n'), ((2972, 2997), 'glob.glob', 'glob', (['"""/dev/tty[A-Za-z]*"""'], {}), "('/dev/tty[A-Za-z]*')\n", (2976, 2997), False, 'from glob import glob\n'), ((3011, 3044), 'sys.platform.startswith', 'sys.platform.startswith', (['"""darwin"""'], {}), "('darwin')\n", (3034, 3044), False, 'import sys\n'), ((3066, 3084), 'glob.glob', 'glob', (['"""/dev/tty.*"""'], {}), "('/dev/tty.*')\n", (3070, 3084), False, 'from glob import glob\n'), ((3713, 3727), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (3721, 3727), True, 'import numpy as np\n'), ((1391, 1403), 'serial.Serial', 'Serial', (['port'], {}), '(port)\n', (1397, 1403), False, 'from serial import Serial, SerialException\n')] |
"""add unique constraint to Source
Revision ID: 4415298e147b
Revises: 7392493a<PASSWORD>
Create Date: 2020-01-02 16:41:03.424945
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '7392493a0768'
branch_labels = None
depends_on = None
def upgrade():
op.create_unique_constraint('ori_id_canonical_fields', 'source', ['resource_ori_id', 'canonical_id', 'canonical_iri'])
def downgrade():
op.drop_constraint('ori_id_canonical_fields', 'source')
| [
"alembic.op.drop_constraint",
"alembic.op.create_unique_constraint"
] | [((335, 458), 'alembic.op.create_unique_constraint', 'op.create_unique_constraint', (['"""ori_id_canonical_fields"""', '"""source"""', "['resource_ori_id', 'canonical_id', 'canonical_iri']"], {}), "('ori_id_canonical_fields', 'source', [\n 'resource_ori_id', 'canonical_id', 'canonical_iri'])\n", (362, 458), False, 'from alembic import op\n'), ((477, 532), 'alembic.op.drop_constraint', 'op.drop_constraint', (['"""ori_id_canonical_fields"""', '"""source"""'], {}), "('ori_id_canonical_fields', 'source')\n", (495, 532), False, 'from alembic import op\n')] |
"""Helper methods for parsing EBS-related data from AWS SDK."""
import logging
import myutils
logger = myutils.get_logger(__name__, logging.DEBUG)
@myutils.log_calls(level=logging.DEBUG)
def parse(sdk_snapshots):
"""Process raw EBS snapshot data."""
snapshots = []
snapshots.extend(
map(map_snapshot, sdk_snapshots.get('Snapshots', []))
)
return snapshots
@myutils.log_calls(level=logging.DEBUG)
def map_snapshot(snapshot):
"""Map AWS EBS snapshot data to response message format."""
tags = snapshot.get('Tags', [])
return {
'name': myutils.get_first('Name', tags),
'server': get_server_name(tags),
'snapshotId': snapshot.get('SnapshotId', ''),
'event': myutils.get_first('Event', tags),
'timestamp': myutils.get_first('Timestamp', tags)
}
def get_server_name(tags):
"""Retrieve server name from across different tag scenarios."""
server = myutils.get_first('Server', tags)
if server is None or server == '':
name_parts = myutils.get_first('Name', tags).split('-')
prefix = name_parts[0] if len(name_parts) > 0 else ''
if prefix == 'minecraft':
server = name_parts[3] if len(name_parts) > 3 else ''
else:
server = name_parts[2] if len(name_parts) > 2 else ''
return server
| [
"myutils.get_first",
"myutils.log_calls",
"myutils.get_logger"
] | [((105, 148), 'myutils.get_logger', 'myutils.get_logger', (['__name__', 'logging.DEBUG'], {}), '(__name__, logging.DEBUG)\n', (123, 148), False, 'import myutils\n'), ((152, 190), 'myutils.log_calls', 'myutils.log_calls', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (169, 190), False, 'import myutils\n'), ((391, 429), 'myutils.log_calls', 'myutils.log_calls', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (408, 429), False, 'import myutils\n'), ((940, 973), 'myutils.get_first', 'myutils.get_first', (['"""Server"""', 'tags'], {}), "('Server', tags)\n", (957, 973), False, 'import myutils\n'), ((587, 618), 'myutils.get_first', 'myutils.get_first', (['"""Name"""', 'tags'], {}), "('Name', tags)\n", (604, 618), False, 'import myutils\n'), ((732, 764), 'myutils.get_first', 'myutils.get_first', (['"""Event"""', 'tags'], {}), "('Event', tags)\n", (749, 764), False, 'import myutils\n'), ((787, 823), 'myutils.get_first', 'myutils.get_first', (['"""Timestamp"""', 'tags'], {}), "('Timestamp', tags)\n", (804, 823), False, 'import myutils\n'), ((1034, 1065), 'myutils.get_first', 'myutils.get_first', (['"""Name"""', 'tags'], {}), "('Name', tags)\n", (1051, 1065), False, 'import myutils\n')] |
import assets
import webbrowser
from PyQt5.Qt import QMessageBox
from PyQt5.QtNetwork import QNetworkDiskCache
from PyQt5.QtWebKitWidgets import QWebPage, QWebInspector
class WebPage(QWebPage):
def __init__(self):
super(WebPage, self).__init__()
self.inspector = QWebInspector()
self.inspector.setPage(self)
self.inspector.resize(1024, 400)
diskCache = QNetworkDiskCache(self)
diskCache.setCacheDirectory(assets.fs.dataPath() + '/Cache')
self.networkAccessManager().setCache(diskCache)
self.networkAccessManager().setCookieJar(assets.dataJar)
def acceptNavigationRequest(self, frame, request, type):
if(type == QWebPage.NavigationTypeLinkClicked):
url = request.url().toString()
if(frame == self.mainFrame()):
self.view().load(url)
return False
elif frame == None:
# self.createWindow(QWebPage.WebBrowserWindow, url)
webbrowser.open(request.url().toString())
return False
return QWebPage.acceptNavigationRequest(self, frame, request, type)
# def downloadRequested(self, request):
# print(request)
def findText(self, text):
return super(WebPage, self).findText(text, QWebPage.FindBackward)
def showInspector(self):
self.inspector.show()
self.inspector.activateWindow()
def hideInspector(self):
self.inspector.close()
def createWindow(self, type, url = None):
from window import Window
window = Window(self.view().parentWidget(), url, isDialog = (type == QWebPage.WebModalDialog))
return window.webView.page()
def javaScriptAlert(self, frame, msg):
QMessageBox.information(self.view().parentWidget(), None, msg)
def javaScriptConfirm(self, frame, msg):
return QMessageBox.question(self.view().parentWidget(), None, msg) == QMessageBox.Yes
# There is a bug in PyQt
# def javaScriptPrompt(self, frame, msg, defaultValue):
# result = QInputDialog.getText(self.view().parentWidget(), None, msg)
# return (result[1], result[0])
def close(self):
self.hideInspector()
assets.dataJar.save()
| [
"assets.dataJar.save",
"assets.fs.dataPath",
"PyQt5.QtWebKitWidgets.QWebPage.acceptNavigationRequest",
"PyQt5.QtWebKitWidgets.QWebInspector",
"PyQt5.QtNetwork.QNetworkDiskCache"
] | [((269, 284), 'PyQt5.QtWebKitWidgets.QWebInspector', 'QWebInspector', ([], {}), '()\n', (282, 284), False, 'from PyQt5.QtWebKitWidgets import QWebPage, QWebInspector\n'), ((365, 388), 'PyQt5.QtNetwork.QNetworkDiskCache', 'QNetworkDiskCache', (['self'], {}), '(self)\n', (382, 388), False, 'from PyQt5.QtNetwork import QNetworkDiskCache\n'), ((932, 992), 'PyQt5.QtWebKitWidgets.QWebPage.acceptNavigationRequest', 'QWebPage.acceptNavigationRequest', (['self', 'frame', 'request', 'type'], {}), '(self, frame, request, type)\n', (964, 992), False, 'from PyQt5.QtWebKitWidgets import QWebPage, QWebInspector\n'), ((1959, 1980), 'assets.dataJar.save', 'assets.dataJar.save', ([], {}), '()\n', (1978, 1980), False, 'import assets\n'), ((419, 439), 'assets.fs.dataPath', 'assets.fs.dataPath', ([], {}), '()\n', (437, 439), False, 'import assets\n')] |
import azure.functions as func
from .add_url_rule import app
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
return func.WsgiMiddleware(app.wsgi_app).handle(req, context)
| [
"azure.functions.WsgiMiddleware"
] | [((151, 184), 'azure.functions.WsgiMiddleware', 'func.WsgiMiddleware', (['app.wsgi_app'], {}), '(app.wsgi_app)\n', (170, 184), True, 'import azure.functions as func\n')] |
from flask import Flask
from app.services import model_manager
from app.controllers.api_blueprint import api_router
from app.controllers.main_blueprint import main_router
def create_app(test_config=None):
app = Flask(__name__)
model_manager.init_app(app)
app.register_blueprint(api_router)
app.register_blueprint(main_router)
return app | [
"app.services.model_manager.init_app",
"flask.Flask"
] | [((216, 231), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (221, 231), False, 'from flask import Flask\n'), ((237, 264), 'app.services.model_manager.init_app', 'model_manager.init_app', (['app'], {}), '(app)\n', (259, 264), False, 'from app.services import model_manager\n')] |
import sys
import time
import threading
import grpc
import numpy
import soundfile as sf
import tensorflow as tf
import _init_paths
import audioset.vggish_input as vggish_input
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
tf.app.flags.DEFINE_integer('concurrency', 1, 'concurrent inference requests limit')
tf.app.flags.DEFINE_integer('num_tests', 100, 'Number of test sample')
tf.app.flags.DEFINE_string('server', '0.0.0.0:8500', 'PredictionService host:port')
tf.app.flags.DEFINE_string('work_dir', '/tmp', 'Working directory')
FLAGS = tf.app.flags.FLAGS
class _ResultCounter(object):
def __init__(self, num_tests, concurrency):
self._num_tests = num_tests
self._concurrency = concurrency
self._error = 0
self._done = 0
self._active = 0
self._condition = threading.Condition()
self._start_time = -1
self._end_time = 0
def inc_done(self):
with self._condition:
self._done += 1
if self._done == self._num_tests:
self.set_end_time(time.time())
self._condition.notify()
def dec_active(self):
with self._condition:
self._active -= 1
self._condition.notify()
def throttle(self):
with self._condition:
if self._start_time == -1:
self._start_time = time.time()
while self._active == self._concurrency:
self._condition.wait()
self._active += 1
def set_start_time(self, start_time):
self._start_time = start_time
def set_end_time(self, end_time):
self._end_time = end_time
def get_throughput(self):
if self._end_time == 0:
self.set_end_time(time.time())
print(self._end_time - self._start_time)
return self._num_tests / (self._end_time - self._start_time)
def time_to_sample(t, sr, factor):
return round(sr * t / factor)
def _create_rpc_callback(label, result_counter):
def _callback(result_future):
exception = result_future.exception()
if exception:
# result_counter.inc_error()
print(exception)
else:
print('normal')
sys.stdout.write('.')
sys.stdout.flush()
response = numpy.array(result_future.result().outputs['output'].float_val)
result_counter.inc_done()
result_counter.dec_active()
return _callback
def inference(hostport, work_dir, concurrency, num_tests):
audio_path = 'test_DB/test_airport.wav'
num_secs = 1
sc_start = 0
sc_end = 2000
wav_data, sr = sf.read(audio_path, dtype='int16')
assert wav_data.dtype == numpy.int16, 'Bad sample type: %r' % wav_data.dtype
samples = wav_data / 32768.0 # Convert to [-1.0, +1.0]
sc_center = time_to_sample((sc_start + sc_end) / 2, sr, 1000.0)
# print('Center is {} when sample_rate is {}'.format(sc_center, sr))
data_length = len(samples)
data_width = time_to_sample(num_secs, sr, 1.0)
half_input_width = int(data_width / 2)
if sc_center < half_input_width:
pad_width = half_input_width - sc_center
samples = numpy.pad(samples, [(pad_width, 0), (0, 0)], mode='constant', constant_values=0)
sc_center += pad_width
elif sc_center + half_input_width > data_length:
pad_width = sc_center + half_input_width - data_length
samples = numpy.pad(samples, [(0, pad_width), (0, 0)], mode='constant', constant_values=0)
samples = samples[sc_center - half_input_width: sc_center + half_input_width]
audio_input = vggish_input.waveform_to_examples(samples, sr)
print(audio_input.dtype)
audio_input = audio_input.astype(numpy.float32)
channel = grpc.insecure_channel(hostport)
stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
result_counter = _ResultCounter(num_tests, concurrency)
for _ in range(num_tests):
request = predict_pb2.PredictRequest()
request.model_spec.name = 'vgg'
request.model_spec.signature_name = 'prediction'
print(audio_input.shape)
request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(audio_input, shape=audio_input.shape))
result_counter.throttle()
result_future = stub.Predict.future(request, 5.0)
result_future.add_done_callback(_create_rpc_callback(None, result_counter))
return result_counter.get_throughput()
def main(_):
if FLAGS.num_tests > 10000:
print('num_tests should not be greater than 10k')
return
if not FLAGS.server:
print('please specify server host:port')
return
tfs_throughput = inference(FLAGS.server, FLAGS.work_dir, FLAGS.concurrency, FLAGS.num_tests)
print('\n TFS Thoughput: %s requests/sec' % (tfs_throughput))
if __name__ == '__main__':
tf.app.run()
| [
"sys.stdout.flush",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow_serving.apis.predict_pb2.PredictRequest",
"tensorflow_serving.apis.prediction_service_pb2_grpc.PredictionServiceStub",
"grpc.insecure_channel",
"tensorflow.app.flags.DEFINE_string",
"sys.stdout.write",
"numpy.pad",
"audioset.vggi... | [((293, 381), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""concurrency"""', '(1)', '"""concurrent inference requests limit"""'], {}), "('concurrency', 1,\n 'concurrent inference requests limit')\n", (320, 381), True, 'import tensorflow as tf\n'), ((378, 448), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_tests"""', '(100)', '"""Number of test sample"""'], {}), "('num_tests', 100, 'Number of test sample')\n", (405, 448), True, 'import tensorflow as tf\n'), ((449, 536), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""server"""', '"""0.0.0.0:8500"""', '"""PredictionService host:port"""'], {}), "('server', '0.0.0.0:8500',\n 'PredictionService host:port')\n", (475, 536), True, 'import tensorflow as tf\n'), ((533, 600), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""work_dir"""', '"""/tmp"""', '"""Working directory"""'], {}), "('work_dir', '/tmp', 'Working directory')\n", (559, 600), True, 'import tensorflow as tf\n'), ((2715, 2749), 'soundfile.read', 'sf.read', (['audio_path'], {'dtype': '"""int16"""'}), "(audio_path, dtype='int16')\n", (2722, 2749), True, 'import soundfile as sf\n'), ((3689, 3735), 'audioset.vggish_input.waveform_to_examples', 'vggish_input.waveform_to_examples', (['samples', 'sr'], {}), '(samples, sr)\n', (3722, 3735), True, 'import audioset.vggish_input as vggish_input\n'), ((3831, 3862), 'grpc.insecure_channel', 'grpc.insecure_channel', (['hostport'], {}), '(hostport)\n', (3852, 3862), False, 'import grpc\n'), ((3874, 3932), 'tensorflow_serving.apis.prediction_service_pb2_grpc.PredictionServiceStub', 'prediction_service_pb2_grpc.PredictionServiceStub', (['channel'], {}), '(channel)\n', (3923, 3932), False, 'from tensorflow_serving.apis import prediction_service_pb2_grpc\n'), ((4942, 4954), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (4952, 4954), True, 'import tensorflow as tf\n'), ((883, 904), 'threading.Condition', 'threading.Condition', ([], {}), '()\n', (902, 904), False, 'import threading\n'), ((3262, 3347), 'numpy.pad', 'numpy.pad', (['samples', '[(pad_width, 0), (0, 0)]'], {'mode': '"""constant"""', 'constant_values': '(0)'}), "(samples, [(pad_width, 0), (0, 0)], mode='constant', constant_values=0\n )\n", (3271, 3347), False, 'import numpy\n'), ((4042, 4070), 'tensorflow_serving.apis.predict_pb2.PredictRequest', 'predict_pb2.PredictRequest', ([], {}), '()\n', (4068, 4070), False, 'from tensorflow_serving.apis import predict_pb2\n'), ((2298, 2319), 'sys.stdout.write', 'sys.stdout.write', (['"""."""'], {}), "('.')\n", (2314, 2319), False, 'import sys\n'), ((2332, 2350), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2348, 2350), False, 'import sys\n'), ((3508, 3593), 'numpy.pad', 'numpy.pad', (['samples', '[(0, pad_width), (0, 0)]'], {'mode': '"""constant"""', 'constant_values': '(0)'}), "(samples, [(0, pad_width), (0, 0)], mode='constant', constant_values=0\n )\n", (3517, 3593), False, 'import numpy\n'), ((4242, 4313), 'tensorflow.contrib.util.make_tensor_proto', 'tf.contrib.util.make_tensor_proto', (['audio_input'], {'shape': 'audio_input.shape'}), '(audio_input, shape=audio_input.shape)\n', (4275, 4313), True, 'import tensorflow as tf\n'), ((1428, 1439), 'time.time', 'time.time', ([], {}), '()\n', (1437, 1439), False, 'import time\n'), ((1813, 1824), 'time.time', 'time.time', ([], {}), '()\n', (1822, 1824), False, 'import time\n'), ((1125, 1136), 'time.time', 'time.time', ([], {}), '()\n', (1134, 1136), False, 'import time\n')] |
import sqlite3
class Stats:
con = sqlite3.connect("data.db")
cur = con.cursor()
stats_insert_com = "INSERT INTO Stats (Player, 'Win Count', 'Play Count', winPlayRatio) VALUES (?, ?, ?, ?);"
matchhist_insert_com = "INSERT INTO MatchHistory (matchNum, playerList, 'Winner', numRounds) VALUES (?, ?, ?, ?);"
stats_update_com = "UPDATE Stats SET 'Win Count'= ?, 'Play Count' = ?, winPlayRatio = ? WHERE Player = ?;"
player_select_com = "SELECT * from Stats WHERE Player = ?"
#test execute
@staticmethod
def test():
ta = 3
na = "lol"
Stats.cur.execute(Stats.stats_update_com, (2, 2, '2/2', 'pp'))
Stats.con.commit()
Stats.con.close()
@staticmethod
def addMatchHist(plr_ls, winner, num_rounds):
try:
Stats.cur.execute("SELECT * from MatchHistory")
#gets latest match number
match_num = len(Stats.cur.fetchall()) + 1
#adds match to db
Stats.cur.execute(Stats.matchhist_insert_com, (match_num, plr_ls.__str__(), winner, num_rounds))
Stats.con.commit()
except sqlite3.Error as err:
print("Cannot add to match history", err)
@staticmethod
def updateStats(player_name, wins):
try:
Stats.cur.execute("SELECT * from Stats")
records = Stats.cur.fetchall()
#get list of all previous player data
existing_players = []
for row in records:
existing_players.append(row[0])
if player_name in existing_players:
player_data = []
for row in records:
if row[0] == player_name:
player_data = row
break
win_c = player_data[1] + int(wins)
play_c = player_data[2] + 1
ratio = str(win_c)+'/'+str(play_c)
Stats.cur.execute(Stats.stats_update_com, (win_c, play_c , ratio, player_name))
else:
win_c = int(wins)
ratio = str(win_c) +"/1"
Stats.cur.execute(Stats.stats_insert_com, (player_name, win_c, 1, ratio))
Stats.con.commit()
except sqlite3.Error as err:
print("Cannot update player stats", err)
@staticmethod
def displayHistory(depth):
try:
Stats.cur.execute("SELECT * from MatchHistory")
records = Stats.cur.fetchall()
for x in range(1,depth+1):
print("Match ID: " + str(records[-x][0]))
print("List of Participants: " + records[-x][1])
print("Winner: " + records[-x][2])
print("Number of Rounds of the Match: " + str(records[-x][3]))
print("")
except sqlite3.Error as err:
print("Cannot display match history", err)
@staticmethod
def getHistorySize():
try:
Stats.cur.execute("SELECT * from MatchHistory")
records = Stats.cur.fetchall()
return len(records)
except sqlite3.Error as err:
print("Could not access match history", err)
return -1
@staticmethod
def displayPlayerStats(player_name):
try:
Stats.cur.execute(Stats.player_select_com, (player_name,))
record = Stats.cur.fetchone()
print("Here are " + player_name + "'s Stats:")
print("Number of games won: " + str(record[1]))
print("Number of times played: " + str(record[2]))
print("Win-Plays ratio: " + record[3])
print("")
except sqlite3.Error as err:
print("Player not found", err)
| [
"sqlite3.connect"
] | [((39, 65), 'sqlite3.connect', 'sqlite3.connect', (['"""data.db"""'], {}), "('data.db')\n", (54, 65), False, 'import sqlite3\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 21:46:56 2020
@author: adwait
"""
import numpy as np
import cv2
import pims
from tkinter import messagebox, Tk
from PIL import ImageFont, ImageDraw, Image
from PyQt5.QtGui import QIcon
import logging
class MainRecordFunctions:
def recordVideo(self, frame1, frame2):
logging.debug("recordvideo")
if self.forceData.force_filepath == "":
start_framenum = -1
end_framenum = -1
else:
# self.forceData.getArea(self.frameTime, self.dataDict)
start_framenum = self.forceData.plot_slice2.start
end_framenum = self.forceData.plot_slice2.stop + 1
if self.recordStatus == True:
if int(self.framePos) >= start_framenum:
h , w = 512, 512 #TODO: include this gui
# dim = (w, h)
if frame2.ndim == 2:
frame2 = cv2.cvtColor(frame2, cv2.COLOR_GRAY2BGR)
## if self.showContours.isChecked() == False:
## roi = self.roiBound
## self.merged_frame[:h, :w] = self.image_resize(frame1[roi[1]:roi[3],
## roi[0]:roi[2]],
## w, h, inter = cv2.INTER_AREA)
## else:
self.merged_frame[:h, :w], scaleFactor = self.image_resize(frame1, w, h,
inter = cv2.INTER_AREA)
if self.configRecWindow.fourRec.isChecked() == True:
if self.forceData.force_filepath == "" or self.cap2 == None:
root = Tk()
root.withdraw()
messagebox.showinfo("Error!", "Check 2nd video file or force data file. Not found!")
root.destroy()
self.record_frame() #finish recording
self.playStatus = False #pause video
return
## frame2 = cv2.cvtColor(self.frame_contours, cv2.COLOR_GRAY2BGR)
# frame2 = self.frame_contour.copy()
# ret, frame3 = self.cap2.read()
# self.forceData.getArea(self.frameTime, self.dataDict)
# self.forceData.plotData(self.lengthUnit.currentText()) #prepare plot
# frame4 = cv2.resize(cv2.cvtColor(self.forceData.convertPlot(), cv2.COLOR_RGB2BGR),
# (w, h), interpolation = cv2.INTER_AREA)
#only record till plot range. continue playing to get all data
if int(self.framePos) == end_framenum:
# if ret == False: #video at end
logging.debug("2nd video end")
# self.cap2.release()
self.cap2 = None
self.record_frame() #finish recording
self.playStatus = True
return
else:
frame2 = self.frame_contour.copy()
frame3 = self.cap2[self.framePos-1]#self.cap2.read()
self.forceData.getArea(self.frameTime, self.dataDict)
# self.forceData.plotData(self.imageDataUnitDict) #prepare plot
self.forceData.plotImageAnimate(int(self.framePos))
frame4 = cv2.resize(cv2.cvtColor(self.forceData.convertPlot(), cv2.COLOR_RGB2BGR),
(w, h), interpolation = cv2.INTER_AREA)
# framenumber1 = self.cap.get(cv2.CAP_PROP_POS_FRAMES)
# framenumber2 = self.cap2.get(cv2.CAP_PROP_POS_FRAMES)
# logging.debug('%s, %s, %s', "position", framenumber1, framenumber2)
# if framenumber1 != framenumber2: #check both videos are in sync
# root = Tk()
# root.withdraw()
# messagebox.showinfo("Error!", "Video frame numbers dont match!\n" +
# "Video-1 frame:\t" + str(framenumber1) + "\n" +
# "Video-2 frame:\t" + str(framenumber2))
# root.destroy()
# self.record_frame() #finish recording
# self.playStatus = False #pause video
# return
# logging.debug('%s, %s, %s', "position", self.cap.get(cv2.CAP_PROP_POS_FRAMES),
# self.cap2.get(cv2.CAP_PROP_POS_FRAMES))
self.merged_frame[:h, w:], r = self.image_resize(frame3, w, h,
inter = cv2.INTER_AREA)
self.merged_frame[h:, :w], r = self.image_resize(frame2, w, h,
inter = cv2.INTER_AREA)
self.merged_frame[h:, w:], r = self.image_resize(frame4, w, h,
inter = cv2.INTER_AREA)
# Write video2 title
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (int(1.0*w), int(0.05*h))
fontScale = 1.5
fontColor = (0,0,250)
thickness = 3
lineType = 1
cv2.putText(self.merged_frame,
self.configRecWindow.video2Title.text(),
bottomLeftCornerOfText, font,fontScale,
fontColor,thickness, lineType)
else:
#only record till plot range. continue playing to get all data
if int(self.framePos) == end_framenum:
self.record_frame() #finish recording
self.playStatus = True
return
else:
self.merged_frame[:h, w:], r = self.image_resize(frame2, w, h,
inter = cv2.INTER_AREA)
# Write video1 title
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (int(0.0*w), int(0.05*h))
fontScale = 1.5
fontColor = (0,0,250)
thickness = 3
lineType = 1
cv2.putText(self.merged_frame,
self.configRecWindow.video1Title.text(),
bottomLeftCornerOfText, font,fontScale,
fontColor,thickness, lineType)
# Write time
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (int(1.55*w), int(0.1*h))
fontScale = 2
fontColor = (0,200,200)
thickness = 10
lineType = 2
logging.debug('%s, %s', self.frameTime.item(int(self.framePos-1)), bottomLeftCornerOfText)
text = 'Time: ' + "{0:.3f}".format(self.frameTime.item(int(self.framePos-1))) + ' s'
cv2.putText(self.merged_frame, text,
bottomLeftCornerOfText, font,fontScale,
fontColor,thickness, lineType)
#Draw scale bar
logging.debug('%s, %s', scaleFactor, "scalef")
pixLength = scaleFactor * self.pixelValue.value()
scalepos1 = (int(0.8*w), int(0.95*h))
scalepos2 = (int(scalepos1[0] + pixLength), scalepos1[1])
scalelabelpos = (int(scalepos1[0] + 0.5 * (pixLength - 100)),
scalepos1[1] + 10) #length of label is 51 pixels
cv2.line(self.merged_frame, scalepos1, scalepos2,
fontColor, thickness)
fontScale = 1
thickness = 5
color = (0,200,200)
text = str(int(self.lengthValue.value())) + ' ' + self.lengthUnit.currentText()
font = ImageFont.truetype("arial.ttf", 28, encoding="unic")
img_pil = Image.fromarray(self.merged_frame)
draw = ImageDraw.Draw(img_pil)
draw.text(scalelabelpos, text, font = font, fill = color)
self.merged_frame = np.array(img_pil)
logging.debug('%s, %s, %s', self.merged_frame.shape, w, h)
self.out.write(self.merged_frame)
cv2.namedWindow("Recording Preview", cv2.WINDOW_KEEPRATIO)
cv2.imshow("Recording Preview", self.merged_frame)
cv2.resizeWindow("Recording Preview", 800, 400)
# elif self.configRecWindow.fourRec.isChecked() == True:
# ret, frame3 = self.cap2.read()
def record_frame(self):
logging.debug("record_frame")
if self.recordStatus == True:
self.out.release()
self.recordBtn.setIcon(QIcon('images/record.png'))
self.recordBtn.setEnabled(False)
self.middleleftGroupBox.setEnabled(True)
self.bcGroupBox.setEnabled(True)
self.dftGroupBox.setEnabled(True)
self.threshGroupBox.setEnabled(True)
self.threshROIGroupBox.setEnabled(True)
self.dataGroupBox.setEnabled(True)
self.roiBtn.setEnabled(True)
self.analyzeVideo.setEnabled(True)
self.recordStatus = False
self.playStatus = False
else:
self.recordBtn.setIcon(QIcon('images/recording.png'))
self.middleleftGroupBox.setEnabled(False)
self.bcGroupBox.setEnabled(False)
self.dftGroupBox.setEnabled(False)
self.threshGroupBox.setEnabled(False)
self.threshROIGroupBox.setEnabled(False)
self.dataGroupBox.setEnabled(False)
self.roiBtn.setEnabled(False)
self.analyzeVideo.setEnabled(False)
self.recordStatus = True
self.playback()
## self.recordStatus = not self.recordStatus
#function to resize frame for recording
def image_resize(self, image, width = None, height = None, inter = cv2.INTER_AREA):
dim = None
(h, w) = image.shape[:2]
resized = np.zeros([height, width, 3], dtype = np.uint8)
if width is None and height is None:
return image, 0
if width is None:
r = height / float(h)
dim = (int(w * r), height)
elif height is None:
r = width / float(w)
dim = (width, int(h * r))
else:
rh = height / float(h)
rw = width / float(w)
if rh < rw:
r = rh
dim = (int(w * r), height)
else:
r = rw
dim = (width, int(h * r))
hdiff = int((height - dim[1])/2)
wdiff = int((width - dim[0])/2)
resized[hdiff:(hdiff + dim[1]),
wdiff:(wdiff + dim[0])] = cv2.resize(image, dim,
interpolation = inter)
logging.debug('%s, %s', dim, resized.shape)
return resized, r
def showRecWindow(self): #open recording configuration window
self.configRecWindow.showWindow(self.recordingPath)
def configureRecord(self):
if self.videoPath != "":
self.w = self.roiBound[2] - self.roiBound[0]
self.h = self.roiBound[3] - self.roiBound[1]
logging.debug('%s, %s, %s', "configurerecord", self.w, self.h)
self.codecChoices = {'DIVX': cv2.VideoWriter_fourcc(*'DIVX'),
'MJPG': cv2.VideoWriter_fourcc('M','J','P','G'),
'FFV1': cv2.VideoWriter_fourcc('F','F','V','1')}
fourcc = self.codecChoices.get(self.configRecWindow.codec.currentText())
self.recordingPath = self.configRecWindow.textbox.toPlainText()
if self.configRecWindow.fourRec.isChecked() == True:
i = 2
else:
i = 1
w = 2 * 512 #TODO: include this in gui (check above)
h = i * 512
size = (w, h)
## fps = self.frameRate
fps = self.configRecWindow.fps.value() #fixed playback fps
self.out = cv2.VideoWriter(self.recordingPath, fourcc, fps, size)
self.merged_frame = np.empty([h, w, 3], dtype = np.uint8)
logging.debug('%s, %s', self.recordingPath, self.merged_frame.shape)
self.recordBtn.setEnabled(True)
videofile2 = self.configRecWindow.videoTextbox.toPlainText() #second video
logging.debug(videofile2)
if videofile2 != "":
# self.cap2 = cv2.VideoCapture(videofile2)
self.cap2 = pims.Video(videofile2)
self.configRecWindow.close()
self.seekSlider.setValue(1) #reset to beginning
# self.showContours.setChecked(False) #uncheck show contours
self.clear_data() #clear data | [
"PyQt5.QtGui.QIcon",
"logging.debug",
"cv2.imshow",
"pims.Video",
"PIL.ImageDraw.Draw",
"numpy.array",
"cv2.resizeWindow",
"cv2.line",
"PIL.ImageFont.truetype",
"cv2.VideoWriter",
"numpy.empty",
"cv2.VideoWriter_fourcc",
"tkinter.messagebox.showinfo",
"cv2.putText",
"cv2.cvtColor",
"cv... | [((352, 380), 'logging.debug', 'logging.debug', (['"""recordvideo"""'], {}), "('recordvideo')\n", (365, 380), False, 'import logging\n'), ((9583, 9612), 'logging.debug', 'logging.debug', (['"""record_frame"""'], {}), "('record_frame')\n", (9596, 9612), False, 'import logging\n'), ((11078, 11122), 'numpy.zeros', 'np.zeros', (['[height, width, 3]'], {'dtype': 'np.uint8'}), '([height, width, 3], dtype=np.uint8)\n', (11086, 11122), True, 'import numpy as np\n'), ((11882, 11925), 'cv2.resize', 'cv2.resize', (['image', 'dim'], {'interpolation': 'inter'}), '(image, dim, interpolation=inter)\n', (11892, 11925), False, 'import cv2\n'), ((11991, 12034), 'logging.debug', 'logging.debug', (['"""%s, %s"""', 'dim', 'resized.shape'], {}), "('%s, %s', dim, resized.shape)\n", (12004, 12034), False, 'import logging\n'), ((13615, 13640), 'logging.debug', 'logging.debug', (['videofile2'], {}), '(videofile2)\n', (13628, 13640), False, 'import logging\n'), ((12412, 12474), 'logging.debug', 'logging.debug', (['"""%s, %s, %s"""', '"""configurerecord"""', 'self.w', 'self.h'], {}), "('%s, %s, %s', 'configurerecord', self.w, self.h)\n", (12425, 12474), False, 'import logging\n'), ((13265, 13319), 'cv2.VideoWriter', 'cv2.VideoWriter', (['self.recordingPath', 'fourcc', 'fps', 'size'], {}), '(self.recordingPath, fourcc, fps, size)\n', (13280, 13319), False, 'import cv2\n'), ((13355, 13390), 'numpy.empty', 'np.empty', (['[h, w, 3]'], {'dtype': 'np.uint8'}), '([h, w, 3], dtype=np.uint8)\n', (13363, 13390), True, 'import numpy as np\n'), ((13406, 13474), 'logging.debug', 'logging.debug', (['"""%s, %s"""', 'self.recordingPath', 'self.merged_frame.shape'], {}), "('%s, %s', self.recordingPath, self.merged_frame.shape)\n", (13419, 13474), False, 'import logging\n'), ((13752, 13774), 'pims.Video', 'pims.Video', (['videofile2'], {}), '(videofile2)\n', (13762, 13774), False, 'import pims\n'), ((7806, 7919), 'cv2.putText', 'cv2.putText', (['self.merged_frame', 'text', 'bottomLeftCornerOfText', 'font', 'fontScale', 'fontColor', 'thickness', 'lineType'], {}), '(self.merged_frame, text, bottomLeftCornerOfText, font,\n fontScale, fontColor, thickness, lineType)\n', (7817, 7919), False, 'import cv2\n'), ((8041, 8087), 'logging.debug', 'logging.debug', (['"""%s, %s"""', 'scaleFactor', '"""scalef"""'], {}), "('%s, %s', scaleFactor, 'scalef')\n", (8054, 8087), False, 'import logging\n'), ((8464, 8535), 'cv2.line', 'cv2.line', (['self.merged_frame', 'scalepos1', 'scalepos2', 'fontColor', 'thickness'], {}), '(self.merged_frame, scalepos1, scalepos2, fontColor, thickness)\n', (8472, 8535), False, 'import cv2\n'), ((8788, 8840), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""arial.ttf"""', '(28)'], {'encoding': '"""unic"""'}), "('arial.ttf', 28, encoding='unic')\n", (8806, 8840), False, 'from PIL import ImageFont, ImageDraw, Image\n'), ((8868, 8902), 'PIL.Image.fromarray', 'Image.fromarray', (['self.merged_frame'], {}), '(self.merged_frame)\n', (8883, 8902), False, 'from PIL import ImageFont, ImageDraw, Image\n'), ((8927, 8950), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img_pil'], {}), '(img_pil)\n', (8941, 8950), False, 'from PIL import ImageFont, ImageDraw, Image\n'), ((9063, 9080), 'numpy.array', 'np.array', (['img_pil'], {}), '(img_pil)\n', (9071, 9080), True, 'import numpy as np\n'), ((9104, 9162), 'logging.debug', 'logging.debug', (['"""%s, %s, %s"""', 'self.merged_frame.shape', 'w', 'h'], {}), "('%s, %s, %s', self.merged_frame.shape, w, h)\n", (9117, 9162), False, 'import logging\n'), ((9231, 9289), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Recording Preview"""', 'cv2.WINDOW_KEEPRATIO'], {}), "('Recording Preview', cv2.WINDOW_KEEPRATIO)\n", (9246, 9289), False, 'import cv2\n'), ((9307, 9357), 'cv2.imshow', 'cv2.imshow', (['"""Recording Preview"""', 'self.merged_frame'], {}), "('Recording Preview', self.merged_frame)\n", (9317, 9357), False, 'import cv2\n'), ((9375, 9422), 'cv2.resizeWindow', 'cv2.resizeWindow', (['"""Recording Preview"""', '(800)', '(400)'], {}), "('Recording Preview', 800, 400)\n", (9391, 9422), False, 'import cv2\n'), ((9720, 9746), 'PyQt5.QtGui.QIcon', 'QIcon', (['"""images/record.png"""'], {}), "('images/record.png')\n", (9725, 9746), False, 'from PyQt5.QtGui import QIcon\n'), ((10309, 10338), 'PyQt5.QtGui.QIcon', 'QIcon', (['"""images/recording.png"""'], {}), "('images/recording.png')\n", (10314, 10338), False, 'from PyQt5.QtGui import QIcon\n'), ((12517, 12548), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'DIVX'"], {}), "(*'DIVX')\n", (12539, 12548), False, 'import cv2\n'), ((12592, 12634), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (['"""M"""', '"""J"""', '"""P"""', '"""G"""'], {}), "('M', 'J', 'P', 'G')\n", (12614, 12634), False, 'import cv2\n'), ((12680, 12722), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (['"""F"""', '"""F"""', '"""V"""', '"""1"""'], {}), "('F', 'F', 'V', '1')\n", (12702, 12722), False, 'import cv2\n'), ((966, 1006), 'cv2.cvtColor', 'cv2.cvtColor', (['frame2', 'cv2.COLOR_GRAY2BGR'], {}), '(frame2, cv2.COLOR_GRAY2BGR)\n', (978, 1006), False, 'import cv2\n'), ((1823, 1827), 'tkinter.Tk', 'Tk', ([], {}), '()\n', (1825, 1827), False, 'from tkinter import messagebox, Tk\n'), ((1894, 1982), 'tkinter.messagebox.showinfo', 'messagebox.showinfo', (['"""Error!"""', '"""Check 2nd video file or force data file. Not found!"""'], {}), "('Error!',\n 'Check 2nd video file or force data file. Not found!')\n", (1913, 1982), False, 'from tkinter import messagebox, Tk\n'), ((2995, 3025), 'logging.debug', 'logging.debug', (['"""2nd video end"""'], {}), "('2nd video end')\n", (3008, 3025), False, 'import logging\n')] |
"""
A simple class to allow quick testing of GPIB programs without instruments.
All reads from an instrument return a semi-randomised number regardless of
the specific command that may have been sent prior to reading.
"""
import stuff
import time
## VisaIOError = False
"""
Old pyvisa calls.
"""
def get_instruments_list():
#specific to this setup
return ['GPIB0::16', 'GPIB0::22']
class Gpib(object):
def send_ifc(self):
return
class GpibInstrument(object):
def __init__(self, name):
self.name = name
self.data = stuff.DataGen()
def write(self, command):
time.sleep(0.1)
return
def read_values(self):
time.sleep(0.2)
return [self.data.next()]
class VisaIOError(object):
"""Exception class for VISA I/O errors.
Please note that all values for "error_code" are negative according to the
specification (VPP-4.3.2, observation 3.3.2) and the NI implementation.
"""
def __init__(self, error_code):
abbreviation, description = _completion_and_error_messages[error_code]
Error.__init__(self, abbreviation + ": " + description)
self.error_code = error_code
"""
New pyVisa calls, post 1.4
"""
class SpecificItem(object):
"""
All the dummy methods that a specific item (instrument or bus)is expected
to have
"""
def __init__(self, name):
self.name = name
self.data = stuff.DataGen()
def send_ifc(self):
return
def write(self,something):
return
def read_raw(self):
time.sleep(0.2)
return self.data.next()
def read(self):
time.sleep(0.2)
return self.data.next()
class ResourceManager(object):
"""
Newer pyVisa approach
"""
def list_resources(self):
return ['GPIB0::10', 'GPIB0::16']
def open_resource(self, specific_item):
specific_item = SpecificItem(specific_item)
return specific_item
| [
"stuff.DataGen",
"time.sleep"
] | [((596, 611), 'stuff.DataGen', 'stuff.DataGen', ([], {}), '()\n', (609, 611), False, 'import stuff\n'), ((666, 681), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (676, 681), False, 'import time\n'), ((749, 764), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (759, 764), False, 'import time\n'), ((1540, 1555), 'stuff.DataGen', 'stuff.DataGen', ([], {}), '()\n', (1553, 1555), False, 'import stuff\n'), ((1705, 1720), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (1715, 1720), False, 'import time\n'), ((1790, 1805), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (1800, 1805), False, 'import time\n')] |
import argparse
from core_extract_comments import *
from core_utils import *
def run(search, input_product_ids_filename):
product_ids = list()
if input_product_ids_filename is not None:
with open(input_product_ids_filename, 'r') as r:
for p in r.readlines():
pro_obj = p.strip('\n').split(' ')
#print(pro_obj)
product_ids.append(pro_obj)
logging.info('{} product ids were found.'.format(len(product_ids)))
reviews_counter = 0
for product_id in product_ids:
reviews = get_comments_with_product_id(product_id[1],product_id[0])
reviews_counter += len(reviews)
logging.info('{} reviews found so far.'.format(reviews_counter))
if reviews is not None:
persist_comment_to_disk(reviews)
return 0
else:
default_search = 'iPhone'
search = default_search if search is None else search
reviews = get_comments_based_on_keyword('https://www.amazon.com', search)
persist_comment_to_disk(reviews)
def get_script_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--search')
parser.add_argument('-i', '--input')
args = parser.parse_args()
input_product_ids_filename = args.input
search = args.search
return search, input_product_ids_filename
def main():
search, input_product_ids_filename = get_script_arguments()
run(search, input_product_ids_filename)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
main()
| [
"argparse.ArgumentParser"
] | [((1171, 1196), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1194, 1196), False, 'import argparse\n')] |
'''
Message Example
b'620901.02908, 3, 0.242, 0.606, 9.527, 4, 0.020, -0.006, 0.001, 5, -24.762,-223.451,-98.491, 81, 173.805, -3.304, 1.315'
'''
import time
import string
import socket, traceback
host="192.168.0.23" # ip address of
port=5555
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
while 1:
message, address = s.recvfrom(8192)
# print(f'{len(message)}')
# print(message)
# print(address)
message = message.decode("utf-8")
message = message.strip(" 'b ")
message = message.split(',')
try:
ndx = message.index(' 81')
orientation = message[ndx+1:ndx+4]
orientation = [float(x) for x in orientation]
print(f"orientation : {orientation}")
except ValueError:
# Not all message packets have orientation data
pass
| [
"socket.socket"
] | [((256, 304), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (269, 304), False, 'import socket, traceback\n')] |
import os
from .local_config import *
PROJECT_NAME = "Useful"
SERVER_HOST = 'http://127.0.0.1:8000'
# Secret key
SECRET_KEY = b"<KEY>"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
API_V1_STR = "/api/v1"
# Token 60 minutes * 24 hours * 7 days = 7 days
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7
# CORS
BACKEND_CORS_ORIGINS = [
"http://localhost",
"http://localhost:4200",
"http://localhost:3000",
"http://localhost:8080",
]
# Data Base via Docker
DATABASE_URI = f"""postgres://{os.environ.get("POSTGRES_USER")}:\
{os.environ.get("POSTGRES_PASSWORD")}@\
{os.environ.get("POSTGRES_HOST")}/\
{os.environ.get("POSTGRES_DB")}"""
USERS_OPEN_REGISTRATION = True
EMAILS_FROM_NAME = PROJECT_NAME
EMAIL_RESET_TOKEN_EXPIRE_HOURS = 48
EMAIL_TEMPLATES_DIR = "src/email-templates/build"
# Email
SMTP_TLS = os.environ.get("SMTP_TLS")
SMTP_PORT = os.environ.get("SMTP_PORT")
SMTP_HOST = os.environ.get("SMTP_HOST")
SMTP_USER = os.environ.get("SMTP_USER")
SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD")
EMAILS_FROM_EMAIL = os.environ.get("EMAILS_FROM_EMAIL")
EMAILS_ENABLED = SMTP_HOST and SMTP_PORT and EMAILS_FROM_EMAIL
EMAIL_TEST_USER = "<EMAIL>"
APPS_MODELS = [
"src.app.user.models",
"src.app.auth.models",
"src.app.board.models",
"src.app.blog.models",
"aerich.models",
]
| [
"os.path.abspath",
"os.environ.get"
] | [((845, 871), 'os.environ.get', 'os.environ.get', (['"""SMTP_TLS"""'], {}), "('SMTP_TLS')\n", (859, 871), False, 'import os\n'), ((884, 911), 'os.environ.get', 'os.environ.get', (['"""SMTP_PORT"""'], {}), "('SMTP_PORT')\n", (898, 911), False, 'import os\n'), ((924, 951), 'os.environ.get', 'os.environ.get', (['"""SMTP_HOST"""'], {}), "('SMTP_HOST')\n", (938, 951), False, 'import os\n'), ((964, 991), 'os.environ.get', 'os.environ.get', (['"""SMTP_USER"""'], {}), "('SMTP_USER')\n", (978, 991), False, 'import os\n'), ((1008, 1039), 'os.environ.get', 'os.environ.get', (['"""SMTP_PASSWORD"""'], {}), "('SMTP_PASSWORD')\n", (1022, 1039), False, 'import os\n'), ((1060, 1095), 'os.environ.get', 'os.environ.get', (['"""EMAILS_FROM_EMAIL"""'], {}), "('EMAILS_FROM_EMAIL')\n", (1074, 1095), False, 'import os\n'), ((181, 206), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (196, 206), False, 'import os\n'), ((527, 558), 'os.environ.get', 'os.environ.get', (['"""POSTGRES_USER"""'], {}), "('POSTGRES_USER')\n", (541, 558), False, 'import os\n'), ((579, 614), 'os.environ.get', 'os.environ.get', (['"""POSTGRES_PASSWORD"""'], {}), "('POSTGRES_PASSWORD')\n", (593, 614), False, 'import os\n'), ((619, 650), 'os.environ.get', 'os.environ.get', (['"""POSTGRES_HOST"""'], {}), "('POSTGRES_HOST')\n", (633, 650), False, 'import os\n'), ((655, 684), 'os.environ.get', 'os.environ.get', (['"""POSTGRES_DB"""'], {}), "('POSTGRES_DB')\n", (669, 684), False, 'import os\n')] |
#%%
# read full assignment
# think algo before implementing
# dont use a dict when you need a list
# assignment is still = and not ==
# dont use itertools when you can use np.roll
# check mathemathical functions if the parentheses are ok
# networkx is awesome
# %%
import os
import re
import numpy as np
try:
os.chdir(os.path.join(os.getcwd(), 'day 13'))
print(os.getcwd())
except:
pass
f = open('input.txt','r')
layers = {int(line.rstrip().split(': ')[0]):int(line.rstrip().split(': ')[1]) for line in f}
layers
for x in range(10000):
severity = 0
for pos in range(100):
if layers.get(pos,None):
# print(pos,layers[pos])
divisor = (layers[pos]-1)*2
if (pos+x+x)% divisor==0:
# print('hit',pos)
severity+=pos*layers[pos]+1
break
if severity== 0:
print('succes',x)
break
severity
# %%
| [
"os.getcwd"
] | [((364, 375), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (373, 375), False, 'import os\n'), ((333, 344), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (342, 344), False, 'import os\n')] |
from django.contrib import admin
from .models import Succession,Succession_Seasons,Succession_Casts,Succession_Season_Episodes
# Register your models here.
# admin.site.register(Succession) # The model Succession is abstract so it can't be registered with admin
admin.site.register(Succession_Seasons)
admin.site.register(Succession_Casts)
admin.site.register(Succession_Season_Episodes)
| [
"django.contrib.admin.site.register"
] | [((278, 317), 'django.contrib.admin.site.register', 'admin.site.register', (['Succession_Seasons'], {}), '(Succession_Seasons)\n', (297, 317), False, 'from django.contrib import admin\n'), ((318, 355), 'django.contrib.admin.site.register', 'admin.site.register', (['Succession_Casts'], {}), '(Succession_Casts)\n', (337, 355), False, 'from django.contrib import admin\n'), ((356, 403), 'django.contrib.admin.site.register', 'admin.site.register', (['Succession_Season_Episodes'], {}), '(Succession_Season_Episodes)\n', (375, 403), False, 'from django.contrib import admin\n')] |
#!/usr/bin/env python3
import sys, os
import arsdkparser
#===============================================================================
class Writer(object):
def __init__(self, fileobj):
self.fileobj = fileobj
def write(self, fmt, *args):
if args:
self.fileobj.write(fmt % (args))
else:
self.fileobj.write(fmt % ())
def capitalize_first(arstr):
nameParts = arstr.split('_')
name = ''
for part in nameParts:
if len(part) > 1:
name = name + part[0].upper() + part[1:]
elif len(part) == 1:
name = name + part[0].upper()
return name
def capitalize(arstr):
return "".join(x.capitalize() for x in arstr.split('_'))
def format_cmd_name(msg):
return capitalize_first(msg.name) if msg.cls is None else capitalize_first(msg.cls.name) + capitalize_first(msg.name)
def ftr_old_name(ftr):
FROM_NEW_NAME = { 'common': '', 'ardrone3':'ARDrone3',
'common_dbg':'commonDebug', 'jpsumo':'JumpingSumo',
'minidrone':'MiniDrone', 'skyctrl':'SkyController'}
if ftr.name in FROM_NEW_NAME:
return FROM_NEW_NAME[ftr.name]
else:
return capitalize(ftr.name)
#===============================================================================
CONSTS_FILENAME = "DeviceCtrlCompatConsts"
GENERATED_HEADER = "/** Generated, do not edit ! */"
DICT_CHANGED_NOTIF = "DeviceControllerNotificationsDictionaryChanged"
DEVICE_CONTROLLER_CLASS_NAME = "DeviceController"
DEFAULT_PROJECT_NAME = "common"
#===============================================================================
def const_decl(const_name):
return "extern NSString *const " + const_name + ";"
def const_impl(const_name):
return "NSString *const " + const_name + " = @\"" + const_name + "\";"
def const_name(feature, evt, param = None):
const_name = ""
if ftr_old_name(feature) != DEFAULT_PROJECT_NAME:
const_name += capitalize_first(ftr_old_name(feature))
const_name += DEVICE_CONTROLLER_CLASS_NAME + capitalize_first(format_cmd_name(evt)) + "Notification"
if param:
const_name += capitalize_first(param.name) + "Key"
return const_name
#===============================================================================
#===============================================================================
def gen_header_file(ctx, out):
out.write("%s\n\n", GENERATED_HEADER)
out.write("#import <Foundation/Foundation.h>\n\n")
out.write("%s\n\n", const_decl(DICT_CHANGED_NOTIF))
for featureId in sorted(ctx.featuresById.keys()):
feature = ctx.featuresById[featureId]
for evt in feature.evts:
out.write("%s\n", const_decl(const_name(feature, evt)))
for arg in evt.args:
out.write("%s\n", const_decl(const_name(feature, evt, arg)))
out.write("\n")
def gen_source_file(ctx, out):
out.write("%s\n\n", GENERATED_HEADER)
out.write("#import \"%s.h\"\n\n", CONSTS_FILENAME)
out.write("%s\n\n", const_impl(DICT_CHANGED_NOTIF))
for featureId in sorted(ctx.featuresById.keys()):
feature = ctx.featuresById[featureId]
for evt in feature.evts:
out.write("%s\n", const_impl(const_name(feature, evt)))
for arg in evt.args:
out.write("%s\n", const_impl(const_name(feature, evt, arg)))
out.write("\n")
#===============================================================================
#===============================================================================
def list_files(ctx, outdir, extra):
print(os.path.join(outdir, CONSTS_FILENAME + ".h"))
print(os.path.join(outdir, CONSTS_FILENAME + ".m"))
def generate_files(ctx, outdir, extra):
if not os.path.exists (outdir):
os.mkdirs (outdir)
# generate the header file
filepath = os.path.join(outdir, CONSTS_FILENAME + ".h")
with open(filepath, "w") as fileobj:
gen_header_file(ctx, Writer(fileobj))
# generate the source file
filepath = os.path.join(outdir, CONSTS_FILENAME + ".m")
with open(filepath, "w") as fileobj:
gen_source_file(ctx, Writer(fileobj))
print("Done generating ff4 compat consts files")
| [
"os.path.exists",
"os.path.join",
"os.mkdirs"
] | [((3917, 3961), 'os.path.join', 'os.path.join', (['outdir', "(CONSTS_FILENAME + '.h')"], {}), "(outdir, CONSTS_FILENAME + '.h')\n", (3929, 3961), False, 'import sys, os\n'), ((4096, 4140), 'os.path.join', 'os.path.join', (['outdir', "(CONSTS_FILENAME + '.m')"], {}), "(outdir, CONSTS_FILENAME + '.m')\n", (4108, 4140), False, 'import sys, os\n'), ((3664, 3708), 'os.path.join', 'os.path.join', (['outdir', "(CONSTS_FILENAME + '.h')"], {}), "(outdir, CONSTS_FILENAME + '.h')\n", (3676, 3708), False, 'import sys, os\n'), ((3720, 3764), 'os.path.join', 'os.path.join', (['outdir', "(CONSTS_FILENAME + '.m')"], {}), "(outdir, CONSTS_FILENAME + '.m')\n", (3732, 3764), False, 'import sys, os\n'), ((3818, 3840), 'os.path.exists', 'os.path.exists', (['outdir'], {}), '(outdir)\n', (3832, 3840), False, 'import sys, os\n'), ((3851, 3868), 'os.mkdirs', 'os.mkdirs', (['outdir'], {}), '(outdir)\n', (3860, 3868), False, 'import sys, os\n')] |
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehuman.org/
**Code Home Page:** http://code.google.com/p/makehuman/
**Authors:** <NAME>
**Copyright(c):** MakeHuman Team 2001-2009
**Licensing:** GPL3 (see also http://sites.google.com/site/makehumandocs/licensing)
**Coding Standards:** See http://sites.google.com/site/makehumandocs/developers-guide
Abstract
--------
Face bone definitions
"""
import mhx_globals as the
from mhx_globals import *
from mhx_rig import addPoseBone, writeDrivers
FaceJoints = [
('head-end', 'l', ((2.0, 'head'), (-1.0, 'neck'))),
('r-mouth', 'v', 2490),
('l-mouth', 'v', 8907),
('eyes', 'l', ((0.5, 'l-eye'), (0.5,'r-eye'))),
('gaze', 'o', ('eyes', (0,0,5))),
]
eyeOffs = (0,0,0.3)
FaceHeadsTails = [
('Jaw', 'mouth', 'jaw'),
('TongueBase', 'tongue-1', 'tongue-2'),
('TongueMid', 'tongue-2', 'tongue-3'),
('TongueTip', 'tongue-3', 'tongue-4'),
('Eye_R', 'l-eye', ('l-eye', eyeOffs)),
('EyeParent_R', 'l-eye', ('l-eye', eyeOffs)),
('DfmUpLid_R', 'l-eye', 'l-upperlid'),
('DfmLoLid_R', 'l-eye', 'l-lowerlid'),
('Eye_L', 'r-eye', ('r-eye', eyeOffs)),
('EyeParent_L', 'r-eye', ('r-eye', eyeOffs)),
('DfmUpLid_L', 'r-eye', 'r-upperlid'),
('DfmLoLid_L', 'r-eye', 'r-lowerlid'),
('Eyes', 'eyes', ('eyes', (0,0,1))),
('Gaze', 'gaze', ('gaze', (0,0,1))),
('GazeParent', 'neck2', 'head-end'),
]
FaceArmature = [
('Jaw', 0, 'Head', F_DEF, L_HEAD, NoBB),
('TongueBase', 0, 'Jaw', F_DEF, L_HEAD, NoBB),
('TongueMid', 0, 'TongueBase', F_DEF, L_HEAD, NoBB),
('TongueTip', 0, 'TongueMid', F_DEF, L_HEAD, NoBB),
('GazeParent', 0, Master, 0, L_HELP, NoBB),
('Gaze', pi, 'GazeParent', 0, L_HEAD, NoBB),
('EyeParent_R', 0, 'Head', 0, L_HELP, NoBB),
('EyeParent_L', 0, 'Head', 0, L_HELP, NoBB),
('Eye_R', 0, 'EyeParent_R', F_DEF, L_HEAD+L_DEF, NoBB),
('Eye_L', 0, 'EyeParent_L', F_DEF, L_HEAD+L_DEF, NoBB),
('Eyes', 0, 'Head', 0, L_HELP, NoBB),
('DfmUpLid_R', 0.279253, 'Head', F_DEF, L_DEF, NoBB),
('DfmLoLid_R', 0, 'Head', F_DEF, L_DEF, NoBB),
('DfmUpLid_L', -0.279253, 'Head', F_DEF, L_DEF, NoBB),
('DfmLoLid_L', 0, 'Head', F_DEF, L_DEF, NoBB),
]
#
# FaceControlPoses(fp):
#
def FaceControlPoses(fp):
addPoseBone(fp, 'Jaw', 'MHJaw', None, (1,1,1), (0,1,0), (1,1,1), (1,1,1), 0,
[('LimitRot', C_OW_LOCAL, 1, ['LimitRot', (-5*D,45*D, 0,0, -20*D,20*D), (1,1,1)])])
addPoseBone(fp, 'TongueBase', None, None, (1,1,1), (0,1,0), (1,0,1), (1,1,1), 0, [])
addPoseBone(fp, 'TongueMid', None, None, (1,1,1), (0,1,0), (1,0,1), (1,1,1), 0, [])
addPoseBone(fp, 'TongueTip', None, None, (1,1,1), (0,1,0), (1,0,1), (1,1,1), 0, [])
addPoseBone(fp, 'Gaze', 'MHGaze', None, (0,0,0), (1,1,1), (0,1,1), (1,1,1), 0, [])
addPoseBone(fp, 'GazeParent', None, None, (0,0,0), (1,1,1), (1,1,1), (1,1,1), 0,
[('CopyTrans', 0, 1, ['Head', 'Head', 0])])
addPoseBone(fp, 'DfmUpLid_R', None, None, (1,1,1), (0,1,1), (1,1,1), (1,1,1), 0, [])
addPoseBone(fp, 'DfmLoLid_R', None, None, (1,1,1), (0,1,1), (1,1,1), (1,1,1), 0, [])
addPoseBone(fp, 'DfmUpLid_L', None, None, (1,1,1), (0,1,1), (1,1,1), (1,1,1), 0, [])
addPoseBone(fp, 'DfmLoLid_L', None, None, (1,1,1), (0,1,1), (1,1,1), (1,1,1), 0, [])
addPoseBone(fp, 'Eyes', None, None, (1,1,1), (0,0,0), (1,1,1), (1,1,1), 0,
[('IK', 0, 1, ['IK', 'Gaze', 1, None, (True, False,False), 1.0])])
addPoseBone(fp, 'Eye_R', 'MHCircle025', None, (1,1,1), (0,0,0), (1,1,1), (1,1,1), 0, [])
addPoseBone(fp, 'Eye_L', 'MHCircle025', None, (1,1,1), (0,0,0), (1,1,1), (1,1,1), 0, [])
addPoseBone(fp, 'EyeParent_L', None, None, (1,1,1), (0,0,0), (1,1,1), (1,1,1), 0,
[('CopyRot', C_LOCAL, 1, ['Eyes', 'Eyes', (1,1,1), (0,0,0), True])])
addPoseBone(fp, 'EyeParent_R', None, None, (1,1,1), (0,0,0), (1,1,1), (1,1,1), 0,
[('CopyRot', C_LOCAL, 1, ['Eyes', 'Eyes', (1,1,1), (0,0,0), True])])
return
#
# FaceDeformDrivers(fp):
#
def FaceDeformDrivers(fp):
lidBones = [
('DfmUpLid_L', 'PUpLid_L', (0, 40*D)),
('DfmLoLid_L', 'PLoLid_L', (0, 20*D)),
('DfmUpLid_R', 'PUpLid_R', (0, 40*D)),
('DfmLoLid_R', 'PLoLid_R', (0, 20*D)),
]
drivers = []
for (driven, driver, coeff) in lidBones:
drivers.append( (driven, 'ROTQ', 'AVERAGE', None, 1, coeff,
[("var", 'TRANSFORMS', [('OBJECT', the.Human, driver, 'LOC_Z', C_LOC)])]) )
writeDrivers(fp, True, drivers)
return
#
# FacePropDrivers
# (Bone, Name, Props, Expr)
#
FacePropDrivers = []
SoftFacePropDrivers = [
('GazeParent', 'Head', ['GazeFollowsHead'], 'x1'),
]
| [
"mhx_rig.writeDrivers",
"mhx_rig.addPoseBone"
] | [((2763, 2953), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""Jaw"""', '"""MHJaw"""', 'None', '(1, 1, 1)', '(0, 1, 0)', '(1, 1, 1)', '(1, 1, 1)', '(0)', "[('LimitRot', C_OW_LOCAL, 1, ['LimitRot', (-5 * D, 45 * D, 0, 0, -20 * D, \n 20 * D), (1, 1, 1)])]"], {}), "(fp, 'Jaw', 'MHJaw', None, (1, 1, 1), (0, 1, 0), (1, 1, 1), (1, \n 1, 1), 0, [('LimitRot', C_OW_LOCAL, 1, ['LimitRot', (-5 * D, 45 * D, 0,\n 0, -20 * D, 20 * D), (1, 1, 1)])])\n", (2774, 2953), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((2941, 3037), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""TongueBase"""', 'None', 'None', '(1, 1, 1)', '(0, 1, 0)', '(1, 0, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'TongueBase', None, None, (1, 1, 1), (0, 1, 0), (1, 0, 1),\n (1, 1, 1), 0, [])\n", (2952, 3037), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3033, 3129), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""TongueMid"""', 'None', 'None', '(1, 1, 1)', '(0, 1, 0)', '(1, 0, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'TongueMid', None, None, (1, 1, 1), (0, 1, 0), (1, 0, 1), (\n 1, 1, 1), 0, [])\n", (3044, 3129), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3124, 3220), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""TongueTip"""', 'None', 'None', '(1, 1, 1)', '(0, 1, 0)', '(1, 0, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'TongueTip', None, None, (1, 1, 1), (0, 1, 0), (1, 0, 1), (\n 1, 1, 1), 0, [])\n", (3135, 3220), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3215, 3309), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""Gaze"""', '"""MHGaze"""', 'None', '(0, 0, 0)', '(1, 1, 1)', '(0, 1, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'Gaze', 'MHGaze', None, (0, 0, 0), (1, 1, 1), (0, 1, 1), (1,\n 1, 1), 0, [])\n", (3226, 3309), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3305, 3441), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""GazeParent"""', 'None', 'None', '(0, 0, 0)', '(1, 1, 1)', '(1, 1, 1)', '(1, 1, 1)', '(0)', "[('CopyTrans', 0, 1, ['Head', 'Head', 0])]"], {}), "(fp, 'GazeParent', None, None, (0, 0, 0), (1, 1, 1), (1, 1, 1),\n (1, 1, 1), 0, [('CopyTrans', 0, 1, ['Head', 'Head', 0])])\n", (3316, 3441), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3447, 3543), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""DfmUpLid_R"""', 'None', 'None', '(1, 1, 1)', '(0, 1, 1)', '(1, 1, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'DfmUpLid_R', None, None, (1, 1, 1), (0, 1, 1), (1, 1, 1),\n (1, 1, 1), 0, [])\n", (3458, 3543), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3539, 3635), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""DfmLoLid_R"""', 'None', 'None', '(1, 1, 1)', '(0, 1, 1)', '(1, 1, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'DfmLoLid_R', None, None, (1, 1, 1), (0, 1, 1), (1, 1, 1),\n (1, 1, 1), 0, [])\n", (3550, 3635), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3631, 3727), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""DfmUpLid_L"""', 'None', 'None', '(1, 1, 1)', '(0, 1, 1)', '(1, 1, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'DfmUpLid_L', None, None, (1, 1, 1), (0, 1, 1), (1, 1, 1),\n (1, 1, 1), 0, [])\n", (3642, 3727), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3723, 3819), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""DfmLoLid_L"""', 'None', 'None', '(1, 1, 1)', '(0, 1, 1)', '(1, 1, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'DfmLoLid_L', None, None, (1, 1, 1), (0, 1, 1), (1, 1, 1),\n (1, 1, 1), 0, [])\n", (3734, 3819), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3815, 3969), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""Eyes"""', 'None', 'None', '(1, 1, 1)', '(0, 0, 0)', '(1, 1, 1)', '(1, 1, 1)', '(0)', "[('IK', 0, 1, ['IK', 'Gaze', 1, None, (True, False, False), 1.0])]"], {}), "(fp, 'Eyes', None, None, (1, 1, 1), (0, 0, 0), (1, 1, 1), (1, 1,\n 1), 0, [('IK', 0, 1, ['IK', 'Gaze', 1, None, (True, False, False), 1.0])])\n", (3826, 3969), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((3973, 4074), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""Eye_R"""', '"""MHCircle025"""', 'None', '(1, 1, 1)', '(0, 0, 0)', '(1, 1, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'Eye_R', 'MHCircle025', None, (1, 1, 1), (0, 0, 0), (1, 1, \n 1), (1, 1, 1), 0, [])\n", (3984, 4074), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((4069, 4170), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""Eye_L"""', '"""MHCircle025"""', 'None', '(1, 1, 1)', '(0, 0, 0)', '(1, 1, 1)', '(1, 1, 1)', '(0)', '[]'], {}), "(fp, 'Eye_L', 'MHCircle025', None, (1, 1, 1), (0, 0, 0), (1, 1, \n 1), (1, 1, 1), 0, [])\n", (4080, 4170), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((4165, 4336), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""EyeParent_L"""', 'None', 'None', '(1, 1, 1)', '(0, 0, 0)', '(1, 1, 1)', '(1, 1, 1)', '(0)', "[('CopyRot', C_LOCAL, 1, ['Eyes', 'Eyes', (1, 1, 1), (0, 0, 0), True])]"], {}), "(fp, 'EyeParent_L', None, None, (1, 1, 1), (0, 0, 0), (1, 1, 1),\n (1, 1, 1), 0, [('CopyRot', C_LOCAL, 1, ['Eyes', 'Eyes', (1, 1, 1), (0, \n 0, 0), True])])\n", (4176, 4336), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((4333, 4504), 'mhx_rig.addPoseBone', 'addPoseBone', (['fp', '"""EyeParent_R"""', 'None', 'None', '(1, 1, 1)', '(0, 0, 0)', '(1, 1, 1)', '(1, 1, 1)', '(0)', "[('CopyRot', C_LOCAL, 1, ['Eyes', 'Eyes', (1, 1, 1), (0, 0, 0), True])]"], {}), "(fp, 'EyeParent_R', None, None, (1, 1, 1), (0, 0, 0), (1, 1, 1),\n (1, 1, 1), 0, [('CopyRot', C_LOCAL, 1, ['Eyes', 'Eyes', (1, 1, 1), (0, \n 0, 0), True])])\n", (4344, 4504), False, 'from mhx_rig import addPoseBone, writeDrivers\n'), ((5005, 5036), 'mhx_rig.writeDrivers', 'writeDrivers', (['fp', '(True)', 'drivers'], {}), '(fp, True, drivers)\n', (5017, 5036), False, 'from mhx_rig import addPoseBone, writeDrivers\n')] |
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('home.jpg')
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist( [hsv], [0, 1], None, [180, 256], [0, 180, 0, 256] )
plt.imshow(hist,interpolation = 'nearest')
plt.show()
# in numpy
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('home.jpg')
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
hist, xbins, ybins = np.histogram2d(h.ravel(),s.ravel(),[180,256],[[0,180],[0,256]])
| [
"matplotlib.pyplot.imshow",
"cv2.calcHist",
"cv2.cvtColor",
"cv2.imread",
"matplotlib.pyplot.show"
] | [((74, 96), 'cv2.imread', 'cv2.imread', (['"""home.jpg"""'], {}), "('home.jpg')\n", (84, 96), False, 'import cv2\n'), ((103, 139), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (115, 139), False, 'import cv2\n'), ((146, 209), 'cv2.calcHist', 'cv2.calcHist', (['[hsv]', '[0, 1]', 'None', '[180, 256]', '[0, 180, 0, 256]'], {}), '([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])\n', (158, 209), False, 'import cv2\n'), ((213, 254), 'matplotlib.pyplot.imshow', 'plt.imshow', (['hist'], {'interpolation': '"""nearest"""'}), "(hist, interpolation='nearest')\n", (223, 254), True, 'from matplotlib import pyplot as plt\n'), ((256, 266), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (264, 266), True, 'from matplotlib import pyplot as plt\n'), ((353, 375), 'cv2.imread', 'cv2.imread', (['"""home.jpg"""'], {}), "('home.jpg')\n", (363, 375), False, 'import cv2\n'), ((382, 418), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (394, 418), False, 'import cv2\n')] |
import network2
import logging
import numpy as np
logging.basicConfig(level=logging.DEBUG)
# read in the data
# logging.info("READING IN DATA...")
# for reading in normal dataset
# training, validation, test = network2.load_data_wrapper("data/mnist.pkl.gz")
### I WILL ADD AND COMMENT OUT SECTIONS OF CODE BASED ON WHICH TASKS I AM TRYING TO EXECUTE FOR ANY GIVEN ITERATION ###
# Task 1 - Experimenting with BPNN
## Task 1.1 - Effect of cost function with default network structure [784, 10]
### - Quadratic cost function with sigmoid activation function; plot convergence
# logging.info("TASK 1.1 A...")
# logging.info("INITIALIZING NETWORK...")
#
# f = open("task1_1a.csv", 'w')
#
# for _ in range(3):
# network = network2.Network([784, 10], cost=network2.QuadraticCost)
#
# logging.info("TRAINING NETWORK...")
# evaluation_cost, evaluation_accuracy, training_cost, training_accuracy = network.SGD(training, 100, 100, 0.9, evaluation_data=validation)
#
# logging.info("EVALUATING RESULTS...")
# results = network.accuracy(test)
#
# logging.info("WRITING RESULTS...")
# buff = "Iteration {}\n".format(_)
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
# f.write(buff)
# buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
# f.write(buff)
# buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
# f.write(buff)
# buff = "test_acc,{}\n\n".format(results)
# f.write(buff)
# f.flush()
# f.close()
### - Cross entropy cost function with sigmoid activation function; plot convergence
# logging.info("TASK 1.1 B...")
# logging.info("INITIALIZING NETWORK...")
#
# f = open("task1_1b.csv", 'w')
#
# for _ in range(3):
# network = network2.Network([784, 10], cost=network2.CrossEntropyCost)
#
# logging.info("TRAINING NETWORK...")
# evaluation_cost, evaluation_accuracy, training_cost, training_accuracy = network.SGD(training, 100, 100, 0.9, evaluation_data=validation)
#
# logging.info("EVALUATING RESULTS...")
# results = network.accuracy(test)
#
# logging.info("WRITING RESULTS...")
# buff = "Iteration {}\n".format(_)
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
# f.write(buff)
# buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
# f.write(buff)
# buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
# f.write(buff)
# buff = "test_acc,{}\n\n".format(results)
# f.write(buff)
# f.flush()
#
# f.close()
### - Log-likelihood cost function with softmax activation function; plot convergence
# logging.info("TASK 1.1 C...")
# logging.info("INITIALIZING NETWORK...")
#
# f = open("task1_1c.csv", 'w')
#
# for _ in range(3):
# network = network2.Network([784, 10], cost=network2.LogLikelihoodCost, output_activation=network2.SoftmaxActivation)
#
# logging.info("TRAINING NETWORK...")
# evaluation_cost, evaluation_accuracy, training_cost, training_accuracy = network.SGD(training, 100, 100, 0.9, evaluation_data=validation)
#
# logging.info("EVALUATING RESULTS...")
# results = network.accuracy(test)
#
# logging.info("WRITING RESULTS...")
# buff = "Iteration {}\n".format(_)
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
# f.write(buff)
# buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
# f.write(buff)
# buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
# f.write(buff)
# buff = "test_acc,{}\n\n".format(results)
# f.write(buff)
# f.flush()
#
# f.close()
## Task 1.2 - Effect of regularization with default network structure [784, 10], no hidden layers, and cross entropy
### - Add L2 normalization on the cost function; plot convergence
# logging.info("TASK 1.2 A...")
# logging.info("INITIALIZING NETWORK...")
#
# f = open("task1_2a.csv", 'w')
#
# for l2 in [0.01, 0.1, 1, 10]:
# network = network2.Network([784, 10], cost=network2.CrossEntropyCost)
#
# logging.info("TRAINING NETWORK...")
# evaluation_cost, evaluation_accuracy, training_cost, training_accuracy = network.SGD(training, 100, 100, 0.9, lmbda=l2, evaluation_data=validation)
#
# logging.info("EVALUATING RESULTS...")
# results = network.accuracy(test)
#
# logging.info("WRITING RESULTS...")
# buff = str(l2) + '\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
# f.write(buff)
# buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
# f.write(buff)
# buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
# f.write(buff)
# buff = "test_acc,{}".format(results) + '\n\n'
# f.write(buff)
# f.flush()
#
# f.close()
### - Add L1 normalization on the cost function; plot convergence
# logging.info("TASK 1.2 B...")
# logging.info("INITIALIZING NETWORK...")
#
# f = open("task1_2b.csv", 'w')
#
# for l1 in [0.01, 0.1, 1, 10]:
# network = network2.Network([784, 10], cost=network2.CrossEntropyCost)
#
# logging.info("TRAINING NETWORK...")
# evaluation_cost, evaluation_accuracy, training_cost, training_accuracy = network.SGD(training, 100, 100, 0.9, gmma=l1, evaluation_data=validation)
#
# logging.info("EVALUATING RESULTS...")
# results = network.accuracy(test)
#
# logging.info("WRITING RESULTS...")
# buff = str(l1) + '\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
# f.write(buff)
# buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
# f.write(buff)
# buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
# f.write(buff)
# buff = "test_acc,{}".format(results) + '\n\n'
# f.write(buff)
# f.flush()
#
# f.close()
### - L1 normalization; expanded training set with affine transforms; plot convergence
# read in the data
logging.info("READING IN DATA...")
# for reading in normal dataset
training, validation, test = network2.load_data_wrapper("data/mnist_expanded.pkl.gz")
# logging.info("TASK 1.2 C...")
# logging.info("INITIALIZING NETWORK...")
#
# f = open("task1_2c.csv", 'w')
#
# for _ in range(3):
# network = network2.Network([784, 10], cost=network2.CrossEntropyCost)
#
# logging.info("TRAINING NETWORK...")
# evaluation_cost, evaluation_accuracy, training_cost, training_accuracy = network.SGD(training, 100, 100, 0.9, gmma=1, evaluation_data=validation)
#
# logging.info("EVALUATING RESULTS...")
# results = network.accuracy(test)
#
# logging.info("WRITING RESULTS...")
# buff = "Iteration {}\n".format(_)
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
# f.write(buff)
# buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
# f.write(buff)
# buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
# f.write(buff)
# buff = "test_acc,{}".format(results) + '\n\n'
# f.write(buff)
# f.flush()
#
# f.close()
## Task 1.3 - Effect of hidden layers; cross entropy; L1 normalization; expanded training set
### - Add one hidden layer with 30 nodes [784, 30, 10]; plot convergence
logging.info("TASK 1.3 A...")
logging.info("INITIALIZING NETWORK...")
f = open("task1_3a.csv", 'w')
for _ in range(3):
network = network2.Network([784, 30, 10], cost=network2.CrossEntropyCost)
logging.info("TRAINING NETWORK...")
evaluation_cost, evaluation_accuracy, training_cost, training_accuracy, _ = network.SGD(training, 100, 100, 0.9, gmma=1, evaluation_data=validation)
logging.info("EVALUATING RESULTS...")
results = network.accuracy(test)
logging.info("WRITING RESULTS...")
buff = "Iteration {}\n".format(_)
f.write(buff)
buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
f.write(buff)
buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
f.write(buff)
buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
f.write(buff)
buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
f.write(buff)
buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
f.write(buff)
buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
f.write(buff)
buff = "test_acc,{}".format(results) + '\n\n'
f.write(buff)
f.flush()
f.close()
### - Add two hidden layers with 30 nodes [784, 30, 30, 10]; plot convergence; plot change rate of each weight in hidden layers
# logging.info("TASK 1.3 B...")
# logging.info("INITIALIZING NETWORK...")
#
# f = open("task1_3b.csv", 'w')
#
# for _ in range(3):
# network = network2.Network([784, 30, 30, 10], cost=network2.CrossEntropyCost)
#
# logging.info("TRAINING NETWORK...")
# evaluation_cost, evaluation_accuracy, training_cost, training_accuracy, weight_change = network.SGD(training, 100, 100, 0.9, gmma=1, evaluation_data=validation)
#
# logging.info("EVALUATING RESULTS...")
# results = network.accuracy(test)
#
# weight_np = np.array(weight_change)
#
# logging.info("WRITING RESULTS...")
# buff = "Iteration {}\n".format(_)
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_cost," + ','.join([str(i) for i in evaluation_cost]) + '\n'
# f.write(buff)
# buff = "train_cost," + ','.join([str(i) for i in training_cost]) + '\n\n'
# f.write(buff)
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# buff = "eval_acc," + ','.join([str(i) for i in evaluation_accuracy]) + '\n'
# f.write(buff)
# buff = "train_acc," + ','.join([str(i) for i in training_accuracy]) + '\n\n'
# f.write(buff)
# buff = "test_acc,{}".format(results) + '\n\n'
# f.write(buff)
# f.flush()
#
# buff = "epoch," + ','.join([str(i) for i in range(100)]) + '\n'
# f.write(buff)
# for i in range(weight_np.shape[1]):
# buff = "w_change_{},".format(i) + ','.join([str(j) for j in weight_change[:][i]]) + '\n'
# f.write(buff)
#
# f.flush()
#
# f.close()
### - (692) L1 normalization; expanded training set; dropout (several %-ages); plot convergence
| [
"logging.basicConfig",
"network2.load_data_wrapper",
"logging.info",
"network2.Network"
] | [((51, 91), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (70, 91), False, 'import logging\n'), ((7511, 7545), 'logging.info', 'logging.info', (['"""READING IN DATA..."""'], {}), "('READING IN DATA...')\n", (7523, 7545), False, 'import logging\n'), ((7608, 7664), 'network2.load_data_wrapper', 'network2.load_data_wrapper', (['"""data/mnist_expanded.pkl.gz"""'], {}), "('data/mnist_expanded.pkl.gz')\n", (7634, 7664), False, 'import network2\n'), ((9113, 9142), 'logging.info', 'logging.info', (['"""TASK 1.3 A..."""'], {}), "('TASK 1.3 A...')\n", (9125, 9142), False, 'import logging\n'), ((9143, 9182), 'logging.info', 'logging.info', (['"""INITIALIZING NETWORK..."""'], {}), "('INITIALIZING NETWORK...')\n", (9155, 9182), False, 'import logging\n'), ((9248, 9311), 'network2.Network', 'network2.Network', (['[784, 30, 10]'], {'cost': 'network2.CrossEntropyCost'}), '([784, 30, 10], cost=network2.CrossEntropyCost)\n', (9264, 9311), False, 'import network2\n'), ((9317, 9352), 'logging.info', 'logging.info', (['"""TRAINING NETWORK..."""'], {}), "('TRAINING NETWORK...')\n", (9329, 9352), False, 'import logging\n'), ((9511, 9548), 'logging.info', 'logging.info', (['"""EVALUATING RESULTS..."""'], {}), "('EVALUATING RESULTS...')\n", (9523, 9548), False, 'import logging\n'), ((9591, 9625), 'logging.info', 'logging.info', (['"""WRITING RESULTS..."""'], {}), "('WRITING RESULTS...')\n", (9603, 9625), False, 'import logging\n')] |
from abc import ABC, abstractmethod
import collections
import statistics
import numpy as np
import sklearn.metrics
import torch
class Evaluator(ABC):
"""Class to evaluate model outputs and report the result.
"""
def __init__(self):
self.reset()
@abstractmethod
def add_predictions(self, predictions, targets):
pass
@abstractmethod
def get_report(self):
pass
@abstractmethod
def reset(self):
pass
class MulticlassClassificationEvaluator(Evaluator):
def add_predictions(self, predictions, targets):
""" Evaluate a batch of predictions.
Args:
predictions: the model output tensor. Shape (N, num_class)
targets: the golden truths. Shape (N,)
"""
assert len(predictions) == len(targets)
assert len(targets.shape) == 1
# top-1 accuracy
_, indices = torch.topk(predictions, 1)
correct = indices.view(-1).eq(targets)
correct_num = int(correct.long().sum(0))
self.top1_correct_num += correct_num
# top-5 accuracy
k = min(5, predictions.shape[1])
_, indices = torch.topk(predictions, k)
correct = indices == targets.view(-1, 1).long().expand(-1, k)
self.top5_correct_num += int(correct.long().sum())
# Average precision
target_vec = torch.zeros_like(predictions, dtype=torch.uint8)
for i, t in enumerate(targets):
target_vec[i, t] = 1
ap = sklearn.metrics.average_precision_score(target_vec.view(-1).cpu().numpy(), predictions.view(-1).cpu().numpy(), average='macro')
self.ap += ap * len(predictions)
self.total_num += len(predictions)
def get_report(self):
return {'top1_accuracy': float(self.top1_correct_num) / self.total_num if self.total_num else 0.0,
'top5_accuracy': float(self.top5_correct_num) / self.total_num if self.total_num else 0.0,
'average_precision': self.ap / self.total_num if self.total_num else 0.0}
def reset(self):
self.top1_correct_num = 0
self.top5_correct_num = 0
self.ap = 0
self.total_num = 0
class MultilabelClassificationEvaluator(Evaluator):
def add_predictions(self, predictions, targets):
""" Evaluate a batch of predictions.
Args:
predictions: the model output tensor. Shape (N, num_class)
targets: the golden truths. Shape (N, num_class)
"""
assert len(predictions) == len(targets)
targets = targets.to(torch.uint8)
num = torch.mul(predictions > 0.5, targets).long().sum(1) # shape (N,)
den = torch.add(predictions > 0.5, targets).ge(1).long().sum(1) # shape (N,)
den[den == 0] = 1 # To avoid zero-division. If den==0, num should be zero as well.
self.correct_num += torch.sum(num.to(torch.float32) / den.to(torch.float32))
ap = sklearn.metrics.average_precision_score(targets.view(-1).cpu().numpy(), predictions.view(-1).cpu().numpy(), average='macro')
self.ap += ap * len(predictions)
self.total_num += len(predictions)
def get_report(self):
return {'accuracy_50': float(self.correct_num) / self.total_num if self.total_num else 0.0,
'average_precision': self.ap / self.total_num if self.total_num else 0.0}
def reset(self):
self.correct_num = 0
self.ap = 0
self.total_num = 0
class ObjectDetectionSingleIOUEvaluator(Evaluator):
def __init__(self, iou):
super(ObjectDetectionSingleIOUEvaluator, self).__init__()
self.iou = iou
def add_predictions(self, predictions, targets):
""" Evaluate list of image with object detection results using single IOU evaluation.
Args:
predictions: list of predictions [[[label_idx, probability, L, T, R, B], ...], [...], ...]
targets: list of image targets [[[label_idx, L, T, R, B], ...], ...]
"""
assert len(predictions) == len(targets)
eval_predictions = collections.defaultdict(list)
eval_ground_truths = collections.defaultdict(dict)
for img_idx, prediction in enumerate(predictions):
for bbox in prediction:
label = int(bbox[0])
eval_predictions[label].append([img_idx, float(bbox[1]), float(bbox[2]), float(bbox[3]), float(bbox[4]), float(bbox[5])])
for img_idx, target in enumerate(targets):
for bbox in target:
label = int(bbox[0])
if img_idx not in eval_ground_truths[label]:
eval_ground_truths[label][img_idx] = []
eval_ground_truths[label][img_idx].append([float(bbox[1]), float(bbox[2]), float(bbox[3]), float(bbox[4])])
class_indices = set(list(eval_predictions.keys()) + list(eval_ground_truths.keys()))
for class_index in class_indices:
is_correct, probabilities = self._evaluate_predictions(eval_ground_truths[class_index], eval_predictions[class_index], self.iou)
true_num = sum([len(l) for l in eval_ground_truths[class_index].values()])
self.is_correct[class_index].extend(is_correct)
self.probabilities[class_index].extend(probabilities)
self.true_num[class_index] += true_num
def _calculate_area(self, rect):
w = rect[2] - rect[0]+1e-5
h = rect[3] - rect[1]+1e-5
return float(w * h) if w > 0 and h > 0 else 0.0
def _calculate_iou(self, rect0, rect1):
rect_intersect = [max(rect0[0], rect1[0]),
max(rect0[1], rect1[1]),
min(rect0[2], rect1[2]),
min(rect0[3], rect1[3])]
area_intersect = self._calculate_area(rect_intersect)
return area_intersect / (self._calculate_area(rect0) + self._calculate_area(rect1) - area_intersect)
def _is_true_positive(self, prediction, ground_truth, already_detected, iou_threshold):
image_id = prediction[0]
prediction_rect = prediction[2:6]
if image_id not in ground_truth:
return False, already_detected
ious = np.array([self._calculate_iou(prediction_rect, g) for g in ground_truth[image_id]])
best_bb = np.argmax(ious)
best_iou = ious[best_bb]
if best_iou < iou_threshold or (image_id, best_bb) in already_detected:
return False, already_detected
already_detected.add((image_id, best_bb))
return True, already_detected
def _evaluate_predictions(self, ground_truths, predictions, iou_threshold):
""" Evaluate the correctness of the given predictions.
Args:
ground_truths: List of ground truths for the class. {image_id: [[left, top, right, bottom], [...]], ...}
predictions: List of predictions for the class. [[image_id, probability, left, top, right, bottom], [...], ...]
iou_threshold: Minimum IOU hreshold to be considered as a same bounding box.
"""
# Sort the predictions by the probability
sorted_predictions = sorted(predictions, key=lambda x: -x[1])
already_detected = set()
is_correct = []
for prediction in sorted_predictions:
correct, already_detected = self._is_true_positive(prediction, ground_truths, already_detected,
iou_threshold)
is_correct.append(correct)
is_correct = np.array(is_correct)
probabilities = np.array([p[1] for p in sorted_predictions])
return is_correct, probabilities
def _calculate_average_precision(self, is_correct, probabilities, true_num):
if true_num == 0:
return 0
if not is_correct or not any(is_correct):
return 0
recall = float(np.sum(is_correct)) / true_num
return sklearn.metrics.average_precision_score(is_correct, probabilities) * recall
def get_report(self):
all_aps = []
for class_index in self.is_correct:
ap = self._calculate_average_precision(self.is_correct[class_index],
self.probabilities[class_index],
self.true_num[class_index])
all_aps.append(ap)
mean_ap = statistics.mean(all_aps) if all_aps else 0
return {'mAP_{}'.format(int(self.iou*100)): mean_ap}
def reset(self):
self.is_correct = collections.defaultdict(list)
self.probabilities = collections.defaultdict(list)
self.true_num = collections.defaultdict(int)
class ObjectDetectionEvaluator(Evaluator):
def __init__(self, iou_values=[0.3, 0.5, 0.75, 0.9]):
self.evaluators = [ObjectDetectionSingleIOUEvaluator(iou) for iou in iou_values]
super(ObjectDetectionEvaluator, self).__init__()
def add_predictions(self, predictions, targets):
for evaluator in self.evaluators:
evaluator.add_predictions(predictions, targets)
def get_report(self):
report = {}
for evaluator in self.evaluators:
report.update(evaluator.get_report())
return report
def reset(self):
for evaluator in self.evaluators:
evaluator.reset()
| [
"statistics.mean",
"torch.mul",
"torch.topk",
"numpy.argmax",
"numpy.array",
"numpy.sum",
"torch.add",
"collections.defaultdict",
"torch.zeros_like"
] | [((904, 930), 'torch.topk', 'torch.topk', (['predictions', '(1)'], {}), '(predictions, 1)\n', (914, 930), False, 'import torch\n'), ((1160, 1186), 'torch.topk', 'torch.topk', (['predictions', 'k'], {}), '(predictions, k)\n', (1170, 1186), False, 'import torch\n'), ((1366, 1414), 'torch.zeros_like', 'torch.zeros_like', (['predictions'], {'dtype': 'torch.uint8'}), '(predictions, dtype=torch.uint8)\n', (1382, 1414), False, 'import torch\n'), ((4069, 4098), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (4092, 4098), False, 'import collections\n'), ((4128, 4157), 'collections.defaultdict', 'collections.defaultdict', (['dict'], {}), '(dict)\n', (4151, 4157), False, 'import collections\n'), ((6290, 6305), 'numpy.argmax', 'np.argmax', (['ious'], {}), '(ious)\n', (6299, 6305), True, 'import numpy as np\n'), ((7523, 7543), 'numpy.array', 'np.array', (['is_correct'], {}), '(is_correct)\n', (7531, 7543), True, 'import numpy as np\n'), ((7568, 7612), 'numpy.array', 'np.array', (['[p[1] for p in sorted_predictions]'], {}), '([p[1] for p in sorted_predictions])\n', (7576, 7612), True, 'import numpy as np\n'), ((8538, 8567), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (8561, 8567), False, 'import collections\n'), ((8597, 8626), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (8620, 8626), False, 'import collections\n'), ((8651, 8679), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (8674, 8679), False, 'import collections\n'), ((8386, 8410), 'statistics.mean', 'statistics.mean', (['all_aps'], {}), '(all_aps)\n', (8401, 8410), False, 'import statistics\n'), ((7878, 7896), 'numpy.sum', 'np.sum', (['is_correct'], {}), '(is_correct)\n', (7884, 7896), True, 'import numpy as np\n'), ((2595, 2632), 'torch.mul', 'torch.mul', (['(predictions > 0.5)', 'targets'], {}), '(predictions > 0.5, targets)\n', (2604, 2632), False, 'import torch\n'), ((2675, 2712), 'torch.add', 'torch.add', (['(predictions > 0.5)', 'targets'], {}), '(predictions > 0.5, targets)\n', (2684, 2712), False, 'import torch\n')] |
import unittest
from lmctl.cli.format import TableFormat, Table, Column
class DummyTable(Table):
columns = [
Column('name', header='Name'),
Column('status', header='Status', accessor=lambda x: 'OK' if x.get('status', None) in ['Excellent', 'Good'] else 'Unhealthy'),
]
class DummyTableNoHeaders(Table):
columns = [
Column('name'),
Column('status', accessor=lambda x: 'OK' if x.get('status', None) in ['Excellent', 'Good'] else 'Unhealthy'),
]
EXPECTED_LIST = '''\
| Name | Status |
|--------+-----------|
| A | OK |
| B | Unhealthy |
| C | OK |
| D | Unhealthy |'''
EXPECTED_ELEMENT = '''\
| Name | Status |
|--------+----------|
| A | OK |'''
EXPECTED_ELEMENT_NO_HEADER_SET = '''\
| name | status |
|--------+----------|
| A | OK |'''
class TestTableFormat(unittest.TestCase):
def test_convert_list(self):
test_list = [
{'name': 'A', 'status': 'Good'},
{'name': 'B', 'status': 'Bad'},
{'name': 'C', 'status': 'Excellent'},
{'name': 'D'}
]
output = TableFormat(table=DummyTable()).convert_list(test_list)
self.assertEqual(output, EXPECTED_LIST)
def test_convert_element(self):
element = {'name': 'A', 'status': 'Good'}
output = TableFormat(table=DummyTable()).convert_element(element)
self.assertEqual(output, EXPECTED_ELEMENT)
def test_table_with_columns_with_no_headers(self):
element = {'name': 'A', 'status': 'Good'}
output = TableFormat(table=DummyTable()).convert_element(element)
self.assertEqual(output, EXPECTED_ELEMENT)
| [
"lmctl.cli.format.Column"
] | [((122, 151), 'lmctl.cli.format.Column', 'Column', (['"""name"""'], {'header': '"""Name"""'}), "('name', header='Name')\n", (128, 151), False, 'from lmctl.cli.format import TableFormat, Table, Column\n'), ((353, 367), 'lmctl.cli.format.Column', 'Column', (['"""name"""'], {}), "('name')\n", (359, 367), False, 'from lmctl.cli.format import TableFormat, Table, Column\n')] |
import logging
import azure.functions as func
import numpy as np
import json
import requests
from os import path
def readjson_from_file(filename):
try:
fp = open(filename, "r")
except:
logging.info(f"WARNING: cant open file {filename} ")
return {}
try:
object = json.load(fp)
except json.JSONDecodeError:
logging.info(f"WARNING: not a json file {filename}")
object = {}
fp.close()
return object
def post_to_create_reference_data(nice_ml_url):
# API url
url = nice_ml_url + "/createreferencedata"
logging.info(f'post url is {url}')
payload={}
payload['Create'] = True
logging.info('payload added')
# Content type must be included in the header
header = {"content-type": "application/json"}
logging.info('sending post request')
# Performs a POST on the specified url to get response
response = requests.post(url, data=json.dumps(
payload), headers=header, verify=False)
logging.info('recived response')
logging.info(response)
# convert response to json format
response_json = response.json()
logging.info(f"status response {response_json['status']}")
# print(response_json)
def main(event: func.EventGridEvent):
result = json.dumps({
'id': event.id,
'data': event.get_json(),
'topic': event.topic,
'subject': event.subject,
'event_type': event.event_type,
})
logging.info('Python EventGrid trigger processed an event: %s', result)
try :
config_json = readjson_from_file("/home/site/wwwroot/config.json")
nice_ml_url = config_json['NICE_ML_APP_SERVICE_URL']
except KeyError :
logging.info('could not load config file properly keys not found exiting function')
exit(0)
post_to_create_reference_data(nice_ml_url)
logging.info('done with all processing exiting function')
| [
"json.load",
"json.dumps",
"logging.info"
] | [((617, 651), 'logging.info', 'logging.info', (['f"""post url is {url}"""'], {}), "(f'post url is {url}')\n", (629, 651), False, 'import logging\n'), ((711, 740), 'logging.info', 'logging.info', (['"""payload added"""'], {}), "('payload added')\n", (723, 740), False, 'import logging\n'), ((848, 884), 'logging.info', 'logging.info', (['"""sending post request"""'], {}), "('sending post request')\n", (860, 884), False, 'import logging\n'), ((1053, 1086), 'logging.info', 'logging.info', (['"""recived response"""'], {}), "('recived response')\n", (1065, 1086), False, 'import logging\n'), ((1092, 1114), 'logging.info', 'logging.info', (['response'], {}), '(response)\n', (1104, 1114), False, 'import logging\n'), ((1196, 1254), 'logging.info', 'logging.info', (['f"""status response {response_json[\'status\']}"""'], {}), '(f"status response {response_json[\'status\']}")\n', (1208, 1254), False, 'import logging\n'), ((1536, 1607), 'logging.info', 'logging.info', (['"""Python EventGrid trigger processed an event: %s"""', 'result'], {}), "('Python EventGrid trigger processed an event: %s', result)\n", (1548, 1607), False, 'import logging\n'), ((1956, 2013), 'logging.info', 'logging.info', (['"""done with all processing exiting function"""'], {}), "('done with all processing exiting function')\n", (1968, 2013), False, 'import logging\n'), ((327, 340), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (336, 340), False, 'import json\n'), ((227, 279), 'logging.info', 'logging.info', (['f"""WARNING: cant open file {filename} """'], {}), "(f'WARNING: cant open file {filename} ')\n", (239, 279), False, 'import logging\n'), ((384, 436), 'logging.info', 'logging.info', (['f"""WARNING: not a json file {filename}"""'], {}), "(f'WARNING: not a json file {filename}')\n", (396, 436), False, 'import logging\n'), ((985, 1004), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (995, 1004), False, 'import json\n'), ((1790, 1878), 'logging.info', 'logging.info', (['"""could not load config file properly keys not found exiting function"""'], {}), "(\n 'could not load config file properly keys not found exiting function')\n", (1802, 1878), False, 'import logging\n')] |
import django
print(django.get_version())
print(f"boa {111 * 6}")
print(f"{6*6}")
input = input("Hey abuser, enter some stuff!\n")
cmp = 1 > 0
print(type(cmp))
print(input)
try:
int(asdf)
except Exception:
print("Oh no, it failed!")
while False:
print("False!")
listeL = [1,2,3,45,6,4,3,6,8,6,3,3]
setS = set(listeL)
listeL.append(33333)
print(listeL)
print("Set S:")
print(setSf)
# This is a comment?
"""asdkjf ölsaföl
sadkf jsaöld jfösa
askdf jöldsakf j
Multi Line Comment!
"""
| [
"django.get_version"
] | [((20, 40), 'django.get_version', 'django.get_version', ([], {}), '()\n', (38, 40), False, 'import django\n')] |
from start import client
from modules import codeforces,delete,notes,hastebin,pin,pm,user,spam,rextester
white=[]
from telethon import TelegramClient,events
import logging
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
level=logging.WARNING)
client.start().run_until_disconnected()
| [
"logging.basicConfig",
"start.client.start"
] | [((172, 286), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s"""', 'level': 'logging.WARNING'}), "(format=\n '[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.\n WARNING)\n", (191, 286), False, 'import logging\n'), ((300, 314), 'start.client.start', 'client.start', ([], {}), '()\n', (312, 314), False, 'from start import client\n')] |
# Let’s make a map! Using Geopandas, Pandas and Matplotlib to make a Choropleth map
# https://towardsdatascience.com/lets-make-a-map-using-geopandas-pandas-and-matplotlib-to-make-a-chloropleth-map-dddc31c1983d
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import Point, Polygon
import adjustText as aT
import pycountry as pc
import numpy as np
countries=gpd.read_file('/Users/vivekparashar/OneDrive/OneDrive-GitHub/Challenges-and-Competitions/30DayMapChallenge/Maps/natural_earth_vector/110m_cultural/ne_110m_admin_0_countries.shp')
countries=countries.to_crs(crs='epsg:4326')
countries.head()
countries.plot(alpha=0.4, color='lightgrey', edgecolor = "dimgrey",)
df = pd.read_csv('/Users/vivekparashar/OneDrive/OneDrive-GitHub/Challenges-and-Competitions/30DayMapChallenge/Data/country_x_language.csv', header=0) # encoding='unicode_escape',
# add country code
def do_fuzzy_search(country):
try:
result = pc.countries.search_fuzzy(country)
except Exception:
return np.nan
else:
return result[0].alpha_3
df["country_code"] = df["Country"].apply(lambda country: do_fuzzy_search(country))
# join the geodataframe with the cleaned up csv dataframe
merged = countries.set_index('SOV_A3').join(df.set_index('country_code'))
merged.head()
merged[merged.Language=='Spanish'].plot()
# Map time!
fig, ax = plt.subplots(figsize=(20.5,10))
#ax.grid(True)
ax.grid(color='darkgoldenrod', linestyle='-.', linewidth=0.50)
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
#fig.suptitle('Indian Cities: Population', fontsize=50)
plt.title(label='Predominantly Spanish Speaking Countries!',
fontdict={'fontsize': 24, #rcParams['axes.titlesize'],
'fontweight': 'bold',
'color': 'firebrick', #rcParams['axes.titlecolor'],
'verticalalignment': 'baseline',})
#'horizontalalignment': 'left'})
#ax.set(title='Indian Cities with Population > 100k')
#ax.xaxis.set_ticks([])
#ax.yaxis.set_ticks([])
#ax.xaxis.set_visible(False)
#ax.yaxis.set_visible(False)
countries.plot(ax=ax, alpha=0.4, color='grey', edgecolor = "dimgrey",)
merged[merged.Language=='Spanish'].plot(ax=ax, alpha=0.7, color='firebrick')
#merged[merged.Language=='Arabic'].plot(ax=ax, alpha=0.7, color='yellow')
plt.text(35, -85, '#30DayMapChallenge - Day 23 - Boundaries \nhttps://twitter.com/vivekparasharr/ \nData from http://geocountries.com', fontsize=18)
#za=terrain[terrain.featurecla=='Desert'][terrain.scalerank<=3]
#za.name[za.name=='RUB<NAME>']='<NAME>'
za=merged[merged.Language=='Spanish']
za["center"] = za["geometry"].representative_point() # centroid
za_points = za.copy()
za_points.set_geometry("center", inplace = True)
texts = []
for x, y, label in zip(za_points.geometry.x, za_points.geometry.y, za_points["Country"].str.title()):
texts.append(plt.text(x, y, label, fontsize = 18, )) #color='saddlebrown'))
aT.adjust_text(texts, force_points=0.3, force_text=0.8, expand_points=(1,1), expand_text=(1,1),
arrowprops=dict(arrowstyle="-", color='grey', lw=0.5))
| [
"matplotlib.pyplot.text",
"pycountry.countries.search_fuzzy",
"geopandas.read_file",
"pandas.read_csv",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplots"
] | [((413, 601), 'geopandas.read_file', 'gpd.read_file', (['"""/Users/vivekparashar/OneDrive/OneDrive-GitHub/Challenges-and-Competitions/30DayMapChallenge/Maps/natural_earth_vector/110m_cultural/ne_110m_admin_0_countries.shp"""'], {}), "(\n '/Users/vivekparashar/OneDrive/OneDrive-GitHub/Challenges-and-Competitions/30DayMapChallenge/Maps/natural_earth_vector/110m_cultural/ne_110m_admin_0_countries.shp'\n )\n", (426, 601), True, 'import geopandas as gpd\n'), ((729, 883), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/vivekparashar/OneDrive/OneDrive-GitHub/Challenges-and-Competitions/30DayMapChallenge/Data/country_x_language.csv"""'], {'header': '(0)'}), "(\n '/Users/vivekparashar/OneDrive/OneDrive-GitHub/Challenges-and-Competitions/30DayMapChallenge/Data/country_x_language.csv'\n , header=0)\n", (740, 883), True, 'import pandas as pd\n'), ((1398, 1430), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(20.5, 10)'}), '(figsize=(20.5, 10))\n', (1410, 1430), True, 'import matplotlib.pyplot as plt\n'), ((1620, 1793), 'matplotlib.pyplot.title', 'plt.title', ([], {'label': '"""Predominantly Spanish Speaking Countries!"""', 'fontdict': "{'fontsize': 24, 'fontweight': 'bold', 'color': 'firebrick',\n 'verticalalignment': 'baseline'}"}), "(label='Predominantly Spanish Speaking Countries!', fontdict={\n 'fontsize': 24, 'fontweight': 'bold', 'color': 'firebrick',\n 'verticalalignment': 'baseline'})\n", (1629, 1793), True, 'import matplotlib.pyplot as plt\n'), ((2268, 2427), 'matplotlib.pyplot.text', 'plt.text', (['(35)', '(-85)', '"""#30DayMapChallenge - Day 23 - Boundaries \nhttps://twitter.com/vivekparasharr/ \nData from http://geocountries.com"""'], {'fontsize': '(18)'}), '(35, -85,\n """#30DayMapChallenge - Day 23 - Boundaries \nhttps://twitter.com/vivekparasharr/ \nData from http://geocountries.com"""\n , fontsize=18)\n', (2276, 2427), True, 'import matplotlib.pyplot as plt\n'), ((979, 1013), 'pycountry.countries.search_fuzzy', 'pc.countries.search_fuzzy', (['country'], {}), '(country)\n', (1004, 1013), True, 'import pycountry as pc\n'), ((2832, 2866), 'matplotlib.pyplot.text', 'plt.text', (['x', 'y', 'label'], {'fontsize': '(18)'}), '(x, y, label, fontsize=18)\n', (2840, 2866), True, 'import matplotlib.pyplot as plt\n')] |
"""
This module exrtacts features from the data, saves the feauters
from all measurements to global results file and creates
one file for every sensor with all measurements.
:copyright: (c) 2022 by <NAME>, Hochschule-Bonn-Rhein-Sieg
:license: see LICENSE for more details.
"""
from pyexpat import features
import pandas as pd
from scipy.signal import chirp, find_peaks, peak_widths
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
######################################################################################################################
## this class creates objects for every sensor and stores all measurment for this sensor ##
class Sensor:
"""This is for creating objects for every sensor and stores the data from all measurements
in this object. Sensor names are picked up in properties. One DataFrame for every sensor is created
Args:
properties (dictionary): properties is a dictionary with all parameters for evaluating the data
"""
def __init__(self, properties):
"""
constructor method
"""
df_dict = {} # dicht with df for each sensor, one for all measurments
self.properties = properties
for sensor in self.properties['sensors']:
df_dict[sensor] = pd.DataFrame()
self.df_dict = df_dict
def add_item(self,df, name): # append data from measurement in global sensor df
"""This function sorts the passed DataFrame into those of the sensor
object and names the respective columns with the name of the measurement.
Args:
df (pandas.DataFrame): The columns of the DataFrame should match those in the properties.json file.
name (string): Measurement name
"""
sensors_to_delelte = []
for sensor in self.df_dict:
try:
self.df_dict[sensor][name] = df[sensor]
except:
print('no data for {0} in {1}'.format(sensor, name))
sensors_to_delelte.append(sensor)
# deleting dataframes for sensors not included in measurements
for del_sensor in sensors_to_delelte:
del self.df_dict[del_sensor]
print('deleting {} from results'.format(del_sensor))
def save_items(self, path): # save one file for every sensor with all measurements
"""This function saves all DataFrames contained in the sensor object, one file
is saved per sensor. A folder "results" is created in the root folder where
the files are stored.
Args:
path (string): Path to the folder in which the measurement folders are stored
"""
for sensor in self.df_dict:
name = sensor + '_gesamt'
save_df(self.df_dict[sensor], path, name)
######################################################################################################################
## this class creates plots with all sensors for every measurement ##
class Plot:
"""
This class creates plot objects. For each one, an image with all sensors of a measurement is created.
Args:
name (string): Name of the measurement
size (int): Number of sensors to be plotted
properties (dictionary): properties is a dictionary with all parameters for evaluating the data
"""
def __init__(self,name, size, properties):
"""
constructor method
"""
self.plot_properties = properties['plot_properties']['measurement_plot']
self.properties = properties
self.fig, self.axs = plt.subplots(size, sharex=True, dpi=self.plot_properties['dpi'], figsize=self.plot_properties['size'])
self.name = name
self.i = 0
def add_subplot(self, sensor, df_corr, peak_properties, results_half, results_full, peaks):
"""This function assigns a subplot for the corresponding sensor to the plot object.
Args:
sensor (string): Name of the sensor
df_corr (pandas.DataFrame): Dataframe with prepared data from measurement
peak_properties (dictionary): peak_properties is a dictionary with data about extracted peaks
results_half (numpy.array): Array with from measurement extracted feauters for the half peak
results_full (numpy.array): Array with from measurement extracted feauters for the full peak
peaks (numpy.array): Array with from measurement extracted feauters for detected peaks
"""
self.axs[self.i].plot(df_corr[sensor], color=self.properties['sensors'][sensor]['color'])
## print peaks in plot
if peaks.size != 0:
self.axs[self.i].plot(df_corr.index[peaks], df_corr[sensor][df_corr.index[peaks]], "x")
self.axs[self.i].vlines(x=df_corr.index[peaks][0], ymin=df_corr[sensor][df_corr.index[peaks][0]] - peak_properties["prominences"],
ymax=df_corr[sensor][df_corr.index[peaks][0]], color="C1")
self.axs[self.i].hlines(y=peak_properties["width_heights"], xmin=df_corr.index[int(peak_properties["left_ips"])],
xmax=df_corr.index[int(peak_properties["right_ips"])], color="C1")
self.axs[self.i].hlines(y=results_full[1], xmin=df_corr.index[int(results_full[2])],
xmax=df_corr.index[int(results_full[3])],
color="C2")
self.axs[self.i].hlines(y=results_half[1], xmin=df_corr.index[int(results_half[2])],
xmax=df_corr.index[int(results_half[3])],
color="C2")
label = sensor + ' [V]'
self.axs[self.i].set_ylabel(label, rotation=0, loc='top', fontsize = self.plot_properties['label_size'])
self.axs[self.i].tick_params(axis='y', labelsize= self.plot_properties['font_size'])
self.axs[self.i].grid()
try:
self.axs[self.i].set_yticks(np.arange(0,np.max(df_corr[sensor]),round(np.max(df_corr[sensor])/3, 2)))
except:
self.axs[self.i].set_yticks(np.arange(0,5,5/3))
self.i = self.i +1
def show_fig(self, path):
"""This function saves the created plot object in the folder "results\\plots\\single_measurements".
Args:
path (string): Path to the folder in which the measurement folders are stored
"""
self.axs[-1].set_xlabel("time [s]" , fontsize = self.plot_properties['label_size'])
plt.xticks(fontsize=self.plot_properties['font_size'])
self.axs[-1].get_shared_x_axes().join(*self.axs)
self.fig.tight_layout()
path = path + '\\results\\plots\\single_measurements'
Path(path).mkdir(parents=True, exist_ok=True)
path = path + '\\' + self.name + '.jpeg'
self.fig.tight_layout()
# plt.show()
self.fig.savefig(path)
plt.close(self.fig)
def width_clip(x, threshold):
"""This function extracts the feauter "width clip", which calculates the length at which a signal is too large for the measuring range.
Args:
x (list): Time series from which the feature is to be extracted
threshold (float): Value from which an exceeding of the measuring range is
Return:
width clip (float): Returns the length in which the signal is greater than the measuring range.
"""
x = x.tolist()
flag = False
list_peaks = []
start = 0
end = 0
for i in range(len(x)):
if flag == False and x[i] > threshold:
flag = True
start = i
elif flag == True and x[i] < threshold:
flag = False
end = i
list_peaks.append(end-start)
if len(list_peaks) == 0 or np.max(list_peaks) <= 4:
return 0
else:
return np.max(list_peaks)
def running_mean(x):
"""This function calculates a moving average of a time series of data. Here N is the sample interval over which the smoothing takes place.
Args:
x (list): Time series to be smoothed
Returns:
smoothed data (list): Returns the smoothed data
"""
N = 20 # über wie viele Werte wird geglättet
return np.convolve(x, np.ones((N,))/N)[(N-1):]
def get_slope(x,t):
"""This function calculates the slope of a peak from exceeding the threshold to the maximum.
Args:
x (list): x Values from which the slope is to be determined
t (list): time section from which the slope is to be determined
Returns:
slope (float): slope of the section
"""
end = 0
flag = False
for i in range(len(x)-1):
if flag == False:
if x[i+1] > x[i]:
pass
else:
end = i
flag = True
slope = (x[end]-x[0])/(t[end]-t[0])
return slope
def evaluate_sensor(df, sensor, threshold):
"""This function calculates the slope of a peak from exceeding the threshold to the maximum.
Args:
df (pandas.DataFrame): DateFrame with all sensors from one measurement
sensor (string): sensor to evaluate
threshold (float): Value from which an exceeding of the measuring range is determined
Return:
peaks (numpy.array): extracted peaks
properties (dictionary): properties of measurement
results_half (numpy.array): extracted feauters from peak half
results_full (numpy.array): extracted feauters from peak full
result_dict (dictionary): dictionary with extracted feauters
"""
peaks, peak_properties = find_peaks(df[sensor], prominence=0, width=1, distance=20000, height=threshold)
results_half = peak_widths(df[sensor], peaks, rel_height=0.5)
results_full = peak_widths(df[sensor], peaks, rel_height=0.99)
try:
df_peak = pd.DataFrame(df[sensor].iloc[int(results_full[2]):int(results_full[3])])
except:
pass
# functions for feature extraction
def get_peak():
return df.index[int(peaks[0])]
def get_start():
return df.index[int(results_full[2])]
def get_stop():
return df.index[int(results_full[3])]
def get_width():
return df.index[int(results_full[3])] - df.index[int(results_full[2])]
def get_width_half():
return df.index[int(results_half[3])] - df.index[int(results_half[2])]
def get_height():
return df[sensor][df.index[int(peaks[0])]]
def get_integral():
return np.trapz(df_peak[sensor] ,x=df_peak.index)
def get_slope_2():
return get_slope(df_peak[sensor].tolist(), df_peak.index.tolist())
def get_width_clip():
return width_clip(df[sensor], 4.9)
def get_width_heigth():
return (df.index[int(results_full[3])] - df.index[int(results_full[2])])/(df[sensor][df.index[int(peaks[0])]])
values = [get_peak, get_start, get_stop,get_width, get_width_half, get_height, get_integral, get_slope_2, get_width_clip, get_width_heigth]
features = "peak[s] start[s] stop[s] width[s] width_half[s] height intetegral[Vs] slope[V/s] width_clip[s] width_heigth[s/V]".split()
#build the json result for this measurement
result_dict = {}
for feature, value in zip(features,values):
name = "{0}_{1} {2}".format(sensor, feature[:feature.find('[')], feature[feature.find('['):])
try:
result_dict[name] = value()
except:
result_dict[name] = 0
return (peaks, peak_properties, results_half, results_full, result_dict)
def cut_peakarea(df, sensor_to_cut,sensors_norm):
"""This function cuts out the sigbificant range of a measurement.
A part from the maximum of the "sensor_to_cut" - "place_before_peak"
to the maximum of the "sensor_to_cut" + "place_after_peak" is cut out.
In addition, columns with the smoothed data of the corresponding sensors are added.
Args:
df (pandas.DataFrame): DateFrame with all sensors from one measurement
sensor_to_cut (string): Sensor with which the time period is to be determined
sensors_norm (list): List of sensors to be normalised
Returns:
df_corr (pandas.DataFrame): DataFrame with significant range of measurement with smoothed values
"""
place_before_peak = 1000
place_after_peak = 10000
step = 0.00001
len_signal = step * (place_after_peak + place_before_peak)
# cuts the important part of the file, adds running mean col and ammount of signals
try:
# error = 1/0
index_sensor_to_cut_max = df[sensor_to_cut].idxmax(axis = 0)
if index_sensor_to_cut_max <= place_before_peak:
index_sensor_to_cut_max = place_before_peak
elif index_sensor_to_cut_max >= (len(df.index)- place_after_peak):
index_sensor_to_cut_max = len(df.index)- place_after_peak
except:
print('no maximum found')
index_sensor_to_cut_max = len(df.index)//2
df_corr = df.iloc[index_sensor_to_cut_max - place_before_peak:index_sensor_to_cut_max + place_after_peak].apply(np.abs)
df_corr['time [s]'] = np.arange(0, 0.11, 0.00001)
for sensor in sensors_norm:
df_corr[[sensor + '_nm']] = df_corr[[sensor]].apply(running_mean)
df_corr.set_index('time [s]', inplace=True)
return df_corr
## saving the result df ##
def save_df(df, path, name):
"""This function saves a DataFrame to csv in the results folder.
Param:
df (pandas.DataFrame): DataFrame to save
path (string): path to root directory of data
name (string): Name under which the file is to be saved
"""
path = path + '\\results'
Path(path).mkdir(parents=True, exist_ok=True)
path = path + '\\' + name + '.csv'
print(name + 'saved as ' + path)
df.to_csv(path, sep=';', decimal=',', index = True)
def read_file(path,decimal,name, path_out, object_raw, properties):
"""This function reads files of the raw data. The data is evaluated
and features are extracted. A plot is created for each file.
The function returns a dict with all extracted features
Args:
path (string): path to measurements file
decimal (string): decimal of stored data
name (string): name of the measurement
path_out (string): path to save the figures
object_raw (object): figure object for plotting measurement
properties (dictionary): properties from properties json
Returns:
dict_result (dictionary): dictionary with all extracted feauters for a measurement
"""
sensors = properties['sensors']
path = path + path[path.rfind('\\'):] + '.txt'
dict_result = {}
df_measurement = pd.read_csv(path, delimiter='\t', decimal=decimal, dtype=float)
df_corr = cut_peakarea(df_measurement, properties['sensor_to_cut'], properties['sensors_norm'])
object_raw.add_item(df_corr, name) # adding data from measurement to df for each sensor including all measurements
fig = Plot(name,len(df_corr.columns), properties)
df_corr = df_corr.reindex(sorted(df_corr.columns), axis=1)
for this_sensor in df_corr.columns:
peaks, peak_properties, results_half, results_full, this_dict_result = evaluate_sensor(df_corr, this_sensor, sensors[this_sensor]['threshold'])
dict_result.update(this_dict_result)
fig.add_subplot(this_sensor, df_corr, peak_properties, results_half, results_full, peaks)
fig.show_fig(path_out)
return dict_result
| [
"numpy.trapz",
"numpy.ones",
"pandas.read_csv",
"matplotlib.pyplot.xticks",
"pathlib.Path",
"numpy.max",
"matplotlib.pyplot.close",
"scipy.signal.peak_widths",
"scipy.signal.find_peaks",
"pandas.DataFrame",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((9673, 9752), 'scipy.signal.find_peaks', 'find_peaks', (['df[sensor]'], {'prominence': '(0)', 'width': '(1)', 'distance': '(20000)', 'height': 'threshold'}), '(df[sensor], prominence=0, width=1, distance=20000, height=threshold)\n', (9683, 9752), False, 'from scipy.signal import chirp, find_peaks, peak_widths\n'), ((9772, 9818), 'scipy.signal.peak_widths', 'peak_widths', (['df[sensor]', 'peaks'], {'rel_height': '(0.5)'}), '(df[sensor], peaks, rel_height=0.5)\n', (9783, 9818), False, 'from scipy.signal import chirp, find_peaks, peak_widths\n'), ((9838, 9885), 'scipy.signal.peak_widths', 'peak_widths', (['df[sensor]', 'peaks'], {'rel_height': '(0.99)'}), '(df[sensor], peaks, rel_height=0.99)\n', (9849, 9885), False, 'from scipy.signal import chirp, find_peaks, peak_widths\n'), ((13172, 13197), 'numpy.arange', 'np.arange', (['(0)', '(0.11)', '(1e-05)'], {}), '(0, 0.11, 1e-05)\n', (13181, 13197), True, 'import numpy as np\n'), ((14769, 14832), 'pandas.read_csv', 'pd.read_csv', (['path'], {'delimiter': '"""\t"""', 'decimal': 'decimal', 'dtype': 'float'}), "(path, delimiter='\\t', decimal=decimal, dtype=float)\n", (14780, 14832), True, 'import pandas as pd\n'), ((3601, 3708), 'matplotlib.pyplot.subplots', 'plt.subplots', (['size'], {'sharex': '(True)', 'dpi': "self.plot_properties['dpi']", 'figsize': "self.plot_properties['size']"}), "(size, sharex=True, dpi=self.plot_properties['dpi'], figsize=\n self.plot_properties['size'])\n", (3613, 3708), True, 'import matplotlib.pyplot as plt\n'), ((6463, 6517), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': "self.plot_properties['font_size']"}), "(fontsize=self.plot_properties['font_size'])\n", (6473, 6517), True, 'import matplotlib.pyplot as plt\n'), ((6873, 6892), 'matplotlib.pyplot.close', 'plt.close', (['self.fig'], {}), '(self.fig)\n', (6882, 6892), True, 'import matplotlib.pyplot as plt\n'), ((7825, 7843), 'numpy.max', 'np.max', (['list_peaks'], {}), '(list_peaks)\n', (7831, 7843), True, 'import numpy as np\n'), ((10559, 10601), 'numpy.trapz', 'np.trapz', (['df_peak[sensor]'], {'x': 'df_peak.index'}), '(df_peak[sensor], x=df_peak.index)\n', (10567, 10601), True, 'import numpy as np\n'), ((1296, 1310), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1308, 1310), True, 'import pandas as pd\n'), ((7758, 7776), 'numpy.max', 'np.max', (['list_peaks'], {}), '(list_peaks)\n', (7764, 7776), True, 'import numpy as np\n'), ((13741, 13751), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (13745, 13751), False, 'from pathlib import Path\n'), ((6677, 6687), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (6681, 6687), False, 'from pathlib import Path\n'), ((8247, 8260), 'numpy.ones', 'np.ones', (['(N,)'], {}), '((N,))\n', (8254, 8260), True, 'import numpy as np\n'), ((5942, 5965), 'numpy.max', 'np.max', (['df_corr[sensor]'], {}), '(df_corr[sensor])\n', (5948, 5965), True, 'import numpy as np\n'), ((6060, 6082), 'numpy.arange', 'np.arange', (['(0)', '(5)', '(5 / 3)'], {}), '(0, 5, 5 / 3)\n', (6069, 6082), True, 'import numpy as np\n'), ((5972, 5995), 'numpy.max', 'np.max', (['df_corr[sensor]'], {}), '(df_corr[sensor])\n', (5978, 5995), True, 'import numpy as np\n')] |
from __future__ import annotations
import json
import os
import shutil
import subprocess
import tempfile
import uuid
from abc import ABC, abstractmethod
from typing import Any, Union
from urllib.error import HTTPError
from urllib.request import urlopen, urlretrieve
import warnings
import meerkat as mk
import pandas as pd
import yaml
from meerkat.tools.lazy_loader import LazyLoader
from dcbench.common.modeling import Model
from dcbench.config import config
storage = LazyLoader("google.cloud.storage")
torch = LazyLoader("torch")
def _upload_dir_to_gcs(local_path: str, gcs_path: str, bucket: "storage.Bucket"):
assert os.path.isdir(local_path)
with tempfile.TemporaryDirectory() as tmp_dir:
tarball_path = os.path.join(tmp_dir, "run.tar.gz")
subprocess.call(
[
"tar",
"-czf",
tarball_path,
"-C",
local_path,
".",
]
)
remote_path = gcs_path + ".tar.gz"
blob = bucket.blob(remote_path)
blob.upload_from_filename(tarball_path)
def _url_exists(url: str):
try:
response = urlopen(url)
status_code = response.getcode()
return status_code == 200
except HTTPError:
return False
def urlretrieve_with_retry(url: str, filename: str, max_retries: int=5):
"""
Retry urlretrieve() if it fails.
"""
for idx in range(max_retries):
try:
urlretrieve(url, filename)
return
except Exception as e:
warnings.warn(
f"Failed to download {url}: {e}\n"
f"Retrying {idx}/{max_retries}..."
)
continue
raise RuntimeError(f"Failed to download {url} after {max_retries} retries.")
class Artifact(ABC):
"""A pointer to a unit of data (e.g. a CSV file) that is stored locally on
disk and/or in a remote GCS bucket.
In DCBench, each artifact is identified by a unique artifact ID. The only
state that the :class:`Artifact` object must maintain is this ID (``self.id``).
The object does not hold the actual data in memory, making it
lightweight.
:class:`Artifact` is an abstract base class. Different types of artifacts (e.g. a
CSV file vs. a PyTorch model) have corresponding subclasses of :class:`Artifact`
(e.g. :class:`CSVArtifact`, :class:`ModelArtifact`).
.. Tip::
The vast majority of users should not call the :class:`Artifact`
constructor directly. Instead, they should either create a new artifact by
calling :meth:`from_data` or load an existing artifact from a YAML file.
The class provides utilities for accessing and managing a unit of data:
- Synchronizing the local and remote copies of a unit of data:
:meth:`upload`, :meth:`download`
- Loading the data into memory: :meth:`load`
- Creating new artifacts from in-memory data: :meth:`from_data`
- Serializing the pointer artifact so it can be shared:
:meth:`to_yaml`, :meth:`from_yaml`
Args:
artifact_id (str): The unique artifact ID.
Attributes:
id (str): The unique artifact ID.
"""
@classmethod
def from_data(
cls, data: Union[mk.DataPanel, pd.DataFrame, Model], artifact_id: str = None
) -> Artifact:
"""Create a new artifact object from raw data and save the artifact to
disk in the local directory specified in the config file at
``config.local_dir``.
.. tip::
When called on the abstract base class :class:`Artifact`, this method will
infer which artifact subclass to use. If you know exactly which artifact
class you'd like to use (e.g. :class:`DataPanelArtifact`), you should call
this classmethod on that subclass.
Args:
data (Union[mk.DataPanel, pd.DataFrame, Model]): The raw data that will be
saved to disk.
artifact_id (str, optional): . Defaults to None, in which case a UUID will
be generated and used.
Returns:
Artifact: A new artifact pointing to the :arg:`data` that was saved to disk.
"""
if artifact_id is None:
artifact_id = uuid.uuid4().hex
# TODO ():At some point we should probably enforce that ids are unique
if cls is Artifact:
# if called on base class, infer which class to use
if isinstance(data, mk.DataPanel):
cls = DataPanelArtifact
elif isinstance(data, pd.DataFrame):
cls = CSVArtifact
elif isinstance(data, Model):
cls = ModelArtifact
elif isinstance(data, (list, dict)):
cls = YAMLArtifact
else:
raise ValueError(
f"No Artifact in dcbench for object of type {type(data)}"
)
artifact = cls(artifact_id=artifact_id)
artifact.save(data)
return artifact
@property
def local_path(self) -> str:
"""The local path to the artifact in the local directory specified in
the config file at ``config.local_dir``."""
return os.path.join(config.local_dir, self.path)
@property
def remote_url(self) -> str:
"""The URL of the artifact in the remote GCS bucket specified in the
config file at ``config.public_bucket_name``."""
return os.path.join(
config.public_remote_url, self.path + (".tar.gz" if self.isdir else "")
)
@property
def is_downloaded(self) -> bool:
"""Checks if artifact is downloaded to local directory specified in the
config file at ``config.local_dir``.
Returns:
bool: True if artifact is downloaded, False otherwise.
"""
return os.path.exists(self.local_path)
@property
def is_uploaded(self) -> bool:
"""Checks if artifact is uploaded to GCS bucket specified in the config
file at ``config.public_bucket_name``.
Returns:
bool: True if artifact is uploaded, False otherwise.
"""
return _url_exists(self.remote_url)
def upload(self, force: bool = False, bucket: "storage.Bucket" = None) -> bool:
"""Uploads artifact to a GCS bucket at ``self.path``, which by default
is just the artifact ID with the default extension.
Args:
force (bool, optional): Force upload even if artifact is already uploaded.
Defaults to False.
bucket (storage.Bucket, optional): The GCS bucket to which the artifact is
uplioaded. Defaults to None, in which case the artifact is uploaded to
the bucket speciried in the config file at config.public_bucket_name.
Returns
bool: True if artifact was uploaded, False otherwise.
"""
if not os.path.exists(self.local_path):
raise ValueError(
f"Could not find Artifact to upload at '{self.local_path}'. "
"Are you sure it is stored locally?"
)
if self.is_uploaded and not force:
warnings.warn(
f"Artifact {self.id} is not being re-uploaded."
"Set `force=True` to force upload."
)
return False
if bucket is None:
client = storage.Client()
bucket = client.get_bucket(config.public_bucket_name)
if self.isdir:
_upload_dir_to_gcs(
local_path=self.local_path,
bucket=bucket,
gcs_path=self.path,
)
else:
blob = bucket.blob(self.path)
blob.upload_from_filename(self.local_path)
blob.metadata = {"Cache-Control": "private, max-age=0, no-transform"}
blob.patch()
return True
def download(self, force: bool = False) -> bool:
"""Downloads artifact from GCS bucket to the local directory specified
in the config file at ``config.local_dir``. The relative path to the
artifact within that directory is ``self.path``, which by default is
just the artifact ID with the default extension.
Args:
force (bool, optional): Force download even if artifact is already
downloaded. Defaults to False.
Returns:
bool: True if artifact was downloaded, False otherwise.
.. warning::
By default, the GCS cache on public urls has a max-age up to an hour.
Therefore, when updating an existin artifacts, changes may not be
immediately reflected in subsequent downloads.
See `here
<https://stackoverflow.com/questions/62897641/google-cloud-storage-public-ob
ject-url-e-super-slow-updating>`_
for more details.
"""
if self.is_downloaded and not force:
return False
if self.isdir:
if self.is_downloaded:
shutil.rmtree(self.local_path)
os.makedirs(self.local_path, exist_ok=True)
tarball_path = self.local_path + ".tar.gz"
urlretrieve_with_retry(self.remote_url, tarball_path)
subprocess.call(["tar", "-xzf", tarball_path, "-C", self.local_path])
os.remove(tarball_path)
else:
if self.is_downloaded:
os.remove(self.local_path)
os.makedirs(os.path.dirname(self.local_path), exist_ok=True)
urlretrieve_with_retry(self.remote_url, self.local_path)
return True
DEFAULT_EXT: str = ""
isdir: bool = False
@abstractmethod
def load(self) -> Any:
"""Load the artifact into memory from disk at ``self.local_path``."""
raise NotImplementedError()
@abstractmethod
def save(self, data: Any) -> None:
"""Save data to disk at ``self.local_path``."""
raise NotImplementedError()
def __init__(self, artifact_id: str, **kwargs) -> None:
"""
.. warning::
In general, you should not instantiate an Artifact directly. Instead, use
:meth:`Artifact.from_data` to create an Artifact.
"""
self.path = f"{artifact_id}.{self.DEFAULT_EXT}"
self.id = artifact_id
os.makedirs(os.path.dirname(self.local_path), exist_ok=True)
super().__init__()
@staticmethod
def from_yaml(loader: yaml.Loader, node):
"""This function is called by the YAML loader to convert a YAML node
into an Artifact object.
It should not be called directly.
"""
data = loader.construct_mapping(node, deep=True)
return data["class"](artifact_id=data["artifact_id"])
@staticmethod
def to_yaml(dumper: yaml.Dumper, data: Artifact):
"""This function is called by the YAML dumper to convert an Artifact
object into a YAML node.
It should not be called directly.
"""
data = {
"artifact_id": data.id,
"class": type(data),
}
node = dumper.represent_mapping("!Artifact", data)
return node
def _ensure_downloaded(self):
if not self.is_downloaded:
raise ValueError(
"Cannot load `Artifact` that has not been downloaded. "
"First call `artifact.download()`."
)
yaml.add_multi_representer(Artifact, Artifact.to_yaml)
yaml.add_constructor("!Artifact", Artifact.from_yaml)
class CSVArtifact(Artifact):
DEFAULT_EXT: str = "csv"
def load(self) -> pd.DataFrame:
self._ensure_downloaded()
data = pd.read_csv(self.local_path, index_col=0)
def parselists(x):
if isinstance(x, str):
try:
return json.loads(x)
except ValueError:
return x
else:
return x
return data.applymap(parselists)
def save(self, data: pd.DataFrame) -> None:
return data.to_csv(self.local_path)
class YAMLArtifact(Artifact):
DEFAULT_EXT: str = "yaml"
def load(self) -> Any:
self._ensure_downloaded()
return yaml.load(open(self.local_path), Loader=yaml.FullLoader)
def save(self, data: Any) -> None:
return yaml.dump(data, open(self.local_path, "w"))
class DataPanelArtifact(Artifact):
DEFAULT_EXT: str = "mk"
isdir: bool = True
def load(self) -> pd.DataFrame:
self._ensure_downloaded()
return mk.DataPanel.read(self.local_path)
def save(self, data: mk.DataPanel) -> None:
return data.write(self.local_path)
class VisionDatasetArtifact(DataPanelArtifact):
DEFAULT_EXT: str = "mk"
isdir: bool = True
COLUMN_SUBSETS = {
"celeba": ["id", "image", "split"],
"imagenet": ["id", "image", "name", "synset"],
}
@classmethod
def from_name(cls, name: str):
if name == "celeba":
dp = mk.datasets.get(name, dataset_dir=config.celeba_dir)
elif name == "imagenet":
dp = mk.datasets.get(name, dataset_dir=config.imagenet_dir, download=False)
else:
raise ValueError(f"No dataset named '{name}' supported by dcbench.")
dp["id"] = dp["image_id"]
dp.remove_column("image_id")
dp = dp[cls.COLUMN_SUBSETS[name]]
artifact = cls.from_data(data=dp, artifact_id=name)
return artifact
def download(self, force: bool = False):
if self.id == "celeba":
dp = mk.datasets.get(self.id, dataset_dir=config.celeba_dir)
elif self.id == "imagenet":
dp = mk.datasets.get(
self.id, dataset_dir=config.imagenet_dir, download=False
)
else:
raise ValueError(f"No dataset named '{self.id}' supported by dcbench.")
dp["id"] = dp["image_id"]
dp.remove_column("image_id")
dp = dp[self.COLUMN_SUBSETS[self.id]]
self.save(data=dp[self.COLUMN_SUBSETS[self.id]])
class ModelArtifact(Artifact):
DEFAULT_EXT: str = "pt"
def load(self) -> Model:
self._ensure_downloaded()
dct = torch.load(self.local_path, map_location="cpu")
model = dct["class"](dct["config"])
model.load_state_dict(dct["state_dict"])
return model
def save(self, data: Model) -> None:
return torch.save(
{
"state_dict": data.state_dict(),
"config": data.config,
"class": type(data),
},
self.local_path,
)
| [
"pandas.read_csv",
"os.remove",
"os.path.exists",
"meerkat.tools.lazy_loader.LazyLoader",
"meerkat.DataPanel.read",
"yaml.add_multi_representer",
"urllib.request.urlretrieve",
"yaml.add_constructor",
"os.path.isdir",
"subprocess.call",
"warnings.warn",
"urllib.request.urlopen",
"json.loads",... | [((474, 508), 'meerkat.tools.lazy_loader.LazyLoader', 'LazyLoader', (['"""google.cloud.storage"""'], {}), "('google.cloud.storage')\n", (484, 508), False, 'from meerkat.tools.lazy_loader import LazyLoader\n'), ((517, 536), 'meerkat.tools.lazy_loader.LazyLoader', 'LazyLoader', (['"""torch"""'], {}), "('torch')\n", (527, 536), False, 'from meerkat.tools.lazy_loader import LazyLoader\n'), ((11491, 11545), 'yaml.add_multi_representer', 'yaml.add_multi_representer', (['Artifact', 'Artifact.to_yaml'], {}), '(Artifact, Artifact.to_yaml)\n', (11517, 11545), False, 'import yaml\n'), ((11546, 11599), 'yaml.add_constructor', 'yaml.add_constructor', (['"""!Artifact"""', 'Artifact.from_yaml'], {}), "('!Artifact', Artifact.from_yaml)\n", (11566, 11599), False, 'import yaml\n'), ((632, 657), 'os.path.isdir', 'os.path.isdir', (['local_path'], {}), '(local_path)\n', (645, 657), False, 'import os\n'), ((668, 697), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (695, 697), False, 'import tempfile\n'), ((733, 768), 'os.path.join', 'os.path.join', (['tmp_dir', '"""run.tar.gz"""'], {}), "(tmp_dir, 'run.tar.gz')\n", (745, 768), False, 'import os\n'), ((777, 846), 'subprocess.call', 'subprocess.call', (["['tar', '-czf', tarball_path, '-C', local_path, '.']"], {}), "(['tar', '-czf', tarball_path, '-C', local_path, '.'])\n", (792, 846), False, 'import subprocess\n'), ((1168, 1180), 'urllib.request.urlopen', 'urlopen', (['url'], {}), '(url)\n', (1175, 1180), False, 'from urllib.request import urlopen, urlretrieve\n'), ((5250, 5291), 'os.path.join', 'os.path.join', (['config.local_dir', 'self.path'], {}), '(config.local_dir, self.path)\n', (5262, 5291), False, 'import os\n'), ((5489, 5579), 'os.path.join', 'os.path.join', (['config.public_remote_url', "(self.path + ('.tar.gz' if self.isdir else ''))"], {}), "(config.public_remote_url, self.path + ('.tar.gz' if self.isdir\n else ''))\n", (5501, 5579), False, 'import os\n'), ((5886, 5917), 'os.path.exists', 'os.path.exists', (['self.local_path'], {}), '(self.local_path)\n', (5900, 5917), False, 'import os\n'), ((11748, 11789), 'pandas.read_csv', 'pd.read_csv', (['self.local_path'], {'index_col': '(0)'}), '(self.local_path, index_col=0)\n', (11759, 11789), True, 'import pandas as pd\n'), ((12628, 12662), 'meerkat.DataPanel.read', 'mk.DataPanel.read', (['self.local_path'], {}), '(self.local_path)\n', (12645, 12662), True, 'import meerkat as mk\n'), ((1486, 1512), 'urllib.request.urlretrieve', 'urlretrieve', (['url', 'filename'], {}), '(url, filename)\n', (1497, 1512), False, 'from urllib.request import urlopen, urlretrieve\n'), ((6966, 6997), 'os.path.exists', 'os.path.exists', (['self.local_path'], {}), '(self.local_path)\n', (6980, 6997), False, 'import os\n'), ((7229, 7334), 'warnings.warn', 'warnings.warn', (['f"""Artifact {self.id} is not being re-uploaded.Set `force=True` to force upload."""'], {}), "(\n f'Artifact {self.id} is not being re-uploaded.Set `force=True` to force upload.'\n )\n", (7242, 7334), False, 'import warnings\n'), ((9148, 9191), 'os.makedirs', 'os.makedirs', (['self.local_path'], {'exist_ok': '(True)'}), '(self.local_path, exist_ok=True)\n', (9159, 9191), False, 'import os\n'), ((9325, 9394), 'subprocess.call', 'subprocess.call', (["['tar', '-xzf', tarball_path, '-C', self.local_path]"], {}), "(['tar', '-xzf', tarball_path, '-C', self.local_path])\n", (9340, 9394), False, 'import subprocess\n'), ((9407, 9430), 'os.remove', 'os.remove', (['tarball_path'], {}), '(tarball_path)\n', (9416, 9430), False, 'import os\n'), ((10412, 10444), 'os.path.dirname', 'os.path.dirname', (['self.local_path'], {}), '(self.local_path)\n', (10427, 10444), False, 'import os\n'), ((13085, 13137), 'meerkat.datasets.get', 'mk.datasets.get', (['name'], {'dataset_dir': 'config.celeba_dir'}), '(name, dataset_dir=config.celeba_dir)\n', (13100, 13137), True, 'import meerkat as mk\n'), ((13646, 13701), 'meerkat.datasets.get', 'mk.datasets.get', (['self.id'], {'dataset_dir': 'config.celeba_dir'}), '(self.id, dataset_dir=config.celeba_dir)\n', (13661, 13701), True, 'import meerkat as mk\n'), ((1575, 1663), 'warnings.warn', 'warnings.warn', (['f"""Failed to download {url}: {e}\nRetrying {idx}/{max_retries}..."""'], {}), '(\n f"""Failed to download {url}: {e}\nRetrying {idx}/{max_retries}...""")\n', (1588, 1663), False, 'import warnings\n'), ((4287, 4299), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (4297, 4299), False, 'import uuid\n'), ((9105, 9135), 'shutil.rmtree', 'shutil.rmtree', (['self.local_path'], {}), '(self.local_path)\n', (9118, 9135), False, 'import shutil\n'), ((9497, 9523), 'os.remove', 'os.remove', (['self.local_path'], {}), '(self.local_path)\n', (9506, 9523), False, 'import os\n'), ((9548, 9580), 'os.path.dirname', 'os.path.dirname', (['self.local_path'], {}), '(self.local_path)\n', (9563, 9580), False, 'import os\n'), ((13188, 13258), 'meerkat.datasets.get', 'mk.datasets.get', (['name'], {'dataset_dir': 'config.imagenet_dir', 'download': '(False)'}), '(name, dataset_dir=config.imagenet_dir, download=False)\n', (13203, 13258), True, 'import meerkat as mk\n'), ((13755, 13828), 'meerkat.datasets.get', 'mk.datasets.get', (['self.id'], {'dataset_dir': 'config.imagenet_dir', 'download': '(False)'}), '(self.id, dataset_dir=config.imagenet_dir, download=False)\n', (13770, 13828), True, 'import meerkat as mk\n'), ((11901, 11914), 'json.loads', 'json.loads', (['x'], {}), '(x)\n', (11911, 11914), False, 'import json\n')] |
import asyncio
import json
import zlib
import aiohttp
import errors
API_BASE = 'https://discordapp.com/api/v6'
CONFIG_FILE = json.load(open('data/config.json'))
TOKEN = CONFIG_FILE['token']
HEADERS = {'Authorization': 'Bot ' + TOKEN,
'User-Agent': 'DiscordBot (https://www.github.com/fourjr/dapi-bot,\
aiohttp and websockets)'}
SESSION = aiohttp.ClientSession(loop=asyncio.get_event_loop())
SESSION_DATA = [None, None]
PREFIX = './'
def parse_data(data):
'''Parses the websocket data into a dictionary'''
if isinstance(data, bytes):
return json.loads(zlib.decompress(data, 15, 10490000).decode('utf-8'))
else:
return json.loads(data)
def find(obj:list, **kwargs):
'''Finds a element of the given object that satisfies all kwargs'''
for i in obj:
if all(i[k] == kwargs[k] for k in kwargs):
return i
return None
async def request(http, endpoint, obj=None):
'''Used to request to the Discord API'''
if http == 'POST':
resp = await SESSION.post(API_BASE + endpoint, json=obj, headers=HEADERS)
elif http == 'DELETE':
resp = await SESSION.delete(API_BASE + endpoint, json=obj, headers=HEADERS)
if resp.status == 204:
return
obj = await resp.json()
print(resp)
if 300 > resp.status >= 200:
return #ok
elif resp.status == 403:
raise errors.Forbidden(resp, obj)
elif resp.status == 404:
raise errors.NotFound(resp, obj)
elif resp.status == 429:
raise errors.RateLimit(resp, obj)
async def get_channel(channel_id):
'''Gets a channel by the ID'''
return await request('GET', f'/channels/{channel_id}')
async def send_message(channel_id, content):
'''Sends a plain text message to the provided channel ID'''
return await request('POST', f'/channels/{channel_id}/messages', {'content':content}) | [
"json.loads",
"errors.NotFound",
"errors.Forbidden",
"asyncio.get_event_loop",
"zlib.decompress",
"errors.RateLimit"
] | [((389, 413), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (411, 413), False, 'import asyncio\n'), ((670, 686), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (680, 686), False, 'import json\n'), ((1384, 1411), 'errors.Forbidden', 'errors.Forbidden', (['resp', 'obj'], {}), '(resp, obj)\n', (1400, 1411), False, 'import errors\n'), ((1455, 1481), 'errors.NotFound', 'errors.NotFound', (['resp', 'obj'], {}), '(resp, obj)\n', (1470, 1481), False, 'import errors\n'), ((592, 627), 'zlib.decompress', 'zlib.decompress', (['data', '(15)', '(10490000)'], {}), '(data, 15, 10490000)\n', (607, 627), False, 'import zlib\n'), ((1525, 1552), 'errors.RateLimit', 'errors.RateLimit', (['resp', 'obj'], {}), '(resp, obj)\n', (1541, 1552), False, 'import errors\n')] |
import sys
import requests
import argparse
import logging
import json
import datetime
import anticrlf
from veracode_api_py import VeracodeAPI as vapi
log = logging.getLogger(__name__)
def setup_logger():
handler = logging.FileHandler('vcoffboard.log', encoding='utf8')
handler.setFormatter(anticrlf.LogFormatter('%(asctime)s - %(levelname)s - %(funcName)s - %(message)s'))
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
def creds_expire_days_warning():
creds = vapi().get_creds()
exp = datetime.datetime.strptime(creds['expiration_ts'], "%Y-%m-%dT%H:%M:%S.%f%z")
delta = exp - datetime.datetime.now().astimezone() #we get a datetime with timezone...
if (delta.days < 7):
print('These API credentials expire ', creds['expiration_ts'])
def get_user_list(usernames):
#get list of guids
user_list = []
for name in usernames:
userinfo = vapi().get_user_by_name(name) # note that this call always returns a list of 1, or 0
if len(userinfo) == 0:
errorstring = "No user found with name {}".format(name)
print(errorstring)
log.warning(errorstring)
#log
continue
userguid = userinfo[0]["user_id"]
user_list.append(userguid)
return user_list
def deactivate_user(userguid):
vapi().disable_user(userguid)
notification = "Deactivated user {}".format(userguid)
log.info(notification)
return 1
def delete_user(userguid):
vapi().delete_user(userguid)
notification = "Deleted user {}".format(userguid)
log.info(notification)
return 1
def main():
parser = argparse.ArgumentParser(
description='This script deactivates a list of users in Veracode.')
parser.add_argument('-u', '--usernames',nargs="+", required=False, help='List of usernames to deactivate.')
parser.add_argument('--delete',action='store_true')
args = parser.parse_args()
usernames = args.usernames
deleteuser = args.delete
# CHECK FOR CREDENTIALS EXPIRATION
creds_expire_days_warning()
count=0
userguids = get_user_list(usernames)
for guid in userguids:
if deleteuser:
count += delete_user(guid)
else:
count += deactivate_user(guid)
if deleteuser:
action="Deleted"
else:
action="Deactivated"
print("{} {} users".format(action,count))
if __name__ == '__main__':
setup_logger()
main() | [
"logging.getLogger",
"anticrlf.LogFormatter",
"argparse.ArgumentParser",
"datetime.datetime.strptime",
"veracode_api_py.VeracodeAPI",
"datetime.datetime.now",
"logging.FileHandler"
] | [((158, 185), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (175, 185), False, 'import logging\n'), ((221, 275), 'logging.FileHandler', 'logging.FileHandler', (['"""vcoffboard.log"""'], {'encoding': '"""utf8"""'}), "('vcoffboard.log', encoding='utf8')\n", (240, 275), False, 'import logging\n'), ((397, 424), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (414, 424), False, 'import logging\n'), ((565, 641), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (["creds['expiration_ts']", '"""%Y-%m-%dT%H:%M:%S.%f%z"""'], {}), "(creds['expiration_ts'], '%Y-%m-%dT%H:%M:%S.%f%z')\n", (591, 641), False, 'import datetime\n'), ((1682, 1778), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""This script deactivates a list of users in Veracode."""'}), "(description=\n 'This script deactivates a list of users in Veracode.')\n", (1705, 1778), False, 'import argparse\n'), ((301, 387), 'anticrlf.LogFormatter', 'anticrlf.LogFormatter', (['"""%(asctime)s - %(levelname)s - %(funcName)s - %(message)s"""'], {}), "(\n '%(asctime)s - %(levelname)s - %(funcName)s - %(message)s')\n", (322, 387), False, 'import anticrlf\n'), ((536, 542), 'veracode_api_py.VeracodeAPI', 'vapi', ([], {}), '()\n', (540, 542), True, 'from veracode_api_py import VeracodeAPI as vapi\n'), ((1372, 1378), 'veracode_api_py.VeracodeAPI', 'vapi', ([], {}), '()\n', (1376, 1378), True, 'from veracode_api_py import VeracodeAPI as vapi\n'), ((1533, 1539), 'veracode_api_py.VeracodeAPI', 'vapi', ([], {}), '()\n', (1537, 1539), True, 'from veracode_api_py import VeracodeAPI as vapi\n'), ((660, 683), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (681, 683), False, 'import datetime\n'), ((948, 954), 'veracode_api_py.VeracodeAPI', 'vapi', ([], {}), '()\n', (952, 954), True, 'from veracode_api_py import VeracodeAPI as vapi\n')] |
from expects import expect, contain, be_an
class Bacon:
...
sanduiche = 'sanduiche com queijo'
expect(sanduiche).to(contain('queijo'))
expect(sanduiche).to_not(be_an(Bacon))
| [
"expects.be_an",
"expects.contain",
"expects.expect"
] | [((127, 144), 'expects.contain', 'contain', (['"""queijo"""'], {}), "('queijo')\n", (134, 144), False, 'from expects import expect, contain, be_an\n'), ((172, 184), 'expects.be_an', 'be_an', (['Bacon'], {}), '(Bacon)\n', (177, 184), False, 'from expects import expect, contain, be_an\n'), ((106, 123), 'expects.expect', 'expect', (['sanduiche'], {}), '(sanduiche)\n', (112, 123), False, 'from expects import expect, contain, be_an\n'), ((147, 164), 'expects.expect', 'expect', (['sanduiche'], {}), '(sanduiche)\n', (153, 164), False, 'from expects import expect, contain, be_an\n')] |
"""
Main
=============
Example
"""
# Import
import numpy as np
import pandas as pd
# Specific
from tpot import TPOTClassifier
# Import own
from pySML2.preprocessing.splitters import cvs_hos_split
from pySML2.preprocessing.splitters import kfolds_split
# ---------------------------------------------
# Configuration
# ---------------------------------------------
# The input features and label for the algorithm
features = sorted(['alb', 'alp', 'alt', 'baso', 'bil', 'cl', 'cre', 'crp', 'egfr',
'eos', 'k', 'ly', 'mcv', 'mono', 'mpv', 'nrbca', 'plt', 'rbc',
'rdw', 'urea', 'wbc'])
# The labels
labels = sorted(['micro_confirmed'])
# The splits
n_splits = 10
# Dataset
# -------
# Dataset filepath
filepath = './dataset.csv'
# ---------------------------------------------
# Load dataset and format it
# ---------------------------------------------
# Read data
data = pd.read_csv(filepath)
data.columns = [c.lower() for c in data.columns.values]
# data = data[features + labels]
# Missing values
data['missing'] = data[features].isnull().sum(axis=1)
# The indexes for complete profiles
cmp = (data.missing == 0)
# Split in CVS and HOS
data['cvs_hos_split'] = cvs_hos_split(data, selected_rows=cmp)
# ---------------------------------------------
# Train
# ---------------------------------------------
data[(data.missing == 0)].to_csv('tpot_data_cvs.csv')
data[(data.cvs_hos_split == 'hos')].to_csv('tpot_data_hos.csv')
data[(data.cvs_hos_split == 'cvs')].to_csv('tpot_data_cvs.csv')
data[(data.cvs_hos_split == 'hos')].to_csv('tpot_data_hos.csv')
# ---------------------------------------------
# Train
# ---------------------------------------------
# The indexes used for cross validation
cvs_idxs = (data.cvs_hos_split == 'cvs')
hos_idxs = (data.cvs_hos_split == 'hos')
# Create matrices train
X_train = data[cvs_idxs][features].to_numpy()
y_train = data[cvs_idxs][labels].to_numpy()
# Create matrices test
X_test = data[cvs_idxs][features].to_numpy()
y_test = data[cvs_idxs][labels].to_numpy()
# ---------------------------------------------
# Search
# ---------------------------------------------
# Create genetic search
tpot = TPOTClassifier(generations=5, verbosity=2,
scoring='roc_auc', cv=2)
# Fit
tpot.fit(X_train, y_train)
# Score
score = tpot.score(X_test, y_test)
# Save
tpot.export('tpot_best_pipeline.py') | [
"tpot.TPOTClassifier",
"pySML2.preprocessing.splitters.cvs_hos_split",
"pandas.read_csv"
] | [((917, 938), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {}), '(filepath)\n', (928, 938), True, 'import pandas as pd\n'), ((1211, 1249), 'pySML2.preprocessing.splitters.cvs_hos_split', 'cvs_hos_split', (['data'], {'selected_rows': 'cmp'}), '(data, selected_rows=cmp)\n', (1224, 1249), False, 'from pySML2.preprocessing.splitters import cvs_hos_split\n'), ((2192, 2259), 'tpot.TPOTClassifier', 'TPOTClassifier', ([], {'generations': '(5)', 'verbosity': '(2)', 'scoring': '"""roc_auc"""', 'cv': '(2)'}), "(generations=5, verbosity=2, scoring='roc_auc', cv=2)\n", (2206, 2259), False, 'from tpot import TPOTClassifier\n')] |
#!/usr/bin/env python3.6
"""Sherlock: Find Usernames Across Social Networks Module
This module contains the main logic to search for usernames at social
networks.
"""
import requests
import csv
import json
import os
import re
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import platform
module_name = "Sherlock: Find Usernames Across Social Networks"
__version__ = "0.1.0"
# TODO: fix tumblr
def unique_list(seq):
return list(dict.fromkeys(seq))
def write_to_file(url, fname):
with open(fname, "a") as f:
f.write(url+"\n")
def print_error(err, errstr, var, debug=False):
if debug:
print(f"\033[37;1m[\033[91;1m-\033[37;1m]\033[91;1m {errstr}\033[93;1m {err}")
else:
print(f"\033[37;1m[\033[91;1m-\033[37;1m]\033[91;1m {errstr}\033[93;1m {var}")
def make_request(url, headers, social_network, verbose=False):
try:
r = requests.get(url, headers=headers)
if r.status_code:
return r
except requests.exceptions.HTTPError as errh:
print_error(errh, "HTTP Error:", social_network, verbose)
except requests.exceptions.ConnectionError as errc:
print_error(errc, "Error Connecting:", social_network, verbose)
except requests.exceptions.Timeout as errt:
print_error(errt, "Timeout Error:", social_network, verbose)
except requests.exceptions.RequestException as err:
print_error(err, "Unknown error:", social_network, verbose)
return None
def get_social_network_result(username,
headers,
social_network,
info,
verbose=False):
_result = {}
_result["username"] = username
_result["social_network"] = social_network
_result["success"] = False
_result["url"] = info["url"].format(username)
error_type = info["errorType"]
if "regexCheck" in info:
if re.search(info["regexCheck"], username) is None:
# No need to do the check at the site: this user name is not allowed.
_result["success"] = False
_result["url"] = "Illegal Username Format For This Site!"
return _result
r = make_request(_result["url"], headers, social_network, verbose)
if r is None:
_result["success"] = False
_result["url"] = "Error"
elif error_type == "message" and r.status_code:
error = info["errorMsg"]
# Checks if the error message is in the HTML
if error not in r.text:
_result["success"] = True
else:
_result["success"] = False
_result["url"] = "Not Found"
elif error_type == "status_code" and r.status_code:
# Checks if the status code of the repsonse is 404
if not r.status_code == 404:
_result["success"] = True
else:
_result["success"] = False
_result["url"] = "Not Found"
elif error_type == "response_url" and r.status_code:
error = info["errorUrl"]
# Checks if the redirect url is the same as the one defined in data.json
if error not in r.url:
_result["success"] = True
else:
_result["success"] = False
_result["url"] = "Not Found"
return _result
def get_username_results(username, verbose=False):
with open("data.json", "r", encoding="utf-8") as raw:
data = json.load(raw)
# User agent is needed because some sites does not
# return the correct information because it thinks that
# we are bot
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0'
}
for social_network, info in data.items():
yield get_social_network_result(username, headers, social_network, info, verbose)
def csv_output(usernames, filename, verbose):
if os.path.isfile(filename):
os.remove(filename)
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Removing previous file:\033[1;37m {}\033[0m".format(filename))
with open("data.json", "r", encoding="utf-8") as raw:
data = json.load(raw)
fieldnames = []
fieldnames += ["username"]
for social_network, info in data.items():
fieldnames += [social_network]
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for username in usernames:
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Checking username\033[0m\033[1;37m {}\033[0m\033[1;92m on: \033[0m".format(username))
row = {}
row["username"] = username
for result in get_username_results(username, verbose):
row[result["social_network"]] = result["url"]
if result["success"]:
print("\033[37;1m[\033[92;1m+\033[37;1m]\033[92;1m {}:\033[0m".
format(result["social_network"]), result["url"])
elif "http" not in result["url"]:
print("\033[37;1m[\033[91;1m-\033[37;1m]\033[92;1m {}:\033[0m".
format(result["social_network"]), result["url"])
else:
print("\033[37;1m[\033[91;1m-\033[37;1m]\033[92;1m {}:\033[93;1m Not Found!".
format(result["social_network"]))
writer.writerow(row)
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Saved: \033[37;1m{}\033[0m".format(filename))
def sherlock(username, verbose=False):
fname = username+".txt"
if os.path.isfile(fname):
os.remove(fname)
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Removing previous file:\033[1;37m {}\033[0m".format(fname))
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Checking username\033[0m\033[1;37m {}\033[0m\033[1;92m on: \033[0m".format(username))
for result in get_username_results(username, verbose):
if result["success"]:
print("\033[37;1m[\033[92;1m+\033[37;1m]\033[92;1m {}:\033[0m".
format(result["social_network"]), result["url"])
write_to_file(result["url"], fname)
elif "http" not in result["url"]:
print("\033[37;1m[\033[91;1m-\033[37;1m]\033[92;1m {}:\033[0m".
format(result["social_network"]), result["url"])
else:
print("\033[37;1m[\033[91;1m-\033[37;1m]\033[92;1m {}:\033[93;1m Not Found!".
format(result["social_network"]))
print("\033[1;92m[\033[0m\033[1;77m*\033[0m\033[1;92m] Saved: \033[37;1m{}\033[0m".format(username+".txt"))
return
def main():
version_string = f"%(prog)s {__version__}\n" + \
f"{requests.__description__}: {requests.__version__}\n" + \
f"Python: {platform.python_version()}"
parser = ArgumentParser(formatter_class=RawDescriptionHelpFormatter,
description=f"{module_name} (Version {__version__})"
)
parser.add_argument("--version",
action="version", version=version_string,
help="Display version information and dependencies."
)
parser.add_argument("--verbose", "-v", "-d", "--debug",
action="store_true", dest="verbose", default=False,
help="Display extra debugging information."
)
parser.add_argument("--quiet", "-q",
action="store_false", dest="verbose",
help="Disable debugging information (Default Option)."
)
parser.add_argument("--input", "-i",
action="store", dest="infile", default="",
help="Input file with one username per line to check with social networks."
)
parser.add_argument("--output", "-o",
action="store", dest="output", default="",
help="Output CSV file."
)
parser.add_argument("username",
nargs='+', metavar='USERNAMES',
action="store",
help="One or more usernames to check with social networks."
)
args = parser.parse_args()
# Banner
print(
"""\033[37;1m .\"\"\"-.
\033[37;1m / \\
\033[37;1m ____ _ _ _ | _..--'-.
\033[37;1m/ ___|| |__ ___ _ __| | ___ ___| |__ >.`__.-\"\"\;\"`
\033[37;1m\___ \| '_ \ / _ \ '__| |/ _ \ / __| |/ / / /( ^\\
\033[37;1m ___) | | | | __/ | | | (_) | (__| < '-`) =|-.
\033[37;1m|____/|_| |_|\___|_| |_|\___/ \___|_|\_\ /`--.'--' \ .-.
\033[37;1m .'`-._ `.\ | J /
\033[37;1m / `--.| \__/\033[0m""")
# Get usernames from command line
usernames = []
for username in args.username:
usernames += [username]
# Get usernames from input file
if args.infile:
with open(args.infile, "r") as fh:
for username in fh:
usernames += [username.strip()]
if not args.output:
# Run report on all specified users and display to screen
for username in unique_list(usernames):
print()
sherlock(username, args.verbose)
else:
csv_output(usernames, args.output, args.verbose)
if __name__ == "__main__":
main()
| [
"csv.DictWriter",
"re.search",
"argparse.ArgumentParser",
"requests.get",
"os.path.isfile",
"json.load",
"platform.python_version",
"os.remove"
] | [((3910, 3934), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (3924, 3934), False, 'import os\n'), ((5626, 5647), 'os.path.isfile', 'os.path.isfile', (['fname'], {}), '(fname)\n', (5640, 5647), False, 'import os\n'), ((6915, 7033), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'formatter_class': 'RawDescriptionHelpFormatter', 'description': 'f"""{module_name} (Version {__version__})"""'}), "(formatter_class=RawDescriptionHelpFormatter, description=\n f'{module_name} (Version {__version__})')\n", (6929, 7033), False, 'from argparse import ArgumentParser, RawDescriptionHelpFormatter\n'), ((901, 935), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (913, 935), False, 'import requests\n'), ((3441, 3455), 'json.load', 'json.load', (['raw'], {}), '(raw)\n', (3450, 3455), False, 'import json\n'), ((3944, 3963), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (3953, 3963), False, 'import os\n'), ((4163, 4177), 'json.load', 'json.load', (['raw'], {}), '(raw)\n', (4172, 4177), False, 'import json\n'), ((4372, 4418), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames'}), '(csvfile, fieldnames=fieldnames)\n', (4386, 4418), False, 'import csv\n'), ((5657, 5673), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (5666, 5673), False, 'import os\n'), ((1949, 1988), 're.search', 're.search', (["info['regexCheck']", 'username'], {}), "(info['regexCheck'], username)\n", (1958, 1988), False, 'import re\n'), ((6873, 6898), 'platform.python_version', 'platform.python_version', ([], {}), '()\n', (6896, 6898), False, 'import platform\n')] |
# 发现疑似实体,辅助训练
# 用ac自动机构建发现疑似实体的工具
import os
from collections import defaultdict
import json
import re
from .acmation import KeywordTree, add_to_ac, entity_files_folder, entity_folder
from curLine_file import curLine, normal_transformer
domain2entity_map = {}
domain2entity_map["music"] = ["age", "singer", "song", "toplist", "theme", "style", "scene", "language", "emotion", "instrument"]
domain2entity_map["navigation"] = ["custom_destination", "city"] # place city
domain2entity_map["phone_call"] = ["phone_num", "contact_name"]
re_phoneNum = re.compile("[0-9一二三四五六七八九十拾]+") # 编译
# 也许直接读取下载的xls文件更方便,但那样需要安装xlrd模块
self_entity_trie_tree = {} # 总的实体字典 自己建立的某些实体类型的实体树
for domain, entity_type_list in domain2entity_map.items():
print(curLine(), domain, entity_type_list)
for entity_type in entity_type_list:
if entity_type not in self_entity_trie_tree:
ac = KeywordTree(case_insensitive=True)
else:
ac = self_entity_trie_tree[entity_type]
# TODO
if entity_type == "city":
# for current_entity_type in ["city", "province"]:
# entity_file = waibu_folder + "%s.json" % current_entity_type
# with open(entity_file, "r") as f:
# current_entity_dict = json.load(f)
# print(curLine(), "get %d %s from %s" %
# (len(current_entity_dict), current_entity_type, entity_file))
# for entity_before, entity_times in current_entity_dict.items():
# entity_after = entity_before
# add_to_ac(ac, entity_type, entity_before, entity_after, pri=1)
## 从标注语料中挖掘得到的地名
for current_entity_type in ["destination", "origin"]:
entity_file = os.path.join(entity_files_folder, "%s.json" % current_entity_type)
with open(entity_file, "r") as f:
current_entity_dict = json.load(f)
print(curLine(), "get %d %s from %s" %
(len(current_entity_dict), current_entity_type, entity_file))
for entity_before, entity_after_times in current_entity_dict.items():
entity_after = entity_after_times[0]
add_to_ac(ac, entity_type, entity_before, entity_after, pri=2)
input(curLine())
# 给的实体库,最高优先级
entity_file = os.path.join(entity_folder, "%s.txt" % entity_type)
if os.path.exists(entity_file):
with open(entity_file, "r") as fr:
lines = fr.readlines()
print(curLine(), "get %d %s from %s" % (len(lines), entity_type, entity_file))
for line in lines:
entity_after = line.strip()
entity_before = entity_after # TODO
pri = 3
if entity_type in ["song"]:
pri -= 0.5
add_to_ac(ac, entity_type, entity_before, entity_after, pri=pri)
ac.finalize()
self_entity_trie_tree[entity_type] = ac
def get_all_entity(corpus, useEntityTypeList):
self_entityTypeMap = defaultdict(list)
for entity_type in useEntityTypeList:
result = self_entity_trie_tree[entity_type].search(corpus)
for res in result:
after, priority = res.meta_data
self_entityTypeMap[entity_type].append({'before': res.keyword, 'after': after, "priority":priority})
if "phone_num" in useEntityTypeList:
token_numbers = re_phoneNum.findall(corpus)
for number in token_numbers:
self_entityTypeMap["phone_num"].append({'before':number, 'after':number, 'priority': 2})
return self_entityTypeMap | [
"os.path.exists",
"curLine_file.curLine",
"re.compile",
"os.path.join",
"collections.defaultdict",
"json.load"
] | [((549, 580), 're.compile', 're.compile', (['"""[0-9一二三四五六七八九十拾]+"""'], {}), "('[0-9一二三四五六七八九十拾]+')\n", (559, 580), False, 'import re\n'), ((3134, 3151), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3145, 3151), False, 'from collections import defaultdict\n'), ((746, 755), 'curLine_file.curLine', 'curLine', ([], {}), '()\n', (753, 755), False, 'from curLine_file import curLine, normal_transformer\n'), ((2414, 2465), 'os.path.join', 'os.path.join', (['entity_folder', "('%s.txt' % entity_type)"], {}), "(entity_folder, '%s.txt' % entity_type)\n", (2426, 2465), False, 'import os\n'), ((2477, 2504), 'os.path.exists', 'os.path.exists', (['entity_file'], {}), '(entity_file)\n', (2491, 2504), False, 'import os\n'), ((1791, 1857), 'os.path.join', 'os.path.join', (['entity_files_folder', "('%s.json' % current_entity_type)"], {}), "(entity_files_folder, '%s.json' % current_entity_type)\n", (1803, 1857), False, 'import os\n'), ((2610, 2619), 'curLine_file.curLine', 'curLine', ([], {}), '()\n', (2617, 2619), False, 'from curLine_file import curLine, normal_transformer\n'), ((1950, 1962), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1959, 1962), False, 'import json\n'), ((2358, 2367), 'curLine_file.curLine', 'curLine', ([], {}), '()\n', (2365, 2367), False, 'from curLine_file import curLine, normal_transformer\n'), ((1989, 1998), 'curLine_file.curLine', 'curLine', ([], {}), '()\n', (1996, 1998), False, 'from curLine_file import curLine, normal_transformer\n')] |
#!python/bin/python3
"""
Copyright (c) 2018 NSF Center for Space, High-performance, and Resilient Computing (SHREC)
University of Pittsburgh. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
"""
# TODO: add key verification
from collections import defaultdict
from copy import deepcopy
from importlib import import_module
from os.path import abspath, dirname
from sys import path
path.append(dirname(dirname(abspath(__file__))))
targets = import_module('src.targets')
load_targets = targets.load_targets
save_targets = targets.save_targets
def tree():
return defaultdict(tree)
missing_total = 0
for device in ['a9', 'p2020']:
jtag_targets = load_targets(device, 'jtag')
simics_targets = load_targets(device, 'simics')
merged_targets = tree()
for old_type in ['simics', 'jtag']: # do simics first because of preprocess
print('\nerrors for', device, old_type)
if old_type == 'jtag':
old_targets = jtag_targets
other_type = 'simics'
other_targets = simics_targets
elif old_type == 'simics':
old_targets = simics_targets
other_type = 'jtag'
other_targets = jtag_targets
else:
raise Exception('unrecognized old_type')
for target in sorted(old_targets.keys()):
if 'unused_targets' not in merged_targets[other_type]:
merged_targets[other_type]['unused_targets'] = []
old_target = old_targets[target]
merged_target = merged_targets['targets'][target]
if target == 'TLB':
merged_target['type'] = 'tlb'
if 'is_gcache' in old_target and old_target['is_gcache']:
merged_target['type'] = 'gcache'
if target not in other_targets:
other_target = None
merged_targets[other_type]['unused_targets'].append(target)
# print('target in '+old_type+' but not '+other_type+':',
# target)
else:
other_target = other_targets[target]
for key in [key for key in old_target.keys()
if key not in ['registers', 'unused_registers']]:
if key == 'base':
merged_target[key] = old_target[key]
elif key == 'count':
if old_target[key] != 1:
merged_target[key] = old_target[key]
elif key in ['CP', 'memory_mapped']:
if not old_target[key]:
print('unexpected value for :', target+'['+key+']:',
old_target[key])
merged_target['type'] = key
elif key == 'OBJECT':
merged_targets[old_type]['targets'][target]['object'] = \
old_target['OBJECT']
elif key == 'limitations':
merged_targets[old_type]['targets'][target][key] = \
old_target[key]
else:
print('* key:', key, 'in target:', target)
if old_type == 'simics':
registers = list(old_target['registers'].keys())
if 'unused_registers' in old_target:
unused_registers = list(
old_target['unused_registers'].keys())
else:
unused_registers = []
for register in registers + unused_registers:
unused_register = register in unused_registers
if unused_register:
old_register = old_target['unused_registers'][register]
else:
old_register = old_target['registers'][register]
if 'count' in old_register:
count = old_register['count']
else:
count = []
if register == 'fpgprs':
for i in range(old_register['count'][0]):
old_target['registers']['fpr'+str(i)] = {'alias': {
'register': register, 'register_index': [i]}}
del old_target['registers'][register]
continue
if other_target is not None and \
register not in other_target['registers']:
matches = []
for other_register in other_target['registers']:
if count:
if other_register.startswith(register):
try:
try:
index = int(
other_register.replace(
register+'_', ''))
except:
index = int(
other_register.replace(
register, ''))
if register == 'SRDSCR' and \
index > 3:
index -= 1
elif register == 'DDR_SDRAM_RCW':
index -= 1
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if register == 'MSI_MSISR' and \
other_register == 'MSISR':
match = ('MSISR', [0])
matches.append(match)
# print(register, count, match)
if register == 'usb_regs_prtsc' and \
other_register == 'PORTSC':
match = ('PORTSC', [0])
matches.append(match)
# print(register, count, match)
if register == 'PM_MR' and \
'MR' in other_register:
try:
index1 = int(other_register[2])
index2 = int(other_register[5])
match = (other_register,
[index1, index2])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if register == 'IADDR' and \
other_register.startswith('IGADDR'):
index = int(other_register.replace(
'IGADDR', ''))
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
if register.startswith('MAC_ADD') and \
'MAC' in other_register and \
'ADDR' in other_register and \
register[-1] == other_register[-1]:
try:
index = int(other_register[3:5])-1
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if register == 'PEX_outbound_OTWBAR' and \
other_register.startswith('PEXOWBAR'):
try:
index = int(
other_register.replace(
'PEXOWBAR', ''))
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if len(register.split('_')) > 1:
reg = register.split('_')
if reg[-1][-1] == 'n':
reg[-1] = reg[-1][:-1]
if reg[0] == 'CS' and '_'.join(reg[1:]) == \
'_'.join(
other_register.split('_')[1:]):
try:
index = int(
other_register.split(
'_')[0].replace('CS', ''))
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if reg[0] == 'PEX' and \
other_register.startswith(
'PEX'+reg[-1]):
try:
index = int(
other_register.replace(
'PEX'+reg[-1], ''))
if reg[-1] in ['IWAR', 'IWBAR',
'ITAR', 'IWBEAR']:
index -= 1
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if reg[0] == 'MSG' and \
reg[1] in ['MER', 'MSR']:
if other_register.startswith(reg[1]):
if other_register[-1] == 'a':
index = 1
else:
index = 0
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
if reg[0] == 'GT' and \
reg[1] in ['TFRR', 'TCR']:
if other_register.startswith(reg[1]):
if other_register[-1] == 'A':
index = 0
elif other_register[-1] == 'B':
index = 1
match = (other_register, [index])
matches.append(match)
# print(register, count, match)
continue
if register == 'regs_port_' \
'port_error_and_status':
reg[2] = 'ESCSR'
if register == 'regs_port_port_control':
reg[2] = 'CCSR'
if register == 'regs_port_port_error_rate':
reg[2] = 'ERCSR'
if register == 'regs_port_' \
'capture_attributes':
reg[2] = 'ECACSR'
if register == 'regs_port_' \
'port_error_detect':
reg[2] = 'EDCSR'
if register == 'regs_port_' \
'port_error_rate_enable':
reg[2] = 'ERECSR'
if register == 'regs_port_' \
'port_error_rate_threshold':
reg[2] = 'ERTCSR'
if register == 'regs_port_capture_symbol':
reg[2] = 'PCSECCSR0'
if register == 'regs_port_' \
'port_local_ackid_status':
reg[2] = 'LASCSR'
if register == 'regs_port_' \
'capture_packet_1':
reg[2] = 'PECCSR1'
if register == 'regs_port_' \
'capture_packet_2':
reg[2] = 'PECCSR2'
if register == 'regs_port_' \
'capture_packet_3':
reg[2] = 'PECCSR3'
if register == 'regs_port_' \
'link_maintenance_request':
reg[2] = 'LMREQCSR'
if register == 'regs_port_' \
'link_maintenance_response':
reg[2] = 'LMRESPCSR'
if reg[1] == 'port' and \
reg[2] in other_register and \
other_register[0] == 'P':
if len(count) == 1:
try:
index = int(other_register[1])
if other_register == \
'P'+str(index)+reg[2]:
index -= 1
match = (other_register,
[index])
matches.append(match)
# print(register, count,
# match)
continue
except:
pass
elif len(count) == 2:
try:
index1 = int(other_register[1])
index1 -= 1
index2 = int(other_register[-1])
if reg[2] in ['RIWTAR',
'ROWTAR',
'ROWTEAR',
'RIWAR',
'ROWAR',
'ROWBAR',
'RIWBAR',
'ROWS1R',
'ROWS2R',
'ROWS3R']:
if index2 == 0:
continue
print('unexpected 0 '
'index')
else:
index2 -= 1
match = (other_register,
[index1, index2])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if reg[1] == 'M':
r = None
if reg[2].startswith('EI'):
s = 'EIM'
r = reg[2][2:]
i = 3
elif reg[2].startswith('EO'):
s = 'EOM'
r = reg[2][2:]
i = 3
elif reg[2].startswith('I'):
s = 'IM'
r = reg[2][1:]
i = 2
elif reg[2].startswith('O'):
s = 'OM'
r = reg[2][1:]
i = 2
if r is not None and \
other_register.endswith(r) and \
other_register.startswith(s):
try:
index = int(other_register[i])
match = (other_register,
[index])
matches.append(match)
# print(register, count, match)
continue
except:
pass
if other_register.startswith(reg[-1]):
index = None
try:
index = int(other_register[-2:])
except:
try:
index = int(other_register[-1])
except:
pass
if index is not None:
if len(count) == 1:
if register == 'regs_SNOOP':
index -= 1
match = (other_register,
[index])
elif len(count) == 2:
if count[0] == 1:
match = (other_register,
[0, index])
elif other_register[-2] == 'a':
match = (other_register,
[1,
index % count[1]])
elif other_register[-2] == 'A':
match = (other_register,
[0, index])
elif other_register[-2] == 'B':
match = (other_register,
[1, index])
elif register == \
'P_IPIDR' and \
other_register.endswith(
'CPU' +
str(index).zfill(2)):
if index >= 10:
index1 = 2
else:
index1 = 1
match = (
other_register,
[index1,
index % 10])
else:
match = (other_register,
[int(index /
count[1]),
index % count[1]])
matches.append(match)
# print(register, count, match)
continue
else:
if other_register == register.upper():
match = (register.upper(), None)
matches.append(match)
# print(register, count, match)
break
if len(register.split('_')) > 1:
reg = register.split('_')
if register == 'regs_layer_error_detect':
reg[-1] = 'LTLEDCSR'
if register == 'regs_layer_error_enable':
reg[-1] = 'LTLEECSR'
if register == 'regs_src_operations':
reg[-1] = 'SOCAR'
if register == 'regs_pe_ll_status':
reg[-1] = 'PELLCCSR'
if register == 'regs_pe_features':
reg[-1] = 'PEFCAR'
if register == 'regs_DMIRIR':
reg[-1] = 'IDMIRIR'
if register == 'regs_error_block_header':
reg[-1] = 'ERBH'
if register == 'regs_dst_operations':
reg[-1] = 'DOCAR'
if register == 'regs_assembly_id':
reg[-1] = 'AIDCAR'
if register == 'regs_assembly_info':
reg[-1] = 'AICAR'
if register == 'regs_port_link_timeout':
reg[-1] = 'PLTOCCSR'
if register == 'regs_base_device_id':
reg[-1] = 'BDIDCSR'
if register == 'regs_component_tag':
reg[-1] = 'CTCSR'
if register == 'regs_device_info':
reg[-1] = 'DICAR'
if register == 'regs_device_id':
reg[-1] = 'DIDCAR'
if register == 'regs_port_block_header':
reg[-1] = 'PMBH0'
if register == 'regs_host_base_device_id':
reg[-1] = 'HBDIDLCSR'
if register == 'regs_port_general_control':
reg[-1] = 'PGCCSR'
if register == 'regs_ODRS':
reg[-1] = 'ODSR'
if register == 'regs_base1_status':
reg[-1] = 'LCSBA1CSR'
if register == 'regs_write_port_status':
reg[-1] = 'PWDCSR'
if register == 'regs_layer_capture_address':
reg[-1] = 'LTLACCSR'
if register == 'regs_layer_capture_control':
reg[-1] = 'LTLCCCSR'
if register == \
'regs_layer_capture_device_id':
reg[-1] = 'LTLDIDCCSR'
if register == '':
reg[-1] = ''
if register == '':
reg[-1] = ''
if other_register == reg[-1]:
match = (reg[-1], None)
matches.append(match)
# print(register, count, match)
break
if reg[0] == 'regs' and other_register == \
'_'.join(reg[1:]):
match = (other_register, None)
matches.append(match)
# print(register, count, match)
break
if other_register == reg[-1].upper():
match = (reg[-1].upper(), None)
matches.append(match)
# print(register, count, match)
break
if other_register == 'I'+reg[-1]:
match = ('I'+reg[-1], None)
matches.append(match)
# print(register, count, match)
break
if reg[-1].startswith('E') and \
other_register.startswith('E') and \
other_register == 'EI'+reg[-1][1:]:
match = ('EI'+reg[-1][1:], None)
matches.append(match)
# print(register, count, match)
break
if reg[-1] == 'ADDRESS' and \
other_register == \
register.replace('ADDRESS',
'ADDR'):
match = (register.replace('ADDRESS',
'ADDR'),
None)
matches.append(match)
# print(register, count, match)
break
if register == 'DDR_SDRAM_INIT':
match = ('DDR_DATA_INIT', None)
matches.append(match)
# print(register, count, match)
break
if register == 'ECMIP_REV1':
match = ('EIPBRR1', None)
matches.append(match)
# print(register, count, match)
break
if register == 'ECMIP_REV2':
match = ('EIPBRR2', None)
matches.append(match)
# print(register, count, match)
break
if register == 'IOVSELCR':
match = ('IOVSELSR', None)
matches.append(match)
# print(register, count, match)
break
if matches:
matches.sort(key=lambda x: x[0])
correct = True
if len(count) > 0:
counts0 = [match[1][0] for match in matches
if len(match[1]) == 1 or
(len(match[1]) == 2 and
match[1][1] == 0)]
missing = []
extra = []
for i in range(count[0]):
if i not in counts0:
correct = False
missing.append([i])
else:
counts0.remove(i)
if len(count) == 2:
counts1 = [match[1][1]
for match in matches
if match[1][0] == i]
for j in range(count[1]):
if j not in counts1:
correct = False
missing.append([i, j])
else:
counts1.remove(j)
if counts1:
extra.append([i, counts1])
correct = False
if counts0:
extra.extend(counts0)
correct = False
elif len(matches) > 1:
correct = False
if correct or register in [
'PEX_inbound_IWBEAR',
'PEX_outbound_OTWBAR',
'P_CTPR',
'regs_ENDPTCTRL',
'P_IPIDR']:
# print('matches:', register, count,
# matches)
if 'count' in old_register:
del old_register['count']
if len(list(old_register.keys())) > 0:
new_register = deepcopy(old_register)
else:
new_register = tree()
if unused_register:
del (old_target['unused_registers']
[register])
else:
del old_target['registers'][register]
for match in matches:
temp_register = deepcopy(new_register)
temp_register['alias'] = {
'register': register}
if match[1] is not None:
(temp_register['alias']
['register_index']) = \
match[1]
if unused_register:
(old_target['unused_registers']
[match[0]]) = \
temp_register
else:
(old_target['registers']
[match[0]]) = \
temp_register
else:
print('\n\nincorrect match for',
register, count)
print(matches)
if missing:
print('missing', missing)
if extra:
print('extra', extra)
print('\n\n')
else:
if target in ['CPU', 'TLB', 'GPR'] or \
('CP' in old_target and old_target['CP']):
merged_targets['targets'][target]['core'] = True
missing = []
registers = list(old_target['registers'].keys())
if 'unused_registers' in old_target:
unused_registers = list(old_target['unused_registers'].keys())
else:
unused_registers = []
for register in registers + unused_registers:
unused_register = register in unused_registers
if unused_register:
old_register = old_target['unused_registers'][register]
else:
old_register = old_target['registers'][register]
other_register = None
if other_target is not None:
if register in other_target['registers']:
other_register = other_target['registers'][register]
elif 'unused_registers' in other_target and \
register in other_target['unused_registers']:
other_register = \
other_target['unused_registers'][register]
merged_register = merged_target['registers'][register]
if unused_register:
(merged_targets[old_type]
['targets'][target]
['unused_registers'][register])
if other_target is not None and other_register is None:
(merged_targets[other_type]
['targets'][target]
['unused_registers'][register])
missing.append(register)
missing_total += 1
elif other_target is not None and other_register is None:
(merged_targets[other_type]
['targets'][target]
['unused_registers'][register])
missing.append(register)
missing_total += 1
for key in [key for key in old_register.keys()
if key not in ['fields', 'unused_fields']]:
if key in ['access', 'CP', 'CRm', 'CRn', 'Op1', 'Op2',
'PMR', 'SPR', 'offset', 'limitations']:
merged_register[key] = old_register[key]
elif key == 'alias':
if unused_register:
(merged_targets[old_type]
['targets'][target]
['unused_registers'][register]
[key]) = old_register[key]
else:
(merged_targets[old_type]
['targets'][target]
['registers'][register]
[key]) = old_register[key]
elif key == 'actual_bits':
if old_register[key] != 32:
merged_register['bits'] = old_register[key]
elif key == 'bits':
if 'actual_bits' not in old_register:
merged_register[key] = old_register[key]
elif key == 'partial':
if 'unused_fields' not in old_register:
print('* partial register:', register,
'in target:', target)
elif key == 'count' and old_type == 'simics' and \
other_register is None:
merged_register[key] = old_register[key]
elif key in ['is_tlb', 'is_gcache']:
pass
else:
print('* key:', key, 'value:', old_register[key],
'in register:', register, 'in target:', target)
if 'fields' in old_register:
if old_type == 'jtag' or target == 'TLB' or \
other_register is None:
merged_register['fields'] = old_register['fields']
if 'unused_fields' in old_register:
merged_register['fields'].extend(
old_register['unused_fields'])
elif other_register is not None and \
'fields' in other_register:
other_fields = other_register['fields']
other_fields.sort(key=lambda x: x[1][1],
reverse=True)
fields = old_register['fields']
if 'unused_fields' in old_register:
fields.extend(old_register['unused_fields'])
fields.sort(key=lambda x: x[1][1], reverse=True)
for i in range(len(fields)):
if fields[i][0] != other_fields[i][0]:
print('field name mismatch',
target, register,
fields[i][0], other_fields[i][0])
elif fields[i][1][0] != \
other_fields[i][1][0] or \
fields[i][1][1] != \
other_fields[i][1][1]:
print('field range mismatch',
target, register, fields[i][0])
if 'unused_fields' in old_register:
if 'actual_bits' not in old_register:
print('* unused_fields found, but missing actual_bits',
register)
if 'partial' not in old_register:
print('* unused_fields found, but missing partial',
register)
if 'unused_fields' not in (
merged_targets[old_type]
['targets'][target]
['registers'][register]):
(merged_targets[old_type]
['targets'][target]
['registers'][register]
['unused_fields']) = []
unused_fields = (merged_targets[old_type]
['targets'][target]
['registers'][register]
['unused_fields'])
for field in old_register['unused_fields']:
if field[0] in unused_fields:
print('* duplicate field', register, field[0])
unused_fields.append(field[0])
unused_fields.sort()
if 'fields' in merged_register and \
target not in ['TLB', 'L1DCACHE0', 'L1ICACHE0',
'L1DCACHE1', 'L1ICACHE1', 'L2CACHE']:
merged_register['fields'].sort(key=lambda x: x[1][0],
reverse=True)
if 'bits' in merged_register:
bits = merged_register['bits']
else:
bits = 32
for field in merged_register['fields']:
bits -= (field[1][1] - field[1][0]) + 1
if bits != 0:
print('* bit count error:', register,
merged_register['fields'])
if missing:
print('*', target, 'registers in', old_type,
'but not', other_type+':', ', '.join(sorted(missing)))
if 'unused_targets' in merged_targets[other_type]:
if merged_targets[other_type]['unused_targets']:
merged_targets[other_type]['unused_targets'].sort()
else:
del merged_targets[other_type]['unused_targets']
save_targets('', device, merged_targets)
print('\ntotal missing registers:', missing_total)
for device in ['a9', 'p2020']:
merged_targets = load_targets('', device)
for type_ in 'jtag', 'simics':
for target in list(merged_targets[type_]['targets'].keys()):
if not merged_targets[type_]['targets'][target]:
del merged_targets[type_]['targets'][target]
else:
if 'unused_registers' in \
merged_targets[type_]['targets'][target] and \
not (merged_targets[type_]
['targets'][target]
['unused_registers']):
del (merged_targets[type_]
['targets'][target]
['unused_registers'])
if device == 'p2020':
merged_targets['jtag']['unused_targets'].append('RAPIDIO')
merged_targets['jtag']['unused_targets'].sort()
reg_count = 0
for target in list(merged_targets['targets'].keys()):
reg_count += len(list(
merged_targets['targets'][target]['registers'].keys()))
print(device, 'register count:', reg_count)
save_targets('', device, merged_targets)
| [
"os.path.abspath",
"collections.defaultdict",
"importlib.import_module",
"copy.deepcopy"
] | [((1658, 1686), 'importlib.import_module', 'import_module', (['"""src.targets"""'], {}), "('src.targets')\n", (1671, 1686), False, 'from importlib import import_module\n'), ((1784, 1801), 'collections.defaultdict', 'defaultdict', (['tree'], {}), '(tree)\n', (1795, 1801), False, 'from collections import defaultdict\n'), ((1627, 1644), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (1634, 1644), False, 'from os.path import abspath, dirname\n'), ((35173, 35195), 'copy.deepcopy', 'deepcopy', (['old_register'], {}), '(old_register)\n', (35181, 35195), False, 'from copy import deepcopy\n'), ((35697, 35719), 'copy.deepcopy', 'deepcopy', (['new_register'], {}), '(new_register)\n', (35705, 35719), False, 'from copy import deepcopy\n')] |
import logging
import pickle
import seaborn as sb
import torch
sb.set_style('whitegrid')
# Class for efficiently handling configurations and parameters, enables to
# easily set them and remember them when one config is reused
# Read with config.key, set with config.update({'key': value}) or config[
# 'key'] = value
default_config = dict(true_meas_noise_var=0.,
process_noise_var=0.,
simu_solver='dopri5',
nb_rollouts=0,
nb_loops=1,
rollout_length=100,
sliding_window_size=None,
verbose=False,
monitor_experiment=True,
multioutput_GP=False,
sparse=None,
memory_saving=False,
restart_on_loop=False,
meas_noise_var=0.1,
batch_adaptive_gain=None,
nb_plotting_pts=500,
no_control=False,
full_rollouts=False,
max_rollout_value=500)
class Config(dict):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Check that necessary keys have been filled in
mandatory_keys = ['system', 'nb_samples', 't0_span', 'tf_span', 't0',
'tf']
for key in mandatory_keys:
assert key in self, 'Mandatory key ' + key \
+ ' was not given.'
self['dt'] = (self.tf - self.t0) / (self.nb_samples - 1)
self['t_eval'] = torch.linspace(self.t0, self.tf, self.nb_samples)
if 'Continuous_model' in self['system']:
self['continuous_model'] = True
else:
self['continuous_model'] = False
if torch.cuda.is_available():
self['cuda_device'] = 'cuda:' + str(
torch.cuda.current_device())
else:
self['cuda_device'] = 'cpu'
# Fill other keys with default values
for key in default_config:
if key not in self:
self[key] = default_config[key]
if 'rollout_controller' not in self:
self['rollout_controller'] = \
{'random': self['nb_rollouts']}
# Warn / assert for specific points
if self.t0 != 0:
logging.warning(
'Initial simulation time is not 0 for each scenario! This is '
'incompatible with DynaROM.')
assert not (self.batch_adaptive_gain and ('adaptive' in self.system)), \
'Cannot adapt the gain both through a continuous dynamic and a ' \
'batch adaptation law.'
# Check same number of rollouts as indicated in rollout_controller
nb_rollout_controllers = 0
for key, val in self['rollout_controller'].items():
nb_rollout_controllers += val
assert nb_rollout_controllers == self['nb_rollouts'], \
'The number of rollouts given by nb_rollouts and ' \
'rollout_controller should match.'
# Check if contains init_state_obs_T but not the equivalent for u,
# in which case they are equal
if self.init_state_obs_T and self.init_state_obs_Tu is None:
self['init_state_obs_Tu'] = self.init_state_obs_T
def __getattr__(self, item):
try:
return self[item]
except KeyError:
if item.startswith('__') and item.endswith('__'):
raise AttributeError(item)
else:
if not 'reg' in item:
logging.info(f'No item {item}')
return None
def __setattr__(self, item, value):
try:
self[item] = value
except KeyError:
raise AttributeError(item)
def __getstate__(self):
return self.__dict__
def __setstate__(self, d):
self.__dict__.update(d)
def save_to_file(self, filename):
with open(filename, 'w') as f:
for key, val in self.items():
print(key, ': ', val, file=f)
class Test:
def __init__(self, config: Config):
self.a = 0
self.config = config
def __getattr__(self, item):
return self.config.__getattr__(item)
if __name__ == '__main__':
config = Config(system='Continuous/Louise_example/Basic_Louise_case',
nb_samples=int(1e4),
t0_span=0,
tf_span=int(1e2),
t0=0,
tf=int(1e2),
hyperparam_optim='fixed_hyperparameters')
test = Test(config)
print(test.config, test.config.t0, config.t0)
print('Test keys:')
for key in test.config:
print(key, test.config[key])
| [
"logging.warning",
"seaborn.set_style",
"torch.cuda.is_available",
"logging.info",
"torch.cuda.current_device",
"torch.linspace"
] | [((65, 90), 'seaborn.set_style', 'sb.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (77, 90), True, 'import seaborn as sb\n'), ((1620, 1669), 'torch.linspace', 'torch.linspace', (['self.t0', 'self.tf', 'self.nb_samples'], {}), '(self.t0, self.tf, self.nb_samples)\n', (1634, 1669), False, 'import torch\n'), ((1833, 1858), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1856, 1858), False, 'import torch\n'), ((2388, 2503), 'logging.warning', 'logging.warning', (['"""Initial simulation time is not 0 for each scenario! This is incompatible with DynaROM."""'], {}), "(\n 'Initial simulation time is not 0 for each scenario! This is incompatible with DynaROM.'\n )\n", (2403, 2503), False, 'import logging\n'), ((1925, 1952), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (1950, 1952), False, 'import torch\n'), ((3644, 3675), 'logging.info', 'logging.info', (['f"""No item {item}"""'], {}), "(f'No item {item}')\n", (3656, 3675), False, 'import logging\n')] |