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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
883a6c20e7944bbab06ab0137f5b161f3a652d38 | 9f5bc6d70835e32a02364766b406d0cc08e45692 | /hello_dj/music/views.py | 986db014c229efe440662c4a77e9f5c3b977a2c1 | [] | no_license | zx490336534/learn_django | f206f13901a4c177bc78629b839da0b947764927 | 78274ccdb5d97b0576fa893a119dc60369300be2 | refs/heads/master | 2020-04-03T16:39:07.325023 | 2018-11-23T13:59:38 | 2018-11-23T13:59:38 | 155,413,348 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'music/music_index.html',
context={'str': 'LIST',
'format_string': '%Y年%m月%d日 %H:%M:%S',
'ls': [1, 2, 3],
'tp': ('taka', 'xiaopo', 'moran')})
| [
"490336534@qq.com"
] | 490336534@qq.com |
9a99affd9330d2197cca6838b31c5b0ee9a601f9 | a9fc496e0724866093dbb9cba70a8fdce12b67a9 | /scripts/quest/q38997s.py | 70187343f30d734e3f2f0de50048ea1ff1017575 | [
"MIT"
] | permissive | ryantpayton/Swordie | b2cd6b605f7f08f725f5e35d23ba3c22ef2ae7c0 | ca6f42dd43f63b1d2e6bb5cdc8fc051c277f326e | refs/heads/master | 2022-12-01T09:46:47.138072 | 2020-03-24T10:32:20 | 2020-03-24T10:32:20 | 253,997,319 | 2 | 0 | MIT | 2022-11-24T08:17:54 | 2020-04-08T05:50:22 | Java | UTF-8 | Python | false | false | 906 | py | # 410000002
MOONBEAM = 3002100
sm.setSpeakerID(MOONBEAM)
sm.sendNext("Let's start with #b[Fox Trot]#k. If you really do have ears, perk them up for this!")
sm.sendSay("#b[Fox Trot]#k is super helpful when you want to move quickly or get close to an enemy. You're way too slow to catch prey, so you need all the help you can get.")
sm.sendSay("Now try using #b[Fox Trot]#k. Oh, and it's a lot easier if you hotkey it and use it that way!")
sm.startQuest(parentID)
sm.sendNext("Whaddaya think? Was that amazingly fast, or what? Use this skill to get close to your prey.")
sm.sendSay("Use this skill when you're using other skills to #binterrupt#k the first one and #bmove#k quickly!")
sm.sendSay("I know you can be a little slow, Shade. Are you keeping up?")
sm.sendSay("I'll tell you how to use it to make up for your weakness. Talk to me when you're ready!")
sm.completeQuest(parentID)
sm.giveExp(700)
| [
"mechaviv@gmail.com"
] | mechaviv@gmail.com |
1fef7a4826a9cfda2ae498faf73994059b0b0e6c | 097dda217c3d31b69cb309369dc0357fe0f229ab | /app/customadmin/mixins.py | 2a50cfaa427fe7b145bd481d88229b25ee87aa49 | [] | no_license | Jaycitrusbug/book-python | 57a96ee343eee5b63ca5f7ee2461db82426321b5 | b5a4de74c9114546ee03b8aa5de1381719ddf74e | refs/heads/master | 2023-06-20T01:52:29.484415 | 2021-07-16T13:06:05 | 2021-07-16T13:06:05 | 386,638,204 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,461 | py | # -*- coding: utf-8 -*-
from django.contrib import messages
from django.contrib.auth import get_permission_codename
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import redirect
# -----------------------------------------------------------------------------
class SuccessMessageMixin(object):
"""CBV mixin which adds a success message on form save."""
success_message = ""
def get_success_message(self):
return self.success_message
def form_valid(self, form):
response = super().form_valid(form)
success_message = self.get_success_message()
if not self.request.is_ajax() and success_message:
messages.success(self.request, success_message)
return response
# def forms_valid(self, forms):
# """Ensure it works with multi_form_view.MultiModelFormView."""
# print("SuccessMessageMixin:forms_valid")
# response = super().forms_valid(forms)
# success_message = self.get_success_message()
# if not self.request.is_ajax() and success_message:
# messages.success(self.request, success_message)
# return response
class ModelOptsMixin(object):
"""CBV mixin which adds model options to the context."""
def get_context_data(self, **kwargs):
"""Returns the context data to use in this view."""
ctx = super().get_context_data(**kwargs)
if hasattr(self, "model"):
ctx["opts"] = self.model._meta
return ctx
class HasPermissionsMixin(object):
"""CBV mixin which adds has_permission options to the context."""
def has_add_permission(self, request):
print('-------------------has_add_permission----------------')
print('-------------------has_add_permission----------------')
print('-------------------has_add_permission----------------')
"""
Return True if the given request has permission to add an object.
Can be overridden by the user in subclasses.
"""
opts = self.model._meta
codename = get_permission_codename("add", opts)
return request.user.has_perm("%s.%s" % (opts.app_label, codename)) or request.user.is_staff
def has_change_permission(self, request, obj=None):
"""
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
"""
opts = self.model._meta
codename = get_permission_codename("change", opts)
return request.user.has_perm("%s.%s" % (opts.app_label, codename)) or request.user.is_staff
def has_delete_permission(self, request, obj=None):
"""
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
"""
opts = self.model._meta
codename = get_permission_codename("delete", opts)
return request.user.has_perm("%s.%s" % (opts.app_label, codename)) or request.user.is_staff
def has_view_permission(self, request, obj=None):
"""
Return True if the given request has permission to view the given
Django model instance. The default implementation doesn't examine the
`obj` parameter.
If overridden by the user in subclasses, it should return True if the
given request has permission to view the `obj` model instance. If `obj`
is None, it should return True if the request has permission to view
any object of the given type.
"""
opts = self.model._meta
codename_view = get_permission_codename("view", opts)
codename_change = get_permission_codename("change", opts)
print('----------------------------------', "%s.%s" % (opts.app_label, codename_view), '----------------------------------' )
return request.user.has_perm(
"%s.%s" % (opts.app_label, codename_view)
) or request.user.has_perm("%s.%s" % (opts.app_label, codename_change)) or request.user.is_staff
def has_view_or_change_permission(self, request, obj=None):
return self.has_view_permission(request, obj) or self.has_change_permission(
request, obj
) or request.user.is_staff
def has_module_permission(self, request):
"""
Return True if the given request has any permission in the given
app label.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to view the module on
the admin index page and access the module's index page. Overriding it
does not restrict access to the add, change or delete views. Use
`ModelAdmin.has_(add|change|delete)_permission` for that.
"""
opts = self.model._meta
return request.user.has_module_perms(opts.app_label) or request.user.is_staff
def get_context_data(self, **kwargs):
"""Returns the context data to use in this view."""
ctx = super().get_context_data(**kwargs)
if hasattr(self, "model"):
ctx["has_add_permission"] = self.has_add_permission(self.request)
ctx["has_change_permission"] = self.has_change_permission(self.request)
ctx["has_delete_permission"] = self.has_delete_permission(self.request)
ctx["has_view_permission"] = self.has_view_permission(self.request)
ctx["has_view_or_change_permission"] = self.has_view_or_change_permission(
self.request
)
ctx["has_module_permission"] = self.has_module_permission(self.request)
if hasattr(self, "object"):
ctx["add"] = self.object is None
return ctx
| [
"jay.citrusbug@gmail.com"
] | jay.citrusbug@gmail.com |
ab44c61a08bafb6bc721cd98b410a587695b4f8f | d2c4934325f5ddd567963e7bd2bdc0673f92bc40 | /tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_MovingAverage_Seasonal_Second_ARX.py | c958c960f5731fcc823ea172e5b07cbf2c2a8f40 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jmabry/pyaf | 797acdd585842474ff4ae1d9db5606877252d9b8 | afbc15a851a2445a7824bf255af612dc429265af | refs/heads/master | 2020-03-20T02:14:12.597970 | 2018-12-17T22:08:11 | 2018-12-17T22:08:11 | 137,104,552 | 0 | 0 | BSD-3-Clause | 2018-12-17T22:08:12 | 2018-06-12T17:15:43 | Python | UTF-8 | Python | false | false | 166 | py | import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Anscombe'] , ['MovingAverage'] , ['Seasonal_Second'] , ['ARX'] ); | [
"antoine.carme@laposte.net"
] | antoine.carme@laposte.net |
aceb6eae41948f7ba22172a460aa667e1dff7b03 | 4656c9b22bee48b4156eb3524bab3215a1993d83 | /packages/gui/assets_widget/assets_item.py | 1d0fb14b51071fdc41de479eeca1fa77a8ee7819 | [] | no_license | mikebourbeauart/tempaam | 0bc9215de0d967788b3c65b481a5fd3c7153dddc | c2582b5cc1fc45042c5b435f703786d7c04a51a2 | refs/heads/master | 2021-03-27T10:35:43.378899 | 2018-09-06T04:46:18 | 2018-09-06T04:46:18 | 120,359,405 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 175 | py | from Qt import QtWidgets
class AssetsItem(QtWidgets.QTreeWidgetItem):
def __init__(self, *args):
QtWidgets.QTreeWidgetItem.__init__(self, *args) | [
"borbs727@gmail.com"
] | borbs727@gmail.com |
7bee31495c45a466373e68c775248f9c546b3a6c | d1b3c9e1055bc759f5fba8379570ddc20cf4caa5 | /Saver.py | 778690ec07d95b39c92c0776b8afd32ca1b8562c | [] | no_license | woolpeeker/bet365_data | 309b38245c77d9f9387c7d946dbb8410c4c84bc6 | 4cb920095f98faf220c74125d39ccdfe84229ee3 | refs/heads/master | 2020-03-29T22:48:40.234365 | 2018-12-14T03:41:42 | 2018-12-14T03:41:42 | 150,441,477 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,069 | py | import datetime
import traceback
import pymysql
from utils import get_logger
sql_cmd = {
'create_table': "CREATE TABLE inplay ( \
id int NOT NULL AUTO_INCREMENT, PRIMARY KEY (id),\
insert_time datetime NOT NULL, \
crawler varchar(255), \
fp char(255) NOT NULL, \
league char(255), date Date NOT NULL, \
team_h char(255) NOT NULL, team_a char(255) NOT NULL, minute smallint NOT NULL, \
corner_h smallint, corner_a smallint, \
yellow_h smallint, yellow_a smallint, \
red_h smallint, red_a smallint, \
throw_h smallint, throw_a smallint, \
freekick_h smallint, freekick_a smallint, \
goalkick_h smallint, goalkick_a smallint, \
penalty_h smallint, penalty_a smallint, \
goal_h smallint, goal_a smallint, \
attacks_h smallint, attacks_a smallint, \
dangerous_attacks_h smallint, dangerous_attacks_a smallint, \
possession_h smallint, possession_a smallint, \
on_target_h smallint, on_target_a smallint, \
off_target_h smallint, off_target_a smallint, \
odds_fulltime varchar(255), odds_double varchar(255), \
odds_corners varchar(255), odds_asian_corners varchar(255),\
odds_match_goals varchar(255), odds_alter_goals varchar(255), \
odds_goals_odd_even varchar(255), odds_most_corners varchar(255));"
}
class Saver:
def __init__(self, name='saver'):
self.name=name
self.logger=get_logger(self.name)
self.conn = pymysql.connect(host="localhost", user="root", password="123456", database="soccer", charset='utf8', autocommit=True)
if not self.exist_table():
self.create_table()
def exist_table(self):
sql = "SELECT table_name FROM information_schema.TABLES WHERE table_schema = 'soccer' and table_name = 'inplay';"
with self.conn.cursor() as cur:
cur.execute(sql)
result = cur.fetchone()
if result is None:
self.logger.info("table doesn't exists")
return False
else:
self.logger.info('table exists')
return True
def create_table(self):
self.logger.info('create_table')
sql = sql_cmd['create_table']
with self.conn.cursor() as cur:
try:
cur.execute(sql)
except:
self.logger.error(traceback.format_exc())
self.conn.rollback()
if not self.exist_table():
self.logger.error('create table Fails.')
raise Exception('create table Fails.')
else:
self.logger.info('create table successful')
def sql_query(self, sql, sql_args):
self.logger.debug('sql_query: %s args: %s' % (sql, sql_args))
with self.conn.cursor() as cur:
cur.execute(sql, sql_args)
result = cur.fetchall()
return result
def process_vals(self,vals):
converted=[]
for v in vals:
if v is None:
converted.append(None)
elif isinstance(v, datetime.date):
converted.append(str(v))
elif isinstance(v,(int, float, str)):
converted.append(v)
else:
converted.append(str(v))
self.logger.error("Unexpected datatype, just str it: %s" % type(v))
return converted
def sql_insert(self, sample):
self.logger.debug('sql_insert: %s' % sample)
assert type(sample) == dict
try:
sample['insert_time'] = datetime.datetime.now()
keys = ','.join(sample.keys())
vals = self.process_vals(sample.values())
holder=lambda num: ','.join(['%s']*num)
sql = 'INSERT INTO inplay ({keys}) VALUES ({vals});'.format(keys=keys,vals=holder(len(vals)))
sql_args=vals
self.logger.debug('sql: %s args: %s'%(sql,sql_args))
with self.conn.cursor() as cur:
cur.execute(sql, sql_args)
except Exception as e:
self.logger.error('sql_insert error: %s' % sample)
self.logger.error(traceback.format_exc())
self.logger.debug('sql_insert success: %s' % sample)
def insert(self, input):
self.logger.debug('insert: %s'%input)
today = datetime.date.today()
same_team_set = self.sql_query("SELECT id, date, minute FROM inplay WHERE team_h=%s and team_a=%s ORDER BY id;",(input['team_h'], input['team_a']))
if not same_team_set:
self.logger.debug('same_team_set is empty')
date = today
else:
id, last_date, last_minute = same_team_set[-1]
delta = today - last_date
if delta.total_seconds() < 24 * 3600:
date = last_date
else:
date = today
if input['minute'] == 90 and input['minute'] < last_minute:
input['minute'] = -1
if date == last_date and input['minute'] == last_minute:
return
input['date'] = date
input['fp'] = '##'.join([str(input[k]) for k in ['league', 'date', 'team_h', 'team_a']])
self.sql_insert(input)
| [
"luojiapeng1993@gmail.com"
] | luojiapeng1993@gmail.com |
cc82fb1b7b8286a21e86fe57bd1cbeba056b0bbe | 3cf0d750948a758d5771dd778fbb783d64a044ae | /src/algo_cases/第9章/9_4.py | 1b8b02fc6a55727dfa928a539382f6f384f9e3db | [
"CC-BY-NC-SA-4.0",
"Apache-2.0"
] | permissive | hbulpf/pydemo | 6552a08b3c85721ac1b2ba335b030e234ad03b6c | ea3e9f9086116a86ecef803e9e3179a34c94c20f | refs/heads/master | 2022-11-30T21:06:29.933820 | 2022-01-15T17:05:16 | 2022-01-15T17:05:16 | 237,584,300 | 6 | 1 | Apache-2.0 | 2022-11-22T09:49:38 | 2020-02-01T08:20:43 | Python | UTF-8 | Python | false | false | 1,001 | py | class Solution:
def findnum(self, nums):
def func(low,high):
if low==high:
return nums[low]
mid=low+(high-low)//2
head=func(low,mid)
tail=func(mid+1,high)
if head==tail:
return tail
head_count=sum(1 for i in range(low,high+1) if nums[i]==head)
tail_count=sum(1 for i in range(low,high+1) if nums[i]==tail)
return head if head_count>tail_count else tail
return func(0,len(nums)-1)
class Solution:
def findnum(self, nums):
dic={}
for i in nums:
dic[i]=dic.get(i,0)+1
return max(dic.keys(),key=dic.get)
class Solution:
def findnum(self, nums):
times=1
re=nums[0]
for i in range(1,len(nums)):
if times==0:
re=nums[i]
times+=1
elif nums[i]==re:
times+=1
else:
times-=1
return re
| [
"hudalpf@163.com"
] | hudalpf@163.com |
4fce15cbe97195207d61da778af98e7e72d75477 | e3a25b40812b6b70f10b52a6f66f9348dcc251a6 | /algorithm/0327야자/장기.py | 5c72cba9ab087f171a914be70dab9629329ed05f | [] | no_license | yoonwoo123/python101 | 75643cb5dcf411c9ddcf988bf09bb88e4523206c | 637dce64a6320a6f46eb941e33e8e9f6ee41c910 | refs/heads/master | 2020-04-14T11:30:43.018126 | 2019-07-25T08:28:31 | 2019-07-25T08:28:31 | 163,815,689 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 884 | py | import sys, collections
sys.stdin = open("장기_input.txt")
dx = [-2, -1, 1, 2, 2, 1, -1, -2]
dy = [1, 2, 2, 1, -1, -2, -2, -1]
def BFS(x, y, cnt):
global res
que = []
que.append([x, y, cnt])
arr[x][y] = 1 # 방문체크
while que:
x, y, cnt = que.pop(0)
cnt += 1
for i in range(8):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx >= N or ny < 0 or ny >= M: continue
if arr[nx][ny] == 1: continue
if arr[nx][ny] == 2:
res = cnt
return
arr[nx][ny] = 1 # 방문처리
que.append([nx, ny, cnt])
N, M = map(int, input().split())
HX, HY, X, Y = map(int, input().split())
HX -= 1
HY -= 1
X -= 1
Y -= 1
arr = [[0 for _ in range(M)] for _ in range(N)]
arr[HX][HY] = 1 # 말
arr[X][Y] = 2 # 졸병
res = 0
BFS(HX, HY, 0)
print(res) | [
"lkkjasd@korea.ac.kr"
] | lkkjasd@korea.ac.kr |
df6ab93663cc3b77221a50587f2e67a918d035eb | a977365234cad283d9f3edc022976a70501c1c41 | /API-Auto/testCase/salesman/test6_20case.py | 2c0fd2d7a472932f5ba3de597609b5174e6782ca | [] | no_license | quqiao/hezongyy | 849f2b9c8a4db562bde5e415ef012ff29c704fd8 | cde6805ada979afe0b24911f8c5d0977cfd92e5a | refs/heads/master | 2021-08-16T10:20:12.618268 | 2020-07-23T09:09:07 | 2020-07-23T09:09:07 | 205,772,625 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,687 | py | import json
import unittest
from common1.configHttp import RunMain
import paramunittest
import geturlParams
import urllib.parse
# import pythoncom
import time
import readExcel
# pythoncom.CoInitialize()
# url = geturlParams.geturlParams().get_Url1_3() # 调用我们的geturlParams获取我们拼接的URL
login_xls = readExcel.readExcel().get_xls('业务员APP.xlsx', '20订单详情')
@paramunittest.parametrized(*login_xls)
class testUserLogin(unittest.TestCase):
def setParameters(self, case_name, url, port, path, query, method, expected, result):
"""
set params
:param case_name:
:param path
:param query
:param method
:return:
"""
self.case_name = str(case_name)
self.url = str(url)
self.port = str(int(port))
self.path = str(path)
self.query = str(query)
self.method = str(method)
self.expected = str(expected)
self.result = str(result)
def description(self):
"""
test report description
:return:
"""
self.case_name
def setUp(self):
"""
:return:
"""
print("执行用例:" + self.case_name)
url = 'http://' + self.url + ':' + self.port + self.path
print(url)
def test1_02case(self):
"""20订单详情接口"""
self.checkResult()
def tearDown(self):
print("测试结束,输出log完结\n\n")
def checkResult(self): # 断言
"""
check test result
:return:
"""
# url1 = "http://www.xxx.com/login?"
# new_url = url1 + self.query
# data1 = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(new_url).query))# 将一个完整的URL中的name=&pwd=转换为{'name':'xxx','pwd':'bbb'}
url = 'http://' + self.url + ':' + self.port + self.path
data1 = self.query.encode('utf-8')
info = RunMain().run_main(self.method, url, data1) # 根据Excel中的method调用run_main来进行requests请求,并拿到响应
ss = json.loads(info) # 将响应转换为字典格式
if self.case_name == 'url正确': # 如果case_name是login,说明合法,返回的code应该为200
self.assertEqual(ss['code'], '000000')
if self.case_name == 'url错误': # 同上
self.assertEqual(ss['code'], "900004")
if self.case_name == 'url为空': # 同上
self.assertEqual(ss['code'], "900004")
print("返回信息:" + ss['message'])
# if __name__ == '__main__': # 测试一下,我们读取配置文件的方法是否可用
# print(testUserLogin().checkResult())
| [
"553248560@.com"
] | 553248560@.com |
d3f0da288b31dd9c16b761b157afff6e6a2e560e | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_0_1_neat/16_0_1_Reckon_sheep.py | 53fe372642f8e0798c770f04c5611f190c3b4e98 | [] | no_license | DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | Python | UTF-8 | Python | false | false | 502 | py | def count_sheep(n):
if n == 0:
return "INSOMNIA"
all_digits = set()
for i in range(0,10):
all_digits.add(i)
digits = set()
total = 0
prev = 0
while digits != all_digits:
prev = total
total += n
for i in str(total):
digits.add(int(i))
return str(total)
len = int(raw_input())
for case in range(0, len):
n = int(raw_input())
print "Case #" + str(case+1) + ":", count_sheep(n)
| [
"[dhuo@tcd.ie]"
] | [dhuo@tcd.ie] |
fc995d5b1e327ff5d62745113f22f6ee8701faf7 | 57db61160494659af43ee255d1e6ab2af6617114 | /ultron-api/advantages/migrations/0001_initial.py | 4896f942309121a367273a44dde8b46f7ed02bb3 | [] | no_license | gloompi/ultron-studio | fc667d563467b386a8dec04a6079e7cdcfedc5a7 | ec2ae8051644df2433b931c7e0228e75eaf20990 | refs/heads/master | 2023-06-25T19:22:45.119315 | 2019-12-08T05:53:02 | 2019-12-08T05:53:02 | 226,545,035 | 0 | 0 | null | 2023-06-10T00:22:15 | 2019-12-07T16:44:16 | JavaScript | UTF-8 | Python | false | false | 1,345 | py | # Generated by Django 2.2.3 on 2019-08-01 16:57
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AdvantagesSection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=30)),
('description', tinymce.models.HTMLField()),
],
options={
'verbose_name': 'Advatages Section',
'verbose_name_plural': 'Advatages Section',
},
),
migrations.CreateModel(
name='Advantage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('icon', models.ImageField(max_length=25, upload_to='')),
('title', models.CharField(max_length=30)),
('description', tinymce.models.HTMLField()),
('section', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='advantages_section', to='advantages.AdvantagesSection')),
],
),
]
| [
"gloompi@gmail.com"
] | gloompi@gmail.com |
3f48495450dbab8a40f102e8fcf7f50b74aa16e7 | f8777c76ec7c8da686c72a2975c17bbd294edc0e | /eden/integration/fsck_test.py | 25fa242bb4141942126412262227e4313e8399cf | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | jmswen/eden | 3a8e96bf0fbbf6c987f4b17bbd79dcbe0964c033 | 5e0b051703fa946cc77fc43004435ae6b20599a1 | refs/heads/master | 2020-06-06T06:08:28.946268 | 2019-06-19T04:45:11 | 2019-06-19T04:45:11 | 192,659,804 | 0 | 0 | NOASSERTION | 2019-06-19T04:43:36 | 2019-06-19T04:43:36 | null | UTF-8 | Python | false | false | 6,885 | py | #!/usr/bin/env python3
#
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
import pathlib
import subprocess
import unittest
from pathlib import Path
from typing import Tuple
from eden.test_support.temporary_directory import TemporaryDirectoryMixin
from .lib import edenclient, overlay as overlay_mod, repobase, testcase
FSCK_RETCODE_OK = 0
FSCK_RETCODE_SKIPPED = 1
FSCK_RETCODE_WARNINGS = 2
FSCK_RETCODE_ERRORS = 3
class FsckTest(testcase.EdenRepoTest):
overlay: overlay_mod.OverlayStore
def populate_repo(self) -> None:
self.repo.write_file("README.md", "tbd\n")
self.repo.write_file("proj/src/main.c", "int main() { return 0; }\n")
self.repo.write_file("proj/src/lib.c", "void foo() {}\n")
self.repo.write_file("proj/src/include/lib.h", "#pragma once\nvoid foo();\n")
self.repo.write_file(
"proj/test/test.sh", "#!/bin/bash\necho test\n", mode=0o755
)
self.repo.write_file("doc/foo.txt", "foo\n")
self.repo.write_file("doc/bar.txt", "bar\n")
self.repo.symlink("proj/doc", "../doc")
self.repo.commit("Initial commit.")
def create_repo(self, name: str) -> repobase.Repository:
return self.create_hg_repo("main")
def setup_eden_test(self) -> None:
super().setup_eden_test()
self.overlay = overlay_mod.OverlayStore(self.eden, self.mount_path)
def run_fsck(self, *args: str) -> Tuple[int, str]:
"""Run `eden fsck [args]` and return a tuple of the return code and
the combined stdout and stderr.
The command output will be decoded as UTF-8 and returned as a string.
"""
cmd_result = self.eden.run_unchecked(
"fsck", *args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
fsck_out = cmd_result.stdout.decode("utf-8", errors="replace")
return (cmd_result.returncode, fsck_out)
def test_fsck_force_and_check_only(self) -> None:
"""Test the behavior of the --force and --check-only fsck flags."""
foo_overlay_path = self.overlay.materialize_file(pathlib.Path("doc/foo.txt"))
# Running fsck with the mount still mounted should fail
returncode, fsck_out = self.run_fsck(self.mount)
self.assertIn(f"Not checking {self.mount}", fsck_out)
self.assertEqual(FSCK_RETCODE_SKIPPED, returncode)
# Running fsck with --force should override that
returncode, fsck_out = self.run_fsck(self.mount, "--force")
self.assertIn(f"warning: could not obtain lock", fsck_out)
self.assertIn(f"scanning anyway due to --force", fsck_out)
self.assertIn(f"Checking {self.mount}", fsck_out)
self.assertEqual(FSCK_RETCODE_OK, returncode)
# fsck should perform the check normally without --force
# if the mount is not mounted
self.eden.run_cmd("unmount", self.mount)
returncode, fsck_out = self.run_fsck(self.mount)
self.assertIn(f"Checking {self.mount}", fsck_out)
self.assertIn("No issues found", fsck_out)
self.assertEqual(FSCK_RETCODE_OK, returncode)
# Truncate the overlay file for doc/foo.txt to 0 length
with foo_overlay_path.open("wb"):
pass
# Running fsck with --check-only should report the error but not try to fix it.
returncode, fsck_out = self.run_fsck("--check-only")
self.assertIn(f"Checking {self.mount}", fsck_out)
self.assertRegex(
fsck_out,
r"invalid overlay file for materialized file .* \(doc/foo.txt\).*: "
r"zero-sized overlay file",
)
self.assertRegex(fsck_out, r"\b1 errors")
self.assertRegex(fsck_out, "Not fixing errors: --check-only was specified")
self.assertEqual(FSCK_RETCODE_ERRORS, returncode)
# Running fsck with no arguments should attempt to fix the errors
returncode, fsck_out = self.run_fsck()
self.assertRegex(
fsck_out,
r"invalid overlay file for materialized file .* \(doc/foo.txt\).*: "
r"zero-sized overlay file",
)
self.assertRegex(fsck_out, r"\b1 errors")
self.assertRegex(fsck_out, "Beginning repairs")
self.assertRegex(
fsck_out, "replacing corrupt file inode 'doc/foo.txt' with an empty file"
)
self.assertRegex(fsck_out, "Fixed 1 of 1 issues")
self.assertEqual(FSCK_RETCODE_ERRORS, returncode)
# There should be no more errors if we run fsck again
returncode, fsck_out = self.run_fsck()
self.assertIn(f"Checking {self.mount}", fsck_out)
self.assertIn("No issues found", fsck_out)
self.assertEqual(FSCK_RETCODE_OK, returncode)
def test_fsck_multiple_mounts(self) -> None:
mount2 = Path(self.mounts_dir) / "second_mount"
mount3 = Path(self.mounts_dir) / "third_mount"
mount4 = Path(self.mounts_dir) / "fourth_mount"
self.eden.clone(self.repo_name, mount2)
self.eden.clone(self.repo_name, mount3)
self.eden.clone(self.repo_name, mount4)
# Unmount all but mount3
self.eden.unmount(Path(self.mount))
self.eden.unmount(mount2)
self.eden.unmount(mount4)
# Running fsck should check all but mount3
returncode, fsck_out = self.run_fsck()
self.assertIn(f"Checking {self.mount}", fsck_out)
self.assertIn(f"Checking {mount2}", fsck_out)
self.assertIn(f"Not checking {mount3}", fsck_out)
self.assertIn(f"Checking {mount4}", fsck_out)
self.assertEqual(FSCK_RETCODE_SKIPPED, returncode)
# Running fsck with --force should check everything
returncode, fsck_out = self.run_fsck("--force")
self.assertIn(f"Checking {self.mount}", fsck_out)
self.assertIn(f"Checking {mount2}", fsck_out)
self.assertIn(f"Checking {mount3}", fsck_out)
self.assertIn(f"Checking {mount4}", fsck_out)
self.assertEqual(FSCK_RETCODE_OK, returncode)
class FsckTestNoEdenfs(unittest.TestCase, TemporaryDirectoryMixin):
def test_fsck_no_checkouts(self) -> None:
tmp_dir = self.make_temporary_directory()
eden = edenclient.EdenFS(Path(tmp_dir))
cmd_result = eden.run_unchecked(
"fsck",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
errors="replace",
)
self.assertIn(
"No Eden checkouts are configured. Nothing to check.", cmd_result.stderr
)
self.assertEqual("", cmd_result.stdout)
self.assertEqual(0, cmd_result.returncode)
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
f29c393fb5d26ef7471da24846610d659313a979 | 44c29ed593d91919752ba251eb328330cfa8ea79 | /logstash/urls.py | f2d42066d18134332b2391b397b6f446f7ef8507 | [
"MIT"
] | permissive | Azimut-Prod/azimut-gestion | 51b21732815a6f9dbe1d15baef746c777469c601 | fafb30599a26cd89cbe34bbf53179c2cfe0d5cb7 | refs/heads/master | 2020-12-24T14:26:51.160788 | 2014-10-02T17:34:15 | 2014-10-02T17:34:15 | 13,557,198 | 0 | 2 | null | 2014-06-20T07:56:43 | 2013-10-14T09:21:32 | Python | UTF-8 | Python | false | false | 575 | py | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns(
'logstash.views',
url(r'^$', 'file_list'),
url(r'^(?P<pk>[0-9]*)/show/$', 'file_show'),
url(r'^(?P<pk>[0-9]*)/edit/$', 'file_edit'),
url(r'^(?P<pk>[0-9]*)/delete/$', 'file_delete'),
url(r'^(?P<name>.*)/shipper.conf$', 'generate_config'),
url(r'^auto$', 'start_autodetect'),
url(r'^auto/(?P<key>[0-9]*)$', 'watch_autodetect'),
url(r'^auto/w/(?P<key>[0-9]*)$', 'watch_get_status'),
url(r'^auto/confirm/(?P<key>[0-9]*)$', 'watch_final'),
)
| [
"maximilien@theglu.org"
] | maximilien@theglu.org |
4b4294d9cc6ed233881c46938df6a8a067bee583 | e146d44875fb44a13b3b004604694bccaa23ddf2 | /docs/Amadeus-master/pactravel-master/python-client/test/test_restricted_rate.py | 477739ad7b3413811f0c07b2ffdbd8a05be8093f | [] | no_license | shopglobal/travel | 8d959b66d77f2e1883b671628c856daf0f3b21bb | 0c33467cd2057da6e01f9240be2fd4b8f5490539 | refs/heads/master | 2022-12-23T00:13:02.597730 | 2017-09-26T06:03:15 | 2017-09-26T06:03:15 | 104,405,869 | 0 | 0 | null | 2022-12-08T00:35:36 | 2017-09-21T22:43:23 | PHP | UTF-8 | Python | false | false | 951 | py | # coding: utf-8
"""
Amadeus Travel Innovation Sandbox
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import swagger_client
from swagger_client.rest import ApiException
from swagger_client.models.restricted_rate import RestrictedRate
class TestRestrictedRate(unittest.TestCase):
""" RestrictedRate unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testRestrictedRate(self):
"""
Test RestrictedRate
"""
# FIXME: construct object with mandatory attributes with example values
#model = swagger_client.models.restricted_rate.RestrictedRate()
pass
if __name__ == '__main__':
unittest.main()
| [
"president@worldvaporexpo.com"
] | president@worldvaporexpo.com |
1638e7347594a5b77e8ede5907e8984e480a8384 | 320bd873b6cf5db2fc9194cc4ad782a49373d6ee | /page/base_page.py | 7753eaa01b0d7f8d3fee1fec5a4453ad2c0757e7 | [] | no_license | donniezhanggit/AppiumDemo8_Android | 7b0aed903969e2101330b5da4e89c39e3d591723 | 7a2ed3be27ed6cb27bd4e30e13d48cc8f34aa654 | refs/heads/master | 2020-09-13T17:35:33.749237 | 2019-03-10T10:04:46 | 2019-03-10T10:04:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,774 | py | from appium.webdriver import WebElement
from appium.webdriver.common.mobileby import MobileBy
from lxml.html import Element
from selenium.webdriver.common.by import By
from driver.Appium import Appium
from lxml import etree
class BasePage(object):
def __init__(self):
pass
@classmethod
def byAndroid(self, text=None, id=None):
text_selector=""
if(text!=None):
text_selector="@text='" + text + "'"
if (id != None):
id_selector = "contains(@resource-id, '" + id + "')"
return (MobileBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("' + id + '").text("' + text + '")')
#return "//*[" + text_selector + " and " + id_selector + "]"
else:
return (MobileBy.ANDROID_UIAUTOMATOR,'new UiSelector().text("'+text+'")')
#return "//*[" + text_selector + "]"
@classmethod
def byAttribute(self, text=None, id=None):
text_selector=""
if(text!=None):
text_selector="@text='" + text + "'"
if (id != None):
id_selector = "contains(@resource-id, '" + id + "')"
#return 'new UiSelector().resourceId("' + id + '").text("' + text + '")'
return "//*[" + text_selector + " and " + id_selector + "]"
else:
#return 'new UiSelector().text("'+text+'")'
return "//*[" + text_selector + "]"
def findBy(self, by=By.ID, value=None):
try:
return Appium.getDriver().find_element(by, value)
except:
self.exception_handle2()
return Appium.getDriver().find_element(by, value)
def find(self, locate) -> WebElement:
return self.findBy(*locate)
def findAll(self, locate) -> []:
return Appium.getDriver().find_elements(*locate)
def exception_handle(self):
self.black_words = [self.byAttribute(text="好的"), self.byAttribute(text="下次再说")]
for w in self.black_words:
elements = Appium.getDriver().find_elements(By.XPATH, w)
if len(elements) > 0:
elements[0].click()
return Appium.getDriver().find_element(By.XPATH, w)
def exception_handle2(self):
self.black_words = [self.byAttribute(text="好的"), self.byAttribute(text="下次再说")]
#todo: 优化弹框处理逻辑,发现toast,自动发现兼容性问题等。。。
page_source=Appium.getDriver().page_source
print(page_source)
#parser = etree.XMLParser(encoding='utf-8')
xml=etree.XML(str(page_source).encode("utf-8"))
for w in self.black_words:
print(w)
if(len(xml.xpath(w))>0):
Appium.getDriver().find_element(By.XPATH, w).click()
| [
"seveniruby@gmail.com"
] | seveniruby@gmail.com |
913718a80453266c1a4049cef48c9a4760dc651f | 0fd92b7d882a1edb5542f6600bb177dcad67ed50 | /powerful104/1003.py | 37f52fb9dbd627a8706e69ccc3234286a7f874e4 | [] | no_license | alpha-kwhn/Baekjun | bce71fdfbbc8302ec254db5901109087168801ed | f8b4136130995dab78f34e84dfa18736e95c8b55 | refs/heads/main | 2023-08-02T11:11:19.482020 | 2021-03-09T05:34:01 | 2021-03-09T05:34:01 | 358,347,708 | 0 | 0 | null | 2021-04-15T17:56:14 | 2021-04-15T17:56:13 | null | UTF-8 | Python | false | false | 340 | py | def fibo(n):
fn = 0
fn1 = 1
ans = fn1
for _ in range(n - 1):
ans = fn + fn1
fn = fn1
fn1 = ans
return ans
num = int(input())
for _ in range(num):
n = int(input())
if(n==0):
print(1,0)
elif(n==1):
print(0,1)
else:
print(fibo(n-1),fibo(n)) | [
"noreply@github.com"
] | alpha-kwhn.noreply@github.com |
136b32274f21e8d126ad13eadf2f5747cf24e7c9 | 99ef323acf05ae8c76f8ade8d2fe03d455c00302 | /tmp/fast_sufarr.py | 2ecb40e3773710a7258987394d63227cc5d35d3f | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | kcarnold/suggestion | b166fd3d986eace138a9d6c877ee4f71d94a796a | 27650cbf724b77361f8f4e609774ecb9bcf9e3c9 | refs/heads/master | 2021-01-13T15:24:43.195938 | 2018-12-21T23:02:31 | 2018-12-21T23:02:31 | 76,397,078 | 1 | 0 | null | 2017-02-21T16:19:02 | 2016-12-13T20:48:02 | Python | UTF-8 | Python | false | false | 5,235 | py | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 20 14:48:33 2017
@author: kcarnold
"""
import numpy as np
from suggestion import suggestion_generator
import kenlm
import tqdm
#%%
def sizeof_fmt(num, suffix='B', units=None, power=None, sep='', precision=2, sign=False):
prefix = '+' if sign and num > 0 else ''
for unit in units[:-1]:
if abs(round(num, precision)) < power:
if isinstance(num, int):
return "{}{}{}{}{}".format(prefix, num, sep, unit, suffix)
else:
return "{}{:3.{}f}{}{}{}".format(prefix, num, precision, sep, unit, suffix)
num /= float(power)
return "{}{:.{}f}{}{}{}".format(prefix, num, precision, sep, units[-1], suffix)
def sizeof_fmt_iec(num, suffix='B', sep='', precision=2, sign=False):
return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, sign=sign,
units=['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'], power=1024)
def sizeof_fmt_decimal(num, suffix='B', sep='', precision=2, sign=False):
return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, sign=sign,
units=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], power=1000)
#%%
model = suggestion_generator.get_model('yelp_train')
start_state = model.get_state([','])[0]
sufarr = suggestion_generator.sufarr
a, b = sufarr.search_range((',', ''))
sizeof_fmt_decimal(b-a)
#%%
%timeit suggestion_generator.collect_words_in_range(a,b,1)
#%%
unigram_probs = model.unigram_probs
lookup_voc = model.model.vocab_index
rarest_words_flat = []
for doc in tqdm.tqdm(sufarr.docs):
word_indices = [lookup_voc(w) for w in doc]
ups = unigram_probs[word_indices]
rarest_words_flat.extend([np.nanmin(ups[i+1:i+6]) for i in range(len(doc)-1)])
rarest_words_flat.append(0.) # for the last token in the document
rarest_words_flat.append(0.) # for the end-of-document token
rarest_words_flat = np.array(rarest_words_flat)
#%%
words_before_eos = []
for doc in tqdm.tqdm(sufarr.docs):
eos_indices = [idx for idx, tok in enumerate(doc) if tok == '</S>'] + [len(doc)]
offset = 0
cur_eos_idx = eos_indices[0]
for i, tok in enumerate(doc):
until_eos = cur_eos_idx - i
if until_eos < 0:
offset += 1
cur_eos_idx = eos_indices[offset]
until_eos = cur_eos_idx - i
words_before_eos.append(until_eos)
words_before_eos.append(0) # for end of document token
words_before_eos = np.array(words_before_eos)
#%%
# A filtered suffix array is one where only a subset of the possible indices exist in the lookup tables.
# To construct one, we create a mask over the existing indices.
# The suffix_array array maps from sorted index to master location.
# doc_idx is the document idx for the
filtered_doc_idx = sufarr.doc_idx[(words_before_eos > 5)[sufarr.suffix_array[1:]]]
filtered_tok_idx = sufarr.tok_idx[(words_before_eos > 5)[sufarr.suffix_array[1:]]]
#%%
idx = 1000
sufarr.docs[filtered_doc_idx[idx]][filtered_tok_idx[idx]:][:10]
#%%
from suggestion.suffix_array import DocSuffixArray
filtered_sufarr = DocSuffixArray(sufarr.docs, None, filtered_doc_idx, filtered_tok_idx, None)
#%%
a, b = filtered_sufarr.search_range(('the', ''))
import random
filtered_sufarr.get_partial_suffix(random.randrange(a,b), 0, 10)
#%%
rare_word_raw = np.array([tok for rw in rarest_words_by_doc for tok in rw + [0]])
#%%
docs_flat_raw = []
for doc in tqdm.tqdm(sufarr.docs):
docs_flat_raw.extend(doc)
docs_flat_raw.append('</d>')
#docs_flat_raw = [tok for doc in sufarr.docs for tok in doc + ['</d>']])
#%%
%timeit rarest_words_by_sufarr_idx = rare_word_raw[sufarr.suffix_array[a:b] + 1]
#[rarest_words_by_doc[sufarr.doc_idx[idx]][sufarr.tok_idx[idx] + 1] for idx in range(a,b)]
#%%
%timeit for idx in range(a,b): offset = sufarr.suffix_array[idx]; phrase = docs_flat_raw[offset:offset+5]
#%%
%timeit for idx in range(a,b): sufarr.get_partial_suffix(idx, 1, 5)
#%%
context_words = 1
N_EVAL = 3
while True:
phrase = sufarr.get_partial_suffix(a, context_words, context_words + N_EVAL)
if len(phrase) < N_EVAL:
a += 1
else:
break
states = [start_state]
scores = [0.]
while len(states) < N_EVAL + 1:
state = kenlm.State()
score = model.model.BaseScore(states[-1], phrase[len(states) - 1], state)
scores.append(scores[-1] + score)
states.append(state)
#%%
skipped = 0
lcp = suggestion_generator.sufarr.lcp
for idx in tqdm.tqdm(range(a+1, b)):
in_common = lcp[idx-1] - context_words
new_phrase = sufarr.get_partial_suffix(idx, context_words, context_words + N_EVAL)
states[in_common+1:] = []
scores[in_common+1:] = []
if len(new_phrase) < N_EVAL or '</S>' in new_phrase:
skipped += 1
continue
while len(states) < N_EVAL + 1:
state = kenlm.State()
score = 0#model.model.BaseScore(states[-1], phrase[len(states) - 1], state)
scores.append(scores[-1] + score)
states.append(state)
# assert scores[-1] * suggestion_generator.LOG10 == model.score_seq(start_state, phrase[:N_EVAL])[0]
#%%
for idx in tqdm.tqdm(range(a+1, b)):
model.score_seq(start_state, sufarr.get_partial_suffix(idx, context_words, context_words + N_EVAL))[0] | [
"kcarnold@alum.mit.edu"
] | kcarnold@alum.mit.edu |
87f02715b690985909049acdc08e8c98984300e1 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_259/ch89_2020_05_06_17_38_05_834845.py | e551edeb3e60c84128b1bced37b853fd9b3307c6 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 265 | py | class Circulo:
def __init__(self,centro,raio):
self.centro = p1
self.raio = numero
def Contem(self,ponto):
if ((self.centro.x-ponto.x)**2+(self.centro.y-ponto.y)**2)**0.5 < self.raio:
return True
return False | [
"you@example.com"
] | you@example.com |
250a4740724dde3382658dc89f01f5972e1f4cd5 | 8b5e9766ca9e2a3457e921f8fda0649b4f4019b5 | /src/pytest_benchmark/histogram.py | 99ed4eacc97952485d642a06d049181befa89fde | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | stanislavlevin/pytest-benchmark | b53b111c20a32f8d8bc4d32a3556740ed0012d96 | e6d9b63468319ec87504f6c81592826ee242887b | refs/heads/master | 2020-04-12T09:58:10.103228 | 2018-11-23T15:45:59 | 2018-11-25T04:03:23 | 162,414,447 | 0 | 0 | BSD-2-Clause | 2018-12-19T09:30:34 | 2018-12-19T09:30:33 | null | UTF-8 | Python | false | false | 3,478 | py | from collections import Iterable
import py
from .utils import TIME_UNITS
from .utils import slugify
try:
from pygal.graph.box import Box
from pygal.style import DefaultStyle
except ImportError as exc:
raise ImportError(exc.args, "Please install pygal and pygaljs or pytest-benchmark[histogram]")
class CustomBox(Box):
def _box_points(self, serie, _):
return serie, [serie[0], serie[6]]
def _value_format(self, x):
return "Min: {0[0]:.4f}\n" \
"Q1-1.5IQR: {0[1]:.4f}\n" \
"Q1: {0[2]:.4f}\nMedian: {0[3]:.4f}\nQ3: {0[4]:.4f}\n" \
"Q3+1.5IQR: {0[5]:.4f}\n" \
"Max: {0[6]:.4f}".format(x[:7])
def _format(self, x, *args):
sup = super(CustomBox, self)._format
if args:
val = x.values
else:
val = x
if isinstance(val, Iterable):
return self._value_format(val), val[7]
else:
return sup(x, *args)
def _tooltip_data(self, node, value, x, y, classes=None, xlabel=None):
super(CustomBox, self)._tooltip_data(node, value[0], x, y, classes=classes, xlabel=None)
self.svg.node(node, 'desc', class_="x_label").text = value[1]
def make_plot(benchmarks, title, adjustment):
class Style(DefaultStyle):
colors = ["#000000" if row["path"] else DefaultStyle.colors[1]
for row in benchmarks]
font_family = 'Consolas, "Deja Vu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace'
minimum = int(min(row["min"] * adjustment for row in benchmarks))
maximum = int(max(
min(row["max"], row["hd15iqr"]) * adjustment
for row in benchmarks
) + 1)
try:
import pygaljs
except ImportError:
opts = {}
else:
opts = {
"js": [
pygaljs.uri("2.0.x", "pygal-tooltips.js")
]
}
plot = CustomBox(
box_mode='tukey',
x_label_rotation=-90,
x_labels=["{0[name]}".format(row) for row in benchmarks],
show_legend=False,
title=title,
x_title="Trial",
y_title="Duration",
style=Style,
min_scale=20,
max_scale=20,
truncate_label=50,
range=(minimum, maximum),
zero=minimum,
css=[
"file://style.css",
"file://graph.css",
"""inline:
.tooltip .value {
font-size: 1em !important;
}
.axis text {
font-size: 9px !important;
}
"""
],
**opts
)
for row in benchmarks:
serie = [row[field] * adjustment for field in ["min", "ld15iqr", "q1", "median", "q3", "hd15iqr", "max"]]
serie.append(row["path"])
plot.add("{0[fullname]} - {0[rounds]} rounds".format(row), serie)
return plot
def make_histogram(output_prefix, name, benchmarks, unit, adjustment):
if name:
path = "{0}-{1}.svg".format(output_prefix, slugify(name))
title = "Speed in {0} of {1}".format(TIME_UNITS[unit], name)
else:
path = "{0}.svg".format(output_prefix)
title = "Speed in {0}".format(TIME_UNITS[unit])
output_file = py.path.local(path).ensure()
plot = make_plot(
benchmarks=benchmarks,
title=title,
adjustment=adjustment,
)
plot.render_to_file(str(output_file))
return output_file
| [
"contact@ionelmc.ro"
] | contact@ionelmc.ro |
fe32a7e6d3393931c7e334cc368e537008db42c1 | c50e7eb190802d7849c0d0cea02fb4d2f0021777 | /src/securityinsight/azext_sentinel/aaz/latest/sentinel/entity_query/template/__cmd_group.py | 91049c1fe8f891761c3c334396713083e30a9df8 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | Azure/azure-cli-extensions | c1615b19930bba7166c282918f166cd40ff6609c | b8c2cf97e991adf0c0a207d810316b8f4686dc29 | refs/heads/main | 2023-08-24T12:40:15.528432 | 2023-08-24T09:17:25 | 2023-08-24T09:17:25 | 106,580,024 | 336 | 1,226 | MIT | 2023-09-14T10:48:57 | 2017-10-11T16:27:31 | Python | UTF-8 | Python | false | false | 648 | 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 aaz-dev-tools
# --------------------------------------------------------------------------------------------
# pylint: skip-file
# flake8: noqa
from azure.cli.core.aaz import *
@register_command_group(
"sentinel entity-query template",
)
class __CMDGroup(AAZCommandGroup):
"""Manage entity query template with sentinel.
"""
pass
__all__ = ["__CMDGroup"]
| [
"noreply@github.com"
] | Azure.noreply@github.com |
fd0fee403e8525c2faf6875daec96b184ed9db55 | 3f658c0098a66015840bd9d631987e6b937bb300 | /53.Flask_CafeWifi/main.py | 3e74bc359eee40baaa9c1fc79e03690a38a78d0a | [] | no_license | RohitPr/PythonProjects | 4cf7ec37cfba60afecc88ae542cc4155b72f4098 | 7dd807a45cd86cf0851cb95a1b1433805891f990 | refs/heads/main | 2023-06-01T06:42:40.147968 | 2021-06-13T00:57:05 | 2021-06-13T00:57:05 | 337,298,986 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,604 | py | from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, DateField
from wtforms.fields.core import SelectField
from wtforms_components import TimeField
from wtforms.validators import DataRequired, URL
import csv
app = Flask(__name__)
app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
Bootstrap(app)
class CafeForm(FlaskForm):
cafe = StringField('Cafe name', validators=[DataRequired()])
location = StringField("Cafe Location on Google Maps (URL)", validators=[
DataRequired(), URL()])
open = TimeField("Opening Time",
validators=[DataRequired()])
close = TimeField("Closing Time",
validators=[DataRequired()])
coffee_rating = SelectField("Coffee Rating", choices=[
"☕️", "☕☕", "☕☕☕", "☕☕☕☕", "☕☕☕☕☕"], validators=[DataRequired()])
wifi_rating = SelectField("Wifi Strength Rating", choices=[
"✘", "💪", "💪💪", "💪💪💪", "💪💪💪💪", "💪💪💪💪💪"], validators=[DataRequired()])
power_rating = SelectField("Power Socket Availability", choices=[
"✘", "🔌", "🔌🔌", "🔌🔌🔌", "🔌🔌🔌🔌", "🔌🔌🔌🔌🔌"], validators=[DataRequired()])
submit = SubmitField('Submit')
# all Flask routes below
@ app.route("/")
def home():
return render_template("index.html")
@ app.route('/add', methods=['GET', 'POST'])
def add_cafe():
form = CafeForm()
if form.validate_on_submit():
with open("cafe-data.csv", mode="a", encoding="utf-8") as csv_file:
csv_file.write(f"\n{form.cafe.data},"
f"{form.location.data},"
f"{form.open.data},"
f"{form.close.data},"
f"{form.coffee_rating.data},"
f"{form.wifi_rating.data},"
f"{form.power_rating.data}")
return redirect(url_for('cafes'))
return render_template('add.html', form=form)
@ app.route('/cafes')
def cafes():
with open('cafe-data.csv', newline='', encoding="utf8") as csv_file:
csv_data = csv.reader(csv_file, delimiter=',')
list_of_rows = []
for row in csv_data:
list_of_rows.append(row)
return render_template('cafes.html', cafes=list_of_rows)
if __name__ == '__main__':
app.run(debug=True)
| [
"bladekiller95@gmail.com"
] | bladekiller95@gmail.com |
46a2c839cd2adda1f78de52d264f9c9633dcced1 | eeeb97414f4182c373ba95e53353adb187bd3b0e | /app/main/views.py | 7272292e11c4878121ddde53a29021f4db377abc | [
"MIT"
] | permissive | tharcissie/pitchapp | 02ad1aad01a751c6bc3ddaa32e1c7bc7fd511e92 | c5c734694f7b68342db5e07e6312ed8605696263 | refs/heads/master | 2023-02-07T07:41:15.065913 | 2020-12-21T06:50:56 | 2020-12-21T06:50:56 | 316,588,283 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 4,124 | py | from flask import render_template, redirect, url_for,abort,request
from . import main
from flask_login import login_required,current_user
from ..models import User,Pitch,Comment,Upvote,Downvote
from .form import UpdateProfile,PitchForm,CommentForm
from .. import db,photos
@main.route('/')
def index():
pitch = Pitch.query.all()
hobbies = Pitch.query.filter_by(category = 'Hobbies').all()
experiences = Pitch.query.filter_by(category = 'Experiences').all()
skills = Pitch.query.filter_by(category = 'Skills').all()
return render_template('index.html', hobbies = hobbies, experiences = experiences, pitch = pitch, skills= skills)
@main.route('/new_pitch', methods = ['POST','GET'])
@login_required
def new_pitch():
form = PitchForm()
if form.validate_on_submit():
title = form.title.data
pitch = form.pitch.data
category = form.category.data
user_id = current_user
new_pitch_object = Pitch(pitch=pitch,user_id=current_user._get_current_object().id,category=category,title=title)
new_pitch_object.save_pitch()
return redirect(url_for('main.index'))
return render_template('pitch.html', form = form)
@main.route('/comment/<int:pitch_id>', methods = ['POST','GET'])
@login_required
def comment(pitch_id):
form = CommentForm()
pitch = Pitch.query.get(pitch_id)
all_comments = Comment.query.filter_by(pitch_id = pitch_id).all()
if form.validate_on_submit():
comment = form.comment.data
pitch_id = pitch_id
user_id = current_user._get_current_object().id
new_comment = Comment(comment = comment,user_id = user_id,pitch_id = pitch_id)
new_comment.save_comment()
return redirect(url_for('.comment', pitch_id = pitch_id))
return render_template('comment.html', form =form, pitch = pitch,all_comments=all_comments)
@main.route('/user/<name>')
def profile(name):
user = User.query.filter_by(username = name).first()
user_id = current_user._get_current_object().id
pitch = Pitch.query.filter_by(user_id = user_id).all()
if user is None:
abort(404)
return render_template("profile/profile.html", user = user,pitch=pitch)
@main.route('/user/<name>/updateprofile', methods = ['POST','GET'])
@login_required
def updateprofile(name):
form = UpdateProfile()
user = User.query.filter_by(username = name).first()
if user == None:
abort(404)
if form.validate_on_submit():
user.bio = form.bio.data
user.save_user()
return redirect(url_for('.profile',name = name))
return render_template('profile/update.html',form =form)
@main.route('/user/<name>/update/profile',methods= ['POST'])
@login_required
def update_profile(name):
user = User.query.filter_by(username = name).first()
if 'photo' in request.files:
filename = photos.save(request.files['photo'])
path = f'photos/{filename}'
user.profile_pic_path = path
db.session.commit()
return redirect(url_for('main.profile',name=name))
@main.route('/upvote/<int:id>',methods = ['POST','GET'])
@login_required
def like(id):
pitches = Upvote.get_upvotes(id)
valid_string = f'{current_user.id}:{id}'
for pitch in pitches:
to_str = f'{pitch}'
print(valid_string+" "+to_str)
if valid_string == to_str:
return redirect(url_for('main.index',id=id))
else:
continue
new_upvote = Upvote(user = current_user, pitch_id=id)
new_upvote.save_upvote()
return redirect(url_for('main.index',id=id))
@main.route('/downvote/<int:id>',methods = ['POST','GET'])
@login_required
def dislike(id):
pitches = Downvote.get_downvotes(id)
valid_string = f'{current_user.id}:{id}'
for pitch in pitches:
to_str = f'{p}'
print(valid_string+" "+to_str)
if valid_string == to_str:
return redirect(url_for('main.index',id=id))
else:
continue
new_downvote = Downvote(user = current_user, pitch_id=id)
new_downvote.save_downvote()
return redirect(url_for('main.index',id = id))
| [
"tharcissieidufashe@gmail.com"
] | tharcissieidufashe@gmail.com |
458015465088494352355186a88764a734c45216 | 234886b79094aa9905a4d44a5167b748c88e7961 | /nod32-2.py | 9777fd2516a205c1bf934bb15f489c493c391919 | [] | no_license | rurigeo/python | 929d3bde7dc90e38ce396831de8d6d016e5a9828 | 31a46533020fb716673e2464f573b2e15f364116 | refs/heads/master | 2021-01-01T17:42:05.071824 | 2015-01-05T03:56:42 | 2015-01-05T03:56:42 | 28,733,277 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 490 | py | #! /usr/bin/env python
# coding=utf-8
import urllib2
response = urllib2.urlopen('http://www.nod32jihuoma.cn/')
html = response.read()
with open('test','wb') as f : f.write(html)
f = open('test','rb')
for line in f:
#print line.decode('utf-8').rstrip()
if line.rstrip().startswith('<p>用户名'):
print line.rstrip()
user = line.rstrip()[15:31]
passwd = line.rstrip()[48:58]
print 'user:%s\npassword:%s' %(user,passwd)
break
| [
"you@example.com"
] | you@example.com |
b7eb06bd358d82f342e1a9fdbfe3a27e4a171857 | 494b763f2613d4447bc0013100705a0b852523c0 | /dnn/ex05_overfittingCheck.py | 9a0575cd56b68bdd68c4c397529f18b80d6362aa | [] | no_license | DL-DeepLearning/Neural-Network | dc4a2dd5efb1b4ef1a3480a1df6896c191ae487f | 3160c4af78dba6bd39552bb19f09a699aaab8e9e | refs/heads/master | 2021-06-17T05:16:22.583816 | 2017-06-07T01:21:39 | 2017-06-07T01:21:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,920 | py | #-*- coding: utf-8 -*-
''' Import theano and numpy '''
import theano
import numpy as np
execfile('00_readingInput.py')
''' set the size of mini-batch and number of epochs'''
batch_size = 16
nb_epoch = 50
''' Import keras to build a DL model '''
from keras.models import Sequential
from keras.layers.core import Dense Activation
print 'Building a model whose optimizer=adam, activation function=softplus'
model_adam = Sequential()
model_adam.add(Dense(128, input_dim=200))
model_adam.add(Activation('softplus'))
model_adam.add(Dense(256))
model_adam.add(Activation('softplus'))
model_adam.add(Dense(5))
model_adam.add(Activation('softmax'))
''' Setting optimizer as Adam '''
from keras.optimizers import SGD, Adam, RMSprop, Adagrad
model_adam.compile(loss= 'categorical_crossentropy',
optimizer='Adam',
metrics=['accuracy'])
'''Fit models and use validation_split=0.1 '''
history_adam = model_adam.fit(X_train, Y_train,
batch_size=batch_size,
nb_epoch=nb_epoch,
verbose=0,
shuffle=True,
validation_split=0.1)
loss_adam= history_adam.history.get('loss')
acc_adam = history_adam.history.get('acc')
''' Access the performance on validation data '''
val_loss_adam = history_adam.history.get('val_loss')
val_acc_adam = history_adam.history.get('val_acc')
''' Visualize the loss and accuracy of both models'''
import matplotlib.pyplot as plt
plt.figure(4)
plt.subplot(121)
plt.plot(range(len(loss_adam)), loss_adam,label='Training')
plt.plot(range(len(val_loss_adam)), val_loss_adam,label='Validation')
plt.title('Loss')
plt.legend(loc='upper left')
plt.subplot(122)
plt.plot(range(len(acc_adam)), acc_adam,label='Training')
plt.plot(range(len(val_acc_adam)), val_acc_adam,label='Validation')
plt.title('Accuracy')
#plt.show()
plt.savefig('05_overfittingCheck.png',dpi=300,format='png')
print 'Result saved into 05_overfittingCheck.png' | [
"teinhonglo@gmail.com"
] | teinhonglo@gmail.com |
2b6473bd7bb963c995ddf41427e148de56526422 | a59ec95fddc064ea9a554ad41e4ac8e82376701a | /xadmin/demo_app/repurchasearea/migrations/0002_sale.py | 02ff589f4ecd5b0fac9b11243a3304b878169813 | [
"BSD-3-Clause"
] | permissive | Nicholas86/PythonDemos | 449c08713c7c03633719a4ae7287b127783d7574 | 4f06639cc65a5e10cc993335d3d34e2d60aac983 | refs/heads/master | 2021-01-22T21:07:11.457179 | 2017-08-18T06:40:44 | 2017-08-18T06:40:44 | 100,681,216 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,954 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-07-17 10:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0007_address_user_id'),
('repurchasearea', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Sale',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('goods_name', models.CharField(max_length=255, verbose_name='\u5546\u54c1\u540d\u79f0')),
('goods_price', models.DecimalField(decimal_places=2, max_digits=10, verbose_name='\u5546\u54c1\u4ef7\u683c')),
('market_price', models.DecimalField(decimal_places=2, max_digits=10, verbose_name='\u5e02\u573a\u4ef7')),
('goods_tag', models.CharField(max_length=2555, verbose_name='\u5546\u54c1\u6807\u7b7e')),
('goods_picture', models.ImageField(upload_to='images/Sale', verbose_name='\u5546\u54c1\u56fe\u7247')),
('addtime', models.DateTimeField(auto_now_add=True, verbose_name='\u53d1\u5e03\u65f6\u95f4')),
('is_ok', models.CharField(choices=[('0', '\u5426'), ('1', '\u662f')], max_length=255, verbose_name='\u662f\u5426\u901a\u8fc7\u5ba1\u6838')),
('discount', models.CharField(max_length=255, verbose_name='\u4f18\u60e0\u6bd4\u4f8b')),
('goods_description', models.TextField(max_length=5555, verbose_name='\u5546\u54c1\u63cf\u8ff0')),
('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.TheUser', verbose_name='\u7528\u6237')),
],
options={
'verbose_name': '\u6211\u8981\u5356',
'verbose_name_plural': '\u6211\u8981\u5356',
},
),
]
| [
"970649831@qq.com"
] | 970649831@qq.com |
bb73d12a82c820135bba274b472bb02a2b25b8f0 | 9262e23dcff032dbbd05d724435d473778f47417 | /pywind/ofgem/StationSearch.py | cbb1acba5bd013e9b00481dfeda6c4be303982cf | [] | no_license | mseaborn/pywind | c825bd6c32db226a10a1389a6fd9e1e28656438a | ca89a305cdcfd56891afce33a0613208f1080ead | refs/heads/master | 2020-07-10T05:37:36.666758 | 2016-01-03T17:04:28 | 2016-01-03T17:04:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,380 | py | # coding=utf-8
#
# Copyright 2013-2015 david reid <zathrasorama@gmail.com>
#
# 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.
#
import copy
from .Base import OfgemForm
from pywind.ofgem.Station import Station
from lxml import etree
class StationSearch(object):
START_URL = 'ReportViewer.aspx?ReportPath=/Renewables/Accreditation/AccreditedStationsExternalPublic&ReportVisibility=1&ReportCategory=1'
def __init__(self):
self.form = OfgemForm(self.START_URL)
self.stations = []
def __len__(self):
return len(self.stations)
def __getitem__(self, item):
if 0 >= item < len(self.stations):
return self.stations[item]
def get_data(self):
if self.form.get_data():
doc = etree.fromstring(self.form.data)
# There are a few stations with multiple generator id's, separated by '\n' so
# capture them and add each as a separate entry.
for detail in doc.xpath("//*[local-name()='Detail']"):
st = Station(detail)
if b'\n' in st.generator_id:
ids = [x.strip() for x in st.generator_id.split(b'\n')]
st.generator_id = ids[0]
for _id in ids[1:]:
_st = copy.copy(st)
_st.generator_id = _id
self.stations.append(_st)
self.stations.append(st)
return True
return False
def filter_technology(self, what):
return self.form.set_value("technology", what)
def filter_scheme(self, scheme):
return self.form.set_value("scheme", scheme.upper())
def filter_name(self, name):
return self.form.set_value("generating station search", name)
def filter_generator_id(self, accno):
return self.form.set_value("accreditation search", accno)
| [
"zathrasorama@gmail.com"
] | zathrasorama@gmail.com |
3ae79867f0f0711e57ceb1c0cedc23de74baf1d0 | 54277288865f738e44d7be1d6b41b19c63af267e | /pyvrl/datasets/frame_samplers/uniform_sampler.py | e5263cac4c5dfcdf043d1b756c2e3cb0057d981c | [] | no_license | scenarios/SR-SVRL | 7b41d29e16cff3020f333efc28a624d85bba4537 | 26e89ecb29355635b10a355f2f16f1b5db9c4e9b | refs/heads/master | 2023-02-26T06:16:13.314491 | 2021-01-30T16:30:57 | 2021-01-30T16:30:57 | 307,295,720 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,568 | py | import numpy as np
import random
from typing import List, Union
class UniformFrameSampler(object):
def __init__(self,
num_clips: int,
clip_len: int,
strides: Union[int, List[int]],
temporal_jitter: bool):
self.num_clips = num_clips
self.clip_len = clip_len
if isinstance(strides, (tuple, list)):
self.strides = strides
else:
self.strides = [strides]
self.temporal_jitter = temporal_jitter
def sample(self, num_frames: int):
stride = random.choice(self.strides)
base_length = self.clip_len * stride
delta_length = num_frames - base_length + 1
if delta_length > 0:
tick = float(delta_length) / self.num_clips
offsets = np.array([int(tick / 2.0 + tick * x)
for x in range(self.num_clips)], np.int)
else:
offsets = np.zeros((self.num_clips, ), np.int)
inds = np.arange(0, base_length, stride, dtype=np.int).reshape(1, self.clip_len)
if self.num_clips > 1:
inds = np.tile(inds, (self.num_clips, 1))
# apply for the init offset
inds = inds + offsets.reshape(self.num_clips, 1)
if self.temporal_jitter and stride > 1:
skip_offsets = np.random.randint(stride, size=self.clip_len)
inds = inds + skip_offsets.reshape(1, self.clip_len)
inds = np.clip(inds, a_min=0, a_max=num_frames-1)
inds = inds.astype(np.int)
return inds
| [
"zyz0205@hotmail.com"
] | zyz0205@hotmail.com |
bef650bd59c2153082ed917c021d96d1a21834a3 | 786232b3c9eac87728cbf2b5c5636d7b6f10f807 | /Leetcode/medium/130.py | f3efee7f4cf1148a224934ce604343805b35df73 | [] | no_license | luoyanhan/Algorithm-and-data-structure | c9ada2e123fae33826975665be37ca625940ddd4 | fb42c3a193f58360f6b6f3b7d5d755cd6e80ad5b | refs/heads/master | 2021-12-22T15:45:28.260386 | 2021-12-02T03:08:35 | 2021-12-02T03:08:35 | 251,007,078 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,850 | py | class Solution:
def solve(self, board) -> None:
if not board:
return
rows = len(board)
cols = len(board[0])
def dfs(board, i, j):
if i < 0 or i >= rows or j < 0 or j >= cols or board[i][j] != 'O':
return
board[i][j] = '#'
dfs(board, i - 1, j)
dfs(board, i + 1, j)
dfs(board, i, j - 1)
dfs(board, i, j + 1)
for i in [0, rows-1]:
for j in range(cols):
if board[i][j] == 'O':
dfs(board, i, j)
for i in range(rows):
for j in [0, cols-1]:
if board[i][j] == 'O':
dfs(board, i, j)
for i in range(rows):
for j in range(cols):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '#':
board[i][j] = 'O'
class Solution:
def solve(self, board) -> None:
if not board:
return
rows = len(board)
cols = len(board[0])
def dfs(i, j):
nonlocal board
board[i][j] = '#'
stack = [[i, j]]
while stack:
x, y = stack[-1]
if 0 <= x+1 < rows and board[x+1][y] == 'O':
board[x+1][y] = '#'
stack.append([x+1, y])
continue
if 0 <= x-1 < rows and board[x-1][y] == 'O':
board[x-1][y] = '#'
stack.append([x-1, y])
continue
if 0 <= y+1 < cols and board[x][y+1] == 'O':
board[x][y+1] = '#'
stack.append([x, y+1])
continue
if 0 <= y-1 < cols and board[x][y-1] == 'O':
board[x][y-1] = '#'
stack.append([x, y-1])
continue
x, y = stack.pop()
for i in [0, rows-1]:
for j in range(cols):
if board[i][j] == 'O':
dfs(i, j)
for i in range(rows):
for j in [0, cols-1]:
if board[i][j] == 'O':
dfs(i, j)
for i in range(rows):
for j in range(cols):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '#':
board[i][j] = 'O'
class Solution:
def solve(self, board) -> None:
if not board:
return
rows = len(board)
cols = len(board[0])
def bfs(i, j):
nonlocal board
board[i][j] = '#'
stack = [[i, j]]
while stack:
x, y = stack.pop(0)
if 0 <= x+1 < rows and board[x+1][y] == 'O':
board[x+1][y] = '#'
stack.append([x+1, y])
if 0 <= x-1 < rows and board[x-1][y] == 'O':
board[x-1][y] = '#'
stack.append([x-1, y])
if 0 <= y+1 < cols and board[x][y+1] == 'O':
board[x][y+1] = '#'
stack.append([x, y+1])
if 0 <= y-1 < cols and board[x][y-1] == 'O':
board[x][y-1] = '#'
stack.append([x, y-1])
for i in [0, rows-1]:
for j in range(cols):
if board[i][j] == 'O':
bfs(i, j)
for i in range(rows):
for j in [0, cols-1]:
if board[i][j] == 'O':
bfs(i, j)
for i in range(rows):
for j in range(cols):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '#':
board[i][j] = 'O'
| [
"707025023@qq.com"
] | 707025023@qq.com |
9be1ccf4fb9057ff69eb200527dba9ac9462a585 | 6b9888a32733bc9d67f290cd006fb4dca84bcaf1 | /users/admin.py | ad1d88cde2247208a9212ee198fc22f718c790b8 | [] | no_license | Shatki/TanyaSite2.7 | a2008257a63134411139594c54473e88f21df8c0 | 69c7d6516d3d28dbe9370d94aacce0ac04070822 | refs/heads/master | 2020-04-30T02:31:10.274659 | 2019-03-27T19:41:59 | 2019-03-27T19:41:59 | 176,562,060 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,569 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import forms
from .models import User, Feedback
class UserCreationForm(forms.UserCreationForm):
class Meta:
model = User
fields = (
'username',
'email',
'first_name',
'last_name',
)
readonly_fields = (
'date_joined',
'date_updated',)
class UserChangeForm(forms.UserChangeForm):
class Meta:
model = User
fields = (
'username',
'email',
'password',
'is_admin',
'user_permissions',
)
@admin.register(User)
class UserAdmin(UserAdmin):
model = User
form = UserChangeForm
add_form = UserCreationForm
list_display = (
'username',
'email',
'first_name',
'last_name',
'last_login')
list_filter = (
'date_joined',
'last_login',
)
readonly_fields = (
'date_joined',
'date_updated',
'last_login',
)
fieldsets = (
(None, {
'fields': (
'username',
'password',
)
}),
(u'Персональная информация', {
'fields': (
'first_name',
'last_name',
'photo',
)
}),
(u'Права доступа', {
'fields': (
'groups',
'user_permissions',
'is_admin',
)
}),
(u'Важные даты', {
'fields': (
'last_login',
'date_joined',
'date_updated',
)
}),
)
add_fieldsets = (
(None, {
'classes':
('wide',),
'fields': (
'email',
'password',
'is_admin',
)
}),
)
search_fields = (
'email',)
ordering = (
'date_joined',)
filter_horizontal = (
'groups',
'user_permissions',
)
# Register your models here.
@admin.register(Feedback)
class FeedbackAdmin(admin.ModelAdmin):
list_display = ('name',
'date',
'email',
'subject',
'message',
)
search_fields = ('name',)
ordering = ('date',)
| [
"Shatki@mail.ru"
] | Shatki@mail.ru |
509047a9ed74a663ba2172533a3ff084bfe7d217 | f9d564f1aa83eca45872dab7fbaa26dd48210d08 | /huaweicloud-sdk-eihealth/huaweicloudsdkeihealth/v1/model/list_image_tag_request.py | 90185a5e2726fddf941f3db5190f683b70ee737d | [
"Apache-2.0"
] | permissive | huaweicloud/huaweicloud-sdk-python-v3 | cde6d849ce5b1de05ac5ebfd6153f27803837d84 | f69344c1dadb79067746ddf9bfde4bddc18d5ecf | refs/heads/master | 2023-09-01T19:29:43.013318 | 2023-08-31T08:28:59 | 2023-08-31T08:28:59 | 262,207,814 | 103 | 44 | NOASSERTION | 2023-06-22T14:50:48 | 2020-05-08T02:28:43 | Python | UTF-8 | Python | false | false | 4,316 | py | # coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListImageTagRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'eihealth_project_id': 'str',
'image_id': 'str'
}
attribute_map = {
'eihealth_project_id': 'eihealth_project_id',
'image_id': 'image_id'
}
def __init__(self, eihealth_project_id=None, image_id=None):
"""ListImageTagRequest
The model defined in huaweicloud sdk
:param eihealth_project_id: 医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。
:type eihealth_project_id: str
:param image_id: 镜像id
:type image_id: str
"""
self._eihealth_project_id = None
self._image_id = None
self.discriminator = None
self.eihealth_project_id = eihealth_project_id
self.image_id = image_id
@property
def eihealth_project_id(self):
"""Gets the eihealth_project_id of this ListImageTagRequest.
医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。
:return: The eihealth_project_id of this ListImageTagRequest.
:rtype: str
"""
return self._eihealth_project_id
@eihealth_project_id.setter
def eihealth_project_id(self, eihealth_project_id):
"""Sets the eihealth_project_id of this ListImageTagRequest.
医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。
:param eihealth_project_id: The eihealth_project_id of this ListImageTagRequest.
:type eihealth_project_id: str
"""
self._eihealth_project_id = eihealth_project_id
@property
def image_id(self):
"""Gets the image_id of this ListImageTagRequest.
镜像id
:return: The image_id of this ListImageTagRequest.
:rtype: str
"""
return self._image_id
@image_id.setter
def image_id(self, image_id):
"""Sets the image_id of this ListImageTagRequest.
镜像id
:param image_id: The image_id of this ListImageTagRequest.
:type image_id: str
"""
self._image_id = image_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListImageTagRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
8ee63e735b089b79918fd1a7e922e8c9e2efe5dd | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_017/ch19_2020_09_30_19_20_44_293987.py | ddb89c04d24c9ab8a2235c3a4071ba046f6c3af0 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 213 | py | def classifica_triangulo(a,b,c):
if a == b and b==c:
return "equilátero"
elif a == b and a != c or a==c and a!= b or b==c and b!=a:
return "isósceles"
else:
return "escaleno"
| [
"you@example.com"
] | you@example.com |
d2ffd9a8a0f8818b36082eb7be20047d65ee079e | 309556112e15b2b79c2e857d495d3f363a9f8c69 | /Python/GA_Class/6_logreg/example_logreg.py | d585a00b18074293f31e9f2431aeda4d7a7daddb | [] | no_license | karoljohnston/data-analysis-examples | 0aeefd8bc0780c0cc6135352a79605ac68484afd | fbd46483072bf544102bc5c02917743c5a3bb976 | refs/heads/master | 2023-03-17T15:09:29.290959 | 2016-03-22T12:15:53 | 2016-03-22T12:15:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 429 | py | """ Logistic Regression is a type of probabilistic statistical classification
model used to predict a binary response from a binary predictor
* We use Linear Regression for a response that is continuous and binary for
one that is 0 and 1's, like alive or dead
* Used for predicting the outcome of a categorical dependent variable
(i.e., a class label) based on one or more predictor variables (features)
*
"""
| [
"William.Q.Liu@gmail.com"
] | William.Q.Liu@gmail.com |
c015ef847a2a849a4f5d0fbfe324e61baf9638bf | d1d79d0c3889316b298852834b346d4246825e66 | /blackbot/core/wss/ttp/art/art_T1071.004-1.py | 6a6eff49b2d77503a64c7522e67acc60bc7209ce | [] | no_license | ammasajan/Atomic-Red-Team-Intelligence-C2 | 78d1ed2de49af71d4c3c74db484e63c7e093809f | 5919804f0bdeb15ea724cd32a48f377bce208277 | refs/heads/master | 2023-07-17T12:48:15.249921 | 2021-08-21T20:10:30 | 2021-08-21T20:10:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,897 | py | from blackbot.core.utils import get_path_in_package
from blackbot.core.wss.atomic import Atomic
from terminaltables import SingleTable
import os
import json
class Atomic(Atomic):
def __init__(self):
self.name = 'CommandControl/T1071.004-1'
self.controller_type = ''
self.external_id = 'T1071.004'
self.blackbot_id = 'T1071.004-1'
self.version = ''
self.language = 'boo'
self.description = self.get_description()
self.last_updated_by = 'Blackbot, Inc. All Rights reserved'
self.references = ["System.Management.Automation"]
self.options = {
'OutString': {
'Description' : 'Appends Out-String to the PowerShellCode',
'Required' : False,
'Value' : True,
},
'BypassLogging': {
'Description' : 'Bypasses ScriptBlock and Techniques logging',
'Required' : False,
'Value' : True,
},
'BypassAmsi': {
'Description' : 'Bypasses AMSI',
'Required' : False,
'Value' : True,
}
}
def payload(self):
with open(get_path_in_package('core/wss/ttp/art/src/powershell.boo'), 'r') as ttp_src:
src = ttp_src.read()
pwsh_script = get_path_in_package('core/wss/ttp/art/pwsh_ttp/commandAndControl/T1071.004-1')
with open(pwsh_script) as pwsh:
src = src.replace("POWERSHELL_SCRIPT", pwsh.read())
src = src.replace("OUT_STRING", str(self.options["OutString"]["Value"]).lower())
src = src.replace("BYPASS_LOGGING", str(self.options["BypassLogging"]["Value"]).lower())
src = src.replace("BYPASS_AMSI", str(self.options["BypassAmsi"]["Value"]).lower())
return src
def get_description(self):
path = get_path_in_package('core/wss/ttp/art/pwsh_ttp/commandAndControl/T1071.004-1')
with open(path) as text:
head = [next(text) for l in range(4)]
technique_name = head[0].replace('#TechniqueName: ', '').strip('\n')
atomic_name = head[1].replace('#AtomicTestName: ', '').strip('\n')
description = head[2].replace('#Description: ', '').strip('\n')
language = head[3].replace('#Language: ', '').strip('\n')
aux = ''
count = 1
for char in description:
if char == '&':
continue
aux += char
if count % 126 == 0:
aux += '\n'
count += 1
out = '{}: {}\n{}\n\n{}\n'.format(technique_name, language, atomic_name, aux)
return out
| [
"root@uw2artic201.blackbot.net"
] | root@uw2artic201.blackbot.net |
c345aa80414650ac554092489ed0ab72952bae22 | eef659a707d87e979741cc11ad59344c911790f5 | /cc3/billing/migrations/0039_auto_20160907_1252.py | 99d7ee5b8028f8e281c4179cfbb988998ba510f3 | [] | no_license | qoin-open-source/samen-doen-cc3 | 1e5e40a9b677886aa78f980670df130cbbb95629 | 8b7806177e1e245af33b5112c551438b8c0af5d2 | refs/heads/master | 2020-05-04T02:26:07.039872 | 2019-04-02T21:19:54 | 2019-04-02T21:19:54 | 178,926,274 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 854 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('billing', '0038_auto_20160907_1132'),
]
operations = [
migrations.AlterModelOptions(
name='transactionparams',
options={'verbose_name_plural': 'Transaction parameters'},
),
migrations.AddField(
model_name='assignedproduct',
name='value',
field=models.FloatField(help_text='For percentage-based prices only', null=True, verbose_name='Value', blank=True),
),
migrations.AlterField(
model_name='transactionparams',
name='product',
field=models.OneToOneField(related_name='transaction_params', to='billing.Product'),
),
]
| [
"stephen.wolff@qoin.com"
] | stephen.wolff@qoin.com |
b1789fc9bfd8eb03b63cd55618176bb3246ad504 | 8e90afd3f0dc945d9ebd6099a60094807c0067cf | /Kangho/pro_four_rules_calculation.py | 152ba821a381a63c190ada513f227f36378c3783 | [] | no_license | Deserve82/KK_Algorithm_Study | ffa109e02f1c9297597c9e07c7c3006628046740 | d3ec01b66d6e3852b7d68adaa8ba87c7e9617e24 | refs/heads/master | 2021-11-10T00:23:30.711422 | 2021-10-23T02:37:04 | 2021-10-23T02:37:04 | 231,358,800 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,099 | py | def solution(arr):
mx = [[None for i in range(len(arr))] for j in range(len(arr)) ]
mi = [[None for i in range(len(arr))] for j in range(len(arr)) ]
def mxdp(a, b):
if a == b:
mx[a][b] = int(arr[a])
mi[a][b] = int(arr[a])
if mx[a][b] != None:
return mx[a][b]
tm = []
for i in range(a+1,b,2):
op = arr[i]
if op == "+":
tm.append(mxdp(a, i-1) + mxdp(i+1, b))
elif op == "-":
tm.append(mxdp(a, i-1) - midp(i+1, b))
mx[a][b] = max(tm)
return mx[a][b]
def midp(a, b):
if a == b:
mx[a][b] = int(arr[a])
mi[a][b] = int(arr[a])
if mi[a][b] != None:
return mi[a][b]
tm = []
for i in range(a+1,b,2):
op = arr[i]
if op == "+":
tm.append(midp(a, i-1) + midp(i+1, b))
elif op == "-":
tm.append(midp(a, i-1) - mxdp(i+1, b))
mi[a][b] = min(tm)
return mi[a][b]
return mxdp(0, len(arr)-1)
| [
"noreply@github.com"
] | Deserve82.noreply@github.com |
d261be900134a7888155a860a7ba078f36751b08 | 9efe15e39ffda8391abd5a63b95e441648ba57c2 | /event_service/app.py | b02fd16c6784654ca29e61e272a3ad7fd1c15105 | [] | no_license | TechAcademy-Azerbaijan/mini_microservice_app | 3af2f80047b9a945f07ac1d4c7dd5a01980169e0 | b06c13a7feac4b9f46ab1d3bed19e36a7de3cd4e | refs/heads/master | 2023-08-15T19:49:22.058966 | 2021-10-22T08:21:40 | 2021-10-22T08:21:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 171 | py | from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
from routers import *
if __name__ == '__main__':
app.run(port=5002, debug=True) | [
"idris.sabanli@gmail.com"
] | idris.sabanli@gmail.com |
129bfd5b719f491ee5efb2dd5d38136c3627af9c | a9e3f3ad54ade49c19973707d2beb49f64490efd | /Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/system_wide_roles/admin/forms.py | 7b0f8b93b9a1abffa55e9db24a5a78a83f9d01e9 | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | permissive | luque/better-ways-of-thinking-about-software | 8c3dda94e119f0f96edbfe5ba60ca6ec3f5f625d | 5809eaca7079a15ee56b0b7fcfea425337046c97 | refs/heads/master | 2021-11-24T15:10:09.785252 | 2021-11-22T12:14:34 | 2021-11-22T12:14:34 | 163,850,454 | 3 | 1 | MIT | 2021-11-22T12:12:31 | 2019-01-02T14:21:30 | JavaScript | UTF-8 | Python | false | false | 180 | py | """
Forms used for system wide roles admin.
"""
from edx_rbac.admin import UserRoleAssignmentAdminForm
class SystemWideRoleAssignmentForm(UserRoleAssignmentAdminForm):
pass
| [
"rafael.luque@osoco.es"
] | rafael.luque@osoco.es |
3e071265284220746e3abe9cf746007211033a47 | fef0991726dad837245b206c1720cf8da894ef53 | /TestWindow/testExample.py | 584e5edfee3c325f2ad42403555dc4ea96cd8fd2 | [] | no_license | TianD/TianDao-git-Test | 95dfbc644e9802b548c8c95201400fce7acd9e19 | 99cfbb742acf04c242a34657495bfa67bcbb68cd | refs/heads/master | 2020-04-15T19:10:57.386454 | 2014-07-04T15:08:35 | 2014-07-04T15:08:35 | 21,501,299 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 359 | py |
#coding=utf-8
import sys
from PyQt4 import QtCore, QtGui
class MyWindow( QtGui.QMainWindow ):
def __init__( self ):
QtGui.QMainWindow.__init__( self )
self.setWindowTitle( "PyQt" )
self.resize( 300, 200 )
app = QtGui.QApplication( sys.argv )
mywindow = MyWindow()
mywindow.show()
app.exec_() | [
"tiandao_dunjian@sina.cn"
] | tiandao_dunjian@sina.cn |
68c58fbec15f59c374e2ad7ea1ea5561ce6410d6 | 885d3e4017d96ed9fd56545d95ad63895e6dc01d | /rootpy/utils/tests/test_cpp.py | 24e5b87907e9d4dfe79ad31dbfa0cee3d658cc29 | [
"BSD-3-Clause"
] | permissive | rootpy/rootpy | c3eb7f70d29e4779a0bda8356fb96922bb95537f | 3926935e1f2100d8ba68070c2ab44055d4800f73 | refs/heads/master | 2021-01-17T04:08:51.330059 | 2019-01-05T17:05:50 | 2019-01-05T17:05:50 | 3,276,014 | 159 | 60 | BSD-3-Clause | 2019-12-08T12:35:08 | 2012-01-26T18:05:37 | Python | UTF-8 | Python | false | false | 1,191 | py | from __future__ import print_function
import sys
from ROOT import MethodProxy
import inspect
from rootpy.utils.cpp import CPPGrammar
from rootpy.utils.extras import iter_ROOT_classes
from nose.plugins.attrib import attr
@attr('slow')
def test_cpp():
i = 0
num_methods = 0
for cls in iter_ROOT_classes():
members = inspect.getmembers(cls)
# filter out those starting with "_" or "operator "
# and non-method members
# also split overloaded methods
methods = {}
for name, func in members:
if name.startswith('_') or name.startswith('operator'):
continue
if not isinstance(func, MethodProxy):
continue
methods[name] = (func, func.func_doc.split('\n'))
for name, (func, sigs) in methods.items():
for sig in sigs:
num_methods += 1
if CPPGrammar.parse_method(sig, silent=False):
i += 1
print("{0} / {1}".format(i, num_methods), end='\r')
sys.stdout.flush()
print("{0} / {1}".format(i, num_methods))
if __name__ == "__main__":
import nose
nose.runmodule()
| [
"noel.dawe@gmail.com"
] | noel.dawe@gmail.com |
19ee67b228a24979c31aff0bd9900dd58e0f1895 | 23545a102f6f937d59d39f95c682235113599096 | /main/models.py | 13076268296cd7d4b761496e8643fb26509001f6 | [] | no_license | Adi19471/vsu-rating-2021 | 11e6204d86e28320ad505bdf77150011fd041ff9 | 3360abf7b024058c60ce4a8d80f98300048e4a2d | refs/heads/main | 2023-07-13T18:56:02.395628 | 2021-06-24T06:17:01 | 2021-06-24T06:17:01 | 379,822,363 | 0 | 0 | null | 2021-08-29T09:58:45 | 2021-06-24T06:11:43 | JavaScript | UTF-8 | Python | false | false | 1,209 | py | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Movie(models.Model):
# fields for the movie table
name = models.CharField(max_length=300)
director = models.CharField(max_length=300)
cast = models.CharField(max_length=800)
description = models.TextField(max_length=5000)
release_date = models.DateField()
averageRating = models.FloatField(default=0)
image = models.URLField(default=None, null=True)
def __str__(self):
return self.name
def __unicode__(self):
return self.name
class Review(models.Model):
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.TextField(max_length=5000)
rating = models.FloatField(default=0)
def __str__(self):
return self.user.username
class Contact(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
# mobile = models.IntegerField()
comment = models.TextField(max_length=100)
def __str__(self):
return self.first_name | [
"akumatha@gmail.com"
] | akumatha@gmail.com |
313ef19914bc291335c072fdcf2d2a678887d9ff | 6c69b3229dc01621561330b67dca894799ea3804 | /PlantillaOpenGL.py | e479b259ec479cc2f03c41449ddd829dfdb32e91 | [] | no_license | DamianBurboa/PracticaCasa | 484cd86afd3890288c83c216cf24ceaee6afafa2 | 83222060594f0ff76d212a5214f0358387d22d71 | refs/heads/master | 2023-02-24T11:42:43.524122 | 2021-01-28T01:30:50 | 2021-01-28T01:30:50 | 333,610,506 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,207 | py | from OpenGL.GL import *
from glew_wish import *
import glfw
from math import *
def dibujarPasto():
glColor3f(0.427,0.819,0.321)
glBegin(GL_QUADS)
glVertex3f(-1.0,-0.6,0)
glVertex3f(1.0,-0.6,0)
glVertex3f(1.0,-1.0,0)
glVertex3f(-1.0,-1.0,0)
glEnd()
def dibujarSol():
glColor3f(0.921,0.898,0.301)
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.2 - 0.6, sin(angulo) * 0.2 + 0.6,0.0)
glEnd()
def dibujarCasa():
glColor3f(0.788,0.596,0.364)
glBegin(GL_QUADS)
glVertex3f(-0.20,0.1,0)
glVertex3f(0.70,0.1,0)
glVertex3f(0.70,-0.70,0)
glVertex3f(-0.20,-0.70,0)
glEnd()
def dibujarnube():
glColor3f(1,1,1)
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.15 - 0.2, sin(angulo) * 0.05 + 0.5 ,0.0)
glEnd()
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.24 - 0.0, sin(angulo) * 0.08 + 0.57 ,0.0)
glEnd()
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.20 + 0.50, sin(angulo) * 0.06 + 0.70 ,0.0)
glEnd()
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.10 + 0.70, sin(angulo) * 0.05 + 0.75 ,0.0)
glEnd()
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.10 + 0.75, sin(angulo) * 0.05 + 0.45 ,0.0)
glEnd()
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.20 + 0.55, sin(angulo) * 0.05 + 0.50 ,0.0)
glEnd()
def dibujartecho():
glColor3f(0.890,0.333,0.054)
glBegin(GL_TRIANGLES)
glVertex3f(-0.40,0.1,0)
glVertex3f(0.25,0.45,0)
glVertex3f(0.90,0.1,0)
glEnd()
def dibujarventana():
#Marco de la ventana
glColor3f(0.658,0.560,0.058)
glBegin(GL_QUADS)
glVertex3f(0.30,-0.05,0)
glVertex3f(0.60,-0.05,0)
glVertex3f(0.60,-0.30,0)
glVertex3f(0.30,-0.3,0)
glEnd()
#Vidrio de la ventana
glColor3f(0.239,0.819,0.741)
glBegin(GL_QUADS)
glVertex3f(0.32,-0.07,0)
glVertex3f(0.58,-0.07,0)
glVertex3f(0.58,-0.28,0)
glVertex3f(0.32,-0.28,0)
glEnd()
#lineas de la ventana
glColor3f(0.658,0.560,0.058)
glBegin(GL_QUADS)
glVertex3f(0.32,-0.173,0) #izqArr
glVertex3f(0.58,-0.173,0) #derArr
glVertex3f(0.58,-0.182,0) #derAba
glVertex3f(0.32,-0.182,0) #IzqAba
glEnd()
glColor3f(0.658,0.560,0.058)
glBegin(GL_QUADS)
glVertex3f(0.44,-0.07,0) #izqArr
glVertex3f(0.46,-0.07,0) #derArr
glVertex3f(0.46,-0.28,0) #derAba
glVertex3f(0.44,-0.28,0) #IzqAba
glEnd()
def dibujarPuerta():
#Puerta
glColor3f(0.545,0.639,0.592)
glBegin(GL_QUADS)
glVertex3f(0.15,-0.38,0) #izqArr
glVertex3f(0.40,-0.38,0) #derArr
glVertex3f(0.40,-0.70,0) #derAba
glVertex3f(0.15,-0.70,0) #IzqAba
glEnd()
#Perilla
glColor3f(0.380,0.388,0.384)
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.020 + 0.35, sin(angulo) * 0.020 - 0.53 ,0.0)
glEnd()
def dibujarArbol():
#Tronco
glColor3f(0.788,0.596,0.364)
glBegin(GL_QUADS)
glVertex3f(-0.75,-0.2,0) #izqArr
glVertex3f(-0.60,-0.2,0) #derArr
glVertex3f(-0.60,-0.70,0) #derAba
glVertex3f(-0.75,-0.70,0) #izqAba
glEnd()
#Hojas
glColor3f(0.196,0.470,0.180)
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.2 - 0.675, sin(angulo) * 0.2 -0.2 ,0.0)
glEnd()
glColor3f(0.196,0.470,0.180)
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.15 - 0.675, sin(angulo) * 0.15 - 0.03 ,0.0)
glEnd()
glColor3f(0.196,0.470,0.180)
glBegin(GL_POLYGON)
for x in range(360):
angulo = x * 3.14159 / 180.0
glVertex3f(cos(angulo) * 0.10 - 0.675, sin(angulo) * 0.10 + 0.1 ,0.0)
glEnd()
def dibujar():
#rutinas de dibujo
dibujarPasto()
dibujarSol()
dibujarCasa()
dibujarnube()
dibujartecho()
dibujarventana()
dibujarPuerta()
dibujarArbol()
def main():
#inicia glfw
if not glfw.init():
return
#crea la ventana,
# independientemente del SO que usemos
window = glfw.create_window(800,800,"Mi ventana", None, None)
#Configuramos OpenGL
glfw.window_hint(glfw.SAMPLES, 4)
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR,3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR,3)
glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
#Validamos que se cree la ventana
if not window:
glfw.terminate()
return
#Establecemos el contexto
glfw.make_context_current(window)
#Activamos la validación de
# funciones modernas de OpenGL
glewExperimental = True
#Inicializar GLEW
if glewInit() != GLEW_OK:
print("No se pudo inicializar GLEW")
return
#Obtenemos versiones de OpenGL y Shaders
version = glGetString(GL_VERSION)
print(version)
version_shaders = glGetString(GL_SHADING_LANGUAGE_VERSION)
print(version_shaders)
while not glfw.window_should_close(window):
#Establece regiond e dibujo
glViewport(0,0,800,800)
#Establece color de borrado
glClearColor(0.474,0.780,0.752,1)
#Borra el contenido de la ventana
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
#Dibujar
dibujar()
#Preguntar si hubo entradas de perifericos
#(Teclado, mouse, game pad, etc.)
glfw.poll_events()
#Intercambia los buffers
glfw.swap_buffers(window)
#Se destruye la ventana para liberar memoria
glfw.destroy_window(window)
#Termina los procesos que inició glfw.init
glfw.terminate()
if __name__ == "__main__":
main() | [
"you@example.com"
] | you@example.com |
afdd4a96f7bf490989dfa4d5e783bff6701247fa | 4d3999e06a63989cd4dc7fe928940e0ca533cbd4 | /test/test_inline_response20011.py | d78bbabcdfd3fc665194d388445a31299edf971d | [] | no_license | ribaguifi/orchestra-client-python | c8f1c4b9760c2df173222bb5bcaf73b231d2b4bb | a211f7f6c0353f4476176c6c2fed11a2be553db8 | refs/heads/main | 2023-06-03T00:28:57.108274 | 2021-06-22T12:22:28 | 2021-06-22T12:22:28 | 379,258,596 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 956 | py | # coding: utf-8
"""
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 0.0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.inline_response20011 import InlineResponse20011 # noqa: E501
from swagger_client.rest import ApiException
class TestInlineResponse20011(unittest.TestCase):
"""InlineResponse20011 unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testInlineResponse20011(self):
"""Test InlineResponse20011"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.inline_response20011.InlineResponse20011() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
"santiago@ribaguifi.com"
] | santiago@ribaguifi.com |
50ba1c7ef8fbb7d9a24a7636649bee002763c5fa | 4eaab9327d25f851f9e9b2cf4e9687d5e16833f7 | /problems/validate_binary_search_tree/solution.py | 4b027255c5de04c726d305a51e41b228bcb44e00 | [] | no_license | kadhirash/leetcode | 42e372d5e77d7b3281e287189dcc1cd7ba820bc0 | 72aea7d43471e529ee757ff912b0267ca0ce015d | refs/heads/master | 2023-01-21T19:05:15.123012 | 2020-11-28T13:53:11 | 2020-11-28T13:53:11 | 250,115,603 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 647 | py | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack = []
prev_node = float('-inf')
while stack or root:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
if prev_node >= root.val:
return False
prev_node = root.val
root = root.right
return True | [
"kadhirash@gmail.com"
] | kadhirash@gmail.com |
4974c067418ad8b5e155e0a7dcd40cd94d0f920c | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_259/ch147_2020_04_08_17_39_35_490926.py | 1cb72ae4df13990fa8e046149c2139db0e4e5da0 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 406 | py | def mais_frequente(lista):
ocorrencias = {}
for i in lista:
ocorrencias[i] = 0
for i in lista:
if i in ocorrencias:
ocorrencias[i]+=1
contadores = occorencias.values()
max = 0
for i in contadores:
for j in contadores:
if i>j:
max = i
for i in ocorrencias:
if ocorrencias[i] = max
return ocorrencias | [
"you@example.com"
] | you@example.com |
6a5bce666dbf467bf0894436cd1fcb1414585edc | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03127/s858089481.py | 6247fc003f271e8077da902951482327a7e441e4 | [] | 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 | 166 | py | n=int(input())
a=list(map(int,input().split()))
def gcd(x,y):
if y==0:
return x
return gcd(y,x%y)
ans=a[0]
for i in a:
ans=gcd(ans,i)
print(ans) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
063a2ab6fefbfe29cb136d4ed2c17a6cb71ffe90 | 5ce1c0ab1b6147428fc30bcd1698e4d0e53b688e | /1094.py | fc044748f63df33ff98d34ab4b9de72e8658f50b | [] | no_license | junyang10734/leetcode-python | 035b12df3f7d9fc33553140d1eb0692750b44f0a | eff322f04d22ffbc4f9b10e77f97c28aac5c7004 | refs/heads/master | 2023-07-22T11:16:38.740863 | 2023-07-14T00:22:00 | 2023-07-14T00:22:00 | 189,197,380 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 555 | py | # 1094. Car Pooling
# Array / 差分数组
# 差分数组
# time: O(n)
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
maxD = 0
for n,f,t in trips:
maxD = max(maxD, t)
diff = [0 for _ in range(maxD+1)]
for n,f,t in trips:
diff[f] += n
diff[t] -= n
used_capacity = 0
for d in diff:
used_capacity += d
if used_capacity > capacity:
return False
return True | [
"48000364+junyang10734@users.noreply.github.com"
] | 48000364+junyang10734@users.noreply.github.com |
d7e6712811fdf092b1950a8d0880765d318b7cd9 | 4e308e8bb7056f1fd6914777b38d98b18254867f | /DECOMPYLED/LV2_LX2_LC2_LD2/Params.py | a509f673e5d1e85d5e6b3c414e982b62497335bd | [] | no_license | bschreck/cuttlefish | 165aae651bf58c1142cc47934802a7a3614e39da | 0f44ccca0ebf1a6f78165001586fcb67b98b406a | refs/heads/master | 2020-05-19T23:07:11.520086 | 2014-02-25T05:26:18 | 2014-02-25T05:26:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,418 | py | # emacs-mode: -*- python-*-
AUTO_FILTER_PARAMS = {'LFO Sync Rate': 'LFO Synced Rate'}
AUTO_PAN_PARAMS = {'Sync Rate': 'Synced Rate'}
BEAT_REPEAT_PARAMS = {'Decay': 'Damp Volume',
'Pitch Decay': 'Damp Pitch',
'Volume': 'Wet Level',
'Repeat': 'Instant Repeat'}
EQ_FOUR_PARAMS = {'1 Filter On A': '1 Filter On',
'1 Frequency A': '1 Frequency',
'1 Gain A': '1 Gain',
'1 Filter Type A': '1 Filter Type',
'1 Resonance A': '1 Resonance',
'2 Filter On A': '2 Filter On',
'2 Frequency A': '2 Frequency',
'2 Gain A': '2 Gain',
'2 Filter Type A': '2 Filter Type',
'2 Resonance A': '2 Resonance',
'3 Filter On A': '3 Filter On',
'3 Frequency A': '3 Frequency',
'3 Gain A': '3 Gain',
'3 Filter Type A': '3 Filter Type',
'3 Resonance A': '3 Resonance',
'4 Filter On A': '4 Filter On',
'4 Frequency A': '4 Frequency',
'4 Gain A': '4 Gain',
'4 Filter Type A': '4 Filter Type',
'4 Resonance A': '4 Resonance'}
FLANGER_PARAMS = {'Frequency': 'LFO Frequency',
'Sync': 'LFO Sync',
'Sync Rate': 'LFO Synced Rate'}
PHASER_PARAMS = {'Sync': 'LFO Sync',
'Sync Rate': 'LFO Synced Rate'}
SATURATOR_PARAMS = {'Base': 'BaseDrive',
'Drive': 'PreDrive'}
FIVETOSIX_PARAMS_DICT = {'AutoFilter': AUTO_FILTER_PARAMS,
'AutoPan': AUTO_PAN_PARAMS,
'BeatRepeat': BEAT_REPEAT_PARAMS,
'Eq8': EQ_FOUR_PARAMS,
'Flanger': FLANGER_PARAMS,
'Phaser': PHASER_PARAMS,
'Saturator': SATURATOR_PARAMS}
# local variables:
# tab-width: 4
| [
"bschreck@mit.edu"
] | bschreck@mit.edu |
b844fe2134f61d12924df1dbdb2e53f8a9063706 | 6fbda2fa7d0741813b5141dfbae7fec76a471fc9 | /modal/popup/urls.py | ccd86b0fcb72169d2e0d2ea843b8b97b17ac1fc7 | [] | no_license | innotexak/Popup-in-Django | f31d1bb9539d38a6bba3b29b7a9e41c7a0187125 | bfefd0feb24eb7729de1cdc3aa4c23cdf75273c7 | refs/heads/master | 2023-03-09T13:56:38.891788 | 2021-03-01T14:36:09 | 2021-03-01T14:36:09 | 343,439,152 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 380 | py | from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
path("", views.home, name ="home"),
path('signup/', views.SignUpView.as_view(), name='signup'),
path('login/', views.CustomLoginView.as_view(), name='login'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| [
"akuhinnocent2016@gmail.com"
] | akuhinnocent2016@gmail.com |
573e0d1262f5d6af7cbc0a4e35a0616f147502be | 2bb633b7b0590d64a1055fb9bf6fcd0e22701ef5 | /main/drive_MTM_study.py | 860ef499307487a32d38c12b2d05a12dd79a69a4 | [] | no_license | nag92/haptic_mtm | 2df0ed46ce284e6726d9352b89d7ba5f9d4b31e6 | 503858d98a395e7465ec12f46657586453d25c53 | refs/heads/master | 2022-04-07T06:29:39.937383 | 2020-02-28T00:02:08 | 2020-02-28T00:02:08 | 241,441,056 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,953 | py | from Tkinter import *
import rosbag
from datetime import datetime
import subprocess
import signal
import shlex
import rospy
from std_msgs.msg import Time
from std_msgs.msg import Empty
from geometry_msgs.msg import Pose, PoseStamped
import time
import os
import threading
class MTM_DRIVER:
def __init__(self):
rospy.init_node('user_study_data')
self._time_pub = rospy.Publisher('/ambf/env/user_study_time', Time, queue_size=1)
self._dvrk_on_pub = rospy.Publisher('/dvrk/console/power_on', Empty, queue_size=1)
self._dvrk_off_pub = rospy.Publisher('/dvrk/console/power_off', Empty, queue_size=1)
self._dvrk_home_pub = rospy.Publisher('/dvrk/console/home', Empty, queue_size=1)
self._goal_pub = rospy.Publisher('/dvrk/MTMR/set_position_goal_cartesian', Pose, queue_size=1)
rospy.Subscriber("/dvrk/MTMR/position_cartesian_current", PoseStamped, self.updatePose)
self._time_msg = 0
self._start_time = 0
self._active = False
self._time_pub_thread = 0
self._my_bag = 0
self._current_pose = PoseStamped()
self._topic_names = ["/dvrk/MTMR/twist_body_current",
"/dvrk/MTMR/set_position_goal_cartesian",
"ambf/env/psm/baselink/State",
"ambf/env/psm/baselink/Command",
"/ambf/image_data/camera1/compressed",
"/ambf/env/World/State",
"/ambf/env/user_study/Base/State",
"/ambf/env/user_study/PuzzleRed/State",
"/ambf/env/user_study/PuzzleYellow/State",
"/ambf/env/camera1/State",
"/ambf/env/camera2/State",
"/ambf/env/simulated_device_1/MTML/State",
"/ambf/env/simulated_device_1/MTMR/State",
"/ambf/env/HandleLeft/State",
"/ambf/env/HandleRight/State",
"/ambf/env/FixedBase/State",
"/ambf/env/MovingBase/State",
"/dvrk/MTML/position_cartesian_current",
"/dvrk/MTMR/position_cartesian_current",
"/dvrk/MTMR/position_cartesian_desired",
"/dvrk/MTML/position_cartesian_desired",
"/dvrk/footpedals/clutch",
"/dvrk/footpedals/coag",
"/dvrk/MTML/set_wrench_body",
"/dvrk/MTMR/set_wrench_body",
"/ambf/env/user_study_time"]
self._topic_names_str = ""
self._rosbag_filepath = 0
self._rosbag_process = 0
for name in self._topic_names:
self._topic_names_str = self._topic_names_str + ' ' + name
def updatePose(self, data):
self._current_pose = data
def call(self):
if self._rosbag_filepath is 0:
self._active = True
self._start_time = rospy.Time.now()
self._time_pub_thread = threading.Thread(target=self.time_pub_thread_func)
self._time_pub_thread.start()
print("Start Recording ROS Bag")
date_time_str = str(datetime.now()).replace(' ', '_')
self._rosbag_filepath = './user_study_data/' + str(e1.get()) + '_' + date_time_str
command = "rosbag record -O" + ' ' + self._rosbag_filepath + self._topic_names_str
print "Running Command", command
command = shlex.split(command)
self._rosbag_process = subprocess.Popen(command)
pose = self._current_pose.pose
pose.position.x = float(x.get())
pose.position.y = float(y.get())
pose.position.z = float(z.get())
self._goal_pub.publish(pose)
else:
print "Already recording a ROSBAG file, please save that first before starting a new record"
def save(self):
if self._rosbag_filepath is not 0:
# self._active = False
filepath = self._rosbag_filepath
self._rosbag_filepath = 0
node_prefix = "/record"
# Adapted from http://answers.ros.org/question/10714/start-and-stop-rosbag-within-a-python-script/
list_cmd = subprocess.Popen("rosnode list", shell=True, stdout=subprocess.PIPE)
list_output = list_cmd.stdout.read()
retcode = list_cmd.wait()
assert retcode == 0, "List command returned %d" % retcode
for node_name in list_output.split("\n"):
if node_name.startswith(node_prefix):
os.system("rosnode kill " + node_name)
print("Saved As:", filepath, ".bag")
self._active = False
else:
print("You should start recording first before trying to save")
def time_pub_thread_func(self):
while self._active:
self._time_msg = rospy.Time.now() - self._start_time
self._time_pub.publish(self._time_msg)
time.sleep(0.05)
def dvrk_power_on(self):
self._dvrk_on_pub.publish(Empty())
time.sleep(0.1)
def dvrk_power_off(self):
self._dvrk_off_pub.publish(Empty())
time.sleep(0.1)
def dvrk_home(self):
self._dvrk_home_pub.publish(Empty())
time.sleep(0.1)
study = MTM_DRIVER()
master = Tk()
master.title("AMBF USER STUDY 1")
width = 550
height = 600
master.geometry(str(width)+'x'+str(height))
Label(master, text='trial number').grid(row=0)
Label(master, text='X').grid(row=1)
Label(master, text='Y').grid(row=2)
Label(master, text='Z').grid(row=3)
e1 = Entry(master)
e1.grid(row=0, column=1)
x = Entry(master)
x.grid(row=1, column=1)
y = Entry(master)
y.grid(row=2, column=1)
z = Entry(master)
z.grid(row=3, column=1)
# Set Default Value
button_start = Button(master, text="Start Record", bg="green", fg="white", height=8, width=20, command=study.call)
button_stop = Button(master, text="Stop Record (SAVE)", bg="red", fg="white", height=8, width=20, command=study.save)
button_destroy = Button(master, text="Close App", bg="black", fg="white", height=8, width=20, command=master.destroy)
button_on = Button(master, text="DVRK ON", bg="green", fg="white", height=4, width=10, command=study.dvrk_power_on)
button_off = Button(master, text="DVRK OFF", bg="red", fg="white", height=4, width=10, command=study.dvrk_power_off)
button_home = Button(master, text="DVRK HOME", bg="purple", fg="white", height=4, width=10, command=study.dvrk_home)
button_on.grid(row=20, column=1)
button_off.grid(row=40, column=1)
button_home.grid(row=60, column=1)
button_start.grid(row=20, column=2)
button_stop.grid(row=40, column=2)
button_destroy.grid(row=60, column=2)
master.mainloop()
| [
"nagoldfarb@wpi.edu"
] | nagoldfarb@wpi.edu |
af8d982fa9c11c8549511d906334edf7a27dc55f | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/303/usersdata/284/109078/submittedfiles/minha_bib.py | 225e6592cfde216e2fee7b7f14605137fb56fb8b | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,952 | py |
import random
def solicitaSimboloDoHumano():
letra = 0
while not (letra == 'O' or letra == 'X'):
print('Qual símbolo você deseja utilizar no jogo? (X ou O) ')
letra = input().upper()
if letra == 'X':
return ['X','O']
else:
return ['O','X']
def sorteioPrimeiraJogada():
if random.randrange(2) == 1:
return 'Computador'
else:
return 'Jogador'
def jogadaHumana(tabuleiro,nome):
movimento = 0
while movimento not in '1 2 3 4 5 6 7 8 9'.split() or not vazio(tabuleiro, int(movimento)):
print('Qual a sua jogada, {}?'.format(nome))
movimento = input()
if movimento == '00':
movimento= '7'
elif movimento == '01':
movimento= '8'
elif movimento == '02':
movimento= '9'
elif movimento == '10':
movimento= '4'
elif movimento == '11':
movimento= '5'
elif movimento == '12':
movimento= '6'
elif movimento == '20':
movimento= '1'
elif movimento == '21':
movimento= '2'
elif movimento == '22':
movimento= '3'
return int(movimento)
def jogadaComputador(tabuleiro, letraComputador):
if letraComputador == 'X':
letraJogador = 'O'
else:
letraJogador = 'X'
for i in range(1,10):
copy = mostraTabuleiro(tabuleiro)
if vazio(copy, i):
movimentacao(copy, letraComputador, i)
if verificaVencedor(copy, letraComputador):
return i
for i in range(1, 10):
copy = mostraTabuleiro(tabuleiro)
if vazio(copy, i):
movimentacao(copy, letraJogador, i)
if verificaVencedor(copy, letraJogador):
return i
movimento = movAleatoria(tabuleiro, [1, 3, 7, 9])
if movimento != None:
return movimento
if vazio(tabuleiro, 5):
return 5
return movAleatoria(tabuleiro, [2, 4, 6, 8])
def mostraTabuleiro(tabuleiro):
dupeTabuleiro = []
for i in tabuleiro:
dupeTabuleiro.append(i)
return dupeTabuleiro
def verificaVencedor(tabuleiro, letra):
return ((tabuleiro[7] == letra and tabuleiro[8] == letra and tabuleiro[9] == letra) or
(tabuleiro[4] == letra and tabuleiro[5] == letra and tabuleiro[6] == letra) or
(tabuleiro[1] == letra and tabuleiro[2] == letra and tabuleiro[3] == letra) or
(tabuleiro[7] == letra and tabuleiro[4] == letra and tabuleiro[1] == letra) or
(tabuleiro[8] == letra and tabuleiro[5] == letra and tabuleiro[2] == letra) or
(tabuleiro[9] == letra and tabuleiro[6] == letra and tabuleiro[3] == letra) or
(tabuleiro[7] == letra and tabuleiro[5] == letra and tabuleiro[3] == letra) or
(tabuleiro[9] == letra and tabuleiro[5] == letra and tabuleiro[1] == letra))
def vazio(tabuleiro, movimento):
return tabuleiro[movimento] == ' '
def desenhaTabuleiro(tabuleiro):
print(' ' + tabuleiro[7] + ' | ' + tabuleiro[8] + ' | ' + tabuleiro[9])
print(' ' + tabuleiro[4] + ' | ' + tabuleiro[5] + ' | ' + tabuleiro[6])
print(' ' + tabuleiro[1] + ' | ' + tabuleiro[2] + ' | ' + tabuleiro[3])
def jogarNovamente():
print('Você deseja jogar novamente?(sim ou não)')
return rodando = True
def movimentacao(tabuleiro, letra, movimento):
tabuleiro[movimento] = letra
def movAleatoria(tabuleiro, movimentosList):
movPossiveis = []
for i in movimentosList:
if vazio(tabuleiro, i):
movPossiveis.append(i)
if len(movPossiveis) != 0:
return random.choice(movPossiveis)
else:
return None
def completo(tabuleiro):
for i in range(1, 10):
if vazio(tabuleiro, i):
return False
return True
| [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
e8f2a8f39ca3eda6c2fbc091779c75346d7c82a4 | 7bd9be7f25be80791f9220b62025f06170273293 | /front-plugins/mstatuses/src/event.py | 0a8fbb59dc5cf9f9aff2be3263775c0b94367aed | [] | no_license | cerebrohq/cerebro-plugins | ab46b4844adcb12c51d14e21f2c0d8b758b0bb57 | e2e0f97b548ef22957e13d614200027ba89215e0 | refs/heads/master | 2021-11-12T16:25:48.228521 | 2021-10-22T11:25:58 | 2021-10-22T11:25:58 | 143,178,631 | 5 | 3 | null | null | null | null | UTF-8 | Python | false | false | 3,907 | py | # -*- coding: utf-8 -*-
import cerebro
import datetime
from cerebro.aclasses import Statuses
from cerebro.aclasses import Users
from cerebro.aclasses import AbstractMessage
report_status_name = 'pending review' # status after posting Report
review_status_name = 'in progress' # status after posting Review
client_review_status_name = 'could be better' # status after posting Client Review
new_task_percent = 5.0 # new progress % after first Report message
complete_status_name = 'completed' # Complete status name
"""
def change_status(task, to_status):
for status in task.possible_statuses():
if status[Statuses.DATA_NAME] == to_status:
task.set_status(status[Statuses.DATA_ID])
return True
return False
"""
def change_status(task, event, to_status):
for status in task.possible_statuses():
if status[Statuses.DATA_NAME] == to_status:
event.set_new_task_status(status[Statuses.DATA_ID])
return True
return False
def task_messages(task_id):
db = cerebro.db.Db()
messs = db.execute('select uid from "_event_list"(%s, false) order by mtm desc limit 1', task_id)
ids = set()
for mess in messs:
ids.add(mess[0])
return db.execute('select * from "eventQuery_08"(%s)', ids)
def remove_event(msg):
db = cerebro.db.Db()
db.execute('select "_event_update"(%s, 1::smallint, 0, 0)', msg[AbstractMessage.DATA_ID])
def before_event(event):
# change progress on first
if event.event_type() == event.EVENT_CREATION_OF_MESSAGE:
task = cerebro.core.task(event.task_id())
if event.type() == event.TYPE_REPORT:
"""has_report = False
for message in task_messages(event.task_id()):
if message[AbstractMessage.DATA_TYPE] == AbstractMessage.TYPE_REPORT:
has_report = True
break
task = cerebro.core.task(event.task_id())"""
if task.progress() < new_task_percent: #not has_report and
task.set_progress(new_task_percent)
if event.new_task_status()[cerebro.aclasses.Statuses.DATA_ID] == task.status()[cerebro.aclasses.Statuses.DATA_ID]:
change_status(task, event, report_status_name)
elif event.type() == event.TYPE_REVIEW:
if event.new_task_status()[cerebro.aclasses.Statuses.DATA_ID] == task.status()[cerebro.aclasses.Statuses.DATA_ID]:
change_status(task, event, review_status_name)
elif event.type() == event.TYPE_CLIENT_REVIEW:
if event.new_task_status()[cerebro.aclasses.Statuses.DATA_ID] == task.status()[cerebro.aclasses.Statuses.DATA_ID]:
change_status(task, event, client_review_status_name)
def after_event(event):
# Message posting
if event.event_type() == event.EVENT_CREATION_OF_MESSAGE:
task = cerebro.core.task(event.task_id())
status_t = task.status()
if status_t[Statuses.DATA_NAME] != complete_status_name and (event.type() == event.TYPE_REPORT or event.type() == event.TYPE_REVIEW or event.type() == event.TYPE_CLIENT_REVIEW):
msgs = task_messages(event.task_id())
if msgs and len(msgs):
msgdel = msgs[len(msgs) - 1]
if (msgdel[1] == AbstractMessage.TYPE_STATUS_CHANGES):
remove_event(msgdel)
if status_t[Statuses.DATA_NAME] == complete_status_name:
task.set_progress(100.0)
# Status change
elif event.event_type() == event.EVENT_CHANGING_OF_TASKS_STATUS:
tasks = event.tasks()
#user_tasks_lst = None
for task in tasks: # All selected tasks
status_t = task.status()
if status_t[Statuses.DATA_NAME] == complete_status_name:
task.set_progress(100.0) | [
"41910371+cerebroSupport@users.noreply.github.com"
] | 41910371+cerebroSupport@users.noreply.github.com |
0f92e21e1cee1331ff57006aa1afe38de3ff9f3d | 286769965e3f4a63753d96fb0bda6e1d85b0c569 | /harvest.py | 8ce22843f11462a883170a1151bbb1b4a0230cb2 | [] | no_license | Krysioly/Harvest-Lab | 2cf64829995c72eb798d31313b0567fc77307cee | b912a97b22c5fc2d2996cf7e75e1b3025fbcd13f | refs/heads/master | 2020-03-28T16:23:58.129249 | 2018-09-13T19:51:04 | 2018-09-13T19:51:04 | 148,690,533 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,429 | py | ############
# Part 1 #
############
class MelonType(object):
"""A species of melon at a melon farm."""
def __init__(self, code, first_harvest, color, is_seedless, is_bestseller,
name):
"""Initialize a melon."""
self.pairings = []
self.code = code
self.first_harvest = first_harvest
self.color = color
self.is_seedless = is_seedless
self.is_bestseller = is_bestseller
self.name = name
def add_pairing(self, pairing):
"""Add a food pairing to the instance's pairings list."""
self.pairings.append(pairing)
def update_code(self, new_code):
"""Replace the reporting code with the new_code."""
self.code = new_code
def make_melon_types():
"""Returns a list of current melon types."""
all_melon_types = []
musk = MelonType("musk", 1998, "green", True, True, "Muskmelon")
musk.add_pairing("mint")
all_melon_types.append(musk)
cas = MelonType("cas", 2003, "orange", True, False, "Casaba")
cas.add_pairing("mint")
cas.add_pairing("strawberries")
all_melon_types.append(cas)
cren = MelonType("cren", 1996, "green", True, False, "Crenshaw")
cren.add_pairing("proscuitto")
all_melon_types.append(cren)
yw = MelonType("yw", 2013, "yellow", True, True, "Yellow Watermelon")
yw.add_pairing("ice cream")
all_melon_types.append(yw)
return all_melon_types
def print_pairing_info(melon_types):
"""Prints information about each melon type's pairings."""
#for melon in melon_types:
for melon in melon_types:
print("{} pairs with ".format(melon.name))
for pairing in melon.pairings:
print("-- {}""".format(pairing))
def make_melon_type_lookup(melon_types):
"""Takes a list of MelonTypes and returns a dictionary of melon type by code."""
melon_dictionary = {}
for melon, value in melon_types.items():
melon_dictionary[melon] = value
return melon_dictionary
############
# Part 2 #
############
class Melon(object):
"""A melon in a melon harvest."""
# Fill in the rest
# Needs __init__ and is_sellable methods
def make_melons(melon_types):
"""Returns a list of Melon objects."""
# Fill in the rest
def get_sellability_report(melons):
"""Given a list of melon object, prints whether each one is sellable."""
# Fill in the rest
| [
"no-reply@hackbrightacademy.com"
] | no-reply@hackbrightacademy.com |
33643977282d87b0b7f0d9e84435de680a12464a | ab621c65fc91f5194c4032d68e750efaa5f85682 | /account_budget_activity/models/account_budget_summary.py | c0293bb5ce21aaffd2c726edb10d045d2fc83b59 | [] | no_license | pabi2/pb2_addons | a1ca010002849b125dd89bd3d60a54cd9b9cdeef | e8c21082c187f4639373b29a7a0905d069d770f2 | refs/heads/master | 2021-06-04T19:38:53.048882 | 2020-11-25T03:18:24 | 2020-11-25T03:18:24 | 95,765,121 | 6 | 15 | null | 2022-10-06T04:28:27 | 2017-06-29T10:08:49 | Python | UTF-8 | Python | false | false | 2,378 | py | # -*- coding: utf-8 -*-
from openerp import tools
import openerp.addons.decimal_precision as dp
from openerp import models, fields, api
class BudgetSummary(models.Model):
_name = 'budget.summary'
_auto = False
budget_id = fields.Many2one(
'account.budget',
string="Budget",
)
budget_method = fields.Selection(
[('revenue', 'Revenue'),
('expense', 'Expense')],
string='Budget Method',
)
activity_group_id = fields.Many2one(
'account.activity.group',
string='Activity Group',
)
m1 = fields.Float(
string='Oct',
)
m2 = fields.Float(
string='Nov',
)
m3 = fields.Float(
string='Dec',
)
m4 = fields.Float(
string='Jan',
)
m5 = fields.Float(
string='Feb',
)
m6 = fields.Float(
string='Mar',
)
m7 = fields.Float(
string='Apr',
)
m8 = fields.Float(
string='May',
)
m9 = fields.Float(
string='Jun',
)
m10 = fields.Float(
string='July',
)
m11 = fields.Float(
string='Aug',
)
m12 = fields.Float(
string='Sep',
)
planned_amount = fields.Float(
string='Planned Amount',
compute='_compute_planned_amount',
digits_compute=dp.get_precision('Account'),
)
@api.multi
@api.depends('m1', 'm2', 'm3', 'm4', 'm5', 'm6',
'm7', 'm8', 'm9', 'm10', 'm11', 'm12',)
def _compute_planned_amount(self):
for rec in self:
planned_amount = sum([rec.m1, rec.m2, rec.m3, rec.m4,
rec.m5, rec.m6, rec.m7, rec.m8,
rec.m9, rec.m10, rec.m11, rec.m12
])
rec.planned_amount = planned_amount # from last year
def init(self, cr):
tools.drop_view_if_exists(cr, self._table)
cr.execute("""CREATE or REPLACE VIEW %s as (
select min(l.id) id, budget_id, activity_group_id, l.budget_method,
sum(m1) m1, sum(m2) m2, sum(m3) m3, sum(m4) m4,
sum(m5) m5, sum(m6) m6, sum(m7) m7, sum(m8) m8, sum(m9) m9,
sum(m10) m10, sum(m11) m11, sum(m12) m12
from account_budget_line l
group by budget_id, activity_group_id, l.budget_method
)""" % (self._table, ))
| [
"kittiu@gmail.com"
] | kittiu@gmail.com |
ea9f1d44be60e436552ebd6088b3a92204b02381 | f8d5c4eb0244c4a227a615bc11c4c797760c3bec | /log/REINFORCEMENT_2017-11-23 01:19:24.645036/REINFORCE_cart_pole.py | c9cc30fc771a980cf4d433f5a4d099bed1fa9fbf | [] | no_license | SamPlvs/reinforcement_learning_pytorch | e9b84659f870d938814177f1288fa4a2eb152599 | ffb9e53eeff011c4d3d5933a60c2b65fdbb18e2a | refs/heads/master | 2020-03-23T04:08:51.778325 | 2018-01-16T22:36:48 | 2018-01-16T22:36:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,768 | py | import torch
import gym
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# import datetime
from REINFORCEAgent import REINFORCEAgent
# import random
# from torch.autograd import Variable
import signal
import utils.util as util
import os, sys, datetime, shutil
import utils.logger as logger
from datetime import datetime
is_ipython = 'inline' in matplotlib.get_backend()
if is_ipython:
from IPython import display
plt.ion()
# use_cuda = torch.cuda.is_available()
# FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
# DoubleTensor = torch.cuda.DoubleTensor if use_cuda else torch.DoubleTensor
# LongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor
# ByteTensor = torch.cuda.ByteTensor if use_cuda else torch.ByteTensor
# Tensor = FloatTensor
class GracefulKiller:
def __init__(self):
self.kill_now = False
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
self.kill_now=True
# gym parameters
def init_gym(env_name):
env = gym.make(env_name).unwrapped
state_dim = env.observation_space.shape[0]
disc_flag = len(env.action_space.shape)==0
if disc_flag: # discrete action
action_dim = env.action_space.n
else:
action_dim = env.action_space.shape[0]
# ActionTensor = LongTensor if disc_flag else FloatTensor
return env, state_dim, action_dim
BATCH_SIZE = 128
GAMMA = 0.999
steps_done = 0
animate = True
def run_episode(env, qf): # on line algorithm
done = False
global steps_done
obs = env.reset()
obs[0], obs[3] = 5,5
# steps_done += 1
# action_new = qf.select_action(obs,steps_done)
reward = 0
add_reward = 0
pending = []
while not done:
# if animate:
# env.render()
# action = action_new
# obs_new, rewards, done, _ = env.step(action[0,0])
# reward += rewards
# steps_done+=1
# action_new = qf.select_action(obs_new,steps_done)
# pending.append([obs,action[0,0],rewards, obs_new,action_new[0,0],done])
# if len(pending)>=6 or done:
# qf.update(pending)
# pending = []
# # qf.update(obs,action[0,0],rewards, obs_new,action_new[0,0],done)
# obs = obs_new
action = qf.select_action(obs)
obs_new, reward, done, _ = env.step(action)
add_reward+=reward
qf.trajectory.append({'reward':reward, 'state':obs, 'action':action})
qf.update()
return add_reward
def run_policy(env, qf, episodes):
total_steps = 0
reward = []
for e in range(episodes):
reward.append(run_episode(env,qf))
qf.update() # update the policy net
qf.clear_trajectory() # clear the old trajectory
return np.mean(reward)
# print(np.mean(reward))
# return reward
def main():
torch.cuda.set_device(0)
print(torch.cuda.current_device())
seed_num = 1
torch.cuda.manual_seed(seed_num)
# data_dir = '/home/bike/data/mnist/'
out_dir = '/home/becky/Git/reinforcement_learning_pytorch/log/REINFORCEMENT_{}/'.format(datetime.now())
if not os.path.exists(out_dir):
os.makedirs(out_dir)
shutil.copyfile(sys.argv[0], out_dir + '/REINFORCE_cart_pole.py')
sys.stdout = logger.Logger(out_dir)
env_name = 'CartPole-v0'
killer = GracefulKiller()
env, obs_dim, act_dim = init_gym(env_name)
num_episodes = 300
rewards = np.zeros(num_episodes)
QValue = REINFORCEAgent(obs_dim, act_dim, learning_rate=0.0001,reward_decay = 0.99, e_greedy=0.9)
for i_episode in range(num_episodes):
rewards[i_episode] = run_policy(env,QValue,episodes=100)
print("In episode {}, the reward is {}".format(str(i_episode),str(rewards[i_episode])))
if killer.kill_now:
now = "REINFORCE_v1"
QValue.save_model(str(now))
break
print('game over!')
util.before_exit(model=QValue.model, reward=rewards)
env.close()
env.render(close=True)
if __name__ == "__main__":
main()
| [
"kebai0624@gmail.com"
] | kebai0624@gmail.com |
0291a73ff7e829012f8dfc0c270e4538dbf177bd | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/p4VQE/R3/benchmark/startQiskit_QC683.py | 68124f75e75ac6a9cc3004e511f0837184c87a77 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,662 | py | # qubit number=3
# total number=15
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def make_circuit(n:int) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0]) # number=1
prog.h(input_qubit[0]) # number=12
prog.cz(input_qubit[3],input_qubit[0]) # number=13
prog.h(input_qubit[0]) # number=14
prog.z(input_qubit[3]) # number=10
prog.cx(input_qubit[3],input_qubit[0]) # number=11
prog.z(input_qubit[1]) # number=8
prog.h(input_qubit[2]) # number=3
prog.h(input_qubit[3]) # number=4
for edge in E:
k = edge[0]
l = edge[1]
prog.cp(-2 * gamma, input_qubit[k-1], input_qubit[l-1])
prog.p(gamma, k)
prog.p(gamma, l)
prog.rx(2 * beta, range(len(V)))
prog.swap(input_qubit[3],input_qubit[0]) # number=5
prog.swap(input_qubit[3],input_qubit[0]) # number=6
# circuit end
return prog
if __name__ == '__main__':
n = 4
V = np.arange(0, n, 1)
E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)]
G = nx.Graph()
G.add_nodes_from(V)
G.add_weighted_edges_from(E)
step_size = 0.1
a_gamma = np.arange(0, np.pi, step_size)
a_beta = np.arange(0, np.pi, step_size)
a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)
F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * (
1 + np.cos(4 * a_gamma) ** 2)
result = np.where(F1 == np.amax(F1))
a = list(zip(result[0], result[1]))[0]
gamma = a[0] * step_size
beta = a[1] * step_size
prog = make_circuit(4)
sample_shot =5600
writefile = open("../data/startQiskit_QC683.csv", "w")
# prog.draw('mpl', filename=(kernel + '.png'))
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = provider.get_backend("ibmq_5_yorktown")
circuit1 = transpile(prog, FakeYorktown())
circuit1.measure_all()
prog = circuit1
info = execute(prog,backend=backend, shots=sample_shot).result().get_counts()
print(info, file=writefile)
print("results end", file=writefile)
print(circuit1.depth(), file=writefile)
print(circuit1, file=writefile)
writefile.close()
| [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
f7cda2f1394a3ee632aec0355cfbb9862944735b | ec78979fd8479e884ab93d723360744db5152134 | /file-move-task1.py | 82398d6af3c6f1287df01f3e489cb86e09123314 | [] | no_license | xushubo/learn-python | 49c5f4fab1ac0e06c91eaa6bd54159fd661de0b9 | 8cb6f0cc23d37011442a56f1c5a11f99b1179ce6 | refs/heads/master | 2021-01-19T17:00:05.247958 | 2017-09-03T03:22:28 | 2017-09-03T03:22:28 | 101,032,298 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 617 | py | import os
from datetime import *
print('当前时间:', datetime.today())
dir_file = input('请输入所查路径:')
print('文件名 ','大小 ','修改时间 ', '创建时间')
for x in os.listdir(dir_file):
full_dir_file = os.path.join(dir_file, x)
mod_time = os.path.getmtime(full_dir_file) #获取文件修改时间
cha_time = os.path.getctime(full_dir_file) #获取文件创建时间
mod_date = datetime.fromtimestamp(mod_time)
cha_date = datetime.fromtimestamp(cha_time)
print(x, os.path.getsize(full_dir_file), mod_date.strftime('%Y-%m-%d %H:%M:%S'), cha_date.strftime('%Y-%m-%d %H:%M:%S')) | [
"tmac523@163.com"
] | tmac523@163.com |
b9eec62397c7f79c955d49c0b46f8fd41ced3917 | e7031386a884ae8ed568d8c219b4e5ef1bb06331 | /processor/migrations/0002_auto_20180913_1628.py | 45d0290b0812897f75230932fc52f99dfa1e0a97 | [] | no_license | ikbolpm/ultrashop-backend | a59c54b8c4d31e009704c3bf0e963085477092cf | 290fa0ecdad40ec817867a019bff2ce82f08d6fe | refs/heads/dev | 2022-11-30T21:49:17.965273 | 2020-09-24T10:16:12 | 2020-09-24T10:16:12 | 147,561,738 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 473 | py | # Generated by Django 2.1.1 on 2018-09-13 11:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('processor', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='processor',
name='integrated_graphics',
field=models.CharField(blank=True, help_text='К примеру: Intel® HD Graphics 630', max_length=255, null=True),
),
]
| [
"ikbolpm@gmail.com"
] | ikbolpm@gmail.com |
ef3543e6c47ae443673e0966415707b5c7a18f6c | 5f2103b1083b088aed3f3be145d01a770465c762 | /162. Find Peak Element.py | d52a25826c9f187eb02642488362b2153d4a0352 | [] | no_license | supersj/LeetCode | 5605c9bcb5ddcaa83625de2ad9e06c3485220019 | 690adf05774a1c500d6c9160223dab7bcc38ccc1 | refs/heads/master | 2021-01-17T17:23:39.585738 | 2017-02-27T15:08:42 | 2017-02-27T15:08:42 | 65,526,089 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 973 | py | # A peak element is an element that is greater than its neighbors.
#
# Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
#
# The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
#
# You may imagine that num[-1] = num[n] = -∞.
#
# For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
#
# click to show spoilers.
#
# Credits:
# Special thanks to @ts for adding this problem and creating all test cases.
#
# Subscribe to see which companies asked this question
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lastindex = 0
for i in range(len(nums)):
if nums[i] < nums[lastindex]:
return lastindex
else:
lastindex += 1
return lastindex | [
"ml@ml.ml"
] | ml@ml.ml |
db9cd50f3aadca1b7aa8743f04df52bb8500e648 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_ragging.py | caeac9f2b2bb16f84f6163f1ccab0b4105891c5f | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 223 | py |
from xai.brain.wordbase.nouns._rag import _RAG
#calss header
class _RAGGING(_RAG, ):
def __init__(self,):
_RAG.__init__(self)
self.name = "RAGGING"
self.specie = 'nouns'
self.basic = "rag"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
242fe20624e3d8037961ba02bdb58f7f241e70f3 | 487487954ce7b34b97a904be4082e5da5cfacec2 | /111 - [Dicionários] Dicionário ao Quadrado.py | 196171116d337553c2a4b528249b5ec6029ee31c | [] | no_license | rifatmondol/Python-Exercises | 62eae905793e4f747a51653fd823fe7aba49a3c3 | 5b5f3fa6bf34408ca9afa035604a79cf19559304 | refs/heads/master | 2022-01-19T02:07:10.940300 | 2018-12-26T18:07:17 | 2018-12-26T18:07:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 356 | py | #111 - Define a function which can print a dictionary where the keys are numbers between 1 and 20
# (both included) and the values are square of keys.
#Hints:
#Use dict[key]=value pattern to put entry into a dictionary.
#Use ** operator to get power of a number.
#Use range() for loops.
dic = dict()
for i in range(1,21):
dic[i] = i**2
print(dic)
| [
"astrodelta14@gmail.com"
] | astrodelta14@gmail.com |
8d0ce9b1ef5e3b6c693faf33f8dbac726b2e6695 | d69361c62ba587b9666f39829afdc9ad8ed9e420 | /svm/svm.py | cc339ecafd0e26cb2994ff4a348ca8775d626ce9 | [] | no_license | ienoob/noob_ml | cd7dc184460344e1029631efd34ded0965e2bb48 | 6998d6e4e181e44ad3f0ca7cf971f16638d04ce4 | refs/heads/master | 2021-07-04T10:27:40.006224 | 2020-07-27T15:17:31 | 2020-07-27T15:17:31 | 129,582,132 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 432 | py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
svm 可以转化为二次规划问题,因此我们使用cvxopt, 优化计算包
hard margin
"""
import numpy as np
from cvxopt import matrix, solvers
A = matrix([[-1.0, -1.0, 0.0, 1.0], [1.0, -1.0, -1.0, -2.0]])
b = matrix([1.0, -2.0, 0.0, 4.0])
c = matrix([2.0, 1.0])
sol = solvers.lp(c,A,b)
print(sol['x'])
print(np.dot(sol['x'].T, c))
print(sol['primal objective']) | [
"jack.li@eisoo.com"
] | jack.li@eisoo.com |
72fa7896536b8eb0c0e4ac68879b393b1d8eb55e | c3432a248c8a7a43425c0fe1691557c0936ab380 | /21_06/21318_피아노 체조.py | 2ac7ef5cc09f9db10fd4aaedd83e2750eab32bd7 | [] | no_license | Parkyunhwan/BaekJoon | 13cb3af1f45212d7c418ecc4b927f42615b14a74 | 9a882c568f991c9fed3df45277f091626fcc2c94 | refs/heads/master | 2022-12-24T21:47:47.052967 | 2022-12-20T16:16:59 | 2022-12-20T16:16:59 | 232,264,447 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 363 | py | import sys
input = sys.stdin.readline
N = int(input())
arr = [0] + list(map(int, input().split()))
count = [0] * (N + 1)
for i in range(1, N + 1):
if arr[i - 1] > arr[i]:
count[i] = count[i - 1] + 1
else:
count[i] = count[i - 1]
for _ in range(int(input())):
x, y = map(int, input().split())
c = count[y] - count[x]
print(c)
| [
"pyh8618@gmail.com"
] | pyh8618@gmail.com |
b84e4f89e4a5a239ea8d712e0f74b8bef791e17c | 781e2692049e87a4256320c76e82a19be257a05d | /all_data/exercism_data/python/bob/14a30f4e97714ddc8d4a087e3b3fe203.py | 2df8a4dced86b19360b6f8f44dbe4d2408d9e2e4 | [] | no_license | itsolutionscorp/AutoStyle-Clustering | 54bde86fe6dbad35b568b38cfcb14c5ffaab51b0 | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | refs/heads/master | 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null | UTF-8 | Python | false | false | 1,677 | py | #
# Skeleton file for the Python "Bob" exercise.
#
def hey(what):
""" exercise bob """
stating_something = ('Tom-ay-to, tom-aaaah-to.')
shouting = ('WATCH OUT!')
asking_a_question = ('Does this cryogenic chamber make me look fat?')
asking_a_numeric_question = ('You are, what, like 15?')
talking_forcefully = ("Let's go make out behind the gym!")
using_acronyms_in_regular_speech = ("It's OK if you don't want to go to the DMV.")
forceful_questions = ("WHAT THE HELL WERE YOU THINKING?")
shouting_numbers = ("1, 2, 3 GO!")
only_numbers = ('1, 2, 3')
question_with_only_numbers = ('4?')
shouting_with_special_characters = ('ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!')
shouting_with_umlauts = ('ÜMLÄÜTS!')
shouting_with_no_exclamation_mark = ('I HATE YOU')
calmly_speaking_with_umlauts = ('ÜMLäÜTS!')
statement_containing_question_mark = ('Ending with ? means a question.')
prattling_on = ("Wait! Hang on. Are you going to be OK?")
silence = ('')
prolonged_silence = (' \t')
starts_with_whitespace = (' hmmmmmmm...')
ends_with_whitespace = ('What if we end with whitespace? ')
if what in [silence, prolonged_silence]:
return 'Fine. Be that way!'
elif what in [shouting, forceful_questions, shouting_numbers, shouting_with_special_characters,
shouting_with_umlauts, shouting_with_no_exclamation_mark]:
return 'Whoa, chill out!'
elif what in [asking_a_question, asking_a_numeric_question, question_with_only_numbers, prattling_on,
ends_with_whitespace]:
return 'Sure.'
else:
return 'Whatever.'
| [
"rrc@berkeley.edu"
] | rrc@berkeley.edu |
5366df88285235633e44287a3950189650d383b1 | 2d9cea7839a900921850f2af1ccafc623b9d53b9 | /websecurityscanner/google/cloud/websecurityscanner_v1alpha/types.py | 594571c6551b0c0557820428c4ec53212cbc344e | [
"Apache-2.0"
] | permissive | smottt/google-cloud-python | cb28e8d59cc36932aa89e838412fe234f6c4498c | 2982dd3d565923509bab210eb45b800ce464fe8a | refs/heads/master | 2020-03-31T21:12:02.209919 | 2018-10-10T18:04:44 | 2018-10-10T18:04:44 | 152,571,541 | 0 | 1 | Apache-2.0 | 2018-10-11T10:10:47 | 2018-10-11T10:10:47 | null | UTF-8 | Python | false | false | 2,175 | py | # Copyright 2018 Google LLC
#
# 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
#
# https://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 absolute_import
import sys
from google.api import http_pb2
from google.protobuf import descriptor_pb2
from google.protobuf import empty_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import timestamp_pb2
from google.api_core.protobuf_helpers import get_messages
from google.cloud.websecurityscanner_v1alpha.proto import crawled_url_pb2
from google.cloud.websecurityscanner_v1alpha.proto import finding_addon_pb2
from google.cloud.websecurityscanner_v1alpha.proto import finding_pb2
from google.cloud.websecurityscanner_v1alpha.proto import (
finding_type_stats_pb2)
from google.cloud.websecurityscanner_v1alpha.proto import scan_config_pb2
from google.cloud.websecurityscanner_v1alpha.proto import scan_run_pb2
from google.cloud.websecurityscanner_v1alpha.proto import (
web_security_scanner_pb2)
_shared_modules = [
http_pb2,
descriptor_pb2,
empty_pb2,
field_mask_pb2,
timestamp_pb2,
]
_local_modules = [
crawled_url_pb2,
finding_addon_pb2,
finding_pb2,
finding_type_stats_pb2,
scan_config_pb2,
scan_run_pb2,
web_security_scanner_pb2,
]
names = []
for module in _shared_modules:
for name, message in get_messages(module).items():
setattr(sys.modules[__name__], name, message)
names.append(name)
for module in _local_modules:
for name, message in get_messages(module).items():
message.__module__ = 'google.cloud.websecurityscanner_v1alpha.types'
setattr(sys.modules[__name__], name, message)
names.append(name)
__all__ = tuple(sorted(names))
| [
"noreply@github.com"
] | smottt.noreply@github.com |
691659c96bf52e69564c6ecb6e45aef25c446dad | ab0deb25919bcc71c1314a817097429063009364 | /tests/conftest.py | 5a05b92c97189d95238ceb1c91c9ae4ff89cb1b0 | [
"MIT"
] | permissive | spiritEcosse/panda | babecf3b4c72b3ddf78d967336547f1ce8728f40 | f81284bfd331a3eb24ce6e5a8adbaf9922fa07e2 | refs/heads/master | 2020-07-29T09:45:33.123744 | 2020-02-06T12:24:31 | 2020-02-06T12:24:31 | 201,935,610 | 0 | 0 | MIT | 2019-08-12T14:09:28 | 2019-08-12T13:26:57 | Python | UTF-8 | Python | false | false | 1,461 | py | import os
import warnings
import uuid
import django
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x)
def pytest_addoption(parser):
parser.addoption(
'--deprecation', choices=['strict', 'log', 'none'], default='log')
def pytest_configure(config):
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')
# media = 'media_{}'.format(uuid.uuid4())
# os.environ.setdefault('MEDIA', media)
# media_root = os.path.join(location('public'), media)
# os.mkdir(media_root)
# os.mkdir(os.path.join(media_root, "images"))
os.environ.setdefault('DJANGO_READ_DOT_ENV_FILE', '1')
os.environ.setdefault(
'DATABASE_URL', 'postgres://SUQWOetkbOGJpuXAxliKpZmnyywHdeqm:YZHXsIPZyoBwOUTwAMCLWcJKhYwpwVoeiAhjYMSIqZCBCjAvDBTXUArvSWuhxkgn@postgres:5432/test_{}'.format(uuid.uuid4())
)
deprecation = config.getoption('deprecation')
if deprecation == 'strict':
warnings.simplefilter('error', DeprecationWarning)
warnings.simplefilter('error', PendingDeprecationWarning)
warnings.simplefilter('error', RuntimeWarning)
if deprecation == 'log':
warnings.simplefilter('always', DeprecationWarning)
warnings.simplefilter('always', PendingDeprecationWarning)
warnings.simplefilter('always', RuntimeWarning)
elif deprecation == 'none':
# Deprecation warnings are ignored by default
pass
django.setup()
| [
"shevchenkcoigor@gmail.com"
] | shevchenkcoigor@gmail.com |
2950e13658a7f32171eb003a46a7e20312cf93e7 | c85ec51b920350e095b6fc67435a490352cef1f4 | /goods/migrations/0011_auto_20171123_1905.py | c64ad543bd44f19a496033c50db30be361e4f006 | [
"Apache-2.0"
] | permissive | huachao2017/goodsdl | 195dbc959d424248982b61f2fe2c22dbc4347746 | 3616d53b90696a97a5d56a064e2a14d484b821d7 | refs/heads/master | 2021-06-11T01:55:16.235507 | 2019-09-24T07:49:08 | 2019-09-24T07:49:08 | 109,931,837 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 720 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-23 19:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('goods', '0010_actionlog_traintype'),
]
operations = [
migrations.AlterField(
model_name='actionlog',
name='action',
field=models.CharField(choices=[('BT', 'Begin Train'), ('ST', 'Stop Train'), ('EG', 'Export Graph'), ('TT', 'Test Train')], max_length=2),
),
migrations.AlterField(
model_name='image',
name='deviceid',
field=models.CharField(default='0', max_length=20),
),
]
| [
"21006735@qq.com"
] | 21006735@qq.com |
99fa6952d27fe8543059eb0ba864ec39c86bcbd7 | 2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae | /python/python_3094.py | fbce41b739b90bf7443909681aa9ce1029fc56ab | [] | no_license | AK-1121/code_extraction | cc812b6832b112e3ffcc2bb7eb4237fd85c88c01 | 5297a4a3aab3bb37efa24a89636935da04a1f8b6 | refs/heads/master | 2020-05-23T08:04:11.789141 | 2015-10-22T19:19:40 | 2015-10-22T19:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 167 | py | # How can I get 'urlpatterns = __import__(<string_name>)' to work like a normal import statement?
urlpatterns = __import__(project_urls).whateversubmodule.urlpatterns
| [
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] | ubuntu@ip-172-31-7-228.us-west-2.compute.internal |
284762867cc565f2e98d0cd20d8e708a667b0cbd | 8dfb45ef6c142bb25183339e6a13e06a14a86dbe | /kansha/comment/comp.py | 71e725244c85f4652c5b1310caff84edf4185a08 | [] | no_license | blugand/kansha | 04be2581fa0bf9d77898bc26f668e2febb78dac4 | 227d834596bd66b03c2fc78f7f65dee04116668a | refs/heads/master | 2021-01-15T10:35:52.144198 | 2015-11-24T09:29:21 | 2015-11-24T09:29:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,094 | py | # -*- coding:utf-8 -*-
#--
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
import datetime
from nagare import component, security
from nagare.database import session
from .models import DataComment
from ..user import usermanager
from ..flow import comp as flow
from .. import notifications, validator
class Comment(flow.FlowElement):
"""Comment component"""
def __init__(self, data):
"""Initialization
In:
- ``data`` -- the comment object from the database
"""
self.db_id = data.id
self.text = data.comment
self.creation_date = data.creation_date
self.author = component.Component(usermanager.UserManager.get_app_user(data.author.username, data=data.author))
self.comment_label = component.Component(Commentlabel(self))
self.comment_label.on_answer(lambda v: self.comment_label.call(model='edit'))
def edit_comment(self):
self.comment_label.call(model='edit')
def is_author(self, user):
return self.author().username == user.username
def set_comment(self, text):
if text is None:
return
text = text.strip()
if text:
self.data.comment = validator.clean_text(text)
@property
def data(self):
"""Return the comment object from the database
"""
return DataComment.get(self.db_id)
class Commentlabel(object):
"""comment label component.
"""
def __init__(self, parent):
"""Initialization
In:
- ``parent`` -- parent of comment label
"""
self.parent = parent
self.text = parent.text or u''
def change_text(self, text):
"""Change the comment of our wrapped object
In:
- ``text`` -- the new comment
Return:
- the new comment
"""
if text is None:
return
text = text.strip()
if text:
text = validator.clean_text(text)
self.text = text
self.parent.set_comment(text)
return text
def is_author(self, user):
return self.parent.is_author(user)
class Comments(flow.FlowSource):
"""Comments component
"""
def __init__(self, parent, data_comments=()):
"""Initialization
In:
- ``parent`` -- the parent card
- ``comments`` -- the comments of the card
"""
self.parent = parent
self.comments = [self._create_comment_component(data_comment) for data_comment in data_comments]
@property
def flow_elements(self):
return self.comments
def _create_comment_component(self, data_comment):
return component.Component(Comment(data_comment)).on_answer(self.delete)
def add(self, v):
"""Add a new comment to the card
In:
- ``v`` -- the comment content
"""
security.check_permissions('comment', self.parent)
if v is None:
return
v = v.strip()
if v:
v = validator.clean_text(v)
user = security.get_user()
comment = DataComment(comment=v.strip(), card_id=self.parent.data.id,
author=user.data, creation_date=datetime.datetime.utcnow())
session.add(comment)
session.flush()
data = {'comment': v.strip(), 'card': self.parent.title().text}
notifications.add_history(self.parent.column.board.data, self.parent.data, security.get_user().data, u'card_add_comment', data)
self.comments.insert(0, self._create_comment_component(comment))
def delete(self, comp):
"""Delete a comment.
In:
- ``comment`` -- the comment to delete
"""
self.comments.remove(comp)
comment = comp()
DataComment.get(comment.db_id).delete()
session.flush()
| [
"romuald.texier-marcade@net-ng.com"
] | romuald.texier-marcade@net-ng.com |
807e79a4a73a139395c2af3d8c63d99759a161d1 | e7dd22eb03b914b1be39c0e46799857fac1d3f8a | /tests/log_generator.py | dae9a56cf64769986c40651a02254901a8875048 | [] | no_license | O-Swad/PyLog | f6d774636e059939fd449daaebe5f8e807ccb1cd | 360d86ef13b40622f7fb83eaf0c2dbea77d5dbc5 | refs/heads/main | 2023-06-03T20:38:04.986515 | 2021-06-26T16:41:47 | 2021-06-26T16:41:47 | 374,059,547 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 591 | py | import time
import random
hours = 2
now_time = int(time.time()*1000)
last_time = now_time - 3600 * 1000 * hours # one day of data in milliseconds
hosts = ['everest', 'annapurna', 'lhotse', 'manaslu', 'dhaulagiri']
separator = ' '
counter = 0
with open('test-log-file.txt', 'a') as log_file:
for log_timestamp in range(last_time, now_time):
host_ori, host_dest = random.sample(hosts, 2)
tokens = (str(log_timestamp), host_ori, host_dest)
line = separator.join(tokens) + '\n'
log_file.write(line)
counter += 1
print('Líneas: ' + str(counter))
| [
"="
] | = |
7ddbc340eb0394d89d0c8a87e6b760b2066eff80 | 65d9e2e2919554af3d84f63006ce7baa9f5b0213 | /oops/class method.py | 82902983f9b732c20f372e10b6324e2014989def | [] | no_license | quintus2020intern/PM_Basic_Python | 538e970f9a416691a229a594ffadfb18f28084a7 | 4891967490f068c7dd2d86df0519d852f066046f | refs/heads/master | 2020-12-11T08:24:09.987816 | 2020-03-30T10:45:03 | 2020-03-30T10:45:03 | 233,799,667 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 458 | py | # class Test:
# count = 0 # static variable
#
# def __init__(self):
# Test.count = Test.count + 1
#
# @classmethod
# def getNoOfObject(cls):
# print("no of object", cls.count)
#
#
# t1 = Test()
# t1.getNoOfObject()
# class Test:
# @classmethod
# def df(cls):
# print(id(cls))
#
# print(id(Test))
# Test.df()
class Test:
def __init__(self):
print( id( self ) )
t1 = Test()
print( id( t1 ) )
| [
"pragayanparamitaguddi111@gmail.com"
] | pragayanparamitaguddi111@gmail.com |
90fae8edfd4aa80e595fc01abed64323bf71279f | fe0017ae33385d7a2857d0aa39fa8861b40c8a88 | /env/lib/python3.8/site-packages/sklearn/cluster/__init__.py | 04fcee55d143f04403e2a52690a0d6b07eb1a638 | [] | no_license | enriquemoncerrat/frasesback | eec60cc7f078f9d24d155713ca8aa86f401c61bf | e2c77f839c77f54e08a2f0930880cf423e66165b | refs/heads/main | 2023-01-03T23:21:05.968846 | 2020-10-18T21:20:27 | 2020-10-18T21:20:27 | 305,198,286 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,474 | py | """
The :mod:`sklearn.cluster` module gathers popular unsupervised clustering
algorithms.
"""
from ._affinity_propagation import affinity_propagation, AffinityPropagation
from ._agglomerative import (ward_tree, AgglomerativeClustering,
linkage_tree, FeatureAgglomeration)
from ._bicluster import SpectralBiclustering, SpectralCoclustering
from ._birch import Birch
from ._dbscan import dbscan, DBSCAN
from ._kmeans import k_means, KMeans, MiniBatchKMeans
from ._mean_shift import (mean_shift, MeanShift,
estimate_bandwidth, get_bin_seeds)
from ._optics import (OPTICS, cluster_optics_dbscan, compute_optics_graph,
cluster_optics_xi)
from ._spectral import spectral_clustering, SpectralClustering
__all__ = ['AffinityPropagation',
'AgglomerativeClustering',
'Birch',
'DBSCAN',
'OPTICS',
'cluster_optics_dbscan',
'cluster_optics_xi',
'compute_optics_graph',
'KMeans',
'FeatureAgglomeration',
'MeanShift',
'MiniBatchKMeans',
'SpectralClustering',
'affinity_propagation',
'dbscan',
'estimate_bandwidth',
'get_bin_seeds',
'k_means',
'linkage_tree',
'mean_shift',
'spectral_clustering',
'ward_tree',
'SpectralBiclustering',
'SpectralCoclustering']
| [
"enriquemoncerrat@gmail.com"
] | enriquemoncerrat@gmail.com |
9e23232fb9f4b9c0dfab6d79764b757d42dd29e1 | 52580a60f1f7b27655a2543b1aa4c92a56053ead | /migrations/versions/824086b2abe3_bookmarks_table.py | 63851c4dfd9eb9032d2371364c2bc96f09fa116f | [] | no_license | nitin-cherian/personal_blog | 4d42a886e527dabecbfc82d30d3125c07d428192 | f3ef365ff0a5d9004c6b5407912aa93af2f0f855 | refs/heads/master | 2021-04-09T15:18:09.855063 | 2018-03-25T11:39:51 | 2018-03-25T11:39:51 | 125,714,136 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,249 | py | """bookmarks table
Revision ID: 824086b2abe3
Revises: 9c5d6731465a
Create Date: 2018-03-25 16:32:09.932871
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '824086b2abe3'
down_revision = '9c5d6731465a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('bookmark',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('post_url', sa.String(length=256), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_bookmark_post_url'), 'bookmark', ['post_url'], unique=True)
op.create_index(op.f('ix_bookmark_timestamp'), 'bookmark', ['timestamp'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_bookmark_timestamp'), table_name='bookmark')
op.drop_index(op.f('ix_bookmark_post_url'), table_name='bookmark')
op.drop_table('bookmark')
# ### end Alembic commands ###
| [
"nitin.cherian@gmail.com"
] | nitin.cherian@gmail.com |
76ca7e8409c7d796eb9fd1e95f6eabb2688c03f6 | f9e50b7c9079c5994b9f9f1b661c6259c3ff7510 | /video_sub/settings.py | 646fdabba6d3920d27a94c5b3564da09fdf1575a | [] | no_license | njokuifeanyigerald/video-subscription | 6598f9ec3a677ec1bcb031aa5499f546fed97bf3 | 5e479f142306f149d0d9aa3169bfeeba0953d6c2 | refs/heads/master | 2022-11-16T07:15:27.780389 | 2020-07-08T12:39:17 | 2020-07-08T12:39:17 | 277,650,980 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,164 | py | """
Django settings for video_sub project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x-7h%*t20+3)9j+c#s(bt)ei!f_byhzxrv=+j5regcn#ts!(^e'
# 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',
'allauth',
'allauth.account',
'allauth.socialaccount',
'video',
'courses',
# 'allauth',
# 'allauth.account',
# 'allauth.socialaccount',
]
SITE_ID = 1
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
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 = 'video_sub.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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 = 'video_sub.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static_root')
]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')
if DEBUG:
STRIPE_PUBLISHABLE_KEY = 'pk_test_yhAYzCLh0qruLoqF3aKvtNa900HGnFUy7B'
STRIPE_SECRET_KEY = 'sk_test_4fZvDGB3VzQ2OYQOyRuhq9bK00b8BiWAVb'
else:
STRIPE_PUBLISHABLE_KEY = ''
STRIPE_SECRET_KEY = ''
LOGIN_REDIRECT_URL = '/'
ACCOUNT_UNIQUE_EMAIL =True
ACCOUNT_EMAIL_REQUIRED = True
| [
"brainboyrichmond@gmail.com"
] | brainboyrichmond@gmail.com |
08f4d070632ee86bad8a064fde41cbfb19aeb520 | e17e40dbb6ed8caaac5c23de29071b403637f5ae | /transformers_keras/transformer/point_wise_ffn.py | 317f811c72b207e769dbb52cc0c3d75b49867c4c | [
"Apache-2.0"
] | permissive | Linessiex/transformers-keras | cb739075c8daab39d52dc6cd6bafe5e45f8259be | 0bb576db356f575390815dc64840b78b8ecf6227 | refs/heads/master | 2020-11-25T05:58:09.448200 | 2019-09-23T09:13:59 | 2019-09-23T09:13:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 669 | py | import tensorflow as tf
class PointWiseFeedForwardNetwork(tf.keras.Model):
def __init__(self, d_model, dff):
super(PointWiseFeedForwardNetwork, self).__init__(name='ffn')
# self.d_model = d_model
self.dense_1 = tf.keras.layers.Dense(dff, activation='relu')
self.dense_2 = tf.keras.layers.Dense(d_model)
def call(self, x, training=None, mask=None):
x = self.dense_1(x)
return self.dense_2(x)
def compute_output_shape(self, input_shape):
# shapes = tf.shape(input_shape).as_list()
# shapes[-1] = self.d_model
# return tf.TensorShape(shapes)
return self.dense_2.output_shape
| [
"zhouyang.luo@gmail.com"
] | zhouyang.luo@gmail.com |
4415658f3a51da55638037244704972110642216 | bb6bc5929b463c6d8564e0d2045b25402e855041 | /graphutils/graphClusterSampler.py | 4af5dbcd62721ee1fd740f2f85707126c18a34a8 | [] | no_license | xjtuwgt/ContrastiveKGE | e6560fc7c8ddacb1bfd8118fe9c4f1112f234a18 | 15e2f58b4bef527fe49e0b2a817c4b7ab706d03b | refs/heads/main | 2023-07-20T13:04:36.780926 | 2021-09-07T02:17:19 | 2021-09-07T02:17:19 | 348,168,386 | 5 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,862 | py | import os
import dgl
import torch
from graphutils.partition_utils import get_partition_list
import numpy as np
class ClusterIter(object):
'''The partition sampler given a DGLGraph and partition number.
The metis is used as the graph partition backend.
'''
def __init__(self, dn, g, psize, batch_size):
"""Initialize the sampler.
Paramters
---------
dn : str
The dataset name.
g : DGLGraph
The full graph of dataset
psize: int
The partition number
batch_size: int
The number of partitions in one batch
"""
self.psize = psize
self.batch_size = batch_size
# cache the partitions of known datasets&partition number
if dn:
fn = os.path.join('./datasets/', dn + '_{}.npy'.format(psize))
if os.path.exists(fn):
self.par_li = np.load(fn, allow_pickle=True)
else:
os.makedirs('./datasets/', exist_ok=True)
self.par_li = get_partition_list(g, psize)
np.save(fn, self.par_li)
else:
self.par_li = get_partition_list(g, psize)
par_list = []
total_nodes = 0
for p in self.par_li:
total_nodes = total_nodes + len(p)
par = torch.Tensor(p)
par_list.append(par)
self.par_list = par_list
print('Partition number = {} over {} nodes on graph with {} nodes'.format(len(par_list), total_nodes, g.num_nodes()))
def __len__(self):
return self.psize
def __getitem__(self, idx):
return self.par_li[idx]
def subgraph_collate_fn(g, batch):
nids = np.concatenate(batch).reshape(-1).astype(np.int64)
g1 = g.subgraph(nids)
g1 = dgl.remove_self_loop(g1)
g1 = dgl.add_self_loop(g1)
return g1 | [
"guangtao.wang@jd.com"
] | guangtao.wang@jd.com |
6a4e0c9277e2d77ad14e7fd67a40cff6e71e563c | b4eb1cd674580ef0136d1d5452cc039b295ecc6c | /tests/test_middleware.py | df774ee26a644c82aa55d405a7c4aca0dcde8b3f | [
"MIT"
] | permissive | jrobichaud/django-groups-cache | e0689c276adc8db93b0babb9245d65aa1896d2bb | cf219753f1e9d8f10437ce11671a246327431598 | refs/heads/master | 2020-04-30T09:31:18.855358 | 2018-01-06T13:57:12 | 2018-01-06T13:57:12 | 176,749,747 | 0 | 0 | null | 2019-03-20T14:18:18 | 2019-03-20T14:18:18 | null | UTF-8 | Python | false | false | 2,242 | py | import django
from django.core.cache import cache
from django.contrib.auth.models import AnonymousUser, User, Group
from django.test import TestCase
from mock import Mock
import mock
from groups_cache.compat import is_authenticated
from groups_cache.middleware import GroupsCacheMiddleware
from groups_cache import signals
class TestMiddleware(TestCase):
def setUp(self):
self.gcm = GroupsCacheMiddleware()
self.request = Mock()
self.user = Mock(id=123, name='bob')
if django.VERSION < (1, 10):
self.user.is_authenticated.return_value = True
else:
self.user.is_authenticated = True
def test_request_should_not_cache_anonymous(self):
self.request.user = Mock()
if django.VERSION < (1, 10):
self.request.user.is_authenticated.return_value = False
else:
self.request.user.is_authenticated = False
self.assertEqual(self.gcm.process_request(self.request), None)
self.assertIsNone(self.request.groups_cache)
cache.clear()
def test_request_should_cache_authenticated_user(self):
self.request.user = self.user
self.user.groups.all.return_value.values_list.return_value = Group.objects.none()
self.assertEqual(self.gcm.process_request(self.request), None)
self.assertIsInstance(self.request.groups_cache, type(Group.objects.none()))
self.assertEqual(len(self.request.groups_cache), 0)
cache.clear()
def test_request_should_cache_one_group(self):
Group.objects.create(name='revelers')
self.user.groups.all.return_value.values_list.return_value = Group.objects.all()
self.request.user = self.user
self.assertEqual(self.gcm.process_request(self.request), None)
self.assertIsInstance(self.request.groups_cache, type(Group.objects.none()))
self.assertEqual(len(self.request.groups_cache), 1)
def test_request_should_hit_cached_one_group(self):
self.request.user = self.user
self.assertEqual(self.gcm.process_request(self.request), None)
self.assertIsInstance(self.request.groups_cache, type(Group.objects.none()))
self.assertEqual(len(self.request.groups_cache), 1)
| [
"castner.rr@gmail.com"
] | castner.rr@gmail.com |
bb042febed8e692192c700d682213ca7c55341eb | 3e7db53009b413d1e9d2631be662487fb1e77117 | /asposetaskscloud/models/timephased_data_type.py | d636d7d383e4b84bb6debe99fdf47c6aa0aed1ca | [
"MIT"
] | permissive | aspose-tasks-cloud/aspose-tasks-cloud-python | d35e318ecc35ee9463fd7602a2e1f4f7dad17e33 | 7b61335d82529020f610bd5ae679244d0cdb83d1 | refs/heads/master | 2022-12-24T23:06:02.336709 | 2022-12-17T12:23:33 | 2022-12-17T12:23:33 | 240,446,905 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,294 | py | # coding: utf-8
# -----------------------------------------------------------------------------------
# <copyright company="Aspose" file="TimephasedDataType.py">
# Copyright (c) 2020 Aspose.Tasks Cloud
# </copyright>
# <summary>
# 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.
# </summary>
# -----------------------------------------------------------------------------------
import pprint
import re # noqa: F401
import six
class TimephasedDataType(object):
"""
"""
"""
allowed enum values
"""
ASSIGNMENTREMAININGWORK = "AssignmentRemainingWork"
ASSIGNMENTACTUALWORK = "AssignmentActualWork"
ASSIGNMENTACTUALOVERTIMEWORK = "AssignmentActualOvertimeWork"
ASSIGNMENTBASELINEWORK = "AssignmentBaselineWork"
ASSIGNMENTBASELINECOST = "AssignmentBaselineCost"
ASSIGNMENTACTUALCOST = "AssignmentActualCost"
RESOURCEBASELINEWORK = "ResourceBaselineWork"
RESOURCEBASELINECOST = "ResourceBaselineCost"
TASKBASELINEWORK = "TaskBaselineWork"
TASKBASELINECOST = "TaskBaselineCost"
TASKPERCENTCOMPLETE = "TaskPercentComplete"
ASSIGNMENTBASELINE1WORK = "AssignmentBaseline1Work"
ASSIGNMENTBASELINE1COST = "AssignmentBaseline1Cost"
TASKBASELINE1WORK = "TaskBaseline1Work"
TASKBASELINE1COST = "TaskBaseline1Cost"
RESOURCEBASELINE1WORK = "ResourceBaseline1Work"
RESOURCEBASELINE1COST = "ResourceBaseline1Cost"
ASSIGNMENTBASELINE2WORK = "AssignmentBaseline2Work"
ASSIGNMENTBASELINE2COST = "AssignmentBaseline2Cost"
TASKBASELINE2WORK = "TaskBaseline2Work"
TASKBASELINE2COST = "TaskBaseline2Cost"
RESOURCEBASELINE2WORK = "ResourceBaseline2Work"
RESOURCEBASELINE2COST = "ResourceBaseline2Cost"
ASSIGNMENTBASELINE3WORK = "AssignmentBaseline3Work"
ASSIGNMENTBASELINE3COST = "AssignmentBaseline3Cost"
TASKBASELINE3WORK = "TaskBaseline3Work"
TASKBASELINE3COST = "TaskBaseline3Cost"
RESOURCEBASELINE3WORK = "ResourceBaseline3Work"
RESOURCEBASELINE3COST = "ResourceBaseline3Cost"
ASSIGNMENTBASELINE4WORK = "AssignmentBaseline4Work"
ASSIGNMENTBASELINE4COST = "AssignmentBaseline4Cost"
TASKBASELINE4WORK = "TaskBaseline4Work"
TASKBASELINE4COST = "TaskBaseline4Cost"
RESOURCEBASELINE4WORK = "ResourceBaseline4Work"
RESOURCEBASELINE4COST = "ResourceBaseline4Cost"
ASSIGNMENTBASELINE5WORK = "AssignmentBaseline5Work"
ASSIGNMENTBASELINE5COST = "AssignmentBaseline5Cost"
TASKBASELINE5WORK = "TaskBaseline5Work"
TASKBASELINE5COST = "TaskBaseline5Cost"
RESOURCEBASELINE5WORK = "ResourceBaseline5Work"
RESOURCEBASELINE5COST = "ResourceBaseline5Cost"
ASSIGNMENTBASELINE6WORK = "AssignmentBaseline6Work"
ASSIGNMENTBASELINE6COST = "AssignmentBaseline6Cost"
TASKBASELINE6WORK = "TaskBaseline6Work"
TASKBASELINE6COST = "TaskBaseline6Cost"
RESOURCEBASELINE6WORK = "ResourceBaseline6Work"
RESOURCEBASELINE6COST = "ResourceBaseline6Cost"
ASSIGNMENTBASELINE7WORK = "AssignmentBaseline7Work"
ASSIGNMENTBASELINE7COST = "AssignmentBaseline7Cost"
TASKBASELINE7WORK = "TaskBaseline7Work"
TASKBASELINE7COST = "TaskBaseline7Cost"
RESOURCEBASELINE7WORK = "ResourceBaseline7Work"
RESOURCEBASELINE7COST = "ResourceBaseline7Cost"
ASSIGNMENTBASELINE8WORK = "AssignmentBaseline8Work"
ASSIGNMENTBASELINE8COST = "AssignmentBaseline8Cost"
TASKBASELINE8WORK = "TaskBaseline8Work"
TASKBASELINE8COST = "TaskBaseline8Cost"
RESOURCEBASELINE8WORK = "ResourceBaseline8Work"
RESOURCEBASELINE8COST = "ResourceBaseline8Cost"
ASSIGNMENTBASELINE9WORK = "AssignmentBaseline9Work"
ASSIGNMENTBASELINE9COST = "AssignmentBaseline9Cost"
TASKBASELINE9WORK = "TaskBaseline9Work"
TASKBASELINE9COST = "TaskBaseline9Cost"
RESOURCEBASELINE9WORK = "ResourceBaseline9Work"
RESOURCEBASELINE9COST = "ResourceBaseline9Cost"
ASSIGNMENTBASELINE10WORK = "AssignmentBaseline10Work"
ASSIGNMENTBASELINE10COST = "AssignmentBaseline10Cost"
TASKBASELINE10WORK = "TaskBaseline10Work"
TASKBASELINE10COST = "TaskBaseline10Cost"
RESOURCEBASELINE10WORK = "ResourceBaseline10Work"
RESOURCEBASELINE10COST = "ResourceBaseline10Cost"
PHYSICALPERCENTCOMPLETE = "PhysicalPercentComplete"
TASKWORK = "TaskWork"
TASKCOST = "TaskCost"
RESOURCEWORK = "ResourceWork"
RESOURCECOST = "ResourceCost"
ASSIGNMENTWORK = "AssignmentWork"
ASSIGNMENTCOST = "AssignmentCost"
UNDEFINED = "Undefined"
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
}
attribute_map = {
}
def __init__(self): # noqa: E501
"""TimephasedDataType - a model defined in Swagger""" # noqa: E501
self.discriminator = None
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, TimephasedDataType):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"ivan.andreychikov@gmail.com"
] | ivan.andreychikov@gmail.com |
817f724a608c79e36228a2d083a46f35bbc6f05e | 6abb92d99ff4218866eafab64390653addbf0d64 | /AtCoder/asa/2020/asa1117/c.py | f70e5d0c728ab867d45e89e016167d61880e2a9b | [] | no_license | Johannyjm/c-pro | 38a7b81aff872b2246e5c63d6e49ef3dfb0789ae | 770f2ac419b31bb0d47c4ee93c717c0c98c1d97d | refs/heads/main | 2023-08-18T01:02:23.761499 | 2023-08-07T15:13:58 | 2023-08-07T15:13:58 | 217,938,272 | 0 | 0 | null | 2023-06-25T15:11:37 | 2019-10-28T00:51:09 | C++ | UTF-8 | Python | false | false | 366 | py | n, m = map(int, input().split())
sc = [list(map(int, input().split())) for _ in range(m)]
for i in range(1000):
num = str(i)
d = len(num)
if(d != n): continue
valid = True
for s, c in sc:
s -= 1
if(num[s] != str(c)):
valid = False
break
if(valid):
print(num)
exit()
print(-1) | [
"meetpastarts@gmail.com"
] | meetpastarts@gmail.com |
120e45f76663885b569469fe940f8275dabec8d8 | 31312c4070788c045a35efb29f97da421ca3b1cf | /models/db.py | b89340b82593eea5e256fd3fdc20294991400418 | [
"LicenseRef-scancode-public-domain"
] | permissive | hitesh96db/stopstalk | c530f30335efdc0c8939c640bb1efd9e33565851 | 486b3876a928ba634d245ed9e153e63d54af5820 | refs/heads/master | 2020-12-30T20:56:08.016000 | 2015-10-06T22:22:33 | 2015-10-06T22:22:33 | 43,397,646 | 0 | 0 | null | 2015-09-29T22:15:46 | 2015-09-29T22:15:46 | null | UTF-8 | Python | false | false | 7,246 | py | # -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
## if SSL/HTTPS is properly configured and you want all HTTP requests to
## be redirected to HTTPS, uncomment the line below:
# request.requires_https()
## app configuration made easy. Look inside private/appconfig.ini
from gluon.contrib.appconfig import AppConfig
## once in production, remove reload=True to gain full speed
myconf = AppConfig(reload=True)
import custom_layout as custom
if not request.env.web2py_runtime_gae:
## if NOT running on Google App Engine use SQLite or other DB
# db = DAL('mysql://' + current.mysql_user + \
# ':' + current.mysql_password + \
# '@' + current.mysql_server + \
# '/' + current.mysql_dbname)
db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all'])
else:
## connect to Google BigTable (optional 'google:datastore://namespace')
db = DAL('google:datastore+ndb')
## store sessions and tickets there
session.connect(request, response, db=db)
## or store session in Memcache, Redis, etc.
## from gluon.contrib.memdb import MEMDB
## from google.appengine.api.memcache import Client
## session.connect(request, response, db = MEMDB(Client()))
## by default give a view/generic.extension to all actions from localhost
## none otherwise. a pattern can be 'controller/function.extension'
response.generic_patterns = ['*']
## choose a style for forms
response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other
response.form_label_separator = myconf.take('forms.separator')
## (optional) optimize handling of static files
# response.optimize_css = 'concat,minify,inline'
# response.optimize_js = 'concat,minify,inline'
## (optional) static assets folder versioning
# response.static_version = '0.0.0'
#########################################################################
## Here is sample code if you need for
## - email capabilities
## - authentication (registration, login, logout, ... )
## - authorization (role based authorization)
## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)
## - old style crud actions
## (more options discussed in gluon/tools.py)
#########################################################################
from gluon.tools import Auth, Service, PluginManager
from datetime import datetime
auth = Auth(db)
service = Service()
plugins = PluginManager()
initial_date = datetime.strptime("2013-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
extra_fields = [Field('institute', requires=IS_NOT_EMPTY()),
Field('stopstalk_handle',
requires=[IS_NOT_IN_DB(db,
'auth_user.stopstalk_handle',
error_message=T("Handle taken")),
IS_NOT_IN_DB(db,
'custom_friend.stopstalk_handle',
error_message=T("Handle taken"))]
),
Field('rating',
default=0,
writable=False),
Field('last_retrieved', 'datetime',
default=initial_date,
writable=False)
]
site_handles = []
for site in current.SITES:
site_handles += [Field(site.lower() + "_handle")]
extra_fields += site_handles
auth.settings.extra_fields['auth_user'] = extra_fields
auth.define_tables(username=False, signature=False)
## configure email
mail = auth.settings.mailer
mail.settings.server = current.smtp_server
mail.settings.sender = current.sender_mail
mail.settings.login = current.sender_mail + ":" + current.sender_password
## configure auth policy
auth.settings.registration_requires_verification = True
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True
#########################################################################
## Define your tables below (or better in another model file) for example
##
## >>> db.define_table('mytable',Field('myfield','string'))
##
## Fields can be 'string','text','password','integer','double','boolean'
## 'date','time','datetime','blob','upload', 'reference TABLENAME'
## There is an implicit 'id integer autoincrement' field
## Consult manual for more options, validators, etc.
##
## More API examples for controllers:
##
## >>> db.mytable.insert(myfield='value')
## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)
## >>> for row in rows: print row.id, row.myfield
#########################################################################
## after defining tables, uncomment below to enable auditing
# auth.enable_record_versioning(db)
custom_friend_fields = [Field("user_id", "reference auth_user"),
Field("first_name", requires=IS_NOT_EMPTY()),
Field("last_name", requires=IS_NOT_EMPTY()),
Field("institute", requires=IS_NOT_EMPTY()),
Field("stopstalk_handle", requires = [IS_NOT_IN_DB(db,
'auth_user.stopstalk_handle',
error_message=T("Handle already exists")),
IS_NOT_IN_DB(db,
'custom_friend.stopstalk_handle',
error_message=T("Handle already exists"))]),
Field("rating",
default=0,
writable=False),
Field("last_retrieved", "datetime",
default=initial_date,
writable=False)]
custom_friend_fields += site_handles
db.define_table("custom_friend",
*custom_friend_fields)
db.define_table("submission",
Field("user_id", "reference auth_user"),
Field("custom_user_id", "reference custom_friend"),
Field("stopstalk_handle"),
Field("site_handle"),
Field("site"),
Field("time_stamp", "datetime"),
Field("problem_name"),
Field("problem_link"),
Field("lang"),
Field("status"),
Field("points"),
)
db.define_table("friend_requests",
Field("from_h", "reference auth_user"),
Field("to_h", "reference auth_user"),
)
db.define_table("friends",
Field("user_id", "reference auth_user"),
Field("friends_list", "text"))
current.db = db
| [
"raj454raj@gmail.com"
] | raj454raj@gmail.com |
c80e6023fed108386a207eb74c98d32d92da4a79 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/adjectives/_swellest.py | c1d8de1b1e9a8d50b6af4e00d336f59e34ce7fc6 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 245 | py |
from xai.brain.wordbase.adjectives._swell import _SWELL
#calss header
class _SWELLEST(_SWELL, ):
def __init__(self,):
_SWELL.__init__(self)
self.name = "SWELLEST"
self.specie = 'adjectives'
self.basic = "swell"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
d7431e16f379bab0fbe33e2d1a47595816abb9e5 | 5dff0d0bcb6f48085f934dc4ab28f4e55727282d | /server/instruments/reaper.py | 4eff8967fb514f27e40d335884bff3d7c351c998 | [] | no_license | the-fool/hoku | 4d2304d602fc86400687c68c359799569e55effd | 2f53ecf6ef978ea9d75fa3c77e750ec328065add | refs/heads/master | 2018-10-26T09:14:12.214534 | 2018-08-26T22:49:19 | 2018-08-26T22:49:19 | 103,051,786 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 785 | py | from .base import BaseInstrument
class Reaper(BaseInstrument):
MINI_1_VOL = 9
MINI_1_VERB = 10
MINI_1_DIST = 11
MINI_2_VOL = 15
MINI_2_VERB = 12
MINI_2_DIST = 13
DRUM_VERB = 14
def mini_1_vol(self, value):
self._control(self.MINI_1_VOL, int(value))
def mini_2_vol(self, value):
self._control(self.MINI_2_VOL, int(value))
def mini_1_dist(self, value):
self._control(self.MINI_1_DIST, value)
def mini_2_dist(self, value):
self._control(self.MINI_2_DIST, value)
def mini_1_verb(self, value):
self._control(self.MINI_1_VERB, value)
def mini_2_verb(self, value):
self._control(self.MINI_2_VERB, value)
def drum_verb(self, value):
self._control(self.DRUM_VERB, value)
| [
"sketchbang@gmail.com"
] | sketchbang@gmail.com |
4720ddc731d6c1da9f9078fa6bd36c468dff766e | b0b87924d07101e25fa56754ceaa2f22edc10208 | /workspace/python_study/python_gspark/day4-1.py | f83b2699257b4262d3bbda20f3dba246ce56ecb2 | [] | no_license | SoheeKwak/Python | 2295dd03e5f235315d07355cbe72998f8b86c147 | e1a5f0ecf31e926f2320c5df0e3416306b8ce316 | refs/heads/master | 2020-04-02T13:49:58.367361 | 2018-11-23T09:33:23 | 2018-11-23T09:33:23 | 154,499,204 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,893 | py | from bs4 import BeautifulSoup
html = """
<html><body>
<ul>
<li>
<a href="http://www.naver.com">naver</a>
</li>
<li>
<a href="http://www.daum.net">daum</a>
</li>
</ul>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
link = soup.find("a")
print(link)
link2 = soup.find_all("a")
print(link2)
for i in link2:
# print(i)
myhref = i.attrs['href']
print(myhref)
text = i.string
print(text, "-->", myhref)
from bs4 import BeautifulSoup
html="""
<html><body>
<h1>빅데이터 분석</h1>
<p>데이터 수집</p>
<p>데이터 전처리</p>
<p>데이터 마이닝</p>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
h1 = soup.h1
print(h1)
h1 = soup.body.h1
print(h1)
h1 = soup.html.body.h1
print(h1)
p1 = soup.html.body.p
print(p1.string)
p2 = p1.next_sibling.next_sibling
print(p2)
p3 = p2.next_sibling.next_sibling
print(p3)
from bs4 import BeautifulSoup
import urllib.request as req
url = "http://info.finance.naver.com/marketindex/"
res = req.urlopen(url).read()
soup = BeautifulSoup(res,'html.parser')
p = soup.select_one("#exchangeList > li.on > a.head.usd > div > span.value").string
print("krw/usd=",p)
html = """
<html><body>
<div id = "test">
<h1>빅데이터 분석</h1>
<ul class = "lec">
<li>파이썬</li>
<li>머신러닝</li>
<li>통계분석</li>
</ul>
</div>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
print(soup)
res = soup.select_one("#test > h1").string
print(res)
res = soup.select_one("div#test > ul.lec > li").string
print(res)
res = soup.select_one("li").string
print(res)
res = soup.li
res2 = res.next_sibling.next_sibling
res3 = res2.next_sibling.next_sibling
print(res.string)
print(res2.string)
print(res3.string)
myList = soup.select("div#test > ul.lec > li")
for li in myList:
print(li.string)
test = soup.find(id = "test")
print(test)
| [
"soheekwak728@gmail.com"
] | soheekwak728@gmail.com |
5b359b667dad448b3a80c84e30867c87d641f496 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/pa3/sample/str_get_element-42.py | 890eb44f037c7631688f2cc5967b68b4d12596ca | [] | no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 184 | py | x:str = "abc"
a:str = ""
b:str = ""
c:str = ""
def str_get(s:str, $TypedVar) -> str:
return s[i]
a = str_get(x, 0)
b = str_get(x, 1)
c = str_get(x, 2)
print(a)
print(b)
print(c)
| [
"647530+Virtlink@users.noreply.github.com"
] | 647530+Virtlink@users.noreply.github.com |
73aaac7076a35b1339df56a6ec97847718e5b576 | a9063fd669162d4ce0e1d6cd2e35974274851547 | /swagger_client/models/inline_response20037.py | 95fc2cf006de2311defe2c4535c4bd38e08daa3b | [] | no_license | rootalley/py-zoom-api | 9d29a8c750e110f7bd9b65ff7301af27e8518a3d | bfebf3aa7b714dcac78be7c0affb9050bbce8641 | refs/heads/master | 2022-11-07T14:09:59.134600 | 2020-06-20T18:13:50 | 2020-06-20T18:13:50 | 273,760,906 | 1 | 3 | null | null | null | null | UTF-8 | Python | false | false | 7,916 | py | # coding: utf-8
"""
Zoom API
The Zoom API allows developers to safely and securely access information from Zoom. You can use this API to build private services or public applications on the [Zoom App Marketplace](http://marketplace.zoom.us). To learn how to get your credentials and create private/public applications, read our [Authorization Guide](https://marketplace.zoom.us/docs/guides/authorization/credentials). All endpoints are available via `https` and are located at `api.zoom.us/v2/`. For instance you can list all users on an account via `https://api.zoom.us/v2/users/`. # noqa: E501
OpenAPI spec version: 2.0.0
Contact: developersupport@zoom.us
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class InlineResponse20037(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'next_page_token': 'str',
'page_count': 'int',
'page_size': 'int',
'participants': 'list[InlineResponse20037Participants]',
'total_records': 'int'
}
attribute_map = {
'next_page_token': 'next_page_token',
'page_count': 'page_count',
'page_size': 'page_size',
'participants': 'participants',
'total_records': 'total_records'
}
def __init__(self, next_page_token=None, page_count=None, page_size=None, participants=None, total_records=None): # noqa: E501
"""InlineResponse20037 - a model defined in Swagger""" # noqa: E501
self._next_page_token = None
self._page_count = None
self._page_size = None
self._participants = None
self._total_records = None
self.discriminator = None
if next_page_token is not None:
self.next_page_token = next_page_token
if page_count is not None:
self.page_count = page_count
if page_size is not None:
self.page_size = page_size
if participants is not None:
self.participants = participants
if total_records is not None:
self.total_records = total_records
@property
def next_page_token(self):
"""Gets the next_page_token of this InlineResponse20037. # noqa: E501
The next page token is used to paginate through large result sets. A next page token will be returned whenever the set of available results exceeds the current page size. The expiration period for this token is 15 minutes. # noqa: E501
:return: The next_page_token of this InlineResponse20037. # noqa: E501
:rtype: str
"""
return self._next_page_token
@next_page_token.setter
def next_page_token(self, next_page_token):
"""Sets the next_page_token of this InlineResponse20037.
The next page token is used to paginate through large result sets. A next page token will be returned whenever the set of available results exceeds the current page size. The expiration period for this token is 15 minutes. # noqa: E501
:param next_page_token: The next_page_token of this InlineResponse20037. # noqa: E501
:type: str
"""
self._next_page_token = next_page_token
@property
def page_count(self):
"""Gets the page_count of this InlineResponse20037. # noqa: E501
The number of pages returned for the request made. # noqa: E501
:return: The page_count of this InlineResponse20037. # noqa: E501
:rtype: int
"""
return self._page_count
@page_count.setter
def page_count(self, page_count):
"""Sets the page_count of this InlineResponse20037.
The number of pages returned for the request made. # noqa: E501
:param page_count: The page_count of this InlineResponse20037. # noqa: E501
:type: int
"""
self._page_count = page_count
@property
def page_size(self):
"""Gets the page_size of this InlineResponse20037. # noqa: E501
The number of records returned within a single API call. # noqa: E501
:return: The page_size of this InlineResponse20037. # noqa: E501
:rtype: int
"""
return self._page_size
@page_size.setter
def page_size(self, page_size):
"""Sets the page_size of this InlineResponse20037.
The number of records returned within a single API call. # noqa: E501
:param page_size: The page_size of this InlineResponse20037. # noqa: E501
:type: int
"""
self._page_size = page_size
@property
def participants(self):
"""Gets the participants of this InlineResponse20037. # noqa: E501
Array of meeting participant objects. # noqa: E501
:return: The participants of this InlineResponse20037. # noqa: E501
:rtype: list[InlineResponse20037Participants]
"""
return self._participants
@participants.setter
def participants(self, participants):
"""Sets the participants of this InlineResponse20037.
Array of meeting participant objects. # noqa: E501
:param participants: The participants of this InlineResponse20037. # noqa: E501
:type: list[InlineResponse20037Participants]
"""
self._participants = participants
@property
def total_records(self):
"""Gets the total_records of this InlineResponse20037. # noqa: E501
The number of all records available across pages. # noqa: E501
:return: The total_records of this InlineResponse20037. # noqa: E501
:rtype: int
"""
return self._total_records
@total_records.setter
def total_records(self, total_records):
"""Sets the total_records of this InlineResponse20037.
The number of all records available across pages. # noqa: E501
:param total_records: The total_records of this InlineResponse20037. # noqa: E501
:type: int
"""
self._total_records = total_records
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(InlineResponse20037, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, InlineResponse20037):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"github@rootalley.com"
] | github@rootalley.com |
473643508173d56ecf3fe8c14b5fb62600047a35 | 4f4ab46092c73b1cfb0a7730bb3ed59b829552a9 | /src/transitive_closure.py | 724181ea557f3b713347230a46afc1f6c3137049 | [
"Unlicense"
] | permissive | kemingy/daily-coding-problem | ab3dcab662593fa9ce15ef49a9105cf962514189 | 0839311ec0848f8f0b4a9edba817ecceb8f944a0 | refs/heads/master | 2020-03-27T06:05:52.028030 | 2019-08-07T03:32:33 | 2019-08-07T03:32:33 | 146,078,162 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,184 | py | # The transitive closure of a graph is a measure of which vertices are reachable
# from other vertices. It can be represented as a matrix M, where M[i][j] == 1
# if there is a path between vertices i and j, and otherwise 0.
# For example, suppose we are given the following graph in adjacency list form:
# graph = [
# [0, 1, 3],
# [1, 2],
# [2],
# [3]
# ]
# The transitive closure of this graph would be:
# [1, 1, 1, 1]
# [0, 1, 1, 0]
# [0, 0, 1, 0]
# [0, 0, 0, 1]
# Given a graph, find its transitive closure.
def closure(graph):
n = len(graph)
matrix = [[0 for _ in range(n)] for row in range(n)]
for i in range(n):
for j in graph[i]:
matrix[i][j] = 1
for i in range(n-2, -1, -1):
path = [p for p in range(i+1, n) if matrix[i][p] == 1]
if not path:
continue
for j in range(i-1, -1, -1):
if matrix[j][i] == 1:
for p in path:
matrix[j][p] = 1
return matrix
if __name__ == '__main__':
graph = [
[0, 1, 3],
[1, 2],
[2,],
[3,],
]
print(closure(graph)) | [
"kemingy94@gmail.com"
] | kemingy94@gmail.com |
b92d0a536b3759e0b69960e134bad0a246f04b01 | 641f76328bfeb7e54f0793a18c5b7c00595b98fd | /packages/qcache/store/goods/migrations/0002_goods_version_timestamp.py | 0b0f87ec3a36bf092a87088fbcb5790ff2d77058 | [
"Apache-2.0"
] | permissive | lianxiaopang/camel-store-api | 1d16060af92eb01607757c0423377a8c94c3a726 | b8021250bf3d8cf7adc566deebdba55225148316 | refs/heads/master | 2020-12-29T13:23:18.118617 | 2020-02-09T08:38:53 | 2020-02-09T08:38:53 | 238,621,246 | 0 | 0 | Apache-2.0 | 2020-02-07T14:28:35 | 2020-02-06T06:17:47 | Python | UTF-8 | Python | false | false | 414 | py | # Generated by Django 2.2.7 on 2019-12-02 09:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('goods', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='goods',
name='version_timestamp',
field=models.DateTimeField(auto_now=True, verbose_name='更新时间'),
),
]
| [
"lyh@gzqichang.com"
] | lyh@gzqichang.com |
8f91fa57271dc972b722d8279dc9b614fbfcc268 | baf3996414315ffb60470c40c7ad797bf4e6897f | /02_ai/1_ml/8_ensemble_learning/code/chapter_23/10_tune_learning_rate.py | 8d53a5f6b6e2f205074bced889b430ee25fd1526 | [
"MIT"
] | permissive | thiago-allue/portfolio | 8fbbecca7ce232567aebe97c19944f444508b7f4 | 0acd8253dc7c5150fef9b2d46eead3db83ca42de | refs/heads/main | 2023-03-15T22:10:21.109707 | 2022-09-14T17:04:35 | 2022-09-14T17:04:35 | 207,919,073 | 0 | 0 | null | 2019-11-13T18:18:23 | 2019-09-11T22:40:46 | Python | UTF-8 | Python | false | false | 1,580 | py | # explore xgboost learning rate effect on performance
from numpy import mean
from numpy import std
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedStratifiedKFold
from xgboost import XGBClassifier
from matplotlib import pyplot
# get the dataset
def get_dataset():
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7)
return X, y
# get a list of models to evaluate
def get_models():
models = dict()
# define learning rates to explore
rates = [0.0001, 0.001, 0.01, 0.1, 1.0]
for r in rates:
key = '%.4f' % r
models[key] = XGBClassifier(eta=r)
return models
# evaluate a given model using cross-validation
def evaluate_model(model, X, y):
# define the evaluation procedure
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
# evaluate the model and collect the results
scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1)
return scores
# define dataset
X, y = get_dataset()
# get the models to evaluate
models = get_models()
# evaluate the models and store results
results, names = list(), list()
for name, model in models.items():
# evaluate the model
scores = evaluate_model(model, X, y)
# store the results
results.append(scores)
names.append(name)
# summarize the performance along the way
print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores)))
# plot model performance for comparison
pyplot.boxplot(results, labels=names, showmeans=True)
pyplot.show() | [
"thiago.allue@yahoo.com"
] | thiago.allue@yahoo.com |
5ca887c236dfdd6747f88e3232427442936668e0 | 3d6bb3df9ca1d0de6f749b927531de0790aa2e1d | /calibrate_CN_histograms.py | f60c6b0dedfab4fd51811d34d1ef3f915ca51ac7 | [] | no_license | standardgalactic/kuhner-python | da1d66a6d638a9a379ba6bae2affdf151f8c27c5 | 30b73554cc8bc9d532c8108b34dd1a056596fec7 | refs/heads/master | 2023-07-07T04:18:30.634268 | 2020-04-06T04:37:48 | 2020-04-06T04:37:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,893 | py | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 7 10:33:59 2016
@author: lpsmith
"""
from __future__ import division
import lucianSNPLibrary as lsl
from os import walk
nsamples_min = 21 #Arbitrary value: minimum number of samples we require
nsamples_max = 100000000
binwidth = 0.001
#indir = "CN_calc_log2rs/"
#outdir = "CN_smoothed_histograms/"
indir = "CN_calc_log2rs_rejoined/"
outdir = "CN_rejoined_histograms/"
srange = ""
if (nsamples_max > 0):
srange = "_" + str(nsamples_min) + "-" + str(nsamples_max)
# read the filtered data that compares Xiaohong's segmentation data with raw SNP data
#filenames = ["954_20016_avglog2rs.txt", "1049_20782_avglog2rs.txt"]
filenames = []
for (_, _, f) in walk(indir):
filenames += f
break
doubled = [[141, 21060], [141, 21062], [141, 21064], [163, 19208], [163, 19214], [194, 19868], [194, 19880], [450, 18974], [450, 18982], [512, 18744], [512, 18746], [512, 18748], [512, 18750], [512, 18762], [660, 19260], [660, 19262], [660, 19264], [660, 19272], [664, 19954], [772, 18944], [772, 18946], [848, 18794], [884, 20354], [884, 20358], [954, 20014], [954, 20016], [954, 20018], [991, 20600], [997, 20656], [997, 20666], [997, 20668], [997, 20672], [997, 20674], [1006, 21104], [1044, 20856], [1044, 20864], [997, 20658], [997, 20660], [997, 20662], [660, 19266], [660, 19270], [997, 20664], [740, 20000]]
#new_doubled = [[141, 21062], [163, 19208], [163, 19214], [194, 19868], [509, 19000], [512, 18748], [512, 18762], [660, 19260], [660, 19262], [660, 19264], [660, 19272], [664, 19954], [772, 18944]]
#doubled += new_doubled
#rejected_doubles = []
#doubled += rejected_doubles
all_data = []
double_loss_data = []
double_loss_from_doubled_data = []
loss_data = []
loss_from_doubled_data = []
wt_data = []
gain_data = []
balanced_gain_data = []
for filename in filenames:
if (filename.find(".txt") == -1):
continue
split= filename.split("_")
if (len(split) < 3):
continue
patient = split[0]
sample = split[1]
if (patient[0] < '0' or patient[0] > '9'):
continue
patient = int(patient)
sample = int(sample)
file = open(indir + filename, "r")
total_n = 0
sample_data = []
for line in file:
(chr, start, end, x_log2r, call, n_log2r, avg_log2r, stdev) = line.rstrip().split()
if (chr == "chr"):
continue
chr = int(chr)
if (chr >= 23):
continue
n_log2r = int(n_log2r)
if (n_log2r < nsamples_min):
continue
if (nsamples_max > 0 and n_log2r > nsamples_max):
continue
total_n += n_log2r
avg_log2r = float(avg_log2r)
all_data.append(avg_log2r)
sample_data.append(avg_log2r)
if (call == "Double_d"):
if ([patient, sample] in doubled):
double_loss_from_doubled_data.append(avg_log2r)
else:
double_loss_data.append(avg_log2r)
elif (call == "Loss"):
if ([patient, sample] in doubled):
loss_from_doubled_data.append(avg_log2r)
else:
loss_data.append(avg_log2r)
#loss_data.append(avg_log2r)
elif (call == "wt"):
wt_data.append(avg_log2r)
elif (call == "Gain"):
gain_data.append(avg_log2r)
elif (call == "Balanced_gain"):
balanced_gain_data.append(avg_log2r)
else:
print "Unknown call ", call
lsl.createPrintAndSaveHistogram(double_loss_from_doubled_data, outdir + str(patient) + "_" + str(sample) + "_smoothhist.txt", binwidth, show=False)
print "Double-loss from doubled genomes histogram:"
lsl.createPrintAndSaveHistogram(double_loss_from_doubled_data, outdir + "double_loss_from_doubled_hist" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
print "Loss from doubled genomes histogram:"
lsl.createPrintAndSaveHistogram(loss_from_doubled_data, outdir + "loss_from_doubled_hist" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
print "Double-loss histogram:"
lsl.createPrintAndSaveHistogram(double_loss_data, outdir + "double_loss" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
print "Loss histogram:"
lsl.createPrintAndSaveHistogram(loss_data, outdir + "loss" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
print "WT histogram:"
lsl.createPrintAndSaveHistogram(wt_data, outdir + "wt_hist" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
print "Balanced gain histogram:"
lsl.createPrintAndSaveHistogram(balanced_gain_data,outdir + "balanced_gain_hist" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
print "Gain histogram:"
lsl.createPrintAndSaveHistogram(gain_data,outdir + "gain_hist" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
print "All data histogram:"
lsl.createPrintAndSaveHistogram(all_data,outdir + "all_hist" + srange + ".txt", binwidth, axis=(-3.5, 1.5, 0))
| [
"lpsmith@uw.edu"
] | lpsmith@uw.edu |
f3831fe26da6c678dc2e49829f78175589d64d94 | 37d8802ecca37cc003053c2175f945a501822c82 | /10-贪心算法/0455.py | abdf70825a17b0ff77b8e07df26ed88d679067fd | [
"Apache-2.0"
] | permissive | Sytx74/LeetCode-Solution-Python | cc0f51e31a58d605fe65b88583eedfcfd7461658 | b484ae4c4e9f9186232e31f2de11720aebb42968 | refs/heads/master | 2020-07-04T18:17:24.781640 | 2019-07-30T03:34:19 | 2019-07-30T03:34:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 490 | py | class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort() # [2,3]
s.sort() # [1,2,3]
# 如果小的饼干满足不了贪心指数最小的小朋友,就放弃这个饼干
gi = 0
si = 0
res = 0
while gi < len(g) and si < len(s):
if s[si] >= g[gi]:
si += 1
gi += 1
res += 1
else:
si += 1
return res
| [
"121088825@qq.com"
] | 121088825@qq.com |
8e9b01a78a6b4215a07315e90ff3abf14419c6af | fed019ab105b513e935fc9f3f3119db5c212c565 | /algorithm/community_detection.py | 77676a894fcbe29355151a013e612afea50e7a2e | [] | no_license | superf2t/ringnet | d7194d31c22f7d5d1dd1aa46d62fca5c34a6f566 | 322942f47bdf27728bdf17e2d71122d8da13361a | refs/heads/master | 2021-01-24T02:53:44.552344 | 2012-12-25T15:22:48 | 2012-12-25T15:22:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,605 | py | '''
Created on Dec 19, 2012
@author: Yutao
Implementation of Girvan-Newman Community Detection Algorithm For Weighted Graphs
'''
import networkx as nx
import pkg_resources
pkg_resources.require("matplotlib")
import matplotlib.pylab as plt
import math
import csv
import random as rand
from metadata import settings
#this method just reads the graph structure from the file
def buildG( G, file_, delimiter_ ):
#construct the weighted version of the contact graph from cgraph.dat file
#reader = csv.reader(open("/home/kazem/Data/UCI/karate.txt"), delimiter=" ")
reader = csv.reader(open(file_), delimiter=delimiter_)
for line in reader:
if float(line[2]) != 0.0:
G.add_edge(int(line[0]),int(line[1]),weight=float(line[2]))
#Keep removing edges from Graph until one of the connected components of Graph splits into two.
#compute the edge betweenness
def CmtyGirvanNewmanStep( G ):
#print "call CmtyGirvanNewmanStep"
init_ncomp = nx.number_connected_components(G) #no of components
ncomp = init_ncomp
while ncomp <= init_ncomp:
bw = nx.edge_betweenness_centrality(G) #edge betweenness for G
#find the edge with max centrality
max_ = 0.0
#find the edge with the highest centrality and remove all of them if there is more than one!
for k, v in bw.iteritems():
_BW = float(v)/float(G[k[0]][k[1]]['weight']) #weighted version of betweenness
if _BW >= max_:
max_ = _BW
for k, v in bw.iteritems():
if float(v)/float(G[k[0]][k[1]]['weight']) == max_:
G.remove_edge(k[0],k[1]) #remove the central edge
ncomp = nx.number_connected_components(G) #recalculate the no of components
#compute the modularity of current split
def _GirvanNewmanGetModularity( G, deg_):
New_A = nx.adj_matrix(G)
New_deg = {}
UpdateDeg(New_deg, New_A)
#Let's compute the Q
comps = nx.connected_components(G) #list of components
print 'no of comp: %d' % len(comps)
Mod = 0 #Modularity of a given partitionning
for c in comps:
EWC = 0 #no of edges within a community
RE = 0 #no of random edges
for u in c:
EWC += New_deg[u]
RE += deg_[u] #count the probability of a random edge
Mod += ( float(EWC) - float(RE*RE)/float(2*m_) )
Mod = Mod/float(2*m_)
#print "Modularity: %f" % Mod
return Mod
def UpdateDeg(deg_, A_):
for i in range(0,n):
deg = 0.0
for j in range(0,n):
deg += A_[i,j]
deg_[i] = deg
#let's create a graph and insert the edges
G = nx.Graph()
buildG(G, settings.GRAPH_PATH+'\\1999', ' ')
#G = nx.read_edgelist('E:\\My Projects\\Eclipse Workspace\\ringnet\\data\\graph\\1999')
n = G.number_of_nodes() #|V|
#adjacenct matrix
A = nx.adj_matrix(G)
m_ = 0.0 #the weighted version for number of edges
for i in range(0,n):
for j in range(0,n):
m_ += A[i,j]
m_ = m_/2.0
print "m: %f" % m_
#calculate the weighted degree for each node
Orig_deg = {}
UpdateDeg(Orig_deg, A)
#let's find the best split of the graph
BestQ = 0.0
Q = 0.0
while True:
CmtyGirvanNewmanStep(G)
Q = _GirvanNewmanGetModularity(G, Orig_deg);
print "current modularity: %f" % Q
if Q > BestQ:
BestQ = Q
Bestcomps = nx.connected_components(G) #Best Split
print "comps:"
print Bestcomps
if G.number_of_edges() == 0:
break
if BestQ > 0.0:
print "Best Q: %f" % BestQ
print Bestcomps
else:
print "Best Q: %f" % BestQ | [
"stack@live.cn"
] | stack@live.cn |
6753857b3ae30e5fc86eb478872920d47de427dc | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/adjectives/_nervier.py | 50e82697190213ebc90d28e9ab11efd7627c8f7f | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 243 | py |
from xai.brain.wordbase.adjectives._nervy import _NERVY
#calss header
class _NERVIER(_NERVY, ):
def __init__(self,):
_NERVY.__init__(self)
self.name = "NERVIER"
self.specie = 'adjectives'
self.basic = "nervy"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
7165431f6198b23aa6e71561e48cfa8437fcba30 | 55173732ce1f2537a4fd8a6137b2a813f594b250 | /azure-mgmt-logic/azure/mgmt/logic/models/workflow.py | e29da68ee3c7ab95fd4d64e671e2c476bfbbee04 | [
"Apache-2.0"
] | permissive | dipple/azure-sdk-for-python | ea6e93b84bfa8f2c3e642aecdeab9329658bd27d | 9d746cb673c39bee8bd3010738c37f26ba6603a4 | refs/heads/master | 2020-02-26T15:32:39.178116 | 2016-03-01T19:25:05 | 2016-03-01T19:25:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,982 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may 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.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class Workflow(Resource):
"""Workflow
:param str id: Gets or sets the resource id.
:param str name: Gets the resource name.
:param str type: Gets the resource type.
:param str location: Gets or sets the resource location.
:param dict tags: Gets or sets the resource tags.
:param str provisioning_state: Gets the provisioning state. Possible
values include: 'NotSpecified', 'Moving', 'Succeeded'
:param datetime created_time: Gets the created time.
:param datetime changed_time: Gets the changed time.
:param str state: Gets or sets the state. Possible values include:
'NotSpecified', 'Enabled', 'Disabled', 'Deleted', 'Suspended'
:param str version: Gets the version.
:param str access_endpoint: Gets the access endpoint.
:param Sku sku: Gets or sets the sku.
:param ContentLink definition_link: Gets or sets the link to definition.
:param object definition: Gets or sets the definition.
:param ContentLink parameters_link: Gets or sets the link to parameters.
:param dict parameters: Gets or sets the parameters.
"""
_required = []
_attribute_map = {
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'WorkflowProvisioningState', 'flatten': True},
'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601', 'flatten': True},
'changed_time': {'key': 'properties.changedTime', 'type': 'iso-8601', 'flatten': True},
'state': {'key': 'properties.state', 'type': 'WorkflowState', 'flatten': True},
'version': {'key': 'properties.version', 'type': 'str', 'flatten': True},
'access_endpoint': {'key': 'properties.accessEndpoint', 'type': 'str', 'flatten': True},
'sku': {'key': 'properties.sku', 'type': 'Sku', 'flatten': True},
'definition_link': {'key': 'properties.definitionLink', 'type': 'ContentLink', 'flatten': True},
'definition': {'key': 'properties.definition', 'type': 'object', 'flatten': True},
'parameters_link': {'key': 'properties.parametersLink', 'type': 'ContentLink', 'flatten': True},
'parameters': {'key': 'properties.parameters', 'type': '{WorkflowParameter}', 'flatten': True},
}
def __init__(self, id=None, name=None, type=None, location=None, tags=None, provisioning_state=None, created_time=None, changed_time=None, state=None, version=None, access_endpoint=None, sku=None, definition_link=None, definition=None, parameters_link=None, parameters=None):
super(Workflow, self).__init__(id=id, name=name, type=type, location=location, tags=tags)
self.provisioning_state = provisioning_state
self.created_time = created_time
self.changed_time = changed_time
self.state = state
self.version = version
self.access_endpoint = access_endpoint
self.sku = sku
self.definition_link = definition_link
self.definition = definition
self.parameters_link = parameters_link
self.parameters = parameters
| [
"lmazuel@microsoft.com"
] | lmazuel@microsoft.com |
abf5cb941fac1874cfb1518b1df89f92c70bdc1b | ae7ba9c83692cfcb39e95483d84610715930fe9e | /jw2013/Leetcode-Py/Word Ladder II.py | f25c932467a340d39233741d56bf9fa9a057abd0 | [] | no_license | xenron/sandbox-github-clone | 364721769ea0784fb82827b07196eaa32190126b | 5eccdd8631f8bad78eb88bb89144972dbabc109c | refs/heads/master | 2022-05-01T21:18:43.101664 | 2016-09-12T12:38:32 | 2016-09-12T12:38:32 | 65,951,766 | 5 | 7 | null | null | null | null | UTF-8 | Python | false | false | 1,036 | py | class Solution:
def backtrack(self, result, trace, path, word):
if len(trace[word]) == 0:
result.append([word] + path)
else:
for prev in trace[word]:
self.backtrack(result, trace, [word] + path, prev)
def findLadders(self, start, end, dict):
result, trace, current = [], {word: [] for word in dict}, set([start])
while current and end not in current:
for word in current:
dict.remove(word)
next = set([])
for word in current:
for i in range(len(word)):
for j in 'abcdefghijklmnopqrstuvwxyz':
candidate = word[:i] + j + word[i + 1:]
if candidate in dict:
trace[candidate].append(word)
next.add(candidate)
current = next
if current:
self.backtrack(result, trace, [], end)
return result | [
"xenron@outlook.com"
] | xenron@outlook.com |
11f8805a3402a80099be4d5d5858bfcfe7aa76e9 | 077c91b9d5cb1a6a724da47067483c622ce64be6 | /updated_debug_branch_loop_mcs/interreplay_26_r.3/replay_config.py | 16dc3f2fb2d3bad8277505363a2b8eb9c6866f0c | [] | no_license | Spencerx/experiments | 0edd16398725f6fd9365ddbb1b773942e4878369 | aaa98b0f67b0d0c0c826b8a1565916bf97ae3179 | refs/heads/master | 2020-04-03T10:11:40.671606 | 2014-06-11T23:55:11 | 2014-06-11T23:55:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 926 | py |
from config.experiment_config_lib import ControllerConfig
from sts.topology import *
from sts.control_flow import Replayer
from sts.simulation_state import SimulationConfig
simulation_config = SimulationConfig(controller_configs=[ControllerConfig(start_cmd='./pox.py --verbose sts.syncproto.pox_syncer --blocking=False openflow.discovery forwarding.l2_multi sts.util.socket_mux.pox_monkeypatcher openflow.of_01 --address=__address__ --port=__port__', address='127.0.0.1', port=6633, cwd='pox', sync='tcp:localhost:18899')],
topology_class=MeshTopology,
topology_params="num_switches=2",
patch_panel_class=BufferedPatchPanel,
multiplex_sockets=True)
control_flow = Replayer(simulation_config, "experiments/updated_debug_branch_loop_mcs/interreplay_26_r.3/events.trace",
wait_on_deterministic_values=False)
# Invariant check: 'None'
| [
"cs@cs.berkeley.edu"
] | cs@cs.berkeley.edu |
2c0f1cf4b9b357f1424d5f1ef20680b82fdd0856 | ce76b3ef70b885d7c354b6ddb8447d111548e0f1 | /know_problem_over_group/hand_or_young_way/able_case/fact.py | 5e6e5cdadb856652ee5e1124bc52d79def4c99ec | [] | 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 | 192 | py |
#! /usr/bin/env python
def time(str_arg):
get_case_with_case(str_arg)
print('hand')
def get_case_with_case(str_arg):
print(str_arg)
if __name__ == '__main__':
time('week')
| [
"jingkaitang@gmail.com"
] | jingkaitang@gmail.com |
b0b16093569febbff40973724100b76c6c799077 | 79910ec27631b7e1f7f36eef0ab453ab66ebdc1b | /smartcontract/forms.py | 50cf4d81e6f670820991a3be7380302b09af2e5f | [] | no_license | SaurabhAgarwala/VeriBuy | bdbe2d93cff7e5335e09f3946dd1566c82ef599b | f971a21752dfd1c9ca9c143beb2ac30bdfa22b41 | refs/heads/main | 2023-01-13T00:57:10.869994 | 2020-11-04T16:47:58 | 2020-11-04T16:47:58 | 309,657,968 | 0 | 0 | null | 2020-11-03T14:01:19 | 2020-11-03T11:00:02 | Python | UTF-8 | Python | false | false | 290 | py | from django import forms
from . import models
class ProductForm(forms.ModelForm):
class Meta:
model = models.Product
fields = ['name', 'desc', 'retailer']
class EditOwnerForm(forms.ModelForm):
class Meta:
model = models.Product
fields = ['owner']
| [
"saur.agarwala@gmail.com"
] | saur.agarwala@gmail.com |
3cf80b733c974ec0f5aaaa1bc68f553ec0617fcd | 3b239e588f2ca6e49a28a63d906dd8dd26173f88 | /code/dlgo/gtp/play_local.py | cc9bdc1acbc90d702fa98051d9d530a2ce4c61b1 | [] | no_license | Angi16/deep_learning_and_the_game_of_go | 3bbf4f075f41359b87cb06fe01b4c7af85837c18 | ba63d5e3f60ec42fa1088921ecf93bdec641fd04 | refs/heads/master | 2020-03-23T16:02:47.431241 | 2018-07-21T02:57:16 | 2018-07-21T02:57:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,604 | py | from __future__ import print_function
# tag::play_local_imports[]
import subprocess
import re
import h5py
from dlgo.agent.predict import load_prediction_agent
from dlgo.agent.termination import PassWhenOpponentPasses, TerminationAgent
from dlgo.goboard_fast import GameState, Move
from dlgo.gotypes import Player
from dlgo.gtp.board import gtp_position_to_coords, coords_to_gtp_position
from dlgo.gtp.utils import SGFWriter
from dlgo.utils import print_board
from dlgo.scoring import compute_game_result
# end::play_local_imports[]
# TODO: py3 problems with strings
# tag::play_local_init[]
class LocalGtpBot():
def __init__(self, agent, termination=None, handicap=0,
opponent='gnugo', output_sgf="out.sgf",
our_color='b'):
self.bot = TerminationAgent(agent, termination) # <1>
self.handicap = handicap
self._stopped = False # <2>
self.game_state = GameState.new_game(19)
self.sgf = SGFWriter(output_sgf) # <3>
self.our_color = Player.black if 'b' else Player.white
self.their_color = self.our_color.other
cmd = self.opponent_cmd(opponent) # <4>
pipe = subprocess.PIPE
self.gtp_stream = subprocess.Popen(
cmd, stdin=pipe, stdout=pipe # <5>
)
def opponent_cmd(self, opponent):
if opponent == 'gnugo':
return ["gnugo", "--mode", "gtp"]
elif opponent == 'pachi':
return ["pachi"]
else:
raise ValueError("Unknown bot name {}".format(opponent))
# <1> We initialize a bot from an agent and a termination strategy.
# <2> We play until the game is stopped by one of the players.
# <3> At the end we write the the game to the provided file in SGF format
# <4> Our opponent will either be GNU Go or Pachi.
# <5> We read and write GTP commands from the command line.
# end::play_local_init[]
# tag::play_local_commands[]
def send_command(self, cmd):
self.gtp_stream.stdin.write(cmd.encode('utf-8'))
def get_response(self):
succeeded = False
result = ''
while succeeded == False:
line = self.gtp_stream.stdout.readline()
if line[0] == '=':
succeeded = True
line = line.strip()
result = re.sub('^= ?', '', line)
return result
def command_and_response(self, cmd):
self.send_command(cmd)
return self.get_response()
# end::play_local_commands[]
# tag::play_local_run[]
def run(self):
self.command_and_response("boardsize 19\n")
self.set_handicap()
self.play()
self.sgf.write_sgf()
def set_handicap(self):
if(self.handicap == 0):
self.command_and_response("komi 7.5\n")
self.sgf.append("KM[7.5]\n")
else:
stones = self.command_and_response("fixed_handicap {}\n".format(self.handicap))
sgf_handicap = "HA[{}]AB".format(self.handicap)
for pos in stones.split(" "):
move = gtp_position_to_coords(pos)
self.game_state = self.game_state.apply_move(move)
sgf_handicap = sgf_handicap + "[" + self.sgf.coordinates(move) + "]"
self.sgf.append(sgf_handicap + "\n")
# end::play_local_run[]
# tag::play_local_play[]
def play(self):
while not self._stopped:
if(self.game_state.next_player == self.our_color):
self.play_our_move()
else:
self.play_their_move()
print(chr(27) + "[2J")
print_board(self.game_state.board)
print("Estimated result: ")
print(compute_game_result(self.game_state))
# end::play_local_play[]
# tag::play_local_our[]
def play_our_move(self):
move = self.bot.select_move(self.game_state)
self.game_state = self.game_state.apply_move(move)
our_name = self.our_color.name
our_letter = our_name[0].upper()
sgf_move = ""
if move.is_pass:
self.command_and_response("play {} pass\n".format(our_name))
elif move.is_resign:
self.command_and_response("play {} resign\n".format(our_name))
else:
pos = coords_to_gtp_position(move)
self.command_and_response("play {} {}\n".format(our_name, pos))
sgf_move = self.sgf.coordinates(move)
self.sgf.append(";{}[{}]\n".format(our_letter, sgf_move))
# end::play_local_our[]
# tag::play_local_their[]
def play_their_move(self):
their_name = self.their_color.name
their_letter = their_name[0].upper()
pos = self.command_and_response("genmove {}\n".format(their_name))
if(pos.lower() == 'resign'):
self.game_state = self.game_state.apply_move(Move.resign())
self._stopped = True
elif(pos.lower() == 'pass'):
self.game_state = self.game_state.apply_move(Move.pass_turn())
self.sgf.append(";{}[]\n".format(their_letter))
if self.game_state.last_move.is_pass:
self._stopped = True
else:
move = gtp_position_to_coords(pos)
self.game_state = self.game_state.apply_move(move)
self.sgf.append(";{}[{}]\n".format(their_letter, self.sgf.coordinates(move)))
# end::play_local_their[]
if __name__ == "__main__":
agent = load_prediction_agent(h5py.File("../../agents/betago.hdf5", "r"))
gnu_go = LocalGtpBot(agent=agent, termination=PassWhenOpponentPasses(),
handicap=0, opponent='pachi', )
gnu_go.run()
| [
"max.pumperla@googlemail.com"
] | max.pumperla@googlemail.com |
16a959f9551c63b9e032874c0a95782b2913e825 | 4577d8169613b1620d70e3c2f50b6f36e6c46993 | /students/1762390/homework02/program01.py | 484371a7177473da3ea507bbb64ce466f2882439 | [] | no_license | Fondamenti18/fondamenti-di-programmazione | cbaf31810a17b5bd2afaa430c4bf85d05b597bf0 | 031ec9761acb1a425fcc4a18b07884b45154516b | refs/heads/master | 2020-03-24T03:25:58.222060 | 2018-08-01T17:52:06 | 2018-08-01T17:52:06 | 142,419,241 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,633 | py | '''
I post di un forum sono raccolti in alcuni file che hanno il seguente formato.
Un file contiene uno o piu' post, l'inizio di un post e' marcato da una linea che contiene
in sequenza le due sottostringhe "<POST>" ed "N" (senza virgolette) eventualmente
inframmezzate, precedute e/o seguite da 0,1 o piu' spazi.
"N" e' l'ID del post (un numero positivo).
Il contenuto del post e' nelle linee successive fino alla linea che marca il prossimo post
o la fine del file (si veda ad esempio il file "file01.txt").
E' assicurato che la stringa "<POST>" non e' contenuta in nessun post.
Nel seguito per parola intendiamo come al solito una qualsiasi sequenza di caratteri
alfabetici di lunghezza massimale. I caratteri alfabetici sono quelli per cui
ritorna True il metodo isalpha().
Scrivere una funzione post(fposts,insieme) che prende in input:
- il percorso di un file (fposts)
- ed un insieme di parole (insieme)
e che restituisce un insieme (risultato).
L'insieme restituito (risultato) dovra' contenere gli identificativi (ID) dei post
che contengono almeno una parola dell'inseme in input.
Due parole sono considerate uguali anche se alcuni caratteri alfabetici compaiono in una
in maiuscolo e nell'altra in minuscolo.
Per gli esempi vedere il file grade.txt
AVVERTENZE:
non usare caratteri non ASCII, come le lettere accentate;
non usare moduli che non sono nella libreria standard.
NOTA: l'encoding del file e' 'utf-8'
ATTENZIONE: Se un test del grader non termina entro 10 secondi il punteggio di quel test e' zero.
'''
def post(fposts,insieme):
messaggio = ""
listaFinale = []
with open(fposts, 'r', encoding = 'utf8') as file:
listaPost = []
for f in file:
if '<POST>' in f:
stringa = f.replace('\n', "").replace(" ", "").replace('<POST>', "")
listaPost.append(stringa)
else:
messaggio += f.replace("\n", "").replace("!", "").replace("£", "").replace("$","").replace("%","").replace("/","").replace("(","").replace(")","").replace("^","").replace(",","").replace("{","").replace("}","").replace(";","").replace(".","").replace(":","").replace("_","").replace("-","").replace("?","")
messaggio = messaggio.lower()
msg = messaggio.split(" ")
for m in msg:
for i in insieme:
if m == i.lower() :
listaFinale.append(str(listaPost[len(listaPost) - 1]))
messaggio = ""
return set(listaFinale)
| [
"a.sterbini@gmail.com"
] | a.sterbini@gmail.com |
a2123dd872e54d5bfb69f05e3c75c3e39798d898 | e41651d8f9b5d260b800136672c70cb85c3b80ff | /Notification_System/temboo/Library/Google/Contacts/DeleteContact.py | 78bb4c79c9ac5d784d8bf6d9ad842b30e04edc0a | [] | 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,655 | py | # -*- coding: utf-8 -*-
###############################################################################
#
# DeleteContact
# Deletes a specified contact.
#
# 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 DeleteContact(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the DeleteContact Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(DeleteContact, self).__init__(temboo_session, '/Library/Google/Contacts/DeleteContact')
def new_input_set(self):
return DeleteContactInputSet()
def _make_result_set(self, result, path):
return DeleteContactResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return DeleteContactChoreographyExecution(session, exec_id, path)
class DeleteContactInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the DeleteContact
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) The access token retrieved in the last step of the OAuth process. Access tokens that are expired will be refreshed and returned in the Choreo output.)
"""
super(DeleteContactInputSet, self)._set_input('AccessToken', value)
def set_ClientID(self, value):
"""
Set the value of the ClientID input for this Choreo. ((required, string) The OAuth client ID provided by Google when you register your application.)
"""
super(DeleteContactInputSet, self)._set_input('ClientID', value)
def set_ClientSecret(self, value):
"""
Set the value of the ClientSecret input for this Choreo. ((required, string) The OAuth client secret provided by Google when you registered your application.)
"""
super(DeleteContactInputSet, self)._set_input('ClientSecret', value)
def set_ContactID(self, value):
"""
Set the value of the ContactID input for this Choreo. ((required, string) The unique ID string for the contact you want to delete.)
"""
super(DeleteContactInputSet, self)._set_input('ContactID', value)
def set_RefreshToken(self, value):
"""
Set the value of the RefreshToken input for this Choreo. ((required, string) The refresh token retrieved in the last step of the OAuth process. This is used when an access token is expired or not provided.)
"""
super(DeleteContactInputSet, self)._set_input('RefreshToken', value)
class DeleteContactResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the DeleteContact Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_AccessToken(self):
"""
Retrieve the value for the "AccessToken" output from this Choreo execution. ((optional, string) The access token retrieved in the last step of the OAuth process. Access tokens that are expired will be refreshed and returned in the Choreo output.)
"""
return self._output.get('AccessToken', None)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Google. No content is returned for a successful delete request.)
"""
return self._output.get('Response', None)
class DeleteContactChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return DeleteContactResultSet(response, path)
| [
"shriswissfed@gmail.com"
] | shriswissfed@gmail.com |
21232647b1233b1d7d6dffa03ced25db2595b0a7 | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_1_1_neat/16_1_1_swmuron_a.py | 8645bb1c638b89d9b6e0812c33738dfd700156c8 | [] | no_license | DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | Python | UTF-8 | Python | false | false | 768 | py |
import sys
def solveIt(s):
maxletter = ''
word = ''
index = 0
slen = len(s)
while (index < slen):
print 'm: ' + maxletter + ' s[index]:' + s[index] + ' word: '+word
if (s[index] >= maxletter):
maxletter = s[index]
word = maxletter + word
else:
word = word + s[index]
index += 1
print 'word is '+word
return word
# actually process the solution file
with open(sys.argv[1]) as file:
with open("ans_"+sys.argv[1],'w') as outFile:
lines = file.read().splitlines()
count = -1
for line in lines:
# skip the test count line
count += 1
if (count == 0):
continue
result = solveIt(line)
outFile.write('Case #'+str(count)+': '+str(result))
outFile.write('\n') | [
"[dhuo@tcd.ie]"
] | [dhuo@tcd.ie] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.