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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
660491e0ab43b182e48bb20b65d28292b8eddcfd | 447aadd08a07857c3bcf826d53448caa8b6a59ee | /bin/Mysite/login/migrations/0007_auto_20200416_1543.py | bcdc7115d79612591477b9bab59fa7163e5ba010 | [] | no_license | aydanaderi/Site1 | 57461e9a43ddc7b7372d2e1690c37b09f73cbdef | 30dce3e5a52a221208b28bcaac51a57a35cd82c6 | refs/heads/master | 2021-06-03T11:30:54.317056 | 2020-05-01T13:43:07 | 2020-05-01T13:43:07 | 254,337,037 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 387 | py | # Generated by Django 3.0.5 on 2020-04-16 15:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login', '0006_auto_20200411_1354'),
]
operations = [
migrations.AlterField(
model_name='documents',
name='docfile',
field=models.FileField(upload_to=''),
),
]
| [
"ayda.f.naderi@gmail.com"
] | ayda.f.naderi@gmail.com |
8e68717886127698dae61c683d9eb0861b6eb68d | 1b48b3980abbe11691310a7f35efef62bc0ae831 | /Qt/treeview_expand.py | 80da55034812bad18d8274e37845f50393117444 | [] | no_license | FXTD-ODYSSEY/MayaScript | 7619b1ebbd664988a553167262c082cd01ab80d5 | 095d6587d6620469e0f1803d59a506682714da17 | refs/heads/master | 2022-11-05T08:37:16.417181 | 2022-10-31T11:50:26 | 2022-10-31T11:50:26 | 224,664,871 | 45 | 11 | null | null | null | null | UTF-8 | Python | false | false | 3,081 | py | # -*- coding: utf-8 -*-
"""
https://stackoverflow.com/questions/4100139
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
__author__ = 'timmyliang'
__email__ = '820472580@qq.com'
__date__ = '2021-07-14 12:07:56'
import sys
from PySide2 import QtCore,QtGui,QtWidgets
class MTreeExpandHook(QtCore.QObject):
"""
MTreeExpandHook( QTreeView )
"""
def __init__(self, tree):
super(MTreeExpandHook, self).__init__()
self.setParent(tree)
# NOTE viewport for MouseButtonPress event listen
tree.viewport().installEventFilter(self)
self.tree = tree
def eventFilter(self, receiver, event):
if (
# NOTE mouse left click
event.type() == QtCore.QEvent.Type.MouseButtonPress
# NOTE keyboard shift press
and event.modifiers() & QtCore.Qt.ShiftModifier
):
# NOTE get mouse local position
pos = self.tree.mapFromGlobal(QtGui.QCursor.pos())
index = self.tree.indexAt(pos)
if not self.tree.isExpanded(index):
# NOTE expand all child
# self.tree.expandRecursively(index)
self.recursive_expand(index)
return True
return super(MTreeExpandHook, self).eventFilter(self.tree, event)
def recursive_expand(self, index):
"""
Recursively expands/collpases all the children of index.
"""
childCount = index.internalPointer().get_child_count()
expand = self.isExpanded(index)
for childNo in range(0, childCount):
childIndex = index.child(childNo, 0)
if expand: #if expanding, do that first (wonky animation otherwise)
self.setExpanded(childIndex, expand)
subChildCount = childIndex.internalPointer().get_child_count()
if subChildCount > 0:
self.recursive_expand(childIndex)
if not expand: #if collapsing, do it last (wonky animation otherwise)
self.setExpanded(childIndex, expand)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
model = QtGui.QStandardItemModel()
# NOTE create nested data
for i in range(3):
parent = QtGui.QStandardItem('Family {}'.format(i))
for j in range(3):
child = QtGui.QStandardItem('Child {}'.format(i*3+j))
for k in range(3):
sub_child = QtGui.QStandardItem("Sub Child")
child.appendRow([sub_child])
for x in range(2):
sub_child_2 = QtGui.QStandardItem("Sub Child 2")
sub_child.appendRow([sub_child_2])
parent.appendRow([child])
model.appendRow(parent)
treeView = QtWidgets.QTreeView()
# NOTE hide header to get the correct position index
treeView.setHeaderHidden(True)
MTreeExpandHook(treeView)
treeView.setModel(model)
treeView.show()
sys.exit(app.exec_())
| [
"timmyliang@tencent.com"
] | timmyliang@tencent.com |
0ee1d341bde661cb3af6b474773b6cc9dd0ffaca | 2ccea24e19026bad25a01be5fa6c6120b9ce0df7 | /com_blacktensor/cop/fin/model/finance_dao.py | 53541b50306a283b24454d5ef880f406d212ed66 | [] | no_license | Jelly6489/BlackTensor_Test | 057f9b5c5c2fbeadd50b37effc0f655aea4d0a6c | 02b576077d5b2368357a0ca02e41d7d594bb2edc | refs/heads/master | 2023-01-19T16:51:25.660358 | 2020-11-21T08:03:00 | 2020-11-21T08:03:00 | 308,791,918 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,600 | py | # import sys
# sys.path.insert(0, '/c/Users/Admin/VscProject/BlackTensor_Test/com_blacktensor/cop/fin/model/')
import csv
import pandas as pd
from com_blacktensor.ext.db import db, openSession, engine
from sqlalchemy import func
from com_blacktensor.cop.fin.model.finance_kdd import FinanceKdd
from com_blacktensor.cop.fin.model.finance_dfo import FinanceDfo
from com_blacktensor.cop.fin.model.finance_dto import FinanceDto
from com_blacktensor.cop.emo.model.emotion_kdd import keyword
Session = openSession()
session = Session()
class FinanceDao(FinanceDto):
@staticmethod
def bulk():
finance_dfo = FinanceDfo()
dfo = finance_dfo.fina_pro(keyword)
session.bulk_insert_mappings(FinanceDto, dfo.to_dict(orient='records'))
session.commit()
session.close()
@classmethod
def count(cls):
return session.query(func.count(cls.no)).one()
@classmethod
def find_all(cls):
# return session.query(cls).all()
return session.query(cls).filter(cls.keyword.like(f'%{keyword}%')).all()
@classmethod
def find_keyword(cls, keyword):
print('==============find_update==============')
finance = session.query(cls).filter(cls.keyword.like(f'%{keyword}%')).all()
if finance != 0:
print('============중복 검사===========')
if finance == []:
print('============행복회로 가동===========')
FinanceDao.bulk()
@classmethod
def find_by_keyword(cls, keyword):
return session.query(cls).filter(cls.keyword.like(f'{keyword}')).all()
| [
"rlaalsrlzld@naver.com"
] | rlaalsrlzld@naver.com |
6620586e32e2dffe80b7dcfc94870b20f44295c3 | 55ab64b67d8abc02907eb43a54ff6c326ded6b72 | /scripts/addon_library/local/weight_layers/extra_props/dict_prop.py | c16420555cb0539a580249bfb0343b7ffd2bdb34 | [
"MIT"
] | permissive | Tilapiatsu/blender-custom_config | 2f03b0bb234c3b098d2830732296d199c91147d0 | 00e14fc190ebff66cf50ff911f25cf5ad3529f8f | refs/heads/master | 2023-08-16T14:26:39.990840 | 2023-08-16T01:32:41 | 2023-08-16T01:32:41 | 161,249,779 | 6 | 2 | MIT | 2023-04-12T05:33:59 | 2018-12-10T23:25:14 | Python | UTF-8 | Python | false | false | 932 | py | class DictProperty():
def __init__(self, get, set, update):
self.fget = get
self.fset = set
del get, set # don't use builtin python keywords
self.fupdate = update
self.value = dict()
self.prop = property(self.get_prop, self.set_prop)
def get_prop(self, parent_cls):
fget = self.fget
if fget:
return fget(parent_cls)
return self.value
def set_prop(self, parent_cls, value):
fget, fset = self.fget, self.fset
if fget and not fset:
raise AttributeError("This property is read only")
if fset:
fset(self, parent_cls, value)
if hasattr(value, "bl_rna"):
raise AttributeError("Cannot store blender properties in dict as they are likely to cause crashes.\
Use builtin Blender properties or NonIDProperty instead")
self.value = value
| [
"tilapiatsu@hotmail.fr"
] | tilapiatsu@hotmail.fr |
038b2cf06296a49f3f1963974e6aa1b8b8e8aff2 | 758c60aed145cf6b780d3cee4a79eb603452e3bd | /code/CNN/gensimBegin.py | e4fa2a76cb3e9ba55b282262a6ea83a4f8568865 | [] | no_license | aiedward/CCIR | 8be5d9b49a1cd653564c4fc00c2ef60f1f1d292d | 215179ac38fbde3899e55b078622606b31595d2d | refs/heads/master | 2020-03-24T09:55:45.382723 | 2018-04-07T14:15:30 | 2018-04-07T14:15:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,361 | py | from gensim import models
from gensim import corpora
from collections import defaultdict
from pprint import pprint
from matplotlib import pyplot as plt
import os
import logging
def PrintDictionary(dictionary):
token2id = dictionary.token2id
dfs = dictionary.dfs
token_info = {}
for word in token2id:
token_info[word] = dict(
word=word,
id=token2id[word],
freq=dfs[token2id[word]]
)
token_items = token_info.values()
token_items = sorted(token_items, key = lambda x:x['id'])
print('The info of dictionary: ')
pprint(token_items)
print('--------------------------')
def Show2dCorpora(corpus):
nodes = list(corpus)
ax0 = [x[0][1] for x in nodes]
ax1 = [x[1][1] for x in nodes]
plt.plot(ax0, ax1, 'o')
plt.show()
if __name__ == '__main__':
documents = ["Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface management system",
"System and human system engineering testing of EPS",
"Relation of user perceived response time to error measurement",
"The generation of random binary unordered trees",
"The intersection graph of paths in trees",
"Graph minors IV Widths of trees and well quasi ordering",
"Graph minors A survey"]
stoplist = set('for a of the end to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in documents]
frequency = defaultdict(int)
for text in texts:
for token in text:
frequency[token]+=1
texts = [[token for token in text if frequency[token] > 1]
for text in texts]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
PrintDictionary(dictionary)
tfidf_model = models.TfidfModel(corpus)
corpus_tfidf = tfidf_model[corpus]
lsi_model = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2)
corpus_lsi = lsi_model[corpus_tfidf]
nodes = list(corpus_lsi)
lsi_model.print_topics(2)
ax0 = [x[0][1] for x in nodes]
ax1 = [x[1][1] for x in nodes]
print(ax0)
print(ax1)
plt.plot(ax0, ax1, 'o')
plt.show()
| [
"872310734@qq.com"
] | 872310734@qq.com |
a13c3670b16ccd37f94df03791b4e5479c7df661 | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_136/506.py | 97cead2d20c05000e6f0ef1b89bf792e94a8dde0 | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 366 | py | T = int(raw_input())
for x in range(T):
C,F,X = map(float,raw_input().split())
baseRate = 2.0
farmSum = 0.0
answer = X/baseRate
nextRate = baseRate
while True:
farmSum = farmSum + C/nextRate
nextRate = nextRate + F
nextTime = farmSum + X/nextRate
if nextTime > answer:
break
else:
answer = nextTime
print "Case #"+str(x+1)+": "+str(answer)
| [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
56b2e52b6079bbad17c9eba7d35550045f064ce3 | 05ce3f49f97fb90cb245857cfc5cad82e1b39b51 | /game/DistributedHQInterior.py | b67e64b4efc968ea93e1aef5a0c8626678d8ab8f | [
"BSD-3-Clause"
] | permissive | rasheelprogrammer/toontown-otp-original | 8f63958330b02b43d0dc7c352b54cb96d54259d2 | 40749161f02c6f75844b1d072bf1498b42c2800d | refs/heads/master | 2020-04-25T18:43:05.476001 | 2018-06-18T06:38:19 | 2018-06-18T06:38:19 | 172,993,364 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 237 | py | from direct.distributed.DistributedObject import DistributedObject
class DistributedHQInterior(DistributedObject):
""" THIS IS A DUMMY FILE FOR THE DISTRIBUTED CLASS"""
def __init__(self, cr):
DistributedObject.__init__(self, cr)
| [
"anythingtechpro@gmail.com"
] | anythingtechpro@gmail.com |
ec57744bc80c9c95af651d2bd98f8ab59915f560 | f07a42f652f46106dee4749277d41c302e2b7406 | /Data Set/bug-fixing-5/27de8e692f7bf3c2efdd9c2d49ec589c29fd74be-<test_with_string_args>-bug.py | 6e1a75cc4d811b01fdc1cc54bd7d2b2d4f0324b2 | [] | no_license | wsgan001/PyFPattern | e0fe06341cc5d51b3ad0fe29b84098d140ed54d1 | cc347e32745f99c0cd95e79a18ddacc4574d7faa | refs/heads/main | 2023-08-25T23:48:26.112133 | 2021-10-23T14:11:22 | 2021-10-23T14:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 200 | py | def test_with_string_args(self):
for arg in ['sum', 'mean', 'min', 'max', 'std']:
result = self.ts.apply(arg)
expected = getattr(self.ts, arg)()
assert (result == expected) | [
"dg1732004@smail.nju.edu.cn"
] | dg1732004@smail.nju.edu.cn |
87d0df3fd49084447d39f97815acd63cc9348e39 | a3926c09872e1f74b57431fbb3e711918a11dc0a | /python/array/0674_longest_continuous_increasing_subsequence.py | ad8f2bf9674e3337c47abfe45fb547ed1dad797c | [
"MIT"
] | permissive | linshaoyong/leetcode | e64297dc6afcebcee0614a153a566323bf223779 | 57080da5fbe5d62cbc0b8a34e362a8b0978d5b59 | refs/heads/main | 2022-09-15T00:05:36.476268 | 2022-08-16T14:09:11 | 2022-08-16T14:09:11 | 196,914,051 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 692 | py | class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
r, start = 0, 0
prev = nums[0]
for i in range(1, len(nums)):
if nums[i] <= prev:
r = max(r, i - start)
start = i
prev = nums[i]
return max(r, len(nums) - start)
def test_find_length_of_lcis():
assert 0 == Solution().findLengthOfLCIS([])
assert 3 == Solution().findLengthOfLCIS([1, 3, 5, 4, 7])
assert 1 == Solution().findLengthOfLCIS([2, 2, 2, 2, 2])
assert 5 == Solution().findLengthOfLCIS([1, 3, 5, 7, 9])
| [
"linshaoyong@gmail.com"
] | linshaoyong@gmail.com |
1b4588f6e856386e80073511fb68317ef7a6fa8f | 2836c3caf8ca332635640a27254a345afd449081 | /asos/fix_drct.py | 4afd163f13bb8f61628c6a7ea92608274545271d | [
"Apache-2.0",
"MIT"
] | permissive | akrherz/DEV | 27cf1bac978a0d6bbfba1851b90d2495a3bdcd66 | 3b1ef5841b25365d9b256467e774f35c28866961 | refs/heads/main | 2023-08-30T10:02:52.750739 | 2023-08-29T03:08:01 | 2023-08-29T03:08:01 | 65,409,757 | 2 | 0 | MIT | 2023-09-12T03:06:07 | 2016-08-10T19:16:28 | Jupyter Notebook | UTF-8 | Python | false | false | 1,122 | py | """Somehow we ended up with directions impossible in METAR."""
import re
from pyiem.util import get_dbconn
WIND_RE = re.compile(r" ([0-9]{3})(\d+)G?(\d*)KT ")
def main(argv):
"""Go Main Go."""
year = argv[1]
pgconn = get_dbconn("asos")
cursor = pgconn.cursor()
cursor2 = pgconn.cursor()
cursor.execute(
f"SELECT station, valid, drct, metar from t{year} "
"WHERE drct is not null and (drct / 5)::int % 2 = 1 and "
"metar is not null LIMIT 10000"
)
hits = 0
fails = 0
for row in cursor:
m = WIND_RE.findall(row[3])
if not m:
fails += 1
continue
drct = int(m[0][0])
if drct == row[2]:
continue
cursor2.execute(
f"UPDATE t{year} SET drct = %s WHERE station = %s "
"and valid = %s",
(drct, row[0], row[1]),
)
hits += 1
print(f"{year} {hits}/{cursor.rowcount} rows updated, {fails} fails")
cursor2.close()
pgconn.commit()
if __name__ == "__main__":
for _year in range(1981, 2009):
main([None, str(_year)])
| [
"akrherz@iastate.edu"
] | akrherz@iastate.edu |
6151266686ffeedab4e8e6c4db45f28dff61d1c2 | 39bd7bf6875c51d8f67b20b67870880e46cddfc3 | /testioc.py | 91ba117b299b6aeced9e6f3b930c4adaaeba3ffd | [] | no_license | klauer/sxu_pot_calibration | 9d5bfa4f83f6c5947ffc7928f9421a1413989be9 | e10a97d61ce3247d0450fc9525aa2e7447bb03e5 | refs/heads/master | 2020-09-26T08:01:05.649486 | 2019-12-18T23:43:49 | 2019-12-18T23:43:49 | 226,210,411 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,409 | py | #!/usr/bin/env python3
from caproto.server import pvproperty, PVGroup, ioc_arg_parser, run
from textwrap import dedent
class SimpleIOC(PVGroup):
'''
'''
gap_des = pvproperty(value=0.1, name='GapDes')
gap_act = pvproperty(value=0.1, name='GapAct')
gap_go = pvproperty(value=0.1, name='Go')
ds_vact = pvproperty(value=0.1, name='DS:VAct')
ds_potvref = pvproperty(value=0.1, name='DS:PotVRef')
ds_gapref = pvproperty(value=0.1, name='DS:GapRef')
ds_potslope = pvproperty(value=0.1, name='DS:PotSlope')
ds_potoffset = pvproperty(value=0.1, name='DS:PotOffset')
ds_ctrlnshift = pvproperty(value=0.1, name='DS:CtrLnShift')
us_vact = pvproperty(value=0.1, name='US:VAct')
us_potvref = pvproperty(value=0.1, name='US:PotVRef')
us_gapref = pvproperty(value=0.1, name='US:GapRef')
us_potslope = pvproperty(value=0.1, name='US:PotSlope')
us_potoffset = pvproperty(value=0.1, name='US:PotOffset')
us_ctrlnshift = pvproperty(value=0.1, name='US:CtrLnShift')
@gap_go.putter
async def gap_go(self, instance, value):
await self.gap_act.write(self.gap_des.value)
if __name__ == '__main__':
ioc_options, run_options = ioc_arg_parser(
default_prefix='USEG:UNDS:4450:',
desc=dedent(SimpleIOC.__doc__))
ioc = SimpleIOC(**ioc_options)
run(ioc.pvdb, **run_options)
| [
"klauer@slac.stanford.edu"
] | klauer@slac.stanford.edu |
9abbab7f6e63ff04054a132dc8aa3f551965b9c0 | 5d91193b44c196ebf93d2c2e72d6d0f6367e248d | /get_framelst.py | 87ef9bfc01937e11b57000aaa871469257b16bbb | [] | no_license | ankitshah009/Object_detection | d2711b7fa0130d373cd0d4c50eee1dd2ef174d64 | c1b102e91c5cd6e7cbfd4233ce44b76488834b67 | refs/heads/master | 2020-05-23T06:55:11.454669 | 2019-04-24T14:28:42 | 2019-04-24T14:28:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,972 | py | # coding=utf-8
# given video lst and annopath, get frame lst
import sys,os,argparse,random
import numpy as np
from tqdm import tqdm
from glob import glob
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("videolst")
parser.add_argument("annopath")
parser.add_argument("framelst")
parser.add_argument("--skip",type=int,default=10)
parser.add_argument("--check_frame",default=None)
return parser.parse_args()
from class_ids import targetClass2id
if __name__ == "__main__":
args = get_args()
"""
selects = {
"Bike":0.7,
"Push_Pulled_Object":0.3,
"Prop":0.5,
"Door":0.02
}
"""
# select 2
selects = {
"Bike":1.0,
"Push_Pulled_Object":0.3,
"Prop":1.0,
"Door":0.01
}
videos = [os.path.splitext(os.path.basename(l.strip()))[0] for l in open(args.videolst).readlines()]
# get the annotation stats for all frames
label_dist = {classname:[] for classname in targetClass2id} # class -> [] num_box in each image
label_dist_all = []
framenames = []
ignored_classes = {}
for videoname in tqdm(videos,ascii=True):
frames = glob(os.path.join(args.annopath, "%s_F_*.npz"%videoname))
if args.check_frame is not None:
newframes = []
for f in frames:
filename = os.path.splitext(os.path.basename(f))[0]
framefile = os.path.join(args.check_frame, "%s"%videoname, "%s.jpg"%filename)
if os.path.exists(framefile):
newframes.append(f)
if not len(newframes) == len(frames):
tqdm.write("%s got %s/%s frames"%(videoname, len(newframes),len(frames)))
frames = newframes
framenames.extend([os.path.splitext(os.path.basename(l))[0] for l in frames])
# all frame for this video, get all anno
for frame in frames:
anno = dict(np.load(frame))
labels = []
boxes = []
for i,classname in enumerate(list(anno['labels'])):
if targetClass2id.has_key(classname):
labels.append(targetClass2id[classname])
boxes.append(anno['boxes'][i])
else:
ignored_classes[classname] = 1
anno['boxes'] = np.array(boxes,dtype="float32")
anno['labels'] = labels
# get stat for each class
for classname in label_dist:
num_box_this_img = len([l for l in anno['labels'] if l == targetClass2id[classname]])
label_dist[classname].append(num_box_this_img)
label_dist_all.append(len(anno['labels']))
print ignored_classes
for classname in label_dist:
d = label_dist[classname]
ratios = [a/float(b) for a,b in zip(d, label_dist_all)]
print "%s, [%s - %s], median %s per img, ratio:[%.3f - %.3f], median %.3f, no label %s/%s [%.3f]"%(classname, min(d), max(d), np.median(d), min(ratios), max(ratios), np.median(ratios), len([i for i in d if i==0]), len(d),len([i for i in d if i==0])/float(len(d)))
print "each img has boxes: [%s - %s], median %s"%(min(label_dist_all),max(label_dist_all),np.median(label_dist_all),)
# get all the frame that has at least one label for each class in select
selects_frames = {}
for classname in selects:
selects_frames[classname] = []
assert len(framenames) == len(label_dist[classname])
for framename,count in zip(framenames, label_dist[classname]):
if count >0:
selects_frames[classname].append(framename)
total = len(selects_frames[classname])
random.shuffle(selects_frames[classname])
selects_frames[classname] = selects_frames[classname][:int(total*selects[classname])]
print "%s, total non empty frame %s, random got %s, "%(classname, total, len(selects_frames[classname]))
# union all the selected class frames
addition_frames = list(set([f for c in selects_frames for f in selects_frames[c]]))
print "got %s frames from the selected class"%(len(addition_frames))
skip = args.skip
order_frames = framenames[::skip]
final = list(set(order_frames + addition_frames))
print "total frame %s, skip %s and get %s, add selected and final get %s"%(len(framenames), skip, len(order_frames), len(final))
with open(args.framelst,"w") as f:
for one in final:
f.writelines("%s\n"%one) | [
"junweil@cs.cmu.edu"
] | junweil@cs.cmu.edu |
c1f07f0edeadb0c59d74edb802cb3cad95b6f4ee | b7aadb2e91566630c563c7a626f190767918dd60 | /2021/day07.py | 6442163286e702b506dd6f64a2255f4048214024 | [] | no_license | kratsg/advent-of-code | 54a66e3959bca340663c4bb8c8e5c0f1aaa088f9 | 672dfa34e811030c8d67e5466d1be218395e1ff3 | refs/heads/master | 2023-08-09T10:48:52.046121 | 2023-07-26T02:04:22 | 2023-07-26T02:04:22 | 225,422,271 | 1 | 0 | null | 2023-07-26T02:04:23 | 2019-12-02T16:40:18 | Python | UTF-8 | Python | false | false | 1,031 | py | import numpy as np
import re
def process_input(data):
return np.array(data.split(","), dtype="int64")
def get_min(data, cost_func):
mmax = data.max()
guesses = np.arange(mmax)
space = data[None, :]
space = np.repeat(space, guesses.size, axis=0)
space = np.abs(space - guesses[:, None])
cost = cost_func(space)
return int(guesses[cost.argmin()]), int(cost.min())
def min_cost_part1(space):
return np.sum(space, axis=1)
def min_cost_part2(space):
return np.sum(space * (space + 1) / 2, axis=1)
if __name__ == "__main__":
from aocd.models import Puzzle
test_vals = process_input("""16,1,2,0,4,2,7,1,2,14""")
assert get_min(test_vals, min_cost_part1) == (2, 37)
puz = Puzzle(2021, 7)
data = process_input(puz.input_data)
puz.answer_a = get_min(data, min_cost_part1)[1]
print(f"Part 1: {puz.answer_a}")
assert get_min(test_vals, min_cost_part2) == (5, 168)
puz.answer_b = get_min(data, min_cost_part2)[1]
print(f"Part 2: {puz.answer_b}")
| [
"kratsg@gmail.com"
] | kratsg@gmail.com |
a5e56765d9ee5e9dc75333b4f471e919d523b536 | c9c329f977138d518636221fde28bfb16e5caab2 | /code/model/print_dataset.py | f928813b655189c1c7e00ce93be05449164d1688 | [
"MIT"
] | permissive | AndreasMadsen/master-thesis | 1690f3ae76531f5b489f48d4980d85c1cbd8628b | 294042091ee595bff813422fc54805f474711594 | refs/heads/master | 2021-03-16T10:12:12.318947 | 2017-08-06T17:13:37 | 2017-08-06T17:13:37 | 78,628,027 | 12 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,785 | py |
import math
from typing import Optional
import sugartensor as stf
from code.model.abstract.model import Model
from code.dataset.abstract.text_dataset import TextDataset
class PrintDataset(Model):
limit: Optional[int]
def __init__(self, dataset: TextDataset, limit=None) -> None:
self.limit = dataset.num_observation
if limit is not None:
self.limit = min(self.limit, limit)
super().__init__(dataset)
def train(self) -> None:
# index formatter
digits = math.ceil(math.log10(self.limit))
formatter = '{:>%d}' % (digits, )
source_formatter = ' ' + formatter + ' source: '
target_formatter = ' ' + (' ' * digits) + ' target: '
# evaluate tensor list with queue runner
with stf.Session() as sess:
stf.sg_init(sess)
with stf.sg_queue_context():
observations_read = 0
for minibatch in range(self.dataset.num_batch):
print('minibatch: %d' % minibatch)
sources, targets = sess.run([
self.dataset.source, self.dataset.target
])
for i, source, target in zip(
range(observations_read, self.limit),
sources,
targets
):
observations_read = i + 1
print(source_formatter.format(i) +
self.dataset.decode_as_str(source))
print(target_formatter +
self.dataset.decode_as_str(target))
print('')
if observations_read == self.limit:
break
| [
"amwebdk@gmail.com"
] | amwebdk@gmail.com |
b7f8b005367c8a00cead3af960a174dbf9b4cea8 | dc3c88f1fe5c80147e4c52ee6ec3136307ec9702 | /navigateTo/test/filenameAndPositionTransform2_tempOff.py | 2b1b7b881c0edc914eadfc300facc5cdd607b1aa | [] | no_license | ypapax/all_sublime_plugins | 062f9b9992a093a02e6b905c1329c681c8532034 | 8b10e471233bd6c2e77907cf5569b0ddccfc88f9 | refs/heads/master | 2021-01-15T21:10:08.029750 | 2015-08-16T06:32:51 | 2015-08-16T06:32:51 | 40,391,701 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,186 | py |
import sys
import os
currentFolder = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(currentFolder, '..'))
sys.path.insert(0, os.path.join(currentFolder, '../util'))
import pyFind
import unittest
import color
import navigateToModel
class Test(unittest.TestCase):
def test_testName(self):
color.blue("test here baby")
filename1 = os.path.join(currentFolder, '../testPoligon/py/as/a.py')
position1 = len("""import b_model2 as b_model
import unittest
import sys
sys.path.insert(0, '/Users/maks/Library/Application Support/Sublime Text 3/Packages/util')
import color
class Test(unittest.TestCase):
def test_bigFile(self):
color.blue("test here baby")
expected = ['', 'startsLikeCodeNumber']
result = b_model.getO""")
result = navigateToModel.filenameAndPositionTransform(filename1, position1)
expected = ('/Users/maks/Library/Application Support/Sublime Text 3/Packages/navigateTo/testPoligon/py/as/b_model2.py',
790)
print(result)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| [
"maxYefr@gmail.com"
] | maxYefr@gmail.com |
2eaddf49f34f8ba648aff47afb0f1151a0001cd9 | d3efc82dfa61fb82e47c82d52c838b38b076084c | /StructuredFund/creationRedemption/YW_FJJJ_SZSS_013.py | d5767db35668897caff2bd0279727c88b72d8fd2 | [] | no_license | nantongzyg/xtp_test | 58ce9f328f62a3ea5904e6ed907a169ef2df9258 | ca9ab5cee03d7a2f457a95fb0f4762013caa5f9f | refs/heads/master | 2022-11-30T08:57:45.345460 | 2020-07-30T01:43:30 | 2020-07-30T01:43:30 | 280,388,441 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,648 | py | #!/usr/bin/python
# -*- encoding: utf-8 -*-
import sys
sys.path.append("/home/yhl2/workspace/xtp_test/xtp/api")
from xtp_test_case import *
sys.path.append("/home/yhl2/workspace/xtp_test/StructuredFund/serviceCreationRedemption")
from mainService import *
from QueryStructuredFundInfo import *
sys.path.append("/home/yhl2/workspace/xtp_test/service")
from log import *
class YW_FJJJ_SZSS_013(xtp_test_case):
# YW_FJJJ_SZSS_013
def test_YW_FJJJ_SZSS_013(self):
title='母基金申赎--申购:错误的交易市场'
#定义当前测试用例的期待值
#期望状态:初始、未成交、部成、全成、部撤已报、部撤、已报待撤、已撤、废单、撤废、内部撤单
#xtp_ID和cancel_xtpID默认为0,不需要变动
case_goal = {
'期望状态': '废单',
'errorID': 11000010,
'errorMSG': 'Failed to get ticker quotes,ticker does not exist or can not be traded!',
'是否生成报单': '是',
'xtp_ID': 0,
'cancel_xtpID': 0,
}
logger.warning(title)
# 定义委托参数信息------------------------------------------
# 参数:证券代码、市场、证券类型、证券状态、交易状态、买卖方向(B买S卖)、期望状态、Api
stkparm = QueryStructuredFundInfo('999999','2','26','2','0','0',case_goal['期望状态'],Api)
# 如果下单参数获取失败,则用例失败
if stkparm['返回结果'] is False:
rs = {
'用例测试结果':stkparm['返回结果'],
'测试错误原因':'获取下单参数失败,'+stkparm['错误原因'],
}
self.assertEqual(rs['用例测试结果'], True)
else:
wt_reqs = {
'business_type':Api.const.XTP_BUSINESS_TYPE['XTP_BUSINESS_TYPE_STRUCTURED_FUND_PURCHASE_REDEMPTION'],
'market': Api.const.XTP_MARKET_TYPE['XTP_MKT_SH_A'],
'ticker': stkparm['证券代码'],
'side': Api.const.XTP_SIDE_TYPE['XTP_SIDE_PURCHASE'],
'price_type': Api.const.XTP_PRICE_TYPE['XTP_PRICE_LIMIT'],
'quantity': 1000
}
ParmIni(Api,case_goal['期望状态'],wt_reqs['price_type'])
rs = serviceTest(Api, case_goal, wt_reqs)
logger.warning('执行结果为' + str(rs['用例测试结果']) + ',' + str(rs['用例错误源']) + ',' + str(rs['用例错误原因']))
self.assertEqual(rs['用例测试结果'], True) # 0
if __name__ == '__main__':
unittest.main()
| [
"418033945@qq.com"
] | 418033945@qq.com |
a58cfc35c7f19d872fc6e26e1a945d63a0d6e651 | a7d1030cb797b862b87ee3e8b8a206814d26eee2 | /videodelayaudiotrack | bb282504b4413d6187140e500d02885e84fd27d9 | [] | no_license | lmanul/sak | 8bdf98d2e463f3e171aa79b82557cd4d6ade2724 | 37604f1d0dc61373bd24d73d742afe9c754e62a3 | refs/heads/master | 2023-08-30T07:51:04.727676 | 2023-08-27T06:09:46 | 2023-08-27T06:09:46 | 144,207,029 | 6 | 0 | null | null | null | null | UTF-8 | Python | false | false | 326 | #!/usr/bin/python3
import os
import sys
movie = sys.argv[1]
delay = sys.argv[2]
bup = movie + ".bup"
os.system("mv " + movie + " " + bup)
cmd = ("ffmpeg "
"-i " + bup + " "
"-itsoffset " + delay + " "
"-i " + bup + " "
"-map 0:v -map 1:a -c copy "
"" + movie)
#print(cmd)
os.system(cmd)
| [
"m@ma.nu"
] | m@ma.nu | |
7fdfd3886944d61fb2cd2d19c39edfb03623fccb | 3ec84a6e34f9bc709cb203f8b3f668f2b6697e2a | /python20200322-master/class_Python기초/py15딕셔너리/py15_05_딕셔너리연산자.py | 1c10fc16e0189c0c15e79618d015d65ed622092c | [] | no_license | eopr12/pythonclass | 52079bd99358ac73664beed236659b97c8b63d40 | 2526fe255969a799f6c534c9db6bff9e4eccd877 | refs/heads/master | 2022-07-10T11:17:31.692754 | 2020-05-16T08:43:00 | 2020-05-16T08:43:00 | 263,377,402 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,612 | py | # 딕셔너리 연산자
# + 결합 연산자 : X
# * 반복 연산자 : X
# [] 선택 연산자
# [:] 범위 선택 연산자
# == 일치 연산자
# del 삭제 연산자
# in in 연산자
# not in not in 연산자
# 딕셔너리 선언
dict1 = {"a": 1, "b": "가", "c": "0101"}
dict2 = {"a": 2, "d": "017"}
print("dict1 : ", dict1)
print("dict2 : ", dict2)
print()
# 딕셔너리 in 연산자
array = [1, 2, 3, 4, 5, 6]
print("array: ", array)
print("딕셔너리 in 연산자 1 in array :", 1 in array) # True
print("딕셔너리 in 연산자 2 in array :", 2 in array) # False
print("딕셔너리 in 연산자 11 in array :", 11 in array) # False
print("딕셔너리 in 연산자 12 in array :", 12 in array) # True
print()
## 딕셔너리 not in 연산자
array = [1, 2, 3, 4, 5, 6]
print("array: ", array)
print("딕셔너리 not in 연산자 1 not in array :", 1 not in array) # True
print("딕셔너리 not in 연산자 2 not in array :", 2 not in array) # False
print("딕셔너리 not in 연산자 11 not in array :", 11 not in array) # False
print("딕셔너리 not in 연산자 12 not in array :", 12 not in array) # True
print()
# del 연산자 : 딕셔너리 요소 제거
list_a = [1, 2, 3, 4, 5, 6]
print("array:", list_a)
del list_a[1]
print("del array[1]:", list_a)
list_b = [0, 1, 2, 3, 4, 5, 6]
del list_b[3:6]
print("del list_b[3:6] >> ", list_b)
list_c = [0, 1, 2, 3, 4, 5, 6]
del list_c[:3]
print("del list_c[:3] >> ", list_c)
list_d = [0, 1, 2, 3, 4, 5, 6]
del list_d[3:]
print("del list_d[3:] >>", list_d)
| [
"kye9565@gmail.com"
] | kye9565@gmail.com |
b6170ce52bdfdb7b7d0ec309432ed36234f1ede4 | 7410903c6cd5ef35c592af00c934fb21c369cbf2 | /00_Code/01_LeetCode/26_RemoveDuplicatesfromSortedArray.py | fcc060229cdf16164868f0cf392025e2c31533d3 | [
"MIT"
] | permissive | KartikKannapur/Algorithms | f4e4726170599db0622d18e8c06a382e9bce9e77 | 66e3c8112826aeffb78bd74d02be1a8d1e478de8 | refs/heads/master | 2020-12-25T18:32:41.086518 | 2020-10-19T02:59:47 | 2020-10-19T02:59:47 | 93,961,043 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,610 | py | """
Given a sorted array, remove the duplicates in-place
such that each element appear only once and return the
new length.
Do not allocate extra space for another array, you must
do this by modifying the input array in-place with O(1)
extra memory.
Example:
Given nums = [1,1,2],
Your function should return length = 2, with the first
two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.
Your runtime beats 76.68 % of python submissions.
"""
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
"""
Method 2:
Iterate from the end of the array.
If the (i-1)th element is the same as the ith element,
pop the ith element
Your runtime beats 28.02 % of python submissions.
"""
# for i in range(len(nums)-1, 0, -1):
# if nums[i] == nums[i-1]:
# nums.pop(i)
# return len(nums)
"""
Method 3:
Two pointers
The fast pointer j, check when the next element is not
equal to the slow pointer i; incrments i and sets the
next element in the array equal to the next occurring
unique element.
Your runtime beats 76.68 % of python submissions.
"""
if len(nums) == 0:
return 0
i = 0
for j in range(1, len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
# print(nums)
return i + 1
| [
"kartikkannapur@gmail.com"
] | kartikkannapur@gmail.com |
c2c92531f87f2e83906b1db64814e5b1855baea7 | f3eaf09705b9dcc92f15d9aaa25aa739bd09c161 | /pyti/money_flow_index.py | 85ccab1a94b2264b5d55a3d95da79ba37045aa52 | [
"MIT"
] | permissive | BernhardSchlegel/pyti | 9f7171d660d6b4e4450d3b5882132204a4d3a3d7 | bfead587fe49f7662df475a28688d3ce649e2e9b | refs/heads/master | 2021-08-19T22:14:52.721190 | 2017-11-27T14:35:59 | 2017-11-27T14:35:59 | 111,237,071 | 1 | 0 | null | 2017-11-18T20:30:59 | 2017-11-18T20:30:59 | null | UTF-8 | Python | false | false | 1,480 | py | import numpy as np
import warnings
from pyti import catch_errors
from pyti.function_helper import fill_for_noncomputable_vals
from pyti.typical_price import typical_price
from pyti.money_flow import money_flow
def money_flow_index(close_data, high_data, low_data, volume, period):
"""
Money Flow Index.
Formula:
MFI = 100 - (100 / (1 + PMF / NMF))
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
catch_errors.check_for_period_error(close_data, period)
mf = money_flow(close_data, high_data, low_data, volume)
tp = typical_price(close_data, high_data, low_data)
flow = map(lambda idx: tp[idx] > tp[idx-1], range(1, len(tp)))
pf = map(lambda idx: mf[idx] if flow[idx] else 0, range(0, len(flow)))
nf = map(lambda idx: mf[idx] if not flow[idx] else 0, range(0, len(flow)))
pmf = map(
lambda idx:
sum(pf[idx+1-period:idx+1]),
range(period-1, len(pf))
)
nmf = map(
lambda idx:
sum(nf[idx+1-period:idx+1]),
range(period-1, len(nf))
)
# Dividing by 0 is not an issue, it turns the value into NaN which we would
# want in that case
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
money_ratio = np.array(pmf) / np.array(nmf)
mfi = 100 - (100 / (1 + money_ratio))
mfi = fill_for_noncomputable_vals(close_data, mfi)
return mfi
| [
"kyle@collectiveidea.com"
] | kyle@collectiveidea.com |
bffa0c03e8811c70e7f4421b0003974ed2c4429e | 9009ad47bc1d6adf8ee6d0f2f2b3125dea44c0aa | /tcs-mvita-a.py | 33c71e2a1f3a822734916449b02ad1a18aaf0e18 | [] | no_license | luctivud/Coding-Trash | 42e880624f39a826bcaab9b6194add2c9b3d71fc | 35422253f6169cc98e099bf83c650b1fb3acdb75 | refs/heads/master | 2022-12-12T00:20:49.630749 | 2020-09-12T17:38:30 | 2020-09-12T17:38:30 | 241,000,584 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 723 | py | import sys; import math; from collections import *
# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().split())
def get_list(): return list(get_ints())
def printspx(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")
UGLYMOD = int(1e9+7); SEXYMOD = 998244353; MAXN = int(1e5)
#sys.stdin = open("input.txt","r"); sys.stdout = open("output.txt","w")
for _testcases_ in range(int(input())):
print(len(bin(int(input())))-2)
'''
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA )
Link may be copy-pasted here if it's taken from other source.
DO NOT PLAGIARISE.
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
''' | [
"luctivud@gmail.com"
] | luctivud@gmail.com |
8676adc573d7c4b079d5baab6d9d16c01faa66cd | bd5b3934969ebf4f693ceb4be17a68f9c3ebd414 | /beginPython/programmingCollectiveIntelligence/chapter5/socialnetwork.py | 11ce5a19d4d6ca402e578eb8a330bd2f3f1a792f | [] | no_license | lyk4411/untitled | bc46863d3bbb2b71edf13947f24b892c2cf43e1a | 875b7dfa765ffa40d76582d2ae41813d2e15c8bd | refs/heads/master | 2021-04-06T09:09:08.977227 | 2021-03-10T02:56:34 | 2021-03-10T02:56:34 | 124,990,530 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,490 | py | import math
from beginPython.programmingCollectiveIntelligence.chapter5 import optimization
people=['Charlie','Augustus','Veruca','Violet','Mike','Joe','Willy','Miranda']
links=[('Augustus', 'Willy'),
('Mike', 'Joe'),
('Miranda', 'Mike'),
('Violet', 'Augustus'),
('Miranda', 'Willy'),
('Charlie', 'Mike'),
('Veruca', 'Joe'),
('Miranda', 'Augustus'),
('Willy', 'Augustus'),
('Joe', 'Charlie'),
('Veruca', 'Augustus'),
('Miranda', 'Joe')]
def crosscount(v):
# Convert the number list into a dictionary of person:(x,y)
loc=dict([(people[i],(v[i*2],v[i*2+1])) for i in range(0,len(people))])
total=0
# Loop through every pair of links
for i in range(len(links)):
for j in range(i+1,len(links)):
# Get the locations
(x1,y1),(x2,y2)=loc[links[i][0]],loc[links[i][1]]
(x3,y3),(x4,y4)=loc[links[j][0]],loc[links[j][1]]
den=(y4-y3)*(x2-x1)-(x4-x3)*(y2-y1)
# den==0 if the lines are parallel
if den==0: continue
# Otherwise ua and ub are the fraction of the
# line where they cross
ua=((x4-x3)*(y1-y3)-(y4-y3)*(x1-x3))/den
ub=((x2-x1)*(y1-y3)-(y2-y1)*(x1-x3))/den
# If the fraction is between 0 and 1 for both lines
# then they cross each other
if ua>0 and ua<1 and ub>0 and ub<1:
total+=1
for i in range(len(people)):
for j in range(i+1,len(people)):
# Get the locations of the two nodes
(x1,y1),(x2,y2)=loc[people[i]],loc[people[j]]
# Find the distance between them
dist=math.sqrt(math.pow(x1-x2,2)+math.pow(y1-y2,2))
# Penalize any nodes closer than 50 pixels
if dist<50:
total+=(1.0-(dist/50.0))
return total
from PIL import Image,ImageDraw
def drawnetwork(sol):
# Create the image
img=Image.new('RGB',(400,400),(255,255,255))
draw=ImageDraw.Draw(img)
# Create the position dict
pos=dict([(people[i],(sol[i*2],sol[i*2+1])) for i in range(0,len(people))])
for (a,b) in links:
draw.line((pos[a],pos[b]),fill=(255,0,0))
for n,p in pos.items():
draw.text(p,n,(0,0,0))
img.show()
domain=[(10,370)]*(len(people)*2)
if __name__ == '__main__':
sol = optimization.randomoptimize(domain, crosscount)
print(crosscount(sol))
drawnetwork(sol)
sol = optimization.annealingoptimize(domain, crosscount, step=50, cool=0.99)
print(crosscount(sol))
drawnetwork(sol) | [
"moneyflying_2006@hotmail.com"
] | moneyflying_2006@hotmail.com |
0dd88cd62595a0835872c85d47978eb458305456 | d93fe0484fc3b32c8fd9b33cc66cfd636a148ec4 | /Codeforces/CR652/probA.py | debf34316a0b2927ad32e4478f6342ab6b7423ea | [] | no_license | wattaihei/ProgrammingContest | 0d34f42f60fa6693e04c933c978527ffaddceda7 | c26de8d42790651aaee56df0956e0b206d1cceb4 | refs/heads/master | 2023-04-22T19:43:43.394907 | 2021-05-02T13:05:21 | 2021-05-02T13:05:21 | 264,400,706 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 144 | py | import sys
input = sys.stdin.readline
N = int(input())
A = [int(input()) for _ in range(N)]
for a in A:
print("YES" if a%4 == 0 else "NO") | [
"wattaihei.rapyuta@gmail.com"
] | wattaihei.rapyuta@gmail.com |
bd5c2f9c364c233a451ea5e73f780f6a73e7d150 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_289/ch47_2020_04_13_16_11_41_596785.py | ed600699bbc1bbdec6acaf871750b1d295e073c7 | [] | 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 | 231 | py | def estritamente_crescente(lista):
nova_lista = [lista[0]]
maior = lista[0]
for e in lista:
if e > maior and e not in nova_lista:
nova_lista.append(e)
maior = e
return nova_lista
| [
"you@example.com"
] | you@example.com |
aa3a24c5e0dea92ac53430654e8adea747c318e3 | 8b3bc4efea5663b356acbabec231d1d647891805 | /322/Solution.py | 2f68bfca817a2e2e39a5c6bc6211dad85d0a8755 | [] | no_license | FawneLu/leetcode | 9a982b97122074d3a8488adec2039b67e709af08 | 03020fb9b721a1c345e32bbe04f9b2189bfc3ac7 | refs/heads/master | 2021-06-18T20:13:34.108057 | 2021-03-03T05:14:13 | 2021-03-03T05:14:13 | 177,454,524 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 979 | py | class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
coins.sort(reverse=True)
INVALID = 10**10
self.ans = INVALID
def dfs(s, amount, count):
if amount == 0:
self.ans = count
return
if s == len(coins): return
coin = coins[s]
for k in range(amount // coin, -1, -1):
if count + k >= self.ans: break
dfs(s + 1, amount - k * coin, count + k)
dfs(0, amount, 0)
return -1 if self.ans == INVALID else self.ans
def coinChange(self, coins: List[int], amount: int) -> int:
dp=[float('inf')]*(amount+1)
dp[0]=0
for coin in coins:
for i in range(coin,amount+1):
if dp[i-coin]!=float('inf'):
dp[i]=min(dp[i],dp[i-coin]+1)
return -1 if dp[amount]==float('inf') else dp[amount]
| [
"tracylu1996@gmail.com"
] | tracylu1996@gmail.com |
8ebdd9e65be3e8ea2c1fd1f030a8e54491034c69 | 115d568228ea4dd48bc567fac1afbe90a67e9a8c | /LSTM/SegWords/BI-LSTM/Demo2/2_word_count_df.py | 7c49cddcd85c9263054bcd3ea21cc3a8bf80e86d | [] | no_license | sunshinelu/NLPLearnNote | 6eb6b016ed18602be3a2fe8ce2f1bdb770efb226 | 76cfd64438e8acbf0aadc727675d7b17b63549e3 | refs/heads/master | 2020-03-08T07:03:25.652478 | 2018-05-06T14:13:02 | 2018-05-06T14:13:02 | 127,985,677 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,391 | py | #-*- coding: UTF-8 -*-
from pyspark.sql import SparkSession
from pyspark.sql.functions import split, explode
from pyspark.sql.functions import col,desc
import sys
reload(sys)
sys.setdefaultencoding('utf8')
"""
解决以下报错:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u4eca' in position 0: ordinal not in range(128)
"""
spark = SparkSession \
.builder \
.appName("word_count_df") \
.getOrCreate()
sc = spark.sparkContext
# inp1 = "/Users/sunlu/Workspaces/PyCharm/Github/NLPLearnNote/LSTM/SegWords/BI-LSTM/Demo2/results/pre_chars_for_w2v.txt"
# otp = "/Users/sunlu/Workspaces/PyCharm/Github/NLPLearnNote/LSTM/SegWords/BI-LSTM/Demo2/results/pre_vocab.txt"
inp1 = sys.argv[1]
otp = sys.argv[2]
text_rdd = sc.textFile(inp1).map(lambda x: (x, ))
def splitChar(x):
result = ""
for i in x:
result = result + " " + i
return result
df1 = text_rdd.toDF(["txt"])
df2 = df1.select("txt", explode(split(col("txt"), "\s+")).alias("word"))
# df2.show(5)
# word_count = df2.groupBy('word').count().sort(desc("count"))
word_count = df2.groupBy('word').count().orderBy(desc("count")).filter(col("count") >= 3)
# word_count.printSchema()
# word_count.show(5)
# word_count.coalesce(1).write.mode('overwrite') \
# .csv(otp ,sep=' ')
word_count.coalesce(1).toPandas().to_csv(otp,sep=' ',
index=False,header=False) | [
"sunlu900326@yeah.net"
] | sunlu900326@yeah.net |
c02ac0ab6a8528ce1992ce8f295f245f8b8ba50a | ef61c5f177ee44ac08325335fc28a12f3fccbb58 | /resource_management/tests/interactors/test_update_item_interactor.py | b78cf2fc4b15bec75d62de8d679d954cbc385126 | [] | no_license | bammidichandini/resource_management-chandini | 3c11c7b2eb5e2f8d3df5b55e4d3ee86a27ed5c3a | aa4ec50f0b36a818bebc2033cb39ee928e5be13c | refs/heads/master | 2022-12-01T19:59:25.366843 | 2020-07-23T09:10:42 | 2020-07-23T09:10:42 | 269,610,045 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,749 | py | import pytest
from unittest.mock import create_autospec
from resource_management.exceptions.exceptions import(
UserCannotManipulateException,
InvalidIdException
)
from resource_management.interactors.update_item_interactor import UpdateItemInteractor
from resource_management.interactors.storages.item_storages import StorageInterface
from resource_management.interactors.presenters.presenter_interface import PresenterInterface
@pytest.mark.django_db
def test_update_item(
item_dto
):
# arrange
item_id = 1
user_id = 1
expected_dto = item_dto
storage = create_autospec(StorageInterface)
presenter = create_autospec(PresenterInterface)
storage.check_for_valid_input.return_value = True
storage.is_admin.return_value = True
interactor = UpdateItemInteractor(
storage=storage,
presenter=presenter
)
# act
interactor.update_item_interactor(
user_id=user_id,
item_id=item_id,
item_dto=item_dto
)
# assert
storage.update_item.assert_called_once_with(
item_dto=expected_dto,
user_id=user_id,
item_id=item_id
)
storage.check_for_valid_input.assert_called_once_with([item_id])
storage.is_admin.assert_called_once_with(user_id)
@pytest.mark.django_db
def test_update_item_with_user_raises_execption(
item_dto
):
# arrange
item_id = 1
user_id = 1
storage = create_autospec(StorageInterface)
presenter = create_autospec(PresenterInterface)
storage.check_for_valid_input.return_value = True
storage.is_admin.return_value = False
presenter.raise_user_cannot_manipulate_exception.side_effect = \
UserCannotManipulateException
interactor = UpdateItemInteractor(
storage=storage,
presenter=presenter
)
# act
with pytest.raises(UserCannotManipulateException):
interactor.update_item_interactor(
user_id=user_id,
item_id=item_id,
item_dto=item_dto
)
@pytest.mark.parametrize("item_id", [
(1),(0)
])
def test_update_item_with_invalid_input(item_id, item_dto):
# arrange
user_id = 1
storage = create_autospec(StorageInterface)
presenter = create_autospec(PresenterInterface)
storage.check_for_valid_input.return_value = False
presenter.raise_invalid_id_exception.side_effect = \
InvalidIdException
interactor = UpdateItemInteractor(
storage=storage,
presenter=presenter
)
# act
with pytest.raises(InvalidIdException):
interactor.update_item_interactor(
user_id=user_id,
item_id=item_id,
item_dto=item_dto
)
| [
"chandini.bammidi123@gmail.com"
] | chandini.bammidi123@gmail.com |
a5cfaa079524e7fe88746e777eca50482b614083 | c81ea73e93df307d35191ab184a85d6c67c57112 | /dockers/data_conversion/pnet_data/Shapenet.py | 3de6a6cf016abd7290779f2f579b6d7050c5f9ee | [] | no_license | BlenderCN-Org/diplomka | 8d0503fc5902dfede8317aed84f5a17f691f687f | 575fe3f2436b9c511496c1dc019d9cc3423ba5f0 | refs/heads/master | 2020-05-22T15:42:00.143738 | 2019-05-07T07:37:46 | 2019-05-07T07:37:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,863 | py | from __future__ import print_function
import os
import json
import numpy as np
from mesh_files import find_files
'This code parses ShapeNet labels and categories'
decoding ={
0:'train',
1:'test'
}
def parse_shapenet_split(root_dir, categories):
files = find_files(root_dir,'obj')
split = {}
coding = {
'train':0,
'test':1,
}
counter = [0]*55
for file in files:
id = get_file_id(file)
cat = categories[id]
if counter[cat]%10 in [0,5]:
split[id] = 1
else:
split[id]=0
counter[cat]+=1
return split
def get_shapenet_labels(root_dir):
categories = {}
dirs = sorted([f for f in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir,f))])
for i, dir in enumerate(dirs):
directory = os.path.join(root_dir, dir)
ids = os.listdir(directory)
for id in ids:
if id not in categories:
categories[id] = i
return categories
def get_cat_names(root_dir, return_dirnames=False):
jsonfile = os.path.join(root_dir, 'taxonomy.json')
cat_names = []
dirs = sorted([f for f in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir,f))])
with open(jsonfile) as f:
data = json.load(f)
for dir in dirs:
for dato in data:
if dato['synsetId'] == dir:
cat_names.append(dato['name'].split(',')[0])
cat_names = [name.replace(' ', '_') for name in cat_names]
if not return_dirnames:
return cat_names
else:
return cat_names, dirs
def write_cat_names(root_dir, dest):
with open(os.path.join(dest, "cat_names.txt"), 'w') as f:
categories = get_cat_names(root_dir)
for cat in categories:
print(cat, file=f)
def get_metadata(shapenet_root_dir):
categories = get_shapenet_labels(shapenet_root_dir)
split = parse_shapenet_split(shapenet_root_dir, categories)
cat_names = get_cat_names(shapenet_root_dir)
return categories, split, cat_names
def get_file_id(file):
return file.split(os.sep)[-3]
def get_files_list(root_dir, categories):
files = find_files(root_dir, 'obj')
_, dirnames = get_cat_names(root_dir, return_dirnames=True)
newfiles = []
for file in files:
id = get_file_id(file)
cat = categories[id]
if file.split(os.sep)[-4] == dirnames[cat]:
newfiles.append(file)
return newfiles
if __name__ == "__main__":
categories, split, _ = get_metadata('/dataset')
files = get_files_list('/dataset', categories)
cat_names, dirnames = get_cat_names('/dataset', return_dirnames=True)
total = 0
a = {0:0, 1:0,2:0}
for key in split.keys():
a[split[key]] +=1
total+=1
cat_count_train = {}
cat_count_test = {}
cat_counts = [cat_count_train, cat_count_test]
for cat in range(len(cat_names)):
for j in [0,1]:
cat_counts[j][cat] = 0
for file in files:
id = get_file_id(file)
cat_counts[split[id]][categories[id]]+=1
with open('/dataset/shapenetsummary.csv', 'w') as f:
print('Category & Train & Test \\\\', file=f)
for i,cat in enumerate(cat_names):
trct = cat_counts[0][i]
tect = cat_counts[1][i]
print("{} & {} & {} \\\\".format(cat.replace('_',' '),trct,tect), file=f)
print('Total & {} & {} \\\\'.format(len(files)-a[1], a[1]), file=f)
with open('/dataset/shapenetsplit.csv', 'w') as f:
print('ID,Dataset,Category,Category ID', file=f)
for file in files:
id = get_file_id(file)
cat = categories[id]
print('{},{},{},{}'.format(id,decoding[split[id]], cat, cat_names[cat]), file=f)
| [
"miroslavkrabec@seznam.cz"
] | miroslavkrabec@seznam.cz |
408b8626355562f2795d96b9ce273ef02aa365b1 | 3fda3ff2e9334433554b6cf923506f428d9e9366 | /hipeac/site/forms/awards.py | 16e47872ec5d38530177b302b9932822c1a607ad | [
"MIT"
] | permissive | CreativeOthman/hipeac | 12adb61099886a6719dfccfa5ce26fdec8951bf9 | 2ce98da17cac2c6a87ec88df1b7676db4c200607 | refs/heads/master | 2022-07-20T10:06:58.771811 | 2020-05-07T11:39:13 | 2020-05-07T11:44:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 464 | py | from django import forms
from hipeac.models import TechTransferApplication
class TechTransferApplicationForm(forms.ModelForm):
class Meta:
model = TechTransferApplication
readonly_fields = ("call", "applicant")
exclude = ("awarded", "team", "team_string", "awardee", "awarded_from", "awarded_to", "awarded_summary")
widgets = {
"call": forms.HiddenInput(),
"applicant": forms.HiddenInput(),
}
| [
"eneko.illarramendi@ugent.be"
] | eneko.illarramendi@ugent.be |
fb79a6ee183beebe732f64ed7cc82a6292d8a01d | da370ba0df9700519139e1da54f3e7f38e9b7f5f | /.nox/tests/lib/python3.7/site-packages/tensorflow_core/_api/v1/sets/__init__.py | 743c607aa45bf3d4e10c8a3e683345eedbce512b | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | antonevenepoel/open_spiel | 90e3c7c6611cf508f2872237412fd67cf6cd10e0 | f2f0c786410018675fc40e9a5b82c40814555fa8 | refs/heads/master | 2021-03-15T20:57:00.562672 | 2020-05-15T16:10:23 | 2020-05-15T16:10:23 | 246,877,171 | 0 | 0 | Apache-2.0 | 2020-03-12T16:07:42 | 2020-03-12T16:07:41 | null | UTF-8 | Python | false | false | 1,068 | py | # This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Tensorflow set operations.
"""
from __future__ import print_function as _print_function
import sys as _sys
from tensorflow.python.ops.sets_impl import set_difference
from tensorflow.python.ops.sets_impl import set_difference as difference
from tensorflow.python.ops.sets_impl import set_intersection
from tensorflow.python.ops.sets_impl import set_intersection as intersection
from tensorflow.python.ops.sets_impl import set_size
from tensorflow.python.ops.sets_impl import set_size as size
from tensorflow.python.ops.sets_impl import set_union
from tensorflow.python.ops.sets_impl import set_union as union
del _print_function
from tensorflow.python.util import module_wrapper as _module_wrapper
if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):
_sys.modules[__name__] = _module_wrapper.TFModuleWrapper(
_sys.modules[__name__], "sets", public_apis=None, deprecation=True,
has_lite=False)
| [
"36889203+antonevenepoel@users.noreply.github.com"
] | 36889203+antonevenepoel@users.noreply.github.com |
342875551c272bb827a74c6082a29ab92432c5d7 | c7b669b7352c9eee3d17f9e57b2fc0df0907f3eb | /Day05_ve/Day05_root/ex07/views.py | c1ec8a559ab9e1396ca7fbd71ce4113c022d09dd | [] | no_license | m1n-q/django-inside | 89da9514c7b4d6d2d883df720b317ce4ea536590 | 9b70915cd798285de096974f9eb271f338756250 | refs/heads/main | 2023-07-18T00:18:15.327135 | 2021-09-02T09:22:31 | 2021-09-02T09:22:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,077 | py | from django.db.models import fields
from django.forms.models import ModelChoiceField
from django.http.request import RawPostDataException
from django.shortcuts import get_object_or_404, render, redirect
from .models import Movies
from datetime import date
from .forms import TitleDropDownForm
data = [
{'epi_nb': 1, 'title': 'The Phantom Menace', 'director': 'George Lucas', 'producer': 'Rick McCallum', 'rel_date': date(1999, 5, 19)},
{'epi_nb': 2, 'title': 'Attack of the Clones', 'director': 'George Lucas', 'producer': 'Rick McCallum', 'rel_date': date(2002, 5, 16)},
{'epi_nb': 3, 'title': 'Revenge of the Sith', 'director': 'George Lucas', 'producer': 'Rick McCallum', 'rel_date': date(2005, 5, 19)},
{'epi_nb': 4, 'title': 'A New Hope', 'director': 'George Lucas', 'producer': 'Gary Kurtz, Rick McCallum', 'rel_date': date(1977, 5, 25)},
{'epi_nb': 5, 'title': 'The Empire Strikes Back', 'director': 'Irvin Kershner', 'producer': 'Gary Kurtz, Rick McCallum', 'rel_date': date(1980, 5, 17)},
{'epi_nb': 6, 'title': 'Return of the Jedi', 'director': 'Richard Marquand', 'producer': 'Howard G. Kazanjian, George Lucas, Rick McCallum', 'rel_date': date(1983, 5, 25)},
{'epi_nb': 7, 'title': 'The Force Awakens', 'director': 'J. J. Abrams', 'producer': 'Kathleen Kennedy, J. J. Abrams, Bryan Burk', 'rel_date': date(2015, 12, 11)},
]
def populate(request):
errors = []
for d in data:
try:
Movies.objects.create(
episode_nb=d['epi_nb'],
title=d['title'],
director=d['director'],
producer=d['producer'],
release_date=d['rel_date']
)
except Exception as e:
errors.append(str(e))
if not errors:
return render(request, 'ex07/populate.html')
else:
return render(request, 'ex07/populate.html', {'errors' : errors})
def display(request):
errors = []
movies = Movies.objects.all()
col_names = list(map(lambda x: str(x).split('.')[-1].capitalize(), Movies._meta.get_fields()))
if not movies:
return render(request, 'ex07/display.html', {'msg': 'No available data.'})
records = Movies.objects.values_list()
return render(request, 'ex07/display.html', {'records' : records, 'col_names': col_names})
def update(request):
msg = ''
if request.method == 'POST':
form = TitleDropDownForm(request.POST)
if form.is_valid():
#method 1
movie = form.cleaned_data['title']
movie.opening_crawl = form.cleaned_data['opening_crawl']
movie.save()
# if with objects.only(), it will updates opening_crawl properly, but not updated_time
# 1) movie.updated
# 2) movie.save(update_fields=['opening_crawl', 'updated'])
# 3) use all() instead. ( it is not displaying all columns. getting instance with all coulmns, and just displaying __str__ )
#method 2
# h = Movies.objects.get(pk=1)
# h.opening_crawl = 'HAND WRITTEN MESSAGE!'
# h.save()
return redirect(request.META.get('HTTP_REFERER'))
else:
form = TitleDropDownForm()
if not form.fields['title'].queryset:
msg = 'No data available.'
return render(request, 'ex07/update.html', context={'form' : form, 'msg' : msg})
| [
"m1n_q@naver.com"
] | m1n_q@naver.com |
fe0ae2d3435cf66c96aecfb98f33fbd610aa998e | cde307025a2f2cc7ffcd1d43ea4f75b23876450d | /tools/accuracy_checker/accuracy_checker/representation/pose_estimation_representation.py | f765dd8890d0c585666f7edaa9f65cc0cd8b75b6 | [
"Apache-2.0"
] | permissive | ni/dldt | 1767885f6bf26d9d13ce10d2de63c1ae38275066 | ed372319eca66a534e1dd6a521613b0caf187b26 | refs/heads/2018 | 2020-04-14T19:29:31.549152 | 2019-07-03T16:22:59 | 2019-07-03T16:22:59 | 164,059,518 | 1 | 2 | Apache-2.0 | 2019-07-03T16:50:11 | 2019-01-04T04:53:33 | C++ | UTF-8 | Python | false | false | 2,381 | py | """
Copyright (c) 2019 Intel Corporation
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 numpy as np
from .base_representation import BaseRepresentation
class PoseEstimationRepresentation(BaseRepresentation):
def __init__(self, identifier='', x_values=None, y_values=None, visibility=None, labels=None):
super().__init__(identifier)
self.x_values = x_values if np.size(x_values) > 0 else []
self.y_values = y_values if np.size(y_values) > 0 else []
self.visibility = visibility if np.size(visibility) > 0 else [2] * len(x_values)
self.labels = labels if labels is not None else np.array([1]*len(x_values))
@property
def areas(self):
areas = self.metadata.get('areas')
if areas:
return areas
x_mins = np.min(self.x_values, axis=1)
x_maxs = np.max(self.x_values, axis=1)
y_mins = np.min(self.y_values, axis=1)
y_maxs = np.max(self.y_values, axis=1)
return (x_maxs - x_mins) * (y_maxs - y_mins)
@property
def bboxes(self):
rects = self.metadata.get('rects')
if rects:
return rects
x_mins = np.min(self.x_values, axis=1)
x_maxs = np.max(self.x_values, axis=1)
y_mins = np.min(self.y_values, axis=1)
y_maxs = np.max(self.y_values, axis=1)
return [[x_min, y_min, x_max, y_max] for x_min, y_min, x_max, y_max in zip(x_mins, y_mins, x_maxs, y_maxs)]
@property
def size(self):
return len(self.x_values)
class PoseEstimationAnnotation(PoseEstimationRepresentation):
pass
class PoseEstimationPrediction(PoseEstimationRepresentation):
def __init__(self, identifier='', x_values=None, y_values=None, visibility=None, scores=None, labels=None):
super().__init__(identifier, x_values, y_values, visibility, labels)
self.scores = scores if scores.any() else []
| [
"alexey.suhov@intel.com"
] | alexey.suhov@intel.com |
de28751d2f05042aa725e0faa417fa0f648899e1 | 2e95ec08f5f4f40179a5c1b86d604e0016e44ed5 | /modules/lti/selenium-tests | cd29d0c03a5afa81924ace1dea4ebde8ec16d459 | [
"ECL-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-free-unknown"
] | permissive | mm-dict/opencast | 0468bb3fec4e6b6fdeb8c642b75878f268701326 | c801305574d91fa5127069ca97ce8d131630fc05 | refs/heads/develop | 2022-10-15T14:48:55.135860 | 2021-03-16T06:32:56 | 2021-03-16T15:35:38 | 174,101,587 | 0 | 1 | ECL-2.0 | 2021-04-09T14:03:59 | 2019-03-06T08:14:37 | Java | UTF-8 | Python | false | false | 4,357 | #!/usr/bin/env python3
import os
import signal
import subprocess
import sys
import urllib3
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
BASE_URL = 'http://127.0.0.1:7878'
proc = []
driver = None
def header(message):
print()
print('#' * 72)
message = '### ' + message + ' '
print(message + '#' * (72 - len(message)))
print('#' * 72)
print()
sys.stdout.flush()
def react_start():
header('Starting React App')
env = os.environ.copy()
env['BROWSER'] = 'none'
env['CI'] = 'true'
proc.append(subprocess.Popen(
['npm', 'run', 'start'],
stdout=subprocess.DEVNULL,
env=env))
# Wait for server
http = urllib3.PoolManager()
retries = urllib3.Retry(10, backoff_factor=0.2)
request = http.request('GET', 'http://127.0.0.1:3000/', retries=retries)
if request.status != 200:
raise Exception('Server not ready after wait')
def mock_proxy_start():
header('Starting Mock Proxy')
proc.append(subprocess.Popen(['npm', 'run', 'mock-proxy']))
# Wait for server
http = urllib3.PoolManager()
retries = urllib3.Retry(10, backoff_factor=0.2)
request = http.request('GET', 'http://127.0.0.1:7878/', retries=retries)
if request.status != 200:
raise Exception('Server not ready after wait')
def navigate(path):
driver.get(f'{BASE_URL}{path}')
def wait_for(driver, element, timeout=20):
WebDriverWait(driver, timeout).until(
expected_conditions.presence_of_element_located(element))
def check_overview_page():
header('Testing Overview Page')
navigate('/ltitools')
elem = driver.find_element(By.TAG_NAME, 'h1')
assert 'Welcome to the LTI Module' == elem.text
def check_series_tool(edit=False, deletion=False):
header('Testing Series Tools')
n_opts = int(edit) + int(deletion)
edit = str(edit).lower()
deletion = str(deletion).lower()
params = '&'.join(['subtool=series',
f'edit={edit}',
f'deletion={deletion}'])
navigate(f'/ltitools/index.html?{params}')
wait_for(driver, (By.TAG_NAME, 'header'))
# Check for results in series
elem = driver.find_element(By.TAG_NAME, 'header')
assert elem.text.startswith('Results 1-')
# Get first result
elem = driver.find_elements(By.CSS_SELECTOR, '.list-group-item')[0]
# Assert number of modification options
assert len(elem.find_elements(By.TAG_NAME, 'button')) == n_opts
# test player link
elem.click()
assert driver.current_url.startswith(f'{BASE_URL}/play/')
def check_upload_tool(edit=False, deletion=False):
header('Testing Upload Tools')
navigate('/ltitools/index.html?subtool=upload&series=')
wait_for(driver, (By.TAG_NAME, 'form'))
# Check that header is present
elem = driver.find_element(By.TAG_NAME, 'h2')
assert elem.text.startswith('Upload new event')
# Click upload with no fields filled out should not yield success message
elem = driver.find_element(By.CSS_SELECTOR, '.btn-primary')
elem.click()
try:
wait_for(driver, (By.CSS_SELECTOR, '.alert-success'), timeout=0.2)
assert False
except TimeoutException:
pass
def check_i18next():
header('Testing Internationalization')
# Probe German translation of the series tool
navigate(f'/ltitools/index.html?subtool=series&lng=de')
wait_for(driver, (By.TAG_NAME, 'header'))
# Check for a translated results header
elem = driver.find_element(By.TAG_NAME, 'header')
assert not elem.text.startswith('Results')
def main():
os.setpgrp()
try:
react_start()
mock_proxy_start()
check_overview_page()
check_series_tool()
check_series_tool(True, True)
check_upload_tool()
check_i18next()
driver.close()
finally:
try:
os.killpg(0, signal.SIGINT)
except KeyboardInterrupt:
pass
if __name__ == '__main__':
options = webdriver.FirefoxOptions()
if sys.argv[-1] != 'gui':
options.headless = True
driver = webdriver.Firefox(options=options)
main()
| [
"lkiesow@uos.de"
] | lkiesow@uos.de | |
e0b07b096a8f81cfadbd0e342ca94935854a83fc | a9749d2b43d0944d6c6dd9f492f9475124f7bda7 | /trip_project/asgi.py | 22675b093af83f79582c9d652e2407e9edd68db1 | [] | no_license | TechAcademyBootcamp/docker_group_trip_project_final | a1f3383eaa0c11cd667cb42b4069d79c27f0aa42 | 87b1c54db0c32ca8ffebfee79c96e8082d93a535 | refs/heads/master | 2022-12-23T21:13:28.030443 | 2020-08-15T13:58:11 | 2020-08-15T13:58:11 | 287,755,974 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 401 | py | """
ASGI config for trip_project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trip_project.settings')
application = get_asgi_application()
| [
"idris.sabanli@gmail.com"
] | idris.sabanli@gmail.com |
f4eac25d9eb6e1ba63e56b8a4f54043cac6c958a | 4fafaff2891c461e671c2e9ff0bc907f34e51d11 | /mock_api_service/handlers/__init__.py | 4a877ddeaa0430aedad86e35572342cac62bf265 | [
"MIT"
] | permissive | stanwood/stanwood-services | 9273b219a35118a97c794c9ca973a7297606c0b9 | a9a3afcb10c94877b656bbf48994e74560ab0166 | refs/heads/develop | 2023-01-08T13:13:34.454190 | 2020-10-26T09:34:15 | 2020-10-26T09:34:15 | 161,368,050 | 0 | 1 | MIT | 2022-12-26T20:15:52 | 2018-12-11T17:13:27 | Python | UTF-8 | Python | false | false | 1,118 | py | # The MIT License (MIT)
#
# Copyright (c) 2018 stanwood GmbH
#
# 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.
| [
"rivinek@gmail.com"
] | rivinek@gmail.com |
95bfb9f7dce892bad23546b6fb36513757a6a38d | f2b27ea4b474916e5b7cf1f55901cf6e01b6ee3c | /01-intro-to-python-for-data-science/3-functions-and-packages/list-methods.py | 243d80f1176ef31a2a8580d9c3459f5a401d645e | [] | no_license | ariscon/DataCamp_Files | a21f1265b6ad5aed04d9724be78b08634f81312e | f7e496391b1d4649bf1186b9a1c9b83fa9a50044 | refs/heads/master | 2020-04-13T04:27:01.650215 | 2018-12-30T22:51:43 | 2018-12-30T22:51:43 | 162,962,035 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 924 | py | '''
List Methods
100xp
Strings are not the only Python types that have methods associated with them. Lists, floats,
integers and booleans are also types that come packaged with a bunch of useful methods.
In this exercise, you'll be experimenting with:
index(), to get the index of the first element of a list that matches its input and
count(), to get the number of times an element appears in a list.
You'll be working on the list with the area of different parts of a house: areas.
Instructions
-Use the index() method to get the index of the element in areas that is equal to 20.0.
Print out this index.
-Call count() on areas to find out how many times 14.5 appears in the list.
Again, simply print out this number.
'''
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Print out the index of the element 20.0
print(areas.index(20))
# Print out how often 14.5 appears in areas
print(areas.count(14.5))
| [
"noreply@github.com"
] | ariscon.noreply@github.com |
c5ed6cea9db1f13e21704c9ea75bd3bebe1105ff | a29f151197c85dee8f05493a8fe697549391fef2 | /nr07_Petle/nr01_While.py | 61d6393a34af1e41a255071bbc3582da8c5f0994 | [] | no_license | sswietlik/helloPython | 18a9cd3bb6ab9276415cbb018c9153c99abcb2f0 | d207567e7d5eabd9d7eef8c72538453ca3382021 | refs/heads/master | 2022-11-26T20:15:07.723910 | 2020-08-11T06:44:34 | 2020-08-11T06:44:34 | 261,168,610 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 294 | py | i=1
imax=10
while i <= imax:
print(i,'I like Python')
i+=1 #inkrementacja - wzrost wartości
else:
print('Now i >= 10 which is equal =',i)
print()
i=10
imax=0
while i >= imax:
print(i,'I like Python')
i-=1 #inkrementacja - wzrost wartości
else:
print('Now i =' ,i+1) | [
"sswietlik@gmail.com"
] | sswietlik@gmail.com |
3f48c75a83478a6f2e6162e11a44c7b2a9991c01 | 3996539eae965e8e3cf9bd194123989741825525 | /HLTrigger/special/hltVertexFilter_cfi.py | 74d345e7c736901e41122b2d566898230cff8150 | [] | no_license | cms-sw/cmssw-cfipython | 01990ea8fcb97a57f0b0cc44a8bf5cde59af2d98 | 25ee4c810103c4a507ca1b949109399a23a524c5 | refs/heads/CMSSW_11_2_X | 2023-09-01T16:56:00.658845 | 2022-06-20T22:49:19 | 2022-06-20T22:49:19 | 136,184,115 | 1 | 0 | null | 2022-10-19T14:04:01 | 2018-06-05T13:47:28 | Python | UTF-8 | Python | false | false | 353 | py | import FWCore.ParameterSet.Config as cms
hltVertexFilter = cms.EDFilter('HLTVertexFilter',
saveTags = cms.bool(True),
inputTag = cms.InputTag('hltPixelVertices'),
minNDoF = cms.double(0),
maxChi2 = cms.double(99999),
maxD0 = cms.double(1),
maxZ = cms.double(15),
minVertices = cms.uint32(1),
mightGet = cms.optional.untracked.vstring
)
| [
"cmsbuild@cern.ch"
] | cmsbuild@cern.ch |
0f61cc2bf74a9daeaa372e8d895eb827b0f4c51e | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/arc014/B/3434820.py | c8a29309a421b7843eeff13968c4628e1bae89b7 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Python | false | false | 663 | py | a = int(input())
ar = []
for i in range(a):
if i == 0:
l = input()
ar.append(l)
elif i >= 1:
l = input()
if l not in ar:
g = ar[len(ar)-1]
if g[-1] == l[0]:
ar.append(l)
else:
if i % 2 == 0:
print("LOSE")
break
else:
print("WIN")
break
else:
if i % 2 == 0:
print("LOSE")
break
else:
print("WIN")
break
if len(ar) == a:
print("DRAW") | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
f980885c59295b07adddc72263a5ca45fc248bbe | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /HvsBiHLGcsv2ex3gv_21.py | 27f076a46baf1bbd6ad478da5f3e8c2f8b4326e8 | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 773 | py | """
Create a function that takes a string of four numbers. These numbers represent
two separate points on a graph known as the x-axis (horizontal axis) and
y-axis (vertical axis).
The order of coordinates in the string corresponds as follows:
"x1,y1,x2,y2"
Calculate the distance between x and y.
### Examples
shortestDistance("1,1,2,1") ➞ 1
shortestDistance("1,1,3,1") ➞ 2
shortestDistance("-5,1,3,1") ➞ 8
shortestDistance("-5,2,3,1") ➞ 8.06
### Notes
All floats fixed to two decimal places (e.g. 2.34).
"""
def shortestDistance(txt):
numbers=[int(a) for a in txt.split(',')]
x1,y1,x2,y2 = numbers
import math
substract=(x2-x1)**2+(y2-y1)**2
dist = math.sqrt(substract)
return round(dist,2)
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
e97d26837ddc6e4afcbc7be7eccfd64f2f8c2d0c | 8d35b8aa63f3cae4e885e3c081f41235d2a8f61f | /discord/ext/dl/extractor/ninecninemedia.py | c8f06a5a7fd6cea1dee09b2557b576836f491f9b | [
"MIT"
] | permissive | alexyy802/Texus | 1255f4e54c8d3cc067f0d30daff1cf24932ea0c9 | c282a836f43dfd588d89d5c13f432896aebb540f | refs/heads/master | 2023-09-05T06:14:36.217601 | 2021-11-21T03:39:55 | 2021-11-21T03:39:55 | 429,390,575 | 0 | 0 | MIT | 2021-11-19T09:22:22 | 2021-11-18T10:43:11 | Python | UTF-8 | Python | false | false | 4,166 | py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
float_or_none,
int_or_none,
parse_iso8601,
try_get,
)
class NineCNineMediaIE(InfoExtractor):
IE_NAME = "9c9media"
_GEO_COUNTRIES = ["CA"]
_VALID_URL = r"9c9media:(?P<destination_code>[^:]+):(?P<id>\d+)"
_API_BASE_TEMPLATE = (
"http://capi.9c9media.com/destinations/%s/platforms/desktop/contents/%s/"
)
def _real_extract(self, url):
destination_code, content_id = re.match(self._VALID_URL, url).groups()
api_base_url = self._API_BASE_TEMPLATE % (destination_code, content_id)
content = self._download_json(
api_base_url,
content_id,
query={
"$include": "[Media.Name,Season,ContentPackages.Duration,ContentPackages.Id]",
},
)
title = content["Name"]
content_package = content["ContentPackages"][0]
package_id = content_package["Id"]
content_package_url = api_base_url + "contentpackages/%s/" % package_id
content_package = self._download_json(
content_package_url,
content_id,
query={
"$include": "[HasClosedCaptions]",
},
)
if try_get(content_package, lambda x: x["Constraints"]["Security"]["Type"]):
raise ExtractorError("This video is DRM protected.", expected=True)
manifest_base_url = content_package_url + "manifest."
formats = []
formats.extend(
self._extract_m3u8_formats(
manifest_base_url + "m3u8",
content_id,
"mp4",
"m3u8_native",
m3u8_id="hls",
fatal=False,
)
)
formats.extend(
self._extract_f4m_formats(
manifest_base_url + "f4m", content_id, f4m_id="hds", fatal=False
)
)
formats.extend(
self._extract_mpd_formats(
manifest_base_url + "mpd", content_id, mpd_id="dash", fatal=False
)
)
self._sort_formats(formats)
thumbnails = []
for image in content.get("Images") or []:
image_url = image.get("Url")
if not image_url:
continue
thumbnails.append(
{
"url": image_url,
"width": int_or_none(image.get("Width")),
"height": int_or_none(image.get("Height")),
}
)
tags, categories = [], []
for source_name, container in (("Tags", tags), ("Genres", categories)):
for e in content.get(source_name, []):
e_name = e.get("Name")
if not e_name:
continue
container.append(e_name)
season = content.get("Season") or {}
info = {
"id": content_id,
"title": title,
"description": content.get("Desc") or content.get("ShortDesc"),
"timestamp": parse_iso8601(content.get("BroadcastDateTime")),
"episode_number": int_or_none(content.get("Episode")),
"season": season.get("Name"),
"season_number": int_or_none(season.get("Number")),
"season_id": season.get("Id"),
"series": try_get(content, lambda x: x["Media"]["Name"]),
"tags": tags,
"categories": categories,
"duration": float_or_none(content_package.get("Duration")),
"formats": formats,
"thumbnails": thumbnails,
}
if content_package.get("HasClosedCaptions"):
info["subtitles"] = {
"en": [
{
"url": manifest_base_url + "vtt",
"ext": "vtt",
},
{
"url": manifest_base_url + "srt",
"ext": "srt",
},
]
}
return info
| [
"noreply@github.com"
] | alexyy802.noreply@github.com |
847604bb1728cd019c9ac30a76e5dab1444ce6ef | b59e093876a78054bf58ae16fa245bace5d924a2 | /sumRootToLeaf.py | 440b0d5f8cad9967a05dff0de66b480592ffe0d9 | [] | no_license | NeilWangziyu/Leetcode_py | 539551585413e1eebd6e6175ba3105c6bc17e943 | 4105e18050b15fc0409c75353ad31be17187dd34 | refs/heads/master | 2020-04-08T03:50:05.904466 | 2019-10-15T07:13:49 | 2019-10-15T07:13:49 | 158,991,828 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 650 | py | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
res = 0
def sumRootToLeaf(self, root: TreeNode) -> int:
if not root:
return 0
def check(r, prev):
if not r.right and not r.left:
self.res += (int(prev+str(r.val),2) % (10**9+7))
else:
if r.left:
check(r.left, prev+str(r.val))
if r.right:
check(r.right, prev + str(r.val))
check(root, "")
return (self.res) % (10**9+7) | [
"17210720158@fudan.edu.cn"
] | 17210720158@fudan.edu.cn |
ca13ce134651146030ca7b810bd6fe3f400d0ae1 | a3c68eafdb433c981f2b90e86f895e4f121c69fb | /笔试/网易/工作.py | 9dc79be405079afd399903545e2bf08cd9880aba | [] | no_license | Cassiexyq/Program-Exercise | ccc236ea76ca99ddc6fe0c4c47edebc3d557cfad | e962cc3add047d61df275dd3e22a091018fd964a | refs/heads/master | 2020-04-25T20:27:33.561226 | 2019-09-22T15:29:35 | 2019-09-22T15:29:35 | 173,050,531 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,159 | py | # -*- coding: utf-8 -*-
# @Author: xyq
import sys
def getMoney(job, case):
i = 0
while i < len(job):
if case > job[i][0]:
i += 1
continue
elif case == job[i][0]:
return job[i][1]
else:
return job[i-1][1]
if __name__ == '__main__':
N,M = [int(x) for x in input().split()]
job = []
while len(job) != N:
line = input()
if line == '':
continue
job.append([int(x) for x in line.split()])
line = input()
if line == '':
line = input()
job.sort()
people = list(map(int, line.split()))
# 把能力小的报酬多的话,就把报酬多的给能力大的 更新报酬
for i in range(1, len(job)):
if job[i-1][1] > job[i][1]:
job[i][1] = job[i-1][1]
ability = [i[0] for i in job]
ans = []
import bisect
for i in people:
# 找到能力大一点的那个位置
idx = bisect.bisect_right(ability,i)-1
if idx == -1:
ans.append(0)
else:
ans.append(job[idx][1])
for i in range(len(ans)):
print(ans[i])
| [
"cassiexuan_yq@163.com"
] | cassiexuan_yq@163.com |
724e7be38da948b7fe7428b7b9f0f20b45bb9f5d | d2e78884d09ee848c23ebd99dc70f4d7764c3d90 | /backend/blog/api/permissions.py | 9decc103e805c5af6346567a54f1ea9ab6a92933 | [] | no_license | Shpilevskiy/portfoliosite | abac997106da2cbece1250d1fe185cf682a97993 | bb4d05ae1f98f320bba3a5e131ce636a20a0e0ee | refs/heads/master | 2021-01-21T17:37:54.552493 | 2017-04-17T18:33:38 | 2017-04-17T18:33:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 456 | py | from rest_framework import permissions
class IsAdminOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow admins to edit object.
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_staff
| [
"trikster1911@gmail.com"
] | trikster1911@gmail.com |
4db4cdc5e695e0ada4c49d733996f4064a86a7b3 | bcb36baf1b3d3eceffba383f72c2b5335cc7048d | /python_workout/b3-cohort/exercise-4/solution.py | c02170fda88ba6811a6d23f971fbbec8deb09ead | [] | no_license | paulghaddad/solve-it | 0aa1400cefab783f4ea757921811668fb2c9477c | e0f72be0fca82bc0378def5499f7158bafff975b | refs/heads/master | 2023-01-24T03:46:24.285793 | 2021-07-06T19:44:29 | 2021-07-06T19:44:29 | 200,406,482 | 2 | 0 | null | 2023-01-06T13:53:43 | 2019-08-03T18:07:53 | Python | UTF-8 | Python | false | false | 589 | py | import tarfile
from zipfile import ZipFile, ZIP_DEFLATED
def tar_to_zip(*tarfiles, zippath):
zipfile = zippath.joinpath("output.zip")
for archive in tarfiles:
with ZipFile(zipfile, "w", compression=ZIP_DEFLATED) as zf:
try:
with tarfile.open(archive, "r") as tf:
for info in tf:
tf.extract(info, path="/tmp/")
zf.write(f"/tmp/{info.name}", arcname=info.name)
except tarfile.ReadError as e:
print(f"There was an error reading the file {archive}")
| [
"paulh16@gmail.com"
] | paulh16@gmail.com |
4aacf51acfd14b4b0cc41be9d5cc638d9c5f0128 | a3c662a5eda4e269a8c81c99e229879b946a76f6 | /.venv/lib/python3.7/site-packages/pylint/test/functional/not_async_context_manager.py | 138d76dfa4ec88a2ab389f3a25e80e86c66ae726 | [
"MIT"
] | permissive | ahmadreza-smdi/ms-shop | 0c29da82c58b243507575672bbc94fb6e8068aeb | 65ba3f3061e2ac5c63115b08dadfe7d67f645fb6 | refs/heads/master | 2023-04-27T19:51:34.858182 | 2019-11-24T20:57:59 | 2019-11-24T20:57:59 | 223,616,552 | 6 | 2 | MIT | 2023-04-21T20:51:21 | 2019-11-23T16:09:03 | Python | UTF-8 | Python | false | false | 1,658 | py | """Test that an async context manager receives a proper object."""
# pylint: disable=missing-docstring, import-error, too-few-public-methods, useless-object-inheritance
import contextlib
from ala import Portocala
@contextlib.contextmanager
def ctx_manager():
yield
class ContextManager(object):
def __enter__(self):
pass
def __exit__(self, *args):
pass
class PartialAsyncContextManager(object):
def __aenter__(self):
pass
class SecondPartialAsyncContextManager(object):
def __aexit__(self, *args):
pass
class UnknownBases(Portocala):
def __aenter__(self):
pass
class AsyncManagerMixin(object):
pass
class GoodAsyncManager(object):
def __aenter__(self):
pass
def __aexit__(self, *args):
pass
class InheritExit(object):
def __aexit__(self, *args):
pass
class SecondGoodAsyncManager(InheritExit):
def __aenter__(self):
pass
async def bad_coro():
async with 42: # [not-async-context-manager]
pass
async with ctx_manager(): # [not-async-context-manager]
pass
async with ContextManager(): # [not-async-context-manager]
pass
async with PartialAsyncContextManager(): # [not-async-context-manager]
pass
async with SecondPartialAsyncContextManager(): # [not-async-context-manager]
pass
async def good_coro():
async with UnknownBases():
pass
async with AsyncManagerMixin():
pass
async with GoodAsyncManager():
pass
async with SecondGoodAsyncManager():
pass
| [
"ahmadreza.smdi@gmail.com"
] | ahmadreza.smdi@gmail.com |
590be27c21d2892fb35c2b992147bbbbeccbd885 | be61a9f30274514857ea34297719157f1e5b8447 | /fhir/resources/DSTU2/identifier.py | 0569f22163f3395c76497539207eadab38b101b8 | [
"BSD-3-Clause"
] | permissive | jwygoda/fhir.resources | ceff3a620100d2e875136b86d3e82816c0e60a33 | 5053565570d1ca992d9971d20db813c53fd350b9 | refs/heads/master | 2021-02-05T02:59:17.436485 | 2019-07-18T10:57:33 | 2019-07-18T10:57:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,304 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Identifier) on 2019-05-14.
# 2019, SMART Health IT.
from . import element
class Identifier(element.Element):
""" An identifier intended for computation.
A technical identifier - identifies some entity uniquely and unambiguously.
"""
resource_name = "Identifier"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.assigner = None
""" Organization that issued id (may be just text).
Type `FHIRReference` referencing `Organization` (represented as `dict` in JSON). """
self.period = None
""" Time period when id is/was valid for use.
Type `Period` (represented as `dict` in JSON). """
self.system = None
""" The namespace for the identifier.
Type `str`. """
self.type = None
""" Description of identifier.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.use = None
""" usual | official | temp | secondary (If known).
Type `str`. """
self.value = None
""" The value that is unique.
Type `str`. """
super(Identifier, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(Identifier, self).elementProperties()
js.extend([
("assigner", "assigner", fhirreference.FHIRReference, False, None, False),
("period", "period", period.Period, False, None, False),
("system", "system", str, False, None, False),
("type", "type", codeableconcept.CodeableConcept, False, None, False),
("use", "use", str, False, None, False),
("value", "value", str, False, None, False),
])
return js
from . import codeableconcept
from . import fhirreference
from . import period
| [
"connect2nazrul@gmail.com"
] | connect2nazrul@gmail.com |
76a759aab88a6908380d5ddba8206be9e95c1d2b | 57094f0d09fd3e74eeb511e94400c3ec97051ad3 | /Quax_dev_archive/quax_benchmarks/paper/partials/h2o/tz/write_integrals.py | cb72cc15ac722a6fcdd416892aa2dd4fba94485c | [] | no_license | adabbott/Research_Notes | cccba246e81065dc4a663703fe225fc1ebbf806b | 644394edff99dc6542e8ae6bd0ce8bcf158cff69 | refs/heads/master | 2023-05-12T20:26:58.938617 | 2021-06-02T17:15:35 | 2021-06-02T17:15:35 | 119,863,228 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 570 | py | import psi4
import psijax
from data import molecule, basis_name
print("Writing integrals up to order 6")
psijax.core.write_integrals(molecule, basis_name, order=1, address=(2,))
psijax.core.write_integrals(molecule, basis_name, order=2, address=(2,2))
psijax.core.write_integrals(molecule, basis_name, order=3, address=(2,2,2))
psijax.core.write_integrals(molecule, basis_name, order=4, address=(2,2,2,2))
psijax.core.write_integrals(molecule, basis_name, order=5, address=(2,2,2,2,2))
psijax.core.write_integrals(molecule, basis_name, order=6, address=(2,2,2,2,2,2))
| [
"adabbott@uga.edu"
] | adabbott@uga.edu |
4c415b3ec63d4a2165d9d5d4a3f3e35d64d661f0 | ffad717edc7ab2c25d5397d46e3fcd3975ec845f | /Python/pyesri/EXAMPLES/generator_expression.py | f9cda64b7ec2904db00cb9a075fe09d51c9e57ec | [] | no_license | shaunakv1/esri-developer-conference-2015-training | 2f74caea97aa6333aa38fb29183e12a802bd8f90 | 68b0a19aac0f9755202ef4354ad629ebd8fde6ba | refs/heads/master | 2021-01-01T20:35:48.543254 | 2015-03-09T22:13:14 | 2015-03-09T22:13:14 | 31,855,365 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 204 | py | #!/usr/bin/python
with open('../DATA/fruit.txt') as fh_fruit:
ufruits = ( fruit[:-1].upper() for fruit in fh_fruit )
print ufruits
print
for fruit in (ufruits):
print fruit
| [
"shaunakv1@gmail.com"
] | shaunakv1@gmail.com |
788b4fa8e1ec138c4849f8fa237343068b066d43 | e9676921804bf8be3bfff6b143122103a0d82ab4 | /DsAl/16.bst.py | 672ff282c71568f47b7704c66e878e59bd21d802 | [] | no_license | gaogep/LeetCode | b69d07a8bc24bc23df44a6a5b3b123111d6bbeb9 | 15e5ff53c91ba96425b87ecaac9aa2d6b6e34dfe | refs/heads/master | 2020-04-28T16:26:15.621875 | 2019-10-08T13:15:03 | 2019-10-08T13:15:03 | 175,410,726 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,227 | py | class bsTreeNote:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def insert(self, root, value):
if not root:
root = bsTreeNote(value)
elif value > root.value:
root.right = self.insert(root.right, value)
else:
root.left = self.insert(root.left, value)
return root
def findMin(self, root, value):
if root:
while root.left:
root = root.left
return root
def delNode(self, root, value):
if not root:
return
if value < root.value:
root.left = self.delNode(root.left, value)
elif value > root.value:
root.right = self.delNode(root.right, value)
else:
if root.left and root.right:
tmp = self.findMin(root.right)
root.value = tmp.value
root.right = self.delNode(root.right, tmp.value)
elif not (root.left and root.right):
root = None
elif root.left:
root = root.left
else:
root = root.right
return root
| [
"zpf1893@qq.com"
] | zpf1893@qq.com |
e4e1a7700a0795528096b3f22ebd6090b36b6e6e | c057efccbe72ee5b7bb9e3b67a3108a5ff7688c7 | /plugin.py | 96d9826b65a7d7652793e5136165399fe2e92afc | [
"Apache-2.0"
] | permissive | boundary/meter-plugin-http | ab21776d0fde1dcbbdb96a1b3a99a1a604d70f7f | 66f0d1419079de603eb5e85a05a612dcf06c5442 | refs/heads/master | 2021-01-20T22:19:36.738741 | 2016-08-16T16:04:19 | 2016-08-16T16:04:19 | 64,500,883 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,379 | py | # Copyright 2016 BMC Software, 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 meterplugin import Collector
from meterplugin import Plugin
from meterplugin import Measurement
from meterplugin import MeasurementSinkAPI
from random import randrange
from time import time, sleep
from soup import Soup
import logging
import sys
logger = logging.getLogger(__name__)
class HttpCollector(Collector):
def __init__(self, interval=1000, name=None, url=None, source=None):
"""
Initialize the HTTP collector
:param interval: How often in milli-seconds to generate a random number
:param name: Name of the collector (becomes the thread name)
:param url: Url to measure the load time
:param source: Label used for generated measurements
"""
super(HttpCollector, self).__init__(interval=interval, name=name)
self.url = url
self.source = source
# self.measurement_output = MeasurementSinkAPI()
def initialize(self):
"""
Initialize the collector
:return: None
"""
pass
def starting(self):
"""
Called when collector is starting
:return: None
"""
pass
def measure_page_load(self):
t0 = time()
delay = float(randrange(1000, 3000)) / 1000.0
sleep(delay)
t1 = time()
return round((t1 - t0) * 1000.0, 3)
def collect(self):
"""
:return:
"""
try:
logger.info("Measuring page load for: {0}".format(self.url))
soup = Soup(url=self.url)
value = soup.measure_load_time()
m = Measurement(metric='HTTP_PAGE_LOAD',
value=value,
source=self.source)
self.measurement_output.send(m)
except Exception as e:
logger.error(e)
class HttpPlugin(Plugin):
def __init__(self):
super(HttpPlugin, self).__init__()
def initialize(self):
"""
Initialize the plugin
:return: None
"""
pass
def starting(self):
"""
Plugin is starting
:return: None
"""
pass
def create_collector(self, item):
"""
Creates the collectors associated with this plugin
:param item: Parameters from the items array in param.json
:return: Derived class from Collector
"""
# Extract parameters from item
if 'interval' in item:
interval = item['interval']
else:
interval = 1000
if 'url' in item:
url = item['url']
if 'source' in item:
source = item['source']
name = source
else:
source = url
return HttpCollector(interval=interval, name=name, url=url, source=source)
| [
"davidg@boundary.com"
] | davidg@boundary.com |
7d32349da856638f0f57af78ab277cde0e918467 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/30/usersdata/107/10113/submittedfiles/atividade.py | 8a0431350d9add7a1c5d68147211722e5eff837a | [] | 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 | 171 | py | # -*- coding: utf-8 -*-
from __future__ import division
import math
s=0
n=input('digite o valor de n:')
j=n
for i in range(1,n+1,1):
s=(i/j)+s
j=j-1
print('%5.f') | [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
7318f71985e8da7fafb617ea385d4c47ab971427 | bccfab4d853f7417401a084be95de293e66ccd2a | /mySpider/spiders/Exhibition153.py | 1670a9699269b0a141b80620ef828bef1ab0c6dc | [] | no_license | CS1803-SE/The-First-Subsystem | a8af03ce04a9de72a6b78ece6411bac4c02ae170 | 4829ffd6a83133479c385d6afc3101339d279ed6 | refs/heads/main | 2023-05-06T02:32:08.751139 | 2021-05-24T06:09:37 | 2021-05-24T06:09:37 | 363,400,147 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,316 | py | #
from ..items import *
from ..str_filter import *
class Exhibition153(scrapy.Spider):
name = "Exhibition153"
allowed_domains = ['baike.baidu.com']
start_urls = ['https://baike.baidu.com/item/%E9%B8%A6%E7%89%87%E6%88%98%E4%BA%89%E5%8D%9A%E7%89%A9%E9%A6%86/1880085?fr=aladdin#4']
custom_settings = {
'ITEM_PIPELINES': {
'mySpider.pipelines.ExhibitionPipeLine': 302,
},
'DOWNLOADER_MIDDLEWARES': {
'mySpider.middlewares.DefaultMiddleware': 0,
},
}
def parse(self, response, **kwargs):
li_list = response.xpath(
"/html/body/div[3]/div[2]/div/div[1]")
print(len(li_list))
for li in li_list:
item = ExhibitionItem()
item["museumID"] = 153
item["museumName"] = "鸦片战争博物馆"
item["exhibitionImageLink"] ='https://baike.baidu.com'+str(li.xpath(
"./div[72]/div/a/@href").extract_first())
item["exhibitionName"] = StrFilter.filter_2(li.xpath("./div[72]/b").extract_first().replace('<b>','').replace('</b>',''))
item["exhibitionTime"] = "常设展览"
item['exhibitionIntroduction'] = StrFilter.filter_2(li.xpath("./div[72]/text()").extract_first())
print(item)
yield item
| [
"1300978939@qq.com"
] | 1300978939@qq.com |
fb0bed573dce05eb362447229f7062934674863c | fdbb74a95924e2677466614f6ab6e2bb13b2a95a | /third_party/python/Lib/idlelib/idle_test/test_autoexpand.py | e5f44c468713258c1f2d5ca893d3ace1055eb6ce | [
"Python-2.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-python-cwi",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-copyleft",
"ISC"
] | permissive | jart/cosmopolitan | fb11b5658939023977060a7c6c71a74093d9cb44 | 0d748ad58e1063dd1f8560f18a0c75293b9415b7 | refs/heads/master | 2023-09-06T09:17:29.303607 | 2023-09-02T03:49:13 | 2023-09-02T03:50:18 | 272,457,606 | 11,887 | 435 | ISC | 2023-09-14T17:47:58 | 2020-06-15T14:16:13 | C | UTF-8 | Python | false | false | 4,640 | py | "Test autoexpand, coverage 100%."
from idlelib.autoexpand import AutoExpand
import unittest
from test.support import requires
from tkinter import Text, Tk
class Dummy_Editwin:
# AutoExpand.__init__ only needs .text
def __init__(self, text):
self.text = text
class AutoExpandTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.tk = Tk()
cls.text = Text(cls.tk)
cls.auto_expand = AutoExpand(Dummy_Editwin(cls.text))
cls.auto_expand.bell = lambda: None
# If mock_tk.Text._decode understood indexes 'insert' with suffixed 'linestart',
# 'wordstart', and 'lineend', used by autoexpand, we could use the following
# to run these test on non-gui machines (but check bell).
## try:
## requires('gui')
## #raise ResourceDenied() # Uncomment to test mock.
## except ResourceDenied:
## from idlelib.idle_test.mock_tk import Text
## cls.text = Text()
## cls.text.bell = lambda: None
## else:
## from tkinter import Tk, Text
## cls.tk = Tk()
## cls.text = Text(cls.tk)
@classmethod
def tearDownClass(cls):
del cls.text, cls.auto_expand
if hasattr(cls, 'tk'):
cls.tk.destroy()
del cls.tk
def tearDown(self):
self.text.delete('1.0', 'end')
def test_get_prevword(self):
text = self.text
previous = self.auto_expand.getprevword
equal = self.assertEqual
equal(previous(), '')
text.insert('insert', 't')
equal(previous(), 't')
text.insert('insert', 'his')
equal(previous(), 'this')
text.insert('insert', ' ')
equal(previous(), '')
text.insert('insert', 'is')
equal(previous(), 'is')
text.insert('insert', '\nsample\nstring')
equal(previous(), 'string')
text.delete('3.0', 'insert')
equal(previous(), '')
text.delete('1.0', 'end')
equal(previous(), '')
def test_before_only(self):
previous = self.auto_expand.getprevword
expand = self.auto_expand.expand_word_event
equal = self.assertEqual
self.text.insert('insert', 'ab ac bx ad ab a')
equal(self.auto_expand.getwords(), ['ab', 'ad', 'ac', 'a'])
expand('event')
equal(previous(), 'ab')
expand('event')
equal(previous(), 'ad')
expand('event')
equal(previous(), 'ac')
expand('event')
equal(previous(), 'a')
def test_after_only(self):
# Also add punctuation 'noise' that should be ignored.
text = self.text
previous = self.auto_expand.getprevword
expand = self.auto_expand.expand_word_event
equal = self.assertEqual
text.insert('insert', 'a, [ab] ac: () bx"" cd ac= ad ya')
text.mark_set('insert', '1.1')
equal(self.auto_expand.getwords(), ['ab', 'ac', 'ad', 'a'])
expand('event')
equal(previous(), 'ab')
expand('event')
equal(previous(), 'ac')
expand('event')
equal(previous(), 'ad')
expand('event')
equal(previous(), 'a')
def test_both_before_after(self):
text = self.text
previous = self.auto_expand.getprevword
expand = self.auto_expand.expand_word_event
equal = self.assertEqual
text.insert('insert', 'ab xy yz\n')
text.insert('insert', 'a ac by ac')
text.mark_set('insert', '2.1')
equal(self.auto_expand.getwords(), ['ab', 'ac', 'a'])
expand('event')
equal(previous(), 'ab')
expand('event')
equal(previous(), 'ac')
expand('event')
equal(previous(), 'a')
def test_other_expand_cases(self):
text = self.text
expand = self.auto_expand.expand_word_event
equal = self.assertEqual
# no expansion candidate found
equal(self.auto_expand.getwords(), [])
equal(expand('event'), 'break')
text.insert('insert', 'bx cy dz a')
equal(self.auto_expand.getwords(), [])
# reset state by successfully expanding once
# move cursor to another position and expand again
text.insert('insert', 'ac xy a ac ad a')
text.mark_set('insert', '1.7')
expand('event')
initial_state = self.auto_expand.state
text.mark_set('insert', '1.end')
expand('event')
new_state = self.auto_expand.state
self.assertNotEqual(initial_state, new_state)
if __name__ == '__main__':
unittest.main(verbosity=2)
| [
"jtunney@gmail.com"
] | jtunney@gmail.com |
b31a41894de26ec451012f0dd4b0ebcb3a9c4ec2 | df670d224688e57a170dc3c8d1a800dfea84b578 | /src/utils/polynomial.py | 95fd3e4de67967dad13c975a01d7077e1fff2576 | [] | no_license | dtbinh/drake-mpc | fb6cc2de6f03eb9c04d310af3b6ea047193a31dd | 2a89ae9e7f1e0d4bb2aeed9a4b5623c72a23c7a4 | refs/heads/master | 2020-04-05T00:39:32.781556 | 2017-05-04T21:33:18 | 2017-05-04T21:33:18 | 156,405,244 | 1 | 0 | null | 2018-11-06T15:31:53 | 2018-11-06T15:31:52 | null | UTF-8 | Python | false | false | 709 | py | from __future__ import absolute_import, division, print_function
import unittest
class Polynomial(object):
def __init__(self, coeffs):
self.coeffs = coeffs
def __getitem__(self, idx):
return self.coeffs[idx]
def __call__(self, x):
return self.evaluate(x)
@property
def degree(self):
return len(self.coeffs) - 1
def evaluate(self, x):
y = self.coeffs[-1]
for i in range(self.degree - 1, -1, -1):
y = self[i] + x * y
return y
def derivative(self):
return Polynomial([i * self[i] for i in range(1, self.degree + 1)])
def map(self, function):
return Polynomial(map(function, self.coeffs))
| [
"robin.deits@gmail.com"
] | robin.deits@gmail.com |
8df4c6881e950531915aa37703150a414870c28d | 4c67693e0a256ff9e2fc37153f0b0ac0a39a7ec3 | /pywick/models/segmentation/mnas_linknets/resnext.py | 6885c978edbe4aa414db8bbb045e025fff3556bf | [
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | liuzhidemaomao/pywick | 666276fdb7a5ee8168fab3f7c234c0af03f0225c | c42ee9728b8f85decc5b46b090524623d12b0580 | refs/heads/master | 2023-04-30T09:40:51.329833 | 2021-05-17T15:46:51 | 2021-05-17T15:46:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,734 | py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from .resnext101_32x4d_features import resnext101_32x4d_features,resnext101_32x4d_features_blob
__all__ = ['ResNeXt101_32x4d', 'resnext101_32x4d']
pretrained_settings = {
'resnext101_32x4d': {
'imagenet': {
'url': 'http://data.lip6.fr/cadene/pretrainedmodels/resnext101_32x4d-29e315fa.pth',
'input_space': 'RGB',
'input_size': [3, 224, 224],
'input_range': [0, 1],
'mean': [0.485, 0.456, 0.406],
'std': [0.229, 0.224, 0.225],
'num_classes': 1000
}
},
'resnext101_64x4d': {
'imagenet': {
'url': 'http://data.lip6.fr/cadene/pretrainedmodels/resnext101_64x4d-e77a0586.pth',
'input_space': 'RGB',
'input_size': [3, 224, 224],
'input_range': [0, 1],
'mean': [0.485, 0.456, 0.406],
'std': [0.229, 0.224, 0.225],
'num_classes': 1000
}
}
}
class ResNeXt101_32x4d_blob(nn.Module):
def __init__(self, num_classes=1000):
super(ResNeXt101_32x4d_blob, self).__init__()
self.num_classes = num_classes
resnext = resnext101_32x4d_features_blob()
self.features = resnext.resnext101_32x4d_features
self.avg_pool = nn.AvgPool2d((7, 7), (1, 1))
self.last_linear = nn.Linear(2048, num_classes)
def logits(self, input):
x = self.avg_pool(input)
x = x.view(x.size(0), -1)
x = self.last_linear(x)
return x
def forward(self, input):
x = self.features(input)
x = self.logits(x)
return x
class ResNeXt101_32x4d(nn.Module):
def __init__(self, num_classes=1000):
super(ResNeXt101_32x4d, self).__init__()
self.num_classes = num_classes
resnext = resnext101_32x4d_features()
self.stem = resnext.resnext101_32x4d_stem
self.layer1 = resnext.resnext101_32x4d_layer1
self.layer2 = resnext.resnext101_32x4d_layer2
self.layer3 = resnext.resnext101_32x4d_layer3
self.layer4 = resnext.resnext101_32x4d_layer4
self.avg_pool = nn.AvgPool2d((7, 7), (1, 1))
self.last_linear = nn.Linear(2048, num_classes)
def logits(self, input):
x = self.avg_pool(input)
x = x.view(x.size(0), -1)
x = self.last_linear(x)
return x
def forward(self, input):
x = self.stem(input)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.logits(x)
return x
def resnext101_32x4d(num_classes=1000, pretrained='imagenet'):
model = ResNeXt101_32x4d(num_classes=num_classes)
model_blob = ResNeXt101_32x4d_blob(num_classes=num_classes)
if pretrained is not None:
settings = pretrained_settings['resnext101_32x4d'][pretrained]
assert num_classes == settings['num_classes'], \
"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
model_blob.load_state_dict(model_zoo.load_url(settings['url']))
model.stem = nn.Sequential(
model_blob.features[0],
model_blob.features[1],
model_blob.features[2],
model_blob.features[3],
)
model.layer1 = nn.Sequential(
model_blob.features[4],
)
model.layer2 = nn.Sequential(
model_blob.features[5],
)
model.layer3 = nn.Sequential(
model_blob.features[6],
)
model.layer4 = nn.Sequential(
model_blob.features[7],
)
# finish here
model.input_space = settings['input_space']
model.input_size = settings['input_size']
model.input_range = settings['input_range']
model.mean = settings['mean']
model.std = settings['std']
return model
# def resnext101_64x4d(num_classes=1000, pretrained='imagenet'):
# model = ResNeXt101_64x4d(num_classes=num_classes)
# if pretrained is not None:
# settings = pretrained_settings['resnext101_64x4d'][pretrained]
# assert num_classes == settings['num_classes'], \
# "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
# model.load_state_dict(model_zoo.load_url(settings['url']))
# model.input_space = settings['input_space']
# model.input_size = settings['input_size']
# model.input_range = settings['input_range']
# model.mean = settings['mean']
# model.std = settings['std']
# return model | [
"Alexei.Samoylov@digikey.com"
] | Alexei.Samoylov@digikey.com |
bb02ae2ce1559c18b22645a7e650a06a32c59e24 | ad4b5ffe1ef0195084e16af58af5d4fcbb84deeb | /kakocase/utils.py | 2691a0fff334051be53e07d62d7f41012c83948c | [] | no_license | arthemis24/Project2 | 53b7a4b356b8b25bca51cef255a51bfaecf456f9 | 1fba9693c255380f3782d16a4a28a1bd900b3c3c | refs/heads/master | 2020-05-22T16:53:53.791427 | 2019-05-04T13:11:16 | 2019-05-04T13:11:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,961 | py | # -*- coding: utf-8 -*-
from django.utils.translation import gettext as _
from ikwen.core.models import Application
from ikwen.core.models import ConsoleEventType
def get_cash_out_requested_message(member):
"""
Returns a tuple (mail subject, mail body, sms text) to send to
member upon generation of an invoice
@param invoice: Invoice object
"""
subject = _("Cash-out requested by %s" % member.full_name)
message = _("Dear %(member_name)s,<br><br>"
"This is a notice that an invoice has been generated on %(date_issued)s.<br><br>"
"<strong style='font-size: 1.2em'>Invoice #%(invoice_number)s</strong><br>"
"Amount: %(amount).2f %(currency)s<br>"
"Due Date: %(due_date)s<br><br>"
"<strong>Invoice items:</strong><br>"
"<span style='color: #111'>%(invoice_description)s</span><br><br>"
"Thank you for your business with "
"%(company_name)s." % {'member_name': member.first_name,
'company_name': config.company_name,
'invoice_number': invoice.number,
'amount': invoice.amount,
'currency': invoicing_config.currency,
'date_issued': invoice.date_issued.strftime('%B %d, %Y'),
'due_date': invoice.due_date.strftime('%B %d, %Y'),
'invoice_description': invoice.subscription.details})
return subject, message
def create_console_event_types():
app = Application.objects.get(slug='kakocase')
CASH_OUT_REQUEST_EVENT = 'CashOutRequestEvent'
PROVIDER_ADDED_PRODUCTS_EVENT = 'ProviderAddedProductsEvent'
PROVIDER_REMOVED_PRODUCT_EVENT = 'ProviderRemovedProductEvent'
PROVIDER_PUSHED_PRODUCT_EVENT = 'ProviderPushedProductEvent'
NEW_ORDER_EVENT = 'NewOrderEvent'
ORDER_SHIPPED_EVENT = 'OrderShippedEvent'
ORDER_PACKAGED_EVENT = 'OrderPackagedEvent' # Case of Pick up in store
INSUFFICIENT_STOCK_EVENT = 'InsufficientStockEvent'
LOW_STOCK_EVENT = 'LowStockEvent'
SOLD_OUT_EVENT = 'SoldOutEvent'
ConsoleEventType.objects.create(app=app, codename=CASH_OUT_REQUEST_EVENT, title="Member requested Cash-out",
target=ConsoleEventType.BUSINESS, renderer="kakocase.views.render_cash_out_request_event")
ConsoleEventType.objects.create(app=app, codename=ORDER_PACKAGED_EVENT, title="Your order is packaged and ready",
target=ConsoleEventType.BUSINESS, renderer="shopping.views.render_order_event")
ConsoleEventType.objects.create(app=app, codename=ORDER_SHIPPED_EVENT, title="Your order was shipped",
target=ConsoleEventType.BUSINESS, renderer="shopping.views.render_order_event")
| [
"rsihon@gmail.com"
] | rsihon@gmail.com |
bfb47756c26332000f75a76d85108bb4cd6c49d7 | 63b0fed007d152fe5e96640b844081c07ca20a11 | /Other/動的計画法/桁dp(3の数字が含まれる数の総数).py | f7bd4271ed471ce670e17b341bcb058f2568f23a | [] | no_license | Nikkuniku/AtcoderProgramming | 8ff54541c8e65d0c93ce42f3a98aec061adf2f05 | fbaf7b40084c52e35c803b6b03346f2a06fb5367 | refs/heads/master | 2023-08-21T10:20:43.520468 | 2023-08-12T09:53:07 | 2023-08-12T09:53:07 | 254,373,698 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 396 | py | n = int(input())
s = str(n)
m = len(s)
dp = [[[0]*2 for _ in range(2)] for _ in range(m+1)]
dp[0][0][0] = 1
for i in range(m):
D = int(s[i])
for smaller in range(2):
limit = 10 if smaller else D+1
for j in range(2):
for x in range(limit):
dp[i+1][smaller | (x < D)][j | (x == 3)] += dp[i][smaller][j]
print(dp)
print(dp[m][0][1]+dp[m][1][1])
| [
"ymdysk911@gmail.com"
] | ymdysk911@gmail.com |
83f7c470c383db4eaf3770e53a9e2d177438c9e3 | 10fdd652b0218d966caab09741418ecbbbe88551 | /Wall.py | 0e9fe2af50f1aea973b841e5250b5edf6834a449 | [] | no_license | flowmin/Autonomous-Car-Simulator | 1c6c260bf4f2dc50da121df2c69b5ebd1493f770 | 14cf75cd19c1cba948475a562fd089e31692bce0 | refs/heads/master | 2020-06-01T12:34:03.641636 | 2019-06-07T14:11:45 | 2019-06-07T14:11:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 636 | py | import pygame
import numpy as np
class WallSprite(pygame.sprite.Sprite):
hit = pygame.image.load('images/collision.png')
def __init__(self, position, width, height):
super(WallSprite, self).__init__()
black_wall = 255 * np.ones((width, height, 3))
self.normal = pygame.surfarray.make_surface(black_wall)
self.rect = pygame.Rect(self.normal.get_rect())
self.rect.center = position
def update(self, hit_list):
if self in hit_list: self.image = self.hit
else: self.image = self.normal
if __name__ == "__main__":
pygame.init()
w = WallSprite((10,2), 1, 1) | [
"x2ever@naver.com"
] | x2ever@naver.com |
417d384633a90741c5cb812eafb4fa8dec8a1489 | 3da7f8a1fae54b4aa6f081e049e03ce28c0d7381 | /app/blue_print/route_comment.py | 83c8f3c68160be7be8295366fac94f83f0ef2a9c | [] | no_license | 1751605606/PersonalBlog | 96259196848418be5344520dda4b94b28f4d85e0 | 29b364897075e0ea6ce358ce0041b5ce29262e32 | refs/heads/master | 2022-09-28T11:05:54.016739 | 2019-12-17T13:19:15 | 2019-12-17T13:19:15 | 222,211,569 | 1 | 0 | null | 2022-09-16T18:13:09 | 2019-11-17T07:17:04 | Python | UTF-8 | Python | false | false | 5,539 | py | # 导入蓝本 blue_print
from . import blue_print
from . import errors
from flask import *
import json
import time
from app.models import *
from app import db
from . import utils
"""
评论文章
请求URL:/api/article/{article_id}/comment
请求方式:POST
参数:
参数名 必选 类型 说明
text 是 string 评论文本
"""
@blue_print.route('/api/article/<article_id>/comment', methods=['POST'])
def comment_article(article_id):
if request.method == 'POST':
# 验证登录状态
token = request.headers.get("Authorization")
is_token_valid = utils.certify_token(token) & utils.certify_user_in_Redis(token)
if is_token_valid is False:
return errors.not_logged_in()
# 评论文章
article = db.session.query(Article).filter_by(id=article_id).first()
if Article is None:
return {
"code": "400",
"error": {
"type": "Not Found",
"message": "The article " + article_id + " does not exist"
},
"data": {}
}
else:
json_data = json.loads(request.get_data())
user_id = utils.get_user_id_from_token(token)
timestamp = int(time.time())
text = json_data.get("text")
comment = Comment(None, int(article_id), user_id, text, timestamp)
comment.add_comment()
article.comment_number += 1
article.update_article()
return {
"code": "201",
"error": {},
}
"""
获取文章评论
请求URL:
/api/article/{article_id}/comment
/api/article/{article_id}/?index=INDEX&size=SIZE
请求方式:GET
参数:
参数名 必选 类型 说明
index 否 unsigned int 评论起始index,默认为0
size 否 unsigned int 要返回的评论最大数量,默认为最大
"""
@blue_print.route('/api/article/<article_id>/comment', methods=['GET'])
def get_comment_by_article(article_id):
if request.method == 'GET':
# 查询数据库返回文章的评论
index = 0 if request.args.get('index') is None else request.args.get('index')
size = request.args.get('size')
if size is not None:
comments = db.session.query(Comment).filter_by(article_id=article_id).offset(index).limit(size).all()
else:
comments = db.session.query(Comment).filter_by(article_id=article_id).offset(index).all()
response = {
'code': '200',
'error': {},
'data': {}
}
if comments is None:
# 若没有找到评论,查看是否因为文章不存在
article = db.session.query(Article).filter_by(id=article_id).first()
if article is None:
response = {
'code': '400',
'error': {
"type": "Not Found",
"message": "This article not found"
},
'data':{}
}
else:
comments_list = []
for comm in comments:
user = db.session.query(User).filter_by(id=comm.user_id).first()
comments_list.append(
{
'user_id': comm.user_id,
'username': user.username,
'text': comm.text,
'time': comm.timestamp
}
)
response = {
'code': '200',
'error': {},
'data': comments_list
}
return json.dumps(response)
"""
获取特定用户的所有评论
请求URL:
/api/user/{user_id}/comment
参数在URI中,是用户id
请求方式:GET
"""
@blue_print.route('/api/user/<user_id>/comment', methods=['GET'])
def get_comment_by_user(user_id):
if request.method == 'GET':
# 查询数据库返回用户的所有评论
comments = db.session.query(Comment).filter_by(user_id=user_id).all()
response = {
'code': '200',
'error': {},
'data': {}
}
if comments is None:
user = db.session.query(User).filter_by(id=user_id).first()
# 若没有找到评论,查看是否因为user不存在
if user is None:
response = {
'code': '400',
'error': {
"type": "Not Found",
"message": "This user not found"
},
'data': {}
}
else:
comments_list = []
for comm in comments:
article = db.session.query(Article).filter_by(id=comm.id).first()
if article is not None:
comments_list.append(
{
"article_id": article.id,
"article_title": article.title,
"text": comm.text,
"time": comm.timestamp
}
)
response = {
'code': '200',
'error': {},
'data': comments_list
}
return json.dumps(response) | [
"16302010030@fudan.edu.cn"
] | 16302010030@fudan.edu.cn |
97e1c8d782b936c10e607d601eee54b552d4133d | 7f523c407d45d116860eff67f079e807f2b53339 | /src/third_party/beaengine/tests/0f91.py | 96be8c460f023211152f96238b8b02b24aa2a6d8 | [
"MIT",
"LGPL-3.0-only",
"LGPL-2.0-or-later"
] | permissive | 0vercl0k/rp | a352c96bfe3715eb9ce8c5942831123e65289dac | b24e7f58a594aaf0ce3771745bf06862f6ecc074 | refs/heads/master | 2023-08-30T08:03:14.842828 | 2023-08-09T00:41:00 | 2023-08-09T00:41:00 | 3,554,173 | 1,557 | 239 | MIT | 2023-08-09T00:41:02 | 2012-02-26T19:26:33 | C++ | UTF-8 | Python | false | false | 3,215 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# @author : beaengine@gmail.com
from headers.BeaEnginePython import *
from nose.tools import *
class TestSuite:
def test(self):
# 0F 91
# REX + 0F 91
# SETNO r/m8
Buffer = bytes.fromhex('0f9100')
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x0f91)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'setno')
assert_equal(myDisasm.repr(), 'setno byte ptr [rax]')
Buffer = bytes.fromhex('0f91c0')
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(myDisasm.infos.Instruction.Opcode, 0x0f91)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'setno')
assert_equal(myDisasm.repr(), 'setno al')
# VEX.L0.0F.W0 91 /r
# KMOVW m16, k1
myVEX = VEX('VEX.L0.0F.W0')
myVEX.R = 1
Buffer = bytes.fromhex('{}9120'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x91')
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kmovw')
assert_equal(myDisasm.repr(), 'kmovw word ptr [r8], k4')
# VEX.L0.66.0F.W0 91 /r
# KMOVB m8, k1
myVEX = VEX('VEX.L0.66.0F.W0')
myVEX.R = 1
Buffer = bytes.fromhex('{}9120'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x91')
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kmovb')
assert_equal(myDisasm.repr(), 'kmovb byte ptr [r8], k4')
# VEX.L0.0F.W1 91 /r
# KMOVQ m64, k1
myVEX = VEX('VEX.L0.0F.W1')
myVEX.R = 1
Buffer = bytes.fromhex('{}9120'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x91')
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kmovq')
assert_equal(myDisasm.repr(), 'kmovq qword ptr [r8], k4')
# VEX.L0.66.0F.W1 91 /r
# KMOVD m32, k1
myVEX = VEX('VEX.L0.66.0F.W1')
myVEX.R = 1
Buffer = bytes.fromhex('{}9120'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x91')
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kmovd')
assert_equal(myDisasm.repr(), 'kmovd dword ptr [r8], k4')
| [
"noreply@github.com"
] | 0vercl0k.noreply@github.com |
68b714ec5e14493309bf92f0c6305be3afa2c4b1 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_hostage.py | 67f6c4d78fe02cafc10da3bfdeced8079067766b | [
"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 | 401 | py |
#calss header
class _HOSTAGE():
def __init__(self,):
self.name = "HOSTAGE"
self.definitions = [u'someone who is taken as a prisoner by an enemy in order to force the other people involved to do what the enemy wants: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
c6fdc7179fbc04c6e5d716acddca67959e76a10d | c79737296bdf4b3a969ab5ceb69198daf66def0e | /python/solutii/alexandru_antochi/fill.py | 6342ce5b1124553d4f2690c8b198795e86bd6c41 | [
"MIT"
] | permissive | ilieandrei98/labs | 96c749072b6455b34dc5f0bd3bb20f7a0e95b706 | cda09cbf5352e88909f51546c2eb360e1ff2bec1 | refs/heads/master | 2020-04-26T03:23:48.220151 | 2019-03-01T08:56:43 | 2019-03-01T08:56:43 | 173,265,757 | 0 | 0 | MIT | 2019-03-01T08:37:14 | 2019-03-01T08:37:14 | null | UTF-8 | Python | false | false | 2,827 | py | #!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""Tuxy dorește să împlementeze un nou paint pentru consolă.
În timpul dezvoltării proiectului s-a izbit de o problemă
pe care nu o poate rezolva singur și a apelat la ajutorul tău.
El dorește să adauge o unealtă care să permită umplerea unei
forme închise.
Exemplu:
Pornim de la imaginea inițială reprezentată mai jos, trebuie să
umplem formele în care se află "x":
|-----*------| |******------| |************|
|--x--*------| |******------| |************|
|******------| -----> |******------| -----> |************|
|-----******-| |-----******-| |-----*******|
|-----*---*--| |-----*---*--| |-----*---***|
|-----*---*-x| |-----*---*--| |-----*---***|
"""
from __future__ import print_function
def umple(imagine, punct):
"""Funcția primește reprezentarea imaginii și coordonatele unui
punct.
În cazul în care punctul se află într-o formă închisă trebuie să
umple forma respectivă cu caracterul "*"
"""
if imagine[punct[0]][punct[1]] == '*':
return
imagine[punct[0]][punct[1]] = '*'
if punct[1] < (len(imagine[0]) - 1):
umple(imagine, (punct[0], punct[1] + 1))
if punct[1] >= 1:
umple(imagine, (punct[0], punct[1] - 1))
if punct[0] < (len(imagine) - 1):
umple(imagine, (punct[0] + 1, punct[1]))
if punct[0] >= 1:
umple(imagine, (punct[0] - 1, punct[1]))
return imagine
def main():
"""Încercăm să rezolvăm problema fill."""
imaginea = [
["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"],
["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"],
["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"],
["*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "-"],
["-", "-", "-", "-", "-", "*", "-", "*", "-", "-", "*", "-"],
["-", "-", "-", "-", "-", "*", "-", "*", "-", "-", "*", "-"],
]
for i in range(0, len(imaginea)):
print(imaginea[i])
print("Filled")
umple(imaginea, (1, 3))
for i in range(0, len(imaginea)):
print(imaginea[i])
print('\n')
imaginea = [
["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"],
["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"],
["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"],
["*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "-"],
["-", "-", "-", "-", "-", "*", "-", "*", "-", "-", "*", "-"],
["-", "-", "-", "-", "-", "*", "-", "*", "-", "-", "*", "-"],
]
umple(imaginea, (5, 11))
for i in range(0, len(imaginea)):
print(imaginea[i])
if __name__ == "__main__":
main()
| [
"mmicu@cloudbasesolutions.com"
] | mmicu@cloudbasesolutions.com |
fec75141a74c5cd2e453737d37d33ec40263685c | 7ebbc52688d9cc960647dab197afb8753c300abc | /hardlinker/gstats.py | 8ee7fb8f3c884687e4976b3e643fa388de9d4955 | [] | no_license | ralphbean/hardlinker | 70f3949b27f64a84c0e9ea158f28f96325d6fcea | 8cd3e1270ba83bf97d1a9d42f50bd4d04d67b1fd | refs/heads/master | 2021-01-02T09:52:21.212395 | 2011-01-26T18:02:21 | 2011-01-26T18:02:21 | 1,295,964 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,068 | py |
import time
import stat
def humanize_number( number ):
if number > 1024 * 1024 * 1024:
return ("%.3f gibibytes" % (number / (1024.0 * 1024 * 1024)))
if number > 1024 * 1024:
return ("%.3f mibibytes" % (number / (1024.0 * 1024)))
if number > 1024:
return ("%.3f kibibytes" % (number / 1024.0))
return ("%d bytes" % number)
class cStatistics:
def __init__(self):
self.dircount = 0L # how many directories we find
self.regularfiles = 0L # how many regular files we find
self.comparisons = 0L # how many file content comparisons
self.hardlinked_thisrun = 0L # hardlinks done this run
self.hardlinked_previously = 0L; # hardlinks that are already existing
self.bytes_saved_thisrun = 0L # bytes saved by hardlinking this run
self.bytes_saved_previously = 0L # bytes saved by previous hardlinks
self.hardlinkstats = [] # list of files hardlinked this run
self.starttime = time.time() # track how long it takes
self.previouslyhardlinked = {} # list of files hardlinked previously
def foundDirectory(self):
self.dircount = self.dircount + 1
def foundRegularFile(self):
self.regularfiles = self.regularfiles + 1
def didComparison(self):
self.comparisons = self.comparisons + 1
def foundHardlink(self,sourcefile, destfile, stat_info):
filesize = stat_info[stat.ST_SIZE]
self.hardlinked_previously = self.hardlinked_previously + 1
self.bytes_saved_previously = self.bytes_saved_previously + filesize
if not self.previouslyhardlinked.has_key(sourcefile):
self.previouslyhardlinked[sourcefile] = (stat_info,[destfile])
else:
self.previouslyhardlinked[sourcefile][1].append(destfile)
def didHardlink(self,sourcefile,destfile,stat_info):
filesize = stat_info[stat.ST_SIZE]
self.hardlinked_thisrun = self.hardlinked_thisrun + 1
self.bytes_saved_thisrun = self.bytes_saved_thisrun + filesize
self.hardlinkstats.append((sourcefile, destfile))
def printStats(self, options):
print "\n"
print "Hard linking Statistics:"
# Print out the stats for the files we hardlinked, if any
if self.previouslyhardlinked and options.printprevious:
keys = self.previouslyhardlinked.keys()
keys.sort()
print "Files Previously Hardlinked:"
for key in keys:
stat_info, file_list = self.previouslyhardlinked[key]
size = stat_info[stat.ST_SIZE]
print "Hardlinked together: %s" % key
for filename in file_list:
print " : %s" % filename
print "Size per file: %s Total saved: %s" % (size,
size * len(file_list))
print
if self.hardlinkstats:
if options.dryrun:
print "Statistics reflect what would have happened if not a dry run"
print "Files Hardlinked this run:"
for (source,dest) in self.hardlinkstats:
print"Hardlinked: %s" % source
print" to: %s" % dest
print
print "Directories : %s" % self.dircount
print "Regular files : %s" % self.regularfiles
print "Comparisons : %s" % self.comparisons
print "Hardlinked this run : %s" % self.hardlinked_thisrun
print "Total hardlinks : %s" % (self.hardlinked_previously + self.hardlinked_thisrun)
print "Bytes saved this run : %s (%s)" % (self.bytes_saved_thisrun, humanize_number(self.bytes_saved_thisrun))
totalbytes = self.bytes_saved_thisrun + self.bytes_saved_previously;
print "Total bytes saved : %s (%s)" % (totalbytes, humanize_number(totalbytes))
print "Total run time : %s seconds" % (time.time() - self.starttime)
gStats = cStatistics()
| [
"ralph.bean@gmail.com"
] | ralph.bean@gmail.com |
5640f7d894827ab0e6136a2d3f95f3c8ae6068a0 | 108e3c5034e9aa2642a902e5e8d79b913b8af275 | /Tag_25.py | 0b3835778118f53470b80d2b574457c72fad9990 | [
"Apache-2.0"
] | permissive | Gravitar64/Advent-of-Code-2015 | 8d4e6fb267ddb80f055a70dd9ada19b92a0571f0 | 423ef65815ecd92dc15ae8edd64c2af346bf8fcc | refs/heads/main | 2023-02-17T00:29:20.666093 | 2021-01-20T14:04:32 | 2021-01-20T14:04:32 | 325,107,023 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 260 | py | from time import perf_counter as pfc
def solve(start, col, row):
for _ in range(sum(range(row + col -1)) + col - 1):
start = (start * 252533) % 33554393
return start
puzzle = (3029,2947)
start = pfc()
print(solve(20151125, *puzzle), pfc()-start)
| [
"gravitar@web.de"
] | gravitar@web.de |
178fe324646dd6c35fa2263db3e17f357e17e46f | b4af235b9dfe43b88dc61396bd2d73be2f2b2dd7 | /data_custom_backend/llib/encryption_utility/__init__.py | 73b28fbbfdb210aaf4c94e22fa254bdb8f4acd15 | [] | no_license | marjeylee/cmdb | 0b4c9b2f3a28de36582e11c21fc76bc601090a29 | ee41eb80d6b8823cfd764920ed8aa4c682d9a013 | refs/heads/master | 2023-02-08T02:03:05.462001 | 2021-01-03T10:25:38 | 2021-01-03T10:25:38 | 320,955,450 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 283 | py | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: __init__.py
Description :
Author : 'li'
date: 2020/10/10
-------------------------------------------------
Change Activity:
2020/10/10:
-------------------------------------------------
"""
| [
"marjey_lee@163.com"
] | marjey_lee@163.com |
31440922ef9878423f54a060a61a4a1836d90997 | 5a648d5c62e640a8df8d18549eaf6e84a36dbd28 | /Palindrome Pairs.py | 2141f924432fb6e6abf19d0ff14e3e5fecf0bd76 | [
"MIT"
] | permissive | quake0day/oj | f5f8576f765a76f0f3a8b2c559db06279e93ef25 | c09333d1738f8735de0d5d825db6f4b707585670 | refs/heads/master | 2021-01-21T04:27:34.035319 | 2016-03-30T02:19:15 | 2016-03-30T02:19:15 | 30,592,861 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 699 | py | class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
self.pair = []
def helper(i, words):
word = words[i]
for j in xrange(len(words)):
if j != i:
c = words[j][::-1]
if c[:len(word)] == word and c[len(word):] == c[len(word):][::-1]:
self.pair.append([i, j])
for i in xrange(len(words)):
helper(i, words)
return self.pair
a = Solution()
print a.palindromePairs(["abcd", "dcba", "lls", "s", "sssll"])
print a.palindromePairs(["bat", "tab", "cat"]) | [
"quake0day@gmail.com"
] | quake0day@gmail.com |
daf9eb5288647fd835992ada07c8d1d27776bcf3 | f569978afb27e72bf6a88438aa622b8c50cbc61b | /douyin_open/PoiProductProduct/models/spu_attributes1212_breakfast.py | ed2898d773c346559088e3e55cd46a1b4dd20a15 | [] | no_license | strangebank/swagger-petstore-perl | 4834409d6225b8a09b8195128d74a9b10ef1484a | 49dfc229e2e897cdb15cbf969121713162154f28 | refs/heads/master | 2023-01-05T10:21:33.518937 | 2020-11-05T04:33:16 | 2020-11-05T04:33:16 | 310,189,316 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,536 | py | # coding: utf-8
"""
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class SpuAttributes1212Breakfast(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 = {
'type': 'int',
'price': 'int'
}
attribute_map = {
'type': 'type',
'price': 'price'
}
def __init__(self, type=None, price=None): # noqa: E501
"""SpuAttributes1212Breakfast - a model defined in Swagger""" # noqa: E501
self._type = None
self._price = None
self.discriminator = None
self.type = type
self.price = price
@property
def type(self):
"""Gets the type of this SpuAttributes1212Breakfast. # noqa: E501
加早类型; 0 - 不支持加早; 1 - 早餐; 2 - 自助早餐 # noqa: E501
:return: The type of this SpuAttributes1212Breakfast. # noqa: E501
:rtype: int
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this SpuAttributes1212Breakfast.
加早类型; 0 - 不支持加早; 1 - 早餐; 2 - 自助早餐 # noqa: E501
:param type: The type of this SpuAttributes1212Breakfast. # noqa: E501
:type: int
"""
if type is None:
raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501
allowed_values = [0, 1, 2, ""] # noqa: E501
if type not in allowed_values:
raise ValueError(
"Invalid value for `type` ({0}), must be one of {1}" # noqa: E501
.format(type, allowed_values)
)
self._type = type
@property
def price(self):
"""Gets the price of this SpuAttributes1212Breakfast. # noqa: E501
加早费用/每人,单位人民币分 不支持加早填0 # noqa: E501
:return: The price of this SpuAttributes1212Breakfast. # noqa: E501
:rtype: int
"""
return self._price
@price.setter
def price(self, price):
"""Sets the price of this SpuAttributes1212Breakfast.
加早费用/每人,单位人民币分 不支持加早填0 # noqa: E501
:param price: The price of this SpuAttributes1212Breakfast. # noqa: E501
:type: int
"""
if price is None:
raise ValueError("Invalid value for `price`, must not be `None`") # noqa: E501
self._price = price
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(SpuAttributes1212Breakfast, 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, SpuAttributes1212Breakfast):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"strangebank@gmail.com"
] | strangebank@gmail.com |
adaedf4367df2691ef0bf7c4a75bc80638bc00e3 | 6e373b40393fb56be4437c37b9bfd218841333a8 | /Level_3/Lecture_11/enroll/views.py | 4b94d5059f8ec5c334813c0fb8634b076279cc03 | [] | no_license | mahto4you/Django-Framework | 6e56ac21fc76b6d0352f004a5969f9d4331defe4 | ee38453d9eceea93e2c5f3cb6895eb0dce24dc2b | refs/heads/master | 2023-01-22T01:39:21.734613 | 2020-12-04T03:01:17 | 2020-12-04T03:01:17 | 318,383,854 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 814 | py | from django.shortcuts import render
#from django.http import HttpResponseRedirect
from .forms import StudentRegistration
# Create your views here.
def thanks(request):
return render(request, 'enroll/success.html')
def showformdata(request):
if request.method == 'POST':
fm = StudentRegistration(request.POST)
if fm.is_valid():
name = fm.cleaned_data['name']
print('Clear Data', fm.cleaned_data['name'])
print('Clear Data', fm.cleaned_data['email'])
print('Clear Data', fm.cleaned_data['password'])
#return HttpResponseRedirect('/reg/success/')
return render(request, 'enroll/success.html', {'nm':name})
else:
fm = StudentRegistration()
return render(request, 'enroll/registration.html', {'form':fm})
| [
"mahto4you@gmail.com"
] | mahto4you@gmail.com |
82df7ecaa93dbebc557490d06923d421146c5441 | 7aa6d2e4a38aa537430b59ccb57cc3275a631e70 | /008-GUI/tk_gui.py | b93ee3c66ddef76c513af88055a38555eeefbc8d | [] | no_license | dcronkite/pytraining | d21c5064f98ef2afa64b0c9c6123416adb47cab1 | 46a427336b2621450d035c4e727bde0210937098 | refs/heads/master | 2018-11-04T22:03:33.061329 | 2018-08-26T23:34:22 | 2018-08-26T23:34:22 | 111,366,979 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,506 | py | import tkinter as tk
import os
class SearchApp:
def __init__(self, parent):
self.parent = parent
# path variable
self.path = tk.StringVar()
self.path_label = tk.StringVar()
self.path_label.set('Path')
self.label = tk.Label(parent, textvariable=self.path_label)
# self.label.pack(side=tk.LEFT)
self.entry = tk.Entry(parent, textvariable=self.path)
# self.entry.pack(side=tk.LEFT)
# extension variable
self.ext = tk.StringVar()
self.ext_label = tk.StringVar()
self.ext_label.set('Extension to Find')
self.label2 = tk.Label(parent, textvariable=self.ext_label)
# self.label2.pack()
self.entry2 = tk.Entry(parent, textvariable=self.ext)
# self.entry2.pack()
self.run_button_label = tk.StringVar()
self.run_button_label.set('Run')
self.button = tk.Button(parent, textvariable=self.run_button_label,
command=self.find_pptx_files)
# self.button.pack()
self.tk_text = tk.Text(parent)
# self.tk_text.pack()
self.label.grid(row=1, column=0)
self.label2.grid(row=2, column=0)
self.entry.grid(row=1, column=1, columnspan=3, sticky='ew')
self.entry2.grid(row=2, column=1, columnspan=3, sticky='ew')
self.button.grid(row=4, column=1)
self.tk_text.grid(row=5, column=0,
rowspan=6, columnspan=4)
def add_text(self):
self.tk_text.insert(tk.END, self.path.get() + '\n')
def find_pptx_files(self):
for curr_dir, dirs, files in os.walk(self.path.get()):
for file in files:
if file.endswith(self.ext.get()):
fp = os.path.join(curr_dir, file)
self.tk_text.insert(tk.END, fp + '\n')
def print_hi():
print('Hi!!')
if __name__ == '__main__':
window = tk.Tk()
# window.geometry('500x500')
window.title('Search Application')
SearchApp(window)
## this was our original application before
## moving it into the class
# name = tk.StringVar()
# up_button = tk.IntVar()
# label = tk.Label(window, textvariable=name)
# label.pack()
# entry = tk.Entry(window, textvariable=name)
# entry.pack()
# button = tk.Button(window, textvariable=name, command=print_hi)
# button.pack()
# text = tk.Text(window)
# text.insert(tk.END, 'hello')
# text.pack()
window.mainloop()
| [
"dcronkite@gmail.com"
] | dcronkite@gmail.com |
46fed765c04601a83ddf273604cf0d9f85fe6c53 | 27ba65fee880e1c1027aa997497736cc25960c10 | /pubnub/endpoints/history_delete.py | 2bbe8d8a76570343364a87fec96a3c40776dd97c | [
"MIT"
] | permissive | gonzalobf/python | 3ce0e2a187a27ecac67f974845bda549b2dfadb9 | defdfa85ad3a82a5ff99921db08843b185f44286 | refs/heads/master | 2020-04-28T15:50:42.220906 | 2018-09-27T08:17:36 | 2018-09-27T08:17:36 | 175,390,892 | 0 | 0 | null | 2019-03-13T09:43:03 | 2019-03-13T09:43:02 | null | UTF-8 | Python | false | false | 1,655 | py | from pubnub import utils
from pubnub.enums import HttpMethod, PNOperationType
from pubnub.endpoints.endpoint import Endpoint
class HistoryDelete(Endpoint): # pylint: disable=W0612
HISTORY_DELETE_PATH = "/v3/history/sub-key/%s/channel/%s"
def __init__(self, pubnub):
Endpoint.__init__(self, pubnub)
self._channel = None
self._start = None
self._end = None
def channel(self, channel):
self._channel = channel
return self
def start(self, start):
self._start = start
return self
def end(self, end):
self._end = end
return self
def custom_params(self):
params = {}
if self._start is not None:
params['start'] = str(self._start)
if self._end is not None:
params['end'] = str(self._end)
return params
def build_path(self):
return HistoryDelete.HISTORY_DELETE_PATH % (
self.pubnub.config.subscribe_key,
utils.url_encode(self._channel)
)
def http_method(self):
return HttpMethod.DELETE
def is_auth_required(self):
return True
def validate_params(self):
self.validate_subscribe_key()
self.validate_channel()
def create_response(self, endpoint):
return {}
def request_timeout(self):
return self.pubnub.config.non_subscribe_request_timeout
def connect_timeout(self):
return self.pubnub.config.connect_timeout
def operation_type(self):
return PNOperationType.PNHistoryDeleteOperation
def name(self):
return "History delete"
| [
"alexander@pubnub.com"
] | alexander@pubnub.com |
b65debed0ea8fa6c4f73201b75cbd32381dce2f2 | f9603ceb5b3bc5b5a22f395dd7281346dc09bd66 | /doing-math-with-python/temperature_trending.py | 11154d94325465dfc823dc96c6ae832a2b900115 | [
"MIT"
] | permissive | liulixiang1988/data-science-learning | 881ec9d479bcd4e1e8a7e4f0d243d469925c68aa | 298462fb1e6b2d4c1b2359d25d722118780bb758 | refs/heads/master | 2022-10-18T17:22:56.372435 | 2022-09-26T01:18:10 | 2022-09-26T01:18:10 | 51,692,336 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 664 | py | # -*- coding: utf-8 -*-
"""
Comparing the Monthly Temperature Trends of New York City.
"""
from pylab import legend, plot, show, title, xlabel, ylabel, savefig
months = range(1, 13)
nyc_temp_2000 = [31.3, 37.3, 47.2, 51.0, 63.5, 71.3, 72.3, 72.7, 66.0, 57.0, 45.3, 31.1]
nyc_temp_2006 = [40.9, 35.7, 43.1, 55.7, 63.1, 71.0, 77.9, 75.8, 66.6, 56.2, 51.9, 43.6]
nyc_temp_2012 = [37.3, 40.9, 50.9, 54.8, 65.1, 71.0, 78.8, 76.7, 68.8, 58.0, 43.9, 41.5]
plot(months, nyc_temp_2000, months, nyc_temp_2006, months, nyc_temp_2012)
title('Average monthly temperature in NYC')
xlabel('Months')
ylabel('Temperature')
legend([2000, 2006, 2012])
savefig('graphe.png')
show()
| [
"liulixiang1988@gmail.com"
] | liulixiang1988@gmail.com |
38f04c57520c530cbe8fe46c06cda7b714784c40 | b027502c2e35f7885a9f7cd79ed6e1e1b8485c2f | /Dynamic Programming/424.Longest Repeating Subsequence.py | 9e139b00bae208a7f873360f229a84e8f258fef4 | [] | no_license | DDR7707/Final-450-with-Python | eb1cd0ee890b64224e8996158d67f9820276d94a | b64717af405fe256bcd791a619cb9fb4ca9178cb | refs/heads/main | 2023-09-05T14:39:39.369036 | 2021-11-16T13:16:32 | 2021-11-16T13:16:32 | 403,002,363 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 490 | py | def solve(arr , n):
dp = [["" for i in range(n+1)] for i in range(n+1)]
for i in range(1,n+1):
for j in range(1,n+1):
if arr[i-1] == arr[j-1] and i != j:
dp[i][j] = dp[i-1][j-1] + str(arr[i-1])
else:
if len(dp[i-1][j]) > len(dp[i][j-1]):
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i][j-1]
return dp
arr = "axxxy"
n = len(arr)
print(solve(arr , n))
| [
"noreply@github.com"
] | DDR7707.noreply@github.com |
6fc9ce638afcbbb5c89f582625d37f7dc94eb5cf | 9dba277eeb0d5e9d2ac75e2e17ab5b5eda100612 | /exercises/1901100105/1001S02E05_string.py | 3bc5ad408f0f53da57c1c291f1da1501f05962c0 | [] | no_license | shen-huang/selfteaching-python-camp | e8410bfc06eca24ee2866c5d890fd063e9d4be89 | 459f90c9f09bd3a3df9e776fc64dfd64ac65f976 | refs/heads/master | 2022-05-02T05:39:08.932008 | 2022-03-17T07:56:30 | 2022-03-17T07:56:30 | 201,287,222 | 9 | 6 | null | 2019-08-08T15:34:26 | 2019-08-08T15:34:25 | null | UTF-8 | Python | false | false | 1,999 | py | sample_text = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambxiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are on honking great idea -- let's do more of those!
'''
#对象.方法(参数)
# 1. 将字符串样本里的 better 全部换成 worse
text = sample_text.replace('better', 'worse')
print('将字符串样本里的 better 全部替换成 worse ==>', text)
# 2. 将单词中包含ea的单词剔除
words = text.split() #通过空格对字符串进行切片
filtered = [] #用一个列表类型的变量存放过滤完的单词
for word in words: #进入循环语句
if word.find('ea') < 0:
filtered.append(word) #添加
print('将单词中包含ea的单词剔除 ==>', filtered)
# 3. 大小写翻转,大写转小写,小写转大写
swapcased = [i.swapcase() for i in filtered]
# 尝试修改语句成 filtereddd = str(filtered)
# swapcased = filtereddd.swapcase(), 运行成功,但因将文本分割成了字母,导致继续运行第4结果有误。须用split分隔再排序
print('进行大小写反转 ==>', swapcased)
#4.所有单词按a...z升序排列,并输出
print('单词按从a到z升序排列 ==>', sorted(swapcased)) #尝试修改,swapcaseed = swapcased.split(),运行成功
# print('降序排列', sorted(swapcased, reverse=true))
| [
"40155646+seven-tears@users.noreply.github.com"
] | 40155646+seven-tears@users.noreply.github.com |
92a20a113f53a824187834fee57bc2bdf75debd6 | bca5b38ed3fd86257a4f67c47929454abb7b973d | /articles/models.py | 7781279a6450bf8e40fd5edd549fed0ac713260b | [
"MIT"
] | permissive | mnosinov/myarticles | a63574c86e14481823be4fbe019bf0d980e32266 | 491a0a8cd0896db15f912422e82d6b3626fc21c3 | refs/heads/master | 2023-06-17T16:00:09.007797 | 2021-07-11T04:43:28 | 2021-07-11T04:43:28 | 325,610,985 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,039 | py | import datetime
from django.db import models
from django.utils import timezone
class Article(models.Model):
article_title = models.CharField('название статьи', max_length=200)
article_text = models.TextField('текст статьи')
pub_date = models.DateTimeField('дата публикации')
def __str__(self):
return self.article_title
def was_published_recently(self):
return self.pub_date >= (timezone.now() - datetime.timedelta(days=7))
class Meta:
verbose_name = 'Статья'
verbose_name_plural = 'Статьи'
class Comment(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
author_name = models.CharField('имя автора', max_length=50)
comment_text = models.CharField('текст комментария', max_length=200)
def __str__(self):
return self.author_name
class Meta:
verbose_name = 'Комментарий'
verbose_name_plural = 'Комментарии'
| [
"mnosinov@gmail.com"
] | mnosinov@gmail.com |
3127914dff44b786682fdae278b4de7f542936bb | cdb7bb6215cc2f362f2e93a040c7d8c5efe97fde | /H/HowManyNumbersAreSmallerThantheCurrentNumber.py | 489621f12bbac8b2f5013ac1ac723418a2e4284d | [] | no_license | bssrdf/pyleet | 8861bbac06dfe0f0f06f6ad1010d99f8def19b27 | 810575368ecffa97677bdb51744d1f716140bbb1 | refs/heads/master | 2023-08-20T05:44:30.130517 | 2023-08-19T21:54:34 | 2023-08-19T21:54:34 | 91,913,009 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,336 | py | '''
-Easy-
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it.
That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
'''
class Solution(object):
def smallerNumbersThanCurrent(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
count = [-1]*101
arr = sorted(nums)
for i,v in enumerate(arr):
if count[v] == -1:
count[v] = i
res = []
for i in nums:
res.append(count[i])
return res
if __name__ == "__main__":
print(Solution().smallerNumbersThanCurrent([8,1,2,2,3])) | [
"merlintiger@hotmail.com"
] | merlintiger@hotmail.com |
6c63a9e2056b4d35f2a5c4832a0d9104ab0171e3 | 1baf76e19a719ebb2207f2af2924fc53349d6a60 | /internship3_env/bin/stubtest | 4af2071cab1dcc685ef022e0c89155b1d1a4e800 | [
"MIT"
] | permissive | Zamy97/internship_3 | 4deb0df914e68930b23faa6bf7e0ca7fd342fbd8 | 9c9db252b6818316e9864839075bb1d23714f7e4 | refs/heads/master | 2023-01-01T15:33:45.980776 | 2020-10-28T02:47:34 | 2020-10-28T02:47:34 | 307,861,296 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 330 | #!/Users/zamy/Desktop/Python_Projects/excl_intrnship_projects/excl_internship_0/internship_3/internship_3/internship3_env/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from mypy.stubtest import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"aktarzaman@berkeley.edu"
] | aktarzaman@berkeley.edu | |
a550d8bfc2907d63a510c5691eb997a83278d4a2 | a59d55ecf9054d0750168d3ca9cc62a0f2b28b95 | /.install/.backup/lib/googlecloudsdk/gcloud/sdktools/auth/activate_service_account.py | 3a68cfc06ba70907a9849cbf38578bc627c075c3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | bopopescu/google-cloud-sdk | bb2746ff020c87271398196f21a646d9d8689348 | b34e6a18f1e89673508166acce816111c3421e4b | refs/heads/master | 2022-11-26T07:33:32.877033 | 2014-06-29T20:43:23 | 2014-06-29T20:43:23 | 282,306,367 | 0 | 0 | NOASSERTION | 2020-07-24T20:04:47 | 2020-07-24T20:04:46 | null | UTF-8 | Python | false | false | 3,582 | py | # Copyright 2013 Google Inc. All Rights Reserved.
"""A simple auth command to bootstrap authentication with oauth2."""
import getpass
import os
from oauth2client import client
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as c_exc
from googlecloudsdk.core import config
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.credentials import store as c_store
class ActivateServiceAccount(base.Command):
"""Get credentials via the private key for a service account.
Get credentials for a service account, using a .p12 file for the private key.
If --project is set, set the default project.
"""
@staticmethod
def Args(parser):
"""Set args for serviceauth."""
parser.add_argument('account', help='The email for the service account.')
parser.add_argument('--key-file',
help=('Path to the service accounts private key.'),
required=True)
parser.add_argument('--password-file',
help=('Path to a file containing the password for the '
'service account private key.'))
parser.add_argument('--prompt-for-password', action='store_true',
help=('Prompt for the password for the service account '
'private key.'))
def Run(self, args):
"""Create service account credentials."""
try:
private_key = open(args.key_file).read()
except IOError as e:
raise c_exc.BadFileException(e)
if args.password_file and args.prompt_for_password:
raise c_exc.InvalidArgumentException(
'Cannot use a password file and prompt for password at the same time.'
)
password = None
if args.password_file:
try:
password = open(args.password_file).read().strip()
except IOError as e:
raise c_exc.UnknownArgumentException(e)
if args.prompt_for_password:
password = getpass.getpass('Password: ')
if not client.HAS_CRYPTO:
if not os.environ.get('CLOUDSDK_PYTHON_SITEPACKAGES'):
raise c_exc.ToolException(
('PyOpenSSL is not available. If you have already installed '
'PyOpenSSL, you will need to enable site packages by '
'setting the environment variable CLOUDSDK_PYTHON_SITEPACKAGES to '
'1. If that does not work, See '
'https://developers.google.com/cloud/sdk/crypto for details.'))
else:
raise c_exc.ToolException(
('PyOpenSSL is not available. See '
'https://developers.google.com/cloud/sdk/crypto for details.'))
if password:
cred = client.SignedJwtAssertionCredentials(
service_account_name=args.account,
private_key=private_key,
scope=config.CLOUDSDK_SCOPES,
private_key_password=password,
user_agent=config.CLOUDSDK_USER_AGENT)
else:
cred = client.SignedJwtAssertionCredentials(
service_account_name=args.account,
private_key=private_key,
scope=config.CLOUDSDK_SCOPES,
user_agent=config.CLOUDSDK_USER_AGENT)
c_store.Store(cred, args.account)
properties.PersistProperty(properties.VALUES.core.account, args.account)
project = args.project
if project:
properties.PersistProperty(properties.VALUES.core.project, project)
return cred
def Display(self, args, result):
if result:
log.Print('Activated service account credentials for %s.' % args.account)
| [
"alfred.wechselberger@technologyhatchery.com"
] | alfred.wechselberger@technologyhatchery.com |
54763bc6a74f3be295892149bc32620155643671 | 5af4b89949a703bcc53bdc25a19a5ff079817cce | /papermerge/core/tasks.py | 4bca26b4fb1817757583f67f96c83700b9d85284 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | 0xpointer42/papermerge | 4b176a865ffa3044605844406fecd3ac5f3c5657 | 9bea16e96d460d00229e813f7063e45bfd07b4e2 | refs/heads/master | 2022-09-09T09:18:56.596921 | 2020-06-02T15:45:11 | 2020-06-02T15:45:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,359 | py | import logging
from celery import shared_task
from papermerge.core.ocr.page import ocr_page as main_ocr_page
from .models import Document, Folder, Page
logger = logging.getLogger(__name__)
@shared_task(bind=True)
def ocr_page(
self,
user_id,
document_id,
file_name,
page_num,
lang,
):
# A task being bound (bind=True) means the first argument
# to the task will always be the
# task instance (self).
# https://celery.readthedocs.io/en/latest/userguide/tasks.html#bound-tasks
logger.info(f"task_id={self.request.id}")
main_ocr_page(
user_id=user_id,
document_id=document_id,
file_name=file_name,
page_num=page_num,
lang=lang
)
return True
def norm_pages_from_doc(document):
logger.debug(f"Normalizing document {document.id}")
for page in Page.objects.filter(document=document):
page.norm()
def norm_pages_from_folder(folder):
for descendent in folder.get_descendants():
norm_pages_from_doc(descendent)
@shared_task
def normalize_pages(origin):
"""
Normalize Pages. The normalization was triggered model origin.
origin can be either a Folder or a Document
"""
if isinstance(origin, Document):
norm_pages_from_doc(origin)
elif isinstance(origin, Folder):
norm_pages_from_folder(origin)
| [
"eugen@django-lessons.com"
] | eugen@django-lessons.com |
cdc2a7f6a23a4895dfcb4eced43ce280b930a562 | fcbedcc2f7483a4b3ce9111c9c889bd4a5079496 | /client-side/xmlparsing1.py | a76da73da1ac0deaa993dd2df42f8f5895d959d6 | [] | no_license | kevlab/RealPython2 | aab94de91d0824290bfce4a318f57f4fe5282f19 | a85f92563b414830431a79d2448682da0c12d645 | refs/heads/master | 2021-01-10T19:10:46.035344 | 2015-05-27T02:24:48 | 2015-05-27T02:24:48 | 31,555,269 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 138 | py | from xml.etree import ElementTree as et
doc = et.parse("cars.xml")
print doc.find("CAR/MODEL").text
print doc.find("CAR[2]/MODEL").text
| [
"greenleaf1348@gmail.com"
] | greenleaf1348@gmail.com |
f7a505ab440fc2a1abcaf9046419cebb44cfd10a | c9508dad39497c492a8bbb5ea7b59216e057355d | /code/visualize/render_server.py | d74dfc4fde0061e1905a0a95ce9243a4156c437b | [
"MIT"
] | permissive | ZziTaiLeo/lets_face_it | 4acaafb5a140f500dcacd6cf9763d75bbed878f1 | fefba5e82d236f89703449bd517cfa5867fda09f | refs/heads/master | 2023-05-17T12:38:12.648823 | 2021-06-17T07:22:51 | 2021-06-17T07:22:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,941 | py | import gc
import io
import os
import subprocess
import tempfile
from pathlib import Path
from uuid import uuid4
import ffmpeg
import numpy as np
import torch
from fastapi import Body, FastAPI, Request
from fastapi.responses import StreamingResponse
try:
subprocess.check_call(
["python3", Path(__file__).parent / "test_egl.py"], stderr=subprocess.DEVNULL
)
os.environ["PYOPENGL_PLATFORM"] = "egl"
except subprocess.CalledProcessError:
print("Could not use EGL (GPU support), falling back on using CPU")
os.environ["PYOPENGL_PLATFORM"] = "osmesa"
from visualize.render_tools import get_vertices, render_double_face_video
app = FastAPI()
VIDEO_DIR = "videos"
def debyteify(x, key):
seqs = io.BytesIO()
seqs.write(x[key].encode("latin-1"))
seqs.seek(0)
return torch.from_numpy(np.load(seqs)).float()
def get_vert(seq):
return get_vertices(
debyteify(seq, "expression"),
debyteify(seq, "pose"),
debyteify(seq, "rotation"),
shape=debyteify(seq, "shape"),
)
@app.post("/render")
def read_root(request: Request, data=Body(...)):
file_name = VIDEO_DIR / Path(data.get("file_name", str(uuid4())))
fps = data["fps"]
left_vert = get_vert(data["seqs"][0])
right_vert = get_vert(data["seqs"][1])
with tempfile.NamedTemporaryFile(suffix=".mp4") as tmpf:
render_double_face_video(tmpf.name, left_vert, right_vert, fps=fps)
file_name.parent.mkdir(parents=True, exist_ok=True)
ffmpeg.input(tmpf.name).output(str(file_name), vcodec="h264").run(
overwrite_output=True
)
gc.collect()
url = f"http://{request.url.netloc}/video/{file_name}"
return {"url": url}
@app.get("/video/{path:path}")
def read_item(request: Request, path: str):
if not path.startswith(VIDEO_DIR):
path = VIDEO_DIR / Path(path)
return StreamingResponse(open(path, mode="rb"), media_type="video/mp4")
| [
"pjjonell@kth.se"
] | pjjonell@kth.se |
c3664d0fa77a72e3f65dbe20c18868e46767524e | 0d0624c7a29b6bcb0f0bc29be7a483689747fe13 | /app_files/__init__.py | d84087d3401bf4fab33a5d82f899bb0bd4494397 | [] | no_license | jodzi/flavor_fave | ceb2820725883a3a7f8d846879ee37955a8b7e5d | a4df3db96fba2ad5b6453885f551d55bfbe08812 | refs/heads/master | 2020-12-30T23:09:47.844988 | 2015-06-29T17:02:05 | 2015-06-29T17:02:05 | 37,070,299 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 161 | py | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 09:53:33 2015
@author: josephdziados
"""
from flask import Flask
app = Flask(__name__)
from app import views | [
"="
] | = |
8c3e3a34b398c535b54f0bcee53dfb699fb60a91 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_115/ch4_2020_03_09_13_05_19_379298.py | 1b92e628fc3abf661f8fe5e93c2d38a0be42a390 | [] | 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 | 281 | py | def classifica_idade(idade):
if (0<=idade<=11):
return('crianca')
elif (12<=idade<=17):
return('adolescente')
elif (idade<=18):
return('adulto')
elif (idade<0):
return('idade não válida')
idade = 6
print(classifica_idade(idade))
| [
"you@example.com"
] | you@example.com |
c699054f77afe0ff7ad3bd018dfa63a97b80081a | 8edd63a42469bf09fcad1c1070995ceda6e49646 | /env/lib/python2.7/site-packages/observations/r/nswdemo.py | 3eded652bd1a15becf9c27c03069f0ed595c733b | [] | no_license | silky/bell-ppls | fa0b5418f40dab59de48b7220ff30caba5945b56 | 369e7602c810b694a70ac1e875017480c8910ac8 | refs/heads/master | 2020-04-06T08:40:28.588492 | 2018-11-01T06:51:33 | 2018-11-01T06:51:33 | 157,312,221 | 1 | 0 | null | 2018-11-13T03:04:18 | 2018-11-13T03:04:18 | null | UTF-8 | Python | false | false | 2,359 | py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def nswdemo(path):
"""Labour Training Evaluation Data
The `nswdemo` data frame contains 722 rows and 10 columns. These data
are pertinent to an investigation of the way that earnings changed,
between 1974-1975 and 1978, for an experimental treatment who were given
job training as compared with a control group who did not receive such
training.
The `psid1` data set is an alternative non-experimental "control"
group. `psid2` and `psid3` are subsets of `psid1`, designed to be
better matched to the experimental data than `psid1`. Note also the
`cps1`, `cps2` and `cps3` datasets (DAAGxtras) that have been
proposed as non-experimental controls.
This data frame contains the following columns:
trt
a numeric vector identifying the study in which the subjects were
enrolled (0 = Control, 1 = treated).
age
age (in years).
educ
years of education.
black
(0 = not black, 1 = black).
hisp
(0 = not hispanic, 1 = hispanic).
marr
(0 = not married, 1 = married).
nodeg
(0 = completed high school, 1 = dropout).
re74
real earnings in 1974.
re75
real earnings in 1975.
re78
real earnings in 1978.
http://www.nber.org/~rdehejia/nswdata.html
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there.
Filename is `nswdemo.csv`.
Returns:
Tuple of np.ndarray `x_train` with 722 rows and 10 columns and
dictionary `metadata` of column headers (feature names).
"""
import pandas as pd
path = os.path.expanduser(path)
filename = 'nswdemo.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/DAAG/nswdemo.csv'
maybe_download_and_extract(path, url,
save_file_name='nswdemo.csv',
resume=False)
data = pd.read_csv(os.path.join(path, filename), index_col=0,
parse_dates=True)
x_train = data.values
metadata = {'columns': data.columns}
return x_train, metadata
| [
"akobeid.1@gmail.com"
] | akobeid.1@gmail.com |
b716bac172dc4c364620394fe603494029957813 | 6ed0503aa4a03acb8c992e2465ea54875d3c9a8f | /personable/api/version_0_0_1/controllers/auth_device.py | 23f1895b98948cd35853e3de36f86f7747e937c6 | [] | no_license | fstakem/personable | 51d59460e3249aa6ecd4b47101c16cdd71a9e6a5 | 4f2e30082c820c7c90c7dba402edee5646ea159a | refs/heads/master | 2021-01-22T08:27:46.378141 | 2017-06-14T02:13:29 | 2017-06-14T02:13:29 | 92,615,582 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 684 | py | # -----------------------------------------------------------------------------------------------
#
# Company: Personal Research
# By: Fredrick Stakem
# Created: 5.27.17
#
# -----------------------------------------------------------------------------------------------
# Libraries
from flask_restful import Resource
class AuthDevice(Resource):
def get(self, id):
return 'auth device get'
def put(self, id):
pass
def post(self, id):
pass
def delete(self, id):
pass
def update(self, id):
pass
class AuthDeviceList(Resource):
def get(self):
return 'auth devices get'
| [
"fstakem@gmail.com"
] | fstakem@gmail.com |
abcd0f045e5746cd8b287fced0740d2ea92f305d | 981fe4a1034f5ca8e03421d107314ef5b73236ea | /nova/rpc/dispatcher.py | 3f46398a979e337d1cf29e67f27d8f90cecc82ba | [
"Apache-2.0"
] | permissive | usc-isi/extra-specs | 5db3390a2193c43ae9206a76d5592cb67aebd191 | 4e5fee4a6830f337f02ca1ec1069285a68629979 | refs/heads/master | 2021-01-19T15:31:20.852091 | 2020-07-24T14:14:34 | 2020-07-24T14:14:34 | 4,393,412 | 0 | 1 | Apache-2.0 | 2020-07-24T14:14:36 | 2012-05-21T12:41:34 | Python | UTF-8 | Python | false | false | 3,931 | py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, 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.
"""
Code for rpc message dispatching.
Messages that come in have a version number associated with them. RPC API
version numbers are in the form:
Major.Minor
For a given message with version X.Y, the receiver must be marked as able to
handle messages of version A.B, where:
A = X
B >= Y
The Major version number would be incremented for an almost completely new API.
The Minor version number would be incremented for backwards compatible changes
to an existing API. A backwards compatible change could be something like
adding a new method, adding an argument to an existing method (but not
requiring it), or changing the type for an existing argument (but still
handling the old type as well).
The conversion over to a versioned API must be done on both the client side and
server side of the API at the same time. However, as the code stands today,
there can be both versioned and unversioned APIs implemented in the same code
base.
"""
from nova.rpc import common as rpc_common
class RpcDispatcher(object):
"""Dispatch rpc messages according to the requested API version.
This class can be used as the top level 'manager' for a service. It
contains a list of underlying managers that have an API_VERSION attribute.
"""
def __init__(self, callbacks):
"""Initialize the rpc dispatcher.
:param callbacks: List of proxy objects that are an instance
of a class with rpc methods exposed. Each proxy
object should have an RPC_API_VERSION attribute.
"""
self.callbacks = callbacks
super(RpcDispatcher, self).__init__()
@staticmethod
def _is_compatible(mversion, version):
"""Determine whether versions are compatible.
:param mversion: The API version implemented by a callback.
:param version: The API version requested by an incoming message.
"""
version_parts = version.split('.')
mversion_parts = mversion.split('.')
if int(version_parts[0]) != int(mversion_parts[0]): # Major
return False
if int(version_parts[1]) > int(mversion_parts[1]): # Minor
return False
return True
def dispatch(self, ctxt, version, method, **kwargs):
"""Dispatch a message based on a requested version.
:param ctxt: The request context
:param version: The requested API version from the incoming message
:param method: The method requested to be called by the incoming
message.
:param kwargs: A dict of keyword arguments to be passed to the method.
:returns: Whatever is returned by the underlying method that gets
called.
"""
if not version:
version = '1.0'
for proxyobj in self.callbacks:
if hasattr(proxyobj, 'RPC_API_VERSION'):
rpc_api_version = proxyobj.RPC_API_VERSION
else:
rpc_api_version = '1.0'
if not hasattr(proxyobj, method):
continue
if self._is_compatible(rpc_api_version, version):
return getattr(proxyobj, method)(ctxt, **kwargs)
raise rpc_common.UnsupportedRpcVersion(version=version)
| [
"rbryant@redhat.com"
] | rbryant@redhat.com |
2c6c0d8983d5a0008c2e85ea0a969d43248a2f72 | aeec8d49676ed90d90f833b2bf05749560093fa3 | /src/util/model_build/make_model/make_model_with_mix_adapter.py | e29a991981bf196048010f8eae171c2edcb6d271 | [] | no_license | zhengxxn/NMT | ce6b56f5441a490583e7d6602bf8207a4b580ff8 | 9206e5aa6535ef53460be7c25eeade60dbaed3d1 | refs/heads/master | 2023-01-06T01:25:21.579576 | 2020-11-04T03:19:37 | 2020-11-04T03:19:37 | 268,415,009 | 0 | 0 | null | 2020-11-04T03:19:38 | 2020-06-01T03:21:17 | Python | UTF-8 | Python | false | false | 6,222 | py | import torch.nn as nn
import copy
from module.embedding.embedding_with_positional_encoding import Embeddings
from module.encoder.transformer_encoder_with_adapter_synthesizer import \
TransformerEncoderLayerWithAdapter, \
TransformerEncoderWithAdapter
from module.decoder.transformer_decoder_with_adapter_synthesizer import \
TransformerDecoderLayerWithAdapter, \
TransformerDecoderWithAdapter
from module.generator.simple_generator import SimpleGenerator
from module.classifier.simple_classifier import SimpleClassifier
from module.classifier.cnn_classifier import CNNClassifier
from module.attention.multihead_attention import MultiHeadedAttention
from module.attention.multihead_attention_with_cache import MultiHeadedAttentionWithCache
from module.feedforward.positional_wise_feed_forward import PositionWiseFeedForward
from model.transformer_with_mix_adapter import TransformerWithMixAdapter
def make_transformer_with_mix_adapter(model_config, vocab):
attention = MultiHeadedAttention(
head_num=model_config['head_num'],
feature_size=model_config['feature_size'],
dropout=model_config['dropout_rate']
)
attention_with_cache = MultiHeadedAttentionWithCache(
head_num=model_config['head_num'],
feature_size=model_config['feature_size'],
dropout=model_config['dropout_rate']
)
feed_forward = PositionWiseFeedForward(
input_dim=model_config['feature_size'],
ff_dim=model_config['feedforward_dim'],
dropout=model_config['dropout_rate']
)
if model_config['classifier_type'] == 'simple':
classifier = SimpleClassifier(input_dim=model_config['feature_size'],
feature_size=model_config['classify_feature_size'],
class_num=model_config['domain_class_num'], )
elif model_config['classifier_type'] == 'cnn':
classifier = CNNClassifier(num_class=model_config['domain_class_num'],
input_dim=model_config['feature_size'],
kernel_nums=model_config['kernel_nums'],
kernel_sizes=model_config['kernel_sizes'],
dropout_rate=model_config['dropout_rate'])
else:
classifier = None
model = TransformerWithMixAdapter(
src_embedding_layer=Embeddings(
vocab_size=len(vocab['src']),
emb_size=model_config['feature_size'],
dropout=model_config['dropout_rate'],
max_len=5000
),
trg_embedding_layer=Embeddings(
vocab_size=len(vocab['trg']),
emb_size=model_config['feature_size'],
dropout=model_config['dropout_rate'],
max_len=5000
),
encoder=TransformerEncoderWithAdapter(
layer=TransformerEncoderLayerWithAdapter(feature_size=model_config['feature_size'],
self_attention_layer=copy.deepcopy(attention),
feed_forward_layer=copy.deepcopy(feed_forward),
domain_adapter_dict=model_config[
'domain_adapter_dict'],
dropout_rate=model_config['dropout_rate'],
max_domain_num=model_config['domain_class_num'],
adapter_setting=model_config['adapter_setting'],
domain_list=model_config['domain_list'],
domain_inner_gate_list=model_config['domain_inner_gate_list'],
),
feature_size=model_config['feature_size'],
num_layers=model_config['num_layers'],
),
decoder=TransformerDecoderWithAdapter(
layer=TransformerDecoderLayerWithAdapter(feature_size=model_config['feature_size'],
self_attention_layer=copy.deepcopy(
attention_with_cache),
cross_attention_layer=copy.deepcopy(
attention_with_cache),
feed_forward_layer=copy.deepcopy(feed_forward),
domain_adapter_dict=model_config[
'domain_adapter_dict'],
dropout_rate=model_config['dropout_rate'],
domain_list=model_config['domain_list'],
domain_inner_gate_list=model_config['domain_inner_gate_list'],
max_domain_num=model_config['domain_class_num'],
adapter_setting=model_config['adapter_setting'],),
num_layers=model_config['num_layers'],
feature_size=model_config['feature_size'],
),
generator=SimpleGenerator(feature_size=model_config['feature_size'],
vocab_size=len(vocab['trg']),
bias=model_config['generator_bias']),
emb_classifier=copy.deepcopy(classifier),
classify_domain_mask=model_config['classify_domain_mask'],
vocab=vocab,
share_decoder_embedding=model_config['share_decoder_embedding'],
share_enc_dec_embedding=model_config['share_enc_dec_embedding'],
)
for p in model.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
for name, param in model.named_parameters():
# if param.dim() > 1 and 'adapter' in name:
# nn.init.zeros_(param)
if 'memory_score_bias' in name:
nn.init.xavier_uniform_(param)
return model
| [
"zhengx9703@gmail.com"
] | zhengx9703@gmail.com |
8518444c652b2821fca23b6a5988f70ef323d732 | 07a14c4aff72e2d276238af6eb6f2e2eab9589ee | /solutions/0880-rectangle-area-ii/rectangle-area-ii.py | 60dec5ed6140a37545ffdb56b0ca31ad3013ce7b | [] | no_license | bongster/leetcode | 0284b016e9d2a0b2d99aee314ea6949210141131 | e85b96711eeddb7d29a454d06dc1c5bd71d1fa13 | refs/heads/master | 2022-09-25T18:04:52.767063 | 2022-09-04T15:24:28 | 2022-09-04T15:24:28 | 193,223,450 | 0 | 0 | null | 2019-06-22T10:53:56 | 2019-06-22T10:53:55 | null | UTF-8 | Python | false | false | 2,884 | py | # You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.
#
# Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.
#
# Return the total area. Since the answer may be too large, return it modulo 109 + 7.
#
#
# Example 1:
#
#
# Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
# Output: 6
# Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.
# From (1,1) to (2,2), the green and red rectangles overlap.
# From (1,0) to (2,3), all three rectangles overlap.
#
#
# Example 2:
#
#
# Input: rectangles = [[0,0,1000000000,1000000000]]
# Output: 49
# Explanation: The answer is 1018 modulo (109 + 7), which is 49.
#
#
#
# Constraints:
#
#
# 1 <= rectangles.length <= 200
# rectanges[i].length == 4
# 0 <= xi1, yi1, xi2, yi2 <= 109
#
#
class Solution:
def rectangleArea(self, rectangles: List[List[int]]) -> int:
# TODO: get timeLimit error
# MOD = 10 ** 9 + 7
# if len(rectangles) == 1:
# x1, y1, x2, y2 = rectangles[0]
# return ((x2 - x1) * (y2 - y1)) % MOD
# min_x = 10 * 9 + 1
# max_x = 0
# min_y = 10 * 9 + 1
# max_y = 0
# for rectangle in rectangles:
# x1, y1, x2, y2 = rectangle
# min_x = min(min_x, x1)
# max_x = max(max_x, x2)
# min_y = min(min_y, y1)
# max_y = max(max_y, y2)
# dp = [[0] * (max_y - min_y + 1) for _ in range(max_x - min_x + 1)]
# for x1, y1, x2, y2 in rectangles:
# # print(x1,y1, x2, y2)
# for i in range(x1, x2):
# for j in range(y1, y2):
# dp[i - min_x][j - min_y] = 1
# ans = 0
# for i in range(len(dp)):
# for j in range(dp[i]):
# if dp[i][j] == 1:
# ans += 1
# return ans % MOD
xs = sorted(set([x for x1, y1, x2, y2 in rectangles for x in [x1, x2]]))
ys = sorted(set([y for x1, y1, x2, y2 in rectangles for y in [y1, y2]]))
x_i = {v: i for i, v in enumerate(xs)}
y_i = {v: i for i, v in enumerate(ys)}
m, n = len(y_i), len(x_i)
grid = [[0] * m for _ in range(n)]
for x1, y1, x2, y2 in rectangles:
for x in range(x_i[x1], x_i[x2]):
for y in range(y_i[y1], y_i[y2]):
grid[x][y] = 1
ans = 0
for x in range(n-1):
for y in range(m-1):
if grid[x][y]:
ans += (xs[x+1] - xs[x]) * (ys[y+1] - ys[y])
return ans % (10**9 + 7)
| [
"bongster88@gmail.com"
] | bongster88@gmail.com |
cb9efbbacbd31fb292e41e7215348c0b66419bd6 | 7f3c0c7cb3987356171e91b2e888e2bfbe2f5077 | /group_discussion/migrations/0021_auto_20151102_1711.py | 9c3cd252587178fed5bb1c7f30a00fe4708f34ce | [] | no_license | jscott1989/newscircle | 7d329673ed58dd2309ac6182fae3452bd50a8d54 | 373eba2f9aaa747272092521581d78524585df55 | refs/heads/master | 2020-12-24T11:53:12.865783 | 2016-11-07T17:50:42 | 2016-11-07T17:50:42 | 73,105,242 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,197 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('group_discussion', '0020_auto_20151028_1939'),
]
operations = [
migrations.CreateModel(
name='Dislike',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('time_voted', models.DateTimeField(auto_now_add=True)),
('active', models.BooleanField(default=True)),
('comment', models.ForeignKey(to='group_discussion.Comment')),
('user', models.ForeignKey(to='group_discussion.TopicUser')),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('time_voted', models.DateTimeField(auto_now_add=True)),
('active', models.BooleanField(default=True)),
('comment', models.ForeignKey(to='group_discussion.Comment')),
('user', models.ForeignKey(to='group_discussion.TopicUser')),
],
options={
},
bases=(models.Model,),
),
migrations.RemoveField(
model_name='comment',
name='disliked_by',
),
migrations.RemoveField(
model_name='comment',
name='liked_by',
),
migrations.AddField(
model_name='comment',
name='disliked_by_raw',
field=models.ManyToManyField(related_name='dislikes', through='group_discussion.Dislike', to='group_discussion.TopicUser'),
preserve_default=True,
),
migrations.AddField(
model_name='comment',
name='liked_by_raw',
field=models.ManyToManyField(related_name='likes', through='group_discussion.Like', to='group_discussion.TopicUser'),
preserve_default=True,
),
]
| [
"jonathan@jscott.me"
] | jonathan@jscott.me |
b5b83c0b8d2ea408f1c0cd0f05865115eb3632f0 | be55991401aef504c42625c5201c8a9f14ca7c3b | /leetcode/easy/two_num_sum/srcs/alibaba_interview.py | 6286f819a67da66ce57231af7b35fa8350a82cb9 | [
"Apache-2.0"
] | permissive | BillionsRichard/pycharmWorkspace | adc1f8bb15b58ded489fc8dec0df397601823d2c | 709e2681fc6d85ff52fb25717215a365f51073aa | refs/heads/master | 2021-09-14T21:12:59.839963 | 2021-08-08T09:05:37 | 2021-08-08T09:05:37 | 143,610,481 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,026 | py | # encoding: utf-8
"""
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: billions.richard@qq.com
@site:https://github.com/BillionsRichard
@software: PyCharm
@time: 2020/12/12 21:11
"""
# // 评测题目: 无
#
# // 编程语言:c / c + +或者python
# // 输入:排序数组(array),指定数字(sum)
# // 输出:如果有两个数字的和等于指定数字(sum),返回1,否则返回0
#
# // [1, 2, 4, 5, 8]
# 10
# // 0: 9
# // 1: 8
# // 2: 6
# // 3: 5
# // 4: 2
def exist_two_nums_equals_sum(input_list, target_sum):
if not input_list or len(input_list) < 2:
return False
remain_index_dict = dict()
for i, num in enumerate(input_list):
remain = target_sum - num
remain_index_dict[remain] = i
for i, num in enumerate(input_list):
if num in remain_index_dict and i != remain_index_dict.get(num):
return True
return False
if __name__ == '__main__':
l = [1, 2, 4, 5, 8]
r = exist_two_nums_equals_sum(l, 8)
print(r)
| [
"295292802@qq.com"
] | 295292802@qq.com |
8a8a00e14ae3bfd7cbba7eed78b44e3ecf9c7fee | c096ed434c24ac4e9f9a4bec75f9a561f49c9911 | /sensibility/miner/names.py | b5fbb35a2982409957fa0e596d79de22c4f42da9 | [
"Apache-2.0"
] | permissive | eddieantonio/ad-hoc-miner | 19781b07ef79fe3c973b4fd2e831cab58ddf9007 | f31aec52f5ea5549bd63db105ca61ac26271e7ee | refs/heads/master | 2021-01-11T02:22:08.879691 | 2017-06-05T19:28:37 | 2017-06-05T19:28:37 | 70,972,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,047 | py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Names for all of the Redis queues.
q:download: <repo/owner>
~ download, extract, and insert JavaScript files
q:analyze: <sha256 of file>
~ requires syntactic and lexical analysis
q:work:[uuid]: <[data]>
~ work queue for a process
"""
from uuid import UUID
__all__ = ['DOWNLOAD_QUEUE', 'PARSE_QUEUE', 'WORK_QUEUE']
class WithErrors(str):
"""
Adds errors
>>> s = WithErrors('some:name')
>>> s.errors
'some:name:errors'
"""
@property
def errors(self) -> str:
return f"{self}:errors"
class WorkQueueName:
"""
>>> uuid = UUID('{12345678-1234-5678-1234-567812345678}')
>>> WORK_QUEUE[uuid]
'q:work:12345678-1234-5678-1234-567812345678'
"""
def __init__(self, prefix: str) -> None:
self.prefix = prefix
def __getitem__(self, queue_id: UUID) -> str:
return f"{self.prefix}:{queue_id!s}"
DOWNLOAD_QUEUE = WithErrors('q:download')
PARSE_QUEUE = WithErrors('q:analyze')
WORK_QUEUE = WorkQueueName('q:work')
| [
"easantos@ualberta.ca"
] | easantos@ualberta.ca |
ae8e1d8dc4bd5274584dc794f55910329dd56fa5 | f7d80454cdbebb08eee0e17cf2e034401e87d337 | /gunicorn.conf | 10ae681495a231bb9b50025bdc05ba08d8623fee | [] | no_license | charlee/flashpins | 8bf1ebe7714a5c20f55a8ddc3ba3ae454a759c20 | 07eaa0c32227dbfa2a42e50a9cea0d77fd5cad16 | refs/heads/master | 2020-06-04T07:09:43.516143 | 2015-04-22T03:34:21 | 2015-04-22T03:35:13 | 37,220,976 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 532 | conf | # vim: ft=python
import os
import multiprocessing
BASEDIR = os.path.dirname(os.path.abspath(__file__))
RUNDIR = os.path.join(BASEDIR, 'run')
LOGDIR = os.path.join(BASEDIR, 'log')
bind = 'unix://' + os.path.join(RUNDIR, 'flashpins.sock')
workers =multiprocessing.cpu_count() * 2
chdir = BASEDIR
pythonpath = BASEDIR
daemon = False
pidfile = os.path.join(RUNDIR, 'flashpins.pid')
#user = 'charlee'
#group = 'charlee'
loglevel = 'info'
accesslog = os.path.join(LOGDIR, 'access.log')
errorlog = os.path.join(LOGDIR, 'error.log')
| [
"oda.charlee@gmail.com"
] | oda.charlee@gmail.com |
4f5be540e978683566161b1c53e085f3e33379e4 | 121c327f208450824ac71c8d4056865248acafb8 | /package-boost.py | 03fa0cccd2e9b418561dd89c52a84e47e6a913fa | [] | no_license | mattbierbaum/openkim-chip-packages | 3f0d8798f51ebd2e50566de3873bbf89409fc3bf | f1a6d260161a1e4d13c0327677709abfc17a5905 | refs/heads/master | 2020-06-30T02:49:33.737660 | 2014-08-29T02:27:14 | 2014-08-29T02:27:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 768 | py | #!/usr/bin/env python
import os
from chip.packages import Package, wrap_install, wrap_default
class BoostPackage(Package):
def __init__(self, *args, **kwargs):
super(ConfigPackage, self).__init__(*args, **kwargs)
self.libpath = os.path.join(self.build_path, "lib")
self.incpath = os.path.join(self.build_path, "include")
@wrap_install
def install(self):
pass
@wrap_default('activate')
def activate(self):
self.path_push(self.libpath, "LIBRARY_PATH")
self.path_push(self.incpath, "CPLUS_INCLUDE_PATH")
@wrap_default('deactivate')
def deactivate(self):
self.path_pull(self.libpath, "LIBRARY_PATH")
self.path_pull(self.incpath, "CPLUS_INCLUDE_PATH")
pkg = BoostPackage
| [
"matt.bierbaum@gmail.com"
] | matt.bierbaum@gmail.com |
dfc77e9d87e3bde6d495cbc1f128df975a9ded2e | a3c68eafdb433c981f2b90e86f895e4f121c69fb | /笔试/拼多多/分巧克力.py | 65788b9fd4370e79a28ec4da478beb8df396566d | [] | no_license | Cassiexyq/Program-Exercise | ccc236ea76ca99ddc6fe0c4c47edebc3d557cfad | e962cc3add047d61df275dd3e22a091018fd964a | refs/heads/master | 2020-04-25T20:27:33.561226 | 2019-09-22T15:29:35 | 2019-09-22T15:29:35 | 173,050,531 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 316 | py | # -*- coding: utf-8 -*-
# @Author: xyq
n = int(input())
h = list(map(int, input().split()))
m = int(input())
w = list(map(int,input().split()))
h = sorted(h)
w = sorted(w)
print(h)
print(w)
i,j = 0,0
cn = 0
while i < len(h) and j < len(w):
if h[i] <= w[j]:
cn += 1
i += 1
j += 1
print(cn)
| [
"cassiexuan_yq@163.com"
] | cassiexuan_yq@163.com |
b1d886da07b9f247618dc2cba911cf74f3607697 | d5f53599338a30a9d6c7de7d5c574db59545ed3d | /Gse/generated/Ref/commands/SG1_SignalGen_Skip.py | 89356c709453ce3e70aad3f6f65b253bf5e924b6 | [
"Apache-2.0"
] | permissive | dstockhouse/eaglesat-fprime | c39a01cc5648dcd8b351f47684923fe481c720be | e640b3faea0000e1ca8acab4d6ff66150196c32b | refs/heads/master | 2020-05-07T15:31:09.289797 | 2019-11-20T00:33:15 | 2019-11-20T00:33:15 | 180,639,007 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,502 | py | '''
Created on Wednesday, 10 April 2019
@author: David
THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT!!!
XML Source: /cygdrive/c/Users/David/Documents/eaglesat/eaglesat-fprime/Ref/SignalGen/SignalGenComponentAi.xml
'''
# Import the types this way so they do not need prefixing for execution.
from models.serialize.type_exceptions import *
from models.serialize.type_base import *
from models.serialize.bool_type import *
from models.serialize.enum_type import *
from models.serialize.f32_type import *
from models.serialize.f64_type import *
from models.serialize.u8_type import *
from models.serialize.u16_type import *
from models.serialize.u32_type import *
from models.serialize.u64_type import *
from models.serialize.i8_type import *
from models.serialize.i16_type import *
from models.serialize.i32_type import *
from models.serialize.i64_type import *
from models.serialize.string_type import *
from models.serialize.serializable_type import *
from models.common import command
# Each file represents the information for a single command
# These module variables are used to instance the command object within the Gse
COMPONENT = "Ref::SignalGen"
MNEMONIC = "SG1_SignalGen_Skip"
OP_CODE = 0xb7
CMD_DESCRIPTION = "Skip next sample"
# Set arguments list with default values here.
ARGUMENTS = [
]
if __name__ == '__main__':
testcmd = command.Command(COMPONENT, MNEMONIC, OP_CODE, CMD_DESCRIPTION, ARGUMENTS)
data = testcmd.serialize()
type_base.showBytes(data)
| [
"dstockhouse@gmail.com"
] | dstockhouse@gmail.com |
7f3062448fe5d459719f340eb7053217a25fc1b0 | cc08f8eb47ef92839ba1cc0d04a7f6be6c06bd45 | /Personal/Jaipur1/Jaipur1/settings.py | 5807d44988408425ec16901816366931630408ca | [] | no_license | ProsenjitKumar/PycharmProjects | d90d0e7c2f4adc84e861c12a3fcb9174f15cde17 | 285692394581441ce7b706afa3b7af9e995f1c55 | refs/heads/master | 2022-12-13T01:09:55.408985 | 2019-05-08T02:21:47 | 2019-05-08T02:21:47 | 181,052,978 | 1 | 1 | null | 2022-12-08T02:31:17 | 2019-04-12T17:21:59 | null | UTF-8 | Python | false | false | 3,161 | py | """
Django settings for Jaipur1 project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd&zvc408e__xo6@x8hfkah3u^0j&*9kv(2ox4^lzd3*!5l1%4^'
# 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',
'app.apps.AppConfig',
]
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 = 'Jaipur1.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 = 'Jaipur1.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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/2.1/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/2.1/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/2.1/howto/static-files/
STATIC_URL = '/static/'
| [
"prosenjitearnkuar@gmail.com"
] | prosenjitearnkuar@gmail.com |
d73e69a3952b2e4956dd6ec65463e0da17c490d1 | 9fc6604ae98e1ae91c490e8201364fdee1b4222a | /po_line_source/model/account_invoice.py | 784b3cfcb73e15b4bd47e931d70bd4354b1b7577 | [] | no_license | nabiforks/baytonia | b65e6a7e1c7f52a7243e82f5fbcc62ae4cbe93c4 | 58cb304d105bb7332f0a6ab685015f070988ba56 | refs/heads/main | 2023-03-23T21:02:57.862331 | 2021-01-04T03:40:58 | 2021-01-04T03:40:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 676 | py | from odoo import models,fields,api
class AccountInvoiceLine(models.Model):
_inherit = 'account.invoice.line'
source_doc = fields.Char('Source')
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
source_doc = fields.Char('Source')
def _prepare_invoice_line_from_po_line(self, line):
res = super(AccountInvoice, self)._prepare_invoice_line_from_po_line(line)
res['source_doc'] = line.source_doc
return res
@api.onchange('purchase_id')
def purchase_order_change(self):
self.source_doc = self.purchase_id.origin
res = super(AccountInvoice, self).purchase_order_change()
return res
| [
"ash@odoxsofthub.com"
] | ash@odoxsofthub.com |
d6906a6133a6fa3b1f9477f77e026dbdf665df7d | 89474b15817bb144542dfa866770fa98cc7ead90 | /tests/bdd/ha-bhyve02/test_NAS_T0948.py | 4036b89f1fb640067e1e1ba351939dc3d2ffc681 | [] | no_license | nasioDSW/webui | dc6bd1a9188d9e7aeeca0f3c844df83950ce5298 | 497d7ce536ba3ead99c51fa0c6a04f636fabcaf6 | refs/heads/master | 2023-03-28T16:53:36.912571 | 2021-04-02T19:26:44 | 2021-04-02T19:26:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,712 | py | # coding=utf-8
"""High Availability (tn-bhyve01) feature tests."""
import time
from function import (
wait_on_element,
is_element_present,
wait_on_element_disappear
)
from pytest_bdd import (
given,
scenario,
then,
when,
parsers
)
@scenario('features/NAS-T948.feature', 'Edit User Shell')
def test_edit_user_shell(driver):
"""Edit User Shell."""
@given(parsers.parse('The browser is open navigate to "{nas_url}"'))
def the_browser_is_open_navigate_to_nas_url(driver, nas_url):
"""The browser is open navigate to "{nas_url}"."""
if nas_url not in driver.current_url:
driver.get(f"http://{nas_url}/ui/sessions/signin")
time.sleep(3)
@when(parsers.parse('If login page appear enter "{user}" and "{password}"'))
def if_login_page_appear_enter_root_and_password(driver, user, password):
"""If login page appear enter "root" and "testing"."""
if not is_element_present(driver, '//mat-list-item[@ix-auto="option__Dashboard"]'):
assert wait_on_element(driver, 0.5, 5, '//input[@data-placeholder="Username"]')
driver.find_element_by_xpath('//input[@data-placeholder="Username"]').clear()
driver.find_element_by_xpath('//input[@data-placeholder="Username"]').send_keys(user)
driver.find_element_by_xpath('//input[@data-placeholder="Password"]').clear()
driver.find_element_by_xpath('//input[@data-placeholder="Password"]').send_keys(password)
assert wait_on_element(driver, 0.5, 7, '//button[@name="signin_button"]')
driver.find_element_by_xpath('//button[@name="signin_button"]').click()
else:
driver.find_element_by_xpath('//mat-list-item[@ix-auto="option__Dashboard"]').click()
@then('You should see the dashboard')
def you_should_see_the_dashboard(driver):
"""You should see the dashboard."""
assert wait_on_element(driver, 1, 10, '//h1[contains(.,"Dashboard")]')
assert wait_on_element(driver, 1, 10, '//span[contains(.,"System Information")]')
@then('Click on the Credentials item in the left side menu')
def click_on_the_credentials_item_in_the_left_side_menu(driver):
"""Click on the Credentials item in the left side menu."""
driver.find_element_by_xpath('//mat-list-item[@ix-auto="option__Credentials"]').click()
@then('The Credentials menu should expand to the right')
def the_credentials_menu_should_expand_to_the_right(driver):
"""The Credentials menu should expand to the right."""
assert wait_on_element(driver, 1, 7, '//mat-list-item[@ix-auto="option__Local Users"]')
@then('Click on Local Users')
def click_on_localusers(driver):
"""Click on Local Users."""
driver.find_element_by_xpath('//mat-list-item[@ix-auto="option__Local Users"]').click()
@then('The Users page should open')
def the_users_page_should_open(driver):
"""The Users page should open."""
assert wait_on_element(driver, 1, 7, '//div[contains(.,"Users")]')
@then('On the right side of the table, click the Greater-Than-Sign for one of the users')
def on_the_right_side_of_the_table_click_the_greaterthansign_for_one_of_the_users(driver):
"""On the right side of the table, click the Greater-Than-Sign for one of the users."""
driver.find_element_by_xpath('//tr[@ix-auto="expander__ericbsd"]/td').click()
@then('The User Field should expand down to list further details')
def the_user_field_should_expand_down_to_list_further_details(driver):
"""The User Field should expand down to list further details."""
assert wait_on_element(driver, 0.5, 7, '//button[@ix-auto="button__EDIT_ericbsd"]')
driver.find_element_by_xpath('//button[@ix-auto="button__EDIT_ericbsd"]')
@then('Click the Edit button that appears')
def click_the_edit_button_that_appears(driver):
"""Click the Edit button that appears."""
driver.find_element_by_xpath('//button[@ix-auto="button__EDIT_ericbsd"]').click()
@then('The User Edit Page should open')
def the_user_edit_page_should_open(driver):
"""The User Edit Page should open."""
assert wait_on_element(driver, 1, 7, '//h3[contains(.,"Edit User")]')
@then('Change the users shell and click save')
def change_the_users_shell_and_click_save(driver):
"""Change the users shell and click save."""
element = driver.find_element_by_xpath('//button[@ix-auto="button__SAVE"]')
driver.execute_script("arguments[0].scrollIntoView();", element)
time.sleep(0.5)
driver.find_element_by_xpath('//mat-select[@ix-auto="select__Shell"]').click()
assert wait_on_element(driver, 0.5, 7, '//mat-option[@ix-auto="option__Shell_sh"]')
driver.find_element_by_xpath('//mat-option[@ix-auto="option__Shell_sh"]').click()
assert wait_on_element(driver, 0.5, 7, '//button[@ix-auto="button__SAVE"]')
driver.find_element_by_xpath('//button[@ix-auto="button__SAVE"]').click()
@then('Change should be saved')
def change_should_be_saved(driver):
"""Change should be saved."""
assert wait_on_element_disappear(driver, 1, 20, '//h6[contains(.,"Please wait")]')
assert wait_on_element(driver, 1, 7, '//div[contains(.,"Users")]')
@then('Open the user drop down to verify the shell was changed')
def open_the_user_drop_down_to_verify_the_shell_was_changed(driver):
"""Open the user drop down to verify the shell was changed."""
driver.find_element_by_xpath('//tr[@ix-auto="expander__ericbsd"]/td').click()
assert wait_on_element(driver, 0.5, 7, '//button[@ix-auto="button__EDIT_ericbsd"]')
driver.find_element_by_xpath('//h4[contains(.,"Shell:")]')
@then('Updated value should be visible')
def updated_value_should_be_visible(driver):
"""Updated value should be visible."""
driver.find_element_by_xpath('//p[contains(.,"/bin/sh")]')
| [
"ericturgeon.bsd@gmail.com"
] | ericturgeon.bsd@gmail.com |
2d0155a51eaa8771e89fa8cddeb6c3ebd3e02ed7 | e3e5a0618b91fe58318763f2186422b95e6edd10 | /baidupcs_py/commands/server.py | 4bb00be941c3ebb3ea44bb38f32af745ebba22a0 | [
"MIT"
] | permissive | hfh1999/BaiduPCS-Py | ddd66ff4d33d0e609021280a1edc040d51654940 | 4cf77bba7afbc8c82e0bc6ecd4ffc4a66aab1c71 | refs/heads/master | 2023-02-20T06:02:08.897248 | 2021-01-26T08:56:37 | 2021-01-26T08:56:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,726 | py | from typing import Optional, Dict
from pathlib import Path
import uvicorn
from baidupcs_py.baidupcs import BaiduPCSApi
from baidupcs_py.common.io import RangeRequestIO, READ_SIZE
from baidupcs_py.common.constant import CPU_NUM
from baidupcs_py.utils import format_date
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, StreamingResponse
from jinja2 import Template
app = FastAPI()
_api: Optional[BaiduPCSApi] = None
_root_dir: str = "/"
# This template is from https://github.com/rclone/rclone/blob/master/cmd/serve/httplib/serve/data/templates/index.html
_html_tempt: Template = Template((Path(__file__).parent / "index.html").open().read())
def fake_io(io: RangeRequestIO, start: int = 0, end: int = -1):
while True:
length = len(io)
io.seek(start, 0)
size = length if end < 0 else end - start + 1
ranges = io._split_chunk(size)
for _range in ranges:
with io._request(_range) as resp:
stream = resp.raw
while True:
b = stream.read(READ_SIZE)
if not b:
break
yield b
return
@app.get("{remotepath:path}")
async def http_server(
request: Request,
remotepath: str,
order: str = "asc", # desc , asc
sort: str = "name", # name, time, size
):
desc = order == "desc"
name = sort == "name"
time = sort == "time"
size = sort == "size"
global _root_dir
global _api
assert _api
remotepath = remotepath.strip("/")
_rp = Path(_root_dir) / remotepath
_rp_str = _rp.as_posix()
_range = request.headers.get("range")
if not _api.exists(_rp_str):
raise HTTPException(status_code=404, detail="Item not found")
is_dir = _api.is_dir(_rp_str)
if is_dir:
chunks = ["/"] + (remotepath.split("/") if remotepath != "" else [])
navigation = [
(i - 1, "../" * (len(chunks) - i), name) for i, name in enumerate(chunks, 1)
]
pcs_files = _api.list(_rp_str, desc=desc, name=name, time=time, size=size)
entries = []
for f in pcs_files:
p = Path(f.path)
entries.append((f.is_dir, p.name, f.size, format_date(f.mtime or 0)))
cn = _html_tempt.render(
root_dir=remotepath, navigation=navigation, entries=entries
)
return HTMLResponse(cn)
else:
range_request_io = _api.file_stream(_rp_str)
length = len(range_request_io)
headers: Dict[str, str] = {
"accept-ranges": "bytes",
"connection": "Keep-Alive",
}
if _range:
assert _range.startswith("bytes=")
status_code = 206
start, end = _range[6:].split("-")
_s, _e = int(start or 0), int(end or length - 1)
_io = fake_io(range_request_io, _s, _e)
headers["content-range"] = f"bytes {_s}-{_e}/{length}"
headers["content-length"] = str(_e - _s + 1)
else:
status_code = 200
_io = fake_io(range_request_io)
headers["content-length"] = str(length)
return StreamingResponse(_io, status_code=status_code, headers=headers)
def start_server(
api: BaiduPCSApi,
root_dir: str = "/",
host: str = "localhost",
port: int = 8000,
workers: int = CPU_NUM,
):
"""Create a http server on remote `root_dir`"""
global _root_dir
_root_dir = root_dir
global _api
if not _api:
_api = api
uvicorn.run(
"baidupcs_py.commands.server:app",
host=host,
port=port,
log_level="info",
workers=1,
)
| [
"dfhayst@gmail.com"
] | dfhayst@gmail.com |
34e5b8a8cb2d4f41d01b08c97a90110b4cd9dd4a | 1ab7b3f2aa63de8488ce7c466a67d367771aa1f2 | /Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/pygame/cursors.pyi | 1f87c9e24792ff960343baa1c86e9c095afb5576 | [
"MIT"
] | permissive | icl-rocketry/Avionics | 9d39aeb11aba11115826fd73357b415026a7adad | 95b7a061eabd6f2b607fba79e007186030f02720 | refs/heads/master | 2022-07-30T07:54:10.642930 | 2022-07-10T12:19:10 | 2022-07-10T12:19:10 | 216,184,670 | 9 | 1 | MIT | 2022-06-27T10:17:06 | 2019-10-19T09:57:07 | C++ | UTF-8 | Python | false | false | 1,655 | pyi | from typing import Tuple, Sequence, Optional, Iterable
from pygame.surface import Surface
_Small_string = Tuple[
str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str
]
_Big_string = Tuple[
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
str,
]
arrow: Cursor
diamond: Cursor
broken_x: Cursor
tri_left: Cursor
tri_right: Cursor
thickarrow_strings: _Big_string
sizer_x_strings: _Small_string
sizer_y_strings: _Big_string
sizer_xy_strings: _Small_string
def compile(
strings: Sequence[str],
black: Optional[str] = "X",
white: Optional[str] = ".",
xor="o",
) -> Tuple[Sequence[int], Sequence[int]]: ...
def load_xbm(cursorfile: str, maskfile: str): ...
class Cursor(Iterable):
@overload
def __init__(constant: int) -> None: ...
@overload
def __init__(size: Union[Tuple[int, int], List[int]],
hotspot: Union[Tuple[int, int], List[int]],
xormasks: Sequence[int],
andmasks: Sequence[int],
) -> None: ...
@overload
def __init__(hotspot: Union[Tuple[int, int], List[int]],
surface: Surface,
) -> None: ...
def __iter__() -> Iterator[object]: ...
type: string
data: Union[Tuple[int],
Tuple[Union[Tuple[int, int], List[int]],
Union[Tuple[int, int], List[int]],
Sequence[int],
Sequence[int]],
Tuple[int, Surface]]
| [
"kd619@ic.ac.uk"
] | kd619@ic.ac.uk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.