blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
8dfc7f44f8c53830fb7ca71ad3a9bdc9268e0d4e
29060e22ab11a03554b09921f53012733d6e1d53
/status/api/views.py
45d8a02a6cc94d9389bf750788177b7b2bbc2c33
[]
no_license
dnyaneshm36/clg3_heroku_odd
93bfa82b7c096d761b38922053c4bf6367edb4bf
b427940c47da5244dc9ba4ec47eacf866050ee55
refs/heads/master
2023-01-10T08:47:16.971785
2020-10-15T07:26:46
2020-10-15T07:26:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,377
py
import json from rest_framework import generics,mixins from rest_framework.views import APIView from rest_framework.response import Response #from rest_framework.generics import ListAPIView #from django.views.generic import View from status.models import Status from .serializers import StatusSerializer from django.shortcuts import get_object_or_404 from rest_framework.generics import ListAPIView def is_json(json_data): try: real_json = json.loads(json_data) is_valid = True except ValueError: is_valid = False return is_valid class StatusAPIView( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.ListAPIView): permission_classes =[] authentication_classes =[] serializer_class =StatusSerializer passed_id =None def get_queryset(self): request = self.request qs = Status.objects.all() query = self.request.GET.get('ur') if query is not None: qs = qs.filter(user__exact = query) return qs def get_object(self): request =self.request passed_id =request.GET.get('id',None) or self.passed_id # print(request.body) # print(passed_id) # print(request.data) queryset =self.get_queryset() obj = None if passed_id is not None: obj = get_object_or_404(queryset, id = passed_id) self.check_object_permissions(request,obj) return obj def get(self,request,*args,**kwargs): url_passed_id = request.GET.get('id',None) json_data ={} body_ =request.body if is_json(body_): json_data =json.loads(request.body) #print(json_data,"jata") new_passed_id =json_data.get('id',None) passed_id = url_passed_id or new_passed_id or None self.passed_id = passed_id if passed_id is not None: return self.retrieve(request, *args,**kwargs) return super(StatusAPIView,self).get(request,*args,**kwargs) def post(self,request,*args,**kwargs): url_passed_id = request.GET.get('id',None) json_data ={} body_ =request.body if is_json(body_): json_data =json.loads(request.body) print(json_data,"jata") new_passed_id =json_data.get('id',None) passed_id = url_passed_id or new_passed_id or None self.passed_id = passed_id return self.create(request,*args,**kwargs) def put(self,request,*args,**kwargs): url_passed_id = request.GET.get('id',None) json_data ={} body_ =request.body if is_json(body_): json_data =json.loads(request.body) print(json_data,"jata") new_passed_id =json_data.get('id',None) passed_id = url_passed_id or new_passed_id or None self.passed_id = passed_id return self.update(request,*args,**kwargs) def patch(self,request,*args,**kwargs): url_passed_id = request.GET.get('id',None) json_data ={} body_ =request.body if is_json(body_): json_data =json.loads(request.body) print(json_data,"jata") new_passed_id =json_data.get('id',None) passed_id = url_passed_id or new_passed_id or None self.passed_id = passed_id return self.partial_update(request,*args,**kwargs) def delete(self,request,*args,**kwargs): url_passed_id = request.GET.get('id',None) json_data ={} body_ =request.body if is_json(body_): json_data =json.loads(request.body) print(json_data,"jata") new_passed_id =json_data.get('id',None) passed_id = url_passed_id or new_passed_id or None self.passed_id = passed_id return self.destroy(request,*args,**kwargs) # def put(self, request, *args, **kwargs): # return self.update(request,*args,**kwargs) # def patch(self, request, *args, **kwargs): # return self.partial_update(request,*args,**kwargs) # def delete(self, request, *args, **kwargs): # return self.destroy(request,*args,**kwargs) # class StatusListSearchAPIView(APIView): # permission_classes = [] # authentication_classes =[] # def get(self,request , format = None): # qs = Status.objects.all() # serializer = StatusSerializer(qs, many=True) # return Response(serializer.data) # def post(self,request , format = None): # qs = Status.objects.all() # serializer = StatusSerializer(qs, many=True) # return Response(serializer.data) # # class StatusAPIView(generics.ListAPIView): # # permission_classes =[] # # authentication_classes =[] # # serializer_class =StatusSerializer # # def get_queryset(self): # # qs = Status.objects.all() # # query = self.request.GET.get('q') # # if query is not None: # # qs = qs.filter(content__icontains = query) # # return qs # # class StatusCreateAPIView(generics.CreateAPIView): # # permission_classes =[] # # authentication_classes =[] # # queryset =Status.objects.all() # # serializer_class =StatusSerializer # # # def perform_create(self, serializer): # # # serializer.save(user=self.request.user) # # class StatusDetailAPIView(generics.RetrieveAPIView): # # permission_classes =[] # # authentication_classes =[] # # queryset =Status.objects.all() # # serializer_class =StatusSerializer # # #lookup_field ='id' #slug # ''' # here this is problem is comees under the # id is not menttion so if # worrite pk in url it will work # or use the folling methed in letter verions not support this # method # ''' # # def get_object(self,*args,**kwargs): # # kwargs = self.kwargs # # kw_id = kwargs.get('id') # # return Status.objects.get(id) # # class StatusUpdateAPIView(generics.UpdateAPIView): # # permission_classes =[] # # authentication_classes =[] # # queryset =Status.objects.all() # # serializer_class =StatusSerializer # # class StatusDeleteAPIView(generics.DestroyAPIView): # # permission_classes =[] # # authentication_classes =[] # # queryset =Status.objects.all() # # serializer_class =StatusSerializer # # CreateModedMixin --- post data # # UpdateModedMixin --- put data # # DestroyModelMixin -- DELETE method http methond # class StatusAPIView(mixins.CreateModelMixin,generics.ListAPIView): #crea te list # permission_classes =[] # authentication_classes =[] # serializer_class =StatusSerializer # def get_queryset(self): # qs = Status.objects.all() # query = self.request.GET.get('q') # if query is not None: # qs = qs.filter(content__icontains = query) # return qs # def post(self,request,*args,**kwargs): # return self.create(request,*args,**kwargs) # class StatusDetailAPIView(mixins.DestroyModelMixin, mixins.UpdateModelMixin , generics.RetrieveAPIView): # permission_classes =[] # authentication_classes =[] # serializer_class =StatusSerializer # queryset =Status.objects.all() # def put(self, request, *args, **kwargs): # return self.update(request,*args,**kwargs) # def patch(self, request, *args, **kwargs): # return self.partial_update(request,*args,**kwargs) # def delete(self, request, *args, **kwargs): # return self.destroy(request,*args,**kwargs)
[ "dnyaneshm36@gmail.com" ]
dnyaneshm36@gmail.com
e6a244504589aefb338ee981f3fa9cc5647fa1d6
a6d964a8111e1f3ed9e869b37b8a7142a7d444aa
/FormularioPersona/views.py
7ad29e8943a6832fd678ad5ba962eedc17b8b16f
[]
no_license
DiegoBastianH/misperris
06d3bb4a7aaa2f823d81bb30617933e09e06686a
405fb905f5e8089763e9fcd5c73c91a8e9d347eb
refs/heads/master
2020-04-05T21:33:04.903005
2018-11-12T14:29:35
2018-11-12T14:29:35
157,224,444
0
0
null
null
null
null
UTF-8
Python
false
false
1,007
py
from django.shortcuts import render from django.utils import timezone from . models import formulariopersona from django.contrib.auth.models import User from django.urls import reverse_lazy from FormularioPersona.forms import RegistroForm from django.views.generic import CreateView def pagina_principal(request): return render(request,'PaginaDelMisPerris/PaginaPrincipal.html') def pagina_contactanos(request): form = formulariopersona() if request.method == "POST": form.CorreoElectronico = request.POST['correopers'] form.Rut = request.POST['ruttt'] form.NombreCompleto = request.POST['nombrepersona'] form.FechaNacimiento = request.POST['Fechapers'] form.Telefono = request.POST['telef'] form.Direccion = request.POST['direcc'] form.save() return render(request,'PaginaDelMisPerris/contactanos.html') class RegistroUsuario(CreateView): model = User template_name = "PaginaDelMisPerris/registrar.html" form_class = RegistroForm success_url = reverse_lazy('login')
[ "kevin_herrera_g@hotmail.com" ]
kevin_herrera_g@hotmail.com
4175498f9d50c2b59eb642788a60f83ea825f8ca
24002364d24c7d146bb72489b1ec04619547d65d
/weddingsite/weddingsite/urls.py
299ab73d65d2e16eb93155bd6115555574fbcbd1
[]
no_license
FredericoTakayama/deniseefred
488a915b760ea21791e6eca451323aa0afc92d99
d96b0ccbcb64c6cf9eb0ee9e8d1b1bfa839e5b54
refs/heads/master
2020-03-31T10:42:19.900914
2019-03-24T14:38:02
2019-03-24T14:38:02
152,145,832
0
0
null
2019-03-24T14:38:03
2018-10-08T20:58:09
JavaScript
UTF-8
Python
false
false
1,067
py
"""weddingsite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainsite.urls')), ] # Use static() to add url mapping to serve static files during development (only) from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
[ "f.takayama2014@gmail.com" ]
f.takayama2014@gmail.com
a1426f24f8e2a2a2171520a289cc98f9baa54a7b
2ece8f5c7161933bb5f6dfb119879ad8ada022e8
/middle_exam/exam_2.py
7449875b0592c89b87b5c5b508e785f06c4e5497
[]
no_license
Baedoli/python
f771d1a51e8272f97f39887dc6dbf0f0b12d0617
d1cc6ad4f2923c7088cf54d67c6686b03f83a694
refs/heads/master
2021-12-20T13:21:22.601514
2021-12-15T09:29:22
2021-12-15T09:29:22
131,465,086
0
0
null
null
null
null
UTF-8
Python
false
false
3,232
py
# 팩키지 임포트 from selenium import webdriver from datetime import datetime import time import pandas as pd import os # Excel 저장 할 경우 필요한 Package ... import openpyxl def extract_content(sections,dataset,counter): for section in sections: member = section.find_element_by_class_name("X43Kjb").text # 별점 Div 항목 안에 있는 값을 가져옴 ... rating = section.find_element_by_class_name("pf5lIe").find_element_by_tag_name("div").get_attribute("aria-label") created = section.find_element_by_class_name("p2TkOb").text likes = section.find_element_by_class_name("jUL89d.y92BAb").text body_ = section.find_element_by_class_name("UD7Dzf").text # 등록자가 있는 정보만 가져 옴 ... if member != "": counter = counter + 1 example = [member, rating, created, likes, body_] example_series = pd.Series(example, index=dataset.columns) dataset = dataset.append(example_series, ignore_index=True) # 최종 등록 건수가 5000개 이상이면 빠져 나옴 .. if counter > 5000: break return dataset, counter driver_path = '/Users/baeseongho/webdriver/chromedriver' driver = webdriver.Chrome(driver_path) column_names = ["member", "rating", "created", "likes", "comment"] dataset = pd.DataFrame(columns = column_names) dataset.head() # 알바천국 url = "https://play.google.com/store/apps/details?id=com.albamon.app&hl=ko&gl=US" driver.get(url) # 리뷰 모두 보기를 클릭 한다.. driver.find_element_by_xpath('//*[@id="fcxH9b"]/div[4]/c-wiz/div/div[2]/div/div/main/div/div[1]/div[6]/div/span/span').click() SCROLL_PAUSE_TIME = 1.5 counter = 1 while True: # (1) 5번의 스크롤링 for i in range(5): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(SCROLL_PAUSE_TIME) sections = driver.find_elements_by_class_name("d15Mdf.bAhLNe") dataset,counter = extract_content(sections, dataset,counter) print("현재 {0} 건이 담겼습니다.".format(counter)) # 첫번째 Div 에 답긴 누적 건수가 5000 개 이상이면 종료 조건 ... if counter > 5000: break # 두번째 종료 조건 .. 최종 건수가 5000 개 이상이면 빠져 나간다.. if counter > 5000: break # (2) 더보기 클릭 try: driver.find_element_by_xpath("//*[@id='fcxH9b']/div[4]/c-wiz[2]/div/div[2]/div/div/main/div/div[1]/div[2]/div[2]/div/span/span").click() # 혹시나 네트워크 속도에 의거하여 느리게 될 경우 더보기 페이지를 찾지 못할경우 다시 시작 ... except: print("계속 진행 합니다.") continue print("Excel 추출을 시작 합니다....") base_dir = "/Users/baeseongho/webdriver" # file_name = "mid_exam_2.xlsx" file_name = "알바몬_리뷰_리스트.xlsx" xlxs_dir = os.path.join(base_dir, file_name) dataset.to_excel(xlxs_dir, sheet_name = 'Sheet1', na_rep = 'NaN',\ float_format = "%.2f", header = True, startrow = 0, startcol = 0,\ engine = 'openpyxl') print("Excel 추출을 종료 합니다.")
[ "bae9808@gmail.com" ]
bae9808@gmail.com
7afc7769d77244292d98d19dc91783b62f99074a
d8ebb47e8929f6acc96005abdf1f030088ecbff5
/web_flask/3-python_route.py
1f75087b23429f09b92ddccbeb8614eb628eb159
[]
no_license
JennyHadir/AirBnB_clone_v2
0b588666cfa9388667d783cc985a1c724b8c4c63
7b9142af5f5d3baeb2710b496c1ad33e3a7c9097
refs/heads/master
2023-04-23T00:19:53.014097
2021-05-02T22:51:26
2021-05-02T22:51:26
353,387,833
1
0
null
null
null
null
UTF-8
Python
false
false
748
py
#!/usr/bin/python3 """ Start Flask web app """ from flask import Flask app = Flask(__name__) @app.route('/', strict_slashes=False) def index(): """ Return Hello hbnb """ return 'Hello HBNB!' @app.route('/hbnb', strict_slashes=False) def hello(): """ Return HBNB""" return 'HBNB' @app.route('/c/<text>', strict_slashes=False) def C(text): """ Return C followed by the value of text""" return 'C {}'.format(text.replace('_', ' ')) @app.route('/python', strict_slashes=False) @app.route('/python/<text>', strict_slashes=False) def python(text="is cool"): """ Return python followed by text""" return 'Python {}'.format(text.replace('_', ' ')) if __name__ == "__main__": app.run(host='0.0.0.0', port='5000')
[ "hadirjenny@hotmail.com" ]
hadirjenny@hotmail.com
85c0cef319283c90391f3ae6bd8515aeb296d20c
be39b5d60c0dc9894f744fda160176a77d5984be
/AmI-Labs/lab_6/tasksapi.py
8cf37a32bdf817c9726a828c78e9c584e5c104f5
[ "MIT" ]
permissive
AndreaCossio/PoliTo-Projects
2f67e7f8026a074428cf6547105292fc93934fc6
f89c8ce1e04d54e38a1309a01c7e3a9aa67d5a81
refs/heads/master
2023-01-04T23:35:24.092142
2020-11-02T11:10:02
2020-11-02T11:10:02
309,335,038
0
1
null
null
null
null
UTF-8
Python
false
false
1,537
py
import sqlite3 db = sqlite3.connect("tasks.db", check_same_thread=False) c = db.cursor() def close_db(): db.commit() db.close() def get_tasks(): query = "SELECT * FROM tasks" tasks = [] for task in c.execute(query).fetchall(): if task[2] == 1: tasks.append({"id": task[0], "todo": task[1], "urgent": True}) else: tasks.append({"id": task[0], "todo": task[1], "urgent": False}) return tasks def add_task(new_task, urgent): query = "INSERT INTO tasks(todo, urgent) VALUES(?,?)" if urgent: c.execute(query, (new_task, 1)) else: c.execute(query, (new_task, 0)) return True def update_task(task_id, upd_task, urgent): query = "UPDATE tasks SET todo=?, urgent=? WHERE id=?" if urgent: c.execute(query, (upd_task, 1, task_id)) else: c.execute(query, (upd_task, 0, task_id)) return True def delete_task(del_task): query = "SELECT COUNT(*) FROM tasks WHERE id=?" res = c.execute(query, (del_task,)).fetchone() if res[0] > 0: query = "DELETE FROM tasks WHERE id=?" c.execute(query, (del_task,)) return True else: return False def delete_task_match(match_sub): query = "SELECT COUNT(*) FROM tasks WHERE todo LIKE ?" res = c.execute(query, ("%" + match_sub + "%",)).fetchone() if res[0] > 0: query = "DELETE FROM tasks WHERE todo LIKE ?" c.execute(query, ("%" + match_sub + "%",)) return True else: return False
[ "andreacossio96@outlook.com" ]
andreacossio96@outlook.com
2dc222f0164479f150b85facb7f6757a9d7c5326
672c362b67de08e8aec1ada245aaf5482eca3134
/naoko/eliza.py
d20e29a5726842570248216982c8844013e0c3bc
[ "BSD-2-Clause" ]
permissive
karloor/kbot
518a68b652032d9e7f93fa1863b66bc5b6ab52f0
0502d1f2fd3450ac503d2d8fa27b2eacecc0434e
refs/heads/master
2021-01-23T03:44:19.387311
2014-07-05T02:33:54
2014-07-05T02:33:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,018
py
#---------------------------------------------------------------------- # eliza.py # # a cheezy little Eliza knock-off by Joe Strout <joe@strout.net> # with some updates by Jeff Epler <jepler@inetnebr.com> # hacked into a module and updated by Jez Higgins <jez@jezuk.co.uk> # last revised: 28 February 2005 #---------------------------------------------------------------------- import string import re import random euro = unichr(0x20ac) class eliza: def __init__(self): self.keys = map(lambda x:re.compile(x[0], re.IGNORECASE),gPats) self.values = map(lambda x:x[1],gPats) #---------------------------------------------------------------------- # translate: take a string, replace any words found in dict.keys() # with the corresponding dict.values() #---------------------------------------------------------------------- def translate(self,str,dict): words = string.split(string.lower(str)) keys = dict.keys(); for i in range(0,len(words)): if words[i] in keys: words[i] = dict[words[i]] return string.join(words) #---------------------------------------------------------------------- # respond: take a string, a set of regexps, and a corresponding # set of response lists; find a match, and return a randomly # chosen response from the corresponding list. #---------------------------------------------------------------------- def respond(self,str): # find a match among keys for i in range(0,len(self.keys)): match = self.keys[i].match(str) if match: # found a match ... stuff with corresponding value # chosen randomly from among the available options resp = random.choice(self.values[i]) # we've got a response... stuff in reflected text where indicated pos = string.find(resp,'%') while pos > -1: num = string.atoi(resp[pos+1:pos+2]) resp = resp[:pos] + \ self.translate(match.group(num),gReflections) + \ resp[pos+2:] pos = string.find(resp,'%') # fix munged punctuation at the end if resp[-2:] == '?.': resp = resp[:-2] + '.' if resp[-2:] == '??': resp = resp[:-2] + '?' return resp #---------------------------------------------------------------------- # gReflections, a translation table used to convert things you say # into things the computer says back, e.g. "I am" --> "you are" #---------------------------------------------------------------------- gReflections = { "am" : "are", "was" : "were", "i" : "you", "i'd" : "you would", "i've" : "you have", "i'll" : "you will", "my" : "your", "are" : "am", "you've": "I have", "you'll": "I will", "your" : "my", "yours" : "mine", "you" : "me", "me" : "you" } #---------------------------------------------------------------------- # gPats, the main response table. Each element of the list is a # two-element list; the first is a regexp, and the second is a # list of possible responses, with group-macros labelled as # %1, %2, etc. #---------------------------------------------------------------------- gPats = [ [r'I need (.*)', [ "Why do you need %1?", "Would it really help you to get %1?", "Are you sure you need %1?"]], [r'Why don\'?t you ([^\?]*)\??', [ "Do you really think I don't %1?", "Perhaps eventually I will %1.", "Do you really want me to %1?"]], [r'Why can\'?t I ([^\?]*)\??', [ "Do you think you should be able to %1?", "If you could %1, what would you do?", "I don't know -- why can't you %1?", "Have you really tried?"]], [r'I can\'?t (.*)', [ "How do you know you can't %1?", "Perhaps you could %1 if you tried.", "What would it take for you to %1?"]], [r'I am (.*)', [ "Did you come to me because you are %1?", "How long have you been %1?", "How do you feel about being %1?"]], [r'I\'?m (.*)', [ "How does being %1 make you feel?", "Do you enjoy being %1?", "Why do you tell me you're %1?", "Why do you think you're %1?"]], [r'Are you ([^\?]*)\??', [ "Why does it matter whether I am %1?", "Would you prefer it if I were not %1?", "Perhaps you believe I am %1.", "I may be %1 -- what do you think?"]], [r'What (.*)', [ "Why do you ask?", "How would an answer to that help you?", "What do you think?"]], [r'How (.*)', [ "How do you suppose?", "Perhaps you can answer your own question.", "What is it you're really asking?"]], [r'Because (.*)', [ "Is that the real reason?", "What other reasons come to mind?", "Does that reason apply to anything else?", "If %1, what else must be true?"]], [r'(.*) sorry (.*)', [ "There are many times when no apology is needed.", "What feelings do you have when you apologize?"]], [r'Hello(.*)', [ "Hello... I'm glad you could drop by today.", "Hi there... how are you today?", "Hello, how are you feeling today?"]], [r'I think (.*)', [ "Do you doubt %1?", "Do you really think so?", "But you're not sure %1?"]], [r'(.*) friend (.*)', [ "Tell me more about your friends.", "When you think of a friend, what comes to mind?", "Why don't you tell me about a childhood friend?"]], [r'Yes', [ "You seem quite sure.", "OK, but can you elaborate a bit?"]], [r'(.*) computer(.*)', [ "Are you really talking about me?", "Does it seem strange to talk to a computer?", "How do computers make you feel?", "Do you feel threatened by computers?"]], [r'Is it (.*)', [ "Do you think it is %1?", "Perhaps it's %1 -- what do you think?", "If it were %1, what would you do?", "It could well be that %1."]], [r'It is (.*)', [ "You seem very certain.", "If I told you that it probably isn't %1, what would you feel?"]], [r'Can you ([^\?]*)\??', [ "What makes you think I can't %1?", "If I could %1, then what?", "Why do you ask if I can %1?"]], [r'Can I ([^\?]*)\??', [ "Perhaps you don't want to %1.", "Do you want to be able to %1?", "If you could %1, would you?"]], [r'You are (.*)', [ "Why do you think I am %1?", "Does it please you to think that I'm %1?", "Perhaps you would like me to be %1.", "Perhaps you're really talking about yourself?"]], [r'You\'?re (.*)', [ "Why do you say I am %1?", "Why do you think I am %1?", "Are we talking about you, or me?"]], [r'I don\'?t (.*)', [ "Don't you really %1?", "Why don't you %1?", "Do you want to %1?"]], [r'I feel (.*)', [ "Good, tell me more about these feelings.", "Do you often feel %1?", "When do you usually feel %1?", "When you feel %1, what do you do?"]], [r'I have (.*)', [ "Why do you tell me that you've %1?", "Have you really %1?", "Now that you have %1, what will you do next?"]], [r'I would (.*)', [ "Could you explain why you would %1?", "Why would you %1?", "Who else knows that you would %1?"]], [r'Is there (.*)', [ "Do you think there is %1?", "It's likely that there is %1.", "Would you like there to be %1?"]], [r'My (.*)', [ "I see, your %1.", "Why do you say that your %1?", "When your %1, how do you feel?"]], [r'You (.*)', [ "We should be discussing you, not me.", "Why do you say that about me?", "Why do you care whether I %1?"]], [r'Why (.*)', [ "Why don't you tell me the reason why %1?", "Why do you think %1?" ]], [r'I want (.*)', [ "What would it mean to you if you got %1?", "Why do you want %1?", "What would you do if you got %1?", "If you got %1, then what would you do?"]], [r'(.*) mother(.*)', [ "Tell me more about your mother.", "What was your relationship with your mother like?", "How do you feel about your mother?", "How does this relate to your feelings today?", "Good family relations are important."]], [r'(.*) father(.*)', [ "Tell me more about your father.", "How did your father make you feel?", "How do you feel about your father?", "Does your relationship with your father relate to your feelings today?", "Do you have trouble showing affection with your family?"]], [r'(.*) child(.*)', [ "Did you have close friends as a child?", "What is your favorite childhood memory?", "Do you remember any dreams or nightmares from childhood?", "Did the other children sometimes tease you?", "How do you think your childhood experiences relate to your feelings today?"]], [r'(.*)\?', [ "Why do you ask that?", "Please consider whether you can answer your own question.", "Perhaps the answer lies within yourself?", "Why don't you tell me?"]], [r'quit', [ "Thank you for talking with me.", "Good-bye.", "Thank you, that will be " + euro + " 150. Have a good day!"]], [r'(.*)', [ "Please tell me more.", "Let's change focus a bit... Tell me about your family.", "Can you elaborate on that?", "Why do you say that... \"%1\"?", "I see.", "Very interesting.", "%1...", "I see. And what does that tell you?", "How does that make you feel?", "How do you feel when you say that?"]] ] #---------------------------------------------------------------------- # command_interface #---------------------------------------------------------------------- def command_interface(): print "Therapist\n---------" print "Talk to the program by typing in plain English, using normal upper-" print 'and lower-case letters and punctuation. Enter "quit" when done.' print '='*72 print "Hello. How are you feeling today?" s = "" therapist = eliza(); while s != "quit": try: s = raw_input(">") except EOFError: s = "quit" print s while s[-1] in "!.": s = s[:-1] print therapist.respond(s) if __name__ == "__main__": command_interface()
[ "karloor@xxxxx.xxx" ]
karloor@xxxxx.xxx
af730a03c3d04a9023386f8472a538484d80d340
719436bdc77b1b4065eb060a0bb700da51d4217a
/blogBackend/wsgi.py
2c0016574a8ede8ad2a0b58f1c05d55fb09e7614
[]
no_license
nazmulshuvo03/blog-backend
44da913f9bed25c5a40ce74ac5f19b96ca3f4c25
4f091ffd134fe22f552ccc40befdac64e6632bc7
refs/heads/master
2023-05-31T07:22:57.341219
2021-07-12T14:34:11
2021-07-12T14:34:11
376,314,960
1
0
null
null
null
null
UTF-8
Python
false
false
399
py
""" WSGI config for blogBackend project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogBackend.settings') application = get_wsgi_application()
[ "nazmulshuvo03@gmail.com" ]
nazmulshuvo03@gmail.com
2d15627e704d240070ba3cf7a030495f69a8e62c
fd4fde28029ea68e1d5971b0c3c907aabd949545
/day09/day9.py
199eefc71ab071a2faaa610bcaac6dcb053b2375
[]
no_license
kdeholton/AdventOfCode2020
1d2635d1e05af0f6926067302e01d4535ce8fa8f
b657da51509cb6bcc5d6729fdffdb99eab3fcf91
refs/heads/master
2023-02-02T07:48:18.501487
2020-12-21T05:08:14
2020-12-21T05:08:14
317,914,325
1
0
null
null
null
null
UTF-8
Python
false
false
1,304
py
#!/usr/bin/python3 import sys preamble_len = 25 preamble = [] sums = [] f = open("input", 'r') def valid_and_insert(num): def update_sums(preamble, sums, num): sum_list = [] for n in preamble: if n != num: sum_list.append(n + num) sums.append(sum_list) if(len(preamble) < preamble_len): preamble.append(num) update_sums(preamble, sums, num) assert len(sums) == len(preamble) return True else: for sum_list in sums: if num in sum_list: update_sums(preamble, sums, num) preamble.append(num) del sums[0] del preamble[0] assert len(sums) == len(preamble) return True return False def find_contiguous(num, f): val_list = [] sum = 0 f.seek(0) for line in f: line = int(line.strip()) sum += line val_list.append(line) while (sum > num): old_val = val_list.pop(0) sum -= old_val if sum == num: if (len(val_list) >= 2): print(val_list) return max(val_list) + min(val_list) else: old_val = val_list.pop(0) sum -= old_val bad_value = None for line in f: line = line.strip() if not valid_and_insert(int(line)): print(line) bad_value = int(line) break val = find_contiguous(bad_value, f) print(val)
[ "kdeholton@fitbit.com" ]
kdeholton@fitbit.com
69aef046542e64ea755986262147f1d5d88220c7
7e85bc4df823c9edd1ed4092bfb7723fc67eb435
/routers/process.py
c65270c8b4fb495b42697b055beb4a71b7f860cc
[]
no_license
rsharma093/messaging-queue
66d4a243fd1c39ab0d6410a4d6ce9f7c995bec7f
98592548c9042ef91c1448c996b9f58185b8dfaf
refs/heads/master
2023-02-23T19:23:11.315801
2021-01-28T16:32:49
2021-01-28T16:32:49
333,814,004
0
0
null
null
null
null
UTF-8
Python
false
false
1,291
py
from typing import List from fastapi import APIRouter, Depends from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session import deps from models import Process from schemas.process_schema import ProcessListModel, ProcessCreateModel router = APIRouter() @router.post("/add", response_model=ProcessListModel) def add_process(process_component: ProcessCreateModel, db: Session = Depends(deps.get_db)): """ Create Process """ return jsonable_encoder(Process.create(db=db, process_component=process_component)) @router.get("/status", response_model=List[ProcessListModel]) def queued_processes_list(db: Session = Depends(deps.get_db)): """ List queued processes """ return jsonable_encoder(Process.queued_processes_list(db=db)) @router.get("/status/{id}", response_model=ProcessListModel) def process_status_detail(id: int, db: Session = Depends(deps.get_db)): """ Get process status detail """ return jsonable_encoder(Process.process_status_detail(db=db, id=id)) @router.get("/output/{id}", response_model=ProcessListModel) def process_output_list(id: int, db: Session = Depends(deps.get_db)): """ Get process output detail """ return jsonable_encoder(Process.process_status_detail(db=db, id=id))
[ "rahul@codejudge.io" ]
rahul@codejudge.io
2eb104628e66eb7cc49c7062da1df470a397002f
e1bc86d23f41ac00bde29028985452a61c617a83
/orders/migrations/0010_auto_20200615_2010.py
265d787f4ae2fe6b33a9675fdc9a6db69f74a5f4
[]
no_license
parthjpatelx/project3
e7b58e50b1bc96414e238ef05f6717adb7b995c3
5629046ace2127cdf28aae318d7dc0de6432c388
refs/heads/master
2023-05-14T14:20:08.286912
2020-06-20T19:56:51
2020-06-20T19:56:51
272,101,787
0
0
null
2021-06-10T23:03:11
2020-06-13T23:29:47
Python
UTF-8
Python
false
false
549
py
# Generated by Django 3.0.7 on 2020-06-16 00:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('orders', '0009_auto_20200615_2002'), ] operations = [ migrations.RenameField( model_name='pastaprotein', old_name='name', new_name='protein', ), migrations.AlterField( model_name='pasta', name='price', field=models.FloatField(max_length=4), ), ]
[ "noreply@github.com" ]
parthjpatelx.noreply@github.com
f1d0bcb291d750ce2a690c507ebed0be84b835b6
a2a492fd3468de5c37d325f1fadc182dcd0f543f
/_sgdict.py
0e23477f643504f5b5c84bb391f74435c63a20d5
[]
no_license
MJmeow/sgd_dict
c7cfc25e43f60d82fb5df1004fa657a24de9bfb9
8b9d0a131530b97c2fdaa6815c76a5c033f55d7c
refs/heads/master
2021-01-13T15:46:37.691269
2016-12-19T16:27:16
2016-12-19T16:27:16
76,878,089
0
1
null
null
null
null
UTF-8
Python
false
false
1,865
py
import re def _sgdict( fastafile ): '''Reads a Saccharomyces Genome Database (SGD) fasta file and enables protein summary information access by trivial or systematic name :param fastafile: file path of fasta file. :returns: A dictionary with a protein's trivial and systematic name (uppercase!) as key to access SGD summary information (systematic name, trivial name, gene & protein description, sequence) ''' fastapattern = '(?P<sys>(\S{5,7}\s))(?P<triv>(\S{4,5}\s))(?P<descr>SGDID.+\n)(?P<seq>[A-Z\*\n]+)' #[\*\n) _stripline = lambda s: s.replace('\n', '').replace('\r', '').strip('*') with open(fastafile, 'rb') as openfile: #with: closes file at end of 'loop', also when error occurs and you don't reach file.close() readfile = openfile.read() #reads the whole file character by charactrer, incl. \n sgdict = dict() regex_fastapattern = re.compile(fastapattern, re.VERBOSE) #'save' regex pattern for further use, already compiled fastapattern_iters = regex_fastapattern.finditer(str(readfile)) #applies pattern to fastafile for iterable in fastapattern_iters: sys = iterable.group('sys').replace('>', '').strip() triv = iterable.group('triv').strip() descr = iterable.group('descr').replace('\n', '').strip() seq = _stripline(iterable.group('seq')) prot_info = {'sys': sys, 'triv': triv, 'descr': descr, 'seq': seq} sgdict[sys] = prot_info sgdict[triv] = prot_info return sgdict exampledata = #path sgd = _sgdict(exampledata) ''' Tasks: - check if protein 'HOG1' is in the list - check if protein 'TFC3' is a subunit of RNA polymerase III transcription initiation complex - print the first 10 aa of protein VPS8 and YAL003W :) '''
[ "noreply@github.com" ]
MJmeow.noreply@github.com
7686e9b6182e3cd24ef283df6a70af4c76228013
3f857f0b66a3416687e7ef62035e262d6dd2d398
/positiveornegative.py
9d9a4281433389809db941140ba9ead5cbc1656a
[]
no_license
joysreb/python
81d5fc08b1f3c36d481022f5f50d5b6f73807871
1c21103419c7af9dd2a4bf8182ef1f9770fa9055
refs/heads/master
2020-06-28T09:25:02.332493
2019-08-11T15:05:11
2019-08-11T15:05:11
200,198,178
0
0
null
null
null
null
UTF-8
Python
false
false
148
py
n=int(input("enter the number:")) if n>0: print("the number is positive") elif n<0: print("the number is negative") else: print("it is zero")
[ "noreply@github.com" ]
joysreb.noreply@github.com
e0be6b0c18a5aab2bb7e68c6c7b1817089aeb648
d5d9bfd07c83d2ec7c63a2e11605303727aa8c69
/term2/lab7_algo/greedyPermutations/prF.py
444a7eb56857cb695b79e60d1e4819bbdf4f857d
[]
no_license
VEK239/algo-labs
cce6f32430c71741614081412b39fffa73892f47
d2e01b52921f86f881ada60b2210d105da3efcf9
refs/heads/master
2022-03-05T01:33:05.624824
2019-12-02T09:16:45
2019-12-02T09:16:45
225,333,773
0
0
null
null
null
null
UTF-8
Python
false
false
1,156
py
def compZero(obj): return obj[0] def compOne(obj): return obj[1] def msort(lst): if len(lst) == 1: return lst; middle = len(lst) // 2 left = lst[:middle] right = lst[middle:] return mergesort(msort(left), msort(right)) def mergesort(left, right): i = 0 j = 0 result = [] global inversion invers = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 invers += len(left) - i if i < len(left): for k in range(i, len(left)): result.append(left[k]) else: for k in range(j, len(right)): result.append(right[k]) inversion += invers return result with open("john.in") as inf: n = int(inf.readline()) lst = [] for i in range(n): ls = list(map(int,inf.readline().split())) lst.append(ls) lst.sort(key=compOne) lst.sort(key=compZero) inversion = 0 invCountingList = msort([el[1] for el in lst]) with open("john.out", "w") as ouf: ouf.write(str(inversion))
[ "vlasova.elizaveta@yandex.ru" ]
vlasova.elizaveta@yandex.ru
b5848d7cd0cd43e8b1544e3bb1eb4b6bc0529c84
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/python/generated/test/test_com_day_cq_wcm_workflow_impl_workflow_package_info_provider_properties.py
8a3b1b6347423914590e0f49419cceb2580af28a
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
Python
false
false
1,389
py
# coding: utf-8 """ Adobe Experience Manager OSGI config (AEM) API Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API # noqa: E501 The version of the OpenAPI document: 1.0.0 Contact: opensource@shinesolutions.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import swaggeraemosgi from swaggeraemosgi.models.com_day_cq_wcm_workflow_impl_workflow_package_info_provider_properties import ComDayCqWcmWorkflowImplWorkflowPackageInfoProviderProperties # noqa: E501 from swaggeraemosgi.rest import ApiException class TestComDayCqWcmWorkflowImplWorkflowPackageInfoProviderProperties(unittest.TestCase): """ComDayCqWcmWorkflowImplWorkflowPackageInfoProviderProperties unit test stubs""" def setUp(self): pass def tearDown(self): pass def testComDayCqWcmWorkflowImplWorkflowPackageInfoProviderProperties(self): """Test ComDayCqWcmWorkflowImplWorkflowPackageInfoProviderProperties""" # FIXME: construct object with mandatory attributes with example values # model = swaggeraemosgi.models.com_day_cq_wcm_workflow_impl_workflow_package_info_provider_properties.ComDayCqWcmWorkflowImplWorkflowPackageInfoProviderProperties() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "michael.bloch@shinesolutions.com" ]
michael.bloch@shinesolutions.com
f47bfa385c4f0ab86dc4a71cb03429da9c5b9a1a
aa4b0fb980980aeca39c97152f36eb81ba110744
/ommelette new.py
c5051867438ba8a8c64cf4c6f75667df021ce1ee
[]
no_license
geekdudeAndrew/Python-Crash-Course
bcab7ffbf90cd772009b24f738e277720ab6aadb
088d226ab227a250181208b417801b660008d234
refs/heads/master
2020-05-16T14:29:58.624057
2019-12-29T20:30:31
2019-12-29T20:30:31
183,104,970
0
0
null
null
null
null
UTF-8
Python
false
false
1,407
py
#updated Ommlettte # Updated "pg53-63 ch4 Lists ommelette" with a while loop and user input # pretends to be a commandline game where you feed your neopet. # it has a funny ending. food = ['plain ommelette','pepperoni ommelette', 'green pepper ommelette', 'pepperoni and sausage ommelette', 'orange jelly', 'lime jelly', 'mint jelly', 'breadfish'] print ("\nYou have just spent hours playing dumb games on an internet site where you"); print ("pretend to have a strange pet like its 1999 or something. your pockets are full"); print ("of some wet food items that do not belong there. your pet Firelizard is hungry \n") while food: print ("This is what you have in your pockets: ") print (*food, sep = ', '); print ("\n"); eat = input ("Which food item do you want to feed to Sparky? "); if eat in food: print (eat + " mmm thats some good eatin. \nYour firelizard eyes you hungrly \n"); food.remove(eat); else: print: ("That doesnt make since \n"); print ("your pet Firelizard George, having just watched you stuff yourself, dies of "); print ("hunger. I guess you should have fed George sometime in the last 10 years sparky.\n") """ for food_item in food: print ("just ate a " + food_item.title() + " mmm thats some good eatin ") print ("yep nothin like a tasty " + food_item.title() + " I realy like " + food_item.title() +"s .\n") # plural nouns not propperly executed """
[ "andrew@andrewparker.info" ]
andrew@andrewparker.info
ec2055783557c9068cc9499ae3f3374aefc94887
9cb21560a6fbedfcdbef26a6f7e28996bc219039
/float.py
ea34d895a9be14ced71de2bfd6851febbbb4d8c6
[ "Apache-2.0" ]
permissive
BitJetKit/learnPython
d417a7ef44bbded5f14df941f13dc964c870d80b
85093c68362852db4413fe079e32445776ad1a52
refs/heads/main
2023-04-02T11:16:15.588109
2021-04-09T06:05:57
2021-04-09T06:05:57
356,151,915
0
0
null
null
null
null
UTF-8
Python
false
false
142
py
#float.py myfloat = 7.0 myfloat2 = 12.0 print(myfloat) print(myfloat2) myfloat = float(7) myfloat2 = float(12) print(myfloat) print(myfloat2)
[ "bitjetkit@gmail.com" ]
bitjetkit@gmail.com
f0a003d48d72094a494ef14e9919942c4c17ddf0
90419da201cd4948a27d3612f0b482c68026c96f
/sdk/python/pulumi_azure_nextgen/web/v20181101/list_web_app_site_push_settings.py
3fa3fe5ae5021d06c3748141d5039e0329e5c328
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
test-wiz-sec/pulumi-azure-nextgen
cd4bee5d70cb0d332c04f16bb54e17d016d2adaf
20a695af0d020b34b0f1c336e1b69702755174cc
refs/heads/master
2023-06-08T02:35:52.639773
2020-11-06T22:39:06
2020-11-06T22:39:06
312,993,761
0
0
Apache-2.0
2023-06-02T06:47:28
2020-11-15T09:04:00
null
UTF-8
Python
false
false
5,742
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'ListWebAppSitePushSettingsResult', 'AwaitableListWebAppSitePushSettingsResult', 'list_web_app_site_push_settings', ] @pulumi.output_type class ListWebAppSitePushSettingsResult: """ Push settings for the App. """ def __init__(__self__, dynamic_tags_json=None, is_push_enabled=None, kind=None, name=None, tag_whitelist_json=None, tags_requiring_auth=None, type=None): if dynamic_tags_json and not isinstance(dynamic_tags_json, str): raise TypeError("Expected argument 'dynamic_tags_json' to be a str") pulumi.set(__self__, "dynamic_tags_json", dynamic_tags_json) if is_push_enabled and not isinstance(is_push_enabled, bool): raise TypeError("Expected argument 'is_push_enabled' to be a bool") pulumi.set(__self__, "is_push_enabled", is_push_enabled) if kind and not isinstance(kind, str): raise TypeError("Expected argument 'kind' to be a str") pulumi.set(__self__, "kind", kind) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if tag_whitelist_json and not isinstance(tag_whitelist_json, str): raise TypeError("Expected argument 'tag_whitelist_json' to be a str") pulumi.set(__self__, "tag_whitelist_json", tag_whitelist_json) if tags_requiring_auth and not isinstance(tags_requiring_auth, str): raise TypeError("Expected argument 'tags_requiring_auth' to be a str") pulumi.set(__self__, "tags_requiring_auth", tags_requiring_auth) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter(name="dynamicTagsJson") def dynamic_tags_json(self) -> Optional[str]: """ Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint. """ return pulumi.get(self, "dynamic_tags_json") @property @pulumi.getter(name="isPushEnabled") def is_push_enabled(self) -> bool: """ Gets or sets a flag indicating whether the Push endpoint is enabled. """ return pulumi.get(self, "is_push_enabled") @property @pulumi.getter def kind(self) -> Optional[str]: """ Kind of resource. """ return pulumi.get(self, "kind") @property @pulumi.getter def name(self) -> str: """ Resource Name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="tagWhitelistJson") def tag_whitelist_json(self) -> Optional[str]: """ Gets or sets a JSON string containing a list of tags that are whitelisted for use by the push registration endpoint. """ return pulumi.get(self, "tag_whitelist_json") @property @pulumi.getter(name="tagsRequiringAuth") def tags_requiring_auth(self) -> Optional[str]: """ Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint. Tags can consist of alphanumeric characters and the following: '_', '@', '#', '.', ':', '-'. Validation should be performed at the PushRequestHandler. """ return pulumi.get(self, "tags_requiring_auth") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") class AwaitableListWebAppSitePushSettingsResult(ListWebAppSitePushSettingsResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListWebAppSitePushSettingsResult( dynamic_tags_json=self.dynamic_tags_json, is_push_enabled=self.is_push_enabled, kind=self.kind, name=self.name, tag_whitelist_json=self.tag_whitelist_json, tags_requiring_auth=self.tags_requiring_auth, type=self.type) def list_web_app_site_push_settings(name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListWebAppSitePushSettingsResult: """ Use this data source to access information about an existing resource. :param str name: Name of web app. :param str resource_group_name: Name of the resource group to which the resource belongs. """ __args__ = dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:web/v20181101:listWebAppSitePushSettings', __args__, opts=opts, typ=ListWebAppSitePushSettingsResult).value return AwaitableListWebAppSitePushSettingsResult( dynamic_tags_json=__ret__.dynamic_tags_json, is_push_enabled=__ret__.is_push_enabled, kind=__ret__.kind, name=__ret__.name, tag_whitelist_json=__ret__.tag_whitelist_json, tags_requiring_auth=__ret__.tags_requiring_auth, type=__ret__.type)
[ "public@paulstack.co.uk" ]
public@paulstack.co.uk
5f99c96f2004b72d78869fdf309d40eddab71b1f
e61ee083ed6e6a9ae9e088170fd3cc9d13343fd7
/ScrapyRedis/ScrapyRedis/pipelines.py
a727a1bc11424a791b5f96c0600bdc0030fbf0c7
[]
no_license
AaronChiu2017/ScrapyRedis-1
8befb9ad142c6a7a699d61614ba2bff64f6b6f87
de831e1df90d0fe0924737c79dd62375659fe15d
refs/heads/master
2020-11-26T20:11:38.136686
2019-09-04T07:05:47
2019-09-04T07:05:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,347
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import pymysql from twisted.enterprise import adbapi class ScrapyredisPipeline(object): def process_item(self, item, spider): return item class MysqlTwistedPipeline(object): def __init__(self, dbpool): self.dbpool = dbpool @classmethod def from_settings(cls, settings): dbparms = dict( host=settings['MYSQL_HOST'], db=settings['MYSQL_DBNAME'], user=settings['MYSQL_USER'], password=settings['MYSQL_PASSWORD'], # charset='utf-8', cursorclass=pymysql.cursors.DictCursor, use_unicode=True ) dbpool = adbapi.ConnectionPool('MySQLdb', **dbparms) return cls(dbpool) def process_item(self, item, spider): # 使用twisted 将mysql 插入变成异步 query = self.dbpool.runInteraction(self.do_insert, item) query.addErrback(self.handle_error) # 处理异常 def handle_error(self, failure): # 处理异常 print(failure) def do_insert(self, cursor, item): insert_sql, params = item.get_insert_sql() cursor.execute(insert_sql, params)
[ "griy26@163.com" ]
griy26@163.com
c5d45db9cdc37579b30539bc87d2cc9e11d67243
c2bb58282fbde971624cfc84291dff6ae5422ad6
/utilities.py
ca3e829fcc39e2bb14ca55c8d9b9ebc03f58f53a
[]
no_license
Adelax92/cv-aimbot
74d5937f1f88dc532d3b27ab5735ce7f05e97b96
fc0066f98ce62ef39693314cac86f44a347007bf
refs/heads/main
2023-08-24T02:15:05.331566
2021-10-15T04:44:56
2021-10-15T04:44:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,803
py
import cv2 import numpy as np from time import time, sleep from gamecapture import GameCapture from detection import Detection from vision import Vision class Utilities: def __init__(self): pass @staticmethod def check_fps(input_video): cap = cv2.VideoCapture(input_video) print(f'FPS: {cap.get(cv2.CAP_PROP_FPS)}') cap.release() # Multi thread # TODO: Refactor @staticmethod def fps_test(w, h, windowname = '', method = 'WIN32GUI'): # C: 162, 0.08039550722381215 # D: 13, 0.774630069732666 cap = GameCapture(w, h, windowname, method) cap.start() sleep(5) cap.stop() print(f'FPS: {int(cap.frame_number / 3)}') return int(cap.frame_number / 3) # Single thread def fps_test2(sw, sh, windowname = '', method = 'WIN32GUI'): capture = GameCapture(sw, sh, windowname, method) detector = Detection() vision = Vision() start = time() for _ in range(32): frame = capture.capture_frame() boxes = detector.detect(frame) target = vision.get_priority_target(boxes) frame = vision.draw_bounding_boxes(frame, boxes) frame = vision.draw_crosshair(frame, target) return int(32 / (time() - start)) # TODO: refactor @staticmethod def process_video(filename): cap = cv2.VideoCapture(f'data/{filename}') out = cv2.VideoWriter(f'output/{filename}', cv2.VideoWriter_fourcc(*'mp4v'), int(cap.get(cv2.CAP_PROP_FPS)), (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))) detector = Detection() vision = Vision() while cap.isOpened(): ret, frame = cap.read() if not ret: break pred = detector.detect(frame) target = vision.get_priority_target(pred) frame = vision.draw_bounding_boxes(frame, pred) frame = vision.draw_crosshair(frame, target) out.write(frame) out.release() cap.release() # TODO: refactor @staticmethod def alter_fps(input_video, output_video, scale): cap = cv2.VideoCapture(input_video) out = cv2.VideoWriter(f'{output_video}', cv2.VideoWriter_fourcc(*'mp4v'), int(cap.get(cv2.CAP_PROP_FPS) / scale), (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))) counter = 0 while cap.isOpened(): ret, frame = cap.read() if not ret: break if counter % scale == 0: out.write(frame) counter += 1 out.release() cap.release()
[ "ryan.sawchuk@dal.ca" ]
ryan.sawchuk@dal.ca
1738b28f3edae3209d50abf2e6c2d40c29b92839
5e553a5ad555ed6bf364373196a1c46b60b5f530
/src/aggregate_stats.py
1c8a5426504dfa708b27d844a0c920dbc0a1ee5a
[ "MIT" ]
permissive
satyakisikdar/infinity-mirror
8a7a0079648c523cf670f836a351b0317c15a870
555bcc7f4c481001991d53f3b90b03c1201a5c40
refs/heads/master
2022-12-08T20:05:56.242257
2022-06-22T16:45:44
2022-06-22T16:45:44
222,779,125
5
1
MIT
2022-12-08T04:32:00
2019-11-19T20:02:32
GAP
UTF-8
Python
false
false
8,600
py
import os import numpy as np import pandas as pd from scipy.stats import entropy from scipy.spatial import distance import src.graph_comparison def compute_mono_stat(dataset, model, stat, agg): def _convert(agg): for trial in agg.keys(): for gen in agg[trial].keys(): agg[trial][gen] = np.asarray(agg[trial][gen]) return agg def _unwrap(agg, model): for trial in agg.keys(): for gen in agg[trial].keys(): if agg[trial][gen] != {}: agg[trial][gen] = list(agg[trial][gen].values()) else: agg[trial][gen] = [] return agg def _normalize_graphlets(agg): for trial in agg.keys(): for gen in agg[trial].keys(): if agg[trial][gen] != {}: graphlets = agg[trial][gen] total = sum(graphlets.values()) for idx, count in graphlets.items(): if total != 0: graphlets[idx] = count/total else: graphlets[idx] = 0 agg[trial][gen] = graphlets return agg if stat == 'b_matrix': agg = _convert(agg) rows = portrait_js(dataset, model, agg) elif stat == 'degree_dist': rows = degree_js(dataset, model, agg) elif stat == 'laplacian_eigenvalues': agg = _convert(agg) rows = lambda_dist(dataset, model, agg) elif stat == 'netlsd': pass #TODO elif stat == 'pagerank': agg = _unwrap(agg, model) rows = pagerank_js(dataset, model, agg) elif stat == 'pgd_graphlet_counts': agg = _normalize_graphlets(agg) rows = pgd_rgfd(dataset, model, agg) elif stat == 'average_path_length': rows = average_path_length(dataset, model, agg) elif stat == 'average_clustering': rows = average_clustering(dataset, model, agg) elif stat == 'apl_cc': rows = apl_cc(dataset, model, agg) else: raise NotImplementedError return pd.DataFrame(rows) def compute_bi_stat(dataset, model, stat, agg1, agg2): if stat == 'apl_cc': rows = apl_cc(dataset, model, agg1, agg2) else: raise NotImplementedError return pd.DataFrame(rows) def apl_cc(dataset, model, agg1, agg2): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'clu': [], 'pl': []} for trial in agg1.keys(): for gen in agg1[trial].keys(): clu = agg1[trial][gen] pl = agg2[trial][gen] rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['clu'].append(clu) rows['pl'].append(pl) return rows def average_clustering(dataset, model, agg): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'avg_clustering': []} for trial in agg.keys(): for gen in agg[trial].keys(): avg_clustering = agg[trial][gen] rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['avg_clustering'].append(avg_clustering) return rows def average_path_length(dataset, model, agg): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'avg_pl': []} for trial in agg.keys(): for gen in agg[trial].keys(): avg_pl = agg[trial][gen] rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['avg_pl'].append(avg_pl) return rows def degree_js(dataset, model, agg): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'degree_js': []} for trial in agg.keys(): dist1 = agg[trial][0] for gen in agg[trial].keys(): if gen != 0: dist2 = agg[trial][gen] union = set(dist1.keys()) | set(dist2.keys()) for key in union: dist1[key] = dist1.get(key, 0) dist2[key] = dist1.get(key, 0) deg1 = np.asarray(list(dist1.values())) + 0.00001 deg2 = np.asarray(list(dist2.values())) + 0.00001 deg_js = distance.jensenshannon(deg1, deg2, base=2.0) rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['degree_js'].append(deg_js) return rows def lambda_dist(dataset, model, agg): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'lambda_dist': []} for trial in agg.keys(): u = agg[trial][0] for gen in agg[trial].keys(): if gen != 0: v = agg[trial][gen] m = min([u.shape[0], v.shape[0]]) L = np.sqrt(np.sum((u[:m] - v[:m])**2)) rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['lambda_dist'].append(L) return rows #TODO def netlsd(dataset, model, agg): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'netlsd': []} raise NotImplementedError def pagerank_js(dataset, model, agg): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'pagerank_js': []} for trial in agg.keys(): pr1 = agg[trial][0] for gen in agg[trial].keys(): if gen != 0: pr2 = agg[trial][gen] try: hist_upperbound = max(max(pr1), max(pr2)) except ValueError as e: continue g1_hist = np.histogram(pr1, range=(0, hist_upperbound), bins=100)[0] + 0.00001 g2_hist = np.histogram(pr2, range=(0, hist_upperbound), bins=100)[0] + 0.00001 pr_js = distance.jensenshannon(g1_hist, g2_hist, base=2.0) rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['pagerank_js'].append(pr_js) return rows def pgd_rgfd(dataset, model, agg): rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'pgd_rgfd': []} for trial in agg.keys(): for gen in agg[trial].keys(): rgfd = 0 first = agg[trial][0] if gen != 0: curr = agg[trial][gen] for graphlet in curr.keys(): rgfd += np.abs(first[graphlet] - curr[graphlet]) rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['pgd_rgfd'].append(rgfd) return rows def portrait_js(dataset, model, agg): def _pad_portraits_to_same_size(B1, B2): ns, ms = B1.shape nl, ml = B2.shape lastcol1 = max(np.nonzero(B1)[1]) lastcol2 = max(np.nonzero(B2)[1]) lastcol = max(lastcol1, lastcol2) B1 = B1[:, :lastcol + 1] B2 = B2[:, :lastcol + 1] BigB1 = np.zeros((max(ns, nl), lastcol + 1)) BigB2 = np.zeros((max(ns, nl), lastcol + 1)) BigB1[:B1.shape[0], :B1.shape[1]] = B1 BigB2[:B2.shape[0], :B2.shape[1]] = B2 return BigB1, BigB2 def _calculate_portrait_divergence(BG, BH): BG, BH = _pad_portraits_to_same_size(BG, BH) L, K = BG.shape V = np.tile(np.arange(K), (L, 1)) XG = BG * V / (BG * V).sum() XH = BH * V / (BH * V).sum() P = XG.ravel() Q = XH.ravel() M = 0.55 * (P + Q) KLDpm = entropy(P, M, base=2) KLDqm = entropy(Q, M, base=2) JSDpq = 0.5 * (KLDpm + KLDqm) return JSDpq rows = {'dataset': [], 'model': [], 'trial': [], 'gen': [], 'portrait_js': []} for trial in agg.keys(): for gen in agg[trial].keys(): if gen != 0: d = _calculate_portrait_divergence(agg[trial][0], agg[trial][gen]) rows['dataset'].append(dataset) rows['model'].append(model) rows['trial'].append(trial) rows['gen'].append(gen) rows['portrait_js'].append(d) return rows
[ "39937561+daniel-gonzalez-cedre@users.noreply.github.com" ]
39937561+daniel-gonzalez-cedre@users.noreply.github.com
5e070108afc7564e576cd0dfce999c5efde2f3a0
250dc34001c9234317ca82a321c0cb6355cc736e
/tracker.py
4ec4c46d055565102bd90db16a4997825ef7e83a
[]
no_license
ashutoshdhanda/opencvtracker
26fceb6dbc3d9831c581325bdae8b57c217e7626
54df1e1e4fdd2e50bb38ade32a9db498fb68cf25
refs/heads/master
2023-08-03T20:46:48.225237
2021-09-27T01:39:01
2021-09-27T01:39:01
410,374,806
0
0
null
null
null
null
UTF-8
Python
false
false
4,018
py
# python 3.9.7 # opencv 4.5.3 # opencv-contrib-python 4.5.3 # Color blue for nuerona boxes # Color green for tracker boxes # import the necessary packages from imutils.video import VideoStream import argparse import imutils import time import cv2 import pickle import sys # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", type=str, help="path to input video file") ap.add_argument("-t", "--tracker", type=str, default="kcf", help="OpenCV object tracker type") args = vars(ap.parse_args()) # initialize a dictionary that maps strings to their corresponding # OpenCV object tracker implementations OPENCV_OBJECT_TRACKERS = { "csrt": cv2.legacy.TrackerCSRT_create, "kcf": cv2.legacy.TrackerKCF_create, #"boosting": cv2.TrackerBoosting_create, "mil": cv2.legacy.TrackerMIL_create, "goturn" : cv2.TrackerGOTURN #"tld": cv2.TrackerTLD_create, #"medianflow": cv2.TrackerMedianFlow_create, #"mosse": cv2.TrackerMOSSE_create } # initialize OpenCV's special multi-object tracker trackers = cv2.legacy.MultiTracker_create() videofile_name = args["video"] full_string_size = len(videofile_name) name_string = videofile_name[:full_string_size-4] #print(name_string) pickle_str = name_string+'.pkl' detecciones=pickle.load(open(pickle_str,'rb')) # if a video path was not supplied, grab the reference to the web cam if not args.get("video", False): print("[INFO] starting video stream...") vs = VideoStream(src=0).start() time.sleep(1.0) # otherwise, grab a reference to the video file else: vs = cv2.VideoCapture(args["video"]) # loop over frames from the video stream while True: # grab the current frame, then handle if we are using a # VideoStream or VideoCapture object frame = vs.read() frame = frame[1] if args.get("video", False) else frame # check to see if we have reached the end of the stream if frame is None: break # resize the frame (so we can process it faster) frame = cv2.resize(frame, (416, 416),interpolation=cv2.INTER_LINEAR) # grab the updated bounding box coordinates (if any) for each # object that is being tracked (success, boxes) = trackers.update(frame) #print(type(boxes)) #print(boxes) # loop over the bounding boxes and draw them on the frame for box in boxes: #print("drawing tracking box") (x, y, w, h) = [int(v) for v in box] cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1) #pop out the first detection from detections (poping is permanently reducing detections list size by 1) deteccionesctuales=detecciones.pop(0) #if len(boxes)==0: #if deteccionesctuales: #for deteccionactual in deteccionesctuales: #x=int(deteccionactual[2][0]) #y=int(deteccionactual[2][1]) #w=int(deteccionactual[2][2]) #h=int(deteccionactual[2][3]) #l = int((x - w / 2) ) #r = int((x + w / 2) ) #t = int((y - h / 2)) #b = int((y + h / 2)) #print("drawing neurona box") #cv2.rectangle(frame,(l,t),(r,b),(0,0,255), 1) #frame = cv2.resize(frame, (416, 416),interpolation=cv2.INTER_LINEAR) #box1 = (l,t,r,b) #tracker = OPENCV_OBJECT_TRACKERS[args["tracker"]]() #trackers.add(tracker, frame, box1) if deteccionesctuales: for deteccionactual in deteccionesctuales: x=int(deteccionactual[2][0]) y=int(deteccionactual[2][1]) w=int(deteccionactual[2][2]) h=int(deteccionactual[2][3]) l = int((x - w / 2) ) r = int((x + w / 2) ) t = int((y - h / 2)) b = int((y + h / 2)) #print("drawing neurona box") #cv2.rectangle(frame,(l,t),(r,b),(0,0,255), 1) frame = cv2.resize(frame, (416, 416),interpolation=cv2.INTER_LINEAR) box1 = (l,t,r,b) tracker = OPENCV_OBJECT_TRACKERS[args["tracker"]]() trackers.add(tracker, frame, box1) cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break #time.sleep(0.1) if not args.get("video", False): vs.stop() # otherwise, release the file pointer else: vs.release() # close all windows cv2.destroyAllWindows()
[ "ashutosh@lythium.cl" ]
ashutosh@lythium.cl
b45e77fc38bd932f6b2ae9fc4c775a799688c0a3
9977239c7c1ed548003f164826acbf85cf6e3595
/tables.py
e43ef616376b01854f22381147764b00c0f25098
[]
no_license
MatteoDome/Marching-Cubes
14d7714e7ad59cd8fcdfbfc1676ca0be0dc02fd0
8bdc9ed3e640bc3d94ab4faba1cd65e800b98c8c
refs/heads/master
2021-06-06T05:38:34.156974
2016-09-15T09:28:56
2016-09-15T09:28:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
16,664
py
edgeTable[256]={ 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0}; triTable[256][16] = {{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}};
[ "mdomenighini@gmail.com" ]
mdomenighini@gmail.com
0605b5b2bfb94b96a725b13cc7d09f818e02c4cc
47a667b92487986135d199d80eab0211127fd0cc
/car_recognition/car_sql/car_spot.py
0db9406c14edb954751e7c3f08fbc549e784cafa
[ "Apache-2.0" ]
permissive
hxf-v/car-management
d6867451380c649e817c52fdd3a069e3c1f54b33
d83af28073a0dde0d81660e9cba588e1a920c9ad
refs/heads/master
2022-12-05T10:07:03.636057
2020-08-27T08:31:20
2020-08-27T08:31:20
290,709,176
0
0
Apache-2.0
2020-08-27T08:32:01
2020-08-27T07:36:50
Java
UTF-8
Python
false
false
1,630
py
import sys import cv2 import numpy as np import HyperLPRLite as pr # from PIL import Image # from PIL import ImageDraw from PIL import ImageFont from datetime import datetime from pandas import DataFrame import imp imp.reload(sys) fontC = ImageFont.truetype("Font/platech.ttf", 14, 0) ''' # 从本地读取图片并做识别,返回所有识别到车牌的【返回车牌号,置信度, 文件路径, 默认的待处理状态, 拍照时间】 # smallest_confidence:最小置信度 ''' def recognize_plate(pict, take_pic_time, used_file, car_location, state='待处理', smallest_confidence=0.7, car_color="黑色"): image = cv2.imdecode(np.fromfile(pict, dtype=np.uint8), -1) model = pr.LPR("model/cascade.xml", "model/model12.h5", "model/ocr_plate_all_gru.h5") # 训练好的模型参数 res_model = model.SimpleRecognizePlateByE2E(image) return_all_plate = [] if res_model.__len__() == 0: # 若未识别出车牌,直接返回 return take_pic_time = datetime.strptime(take_pic_time, '%Y%m%d%H%M%S') # 字符串转datetime类型 for pstr, confidence, rect in res_model: confidence = round(confidence, 2) if confidence > smallest_confidence: # 返回车牌号,置信度, 文件路径, 默认的待处理状态, 拍照时间 return_all_plate.append([pstr, confidence, used_file, state, take_pic_time, car_color, car_location]) # list转DataFrame用于后续存数据库 df = DataFrame(return_all_plate, columns=['car_id', 'confidence', 'pic_path', 'state', 'take_time', 'car_color', 'car_location']) return df
[ "1414451346@qq.com" ]
1414451346@qq.com
3fed4f51dba1623c41f303d5f0bf90b15dd73ddf
3221296be066406bdceb530a486b5753825d3ac1
/dorMat.py
484be8e6a1ad9fd94e264f69e96e23d30844d7fe
[]
no_license
guptaShantanu/Python-Programs
c6bd397215743f40eb885c645e0331e6f9e764ed
b1e01b86a2a53f8c7195660367f667a84493d56e
refs/heads/master
2022-11-16T22:42:06.133930
2020-07-14T03:22:34
2020-07-14T03:22:34
271,881,341
0
0
null
null
null
null
UTF-8
Python
false
false
243
py
n,w=input().split() n=int(n) w=int(w) j=1 for i in range(1,int(((n-1)/2))+1): print((".|."*j).center(w,"-")) j+=2 print('WELCOME'.center(w,'-')) j-=2 for i in range(1,int(((n-1)/2))+1): print((".|."*j).center(w,"-")) j-=2
[ "officialshantanugupta08@gmail.com" ]
officialshantanugupta08@gmail.com
8777d2c310b1aa4d0ca9ea406d7f2be3a476339e
793cc5d048c2830a285d197037cab5f8f157065c
/train.py
a0a886d99ffc5d3ce6f78b304cffac257bec4e61
[]
no_license
profects/codebythesea-tensorflow
8a7ccf60b1ad578af78a7bbac462708e6fd3dc1a
35555e1a12cf6bfe17608871d9da346317712d8d
refs/heads/master
2020-03-07T13:59:24.930787
2018-04-24T11:01:38
2018-04-24T11:01:38
127,515,749
2
2
null
2018-04-24T11:01:39
2018-03-31T08:53:09
Python
UTF-8
Python
false
false
7,914
py
from datetime import datetime import tensorflow as tf import dataset # # Initialize variables # batch_size = 32 # Prepare input data classes = ['hotdog', 'not-hotdog'] num_classes = len(classes) # 20% of the data will automatically be used for validation validation_size = 0.3 img_size = 128 num_channels = 3 train_path = 'images' # We shall load all the training and validation images and labels into memory using openCV and use that during training data = dataset.read_train_sets(train_path, img_size, classes, validation_size=validation_size) print("Complete reading input data. Will Now print a snippet of it") print("Number of files in Training-set:\t\t{}".format(len(data.train.labels))) print("Number of files in Validation-set:\t{}".format(len(data.valid.labels))) # # Set the in- and output variables of the model and add them to the graph # session = tf.Session() x = tf.placeholder(tf.float32, shape=[None, img_size, img_size, num_channels], name='x') # labels y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true') y_true_cls = tf.argmax(y_true, dimension=1) # Network graph parameters filter_size_conv1 = 3 num_filters_conv1 = 32 filter_size_conv2 = 3 num_filters_conv2 = 32 filter_size_conv3 = 3 num_filters_conv3 = 64 fc_layer_size = 128 # # Define helper functions to create the layers of the model # def create_weights(shape): new_weights = tf.Variable(tf.truncated_normal(shape, stddev=0.05)) # with tf.name_scope('summary'): # tf.summary.histogram(new_weights) return new_weights def create_biases(size): return tf.Variable(tf.constant(0.05, shape=[size])) def create_convolutional_layer(input, num_input_channels, conv_filter_size, num_filters): # We shall define the weights that will be trained using create_weights function. weights = create_weights(shape=[conv_filter_size, conv_filter_size, num_input_channels, num_filters]) # We create biases using the create_biases function. These are also trained. biases = create_biases(num_filters) # Creating the convolutional layer layer = tf.nn.conv2d(input=input, filter=weights, strides=[1, 1, 1, 1], padding='SAME') layer += biases # We shall be using max-pooling. layer = tf.nn.max_pool(value=layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Output of pooling is fed to Relu which is the activation function for us. layer = tf.nn.relu(layer) return layer def create_flatten_layer(layer): # We know that the shape of the layer will be [batch_size img_size img_size num_channels] # But let's get it from the previous layer. layer_shape = layer.get_shape() # Number of features will be img_height * img_width* num_channels. But we shall calculate it in place of hard-coding it. num_features = layer_shape[1:4].num_elements() # Now, we Flatten the layer so we shall have to reshape to num_features layer = tf.reshape(layer, [-1, num_features]) return layer def create_fc_layer(input, num_inputs, num_outputs, use_relu=True): # Let's define trainable weights and biases. weights = create_weights(shape=[num_inputs, num_outputs]) biases = create_biases(num_outputs) # Fully connected layer takes input x and produces wx+b.Since, these are matrices, we use matmul function in Tensorflow layer = tf.matmul(input, weights) + biases if use_relu: layer = tf.nn.relu(layer) return layer layer_conv1 = create_convolutional_layer(input=x, num_input_channels=num_channels, conv_filter_size=filter_size_conv1, num_filters=num_filters_conv1) layer_conv2 = create_convolutional_layer(input=layer_conv1, num_input_channels=num_filters_conv1, conv_filter_size=filter_size_conv2, num_filters=num_filters_conv2) layer_conv3 = create_convolutional_layer(input=layer_conv2, num_input_channels=num_filters_conv2, conv_filter_size=filter_size_conv3, num_filters=num_filters_conv3) layer_flat = create_flatten_layer(layer_conv3) layer_fc1 = create_fc_layer(input=layer_flat, num_inputs=layer_flat.get_shape()[1:4].num_elements(), num_outputs=fc_layer_size, use_relu=True) layer_fc2 = create_fc_layer(input=layer_fc1, num_inputs=fc_layer_size, num_outputs=num_classes, use_relu=False) y_pred = tf.nn.softmax(layer_fc2, name='y_pred') y_pred_cls = tf.argmax(y_pred, dimension=1) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2, labels=y_true) cost = tf.reduce_mean(cross_entropy) optimizer = tf.train.AdamOptimizer(learning_rate=5e-6).minimize(cost) correct_prediction = tf.equal(y_pred_cls, y_true_cls) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.name_scope('summary'): tf.summary.histogram('loss function', accuracy) # Merge all the summaries and write them out to /tmp/mnist_logs (by default) merged = tf.summary.merge_all() current_time = datetime.now().strftime("%Y%m%d-%H%M") train_writer = tf.summary.FileWriter('./logs/{}/train'.format(current_time), session.graph) test_writer = tf.summary.FileWriter('./logs/{}/test'.format(current_time)) session.run(tf.global_variables_initializer()) def show_progress(epoch, feed_dict_train, feed_dict_validate, val_loss): acc = session.run(accuracy, feed_dict=feed_dict_train) val_acc = session.run(accuracy, feed_dict=feed_dict_validate) msg = "Training Epoch {0} --- Training Accuracy: {1:>6.1%}, Validation Accuracy: {2:>6.1%}, Validation Loss: {3:.3f}" print(msg.format(epoch + 1, acc, val_acc, val_loss)) total_iterations = 0 saver = tf.train.Saver() # # Run the model: do the training phase of the model # def train(num_iteration): global total_iterations for i in range(total_iterations, total_iterations + num_iteration): x_batch, y_true_batch, _, cls_batch = data.train.next_batch(batch_size) x_valid_batch, y_valid_batch, _, valid_cls_batch = data.valid.next_batch(batch_size) feed_dict_tr = {x: x_batch, y_true: y_true_batch} feed_dict_val = {x: x_valid_batch, y_true: y_valid_batch} session.run(optimizer, feed_dict=feed_dict_tr) accuracy_summary, _ = session.run([merged, accuracy], feed_dict=feed_dict_tr) train_writer.add_summary(accuracy_summary, i) if i % int(data.train.num_examples / batch_size) == 0: val_loss_summary, val_loss = session.run([merged, cost], feed_dict=feed_dict_val) epoch = int(i / int(data.train.num_examples / batch_size)) show_progress(epoch, feed_dict_tr, feed_dict_val, val_loss) accuracy_summary, _ = session.run([merged, accuracy], feed_dict=feed_dict_val) test_writer.add_summary(val_loss_summary, i) test_writer.add_summary(accuracy_summary, i) saver.save(session, './model/hotdog-classifier') total_iterations += num_iteration if __name__ == '__main__': train(num_iteration=3000)
[ "kees.meliefste@yoursurprise.com" ]
kees.meliefste@yoursurprise.com
f9661a847e427ab18ad2344d279823200eb50f26
2626f6e6803c8c4341d01f57228a0fe117e3680b
/students/BrandonHenson/Lesson02/generators.py
8db9a884d80435aa3a12223bbb00ef5711c8c4c3
[]
no_license
kmsnyde/SP_Online_Course2_2018
9e59362da253cdec558e1c2f39221c174d6216f3
7fe8635b47d4792a8575e589797260ad0a2b027e
refs/heads/master
2020-03-19T17:15:03.945523
2018-09-05T22:28:55
2018-09-05T22:28:55
136,750,231
0
0
null
2018-06-09T19:01:52
2018-06-09T19:01:51
null
UTF-8
Python
false
false
441
py
# Brandon Henson # Python 220 # Lesson 2 # 6-29-18 # !/usr/bin/env python3 import pandas as pd from operator import itemgetter music = pd.read_csv("featuresdf.csv") def music_generator(a): for i in a: yield i selection = (x for x in zip(music.name, music.artists, music.danceability, music.loudness) if x[1] == 'Ed Sheeran') ed_sheeran = music_generator(selection) print(next(ed_sheeran))
[ "kmsnyder2@verizon.net" ]
kmsnyder2@verizon.net
6a56db3d8803a59882843bacb14f932b62239eba
ea17d14813ab70dd3fb3f766a39a122b7a61967c
/udp_time_server.py
37346b5a5160f719bc20ae6e09a3a55620606a29
[]
no_license
mucollabo/IntroducingPython
8e03545e8285ca76fa8b7006dec87d8247cd7214
7fe763187b83d951a8bdec6add8ebc2924586baf
refs/heads/master
2023-02-26T13:15:53.531109
2021-02-03T14:17:23
2021-02-03T14:17:23
288,616,614
0
0
null
null
null
null
UTF-8
Python
false
false
507
py
from datetime import datetime import socket address = ('localhost', 6789) max_size = 4096 print('Starting the server at', datetime.now()) print('Waiting for a client to call.') server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(address) while True: data, client_addr = server.recvfrom(max_size) if data == b'time': now = str(datetime.utcnow()) data = now.encode('utf-8') server.sendto(data, client_addr) print('Server sent', data) server.close()
[ "mucollabo@gmail.com" ]
mucollabo@gmail.com
c703e4a0aaced87b0a9cd9da5c6c62b6471e0fae
234f3eb000da9f244380b35c45a1a94905df1deb
/blog/models.py
830a8f1211f2f85c877f0d35b9b0e9174e17b86c
[]
no_license
awakeharu/p_rogramming-5th
05d252cf2209160a65f02f632c2dbb38ab7d5d45
f6034771dae0654f912a913486c1ec98ecbc997e
refs/heads/master
2021-01-20T20:09:20.415253
2016-07-12T07:42:10
2016-07-12T07:42:10
63,129,872
0
0
null
null
null
null
UTF-8
Python
false
false
770
py
from django.db import models import re from django.db import models from django.forms import ValidationError from django.utils import timezone def lenlat_validator(lanlat): if not re.match(r'^(\d+\.?\d*),(\d+\.?\d*)$',lanlat ): raise froms.ValidationError('Invalid LngLat Type') class Post(models.Model): title = models.CharField(max_length=100, verbose_name='제목') content = models.TextField(help_text='Markdown 문법을 써주세요.') tags = models.CharField(max_length=100, blank=True) lanlat = models.CharField(max_length=50, validators=[lenlat_validator], help_text='경도, 위도 포맷으로 입력') created_at = models.DateTimeField(default=timezone.now) test_field = models.IntegerField(default=10)
[ "haru_o@naver.com" ]
haru_o@naver.com
d5de92fa3845274053a191c69b2c273112816be7
4d1d3b37d6c1a08dff8343cf19fa95bb36f3942e
/Учеба/Sechin/Учеба/ВКР 4 курс/minimal-generator-master/MinGen/min_gen.py
ece392c5b17a8c8eeb6da99a006ce42769309a02
[]
no_license
Mikel4u4u/minimal-generator-master
e2ec80a443ddb6ccf40d9f42bb18aa0e568d8878
fb7a389e507d7fdc25ddb310c05e042ade63d454
refs/heads/master
2023-06-04T23:41:58.230917
2021-07-01T13:58:54
2021-07-01T13:58:54
382,050,128
0
0
null
null
null
null
UTF-8
Python
false
false
8,891
py
from openpyxl.styles import Color, PatternFill, Font, Border from MinGen.dataclasses import PromRow import openpyxl class MinGen: def __init__(self, signs_count, objects_count, data): self.signs_count = signs_count self.objects_count = objects_count self.data = self._form_data(data) self.prom_tab = self._make_prom_tab() self.result = [] self.resulti = [] self.gener = [] @staticmethod def _form_data(data): formed_data = [] for i in data: formed_row = [] for j in i: formed_row.append(j) formed_data.append(formed_row) return formed_data def print_data(self): print(' '.join(self.chars)) for i in range(self.objects_count): print(' '.join([str(j) for j in self.data[i]])) def print_result(self): for res in self.result: print(res) def print_prom_tab(self): data_to_print = [['X', 'K', 'X\'', 'X"' ]] for i in self.prom_tab: data_to_print.append([i.X_name, '+' if i.Key else '-', ''.join([str(j) for j in i.X_1]), i.X_2]) for row in data_to_print: text = '' for i in row: text += i + ' ' * (10 - len(i)) print(text) def _intersect(self, lst): if not lst: return [1] * self.signs_count res = [] for i in range(len(lst[0])): if sum([lst[j][i] for j in range(len(lst))]) == len(lst): res.append(1) else: res.append(0) return res def _union(self, lst): if not lst: return [0] * self.signs_count res = [] for i in range(len(lst[0])): if sum([lst[j][i] for j in range(len(lst))]) > 0: res.append(1) else: res.append(0) return res def _list_from_chars(self, chars): res = [] for i in range(self.signs_count): if self.chars[i] in chars: res.append(1) else: res.append(0) return res def _chars_from_str(self, string): res = [] for i in self.chars: if i in string: res.append(i) return res def _chars_from_list(self, lst): res = "" for i in range(len(lst)): if lst[i]: res += self.chars[i] return res if res else 'ø' def _get_objects_by_signs(self, signs_indexes): objects = [] for j in range(len(self.data)): if sum([self.data[j][i] for i in signs_indexes]) == len(signs_indexes): objects.append(j) return objects def _get_objects_by_char(self, char): index = self.chars.index(char) return self._get_objects_by_signs([index]) def _get_objects_by_x(self, x): signs_indexes = [] for i in range(len(self.chars)): if x.find(self.chars[i]) != -1: signs_indexes.append(i) return self._get_objects_by_signs(signs_indexes) def _get_x_2_lst_from_objects(self, objects): obj_lists = [self.data[i] for i in range(self.objects_count) if i in objects] x_2_lst = self._intersect(obj_lists) return x_2_lst @property def chars(self): chars = [] for i in range(self.signs_count): char = chr(ord('A') + i ) chars.append(char) return chars def _make_prom_tab(self): prom_tab = [] for char in self.chars: lst = self._list_from_chars(char) x_1 = self._get_objects_by_char(char) x_2_lst = self._get_x_2_lst_from_objects(x_1) x_2 = self._chars_from_list(x_2_lst) prom_tab.append(PromRow(char, x_2, x_1, x_2, x_2_lst,)) return prom_tab def _approx(self, x: str): signs_x_2 = [prom_row.X_2_lst for prom_row in self.prom_tab if x.find(prom_row.X_name) != -1] return self._chars_from_list(self._union(signs_x_2)) @staticmethod def _get_sublist(lst): return [[j for j in lst if j != i] for i in lst] def _is_equal_names(self, name1, name2): return set(self._chars_from_str(name1)) == set(self._chars_from_str(name2)) def _name1_contain_name2(self, name1, name2): for char in self._chars_from_str(name2): if char not in name1: return False return True def _name1_del_name2(self, name1,name2): x_chars = self._chars_from_str(name2) for i in x_chars: name1 = name1.replace(i, '') return name1 def _get_row_by_name(self, row_name): all_known_rows = self.prom_tab + self.result for row in all_known_rows: if self._is_equal_names(row.X_name, row_name): return row def _is_key(self, x: str,type): x_chars = self._chars_from_str(x) if len(x_chars) == 1: return True chars_subsets = self._get_sublist(x_chars) for chars_subset in chars_subsets: substring = ''.join(chars_subset) if not self._is_key(substring,type): return False substring_row = self._get_row_by_name(substring) if type == 'Apr': if self._name1_contain_name2(substring_row.X_Apr, x): return False else: if self._name1_contain_name2(substring_row.X_2, x): return False return True def check(self): for i in self.result: x_1 = self._get_objects_by_x(i.X_name) x_2_lst = self._get_x_2_lst_from_objects(x_1) x_2 = self._chars_from_list(x_2_lst) i.X_1 = x_1 i.X_2_lst = x_2_lst i.X_2 = x_2 i.Key = self._is_key(i.X_name,'X_2') def gen_next(self,iter): if iter == 1: t = self.prom_tab else: t = self.resulti for i in t: if i.Key: self.gener.append(i.X_name) y = Apgen(self.gener, len(self.gener)) self.resulti.clear() self.gener.clear() for x in y: self.resulti.append( PromRow( x, self._approx(x), 0, 0, 0, self._is_key(x,'Apr') ) ) self.result.extend(self.resulti) def gen_all(self): for iter in range(1,100): self.gen_next(iter) def save_all_to_excel(self): wb = openpyxl.Workbook() ws1 = wb.get_active_sheet() ws1.title = 'Input' ws1.append(['G\\M'] + self.chars) for i in range(self.objects_count): ws1.append([i] + self.data[i]) ws2 = wb.create_sheet('Output') ws2.append([ 'X', 'K', 'X+', 'X\'', 'X"','З','Л.С.']) for i in self.prom_tab: ws2.append([i.X_name, '+' if i.Key else '-', i.X_Apr, ''.join(map(str, i.X_1)) if i.X_1 else 'ø', i.X_2 if i.X_2 else 'ø','+' if i.X_name == i.X_2 else '-', '-']) for i in self.result: ws2.append([ i.X_name, '+' if i.Key else '-',i.X_Apr, ''.join(map(str, i.X_1)) if i.X_1 else 'ø', i.X_2 if i.X_2 else 'ø','+' if i.X_name == i.X_2 else '-', '+' if i.X_Apr == i.X_2 else '-']) ws3 = wb.create_sheet('Minmax AR') ws3.append(['X -> ','X"'," ",'X -> ', 'X"\X ' ]) for i in self.prom_tab: if i.Key and i.X_1 : ws3.append([i.X_name + " ->",i.X_2 if i.X_2 else 'ø'," ", i.X_name + " ->" if self._name1_del_name2(i.X_2,i.X_name) else '' ,self._name1_del_name2(i.X_2,i.X_name)]) for i in self.result: if i.Key and i.X_1 and i.X_Apr != i.X_2 : ws3.append([i.X_name + " ->", i.X_2 if i.X_2 else 'ø', " ", i.X_name + " ->" if self._name1_del_name2(i.X_2, i.X_name) else '', self._name1_del_name2(i.X_2, i.X_name)]) wb.save('output.xlsx') def Apgen(Itemset, lenght): canditate = [] for i in range(0, lenght): element = str(Itemset[i]) for j in range(i + 1, lenght): element1 = str(Itemset[j]) if element[0:(len(element) - 1)] == element1[0:(len(element1) - 1)]: unionset = element[0:(len(element) - 1)] + element1[len(element1) - 1] + element[ len(element) - 1] unionset = ''.join(sorted(unionset)) canditate.append(unionset) return canditate
[ "mikle22qwaszx@mail.ru" ]
mikle22qwaszx@mail.ru
bd0de741af6c7ac0bc0a67b0fcaae54bac565a5b
d858be58a35bc3322a5dec5cb8dd3bae8747e238
/securitybot/secretsmgmt/secretsmgmt.py
c640f4806ae3f393770285656c8b8088406fefbd
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
gyrospectre/securitybot
149d67747496ed5d1b59054ea52a396e39d94f18
90db2ae532667c48ca080108b895c2e1fe16b1e8
refs/heads/master
2022-10-09T16:36:21.780554
2020-06-14T03:04:44
2020-06-14T03:04:44
267,812,032
3
1
Apache-2.0
2020-06-14T03:04:46
2020-05-29T08:56:26
Python
UTF-8
Python
false
false
736
py
''' A wrapper over an abstract secrets management system. ''' __author__ = 'Bill Mahony' from abc import ABCMeta, abstractmethod class BaseSecretsClient(object, metaclass=ABCMeta): ''' A wrapper over various secrets management frameworks, like Vault. ''' @abstractmethod def __init__(self, reauth_time, auth_attrib): ''' Initialise default values for global config and connects to the secrets management system. ''' pass @abstractmethod def get_secret(self, secret): '''Fetch a secret from the backend''' pass @abstractmethod def create_secret(self, name, value, description): '''Store a new secret in the backend''' pass
[ "noreply@github.com" ]
gyrospectre.noreply@github.com
03ff35a6aa111d03dd40e338b9c8d5ff469fbf96
0ae8ba26a59179ec39176522d6b5320738bf6623
/OCRModel.py
5a76eace54bbee7102d9625d8799f67c804d30ba
[]
no_license
prerna-agarwal/OpticalWordRecognition
1d530663c19ca68ca670a32542dd9fb536be6ec2
31e41b8627f3ce397c426ebdb4cf4411de035965
refs/heads/master
2021-01-11T23:42:02.404000
2017-01-11T09:40:05
2017-01-11T09:40:05
78,624,227
0
0
null
null
null
null
UTF-8
Python
false
false
1,964
py
import itertools import math count1=0 total=0 count2=0 characters=['d','o','i','r','a','h','t','n','s','e'] with open("C:\Users\Adarsh Agarwal\Downloads\hw2\ocr.dat", "r") as f: lines=f.readlines() with open("C:\Users\Adarsh Agarwal\Downloads\hw2\data.dat", "r") as f,open("C:\Users\Adarsh Agarwal\Downloads\hw2\otruth.dat", "r") as f1: words=f.readlines() original=f1.readlines() for j in range(0,len(words)): new_word='' word=words[j] org=original[j] org=org[:-1] orig=list(original[j]) word=word.split() for k in range(0,len(word)): max=0 char='' for i in range(0,10): line=lines[int(word[k])*10+i] line=line.split() if max<float(line[2]): max=float(line[2]) char=line[1] new_word=new_word+char total=total+1 if char==orig[k]: count1=count1+1 if new_word==org: count2=count2+1 print "Character Wise: "+`float(count1)/float(total)*100.0` print "Word Wise: "+`float(count2)/float(len(words))*100.0` #Exhaustive inference loglike=0.0 count1=count2=0 for i in range(0,len(words)): permute=[] z=0.0 max=0 new_word='' word=words[i].split() org=original[i] for j in range(0,len(word)): permute.append(characters) for element in itertools.product(*permute): value=1.0 string='' for j in range(0,len(element)): #value=value+math.log10(float(lines[int(word[j])*10+characters.index(element[j])].split()[2])) value=value*float(lines[int(word[j])*10+characters.index(element[j])].split()[2]) z=z+value for c in element: string=string+c if max<value: max=value new_word=string if string==org[:-1]: temp=value print z loglike=loglike+math.log10(float(temp)/float(z)) for x in range(0,len(new_word)): if new_word[x]==org[x]: count1=count1+1 if new_word==org[:-1]: count2=count2+1 print "Exhaustive" print count1,count2 print "Average Log likelihood: "+`float(loglike)/float(len(words))`
[ "noreply@github.com" ]
prerna-agarwal.noreply@github.com
4b6f497444a623bf6a45124d81cc92f91b1ad2d2
ca6b0f5ac984e757daf5242f8faf0f83d2cc06bc
/apps/member/migrations/0001_initial.py
9e8aa1602d038606ab25adcbb7640808f0837970
[]
no_license
oppongntiamoah/Church-Database
04a7a6b3d827fc07b7556fde75bab052454d5131
0f63dd2e31449e19da43298142a26e77ded91826
refs/heads/master
2023-02-02T14:54:42.372388
2020-12-23T13:02:47
2020-12-23T13:02:47
320,276,131
0
0
null
null
null
null
UTF-8
Python
false
false
5,270
py
# Generated by Django 3.1.3 on 2020-11-30 11:37 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ ('event', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('location', '0001_initial'), ] operations = [ migrations.CreateModel( name='Member', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(blank=True, max_length=20)), ('first_name', models.CharField(max_length=50)), ('middle_name', models.CharField(blank=True, max_length=50)), ('last_name', models.CharField(max_length=50)), ('date_joined', models.DateField()), ('dob', models.DateField()), ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=1)), ('marital_status', models.CharField(choices=[('m', 'Married'), ('d', 'Divorce'), ('w', 'Widowed'), ('s', 'Single')], max_length=1)), ('phone_number', phonenumber_field.modelfields.PhoneNumberField(max_length=128, region=None)), ('email', models.EmailField(blank=True, max_length=254, unique=True)), ('photo', models.ImageField(blank=True, upload_to='upload')), ('note', models.TextField(blank=True)), ('occupation', models.CharField(blank=True, max_length=255)), ('workplace', models.CharField(blank=True, max_length=255)), ('school', models.CharField(blank=True, max_length=120)), ('date_added', models.DateTimeField(auto_now_add=True)), ('address', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='location.address')), ], options={ 'verbose_name': 'Member', 'verbose_name_plural': "Member's", }, ), migrations.CreateModel( name='Visitor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(blank=True, max_length=20)), ('first_name', models.CharField(max_length=50)), ('middle_name', models.CharField(blank=True, max_length=50)), ('last_name', models.CharField(max_length=50)), ('age', models.PositiveSmallIntegerField()), ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=1)), ('phone_number', phonenumber_field.modelfields.PhoneNumberField(max_length=128, region=None)), ('email', models.EmailField(blank=True, max_length=254, unique=True)), ('marital_status', models.CharField(choices=[('m', 'Married'), ('d', 'Divorce'), ('w', 'Widowed'), ('s', 'Single')], max_length=1)), ('date', models.DateField()), ('occupation', models.CharField(blank=True, max_length=255)), ('workplace', models.CharField(blank=True, max_length=255)), ('school', models.CharField(blank=True, max_length=120)), ('status', models.CharField(choices=[('f', 'First Time Visitor'), ('r', 'Returning Visitor')], max_length=1)), ('reason', models.CharField(choices=[('c', 'Would like to know more about the Church'), ('m', 'Would like to be a member'), ('v', 'Would like a Visit'), ('a', 'New to area'), ('b', 'Would like to know more being a Christian')], max_length=1)), ('note', models.TextField(blank=True)), ('address', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='location.address')), ('event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='event.event')), ('guest_of', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='member.member')), ('received_by', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Visitor', 'verbose_name_plural': "Visitor's", }, ), migrations.CreateModel( name='Attendance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('men', models.PositiveIntegerField()), ('women', models.PositiveIntegerField()), ('children', models.PositiveIntegerField()), ('visitors', models.PositiveIntegerField()), ('date', models.DateField()), ('note', models.TextField(blank=True)), ('event', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='event.event')), ], ), ]
[ "ladamob47@gmail.com" ]
ladamob47@gmail.com
2174a6e8d34fb1c4121f2546de5d41cbf9c61272
8a365e31119ab89064c604bcc550af2de757f56f
/src/Mona_WebApp/thisEnv/bin/pip-3.6
52cd672db9d6bb8ceabb74001d2db1de507acae9
[]
no_license
shananlynch/2020-ca400-lynchs43-afanaa2
b5a17be1752ef1ee8a47b72dc4f46ef624ea8a8e
ccb469cc971e9bdeb8c53b29decb8db9c485a7ef
refs/heads/master
2023-04-08T07:07:57.782427
2020-05-19T01:08:12
2020-05-19T01:08:12
355,993,738
0
0
null
null
null
null
UTF-8
Python
false
false
277
6
#!/home/ubuntu/2020-ca400-template-repo/src/Mona_WebApp/thisEnv/bin/python # -*- coding: utf-8 -*- import re import sys from pip._internal.cli.main import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "ubuntu@ip-172-31-16-165.eu-west-1.compute.internal" ]
ubuntu@ip-172-31-16-165.eu-west-1.compute.internal
d13ad55dcb3b69e5e9bca92f2da2199d7526b165
60e83ab32df87f0461db87a2e304d2dab389de9d
/tests/test_util.py
19a9a84af987e4670a932d0e491cfac9629ef705
[ "MIT" ]
permissive
jarrah42/original-nbgrader
2671cce9959727aa3fea43b0656a80fa1653dfdf
bef9c9249be0b67e3f940086e6ee58d6f8bb5a3e
refs/heads/master
2021-01-24T05:05:53.435593
2014-09-26T19:55:55
2014-09-26T19:55:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
878
py
from IPython.nbformat.current import NotebookNode from nbgrader import util def test_get_assignment_cell_type_default(): """Is the cell type '-' when the assignment metadata is missing?""" cell = NotebookNode() cell.metadata = {} cell_type = util.get_assignment_cell_type(cell) assert cell_type == '-' def test_get_assignment_cell_type_default2(): """Is the cell type '-' when the assignment cell type is missing?""" cell = NotebookNode() cell.metadata = {'assignment': {}} cell_type = util.get_assignment_cell_type(cell) assert cell_type == '-' def test_get_assignment_cell_type_given(): """Is the cell type correct when the assignment metadata is present?""" cell = NotebookNode() cell.metadata = dict(assignment=dict(cell_type="foo")) cell_type = util.get_assignment_cell_type(cell) assert cell_type == "foo"
[ "jhamrick@berkeley.edu" ]
jhamrick@berkeley.edu
c11d111424c3043c44dddf567cad80556971299a
cde8c0355321e804aa8fa78d6e97c2c94b5781b2
/Aula34/view/web.py
754859242c81c906ff2ec25d81358ac77308be7f
[ "MIT" ]
permissive
marcelabbc07/TrabalhosPython
22677c6a37b8145a282ea2b15428356c3a20e568
91734d13110e4dee12a532dfd7091e36394a6449
refs/heads/master
2020-09-05T21:27:30.761501
2020-01-29T13:16:20
2020-01-29T13:16:20
220,218,836
0
0
null
null
null
null
UTF-8
Python
false
false
644
py
from flask import Flask, render_template import sys sys.path.append('C:/Users/900146/Documents/git/TrabalhosPython/Aula34') from controller.pessoa_controller import PessoaController app = Flask(__name__) pessoa_controller = PessoaController() nome = 'Cadastros' @app.route('/') def inicio(): return render_template('index.html', titulo_app = nome ) @app.route('/listar') def listar(): pessoas = pessoa_controller.listar_todos() return render_template('listar.html', titulo_app = nome, lista = pessoas) @app.route('/cadastrar') def cadastrar(): return render_template('cadastrar.html', titulo_app = nome) app.run(debug=True)
[ "marcelabbc07@gmail.com" ]
marcelabbc07@gmail.com
ef4547d5d06ac0bb96d7e7870395956660231be5
99d48c033581cd3b38ce1f5dab136dd7dd3de3a9
/models/logistic_model.py
e3342ca6bac35a14eba881df22ea66c7437db094
[]
no_license
samfway/university_network
eb7846b096624f0129620bce258da6edaede62a5
9d7c07d79a425adb8a3536e012ede6adb72a4b67
refs/heads/master
2019-01-02T08:36:05.620066
2015-08-22T22:00:29
2015-08-22T22:00:29
25,659,619
0
0
null
null
null
null
UTF-8
Python
false
false
5,302
py
#!/usr/bin/env python __author__ = "Sam Way" __copyright__ = "Copyright 2014, The Clauset Lab" __license__ = "BSD" __maintainer__ = "Sam Way" __email__ = "samfway@gmail.com" __status__ = "Development" from numpy import array, exp, mean, delete, inf, dot from numpy.random import randn, choice from university_network.misc.scoring import sse_rank_diff def sigmoid(x): return 1. / (1. + exp(-x)) class LogisticModelSimulator: def __init__(self, cand_pools, job_pools, school_info, ranking='pi', features=[None, 'pi'], weights=[0,1.0], iters=10, reg=0.): self.cand_pools = cand_pools self.job_pools = job_pools self.school_info = school_info self.ranking = ranking self.features = features self.weights = weights self.model = LogisticModel() self.iterations = iters self.num_pools = len(cand_pools) self.regularization = reg if len(cand_pools) != len(job_pools): raise ValueError("Job/Candidate pools must be of equal length!") self.worst_rank = 0 for s in school_info: if ranking in school_info[s] and school_info[s][ranking] > self.worst_rank: self.worst_rank = school_info[s][ranking] def simulate(self, weights): total_err = 0.0 # L2 Regularization Penalty w = array(weights[1:]) l2_penalty = dot(w,w) * self.regularization for t in xrange(self.iterations): for i in xrange(self.num_pools): hires = self.model.simulate_hiring(self.cand_pools[i], self.job_pools[i], self.school_info, self.ranking, self.features, weights) total_err += sse_rank_diff(hires, self.school_info, self.worst_rank) total_err += l2_penalty return total_err class LogisticModel: def __init__(self): pass def simulate_hiring(self, candidates, positions, school_info, ranking='pi', features=[None, 'pi'], weights=[0, 1.0]): """ Simulate faculty hiring under the sigmoid (logistic regression) model. Algorithm: [ FILL THIS OUT ] Returns a list of tuples: [(candidate, position), (candidate, position), ... ] Inputs: - 'candidates' is a list of faculty profiles. - 'positions' is a list of school names. - 'school_info' is a dict indexed by school name, providing information like rank, region, etc. As an assumption, I will say that any unranked school is effectively tied for last place. A small amount of noise is added to their ranking to serve as a tie-breaker. Haven't heard of that school? We'll assume the hiring committee hasn't either, and you get no bonus points for prestige. """ if len(features) != len(weights): raise ValueError('Feature/weight vectors must be of equal length.') if features[0] is not None: raise ValueError('First feature must be None (offset term)') weights = array(weights) rankings = array([school_info[s][ranking] for s in school_info]) rankings.sort() worst_ranking = rankings[-1] best_ranking = rankings[0] delta = mean(rankings[1:] - rankings[0:-1]) scale = lambda x: 1. - (x-best_ranking)/(worst_ranking-best_ranking+delta) # Delta ensures all schools have a positive rank jobs = positions[:] job_ranks = [] for j in jobs: if j in school_info: job_ranks.append(scale(school_info[j][ranking])) else: job_ranks.append(scale(worst_ranking)) job_ranks = array(job_ranks) candidate_pool = candidates[:] candidate_ranks = [] for f in candidates: place, year = f.phd() if place in school_info: candidate_ranks.append(scale(school_info[place][ranking])) else: candidate_ranks.append(scale(worst_ranking)) candidate_ranks = array(candidate_ranks) hires = [] while jobs: # Select job job_p = job_ranks.copy() job_p /= job_p.sum() job_ind = choice(xrange(len(job_p)), p=job_p) job_rank = job_ranks[job_ind] # Select candidate cand_p = array([sigmoid(sum(weights * array([1, candidate_rank-job_rank]))) for candidate_rank in candidate_ranks]) cand_p /= cand_p.sum() cand_ind = choice(xrange(len(cand_p)), p=cand_p) # Save then remove from lists hires.append((candidate_pool[cand_ind], jobs[job_ind])) del candidate_pool[cand_ind] del jobs[job_ind] candidate_ranks = delete(candidate_ranks, cand_ind) job_ranks = delete(job_ranks, job_ind) return hires
[ "samfway@gmail.com" ]
samfway@gmail.com
755dd8feef89359c3506135487f3c7b52132ff87
b887da155f41432b36d6c9513706eac6ffc1370e
/usep_app/urls_app.py
250459185e03f633be7e2a9570e7af9034635158
[ "MIT" ]
permissive
zaaakk/usepweb_project
ab99f7e318a3d4817863c6cedfb207e38aa22dbc
8da6db9e47f51bb46c7b6a9524359d356d7362fc
refs/heads/master
2020-07-16T04:56:49.967741
2018-07-09T17:09:43
2018-07-09T17:09:43
73,951,564
0
0
null
2016-11-16T19:03:25
2016-11-16T19:03:24
null
UTF-8
Python
false
false
1,365
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import patterns, include, url from django.views.generic import RedirectView urlpatterns = patterns('', url( r'^info/$', 'usep_app.views.hi', name='info_url' ), url( r'^collections/$', 'usep_app.views.collections', name='collections_url' ), url( r'^collections/(?P<collection>[^/]+)/$', 'usep_app.views.collection', name='collection_url' ), url( r'^inscription/(?P<inscription_id>[^/]+)/$', 'usep_app.views.display_inscription', name='inscription_url' ), url( r'^publications/$', 'usep_app.views.publications', name='publications_url' ), url( r'^publication/(?P<publication>[^/]+)/$', 'usep_app.views.pub_children', name='publication_url' ), url( r'^texts/$', 'usep_app.views.texts', name='texts_url' ), url( r'^links/$', 'usep_app.views.links', name='links_url' ), url( r'^about/$', 'usep_app.views.about', name='about_url' ), url( r'^contact/$', 'usep_app.views.contact', name='contact_url' ), url( r'^search/$', 'usep_app.search.search_form', name='search_url'), # url( r'^search/results/$', 'usep_app.views.coming', name='search_results_url'), url( r'^search/results/$', 'usep_app.search.results', name='search_results_url'), url( r'^$', RedirectView.as_view(pattern_name='collections_url') ), )
[ "birkin.diana@gmail.com" ]
birkin.diana@gmail.com
b0faa2fc8be42222635917ab9d3e82138a8f88ae
f63fabc9645df3228bac5b28c375fe1a4b8e15a6
/v3.3/result.py
e9a7fedc5261f1bf24350e196aa630fc993e9f9b
[]
no_license
James992927108/6.GWGHA_SUMO
23e7813470a1e078837b1385b061a7f4acf60331
201541d54154d17e631551ec48af8c629d2fa29f
refs/heads/master
2022-03-05T16:12:49.070776
2019-11-10T14:36:10
2019-11-10T14:36:10
219,684,518
0
0
null
null
null
null
UTF-8
Python
false
false
1,142
py
import numpy as np class result(): def __init__(self,position,SimulateResult_List): self.position = position self.SimulateResult_List = SimulateResult_List self.evaluation_list = np.asarray([x[0] for x in SimulateResult_List]) self.convergence_list = self.get_convergence_list() self.min_fitness = min(self.evaluation_list) self.complete_veh_num_list = np.asarray([x[1] for x in SimulateResult_List]) self.complete_veh_duration_time_list = np.asarray([x[2] for x in SimulateResult_List]) self.incomplete_veh_duration_time_list = np.asarray([x[3] for x in SimulateResult_List]) self.total_veh_duration_time_list = np.asarray([x[4] for x in SimulateResult_List]) self.waiting_time_list = np.asarray([x[5] for x in SimulateResult_List]) def get_convergence_list(self): temp_convergence_list = [] temp = float("inf") for x in self.SimulateResult_List: if x[0] < temp: temp = x[0] temp_convergence_list.append(temp) return np.asarray(temp_convergence_list)
[ "james992927108@gmail.com" ]
james992927108@gmail.com
34a71f68d7888f745816aa393a1328f5df369da3
490850f712195ae62358a7f935eff300a46b01ad
/Rabbitmq-Python-Examples/route_send.py
e3ca417dde6c354ca61d9634a3500fa5a5e7bba5
[]
no_license
rangershs/Miscellaneous
95ef0749b1ec8a85253eea7f7fccec48fd6ac553
0e899950a83aaf6b5d26acd93346ccbae928d46f
refs/heads/master
2021-01-01T20:01:53.296640
2020-03-24T01:45:37
2020-03-24T01:45:37
98,741,319
0
0
null
null
null
null
UTF-8
Python
false
false
737
py
#!/usr/bin/python3 import pika import sys import time if __name__ == '__main__': connection = pika.BlockingConnection( pika.ConnectionParameters(host='172.81.240.3')) channel = connection.channel() channel.exchange_declare(exchange='direct_logs', exchange_type='direct') # severity = sys.argv[1] if len(sys.argv) > 1 else 'info' # message = ' '.join(sys.argv[2:]) or 'Hello World!' severities = ('info', 'warning', 'error') for i in range(0, 120): index = i % 3 severity = severities[index] message = 'Route log message' + ' ' + str(i) channel.basic_publish( exchange='direct_logs', routing_key=severity, body=message) print(" [x] Sent %r:%r" % (severity, message)) time.sleep(0.5) connection.close()
[ "rangershs@163.dom" ]
rangershs@163.dom
dce01d28d3c97e0e4973377788da9b3805018cb2
bb81c12c2d391a8d18073d8fef055a9893655e60
/boxspring/error_ode.py
42bb97e6c1202b11a84d19eaab273c291f12c265
[]
no_license
georgkuenze/ScientificComputingPython
77dc06a55e2daecb64c6d6a37d1235661993bbed
89b475578753660d48d868e37fa063076a176c1d
refs/heads/master
2021-01-10T11:19:55.508164
2016-02-03T23:48:12
2016-02-03T23:48:12
51,037,498
0
0
null
null
null
null
UTF-8
Python
false
false
2,255
py
# -*- coding: utf-8 -*- """ Created on Fri Oct 09 15:42:24 2015 @author: Georg """ from ode_project import init_prms, solve import numpy as np import matplotlib.pyplot as plt import glob, os for filename in glob.glob('tmp_errors*.pdf'): os.remove(filename) def exact_S_solution(t): return g*(1 - np.cos(t)) ## Default values m = 1; b = 2; L = 10; k = 1; beta = 0; S0 = 0; dt = 2*np.pi/40; g = 9.81; w_formula='0'; N = 200 m, b, L, k, beta, S0, dt, g, w, N = init_prms(m, b, L, k, beta, S0, dt, g, w_formula, N) def w(t): return 0 S = solve(m, k, beta, S0, dt, g, w, N) S = np.array(S) tcoor = np.linspace(0, N*dt, len(S)) exact = exact_S_solution(tcoor) error = exact - S fig1, (ax1, ax2) = plt.subplots(1,2) ax1.plot(tcoor, S, 'r-', label='numeric solution') ax1.plot(tcoor, exact, 'b-', label='exact solution') ax1.set_xlabel('time'); ax1.set_ylabel('S'); ax1.legend(loc=1) ax2.plot(tcoor, error, 'b-', label='error') ax2.set_xlabel('time'); ax2.set_ylabel('error'); ax2.legend(loc=1) fig1.show() fig1.savefig('tmp_errors_1.pdf') fig2 = plt.figure() dt = 2*np.pi/10 tstop = 8*np.pi N = int(tstop/dt) for i in range(6): dt /= 2.0 N *= 2 S = solve(m, k, beta, S0, dt, g, w, N) S = np.array(S) tcoor = np.linspace(0, tstop, len(S)) exact = exact_S_solution(tcoor) abserror = abs(exact - S) logerror = np.log10(abserror[1:]) plt.plot(tcoor[1:], logerror) plt.xlabel('time'); plt.ylabel('log(absolute error)') plt.hold('on') fig2.show() fig2.savefig('tmp_errors_2.pdf') fig3 = plt.figure() dt = 2*np.pi/10 tstop = 8*np.pi N = int(tstop/dt) for i in range(6): dt /= 2.0 N *= 2 S = solve(m, k, beta, S0, dt, g, w, N) S = np.array(S) tcoor = np.linspace(0, tstop, len(S)) exact = exact_S_solution(tcoor) abserror = abs(exact - S) logerror = np.log10(abserror[1:]) if i > 0: logerror_diff = logerror_prev - logerror[::2] plt.plot(tcoor[1::2], logerror_diff) plt.xlabel('time'); plt.ylabel('difference of log(absolute error)') plt.hold('on') meandiff = np.mean(logerror_diff) print 'average log10(abs(error)) difference: %g' % meandiff logerror_prev = logerror fig3.show() fig3.savefig('tmp_errors_3.pdf')
[ "georg.kuenze@vanderbilt.edu" ]
georg.kuenze@vanderbilt.edu
8938685a63e79ce0d432f78ba32c0ba2b83b0e2a
0ac279a95162b777c7dccddb29c7b237b791e884
/LDA.py
f7bb0a2e01ff0ee584fe2527134be2ff32c8f384
[]
no_license
piraog/PatternRecognition-mnist
0702f89827352b8e0b491235082426be1b1d5c01
71351259ccc60708903fceb8082573e9891982af
refs/heads/master
2020-04-01T00:24:07.805577
2018-10-16T08:01:06
2018-10-16T08:01:06
152,695,008
0
0
null
null
null
null
UTF-8
Python
false
false
6,385
py
import os import numpy as np import matplotlib.pyplot as plt from scipy import linalg as la from mnist import * from collections import Counter from mpl_toolkits.mplot3d import axes3d, Axes3D from sklearn import neighbors def LDA(data, target, dims_rescaled_data=2): '''main LDA function given the data, compute the LDA matrix and returns: - the data projected along the dims_rescaled_data most important eigenvectors - the eigenvalues - the eigenvectors ''' n = len(data) mean = data.mean(axis=0) Sw = np.zeros((data.shape[1],data.shape[1])) Sb = np.zeros((data.shape[1],data.shape[1])) for cat in range(10): idx = target==cat data_cat = data[idx] n_cat = len(data_cat) mean_cat = data_cat.mean(axis=0) S = 1/n_cat * np.matmul((data_cat-mean_cat).T,data_cat-mean_cat) Sw += n_cat/n * S Sb += n_cat/n * np.matmul((mean_cat-mean).reshape(len(mean),1),(mean_cat-mean).reshape(1,len(mean))) LDA = la.inv(Sw)*Sb # calculate eigenvectors & eigenvalues of the covariance matrix # use 'eigh' rather than 'eig' since R is symmetric, # the performance gain is substantial evals, evecs = la.eig(LDA) # sort eigenvalue in decreasing order idx = np.argsort(evals)[::-1] evecs = evecs[:,idx] # sort eigenvectors according to same index evals = evals[idx] # select the first n eigenvectors (n is desired dimension # of rescaled data array, or dims_rescaled_data) evecs = evecs[:, :dims_rescaled_data] # carry out the transformation on the data using eigenvectors # and return the re-scaled data, eigenvalues, and eigenvectors return np.dot(data,evecs), evals, evecs def plot_eig(data, target,image_shape, nb_vects=10): '''Plots the nb_vects most weighted eigenvectors of the LDA matrix obtained with data''' _, _, evecs = LDA(data, target, nb_vects) print(np.amax(evecs),np.amin(evecs)) indices = np.array(range(nb_vects)) images = data[indices].reshape((nb_vects, image_shape[0], image_shape[1])) for i, image in enumerate(images): plt.subplot(5, 5, i+1) plt.imshow(image, cmap='Greys', vmin=0, vmax=255, interpolation='none') plt.title(str(i)) frame = plt.gca() frame.axes.get_xaxis().set_visible(False) frame.axes.get_yaxis().set_visible(False) plt.tight_layout() plt.show() def plot_lda(data,target): '''Plots the vectors of data projected in 2D using 2 dimensions LDA''' fig = plt.figure(figsize = (8,8)) ax = fig.add_subplot(1,1,1) ax.set_xlabel('Projection direction 1', fontsize = 15) ax.set_ylabel('Projection direction 2', fontsize = 15) ax.set_title('2 Component LDA', fontsize = 20) from sklearn.discriminant_analysis import LinearDiscriminantAnalysis clf = LinearDiscriminantAnalysis() proj_data = clf.fit_transform(data, target)[:,:2] #proj_data,_,_ = LDA(data,target) targets = [0,1,2,3,4,5,6,7,8,9] colors = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'] for target, color in zip(targets,colors): indicesToKeep = Y == target ax.scatter(proj_data[indicesToKeep,0] , proj_data[indicesToKeep,1] , c = color , s = 2) ax.legend(targets) ax.grid() plt.show() def plot_lda_3D(data,target): '''Plots the vectors of data projected in 3D using 3 dimensions LDA''' fig = plt.figure(figsize = (8,8)) ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('Projection direction 1', fontsize = 15) ax.set_ylabel('Projection direction 2', fontsize = 15) ax.set_zlabel('Projection direction 3', fontsize = 15) ax.set_title('3 Component LDA', fontsize = 20) from sklearn.discriminant_analysis import LinearDiscriminantAnalysis clf = LinearDiscriminantAnalysis() proj_data = clf.fit_transform(data, target)[:,:3] targets = [0,1,2,3,4,5,6,7,8,9] colors = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'] for target, color in zip(targets,colors): indicesToKeep = Y == target ax.scatter(proj_data[indicesToKeep,0] , proj_data[indicesToKeep,1] , proj_data[indicesToKeep,2] , c = color , s = 2) ax.legend(targets) ax.grid() plt.show() def lda_1NN(train, Y, test, Y_test, dim_rescale): '''Trains the 1 nearest neighbour algorithm over data, projected along dim_rescale directions using LDA and print the accuracy on test projected along the same directions as data''' from sklearn.discriminant_analysis import LinearDiscriminantAnalysis clf = LinearDiscriminantAnalysis() proj_train = clf.fit_transform(train, Y)[:,:dim_rescale] proj_test = clf.transform(test)[:,:dim_rescale] #compute distance of the results with the training set and select the closest neighboor NN = neighbors.KNeighborsClassifier(1, weights='distance') NN.fit(proj_train,Y) results = NN.predict(proj_test) accuracy = sum(results==Y_test)/len(Y_test) print(accuracy) if __name__=='__main__': #import the datasets X, image_shape, Y = get_training_set('mnist') X_test, (_, _), Y_test = get_test_set('mnist') #normalise and cropp the images (4 pixels margin) X = X.astype(np.float64).reshape(60000,28,28)[:,4:24,4:24] X = X.reshape(60000,400) X = (X-X.mean(axis=0))/263 X_test = X_test.astype(np.float64).reshape(10000,28,28)[:,4:24,4:24] X_test = X_test.reshape(10000,400) X_test = (X_test-X_test.mean(axis=0))/263 #LDA(X,Y) #plot_lda(X, Y) plot_lda_3D(X, Y) #plot_eig(X,Y,(20,20),25) #lda_1NN(X,Y,X_test,Y_test,2) #0.440 #good for some classes (0.84 for class2), bad for others (0.26 for class3) #lda_1NN(X,Y,X_test,Y_test,3) #0.667 #lda_1NN(X,Y,X_test,Y_test,9) #0.899 #so not so good since we can't get a high enough number of dimensions to get enough precision #since 10 categories, the largest number of dim obtainable is 9 #proof: the 11th eigenvalue is close to 0, ame for all the 11+ eigenvalues
[ "marc@belicards.com" ]
marc@belicards.com
9315aa48f18e5eddb37b3a5db1a1286ae868d27d
f3fe8c80c185e02381983a4b18da40164fb72667
/simplecrm/opportunities/views.py
37ef4cb6812dff65a80e9e17be051d94c5dac082
[]
no_license
Sasikumar-P/djangorestheroku
8181ba5dfc7bdfad725d3ba350b31e091de4a668
8ccc5d9cbfbd5a6f0c237765b33492f56e8b2e05
refs/heads/master
2020-04-04T19:37:00.476232
2018-11-05T12:56:42
2018-11-05T12:56:42
156,213,282
0
0
null
null
null
null
UTF-8
Python
false
false
502
py
from django.shortcuts import render # Create your views here. from django.shortcuts import render from rest_framework import generics from opportunities.models import Opportunity from opportunities.serializers import OpportunitySerializer from rest_framework.permissions import IsAdminUser # Create your views here. class OpportunityListAPIView(generics.ListCreateAPIView): queryset = Opportunity.objects.all() serializer_class = OpportunitySerializer #permission_classes = (IsAdminUser,)
[ "sasi.p@vvdntech.in" ]
sasi.p@vvdntech.in
d07f9a6fbf9e7d93bf459013eb9a11b848f329b0
e888ccffbfe27138ea72f208ef6ff1d50b0e422a
/main.py
7b306ed73de8f802a13fa0033b5167ead0ebec5b
[ "MIT" ]
permissive
jmadler/nyc-tax-calc
2178fc2715745afa047902348781b969a4fb64f9
441c43e2e565d500ec09f43923bc4a630d28695c
refs/heads/master
2020-06-26T08:53:38.524750
2014-10-26T23:35:51
2014-10-26T23:35:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,669
py
#!/usr/bin/env python from bottle import Bottle, template, request from nyctax import tax_calc bottle = Bottle() def valid_home(value): permitted = ['NYC'] if value in permitted: return value else: raise Exception def valid_int(value): if value.isdigit and int(value) >= 0: return float(value) else: raise Exception @bottle.route('/', method='GET') def index(): return template('tax_form') @bottle.route('/', method='POST') def tax_results(): params = { 'gross' : valid_int, 'deduction' : valid_int, 'residence' : valid_home, } invalid = [] tax_results = {} for i in params: if request.params.get(i): try: # Validate the incoming parameters. tax_results[i] = params[i](request.params.get(i)) except Exception: invalid.append(i) else: invalid.append(i) if not invalid and tax_results['deduction'] > tax_results['gross']: invalid.append('deduction', 'gross') if invalid: return template('tax_form', invalid=invalid) else: try: tax_results['tax'] = tax_calc(**tax_results) except Exception: raise tax_results['net'] = tax_results['gross'] - tax_results['tax']; for i in 'deduction', 'gross', 'tax', 'net': tax_results[i + '_fmtd'] = '$' + '%.2f' % tax_results[i] return template('tax_form', **tax_results) # Define an handler for 404 errors. @bottle.error(404) def error_404(error): """Return a custom 404 error.""" return 'Sorry, nothing at this URL.'
[ "jmadler@cpan.org" ]
jmadler@cpan.org
eb29a4e6940e43aac67baf09cbe9749c0f72f8f1
713f9168a7ba68740bb9b4ea6994e853a56d2d5c
/python/2019-10-07/db_basics.py
0bf35c97021e29f1cebce9edef2ccf07b0710d8a
[]
no_license
marko-knoebl/courses-code
ba7723c9a61861b037422670b98276fed41060e2
faeaa31c9a156a02e4e9169bc16f229cdaee085d
refs/heads/master
2022-12-29T02:13:12.653745
2022-12-16T09:21:18
2022-12-16T09:21:18
142,756,698
16
10
null
2022-03-08T22:30:11
2018-07-29T11:51:04
Jupyter Notebook
UTF-8
Python
false
false
1,822
py
import sqlite3 from datetime import date connection = sqlite3.connect("contacts.db", detect_types=sqlite3.PARSE_DECLTYPES) def init(): """Initialize the database with a table 'person'. """ cursor = connection.cursor() cursor.execute( """ CREATE TABLE person( first_name VARCHAR(50), last_name VARCHAR(50), date_of_birth DATE ); """ ) connection.commit() def insert_entries(): cursor = connection.cursor() cursor.execute( """ INSERT INTO person (first_name, last_name, date_of_birth) VALUES (?, ?, ?); """, ("Tom", "Baker", date(1970, 4, 12)), ) cursor.execute( """ INSERT INTO person (first_name, last_name, date_of_birth) VALUES (?, ?, ?); """, ("Anne", "Baker", date(1972, 5, 10)), ) connection.commit() def insert_entry_interactive(): # ask user for first name, last name and birth year while True: print("first name:") first_name = input() if first_name: break print("last name:") last_name = input() while True: print("date of birth (YYYY-MM-DD):") try: birth_year = date.fromisoformat(input()) break except ValueError: print("invalid date format") cursor = connection.cursor() cursor.execute( """ INSERT INTO person (first_name, last_name, date_of_birth) VALUES (?, ?, ?); """, (first_name, last_name, birth_year), ) connection.commit() def get_all(): cursor = connection.cursor() cursor.execute( """ SELECT first_name, last_name, date_of_birth FROM person; """ ) return cursor.fetchall()
[ "abcd" ]
abcd
d502a5ad0307e641bad478a02d9af45a158e4fb6
f82757475ea13965581c2147ff57123b361c5d62
/gi-stubs/repository/ICalGLib/ValueKind.py
7bcd2a1e582e56503f56aedc2855de1c81281c9f
[]
no_license
ttys3/pygobject-stubs
9b15d1b473db06f47e5ffba5ad0a31d6d1becb57
d0e6e93399212aada4386d2ce80344eb9a31db48
refs/heads/master
2022-09-23T12:58:44.526554
2020-06-06T04:15:00
2020-06-06T04:15:00
269,693,287
8
2
null
2020-06-05T15:57:54
2020-06-05T15:57:54
null
UTF-8
Python
false
false
18,912
py
# encoding: utf-8 # module gi.repository.ICalGLib # from /usr/lib64/girepository-1.0/ICalGLib-3.0.typelib # by generator 1.147 """ An object which wraps an introspection typelib. This wrapping creates a python module like representation of the typelib using gi repository as a foundation. Accessing attributes of the module will dynamically pull them in and create wrappers for the members. These members are then cached on this introspection module. """ # imports import gi as __gi import gi.overrides.GObject as __gi_overrides_GObject import gobject as __gobject class ValueKind(__gobject.GEnum): # no doc def as_integer_ratio(self): # real signature unknown; restored from __doc__ """ Return integer ratio. Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator. >>> (10).as_integer_ratio() (10, 1) >>> (-10).as_integer_ratio() (-10, 1) >>> (0).as_integer_ratio() (0, 1) """ pass def bit_length(self): # real signature unknown; restored from __doc__ """ Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6 """ pass def conjugate(self, *args, **kwargs): # real signature unknown """ Returns self, the complex conjugate of any int. """ pass def from_bytes(self, *args, **kwargs): # real signature unknown """ Return the integer represented by the given array of bytes. bytes Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Indicates whether two's complement is used to represent the integer. """ pass def to_bytes(self, *args, **kwargs): # real signature unknown """ Return an array of bytes representing an integer. length Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised. """ pass def __abs__(self, *args, **kwargs): # real signature unknown """ abs(self) """ pass def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __bool__(self, *args, **kwargs): # real signature unknown """ self != 0 """ pass def __ceil__(self, *args, **kwargs): # real signature unknown """ Ceiling of an Integral returns itself. """ pass def __delattr__(self, *args, **kwargs): # real signature unknown """ Implement delattr(self, name). """ pass def __dir__(self, *args, **kwargs): # real signature unknown """ Default dir() implementation. """ pass def __divmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(self, value). """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __float__(self, *args, **kwargs): # real signature unknown """ float(self) """ pass def __floordiv__(self, *args, **kwargs): # real signature unknown """ Return self//value. """ pass def __floor__(self, *args, **kwargs): # real signature unknown """ Flooring an Integral returns itself. """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __index__(self, *args, **kwargs): # real signature unknown """ Return self converted to an integer, if self is suitable for use as an index into a list. """ pass def __init_subclass__(self, *args, **kwargs): # real signature unknown """ This method is called when a class is subclassed. The default implementation does nothing. It may be overridden to extend subclasses. """ pass def __init__(self, *args, **kwargs): # real signature unknown pass def __int__(self, *args, **kwargs): # real signature unknown """ int(self) """ pass def __invert__(self, *args, **kwargs): # real signature unknown """ ~self """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lshift__(self, *args, **kwargs): # real signature unknown """ Return self<<value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __neg__(self, *args, **kwargs): # real signature unknown """ -self """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __pos__(self, *args, **kwargs): # real signature unknown """ +self """ pass def __pow__(self, *args, **kwargs): # real signature unknown """ Return pow(self, value, mod). """ pass def __radd__(self, *args, **kwargs): # real signature unknown """ Return value+self. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __rdivmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(value, self). """ pass def __reduce_ex__(self, *args, **kwargs): # real signature unknown """ Helper for pickle. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rfloordiv__(self, *args, **kwargs): # real signature unknown """ Return value//self. """ pass def __rlshift__(self, *args, **kwargs): # real signature unknown """ Return value<<self. """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return value*self. """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __round__(self, *args, **kwargs): # real signature unknown """ Rounding an Integral returns itself. Rounding with an ndigits argument also returns an integer. """ pass def __rpow__(self, *args, **kwargs): # real signature unknown """ Return pow(value, self, mod). """ pass def __rrshift__(self, *args, **kwargs): # real signature unknown """ Return value>>self. """ pass def __rshift__(self, *args, **kwargs): # real signature unknown """ Return self>>value. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rtruediv__(self, *args, **kwargs): # real signature unknown """ Return value/self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __setattr__(self, *args, **kwargs): # real signature unknown """ Implement setattr(self, name, value). """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Returns size in memory, in bytes. """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass def __subclasshook__(self, *args, **kwargs): # real signature unknown """ Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached). """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __truediv__(self, *args, **kwargs): # real signature unknown """ Return self/value. """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Truncating an Integral returns itself. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number""" value_name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default value_nick = property(lambda self: object(), lambda self, v: None, lambda self: None) # default ACTION_VALUE = 5027 ANY_VALUE = 5000 ATTACH_VALUE = 5003 BINARY_VALUE = 5011 BOOLEAN_VALUE = 5021 BUSYTYPE_VALUE = 5032 CALADDRESS_VALUE = 5023 CARLEVEL_VALUE = 5016 CLASS_VALUE = 5019 CMD_VALUE = 5010 DATETIMEDATE_VALUE = 5036 DATETIMEPERIOD_VALUE = 5015 DATETIME_VALUE = 5028 DATE_VALUE = 5002 DURATION_VALUE = 5020 FLOAT_VALUE = 5013 GEO_VALUE = 5004 INTEGER_VALUE = 5017 METHOD_VALUE = 5030 NO_VALUE = 5031 PERIOD_VALUE = 5014 POLLCOMPLETION_VALUE = 5034 POLLMODE_VALUE = 5033 QUERYLEVEL_VALUE = 5012 QUERY_VALUE = 5001 RECUR_VALUE = 5026 REQUESTSTATUS_VALUE = 5009 STATUS_VALUE = 5005 STRING_VALUE = 5007 TASKMODE_VALUE = 5035 TEXT_VALUE = 5008 TRANSP_VALUE = 5006 TRIGGER_VALUE = 5024 URI_VALUE = 5018 UTCOFFSET_VALUE = 5029 XLICCLASS_VALUE = 5025 X_VALUE = 5022 __class__ = type __dict__ = None # (!) real value is "mappingproxy({'__module__': 'gi.repository.ICalGLib', '__dict__': <attribute '__dict__' of 'ValueKind' objects>, '__doc__': None, '__gtype__': <GType PyICalGLibValueKind (94403188614944)>, '__enum_values__': {5000: <enum I_CAL_ANY_VALUE of type ICalGLib.ValueKind>, 5027: <enum I_CAL_ACTION_VALUE of type ICalGLib.ValueKind>, 5003: <enum I_CAL_ATTACH_VALUE of type ICalGLib.ValueKind>, 5011: <enum I_CAL_BINARY_VALUE of type ICalGLib.ValueKind>, 5021: <enum I_CAL_BOOLEAN_VALUE of type ICalGLib.ValueKind>, 5032: <enum I_CAL_BUSYTYPE_VALUE of type ICalGLib.ValueKind>, 5023: <enum I_CAL_CALADDRESS_VALUE of type ICalGLib.ValueKind>, 5016: <enum I_CAL_CARLEVEL_VALUE of type ICalGLib.ValueKind>, 5019: <enum I_CAL_CLASS_VALUE of type ICalGLib.ValueKind>, 5010: <enum I_CAL_CMD_VALUE of type ICalGLib.ValueKind>, 5002: <enum I_CAL_DATE_VALUE of type ICalGLib.ValueKind>, 5028: <enum I_CAL_DATETIME_VALUE of type ICalGLib.ValueKind>, 5036: <enum I_CAL_DATETIMEDATE_VALUE of type ICalGLib.ValueKind>, 5015: <enum I_CAL_DATETIMEPERIOD_VALUE of type ICalGLib.ValueKind>, 5020: <enum I_CAL_DURATION_VALUE of type ICalGLib.ValueKind>, 5013: <enum I_CAL_FLOAT_VALUE of type ICalGLib.ValueKind>, 5004: <enum I_CAL_GEO_VALUE of type ICalGLib.ValueKind>, 5017: <enum I_CAL_INTEGER_VALUE of type ICalGLib.ValueKind>, 5030: <enum I_CAL_METHOD_VALUE of type ICalGLib.ValueKind>, 5014: <enum I_CAL_PERIOD_VALUE of type ICalGLib.ValueKind>, 5034: <enum I_CAL_POLLCOMPLETION_VALUE of type ICalGLib.ValueKind>, 5033: <enum I_CAL_POLLMODE_VALUE of type ICalGLib.ValueKind>, 5001: <enum I_CAL_QUERY_VALUE of type ICalGLib.ValueKind>, 5012: <enum I_CAL_QUERYLEVEL_VALUE of type ICalGLib.ValueKind>, 5026: <enum I_CAL_RECUR_VALUE of type ICalGLib.ValueKind>, 5009: <enum I_CAL_REQUESTSTATUS_VALUE of type ICalGLib.ValueKind>, 5005: <enum I_CAL_STATUS_VALUE of type ICalGLib.ValueKind>, 5007: <enum I_CAL_STRING_VALUE of type ICalGLib.ValueKind>, 5035: <enum I_CAL_TASKMODE_VALUE of type ICalGLib.ValueKind>, 5008: <enum I_CAL_TEXT_VALUE of type ICalGLib.ValueKind>, 5006: <enum I_CAL_TRANSP_VALUE of type ICalGLib.ValueKind>, 5024: <enum I_CAL_TRIGGER_VALUE of type ICalGLib.ValueKind>, 5018: <enum I_CAL_URI_VALUE of type ICalGLib.ValueKind>, 5029: <enum I_CAL_UTCOFFSET_VALUE of type ICalGLib.ValueKind>, 5022: <enum I_CAL_X_VALUE of type ICalGLib.ValueKind>, 5025: <enum I_CAL_XLICCLASS_VALUE of type ICalGLib.ValueKind>, 5031: <enum I_CAL_NO_VALUE of type ICalGLib.ValueKind>}, '__info__': gi.EnumInfo(ValueKind), 'ANY_VALUE': <enum I_CAL_ANY_VALUE of type ICalGLib.ValueKind>, 'ACTION_VALUE': <enum I_CAL_ACTION_VALUE of type ICalGLib.ValueKind>, 'ATTACH_VALUE': <enum I_CAL_ATTACH_VALUE of type ICalGLib.ValueKind>, 'BINARY_VALUE': <enum I_CAL_BINARY_VALUE of type ICalGLib.ValueKind>, 'BOOLEAN_VALUE': <enum I_CAL_BOOLEAN_VALUE of type ICalGLib.ValueKind>, 'BUSYTYPE_VALUE': <enum I_CAL_BUSYTYPE_VALUE of type ICalGLib.ValueKind>, 'CALADDRESS_VALUE': <enum I_CAL_CALADDRESS_VALUE of type ICalGLib.ValueKind>, 'CARLEVEL_VALUE': <enum I_CAL_CARLEVEL_VALUE of type ICalGLib.ValueKind>, 'CLASS_VALUE': <enum I_CAL_CLASS_VALUE of type ICalGLib.ValueKind>, 'CMD_VALUE': <enum I_CAL_CMD_VALUE of type ICalGLib.ValueKind>, 'DATE_VALUE': <enum I_CAL_DATE_VALUE of type ICalGLib.ValueKind>, 'DATETIME_VALUE': <enum I_CAL_DATETIME_VALUE of type ICalGLib.ValueKind>, 'DATETIMEDATE_VALUE': <enum I_CAL_DATETIMEDATE_VALUE of type ICalGLib.ValueKind>, 'DATETIMEPERIOD_VALUE': <enum I_CAL_DATETIMEPERIOD_VALUE of type ICalGLib.ValueKind>, 'DURATION_VALUE': <enum I_CAL_DURATION_VALUE of type ICalGLib.ValueKind>, 'FLOAT_VALUE': <enum I_CAL_FLOAT_VALUE of type ICalGLib.ValueKind>, 'GEO_VALUE': <enum I_CAL_GEO_VALUE of type ICalGLib.ValueKind>, 'INTEGER_VALUE': <enum I_CAL_INTEGER_VALUE of type ICalGLib.ValueKind>, 'METHOD_VALUE': <enum I_CAL_METHOD_VALUE of type ICalGLib.ValueKind>, 'PERIOD_VALUE': <enum I_CAL_PERIOD_VALUE of type ICalGLib.ValueKind>, 'POLLCOMPLETION_VALUE': <enum I_CAL_POLLCOMPLETION_VALUE of type ICalGLib.ValueKind>, 'POLLMODE_VALUE': <enum I_CAL_POLLMODE_VALUE of type ICalGLib.ValueKind>, 'QUERY_VALUE': <enum I_CAL_QUERY_VALUE of type ICalGLib.ValueKind>, 'QUERYLEVEL_VALUE': <enum I_CAL_QUERYLEVEL_VALUE of type ICalGLib.ValueKind>, 'RECUR_VALUE': <enum I_CAL_RECUR_VALUE of type ICalGLib.ValueKind>, 'REQUESTSTATUS_VALUE': <enum I_CAL_REQUESTSTATUS_VALUE of type ICalGLib.ValueKind>, 'STATUS_VALUE': <enum I_CAL_STATUS_VALUE of type ICalGLib.ValueKind>, 'STRING_VALUE': <enum I_CAL_STRING_VALUE of type ICalGLib.ValueKind>, 'TASKMODE_VALUE': <enum I_CAL_TASKMODE_VALUE of type ICalGLib.ValueKind>, 'TEXT_VALUE': <enum I_CAL_TEXT_VALUE of type ICalGLib.ValueKind>, 'TRANSP_VALUE': <enum I_CAL_TRANSP_VALUE of type ICalGLib.ValueKind>, 'TRIGGER_VALUE': <enum I_CAL_TRIGGER_VALUE of type ICalGLib.ValueKind>, 'URI_VALUE': <enum I_CAL_URI_VALUE of type ICalGLib.ValueKind>, 'UTCOFFSET_VALUE': <enum I_CAL_UTCOFFSET_VALUE of type ICalGLib.ValueKind>, 'X_VALUE': <enum I_CAL_X_VALUE of type ICalGLib.ValueKind>, 'XLICCLASS_VALUE': <enum I_CAL_XLICCLASS_VALUE of type ICalGLib.ValueKind>, 'NO_VALUE': <enum I_CAL_NO_VALUE of type ICalGLib.ValueKind>})" __enum_values__ = { 5000: 5000, 5001: 5001, 5002: 5002, 5003: 5003, 5004: 5004, 5005: 5005, 5006: 5006, 5007: 5007, 5008: 5008, 5009: 5009, 5010: 5010, 5011: 5011, 5012: 5012, 5013: 5013, 5014: 5014, 5015: 5015, 5016: 5016, 5017: 5017, 5018: 5018, 5019: 5019, 5020: 5020, 5021: 5021, 5022: 5022, 5023: 5023, 5024: 5024, 5025: 5025, 5026: 5026, 5027: 5027, 5028: 5028, 5029: 5029, 5030: 5030, 5031: 5031, 5032: 5032, 5033: 5033, 5034: 5034, 5035: 5035, 5036: 5036, } __gtype__ = None # (!) real value is '<GType PyICalGLibValueKind (94403188614944)>' __info__ = gi.EnumInfo(ValueKind)
[ "ttys3@outlook.com" ]
ttys3@outlook.com
b8054be459e952b2edf1f0f544dbd1d044dbcb65
fe149015eb41aa71bd0614ee06ab40c02ebffa00
/items/api.py
10cb271f1504ba19936cb25074b94325def91aae
[]
no_license
harvard-lil/interestingness
3d02657aa87b2ae097e4d9f25d547536c9fd32e8
5d9f6a18c758565e50f73c52eb3c957bd6e0fbcf
refs/heads/master
2021-01-10T11:33:04.504836
2016-03-04T20:42:42
2016-03-04T20:42:42
52,763,361
0
0
null
null
null
null
UTF-8
Python
false
false
1,781
py
from items.models import Item from django.conf import settings from django.conf.urls import url from tastypie.utils import trailing_slash from tastypie.resources import ModelResource class ItemResource(ModelResource): """ The API for our Item model. The search piece is likely the thing that's of most interest. It allows for the flitering of links based on the organization's slug """ class Meta: queryset = Item.objects.all() resource_name = 'item' def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/search%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_search'), name="api_get_search"), ] def get_search(self, request, **kwargs): self.method_check(request, allowed=['get']) # TODO: Use the tastypie/django pagination stuff to handle this. # there has to be a good tastypie pattern for this org_slug = request.GET.get('q', '') objects = Item.objects.filter(contributor__organization__slug=org_slug).order_by('-contributed_date')[:200] object_list = [] for o in objects: stripped_object = { 'description': o.description, 'link': o.link, 'short_link': o.short_link, 'contributor': o.contributor.display_name, 'contributed_date': o.contributed_date, 'profile_pic': "%s%s" % (settings.MEDIA_URL, o.contributor.profile_pic), } object_list.append(stripped_object) return self.create_response(request, object_list)
[ "mphillips@law.harvard.edu" ]
mphillips@law.harvard.edu
6e97e55ec3ce1bc0173b52c43fcc960ee3ae1ccc
a59566aa698e02550cc6ce1d3df57a70c20354ab
/service/serializers.py
7fbc6ad5809592109853822db34105525f22790c
[]
no_license
GregoryBuligin/handyman
ad8c3bcf4c41eecb79573fea79b1338b12e985e8
059d4f5c4122d7cbd132668fbe7ff1f231aff00b
refs/heads/master
2021-01-01T05:11:13.338584
2016-05-17T12:34:05
2016-05-17T12:34:05
59,012,451
1
0
null
null
null
null
UTF-8
Python
false
false
437
py
# -*- coding: utf-8 -*- from rest_framework import serializers from .models import Service from category.serializers import CategoryHyperlinkedSerializer class ServiceListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Service fields = ('id', 'url', 'title', 'capture', 'category') class ServiceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Service
[ "gri9996@yandex.ru" ]
gri9996@yandex.ru
86642e7bedd7da193a75b8f06e6c7278010b12bd
e90f92f25136e27ae454592d459c4e1c19f92eea
/import.py
584a8b14b664a23a6474c0fc6e9386776c1e9b8e
[ "MIT" ]
permissive
iskaira/rentcontrol
325e39402d810067f129ce9adec0d45a5c492c39
ad82e88143fb4f8ae2633a6fe774da19e1982fb9
refs/heads/master
2020-03-19T05:07:00.521905
2018-06-03T12:30:37
2018-06-03T12:30:37
135,901,978
0
1
null
null
null
null
UTF-8
Python
false
false
8,700
py
import telebot import constants import requests import pygsheets from datetime import datetime from pytz import timezone from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from manager_db import SQLight from os import system from time import sleep db=SQLight(constants.db) bot = telebot.TeleBot(constants.token) for i in range(3): ok=0 file='' data=db.get_last_row_import() if len(data)>0: fmt = "%Y-%m-%d %H:%M:%S" time_zone='Asia/Almaty' current="%Y-%m-%d" now_time = datetime.now(timezone(time_zone)) current_time = now_time.strftime(current) now_current_time= now_time.strftime(fmt) print (data) data=data[0] row_id=data[0] id=data[1] m_name=data[2] m_surname=data[3] m_username=data[4] date =data[5] phone =data[6] name =data[7] course =data[8] email =data[9] city =data[10] potok =data[11] price =data[12] fact_price =data[13] doplata =data[14] file_path =data[15] r=requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(constants.token, file_path),stream=True) month_dict={"01":"Январь","02":"Февраль","03":"Март","04":"Апрель","05":"Май","06":"Июнь","07":"Июль","08":"Август","09":"Сентябрь","10":"Октябрь","11":"Ноябрь","12":"Декабрь"} letter_dict={0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",10:"K",11:"L",12:"M",13:"N",14:"O",15:"P",16:"Q",17:"R",18:"S",19:"T",20:"U",21:"V",22:"W",23:"X",24:"Y",25:"Z",26:"AA",27:"AB",28:"AC",29:"AD",30:"AE"} file = m_name+m_surname+'-'+str(phone)+'.jpg' f=open(file, 'wb') f.write(r.content) gauth = GoogleAuth(constants.client_secrets) # Try to load saved client credentials gauth.LoadCredentialsFile(constants.creds) if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile(constants.creds) drive = GoogleDrive(gauth) file2 = drive.CreateFile() file2.SetContentFile(file) file2.Upload() print('Created file %s with mimeType %s with id %s' % (file2['title'], file2['mimeType'],file2['id'])) permission = file2.InsertPermission({ 'type': 'anyone', 'value': 'anyone', 'role': 'reader'}) photo_path = file2['alternateLink'] gc = pygsheets.authorize(service_file=constants.client,no_cache=True) try: sht = gc.open("TF") sheet = sht.worksheet('title','События') except Exception as e: bot.send_message(295091909,"ТФ sheet OPEN:"+str(e)) index = 1 manager_name=db.get_manager(id) manager=gc.open(manager_name) ##################################################################################### ##################################################################################### if doplata is None: month=month_dict[date.split("-")[1]] print(month) print(manager_name) try: manager_sheet = manager.worksheet('title',month) ok+=1 except Exception as e: bot.send_message(295091909,"менеджер sheet OPEN:"+str(e)) try: kurs_gs=gc.open(course) ok+=1 except Exception as e: bot.send_message(295091909,"kurs sheet OPEN:"+str(e)) if city is None: temp_title=course+" "+str(potok) else: temp_title=city+" "+course+" "+str(potok) try: kurs_sheet=kurs_gs.worksheet('title',temp_title) ok+=1 except Exception as e: bot.send_message(295091909,"kurs sheet, kurs imya proverit nado KURS OPEN: "+str(e)) row = [date,manager_name,name,phone,email,city,course,potok,price,fact_price,doplata,photo_path,now_current_time] try: sheet.insert_rows(index,values=row) ok+=1 except Exception as e: bot.send_message(295091909,"insert_row Sobytie OPEN:"+str(e)) if city is None: row_manager = [manager_name,name,phone,str(course)+" "+str(potok),price,"","",fact_price,"","","","","",photo_path,"","","","","",date,"","","","","",current_time] row_kurs = [manager_name,name,phone,str(course)+" "+str(potok),price,"","",fact_price,"","","","","",email] else: row_manager = [manager_name,name,phone,str(city)+" "+str(course)+" "+str(potok),price,"","",fact_price,"","","","","",photo_path,"","","","","",date,"","","","","",current_time] row_kurs = [manager_name,name,phone,str(city)+" "+str(course)+" "+str(potok),price,"","",fact_price,"","","","","",email] try: manager_sheet.insert_rows(index,values=row_manager) kurs_sheet.insert_rows(index,values=row_kurs) ok+=1 except Exception as e: bot.send_message(295091909,"insert_to manager and kurs: "+str(e)) else: client_info=db.get_client_info(phone) month=month_dict[(str(client_info[-1]).split("-")[1])] kurs=client_info[2] gorod=client_info[1] potok=client_info[3] print(month) print(manager_name) try: manager_sheet = manager.worksheet('title',month) ok+=1 except Exception as e: bot.send_message(295091909,"Manager_sheet title Doplata WORKSHEET: "+str(e)) print (client_info) if client_info[1] is None or client_info[1] is '': temp_title=client_info[2]+" "+str(client_info[3]) else: temp_title=client_info[1]+" "+client_info[2]+" "+str(client_info[3]) try: kurs_gs=gc.open(client_info[2]) kurs_sheet=kurs_gs.worksheet('title',temp_title) ok+=1 except Exception as e: bot.send_message(295091909,"kurs open worksheet: "+temp_title+str(e)) try: cell_list = manager_sheet.find(phone) cell_list_kurs = kurs_sheet.find(phone) ok+=1 except Exception as e: bot.send_message(295091909,"CELL FIND: "+str(e)) temp_data=str(cell_list[0]).split(" ")[1] temp_end_index=temp_data.index("C") row_num=temp_data[1:temp_end_index] row_from_manager=manager_sheet.get_row(row_num) dpl=1 for i in range(8,13): if row_from_manager[i]=='': dpl=i-7 print(dpl) if dpl>5: dpl=5 break try: manager_sheet.update_cell(letter_dict[7+dpl]+str(row_num),str(doplata))#doplata1 manager_sheet.update_cell(letter_dict[13+dpl]+str(row_num),str(photo_path))#checkdop1 manager_sheet.update_cell(letter_dict[19+dpl]+str(row_num),str(date))#datadop1 manager_sheet.update_cell(letter_dict[25+dpl]+str(row_num),str(current_time)) temp_data=str(cell_list_kurs[0]).split(" ")[1] temp_end_index=temp_data.index("C") row_num=temp_data[1:temp_end_index] kurs_sheet.update_cell(letter_dict[7+dpl]+str(row_num),str(doplata))#doplata1 ok+=1 except Exception as e: bot.send_message(295091909,"UPDate in doplata: "+str(e)) #('Oskar', 'Almaty', 'A', '42', 'kiro@gmail.com', 45000) try: if client_info: row = [date,manager_name,client_info[0],phone,client_info[4],client_info[1],client_info[2],client_info[3],client_info[5],fact_price,doplata,photo_path,now_current_time] sheet.insert_rows(index,values=row) else: row = [date,manager_name,name,phone,email,city,course,potok,price,fact_price,doplata,photo_path,now_current_time] sheet.insert_rows(index,values=row) ok+=1 except Exception as e: bot.send_message(295091909,"insert to sheet sobytie in DOPLATA: "+str(e)) try: cell_list = manager_sheet.find(phone) cell_list_kurs = kurs_sheet.find(phone) temp_data=str(cell_list[0]).split(" ")[1] temp_end_index=temp_data.index("C") temp_end=temp_data[1:temp_end_index] formula='H'+str(temp_end)+ "+" +'I'+str(temp_end)+ "+" +'J'+str(temp_end)+ "+" +'K'+str(temp_end)+ "+" +'L'+str(temp_end)+ "+" +'M'+str(temp_end) manager_sheet.update_cell('F'+str(temp_end),'='+formula) manager_sheet.update_cell('G'+str(temp_end),'=if('+'(E'+str(temp_end) + "-" +"F"+str(temp_end)+")>0,"+'E'+str(temp_end) + "-" +"F"+str(temp_end)+",0)")#dolg temp_data=str(cell_list_kurs[0]).split(" ")[1] temp_end_index=temp_data.index("C") temp_end=temp_data[1:temp_end_index] kurs_sheet.update_cell('F'+str(temp_end),'='+formula)#oplatil vsego #=if((E4-F4)>0,E4-F4,0) kurs_sheet.update_cell('G'+str(temp_end),'=if('+'(E'+str(temp_end) + "-" +"F"+str(temp_end)+")>0,"+'E'+str(temp_end) + "-" +"F"+str(temp_end)+",0)")#dolg except Exception as e: bot.send_message(295091909,"FORMULA OBWAYA: "+str(e)) ############################################################################################################ print("DEL") print(file) system('python del.py root/'+file) print("Happened") if ok==5: db.delete_data() else: bot.send_message(295091909,"NOT OK: ") sleep(17)
[ "noreply@github.com" ]
iskaira.noreply@github.com
c6c0e8ad14a0a5a6173144eba2f80efaf3a85609
30e9efdec9e02ed9704c675041770f16fb696f58
/welcome.py
6eee4b367e3ff3d8e81d8509558b2234d8542158
[]
no_license
aravindakumar79/code
036449339459191aa516e1f55760d2428ad3717a
b4649ce183f1439028976ec7b514a612e79d3331
refs/heads/master
2020-12-02T02:43:12.539789
2019-12-30T10:00:50
2019-12-30T10:00:50
230,861,714
1
0
null
2019-12-30T10:00:21
2019-12-30T06:34:28
Python
UTF-8
Python
false
false
49
py
Print("welcome to CTS Network") Print"Good Bye")
[ "noreply@github.com" ]
aravindakumar79.noreply@github.com
981d85c363447df54ec3ae8f37ef73be37c6a640
0e719bc0915f83d0fb96a252ab24af9159624a44
/CodeCamp/recursion2.py
da6c649c84377d7b9929b66fe580a5443e22c878
[]
no_license
skhadka007/learning_algos
09a0d89194fe610186e5af03a4683b971d1c7f2c
a9f7e432f5b6b5a2ccefb713e029c43be9421969
refs/heads/master
2023-09-02T03:11:27.855951
2021-10-04T14:11:34
2021-10-04T14:11:34
286,854,625
0
0
null
null
null
null
UTF-8
Python
false
false
799
py
''' SANTOSH KHADKA We have defined a function named rangeOfNumbers with two parameters. The function should return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both startNum and endNum are the same. ''' def rangeOfNumbers(startNum, endNum): if (startNum > endNum): return [] else: countArray = rangeOfNumbers(startNum + 1, endNum) countArray.insert(0, startNum) return countArray return [] print(rangeOfNumbers(1, 5)) print(rangeOfNumbers(6, 9)) print(rangeOfNumbers(4, 4))
[ "skhadka.code@gmail.com" ]
skhadka.code@gmail.com
0721bcf2e20cbe3c18af3d24ec6b75554f54b095
9a5db7aca2afdbf124da0d3c80a57433bbcf011f
/funtool_scratch_processes/reporters/save_groups_to_file.py
003a17bd46d1d8e77aa0b0b0a808bb66ae2f7a33
[ "MIT" ]
permissive
pjanis/funtool-scratch-processes
8d6308c3ec2c66b8817f645822087c0259dd0d9b
2123962258d4b04a670e698bc0985582cc4dc622
refs/heads/master
2016-09-06T18:45:27.054130
2015-06-02T11:15:28
2015-06-02T11:15:28
27,767,640
0
2
null
null
null
null
UTF-8
Python
false
false
3,476
py
# This reporter will save all meta and measures for all states in a state_collection to a file # Reporter should include the following parameters # save_directory location of the save file # filename basename of the file # filetype file type which is added as an extension, either csv or tsv # overwrite boolean to overwrite existing file if it exists import csv import json import os import funtool.reporter def save(reporter,state_collection,overriding_parameters=None,logging=None): reporter_parameters= funtool.reporter.get_parameters(reporter,overriding_parameters) save_path= funtool.reporter.get_default_save_path(reporter_parameters) if not os.path.exists(save_path): os.makedirs(save_path) if not _can_write(reporter_parameters): raise funtool.reporter.ReporterError("Can't write to %s at %s" % (reporter_parameters['filename'], reporter_parameters['save_directory'] ) ) meta_keys= sorted(_gather_keys(state_collection, 'meta')) measures_keys= sorted(_gather_keys(state_collection, 'measures')) path_and_filename= os.path.join(save_path,".".join([reporter_parameters['filename'], reporter_parameters['file_type']])) with open( path_and_filename, 'w', newline='' ) as f: writer = _get_writer(reporter_parameters,f) _write_line(reporter_parameters,writer, (['grouping_name'] + meta_keys + measures_keys) ) for (grouping_name, groups) in state_collection.groupings.items(): for group in groups.values(): group_values= [ grouping_name] + \ [ group.meta.get(meta_key) for meta_key in meta_keys ] + \ [ group.measures.get(measure_key) for measure_key in measures_keys ] _write_line(reporter_parameters,writer, group_values) funtool.reporter.link_latest_output(reporter_parameters['save_directory']) return state_collection # Internal functions def _gather_keys(state_collection, key_type): collection_keys = {} for (grouping_name,groups) in state_collection.groupings.items(): for group in groups.values(): for group_keys in group.__getattribute__(key_type).keys(): collection_keys[group_keys] = 1 return list(collection_keys.keys()) def _can_write(reporter_parameters): path_and_filename= os.path.join(reporter_parameters['save_directory'],".".join([reporter_parameters['filename'], reporter_parameters['file_type']])) return os.path.exists(reporter_parameters['save_directory']) and ( not os.path.exists(path_and_filename) or reporter_parameters['overwrite'] ) def _get_writer(reporter_parameters, file_handler): if reporter_parameters['file_type'].lower() == 'csv' : return csv.writer(file_handler) elif reporter_parameters['file_type'].lower() == 'tsv' : return file_handler else : return None def _write_line(reporter_parameters, writer, state_values): if reporter_parameters['file_type'].lower() == 'csv' : writer.writerow(state_values) elif reporter_parameters['file_type'].lower() == 'tsv' : writer.write( "\t".join([ _write_value(v) for v in state_values ])) writer.write( "\n" ) return True def _write_value(value): #converts value in json encoded string if possible and a regular string if not try: write_value= json.dumps(value) except: write_value= str(value) return write_value
[ "pjanisiewicz@gmail.com" ]
pjanisiewicz@gmail.com
14c58aed9e566dfe2a3c7ddbf714786a4e6e44f4
15e4ea46e2b1944add82746c4b3369184550af1b
/9 Strings/Excersises/19.py
7893e1b258d167f093df275420b07f5dd18d6e68
[]
no_license
eduardogomezvidela/Summer-Intro
53204a61b05066d8b8bc1ef234e83e15f823934d
649a85b71a7e76eade3665554b03ca65108c648b
refs/heads/master
2021-04-29T13:34:26.873513
2018-02-16T13:35:48
2018-02-16T13:35:48
121,754,165
0
0
null
null
null
null
UTF-8
Python
false
false
790
py
#THE ENIGMA MACHINE import cipher_machine cipher = "plmkonhijbuvygtfcrxdeszwaq" abc = "abcdefghijklmnopqrstuvwxyz" ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" encrypted_message = (cipher_machine.cipher("It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief.", cipher)) decrypted_message = '' print(encrypted_message) for char in encrypted_message: if ord(char) > 96: decrypted_message = decrypted_message + abc[cipher.find(char)] elif ord(char) > 64: char = char.lower() decrypted_message = decrypted_message + ABC[cipher.find(char)].upper() else: decrypted_message = decrypted_message + char print (decrypted_message, encrypted_message[len(decrypted_message):])
[ "eduardogomezvidela@gmail.com" ]
eduardogomezvidela@gmail.com
dc466e1cd7058dcbe2db28fa540a149a0a4b7f5f
ff28d0bb7b54536170ce4a9b8713f05702c73722
/apps/bento_create_card/main_create_card.py
0471be01a60782832d22f30425ac4af59f0ebeca
[]
no_license
HelenLiu97/new_bento
94423cd9d466083cc6eb48aba8a44014fdaa9b1c
fd8d89913359669e373175bdc1a6a41dba9bed0a
refs/heads/master
2022-11-13T23:44:21.229215
2020-07-14T07:52:11
2020-07-14T07:52:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,892
py
import requests import json import time from tools_me.bento_token import GetToken from apps.bento_create_card.sqldata_native import SqlDataNative from requests.adapters import HTTPAdapter class CreateCard(object): def __init__(self): self.headers = { "Content-Type": "application/json", "authorization": GetToken(), "Connection": "close" } requests.adapters.DEFAULT_RETRIES = 5 self.requests = requests.session() self.requests.keep_alive = False def create_card(self, card_alias, card_amount, label, attribution): user_data = {} url = "https://api.bentoforbusiness.com/cards" try: r = self.requests.post(url=url, data=json.dumps( bento_data(card_alias=card_alias, card_amount=card_amount, attribution=attribution)), headers=self.headers, verify=False, timeout=14) user_data["alias"] = r.json().get("alias") user_data["cardId"] = r.json().get("cardId") user_data["card_amount"] = card_amount if user_data.get("cardId"): pan_data = self.get_pan(cardid=user_data.get("cardId")) user_data.update(pan_data) expriation_data = self.get_expiration(cardid=user_data.get("cardId")) user_data.update(expriation_data) # update alias card_id, card_amount SqlDataNative.insert_new_account(alias=user_data.get("alias"), card_id=user_data.get("cardId"), card_amount=card_amount, card_number=user_data.get("pan"), card_cvv=user_data.get("cvv"), label=label, card_validity=user_data.get("expiration"), attribution=attribution, create_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) self.billing_address(user_data.get("cardId")) return user_data except Exception as e: return False # 获取pan cvv def get_pan(self, cardid): url = "https://api.bentoforbusiness.com/cards/{}/pan".format(cardid) response = self.requests.get(url=url, headers=self.headers, verify=False, timeout=14) return { "pan": response.json().get("pan"), "cvv": response.json().get("cvv") } # 获取有效期 def get_expiration(self, cardid): url = "https://api.bentoforbusiness.com/cards/{}".format(cardid) response = self.requests.get(url=url, headers=self.headers, verify=False, timeout=14) return { "expiration": response.json().get("expiration") } def billing_address(self, card_id): url = "https://api.bentoforbusiness.com/cards/{}/billingaddress ".format(card_id) data = { "id": 91308, "street": "1709 Elmwood Dr", "city": "Harlingen", "country": "US", "zipCode": "78550", "state": "TX", "addressType": "BUSINESS_ADDRESS", "bentoType": "com.bentoforbusiness.entity.business.BusinessAddress" } print(url) respone = requests.put(url, headers=self.headers, data=json.dumps(data), verify=False, timeout=14) print(respone.text) print(respone.status_code) if respone.status_code == 200: return True else: return False def get_card_list(self): url = "https://api.bentoforbusiness.com/cards?index=0&limit=0" res = self.requests.get(url, headers=self.headers, verify=False, timeout=14) crads = res.json().get('cards') # 返回未注销的所有卡信息(详细信息参数api文档card-list接口) # 单张开卡 def main_createcard(limit_num, card_amount, label, attribution): """ :param limit_num:开卡的数量 :param card_amount: 开卡的金额 :param label: 开卡的备注 :return: 返回开卡的数据并入库 """ for i in SqlDataNative.search_data(limit_num=limit_num): c = CreateCard().create_card(card_alias=i.get("username"), card_amount=card_amount, label=label, attribution=attribution) return c def get_bento_data(cardid): pan = CreateCard().get_pan(cardid) expiration = CreateCard().get_expiration(cardid) return { "pan": pan.get("pan"), "cvv": pan.get("cvv"), "expiration": expiration.get("expiration"), } if __name__ == "__main__": s = CreateCard() r = s.billing_address(1081270) print(r) # main(limit_num=3, card_amount=300, label="杨经理kevin") pass
[ "2404052713@qq.com" ]
2404052713@qq.com
2eb072af884631fbd7910780f193d2c35d9a976e
b6259a82de4b231c7f6ba20b0844d7d7ff263feb
/Chapter-02/os_path_dir.py
4c12f3c287d4494b90b2ec340de9efa34c8ea6f6
[]
no_license
gaoxuejian01/pychram_test01
e7665d52ff60162469ab665005d21ae8022e5a0a
63e6a6d2699f726aa5d850d234aa86838e814336
refs/heads/master
2020-05-09T16:25:18.212880
2019-04-21T08:24:14
2019-04-21T08:24:14
181,269,977
0
0
null
2019-04-14T08:14:24
2019-04-14T06:39:35
Python
UTF-8
Python
false
false
222
py
import os for dirpath,dienames,filenames in os.walk('/Users/gaoxuejian/PycharmProjects/pychram_test01/Chapter-02/'): print('['+dirpath+']') for filename in filenames: print(os.path.join(dirpath+filename))
[ "gaoxuejian@corp.netease.com" ]
gaoxuejian@corp.netease.com
e6d788a191a1d2289ff32fa827ae588336ee7073
245381ad175dcc03ee0710964340eed4daa2ef85
/administration/cognitive_solutions/programs/migrations/0028_batch_status.py
333e38ea1c83c46ae9155cd3861af6466c74646c
[]
no_license
musabansari-1/Shagroup-erp-backend
2c1f56f7ce5763dae668d160cdcc1a26dbc2e8d7
87845f11faae50301d5bb73ffa0c3ee0bed38256
refs/heads/main
2023-04-13T02:25:36.808755
2021-04-15T16:28:19
2021-04-15T16:28:19
358,324,699
0
0
null
null
null
null
UTF-8
Python
false
false
525
py
# Generated by Django 3.1.2 on 2020-12-27 12:55 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('programs', '0027_auto_20201227_1247'), ] operations = [ migrations.AddField( model_name='batch', name='status', field=models.PositiveSmallIntegerField(choices=[(1, 'Ongoing'), (0, 'Closed')], default=1, validators=[django.core.validators.MinValueValidator(0)]), ), ]
[ "musabzahida@gmail.com" ]
musabzahida@gmail.com
d1c1e00e01b900b0d44191595a8fc350956c6e53
942e89c730393d8134c373aba857612734b06373
/mysite/mysite/settings.py
4b1fafa1147ffec02c150adbea2e9b02298bf7e3
[]
no_license
jamwilson21/first_django_project
a6e75915b1417902d0141bced4d46b0672678782
0a7d67a96d7a4d424ae1577c73633eda7859b720
refs/heads/main
2023-04-19T11:35:25.865402
2021-04-30T11:24:23
2021-04-30T11:24:23
361,810,458
0
0
null
null
null
null
UTF-8
Python
false
false
3,133
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #application created by me 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
[ "monif64@gmail.com" ]
monif64@gmail.com
2f9af75898d23cf5abf51172f70817ff24aa0954
d6b87692b8cf3545bf7671e8d9fe53f189e339e2
/tftpsvr.py
d0aa282ab5d3d7e4173b558682cfc773dea7e1b9
[]
no_license
hendrasoewarno/HoneyPot
2d1b00d0d7e6b2be23494957b2630f94ba377796
5fb21d9be6ddb10ca4ed601a3affeb25f5e926fb
refs/heads/main
2023-08-16T06:30:36.779604
2021-09-23T07:29:49
2021-09-23T07:29:49
340,642,714
0
0
null
null
null
null
UTF-8
Python
false
false
8,193
py
''' Hendra Soewarno (0119067305) Honeypot TFTP ini tidak disertai pembatasan jumlah thread, sehingga perlu dilakukan pembatasan pada level firewall. /sbin/iptables -A INPUT -p udp --syn --dport 6969 -m connlimit --connlimit-above 50 -j REJECT TFtpSvr mensimulasikan server ftp untuk sebagai honeypot yang menarik penyerang untuk melakukan bruteforce password. Honeypot akan merekam semua userid dan password yang dicoba penyerang, sehingga menjadi early warning bagi administrator terkait dengan userid/password yang compromis. nohup python /path/to/tftpsvr.py & ''' #!/usr/bin/env python3 import time import datetime import socket import os import logging from logging.handlers import TimedRotatingFileHandler from _thread import * from pathlib import Path class Client: def __init__(self, opcode, filename, mode): self.opcode = opcode self.time = time.time() self.mode = mode self.currentBlock = 0 self.ackBlock = -1 self.closed = False self.errorCode = -1 now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M%S") + "." fn=Path(filename.decode("utf-8").replace(".",now,1)) try: if opcode==1: #Read request RRQ self.ackBlock = 0 self.currentBlock = 0 self.file0=open(filename, "rb") else: self.file0=open(fn, "xb") self.file1=open(filename, "wb") except IOError: self.errorCode = 1 self.closed = True def isClosed(self): return self.closed def isTimeOut(self): timeout = False if time.time() - self.time > 10: #second self.file0.close() if self.getOpcode() > 1: self.file1.close() timeout = True return timeout def getOpcode(self): return self.opcode def getErrorCode(self): return self.errorCode class RRQClient(Client): def getNextBlock(self): return self.ackBlock+1 def getNextData(self): if self.currentBlock == self.ackBlock: self.currentBlock = self.ackBlock + 1 #step next self.lastData = self.file0.read(512) if len(self.lastData) < 512: #EOF self.closed = True self.file0.close(); return self.lastData def ackReceived(self, block): print("ACK Recieve") print(block) self.ackBlock=block def isNextDataReady(self): print("IsNExtDataReady") print(self.currentBlock) print(self.ackBlock) return (self.currentBlock == self.ackBlock) #RRQ class WRQClient(Client): def putDataPacket(self, block, data): if block > self.ackBlock: self.file0.write(data) self.file1.write(data) self.currentBlock = block else: self.closed = True self.file0.close() self.file1.close() def isMustAck(self): return (self.ackBlock < self.currentBlock) #WRQ def getNextAckBlock(self): self.ackBlock=self.currentBlock return self.ackBlock def craftAckPacket(block): return b'\0\4' + block.to_bytes(2, byteorder='big') def craftDataPacket(block, data): return b'\0\3' + block.to_bytes(2, byteorder='big') + data def craftErrorPacket(errorCode): error = [b'Not defined, see error message (if any).', b'File not found.', b'Access violation.', b'Disk full or allocation exceeded.', b'Unknown transfer ID.', b'File already exists.', b'No such user.' ] return b'\0\5' + errorCode.to_bytes(2, byteorder='big') + error[errorCode] def parsePacketAndUpdate(client, address, packet): #https://tools.ietf.org/html/rfc1350 opcode = int.from_bytes(packet[0:2],byteorder='big') ''' pcode operation 1 Read request (RRQ) 2 Write request (WRQ) 3 Data (DATA) 4 Acknowledgment (ACK) 5 Error (ERROR) ''' if opcode == 1 or opcode == 2: #RRQ or WRQ print(packet) logger.info(packet) firstZPos = packet[2:].find(b'\0') filename = packet[2:][0:firstZPos] secondZPos = packet[2:][0:firstZPos].find(b'\0') mode = packet[2+firstZPos+1:secondZPos] secondZPos = packet[2+firstZPos:].find(b'\0') if opcode==1: client[address] = RRQClient(opcode, filename, mode) else: client[address] = WRQClient(opcode, filename, mode) elif opcode == 3: #DATA only posible for WRQ block = int.from_bytes(packet[2:4],byteorder='big') data = packet[4:] client[address].putDataPacket(block,data) elif opcode == 4: #ACK only posible for RRQ print(packet) block = int.from_bytes(packet[2:],byteorder='big') client[address].ackReceived(block) else: #ERROR print(packet) logger.info(packet) errorCode=int.from_bytes(packet[2:4],byteorder='big') ''' Value Meaning 0 Not defined, see error message (if any). 1 File not found. 2 Access violation. 3 Disk full or allocation exceeded. 4 Illegal TFTP operation. 5 Unknown transfer ID. 6 File already exists. 7 No such user. ''' errMsg=packet[4:-1] #entry point VERSION = "0.1a" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = "0.0.0.0" port = 6969 ThreadCount = 0 #create logger object logger = logging.getLogger() logger.setLevel(logging.INFO) #create logrotate daily, keep 30 days handler = TimedRotatingFileHandler('HPOTtftp.log', when='midnight', interval=1, backupCount=30) log_format="%(asctime)s %(levelname)s %(threadName)s %(message)s" handler.setFormatter(logging.Formatter(log_format)) logger.addHandler(handler) try: sock.bind((host, port)) except Exception as e: print(str(e)) logger.info("TFTP HoneyPot " + VERSION + " ready at port " + str(port)) print("TFTP HoneyPot " + VERSION + " ready at port " + str(port)) client = dict() #maintain each client session while True: ## Get the data and the address packet, address = sock.recvfrom(4096) print(address) logger.info(address) parsePacketAndUpdate(client, address, packet) try: if address in client: currentClient=client[address] if currentClient.getErrorCode() > -1: sock.sendto(craftErrorPacket(currentClient.getErrorCode()), address) for scanAddr in list(client): if client[scanAddr].isClosed(): print("Closed") logger.info("Closed") client.pop(scanAddr) #remove from client session elif client[scanAddr].isTimeOut(): print("Timeout") logger.info("Timeout") client.pop(scanAddr) #remove from client session if address in client: currentClient=client[address] if currentClient.getOpcode()==1: if currentClient.isNextDataReady(): sock.sendto(craftDataPacket(currentClient.getNextBlock(), currentClient.getNextData()), address) elif client[address].getOpcode()==2: if currentClient.isMustAck(): sock.sendto(craftAckPacket(currentClient.getNextAckBlock()), address) except Exception as e: print(str(e))
[ "noreply@github.com" ]
hendrasoewarno.noreply@github.com
bee97dd842ae97b96451af9fc27d7998ebdafcec
b6e49dfd3af7e352270e91d12f26acd383761da7
/Dojo_Assignments/Python/django/django_fundamentals/great_num_game/guess_me/views.py
22f575dc9efd31865e051a398bd3e766d7216629
[]
no_license
Banapple01/Coding_Dojo-School-work
b6fb0efc69cc7eac7195be7009167250e4f65096
adb15a673a7e6679a9772121d6a00006aac9e08b
refs/heads/master
2023-03-17T05:41:16.503413
2021-03-02T03:17:40
2021-03-02T03:17:40
295,498,032
0
0
null
null
null
null
UTF-8
Python
false
false
853
py
from django.shortcuts import render, redirect import random # Create your views here. def index(request): if 'number' in request.session: pass else: request.session['number'] = random.randint(1, 100) return render(request, 'index.html') def guess(request): print(request.POST['num']) if int(request.POST['num']) == int(request.session['number']): request.session['user_guess'] = 1 elif int(request.POST['num']) < int(request.session['number']): request.session['user_guess'] = 0 elif int(request.POST['num']) > int(request.session['number']): request.session['user_guess'] = 2 else: pass print(request.session['user_guess']) return redirect('/') def reset(request): del request.session['number'] del request.session['user_guess'] return redirect('/')
[ "48165909+Banapple01@users.noreply.github.com" ]
48165909+Banapple01@users.noreply.github.com
9443ed93cb6923faa3fbef387f96c0caceb2c2ef
1ddada988a52e9734a1ede434fb16fc43f9decd1
/app.py
62b767187956b44a7fa666bfca0f661b6824dc0f
[ "MIT" ]
permissive
Sanjukta-Das/JMP
016d5835b43581abf4b035225d04f8e89ab37abf
3c35f0ccdf4b2385219bb136f97bba657b605194
refs/heads/master
2022-12-27T12:42:49.746525
2020-09-27T20:01:36
2020-09-27T20:01:36
299,006,461
0
0
null
null
null
null
UTF-8
Python
false
false
155
py
from flask import Flask, current_app app = Flask(__name__) @app.route('/') def hello_world(): return current_app.send_static_file('EmployeeStats.htm')
[ "sanjukta.moocs@gmail.com" ]
sanjukta.moocs@gmail.com
606381979829657434fd9845d5a2027149122b34
50e81c2e7b5bc8e8cf31ecedc271e615e896cc99
/venv/3.F.py
6f1b09f79e82fdcf6cfeea228fec96d961a10487
[]
no_license
Anupreet1299/practice
1faec9e1658b7d396ebd3360c1f29a33a612f7eb
23d269ad8af63bf08cb5322ba99c79812c488308
refs/heads/master
2020-06-02T09:51:48.340194
2019-06-10T07:19:19
2019-06-10T07:19:19
191,119,843
1
0
null
null
null
null
UTF-8
Python
false
false
216
py
#loops or iterations #for loop num = int(input("enter a number =")) #for i in range(0, 11): #print(i**2) #for i in range(1, 11, 2): #print(i**2) #while loops i= 1 while i<10: print( i*num) i+=1
[ "anupreet1299@gmail.com" ]
anupreet1299@gmail.com
a0c1d414f21baf68c328be27697aebb68ac82837
b83ac23819fd7ba998563f2ad870405bdd07cc2b
/experiments/manual_play/v18/minimal_defense/manual_vs_openai_ppo/run.py
26d31c17ed5758f25146ba6d7d050c98873f9e3f
[ "MIT" ]
permissive
Limmen/gym-idsgame
699abd2894bce15108f1606f5fb71f612dd7ba03
d10830fef55308d383c98b41b34688a7fceae357
refs/heads/master
2023-09-01T17:32:16.768138
2023-08-22T12:00:53
2023-08-22T12:00:53
247,794,752
49
12
MIT
2021-04-21T07:50:06
2020-03-16T19:00:27
Python
UTF-8
Python
false
false
4,632
py
import os from gym_idsgame.config.runner_mode import RunnerMode from gym_idsgame.agents.dao.agent_type import AgentType from gym_idsgame.config.client_config import ClientConfig from gym_idsgame.agents.training_agents.policy_gradient.pg_agent_config import PolicyGradientAgentConfig from gym_idsgame.runnner import Runner from experiments.util import util def default_output_dir() -> str: """ :return: the default output dir """ script_dir = os.path.dirname(__file__) return script_dir def default_config_path() -> str: """ :return: the default path to configuration file """ config_path = os.path.join(default_output_dir(), './config.json') return config_path def default_config() -> ClientConfig: """ :return: Default configuration for the experiment """ env_name = "idsgame-v18" pg_agent_config = PolicyGradientAgentConfig(gamma=1, alpha_attacker=0.00001, epsilon=1, render=False, alpha_defender=0.0001, eval_sleep=0.9, min_epsilon=0.01, eval_episodes=100, train_log_frequency=1, epsilon_decay=0.9999, video=True, eval_log_frequency=1, video_fps=5, video_dir=default_output_dir() + "/results/videos", num_episodes=100000000, eval_render=False, gifs=True, gif_dir=default_output_dir() + "/results/gifs", eval_frequency=100000, attacker=True, defender=False, video_frequency=101, save_dir=default_output_dir() + "/results/data", checkpoint_freq=5000, input_dim_attacker=(4 + 2) * 2, output_dim_attacker=(4+1) * 2, input_dim_defender=(4 + 2) * 3, output_dim_defender=5 * 3, hidden_dim=64, num_hidden_layers=4, batch_size=2000, gpu=False, tensorboard=True, tensorboard_dir=default_output_dir() + "/results/tensorboard", optimizer="Adam", lr_exp_decay=False, lr_decay_rate=0.999, state_length=1, normalize_features=False, merged_ad_features=True, zero_mean_features=False, gpu_id=0, lstm_network=False, lstm_seq_length=4, num_lstm_layers=2, optimization_iterations=10, eps_clip=0.2, max_gradient_norm=0.5, gae_lambda=0.95, cnn_feature_extractor=False, features_dim=512, flatten_feature_planes=False, attacker_load_path="/home/kim/storage/workspace/gym-idsgame/experiments/manual_play/v18/minimal_defense/manual_vs_openai_ppo/1591093705.5003314_attacker_policy_network.zip") client_config = ClientConfig(env_name=env_name, attacker_type=AgentType.PPO_OPENAI_AGENT.value, mode=RunnerMode.MANUAL_DEFENDER.value, output_dir=default_output_dir(), title="OpenAI PPO vs ManualDefender", pg_agent_config=pg_agent_config, bot_attacker=True) return client_config def write_default_config(path:str = None) -> None: """ Writes the default configuration to a json file :param path: the path to write the configuration to :return: None """ if path is None: path = default_config_path() config = default_config() util.write_config_file(config, path) # Program entrypoint if __name__ == '__main__': args = util.parse_args(default_config_path()) if args.configpath is not None: if not os.path.exists(args.configpath): write_default_config() config = util.read_config(args.configpath) else: config = default_config() Runner.run(config)
[ "kimham@kth.se" ]
kimham@kth.se
44fec512f858f521f2d76229d04f02f0ab5fe4d5
c8ea4fe0dccca928b92234b72a7a8d9cd6cf4d14
/eth2/beacon/deposit_helpers.py
687e2a55062aaf64f094f3a6293fc962823480bf
[ "MIT" ]
permissive
kclowes/trinity
b6bc4f7c57ade1651cf9b2ca9ca88493f3485007
f0400c78a6d828dd266b1f31dd3fa7aacf97486d
refs/heads/master
2020-04-16T16:11:28.531260
2019-01-14T17:03:56
2019-01-14T17:44:58
165,728,497
0
0
MIT
2019-01-14T20:17:01
2019-01-14T20:17:00
null
UTF-8
Python
false
false
4,087
py
from eth_typing import ( Hash32, ) from eth_utils import ( ValidationError, ) from eth2._utils import bls from eth2.beacon.constants import ( EMPTY_SIGNATURE, ) from eth2.beacon.enums import ( SignatureDomain, ) from eth2.beacon.types.deposit_input import DepositInput from eth2.beacon.types.states import BeaconState from eth2.beacon.types.validator_records import ValidatorRecord from eth2.beacon.helpers import ( get_domain, ) from eth2.beacon.typing import ( BLSPubkey, BLSSignature, ValidatorIndex, Gwei, ) def validate_proof_of_possession(state: BeaconState, pubkey: BLSPubkey, proof_of_possession: BLSSignature, withdrawal_credentials: Hash32, randao_commitment: Hash32, custody_commitment: Hash32) -> None: deposit_input = DepositInput( pubkey=pubkey, withdrawal_credentials=withdrawal_credentials, randao_commitment=randao_commitment, custody_commitment=custody_commitment, proof_of_possession=EMPTY_SIGNATURE, ) is_valid_signature = bls.verify( pubkey=pubkey, # TODO: change to hash_tree_root(deposit_input) when we have SSZ tree hashing message=deposit_input.root, signature=proof_of_possession, domain=get_domain( state.fork_data, state.slot, SignatureDomain.DOMAIN_DEPOSIT, ), ) if not is_valid_signature: raise ValidationError( "BLS signature verification error" ) def add_pending_validator(state: BeaconState, validator: ValidatorRecord, amount: Gwei) -> BeaconState: """ Add a validator to ``state``. """ state = state.copy( validator_registry=state.validator_registry + (validator,), validator_balances=state.validator_balances + (amount, ), ) return state def process_deposit(*, state: BeaconState, pubkey: BLSPubkey, amount: Gwei, proof_of_possession: BLSSignature, withdrawal_credentials: Hash32, randao_commitment: Hash32, custody_commitment: Hash32) -> BeaconState: """ Process a deposit from Ethereum 1.0. """ validate_proof_of_possession( state=state, pubkey=pubkey, proof_of_possession=proof_of_possession, withdrawal_credentials=withdrawal_credentials, randao_commitment=randao_commitment, custody_commitment=custody_commitment, ) validator_pubkeys = tuple(v.pubkey for v in state.validator_registry) if pubkey not in validator_pubkeys: validator = ValidatorRecord.create_pending_validator( pubkey=pubkey, withdrawal_credentials=withdrawal_credentials, randao_commitment=randao_commitment, custody_commitment=custody_commitment, ) # Note: In phase 2 registry indices that has been withdrawn for a long time # will be recycled. state = add_pending_validator( state, validator, amount, ) else: # Top-up - increase balance by deposit index = ValidatorIndex(validator_pubkeys.index(pubkey)) validator = state.validator_registry[index] if validator.withdrawal_credentials != withdrawal_credentials: raise ValidationError( "`withdrawal_credentials` are incorrect:\n" "\texpected: %s, found: %s" % ( validator.withdrawal_credentials, validator.withdrawal_credentials, ) ) # Update validator's balance and state state = state.update_validator_balance( validator_index=index, balance=state.validator_balances[index] + amount, ) return state
[ "hwwang156@gmail.com" ]
hwwang156@gmail.com
9d39f65fec0f9b59b6ed2cfa384702ba5fd9443d
d4e9b94d9db1a49d1b2ecdfd88c5277c89ad17c3
/Function(def).py
cba7e401de27d0ca308b551200362a80baa5056f
[]
no_license
abdulwagab/Demopygit
1560123048f2924fa43030d12ad41b0ce3ddf69f
17b2f1fa435cbee9c34d91267075092828b4d42a
refs/heads/master
2022-12-30T19:47:56.115158
2020-10-15T01:51:04
2020-10-15T01:51:04
271,227,717
3
0
null
2020-10-04T23:46:02
2020-06-10T08:54:53
Python
UTF-8
Python
false
false
306
py
def clock(a, b): #function definition sum = a + b #adding the arguments and store it to sum return sum #return the value clock1 = 5; #Assigning values to variable clock2 = 3; #Assigning values to variable print("clock value is: ", clock(clock1, clock2)); #print the statement
[ "noreply@github.com" ]
abdulwagab.noreply@github.com
60fae60da800ce41b7d9e2d49956de686189aca6
4bc19439ba498e16264e0f5e9557f6effc10c248
/classes/classes_08_Constructors.py
329d6682d6a2e37ae5927a9d9a16c576643ed7e9
[]
no_license
wastefulox/learningpython
7fe7ee3bcee670fe39aadfffb14d7e44e0b4b96a
c34391798372bfc30034f520443a3c308f352e68
refs/heads/master
2020-04-05T16:58:32.983506
2020-02-11T01:13:08
2020-02-11T01:13:08
157,037,963
0
0
null
null
null
null
UTF-8
Python
false
false
205
py
class Circle: pi = 3.14 # Add constructor here: def __init__(self, diameter): print("New circle with diameter: {diameter}".format(diameter=int(diameter))) teaching_table = Circle(36)
[ "mathew.sturdevant@mail.strayer.edu" ]
mathew.sturdevant@mail.strayer.edu
504701a5db3c11a2ad30fc14efd2e21fd1165f5c
259bd89b5086517b26eb0e99fe09c6b7dbdad638
/react_comm/config/wsgi.py
2da5615228a3c0859219019a2e05bafd7c687b29
[ "MIT" ]
permissive
skyshop300/react_comm
4d7a3c1c32874bf2fdd947ce0ab3092738447a86
caa8fdb9a2591473c86979c451c1a489190e8789
refs/heads/master
2020-05-07T08:53:19.512114
2019-12-30T07:56:09
2019-12-30T07:56:09
180,351,131
0
0
null
null
null
null
UTF-8
Python
false
false
1,684
py
""" WSGI config for react_community project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import sys from django.core.wsgi import get_wsgi_application # This allows easy placement of apps within the interior # psy directory. app_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) sys.path.append(os.path.join(app_path, "psy")) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
[ "skyshop5210@gmail.com" ]
skyshop5210@gmail.com
e59818c7a431b96f28be9313607888e4cf91ed94
d34074274d8d5f480c192cdcc020df3e1e2626cd
/online_exam/admin.py
f519992cb38995282137ac67ac954815d20a432c
[]
no_license
Lishat/Online-Examination-Portal
d3c68e32f6b3f4a0b48fec543f60ba46247aa34c
4f70bea29c847e75e75fe12bab6699ae095b1a11
refs/heads/master
2020-04-27T10:28:58.356995
2019-03-07T02:19:42
2019-03-07T02:19:42
174,255,861
2
2
null
null
null
null
UTF-8
Python
false
false
627
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import course, user, topic, subtopic, question_type, level, exam_detail, question_bank, option, answer, registration, result # Register your models here. admin.site.register(course) admin.site.register(user) admin.site.register(topic) admin.site.register(subtopic) admin.site.register(question_type) admin.site.register(level) admin.site.register(exam_detail) admin.site.register(question_bank) admin.site.register(option) admin.site.register(answer) admin.site.register(registration) admin.site.register(result)
[ "30794115+Lishat@users.noreply.github.com" ]
30794115+Lishat@users.noreply.github.com
af216a9be8b1a87518fc54ab5ea1287a827ce0c0
c9a809c5ef2a6b5e7e50da548c182510d203f430
/tests/unit/modules/test_cpan.py
c02cbafec92196df308d334df7b8fb287354f7ba
[ "Apache-2.0" ]
permissive
andyyumiao/saltx
676a44c075ce06d5ac62fc13de6dcd750b3d0d74
a05c22a60706b5c4389adbd77581b5cf985763b5
refs/heads/master
2022-02-24T00:51:42.420453
2022-02-09T06:46:40
2022-02-09T06:46:40
231,860,568
1
5
NOASSERTION
2022-02-09T06:46:40
2020-01-05T03:10:15
Python
UTF-8
Python
false
false
4,945
py
# -*- coding: utf-8 -*- ''' :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import TestCase, skipIf from tests.support.mock import ( MagicMock, patch, NO_MOCK, NO_MOCK_REASON ) # Import Salt Libs import salt.modules.cpan as cpan @skipIf(NO_MOCK, NO_MOCK_REASON) class CpanTestCase(TestCase, LoaderModuleMockMixin): ''' Test cases for salt.modules.cpan ''' # 'install' function tests: 2 def setup_loader_modules(self): return {cpan: {}} def test_install(self): ''' Test if it install a module from cpan ''' mock = MagicMock(return_value='') with patch.dict(cpan.__salt__, {'cmd.run': mock}): mock = MagicMock(side_effect=[{'installed version': None}, {'installed version': '3.1'}]) with patch.object(cpan, 'show', mock): self.assertDictEqual(cpan.install('Alloy'), {'new': '3.1', 'old': None}) def test_install_error(self): ''' Test if it install a module from cpan ''' mock = MagicMock(return_value="don't know what it is") with patch.dict(cpan.__salt__, {'cmd.run': mock}): self.assertDictEqual(cpan.install('Alloy'), {'error': 'CPAN cannot identify this package', 'new': None, 'old': None}) # 'remove' function tests: 4 def test_remove(self): ''' Test if it remove a module using cpan ''' with patch('os.listdir', MagicMock(return_value=[''])): mock = MagicMock(return_value='') with patch.dict(cpan.__salt__, {'cmd.run': mock}): mock = MagicMock(return_value={'installed version': '2.1', 'cpan build dirs': [''], 'installed file': '/root'}) with patch.object(cpan, 'show', mock): self.assertDictEqual(cpan.remove('Alloy'), {'new': None, 'old': '2.1'}) def test_remove_unexist_error(self): ''' Test if it try to remove an unexist module using cpan ''' mock = MagicMock(return_value="don't know what it is") with patch.dict(cpan.__salt__, {'cmd.run': mock}): self.assertDictEqual(cpan.remove('Alloy'), {'error': 'This package does not seem to exist'}) def test_remove_noninstalled_error(self): ''' Test if it remove non installed module using cpan ''' mock = MagicMock(return_value={'installed version': None}) with patch.object(cpan, 'show', mock): self.assertDictEqual(cpan.remove('Alloy'), {'new': None, 'old': None}) def test_remove_nopan_error(self): ''' Test if it gives no cpan error while removing ''' ret = {'error': 'No CPAN data available to use for uninstalling'} mock = MagicMock(return_value={'installed version': '2.1'}) with patch.object(cpan, 'show', mock): self.assertDictEqual(cpan.remove('Alloy'), ret) # 'list' function tests: 1 def test_list(self): ''' Test if it list installed Perl module ''' mock = MagicMock(return_value='') with patch.dict(cpan.__salt__, {'cmd.run': mock}): self.assertDictEqual(cpan.list_(), {}) # 'show' function tests: 2 def test_show(self): ''' Test if it show information about a specific Perl module ''' mock = MagicMock(return_value='') with patch.dict(cpan.__salt__, {'cmd.run': mock}): self.assertDictEqual(cpan.show('Alloy'), {'error': 'This package does not seem to exist', 'name': 'Alloy'}) def test_show_mock(self): ''' Test if it show information about a specific Perl module ''' with patch('salt.modules.cpan.show', MagicMock(return_value={'Salt': 'salt'})): mock = MagicMock(return_value='Salt module installed') with patch.dict(cpan.__salt__, {'cmd.run': mock}): self.assertDictEqual(cpan.show('Alloy'), {'Salt': 'salt'}) # 'show_config' function tests: 1 def test_show_config(self): ''' Test if it return a dict of CPAN configuration values ''' mock = MagicMock(return_value='') with patch.dict(cpan.__salt__, {'cmd.run': mock}): self.assertDictEqual(cpan.show_config(), {})
[ "yumiao3@jd.com" ]
yumiao3@jd.com
843946bab7cf27019c3609443da623c27ddcd33f
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03347/s362816288.py
ef42242a7d6bc72e9552c630edd29cff9fdb40cd
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
192
py
n = int(input()) a = [int(input()) for i in range(n)] ans = 0 now = -1 for i in a: if i > now + 1: print(-1) exit() elif i < now + 1: ans += now now = i ans += now print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
3ac4aba32b17efca5a6d5896bd4bafe0205a8e1a
b2ab9ce84968f854cd15cfb777ba517c29e30cb5
/Python/Tests/test_epi_5.py
0b1b0578d4756365c713e7800fae32913ea5033d
[]
no_license
dongpin/AlgorithmProblems
662c933570e7999d0e04f6926c11c9fb79f2c59e
266c677ad8ed16cecc2dfb5a6149b4244ffe23ef
refs/heads/master
2020-03-23T17:56:37.746598
2019-08-27T08:58:42
2019-08-27T08:58:42
141,882,231
0
0
null
null
null
null
UTF-8
Python
false
false
225
py
import unittest from Python.Problems.epi5_6_buy_and_sell_a_stock_once import * # Test Cases def test_buy_and_sell_a_stock_once(): assert buy_and_sell_stock_once([310, 315, 275, 295, 260, 270, 290, 230, 255, 250]) == 30
[ "dongpin@hotmail.com" ]
dongpin@hotmail.com
7d4233037408163106582970979f683a0c034959
dc94aea96ed3e3fcd890b9b6e3e624cb06b5b134
/process.py
e28f8a264720e154e18438b373b37085f2f2642b
[ "BSD-3-Clause" ]
permissive
Sec-Fork/SiteScan
af6c3b28820f27894fc45d582220e8d9861c5d0f
6f8fa9487f0a7cba5105246ccf031ecca1124ee3
refs/heads/main
2023-09-06T05:46:13.736992
2021-11-26T10:33:10
2021-11-26T10:33:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,699
py
# -*- coding:utf-8 -*- # by:kracer # 引入模块、包部分 import re, json, sys import html import dominate from dominate.tags import * # 对allDict的数据处理函数 def processData(allDict): global nowIP, historyIP, isCDN, domain, ports, pangZhan, whois, urlPATH, beiAn, framework, cms, waf, houTai, error nowIP = allDict['nowIP'] if nowIP == []: nowIP = ['空', '空'] else: nowIP = nowIP[0].split('::') historyIP = allDict['historyIP'] historyIP_list = [] if historyIP == []: historyIP = ['空', '空'] isCDN = allDict['isCDN'] if isCDN == []: isCDN = [{'ip': '空', 'location': '空', 'exist': '空'}] else: if len(isCDN) >= 2: isCDN += [{'exist': "存在CDN"}] else: isCDN += [{'exist': "不存在CDN"}] domain0 = allDict["domain"] if domain0 == []: domain = ['空'] else: domain = list(set(domain0)) # 去重 ports0 = allDict["ports"] if ports0 == []: ports = ['空'] else: ports = list(set(ports0)) pangZhan0 = allDict["pangZhan"] if pangZhan0 == []: pangZhan = ['空'] else: pangZhan = list(set(pangZhan0)) whois = allDict["whois"] if (whois == [[]]) or (whois == []): whois = {'空': '空'} else: whois = whois[0] urlPathList = [] for urlPath in allDict["urlPATH"]: if '://' in urlPath: url0 = urlPath[urlPath.find(':')+3:] urlPathList.append(url0) else: urlPathList.append(urlPath) urlPATH = list(set(urlPathList)) if urlPATH == []: urlPATH = ['空'] beiAn = allDict["beiAn"] if beiAn == []: beiAn = ['空:空', '空:空'] framework = allDict["framework"] if framework[0] == []: framework[0] = ['空', '空'] cms = framework[1] if cms == {}: cms = {'空': '空'} waf = framework[2] if waf == {}: waf = {'waf': '没有侦测到waf'} houTai_list = ['admin', 'login', 'pass', 'user', 'member', 'system', 'manage', 'service', 'main'] houTai = [] for d in urlPATH: for k in houTai_list: if k in d: houTai.append(d) for t in houTai: try: urlPATH.remove(t) except Exception as e: continue error = allDict['error'] def all2HTML(url, allDict): processData(allDict) doc = dominate.document(title='webscan_report') with doc.head: link(rel='stylesheet', type="text/css", href='..\lib\\css\\bootstrap.min.css') meta(charset="utf-8") meta(name="viewport", content="width=device-width, initial-scale=1") with doc.body: body(cls="table-responsive") h2('探测目标:{0}'.format(url), cls="text-center text-success") # 定义上文 br() '''域名ip地址解析----allDict["nowIP"]、allDict["histotyIP"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("域名地址解析", cls="text-center text-info bg-success") tr(td('当前域名ip解析:', align="center"), td('{0}'.format(nowIP[0]), align="center"), td('{0}'.format(nowIP[1]), align="center")) for i in historyIP: data = i.split("::") if len(data) < 2: data = ["空", "空"] tr(td('历史域名ip解析:', align="center"), td('{0}'.format(data[0]), align="center"), td('{0}'.format(data[1]), align="center")) br() '''网站是否存在CDN解析----allDict["isCDN"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("是否存在CDN", cls="text-center text-info bg-success") tr(td('ip', align="center"), td('location', align="center")) data1 = [] for i in isCDN: for k, v in i.items(): data1.append(v) for j in range(0, (len(data1)-1), 2): tr(td('{0}'.format(data1[j]), align="center"), td('{0}'.format(data1[j+1]), align="center")) tr(td('{0}'.format(data1[-1]), align="center", colspan="2")) br() '''网站是子域名解析----allDict["domain"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("子域名解析", cls="text-center text-info bg-success") for i in domain: tr(td('{0}'.format(i), align="center")) br() '''网站端口开放解析----allDict["ports"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网站端口开放情况", cls="text-center text-info bg-success") for i in ports: tr(td('{0}'.format(i), align="center")) br() '''网站的旁站解析----allDict["pangZhan"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网站的旁站情况", cls="text-center text-info bg-success") for i in pangZhan: tr(td('{0}'.format(i), align="center")) br() '''根域名的whois解析----allDict["whois"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网站的whois情况", cls="text-center text-info bg-success") for i, k in whois.items(): tr(td('{0}'.format(i), align="center"), td('{0}'.format(k), align="center")) br() '''网址的目录解析----allDict["urlPATH"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网址的目录解析", cls="text-center text-info bg-success") for h in houTai: tr(td('可能的后台地址: {0}'.format(h), align="center")) for i in urlPATH: tr(td('{0}'.format(i), align="center")) br() '''网站的备案解析----allDict["beiAn"]''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网站的备案信息", cls="text-center text-info bg-success") for i in beiAn: if type(i) != dict: data = i.split(":") tr(td('{0}'.format(data[0]), align="center"), td('{0}'.format(data[1]), align="center")) else: for k, v in i.items(): tr(td('{0}'.format(k), align="center"), td('{0}'.format(v), align="center")) br() '''网站的whatweb架构信息----whatweb''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网址的架构解析", cls="text-center text-info bg-success") for i in framework[0]: tr(td('{0}'.format(i), align="center")) br() '''网站的CMS架构信息----cms''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网址的CMS解析", cls="text-center text-info bg-success") for k, v in cms.items(): tr(td('{0}'.format(k), align="center"), td('{0}'.format(v), align="center")) br() '''网站的WAF信息----waf''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("网址的WAF解析", cls="text-center text-info bg-success") for k, v in waf.items(): tr(td('{0}'.format(k), align="center"), td('{0}'.format(v), align="center")) br() '''侦测过程的报错信息----error''' with table(cls="table table-responsive table-bordered table-hover").add(tbody()): caption("侦测过程的错误信息", cls="text-center text-info bg-success") if error != []: for e in error: tr(td('{0}'.format(e), align="center")) else: tr(td('{0}'.format("运行过程完好无报错!"), align="center")) br() br() br() with open('output/{0}_report.html'.format(url), 'w', encoding='utf-8') as f: f.write(doc.render()) print("\033[1;34m[*] 检测报告位置: output/{0}_report.html!!\033[0m \n".format(url))
[ "noreply@github.com" ]
Sec-Fork.noreply@github.com
21b2d7ca3640fbcf1c9629ad2004783e9883ed59
0ff832fee21987d0dfbfd8794c202fef3802cf23
/posts/migrations/0001_initial.py
fae0fc45c62b46cd923dfb4e5ff59c6587660b30
[]
no_license
Wings30306/django-blog
84f35423ed78e72bccad5d0de92fb72e61892617
37c92beef49e6285209e0949a838a3b57e4892d7
refs/heads/master
2022-12-15T09:10:42.078232
2019-04-14T08:30:16
2019-04-14T08:30:16
181,018,448
0
0
null
2022-11-22T03:46:03
2019-04-12T13:55:47
Python
UTF-8
Python
false
false
1,046
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-04-13 14:42 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('content', models.TextField()), ('created_date', models.DateTimeField(auto_now_add=True)), ('published_date', models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True)), ('views', models.IntegerField(default=0)), ('tag', models.CharField(blank=True, max_length=30, null=True)), ('image', models.ImageField(blank=True, null=True, upload_to='img')), ], ), ]
[ "jo_hannah@outlook.com" ]
jo_hannah@outlook.com
d058fee429ba36f54252510df71cf8497ef955f9
3e7f505baf1798975f1b14379a6ec05b381184a3
/automl/automl.py
ad9ed15f9285c321dbead83b47765701f0ba6506
[]
no_license
claudioti/machine-learning
e8099a8b5ce68b5a46a8af4ab45068fab53f9ebe
56cb4b5c90c71fa8f744283c29d757a3dedc352d
refs/heads/master
2023-07-14T11:01:17.336814
2021-08-22T22:22:08
2021-08-22T22:22:08
364,391,769
0
0
null
null
null
null
UTF-8
Python
false
false
1,196
py
# define dataset from pandas import np from sklearn.model_selection import RepeatedStratifiedKFold from tpot import TPOTClassifier from utils import functions, Constants from torch import nn import pandas as pd dataset = np.loadtxt(Constants.dataset_path_final,delimiter=',',skiprows=1) #dataset = pd.read_csv(Constants.dataset_path_final) #dataset = functions.read_data(path=Constants.dataset_path_final, fillna=True, normalization=False) ##DROPING IP COLUMN #dataset = np.delete(dataset, 5, 1) X = dataset[:, :-1] y = dataset[:, -1] y = y.astype(int) # define model evaluation ##cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) # define search ##model = TPOTClassifier(generations=5, population_size=50, cv=cv, scoring='accuracy', verbosity=2, random_state=1, n_jobs=1) model = TPOTClassifier(generations=5, population_size=50, cv=cv, scoring='accuracy', verbosity=2, random_state=1, n_jobs=4, max_eval_time_mins=2) # perform the search model.fit(X, y) # export the best model model.export('C:\\Mestrado\\machine-learning\\tpot_sonar_best_model_new.py')
[ "cmarques@smithmicro.com" ]
cmarques@smithmicro.com
aa9452df9fcbf5450de6e6e947235b0a322e03a3
9d3b7fd011c06344f7ec66039a04a24d45b7cee0
/board.py
f46b7f163089af9eb141ef9c2618aa21b23dd8a7
[]
no_license
jishnusen/karel
15adaa8207997f3955a1a39c685ff58b4ec7059a
8d3d79b0c5fc1d8ed42d964a390686df7c56bb9e
refs/heads/master
2021-01-20T03:17:20.380696
2017-09-07T03:43:47
2017-09-07T03:43:47
101,358,601
0
1
null
2017-08-25T03:37:19
2017-08-25T02:44:09
Python
UTF-8
Python
false
false
4,980
py
#!/usr/bin/env python import curses import time from karel import Karel class LogicException(Exception): pass class Board(object): KAREL_CHARS = '<^>v' BEEPER_CHAR = 'o' def __init__(self, map_path): self.map = None self.karel = None self.screen = None self.beepers = [] self.construct_map(map_path) def __enter__(self): self.start_screen() return self def __exit__(self, *args): self.end_screen() def start_screen(self): self.screen = curses.initscr() curses.start_color() # wall curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_WHITE) # Karel curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) # beeper curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Karel on beeper curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK) def end_screen(self): self.screen.getch() curses.endwin() def construct_map(self, map_path): directions = { '>': (1, 0), '^': (0, 1), '<': (-1, 0), 'v': (0, -1), } map = [[]] with open(map_path, 'rb') as f: for y, line in enumerate(f): row = [] for x, char in enumerate(line.strip()): if char in self.KAREL_CHARS: self.karel = Karel((x + 1, y + 1), directions[char]) char = '.' elif char == self.BEEPER_CHAR: self.beepers.append((x + 1, y + 1)) char = '.' row.append(char) map.append(['#'] + row + ['#']) map.append([]) for _ in xrange(len(map[1])): map[0].append('#') map[-1].append('#') self.map = map def draw(self): screen = self.screen for y, row in enumerate(self.map): for x, char in enumerate(row): args = [y + 1, x, char] if char == '#': args.append(curses.color_pair(1)) elif char == 'o': args.append(curses.color_pair(3)) screen.addstr(*args) beeper_color = curses.color_pair(3) for bx, by in self.beepers: screen.addstr(by + 1, bx, 'o', beeper_color) screen.addstr( self.karel.position[1] + 1, self.karel.position[0], self.karel_char(), curses.color_pair(4) if self.beeper_is_present() else curses.color_pair(2) ) screen.addstr(y + 4, 0, ' ') screen.refresh() time.sleep(0.5) def draw_exception(self, exception): curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK) self.screen.addstr(0, 0, str(exception), curses.color_pair(5)) def karel_char(self): # index will be in (-2, -1, 1, 2) index = self.karel.facing[0] + 2*self.karel.facing[1] return ' >v^<'[index] # Karel passthroughs def move(self): if not self.front_is_clear(): raise LogicException('can\'t move. There is a wall in front of Karel') self.karel.move() def turn_left(self): self.karel.turn_left() def pick_beeper(self): position = self.karel.position for i, coord in enumerate(self.beepers): if coord == self.karel.position: del self.beepers[i] self.karel.pick_beeper() break else: raise LogicException('can\'t pick beeper from empty location') def put_beeper(self): if not self.holding_beepers(): raise LogicException('can\'t put beeper. Karel has none') self.beepers.append(self.karel.position) self.karel.put_beeper() # world conditions def front_is_clear(self): next_x = self.karel.position[0] + self.karel.facing[0] next_y = self.karel.position[1] + self.karel.facing[1] return self.map[next_y][next_x] == '.' def left_is_clear(self): next_x = self.karel.position[0] + self.karel.facing[1] next_y = self.karel.position[1] - self.karel.facing[0] return self.map[next_y][next_x] == '.' def right_is_clear(self): next_x = self.karel.position[0] - self.karel.facing[1] next_y = self.karel.position[1] + self.karel.facing[0] return self.map[next_y][next_x] == '.' def facing_north(self): return self.karel.facing[1] == -1 def facing_south(self): return self.karel.facing[1] == 1 def facing_east(self): return self.karel.facing[0] == 1 def facing_west(self): return self.karel.facing[0] == -1 def beeper_is_present(self): return self.karel.position in self.beepers def holding_beepers(self): return self.karel.holding_beepers()
[ "stephen@evilrobotstuff.com" ]
stephen@evilrobotstuff.com
abf9506c61329778d9bfcf4d1a551b867c255d03
f18cd4f9fc23dcf895aa00a4a565c2e7a811a1af
/logic/board.py
d2cc71bf8071adcaba903377c368fc0d2ba54490
[ "MIT" ]
permissive
shri3016/Project
9ce86ab605d42ab064ec724b32bd505db1fca311
28e25d3726239771b123354de1847725f0bb1845
refs/heads/main
2023-01-23T11:14:57.334139
2020-11-29T14:20:55
2020-11-29T14:20:55
316,783,038
0
0
MIT
2020-11-28T17:10:56
2020-11-28T17:10:56
null
UTF-8
Python
false
false
316
py
def generate_board(): board = [[0 for i in range(10)] for i in range(10)] k = 1 for i in range(10): for j in range(10): board[i][j] = k k+=1 return board def show_board(board): for i in board: for j in i: print(j,end=' ') print()
[ "noreply@github.com" ]
shri3016.noreply@github.com
bc2e3114b26436a81ffc96ea3c0901c1a1ce21f8
b21c601920ed0a1a3382588eb8a581cb8b459115
/configuration.py
8da405813ff073cfd4469e6bb41df94ea5f1ff77
[]
no_license
Langlofts/flaskStorageDemo
1674ab2a4d7cbc674cdd793cf67522b9ab3d7ed3
4b0ebefbd730b01f685c88dde28c5c2233050522
refs/heads/master
2023-02-05T23:52:53.223918
2020-02-19T08:53:16
2020-02-19T08:53:16
241,562,232
0
0
null
null
null
null
UTF-8
Python
false
false
760
py
class Config(object): DEBUG = False TESTING = False class ProductionConfig(Config): AZURE_STORE_CONNECTION ="DefaultEndpointsProtocol=https;AccountName=pydemostore;AccountKey=EDI1bZePwltDk6slUoVAd/TUAhBSmCEv60WQK24+PsDsRXnZq6mRuB5HFROGOQFDYq8TXRsUpI/o38lR2HEbeA==;EndpointSuffix=core.windows.net" BLOB_CONTAINER ="profilepic" TABLE_NAME = "profile" QUEUE_NAME = "profilequeue" class DevelopmentConfig(Config): DEBUG = True AZURE_STORE_CONNECTION ="DefaultEndpointsProtocol=https;AccountName=pydemostore;AccountKey=EDI1bZePwltDk6slUoVAd/TUAhBSmCEv60WQK24+PsDsRXnZq6mRuB5HFROGOQFDYq8TXRsUpI/o38lR2HEbeA==;EndpointSuffix=core.windows.net" BLOB_CONTAINER ="profilepic" TABLE_NAME = "profile" QUEUE_NAME = "profilequeue"
[ "justinvv2321@gmail.com" ]
justinvv2321@gmail.com
8ef63c8ffc23692ae6897c70c5a28ac531aaad7b
be3d301bf8c502bb94149c76cc09f053c532d87a
/python/GafferImageTest/FormatDataTest.py
1586d86f9a2116930c71e23969ddf0c968385dff
[ "BSD-3-Clause" ]
permissive
ljkart/gaffer
28be401d04e05a3c973ef42d29a571aba6407665
d2ce0eb7134a33ceee375d0a3676129a9bdcfbc6
refs/heads/master
2021-01-18T08:30:19.763744
2014-08-10T13:48:10
2014-08-10T13:48:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,148
py
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import unittest import IECore import Gaffer import GafferImage class FormatDataTest( unittest.TestCase ) : def test( self ) : f1 = GafferImage.Format( IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 200, 100 ) ), 0.5 ) f2 = GafferImage.Format( IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 200, 100 ) ), 1 ) fd1a = GafferImage.FormatData( f1 ) fd1b = GafferImage.FormatData( f1 ) fd2 = GafferImage.FormatData( f2 ) self.assertEqual( fd1a.value, f1 ) self.assertEqual( fd1b.value, f1 ) self.assertEqual( fd2.value, f2 ) self.assertEqual( fd1a, fd1b ) self.assertNotEqual( fd1a, fd2 ) self.assertEqual( fd1a.hash(), fd1b.hash() ) self.assertNotEqual( fd1a.hash(), fd2.hash() ) fd2c = fd2.copy() self.assertEqual( fd2c, fd2 ) self.assertEqual( fd2c.hash(), fd2.hash() ) def testSerialisation( self ) : f = GafferImage.Format( IECore.Box2i( IECore.V2i( 10, 20 ), IECore.V2i( 200, 100 ) ), 0.5 ) fd = GafferImage.FormatData( f ) m = IECore.MemoryIndexedIO( IECore.CharVectorData(), [], IECore.IndexedIO.OpenMode.Write ) fd.save( m, "f" ) m2 = IECore.MemoryIndexedIO( m.buffer(), [], IECore.IndexedIO.OpenMode.Read ) fd2 = IECore.Object.load( m2, "f" ) self.assertEqual( fd2, fd ) self.assertEqual( fd2.value, f ) if __name__ == "__main__": unittest.main()
[ "thehaddonyoof@gmail.com" ]
thehaddonyoof@gmail.com
116e7f5198160b2fb99e53da48c607dc3536f281
6e77ee7ab7e937527426d9d9d7f8d0b72e6e96c0
/hello/validator.py
0aaac680fa7bd15178ff0aa1daf659999db16cb0
[ "MIT" ]
permissive
isabella232/sample-linux-python-app
e72da4f0e7a8dcd2c3a01afaaee738bdfb111845
4c72ea082d9fb34e7a35f242e54b98ba4d079d55
refs/heads/master
2022-02-21T20:06:42.471731
2019-08-26T17:51:18
2019-08-26T17:51:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,040
py
""" Module contains a simple header validator used to check for allowed characters in header inputs. """ class HeaderValidator: """ Validates if a header has valid Name:Value values for the data presented from the browser. """ def __init__(self): self.allowed_header_name_chars = [] self.allowed_header_name_chars.extend(list(range(48, 58))) # 0-9 self.allowed_header_name_chars.extend(list(range(65, 91))) # a-z self.allowed_header_name_chars.extend(list(range(97, 123))) # A-Z self.allowed_header_name_chars.extend( [94, 95, 96, 124, 126]) # ^, _, `, |, ~ self.allowed_header_name_chars.extend( [33, 35, 36, 37, 38, 39, 42, 43, 45, 46]) # !, #, $, %, &, ', *, +, -, ., def is_valid_value_character(self, char): """ Checks whether a header value character is valid """ if char == 9: return True if char > 31 and char <= 255 and char != 127: return True return False def is_valid_header_value(self, value): """ Checks whether a header value is valid """ characters = [ord(char) for char in value] for char in characters: if not self.is_valid_value_character(char): return False return True def is_valid_header_name(self, name): """ Checks whether a header name is valid """ characters = [ord(char) for char in name] for char in characters: if char not in self.allowed_header_name_chars: return False return True def is_valid(self, header): """ Validates a header string """ try: name, value = header.split(':', 1) name, value = name.strip(), value.strip() if name and value: return self.is_valid_header_name( name) and self.is_valid_header_value(value) except ValueError: print("Error unpacking header values") return False
[ "47990584+isaiah-msft@users.noreply.github.com" ]
47990584+isaiah-msft@users.noreply.github.com
e1ecb0a2c808d83be83a0a2468e2298da3054787
72d3bddd2866ad93805bee8484c3d7e21281e1fd
/blog/models.py
1f9511739722c37393c23d447c4dd1637ee50309
[]
no_license
analavishal/my-first-blog
edb014832c2d2ffc3210bff79df5c8328d3340de
ebb6e3dda48aec1da8dc645651554f9e51ff092e
refs/heads/master
2021-01-22T20:34:25.156206
2017-03-18T10:27:31
2017-03-18T10:27:31
85,331,272
0
0
null
null
null
null
UTF-8
Python
false
false
438
py
from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.user') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
[ "rao.vishal10@gmail.com" ]
rao.vishal10@gmail.com
23c9a8f00505fa58236b3a075f5d0eef10be4a89
d2346575f7cbe13cd36e8dca966df0f627ef959d
/stocks/migrations/0014_auto_20210807_1740.py
67486d20bcbd78e68cc584529cf2e0309a362504
[]
no_license
icerahi/pendemic-supply-management
db3a9fb44359496d6beed2c75d2439933ab8668e
5ffef9f93fc7ecd906d792b651a1db4a31c524fc
refs/heads/master
2023-07-03T03:20:18.160187
2021-08-07T17:14:57
2021-08-07T17:14:57
392,214,359
0
0
null
null
null
null
UTF-8
Python
false
false
583
py
# Generated by Django 3.2 on 2021-08-07 11:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stocks', '0013_auto_20210807_1117'), ] operations = [ migrations.RemoveConstraint( model_name='stock', name="Can't create multiple stock of same equipment,So update the existing equipment's quantity", ), migrations.AlterField( model_name='request', name='message', field=models.TextField(blank=True, null=True), ), ]
[ "zanjarwhite@gmail.com" ]
zanjarwhite@gmail.com
ed4feb8e92a08860f41991b72a1f5660f3d176c9
ac33ff4ac0411481adce6d96b8eb24dab158658d
/assignment5/problem1/sarsa_lamda_mountain_car.py
44cf305d458a7dc9abd93e4fefa706a948c3b983
[]
no_license
elitalobo/Reinforcement-Learning
9bcc7fb4aae88cfbe681335fa5b121c6d87ba66e
816db6225ae744b30acdb5518c5be4775b70d5ca
refs/heads/master
2020-04-03T03:41:23.516380
2018-12-13T23:23:48
2018-12-13T23:23:48
154,992,788
0
0
null
null
null
null
UTF-8
Python
false
false
11,971
py
import sys import numpy as np from numpy.random import randint import operator import matplotlib.pylab as plt import random import math gamma=1 #plt.style.use('seaborn-whitegrid') order = 3 actions_len=3 ld=0.2 epsilons = [0.3,0.15,0.075,0.05] time_limit=50000 action_index = {-1:0,0:1,1:2} def random_pick(some_list, probabilities): x = random.uniform(0, 1) cnt=0 cumulative_probability = 0.0 for item, item_probability in zip(some_list, probabilities): cumulative_probability += item_probability if x < cumulative_probability: break cnt+=1 try: assert(some_list[cnt]==item) except: return cnt-1 return cnt def filter(arr): temp = [] for x in arr: if x<-1000: temp.append(-1000) continue else: temp.append(x) return temp def pick_action(): action_picked = random_pick(actions,action_probabilities) return action_picked[0] def pick_action_success(): action_success = random_pick(action_result,action_result_probabilities) return action_success def softmax(x,episode_cnt,epsilon): sigma = 0.5 """Compute softmax values for each sets of scores in x.""" e_x = np.exp((x - np.max(x))*sigma) return (e_x) / e_x.sum() def e_greedy(x,episode_cnt,epsilon): #if(episode_cnt<100): # epsilon = epsilons[int(episode_cnt/(100/len(epsilons)))] probabilities = [] maxm = np.max(x) cnt=0 max_arr = [] for value in x: if value == maxm: max_arr.append(cnt) cnt+=1 try: idx = max_arr[0] except: import ipdb; ipdb.set_trace() if len(max_arr)!=1: idx = max_arr[randint(0, len(max_arr)-1)] cnt=0 for value in x: if(cnt!=idx): probabilities.append(epsilon/actions_len) else: probabilities.append(1.0-epsilon+(epsilon/actions_len)) cnt+=1 return probabilities def select_action(s): #import ipdb; ipdb.set_trace() global s_a_probs global actions #import ipdb; ipdb.set_trace() action_probs = s_a_probs[s*actions_len:s*actions_len+4] action_idx = random_pick(actions,action_probs) success_idx = random_pick(action_result,action_result_probabilities) return action_idx,success_idx def plot_error(error,time_steps,xlabel,ylabel,title,filename,y_error=[]): global alphas #new_alphas = [np.log10(x) for x in alphas] plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) if len(y_error)==0: plt.plot(np.array(time_steps),np.array(error)) else: plt.axhline(y=np.max(error),linestyle='--',label="max: "+str(np.max(error))) plt.errorbar(np.array(time_steps),np.array(error), yerr=y_error,fmt='-', color='black', ecolor='lightgray',label="rewards vs episodes") #plt.show() plt.legend() plt.savefig(filename) plt.clf() action_probabilities = [0.5,0.5] def random_pick(some_list, probabilities): x = random.uniform(0, 1) cumulative_probability = 0.0 for item, item_probability in zip(some_list, probabilities): cumulative_probability += item_probability if x < cumulative_probability: break return item,item_probability max_dist = 0.5 min_dist=-1.2 max_vel = 0.07 #10.0 min_vel= -0.07 #-10.0 from math import sin, cos class MountainCar() : def __init__(self,order,alpha,epsilon): self.episodes = 0 self.alpha = alpha self.result=0.0 self.dist=-0.5; self.vel = 0.0; self.old_vel=0.0; self.old_dist=0.0 self.actions = [-1,0,1] self.action =0 self.old_action = 0.0 self.action = 0.0 self.order = order self.epsilon=epsilon self.value_weights = np.array([np.random.normal(loc =0, scale =1, size=(1,np.power(self.order+1,2))),np.random.normal(loc =0, scale =1, size=(1,np.power(self.order+1,2))),np.random.normal(loc =0, scale =1, size=(1,np.power(self.order+1,2)))]) self.etraces = np.array([np.zeros((1,np.power(self.order+1,2))),np.zeros((1,np.power(self.order+1,2))),np.zeros((1,np.power(self.order+1,2)))]) #self.value_weights = np.array([np.zeros((1,int(np.power((self.order+1),2)))),np.zeros((1,int(np.power((self.order+1),2))))]) self.fourier_vector = np.array([]) self.initialize_fourier_vector() def initialize_fourier_vector(self): i=0 j=0 k=0 l=0 lent = self.order while i <= lent: j=0 k=0 l=0 while j <= lent: vec = np.array([i,j]) if self.fourier_vector.size==0: self.fourier_vector = vec else: self.fourier_vector = np.vstack((self.fourier_vector,vec)) j+=1 i+=1 def apply_cos(self,arr): #res = [cos(y) for y in arr] res = np.sum(arr) return np.cos(res*math.pi) def evaluate_fourier(self,dist,vel): dist,vel = self.get_normalized(dist,vel) req = np.array([dist,vel]) evaluated_fourier = np.cos(np.matmul(self.fourier_vector,req)*np.pi) #res = np.apply_along_axis(self.apply_cos, 1, evaluated_fourier) res = evaluated_fourier.reshape(evaluated_fourier.shape[0],1) return res def evaluate_value_estimate(self,Reward,new_action,flag,update=False): evaluated_fourier = self.evaluate_fourier(self.old_dist,self.old_vel) target = Reward if flag==False: target = Reward + gamma*(np.matmul(self.value_weights[action_index[new_action]],self.evaluate_fourier(self.dist,self.vel))) td = ( target - np.matmul(self.value_weights[action_index[self.action]],evaluated_fourier)) #print td #import ipdb; ipdb.set_trace() #print "start" #print self.value_weights.shape #print evaluated_fourier #print np.matmul(self.value_weights,np.transpose(evaluated_fourier)) #print np.matmul(self.value_weights,np.transpose(self.evaluate_fourier(self.dist,self.vel))) #print "end" #print td #assert(alpha==1.0) if update: for action in range(0,actions_len): if(action==action_index[self.action]): self.etraces[action] = gamma*ld*self.etraces[action] + np.transpose(evaluated_fourier) else: self.etraces[action] = gamma*ld*self.etraces[action] self.value_weights[action] = self.value_weights[action] + self.alpha*td*self.etraces[action] return td def update_action(self,action): self.old_action = self.action self.action = action def update_velocity(self): global max_vel global min_vel self.old_vel = self.vel self.vel += 0.001*self.action-(0.0025)*cos(3*self.dist) if(self.vel < min_vel): self.vel = min_vel if(self.vel > max_vel): self.vel = max_vel def update_distance(self): global max_dist global min_dist self.old_dist = self.dist self.dist += (self.vel) flag = False if(self.dist >= max_dist): self.dist = max_dist self.vel = 0.0 flag = True if( self.dist <= min_dist): self.dist = min_dist self.vel = 0.0 return flag def reset_state(self): self.dist=-0.5 self.old_dist=0.0 self.vel=0.0 self.old_vel=0.0 self.old_action = 0.0 self.action = 0 self.etraces = np.array([np.zeros((1,np.power(self.order+1,2))),np.zeros((1,np.power(self.order+1,2))),np.zeros((1,np.power(self.order+1,2)))]) def get_action(self): import ipdb; action_values = [np.matmul(self.value_weights[0],self.evaluate_fourier(self.dist,self.vel))[0][0],np.matmul(self.value_weights[1],self.evaluate_fourier(self.dist,self.vel))[0][0],np.matmul(self.value_weights[2],self.evaluate_fourier(self.dist,self.vel))[0][0]] action_probabilities = softmax(action_values,self.episodes,self.epsilon) action, proba = random_pick(self.actions,action_probabilities) return action def update_state(self,action): flag=False self.update_action(action) self.update_velocity() flag = flag or self.update_distance() return flag def get_normalized(self,dist,vel): global min_dist global max_dist global min_vel global max_vel dist = (dist-min_dist)/(max_dist-min_dist) vel = (vel-min_vel)/(max_vel-min_vel) if math.isnan(dist) or math.isnan(vel): print "FOUND NAN" return dist,vel def run_episode(self,td_errors,reset=True,update=False,debug=False): global time_limit if reset: self.reset_state() flag=False delta=1 REWARD =0.0 time_steps=0.0 #print "episode started" action = self.get_action() while flag==False and time_steps<time_limit: if debug: print("Timestep: " + str(time_steps)) print "old dist: " + str(self.old_dist) + " dist: " + str(self.dist) print "old vel:" + str(self.old_vel) + " vel: " + str(self.vel) print " old ang: " + str(self.old_ang) + " ang: " + str(self.ang) print "old ang_vel: " + str(self.old_ang_vel) + " ang_vel: " + str(self.ang_vel) print "action: " + str(self.action) flag = self.update_state(action) action = self.get_action() td = self.evaluate_value_estimate(-1.0,action,flag,update) #print td td_errors.append(td) if(flag): break REWARD+=-1.0 time_steps+=1 #print time_steps print "REWARD:" + str(REWARD) self.episodes+=1 #self.epsilon*=0.90 print "episode ended" return td_errors,REWARD def run_trials(mountain_car,trials=1, update=False): trial_cnt=0 td_errors = [] trial_rewards = [] while trial_cnt < trials: td_errors,reward = mountain_car.run_episode(td_errors,True,update,False) trial_cnt+=1 trial_rewards.append(reward) print trial_cnt print reward print "Norm:" + str(np.sum(mountain_car.value_weights[0]*mountain_car.value_weights[0])) print "Norm:" + str(np.sum(mountain_car.value_weights[1]*mountain_car.value_weights[1])) print "Norm:" + str(np.sum(mountain_car.value_weights[2]*mountain_car.value_weights[2])) #print len(td_errors) #import ipdb; ipdb.set_trace() td_errors = [np.power(y,2) for y in td_errors] #print "TD errors: " #print td_errors #print "DONE" if(update==False): print "Mean rewards: " + str(np.mean(trial_rewards)) else: rewards = filter(trial_rewards) #plot_error(rewards,[i for i in range(0,len(rewards))],"episodes","rewards","rewards vs episodes","final/mountain_car_rewards_" + str(mountain_car.order) + "_"+ str(mountain_car.alpha) + "_" + str(mountain_car.epsilon) +".png") return mountain_car,rewards if __name__=="__main__": global etraces trials = 100 if len(sys.argv)>1: trials = max(2,int(sys.argv[1]) ) global order global ld orders = [1,3,5,7,9,11] orders = [2,3,4] #epsilons = [0.1,,0.01,0.05,0.001,0.005] epsilons = [0.005,0.001,0.0001,0.01,0.05] total_rewards=[] #[4,0.0056,0.05],[2,0.001,0.01] gridsearch = [[2,0.001778,0.0007],[5,0.001778,0.0001],[3,0.00316,0.0001]] #for order in orders: # alphas = [np.power(10.0,-1.0*x) for x in np.arange(2.5,4.0,0.5)] # for alpha in alphas: # for epsilon in epsilons: lds = [0.2,0.5] for ld_value in lds: for values in gridsearch: ld = ld_value total_rewards=[] trial_cnt=0 while trial_cnt < trials: #mountain_car = MountainCar(order,alpha,epsilon) mountain_car = MountainCar(values[0],values[1],values[2]) mountain_car,trial_reward = run_trials(mountain_car,1000,True) total_rewards.append(trial_reward) trial_cnt+=1 std_dev = np.std(total_rewards,axis=0) rewards = np.mean(total_rewards,axis=0) print rewards plot_error(rewards,[i for i in range(0,len(rewards))],"episodes","rewards","rewards vs episodes","sarsa_lamda_mountain_car_rewards_" + str(mountain_car.order) + "_"+ str(mountain_car.alpha)+ "_" + str(mountain_car.epsilon)+"_"+str(ld)+".png",std_dev)
[ "loboelita@gmail.com" ]
loboelita@gmail.com
2033b2fb67cd046071d7e521baf4c4fdd6ae15d2
d8e520663e1e1b674fbd3945e80437217a741a18
/arcade/python/yin_and_yang_of_yields.py
dc602facf3ec869d867b5d90469bf9ccd7c3a81d
[]
no_license
sandrohp88/code_fight
d2cae46dfe7812757d3947058652989f1a809cb9
c3c86b7a60ecf81cbe66a4153ef88df2037d8fb1
refs/heads/master
2022-06-15T17:23:33.350592
2022-06-01T21:25:39
2022-06-01T21:25:39
156,311,504
0
0
null
null
null
null
UTF-8
Python
false
false
9,963
py
import math # You are working on a revolutionary video game. In this game the player will be able to collect several types of bonuses on each level, and his total score for the level is equal to the sum of the first n bonuses he collected. However, if he collects less than n bonuses, his score will be equal to 0. # Given the bonuses the player got, your task is to return his final score for the level. # Example # For bonuses = [4, 2, 4, 5] and n = 3, # the output should be # calcBonuses(bonuses, n) = 10. # 4 + 2 + 4 = 10. # For bonuses = [4, 2, 4, 5] and n = 5, # the output should be # calcBonuses(bonuses, n) = 0. # The player has collected only 4 bonuses, so his final score is 0. def calcBonuses(bonuses, n): it = iter(bonuses) res = 0 try: for _ in range(n): res += next(it) except StopIteration: res = 0 return # You are working on a revolutionary video game. This game will consist of several levels, and on each level the player will be able to collect bonuses. For each passed level the player will thus get some score, determined by the number of collected bonuses. # Player's final score is decided by the number of completed levels and scores obtained on each of them. The final score is calculated as the sum of squares of n maximum scores obtained. If the number of completed levels is less than n, the score is calculated as the sum of squared scores for each level, and final result is divided by 5 as a penalty (the result is rounded down to the nearest integer). # Given the list of scores the player got for completed levels and the number n that determines the number of levels you have to pass to avoid being penalized, return the player's final game score. # Example # For scores = [4, 2, 4, 5] and n = 3, # the output should be # calcFinalScore(scores, n) = 57. # 52 + 42 + 42 = 57. # For scores = [4, 2, 4, 5] and n = 5, # the output should be # calcFinalScore(scores, n) = 12. # (42 + 22 + 42 + 52) / 5 = 61 / 5 ≈ 12. def calcFinalScore(scores, n): gen = iter([x*x for x in sorted(scores, reverse=True)[:n]]) res = 0 try: for _ in range(n): res += next(gen) except StopIteration: res //= 5 return res # Fibonacci sequence is known to every programmer, and you're not an exception. It is believed that not all properties of Fibonacci numbers are yet studied, and in order to help your descendants, you'd like to implement a generator that will generate Fibonacci numbers infinitely. Who knows, maybe in the distant future your generator will help to make a breakthrough in this field! # To test your generator, you'd like to check the first few values. Given the number n, return the first n numbers of Fibonacci sequence. # Example # For n = 3, the output should be # fibonacciGenerator(n) = [0, 1, 1]. # The first three Fibonacci numbers are 0, 1 and 1. def fibonacciGenerator(n): def fib(): last = (0, 1) while True: yield last[0] last = last[0] + last[1], last[0] gen = fib() return [next(gen) for _ in range(n)] # The Calkin-Wilf tree is a tree in which the vertices correspond 1-for-1 to the positive rational numbers. The tree is rooted at the number 1, and any rational number expressed in simplest terms as the fraction a / b has as its two children the numbers a / (a + b) and (a + b) / b. Every positive rational number appears exactly once in the tree. Here's what it looks like: # The Calkin-Wilf sequence is the sequence of rational numbers generated by a breadth-first traversal of the Calkin-Wilf tree, where the vertices of the same level are traversed from left to right (as displayed in the image above). The sequence thus also contains each rational number exactly once, and can be represented as follows: # Given a rational number, your task is to return its 0-based index in the Calkin-Wilf sequence. # Example # For number = [1, 3], the output should be # calkinWilfSequence(number) = 3. # As you can see in the image above, 1 / 3 is the 3rd 0-based number in the sequenc def calkinWilfSequence(number): def fractions(): numerator = 1 denominator = 1 yield [numerator, denominator] while True: numerator, denominator = denominator, 2 * \ (numerator//denominator) * denominator + denominator - numerator yield [numerator, denominator] gen = fractions() res = 0 while next(gen) != number: res += 1 return res def checkPassword(attempts, password): ''' You're implementing a web application. Like most applications, yours also has the authorization function. Now you need to implement a server function that will check password attempts made by users. Since you expect heavy loads, the function should be able to accept a bunch of requests that will be sent simultaneously. In order to validate your function, you want to test it locally. Given a list of attempts and the correct password, return the 1-based index of the first correct attempt, or -1 if there were none. Example For attempts = ["hello", "world", "I", "like", "coding"] and password = "like", the output should be checkPassword(attempts, password) = 4. ''' def check(): while True: yield attempt == password checker = check() for i, attempt in enumerate(attempts): next(checker) if checker.send(attempt): return i + 1 return -1 class FRange(object): ''' An you may know, the range function in Python allows coders to iterate over elements from start to stop with the given step. Unfortunately it works only for integer values, and additional libraries should be used if a programmer wants to use float values. CodeSignal doesn't include third-party libraries, so you have to make do with the standard ones. Given array of arguments args, return array of values the float range generator should return. Example For args = [5], the output should be rangeFloat(args) = [0, 1, 2, 3, 4]. Since args contains only one element, it corresponds to the stop argument. start and step arguments have default parameters, which are 0 and 1, respectively. For args = [0.5, 7.5], the output should be rangeFloat(args) = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5]. There are only two elements in args, which means that the first value corresponds to start, and the second value corresponds to stop. The step argument thus has a default value, which is 1. For args = [-1.1, 2.4, 0.3], the output should be rangeFloat(args) = [-1.1, -0.8, -0.5, -0.2, 0.1, 0.4, 0.7, 1, 1.3, 1.6, 1.9, 2.2]. Since args contains all three elements, the values of start, stop and step are -1.1, 2.4 and 0.3, respectively. ''' def __init__(self, start, stop=None, step=None): if stop is None: self.i = 0 self.stop = start self.step = 1 elif step is None: self.i = start self.stop = stop self.step = 1 else: self.i = start self.stop = stop self.step = step def __iter__(self): return self def __next__(self): if self.step >= 0: if self.i < self.stop: self.i += self.step return (self.i - self.step) else: raise StopIteration else: if self.i > self.stop: self.i += self.step return (self.i - self.step) else: raise StopIteration def rangeFloat(args): return list(FRange(*args)) class Prizes(object): ''' In a large and famous supermarket a new major campaign was launched. From now on, each nth customer has a chance to win a prize: a brand new luxury car! However, it's not that simple. A customer wins a prize only if the total price of their purchase is divisible by d. This number is kept as a secret, so the customers don't know in advance how much they should spend on their purchases. The winners will be announced once the campaign is over. Your task is to implement a function that will determine the winners. Given the purchases of some customers over time, return the 1-based indices of all the customers who won the prize, i.e. each nth who spend on their purchases amount of money divisible by d. Example For purchases = [12, 43, 13, 465, 1, 13], n = 2, and d = 3, the output should be superPrize(purchases, n, d) = [4]. Each second customer has a chance to win a car, which makes customers 2, 4 and 6 potential winners. Customer number 2 spent 43 on his purchase, which is not divisible by 3. 13 also is not divisible by 3, so the sixth customer also doesn't get the price. Customer 4, however, spent 465, which is divisible by 3, so he is the only lucky guy. ''' def __init__(self, purchases, n, d): self.purchases = purchases self.n = n self.d = d self.index = n - 1 def __iter__(self): return self def won(self): return self.purchases[self.index - self.n] % self.d == 0 def __next__(self): while self.index < len(self.purchases): self.index += self.n if self.won(): self.winner = (self.index - self.n + 1) return self.winner raise StopIteration def superPrize(purchases, n, d): return list(Prizes(purchases, n, d)) def main(): attempts = ["hello", "world", "I", "like", "coding"] password = "like" print(checkPassword(attempts, password)) # Expected result = 4 # # bonuses = [4, 2, 4, 5] # number = [1931, 1076] # print(calkinWilfSequence(number)) # # print(calcBonuses(bonuses,3)) if __name__ == '__main__': main()
[ "sandrohp88@gmail.com" ]
sandrohp88@gmail.com
80ff3d85131b2d5c74a3468084f00e302893e2cf
f4a60261fdb25d923cf68143af51086b0a1076d9
/optmet/tests/test_minimum_golden.py
154db361ebc5e1723e4dd58b25a4597cb29c406b
[]
no_license
hrsrashid/opt-met
00a0d16e6b6c7abbf8356d6cea2a2369c247ace7
8d3b6d4ee558437902db4bcd4262fc7952e2a21e
refs/heads/master
2021-01-22T11:15:25.252472
2017-08-30T16:01:44
2017-08-30T16:01:44
92,676,803
1
0
null
null
null
null
UTF-8
Python
false
false
766
py
import unittest from optmet.minimum_golden import find_minimum_golden from optmet.function import Function, Domain class MinimumGoldenTest(unittest.TestCase): def setUp(self): self.eps = .001 self.places = 2 def test_finds_inside(self): self.assertAlmostEqual(find_minimum_golden( Function(f=lambda x: x * x, domain=Domain(-2, 3)), self.eps), 0, self.places) def test_finds_left_bound(self): self.assertAlmostEqual(find_minimum_golden( Function(f=lambda x: x * x, domain=Domain(0, 1)), self.eps), 0, self.places) def test_finds_right_bound(self): self.assertAlmostEqual(find_minimum_golden( Function(f=lambda x: x * x, domain=Domain(-1, 0)), self.eps), 0, self.places)
[ "hrs.rashid@gmail.com" ]
hrs.rashid@gmail.com
740c97440e71c02cba1722d381c84c7d4cd74a5e
605fe2330a3765e680fae53f85670849bac84bed
/water_level/water_firmata_analog.py
ccb99ffba0e037368ef2be3df89cb3167a2cdee3
[]
no_license
onitonitonito/raspberry
564a8b020bc94e1ecedadad0f0ce112a4ec0d481
1a9ba24a0857517fba0f46d11d6fb3370c1457d7
refs/heads/master
2021-06-26T11:12:25.841194
2020-02-17T08:56:44
2020-08-25T09:16:42
98,432,676
1
2
null
null
null
null
UTF-8
Python
false
false
1,225
py
#!/usr/bin/python3 """ # Arduino Shield - Digital INPUT. # DFRobot Non-contact Liquid Level Sensor XKC-Y25-T12V SKU: SEN0204 # 1, 7, 8, 15 : DFRobot Water level sensor kit # 21,20,16,12 : Arduino Water level sensor """ print(__doc__) import sys import time from pyfirmata import Arduino, util INTERVAL = 1 # in second # Creates a new BOARD PORT = '/dev/ttyACM0' # Extention Port BOARD = Arduino(PORT) # Definition of the analog pin # PINS = (0, 1, 2, 3) PINS = (0, 1, 2, 3, 4, 5) print("*** Setting up the connection to the BOARD ...") iter_some = util.Iterator(BOARD) iter_some.start() def main(): setup() try: loop() except KeyboardInterrupt: sys.exit() BOARD.exit() def setup(): # Start reporting for defined pins for pin in PINS: BOARD.analog[pin].enable_reporting() def loop(): count = 1 while True: # Loop for reading the input. Duration approx. 10 s print("\nValues after %s second(s) --- %s times " % (INTERVAL, count)) for pin in PINS: print("Pin A%i : %s" % (pin, BOARD.analog[pin].read())) BOARD.pass_time(INTERVAL) count += 1 if __name__ == '__main__': main()
[ "nitt0x0@gmail.com" ]
nitt0x0@gmail.com
92be4d49a138d4985b35dacfc6837b47f7170f08
bd452440c8065cf306b1a68d71237a9be617a61d
/Open_street_map.py
c48e02b057f6753be4617876d282aa3356addece
[ "MIT" ]
permissive
hardeepsjohar/Open-Street-Map-Pasadena
bc91bb85cd280771c91e566faf62ad2315cf990d
31b0e6259152274cff1b33b4520155b0cb0ec4e1
refs/heads/master
2021-01-20T02:38:46.065720
2017-08-25T17:48:42
2017-08-25T17:48:42
101,325,773
0
0
null
null
null
null
UTF-8
Python
false
false
12,761
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET from collections import defaultdict import re import pprint import csv import codecs import cerberus import schema osm_file = open("pasadena.osm", "r") #paths NODES_PATH = "nodes.csv" NODE_TAGS_PATH = "nodes_tags.csv" WAYS_PATH = "ways.csv" WAY_NODES_PATH = "ways_nodes.csv" WAY_TAGS_PATH = "ways_tags.csv" street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) PROBLEMCHARS = re.compile(r'[=\+/&<>;\'"\?%#$@\,\. \t\r\n]') SCHEMA = schema.schema #fields NODE_FIELDS = ['id', 'lat', 'lon', 'user', 'uid', 'version', 'changeset', 'timestamp'] NODE_TAGS_FIELDS = ['id', 'key', 'value', 'type'] WAY_FIELDS = ['id', 'user', 'uid', 'version', 'changeset', 'timestamp'] WAY_TAGS_FIELDS = ['id', 'key', 'value', 'type'] WAY_NODES_FIELDS = ['id', 'node_id', 'position'] #lists and dictionaries functions refer to street_types = defaultdict(set) zip_types = defaultdict(set) street_fixes_list = [] street_fixes = defaultdict(list) names_dict = defaultdict() expected_street = ["Street", "Alley", "Avenue", "Boulevard", "Drive", "Court", "Place", "Square", "Lane", "Road", "Trail", "Parkway", "Commons"] mapping_street = { "St": "Street", "Ave": "Avenue", "Ave.": "Avenue", "Blvd.": "Boulevard", "Blvd": "Boulevard", "Ln": "Lane", "Rd": "Road", "Rd.": "Road", "St.": "Street", "Dr": "Drive", "Dr.": "Drive" } def audit_street_type(street_types, street_name, elem): '''Checks street name for problem characters or if it is already correctly inputted. If no issues adds their street type as the key and street name as the value into the street_types dictionary. Takes their element id# and stores it in the street_fixes list''' m = street_type_re.search(street_name) if m: street_type = m.group() if street_type not in expected_street: if not street_type[-1].isdigit() and street_type in mapping_street: street_types[street_type].add(street_name) elem_id = elem.attrib["id"] street_fixes_list.append(elem_id) def is_street_name(elem): '''Checks if element's tag is a street name.''' return (elem.attrib['k'] == "addr:street") def audit_street(osmfile): '''Iterates through the osm_file, checks if tag is a street name and send it to audit_street_type.''' for event, elem in ET.iterparse(osm_file, events=("start",)): if elem.tag == "node" or elem.tag == "way": for tag in elem.iter("tag"): if is_street_name(tag): audit_street_type(street_types, tag.attrib['v'], elem) return street_types def update_name(name, mapping_street): '''For the items whose names can be fixed, if the key from mapping_street is in the name, it is split there and the first part of the name is paired with the value of that key from mapping_street thus creating a full and proper name.''' for key in mapping_street: if key in name: new_name = name.split(key) name = new_name[0] + mapping_street[key] return name def street_test(): '''Creates a dictionary called st_types which is iterated over multiples times. The first time is done to add the element id# and shorter name to a dictionary called street_fixes. The second time is done to update the name using update_name and store the shorter name and the proper name in a dictionary called names_dict. The loop combines these above two dictionaries into the first dictionary street_fixes which has the element ID as the key and the shorter name and proper name in a set as the values.''' osm_file.seek(0) st_types = audit_street(osm_file) #pprint.pprint(dict(st_types)) osm_file.seek(0) for event, elem in ET.iterparse(osm_file, events=("start",)): if elem.tag == "node" or elem.tag == "way": for tag in elem.iter("tag"): if is_street_name(tag) and elem.attrib['id'] in street_fixes_list: elem_id = elem.attrib['id'] street_fixes[elem_id].append(tag.attrib['v']) for st_type, ways in st_types.iteritems(): for name in ways: better_name = update_name(name, mapping_street) if better_name != None: print name, "=>", better_name names_dict[name]=better_name for old_name, new_name in names_dict.iteritems(): for k, v in street_fixes.iteritems(): if list(v)[0] == old_name: street_fixes[k].append(names_dict[list(v)[0]]) pprint.pprint(dict(street_fixes)) def count_street_types_fixed(): '''A test to see how clean the data would be if we printed a dictionary which counted how many of each zip code there are.''' st_types_fixed = defaultdict(int) st_types = audit_street(osm_file) for st_type, ways in st_types.iteritems(): for name in ways: if st_type in mapping_street: st_types_fixed[st_type]+=1 st_types_fixed = dict(st_types_fixed) return st_types_fixed def audit_zip_type(zip_types, zipcode): '''Checks to make sure zip codes don't have problems.''' m = street_type_re.search(zipcode) if m: zip_type = m.group() zip_types[zip_type].add(zipcode) def is_zip(elem): '''Checks to make sure it is a zipcode.''' return (elem.attrib['k'] == "addr:postcode") def audit_zip(osmfile): '''Iterates through the osm_file, checks if tag is a zipcode and send it to audit_zip_type.''' osm_file.seek(0) for event, elem in ET.iterparse(osm_file, events=("start",)): if elem.tag == "node" or elem.tag == "way": for tag in elem.iter("tag"): if is_zip(tag): audit_zip_type(zip_types, tag.attrib['v']) return zip_types def zip_test(): '''Creates a dictionary called zip_types which is looped over to print the old and new zip codes to ensure output is clean.''' zip_types = audit_zip(osm_file) pprint.pprint(dict(zip_types)) for zip_type, zipcode in zip_types.iteritems(): for zipc in zipcode: if "CA" in zipc: print zipc, "=>", zip_type def clean_key (attribute): '''Fixing the "key" column: the full tag "k" attribute value if no colon is present or the characters after the colon if one is.''' if ":" in attribute: string = attribute.split(":", 1) return string[1] else: return attribute def clean_type (attribute): '''Fixing the "type" column: either the characters before the colon in the tag "k" value or "regular" if a colon is not present.''' if ":" in attribute: string = attribute.split(":", 1) return string[0] else: return "regular" def change_name (tag, id_number, name): '''Receives tags, id numbers and values from shape_element which are then checked against the dictionaries created by the street_test and zip_test functions. The data is matched to see if it needs to be replaced with the corrected data or to remain as it is.''' if tag.attrib['k'] == "addr:street": for k, v in street_fixes.iteritems(): if id_number == k: return list(v)[1] elif tag.attrib['k'] == "addr:postcode": for k, v in zip_types.iteritems(): if k in name: return k elif "90032" in name: return "90032" return name def shape_element(element, node_attr_fields=NODE_FIELDS, way_attr_fields=WAY_FIELDS, problem_chars=PROBLEMCHARS, default_tag_type='regular'): """Clean and shape node or way XML element to Python dict""" node_attribs = {} way_attribs = {} way_nodes = [] tags = [] counter = 0 if element.tag == 'node': for attrib in NODE_FIELDS: node_attribs[attrib] = element.attrib[attrib] for tag in element.iter("tag"): k = tag.attrib['k'] if re.search(PROBLEMCHARS,k): break tag_dict = {} tag_dict["id"] = node_attribs["id"] tag_dict["key"] = clean_key(tag.attrib['k']) tag_dict["value"] = change_name(tag, tag_dict["id"], tag.attrib['v']) tag_dict["type"] = clean_type(tag.attrib['k']) tags.append(tag_dict) return {'node': node_attribs, 'node_tags': tags} elif element.tag == 'way': for attrib in WAY_FIELDS: way_attribs[attrib] = element.attrib[attrib] for node in element.iter("nd"): nodes_dict = {} nodes_dict["id"] = way_attribs["id"] nodes_dict["node_id"] = node.attrib['ref'] nodes_dict["position"] = counter counter +=1 way_nodes.append(nodes_dict) for tag in element.iter("tag"): k = tag.attrib['k'] if re.search(PROBLEMCHARS,k): break tag_dict = {} tag_dict["id"] = way_attribs["id"] tag_dict["key"] = clean_key(tag.attrib['k']) tag_dict["value"] = change_name(tag, tag_dict["id"], tag.attrib['v']) tag_dict["type"] = clean_type(tag.attrib['k']) tags.append(tag_dict) return {'way': way_attribs, 'way_nodes': way_nodes, 'way_tags': tags} # ================================================== # # Helper Functions # # ================================================== # def get_element(osm_file, tags=('node', 'way', 'relation')): """Yield element if it is the right type of tag""" context = ET.iterparse(osm_file, events=('start', 'end')) _, root = next(context) for event, elem in context: if event == 'end' and elem.tag in tags: yield elem root.clear() def validate_element(element, validator, schema=SCHEMA): """Raise ValidationError if element does not match schema""" if validator.validate(element, schema) is not True: field, errors = next(validator.errors.iteritems()) message_string = "\nElement of type '{0}' has the following errors:\n{1}" error_string = pprint.pformat(errors) raise Exception(message_string.format(field, error_string)) class UnicodeDictWriter(csv.DictWriter, object): """Extend csv.DictWriter to handle Unicode input""" def writerow(self, row): super(UnicodeDictWriter, self).writerow({ k: (v.encode('utf-8') if isinstance(v, unicode) else v) for k, v in row.iteritems() }) def writerows(self, rows): for row in rows: self.writerow(row) # ================================================== # # Main Function # # ================================================== # def process_map(file_in, validate): """Iteratively process each XML element and write to csv(s)""" osm_file.seek(0) with codecs.open(NODES_PATH, 'w') as nodes_file, \ codecs.open(NODE_TAGS_PATH, 'w') as nodes_tags_file, \ codecs.open(WAYS_PATH, 'w') as ways_file, \ codecs.open(WAY_NODES_PATH, 'w') as way_nodes_file, \ codecs.open(WAY_TAGS_PATH, 'w') as way_tags_file: nodes_writer = UnicodeDictWriter(nodes_file, NODE_FIELDS) node_tags_writer = UnicodeDictWriter(nodes_tags_file, NODE_TAGS_FIELDS) ways_writer = UnicodeDictWriter(ways_file, WAY_FIELDS) way_nodes_writer = UnicodeDictWriter(way_nodes_file, WAY_NODES_FIELDS) way_tags_writer = UnicodeDictWriter(way_tags_file, WAY_TAGS_FIELDS) nodes_writer.writeheader() node_tags_writer.writeheader() ways_writer.writeheader() way_nodes_writer.writeheader() way_tags_writer.writeheader() validator = cerberus.Validator() for element in get_element(file_in, tags=('node', 'way')): el = shape_element(element) if el: if validate is True: validate_element(el, validator) if element.tag == 'node': nodes_writer.writerow(el['node']) node_tags_writer.writerows(el['node_tags']) elif element.tag == 'way': ways_writer.writerow(el['way']) way_nodes_writer.writerows(el['way_nodes']) way_tags_writer.writerows(el['way_tags']) street_test() zip_test() process_map(osm_file, validate=False) #count_street_types_fixed()
[ "hjohar@gmail.com" ]
hjohar@gmail.com
037b6b3e43f7b4c054f32fa645df6fd903c159ba
ba245e3a0f37d5004790d2f7afb47bf9bd4ef8f8
/pruners/l1_pruner.py
e0cba4eb415b529fbe2b74136a107657031cf854
[ "MIT" ]
permissive
oliver12323/deep-compression
cd3ed1ad5112c4b1da76476f806a8f0be7f05e61
1d13736562f77f7e27e282e6ba5d655e3f000917
refs/heads/master
2023-07-24T03:01:17.406634
2021-09-08T08:31:51
2021-09-08T08:31:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,358
py
import torch import torch.nn as nn import numpy as np class L1Pruner: def __init__(self, pruning_type="unstructured"): self.pruning_type = pruning_type def structured_prune(self, model, prune_rate): # get all the prunable convolutions convs = model.get_prunable_layers(pruning_type=self.pruning_type) # figure out the threshold of l1-norm under which channels should be turned off channel_norms = [] for conv in convs: channel_norms.append( torch.sum( torch.abs(conv.conv.weight.view(conv.conv.out_channels, -1)), axis=1 ) ) threshold = np.percentile(channel_norms, prune_rate) # prune anything beneath the l1-threshold for conv in convs: channel_norms = torch.sum( torch.abs(conv.conv.weight.view(conv.conv.out_channels, -1)), axis=1 ) mask = conv.mask * (channel_norms < threshold) conv.mask = torch.einsum("cijk,c->cijk", conv.weight.data, mask) def unstructured_prune(self, model, prune_rate=50.0): # get all the prunable convolutions convs = model.get_prunable_layers(pruning_type=self.pruning_type) # collate all weights into a single vector so l1-threshold can be calculated all_weights = torch.Tensor() if torch.cuda.is_available(): all_weights = all_weights.cuda() for conv in convs: all_weights = torch.cat((all_weights.view(-1), conv.conv.weight.view(-1))) abs_weights = torch.abs(all_weights.detach()) threshold = np.percentile(abs_weights, prune_rate) # prune anything beneath l1-threshold for conv in model.get_prunable_layers(pruning_type=self.pruning_type): conv.mask.update( torch.mul( torch.gt(torch.abs(conv.conv.weight), threshold).float(), conv.mask.mask.weight, ) ) def prune(self, model, prune_rate): if self.pruning_type.lower() == "unstructured": self.unstructured_prune(model, prune_rate) elif self.pruning_type.lower() == "structured": self.structured_prune(model, prune_rate) else: raise ValueError("Invalid type of pruning")
[ "jackwilliamturner@icloud.com" ]
jackwilliamturner@icloud.com
f10c14bba0fed87c348c1be34a3b82fa74a13c47
62f63df5869d069116f76bbee7b0e8c88b751fd3
/src/data/util.py
aac46347bc6cbe6aa2c28a1c4fef0dc3bce5efc6
[]
no_license
TheStarkor/IRN
042676b884a3baecfed68c64f34a635e4d0b44e6
4a58f04e16b73f60f96a4f84976841d9dbedcdd2
refs/heads/main
2023-02-26T06:20:35.835599
2021-01-21T10:15:13
2021-01-21T10:15:13
326,608,901
3
1
null
2021-01-21T10:15:14
2021-01-04T07:54:13
Python
UTF-8
Python
false
false
8,544
py
import os import cv2 # type: ignore import numpy as np # type: ignore import random import torch import math from typing import Tuple, List, Any, Optional IMG_EXTENSIONS = [ ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".ppm", ".PPM", ".bmp", ".BMP", ] def is_image_file(filename: str) -> bool: return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) def _get_paths_from_images(path: str) -> List[str]: assert os.path.isdir(path), f"{path:s} is not a valid directory" images = [] for dirpath, _, fnames in sorted(os.walk(path)): for fname in sorted(fnames): if is_image_file(fname): img_path: str = os.path.join(dirpath, fname) images.append(img_path) assert images, f"{path:s} has no valid image file" return images def get_image_paths(data_type: str, dataroot: str) -> List[str]: paths: Optional[List[str]] = None if dataroot is not None: if data_type == "img": paths = sorted(_get_paths_from_images(dataroot)) else: raise NotImplementedError( "data_type [{:s}] is not recognized.".format(data_type) ) return paths def read_img(path: str) -> Any: img = cv2.imread(path, cv2.IMREAD_COLOR) img = img.astype(np.float32) / 255.0 if img.ndim == 2: img = np.expand_dims(img, axis=2) # some images have 4 channels if img.shape[2] > 3: img = img[:, :, :3] return img def modcrop(img_in: Any, scale: int) -> Any: img: Any = np.copy(img_in) H: int W: int C: int H_r: int W_r: int if img.ndim == 2: H, W = img.shape H_r, W_r = H % scale, W % scale img = img[: H - H_r, : W - W_r] elif img.ndim == 3: H, W, C = img.shape H_r, W_r = H % scale, W % scale img = img[: H - H_r, : W - W_r] else: raise ValueError("Wrong img ndim: [{:d}].".format(img.ndim)) return img def augment(img_list: List[Any], hflip: bool = True, rot: bool = True) -> List[Any]: hflip = hflip and random.random() < 0.5 vflip: bool = rot and random.random() < 0.5 rot90: bool = rot and random.random() < 0.5 def _augment(img: Any) -> Any: if hflip: img = img[:, ::-1, :] if vflip: img = img[::-1, :, :] if rot90: img = img.transpose(1, 0, 2) return img return [_augment(img) for img in img_list] def debugging_image_numpy(img, filename: str = "test.png"): img_t = img.astype(np.float32) * 255.0 cv2.imwrite(filename, img_t) def cubic(x): absx = torch.abs(x) absx2 = absx ** 2 absx3 = absx ** 3 return (1.5 * absx3 - 2.5 * absx2 + 1) * ((absx <= 1).type_as(absx)) + ( -0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2 ) * (((absx > 1) * (absx <= 2)).type_as(absx)) def calculate_weights_indices( in_length, out_length, scale, kernel, kernel_width, antialiasing ): if (scale < 1) and (antialiasing): # Use a modified kernel to simultaneously interpolate and antialias- larger kernel width kernel_width = kernel_width / scale # Output-space coordinates x = torch.linspace(1, out_length, out_length) # Input-space coordinates. Calculate the inverse mapping such that 0.5 # in output space maps to 0.5 in input space, and 0.5+scale in output # space maps to 1.5 in input space. u = x / scale + 0.5 * (1 - 1 / scale) # What is the left-most pixel that can be involved in the computation? left = torch.floor(u - kernel_width / 2) # What is the maximum number of pixels that can be involved in the # computation? Note: it's OK to use an extra pixel here; if the # corresponding weights are all zero, it will be eliminated at the end # of this function. P = math.ceil(kernel_width) + 2 # The indices of the input pixels involved in computing the k-th output # pixel are in row k of the indices matrix. indices = left.view(out_length, 1).expand(out_length, P) + torch.linspace( 0, P - 1, P ).view(1, P).expand(out_length, P) # The weights used to compute the k-th output pixel are in row k of the # weights matrix. distance_to_center = u.view(out_length, 1).expand(out_length, P) - indices # apply cubic kernel if (scale < 1) and (antialiasing): weights = scale * cubic(distance_to_center * scale) else: weights = cubic(distance_to_center) # Normalize the weights matrix so that each row sums to 1. weights_sum = torch.sum(weights, 1).view(out_length, 1) weights = weights / weights_sum.expand(out_length, P) # If a column in weights is all zero, get rid of it. only consider the first and last column. weights_zero_tmp = torch.sum((weights == 0), 0) if not math.isclose(weights_zero_tmp[0], 0, rel_tol=1e-6): indices = indices.narrow(1, 1, P - 2) weights = weights.narrow(1, 1, P - 2) if not math.isclose(weights_zero_tmp[-1], 0, rel_tol=1e-6): indices = indices.narrow(1, 0, P - 2) weights = weights.narrow(1, 0, P - 2) weights = weights.contiguous() indices = indices.contiguous() sym_len_s = -indices.min() + 1 sym_len_e = indices.max() - in_length indices = indices + sym_len_s - 1 return weights, indices, int(sym_len_s), int(sym_len_e) def imresize_np(img, scale, antialiasing=True): # Now the scale should be the same for H and W # input: img: Numpy, HWC BGR [0,1] # output: HWC BGR [0,1] w/o round img = torch.from_numpy(img) in_H, in_W, in_C = img.size() _, out_H, out_W = in_C, math.ceil(in_H * scale), math.ceil(in_W * scale) kernel_width = 4 kernel = "cubic" # Return the desired dimension order for performing the resize. The # strategy is to perform the resize first along the dimension with the # smallest scale factor. # Now we do not support this. # get weights and indices weights_H, indices_H, sym_len_Hs, sym_len_He = calculate_weights_indices( in_H, out_H, scale, kernel, kernel_width, antialiasing ) weights_W, indices_W, sym_len_Ws, sym_len_We = calculate_weights_indices( in_W, out_W, scale, kernel, kernel_width, antialiasing ) # process H dimension # symmetric copying img_aug = torch.FloatTensor(in_H + sym_len_Hs + sym_len_He, in_W, in_C) img_aug.narrow(0, sym_len_Hs, in_H).copy_(img) sym_patch = img[:sym_len_Hs, :, :] inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long() sym_patch_inv = sym_patch.index_select(0, inv_idx) img_aug.narrow(0, 0, sym_len_Hs).copy_(sym_patch_inv) sym_patch = img[-sym_len_He:, :, :] inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long() sym_patch_inv = sym_patch.index_select(0, inv_idx) img_aug.narrow(0, sym_len_Hs + in_H, sym_len_He).copy_(sym_patch_inv) out_1 = torch.FloatTensor(out_H, in_W, in_C) kernel_width = weights_H.size(1) for i in range(out_H): idx = int(indices_H[i][0]) out_1[i, :, 0] = ( img_aug[idx : idx + kernel_width, :, 0].transpose(0, 1).mv(weights_H[i]) ) out_1[i, :, 1] = ( img_aug[idx : idx + kernel_width, :, 1].transpose(0, 1).mv(weights_H[i]) ) out_1[i, :, 2] = ( img_aug[idx : idx + kernel_width, :, 2].transpose(0, 1).mv(weights_H[i]) ) # process W dimension # symmetric copying out_1_aug = torch.FloatTensor(out_H, in_W + sym_len_Ws + sym_len_We, in_C) out_1_aug.narrow(1, sym_len_Ws, in_W).copy_(out_1) sym_patch = out_1[:, :sym_len_Ws, :] inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long() sym_patch_inv = sym_patch.index_select(1, inv_idx) out_1_aug.narrow(1, 0, sym_len_Ws).copy_(sym_patch_inv) sym_patch = out_1[:, -sym_len_We:, :] inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long() sym_patch_inv = sym_patch.index_select(1, inv_idx) out_1_aug.narrow(1, sym_len_Ws + in_W, sym_len_We).copy_(sym_patch_inv) out_2 = torch.FloatTensor(out_H, out_W, in_C) kernel_width = weights_W.size(1) for i in range(out_W): idx = int(indices_W[i][0]) out_2[:, i, 0] = out_1_aug[:, idx : idx + kernel_width, 0].mv(weights_W[i]) out_2[:, i, 1] = out_1_aug[:, idx : idx + kernel_width, 1].mv(weights_W[i]) out_2[:, i, 2] = out_1_aug[:, idx : idx + kernel_width, 2].mv(weights_W[i]) return out_2.numpy()
[ "sk_and_mc@kaist.ac.kr" ]
sk_and_mc@kaist.ac.kr
1a987fe189f8af64941603493a1ca7f36aa9b3cc
5bc6b018ef99cb96ba59f25f063b592eb8427360
/recommendation/offline_music_recommendation/solution1/music_suggest.py
80645cda191def853d2b8d135c524d2cb819f9ad
[]
no_license
mcnemesis/ml
a242d05f4efa662fbbb5e831cc2f5cd272d9a063
310680338caf86a093f2cb8ffef0c6654a187939
refs/heads/master
2016-09-11T01:06:33.498071
2012-12-29T17:57:17
2012-12-29T17:57:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,012
py
#!/usr/bin/env python import os from datetime import datetime,timedelta import re class Entity: file_filter = r'^.+\.(mp3)$' def __init__(self,path,parent=None,ffilter=None): self.path = path self.is_file = Entity.path_is_file(path) self.most_recent_member_atime = 0 self.number_plays = 0 self.parent = parent self.members = [] if filter is not None: self.file_filter = ffilter self.evaluate_members() self.rank = 0 def set_most_recent_atime(self,atime): if atime > self.most_recent_member_atime: self.most_recent_member_atime = atime if self.parent: self.parent.set_most_recent_atime(atime) def set_number_plays(self,plays): if self.is_file: self.number_plays = plays if self.parent: self.parent.set_number_plays(plays) else: self.number_plays += plays if self.parent: self.parent.set_number_plays(plays) def get_number_plays(self): return self.number_plays def evaluate_members(self): if self.is_file: self.most_recent_member_atime = os.stat(self.path).st_atime self.parent.set_most_recent_atime(self.most_recent_member_atime) #the number of plays for a file would have ideally been obtained from some index/db of sorts recorded over-time #/but, for simplicity in the current implementation, we shall assume all files have only been played once, by default self.set_number_plays(1) else: for p in os.listdir(self.path): path = os.path.join(self.path,p) if Entity.path_is_file(path): if re.match(Entity.file_filter,path) is not None: self.members.append(Entity(path,parent=self,ffilter=self.file_filter)) else: self.members.append(Entity(path,parent=self,ffilter=self.file_filter)) def get_most_recent_member_access_time(self): return self.most_recent_member_atime def calculate_rarity_rank(self): atime = datetime.fromtimestamp(self.get_most_recent_member_access_time()) now = datetime.now() radiff = (now - atime).seconds #print "radiff (now - atime) : %s | %s " % (radiff,self.path) if radiff == 0: self.rank = 1.0/self.get_number_plays() else: self.rank = (1 - 1.0 / radiff ) * self.get_number_plays() def calculate_rank(self,request_datetime): epoch = datetime(year=1970,month=1,day=1) atime = datetime.fromtimestamp(self.get_most_recent_member_access_time()) t = atime.time() atime = epoch + timedelta(hours=t.hour,minutes=t.minute,seconds=t.second) t = request_datetime.time() request_datetime = epoch + timedelta(hours=t.hour,minutes=t.minute,seconds=t.second) radiff = (request_datetime - atime).seconds #print "radiff (re - atime) : %s | %s " % (radiff,self.path) if radiff == 0: self.rank = self.get_number_plays() else: self.rank = ( 1.0 / radiff ) * self.get_number_plays() def get_best_members(self,request_datetime,size): from random import sample map(lambda m : m.calculate_rank(request_datetime), self.members) if self.is_file: return [self] else: best = [] for member in self.members: best.extend(member.get_best_members(request_datetime,size)) best_list = sorted(best,key=lambda m: m.rank,reverse=True)[0:size * 2] best_list = sample(best_list,min(size,len(best_list))) return best_list def get_rarest_members(self,size): from random import sample map(lambda m : m.calculate_rarity_rank(), self.members) if self.is_file: return [self] else: best = [] for member in self.members: best.extend(member.get_rarest_members(size)) best_list = sorted(best,key=lambda m: m.rank,reverse=True)[0:size * 2] best_list = sample(best_list,min(size,len(best_list))) return best_list def __repr__(self): return "%s : r:%s | p:%s { %s }" % ( "File" if self.is_file else "Dir", self.rank, self.number_plays, self.path ) @staticmethod def path_is_file(path): return os.path.isfile(path) class RecommendationEngine: def __init__(self,music_base,ffilter=r'^.+\.(mp3)$'): #only mp3 by default self.collection = Entity(music_base,ffilter=ffilter) def recommend_best(self,request_datetime,size): return self.collection.get_best_members(request_datetime,size) def recommend_rarest(self,size): return self.collection.get_rarest_members(size) if __name__ == '__main__': import sys collection_path = '/media/planet/Ziki' recommendation_size = 1 mode = 'best' if len(sys.argv) == 2: collection_path = os.path.expanduser(sys.argv[1]) elif len(sys.argv) == 3: collection_path = os.path.expanduser(sys.argv[1]) recommendation_size = int(sys.argv[2]) elif len(sys.argv) == 4: collection_path = os.path.expanduser(sys.argv[1]) recommendation_size = int(sys.argv[2]) mode = sys.argv[2] if os.path.exists(collection_path): if recommendation_size > 0: r = RecommendationEngine(collection_path,ffilter=r'^.+\.(mp3|mp4|flv|wma)$') request_datetime = datetime.now() playlist = r.recommend_best(request_datetime,recommendation_size) if mode == 'best' else r.recommend_rarest(recommendation_size) for p in playlist: print '"%s"' % p.path
[ "jlutalo@ds.co.ug" ]
jlutalo@ds.co.ug
28134dd8282ad2327183641cf55949cea7bc87f4
4d3032fd5062f7b6790951899c0ef6333a54bb83
/ppr-api/tests/unit/models/test_event_tracking.py
0154b3febec8bbe4f2505766782a1ad715e81fa7
[ "Apache-2.0" ]
permissive
bcgov/ppr
381ceb4120fc14fb21b0ee863b08e56fe35cf156
af1a4458bb78c16ecca484514d4bd0d1d8c24b5d
refs/heads/main
2023-08-24T00:34:09.508413
2023-08-23T18:44:52
2023-08-23T18:44:52
332,897,262
4
373
Apache-2.0
2023-09-14T17:24:40
2021-01-25T22:06:53
HTML
UTF-8
Python
false
false
6,284
py
# Copyright © 2019 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests to assure the EventTracking Model. Test-Suite to ensure that the EventTracking Model is working as expected. """ from http import HTTPStatus import pytest from ppr_api.models import EventTracking, utils as model_utils # testdata pattern is ({description}, {exists}, {search_value}) TEST_DATA_ID = [ ('Exists', True, 200000000), ('Does not exist', False, 300000000) ] # testdata pattern is ({description}, {exists}, {search_value}) TEST_DATA_KEY_ID = [ ('Exists', True, 200000008), ('Does not exist', False, 300000000) ] # testdata pattern is ({description}, {results_size}, {key_id}, {type}) TEST_DATA_KEY_ID_TYPE = [ ('No results', 0, 200000000, EventTracking.EventTrackingTypes.SEARCH_REPORT), ('1 result search', 1, 200000009, EventTracking.EventTrackingTypes.SEARCH_REPORT), ('3 results search', 1, 200000010, EventTracking.EventTrackingTypes.SEARCH_REPORT), ('1 result notification', 1, 200000011, EventTracking.EventTrackingTypes.API_NOTIFICATION), ('1 result email', 1, 200000012, EventTracking.EventTrackingTypes.EMAIL), ('1 result surface mail', 1, 200000013, EventTracking.EventTrackingTypes.SURFACE_MAIL), ('1 result email report', 1, 200000014, EventTracking.EventTrackingTypes.EMAIL_REPORT) ] # testdata pattern is ({description}, {key_id}, {type}, {status}, {message}) TEST_DATA_CREATE = [ ('Search', 200000010, EventTracking.EventTrackingTypes.SEARCH_REPORT, int(HTTPStatus.OK), 'message'), ('Notification', 200000011, EventTracking.EventTrackingTypes.API_NOTIFICATION, int(HTTPStatus.OK), 'message'), ('Email', 200000012, EventTracking.EventTrackingTypes.EMAIL, int(HTTPStatus.OK), 'message'), ('Surface mail', 200000013, EventTracking.EventTrackingTypes.SURFACE_MAIL, int(HTTPStatus.OK), 'message'), ('Email report', 200000014, EventTracking.EventTrackingTypes.EMAIL_REPORT, int(HTTPStatus.OK), 'message') ] # testdata pattern is ({description}, {results_size}, {key_id}, {type}, extra_key) TEST_DATA_KEY_ID_TYPE_EXTRA = [ ('No results registration id', 0, 200000000, EventTracking.EventTrackingTypes.SURFACE_MAIL, '9999998'), ('No results party id', 0, 200000030, EventTracking.EventTrackingTypes.SURFACE_MAIL, '9999998'), ('4 results party id', 4, 200000030, EventTracking.EventTrackingTypes.SURFACE_MAIL, '9999999') ] @pytest.mark.parametrize('desc,exists,search_value', TEST_DATA_ID) def test_find_by_id(session, desc, exists, search_value): """Assert that find event tracking by id contains all expected elements.""" event_tracking = EventTracking.find_by_id(search_value) if exists: assert event_tracking assert event_tracking.id == search_value assert event_tracking.key_id assert event_tracking.event_ts assert event_tracking.event_tracking_type == EventTracking.EventTrackingTypes.SEARCH_REPORT else: assert not event_tracking @pytest.mark.parametrize('desc,exists,search_value', TEST_DATA_KEY_ID) def test_find_by_key_id(session, desc, exists, search_value): """Assert that find event tracking by key id contains all expected elements.""" events = EventTracking.find_by_key_id(search_value) if exists: assert events assert events[0].id > 0 assert events[0].key_id == search_value assert events[0].event_ts assert events[0].event_tracking_type == EventTracking.EventTrackingTypes.SEARCH_REPORT else: assert not events @pytest.mark.parametrize('desc,results_size,key_id,type', TEST_DATA_KEY_ID_TYPE) def test_find_by_id_type(session, desc, results_size, key_id, type): """Assert that find event tracking by key id and type contains all expected elements.""" events = EventTracking.find_by_key_id_type(key_id, type) if results_size > 0: assert events assert len(events) >= results_size else: assert not events @pytest.mark.parametrize('desc,key_id,type,status,message', TEST_DATA_CREATE) def test_create(session, desc, key_id, type, status, message): """Assert that create event tracking works as expected.""" event_tracking = EventTracking.create(key_id, type, status, message) assert event_tracking assert event_tracking.id > 0 assert event_tracking.event_ts assert event_tracking.event_tracking_type == type assert event_tracking.status == status assert event_tracking.message == message @pytest.mark.parametrize('desc,results_size,key_id,type,extra_key', TEST_DATA_KEY_ID_TYPE_EXTRA) def test_find_by_id_type_extra(session, desc, results_size, key_id, type, extra_key): """Assert that find event tracking by key id, extra key, and type contains all expected elements.""" events = EventTracking.find_by_key_id_type(key_id, type, extra_key) if results_size > 0: assert events assert len(events) >= results_size else: assert not events def test_event_tracking_json(session): """Assert that the event tracking model renders to a json format correctly.""" now_ts = model_utils.now_ts() tracking = EventTracking( id=1000, key_id=1000, event_ts=now_ts, event_tracking_type=EventTracking.EventTrackingTypes.SEARCH_REPORT, status=200, message='message', email_id='test@gmail.com' ) tracking_json = { 'eventTrackingId': tracking.id, 'keyId': tracking.key_id, 'type': tracking.event_tracking_type, 'createDateTime': model_utils.format_ts(tracking.event_ts), 'status': tracking.status, 'message': tracking.message, 'emailAddress': tracking.email_id } assert tracking.json == tracking_json
[ "noreply@github.com" ]
bcgov.noreply@github.com
81a2523e98ce2cd990ae80580e687a48b209f37a
f9d17c9d5934195f110e4bbcb6cc965028d7e5fe
/T1/ServoTest/SerialTest.py
79af3ec0fd1964f6b0e7bdc89c47314dcace5097
[]
no_license
chaturatbs/Shef_E3RoboPorter-2016
43944f4c0e1dbedeee355e065dd9ef52eace8484
5b9d1447d15c836bf79c8cba078b8b3b5aad1f70
refs/heads/master
2020-08-01T16:59:42.956498
2017-12-14T12:19:22
2017-12-14T12:19:22
73,572,154
0
2
null
null
null
null
UTF-8
Python
false
false
653
py
import serial import time serialConnected = False usInput = raw_input("input control command - ") while True: if not serialConnected: # setup serial connection to motor controller print("Trying to connect to serial devices") try: motorConn = serial.Serial('COM4', 19200) # EDIT THIS LINE serialConnected = True print ('Connected to serial port COM4') except Exception as e: print ('Unable to establish serial comms to port /dev/ttyACM0') else: print("Instructing to go at " + usInput) motorConn.write(usInput) time.sleep(1.5) #AND THIS LINE
[ "chaturasamarakoon@rocketmail.com" ]
chaturasamarakoon@rocketmail.com
bedbc5233537da4503b44207d0e30f0759039d35
09c7443ee3fdc0095b0f2aef5cdd4f7d81a8bcc0
/data/parser.py
630a5e2ee9ff62470dfe078dcc766045b98e4682
[]
no_license
dacharya64/PhandelverProlog
8036e7fff3d24a9b52a4170d67c464f14d8aa334
41dbaae4c86f7697cf7cf5106e041af22078ae32
refs/heads/main
2023-07-03T14:06:00.676640
2021-05-19T23:54:46
2021-05-19T23:54:46
346,779,147
1
0
null
2021-05-10T18:11:04
2021-03-11T17:13:07
JavaScript
UTF-8
Python
false
false
1,203
py
import json import re # file to which we will be writing fWrite = open('parsed.txt', 'w') # opens the JSON file with the data and saves it to a JSON object with open('cast.json') as data_file: data = json.load(data_file) # runs through each element in JSON object and extracts the data, writing it to file for item in data: orig_tag = item["tag"] if "faction" in item: orig_name = item["faction"] # for info in orig_name: # new_tag = re.sub(r'(?<!^)(?=[A-Z])', '_', orig_tag).lower() # new_info = re.sub(r'(?<!^)(?=[A-Z])', '_', info).lower() # fWrite.write("goes_to_info(" + new_tag + ", " + new_info + ").\n") #name = orig_name.split(" ") #first_name = name[1].lower() #if (first_name != None): new_tag = re.sub(r'(?<!^)(?=[A-Z])', '_', orig_tag).lower() #fWrite.write("character_info(" + new_tag + ", status, " + orig_name + ").\n") # convert tag to snake case #new_name = re.sub(r'(?<!^)(?=[A-Z])', '_', orig_name).lower() # write without quotes # write with quotes fWrite.write("character_info(" + new_tag + ", faction, \"" + orig_name + "\").\n") fWrite.close()
[ "dacharya64@gmail.com" ]
dacharya64@gmail.com
cd96606f20cea9ef658e037040d9d9f89bdea892
407c6f47116c32c909e353b41b88b42eae7a0873
/tests/1_local/test_key.py
871ec0dac372c401b153554363111114c10c885a
[ "Apache-2.0", "Python-2.0" ]
permissive
cloudmesh/cloudmesh-cloud
29132f95beb665ff6fd7f5baf14c2c5fc26d528a
cef0c22a3b89a11a838da1ae6734344dd5415277
refs/heads/main
2022-12-11T16:09:36.136775
2021-04-21T15:03:27
2021-04-21T15:03:27
147,824,315
5
27
Apache-2.0
2022-12-08T01:20:52
2018-09-07T13:03:38
Python
UTF-8
Python
false
false
1,588
py
############################################################### # pytest -v --capture=no tests/1_local/test_key.py # pytest -v tests/1_local/test_key.py # pytest -v --capture=no tests/1_local/test_key..py::Test_key::<METHODNAME> ############################################################### from pprint import pprint import pytest from cloudmesh.common.Benchmark import Benchmark from cloudmesh.common.util import HEADING from cloudmesh.management.configuration.SSHkey import SSHkey Benchmark.debug() cloud = "local" @pytest.mark.incremental class TestName: def test_key(self): HEADING() Benchmark.Start() key = SSHkey() Benchmark.Stop() pprint(key) print(key) print(type(key)) pprint(key.__dict__) assert key.__dict__ is not None # def test_git(self): # HEADING() # config = Config() # username = config["cloudmesh.profile.github"] # print("Username:", username) # key = SSHkey() # Benchmark.Start() # keys = key.get_from_git(username) # Benchmark.Stop() # pprint(keys) # print(Printer.flatwrite(keys, # sort_keys=["name"], # order=["name", "fingerprint"], # header=["Name", "Fingerprint"]) # ) # assert len(keys) > 0 def test_benchmark(self): HEADING() Benchmark.print(csv=True, sysinfo=False, tag=cloud)
[ "laszewski@gmail.com" ]
laszewski@gmail.com
eefddb41bc553702f602778afced539c75245384
224d300356bc6a1f67e87c6a8eb4a506b5e4ff93
/projetTDlog/manage.py
fd3f72e41b35b15f01388cc2312989d057e900ac
[]
no_license
ClementHardy/projet
1fac219c17a30c529238c3f11a11cb2c77ae9192
a911930133cc4f4d63e40b66b6d768365c58c6c0
refs/heads/master
2020-06-11T14:57:52.774388
2017-02-21T14:31:25
2017-02-21T14:31:25
75,640,638
0
0
null
null
null
null
UTF-8
Python
false
false
809
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projetTDlog.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
[ "clement.hardy@eleves.enpc.fr" ]
clement.hardy@eleves.enpc.fr
1cd697855141f55f88e899f846bad705a48bae85
ac2c3e8c278d0aac250d31fd023c645fa3984a1b
/saleor/saleor/plugins/invoicing/plugin.py
137714cdd3c67fe77e28a0bffdd157ebe0409078
[ "BSD-3-Clause", "CC-BY-4.0" ]
permissive
jonndoe/saleor-test-shop
152bc8bef615382a45ca5f4f86f3527398bd1ef9
1e83176684f418a96260c276f6a0d72adf7dcbe6
refs/heads/master
2023-01-21T16:54:36.372313
2020-12-02T10:19:13
2020-12-02T10:19:13
316,514,489
1
1
BSD-3-Clause
2020-11-27T23:29:20
2020-11-27T13:52:33
TypeScript
UTF-8
Python
false
false
1,200
py
from typing import Any, Optional from uuid import uuid4 from django.core.files.base import ContentFile from ...core import JobStatus from ...invoice.models import Invoice from ...order.models import Order from ..base_plugin import BasePlugin from .utils import generate_invoice_number, generate_invoice_pdf class InvoicingPlugin(BasePlugin): PLUGIN_ID = "mirumee.invoicing" PLUGIN_NAME = "Invoicing" DEFAULT_ACTIVE = True PLUGIN_DESCRIPTION = "Built-in saleor plugin that handles invoice creation." def invoice_request( self, order: "Order", invoice: "Invoice", number: Optional[str], previous_value: Any, ) -> Any: invoice.update_invoice(number=generate_invoice_number()) file_content, creation_date = generate_invoice_pdf(invoice) invoice.created = creation_date invoice.invoice_file.save( f"invoice-{invoice.number}-order-{order.id}-{uuid4()}.pdf", ContentFile(file_content), ) invoice.status = JobStatus.SUCCESS invoice.save( update_fields=["created", "number", "invoice_file", "status", "updated_at"] ) return invoice
[ "testuser@151-248-122-3.cloudvps.regruhosting.ru" ]
testuser@151-248-122-3.cloudvps.regruhosting.ru
3ab2ce4378e2248095071b8b0936949ff0df0a5c
50f3b7fd58394ff0ed8a988014a371b09f61e13f
/sandbox/wierzbicki/test27/CPythonLib/distutils/command/upload.py
df82e4ca562c2048d8f4b52e73a8f31caa4b2229
[ "LicenseRef-scancode-jython" ]
permissive
pombreda/jython-jbossorg
db2e1caf780b1bf863ab5fa253a3ab22804f4b0b
b41953a1bc73720d14e36d88ed19c77e8199c229
refs/heads/master
2020-12-26T05:01:59.536537
2012-04-25T14:05:45
2012-04-25T15:41:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,977
py
"""distutils.command.upload Implements the Distutils 'upload' subcommand (upload package to PyPI).""" from distutils.errors import * from distutils.core import PyPIRCCommand from distutils.spawn import spawn from distutils import log import sys import os import socket import platform import httplib import base64 import urlparse import cStringIO as StringIO from ConfigParser import ConfigParser # this keeps compatibility for 2.3 and 2.4 if sys.version < "2.5": from md5 import md5 else: from hashlib import md5 class upload(PyPIRCCommand): description = "upload binary package to PyPI" user_options = PyPIRCCommand.user_options + [ ('sign', 's', 'sign files to upload using gpg'), ('identity=', 'i', 'GPG identity used to sign files'), ] boolean_options = PyPIRCCommand.boolean_options + ['sign'] def initialize_options(self): PyPIRCCommand.initialize_options(self) self.username = '' self.password = '' self.show_response = 0 self.sign = False self.identity = None def finalize_options(self): PyPIRCCommand.finalize_options(self) if self.identity and not self.sign: raise DistutilsOptionError( "Must use --sign for --identity to have meaning" ) config = self._read_pypirc() if config != {}: self.username = config['username'] self.password = config['password'] self.repository = config['repository'] self.realm = config['realm'] # getting the password from the distribution # if previously set by the register command if not self.password and self.distribution.password: self.password = self.distribution.password def run(self): if not self.distribution.dist_files: raise DistutilsOptionError("No dist file created in earlier command") for command, pyversion, filename in self.distribution.dist_files: self.upload_file(command, pyversion, filename) def upload_file(self, command, pyversion, filename): # Sign if requested if self.sign: gpg_args = ["gpg", "--detach-sign", "-a", filename] if self.identity: gpg_args[2:2] = ["--local-user", self.identity] spawn(gpg_args, dry_run=self.dry_run) # Fill in the data - send all the meta-data in case we need to # register a new release content = open(filename,'rb').read() meta = self.distribution.metadata data = { # action ':action': 'file_upload', 'protcol_version': '1', # identify release 'name': meta.get_name(), 'version': meta.get_version(), # file content 'content': (os.path.basename(filename),content), 'filetype': command, 'pyversion': pyversion, 'md5_digest': md5(content).hexdigest(), # additional meta-data 'metadata_version' : '1.0', 'summary': meta.get_description(), 'home_page': meta.get_url(), 'author': meta.get_contact(), 'author_email': meta.get_contact_email(), 'license': meta.get_licence(), 'description': meta.get_long_description(), 'keywords': meta.get_keywords(), 'platform': meta.get_platforms(), 'classifiers': meta.get_classifiers(), 'download_url': meta.get_download_url(), # PEP 314 'provides': meta.get_provides(), 'requires': meta.get_requires(), 'obsoletes': meta.get_obsoletes(), } comment = '' if command == 'bdist_rpm': dist, version, id = platform.dist() if dist: comment = 'built for %s %s' % (dist, version) elif command == 'bdist_dumb': comment = 'built for %s' % platform.platform(terse=1) data['comment'] = comment if self.sign: data['gpg_signature'] = (os.path.basename(filename) + ".asc", open(filename+".asc").read()) # set up the authentication auth = "Basic " + base64.encodestring(self.username + ":" + self.password).strip() # Build up the MIME payload for the POST data boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = '\n--' + boundary end_boundary = sep_boundary + '--' body = StringIO.StringIO() for key, value in data.items(): # handle multiple entries for the same name if type(value) != type([]): value = [value] for value in value: if type(value) is tuple: fn = ';filename="%s"' % value[0] value = value[1] else: fn = "" value = str(value) body.write(sep_boundary) body.write('\nContent-Disposition: form-data; name="%s"'%key) body.write(fn) body.write("\n\n") body.write(value) if value and value[-1] == '\r': body.write('\n') # write an extra newline (lurve Macs) body.write(end_boundary) body.write("\n") body = body.getvalue() self.announce("Submitting %s to %s" % (filename, self.repository), log.INFO) # build the Request # We can't use urllib2 since we need to send the Basic # auth right with the first request schema, netloc, url, params, query, fragments = \ urlparse.urlparse(self.repository) assert not params and not query and not fragments if schema == 'http': http = httplib.HTTPConnection(netloc) elif schema == 'https': http = httplib.HTTPSConnection(netloc) else: raise AssertionError, "unsupported schema "+schema data = '' loglevel = log.INFO try: http.connect() http.putrequest("POST", url) http.putheader('Content-type', 'multipart/form-data; boundary=%s'%boundary) http.putheader('Content-length', str(len(body))) http.putheader('Authorization', auth) http.endheaders() http.send(body) except socket.error, e: self.announce(str(e), log.ERROR) return r = http.getresponse() if r.status == 200: self.announce('Server response (%s): %s' % (r.status, r.reason), log.INFO) else: self.announce('Upload failed (%s): %s' % (r.status, r.reason), log.ERROR) if self.show_response: print '-'*75, r.read(), '-'*75
[ "kkhan@redhat.com" ]
kkhan@redhat.com
450c636027f99f51a734838caab2bb006cfbae52
e10ee9866c4338ed7e1aba9b10d134c933e75018
/backend/task/models.py
9a68128b131edee741fa608e0c30af2a9701968c
[]
no_license
luyang14/IoT_device_client
052711e1240a0226057e90a0aea7638d4a1528d5
7d5c098ff8a2c8174af68704da75df7aec415639
refs/heads/master
2022-12-08T11:12:45.957013
2019-06-17T14:09:25
2019-06-17T14:09:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,707
py
from django.db import models from gateway.models import GatewayBase from django.utils import timezone # Create your models here. class Gateway_task(models.Model): name = models.CharField(max_length=20, null=False) gateway = models.ForeignKey(GatewayBase, on_delete=models.CASCADE, to_field='gateway_name') description = models.TextField(default='', max_length=200) protocol = models.CharField(default='modbus', max_length=10) create_time = models.DateField() status = models.BooleanField(default=False) class TaskRecord(models.Model): SEND_WAY = ( ("change", u"改变上报"), ("time", u"定时上报") ) gateway = models.ForeignKey(GatewayBase, on_delete=models.CASCADE, to_field='gateway_name') slave_id = models.IntegerField(null=False, default=1, verbose_name='设备地址') function_name = models.CharField(max_length=20, null=True, verbose_name='功能名称') identifier = models.CharField(max_length=10, verbose_name='标识符') modbus_function_code = models.IntegerField(null=False, verbose_name='modbus功能码') start_address = models.IntegerField(null=False) # address_length = models.IntegerField(default=1) data_length = models.IntegerField(default=16) top_limit = models.FloatField(null=True) low_limit = models.FloatField(null=True) scale = models.FloatField(default=1, verbose_name='缩放因子') interval = models.IntegerField(default=5, verbose_name='采集间隔(s)') send_way = models.CharField(choices=SEND_WAY, max_length=6) compute = models.TextField(max_length=200, default='', verbose_name='计算公式') active_status = models.BooleanField(default=True)
[ "1343837706@qq.com" ]
1343837706@qq.com
141d021adc4a96e35dc326ccab9e078a56c9c6c2
88b667f671beb285e567f7648e92247d644a3abd
/dummies/zerg/Paul.py
fef05d8d6c136936c7a4d32eeb5778656e427711
[ "MIT" ]
permissive
august-k/sharpy-paul
e7fbd6ac181d7e81e1f60eb34016063227590a64
6f4462208842db6dd32b30d5c1ebf90e79e975a0
refs/heads/master
2022-07-17T15:40:31.603339
2021-02-26T02:56:34
2021-02-26T02:56:34
257,317,358
1
1
MIT
2022-06-22T02:07:06
2020-04-20T15:05:13
Python
UTF-8
Python
false
false
10,631
py
"""Main code for running Paul.""" from typing import List, Optional, Dict import numpy as np import sc2 from sc2 import position from sc2.data import AIBuild, Difficulty, Race from sc2.ids.unit_typeid import UnitTypeId from sc2.player import Bot, Computer from sc2.position import Point2 from sc2.unit import Unit from sklearn.cluster import KMeans from paul_plans.build_manager import BuildSelector from sharpy.knowledges import KnowledgeBot from sharpy.managers import ManagerBase from sharpy.managers.unit_role_manager import UnitTask from sharpy.plans import BuildOrder from sharpy.plans.tactics import ( PlanCancelBuilding, PlanFinishEnemy, PlanWorkerOnlyDefense, PlanZoneAttack, PlanZoneDefense, PlanZoneGather, ) from sharpy.plans.tactics.zerg import InjectLarva, SpreadCreep, PlanHeatOverseer, CounterTerranTie from paul_plans.single_build_order import PaulBuild from paul_plans.mass_expand import MassExpand from paul_plans.scout_manager import ScoutManager class PaulBot(KnowledgeBot): """Run Paul.""" def __init__(self, build_name: str = ""): """Set up attack parameters and name.""" super().__init__("Paul") self.my_race = Race.Zerg self.attack = PlanZoneAttack(200) self.attack.retreat_multiplier = 0.3 self.build_name = build_name self.build_selector = BuildSelector(build_name) self.scout_manager = ScoutManager() self.hidden_ol_spots: List[Point2] self.hidden_ol_index: int = 0 self.scout_ling_count = 0 self.ling_scout_location: Dict[int, Point2] = {} async def create_plan(self) -> BuildOrder: """Turn plan into BuildOrder.""" attack_tactics = [ PlanZoneGather(), PlanZoneDefense(), self.attack, PlanFinishEnemy(), PlanWorkerOnlyDefense(), ] return BuildOrder( [ CounterTerranTie([PaulBuild()]), attack_tactics, InjectLarva(), SpreadCreep(), PlanCancelBuilding(), MassExpand(), PlanHeatOverseer(), ] ) async def on_start(self): """ Calculate and sort Overlord hidden spots. Automatically called at the start of the game once game info is available. """ await self.real_init() self.calculate_overlord_spots() # This is Infy's fault # noinspection PyProtectedMember self.hidden_ol_spots.sort( key=lambda x: self.knowledge.ai._distance_pos_to_pos(x, self.knowledge.enemy_main_zone.center_location), ) self.ling_scout_location = { 0: self.knowledge.zone_manager.enemy_expansion_zones[1].gather_point, 1: self.knowledge.zone_manager.enemy_expansion_zones[2].gather_point, 2: self.knowledge.ai.game_info.map_center, 3: self.knowledge.zone_manager.expansion_zones[2].gather_point, } if self.knowledge.ai.watchtowers: self.ling_scout_location[2] = self.knowledge.ai.watchtowers.closest_to( self.knowledge.enemy_expansion_zones[1].center_location ) if self.knowledge.enemy_race == Race.Zerg: self.ling_scout_location[0] = self.knowledge.zone_manager.enemy_expansion_zones[ 0 ].behind_mineral_position_center def configure_managers(self) -> Optional[List[ManagerBase]]: """Add custom managers.""" return [self.scout_manager] async def on_unit_created(self, unit: Unit): """Send Overlords and lings to scouting spots.""" if unit.type_id == UnitTypeId.OVERLORD: if self.hidden_ol_index + 1 >= len(self.hidden_ol_spots): return else: if self.hidden_ol_index == 0: self.do( unit.move( self.knowledge.zone_manager.enemy_expansion_zones[1].center_location.towards( self.knowledge.ai.game_info.map_center, 11 ) ) ) self.do(unit.move(self.hidden_ol_spots[self.hidden_ol_index], queue=True)) self.hidden_ol_index += 1 elif unit.type_id == UnitTypeId.ZERGLING: if self.scout_ling_count in self.ling_scout_location: self.do(unit.move(self.ling_scout_location[self.scout_ling_count])) self.knowledge.roles.set_task(UnitTask.Scouting, unit) self.scout_ling_count += 1 # async def on_enemy_unit_entered_vision(self, unit: Unit): # """ # Get scouting information when units enter vision. # # Called automatically. # """ # if ( # not self.paul_build.enemy_rush # and unit.can_attack # and unit.type_id not in {UnitTypeId.DRONE, UnitTypeId.PROBE, UnitTypeId.SCV} # ): # if self.knowledge.enemy_units_manager.enemy_total_power.power >= 3 and self.time <= 3 * 60: # self.paul_build.enemy_rush = True def calculate_overlord_spots(self): """Calculate hidden overlord spots for scouting.""" # first get all highground tiles max_height: int = np.max(self.game_info.terrain_height.data_numpy) highground_spaces: np.array = np.where(self.game_info.terrain_height.data_numpy == max_height) # stack the y and x coordinates together, transpose the matrix for # easier use, this then reflects x and y coordinates all_highground_tiles: np.array = np.vstack((highground_spaces[1], highground_spaces[0])).transpose() # get distances of high ground tiles to start dist_from_start: np.array = self.calculate_distance_points_from_location( self.start_location, all_highground_tiles ) # get ids of all tiles that are further than 30 valid_tiles_start: np.array = np.where(dist_from_start > 30)[0] # get all distances of high ground tiles to enemy start dist_from_enemy_start: np.array = self.calculate_distance_points_from_location( self.enemy_start_locations[0], all_highground_tiles ) # get ids of all tiles that are further than 30 valid_tiles_enemy_start: np.array = np.where(dist_from_enemy_start > 30)[0] # valid tiles = where valid_tiles_start == valid_tiles_enemy_start valid_tiles_idx: np.array = np.intersect1d(valid_tiles_start, valid_tiles_enemy_start) # finally, store all coordinates that are valid valid_tiles: np.array = all_highground_tiles[valid_tiles_idx] self.hidden_ol_spots = self.find_highground_centroids(valid_tiles) def find_highground_centroids(self, highground_tiles) -> np.array: """Find the centroids of the highground clusters for KMeans.""" # using db index, find the optimal number of clusters for kmeans range_of_k = range(4, 22) # store all the davies-bouldin index values dbindexes = [] for k in range_of_k: # try kmeans for each k value kmeans = KMeans(n_clusters=k, random_state=42).fit(highground_tiles) dbindexes.append(self.davis_bouldin_index(highground_tiles, kmeans.labels_, k)) kmeans = KMeans(n_clusters=np.argmin(dbindexes) + 4, random_state=42).fit(highground_tiles) ol_spots: List[Point2] = [Point2(position.Pointlike((pos[0], pos[1]))) for pos in kmeans.cluster_centers_] # each clusters centroid is the overlord positions return ol_spots def davis_bouldin_index(self, X, y_pred, k): """ Calculate an index value score on a model and its predicted clusters. Parameters ---------- X : np matrix the whole dataset y_pred : np array array of indices indicating which values of X belong to a cluster k : int number of clusters Returns ------- float Davies_Bouldin index """ def euclidean_distance(x, y): return np.sqrt(np.sum(np.square(x - y))) # somewhere to store distances in each cluster distances = [[] for i in range(k)] # somewhere to store the centroids for each cluster centroids = np.zeros(k * 2).reshape(k, 2) # compute euclidean distance between each point # to its clusters centroid for i in range(k): centroids[i] = np.array([np.mean(X[y_pred == i, :1]), np.mean(X[y_pred == i, 1:])]) for sample in X[y_pred == i]: distances[i].append(euclidean_distance(sample, centroids[i])) # now all the distances have been computed, # calculate the mean distances for each cluster mean_distances = [np.mean(distance) for distance in distances] # will hold the summation of max value for the ratio # within-to-between clusters i and j dbi = 0 for i in range(k): max_distance = 0.0 for j in range(k): if i != j: # ratio within-to-between clusters i and j values = (mean_distances[i] + mean_distances[j]) / euclidean_distance(centroids[i], centroids[j]) # if worst case so far change max_distance to the value if values > max_distance: max_distance = values # add worst case distance for this pair of clusters to dbi dbi += max_distance # returns the average of all the worst cases # between each pair of clusters return dbi / k def calculate_distance_points_from_location(self, start: Point2, points: np.array) -> np.array: """Determine distance from point to start location.""" sl = np.array([start[0], start[1]]) sl = np.expand_dims(sl, 0) # euclidean distance on multiple points to a single point dist = (points - sl) ** 2 dist = np.sum(dist, axis=1) dist = np.sqrt(dist) return dist def main(): """Run things.""" sc2.run_game( sc2.maps.get("TritonLE"), [Bot(Race.Zerg, PaulBot()), Computer(Race.Terran, Difficulty.VeryEasy)], # [Bot(Race.Zerg, PaulBot()), Computer(Race.Terran, Difficulty.VeryHard, AIBuild.Rush)], realtime=False, save_replay_as="Paul2.SC2Replay", ) if __name__ == "__main__": main()
[ "august.kaplan@gmail.com" ]
august.kaplan@gmail.com
55dc05cdce531140b7ca72b0faa16248f3266bbb
06c9edb02884ced68c62b5527d2be0e1a2e65bf1
/2577.py
7f53e62567eb22b619ff25d4224d8c1bd7aa9546
[]
no_license
0x232/BOJ
3c5d3973b62036bfe9b761c88c822cf7fe909bce
5f135ac51b1c304eff4630798fb5c516b666a5c6
refs/heads/master
2021-07-03T02:56:00.132987
2020-10-31T02:18:19
2020-10-31T02:18:19
191,161,517
0
0
null
null
null
null
UTF-8
Python
false
false
135
py
a = int(input()) b = int(input()) c = int(input()) arr = [0] * 10 for i in str(a*b*c): arr[int(i)] += 1 for i in arr: print(i)
[ "51640066+0x232@users.noreply.github.com" ]
51640066+0x232@users.noreply.github.com
036c323e0db3a4c3d503def0990f28bebd68f594
dabe85f4b2a6f683bfaa7decd358b2f282430350
/com.lxh/exercises/30_tuple_to_dict/__init__.py
5ab1709276c196c5bb64155e9c89f1117419fb8c
[]
no_license
hnz71211/Python-Basis
e6d239df7bb2873600173d05c32c136c28cc9f4b
2893d0d3402ee0bfb5292e2f6409211845a88e26
refs/heads/master
2020-11-29T21:37:06.774000
2020-04-13T04:15:04
2020-04-13T04:15:04
230,220,833
0
0
null
null
null
null
UTF-8
Python
false
false
158
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 将空间坐标元组 (1,2,3) 的三个元素解包对应到变量 x,y,z x, y, z = (1, 2, 3) print(x, y, z)
[ "hxl71396812@gmail.com" ]
hxl71396812@gmail.com
96619644665200a2e51fa831412b76fc8b3285a6
e13e18d322e76a82e3c41e1a1947fff59f27a503
/OpenML/OpenML/datasets/urls.py
da82126cc6fe93530a2e2d3c76a6e7cad8ef1e85
[]
no_license
Dihia/OpenML_Streaming_Challenge
427bed2fb3b85f7d32fa94c3b2c9764c401fbbd6
4d1d390e71eea4317919a7e4cbf8381fa60b5d6f
refs/heads/master
2021-01-21T11:15:09.213811
2017-03-09T14:29:15
2017-03-09T14:29:15
83,536,615
0
0
null
null
null
null
UTF-8
Python
false
false
179
py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<id>[1-9][0-9]*)$', views.show, name='show'), url(r'^list$', views.index, name='index') ]
[ "maxime@buron.coffee" ]
maxime@buron.coffee