uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d7cffc26eb1fe76f5dea7c5 | train | function | def get_rrr():
"""
获取存款准备金率数据
Return
--------
DataFrame
date :变动日期
before :调整前存款准备金率(%)
now:调整后存款准备金率(%)
changed:调整幅度(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
... | def get_rrr():
| """
获取存款准备金率数据
Return
--------
DataFrame
date :变动日期
before :调整前存款准备金率(%)
now:调整后存款准备金率(%)
changed:调整幅度(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdi... | tr = datastr.split('data:')[1]
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.LOAN_COLS)
for i in df.columns:
df[i] = df[i].apply(lambda x:np.where(x is None, '--', x))
return df
def get_rrr():
| 73 | 73 | 246 | 5 | 67 | liufeirong/tushare | tushare/stock/macro.py | Python | get_rrr | get_rrr | 296 | 321 | 296 | 296 | 758608baafecf64eab170c80bd2c89bf906be4d8 | bigcode/the-stack | train |
aca3bd09d96ac76d441b5ee2 | train | function | def get_ppi():
"""
获取工业品出厂价格指数数据
Return
--------
DataFrame
month :统计月份
ppiip :工业品出厂价格指数
ppi :生产资料价格指数
qm:采掘工业价格指数
rmi:原材料工业价格指数
pi:加工工业价格指数
cg:生活资料价格指数
food:食品类价格指数
clothing:衣着类价格指数
roeu:一般日用品价格指数
... | def get_ppi():
| """
获取工业品出厂价格指数数据
Return
--------
DataFrame
month :统计月份
ppiip :工业品出厂价格指数
ppi :生产资料价格指数
qm:采掘工业价格指数
rmi:原材料工业价格指数
pi:加工工业价格指数
cg:生活资料价格指数
food:食品类价格指数
clothing:衣着类价格指数
roeu:一般日用品价格指数
dcg:耐用消... | ct.PY3 else text
regSym = re.compile(r'\,count:(.*?)\}')
datastr = regSym.findall(text)
datastr = datastr[0]
datastr = datastr.split('data:')[1]
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.CPI_COLS)
df['cpi'] = df['cpi'].astype(float)
return df
def get_ppi():
| 101 | 101 | 337 | 5 | 95 | liufeirong/tushare | tushare/stock/macro.py | Python | get_ppi | get_ppi | 205 | 239 | 205 | 205 | 896a8fe4acb4b9332dfd84dd6353e1b0508a855b | bigcode/the-stack | train |
0853f8e30d3c5220ed1a8cc2 | train | function | def get_loan_rate():
"""
获取贷款利率数据
Return
--------
DataFrame
date :执行日期
loan_type :存款种类
rate:利率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdint, vs.MACRO_TYP... | def get_loan_rate():
| """
获取贷款利率数据
Return
--------
DataFrame
date :执行日期
loan_type :存款种类
rate:利率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdint, vs.MACRO_TYPE[2], 3, 800,
... | :')[1]
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.DEPOSIT_COLS)
for i in df.columns:
df[i] = df[i].apply(lambda x:np.where(x is None, '--', x))
return df
def get_loan_rate():
| 69 | 69 | 230 | 6 | 62 | liufeirong/tushare | tushare/stock/macro.py | Python | get_loan_rate | get_loan_rate | 269 | 293 | 269 | 269 | 4c84ad09c7194f45b4881adc6a14accd3d0f6bef | bigcode/the-stack | train |
0cc6675bb51a51936cf1234f | train | function | def get_gdp_for():
"""
获取三大需求对GDP贡献数据
Return
--------
DataFrame
year :统计年度
end_for :最终消费支出贡献率(%)
for_rate :最终消费支出拉动(百分点)
asset_for :资本形成总额贡献率(%)
asset_rate:资本形成总额拉动(百分点)
goods_for :货物和服务净出口贡献率(%)
goods_rate :货物和服务净出口拉动(百分点)
... | def get_gdp_for():
| """
获取三大需求对GDP贡献数据
Return
--------
DataFrame
year :统计年度
end_for :最终消费支出贡献率(%)
for_rate :最终消费支出拉动(百分点)
asset_for :资本形成总额贡献率(%)
asset_rate:资本形成总额拉动(百分点)
goods_for :货物和服务净出口贡献率(%)
goods_rate :货物和服务净出口拉动(百分点)
"""
rdint = vs... | # js = json.loads(datastr)
# df = pd.DataFrame(js, columns=vs.GDP_QUARTER_COLS)
# df['quarter'] = df['quarter'].astype(object)
# df[df==0] = np.NaN
# return df
return "请使用pro版数据:https://tushare.pro/document/2?doc_id=227"
def get_gdp_for():
| 89 | 90 | 300 | 6 | 83 | liufeirong/tushare | tushare/stock/macro.py | Python | get_gdp_for | get_gdp_for | 93 | 120 | 93 | 93 | 7f48a1fb3bdf230f687a23e756fe2aaed171e7c0 | bigcode/the-stack | train |
f8f9486848311bca4ee000f2 | train | function | def get_money_supply_bal():
"""
获取货币供应量(年底余额)数据
Return
--------
DataFrame
year :统计年度
m2 :货币和准货币(亿元)
m1:货币(亿元)
m0:流通中现金(亿元)
cd:活期存款(亿元)
qm:准货币(亿元)
ftd:定期存款(亿元)
sd:储蓄存款(亿元)
rests:其他存款(亿元)
"""
rdint = vs... | def get_money_supply_bal():
| """
获取货币供应量(年底余额)数据
Return
--------
DataFrame
year :统计年度
m2 :货币和准货币(亿元)
m1:货币(亿元)
m0:流通中现金(亿元)
cd:活期存款(亿元)
qm:准货币(亿元)
ftd:定期存款(亿元)
sd:储蓄存款(亿元)
rests:其他存款(亿元)
"""
rdint = vs.random()
request = Requ... | Sym.findall(text)
datastr = datastr[0]
datastr = datastr.split('data:')[1]
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.MONEY_SUPPLY_COLS)
for i in df.columns:
df[i] = df[i].apply(lambda x:np.where(x is None, '--', x))
return df
def get_money_supply_bal():
| 91 | 91 | 304 | 6 | 84 | liufeirong/tushare | tushare/stock/macro.py | Python | get_money_supply_bal | get_money_supply_bal | 365 | 395 | 365 | 365 | 1496f0062cfc89354774bb15854a3d05181523e6 | bigcode/the-stack | train |
cf760c966952e0a0235ac1ce | train | function | def get_gdp_quarter():
"""
获取季度国内生产总值数据
Return
--------
DataFrame
quarter :季度
gdp :国内生产总值(亿元)
gdp_yoy :国内生产总值同比增长(%)
pi :第一产业增加值(亿元)
pi_yoy:第一产业增加值同比增长(%)
si :第二产业增加值(亿元)
si_yoy :第二产业增加值同比增长(%)
ti :第三产业增加值(亿元)
... | def get_gdp_quarter():
| """
获取季度国内生产总值数据
Return
--------
DataFrame
quarter :季度
gdp :国内生产总值(亿元)
gdp_yoy :国内生产总值同比增长(%)
pi :第一产业增加值(亿元)
pi_yoy:第一产业增加值同比增长(%)
si :第二产业增加值(亿元)
si_yoy :第二产业增加值同比增长(%)
ti :第三产业增加值(亿元)
ti_yoy :第三产业增加值同比增长(%)
... | regSym = re.compile(r'\,count:(.*?)\}')
datastr = regSym.findall(text)
datastr = datastr[0]
datastr = datastr.split('data:')[1]
datastr = datastr.replace('"', '').replace('null', '0')
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.GDP_YEAR_COLS)
df[df==0] = np.NaN
... | 110 | 111 | 370 | 7 | 102 | liufeirong/tushare | tushare/stock/macro.py | Python | get_gdp_quarter | get_gdp_quarter | 58 | 90 | 58 | 58 | 19da0f12c7cff7642127cc99e428194c2b1f7b72 | bigcode/the-stack | train |
085b4cd3a5cdd5886586e0b5 | train | function | def get_gold_and_foreign_reserves():
"""
获取外汇储备
Returns
-------
DataFrame
month :统计时间
gold:黄金储备(万盎司)
foreign_reserves:外汇储备(亿美元)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL % (vs.P_TYPE['http'], vs.DOMAINS['sina'],
... | def get_gold_and_foreign_reserves():
| """
获取外汇储备
Returns
-------
DataFrame
month :统计时间
gold:黄金储备(万盎司)
foreign_reserves:外汇储备(亿美元)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL % (vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdint, vs.MACRO_TYPE[2], 5,... | ')[1]
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.MONEY_SUPPLY_BLA_COLS)
for i in df.columns:
df[i] = df[i].apply(lambda x:np.where(x is None, '--', x))
return df
def get_gold_and_foreign_reserves():
| 73 | 73 | 246 | 9 | 63 | liufeirong/tushare | tushare/stock/macro.py | Python | get_gold_and_foreign_reserves | get_gold_and_foreign_reserves | 398 | 422 | 398 | 398 | 38de582cc525c9f8acd432a38824523386f6dbfa | bigcode/the-stack | train |
537259b3f1d42fd0d6ef764e | train | function | def get_gdp_pull():
"""
获取三大产业对GDP拉动数据
Return
--------
DataFrame
year :统计年度
gdp_yoy :国内生产总值同比增长(%)
pi :第一产业拉动率(%)
si :第二产业拉动率(%)
industry:其中工业拉动(%)
ti :第三产业拉动率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.... | def get_gdp_pull():
| """
获取三大产业对GDP拉动数据
Return
--------
DataFrame
year :统计年度
gdp_yoy :国内生产总值同比增长(%)
pi :第一产业拉动率(%)
si :第二产业拉动率(%)
industry:其中工业拉动(%)
ti :第三产业拉动率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DO... | tr = datastr[0]
datastr = datastr.split('data:')[1]
datastr = datastr.replace('"','').replace('null','0')
js = json.loads(datastr)
df = pd.DataFrame(js,columns=vs.GDP_FOR_COLS)
df[df==0] = np.NaN
return df
def get_gdp_pull():
| 82 | 82 | 276 | 6 | 75 | liufeirong/tushare | tushare/stock/macro.py | Python | get_gdp_pull | get_gdp_pull | 123 | 149 | 123 | 123 | 7cf8fafa862f897305ad4a21368bcc778df1039a | bigcode/the-stack | train |
459f72bc873c271d38938732 | train | function | def get_deposit_rate():
"""
获取存款利率数据
Return
--------
DataFrame
date :变动日期
deposit_type :存款种类
rate:利率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdint, vs.MAC... | def get_deposit_rate():
| """
获取存款利率数据
Return
--------
DataFrame
date :变动日期
deposit_type :存款种类
rate:利率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdint, vs.MACRO_TYPE[2], 2, 600,
... | Frame(js, columns=vs.PPI_COLS)
for i in df.columns:
df[i] = df[i].apply(lambda x:np.where(x is None, np.NaN, x))
if i != 'month':
df[i] = df[i].astype(float)
return df
def get_deposit_rate():
| 70 | 70 | 234 | 6 | 63 | liufeirong/tushare | tushare/stock/macro.py | Python | get_deposit_rate | get_deposit_rate | 242 | 266 | 242 | 242 | 96ef176b53db3cde675c165488b8ec667ef07db5 | bigcode/the-stack | train |
623d1fae25ff4c01337f47e6 | train | function | def get_cpi():
"""
获取居民消费价格指数数据
Return
--------
DataFrame
month :统计月份
cpi :价格指数
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdint, vs.MACRO_TYPE[1], 0, 600,
... | def get_cpi():
| """
获取居民消费价格指数数据
Return
--------
DataFrame
month :统计月份
cpi :价格指数
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina'],
rdint, vs.MACRO_TYPE[1], 0, 600,
... | datastr = datastr.replace('"', '').replace('null', '0')
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.GDP_CONTRIB_COLS)
df[df==0] = np.NaN
return df
def get_cpi():
| 64 | 64 | 213 | 5 | 58 | liufeirong/tushare | tushare/stock/macro.py | Python | get_cpi | get_cpi | 180 | 202 | 180 | 180 | b11850b5eabb037815e9c52db6f04c70acdfb55c | bigcode/the-stack | train |
3e05a999b0774b77d62837d3 | train | function | def get_gdp_year():
"""
获取年度国内生产总值数据
Return
--------
DataFrame
year :统计年度
gdp :国内生产总值(亿元)
pc_gdp :人均国内生产总值(元)
gnp :国民生产总值(亿元)
pi :第一产业(亿元)
si :第二产业(亿元)
industry :工业(亿元)
cons_industry :建筑业(亿元)
ti :第三产业(亿元)
... | def get_gdp_year():
| """
获取年度国内生产总值数据
Return
--------
DataFrame
year :统计年度
gdp :国内生产总值(亿元)
pc_gdp :人均国内生产总值(元)
gnp :国民生产总值(亿元)
pi :第一产业(亿元)
si :第二产业(亿元)
industry :工业(亿元)
cons_industry :建筑业(亿元)
ti :第三产业(亿元)
trans_industry :交... | Created on 2015/01/24
@author: Jimmy Liu
@group : waditu
@contact: jimmysoa@sina.cn
"""
import pandas as pd
import numpy as np
import re
import json
from tushare.stock import macro_vars as vs
from tushare.stock import cons as ct
try:
from urllib.request import urlopen, Request
except ImportError:
... | 99 | 99 | 332 | 6 | 92 | liufeirong/tushare | tushare/stock/macro.py | Python | get_gdp_year | get_gdp_year | 23 | 55 | 23 | 23 | b5200158ce9214b6a90c6e5eba86beceb9c693e4 | bigcode/the-stack | train |
b967e96aad99c3f67400569b | train | function | def get_money_supply():
"""
获取货币供应量数据
Return
--------
DataFrame
month :统计时间
m2 :货币和准货币(广义货币M2)(亿元)
m2_yoy:货币和准货币(广义货币M2)同比增长(%)
m1:货币(狭义货币M1)(亿元)
m1_yoy:货币(狭义货币M1)同比增长(%)
m0:流通中现金(M0)(亿元)
m0_yoy:流通中现金(M0)同比增长(%)
cd:活期存款... | def get_money_supply():
| """
获取货币供应量数据
Return
--------
DataFrame
month :统计时间
m2 :货币和准货币(广义货币M2)(亿元)
m2_yoy:货币和准货币(广义货币M2)同比增长(%)
m1:货币(狭义货币M1)(亿元)
m1_yoy:货币(狭义货币M1)同比增长(%)
m0:流通中现金(M0)(亿元)
m0_yoy:流通中现金(M0)同比增长(%)
cd:活期存款(亿元)
cd_yoy:活期存款... | int))
text = urlopen(request, timeout=10).read()
text = text.decode('gbk')
regSym = re.compile(r'\,count:(.*?)\}')
datastr = regSym.findall(text)
datastr = datastr[0]
datastr = datastr.split('data:')[1]
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.RRR_COLS)
for ... | 132 | 132 | 442 | 5 | 126 | liufeirong/tushare | tushare/stock/macro.py | Python | get_money_supply | get_money_supply | 324 | 362 | 324 | 324 | 3940857746811951eb641a4d8cbf184dd1f4812c | bigcode/the-stack | train |
cc307f7304f0831fa24ea9fb | train | function | def get_gdp_contrib():
"""
获取三大产业贡献率数据
Return
--------
DataFrame
year :统计年度
gdp_yoy :国内生产总值
pi :第一产业献率(%)
si :第二产业献率(%)
industry:其中工业献率(%)
ti :第三产业献率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['ht... | def get_gdp_contrib():
| """
获取三大产业贡献率数据
Return
--------
DataFrame
year :统计年度
gdp_yoy :国内生产总值
pi :第一产业献率(%)
si :第二产业献率(%)
industry:其中工业献率(%)
ti :第三产业献率(%)
"""
rdint = vs.random()
request = Request(vs.MACRO_URL%(vs.P_TYPE['http'], vs.DOMAINS['sina']... | tr[0]
datastr = datastr.split('data:')[1]
datastr = datastr.replace('"', '').replace('null', '0')
js = json.loads(datastr)
df = pd.DataFrame(js, columns=vs.GDP_PULL_COLS)
df[df==0] = np.NaN
return df
def get_gdp_contrib():
| 81 | 81 | 271 | 7 | 73 | liufeirong/tushare | tushare/stock/macro.py | Python | get_gdp_contrib | get_gdp_contrib | 152 | 178 | 152 | 152 | b588b46e1150b5bd3da4d57bc6c0e044b4721aee | bigcode/the-stack | train |
e5144d4736b1e7fa81eaf8a5 | train | class | class ACIModule(object):
def __init__(self, module):
self.module = module
self.params = module.params
self.result = dict(changed=False)
self.headers = dict()
self.child_classes = set()
# error output
self.error = dict(code=None, text=None)
# normal ... | class ACIModule(object):
| def __init__(self, module):
self.module = module
self.params = module.params
self.result = dict(changed=False)
self.headers = dict()
self.child_classes = set()
# error output
self.error = dict(code=None, text=None)
# normal output
self.existi... |
HAS_LXML_ETREE = True
except ImportError:
HAS_LXML_ETREE = False
# Optional, only used for XML payload
try:
from xmljson import cobra
HAS_XMLJSON_COBRA = True
except ImportError:
HAS_XMLJSON_COBRA = False
def aci_argument_spec():
return dict(
host=dict(type='str', required=True, alia... | 256 | 256 | 8,995 | 6 | 250 | lakhlaifi/RedHat-Ansible | virt/ansible-latest/lib/python2.7/site-packages/ansible/module_utils/network/aci/aci.py | Python | ACIModule | ACIModule | 81 | 997 | 81 | 82 | d02827a6d77678bfca50814758587a64091a13d5 | bigcode/the-stack | train |
43d769e77cc2e535206f3e83 | train | function | def aci_argument_spec():
return dict(
host=dict(type='str', required=True, aliases=['hostname']),
port=dict(type='int', required=False),
username=dict(type='str', default='admin', aliases=['user']),
password=dict(type='str', no_log=True),
private_key=dict(type='str', aliases=... | def aci_argument_spec():
| return dict(
host=dict(type='str', required=True, aliases=['hostname']),
port=dict(type='int', required=False),
username=dict(type='str', default='admin', aliases=['user']),
password=dict(type='str', no_log=True),
private_key=dict(type='str', aliases=['cert_key'], no_log=True... | = True
except ImportError:
HAS_LXML_ETREE = False
# Optional, only used for XML payload
try:
from xmljson import cobra
HAS_XMLJSON_COBRA = True
except ImportError:
HAS_XMLJSON_COBRA = False
def aci_argument_spec():
| 64 | 64 | 185 | 6 | 57 | lakhlaifi/RedHat-Ansible | virt/ansible-latest/lib/python2.7/site-packages/ansible/module_utils/network/aci/aci.py | Python | aci_argument_spec | aci_argument_spec | 65 | 78 | 65 | 65 | 85c0c9aa4345ee02eaa724a3d9175bebcf2c52ba | bigcode/the-stack | train |
4fe0470443cbf2e3741aa2ff | train | class | class Sidebar(db.Model):
"""侧边栏
"""
__tablename__ = 'sidebar'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(250), nullable=False, default=u'')
image_url = db.Column(db.String(256), nullable=False, default='')
content = db.Column(db.Text, nullable=True)
created... | class Sidebar(db.Model):
| """侧边栏
"""
__tablename__ = 'sidebar'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(250), nullable=False, default=u'')
image_url = db.Column(db.String(256), nullable=False, default='')
content = db.Column(db.Text, nullable=True)
created = db.Column(db.DateTime,... | _url = db.Column(db.String(256), nullable=False, default='')
content = db.Column(db.Text, nullable=True)
created = db.Column(db.DateTime, default=db.func.now())
update = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now())
class Sidebar(db.Model):
| 64 | 64 | 112 | 5 | 59 | NlxF/wuaiwow | wuaiwow/models/news.py | Python | Sidebar | Sidebar | 19 | 29 | 19 | 19 | b26273f0451f4a9f4505487243b026c226dc5c8a | bigcode/the-stack | train |
60ac4a79e81920cb28a6fc11 | train | class | class News(db.Model):
"""主页新闻
"""
__tablename__ = 'news'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Unicode(256), nullable=False, default=u'我是标题')
summary = db.Column(db.Unicode(256), nullable=False, default=u'新闻概要')
image_url = db.Column(db.String(256), nullable=Fals... | class News(db.Model):
| """主页新闻
"""
__tablename__ = 'news'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Unicode(256), nullable=False, default=u'我是标题')
summary = db.Column(db.Unicode(256), nullable=False, default=u'新闻概要')
image_url = db.Column(db.String(256), nullable=False, default='')
con... | # coding:utf-8
from wuaiwow import db
class News(db.Model):
| 18 | 64 | 133 | 5 | 12 | NlxF/wuaiwow | wuaiwow/models/news.py | Python | News | News | 5 | 16 | 5 | 5 | 545629c2d83772e0bae6745bb21442a728599b85 | bigcode/the-stack | train |
cb920fbb5a05fdf3928ac7ae | train | function | def last_word(initial):
out = [initial[0]]
for index in range(1, len(initial)):
if out[0] <= initial[index]:
out.insert(0, initial[index])
else:
out.append(initial[index])
return ''.join(out)
| def last_word(initial):
| out = [initial[0]]
for index in range(1, len(initial)):
if out[0] <= initial[index]:
out.insert(0, initial[index])
else:
out.append(initial[index])
return ''.join(out)
| #-*- coding: utf-8 -*-
import os
in_file = '{base}/the_last_word_large.in'.format(base=os.getcwd())
out_file = '{base}/the_last_word_large.out'.format(base=os.getcwd())
def last_word(initial):
| 51 | 64 | 58 | 5 | 46 | ssavinash1/Algorithm_stanford | codejam/the_last_word.py | Python | last_word | last_word | 8 | 15 | 8 | 8 | 9677cc7a12438ec476af97554d7b2fd4e5c4ef8c | bigcode/the-stack | train |
e37bfb4c0511ffa20a369619 | train | function | def loadData(path,random_seed):
inputData = pd.read_csv(path)
# Transform 'string' into class number
Labels = [
['usual', 'pretentious', 'great_pret'],
['proper', 'less_proper', 'improper', 'critical', 'very_crit'],
['complete', 'completed', 'incomplete', 'foster'],
['1', '2... | def loadData(path,random_seed):
| inputData = pd.read_csv(path)
# Transform 'string' into class number
Labels = [
['usual', 'pretentious', 'great_pret'],
['proper', 'less_proper', 'improper', 'critical', 'very_crit'],
['complete', 'completed', 'incomplete', 'foster'],
['1', '2', '3', 'more'],
['conve... | label = 8
else:
print("define your own data_set and embedding knowledge.\n")
return
if val == True:
return x_train, y_train, x_test, y_test, x_val, y_val, trigger, label, class_n
else:
return x_train, y_train, x_test, y_test, trigger, label, class_n
# nursery
... | 94 | 94 | 315 | 8 | 85 | nberth/DeepConcolic | EKiML/src/load_data.py | Python | loadData | loadData | 171 | 198 | 171 | 171 | 243662eabfe9b2986fd91e2a88afacf81c202333 | bigcode/the-stack | train |
61e72c4c536ee2a3bd014500 | train | function | def load_data(data_name, val, random_seed, datadir = os.path.join ('EKiML', 'dataset')):
if data_name == "iris":
# iris
iris = load_iris()
x = iris.data
y = iris.target
class_n = 3
# convert data to float32
x = x.astype('float32')
if val == True:
... | def load_data(data_name, val, random_seed, datadir = os.path.join ('EKiML', 'dataset')):
| if data_name == "iris":
# iris
iris = load_iris()
x = iris.data
y = iris.target
class_n = 3
# convert data to float32
x = x.astype('float32')
if val == True:
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_s... | import os
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris, load_breast_cancer
from sklearn.preprocessing import LabelEncoder
from sklearn.datasets import load_svmlight_file
import numpy as np
import pandas as pd
def load_data(data_name, val, random_seed, datadir = os.path.joi... | 79 | 256 | 1,710 | 25 | 53 | nberth/DeepConcolic | EKiML/src/load_data.py | Python | load_data | load_data | 10 | 163 | 10 | 10 | 37a484618f225958c35d03e21348a55805f154d6 | bigcode/the-stack | train |
6d9ae98ed9a752dab2c324fa | train | class | class Match(object):
def __init__(self, eq=None, not_=None, range=None, regexp=None, simple_query_string=None, simpleQuery=None, substring=None):
"""
:param eq: (Optional)
:param not_: (Optional)
:param range: (Optional)
:param regexp: (Optional)
:param simple_qu... | class Match(object):
| def __init__(self, eq=None, not_=None, range=None, regexp=None, simple_query_string=None, simpleQuery=None, substring=None):
"""
:param eq: (Optional)
:param not_: (Optional)
:param range: (Optional)
:param regexp: (Optional)
:param simple_query_string: (Optional)... | 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.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class Match(object)... | 64 | 64 | 156 | 4 | 60 | Ureimu/weather-robot | python_code/vnev/Lib/site-packages/jdcloud_sdk/services/logs/models/Match.py | Python | Match | Match | 20 | 39 | 20 | 21 | 7453c1ca80a49907e727b8fff28660374be2e782 | bigcode/the-stack | train |
eec139fa235711408ef243b6 | train | class | class NestMsServer():
'''Nest style microservice server
'''
def __init__(self, host='0.0.0.0', port=None):
self.host = host
if port:
if isinstance(port, str):
self.port = int(port)
else:
self.port = port
else:
self.... | class NestMsServer():
| '''Nest style microservice server
'''
def __init__(self, host='0.0.0.0', port=None):
self.host = host
if port:
if isinstance(port, str):
self.port = int(port)
else:
self.port = port
else:
self.port = None
def a... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Jerry Wang<wangjianjun@gmail.com>'
import socketserver
import functools
from .TCPServer import MsTcpHandler
class NestMsServer():
| 48 | 103 | 345 | 5 | 42 | defartsa23/python-nest | nest/NestMsServer.py | Python | NestMsServer | NestMsServer | 10 | 55 | 10 | 10 | 29aaa667570fd7a46b5c689046102d92d7f069a8 | bigcode/the-stack | train |
410a55e6c75f4f1a13b2fbc9 | train | class | class GCCollector(object):
"""Collector for Garbage collection statistics."""
def __init__(self, registry=REGISTRY):
if not hasattr(gc, 'get_stats'):
return
registry.register(self)
def collect(self):
collected = CounterMetricFamily(
'python_gc_objects_collec... | class GCCollector(object):
| """Collector for Garbage collection statistics."""
def __init__(self, registry=REGISTRY):
if not hasattr(gc, 'get_stats'):
return
registry.register(self)
def collect(self):
collected = CounterMetricFamily(
'python_gc_objects_collected',
'Objects ... | #!/usr/bin/python
from __future__ import unicode_literals
import gc
from .metrics_core import CounterMetricFamily
from .registry import REGISTRY
class GCCollector(object):
| 37 | 65 | 217 | 5 | 31 | verma-varsha/fraud-detection | exl_env/lib/python3.6/site-packages/prometheus_client/gc_collector.py | Python | GCCollector | GCCollector | 11 | 43 | 11 | 11 | 6eed5c859885ddb539abdcb63d9f672d7673b179 | bigcode/the-stack | train |
fe59c45e5df9bd18e685a7f5 | train | function | def get_conf_base(param_dict):
try:
conf_seed = param_dict['conf_seed']
except:
conf_seed = None
try:
conf_var = param_dict['conf_var']
except:
conf_var = None
return conf_seed, conf_var | def get_conf_base(param_dict):
| try:
conf_seed = param_dict['conf_seed']
except:
conf_seed = None
try:
conf_var = param_dict['conf_var']
except:
conf_var = None
return conf_seed, conf_var | def get_conf_base(param_dict):
| 7 | 64 | 59 | 7 | 0 | lastBird/NNCF | configs/conf_utils.py | Python | get_conf_base | get_conf_base | 2 | 11 | 2 | 2 | 370b46a7819da0dd741e1379d3c85be0fd6349a2 | bigcode/the-stack | train |
7d3da6da3d24ac257b0e30eb | train | class | class LogoutView(View):
def get(self, request):
"""
Redirects to CAS logout page
:param request:
:return:
"""
next_page = clean_next_page(request, request.GET.get('next'))
# try to find the ticket matching current session for logout signal
try:
... | class LogoutView(View):
| def get(self, request):
"""
Redirects to CAS logout page
:param request:
:return:
"""
next_page = clean_next_page(request, request.GET.get('next'))
# try to find the ticket matching current session for logout signal
try:
st = SessionTicke... | messages.success(request, message)
return self.successful_login(request=request, next_page=next_page)
elif settings.CAS_RETRY_LOGIN or required:
return HttpResponseRedirect(client.get_login_url())
else:
raise PermissionDenied(_(... | 92 | 92 | 308 | 5 | 87 | orbitvu/django-cas-ng | django_cas_ng/views.py | Python | LogoutView | LogoutView | 171 | 210 | 171 | 171 | 404ac6e323576a7cf57b35f25a6e38bbe927ebd3 | bigcode/the-stack | train |
32faea2a9dfc239e79d526ea | train | class | class CallbackView(View):
"""
Read PGT and PGTIOU sent by CAS
"""
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request):
if request.POST.get('logoutRequest'):
clean_sess... | class CallbackView(View):
| """
Read PGT and PGTIOU sent by CAS
"""
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request):
if request.POST.get('logoutRequest'):
clean_sessions(get_cas_client(reques... | =request)
return HttpResponseRedirect(client.get_logout_url(redirect_url))
else:
# This is in most cases pointless if not CAS_RENEW is set. The user will
# simply be logged in again on next request requiring authorization.
return HttpResponseRedirect(next_page)
cl... | 64 | 64 | 216 | 5 | 59 | orbitvu/django-cas-ng | django_cas_ng/views.py | Python | CallbackView | CallbackView | 213 | 236 | 213 | 213 | 7d721a3b2ad4c7555f65468cfc158b6253a38751 | bigcode/the-stack | train |
7b6df6e73f0cdd54052932a4 | train | function | def is_local_url(host_url, url):
"""
:param host_url: is an absolute host url, say https://site.com/
:param url: is any url
:return: Is :url: local to :host_url:?
"""
url = url.strip()
parsed_url = urllib_parse.urlparse(url)
if not parsed_url.netloc:
return True
parsed_host =... | def is_local_url(host_url, url):
| """
:param host_url: is an absolute host url, say https://site.com/
:param url: is any url
:return: Is :url: local to :host_url:?
"""
url = url.strip()
parsed_url = urllib_parse.urlparse(url)
if not parsed_url.netloc:
return True
parsed_host = urllib_parse.urlparse(host_url)
... | = getattr(settings, 'CAS_CHECK_NEXT',
lambda _next_page: is_local_url(request.build_absolute_uri('/'), _next_page))
if not is_safe(next_page):
raise Exception("Non-local url is forbidden to be redirected to.")
return next_page
def is_local_url(host_url, url):
| 64 | 64 | 174 | 9 | 54 | orbitvu/django-cas-ng | django_cas_ng/views.py | Python | is_local_url | is_local_url | 47 | 64 | 47 | 47 | 08727319e89261555778aba0207a833d16fd60c4 | bigcode/the-stack | train |
11056e608f40ff5e62f6da23 | train | function | def clean_sessions(client, request):
if not hasattr(client, 'get_saml_slos'):
return
for slo in client.get_saml_slos(request.POST.get('logoutRequest')):
try:
st = SessionTicket.objects.get(ticket=slo.text)
session = SessionStore(session_key=st.session_key)
# s... | def clean_sessions(client, request):
| if not hasattr(client, 'get_saml_slos'):
return
for slo in client.get_saml_slos(request.POST.get('logoutRequest')):
try:
st = SessionTicket.objects.get(ticket=slo.text)
session = SessionStore(session_key=st.session_key)
# send logout signal
cas_use... | gtid)
pgt.save()
ProxyGrantingTicket.objects.filter(
session_key=None,
date__lt=(timezone.now() - timedelta(seconds=60))
).delete()
return HttpResponse("{}\n".format(_('ok')), content_type="text/plain")
def clean_sessions(client, request):
| 64 | 64 | 163 | 7 | 57 | orbitvu/django-cas-ng | django_cas_ng/views.py | Python | clean_sessions | clean_sessions | 239 | 258 | 239 | 239 | 504c3ed53414233b3b84686d07598e7f3f734ad3 | bigcode/the-stack | train |
ba3e3e8f111cfc4ba23ca040 | train | class | class LoginView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def successful_login(self, request, next_page):
"""
This method is called on successful login. Override this method for
custo... | class LoginView(View):
@method_decorator(csrf_exempt)
| def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def successful_login(self, request, next_page):
"""
This method is called on successful login. Override this method for
custom post-auth actions (i.e, to add a cookie with a token).
... | .build_absolute_uri('/'), _next_page))
if not is_safe(next_page):
raise Exception("Non-local url is forbidden to be redirected to.")
return next_page
def is_local_url(host_url, url):
"""
:param host_url: is an absolute host url, say https://site.com/
:param url: is any url
:return: Is ... | 225 | 225 | 750 | 15 | 210 | orbitvu/django-cas-ng | django_cas_ng/views.py | Python | LoginView | LoginView | 67 | 168 | 67 | 68 | cec6241ed389ccb063abc047359ae9821fd44020 | bigcode/the-stack | train |
f1396dbb406e74819213969e | train | function | def clean_next_page(request, next_page):
"""
set settings.CAS_CHECK_NEXT to lambda _: True if you want to bypass this check.
"""
if not next_page:
return next_page
is_safe = getattr(settings, 'CAS_CHECK_NEXT',
lambda _next_page: is_local_url(request.build_absolute_uri('... | def clean_next_page(request, next_page):
| """
set settings.CAS_CHECK_NEXT to lambda _: True if you want to bypass this check.
"""
if not next_page:
return next_page
is_safe = getattr(settings, 'CAS_CHECK_NEXT',
lambda _next_page: is_local_url(request.build_absolute_uri('/'), _next_page))
if not is_safe(next... | get_cas_client,
get_protocol,
get_redirect_url,
get_service_url,
get_user_from_session,
)
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
__all__ = ['LoginView', 'LogoutView', 'CallbackView']
def clean_next_page(request, next_page):
| 64 | 64 | 101 | 9 | 55 | orbitvu/django-cas-ng | django_cas_ng/views.py | Python | clean_next_page | clean_next_page | 34 | 44 | 34 | 34 | 20f94c9e0424832d5d63badb03a235a48204a6ec | bigcode/the-stack | train |
64eb526a6ae2bcd2a693eba5 | train | class | class Migration(migrations.Migration):
dependencies = [
('swot_item', '0004_change_name_swot_item'),
]
operations = [
migrations.CreateModel(
name='Vote',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_n... | class Migration(migrations.Migration):
| dependencies = [
('swot_item', '0004_change_name_swot_item'),
]
operations = [
migrations.CreateModel(
name='Vote',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created',... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-02-26 02:55
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
| 61 | 66 | 222 | 7 | 53 | imranariffin/liveswot-api | swot_item/migrations/0005_auto_20180226_0255.py | Python | Migration | Migration | 9 | 40 | 9 | 9 | 71c1b249435009073683bc3015c360b1d4f4a1c7 | bigcode/the-stack | train |
6738a4d1b294ce97448c26af | train | class | class Program():
def __init__(self, img_folder):
self.images = []
names = os.listdir(img_folder)
for n in names:
img = cv2.imread(img_folder + n)
self.images.append(Image(img, n))
def start(self, at=0):
for i in range(at, len(self.images)):
with open(SEGMAP + self.images[i].base, 'w') as m: # open... | class Program():
| def __init__(self, img_folder):
self.images = []
names = os.listdir(img_folder)
for n in names:
img = cv2.imread(img_folder + n)
self.images.append(Image(img, n))
def start(self, at=0):
for i in range(at, len(self.images)):
with open(SEGMAP + self.images[i].base, 'w') as m: # open segmap file
... | import os
import sys
import cv2
import numpy as np
sys.path.insert(0, "..")
from models import Image
FRONT = "front/"
BACK = "back/"
SEGMAP = "segmap/"
# predetermined intervals from fixed font size to save my time
NUM_INTERVALS = [40, 45, 40, 50, 40, 50, 40]
DOB_INTERVALS = [25, 13, 27, 22, 13, 25, 25, 25]
class P... | 116 | 256 | 1,063 | 3 | 113 | trangnm58/idrec | all_data/generate_segmap.py | Python | Program | Program | 19 | 141 | 19 | 19 | 99b8e9208df604a9388de58ed0f630218d77f727 | bigcode/the-stack | train |
f51b988e07910fd106a6a73d | train | class | class QueuedMail(ObjectIDMixin, BaseModel):
user = models.ForeignKey('OSFUser', db_index=True, null=True)
to_addr = models.CharField(max_length=255)
send_at = NonNaiveDateTimeField(db_index=True, null=False)
# string denoting the template, presend to be used. Has to be an index of queue_mail types
... | class QueuedMail(ObjectIDMixin, BaseModel):
| user = models.ForeignKey('OSFUser', db_index=True, null=True)
to_addr = models.CharField(max_length=255)
send_at = NonNaiveDateTimeField(db_index=True, null=False)
# string denoting the template, presend to be used. Has to be an index of queue_mail types
email_type = models.CharField(max_length=255... | from django.db import models
from django.utils import timezone
from osf.utils.fields import NonNaiveDateTimeField
from website.mails import Mail, send_mail
from website.mails import presends
from website import settings as osf_settings
from osf.models.base import BaseModel, ObjectIDMixin
from osf.modm_compat import Q... | 102 | 179 | 597 | 11 | 90 | hmoco/osf.io | osf/models/queued_mail.py | Python | QueuedMail | QueuedMail | 14 | 75 | 14 | 14 | 22b5832d0f0dfe9ad81288d1ba8599ec74ac17a7 | bigcode/the-stack | train |
4a616b47d2f15bcdbabc2fc1 | train | function | def queue_mail(to_addr, mail, send_at, user, **context):
"""
Queue an email to be sent using send_mail after a specified amount
of time and if the presend returns True. The presend is attached to
the template under mail.
:param to_addr: the address email is to be sent to
:param mail: the type ... | def queue_mail(to_addr, mail, send_at, user, **context):
| """
Queue an email to be sent using send_mail after a specified amount
of time and if the presend returns True. The presend is attached to
the template under mail.
:param to_addr: the address email is to be sent to
:param mail: the type of mail. Struct following template:
... | those emails
"""
return self.__class__.find(
Q('email_type', 'eq', self.email_type) &
Q('user', 'eq', self.user) &
Q('sent_at', 'ne', None)
)
def queue_mail(to_addr, mail, send_at, user, **context):
| 68 | 68 | 228 | 16 | 52 | hmoco/osf.io | osf/models/queued_mail.py | Python | queue_mail | queue_mail | 78 | 104 | 78 | 78 | 59159fa5059f9e4cd67c59a5a80d5ace9663eb48 | bigcode/the-stack | train |
4499dd622bf5f743a11797d5 | train | function | def test_shell_read_data():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 4
$... | def test_shell_read_data():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 4
$TABLE: CHANNELS
! No Nam... | import datetime
import math
import pytest
import os
import ios_shell as shell
import ios_shell.sections as sections
def test_shell_read_data():
| 31 | 190 | 636 | 6 | 24 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_shell_read_data | test_shell_read_data | 10 | 75 | 10 | 10 | 818842dd088533f1cd67449f460f7753ea68d325 | bigcode/the-stack | train |
48355e8e7790a0728dc70437 | train | function | def test_get_obs_time_combined_date_time_column():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER ... | def test_get_obs_time_combined_date_time_column():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 3
$TABLE: CHANNELS
! No Nam... | *END OF HEADER
2015/03/28 10:36:00.00 14.00
2015/03/28 10:46:00.00 15.00
2015/03/28 10:56:00.00 16.00
2015/03/28 11:06:00.00 17.00"""
info = shell.ShellFile.fromcontents(contents, process_data=True)
obs_time = info.get_obs_time()
assert len(obs_time) == 4
def test_get_obs_time_combined_date_time_col... | 134 | 134 | 449 | 11 | 122 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_obs_time_combined_date_time_column | test_get_obs_time_combined_date_time_column | 727 | 769 | 727 | 727 | 17afd7fb148081a90ff8a4244357ab5cc2e57185 | bigcode/the-stack | train |
ca50fd0517fdf9b4c7510362 | train | function | def test_get_obs_time_date_and_time_columns():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF C... | def test_get_obs_time_date_and_time_columns():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 3
$TABLE: CHANNELS
! No Nam... | 223916E-01)",
},
],
"remarks": " words words words",
},
"deployment": {
"mission": "1930-01",
"type": "some type",
"time anchor dropped": "UTC 1930/01/01 00:00:00",
"remarks": " words words words",
... | 150 | 150 | 500 | 10 | 140 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_obs_time_date_and_time_columns | test_get_obs_time_date_and_time_columns | 680 | 724 | 680 | 680 | 6e1f47673d5034378a1208b4a91193b5b344503e | bigcode/the-stack | train |
c3e8eba842f6b9c8d8bd26a9 | train | function | def test_shell_init_does_the_right_thing():
some_date = datetime.datetime(1970, 1, 1)
some_delta = datetime.timedelta(minutes=30)
some_units = "Minutes"
filename = "thing.bot"
modified = some_date
version = sections.Version(
version_no="some version", date1="some date", date2="some other... | def test_shell_init_does_the_right_thing():
| some_date = datetime.datetime(1970, 1, 1)
some_delta = datetime.timedelta(minutes=30)
some_units = "Minutes"
filename = "thing.bot"
modified = some_date
version = sections.Version(
version_no="some version", date1="some date", date2="some other date"
)
file = sections.FileInfo(
... | ob",
"BP2_20130705_20130810_0114m.ctd",
"B515_19750812_19750901a_0002m.cur",
"cmp1_20160127_20160520_0193m.ctd",
"dev1_20150727_20160517_0152m.ctd",
"nep3_20061220_20070117_0093m.adcp",
"prc1_20190809_20200514_0037m.adcp",
],
)
def test_shell_fromfile_just_header(file... | 188 | 188 | 629 | 11 | 177 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_shell_init_does_the_right_thing | test_shell_init_does_the_right_thing | 155 | 270 | 155 | 155 | 36170871c45d5e0bedf0abdeb4aa3fab17854cd6 | bigcode/the-stack | train |
a0ba479e81522b923fe484e1 | train | function | def test_get_obs_time_fails_when_start_times_mismatch():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
N... | def test_get_obs_time_fails_when_start_times_mismatch():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 3
$TABLE: CHANNELS
! No Nam... | R4 2
$END
*ADMINISTRATION
MISSION : 1993-001
*LOCATION
LATITUDE : 50 6.00000 N ! (deg min)
LONGITUDE : 124 54.00000 W ! (deg min)
*COMMENTS
words words words
*END OF HEADER
14.00
15.00
16.00
17.00"""
info = shell.ShellFile.fromcontents(contents, p... | 151 | 151 | 506 | 13 | 137 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_obs_time_fails_when_start_times_mismatch | test_get_obs_time_fails_when_start_times_mismatch | 903 | 950 | 903 | 903 | 9d47d2da2da31b808834c49572cd851cb317e7c3 | bigcode/the-stack | train |
640f3efdad531984826f4161 | train | function | def test_shell_fills_empty_cells():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : ... | def test_shell_fills_empty_cells():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 4
$TABLE: CHANNELS
! No Nam... |
LATITUDE : 50 6.00000 N ! (deg min)
LONGITUDE : 124 54.00000 W ! (deg min)
*COMMENTS
words words words
*END OF HEADER
2015/03/28 10:36:00.00 14.00
2015/03/28 10:46:00.00 15.00
2015/03/28 10:56:00.00 16.00
2015/03/28 11:06:00.00 17.00"""
info_no_data = shell.ShellFile.fr... | 256 | 256 | 991 | 8 | 248 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_shell_fills_empty_cells | test_shell_fills_empty_cells | 1,055 | 1,146 | 1,055 | 1,055 | c1a9cfedf9a3d518226d5297fc44e91f71dca2b4 | bigcode/the-stack | train |
fce40e5d16e67ba57ff62c00 | train | function | def test_get_complete_header_non_optional_sections():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMB... | def test_get_complete_header_non_optional_sections():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 4
$TABLE: CHANNELS
! No Nam... | TABLE: CHANNEL DETAIL
! No Pad Start Width Format Type Decimal_Places
!--- ---- ----- ----- ------ ---- --------------
1 -99 ' ' 6 F R4 0
2 -99 ' ' 5 I I 0
3 -99 ' ' 7 F R4 2
4 ' ' ' ' 3 NQ ... | 256 | 256 | 1,069 | 9 | 247 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_complete_header_non_optional_sections | test_get_complete_header_non_optional_sections | 323 | 450 | 323 | 323 | 121127108d8c7f052880d9428f7b9bf358a196cc | bigcode/the-stack | train |
5b3f075b2c00c92146963623 | train | function | @pytest.mark.parametrize(
"file_name",
[
"2008-007-0002.tob",
"BP2_20130705_20130810_0114m.ctd",
"B515_19750812_19750901a_0002m.cur",
"cmp1_20160127_20160520_0193m.ctd",
"dev1_20150727_20160517_0152m.ctd",
"nep3_20061220_20070117_0093m.adcp",
"prc1_2019080... | @pytest.mark.parametrize(
"file_name",
[
"2008-007-0002.tob",
"BP2_20130705_20130810_0114m.ctd",
"B515_19750812_19750901a_0002m.cur",
"cmp1_20160127_20160520_0193m.ctd",
"dev1_20150727_20160517_0152m.ctd",
"nep3_20061220_20070117_0093m.adcp",
"prc1_2019080... | full_file_name = os.path.join(os.path.dirname(__file__), "data", file_name)
info = shell.ShellFile.fromfile(full_file_name, process_data=False)
assert not info.data_is_processed()
| @pytest.mark.parametrize(
"file_name",
[
"2008-007-0002.tob",
"BP2_20130705_20130810_0114m.ctd",
"B515_19750812_19750901a_0002m.cur",
"cmp1_20160127_20160520_0193m.ctd",
"dev1_20150727_20160517_0152m.ctd",
"nep3_20061220_20070117_0093m.adcp",
"prc1_2019080... | 153 | 64 | 198 | 153 | 0 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_shell_fromfile_just_header | test_shell_fromfile_just_header | 137 | 152 | 137 | 149 | 47dce7c8f6419dc9333a68c52f4366cd65418bd4 | bigcode/the-stack | train |
20aaa266c8fc8be381d64f00 | train | function | @pytest.mark.parametrize(
"file_name",
[
"00200001.med",
"1930-031-0001.bot",
"1930-031-0010.bot",
"1930-099-0001.bot",
"1930-003-0058.bot",
"1933-001-0001.bot",
"1933-001-0004.bot",
"1938-019-0001.bot",
"1950-001-0033.bot",
"1950-0... | @pytest.mark.parametrize(
"file_name",
[
"00200001.med",
"1930-031-0001.bot",
"1930-031-0010.bot",
"1930-099-0001.bot",
"1930-003-0058.bot",
"1933-001-0001.bot",
"1933-001-0004.bot",
"1938-019-0001.bot",
"1950-001-0033.bot",
"1950-0... | full_file_name = os.path.join(os.path.dirname(__file__), "data", file_name)
info = shell.ShellFile.fromfile(full_file_name, process_data=False)
assert not info.data_is_processed()
info.process_data()
assert isinstance(info.data, list)
assert info.data_is_processed()
info = shell.ShellFile.f... | @pytest.mark.parametrize(
"file_name",
[
"00200001.med",
"1930-031-0001.bot",
"1930-031-0010.bot",
"1930-099-0001.bot",
"1930-003-0058.bot",
"1933-001-0001.bot",
"1933-001-0004.bot",
"1938-019-0001.bot",
"1950-001-0033.bot",
"1950-0... | 456 | 167 | 558 | 456 | 0 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_shell_fromfile | test_shell_fromfile | 78 | 133 | 78 | 123 | d65fe816f6be8cddb321d0043d1cf50a73bdead2 | bigcode/the-stack | train |
e8ebb7be8c0db5bd49561dc7 | train | function | def test_get_obs_time_from_increment_value():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
TIME INCREME... | def test_get_obs_time_from_increment_value():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
TIME INCREMENT : 0 0 10 0 0 ! (day hr min sec msec)
... | ---- --------------
1 -99 ' ' ' ' HH:MM DT ' '
2 -99 ' ' 7 F R4 2
$END
*ADMINISTRATION
MISSION : 1993-001
*LOCATION
LATITUDE : 50 6.00000 N ! (deg min)
LONGITUDE : 124 54.00000 W ! (deg min)
*COMMENTS
words wo... | 232 | 232 | 775 | 9 | 222 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_obs_time_from_increment_value | test_get_obs_time_from_increment_value | 772 | 854 | 772 | 772 | 503ee83c0e320598a8430050586bac5b8bea0edb | bigcode/the-stack | train |
83b1ebf42f2729220f019909 | train | function | def test_process_data_fails_on_invalid_data():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 2
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF C... | def test_process_data_fails_on_invalid_data():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 2
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 4
$TABLE: CHANNELS
! No Nam... | deployment=deployment,
recovery=recovery,
raw=raw,
comments=comments,
data=data,
)
assert info.filename == filename
assert info.modified_date == modified
assert info.header_version == version
assert info.file == file
assert info.administration == administ... | 140 | 140 | 467 | 10 | 129 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_process_data_fails_on_invalid_data | test_process_data_fails_on_invalid_data | 273 | 320 | 273 | 273 | 78da9699f9d04c598d1e39969af110c669063be4 | bigcode/the-stack | train |
ca5730d7dd83abfc3d452cf6 | train | function | def test_get_complete_header_optional_sections():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER O... | def test_get_complete_header_optional_sections():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/16 10:36:00.000
NUMBER OF RECORDS : 1
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 1
$TABLE: CHANNELS
! No Nam... | "' ' ",
"width": " 5",
"format": "I ",
"type": "I ",
"decimal_places": " 0 ",
},
{
"no": " 3",
"pad": "-99 ",
"start": "' ' ... | 256 | 256 | 1,739 | 8 | 248 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_complete_header_optional_sections | test_get_complete_header_optional_sections | 453 | 677 | 453 | 453 | f70de579524d863c4d0b3f196ed0b203fa277f36 | bigcode/the-stack | train |
2590383c99b44be8c44406c3 | train | function | def test_get_obs_time_date_no_time_columns():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CH... | def test_get_obs_time_date_no_time_columns():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 3
$TABLE: CHANNELS
! No Nam... | HEADER
2016/03/28 10:36:00.00 14.00
2016/03/28 10:46:00.00 15.00
2016/03/28 10:56:00.00 16.00
2016/03/28 11:06:00.00 17.00"""
info = shell.ShellFile.fromcontents(contents, process_data=True)
try:
obs_time = info.get_obs_time()
assert False
except:
pass
def test_get_obs_time_... | 133 | 133 | 445 | 10 | 122 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_obs_time_date_no_time_columns | test_get_obs_time_date_no_time_columns | 953 | 998 | 953 | 953 | f119b090b043ea8a3f7a828d39c9b321314cfe33 | bigcode/the-stack | train |
e7f8726ceb8690f72785930a | train | function | @pytest.mark.pandas
def test_to_pandas():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNE... | @pytest.mark.pandas
def test_to_pandas():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 3
$TABLE: CHANNELS
! No Nam... | : 1993-001
*LOCATION
LATITUDE : 50 6.00000 N ! (deg min)
LONGITUDE : 124 54.00000 W ! (deg min)
*COMMENTS
words words words
*END OF HEADER
2015/03/28 14.00
2015/03/28 15.00
2015/03/28 16.00
2015/03/28 17.00"""
info = shell.ShellFile.fromcontents(contents, process_data=... | 173 | 173 | 577 | 11 | 161 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_to_pandas | test_to_pandas | 1,001 | 1,052 | 1,001 | 1,002 | 5584e4d3072eac92c4895f7c1f933671e06c0237 | bigcode/the-stack | train |
5d3dc4af8fe0afb0791bd04c | train | function | def test_get_obs_time_fails_without_increment_value():
contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUM... | def test_get_obs_time_fails_without_increment_value():
| contents = """*2018/06/22 09:04:04.94
*IOS HEADER VERSION 2.0 2016/04/28 2016/06/13 IVF16
*FILE
START TIME : UTC 2015/03/28 10:36:00.000
NUMBER OF RECORDS : 4
DATA DESCRIPTION : Bottle:Wire
FILE TYPE : ASCII
NUMBER OF CHANNELS : 3
$TABLE: CHANNELS
! No Nam... | 3-001
*LOCATION
LATITUDE : 50 6.00000 N ! (deg min)
LONGITUDE : 124 54.00000 W ! (deg min)
*COMMENTS
words words words
*END OF HEADER
17.00"""
info = shell.ShellFile.fromcontents(contents, process_data=True)
obs_time = info.get_obs_time()
assert len(obs_time) == 1
def ... | 110 | 110 | 368 | 11 | 98 | cyborgsphinx/ios-shell | tests/shell_test.py | Python | test_get_obs_time_fails_without_increment_value | test_get_obs_time_fails_without_increment_value | 857 | 900 | 857 | 857 | 99d3ca8c2b1c28057accdfb7f45eb1dfe46344c2 | bigcode/the-stack | train |
ee4e3984d9ca123098e9a33d | train | class | class User(object):
"""
Represents the user registered to the device initiating the request.
:param user_id: A string that represents a unique identifier for the user who made the request. The length of this identifier can vary, but is never more than 255 characters. The userId is automatically generated ... | class User(object):
| """
Represents the user registered to the device initiating the request.
:param user_id: A string that represents a unique identifier for the user who made the request. The length of this identifier can vary, but is never more than 255 characters. The userId is automatically generated when a user enables ... | # coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... | 195 | 256 | 884 | 4 | 190 | ReciPull/reciprogram | Non-React Stuff/alexa/lambda/skill_env/ask_sdk_model/user.py | Python | User | User | 29 | 122 | 29 | 29 | 171c665765ca440458f52453922931c5feeda3a5 | bigcode/the-stack | train |
6a3587034a7773f058e27941 | train | class | @typing_extensions.runtime
class Logger(typing_extensions.Protocol):
def write(self, data: Mapping[str, Any]) -> None:
pass
| @typing_extensions.runtime
class Logger(typing_extensions.Protocol):
| def write(self, data: Mapping[str, Any]) -> None:
pass
| 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.
"""The Logger type."""
from typing import Any, Mapping
import typing_extensions
@typing_extensions.runtime
class Logger(typing_e... | 64 | 64 | 30 | 12 | 51 | wx-b/dm_robotics | py/agentflow/loggers/types.py | Python | Logger | Logger | 21 | 25 | 21 | 23 | e9486698b4a296d1c0350edf3341fbc50b3943a2 | bigcode/the-stack | train |
89f85bd883df2bfb1bd98ed6 | train | function | def packages_example_setup_workspace():
"""Node repositories for @packages_examples
"""
npm_install(
name = "packages_example_npm_install",
package_json = "@packages_example//:package.json",
package_lock_json = "@packages_example//:package-lock.json",
data = ["@packages_examp... | def packages_example_setup_workspace():
| """Node repositories for @packages_examples
"""
npm_install(
name = "packages_example_npm_install",
package_json = "@packages_example//:package.json",
package_lock_json = "@packages_example//:package-lock.json",
data = ["@packages_example//:postinstall.js"],
# Just he... | 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.
"""Helper function to setup @package_example worksp... | 92 | 92 | 308 | 6 | 86 | renovate-tests/rules_nodejs | internal/e2e/packages/setup_workspace.bzl | Python | packages_example_setup_workspace | packages_example_setup_workspace | 20 | 57 | 20 | 20 | bffb7f83727979cd1275e47e5563164984c328c9 | bigcode/the-stack | train |
ec32290c2c7d18d158f7f360 | train | class | class ARProvinceSelect(Select):
"""
A Select widget that uses a list of Argentinean provinces/autonomous cities
as its choices.
"""
def __init__(self, attrs=None):
super(ARProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
| class ARProvinceSelect(Select):
| """
A Select widget that uses a list of Argentinean provinces/autonomous cities
as its choices.
"""
def __init__(self, attrs=None):
super(ARProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
| _import, unicode_literals
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, CharField, Select
from django.utils.translation import ugettext_lazy as _
from .ar_provinces import PROVINCE_CHOICES
class ARProvinceSelect(Select):
| 64 | 64 | 63 | 7 | 56 | stephendwolff/django-localflavor | localflavor/ar/forms.py | Python | ARProvinceSelect | ARProvinceSelect | 16 | 22 | 16 | 16 | 51e94dd376edb1becbd73540060bee06333375c9 | bigcode/the-stack | train |
7b5802ac359c3d016819d395 | train | class | class ARCUITField(RegexField):
"""
This field validates a CUIT (Código Único de Identificación Tributaria). A
CUIT is of the form XX-XXXXXXXX-V. The last digit is a check digit.
More info:
http://es.wikipedia.org/wiki/Clave_%C3%9Anica_de_Identificaci%C3%B3n_Tributaria
English info:
http://... | class ARCUITField(RegexField):
| """
This field validates a CUIT (Código Único de Identificación Tributaria). A
CUIT is of the form XX-XXXXXXXX-V. The last digit is a check digit.
More info:
http://es.wikipedia.org/wiki/Clave_%C3%9Anica_de_Identificaci%C3%B3n_Tributaria
English info:
http://www.justlanded.com/english/Arge... | ': _("This field requires 7 or 8 digits."),
}
def __init__(self, max_length=10, min_length=7, *args, **kwargs):
super(ARDNIField, self).__init__(max_length, min_length,
*args, **kwargs)
def clean(self, value):
"""
Value can be a string eithe... | 189 | 189 | 633 | 9 | 179 | stephendwolff/django-localflavor | localflavor/ar/forms.py | Python | ARCUITField | ARCUITField | 83 | 139 | 83 | 83 | 7ac6f82c59bb946d30e5dc709f788be53699475b | bigcode/the-stack | train |
877a976e3342d0c0ff8ed170 | train | class | class ARPostalCodeField(RegexField):
"""
A field that accepts a 'classic' NNNN Postal Code or a CPA.
See:
http://www.correoargentino.com.ar/cpa/que_es
http://www.correoargentino.com.ar/cpa/como_escribirlo
"""
default_error_messages = {
'invalid': _("Enter a postal code in th... | class ARPostalCodeField(RegexField):
| """
A field that accepts a 'classic' NNNN Postal Code or a CPA.
See:
http://www.correoargentino.com.ar/cpa/que_es
http://www.correoargentino.com.ar/cpa/como_escribirlo
"""
default_error_messages = {
'invalid': _("Enter a postal code in the format NNNN or ANNNNAAA."),
}
... | vinces import PROVINCE_CHOICES
class ARProvinceSelect(Select):
"""
A Select widget that uses a list of Argentinean provinces/autonomous cities
as its choices.
"""
def __init__(self, attrs=None):
super(ARProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
class ARPostalCodeField... | 81 | 81 | 271 | 9 | 72 | stephendwolff/django-localflavor | localflavor/ar/forms.py | Python | ARPostalCodeField | ARPostalCodeField | 25 | 50 | 25 | 25 | 231c6e429d7f1566bf1bd348911594c87fc39635 | bigcode/the-stack | train |
73176d4556d0b50bab2503ab | train | class | class ARDNIField(CharField):
"""
A field that validates 'Documento Nacional de Identidad' (DNI) numbers.
"""
default_error_messages = {
'invalid': _("This field requires only numbers."),
'max_digits': _("This field requires 7 or 8 digits."),
}
def __init__(self, max_length=10, m... | class ARDNIField(CharField):
| """
A field that validates 'Documento Nacional de Identidad' (DNI) numbers.
"""
default_error_messages = {
'invalid': _("This field requires only numbers."),
'max_digits': _("This field requires 7 or 8 digits."),
}
def __init__(self, max_length=10, min_length=7, *args, **kwargs)... | len(value) not in (4, 8):
raise ValidationError(self.error_messages['invalid'])
if len(value) == 8:
return '%s%s%s' % (value[0].upper(), value[1:5], value[5:].upper())
return value
class ARDNIField(CharField):
| 69 | 69 | 231 | 8 | 60 | stephendwolff/django-localflavor | localflavor/ar/forms.py | Python | ARDNIField | ARDNIField | 53 | 80 | 53 | 53 | f65aad7bd83c0dcffe88402d4b18fe5d4ed9bbb4 | bigcode/the-stack | train |
365d5d96b92ffd8f6d4dbef5 | train | function | def py_ast_to_generic(tree):
"""Convert a gast AST node to a generic representation.
IDs are set based on the python `id` of the AST node. Only children that are
AST nodes or lists of AST nodes will be processed.
Args:
tree: Node of the AST to convert.
Returns:
Generic representation of the AST.
... | def py_ast_to_generic(tree):
| """Convert a gast AST node to a generic representation.
IDs are set based on the python `id` of the AST node. Only children that are
AST nodes or lists of AST nodes will be processed.
Args:
tree: Node of the AST to convert.
Returns:
Generic representation of the AST.
"""
fields = {}
for field... | "kw_defaults": generic_ast_graphs.FieldType.NO_CHILDREN,
"kwarg": generic_ast_graphs.FieldType.NO_CHILDREN,
"defaults": generic_ast_graphs.FieldType.NO_CHILDREN
},
sequence_item_types={"args": "arguments_args"}),
}
def py_ast_to_generic(tree):
| 64 | 64 | 205 | 7 | 57 | gunpowder78/google-research | gfsa/py_ast_graphs.py | Python | py_ast_to_generic | py_ast_to_generic | 207 | 232 | 207 | 207 | 57ee724a0defe7341bf8b5ffe17a2eac0b10f9d9 | bigcode/the-stack | train |
51763413b4589b952f7a2013 | train | function | def py_ast_to_graph(
tree):
"""Convert an unsimplified AST into a graph, with a forward mapping.
Args:
tree: The (unsimplified) AST for the program.
Returns:
- Graph representing the tree.
- Dictionary that maps from AST node ids to graph node ids.
"""
return generic_ast_graphs.ast_to_graph(... | def py_ast_to_graph(
tree):
| """Convert an unsimplified AST into a graph, with a forward mapping.
Args:
tree: The (unsimplified) AST for the program.
Returns:
- Graph representing the tree.
- Dictionary that maps from AST node ids to graph node ids.
"""
return generic_ast_graphs.ast_to_graph(
root=py_ast_to_generic(tr... | _id=id(tree), node_type=type(tree).__name__, fields=fields)
# Default definitions used elsewhere
SCHEMA = generic_ast_graphs.build_ast_graph_schema(PY_AST_SPECS)
BUILDER = automaton_builder.AutomatonBuilder(SCHEMA)
def py_ast_to_graph(
tree):
| 64 | 64 | 104 | 9 | 55 | gunpowder78/google-research | gfsa/py_ast_graphs.py | Python | py_ast_to_graph | py_ast_to_graph | 240 | 254 | 240 | 241 | 6c837badc149a60c747085361fc2b819ad5ca6ec | bigcode/the-stack | train |
71ab137da3968d3d63877ebb | train | function | def message(self):
pop = Popup(text=self.text)
| def message(self):
| pop = Popup(text=self.text)
| .src = src
c.type = 0x8863
c.payload.code = 0xa7
c.payload.sessionid = i
c.payload.len = 0
sendp(c,iface='Realtek PCIe GbE Family Controller', verbose=0)
def message(self):
| 64 | 64 | 12 | 4 | 60 | haohaoget/buildozer | main.py | Python | message | message | 26 | 27 | 26 | 26 | d8302064079eac03ab790d09b6deab265b08d96e | bigcode/the-stack | train |
56a7ee257ecf7c6795432c13 | train | class | class TextInputApp(App):
def build(self):
layout = BoxLayout(orientation='vertical', spacing=15, padding=10)
self.text=TextInput(font_size=50) # font_size输入文本框大小
self.out_text=TextInput(font_size=50)
button = Button(text="Run", size_hint=(0.5, 0.5),
pos_hint={... | class TextInputApp(App):
| def build(self):
layout = BoxLayout(orientation='vertical', spacing=15, padding=10)
self.text=TextInput(font_size=50) # font_size输入文本框大小
self.out_text=TextInput(font_size=50)
button = Button(text="Run", size_hint=(0.5, 0.5),
pos_hint={"center_x":0.5, "center_y... | c.dst = mac
c.src = src
c.type = 0x8863
c.payload.code = 0xa7
c.payload.sessionid = i
c.payload.len = 0
sendp(c,iface='Realtek PCIe GbE Family Controller', verbose=0)
def message(self):
pop = Popup(text=self.text)
class TextInputApp(App):
| 86 | 86 | 288 | 6 | 80 | haohaoget/buildozer | main.py | Python | TextInputApp | TextInputApp | 29 | 56 | 29 | 29 | 847f96a04f6029cd0e050a066e546f1efdeb735c | bigcode/the-stack | train |
b64a4c062e2bfd947e816e45 | train | function | def st(mac):
for i in range(6553):
c = Ether() / PPPoE()
c.dst = mac
c.src = src
c.type = 0x8863
c.payload.code = 0xa7
c.payload.sessionid = i
c.payload.len = 0
sendp(c,iface='Realtek PCIe GbE Family Controller', verbose=0)
| def st(mac):
| for i in range(6553):
c = Ether() / PPPoE()
c.dst = mac
c.src = src
c.type = 0x8863
c.payload.code = 0xa7
c.payload.sessionid = i
c.payload.len = 0
sendp(c,iface='Realtek PCIe GbE Family Controller', verbose=0)
| import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from math import *
from scapy.all import *
ipscan='10.0.2.1/24'
src = os.environ["SRC"]
dst = os.environ["DST"]
def st(mac):
| 64 | 64 | 91 | 4 | 60 | haohaoget/buildozer | main.py | Python | st | st | 15 | 24 | 15 | 15 | 0f27bd3357acb3d13b59b615c03856b5aaa6b44e | bigcode/the-stack | train |
f8f309bb726338adc55f5e67 | train | class | class UserInstanceEndpoint:
'''User instance resource. Must be routed with a UUID parameter.'''
@with_session
@authenticate
def on_put(self, req, resp, sess, user, id=None):
'''Update user details.'''
# Assert authz.
if user.type != 'admin' and user.id != id:
raise Unauthorized(message="You can't do that"... | class UserInstanceEndpoint:
| '''User instance resource. Must be routed with a UUID parameter.'''
@with_session
@authenticate
def on_put(self, req, resp, sess, user, id=None):
'''Update user details.'''
# Assert authz.
if user.type != 'admin' and user.id != id:
raise Unauthorized(message="You can't do that")
# Retrieve user to edit... | as ex:
# Return a relevant error description.
desc = get_error_description(ex, CONSTRAINT_DESC_MAP)
raise UnprocessableEntity(message=desc) from None
# Authenticate and persist.
user.authorize_session(resp, sess)
sess.commit()
# Respond.
resp.status = 201
resp.json = {'created_id': user.id}
cla... | 88 | 88 | 294 | 5 | 83 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | UserInstanceEndpoint | UserInstanceEndpoint | 271 | 308 | 271 | 271 | 81e3ae3944d7bb306c48cac7ed8f6091be066260 | bigcode/the-stack | train |
3cfc762bc98de9b70a18ce9a | train | class | class UserCollectionEndpoint:
'''User creation and collection retrieval for admins.'''
@with_session
def on_post(self, req, resp, sess):
'''Create a user given a JSON payload in the request.'''
# Assert password confirmation.
password = req.json[('password', str)]
if password != req.json['confirm_password']... | class UserCollectionEndpoint:
| '''User creation and collection retrieval for admins.'''
@with_session
def on_post(self, req, resp, sess):
'''Create a user given a JSON payload in the request.'''
# Assert password confirmation.
password = req.json[('password', str)]
if password != req.json['confirm_password']:
raise UnprocessableEntity... | the unexpired, unused reset token with key `key`. The caller
must mark the key as used.'''
return sess.query(cls).filter(query_and(
cls.key == key, cls.expiry > datetime.now(), cls.used == False
)).first()
# Endpoints.
class UserCollectionEndpoint:
| 68 | 68 | 227 | 5 | 63 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | UserCollectionEndpoint | UserCollectionEndpoint | 237 | 269 | 237 | 237 | c56491497b58d11af6293f0d9826993bb9aa5073 | bigcode/the-stack | train |
da20471a9bbc6721ceb4b576 | train | class | class AuthResource:
'''The authentication endpoint for inspection, login, and logout.'''
@with_session
def on_get(self, req, resp, sess):
'''Return a JSON playload that describes the currently authenticated
user under its "user" key.'''
user = User.get_authenticated(req, sess)
# Maybe include visitor sessi... | class AuthResource:
| '''The authentication endpoint for inspection, login, and logout.'''
@with_session
def on_get(self, req, resp, sess):
'''Return a JSON playload that describes the currently authenticated
user under its "user" key.'''
user = User.get_authenticated(req, sess)
# Maybe include visitor session.
if req.params.... | )]:
raise Unauthorized(message='Incorrect password')
password, confirm = (
req.json[('password', str)], req.json['confirm_password']
)
if password != confirm:
raise UnprocessableEntity(message="Passwords didn't match")
# Set new password.
to_edit.password = password
# XXX: Add project-spec... | 130 | 130 | 436 | 4 | 125 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | AuthResource | AuthResource | 310 | 365 | 310 | 310 | 72dacb4d1adbec297a9f578dcee8acd1fd50eb3f | bigcode/the-stack | train |
2f87cfb6d48f906e969c3fd0 | train | function | def authenticate(*args, **kwargs):
'''A decorator that adds an authentication precondition to a responder.
Must follow the `db.with_session` decorator. The keyword argument `authz`
can specify an authorization requirement. If it isn't, the decorator
should be used without a call.'''
# Define the extender.
def met... | def authenticate(*args, **kwargs):
| '''A decorator that adds an authentication precondition to a responder.
Must follow the `db.with_session` decorator. The keyword argument `authz`
can specify an authorization requirement. If it isn't, the decorator
should be used without a call.'''
# Define the extender.
def meth_extender(meth):
'''Extend a met... | **config.security.session_timeout.__data
)
def _password_reset_timeout_generator():
'''A password reset token timeout schedule generator.'''
return datetime.now() + timedelta(
**config.security.password_reset_grace.__data
)
# pylint: enable=protected-access
# Decorator.
def authenticate(*args, **kwargs):
| 71 | 71 | 238 | 8 | 63 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | authenticate | authenticate | 40 | 67 | 40 | 40 | 09353c84c5370b104033e4e3bf6c7b6d09205849 | bigcode/the-stack | train |
1e05460e1fdc560778a3b9fe | train | class | class PasswordTokenCollection:
'''Password reset machinery. POST to create token, PUT to use.'''
@with_session
def on_put(self, req, resp, sess):
'''Reset the password of the user to which the token supplied in the
request JSON is associated. The JSON must also include a new
password.'''
# Parse request bod... | class PasswordTokenCollection:
| '''Password reset machinery. POST to create token, PUT to use.'''
@with_session
def on_put(self, req, resp, sess):
'''Reset the password of the user to which the token supplied in the
request JSON is associated. The JSON must also include a new
password.'''
# Parse request body.
token_key = req.json[('res... | # Retrieve the session key and assert it exists.
cookie_key = config.client_keys.auth_cookie_key
auth_tkn = req.cookies.get(cookie_key)
if not auth_tkn:
raise Unauthorized()
# Retrieve the user session and assert it exists.
user_session = UserSession.get_by_key(auth_tkn, sess)
if not user_session:
... | 129 | 129 | 431 | 5 | 124 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | PasswordTokenCollection | PasswordTokenCollection | 368 | 425 | 368 | 368 | cd47253f467fbac5f42bf8bc7cb70592e024a9af | bigcode/the-stack | train |
a99fd5d27220e1a00647cb7d | train | function | def _password_reset_timeout_generator():
'''A password reset token timeout schedule generator.'''
return datetime.now() + timedelta(
**config.security.password_reset_grace.__data
)
| def _password_reset_timeout_generator():
| '''A password reset token timeout schedule generator.'''
return datetime.now() + timedelta(
**config.security.password_reset_grace.__data
)
| .
log = logger(__name__)
# Internal helpers.
# pylint: disable=protected-access
def _session_timeout_generator():
'''An authentication session timeout schedule generator.'''
return datetime.now() + timedelta(
**config.security.session_timeout.__data
)
def _password_reset_timeout_generator():
| 64 | 64 | 39 | 7 | 57 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | _password_reset_timeout_generator | _password_reset_timeout_generator | 32 | 36 | 32 | 32 | 8523ecc24ec6a479f1fe43fb0f76aec324a5a67a | bigcode/the-stack | train |
e3ecc5f678fe9a4635a0837f | train | class | class UserSession(Model):
'''A `UserSession` is an expiring token based authentication scheme. The
key of a user's current authentication session is stored in their cookie
session.
This class should almost never be referenced directly; use the
`@authenticate` decorator for everyday needs.'''
# Describe table.
# ... | class UserSession(Model):
| '''A `UserSession` is an expiring token based authentication scheme. The
key of a user's current authentication session is stored in their cookie
session.
This class should almost never be referenced directly; use the
`@authenticate` decorator for everyday needs.'''
# Describe table.
# pylint: disable=bad-contin... | .development.debug, path='/'
)
def dictize(self, user): # pylint: disable=unused-argument
'''Return a dictization of the user.'''
# Don't expose sensitive info!
if not user or not (user is self or user.type == 'admin'):
raise SecurityError()
return dictize_attrs(self, user, (
'id', 'type', 'email_add... | 108 | 108 | 362 | 5 | 103 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | UserSession | UserSession | 169 | 208 | 169 | 169 | 6a6add5eeb703b6e4951ebbcd802ce62fd72470a | bigcode/the-stack | train |
814a061cb6bc137c570e98b2 | train | function | def _session_timeout_generator():
'''An authentication session timeout schedule generator.'''
return datetime.now() + timedelta(
**config.security.session_timeout.__data
)
| def _session_timeout_generator():
| '''An authentication session timeout schedule generator.'''
return datetime.now() + timedelta(
**config.security.session_timeout.__data
)
| of allowed user types.
ALLOWED_USER_TYPES = ('basic', 'admin')
CONSTRAINT_DESC_MAP = {'email_address': 'That email address is taken'}
# Create a logger.
log = logger(__name__)
# Internal helpers.
# pylint: disable=protected-access
def _session_timeout_generator():
| 64 | 64 | 35 | 6 | 57 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | _session_timeout_generator | _session_timeout_generator | 27 | 31 | 27 | 27 | 91c6555c422341bbf9dd04dbd036db3d894dcf99 | bigcode/the-stack | train |
209033ca80d682c9daa405df | train | class | class PasswordResetToken(Model):
'''Password reset tokens are sent in links to account emails.'''
# Describe table.
# pylint: disable=bad-continuation, bad-whitespace
__tablename__ = 'password_reset_tokens'
key = PrimaryKeyColumn()
expiry = Column(DateTime(), nullable=False, \
default=_password... | class PasswordResetToken(Model):
| '''Password reset tokens are sent in links to account emails.'''
# Describe table.
# pylint: disable=bad-continuation, bad-whitespace
__tablename__ = 'password_reset_tokens'
key = PrimaryKeyColumn()
expiry = Column(DateTime(), nullable=False, \
default=_password_reset_timeout_generator)
user_i... | a query condition specifying a session that is not expired.'''
return query_and(cls.expiry >= datetime.now(), cls.canceled == False)
def cancel(self):
'''Cancel this session. Once a session is canceled, the authentication
API will never expose that session again.'''
self.canceled = True
class PasswordResetTo... | 73 | 73 | 244 | 6 | 66 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | PasswordResetToken | PasswordResetToken | 210 | 234 | 210 | 210 | d2a4a0f3943fdedd8efdb5952428ccaad5f4caef | bigcode/the-stack | train |
0748056d53d08a74836a01e4 | train | class | class User(Model):
'''A user.'''
# Describe table.
# pylint: disable=bad-continuation, bad-whitespace
__tablename__ = 'users'
id = PrimaryKeyColumn()
type = Column(Enum(
*ALLOWED_USER_TYPES, name='user_types'
), nullable=False, default='basic')
email_address = Column(EmailType... | class User(Model):
| '''A user.'''
# Describe table.
# pylint: disable=bad-continuation, bad-whitespace
__tablename__ = 'users'
id = PrimaryKeyColumn()
type = Column(Enum(
*ALLOWED_USER_TYPES, name='user_types'
), nullable=False, default='basic')
email_address = Column(EmailType(), unique=True, nu... | ):
'''A decorator that adds an authentication precondition to a responder.
Must follow the `db.with_session` decorator. The keyword argument `authz`
can specify an authorization requirement. If it isn't, the decorator
should be used without a call.'''
# Define the extender.
def meth_extender(meth):
'''Extend a ... | 239 | 239 | 798 | 4 | 235 | StonebreakerDesigns/project-boilerplate | api/domain/users.py | Python | User | User | 70 | 167 | 70 | 70 | 98e5bc9c3bb93d12ccbc38192b93f77cb62799f4 | bigcode/the-stack | train |
459d2acc9753a05998ed0ed2 | train | function | def _register_module():
import pulumi
from .. import _utilities
class Module(pulumi.runtime.ResourceModule):
_version = _utilities.get_semver_version()
def version(self):
return Module._version
def construct(self, name: str, typ: str, urn: str) -> pulumi.Resource:
... | def _register_module():
| import pulumi
from .. import _utilities
class Module(pulumi.runtime.ResourceModule):
_version = _utilities.get_semver_version()
def version(self):
return Module._version
def construct(self, name: str, typ: str, urn: str) -> pulumi.Resource:
if typ == "aws:... | coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from .portfolio import *
def _register_module():
| 64 | 64 | 141 | 5 | 59 | sibuthomasmathew/pulumi-aws | sdk/python/pulumi_aws/servicecatalog/__init__.py | Python | _register_module | _register_module | 8 | 27 | 8 | 8 | b523bceed4f6742205acb167259486048140476c | bigcode/the-stack | train |
a91a5ad2caf802a856079011 | train | class | @dataclass(frozen=True)
@streamable
class SpendBundle(Streamable):
"""
This is a list of coins being spent along with their solution programs, and a single
aggregated signature. This is the object that most closely corresponds to a bitcoin
transaction (although because of non-interactive signature aggre... | @dataclass(frozen=True)
@streamable
class SpendBundle(Streamable):
| """
This is a list of coins being spent along with their solution programs, and a single
aggregated signature. This is the object that most closely corresponds to a bitcoin
transaction (although because of non-interactive signature aggregation, the boundaries
between transactions are more flexible t... | from dataclasses import dataclass
from typing import List
from src.types.coin import Coin
from src.types.sized_bytes import bytes32
from src.util.chain_utils import additions_for_solution
from src.util.streamable import Streamable, streamable
from .BLSSignature import BLSSignature
from .coin_solution import CoinSoluti... | 87 | 158 | 528 | 16 | 70 | cryptonoob42/chia-blockchain | src/types/spend_bundle.py | Python | SpendBundle | SpendBundle | 12 | 87 | 12 | 14 | bae5c52f5eeed19cd4de7e5860b7e018fa1bd676 | bigcode/the-stack | train |
f3be7774ad1e643bf6bffee5 | train | class | class PieceHunter(Subject):
@staticmethod
def start(hunting_scheduler, piece_assembler, client_id, metainfo, peer_ip, peer_port):
return PieceHunter(hunting_scheduler, piece_assembler, client_id, metainfo, peer_ip, peer_port)
def __init__(self, hunting_scheduler, piece_assembler, client_id, metain... | class PieceHunter(Subject):
@staticmethod
| def start(hunting_scheduler, piece_assembler, client_id, metainfo, peer_ip, peer_port):
return PieceHunter(hunting_scheduler, piece_assembler, client_id, metainfo, peer_ip, peer_port)
def __init__(self, hunting_scheduler, piece_assembler, client_id, metainfo, peer_ip, peer_port):
super(PieceHun... | _ext:
if self.piece_radio.is_prepared() is False:
order_list = self.hunting_scheduler.get_order_list(
self.bitfield_ext, self.request_order_size)
if len(order_list) > 0:
self.piece_radio.request(order_list)
else:
... | 79 | 79 | 264 | 10 | 69 | reignofmiracle/RM_Torrent | TorrentPython/TorrentPython/PieceHunter.py | Python | PieceHunter | PieceHunter | 91 | 119 | 91 | 93 | 942707ed73c0ffd342c4b718d72f532debf065cf | bigcode/the-stack | train |
30aa3c4bd10fe4121d42aa61 | train | class | class PieceHunterActor(pykka.ThreadingActor):
DEFAULT_REQUEST_ORDER_SIZE = 5
def __init__(self, piece_hunter, hunting_scheduler, piece_assembler, client_id, metainfo, peer_ip, peer_port):
super(PieceHunterActor, self).__init__()
self.piece_hunter = piece_hunter
self.hunting_scheduler = ... | class PieceHunterActor(pykka.ThreadingActor):
| DEFAULT_REQUEST_ORDER_SIZE = 5
def __init__(self, piece_hunter, hunting_scheduler, piece_assembler, client_id, metainfo, peer_ip, peer_port):
super(PieceHunterActor, self).__init__()
self.piece_hunter = piece_hunter
self.hunting_scheduler = hunting_scheduler # DI
self.piece_ass... | from TorrentPython.PieceRadio import *
class PieceHunterActor(pykka.ThreadingActor):
| 18 | 203 | 679 | 10 | 8 | reignofmiracle/RM_Torrent | TorrentPython/TorrentPython/PieceHunter.py | Python | PieceHunterActor | PieceHunterActor | 4 | 88 | 4 | 4 | 07b5f6d14237a1a249de9c411fe46a14478abf0c | bigcode/the-stack | train |
49734318cc029597e9b490e6 | train | class | class Send(object):
def __init__(self, url):
self._url = url
def test_payload(self, payload_filepath):
headers = {
"User-Agent": "SendGrid-Test",
"Content-Type": "multipart/form-data; boundary=xYzZY"
}
client = Client(host=self.url, request_headers=header... | class Send(object):
| def __init__(self, url):
self._url = url
def test_payload(self, payload_filepath):
headers = {
"User-Agent": "SendGrid-Test",
"Content-Type": "multipart/form-data; boundary=xYzZY"
}
client = Client(host=self.url, request_headers=headers)
f = open(... |
Usage: ./send.py [path to file containing test data]"""
import argparse
import os
import sys
try:
from config import Config
except:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
from python_http_client import Client
class Send(object):
| 64 | 64 | 112 | 4 | 59 | adammenges/sendgrid-python | sendgrid/helpers/inbound/send.py | Python | Send | Send | 14 | 30 | 14 | 14 | 4476c57d77f90d97ef8d5df743a447af736d22f5 | bigcode/the-stack | train |
b5e71a2a361bf24f1c395b2b | train | function | def get_parsed_object_from_url_without_extra_info(url):
parsed_object = urlparse.urlparse(url)
# remove url fragment
parsed_object = parsed_object._replace(fragment='')
return parsed_object
| def get_parsed_object_from_url_without_extra_info(url):
| parsed_object = urlparse.urlparse(url)
# remove url fragment
parsed_object = parsed_object._replace(fragment='')
return parsed_object
| _from_url(url):
if url in urlparsed_object_mapping:
return urlparsed_object_mapping[url]
parsed_object = get_parsed_object_from_url_without_extra_info(url)
urlparsed_object_mapping[url] = parsed_object
return parsed_object
def get_parsed_object_from_url_without_extra_info(url):
| 64 | 64 | 44 | 12 | 51 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | get_parsed_object_from_url_without_extra_info | get_parsed_object_from_url_without_extra_info | 27 | 33 | 27 | 27 | 966a22d4f0bb095119f5bc23a4ee4e52f2d11f2f | bigcode/the-stack | train |
dbdfd122891a31bf5cc63b20 | train | function | def save_to_yaml(data, filepath):
file_dir = os.path.dirname(filepath)
try:
os.makedirs(file_dir)
except OSError:
pass
with open(filepath, 'w+') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
| def save_to_yaml(data, filepath):
| file_dir = os.path.dirname(filepath)
try:
os.makedirs(file_dir)
except OSError:
pass
with open(filepath, 'w+') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
| ),
'json': json.loads(content)
}
elif file_suffix in ['.yaml', '.yml']:
content = load_yaml_file(file_path)
return {
'md5': get_md5(json.dumps(content)),
'json': content
}
def save_to_yaml(data, filepath):
| 64 | 64 | 57 | 8 | 56 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | save_to_yaml | save_to_yaml | 134 | 141 | 134 | 134 | 2148685c076f54cda863279a34055e350ea1de2e | bigcode/the-stack | train |
181be5cde6d0a24a189b6b75 | train | function | def load_yaml_file(yaml_file):
with open(yaml_file, 'r') as stream:
return yaml.load(stream)
| def load_yaml_file(yaml_file):
| with open(yaml_file, 'r') as stream:
return yaml.load(stream)
| bold']))
elif log_level == 'ERROR':
color = color or 'red'
logging.info(colored(text, color, attrs=['bold']))
def load_json_file(json_file):
with open(json_file, 'r') as f:
return f.read()
def load_yaml_file(yaml_file):
| 64 | 64 | 27 | 8 | 56 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | load_yaml_file | load_yaml_file | 112 | 114 | 112 | 112 | 77a8d6a162760b7d77008cce47ac6d1486201dcd | bigcode/the-stack | train |
6b9e2a6bfdb7efbe91e338c5 | train | function | def color_logging(text, log_level='info', color=None):
log_level = log_level.upper()
if log_level == 'DEBUG':
color = color or 'blue'
logging.info(colored(text, color))
elif log_level == 'INFO':
color = color or 'green'
logging.info(colored(text, color, attrs=['bold']))
e... | def color_logging(text, log_level='info', color=None):
| log_level = log_level.upper()
if log_level == 'DEBUG':
color = color or 'blue'
logging.info(colored(text, color))
elif log_level == 'INFO':
color = color or 'green'
logging.info(colored(text, color, attrs=['bold']))
elif log_level == 'WARNING':
color = color or 'y... | =new_path)
origin_parsed_obj = origin_parsed_obj._replace(
scheme=referer_url_parsed_object.scheme,
netloc=referer_url_parsed_object.netloc
)
return origin_parsed_obj.geturl()
def color_logging(text, log_level='info', color=None):
| 64 | 64 | 133 | 13 | 51 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | color_logging | color_logging | 93 | 106 | 93 | 93 | 8a4e652fe759613c9de73b72430a565c894a097b | bigcode/the-stack | train |
67a6b379c7f81c47b05f16f0 | train | function | def get_parsed_object_from_url(url):
if url in urlparsed_object_mapping:
return urlparsed_object_mapping[url]
parsed_object = get_parsed_object_from_url_without_extra_info(url)
urlparsed_object_mapping[url] = parsed_object
return parsed_object
| def get_parsed_object_from_url(url):
| if url in urlparsed_object_mapping:
return urlparsed_object_mapping[url]
parsed_object = get_parsed_object_from_url_without_extra_info(url)
urlparsed_object_mapping[url] = parsed_object
return parsed_object
|
from termcolor import colored
try:
# Python3
import urllib.parse as urlparse
from urllib.parse import urlencode
except ImportError:
# Python2
import urlparse
from urllib import urlencode
urlparsed_object_mapping = {}
def get_parsed_object_from_url(url):
| 64 | 64 | 57 | 9 | 55 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | get_parsed_object_from_url | get_parsed_object_from_url | 19 | 25 | 19 | 19 | bdd9c2e18e0aa4a9b8652a12352af193e17c51a4 | bigcode/the-stack | train |
b730fa5991bdb489bb9e35c4 | train | function | def load_json_file(json_file):
with open(json_file, 'r') as f:
return f.read()
| def load_json_file(json_file):
| with open(json_file, 'r') as f:
return f.read()
| log_level == 'WARNING':
color = color or 'yellow'
logging.info(colored(text, color, attrs=['bold']))
elif log_level == 'ERROR':
color = color or 'red'
logging.info(colored(text, color, attrs=['bold']))
def load_json_file(json_file):
| 63 | 64 | 24 | 7 | 56 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | load_json_file | load_json_file | 108 | 110 | 108 | 108 | 09703acde2e671b1e94b23e0258487d6899626c1 | bigcode/the-stack | train |
448a502742acffeec14a2fa6 | train | function | def load_foler_files(folder_path):
""" load folder path, return all files in set format.
"""
file_list = []
for dirpath, dirnames, filenames in os.walk(folder_path):
if dirnames:
continue
for filename in filenames:
basename = os.path.basename(dirpath)
... | def load_foler_files(folder_path):
| """ load folder path, return all files in set format.
"""
file_list = []
for dirpath, dirnames, filenames in os.walk(folder_path):
if dirnames:
continue
for filename in filenames:
basename = os.path.basename(dirpath)
file_relative_path = os.path.join... | save_to_yaml(data, filepath):
file_dir = os.path.dirname(filepath)
try:
os.makedirs(file_dir)
except OSError:
pass
with open(filepath, 'w+') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
def load_foler_files(folder_path):
| 64 | 64 | 94 | 8 | 56 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | load_foler_files | load_foler_files | 143 | 157 | 143 | 143 | 9eb9b881281f055f3c305fcb09dcfef06b55d6f7 | bigcode/the-stack | train |
d73ebe0e94b7988f97766a10 | train | function | def make_url_with_referer(url, referer_url):
"""
@params
referer_url: e.g. https://store.debugtalk.com/product/osmo
url e.g.:
(1) complete urls: http(s)://store.debugtalk.com/product/phantom-4-pro
(2) cdn asset files: //asset1.xcdn.com/assets/xxx.png
(3) relat... | def make_url_with_referer(url, referer_url):
| """
@params
referer_url: e.g. https://store.debugtalk.com/product/osmo
url e.g.:
(1) complete urls: http(s)://store.debugtalk.com/product/phantom-4-pro
(2) cdn asset files: //asset1.xcdn.com/assets/xxx.png
(3) relative links type1: /category/phantom
... | import os
import yaml
import json
import hashlib
import logging
from termcolor import colored
try:
# Python3
import urllib.parse as urlparse
from urllib.parse import urlencode
except ImportError:
# Python2
import urlparse
from urllib import urlencode
urlparsed_object_mapping = {}
def get_pars... | 183 | 183 | 610 | 13 | 169 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | make_url_with_referer | make_url_with_referer | 35 | 91 | 35 | 35 | d420f2baf5edecf16a1577241bcdbd13648122d1 | bigcode/the-stack | train |
e7be77bc374894ad4baf1f96 | train | function | def load_file(file_path, file_suffix='.json'):
file_suffix = file_suffix.lower()
if file_suffix == '.json':
content = load_json_file(file_path)
return {
'md5': get_md5(content),
'json': json.loads(content)
}
elif file_suffix in ['.yaml', '.yml']:
conte... | def load_file(file_path, file_suffix='.json'):
| file_suffix = file_suffix.lower()
if file_suffix == '.json':
content = load_json_file(file_path)
return {
'md5': get_md5(content),
'json': json.loads(content)
}
elif file_suffix in ['.yaml', '.yml']:
content = load_yaml_file(file_path)
return {... | r') as f:
return f.read()
def load_yaml_file(yaml_file):
with open(yaml_file, 'r') as stream:
return yaml.load(stream)
def get_md5(content):
return hashlib.md5(content).hexdigest()
def load_file(file_path, file_suffix='.json'):
| 64 | 64 | 104 | 11 | 53 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | load_file | load_file | 119 | 132 | 119 | 119 | a9a830c47a775cf0f7c54e3fa6bae74c7a4b6ffe | bigcode/the-stack | train |
616c116dfdfe2f4b96354c2b | train | function | def get_md5(content):
return hashlib.md5(content).hexdigest()
| def get_md5(content):
| return hashlib.md5(content).hexdigest()
| color, attrs=['bold']))
def load_json_file(json_file):
with open(json_file, 'r') as f:
return f.read()
def load_yaml_file(yaml_file):
with open(yaml_file, 'r') as stream:
return yaml.load(stream)
def get_md5(content):
| 64 | 64 | 16 | 6 | 58 | debugtalk/WebCrawler | webcrawler/helpers.py | Python | get_md5 | get_md5 | 116 | 117 | 116 | 116 | b15a2f3eaef2d2657bb18245f71d54bde8d39986 | bigcode/the-stack | train |
6929ad929b107b7a97013a66 | train | function | def lineage_proof_for_coin(parent_coin: Coin) -> Program:
if parent_coin.amount == 0:
return lineage_proof_for_zero(parent_coin)
return lineage_proof_for_genesis_puzzle(parent_coin)
| def lineage_proof_for_coin(parent_coin: Coin) -> Program:
| if parent_coin.amount == 0:
return lineage_proof_for_zero(parent_coin)
return lineage_proof_for_genesis_puzzle(parent_coin)
| Program:
return Program.to((0, [parent_coin.as_list(), 0]))
def lineage_proof_for_zero(parent_coin: Coin) -> Program:
return Program.to((0, [parent_coin.as_list(), 1]))
def lineage_proof_for_coin(parent_coin: Coin) -> Program:
| 63 | 64 | 46 | 14 | 49 | hulatang/skynet-blockchain | skynet/wallet/puzzles/genesis_by_puzzle_hash_with_0.py | Python | lineage_proof_for_coin | lineage_proof_for_coin | 43 | 46 | 43 | 43 | 9f9fe286ff7b4389e98872cf8518e3adc4a33deb | bigcode/the-stack | train |
f0e06e029c2b15704880df63 | train | function | def lineage_proof_for_genesis_puzzle(parent_coin: Coin) -> Program:
return Program.to((0, [parent_coin.as_list(), 0]))
| def lineage_proof_for_genesis_puzzle(parent_coin: Coin) -> Program:
| return Program.to((0, [parent_coin.as_list(), 0]))
| """
r = genesis_coin_checker.uncurry()
if r is None:
return r
f, args = r
if f != MOD:
return None
return args.first().as_atom()
def lineage_proof_for_genesis_puzzle(parent_coin: Coin) -> Program:
| 64 | 64 | 33 | 17 | 47 | hulatang/skynet-blockchain | skynet/wallet/puzzles/genesis_by_puzzle_hash_with_0.py | Python | lineage_proof_for_genesis_puzzle | lineage_proof_for_genesis_puzzle | 35 | 36 | 35 | 35 | 4118b54e3ce92184f93811b724da6c5c82535007 | bigcode/the-stack | train |
f400299e16d3e46fdb5ed213 | train | function | def lineage_proof_for_zero(parent_coin: Coin) -> Program:
return Program.to((0, [parent_coin.as_list(), 1]))
| def lineage_proof_for_zero(parent_coin: Coin) -> Program:
| return Program.to((0, [parent_coin.as_list(), 1]))
| f != MOD:
return None
return args.first().as_atom()
def lineage_proof_for_genesis_puzzle(parent_coin: Coin) -> Program:
return Program.to((0, [parent_coin.as_list(), 0]))
def lineage_proof_for_zero(parent_coin: Coin) -> Program:
| 63 | 64 | 30 | 14 | 49 | hulatang/skynet-blockchain | skynet/wallet/puzzles/genesis_by_puzzle_hash_with_0.py | Python | lineage_proof_for_zero | lineage_proof_for_zero | 39 | 40 | 39 | 39 | e145275cf27b382e155a741653487e89ebf441c3 | bigcode/the-stack | train |
6a4c73e8b2a47d12ed1dc571 | train | function | def create_genesis_puzzle_or_zero_coin_checker(genesis_puzzle_hash: bytes32) -> Program:
"""
Given a specific genesis coin id, create a `genesis_coin_mod` that allows
both that coin id to issue a cc, or anyone to create a cc with amount 0.
"""
genesis_coin_mod = MOD
return genesis_coin_mod.curry... | def create_genesis_puzzle_or_zero_coin_checker(genesis_puzzle_hash: bytes32) -> Program:
| """
Given a specific genesis coin id, create a `genesis_coin_mod` that allows
both that coin id to issue a cc, or anyone to create a cc with amount 0.
"""
genesis_coin_mod = MOD
return genesis_coin_mod.curry(genesis_puzzle_hash)
| 32
from skynet.wallet.puzzles.load_clvm import load_clvm
MOD = load_clvm("genesis-by-puzzle-hash-with-0.clvm", package_or_requirement=__name__)
def create_genesis_puzzle_or_zero_coin_checker(genesis_puzzle_hash: bytes32) -> Program:
| 64 | 64 | 86 | 22 | 42 | hulatang/skynet-blockchain | skynet/wallet/puzzles/genesis_by_puzzle_hash_with_0.py | Python | create_genesis_puzzle_or_zero_coin_checker | create_genesis_puzzle_or_zero_coin_checker | 11 | 17 | 11 | 11 | 2acce179da71f9df35622fa0be1fb56afce4977a | bigcode/the-stack | train |
318d3ff5dfcf6ce2b5b67a48 | train | function | def genesis_puzzle_hash_for_genesis_coin_checker(
genesis_coin_checker: Program,
) -> Optional[bytes32]:
"""
Given a `genesis_coin_checker` program, pull out the genesis puzzle hash.
"""
r = genesis_coin_checker.uncurry()
if r is None:
return r
f, args = r
if f != MOD:
re... | def genesis_puzzle_hash_for_genesis_coin_checker(
genesis_coin_checker: Program,
) -> Optional[bytes32]:
| """
Given a `genesis_coin_checker` program, pull out the genesis puzzle hash.
"""
r = genesis_coin_checker.uncurry()
if r is None:
return r
f, args = r
if f != MOD:
return None
return args.first().as_atom()
| id to issue a cc, or anyone to create a cc with amount 0.
"""
genesis_coin_mod = MOD
return genesis_coin_mod.curry(genesis_puzzle_hash)
def genesis_puzzle_hash_for_genesis_coin_checker(
genesis_coin_checker: Program,
) -> Optional[bytes32]:
| 64 | 64 | 92 | 25 | 39 | hulatang/skynet-blockchain | skynet/wallet/puzzles/genesis_by_puzzle_hash_with_0.py | Python | genesis_puzzle_hash_for_genesis_coin_checker | genesis_puzzle_hash_for_genesis_coin_checker | 20 | 32 | 20 | 22 | 714f269ad2d2265c59b7369c700472d5f639689e | bigcode/the-stack | train |
21328b907edd0b3bddfc2a1f | train | function | def rss_main(conn):
# connections
bucket_name = 'arxivoverload-developement'
filename = 'data-engineering-service/arxivdailyrss/txt/' + str(datetime.date.today()) + '.txt'
csv_filename = 'data-engineering-service/arxivdailyrss/csv/' + str(datetime.date.today()) + '.csv'
path = "data/daily_update/"+s... | def rss_main(conn):
# connections
| bucket_name = 'arxivoverload-developement'
filename = 'data-engineering-service/arxivdailyrss/txt/' + str(datetime.date.today()) + '.txt'
csv_filename = 'data-engineering-service/arxivdailyrss/csv/' + str(datetime.date.today()) + '.csv'
path = "data/daily_update/"+str(datetime.date.today()) + '.txt'
... | _cat = [t['term'] for t in entry.tags]
all_categories = (', ').join(all_cat)
# The abstract is in the <summary> element
Abstract = entry.summary
metadata_dict['arxiv_id'] = arxiv_id
metadata_dict['title'] = title
metadata_dict['abstract'] = Abstract
metadata_dict[... | 223 | 223 | 744 | 9 | 213 | ResearchKernel/MachineLearning | rk_brain/arxiv_db_updater/rss_fetcher.py | Python | rss_main | rss_main | 83 | 148 | 83 | 84 | e02030db698643ddb00c76cd47ae2822335a7eb8 | bigcode/the-stack | train |
ed5be4b55c4d1ae0588b3357 | train | function | def extract_metadata(feed):
'''
Function: Extract all metadata from arxiv respose
Input: takes api respose from arxiv, arxiv_id in our database
Return: list of dictionaries
'''
# for time formating
f = '%Y-%m-%d %H:%M:%S'
now = datetime.datetime.now... | def extract_metadata(feed):
| '''
Function: Extract all metadata from arxiv respose
Input: takes api respose from arxiv, arxiv_id in our database
Return: list of dictionaries
'''
# for time formating
f = '%Y-%m-%d %H:%M:%S'
now = datetime.datetime.now()
created_at = now.strf... | import os
import boto3
import feedparser
import requests
import urllib.request
import datetime
import re
import pandas as pd
import ast
def extract_metadata(feed):
| 37 | 183 | 610 | 5 | 31 | ResearchKernel/MachineLearning | rk_brain/arxiv_db_updater/rss_fetcher.py | Python | extract_metadata | extract_metadata | 10 | 82 | 10 | 10 | 683d6b5e4955df9d79a64fab32dc31742601b4e1 | bigcode/the-stack | train |
1b88bccb1e10b74fea7b410b | train | class | class CompositorNodeAlphaOver:
premul = None
use_premultiply = None
def update(self):
pass
| class CompositorNodeAlphaOver:
| premul = None
use_premultiply = None
def update(self):
pass
| class CompositorNodeAlphaOver:
| 7 | 64 | 29 | 7 | 0 | cmbasnett/fake-bpy-module | modules/2.79/bpy/types/CompositorNodeAlphaOver.py | Python | CompositorNodeAlphaOver | CompositorNodeAlphaOver | 1 | 6 | 1 | 1 | 6d910c622c71d99ac7cd5cd2d346e437d2e0a37e | bigcode/the-stack | train |
0a6ed57b7a9979b26a6454bb | train | function | def calc_gradient_penalty(netD, input, fake):
LAMBDA = 10
alpha = torch.rand(opt.batchSize, 1, 1, 1)
#alpha = alpha.expand(opt.batchSize, map_size)
if opt.cuda:
alpha = alpha.cuda()
interpolates = alpha * input + ((1 - alpha) * fake)
interpolates.requires_grad = True
# if opt.cuda:... | def calc_gradient_penalty(netD, input, fake):
| LAMBDA = 10
alpha = torch.rand(opt.batchSize, 1, 1, 1)
#alpha = alpha.expand(opt.batchSize, map_size)
if opt.cuda:
alpha = alpha.cuda()
interpolates = alpha * input + ((1 - alpha) * fake)
interpolates.requires_grad = True
# if opt.cuda:
# interpolates = interpolates.cuda()
... | = 3 # Channels
num_batches = X.shape[0] / opt.batchSize
ngpu = int(opt.ngpu)
nz = int(opt.nz)
ngf = int(opt.ngf)
ndf = int(opt.ndf)
n_extra_layers = int(opt.n_extra_layers)
# gradient penalty
def calc_gradient_penalty(netD, input, fake):
| 76 | 76 | 255 | 12 | 63 | fang2hou/ABGAN | experiments/wgan_gp_3.py | Python | calc_gradient_penalty | calc_gradient_penalty | 94 | 122 | 94 | 94 | 99dd7cf176b4edfcb42772baad635dbf92ce2909 | bigcode/the-stack | train |
eac3433e7e62ed29fa96c4dc | train | function | def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
| def weights_init(m):
| classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
| retain_graph=True, only_inputs=True)[0]
gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * LAMBDA
return gradient_penalty
# custom weights initialization called on netG and netD
def weights_init(m):
| 64 | 64 | 75 | 5 | 58 | fang2hou/ABGAN | experiments/wgan_gp_3.py | Python | weights_init | weights_init | 127 | 133 | 127 | 127 | c0cb50d61be0c6911fd01629dbdc225b4f0a196b | bigcode/the-stack | train |
9b0e563c5a18c72ef0f8c058 | train | class | class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += va... | class AverageMeter(object):
| """Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += ... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
import time
from pathlib import Path
from torch.utils.tensorboard import SummaryWriter
class AverageMeter(object):
| 51 | 64 | 102 | 5 | 45 | CFM-MSG/Code_CDN | lib/core/utils.py | Python | AverageMeter | AverageMeter | 13 | 29 | 13 | 13 | efb0bae6e412f82360b061fbdc068fc519c2f8bb | bigcode/the-stack | train |
18123689b9479431eed4b366 | train | function | def create_logger(cfg, cfg_name, tag='train'):
root_log_dir = Path(cfg.LOG_DIR)
# set up logger
if not root_log_dir.exists():
print('=> creating {}'.format(root_log_dir))
root_log_dir.mkdir()
dataset = cfg.DATASET.NAME
cfg_name = os.path.basename(cfg_name).split('.yaml')[0]
fin... | def create_logger(cfg, cfg_name, tag='train'):
| root_log_dir = Path(cfg.LOG_DIR)
# set up logger
if not root_log_dir.exists():
print('=> creating {}'.format(root_log_dir))
root_log_dir.mkdir()
dataset = cfg.DATASET.NAME
cfg_name = os.path.basename(cfg_name).split('.yaml')[0]
final_log_dir = root_log_dir / dataset / cfg_name
... | current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count... | 100 | 100 | 336 | 12 | 87 | CFM-MSG/Code_CDN | lib/core/utils.py | Python | create_logger | create_logger | 32 | 70 | 32 | 32 | fddaf3852fc3756c906f897535aabc36d5e2d39c | bigcode/the-stack | train |
b753ce839be002ebf4f8f42f | train | function | def create_tf_writer(cfg, cfg_name, is_feature_writer=True, feature_name='default'):
root_tb_dir = Path(cfg.TENSORBOARD_DIR)
dataset = cfg.DATASET.NAME
cfg_name = os.path.basename(cfg_name).split('.yaml')[0]
time_str = time.strftime('%Y-%m-%d-%H-%M')
# set up logger
if not root_tb_dir.exists():
... | def create_tf_writer(cfg, cfg_name, is_feature_writer=True, feature_name='default'):
| root_tb_dir = Path(cfg.TENSORBOARD_DIR)
dataset = cfg.DATASET.NAME
cfg_name = os.path.basename(cfg_name).split('.yaml')[0]
time_str = time.strftime('%Y-%m-%d-%H-%M')
# set up logger
if not root_tb_dir.exists():
print('=> creating {}'.format(root_tb_dir))
root_tb_dir.mkdir()
i... | {}'.format(final_tb_dir))
final_tb_dir.mkdir(parents=True, exist_ok=True)
tb_writer = SummaryWriter(str(final_tb_dir))
return logger, str(final_log_dir), time_str, tb_writer
def create_tf_writer(cfg, cfg_name, is_feature_writer=True, feature_name='default'):
| 64 | 64 | 190 | 19 | 44 | CFM-MSG/Code_CDN | lib/core/utils.py | Python | create_tf_writer | create_tf_writer | 72 | 90 | 72 | 72 | 290ff238bee9ee8c5469f669bccac961d6f45cdd | bigcode/the-stack | train |
33b0d571c062ca78aafd5697 | train | function | def hid2ascii(lst):
"""The USB HID device sends an 8-byte code for every character. This
routine converts the HID code to an ASCII character.
See https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
for a complete code table. Only relevant codes are used here."""
# Example input... | def hid2ascii(lst):
| """The USB HID device sends an 8-byte code for every character. This
routine converts the HID code to an ASCII character.
See https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
for a complete code table. Only relevant codes are used here."""
# Example input from scanner repres... | a keyboard so a scan will "type"
the data into any program. But that also becomes its limitation. Often,
you don't want it to act like it's typing on a keyboard; you just want
to get data directly from it.
This program detaches the device from the kernel so it will not "type"
anything, and reads directly from the dev... | 256 | 256 | 915 | 6 | 250 | bungernut/barcode_scanner_python | usb_scanner_hid_read_demo.py | Python | hid2ascii | hid2ascii | 39 | 126 | 39 | 39 | 07fdb2579cc74ea1fc206d7912daa1ae322c9421 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.