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
f4d59ea2da37b9540c5730eb
train
function
def create_user(username: str, email: str, password: Optional[str]) -> None: with sqlite3.connect(db_file) as db: cur = db.cursor() registered_time = time() cur.execute("""INSERT INTO users ( username, email, registered_time, last_login_time, ...
def create_user(username: str, email: str, password: Optional[str]) -> None:
with sqlite3.connect(db_file) as db: cur = db.cursor() registered_time = time() cur.execute("""INSERT INTO users ( username, email, registered_time, last_login_time, password_hash ) VALUES (?, ?, ?, ?, ?);""", [ ...
Does not check whether that user actually exists. """ session["user"] = user_id def logout(): """ Clears the session variable corresponding to logged-in username. """ session.pop("user") def create_user(username: str, email: str, password: Optional[str]) -> None:
64
64
103
19
45
hinsley/infinite-go
user_db.py
Python
create_user
create_user
31
49
31
31
bdf9e356c2542b8f988ea9cbb0f8ed28dc0041fa
bigcode/the-stack
train
aab46af201d66b09ab6ad892
train
function
def login(user_id: int): """ Forces a login as the specified user. Does not check whether that user actually exists. """ session["user"] = user_id
def login(user_id: int):
""" Forces a login as the specified user. Does not check whether that user actually exists. """ session["user"] = user_id
session import errno import hashlib import json import os import re import sqlite3 from time import time from typing import List, Optional with open("config.json") as f: cfg = json.load(f) db_file = "data/database.db" def login(user_id: int):
64
64
39
7
57
hinsley/infinite-go
user_db.py
Python
login
login
18
23
18
18
29b0d49490303a2cb391d9b6909d8d7d9d49be4c
bigcode/the-stack
train
b98c14bbd8ea6faed4d21cbf
train
function
def logout(): """ Clears the session variable corresponding to logged-in username. """ session.pop("user")
def logout():
""" Clears the session variable corresponding to logged-in username. """ session.pop("user")
("config.json") as f: cfg = json.load(f) db_file = "data/database.db" def login(user_id: int): """ Forces a login as the specified user. Does not check whether that user actually exists. """ session["user"] = user_id def logout():
64
64
24
3
60
hinsley/infinite-go
user_db.py
Python
logout
logout
25
29
25
25
c7389910713c2d96093d04f941d71ce0cb164139
bigcode/the-stack
train
6fb72f19615faf81b1887bd6
train
function
def get_user_info(user_id: int, *fields: List[str]): with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute(f"""SELECT {", ".join(fields)} FROM users WHERE id = ?""", [user_id]) return cur.fetchone()
def get_user_info(user_id: int, *fields: List[str]):
with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute(f"""SELECT {", ".join(fields)} FROM users WHERE id = ?""", [user_id]) return cur.fetchone()
email, registered_time, last_login_time, password_hash ) VALUES (?, ?, ?, ?, ?);""", [ username, email, registered_time, registered_time, hash_password(password) ]) def get_user_info(user_id: int, *f...
64
64
61
15
49
hinsley/infinite-go
user_db.py
Python
get_user_info
get_user_info
51
57
51
51
387ef2a96fe342cfc5407b4cfde88f4bb369367c
bigcode/the-stack
train
6f750b64172c1bcd0511139e
train
function
def get_user_id_from_email(email: str) -> int: with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("SELECT id FROM users WHERE email = ?", [email]) result = cur.fetchone() if result is None: return None return result[0]
def get_user_id_from_email(email: str) -> int:
with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("SELECT id FROM users WHERE email = ?", [email]) result = cur.fetchone() if result is None: return None return result[0]
fields: List[str]): with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute(f"""SELECT {", ".join(fields)} FROM users WHERE id = ?""", [user_id]) return cur.fetchone() def get_user_id_from_email(email: str) -> int:
64
64
68
13
51
hinsley/infinite-go
user_db.py
Python
get_user_id_from_email
get_user_id_from_email
59
69
59
59
7766debba14ac4b8a9226165c770390bb0040a82
bigcode/the-stack
train
d961acf8e513182ba641f672
train
function
def validate_username(username: str) -> bool: """ Returns True if valid, False if invalid. """ return re.fullmatch(r"[a-z0-9_]{3,16}", username) is not None
def validate_username(username: str) -> bool:
""" Returns True if valid, False if invalid. """ return re.fullmatch(r"[a-z0-9_]{3,16}", username) is not None
) def validate_password(password: str) -> bool: """ Returns True if valid, False if invalid. """ return re.fullmatch(r"[A-Za-z0-9@#$%^&+=]{8,30}", password) is not None def validate_username(username: str) -> bool:
64
64
48
10
53
hinsley/infinite-go
user_db.py
Python
validate_username
validate_username
108
112
108
108
fd756cebfd88ae1f804e8a91e5d902ff6b96d775
bigcode/the-stack
train
820eaeb789a31f225ff5ce36
train
function
def hash_password(password: Optional[str]) -> str: if password is None: # For SAI. return "" salted_password = password + cfg["password salt"] return hashlib.sha256(bytes(salted_password, "utf-8")).hexdigest()
def hash_password(password: Optional[str]) -> str:
if password is None: # For SAI. return "" salted_password = password + cfg["password salt"] return hashlib.sha256(bytes(salted_password, "utf-8")).hexdigest()
def get_user_id_from_username(username: str) -> int: with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("SELECT id FROM users WHERE username = ?", [username]) return cur.fetchone()[0] def hash_password(password: Optional[str]) -> str:
64
64
54
11
53
hinsley/infinite-go
user_db.py
Python
hash_password
hash_password
79
84
79
79
a9c66ed46738710a4b0af564951e981011d846be
bigcode/the-stack
train
ee054a3b130bf3bda0b7955e
train
function
def get_user_id_from_username(username: str) -> int: with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("SELECT id FROM users WHERE username = ?", [username]) return cur.fetchone()[0]
def get_user_id_from_username(username: str) -> int:
with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("SELECT id FROM users WHERE username = ?", [username]) return cur.fetchone()[0]
.connect(db_file) as db: cur = db.cursor() cur.execute("SELECT id FROM users WHERE email = ?", [email]) result = cur.fetchone() if result is None: return None return result[0] def get_user_id_from_username(username: str) -> int:
64
64
53
13
51
hinsley/infinite-go
user_db.py
Python
get_user_id_from_username
get_user_id_from_username
71
77
71
71
4276f1742caa8ad035a34fdf07eaa9a685209542
bigcode/the-stack
train
ed05e1a9e367c2487962e49c
train
class
class GroupStatusResponse(Group): pass
class GroupStatusResponse(Group):
pass
"""This module contains the GroupStatusResponse domain model.""" from .group import Group class GroupStatusResponse(Group):
23
64
9
6
16
ConsenSys/mythx-models
mythx_models/response/group_status.py
Python
GroupStatusResponse
GroupStatusResponse
6
7
6
6
fc49bc69fdba8b16772f0d18aa7a47e90e961baf
bigcode/the-stack
train
b113ce767ebb301a782b4d2d
train
function
def get_roles_with_permission(permission): ''' returns the roles with the permission requested ''' roles = [] for role in ROLE_PERMISSIONS: permissions = ROLE_PERMISSIONS[role] if permission in permissions or 'admin' in permissions: roles.append(role) return roles
def get_roles_with_permission(permission):
''' returns the roles with the permission requested ''' roles = [] for role in ROLE_PERMISSIONS: permissions = ROLE_PERMISSIONS[role] if permission in permissions or 'admin' in permissions: roles.append(role) return roles
roles.append(dict(text=trans_role(role), value=role)) return roles def roles_trans(): ''' return dict of roles with translation ''' roles = {} for role in ROLE_PERMISSIONS: roles[role] = trans_role(role) return roles def get_roles_with_permission(permission):
64
64
59
7
56
opendata-ee/ckan
ckan/new_authz.py
Python
get_roles_with_permission
get_roles_with_permission
242
249
242
242
17d16cfe82d1cf4dce3f8df4765e35780318a90a
bigcode/the-stack
train
d09cb3c893fa804c7b920101
train
function
def has_user_permission_for_group_or_org(group_id, user_name, permission): ''' Check if the user has the given permissions for the group, allowing for sysadmin rights and permission cascading down a group hierarchy. ''' if not group_id: return False group = model.Group.get(group_id) if ...
def has_user_permission_for_group_or_org(group_id, user_name, permission):
''' Check if the user has the given permissions for the group, allowing for sysadmin rights and permission cascading down a group hierarchy. ''' if not group_id: return False group = model.Group.get(group_id) if not group: return False group_id = group.id # Sys admins c...
get_roles_with_permission(permission): ''' returns the roles with the permission requested ''' roles = [] for role in ROLE_PERMISSIONS: permissions = ROLE_PERMISSIONS[role] if permission in permissions or 'admin' in permissions: roles.append(role) return roles def has_user_p...
74
74
248
16
57
opendata-ee/ckan
ckan/new_authz.py
Python
has_user_permission_for_group_or_org
has_user_permission_for_group_or_org
252
281
252
252
097ebba392a09e91d9565657ad003f680f42ad96
bigcode/the-stack
train
9d7bcb2dc0eeb7e5cdbcafdb
train
function
def clear_auth_functions_cache(): _AuthFunctions.clear() CONFIG_PERMISSIONS.clear()
def clear_auth_functions_cache():
_AuthFunctions.clear() CONFIG_PERMISSIONS.clear()
resolved_auth_function_plugins[name] = plugin.name fetched_auth_functions[name] = auth_function # Use the updated ones in preference to the originals. self._functions.update(fetched_auth_functions) _AuthFunctions = AuthFunctions() #remove the class del AuthFunctions def clear_auth_func...
64
64
18
6
57
opendata-ee/ckan
ckan/new_authz.py
Python
clear_auth_functions_cache
clear_auth_functions_cache
99
101
99
99
6887655bd1440f2bdfb3f591ad6cd57976069af1
bigcode/the-stack
train
fade88f2e8176566e723cbf9
train
function
@maintain.deprecated('Use auth_is_loggedin_user instead') def auth_is_registered_user(): ''' This function is deprecated, please use the auth_is_loggedin_user instead ''' return auth_is_loggedin_user()
@maintain.deprecated('Use auth_is_loggedin_user instead') def auth_is_registered_user():
''' This function is deprecated, please use the auth_is_loggedin_user instead ''' return auth_is_loggedin_user()
: # most permissions are boolean CONFIG_PERMISSIONS[perm] = asbool(CONFIG_PERMISSIONS[perm]) if permission in CONFIG_PERMISSIONS: return CONFIG_PERMISSIONS[permission] return False @maintain.deprecated('Use auth_is_loggedin_user instead') def auth_is_registered_user():
64
64
48
20
43
opendata-ee/ckan
ckan/new_authz.py
Python
auth_is_registered_user
auth_is_registered_user
419
424
419
420
fa7583c5938c0bb5fd084ed7eb2a184f6a35d57c
bigcode/the-stack
train
ec832b854d4a1dc1b63ea056
train
function
def users_role_for_group_or_org(group_id, user_name): ''' Returns the user's role for the group. (Ignores privileges that cascade in a group hierarchy.) ''' if not group_id: return None group_id = model.Group.get(group_id).id user_id = get_user_id_for_username(user_name, allow_none=Tru...
def users_role_for_group_or_org(group_id, user_name):
''' Returns the user's role for the group. (Ignores privileges that cascade in a group hierarchy.) ''' if not group_id: return None group_id = model.Group.get(group_id).id user_id = get_user_id_for_username(user_name, allow_none=True) if not user_id: return None # get a...
required permission # admin permission allows anything for the group for row in q.all(): perms = ROLE_PERMISSIONS.get(row.capacity, []) if 'admin' in perms or permission in perms: return True return False def users_role_for_group_or_org(group_id, user_name):
64
64
180
13
50
opendata-ee/ckan
ckan/new_authz.py
Python
users_role_for_group_or_org
users_role_for_group_or_org
309
330
309
309
40f5a4f63e677612296386b73527d1c7af5f3efb
bigcode/the-stack
train
c1f5fbb85aaebb17b3834677
train
function
def roles_list(): ''' returns list of roles for forms ''' roles = [] for role in ROLE_PERMISSIONS: roles.append(dict(text=trans_role(role), value=role)) return roles
def roles_list():
''' returns list of roles for forms ''' roles = [] for role in ROLE_PERMISSIONS: roles.append(dict(text=trans_role(role), value=role)) return roles
_role_admin(): return _('Admin') def _trans_role_editor(): return _('Editor') def _trans_role_member(): return _('Member') def trans_role(role): module = sys.modules[__name__] return getattr(module, '_trans_role_%s' % role)() def roles_list():
64
64
43
4
60
opendata-ee/ckan
ckan/new_authz.py
Python
roles_list
roles_list
226
231
226
226
c7002762504355c163785a0df260ab486a02ecad
bigcode/the-stack
train
2cd1faab08f5b3fec19c82c1
train
function
def clean_action_name(action_name): ''' Used to convert old style action names into new style ones ''' new_action_name = re.sub('package', 'dataset', action_name) # CS: bad_spelling ignore return re.sub('licence', 'license', new_action_name)
def clean_action_name(action_name):
''' Used to convert old style action names into new style ones ''' new_action_name = re.sub('package', 'dataset', action_name) # CS: bad_spelling ignore return re.sub('licence', 'license', new_action_name)
_PERMISSIONS.clear() def auth_functions_list(): '''Returns a list of the names of the auth functions available. Currently this is to allow the Auth Audit to know if an auth function is available for a given action.''' return _AuthFunctions.keys() def clean_action_name(action_name):
64
64
61
7
57
opendata-ee/ckan
ckan/new_authz.py
Python
clean_action_name
clean_action_name
111
115
111
111
9fbef4eb0a0ebdb67d1891276fcb0a6711ae96d8
bigcode/the-stack
train
c586446e042b5893a4664fac
train
function
def roles_trans(): ''' return dict of roles with translation ''' roles = {} for role in ROLE_PERMISSIONS: roles[role] = trans_role(role) return roles
def roles_trans():
''' return dict of roles with translation ''' roles = {} for role in ROLE_PERMISSIONS: roles[role] = trans_role(role) return roles
__] return getattr(module, '_trans_role_%s' % role)() def roles_list(): ''' returns list of roles for forms ''' roles = [] for role in ROLE_PERMISSIONS: roles.append(dict(text=trans_role(role), value=role)) return roles def roles_trans():
64
64
39
4
59
opendata-ee/ckan
ckan/new_authz.py
Python
roles_trans
roles_trans
234
239
234
234
a3b6f34c29d63bbae878ee14a9d44fefb396e9da
bigcode/the-stack
train
80b07decc6890559c8e06078
train
function
def is_authorized_boolean(action, context, data_dict=None): ''' runs the auth function but just returns True if allowed else False ''' outcome = is_authorized(action, context, data_dict=data_dict) return outcome.get('success', False)
def is_authorized_boolean(action, context, data_dict=None):
''' runs the auth function but just returns True if allowed else False ''' outcome = is_authorized(action, context, data_dict=data_dict) return outcome.get('success', False)
== group_id) \ .filter(model.Member.table_name == 'user') \ .filter(model.Member.state == 'active') \ .filter(model.Member.capacity == 'admin') return [a.table_id for a in q.all()] def is_authorized_boolean(action, context, data_dict=None):
63
64
54
13
50
opendata-ee/ckan
ckan/new_authz.py
Python
is_authorized_boolean
is_authorized_boolean
151
155
151
151
89998cc4f8e7d6bb8127945b52cd1fd9f1a9a872
bigcode/the-stack
train
33c77d5f6ef0074c22582648
train
function
def get_user_id_for_username(user_name, allow_none=False): ''' Helper function to get user id ''' # first check if we have the user object already and get from there try: if c.userobj and c.userobj.name == user_name: return c.userobj.id except TypeError: # c is not available ...
def get_user_id_for_username(user_name, allow_none=False):
''' Helper function to get user id ''' # first check if we have the user object already and get from there try: if c.userobj and c.userobj.name == user_name: return c.userobj.id except TypeError: # c is not available pass user = model.User.get(user_name) if us...
q = model.Session.query(model.Group) \ .filter(model.Group.is_organization == True) \ .filter(model.Group.state == 'active') \ .filter(model.Group.id.in_(group_ids)) return bool(q.count()) def get_user_id_for_username(user_name, allow_none=False):
64
64
113
13
51
opendata-ee/ckan
ckan/new_authz.py
Python
get_user_id_for_username
get_user_id_for_username
364
378
364
364
6e7fe4e92b29cb9badbf269c5675c09c7fd14189
bigcode/the-stack
train
9a36dff95f7869f0bc0fe7d6
train
function
def get_group_or_org_admin_ids(group_id): if not group_id: return [] group_id = model.Group.get(group_id).id q = model.Session.query(model.Member) \ .filter(model.Member.group_id == group_id) \ .filter(model.Member.table_name == 'user') \ .filter(model.Member.state == 'active...
def get_group_or_org_admin_ids(group_id):
if not group_id: return [] group_id = model.Group.get(group_id).id q = model.Session.query(model.Member) \ .filter(model.Member.group_id == group_id) \ .filter(model.Member.table_name == 'user') \ .filter(model.Member.state == 'active') \ .filter(model.Member.capacity...
DB try: if c.userobj and c.userobj.name == username: return c.userobj except TypeError: # c is not available pass # Get user from the DB return model.User.get(username) def get_group_or_org_admin_ids(group_id):
64
64
98
10
54
opendata-ee/ckan
ckan/new_authz.py
Python
get_group_or_org_admin_ids
get_group_or_org_admin_ids
139
148
139
139
00e3be275757b8a65dc8de548828a09077ba2535
bigcode/the-stack
train
04dbda499a1ff43d4924cab4
train
function
def _trans_role_editor(): return _('Editor')
def _trans_role_editor():
return _('Editor')
MISSIONS = OrderedDict([ ('admin', ['admin']), ('editor', ['read', 'delete_dataset', 'create_dataset', 'update_dataset', 'manage_group']), ('member', ['read', 'manage_group']), ]) def _trans_role_admin(): return _('Admin') def _trans_role_editor():
64
64
11
6
58
opendata-ee/ckan
ckan/new_authz.py
Python
_trans_role_editor
_trans_role_editor
213
214
213
213
a961626fde2ee550e0b37617cbc799d51c7ff5d9
bigcode/the-stack
train
8ddc8d0c7e247dc2bad1ac02
train
function
def _trans_role_admin(): return _('Admin')
def _trans_role_admin():
return _('Admin')
# these are the permissions that roles have ROLE_PERMISSIONS = OrderedDict([ ('admin', ['admin']), ('editor', ['read', 'delete_dataset', 'create_dataset', 'update_dataset', 'manage_group']), ('member', ['read', 'manage_group']), ]) def _trans_role_admin():
64
64
11
6
58
opendata-ee/ckan
ckan/new_authz.py
Python
_trans_role_admin
_trans_role_admin
209
210
209
209
1857af772bc8f7e4e523546999b4ce911ea27636
bigcode/the-stack
train
6f809d1e04269d58626ca2fb
train
function
def _trans_role_member(): return _('Member')
def _trans_role_member():
return _('Member')
']), ('editor', ['read', 'delete_dataset', 'create_dataset', 'update_dataset', 'manage_group']), ('member', ['read', 'manage_group']), ]) def _trans_role_admin(): return _('Admin') def _trans_role_editor(): return _('Editor') def _trans_role_member():
64
64
11
6
58
opendata-ee/ckan
ckan/new_authz.py
Python
_trans_role_member
_trans_role_member
217
218
217
217
97cb2366154abd14f1c97bd517898da847d65aaf
bigcode/the-stack
train
e9e278fa9102f3f071fa3826
train
function
def trans_role(role): module = sys.modules[__name__] return getattr(module, '_trans_role_%s' % role)()
def trans_role(role):
module = sys.modules[__name__] return getattr(module, '_trans_role_%s' % role)()
_dataset', 'create_dataset', 'update_dataset', 'manage_group']), ('member', ['read', 'manage_group']), ]) def _trans_role_admin(): return _('Admin') def _trans_role_editor(): return _('Editor') def _trans_role_member(): return _('Member') def trans_role(role):
64
64
30
5
59
opendata-ee/ckan
ckan/new_authz.py
Python
trans_role
trans_role
221
223
221
221
f216da49dcfb0274441aeb6ae7901f148a503844
bigcode/the-stack
train
8aa3e13e3ab6897caadc806a
train
function
def auth_functions_list(): '''Returns a list of the names of the auth functions available. Currently this is to allow the Auth Audit to know if an auth function is available for a given action.''' return _AuthFunctions.keys()
def auth_functions_list():
'''Returns a list of the names of the auth functions available. Currently this is to allow the Auth Audit to know if an auth function is available for a given action.''' return _AuthFunctions.keys()
auth_function # Use the updated ones in preference to the originals. self._functions.update(fetched_auth_functions) _AuthFunctions = AuthFunctions() #remove the class del AuthFunctions def clear_auth_functions_cache(): _AuthFunctions.clear() CONFIG_PERMISSIONS.clear() def auth_functions_list...
64
64
53
5
59
opendata-ee/ckan
ckan/new_authz.py
Python
auth_functions_list
auth_functions_list
104
108
104
104
b2f2729c2e058935e1ee541bb8d5de84cf8cd426
bigcode/the-stack
train
a73d867f6fa31e6f03c31538
train
class
class AuthFunctions: ''' This is a private cache used by get_auth_function() and should never be accessed directly. We will create an instance of it and then delete this class.''' _functions = {} def clear(self): ''' clear any stored auth functions. ''' self._functions.clear() ...
class AuthFunctions:
''' This is a private cache used by get_auth_function() and should never be accessed directly. We will create an instance of it and then delete this class.''' _functions = {} def clear(self): ''' clear any stored auth functions. ''' self._functions.clear() def keys(self): ...
import sys import re from logging import getLogger from pylons import config from paste.deploy.converters import asbool import ckan.plugins as p import ckan.model as model from ckan.common import OrderedDict, _, c import ckan.lib.maintain as maintain log = getLogger(__name__) class AuthFunctions:
73
186
621
4
69
opendata-ee/ckan
ckan/new_authz.py
Python
AuthFunctions
AuthFunctions
17
92
17
17
41364f8f552c504a2a338612a3d2d251137e61e8
bigcode/the-stack
train
e81652ac37f39bb20a016558
train
function
def _get_user(username): ''' Try to get the user from c, if possible, and fallback to using the DB ''' if not username: return None # See if we can get the user without touching the DB try: if c.userobj and c.userobj.name == username: return c.userobj except TypeError: ...
def _get_user(username):
''' Try to get the user from c, if possible, and fallback to using the DB ''' if not username: return None # See if we can get the user without touching the DB try: if c.userobj and c.userobj.name == username: return c.userobj except TypeError: # c is not availabl...
) # CS: bad_spelling ignore return re.sub('licence', 'license', new_action_name) def is_sysadmin(username): ''' Returns True is username is a sysadmin ''' user = _get_user(username) return user and user.sysadmin def _get_user(username):
64
64
101
6
57
opendata-ee/ckan
ckan/new_authz.py
Python
_get_user
_get_user
124
136
124
124
9c2512f82deac83fb29a6afd7eb789c4e5ea49fc
bigcode/the-stack
train
fd439b18484645a03478077f
train
function
def has_user_permission_for_some_org(user_name, permission): ''' Check if the user has the given permission for any organization. ''' user_id = get_user_id_for_username(user_name, allow_none=True) if not user_id: return False roles = get_roles_with_permission(permission) if not roles: ...
def has_user_permission_for_some_org(user_name, permission):
''' Check if the user has the given permission for any organization. ''' user_id = get_user_id_for_username(user_name, allow_none=True) if not user_id: return False roles = get_roles_with_permission(permission) if not roles: return False # get any groups the user has with the ne...
\ .filter(model.Member.table_name == 'user') \ .filter(model.Member.state == 'active') \ .filter(model.Member.table_id == user_id) # return the first role we find for row in q.all(): return row.capacity return None def has_user_permission_for_some_org(user_name, permission):...
72
72
242
12
59
opendata-ee/ckan
ckan/new_authz.py
Python
has_user_permission_for_some_org
has_user_permission_for_some_org
333
361
333
333
7bbe05792c34c4be4f660ec559949d000527da67
bigcode/the-stack
train
e9f85db7114ac95bcaf9bb18
train
function
def _has_user_permission_for_groups(user_id, permission, group_ids, capacity=None): ''' Check if the user has the given permissions for the particular group (ignoring permissions cascading in a group hierarchy). Can also be filtered by a particular capacity. ''' i...
def _has_user_permission_for_groups(user_id, permission, group_ids, capacity=None):
''' Check if the user has the given permissions for the particular group (ignoring permissions cascading in a group hierarchy). Can also be filtered by a particular capacity. ''' if not group_ids: return False # get any roles the user has for the group q = model.Session.query(model.M...
) group_ids = [group_.id for group_ in parent_groups] if _has_user_permission_for_groups(user_id, permission, group_ids, capacity=capacity): return True return False def _has_user_permission_for_groups(user_id, permission, group_ids, ...
64
64
210
19
44
opendata-ee/ckan
ckan/new_authz.py
Python
_has_user_permission_for_groups
_has_user_permission_for_groups
284
306
284
285
50c4a6d7acb61b59d882f258c98f0b08c0d05225
bigcode/the-stack
train
06a2beabbb653cff77da2155
train
function
def is_sysadmin(username): ''' Returns True is username is a sysadmin ''' user = _get_user(username) return user and user.sysadmin
def is_sysadmin(username):
''' Returns True is username is a sysadmin ''' user = _get_user(username) return user and user.sysadmin
_name(action_name): ''' Used to convert old style action names into new style ones ''' new_action_name = re.sub('package', 'dataset', action_name) # CS: bad_spelling ignore return re.sub('licence', 'license', new_action_name) def is_sysadmin(username):
64
64
33
6
58
opendata-ee/ckan
ckan/new_authz.py
Python
is_sysadmin
is_sysadmin
118
121
118
118
39ed67f173cb4a85c082a3bbc8dee9efa96a3b69
bigcode/the-stack
train
0451d3cd20ee9c365c5c35e5
train
function
def check_config_permission(permission): ''' Returns the permission configuration, usually True/False ''' # set up perms if not already done if not CONFIG_PERMISSIONS: for perm in CONFIG_PERMISSIONS_DEFAULTS: key = 'ckan.auth.' + perm default = CONFIG_PERMISSIONS_DEFAULTS[per...
def check_config_permission(permission):
''' Returns the permission configuration, usually True/False ''' # set up perms if not already done if not CONFIG_PERMISSIONS: for perm in CONFIG_PERMISSIONS_DEFAULTS: key = 'ckan.auth.' + perm default = CONFIG_PERMISSIONS_DEFAULTS[perm] CONFIG_PERMISSIONS[perm] =...
, 'user_delete_groups': True, 'user_delete_organizations': True, 'create_user_via_api': False, 'create_user_via_web': True, 'roles_that_cascade_to_sub_groups': 'admin', } CONFIG_PERMISSIONS = {} def check_config_permission(permission):
63
64
183
6
57
opendata-ee/ckan
ckan/new_authz.py
Python
check_config_permission
check_config_permission
399
417
399
399
0d7b4baeb2b1f737df7deb7e536d020d1761f8f7
bigcode/the-stack
train
4546eed1d7113a4d8791be42
train
function
def auth_is_loggedin_user(): ''' Do we have a logged in user ''' try: context_user = c.user except TypeError: context_user = None return bool(context_user)
def auth_is_loggedin_user():
''' Do we have a logged in user ''' try: context_user = c.user except TypeError: context_user = None return bool(context_user)
_PERMISSIONS[permission] return False @maintain.deprecated('Use auth_is_loggedin_user instead') def auth_is_registered_user(): ''' This function is deprecated, please use the auth_is_loggedin_user instead ''' return auth_is_loggedin_user() def auth_is_loggedin_user():
64
64
44
7
57
opendata-ee/ckan
ckan/new_authz.py
Python
auth_is_loggedin_user
auth_is_loggedin_user
426
432
426
426
d6d7f37eea27bb0adc6237ae83dbd9d86b9b09ce
bigcode/the-stack
train
8ea54b4668af6f698760627d
train
function
def auth_is_anon_user(context): ''' Is this an anonymous user? eg Not logged in if a web request and not user defined in context if logic functions called directly See ckan/lib/base.py:232 for pylons context object logic ''' try: is_anon_user = (not bool(c.user) and bool(c.a...
def auth_is_anon_user(context):
''' Is this an anonymous user? eg Not logged in if a web request and not user defined in context if logic functions called directly See ckan/lib/base.py:232 for pylons context object logic ''' try: is_anon_user = (not bool(c.user) and bool(c.author)) except TypeError: ...
instead ''' return auth_is_loggedin_user() def auth_is_loggedin_user(): ''' Do we have a logged in user ''' try: context_user = c.user except TypeError: context_user = None return bool(context_user) def auth_is_anon_user(context):
64
64
137
8
56
opendata-ee/ckan
ckan/new_authz.py
Python
auth_is_anon_user
auth_is_anon_user
434
449
434
434
cde32d73ba6ebfba0eb52233ccd1aeaf748aedd4
bigcode/the-stack
train
c825b27becf4af4f73a052cf
train
function
def is_authorized(action, context, data_dict=None): '''Returns whether this user is allowed to do an action. The response is a dict, so not suitable for most purposes. ALL calling methods instead should use the logic/check_access wrapper. check_access raises NotAuthorized, which is more pythonic. ...
def is_authorized(action, context, data_dict=None):
'''Returns whether this user is allowed to do an action. The response is a dict, so not suitable for most purposes. ALL calling methods instead should use the logic/check_access wrapper. check_access raises NotAuthorized, which is more pythonic. ''' if context.get('ignore_auth'): re...
filter(model.Member.state == 'active') \ .filter(model.Member.capacity == 'admin') return [a.table_id for a in q.all()] def is_authorized_boolean(action, context, data_dict=None): ''' runs the auth function but just returns True if allowed else False ''' outcome = is_authorized(action, context...
98
98
328
12
86
opendata-ee/ckan
ckan/new_authz.py
Python
is_authorized
is_authorized
158
198
158
158
cb804f709f7ef35b442bf780151ae10780ad0da2
bigcode/the-stack
train
27b92ad8ee8d06759768ec37
train
class
class CallbackHandler(object): workdone=0 def done(self, number): print("callback: worker %d reports work is done!" % number) CallbackHandler.workdone+=1
class CallbackHandler(object):
workdone=0 def done(self, number): print("callback: worker %d reports work is done!" % number) CallbackHandler.workdone+=1
# We need to set either a socket communication timeout, # or use the select based server. Otherwise the daemon requestLoop # will block indefinitely and is never able to evaluate the loopCondition. Pyro4.config.COMMTIMEOUT=0.5 NUM_WORKERS=5 class CallbackHandler(object):
64
64
42
5
58
nelmiux/CS347-Data_Management
tests/Pyro4-4.17/examples/callback/client.py
Python
CallbackHandler
CallbackHandler
12
16
12
12
11652128ed01cae51261457e12c11247b44ed891
bigcode/the-stack
train
c590f77cc4b15414f7944fab
train
class
@pytest.mark.skipif('sys.version_info[0] == 2', reason='') class LocalTest(ClusterTest, unittest.TestCase): Cluster = partial(LocalCluster, silence_logs=False, diagnostics_port=None)
@pytest.mark.skipif('sys.version_info[0] == 2', reason='') class LocalTest(ClusterTest, unittest.TestCase):
Cluster = partial(LocalCluster, silence_logs=False, diagnostics_port=None)
(v == 3 for v in e.ncores().values()) c.start_worker(nanny=False) assert isinstance(c.workers[-1], Worker) repr(c) @pytest.mark.skipif('sys.version_info[0] == 2', reason='') class LocalTest(ClusterTest, unittest.TestCase):
64
64
43
28
36
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
LocalTest
LocalTest
53
55
53
54
d049df3821c6bea2ecdcf0ed23a495793fa5fd16
bigcode/the-stack
train
b172e70ef582347fdaea9f2f
train
function
def test_worker_params(): with LocalCluster(n_workers=2, scheduler_port=0, silence_logs=False, diagnostics_port=None, memory_limit=500) as c: assert [w.memory_limit for w in c.workers] == [500] * 2
def test_worker_params():
with LocalCluster(n_workers=2, scheduler_port=0, silence_logs=False, diagnostics_port=None, memory_limit=500) as c: assert [w.memory_limit for w in c.workers] == [500] * 2
with LocalCluster(threads_per_worker=2, n_workers=3, scheduler_port=0, silence_logs=False, diagnostics_port=None) as c: assert len(c.workers) == 3 assert all(w.ncores == 2 for w in c.workers) def test_worker_params():
64
64
57
5
59
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_worker_params
test_worker_params
115
118
115
115
a1d7c5dbce9ec02b0d26ca24b48a247863db4aef
bigcode/the-stack
train
2c99be2695c5c019402ec274
train
function
def test_bokeh(loop): from distributed.http import HTTPScheduler import requests with LocalCluster(scheduler_port=0, silence_logs=False, loop=loop, diagnostics_port=4724, services={('http', 0): HTTPScheduler}, ) as c: start = time() while True: with ignori...
def test_bokeh(loop):
from distributed.http import HTTPScheduler import requests with LocalCluster(scheduler_port=0, silence_logs=False, loop=loop, diagnostics_port=4724, services={('http', 0): HTTPScheduler}, ) as c: start = time() while True: with ignoring(Exception): ...
=0, silence_logs=False, services={('http', 3485): HTTPScheduler}, diagnostics_port=None, loop=loop) as c: response = requests.get('http://127.0.0.1:3485/info.json') assert response.ok def test_bokeh(loop):
64
64
173
6
57
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_bokeh
test_bokeh
150
169
150
150
f75698686706c61d2d7d3e6706546f74d574a490
bigcode/the-stack
train
c3898495abfe127586193fd3
train
function
def test_repeated(): with LocalCluster(scheduler_port=8448, silence_logs=False, diagnostics_port=None) as c: pass with LocalCluster(scheduler_port=8448, silence_logs=False, diagnostics_port=None) as c: pass
def test_repeated():
with LocalCluster(scheduler_port=8448, silence_logs=False, diagnostics_port=None) as c: pass with LocalCluster(scheduler_port=8448, silence_logs=False, diagnostics_port=None) as c: pass
c = LocalCluster(2, scheduler_port=0, silence_logs=False, diagnostics_port=None) port = c.scheduler.port c.close() c2 = LocalCluster(2, scheduler_port=port, silence_logs=False, diagnostics_port=None) c.close() def test_repeated():
64
64
57
5
59
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_repeated
test_repeated
131
137
131
131
ce16b3f4f397b3068789ae423d97b155301e096a
bigcode/the-stack
train
5ada8003da15d46d3c3db479
train
function
def test_cleanup(): c = LocalCluster(2, scheduler_port=0, silence_logs=False, diagnostics_port=None) port = c.scheduler.port c.close() c2 = LocalCluster(2, scheduler_port=port, silence_logs=False, diagnostics_port=None) c.close()
def test_cleanup():
c = LocalCluster(2, scheduler_port=0, silence_logs=False, diagnostics_port=None) port = c.scheduler.port c.close() c2 = LocalCluster(2, scheduler_port=port, silence_logs=False, diagnostics_port=None) c.close()
.workers) def test_worker_params(): with LocalCluster(n_workers=2, scheduler_port=0, silence_logs=False, diagnostics_port=None, memory_limit=500) as c: assert [w.memory_limit for w in c.workers] == [500] * 2 def test_cleanup():
64
64
64
4
59
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_cleanup
test_cleanup
121
128
121
121
1c383fcddad825b8d2d545419efc0d79fa45b270
bigcode/the-stack
train
19bc850c70e8cbef3e4f63dc
train
function
def test_http(loop): from distributed.http import HTTPScheduler import requests with LocalCluster(scheduler_port=0, silence_logs=False, services={('http', 3485): HTTPScheduler}, diagnostics_port=None, loop=loop) as c: response = requests.get('http://127.0.0.1:3485/info.json')...
def test_http(loop):
from distributed.http import HTTPScheduler import requests with LocalCluster(scheduler_port=0, silence_logs=False, services={('http', 3485): HTTPScheduler}, diagnostics_port=None, loop=loop) as c: response = requests.get('http://127.0.0.1:3485/info.json') assert respo...
.close() def test_repeated(): with LocalCluster(scheduler_port=8448, silence_logs=False, diagnostics_port=None) as c: pass with LocalCluster(scheduler_port=8448, silence_logs=False, diagnostics_port=None) as c: pass def test_http(loop):
64
64
82
5
58
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_http
test_http
140
147
140
140
f6c0b7305dfa5ef93015e3be73cf9c27b58167a4
bigcode/the-stack
train
34b6344be838a8246f9b5341
train
function
def test_Client_with_local(loop): with LocalCluster(1, scheduler_port=0, silence_logs=False, diagnostics_port=None, loop=loop) as c: with Client(c, loop=loop) as e: assert len(e.ncores()) == len(c.workers) assert c.scheduler_address in repr(c)
def test_Client_with_local(loop):
with LocalCluster(1, scheduler_port=0, silence_logs=False, diagnostics_port=None, loop=loop) as c: with Client(c, loop=loop) as e: assert len(e.ncores()) == len(c.workers) assert c.scheduler_address in repr(c)
assert isinstance(c.workers[-1], Worker) repr(c) @pytest.mark.skipif('sys.version_info[0] == 2', reason='') class LocalTest(ClusterTest, unittest.TestCase): Cluster = partial(LocalCluster, silence_logs=False, diagnostics_port=None) def test_Client_with_local(loop):
64
64
69
7
57
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_Client_with_local
test_Client_with_local
58
63
58
58
e4706e6d43e56dd902226d414da1774c871a33bc
bigcode/the-stack
train
639c43fa83ca40cb946b14e6
train
function
def test_only_local_access(loop): with LocalCluster(scheduler_port=0, silence_logs=False, diagnostics_port=None, loop=loop) as c: sync(loop, assert_can_connect_locally_4, c.scheduler.port)
def test_only_local_access(loop):
with LocalCluster(scheduler_port=0, silence_logs=False, diagnostics_port=None, loop=loop) as c: sync(loop, assert_can_connect_locally_4, c.scheduler.port)
LocalCluster(diagnostics_port=None, loop=loop, scheduler_port=0): sleep(0.5) out, err = capsys.readouterr() assert not out for line in err.split('\n'): assert 'worker' not in line def test_only_local_access(loop):
64
64
49
7
56
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_only_local_access
test_only_local_access
229
232
229
229
b35c48cd06760bb0a6926a8707684bc24dd3a3ea
bigcode/the-stack
train
1eac8034a458939421744b27
train
function
def test_defaults(): from distributed.worker import _ncores with LocalCluster(scheduler_port=0, silence_logs=False, diagnostics_port=None) as c: assert sum(w.ncores for w in c.workers) == _ncores assert all(isinstance(w, Nanny) for w in c.workers) assert all(w.ncores == 1 fo...
def test_defaults():
from distributed.worker import _ncores with LocalCluster(scheduler_port=0, silence_logs=False, diagnostics_port=None) as c: assert sum(w.ncores for w in c.workers) == _ncores assert all(isinstance(w, Nanny) for w in c.workers) assert all(w.ncores == 1 for w in c.workers) ...
, silence_logs=False, diagnostics_port=None, loop=loop) as c: with Client(c, loop=loop) as e: assert len(e.ncores()) == len(c.workers) assert c.scheduler_address in repr(c) def test_Client_solo(loop): with Client(loop=loop) as c: pass assert c.cluster.status...
123
123
411
4
118
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_defaults
test_defaults
78
112
78
78
c283efecf442ab337c52468659a558cb224b570f
bigcode/the-stack
train
523aedb05552d80a0b9cf2d3
train
function
@gen_test() def test_scale_up_and_down(): loop = IOLoop.current() cluster = LocalCluster(0, scheduler_port=0, nanny=False, silence_logs=False, diagnostics_port=None, loop=loop, start=False) c = Client(cluster, start=False, loop=loop) yield c._start() assert not cluster.wo...
@gen_test() def test_scale_up_and_down():
loop = IOLoop.current() cluster = LocalCluster(0, scheduler_port=0, nanny=False, silence_logs=False, diagnostics_port=None, loop=loop, start=False) c = Client(cluster, start=False, loop=loop) yield c._start() assert not cluster.workers yield cluster.scale_up(2) a...
if response.ok: break assert time() < start + 20 sleep(0.01) def test_blocks_until_full(loop): with Client(loop=loop) as c: assert len(c.ncores()) > 0 @gen_test() def test_scale_up_and_down():
64
64
160
11
52
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_scale_up_and_down
test_scale_up_and_down
195
216
195
196
8d31f2d184532e1eeab4febc79990f1cc4bd21af
bigcode/the-stack
train
13b0c1bad5633cd24994725e
train
function
def test_silent_startup(capsys, loop): with LocalCluster(diagnostics_port=None, loop=loop, scheduler_port=0): sleep(0.5) out, err = capsys.readouterr() assert not out for line in err.split('\n'): assert 'worker' not in line
def test_silent_startup(capsys, loop):
with LocalCluster(diagnostics_port=None, loop=loop, scheduler_port=0): sleep(0.5) out, err = capsys.readouterr() assert not out for line in err.split('\n'): assert 'worker' not in line
addr = cluster.workers[0].address yield cluster.scale_down([addr]) assert len(cluster.workers) == 1 assert addr not in cluster.scheduler.ncores yield c._shutdown() yield cluster._close() def test_silent_startup(capsys, loop):
64
64
71
12
52
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_silent_startup
test_silent_startup
219
226
219
219
3b6b78e115a086e6420969d28a8154b9e6f1081b
bigcode/the-stack
train
4183ae452e430e9313abf134
train
function
def test_Client_solo(loop): with Client(loop=loop) as c: pass assert c.cluster.status == 'closed'
def test_Client_solo(loop):
with Client(loop=loop) as c: pass assert c.cluster.status == 'closed'
1, scheduler_port=0, silence_logs=False, diagnostics_port=None, loop=loop) as c: with Client(c, loop=loop) as e: assert len(e.ncores()) == len(c.workers) assert c.scheduler_address in repr(c) def test_Client_solo(loop):
64
64
29
7
57
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_Client_solo
test_Client_solo
66
69
66
66
5a9926ca8fdab2e1e76b61e427ed8ceef67a7da4
bigcode/the-stack
train
678e0ef558037fba5c2e4fc8
train
function
def test_remote_access(loop): with LocalCluster(scheduler_port=0, silence_logs=False, diagnostics_port=None, ip='', loop=loop) as c: sync(loop, assert_can_connect_from_everywhere_4_6, c.scheduler.port)
def test_remote_access(loop):
with LocalCluster(scheduler_port=0, silence_logs=False, diagnostics_port=None, ip='', loop=loop) as c: sync(loop, assert_can_connect_from_everywhere_4_6, c.scheduler.port)
assert 'worker' not in line def test_only_local_access(loop): with LocalCluster(scheduler_port=0, silence_logs=False, diagnostics_port=None, loop=loop) as c: sync(loop, assert_can_connect_locally_4, c.scheduler.port) def test_remote_access(loop):
64
64
53
6
58
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_remote_access
test_remote_access
235
238
235
235
f20d7bd5ff532689fd2a3e0abe73fee6b5e2ef1a
bigcode/the-stack
train
31b4c0a72902d7e9b451e138
train
function
def test_start_diagnostics(loop): from distributed.http import HTTPScheduler import requests with LocalCluster(scheduler_port=0, silence_logs=False, loop=loop, diagnostics_port=None) as c: c.start_diagnostics_server(show=False, port=3748) start = time() while True: ...
def test_start_diagnostics(loop):
from distributed.http import HTTPScheduler import requests with LocalCluster(scheduler_port=0, silence_logs=False, loop=loop, diagnostics_port=None) as c: c.start_diagnostics_server(show=False, port=3748) start = time() while True: with ignoring(Exception): ...
sleep(0.01) start = time() while not raises(lambda: requests.get('http://127.0.0.1:%d/status/' % 4724)): assert time() < start + 10 sleep(0.01) def test_start_diagnostics(loop):
64
64
124
7
57
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_start_diagnostics
test_start_diagnostics
172
187
172
172
b77a55ca7bb84d6d1e140b0acf34b95dbcebf569
bigcode/the-stack
train
835e43473a242d51ebf0aa60
train
function
def test_Client_twice(loop): with Client(loop=loop) as c: with Client(loop=loop) as f: assert c.cluster.scheduler.port != f.cluster.scheduler.port
def test_Client_twice(loop):
with Client(loop=loop) as c: with Client(loop=loop) as f: assert c.cluster.scheduler.port != f.cluster.scheduler.port
=loop) as e: assert len(e.ncores()) == len(c.workers) assert c.scheduler_address in repr(c) def test_Client_solo(loop): with Client(loop=loop) as c: pass assert c.cluster.status == 'closed' def test_Client_twice(loop):
64
64
39
7
57
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_Client_twice
test_Client_twice
72
75
72
72
89f235a4544fdb8cf9bad5c968a4914ba48355df
bigcode/the-stack
train
fcf1fc9c6be81f2670bf710a
train
function
def test_simple(loop): with LocalCluster(4, scheduler_port=0, nanny=False, silence_logs=False, diagnostics_port=None, loop=loop) as c: with Client(c.scheduler_address, loop=loop) as e: x = e.submit(inc, 1) x.result() assert x.key in c.scheduler.tasks...
def test_simple(loop):
with LocalCluster(4, scheduler_port=0, nanny=False, silence_logs=False, diagnostics_port=None, loop=loop) as c: with Client(c.scheduler_address, loop=loop) as e: x = e.submit(inc, 1) x.result() assert x.key in c.scheduler.tasks assert any...
from distributed.metrics import time from distributed.utils_test import (inc, loop, raises, gen_test, assert_can_connect_locally_4, assert_can_connect_from_everywhere_4_6) from distributed.utils import ignoring, sync from distributed.deploy.utils_test import ClusterTest def test_simple(loop):
64
64
94
5
58
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_simple
test_simple
21
28
21
21
f11ebad5dbb2ba70671e188a540d6d3e7dc56660
bigcode/the-stack
train
74d3d881464adc039f2060a2
train
function
@pytest.mark.skipif('sys.version_info[0] == 2', reason='multi-loop') def test_procs(loop): with LocalCluster(2, scheduler_port=0, nanny=False, threads_per_worker=3, diagnostics_port=None, silence_logs=False) as c: assert len(c.workers) == 2 assert all(isinstance(w, Worker) for w in c.wor...
@pytest.mark.skipif('sys.version_info[0] == 2', reason='multi-loop') def test_procs(loop):
with LocalCluster(2, scheduler_port=0, nanny=False, threads_per_worker=3, diagnostics_port=None, silence_logs=False) as c: assert len(c.workers) == 2 assert all(isinstance(w, Worker) for w in c.workers) with Client(c.scheduler.address, loop=loop) as e: assert all(w.nc...
x = e.submit(inc, 1) x.result() assert x.key in c.scheduler.tasks assert any(w.data == {x.key: 2} for w in c.workers) @pytest.mark.skipif('sys.version_info[0] == 2', reason='multi-loop') def test_procs(loop):
70
70
234
26
44
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_procs
test_procs
31
50
31
32
54a7f451b26d617e7f14521fc69cadfc06bdc350
bigcode/the-stack
train
f55070ef046eae0d754b2c30
train
function
def test_blocks_until_full(loop): with Client(loop=loop) as c: assert len(c.ncores()) > 0
def test_blocks_until_full(loop):
with Client(loop=loop) as c: assert len(c.ncores()) > 0
: with ignoring(Exception): response = requests.get('http://127.0.0.1:%d/status/' % c.diagnostics.port) if response.ok: break assert time() < start + 20 sleep(0.01) def test_blocks_until_full(...
64
64
28
7
57
brinkar/distributed
distributed/deploy/tests/test_local.py
Python
test_blocks_until_full
test_blocks_until_full
190
192
190
190
61de8e934536c175d85b09bcf9c9066236c55add
bigcode/the-stack
train
fa05c768a430d5ff87445e8f
train
function
@pytest.mark.slow def test_iss_pipeline_in_docs(): # Just importing the file and verifying it runs for now __import__('iss_pipeline')
@pytest.mark.slow def test_iss_pipeline_in_docs(): # Just importing the file and verifying it runs for now
__import__('iss_pipeline')
.dirname(os.path.abspath(starfish.__file__))) os.environ["TESTING"] = "1" sys.path.append(os.path.join(ROOT_DIR, "examples", "pipelines")) @pytest.mark.slow def test_iss_pipeline_in_docs(): # Just importing the file and verifying it runs for now
63
64
33
26
37
haoxusci/starfish
starfish/test/full_pipelines/api/test_iss_doc_pipeline.py
Python
test_iss_pipeline_in_docs
test_iss_pipeline_in_docs
14
17
14
16
b4c79b6b2d5c7ca7614a2cb54d035e9bea9c08fa
bigcode/the-stack
train
3d49cf7807d866f78b817f56
train
function
def evaluate(config, task, learning_network, extra): test_rewards = [] test_points = [] test_wall_times = [] initial_time = time.time() worker = config.worker(config, learning_network, extra) # config.logger = Logger('./evaluation_log', gym.logger) while True: steps = config.total_st...
def evaluate(config, task, learning_network, extra):
test_rewards = [] test_points = [] test_wall_times = [] initial_time = time.time() worker = config.worker(config, learning_network, extra) # config.logger = Logger('./evaluation_log', gym.logger) while True: steps = config.total_steps.value if config.test_interval and steps %...
reward = worker.episode() rewards.append(reward) if len(rewards) > 100: rewards.pop(0) config.logger.debug('worker %d, episode %d, return %f, avg return %f, episode steps %d, total steps %d' % ( id, episode, rewards[-1], np.mean(rewards[-100:]), steps, config.total_steps.value)) ...
102
102
340
11
90
bibofeng/DeepRL-1
agent/async_agent.py
Python
evaluate
evaluate
29
56
29
29
ed4c231f8ac35a3c065a1cde4d757fb75d4cfe83
bigcode/the-stack
train
ea444db61a16508886c82373
train
class
class AsyncAgent: def __init__(self, config): self.config = config self.config.steps_lock = mp.Lock() self.config.network_lock = mp.Lock() self.config.total_steps = mp.Value('i', 0) self.config.stop_signal = mp.Value('i', False) def run(self): config = self.confi...
class AsyncAgent:
def __init__(self, config): self.config = config self.config.steps_lock = mp.Lock() self.config.network_lock = mp.Lock() self.config.total_steps = mp.Value('i', 0) self.config.stop_signal = mp.Value('i', False) def run(self): config = self.config task = c...
wards), np.std(rewards) / np.sqrt(config.test_repetitions))) test_rewards.append(np.mean(rewards)) test_points.append(steps) test_wall_times.append(time.time() - initial_time) with open('data/%s-%s-statistics-%s.bin' % ( config.tag, config.worker.__nam...
133
133
444
4
128
bibofeng/DeepRL-1
agent/async_agent.py
Python
AsyncAgent
AsyncAgent
58
105
58
58
a28e0a4d8cd8d3e0cf6571a8ca33b68c65ecd3c5
bigcode/the-stack
train
785e232bdd37cf563b89197a
train
function
def train(id, config, learning_network, extra): worker = config.worker(config, learning_network, extra) episode = 0 rewards = [] while not config.stop_signal.value: steps, reward = worker.episode() rewards.append(reward) if len(rewards) > 100: rewards.pop(0) config.logger...
def train(id, config, learning_network, extra):
worker = config.worker(config, learning_network, extra) episode = 0 rewards = [] while not config.stop_signal.value: steps, reward = worker.episode() rewards.append(reward) if len(rewards) > 100: rewards.pop(0) config.logger.debug('worker %d, episode %d, return %f, avg re...
keep this # # declaration at the top # ####################################################################### import numpy as np import torch.multiprocessing as mp from network import * from utils import * from component import * from async_worker import * import p...
64
64
135
11
52
bibofeng/DeepRL-1
agent/async_agent.py
Python
train
train
17
27
17
17
3152a94e6e8598a4faa3d48e637ab2f98fe2d6a8
bigcode/the-stack
train
023b37b13d666bd3b683937f
train
function
def is_verb(label): if re.match(r'^VB.?$', label): return True return False
def is_verb(label):
if re.match(r'^VB.?$', label): return True return False
claimed # VBZ 3rd person singular present tense verb is # VBP non-3rd person singular present tense verb have # VBN past participle found # VB Verb, base form # VBG Verb, gerund or present participle def is_verb(label):
64
64
25
6
57
xinru1414/sheenroo_algs
sheenroo_algs/allennlp/verbs.py
Python
is_verb
is_verb
10
13
10
10
829f012a0b69c505e08ef2d114470f7815e3fa7d
bigcode/the-stack
train
a64a494b1b1cf326401796bd
train
class
class ElementContainer: """ The base class for HTML elements that can contain other elements """ # meta-methods def __init__(self, **kwds): # chain up super().__init__(**kwds) # make storage for the contents self.contents = [] # all done return
class ElementContainer:
""" The base class for HTML elements that can contain other elements """ # meta-methods def __init__(self, **kwds): # chain up super().__init__(**kwds) # make storage for the contents self.contents = [] # all done return
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2018 all rights reserved # # superclass from .Element import Element # class declaration class ElementContainer:
57
64
74
4
52
BryanRiel/pyre
packages/opal/html/ElementContainer.py
Python
ElementContainer
ElementContainer
14
27
14
14
fae637923affe96fd9a2bb4a8a540fea41f1528d
bigcode/the-stack
train
08acc36a879586f8dfe7e2ae
train
class
class Phone_Number_Valid_To_Phone_Number(unittest.TestCase): def setUp(self): self.BadPhoneNumber = '+1999a123a23abc32' self.Account = models.accounts.Account.new(key_name='email@email.com',email='email@email.com',password='password') self.Account.put() self.PhoneNumber,Valid,TwilioCode, TwilioMsg = models.in...
class Phone_Number_Valid_To_Phone_Number(unittest.TestCase):
def setUp(self): self.BadPhoneNumber = '+1999a123a23abc32' self.Account = models.accounts.Account.new(key_name='email@email.com',email='email@email.com',password='password') self.Account.put() self.PhoneNumber,Valid,TwilioCode, TwilioMsg = models.incoming_phone_numbers.Incoming_Phone_Number.new(PhoneNumber = ...
_number(self.ValidPhoneNumber) self.assertTrue(Valid) self.assertEqual(phone_number, self.ValidPhoneNumber) def test_Parse_Phone_Number_Failure_TooShort(self): phone_number, Valid, phoneGroups = pn_helper.parse_phone_number(self.TooShortPhoneNumber) self.assertFalse(Valid) def test_Parse_Phone_Number_Fail...
121
121
405
13
108
arfrank/Fake-Twilio-Api
unit_tests/phone_number_helper_test.py
Python
Phone_Number_Valid_To_Phone_Number
Phone_Number_Valid_To_Phone_Number
29
55
29
29
73f5e661909f909a9d32f49ee5974d00ede9046c
bigcode/the-stack
train
34b43419347f41e5af9ead4d
train
class
class Phone_Number_Parse_Phone_Numbers(unittest.TestCase): def setUp(self): self.ValidPhoneNumber = '+12405559999' self.TooShortPhoneNumber = '+1 222 222 222' self.BadPhoneNumber = '+1999a123a23abc32' def test_Parse_Phone_Number_Valid(self): phone_number, Valid, phoneGroups = pn_helper.parse_phone_number(s...
class Phone_Number_Parse_Phone_Numbers(unittest.TestCase):
def setUp(self): self.ValidPhoneNumber = '+12405559999' self.TooShortPhoneNumber = '+1 222 222 222' self.BadPhoneNumber = '+1999a123a23abc32' def test_Parse_Phone_Number_Valid(self): phone_number, Valid, phoneGroups = pn_helper.parse_phone_number(self.ValidPhoneNumber) self.assertTrue(Valid) self.asser...
import unittest import logging from google.appengine.ext import db import models from helpers import phone_number_helper as pn_helper, parameters class Phone_Number_Parse_Phone_Numbers(unittest.TestCase):
41
64
195
12
28
arfrank/Fake-Twilio-Api
unit_tests/phone_number_helper_test.py
Python
Phone_Number_Parse_Phone_Numbers
Phone_Number_Parse_Phone_Numbers
10
27
10
10
470b75dff92bc3e186d98bb0555c1352fc10ffbb
bigcode/the-stack
train
bd00b3f86f74a130315c3bab
train
class
class Phone_Number_Valid_From_Phone_Number(unittest.TestCase): def setUp(self): self.BadPhoneNumber = '+1999a123a23abc32' self.Account = models.accounts.Account.new(key_name='email@email.com',email='email@email.com',password='password') self.Account.put() self.PhoneNumber,Valid,TwilioCode, TwilioMsg = models....
class Phone_Number_Valid_From_Phone_Number(unittest.TestCase):
def setUp(self): self.BadPhoneNumber = '+1999a123a23abc32' self.Account = models.accounts.Account.new(key_name='email@email.com',email='email@email.com',password='password') self.Account.put() self.PhoneNumber,Valid,TwilioCode, TwilioMsg = models.incoming_phone_numbers.Incoming_Phone_Number.new(PhoneNumber = ...
.valid_to_phone_number(self.BadPhoneNumber,True) self.assertFalse(Valid) def test_To_Phone_Number_Failure_SMS_InvalidNumbers(self): for number in self.InvalidNumbers: Valid, TwilioCode, TwilioMsg = pn_helper.valid_to_phone_number(number,True, SMS = True) self.assertFalse(Valid) self.assertEqual(14101, T...
98
99
333
13
85
arfrank/Fake-Twilio-Api
unit_tests/phone_number_helper_test.py
Python
Phone_Number_Valid_From_Phone_Number
Phone_Number_Valid_From_Phone_Number
58
80
58
58
46119b0a3271c86d3136493fca83e739d2a62ef8
bigcode/the-stack
train
8cddeebeb30801d564c625b6
train
class
class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list')
class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin):
model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list')
, self).get_queryset() return qs.filter(owner=self.request.user) class OwnerEditMixin(object): def form_valid(self, form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin):
64
64
43
12
52
kableson/panda
Chapter12/educa/courses/views.py
Python
OwnerCourseMixin
OwnerCourseMixin
32
35
32
32
71be1a3295d0955b2ef969c597fbf6a75d743ec8
bigcode/the-stack
train
1bc478ce7adcb7191adab7a9
train
class
class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'courses/manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course,...
class CourseModuleUpdateView(TemplateResponseMixin, View):
template_name = 'courses/manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course, id=pk, ...
.change_course' class CourseDeleteView(PermissionRequiredMixin, OwnerCourseMixin, DeleteView): template_name = 'courses/manage/course/delete.html' success_url = reverse_lazy('manage_course_list') permission_required = 'courses.delete_course' class CourseModule...
64
64
205
12
52
kableson/panda
Chapter12/educa/courses/views.py
Python
CourseModuleUpdateView
CourseModuleUpdateView
68
92
68
68
b08362b81c016514447c008dd99d2db92818be65
bigcode/the-stack
train
ea91da74c02db9602488c8b9
train
class
class ModuleContentListView(TemplateResponseMixin, View): template_name = 'courses/manage/module/content_list.html' def get(self, request, module_id): module = get_object_or_404(Module, id=module_id, course__owner=request.user) ...
class ModuleContentListView(TemplateResponseMixin, View):
template_name = 'courses/manage/module/content_list.html' def get(self, request, module_id): module = get_object_or_404(Module, id=module_id, course__owner=request.user) return self.render_to_response({'module': module})
, id): content = get_object_or_404(Content, id=id, module__course__owner=request.user) module = content.module content.item.delete() content.delete() return redirect('module_content_list', module.id) class Mo...
64
64
68
12
52
kableson/panda
Chapter12/educa/courses/views.py
Python
ModuleContentListView
ModuleContentListView
162
170
162
162
faa64d3c1ab2a9d9d417fe6d53a4bf61a743438d
bigcode/the-stack
train
cf54e45d8e627e8a1be71459
train
class
class OwnerMixin(object): def get_queryset(self): qs = super(OwnerMixin, self).get_queryset() return qs.filter(owner=self.request.user)
class OwnerMixin(object):
def get_queryset(self): qs = super(OwnerMixin, self).get_queryset() return qs.filter(owner=self.request.user)
apps from braces.views import CsrfExemptMixin, JsonRequestResponseMixin from django.db.models import Count from .models import Subject, Course, Module, Content from .forms import ModuleFormSet from students.forms import CourseEnrollForm from django.core.cache import cache class OwnerMixin(object):
64
64
33
5
58
kableson/panda
Chapter12/educa/courses/views.py
Python
OwnerMixin
OwnerMixin
20
23
20
20
cd78522e55dac19643a3b79bd536ea634eba26a3
bigcode/the-stack
train
f1f77c7e137eeac28d738b8b
train
class
class ManageCourseListView(OwnerCourseMixin, ListView): template_name = 'courses/manage/course/list.html'
class ManageCourseListView(OwnerCourseMixin, ListView):
template_name = 'courses/manage/course/list.html'
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin): fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') template_name = 'courses/manage/course/form.html' class ManageCourseListView(OwnerCourseMixin, ListView):
64
64
24
13
51
kableson/panda
Chapter12/educa/courses/views.py
Python
ManageCourseListView
ManageCourseListView
44
45
44
44
c663b203a4492413a5008cccd42f506a3878e93f
bigcode/the-stack
train
1ef23e70d9fcad0bd5cf5039
train
class
class CourseCreateView(PermissionRequiredMixin, OwnerCourseEditMixin, CreateView): permission_required = 'courses.add_course'
class CourseCreateView(PermissionRequiredMixin, OwnerCourseEditMixin, CreateView):
permission_required = 'courses.add_course'
success_url = reverse_lazy('manage_course_list') template_name = 'courses/manage/course/form.html' class ManageCourseListView(OwnerCourseMixin, ListView): template_name = 'courses/manage/course/list.html' class CourseCreateView(PermissionRequiredMixin, OwnerCourseEditMixin, ...
64
64
28
19
45
kableson/panda
Chapter12/educa/courses/views.py
Python
CourseCreateView
CourseCreateView
48
51
48
50
bbf97468e8c26eebd0bd92cf3ebaec9196db05a2
bigcode/the-stack
train
6ae8217bf7eb9bdfdf9cf7a6
train
class
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin): fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') template_name = 'courses/manage/course/form.html'
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin):
fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') template_name = 'courses/manage/course/form.html'
, self).form_valid(form) class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin):
64
64
51
14
50
kableson/panda
Chapter12/educa/courses/views.py
Python
OwnerCourseEditMixin
OwnerCourseEditMixin
38
41
38
38
3cd7aec28bbd95928d203727d40579ca6e7e350f
bigcode/the-stack
train
7601b687958c376ef328aab4
train
class
class CourseUpdateView(PermissionRequiredMixin, OwnerCourseEditMixin, UpdateView): permission_required = 'courses.change_course'
class CourseUpdateView(PermissionRequiredMixin, OwnerCourseEditMixin, UpdateView):
permission_required = 'courses.change_course'
CourseMixin, ListView): template_name = 'courses/manage/course/list.html' class CourseCreateView(PermissionRequiredMixin, OwnerCourseEditMixin, CreateView): permission_required = 'courses.add_course' class CourseUpdateView(PermissionRequiredMixin, ...
64
64
28
19
45
kableson/panda
Chapter12/educa/courses/views.py
Python
CourseUpdateView
CourseUpdateView
54
57
54
56
6483efb1727d6d513e5196546f92bcf2840b5a8b
bigcode/the-stack
train
5e3d67420c800e40b0da66ce
train
class
class CourseListView(TemplateResponseMixin, View): model = Course template_name = 'courses/course/list.html' def get(self, request, subject=None): subjects = cache.get('all_subjects') if not subjects: subjects = Subject.objects.annotate( total_courses=Count('cour...
class CourseListView(TemplateResponseMixin, View):
model = Course template_name = 'courses/course/list.html' def get(self, request, subject=None): subjects = cache.get('all_subjects') if not subjects: subjects = Subject.objects.annotate( total_courses=Count('courses')) cache.set('all_subjects', subjec...
post(self, request): for id, order in self.request_json.items(): Content.objects.filter(id=id, module__course__owner=request.user) \ .update(order=order) return self.render_json_response({'saved': 'OK'}) class CourseListView(TemplateRespons...
63
64
210
11
52
kableson/panda
Chapter12/educa/courses/views.py
Python
CourseListView
CourseListView
195
221
195
195
22cd07d23cf92b3cd73ba97dac3452fe7cc06cf9
bigcode/the-stack
train
bf0185ec5f8534febd05c570
train
class
class CourseDetailView(DetailView): model = Course template_name = 'courses/course/detail.html' def get_context_data(self, **kwargs): context = super(CourseDetailView, self).get_context_data(**kwargs) context['enroll_form'] = CourseEnrollForm( initial={'c...
class CourseDetailView(DetailView):
model = Course template_name = 'courses/course/detail.html' def get_context_data(self, **kwargs): context = super(CourseDetailView, self).get_context_data(**kwargs) context['enroll_form'] = CourseEnrollForm( initial={'course': self.object}) return...
) else: courses = cache.get('all_courses') if not courses: courses = all_courses cache.set('all_courses', courses) return self.render_to_response({'subjects': subjects, 'subject': subject, ...
64
64
75
8
56
kableson/panda
Chapter12/educa/courses/views.py
Python
CourseDetailView
CourseDetailView
224
233
224
224
e6843d47a38ad385d177dbb58d5788736c62c29f
bigcode/the-stack
train
cf3d28aa7168e83ca55a76fe
train
class
class ContentDeleteView(View): def post(self, request, id): content = get_object_or_404(Content, id=id, module__course__owner=request.user) module = content.module content.item.delete() content.delete() ...
class ContentDeleteView(View):
def post(self, request, id): content = get_object_or_404(Content, id=id, module__course__owner=request.user) module = content.module content.item.delete() content.delete() return redirect('module_content_...
.user obj.save() if not id: # new content Content.objects.create(module=self.module, item=obj) return redirect('module_content_list', self.module.id) return self.render_to_response({'form': form, ...
64
64
64
6
58
kableson/panda
Chapter12/educa/courses/views.py
Python
ContentDeleteView
ContentDeleteView
150
159
150
151
cd823bed746c418af95851e7cd1b1d685c28ac86
bigcode/the-stack
train
6fa93e8ed3253a78721507c6
train
class
class ModuleOrderView(CsrfExemptMixin, JsonRequestResponseMixin, View): def post(self, request): for id, order in self.request_json.items(): Module.objects.filter( id=id, course__owner=request.user).update( order=order) ...
class ModuleOrderView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def post(self, request): for id, order in self.request_json.items(): Module.objects.filter( id=id, course__owner=request.user).update( order=order) return self.render_json_response({'saved': 'OK'})
' def get(self, request, module_id): module = get_object_or_404(Module, id=module_id, course__owner=request.user) return self.render_to_response({'module': module}) class ModuleOrderView(CsrfExemptMixin, Js...
64
64
71
19
45
kableson/panda
Chapter12/educa/courses/views.py
Python
ModuleOrderView
ModuleOrderView
173
181
173
175
67e44309a75f26fa735a887f7aae99a28b1fab8c
bigcode/the-stack
train
a30e6cb51cee491e174b2b58
train
class
class ContentOrderView(CsrfExemptMixin, JsonRequestResponseMixin, View): def post(self, request): for id, order in self.request_json.items(): Content.objects.filter(id=id, module__course__owner=request.user) \ ...
class ContentOrderView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def post(self, request): for id, order in self.request_json.items(): Content.objects.filter(id=id, module__course__owner=request.user) \ .update(order=order) return self.render_json_response({'saved': 'OK'})
for id, order in self.request_json.items(): Module.objects.filter( id=id, course__owner=request.user).update( order=order) return self.render_json_response({'saved': 'OK'}) class ContentOrderView(CsrfExemptMixin, JsonRequestResponseMixin, ...
63
64
73
19
44
kableson/panda
Chapter12/educa/courses/views.py
Python
ContentOrderView
ContentOrderView
184
192
184
186
a2996d07f99f6000a319d04c3ca22a0def0c0af5
bigcode/the-stack
train
7634f23109e17a8c54996009
train
class
class CourseDeleteView(PermissionRequiredMixin, OwnerCourseMixin, DeleteView): template_name = 'courses/manage/course/delete.html' success_url = reverse_lazy('manage_course_list') permission_required = 'courses.delete_course'
class CourseDeleteView(PermissionRequiredMixin, OwnerCourseMixin, DeleteView):
template_name = 'courses/manage/course/delete.html' success_url = reverse_lazy('manage_course_list') permission_required = 'courses.delete_course'
OwnerCourseEditMixin, CreateView): permission_required = 'courses.add_course' class CourseUpdateView(PermissionRequiredMixin, OwnerCourseEditMixin, UpdateView): permission_required = 'courses.change_course' class CourseDeleteView(Permission...
64
64
49
18
46
kableson/panda
Chapter12/educa/courses/views.py
Python
CourseDeleteView
CourseDeleteView
60
65
60
62
1d614ef64020694a2462bae53a4368f295199ace
bigcode/the-stack
train
c471de15f43196de14f59979
train
class
class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', ...
class ContentCreateUpdateView(TemplateResponseMixin, View):
module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) ...
def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course': self.course, 'formset': formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if forms...
118
118
394
12
106
kableson/panda
Chapter12/educa/courses/views.py
Python
ContentCreateUpdateView
ContentCreateUpdateView
95
147
95
95
ab6f10bf9b80799782c7bac0aeda8c559015c0bf
bigcode/the-stack
train
713d2d3f6ad9feab5bcd6e4f
train
class
class OwnerEditMixin(object): def form_valid(self, form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form)
class OwnerEditMixin(object):
def form_valid(self, form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form)
Content from .forms import ModuleFormSet from students.forms import CourseEnrollForm from django.core.cache import cache class OwnerMixin(object): def get_queryset(self): qs = super(OwnerMixin, self).get_queryset() return qs.filter(owner=self.request.user) class OwnerEditMixin(object):
64
64
37
6
58
kableson/panda
Chapter12/educa/courses/views.py
Python
OwnerEditMixin
OwnerEditMixin
26
29
26
26
d34eeb98e0c5a16b78d096b8c9aac5ed5eb56896
bigcode/the-stack
train
1614946b2728251ab163a4a2
train
class
class MinStack: def __init__(self): """ initialize the data structure. Using dynamic arrays. Every item in the min_nums array, is the smallest item. Out of itself and all its left neighbors. Adds O(n) space, and alls all methods to run in O(1) time. """ self...
class MinStack:
def __init__(self): """ initialize the data structure. Using dynamic arrays. Every item in the min_nums array, is the smallest item. Out of itself and all its left neighbors. Adds O(n) space, and alls all methods to run in O(1) time. """ self.stack = list() ...
1, MAX) --> next largest hasn't yet come } when min is deleted, how to find the next smallest push 2 push 2 push 5 push 1 pop() push 3 stack: [2, 5, 1, -9 ,5, 6, 4] min: -9 Helpful Hint from LeetCode (credit to @aakarshmadhavan): "Consider each node in the stack having a minimum value." """ class MinStack:
107
107
359
4
103
UPstartDeveloper/Problem_Solving_Practice
array_str_problems/stack_min.py
Python
MinStack
MinStack
95
142
95
95
ad0f0a4b116fd579bd201e94eb7b588f95d9ee1e
bigcode/the-stack
train
830ef77e210c8f80337fecbf
train
class
class Solution: def guessNumber(self, n: int) -> int: if n < 2: return n left = 1 right = n while left <= right: mid = (left + right) // 2 result = guess(mid) if result == 0: return mid elif result == 1: ...
class Solution:
def guessNumber(self, n: int) -> int: if n < 2: return n left = 1 right = n while left <= right: mid = (left + right) // 2 result = guess(mid) if result == 0: return mid elif result == 1: left...
Lower # # @lc code=start # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution:
64
64
99
3
61
zhongqi1112/Hulk
leetcode/374.guess-number-higher-or-lower.py
Python
Solution
Solution
13
27
13
13
ad0b6b4361c28f1a64c2bd372724802e77ca1ad8
bigcode/the-stack
train
02c0e01ed5e0ba0869fff0e1
train
function
def check_clause(clause, solution): for lit in clause: var = abs(lit) if lit < 0: inverted = True else: inverted = False if solution[var] != inverted: return True
def check_clause(clause, solution):
for lit in clause: var = abs(lit) if lit < 0: inverted = True else: inverted = False if solution[var] != inverted: return True
_literals from __future__ import print_function from array import array as _array import sys import unittest import pycryptosat from pycryptosat import Solver def array(typecode, initializer=()): return _array(str(typecode), initializer) def check_clause(clause, solution):
64
64
53
8
56
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
check_clause
check_clause
38
47
38
38
801ba2e50a55de9af8bfef6a0301f26128448d12
bigcode/the-stack
train
c73cca99b417ca01348a1786
train
function
def check_solution(clauses, solution): for clause in clauses: if check_clause(clause, solution) is False: return False return True
def check_solution(clauses, solution):
for clause in clauses: if check_clause(clause, solution) is False: return False return True
initializer) def check_clause(clause, solution): for lit in clause: var = abs(lit) if lit < 0: inverted = True else: inverted = False if solution[var] != inverted: return True def check_solution(clauses, solution):
64
64
35
9
54
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
check_solution
check_solution
50
55
50
50
370c37e2e75f4fdc6b6037d679bd29753598a67a
bigcode/the-stack
train
2c162aed39f95a17c497d125
train
class
class InitTester(unittest.TestCase): def test_wrong_args_to_solver(self): self.assertRaises(ValueError, Solver, threads=-1) self.assertRaises(ValueError, Solver, threads=0) self.assertRaises(ValueError, Solver, verbose=-1) self.assertRaises(ValueError, Solver, time_limit=-1) ...
class InitTester(unittest.TestCase):
def test_wrong_args_to_solver(self): self.assertRaises(ValueError, Solver, threads=-1) self.assertRaises(ValueError, Solver, threads=0) self.assertRaises(ValueError, Solver, verbose=-1) self.assertRaises(ValueError, Solver, time_limit=-1) self.assertRaises(ValueError, Solver,...
1: toassume.append(i * -1) self.solver.add_xor_clause(toadd, False) res, solution = self.solver.solve(toassume) self.assertEqual(res, True) self.assertEqual(solution, tuple(solution_expected)) class InitTester(unittest.TestCase):
64
64
137
7
57
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
InitTester
InitTester
138
149
138
139
b1c3ed25e7b0506d54d25cf06210db367e52ebaa
bigcode/the-stack
train
4ef18a1c7b55a1789e166eef
train
function
def array(typecode, initializer=()): return _array(str(typecode), initializer)
def array(typecode, initializer=()):
return _array(str(typecode), initializer)
OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import unicode_literals from __future__ import print_function from array import array as _array import sys import unittest import pycryptosat from pycryptosat import Solver def array(typecode, initializer=()):
64
64
18
8
55
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
array
array
34
35
34
34
81c0a558488764b94f605ce591c9eb8c82d94d73
bigcode/the-stack
train
ec5ce9e31f3aa7bba68155d3
train
class
class TestXor(unittest.TestCase): def setUp(self): self.solver = Solver(threads=2) def test_wrong_args(self): self.assertRaises(TypeError, self.solver.add_xor_clause, [1, 2]) self.assertRaises(ValueError, self.solver.add_xor_clause, [1, 0], True) self.assertRaises( ...
class TestXor(unittest.TestCase):
def setUp(self): self.solver = Solver(threads=2) def test_wrong_args(self): self.assertRaises(TypeError, self.solver.add_xor_clause, [1, 2]) self.assertRaises(ValueError, self.solver.add_xor_clause, [1, 0], True) self.assertRaises( ValueError, self.solver.add_xor_cla...
5 3 4 0 # -3 -4 0 clauses1 = [[1, -5, 4], [-1, 5, 3, 4], [-3, -4]] # p cnf 2 2 # -1 0 # 1 0 clauses2 = [[-1], [1]] # p cnf 2 3 # -1 2 0 # -1 -2 0 # 1 -2 0 clauses3 = [[-1, 2], [-1, -2], [1, -2]] # -------------------------- actual unit tests --------------------------- class TestXor(unittest.TestCase):
152
153
510
8
144
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
TestXor
TestXor
79
135
79
80
d7e4552171150e31e084db4a58baa818e0764933
bigcode/the-stack
train
402ecb81078d8d235876911f
train
class
class TestDump(unittest.TestCase): def setUp(self): self.solver = Solver() def test_max_glue_missing(self): self.assertRaises(TypeError, self.solver.start_getting_small_clauses, 4) def test_one_dump(self): with open("tests/test.cnf", "r") as x: ...
class TestDump(unittest.TestCase):
def setUp(self): self.solver = Solver() def test_max_glue_missing(self): self.assertRaises(TypeError, self.solver.start_getting_small_clauses, 4) def test_one_dump(self): with open("tests/test.cnf", "r") as x: for line in x: lin...
=-1) self.assertRaises(TypeError, Solver, threads="fail") self.assertRaises(TypeError, Solver, verbose="fail") self.assertRaises(TypeError, Solver, time_limit="fail") self.assertRaises(TypeError, Solver, confl_limit="fail") class TestDump(unittest.TestCase):
64
64
196
7
57
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
TestDump
TestDump
152
177
152
153
0aa21e49bfa4aa3fb54e16056f6afdb121e1e2ee
bigcode/the-stack
train
18fca70810edad033dcfa2cc
train
class
class TestSolve(unittest.TestCase): def setUp(self): self.solver = Solver(threads=2) def test_wrong_args(self): self.assertRaises(TypeError, self.solver.add_clause, 'A') self.assertRaises(TypeError, self.solver.add_clause, 1) self.assertRaises(TypeError, self.solver.add_clause,...
class TestSolve(unittest.TestCase):
def setUp(self): self.solver = Solver(threads=2) def test_wrong_args(self): self.assertRaises(TypeError, self.solver.add_clause, 'A') self.assertRaises(TypeError, self.solver.add_clause, 1) self.assertRaises(TypeError, self.solver.add_clause, 1.0) self.assertRaises(TypeE...
Solver, verbose="fail") self.assertRaises(TypeError, Solver, time_limit="fail") self.assertRaises(TypeError, Solver, confl_limit="fail") class TestDump(unittest.TestCase): def setUp(self): self.solver = Solver() def test_max_glue_missing(self): self.assertRaises(TypeError, ...
237
237
790
7
230
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
TestSolve
TestSolve
180
267
180
181
e6b4080eb4ea38b63970bd4c53b51e59922dab9a
bigcode/the-stack
train
8aa2bbb41eacf05ba444b3ef
train
function
def run(): print("sys.prefix: %s" % sys.prefix) print("sys.version: %s" % sys.version) try: print("pycryptosat version: %r" % pycryptosat.__version__) except AttributeError: pass suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestXor)) suite.addTest(unittest.ma...
def run():
print("sys.prefix: %s" % sys.prefix) print("sys.version: %s" % sys.version) try: print("pycryptosat version: %r" % pycryptosat.__version__) except AttributeError: pass suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestXor)) suite.addTest(unittest.makeSuite(Ini...
self.solver.add_clause([-5, 1]) self.solver.add_clause([4, -3]) self.solver.add_clause([2, 3, 5]) res, _ = self.solver.solve() self.assertEqual(res, True) # ------------------------------------------------------------------------ def run():
63
64
195
3
60
xhochy/cryptominisat
python/tests/test_pycryptosat.py
Python
run
run
272
297
272
272
45e47b41d9c51c58ee74052c51cdc017bdf235a6
bigcode/the-stack
train
3ecf1b4d42cab10fc1731b8a
train
class
class LinuxConfiguration(Model): """Specifies the Linux operating system settings on the virtual machine. <br><br>For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazur...
class LinuxConfiguration(Model):
"""Specifies the Linux operating system settings on the virtual machine. <br><br>For a list of supported Linux distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-linux-endorsed-distros?toc=%2fazure%2fvirtual-machines%2flinux%2fto...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
88
135
452
5
82
pjquirk/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_03_01/models/linux_configuration.py
Python
LinuxConfiguration
LinuxConfiguration
15
47
15
15
99b8b2bd029db351f563f2a35b933d9e1031aa6a
bigcode/the-stack
train
2cdb160b1076dad178e77b04
train
class
class CoverageTest(utils.TestCase): def test_start_coverage(self): c = cs.coverage.start() cs.assert_called('POST', '/os-coverage/action') def test_stop_coverage(self): c = cs.coverage.stop() return_dict = {'path': '/tmp/tmpdir/report'} cs.assert_called_anytime('POST', ...
class CoverageTest(utils.TestCase):
def test_start_coverage(self): c = cs.coverage.start() cs.assert_called('POST', '/os-coverage/action') def test_stop_coverage(self): c = cs.coverage.stop() return_dict = {'path': '/tmp/tmpdir/report'} cs.assert_called_anytime('POST', '/os-coverage/action') def test_...
# See: http://wiki.openstack.org/Nova/CoverageExtension for more information # and usage explanation for this API extension from novaclient.tests import utils from novaclient.tests.v1_1 import fakes cs = fakes.FakeClient() class CoverageTest(utils.TestCase):
64
64
157
7
57
citrix-openstack-build/python-novaclient
novaclient/tests/v1_1/test_coverage_ext.py
Python
CoverageTest
CoverageTest
27
45
27
28
9b684eaff2f70b9a6f3fa784fbd9f713bf20e812
bigcode/the-stack
train
c3c1892eabcefaf85f85fedb
train
function
def browserViewProviding(for_, factory, providing, layer=IDefaultBrowserLayer): """Define a view providing a particular interface.""" return browserView(for_, '', factory, layer, providing)
def browserViewProviding(for_, factory, providing, layer=IDefaultBrowserLayer):
"""Define a view providing a particular interface.""" return browserView(for_, '', factory, layer, providing)
browserView(for_, name, factory, layer=IDefaultBrowserLayer, providing=Interface): """Define a global browser view """ provideAdapter(for_, providing, factory, name, (layer,)) def browserViewProviding(for_, factory, providing, layer=IDefaultBrowserLayer):
63
64
41
18
46
zopefoundation/zope.app.authentication
src/zope/app/authentication/browser/tests/__init__.py
Python
browserViewProviding
browserViewProviding
51
53
51
51
b2fd245bfc715582134a3266275c88305b2eb64a
bigcode/the-stack
train
387d0e2d3b36511ed1ef22ad
train
function
def provideMultiView(for_, type, providing, name, factory, layer=None): if layer is None: layer = type provideAdapter(for_[0], providing, factory, name, tuple(for_[1:])+(layer,))
def provideMultiView(for_, type, providing, name, factory, layer=None):
if layer is None: layer = type provideAdapter(for_[0], providing, factory, name, tuple(for_[1:])+(layer,))
name, (layer,)) def browserViewProviding(for_, factory, providing, layer=IDefaultBrowserLayer): """Define a view providing a particular interface.""" return browserView(for_, '', factory, layer, providing) def provideMultiView(for_, type, providing, name, factory, layer=None):
64
64
50
17
47
zopefoundation/zope.app.authentication
src/zope/app/authentication/browser/tests/__init__.py
Python
provideMultiView
provideMultiView
56
59
56
56
116c5485fb7241400293e8c5bea60905fc5f032d
bigcode/the-stack
train
4e093bbf62479c6e8117f77c
train
function
def provideUtility(provided, utility, name=''): gsm = component.getGlobalSiteManager() gsm.registerUtility(utility, provided, name, event=False)
def provideUtility(provided, utility, name=''):
gsm = component.getGlobalSiteManager() gsm.registerUtility(utility, provided, name, event=False)
, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## "Test helpers; not public API" from zope import component from zope.interface import Interface from zope.publisher.interfaces.browser import IDefaultBrowser...
64
64
34
11
52
zopefoundation/zope.app.authentication
src/zope/app/authentication/browser/tests/__init__.py
Python
provideUtility
provideUtility
22
24
22
22
d948dd752f7cee047bf926ffbdbdcbea94cdd9bb
bigcode/the-stack
train
846bc3105ef738a03719f641
train
function
def provideAdapter(required, provided, factory, name='', using=None, **kw): assert 'with' not in kw assert not isinstance(factory, stypes), "Factory cannot be a list or tuple" gsm = component.getGlobalSiteManager() if using: required = (required, ) + tuple(using) elif not isinstance(requir...
def provideAdapter(required, provided, factory, name='', using=None, **kw):
assert 'with' not in kw assert not isinstance(factory, stypes), "Factory cannot be a list or tuple" gsm = component.getGlobalSiteManager() if using: required = (required, ) + tuple(using) elif not isinstance(required, stypes): required = (required,) gsm.registerAdapter(factory...
import IDefaultBrowserLayer def provideUtility(provided, utility, name=''): gsm = component.getGlobalSiteManager() gsm.registerUtility(utility, provided, name, event=False) stypes = list, tuple def provideAdapter(required, provided, factory, name='', using=None, **kw):
64
64
99
17
46
zopefoundation/zope.app.authentication
src/zope/app/authentication/browser/tests/__init__.py
Python
provideAdapter
provideAdapter
30
41
30
30
c0afca80841b13767bb8972b0bf742fbe7286d63
bigcode/the-stack
train
9d513351c41ffe15a10852c5
train
function
def browserView(for_, name, factory, layer=IDefaultBrowserLayer, providing=Interface): """Define a global browser view """ provideAdapter(for_, providing, factory, name, (layer,))
def browserView(for_, name, factory, layer=IDefaultBrowserLayer, providing=Interface):
"""Define a global browser view """ provideAdapter(for_, providing, factory, name, (layer,))
required = (required, ) + tuple(using) elif not isinstance(required, stypes): required = (required,) gsm.registerAdapter(factory, required, provided, name, event=False) def browserView(for_, name, factory, layer=IDefaultBrowserLayer, providing=Interface):
64
64
46
22
42
zopefoundation/zope.app.authentication
src/zope/app/authentication/browser/tests/__init__.py
Python
browserView
browserView
44
48
44
45
42659e8ead1d140886576e2f9ba4c1f4de51d5bf
bigcode/the-stack
train
8354e7f835f38348e269a672
train
function
def parse_tff_to_tf(comp, grappler_config_proto): """Parses TFF construct `comp` into TensorFlow construct. Does not change the type signature of `comp`. Therefore may return either a `building_blocks.CompiledComputation` or a `building_blocks.Call` with no argument and function `building_blocks.CompiledComput...
def parse_tff_to_tf(comp, grappler_config_proto):
"""Parses TFF construct `comp` into TensorFlow construct. Does not change the type signature of `comp`. Therefore may return either a `building_blocks.CompiledComputation` or a `building_blocks.Call` with no argument and function `building_blocks.CompiledComputation`. Args: comp: Instance of `building_b...
described above. """ py_typecheck.check_type(comp, building_blocks.ComputationBuildingBlock) comp.type_signature.check_function() # Drop any unused subcomputations which may reference placements different # from the result. simplified = transformations.to_deduped_call_dominant(comp) unplaced, _ = tree_tr...
121
121
405
13
107
truthiswill/federated
tensorflow_federated/python/core/backends/mapreduce/transformations.py
Python
parse_tff_to_tf
parse_tff_to_tf
231
268
231
231
db2e692efc4e1192ce2e23af670a73241916f9e2
bigcode/the-stack
train
22af37ba40cf776a476dc0d8
train
class
class MapReduceFormCompilationError(Exception): pass
class MapReduceFormCompilationError(Exception):
pass
.compiler import transformations from tensorflow_federated.python.core.impl.compiler import tree_analysis from tensorflow_federated.python.core.impl.compiler import tree_transformations from tensorflow_federated.python.core.impl.types import computation_types from tensorflow_federated.python.core.impl.types import plac...
64
64
11
8
55
truthiswill/federated
tensorflow_federated/python/core/backends/mapreduce/transformations.py
Python
MapReduceFormCompilationError
MapReduceFormCompilationError
78
79
78
78
77268052f7f528a9cb9f56a9f0390d4391b832a6
bigcode/the-stack
train
56a9ca4148bec0c636e73e6f
train
function
def concatenate_function_outputs(first_function, second_function): """Constructs a new function concatenating the outputs of its arguments. Assumes that `first_function` and `second_function` already have unique names, and have declared parameters of the same type. The constructed function will bind its parame...
def concatenate_function_outputs(first_function, second_function):
"""Constructs a new function concatenating the outputs of its arguments. Assumes that `first_function` and `second_function` already have unique names, and have declared parameters of the same type. The constructed function will bind its parameter to each of the parameters of `first_function` and `second_fun...
TODO(b/184883078): Remove this check and trust Grappler to disable itself # based on the `disable_meta_optimizer` config. should_skip_grappler = ( grappler_config_proto.HasField('graph_options') and grappler_config_proto.graph_options.HasField('rewrite_options') and grappler_config_proto.graph_op...
148
148
496
10
137
truthiswill/federated
tensorflow_federated/python/core/backends/mapreduce/transformations.py
Python
concatenate_function_outputs
concatenate_function_outputs
271
327
271
271
b9056a0586a882c5566a2acb1b914d748f1f1f66
bigcode/the-stack
train
bbbb9747ce3698fd71439bac
train
function
def normalize_all_equal_bit(comp): """Normalizes the all equal bits under `comp`. For any computation of `tff.FederatedType`, we rely on uniformity of the `all_equal` bit to compile down to MapReduce form. For example, the values processed on the clients can only be accessed through a `federated_zip`, which ...
def normalize_all_equal_bit(comp):
"""Normalizes the all equal bits under `comp`. For any computation of `tff.FederatedType`, we rely on uniformity of the `all_equal` bit to compile down to MapReduce form. For example, the values processed on the clients can only be accessed through a `federated_zip`, which produces a value with its `all_equa...
passed ' 'one function which declared a parameter of type {}, and ' 'another which declares a parameter of type {}'.format( first_function.type_signature, second_function.type_signature)) def _rename_first_function_arg(comp): ...
201
201
671
7
193
truthiswill/federated
tensorflow_federated/python/core/backends/mapreduce/transformations.py
Python
normalize_all_equal_bit
normalize_all_equal_bit
330
401
330
330
3c0c851e3da4d0cbe5bdc54050b796afda27dadc
bigcode/the-stack
train
50897f23bc428da1442ed390
train
function
def consolidate_and_extract_local_processing(comp, grappler_config_proto): """Consolidates all the local processing in `comp`. The input computation `comp` must have the following properties: 1. The output of `comp` may be of a federated type or unplaced. We refer to the placement `p` of that type as the p...
def consolidate_and_extract_local_processing(comp, grappler_config_proto):
"""Consolidates all the local processing in `comp`. The input computation `comp` must have the following properties: 1. The output of `comp` may be of a federated type or unplaced. We refer to the placement `p` of that type as the placement of `comp`. There is no placement anywhere in the body of `com...
-functional type {} after unwrapping placement. Instead we ' 'have the computation {} of type {}'.format( before_extraction.type_signature, extracted, extracted.type_signature)) if not extracted.function.is_compiled_computation(): raise MapReduceFormCompilationError( ...
256
256
1,182
13
243
truthiswill/federated
tensorflow_federated/python/core/backends/mapreduce/transformations.py
Python
consolidate_and_extract_local_processing
consolidate_and_extract_local_processing
121
228
121
121
556093259c3276bb9259963415d3d15ecd3ad9dd
bigcode/the-stack
train