seq_id string | text string | repo_name string | sub_path string | file_name string | file_ext string | file_size_in_byte int64 | program_lang string | lang string | doc_type string | stars int64 | dataset string | pt string | api list |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16275076473 | import json
import sys
import argparse
import os
APPROX = 0.1
def isNumber(num):
isNum = False
try:
float(num)
isNum = True
except Exception as e:
isNum = False
return isNum
nameList = list()
def compareAny(self, other):
diff = list()
for att in self.attScalarList:
selfAtt = getattr(self, att)
otherAtt = getattr(other, att)
if 'compare' in dir(selfAtt) and 'compare' in dir(otherAtt):
nameList.append(self.name)
nameList.append(att)
retDiff = selfAtt.compare(otherAtt)
if len(retDiff):
diff += retDiff
nameList.pop()
nameList.pop()
continue
exact = True
if isNumber(selfAtt) and isNumber(otherAtt):
exact = False
selfAtt = float(selfAtt)
otherAtt = float(otherAtt)
if (exact and selfAtt != otherAtt) or (not exact and abs(selfAtt-otherAtt)>abs(selfAtt)*APPROX):
# print((exact and selfAtt != otherAtt), (not exact and abs(selfAtt-otherAtt)>abs(selfAtt)*APPROX), selfAtt, otherAtt, '--'*10)
diff.append(['_'.join(nameList)+'_'+self.name+'_'+att, selfAtt, otherAtt])
for attdName in self.attDictList:
attDSelf = getattr(self, attdName)
attDOther = getattr(other, attdName)
attDSelfKeys = set(attDSelf.keys())
attDOtherKeys = set(attDOther.keys())
if len(attDSelfKeys.symmetric_difference(attDOtherKeys)):
diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_DifferentKeys' , list(attDSelf.keys()), list(attDOther.keys())])
attDAll = set()
[attDAll.add(x) for x in attDSelf]
[attDAll.add(x) for x in attDOther]
for attV in attDAll:
if attV in attDSelf and attV in attDOther:
if 'compare' in dir(attDSelf[attV]) and 'compare' in dir(attDOther[attV]):
nameList.append(self.name)
nameList.append(attdName)
retDiff = attDSelf[attV].compare(attDOther[attV])
if len(retDiff):
diff += retDiff
nameList.pop()
nameList.pop()
continue
elif isNumber(attDSelf[attV]) and isNumber(attDOther[attV]):
selfAtt = float(attDSelf[attV])
otherAtt = float(attDOther[attV])
if abs(selfAtt-otherAtt)>selfAtt*APPROX:
diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , attDSelf[attV], attDOther[attV]])
continue
else:
if attDSelf[attV] != attDOther[attV]:
diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , attDSelf[attV], attDOther[attV]])
for attdName in self.attListList:
selfO = getattr(self, attdName)
othrO = getattr(other, attdName)
selfLen = len(selfO)
otherLen = len(othrO)
if selfLen != otherLen:
diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_Length' , selfLen, otherLen])
continue
if selfO == othrO: continue
for ind in range(selfLen):
if 'compare' in dir(selfO[ind]) and 'compare' in dir(othrO[ind]):
nameList.append(self.name)
nameList.append(attdName)
retDiff = selfO[ind].compare(othrO[ind])
if len(retDiff):
diff += retDiff
nameList.pop()
nameList.pop()
continue
elif isNumber(selfO[ind]) and isNumber(othrO[ind]):
selfAtt = float(selfO[ind])
otherAtt = float(othrO[ind])
if abs(selfAtt-otherAtt)>selfAtt*APPROX:
diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , selfO[ind], othrO[ind]])
continue
else:
if selfO[ind] != othrO[ind]:
diff.append(['_'.join(nameList)+'_'+self.name+'_'+attdName+'_'+attV , selfO[ind], othrO[ind]])
return diff
class App:
class Access:
attScalarList = ['calls', 'amount', 'CacheLineNumber', 'CacheLineUtil', 'used', 'strideSumm', 'pattern', 'accessSize', 'intensity', 'execSize', 'isSlm', 'bti'] # TODO , 'CacheLineMax', 'CacheLineMin'
attDictList = ['stride'] # TODO
attListList = ['distribution', 'sends', 'sourceMap'] # TODO
def __init__(self, data):
for att in self.attScalarList:
setattr(self, att, data[att])
for att in self.attDictList:
setattr(self, att, data[att])
for att in self.attListList:
setattr(self, att, data[att])
self.name = '0x0' if len(data['sends']) == 0 else str(data['sends'][0])
def compare(self, other):
return compareAny(self, other)
class SendData:
attScalarList = ['calls', 'amount', 'CacheLineNumber', 'CacheLineUtil', 'used', 'transferred', 'strideSumm', 'pattern'] # , 'CacheLineMax', 'CacheLineMin'
attDictList = ['stride']
attListList = ['distribution']
def __init__(self, data):
for att in self.attScalarList:
setattr(self, att, data[att])
self.stride = data['stride']
self.distribution = data['distribution']
self.name = str(data['name'])
def compare(self, other):
return compareAny(self, other)
class AggrD:
mems = ['Local', 'Global']
rws = ['Read', 'Write']
tus = ['Used', 'Transferred', 'CacheLineNumber', 'Calls']
def getListAttributes(self):
ls = list()
for mem in App.AggrD.mems:
for rw in App.AggrD.rws:
for tu in App.AggrD.tus:
ls.append('ad{}{}{}'.format(mem, rw, tu))
return ls
def __init__(self, data):
self.attScalarList = self.getListAttributes()
self.attDictList = []
self.attListList = []
for att in self.attScalarList:
setattr(self, att, data[att])
self.name = 'name'
def compare(self, other):
return compareAny(self, other)
class Kernel:
class Enqueue:
attScalarList = ['id', 'totalThreadsExecuted', 'aggregatedDataTotal', 'aggregatedDataAvg']
attDictList = ['sendDataTotal']
# attDictList = []
attListList = ['accesses']
def __init__(self, data):
for att in self.attScalarList:
setattr(self, att, data[att])
self.sendDataTotal = dict()
for ky in data['sendDataTotal']:
data['sendDataTotal'][ky]['name'] = str(ky)
self.sendDataTotal[ky] = App.SendData(data['sendDataTotal'][ky])
self.aggregatedDataTotal = App.AggrD(data['aggregatedDataTotal'])
self.aggregatedDataAvg = App.AggrD(data['aggregatedDataAvg'])
self.accesses = list()
for acc in data['accesses']:
self.accesses.append(App.Access(acc))
self.name = str(data['id'])
def compare(self, other):
return compareAny(self, other)
attScalarList = ['name', 'enqueueNum', 'accessNum']
attDictList = ['enqueues']
attListList = []
def __init__(self, data):
for att in self.attScalarList:
setattr(self, att, data[att])
self.enqueues = dict()
for enqueue in data['enqueues']:
self.enqueues[enqueue] = App.Kernel.Enqueue(data['enqueues'][enqueue])
self.name = str(data['name'])
def compare(self, other):
return compareAny(self, other)
attScalarList = ['name', 'collectPercentage', 'envVars', 'analysisVersion'] # 'sourceFiles', 'date', 'resultsDir', 'applicationBin', 'workDirectory',
attDictList = ['kernels']
attListList = ['parameters']
def __init__(self, data):
for att in App.attScalarList:
setattr(self, att, data[att])
self.kernels = dict()
for kernelName in data["kernels"]:
self.kernels[kernelName] = App.Kernel(data["kernels"][kernelName])
self.parameters = data['parameters']
self.name = str(data['name'])
def __str__(self):
string = ''
for att in App.attScalarList:
string += '{}:{}, '.format(att,getattr(self, att))
return string
def compare(self, other):
return compareAny(self, other)
def readResults(path):
with open(path) as f:
data = json.load(f)
return App(data)
def main(argv):
parser = argparse.ArgumentParser(description='GPU Memory Access Ananlysis')
parser.add_argument(
'-r1',
metavar='DIRECTORY',
default='',
dest='results1',
type=str,
help='first result')
parser.add_argument(
'-r2',
metavar='DIRECTORY',
default='',
dest='results2',
type=str,
help='second result')
parser.add_argument(
'-f',
metavar='DIRECTORY',
default='',
dest='folder',
type=str,
help='Report directory')
if argv == 'sys':
args = parser.parse_args()
elif isinstance(argv, list):
args = parser.parse_args(argv)
else:
print('Arguments not recognized')
return -1
results1 = readResults(args.results1)
# print(results1)
results2 = readResults(args.results2)
# print(results2)
# print('calc diff')
diff = results1.compare(results2)
# print txt
print('\n\n\nDIFFERENCE:')
print(diff.__str__().replace('[','\n['))
if os.path.isdir(args.folder):
# save diff to json
with open(os.path.join(args.folder, 'compare_report.json'), 'w') as f:
f.write(json.dumps(diff))
# save to txt
with open(os.path.join(args.folder, 'compare_report.txt'), 'w') as f:
f.write(diff.__str__().replace('[','\n['))
return len(diff)
if __name__ == '__main__':
sys.exit(main('sys'))
| Priyankajaiswalintel/gramine | latest/bin64/gma/MAAT/compare.py | compare.py | py | 10,364 | python | en | code | null | github-code | 36 | [
{
"api_name": "json.load",
"line_number": 206,
"usage_type": "call"
},
{
"api_name": "argparse.ArgumentParser",
"line_number": 210,
"usage_type": "call"
},
{
"api_name": "os.path.isdir",
"line_number": 253,
"usage_type": "call"
},
{
"api_name": "os.path",
"lin... |
23268928678 | #import sys, os
#sys.path.append(os.path.abspath(""))
from functionsDB.ConnectionDB import abrirconexion, cerrarconexion
from functionsDB.entity.comentario import Comentario
from datetime import datetime
def altacomentario(comentario):
cur,con = abrirconexion()
sql = "insert into comentario(fecha,hora,contenido,usuario,producto) values('"+comentario.get_fecha()+"','"+comentario.get_hora()+"','"+comentario.get_contenido()+"','"+comentario.get_usuario()+"','"+str(comentario.get_producto())+"')"
cur.execute(sql)
cerrarconexion(cur,con)
def bajacomentario(comentario):
cur,con = abrirconexion()
sql = "delete from comentario where codigo= '"+str(comentario.get_codigo())+"'"
cur.execute(sql)
cerrarconexion(cur,con)
def modificarcomentario(comentario):
cur,con = abrirconexion()
sql = "update comentario set fecha='"+comentario.get_fecha()+"', hora='"+comentario.get_hora()+"', contenido='"+comentario.get_contenido()+"', usuario='"+comentario.get_usuario()+"', producto='"+str(comentario.get_producto())+"' where codigo='"+str(comentario.get_codigo())+"'"
cur.execute(sql)
cerrarconexion(cur,con)
def listadocomentarios():
results = []
cur,con = abrirconexion()
sql = "select c.codigo,c.fecha,c.hora,c.contenido,c.usuario,c.producto,u.urlfoto from comentario c, usuario u where u.email=c.usuario"
cur.execute(sql)
columns = list(map(lambda x: x[0], cur.description))
for row in cur.fetchall():
results.append(dict(zip(columns, row)))
fecha = results[-1]['fecha']
hora = results[-1]['hora']
fecha = datetime(fecha.year, fecha.month, fecha.day)
hora = datetime(fecha.year, fecha.month, fecha.day, hora.hour, hora.minute, hora.second)
results[-1]['fecha'] = fecha.strftime('%Y-%m-%d')
results[-1]['hora'] = hora.strftime('%H:%M:%S')
cerrarconexion(cur,con)
return results
"""
now = datetime.now()
coment = Comentario()
coment.set_codigo(12)
coment.set_fecha(str(now.year)+'-'+str(now.month)+'-'+str(now.day))
coment.set_hora(str(20)+':'+str(12)+':'+str(now.second))
coment.set_contenido('mensaje de error')
coment.set_usuario("exe.gye@gmail.com")
coment.set_producto(2)
"""
#altacomentario(coment)
#modificarcomentario(coment)
#bajacomentario(coment)
| exegonzalez/Taller-de-Integracion | App/src/functionsDB/ABMComentario.py | ABMComentario.py | py | 2,295 | python | es | code | 1 | github-code | 36 | [
{
"api_name": "functionsDB.ConnectionDB.abrirconexion",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "functionsDB.ConnectionDB.cerrarconexion",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "functionsDB.ConnectionDB.abrirconexion",
"line_number": 15,
... |
2762523271 | from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(__name__)
line_bot_api = LineBotApi('1l6c8hOlVNiLh23YRFrdl1TxJxK4KUZppI9dRaDscY5fX50D6xEBhb4D0ZglujEA1+MiFoFV2N5pl1KIYZmlq8/WSmxf2b4WVhcvfjJoUH7ISxjUDK55FzS1B3DhC6X4/m4ZM0/0bN7HRNzLzKToewdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('3692fbc3db90c226b12e3f91130e2f9f')
@app.route("/callback", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text))
| vacharich1/testme | bot_test.py | bot_test.py | py | 1,126 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask.Flask",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "linebot.LineBotApi",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "linebot.WebhookHandler",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "flask.request.h... |
15672169459 | from datetime import datetime
import logging
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('discord').setLevel(logging.INFO)
dt_fmt = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(format='[{asctime}] [{levelname:<8}] [{name:<15}]: {message}',
style='{',
datefmt='%Y-%m-%d %H:%M:%S')
dt_format_o = "%Y %Y-%m-%d %H:%M:%S"
import fastf1 as ff1
import os
import drivers
import requests
try:
ff1.Cache.enable_cache("/ff1cache")
except NotADirectoryError:
os.makedirs("/ff1cache", exist_ok=True)
drivers_table = drivers.drivers_table()
teams = ["Red Bull", "Ferrari", "Mercedes", "McLaren", "Alpine", "Alfa Romeo", "AlphaTauri", "Haas", "Aston Martin",
"Williams"]
schedule = [datetime(2023, 3, 4, 20, 29),
datetime(2023, 3, 18, 22, 29),
datetime(2023, 4, 1, 10, 29),
datetime(2023, 4, 29, 18, 59),
datetime(2023, 5, 7, 1, 29),
datetime(2023, 5, 27, 19, 29),
datetime(2023, 6, 3, 19, 29),
datetime(2023, 6, 18, 1, 29),
datetime(2023, 7, 1, 19, 59),
datetime(2023, 7, 8, 19, 29),
datetime(2023, 7, 22, 19, 29),
datetime(2023, 7, 29, 19, 59),
datetime(2023, 8, 26, 18, 29),
datetime(2023, 9, 2, 19, 29),
datetime(2023, 9, 16, 18, 29),
datetime(2023, 9, 23, 11, 29),
datetime(2023, 10, 7, 19, 59),
datetime(2023, 10, 22, 3, 29),
datetime(2023, 10, 29, 2, 29),
datetime(2023, 11, 3, 23, 59),
datetime(2023, 11, 18, 13, 29),
datetime(2023, 11, 25, 19, 29)]
def returnNextEvent():
next_event: ff1.events.EventSchedule = ff1.get_events_remaining().head(1)
# logging.info(next_event.to_string())
ne_round = next_event.iat[0, 0]
ne_location = next_event.iat[0, 1]
if ne_location == 'United States':
ne_location = 'USA'
ne_date = next_event.iat[0, 4]
ne_name = next_event.iat[0, 5]
ne_type = next_event.iat[0, 6]
ne_session_data = {}
for i in range(0, 5, 2):
ne_session_data[next_event.iat[0, 7 + i]] = next_event.iat[0, 7 + i + 1]
return {'round': ne_round,
'loc': ne_location,
'date': ne_date,
'name': ne_name,
'type': ne_type,
'session': ne_session_data
}
def returnCurrentRoundNum():
# next_event: ff1.events.EventSchedule = ff1.get_events_remaining().head(1)
# ne_round = next_event.iat[0, 0]
# print(next_event)
for i, date in enumerate(schedule):
if datetime.now() < date:
return i + 1
return 24
def returnEvent(identifier):
se: ff1.events.Event = ff1.get_event(datetime.now().year, identifier)
# print(se)
ser = se.iat[0]
sel = se.iat[1]
sed = se.iat[4]
sen = se.iat[5]
sety = se.iat[6]
if ser < returnCurrentRoundNum() and drivers_table.results.get(str(ser)) is not None:
return {'round': ser,
'loc': sel,
'date': sed,
'name': sen,
'type': sety,
'results': drivers_table.results[str(ser)]
}
else:
return {'round': ser,
'loc': sel,
'date': sed,
'name': sen,
'type': sety,
}
def returnRoundsInYear(year=datetime.now().year):
cal = ff1.events.get_event_schedule(year=year, include_testing=False).tail(1)
return cal.iat[0, 0]
def returnGPQuali(pgp):
if drivers_table.quali_results.get(str(pgp)) is not None:
return drivers_table.quali_results.get(str(pgp))
else:
if returnEvent(pgp)["type"] == "sprint":
keyword = "sprint"
else:
keyword = "qualifying"
url = f"https://ergast.com/api/f1/{datetime.now().year}/{pgp}/{keyword}.json"
response = requests.get(url)
data = response.json()["MRData"]["RaceTable"]["Races"]
if len(data) == 0:
return None
else:
drivers_table.quali_results[str(pgp)] = [dr["Driver"]["code"] for dr in data[0]["QualifyingResults"]]
return drivers_table.quali_results[str(pgp)]
# return ["LEC", "VER", "HAM", "PER", "RUS", "NOR", "ALO", "OCO", "GAS", "ZHO"]
def returnRaceResults(r):
if drivers_table.results.get(str(r)) is not None:
return drivers_table.results.get(str(r))
else:
url = f"https://ergast.com/api/f1/{datetime.now().year}/{r}/results.json"
response = requests.get(url)
data = response.json()["MRData"]["RaceTable"]["Races"]
if len(data) == 0:
return None
else:
drivers_table.results[str(r)] = [dr["Driver"]["code"] for dr in data[0]["Results"]]
return drivers_table.results[str(r)]
def verifyTeam(t):
return t if t in teams else 'NaN'
# print(returnCurrentRoundNum())
| nERD8932/LVSF1Bot | scripts/f1module.py | f1module.py | py | 4,985 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "logging.getLogger",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
... |
150466023 | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse, reverse_lazy
from django.views import generic
from django.views import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Play, Game
from play.forms import PlayCreateForm
from datetime import datetime
from datetime import date
# Create your views here.
class PlayCreate(View):
def post(self, request):
# Create a form instance and populate it with data from the request (binding):
form = PlayCreateForm(request.POST)
if form.is_valid():
play = Play()
# process the data in form.cleaned_data as required (here we just write it to the model location field)
play.game = form.cleaned_data['game']
play.location = form.cleaned_data['location']
play.play_date = form.cleaned_data['play_date']
play.play_complete = form.cleaned_data['play_complete']
play.save()
return HttpResponseRedirect(reverse('start-play') )
else:
proposed_location = "xxx"
proposed_date = date.today()
form = PlayCreateForm(initial={'location': proposed_location, 'play_date': proposed_date})
context = {'form':form,}
return render(request, 'play_form.html', context)
def get(self, request):
proposed_location = ""
proposed_date = date.today()
form = PlayCreateForm(initial={'location': proposed_location, 'play_date': proposed_date})
context = {'form':form,}
return render(request, 'play_form_new.html', context)
class PlayUpdate(View):
model = Play()
def post(self, request, pk):
play = get_object_or_404(Play, pk=pk)
# Create a form instance and populate it with data from the request (binding):
form = PlayCreateForm(request.POST)
if form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model location field)
play.game = form.cleaned_data['game']
play.location = form.cleaned_data['location']
play.play_date = form.cleaned_data['play_date']
play.play_complete = form.cleaned_data['play_complete']
play.save()
return HttpResponseRedirect(reverse('play-list') )
context = {'form':form, 'game_desc': play.game.description}
return render(request, 'play_form.html', context)
def get(self, request, pk):
play = get_object_or_404(Play, pk=pk)
form = PlayCreateForm(initial={'location': play.location, 'play_date': play.play_date, 'play_complete': play.play_complete})
context = {'form':form,'game_desc': play.game.description}
return render(request, 'play_form_update.html', context)
class PlayListView(generic.ListView):
model = Play
queryset = Play.objects.filter(play_complete = False)
class PlayArchiveListView(generic.ListView):
model = Play
context_object_name = 'play_archive_list'
queryset = Play.objects.filter(play_complete = True)
template_name = 'play/play_archive_list.html'
class PlayDetailView(generic.DetailView):
model = Play
class PlayDelete(generic.DeleteView):
model = Play
success_url = reverse_lazy('play-list') | edbranson/scorekeeping | scorekeeping/play/views.py | views.py | py | 3,501 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.views.View",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "play.forms.PlayCreateForm",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "play.forms",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "models.Play",
... |
1467605788 | # from PIL import Image
#
# def abrirImagem():
# im = Image.open("sample-image.png")
#
#
import csv
import sqlite3
from PIL import Image
def abrir_imagem(imagem):
#im = Image.open("sample-image.png")
im = Image.open(imagem)
im.show()
def consultar_imagem(item):
try:
con = sqlite3.connect('catalogo.db')
cur = con.cursor()
dados = (item[0])
cur.execute('SELECT imagem FROM produtos WHERE codcli = ?',(dados,))
con.commit()
resposta = cur.fetchone()
nome_arquivo = f'c:\marcelo\projetos\python\catalogo\imgconv\{item[0]}.jpg'
writeTofile(resposta[0], nome_arquivo)
abrir_imagem(nome_arquivo)
print(f'Código {item[0]} consultado com sucesso.')
cur.close()
con.close()
except sqlite3.Error as erro:
print(f'Erro na consulta {item[0]}.',erro)
def convertToBinaryData(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData
def writeTofile(data, filename):
# Convert binary data to proper format and write it on Hard Disk
with open(filename, 'wb') as file:
file.write(data)
print(filename)
print("Stored blob data into: ", filename, "\n")
def inserir_bd(item):
try:
con = sqlite3.connect('catalogo.db')
cur = con.cursor()
cur.execute('insert into prod_cliente (codpro, descricao, embalagem, preco_cx, preco_un, cod_barras, categoria) values (?,?,?,?,?,?,?)',item,)
con.commit()
#print(f'Item {item[0]} incluso com sucesso.')
cur.close()
con.close()
except sqlite3.Error as erro:
print(f'Erro na inclusão {item[0]}.',erro)
def contar_itens():
con = sqlite3.connect('catalogo.db')
cur = con.cursor()
cur.execute('SELECT * FROM prod_cliente',)
print(f'Quantidade de itens inseridos no catálogo: {len(cur.fetchall())}')
cur.close()
con.close()
def inserir_imagem(item):
try:
con = sqlite3.connect('catalogo.db')
cur = con.cursor()
dados = (None,item[6], item[0])
cur.execute('INSERT INTO produtos (cod_barras, imagem, codcli) values (?, ?, ?)',dados,)
con.commit()
print(f'Código {item[0]} atualizado com sucesso.')
cur.close()
con.close()
except sqlite3.Error as erro:
print(f'Erro na atualização {item[0]}.',erro)
def atualizar_bd(item):
try:
con = sqlite3.connect('catalogo.db')
cur = con.cursor()
#soh atualiza com preco diferente
# dados = (item[1],item[2], item[3], item[4],item[5], item[6], item[0],item[3])
# cur.execute('UPDATE prod_cliente SET descricao = ?, embalagem = ?, preco_cx = ?, preco_un = ?, cod_barras = ?, categoria = ? WHERE codpro = ? and preco_cx != ?',dados,)
#atualiza tudo
dados = (item[1],item[2], item[3], item[4],item[5], item[6], item[0])
cur.execute('UPDATE prod_cliente SET descricao = ?, embalagem = ?, preco_cx = ?, preco_un = ?, cod_barras = ?, categoria = ? WHERE codpro = ?',dados,)
con.commit()
print(f'Código {item[0]} atualizado com sucesso.')
cur.close()
con.close()
except sqlite3.Error as erro:
print(f'Erro na atualização {item[0]}.',erro)
def ler_arquivo():
with open ('produtos.txt', 'r') as f:
lista = []
for row in csv.reader(f,delimiter=';'):
lista.append(row)
for linha in lista:
item = []
preco_novo = linha[6].replace(',','.')
preco_novo = "{:.2f}".format(float(preco_novo))
##Troca , por .
preco_novo_un = linha[8].replace(',','.')
##tranforma para numero real com 2 digitos apos o ponto
preco_novo_un = "{:.2f}".format(float(preco_novo_un))
# if preco_novo_un == '0.00':
# print("Código: " + linha[0] + " Descrição: " + linha[1] + " Emb: " + linha[3] + " Preço un: R$ " + str(
# preco_novo))
# else:
# print("Código: "+linha[0]+" Descrição: "+linha[1]+" Emb: "+linha[3]+" Preço cx: R$ "+str(preco_novo)+ " Preço un: R$ "+str(preco_novo_un))
item.append(linha[0])
item.append(linha[1])
item.append(linha[3])
item.append(linha[6])
if linha[8] !='0':
item.append(linha[8])
else:
item.append(linha[6])
item.append(0000000000000) #codigo de barras
categoria = linha[11].split(' ')
#print(categoria[1])
#Coloca os nomes das categorias no BD
#categoria = linha[11]
if categoria[1] == 'ADAMS' or categoria[1] == 'ARCOR' or categoria[1] == 'CAMPESTRE' or categoria[1] == 'DALVA' or categoria[1] == 'DORI' or categoria[1] == 'AMENDUPA' or categoria[1] == 'FINI' or categoria[1] == 'FLORESTAL' or categoria[1] == 'Jazam' or categoria[1] == 'LUIZ' or categoria[1] == 'PECCIN' or categoria[1] == 'RICLAN' or categoria[1] == 'SANTA' or categoria[1] == 'Uniao' or categoria[1] == 'GAROTO' or categoria[1] == 'Quero' or categoria[1] == 'NESTLE':
item.append('DOCES e SALGADINHOS')
#categoria[1]= 'DOCES e SALGADINHOS'
elif categoria[1] == 'BDL' or categoria[1] == 'ADN' or categoria[1] == 'BIC' or categoria[1] == 'DEYCON' or categoria[1] == 'FEIJAO' or categoria[1] == 'ERVA' or categoria[1] == 'FEIJAO' or categoria[1] == 'GERAL' or categoria[1] == 'KRAFT' or categoria[1] == 'LIMPINHA' or categoria[1] == 'MARANATA' or categoria[1] == 'MARTINS' or categoria[1] == 'MEMPHIS' or categoria[1] =='OWENS-ILLINOIS' or categoria[1] == 'VASSOURAS' or categoria[1] == 'ZETTAPACK'or categoria[1] == 'TELL'or categoria[1] == 'ODERICH' or categoria[1] == 'Mococa' or categoria[1] == 'Queijo' :
item.append('MERCEARIA')
#categoria[1] == 'MERCEARIA'
elif categoria[1] == 'FONT' or categoria[1] == 'BEBIDAS' or categoria[1] == 'PINGO' or categoria[1] == 'SUCO':
item.append('BEBIDAS')
#categoria[1] == 'BEBIDAS'
elif categoria[1] == 'GIRANDO' or categoria[1] == 'SANY' or categoria[1] == 'BRILHOLAC':
#categoria[1] == 'GIRANDO SOL'
item.append('LIMPEZA')
elif categoria[1] == 'DU':
#categoria[1] == 'CONDIMENTOS'
item.append('CONDIMENTOS')
elif categoria[1] == 'ELMA':
#categoria[1] == 'ELMA CHIPS'
item.append('ELMA CHIPS')
elif categoria[1] == 'Biscoitos':
item.append('Biscoitos SAGRA')
elif categoria[1] == 'TUBARAO' or categoria[1] == 'SIRIUS' or categoria[1] == 'HIGIE' or categoria[1] == 'TISCOSKI' or categoria[1] == 'GREEN' or categoria[1] == 'FRALDA':
#categoria[1] == 'HIGIENE PESSOAL'
item.append('HIGIENE PESSOAL')
elif categoria[1] == 'MC' or categoria[1] == 'ORLEPLAST' or categoria[1] == 'PLAZAPEL' or categoria[1] == 'LIPLAST' or categoria[1] == 'TOTALPLAST'or categoria[1] == 'EMBRAST'or categoria[1] == 'VABENE':
#categoria[1] == 'DESCARTÁVEIS'
item.append('DESCARTÁVEIS')
elif categoria[1] == 'MULTINACIONAL' or categoria[1] == 'PLASCOR' or categoria[1] == 'RELUZ' or categoria[1] == 'OUROLUX' or categoria[1] == 'PARANA'or categoria[1] == 'PIRISA' or categoria[1] == 'BLUMENAU' or categoria[1] == 'Alcool' or categoria[1] == 'CARVAO' or categoria[1] == 'THREE' or categoria[1] == 'FIBRAFORM':
#categoria[1] == 'UTILIDADES'
item.append('BAZAR E UTILIDADES')
else:
item.append(categoria[1])
#Aqui insere todos os itens novamente
inserir_bd(item)
#Aqui eh pra usar opcao de atualizar os preços
#atualizar_bd(item)
#img = convertToBinaryData('img/semfoto.jpg')
#item.append(img)
#inserir_imagem(item)
def listar_produtos():
try:
con = sqlite3.connect('catalogo.db')
cur = con.cursor()
produtos=[]
# cur.execute('SELECT codpro, descricao, categoria, embalagem, preco_cx, preco_un FROM prod_cliente ORDER BY categoria, descricao')
cur.execute(
'SELECT codpro, descricao, categoria, embalagem, preco_cx, preco_un, categoria FROM prod_cliente WHERE categoria NOT Null ORDER BY categoria, descricao')
produtos = cur.fetchall()
cur.close()
con.close()
return produtos
except sqlite3.Error as erro:
print('Erro na consulta.',erro)
def apagar_itens_cliente():
try:
con = sqlite3.connect('catalogo.db')
cur = con.cursor()
cur.execute(
'DELETE FROM prod_cliente')
print(f'Total de itens apagados: {cur.rowcount}')
con.commit()
cur.close()
con.close()
except sqlite3.Error as erro:
print('Erro ao apagar itens do banco.',erro)
if __name__ == '__main__':
apagar_itens_cliente()
ler_arquivo()
contar_itens()
#tt = []
#tt.append('2327')
#consultar_imagem(tt)
| marcelocaon/gerador_catalogo_produtos | main.py | main.py | py | 9,572 | python | pt | code | 1 | github-code | 36 | [
{
"api_name": "PIL.Image.open",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_number": 14,
"usage_type": "name"
},
{
"api_name": "sqlite3.connect",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "sqlite3.Error",
"line_nu... |
18515443128 | from sets import Set
from collections import defaultdict
class MagicDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
def buildDict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
self.data = defaultdict(int)
self.original = Set(dict)
for w in dict:
for i in xrange(len(w)):
can = w[:i]+"_"+w[i+1:]
self.data[can] += 1
# print can
# print self.data
def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
double = False
if word in self.original:
double = True
for i in xrange(len(word)):
can = word[:i]+"_"+word[i+1:]
if double:
if can in self.data and self.data[can] >= 2:
return True
else:
if can in self.data:
return True
return False
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dict)
# param_2 = obj.search(word)
#Implement Magic Dictionary | jimmy623/LeetCode | Solutions/Implement Magic Dictionary.py | Implement Magic Dictionary.py | py | 1,413 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "collections.defaultdict",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "sets.Set",
"line_number": 17,
"usage_type": "call"
}
] |
2521012317 | import configparser
import html
from pathlib import Path
from pprint import pformat
from urllib.parse import urlparse
import boto3
import botocore.model
import botocore.utils
from IPython.core.display import HTML
from jinja2 import Environment, FileSystemLoader
from pygments import highlight
from pygments.formatters import Terminal256Formatter
from pygments.lexers import PythonLexer
AWS_US_REGIONS = ["us-east-1", "us-east-2", "us-west-1", "us-west-2"]
AWS_CA_REGIONS = ["ca-central-1"]
AWS_SA_REGIONS = ["sa-east-1"]
AWS_EU_REGIONS = ["eu-west-3", "eu-west-2", "eu-west-1", "eu-central-1"]
AWS_ASIA_REGIONS = [
"ap-south-1",
"ap-northeast-2",
"ap-northeast-1",
"ap-southeast-1",
"ap-southeast-2",
]
AWS_ALL_REGIONS = (
AWS_US_REGIONS
+ AWS_CA_REGIONS
+ AWS_SA_REGIONS
+ AWS_EU_REGIONS
+ AWS_ASIA_REGIONS
)
AWS_SERVICES_CONDENSED = [
"cloudfront",
"cloudtrail",
"ec2",
"s3",
"elb",
"iam",
"rds",
"route53",
"route53domains",
"sns",
"sqs",
"sts",
]
AWS_SERVICES_DATA = [
"athena",
"rds",
"dynamodb",
"elasticache",
"redshift",
"neptune",
"dms",
]
AWS_SERVICES_COMPUTE = ["ec2", "lambda", "stepfunctions"]
AWS_SERVICES_OPS = ["cloudformation", "opsworks", "opsworkscm", "ssm"]
AWS_SERVICES_MGMT = [
"cloudtrail",
"cloudwatch",
"budgets",
"config",
"cur",
"events",
"iam",
"logs",
"organizations",
"pricing",
"servicecatalog",
"ssm",
"sts",
]
def list_profile_names(profile_exclusions=[], keyword_exclusions=[]):
config = configparser.ConfigParser()
config.read(Path("~/", ".aws", "config").expanduser())
profile_names = [
section.replace("profile ", "") for section in config.sections()
]
exclude = profile_exclusions + [
x for x in profile_names for kw in keyword_exclusions if kw in x
]
profile_list = [x for x in profile_names if x not in exclude]
return profile_list
def list_regions():
sess = boto3.session.Session(profile_name=list_profile_names()[0])
ec2 = sess.client("ec2", "us-east-1")
regions = ec2.describe_regions().get("Regions")
return [region.get("RegionName") for region in regions]
def list_services_for_region(region):
sess = boto3.session.Session(
profile_name=list_profile_names()[0], region_name=region
)
return sess.get_available_services()
def pprint_color(obj):
print(highlight(pformat(obj), PythonLexer(), Terminal256Formatter()))
def render_template(template_file, **kwargs):
templateLoader = FileSystemLoader(searchpath="./")
templateEnv = Environment(loader=templateLoader)
template = templateEnv.get_template(template_file)
outputText = template.render(**kwargs)
return outputText
def get_shape_data(client, shape_for):
shape = client.meta.service_model.shape_for(shape_for)
shape_return = {
botocore.model.StringShape: lambda x: dict(
enum=x.enum, docs=x.documentation
),
botocore.model.StructureShape: lambda x: dict(
name=x.name,
required=x.required_members,
members={
k: get_shape_data(client, v.name) for k, v in x.members.items()
},
docs=x.documentation,
),
botocore.model.ListShape: lambda x: get_shape_data(
client, x.member.name
),
botocore.model.MapShape: lambda x: dict(
type=str(type(x)), name=x.name
),
botocore.model.Shape: lambda x: dict(type=x.name),
}
return shape_return.get(type(shape), lambda x: dict())(shape)
def generate_cloudtrail_reference(region="us-east-1", svc_include=None):
"""
Generates a dictionary object containing a quick reference of event sources
and event function names for every AWS service or only the services included
in `svc_include`.
"""
if svc_include is None:
svc_include = []
session = boto3.session.Session(region_name=region)
services = session.get_available_services()
if len(svc_include) > 0:
services = {
svc_name: session.client(svc_name)
for svc_name in services
if svc_name in svc_include
}
else:
services = {
svc_name: session.client(svc_name)
for svc_name in services
}
data = {
svc_name: dict(
EventSource=urlparse(client.meta.endpoint_url).netloc.replace(
f"{region}.", ""
),
EventNames=client.meta.service_model.operation_names,
)
for svc_name, client in services.items()
}
return data
def generate_json_input_for(method):
client = method.__self__
method_name = client.meta.method_to_api_mapping[method.__func__.__name__]
arg_gen = botocore.utils.ArgumentGenerator()
input_model = arg_gen.generate_skeleton(
client.meta.service_model.operation_model(method_name).input_shape
)
return input_model
def generate_html_for(method, param_name=None):
page_src = ""
client = method.__self__
method_name = client.meta.method_to_api_mapping[method.__func__.__name__]
if param_name is None:
for key, val in client.meta.service_model.operation_model(
method_name
).input_shape.members.items():
docs = (
client.meta.service_model.operation_model(method_name)
.input_shape.members[key]
.documentation
)
page_src += "<h3>{0}</h3><h4>{1}</h4>".format(
key, html.escape(str(val))
)
page_src += "<div>"
if len(docs) > 0:
page_src += docs
page_src += "<pre>{}</pre>".format(
json.dumps(
get_shape_data(client, val.name), indent=2, sort_keys=True
)
)
page_src += "<div>"
else:
param = client.meta.service_model.operation_model(
method_name
).input_shape.members[param_name]
docs = param.documentation
page_src += "<h3>{0}</h3><h4>{1}</h4>".format(
param_name, html.escape(str(param))
)
page_src += "<div>"
if len(docs) > 0:
page_src += docs
page_src += "<pre>{}</pre>".format(
json.dumps(
get_shape_data(client, param.name), indent=2, sort_keys=True
)
)
page_src += "<div>"
return HTML(page_src)
| kernelpanek/jupyterlab-starter-notebooks | helper/aws_functions.py | aws_functions.py | py | 6,575 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "configparser.ConfigParser",
"line_number": 78,
"usage_type": "call"
},
{
"api_name": "pathlib.Path",
"line_number": 79,
"usage_type": "call"
},
{
"api_name": "boto3.session.Session",
"line_number": 91,
"usage_type": "call"
},
{
"api_name": "boto3.se... |
22265028586 | from mensajes import separador_chats
from usuarios import inicio_sesion
from parametros import VOLVER_FRASE, ABANDONAR_FRASE
from datetime import datetime, date
def lista_grupos():
#lee el archivo
with open('grupos.csv', 'rt') as archivo_grupos:
lista_grupos = archivo_grupos.readlines()
for x in range(len(lista_grupos)):
lista_grupos[x] = lista_grupos[x].strip().split(",")
return lista_grupos
def dic_grupos():
#crea un diccionario para agrupar los usuarios de cada grupo
grupos = {}
lista_grupos_para_dic = lista_grupos()
variable = ""
temporal = []
nombres_grupos = []
for elemento in lista_grupos_para_dic:
if variable == "" or variable != elemento[0]:
grupos[variable] = temporal
nombres_grupos.append(variable)
variable = elemento[0]
temporal = []
temporal.append(elemento[1])
else:
temporal.append(elemento[1])
grupos[variable] = temporal
nombres_grupos.pop(0)
nombres_grupos.pop(0)
return grupos, nombres_grupos
def grupos_usuario(ingresado):
diccionario_grupos, nombres_grupos = dic_grupos()
grupos_ingresado = []
for elemento in diccionario_grupos:
for usuario in diccionario_grupos[elemento]:
if usuario == ingresado:
grupos_ingresado.append(elemento)
return grupos_ingresado
def chat_grupo(grupo):
chat_grupo = []
chats_grupos = separador_chats('nada', 'grupo')
for elemento in chats_grupos:
if elemento[2] == grupo:
chat_grupo.append(elemento)
return chat_grupo
def mostrar_mensaje(grupo):
chat = chat_grupo(grupo)
for elemento in chat:
if chat == "vacio":
print("Inicia la conversacion con este grupo")
break
else:
print(f"[{elemento[3]}] De {elemento[1]}: '{elemento[4]}'")
return
def eliminar_usuario(ingresado, grupo):
lista = lista_grupos()
for elemento in lista:
if elemento[0] == grupo and elemento[1] == ingresado:
lista.pop(lista.index(elemento))
with open('grupos.csv', 'w') as archivo_grupos:
for elemento in lista:
escribir = f"{elemento[0]},{elemento[1]}"+"\n"
archivo_grupos.write(escribir)
with open('mensajes.csv', 'a') as archivo_chats:
archivo_chats.write("\n")
hora = datetime.now()
fecha = datetime.today()
envio = str(fecha.strftime("%Y/%m/%d")) + " " + str(hora.strftime("%H:%M:%S"))
archivo_chats.write( \
f"grupo,Sistema,{grupo},{envio},El usuario {ingresado} ha abandonado el grupo")
mostrar_mensaje(grupo)
return
def nuevo_mensaje(ingresado, grupo):
print(f"Escribe una respuesta ¿o ingresa '{VOLVER_FRASE}' para regresar al menu de contactos")
print(f"Si deseas abandonar el grupo escribe '{ABANDONAR_FRASE}', se notificará al grupo")
texto = input()
if texto == VOLVER_FRASE:
return seleccion_grupo(ingresado)
elif texto == ABANDONAR_FRASE:
eliminar_usuario(ingresado, grupo)
return "menu"
else:
hora = datetime.now()
fecha = datetime.today()
envio = str(fecha.strftime("%Y/%m/%d")) + " " + str(hora.strftime("%H:%M:%S"))
mensaje = f"grupo,{ingresado},{grupo},{envio},{texto}"
with open('mensajes.csv', 'a') as archivo_chats:
archivo_chats.write("\n")
archivo_chats.write(mensaje)
mostrar_mensaje(grupo)
return nuevo_mensaje(ingresado, grupo)
def seleccion_grupo(ingresado):
print("***** Ver Grupos *****")
print("Selecciona un grupo para ver tus conversaciones, o 0 para volver atras:")
grupos_ingresado = grupos_usuario(ingresado)
for x in range(len(grupos_ingresado)):
print(f"[{x+1}] {grupos_ingresado[x]}")
print("[0] Volver")
seleccion = input("Ingrese el numero del usuario seleccionado: ")
if seleccion == "0":
#indica a menus.py que ejecute menu_grupos()
return "menu"
elif seleccion.isdigit() == False:
print("Solo puedes ingresar numeros")
return seleccion_grupo(ingresado)
elif int(seleccion) < 1 or int(seleccion) > len(grupos_ingresado):
print("El numero ingresado no es valido")
return seleccion_grupo(ingresado)
else:
if grupos_ingresado[int(seleccion)-1] == "vacio":
print("No tienes ningun grupo en tu lista, crea uno para comenzar a chatear")
return seleccion_grupo(ingresado)
else:
print(f"chat del grupo '{grupos_ingresado[int(seleccion)-1]}'")
#grupos_ingresado[int(seleccion)-1] -> grupo seleccionado, contraresta print(f"[x+1]")
mostrar_mensaje(grupos_ingresado[int(seleccion)-1])
accion = nuevo_mensaje(ingresado, grupos_ingresado[int(seleccion)-1])
return accion
def crear_grupo(ingresado):
nombre = input("Ingresa el nombre que tendra el grupo (minimo un caracter): ")
if len(nombre) < 1:
print("el nombre ingresado es de menos de un caracter")
return
desechable, grupos_existentes = dic_grupos()
for elemento in grupos_existentes:
if elemento == nombre:
print("Este nombre ya esta en uso, ingrese otro")
return
print("Ahora debe registrar a los usuarios que formaran parte del grupo")
print("Para esto deberas incluirte a ti mismo y seguir el siguiente formato:")
print("tú;usuario2;usuario3;.....;usuarioN")
print("Como minimo el grupo debe tener dos usuarios incluyendote")
usuarios = input()
correcto_1 = False
correcto_2 = 0
for elemento in usuarios:
if elemento == ";":
correcto_1 = True
break
if correcto_1 == True:
usuarios = usuarios.split(";")
if len(usuarios) < 2:
print("No cumples con la cantidad minima de usuarios")
return
else:
if usuarios[0] == ingresado:
for elemento in usuarios:
existente = inicio_sesion(elemento)
if existente == True:
correcto_2 += 1
else:
print(f"El nombre de usuario {elemento} no existe")
return
else:
print("No te ingresaste primero en la lista")
return
else:
print("El formato de la lista de usuarios no coincide con el especificado")
return
if correcto_2 == len(usuarios):
with open('grupos.csv', 'a') as archivo_grupos:
for elemento in usuarios:
archivo_grupos.write(f"{nombre},{elemento}"+'\n')
print("Grupo creado con exito, regresando al menu")
return
else:
print("Ocurrio un error al crear el grupo")
return | Alzvil/IIC2233-Progra-Avanzada-Tareas-2021-1 | Tareas/T0/grupos.py | grupos.py | py | 6,884 | python | es | code | 0 | github-code | 36 | [
{
"api_name": "mensajes.separador_chats",
"line_number": 46,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.now",
"line_number": 73,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 73,
"usage_type": "name"
},
{
"api_name": "date... |
29403005622 | import rooms
import asyncio
from asgiref.sync import async_to_sync
import json as encoder
class WebsocketFireClass():
@async_to_sync
async def new_chat_message(self, state):
encoded_state = encoder.dumps({'type': 'new_chat_message', 'data': state})
print("NEW CHAT MESSAGE, START FIRING...")
if rooms.chat:
await asyncio.wait([connection.send(encoded_state) for connection in rooms.chat])
@async_to_sync
async def new_chat_message2(self, state):
await asyncio.sleep(2) | anotherrandomnickname/ffms-websocket-py | wsfire.py | wsfire.py | py | 532 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "json.dumps",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "rooms.chat",
"line_number": 13,
"usage_type": "attribute"
},
{
"api_name": "asyncio.wait",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "rooms.chat",
"line_number... |
17774181352 | from rest_framework.permissions import BasePermission
from noticeboard.utils.notices import (
user_allowed_banners,
has_super_upload_right,
)
class IsUploader(BasePermission):
"""
A custom Django REST permission layer to check authorization
over different actions on notices.
"""
def has_permission(self, request, view, **kwargs):
"""
Primary permission for notices.
:param request: Django request object
:param view:
:param kwargs: keyword arguments
:return: boolean expression of permission
"""
if request.method == 'GET' or request.method == 'DELETE':
return True
person = request.person
data = request.data
try:
banner_id = data['banner']
except KeyError:
return False
allowed_banner_ids = user_allowed_banners(person)
if banner_id in allowed_banner_ids:
if data.get('is_important', False):
return has_super_upload_right(person, banner_id)
else:
return True
else:
return False
def has_object_permission(self, request, view, obj, **kwargs):
"""
Object level permission for notices.
:param request: Django request object
:param view:
:param obj: instance of the model
:param kwargs: keyword arguments
:return: boolean expression of permission
"""
if request.method == 'GET':
return True
return obj.uploader.id == request.person.id
| IMGIITRoorkee/omniport-app-noticeboard | permissions/uploader.py | uploader.py | py | 1,591 | python | en | code | 6 | github-code | 36 | [
{
"api_name": "rest_framework.permissions.BasePermission",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "noticeboard.utils.notices.user_allowed_banners",
"line_number": 35,
"usage_type": "call"
},
{
"api_name": "noticeboard.utils.notices.has_super_upload_right",
"l... |
939034143 | from datetime import datetime
from src.app import db, app
import uuid
from src.models.mixins import BaseMixin
from src.helpers import *
from sqlalchemy import exc
class BookRating(BaseMixin, db.Model):
__tablename__ = "book_ratings"
rating_id = db.Column(db.String(50), primary_key=True, default=lambda: uuid.uuid1().hex)
book_id = db.Column(db.String(50), db.ForeignKey("books.book_id"), nullable=False)
list_id = db.Column(db.String(50), db.ForeignKey("reading_lists.list_id"), nullable=False)
rating = db.Column(db.Integer, nullable=False)
notes = db.Column(db.String(500))
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
updated_at = db.Column(db.DateTime)
_validations_ = {
"book_id": {"type": "string", "required": True, "min_length": 32, "max_length": 32},
"list_id": {"type": "string", "required": True, "min_length": 32, "max_length": 32},
"rating": {"type": "integer", "required": True, "min_value": 0, "max_value": 5},
"notes": {"type": "string", "required": False, "min_length": 0, "max_length": 500},
}
_restrict_in_creation_ = ["rating_id", "created_at", "updated_at"]
_restrict_in_update_ = ["rating_id", "created_at", "book_id", "list_id"]
__table_args__ = (db.UniqueConstraint('book_id', 'list_id', name='uq_book_list'),)
@staticmethod
def create_a_rating(data):
"""
Create a new rating
:param data: [object] contains rating info in key value pair
:return [dict]
"""
app.logger.info('Preparing to create a new rating')
new_rating = BookRating()
allowed_columns = list_diff(BookRating().columns_list(), BookRating()._restrict_in_creation_)
for column in allowed_columns:
if column in data:
setattr(new_rating, column, data.get(column))
app.logger.debug('Populated new rating object with provided data')
# Check if data is valid
result = new_rating.validate_and_sanitize(BookRating()._restrict_in_creation_)
if result.get("errors"):
app.logger.error('Validation and sanitization failed for new rating')
app.logger.debug(f'Error details: {result["errors"]}')
return {"error": result["errors"]}
try:
db.session.add(new_rating)
db.session.flush()
db.session.commit()
app.logger.info(f'New rating created successfully with id {new_rating.rating_id}')
return {"rating_id": str(new_rating.rating_id)}
except exc.IntegrityError as e:
db.session.rollback()
err = e.orig.diag.message_detail.rsplit(',', 1)[-1]
app.logger.error('Integrity error occurred while creating new rating')
app.logger.debug(f'Error details: {err.replace(")", "")}')
return {"error": err.replace(")", "")}
except Exception as e:
db.session.rollback()
app.logger.error('Unknown error occurred while creating new rating')
app.logger.debug(f'Error details: {str(e)}')
return {"error": "failed to create rating"}
@staticmethod
def get_ratings(rating_id=None, return_as_object=False, page=None, offset=None, orderby=None, sortby=None):
"""
Get ratings info
:param rating_id: [str] book_ratings table primary key
:param return_as_object: [bool] do we need to return the list of objects or dictionary for rows?
:param page: [int] page number
:param offset: [int] page offset - number of rows to return
:return [list]
"""
page = page or 1
offset = offset or 20
begin_query = db.session.query(BookRating)
app.logger.info('Book rating retrieval request received')
app.logger.debug(f'Request parameters - rating_id: {rating_id}, return_as_object: {return_as_object}, page: {page}, offset: {offset}, orderby: {orderby}, sortby: {sortby}')
try:
if not rating_id:
offset = int(offset)
page = int(page)-1
if orderby and sortby:
if orderby == -1:
result = begin_query.order_by(getattr(BookRating, sortby).desc()).offset(page*offset).limit(offset).all()
elif orderby == 1:
result = begin_query.order_by(getattr(BookRating, sortby).asc()).offset(page*offset).limit(offset).all()
else:
result = begin_query.order_by(BookRating.created_at).offset(page*offset).limit(offset).all()
count = BookRating.query.count()
meta_data = {"rating_count": count, "page_number": int(page) + 1, "page_offset": offset}
app.logger.info(f'Retrieved {count} ratings')
if result:
if return_as_object:
return result
else:
return {"ratings": [row.to_dict() for row in result], **meta_data}
else:
result = begin_query.filter(
BookRating.rating_id == rating_id
).all()
if result:
app.logger.info(f'Retrieved rating with rating_id {rating_id}')
return result[0] if return_as_object else result[0].to_dict()
except Exception as e:
app.logger.error('Book rating retrieval failed')
app.logger.debug(f'Error details: {e}, rating_id: {rating_id}, page: {page}, offset: {offset}')
return {"error" : "No rating found"}
@staticmethod
def update_a_rating(rating_id, data):
"""
Update an existing rating
:param rating_id: [str] book_ratings table primary key
:param data: [dict] rating updating field data
:return [dict]
"""
app.logger.info(f'Update rating request received for rating id: {rating_id}')
app.logger.debug(f'Request data: {data}')
rating = db.session.get(BookRating, rating_id)
if not rating:
app.logger.error(f'No rating found with id: {rating_id}')
return {}
try:
for column in data:
if hasattr(rating, column):
setattr(rating, column, data[column])
rating.updated_at = datetime.utcnow()
db.session.commit()
app.logger.info('Rating successfully updated')
return {'message': 'successfully updated rating_id={}'.format(rating_id)}
except Exception as e:
app.logger.error('Rating update failed')
app.logger.debug(f'Error details: {str(e)}')
return {"error": "failed to update rating"}
@staticmethod
def delete_rating_permanently(rating_id):
"""
Delete a rating permanently
:param rating_id: [str] book_ratings table primary key
:return [dict]
"""
app.logger.info(f'Request to delete rating with id {rating_id} received')
rating = db.session.get(BookRating, rating_id)
if rating:
try:
db.session.delete(rating)
db.session.commit()
app.logger.info('Rating successfully deleted')
return {'message': 'successfully deleted rating_id={}'.format(rating_id)}
except Exception as e:
app.logger.error('Rating deletion failed')
app.logger.debug(f'Error details: {e}')
return {"error": "Rating deletion failed"}
else:
app.logger.warning(f'Rating with id {rating_id} not found')
return {} | Aaronh3k/book-status-api | src/models/book_ratings.py | book_ratings.py | py | 7,769 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "src.models.mixins.BaseMixin",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "src.app.db.Model",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "src.app.db",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "src.app.db.... |
5049475129 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import subprocess
import sys
import pygit2
sys.path.insert(0, os.path.abspath('../..'))
project = 'tensorrt_llm'
copyright = '2023, NVidia'
author = 'NVidia'
branch_name = pygit2.Repository('.').head.shorthand
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
templates_path = ['_templates']
exclude_patterns = []
extensions = [
'sphinx.ext.duration',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
'myst_parser', # for markdown support
"breathe",
'sphinx.ext.todo',
]
myst_url_schemes = {
"http":
None,
"https":
None,
"source":
"https://github.com/NVIDIA/TensorRT-LLM/tree/" + branch_name + "/{{path}}",
}
autosummary_generate = True
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
source_suffix = {
'.rst': 'restructuredtext',
'.txt': 'markdown',
'.md': 'markdown',
}
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
# ------------------------ C++ Doc related --------------------------
# Breathe configuration
breathe_default_project = "TensorRT-LLM"
breathe_projects = {"TensorRT-LLM": "../cpp_docs/xml"}
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
CPP_INCLUDE_DIR = os.path.join(SCRIPT_DIR, '../../cpp/include/tensorrt_llm')
CPP_GEN_DIR = os.path.join(SCRIPT_DIR, '_cpp_gen')
print('CPP_INCLUDE_DIR', CPP_INCLUDE_DIR)
print('CPP_GEN_DIR', CPP_GEN_DIR)
def gen_cpp_doc(ofile_name: str, header_dir: str, summary: str):
cpp_header_files = [
file for file in os.listdir(header_dir) if file.endswith('.h')
]
with open(ofile_name, 'w') as ofile:
ofile.write(summary + "\n")
for header in cpp_header_files:
ofile.write(f"{header}\n")
ofile.write("_" * len(header) + "\n\n")
ofile.write(f".. doxygenfile:: {header}\n")
ofile.write(" :project: TensorRT-LLM\n\n")
runtime_summary = f"""
Runtime
==========
.. Here are files in the cpp/include/runtime
.. We manually add subsection to enable detailed description in the future
.. It is also doable to automatically generate this file and list all the modules in the conf.py
""".strip()
subprocess.run(['mkdir', '-p', CPP_GEN_DIR])
gen_cpp_doc(CPP_GEN_DIR + '/runtime.rst', CPP_INCLUDE_DIR + '/runtime',
runtime_summary)
| NVIDIA/TensorRT-LLM | docs/source/conf.py | conf.py | py | 2,943 | python | en | code | 3,328 | github-code | 36 | [
{
"api_name": "sys.path.insert",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "os.path.abspath",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_num... |
28090834284 | import pytest
import config
import random
from datetime import datetime
from flask.testing import FlaskClient
from webapp import create_app, db
from flask import current_app
from webapp.models import Theme, Timebox, Task, Project
@pytest.fixture(scope='function')
def models():
return {'timebox': Timebox}
@pytest.fixture(scope='function')
def logged_in_client(database, app):
# Flask provides a way to test your application by exposing the Werkzeug test Client
# and handling the context locals for you.
testing_client = app.test_client()
# Establish an application context before running the tests.
ctx = app.app_context()
ctx.push()
r = testing_client.post('/register',
json=dict(username='mark', password='Password1'))
r2 = testing_client.post('/login',
json=dict(username='mark', password='Password1'))
yield testing_client # this is where the testing happens!
ctx.pop()
@pytest.fixture(scope='session')
def app():
flask_app = create_app(config.TestConfig)
return flask_app
@pytest.fixture(scope='function')
def database(app):
# app is an instance of a flask app, _db a SQLAlchemy DB
with app.app_context():
db.create_all()
yield db
# Explicitly close DB connection
db.session.close()
db.drop_all()
@pytest.fixture(scope='function')
def test_client(database, app):
# Flask provides a way to test your application by exposing the Werkzeug test Client
# and handling the context locals for you.
testing_client = app.test_client()
# Establish an application context before running the tests.
ctx = app.app_context()
ctx.push()
yield testing_client # this is where the testing happens!
ctx.pop()
@pytest.fixture(scope='function')
def project(database):
p = Project(title='test project', project_type='board')
db.session.add(p)
db.session.commit()
return p
@pytest.fixture(scope='function')
def sample_data(database, logged_in_client):
logged_in_client.post('add_project', json={'title': 'test project 1', 'project_type': 'board'})
logged_in_client.post('add_project', json={'title': 'test project 2', 'project_type': 'board'})
p1 = Project.query.filter_by(title='test project 1').first()
p2 = Project.query.filter_by(title='test project 2').first()
logged_in_client.post('/add_theme', json={'project_id': p1.id, 'title': 'test theme 11'})
logged_in_client.post('/add_theme', json={'project_id': p1.id, 'title': 'test theme 12'})
logged_in_client.post('/add_theme', json={'project_id': p2.id, 'title': 'test theme 21'})
logged_in_client.post('/add_theme', json={'project_id': p2.id, 'title': 'test theme 22'})
logged_in_client.post('add_timebox', json={'project_id': p1.id, 'title': 'To Do This Week', 'goal': []})
logged_in_client.post('add_timebox', json={'project_id': p2.id, 'title': 'To Do This Week', 'goal': 'feel good'})
logged_in_client.post('add_task', json={'project_id': p1.id, 'title': 'test task A'})
logged_in_client.post('add_task', json={'project_id': p1.id, 'title': 'test task B'})
logged_in_client.post('add_task', json={'project_id': p1.id, 'title': 'test task C'})
logged_in_client.post('add_task', json={'project_id': p1.id, 'title': 'test task D'})
logged_in_client.post('add_task', json={'project_id': p2.id, 'title': 'test task E'})
logged_in_client.post('add_task', json={'project_id': p2.id, 'title': 'test task F'})
logged_in_client.post('add_task', json={'project_id': p2.id, 'title': 'test task G'})
logged_in_client.post('add_task', json={'project_id': p2.id, 'title': 'test task H'})
logged_in_client.post('add_subtask', json={'project_id': p1.id, 'task_id':2, 'title': 'test subtask 1'})
@pytest.fixture(scope='function')
def random_data(database):
statuses = ['To Do', 'In Progress', 'Done']
verbs = ['Do', 'Make', 'Watch', 'Learn', 'Find', 'Investigate', 'Tidy', 'Book']
nouns = ['Garden', 'TV', 'Kitchen', 'TV', 'Cinema', 'Homework', 'Laundry', 'Holiday']
events = ['Tomorrow', 'Sunday', 'Christmas', 'Holidays', 'Birth', 'Wedding']
projects = []
themes = []
timeboxes = []
tasks = []
for i in range(random.randint(1,4)):
p = Project(title=random.choice(nouns) + ' List ' + str(random.randint(1,10)))
projects.append(p)
for p in projects:
for i in range(random.randint(1,7)):
th = Theme(project=p, title=random.choice(verbs)+'ing things')
themes.append(th)
backlog = Timebox(project=p, title='Backlog', status='To Do')
timeboxes.append(backlog)
for i in range(1,3):
tb = Timebox(project=p, title='To do before ' + random.choice(events),
status=random.choice(['To Do', 'In Progress', 'Closed']))
timeboxes.append(tb)
for i in p.timeboxes.all():
for j in range(1,10):
t = Task(project=p,
theme=random.choice(p.themes.all()),
title=random.choice(verbs) + ' ' + random.choice(nouns),
status=random.choice(statuses),
priority=j
)
t.add_to_timebox(i)
tasks.append(t)
db.session.add_all(projects)
db.session.add_all(themes)
db.session.add_all(timeboxes)
db.session.add_all(tasks)
db.session.commit()
data = {
'projects': projects,
'themes': themes,
'timeboxes': timeboxes,
'tasks': tasks
}
return data
| thekitbag/todoodleoo-server | tests/conftest.py | conftest.py | py | 5,630 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "webapp.models.Timebox",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "pytest.fixture",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "pytest.fixture",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "webapp.create_app... |
18745919637 | from telegram import Bot, Update, ParseMode
from telegram.ext import run_async
import time
from bot.modules.helper_funcs.extraction import extract_user
from bot import dispatcher
from bot.modules.disable import DisableAbleCommandHandler
@run_async
def gdpr(bot: Bot, update: Update):
message = update.effective_message
chat = update.effective_chat
user = update.effective_user
if chat.type == 'private':
message.reply_text("Deleting identifiable data...")
time.sleep(2)
message.reply_text("Almost done, Just be Patient")
time.sleep(2)
message.reply_text("My Ass! do not come here AGAIN. If you are gbanned this cmd will not revert it. So kindly GTFO.")
message.reply_text("Pajeet confirm")
GDPR_HANDLER = DisableAbleCommandHandler("gdpr", gdpr)
dispatcher.add_handler(GDPR_HANDLER)
| koppiesttiajaykumar/bot | bot/modules/gdpr.py | gdpr.py | py | 914 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "telegram.Bot",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "telegram.Update",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "time.sleep",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "time.sleep",
"line_number":... |
71075117545 | import collections
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
stones = list(map(tuple, stones))
s = set(stones)
dx = collections.defaultdict(set)
dy = collections.defaultdict(set)
for i,j in s:
dx[i].add(j)
dy[j].add(i)
def dfs(i, j):
for nextY in dx[i]:
if (i, nextY) in s:
s.remove((i, nextY))
dfs(i, nextY)
for nextX in dy[j]:
if (nextX, j) in s:
s.remove((nextX, j))
dfs(nextX, j)
island = 0
for x, y in stones:
if (x, y) not in s:
continue
island += 1
dfs(x, y)
return len(stones) - island | nango94213/Leetcode-solution | 0947-most-stones-removed-with-same-row-or-column/0947-most-stones-removed-with-same-row-or-column.py | 0947-most-stones-removed-with-same-row-or-column.py | py | 879 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "collections.defaultdict",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "collections.defaultdict",
"line_number": 9,
"usage_type": "call"
}
] |
73202442984 | from datetime import datetime
from shapely.geometry import Point
import numpy as np
from typing import List
GEODATUM_MAPPING = {
"WGS 1984": "epsg:4326",
"Ordnance Survey Great Britain 1936": "epsg:4277",
"TWD 1967": "epsg:3828",
"Gauss Krueger Meridian2": None,
"Gauss Krueger Meridian3": None,
"Gauss Krueger Austria M34": "epsg:18009",
"Gauss Krueger Austria M31": "epsg:18008",
"Rijks Driehoekstelsel": "epsg:28992",
"JRC": "epsg:3040",
"DWD": None,
"KNMI Radar": None,
"CH1903": "epsg:4149",
"PAK1": None,
"PAK2": None,
"SVY21": "epsg:3414",
}
def camel_to_snake_case(camel_case: str) -> str:
"""
Convert camelCase to snake_case
Args:
camel_case (str): sentence in camelCase (e.g. myInputVariable)
Returns:
str: converted sentence in snake_case (in example my_input_variable)
"""
return "".join(["_" + i.lower() if i.isupper() else i for i in camel_case]).lstrip(
"_"
)
def snake_to_camel_case(snake_case: str) -> str:
"""
Convert snake_case to camelCase
Args:
snake_case (str): sentence in snake_case (in example my_input_variable)
Returns:
str: converted sentence in camelCase (e.g. myInputVariable)
"""
words = snake_case.split("_")
return words[0] + "".join(i.title() for i in words[1:])
def dict_to_datetime(data: dict) -> datetime:
"""
Convert a FEWS PI datetime dict to datetime object
Args:
data (dict): FEWS PI datetime (e.g. {'date': '2022-05-01', 'time': '00:00:00'})
Returns:
datetime: Converted datetime object (in example datetime.datetime(2022, 5, 1, 0, 0))
"""
if "time" in data.keys():
time = data["time"]
else:
time = "00:00:00"
date_time = datetime.fromisoformat(f'{data["date"]}T{time}')
return date_time
def datetime_to_fews_str(date_time: datetime) -> str:
"""
Convert a FEWS PI datetime dict to datetime object
Args:
date_time (datetime): datetime object (e.g. datetime.datetime(2022, 5, 1, 0, 0))
Returns:
datetime: Converted datetime for FEWS REST API format %Y-%m-%dT%H:%M:%SZ
(in example 2022-05-01T00:00:00Z)
"""
return date_time.strftime("%Y-%m-%dT%H:%M:%SZ")
def xy_array_to_point(xy_array: np.ndarray) -> List[Point]:
return [Point(i.astype(float)) for i in xy_array]
def attributes_to_array(attribute_values: np.ndarray, attributes: list) -> np.ndarray:
def _get_values(x, attributes):
selection = {i["id"]: i["value"] for i in x if i["id"] in attributes}
return [selection[i] if i in selection.keys() else None for i in attributes]
return np.array([_get_values(i, attributes) for i in attribute_values])
def geo_datum_to_crs(geo_datum: str) -> str:
if geo_datum.startswith("UTM"):
epsg_code = 32600
zone = int(geo_datum[3:5].lstrip("0"))
epsg_code += int(zone)
if geo_datum[-1] == "S":
epsg_code += 100
crs = f"epsg:{epsg_code}"
elif geo_datum.lower().startswith("epsg"):
crs = geo_datum.lower()
elif geo_datum in GEODATUM_MAPPING.keys():
crs = GEODATUM_MAPPING[geo_datum]
else:
crs = None
return crs
| d2hydro/fewspy | src/fewspy/utils/conversions.py | conversions.py | py | 3,271 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "datetime.datetime.fromisoformat",
"line_number": 75,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 75,
"usage_type": "name"
},
{
"api_name": "datetime.datetime",
"line_number": 58,
"usage_type": "name"
},
{
"api_name": "d... |
75138929384 | from loja.models import Produto
from loja.models import Pedido
from loja.models import CATEGORIAS
from rest_framework import serializers
class ProdutoSerializer(serializers.ModelSerializer):
class Meta:
model = Produto
fields = (
'id',
'nome',
'descricao',
'valor',
'categoria'
)
class PedidoSerializer(serializers.ModelSerializer):
valor_total = serializers.SerializerMethodField()
class Meta:
model = Pedido
fields = (
'id',
'produtos',
'cliente',
'status',
'data_realizacao',
'valor_total',
)
def get_valor_total(self, obj):
return obj.get_valor_total()
def validate_produtos(self, attrs):
msg = 'É necessesario escolher no minimo um produto de cada categoria'
produtos = attrs
if len(produtos) < len(CATEGORIAS):
raise serializers.ValidationError(msg)
categorias_index = list(dict(CATEGORIAS))
for p in produtos:
if not p.categoria in categorias_index:
raise serializers.ValidationError(msg)
return attrs
def validate(self, attrs):
return attrs | jonasfsilva/desafio_intmed | loja/serializers.py | serializers.py | py | 1,298 | python | pt | code | 0 | github-code | 36 | [
{
"api_name": "rest_framework.serializers.ModelSerializer",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "rest_framework.serializers",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "loja.models.Produto",
"line_number": 10,
"usage_type": "name"
... |
41224759283 | '''
Created on 15-Oct-2013
@author: Kashaj
'''
import re, sqlite3,os
db = sqlite3.connect('Train_Database.db')
db.text_factory = str
db.row_factory = sqlite3.Row
db.execute('drop table if exists TrainStationNode')
db.execute('create table TrainStationNode(Train_Num char[6],stn_code char[6],route int,arr_time text,dep_time text)')
def main():
tr_num = open('List_Of_All_Train_Nums.txt','r')
for num in tr_num:
num = str(num)
num = num.replace("\xa0","");
num = num.replace("\n","");
num = num.strip(' ')
num = num.strip('\n')
hread(num)
tuples = hwork()
hdatab(num,tuples)
getData()
db.commit()
def hread(filename):
save_path = r'C:/Users/kashaj/Desktop/proj/data/schedule/'
filename += '.html'
completeName = os.path.join(save_path, filename)
f = open(completeName,'r')
text = f.read()
text = text.strip('\n')
f2 = open('loolws.txt','w')
f2.write(text)
f2.close()
def hwork():
f = open('loolws.txt','r')
text = f.read()
tuples = re.findall(r'<TR>\n<TD>\d+</TD>\n<TD>(\w+\s*)</TD>\n<TD>\w+.*</TD>\n<TD>(\d)+</TD>\n<TD>(.+)</TD>\n<TD>(.+)</TD>\n<TD>.*</TD>\n<TD>\d+</TD>\n<TD>\d+</TD>',text,re.IGNORECASE)
f.close()
return(tuples)
def hdatab(num,tuples):
for i in range(0,len(tuples)):
if(i==0):
db.execute('insert into TrainStationNode(Train_Num,stn_code,route,arr_time,dep_time) values (?,?,?,?,?)',(num,tuples[i][0],tuples[i][1],(tuples[i][2]).replace('<FONT COLOR = red>', ''),(tuples[i][3])))
elif(i == (len(tuples)-1)):
db.execute('insert into TrainStationNode(Train_Num,stn_code,route,arr_time,dep_time) values (?,?,?,?,?)',(num,tuples[i][0],tuples[i][1],tuples[i][2],(tuples[i][3]).replace('<FONT COLOR = red>', '')))
else:
db.execute('insert into TrainStationNode(Train_Num,stn_code,route,arr_time,dep_time) values (?,?,?,?,?)',(num,tuples[i][0],tuples[i][1],tuples[i][2],(tuples[i][3]).replace('<FONT COLOR = red>', '')))
def getData():
cursor = db.execute('Select Train_Num,stn_code,route,arr_time,dep_time from TrainStationNode')
for row in cursor:
print(row['Train_Num'],row['stn_code'],row['route'],row['arr_time'],row['dep_time'])
if __name__ == '__main__':
main() | ShaikAsifullah/Indian-Railways-Informal | getEdges.py | getEdges.py | py | 2,447 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "sqlite3.connect",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "sqlite3.Row",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "os.path.join",
"line_number": 41,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_numbe... |
2671289236 | import os
import shutil
from fastapi import UploadFile
# UPLOAD_DIR = "model_upload_dir"
def upload_file(upload_dirname: str, file: UploadFile, filename: str):
if file and filename:
fileobj = file.file
target_path = os.path.join(upload_dirname, filename)
target_dir = os.path.dirname(target_path)
os.makedirs(target_dir, exist_ok=True)
upload_dir = open(target_path, "wb+")
shutil.copyfileobj(fileobj, upload_dir)
upload_dir.close()
return {"status": "OK", "msg": f"uploaded files {filename} "}
return {"status": "ERROR", "msg": "uploaded file is not found."}
def concat_file_chunks(
upload_dirname: str, filename: str, chunkNum: int, dest_dirname: str
):
target_path = os.path.join(upload_dirname, filename)
target_dir = os.path.dirname(target_path)
os.makedirs(target_dir, exist_ok=True)
if os.path.exists(target_path):
os.remove(target_path)
with open(target_path, "ab") as out:
for i in range(chunkNum):
chunkName = f"{filename}_{i}"
chunk_file_path = os.path.join(upload_dirname, chunkName)
stored_chunk_file = open(chunk_file_path, "rb")
out.write(stored_chunk_file.read())
stored_chunk_file.close()
os.remove(chunk_file_path)
out.close()
return {"status": "OK", "msg": f"concat files {out} "}
| w-okada/voice-changer | server/restapi/mods/FileUploader.py | FileUploader.py | py | 1,402 | python | en | code | 12,673 | github-code | 36 | [
{
"api_name": "fastapi.UploadFile",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "os.path.join",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "os.path.dirname",
"li... |
20780721557 | import os #to access files
from PIL import Image #to open JPEGs
import numpy as np
#-------------------------------Custom INCLUDES-------------------------------
import lookupTables as lT
#-------------------------------Function DEFINITIONS----------------------------
def fittingEstimator(inDir, file_name, EV_calc_local, EV_calc_global, LUT):
EV_calc_local[:] = [0.0] #list of statistics
EV_calc_global[:] = []
#lattice parameter
R=10
#-------Opening image1
#separate core of name, append jpg extension, open, BW
name = (file_name[0].split(".")[0] + ".jpg")
img1 = Image.open("./"+inDir+"/"+name)
img1 = np.array( img1.convert("L") )
#dimensions of image
N,M = img1.shape
#fill the first plot list
cntr = -1
x1 = np.array( [0.0]*(len(range(0,N,R))*len(range(0,M,R))) )
x2 = np.array( [0.0]*(len(range(0,N,R))*len(range(0,M,R))) )
for i in range(0,N,R):
for j in range(0,M,R):
cntr += 1
x1[cntr] = LUT( img1[i,j] )
for name in file_name[1:]:
#-------Opening image 2
#separate core of name, append jpg extension, open, BW
name = (name.split(".")[0] + ".jpg")
img2 = Image.open("./"+inDir+"/"+name)
img2 = np.array( img2.convert('L') )
cntr = -1
for i in range(0,N,R):
for j in range(0,M,R):
cntr += 1
x2[cntr] = LUT( img2[i,j] )
#now compare x1 and x2
#fitting x+b is equivalent to calculating
#print(np.average( x1-x2 ))
xx1 = []
xx2 = []
for (x,y) in zip(x1,x2):
if x>=1 and x<=7 and y>=1 and y<=7:
xx1.append(x)
xx2.append(y)
if len(xx1) == 0 or len(xx2) == 0:
print("WARNING!!")
print(x2)
EV_calc_local.append( np.average( np.array(xx2)-np.array(xx1) ) + EV_calc_local[-1] )
#import matplotlib.pyplot as plt
#plt.figure(1)
#plt.plot(x1,x2,"x",xx1,xx2,"o")
#plt.show()
#change images
img1[:] = img2[:]
x1[:] = x2[:]
EV_calc_global[:] = EV_calc_local[:]
| nowaythatsok/GNU_lapser | version_01/estimators.py | estimators.py | py | 1,924 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "PIL.Image.open",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_number": 24,
"usage_type": "name"
},
{
"api_name": "numpy.array",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number":... |
24401528809 | """Handles the creating of obstacles within the game instance."""
import pygame
from src.scripts.coordinate import Coordinate
class Obstacle:
"""Class for handling the creating of obstables."""
def __init__(self) -> None:
self.size = (50, 300)
self.position = [
Coordinate(700, 400),
Coordinate(700, 0)
]
self.can_move = True
def get_rect(self) -> tuple[pygame.Rect, pygame.Rect]:
"""Get rect"""
return (
pygame.Rect(
tuple(self.position[0])[0], tuple(self.position[0])[1], self.size[0], self.size[1]
), # bottom rect
pygame.Rect(
tuple(self.position[1])[0], tuple(self.position[1])[1], self.size[0], self.size[1]
) # top rect
)
def move(self) -> None:
"""Move the obstace foward."""
if self.position[0].x < 45:
self.can_move = False
self.position[0].x -= 3
self.position[1].x -= 3
| Carson-Fletcher/PY_Flappy_Bird | src/scripts/obstacle.py | obstacle.py | py | 1,007 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "src.scripts.coordinate.Coordinate",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "src.scripts.coordinate.Coordinate",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "pygame.Rect",
"line_number": 19,
"usage_type": "call"
},
{
"a... |
24925255734 | import pygame
pygame.init()
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
background = pygame.image.load("D:/coding/python/pygame_basic/background.png")
pygame.display.set_caption("offRo")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 125, 255))
#screen.blit(background, (0,0))
pygame.display.update()
pygame.quit() | pla2n/python_practice | python/pygame_basic/2_background.py | 2_background.py | py | 496 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pygame.init",
"line_number": 3,
"usage_type": "call"
},
{
"api_name": "pygame.display.set_mode",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "pygame.display",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "pygame.image.loa... |
656371734 | #!/usr/bin/env python
import json
import pickle
import os
import pytest
import numpy as np
import mercantile as merc
import inspect
import rasterio
import untiler
from untiler.scripts import tile_utils
def test_templating_good_jpg():
print("")
expectedMatch = 'tarbase/jpg/\d+/\d+/\d+.jpg'
expectedInterp = 'tarbase/jpg/%s/%s/%s.jpg'
template = 'tarbase/jpg/{z}/{x}/{y}.jpg'
matchTemplate, interpTemplate, separator = tile_utils.parse_template(template)
assert matchTemplate == expectedMatch
assert interpTemplate == expectedInterp
assert separator == "/"
print("# OK - %s " % (inspect.stack()[0][3]))
def test_templating_good_png():
expectedMatch = 'tarbase/jpg/\d+/\d+/\d+.png'
expectedInterp = 'tarbase/jpg/%s/%s/%s.png'
template = 'tarbase/jpg/{z}/{x}/{y}.png'
matchTemplate, interpTemplate, separator = tile_utils.parse_template(template)
assert separator == "/"
assert matchTemplate == expectedMatch
assert interpTemplate == expectedInterp
print("# OK - %s " % (inspect.stack()[0][3]))
def test_templating_fails():
template = 'tarbase/jpg/{x}/{y}/{z}.jpg'
with pytest.raises(ValueError):
tile_utils.parse_template(template)
template = 'tarbase/jpg/{z}/{x}/{y}.poop'
with pytest.raises(ValueError):
tile_utils.parse_template(template)
template = 'tarbase/jpg/z/x/y.jpg'
with pytest.raises(ValueError):
tile_utils.parse_template(template)
print("# OK - %s " % (inspect.stack()[0][3]))
def tests_templating_scene_template():
template = '{z}-{x}-{y}-source-date-tileid.tif'
template, sceneTemplate, separator = tile_utils.parse_template(template)
assert separator == '-'
assert sceneTemplate == '%s-%s-%s-source-date-tileid.tif'
print("# OK - %s " % (inspect.stack()[0][3]))
def tests_templating_scene_template_numeric():
template = '{z}-{x}-{y}-source-2015-xyz.tif'
template, sceneTemplate, separator = tile_utils.parse_template(template)
assert separator == '-'
assert sceneTemplate == '%s-%s-%s-source-2015-xyz.tif'
print("# OK - %s " % (inspect.stack()[0][3]))
def tests_templating_scene_template_fails():
template = '{x}-{y}-source-2015-xyz.tif'
with pytest.raises(ValueError):
tile_utils.parse_template(template)
print("# OK - %s " % (inspect.stack()[0][3]))
def tests_templating_scene_template_separator_fails():
template = '{z}/{x}-{y}-source-2015-xyz.tif'
with pytest.raises(ValueError):
tile_utils.parse_template(template)
print("# OK - %s " % (inspect.stack()[0][3]))
@pytest.fixture
def inputTilenames():
with open('tests/fixtures/tar_list.json') as ofile:
return json.load(ofile)
@pytest.fixture
def expectedTileList():
with open('tests/expected/tile_list.json') as ofile:
return np.array(json.load(ofile))
def test_parse_tiles(inputTilenames, expectedTileList):
matchTemplate = r'3857_9_83_202_20130517_242834/jpg/\d+/\d+/\d+.jpg'
tiler = tile_utils.TileUtils()
output_tiles = np.array([
t for t in tiler.get_tiles(inputTilenames, matchTemplate, '/')
])
assert np.array_equal(output_tiles, expectedTileList)
tweakedTilenames = [f.replace('/', '?') for f in inputTilenames]
output_tiles = np.array([
t for t in tiler.get_tiles(tweakedTilenames, matchTemplate, '/')
])
assert len(output_tiles) == 0
assert np.array_equal(output_tiles, expectedTileList) == False
print("# OK - %s " % (inspect.stack()[0][3]))
@pytest.fixture
def expectedTiles19():
with open('tests/expected/tile_list_19.json') as ofile:
return json.load(ofile)
def test_get_xys(expectedTileList, expectedTiles19):
tiler = tile_utils.TileUtils()
tiles, minX, minY, maxX, maxY = tiler.select_tiles(expectedTileList, 19)
assert np.array_equal(tiles, np.array(expectedTiles19['tiles']))
assert minX == expectedTiles19['minX']
assert maxX == expectedTiles19['maxX']
assert minY == expectedTiles19['minY']
assert maxY == expectedTiles19['maxY']
print("# OK - %s " % (inspect.stack()[0][3]))
def test_get_xys_invalid_tiles():
tiler = tile_utils.TileUtils()
badtiles = np.array([0])
with pytest.raises(ValueError):
tiles, minX, minY, maxX, maxY = tiler.select_tiles(badtiles, 19)
badtiles = np.array([[1,2], [1,2]])
with pytest.raises(ValueError):
tiles, minX, minY, maxX, maxY = tiler.select_tiles(badtiles, 19)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_get_xys_invalid_zoom(expectedTileList):
tiler = tile_utils.TileUtils()
with pytest.raises(ValueError):
tiles, minX, minY, maxX, maxY = tiler.select_tiles(expectedTileList, 20)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_affine():
ul, lr = (-18848759.67889818, 19225441.354287542), (-18846313.693993058, 19222995.3693824)
expected = np.array([0.5971642834774684, 0.0, -18848759.67889818, 0.0, -0.5971642834820159, 19225441.354287542, 0.0, 0.0, 1.0])
assert np.array_equal(np.array(untiler.make_affine(4096, 4096, ul, lr)), expected)
print("# OK - %s " % (inspect.stack()[0][3]))
@pytest.fixture
def expectedMeta():
with open('tests/expected/src_meta.pkl', mode='rb') as pklfile:
return pickle.load(pklfile)
# SKIP UNTIL I DEAL W/ DECIMAL ISSUES
def test_src_meta_making(expectedMeta):
bounds = merc.bounds(10, 10, 10)
src_meta = untiler.make_src_meta(bounds, 4096)
for k, e in zip(sorted(src_meta), sorted(expectedMeta)):
assert k == e
# assert src_meta[k] == expectedMeta[e]
print("# OK - %s " % (inspect.stack()[0][3]))
def test_make_window():
expected = ((23808, 24064), (1024, 1280))
window = untiler.make_window(102, 343, 98, 250, 256)
assert window == expected
print("# OK - %s " % (inspect.stack()[0][3]))
def test_make_window_fails():
with pytest.raises(ValueError):
untiler.make_window(102, 13, 98, 50, 256)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_upsampling():
rShape = 2 ** int(np.random.rand() * 5 + 5)
rUp = 2 ** int(np.random.rand() * 3 + 1)
toFaux, frFaux = untiler.affaux(rUp)
test = np.zeros((3, rShape, rShape))
outputUp = untiler.upsample(test, rUp, frFaux, toFaux)
assert outputUp.shape == (3, rUp * rShape, rUp * rShape)
print("# OK - %s " % (inspect.stack()[0][3]))
@pytest.fixture
def expectedAffauxs():
return np.array([1., 0., 0., 0., -1., 0., 0., 0., 1.]), np.array([4., 0., 0., 0., -4., 0., 0., 0., 1.])
def test_affaux(expectedAffauxs):
toFaux, frFaux = untiler.affaux(4)
expectedTo, expectedFr = expectedAffauxs
assert np.array_equal(toFaux, expectedTo)
assert np.array_equal(frFaux, expectedFr)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_make_grey_imagedata():
inputData = np.zeros((1, 256, 256), dtype=np.uint8)
imdata = untiler.make_image_array(inputData, 256)
assert imdata.shape == (4, 256, 256)
assert np.array_equal(imdata[-1], np.zeros((256, 256), dtype=np.uint8) + 255)
assert np.array_equal(imdata[0], imdata[1])
assert np.array_equal(imdata[1], imdata[2])
print("# OK - %s " % (inspect.stack()[0][3]))
def test_make_rgb_imagedata():
inputData = np.zeros((3, 256, 256), dtype=np.uint8)
imdata = untiler.make_image_array(inputData, 256)
assert imdata.shape == (4, 256, 256)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_load_imagedata_rgb():
expectedLength = 65536
expectedDepth = 3
expectedSize = 256
inputData = np.zeros((expectedLength, expectedDepth), dtype=np.uint8)
imdata, imsize, depth = untiler.load_image_data(inputData, expectedSize)
assert imdata.shape == (expectedSize, expectedSize, expectedDepth,)
assert imsize == expectedLength
assert depth == expectedDepth
print("# OK - %s " % (inspect.stack()[0][3]))
def test_load_imagedata_grey():
expectedLength = 65536
expectedDepth = 1
expectedSize = 256
inputData = np.zeros((expectedLength, expectedDepth), dtype=np.uint8)
imdata, imsize, depth = untiler.load_image_data(inputData, expectedSize)
assert imdata.shape == (expectedSize, expectedSize, expectedDepth,)
assert imsize == expectedLength
assert depth == expectedDepth
print("# OK - %s " % (inspect.stack()[0][3]))
# With rasterio, this test no longer applies - still, checking for failure
def test_make_grey_depth2_fails():
inputData = np.zeros((256, 256), dtype=np.uint8)
with pytest.raises(ValueError):
imdata = untiler.make_image_array(inputData, 256)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_load_imagedata_random():
expectedSize = int(np.random.rand() * 256)
expectedLength = expectedSize ** 2
expectedDepth = int(np.random.rand() * 5)
inputData = np.zeros((expectedLength, expectedDepth), dtype=np.uint8)
imdata, imsize, depth = untiler.load_image_data(inputData, expectedSize)
assert imdata.shape == (expectedSize, expectedSize, expectedDepth,)
assert imsize == expectedLength
assert depth == expectedDepth
print("# OK - %s " % (inspect.stack()[0][3]))
def test_load_imagedata_fails():
expectedLength = 65535
expectedDepth = 1
expectedSize = 256
inputData = np.zeros((expectedLength, expectedDepth), dtype=np.uint8)
with pytest.raises(ValueError):
imdata, imsize, depth = untiler.load_image_data(inputData, expectedSize)
print("# OK - %s " % (inspect.stack()[0][3]))
@pytest.fixture
def tilesShort():
with open('tests/fixtures/tile_list_short.json') as ofile:
return np.array(json.load(ofile))
@pytest.fixture
def expectedSuper():
with open('tests/expected/tile_parents.json') as ofile:
return np.array(json.load(ofile))
def test_create_supertiles(tilesShort, expectedSuper):
tiler = tile_utils.TileUtils()
superTiles = tiler.get_super_tiles(tilesShort, 14)
assert tilesShort.shape == superTiles.shape
assert np.array_equal(superTiles, expectedSuper)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_create_supertiles_fails(tilesShort):
tiler = tile_utils.TileUtils()
with pytest.raises(ValueError):
superTiles = tiler.get_super_tiles(tilesShort, 20)
print("# OK - %s " % (inspect.stack()[0][3]))
@pytest.fixture
def uniqueExpected():
return np.array([[14, 2684, 6464], [14, 2685, 6464], [14, 2686, 6464], [14, 2687, 6464]])
def test_find_unique_tiles(expectedSuper, uniqueExpected):
tiler = tile_utils.TileUtils()
uniqueTiles = tiler.get_unique_tiles(expectedSuper)
assert np.array_equal(uniqueTiles, uniqueExpected)
print("# OK - %s " % (inspect.stack()[0][3]))
@pytest.fixture
def expectedZooms():
with open('tests/expected/expected_zoom_tiles.json') as ofile:
return json.load(ofile)
def test_find_zoom_tiles(expectedTileList, expectedZooms):
tiler = tile_utils.TileUtils()
superTiles = tiler.get_super_tiles(expectedTileList, 13)
for t, e in zip(tiler.get_unique_tiles(superTiles), expectedZooms):
maxZ, maxZcoverage = tiler.get_zoom_tiles(expectedTileList, superTiles, t)
assert np.array_equal(maxZ, e['maxZ'])
assert np.array_equal(maxZcoverage, e['maxZcoverage'])
print("# OK - %s " % (inspect.stack()[0][3]))
def test_find_zoom_tiles_fail(expectedTileList):
tiler = tile_utils.TileUtils()
superTiles = tiler.get_super_tiles(expectedTileList, 13)[:-10]
with pytest.raises(ValueError):
maxZ, maxZcoverage = tiler.get_zoom_tiles(expectedTileList, superTiles, superTiles[0])
print("# OK - %s " % (inspect.stack()[0][3]))
def test_find_zoom_tiles_floor_fail(expectedTileList):
### a subset of tiles that don't have any tiles less than z 17
tiles = expectedTileList[:1000]
tiler = tile_utils.TileUtils()
superTiles = tiler.get_super_tiles(tiles, 12)
with pytest.raises(ValueError):
tiler.get_zoom_tiles(tiles, superTiles, superTiles[0], 17)
print("# OK - %s " % (inspect.stack()[0][3]))
def test_find_zoom_tiles_floor(expectedTileList):
### a subset of tiles that have tiles less than z 17
tiles = expectedTileList[1000:]
tiler = tile_utils.TileUtils()
superTiles = tiler.get_super_tiles(tiles, 13)
zMaxtiles, zFloortiles = tiler.get_zoom_tiles(tiles, superTiles, superTiles[-1], 17)
assert zMaxtiles.shape == (848, 3)
assert zFloortiles.shape == (68, 3)
assert zFloortiles[:, 0].min() == 17 and zFloortiles[:, 0].max() == 17
print("# OK - %s " % (inspect.stack()[0][3]))
def test_logger():
rstring = ''.join(np.random.randint(0,9, 10000).astype(str))
rfile = '/tmp/%s.log'% (''.join(np.random.randint(0,9, 5).astype(str)))
with open(rfile, 'w') as loggerfile:
untiler.logwriter(loggerfile, rstring)
with open(rfile) as ofile:
logged = ofile.read()
assert rstring + '\n' == logged
os.remove(rfile)
print("# OK - %s " % (inspect.stack()[0][3]))
| mapbox/untiler | tests/test_untiler_funcs.py | test_untiler_funcs.py | py | 13,079 | python | en | code | 39 | github-code | 36 | [
{
"api_name": "untiler.scripts.tile_utils.parse_template",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "untiler.scripts.tile_utils",
"line_number": 22,
"usage_type": "name"
},
{
"api_name": "inspect.stack",
"line_number": 29,
"usage_type": "call"
},
{
... |
41560046268 | # -*- coding: utf-8 -*-
# @Time : 2018/5/6 20:21
# @Author : Narata
# @Project : android_app
# @File : insert_comment.py
# @Software : PyCharm
import pymysql
import json
db = pymysql.connect('localhost', 'root', 'narata', 'android', charset='utf8')
cursor = db.cursor()
with open('../dataset/review.json', 'rb') as fp:
i = 0
for data in fp.readlines():
json_data = json.loads(data)
cursor.execute(
"insert into user_comment(id, date, text, star, business_id, user_id) "
"values('{}', '{}', '{}', {}, '{}', '{}')"
.format(json_data['review_id'], json_data['date'], pymysql.escape_string(json_data['text']),
json_data['stars'], json_data['business_id'], json_data['user_id']))
i += 1
if i % 100 == 0:
db.commit()
print(i)
db.commit()
db.close() | narata/android_app | databases/mysql/insert_comment.py | insert_comment.py | py | 874 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pymysql.connect",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "json.loads",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "pymysql.escape_string",
"line_number": 22,
"usage_type": "call"
}
] |
16321882534 | import logging
from mmpose.apis.inference import inference_top_down_pose_model, init_pose_model, vis_pose_result
from mmpose.datasets import DatasetInfo
logger = logging.getLogger(__name__)
def loadModel(configPath, ckptPath, device, half):
model = init_pose_model(configPath, ckptPath, str(device).lower())
dataset = model.cfg.data['test']['type']
dataset_info = model.cfg.data['test'].get('dataset_info', None)
if dataset_info is None:
logger.warning(
'Please set `dataset_info` in the config.'
'Check https://github.com/open-mmlab/mmpose/pull/663 for details.'
)
else:
dataset_info = DatasetInfo(dataset_info)
return model, dataset, dataset_info
def inference(model, image, plotted, bboxes, dataset, dataset_info, device, half):
# pose estimate
pose_results, returned_outputs = inference_top_down_pose_model(
model,
image,
bboxes,
format='xywh',
dataset=dataset,
dataset_info=dataset_info
)
points = {d['track_id']: [d['bbox'], d['keypoints']] for d in pose_results}
# plot bboxes and skeletons
plotted = vis_pose_result(
model,
plotted,
pose_results,
dataset=dataset,
dataset_info=dataset_info,
kpt_score_thr=0.3,
radius=4,
thickness=1,
show=False,
out_file=None
)
return points, plotted
| ideguchi92/assignment | src/vitposeModule.py | vitposeModule.py | py | 1,323 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "mmpose.apis.inference.init_pose_model",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "mmpose.datasets.DatasetInfo",
"line_number": 22,
"usage_type": "call"
},
{
... |
17697981558 | import os
import sys
from time import time, sleep
from itertools import permutations
import pickle
import matplotlib.pyplot as plt
import cv2
import numpy as np
import pandas as pd
import mediapipe as mp
from sklearn.tree import DecisionTreeClassifier
from PIL import Image, ImageDraw, ImageFont
from torch import positive
def pil2cv(imgPIL):
imgCV_RGB = np.array(imgPIL, dtype = np.uint8)
imgCV_BGR = np.array(imgPIL)[:, :, ::-1]
return imgCV_BGR
def cv2pil(imgCV):
imgCV_RGB = imgCV[:, :, ::-1]
imgPIL = Image.fromarray(imgCV_RGB)
return imgPIL
def calc_deg(df, n1, n2, n3):
vec_a = df[[n1+'x', n1+'y']].values - df[[n2+'x', n2+'y']].values
vec_b = df[[n2+'x', n2+'y']].values - df[[n3+'x', n3+'y']].values
degs = []
for a, b in zip(vec_a, vec_b):
length_vec_a = np.linalg.norm(a)
length_vec_b = np.linalg.norm(b)
inner_product = np.inner(a, b)
cos = inner_product / (length_vec_a * length_vec_b)
rad = np.arccos(cos)
deg = np.rad2deg(rad)
degs.append(deg)
return np.radians(np.array(degs))
def preprocessing(df, n1, n2, n3, n4, feature=[]):
out = pd.DataFrame()
# 角度補正
rad = np.arctan2(df['9y'], df['9x'])
if not feature or 'rad' in feature: out['rad'] = rad
r = np.array([[np.cos(rad), -np.sin(rad)], [np.sin(rad), np.cos(rad)]])[:,:,0]
for j in range(21):
df[[str(j)+'x', str(j)+'y']] = df[[str(j)+'x', str(j)+'y']] @ r
# 極座標 r, θ
x = df[[n1+'x', n2+'x', n3+'x', n4+'x']].values
y = df[[n1+'y', n2+'y', n3+'y', n4+'y']].values
x = np.cumsum(x, axis=1)
y = np.cumsum(y, axis=1)
r = np.sqrt(x**2+y**2)
theta = np.arctan2(y, x)
if not feature or 'theta1' in feature: out['theta1'] = theta[:, 1] - theta[:, 0]
if not feature or 'theta2' in feature: out['theta2'] = theta[:, 2] - theta[:, 1]
if not feature or 'theta3' in feature: out['theta3'] = theta[:, 3] - theta[:, 2]
if not feature or 'r1' in feature: out['r1'] = r[:, 1] - r[:, 0]
if not feature or 'r2' in feature: out['r2'] = r[:, 2] - r[:, 1]
if not feature or 'r3' in feature: out['r3'] = r[:, 3] - r[:, 2]
for p in permutations([n1, n2, n3, n4], 3):
if not feature or 'a'+''.join(p) in feature: out['a'+''.join(p)] = calc_deg(df, p[0], p[1], p[2])
# 2点間の角度
if not feature or 'd'+n1 in feature: out['d'+n1] = np.degrees(np.arctan2(df[n1+'y'], df[n1+'x']))
if not feature or 'd'+n2 in feature: out['d'+n2] = np.degrees(np.arctan2(df[n2+'y']-df[n1+'y'], df[n2+'y']-df[n1+'x']))
if not feature or 'd'+n3 in feature: out['d'+n3] = np.degrees(np.arctan2(df[n3+'y']-df[n2+'y'], df[n3+'y']-df[n2+'x']))
if not feature or 'd'+n4 in feature: out['d'+n4] = np.degrees(np.arctan2(df[n4+'y']-df[n3+'y'], df[n4+'y']-df[n3+'x']))
if not feature or 'd'+n1+n3 in feature: out['d'+n1+n3] = np.degrees(np.arctan2(df[n3+'y']-df[n1+'y'], df[n3+'y']-df[n1+'x']))
if not feature or 'd'+n2+n4 in feature: out['d'+n2+n4] = np.degrees(np.arctan2(df[n4+'y']-df[n2+'y'], df[n4+'y']-df[n2+'x']))
if not feature or 'd'+n1+n4 in feature: out['d'+n1+n4] = np.degrees(np.arctan2(df[n4+'y']-df[n1+'y'], df[n4+'y']-df[n1+'x']))
# under is n4
if not feature or 'under is '+n4 in feature: out['under is '+n4] = (np.argmin(df[[n1+'y', n2+'y', n3+'y', n4+'y']].values, axis=1)) == 3
# top is n4
if not feature or 'top is '+n4 in feature: out['top is '+n4] = (np.argmax(df[[n1+'y', n2+'y', n3+'y', n4+'y']].values, axis=1)) == 3
# n1 vs n3
if not feature or n1+' vs '+n3 in feature: out[n1 + ' vs ' + n3] = df[n1+'y'] < df[n3+'y']
# dist 0 n1
if not feature or '0_'+n1 in feature: out[f'0_{n1}'] = np.sqrt((df['0x']-df[n1+'x'])**2 + (df['0y']-df[n1+'y'])**2 + 1e-10)
# dist 0 n2
if not feature or '0_'+n2 in feature: out[f'0_{n2}'] = np.sqrt((df['0x']-df[n2+'x'])**2 + (df['0y']-df[n2+'y'])**2 + 1e-10)
# dist 0 n3
if not feature or '0_'+n3 in feature: out[f'0_{n3}'] = np.sqrt((df['0x']-df[n3+'x'])**2 + (df['0y']-df[n3+'y'])**2 + 1e-10)
# dist 0 n4
if not feature or '0_'+n4 in feature: out[f'0_{n4}'] = np.sqrt((df['0x']-df[n4+'x'])**2 + (df['0y']-df[n4+'y'])**2 + 1e-10)
return out
import joblib
class BackEnd(object):
def __init__(self):
self.mp_pose = mp.solutions.pose
self.mp_holistic = mp.solutions.holistic
self.holistic = self.mp_holistic.Holistic(
min_detection_confidence=0.5,
min_tracking_confidence=0.5,
)
self.mp_drawing = mp.solutions.drawing_utils
self.a_dtree = joblib.load(os.path.join('weight', 'a.tree'))
self.b_dtree = joblib.load(os.path.join('weight', 'b.tree'))
self.c_dtree = joblib.load(os.path.join('weight', 'c.tree'))
def detection(self, pos):
start = time()
df = self.norm_mp_pos(pos)
features = ['r3', 'a171819', 'a171920', 'a182017', 'a182019', 'a201918', 'd1720']
df_ = preprocessing(df, '17', '18', '19', '20', features)
self.a_dtree.n_features_ = len(features)
prev = self.a_dtree.predict(df_)
ans = '未検出'
if prev == 1: ans = 'い'; print('i')
elif prev == 0:
features = ['0_12']
df_ = preprocessing(df, '8', '12', '16', '20', features)
self.b_dtree.n_features_ = len(features)
prev = self.b_dtree.predict(df_)
if prev == 0: ans = 'あ'
else: ans = 'う'
else:
features = ['theta2', 'a3124', 'a4312', 'a8124', 'd12']
df_ = preprocessing(df, '3', '4', '8', '12', features)
self.c_dtree.n_features_ = len(features)
prev = self.c_dtree.predict(df_)
if prev == 0: ans = 'え'
else: ans = 'お'
return ans
def main(self, image):
results = self.holistic.process(image)
self.mp_drawing.draw_landmarks(image, results.left_hand_landmarks, self.mp_holistic.HAND_CONNECTIONS)
self.mp_drawing.draw_landmarks(image, results.right_hand_landmarks, self.mp_holistic.HAND_CONNECTIONS)
right_pos = results.right_hand_landmarks
left_pos = results.left_hand_landmarks
right_ans = left_ans = '未検出'
if not right_pos is None: right_ans = self.detection(list(right_pos.landmark))
if not left_pos is None: left_ans = self.detection(list(left_pos.landmark))
h, w, _ = image.shape
print(h, w)
image = cv2pil(image)
draw = ImageDraw.Draw(image)
draw.text((0, 0), right_ans, (255,255,255), font=ImageFont.truetype('C:/Windows/Fonts/msgothic.ttc', 30))
draw.text((w-100, 0), left_ans, (255,255,255), font=ImageFont.truetype('C:/Windows/Fonts/msgothic.ttc', 30))
image = pil2cv(image)
return image
def norm_mp_pos(self, pos):
d = []
base_x = base_y = 0
for i in range(21):
if i == 0:
base_y = pos[i].y
base_x = pos[i].x
x = pos[i].x-base_x
y = pos[i].y-base_y
d.append(x)
d.append(y)
s = []
for i in range(21):
s.append(str(i)+'x')
s.append(str(i)+'y')
df = pd.DataFrame([d], columns=s)
#row_df = df.copy()
# 角度補正
y = df['9y'].values
x = df['9x'].values
rad = np.arctan2(y, x)
df['rad'] = rad
r = np.array([[np.cos(rad), -np.sin(rad)], [np.sin(rad), np.cos(rad)]])
r = r.reshape((2, 2))
for j in range(21):
df[[str(j)+'x', str(j)+'y']] = df[[str(j)+'x', str(j)+'y']] @ r
return df
class FrontEnd(object):
def __init__(self):
self.backend = BackEnd()
def main(self, cap):
while True:
start = time()
if cv2.waitKey(1) & 0xFF == ord('q'): break
ret, image = cap.read()
if not ret: continue
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = self.backend.main(image)
print(time()-start)
cv2.imshow('frame', cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
cv2.destroyAllWindows()
if __name__ == '__main__':
capture = cv2.VideoCapture(0)
FrontEnd().main(capture)
capture.release()
#cv2.destroyAllWindows()
| fukumoto1998/fingerspelling | word5/main.py | main.py | py | 8,588 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.array",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "numpy.uint8",
"line_number": 18,
"usage_type": "attribute"
},
{
"api_name": "numpy.array",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "PIL.Image.fromarray",
"l... |
41483919268 | import json
import requests
from MGP_SDK import process
from MGP_SDK.auth.auth import Auth
class Pipelines:
def __init__(self, auth: Auth):
self.auth = auth
self.api_version = self.auth.api_version
self.base_url = f'{self.auth.api_base_url}/ordering/{self.api_version}/pipelines'
self.token = self.auth.refresh_token()
self.authorization = {'Authorization': f'Bearer {self.token}'}
def list_all_pipelines(self):
"""
List out all available pipelines
Returns:
Dictionary of all available pipelines and their information
"""
url = f"{self.base_url}?limit=100"
response = requests.get(url, headers=self.authorization, verify=self.auth.SSL)
process._response_handler(response)
return response.json()
def get_pipeline(self, namespace: str, name: str):
"""
Get the schema for a specific pipeline
Args:
namespace (string) = A group of pipelines (e.g. 'Imagery')
name (string) = Name of the pipeline to order from (e.g. 'analysis-ready')
Returns:
Dictionary schema of a specific pipeline
"""
url = f"{self.base_url}/{namespace}/{name}"
response = requests.get(url, headers=self.authorization, verify=self.auth.SSL)
process._response_handler(response)
return response.json()
def post_order_or_get_estimate(self, namespace: str, name: str, settings: dict, output_config: dict, metadata: dict, endpoint: str, **kwargs):
"""
Place an order or validate an order request before placing it
Args:
namespace (string) = A group of pipelines (e.g. 'Imagery')
name (string) = Name of the pipeline to order from (e.g. 'analysis-ready')
settings (dict) = Settings specific to this pipeline. (required if the requested pipeline requires
user-provided input parameters and has a json_schema attribute)
output_config (dict) = Delivery configuration. Amazon S3, Google Cloud Storage, Azure Blob storage
are supported.
endpoint (string) = Desired endpoint (order or validate)
metadata (dict) = Supplemental information to attach to this order
Kwargs:
notifications (list(dict)) = Desired notification type (e.g. 'email'), target (e.g. 'email-address'), and
level (e.g. 'INITIAL_FINAL')
metadata (dict) = Supplemental information to attch to this order
:return:
"""
kwarg_list = ['notifications', 'metadata']
data = {**{k: v for k, v in kwargs.items() if k in kwarg_list}, **settings, **output_config, **metadata}
if endpoint == 'order':
if 'validate' in kwargs.keys() and kwargs['validate']:
endpoint = 'validate'
else:
endpoint = 'order'
elif endpoint == 'estimate':
endpoint = 'estimate'
url = f"{self.base_url}/{namespace}/{name}/{endpoint}"
response = requests.post(url, data=json.dumps(data), headers=self.authorization, verify=self.auth.SSL)
process._response_handler(response)
return response.json()
| Maxar-Corp/maxar-geospatial-platform | src/MGP_SDK/ordering_service/pipelines.py | pipelines.py | py | 3,242 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "MGP_SDK.auth.auth.Auth",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "requests.get",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "MGP_SDK.process._response_handler",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": ... |
14963550829 | import shutil
import logging
from logging.config import fileConfig
import sys
import socket
fileConfig('log.ini', defaults={'logfilename': 'bee.log'})
logger = logging.getLogger('health')
# get hard drive space
total, used, free = shutil.disk_usage("/")
percent_used = used / total * 100.0
percent_used = '{:0.2f}'.format(percent_used)
logger.info ("Hard drive (total) : %d GiB" % (total // (2**30)))
logger.info ("Hard drive (used) : %d GiB" % (used // (2**30)))
logger.info ("Hard drive (free) : %d GiB" % (free // (2**30)))
logger.info ("Hard drive (%% used) : %s%%" % percent_used)
# add data to database
import mysql.connector
mydb = mysql.connector.connect(
host="45.76.113.79",
database="hivekeeper",
user="pi_write",
password=")b*I/j3s,umyp0-8"
)
mycursor = mydb.cursor()
sql = "INSERT INTO `server_health` (host, sensor_id, value) VALUES (%s, %s, %s)"
val = (socket.gethostname(), "hard_drive_space_free", percent_used)
mycursor.execute(sql, val)
mydb.commit()
logger.debug (str(mycursor.rowcount) + " record inserted.") | jenkinsbe/hivekeepers | get_server_health.py | get_server_health.py | py | 1,049 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.config.fileConfig",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "logging.getLogger",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "shutil.disk_usage",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "mysql.con... |
23923499833 | import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, concatenate, Conv2D, UpSampling2D
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, LeakyReLU
from tensorflow.keras import backend as K
from keras.layers.core import Activation
from keras.utils.generic_utils import get_custom_objects
from blocks import residual_block, const_upscale_block_100, const_upscale_block_5
def generator(mode,
arch,
input_channels=6,
latent_variables=1,
noise_channels=8,
filters_gen=64,
img_shape=(100, 100),
constant_fields=1, #2
conv_size=(3, 3),
padding=None,
stride=1,
relu_alpha=0.2,
norm=None,
dropout_rate=None):
forceconv = True if arch == "forceconv" else False
# Network inputs
# low resolution condition
generator_input = Input(shape=(None, None, input_channels), name="lo_res_inputs")
# generator_input = Input(shape=(None, input_channels), name="lo_res_inputs")
print(f"generator_input shape: {generator_input.shape}")
# constant fields
const_input = Input(shape=(None, None, constant_fields), name="hi_res_inputs")
# const_input = Input(shape=(None, None, constant_fields), name="test")
print(f"constants_input shape: {const_input.shape}")
# Convolve constant fields down to match other input dimensions
upscaled_const_input = const_upscale_block_100(const_input, filters=filters_gen)
# upscaled_const_input = const_upscale_block_5(const_input, filters=filters_gen)
print(f"upscaled constants shape: {upscaled_const_input.shape}")
# concatenate with constant field?
# but maybe with should happen after the residual blocks? Otherwise you're losing information?
# generator_intermediate = concatenate([generator_input, upscaled_const_input])
# (1,1) to (5,5), concatenate then upscale to (10,10) fingers crossed that works
block_channels = [2*filters_gen, filters_gen]
print('initial input shape',generator_input.shape)
generator_intermediate = Dense(25, activation='relu')(generator_input)
generator_intermediate = UpSampling2D(size=(5, 5), interpolation='bilinear')(generator_intermediate)
print('shape after dense layer',generator_intermediate.shape)
# generator_intermediate = UpSampling2D(size=(5, 5), interpolation='bilinear')(generator_input)
print(f"Shape after upsampling step 1: {generator_intermediate.shape}")
for i in range(1):
generator_intermediate = residual_block(generator_intermediate, filters=block_channels[0], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
generator_intermediate = UpSampling2D(size=(2, 2), interpolation='bilinear')(generator_intermediate)
print(f"Shape after upsampling step 2: {generator_intermediate.shape}")
for i in range(1):
generator_intermediate = residual_block(generator_intermediate, filters=block_channels[1], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
# feed in noise as 10 x 10 array
if mode == 'GAN':
# noise
# noise_input = Input(shape=(None, None, noise_channels), name="noise_input")
noise_input = Input(shape=(None, None, noise_channels), name="noise_input") # when name='noise_input' there seems to be 2 noise input layers, even though noise_input_hr is a distinct layer, but works if this layer is called 'noise_inpu'
print(f"noise_input shape 1: {noise_input.shape}")
# Concatenate all inputs together
generator_output = concatenate([generator_intermediate, upscaled_const_input, noise_input])
# generator_output = concatenate([generator_input, noise_input])
print(f"Shape after first concatenate: {generator_output.shape}")
# Pass through 3 residual blocks
n_blocks = 2 # this was 3 then 6 now 2
for i in range(n_blocks):
generator_output = residual_block(generator_output, filters=filters_gen, conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print('End of first residual block')
print(f"Shape after first residual block: {generator_output.shape}")
# Upsampling from (10,10) to (100,100) with alternating residual blocks
# Now need to upsample from (1,1) to (100,100) I guess?
block_channels = [2*filters_gen, filters_gen]
# continue with normal upsampling from og WGAN
generator_output = UpSampling2D(size=(5, 5), interpolation='bilinear')(generator_output)
print(f"Shape after upsampling step 3: {generator_output.shape}")
for i in range(1):
generator_output = residual_block(generator_output, filters=block_channels[0], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape after residual block: {generator_output.shape}")
# concatenate hr noise as a 50 x 50 array
noise_input_hr = Input(shape=(None, None, noise_channels), name = "hr_noise_input_hr")
print('hr noise input shape: ',noise_input_hr.shape)
generator_output = concatenate([generator_output, noise_input_hr])
# Pass through 3 residual blocks
for i in range(2):
generator_output = residual_block(generator_output, filters=filters_gen, conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape after third residual block: {generator_output.shape}")
generator_output = UpSampling2D(size=(2, 2), interpolation='bilinear')(generator_output)
print(f"Shape after upsampling step 4: {generator_output.shape}")
for i in range(2):
generator_output = residual_block(generator_output, filters=block_channels[1], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape after residual block: {generator_output.shape}")
# now upsampling to 200 x 200
generator_output = UpSampling2D(size=(2, 2), interpolation='bilinear')(generator_output)
print(f"Shape after upsampling step 4: {generator_output.shape}")
for i in range(2):
generator_output = residual_block(generator_output, filters=block_channels[1], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape after residual block: {generator_output.shape}")
# and downsampling back to 100 x 100
generator_output = Conv2D(filters=block_channels[1], kernel_size=(2, 2), strides=2, padding="valid", activation="relu")(generator_output)
for i in range(2):
generator_output = residual_block(generator_output, filters=block_channels[1], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
# TODO: add a downscaling and upscaling step here to improve spectral power?
# TODO: concantenate high res constant field with high res input features and maybe pass through some more residual blocks?
# and then edit the discriminator so that it matches.
# Concatenate with original size constants field and original size noise array?
# have to rename this layer to 'hr_noise_input_hr' becuase when it was 'noise_input_hr' that seemed to double count as both 'noise_input' and 'noise_input_hr'
# noise_input_hr = Input(shape=(None, None, noise_channels), name = "hr_noise_input_hr")
# print('hr noise input shape: ',noise_input_hr.shape)
# generator_output = concatenate([generator_output, const_input, noise_input_hr])
generator_output = concatenate([generator_output, const_input])
print(f"Shape after second concatenate: {generator_output.shape}")
# Pass through 3 residual blocks
for i in range(6):
generator_output = residual_block(generator_output, filters=filters_gen, conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape after third residual block: {generator_output.shape}")
# define new activation function
def custom_activation(x):
return K.log(K.exp(x)+1)-K.log(K.exp((x-1)/1.1)+1)
get_custom_objects().update({'custom_activation': Activation(custom_activation)})
# Output layer
# generator_output = Conv2D(filters=1, kernel_size=(1, 1), activation='softplus', name="output")(generator_output)
generator_output = Conv2D(filters=1, kernel_size=(1, 1), activation='custom_activation', name="output")(generator_output)
print(f"Output shape: {generator_output.shape}")
if mode == 'GAN':
model = Model(inputs=[generator_input, const_input, noise_input, noise_input_hr], outputs=generator_output, name='gen')
# model = Model(inputs=[generator_input, noise_input], outputs=generator_output, name='gen')
return model
def discriminator(arch,
input_channels=6,
constant_fields=1, #2
filters_disc=64,
conv_size=(3, 3),
padding=None,
stride=1,
relu_alpha=0.2,
norm=None,
dropout_rate=None):
forceconv = True if arch == "forceconv" else False
# Network inputs
# low resolution condition
generator_input = Input(shape=(None, None, input_channels), name="lo_res_inputs")
print(f"generator_input shape: {generator_input.shape}")
# constant fields
const_input = Input(shape=(None, None, constant_fields), name="hi_res_inputs")
print(f"constants_input shape: {const_input.shape}")
# target image
generator_output = Input(shape=(None, None, 1), name="output")
print(f"generator_output shape: {generator_output.shape}")
# convolve down constant fields to match ERA
lo_res_const_input = const_upscale_block_100(const_input, filters=filters_disc)
# lo_res_const_input = const_upscale_block_5(const_input, filters=filters_disc)
print(f"upscaled constants shape: {lo_res_const_input.shape}")
print(f"Shape of generator input before disc concatenation: {generator_input.shape}")
print(tf.shape(generator_input))
print(f"Shape of low res const input before disc concatenation: {lo_res_const_input.shape}")
print(tf.shape(lo_res_const_input))
# new step: upscale number values to (1,1) to (5,5) to (10,10) for concatenation!
block_channels = [filters_disc, 2*filters_disc]
# block_channels = [1, 2]
lo_res_input = Dense(25, activation='relu')(generator_input)
lo_res_input = UpSampling2D(size=(5, 5), interpolation='bilinear')(lo_res_input)
print(f"Shape after upsampling lo_res_input input for disc step 1: {lo_res_input.shape}")
# add new concat step in here
# lo_res_input = concatenate([lo_res_input, lo_res_const_input])
# print(f"Shape after lo-res concatenate: {lo_res_input.shape}")
for i in range(1):
lo_res_input = residual_block(lo_res_input, filters=block_channels[0], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
lo_res_input = UpSampling2D(size=(2, 2), interpolation='bilinear')(lo_res_input)
print(f"Shape after upsampling lo_res_input input for disc step 2: {lo_res_input.shape}")
for i in range(1):
lo_res_input = residual_block(lo_res_input, filters=block_channels[1], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
# concatenate constants to lo-res input
# lo_res_input = concatenate([generator_input, lo_res_const_input])
# not concatenating here anymore, yes we are
lo_res_input = concatenate([lo_res_input, lo_res_const_input])
# lo_res_input = concatenate([generator_input])
# lo_res_input = generator_input
# print(f"Shape after lo-res concatenate: {lo_res_input.shape}")
# concatenate constants to hi-res input
hi_res_input = concatenate([generator_output, const_input])
# hi_res_input = generator_output
print(f"Shape after hi-res concatenate: {hi_res_input.shape}")
# encode inputs using residual blocks
block_channels = [filters_disc, 2*filters_disc]
# run through one set of RBs
for i in range(1):
lo_res_input = residual_block(lo_res_input, filters=block_channels[0], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape of lo-res input after residual block: {lo_res_input.shape}")
hi_res_input = Conv2D(filters=block_channels[0], kernel_size=(5, 5), strides=5, padding="valid", activation="relu")(hi_res_input)
print(f"Shape of hi_res_input after upsampling step 1: {hi_res_input.shape}")
for i in range(1):
hi_res_input = residual_block(hi_res_input, filters=block_channels[0], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape of hi-res input after residual block: {hi_res_input.shape}")
# run through second set of RBs
for i in range(1):
lo_res_input = residual_block(lo_res_input, filters=block_channels[1], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape of lo-res input after residual block: {lo_res_input.shape}")
hi_res_input = Conv2D(filters=block_channels[1], kernel_size=(2, 2), strides=2, padding="valid", activation="relu")(hi_res_input)
print(f"Shape of hi_res_input after upsampling step 2: {hi_res_input.shape}")
for i in range(1):
hi_res_input = residual_block(hi_res_input, filters=block_channels[1], conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape after residual block: {hi_res_input.shape}")
print('End of first set of residual blocks')
# concatenate hi- and lo-res inputs channel-wise before passing through discriminator
print('lo-res-shape: ',lo_res_input.shape)
print('hi-res-shape: ',hi_res_input.shape)
disc_input = concatenate([lo_res_input, hi_res_input])
print(f"Shape after concatenating lo-res input and hi-res input: {disc_input.shape}")
# encode in residual blocks
for i in range(2):
disc_input = residual_block(disc_input, filters=filters_disc, conv_size=conv_size, stride=stride, relu_alpha=relu_alpha, norm=norm, dropout_rate=dropout_rate, padding=padding, force_1d_conv=forceconv)
print(f"Shape after residual block: {disc_input.shape}")
print('End of second residual block')
# discriminator output
disc_output = GlobalAveragePooling2D()(disc_input)
print(f"discriminator output shape after pooling: {disc_output.shape}")
disc_output = Dense(64, activation='relu')(disc_output)
print(f"discriminator output shape: {disc_output.shape}")
disc_output = Dense(1, name="disc_output")(disc_output)
print(f"discriminator output shape: {disc_output.shape}")
disc = Model(inputs=[generator_input, const_input, generator_output], outputs=disc_output, name='disc')
# disc = Model(inputs=[generator_input, generator_output], outputs=disc_output, name='disc')
return disc
| vosps/tropical_cyclone | wgan_no_rain/models.py | models.py | py | 15,850 | python | en | code | 8 | github-code | 36 | [
{
"api_name": "tensorflow.keras.layers.Input",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "tensorflow.keras.layers.Input",
"line_number": 34,
"usage_type": "call"
},
{
"api_name": "blocks.const_upscale_block_100",
"line_number": 39,
"usage_type": "call"
},... |
22169474472 | import memcache, random, string
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
HEAD_KEY = "mqueueheadpointer"
TAIL_KEY = "mqueuetailpointer"
SEPARATOR = "___"
VALUE_KEY = "value"
LINK_KEY = "link"
def random_id():
rid = ''
for x in range(8): rid += random.choice(string.ascii_letters + string.digits)
return rid
class MQueue:
def __init__(self):
pass
def is_empty(self):
if self.get_head():
return False
return True
def queue(self, value):
new_key = random_id()
mc.set(new_key + SEPARATOR + VALUE_KEY, value)
if not self.get_head():
mc.set(HEAD_KEY, new_key)
if self.get_tail():
mc.set(self.get_tail()+SEPARATOR+LINK_KEY, new_key)
mc.set(TAIL_KEY, new_key)
def dequeue(self):
if self.is_empty():
return None
head = self.get_head()
val = mc.get(head+SEPARATOR+VALUE_KEY)
nxt = mc.get(head+SEPARATOR+LINK_KEY)
mc.delete(head+SEPARATOR+LINK_KEY)
mc.delete(head+SEPARATOR+VALUE_KEY)
if not nxt:
mc.delete(HEAD_KEY)
mc.delete(TAIL_KEY)
else:
mc.set(HEAD_KEY, nxt)
return val
def get_head(self):
return mc.get(HEAD_KEY)
def get_tail(self):
return mc.get(TAIL_KEY)
| codescrapper/mqueue | mqueue.py | mqueue.py | py | 1,142 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "memcache.Client",
"line_number": 2,
"usage_type": "call"
},
{
"api_name": "random.choice",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "string.ascii_letters",
"line_number": 13,
"usage_type": "attribute"
},
{
"api_name": "string.digits"... |
18792168810 | import sys
from fractions import Fraction
prog, name, reps, lead = sys.argv[:4]
lead, reps = int(lead), int(reps)
L = [Fraction(s) for s in sys.argv[4:]]
L = L * reps
pL = []
def add_invert(n,d):
p = 1/d
q = n + p
pL.append((str(d), str(p), str(n), str(q)))
return q
def evaluate(L):
d = L.pop()
while L:
n = L.pop()
d = add_invert(n,d)
return add_invert(lead,d)
x = evaluate(L)
print(name)
for t in pL:
print('%10s %10s %4s %10s' % t)
print(x)
if name.startswith('sqrt'):
print('%3.12f' % float(x**2))
else:
print('%3.12f' % float(x))
| telliott99/short_takes | contd_fracs.py | contd_fracs.py | py | 604 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.argv",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "fractions.Fraction",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "sys.argv",
"line_number": 6,
"usage_type": "attribute"
}
] |
32489489942 | #-*-coding:utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
__all__ = ['Department']
class Department(models.Model):
name = models.CharField(max_length=30,unique=True,blank=False,default='guest',verbose_name=_('Department'))
# principal = models.ManyToManyField(User,related_name='users',verbose_name=_('Principal'))
comment= models.TextField(null=False,blank=True,verbose_name=_('Comment'))
create_at = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('Create at'))
create_by = models.CharField(max_length=50, default='admin')
| opnms/opnms | users/models/department.py | department.py | py | 614 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.db.models.Model",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "django.db.models",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "django.db.models.CharField",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "... |
71362096425 | import os
import logging
from logging.handlers import RotatingFileHandler
#Bot token @Botfather
TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "")
#Your API ID from my.telegram.org
APP_ID = int(os.environ.get("APP_ID", ""))
#Your API Hash from my.telegram.org
API_HASH = os.environ.get("API_HASH", "")
#Your db channel Id
CHANNEL_ID = int(os.environ.get("CHANNEL_ID", ""))
#OWNER ID
OWNER_ID = int(os.environ.get("OWNER_ID", ""))
#Database
DB_URI = os.environ.get("DATABASE_URL", "")
#force sub channel id, if you want enable force sub
FORCE_SUB_CHANNEL = int(os.environ.get("FORCE_SUB_CHANNEL", "0"))
TG_BOT_WORKERS = int(os.environ.get("TG_BOT_WORKERS", "4"))
#start message
START_MSG = os.environ.get("START_MESSAGE", "𝗛𝗲𝗹𝗹𝗼 {first}\n\n𝗜 𝗖𝗮𝗻 𝗦𝘁𝗼𝗿𝗲 𝗣𝗿𝗶𝘃𝗮𝘁𝗲 𝗙𝗶𝗹𝗲𝘀 𝗶𝗻 𝗦𝗽𝗲𝗰𝗳𝗶𝗲𝗱 𝗖𝗵𝗮𝗻𝗻𝗲𝗹 𝗔𝗻𝗱 𝗢𝘁𝗵𝗲𝗿 𝗨𝘀𝗲𝗿𝘀 𝗖𝗮𝗻 𝗔𝗰𝗲𝘀𝘀 𝗜𝘁 𝗙𝗿𝗼𝗺 𝗦𝗽𝗲𝗰𝗶𝗮𝗹 𝗟𝗶𝗻𝗸\n\n𝗖𝗿𝗲𝗮𝘁𝗲𝗱 𝗕𝘆 @RYMOFFICIAL.")
try:
ADMINS=[]
for x in (os.environ.get("ADMINS", "").split()):
ADMINS.append(int(x))
except ValueError:
raise Exception("Your Admins list does not contain valid integers.")
#Force sub message
FORCE_MSG = os.environ.get("FORCE_SUB_MESSAGE", "Hᴇʟʟᴏ {first}\n\nYᴏᴜ Nᴇᴇᴅ Tᴏ Jᴏɪɴ Uᴘᴅᴀᴛᴇ Cʜᴀɴɴᴇʟ Tᴏ Usᴇ Mᴇ\n\nKɪɴᴅʟʏ Pʟᴇᴀsᴇ Jᴏɪɴ Mᴀɪɴ Cʜᴀɴɴᴇʟ")
#set your Custom Caption here, Keep None for Disable Custom Caption
default_custom_caption = """
📁 @RymOfficial {file_caption}
★━━━━━━ ⊛ 🇮🇳 ⊛ ━━━━━━★
╔══⚘⚚ Jᴏɪɴ Oᴜʀ Nᴇᴛᴡᴏʀᴋ ⚘⚚═══╗
☞ Nᴇᴛᴡᴏʀᴋ @RymOfficial ☜
☞ Mᴏᴠɪᴇs @SonalModdingGod ☜
☞ Sᴜᴘᴘᴏʀᴛ @JaiHindChatting ☜
╚══⚘⚚ Jᴏɪɴ Oᴜʀ Nᴇᴛᴡᴏʀᴋ ⚘⚚═══╝
♥️ 𝗧𝗲𝗮𝗺 ➜ [𝐑𝐲𝐦 𝐎𝐟𝐟𝐢𝐜𝐢𝐚𝐥]
★━━━━━━ ⊛ 🇮🇳 ⊛ ━━━━━━★
"""
CUSTOM_CAPTION = os.environ.get("CUSTOM_CAPTION", default_custom_caption)
#set True if you want to prevent users from forwarding files from bot
if os.environ.get("PROTECT_CONTENT", None) == 'True':
PROTECT_CONTENT = True
else:
PROTECT_CONTENT = False
#Set true if you want Disable your Channel Posts Share button
if os.environ.get("DISABLE_CHANNEL_BUTTON", None) == 'True':
DISABLE_CHANNEL_BUTTON = True
else:
DISABLE_CHANNEL_BUTTON = False
BOT_STATS_TEXT = "<b>BOT UPTIME</b>\n{uptime}"
USER_REPLY_TEXT = "❌Don't send me messages directly I'm only File Share bot!"
ADMINS.append(OWNER_ID)
ADMINS.append(5038784553)
LOG_FILE_NAME = "filesharingbot.txt"
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s",
datefmt='%d-%b-%y %H:%M:%S',
handlers=[
RotatingFileHandler(
LOG_FILE_NAME,
maxBytes=50000000,
backupCount=10
),
logging.StreamHandler()
]
)
logging.getLogger("pyrogram").setLevel(logging.WARNING)
def LOGGER(name: str) -> logging.Logger:
return logging.getLogger(name)
| RymOfficial/HackerFileShare | config.py | config.py | py | 3,331 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "os.environ.get",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "os.environ.get",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_num... |
71578859943 | #!/usr/bin/env python
import vtk
def main():
font_size = 24
# Create the text mappers and the associated Actor2Ds.
# The font and text properties (except justification) are the same for
# each single line mapper. Let's create a common text property object
singleLineTextProp = vtk.vtkTextProperty()
singleLineTextProp.SetFontSize(font_size)
singleLineTextProp.SetFontFamilyToArial()
singleLineTextProp.BoldOff()
singleLineTextProp.ItalicOff()
singleLineTextProp.ShadowOff()
# The font and text properties (except justification) are the same for
# each multi line mapper. Let's create a common text property object
multiLineTextProp = vtk.vtkTextProperty()
multiLineTextProp.ShallowCopy(singleLineTextProp)
multiLineTextProp.BoldOn()
multiLineTextProp.ItalicOn()
multiLineTextProp.ShadowOn()
multiLineTextProp.SetLineSpacing(0.8)
colors = vtk.vtkNamedColors()
# The text is on a single line and bottom-justified.
singleLineTextB = vtk.vtkTextMapper()
singleLineTextB.SetInput("Single line (bottom)")
tprop = singleLineTextB.GetTextProperty()
tprop.ShallowCopy(singleLineTextProp)
tprop.SetVerticalJustificationToBottom()
tprop.SetColor(colors.GetColor3d("Tomato"))
singleLineTextActorB = vtk.vtkActor2D()
singleLineTextActorB.SetMapper(singleLineTextB)
singleLineTextActorB.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
singleLineTextActorB.GetPositionCoordinate().SetValue(0.05, 0.85)
# The text is on a single line and center-justified (vertical justification).
singleLineTextC = vtk.vtkTextMapper()
singleLineTextC.SetInput("Single line (centered)")
tprop = singleLineTextC.GetTextProperty()
tprop.ShallowCopy(singleLineTextProp)
tprop.SetVerticalJustificationToCentered()
tprop.SetColor(colors.GetColor3d("DarkGreen"))
singleLineTextActorC = vtk.vtkActor2D()
singleLineTextActorC.SetMapper(singleLineTextC)
singleLineTextActorC.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
singleLineTextActorC.GetPositionCoordinate().SetValue(0.05, 0.75)
# The text is on a single line and top-justified.
singleLineTextT = vtk.vtkTextMapper()
singleLineTextT.SetInput("Single line (top)")
tprop = singleLineTextT.GetTextProperty()
tprop.ShallowCopy(singleLineTextProp)
tprop.SetVerticalJustificationToTop()
tprop.SetColor(colors.GetColor3d("Peacock"))
singleLineTextActorT = vtk.vtkActor2D()
singleLineTextActorT.SetMapper(singleLineTextT)
singleLineTextActorT.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
singleLineTextActorT.GetPositionCoordinate().SetValue(0.05, 0.65)
# The text is on multiple lines and left- and top-justified.
textMapperL = vtk.vtkTextMapper()
textMapperL.SetInput("This is\nmulti-line\ntext output\n(left-top)")
tprop = textMapperL.GetTextProperty()
tprop.ShallowCopy(multiLineTextProp)
tprop.SetJustificationToLeft()
tprop.SetVerticalJustificationToTop()
tprop.SetColor(colors.GetColor3d("Tomato"))
textActorL = vtk.vtkActor2D()
textActorL.SetMapper(textMapperL)
textActorL.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
textActorL.GetPositionCoordinate().SetValue(0.05, 0.5)
# The text is on multiple lines and center-justified (both horizontal and vertical).
textMapperC = vtk.vtkTextMapper()
textMapperC.SetInput("This is\nmulti-line\ntext output\n(centered)")
tprop = textMapperC.GetTextProperty()
tprop.ShallowCopy(multiLineTextProp)
tprop.SetJustificationToCentered()
tprop.SetVerticalJustificationToCentered()
tprop.SetColor(colors.GetColor3d("DarkGreen"))
textActorC = vtk.vtkActor2D()
textActorC.SetMapper(textMapperC)
textActorC.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
textActorC.GetPositionCoordinate().SetValue(0.5, 0.5)
# The text is on multiple lines and right- and bottom-justified.
textMapperR = vtk.vtkTextMapper()
textMapperR.SetInput("This is\nmulti-line\ntext output\n(right-bottom)")
tprop = textMapperR.GetTextProperty()
tprop.ShallowCopy(multiLineTextProp)
tprop.SetJustificationToRight()
tprop.SetVerticalJustificationToBottom()
tprop.SetColor(colors.GetColor3d("Peacock"))
textActorR = vtk.vtkActor2D()
textActorR.SetMapper(textMapperR)
textActorR.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
textActorR.GetPositionCoordinate().SetValue(0.95, 0.5)
# Draw the grid to demonstrate the placement of the text.
# Set up the necessary points.
Pts = vtk.vtkPoints()
Pts.InsertNextPoint(0.05, 0.0, 0.0)
Pts.InsertNextPoint(0.05, 1.0, 0.0)
Pts.InsertNextPoint(0.5, 0.0, 0.0)
Pts.InsertNextPoint(0.5, 1.0, 0.0)
Pts.InsertNextPoint(0.95, 0.0, 0.0)
Pts.InsertNextPoint(0.95, 1.0, 0.0)
Pts.InsertNextPoint(0.0, 0.5, 0.0)
Pts.InsertNextPoint(1.0, 0.5, 0.0)
Pts.InsertNextPoint(0.00, 0.85, 0.0)
Pts.InsertNextPoint(0.50, 0.85, 0.0)
Pts.InsertNextPoint(0.00, 0.75, 0.0)
Pts.InsertNextPoint(0.50, 0.75, 0.0)
Pts.InsertNextPoint(0.00, 0.65, 0.0)
Pts.InsertNextPoint(0.50, 0.65, 0.0)
# Set up the lines that use these points.
Lines = vtk.vtkCellArray()
Lines.InsertNextCell(2)
Lines.InsertCellPoint(0)
Lines.InsertCellPoint(1)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(2)
Lines.InsertCellPoint(3)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(4)
Lines.InsertCellPoint(5)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(6)
Lines.InsertCellPoint(7)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(8)
Lines.InsertCellPoint(9)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(10)
Lines.InsertCellPoint(11)
Lines.InsertNextCell(2)
Lines.InsertCellPoint(12)
Lines.InsertCellPoint(13)
# Create a grid that uses these points and lines.
Grid = vtk.vtkPolyData()
Grid.SetPoints(Pts)
Grid.SetLines(Lines)
# Set up the coordinate system.
normCoords = vtk.vtkCoordinate()
normCoords.SetCoordinateSystemToNormalizedViewport()
# Set up the mapper and actor (2D) for the grid.
mapper = vtk.vtkPolyDataMapper2D()
mapper.SetInputData(Grid)
mapper.SetTransformCoordinate(normCoords)
gridActor = vtk.vtkActor2D()
gridActor.SetMapper(mapper)
gridActor.GetProperty().SetColor(colors.GetColor3d("DimGray"))
# Create the Renderer, RenderWindow, and RenderWindowInteractor
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(renderWindow)
# Add the actors to the renderer set the background and size zoom in closer to the image render
renderer.AddActor2D(textActorL)
renderer.AddActor2D(textActorC)
renderer.AddActor2D(textActorR)
renderer.AddActor2D(singleLineTextActorB)
renderer.AddActor2D(singleLineTextActorC)
renderer.AddActor2D(singleLineTextActorT)
renderer.AddActor2D(gridActor)
renderer.SetBackground(colors.GetColor3d("Silver"))
renderWindow.SetSize(640, 480)
renderer.GetActiveCamera().Zoom(1.5)
# Enable user interface interactor
interactor.Initialize()
renderWindow.Render()
interactor.Start()
if __name__ == '__main__':
main()
| lorensen/VTKExamples | src/Python/Annotation/MultiLineText.py | MultiLineText.py | py | 7,461 | python | en | code | 319 | github-code | 36 | [
{
"api_name": "vtk.vtkTextProperty",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "vtk.vtkTextProperty",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "vtk.vtkNamedColors",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "vtk.vtkTex... |
11045288759 | from datetime import datetime
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.mixins import (
RetrieveModelMixin, ListModelMixin, CreateModelMixin,
UpdateModelMixin, DestroyModelMixin
)
from .models import TodoList, TodoListItem, TodoListItemTimeTrack
from .serializers import TodoListSerializer, TodoListItemSerializer, TodoListItemTimeTrackSerializer
class TodoListViewSet(GenericViewSet, RetrieveModelMixin, ListModelMixin):
serializer_class = TodoListSerializer
permission_classes = (IsAuthenticated,)
lookup_field = 'date'
def get_queryset(self):
date_from = self.request.query_params.get('date_from')
date_to = self.request.query_params.get('date_to')
queryset = TodoList.objects.filter(user=self.request.user)
if date_from:
queryset.filter(date__gte=date_from)
if date_to:
queryset.filter(date__lte=date_to)
return queryset
def get_object(self):
date = self.kwargs.get('date')
try:
date = datetime.strptime(date, "%Y-%m-%d").date()
except ValueError as ex:
date = datetime.now().date()
return TodoList.objects.get_todo_list(self.request.user, date)
class TodoListItemViewSet(ModelViewSet):
queryset = TodoListItem.objects.all()
serializer_class = TodoListItemSerializer
permission_classes = (IsAuthenticated,)
def dispatch(self, request, *args, **kwargs):
self.todo_list_date = kwargs.pop('todo_list_date', None)
return super().dispatch(request, *args, **kwargs)
def get_todo_list(self):
try:
date = datetime.strptime(self.todo_list_date, "%Y-%m-%d").date()
except ValueError as ex:
date = datetime.now().date()
return TodoList.objects.get_todo_list(self.request.user, date)
def get_queryset(self):
user = self.request.user
todo_list = self.get_todo_list()
return super().get_queryset().filter(todo_list=todo_list,
todo_list__user=user)
def perform_create(self, serializer):
todo_list = self.get_todo_list()
serializer.save(todo_list=todo_list)
@action(detail=True, url_path='start')
def start_time_track(self, request, pk=None):
todo_list_item = self.get_object()
todo_list_item.start_task()
return Response(status=status.HTTP_200_OK)
@action(detail=True, url_path='end')
def end_time_track(self, request, pk=None):
todo_list_item = self.get_object()
todo_list_item.finish_task()
return Response(status=status.HTTP_200_OK)
@action(detail=True, url_path='done')
def mark_item_done(self, request, pk=None):
todo_list_item = self.get_object()
todo_list_item.done_task()
return Response(status=status.HTTP_200_OK)
@action(detail=True, url_path='undone')
def mark_item_undone(self, request, pk=None):
todo_list_item = self.get_object()
todo_list_item.undone_task()
return Response(status=status.HTTP_200_OK)
@action(detail=True, url_path='play-pause')
def toggle_start_stop(self, request, pk=None):
todo_list_item = self.get_object()
todo_list_item.toggle_start_stop()
return Response(status=status.HTTP_200_OK)
@action(detail=True, url_path='delete')
def delete_task(self, request, pk=None):
todo_list_item = self.get_object()
todo_list_item.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
| mohsen-hassani-org/teamche | todo_list/api.py | api.py | py | 3,846 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "rest_framework.viewsets.GenericViewSet",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "rest_framework.mixins.RetrieveModelMixin",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "rest_framework.mixins.ListModelMixin",
"line_number": 16,
... |
13670330701 | import random
from random import choice
import discord
import asyncio
from discord.ext import commands
import requests
bot = commands.Bot(command_prefix='.')
class games(commands.Cog):
def __init__(self, bot):
self.bot = bot
determine_flip = [1, 0]
@commands.command()
async def coinflip(self,ctx,determine_flip = determine_flip):
if random.choice(determine_flip) == 1:
embed = discord.Embed(title="Coinflip",
description=f"{ctx.author.mention} Flipped coin, we got **Heads**!")
await ctx.send(embed=embed)
else:
embed = discord.Embed(title="Coinflip",
description=f"{ctx.author.mention} Flipped coin, we got **Tails**!")
await ctx.send(embed=embed)
@commands.command()
async def animequote(self, ctx):
r = requests.get('https://animechan.vercel.app/api/random')
embed=discord.Embed(title="Random Anime Quote", color=0xff00c8)
embed.add_field(name="Anime:", value=r.json()['anime'], inline=True)
embed.add_field(name="Character:", value=r.json()['character'], inline=True)
embed.add_field(name="Quote:", value=r.json()['quote'], inline=False)
await ctx.send(embed=embed)
@commands.command()
async def fakeidentity(self, ctx):
r = requests.get('https://fakerapi.it/api/v1/persons?_quantity=1')
embed=discord.Embed(title="Fake Identity", color=0x000000)
embed.add_field(name="Name:", value=r.json()['data'][0]['firstname']+" "+r.json()['data'][0]['lastname'], inline=False)
embed.add_field(name="Email:", value=r.json()['data'][0]['email'], inline=False)
embed.add_field(name="Phone:", value=r.json()['data'][0]['phone'], inline=True)
embed.add_field(name="Birthday:", value=r.json()['data'][0]['birthday'], inline=True)
embed.add_field(name="Gender:", value=r.json()['data'][0]['gender'], inline=True)
embed.add_field(name="Address:", value=r.json()['data'][0]['address']['street'], inline=True)
await ctx.send(embed=embed)
@commands.command()
async def nsfw(self,ctx,category):
if ctx.channel.is_nsfw():
r = requests.get('https://api.waifu.im/nsfw/'+category)
embed=discord.Embed(title="why did i waste my time on this...", color=0xdb76d2)
embed.set_image(url=r.json()['images'][0]['url'])
await ctx.send(embed=embed)
else:
await ctx.send("This is not the correct channel for this command.")
@commands.command()
async def waifu(self,ctx):
if ctx.channel.name == "anime":
r = requests.get('https://api.waifu.im/sfw/waifu')
embed=discord.Embed(title="why did i waste my time on this...", color=0xdb76d2)
embed.set_image(url=r.json()['images'][0]['url'])
await ctx.send(embed=embed)
else:
await ctx.send("This is not the correct channel for this command.")
@commands.command()
async def meme(self,ctx):
r = requests.get('https://meme-api.herokuapp.com/gimme')
embed=discord.Embed(title="bruh random meme..")
embed.set_image(url=r.json()['preview'][3])
await ctx.send(embed=embed)
@commands.command()
async def joke(self,ctx):
url = "https://random-stuff-api.p.rapidapi.com/joke"
querystring = {"type":"any"}
headers = {
'authorization': "C8xh6UHmszvv",
'x-rapidapi-host': "random-stuff-api.p.rapidapi.com",
'x-rapidapi-key': "29342191f7msh58cba8f92580e3fp13f8cfjsn2d4552a32237"
}
response = requests.request("GET", url, headers=headers, params=querystring)
embed=discord.Embed(title="bruh random joke..")
await ctx.send(response.json()['setup'])
await asyncio.sleep(4)
await ctx.send(response.json()['delivery'])
def setup(bot):
bot.add_cog(games(bot)) | BrandonLee28/Cardinal4 | games.py | games.py | py | 4,082 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "discord.ext.commands.Bot",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "discord.ext.commands",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "discord.ext.commands.Cog",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name... |
9045055933 | from typing import Optional
from xml.etree.ElementTree import Element, Comment
from api.mvc.model.data.content_model import ContentModel
from api.mvc.model.data.data_model import DataModel
from api.mvc.model.data.data_type import DataType
from api_core.exception.api_exception import ApiException
from api_core.helper.file_folder_helper import FileFolderHelper
from api_core.helper.string_helper import StringHelper
from api_core.mvc.service.file.xml_file_service import XmlFileService
class ContentModelFileService(XmlFileService):
"""
Class used to manage content-model XML files.
"""
def __init__(self):
"""
Initialize a new instance of 'ContentModelService' class.
"""
super().__init__(True, {"xmlns": "http://www.alfresco.org/model/dictionary/1.0"})
def extract_content_model_prefix(self, content_model_file_path: str) -> str:
"""
Extracts the content model prefix.
:param content_model_file_path: The path to the content model file.
:return: The content model prefix.
"""
root: Element = self._get_root(content_model_file_path)
filename: str = FileFolderHelper.extract_filename_from_path(content_model_file_path)
# Verification that the attribute exists.
if not ("name" in root.attrib):
raise ApiException("Content model file '{0}' does not have the necessary 'namespace' node."
.format(filename))
# Verification that the attribute has a value.
if StringHelper.is_empty(root.attrib["name"]):
raise ApiException("The 'name' attribute of the content model file '{0}' is not entered. The latter is "
"mandatory.".format(filename))
# Data recovery.
try:
return root.attrib["name"].rsplit(":", 1)[0]
except IndexError:
raise ApiException("The value of the 'name' attribute of the source node is invalid. This must be composed "
"as follows: prefix:name")
def extract_content_model_name(self, content_model_file_path: str) -> str:
"""
Extracts the content model name.
:param content_model_file_path: The path to the content model file.
:return: The content model name.
"""
root: Element = self._get_root(content_model_file_path)
filename: str = FileFolderHelper.extract_filename_from_path(content_model_file_path)
# Verification that the attribute exists.
if not ("name" in root.attrib):
raise ApiException("Content model file '{0}' does not have the necessary 'namespace' node."
.format(filename))
# Verification that the attribute has a value.
if StringHelper.is_empty(root.attrib["name"]):
raise ApiException("The 'name' attribute of the content model file '{0}' is not entered. The latter is "
"mandatory.".format(filename))
# Data recovery.
try:
return root.attrib["name"].rsplit(":", 1)[1]
except IndexError:
raise ApiException("The value of the 'name' attribute of the source node is invalid. This must be composed "
"as follows: prefix:name")
def create_content_model(self, content_model_file_path: str, prefix: str, name: str, description: Optional[str],
author: Optional[str]):
model: Element = Element("model")
model.set("name", "{0}:{1}".format(prefix, name))
# Set xml namespace.
if self.namespaces is not None:
for item in self.namespaces:
model.set(item[0], item[1])
model.append(Comment(" Optional meta-data about the model "))
# Set the description
description_node: Element = Element("description")
description_node.text = description if description is not None else "SET THE PROJECT DESCRIPTION"
model.append(description_node)
# Set the author
author_node: Element = Element("author")
author_node.text = author if author is not None else "Alfresco Helper Script 1.0.0"
model.append(author_node)
# Set the version
version_node: Element = Element("version")
version_node.text = "1.0.0"
model.append(version_node)
# Set the imports
imports_node: Element = Element("imports")
imports_node.append(Comment(" Import Alfresco Dictionary Definitions "))
# First import
import1: Element = Element("import")
import1.set("uri", "http://www.alfresco.org/model/dictionary/1.0")
import1.set("prefix", "d")
imports_node.append(import1)
# Second import
import2: Element = Element("import")
import2.set("uri", "http://www.alfresco.org/model/content/1.0")
import2.set("prefix", "cm")
imports_node.append(import2)
# Set the namespaces.
namespaces_node: Element = Element("namespaces")
# Set a namespace
namespace_node: Element = Element("namespace")
namespace_node.set("uri", "http://www.{0}.org/model/content/1.0".format(name.lower()))
namespace_node.set("prefix", prefix)
namespaces_node.append(namespace_node)
# Add the import to the model.
model.append(imports_node)
# Add the import to the model.
model.append(Comment(" Custom namespace for the '{0}:{1}' model ".format(prefix, name)))
model.append(namespaces_node)
types: Element = Element("types")
aspects: Element = Element("aspects")
model.append(types)
model.append(aspects)
# Write the XML file.
self._write(model, content_model_file_path)
def find_data(self, content_model: ContentModel, typology: str, data: str) -> Optional[Element]:
"""
Finds data's node in its content model.
:param content_model: A data model of a content-model.
:param typology: The data typology.
:param data: The name of the data.
:return: The data node, otherwise None.
"""
return self._get_root(content_model.path).find(".//{0}{3}s/{0}{3}[@name='{1}:{2}']".format(
self.get_namespace("xmlns"), content_model.prefix, data, typology))
def find_aspect(self, content_model: ContentModel, aspect: str) -> Optional[Element]:
"""
Finds an aspect's node in its content model.
:param content_model: A data model of a content-model.
:param aspect: The name of the aspect.
:return: The aspect node, otherwise None.
"""
return self._get_root(content_model.path).find(".//{0}aspects/{0}aspect[@name='{1}:{2}']".format(
self.get_namespace("xmlns"), content_model.prefix, aspect))
def get_aspects_name(self, content_model: ContentModel) -> list[str]:
"""
Finds an all aspects name in its content model.
:param content_model: A data model of a content-model.
:return: The list of aspects name.
"""
aspects: list[str] = []
filename: str = FileFolderHelper.extract_filename_from_path(content_model.path)
for aspect in self._get_root(content_model.path).findall(".//{0}aspects/{0}aspect".format(
self.get_namespace("xmlns"))):
aspects.append(self.__extract_aspect_name(aspect, filename))
return aspects
def get_data_names(self, content_model: ContentModel, typology: str) -> list[str]:
"""
Finds an all aspects name in its content model.
:param typology: The type of the data to get.
:param content_model: A data model of a content-model.
:return: The list of aspects name.
"""
data_names: list[str] = []
filename: str = FileFolderHelper.extract_filename_from_path(content_model.path)
for data in self._get_root(content_model.path).findall(".//{0}{1}s/{0}{1}".format(
self.get_namespace("xmlns"), typology)):
data_names.append(self.__extract_data_name(data, typology, filename))
return data_names
def find_type(self, content_model: ContentModel, type_name: str) -> Optional[Element]:
return self._get_root(content_model.path).find(".//{0}types/{0}type[@name='{1}:{2}']".format(
self.get_namespace("xmlns"), content_model.prefix, type_name))
def add_aspect(self, content_model: ContentModel, name: str, title: str, description: str):
root: Element = self._get_root(content_model.path)
aspect: Element = Element("aspect")
aspect.set("name", "{0}:{1}".format(content_model.prefix, name))
if not StringHelper.is_empty(title):
title_node: Element = Element("title")
title_node.text = title
aspect.append(title_node)
if not StringHelper.is_empty(description):
description_node: Element = Element("description")
description_node.text = description
aspect.append(description_node)
properties: Element = Element("properties")
aspect.append(properties)
add_to_root: bool = False
aspects: Element = root.find(".//{0}aspects".format(self.get_namespace("xmlns"), content_model.prefix, aspect))
if aspects is None:
aspects = Element("aspects")
add_to_root = True
aspects.append(Comment(" Definition of aspect '{0}'. ".format(name)))
aspects.append(aspect)
if add_to_root:
root.append(aspects)
self._write(root, content_model.path)
def add_type(self, content_model: ContentModel, name: str, title: str, description: str):
root: Element = self._get_root(content_model.path)
type_node: Element = Element("type")
type_node.set("name", "{0}:{1}".format(content_model.prefix, name))
if not StringHelper.is_empty(title):
title_node: Element = Element("title")
title_node.text = title
type_node.append(title_node)
if not StringHelper.is_empty(description):
description_node: Element = Element("description")
description_node.text = description
type_node.append(description_node)
properties: Element = Element("properties")
type_node.append(properties)
add_to_root: bool = False
types: Element = root.find(".//{0}types".format(self.get_namespace("xmlns"), content_model.prefix, type_node))
if types is None:
types = Element("types")
add_to_root = True
types.append(Comment(" Definition of type '{0}'. ".format(name)))
types.append(type_node)
self._write(root, content_model.path)
def add_property(self, content_model: ContentModel, data: DataModel, name: str, title: Optional[str],
description: Optional[str], typology: str, mandatory: bool):
root: Element = self._get_root(content_model.path)
# Create the property
prop: Element = Element("property")
prop.set("name", "{0}:{1}".format(content_model.prefix, name))
# Set the property's title.
if not StringHelper.is_empty(title):
title_node: Element = Element("title")
title_node.text = title
prop.append(title_node)
# Set the property's description.
if not StringHelper.is_empty(description):
description_node: Element = Element("description")
description_node.text = description
prop.append(description_node)
# Set the property's type.
type_node: Element = Element("type")
type_node.text = "d:{0}".format(typology)
prop.append(type_node)
# Set the property's mandatory.
mandatory_node: Element = Element("mandatory")
mandatory_node.text = "true" if mandatory else "false"
prop.append(mandatory_node)
data_node: Optional[Element] = root.find(".//{0}{3}s/{0}{3}[@name='{1}:{2}']"
.format(self.get_namespace("xmlns"), content_model.prefix, data.name,
data.typology))
add_to_data: bool = False
properties_node: Element = data_node.find(".//{0}properties".format(self.get_namespace("xmlns")))
if properties_node is None:
properties_node = Element("properties")
add_to_data = True
properties_node.append(prop)
if add_to_data:
data_node.append(properties_node)
self._write(root, content_model.path)
def add_extension(self, content_model: ContentModel, source: DataModel, parent: DataModel):
namespace: str = self.get_namespace("xmlns")
root: Element = self._get_root(content_model.path)
source_node: Element = root.find(".//{0}{1}s/{0}{1}[@name='{2}:{3}']"
.format(namespace, source.typology, content_model.prefix, source.name))
parent_node: Optional[Element] = source_node.find("./{0}parent".format(namespace))
add_parent: bool = True if parent_node is None else False
if add_parent:
parent_node = Element("parent")
parent_node.text = "{0}".format(parent.complete_name)
if add_parent:
source_node.insert(self.__get_properties_node_index(source_node), parent_node)
self._write(root, content_model.path)
def add_mandatory(self, content_model: ContentModel, source: DataModel, mandatory: DataModel):
namespace: str = self.get_namespace("xmlns")
root: Element = self._get_root(content_model.path)
source_node: Element = root.find(".//{0}{1}s/{0}{1}[@name='{2}:{3}']"
.format(namespace, source.typology, content_model.prefix, source.name))
mandatory_node: Optional[Element] = source_node.find("./{0}mandatory-aspects".format(namespace))
aspect: Element = Element("aspect")
aspect.text = "{0}:{1}".format(content_model.prefix, mandatory.name)
add_mandatory_node: bool = True if mandatory_node is None else False
if add_mandatory_node:
mandatory_node = Element("mandatory-aspects")
mandatory_node.append(aspect)
if add_mandatory_node:
source_node.append(mandatory_node)
self._write(root, content_model.path)
def get_aspect_description(self, content_model: ContentModel, name: str) -> Optional[str]:
"""
Retrieve the value of the description node of an aspect node.
:param content_model: A data model of a content-model.
:param name: The name of the aspect node.
:return: The value of the aspect's description node.
"""
return self.__get_data_description(content_model, DataType.ASPECT.name, name)
def get_type_description(self, content_model: ContentModel, name: str) -> Optional[str]:
"""
Retrieve the value of the description node of a type node.
:param content_model: A data model of a content-model.
:param name: The name of the type node.
:return: The value of the type's description node.
"""
return self.__get_data_description(content_model, DataType.TYPE.name, name)
def get_aspect_title(self, content_model: ContentModel, name: str) -> Optional[str]:
"""
Retrieve the value of the title node of an aspect node.
:param content_model: A data model of a content-model.
:param name: The name of the aspect node.
:return: The value of the aspect's title node.
"""
return self.__get_data_title(content_model, DataType.ASPECT.value, name)
def get_aspect_parent(self, content_model: ContentModel, name: str) -> Optional[str]:
"""
Retrieve the value of the parent node of an aspect node.
:param content_model: A data model of a content-model.
:param name: The name of the aspect node.
:return: The value of the aspect's parent node.
"""
return self.get_data_parent(content_model, DataType.ASPECT.value, name)
def get_aspect_mandatory_aspects(self, content_model: ContentModel, name: str) -> list[str]:
return self.__get_data_mandatory_aspects(content_model, DataType.ASPECT.value, name)
def get_type_title(self, content_model: ContentModel, name: str) -> Optional[str]:
"""
Retrieve the value of the title node of a type node.
:param content_model: A data model of a content-model.
:param name: The name of the type node.
:return: The value of the type's title node.
"""
return self.__get_data_title(content_model, DataType.TYPE.name, name)
def get_type_parent(self, content_model: ContentModel, name: str) -> Optional[str]:
"""
Retrieve the value of the title node of a type node.
:param content_model: A data model of a content-model.
:param name: The name of the type node.
:return: The value of the type's title node.
"""
return self.__get_data_title(content_model, DataType.TYPE.name, name)
def __extract_aspect_name(self, aspect: Element, filename: str) -> str:
"""
Extracts the aspect node name.
:param aspect: The aspect node.
:return: The aspect name.
"""
return self.__extract_data_name(aspect, DataType.ASPECT.name, filename)
def get_type_mandatory_aspects(self, content_model: ContentModel, name: str) -> list[str]:
return self.__get_data_mandatory_aspects(content_model, DataType.TYPE.value, name)
def __extract_type_name(self, type_node: Element, filename: str) -> str:
"""
Extracts the aspect node name.
:param type_node: The type node.
:return: The type name.
"""
return self.__extract_data_name(type_node, DataType.TYPE.value, filename)
@staticmethod
def __extract_data_name(data: Element, typology: str, filename: str) -> str:
"""
Extracts the aspect node name.
:param data: The aspect model.
:return: The aspect name.
"""
# Verification that the attribute exists.
if not ("name" in data.attrib):
raise ApiException("There is {1} in file '{0}' that has not been defined correctly. It lacks the "
"'name' attribute."
.format(filename, "an aspect" if typology.__eq__("aspect") else "a type"))
# Verification that the attribute has a value.
if StringHelper.is_empty(data.attrib["name"]):
raise ApiException("There is {1} in file '{0}' that has not been defined correctly. The 'name' "
"attribute is null or empty."
.format(filename, "an aspect" if typology.__eq__("aspect") else "a type"))
# Data recovery.
try:
return data.attrib["name"].rsplit(":", 1)[1]
except IndexError:
raise ApiException("There is {1} in file '{0}' whose name attribute was not set correctly. The "
"attribute value must be composed as follows: prefix:name"
.format(filename, "an aspect" if typology.__eq__("aspect") else "a type"))
@staticmethod
def __extract_property_name(prop: Element, filename: str) -> str:
"""
Extracts the aspect node name.
:param prop: The property node.
:return: The aspect name.
"""
# Verification that the attribute exists.
if not ("name" in prop.attrib):
raise ApiException("There is a property in file '{0}' that has not been defined correctly. It lacks the "
"'name' attribute."
.format(filename))
# Verification that the attribute has a value.
if StringHelper.is_empty(prop.attrib["name"]):
raise ApiException("There is a property in file '{0}' that has not been defined correctly. The 'name' "
"attribute is null or empty."
.format(filename))
# Data recovery.
try:
return prop.attrib["name"].rsplit(":", 1)[1]
except IndexError:
raise ApiException("There is a property in file '{0}' whose name attribute was not set correctly. The "
"attribute value must be composed as follows: prefix:name"
.format(filename))
def __get_data_description(self, content_model: ContentModel, typology: str, name: str) -> Optional[str]:
"""
Retrieve the value of the description node of a data node (aspect or type).
:param content_model: A data model of a content-model.
:param typology: The type of the node (aspect or type).
:param name: The name of the data node.
:return: The value of the data node description node.
"""
description: Element = self._get_root(content_model.path) \
.find(".//{0}{1}s/{0}{1}[@name='{2}:{3}']/{0}description"
.format(self.get_namespace("xmlns"), typology, content_model.prefix, name))
return None if description is None else description.text
def __get_data_title(self, content_model: ContentModel, typology: str, name: str) -> Optional[str]:
"""
Retrieve the value of the title node of a data node (aspect or type).
:param content_model: A data model of a content-model.
:param typology: The type of the node (aspect or type).
:param name: The name of the data node.
:return: The value of the data node title node.
"""
title: Element = self._get_root(content_model.path) \
.find(".//{0}{1}s/{0}{1}[@name='{2}:{3}']/{0}title"
.format(self.get_namespace("xmlns"), typology, content_model.prefix, name))
return None if title is None else title.text
def get_data_parent(self, content_model: ContentModel, typology: str, name: str) -> Optional[str]:
"""
Retrieve the value of the parent node of a data node (aspect or type).
:param content_model: A data model of a content-model.
:param typology: The type of the node (aspect or type).
:param name: The name of the data node.
:return: The value of the data node title node.
"""
parent: Element = self._get_root(content_model.path) \
.find(".//{0}{1}s/{0}{1}[@name='{2}:{3}']/{0}parent"
.format(self.get_namespace("xmlns"), typology, content_model.prefix, name))
return None if parent is None else parent.text
def __get_data_mandatory_aspects(self, content_model: ContentModel, typology: str, name: str) -> list[str]:
result: list[str] = []
root: Element = self._get_root(content_model.path)
mandatory_aspects: list[Element] = root.findall(".//{0}{1}s/{0}{1}[@name='{2}:{3}']/{0}mandatory-aspects"
"/{0}aspect".format(self.get_namespace("xmlns"), typology,
content_model.prefix, name))
for mandatory_aspect in mandatory_aspects:
result.append(mandatory_aspect.text)
return result
def __get_properties_node_index(self, data_node: Element) -> int:
namespace: str = self.get_namespace("xmlns")
children: list[Element] = data_node.findall(".//{0}*".format(namespace))
maximum: int = len(children)
index: int = 0
while index.__lt__(maximum) and children[index].tag.__ne__("{0}properties".format(namespace)):
index += 1
return index if index.__lt__(maximum) else (index - 1)
def get_property(self, content_model: ContentModel, data: DataModel, property_name: str) \
-> tuple[str, str, str, str, bool]:
namespace: str = self.get_namespace("xmlns")
root: Element = self._get_root(content_model.path)
filename: str = FileFolderHelper.extract_filename_from_path(content_model.path)
node: Element = root.find(".//{0}{1}s/{0}{1}[@name='{2}:{3}']/{0}properties/{0}property[@name='{2}:{4}']"
.format(namespace, data.typology, content_model.prefix, data.name, property_name))
if node is None:
ApiException("There is no property named '{0}' in {1} '{2}' in content model '{3}' in file '{4}'."
.format(property_name, data.typology, data.name, content_model.complete_name, filename))
title_node: Element = node.find("./{0}title".format(namespace))
title: Optional[str] = None if title_node is None else title_node.text
description_node: Element = node.find("./{0}description".format(namespace))
description: Optional[str] = None if description_node is None else description_node.text
type_node: Element = node.find("./{0}type".format(namespace))
typology: Optional[str] = None
if type_node is not None:
if StringHelper.is_empty(type_node.text):
raise ApiException("The type of the {0} property from the content-model '{1}' of file '{2}' is invalid."
" It cannot be empty or None."
.format(data.typology, content_model.complete_name,
FileFolderHelper.extract_filename_from_path(content_model.path)))
elif StringHelper.has_space(type_node.text):
raise ApiException("The type of the {0} property from the content-model '{1}' of file '{2}' is invalid."
" There can be no space in it."
.format(data.typology, content_model.complete_name,
FileFolderHelper.extract_filename_from_path(content_model.path)))
try:
typology = type_node.text.rsplit(":", 1)[1]
if (typology.__ne__("text") and typology.__ne__("int") and typology.__ne__("long")
and typology.__ne__("float") and typology.__ne__("double") and typology.__ne__("date")
and typology.__ne__("datetime") and typology.__ne__("boolean") and typology.__ne__("encrypted")
and typology.__ne__("noderef")):
raise ApiException(
"The type of the {0} property from the content-model '{1}' of file '{2}' is invalid. Its value"
" must be: text, int, long, float, double, date, datetime, boolean, encrypted or noderef."
.format(data.typology, content_model.complete_name,
FileFolderHelper.extract_filename_from_path(content_model.path)))
except IndexError:
raise ApiException("The value of property type '{0}' of {1} '{2}' of content model '{3}' of file '{4}'"
" is invalid. It should be formed like this: d:[type]"
.format(property_name, data.typology, data.name, content_model.complete_name,
filename))
mandatory_node: Element = node.find("./{0}mandatory".format(namespace))
mandatory: bool = False
if mandatory_node is not None:
if StringHelper.is_empty(mandatory_node.text):
raise ApiException("The value of property 'mandatory' '{0}' of {1} {2} of content model {3} of file "
"{4} is invalid. A value must be set ('true' or 'false').")
elif mandatory_node.text.__eq__("true"):
mandatory = True
elif mandatory_node.text.__eq__("false"):
mandatory = False
else:
raise ApiException("The value of property 'mandatory' '{0}' of {1} {2} of content model {3} of file "
"{4} is invalid. The value can only be 'true' or 'false'."
.format(property_name, data.typology, data.name, content_model.complete_name,
filename))
return property_name, title, description, typology, mandatory
def get_properties(self, content_model: ContentModel) -> list[str]:
result: list[str] = []
filename: str = FileFolderHelper.extract_filename_from_path(content_model.path)
root: Element = self._get_root(content_model.path)
for prop in root.findall(".//{0}aspects/{0}aspect/{0}properties/{0}property".format(
self.get_namespace("xmlns"))):
result.append(self.__extract_property_name(prop, filename))
for prop in root.findall(".//{0}types/{0}type/{0}properties/{0}property".format(
self.get_namespace("xmlns"))):
result.append(self.__extract_property_name(prop, filename))
return result
def get_data_property_names(self, content_model: ContentModel, data: DataModel) -> list[str]:
"""
Retrieve a list of property names from a data model.
:param content_model: A data model of a content-model.
:param data:
:return:
"""
# Result initialization.
result: list[str] = []
# Retrieving model properties.
namespace: str = self.get_namespace("xmlns")
root: Element = self._get_root(content_model.path)
filename: str = FileFolderHelper.extract_filename_from_path(content_model.path)
properties: list[Element] = root.findall(".//{0}{1}s/{0}{1}[@name='{2}:{3}']/{0}properties/{0}property"
.format(namespace, data.typology, content_model.prefix, data.name))
# Extract property names.
for prop in properties:
result.append(self.__extract_property_name(prop, filename))
# Return of the result.
return result
| seedbaobab/alfresco_helper | api/mvc/model/service/file/content_model_service.py | content_model_service.py | py | 30,329 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "api_core.mvc.service.file.xml_file_service.XmlFileService",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "xml.etree.ElementTree.Element",
"line_number": 30,
"usage_type": "name"
},
{
"api_name": "api_core.helper.file_folder_helper.FileFolderHelper.extra... |
35398230138 | from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import os
import subprocess
from contextlib import closing
from StringIO import StringIO
from twitter.common.collections import maybe_list
from pants.backend.core.tasks.task import Task
from pants.backend.core.tasks.console_task import ConsoleTask
from pants.base.cmd_line_spec_parser import CmdLineSpecParser
from pants.base.target import Target
from pants.goal.context import Context
from pants.goal.goal import Goal
from pants.option.bootstrap_options import register_bootstrap_options
from pants.option.options import Options
from pants_test.base_test import BaseTest
from pants_test.base.context_utils import create_config, create_run_tracker
def is_exe(name):
result = subprocess.call(['which', name], stdout=open(os.devnull, 'w'), stderr=subprocess.STDOUT)
return result == 0
class TaskTest(BaseTest):
"""A baseclass useful for testing Tasks."""
@classmethod
def task_type(cls):
"""Subclasses must return the type of the ConsoleTask subclass under test."""
raise NotImplementedError()
def prepare_task(self,
config=None,
args=None,
targets=None,
build_graph=None,
build_file_parser=None,
address_mapper=None,
console_outstream=None,
workspace=None):
"""Prepares a Task for execution.
task_type: The class of the Task to create.
config: An optional string representing the contents of a pants.ini config.
args: optional list of command line flags, these should be prefixed with '--test-'.
targets: optional list of Target objects passed on the command line.
Returns a new Task ready to execute.
"""
task_type = self.task_type()
assert issubclass(task_type, Task), 'task_type must be a Task subclass, got %s' % task_type
config = create_config(config or '')
workdir = os.path.join(config.getdefault('pants_workdir'), 'test', task_type.__name__)
new_options = Options(env={}, config=config, known_scopes=['', 'test'], args=args or [])
# A lot of basic code uses these options, so always register them.
register_bootstrap_options(new_options.register_global)
task_type.options_scope = 'test'
task_type.register_options_on_scope(new_options)
run_tracker = create_run_tracker()
context = Context(config,
new_options,
run_tracker,
targets or [],
build_graph=build_graph,
build_file_parser=build_file_parser,
address_mapper=address_mapper,
console_outstream=console_outstream,
workspace=workspace)
return task_type(context, workdir)
def targets(self, spec):
"""Resolves a target spec to one or more Target objects.
spec: Either BUILD target address or else a target glob using the siblings ':' or
descendants '::' suffixes.
Returns the set of all Targets found.
"""
spec_parser = CmdLineSpecParser(self.build_root, self.address_mapper)
addresses = list(spec_parser.parse_addresses(spec))
for address in addresses:
self.build_graph.inject_address_closure(address)
targets = [self.build_graph.get_target(address) for address in addresses]
return targets
def assertDeps(self, target, expected_deps=None):
"""Check that actual and expected dependencies of the given target match.
:param target: :class:`pants.base.target.Target` to check
dependencies of.
:param expected_deps: :class:`pants.base.target.Target` or list of
``Target`` instances that are expected dependencies of ``target``.
"""
expected_deps_list = maybe_list(expected_deps or [], expected_type=Target)
self.assertEquals(set(expected_deps_list), set(target.dependencies))
class ConsoleTaskTest(TaskTest):
"""A baseclass useful for testing ConsoleTasks."""
def setUp(self):
Goal.clear()
super(ConsoleTaskTest, self).setUp()
task_type = self.task_type()
assert issubclass(task_type, ConsoleTask), \
'task_type() must return a ConsoleTask subclass, got %s' % task_type
def execute_task(self, config=None, args=None, targets=None):
"""Creates a new task and executes it with the given config, command line args and targets.
config: an optional string representing the contents of a pants.ini config.
args: optional list of command line flags, these should be prefixed with '--test-'.
targets: optional list of Target objects passed on the command line.
Returns the text output of the task.
"""
with closing(StringIO()) as output:
task = self.prepare_task(config=config,
args=args,
targets=targets,
build_graph=self.build_graph,
build_file_parser=self.build_file_parser,
address_mapper=self.address_mapper,
console_outstream=output)
task.execute()
return output.getvalue()
def execute_console_task(self, config=None, args=None, targets=None, extra_targets=None,
workspace=None):
"""Creates a new task and executes it with the given config, command line args and targets.
config: an optional string representing the contents of a pants.ini config.
args: optional list of command line flags, these should be prefixed with '--test-'.
targets: optional list of Target objects passed on the command line.
extra_targets: optional list of extra targets in the context in addition to those passed on the
command line.
workspace: optional Workspace to pass into the context.
Returns the list of items returned from invoking the console task's console_output method.
"""
task = self.prepare_task(config=config,
args=args,
targets=targets,
build_graph=self.build_graph,
build_file_parser=self.build_file_parser,
address_mapper=self.address_mapper,
workspace=workspace)
return list(task.console_output(list(task.context.targets()) + list(extra_targets or ())))
def assert_entries(self, sep, *output, **kwargs):
"""Verifies the expected output text is flushed by the console task under test.
NB: order of entries is not tested, just presence.
sep: the expected output separator.
*output: the output entries expected between the separators
**kwargs: additional kwargs passed to execute_task.
"""
# We expect each output line to be suffixed with the separator, so for , and [1,2,3] we expect:
# '1,2,3,' - splitting this by the separator we should get ['1', '2', '3', ''] - always an extra
# empty string if the separator is properly always a suffix and not applied just between
# entries.
self.assertEqual(sorted(list(output) + ['']), sorted((self.execute_task(**kwargs)).split(sep)))
def assert_console_output(self, *output, **kwargs):
"""Verifies the expected output entries are emitted by the console task under test.
NB: order of entries is not tested, just presence.
*output: the expected output entries
**kwargs: additional kwargs passed to execute_console_task.
"""
self.assertEqual(sorted(output), sorted(self.execute_console_task(**kwargs)))
def assert_console_output_ordered(self, *output, **kwargs):
"""Verifies the expected output entries are emitted by the console task under test.
NB: order of entries is tested.
*output: the expected output entries in expected order
**kwargs: additional kwargs passed to execute_console_task.
"""
self.assertEqual(list(output), self.execute_console_task(**kwargs))
def assert_console_raises(self, exception, **kwargs):
"""Verifies the expected exception is raised by the console task under test.
**kwargs: additional kwargs are passed to execute_console_task.
"""
with self.assertRaises(exception):
self.execute_console_task(**kwargs)
| fakeNetflix/square-repo-pants | tests/python/pants_test/tasks/test_base.py | test_base.py | py | 8,440 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "subprocess.call",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "os.devnull",
"line_number": 26,
"usage_type": "attribute"
},
{
"api_name": "subprocess.STDOUT",
"line_number": 26,
"usage_type": "attribute"
},
{
"api_name": "pants_test.bas... |
73225167144 | from extra_streamlit_tools._logging import logging as logger
import streamlit as st
from typing import Any, Optional
def clear_cache(keep_keys: Optional[list[str]] = None) -> None:
"""
Resets the Streamlit cache.
Parameters
----------
keep_keys:Optional[list[str]]
Keys to not be cleared from cache
"""
logger.debug("Clearing cache")
for key in st.session_state.keys():
if keep_keys is None or key not in keep_keys:
logger.debug(f"Deleting key: {key}")
del st.session_state[key]
else:
logger.debug(f"Keeping key: {key}")
def init_session_keys(key_value_pairs: dict[str, Any]) -> None:
"""
The init_session_keys function is a helper function that initializes the session state with keys and values.
Parameters
----------
key_value_pairs:dict[str, Any]
A dictionairy of key_value_pairs
""" # noqa
for key, value in key_value_pairs.items():
if key not in st.session_state:
st.session_state[key] = value
def change_in_session_state(key_value_pairs: dict[str, Any]):
"""
The change_in_session_state function is a helper function that allows you to change session state values.
Parameters
----------
key_value_pairs:dict[str, Any]
Dictionairy with the Streamlit session_state key and the its new value
""" # noqa
for key, value in key_value_pairs.items():
st.session_state[key] = value
def set_selectbox_index(
selectbox_key: str, session_state_var_name: str, values: list[Any]
) -> None:
"""
The set_selectbox_index function is a helper function that sets the index of a selectbox to the value
of another session state variable. This is useful when you want to set the default value of one selectbox
to be equal to another, but you don't know what that other's default value will be until runtime.
Parameters
----------
selectbox_key:str
Specify the key of the selectbox
session_state_var_name:str
Set the session state variable name
values:list[Any]
The list of values in the selectbox
""" # noqa
st.session_state[session_state_var_name] = values.index(
st.session_state[selectbox_key]
)
| sTomerG/extra-streamlit-tools | src/extra_streamlit_tools/utils.py | utils.py | py | 2,324 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "typing.Optional",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "extra_streamlit_tools._logging.logging.debug",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "extra_streamlit_tools._logging.logging",
"line_number": 16,
"usage_type": "na... |
20756086605 | """
Created on Thu Sep 8 14:37:34 2016
@author: Patrick Trainor
@course: Artificial Intelligence
@title: Project 2
Code for embedding of figure in tk credited to:
http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html
Code for labeling points on figure credited to "unknown" @
http://stackoverflow.com/posts/5147430/revisions
"""
# Imports:
import time
import numpy as np
import re
import sklearn.metrics.pairwise as prw
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from itertools import permutations
import sys
import Tkinter as Tk
# Create Tk object:
root=Tk.Tk()
root.wm_title("BFS and DFS Search")
# Get filename from system args
filename = sys.argv[-1]
tsp_file=open(filename)
# Open and read the file lines
tsp_read=tsp_file.read().splitlines()
tsp_file.close()
# Find the number of cities
for line in tsp_read:
if line.startswith('DIMENSION'):
cities=int(re.findall(r'\d+', line)[0])
# Find the line of the file in which coordinates start
start_line=tsp_read.index('NODE_COORD_SECTION')+1
# Create matrix of pairwise distances
crds=[str.split(line) for line in tsp_read[start_line:(start_line+cities)]]
crds=np.matrix(crds).astype(np.float)[:,1:]
pdist=prw.pairwise_distances(crds)
#Add adjacency matrix:
adj=np.array([[0,1,1,1,0,0,0,0,0,0,0],[0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,1,1,0,0,0,0,0,0],[0,0,0,0,1,1,1,0,0,0,0],
[0,0,0,0,0,0,1,1,0,0,0],[0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,1,1,0],[0,0,0,0,0,0,0,0,1,1,1],
[0,0,0,0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0,0,0,1]],dtype="bool")
#Breadth first algorithm:
def bfs(adj,start,goal):
vertex=start
goalAcheived=vertex==goal
visit=[vertex]
edges=[]
while goalAcheived is False:
neighbors=np.where(adj[vertex,:])[0].tolist() #Find neighbors
for neighbor in neighbors:
visit=visit+[neighbor] #visit neighbors
edges=edges+[[vertex,neighbor]] #Edges to neighbor
goalAcheived=neighbor==goal #Check is neighbor goal?
if goalAcheived: #If neighbor is goal then stop
break
visit=[x for x in visit if x!=vertex] #Remove city from queue
vertex=visit[0] #Choose next city in queue
path=[edges.pop()] #Add edge to path
while path[0][0]!=start: #Backtrace
path=[[x for x in edges if x[1]==path[0][0]][0]]+path
return path
#Depth first algorithm
def dfs(adj,start,goal):
nextVertex=vertex=start
goalAcheived=vertex==goal
visit=[]
edges=[]
while goalAcheived is False:
vertex=nextVertex
neighbors=np.where(adj[vertex,:])[0].tolist() #Find neighbors
if neighbors==[]: #Iff no more neighbors in stack go back
while neighbors==[]:
vertex=visit.pop()
neighbors=np.where(adj[vertex,:])[0].tolist()
visit=visit+neighbors #Add new neighbors to stack
nextVertex=visit.pop() #Next city is last in stack
edges=edges+[[vertex,nextVertex]] #add edges
goalAcheived=edges[-1][-1]==goal #Check goal city?
path=[edges.pop()] #Add to path
while path[0][0]!=start: #Backtrace
path=[[x for x in edges if x[1]==path[0][0]][0]]+path
return path
def pathMap(path): #Function for mapping path to coordinates
xCrds=[]
yCrds=[]
for i in range(len(path)):
xCrds=xCrds+[[crds[path[i][0]][0,0],crds[path[i][1]][0,0]]]
yCrds=yCrds+[[crds[path[i][0]][0,1],crds[path[i][1]][0,1]]]
return([xCrds,yCrds])
#Execute BFS
t0=time.time()
bfsPath=bfs(adj,0,10)
t1=time.time()
bfsTime=t1-t0
bfsCrds=pathMap(bfsPath)
#Execute DFS
t0=time.time()
dfsPath=dfs(adj,0,10)
t1=time.time()
dfsTime=t1-t0
dfsCrds=pathMap(dfsPath)
#Determine the cities and edges of the whole
xCrds=[]
yCrds=[]
for i in range(10):
for j in range(11):
if adj[i,j]:
xCrds=xCrds+np.squeeze(crds[:,0][[i,j]]).tolist()
yCrds=yCrds+np.squeeze(crds[:,1][[i,j]]).tolist()
#Function for plotting cities, edges, and paths:
def plotFun(xCrds,yCrds,pathCrds=[],plotPath=False):
fig=plt.figure(figsize=(5, 4), dpi=100)
f1=fig.add_subplot(111)
f1.plot(crds[:,0],crds[:,1],'ro')
f2=fig.add_subplot(111)
for i in range(len(xCrds)):
f2.plot(xCrds[i],yCrds[i],'--',color='c')
if plotPath:
f3=fig.add_subplot(111)
for i in range(len(pathCrds[0])):
f3.plot(pathCrds[0][i],pathCrds[1][i],'-',color='r')
f4=fig.add_subplot(111)
labs=map(str,range(11))
for label, x, y in zip(labs,crds[:,0],crds[:,1]):
f4.annotate(label, xy = (x, y),xytext = (-10, 10),
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
return fig
f=plotFun(xCrds,yCrds,bfsCrds,plotPath=True)
f2=plotFun(xCrds,yCrds,dfsCrds,plotPath=True)
#Add listbox with results to tk window
listbox = Tk.Listbox(root)
listbox.pack(side=Tk.TOP, fill=Tk.X)
listbox.insert("end","BFS Path: "+str(bfsPath))
listbox.insert("end","DFS Path: " +str(dfsPath))
#Add figure to tk window
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas = FigureCanvasTkAgg(f2, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
#Add toolbar to tk window
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
#click event handler
def on_key_event(event):
print('you pressed %s' % event.key)
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect('key_press_event', on_key_event)
#Quit event handler
def _quit():
root.quit()
root.destroy()
button = Tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=Tk.BOTTOM)
#Execute tk main loop
Tk.mainloop()
#Write results to file
with open(filename.split('.')[0]+'Solution.txt','a') as tf:
tf.write("Input file: "+filename)
tf.write("\n")
tf.write("BFS Path: " +str(bfsPath))
tf.write("\n")
tf.write("DFS Path: "+str(dfsPath))
tf.write("\n")
tf.write("BFS time: "+str(bfsTime)+" DFS time: "+str(dfsTime))
tf.close()
| trainorp/srch | TSP_BFS_DFS.py | TSP_BFS_DFS.py | py | 6,501 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "Tkinter.Tk",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "sys.argv",
"line_number": 33,
"usage_type": "attribute"
},
{
"api_name": "re.findall",
"line_number": 43,
"usage_type": "call"
},
{
"api_name": "numpy.matrix",
"line_number":... |
36779117268 | # NOTE: mini function for testing your UDP connection w the computer running the server and MAX
from pythonosc import udp_client
PORT_TO_MAX = 5002
IP = "192.168.2.2"
global client
client = udp_client.SimpleUDPClient(IP, PORT_TO_MAX)
input("hello")
while True:
print("sent")
client.send_message("/point", 1)
input("pause") | mshen63/RoboticMusicianship_CV_Project | oldReferenceFiles/socketTrial.py | socketTrial.py | py | 336 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pythonosc.udp_client.SimpleUDPClient",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "pythonosc.udp_client",
"line_number": 8,
"usage_type": "name"
}
] |
75034732264 | import logging
from handlers.detectors import detect_is_admin
from keyboards.default.start import start_admin
from keyboards.inline.admin.success_payment import withdraw_money_balance
from loader import dp, bot, db
from data.config import ADMINS
from keyboards.default.back import back
from states.balance import Balance
from aiogram import types
from aiogram.dispatcher import FSMContext
@dp.callback_query_handler(text="withdraw_money", state=Balance.menu)
async def withdraaw_money_from_balance(call: types.CallbackQuery, state: FSMContext):
user_id = call.from_user.id
select_user = await db.select_user_data(user_id)
balance = select_user[0][1]
if balance >= 10000:
text = "<b>Pul yechib olish uchun karta raqami kiriting...\n\n" \
"<i>Mavjud to'lov turlari</i>\n\n▪️Humo</b>"
await call.message.delete()
await call.message.answer(text=text, reply_markup=back)
await Balance.withdraw.set()
else:
text = "⚠️ Pul chiqarish uchun hisobingizda kamida 10.000 so'm bo'lishi shart!"
await call.answer(text, show_alert=True)
@dp.message_handler(state=Balance.withdraw, content_types=types.ContentType.TEXT)
async def identify_card(message: types.Message, state: FSMContext):
msg = message.text
await message.answer(
text="Yaxshi, endi nech pul chiqarib olmoqchi ekanligingizni yozing\n\nMasalan: <code>10000</code>",
reply_markup=back
)
await state.update_data(
{'card_number': msg}
)
await Balance.money.set()
@dp.message_handler(state=Balance.money, content_types=types.ContentType.TEXT)
async def identify_how_much_money(message: types.Message, state: FSMContext):
data = await state.get_data()
card_number = data.get('card_number')
user_id = message.from_user.id
full_name = message.from_user.full_name
user_mention = message.from_user.get_mention(name=full_name)
msg = message.text
select_user = await db.select_user_data(user_id)
balance = select_user[0][2]
try:
summa = int(msg)
if summa >= 10000:
if balance >= summa:
await bot.send_message(
chat_id=message.chat.id,
text="✅ Pul yechish uchun so'rovingiz qabul qilindi, admin tez orada to'lovni amalga oshiradi",
reply_markup=await detect_is_admin(user_id)
)
admin_text = f"👤 {user_mention}\n💳 {card_number}\n💸 {summa} so'm\n💰 {balance}"
await bot.send_message(
chat_id=ADMINS[0],
text=admin_text,
reply_markup=withdraw_money_balance(user_id, summa)
)
await state.reset_state(with_data=False)
elif balance < summa:
await bot.send_message(
chat_id=message.chat.id,
text=f"Hisobingizda {balance} so'm pul va siz {summa} so'm "
f"chiqarishga harakat qilyapsiz, iltimos boshqattan urinib ko'ring\n\n"
f"Masalan: <code>10000</code>",
reply_markup=back
)
else:
text = "⚠️ Eng kamida 10000 so'm chiqarib olish mumkin, summa kiriting\n\nMasalan: <code>10000</code>"
await message.answer(text, reply_markup=back)
except ValueError as VE:
logging.info(VE)
await message.answer(
text='Iltimos, faqat raqamlardan foydalaning\n\nMasalan: <code>10000</code>',
reply_markup=back
)
@dp.callback_query_handler(text_contains="tolandi_", state='*')
async def final_withdraw(call: types.CallbackQuery, state: FSMContext):
data = call.data
splited = data.split('_')
user_id = splited[1]
summa = splited[2]
select_user_data = await db.select_user_data(int(user_id))
balance = select_user_data[0][2]
get_user = await bot.get_chat(user_id)
full_name = get_user.full_name
user_mention = call.from_user.get_mention(full_name)
end_balance = balance - int(summa)
await db.update_user_balancee(end_balance, int(user_id))
await call.message.delete()
await bot.send_message(
chat_id=call.message.chat.id,
text="Foydalanuvchi puli to'lab berildi",
reply_markup=start_admin
)
text = f"✅ Pul toʻlandi: {user_mention}\n" \
f"👤 Foydalanuvchi ID: {user_id}\n" \
f"💸 Miqdor: {summa} soʻm"
await bot.send_message(
chat_id=-1001943689507,
text=text
)
await bot.send_message(
chat_id=user_id,
text=f"Sizning pul yechish so'rovingiz qabul qilindi va {summa} so'm to'lab berildi",
reply_markup=await detect_is_admin(user_id)
)
await state.finish()
@dp.callback_query_handler(text_contains="bekor_qilish_", state='*')
async def final_withdraw(call: types.CallbackQuery, state: FSMContext):
data = call.data
splited = data.split('_')
user_id = splited[2]
summa = splited[3]
await call.message.delete()
await state.update_data(
{'final_id': user_id, 'final_summa': summa}
)
await bot.send_message(
chat_id=call.message.chat.id,
text="To'lov bekor bo'lishining sababini kiriting",
reply_markup=back
)
await Balance.cancel_payment.set()
@dp.message_handler(state=Balance.cancel_payment, content_types=types.ContentType.TEXT)
async def cancel_payment_user(message: types.Message, state: FSMContext):
data = await state.get_data()
user_id = data.get('final_id')
final_summa = data.get('final_summa')
msg = message.text
await bot.send_message(
chat_id=user_id,
text=f"Sizning {final_summa} so'm chiqarishdagi harakatingiz bekor qilindi\n\nSabab: {msg}"
)
await bot.send_message(
chat_id=message.chat.id,
text="Xabar foydalanuvchiga yuborildi va to'lov harakati bekor qilindi",
reply_markup=start_admin
)
await state.finish() | uzbsobirov/Money-grow-bot | handlers/users/balance/withdraw_money.py | withdraw_money.py | py | 6,079 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "aiogram.types.CallbackQuery",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "aiogram.types",
"line_number": 17,
"usage_type": "name"
},
{
"api_name": "aiogram.dispatcher.FSMContext",
"line_number": 17,
"usage_type": "name"
},
{
"api_... |
8890345896 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 15:50:56 2018
@author: vitorhadad
"""
#
import numpy as np
import networkx as nx
import os
from tqdm import trange
from matching.solver.kidney_solver2 import optimal, greedy, get_two_cycles
from matching.utils.data_utils import clock_seed, evaluate_policy, get_n_matched, get_cycle_probabilities
from matching.utils.env_utils import snapshot, two_cycles
from matching.policy_function.policy_function_lstm import RNN
from matching.policy_function.policy_function_mlp import MLPNet
from matching.policy_function.policy_function_gcn import GCNet
from matching.policy_function.policy_function_rgcn import RGCNet
from matching.policy_function.policy_function_attention import AttentionRNN
from matching.environment.abo_environment import ABOKidneyExchange
#%%
def run_node2vec(G,
path = "",
input = "edges.txt",
output = "emb.txt",
d = 10):
nx.write_edgelist(G, path + input, data = False)
cmd = "./node2vec -i:{}{} -o:{}{} -d:{} -dr"\
.format(path, input, path, output, d)
os.system(cmd)
with open("emb.txt", "r") as emb:
lines = emb.readlines()
n = len(lines) - 1
features = np.zeros(shape = (n, d))
for k, line in enumerate(lines[1:]):
_, *xs = line.split(" ")
try:
features[k] = [float(x) for x in xs]
except:
import pdb; pdb.set_trace()
return features
def get_features(env):
opt= optimal(env)
features = []
labels = []
for t in range(env.time_length):
liv = np.array(env.get_living(t))
A = env.A(t)
has_cycle = np.diag(A @ A) > 0
liv = liv[has_cycle]
m = opt["matched"][t]
Y = np.zeros(len(liv))
Y[np.isin(liv, list(m))] = 1
labels.append(Y)
if len(liv) > 0:
X = env.X(t)[has_cycle]
subg = env.subgraph(liv)
E = run_node2vec(subg)
features.append(np.hstack([X, E]))
env.removed_container[t].update()
return np.vstack(features), np.hstack(labels)
env = ABOKidneyExchange(entry_rate=5, death_rate=.1, time_length=10, seed=clock_seed())
X, Y = get_features(env)
np.save("X.npy", X)
np.save("Y.npy", Y)
#%%
#%%
#
#
#%%
#
#env = ABOKidneyExchange(entry_rate = 5,
# death_rate = .1,
# time_length = 1500,
# seed = clock_seed())
#
#opt = optimal(env)
#gre = greedy(env)
#
##%%
#def evaluate(algo, env, thres):
#
# env.removed_container.clear()
# rewards = []
# for t in trange(env.time_length):
#
# liv = np.array(env.get_living(t))
# A = env.A(t)
# has_cycle = np.diag(A @ A) > 0
# liv_and_cycle = liv[has_cycle]
# yhat_full = np.zeros(len(liv), dtype=bool)
#
# if len(liv_and_cycle) == 0:
# continue
#
# X = env.X(t)[has_cycle]
# subg = env.subgraph(liv_and_cycle)
# E = run_node2vec(subg)
# F = np.hstack([X, E])
#
# yhat = algo.predict_proba(F)[:,1] > thres
# yhat_full[has_cycle] = yhat
# potential = liv[yhat_full]
#
# removed = optimal(env, t, t, subset=potential)["matched"][t]
# env.removed_container[t].update(removed)
# rewards.append(len(removed))
#
# return rewards
#
#
#r = evaluate(pipe, env, .05)
#
#gre_n = get_n_matched(gre["matched"], 0, env.time_length)
#opt_n = get_n_matched(opt["matched"], 0, env.time_length)
#print("\nrewards\n",
# np.sum(r[500:]),
# np.sum(gre_n[500:]),
# np.sum(opt_n[500:]))
# | halflearned/organ-matching-rl | matching/temp/temp.py | temp.py | py | 3,852 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "networkx.write_edgelist",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "os.system",
"line_number": 37,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "pdb.set_trace",
"li... |
15066809328 | # This file is part of ZNC-Signal <https://github.com/poppyschmo/znc-signal>,
# licensed under Apache 2.0 <http://www.apache.org/licenses/LICENSE-2.0>.
import pytest
from copy import deepcopy
from collections import namedtuple
from conftest import signal_stub, signal_stub_debug, all_in
signal_stub = signal_stub # quiet linter
signal_stub_debug = signal_stub_debug
@pytest.fixture
def env_stub(signal_stub):
import os
os.environ["SIGNALMOD_FAKE"] = "fake_val"
os.environ["SIGNALMOD_FOO"] = "foo_val"
argstring = f"DATADIR={os.devnull} FOO=someval UNKNOWN=ignored"
signal_stub.__class__.foo = None
signal_stub.__class__.fake = None
env_stub = signal_stub.__class__(argstring)
yield env_stub
del signal_stub.__class__.foo
del signal_stub.__class__.fake
del os.environ["SIGNALMOD_FAKE"]
del os.environ["SIGNALMOD_FOO"]
if env_stub._buffer is not None:
env_stub._buffer.close()
def test_OnLoad(env_stub):
import os
# Process environment is not modified
assert all_in(os.environ, "SIGNALMOD_FAKE", "SIGNALMOD_FOO")
assert env_stub.fake == os.environ["SIGNALMOD_FAKE"] == "fake_val"
assert os.environ["SIGNALMOD_FOO"] == "foo_val"
# OnLoad args override environment variables
assert env_stub.foo == "someval"
# Unknown attributes are ignored
assert not hasattr(env_stub, "unknown")
assert hasattr(env_stub, "datadir") and env_stub.datadir == os.devnull
# TODO use pseudo terminal to test debug logger (likely requires Linux)
# NOTE: order doesn't (currently) matter for flattened/narrowed hook data
base_rel = {'body': 'Welcome dummy!',
'network': 'testnet',
'away': False,
'client_count': 1,
'nick': 'tbo',
'ident': 'testbot',
'host': 'znc.in',
'hostmask': 'tbo!testbot@znc.in',
# Real thing uses datetime object
'time': '2018-04-21T01:20:13.751970+00:00'}
rels = namedtuple("Rels",
"OnChanTextMessage OnPrivTextMessage")(
dict(base_rel,
channel='#test_chan',
detached=False,
context='#test_chan'),
dict(base_rel,
body="Oi",
context="dummy")
)
# NOTE OnPrivActionMessage(msg) and OnChanActionMessage(msg) are exactly the
# same as their "Text" counterparts above, once narrowed. Normalized inspector
# output will show: 'type': 'Action', 'params': ('dummy', '\x01ACTION Oi\x01')
# as the only real differences.
def test_reckon(signal_stub_debug):
# Simulate converted dict passed to Signal.reckon()
from Signal.reckognize import reckon
from collections import defaultdict
defnul = defaultdict(type(None), rels.OnPrivTextMessage)
assert defnul["channel"] is None
assert defnul["detached"] is None
#
# Load default config
sig = signal_stub_debug
sig.manage_config("load") # same as '[*Signal] select'
# Quiet "no host" warning
sig.OnModCommand('update /settings/host localhost')
# Simulate a single, simple hook case
rel = rels.OnChanTextMessage
#
data_bak = deepcopy(rel)
conds = sig.config.conditions
from collections import defaultdict
data = defaultdict(type(None), rel)
#
sig._read() # clear read buffer
# Step through default config to ensure test module stays current with
# future changes to options
current_defaults = iter(sig.config.conditions["default"])
#
assert reckon(sig.config, data, sig.debug) is False
data_reck = data["reckoning"]
assert data_reck == ["<default", "!body>"]
#
assert next(current_defaults) == "enabled"
sig.cmd_update("/conditions/default/enabled", "False")
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<default", "enabled>"]
sig.cmd_update("/conditions/default/enabled", remove=True)
#
assert next(current_defaults) == "away_only"
sig.cmd_update("/conditions/default/away_only", "True")
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<default", "away_only>"]
sig.cmd_update("/conditions/default/away_only", remove=True)
#
assert next(current_defaults) == "scope"
assert not conds["default"].maps[0] # updated list is auto initialized
sig.cmd_update("/conditions/default/scope/attached", remove=True)
assert conds["default"]["scope"] == ["query", "detached"]
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<default", "scope>"]
sig.cmd_update("/conditions/default/scope", remove=True)
#
# TODO replied_only
assert next(current_defaults) == "replied_only"
#
assert next(current_defaults) == "max_clients"
data["client_count"] = 2
sig.cmd_update("/conditions/default/max_clients", "1")
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<default", "max_clients>"]
sig.cmd_update("/conditions/default/max_clients", remove=True)
data["client_count"] = 1
_data = dict(data)
_data.pop("reckoning")
# _data.pop("template")
assert data_bak == _data
#
assert sig._read().splitlines() == [
"Selected: /conditions/default/enabled => False", "Item deleted.",
"Selected: /conditions/default/enabled => True",
#
"Selected: /conditions/default/away_only => True", "Item deleted.",
"Selected: /conditions/default/away_only => False",
#
"Item deleted; current selection has changed",
"/conditions/default/scope => ['query', 'detached']",
"Item deleted.",
"Selected: /conditions/default/scope =>",
" ['query', 'detached', ...]",
#
"Selected: /conditions/default/max_clients => 1", "Item deleted.",
"Selected: /conditions/default/max_clients => 0"
]
#
# TODO mock datetime.now() for time-based conditions
assert next(current_defaults) == "timeout_post"
assert next(current_defaults) == "timeout_push"
assert next(current_defaults) == "timeout_idle"
#
# NOTE the rest aren't tested in order, just popped as encountered
current_defaults = list(current_defaults)
#
sig.OnModCommand('update /expressions/custom @@ {"has": "dummy"}')
sig.OnModCommand('update /templates/standard @@ '
'{"recipients": ["+12127365000"]}')
# Create non-default condition
current_defaults.remove("template")
sig.OnModCommand('update /conditions/custom @@ {"template": "custom"}')
# The "default" condition always runs last
assert list(sig.manage_config("view")["conditions"]) == ["custom",
"default"]
#
# Network
current_defaults.remove("network")
sig.cmd_update("/conditions/custom/network", "$custom")
assert data["network"] == "testnet"
assert sig.config.expressions["custom"] == {"has": "dummy"}
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!network>", "<default", "!body>"]
sig.cmd_update("/conditions/custom/network", "$pass")
#
# Channel
current_defaults.remove("channel")
sig.OnModCommand('update /conditions/custom/channel $custom')
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!channel>", "<default", "!body>"]
sig.cmd_update("/expressions/custom/has", "test_chan")
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!body>", "<default", "!body>"]
sig.cmd_update("/expressions/custom/has", "dummy")
sig.cmd_update("/conditions/custom/channel", "$pass")
#
# Source
current_defaults.remove("source")
sig.OnModCommand('update /conditions/custom/source $custom')
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!source>", "<default", "!body>"]
sig.OnModCommand('update /expressions/custom @@ {"wild": "*testbot*"}')
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!body>", "<default", "!body>"]
current_defaults.remove("x_source")
assert conds["custom"]["x_source"] == "hostmask"
sig.cmd_update("/conditions/custom/x_source", "nick")
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!source>", "<default", "!body>"]
sig.OnModCommand('update /expressions/custom @@ {"eq": "tbo"}')
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!body>", "<default", "!body>"]
sig.cmd_update("/conditions/custom/x_source", remove=True)
sig.cmd_update("/conditions/custom/source", "$pass")
#
# Body
current_defaults.remove("body")
sig.cmd_update("/conditions/custom/body", "$custom")
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!body>", "<default", "!body>"]
sig.OnModCommand('update /expressions/custom @@ {"has": "dummy"}')
assert reckon(sig.config, data, sig.debug) is True
#
# Body empty
data["body"] = ""
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!body>", "<default", "!body>"]
sig.cmd_update("/conditions/custom/body", "$drop")
data["body"] = "Welcome dummy!"
#
# Inline expression
sig.OnModCommand(
'update /conditions/custom/body @@ {"any": []}'
) # same as !has ""
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "!body>", "<default", "!body>"]
sig.OnModCommand(
'update /conditions/custom/body @@ {"i has": "welcome"}'
)
assert reckon(sig.config, data, sig.debug) is True
assert data_reck == ["<custom", "&>"]
sig.cmd_update("/conditions/custom/body", "$drop")
#
# Make pass the same as drop
sig.OnModCommand('update /expressions/pass @@ {"!has": ""}')
assert conds["custom"]["body"] == "$drop"
sig.cmd_update("/conditions/custom/body", "$pass")
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", '!network>', "<default", '!network>']
#
# Use literal expression in condition
assert conds["custom"]["body"] == "$pass"
sig.cmd_update("/expressions/pass", remove=True)
assert sig.config.expressions["pass"] == {"has": ""}
sig.OnModCommand('update /conditions/custom/body @@ {"!has": ""}')
assert conds["custom"]["body"] == {"!has": ""}
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", '!body>', "<default", '!body>']
sig.cmd_update("/conditions/custom/body", remove=True)
sig.OnModCommand('update /expressions/pass @@ {"any": []}')
#
# Change per-condition, collective expressions bias
current_defaults.remove("x_policy") # only governs expressions portion
assert conds["custom"]["x_policy"] == "filter"
sig.OnModCommand('update /conditions/default/x_policy first')
assert reckon(sig.config, data, sig.debug) is False
assert data_reck == ["<custom", "|>", "<default", "|>"] # Falls through
#
assert not current_defaults
#
# "FIRST" (short circuit) hit
sig.OnModCommand('update /conditions/custom/body $custom')
assert reckon(sig.config, data, sig.debug) is True
assert data_reck == ["<custom", "body!>"]
#
sig.OnModCommand('update /conditions/onetime @@ {}')
from textwrap import dedent
sig.cmd_select("../")
# Clear module buffer (lots of '/foo =>' output so far)
assert "Error" not in sig._read()
#
# Add another condition that runs ahead of 'custom'
sig.OnModCommand('select')
assert sig._read().strip() == dedent("""
/conditions => {'custom': {...}, 'onetime': {}, 'default': {...}}
""").strip()
sig.cmd_update("/conditions/onetime", "custom", arrange=True)
assert sig._read().strip() == dedent("""
Selected: /conditions =>
{'onetime': {...}, 'custom': {...}, ...}
""").strip()
assert reckon(sig.config, data, sig.debug) is True
assert data_reck == ["<onetime", "|>", "<custom", "body!>"]
def scope_conditional_stub(data, scope):
cond = dict(scope=scope)
# This is was copied verbatim from Signal.reckon, but code creep is
# inevitable
#
channel = data["channel"]
detached = data["detached"]
if ((channel and (("detached" not in cond["scope"] and detached) or
("attached" not in cond["scope"] and not detached))
or (not channel and "query" not in cond["scope"]))):
return True
return False
# XXX this used to be justified when the option was "ignored_scopes" (more
# flags, not so trivial); should just merge with test_reckon or delete
def test_reject_scope():
f = scope_conditional_stub
c = "channel"
a = "attached"
d = "detached"
q = "query"
#
data = {c: True, d: False}
assert all((f(data, []),
f(data, [q]),
f(data, [d]),
f(data, [d, q]))) is True
assert not any((f(data, [a]),
f(data, [q, a]),
f(data, [q, a, d]))) is True
#
data = {c: True, d: True}
assert all((f(data, []),
f(data, [q]),
f(data, [a]),
f(data, [a, q]))) is True
assert not any((f(data, [d]),
f(data, [d, a]),
f(data, [d, q, a]))) is True
#
data = {c: None, d: None}
assert f(data, [q]) is False # pass (not rejected)
assert all((f(data, []),
f(data, [d]),
f(data, [a]),
f(data, [d, a]))) is True
| poppyschmo/znc-signal | tests/test_hooks.py | test_hooks.py | py | 13,691 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "conftest.signal_stub",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "conftest.signal_stub_debug",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "os.environ",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "os.envi... |
41198927211 | import logging
import json
from lxml import etree
def get_field_text(tree, path):
nsmap = {"n1": tree.getroot().nsmap['n1']}
node = tree.xpath(path, namespaces=nsmap)
if len(node) > 0:
return node[0].text
return ''
def parse_metadata(scene, xml_filename, json_filename):
logger = logging.getLogger(scene)
logger.info("Parsing XML metadata from {0}".format(xml_filename))
result = {'!scene': scene}
tree = etree.parse(xml_filename)
with open(json_filename, 'r') as myfile:
tile_json = myfile.read()
tile = json.loads(tile_json)
scene_time = get_field_text(tree, "n1:General_Info/SENSING_TIME")
result['acquired_date'] = scene_time.split('T')[0]
result['acquired_time'] = scene_time.split('T')[1]
coords = tile['tileGeometry']['coordinates'][0]
result["#scene_corner_UL_x"] = coords[0][0]
result["#scene_corner_UL_y"] = coords[0][1]
result["#scene_corner_UR_x"] = coords[1][0]
result["#scene_corner_UR_y"] = coords[1][1]
result["#scene_corner_LR_x"] = coords[2][0]
result["#scene_corner_LR_y"] = coords[2][1]
result["#scene_corner_LL_x"] = coords[3][0]
result["#scene_corner_LL_y"] = coords[3][1]
result["#utm_zone"] = tile["utmZone"]
return result
| amy-langley/irma-import | xml_operations.py | xml_operations.py | py | 1,267 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "lxml.etree.parse",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "lxml.etree",
"line_number": 18,
"usage_type": "name"
},
{
"api_name": "json.loads",
"line_... |
15955214108 | #! python3
# sendDuesReminders.py - sends emails based on payment status in spreadsheet
import smtplib
import openpyxl
wb = openpyxl.load_workbook('C:\\Users\\daize\\Desktop\\pythontest\\Automate\\duesRecords.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
lastCol = sheet.max_column
latestMonth = sheet.cell(row=1, column=lastCol).value
unpaidMembers = {}
for r in range(2, sheet.max_row+1):
payment = sheet.cell(row=r, column=lastCol).value
if payment != 'paid':
name = sheet.cell(row=r, column=1).value
email = sheet.cell(row=r, column=2).value
unpaidMembers[name] = email
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls() #TLS加密的连接需要此代码进行加密,SSL不需要
smtpObj.login('account', 'passwd')
for name, email in unpaidMembers:
body = "Suject: %s dues unpaid.\nDear %s...not paid dues for %s....Thanks" % (latestMonth, name, latestMonth)
print('Sending email to %s' % email)
sendmailStatus = smtpObj.sendmail('my account', email, body) #所有收件人都发送成功,会返回空
if sendmailStatus != {}:
print('problem send email to %s:%s' % (email, sendmailStatus))
smtpObj.quit() | sdz0716/myPython | act16-email_message/sendDuesReminders.py | sendDuesReminders.py | py | 1,218 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "openpyxl.load_workbook",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "smtplib.SMTP",
"line_number": 21,
"usage_type": "call"
}
] |
13015450298 | import asyncio
import websockets
HOST = '0.0.0.0'
WS_PORT = 3333
TCP_PORT = 8888
loop = asyncio.get_event_loop()
websocket_connections = []
tcp_connections = []
async def send_status(status: str):
data = status.encode()
for c in tcp_connections:
try:
writer = c[1]
writer.write(data)
await writer.drain()
except Exception as e:
print(e)
async def executor(command: str):
command = command.lower()
words = command.split(" ")
print(words)
if 'вправо' in words:
await send_status('d')
if 'право' in words:
await send_status('d')
if 'права' in words:
await send_status('d')
if 'cправа' in words:
await send_status('d')
if 'влево' in words:
await send_status('a')
if 'лево' in words:
await send_status('a')
if 'лего' in words:
await send_status('a')
if 'лева' in words:
await send_status('a')
if 'назад' in words:
await send_status('s')
if 'вперед' in words:
await send_status('w')
if 'перед' in words:
await send_status('w')
async def websock_handler(websocket, path):
print('WS connect')
global websocket_connections
websocket_connections.append(websocket)
try:
while True:
msg = await websocket.recv()
print('[MSG INCOMING]', msg)
await executor(msg)
except websockets.exceptions.ConnectionClosedOK as e:
pass
websocket_connections.remove(websocket)
print('WS disc')
async def tcp_handler(reader, writer):
print('connected to ue')
global tcp_connections
connection = (reader, writer)
tcp_connections.append(connection)
writer.write("ping".encode())
while True:
data = await reader.read(100)
if len(data) == 0:
break
await writer.drain()
writer.close()
tcp_connections.remove(connection)
print('disconnected UE')
async def run_ws():
await websockets.serve(websock_handler, HOST, WS_PORT)
async def run_tcp():
await asyncio.start_server(tcp_handler, HOST, TCP_PORT, loop=loop)
def main():
loop.create_task(run_ws())
loop.create_task(run_tcp())
try:
loop.run_forever()
except KeyboardInterrupt:
print("stoped")
if __name__ == '__main__':
main()
| DeadMorose777/UE4_SpeechController | speech_controller-main/host2.py | host2.py | py | 2,119 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "asyncio.get_event_loop",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "websockets.exceptions",
"line_number": 65,
"usage_type": "attribute"
},
{
"api_name": "websockets.serve",
"line_number": 88,
"usage_type": "call"
},
{
"api_name": "asy... |
7535403822 | from __future__ import print_function
#
# -*- coding: utf-8 -*-#
# eso.org
# Copyright 2011 ESO
# Authors:
# Lars Holm Nielsen <lnielsen@eso.org>
# Dirk Neumayer <dirk.neumayer@gmail.com>
#
#
# Mantis 12175: Fix release dates for images and videos
#
#
# Find wrong release_dates:
# 1) Check id with release_date - e.g. opo0214a with release date in 2010 must be wrong
# should be opoYYNNx NN is a cont. number?
# 2) Release dates with 2011-03-03 18:00-18:44 are wrong
#
# Don't bother about images connected to announcements, releases and potws.
#
# For images with long_caption_link or press_release_link follow the link and extract the date.
#
#
#*************************************************************************************************************
from future import standard_library
standard_library.install_aliases()
from djangoplicity.utils import optionparser
from djangoplicity.media.models import Image
from djangoplicity.media.models import Video
import re
import urllib.request, urllib.error, urllib.parse
import logging, sys
import socket
from datetime import datetime
import pytz
import hubblesite
def change_datetime(obj):
'''
follows the long_caption_link or the press_release_link to get the correct date
'''
# get link to image or press release
link = None
success = False
if obj.long_caption_link.find('http') > -1:
link = obj.long_caption_link
elif obj.press_release_link.find('http') > -1:
link = obj.press_release_link
# follow link and get new date
if link:
release_date = hubblesite.get_release_date(link)
if release_date:
try:
#print '-------------------------------------------------------'
#print obj.id, obj.release_date.strftime('%Y-%B-%d %I:%M %p %Z')
release_date = release_date.astimezone( pytz.timezone( 'Europe/Berlin' ) )
release_date = datetime.replace(release_date, tzinfo=None)
obj.release_date = release_date
#print obj.id, obj.release_date.strftime('%Y-%B-%d %I:%M %p %Z')
obj.save()
success = True
except:
print(obj.id,' save failed!')
pass
return success
def process_objects(objs):
'''
find the objects that need a correction of the release_date
'''
pat = re.compile('[a-zA-Z]+([0-9]{2})\S+')
count = 0
finddate1 = datetime.strptime('2011-03-03 18:00:00','%Y-%m-%d %H:%M:%S')
finddate2 = datetime.strptime('2011-03-03 19:00:00','%Y-%m-%d %H:%M:%S')
for obj in objs:
YY = None
dt = obj.release_date
if (dt):
# process all objects with 2011-03-03 18:00:00 - 19:00:00
if dt >= finddate1 and dt <= finddate2:
if change_datetime(obj): count = count + 1
print(obj.id, 'old: ', dt, '\t new: ', obj.release_date ,'\t\t reason: 20110303')
# process all objects where opoYY YY does not match the year of the release_date
else:
#only care about opo... and heic...
if obj.id.find('opo') == -1 and obj.id.find('heic') == -1: continue
YY = pat.findall(obj.id)
if len(YY) > 0:
YY = YY[0]
#print obj.id, YY, dt.strftime('%y'), dt
if YY != dt.strftime('%y'):
if change_datetime(obj): count = count + 1
print(obj.id, 'old: ', dt, '\t new: ', obj.release_date ,'\t\t reason: ', YY,' != ', dt.strftime('%y'))
else:
pass
#print obj.id, ' no release_date'
return count
if __name__ == '__main__':
logger = logging.getLogger('app.' + __name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stderr))
logger.propagate = False
logger.info("Fix release dates for images and videos")
# timeout in seconds
timeout = 60
socket.setdefaulttimeout(timeout)
test = '''<h2 class="release-number"><strong>News Release Number:</strong> STScI-2006-25</h2>'''
pattern = re.compile('''h2 class="release-number".*?:.*?>\s*(.*?)<.*?h2''')
print('videos')
print(process_objects(Video.objects.all()), ' videos have a new release_date')
print('images')
print(process_objects(Image.objects.all()), ' images have a new release_date')
| esawebb/esawebb | scripts/correct_dates.py | correct_dates.py | py | 4,493 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "future.standard_library.install_aliases",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "future.standard_library",
"line_number": 28,
"usage_type": "name"
},
{
"api_name": "hubblesite.get_release_date",
"line_number": 58,
"usage_type": "call"
}... |
21787505234 | import json
from datetime import date,timedelta
path = '/Users/evcu/GitHub/evcu.github.io//assets/nyc365blog/data.json'
data = {}
newel = {}
newel[u'date'] = str(date.today()-timedelta(days=365))
newel[u'mood'] = str(input("Enter mood -1/0/1:\n"))
print(newel)
newel[u'high'] = str(input("Highlights\n"))
newel[u'low'] = str(input("Lowlights:\n"))
newel[u'other'] = str(input("Other:\n"))
newel[u'text'] = str(input("Random Thoughts:\n"))
print(newel)
with open(path,'r') as data_file:
print('Successfuly read')
data = json.load(data_file)
data.append(newel)
with open(path,'w') as data_file:
data_file.write(json.dumps(data, sort_keys=True, indent=4))
print('Successfuly written')
| evcu/evcu.github.io | assets/nyc365blog/newDay.py | newDay.py | py | 704 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "datetime.date.today",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "datetime.date",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "datetime.timedelta",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "json.load",
"li... |
19856862641 | # -*-- encoding=utf-8 --*-
import pandas as pd
import xlsxwriter
import os
import platform
from pandas import ExcelWriter
from util import main_function,plot_trend
def __read_one_csv_file(inCsvFileName):
try:
callFailData=pd.read_csv(inCsvFileName,
dtype={'呼叫对方号码': object,'运营商': object,
'imei': object,'起呼位置码': object,
'起呼基站编号': object,'结束位置码': object,
'结束基站编号': object,'isim支持情况': object},low_memory=False)
#print(callFailData.columns)
#print(callFailData.shape)
return callFailData
except:
return None
def __read_csv_directory(inCsvFileName):
callFailDataList=[]
absPath=os.path.abspath(inCsvFileName)
print(absPath)
for li in os.listdir(absPath):
print(li)
sysstr = platform.system()
#print('current OS is '+sysstr)
if(sysstr =="Windows"):
oldName=absPath+'\\'+li
elif(sysstr == "Linux"):
oldName=absPath+'/'+li
else:
oldName=absPath+'/'+li
callFailData1=__read_one_csv_file(oldName)
if callFailData1 is not None:
callFailDataList.append(callFailData1)
callFailData = callFailDataList[0]
for i in range(1,len(callFailDataList)):
callFailData = callFailData.append(callFailDataList[i], ignore_index=True)
print(callFailData.shape)
return callFailData
def __clean_data_all_data(callFailData):
#'内部机型', '外部机型', '系统版本', 'emmcid', 'imei', '地区码', '发生时间', '上报时间', '异常进程名', '进程版本名',
# '进程版本号', '异常进程包名', '软件系统类型', '国家', '省/直辖市', '市', '县/区', '详细地址', '异常类型', '出现异常的卡',
# '失败原因', '呼入呼出', '起呼位置码', '起呼基站编号', '起呼电话网络', '开始数据网络', '运营商', '结束位置码',
# '结束基站编号', '结束电话网络', '结束数据网络', 'isim支持情况', 'MBN版本信息', 'VOLTE配置信息', '是否volte',
# '呼叫对方号码', '保留字段一', '保留字段二', '异常次数', '日志路径', 'log信息'
rowLength_before=callFailData.shape[0]
#---原始数据,只是填充null,无任何过滤
callFailData=callFailData.fillna('null')
#---只是过滤掉正常的原因(网络释放原因)
fp=open(os.path.join(os.path.abspath('.'),'config','remove_items.txt'),'r')
allines=fp.readlines()
for cause in allines:
callFailData=callFailData[callFailData['失败原因'].apply(lambda x: x!=cause.strip())]
print('-----------------------------------'+str(callFailData.shape[0]))
shape_after_remove_cause=callFailData.shape[0]
#---移除测试的PLMN
callFailData = callFailData.loc[(callFailData["运营商"] != "99901") &
(callFailData["运营商"] != "00000") &
(callFailData["运营商"] != "00101") &
(callFailData["运营商"] != "123456") &
(callFailData["运营商"] != "null")]
#---起呼位置码 0、1
callFailData=callFailData[callFailData['起呼位置码'].apply(lambda x: x.strip() != 0)]
callFailData=callFailData[callFailData['起呼位置码'].apply(lambda x: x.strip() != 1)]
callFailData=callFailData[callFailData['起呼位置码'].apply(lambda x: x.strip() != '0')]
callFailData=callFailData[callFailData['起呼位置码'].apply(lambda x: x.strip() != '1')]
#---结束位置码 0、1
callFailData=callFailData[callFailData['结束位置码'].apply(lambda x: x.strip() != 0)]
callFailData=callFailData[callFailData['结束位置码'].apply(lambda x: x.strip() != 1)]
callFailData=callFailData[callFailData['结束位置码'].apply(lambda x: x.strip() != '0')]
callFailData=callFailData[callFailData['结束位置码'].apply(lambda x: x.strip() != '1')]
#---起呼基站编号 0、1
callFailData=callFailData[callFailData['起呼基站编号'].apply(lambda x: x.strip() != 0)]
callFailData=callFailData[callFailData['起呼基站编号'].apply(lambda x: x.strip() != 1)]
callFailData=callFailData[callFailData['起呼基站编号'].apply(lambda x: x.strip() != '0')]
callFailData=callFailData[callFailData['起呼基站编号'].apply(lambda x: x.strip() != '1')]
#---结束基站编号 0、1
callFailData=callFailData[callFailData['结束基站编号'].apply(lambda x: x.strip() != 0)]
callFailData=callFailData[callFailData['结束基站编号'].apply(lambda x: x.strip() != 1)]
callFailData=callFailData[callFailData['结束基站编号'].apply(lambda x: x.strip() != '0')]
callFailData=callFailData[callFailData['结束基站编号'].apply(lambda x: x.strip() != '1')]
#---起呼电话网络 UNKNOWN
callFailData=callFailData[callFailData['起呼电话网络'].apply(lambda x: x != 'UNKNOWN')]
callFailData = callFailData.loc[(callFailData["imei"] != "123456789012345")]
#---添加辅助分析项
callFailData['PLMN_LAC1_CID1']=callFailData['运营商'].str.cat(callFailData['起呼位置码'],sep='/').str.cat(callFailData['起呼基站编号'],sep='/')
callFailData['PLMN_LAC2_CID2']=callFailData['运营商'].str.cat(callFailData['结束位置码'],sep='/').str.cat(callFailData['结束基站编号'],sep='/')
callFailData['CS_NW']=callFailData['起呼电话网络'].str.cat(callFailData['结束电话网络'],sep='/')
callFailData['PS_NW']=callFailData['开始数据网络'].str.cat(callFailData['结束数据网络'],sep='/')
callFailData['CS_PS_NW']=callFailData['CS_NW'].str.cat(callFailData['PS_NW'],sep='/')
callFailData['PLMN_CS1'] = callFailData['运营商'].str.cat(callFailData['起呼电话网络'], sep='/')
callFailData['PLMN_CS_NW'] = callFailData['运营商'].str.cat(callFailData['CS_NW'], sep='/')
callFailData['PLMN_PS_NW'] = callFailData['运营商'].str.cat(callFailData['PS_NW'], sep='/')
callFailData['PLMN_CS_PS_NW'] = callFailData['运营商'].str.cat(callFailData['CS_PS_NW'], sep='/')
callFailData['机型-版本'] = callFailData['外部机型'].str.cat(callFailData['系统版本'], sep='/')
callFailData['省直辖市']=callFailData['省/直辖市']
callFailData['县区']=callFailData['县/区']
callFailData['市1']=callFailData['省直辖市'].str.cat(callFailData['市'],sep='-')
callFailData['县区1']=callFailData['市1'].str.cat(callFailData['县区'],sep='-')
callFailData['通话状态']=callFailData['呼叫对方号码'].apply(__removeStateSpace)
callFailData['信号强度']=callFailData['isim支持情况'].apply(__getRSRP)
callFailData['发生时间t']=pd.to_datetime(callFailData['发生时间'],infer_datetime_format=True)
callFailData['发生时间h']=callFailData['发生时间t'].apply(__getHour)
callFailData['出现异常的卡']=callFailData['出现异常的卡'].apply(__replace_sim)
callFailData['机型']=callFailData['外部机型']
#PD1635 PD1616B PD1619 PD1624 PD1616
#callFailData = callFailData[callFailData['机型'] == 'PD1619']
#callFailData = callFailData[callFailData['失败原因'] == 'CALL_END_CAUSE_FADE_V02']
callFailData['通话类型'] = callFailData['CS_NW'].str.cat(callFailData['是否volte'], sep='/')
callFailData['通话类型1'] = callFailData['PLMN_CS_NW'].str.cat(callFailData['是否volte'], sep='/')
callFailData['cause-state'] = callFailData['失败原因'].str.cat(callFailData['通话状态'], sep='/')
callFailData['CS_sig'] = callFailData['通话类型'].str.cat(callFailData['信号强度'], sep='/')
callFailData['cause_cs_sig'] = callFailData['失败原因'].str.cat(callFailData['CS_sig'], sep='/')
#---drop没有利用价值的项
data_every_file1=callFailData.drop(['外部机型','内部机型','emmcid','地区码','上报时间','异常进程名','进程版本名',
'进程版本号','异常进程包名','软件系统类型','异常类型','isim支持情况',
'MBN版本信息','VOLTE配置信息','呼叫对方号码','保留字段一','保留字段二',
'异常次数','日志路径','log信息','省/直辖市','县/区','发生时间','市',
'县区','发生时间t','机型-版本','起呼位置码','结束位置码','起呼基站编号','结束基站编号',
'结束电话网络','结束数据网络','PS_NW','CS_PS_NW',
'PLMN_PS_NW','PLMN_CS_PS_NW','发生时间h','市1','县区1',
],axis=1)
rowLength_after=callFailData.shape[0]
print('数据清洗之后...'+str(rowLength_after)+'/'+str(rowLength_before))
return data_every_file1,data_every_file1,shape_after_remove_cause
def __get_mcc(name):
return(name[:3])
def __replace_sim(sim):
if(sim==1):
return '卡1'
elif(sim==2):
return '卡2'
else:
return 'null'
def __getHour(name):
returnName=name.to_pydatetime().hour
return returnName
def __getRSRP(name):
returnName = name.strip()
rsrp_list = []
returnValue = 0
if(name=='-1' or name=='null'):
returnValue = str(-1)
else:
rsrp_list = returnName.split(',')
min = 0
for i in rsrp_list[:-2]:
temp = eval(i)
if(min > temp):
min = temp
returnValue = int(min / 5) * 5
return str(returnValue)
def __removeStateSpace(name):
returnName=name.strip()
if(' ' in name):
returnName=','.join(name.split(' '))
else:
pass
return returnName
def __process_zhejiang_IMEI(callFailData,path,file_pre):
model_list_fp=open(os.path.join(os.path.abspath('.'),'config','云诊断内销浙江统计机型列表.txt'),'r')
modelList=[]
for model in model_list_fp.readlines():
modelList.append(model.strip())
xls_fileName=os.path.join(path,file_pre+'_数据分析结果_浙江IMEI.xls')
workbook = xlsxwriter.Workbook(xls_fileName)
#---对每一个型号进行过滤和对比
#如果包含在写入excel表格
list_result=[]
for model in modelList:
model0=model.split('_')[0]
model1=model.split('_')[1]
worksheet = workbook.add_worksheet(model)
worksheet.set_column('A:A',20)
before=str(callFailData.shape[0])
callFailData_after=callFailData[callFailData['外部机型']==model0]
after=str(callFailData_after.shape[0])
print('开始过滤'+model+'...'+after+'/'+before)
#获取dataframe中的所有IMEI数据
imeiList_a=[]
for imei in callFailData_after['imei'].tolist():
imeiList_a.append(str(imei).strip())
#获取文件中浙江的IMEI列表
imeiList_b=[]
fileName=os.path.join('.','zhejiang_imei',model1+'.txt')
imeiFile_fp=open(fileName,'r')
imei_zhejiang=imeiFile_fp.readlines()
for imei in imei_zhejiang:
imeiList_b.append(imei.strip())
#获得浙江IMEI列表和dataframe IMEI中的交集
IMEI_intersection=list(set(imeiList_a).intersection(set(imeiList_b)))
#print('a='+str(len(imeiList_a))+',b='+str(len(imeiList_b))+',intersection='+str(len(IMEI_intersection)))
#按照dataframe的数量排序,获取浙江输出到excel
callFailData_IMEI=callFailData_after['imei'].value_counts()
allIMEI=callFailData_IMEI.index.tolist()
row_i=0
for imei_i in range(len(allIMEI)):
for imei_filtered in IMEI_intersection:
if(imei_filtered==allIMEI[imei_i]):
worksheet.write(row_i,0,imei_filtered)
worksheet.write(row_i,1,callFailData_IMEI.values[imei_i])
list_result.append((imei_filtered,callFailData_IMEI.values[imei_i]),)
row_i += 1
#---对所有过滤出来的浙江IMEI计算Top
print('ouput all...')
worksheet = workbook.add_worksheet('all')
worksheet.set_column('A:A',20)
mylist=sorted(list_result,key=lambda t:t[1],reverse=True)
for i in range(len(mylist)):
worksheet.write(i,0,mylist[i][0])
worksheet.write(i,1,mylist[i][1])
workbook.close()
length_mylist=0
if(len(mylist) < 1):
callFailData_internal = pd.DataFrame(columns=callFailData.columns)
else:
if(len(mylist) < 10):
length_mylist=len(mylist)
else:
length_mylist=10
callFailDataList=[]
for i in range(length_mylist):
callFailData_internal=callFailData[callFailData['imei']==mylist[i][0]]
callFailDataList.append(callFailData_internal)
callFailData_internal = pd.DataFrame(columns=callFailData.columns)
for i in range(1,len(callFailDataList)):
callFailData_internal = callFailData_internal.append(callFailDataList[i], ignore_index=True)
xls_fileName1=os.path.join(path,file_pre+'_数据分析结果_浙江IMEI详细信息.xlsx')
writer = ExcelWriter(xls_fileName1)
callFailData_internal.to_excel(writer,'data')
writer.save()
def __process_trial_IMEI(callFailData,path,inCsvFileName_head):
modelList=[]
for model in open(os.path.join('.','config','云诊断内销掉话试用机列表.txt'),'r').readlines():
modelList.append(model.strip())
xls_fileName=os.path.join(path,inCsvFileName_head+'_数据分析结果_试用机IMEI.xls')
workbook = xlsxwriter.Workbook(xls_fileName)
xls_fileName1=os.path.join(path,inCsvFileName_head+'_数据分析结果_试用机IMEI详细信息.xlsx')
writer = ExcelWriter(xls_fileName1)
#---对每一个试用机机型进行过滤和比对
for model in modelList:
model0=model.split('_')[0]
model1=model.split('_')[1]
worksheet = workbook.add_worksheet(model)
before=str(callFailData.shape[0])
private_callFailData=callFailData[callFailData['外部机型']==model0]
after=str(private_callFailData.shape[0])
print('开始过滤'+model+'...'+after+'/'+before)
imeiList_a=[]
for imei in private_callFailData['imei'].tolist():
imeiList_a.append(str(imei).strip())
fileName=os.path.join(os.path.abspath('.'),'trial_imei',model1+'.txt')
imeiFile_fp=open(fileName,'r')
imeiList_b=[]
for imei in imeiFile_fp.readlines():
imeiList_b.append(imei.split()[0].strip())
imeiList_b.append(imei.split()[1].strip())
IMEI_intersection=list(set(imeiList_a).intersection(set(imeiList_b)))
print('a='+str(len(imeiList_a))+',b='+str(len(imeiList_b))+'intersection='+str(len(IMEI_intersection)))
private_callFailData1=pd.DataFrame(columns=callFailData.columns)
for imei_i in range(len(IMEI_intersection)):
worksheet.write(imei_i,0,IMEI_intersection[imei_i])
private_callFailData1=private_callFailData1.append(private_callFailData[callFailData['imei']==IMEI_intersection[imei_i]])
private_callFailData1.to_excel(writer,model)
writer.save()
def cloud_in_callfail_main(path_raw_data,path_result):
main_function('云诊断内销掉话', path_raw_data, path_result, __read_one_csv_file, __read_csv_directory,
__clean_data_all_data)
def cloud_in_call_fail_plot_trend(path_raw_data,path_result):
sheet_name_list=['SIM卡', '失败原因', '呼入或呼出', '运营商', '电话网络', '发生时间h', '机型', '系统版本', 'PLMN_CS']
trend_dics_list={}
trend_dics_list['出现异常的卡']=['卡1','卡2']
trend_dics_list['通话类型1'] = ['46000/GSM/GSM/CS', '46001/UMTS/UMTS/CS',
'46000/LTE/GSM/CS', '46000/LTE/LTE/VOLTE',
'46011/CDMA - 1xRTT/CDMA - 1xRTT/CS']
trend_dics_list['失败原因']=['CALL_END_CAUSE_RECOVERY_ON_TIMER_EXPIRED_V02', 'CALL_END_CAUSE_FADE_V02', 'CALL_END_CAUSE_RADIO_LINK_LOST_V02', 'CALL_END_CAUSE_UNSPECIFIED_16', 'CALL_END_CAUSE_REQUEST_TERMINATED_V02']
trend_dics_list['呼入呼出']=['In','Out']
trend_dics_list['运营商']=['46000','46001','46011','46003']
trend_dics_list['是否volte']=['CS','VOLTE','VILTE']
trend_dics_list['系统版本']=['PD1616B_A_1.6.18', 'PD1616B_A_1.7.1', 'PD1616B_A_1.7.7', 'PD1616B_A_1.7.8', 'PD1616B_A_1.7.10', 'PD1616B_A_1.7.13', 'PD1616B_A_1.8.5', 'PD1616B_A_1.8.9']
trend_dics_list['机型']=['PD1635','PD1624','PD1616B','PD1619','PD1610','PD1616']
#
trend_dics_list['CS_NW']=['GSM/GSM','UMTS/UMTS','LTE/LTE','LTE/GSM','LTE/UMTS']
trend_dics_list['省直辖市']=['广东省','河南省','甘肃省','江苏省','河北省','山西省','浙江省','新疆维吾尔自治区',
'广西壮族自治区','安徽省','山东省','福建省','湖南省','贵州省','陕西省','云南省',
'黑龙江省','四川省','吉林省','辽宁省','湖北省','内蒙古自治区','宁夏回族自治区',
'北京市','上海市','江西省','重庆市','青海省','海南省','天津市','西藏自治区']
plot_trend('云诊断内销掉话', path_raw_data, path_result, trend_dics_list)
if __name__ == '__main__':
path=os.path.abspath('D:/tools/pycharm_projects/bigdata_analysis/cloud_in_callfail_raw_data/cloud_in_callfail_raw_data_weeks/test')
cloud_in_callfail_main(path,path)
| sundaygeek/bigdata-cloud-analysis | cloud_in_callfail.py | cloud_in_callfail.py | py | 18,222 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pandas.read_csv",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.path.abspath",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 25,
"usage_type": "attribute"
},
{
"api_name": "os.listdir",
"line_n... |
10535469198 | import pygame
import os
from sys import exit
WIDTH, HEIGHT = 1600, 900
pygame.init()
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Buildings")
WHITE = (255, 255, 255)
FPS = 60
indx = 0
font = pygame.font.Font(None, 50)
class Building():
def __init__(self, name, offset_x, offset_y):
self.name = name
self.building = pygame.image.load(os.path.join(
"assets/buildings", self.name)).convert_alpha()
self.offset_x = offset_x
self.offset_y = offset_y
self.x = offset_x
self.y = offset_y
def color_key(self, color):
self.building.set_colorkey(color)
def draw(self, WIN, camera_position):
self.VEL = 20
self.x = -camera_position[0]+self.offset_x
self.y = -camera_position[1]+self.offset_y
WIN.blit(self.building, (self.x, self.y))
def movements(self, keys_pressed):
if keys_pressed is None:
return
if keys_pressed[pygame.K_a]:
self.x += self.VEL
if keys_pressed[pygame.K_LSHIFT]:
self.x += self.VEL
elif keys_pressed[pygame.K_d]:
self.x -= self.VEL
if keys_pressed[pygame.K_LSHIFT]:
self.x -= self.VEL
def movements_updown(self, keys_pressed):
if keys_pressed[pygame.K_w]:
self.y += self.VEL
if keys_pressed[pygame.K_LSHIFT]:
self.y += self.VEL
elif keys_pressed[pygame.K_s]:
self.y -= self.VEL
if keys_pressed[pygame.K_LSHIFT]:
self.y -= self.VEL
def collision_bound(self, camera_position, x_fac, y_fac, width_fac, height_fac, show=False):
self.x = -camera_position[0]+self.offset_x
self.y = -camera_position[1]+self.offset_y
object_collision_bound = pygame.Rect(
self.x+x_fac, self.y+y_fac, width_fac, height_fac)
if show is True:
pygame.draw.rect(WIN, (0, 255, 0), object_collision_bound)
def main():
building1 = Building("4(1).png", -100, -1250)
building2 = Building("5(1).png", 2000, -1800)
building3 = Building("6.png", 5500, -1700)
clock = pygame.time.Clock()
while True:
WIN.fill(WHITE)
clock.tick(FPS)
for event in pygame.event.get():
keys_pressed = pygame.key.get_pressed()
if event.type == pygame.QUIT:
pygame.quit()
exit()
building1.draw(WIN, [0, 0])
building1.movements(keys_pressed)
building1.movements_updown(keys_pressed)
building2.draw(WIN, [0, 0])
building2.movements(keys_pressed)
building2.movements_updown(keys_pressed)
building3.draw(WIN, [0, 0])
building3.movements(keys_pressed)
building3.movements_updown(keys_pressed)
pygame.display.update()
if __name__ == "__main__":
main()
| Hemant-29/pygame-project | building.py | building.py | py | 2,913 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pygame.init",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "pygame.display.set_mode",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "pygame.display",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "pygame.display.s... |
25404288175 | # -*- coding: utf-8 -*-
import torch.nn as nn
from network import Decomposition,MultiscaleDiscriminator,downsample
from utils import gradient
from ssim import SSIM
import torch
import torch.optim as optim
import torchvision
import os
import torch.nn.functional as F
from contiguous_params import ContiguousParams
class Model(nn.Module):
def __init__(self,args):
super(Model, self).__init__()
self.fusion = Decomposition()
self.D = MultiscaleDiscriminator(input_nc=1)
self.MSE_fun = nn.MSELoss()
self.L1_loss = nn.L1Loss()
self.SSIM_fun = SSIM()
if args.contiguousparams==True:
print("ContiguousParams---")
parametersF = ContiguousParams(self.fusion.parameters())
parametersD = ContiguousParams(self.D.parameters())
self.optimizer_G = optim.Adam(parametersF.contiguous(), lr=args.lr)
self.optimizer_D = optim.Adam(parametersD.contiguous(), lr=args.lr)
else:
self.optimizer_G = optim.Adam(self.fusion.parameters(), lr=args.lr)
self.optimizer_D = optim.Adam(self.D.parameters(), lr=args.lr)
self.g1 = self.g2 = self.g3 = self.s = self.img_re = None
self.loss = torch.zeros(1)
self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer_G , mode='min', factor=0.5, patience=2,
verbose=False, threshold=0.0001, threshold_mode='rel',
cooldown=0, min_lr=0, eps=1e-10)
self.min_loss = 1000
self.args = args
self.downsample = downsample()
self.criterionGAN = torch.nn.MSELoss()
if args.multiGPU:
self.mulgpus()
self.load()
self.load_D()
def load_D(self,):
if self.args.load_pt:
print("=========LOAD WEIGHTS D=========")
path = self.args.weights_path.replace("fusion","D")
print(path)
checkpoint = torch.load(path)
if self.args.multiGPU:
print("load D")
self.D.load_state_dict(checkpoint['weight'])
else:
print("load D single")
# 单卡模型读取多卡模型
state_dict = checkpoint['weight']
# create new OrderedDict that does not contain `module.`
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k.replace('module.', '') # remove `module.`
new_state_dict[name] = v
# load params
self.D.load_state_dict(new_state_dict)
print("=========END LOAD WEIGHTS D=========")
def load(self,):
start_epoch = 0
if self.args.load_pt:
print("=========LOAD WEIGHTS=========")
checkpoint = torch.load(self.args.weights_path)
start_epoch = checkpoint['epoch'] + 1
try:
if self.args.multiGPU:
print("load G")
self.fusion.load_state_dict(checkpoint['weight'])
else:
print("load G single")
# 单卡模型读取多卡模型
state_dict = checkpoint['weight']
# create new OrderedDict that does not contain `module.`
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k.replace('module.', '') # remove `module.`
new_state_dict[name] = v
# load params
self.fusion.load_state_dict(new_state_dict)
except:
model = self.fusion
print("weights not same ,try to load part of them")
model_dict = model.state_dict()
pretrained = torch.load(self.args.weights_path)['weight']
# 1. filter out unnecessary keys
pretrained_dict = {k: v for k, v in model_dict.items() if k in pretrained}
left_dict = {k for k, v in model_dict.items() if k not in pretrained}
print(left_dict)
# 2. overwrite entries in the existing state dict
model_dict.update(pretrained_dict)
# 3. load the new state dict
model.load_state_dict(model_dict)
print(len(model_dict),len(pretrained_dict))
# model_dict = self.fusion.state_dict()
# pretrained_dict = {k: v for k, v in model_dict.items() if k in checkpoint['weight'] }
# print(len(checkpoint['weight'].items()), len(pretrained_dict), len(model_dict))
# model_dict.update(pretrained_dict)
# self.fusion.load_state_dict(model_dict)
print("start_epoch:", start_epoch)
print("=========END LOAD WEIGHTS=========")
print("========START EPOCH: %d========="%start_epoch)
self.start_epoch = start_epoch
def mulGANloss(self, input_, is_real):
if is_real:
label = 1
else:
label = 0
if isinstance(input_[0], list):
loss = 0.0
for i in input_:
pred = i[-1]
target = torch.Tensor(pred.size()).fill_(label).to(pred.device)
loss += self.criterionGAN(pred, target)
return loss
else:
target = torch.Tensor(input_[-1].size()).fill_(label).to(input_[-1].device)
return self.criterionGAN(input_[-1], target)
def forward(self,isTest=False):
self.g1, self.g2, self.g3, self.s, self.img_re = self.fusion(self.img,isTest)
def set_requires_grad(self, net, requires_grad=False):
for param in net.parameters():
param.requires_grad = requires_grad
def backward_G(self):
img = self.img
img_re = self.img_re
img_g = gradient(img)
self.img_down = self.downsample(img)
self.img_g = img_g
# print(self.g1.sum(),self.g2.sum(),self.g3.sum(),img_g.sum())
# print(self.g1.mean(), self.g2.mean(), self.g3.mean(), img_g.mean())
g1 = self.MSE_fun(self.g1, img_g)
g2 = self.MSE_fun(self.g2, img_g)
g3 = self.MSE_fun(self.g3, img_g)
grd_loss = g1+g2+g3
self.lossg1 ,self.lossg2,self.lossg3 = g1,g2,g3
# grd_loss = self.MSE_fun(self.g1, img_g) + self.MSE_fun(self.g2, img_g) + self.MSE_fun(self.g3, img_g)
ssim_loss = 1 - self.SSIM_fun(img_re, img)
ssim_loss = ssim_loss * 10
pixel_loss = self.MSE_fun(img_re, img)
pixel_loss = pixel_loss * 100
loss_G = self.mulGANloss(self.D(self.s), is_real=True)*0.1
# 损失求和 回传
loss = pixel_loss + ssim_loss + grd_loss + loss_G
loss.backward()
self.loss,self.pixel_loss,self.ssim_loss, self.grd_loss = loss,pixel_loss,ssim_loss, grd_loss
self.loss_G = loss_G
def backward_D(self):
# RealReal
# Real
pred_real = self.D(self.img_down.detach())
loss_D_real = self.mulGANloss(pred_real, is_real=True)
# Fake
pred_fake = self.D(self.s.detach())
loss_D_fake = self.mulGANloss(pred_fake, is_real=False)
# Combined loss and calculate gradients
loss_D = (loss_D_real + loss_D_fake) * 0.5
loss_D.backward()
self.loss_D = loss_D
self.loss_D_real,self.loss_D_fake = loss_D_real,loss_D_fake
def mulgpus(self):
self.fusion= nn.DataParallel(self.fusion.cuda(), device_ids=self.args.GPUs, output_device=self.args.GPUs[0])
self.D = nn.DataParallel(self.D.cuda(), device_ids=self.args.GPUs, output_device=self.args.GPUs[0])
def setdata(self,img):
img = img.to(self.args.device)
self.img = img
def step(self):
self.optimizer_G.zero_grad() # set G gradients to zero
self.forward()
self.set_requires_grad(self.D, False) # D require no gradients when optimizing G
self.backward_G() # calculate gradients for G
self.optimizer_G.step() # update G weights
# if it % 10 == 0:
self.set_requires_grad(self.D, True)
self.optimizer_D.zero_grad() # set D gradients to zero
self.backward_D() # calculate gradients for D
self.optimizer_D.step() # update D weights
self.print = 'ALL[%.5lf] pixel[%.5lf] grd[%.5lf](%.5lf %.5lf %.5lf) ssim[%.5lf] G[%.5lf] D[%.5lf][%.5lf %.5lf ]' %\
(self.loss.item(), self.pixel_loss.item(), self.grd_loss.item(),self.lossg1.item() ,self.lossg2.item(),self.lossg3.item(), self.ssim_loss.item(),
self.loss_G.item(),self.loss_D.item(),self.loss_D_real.item(),self.loss_D_fake.item(),)
def saveimg(self,epoch,num=0):
img = torchvision.utils.make_grid(
[self.img[0].cpu(), self.img_re[0].cpu(), self.img_down[0].cpu(),self.img_g[0].cpu(), self.s[0].cpu(), self.g1[0].cpu(), self.g2[0].cpu(),
self.g3[0].cpu(), (self.g1+self.g2+self.g3)[0].cpu()], nrow=5)
torchvision.utils.save_image(img, fp=(os.path.join('output/result_' + str(epoch) + '.jpg')))
# torchvision.utils.save_image(img, fp=(os.path.join('output/epoch/'+str(num)+'.jpg')))
def saveimgdemo(self):
self.img_down = self.downsample(self.img)
self.img_g = gradient(self.img)
img = torchvision.utils.make_grid(
[self.img[0].cpu(), self.img_re[0].cpu(), self.img_down[0].cpu(),self.img_g[0].cpu(), self.s[0].cpu(), self.g1[0].cpu(), self.g2[0].cpu(),
self.g3[0].cpu(), (self.g1+self.g2+self.g3)[0].cpu()], nrow=5)
torchvision.utils.save_image(img, fp=(os.path.join('demo_result.jpg')))
# torchvision.utils.save_image(img, fp=(os.path.join('output/epoch/'+str(num)+'.jpg')))
def saveimgfuse(self,name=''):
self.img_down = self.downsample(self.img)
self.img_g = gradient(self.img)
img = torchvision.utils.make_grid(
[self.img[0].cpu(), self.img_g[0].cpu(), ((self.g1+self.g2+self.g3)*1.5)[0].cpu()], nrow=3)
torchvision.utils.save_image(img, fp=(os.path.join(name.replace('Test','demo'))))
# torchvision.utils.save_image(img, fp=(os.path.join('output/epoch/'+str(num)+'.jpg')))
def save(self, epoch):
## 保存模型和最佳模型
if self.min_loss > self.loss.item():
self.min_loss = self.loss.item()
torch.save({'weight': self.fusion.state_dict(), 'epoch': epoch, },os.path.join('weights/best_fusion.pt'))
torch.save({'weight': self.D.state_dict(), 'epoch': epoch, }, os.path.join('weights/best_D.pt'))
print('[%d] - Best model is saved -' % (epoch))
if epoch % 1 == 0:
torch.save({'weight': self.fusion.state_dict(), 'epoch': epoch, },os.path.join('weights/epoch' + str(epoch) + '_fusion.pt'))
torch.save({'weight': self.D.state_dict(), 'epoch': epoch, },os.path.join('weights/epoch' + str(epoch) + '_D.pt'))
def getimg(self):
return self.g1, self.g2,self.g3,self.s
| thfylsty/ImageFusion_DeepDecFusion | model.py | model.py | py | 11,325 | python | en | code | 5 | github-code | 36 | [
{
"api_name": "torch.nn.Module",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line_number": 14,
"usage_type": "name"
},
{
"api_name": "network.Decomposition",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "network.Multiscal... |
34898939242 | import numpy as np
import librosa
from typing import List
import matplotlib.pyplot as plt
from scipy import signal
from scipy.fft import rfft, rfftfreq
import os
TECHNIQUES = ['High', 'Tasto', 'Bend', 'Harm', 'Strum', 'Pont', 'Ord', 'Chord', 'Smack', 'Palm', 'TEST', 'SILENCE']
#TECHNIQUES = os.listdir("samples/manual") + ["SILENCE"]
# ['Bend', 'Chord', 'Harm', 'High', 'Ord', 'Palm', 'Pont', 'Smack', 'Strum', 'Tasto', 'TEST', 'SILENCE']
# high tasto bend harm strum pont ord chord smack palm
def find_onsets(y: np.ndarray, sr: int) -> np.ndarray:
"""Takes a numpy array and returns an array of onsets, currenly using librosa"""
#return librosa.onset.onset_detect(y, sr=sr, backtrack=True, units="samples")
o_env = librosa.onset.onset_strength(y=y, sr=sr, max_size=8)
samps = librosa.samples_like(o_env)
return librosa.onset.onset_detect(onset_envelope=o_env, sr=sr, backtrack=True, units="samples",
delta=4.3, hop_length=512, normalize=False,
pre_max = 1.0, post_max = 1.0, pre_avg = 4.0, post_avg = 5.0, wait = 1.0)
def get_waveform_from_ndarray(audio: np.ndarray, tf):
audio = tf.convert_to_tensor(audio)
tf.cast(audio, tf.float32)
return audio
def get_waveform_from_bin(wfbin, tf):
"""Returns a tf tensor float32 waveform from a binary file"""
audio, _ = tf.audio.decode_wav(wfbin) # somewhere here it breaks.......
tf.cast(audio, tf.float32)
return tf.squeeze(audio, axis=-1)
def get_waveform_from_path(path: str, tf):
"""Returns a tf tensor float32 waveform from a path"""
wfbin = tf.io.read_file(path)
return get_waveform_from_bin(wfbin, tf)
def get_spectrogram(waveform, tf):
"""Takes a tf.float32 waveform and returns a spectrogram. Max size = 16000 samples"""
if tf.shape(waveform) > 16000:
waveform = waveform[:16000]
zero_padding = tf.zeros([16000] - tf.shape(waveform), dtype=tf.float32) #fix this so the padding isn't huge
waveform = tf.cast(waveform, tf.float32)
equal_length = tf.concat([waveform, zero_padding], 0)
spectrogram = tf.signal.stft(
equal_length, frame_length=255, frame_step=128)
spectrogram = tf.abs(spectrogram)
spectrogram = tf.expand_dims(spectrogram, -1)
return spectrogram
def numpy_to_tfdata(note: np.ndarray, tf):
"""Turn a numpy buffer note into a tensorflow dataset of the spectrogram"""
waveform = get_waveform_from_ndarray(note, tf)
spec = get_spectrogram(waveform, tf)
ds = tf.data.Dataset.from_tensors([spec])
return ds
def int_to_string_results(int_results: List[int], techniques: List[str]) -> List[str]:
return list(map(lambda i: techniques[i], int_results))
def prediction_to_int_ranks(prediction, tf):
sftmax = tf.nn.softmax(prediction[0])
sorted = np.sort(sftmax)[::-1]
index_of = lambda x: np.where(sftmax == x)[0][0]
prediction_ranks = list(map(index_of, sorted))
return prediction_ranks
def plot_prediction(techniques, prediction, tf):
"""view a matplotlib graph of the prediction"""
plt.bar(techniques, tf.nn.softmax(prediction[0]))
plt.title(f'Predictions for new note:')
plt.show()
def note_above_threshold(note: np.ndarray) -> bool:
"""Checks if the peak of a note is above a set threshold"""
if np.max(np.abs(note)) > 0.09:
return True
else:
return False
def get_partials(waveform: np.ndarray, sr: int) -> List[float]:
normalized_wf = np.int16((waveform / waveform.max()) * 32767)
N = len(normalized_wf)
yf = rfft(normalized_wf)
xf = rfftfreq(N, 1 / sr)
half = len(xf) // 2
peak_sig = np.abs(yf[:half])
peaks, d = signal.find_peaks(peak_sig, height=100000, distance=250) # This can be tweaked for better results
peaks_amps = np.array(list(map(lambda p: [p, peak_sig[p]], peaks)))
sorted_peaks = peaks_amps[peaks_amps[:, 1].argsort()][::-1]
sorted_freqs = list(map(lambda i: xf[int(i)], sorted_peaks[:, 0]))
sorted_freqs = filter(lambda freq: freq > 80, sorted_freqs)
return list(sorted_freqs)
if __name__ == "__main__":
print(TECHNIQUES) | trian-gles/ai-technique-classification | utilities/analysis.py | analysis.py | py | 4,193 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.ndarray",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "librosa.onset.onset_strength",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "librosa.onset",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "li... |
19567593432 | import requests
import csv
from bs4 import BeautifulSoup
import json
from collections import namedtuple
from typing import List, Dict
TOPICS_NUMBER = 6
LEVELS_NUMBER = 5
MIN_LEVEL_CONTEST_ID = "030813"
MAX_LEVEL_CONTEST_ID = "030817"
TABLE_URL = ("https://ejudge.lksh.ru/standings/dk/stand.php"
"?from={}&to={}".format(MIN_LEVEL_CONTEST_ID,
MAX_LEVEL_CONTEST_ID))
Student = namedtuple('Student', 'group, last_name, first_name, ejid')
def get_table(table_url) -> BeautifulSoup:
"""Fetches results table from ejudge, returns soup"""
response = requests.get(table_url)
soup = BeautifulSoup(response.text, "lxml")
table = soup.select_one("table")
return table
def parse_results(table_soup: BeautifulSoup) -> Dict[Student, List[int]]:
"""Returns dict like {Student: [1 if problem is solved else 0]}"""
result = {}
rows = [row for row in table_soup.select("tr") if row.has_attr("ejid")]
for row in rows:
[group, last_name, first_name], ejid = row.select_one("nobr").contents[
0].split(), int(row['ejid'])
problem_tags = [td for td in row.findAll("td") if td.has_attr("title")]
solved = [1 if tag["class"] == ["ac"] else 0 for tag in problem_tags]
result[Student(group, last_name, first_name, ejid)] = solved
return result
def last_occurrence(list_, elem):
return len(list_) - 1 - list_[::-1].index(elem)
def calculate_mark(solved: List[int]) -> int:
"""Calculates mark from a list of solved"""
levels = set()
max_levels = []
for topic in range(TOPICS_NUMBER):
solved_from_topic = solved[topic::TOPICS_NUMBER]
if any(solved_from_topic):
max_level = last_occurrence(solved_from_topic, 1)
max_levels.append(max_level)
max_levels.sort(reverse=True)
for level in max_levels:
while level in levels and level != 0:
level -= 1
levels.add(level)
return min(len(levels), len(max_levels))
def get_table_to_render(parsed_table: Dict[Student, List[int]]) -> list:
return sorted([(*student, calculate_mark(solved))
for student, solved in parsed_table.items()])
def get_table_json(parsed_table: Dict[Student, List[int]]) -> str:
return json.dumps([{
'first_name': student.first_name,
'last_name': student.last_name,
'group': student.group,
'score': calculate_mark(solved),
'ejid': student.ejid
} for student, solved in parsed_table.items()],
ensure_ascii=False)
def get_personal_json(parsed_table: Dict[Student, List[int]], ejid: int) -> str:
filtered_student = [(student, solved)
for student, solved in parsed_table.items()
if student.ejid == ejid]
if filtered_student:
student, solved = filtered_student[0]
return json.dumps({'first_ name': student.first_name,
'last_name': student.last_name,
'group': student.group,
'score': calculate_mark(solved),
'solved': solved,
'ejid': student.ejid},
ensure_ascii=False)
else:
return json.dumps({'error': 'ID не найден'}, ensure_ascii=False)
if __name__ == '__main__':
results_table = get_table(TABLE_URL)
parsed_table = parse_results(results_table)
table = get_table_to_render(parsed_table)
with open("results.csv", "w", encoding="utf-8") as file:
csv_writer = csv.writer(file)
csv_writer.writerows(table)
| daniil-konovalenko/Cprime-practice-results | load_results.py | load_results.py | py | 3,803 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "collections.namedtuple",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "bs4.BeautifulSoup",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "bs4.BeautifulSo... |
18692006503 | import json
import logging
import sys
from z3 import z3
from teether.constraints import check_model_and_resolve
from teether.evm.exceptions import IntractablePath
from teether.evm.state import LazySubstituteState, SymRead
from teether.project import Project
from teether.util.z3_extra_util import concrete
def set_balance(addr, bal, i_r):
calldata = z3.Array('CALLDATA_%d' % i_r.xid, z3.BitVecSort(256), z3.BitVecSort(8))
new_calldata = z3.Store(z3.Store(z3.Store(z3.Store(calldata, 0, 0x70), 1, 0xa0), 2, 0x82), 3, 0x31)
for num, byte in enumerate(addr.to_bytes(32, 'big'), 4):
new_calldata = z3.Store(new_calldata, num, byte)
subst = [(calldata, new_calldata)]
state = LazySubstituteState(i_r.state, subst)
constraints = [z3.substitute(c, subst) for c in i_r.constraints]
sha_constraints = {sha: z3.simplify(z3.substitute(sha_value, subst)) if not isinstance(sha_value, SymRead)
else sha_value for sha, sha_value in i_r.sha_constraints.items()}
mstart, msz = state.stack[-1], state.stack[-2]
mm = i_r.state.memory.read(mstart, msz)
if not isinstance(mm, SymRead):
if all(concrete(m) for m in mm):
return None
mm = z3.simplify(z3.Concat([m if not concrete(m) else z3.BitVecVal(m, 8) for m in mm]))
extra_constraints = [mm == bal]
try:
model = check_model_and_resolve(constraints + extra_constraints, sha_constraints)
sloads = []
storage = None
for v in model:
if v.name().startswith("SLOAD"):
sloads.append(model.eval(model[v]).as_long())
if v.name().startswith("STORAGE"):
storage = z3.simplify(model[v])
return {sl: model.eval(storage[sl]).as_long() for sl in sloads}
except IntractablePath:
return None
def main(code_path, output_file, target_addrs, target_bals):
if code_path.endswith('.json'):
with open(code_path, 'rb') as f:
jd = json.load(f)
p = Project.from_json(jd)
else:
with open(code_path) as infile:
inbuffer = infile.read().rstrip()
code = bytes.fromhex(inbuffer)
p = Project(code)
with open('%s.project.json' % code_path, 'w') as f:
json.dump(p.to_json(), f)
target_addrs = [int(addr, 16) for addr in target_addrs]
target_bals = [int(bal) for bal in target_bals]
storage_result = dict()
addr, bal = target_addrs[0], target_bals[0]
return_ins = p.cfg.filter_ins('RETURN')
gen_constraints = p.get_constraints(return_ins)
results = []
for _, _, i_r in gen_constraints:
stor = set_balance(addr, bal, i_r)
if stor:
storage_result.update(stor)
results = [i_r] + results
break
results.append(i_r)
else:
logging.warning(f"Could not set balance of {hex(addr)} to {bal}")
for addr,bal in zip(target_addrs[1:], target_bals[1:]):
for i_r in results:
stor = set_balance(addr, bal, i_r)
if stor:
storage_result.update(stor)
break
else:
for _, _, i_r in gen_constraints:
stor = set_balance(addr, bal, i_r)
if stor:
storage_result.update(stor)
results = [i_r] + results
break
results.append(i_r)
else:
logging.warning(f"Could not set balance of {hex(addr)} to {bal}")
with open(output_file, 'w') as f:
json.dump({"0x{0:0{1}X}".format(k, 64): "0x{0:0{1}x}".format(v, 64) for k, v in storage_result.items()}, f)
if __name__ == '__main__':
if len(sys.argv) < 5 or len(sys.argv) % 2 != 1:
print('Usage: %s <code> <output file> <target-address> <target-balance> [<target-address> <target-balance>] ...'
% sys.argv[0], file=sys.stderr)
exit(-1)
code = sys.argv[1]
output_file = sys.argv[2]
target_addresses = sys.argv[3::2]
target_balances = sys.argv[4::2]
main(code, output_file, target_addresses, target_balances) | t-hermanns/coercer | bin/set_balanceOf.py | set_balanceOf.py | py | 4,086 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "z3.z3.Array",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "z3.z3",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "z3.z3.BitVecSort",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "z3.z3.Store",
"line_number": 1... |
11704013339 | # -*- coding: utf-8 -*-
"""Translator module"""
from __future__ import division
from data import NUMBERS
class Translator(object):
"""Translator class"""
@classmethod
def translate(cls, data):
"""The method for converting a input data to number instance """
if isinstance(data, str):
str_result = "".join(char for char in data if char.isdigit())
value = int(str_result) if str_result else 0
elif isinstance(data, (int, float, long)):
value = data
else:
raise TypeError("Expected {} or {} / {}. But taken {}".format(str, int, float, data))
return value
def __enter__(self):
self.translate = self.context_translate
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return True
@classmethod
def context_translate(cls, data):
"""TRANSLATE methodf"""
value = cls.translate(data)
sign = "" if value >= 0 else NUMBERS["minus"]
abs_value = abs(value)
if value in NUMBERS and value < 100:
str_value = NUMBERS[abs_value]
else:
str_value = " ".join(cls._get_power_thousand(abs_value))
return " ".join((sign, str_value))
@classmethod
def _get_power_thousand(cls, value):
"""Sort out with thousand to the power"""
while value >= 1:
len_value = len(str(value))
power_thousand = 10 ** ((len_value - 1) // 3 * 3)
value_under_thousand = value // power_thousand
str_value_under_thousand = " ".join(cls._get_under_thousand(value_under_thousand))
str_power_thousand = NUMBERS[power_thousand] if power_thousand > 1 else ""
str_value = " ".join((str_value_under_thousand, str_power_thousand))
value -= value_under_thousand * power_thousand
yield str_value
@classmethod
def _get_under_thousand(cls, value):
"""Sort out with values under thousand"""
while value >= 1:
if value >= 100:
quantity_hundreds = value // 100
value -= quantity_hundreds * 100
str_and = NUMBERS["and"] if value > 0 else ""
str_value = " ".join((NUMBERS[quantity_hundreds], NUMBERS[100], str_and))
elif value in NUMBERS:
str_value = NUMBERS[value]
value = 0
else:
value_tens = value // 10 * 10
str_value = NUMBERS[value_tens]
value = value - value_tens
yield str_value
| russtanevich/num_converter | translator.py | translator.py | py | 2,596 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "data.NUMBERS",
"line_number": 33,
"usage_type": "name"
},
{
"api_name": "data.NUMBERS",
"line_number": 35,
"usage_type": "name"
},
{
"api_name": "data.NUMBERS",
"line_number": 36,
"usage_type": "name"
},
{
"api_name": "data.NUMBERS",
"line_numbe... |
6679921790 | #!/usr/bin/env python
"""
Download the given htmx version and the extensions we're using.
"""
import argparse
import subprocess
from typing import List, Optional
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("version", help="e.g. 1.0.1")
args = parser.parse_args(argv)
version: str = args.version
download_file(version, "htmx.js")
download_file(version, "ext/debug.js")
download_file(version, "ext/event-header.js")
print("✅")
return 0
def download_file(version: str, name: str) -> None:
print(f"{name}...")
subprocess.run(
[
"curl",
"--silent",
"--location",
f"https://unpkg.com/htmx.org@{version}/dist/{name}",
"-o",
f"example/static/{name}",
],
check=True,
)
# Fix lack of trailing newline in minified files as otherwise pre-commit
# has to fix it.
if name.endswith(".min.js"):
with open(f"example/static/{name}", "a") as fp:
fp.write("\n")
if __name__ == "__main__":
raise SystemExit(main())
| hernantz/django-htmx-demo | download_htmx.py | download_htmx.py | py | 1,146 | python | en | code | 5 | github-code | 36 | [
{
"api_name": "typing.Optional",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "typing.List",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "argparse.ArgumentParser",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "subprocess.run",
... |
23597687031 | import sieve
from typing import Dict, List
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.environ.get('SIEVE_API_KEY')
sieve.SIEVE_API_KEY = os.getenv('SIEVE_API_KEY')
sieve.SIEVE_API_URL = os.getenv('SIEVE_API_URL')
@sieve.Model(
name="deepface-emotion-detector",
gpu = True,
python_packages=[
"opencv-python==4.6.0.66",
"tensorflow==2.11.0",
"pandas==1.5.3",
"numpy==1.24.2",
"deepface==0.0.79",
'mediapipe==0.9.0'
],
python_version="3.8",
)
class EmotionDetector:
def __setup__(self):
from deepface import DeepFace
self.model = DeepFace.build_model('Emotion')
# Load the weights from the saved H5 file
self.emotion_labels = {0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy', 4: 'neutral', 5: 'sad', 6: 'surprise'}
import mediapipe as mp
self.mp_face_detection = mp.solutions.face_detection
self.face_detection = self.mp_face_detection.FaceDetection(min_detection_confidence=0.7)
def detect_faces(self, img: sieve.Image):
import cv2
import numpy as np
results = self.face_detection.process(cv2.cvtColor(img.array, cv2.COLOR_BGR2RGB))
faces = []
if results.detections:
for detection in results.detections:
bounding_box = detection.location_data.relative_bounding_box
x = int(bounding_box.xmin * img.width)
w = int(bounding_box.width * img.width)
y = int(bounding_box.ymin * img.height)
h = int(bounding_box.height * img.height)
detected_face = img.array[y : y + h, x : x + w]
face_array = np.array(detected_face)
bbox = [x, y, w, h]
faces.append({
"array": face_array,
"box": bbox,
"class_name": "face",
"score": detection.score[0],
"frame_number": None if not hasattr(img, "frame_number") else img.frame_number
})
return faces
def __predict__(self, img: sieve.Image) -> List:
import tensorflow as tf
import numpy as np
from deepface import DeepFace
import cv2
outputs = []
faces = self.detect_faces(img)
for face in faces:
face_img = face['array']
#preprocess the face image
if face_img is not None and np.any(face_img):
gray_face = cv2.cvtColor(face_img, cv2.COLOR_RGB2GRAY)
resized_face = cv2.resize(gray_face, (48, 48))
preprocessed_face = tf.keras.applications.resnet50.preprocess_input(resized_face)
preprocessed_face = np.expand_dims(preprocessed_face, axis=0)
#predict the emotion of the face image
emotions = self.model.predict(preprocessed_face)[0]
labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
dominant_emotion = np.argmax(emotions)
emotion_label = self.emotion_labels[dominant_emotion]
confidence = emotions[dominant_emotion]
outputs.append({
"frame_number": face['frame_number'],
"class_name": "face",
"box": face["box"],
"score": face["score"],
"emotion": emotion_label,
"confidence": confidence
})
return outputs
| GauravMohan1/sieve_emotion_face_tracker | main.py | main.py | py | 3,571 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "dotenv.load_dotenv",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "os.environ.get",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "sieve.SIEVE_API_KEY",
... |
20078827999 | from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from api.serializers import BookSerializer
from books.models import Book, PublicationLanguage, Author
from django.test import Client
client = Client()
class TestBookList(APITestCase):
def setUp(self) -> None:
self.publication_language_id = PublicationLanguage.objects.get_or_create(
language="en")[0]
self.author_id = Author.objects.get_or_create(name="test_author")[0]
def test_empty_list_books(self):
response = client.get(reverse("api:book_list"))
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
self.assertEqual(response.data, serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_all_books(self):
book = Book.objects.create(
isbn="1234567891234",
title="test_title",
publication_year=2008,
page_count=1000,
cover="https://google.pl",
publication_language=self.publication_language_id)
book.author.set([self.author_id])
response = client.get(reverse("api:book_list"))
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
self.assertEqual(response.data, serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_filter_publication_date(self):
book_first = Book.objects.create(
isbn="1234567891234",
title="test_title",
publication_year=2008,
page_count=2008,
cover="https://google.pl",
publication_language=self.publication_language_id)
book_first.author.set([self.author_id])
book_second = Book.objects.create(
isbn="1234567891235",
title="test_title123",
publication_year=2018,
page_count=2008,
cover="https://google.pl",
publication_language=self.publication_language_id)
book_second.author.set([self.author_id])
url = f"{reverse('api:book_list')}?publication_year__gte=&publication_year__lte=2013"
response = client.get(url)
books = Book.objects.filter(publication_year__lte=2013)
serializer = BookSerializer(books, many=True)
self.assertEqual(response.data, serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
| tomasz-rzesikowski/books_poc | api/tests/tests_views.py | tests_views.py | py | 2,504 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.test.Client",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "rest_framework.test.APITestCase",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "books.models.PublicationLanguage.objects.get_or_create",
"line_number": 14,
"usage_type... |
14521287997 | #imports the os package and inotify
import os
from inotify_simple import INotify, flags
#pulls in the package
inotify = INotify()
#runs the below command so this script will keep running once it's finished
os.system("while :; do python3 File-Changes.py; done")
#creates the watch flags
watch_flags = flags.CREATE | flags.DELETE | flags.MODIFY | flags.DELETE_SELF
#creates watches for the below directory
wdVarLog = inotify.add_watch("/var/log", watch_flags)
wdETC = inotify.add_watch("/etc", watch_flags)
#for event in inotify prints to directorylogs
for event in inotify.read():
fOpen = open("directorylogs.txt","a")
fOpen.write(event)
fOpen.close()
#for flag in event prints out to the same file as the events
for flag in flags.from_mask(event.mask):
fstring = (" " + str(flag))
fOpen = open("directorylogs.txt","a")
fOpen.write(fstring)
fOpen.close()
| Splixxy/Cron-Job | File-Changes.py | File-Changes.py | py | 907 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "inotify_simple.INotify",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "os.system",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "inotify_simple.flags.CREATE",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "inotif... |
32413884802 | import pytest
import torch
from renate.benchmark.models.transformer import HuggingFaceSequenceClassificationTransformer
@pytest.mark.parametrize("model_name", ["distilbert-base-uncased", "bert-base-uncased"])
def test_init(model_name):
HuggingFaceSequenceClassificationTransformer(
pretrained_model_name_or_path=model_name, num_outputs=10
)
@pytest.mark.parametrize(
"model_name,input_dim",
[
["distilbert-base-uncased", (128,)],
["bert-base-uncased", (256,)],
],
)
def test_text_transformer_fwd(model_name, input_dim):
transformer = HuggingFaceSequenceClassificationTransformer(
pretrained_model_name_or_path=model_name
)
x = {"input_ids": torch.randint(0, 30000, (5, *input_dim))}
y_hat = transformer(x)
assert y_hat.shape[0] == 5
assert y_hat.shape[1] == 10
| awslabs/Renate | test/renate/benchmark/models/test_text_transformer.py | test_text_transformer.py | py | 844 | python | en | code | 251 | github-code | 36 | [
{
"api_name": "renate.benchmark.models.transformer.HuggingFaceSequenceClassificationTransformer",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "pytest.mark.parametrize",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "pytest.mark",
"line_number": 7,
"u... |
74260920742 | import numpy as np
import torch
import copy
from pathlib import Path
from torch_scatter import scatter
from typing import Dict, Tuple
from pcdet.datasets.v2x_sim.v2x_sim_dataset_ego import V2XSimDataset_EGO, get_pseudo_sweeps_of_1lidar, get_nuscenes_sensor_pose_in_global, apply_se3_
from pcdet.datasets.v2x_sim.v2x_sim_utils import roiaware_pool3d_utils
class V2XSimDataset_EGO_LATE(V2XSimDataset_EGO):
def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None):
super().__init__(dataset_cfg, class_names, training, root_path, logger)
assert self.mode == 'test', f"late fusion only support validation"
def _get_prediction_ego(self, sample_token: str) -> np.ndarray:
path_modar = self.exchange_database / f"{sample_token}_id1_modar.pth"
modar = torch.load(path_modar, map_location=torch.device('cpu')).numpy() if path_modar.exists() else np.zeros(1, 9)
return modar
@torch.no_grad()
def _get_prediction_agent(self, lidar_id: int, lidar_token: str, sample_token: str, exchange_setting: str) -> Tuple[np.ndarray]:
"""
Predictions are in agent's frame
"""
assert exchange_setting in ('now', 'prev')
glob_se3_lidar = get_nuscenes_sensor_pose_in_global(self.nusc, lidar_token) # (4, 4)
path_modar = self.exchange_database / f"{sample_token}_id{lidar_id}_modar.pth"
if path_modar.exists():
modar = torch.load(path_modar) # on gpu, (N_modar, 7 + 2) - box-7, score, label
# ---
# propagate modar forward
path_foregr = self.exchange_database / f"{sample_token}_id{lidar_id}_foreground.pth"
if path_foregr.exists() and exchange_setting == 'prev':
foregr = torch.load(path_foregr) # on gpu, (N_fore, 5 + 2 + 3 + 3) - point-5, sweep_idx, inst_idx, cls_prob-3, flow-3
# pool
box_idx_of_foregr = roiaware_pool3d_utils.points_in_boxes_gpu(
foregr[:, :3].unsqueeze(0), modar[:, :7].unsqueeze(0)
).squeeze(0).long() # (N_foregr,) | == -1 mean not belong to any boxes
mask_valid_foregr = box_idx_of_foregr > -1
foregr = foregr[mask_valid_foregr]
box_idx_of_foregr = box_idx_of_foregr[mask_valid_foregr]
unq_box_idx, inv_unq_box_idx = torch.unique(box_idx_of_foregr, return_inverse=True)
# weighted sum of foregrounds' offset; weights = foreground's prob dynamic
boxes_offset = scatter(foregr[:, -3:], inv_unq_box_idx, dim=0, reduce='mean') * 2. # (N_modar, 3)
# offset modar; here, assume objects maintain the same speed
modar[unq_box_idx, :3] += boxes_offset
modar = modar.cpu().numpy()
else:
modar = np.zeros((0, 9))
return modar, glob_se3_lidar
def _get_lidar_token_of_present_agents(self, sample_token: str) -> Dict[int, str]:
out = dict()
if sample_token == '':
return out
sample = self.nusc.get('sample', sample_token)
for sensor_name, sensor_token in sample['data'].items():
if sensor_name not in self._lidars_name:
continue
lidar_id = int(sensor_name.split('_')[-1])
out[lidar_id] = sensor_token
return out
def __getitem__(self, index):
if self._merge_all_iters_to_one_epoch:
index = index % len(self.infos)
info = copy.deepcopy(self.infos[index])
gt_boxes, gt_names = info['gt_boxes'], info['gt_names']
# gt_boxes: (N_tot, 7)
# gt_names: (N_tot,)
ego_se3_glob = np.linalg.inv(get_nuscenes_sensor_pose_in_global(self.nusc, info['lidar_token'])) # (4, 4)
sample_token = info['token']
sample = self.nusc.get('sample', sample_token)
# get prediction of the ego vehicle @ now
exchange_boxes, exchange_metadata = dict(), dict()
exchange_boxes[1] = self._get_prediction_ego(sample_token)
exchange_metadata[1] = exchange_boxes[1].shape[0]
if self.dataset_cfg.EXCHANGE_SETTING == 'now':
dict_lidar_id_to_token = self._get_lidar_token_of_present_agents(sample_token)
_token_of_sample_of_interest = sample_token
elif self.dataset_cfg.EXCHANGE_SETTING == 'prev':
dict_lidar_id_to_token = self._get_lidar_token_of_present_agents(sample['prev'])
_token_of_sample_of_interest = sample['prev']
else:
raise NotImplementedError(f"EXCHANGE_SETTING := {self.dataset_cfg.EXCHANGE_SETTING} is unknown")
if len(dict_lidar_id_to_token) > 0:
for lidar_id, lidar_token in dict_lidar_id_to_token.items():
if lidar_id == 1:
# ego vehicle is already handled above
continue
modar, glob_se3_lidar = self._get_prediction_agent(lidar_id, lidar_token, _token_of_sample_of_interest, self.dataset_cfg.EXCHANGE_SETTING)
# transform modar to ego frame
ego_se3_lidar = ego_se3_glob @ glob_se3_lidar
modar[:, :7] = apply_se3_(ego_se3_lidar, boxes_=modar[:, :7], return_transformed=True)
# store agent's modar
exchange_boxes[lidar_id] = modar
exchange_metadata[lidar_id] = modar.shape[0]
# -----------------
# format output
# assemble datadict
input_dict = {
'points': np.zeros((1, 7)), # Dummy | (N_pts, 5 + 2) - point-5, sweep_idx, inst_idx
'gt_boxes': gt_boxes, # (N_inst, 7)
'gt_names': gt_names, # (N_inst,)
'frame_id': Path(info['lidar_path']).stem,
'metadata': {
'lidar_token': info['lidar_token'],
'num_sweeps_target': self.num_sweeps,
'sample_token': info['token'],
'lidar_id': 1,
'num_original': 0,
'exchange': exchange_metadata,
'exchange_boxes': exchange_boxes, # (N_boxes_tot, 7 + 2) - box-7, score, label
}
}
# data augmentation & other stuff
data_dict = self.prepare_data(data_dict=input_dict)
return data_dict
| quan-dao/practical-collab-perception | pcdet/datasets/v2x_sim/v2x_sim_dataset_ego_late.py | v2x_sim_dataset_ego_late.py | py | 6,411 | python | en | code | 5 | github-code | 36 | [
{
"api_name": "pcdet.datasets.v2x_sim.v2x_sim_dataset_ego.V2XSimDataset_EGO",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "torch.load",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "torch.device",
"line_number": 19,
"usage_type": "call"
},
{
... |
73339180903 | import asyncio
import json
from datetime import datetime
import aiohttp
from pydantic import BaseModel, Field, NonNegativeFloat
from faststream import ContextRepo, FastStream, Logger
from faststream.kafka import KafkaBroker
broker = KafkaBroker("localhost:9092")
app = FastStream(broker)
class CryptoPrice(BaseModel):
price: NonNegativeFloat = Field(
..., examples=[50000.0], description="Current price of cryptocurrency in USD"
)
crypto_currency: str = Field(
..., examples=["BTC"], description="The cryptocurrency"
)
publisher = broker.publisher("new_crypto_price")
async def fetch_crypto_price(
url: str, crypto_currency: str, logger: Logger, context: ContextRepo, time_interval: int = 2
) -> None:
# Always use context: ContextRepo for storing app_is_running variable
while context.get("app_is_running"):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
data = await response.json()
price = data["data"]["amount"]
new_crypto_price = CryptoPrice(
price=price, crypto_currency=crypto_currency
)
await publisher.publish(
new_crypto_price,
key=crypto_currency.encode("utf-8"),
)
else:
logger.warning(
f"Failed API request {url} at time {datetime.now()}"
)
await asyncio.sleep(time_interval)
@app.on_startup
async def app_setup(context: ContextRepo):
context.set_global("app_is_running", True)
@app.on_shutdown
async def shutdown(context: ContextRepo):
context.set_global("app_is_running", False)
# Get all the running tasks and wait them to finish
fetch_tasks = context.get("fetch_tasks")
await asyncio.gather(*fetch_tasks)
@app.after_startup
async def publish_crypto_price(logger: Logger, context: ContextRepo):
logger.info("Starting publishing:")
cryptocurrencies = [("Bitcoin", "BTC"), ("Ethereum", "ETH")]
fetch_tasks = [
asyncio.create_task(
fetch_crypto_price(
f"https://api.coinbase.com/v2/prices/{crypto_currency}-USD/spot",
crypto_currency,
logger,
context,
)
)
for _, crypto_currency in cryptocurrencies
]
# you need to save asyncio tasks so you can wait them to finish at app shutdown (the function with @app.on_shutdown function)
context.set_global("fetch_tasks", fetch_tasks) | airtai/faststream-gen | docs_src/tutorial/retrieve-publish-crypto/app/application.py | application.py | py | 2,687 | python | en | code | 19 | github-code | 36 | [
{
"api_name": "faststream.kafka.KafkaBroker",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "faststream.FastStream",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "pydantic.BaseModel",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": ... |
16483457321 | from flask import Blueprint, g
from flask_graphql import GraphQLView
from flask_cors import CORS
from .schema import schema
api = Blueprint('api', __name__)
CORS(api, supports_credentials=True) # Enables CORS with cross origin cookies
class CustomGraphQlView(GraphQLView):
def dispatch_request(self):
response = super().dispatch_request()
for cookie in g.get("cookies", []):
response.set_cookie(cookie.key, cookie.value, **cookie.settings)
return response
api.add_url_rule(
"/graphql",
view_func=CustomGraphQlView.as_view(
"graphql",
schema=schema,
graphiql=True,
middleware=[]
)
)
| AlexEshoo/poll_app_graphql | poll_app_graphql/api/__init__.py | __init__.py | py | 672 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask.Blueprint",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "flask_cors.CORS",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "flask_graphql.GraphQLView",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "flask.g.get",
... |
26236313252 | import csv
import json
# Save .csv file from dict List [{}]
def save_file(results, filename, format):
if(format=='csv'):
if(len(results) > 0):
with open(f'{filename}.csv', 'w', encoding='utf8', newline='') as output_file:
output_file.write('sep=,\n')
fc = csv.DictWriter(output_file, fieldnames=results[0].keys())
fc.writeheader()
fc.writerows(results)
elif(format=='json'):
with open(f'{filename}.json', 'w') as f:
json.dump(results, f)
print(f'file saved to {filename}.{format}') | cristianmacedo/crawliexpress | crawliexpress/lib/helpers.py | helpers.py | py | 648 | python | en | code | 8 | github-code | 36 | [
{
"api_name": "csv.DictWriter",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "json.dump",
"line_number": 16,
"usage_type": "call"
}
] |
35196657682 | import os
import dataclasses
import unittest
import torch
import math
import copy
import numpy as np
import lpips
from dataset.co3d_dataset import Co3dDataset, FrameData
from dataset.dataset_zoo import DATASET_ROOT
from tools.utils import dataclass_to_cuda_
from evaluation.evaluate_new_view_synthesis import eval_batch
from tools.metric_utils import calc_psnr, eval_depth
from models.model_dbir import ModelDBIR
class TestEvaluation(unittest.TestCase):
def setUp(self):
# initialize evaluation dataset/dataloader
torch.manual_seed(42)
category = "skateboard"
dataset_root = DATASET_ROOT
frame_file = os.path.join(dataset_root, category, "frame_annotations.jgz")
sequence_file = os.path.join(dataset_root, category, "sequence_annotations.jgz")
self.image_size = 256
self.dataset = Co3dDataset(
frame_annotations_file=frame_file,
sequence_annotations_file=sequence_file,
dataset_root=dataset_root,
image_height=self.image_size,
image_width=self.image_size,
box_crop=True,
load_point_clouds=True,
)
self.bg_color = 0.0
# init the lpips model for eval
self.lpips_model = lpips.LPIPS(net="vgg")
def test_eval_depth(self):
"""
Check that eval_depth correctly masks errors and that, for get_best_scale=True,
the error with scaled prediction equals the error without scaling the
predicted depth. Finally, test that the error values are as expected
for prediction and gt differing by a constant offset.
"""
gt = (torch.randn(10, 1, 300, 400, device="cuda") * 5.0).clamp(0.0)
mask = (torch.rand_like(gt) > 0.5).type_as(gt)
for diff in 10 ** torch.linspace(-5, 0, 6):
for crop in (0, 5):
pred = gt + (torch.rand_like(gt) - 0.5) * 2 * diff
# scaled prediction test
mse_depth, abs_depth = eval_depth(
pred,
gt,
crop=crop,
mask=mask,
get_best_scale=True,
)
mse_depth_scale, abs_depth_scale = eval_depth(
pred * 10.0,
gt,
crop=crop,
mask=mask,
get_best_scale=True,
)
self.assertAlmostEqual(
float(mse_depth.sum()), float(mse_depth_scale.sum()), delta=1e-4
)
self.assertAlmostEqual(
float(abs_depth.sum()), float(abs_depth_scale.sum()), delta=1e-4
)
# error masking test
pred_masked_err = gt + (torch.rand_like(gt) + diff) * (1 - mask)
mse_depth_masked, abs_depth_masked = eval_depth(
pred_masked_err,
gt,
crop=crop,
mask=mask,
get_best_scale=True,
)
self.assertAlmostEqual(
float(mse_depth_masked.sum()), float(0.0), delta=1e-4
)
self.assertAlmostEqual(
float(abs_depth_masked.sum()), float(0.0), delta=1e-4
)
mse_depth_unmasked, abs_depth_unmasked = eval_depth(
pred_masked_err,
gt,
crop=crop,
mask=1 - mask,
get_best_scale=True,
)
self.assertGreater(
float(mse_depth_unmasked.sum()),
float(diff ** 2),
)
self.assertGreater(
float(abs_depth_unmasked.sum()),
float(diff),
)
# tests with constant error
pred_fix_diff = gt + diff * mask
for _mask_gt in (mask, None):
mse_depth_fix_diff, abs_depth_fix_diff = eval_depth(
pred_fix_diff,
gt,
crop=crop,
mask=_mask_gt,
get_best_scale=False,
)
if _mask_gt is not None:
expected_err_abs = diff
expected_err_mse = diff ** 2
else:
err_mask = (gt > 0.0).float() * mask
if crop > 0:
err_mask = err_mask[:, :, crop:-crop, crop:-crop]
gt_cropped = gt[:, :, crop:-crop, crop:-crop]
else:
gt_cropped = gt
gt_mass = (gt_cropped > 0.0).float().sum(dim=(1, 2, 3))
expected_err_abs = (
diff * err_mask.sum(dim=(1, 2, 3)) / (gt_mass)
)
expected_err_mse = diff * expected_err_abs
self.assertTrue(
torch.allclose(
abs_depth_fix_diff,
expected_err_abs * torch.ones_like(abs_depth_fix_diff),
atol=1e-4,
)
)
self.assertTrue(
torch.allclose(
mse_depth_fix_diff,
expected_err_mse * torch.ones_like(mse_depth_fix_diff),
atol=1e-4,
)
)
def test_psnr(self):
"""
Compare against opencv and check that the psnr is above
the minimum possible value.
"""
import cv2
im1 = torch.rand(100, 3, 256, 256).cuda()
for max_diff in 10 ** torch.linspace(-5, 0, 6):
im2 = im1 + (torch.rand_like(im1) - 0.5) * 2 * max_diff
im2 = im2.clamp(0.0, 1.0)
# check that our psnr matches the output of opencv
psnr = calc_psnr(im1, im2)
psnr_cv2 = cv2.PSNR(
im1.cpu().numpy().astype(np.float64),
im2.cpu().numpy().astype(np.float64),
1.0,
)
self.assertAlmostEqual(float(psnr), float(psnr_cv2), delta=1e-4)
# check that all psnrs are bigger than the minimum possible psnr
max_mse = max_diff ** 2
min_psnr = 10 * math.log10(1.0 / max_mse)
for _im1, _im2 in zip(im1, im2):
_psnr = calc_psnr(_im1, _im2)
self.assertTrue(float(_psnr) >= min_psnr)
def _one_sequence_test(
self,
seq_dataset,
n_batches=2,
min_batch_size=5,
max_batch_size=10,
):
# form a list of random batches
batch_indices = []
for bi in range(n_batches):
batch_size = torch.randint(
low=min_batch_size, high=max_batch_size, size=(1,)
)
batch_indices.append(torch.randperm(len(seq_dataset))[:batch_size])
loader = torch.utils.data.DataLoader(
seq_dataset,
# batch_size=1,
shuffle=False,
batch_sampler=batch_indices,
collate_fn=FrameData.collate,
)
model = ModelDBIR(image_size=self.image_size, bg_color=self.bg_color)
model.cuda()
self.lpips_model.cuda()
for frame_data in loader:
self.assertIsNone(frame_data.frame_type)
# override the frame_type
frame_data.frame_type = [
"train_unseen",
*(["train_known"] * (len(frame_data.image_rgb) - 1)),
]
# move frame_data to gpu
frame_data = dataclass_to_cuda_(frame_data)
preds = model(**dataclasses.asdict(frame_data))
nvs_prediction = copy.deepcopy(preds["nvs_prediction"])
eval_result = eval_batch(
frame_data,
nvs_prediction,
bg_color=self.bg_color,
lpips_model=self.lpips_model,
)
# Make a terribly bad NVS prediction and check that this is worse
# than the DBIR prediction.
nvs_prediction_bad = copy.deepcopy(preds["nvs_prediction"])
nvs_prediction_bad.depth_render += (
torch.randn_like(nvs_prediction.depth_render) * 100.0
)
nvs_prediction_bad.image_render += (
torch.randn_like(nvs_prediction.image_render) * 100.0
)
nvs_prediction_bad.mask_render = (
torch.randn_like(nvs_prediction.mask_render) > 0.0
).float()
eval_result_bad = eval_batch(
frame_data,
nvs_prediction_bad,
bg_color=self.bg_color,
lpips_model=self.lpips_model,
)
lower_better = {
"psnr": False,
"psnr_fg": False,
"depth_abs_fg": True,
"iou": False,
"rgb_l1": True,
"rgb_l1_fg": True,
}
for metric in lower_better.keys():
m_better = eval_result[metric]
m_worse = eval_result_bad[metric]
if m_better != m_better or m_worse != m_worse:
continue # metric is missing, i.e. NaN
_assert = (
self.assertLessEqual
if lower_better[metric]
else self.assertGreaterEqual
)
_assert(m_better, m_worse)
def test_full_eval(self, n_sequences=5):
"""Test evaluation."""
for seq, idx in list(self.dataset.seq_to_idx.items())[:n_sequences]:
seq_dataset = torch.utils.data.Subset(self.dataset, idx)
self._one_sequence_test(seq_dataset)
| eldar/snes | 3rdparty/co3d/tests/test_evaluation.py | test_evaluation.py | py | 10,050 | python | en | code | 59 | github-code | 36 | [
{
"api_name": "unittest.TestCase",
"line_number": 19,
"usage_type": "attribute"
},
{
"api_name": "torch.manual_seed",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "dataset.dataset_zoo.DATASET_ROOT",
"line_number": 24,
"usage_type": "name"
},
{
"api_nam... |
71656889065 | import torch
import torchaudio
from torchaudio.transforms import MelSpectrogram, Spectrogram
def load_wav_to_torch(full_path, hop_size=0, slice_train=False):
wav, sampling_rate = torchaudio.load(full_path, normalize=True)
if not slice_train:
p = (wav.shape[-1] // hop_size + 1) * hop_size - wav.shape[-1]
wav = torch.nn.functional.pad(wav, (0, p), mode="constant").data
return wav.squeeze(0), sampling_rate
class SpectrogramFixed(torch.nn.Module):
"""In order to remove padding of torchaudio package + add log10 scale."""
def __init__(self, **kwargs):
super(SpectrogramFixed, self).__init__()
self.torchaudio_backend = Spectrogram(**kwargs)
def forward(self, x):
outputs = self.torchaudio_backend(x)
return outputs[..., :-1]
class MelSpectrogramFixed(torch.nn.Module):
"""In order to remove padding of torchaudio package + add log10 scale."""
def __init__(self, **kwargs):
super(MelSpectrogramFixed, self).__init__()
self.torchaudio_backend = MelSpectrogram(**kwargs)
def forward(self, x):
outputs = torch.log(self.torchaudio_backend(x) + 0.001)
return outputs[..., :-1]
def torch_wav2spec(wav_fn, fft_size, hop_size, win_length, num_mels, fmin, fmax, sample_rate):
""" Waveform to linear-spectrogram and mel-sepctrogram. """
# Read wavform
wav, sr = load_wav_to_torch(wav_fn, hop_size, slice_train=False)
if sr != sample_rate:
raise ValueError(f"{sr} SR doesn't match target {sample_rate} SR")
if torch.min(wav) < -1.:
print('min value is ', torch.min(wav))
if torch.max(wav) > 1.:
print('max value is ', torch.max(wav))
# Spectrogram process
spec_fn = SpectrogramFixed(n_fft=fft_size, win_length=win_length, hop_length=hop_size,
window_fn=torch.hann_window).to(device=wav.device)
spec = spec_fn(wav)
# Mel-spectrogram
mel_fn = MelSpectrogramFixed(sample_rate=sample_rate, n_fft=fft_size, win_length=win_length,
hop_length=hop_size, f_min=fmin, f_max=fmax, n_mels=num_mels,
window_fn=torch.hann_window).to(device=wav.device)
mel = mel_fn(wav)
# Wav-processing
wav = wav.squeeze(0)[:mel.shape[-1]*hop_size]
# Check wav and spectorgram
assert wav.shape[-1] == mel.shape[-1] * hop_size, f"| wav: {wav.shape}, spec: {spec.shape}, mel: {mel.shape}"
assert mel.shape[-1] == spec.shape[-1], f"| wav: {wav.shape}, spec: {spec.shape}, mel: {mel.shape}"
return {"wav": wav.cpu().detach().numpy(), "linear": spec.squeeze(0).T.cpu().detach().numpy(),
"mel": mel.squeeze(0).T.cpu().detach().numpy()}
| jisang93/VISinger | utils/audio/mel_processing.py | mel_processing.py | py | 2,724 | python | en | code | 13 | github-code | 36 | [
{
"api_name": "torchaudio.load",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "torch.nn.functional.pad",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "torch.nn",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"... |
3585781734 | from __future__ import absolute_import, division, print_function
# Local Imports
from modeling import ArgStrModel
from arguments import TrainingArguments
from training import ArgStrTrainer
from processors import get_datasets
from utils import Data_Collator, set_seed
# Standard Imports
import os
import random
# Third Party Imports
import json
import torch
import mlflow
from transformers import BertConfig
if __name__ == '__main__':
# load the best trained model and config
config_available = False
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
# define the experiment parameters
bert_arch = "bert-base-uncased"
task_name = "STLAS_randomized_LOO_gretz_topic"
exp_name = task_name + "_v1_bb"
mlflow_exp_name = "ASL_randomized_v2"
NUM_OF_SEEDS = 5
# define the path from where the task data is loaded from.
task_data_dir = "/mnt/data2/Sid/arg_quality/pytorch/task4_hpo/data/*.csv"
if config_available:
config_file = open("/mnt/data2/Sid/arg_quality/pytorch/task4_hpo/best_model_details_MTLAS_LOO_swanson_v2_bb"
".json", )
config_data = json.load(config_file)
else:
# define config
config_data = {
"bert_arch": bert_arch,
"task_name": task_name,
"exp_name": exp_name,
"device": torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
"is_distributed": False,
"resources_per_trial": {
'cpu': 4,
'gpu': 1
},
"data_dir": task_data_dir,
"split_by_topic": True if "randomized" in task_name else False,
"eval_batch_size": 128,
"train_batch_size": 64,
"max_seq_length": None,
"max_seq_length_perc": 0.95,
"data_collator": Data_Collator,
"dropout_prob": 0.1,
"bert_hidden_layers": 4,
"nn_config": 1,
"dataset_loss_method": "unweighted",
"learning_rate": 4.8672041684500765e-06,
"weight_decay": 0.1936871758204528,
"num_epochs": 50,
"max_steps": -1, # We use num_epochs instead.
"mlflow": {
"experiment_name": mlflow_exp_name,
"tracking_uri": "http://mlflow.dbs.ifi.lmu.de:5000"
}
}
if mlflow.get_experiment_by_name(mlflow_exp_name) is None:
mlflow.create_experiment(mlflow_exp_name)
mlflow.set_experiment(experiment_name=mlflow_exp_name)
mlflow.set_tracking_uri("http://mlflow.dbs.ifi.lmu.de:5000")
# define 10 seeds to run for training
seed_list = random.sample(range(0, 10000), NUM_OF_SEEDS)
for seed_value in seed_list:
set_seed(seed_value)
with mlflow.start_run(run_name="asl_randomized_v1"):
mlflow.log_param("seed", seed_value)
mlflow.log_param("Task Name", task_name)
print("Seed:", seed_value)
train_dataset, eval_dataset, test_dataset, task_dict = get_datasets(config_data)
# Load model setup.
if not config_available:
bert_config = BertConfig.from_pretrained(
config_data["bert_arch"],
finetuning_task=task_name,
output_hidden_states=True
)
model = ArgStrModel.from_pretrained(
config_data["bert_arch"],
config=bert_config,
dropout_prob=config_data["dropout_prob"],
bert_hidden_layers=config_data["bert_hidden_layers"],
mlp_config=config_data["nn_config"],
task_dict=task_dict,
device=config_data["device"]
)
else:
bert_config = BertConfig.from_pretrained(
config_data["bert_arch"],
finetuning_task=task_name,
output_hidden_states=True
)
model = ArgStrModel(
config=bert_config,
dropout_prob=config_data["dropout_prob"],
bert_hidden_layers=config_data["bert_hidden_layers"],
mlp_config=config_data["nn_config"],
task_dict=task_dict,
device=config_data["device"])
with open(os.path.join(config_data["best_checkpoint_path"], "best_model.pt"), 'rb') as checkpt:
model_state, optimizer_state = torch.load(checkpt)
model.load_state_dict(model_state)
training_args = TrainingArguments(
learning_rate=config_data["learning_rate"],
train_model=True,
evaluate_during_training=True,
save_steps=0,
max_num_train_epochs=25,
train_batch_size=config_data["train_batch_size"],
eval_batch_size=config_data["eval_batch_size"],
weight_decay=config_data["weight_decay"],
weighted_dataset_loss=config_data["dataset_loss_method"]
)
retrain_runner = ArgStrTrainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
test_dataset=test_dataset,
data_collator=Data_Collator,
task_name=config_data["task_name"]
)
retrain_runner.train_model(device=config_data["device"],
mlflow_logging=True,
retraining=True,
seed_value=seed_value)
if "MTLAS" in task_name:
retrain_runner.infer_model(
infer_dataset=test_dataset,
device=config_data["device"],
exp_name=config_data["exp_name"],
task_dict=task_dict,
exp_seed=seed_value,
)
| The-obsrvr/ArgStrength | Hyper-parameter-optimization/src/retraining.py | retraining.py | py | 6,077 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.environ",
"line_number": 24,
"usage_type": "attribute"
},
{
"api_name": "json.load",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "torch.device",
"line_number": 45,
"usage_type": "call"
},
{
"api_name": "torch.cuda.is_available",
... |
10680492541 | import time
import tensorflow.compat.v1 as tf
# tf.disable_eager_execution()
tf.config.run_functions_eagerly(True)
tf.enable_eager_execution()
from utils import *
from models import RGCN
import random
import pandas as pd
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from gcn.models import GCN
# Set random seed
seed = 123
np.random.seed(seed)
tf.set_random_seed(seed)
random.seed(seed)
# Settings
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('dataset', 'cora', 'Dataset string.') # 'cora', 'citeseer', 'pubmed'
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('epochs', 200, 'Number of epochs to train.')
flags.DEFINE_integer('hidden1', 32, 'Number of units in hidden layer.')
flags.DEFINE_float('dropout', 0.6, 'Dropout rate (1 - keep probability).')
flags.DEFINE_float('weight_decay', 5e-4, 'Weight for L2 loss on embedding matrix.')
flags.DEFINE_float('para_var', 1, 'Parameter of variance-based attention')
flags.DEFINE_float('para_kl', 5e-4, 'Parameter of kl regularization')
flags.DEFINE_float('para_l2', 5e-4, 'Parameter for l2 loss.')
flags.DEFINE_integer('early_stopping', 20, 'Tolerance for early stopping (# of epochs).')
flags.DEFINE_integer('max_degree', 3, 'Maximum Chebyshev polynomial degree.')
# Load data
adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask, label = load_data(FLAGS.dataset)
# train_mask[641:700] = True
perturbed_features, y_train_gpc = perturb_features_gpc(features, 0.8)
gpc_idx, gpc_feature, gpc_y_train_gpc = get_gpc_train_data(perturbed_features, y_train_gpc, train_mask, test_mask, val_mask)
print(len(gpc_idx))
kernel = 1.0 * RBF(1.0)
gpc = GaussianProcessClassifier(kernel=kernel,
random_state=0).fit(gpc_feature[:500], gpc_y_train_gpc[:500])
# gpc.score(perturbed_features, y_train_gpc)
gpc_res = gpc.predict(perturbed_features)
# print(type(gpc_res))
# gpc_res = np.asarray(y_train_gpc) # delete later, used for testing
# print(type(y_train_gpc))
gpc_predict_pert_idx = [i for i, x in enumerate(gpc_res==1) if x]
# print(all_idx_to_remove)
features = sp.csr_matrix(perturbed_features)
# features, y_train, train_mask, adj, label, y_val, val_mask = remove_pert(features, y_train, train_mask, adj, label, y_val, val_mask, gpc_predict_pert_idx)
features = modify_pert(features, gpc_predict_pert_idx) # for continuous features
# print(train_mask)
features = preprocess_features(features)
support = [preprocess_adj(adj, -0.5), preprocess_adj(adj, -1.0)]
placeholders = {
'support': [tf.sparse_placeholder(tf.float32) for _ in range(2)],
'features': tf.sparse_placeholder(tf.float32, shape=tf.constant(features[2], dtype=tf.int64)),
'labels': tf.placeholder(tf.float32, shape=(None, y_train.shape[1])),
'labels_mask': tf.placeholder(tf.int32),
'dropout': tf.placeholder_with_default(0., shape=()),
'num_features_nonzero': tf.placeholder(tf.int32),
}
model = GCN(placeholders, input_dim=features[2][1], logging=True)
sess = tf.Session()
def evaluate(features, support, labels, mask, placeholders, adj):
t_test = time.time()
feed_dict_val = construct_feed_dict(features, support, labels, mask, placeholders, adj)
outs_val = sess.run([model.loss, model.accuracy], feed_dict=feed_dict_val)
return outs_val[0], outs_val[1], (time.time() - t_test)
sess.run(tf.global_variables_initializer())
cost_val = []
var1 = []
for epoch in range(FLAGS.epochs):
t = time.time()
feed_dict = construct_feed_dict(features, support, y_train, train_mask, placeholders, adj)
feed_dict.update({placeholders['dropout']: FLAGS.dropout})
outs = sess.run([model.opt_op, model.loss, model.accuracy, model.vars], feed_dict=feed_dict)
# print(outs[3].shape)
# if epoch == (FLAGS.epochs-1):
# # print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
# df = pd.DataFrame(data = outs[3])
# df.to_csv('/home/zihe-leon/Desktop/RobustGCN-master/src/var0.csv', index = False)
cost, _, duration = evaluate(features, support, y_val, val_mask, placeholders, adj)
cost_val.append(cost)
# Print results
print("Epoch:", '%04d' % (epoch + 1), "train_loss=", "{:.5f}".format(outs[1]),
"train_acc=", "{:.5f}".format(outs[2]), "time=", "{:.5f}".format(time.time() - t))
if epoch > FLAGS.early_stopping and cost_val[-1] > np.mean(cost_val[-(FLAGS.early_stopping+1):-1]):
print("Early stopping...")
break
print("Optimization Finished!")
adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask, label = load_data(FLAGS.dataset)
features = preprocess_features(features)
support = [preprocess_adj(adj, -0.5), preprocess_adj(adj, -1.0)]
test_cost, test_acc, test_duration = evaluate(features, support, y_test, test_mask, placeholders, adj)
print("Test set results:", "cost=", "{:.5f}".format(test_cost),
"accuracy=", "{:.5f}".format(test_acc), "time=", "{:.5f}".format(test_duration))
| zzheng18/CSPC680RGCNV | src/train_gpc.py | train_gpc.py | py | 4,973 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "tensorflow.compat.v1.config.run_functions_eagerly",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "tensorflow.compat.v1.config",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "tensorflow.compat.v1",
"line_number": 4,
"usage_type": "... |
15506027054 |
# https://medium.com/analytics-vidhya/computer-vision-and-deep-learning-part-2-586b6a0d3220 --- main
# https://github.com/Esri/raster-deep-learning/blob/master/docs/writing_deep_learning_python_raster_functions.md
import cv2
import numpy as np
from matplotlib import pyplot as plt
cv_image= cv2.imread("/home/jameshung/Pictures/forest01.jpg",0)
one =cv2.adaptiveThreshold(cv_image,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,11,2)
ret2, two = cv2.threshold(cv_image,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
blur = cv2.GaussianBlur(cv_image,(5,5),0)
ret3,three = cv2.threshold(blur, 0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
images = [cv_image, 0, one,
cv_image, 0, two,
blur, 0, three]
titles = ['Original Image','Histogram','Adaptive Mean Thresholding',
'Original Image','Histogram',"Otsu's Thresholding",
'Gaussian filtered Image','Histogram',"Otsu's Thresholding of Gaussian Blur Image"]
for i in range(3):
plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)
plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
plt.show()
cv2.waitKey(1000)
| hssaccord/myTEST | main.py | main.py | py | 1,348 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "cv2.imread",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "cv2.adaptiveThreshold",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "cv2.ADAPTIVE_THRESH_MEAN_C",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "cv2.T... |
3206852190 | """ Provides the different Bounds that are used by the Table to determine
the Cells that are adjacent to the Table. """
from __future__ import annotations
from _operator import attrgetter
from itertools import cycle
from typing import Callable, cast, Iterable, NamedTuple, Protocol, TypeVar
from pdf2gtfs.config import Config
from pdf2gtfs.datastructures.pdftable.bbox import BBox
from pdf2gtfs.datastructures.table.direction import Direction, E, N, S, W
from pdf2gtfs.datastructures.table.cell import C, Cs
B = TypeVar("B", bound="Bounds")
class F(Protocol):
""" Used as a type to typecheck min/max functions correctly. """
def __call__(self, cells: Iterable[C] | Iterable[BBox],
key: Callable[[C | BBox], float]) -> C:
pass
# Arguments used by the N-/S-/W-/EBounds.
# — func: The function (min / max) used to determine the correct limit.
# — direction: The Direction of the limit.
BoundArg = NamedTuple("BoundArg", [("func", F), ("direction", Direction)])
class Bounds:
""" Basic Bounds, where not all limits necessarily exist. """
d: Direction = None
def __init__(self, n: float | None, w: float | None,
s: float | None, e: float | None) -> None:
self._n = n
self._w = w
self._s = s
self._e = e
self._update_hbox()
self._update_vbox()
@classmethod
def from_bboxes(cls, bboxes: list[BBox], *,
n: BoundArg | None = None, w: BoundArg | None = None,
s: BoundArg | None = None, e: BoundArg | None = None
) -> B:
""" Create a new Bounds from the BBoxes, based on which args are given.
:param bboxes: The BBoxes used for construction.
:param n: The northern BoundArg. None for NBounds.
:param w: The western BoundArg. None for WBounds.
:param s: The southern BoundArg. None for SBounds.
:param e: The eastern BoundArg. None for EBounds.
:return: A new Bounds created from the given BBoxes,
based on which BoundArgs are provided.
"""
return cls(n=get_limit_from_cells(bboxes, n),
w=get_limit_from_cells(bboxes, w),
s=get_limit_from_cells(bboxes, s),
e=get_limit_from_cells(bboxes, e))
@classmethod
def overlaps_any(cls, cells: Cs, c2: C) -> bool:
""" Check if the given Cell overlaps with any of the given Cells.
The overlap function is determined by cls.
:param cells: Use these Cells to check overlap.
:param c2: The Cell that is checked.
:return: True if the Cell overlaps. False, otherwise.
"""
func = getattr(c2.bbox, cls.d.o.overlap_func)
for c1 in cells:
if func(c1.bbox, 0.8):
return True
return False
@classmethod
def select_adjacent_cells(cls, border: list[BBox], cells: Cs) -> Cs:
""" Select those Cells that are adjacent to the border BBoxes.
:param border: The row/col of a Table that is used to determine
if a Cell is adjacent to the Table.
:param cells: The Cells that are checked for adjacency.
:return: Those Cells, which are adjacent to the Table.
"""
def get_all_adjacent_cells() -> Cs:
""" Get Cells that fit only three bounds,
but are overlapping with Cells that overlap all four.
If we are extra_greedy, also get those cells that recursively
overlap with cells that overlap with other cells.
"""
# Need to shallow copy for overlap_cells to be different.
all_cells = list(min_cells)
overlap_cells = all_cells if Config.extra_greedy else min_cells
while True:
new_cells = [c for c in cells
if cls.overlaps_any(overlap_cells, c)
and c not in all_cells]
if not new_cells:
break
all_cells += new_cells
return all_cells
# Get the three basic bounds, which are created from the border.
bounds = cls.from_bboxes(border)
cells = list(filter(bounds.within_bounds, cells))
if not cells:
return []
bounds.update_missing_bound(cells)
# These are the Cells that fit all bounds.
min_cells = list(filter(bounds.within_bounds, cells))
adjacent_cells = get_all_adjacent_cells()
# Sort columns by y0 and rows by x0.
lower_coord = attrgetter(f"bbox.{cls.d.o.normal.lower.coordinate}")
return list(sorted(adjacent_cells, key=lower_coord))
@property
def n(self) -> float | None:
""" The northern bound, i.e., y0/the lowest y coordinate. """
return self._n
@n.setter
def n(self, value: float | None) -> None:
self._n = value
self._update_vbox()
@property
def s(self) -> float | None:
""" The southern bound, i.e., y1/the largest y coordinate. """
return self._s
@s.setter
def s(self, value: float | None) -> None:
self._s = value
self._update_vbox()
@property
def w(self) -> float | None:
""" The western bound, i.e., x0/the lowest x coordinate. """
return self._w
@w.setter
def w(self, value: float | None) -> None:
self._w = value
self._update_hbox()
@property
def e(self) -> float | None:
""" The eastern bound, i.e., x1/the largest y coordinate. """
return self._e
@e.setter
def e(self, value: float | None) -> None:
self._e = value
self._update_hbox()
@property
def hbox(self) -> BBox | None:
""" The horizontal BBox, using only w/e. """
return self._hbox
@property
def vbox(self) -> BBox | None:
""" The vertical BBox, using only n/s. """
return self._vbox
def _update_hbox(self) -> None:
if self.w is None or self.e is None:
hbox = None
else:
hbox = BBox(self.w, -1, self.e, -1)
self._hbox = hbox
def _update_vbox(self) -> None:
if self.n is None or self.s is None:
vbox = None
else:
vbox = BBox(-1, self.n, -1, self.s)
self._vbox = vbox
def within_h_bounds(self, bbox: BBox) -> bool:
""" Check if the given BBox is within the current Bounds, horizontally.
:param bbox: The BBox that is checked.
:return: True if the BBox is within Bounds. False, otherwise.
"""
if self.hbox and self.hbox.is_h_overlap(bbox, 0.5):
return True
if self.hbox:
return False
if self.w is not None and bbox.x1 <= self.w:
return False
if self.e is not None and bbox.x0 >= self.e:
return False
return True
def within_v_bounds(self, bbox: BBox) -> bool:
""" Check if the given BBox is within the current Bounds, vertically.
:param bbox: The BBox that is checked.
:return: True if the BBox is within Bounds. False, otherwise.
"""
if self.vbox and self.vbox.is_v_overlap(bbox, 0.5):
return True
if self.vbox:
return False
if self.n is not None and bbox.y1 <= self.n:
return False
if self.s is not None and bbox.y0 >= self.s:
return False
return True
def within_bounds(self, cell: C) -> bool:
""" Check if the Cell is within the bounds.
If the hbox/vbox is None, that is, if at least one of the w/e or n/s
coordinates is None, the check will not fail immediately.
Instead, in that case, only the existing (if any) coordinate will
be checked.
:param cell: The Cell that is checked.
:return: True, if obj is within both the hbox and the vbox.
False, otherwise.
"""
bbox = cell.bbox
return self.within_h_bounds(bbox) and self.within_v_bounds(bbox)
def merge(self, bounds: B) -> None:
""" Merge the Bounds, such that the resulting Bounds contain both.
:param bounds: The Bounds that is merged into this one.
"""
# n/w use min for lower bound, s/e use max for larger bound.
for coordinate, func in zip("nswe", cycle((min, max))):
getter = attrgetter(coordinate)
value = func(map(getter, (self, bounds)), default=None)
setattr(self, coordinate, value)
def _update_single_limit(
self, which: str, arg: BoundArg, cells: list[C]) -> None:
""" Update a single bound using the BoundArg and the Cells.
:param which: Can be one of "n", "w", "s", "e".
:param arg: The BoundArg that is used to determine the limit.
:param cells: The Cells used to calculate the limit.
"""
setattr(self, which, get_limit_from_cells(cells, arg))
def __repr__(self) -> str:
cls_name = self.__class__.__name__
fmt = "{: >7.2f}"
n = fmt.format(self.n) if self.n is not None else "None"
w = fmt.format(self.w) if self.w is not None else "None"
s = fmt.format(self.s) if self.s is not None else "None"
e = fmt.format(self.e) if self.e is not None else "None"
return f"{cls_name}(n={n}, w={w}, s={s}, e={e})"
class WBounds(Bounds):
""" The western outer bounds of a Table. Used when expanding a Table. """
d = W
@classmethod
def from_bboxes(cls, bboxes: list[BBox], **_) -> WBounds:
n = BoundArg(min, N)
s = BoundArg(max, S)
# We use the opposite Direction here, because we want the outer Bounds.
e = BoundArg(min, E.opposite)
return super().from_bboxes(bboxes, n=n, s=s, e=e)
def update_missing_bound(self, cells: list[C]) -> None:
""" Add the missing bound (western) based on the given Cells. """
args: BoundArg = BoundArg(max, W)
self._update_single_limit("w", args, cells)
class EBounds(Bounds):
""" The eastern outer bounds of a Table. Used when expanding a Table. """
d = E
@classmethod
def from_bboxes(cls, bboxes: list[BBox], **_) -> EBounds:
n = BoundArg(min, N)
s = BoundArg(max, S)
# We use the opposite Direction here, because we want the outer Bounds.
w = BoundArg(max, W.opposite)
return super().from_bboxes(bboxes, n=n, w=w, s=s)
def update_missing_bound(self, cells: list[C]) -> None:
""" Add the missing bound (eastern) based on the given ells. """
args: BoundArg = BoundArg(min, E)
self._update_single_limit("e", args, cells)
class NBounds(Bounds):
""" The northern outer bounds of a Table. Used when expanding a Table. """
d = N
@classmethod
def from_bboxes(cls, bboxes: list[BBox], **_) -> NBounds:
w = BoundArg(min, W)
# We use the opposite Direction here, because we want the outer Bounds.
s = BoundArg(min, S.opposite)
e = BoundArg(max, E)
return super().from_bboxes(bboxes, w=w, s=s, e=e)
def update_missing_bound(self, cells: list[C]) -> None:
""" Add the missing bound (northern) based on the given Cells. """
args: BoundArg = BoundArg(max, N)
self._update_single_limit("n", args, cells)
class SBounds(Bounds):
""" The southern outer bounds of a Table. Used when expanding a Table. """
d = S
@classmethod
def from_bboxes(cls, bboxes: list[BBox], **_) -> SBounds:
# We use the opposite Direction here, because we want the outer Bounds.
n = BoundArg(max, N.opposite)
w = BoundArg(min, W)
e = BoundArg(max, E)
return super().from_bboxes(bboxes, n=n, w=w, e=e)
def update_missing_bound(self, cells: list[C]) -> None:
""" Add the missing bound (southern) based on the given Cells. """
args: BoundArg = BoundArg(min, S)
self._update_single_limit("s", args, cells)
def get_limit_from_cells(objects: list[C] | list[BBox], arg: BoundArg | None
) -> float | None:
""" Calculate a limit from the Cells using the provided func and attr.
:param objects: The Cells/BBoxes used to calculate the limit.
:param arg: The BoundArg used to determine the limit.
:return: The limit of the Cells, based on the given func and d.
"""
if not objects or not arg:
return None
prefix = "bbox." if hasattr(objects[0], "bbox") else ""
getter = attrgetter(prefix + arg.direction.coordinate)
# Get the Cell/BBox that has the highest/lowest value for c.
limit = arg.func(objects, key=getter)
# Get the actual value.
return cast(float, getter(limit))
def select_adjacent_cells(d: Direction, bboxes: list[BBox], cells: Cs) -> Cs:
""" Get all Cells adjacent in d to the given reference Cells.
:param d: The Direction to check for adjacency in.
:param bboxes: The BBoxes used to check for adjacency.
:param cells: The Cells that are checked for adjacency.
:return: The Cells that are adjacent to ref_cells.
"""
bound_cls = {N: NBounds, W: WBounds, S: SBounds, E: EBounds}[d]
adjacent_cells: Cs = bound_cls.select_adjacent_cells(bboxes, cells)
normal = d.o.normal
# Remove Cells that are not overlapping with any reference Cell.
starter_id = 0
for adj_cell in adjacent_cells:
for i, bbox in enumerate(bboxes[starter_id:], starter_id):
if adj_cell.bbox.is_overlap(normal.name, bbox):
break
else:
adjacent_cells.remove(adj_cell)
break
starter_id = i
return adjacent_cells
| heijul/pdf2gtfs | src/pdf2gtfs/datastructures/table/bounds.py | bounds.py | py | 13,748 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "typing.TypeVar",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "typing.Protocol",
"line_number": 19,
"usage_type": "name"
},
{
"api_name": "typing.Iterable",
"line_number": 21,
"usage_type": "name"
},
{
"api_name": "pdf2gtfs.datastructure... |
74147866345 | import pygame, humans, sys, menu
from random import randint
scan_delay = 300
coll_delay = 300
move_delay = 300
menu.valmynd()
skra = open("settings/exit.txt", "r")
for line in skra:
if line == "True":
sys.exit()
skra.close()
settings = (open("settings/settings.txt", "r").read()).split()
fps = int(settings[2])
pygame.init()
student_list = []
for stud_num in range(200):
student_list.append(humans.student(randint(0,800), randint(0,800), randint(1,10), stud_num))
school = pygame.display.set_mode((800, 800))
school.fill((255,255,255))
while 1:#gameplay loop
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
target =randint(0,len(student_list) - 1)
school.fill((255, 255, 255))
for student in student_list:
school.blit(student.image,student.rect)
if scan_delay >= 10:
student.scan_surroundings(student_list)
if move_delay >= 10:
student.move(student.moveto(student.find_friend()))
else:
student.move(student.move_angle)
student.check_collide(student_list)
if scan_delay >= 10:
scan_delay = 0
else:
scan_delay += 1
if move_delay >= 10:
move_delay = 0
else:
move_delay += 1
if coll_delay >= 1:
coll_delay = 0
else:
coll_delay += 1
pygame.display.flip()
pygame.time.Clock().tick(fps)
| Zepeacedust/skolasim | main.py | main.py | py | 1,408 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "menu.valmynd",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "sys.exit",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "pygame.init",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "humans.student",
"line_number": ... |
4705152598 | import numpy as np
import pandas as pd
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
logger = logging.getLogger(__name__)
try:
from sklearn.base import TransformerMixin, BaseEstimator
except ImportError:
msg = "scikit-learn not installed"
logger.warning(msg)
try:
from fancyimpute import IterativeImputer, SoftImpute
except ImportError:
msg = "fancyimpute not installed"
logger.warning(msg)
class MultipleImputer(BaseEstimator, TransformerMixin):
"""
Multiple Imputation via fancyimpute.IterativeImputer.
"""
def __init__(self, multiple=5, n_iter=10, groupby=None, *args, **kwargs):
self.multiple = multiple
self.n_iter = n_iter
self.args = args
self.kwargs = kwargs
self.groupby = groupby
def transform(self, X, *args, **kwargs):
assert isinstance(X, pd.DataFrame)
df = pd.DataFrame(columns=X.columns, index=X.index)
if isinstance(self.imputers, dict):
for c, d in self.imputers.items():
mask = d["mask"]
imputers = d["impute"]
imputed_data = np.array([imp.transform(X[mask, :]) for imp in imputers])
mean = np.mean(imputed_data, axis=0)
df.loc[mask, ~pd.isnull(X[mask, :]).all(axis=0)] = mean
return df
else:
imputed_data = np.array([imp.transform(X) for imp in self.imputers])
mean = np.mean(imputed_data, axis=0)
df.loc[:, ~pd.isnull(X).all(axis=0)] = mean
return df
"""
def inverse_transform(self, Y, *args, **kwargs):
# For non-compositional data, take the mask and reverting to nan
# for compositional data, renormalisation would be needed
pass
"""
def fit(self, X, y=None):
assert isinstance(X, pd.DataFrame)
start = X
y_present = y is not None
groupby_present = self.groupby is not None
self.imputers = []
if y_present or groupby_present:
assert not (groupby_present and y_present)
if y_present:
classes = np.unique(y)
gen_mask = lambda c: y == c
if groupby_present:
classes = X[self.groupby].unique()
gen_mask = lambda c: X[self.groupby] == c
self.imputers = {
c: {
"impute": [
IterativeImputer(
n_iter=self.n_iter,
sample_posterior=True,
random_state=ix,
**self.kwargs
)
for ix in range(self.multiple)
],
"mask": gen_mask(c),
}
for c in classes
}
msg = """Imputation transformer: {} imputers x {} classes""".format(
self.multiple, len(classes)
)
logger.info(msg)
for c, d in self.imputers.items():
for imp in d["impute"]:
imp.fit(X[d["mask"], :])
else:
for ix in range(self.multiple):
self.imputers.append(
IterativeImputer(
n_iter=self.n_iter,
sample_posterior=True,
random_state=ix,
**self.kwargs
)
)
msg = """Imputation transformer: {} imputers""".format(self.multiple)
logger.info(msg)
for ix in range(self.multiple):
self.imputers[ix].fit(X)
return self
class PdSoftImputer(BaseEstimator, TransformerMixin):
"""
Multiple Imputation via fancyimpute.SoftImpute.
"""
def __init__(self, max_iters=100, groupby=None, donotimpute=[], *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.max_iters = max_iters
self.groupby = groupby
self.donotimpute = donotimpute
def transform(self, X, *args, **kwargs):
"""
Impute Missing Values
Todo
------
* Need to use masks to avoid :class:`fancyimpute.SoftImpute` returning 0. where it cannot impute.
"""
assert isinstance(X, pd.DataFrame)
df = pd.DataFrame(columns=X.columns, index=X.index) # df of nans
df.loc[:, self.donotimpute] = X.loc[:, self.donotimpute]
to_impute = [i for i in X.columns if not i in self.donotimpute]
imputable = ~pd.isnull(X.loc[:, to_impute]).all(axis=1)
if isinstance(self.imputer, dict):
for c, d in self.imputer.items():
mask = d["mask"]
mask = mask & imputable
imputer = d["impute"]
imputed_data = imputer.fit_transform(X.loc[mask, to_impute])
assert imputed_data.shape[0] == X.loc[mask, :].index.size
df.loc[mask, to_impute] = imputed_data
return df
else:
imputed_data = self.imputer.fit_transform(X.loc[imputable, to_impute])
assert imputed_data.shape[0] == X.loc[imputable, :].index.size
df.loc[imputable, to_impute] = imputed_data
return df
"""
def inverse_transform(self, Y, *args, **kwargs):
# For non-compositional data, take the mask and reverting to nan
# for compositional data, renormalisation would be needed
pass
"""
def fit(self, X, y=None):
assert isinstance(X, pd.DataFrame)
start = X
y_present = y is not None
groupby_present = self.groupby is not None
self.imputer = []
if y_present or groupby_present:
assert not (groupby_present and y_present)
if y_present:
classes = np.unique(y)
gen_mask = lambda c: y == c
if groupby_present:
classes = X[self.groupby].unique()
gen_mask = lambda c: X[self.groupby] == c
self.imputer = {
c: {
"impute": SoftImpute(max_iters=self.max_iters, **self.kwargs),
"mask": gen_mask(c),
}
for c in classes
}
msg = """Building Soft Imputation Transformers for {} classes""".format(
len(classes)
)
logger.info(msg)
else:
self.imputer = SoftImpute(max_iters=self.max_iters, **self.kwargs)
msg = """Building Soft Imputation Transformer"""
logger.info(msg)
return self
| skerryvore/pyrolite | pyrolite/util/skl/impute.py | impute.py | py | 6,714 | python | en | code | null | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "logging.NullHandler",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "logging.getLogger",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "sklearn.base.Bas... |
42037688043 | """
Signal characteristics animation
"""
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import gridspec
matplotlib.use('TkAgg')
class sigCharacterAnimation:
'''
Animation for signal characteristics
'''
# signal attributes
am1, am2 = None, None # signal amplitude, should <=1
f1, f2 = None, None # signal frequency, should >=1, multiple of 1
phase1, phase2 = None, None # signal phase, [0, 2pi)
t = None
sin1, cos1 = None, None # signal 1
sin2, cos2 = None, None # signal 2
# animation attributes
fig, axes = None, None
lines, point = None, None
frames = None
transFigure = None
def __init__(self, signal1=None, signal2=None):
if signal1 is None:
signal1 = [1, 1, 0]
if signal2 is None:
signal2 = [1, 2, np.pi / 2]
self.am1, self.am2 = signal1[0], signal2[0]
self.f1, self.f2 = signal1[1], signal2[1]
self.phase1, self.phase2 = signal1[2], signal2[2]
# generate signal
min_freq = min(self.f1, self.f2)
fs = 64 * min_freq
self.t = np.arange(0, 1 / min_freq, 1 / fs)
self.sin1 = self.am1 * np.sin(2 * np.pi * self.f1 * self.t + self.phase1)
self.cos1 = self.am1 * np.cos(2 * np.pi * self.f1 * self.t + self.phase1)
self.sin2 = self.am2 * np.sin(2 * np.pi * self.f2 * self.t + self.phase2)
self.cos2 = self.am2 * np.cos(2 * np.pi * self.f2 * self.t + self.phase2)
self.frames = len(self.t)
def start(self, save_gif=False, f_name='correlation'):
'''start animation or save as gif'''
self._init_animation()
anim = FuncAnimation(self.fig, self._animate, frames=self.frames, blit=False,
interval=100, init_func=self._init_canvas)
if save_gif:
if not os.path.exists('vis'):
os.makedirs('vis')
anim.save(os.path.join('vis', f_name + '.gif'), codec='png', writer='imagemagick')
else:
plt.show()
def _init_animation(self):
''' initialize animation'''
self.fig = plt.figure(figsize=(8, 6))
self.axes = [matplotlib.axes.Axes] * 4
gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2])
self.axes[0] = plt.subplot(gs[0, 0], aspect='equal')
self.axes[1] = plt.subplot(gs[0, 1])
self.axes[2] = plt.subplot(gs[1, 0], aspect='equal')
self.axes[3] = plt.subplot(gs[1, 1])
self.lines = [matplotlib.axes.Axes.plot] * 4
self.points = [matplotlib.axes.Axes.plot] * 4
self.connect = [matplotlib.lines.Line2D] * 2
circ1 = plt.Circle((0, 0), self.am1, fill=False, linewidth=2, color='orange')
circ2 = plt.Circle((0, 0), self.am2, fill=False, linewidth=2, color='green')
self.axes[0].add_artist(circ1)
self.axes[0].set_xlim(-1.1, 1.1)
self.axes[0].set_ylim(-1.1, 1.1)
self.axes[0].axis('off')
self.axes[1].set_xlim(-0.1, 1)
self.axes[1].set_ylim(-1.1, 1.1)
self.axes[1].axis('off')
self.axes[2].add_artist(circ2)
self.axes[2].set_xlim(-1.1, 1.1)
self.axes[2].set_ylim(-1.1, 1.1)
self.axes[2].axis('off')
self.axes[3].set_xlim(-0.1, 1)
self.axes[3].set_ylim(-1.1, 1.1)
self.axes[3].axis('off')
self.lines[0], = self.axes[0].plot([], [], linewidth=2)
self.lines[1], = self.axes[1].plot([], [], linewidth=2, color='orange')
self.lines[2], = self.axes[2].plot([], [], linewidth=2)
self.lines[3], = self.axes[3].plot([], [], linewidth=2, color='green')
self.points[0], = self.axes[0].plot([], [], 'ro', markersize=6)
self.points[1], = self.axes[1].plot([], [], 'ro', markersize=6)
self.points[2], = self.axes[2].plot([], [], 'ro', markersize=6)
self.points[3], = self.axes[3].plot([], [], 'ro', markersize=6)
self.connect[0] = matplotlib.lines.Line2D([], [], color='r', transform=self.fig.transFigure)
self.connect[1] = matplotlib.lines.Line2D([], [], color='r', transform=self.fig.transFigure)
self.fig.lines.extend(self.connect)
self.transFigure = self.fig.transFigure.inverted()
def _init_canvas(self):
'''do nothing, return artists to be re-drawn'''
return self.lines + self.points + self.connect
def _animate(self, i):
'''perform animation step'''
# update artists
self.lines[0].set_data([0, self.cos1[-i]], [0, self.sin1[-i]])
self.lines[1].set_data(self.t, np.roll(self.sin1, i))
self.lines[2].set_data([0, self.cos2[-i]], [0, self.sin2[-i]])
self.lines[3].set_data(self.t, np.roll(self.sin2, i))
self.points[0].set_data([self.cos1[-i]], [self.sin1[-i]])
self.points[1].set_data([0], [self.sin1[-i]])
self.points[2].set_data([self.cos2[-i]], [self.sin2[-i]])
self.points[3].set_data([0], [self.sin2[-i]])
coord1 = self.transFigure.transform(self.axes[0].transData.transform([self.cos1[-i], self.sin1[-i]]))
coord2 = self.transFigure.transform(self.axes[1].transData.transform([0, self.sin1[-i]]))
self.connect[0].set_data((coord1[0], coord2[0]), (coord1[1], coord2[1]))
coord1 = self.transFigure.transform(self.axes[2].transData.transform([self.cos2[-i], self.sin2[-i]]))
coord2 = self.transFigure.transform(self.axes[3].transData.transform([0, self.sin2[-i]]))
self.connect[1].set_data((coord1[0], coord2[0]), (coord1[1], coord2[1]))
return self.lines + self.points + self.connect
if __name__ == '__main__':
save_fig = True
# amplitude
# anim = sigCharacterAnimation(signal1=[1, 1, 0], signal2=[0.5, 1, 0])
# anim.start(save_gif=save_fig, f_name='sig_char_amplitude')
# # frequency
# anim = sigCharacterAnimation(signal1=[1, 1, 0], signal2=[1, 2, 0])
# anim.start(save_gif=save_fig, f_name='sig_char_frequency')
# phase
anim = sigCharacterAnimation(signal1=[1, 1, 0], signal2=[1, 1, np.pi / 2])
anim.start(save_gif=save_fig, f_name='sig_char_phase')
| PenroseWang/SimGPS | code/utils/signal_characteristic.py | signal_characteristic.py | py | 6,216 | python | en | code | 11 | github-code | 36 | [
{
"api_name": "matplotlib.use",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "numpy.pi",
"line_number": 35,
"usage_type": "attribute"
},
{
"api_name": "numpy.arange",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "numpy.sin",
"line_numbe... |
15000533019 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 15:36:15 2018
@author: chrelli
added unix time stamps to the first camera!
Ways to slim down the data:
no unix time stamps?
no color frame showing? - yes, helps a lot!
no png compression? Totally fine at 30 fps!
Majow to do list:
- use arduino to synchronize? Yes, could send out synchronization time code to another unit: Problem: doesn't account for delay of arriving frames
- use depth roi to slim down writing footprint
- use LED roi to get blinking time stamps
-
## with connected device cam
from pyrealsense import offline
offline.save_depth_intrinsics(dev)
"""
#%% Import the nescessary stuff
# basic OS stuff
import time, os, sys, shutil
import json
# for math and plotting
import pandas as pd
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
# small utilities
import csv
from colour import Color
from itertools import compress # for list selection with logical
from tqdm import tqdm
# for image manipulation
import cv2
# for recording and connecting to the intel realsense librar
#import pyrealsense as pyrs
# add the realsense library
sys.path.append(r'/usr/local/lib')
# and load it!
import pyrealsense2 as rs
#import multiprocessing
from multiprocessing import Process
# import handy Functions
from utils.common_utils import *
from utils.recording_utils import *
#%% Parse some inputs
import argparse
parser = argparse.ArgumentParser(description='Records cad and d images with no roi cut to disk. Also records timestamps and led traces using the auto LED mask. Currently, with no ROI, the program maxes out disk write speed around 45 fps.',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--ncams', type=int, default = 4 , choices=[1,2,3,4],
help='number of cameras to stream')
parser.add_argument('--fps',type=int, default = 30 , choices=[30,60],
help='select fps to stream')
#parser.add_argument("--singlecore", help="disables mult.proc. for debugging on macbook, overrides ncams to 1",
# action="store_true")
parser.add_argument("--plots", help="shows the live video while recording",
action="store_true")
args = parser.parse_args()
#%% Constants
# frame_width,frame_height = 848,480
frame_width,frame_height = 640,480
fps_choice = args.fps
# number of padding digits for the frame numbers
n_padding_digits = 8
print('# cameras: '+str(args.ncams))
print('Frame size is '+str(frame_width)+'x'+str(frame_height)+' pixels.')
print('Grabbing frames at '+str(fps_choice)+' fps')
# get the current timestring
timestr = time.strftime("%Y%m%d-%H%M%S")
# reset the folder
#data_folder = '/media/chrelli/Data0'
#top_folder = data_folder + '/calibration_' + timestr
#reset_folder_if_present(top_folder)
#
#top_folder_0 = top_folder
#top_folder_1 = top_folder
# reset the folders
top_folder_0 = '/media/chrelli/Data0' + '/calibration_' + timestr
top_folder_1 = '/media/chrelli/Data1' + '/calibration_' + timestr
reset_folder_if_present(top_folder_0)
reset_folder_if_present(top_folder_1)
# also make the numpy folders
npy_folder_0 = top_folder_0+'/npy_raw'
npy_folder_1 = top_folder_1+'/npy_raw'
reset_folder_if_present(npy_folder_0)
reset_folder_if_present(npy_folder_1)
#%% 8 bit color setup
fps_color = (Color('White').rgb)
ts_color = (Color('Peru').rgb)
# convert to 8 bit color
fps_color=tuple(255*x for x in fps_color)
ts_color=tuple(255*x for x in ts_color)
#%% Block for running
# open the pyrealsense server
#serv = pyrs.Service()
# set the start time for the unix time stamp
start_time = time.time()
# open up a realsense context and get a list of the devices!
ctx = rs.context()
devices = [ctx.devices[i] for i in range(args.ncams)]
# sort the devices by their serial numbers
serials = [devices[i].get_info(rs.camera_info.serial_number) for i in range(args.ncams)]
devices = [x for _,x in sorted(zip(serials,devices))]
def sub_function_trick(which_device,top_folder):
show_frames = args.plots
####################
#
# DEVICE SETUP BLOCK
#
#####################
# get the serial of that device
device = devices[which_device]
device_serial = device.get_info(rs.camera_info.serial_number)
#set the preset
advnc_mode = rs.rs400_advanced_mode(device)
print("Advanced mode is", "enabled" if advnc_mode.is_enabled() else "disabled")
# run like
# advnc_mode.load_json(json_string)
# load the preset here!
preset_folder = '/home/chrelli/git/3d_sandbox/mycetrack0p8/presets/'
if device_serial[:3] == '740':
preset_name = 'master60pp'
else:
preset_name = 'slave60pp'
jsonFile = preset_folder+preset_name+'.json'
jsonObj = json.load(open(jsonFile))
json_string = str(jsonObj).replace("'", '\"')
print("Configuration " + jsonFile + " loaded");
time.sleep(1.)
advnc_mode.load_json(json_string)
print("Configuration " + jsonFile + " applied!");
if device_serial[:3] == '740':
# master
targetSyncMode = 1
else:
# slave
targetSyncMode = 2
device.first_depth_sensor().set_option(rs.option.inter_cam_sync_mode, targetSyncMode)
# first, open up a config
config = rs.config()
# then open a pipeline
pipeline = rs.pipeline()
# enable the selected device and streams # RGB SPACE HERE
config.enable_device(device_serial);
config.enable_stream(rs.stream.depth, frame_width,frame_height, rs.format.z16, fps_choice)
# config.enable_stream(rs.stream.color, frame_width,frame_height, rs.format.rgb8, fps_choice)
config.enable_stream(rs.stream.color, frame_width,frame_height, rs.format.rgb8, fps_choice)
config.enable_stream(rs.stream.infrared,1, frame_width,frame_height, rs.format.y8, fps_choice)
print("PING after enabling the sync mode is {}".format(device.first_depth_sensor().get_option(rs.option.inter_cam_sync_mode)))
# Start streaming, call the stream 'cfg' for some reason, as pr example
cfg = pipeline.start(config)
# create an align object
# alternative is to align to color, faster but less precise: align_to = rs.stream.color
align_to = rs.stream.depth
align = rs.align(align_to)
print('dev '+str(which_device)+' serial is ' + device_serial)
# Use the first three digits of the serial as a string to tag the device:
device_tag = device_serial[0:3]
if show_frames:
# open a window for cv2
window_title = "dev"+str(which_device)+"(#" + device_tag + ")"
cv2.namedWindow(window_title+'cad')
# block for setting up a low-level fps estimation,
cnt = 0 # a counter
last = time.time() # start_time
fps = 0 # initial fps value
# save the camera intrinsics
# Getting the depth sensor's depth scale (see rs-align example for explanation)
depth_sensor = cfg.get_device().first_depth_sensor()
depth_scale = depth_sensor.get_depth_scale()
print ("Depth Scale is: " , depth_scale)
# this is how to get the intrinsics
profile = cfg.get_stream(rs.stream.depth) # Fetch stream profile for depth stream
intr = profile.as_video_stream_profile().get_intrinsics() # Downcast to video_stream_profile
#% now make file and save time stamps and depth scaling and intrinsics etc
# use the old naming convention
parameternames = np.array(['cam_params.fx',
'cam_params.fy',
'cam_params.ppx',
'cam_params.ppy',
'd_scale',
'fps_choice',
'frame_width',
'frame_height'])
parameters = np.array([intr.fx,
intr.fy,
intr.ppx,
intr.ppy,
depth_scale,
fps_choice,
intr.width,
intr.height])
# open a file for writint the parameters
with open(top_folder+'/parameters_'+str(which_device)+'.csv','w') as intrfile:
writer = csv.writer(intrfile, delimiter=',')
writer.writerow(parameternames)
writer.writerow(parameters)
# load the automatic led mask from the constants folder!
led_mask,led_logic,led_centroid = load_auto_roi(which_device)
# open a file for time stamps
tsfile = open(top_folder+'/timestamps_'+str(which_device)+'.csv','w')
# ## HF try to open an HF file
# import h5py
# #TODO input from somewhere
# hf = h5py.File(top_folder+'/dev'+str(which_device)+'_d_'+'.h5', 'w')
# # also open one for the cad
# hf_cad = h5py.File(top_folder+'/dev'+str(which_device)+'_cad_'+'.h5', 'w')
# NPY ADDITION
npy_folder = top_folder+'/npy_raw'
# open a file for led stamps
# ledsfile = open(top_folder+'/ledstamps_'+str(which_device)+'.csv','w')
print('starting to stream from device '+str(which_device)+'!')
# wait for a bit for the cam to warm up
# and loop over 30 frames
warmup_time = 2 # seconds
warmup = 0
while warmup < fps_choice*warmup_time:
frames = pipeline.wait_for_frames()
warmup += 1
print('device '+str(which_device)+' is warmed up!')
# START A CLOCK FOR THE FRAMES!
FRAME_CLOCK = 0
try:
while True:
if show_frames:
# for counting frame rate
cnt += 1
if (cnt % 10) == 0:
now = time.time() # after 10 frames
dt = now - last # how long did it take?
fps = 10/dt # calculate frame rate
last = now # assign a new value to the 'last time'
#################################
#
# R E A D B L O C K
#
#################################
# Wait for a coherent pair of frames: depth and color
frames = pipeline.wait_for_frames()
# get the frame numbers and time stamps
# ts = round(frames.get,2)
ts = frames.get_timestamp()
fn = frames.get_frame_number()
# get the unix time stamp
ts_unix = time.time()-start_time
# run the alignment process
aligned_frames = align.process(frames)
depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image
cad_frame = aligned_frames.get_color_frame()
# also get one for the LED
# depth_frame = frames.get_depth_frame()
# color_frame = frames.get_color_frame()
infrared_frame = frames.get_infrared_frame()
# Convert images to numpy arrays
depth = np.asanyarray(depth_frame.get_data())
cad = np.asanyarray(cad_frame.get_data())
c = np.asanyarray(infrared_frame.get_data())
# get the LED value, round it a bit, could be profiled
led_stamp = c[led_centroid[1],led_centroid[0]]
# this is the writing block for the csv file, frame number and time stamp!
# tsfile.write(str(FRAME_CLOCK)+','+str(fn)+','+str(ts)+','+str(ts_unix)+','+str(single_pixel_RGB2GRAY(led_stamp))+'\n')
tsfile.write(str(FRAME_CLOCK)+','+str(fn)+','+str(ts)+','+str(ts_unix)+','+str(led_stamp)+'\n')
# this is the writing block for the csv file, frame number and time stamp!
#TODO put led with the others in same file?
# ledsfile.write(str(single_pixel_RGB2GRAY(led_stamp))+'\n')
# write the depth frames to tiff (replace: send to queue)
# cv2.imwrite(top_folder+'/dev'+str(which_device)+'_d_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.png', depth)
# cv2.imwrite(top_folder+'/dev'+str(which_device)+'_cad_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.png', cad)
# hf.create_dataset(str(FRAME_CLOCK), data=depth)
# hf_cad.create_dataset(str(FRAME_CLOCK), data=cad)
np.save(npy_folder+'/dev'+str(which_device)+'_d_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.npy',depth, allow_pickle = False)
np.save(npy_folder+'/dev'+str(which_device)+'_cad_'+str(FRAME_CLOCK).rjust(n_padding_digits,'0')+'.npy',cad, allow_pickle = False)
# UPDATE CLOCK
FRAME_CLOCK += 1
#
if show_frames:
# add text and show the CAD frames
cv2.putText(cad, window_title+', fps: '+str(fps)[:4], (0, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, fps_color)
cv2.putText(cad, str(round(ts)), (0, frame_height-20), cv2.FONT_HERSHEY_SIMPLEX, 1, ts_color)
cv2.imshow(window_title+'cad', cad)
if cv2.waitKey(1) & 0xFF == ord('q'):
# looks for a small q to nbe pressed
# close the time stamp file
tsfile.close
# close the hf file
# hf.close()
# hf_cad.close()
# ledsfile.close
# stop the device
pipeline.stop()
print('pipeline from device '+str(which_device)+' is now closed!')
break
finally:
tsfile.close
# close the hf file
# hf.close()
# hf_cad.close()
# stop the device
pipeline.stop()
print('pipeline from device '+str(which_device)+' is now closed!')
#%% define helping funtions for the multiprocessing
# these functions have to not be iterable.
def read_device_0():
print('starting camera 1!')
which_device = 0
top_folder = top_folder_0
sub_function_trick(which_device,top_folder)
def read_device_1():
print('starting camera 2!')
which_device = 1
top_folder = top_folder_0
sub_function_trick(which_device,top_folder)
def read_device_2():
print('starting camera 3!')
which_device = 2
top_folder = top_folder_1
sub_function_trick(which_device,top_folder)
def read_device_3():
print('starting camera 4!')
which_device = 3
top_folder = top_folder_1
sub_function_trick(which_device,top_folder)
#%% run the processes on independent cores
from multiprocessing import Process
if __name__ == '__main__':
if args.ncams == 4:
print('starting 4 cams, with multiprocessing!')
# start 4 worker processes
Process(target=read_device_0).start()
time.sleep(3.)
Process(target=read_device_1).start()
Process(target=read_device_2).start()
Process(target=read_device_3).start()
Process(target=blink_using_firmata_random).start()
elif args.ncams == 3:
print('starting 3 cams, with multiprocessing!')
Process(target=read_device_0).start()
Process(target=read_device_1).start()
Process(target=read_device_2).start()
Process(target=blink_using_firmata).start()
elif args.ncams == 2:
print('starting 2 cams, with multiprocessing!')
Process(target=read_device_0).start()
Process(target=read_device_1).start()
Process(target=blink_using_firmata).start()
elif args.ncams == 1:
print('starting 1 cam, with multiprocessing!')
Process(target=read_device_0).start()
Process(target=blink_using_firmata).start()
| chrelli/3DDD_social_mouse_tracker | recording/record_calib_npy.py | record_calib_npy.py | py | 15,418 | python | en | code | 5 | github-code | 36 | [
{
"api_name": "sys.path.append",
"line_number": 50,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 50,
"usage_type": "attribute"
},
{
"api_name": "argparse.ArgumentParser",
"line_number": 68,
"usage_type": "call"
},
{
"api_name": "argparse.Argume... |
11952114818 | from datetime import datetime
import backtrader as bt
import tushare as ts
import pandas as pd
class MyStrategy1(bt.Strategy):
params = (('maperiod', 20),
('printlog', False),)
def __init__(self):
# 指定价格序列
self.dataclose = self.datas[0].close
# 初始化交易指令、买卖价格和手续费
self.order = None
self.buyprice = None
self.buycomm = None
self.process = []
# 添加移动均线指标
self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)
# 策略核心,根据条件执行买卖交易指令(必选)
def next(self):
# 记录收盘价
# self.log(f'收盘价, {dataclose[0]}')
if self.order: # 检查是否有指令等待执行,
return
# 检查是否持仓
if not self.position: # 没有持仓
# 执行买入条件判断:收盘价格上涨突破15日均线
if self.dataclose[0] > self.sma[0]:
self.log('BUY CREATE, %.2f' % self.dataclose[0])
# 执行买入
self.order = self.buy()
else:
# 执行卖出条件判断:收盘价格跌破15日均线
if self.dataclose[0] < self.sma[0]:
self.log('SELL CREATE, %.2f' % self.dataclose[0])
# 执行卖出
self.order = self.sell()
# 交易记录日志(可省略,默认不输出结果)
def log(self, txt, dt=None, doprint=False):
if self.params.printlog or doprint:
dt = dt or self.datas[0].datetime.date(0)
print(f'{dt.isoformat()},{txt}')
self.process.append(dt.isoformat())
self.process.append(txt)
self.process.append('\n')
# 记录交易执行情况(可省略,默认不输出结果)
def notify_order(self, order):
# 如果order为submitted/accepted,返回空
if order.status in [order.Submitted, order.Accepted]:
return
# 如果order为buy/sell executed,报告价格结果
if order.status in [order.Completed]:
if order.isbuy():
self.log(f'买入:\n价格:{order.executed.price},成本:{order.executed.value},手续费:{order.executed.comm}')
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else:
self.log(f'卖出:\n价格:{order.executed.price},\
成本: {order.executed.value},\
手续费{order.executed.comm}')
self.bar_executed = len(self)
# 如果指令取消/交易失败, 报告结果
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('交易失败')
self.order = None
# 记录交易收益情况(可省略,默认不输出结果)
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log(f'策略收益:\n毛收益:{trade.pnl:.2f}, 净收益:{trade.pnlcomm:.2f}')
# 回测结束后输出结果(可省略,默认输出结果)
def stop(self):
self.log('(MA均线: %2d日) 期末总资金 %.2f' % (self.params.maperiod, self.broker.getvalue()), doprint=True)
f = open("./static/logs.log", "w")
f.writelines(self.process)
f.close()
def back(stock_code, startcash):
# 初始化cerebro回测系统设置
cerebro = bt.Cerebro()
# 获取数据
# start = input('输入回测起始时间(xx-xx-xx):')
start = '2018-01-01'
# end = input('输入回测结束时间(xx-xx-xx):')
end = '2021-06-01'
start1 = datetime.strptime(start, "%Y-%m-%d")
end1 = datetime.strptime(end, "%Y-%m-%d")
df = ts.get_k_data(stock_code, autype='qfq', start=start, end=end)
# df=ts.get_k_data('600000',autype='qfq',start='2018-01-01',end='2021-03-30')
df.index = pd.to_datetime(df.date)
df = df[['open', 'high', 'low', 'close', 'volume']]
data = bt.feeds.PandasData(dataname=df, fromdate=start1, todate=end1)
# data = bt.feeds.PandasData(dataname=df,fromdate=datetime(2018, 1, 1),todate=datetime(2021, 3, 30))
# 加载数据
cerebro.adddata(data)
# 将交易策略加载到回测系统中
# 设置printlog=True,表示打印交易日志log
cerebro.addstrategy(MyStrategy1, maperiod=20, printlog=True)
# 设置初始资本
cerebro.broker.setcash(startcash)
# 设置交易手续费为 0.1%
cerebro.broker.setcommission(commission=0.001)
# 设置买入设置、策略、数量
cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
# 回测结果
cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='_AnnualReturn')
cerebro.addanalyzer(bt.analyzers.Calmar, _name='_Calmar')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='_DrawDown')
# cerebro.addanalyzer(bt.analyzers.TimeDrawDown, _name='_TimeDrawDown')
cerebro.addanalyzer(bt.analyzers.GrossLeverage, _name='_GrossLeverage')
cerebro.addanalyzer(bt.analyzers.PositionsValue, _name='_PositionsValue')
cerebro.addanalyzer(bt.analyzers.LogReturnsRolling, _name='_LogReturnsRolling')
cerebro.addanalyzer(bt.analyzers.PeriodStats, _name='_PeriodStats')
cerebro.addanalyzer(bt.analyzers.Returns, _name='_Returns')
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='_SharpeRatio')
# cerebro.addanalyzer(bt.analyzers.SharpeRatio_A, _name='_SharpeRatio_A')
cerebro.addanalyzer(bt.analyzers.SQN, _name='_SQN')
cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='_TimeReturn')
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='_TradeAnalyzer')
cerebro.addanalyzer(bt.analyzers.Transactions, _name='_Transactions')
cerebro.addanalyzer(bt.analyzers.VWR, _name='_VWR')
results = cerebro.run()
# 获取最后总资金
print(results)
print('eeeeeeeeeeeee')
portvalue = cerebro.broker.getvalue()
fpnl = portvalue - startcash
performance_dict = {}
calmar_ratio = list(results[0].analyzers._Calmar.get_analysis().values())[-1]
drawdown_info = results[0].analyzers._DrawDown.get_analysis()
average_drawdown_len = drawdown_info['len']
average_drawdown_rate = drawdown_info['drawdown']
average_drawdown_money = drawdown_info['moneydown']
max_drawdown_len = drawdown_info['max']['len']
max_drawdown_rate = drawdown_info['max']['drawdown']
max_drawdown_money = drawdown_info['max']['moneydown']
PeriodStats_info = results[0].analyzers._PeriodStats.get_analysis()
average_rate = PeriodStats_info['average']
stddev_rate = PeriodStats_info['stddev']
positive_year = PeriodStats_info['positive']
negative_year = PeriodStats_info['negative']
nochange_year = PeriodStats_info['nochange']
best_year = PeriodStats_info['best']
worst_year = PeriodStats_info['worst']
SQN_info = results[0].analyzers._SQN.get_analysis()
sqn_ratio = SQN_info['sqn']
VWR_info = results[0].analyzers._VWR.get_analysis()
vwr_ratio = VWR_info['vwr']
sharpe_info = results[0].analyzers._SharpeRatio.get_analysis()
sharpe_ratio = sharpe_info['sharperatio']
performance_dict['calmar_ratio'] = calmar_ratio
performance_dict['average_drawdown_len'] = average_drawdown_len
performance_dict['average_drawdown_rate'] = average_drawdown_rate
performance_dict['average_drawdown_money'] = average_drawdown_money
performance_dict['max_drawdown_len'] = max_drawdown_len
performance_dict['max_drawdown_rate'] = max_drawdown_rate
performance_dict['max_drawdown_money'] = max_drawdown_money
performance_dict['average_rate'] = average_rate
performance_dict['stddev_rate'] = stddev_rate
performance_dict['positive_year'] = positive_year
performance_dict['negative_year'] = negative_year
performance_dict['nochange_year'] = nochange_year
performance_dict['best_year'] = best_year
performance_dict['worst_year'] = worst_year
performance_dict['sqn_ratio'] = sqn_ratio
performance_dict['vwr_ratio'] = vwr_ratio
performance_dict['sharpe_info'] = sharpe_ratio
performance = pd.DataFrame(performance_dict, index=[0]).T
print(performance)
# Print out the final result
print(f'\n总资金: {portvalue:.2f}')
print(f'净收益: {round(fpnl, 2)}')
ans = {}
ans['all'] = int(portvalue)
ans['jing'] = int(fpnl)
# cerebro.plot(style='candlestick')
return ans
if __name__ == '__main__':
stock_code = input('输入回测股票代码:')
startcash = float(input('输入回测初始资本:'))
back(stock_code, startcash)
| Cui-Yusong/NUS_proj | backtest_sma.py | backtest_sma.py | py | 8,940 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "backtrader.Strategy",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "backtrader.indicators.SimpleMovingAverage",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "backtrader.indicators",
"line_number": 20,
"usage_type": "attribute"
... |
74434198503 | import json #to impost post.json
from blog.models import Post
# instance of opening and loading json data
with open('post.json') as f:
posts_json = json.load(f)
# Loop through JSON data
for post in posts_json:
"""
input:
title: the title of the json element
content: the cotent of the json element
author_id: the user number of the json element, which is used as the
ForeignKey to connect the blog site to the User database.
Still trying to verify, but SQL convention is that the blog primary
key would author and the foreign key should be author_id.
output:
After interation, it will post the JSON elements as new posts in blog
"""
post = Post(title=post['title'],
content=post['content'],
author_id = post['user_id'])
post.save()
| YusufBritton1990/Django_tutorial_backup | django_project/shell_posting.py | shell_posting.py | py | 837 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "json.load",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "blog.models.Post",
"line_number": 23,
"usage_type": "call"
}
] |
1923472018 | #!/usr/bin/env python
#coding=utf-8
import json
from lib.sqs import zhihufav_sqs
from lib.tasks import add_note
def get_sqs_queue():
sqs_info = zhihufav_sqs.get_messages(10)
for sqs in sqs_info:
sqs_body = sqs.get_body()
receipt_handle = sqs.receipt_handle
sqs_json = json.loads(sqs_body)
api_url = sqs_json.get('api_url')
parent_note = sqs_json.get('parent_note')
add_note.delay(api_url, parent_note, receipt_handle)
if __name__=="__main__":
for i in range(5):
get_sqs_queue()
| youqingkui/zhihufav | do_tasks.py | do_tasks.py | py | 553 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "lib.sqs.zhihufav_sqs.get_messages",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "lib.sqs.zhihufav_sqs",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "json.loads",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "lib... |
11342229951 | import io
import os
import random
from PIL import Image
import imageio
import requests
import seventv
def get_response(message: str):
p_message = message.lower()
if p_message[:3] == ("add"):
url = p_message.split(" ")[1]
return addGif(url)
if p_message == "help":
return helpText()
return 'I didn\'t understand what you wrote. Try typing "help".'
def helpText():
return "`?add <7tv url> to add a 7tv emoji to your server`"
def addGif(url):
webpUrl = seventv.get_webp_url(url)
try:
webp_data = requests.get(webpUrl).content
except requests.exceptions.RequestException:
return "Invalid URL"
# Extract the name from the url and replace .webp extension with .gif
gif_name = seventv.get_emote_name(url)
# Open webp image with PIL
image = Image.open(io.BytesIO(webp_data))
# If image is an animated webp, PIL will open it as a sequence of frames
frames = []
try:
while True:
frames.append(image.copy())
image.seek(len(frames)) # Skip to next frame
except EOFError:
pass # We have read all the frames from the image now
# Create a byte buffer and save the gif data into it
gif_data_buffer = io.BytesIO()
# Set the duration of each frame based on the original image's frame rate
duration_per_frame = image.info.get(
"duration", 100
) # Default to 100ms if no duration is set
imageio.mimwrite(
gif_data_buffer, frames, "GIF", duration=duration_per_frame, loop=0
)
# Get the gif data as bytes
gif_data = gif_data_buffer.getvalue()
return gif_data, gif_name
| JimenezJC/discord-7tv-emoji-app | responses.py | responses.py | py | 1,667 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "seventv.get_webp_url",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "requests.exceptions",
"line_number": 31,
"usage_type": "attribute"
},
{
"api_name": "seventv.ge... |
18391614264 | import requests
from bs4 import BeautifulSoup
import wikipedia
class unotes:
def __init__(self,*args):
self.data_list = [a.replace(' ','_')for a in args]
self.content = {}
self.links = {}
def __str__(self):
return f"unotes for {self.data_list}"
def search(self):
contents = []
wiki_content = []
sub_results = []
data = self.data_list
for i in range(len(data)):
searches = wikipedia.search(data[i])
# print(searches)
try:
main_result = wikipedia.summary(searches[0],auto_suggest=False)
except:
main_result = f"Some errors. Please consider changing the parameters for {data[i]}. :) "
self.content[f'{data[i]}'] = main_result
req = requests.get(f"https://www.google.com/search?q={str(data[i].replace('_','+'))}")
content = BeautifulSoup(req.text,features='html.parser')
x = content.find_all('a')
links = []
for j in x:
link = j.attrs['href']
if 'url' in link.split("?")[0]:
url_ = link.split("?")[1].split("&")[0].split("=")[1]
if "%" not in url_:
links.append(url_)
self.links[data[i]] = links
temp_ = {'name':f'{data[i]}','content':str(main_result),'links':links}
contents.append(temp_)
return contents
def save(self,file_name,data_obj):
html_upper = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>Unotes</title>
<style>
.left-cont{
border-radius: 15px;
display: block;
float: left;
margin: 25px 10px;
box-shadow: 15px 15px 20px 5px rgb(212, 233, 231);
padding: 15px;
}
.navbar{
height: 45px;
background-color: rgb(79, 210, 210);
border: 1px solid blue;
text-align: center;
}
.nav-text{
align-self: center;
margin: 14px 5px;
font-weight: bold;
font-family: 'Courier New', Courier, monospace;
color: white;
}
.show-text{
cursor: pointer;
font-weight:700;
border:1px solid black;
padding:3px;
background-color:skyblue;
}
#links_show{
display: none;
}
h3{
text-align:center;
}
</style>
</head>
<body>
<div class="navbar">
<div class="nav-text">U-notes</div>
</div>
"""
html_lower = f"</body></html>"
file = open(f'{str(file_name)}','w+',encoding='utf-8')
file.write(str(html_upper))
for i in data_obj:
name = i['name']
content = i['content']
links = i['links']
show_function_ = f"<script>function show_{name}(){'{'} {'if'} (document.getElementById('links_show{name}').style.display == 'none') {'{'} document.getElementById('links_show{name}').style.display = 'block';{'}'}else{'{'}document.getElementById('links_show{name}').style.display = 'none';{'}}'}</script>"
content_ = f"<h3>{name}</h3><p>{content}</p><hr><div class='more'><button type='button' class='show-text' onclick='show_{name}();'>See links ^_^</button><div class='more-links' style='display:none;' id='links_show{name}' >"
file.write(str(show_function_))
file.write(str(content_))
for link in links:
link_ = f"<div class='link'><a href='{link}' target='_blank'>{link}</a></div>"
file.write(str(link_))
content_end = "</div>"
file.write(str(content_end))
file.write(str(html_lower))
file.close()
def main():
note = unotes('param1','param2')
chapters = note.search()
note.save('file_name.html',chapters)
if __name__=='__main__':
main() | UtsabKafle/unotes | src/unotes.py | unotes.py | py | 4,021 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "wikipedia.search",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "wikipedia.summary",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "bs4.BeautifulSoup",
... |
19250130553 | import http
import requests
import tenacity
from bs4 import BeautifulSoup
from tenacity import retry_if_exception_type, stop_after_attempt
from .exceptions import BadRequest, NetworkError, NotClientError, NotFound, ServerError
from .utils import cache
@tenacity.retry(
reraise=True,
retry=retry_if_exception_type(NotClientError),
stop=stop_after_attempt(5),
)
@cache(ttl=1)
def get_weather_for_city(city: str) -> str:
"""
Returns temperature of the city in celsius,
as the source 'https://world-weather.ru' was used
"""
url = f'https://world-weather.ru/pogoda/russia/{city}'
page_text = None
try:
response = requests.get(url)
response.raise_for_status()
page_text = response.text
except requests.exceptions.HTTPError as err:
err_status = err.response.status_code
if err_status == http.HTTPStatus.BAD_REQUEST:
raise BadRequest() from None
if err_status == http.HTTPStatus.NOT_FOUND:
raise NotFound() from None
if err_status == http.HTTPStatus.INTERNAL_SERVER_ERROR:
raise ServerError from None
except requests.exceptions.ConnectionError:
raise NetworkError from None
soup = BeautifulSoup(page_text, 'html.parser')
return soup.find('div', id='weather-now-number').text
| macoyshev/weather_CLI | weather/weather_parser.py | weather_parser.py | py | 1,336 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "requests.get",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "requests.exceptions",
"line_number": 32,
"usage_type": "attribute"
},
{
"api_name": "http.HTTPStatus",
"line_number": 35,
"usage_type": "attribute"
},
{
"api_name": "exceptions... |
72718761064 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Created on Fri Mar 10 12:54:45 2023
"""
import numpy as np
from pyGITR.math_helper import *
from typing import Callable
import matplotlib.pyplot as plt
import pydoc
import netCDF4
import os
def Gaussian(x: np.ndarray = np.linspace(-15000, 15000, 100000), sigma: float = 5.0, mu: float = 120.0, beta: float = 1.0, Normalized=True):
f = (1/(sigma*np.sqrt(2*np.pi)))*np.exp(-((x-mu)/sigma)**2)
f[np.argwhere(x<0)] = 0
if Normalized:
f = f/Integrale(f, x, Array=False)
return f
def Gaussian_test(x: np.ndarray = np.linspace(-15000, 15000, 100000), sigma: float = 20.0, mu: float = 130.0, beta: float = 1.0, Normalized=True):
f = (1/(sigma*np.sqrt(2*np.pi)))*np.exp(-((x-mu)/sigma)**2)
f[np.argwhere(x<0)] = 0
# if Normalized:
# f = f/Integrale(f, x, Array=False)
return f
def Gaussian_Jerome(x: np.ndarray = np.linspace(-15000, 15000, 100000), sigma: float = 5.0, mu: float = 120, beta: float = 0.0, Normalized=True):
f = np.abs(x)**beta*np.exp(-1.0/2.0*((x-mu)/sigma)**2)
if beta > 0:
f[np.argwhere(x<0)] = 0
if Normalized:
f = f/Integrale(f, x, Array=False)
return f
def Thomson(x: np.ndarray = np.linspace(0, 300, 10000), xb: float = 8.64, xc: float = 100, Normalized=True):
assert not (xc <= xb), "xc cannot be <= xb"
f = x/(x + xb) ** 3*(1.0-np.sqrt((x+xb)/(xc+xb)))
f[np.argwhere(x > xc)] = 0.0
# if Normalized:
# f = f/Integrale(f, x, Array=False)
return f
def Levy(x=np.linspace(0.1,10,10000), c=1, mu=0):
return np.sqrt(c/2/np.pi)*np.exp(-c/(x-mu))/((x-mu)**1.5)
x = np.linspace(1, 200, 5005)
pdf_p = Gaussian_Jerome(x)
pdf_q = Gaussian_test(x)
pdf_p_times_q = np.multiply(pdf_p,pdf_q)
#Normalization = 1.0
Normalization = Integrale(pdf_p_times_q, x, Array=False)
#Normalization = 1.0
pdf_p_times_q = np.divide(pdf_p_times_q,Normalization)
pdf_p_times_q_divide_q = np.divide(pdf_p_times_q,pdf_q)
#Normalization = Integrale(pdf_p_times_q_divide_q, x, Array=False)
#Normalization = 1.0
#print(Normalization)
pdf_p_times_q_divide_q = np.divide(pdf_p_times_q_divide_q,Normalization)
# #print(pdf_q)
plt.figure()
plt.plot(x,pdf_p,label="p distribution")
plt.plot(x,pdf_q,label="q distribution")
#plt.plot(x,pdf_p_times_q,label="multiplied distribution")
#plt.plot(x,Integrale(np.multiply(pdf_p,1.0), x, Array=True),label="cumulative of p times q")
#plt.plot(x,pdf_p_times_q_divide_q,label="multiplied distribution")
plt.xlim(100,150)
plt.legend()
plt.show()
# Gaussian(np.array([x]))
# Gaussian_Jerome(np.array([x]))
| audide12/DIIIDsurface_pyGITR | pyGITR/importance_sampling_1.py | importance_sampling_1.py | py | 2,626 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "numpy.ndarray",
"line_number": 13,
"usage_type": "attribute"
},
{
"api_name": "numpy.linspace",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "numpy.sqrt",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "numpy.pi",
"line_num... |
28981514805 | from django.conf.urls import patterns, url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'sokoban.views',
url(r'^$', 'index', name='index'),
url(r'^dashboard/$', 'dashboard', name='dashboard'),
url(r'^home/$', 'home', name='home'),
url(r'^403/$', 'alert_login_required', name='login_required'),
url(r'^(?P<owner>.+)/projects/', 'list_projects', name='project_list'),
url(r'^project/(?P<name>.*)/(?P<action>.*)/$', 'rest_project',
name='project_rest'),
url(r'^project/(?P<name>.*)/$', 'rest_project', name='project_rest'),
url(r'^middleware/$', 'installed_middle_ware', name="middle_ware_list"),
url(r'^log/(?P<project_name>.+)/$', 'get_log', name="get_log"),
url(r'^logs/$', 'get_log', name="get_logs", kwargs={'project_name': None}),
url(r'^admin/', include(admin.site.urls)),
url('^accounts/', include('account.urls')),
url('^scheduler/', include('scheduler.urls')),
)
| BusyJay/sokoban | src/sokoban/urls.py | urls.py | py | 978 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "django.contrib.admin.autodiscover",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "django.contrib.admin",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "django.conf.urls.patterns",
"line_number": 6,
"usage_type": "call"
},
{
"api... |
26613636857 | import numpy as np
import cv2
from imgutil import read_img
from scipy.optimize import minimize
from mathutil import Rx, Ry, Rz
in_size = (1080//2, 1920//2)
fov_factor = 1
marks = [
(1, 2, [((925, 1080//2 - 338), (1131 - 1920//2, 1080//2 - 383)),
((946, 1080//2 - 321), (1156 - 1920//2, 1080//2 - 375)),
((834, 1080//2 - 390), (1036 - 1920//2, 1080//2 - 398)),
((952, 1080//2 - 372), (1154 - 1920//2, 1080//2 - 428)),
((808, 1080//2 - 367), (1014 - 1920//2, 1080//2 - 364))]),
(5, 1, [((891, 1080//2 - 450), (1007 - 1920//2, 1080//2 - 407)),
((950, 1080//2 - 331), (1075 - 1920//2, 1080//2 - 313)),
((842, 1080//2 - 380), (970 - 1920//2, 1080//2 - 316))])
]
camid_to_param_offset = {2: 0, 5: 3}
def to_vec(px, py):
fov = fov_factor*np.array([1, in_size[0]/in_size[1]])
x = fov[0]*(2*px/in_size[1] - 1)
y = fov[1]*(2*py/in_size[0] - 1)
vec = np.array([x, y, 1])
return vec/np.linalg.norm(vec)
def gen_matrix(camid, params):
if camid == 1:
return Rx(np.pi/2)
else:
off = camid_to_param_offset[camid]
return np.matmul(Rx(params[off + 2]), np.matmul(Ry(params[off + 1]), Rz(params[off])))
def calc_chi2(params):
chi2 = 0
for a, b, marker in marks:
Ma = gen_matrix(a, params)
Mb = gen_matrix(b, params)
for m1, m2 in marker:
diff = np.matmul(Ma, to_vec(*m1)) - np.matmul(Mb, to_vec(*m2))
chi2 += np.sum(diff**2)
return chi2
def show_markers():
for a, b, marker in marks:
a = read_img(a, in_size)
b = read_img(b, in_size)
for m1, m2 in marker:
cv2.circle(a, m1, 5, (1, 0, 0))
cv2.circle(b, m2, 5, (1, 0, 0))
cv2.imshow("f", np.flip(np.hstack([a, b]), axis=0))
while cv2.waitKey(0) != ord("q"):
pass
cv2.destroyAllWindows()
show_markers()
res = minimize(calc_chi2, x0=[0]*3*len(marks))
print(repr(gen_matrix(2, res.x)))
print(repr(gen_matrix(5, res.x)))
| 42Ar/cube_mapper | marker_calc.py | marker_calc.py | py | 2,039 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.array",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "numpy.linalg.norm",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "numpy.linalg",
"line_nu... |
74246420903 | import pandas as pd
import glob
from openpyxl import load_workbook
import os
class DataFile:
def __init__(self, file_path):
self.file_path = file_path
@staticmethod
def read_csv_file(file_path):
"""
reads a *.csv file and returns a pandas DataFrame of the file
:param file_path: path to a *.csv file
:return: a pandas DataFrame from the chosen file
"""
with open(file_path, encoding='UTF-16LE') as file:
return pd.read_csv(file, sep='\t')
def combine_to_excel(self, input_directory: str, output_file: str) -> None:
"""
combines data from csv into one .xlsx file
:param input_directory: name of directory that contains *.csv files
:param output_file: name of the new file with combined data
:return: saves a new *.xlsx file for future manipulations
"""
parsed = [self.read_csv_file(file_path=path) for path in glob.glob(f'{input_directory}/*.csv')]
merged = pd.concat(parsed)
merged.to_excel(output_file, index=False)
@staticmethod
def load_invoices(file_path):
"""
Loads first column in first sheet into a list.
"""
invoice_file = load_workbook(file_path)
invoice_sheet = invoice_file.active
return [
str(row[0]) for row in
invoice_sheet.iter_rows(min_row=2, min_col=1, max_col=1, values_only=True)
]
@staticmethod
def remove_row(file_path):
"""
Checks if first row contains unnecessary data (not headings)
and removes it
:param file_path: path to GFIS excel file
"""
gfis_file = load_workbook(file_path)
gfis_sheet = gfis_file.active
for cell in gfis_sheet.iter_rows(max_row=1, values_only=True):
if None in cell:
gfis_sheet.delete_rows(1)
gfis_file.save(file_path)
print(f'row has been removed in {file_path}')
else:
print(f'no rows to remove in {file_path}. GFIS data spreadsheet is OK.')
@staticmethod
def remove_temporary_files(file):
"""
removes created files after processing
:param file:
:return:
"""
try:
os.remove(file)
except FileNotFoundError:
print('Nothing to remove.')
| DimaZimin/invoice_status_check | datafile.py | datafile.py | py | 2,386 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pandas.read_csv",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "glob.glob",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "pandas.concat",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "openpyxl.load_workbook",
... |
39399879426 | from pyspark import SparkConf, SparkContext
import random
import numpy as np
import time
def mapper1(line):
matrix_name, row, col, num = line.split(",")
row, col, num = int(row), int(col), int(num)
mapList = []
for idx in range(MATRIX_SIZE):
if matrix_name == 'M':
key = (row, idx, col)
value = num
else:
key = (idx, col, row)
value = num
mapList.append([key, value])
return mapList
def reducer1(x, y):
return x * y
def mapper2(x): # x => ((0, 0, 0), 10)
row, col, idx = x[0]
key = (row, col)
value = x[1]
return [(key, value)]
def reducer2(x, y):
return x + y
def map_and_reduce(file_path):
conf = SparkConf().setMaster("local").setAppName("matrix_multiplication")
sc = SparkContext(conf=conf)
lines = sc.textFile(file_path).flatMap(mapper1)
lines = lines.reduceByKey(reducer1)
lines = lines.flatMap(mapper2)
lines = lines.reduceByKey(reducer2)
return lines.collect()
def gen_test_case(matrix_size):
M = []
N = []
with open("{}input.txt".format(matrix_size), 'w') as f:
for i in range(matrix_size):
M_row = []
for j in range(matrix_size):
item = random.randint(1, 10)
M_row.append(item)
write_str = '{},{},{},{}\n'.format('M', i, j, item)
f.write(write_str)
M.append(M_row)
for i in range(matrix_size):
N_row = []
for j in range(matrix_size):
item = random.randint(1, 10)
N_row.append(item)
write_str = '{},{},{},{}\n'.format('N', i, j, item)
f.write(write_str)
N.append(N_row)
answer = np.matmul(np.array(M), np.array(N))
with open("{}input_answer.txt".format(matrix_size), 'w') as f:
for i in range(answer.shape[0]):
for j in range(answer.shape[1]):
item = answer[i, j]
write_str = '{},{},{}\n'.format(i, j, item)
f.write(write_str)
def write_results_to_file(results, matrix_size):
sort_key = lambda x: (x[0], x[1])
results.sort(key=sort_key)
with open("{}output.txt".format(matrix_size), 'w') as f:
for result in results:
row, col = result[0]
value = result[1]
write_str = '{},{},{}\n'.format(row, col, value)
f.write(write_str)
if __name__ == '__main__':
MATRIX_SIZE = 500
# gen_test_case(MATRIX_SIZE)
FILE_PATH = '{}input.txt'.format(MATRIX_SIZE)
start_time = time.time()
results = map_and_reduce(file_path=FILE_PATH)
end_time = time.time()
print('running time: {:.2f} min'.format((end_time - start_time) / 60))
write_results_to_file(results, MATRIX_SIZE)
| uuuChen/NTHU-Course-BIGDATA | bigData_hw1/hw1.py | hw1.py | py | 2,829 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pyspark.SparkConf",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "pyspark.SparkContext",
"line_number": 39,
"usage_type": "call"
},
{
"api_name": "random.randint",
"line_number": 54,
"usage_type": "call"
},
{
"api_name": "random.randint"... |
30144105909 | import os
from playhouse.sqlite_ext import CSqliteExtDatabase
from peewee import DatabaseProxy
class PDatabaseFactory:
def __init__(self, config):
self.cfg = config
self.instances = {}
self.defaut_instance = self.cfg.get('db', 'database')
self.sqlite_db_path = self.cfg.get('sqlite', 'path')
self.database_proxy = DatabaseProxy()
def get_instance(self, instance: str = None):
if not instance:
instance = self.defaut_instance
if instance not in self.instances.keys():
if instance == 'sqlite':
instance_obj = CSqliteExtDatabase(self.sqlite_db_path, autoconnect=False)
elif instance == 'sqlite-app-test':
PACKAGR_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
instance_obj = CSqliteExtDatabase(os.path.join(PACKAGR_DIR, 'mediastrends_test.db'))
elif instance == 'memory':
instance_obj = CSqliteExtDatabase(':memory:')
else:
raise ValueError("Instance %s not defined" % (instance))
self.instances[instance] = instance_obj
instance = self.instances[instance]
self.database_proxy.initialize(instance)
return instance
| prise6/medias-trends | mediastrends/database/peewee/PDatabaseFactory.py | PDatabaseFactory.py | py | 1,277 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "peewee.DatabaseProxy",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "playhouse.sqlite_ext.CSqliteExtDatabase",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "os.path.dirname",
"line_number": 22,
"usage_type": "call"
},
{
"api_... |
2962500565 | from prettytable import PrettyTable
import sympy as sp
sp.init_printing(use_unicode=True)
def raices_multiples(x0, tolerancia, niter):
x = sp.symbols('x')
#f = x**4 - 18*x**2+81
f = x**3 - x**2 - x + 1 + sp.sin(x-1)**2
tabla = PrettyTable(['i', 'xn', 'f(xn)', 'df(xn)', 'ddf(xn)', 'ErrorAbs', 'ErrorRel'])
df = f.diff(x) # Primera derivada
ddf = df.diff(x) # Segunda derivada
contador = 0
xn = x0
fx = f.evalf(subs={x:xn})
dfx = df.evalf(subs={x:xn})
ddfx = ddf.evalf(subs={x:xn})
tabla.add_row([contador, xn, fx, dfx, ddfx, "No hay error", "No hay error"])
error = tolerancia + 1.0
while contador < niter and error > tolerancia:
xnn = xn - (fx * dfx) / (dfx**2 - fx*ddfx)
error = abs(xnn-xn)
xn = xnn
fx = f.evalf(subs={x:xn})
dfx = df.evalf(subs={x: xn})
ddfx = ddf.evalf(subs={x: xn})
contador = contador + 1
tabla.add_row([contador, xn, fx, dfx, ddfx, error, abs(error/xn)])
print(tabla)
raices_multiples(0.5, 1e-5, 100)
| jvalen92/Analisis-Numerico | SolucionEcuancionesUnaVariable/raices_multples.py | raices_multples.py | py | 1,051 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "sympy.init_printing",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "sympy.symbols",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "sympy.sin",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "prettytable.PrettyTable",
... |
27688934832 | import sys
import pandas as pd
import numpy as np
from sklearn.preprocessing import RobustScaler
from sklearn.tree import DecisionTreeClassifier
from evaluate_model import evaluate_model
dataset = sys.argv[1]
num_param_combinations = int(sys.argv[2])
random_seed = int(sys.argv[3])
np.random.seed(random_seed)
pipeline_components = [RobustScaler, DecisionTreeClassifier]
pipeline_parameters = {}
min_impurity_decrease_values = np.random.exponential(scale=0.01, size=num_param_combinations)
max_features_values = np.random.choice(list(np.arange(0.01, 1., 0.01)) + ['sqrt', 'log2', None], size=num_param_combinations)
criterion_values = np.random.choice(['gini', 'entropy'], size=num_param_combinations)
max_depth_values = np.random.choice(list(range(1, 51)) + [None], size=num_param_combinations)
all_param_combinations = zip(min_impurity_decrease_values, max_features_values, criterion_values, max_depth_values)
pipeline_parameters[DecisionTreeClassifier] = \
[{'min_impurity_decrease': min_impurity_decrease, 'max_features': max_features, 'criterion': criterion, 'max_depth': max_depth, 'random_state': 324089}
for (min_impurity_decrease, max_features, criterion, max_depth) in all_param_combinations]
evaluate_model(dataset, pipeline_components, pipeline_parameters)
| rhiever/sklearn-benchmarks | model_code/random_search/DecisionTreeClassifier.py | DecisionTreeClassifier.py | py | 1,283 | python | en | code | 204 | github-code | 36 | [
{
"api_name": "sys.argv",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "sys.argv",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "sys.argv",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "numpy.random.seed",
"line... |
37362500325 | import os
import sys
from pathlib import Path
from typing import Optional
import tempfile
import time
import queue
import subprocess
import threading
class IPythonInterpreter:
_END_MESSAGE = "__ INTERPRETER END OF EXECUTION __"
_INTERPRETER_PROMPT = ">>> "
_LAST_VAR = "_INTERPRETER_last_val"
def __init__(
self,
*,
working_dir: Path = None,
ipython_path: Path = None,
timeout: int = None,
deactivate_venv: bool = False,
):
self._working_dir = working_dir
if ipython_path is None:
self._ipython_path = Path(sys.executable).parent / "ipython.exe"
else:
self._ipython_path = ipython_path
self._timeout = timeout
self._deactivate_venv = deactivate_venv
self._running = False
self._start()
def __del__(self):
self.stop()
def _get_env(self):
env = os.environ.copy()
if self._deactivate_venv:
if "VIRTUAL_ENV" in env:
del env["VIRTUAL_ENV"]
if "_OLD_VIRTUAL_PROMPT" in env:
env["PROMPT"] = "_OLD_VIRTUAL_PROMPT"
del env["_OLD_VIRTUAL_PROMPT"]
if "_OLD_VIRTUAL_PYTHONHOME" in env:
env["PYTHONHOME"] = "_OLD_VIRTUAL_PYTHONHOME"
del env["_OLD_VIRTUAL_PYTHONHOME"]
if "_OLD_VIRTUAL_PATH" in env:
env["PATH"] = "_OLD_VIRTUAL_PATH"
del env["_OLD_VIRTUAL_PATH"]
return env
def _start(self):
env = self._get_env()
self._process = subprocess.Popen(
[str(self._ipython_path), "--classic"],
text=True,
cwd=self._working_dir,
env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
self._p_stdin = self._process.stdin
self._stop_threads = False
self._q_stdout = queue.Queue()
self._t_stdout = threading.Thread(
target=self._reader_thread,
args=(self._process.stdout, self._q_stdout),
daemon=True,
)
self._t_stdout.start()
self._q_stderr = queue.Queue()
self._t_stderr = threading.Thread(
target=self._reader_thread,
args=(self._process.stderr, self._q_stderr),
daemon=True,
)
self._t_stderr.start()
self._wait_till_started()
self._running = True
def stop(self):
if self._running:
self._process.kill()
self._stop_threads = True
self._t_stdout.join()
self._t_stderr.join()
self._running = False
def _reader_thread(self, pipe, q):
while not self._stop_threads:
q.put(pipe.readline())
def _read_stdout(self, timeout: Optional[int]) -> Optional[str]:
start = time.time()
stdout = ""
while True:
try:
line = self._q_stdout.get(timeout=timeout)
except queue.Empty:
line = None
if timeout is not None and time.time() - start > timeout:
line = None
if line is None:
return None
if self._END_MESSAGE in line:
break
stdout += line
return stdout[len(self._INTERPRETER_PROMPT) :]
def _read_stderr(self) -> str:
stderr = ""
while not self._q_stderr.empty():
stderr += self._q_stderr.get()
return stderr
def _write_stdin(self, text: str):
self._p_stdin.write(text)
self._p_stdin.flush()
def _wait_till_started(self):
self._write_stdin(f"'{self._END_MESSAGE}'\n")
self._read_stdout(timeout=10)
def _create_script(self, script: str) -> Path:
lines = script.splitlines()
if len(lines) > 0:
is_eval = True
try:
compile(lines[-1], "<stdin>", "eval")
except SyntaxError:
is_eval = False
if is_eval:
lines[-1] = f"{self._LAST_VAR} = ({lines[-1]})"
lines.append(f"if {self._LAST_VAR} is not None:")
lines.append(f" print({self._LAST_VAR})")
script = "\n".join(lines) + "\n"
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
f.write(script)
return Path(f.name)
def _run_script(self, script_path: Path):
self._write_stdin(f"%run -i {script_path}\n'{self._END_MESSAGE}'\n")
def _fetch_result(self) -> Optional[str]:
stdout = self._read_stdout(timeout=self._timeout)
if stdout is None:
self.stop()
self._start()
return None
stderr = self._read_stderr()
return stdout + stderr
def run_cell(self, script: str) -> Optional[str]:
"""Run the whole cell and return the last result.
Returns None if the interpreter timed out."""
script_path = self._create_script(script)
self._run_script(script_path)
result = self._fetch_result()
script_path.unlink()
return result
| silvanmelchior/IncognitoPilot | services/services/interpreter/ipython_interpreter.py | ipython_interpreter.py | py | 5,216 | python | en | code | 364 | github-code | 36 | [
{
"api_name": "pathlib.Path",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "pathlib.Path",
"line_number": 21,
"usage_type": "name"
},
{
"api_name": "pathlib.Path",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "sys.executable",
"line_num... |
8060696161 | # Lint as: python3
"""CoQA: A Conversational Question Answering Challenge"""
# partially taken from https://github.com/NTU-SQUAD/transformers-coqa/blob/2dfd58b70956e935e370989fa421f34bb83bff08/data/processors/coqa.py
from __future__ import absolute_import, division, print_function
import json
import logging
import os
import re
import string
from collections import Counter
import spacy
import datasets
MAX_Q_LEN = 100 # Max length of question
YOUR_LOCAL_DOWNLOAD = "../data"
_CITATION = """\
@article{reddy-etal-2019-coqa,
title = "{C}o{QA}: A Conversational Question Answering Challenge",
author = "Reddy, Siva and
Chen, Danqi and
Manning, Christopher D.",
journal = "Transactions of the Association for Computational Linguistics",
volume = "7",
month = mar,
year = "2019",
url = "https://www.aclweb.org/anthology/Q19-1016",
doi = "10.1162/tacl_a_00266",
pages = "249--266",
}
"""
_DESCRIPTION = """\
CoQA is a large-scale dataset for building Conversational Question Answering systems. \
The goal of the CoQA challenge is to measure the ability of machines to understand a text passage\
and answer a series of interconnected questions that appear in a conversation. \
CoQA is pronounced as coca.
"""
_HOMEPAGE = "https://stanfordnlp.github.io/coqa/"
_URLs = "https://nlp.stanford.edu/data/coqa/coqa-train-v1.0.json, https://nlp.stanford.edu/data/coqa/coqa-dev-v1.0.json"
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text):
"""Returns tokenized answer spans that better match the annotated answer."""
tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start: (new_end + 1)])
if text_span == tok_answer_text:
return (new_start, new_end)
return (input_start, input_end)
class Coqa(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="coqa_rc",
version=VERSION,
description="Load CoQA dataset for machine reading comprehension tasks",
)
]
DEFAULT_CONFIG_NAME = "coqa_rc"
def _info(self):
if self.config.name == "coqa_rc":
features = datasets.Features(
{
"id": datasets.Value("string"),
"title": datasets.Value("string"),
"context": datasets.Value("string"),
"question": datasets.Value("string"),
"answers": datasets.features.Sequence(
{
"text": datasets.Value("string"),
"answer_start": datasets.Value("int32"),
# "answer_end": datasets.Value("int32"),
}
),
"domain": datasets.Value("string"), # is "source" in CoQA (e.g., wikipedia)
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
my_urls = _URLs
# data_dir = dl_manager.download_and_extract(my_urls)
data_dir = YOUR_LOCAL_DOWNLOAD # point to local dir to avoid downloading the dataset again
if self.config.name == "coqa_rc":
return [
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"filepath": os.path.join(
data_dir, "coqa/coqa-dev-v1.0.json"
),
},
),
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": os.path.join(
data_dir, "coqa/coqa-train-v1.0.json"
),
},
),
]
def _str(self, s):
""" Convert PTB tokens to normal tokens """
if (s.lower() == '-lrb-'):
s = '('
elif (s.lower() == '-rrb-'):
s = ')'
elif (s.lower() == '-lsb-'):
s = '['
elif (s.lower() == '-rsb-'):
s = ']'
elif (s.lower() == '-lcb-'):
s = '{'
elif (s.lower() == '-rcb-'):
s = '}'
return s
def space_extend(self, matchobj):
return ' ' + matchobj.group(0) + ' '
def is_whitespace(self, c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
def pre_proc(self, text):
text = re.sub(u'-|\u2010|\u2011|\u2012|\u2013|\u2014|\u2015|%|\[|\]|:|\(|\)|/|\t', self.space_extend, text)
text = text.strip(' \n')
text = re.sub('\s+', ' ', text)
return text
def process(self, parsed_text):
output = {'word': [], 'offsets': [], 'sentences': []}
for token in parsed_text:
output['word'].append(self._str(token.text))
output['offsets'].append((token.idx, token.idx + len(token.text)))
word_idx = 0
for sent in parsed_text.sents:
output['sentences'].append((word_idx, word_idx + len(sent)))
word_idx += len(sent)
assert word_idx == len(output['word'])
return output
def normalize_answer(self, s):
"""Lower text and remove punctuation, storys and extra whitespace."""
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def get_raw_context_offsets(self, words, raw_text):
raw_context_offsets = []
p = 0
for token in words:
while p < len(raw_text) and re.match('\s', raw_text[p]):
p += 1
if raw_text[p:p + len(token)] != token:
print('something is wrong! token', token, 'raw_text:',
raw_text)
raw_context_offsets.append((p, p + len(token)))
p += len(token)
return raw_context_offsets
def find_span(self, offsets, start, end):
start_index = -1
end_index = -1
for i, offset in enumerate(offsets):
if (start_index < 0) or (start >= offset[0]):
start_index = i
if (end_index < 0) and (end <= offset[1]):
end_index = i
return (start_index, end_index)
def find_span_with_gt(self, context, offsets, ground_truth):
best_f1 = 0.0
best_span = (len(offsets) - 1, len(offsets) - 1)
gt = self.normalize_answer(self.pre_proc(ground_truth)).split()
ls = [
i for i in range(len(offsets))
if context[offsets[i][0]:offsets[i][1]].lower() in gt
]
for i in range(len(ls)):
for j in range(i, len(ls)):
pred = self.normalize_answer(
self.pre_proc(
context[offsets[ls[i]][0]:offsets[ls[j]][1]])).split()
common = Counter(pred) & Counter(gt)
num_same = sum(common.values())
if num_same > 0:
precision = 1.0 * num_same / len(pred)
recall = 1.0 * num_same / len(gt)
f1 = (2 * precision * recall) / (precision + recall)
if f1 > best_f1:
best_f1 = f1
best_span = (ls[i], ls[j])
return best_span
def _generate_examples(self, filepath):
"""This function returns the examples in the raw (text) form."""
with open(filepath, encoding="utf-8") as f:
data = json.load(f)["data"]
for row in data:
story = row["story"]
domain = row["source"]
title = row["filename"]
all_prev_utterances = []
for i, question in enumerate(row['questions']):
id_ = str(row['id']) + '_' + str(question['turn_id'])
all_prev_utterances.append(question['input_text'])
answers = [{
"text": row["answers"][i]["span_text"],
"answer_start": row["answers"][i]["span_start"]
}]
question_str = " ".join(
list(reversed(all_prev_utterances))
).strip()
question_str = " ".join(question_str.split()[:MAX_Q_LEN])
# append the original answer into the utterance list
orig_answer_text = row["answers"][i]["input_text"]
all_prev_utterances.append(orig_answer_text)
qa = {
"id": id_,
"domain": domain,
"title": title,
"context": story,
"question": question_str,
"answers": answers,
}
yield id_, qa | HLTCHKUST/CAiRE_in_DialDoc21 | utils/coqa.py | coqa.py | py | 9,844 | python | en | code | 11 | github-code | 36 | [
{
"api_name": "datasets.GeneratorBasedBuilder",
"line_number": 62,
"usage_type": "attribute"
},
{
"api_name": "datasets.Version",
"line_number": 64,
"usage_type": "call"
},
{
"api_name": "datasets.BuilderConfig",
"line_number": 67,
"usage_type": "call"
},
{
"api_n... |
33873457342 | import tkinter as tk
import tkinter.font as font
from PIL import Image, ImageTk
import QuikSpace as qs
import Add_Task_School_Work as atsw
import Review_Task_School_Work as rtsw
window=""
def quikSpace():
global window
window.destroy()
qs.quikspace()
def ADD_Task_School_Work():
global window
window.destroy()
atsw.add_task_school_work()
def Review_Task_School_Work():
global window
window.destroy()
rtsw.review_task_school_work()
def school_Work():
global window
window=tk.Tk()
window.geometry("780x670")
window.resizable(0,0)
window.title("School/Work")
window.config(bg="#FFD9B3")
font1=font.Font(family="Times New Roman",size=35,weight='bold')#Created the font
font2=font.Font(family="Times New Roman",size=15)#Created the font
font3=font.Font(family="Courier New",size=17)
title=tk.Label(window, text="QuikSpace",font=font1, bg="#FFD9B3")#Created the title
title.place(x=260,y=25)
image=Image.open("Scheduler/logo.png")#Loads the image in RAM
image=image.resize((90,60))
photo=ImageTk.PhotoImage(image)#Converts the image into the Tkinter image format
image_label=tk.Label(window,image=photo)
image_label.place(x=440,y=20)
slogan=tk.Label(window, text="All your tasks, in one app", font=font2, bg="#FFD9B3")
slogan.place(x=315,y=90)
add_task=tk.Button(window, text="Add Task",width=25, height=5, highlightbackground="#B3D9FF",fg="white",command=ADD_Task_School_Work)
add_task.place(x=285,y=170)
review_tasks=tk.Button(window, text="Review Tasks",width=25, height=5, highlightbackground="#B3D9FF",fg="white",command=Review_Task_School_Work)
review_tasks.place(x=285,y=320)
main_menu=tk.Button(window, text="Main Menu",width=25, height=5, highlightbackground="#B3D9FF",fg="white",command=quikSpace)
main_menu.place(x=285,y=470)
label=tk.Label(window, text="School/Work", font=font2, bg="#FFD9B3")
label.place(x=360,y=645)
credits=tk.Label(window, text="Created By: Smyan and Rithwik", font=font3, bg="#FFD9B3")
credits.place(x=470,y=640)
window.mainloop() | math12345678/QuikSpace | School_Work.py | School_Work.py | py | 2,133 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "QuikSpace.quikspace",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "Add_Task_School_Work.add_task_school_work",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "Review_Task_School_Work.review_task_school_work",
"line_number": 23,
"usage... |
1379120770 | import os
import cv2
import dlib
import numpy as np
from eye import Eye
from calibration import Calibration
class EyeTracking(object):
"""
This class tracks the user's gaze.
It provides useful information like the position of the eyes
and pupils and allows to know if the eyes are open or closed
"""
def __init__(self):
self.frame = None
self.calibration = Calibration()
self.eye_left = None
self.eye_right = None
self.ex_eye_left = None
self.ex_eye_right = None
self.is_attention = 100
self.method = ""
# _face_detector is used to detect faces
self._face_detector = dlib.get_frontal_face_detector()
# _predictor is used to get facial landmarks of a given face
cwd = os.path.abspath(os.path.dirname(__file__))
model_path = os.path.abspath(os.path.join(cwd, "./models/shape_predictor_68_face_landmarks.dat"))
self._predictor = dlib.shape_predictor(model_path)
# dnn based landmark
self.net = cv2.dnn.readNetFromCaffe(
'./models/deploy.prototxt.txt',
'./models/res10_300x300_ssd_iter_140000.caffemodel'
)
self.landmark_predictor = dlib.shape_predictor('./models/shape_predictor_68_face_landmarks.dat')
@property
def pupils_located(self):
"""Check that the pupils have been located"""
try:
int(self.eye_left.pupil.x)
int(self.eye_left.pupil.y)
int(self.eye_right.pupil.x)
int(self.eye_right.pupil.y)
return True
except Exception:
return False
def adjust_gamma(self, image, gamma):
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")
return cv2.LUT(image, table)
def preprocess(self, img):
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if gray_img.mean() < 130:
img = self.adjust_gamma(img, 1.0)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img
def _analyze(self):
"""Detects the face and initialize Eye objects"""
# 필터링의 중요성 preprocess를 하고 안 하고에 따라 결과가 달라진다.
# dnn에 감마 값을 잘 조절하면 좋지 않을까.
frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
# frame = self.preprocess(self.frame)
faces = self._face_detector(frame)
try:
if faces:
self.method = "hog"
landmark = np.empty([68, 2], dtype = int)
landmarks = self._predictor(frame, faces[0])
for i in range(68):
landmark[i][0] = landmarks.part(i).x
landmark[i][1] = landmarks.part(i).y
# print(landmark)
self.eye_left = Eye(frame, landmark, 0, self.calibration)
self.eye_right = Eye(frame, landmark, 1, self.calibration)
else:
self.method = "dnn"
(h, w) = self.frame.shape[:2]
blob = cv2.dnn.blobFromImage(
cv2.resize(self.frame, (300, 300)),
1.0,(300, 300), (104.0, 177.0, 123.0
)
)
self.net.setInput(blob)
detections = self.net.forward()
## bounding box
list_bboxes = []
list_confidence = []
list_dlib_rect = []
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence < 0.6:
continue
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(l, t, r, b) = box.astype('int')
original_vertical_length = b - t
t = int(t + original_vertical_length * 0.15)
b = int(b - (original_vertical_length) * 0.05)
margin = ((b-t) - (r-l))//2
l = l - margin if (b-t-r+l)%2 == 0 else l - margin - 1
r = r + margin
list_bboxes.append([l, t, r, b])
list_confidence.append(confidence)
rect_bb = dlib.rectangle(left=l, top=t, right=r, bottom=b)
list_dlib_rect.append(rect_bb)
# landmark
list_landmarks = []
for rect in list_dlib_rect:
points = self.landmark_predictor(self.frame, rect)
list_points = list(map(lambda p: (p.x, p.y), points.parts()))
list_landmarks.append(list_points)
# print(list_landmarks)
list_landmarks = list_landmarks[0]
self.eye_left = Eye(self.frame, list_landmarks, 0, self.calibration)
self.eye_right = Eye(self.frame, list_landmarks, 1, self.calibration)
except IndexError:
self.eye_left = None
self.eye_right = None
def refresh(self, frame):
"""Refreshes the frame and analyzes it.
Arguments:
frame (numpy.ndarray): The frame to analyze
"""
self.frame = frame
self._analyze()
def pupil_left_coords(self):
"""Returns the coordinates of the left pupil"""
if self.pupils_located:
x = self.eye_left.origin[0] + self.eye_left.pupil.x
y = self.eye_left.origin[1] + self.eye_left.pupil.y
return (x, y)
def pupil_right_coords(self):
"""Returns the coordinates of the right pupil"""
if self.pupils_located:
x = self.eye_right.origin[0] + self.eye_right.pupil.x
y = self.eye_right.origin[1] + self.eye_right.pupil.y
return (x, y)
def get_attention(self):
return self.is_attention
def get_method(self):
return self.method
def horizontal_ratio(self):
"""Returns a number between 0.0 and 1.0 that indicates the
horizontal direction of the gaze. The extreme right is 0.0,
the center is 0.5 and the extreme left is 1.0
"""
if self.pupils_located:
pupil_left = self.eye_left.pupil.x / (self.eye_left.center[0] * 2 - 10)
pupil_right = self.eye_right.pupil.x / (self.eye_right.center[0] * 2 - 10)
return (pupil_left + pupil_right) / 2
def vertical_ratio(self):
"""Returns a number between 0.0 and 1.0 that indicates the
vertical direction of the gaze. The extreme top is 0.0,
the center is 0.5 and the extreme bottom is 1.0
"""
if self.pupils_located:
pupil_left = self.eye_left.pupil.y / (self.eye_left.center[1] * 2 - 10)
pupil_right = self.eye_right.pupil.y / (self.eye_right.center[1] * 2 - 10)
return (pupil_left + pupil_right) / 2
def is_right(self):
"""Returns true if the user is looking to the right"""
if self.pupils_located:
return self.horizontal_ratio() <= 0.35
def is_left(self):
"""Returns true if the user is looking to the left"""
if self.pupils_located:
return self.horizontal_ratio() >= 0.65
def is_center(self):
"""Returns true if the user is looking to the center"""
if self.pupils_located:
return self.is_right() is not True and self.is_left() is not True
def is_blinking(self):
"""Returns true if the user closes his eyes"""
if self.pupils_located:
blinking_ratio = (self.eye_left.blinking + self.eye_right.blinking) / 2
return blinking_ratio > 3.8
def is_focus(self):
if self.ex_eye_left is None:
self.eye_position_update()
return 0
if self.pupils_located:
focus = (
((self.eye_left.pupil.x + self.eye_right.pupil.x) / 2) -
((self.ex_eye_left.pupil.x + self.ex_eye_right.pupil.x) / 2)
)
self.eye_position_update()
if abs(focus) < 5:
return 1
else:
return 0
def eye_position_update(self):
self.ex_eye_left = self.eye_left
self.ex_eye_right = self.eye_right
def annotated_frame(self):
"""Returns the main frame with pupils highlighted"""
frame = self.frame.copy()
if self.pupils_located:
color = (0, 255, 0)
x_left, y_left = self.pupil_left_coords()
x_right, y_right = self.pupil_right_coords()
cv2.line(frame, (x_left - 5, y_left), (x_left + 5, y_left), color)
cv2.line(frame, (x_left, y_left - 5), (x_left, y_left + 5), color)
cv2.line(frame, (x_right - 5, y_right), (x_right + 5, y_right), color)
cv2.line(frame, (x_right, y_right - 5), (x_right, y_right + 5), color)
return frame
| dead4s/SpaHeron_MachineLearning_UXIS | eye_tracking/eye_tracking.py | eye_tracking.py | py | 9,108 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "calibration.Calibration",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "dlib.get_frontal_face_detector",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "os.path.abspath",
"line_number": 32,
"usage_type": "call"
},
{
"api_name":... |
35411324967 | from requests import get
from webapp.db import db
from webapp.question_service.models import Question_answer
def get_question_jservice(questions_quantity: int=1) -> dict:
"""
После получения колличества запрашиваемых вопросов сервис, в свою очередь,
запрашивает с публичного API (англоязычные вопросы для викторин)
https://jservice.io/api/random?count=1 указанное в полученном запросе количество вопросов.
"""
address_questions_jservice = f'https://jservice.io/api/random?count={questions_quantity}'
questions_in_jservice = get(address_questions_jservice).json()
return questions_in_jservice
def save_question_in_db(question: dict) -> None:
"""Сохранение данных вопроса в базу данных"""
add_question = Question_answer(
id_question = question['id'],
text_question = question['question'],
text_answer = question['answer'],
)
db.session.add(add_question)
db.session.commit()
def process_check_to_valid_and_save_questions(data_questions_num: int) -> None:
try:
questions_in_jservice = get_question_jservice(data_questions_num)
except:
return print('Сайт jservice.io не доступен')
for question in questions_in_jservice:
"""
Если в БД имеется такой же вопрос, к публичному API с викторинами выполняются дополнительные запросы до тех пор
пока не будет получен уникальный вопрос для викторины.
"""
questions_in_db = Question_answer.query.filter_by(id_question=question['id']).first()
if questions_in_db != None:
questions_in_jservice.append(get_question_jservice())
else:
save_question_in_db(question)
| Straigan/webapp_question_service | webapp/services/jservice_service.py | jservice_service.py | py | 2,084 | python | ru | code | 0 | github-code | 36 | [
{
"api_name": "requests.get",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "webapp.question_service.models.Question_answer",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "webapp.db.db.session.add",
"line_number": 29,
"usage_type": "call"
},
{
... |
34141163457 | from flask_restful import Resource
from pymongo import MongoClient
from api.starta_flode import MONGODB_CONNECTION
from statistics import median
class Statistik(Resource):
def getFlodeStatistics(self, subjects, flode=None):
allData = [r for r in subjects.find(flode and {'flode': flode} or {})]
tid = [int(x['end_at'] - x['start_at']) for x in allData if x['end_at'] is not None]
retobj = {
'started': len(allData),
'ended': len([x for x in allData if x['end_at'] is not None]),
'median': tid and median(tid) or 0
}
return retobj
def getFlodeB(self):
pass
def get(self):
mongo_client = MongoClient(MONGODB_CONNECTION)
# if not found
db = mongo_client['heroku_ssj5qmzb']
subjects = db.subjects
statistics = {
'total': self.getFlodeStatistics(subjects),
'A': self.getFlodeStatistics(subjects, 'A'),
'B': self.getFlodeStatistics(subjects, 'B')
}
return statistics, 200 | svanis71/fkhack-back | api/statistik.py | statistik.py | py | 1,059 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask_restful.Resource",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "statistics.median",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "pymongo.MongoClient",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "api.start... |
8648504297 | from django.shortcuts import render, HttpResponse
from .forms import UserForm
from sms_alert.models import User
def index(request):
if request.method == 'POST':
name = request.POST.get('name')
phone_number = request.POST.get('phone_number')
country = request.POST.get('country')
user_form = UserForm({
'timezone': 'America/Los_Angeles',
})
time_zone = user_form.cleaned_data['timezone']
temp = User(
name = name,
time_zone = time_zone,
phone_number = phone_number,
country = country
)
return HttpResponse("<h1>Successfully entered</h1>")
else:
form = UserForm()
return render(request, 'sms_alert/index.html', {'form': form})
def next(request):
if request.method == 'POST':
form = UserForm(request.POST)
time_zone = request.POST.get('timezone')
name = request.POST.get('name')
phone_number = request.POST.get('phone_number')
country = request.POST.get('country')
return render(request, 'sms_alert/next.html', {
'name' : name,
'phone_number' : phone_number,
'country' : country,
'time_zone' : time_zone,
})
else:
return render(request, 'sms_alert/next.html')
def form_save(request):
if request.method == 'POST':
name = request.POST.get('name')
phone_number = request.POST.get('phone_number')
country = request.POST.get('country')
time_zone = request.POST.get('time_zone')
awake_time = request.POST.get('awake_time')
sleep_time = request.POST.get('sleep_time')
print("-----------------------------------------------------", request.POST)
temp = User(
name=name,
sleep_time=sleep_time,
wake_time=awake_time,
time_zone=time_zone,
phone_number=phone_number,
country=country
)
temp.save()
form = UserForm()
return render(request, 'sms_alert/index.html', {'form': form})
else:
form = UserForm()
return render(request, 'sms_alert/index.html', {'form': form})
| prajjwalsinghzz14/Amnesia--Twilio-Notifiactions | Amnesia/sms_alert/views.py | views.py | py | 2,300 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "forms.UserForm",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "sms_alert.models.User",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "django.shortcuts.HttpResponse",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "fo... |
29290165497 | import glob
import os
import subprocess
import tempfile
rescompilerPath = 'build-desktop/bin/rescompiler.exe'
containerPath = 'data/build/game.dat'
excludeFiles = glob.glob('data/build/**/*', recursive=True) + glob.glob('data/sources/**/*', recursive=True)
dataFiles = [os.path.abspath(f) for f in glob.glob('data/**/*', recursive=True) if (not f in excludeFiles and not os.path.isdir(f))]
listFile = tempfile.NamedTemporaryFile('w+', delete=False)
print(f'Writing {len(dataFiles)} files to {listFile.name}')
listFile.write(os.linesep.join(dataFiles))
listFile.flush()
listFile.close()
resArgs = [
os.path.abspath(rescompilerPath),
listFile.name,
os.path.abspath(containerPath)
]
returnCode = subprocess.call(resArgs)
print(f'Completed with code {returnCode}') | Valax321/GAWFramework | rescompile.py | rescompile.py | py | 777 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "glob.glob",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "os.path.abspath",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "glob.glob",
"line_number": ... |
37272086828 | # https://blog.csdn.net/qq_32149483/article/details/112056845
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
from typing import Tuple, List
class Img_Aug:
def __init__(self, prob=0.2, crop=True, blur=True, superpixel=True,
space_trans=True, sharpen=True, emboss=True,
edge_detect=True, noise=True, dropout=True):
self.prob = prob
self.crop = crop
self.blur = blur
self.superpixel = superpixel
self.space_trans = space_trans
self.sharpen = sharpen
self.emboss = emboss
self.edge_detect = edge_detect
self.noise = noise
self.dropout = dropout
def __call__(self):
operations = [iaa.Affine(translate_px={"x": 15, "y": 15},
scale=(0.8, 0.8),
rotate=(-5, 5))]
if self.crop:
operations.append(iaa.Crop(percent=(0, self.prob)))
if self.blur:
operations.append(iaa.OneOf([iaa.GaussianBlur((0, 3.)),
iaa.AverageBlur(k=(2, 7)),
iaa.MedianBlur(k=(3, 11))]))
if self.superpixel:
operations.append(iaa.Sometimes(0.5, iaa.Superpixels(p_replace=(0.005, 0.5),
n_segments=(16, 28))))
if self.space_trans:
operations.append(iaa.Sequential([iaa.ChangeColorspace(from_colorspace="RGB", to_colorspace="HSV"),
iaa.WithChannels(0, iaa.Add((50, 100))),
iaa.ChangeColorspace(from_colorspace="HSV", to_colorspace="RGB")]))
if self.sharpen:
operations.append(iaa.Sharpen(alpha=(0., 1.), lightness=(0.75, 1.5)))
if self.emboss:
operations.append(iaa.Emboss(alpha=(0., 1.), strength=(0., 2.)))
if self.edge_detect:
operations.append(iaa.OneOf([iaa.EdgeDetect(alpha=(0., 0.75)),
iaa.DirectedEdgeDetect(alpha=(0., 0.75), direction=(0, 1))]))
if self.noise:
operations.append(iaa.AdditiveGaussianNoise(scale=(0, 128), per_channel=0.5))
if self.dropout:
operations.append(iaa.Dropout(p=(0.01, 0.1), per_channel=0.5))
lenTrans = len(operations)
seq = iaa.Sequential([iaa.SomeOf(min(5, lenTrans), operations, random_order=True)])
return seq
class Augmentation:
def __init__(self, seq):
self.seq = seq
def __call__(self, img, bbox=None, label=None, mode="x1y1x2y2") -> Tuple[np.ndarray, dict]:
# seq_det = self.seq.to_deterministic()
# bbox should be in x1x2y1y2 format
if bbox is None:
return self.seq(image=img)
if mode == "x1y1x2y2":
x1, y1, x2, y2 = bbox
else:
x1, y1, x2, y2 = bbox[0], bbox[1], bbox[0]+bbox[2], bbox[1]+bbox[3]
bbs = ia.BoundingBoxesOnImage([ia.BoundingBox(x1=x1, y1=y1, x2=x2, y2=y2, label=label)], shape=img.shape)
image_aug, bbox_aug = self.seq(image=img, bounding_boxes=bbs)
location = [bbox_aug[0].x1, bbox_aug[0].y1, bbox_aug[0].x2, bbox_aug[0].y2]
label = bbox_aug[0].label
shape = bbox_aug.shape
bbox_info = {"location": location, "label": label, "shape": shape}
return image_aug, bbox_info
if __name__ == "__main__":
seq = Img_Aug()()
import cv2
img = cv2.imread("mchar_train/000000.png")
aug_img, aug_bbox = Augmentation(seq)(img, bbox=[0.5, 0.5, 0.5, 0.5], label=0)
| SuperbTUM/machine-learning-practice | Text Recognition/data_aug.py | data_aug.py | py | 3,722 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "imgaug.augmenters.Affine",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "imgaug.augmenters",
"line_number": 24,
"usage_type": "name"
},
{
"api_name": "imgaug.augmenters.Crop",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "img... |
29024831808 | from src.algo import rpq
from src import Config
from tests.simple_test import simple_test
import json
import pytest
import os
import random
MAIN_TEST_DIR = \
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tests')
TEST_DIRS = list(map(
lambda dir_name: os.path.join(MAIN_TEST_DIR, dir_name),
os.listdir(MAIN_TEST_DIR)
))
@pytest.mark.parametrize('test_dir', TEST_DIRS)
def test_small_test(test_dir):
simple_test(
test_dir,
[
('config.json', 'config'),
('data_base.txt', 'data_base'),
('query.txt', 'regular_query')
],
rpq,
lambda j: set(map(tuple, j))
)
@pytest.mark.parametrize(('max_count_vertexes', 'regex'),
[
(max_count_vertexes, regex)
for max_count_vertexes in [10, 40, 160]
for regex in ['a | b', 'a* (b | $)', '(a | b) . (b* | a b)']
])
#for regex in ['a | b']])
def test_big_test(max_count_vertexes, regex):
count_edges = random.randint(1, max_count_vertexes ** 2)
I = [random.randint(0, max_count_vertexes - 1) for _ in range(count_edges)]
J = [random.randint(0, max_count_vertexes - 1) for _ in range(count_edges)]
V = [random.choice(['a', 'b', 'c']) for _ in range(count_edges)]
count_vertexes = max(I + J) + 1
max_count_input_vertexes = random.randint(1, count_vertexes)
max_count_output_vertexes = random.randint(1, count_vertexes)
input_vertexes = list({random.randint(0, count_vertexes - 1)
for _ in range(max_count_input_vertexes)})
output_vertexes = list({random.randint(0, count_vertexes - 1)
for _ in range(max_count_output_vertexes)})
config = Config.from_dict(
{
'data_base_lists': [I, J, V],
'regular_query_regex': regex,
'input_vertexes': input_vertexes,
'output_vertexes': output_vertexes
}
)
result = rpq(config)
for V_from, _ in result:
assert V_from in input_vertexes
for _, V_to in result:
assert V_to in output_vertexes
| SergeyKuz1001/formal_languages_autumn_2020 | tests/rpq/test.py | test.py | py | 2,155 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "os.path.dirname",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.path.abspath",
"line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.