blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
041e262947c9bf7972e3fb50938ddef32cf407cc
8ed4bf9fbead471c9e5f88e4d18ac432ec3d628b
/hackerrank/algorithm/implementation/bonetrousle.py
f757a2dcc98a7f8c3969b716375b3557e543a413
[]
no_license
hizbul25/programming_problem
9bf26e49ed5bb8c9c829d00e765c9401222fb35c
2acca363704b993ffe5f6c2b00f81a4f4eca7204
refs/heads/master
2021-01-10T22:28:26.105787
2018-01-21T16:45:45
2018-01-21T16:45:45
65,394,734
1
0
null
null
null
null
UTF-8
Python
false
false
1,109
py
# Problem URL: https://www.hackerrank.com/challenges/bonetrousle firstLine = int(input()) for a in range(0, firstLine): nums = input() numsArr = list(map(int, nums.split(" "))) n = numsArr[0] k = numsArr[1] b = numsArr[2] num1 = 0 rem = 0 answer = True remAdded = False count = 0 boxArr = [] for i in range(1, b+1): count += i boxArr.append(i) num1 = (n - count)//b rem = (n - count) % b for j in range(0, len(boxArr)): boxArr[j] += num1 if boxArr[j] > k: answer = False if rem == 0: remAdded = True elif boxArr[-1] + 1 > k: remAdded = False elif answer is not False: l = len(boxArr) - 1 for r in range(l, l - rem, -1): boxArr[r] += 1 remAdded = True if answer is False or remAdded is False: print(-1) elif 0 in boxArr: print(-1) else: for z in range(0, len(boxArr)): if z != len(boxArr) - 1: print(boxArr[z], end=" ") else: print(boxArr[z])
[ "hizbul.ku@gmail.com" ]
hizbul.ku@gmail.com
6b8f6dbf41521d7d6397fdaf4ef3af2ad4fcc709
0d9c964fd7644395a3f0763f484e485fcc67f762
/new/src/13.03.2021/OOP_ Змейка.py
92f0fa1f4d92712f47d0aa2dcf595724363bb77d
[ "Apache-2.0" ]
permissive
VladBaryliuk/my_start_tasks
eaa2e6ff031f2f504be11f0f64f5d99bd1a68a0e
bf387543e6fa3ee303cbef04d2af48d558011ed9
refs/heads/main
2023-04-14T14:00:08.415787
2021-04-24T13:47:38
2021-04-24T13:47:38
354,538,499
0
0
null
null
null
null
UTF-8
Python
false
false
4,801
py
from tkinter import * import random # Создаем окно root = Tk() # Устанавливаем название окна root.title("Змейка на PYTНON") # ширина экрана WIDTH = 800 # высота экрана HEIGHT = 600 # Размер сегмента змейки SEG_SIZE = 20 # Переменная отвечающая за состояние игры IN_GAME = True # создаем экземпляр класса Canvas (его мы еще будем использовать) и заливаем все зеленым цветом c = Canvas(root, width=WIDTH, height=HEIGHT, bg="#003300") c.grid() # Наводим фокус на Canvas, чтобы мы могли ловить нажатия клавиш c.focus_set() class Segment(object): """ Класс сегмента змейки """ def __init__(self, x, y): self.instance = c.create_rectangle(x, y, x + SEG_SIZE, y + SEG_SIZE, fill="white") class Snake(object): """ Класс змейки """ def __init__(self, segments): self.segments = segments # список доступных направлений движения змейки self.mapping = {"Down": (0, 1), "Right": (1, 0), "Up": (0, -1), "Left": (-1, 0)} # изначально змейка двигается вправо self.vector = self.mapping["Right"] def move(self): """ Двигает змейку в заданном направлении """ # перебираем все сегменты кроме первого for index in range(len(self.segments) - 1): segment = self.segments[index].instance x1, y1, x2, y2 = c.coords(self.segments[index + 1].instance) # задаем каждому сегменту позицию сегмента стоящего после него c.coords(segment, x1, y1, x2, y2) # получаем координаты сегмента перед "головой" x1, y1, x2, y2 = c.coords(self.segments[-2].instance) # получаем координаты сегмента перед "головой" c.coords(self.segments[-1].instance, x1 + self.vector[0] * SEG_SIZE, y1 + self.vector[1] * SEG_SIZE, x2 + self.vector[0] * SEG_SIZE, y2 + self.vector[1] * SEG_SIZE) def add_segment(self): """ Добавляет сегмент змейке """ # определяем последний сегмент last_seg = c.coords(self.segments[0].instance) # определяем последний сегмент x = last_seg[2] - SEG_SIZE y = last_seg[3] - SEG_SIZE self.segments.insert(0, Segment(x, y)) """ Изменяет направление движения змейки """ def change_direction(self, event): if event.keysym in self.mapping: self.vector = self.mapping[event.keysym] # создаем набор сегментов segments = [Segment(SEG_SIZE, SEG_SIZE), Segment(SEG_SIZE * 2, SEG_SIZE), Segment(SEG_SIZE * 3, SEG_SIZE)] s = Snake(segments) def create_block(): """ Создает блок в случайной позиции на карте """ global BLOCK posx = SEG_SIZE * random.randint(1, (WIDTH - SEG_SIZE) / SEG_SIZE) posy = SEG_SIZE * random.randint(1, (HEIGHT - SEG_SIZE) / SEG_SIZE) BLOCK = c.create_oval(posx, posy, posx + SEG_SIZE, posy + SEG_SIZE, fill="red") def main(): global IN_GAME if IN_GAME: s.move() head_coords = c.coords(s.segments[-1].instance) x1, y1, x2, y2 = head_coords # Столкновение с границами экрана if x2 > WIDTH or x1 < 0 or y1 < 0 or y2 > HEIGHT: IN_GAME = False # Поедание яблок elif head_coords == c.coords(BLOCK): s.add_segment() c.delete(BLOCK) create_block() # Самоедство else: for index in range(len(s.segments) - 1): if head_coords == c.coords(s.segments[index].instance): IN_GAME = False root.after(100, main) # Если не в игре выводим сообщение о проигрыше else: c.create_text(WIDTH / 2, HEIGHT / 2, text="GAME OVER!", font="Arial 20", fill="red") c.bind("<KeyPress>", s.change_direction) create_block() main() # Запускаем окно root.mainloop()
[ "vladmain9@gmail.com" ]
vladmain9@gmail.com
6296a611321521ffd2004163b14e0bc37d43db87
4d2238210813c1581bf44f64d8a63196f75d2df4
/dfs.py
d9fd93c39b98cb91429e37fb06a310f3bc3625f3
[]
no_license
wwtang/code02
b1600d34907404c81fa523cfdaa74db0021b8bb3
9f03dda7b339d8c310c8a735fc4f6d795b153801
refs/heads/master
2020-12-24T14:10:33.738734
2012-12-14T04:24:47
2012-12-14T04:24:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,172
py
class Vertex: def __init__(self, data): self.data =data self.successor = [] #generate a Graph def petersenGraph(): v = [Vertex(i) for i in xrange(10)] edges = \ [(0,1), (1,0), (1,2), (2,1), (2,3), (3,2), (3,4), (4,3), (4,0), (0,4), (5,6), (6,5), (6,7), (7,6), (7,8), (8,7), (8,9), (9,8), (9,5), (5,9), (5,0), (0,5), (6,2), (2,6), (7,4), (4,7), (8,1), (1,8), (9,3), (3,9)] for a, b in edges: v[a].successor.append(v[b]) return v def dfs(start, isGoal, result): if start in result: return False result.append(start) if isGoal(start):#reach the target item return True for s in start.successor: if dfs(s, isGoal, result): return True #NO path was found result.pop() return False def main(): v = petersenGraph() for vertex in v: print vertex.data print [item.data for item in vertex.successor] print "*"*20 path = [] if dfs(v[0], (lambda v: v.data ==7), path): print "Found path", [u.data for u in path] else: print "No path found" if __name__=="__main__": main()
[ "andytang1994@gmail.com" ]
andytang1994@gmail.com
0f69064cc124c90fd91b36b89f7ef3e0045c1c86
536ec8e275d0e4ac826ed492a818802f17eb29da
/other/diverta20192/b.py
a1dda6c0b38d2f1cf3ff5d45c0772170667c90dd
[]
no_license
tamanyan/coding-problems
3d74ee708a943348ee06f1a25c45ee3a35cfd9ee
415e8230c8386163e1abf5eea217a1e5be8a15bc
refs/heads/master
2020-07-03T21:36:23.566534
2020-06-10T16:33:55
2020-06-10T16:33:55
202,057,698
0
0
null
null
null
null
UTF-8
Python
false
false
1,924
py
from heapq import heappush, heappop, heapify from collections import deque, defaultdict, Counter import itertools from itertools import permutations, combinations, accumulate import sys import bisect import string import math import time def I(): return int(input()) def MI(): return map(int, input().split()) def S(): return input() def MS(): return map(str, input().split()) def LI(): return [int(i) for i in input().split()] def LI_(): return [int(i)-1 for i in input().split()] def StoI(): return [ord(i)-97 for i in input()] def ItoS(nn): return chr(nn+97) def input(): return sys.stdin.readline().rstrip() def show(*inp, end='\n'): if show_flg: print(*inp, end=end) def print_matrix(mat): for i in range(len(mat)): print(*mat[i]) YNL = {False: 'No', True: 'Yes'} YNU = {False: 'NO', True: 'YES'} MOD = 10**9+7 inf = float('inf') IINF = 10**19 l_alp = string.ascii_lowercase u_alp = string.ascii_uppercase ts = time.time() # sys.setrecursionlimit(10**6) nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] # show_flg = True show_flg = False def cost(x, y, initial, N): a = x[initial] b = y[initial] for i in range(N): if i == initial: continue return 0 def main(): N = I() x = [0] * N y = [0] * N ans = 0 dist = [[None] * N for i in range(N)] if N == 1: print(1) return for i in range(N): x[i], y[i] = MI() for i in range(N): for j in range(N): if i == j: continue dist[i][j] = str(x[j] - x[i]) + "," + str(y[j] - y[i]) # print_matrix(dist) c = defaultdict(int) ans = 1 for i in range(N): for j in range(N): if dist[i][j] == None: continue c[dist[i][j]] += 1 mcost = max(c.values()) print(N - mcost) if __name__ == '__main__': main()
[ "tamanyan.sss@gmail.com" ]
tamanyan.sss@gmail.com
94e635241a858c40290e54fa2adf9b57550f8043
70fbcca27b1bf777db40319a025ef1c752e2e11d
/ecmo/sockets.py
34f0deb09632354e978675865e277b199f5c9823
[]
no_license
thecaffiend/ecmo_data_viz
051297ddac642a5f0dbae1ef006158c677aca947
8f80e4070377f173f1883062dac776339f170aa9
refs/heads/master
2021-01-01T18:18:14.818933
2011-08-04T03:00:07
2011-08-04T03:00:07
2,093,412
1
1
null
null
null
null
UTF-8
Python
false
false
5,379
py
from django_websocket import require_websocket from django.utils import simplejson from django.core.cache import cache import math import time from copy import deepcopy from ecmo.models import * import sys def jsjson(msg): return simplejson.dumps(msg, ensure_ascii=True) @require_websocket def screen_socket(request, screen_name, run_id): """ The main end user socket. Doesn't really accept anything. """ run = Run.objects.get(id=run_id) screen = Screen.objects.get(js_name=screen_name) ws = request.websocket ss_base, point_ss_map = screen.struct_base_map() last_sent = None while True: points = cache.get(run.raw_points_key) if points and points.get('points',False) and points['run_time'] != last_sent: run_time = points['run_time'] screen_struct = deepcopy(ss_base) for p in points['points']: p_map = point_ss_map[p['feed']] screen_struct[p_map[0]][p_map[1]].append([run_time, p['val']]) jstruct = jsjson(screen_struct) ws.send(jstruct) last_sent = run_time time.sleep(.25) @require_websocket def mbc_command(request, run_id): """ The main MBC socket. Used for creating new (and deleting old) FeedEvents. Gives the current value. Accepts: { feed: <js_name>, value: <value or min or mean>, arg: <max or stddev>, run_time: <int>, distribution: one of EVT_DISTRIBUTIONS, trend: one of EVT_TRENDS } or { delete: <event_id>} Returns: {points: [{feed: <feed_name>, val:<float>}]} or {events: [<above struct, plus id>,]} """ run = Run.objects.get(id=run_id) ws = request.websocket last_sent = None while True: points = cache.get(run.raw_points_key) if points and points['points'] and points['run_time'] != last_sent: ws.send(jsjson({'points':points['points']})) last_sent = points['run_time'] if ws.has_messages(): msg = ws.read() msg = simplejson.loads(msg) if msg.get('shutdown', False): return if msg.get('delete', False): try: FeedEvent.objects.get(id=msg['delete']).delete() ws.send(jsjson(msg)) except: sys.stderr.write("bad delete %s" % e) if msg.get('feed', False): for feed in run.feed_set.all(): if feed.feed_type.js_name == msg['feed']: msg['feed'] = feed try: event = FeedEvent(**msg) event.full_clean() event.save() ws.send(jsjson({'events':[event.msg]})) except Exception, e: sys.stderr.write("bad insert %s" % e) time.sleep(.25) # DRY would put this in a JSON file that python can use, too CLK_RESUME = 0 CLK_SET = 1 CLK_PAUSE = 2 @require_websocket def mbc_clock(request, run_id): """ Handles the magic of the clock as best as possible... there is some drift, but it's good enough for demo purposes. Expects: {type: CLK_RESUME|CLK_PAUSE} or {type: CLK_SET, run_time: <int>} Returns: {run_time: <int>} """ run = Run.objects.get(id=run_id) ws = request.websocket def msg_time(): ws.send(jsjson({'run_time':run.run_time})) run.save() # iterator will run forever until client disconnects for msg in ws: interrupted = False msg = simplejson.loads(msg) if msg.get('shutdown', False): return if msg['type'] == CLK_RESUME: # initialize wake time for outer loop wake_time = time.time() while not interrupted: if ws.has_messages(): # on pause or set, special stuff interrupt = simplejson.loads(ws.read()) if interrupt.get('shutdown', False): return if interrupt["type"] == CLK_PAUSE: msg_time() # sends back to outer loop interrupted = True break elif interrupt["type"] == CLK_SET: # just updated the time run.run_time = interrupt['run_time'] else: run.run_time += 1 msg_time() # generates all the new points points = run.update_feeds() # send this up so other listeners can hear cache.set(run.raw_points_key, {'run_time': run.run_time, 'points': [p.msg for p in points]}) sleep_time = time.time() # attempt to counter drift time.sleep(1 - (sleep_time - wake_time)) wake_time = time.time() elif msg['type'] == CLK_SET: run.run_time = msg['run_time'] msg_time()
[ "nick.bollweg@gmail.com" ]
nick.bollweg@gmail.com
6d59e0b17594d456e339941c2951d033580722a3
ac5e52a3fc52dde58d208746cddabef2e378119e
/exps-gsn-edf.0/gsn-edf_ut=3.5_rd=0.8_rw=0.06_rn=4_u=0.075-0.325_p=harmonic-2/sched=RUN_trial=7/params.py
d1044ead6dd845269e7675cbd1da27353c9e2499
[]
no_license
ricardobtxr/experiment-scripts
1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1
7bcebff7ac2f2822423f211f1162cd017a18babb
refs/heads/master
2023-04-09T02:37:41.466794
2021-04-25T03:27:16
2021-04-25T03:27:16
358,926,457
0
0
null
null
null
null
UTF-8
Python
false
false
253
py
{'cpus': 4, 'duration': 30, 'final_util': '3.611238', 'max_util': '3.5', 'periods': 'harmonic-2', 'release_master': False, 'res_distr': '0.8', 'res_nmb': '4', 'res_weight': '0.06', 'scheduler': 'GSN-EDF', 'trial': 7, 'utils': 'uni-medium-3'}
[ "ricardo.btxr@gmail.com" ]
ricardo.btxr@gmail.com
23aebddeccd15771fc92e83af3e8ccd3ce23cc3f
b8d89bd2b0a4464146b349c6702d13caf776127b
/resticus/parsers.py
8ea5511ef0391e77c7ce9628f8939f579708a74c
[ "MIT" ]
permissive
ssteinerx/django-resticus
7683d20dbf30fe68f5c5ab04219d40f6b8f4627b
772a89d7bbe3ae72b2551f2dd5b823405460ddf8
refs/heads/develop
2020-12-24T06:44:54.998362
2016-11-11T14:17:39
2016-11-11T14:17:39
73,331,769
0
0
null
2016-11-10T00:06:54
2016-11-10T00:06:54
null
UTF-8
Python
false
false
823
py
from django.utils.translation import ugettext as _ from .exceptions import ParseError from .settings import api_settings def parse_content_type(content_type): if ';' in content_type: content_type, params = content_type.split(';', 1) try: params = dict(param.split('=') for param in params.split()) except Exception: params = {} else: params = {} return content_type, params def parse_json(request, **extra): charset = extra.get('charset', 'utf-8') try: data = request.body.decode(charset) return api_settings.JSON_DECODER().decode(data) except Exception: raise ParseError() def parse_post(request, **extra): return dict(request.POST.items()) def parse_plain_text(request, **extra): return request.body
[ "derek.payton@gmail.com" ]
derek.payton@gmail.com
4337257b1cc102097378401dabda4458d298a225
250e692078234b0e3ef22ad20ab7168f807d1d5f
/plus_minus.py
65eeef59116a3bb9fbe1461fbf5552b207e0c437
[]
no_license
AnTznimalz/python_prepro
694338609985971c5e6eaf8ec463c2a5c62dd836
bdc1e49fa03704bebcf2ab69a4c1600e4cd46a74
refs/heads/master
2022-06-22T23:47:28.396580
2020-05-07T15:07:56
2020-05-07T15:07:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
422
py
""" Plus Minus """ def ratio(): """ Func. ratio for calculate ratio of the given array """ num = int(input()) msg = input().split() pos = 0 zero = 0 neg = 0 for i in msg: if int(i) > 0: pos += 1 elif int(i) == 0: zero += 1 else: neg += 1 print("%.6f" %(pos/num)) print("%.6f" %(neg/num)) print("%.6f" %(zero/num)) ratio()
[ "thuchpunapivitcholachat@gmail.com" ]
thuchpunapivitcholachat@gmail.com
422e9f9d1e84b4d2346b968275d55ea920cf8315
85a0ee08b54b2c5e3154e3727b92c37915b4c1de
/test/TT/Strategy7.py
95b8bc12608c042b3536a3d8cca7e4019aa3e6fd
[]
no_license
yaotony/sandbox-empty
877da9b9ba0ec658bbdc8acc79a97267f96408b9
85f04e5db5d26a04fad9ae4ad6d3c86977a9f865
refs/heads/master
2022-05-20T17:14:51.348759
2022-05-04T08:06:56
2022-05-04T08:06:56
35,472,699
0
0
null
null
null
null
UTF-8
Python
false
false
1,569
py
import math import numpy as np def BoxTheory(df,N,S): df['BoxTop'] = 0 df['BoxDown'] = 0 df['BoxTopN'] = 0 df['BoxDownN'] = 0 df['BoxTopD'] = 0 df['BoxDownD'] = 0 #Box 交易訊號欄 df['BoxTopD'] = df['high'].iloc[:].rolling(N).max() df['BoxDownD'] = df['low'].iloc[:].rolling(N).min() df['BoxTopN'] = df['high'].iloc[:].shift(1+N).rolling(N).max() df['BoxDownN'] = df['low'].iloc[:].shift(1+N).rolling(N).min() topV = 0 DownV = 0 boxIndex =0 BoxIndexOrder=0 boxIndexTop =0 boxIndexDown =0 boxIndexBL = 0 BoxTop = 0 BoxDown = 0 BoxTopAr = [] BoxDownAr = [] for i in range( len(df)): BoxTopD = df['BoxTopD'].iloc[i] BoxTopN = df['BoxTopN'].iloc[i] BoxDownD = df['BoxDownD'].iloc[i] BoxDownN = df['BoxDownN'].iloc[i] if BoxTopD < BoxTopN : BoxTop = BoxTopN boxIndexTop = BoxTop else : BoxTop = boxIndexTop if BoxDownD > BoxDownN : BoxDown = BoxDownN boxIndexDown = BoxDownN else : BoxDown = boxIndexDown if BoxTop == 0 : BoxTop = BoxTopD if BoxDown == 0 : BoxDown = BoxDownD BoxTopAr.append(BoxTop) BoxDownAr.append(BoxDown) df['BoxTop'] = BoxTopAr df['BoxDown'] = BoxDownAr return df
[ "tony.exmail@gmail.com" ]
tony.exmail@gmail.com
416d9a1dc7d09ded0fbe07e5a5ca26b458661b4c
6f05f7d5a67b6bb87956a22b988067ec772ba966
/data/train/python/0fee3ef0355224294ed245f863279f4c010e2ae7urls.py
0fee3ef0355224294ed245f863279f4c010e2ae7
[ "MIT" ]
permissive
harshp8l/deep-learning-lang-detection
93b6d24a38081597c610ecf9b1f3b92c7d669be5
2a54293181c1c2b1a2b840ddee4d4d80177efb33
refs/heads/master
2020-04-07T18:07:00.697994
2018-11-29T23:21:23
2018-11-29T23:21:23
158,597,498
0
0
MIT
2018-11-21T19:36:42
2018-11-21T19:36:41
null
UTF-8
Python
false
false
654
py
from django.conf.urls.defaults import * import views from tastypie.api import Api from wdd.api import * api = Api(api_name='v1') api.register(EntryResource()) api.register(RoomResource()) api.register(UserResource()) urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^chat/rooms/$', views.RoomList.as_view(), name='room-list'), url(r'^chat/rooms/(?P<pk>\d+)/$', views.RoomDetail.as_view(), name='room-detail'), url(r'^chat/(?P<room>[\w.]+).(?P<mimetype>(json)|(html))$', views.chat, name = 'chat'), #(r'^api/', include(api.urls)), )
[ "aliostad+github@gmail.com" ]
aliostad+github@gmail.com
c9b044f351ab64212748338576bcbb175ceb4044
c2fa3b814a7f56ad804dffc767fc54f5099d60f8
/models/structs/snakes_400/mu_context_time.py
db61ba172954e8df0734bdef3f116521d2e2303a
[]
no_license
dmely/contextual_circuit_bp
223b602dbabbe8f8091fbb9106f3103bd5e1dcba
a277bc3146beaa4e3edd2134fc9fb8d3388a6013
refs/heads/master
2021-10-07T19:04:14.509951
2018-03-31T17:10:33
2018-03-31T17:10:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,355
py
"""2D convolutional model for Allen data.""" layer_structure = [ { # 'layers': ['alexnet_conv'], # 'alexnet_npy': '/media/data_cifs/clicktionary/pretrained_weights/gabors_for_contours_7.npy', # 'alexnet_layer': 's1', # 'trainable': True, # 'init_bias': True, 'layers': ['conv'], 'names': ['conv1'], 'stride': [1, 2, 2, 1], 'weights': [8], 'filter_size': [7], 'hardcoded_erfs': { 'SRF': 6, 'CRF_excitation': 6, 'CRF_inhibition': 6, 'SSN': [10, 10, 10], # [5, 5, 5], # [11, 11, 11], 'SSF': [10, 10, 10], # [5, 5, 5], # [11, 11, 11] # 30 # 'SSN': [5, 5, 5, 5, 5], # Vanilla VGG-style # 'SSF': [5, 5, 5, 5, 5], # Vanilla VGG-style # 'SSF': [8, 8, 8, 3] # 'SSN': [6, 6, 6], # Atrous VGG-style # 'SSF': [6, 6, 6] }, 'normalization': ['contextual_single_ecrf_time'], 'normalization_target': ['post'], 'normalization_aux': { 'timesteps': 5, 'xi': False, # If FF drive is not trainable 'rectify_weights': True, 'pre_batchnorm': True, 'post_batchnorm': False, # 'dense_connections': True, # 'batch_norm': True, 'atrous_convolutions': False, 'association_field': True, 'multiplicative_excitation': False, 'gru_gates': False, 'trainable': True, 'regularization_targets': { # Modulate sparsity 'q_t': { 'regularization_type': 'l1', # 'orthogonal', 'regularization_strength': 1e-7 # 1e-5 # 0.01 }, 'p_t': { 'regularization_type': 'l1', # 'laplace', # 'orthogonal', 'regularization_strength': 1e-7 # 1e-5 # 1. }, } } }, # { # 'layers': ['global_pool'], # 'weights': [None], # 'names': ['pool2'], # # 'activation': ['relu'], # # 'activation_target': ['post'] # } ] output_structure = [ { 'flatten': [True], 'flatten_target': ['pre'], 'layers': ['fc'], 'weights': [2], 'names': ['fc2'], } ]
[ "drewlinsley@gmail.com" ]
drewlinsley@gmail.com
a29ae03ae7a520b7baa848f815ccbd35b19898db
9df795e57589a99838199f97945e96811e288e75
/W174.py
7c8477888852a7017a676af9a8e81382b0220935
[]
no_license
JakeAttard/2810ICTPythonExercises
945783908a6bf981fc8128a5fc0b4bda6fd52eea
199cc42402a5cf4d8b86060af377d3906af00429
refs/heads/master
2020-06-17T19:07:46.788283
2019-07-16T11:22:15
2019-07-16T11:22:15
196,018,674
0
0
null
null
null
null
UTF-8
Python
false
false
483
py
from PyTest import * ##//////////////////////////// PROBLEM STATEMENT /////////////////////////// ## Given a number n, write while and for loops that add up the numbers in // ## the series 1,2,3,4,..., n-2, n-1, n and display the resultant sum. The // ## number n will be input by the user of the algorithm. // ## 10 -> 55 55 // ##//////////////////////////////////////////////////////////////////////////
[ "jakeattard18@gmail.com" ]
jakeattard18@gmail.com
d1790f748dc1ee5ef4f3bd93c1d0df251d24eeda
dfb53581b4e6dbdc8e3789ea2678de1e1c4b5962
/AI/Machine_Learning/Day02/demo03_save.py
a89925c6b46c5a5bdc001dc176b456aa68c53a86
[]
no_license
biabulinxi/Python-ML-DL
7eff6d6898d72f00575045c5aa2acac45b4b0b82
217d594a3c0cba1e52550f74d100cc5023fb415b
refs/heads/master
2020-06-01T09:13:17.314121
2019-06-08T03:59:36
2019-06-08T03:59:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,518
py
# -*- coding: utf-8 -*- # @Project:AID1810 # @Author:biabu # @Date:2019/3/26 14:12 # @File_name:demo03_save.py # @IDE:PyCharm """ 模型保存 """ import pickle import pandas as pd import numpy as np import sklearn.linear_model as lm import matplotlib.pyplot as plt import sklearn.metrics as sm x, y = np.loadtxt('../ml_data/single.txt',delimiter=',',usecols=(0,1), unpack=True) x = x.reshape(-1, 1) # x变为n行1列 # 创建训练模型 model = lm.LinearRegression() model.fit(x, y) # 保存模型 with open('../ml_data/linear.pkl','wb') as f: pickle.dump(model, f) print('Save Success!') pred_y = model.predict(x) ##################################################### # 评估模型的误差 # 平均绝对值误差:1/m*∑|实际输出-预测输出| print(sm.mean_absolute_error(y,pred_y)) # 平均平方误差:sqrt(1/m*∑(实际输出-预测输出)^2) print(sm.mean_squared_error(y, pred_y)) # 中位数绝对值误差: median(|实际输出-预测输出|) print(sm.median_absolute_error(y, pred_y)) # R2得分 (0, 1]区间上的分值,分数越高,模型越好, 误差越小 print(sm.r2_score(y,pred_y)) plt.figure('Linear Regression', facecolor='lightgray') plt.title('Linear Regression', fontsize=14) plt.xlabel('x', fontsize=12) plt.ylabel('y', fontsize=12) plt.tick_params(labelsize=10) plt.grid(linestyle=":") plt.scatter(x, y, c='dodgerblue', alpha=0.5,s=60, label='Sample Points') plt.plot(x, pred_y, c='orangered',linewidth=2,label='Regression Line') plt.legend() plt.show()
[ "biabu1208@163.com" ]
biabu1208@163.com
c3bd9b7c3ecbdb2de5e7f3c78ae57b2ded1ebef1
dccdfc0b58b24035c614a2fcd3efcc6a88cfa51d
/setup.py
9bf155862a113c7bb84c77fe5c8f87e0b5ae8380
[ "MIT" ]
permissive
igorsobreira/django-test-extensions
203bbb19ccb285a7e816b2b225adc11b89bc8107
d57313401d6964ad0102ad1c584a7b848ba76615
refs/heads/master
2021-01-16T21:02:34.784060
2011-03-12T02:56:16
2011-03-12T02:56:16
1,470,571
1
0
null
null
null
null
UTF-8
Python
false
false
823
py
from setuptools import setup, find_packages setup( name = "django-test-extensions", version = "0.9", author = "Gareth Rushgrove", author_email = "gareth@morethanseven.net", url = "http://github.com/garethr/django-test-extensions/", packages = find_packages('src'), package_dir = {'':'src'}, license = "MIT License", keywords = "django testing", description = "A few classes to make testing django applications easier", install_requires=[ 'setuptools', 'BeautifulSoup', 'coverage', ], classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Testing', ] )
[ "gareth@morethanseven.net" ]
gareth@morethanseven.net
cf969a758c84028af52f86848a1607da7e7e5a80
e86fd9f61a41731deb9d56e1107db04de41b6789
/beebeeto/poc_2015_0077.py
96f303abff8c84e77d24cf76f202c39562561b7a
[]
no_license
c0py7hat/POC-EXP
f58e0f1df41e1905e5fdc72b019f8125aac48799
7ddf2790012efb7fb5bd258ddcd1e1c25f0cf201
refs/heads/master
2020-04-30T07:05:31.390537
2019-03-20T08:38:50
2019-03-20T08:38:50
176,674,030
3
2
null
2019-03-20T08:09:56
2019-03-20T07:00:45
Python
UTF-8
Python
false
false
3,536
py
#!/usr/bin/env python # coding=utf-8 """ Site: http://www.beebeeto.com/ Framework: https://github.com/n0tr00t/Beebeeto-framework """ import socket import urllib2 from baseframe import BaseFrame class MyPoc(BaseFrame): poc_info = { # poc相关信息 'poc': { 'id': 'poc-2015-0077', 'name': 'w3tw0rk / Pitbull Perl IRC Bot 远程代码执行漏洞 Exploit', 'author': 'foundu', 'create_date': '2015-04-07', }, # 协议相关信息 'protocol': { 'name': 'http', 'port': [6667], 'layer4_protocol': ['tcp'], }, # 漏洞相关信息 'vul': { 'app_name': 'w3tw0rk / Pitbull Perl IRC', 'vul_version': ['*'], 'type': 'Code Execution', 'tag': ['w3tw0rk / Pitbull Perl IRC Bot 漏洞', 'w3tw0rk / Pitbull Perl IRC Bot Vulnerability'], 'desc': ''' pitbull-w3tw0rk_hunter is POC exploit for Pitbull or w3tw0rk IRC Bot that takes over the owner of a bot which then allows Remote Code Execution. ''', 'references': ['http://www.exploit-db.com/exploits/36652/', ], }, } def _init_user_parser(self): # 定制命令行参数 self.user_parser.add_option('-c','--channel', action='store', dest='channel', type='string', default=None, help='IRC channel') self.user_parser.add_option('-n','--nick', action='store', dest='nick', type='string', default='beebeeto', help='IRC nick') @classmethod def verify(cls, args): #irc server connection settings server = args['options']['target'] # IRC Server botnick = args['options']['nick'] # admin payload for taking over the w3wt0rk bot channel = "#%s"%args['options']['channel'] #channel where the bot is located irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print "connecting to: " + server irc.connect((server, 6667)) #connects to the server irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :I eat w3tw0rk bots!\n") #user authentication irc.send("NICK "+ botnick +"\n") #sets nick irc.send("JOIN "+ channel +"\n") #join the chan irc.send("PRIVMSG "+channel+" :!bot @system 'uname -a' \n") #send the payload to the bot #puts it in a loop while True: text = irc.recv(2040) print text #print text to console if text.find('PING') != -1: #check if 'PING' is found irc.send('PONG ' + text.split() [1] + '\r\n') #returnes 'PONG' back to the server (prevents pinging out!) if text.find('!quit') != -1: #quit the Bot irc.send ("QUIT\r\n") return args if text.find('Linux') != -1: irc.send("PRIVMSG "+channel+" :The bot answers to "+botnick+" which allows command execution \r\n") irc.send ("QUIT\r\n") args['success'] = True return args return args exploit = verify if __name__ == '__main__': from pprint import pprint mp = MyPoc() pprint(mp.run())
[ "noreply@github.com" ]
c0py7hat.noreply@github.com
79770caee3376d14b2ae8c0350f4fcd214826bdb
9a78b2fafd64e200f844a2f6f0deb034ffc96c8d
/rentapps/migrations/0001_initial.py
ace5c693acfd27f917134ddf7e9617354dd36024
[]
no_license
gabrielcoder247/property
8ba29ae443e03f60a39d73b97cd4b0f9e5fea9c4
5620ad7220e2f90d7d95ec711ed3caace4823291
refs/heads/master
2020-06-19T05:16:13.632824
2019-07-17T18:35:06
2019-07-17T18:35:06
196,574,085
0
0
null
null
null
null
UTF-8
Python
false
false
2,493
py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-07-12 12:37 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Billing', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('firstname', models.CharField(max_length=30, null=True)), ('lastname', models.CharField(max_length=30, null=True)), ('email', models.EmailField(max_length=254, null=True, unique=True)), ('state', models.CharField(max_length=100, null=True)), ('country', models.CharField(max_length=100, null=True)), ('postal_code', models.CharField(max_length=20, null=True)), ('pub_date', models.DateField(auto_now_add=True, null=True)), ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pub_date', models.DateField(auto_now_add=True)), ('username', models.CharField(max_length=30, null=True)), ('email', models.EmailField(max_length=254, null=True, unique=True)), ('fname', models.CharField(max_length=30, null=True)), ('lname', models.CharField(max_length=30, null=True)), ('location', models.CharField(max_length=50, null=True)), ('occupation', models.CharField(max_length=60, null=True)), ('org_name', models.CharField(max_length=60, null=True)), ('phone_num', models.CharField(max_length=30, null=True)), ('profile_photo', models.ImageField(upload_to='profile/')), ('bio', models.TextField(max_length=255, null=True)), ('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='signup', to=settings.AUTH_USER_MODEL)), ], ), ]
[ "gabrielcoder247@gmail.com" ]
gabrielcoder247@gmail.com
59f25ff70be224b12e6cf04bfee0dce4295358cb
223590e81400eb8192aeb0a56b36b5a80408d4b4
/untitled0.py
5d8197e9f495e56c5efd0c87cbde3b294eba5703
[]
no_license
TianyaoHua/LeetCodeSolutions
c47fd3b6ae0bf60c0656ce12fb88290672c129ed
418172cee1bf48bb2aed3b84fe8b4defd9ef4fdf
refs/heads/master
2020-03-06T19:48:13.338630
2018-08-10T18:27:52
2018-08-10T18:27:52
127,037,907
0
0
null
null
null
null
UTF-8
Python
false
false
936
py
# -*- coding: utf-8 -*- """ Created on Sun Feb 25 16:57:27 2018 @author: Hua Tianyao """ class Solution(object): def dfs(self, color, nums, i, n): next_index = (i + nums[i]) % n if color[next_index] == 1: color[i] = 2 return True elif next_index != i and color[next_index] == 0: color[i] = 1 answer = self.dfs(color, nums, next_index, n) color[i] = 2 return answer else: color[i] = 2 return False def circularArrayLoop(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) color = [0 for i in range(n)] i = 0 while i < n: if color[i] == 0: if self.dfs(color,nums,i,n): return True i += 1 return False print(Solution().circularArrayLoop([1,2,3,4,5]))
[ "hua.tianyao@columbia.edu" ]
hua.tianyao@columbia.edu
c6dac6d64165754472f17a77ad466a0ca0279b6e
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/last_thing/good_week_and_person/own_eye_and_person/part_and_big_point/problem/problem_or_case.py
20ae2bf35ce4c8e25534587be86a80ec979d2b7a
[]
no_license
JingkaiTang/github-play
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
51b550425a91a97480714fe9bc63cb5112f6f729
refs/heads/master
2021-01-20T20:18:21.249162
2016-08-19T07:20:12
2016-08-19T07:20:12
60,834,519
0
0
null
null
null
null
UTF-8
Python
false
false
214
py
#! /usr/bin/env python def next_person(str_arg): public_week(str_arg) print('own_fact') def public_week(str_arg): print(str_arg) if __name__ == '__main__': next_person('do_good_day_after_case')
[ "jingkaitang@gmail.com" ]
jingkaitang@gmail.com
9682453679a05e8d64bd30fb27ba145b36d956f7
78c3082e9082b5b50435805723ae00a58ca88e30
/03.AI알고리즘 소스코드/venv/Lib/site-packages/caffe2/python/data_workers_test.py
81fa0f865d93340abf4508206c0454608bf2f22e
[]
no_license
jinStar-kimmy/algorithm
26c1bc456d5319578110f3d56f8bd19122356603
59ae8afd8d133f59a6b8d8cee76790fd9dfe1ff7
refs/heads/master
2023-08-28T13:16:45.690232
2021-10-20T08:23:46
2021-10-20T08:23:46
419,217,105
0
1
null
null
null
null
UTF-8
Python
false
false
6,757
py
import numpy as np import unittest import time from caffe2.python import workspace, model_helper from caffe2.python import timeout_guard import caffe2.python.data_workers as data_workers def dummy_fetcher(fetcher_id, batch_size): # Create random amount of values n = np.random.randint(64) + 1 data = np.zeros((n, 3)) labels = [] for j in range(n): data[j, :] *= (j + fetcher_id) labels.append(data[j, 0]) return [np.array(data), np.array(labels)] def dummy_fetcher_rnn(fetcher_id, batch_size): # Hardcoding some input blobs T = 20 N = batch_size D = 33 data = np.random.rand(T, N, D) label = np.random.randint(N, size=(T, N)) seq_lengths = np.random.randint(N, size=(N)) return [data, label, seq_lengths] class DataWorkersTest(unittest.TestCase): def testNonParallelModel(self): workspace.ResetWorkspace() model = model_helper.ModelHelper(name="test") old_seq_id = data_workers.global_coordinator._fetcher_id_seq coordinator = data_workers.init_data_input_workers( model, ["data", "label"], dummy_fetcher, 32, 2, input_source_name="unittest" ) new_seq_id = data_workers.global_coordinator._fetcher_id_seq self.assertEqual(new_seq_id, old_seq_id + 2) coordinator.start() workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) for _i in range(500): with timeout_guard.CompleteInTimeOrDie(5): workspace.RunNet(model.net.Proto().name) data = workspace.FetchBlob("data") labels = workspace.FetchBlob("label") self.assertEqual(data.shape[0], labels.shape[0]) self.assertEqual(data.shape[0], 32) for j in range(32): self.assertEqual(labels[j], data[j, 0]) self.assertEqual(labels[j], data[j, 1]) self.assertEqual(labels[j], data[j, 2]) coordinator.stop_coordinator("unittest") self.assertEqual(coordinator._coordinators, []) def testRNNInput(self): workspace.ResetWorkspace() model = model_helper.ModelHelper(name="rnn_test") old_seq_id = data_workers.global_coordinator._fetcher_id_seq coordinator = data_workers.init_data_input_workers( model, ["data1", "label1", "seq_lengths1"], dummy_fetcher_rnn, 32, 2, dont_rebatch=False, batch_columns=[1, 1, 0], ) new_seq_id = data_workers.global_coordinator._fetcher_id_seq self.assertEqual(new_seq_id, old_seq_id + 2) coordinator.start() workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) while coordinator._coordinators[0]._state._inputs < 100: time.sleep(0.01) # Run a couple of rounds workspace.RunNet(model.net.Proto().name) workspace.RunNet(model.net.Proto().name) # Wait for the enqueue thread to get blocked time.sleep(0.2) # We don't dequeue on caffe2 side (as we don't run the net) # so the enqueue thread should be blocked. # Let's now shutdown and see it succeeds. self.assertTrue(coordinator.stop()) @unittest.skip("Test is flaky: https://github.com/pytorch/pytorch/issues/9064") def testInputOrder(self): # # Create two models (train and validation) with same input blobs # names and ensure that both will get the data in correct order # workspace.ResetWorkspace() self.counters = {0: 0, 1: 1} def dummy_fetcher_rnn_ordered1(fetcher_id, batch_size): # Hardcoding some input blobs T = 20 N = batch_size D = 33 data = np.zeros((T, N, D)) data[0][0][0] = self.counters[fetcher_id] label = np.random.randint(N, size=(T, N)) label[0][0] = self.counters[fetcher_id] seq_lengths = np.random.randint(N, size=(N)) seq_lengths[0] = self.counters[fetcher_id] self.counters[fetcher_id] += 1 return [data, label, seq_lengths] workspace.ResetWorkspace() model = model_helper.ModelHelper(name="rnn_test_order") coordinator = data_workers.init_data_input_workers( model, input_blob_names=["data2", "label2", "seq_lengths2"], fetch_fun=dummy_fetcher_rnn_ordered1, batch_size=32, max_buffered_batches=1000, num_worker_threads=1, dont_rebatch=True, input_source_name='train' ) coordinator.start() val_model = model_helper.ModelHelper(name="rnn_test_order_val") coordinator1 = data_workers.init_data_input_workers( val_model, input_blob_names=["data2", "label2", "seq_lengths2"], fetch_fun=dummy_fetcher_rnn_ordered1, batch_size=32, max_buffered_batches=1000, num_worker_threads=1, dont_rebatch=True, input_source_name='val' ) coordinator1.start() workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) workspace.CreateNet(val_model.net) while coordinator._coordinators[0]._state._inputs < 900: time.sleep(0.01) with timeout_guard.CompleteInTimeOrDie(5): for m in (model, val_model): print(m.net.Proto().name) workspace.RunNet(m.net.Proto().name) last_data = workspace.FetchBlob('data2')[0][0][0] last_lab = workspace.FetchBlob('label2')[0][0] last_seq = workspace.FetchBlob('seq_lengths2')[0] # Run few rounds for _i in range(10): workspace.RunNet(m.net.Proto().name) data = workspace.FetchBlob('data2')[0][0][0] lab = workspace.FetchBlob('label2')[0][0] seq = workspace.FetchBlob('seq_lengths2')[0] self.assertEqual(data, last_data + 1) self.assertEqual(lab, last_lab + 1) self.assertEqual(seq, last_seq + 1) last_data = data last_lab = lab last_seq = seq time.sleep(0.2) self.assertTrue(coordinator.stop())
[ "gudwls3126@gmail.com" ]
gudwls3126@gmail.com
4862104a0fb2371de05ff5051d73fe8321f166a0
6ac0bba8c1851e71529269c0d9d89a7c8fa507f2
/Easy/26.py
0915536721dec4fcf77cccd8a1e6caa20567b01f
[]
no_license
Hellofafar/Leetcode
e81dc85689cd6f9e6e9756beba070cb11e7b192e
7a459e9742958e63be8886874904e5ab2489411a
refs/heads/master
2021-05-16T07:07:19.823953
2020-02-17T03:00:09
2020-02-17T03:00:09
103,690,780
6
0
null
null
null
null
UTF-8
Python
false
false
1,944
py
# ------------------------------ # 26. Remove Duplicates from Sorted Array # # Description: # Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. # Do not allocate extra space for another array, you must do this in place with constant memory. # # For example, # Given input array nums = [1,1,2], # # Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. # # Version: 1.0 # 09/17/17 by Jianfa # ------------------------------ class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 else: nums_len = len(nums) i = 0 check = nums[0] - 1 while i < nums_len: if check != nums[i]: check = nums[i] i += 1 else: nums.pop(i) nums_len -= 1 return len(nums) # Used for test if __name__ == "__main__": test = Solution() nums = [1,1,1,2,3,4,4,4,4] print(test.removeDuplicates(nums)) # ------------------------------ # Good idea from other solution: # Actually there is no need to really remove value from the list. As the last sentence said # "It doesn't matter what you leave beyond the new length." So we can just modify the first several # numbers which is the length of unique values, but leave other values behind unchanged. We set two # runner: a fast runner and a slow runner. As long as a different value is met, modify the corresponding # value in position of slow runner, otherwise move the fast runner. # Here is a link for reference: # https://leetcode.com/problems/remove-duplicates-from-sorted-array/solution/
[ "buptljf@gmail.com" ]
buptljf@gmail.com
56d262b69962f3c5f4793a2e6e4dc4c0a775ee3f
f69fdcbc208045fc0b6f5f83231309d9ee473ff7
/src/kedja/models/auth.py
04af025f3ade3f27ecca593937be1b9770514b5d
[]
no_license
kedjaproject/kedja_server
d578266ad5e688dcbd21ceac8694ad60e4b1e72a
6df14d221c8ea247460e7f4600bf7fa860eb18de
refs/heads/master
2020-05-07T18:02:16.816912
2019-10-22T19:43:58
2019-10-22T19:43:58
180,751,037
0
1
null
null
null
null
UTF-8
Python
false
false
5,633
py
import json from random import choice from string import ascii_letters, digits from pyramid.authentication import CallbackAuthenticationPolicy from pyramid.authentication import extract_http_basic_credentials from pyramid.authorization import ACLAuthorizationPolicy from pyramid.interfaces import IAuthenticationPolicy from pyramid.interfaces import IDebugLogger from zope.component import adapter from zope.interface import implementer from kedja.models.credentials import get_valid_credentials from kedja.models.credentials import remove_credentials from kedja.models.credentials import Credentials from kedja.interfaces import IOneTimeAuthToken, IRoot from kedja.interfaces import IOneTimeRegistrationToken from kedja.utils import get_redis_conn @implementer(IAuthenticationPolicy) class HTTPHeaderAuthenticationPolicy(CallbackAuthenticationPolicy): """ An authentication policy that fetches authentication objects from the user profile. It will decode a basic HTTP header """ def __init__(self, callback=None, debug=False): self.callback = callback self.debug = debug def remember(self, request, userid, token=None, **kw): cred = Credentials(userid=userid, token=token, registry=request.registry) cred.save() return cred def forget(self, request): http_creds = extract_http_basic_credentials(request) if http_creds is not None: remove_credentials(http_creds.username, http_creds.password, registry=request.registry) def unauthenticated_userid(self, request): http_creds = extract_http_basic_credentials(request) if http_creds is None: self.debug and self._log( 'No HTTP Credentials received, so no auth. Will return None', 'authenticated_userid', request, ) return # username == userid, and password is the token for the actual credentials cred = get_valid_credentials(http_creds.username, http_creds.password, registry=request.registry) if cred is None: self.debug and self._log( "Credentials weren't valid, will return None", 'authenticated_userid', request, ) return else: self.debug and self._log( 'Valid credentials and user found, will return userid "%s" ' % cred.userid, 'authenticated_userid', request, ) return cred.userid def _log(self, msg, methodname, request): logger = request.registry.queryUtility(IDebugLogger) if logger: # pragma: no cover cls = self.__class__ classname = cls.__module__ + '.' + cls.__name__ methodname = classname + '.' + methodname logger.debug(methodname + ': ' + msg) @implementer(IOneTimeRegistrationToken) @adapter(IRoot) class OneTimeRegistrationToken(object): __doc__ = IOneTimeRegistrationToken.__doc__ prefix = 'otrt' def __init__(self, context: IRoot): self.context = context def get_key(self, token:str): return "{}.{}".format(self.prefix, token) def create(self, payload:dict, expires:int=1200, registry=None): token = _generate_token(length=70) conn = get_redis_conn(registry) key_name = self.get_key(token) conn.setex(key_name, expires, json.dumps(payload)) return token def consume(self, token:str, registry=None): key_name = self.get_key(token) conn = get_redis_conn(registry) payload = conn.get(key_name) if payload: payload = payload.decode() return json.loads(payload) def validate(self, token:str, registry=None): conn = get_redis_conn(registry) key_name = self.get_key(token) return bool(conn.exists(key_name)) @implementer(IOneTimeAuthToken) @adapter(IRoot) class OneTimeAuthToken(object): __doc__ = IOneTimeAuthToken.__doc__ prefix = 'otat' def __init__(self, context: IRoot): self.context = context def get_key(self, userid:str, token:str): return "{}.{}.{}".format(self.prefix, userid, token) def create(self, credentials, expires=30, registry=None): assert isinstance(credentials, Credentials) # Test one_time_token = _generate_token() key_name = self.get_key(credentials.userid, one_time_token) conn = get_redis_conn(registry) conn.setex(key_name, expires, credentials.token) return one_time_token def consume(self, userid:str, token:str, registry=None): key_name = self.get_key(userid, token) conn = get_redis_conn(registry) cred_token = conn.get(key_name) if cred_token: cred_token = cred_token.decode() return Credentials.load(userid, cred_token, registry) def validate(self, userid:str, token:str, registry=None): key_name = self.get_key(userid, token) conn = get_redis_conn(registry) return bool(conn.exists(key_name)) def _generate_token(length=30): out = "" for i in range(length): out += choice(ascii_letters + digits) return out def includeme(config): debug_authn = config.registry.settings.get('pyramid.debug_authorization', False) config.set_authorization_policy(ACLAuthorizationPolicy()) config.set_authentication_policy(HTTPHeaderAuthenticationPolicy(debug=debug_authn)) config.registry.registerAdapter(OneTimeRegistrationToken) config.registry.registerAdapter(OneTimeAuthToken)
[ "robin@betahaus.net" ]
robin@betahaus.net
0a07346dc2887b6524b57e969d9e6eae196467c4
9f5dce388b745c3e7354948a3b833812fb43f202
/storyscript/Features.py
5caefb0e1ed20853201f45714032a47017159eff
[ "Apache-2.0" ]
permissive
ramlaxman/storyscript
f9ba96ea85f50a85ade0083209c588acd1783c0a
274047c4cb4ed7ec301ce4a65f0fb8b98e595cc9
refs/heads/master
2023-04-14T14:59:04.036023
2019-10-01T19:30:03
2019-10-01T19:30:03
212,381,736
0
0
Apache-2.0
2023-04-04T01:23:50
2019-10-02T15:53:11
null
UTF-8
Python
false
false
819
py
# -*- coding: utf-8 -*- class Features: """ Configuration for compiler settings or features. """ defaults = { 'globals': False, # makes global variables writable 'debug': False, # enable debug output } def __init__(self, features): self.features = self.defaults.copy() if features is not None: for k, v in features.items(): assert k in self.defaults, f'{k} is in invalid feature option' self.features[k] = v def __str__(self): features = ','.join([f'{k}={v}' for k, v in self.features.items()]) return f'Features({features})' def __getattr__(self, attribute): return self.features[attribute] @classmethod def all_feature_names(cls): return cls.defaults.keys()
[ "seb@wilzba.ch" ]
seb@wilzba.ch
ec92634dfe091b522492d966ab421e420a73a01a
41dc19883789f45b6086399a1ae23995f53b4b2c
/IPython-parallel-tutorial/check_env.py
85c49fd4c3e695589de399a92b65d5ba442a02d9
[ "MIT" ]
permissive
sunny2309/scipy_conf_notebooks
f86179ddcd67168b709c755cc01862ed7c9ab2bd
30a85d5137db95e01461ad21519bc1bdf294044b
refs/heads/master
2022-10-28T17:27:42.717171
2021-01-25T02:24:05
2021-01-25T02:24:05
221,385,814
2
0
MIT
2022-10-20T02:55:20
2019-11-13T06:12:07
Jupyter Notebook
UTF-8
Python
false
false
707
py
"""check_env.py for IPython.parallel tutorial at SciPy 2014""" import sys import numpy import scipy import requests import matplotlib.pyplot import skimage import matplotlib try: from bs4 import BeautifulSoup except ImportError: print("BeautifulSoup will be used for an example.") try: import networkx except ImportError: print("networkx will be used for an example.") try: import cv except ImportError: print("opencv will be used for an example.") from distutils.version import LooseVersion as V import IPython if V(IPython.__version__) < V('2.0'): print("Need IPython >= 2.0, have %s" % IPython.__version__) sys.exit(1) from IPython import parallel print("OK")
[ "sunny.2309@yahoo.in" ]
sunny.2309@yahoo.in
48bc29bb081af5a16c80a9718cac5b56f870de00
e09930641fa513b821d99674fa0bef3023a7123c
/classification/data_conversion/convert.py
88e354213c1c3d02a8b1560e350ffbee6f19b71b
[]
no_license
abhilashdighe/loop-unroll-583
d7106f9d044b308e3cf778c40a8954becc47626e
9bbbac5b745fc0f33397e3813872ba22379a1ded
refs/heads/master
2021-01-21T09:18:05.299439
2016-03-17T20:22:15
2016-03-17T20:22:15
45,954,635
1
0
null
null
null
null
UTF-8
Python
false
false
2,462
py
import csv import sys from sklearn.cross_validation import train_test_split import cPickle as pickle loop_to_features = {} loop_to_timings = {} with open('features.csv') as features_file: features_csv = csv.reader(features_file) for sample in features_csv: benchmark , loopid = sample[:2] features = map(float , sample[2:]) loop_to_features[(benchmark,loopid)] = features with open('runtime.csv') as runtime_file: runtimes_csv = csv.reader(runtime_file) for sample in runtimes_csv: loopid , trip_count , unroll_factor , time = sample # print benchmark , loopid , trip_count , unroll_factor , time # time_per_trip = float(time) / float(trip_count) time=float(time) if loopid in loop_to_timings: if unroll_factor in loop_to_timings[loopid]: # print loop_to_timings[(benchmark,loopid)] (loop_to_timings[loopid])[unroll_factor].append(time) else: # print loop_to_timings[(benchmark,loopid)] (loop_to_timings[loopid])[unroll_factor] = [time] else: loop_to_timings[loopid] = {} loop_to_timings[loopid][unroll_factor] = [time,] loop_to_label = {} for loopid in loop_to_timings: best_factor = -1 best_time = sys.maxint for unroll_factor in loop_to_timings[loopid]: curr_timing_list = loop_to_timings[loopid][unroll_factor] curr_time = sum(curr_timing_list) / len(curr_timing_list) loop_to_timings[loopid][unroll_factor] = curr_time if curr_time < best_time: best_time = curr_time best_factor = unroll_factor loop_to_label[loopid] = best_factor X = [] y = [] with open('labelled_data.csv' , 'wb') as labelled_file: labelled_csv = csv.writer(labelled_file) for benchmark , loopid in loop_to_features: if loopid in loop_to_timings: features = loop_to_features[(benchmark,loopid)] X.append(features) label = loop_to_label[loopid] y.append(int(label)-1) features.append(label) labelled_csv.writerow(features) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42 , stratify=y) print y_train print y_test data = {} data['X_train'] = X_train data['X_test'] = X_test data['y_train'] = y_train data['y_test'] = y_test pickle.dump( data , open('split_data.p' , 'wb'))
[ "=" ]
=
1f4c7521cdae03be724f7fda5a14b675b3ac1ba9
fd0be9219fbc479548829289921907659dcfe18c
/src/k8s/my_pod.py
1f5944c99fb3eb7f8b0dc96f19499eb616fa57d1
[ "MIT" ]
permissive
latonaio/kube-etcd-sentinel
00f18c2dabada0211aff474afc25b1b79c4c53a9
bf8d1248ac9b13c30b4624867d8d4d17fa5ab06e
refs/heads/main
2022-12-19T16:58:28.196293
2020-10-21T06:01:22
2020-10-21T06:01:22
305,906,052
10
0
null
null
null
null
UTF-8
Python
false
false
1,416
py
from datetime import datetime as dt from kubernetes import client from k8s.my_kubernetes import MyKubernetes class MyPod(MyKubernetes): def __init__(self, kube_client: client.CoreV1Api, node_name, datetime_fmt): super().__init__(kube_client, node_name, datetime_fmt) self.pod_names = [] self.current_index = 0 self._fetch_names() def __iter__(self): return self def __next__(self): if self.current_index >= len(self.pod_names): raise StopIteration self.name = self.pod_names[self.current_index] pod = self.kube_client.read_namespaced_pod(self.name, self.project_symbol) self.current_index = self.current_index + 1 # remove additional string from docker registry image_name = pod.spec.containers[0].image.split('/')[-1].split(':')[0] return { "podName": self.name, "imageName": image_name, "deviceNameFk": self.node_name, "deployedAt": pod.status.start_time.strftime(self.datetime_fmt), "currentVersion": "1.00", "latestVersion": "2.00", "status": "0", # always true "updateAt": dt.now().strftime(self.datetime_fmt), } def _fetch_names(self): for pod in self.kube_client.list_namespaced_pod(self.project_symbol).items: self.pod_names.append(pod.metadata.name)
[ "kokorononakaniitumo@yahoo.co.jp" ]
kokorononakaniitumo@yahoo.co.jp
bca470acefa5e161ce2520a221ac6e2465d1d88e
deddca116d34aaeac1193334f6341dffda5bd025
/umonya/content/views.py
59d09160f668c61b1ca1bfc6e29e7c113ee06596
[]
no_license
keegancsmith/Umonya-Website
7079177fe60b9088acd42184ad496a4fb92ad6d2
5575a003dadcc66940cc22564e751051120801cf
refs/heads/master
2016-09-06T16:46:50.882232
2011-07-24T15:04:24
2011-07-24T15:04:24
2,009,325
0
0
null
null
null
null
UTF-8
Python
false
false
287
py
from annoying.decorators import render_to from umonya.content.models import Sponsor @render_to('sponsors.html') def sponsors(request): return { 'sponsors': Sponsor.objects.filter(type='Sponsor'), 'collaborators': Sponsor.objects.filter(type='Collaborator'), }
[ "keegan.csmith@gmail.com" ]
keegan.csmith@gmail.com
9c973488f9d719fd9c2a411440ca647bee688d38
ef187d259d33e97c7b9ed07dfbf065cec3e41f59
/work/atcoder/abc/abc071/B/answers/522566_koshin.py
20bb39dec8949fc4e380efefc6a903dbde19a1ce
[]
no_license
kjnh10/pcw
847f7295ea3174490485ffe14ce4cdea0931c032
8f677701bce15517fb9362cc5b596644da62dca8
refs/heads/master
2020-03-18T09:54:23.442772
2018-07-19T00:26:09
2018-07-19T00:26:09
134,586,379
0
0
null
null
null
null
UTF-8
Python
false
false
146
py
S=list(str(input())) a=list('abcdefghijklmnopqrstuvwxyz') for i in a: if i not in S: print(i) exit() else: print('None')
[ "kojinho10@gmail.com" ]
kojinho10@gmail.com
eb04578dd4f8e1459026e5d3de2526c389876ca4
916480ae24345193efa95df013f637e0a115653b
/web/transiq/utils/migrations/0019_auto_20180513_1844.py
450db0d4d873f520e5f19a49c64c33e02caa89ff
[ "Apache-2.0" ]
permissive
manibhushan05/tms
50e289c670e1615a067c61a051c498cdc54958df
763fafb271ce07d13ac8ce575f2fee653cf39343
refs/heads/master
2022-12-11T07:59:30.297259
2021-09-08T03:24:59
2021-09-08T03:24:59
210,017,184
0
0
Apache-2.0
2022-12-08T02:35:01
2019-09-21T16:23:57
Python
UTF-8
Python
false
false
1,611
py
# Generated by Django 2.0.2 on 2018-05-13 18:44 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('utils', '0018_merge_20180508_1254'), ] operations = [ migrations.AlterModelOptions( name='aahooffice', options={'ordering': ['-id']}, ), migrations.AlterModelOptions( name='bank', options={'ordering': ['-id'], 'verbose_name_plural': 'Bank Account Details'}, ), migrations.AlterField( model_name='district', name='created_by', field=models.ForeignKey(limit_choices_to={'is_staff': True}, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='locality', name='created_by', field=models.ForeignKey(limit_choices_to={'is_staff': True}, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='pincode', name='created_by', field=models.ForeignKey(limit_choices_to={'is_staff': True}, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='subdistrict', name='created_by', field=models.ForeignKey(limit_choices_to={'is_staff': True}, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
[ "mani@myhost.local" ]
mani@myhost.local
ac65ddd449c21c09edc55058e5b68f2044967871
62221ae1588e496d278806c63eadd30c6b6ccc56
/chp44/ex44b.py
ea43712920ed198fd78e467ca3c933fd4ded54e3
[ "MIT" ]
permissive
udoyen/pythonlearning
1b2aa32cad2b274fff46ce6abf69363bbfd0efd7
b157a19ebc1bcf8cb8fb5f76d8a98fcb8e465476
refs/heads/master
2021-01-21T04:59:53.287035
2016-06-19T19:13:35
2016-06-19T19:13:35
48,765,097
0
0
null
2016-06-18T23:07:23
2015-12-29T20:06:48
Python
UTF-8
Python
false
false
246
py
# Override Explicitly class Parent(object): def override(self): print "PARENT override()" class Child(Parent): def override(self): print "CHILD override()" dad = Parent() son = Child() dad.override() son.override()
[ "datameshprojects@gmail.com" ]
datameshprojects@gmail.com
8ea1165a34eb37731299f45c15b41003279813a3
5698fb67c9925902832f69738f1f116bb837528e
/pizza/forms.py
d4bf6b7531157eea4f9afb3d0f6d67b5aa4ac1a9
[]
no_license
lo1cgsan/djangoapp2
ebcc1a2e5758ec2a566d5292ebb3f377bc53dfe7
28aebc44f8a0e70f239626da37fa9bdeab44177c
refs/heads/master
2023-04-28T09:36:55.483445
2021-05-16T18:12:59
2021-05-16T18:12:59
206,551,530
0
0
null
2023-04-21T20:42:23
2019-09-05T11:50:44
Python
UTF-8
Python
false
false
195
py
from django.forms import ModelForm from pizza.models import Skladnik class SkladnikForm(ModelForm): class Meta: model = Skladnik fields = ('nazwa', 'cena', 'jarski', 'pizze')
[ "lo1cgsan@gmail.com" ]
lo1cgsan@gmail.com
55db7e12ea7dea676a28d62fd2b98986a76904b9
5c6ccc082d9d0d42a69e22cfd9a419a5b87ff6cd
/coursera/pythonHse/third/17.py
c6a636de267b026260f08684218d38d2b49704b3
[]
no_license
kersky98/stud
191c809bacc982c715d9610be282884a504d456d
d395a372e72aeb17dfad5c72d46e84dc59454410
refs/heads/master
2023-03-09T20:47:25.082673
2023-03-01T08:28:32
2023-03-01T08:28:32
42,979,807
0
0
null
null
null
null
UTF-8
Python
false
false
721
py
# Дана строка. Найдите в этой строке второе вхождение буквы f, и выведите # индекс этого вхождения. Если буква f в данной строке встречается только один # раз, выведите число -1, а если не встречается ни разу, выведите число -2. # При решении этой задачи нельзя использовать метод count. # s = 'comfort' # s = 'coffee' # s = 'qwerty' s = input() i1 = s.find('f') if i1 < 0: print(-2) else: i2 = s.find('f', i1+1) if i2 < 0: print(-1) else: print(i2)
[ "kerskiy-ev@pao.local" ]
kerskiy-ev@pao.local
9fd947528b778aef4c2487cc0fd92ba8504da87e
0234ad09e974ca91947751dea575a4fb4d2d138d
/tests/commands/element/test_misc.py
2e0381c1559ee70ad8c52362e0fef632fa26ecf3
[ "MIT", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
o3seespy/o3seespy
8e0cee872ec4ec88b81af6c39b6d9287e6d6e057
57e47940cf6c0979215a04a11e184e38fd6f73a5
refs/heads/master
2023-09-04T18:38:45.126336
2023-08-19T01:13:54
2023-08-19T01:13:54
216,960,642
18
6
MIT
2023-02-08T00:40:39
2019-10-23T03:31:48
Python
UTF-8
Python
false
false
1,312
py
import o3seespy as o3 # for testing only import pytest def test_surface_load(): osi = o3.OpenSeesInstance(ndm=2) coords = [[0, 0], [1, 0], [1, 1], [0, 1]] ele_nodes = [o3.node.Node(osi, *coords[x]) for x in range(4)] o3.element.SurfaceLoad(osi, ele_nodes=ele_nodes, p=1.0) def test_vs3d4(): osi = o3.OpenSeesInstance(ndm=2) coords = [[0, 0], [1, 0], [1, 1], [0, 1]] ele_nodes = [o3.node.Node(osi, *coords[x]) for x in range(4)] o3.element.VS3D4(osi, ele_nodes=ele_nodes, big_e=1.0, big_g=1.0, rho=1.0, big_r=1.0, alpha_n=1.0, alpha_t=1.0) @pytest.mark.skip() def test_ac3d8(): osi = o3.OpenSeesInstance(ndm=2) coords = [[0, 0], [1, 0], [1, 1], [0, 1]] ele_nodes = [o3.node.Node(osi, *coords[x]) for x in range(4)] mat = o3.nd_material.ElasticIsotropic(osi, 1, 0.45) o3.element.AC3D8(osi, ele_nodes=ele_nodes, mat=mat) @pytest.mark.skip() def test_asi3d8(): osi = o3.OpenSeesInstance(ndm=2) o3.element.ASI3D8(osi, ele_nodes1=1, ele_nodes2=1) @pytest.mark.skip() def test_av3d4(): osi = o3.OpenSeesInstance(ndm=2) coords = [[0, 0], [1, 0], [1, 1], [0, 1]] ele_nodes = [o3.node.Node(osi, *coords[x]) for x in range(4)] mat = o3.nd_material.ElasticIsotropic(osi, 1, 0.45) o3.element.AV3D4(osi, ele_nodes=ele_nodes, mat=mat)
[ "maxim.millen@gmail.com" ]
maxim.millen@gmail.com
8e7e2b242a40a59a3882ec99d3e0e89f24f03055
b7ae24b0dd67a7fafbf0253f24c80924df88da62
/lab/logger/loop.py
c2ba8b296b533dc4d7b722622f7fd1cf8c2792b3
[ "MIT" ]
permissive
gear/lab
b3a2b1e5babc1adb172f842651e4db5d20939a16
ad1c5838acbcc98abb5d5d93d5c7a6c2b74bdfa2
refs/heads/master
2020-12-19T01:30:33.478027
2020-01-23T10:30:52
2020-01-23T10:30:52
235,579,450
0
0
MIT
2020-01-22T13:29:16
2020-01-22T13:29:15
null
UTF-8
Python
false
false
3,712
py
import math import time from typing import Optional, Dict from lab.logger import internal from lab.logger.sections import LoopingSection from .colors import Text class Loop: def __init__(self, iterator: range, *, logger: 'internal.LoggerInternal', is_print_iteration_time: bool): """ Creates an iterator with a range `iterator`. See example for usage. """ self.iterator = iterator self._start_time = 0. self._iter_start_time = 0. self._init_time = 0. self._iter_time = 0. self._beta_pow = 1. self._beta = 0.9 self.steps = len(iterator) self.counter = 0 self.logger = logger self.__global_step: Optional[int] = None self.__looping_sections: Dict[str, LoopingSection] = {} self._is_print_iteration_time = is_print_iteration_time self.is_started = False def __iter__(self): self.is_started = True self.iterator_iter = iter(self.iterator) self._start_time = time.time() self._init_time = 0. self._iter_time = 0. self.counter = 0 return self def __next__(self): try: next_value = next(self.iterator_iter) except StopIteration as e: self.logger.finish_loop() raise e now = time.time() if self.counter == 0: self.__init_time = now - self._start_time else: self._beta_pow *= self._beta self._iter_time *= self._beta self._iter_time += (1 - self._beta) * (now - self._iter_start_time) self._iter_start_time = now self.counter = next_value return next_value def log_progress(self): """ Show progress """ now = time.time() spent = now - self._start_time if not math.isclose(self._iter_time, 0.): estimate = self._iter_time / (1 - self._beta_pow) else: estimate = sum([s.get_estimated_time() for s in self.__looping_sections.values()]) total_time = estimate * self.steps + self._init_time total_time = max(total_time, spent) remain = total_time - spent remain /= 60 spent /= 60 estimate *= 1000 spent_h = int(spent // 60) spent_m = int(spent % 60) remain_h = int(remain // 60) remain_m = int(remain % 60) to_print = [(" ", None)] if self._is_print_iteration_time: to_print.append((f"{estimate:,.0f}ms", Text.meta)) to_print.append((f"{spent_h:3d}:{spent_m:02d}m/{remain_h:3d}:{remain_m:02d}m ", Text.meta2)) return to_print def get_section(self, *, name: str, is_silent: bool, is_timed: bool, is_partial: bool, total_steps: float): if name not in self.__looping_sections: self.__looping_sections[name] = LoopingSection(logger=self.logger, name=name, is_silent=is_silent, is_timed=is_timed, is_partial=is_partial, total_steps=total_steps) return self.__looping_sections[name] def log_sections(self): parts = [] for name, section in self.__looping_sections.items(): parts += section.log() return parts
[ "vpjayasiri@gmail.com" ]
vpjayasiri@gmail.com
c81184fc056080d1b7ac9ab3668ec51f80548815
238cff74530e5571648da88f127d086d2d9294b4
/0x08-python-more_classes/6-rectangle.py
a84bd8002a4564362e770c5557e21640e606a829
[]
no_license
Achilik/holbertonschool-higher_level_programming-6
b92fcbd1bc6bbedcfef4b49bb3907d97b8be41ff
d0c46cc5ed2bfd1c8d75ce4a2a7604fc4f3f1c5c
refs/heads/master
2023-03-21T08:03:31.613145
2018-09-08T10:10:53
2018-09-08T10:10:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,985
py
#!/usr/bin/python3 """Contains the rectangle class""" class Rectangle: """A rectangle class""" number_of_instances = 0 def __init__(self, width=0, height=0): """Initilizes a rectangle""" self.width = width self.height = height Rectangle.number_of_instances += 1 def __del__(self): """Delete a rectangle""" print("Bye rectangle...") if Rectangle.number_of_instances != 0: Rectangle.number_of_instances -= 1 @property def width(self): """width property""" return self.__width @width.setter def width(self, width): """width setter""" if type(width) is not int: raise TypeError("width must be an integer") if width < 0: raise ValueError("width must be >= 0") self.__width = width @property def height(self): """height property""" return self.__height @height.setter def height(self, height): """height setter""" if type(height) is not int: raise TypeError("height must be an integer") if height < 0: raise ValueError("height must be >= 0") self.__height = height def __str__(self): """Returns rectangle str""" if self.width == 0 or self.height == 0: return "" string = "" for y in range(self.height - 1): string += '#' * self.width + '\n' string += '#' * self.width return string def __repr__(self): """Returns repr of the rectangle""" string = "Rectangle(" + str(self.width) + ", " + str(self.height) + ")" return string def area(self): """Returns area of a rectangle""" return self.height * self.width def perimeter(self): """Returns perimeter of a rectangle""" if self.height == 0 or self.width == 0: return 0 return self.height * 2 + self.width * 2
[ "sidneyriffic@gmail.com" ]
sidneyriffic@gmail.com
4d0c92e543eecad07812775d1c61c09793a91b41
4eb67371900b24faab41ca615612c41f78939bef
/stockpy_venv/Scripts/pip-script.py
28c9fc512610a5dbff315b2e8c74e484ab258a30
[]
no_license
CyborgVillager/ja_stock_pydjango
1670b8b48c238994cd7f604954b6d5f9176f1f8c
b352bc1d4d91e809ce8b34b7d85eb7f705b3e98c
refs/heads/master
2020-10-01T00:19:39.965922
2019-12-15T20:02:57
2019-12-15T20:02:57
227,406,481
0
0
null
null
null
null
UTF-8
Python
false
false
435
py
#!D:\PyProject\GitRespo\stock_pydjango\ja_stock_pydjango\stockpy_venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip' __requires__ = 'pip==19.0.3' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==19.0.3', 'console_scripts', 'pip')() )
[ "almawijonathan@gmail.com" ]
almawijonathan@gmail.com
50c67bed7ba721e1cbacce1759cd7d0a11a0e433
3da7f8a1fae54b4aa6f081e049e03ce28c0d7381
/venv/Lib/site-packages/pip/_vendor/urllib3/__init__.py
f05ac4feb8638484d1b140b92ec7e5b6b291bd7d
[]
no_license
1751605606/PersonalBlog
96259196848418be5344520dda4b94b28f4d85e0
29b364897075e0ea6ce358ce0041b5ce29262e32
refs/heads/master
2022-09-28T11:05:54.016739
2019-12-17T13:19:15
2019-12-17T13:19:15
222,211,569
1
0
null
2022-09-16T18:13:09
2019-11-17T07:17:04
Python
UTF-8
Python
false
false
2,683
py
""" urllib3 - Thread-safe connection pooling and re-using. """ from __future__ import absolute_import import warnings from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url from . import exceptions from .filepost import encode_multipart_formdata from .poolmanager import PoolManager, ProxyManager, proxy_from_url from .response import HTTPResponse from .util.request import make_headers from .util.url import get_host from .util.timeout import Timeout from .util.retry import Retry # Set default logging handler to avoid "No handler found" warnings. import logging from logging import NullHandler __author__ = "Andrey Petrov (andrey.petrov@shazow.net)" __license__ = "MIT" __version__ = "1.25.6" __all__ = ( "HTTPConnectionPool", "HTTPSConnectionPool", "PoolManager", "ProxyManager", "HTTPResponse", "Retry", "Timeout", "add_stderr_logger", "connection_from_url", "disable_warnings", "encode_multipart_formdata", "get_host", "make_headers", "proxy_from_url", ) logging.getLogger(__name__).addHandler(NullHandler()) def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another package. logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) logger.addHandler(handler) logger.setLevel(level) logger.debug("Added a stderr logging handler to logger: %s", __name__) return handler # ... Clean up. del NullHandler # All warning filters *must* be appended unless you're really certain that they # shouldn't be: otherwise, it's very hard for model to use most Python # mechanisms to silence them. # SecurityWarning's always go off by default. warnings.simplefilter("always", exceptions.SecurityWarning, append=True) # SubjectAltNameWarning's should go off once per host warnings.simplefilter("default", exceptions.SubjectAltNameWarning, append=True) # InsecurePlatformWarning's don't vary between requests, so we keep it default. warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True) # SNIMissingWarnings should go off only once. warnings.simplefilter("default", exceptions.SNIMissingWarning, append=True) def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter("ignore", category)
[ "16302010030@fudan.edu.cn" ]
16302010030@fudan.edu.cn
c56b4d049ae904203932b8be248c75f798ac22ab
2a6d385c7737aea3c6b49eef9252babb7557b909
/Scripts/submitDY.py
5ffaab269ea817873d6d083ec627f80c3c6dd808
[]
no_license
Sam-Harper/usercode
1b302a4b647e479d27a9501f9576bd04b07e111a
fa43427fac80d773978ea67b78be58d264f39ec8
refs/heads/120XNtup
2022-08-26T12:59:53.388853
2022-07-12T16:52:46
2022-07-12T16:52:46
15,675,175
1
11
null
2022-07-21T13:27:57
2014-01-06T13:54:22
Python
UTF-8
Python
false
false
3,154
py
#!/usr/bin/env python import threading import subprocess class JobThread (threading.Thread): def __init__(self, cmds): threading.Thread.__init__(self) self.cmds=cmds.split() self.stdout=None self.stderr=None def run(self): # print self.cmds, import subprocess self.stdout,self.stderr = subprocess.Popen(self.cmds,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate() import argparse import os parser = argparse.ArgumentParser(description='submits CMSSW jobs to RAL batch system') parser.add_argument('--config',help='cmsRun config file to run',required=True) #parser.add_argument('--output',help='output filebase name, defaults to outputDir+.root',default=None) parser.add_argument('--outputDir',help='ouput dir (under scratch/mc/CMSSWVersion/<outputdir>',required=True) parser.add_argument('--baseOutDir',help='base output directory',default="mc") args = parser.parse_args() inputFiles=[ "ZToEE_NNPDF30_13TeV-powheg_M_120_200_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_200_400_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_400_800_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_800_1400_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_1400_2300_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_2300_3500_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v5_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_3500_4500_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_4500_6000_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list", "ZToEE_NNPDF30_13TeV-powheg_M_6000_Inf_RunIISpring16DR80-PUSpring16RAWAODSIM_80X_mcRun2_asymptotic_2016_v3-v1_RAWAODSIM.list"] baseDir="/opt/ppd/scratch/harper" baseOutputDir=baseDir+"/"+args.baseOutDir cmsswVersion=os.environ['CMSSW_VERSION'] fullOutputDir=baseOutputDir+"/"+cmsswVersion.split("CMSSW_")[1]+"/"+args.outputDir if os.path.exists(fullOutputDir): print "output directory ",fullOutputDir," exists, aborting " exit(1) os.makedirs(fullOutputDir) threads=[] for filelist in inputFiles: outputFilename=fullOutputDir.rstrip("/")+"/"+filelist.split("_RunIISpring16")[0]+"_ntup_SHv29pre2.root" cmd="cmsRun %s %s %s" % (args.config,filelist,outputFilename) threads.append(JobThread(cmd)) for thread in threads: thread.start() while(len(threads)!=0): for thread in threads: if not thread.isAlive(): print "job","finished" # print thread.cmds print thread.stdout print thread.stderr threads.remove(thread) print "all jobs done"
[ "sam.j.harper@gmail.com" ]
sam.j.harper@gmail.com
fb30adb175d3b157046e8a351c35bbae75a1518a
af41c215f420bbd66067d6dc851ce41d9ed40819
/CRBM/CRBM_linBin.py
37486616144c92d247cebe64ad8654224778066e
[]
no_license
danathughes/pyNeuralNetwork
b704f525bddbc64eabf33c1174dad0649be7bfd9
dbe2090e50434f33ac7a46845ad67eb5dc7dea87
refs/heads/master
2021-01-01T16:30:47.781646
2016-01-27T23:11:51
2016-01-27T23:11:51
19,729,930
0
4
null
2015-02-27T22:22:18
2014-05-13T07:32:24
Python
UTF-8
Python
false
false
4,365
py
import numpy as np import random import copy class CRBM: """ """ def __init__(self, num_visible, num_hidden): """ """ self.num_visible = num_visible self.num_hidden = num_hidden # Weights is a matrix representing the weights between visible units # (rows) and hidden unit (columns) # Biases are column vectors with the number of hidden or visible units self.weights = np.zeros((num_visible, num_hidden)) self.bias_visible = np.zeros((num_visible, 1)) self.bias_hidden = np.zeros((num_hidden, 1)) self.A_visible = np.ones((num_visible, 1)) self.sigma = 1.0 self.lo = 0.0 self.hi = 1.0 self.randomize_weights_and_biases(0.1) def randomize_weights_and_biases(self, value_range = 1): """ Set all weights and biases to a value between [-range/2 and range/2] """ for i in range(self.num_visible): for j in range(self.num_hidden): self.weights[i,j] = value_range*random.random() - value_range/2 for i in range(self.num_visible): self.bias_visible[i,0] = value_range*random.random() - value_range/2 for i in range(self.num_hidden): self.bias_hidden[i,0] = value_range*random.random() - value_range/2 def sigmoid(self, z, A): """ """ return self.lo + (self.hi-self.lo) / (1.0 + np.exp(-A*z)) def binSigmoid(self, z): """ """ return 1.0 / (1.0 + np.exp(-z)) def sample_visible(self, hidden): """ Generate a sample of the visible layer given the hidden layer. """ v = np.dot(self.weights, hidden) + self.bias_visible v += np.random.normal(0,self.sigma, (self.num_visible, 1)) return self.sigmoid(v, self.A_visible) def get_probability_hidden(self, visible): """ Returns the probability of setting hidden units to 1, given the visible unit. """ # h = sigmoid(W'v + c) return self.binSigmoid(np.dot(self.weights.transpose(), visible) + self.bias_hidden) def sample_hidden(self, visible): """ Generate a sample of the hidden layer given the visible layer. """ P_hidden = self.get_probability_hidden(visible) h_sample = [1.0 if random.random() < p else 0.0 for p in P_hidden] return np.array([h_sample]).transpose() def contrastive_divergence(self, v0, k=1): """ Perform CD-k for the given data point """ # Calculate an h0 given the v0 h0 = self.sample_hidden(v0) # We'll need to iteratively sample to get the next values. We'll start # with k=0 and iterate vk = v0 hk = h0 # Now calculate vk and hk for i in range(k): vk = self.sample_visible(hk) hk = self.sample_hidden(vk) # Compute positive and negative as the outer product of these positive = np.dot(v0, h0.transpose()) negative = np.dot(vk, hk.transpose()) # Calculate the delta-weight and delta-biases delta_weights = positive - negative delta_visible_bias = v0 - vk delta_hidden_bias = h0 - hk delta_A_visible = v0*v0 - vk*vk # Return these--let the learning rule handle them return delta_weights, delta_visible_bias, delta_hidden_bias, delta_A_visible def train_epoch(self, dataset, learning_rate = 0.5, k = 1): """ """ total_err = 0.0 dW = np.zeros(self.weights.shape) dB_vis = np.zeros(self.bias_visible.shape) dB_hid = np.zeros(self.bias_hidden.shape) dA_vis = np.zeros(self.A_visible.shape) for data in dataset: dw, db_vis, db_hid, da_vis = self.contrastive_divergence(np.array([data]).transpose(), k) dW = dW + dw dB_vis = dB_vis + db_vis dB_hid = dB_hid + db_hid dA_vis = dA_vis + da_vis total_err += np.sum(db_vis*db_vis) dW = dW / len(dataset) dB_vis = dB_vis / len(dataset) dB_hid = dB_hid / len(dataset) dA_vis = dA_vis / len(dataset) self.weights = self.weights + learning_rate*dW self.bias_hidden = self.bias_hidden + learning_rate*dB_hid self.bias_visible = self.bias_visible + learning_rate*dB_vis self.A_visible = self.A_visible + learning_rate*dA_vis/(self.A_visible*self.A_visible) return total_err / len(dataset)
[ "danathughes@gmail.com" ]
danathughes@gmail.com
9f8789fccf3df008ae84be98d9f9d1eaa6a2e518
2952677aeb4ab4765fd0b588b8cf2a9f58408f3a
/requests/create_geo_objects.py
22ffb604598aab36bd4d8167fbbfba21747d74b4
[]
no_license
VToropov1337/MA
a60c69110a557a744a1b1a949d4dbcfc1d2ca8aa
823c204154f973ded50b62ab2104358f5b2c7131
refs/heads/master
2020-03-20T21:58:45.039951
2019-06-27T18:24:35
2019-06-27T18:24:35
137,772,268
0
0
null
null
null
null
UTF-8
Python
false
false
2,209
py
import requests import json import pandas as pd COL = ['title', 'comment', 'country', 'region', 'city', 'street', 'house', 'ltd', 'lgt', 'address', 'territory', 'metro_city', 'metro_competitor', 'problematical', 'at_code', 'category_id', 'regional_category_id'] token = '***' params = {'Content-Type': 'application/json; charset=utf-8', 'X-Authentication-Token': token} base_url = 'https://***/api/***/***/***/***' # создание 1 тт create = '/geo_objects' def check_file(filename): dataframe = pd.read_excel(filename,sheet_name=0) if list(dataframe.columns) == COL: return dataframe else: raise BaseException('Проверь названия колонок и их порядок') df = check_file('geo_objects.xlsx') df = df.fillna('') data = dict() for i in range(len(df)): data[i] = { "title": df['title'].iloc[i], "comment": df['comment'].iloc[i], "city": df['city'].iloc[i], "address":df['address'].iloc[i], "territory": df['territory'].iloc[i], "metro_city": df['metro_city'].iloc[i], "metro_competitor": df['metro_competitor'].iloc[i], "problematical": str(df['problematical'].iloc[i]).capitalize(), "at_code": df['at_code'].iloc[i], "category_id": df['category_id'].iloc[i], "regional_category_id": df['regional_category_id'].iloc[i] } # print(data) for i in data.keys(): r = requests.post(base_url + create, headers=params, data=json.dumps({"geo_object": { "title": str(data[i]['title']), "comment": str(data[i]['comment']), "city": str(data[i]['city']), "address": str(data[i]['address']), "territory": str(data[i]['territory']), "metro_city": str(data[i]['metro_city']), "metro_competitor": str(data[i]['metro_competitor']), "problematical": str(data[i]['problematical']), "at_code": str(data[i]['at_code']), "category_id": int(data[i]['category_id']), "regional_category_id": int(data[i]['regional_category_id']) }})) print(r.text) print(r)
[ "vladimirtoropov87@gmail.com" ]
vladimirtoropov87@gmail.com
d75a7d8956bc4a6db76ca03519d33c3abfa7d77d
5504bdf5045343145d962537a39fcf4adb823d9b
/simplesocial/posts/models.py
ce20fbee2474320cef8fcfe6b02fac8ceec8f611
[]
no_license
haruyasu/django-deployment-social
f3df16b67ed96175a23537bdb004eaa51510ac61
e4cb3ac2b88ce76d17ec3b6d18686966d5e33673
refs/heads/master
2021-08-23T03:43:53.213940
2017-12-03T01:18:11
2017-12-03T01:18:11
112,890,239
0
0
null
null
null
null
UTF-8
Python
false
false
963
py
from django.db import models from django.core.urlresolvers import reverse from django.conf import settings import misaka from groups.models import Group # Create your models here. from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts') created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs={'username':self.user.username, 'pk':self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message']
[ "harukun2002@gmail.com" ]
harukun2002@gmail.com
c445921ea9533fb28a3bb8e2efc58bb3c23255fd
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2880/61020/248415.py
1e2294e028de52f931cc843ec994906932c8770c
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
533
py
import os import sys s = input() n = int(s[0:1]) k = int(s[2:3]) ''' 8 4 4 2 3 1 5 1 6 4''' weight_list = input().split() for i in range(0, len(weight_list)): weight_list[i] = int(weight_list[i]) left_index = 0 while (left_index < len(weight_list)) and (weight_list[left_index] <= k): left_index += 1 if left_index == len(weight_list): print(n) # os._exit() sys.exit(0) right_index = len(weight_list) - 1 while weight_list[right_index] <= k: right_index -= 1 print(n - (right_index - left_index + 1))
[ "1069583789@qq.com" ]
1069583789@qq.com
fb5ab7fefb1602942552482e3abcdb141674b869
0c9ec5d4bafca45505f77cbd3961f4aff5c10238
/openapi-python-client/test/test_version_dto.py
42e411d4b0a5c74d862fd2bbd0bb770eb27d12b8
[ "Apache-2.0" ]
permissive
yanavasileva/camunda-bpm-examples
98cd2930f5c8df11a56bf04845a8ada5b3bb542d
051f8f28c62845e68ce4059ab64264c5a0bdc009
refs/heads/master
2022-10-19T20:07:21.278160
2020-05-27T15:28:27
2020-05-27T15:28:27
267,320,400
0
0
Apache-2.0
2020-05-27T14:35:22
2020-05-27T13:00:01
null
UTF-8
Python
false
false
1,309
py
# coding: utf-8 """ Camunda BPM REST API OpenApi Spec for Camunda BPM REST API. # noqa: E501 The version of the OpenAPI document: 7.13.0 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import datetime import openapi_client from openapi_client.models.version_dto import VersionDto # noqa: E501 from openapi_client.rest import ApiException class TestVersionDto(unittest.TestCase): """VersionDto unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test VersionDto include_option is a boolean, when False only required params are included, when True both required and optional params are included """ # model = openapi_client.models.version_dto.VersionDto() # noqa: E501 if include_optional : return VersionDto( version = '0' ) else : return VersionDto( ) def testVersionDto(self): """Test VersionDto""" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__ == '__main__': unittest.main()
[ "noreply@github.com" ]
yanavasileva.noreply@github.com
5357c9994f096c88200299181ed677f3cdcb2aa4
75275e1cd5ef1a5dddd5fdcb82db03fdf1b609d3
/lib/ansible/modules/cloud/alicloud/alicloud_vswitch_facts.py
561d125b8647854e88f68e032792d213c1b52967
[ "Apache-2.0" ]
permissive
jumping/ansible-provider
bc8b2bc51aa422de89d255ba1208ba8e8ae8f0be
067ce1aa4277720bc481c2ba08e3d1b408b8f13c
refs/heads/master
2020-03-13T21:30:50.287049
2018-04-27T13:12:23
2018-04-27T13:12:23
131,297,789
0
0
Apache-2.0
2018-04-27T13:12:24
2018-04-27T13:07:37
Python
UTF-8
Python
false
false
7,048
py
#!/usr/bin/python # Copyright (c) 2017 Alibaba Group Holding Limited. He Guimin <heguimin36@163.com.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see http://www.gnu.org/licenses/. from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: alicloud_vswitch_facts version_added: "2.4" short_description: Gather facts on vswitchs of Alibaba Cloud. description: - This module fetches data from the Open API in Alicloud. The module must be called from within the vswitch itself. options: vpc_id: description: - A vpc id to list vswitches in specified vpc. required: true aliases: ["id"] vswitch_ids: required: false description: - A list of vswitch ids. author: - "He Guimin (@xiaozhu36)" requirements: - "python >= 2.6" - "footmark" extends_documentation_fragment: - alicloud ''' EXAMPLES = ''' # Fetch vswitch details according to setting different filters - name: Fetch vswitch details example hosts: localhost vars: alicloud_access_key: <your-alicloud-access-key> alicloud_secret_key: <your-alicloud-secret-key> alicloud_region: cn-beijing vpc_id: xxxxxxxxxxxxx vswitch_ids: - xxxxxxxxxxxxx - xxxxxxxxxxxxx tasks: - name: Find all vswitches in the specified vpc alicloud_vswitch_facts: alicloud_access_key: '{{ alicloud_access_key }}' alicloud_secret_key: '{{ alicloud_secret_key }}' alicloud_region: '{{ alicloud_region }}' vpc_id: '{{ vpc_id }}' register: vswitch_by_vpc - debug: var=vswitch_by_vpc - name: Find all vswitches in the specified vpc by vswitch_ids alicloud_vswitch_facts: alicloud_access_key: '{{ alicloud_access_key }}' alicloud_secret_key: '{{ alicloud_secret_key }}' alicloud_region: '{{ alicloud_region }}' vpc_id: '{{ vpc_id }}' vswitch_ids: '{{ vswitch_ids }}' register: vswich_by_vswitch_ids - debug: var=vswich_by_vswitch_ids ''' RETURN = ''' vpc_id: description: vpc_id to list all vswitch in specified vpc. returned: when success type: string sample: "vpc-2zegusms7jwd94lq7ix8o" vswitch_ids: description: List all vswitch's id after operating vswitch. returned: when success type: list sample: [ "vsw-2zepee91iv5sl6tg85xnl", "vsw-2zeuo4b8jx8tdg9esy8m7" ] vswitchs: description: Details about the vswitchs that were created. returned: when success type: list sample: [ { "available_ip_address_count": 4091, "cidr_block": "172.17.128.0/20", "description": "System created default virtual switch.", "is_default": true, "region": "cn-beijing", "status": "Available", "tags": {}, "vpc_id": "vpc-2zegusms7jwd94lq7ix8o", "vswitch_id": "vsw-2zepee91iv5sl6tg85xnl", "vswitch_name": "", "zone_id": "cn-beijing-e" }, { "available_ip_address_count": 4092, "cidr_block": "172.17.144.0/20", "description": "System created default virtual switch.", "is_default": true, "region": "cn-beijing", "status": "Available", "tags": {}, "vpc_id": "vpc-2zegusms7jwd94lq7ix8o", "vswitch_id": "vsw-2zeuo4b8jx8tdg9esy8m7", "vswitch_name": "", "zone_id": "cn-beijing-c" } ] total: description: The number of all vswitchs after operating vpc. returned: when success type: int sample: 2 ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.alicloud_ecs import ecs_argument_spec, vpc_connect HAS_FOOTMARK = False try: from footmark.exception import VPCResponseError HAS_FOOTMARK = True except ImportError: HAS_FOOTMARK = False def get_info(vswitch): """ Retrieves vswitch information from an vswitch ID and returns it as a dictionary """ return { 'available_ip_address_count': vswitch.available_ip_address_count, 'cidr_block': vswitch.cidr_block, 'description': vswitch.description, 'is_default': vswitch.is_default, 'region': vswitch.region, 'status': vswitch.status, 'tags': vswitch.tags, 'vpc_id': vswitch.vpc_id, 'vswitch_id': vswitch.vswitch_id, 'vswitch_name': vswitch.vswitch_name, 'zone_id': vswitch.zone_id } def main(): argument_spec = ecs_argument_spec() argument_spec.update(dict( alicloud_zone=dict(aliases=['acs_zone', 'ecs_zone', 'zone_id', 'zone']), vpc_id=dict(required=True, aliases=['id']), vswitch_ids=dict(type='list') ) ) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json(msg="Package 'footmark' required for this module.") result = [] zone_id = module.params['alicloud_zone'] vpc_id = module.params['vpc_id'] vswitch_ids = module.params['vswitch_ids'] if vswitch_ids and (not isinstance(vswitch_ids, list) or len(vswitch_ids)) < 1: module.fail_json(msg='vswitch_ids should be a list of vswitch id, aborting') try: vpc_conn = vpc_connect(module) # list all vswitches by vswitch ids if vswitch_ids: for vswitch_id in vswitch_ids: vswitchs = vpc_conn.get_all_vswitches(vpc_id=vpc_id, vswitch_id=vswitch_id, zone_id=zone_id) if vswitchs and len(vswitchs) == 1: result.append(get_info(vswitchs[0])) # list all vswitches in specified vpc else: vswitchs = vpc_conn.get_all_vswitches(vpc_id=vpc_id) vswitch_ids = [] for vswitch in vswitchs: vswitch_ids.append(vswitch.vswitch_id) result.append(get_info(vswitch)) except Exception as e: module.fail_json(msg=str("Unable to describe vswitch, error:{0}".format(e))) module.exit_json(changed=False, vpc_id=vpc_id, vswitch_ids=vswitch_ids, vswitchs=result, total=len(result)) if __name__ == '__main__': main()
[ "guimin.hgm@alibaba-inc.com" ]
guimin.hgm@alibaba-inc.com
93e90f8008b9eb70c05f3db8771a4a04c3ee4d08
643e4cf0a3fe3a3ab04cf584b97e38b4838e4e1d
/1.2.2_[T.S].py
7abc50bd411c7b5bf73393a0ff90c5a3264cd8e8
[]
no_license
riley-csp-2019-20/1-2-2-catch-a-turtle-leaderboard-tiffany85615
188e86ba3a6b85a669321c431305edc702ce5866
20ef11e6aafcf1e87d676aa1a2459bf443888791
refs/heads/master
2020-08-31T22:19:17.319740
2019-11-08T15:59:14
2019-11-08T15:59:14
218,799,571
0
0
null
null
null
null
UTF-8
Python
false
false
2,808
py
# a121_catch_a_turtle.py #-----import statements----- import turtle as trtl import random import leaderboard as lb #-----game configuration---- shape = "turtle" size = 10 color = "orange" score = 0 timer = 5 counter_interval = 1000 #1000 represents 1 second timer_up = False #leaderboard variables leaderboard_file_name = "a122_leaderboard.txt" leader_names_list = [] leader_scores_list = [] player_name = input("Please enter your name:") #-----initialize turtle----- dude = trtl.Turtle(shape = shape) dude.color(color) dude.shapesize(size) writer = trtl.Turtle() writer.shapesize(2) writer.color("green") writer.penup() writer.goto(-270, 330) font = ("Arial", 30, "bold") writer.write(score, font = font) writer.ht() counter = trtl.Turtle() counter.up() counter.goto(250,310) counter.ht() #-----game functions-------- def turtle_clicked(x,y): print("dude was clicked") change_position() score_counter() # this is my customization size_down() '''colors = {"red","orange", "yellow", "green","blue","purple"}''' def change_position(): dude.penup() dude.ht() new_xpos = random.randint(-400, 400) new_ypos = random.randint(-300, 300) dude.goto(new_xpos, new_ypos) dude.showturtle() def score_counter(): global score score += 1 print(score) writer.write(score,font = font) writer.clear() writer.write(score, font = font) def countdown(): global timer, timer_up counter.clear() if timer <= 0: game_end() timer_up = True manage_leaderboard() else: counter.write("Timer: " + str(timer), font = font) timer -= 1 counter.getscreen().ontimer(countdown, counter_interval) def game_end(): dude.ht() dude.goto(500,500) counter.goto(0,0) counter.write("Time's Up", font = font) wn.bgcolor("red") def size_down(): global size size -= 1 dude.shapesize(size) # manages the leaderboard for top 5 scorers def manage_leaderboard(): global leader_scores_list global leader_names_list global score global dude # load all the leaderboard records into the lists lb.load_leaderboard(leaderboard_file_name, leader_names_list, leader_scores_list) # TODO if (len(leader_scores_list) < 5 or score > leader_scores_list[4]): lb.update_leaderboard(leaderboard_file_name, leader_names_list, leader_scores_list, player_name, score) lb.draw_leaderboard(leader_names_list, leader_scores_list, True, dude, score) else: lb.draw_leaderboard(leader_names_list, leader_scores_list, False, dude, score) #-----events---------------- dude.onclick(turtle_clicked) wn = trtl.Screen() wn.ontimer(countdown, counter_interval) wn.mainloop()
[ "noreply@github.com" ]
riley-csp-2019-20.noreply@github.com
83d75d742cdf7f8b7d4970dff0532f6e23253ee2
171179bbef63781fa55ffe94bd33868578272db0
/prog/lu.py
83a4dca99e822dc012b36010c749e84aba2dfab5
[]
no_license
nineties/math-seminar
9a038a4fb88bbcb2fbc2456860a3bd88b99ca10e
51bbc071aa46418abf525969391a502312867c08
refs/heads/master
2020-04-16T16:36:22.207459
2018-09-12T22:41:08
2018-09-12T22:41:08
12,613,664
14
7
null
2019-11-08T12:10:17
2013-09-05T09:06:37
HTML
UTF-8
Python
false
false
659
py
# -*- coding: utf-8 -*- import numpy as np def lu(A): A = np.copy(A) # 作業用 n = A.shape[0] L = np.identity(n, dtype=float) # 対角行列 U = np.zeros((n,n), dtype=float) # 零行列 for k in xrange(n): U[k,k] = A[k,k] for i in xrange(k+1,n): U[k,i] = A[k,i] L[i,k] = A[i,k]/A[k,k] for i in xrange(k+1,n): for j in xrange(k+1,n): A[i,j] -= L[i,k] * U[k,j] return (L, U) A = np.array([[4, 5, 1, 9], [2, 1, 3, 1], [3, 1, 5, 3], [-2, 1, 4, 3]], dtype=float) L,U = lu(A) print "A=\n",A print "L=\n",L print "U=\n",U print "LU=\n", np.dot(L, U)
[ "nineties48@gmail.com" ]
nineties48@gmail.com
16d7ba3880938e774a1bd1213fd7bd46d6db8316
81529f3d8570db42218b9420fe82ddc3ec7820b6
/15-exercises/stochastic_gradient_descent_two.py
15e114c355202edec727a4eb39980aeb15544444
[]
no_license
rileyL6122428/data-science-from-scratch-notes
f10770030fbdd5062de0477b8997cd33b5acf1e6
8202442024a502b13d0b462c398b2dcb74712e38
refs/heads/master
2020-07-13T10:25:39.318516
2019-08-29T02:45:33
2019-08-29T02:45:33
205,064,746
0
0
null
null
null
null
UTF-8
Python
false
false
3,071
py
import random import pdb # USUALLY, ERROR FUNCTIONS FOR GRADIENT DESCENT PROBLEMS ARE ADDITIVE # WHICH MEANS THE PREDICTIVE ERROR ON THE WHOLE DATA SET IS SIMPLY THE SUM # OF THE PREDICTIVE ERRORS FOR EACH DATA POINT # STOCHASTIC GRADIENT DESCENT: # COMPUTES THE GRADIENT OF A SINGLE DATA POINT AND TAKES A STEP # IT CYCLES OVER OUR DATA REPEATEDLY UNTIL IT REACHES A STOPPING POINT def random_order(data): indexes = [ index for index, _ in enumerate(data) ] random.shuffle(indexes) for index in indexes: yield data[index] def vector_subtract(vector_a, vector_b): return [ component_a - component_b for component_a, component_b in zip(vector_a, vector_b) ] def scalar_multiply(scalar, vector): return [ scalar * component for component in vector ] def minimize_stochastic(target_fn, gradient_fn, xs, ys, theta_0, alpha_0=0.01): data = list(zip(xs, ys)) theta = theta_0 alpha = alpha_0 min_theta, min_value = None, float('inf') iterations_with_no_improvement = 0 print('theta_0 = %s' % theta_0) while iterations_with_no_improvement < 100: value = sum( target_fn(x_i, y_i, theta) for x_i, y_i in data ) if value < min_value: print('next_theta = %s' % theta) min_theta, min_value = theta, value iterations_with_no_improvement = 0 alpha = alpha_0 else: iterations_with_no_improvement += 1 print('iterations_with_no_improvement = %s' % iterations_with_no_improvement) alpha *= 0.9 for x_i, y_i in random_order(data): gradient_i = gradient_fn(x_i, y_i, theta) theta = vector_subtract(theta, scalar_multiply(alpha, gradient_i)) return min_theta def negate(func): return lambda *args, **kwargs : -func(*args, **kwargs) def negate_all(func): return lambda *args, **kwargs : [ -y for y in func(*args, **kwargs) ] def maximize_stochastic(target_func, gradient_func, x, y, theta_0, tolerance=0.01): return minimize_stochastic( negate(target_func), negate_all(gradient_func), x, y, theta_0, tolerance ) # TEST STOCHASTIC GRADIENT DESCENT from simple_linear_regression import error from pokemon_trainer_data import trainer_pokemon_counts, trainer_win_counts def squared_error(x_i, y_i, theta): alpha, beta = theta return error(alpha, beta, x_i, y_i) def squared_error_gradient(x_i, y_i, theta): alpha, beta, = theta return [ -2 * error(alpha, beta, x_i, y_i), # alpha partial derivative -2 * error(alpha, beta, x_i, y_i) * x_i # beta partial derivative ] # theta = [ random.random() - 0.5, random.random() - 0.5 ] # alpha, beta = minimize_stochastic( # squared_error, # squared_error_gradient, # trainer_pokemon_counts, # trainer_win_counts, # theta, # 0.001 # ) # print('stochastic alpha = %s' % alpha) # print('stochastic beta = %s' % beta)
[ "rileylittlefield@ymail.com" ]
rileylittlefield@ymail.com
7937369f1aa7ea27e2c1bfb5fe1d8b91569a4c89
3fa149cfcdd8ec56d51cf99a16cbf3afbd9b1266
/django/mysite/blog/views.py
2f789f2fc7fa924fcdb58c4d500f5c19f37ec596
[]
no_license
leinian85/project
045ec90475b012063624151d604d9148d2d8c948
c2463da30cbdda8c35a557048988260e62212d08
refs/heads/master
2020-07-06T16:44:42.993050
2019-11-04T06:44:41
2019-11-04T06:44:41
203,082,284
0
0
null
null
null
null
UTF-8
Python
false
false
3,136
py
from django.shortcuts import render from django.http import HttpResponseRedirect from . import models def index(request): return render(request,"blog/index.html") def list(request): return render(request, "blog/list.html") def mypic(request): return render(request, "blog/mypic.html") def login(request): if request.method == "GET": username = request.COOKIES.get("username","") return render(request, "blog/login.html",locals()) elif request.method == "POST": username = request.POST.get("username") if username == "": user_error = "用户名不能为空" return render(request, "blog/login.html", locals()) password = request.POST.get("password") if password == "": password_error = "密码不能为空" return render(request, "blog/login.html", locals()) try: user = models.User.objects.get(name = username,password = password) request.session["user"] = { "username" : user.name, "id": user.id, } # reps = render(request, "blog/index.html", locals()) # if "remember" in request.POST: # reps.set_cookie("username",username) # # return reps reps = HttpResponseRedirect("/blog/index") reps.set_cookie("username",username) return reps except: password_error = "用户名或密码不正确" return render(request, "blog/login.html", locals()) def regist(request): if request.method == "GET": return render(request, "blog/regist.html") elif request.method == "POST": username = request.POST.get("username") password1 = request.POST.get("password1") password2 = request.POST.get("password2") if len(username)<6: user_error = "用户名太短" return render(request, "blog/regist.html", locals()) if len(password1) == 0: password1_error = "密码不能为空" return render(request, "blog/regist.html", locals()) if len(password2) == 0: password2_error = "密码不能为空" return render(request, "blog/regist.html", locals()) if password1 != password2: password2_error = "两次密码不一致" password1 = password2 = "" return render(request, "blog/regist.html", locals()) try: user = models.User.objects.get(name = username) user_error = "用户已存在" return render(request, "blog/regist.html", locals()) except Exception as e: user = models.User.objects.create( name=username, password = password1 ) msg = "注册成功!" request.session["user"] = {"username":username} return render(request, "blog/ok.html", locals()) def logout(request): if "user" in request.session: del request.session["user"] return render(request, "blog/index.html", locals())
[ "42737521@qq.com" ]
42737521@qq.com
2863c98cb8176410c703c0fd4c2af26245e0829a
ac3db86631a4ab6fd9ef0d1397ccd842cef957fa
/blocks/eyeBlocks/timecomponent.py
14a3c47580776b1a3ce2feb4754be17b0ad1e669
[ "MIT" ]
permissive
csparkresearch/ExpEYES17-Qt
57f5e19196bfd7a04454c0708c33d6eccd36e1e1
7a3bdc0df19569c0321434d8fd897439b1854fb1
refs/heads/master
2020-12-31T00:30:42.669312
2018-04-19T11:11:39
2018-04-19T11:11:39
86,545,764
1
4
null
2017-07-21T10:00:39
2017-03-29T06:22:12
Python
UTF-8
Python
false
false
2,722
py
# -*- coding: utf-8; mode: python; indent-tabs-mode: t; tab-width:4 -*- ############################################################################ # # Copyright (C) 2017 Georges Khaznadar <georgesk@debian.org> # # # This file may be used under the terms of the GNU General Public # License version 3.0 as published by the Free Software Foundation, # or, at your preference, any later verion of the same. # # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE # WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # ############################################################################ from __future__ import print_function from PyQt4 import QtCore, QtGui from component import InputComponent, Component def _translate(context, text, disambig): return QtGui.QApplication.translate(context, unicode(text), disambig) class TimeComponent(InputComponent): """ A component to implement a time base for an oscilloscope """ # standard numbers of points np = [11, 101, 501, 1001, 2001] def __init__(*args,**kw): InputComponent.__init__(*args,**kw) self=args[0] self.initDefaults() for a in ("npoints","delay","duration"): if a in kw: setattribute(self, a, kw[a]) def __str__(self): result=super(self.__class__,self).__str__() result+="\n npoints = %s delay = %s duration = %s" %(self.npoints, self.delay, self.duration) return result def initDefaults(self): self.npoints = TimeComponent.np[2] self.delay = 1000 # µs self.duration = (self.npoints-1)*self.delay def draw(self, painter): super(TimeComponent, self).draw(painter) lh=12 # lineheight x=10;y=15 pos=self.rect.topLeft() titlePos=pos+QtCore.QPoint(x,y) x=15; y+=lh delayPos=pos+QtCore.QPoint(x,y) y+=lh durationPos=pos+QtCore.QPoint(x,y) y+=lh pointsPos=pos+QtCore.QPoint(x,y) painter.drawText(titlePos,_translate("eyeBlocks.timecomponent","Time Base",None)) painter.drawText(delayPos,_translate("eyeBlocks.timecomponent","delay: %1 s",None).arg(self.delay/1e6)) painter.drawText(durationPos,_translate("eyeBlocks.timecomponent","duration: %1 s",None) .arg(self.duration/1e6)) painter.drawText(pointsPos,_translate("eyeBlocks.timecomponent","(%1 points)",None).arg(self.npoints)) def getMoreData(self, dataStream): delay=QtCore.QVariant() duration=QtCore.QVariant() npoints=QtCore.QVariant() dataStream >> delay >> duration >> npoints self.delay, report=delay.toInt() self.duration, report=delay.toInt() self.npoints, report=npoints.toInt() return def putMoreData(self, dataStream): dataStream << QtCore.QVariant(self.delay) << QtCore.QVariant(self.duration) << QtCore.QVariant(self.npoints) return
[ "georgesk@debian.org" ]
georgesk@debian.org
3fb4f0e2850f32ab1f80edb8ed59569c4b953632
84a5c4c2e0977d42425771098f5f881c750da7f0
/neomodel_constraints/fetcher/constraints/__init__.py
73fec18b7981f1156387bb109741685f95637d1e
[]
no_license
SSripilaipong/neomodel-constraints
6c3023ba156275e48f5f7ebcbdd283ce8d41f9a1
4b91185ba9eec993c58e9ae770fd3d0e90f915ae
refs/heads/main
2023-07-15T09:58:41.451631
2021-08-29T13:19:38
2021-08-29T13:19:38
390,312,509
1
0
null
null
null
null
UTF-8
Python
false
false
128
py
from .data import Neo4jConstraintQueryRecord from .fetcher import get_constraints_fetcher from . import v4_2 from . import v4_1
[ "santhapon.s@siametrics.com" ]
santhapon.s@siametrics.com
009c7689d899f6b590b2b405a7df7c8ed717a727
1c6283303ceb883add8de4ee07c5ffcfc2e93fab
/Jinja2/lib/python3.7/site-packages/ixnetwork_restpy/testplatform/sessions/ixnetwork/globals/topology/cuspup/cuspup_985b33e540b199c473b9a9aa9d00f4c4.py
44cd2b03fca9c53826daa25735c52165e2446bed
[]
no_license
pdobrinskiy/devcore
0f5b3dfc2f3bf1e44abd716f008a01c443e14f18
580c7df6f5db8c118990cf01bc2b986285b9718b
refs/heads/main
2023-07-29T20:28:49.035475
2021-09-14T10:02:16
2021-09-14T10:02:16
405,919,390
0
0
null
null
null
null
UTF-8
Python
false
false
5,044
py
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files from typing import List, Any, Union class CuspUP(Base): """CUSP UP Port Specific Data The CuspUP class encapsulates a required cuspUP resource which will be retrieved from the server every time the property is accessed. """ __slots__ = () _SDM_NAME = 'cuspUP' _SDM_ATT_MAP = { 'Count': 'count', 'DescriptiveName': 'descriptiveName', 'Name': 'name', 'RowNames': 'rowNames', } _SDM_ENUM_MAP = { } def __init__(self, parent, list_op=False): super(CuspUP, self).__init__(parent, list_op) @property def StartRate(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.globals.topology.ethernet.startrate.startrate_2bc83a4fb9730935e8259bdb40af2dc0.StartRate): An instance of the StartRate class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.globals.topology.ethernet.startrate.startrate_2bc83a4fb9730935e8259bdb40af2dc0 import StartRate if self._properties.get('StartRate', None) is not None: return self._properties.get('StartRate') else: return StartRate(self)._select() @property def StopRate(self): """ Returns ------- - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.globals.topology.ethernet.stoprate.stoprate_4ea9a1b38960d2b21012777131469a04.StopRate): An instance of the StopRate class Raises ------ - ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.globals.topology.ethernet.stoprate.stoprate_4ea9a1b38960d2b21012777131469a04 import StopRate if self._properties.get('StopRate', None) is not None: return self._properties.get('StopRate') else: return StopRate(self)._select() @property def Count(self): # type: () -> int """ Returns ------- - number: Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. """ return self._get_attribute(self._SDM_ATT_MAP['Count']) @property def DescriptiveName(self): # type: () -> str """ Returns ------- - str: Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. """ return self._get_attribute(self._SDM_ATT_MAP['DescriptiveName']) @property def Name(self): # type: () -> str """ Returns ------- - str: Name of NGPF element, guaranteed to be unique in Scenario """ return self._get_attribute(self._SDM_ATT_MAP['Name']) @Name.setter def Name(self, value): # type: (str) -> None self._set_attribute(self._SDM_ATT_MAP['Name'], value) @property def RowNames(self): # type: () -> List[str] """ Returns ------- - list(str): Name of rows """ return self._get_attribute(self._SDM_ATT_MAP['RowNames']) def update(self, Name=None): # type: (str) -> CuspUP """Updates cuspUP resource on the server. Args ---- - Name (str): Name of NGPF element, guaranteed to be unique in Scenario Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
[ "pdobrinskiy@yahoo.com" ]
pdobrinskiy@yahoo.com
a99f0536c1d5f211f5d364eb549957ee8b00dfec
3c7057226c7bb01cd493cde5742b3979cf030f94
/lmctl/client/api/behaviour_projects.py
0b0e73b6319e5993be94a05d25387e22b98be3d4
[ "Apache-2.0" ]
permissive
sharadc2001/lmctl
2d047f776d1bbee811801ccc5454a097b1484841
a220a3abeef5fc1f7c0a9410524625c2ff895a0a
refs/heads/master
2023-05-27T06:14:49.425793
2021-04-29T20:08:52
2021-04-29T20:08:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
133
py
from .resource_api_base import ResourceAPIBase class BehaviourProjectsAPI(ResourceAPIBase): endpoint = 'api/behaviour/projects'
[ "daniel.vaccaro-senna@ibm.com" ]
daniel.vaccaro-senna@ibm.com
38f5fcd0c82d2fedebb31c1e82541d9708fd8458
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03252/s222988530.py
d03803223cba2148882efcfde3db4be3936b980f
[]
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
1,205
py
#from statistics import median #import collections #aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0] from fractions import gcd from itertools import combinations,permutations,accumulate, product # (string,3) 3回 #from collections import deque from collections import deque,defaultdict,Counter import decimal import re #import bisect # # d = m - k[i] - k[j] # if kk[bisect.bisect_right(kk,d) - 1] == d: # # # # pythonで無理なときは、pypyでやると正解するかも!! # # # my_round_int = lambda x:np.round((x*2 + 1)//2) # 四捨五入g import sys sys.setrecursionlimit(10000000) mod = 10**9 + 7 #mod = 9982443453 def readInts(): return list(map(int,input().split())) def I(): return int(input()) dics = defaultdict(str) dict = defaultdict(str) s = input() t = input() for i in range(len(s)): if dics[s[i]]: if dics[s[i]] == t[i]: pass else: print('No') exit() else: dics[s[i]] = t[i] if dict[t[i]]: if dict[t[i]] == s[i]: pass else: print('No') exit() else: dict[t[i]] = s[i] print('Yes')
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
7dcfd73cbe7545f48aac779d51ddde20a249fdd4
3493c9edcc457ea692aa2f992f79c103f558d9c5
/alarms/views.py
51530a89d54e7b91f64f960cdf3d4e94156dbb65
[ "MIT" ]
permissive
RashaMou/clock-api
ad2427d2a0bda03a05a871d63bd0a35f1fbbfd26
57c16e83cdb405feea268c6a03959207a12cb4d0
refs/heads/master
2023-07-05T13:18:42.767423
2021-08-12T15:15:29
2021-08-12T15:15:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
483
py
from rest_framework import viewsets from . import models, serializers class AlarmViewSet(viewsets.ModelViewSet): authentication_classes = [] permission_classes = [] queryset = models.Alarm.objects.select_related("sound", "task__crontab").all() serializer_class = serializers.AlarmSerializer filterset_fields = ("active",) class SoundViewSet(viewsets.ModelViewSet): queryset = models.Sound.objects.all() serializer_class = serializers.SoundSerializer
[ "flavio.curella@gmail.com" ]
flavio.curella@gmail.com
2f84e673311d417b421b9ae8507b879d52c87744
16f11e566c5069a874a99ff33debb47913881bfa
/python/sets/symetric_difference.py
1845ad05bcf46c0bdf85ba51b2d9ade857fbb091
[]
no_license
Suraj-KD/HackerRank
7c5a1a73ea2d2c30370ff5d2dd633aaef315f00a
ef6ba86b2245172de6f62a6fb63916318adef2a6
refs/heads/master
2021-06-27T10:30:14.195489
2019-03-20T12:33:54
2019-03-20T12:33:54
129,599,426
2
0
null
null
null
null
UTF-8
Python
false
false
243
py
import sys def setsym(a, b): return len(set(a) ^ set(b)) def main(): lines = [[int(x) for x in line.strip().split()] for line in sys.stdin.readlines()[:4]] print(setsym(lines[1], lines[3])) if __name__ == '__main__': main()
[ "surajdubey302@gmail.com" ]
surajdubey302@gmail.com
aa09f2d8129f95e2dca1a311d322ace71a2eaa32
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/sdssj_143026.15+195346.7/sdB_sdssj_143026.15+195346.7_coadd.py
60fd321f363d4a9442ec3bb3c4bf7aaccdebdbb7
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
482
py
from gPhoton.gMap import gMap def main(): gMap(band="NUV", skypos=[217.608958,19.896306], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_sdssj_143026.15+195346.7/sdB_sdssj_143026.15+195346.7_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_sdssj_143026.15+195346.7/sdB_sdssj_143026.15+195346.7_count_coadd.fits", overwrite=True, verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
7b2a69f3ac172111bffd9b484e13e7b56ac6be8a
2a0c2b3b682fdc7a49ff2ea107f53ac4b8fb5d20
/tool/mySpiderUtil/getFontTTF/__init__.py
09fb027b761e9a2e1580ff3f506b9974fab89d76
[]
no_license
NoobsZero/DesignMode
29f8327c09ecd8f26e9fc3c8618e5fba3de712b2
161997377020436491520a10fc3ac927469458f1
refs/heads/master
2023-07-08T04:24:59.776257
2021-08-17T05:55:46
2021-08-17T05:55:46
303,366,863
1
0
null
null
null
null
UTF-8
Python
false
false
139
py
# encoding: utf-8 """ @file: __init__.py.py @time: 2021/6/11 10:54 @author: Chen @contact: Afakerchen@em-data.com.cn @software: PyCharm """
[ "870628995@qq.com" ]
870628995@qq.com
10a0be8ff0647bb8a664bf5229355fe8e245c642
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03291/s377331832.py
862748becfb1ad9796cc654b44a9968803c6871f
[]
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
435
py
s = input() dp = [[0] * (len(s) + 1) for _ in range(4)] dp[0][0] = 1 for i, c in enumerate(s): # use c if c == "A" or c == "?": dp[1][i+1] = dp[0][i] if c == "B" or c == "?": dp[2][i+1] = dp[1][i] if c == "C" or c == "?": dp[3][i+1] = dp[2][i] # not use c for j in range(4): if c == "?": dp[j][i+1] += dp[j][i] * 3 else: dp[j][i+1] += dp[j][i] dp[j][i+1] %= 10**9+7 print(dp[-1][-1])
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
7d76bf001033d051ea34ded6b3e5c8d0d9d5bc2b
aa071e5782c76d8552844329073214ae73f005f0
/Study_9/Study_9.py
cfe964bcbcd8e8a9713f89965fb88d27deb883cd
[ "MIT" ]
permissive
LeeDaeil/PyQt5_study
1feff7a934aa9b46c7e70c4de00e02c49f292db8
ecdd22ce2809ce6f01c8691a7ca75ef1771b7202
refs/heads/master
2021-06-24T09:14:32.358137
2020-12-06T13:35:30
2020-12-06T13:35:30
176,840,877
1
0
null
null
null
null
UTF-8
Python
false
false
1,453
py
import sys from PyQt5.QtWidgets import QDialog, QApplication from ui_data.gui_study_9 import * import Study_9_re_rc # resource file class MyForm(QDialog): def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.background_setting() self.initial_interface() # self.show() def background_setting(self): self.back_color ={ 'gray': "background-color: rgb(229, 229, 229);", 'green': "background-color: rgb(0, 170, 0);", 'yellow': "background-color: rgb(0, 170, 0);", 'orange': "background-color: rgb(255, 85, 0);", 'red': "background-color: rgb(255, 0, 0);", } self.back_img = { 'P_1_ON': "image: url(:/Sys/Pump_1_ON.png);", # P_1~6 'P_1_OFF': "image: url(:/Sys/Pump_1_OFF.png);", # P_1~6 'P_2_ON': "image: url(:/Sys/Pump_2_ON.png);", # P_7~9 'P_2_OFF': "image: url(:/Sys/Pump_2_OFF.png);", # P_7~9 'P_3_ON': "image: url(:/Sys/Pump_3_ON.png);", # P_7~9 } def initial_interface(self): self.ui.CSF_1_1.setStyleSheet(self.back_color['gray']) self.ui.CSF_1_2.setStyleSheet(self.back_color['gray']) self.ui.P_1.setStyleSheet(self.back_img['P_1_OFF']) if __name__=="__main__": app = QApplication(sys.argv) w = MyForm() w.show() sys.exit(app.exec_())
[ "dleodlf1004@naver.com" ]
dleodlf1004@naver.com
af5386d8b29e79b56dcf99e9be2b9c056aa19606
4b61ae276d8a198017a5986e72fb2c4d991286b3
/utils/test/visibility_tests/VisibilityDataPrepToolsTestSuite.py
1c8c2cdfd11164f5afad6e168c8b666a2129fd9c
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
NatalieCampos/solutions-geoprocessing-toolbox
b8e13de5b0686d3f0d521e4e4f99520afc965b14
de6b175cd97ad4030fb72b3e66995a018448ffbf
refs/heads/master
2018-01-16T20:20:04.729686
2017-07-20T16:33:41
2017-07-20T16:33:41
24,063,516
0
0
null
null
null
null
UTF-8
Python
false
false
1,274
py
# coding: utf-8 ''' ----------------------------------------------------------------------------- Copyright 2015 Esri 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. ----------------------------------------------------------------------------- ================================================== VisibilityDataPrepToolsTestSuite.py -------------------------------------------------- * ArcGIS Desktop 10.X+ or ArcGIS Pro 1.X+ * Python 2.7 or Python 3.4 author: ArcGIS Solutions company: Esri ================================================== description: This test suite collects all of the test cases for the Visibility Data Prep Tools toolboxes: ================================================== history: <date> - <initals> - <modifications> ================================================== '''
[ "mfunk@esri.com" ]
mfunk@esri.com
fb8592e0e861914b0b99b4c905db34c43e5a08c8
e87d0cee1ce41124a808000850d4af5c7cd04f08
/mark/装饰器/sort改进.py
dea985ce7ebbc0745adb39f2a0de44548fd40082
[]
no_license
thinkingjxj/Python
0e8e5f60874c23a30aa8f54412fcf63c453f412a
9e92717b7871083c833612d220d1991d8d906275
refs/heads/master
2021-07-05T23:09:03.610678
2018-12-07T03:39:50
2018-12-07T03:39:50
148,290,201
0
0
null
null
null
null
UTF-8
Python
false
false
2,176
py
lst = [4, 1, 6, 8, 3, 9, 5] def sort(iterable, reverse=False): new = [] for x in iterable: for i, y in enumerate(new): flag = x > y if reverse else x < y if flag: new.insert(i, x) break else: new.append(x) return new print(1, sort(lst)) def sort(iterable, reverse=False): new = [] for x in iterable: for i, y in enumerate(new): flag = x > y if not reverse else x < y if flag: new.insert(i, x) break else: new.append(x) return new print(2, sort(lst)) def sort(iterable, reverse=False): def comp(a, b): flag = a > b if not reverse else a < b return flag new = [] for x in iterable: for i, y in enumerate(new): if comp(x, y): new.insert(i, x) break else: new.append(x) return new def sort(iterable, reverse=False): def comp(a, b): return a > b if not reverse else a < b new = [] for x in iterable: for i, y in enumerate(new): if comp(x, y): new.insert(i, x) break else: new.append(x) return new def comp(a, b, reverse=False): return a > b if not reverse else a < b def sort(iterable): new = [] for x in iterable: for i, y in enumerate(new): if comp(x, y, reverse=False): new.insert(i, x) break else: new.append(x) return new def comp(a, b): return a > b def sort(iterable, key=comp, reverse=False): new = [] for x in iterable: for i, y in enumerate(new): if comp(x, y): new.insert(i, x) break else: new.append(x) return new def sort(iterable, key=lambda a, b: a < b, reverse=False): new = [] for x in iterable: for i, y in enumerate(new): if key(x, y): new.insert(i, x) break else: new.append(x) return new
[ "thinkingjxj@users.noreply.github.com" ]
thinkingjxj@users.noreply.github.com
93721cd2e823ee88f70a194edd43ef814f82160b
ee0c8cc7b86d4dc41469aae59e3632102fedfdb1
/mysite/blog/forms.py
a59512aba992f8bfe4189065a04edc6bc5ede81e
[]
no_license
Hamza-abughazaleh/blog-django
1a177aa00d86a34cc49c6ee39f2b068d291a4f12
3a4b43b58beb25054e5798f219d7175629009138
refs/heads/master
2021-07-20T07:00:37.651344
2017-10-25T12:15:58
2017-10-25T12:15:58
108,093,782
0
0
null
2017-10-25T12:19:14
2017-10-24T07:44:17
Python
UTF-8
Python
false
false
690
py
from django import forms from blog.models import Post,Comment class PostForm(forms.ModelForm): class Meta(): model = Post fields = ('author','title','text') widgets = { 'title' : forms.TextInput(attrs={'class':'textinputclass'}), 'text' : forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent'}) } class CommentForm(forms.ModelForm): class Meta(): model = Comment fields = ('author','text') widgets = { 'author' : forms.TextInput(attrs={'class':'textinputclass'}), 'text' : forms.Textarea(attrs={'class':'editable medium-editor-textarea'}) }
[ "hamzaabughazaleh23@gmail.com" ]
hamzaabughazaleh23@gmail.com
5d6d354b1359f8d7e8a575a73c06cc26fcfff920
72316a1d1a2e0358486d50aeecbac8219ccdf092
/ietf/utils/aliases.py
edfce0b067795e18127bc2f6ebe1df4accdbbe5b
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
algby/ietfdb
363541941bd6e806bed70891bed4c7f47c9f0539
9ff37e43abbecac873c0362b088a6d9c16f6eed2
refs/heads/master
2021-01-16T18:57:50.100055
2014-09-29T21:16:55
2014-09-29T21:16:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,162
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- # # $Id: aliasutil.py $ # # Author: Markus Stenberg <mstenber@cisco.com> # """ Mailing list alias dumping utilities """ from django.conf import settings def rewrite_email_address(email): """ Prettify the email address (and if it's empty, skip it by returning None). """ if not email: return email = email.strip() if not email: return if email[0]=='<' and email[-1] == '>': email = email[1:-1] # If it doesn't look like email, skip if '@' not in email and '?' not in email: return return email def rewrite_address_list(l): """ This utility function makes sure there is exactly one instance of an address within the result list, and preserves order (although it may not be relevant to start with) """ h = {} for address in l: #address = address.strip() if h.has_key(address): continue h[address] = True yield address def dump_sublist(afile, vfile, alias, emails): if not emails: return emails # Nones in the list should be skipped emails = filter(None, emails) # Make sure emails are sane and eliminate the Nones again for # non-sane ones emails = [rewrite_email_address(e) for e in emails] emails = filter(None, emails) # And we'll eliminate the duplicates too but preserve order emails = list(rewrite_address_list(emails)) if not emails: return emails try: virtualname = 'xalias-%s' % (alias, ) expandname = 'expand-%s' % (alias) aliasaddr = '%s@ietf.org' % (alias, ) vfile.write('%-64s %s\n' % (aliasaddr, virtualname)) afile.write('%-64s "|%s filter %s"\n' % (virtualname+':', settings.POSTCONFIRM_PATH, expandname)) afile.write('%-64s %s\n' % (expandname+':', ', '.join(emails))) except UnicodeEncodeError: # If there's unicode in email address, something is badly # wrong and we just silently punt # XXX - is there better approach? print '# Error encoding', alias, repr(emails) return [] return emails
[ "henrik@levkowetz.com@7b24d068-2d4e-4fce-9bd7-cbd2762980b0" ]
henrik@levkowetz.com@7b24d068-2d4e-4fce-9bd7-cbd2762980b0
cd3f496c90a66b66218d79e1422aaae354538abc
52e53ee23573b1a50f892089d7418a16bf496422
/ARCADE/airborne/components/interfaces/gps_monitor/gps_monitor
1d899d880a1f89d5d0309d809130b1b1c0cad8e9
[]
no_license
jalishah/airborne
584bbf4a51f6a087a4295991c79702343f364af7
c374b775c608de9bf8f7152aa2c79bc9e1ecec6e
refs/heads/master
2020-04-11T08:03:16.624788
2013-09-17T12:04:47
2013-09-17T12:04:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
331
#!/usr/bin/env python import sys from gps_data_pb2 import GpsData from scl import generate_map socket = generate_map('gps_test')['gps'] gps_data = GpsData() print 'waiting for gps data' try: while True: str = socket.recv() gps_data.ParseFromString(str) print gps_data except: print 'terminated by user'
[ "tobias.simon@tu-ilmenau.de" ]
tobias.simon@tu-ilmenau.de
33fdc1a60605a67f79190f363ea143e287eb099a
29a18e048de426ed5cbea063774958680a24d3c8
/acm.py
93aeed49bd2f6a215057bc22d42ab02f60a427ba
[]
no_license
liliahache/kattis
de5d8e3482f6f8691354aa3fa2dc7fb9366b5d54
cd4fb965cbad498ac85c07987aad0db3479e31c4
refs/heads/master
2022-02-01T01:44:52.596099
2018-12-17T23:27:22
2018-12-17T23:27:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
631
py
import sys problems = dict() for line in map(str.strip, sys.stdin): if line != '-1': time, letter, result = line.split() if letter not in problems: problems[letter] = {'solved':False, 'time':0} if result == 'wrong' and not problems[letter]['solved']: problems[letter]['time'] += 20 elif result == 'right' and not problems[letter]['solved']: problems[letter]['solved'] = True problems[letter]['time'] += int(time) solved = [problems[p]['time'] for p in problems if problems[p]['solved']] print len(solved), sum(solved)
[ "pedrotari7@gmail.com" ]
pedrotari7@gmail.com
165419196495735d51fb2e3270b93287e7c575b2
d272b041f84bbd18fd65a48b42e0158ef6cceb20
/catch/datasets/eyach.py
075cca99426edd9c899b9e90af8fc1b82212d3fa
[ "MIT" ]
permissive
jahanshah/catch
bbffeadd4113251cc2b2ec9893e3d014608896ce
2fedca15f921116f580de8b2ae7ac9972932e59e
refs/heads/master
2023-02-19T13:30:13.677960
2021-01-26T03:41:10
2021-01-26T03:41:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,268
py
"""Dataset with 'Eyach virus' sequences. A dataset with 24 'Eyach virus' sequences. The virus is segmented and has 12 segments. Based on their strain and/or isolate, these sequences were able to be grouped into 2 genomes. Many genomes may have fewer than 12 segments. THIS PYTHON FILE WAS GENERATED BY A COMPUTER PROGRAM! DO NOT EDIT! """ import sys from catch.datasets import GenomesDatasetMultiChrom def seq_header_to_chr(header): import re c = re.compile(r'\[segment (1|10|11|12|2|3|4|5|6|7|8|9)\]') m = c.search(header) if not m: raise Exception("Unknown or invalid segment in header %s" % header) seg = m.group(1) return "segment_" + seg def seq_header_to_genome(header): import re c = re.compile(r'\[genome (.+)\]') m = c.search(header) if not m: raise Exception("Unknown genome in header %s" % header) return m.group(1) chrs = ["segment_" + seg for seg in ['1', '10', '11', '12', '2', '3', '4', '5', '6', '7', '8', '9']] ds = GenomesDatasetMultiChrom(__name__, __file__, __spec__, chrs, seq_header_to_chr, seq_header_to_genome=seq_header_to_genome) ds.add_fasta_path("data/eyach.fasta.gz", relative=True) sys.modules[__name__] = ds
[ "hmetsky@gmail.com" ]
hmetsky@gmail.com
effb18385de7cb5028c07a7bc626515f7186276c
1bf9f6b0ef85b6ccad8cb029703f89039f74cedc
/src/dnc/azext_dnc/manual/tests/latest/preparers.py
53aa6614e7eb6af55ac6829dfef768e3bd1fbe08
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
VSChina/azure-cli-extensions
a1f4bf2ea4dc1b507618617e299263ad45213add
10b7bfef62cb080c74b1d59aadc4286bd9406841
refs/heads/master
2022-11-14T03:40:26.009692
2022-11-09T01:09:53
2022-11-09T01:09:53
199,810,654
4
2
MIT
2020-07-13T05:51:27
2019-07-31T08:10:50
Python
UTF-8
Python
false
false
4,962
py
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import os from datetime import datetime from azure.cli.testsdk.scenario_tests import SingleValueReplacer from azure.cli.testsdk.preparers import NoTrafficRecordingPreparer from azure.cli.testsdk.exceptions import CliTestError from azure.cli.testsdk.reverse_dependency import get_dummy_cli KEY_RESOURCE_GROUP = 'rg' KEY_VIRTUAL_NETWORK = 'vnet' KEY_VNET_SUBNET = 'subnet' KEY_VNET_NIC = 'nic' class VirtualNetworkPreparer(NoTrafficRecordingPreparer, SingleValueReplacer): def __init__(self, name_prefix='clitest.vn', parameter_name='virtual_network', resource_group_name=None, resource_group_key=KEY_RESOURCE_GROUP, dev_setting_name='AZURE_CLI_TEST_DEV_VIRTUAL_NETWORK_NAME', random_name_length=24, key=KEY_VIRTUAL_NETWORK): if ' ' in name_prefix: raise CliTestError( 'Error: Space character in name prefix \'%s\'' % name_prefix) super(VirtualNetworkPreparer, self).__init__( name_prefix, random_name_length) self.cli_ctx = get_dummy_cli() self.parameter_name = parameter_name self.key = key self.resource_group_name = resource_group_name self.resource_group_key = resource_group_key self.dev_setting_name = os.environ.get(dev_setting_name, None) def create_resource(self, name, **_): if self.dev_setting_name: return {self.parameter_name: self.dev_setting_name, } if not self.resource_group_name: self.resource_group_name = self.test_class_instance.kwargs.get( self.resource_group_key) if not self.resource_group_name: raise CliTestError("Error: No resource group configured!") tags = {'product': 'azurecli', 'cause': 'automation', 'date': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')} if 'ENV_JOB_NAME' in os.environ: tags['job'] = os.environ['ENV_JOB_NAME'] tags = ' '.join(['{}={}'.format(key, value) for key, value in tags.items()]) template = 'az network vnet create --resource-group {} --name {} --subnet-name default --tag ' + tags self.live_only_execute(self.cli_ctx, template.format( self.resource_group_name, name)) self.test_class_instance.kwargs[self.key] = name return {self.parameter_name: name} def remove_resource(self, name, **_): # delete vnet if test is being recorded and if the vnet is not a dev rg if not self.dev_setting_name: self.live_only_execute( self.cli_ctx, 'az network vnet delete --name {} --resource-group {}'.format(name, self.resource_group_name)) class VnetSubnetPreparer(NoTrafficRecordingPreparer, SingleValueReplacer): def __init__(self, name_prefix='clitest.vn', parameter_name='subnet', resource_group_key=KEY_RESOURCE_GROUP, vnet_key=KEY_VIRTUAL_NETWORK, address_prefixes="11.0.0.0/24", dev_setting_name='AZURE_CLI_TEST_DEV_VNET_SUBNET_NAME', key=KEY_VNET_SUBNET): if ' ' in name_prefix: raise CliTestError( 'Error: Space character in name prefix \'%s\'' % name_prefix) super(VnetSubnetPreparer, self).__init__(name_prefix, 15) self.cli_ctx = get_dummy_cli() self.parameter_name = parameter_name self.key = key self.resource_group = [resource_group_key, None] self.vnet = [vnet_key, None] self.address_prefixes = address_prefixes self.dev_setting_name = os.environ.get(dev_setting_name, None) def create_resource(self, name, **_): if self.dev_setting_name: return {self.parameter_name: self.dev_setting_name, } if not self.resource_group[1]: self.resource_group[1] = self.test_class_instance.kwargs.get( self.resource_group[0]) if not self.resource_group[1]: raise CliTestError("Error: No resource group configured!") if not self.vnet[1]: self.vnet[1] = self.test_class_instance.kwargs.get(self.vnet[0]) if not self.vnet[1]: raise CliTestError("Error: No vnet configured!") self.test_class_instance.kwargs[self.key] = 'default' return {self.parameter_name: name} def remove_resource(self, name, **_): pass
[ "noreply@github.com" ]
VSChina.noreply@github.com
d21e8fa14b9a62887e0214c8d267414541c86784
cafa52c05f020af31985cfd1b8e2c676ea6e3baa
/lib/Chipseq/croo.py
8bd340dd55c88a7b03738de398e054961eebce23
[ "Apache-2.0" ]
permissive
shengqh/ngsperl
cd83cb158392bd809de5cbbeacbcfec2c6592cf6
9e418f5c4acff6de6f1f5e0f6eac7ead71661dc1
refs/heads/master
2023-07-10T22:51:46.530101
2023-06-30T14:53:50
2023-06-30T14:53:50
13,927,559
10
9
Apache-2.0
2018-09-07T15:52:27
2013-10-28T14:07:29
Perl
UTF-8
Python
false
false
2,231
py
import argparse import glob import logging import os DEBUG=False NotDEBUG=not DEBUG parser = argparse.ArgumentParser(description="Perform croo to retrive wdl result.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--input', action='store', nargs='?', help='Input wdl result folder', required=NotDEBUG) parser.add_argument('-n', '--name', action='store', nargs='?', help='Input sample name', required=NotDEBUG) parser.add_argument('-o', '--output', action='store', nargs='?', help="Output folder", required=NotDEBUG) parser.add_argument('--croo', action='store', nargs='?', default="croo", help='Input croo command', required=NotDEBUG) parser.add_argument('--out_def_json', action='store', nargs='?', default="croo", help='Input output definition JSON file for a WDL file', required=NotDEBUG) args = parser.parse_args() if DEBUG: args.input = "/workspace/shengq2/20210522_atacseq_6314_human_encode/encode_atacseq/result/IFNg_Rep_1/atac" args.name = "IFNg_Rep_1" args.output = "/workspace/shengq2/20210522_atacseq_6314_human_encode/encode_atacseq_croo/result/IFNg_Rep_1" args.croo = "singularity exec -c -B /gpfs52/data:/data,/workspace -e /data/cqs/softwares/singularity/cqs_encode.sif croo" args.out_def_json = "/data/cqs/softwares/encode/atac-seq-pipeline/atac.croo.v5.json" logger = logging.getLogger('croo') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)-8s - %(message)s') subfolders = [ f.path for f in os.scandir(args.input) if f.is_dir() ] metafiles = [os.path.join(sf, "metadata.json") for sf in subfolders if os.path.exists(os.path.join(sf, "metadata.json"))] if len(metafiles) > 1: raise Exception("Multiple metadata.json found: %s" % ",".join(metafiles)) elif len(metafiles) == 0: raise Exception("No metadata.json found: %s" % args.input) cmd = "%s --method copy --out-dir %s %s" % (args.croo, args.output, metafiles[0]) logger.info(cmd) os.system(cmd) bamfiles = glob.glob(args.output + "/**/*.bam", recursive = True) for bamfile in bamfiles: cmd = "samtools index %s " % bamfile logger.info(cmd) os.system(cmd) logger.info("done")
[ "shengqh@gmail.com" ]
shengqh@gmail.com
2df691e03048b0c0af2533b7324898f4e1754d64
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03804/s751492495.py
cb9208249e76e540c4b8a33202d935417cb92369
[]
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
309
py
n, m = map(int,input().split()) a = [input() for _ in range(n)] b = [input() for _ in range(m)] for i in range(n - m + 1): for j in range(n - m + 1): for k in range(m): #print(a[i+k][j:j+m], b[k]) if a[i+k][j:j+m] != b[k]: break else: print('Yes') exit() print('No')
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
82ba3fd7d3c8dcd9a1e0351bd94c388c06d779c4
876b629258e3752c7986807c48e7cf82c93832f0
/python/mltraining/linear_regression/exponential_regression.py
88c36dd208b692e775136988164f26600818f2d3
[ "MIT" ]
permissive
imjoseangel/100-days-of-code
45f736b0e529f504926faded6b3a18bc05719698
bff90569033e2b02a56e893bd45727125962aeb3
refs/heads/devel
2022-05-02T16:10:59.273585
2022-03-20T12:19:05
2022-03-20T12:19:05
174,882,423
3
4
MIT
2022-03-20T12:19:06
2019-03-10T21:20:43
HTML
UTF-8
Python
false
false
623
py
import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split # Create a data set for analysis x, y = make_regression(n_samples=500, n_features=1, noise=25, random_state=0) y = np.exp((y + abs(y.min())) / 75) # Split the data set into testing and training data x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=0) # Plot the data sns.set_style("darkgrid") sns.regplot(x_test, y_test, fit_reg=False) # Remove ticks from the plot plt.xticks([]) plt.yticks([]) plt.tight_layout() plt.show()
[ "noreply@github.com" ]
imjoseangel.noreply@github.com
75ecc7d1b2fa59f883577bd379697ee9b13b6bd6
ce07ccf78739a768971f393222fdca4a56315241
/employee_management/employee_management/report/wallet_transaction_vivek_report/wallet_transaction_vivek_report.py
f1b2c22ab35a29b5703d75b0d2bdc844066d6ca5
[ "MIT" ]
permissive
Gdinesh03/Frappe
563e0ddbe925be536f65f925787ed321a6098c0d
efd2d1568b6f5b8a4e0ff31e06a415c717a3d32a
refs/heads/master
2023-08-27T19:24:12.024442
2021-09-14T07:04:27
2021-09-14T07:04:27
406,260,373
0
0
null
null
null
null
UTF-8
Python
false
false
964
py
# Copyright (c) 2013, Gopi and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe def execute(filters=None): columns, data = [], [] if not filters: filters={} columns=get_columns() data=customer_report(filters) return columns, data, None, def get_columns(): columns = [ "Customer Name" +":Data:120", "Payment Status" + ":Data:120", # "Shipping Status" + ":Data:120", "Date" + ":Date:120", "Amount" + ":Data:120" ] return columns def customer_report(filters): condition='' if filters.get('customer_name'): condition+=' and customer_name ="%s"' % filters.get('customer_name') if filters.get('payment_type'): condition+=' and payment_type ="%s"' % filters.get('payment_type') string = frappe.db.sql('''select customer_name,payment_type,date,amount from `tabWallet Transaction Vivek` where docstatus=1 {condition}'''.format(condition=condition),as_list=1) return string
[ "vivekananthan112599@gmail.com" ]
vivekananthan112599@gmail.com
8c853fb9a3d4490455aa94d70d2632b9b7e9f71e
536538af28cfe40e10ff1ce469cd0f81e8b3a8fe
/populating_next_right_pointers_in_each_node_II.py
4c6ade6a23ab25051cb6f92917848860ec9d358b
[]
no_license
ShunKaiZhang/LeetCode
7e10bb4927ba8581a3a7dec39171eb821c258c34
ede2a2e19f27ef4adf6e57d6692216b8990cf62b
refs/heads/master
2021-09-01T07:41:03.255469
2017-12-25T19:22:18
2017-12-25T19:22:18
104,136,129
0
0
null
null
null
null
UTF-8
Python
false
false
1,344
py
# python3 # Follow up for problem "Populating Next Right Pointers in Each Node". # What if the given tree could be any binary tree? Would your previous solution still work? # Note: # You may only use constant extra space. # For example, # Given the following binary tree, # 1 # / \ # 2 3 # / \ \ # 4 5 7 # After calling your function, the tree should look like: # 1 -> NULL # / \ # 2 -> 3 -> NULL # / \ \ # 4-> 5 -> 7 -> NULL # My solution # Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): level_next = {} def search(node, level): if node is None: return if level not in level_next: node.next = None else: node.next = level_next[level] level_next[level] = node search(node.right, level + 1) search(node.left, level + 1) return if root is None: return None search(root, 0)
[ "noreply@github.com" ]
ShunKaiZhang.noreply@github.com
7a190e07ebcd6540f99582f00f9779afe5ab9716
ca308829e5e43619a736e98b00ae0297f57e3d5c
/tests/_rooster_tests.py
f6c83d3f756ce7c38854d20e10a9049a43066473
[ "MIT", "BSD-2-Clause" ]
permissive
aa1830/snipe
b4a151cf308004ca31243355a51457ba440360b9
5193ed31b43dc1b6eb5913966b8a7f0b1483642d
refs/heads/master
2020-06-28T01:33:08.758403
2018-04-27T20:14:31
2018-04-27T20:14:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,651
py
#!/usr/bin/python3 # -*- encoding: utf-8 -*- # Copyright © 2017 the Snipe contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. ''' Unit tests for rooster backend backend ''' import unittest import sys sys.path.append('..') sys.path.append('../lib') import snipe._rooster as rooster # noqa: E402,F401 class TestRooster(unittest.TestCase): def test_null(self): pass
[ "kcr@1ts.org" ]
kcr@1ts.org
b4e34535beb155e2f12a9bd88cb18922c343dae4
0c1d6b8dff8bedfffa8703015949b6ca6cc83f86
/lib/worklists/operator/CT/v3.0/business/ADSL_2LAN/IPTV_Enable/script.py
239d0f5d606aae2a2351a300200d9ef17e72cb09
[]
no_license
samwei8/TR069
6b87252bd53f23c37186c9433ce4d79507b8c7dd
7f6b8d598359c6049a4e6cb1eb1db0899bce7f5c
refs/heads/master
2021-06-21T11:07:47.345271
2017-08-08T07:14:55
2017-08-08T07:14:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,245
py
#coding:utf-8 # -----------------------------rpc -------------------------- import os import sys #debug DEBUG_UNIT = False if (DEBUG_UNIT): g_prj_dir = os.path.dirname(__file__) parent1 = os.path.dirname(g_prj_dir) parent2 = os.path.dirname(parent1) parent3 = os.path.dirname(parent2) parent4 = os.path.dirname(parent3) # tr069v3\lib parent5 = os.path.dirname(parent4) # tr069v3\ sys.path.insert(0, parent4) sys.path.insert(0, os.path.join(parent4, 'common')) sys.path.insert(0, os.path.join(parent4, 'worklist')) sys.path.insert(0, os.path.join(parent4, 'usercmd')) sys.path.insert(0, os.path.join(parent5, 'vendor')) from TR069.lib.common.event import * from TR069.lib.common.error import * from time import sleep import TR069.lib.common.logs.log as log g_prj_dir = os.path.dirname(__file__) parent1 = os.path.dirname(g_prj_dir) parent2 = os.path.dirname(parent1) # dir is system try: i = sys.path.index(parent2) if (i !=0): # stratege= boost priviledge sys.path.pop(i) sys.path.insert(0, parent2) except Exception,e: sys.path.insert(0, parent2) import _Common reload(_Common) from _Common import * import _IPTVEnable reload(_IPTVEnable) from _IPTVEnable import IPTVEnable def test_script(obj): """ """ sn = obj.sn # 取得SN号 DeviceType = "ADSL" # 绑定tr069模板类型.只支持ADSL\LAN\EPON三种 AccessMode = 'PPPoE_Bridged' # WAN接入模式,可选PPPoE_Bridge,PPPoE,DHCP,Static rollbacklist = [] # 存储工单失败时需回退删除的实例.目前缺省是不开启回退 # 初始化日志 obj.dict_ret.update(str_result=u"开始执行工单:%s........\n" % os.path.basename(os.path.dirname(__file__))) # data传参 PVC_OR_VLAN = obj.dict_data.get("PVC_OR_VLAN")[0] # ADSL上行只关心PVC值,LAN和EPON上行则关心VLAN值 X_CT_COM_MulticastVlan = obj.dict_data.get("X_CT_COM_MulticastVlan")[0] # 新增公共组播VLAN的下发 WANEnable_Switch = obj.dict_data.get("WANEnable_Switch")[0] # IPTV节点参数 dict_root = {'IGMPEnable':[1, '1'], 'ProxyEnable':[0, 'Null'], 'SnoopingEnable':[0, 'Null']} # WANDSLLinkConfig节点参数 if PVC_OR_VLAN == "": PVC_OR_VLAN_flag = 0 else: PVC_OR_VLAN_flag = 1 dict_wanlinkconfig = {'Enable':[1, '1'], 'DestinationAddress':[PVC_OR_VLAN_flag, PVC_OR_VLAN], 'LinkType':[1, 'EoA'], 'X_CT-COM_VLAN':[0, 'Null']} # WANPPPConnection节点参数 # 注意:X_CT-COM_IPMode节点有些V4版本没有做,所以不能使能为1.实际贝曼工单也是没有下发的 LAN2 = 'InternetGatewayDevice.LANDevice.1.LANEthernetInterfaceConfig.2' # 绑字到LAN2 if X_CT_COM_MulticastVlan == "": X_CT_COM_MulticastVlan_flag = 0 else: X_CT_COM_MulticastVlan_flag = 1 dict_wanpppconnection = {'Enable':[1, '1'], 'ConnectionType':[1, 'PPPoE_Bridged'], 'Name':[0, 'Null'], 'Username':[0, 'Null'], 'Password':[0, 'Null'], 'X_CT-COM_LanInterface':[1, LAN2], 'X_CT-COM_ServiceList':[1, 'OTHER'], 'X_CT-COM_LanInterface-DHCPEnable':[0, 'Null'], 'X_CT-COM_MulticastVlan':[X_CT_COM_MulticastVlan_flag, X_CT_COM_MulticastVlan]} # WANIPConnection节点参数 dict_wanipconnection = {} # 执行IPTV开通工单 ret, ret_data = IPTVEnable(obj, sn, WANEnable_Switch, DeviceType, AccessMode, PVC_OR_VLAN, dict_root, dict_wanlinkconfig, dict_wanpppconnection, dict_wanipconnection, change_account=1, rollbacklist=rollbacklist) # 将工单脚本执行结果返回到OBJ的结果中 obj.dict_ret.update(str_result=obj.dict_ret["str_result"] + ret_data) # 如果执行失败,统一调用回退机制(缺省是关闭的) if ret == ERR_FAIL: ret_rollback, ret_data_rollback = rollback(sn, rollbacklist, obj) obj.dict_ret.update(str_result=obj.dict_ret["str_result"] + ret_data_rollback) info = u"工单:%s执行结束\n" % os.path.basename(os.path.dirname(__file__)) obj.dict_ret.update(str_result=obj.dict_ret["str_result"] + info) return ret if __name__ == '__main__': log_dir = g_prj_dir log.start(name="nwf", directory=log_dir, level="DebugWarn") log.set_file_id(testcase_name="tr069") obj = MsgWorklistExecute(id_="1") obj.sn = "201303051512" dict_data= {"PVC_OR_VLAN":("PVC:0/65","1"),"WANEnable_Switch":("1","2")} obj.dict_data = dict_data try: ret = test_script(obj) if ret == ERR_SUCCESS: print u"测试成功" else: print u"测试失败" print "****************************************" print obj.dict_ret["str_result"] except Exception, e: print u"测试异常"
[ "zhaojunhhu@gmail.com" ]
zhaojunhhu@gmail.com
1ed500d2092c41452a46ad59d7b79b34563f3689
72a9d5019a6cc57849463fc315eeb0f70292eac8
/Python-Programming/1- Data_Type/Data_type.py
dbd356e19b44c537485ec8d44ca7bc376d8d3e93
[]
no_license
lydiawawa/Machine-Learning
393ce0713d3fd765c8aa996a1efc9f1290b7ecf1
57389cfa03a3fc80dc30a18091629348f0e17a33
refs/heads/master
2020-03-24T07:53:53.466875
2018-07-22T23:01:42
2018-07-22T23:01:42
142,578,611
1
0
null
2018-07-27T13:08:47
2018-07-27T13:08:47
null
UTF-8
Python
false
false
2,269
py
# %%%%%%%%%%%%% Python %%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%% Authors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Dr. Martin Hagan----->Email: mhagan@okstate.edu # Dr. Amir Jafari------>Email: amir.h.jafari@okstate.edu # %%%%%%%%%%%%% Date: # V1 Jan - 01 - 2017 # V2 Sep - 29 - 2017 # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%% Base Python %%%%%%%%%%%%%%%%%%%%%%%%%%%% # ============================================================= # Integers print('Hello World!!!') print(2 + 2) print(2 - 2) print(2 ** 6) print(6 * 3) print(10%2) print(1/2) print(1.0/2.0) print('P' + 'y' + 't' + 'h' + 'o' + 'n') print('Answer to 2 + 2:', 2 + 2) # ============================================================= # Variable + Integers Var = 5 print('Variable = ', Var) print('Variable + 1 = ', Var + 1) print('Variable x Variable = ', Var * Var) print(type(1)) print(type(-1)) print(type(0.5)) print(type(1/2)) print(type(1.0/2.0)) # ============================================================= # Strings First_name = 'Amir' Sur_name = 'Jafari' print(len(First_name)) Full_name = First_name + Sur_name print(Full_name + ' !!!!') Convert_int_str = str(1) print(First_name.upper()) print(First_name.lower()) print(First_name.capitalize()) New_name = First_name.replace('Amir', 'Martin') + ' ' +Sur_name.replace('Jafari', 'Hagan') print(New_name) My_string = "Hello World!" print( My_string[4]) print( My_string.split(' ')) print( My_string.split('r')) # ============================================================= # Booleans Number_1 = True Number_0 = False type(Number_1) print(not Number_1) # ============================================================= # Logical operators Var = 1 Var2 = 2 print(Var > Var2) Var3 = Var > Var2 print(Var3) print(Var3 +1 ) print(Var == Var2) print(Var != Var2) print(Var < 2 and Var >2) # ============================================================= # Accessing Strings My_String = 'Amir Jafari' print(My_String[0]) print(My_String[0:1]) print(My_String[0:2]) print(My_String[::-1]) Find = My_String.find('Amir') print(Find) # ============================================================= # Useful Commands str(1) bool(1) int(False) float(False) float(1) str(1/2) int(1.2) str(True) str(None)
[ "amir.h.jafari@okstate.edu" ]
amir.h.jafari@okstate.edu
864b47b461ce61716749f79288c2a38ef0d853c7
10b5d73b4d53a15134fff6560156e5195963a25d
/tests/test_plan.py
09726946b398601a6f4a9972341cc496513d28e4
[]
no_license
tonyguesswho/Licencing-System
d7bb859016f59908f55a2443d8ee62b40756c7f1
27c80d29fcdb3b627df33370257b4362607345e8
refs/heads/master
2020-07-04T07:16:00.320238
2019-08-13T18:15:43
2019-08-13T21:47:34
202,199,970
0
0
null
null
null
null
UTF-8
Python
false
false
2,245
py
import unittest from plan import Plan from user import User from subscription import Subscription from app import single_plan, plus_plan from utils.db import database class PlanTest(unittest.TestCase): def setUp(self): self.user = User('Tony', 'Tony@test.com', 'password') self.plan = single_plan def test_create_plan(self): """Test creating a Plan object""" plan = Plan('Test', 50, 5) self.assertEqual('Test', plan.name) self.assertEqual(50, plan.price) self.assertEqual(5, plan.limit) def test_repr_method(self): """test repr method""" plan = Plan('Test', '50', 5) self.assertEqual(f'< Plan {plan.limit}>', str(plan)) def test_get_plan(self): """test getting plan associated with a subscription""" new_sub = Subscription(self.user, self.plan) result = new_sub.get_plan() self.assertEqual(result, new_sub.plan) def test_update_plan(self): """Test updating existing plan in a subscription""" self.user.authenticated = True self.user.subsrcibe_to_plan(single_plan) self.user.change_plan(plus_plan) self.assertIsInstance(database['subscriptions']['Tony@test.com'].plan, Plan) self.assertEqual(database['subscriptions']['Tony@test.com'].plan, plus_plan) self.assertEqual(database['subscriptions']['Tony@test.com'].plan.limit, plus_plan.limit) def test_change_plan_no_auth(self): """Test updating plan without authentication fails""" with self.assertRaises(ValueError) as error: self.user.change_plan(plus_plan) self.assertEqual('User is not authenticated', str(error.exception)) def test_change_plan_no_initial_plan(self): """Test using the change_plan method to create a new subscription/plan""" self.user.authenticated = True self.user.change_plan(single_plan) self.assertIsInstance(database['subscriptions']['Tony@test.com'].plan, Plan) self.assertEqual(database['subscriptions']['Tony@test.com'].plan, single_plan) self.assertEqual(database['subscriptions']['Tony@test.com'].plan.limit, single_plan.limit) if __name__ == '__main__': unittest.main()
[ "anthonyugwu234@gmail.com" ]
anthonyugwu234@gmail.com
d342a41c63df6d4cf2b8f0660392d08df7cea5d1
e7b98d027990b23a522b4811afc79251de5b28b0
/course/w21/2/Ins_Logistic_Regression.py
a16e23d0d7e7deb92ae77f4a5de4a07fd9c71eae
[]
no_license
eufmike/wu_data_bootcamp_code
122594eeb935d10bfdba1dfbc06d5df711328378
b90cc3f10d3fb256a8089609e6182465a01f7f20
refs/heads/master
2021-06-30T12:43:19.047349
2019-04-12T22:01:50
2019-04-12T22:01:50
141,653,570
0
1
null
null
null
null
UTF-8
Python
false
false
2,038
py
#%% [markdown] # # Logistic Regression # # Logistic Regression is a statistical method for predicting binary outcomes from data. # # Examples of this are "yes" vs "no" or "young" vs "old". # # These are categories that translate to probability of being a 0 or a 1 #%% [markdown] # We can calculate logistic regression by adding an activation function as the final step to our linear model. # # This converts the linear regression output to a probability. # %% # get_ipython().magic(u'matplotlib inline') import matplotlib.pyplot as plt import pandas as pd # %% [markdown] # Generate some data # %% from sklearn.datasets import make_blobs X, y = make_blobs(centers=2, random_state=42) print(f"Labels: {y[:10]}") print(f"Data: {X[:10]}") #%% # Visualizing both classes plt.scatter(X[:, 0], X[:, 1], c=y) #%% [markdown] # Split our data into training and testing #%% from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y) #%% [markdown] # Create a Logistic Regression Model #%% from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() classifier #%% [markdown] # Fit (train) or model using the training data #%% classifier.fit(X_train, y_train) #%% [markdown] # Validate the model using the test data #%% print(f"Training Data Score: {classifier.score(X_train, y_train)}") print(f"Testing Data Score: {classifier.score(X_test, y_test)}") #%% [markdown] # Make predictions #%% # Generate a new data point (the red circle) import numpy as np new_data = np.array([[-2, 6]]) plt.scatter(X[:, 0], X[:, 1], c=y) plt.scatter(new_data[0, 0], new_data[0, 1], c="r", marker="o", s=100) #%% # Predict the class (purple or yellow) of the new data point predictions = classifier.predict(new_data) print("Classes are either 0 (purple) or 1 (yellow)") print(f"The new point was classified as: {predictions}") #%% predictions = classifier.predict(X_test) pd.DataFrame({"Prediction": predictions, "Actual": y_test})
[ "sc2.shih@gmail.com" ]
sc2.shih@gmail.com
51f16a499c64119c9437564c782451e1ed56a5ae
c4576ed34ad1d9066c6d8dcf9e017ec345f23114
/locallibrary/catalog/migrations/0002_auto_20200117_0649.py
b7c785200143752993586b377dd263b39d7cc473
[]
no_license
aspiringguru/mdnDjangoLibraryDemo
14151d19bfc1240700e2f5b3613974df6b21174b
506038fd64719e5a4a9d174e76af4704e01b380a
refs/heads/master
2020-12-12T22:12:49.601036
2020-01-17T21:43:51
2020-01-17T21:43:51
234,243,169
0
0
null
null
null
null
UTF-8
Python
false
false
840
py
# Generated by Django 2.2.9 on 2020-01-17 06:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.CreateModel( name='Language', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text="Enter the book's natural language (e.g. English, French, Japanese etc.)", max_length=200)), ], ), migrations.AddField( model_name='book', name='language', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='catalog.Language'), ), ]
[ "bmatthewtaylor@gmail.com" ]
bmatthewtaylor@gmail.com
6dd18905cfda9e7744fbd346162d19b5c89f6784
e41651d8f9b5d260b800136672c70cb85c3b80ff
/Notification_System/temboo/Library/Google/Drive/Revisions/List.py
f6fef1063fba4694f614cfb1c7d5cdbaa004f587
[]
no_license
shriswissfed/GPS-tracking-system
43e667fe3d00aa8e65e86d50a4f776fcb06e8c5c
1c5e90a483386bd2e5c5f48f7c5b306cd5f17965
refs/heads/master
2020-05-23T03:06:46.484473
2018-10-03T08:50:00
2018-10-03T08:50:00
55,578,217
1
0
null
null
null
null
UTF-8
Python
false
false
4,623
py
# -*- coding: utf-8 -*- ############################################################################### # # List # Lists a file's revisions. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. # # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class List(Choreography): def __init__(self, temboo_session): """ Create a new instance of the List Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(List, self).__init__(temboo_session, '/Library/Google/Drive/Revisions/List') def new_input_set(self): return ListInputSet() def _make_result_set(self, result, path): return ListResultSet(result, path) def _make_execution(self, session, exec_id, path): return ListChoreographyExecution(session, exec_id, path) class ListInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the List Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth2 process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.) """ super(ListInputSet, self)._set_input('AccessToken', value) def set_ClientID(self, value): """ Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Google. Required unless providing a valid AccessToken.) """ super(ListInputSet, self)._set_input('ClientID', value) def set_ClientSecret(self, value): """ Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Google. Required unless providing a valid AccessToken.) """ super(ListInputSet, self)._set_input('ClientSecret', value) def set_Fields(self, value): """ Set the value of the Fields input for this Choreo. ((optional, string) Selector specifying a subset of fields to include in the response.) """ super(ListInputSet, self)._set_input('Fields', value) def set_FileID(self, value): """ Set the value of the FileID input for this Choreo. ((required, string) The ID of the file.) """ super(ListInputSet, self)._set_input('FileID', value) def set_RefreshToken(self, value): """ Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.) """ super(ListInputSet, self)._set_input('RefreshToken', value) class ListResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the List Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_NewAccessToken(self): """ Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.) """ return self._output.get('NewAccessToken', None) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Google.) """ return self._output.get('Response', None) class ListChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return ListResultSet(response, path)
[ "shriswissfed@gmail.com" ]
shriswissfed@gmail.com
e74a7f17a1f66d420fd2ded7b814e718433aa36a
a0c10f7e4bd5bed78915722cf1540d01ea05e3d0
/coreapp/models.py
726b73d5b1c76f2f11a6e7b2f4eb2b1a462d08d1
[]
no_license
jod35/MyMDB
54b4f162124350902eb8811aa313181f68085715
df3bde5753356963ad653a721897a5a04e571ed1
refs/heads/master
2020-12-12T23:36:32.363098
2020-01-16T08:14:26
2020-01-16T08:14:26
234,258,304
0
0
null
null
null
null
UTF-8
Python
false
false
661
py
from django.db import models class Movie(models.Model): NOT_RATED=0 RATED_G=1 RATED_PG=2 RATED_R=3 RATINGS=( (NOT_RATED,'NR - Not Rated'), (RATED_G,'G - General Audience'), (RATED_PG,'PG - Parental Guidance'), (NOT_RATED,'R - Restricted'), ) title=models.CharField(max_length=140) plot=models.TextField() year=models.PositiveIntegerField() ratings=models.IntegerField( choices=RATINGS, default=NOT_RATED ) runtime=models.IntegerField() website=models.URLField(blank=True) def __str__(self): return "{} {}".format(self.title,self.year)
[ "jodestrevin@gmail.com" ]
jodestrevin@gmail.com
34789906fdcd412187d4169895f0e6ad0c4645ff
72bc5502cd7c991075646cae98769fefd5702d50
/protogen/stalk_proto/reporter_pb2.pyi
5cb08a5094c9073f54472f057820b49a9f894ac1
[ "MIT" ]
permissive
peake100/stalkbroker-py
c9a337dcfe088b807b8fffc182e45b31486e2635
95bed6e6d89dc00b183b71d5d3fce7908c554ed9
refs/heads/master
2022-12-10T15:19:22.557382
2020-08-15T00:13:36
2020-08-15T00:13:36
256,074,008
0
0
MIT
2020-05-31T18:18:29
2020-04-16T01:03:23
Python
UTF-8
Python
false
false
156
pyi
# @generated by generate_proto_mypy_stubs.py. Do not edit! import sys from google.protobuf.message import Message as google___protobuf___message___Message
[ "b.peake@illuscio.com" ]
b.peake@illuscio.com
1f7154dd1ecd25675b63ec9c863c145945649d93
0581988cad7e0ea62a638d551548e409af1e5dc1
/20200523/TCP_Chat_Room_Windows_UI/Server/ui_server.py
29b4f4beb74d4ae71acc85653073cbc794f2590f
[]
no_license
Aimee888/python-20200513
7c1dff7d7f0fdea08e12735efeb2e889fedeee10
578c388be5582dc7f1556f95168adf0399b7ea1f
refs/heads/master
2023-01-06T10:21:35.014780
2020-11-03T01:07:04
2020-11-03T01:07:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,195
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_server.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
[ "961745931@qq.com" ]
961745931@qq.com
6557b4ad2373d14ba3d8ab0ed709e25a1b24e9c1
e309516495825212ca7dbecaac426c9357116554
/dpipe/medim/registration.py
5cbd78675984aaf79e7c044043380077e5c7d213
[ "MIT" ]
permissive
samokhinv/deep_pipe
547731e174a6f08be71a4c59ccef59c46960d8c8
9461b02f5f32c3e9f24490619ebccf417979cffc
refs/heads/master
2022-11-30T03:58:29.955375
2020-08-12T08:05:13
2020-08-12T08:05:13
286,951,953
0
0
MIT
2020-08-12T07:53:04
2020-08-12T07:53:03
null
UTF-8
Python
false
false
1,487
py
from os.path import join as jp import tempfile import numpy as np import nibabel as nib from nipype.interfaces.ants import RegistrationSynQuick def register_images(moving: np.ndarray, fixed: np.ndarray, transform_type: str = 'a', n_threads: int = 1) -> np.ndarray: """ Apply RegistrationSynQuick to the input images. Parameters ---------- moving: np.ndarray fixed: np.ndarray transform_type: str, optional | t: translation | r: rigid | a: rigid + affine (default) | s: rigid + affine + deformable syn | sr: rigid + deformable syn | b: rigid + affine + deformable b-spline syn | br: rigid + deformable b-spline syn n_threads: int, optional the number of threads used to apply the registration """ with tempfile.TemporaryDirectory() as tempdir: template_path = jp(tempdir, 'template.nii.gz') moving_path = jp(tempdir, 'moving.nii.gz') nib.save(nib.Nifti1Image(fixed, np.eye(4)), template_path) nib.save(nib.Nifti1Image(moving, np.eye(4)), moving_path) reg = RegistrationSynQuick() reg.inputs.fixed_image = template_path reg.inputs.moving_image = moving_path reg.inputs.num_threads = n_threads reg.inputs.transform_type = transform_type reg.inputs.output_prefix = jp(tempdir, 'transform') reg.run() return nib.load(jp(tempdir, 'transformWarped.nii.gz')).get_data()
[ "maxs987@gmail.com" ]
maxs987@gmail.com
7951b499b65677e48fd1f73f9eb7ca4a6279aee6
13d3a44447f6a7d8b0d61c2fb445fa6aa76c2f95
/stackdio/core/notifications/registry.py
5c214313868f3ac2dd0bd6d0bd3121e7bda326b4
[ "Apache-2.0" ]
permissive
stackdio/stackdio
6ba4ad6c2ef10a323cbd955e6d6d5bd7917c17c2
84be621705031d147e104369399b872d5093ef64
refs/heads/master
2021-04-09T16:36:38.220557
2018-08-13T18:25:29
2018-08-13T18:25:29
17,679,603
9
11
Apache-2.0
2020-03-19T17:21:45
2014-03-12T19:02:06
Python
UTF-8
Python
false
false
4,871
py
# -*- coding: utf-8 -*- # Copyright 2017, Digital Reasoning # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import unicode_literals from collections import namedtuple from django.conf import settings from django.db.models.base import ModelBase from django.http.request import HttpRequest from django.utils.encoding import iri_to_uri from rest_framework.request import Request from rest_framework.reverse import reverse from rest_framework.serializers import BaseSerializer from six.moves import urllib_parse as urllib from stackdio.core.config import StackdioConfigException NotifiableModelConfig = namedtuple('NotifiableModelConfig', ['serializer_class', 'url_name']) class DummyRequest(HttpRequest): def __init__(self, prod_url): super(DummyRequest, self).__init__() self.prod_url = prod_url def build_absolute_uri(self, location=None): if location is None: return None bits = urllib.urlsplit(location) if not (bits.scheme and bits.netloc): location = urllib.urljoin(self.prod_url, location) return iri_to_uri(location) def validate_model_class(model_class): if not isinstance(model_class, ModelBase): raise StackdioConfigException( 'Object %r is not a Model class.' % model_class) if model_class._meta.abstract: raise StackdioConfigException( 'The model %r is abstract, so it cannot be registered with ' 'actstream.' % model_class) if not model_class._meta.installed: raise StackdioConfigException( 'The model %r is not installed, please put the app "%s" in your ' 'INSTALLED_APPS setting.' % (model_class, model_class._meta.app_label)) return model_class def validate_serializer_class(serializer_class): if not issubclass(serializer_class, BaseSerializer): raise StackdioConfigException( 'Object %r is not a Serializer class.' % serializer_class) return serializer_class class NotifiableModelRegistry(dict): serializer_context = { 'request': Request(DummyRequest(settings.STACKDIO_CONFIG.server_url)), } def register(self, model_class, serializer_class, url_name): model_class = validate_model_class(model_class) serializer_class = validate_serializer_class(serializer_class) if model_class not in self: self[model_class] = NotifiableModelConfig(serializer_class, url_name) def get_notification_serializer(self, notification): from stackdio.core.notifications.serializers import AbstractNotificationSerializer model_class = notification.content_type.model_class() object_serializer_class = self.get_model_serializer_class(model_class) # Create a dynamic class that has the object set to the appropriate serializer class NotificationSerializer(AbstractNotificationSerializer): object = object_serializer_class(source='content_object') return NotificationSerializer(notification, context=self.serializer_context) def get_model_serializer_class(self, model_class): if model_class not in self: raise StackdioConfigException('Model %r is not registered with the ' 'notification registry.' % model_class) return self[model_class].serializer_class def get_object_serializer(self, content_object): serializer_class = self.get_model_serializer_class(content_object._meta.model) return serializer_class(content_object, context=self.serializer_context) def get_ui_url(self, content_object): model_class = content_object._meta.model if model_class not in self: raise StackdioConfigException('Model %r is not registered with the ' 'notification registry.' % model_class) url_name = self[model_class].url_name return reverse(url_name, request=self.serializer_context['request'], kwargs={'pk': content_object.pk}) registry = NotifiableModelRegistry() register = registry.register get_notification_serializer = registry.get_notification_serializer get_object_serializer = registry.get_object_serializer get_ui_url = registry.get_ui_url
[ "clark.perkins@digitalreasoning.com" ]
clark.perkins@digitalreasoning.com
aea5fc9607f3f9b87efbf7cf19f4f67fee7529db
09db6c4ff70cca176f2fbc667e66266a31fa440e
/apps/projects/admin.py
b3fd575fb9582b782634ff4b82e90089d68cf6a2
[ "MIT" ]
permissive
myhumankit/mytimetracker
e99c006edb06d5b10ce908049ded5bb8d3ffa55c
b9bdf5af2e7f85758d43f37b36c10884f0412d43
refs/heads/master
2023-04-29T23:50:27.606367
2019-11-19T14:51:57
2019-11-19T14:51:57
209,867,791
0
0
MIT
2023-04-21T20:38:20
2019-09-20T19:37:41
Python
UTF-8
Python
false
false
4,008
py
from django.contrib import admin from mptt.admin import DraggableMPTTAdmin from simple_history.admin import SimpleHistoryAdmin from projects.models import Location, Project, Activity, Leave, Resource, Capacity class LocationAdmin(SimpleHistoryAdmin): list_display = ("title", "comment", "id") class LeaveAdmin(SimpleHistoryAdmin): exclude = ("user",) list_display = ("id", "user", "type", "date", "duration", "comment") def get_queryset(self, request): qs = super(LeaveAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) def save_model(self, request, obj, form, change): if not change: obj.user = request.user super().save_model(request, obj, form, change) class ActivityAdmin(SimpleHistoryAdmin): exclude = ("user",) list_display = ( "id", "user", "project", "date", "duration", "progression", "is_teleworking", "is_business_trip", "location", ) def get_queryset(self, request): qs = super(ActivityAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) def save_model(self, request, obj, form, change): if not change: obj.user = request.user super().save_model(request, obj, form, change) class ActivityInline(admin.TabularInline): model = Activity fields = ( "id", "user", "project", "date", "duration", "progression", "is_teleworking", "is_business_trip", "location", ) readonly_fields = fields can_delete = False extra = 0 def get_queryset(self, request): qs = super(ActivityInline, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) class ResourceInline(admin.TabularInline): model = Resource fields = ("user", "project", "date", "duration", "comment") extra = 0 class ProjectAdmin(SimpleHistoryAdmin, DraggableMPTTAdmin): list_display = ("tree_actions", "indented_title", "comment", "id") list_display_links = ("indented_title",) inlines = [ResourceInline, ActivityInline] def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: print(instance) instance.save() formset.save_m2m() class ResourceAdmin(SimpleHistoryAdmin): exclude = ("user",) list_display = ("id", "user", "project", "date", "duration", "comment") def get_queryset(self, request): qs = super(ResourceAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) def save_model(self, request, obj, form, change): if not change: obj.user = request.user super().save_model(request, obj, form, change) class CapacityInline(admin.TabularInline): model = Capacity fields = ("user", "date", "duration", "comment") extra = 0 class CapacityAdmin(SimpleHistoryAdmin): exclude = ("user",) list_display = ("id", "user", "date", "duration", "comment") def get_queryset(self, request): qs = super(CapacityAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) def save_model(self, request, obj, form, change): if not change: obj.user = request.user super().save_model(request, obj, form, change) admin.site.register(Location, LocationAdmin) admin.site.register(Project, ProjectAdmin) admin.site.register(Activity, ActivityAdmin) admin.site.register(Leave, LeaveAdmin) admin.site.register(Resource, ResourceAdmin) admin.site.register(Capacity, CapacityAdmin)
[ "julien@lebunetel.com" ]
julien@lebunetel.com
db6c1fcc7c2e9399cbd6deaa8ee2d112b0cb898c
15afc6a3270d9b42cc84a788853ce46456be01f2
/section_ii/project_b/example/example_15/mpl_squares.py
45bc81e546238abb1e2d8a87e45e48bd12383f85
[]
no_license
xieqing0428/python_helloworld
161c90564638dc49e3a82a00607a762b36a39212
e08f63616aabe609ff1ac53b8e0ab32eaf2a472b
refs/heads/master
2020-04-16T11:01:37.918248
2019-02-14T07:19:09
2019-02-14T07:19:09
165,521,440
0
0
null
null
null
null
UTF-8
Python
false
false
488
py
# -*- coding:utf-8 -*- """ @author: Alessa0 @file: example_15.py @time: 2019-01-22 20:48 """ import matplotlib.pyplot as plt input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plt.plot(input_values, squares, linewidth=5) # 设置图表标题,并给坐标轴加上标签 plt.title("Square Numbers", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) # 设置刻度标记的大小 plt.tick_params(axis='both', labelsize=14) plt.show()
[ "849565690@qq.com" ]
849565690@qq.com
825bb8d2372f489f9368507af5f591f69517f001
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2378/60668/302915.py
d3fbbd4909e841f89709063f794ddfe1b79c3b81
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
453
py
def tree_17_local(m,n,s,k): if s=="1 2 8": print(8,end='') elif s=="1 2 13": print(32,end='') elif s=="1 2 5": print(15,end='') elif s=="1 3 3": if k=="1 6 1": print(25,end='') else:print(k) else: print(s) if __name__=='__main__': m,n = input().split() s = input() k = input() d = input() j = input() l = input() tree_17_local(int(m),int(n),s,l)
[ "1069583789@qq.com" ]
1069583789@qq.com
ad14adf6d06a381b56dbed4933f77e2d167fe623
b5e8cb4102965199b0c35c995591a0eca1b589f2
/프로그레머스/Level1/두개 뽑아서더하기.py
a8659d10b25ac3e6895e1be22edec8593c79cf61
[]
no_license
smilejakdu/leetcode_with_silva_mento
36af4d8242e700f8f47567c6fdc8eb116c44c0b1
09a2fe53befe3fa3b23eb7f14059b8d897fd53b5
refs/heads/master
2022-12-20T01:11:27.691518
2020-10-04T15:16:31
2020-10-04T15:16:31
283,961,081
0
0
null
null
null
null
UTF-8
Python
false
false
953
py
''':arg 정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요. numbers의 길이는 2 이상 100 이하입니다. numbers의 모든 수는 0 이상 100 이하입니다. numbers result [2,1,3,4,1] [2,3,4,5,6,7] [5,0,2,7] [2,5,7,9,12] ''' # numbers = [2, 1, 3, 4, 1] numbers = [5, 0, 2, 7] def solution(numbers): answer = [] for i in range(0, len(numbers)): for r in range(i + 1, len(numbers)): if not numbers[i] + numbers[r] in answer: answer.append(numbers[i] + numbers[r]) answer.sort() return answer ''':arg 다른사람 풀이 ''' def solution(numbers): return sorted( {numbers[i] + numbers[j] for i in range(len(numbers)) for j in range(len(numbers)) if i > j}) print(solution(numbers))
[ "ash982416@gmail.com" ]
ash982416@gmail.com
8eda5ec5410f3fbd05334a9373b1bcbc7f2371f3
148072ce210ca4754ea4a37d83057e2cf2fdc5a1
/src/core/w3af/w3af/plugins/attack/payloads/payloads/hostname.py
102ad20b04e92b675013d7442960f156788aea8e
[]
no_license
ycc1746582381/webfuzzer
8d42fceb55c8682d6c18416b8e7b23f5e430c45f
0d9aa35c3218dc58f81c429cae0196e4c8b7d51b
refs/heads/master
2021-06-14T18:46:59.470232
2017-03-14T08:49:27
2017-03-14T08:49:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,225
py
import re from w3af.plugins.attack.payloads.base_payload import Payload from w3af.core.ui.console.tables import table class hostname(Payload): """ This payload shows the server hostname """ def api_read(self): result = {} result['hostname'] = [] values = [] values.append(self.shell.read('/etc/hostname')[:-1]) values.append(self.shell.read('/proc/sys/kernel/hostname')[:-1]) values = list(set(values)) values = [p for p in values if p != ''] result['hostname'] = values return result def api_win_read(self): result = {} result['hostname'] = [] def parse_iis6_log(iis6_log): root1 = re.findall('(?<=OC_COMPLETE_INSTALLATION:m_csMachineName=)(.*?) ', iis6_log, re.MULTILINE) root2 = re.findall('(?<=OC_QUEUE_FILE_OPS:m_csMachineName=)(.*?) ', iis6_log, re.MULTILINE) root3 = re.findall('(?<=OC_COMPLETE_INSTALLATION:m_csMachineName=)(.*?) ', iis6_log, re.MULTILINE) root = root1 + root2 + root3 if root: return root else: return [] def parse_certocm_log(certocm_log): hostname = re.search( '(?<=Set Directory Security:\\)(.*?)\\', certocm_log) if hostname: return '\\' + hostname.group(0) else: return '' hostnames = parse_iis6_log(self.shell.read('/windows/iis6.log')) hostnames += parse_certocm_log(self.shell.read('/windows/certocm.log')) hostnames = list(set(hostnames)) hostnames = [p for p in hostnames if p != ''] result['hostname'] = hostnames return result def run_read(self): api_result = self.api_read() if not api_result['hostname']: return 'Host name could not be identified.' else: rows = [] rows.append(['Hostname', ]) rows.append([]) for hostname in api_result['hostname']: rows.append([hostname, ]) result_table = table(rows) result_table.draw(80) return rows
[ "everping@outlook.com" ]
everping@outlook.com
9ac0f02a82eef6628f4229af2b726135e8012d50
60b48df762a515a734cfbedd7ca101df43f04824
/python/ray/data/impl/pipeline_executor.py
8fdaed897bb30c088d238f2afa41bdc8ad830696
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
LuBingtan/ray
a02b13c4dceab2b0d54870fd3abae5c11bae916e
298742d7241681ee1f307ec0dd3cd7e9713a3c7d
refs/heads/master
2023-03-05T16:32:35.596725
2022-06-05T23:21:53
2022-06-05T23:21:53
223,334,544
0
1
Apache-2.0
2023-03-04T08:56:53
2019-11-22T06:01:51
Python
UTF-8
Python
false
false
5,793
py
from typing import Any, Callable, List, Optional, TYPE_CHECKING import time import concurrent.futures import logging import ray from ray.data.context import DatasetContext from ray.data.dataset import Dataset, T from ray.data.impl.progress_bar import ProgressBar from ray.data.impl import progress_bar logger = logging.getLogger(__name__) if TYPE_CHECKING: from ray.data.dataset_pipeline import DatasetPipeline def pipeline_stage(fn: Callable[[], Dataset[T]]) -> Dataset[T]: # Force eager evaluation of all blocks in the pipeline stage. This # prevents resource deadlocks due to overlapping stage execution (e.g., # task -> actor stage). return fn().fully_executed() class PipelineExecutor: def __init__(self, pipeline: "DatasetPipeline[T]"): self._pipeline: "DatasetPipeline[T]" = pipeline self._stages: List[concurrent.futures.Future[Dataset[Any]]] = [None] * ( len(self._pipeline._optimized_stages) + 1 ) self._iter = iter(self._pipeline._base_iterable) self._pool = concurrent.futures.ThreadPoolExecutor( max_workers=len(self._stages) ) self._stages[0] = self._pool.submit( lambda n: pipeline_stage(n), next(self._iter) ) if self._pipeline._length and self._pipeline._length != float("inf"): length = self._pipeline._length else: length = 1 if self._pipeline._progress_bars: self._bars = [ ProgressBar("Stage {}".format(i), length, position=i) for i in range(len(self._stages)) ] else: self._bars = None def __del__(self): for f in self._stages: if f is not None: f.cancel() self._pool.shutdown(wait=False) # Signal to all remaining threads to shut down. with progress_bar._canceled_threads_lock: for t in self._pool._threads: if t.is_alive(): progress_bar._canceled_threads.add(t) # Wait for 1s for all threads to shut down. start = time.time() while time.time() - start < 1: self._pool.shutdown(wait=False) if not [t for t in self._pool._threads if t.is_alive()]: break if [t for t in self._pool._threads if t.is_alive()]: logger.info( "Failed to shutdown all DatasetPipeline execution threads. " "These threads will be destroyed once all current stages " "complete or when the driver exits" ) def __iter__(self): return self def __next__(self): output = None start = time.perf_counter() while output is None: if all(s is None for s in self._stages): raise StopIteration # Wait for any completed stages. pending = [f for f in self._stages if f is not None] ready, _ = concurrent.futures.wait(pending, timeout=0.1) # Bubble elements down the pipeline as they become ready. for i in range(len(self._stages))[::-1]: is_last = i + 1 >= len(self._stages) next_slot_free = is_last or self._stages[i + 1] is None if not next_slot_free: continue slot_ready = self._stages[i] in ready if not slot_ready: continue # Bubble. result = self._stages[i].result() if self._bars: self._bars[i].update(1) self._stages[i] = None if is_last: output = result else: self._stages[i + 1] = self._pool.submit( lambda r, fn: pipeline_stage(lambda: fn(r)), result, self._pipeline._optimized_stages[i], ) # Pull a new element for the initial slot if possible. if self._stages[0] is None: try: self._stages[0] = self._pool.submit( lambda n: pipeline_stage(n), next(self._iter) ) except StopIteration: pass self._pipeline._stats.wait_time_s.append(time.perf_counter() - start) self._pipeline._stats.add(output._plan.stats()) return output @ray.remote(num_cpus=0) class PipelineSplitExecutorCoordinator: def __init__( self, pipeline: "DatasetPipeline[T]", n: int, splitter: Callable[[Dataset], "DatasetPipeline[T]"], context: DatasetContext, ): DatasetContext._set_current(context) pipeline._optimize_stages() self.executor = PipelineExecutor(pipeline) self.n = n self.splitter = splitter self.cur_splits = [None] * self.n def next_dataset_if_ready(self, split_index: int) -> Optional[Dataset[T]]: # TODO(swang): This will hang if one of the consumers fails and is # re-executed from the beginning. To make this fault-tolerant, we need # to make next_dataset_if_ready idempotent. # Pull the next dataset once all splits are fully consumed. if all(s is None for s in self.cur_splits): ds = next(self.executor) self.cur_splits = self.splitter(ds) assert len(self.cur_splits) == self.n, (self.cur_splits, self.n) # Return the dataset at the split index once per split. ret = self.cur_splits[split_index] self.cur_splits[split_index] = None return ret def get_stats(self): return self.executor._pipeline._stats
[ "noreply@github.com" ]
LuBingtan.noreply@github.com
2efa37dc9c262a28dbac42705bb7457067a8f29a
40d978aa02335dd0cbab732dc4c8129aaf8590df
/term_sheet_generator_1173/settings.py
8ae02a9064ae45703b98df27ec4632a848e41df7
[]
no_license
crowdbotics-apps/term-sheet-generator-1173
ab35fa1798295c7d8a1ada395cd875bb9a351b99
86c2995f7dfa1bfbe3f1a90e04f1ea23bbca105c
refs/heads/master
2022-12-09T11:05:41.405844
2019-03-03T23:41:55
2019-03-03T23:41:55
173,643,543
0
0
null
2022-12-08T01:42:56
2019-03-03T23:40:17
Python
UTF-8
Python
false
false
4,612
py
""" Django settings for term_sheet_generator_1173 project. Generated by 'django-admin startproject' using Django 1.11.16. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'eb$b28$q)bqagzdoqff=n8%l-#o+@&x+myqu*%jy%9q7@82j%*' # 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', 'django.contrib.sites' ] 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 = 'term_sheet_generator_1173.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 = 'term_sheet_generator_1173.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' import environ env = environ.Env() ALLOWED_HOSTS = ['*'] SITE_ID = 1 MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DEBUG", default=False) if env.str("DATABASE_URL", default=None): DATABASES = { 'default': env.db() } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' LOCAL_APPS = [ 'home', ] THIRD_PARTY_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS # allauth ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = None LOGIN_REDIRECT_URL = '/' if DEBUG: # output email to console instead of sending EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" EMAIL_HOST = "smtp.sendgrid.net" EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "") EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "") EMAIL_PORT = 587 EMAIL_USE_TLS = True
[ "team@crowdbotics.com" ]
team@crowdbotics.com
099c4e2af0ac551a0ae579ae294358ef5b0e82a3
2dc8c387de8bf7a6bd7506bd128b9dfa2bc8a3e2
/0x05-python-exceptions/6-main.py~
df03a1652e5a941660b8acdf869fdf3a7c3c3f5a
[]
no_license
yasmineholb/holbertonschool-higher_level_programming
ab57f9aa718ad8ebeb927a49c007e0232b0125e6
ee66c781e9421a0dbf03795707572d9d1183e42e
refs/heads/master
2020-09-28T19:35:52.740417
2020-06-15T09:45:18
2020-06-15T09:45:18
226,847,521
0
0
null
null
null
null
UTF-8
Python
false
false
154
#!/usr/bin/python3 raise_exception_msg = __import__('6-raise_exception_msg').raise_exception_msg try: raise_exception_msg("C is fun") except NameErr
[ "1055@holbertonschool.com" ]
1055@holbertonschool.com
437ef66dc3ac0f7cf2e9efffac97408be8c83276
35109088e79989e8b0ca9d9ddadad1546eebc8e3
/AB/linux2/day20/code/03_mylist.py
1d6725b8fc9f0dfd48f26baa85172076a58f52d0
[]
no_license
ABCmoxun/AA
d0f8e18186325bfd832b26f3b71027d1dc8255b2
c2c4a5b6683555b5d6200730b789d6e655f64c7f
refs/heads/master
2020-03-25T11:11:54.882204
2020-03-03T05:19:07
2020-03-03T05:19:07
143,722,606
1
0
null
null
null
null
UTF-8
Python
false
false
621
py
# 02_mylist.py # 此示例示意复合赋值算术运算符的重载 class MyList: def __init__(self, iterable): self.data = [x for x in iterable] def __repr__(self): return 'MyList(%r)' % self.data def __add__(self, rhs): print("__add__方法被调用") return MyList(self.data + rhs.data) def __iadd__(self, rhs): print("__iadd__方法被调用") self.data.extend(rhs.data) return self L1 = MyList([1, 2, 3]) L2 = MyList(range(4, 7)) print("id(L1) =", id(L1)) L1 += L2 # 相当于 L1 = L1 + L2 print('L1 =', L1) print("id(L1) =", id(L1))
[ "1945568441@qq.com" ]
1945568441@qq.com
4e0edaf1cd36c0f931aac8d2103253e56aa72e17
52b5773617a1b972a905de4d692540d26ff74926
/.history/binary_20200524142534.py
267e8eb35d054308ed642c67fdebaceeb181260e
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,224
py
def solution(N): print(N) maximumCount = 0 number = format(9,"b") print("wow",number) s = [str(i) for i in number] binary = int("".join(s)) intialNumber = None lastNumber = None totalCount = 0 print("binary",number) for i in range(len(str(number))): if intialNumber is not None: print(intialNumber + int(number[i])) if number[i] == 1: if intialNumber is not None and maximumCount >0: print("count",maximumCount) else: intialNumber = 1 maximumCount = 0 if number[i] == 0: maximumCount +=1 # if i < len(number)-1: # if number[i] == 0 and number[i+1] : # lastNumber = 1 # if intialNumber is not None and lastNumber is not None and number[i] == 0: # maximumCount = maximumCount + 1 # else: # totalCount = maximumCount # maximumCount = 0 print("total",totalCount) solution(9)
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
78ffed87f713d3a8dc3b7f88d12dd15354d53019
11587d450eb274a4684a393bd1073ea7cf6e28bf
/codingtest/week13/sequential_sum.py
b370fa4b7d8f1ec52c12b19dc448e31e15d193df
[]
no_license
Greek-and-Roman-God/Athena
3b45869806ea06812e3d26661b159294fb49593b
73a3a24df9667402258bff038325fd31cca36cf1
refs/heads/main
2023-05-28T23:04:10.760717
2021-06-13T04:39:31
2021-06-13T04:39:31
308,242,740
0
1
null
null
null
null
UTF-8
Python
false
false
433
py
# 소수의 연속합 n=int(input()) temp=[True]*(n+1) end=round(n**0.5)+1 for i in range(2,end): if temp[i]: for j in range(i+i, n+1, i): temp[j]=False prime=[i for i in range(2, n+1) if temp[i]] cnt=0 for i in range(len(prime)): seq_sum=0 idx=i while seq_sum<=n and idx<=len(prime): if seq_sum==n: cnt+=1 break if idx==len(prime): break seq_sum+=prime[idx] idx+=1 print(cnt)
[ "yelin1106@naver.com" ]
yelin1106@naver.com
721e9268d352f8c85508d0063c8e61cf288831b9
feda93b7c67b60759bbff2ffd7f7bb2b71ed4bde
/convertToBase7.py
07bdb887ce8e9d15534b6541dbd7db599ef03175
[]
no_license
unsortedtosorted/codeChallenges
fcc8d92cc568922f2eb3b492c530e2e93d0e95ab
de8f9e7a7c45e325ac0de43a4e1f711a7c6a0a0c
refs/heads/master
2020-04-04T14:38:43.538723
2019-03-14T03:24:49
2019-03-14T03:24:49
156,006,456
0
0
null
null
null
null
UTF-8
Python
false
false
715
py
""" 7 : 10 7/7 --> div=1, rem=0 14 : 20 14/7 --> div=2, rem=0 100: 202 100/7 --> div=14, rem=2 14/7 --> div=2 , rem=0 151:304 152/7 --> div=22, rem=4 22 --> div=3, rem=2 """ class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ if num<7 and num > -7: return str(num) rem=8 s="" isNeg=False if num<0: num=num*(-1) isNeg=True while num>=7: div=num/7 rem=num-div*7 num=div s=str(rem)+s s=str(div)+s if isNeg: s="-"+s return (s)
[ "noreply@github.com" ]
unsortedtosorted.noreply@github.com
8483392f85338b9ab4a9e0aa3e6925ca401d927a
256fbfbc34952d60ebb1ce5cf92ba107f8d3e905
/backend/agalot_app_23898/urls.py
1479158011d81c28eeb290da27286e3ffb93a350
[]
no_license
crowdbotics-apps/agalot-app-23898
8a337647047d79589bd2533cf13dda168a776f8a
1fd14f5a1dc70a8c436e8a19c45164a3407d4a9d
refs/heads/master
2023-02-17T13:43:56.206704
2021-01-17T17:12:07
2021-01-17T17:12:07
330,443,006
0
0
null
null
null
null
UTF-8
Python
false
false
2,668
py
"""agalot_app_23898 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/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, include from allauth.account.views import confirm_email from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ path("", include("home.urls")), path("accounts/", include("allauth.urls")), path("modules/", include("modules.urls")), path("api/v1/", include("home.api.v1.urls")), path("admin/", admin.site.urls), path("users/", include("users.urls", namespace="users")), path("rest-auth/", include("rest_auth.urls")), # Override email confirm to use allauth's HTML view instead of rest_auth's API view path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email), path("rest-auth/registration/", include("rest_auth.registration.urls")), path("api/v1/", include("task.api.v1.urls")), path("task/", include("task.urls")), path("api/v1/", include("task_profile.api.v1.urls")), path("task_profile/", include("task_profile.urls")), path("api/v1/", include("tasker_business.api.v1.urls")), path("tasker_business/", include("tasker_business.urls")), path("api/v1/", include("location.api.v1.urls")), path("location/", include("location.urls")), path("api/v1/", include("wallet.api.v1.urls")), path("wallet/", include("wallet.urls")), path("api/v1/", include("task_category.api.v1.urls")), path("task_category/", include("task_category.urls")), path("home/", include("home.urls")), ] admin.site.site_header = "agalot app" admin.site.site_title = "agalot app Admin Portal" admin.site.index_title = "agalot app Admin" # swagger api_info = openapi.Info( title="agalot app API", default_version="v1", description="API documentation for agalot app App", ) schema_view = get_schema_view( api_info, public=True, permission_classes=(permissions.IsAuthenticated,), ) urlpatterns += [ path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs") ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
df1d048f17f5a566209ef32349cf25f4c9e2f754
be5ea20226c37d81f1ccb2f704d8825d36e88765
/09. Decorators/EXERCISE/07_execution_time.py
46206ea6d73977ddd8aef00da8cdfe89e906e747
[]
no_license
dimDamyanov/PythonOOP
3845e450e5a48fef4f70a186664e07c0cd60e09b
723204f5b7e953874fac9314e48eb1d1628d6ff5
refs/heads/main
2023-04-07T18:00:36.735248
2021-04-19T20:57:14
2021-04-19T20:57:14
341,329,346
0
0
null
null
null
null
UTF-8
Python
false
false
500
py
import time def exec_time(func): def wrapper(*args): start = time.time() func(*args) end = time.time() return end - start return wrapper @exec_time def loop(start, end): total = 0 for x in range(start, end): total += x return total print(loop(1, 10000000)) @exec_time def concatenate(strings): result = "" for string in strings: result += string return result print(concatenate(["a" for i in range(1000000)]))
[ "dim.damianov@gmail.com" ]
dim.damianov@gmail.com
162cb9aa4751a361be68509ebfa3fbe28df00f56
dd6b0635021185bf29f20b5b49ab03f93ff841e3
/BH_Mergers.py
24b202c99314f23f6630a06b5e31721bdede2d65
[]
no_license
sbustamante/Spinstractor
27754ee5506b929fb51d6af35852c4780873e960
d546010735fb698963b48b19a2e017060d13ef10
refs/heads/master
2021-01-22T02:05:00.969180
2018-10-30T09:13:39
2018-10-30T09:13:39
92,332,959
0
0
null
null
null
null
UTF-8
Python
false
false
2,537
py
#======================================================================================== # LIBRARIES #======================================================================================== import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import os import h5py import time plt.close('all') #======================================================================================== # PARAMETERS #======================================================================================== #Data folder DataFolder = '/home/bustamsn/bustamsn/cosmological_BH/Sims256/' #Simulation Simulation = 'cosmobh03' #Number of chunks (same number of used processors) N_proc = 256 #======================================================================================== # Extracting data #======================================================================================== indexes = np.loadtxt('%s%s/analysis/BH_IDs.txt'%(DataFolder,Simulation))[:,[0,1]] #os.system('rm tmp.txt') for i in xrange(N_proc): print 'In file', i #Loading data str_cmd = "less %s%s/output/blackhole_mergers/blackhole_mergers_%d.txt >> tmp.txt"%(DataFolder,Simulation,i) os.system(str_cmd) #Storing concatenated file data = np.loadtxt('tmp.txt') os.system('rm tmp.txt') f= open('%s%s/analysis/BH_Mergers_R.txt'%(DataFolder,Simulation), 'a') np.savetxt(f, data[:,1:], fmt='%e %d %e %d %e') f.close() #======================================================================================== # Applying correction to merger file #======================================================================================== data_merger = np.loadtxt('%s%s/analysis/BH_Mergers_R.txt'%(DataFolder,Simulation)) M1 = [] for i in xrange(len(data_merger)): time = data_merger[i,0] id_mr = indexes[indexes[:,1]==data_merger[i,1].astype(int),0].astype(int) if len(id_mr)==1: try: id_mr = id_mr[0] #Loading data of current BH data_BHi = np.loadtxt('%s%s/analysis/spins/BH_%d.txt'%(DataFolder,Simulation,id_mr)) mask_t = data_BHi[:,0] > time M1.append( data_BHi[mask_t,2][0] - data_merger[i,4] ) except: print i M1.append( data_merger[i,2] ) else: M1.append( data_merger[i,2] ) M1 = np.array(M1) np.savetxt( '%s%s/analysis/BH_Mergers.txt'%(DataFolder,Simulation), np.array( [data_merger[:,0], data_merger[:,1], M1, data_merger[:,3], data_merger[:,4]] ).T, fmt='%e %d %e %d %e' )
[ "macsebas33@gmail.com" ]
macsebas33@gmail.com
eb05a439ca3e8cb84a9dd47e7476548ed343a980
5db75589901eb5eb991d8efd5aa043fbd475179c
/leetcode/strStr.py
6af411d87627e6fa6c68306c8bebf86d0cfe9c05
[]
no_license
cizixs/playground
b15f503ddb7a406791443768b6325776c9fe6f22
eea3668cc80d7f328359a56144a5344029e83b47
refs/heads/master
2021-01-22T02:53:09.981444
2014-10-26T07:19:17
2014-10-26T07:19:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
386
py
class Solution: # @param haystack, a string # @param needle, a string # @return a string or None def strStr(self, haystack, needle): if len(haystack) < len(needle): return None if needle == "": return haystack result = haystack.find(needle) if result < 0: return None return haystack[result:]
[ "vagrant@precise64.(none)" ]
vagrant@precise64.(none)
ed08064f64c5c4407c7c2f69b59101480452a297
fa795af74cda4d92604fa3332179ba939460a9b5
/JUBioactivities/QSARDB/Zhang_Property_logKMXa_Cuticular_polymer_matrix/__init__.py
adddf136cd274fcf5c3c41ccd4a71b4f7ab2e83c
[]
no_license
JenniferHemmerich/JUBioactivities
7329a89db0e2790aff9bcfe153ab4dcd2c19a489
87054ac135d91e034dcfb6028562b4a7930a3433
refs/heads/master
2020-04-26T03:56:36.177955
2019-03-07T13:08:08
2019-03-07T13:08:08
173,284,341
1
1
null
null
null
null
UTF-8
Python
false
false
940
py
import os.path import pandas as pd from ... import utils import glob __data_src__ = [os.path.join(__path__[0], "compounds/InChI_from_XML.csv")] __data_src__ += list(sorted(glob.glob(os.path.join(__path__[0], "properties/*.txt")))) def read_data(raw=False): dat = pd.read_csv(__data_src__[0], index_col=0) prop = pd.read_csv(__data_src__[1], index_col=0, sep="\t") prop.columns = ['logKMXa_Zhang'] df = pd.concat([dat, prop], axis=1) df = df.set_index('InchiCode') df = utils.index_from_inchicode(df) if raw: return df df = utils.drop_rows(df) df = utils.handle_duplicates(df, type='cont') return df def read_structures(raw=False): df = pd.read_csv(__data_src__[0], index_col=1).drop('ID', axis=1) df = utils.index_from_inchicode(df, smiles=True) if raw: return df df = utils.drop_rows(df) df = utils.handle_duplicates(df, type='str') return df
[ "jennifer.hemmerich@univie.ac.at" ]
jennifer.hemmerich@univie.ac.at