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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25750b97c06cd8f7e521dc7b | train | function | def file_already_has_core_copyright(file_lines):
index, _ = get_updatable_copyright_line(file_lines)
return index != None
| def file_already_has_core_copyright(file_lines):
| index, _ = get_updatable_copyright_line(file_lines)
return index != None
| ))
################################################################################
# query git for year of last change
################################################################################
def get_git_change_year_range(filename):
years = get_git_change_years(filename)
return min(years), max(years)... | 64 | 64 | 31 | 11 | 52 | caapisas88/lukcore | contrib/devtools/copyright_header.py | Python | file_already_has_core_copyright | file_already_has_core_copyright | 490 | 492 | 490 | 490 | 7a4dc58c2443f7cf596a5f187ba7451b4ccd0645 | bigcode/the-stack | train |
fb2388644e8d7dfe0bbd8da9 | train | function | def call_git_log(filename):
out = subprocess.check_output((GIT_LOG_CMD % filename).split(' '))
return out.decode("utf-8").split('\n')
| def call_git_log(filename):
| out = subprocess.check_output((GIT_LOG_CMD % filename).split(' '))
return out.decode("utf-8").split('\n')
| True
else:
sys.exit("*** unknown argument: %s" % argv[2])
exec_report(base_directory, verbose)
################################################################################
# query git for year of last change
################################################################################
GIT_LOG... | 64 | 64 | 36 | 6 | 58 | caapisas88/lukcore | contrib/devtools/copyright_header.py | Python | call_git_log | call_git_log | 307 | 309 | 307 | 307 | ecd3510aa3bad22578e537720c63547e9c7d92e0 | bigcode/the-stack | train |
07bd84c3245bef3a2424a62a | train | function | def read_file(filename):
return open(os.path.abspath(filename), 'r').read()
| def read_file(filename):
| return open(os.path.abspath(filename), 'r').read()
| _name].search(contents)
return match is not None
def file_has_without_c_style_copyright_for_holder(contents, holder_name):
match = WITHOUT_C_STYLE_COMPILED[holder_name].search(contents)
return match is not None
################################################################################
# get file inf... | 64 | 64 | 18 | 5 | 58 | caapisas88/lukcore | contrib/devtools/copyright_header.py | Python | read_file | read_file | 146 | 147 | 146 | 146 | 87d60ab9639aa3c2a85b5542380d5759b368b481 | bigcode/the-stack | train |
b6fae931571c8b9aae04d3a7 | train | function | def exec_insert_header(filename, style):
file_lines = read_file_lines(filename)
if file_already_has_core_copyright(file_lines):
sys.exit('*** %s already has a copyright by The Bitcoin Core developers'
% (filename))
start_year, end_year = get_git_change_year_range(filename)
if st... | def exec_insert_header(filename, style):
| file_lines = read_file_lines(filename)
if file_already_has_core_copyright(file_lines):
sys.exit('*** %s already has a copyright by The Bitcoin Core developers'
% (filename))
start_year, end_year = get_git_change_year_range(filename)
if style == 'python':
insert_python_he... | def insert_cpp_header(filename, file_lines, start_year, end_year):
header_lines = get_cpp_header_lines_to_insert(start_year, end_year)
for line in header_lines:
file_lines.insert(0, line)
write_file_lines(filename, file_lines)
def exec_insert_header(filename, style):
| 64 | 64 | 105 | 8 | 56 | caapisas88/lukcore | contrib/devtools/copyright_header.py | Python | exec_insert_header | exec_insert_header | 521 | 530 | 521 | 521 | e5c0041a21313ee710fc537d11d270a814f6c5a9 | bigcode/the-stack | train |
9b6ae5c24b4a61fc0ad844a6 | train | function | def file_has_dominant_style_copyright_for_holder(contents, holder_name):
match = DOMINANT_STYLE_COMPILED[holder_name].search(contents)
return match is not None
| def file_has_dominant_style_copyright_for_holder(contents, holder_name):
| match = DOMINANT_STYLE_COMPILED[holder_name].search(contents)
return match is not None
| _STYLE,
holder_name))
################################################################################
# search file contents for copyright message of particular category
################################################################################
def get_count_of_copyrights_of_any... | 64 | 64 | 40 | 16 | 48 | caapisas88/lukcore | contrib/devtools/copyright_header.py | Python | file_has_dominant_style_copyright_for_holder | file_has_dominant_style_copyright_for_holder | 130 | 132 | 130 | 130 | b07b185bfa580fb1d67a75807df04abed9099196 | bigcode/the-stack | train |
8ade12c2a8b1945da7c3c329 | train | function | @admin_bp.route(app.config['ADMINHOME'] + 'add_user/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def add_user():
form = AddUserForm()
if form.validate_on_submit():
create_user(form.username.data,
form.password.data,
ema... | @admin_bp.route(app.config['ADMINHOME'] + 'add_user/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def add_user():
| form = AddUserForm()
if form.validate_on_submit():
create_user(form.username.data,
form.password.data,
email=form.email.data,
name=form.name.data,
job_title=form.job_title.data,
locale=form.locale.data,
... | UnresolvedReferences
return render_template('admin_users.html', title='Usuários', users=users)
# add user
@admin_bp.route(app.config['ADMINHOME'] + 'add_user/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def add_user():
| 64 | 64 | 156 | 38 | 25 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | add_user | add_user | 92 | 108 | 92 | 95 | 06532cbfd01f5aace1e1a46a3e2bf1affee0904b | bigcode/the-stack | train |
fee7136acd7ecd4e4a4f893f | train | function | @identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
# set the identity user object
identity.user = current_user
# Add the UserNeed to the identity
if hasattr(current_user, 'id'):
identity.provides.add(UserNeed(current_user.id))
# Assuming the User model has a list of... | @identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
# set the identity user object
| identity.user = current_user
# Add the UserNeed to the identity
if hasattr(current_user, 'id'):
identity.provides.add(UserNeed(current_user.id))
# Assuming the User model has a list of groups, update the
# identity with the groups that the user provides
if hasattr(current_user, 'flicket... | ,
job_title=job_title,
date_added=datetime.datetime.now(),
locale=locale,
disabled=disabled)
db.session.add(register)
db.session.commit()
# add permissions
@identity_loaded.connect_via(app)
def on_ident... | 64 | 64 | 143 | 24 | 39 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | on_identity_loaded | on_identity_loaded | 54 | 67 | 54 | 56 | 35a3b8d0b1c9c920d68b0a2c46745c9d704ac952 | bigcode/the-stack | train |
5c3f10228260439004797878 | train | function | @admin_bp.route(app.config['ADMINHOME'] + 'groups/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def groups():
form = AddGroupForm()
groups = FlicketGroup.query.all()
if form.validate_on_submit():
add_group = FlicketGroup(
group_name=form.group_... | @admin_bp.route(app.config['ADMINHOME'] + 'groups/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def groups():
| form = AddGroupForm()
groups = FlicketGroup.query.all()
if form.validate_on_submit():
add_group = FlicketGroup(
group_name=form.group_name.data
)
db.session.add(add_group)
db.session.commit()
flash(gettext('Novo grupo "{}" adicionado.'.format(form.group_na... | _template('admin_delete_user.html', title='Deletar usuário',
user_details=user_details, form=form)
# Add new groups
@admin_bp.route(app.config['ADMINHOME'] + 'groups/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def groups():
| 64 | 64 | 150 | 36 | 27 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | groups | groups | 202 | 218 | 202 | 205 | ac54c03f2035ff2c3387184535110abd0de02b18 | bigcode/the-stack | train |
c1f511a6775f66e4e3a82d13 | train | function | @admin_bp.route(app.config['ADMINHOME'] + 'delete_user/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def delete_user():
form = EnterPasswordForm()
id = request.args.get('id')
user_details = FlicketUser.query.filter_by(id=id).first()
# we won't ever delete the... | @admin_bp.route(app.config['ADMINHOME'] + 'delete_user/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def delete_user():
| form = EnterPasswordForm()
id = request.args.get('id')
user_details = FlicketUser.query.filter_by(id=id).first()
# we won't ever delete the flicket_admin user (id = 1)
if id == '1':
flash(gettext('Não é possível excluir o usuário flicket_admin padrão.'), category='warning')
return r... |
return render_template('admin_user.html',
title='Editar usuário',
admin_edit=True,
form=form, user=user)
# Delete user
@admin_bp.route(app.config['ADMINHOME'] + 'delete_user/', methods=['GET', 'POST'])
@login_required
@admin_permiss... | 70 | 70 | 234 | 38 | 31 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | delete_user | delete_user | 175 | 198 | 175 | 178 | 2865a004714aae148e7d41219737ebf34168465e | bigcode/the-stack | train |
63da029c5bcb5b50eec8c7d4 | train | function | @admin_bp.route(app.config['ADMINHOME'] + 'edit_user/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def edit_user():
_id = request.args.get('id')
user = FlicketUser.query.filter_by(id=_id).first()
if user:
form = EditUserForm()
if form.validate_on_s... | @admin_bp.route(app.config['ADMINHOME'] + 'edit_user/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def edit_user():
| _id = request.args.get('id')
user = FlicketUser.query.filter_by(id=_id).first()
if user:
form = EditUserForm()
if form.validate_on_submit():
# check the username is unique
if user.username != form.username.data:
query = FlicketUser.query.filter_by(user... | ()
if form.validate_on_submit():
create_user(form.username.data,
form.password.data,
email=form.email.data,
name=form.name.data,
job_title=form.job_title.data,
locale=form.locale.data,
dis... | 154 | 154 | 514 | 38 | 115 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | edit_user | edit_user | 112 | 171 | 112 | 115 | 49d7ba3691705381fa249c4b320314be2fa06e87 | bigcode/the-stack | train |
2f68c76e994f1c699d7cc65b | train | function | @admin_bp.route(app.config['ADMINHOME'])
@login_required
@admin_permission.require(http_exception=403)
def index():
# noinspection PyUnresolvedReferences
return render_template('admin.html', title='Admin')
| @admin_bp.route(app.config['ADMINHOME'])
@login_required
@admin_permission.require(http_exception=403)
def index():
# noinspection PyUnresolvedReferences
| return render_template('admin.html', title='Admin')
| ).first()
for g in the_user.flicket_groups:
identity.provides.add(RoleNeed('{}'.format(g.group_name)))
@admin_bp.route(app.config['ADMINHOME'])
@login_required
@admin_permission.require(http_exception=403)
def index():
# noinspection PyUnresolvedReferences
| 63 | 64 | 46 | 34 | 29 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | index | index | 70 | 75 | 70 | 74 | 3e39485ae154cf611557228fa8088ddb17fd6d69 | bigcode/the-stack | train |
9bf5dec5ec245c706eb43352 | train | function | @admin_bp.route(app.config['ADMINHOME'] + 'edit_group/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def admin_edit_group():
form = AddGroupForm()
id = request.args.get('id')
group = FlicketGroup.query.filter_by(id=id).first()
# if group can't be found in data... | @admin_bp.route(app.config['ADMINHOME'] + 'edit_group/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def admin_edit_group():
| form = AddGroupForm()
id = request.args.get('id')
group = FlicketGroup.query.filter_by(id=id).first()
# if group can't be found in database.
if not group:
flash(gettext('Não foi possível encontrar o grupo {}'.format(group.group_name)), category='warning')
return redirect(url_for('ad... | ')
return redirect(url_for('admin_bp.groups'))
# noinspection PyUnresolvedReferences
return render_template('admin_groups.html', title='Groups', form=form, groups=groups)
# Edit groups
@admin_bp.route(app.config['ADMINHOME'] + 'edit_group/', methods=['GET', 'POST'])
@login_required
@admin_permission.... | 83 | 83 | 278 | 39 | 43 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | admin_edit_group | admin_edit_group | 222 | 248 | 222 | 225 | 71bcb2086b118b48f00a939608306b4811ffd5d6 | bigcode/the-stack | train |
03a4332591af8edf0c2ca50c | train | function | def create_user(username, password, email=None, name=None, job_title=None, locale=None, disabled=None):
password = hash_password(password)
register = FlicketUser(username=username,
email=email,
name=name,
password=password,
... | def create_user(username, password, email=None, name=None, job_title=None, locale=None, disabled=None):
| password = hash_password(password)
register = FlicketUser(username=username,
email=email,
name=name,
password=password,
job_title=job_title,
date_added=datetime.datetime.now(),
... | UserForm
from . import admin_bp
principals = Principal(app)
# define flicket_admin role need
admin_only = RoleNeed('flicket_admin')
admin_permission = Permission(admin_only)
def create_user(username, password, email=None, name=None, job_title=None, locale=None, disabled=None):
| 64 | 64 | 86 | 23 | 41 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | create_user | create_user | 39 | 50 | 39 | 39 | 85480a188cb2d7b589db5fa8de1d1cc13429f505 | bigcode/the-stack | train |
cf221b665f54ee08efab7c9b | train | function | @admin_bp.route(app.config['ADMINHOME'] + 'delete_group/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def admin_delete_group():
form = EnterPasswordForm()
id = request.args.get('id')
group_details = FlicketGroup.query.filter_by(id=id).first()
# we won't ever ... | @admin_bp.route(app.config['ADMINHOME'] + 'delete_group/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def admin_delete_group():
| form = EnterPasswordForm()
id = request.args.get('id')
group_details = FlicketGroup.query.filter_by(id=id).first()
# we won't ever delete the flicket_admin group (id = 1)
if id == '1':
flash(gettext('Não é possível excluir o grupo flicket_admin padrão.'), category='warning')
return ... | _name
# noinspection PyUnresolvedReferences
return render_template('admin_edit_group.html', title='Editar grupo', form=form)
# Delete group
@admin_bp.route(app.config['ADMINHOME'] + 'delete_group/', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def admin_delete_group(... | 72 | 72 | 240 | 39 | 32 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | admin_delete_group | admin_delete_group | 252 | 276 | 252 | 255 | a7d774c51293bce9bd2f1e404c0380d071897e51 | bigcode/the-stack | train |
3b57436e67a1e10b941e79b3 | train | function | @admin_bp.route(app.config['ADMINHOME'] + 'users/', methods=['GET', 'POST'])
@admin_bp.route(app.config['ADMINHOME'] + 'users/<int:page>', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def users(page=1):
users = FlicketUser.query.order_by(FlicketUser.username)
users = us... | @admin_bp.route(app.config['ADMINHOME'] + 'users/', methods=['GET', 'POST'])
@admin_bp.route(app.config['ADMINHOME'] + 'users/<int:page>', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def users(page=1):
| users = FlicketUser.query.order_by(FlicketUser.username)
users = users.paginate(page, app.config['posts_per_page'])
# noinspection PyUnresolvedReferences
return render_template('admin_users.html', title='Usuários', users=users)
| @admin_bp.route(app.config['ADMINHOME'] + 'users/', methods=['GET', 'POST'])
@admin_bp.route(app.config['ADMINHOME'] + 'users/<int:page>', methods=['GET', 'POST'])
@login_required
@admin_permission.require(http_exception=403)
def users(page=1):
| 64 | 64 | 121 | 64 | 0 | By-Lucas/Sistema-de-tickets-flask | application/flicket_admin/views/view_admin.py | Python | users | users | 79 | 88 | 79 | 83 | 3196e18062392fa95297ac5b5846b06dd3dfb902 | bigcode/the-stack | train |
70241ff7da5fb4a1253d0f36 | train | function | def sort_arr(arr):
n = len(arr)
for i in range(0, n-1):
for j in range(0, n-i-1):
if(arr[j] < arr[j+1]):
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
| def sort_arr(arr):
| n = len(arr)
for i in range(0, n-1):
for j in range(0, n-i-1):
if(arr[j] < arr[j+1]):
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
| ''' K-TH LARGEST NUMBER
To find the k-th largest number from an array of distinct numbers
* The array is sorted in descending order
* arr[k-1] gives the k-th largest number
'''
# to sort the array- Bubble Sort
def sort_arr(arr):
| 63 | 64 | 76 | 5 | 57 | zhcet19/NeoAlgo-1 | Python/math/K_largest.py | Python | sort_arr | sort_arr | 8 | 16 | 8 | 8 | 6c909ee84579cdbff23165e85d0742520336e291 | bigcode/the-stack | train |
47002a2dd9e7068acae7c8a6 | train | function | def main():
#accept array and k as user inputs
arr = list(map(int, input("Enter the array: ").split()))
k = int(input("Enter the value of k: "))
print(k_largest(sort_arr(arr), k))
| def main():
#accept array and k as user inputs
| arr = list(map(int, input("Enter the array: ").split()))
k = int(input("Enter the value of k: "))
print(k_largest(sort_arr(arr), k))
| ]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
#to find k-th largest element
def k_largest(arr, k):
return arr[k-1]
#driver code
def main():
#accept array and k as user inputs
| 64 | 64 | 53 | 13 | 50 | zhcet19/NeoAlgo-1 | Python/math/K_largest.py | Python | main | main | 23 | 27 | 23 | 24 | 909aa2be44e091f427312c98dad941e09162d6b9 | bigcode/the-stack | train |
28f32118776d02f01eea613a | train | function | def k_largest(arr, k):
return arr[k-1]
| def k_largest(arr, k):
| return arr[k-1]
| (0, n-i-1):
if(arr[j] < arr[j+1]):
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
#to find k-th largest element
def k_largest(arr, k):
| 64 | 64 | 15 | 8 | 55 | zhcet19/NeoAlgo-1 | Python/math/K_largest.py | Python | k_largest | k_largest | 19 | 20 | 19 | 19 | 146c9985784758a9a014657e48cacafb6ad2bd3b | bigcode/the-stack | train |
e74a467a683ffa4694a59815 | train | function | def retrieve_interim():
"""
An ERA interim request for analysis pressure level data.
Change the keywords below to adapt it to your needs.
(eg to add or to remove levels, parameters, times etc)
Request cost per day is 112 fields, 14.2326 Mbytes
"""
server.retrieve({
... | def retrieve_interim():
| """
An ERA interim request for analysis pressure level data.
Change the keywords below to adapt it to your needs.
(eg to add or to remove levels, parameters, times etc)
Request cost per day is 112 fields, 14.2326 Mbytes
"""
server.retrieve({
"class": "ei",
... | #!/usr/bin/env python
import calendar
from ecmwfapi import ECMWFDataServer
server = ECMWFDataServer()
def retrieve_interim():
| 32 | 77 | 259 | 5 | 27 | orb1t/RocketPy | data/weather/fetchRioSaoPaulo.py | Python | retrieve_interim | retrieve_interim | 6 | 28 | 6 | 6 | 254454b5e5402bb9d5dd9da1867540b82a1af6a0 | bigcode/the-stack | train |
0aedb9a77bb49ab148430247 | train | class | class RDBMSHost:
def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str):
self.host: str = host
self.port: int = port
self.db_name: str = db_name
self.db_schema: str = db_schema
self.db_user: str = db_user
self.db_passwor... | class RDBMSHost:
| def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str):
self.host: str = host
self.port: int = port
self.db_name: str = db_name
self.db_schema: str = db_schema
self.db_user: str = db_user
self.db_password: str = db_passw... | class RDBMSHost:
| 6 | 64 | 97 | 6 | 0 | pongthep/apache-atlas-external-tools | metadata_extractor/models/hosts/rdbms_host.py | Python | RDBMSHost | RDBMSHost | 1 | 8 | 1 | 1 | 309244302e3732c1a190e27a6ce575dc04b40df7 | bigcode/the-stack | train |
a114e2d83951bc42b4ad35f8 | train | class | class InferredAssetS3DataConnector(InferredAssetFilePathDataConnector):
"""
Extension of InferredAssetFilePathDataConnector used to connect to S3
The InferredAssetS3DataConnector is one of two classes (ConfiguredAssetS3DataConnector being the
other one) designed for connecting to filesystem-like data, ... | class InferredAssetS3DataConnector(InferredAssetFilePathDataConnector):
| """
Extension of InferredAssetFilePathDataConnector used to connect to S3
The InferredAssetS3DataConnector is one of two classes (ConfiguredAssetS3DataConnector being the
other one) designed for connecting to filesystem-like data, more specifically files on S3. It connects to assets
inferred from b... | import logging
import os
from typing import List, Optional
from great_expectations.core.batch import BatchDefinition
from great_expectations.core.batch_spec import PathBatchSpec, S3BatchSpec
from great_expectations.exceptions.exceptions import ParserError
try:
import boto3
except ImportError:
boto3 = None
fr... | 150 | 256 | 930 | 16 | 134 | victorcouste/great_expectations | great_expectations/datasource/data_connector/inferred_asset_s3_data_connector.py | Python | InferredAssetS3DataConnector | InferredAssetS3DataConnector | 25 | 143 | 25 | 25 | 594c143e4163685c3897545a453199b7e7d2c308 | bigcode/the-stack | train |
75f9c043550b5e82b0c00539 | train | function | def _check_valid_s3_path(
path: str,
) -> None:
"""Performs a basic check for validity of the S3 path"""
bad_chars = [c for c in INVALID_S3_CHARS if c in path]
if len(bad_chars) > 0:
msg = (
f"The parsed S3 path={path} contains the invalid characters {bad_chars}."
"Please... | def _check_valid_s3_path(
path: str,
) -> None:
| """Performs a basic check for validity of the S3 path"""
bad_chars = [c for c in INVALID_S3_CHARS if c in path]
if len(bad_chars) > 0:
msg = (
f"The parsed S3 path={path} contains the invalid characters {bad_chars}."
"Please make sure your regex is correct and characters are ... | data_asset_name isn't used in this method.
# It's only kept for compatibility with parent methods.
_check_valid_s3_path(path)
return f"s3a://{os.path.join(self._bucket, path)}"
def _check_valid_s3_path(
path: str,
) -> None:
| 64 | 64 | 134 | 17 | 47 | victorcouste/great_expectations | great_expectations/datasource/data_connector/inferred_asset_s3_data_connector.py | Python | _check_valid_s3_path | _check_valid_s3_path | 146 | 158 | 146 | 148 | c9a9ee7ffd16bf782a3b520f7a3b3c15c57a816c | bigcode/the-stack | train |
558ee55d5b45bd644b2171a5 | train | class | class ThoreSubmission(SubmissionPy):
def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
program = self.parse_program(s)
for i, (op, arg) in enumerate(program):
if op == "jmp":
program[i] = ("nop", arg)
... | class ThoreSubmission(SubmissionPy):
| def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
program = self.parse_program(s)
for i, (op, arg) in enumerate(program):
if op == "jmp":
program[i] = ("nop", arg)
elif op == "nop":
... | from tool.runners.python import SubmissionPy
class ThoreSubmission(SubmissionPy):
| 16 | 92 | 309 | 8 | 7 | evqna/adventofcode-2020 | day-08/part-2/thore.py | Python | ThoreSubmission | ThoreSubmission | 4 | 58 | 4 | 4 | b2c85d00ef2d323dbe5b5a8f373868ad00545b9f | bigcode/the-stack | train |
842746ebb3fbc6b6b16862a2 | train | class | class SqlSensor(BaseSensorOperator):
"""
Runs a sql statement until a criteria is met. It will keep trying while
sql returns no row, or if the first cell in (0, '0', '').
:param conn_id: The connection to run the sensor against
:type conn_id: str
:param sql: The sql to run. To pass, it needs to... | class SqlSensor(BaseSensorOperator):
| """
Runs a sql statement until a criteria is met. It will keep trying while
sql returns no row, or if the first cell in (0, '0', '').
:param conn_id: The connection to run the sensor against
:type conn_id: str
:param sql: The sql to run. To pass, it needs to return at least one cell
tha... | BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from builtins import str
from airflow.hooks.base_hook import BaseHook
from airflow.sensors.base_sensor_operator import BaseSensorOp... | 80 | 80 | 267 | 7 | 72 | jacky-nirvana/incubator-airflow | airflow/sensors/sql_sensor.py | Python | SqlSensor | SqlSensor | 27 | 58 | 27 | 27 | 69dfd4310b7a35be9571d69c422977cff175fc08 | bigcode/the-stack | train |
92d7bb0a687e10e4d632b799 | train | class | class DcxImageFile(PcxImageFile):
format = "DCX"
format_description = "Intel DCX"
_close_exclusive_fp_after_loading = False
def _open(self):
# Header
s = self.fp.read(4)
if not _accept(s):
raise SyntaxError("not a DCX file")
# Component directory
s... | class DcxImageFile(PcxImageFile):
| format = "DCX"
format_description = "Intel DCX"
_close_exclusive_fp_after_loading = False
def _open(self):
# Header
s = self.fp.read(4)
if not _accept(s):
raise SyntaxError("not a DCX file")
# Component directory
self._offset = []
for i in r... | as i32
from .PcxImagePlugin import PcxImageFile
MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
def _accept(prefix):
return len(prefix) >= 4 and i32(prefix) == MAGIC
##
# Image plugin for the Intel DCX format.
class DcxImageFile(PcxImageFile):
| 80 | 80 | 269 | 10 | 70 | avrumnoor/NewsSummarizer | venv/lib/python3.8/site-packages/PIL/DcxImagePlugin.py | Python | DcxImageFile | DcxImageFile | 39 | 84 | 39 | 40 | 8964a14d6c3c1b88826b95b8f7cd66c2855f1013 | bigcode/the-stack | train |
6f7ae6380303e0d278e41c17 | train | function | def _accept(prefix):
return len(prefix) >= 4 and i32(prefix) == MAGIC
| def _accept(prefix):
| return len(prefix) >= 4 and i32(prefix) == MAGIC
| for information on usage and redistribution.
#
from . import Image
from ._binary import i32le as i32
from .PcxImagePlugin import PcxImageFile
MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
def _accept(prefix):
| 64 | 64 | 21 | 5 | 59 | avrumnoor/NewsSummarizer | venv/lib/python3.8/site-packages/PIL/DcxImagePlugin.py | Python | _accept | _accept | 31 | 32 | 31 | 31 | 449c4fcd2acbd2dc037870f24c2fad98896d552b | bigcode/the-stack | train |
e3bb4b9b15e198573615ebe3 | train | function | def maxpool2d(x, k=2):
# MaxPool2D wrapper
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding="SAME")
| def maxpool2d(x, k=2):
# MaxPool2D wrapper
| return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding="SAME")
| x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding="SAME")
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
# MaxPool2D wrapper
| 64 | 64 | 55 | 19 | 45 | vsoch/caliper-analysis | tensorflow_v0.11/3_NeuralNetworks/convolutional_network.py | Python | maxpool2d | maxpool2d | 50 | 52 | 50 | 51 | cadaf8cd9638d15de153c152a564ebebc69632a4 | bigcode/the-stack | train |
16d7f3cd3d835952bd4fa1d1 | train | function | def conv_net(x, weights, biases, dropout):
# Reshape input picture
x = tf.reshape(x, shape=[-1, 28, 28, 1])
# Convolution Layer
conv1 = conv2d(x, weights["wc1"], biases["bc1"])
# Max Pooling (down-sampling)
conv1 = maxpool2d(conv1, k=2)
# Convolution Layer
conv2 = conv2d(conv1, weights... | def conv_net(x, weights, biases, dropout):
# Reshape input picture
| x = tf.reshape(x, shape=[-1, 28, 28, 1])
# Convolution Layer
conv1 = conv2d(x, weights["wc1"], biases["bc1"])
# Max Pooling (down-sampling)
conv1 = maxpool2d(conv1, k=2)
# Convolution Layer
conv2 = conv2d(conv1, weights["wc2"], biases["bc2"])
# Max Pooling (down-sampling)
conv2 = m... | )
def maxpool2d(x, k=2):
# MaxPool2D wrapper
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding="SAME")
# Create model
def conv_net(x, weights, biases, dropout):
# Reshape input picture
| 78 | 78 | 263 | 18 | 59 | vsoch/caliper-analysis | tensorflow_v0.11/3_NeuralNetworks/convolutional_network.py | Python | conv_net | conv_net | 56 | 80 | 56 | 57 | 3c09bf21036b2b0d42bf79e0646c9f8a57387595 | bigcode/the-stack | train |
95f12ca7829ca45370fafed9 | train | function | def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding="SAME")
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
| def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
| x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding="SAME")
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
| = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)
# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
| 64 | 64 | 74 | 28 | 35 | vsoch/caliper-analysis | tensorflow_v0.11/3_NeuralNetworks/convolutional_network.py | Python | conv2d | conv2d | 43 | 47 | 43 | 44 | c408cae6f1fa31d2ab086acc2f45642b6f0e4b9d | bigcode/the-stack | train |
75170ecd22590b713704a2e8 | train | class | class LeveledLoadPatternParser(LoadPatternParser):
_Registry = {}
@classmethod
def register(cls, name : str):
def decorator(load_pattern_parser_class):
cls._Registry[name] = load_pattern_parser_class
return load_pattern_parser_class
return decorator
@classmet... | class LeveledLoadPatternParser(LoadPatternParser):
| _Registry = {}
@classmethod
def register(cls, name : str):
def decorator(load_pattern_parser_class):
cls._Registry[name] = load_pattern_parser_class
return load_pattern_parser_class
return decorator
@classmethod
def get(cls, name : str):
if not na... | from .pattern_parser import LoadPatternParser
class LeveledLoadPatternParser(LoadPatternParser):
| 21 | 64 | 112 | 12 | 8 | Remit/autoscaling-simulator | autoscalingsim/load/regional_load_model/load_models/parsers/patterns_parsers/leveled_load_parser.py | Python | LeveledLoadPatternParser | LeveledLoadPatternParser | 3 | 22 | 3 | 4 | de3a967d936251b5c3d9e900883ea19ae89c9b16 | bigcode/the-stack | train |
a76550c4fd51ccf0780d7568 | train | function | def calc_delta_lampamD_swap_1(
angle_first, angle_second, n_first_ply, n_second_ply, n_plies_group,
n_plies, constraints):
'''
returns the out-of-plane lamination parameters variation due to the swap
of ply groups, taking into account the two symmetric parts for symmetric
laminates... | def calc_delta_lampamD_swap_1(
angle_first, angle_second, n_first_ply, n_second_ply, n_plies_group,
n_plies, constraints):
| '''
returns the out-of-plane lamination parameters variation due to the swap
of ply groups, taking into account the two symmetric parts for symmetric
laminates - only one panel accounted for
INPUTS
- angle_first: fibre orientation of the first block of plies
- angle_second: fibre o... | el in sett for el in constraints.set_of_angles]):
# delta_lampam_D[3] = 0
return delta_lampam_D
def calc_delta_lampamD_swap_1(
angle_first, angle_second, n_first_ply, n_second_ply, n_plies_group,
n_plies, constraints):
| 75 | 75 | 251 | 40 | 34 | noemiefedon/BELLA | src/RELAY/repair_flexural_tools.py | Python | calc_delta_lampamD_swap_1 | calc_delta_lampamD_swap_1 | 150 | 174 | 150 | 152 | 9a15cedd0e5399194be98c5ae4a57f0a385aa936 | bigcode/the-stack | train |
405fa6fe7b2aca1e6a779be7 | train | function | def calc_delta_lampamD_swap(
angle_first, angle_second, pos_first, pos_second, n_plies,
constraints):
'''
returns the out-of-plane lamination parameters variation due to the
modifications of some ply fibre orientations, taking into account the two
symmetric parts for symmetric lami... | def calc_delta_lampamD_swap(
angle_first, angle_second, pos_first, pos_second, n_plies,
constraints):
| '''
returns the out-of-plane lamination parameters variation due to the
modifications of some ply fibre orientations, taking into account the two
symmetric parts for symmetric laminates - only one panel accounted for
OUTPUTS
- delta_lampam_D: out-of-plane partial lamination parameters
... | account the two symmetric parts for symmetric
# laminates - account for several panels
- find_list_blocks
divides a stacking sequence into blocks of plies at the same
fibre orientation
"""
__version__ = '1.0'
__author__ = 'Noemie Fedon'
import sys
import operator
import numpy as np
import num... | 256 | 256 | 1,073 | 29 | 226 | noemiefedon/BELLA | src/RELAY/repair_flexural_tools.py | Python | calc_delta_lampamD_swap | calc_delta_lampamD_swap | 45 | 147 | 45 | 47 | 717ded16115bf7850d9a20612fcffca4eb84307a | bigcode/the-stack | train |
69b9d09663398bb9c9694a56 | train | class | class Block():
" An object for a block of plies oriented at the same fibre orientation"
def __init__(self, ID, angle, n_block_of_plies, first_ply_pos,
n_plies, angle_before, angle_after, constraints):
self.ID = ID
self.angle = angle
self.n_block_of_plies = n_block_... | class Block():
| " An object for a block of plies oriented at the same fibre orientation"
def __init__(self, ID, angle, n_block_of_plies, first_ply_pos,
n_plies, angle_before, angle_after, constraints):
self.ID = ID
self.angle = angle
self.n_block_of_plies = n_block_of_plies
... | pdl_ref=reduced_pdl[multipanel.ind_ref])
## print('pos_in_sst_first', pos_in_sst_first)
## print('pos_in_sst_second', pos_in_sst_second)
#
# for ind_panel in range(reduced_multipanel.n_panels):
## print('ind_panel', ind_panel)
#
# pos_in_panel_first = pos_in_sst_to_pos_in_panel(
# ... | 256 | 256 | 924 | 3 | 252 | noemiefedon/BELLA | src/RELAY/repair_flexural_tools.py | Python | Block | Block | 240 | 334 | 240 | 240 | 522eeff01971dbe52bef1c467a1777fee25de67e | bigcode/the-stack | train |
239788456371e07f6bbc1411 | train | function | def find_list_blocks(ss_ref, n_plies, constraints):
"""
divides a stacking sequence into blocks of plies at the same
fibre orientation
"""
if constraints.sym:
if n_plies % 2:
ind_start = n_plies // 2 - 1
while ss_ref[ind_start] == ss_ref[n_plies // 2]:
... | def find_list_blocks(ss_ref, n_plies, constraints):
| """
divides a stacking sequence into blocks of plies at the same
fibre orientation
"""
if constraints.sym:
if n_plies % 2:
ind_start = n_plies // 2 - 1
while ss_ref[ind_start] == ss_ref[n_plies // 2]:
ind_start -= 1
else:
... | if block1.ID == self.ID - 1:
block1.neighbour_angles = []
for block2 in list_blocks:
if block2.ID == block1.ID + 1 \
or block2.ID == block1.ID - 1:
block1.neighbour_angles.append(block2.angle)
block1.c... | 182 | 183 | 611 | 13 | 169 | noemiefedon/BELLA | src/RELAY/repair_flexural_tools.py | Python | find_list_blocks | find_list_blocks | 336 | 407 | 336 | 336 | 61da0b781816b7d9f5539a9ef96c7cde7f1a4f9b | bigcode/the-stack | train |
35adc616ed119a8e73d46049 | train | function | @client.event
async def on_message(message):
with open('banks2.txt') as bankin:
bank = json.load(bankin)
# Banking Functions
if message.content.startswith('/bank'):
user = str(message.author)
operation = message.content.split()[1]
if operation in ['add', 'subtract']:
... | @client.event
async def on_message(message):
| with open('banks2.txt') as bankin:
bank = json.load(bankin)
# Banking Functions
if message.content.startswith('/bank'):
user = str(message.author)
operation = message.content.split()[1]
if operation in ['add', 'subtract']:
metal = message.content.split()[2]
... | # -*- coding: utf-8 -*-
# Imports
import json
import discord
import random
import datetime
import asyncio
client = discord.Client()
# Readiness Indicator
@client.event
async def on_ready():
print("The bot is ready!")
await client.change_presence(game=discord.Game(name="roulette with your money"))
# Remind... | 179 | 256 | 1,670 | 10 | 168 | qwerq33/WestMarchesBot | WestMarchesBot.py | Python | on_message | on_message | 39 | 219 | 39 | 40 | 0dd7e0bd4d2c1f1bb488275a35fc197f9141dade | bigcode/the-stack | train |
a20c15c31fb7d0df35ef90c4 | train | function | @client.event
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
if datetime.weekday == 0:
channel = client.get_channel("397349083318059010")
message = "Don't forget downtime!"
await client.send_message(channel, message)
... | @client.event
async def background_loop():
| await client.wait_until_ready()
while not client.is_closed:
if datetime.weekday == 0:
channel = client.get_channel("397349083318059010")
message = "Don't forget downtime!"
await client.send_message(channel, message)
await asyncio.sleep(604800)
| .event
async def on_ready():
print("The bot is ready!")
await client.change_presence(game=discord.Game(name="roulette with your money"))
# Reminder Message
# CURRENTLY NOT WORKING AS INTENDED
# Intended to send the message every Monday
@client.event
async def background_loop():
| 64 | 64 | 71 | 9 | 54 | qwerq33/WestMarchesBot | WestMarchesBot.py | Python | background_loop | background_loop | 25 | 33 | 25 | 26 | 629565690edff1a1bf5bb9982924c7c46d2fe2bd | bigcode/the-stack | train |
b9118ca002563013ce209e6d | train | function | @client.event
async def on_ready():
print("The bot is ready!")
await client.change_presence(game=discord.Game(name="roulette with your money"))
| @client.event
async def on_ready():
| print("The bot is ready!")
await client.change_presence(game=discord.Game(name="roulette with your money"))
| # -*- coding: utf-8 -*-
# Imports
import json
import discord
import random
import datetime
import asyncio
client = discord.Client()
# Readiness Indicator
@client.event
async def on_ready():
| 45 | 64 | 33 | 9 | 35 | qwerq33/WestMarchesBot | WestMarchesBot.py | Python | on_ready | on_ready | 14 | 17 | 14 | 15 | 5630670dbf9998355bab08ee3a4dd09b2666218e | bigcode/the-stack | train |
c901d42128790212b85f27da | train | class | class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'FoiAttachment.can_approve'
db.add_column('foirequest_foiattachment', 'can_approve', self.gf('django.db.models.fields.BooleanField')(default=True), keep_default=False)
def backwards(self, orm):
... | class Migration(SchemaMigration):
| def forwards(self, orm):
# Adding field 'FoiAttachment.can_approve'
db.add_column('foirequest_foiattachment', 'can_approve', self.gf('django.db.models.fields.BooleanField')(default=True), keep_default=False)
def backwards(self, orm):
# Deleting field 'FoiAttachment.ca... | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| 36 | 256 | 4,646 | 6 | 29 | rufuspollock/froide | froide/foirequest/migrations/0021_auto__add_field_foiattachment_can_approve.py | Python | Migration | Migration | 7 | 227 | 7 | 8 | 98c7c252bba6b53bb31991e8bb9e170d501041c7 | bigcode/the-stack | train |
3e0cbda41c0861de662e639c | train | class | class SealedBids(object):
def __init__(self, bids):
self.bids = np.array(bids)
@property
def num_players(self):
return self.bids.shape[1]
@property
def settlement(self):
# for each item, mark the index of the player who bids the most
winners = np.argmax(self... | class SealedBids(object):
| def __init__(self, bids):
self.bids = np.array(bids)
@property
def num_players(self):
return self.bids.shape[1]
@property
def settlement(self):
# for each item, mark the index of the player who bids the most
winners = np.argmax(self.bids, axis=1)
# f... | import numpy as np
class SealedBids(object):
| 12 | 140 | 468 | 7 | 4 | ashwinreddy/voting | socialchoice/sharing/bids.py | Python | SealedBids | SealedBids | 3 | 46 | 3 | 3 | 1e94d832c071f091f4e977cefa3d1ba8e8ed4166 | bigcode/the-stack | train |
71b10455f853ec457d2c51e1 | train | function | def cut_odd_events(end_time, event, save = True):
"""
Cuts sync pulses so that they are even (e.g recording stop before the last
trial ended)
:param end_time: Time in seconds of the end of the last trial
:param event: Syncing event to be corrected. It has to be a bunch object
(see brainb... | def cut_odd_events(end_time, event, save = True):
| """
Cuts sync pulses so that they are even (e.g recording stop before the last
trial ended)
:param end_time: Time in seconds of the end of the last trial
:param event: Syncing event to be corrected. It has to be a bunch object
(see brainbox.core bunch)
:return: even syncing for the e... | = Path(output_path)
if not output_path.exists():
output_path.mkdir()
s = _get_sync_fronts(sync, chmap['camera'])
np.save(output_path / '_Camera.times.npy', s.times[::2])
def cut_odd_events(end_time, event, save = True):
| 63 | 64 | 155 | 14 | 49 | alejandropan/working-memory | extractors.py | Python | cut_odd_events | cut_odd_events | 53 | 67 | 53 | 53 | 91c16f17d70922b87ac316e3402da916d1aa34b8 | bigcode/the-stack | train |
1f21c9c075336cfbc3903fc0 | train | function | def extract_behaviour_sync(sync, output_path=None, save=False, chmap=None):
"""
Extract wheel positions and times from sync fronts dictionary
:param sync: dictionary 'times', 'polarities' of fronts detected on sync
trace for all 16 chans
:param output_path: where to save the data
:param save: T... | def extract_behaviour_sync(sync, output_path=None, save=False, chmap=None):
| """
Extract wheel positions and times from sync fronts dictionary
:param sync: dictionary 'times', 'polarities' of fronts detected on sync
trace for all 16 chans
:param output_path: where to save the data
:param save: True/False
:param chmap: dictionary containing channel index. Default to ... | poke': 22,
'reward_pump' :21,
'reward_port':23,
'camera':16
}
output_path = Path(output_path)
if not output_path.exists():
output_path.mkdir()
s = _get_sync_fronts(sync, chmap['camera'])
np.save(output_path / '_Camera.times.npy', s.times[::2])... | 256 | 256 | 3,433 | 18 | 237 | alejandropan/working-memory | extractors.py | Python | extract_behaviour_sync | extract_behaviour_sync | 69 | 333 | 69 | 69 | d45afe89145a99af44941afe8e182c3807b0c2ce | bigcode/the-stack | train |
7400a5c9cf45dc1c664cc870 | train | function | def fix_keys(sync):
'''
Fixes keys of bunch objects to channels, polarirites and times
:param sync : bunch object with channels, polarities and times
:return : bunch file with standardized name
'''
sync['channels'] = sync.pop(sorted(sync)[0])
sync['polarities'] = sync.pop(sorted(sync)[1])
... | def fix_keys(sync):
| '''
Fixes keys of bunch objects to channels, polarirites and times
:param sync : bunch object with channels, polarities and times
:return : bunch file with standardized name
'''
sync['channels'] = sync.pop(sorted(sync)[0])
sync['polarities'] = sync.pop(sorted(sync)[1])
sync['times'] = s... | (output_path + '/' + '_trial_nosepoke_last.npy', trial_nosepoke_last)
np.save(output_path + '/' + '_trial_opto_first.npy', trial_opto_first)
np.save(output_path + '/' + '_trial_opto_last.npy', trial_opto_last)
def fix_keys(sync):
| 64 | 64 | 95 | 5 | 59 | alejandropan/working-memory | extractors.py | Python | fix_keys | fix_keys | 335 | 346 | 335 | 335 | 9480173d8c3e073ccd6ec1895305962c319166fa | bigcode/the-stack | train |
705469243388d402674f3512 | train | function | def extract_camera_sync(sync, output_path=None, save=False, chmap=None):
"""
Extract camera timestamps from the sync matrix
:param sync: dictionary 'times', 'polarities' of fronts detected on sync trace
:param output_path: where to save the data
:param save: True/False
:param chmap: dictionary c... | def extract_camera_sync(sync, output_path=None, save=False, chmap=None):
| """
Extract camera timestamps from the sync matrix
:param sync: dictionary 'times', 'polarities' of fronts detected on sync trace
:param output_path: where to save the data
:param save: True/False
:param chmap: dictionary containing channel indices. Default to constant.
:return: dictionary c... | _sync_fronts
from ibllib.io.extractors.ephys_fpga import *
from pathlib import Path
from brainbox.core import Bunch
import matplotlib.pyplot as plt
import ibllib.plots as plots
import numpy as np
import math
import sys
# Function definitions
def extract_camera_sync(sync, output_path=None, save=False, chmap=None):
| 75 | 75 | 252 | 17 | 57 | alejandropan/working-memory | extractors.py | Python | extract_camera_sync | extract_camera_sync | 22 | 50 | 22 | 22 | adebf5fe088708def5d284f063965286b52406d5 | bigcode/the-stack | train |
76496a7174d13f31dfb04701 | train | function | def read_avg_move():
avg_index = pd.DataFrame()
ds = pd.read_csv("raw-move-data/avg.csv", header = None)
ds.columns = ['county', 'avg_index']
avg_index = avg_index.append(ds)
return avg_index
| def read_avg_move():
| avg_index = pd.DataFrame()
ds = pd.read_csv("raw-move-data/avg.csv", header = None)
ds.columns = ['county', 'avg_index']
avg_index = avg_index.append(ds)
return avg_index
| ,regex=True)
move_data = move_data.dropna(axis=0, subset=[index_col])
move_data = move_data.sort_values(by="county", inplace=False)
move_data['county'] = move_data['county'].replace(replace_counties)
return move_data
def read_avg_move():
| 64 | 64 | 54 | 5 | 58 | sejaldua/covid-tracker | data/move-data/gen_move_data.py | Python | read_avg_move | read_avg_move | 41 | 46 | 41 | 41 | d7c298bf98c8760902a480934bd45d4337268cb7 | bigcode/the-stack | train |
4d0dbaf4a1b81d94c570926a | train | function | def read_move_data(week):
move_data = pd.DataFrame()
file_name = "raw-move-data/" + week + ".csv"
ds = pd.read_csv(file_name, header = 0)
ds.columns = ['county', 'move_index']
move_data = move_data.append(ds)
return move_data
| def read_move_data(week):
| move_data = pd.DataFrame()
file_name = "raw-move-data/" + week + ".csv"
ds = pd.read_csv(file_name, header = 0)
ds.columns = ['county', 'move_index']
move_data = move_data.append(ds)
return move_data
| import requests
import json
import pandas as pd
import csv
from pandas.io.json import json_normalize
import numpy as np
def read_move_data(week):
| 35 | 64 | 68 | 7 | 27 | sejaldua/covid-tracker | data/move-data/gen_move_data.py | Python | read_move_data | read_move_data | 8 | 14 | 8 | 8 | 5d0b8587a5d0a629813e1d8c1932d7232a8e5e69 | bigcode/the-stack | train |
238c34c45298c3a29e100b50 | train | function | def clean_data(move_data, replace_counties, index_col):
move_data[index_col] = move_data[index_col].replace(r'^\s*$',np.nan,regex=True)
move_data[index_col] = move_data[index_col].replace("Index",np.nan,regex=True)
move_data = move_data.dropna(axis=0, subset=[index_col])
move_data = move_data.sort_values(by="co... | def clean_data(move_data, replace_counties, index_col):
| move_data[index_col] = move_data[index_col].replace(r'^\s*$',np.nan,regex=True)
move_data[index_col] = move_data[index_col].replace("Index",np.nan,regex=True)
move_data = move_data.dropna(axis=0, subset=[index_col])
move_data = move_data.sort_values(by="county", inplace=False)
move_data['county'] = move_data[... | ["curr_name", "new_name"]
replace_counties = replace_counties.append(ds)
replace_counties = pd.Series(replace_counties.new_name.values,
index=replace_counties.curr_name).to_dict()
return replace_counties
def clean_data(move_data, replace_counties, index_col):
| 64 | 64 | 115 | 13 | 50 | sejaldua/covid-tracker | data/move-data/gen_move_data.py | Python | clean_data | clean_data | 33 | 39 | 33 | 33 | 827c5bfb54d96040c04c5da463cc4b6649b7206b | bigcode/the-stack | train |
4d1a6234af6fe2e818d858bc | train | function | def gen_data():
print("gen data start")
start = "march-02"
move_dates = ["march-09","march-16",
"march-23","march-30"]
fips = read_fips_data()
replace_counties = read_replace_data()
data = dict()
move_by_week = []
delta_by_week = []
print("getting first week data")
move_data = ge... | def gen_data():
| print("gen data start")
start = "march-02"
move_dates = ["march-09","march-16",
"march-23","march-30"]
fips = read_fips_data()
replace_counties = read_replace_data()
data = dict()
move_by_week = []
delta_by_week = []
print("getting first week data")
move_data = get_move_index(sta... | =0, subset=[index_col])
move_data = move_data.sort_values(by="county", inplace=False)
move_data['county'] = move_data['county'].replace(replace_counties)
return move_data
def read_avg_move():
avg_index = pd.DataFrame()
ds = pd.read_csv("raw-move-data/avg.csv", header = None)
ds.columns = ['county', 'avg_index... | 170 | 170 | 568 | 4 | 165 | sejaldua/covid-tracker | data/move-data/gen_move_data.py | Python | gen_data | gen_data | 56 | 117 | 56 | 56 | f0996f78f1f9353d14d9916f7f252359220a62f5 | bigcode/the-stack | train |
1c465c89ac411d060652d296 | train | function | def get_move_index(week, replace_counties):
move_data = read_move_data(week)
move_data = clean_data(move_data, replace_counties, 'move_index')
move_data['move_index'] = move_data['move_index'].astype(float)
move_data.round({'move_index': 2})
return move_data
| def get_move_index(week, replace_counties):
| move_data = read_move_data(week)
move_data = clean_data(move_data, replace_counties, 'move_index')
move_data['move_index'] = move_data['move_index'].astype(float)
move_data.round({'move_index': 2})
return move_data
| read_avg_move():
avg_index = pd.DataFrame()
ds = pd.read_csv("raw-move-data/avg.csv", header = None)
ds.columns = ['county', 'avg_index']
avg_index = avg_index.append(ds)
return avg_index
def get_move_index(week, replace_counties):
| 64 | 64 | 66 | 11 | 52 | sejaldua/covid-tracker | data/move-data/gen_move_data.py | Python | get_move_index | get_move_index | 48 | 53 | 48 | 48 | 8f147bf5c7c67b0b77f68ed8a0a1dbc41599b0d3 | bigcode/the-stack | train |
b3e96c210f8ae167fee57b8f | train | function | def read_replace_data():
replace_counties = pd.DataFrame()
ds = pd.read_csv("replace-long-counties.csv", header=0)
ds.columns = ["curr_name", "new_name"]
replace_counties = replace_counties.append(ds)
replace_counties = pd.Series(replace_counties.new_name.values,
index=replace_counties... | def read_replace_data():
| replace_counties = pd.DataFrame()
ds = pd.read_csv("replace-long-counties.csv", header=0)
ds.columns = ["curr_name", "new_name"]
replace_counties = replace_counties.append(ds)
replace_counties = pd.Series(replace_counties.new_name.values,
index=replace_counties.curr_name).to_dict()
re... | pd.read_csv("fips.csv", header = 0)
ds.columns = ["state", "sab", "sid", "sfips", "county",
"saint", "cfips", "fips"]
fips = fips.append(ds)
return fips
def read_replace_data():
| 64 | 64 | 86 | 5 | 58 | sejaldua/covid-tracker | data/move-data/gen_move_data.py | Python | read_replace_data | read_replace_data | 24 | 31 | 24 | 24 | 1a9de45413f24315ae9baeb7e1bfbd6a9d448493 | bigcode/the-stack | train |
5dbdff072991e21207c2c690 | train | function | def read_fips_data():
fips = pd.DataFrame()
ds = pd.read_csv("fips.csv", header = 0)
ds.columns = ["state", "sab", "sid", "sfips", "county",
"saint", "cfips", "fips"]
fips = fips.append(ds)
return fips
| def read_fips_data():
| fips = pd.DataFrame()
ds = pd.read_csv("fips.csv", header = 0)
ds.columns = ["state", "sab", "sid", "sfips", "county",
"saint", "cfips", "fips"]
fips = fips.append(ds)
return fips
| = pd.DataFrame()
file_name = "raw-move-data/" + week + ".csv"
ds = pd.read_csv(file_name, header = 0)
ds.columns = ['county', 'move_index']
move_data = move_data.append(ds)
return move_data
def read_fips_data():
| 64 | 64 | 76 | 6 | 57 | sejaldua/covid-tracker | data/move-data/gen_move_data.py | Python | read_fips_data | read_fips_data | 16 | 22 | 16 | 16 | 2d049b2af6252105e7df479be534a563235587be | bigcode/the-stack | train |
2abb79bb34c9bde244696d83 | train | function | def continue_line(line):
"""
:param line: line to examine to see if record continues to next
line
:return: True if record is continued, False if the record is complete
"""
if QUOTE_RE.match(line):
# if the line ends with an unclosed quote, it's continued
return True... | def continue_line(line):
| """
:param line: line to examine to see if record continues to next
line
:return: True if record is continued, False if the record is complete
"""
if QUOTE_RE.match(line):
# if the line ends with an unclosed quote, it's continued
return True
elif (line.count('"'... | #!/usr/bin/env python
import sys
import argparse
import re
QUOTE_RE = re.compile(r'.*"[^,]*$')
def continue_line(line):
| 33 | 64 | 152 | 5 | 28 | DHTC-Tools/logstash-confs | job-records/python/process_logs.py | Python | continue_line | continue_line | 11 | 29 | 11 | 11 | 40967e50010ed211bb96dd0aa156cbcb56efce0c | bigcode/the-stack | train |
fdca7ffcc953ea3142bfdd8b | train | function | def generate_log_lines(input_file, bad_file):
"""
Generator that processes csv with ATLAS records and try to fix broken lines
returns fixed lines
:param input_file: file object with input
:param badfile: file object to write lines with errors to
:return: corrected lines stripped of tabs and emb... | def generate_log_lines(input_file, bad_file):
| """
Generator that processes csv with ATLAS records and try to fix broken lines
returns fixed lines
:param input_file: file object with input
:param badfile: file object to write lines with errors to
:return: corrected lines stripped of tabs and embedded newlines
"""
buf = ""
for li... | continued
return True
elif len(line) > 2048:
# if the line is more than 2k in length, just close it and
# move to the next line
return False
else:
return False
def generate_log_lines(input_file, bad_file):
| 64 | 64 | 152 | 10 | 53 | DHTC-Tools/logstash-confs | job-records/python/process_logs.py | Python | generate_log_lines | generate_log_lines | 32 | 54 | 32 | 32 | c18011569087e6ab4469e45f3c78b1660afbbf06 | bigcode/the-stack | train |
2cc23dcc3226d4e35d218f4e | train | function | def process_records(date_string):
"""
Process log files and remove tabs and try to join broken lines
parameters:
date_string - date to start download
"""
input_file = open("jobsarchived{0}.csv".format(date_string), 'r')
output_file = open("jobsarchived{0}-processed.csv".format(date_string),... | def process_records(date_string):
| """
Process log files and remove tabs and try to join broken lines
parameters:
date_string - date to start download
"""
input_file = open("jobsarchived{0}.csv".format(date_string), 'r')
output_file = open("jobsarchived{0}-processed.csv".format(date_string), 'w')
bad_file = open("jobsarc... | _line(buf):
buf = buf.replace("\n", " ")
continue
else:
record = buf
buf = ""
if record.split(',')[1] == '':
bad_file.write(record)
# don't return bad records
continue
yield record
def process... | 64 | 64 | 124 | 6 | 57 | DHTC-Tools/logstash-confs | job-records/python/process_logs.py | Python | process_records | process_records | 57 | 70 | 57 | 57 | 534588dde3123a61ca6d0634fc47888e098f8378 | bigcode/the-stack | train |
fe6a359671d4968c9b39938d | train | class | class DRN_A(nn.Module):
def __init__(self, block, layers, BatchNorm = None):
self.inplanes = 64
super(DRN_A, self).__init__()
self.out_dim = 512 * block.expansion
self.conv1 = nn.Conv2d(3, 64, kernel_size = 7, stride = 2, padding = 3,
bias = False)
self.bn1 = BatchNorm(64)
self.re... | class DRN_A(nn.Module):
| def __init__(self, block, layers, BatchNorm = None):
self.inplanes = 64
super(DRN_A, self).__init__()
self.out_dim = 512 * block.expansion
self.conv1 = nn.Conv2d(3, 64, kernel_size = 7, stride = 2, padding = 3,
bias = False)
self.bn1 = BatchNorm(64)
self.relu = nn.ReLU(inplace = Tr... | annels),
nn.ReLU(inplace = True)])
self.inplanes = channels
return nn.Sequential(*modules)
def forward(self, x):
if self.arch == 'C':
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
elif self.arch == 'D':
x = self.layer0(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
... | 192 | 192 | 640 | 7 | 184 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | DRN_A | DRN_A | 236 | 297 | 236 | 237 | 37458e5eea5a637e8d96177ab2af68336c431dce | bigcode/the-stack | train |
15800af5be56b38e62565719 | train | function | def drn_d_22(BatchNorm, pretrained = True):
model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-22'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_d_22(BatchNorm, pretrained = True):
| model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-22'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-58'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_d_22(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_d_22 | drn_d_22 | 337 | 344 | 337 | 337 | 4b34bb9ffb719d64b6b5ee59eee5bc74304756f2 | bigcode/the-stack | train |
a0cdee02e940d74de52f4af1 | train | function | def conv3x3(in_planes, out_planes, stride = 1, padding = 1, dilation = 1):
return nn.Conv2d(in_planes, out_planes, kernel_size = 3, stride = stride,
padding = padding, bias = False, dilation = dilation)
| def conv3x3(in_planes, out_planes, stride = 1, padding = 1, dilation = 1):
| return nn.Conv2d(in_planes, out_planes, kernel_size = 3, stride = stride,
padding = padding, bias = False, dilation = dilation)
| _d_54-0e0534ff.pth',
'drn-d-105': webroot + 'drn_d_105-12b40979.pth'
}
def conv3x3(in_planes, out_planes, stride = 1, padding = 1, dilation = 1):
| 64 | 64 | 60 | 26 | 38 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | conv3x3 | conv3x3 | 20 | 22 | 20 | 20 | 7e9fda3bd027f46d4760c0c648c8e0b354f6673a | bigcode/the-stack | train |
eb4d0d3c69eb0e5083c25487 | train | class | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride = 1, downsample = None,
dilation = (1, 1), residual = True, BatchNorm = None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size = 1, bias = False)
self.bn1 = BatchNorm(pla... | class Bottleneck(nn.Module):
| expansion = 4
def __init__(self, inplanes, planes, stride = 1, downsample = None,
dilation = (1, 1), residual = True, BatchNorm = None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size = 1, bias = False)
self.bn1 = BatchNorm(planes)
self.conv2 = nn.Conv2d... | forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
if self.residual:
out += residual
out = self.relu(out)
return out
class Bottleneck(nn.Module)... | 96 | 96 | 323 | 6 | 89 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | Bottleneck | Bottleneck | 61 | 99 | 61 | 61 | d02db721a7b00da2b3eb37db10c9e156b342018d | bigcode/the-stack | train |
39a2534bf30f5dc4d31a683a | train | class | class DRN(nn.Module):
def __init__(self, block, layers, arch = 'D',
channels = (16, 32, 64, 128, 256, 512, 512, 512),
BatchNorm = None):
super(DRN, self).__init__()
self.inplanes = channels[0]
self.out_dim = channels[-1]
self.arch = arch
if arch == 'C':
self.conv1 = nn.Conv2d... | class DRN(nn.Module):
| def __init__(self, block, layers, arch = 'D',
channels = (16, 32, 64, 128, 256, 512, 512, 512),
BatchNorm = None):
super(DRN, self).__init__()
self.inplanes = channels[0]
self.out_dim = channels[-1]
self.arch = arch
if arch == 'C':
self.conv1 = nn.Conv2d(3, channels[0], kernel... | planes, kernel_size = 1, bias = False)
self.bn1 = BatchNorm(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size = 3, stride = stride,
padding = dilation[1], bias = False,
dilation = dilation[1])
self.bn2 = BatchNorm(planes)
self.conv3 = nn.Conv2d(planes,... | 256 | 256 | 1,368 | 6 | 249 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | DRN | DRN | 102 | 233 | 102 | 103 | 25ccf6f14dde5c067f5c8706c43961d4af97bea8 | bigcode/the-stack | train |
697639a7a554aa70ef244756 | train | function | def drn_d_105(BatchNorm, pretrained = True):
model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-105'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_d_105(BatchNorm, pretrained = True):
| model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-105'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-54'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_d_105(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_d_105 | drn_d_105 | 387 | 394 | 387 | 387 | 2948072aa3828fa652c37fefa52fa09e724a763f | bigcode/the-stack | train |
7deda385eadec535488ee41a | train | function | def drn_d_38(BatchNorm, pretrained = True):
model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-38'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_d_38(BatchNorm, pretrained = True):
| model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-38'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-24'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_d_38(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_d_38 | drn_d_38 | 357 | 364 | 357 | 357 | 5f51e3d3225336a0cae622ba7554ee9ef33ba414 | bigcode/the-stack | train |
8b3457127b044bdf137c1c6b | train | function | def drn_d_54(BatchNorm, pretrained = True):
model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-54'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_d_54(BatchNorm, pretrained = True):
| model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-54'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-40'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_d_54(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_d_54 | drn_d_54 | 377 | 384 | 377 | 377 | a51f84acc9ffa0788a49f251b919c28cec128354 | bigcode/the-stack | train |
026b1ef664d2916886146f59 | train | class | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride = 1, downsample = None,
dilation = (1, 1), residual = True, BatchNorm = None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride,
padding = dilation[0], dilat... | class BasicBlock(nn.Module):
| expansion = 1
def __init__(self, inplanes, planes, stride = 1, downsample = None,
dilation = (1, 1), residual = True, BatchNorm = None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride,
padding = dilation[0], dilation = dilation[0])
self.bn1... | _d_105-12b40979.pth'
}
def conv3x3(in_planes, out_planes, stride = 1, padding = 1, dilation = 1):
return nn.Conv2d(in_planes, out_planes, kernel_size = 3, stride = stride,
padding = padding, bias = False, dilation = dilation)
class BasicBlock(nn.Module):
| 78 | 78 | 263 | 6 | 72 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | BasicBlock | BasicBlock | 25 | 58 | 25 | 25 | 2898a737ebb17e96fc00bc69668f320e325d7934 | bigcode/the-stack | train |
1cd46f9524871eadfe77b8f3 | train | function | def drn_a_50(BatchNorm, pretrained = True):
model = DRN_A(Bottleneck, [3, 4, 6, 3], BatchNorm = BatchNorm)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model
| def drn_a_50(BatchNorm, pretrained = True):
| model = DRN_A(Bottleneck, [3, 4, 6, 3], BatchNorm = BatchNorm)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model
| x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
return x
def drn_a_50(BatchNorm, pretrained = True):
| 64 | 64 | 64 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_a_50 | drn_a_50 | 300 | 304 | 300 | 300 | 7a6448e1ab6e850963700b9cc8ca4297e258c8b9 | bigcode/the-stack | train |
e9ce75090a2a4cc8e03001f8 | train | function | def drn_d_24(BatchNorm, pretrained = True):
model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 2, 2], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-24'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_d_24(BatchNorm, pretrained = True):
| model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 2, 2], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-24'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-22'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_d_24(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_d_24 | drn_d_24 | 347 | 354 | 347 | 347 | a48ffb2f1faea8755d489d54314aba88e1c7f5e9 | bigcode/the-stack | train |
9025bb71273befcd5022384c | train | function | def drn_c_58(BatchNorm, pretrained = True):
model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'C', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-58'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_c_58(BatchNorm, pretrained = True):
| model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'C', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-58'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-42'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_c_58(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_c_58 | drn_c_58 | 327 | 334 | 327 | 327 | 892f2bd9e8ca2d0affdcd84321584c439e54d81f | bigcode/the-stack | train |
bd3172d4f9287acb300e2781 | train | function | def drn_d_40(BatchNorm, pretrained = True):
model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 2, 2], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-40'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_d_40(BatchNorm, pretrained = True):
| model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 2, 2], arch = 'D', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-40'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-38'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_d_40(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_d_40 | drn_d_40 | 367 | 374 | 367 | 367 | 940d282d0d10d6355f0c4b9593f65e7170a5f952 | bigcode/the-stack | train |
075ceb477ea45ff9b3c54d30 | train | function | def drn_c_42(BatchNorm, pretrained = True):
model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'C', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-42'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_c_42(BatchNorm, pretrained = True):
| model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch = 'C', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-42'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-26'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
def drn_c_42(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_c_42 | drn_c_42 | 317 | 324 | 317 | 317 | 142c57b0f26dd453d90ac1d844362ebc266936af | bigcode/the-stack | train |
404431aae93102d694162865 | train | function | def drn_c_26(BatchNorm, pretrained = True):
model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch = 'C', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-26'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| def drn_c_26(BatchNorm, pretrained = True):
| model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch = 'C', BatchNorm = BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-26'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrained)
return model
| model = DRN_A(Bottleneck, [3, 4, 6, 3], BatchNorm = BatchNorm)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model
def drn_c_26(BatchNorm, pretrained = True):
| 64 | 64 | 103 | 14 | 49 | rucnyz/pytorch-deeplab | modeling/backbone/drn.py | Python | drn_c_26 | drn_c_26 | 307 | 314 | 307 | 307 | 6bd758fb09372856f8e3ed1d0342815a6a48c927 | bigcode/the-stack | train |
5e4b222189ce332d359c5851 | train | function | def get_crafter(classifier, attack, params=None):
try:
crafter = supported_methods[attack]["class"](classifier)
except:
raise NotImplementedError("{} crafting method not supported.".format(attack))
if params:
crafter.set_params(**params)
return crafter
| def get_crafter(classifier, attack, params=None):
| try:
crafter = supported_methods[attack]["class"](classifier)
except:
raise NotImplementedError("{} crafting method not supported.".format(attack))
if params:
crafter.set_params(**params)
return crafter
| 1.}},
# "jsma": {"class": SaliencyMapMethod, "params": {"theta": 1., "gamma": 0.01, "clip_min": 0., "clip_max": 1.}}
}
def get_crafter(classifier, attack, params=None):
| 64 | 64 | 64 | 13 | 51 | alonhare/adversarial-robustness-toolbox | art/metrics.py | Python | get_crafter | get_crafter | 22 | 31 | 22 | 22 | c63cedc1e8e07461518ba3b92a991fa0794f198e | bigcode/the-stack | train |
af60dceec348df35a3f7615e | train | function | def empirical_robustness(classifier, x, attack_name, attack_params=None):
"""Compute the Empirical Robustness of a classifier object over the sample `x` for a given adversarial crafting
method `attack`. This is equivalent to computing the minimal perturbation that the attacker must introduce for a
successfu... | def empirical_robustness(classifier, x, attack_name, attack_params=None):
| """Compute the Empirical Robustness of a classifier object over the sample `x` for a given adversarial crafting
method `attack`. This is equivalent to computing the minimal perturbation that the attacker must introduce for a
successful attack. Paper link: https://arxiv.org/abs/1511.04599
:param classif... | iencyMapMethod, "params": {"theta": 1., "gamma": 0.01, "clip_min": 0., "clip_max": 1.}}
}
def get_crafter(classifier, attack, params=None):
try:
crafter = supported_methods[attack]["class"](classifier)
except:
raise NotImplementedError("{} crafting method not supported.".format(attack))
... | 120 | 120 | 402 | 18 | 101 | alonhare/adversarial-robustness-toolbox | art/metrics.py | Python | empirical_robustness | empirical_robustness | 34 | 68 | 34 | 34 | d507f5b5970e4b9332754329e9fe9cb6c5e6a9e2 | bigcode/the-stack | train |
0c8a957bffc3278bb8b90f42 | train | function | def clever_u(classifier, x, nb_batches, batch_size, radius, norm, c_init=1, pool_factor=10):
"""
Compute CLEVER score for an untargeted attack. Paper link: https://arxiv.org/abs/1801.10578
:param classifier: A trained model.
:type classifier: :class:`Classifier`
:param x: One input sample
:type... | def clever_u(classifier, x, nb_batches, batch_size, radius, norm, c_init=1, pool_factor=10):
| """
Compute CLEVER score for an untargeted attack. Paper link: https://arxiv.org/abs/1801.10578
:param classifier: A trained model.
:type classifier: :class:`Classifier`
:param x: One input sample
:type x: `np.ndarray`
:param nb_batches: Number of repetitions of the estimate
:type nb_ba... | [target]
else:
# Assume it's iterable
target_classes = target
score_list = []
for j in target_classes:
if j == pred_class:
score_list.append(None)
continue
s = clever_t(classifier, x, j, nb_batches, batch_size, radius, norm, c_init, pool_factor)
... | 115 | 115 | 386 | 28 | 87 | alonhare/adversarial-robustness-toolbox | art/metrics.py | Python | clever_u | clever_u | 182 | 216 | 182 | 182 | 5fe480f2cfabd98c9299a672fb008681f1478e82 | bigcode/the-stack | train |
0fd3bb26d5782516307774e6 | train | function | def loss_sensitivity(classifier, x, y):
"""
Local loss sensitivity estimated through the gradients of the prediction at points in `x`, as defined in
https://arxiv.org/pdf/1706.05394.pdf.
:param classifier: A trained model
:type classifier: :class:`Classifier`
:param x: Data sample of shape that... | def loss_sensitivity(classifier, x, y):
| """
Local loss sensitivity estimated through the gradients of the prediction at points in `x`, as defined in
https://arxiv.org/pdf/1706.05394.pdf.
:param classifier: A trained model
:type classifier: :class:`Classifier`
:param x: Data sample of shape that can be fed into `classifier`
:type ... | ord=2, axis=1)
# idxs = (np.argmax(y_pred, axis=1) != np.argmax(y, axis=1))
# avg_nn_dist = np.mean(dists[idxs])
#
# return avg_nn_dist
def loss_sensitivity(classifier, x, y):
| 64 | 64 | 180 | 11 | 52 | alonhare/adversarial-robustness-toolbox | art/metrics.py | Python | loss_sensitivity | loss_sensitivity | 109 | 126 | 109 | 109 | 5fd71d643b4b8eea3f7d75d6e88695e16205f7c4 | bigcode/the-stack | train |
1d525fe746212cd3c6eb0111 | train | function | def clever_t(classifier, x, target_class, nb_batches, batch_size, radius, norm, c_init=1, pool_factor=10):
"""
Compute CLEVER score for a targeted attack. Paper link: https://arxiv.org/abs/1801.10578
:param classifier: A trained model
:type classifier: :class:`Classifier`
:param x: One input sample... | def clever_t(classifier, x, target_class, nb_batches, batch_size, radius, norm, c_init=1, pool_factor=10):
| """
Compute CLEVER score for a targeted attack. Paper link: https://arxiv.org/abs/1801.10578
:param classifier: A trained model
:type classifier: :class:`Classifier`
:param x: One input sample
:type x: `np.ndarray`
:param target_class: Targeted class
:type target_class: `int`
:param... | .inf
:type norm: `int`
:param c_init: initialization of Weibull distribution
:type c_init: `float`
:param pool_factor: The factor to create a pool of random samples with size pool_factor x n_s
:type pool_factor: `int`
:return: CLEVER score
:rtype: `float`
"""
# Get a list of untarget... | 240 | 240 | 802 | 31 | 209 | alonhare/adversarial-robustness-toolbox | art/metrics.py | Python | clever_t | clever_t | 219 | 299 | 219 | 219 | 2ed8cd49342dbf16b1feb49cd2f351d4e48b9bba | bigcode/the-stack | train |
b1537eb9aa4736b4a6644390 | train | function | def clever(classifier, x, nb_batches, batch_size, radius, norm, target=None, target_sort=False, c_init=1,
pool_factor=10):
"""
Compute CLEVER score for an untargeted attack. Paper link: https://arxiv.org/abs/1801.10578
:param classifier: A trained model.
:type classifier: :class:`Classifier`... | def clever(classifier, x, nb_batches, batch_size, radius, norm, target=None, target_sort=False, c_init=1,
pool_factor=10):
| """
Compute CLEVER score for an untargeted attack. Paper link: https://arxiv.org/abs/1801.10578
:param classifier: A trained model.
:type classifier: :class:`Classifier`
:param x: One input sample
:type x: `np.ndarray`
:param nb_batches: Number of repetitions of the estimate
:type nb_ba... | param classifier: A trained model
:type classifier: :class:`Classifier`
:param x: Data sample of shape that can be fed into `classifier`
:type x: `np.ndarray`
:param y: Labels for sample `x`, one-hot encoded.
:type y: `np.ndarray`
:return: The average loss sensitivity of the model
:rtype: `f... | 164 | 164 | 547 | 35 | 129 | alonhare/adversarial-robustness-toolbox | art/metrics.py | Python | clever | clever | 129 | 179 | 129 | 130 | c104a0622451bbaf506581e04ce41c99d2c88860 | bigcode/the-stack | train |
e2f7bc3579821ed6afc73a96 | train | class | class TestAutoAllocatedTopology(base.BaseAdminNetworkTest):
"""
NOTE: This test may eventually migrate to Tempest.
Tests the Get-Me-A-Network operation in the Neutron API
using the REST client for Neutron.
"""
@classmethod
def skip_checks(cls):
super(TestAutoAllocatedTopology, cls... | class TestAutoAllocatedTopology(base.BaseAdminNetworkTest):
| """
NOTE: This test may eventually migrate to Tempest.
Tests the Get-Me-A-Network operation in the Neutron API
using the REST client for Neutron.
"""
@classmethod
def skip_checks(cls):
super(TestAutoAllocatedTopology, cls).skip_checks()
if not test.is_extension_enabled('au... | # Copyright 2016 IBM
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | 173 | 240 | 802 | 11 | 161 | BobzhouCH/neutron-nfv-acc | neutron/tests/api/test_auto_allocated_topology.py | Python | TestAutoAllocatedTopology | TestAutoAllocatedTopology | 22 | 104 | 22 | 23 | 15e0ec463383f69ce5650df6f73cad1275b2fc7c | bigcode/the-stack | train |
245fa0e1d85582718f2fc1bc | train | class | class VideoClassificationDirectoryTreeImporter(LabeledVideoDatasetImporter):
"""Importer for a viideo classification directory tree stored on disk.
See :ref:`this page <VideoClassificationDirectoryTree-import>` for format
details.
Args:
dataset_dir: the dataset directory
compute_metada... | class VideoClassificationDirectoryTreeImporter(LabeledVideoDatasetImporter):
| """Importer for a viideo classification directory tree stored on disk.
See :ref:`this page <VideoClassificationDirectoryTree-import>` for format
details.
Args:
dataset_dir: the dataset directory
compute_metadata (False): whether to produce
:class:`fiftyone.core.metadata.Vid... | "):
continue
if label == self.unlabeled:
label = None
else:
classes.add(label)
for path in etau.list_files(
class_dir, abs_paths=True, recursive=True
):
samples.append((path, label))
... | 211 | 211 | 705 | 12 | 198 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | VideoClassificationDirectoryTreeImporter | VideoClassificationDirectoryTreeImporter | 2,107 | 2,224 | 2,107 | 2,107 | a96b3fdb605ff3afea0cce98aa01e45710ec907d | bigcode/the-stack | train |
f98807fa81602b6afdfee639 | train | function | def _build_parse_sample_fcn(
dataset, dataset_importer, label_field, tags, expand_schema
):
if isinstance(dataset_importer, GenericSampleDatasetImporter):
# Generic sample dataset
#
# If the importer provides a sample field schema, apply it now
#
# This is more efficient... | def _build_parse_sample_fcn(
dataset, dataset_importer, label_field, tags, expand_schema
):
| if isinstance(dataset_importer, GenericSampleDatasetImporter):
# Generic sample dataset
#
# If the importer provides a sample field schema, apply it now
#
# This is more efficient than adding samples with
# `expand_schema == True`. Also, ensures that all fields exist... | = map(parse_sample, iter(dataset_importer))
dataset.merge_samples(
samples,
key_field=key_field,
key_fcn=key_fcn,
skip_existing=skip_existing,
insert_new=insert_new,
fields=fields,
omit_fields=omit_fields,
merge_li... | 252 | 252 | 840 | 24 | 227 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | _build_parse_sample_fcn | _build_parse_sample_fcn | 337 | 468 | 337 | 339 | bbdcc45e6e5618e41178f91d85f13d44e4068fa3 | bigcode/the-stack | train |
db86897ee39798c32d6f9a61 | train | class | class ImportPathsMixin(object):
"""Mixin for :class:`DatasetImporter` classes that provides convenience
methods for parsing the ``data_path`` and ``labels_path`` parameters
supported by many importers.
"""
@staticmethod
def _parse_data_path(dataset_dir=None, data_path=None, default=None):
... | class ImportPathsMixin(object):
| """Mixin for :class:`DatasetImporter` classes that provides convenience
methods for parsing the ``data_path`` and ``labels_path`` parameters
supported by many importers.
"""
@staticmethod
def _parse_data_path(dataset_dir=None, data_path=None, default=None):
"""Helper function that compu... | mask_targets = info.pop("mask_targets", None)
if mask_targets is not None:
mask_targets = dataset._parse_mask_targets(mask_targets)
if overwrite:
dataset.mask_targets.update(mask_targets)
else:
_update_no_overwrite(dataset.mask_targets, mask_targets)
default_mas... | 179 | 179 | 598 | 6 | 173 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | ImportPathsMixin | ImportPathsMixin | 603 | 683 | 603 | 603 | 7b11d921bf5261400b4b74b136ecc90246ecfafe | bigcode/the-stack | train |
c61c91a453001a553d8d9d6c | train | class | class FiftyOneImageLabelsDatasetImporter(LabeledImageDatasetImporter):
"""Importer for labeled image datasets whose labels are stored in
`ETA ImageLabels format <https://github.com/voxel51/eta/blob/develop/docs/image_labels_guide.md>`_.
See :ref:`this page <FiftyOneImageLabelsDataset-import>` for format
... | class FiftyOneImageLabelsDatasetImporter(LabeledImageDatasetImporter):
| """Importer for labeled image datasets whose labels are stored in
`ETA ImageLabels format <https://github.com/voxel51/eta/blob/develop/docs/image_labels_guide.md>`_.
See :ref:`this page <FiftyOneImageLabelsDataset-import>` for format
details.
Args:
dataset_dir: the dataset directory
... | (self):
return fol.Segmentation
def setup(self):
self._image_paths_map = self._load_data_map(
self.data_path, ignore_exts=True, recursive=True
)
self._mask_paths_map = {
os.path.splitext(p)[0]: os.path.join(self.labels_path, p)
for p in etau.list... | 256 | 256 | 857 | 13 | 242 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | FiftyOneImageLabelsDatasetImporter | FiftyOneImageLabelsDatasetImporter | 2,745 | 2,865 | 2,745 | 2,745 | b97606cbd1950ddb1cf589b8368544863b542384 | bigcode/the-stack | train |
d9f052abc1178a3ef5fda6c0 | train | function | def _handle_legacy_formats(dataset_importer):
if (
isinstance(dataset_importer, FiftyOneDatasetImporter)
and dataset_importer._is_legacy_format_data()
):
logger.debug(
"Found data in LegacyFiftyOneDataset format; converting to legacy "
"importer now"
)
... | def _handle_legacy_formats(dataset_importer):
| if (
isinstance(dataset_importer, FiftyOneDatasetImporter)
and dataset_importer._is_legacy_format_data()
):
logger.debug(
"Found data in LegacyFiftyOneDataset format; converting to legacy "
"importer now"
)
return dataset_importer._to_legacy_import... | _info and dataset_importer.has_dataset_info:
info = dataset_importer.get_dataset_info()
if info:
parse_dataset_info(dataset, info)
if isinstance(dataset_importer, LegacyFiftyOneDatasetImporter):
dataset_importer.import_run_results(dataset)
def _handle_legacy_... | 64 | 64 | 84 | 10 | 54 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | _handle_legacy_formats | _handle_legacy_formats | 323 | 334 | 323 | 323 | 33c37597c2275539ae11fd9a41d26199a3cba05e | bigcode/the-stack | train |
49d7824f3baf974c2566a4f6 | train | class | class GenericSampleDatasetImporter(DatasetImporter):
"""Interface for importing datasets that contain arbitrary
:class:`fiftyone.core.sample.Sample` instances.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page... | class GenericSampleDatasetImporter(DatasetImporter):
| """Interface for importing datasets that contain arbitrary
:class:`fiftyone.core.sample.Sample` instances.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for information... | _samples() "
"instead" % type(self)
)
@property
def has_dataset_info(self):
return False
def import_samples(self, dataset, tags=None):
"""Imports the samples into the given dataset.
Args:
dataset: a :class:`fiftyone.core.dataset.Dataset`
... | 125 | 125 | 417 | 9 | 116 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | GenericSampleDatasetImporter | GenericSampleDatasetImporter | 861 | 919 | 861 | 861 | 4cadab27ad99c489a2e67c2cd3a45431078bfad6 | bigcode/the-stack | train |
3d2d8d64893a7f38d750c956 | train | class | class FiftyOneVideoLabelsDatasetImporter(LabeledVideoDatasetImporter):
"""Importer for labeled video datasets whose labels are stored in
`ETA VideoLabels format <https://github.com/voxel51/eta/blob/develop/docs/video_labels_guide.md>`_.
See :ref:`this page <FiftyOneVideoLabelsDataset-import>` for format
... | class FiftyOneVideoLabelsDatasetImporter(LabeledVideoDatasetImporter):
| """Importer for labeled video datasets whose labels are stored in
`ETA VideoLabels format <https://github.com/voxel51/eta/blob/develop/docs/video_labels_guide.md>`_.
See :ref:`this page <FiftyOneVideoLabelsDataset-import>` for format
details.
Args:
dataset_dir: the dataset directory
... | return bool(self._description)
@property
def has_image_metadata(self):
return self.compute_metadata
@property
def label_cls(self):
return {
"attributes": fol.Classifications,
"detections": fol.Detections,
"polylines": fol.Polylines,
... | 256 | 256 | 911 | 13 | 243 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | FiftyOneVideoLabelsDatasetImporter | FiftyOneVideoLabelsDatasetImporter | 2,868 | 2,992 | 2,868 | 2,868 | 864256c56b249dec043cf48f60411d2b7dd10e40 | bigcode/the-stack | train |
2536f587899c8905d2e48171 | train | function | def merge_samples(
dataset,
dataset_importer,
label_field=None,
tags=None,
key_field="filepath",
key_fcn=None,
skip_existing=False,
insert_new=True,
fields=None,
omit_fields=None,
merge_lists=True,
overwrite=True,
expand_schema=True,
add_info=True,
):
"""Merge... | def merge_samples(
dataset,
dataset_importer,
label_field=None,
tags=None,
key_field="filepath",
key_fcn=None,
skip_existing=False,
insert_new=True,
fields=None,
omit_fields=None,
merge_lists=True,
overwrite=True,
expand_schema=True,
add_info=True,
):
| """Merges the samples from the given :class:`DatasetImporter` into the
dataset.
See :ref:`this guide <custom-dataset-importer>` for more details about
importing datasets in custom formats by defining your own
:class:`DatasetImporter`.
By default, samples with the same absolute ``filepath`` are... | dataset_importer:
return dataset_importer.import_samples(dataset, tags=tags)
#
# Non-batch imports
#
with dataset_importer:
parse_sample, expand_schema = _build_parse_sample_fcn(
dataset, dataset_importer, label_field, tags, expand_schema
)
try:
... | 256 | 256 | 1,543 | 72 | 183 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | merge_samples | merge_samples | 144 | 320 | 144 | 159 | d692a83dd73cb65e08d5c6d3171b088a0cb6a9c5 | bigcode/the-stack | train |
2cd53aecc1b90ed177a54283 | train | function | def parse_dataset_info(dataset, info, overwrite=True):
"""Parses the info returned by :meth:`DatasetImporter.get_dataset_info` and
stores it on the relevant properties of the dataset.
Args:
dataset: a :class:`fiftyone.core.dataset.Dataset`
info: an info dict
overwrite (True): whethe... | def parse_dataset_info(dataset, info, overwrite=True):
| """Parses the info returned by :meth:`DatasetImporter.get_dataset_info` and
stores it on the relevant properties of the dataset.
Args:
dataset: a :class:`fiftyone.core.dataset.Dataset`
info: an info dict
overwrite (True): whether to overwrite existing dataset info fields
"""
... | of %s to learn more"
% (dataset_importer_cls, dataset_importer_cls)
) from e
if warn_unused:
for key, value in unused_kwargs.items():
if value is not None:
logger.warning(
"Ignoring unsupported parameter '%s' for importer type %s",
... | 96 | 96 | 322 | 11 | 84 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | parse_dataset_info | parse_dataset_info | 552 | 596 | 552 | 552 | 78fa75ba592958cfc82ec13166f87aab031bd898 | bigcode/the-stack | train |
9572c4266d6f5987e6a5321c | train | function | def _update_no_overwrite(d, dnew):
d.update({k: v for k, v in dnew.items() if k not in d})
| def _update_no_overwrite(d, dnew):
| d.update({k: v for k, v in dnew.items() if k not in d})
| dataset.default_mask_targets:
dataset.default_mask_targets = dataset._parse_default_mask_targets(
default_mask_targets
)
if overwrite:
dataset.info.update(info)
else:
_update_no_overwrite(dataset.info, info)
dataset.save()
def _update_no_overwrite(d... | 64 | 64 | 33 | 11 | 53 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | _update_no_overwrite | _update_no_overwrite | 599 | 600 | 599 | 599 | a8d99be49b621d616a6f8da3a400fcd81bad7efc | bigcode/the-stack | train |
d0d12f9d875af78b2991752c | train | class | class UnlabeledVideoDatasetImporter(DatasetImporter):
"""Interface for importing datasets of unlabeled video samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for info... | class UnlabeledVideoDatasetImporter(DatasetImporter):
| """Interface for importing datasets of unlabeled video samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for information
about implementing/using dataset importers... | meth:`has_image_metadata` is ``False``
Raises:
StopIteration: if there are no more samples to import
"""
raise NotImplementedError("subclass must implement __next__()")
@property
def has_image_metadata(self):
"""Whether this importer produces
:class:`fiftyon... | 106 | 106 | 356 | 11 | 95 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | UnlabeledVideoDatasetImporter | UnlabeledVideoDatasetImporter | 968 | 1,011 | 968 | 968 | 58d9ad9300d604d923129a53333bd91ac571998c | bigcode/the-stack | train |
29e06d033e72d244c48664e0 | train | class | class FiftyOneTemporalDetectionDatasetImporter(
LabeledVideoDatasetImporter, ImportPathsMixin
):
"""Importer for temporal video detection datasets stored on disk in a
simple JSON format.
See :ref:`this page <FiftyOneTemporalDetectionDataset-import>` for format
details.
Args:
dataset_di... | class FiftyOneTemporalDetectionDatasetImporter(
LabeledVideoDatasetImporter, ImportPathsMixin
):
| """Importer for temporal video detection datasets stored on disk in a
simple JSON format.
See :ref:`this page <FiftyOneTemporalDetectionDataset-import>` for format
details.
Args:
dataset_dir (None): the dataset directory. If omitted, ``data_path``
and/or ``labels_path`` must be... | and os.path.isfile(self.labels_path):
labels = etas.load_json(self.labels_path)
else:
labels = {}
self._classes = labels.get("classes", None)
self._sample_parser.classes = self._classes
self._labels_map = labels.get("labels", {})
self._has_labels = any(s... | 256 | 256 | 1,284 | 20 | 236 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | FiftyOneTemporalDetectionDatasetImporter | FiftyOneTemporalDetectionDatasetImporter | 2,398 | 2,572 | 2,398 | 2,400 | e666264fa75a0f4786560adc049aed65d05d9b58 | bigcode/the-stack | train |
a2713b0a2796ce21037bf6d2 | train | function | def _read_mask(mask_path, force_grayscale=False):
# pylint: disable=no-member
mask = etai.read(mask_path, cv2.IMREAD_UNCHANGED)
if force_grayscale and mask.ndim > 1:
mask = mask[:, :, 0]
return mask
| def _read_mask(mask_path, force_grayscale=False):
# pylint: disable=no-member
| mask = etai.read(mask_path, cv2.IMREAD_UNCHANGED)
if force_grayscale and mask.ndim > 1:
mask = mask[:, :, 0]
return mask
| len(self._uuids)
@staticmethod
def _get_num_samples(dataset_dir):
# Used only by dataset zoo
return len(etau.list_files(os.path.join(dataset_dir, "data")))
def _read_mask(mask_path, force_grayscale=False):
# pylint: disable=no-member
| 63 | 64 | 63 | 20 | 43 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | _read_mask | _read_mask | 2,736 | 2,742 | 2,736 | 2,737 | 471b26c839e5ce7744c741172264e91e7155f896 | bigcode/the-stack | train |
bc0d003eb79b2c2509f56b47 | train | class | class UnlabeledImageDatasetImporter(DatasetImporter):
"""Interface for importing datasets of unlabeled image samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for info... | class UnlabeledImageDatasetImporter(DatasetImporter):
| """Interface for importing datasets of unlabeled image samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for information
about implementing/using dataset importers... | to to string
representations of :class:`fiftyone.core.fields.Field` instances
generated by ``str(field)``.
Returns:
a dict
"""
if not self.has_sample_field_schema:
raise ValueError(
"This '%s' does not provide a sample field schema"
... | 106 | 106 | 356 | 11 | 95 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | UnlabeledImageDatasetImporter | UnlabeledImageDatasetImporter | 922 | 965 | 922 | 922 | 638fae4347e401e5704497db9e40d5a99e75f02b | bigcode/the-stack | train |
010322313259cbdd889b066d | train | function | def build_dataset_importer(
dataset_type, strip_none=True, warn_unused=True, name=None, **kwargs
):
"""Builds the :class:`DatasetImporter` instance for the given parameters.
Args:
dataset_type: the :class:`fiftyone.types.dataset_types.Dataset` type
strip_none (True): whether to exclude None... | def build_dataset_importer(
dataset_type, strip_none=True, warn_unused=True, name=None, **kwargs
):
| """Builds the :class:`DatasetImporter` instance for the given parameters.
Args:
dataset_type: the :class:`fiftyone.types.dataset_types.Dataset` type
strip_none (True): whether to exclude None-valued items from ``kwargs``
warn_unused (True): whether to issue warnings for any non-None unu... | label.items()}
)
elif label is not None:
sample[label_field] = label
if frames is not None:
frame_labels = {}
for frame_number, _label in frames.items():
if isinstance(_label, dict):
fr... | 173 | 173 | 577 | 25 | 147 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | build_dataset_importer | build_dataset_importer | 471 | 549 | 471 | 473 | 4971be7bb792e0dd751f0a5cc5309e46febd3eaf | bigcode/the-stack | train |
7d9a276d878f2bec37d705fc | train | class | class DatasetImporter(object):
"""Base interface for importing datasets stored on disk into FiftyOne.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for information
abou... | class DatasetImporter(object):
| """Base interface for importing datasets stored on disk into FiftyOne.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for information
about implementing/using dataset im... | def _load_data_map(data_path, ignore_exts=False, recursive=False):
"""Helper function that parses either a data directory or a data
manifest file into a UUID -> filepath map.
"""
if ignore_exts:
to_uuid = lambda p: os.path.splitext(p)[0]
else:
to_uuid ... | 243 | 243 | 812 | 5 | 238 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | DatasetImporter | DatasetImporter | 686 | 815 | 686 | 686 | 0a4c1a8fd56f7414b461086e8e3474f79da0e4af | bigcode/the-stack | train |
9b31506e9d15bba13e82f4f2 | train | class | class ImageSegmentationDirectoryImporter(
LabeledImageDatasetImporter, ImportPathsMixin
):
"""Importer for image segmentation datasets stored on disk.
See :ref:`this page <ImageSegmentationDirectory-import>` for format
details.
Args:
dataset_dir (None): the dataset directory. If omitted, `... | class ImageSegmentationDirectoryImporter(
LabeledImageDatasetImporter, ImportPathsMixin
):
| """Importer for image segmentation datasets stored on disk.
See :ref:`this page <ImageSegmentationDirectory-import>` for format
details.
Args:
dataset_dir (None): the dataset directory. If omitted, ``data_path``
and/or ``labels_path`` must be provided
data_path (None): an o... | None and os.path.isfile(self.labels_path):
labels = etas.load_json(self.labels_path)
else:
labels = {}
self._classes = labels.get("classes", None)
self._sample_parser.classes = self._classes
self._labels_map = labels.get("labels", {})
self._has_labels = ... | 256 | 256 | 1,207 | 19 | 237 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | ImageSegmentationDirectoryImporter | ImageSegmentationDirectoryImporter | 2,575 | 2,733 | 2,575 | 2,577 | 27e64cd44cfc5b39af295309e8a12c2f4ed68dd0 | bigcode/the-stack | train |
295c2aea1342a69a10df8b2e | train | class | class FiftyOneImageClassificationDatasetImporter(
LabeledImageDatasetImporter, ImportPathsMixin
):
"""Importer for image classification datasets stored on disk in a simple
JSON format.
See :ref:`this page <FiftyOneImageClassificationDataset-import>` for format
details.
Args:
dataset_di... | class FiftyOneImageClassificationDatasetImporter(
LabeledImageDatasetImporter, ImportPathsMixin
):
| """Importer for image classification datasets stored on disk in a simple
JSON format.
See :ref:`this page <FiftyOneImageClassificationDataset-import>` for format
details.
Args:
dataset_dir (None): the dataset directory. If omitted, ``data_path``
and/or ``labels_path`` must be p... | __len__(self):
return self._num_samples
def __next__(self):
video_path = next(self._iter_filepaths)
if self.compute_metadata:
video_metadata = fom.VideoMetadata.build_for(video_path)
else:
video_metadata = None
return video_path, video_metadata
... | 256 | 256 | 1,225 | 20 | 236 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | FiftyOneImageClassificationDatasetImporter | FiftyOneImageClassificationDatasetImporter | 1,823 | 1,988 | 1,823 | 1,825 | 22e092bcce5de9d8354f3d6762435a9d8eabe00d | bigcode/the-stack | train |
722dd9f52ddd33e3481c922b | train | class | class LabeledImageDatasetImporter(DatasetImporter):
"""Interface for importing datasets of labeled image samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for informat... | class LabeledImageDatasetImporter(DatasetImporter):
| """Interface for importing datasets of labeled image samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for information
about implementing/using dataset importers.
... | """Returns information about the next sample in the dataset.
Returns:
an ``(video_path, video_metadata)`` tuple, where
- ``video_path``: the path to the video on disk
- ``video_metadata``: an
:class:`fiftyone.core.metadata.VideoMetadata` instance... | 186 | 186 | 620 | 10 | 176 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | LabeledImageDatasetImporter | LabeledImageDatasetImporter | 1,014 | 1,081 | 1,014 | 1,014 | 030d98f79ffa1b253d475588727937c5949747e2 | bigcode/the-stack | train |
e96ff88ae78b57cead4fd9ea | train | class | class FiftyOneDatasetImporter(BatchDatasetImporter):
"""Importer for FiftyOne datasets stored on disk in serialized JSON format.
See :ref:`this page <FiftyOneDataset-import>` for format details.
Args:
dataset_dir: the dataset directory
rel_dir (None): a relative directory to prepend to the... | class FiftyOneDatasetImporter(BatchDatasetImporter):
| """Importer for FiftyOne datasets stored on disk in serialized JSON format.
See :ref:`this page <FiftyOneDataset-import>` for format details.
Args:
dataset_dir: the dataset directory
rel_dir (None): a relative directory to prepend to the ``filepath``
of each sample if the filep... | )
dataset._doc.evaluations.update(d)
_import_run_results(
dataset,
self._eval_dir,
foe.EvaluationMethod,
keys=list(d.keys()),
)
dataset._doc.save()
@staticmethod
def _get_classes(dataset_dir):
... | 256 | 256 | 1,702 | 10 | 246 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | FiftyOneDatasetImporter | FiftyOneDatasetImporter | 1,402 | 1,644 | 1,402 | 1,402 | dc563cca33504641b6206ba49e63f296972f239e | bigcode/the-stack | train |
cfad90b9bcb835165e7d3bc4 | train | class | class LegacyFiftyOneDatasetImporter(GenericSampleDatasetImporter):
"""Legacy importer for FiftyOne datasets stored on disk in a serialized
JSON format.
.. warning::
The :class:`fiftyone.types.dataset_types.FiftyOneDataset` format was
upgraded in ``fiftyone==0.8`` and this importer is now d... | class LegacyFiftyOneDatasetImporter(GenericSampleDatasetImporter):
| """Legacy importer for FiftyOne datasets stored on disk in a serialized
JSON format.
.. warning::
The :class:`fiftyone.types.dataset_types.FiftyOneDataset` format was
upgraded in ``fiftyone==0.8`` and this importer is now deprecated.
However, to maintain backwards compatibility,
... | may return
"""
raise NotImplementedError("subclass must implement label_cls")
@property
def frame_labels_cls(self):
"""The :class:`fiftyone.core.labels.Label` class(es) returned by this
importer within the frame labels that it produces.
This can be any of the following... | 256 | 256 | 1,508 | 12 | 244 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | LegacyFiftyOneDatasetImporter | LegacyFiftyOneDatasetImporter | 1,187 | 1,399 | 1,187 | 1,187 | d2fc597200cf7d4eca2823d5f1b826da69dd2c52 | bigcode/the-stack | train |
fca6eb74817c97b049109d61 | train | function | def import_samples(
dataset,
dataset_importer,
label_field=None,
tags=None,
expand_schema=True,
add_info=True,
):
"""Adds the samples from the given :class:`DatasetImporter` to the dataset.
See :ref:`this guide <custom-dataset-importer>` for more details about
importing datasets in ... | def import_samples(
dataset,
dataset_importer,
label_field=None,
tags=None,
expand_schema=True,
add_info=True,
):
| """Adds the samples from the given :class:`DatasetImporter` to the dataset.
See :ref:`this guide <custom-dataset-importer>` for more details about
importing datasets in custom formats by defining your own
:class:`DatasetImporter`.
Args:
dataset: a :class:`fiftyone.core.dataset.Dataset`
... |
import fiftyone.core.annotation as foa
import fiftyone.core.brain as fob
import fiftyone.core.dataset as fod
import fiftyone.core.evaluation as foe
import fiftyone.core.frame as fof
import fiftyone.core.labels as fol
import fiftyone.core.metadata as fom
import fiftyone.core.media as fomm
import fiftyone.core.odm as f... | 207 | 207 | 693 | 32 | 175 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | import_samples | import_samples | 50 | 141 | 50 | 57 | 905ab49dd1d95fde53435638b765f652a760cc92 | bigcode/the-stack | train |
eeb1dfc8c61789d222ad7d49 | train | class | class LabeledVideoDatasetImporter(DatasetImporter):
"""Interface for importing datasets of labeled video samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for informat... | class LabeledVideoDatasetImporter(DatasetImporter):
| """Interface for importing datasets of labeled video samples.
Typically, dataset importers should implement the parameters documented on
this class, although this is not mandatory.
See :ref:`this page <writing-a-custom-dataset-importer>` for information
about implementing/using dataset importers.
... | :class:`fiftyone.core.metadata.ImageMetadata` instances for each image.
"""
raise NotImplementedError("subclass must implement has_image_metadata")
@property
def label_cls(self):
"""The :class:`fiftyone.core.labels.Label` class(es) returned by this
importer.
This can b... | 256 | 256 | 966 | 10 | 246 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | LabeledVideoDatasetImporter | LabeledVideoDatasetImporter | 1,084 | 1,184 | 1,084 | 1,084 | fd00bd3b903953ffc8f3d906e997f58c68bdddb0 | bigcode/the-stack | train |
9f0db4478c643741a001c407 | train | function | def _import_run_results(dataset, run_dir, run_cls, keys=None):
if keys is None:
keys = [os.path.splitext(f)[0] for f in etau.list_files(run_dir)]
for key in keys:
json_path = os.path.join(run_dir, key + ".json")
if os.path.exists(json_path):
view = run_cls.load_run_view(data... | def _import_run_results(dataset, run_dir, run_cls, keys=None):
| if keys is None:
keys = [os.path.splitext(f)[0] for f in etau.list_files(run_dir)]
for key in keys:
json_path = os.path.join(run_dir, key + ".json")
if os.path.exists(json_path):
view = run_cls.load_run_view(dataset, key)
run_info = run_cls.get_run_info(dataset, ... | " not in metadata
def _to_legacy_importer(self):
return LegacyFiftyOneDatasetImporter(
self.dataset_dir,
shuffle=self.shuffle,
seed=self.seed,
max_samples=self.max_samples,
)
def _import_run_results(dataset, run_dir, run_cls, keys=None):
| 64 | 64 | 134 | 16 | 48 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | _import_run_results | _import_run_results | 1,647 | 1,658 | 1,647 | 1,647 | 8708bb0bc8b6b1e5b755e2f1de5121ba1a03d7e8 | bigcode/the-stack | train |
f57db0d6253ed8af32f77782 | train | class | class ImageDirectoryImporter(UnlabeledImageDatasetImporter):
"""Importer for a directory of images stored on disk.
See :ref:`this page <ImageDirectory-import>` for format details.
Args:
dataset_dir: the dataset directory
recursive (True): whether to recursively traverse subdirectories
... | class ImageDirectoryImporter(UnlabeledImageDatasetImporter):
| """Importer for a directory of images stored on disk.
See :ref:`this page <ImageDirectory-import>` for format details.
Args:
dataset_dir: the dataset directory
recursive (True): whether to recursively traverse subdirectories
compute_metadata (False): whether to produce
... | .seed,
max_samples=self.max_samples,
)
def _import_run_results(dataset, run_dir, run_cls, keys=None):
if keys is None:
keys = [os.path.splitext(f)[0] for f in etau.list_files(run_dir)]
for key in keys:
json_path = os.path.join(run_dir, key + ".json")
if os.path.exi... | 156 | 156 | 520 | 11 | 145 | pixta-dev/fiftyone | fiftyone/utils/data/importers.py | Python | ImageDirectoryImporter | ImageDirectoryImporter | 1,661 | 1,739 | 1,661 | 1,661 | 266b6ed4fa796c4e23a9cab2903aa6805e70554a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.