code stringlengths 31 2.05k | label_name stringclasses 5
values | label int64 0 4 |
|---|---|---|
def on_header_value(self, data: bytes, start: int, end: int) -> None:
message = (MultiPartMessage.HEADER_VALUE, data[start:end])
self.messages.append(message) | Class | 2 |
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
self.messa... | Class | 2 |
def on_end(self) -> None:
message = (MultiPartMessage.END, b"")
self.messages.append(message) | Class | 2 |
def on_headers_finished(self) -> None:
message = (MultiPartMessage.HEADERS_FINISHED, b"")
self.messages.append(message) | Class | 2 |
def on_header_end(self) -> None:
message = (MultiPartMessage.HEADER_END, b"")
self.messages.append(message) | Class | 2 |
def form(self) -> AwaitableOrContextManager[FormData]:
return AwaitableOrContextManagerWrapper(self._get_form()) | Class | 2 |
async def _get_form(self) -> FormData:
if self._form is None:
assert (
parse_options_header is not None
), "The `python-multipart` library must be installed to use form parsing."
content_type_header = self.headers.get("Content-Type")
content_ty... | Class | 2 |
def execute(self):
# clean up tmp extraction folder
if os.path.exists(TEMP_EXTRACTION_PATH) and not CleanupDir(TEMP_EXTRACTION_PATH).run():
logger.error('Could not clean temp folder')
raise IOError
# untar the package into tmp folder
with closing(tarfile.open... | Base | 1 |
def open(self, *args, **kwargs):
"""Websocket connection opened.
Call our terminal manager to get a terminal, and connect to it as a
client.
"""
# Jupyter has a mixin to ping websockets and keep connections through
# proxies alive. Call super() to allow that to set u... | Base | 1 |
def __init__(self, path):
self.path = path | Class | 2 |
def _write(self, contents: dict):
LOGGER.debug(f'Writing to {self.path}')
with open(self.path, 'w') as fp:
fp.write(json.dumps(contents)) | Class | 2 |
def secret_path(monkeypatch, tmp_path):
secret_path = str(tmp_path / '.test')
monkeypatch.setattr(auth, 'SECRET_FILE_PATH', secret_path)
yield secret_path | Class | 2 |
def __init__(self, config, md):
"""Initialize."""
base = config.get('base_path')
if isinstance(base, str):
base = [base]
self.base_path = base
self.encoding = config.get('encoding')
self.check_paths = config.get('check_paths')
self.auto_a... | Base | 1 |
def get_snippet_path(self, path):
"""Get snippet path."""
snippet = None
for base in self.base_path:
if os.path.exists(base):
if os.path.isdir(base):
filename = os.path.join(base, path)
if os.path.exists(filename):
... | Base | 1 |
def rebuild_proxies(self, prepared_request, proxies):
"""This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
proxy keys for this URL (... | Class | 2 |
def confirm_sns_subscription(notification):
logger.info(
'Received subscription confirmation: TopicArn: %s',
notification.get('TopicArn'),
extra={
'notification': notification,
},
)
# Get the subscribe url and hit the url to confirm the subscription.
subscrib... | Base | 1 |
def _get_bytes_to_sign(self):
"""
Creates the message used for signing SNS notifications.
This is used to verify the bounce message when it is received.
"""
# Depending on the message type the fields to add to the message
# differ so we handle that here.
msg_... | Base | 1 |
def BounceMessageVerifier(*args, **kwargs):
warnings.warn(
'utils.BounceMessageVerifier is deprecated. It is renamed to EventMessageVerifier.',
RemovedInDjangoSES20Warning,
)
# parameter name is renamed from bounce_dict to notification.
if 'bounce_dict' in kwargs:
kwargs['notifi... | Base | 1 |
def verify_bounce_message(msg):
"""
Verify an SES/SNS bounce(event) notification message.
"""
warnings.warn(
'utils.verify_bounce_message is deprecated. It is renamed to verify_event_message.',
RemovedInDjangoSES20Warning,
)
return verify_event_message(msg) | Base | 1 |
def get_keys(self, lst):
"""
return a list of pk values from object list
"""
pk_name = self.get_pk_name()
if self.is_pk_composite():
return [[getattr(item, pk) for pk in pk_name] for item in lst]
else:
return [getattr(item, pk_name) for ite... | Base | 1 |
def get_user_columns_list(self):
"""
Returns a list of user viewable columns names
"""
return self.get_columns_list() | Base | 1 |
def get_columns_list(self):
"""
Returns a list of all the columns names
"""
return [] | Base | 1 |
def get(self, pk, filter=None):
"""
return the record from key, you can optionally pass filters
if pk exits on the db but filters exclude it it will return none.
"""
pass | Base | 1 |
def get_values_json(self, lst, list_columns):
"""
Converts list of objects from query to JSON
"""
result = []
for item in self.get_values(lst, list_columns):
for key, value in list(item.items()):
if isinstance(value, datetime.datetime) or isins... | Base | 1 |
def add(self, item):
"""
Adds object
"""
raise NotImplementedError | Base | 1 |
def get_search_columns_list(self):
"""
Returns a list of searchable columns names
"""
return [] | Base | 1 |
def get_order_columns_list(self, list_columns=None):
"""
Returns a list of order columns names
"""
return [] | Base | 1 |
def edit(self, item):
"""
Edit (change) object
"""
raise NotImplementedError | Base | 1 |
def get_pk_name(self):
"""
Returns the primary key name
"""
raise NotImplementedError | Base | 1 |
def get_values(self, lst, list_columns):
"""
Get Values: formats values for list template.
returns [{'col_name':'col_value',....},{'col_name':'col_value',....}]
:param lst:
The list of item objects from query
:param list_columns:
... | Base | 1 |
def get_related_interface(self, col_name):
"""
Returns a BaseInterface for the related model
of column name.
:param col_name: Column name with relation
:return: BaseInterface
"""
raise NotImplementedError | Base | 1 |
def _get_values(self, lst, list_columns):
"""
Get Values: formats values for list template.
returns [{'col_name':'col_value',....},{'col_name':'col_value',....}]
:param lst:
The list of item objects from query
:param list_columns:
... | Base | 1 |
def delete(self, item):
"""
Deletes object
"""
raise NotImplementedError | Base | 1 |
def delete(self, item: Model, raise_exception: bool = False) -> bool:
try:
self._delete_files(item)
self.session.delete(item)
self.session.commit()
self.message = (as_unicode(self.delete_row_message), "success")
return True
except Integrity... | Base | 1 |
def delete_all(self, items: List[Model]) -> bool:
try:
for item in items:
self._delete_files(item)
self.session.delete(item)
self.session.commit()
self.message = (as_unicode(self.delete_row_message), "success")
return True
... | Base | 1 |
def add(self, item: Model, raise_exception: bool = False) -> bool:
try:
self.session.add(item)
self.session.commit()
self.message = (as_unicode(self.add_row_message), "success")
return True
except IntegrityError as e:
self.message = (as_uni... | Base | 1 |
def edit(self, item: Model, raise_exception: bool = False) -> bool:
try:
self.session.merge(item)
self.session.commit()
self.message = (as_unicode(self.edit_row_message), "success")
return True
except IntegrityError as e:
self.message = (as... | Base | 1 |
def warn( # type: ignore[override]
self,
msg: str,
path_name: str | None = None,
func_name: str | None = None,
*args: Any,
**kwargs: Any,
) -> None:
warnings.warn(
"The 'warn' method is deprecated, " "use 'warning' instead",
Deprec... | Class | 2 |
def write_log(self, log_message, ipaddress):
# Make entry.
db = self.connect_logdb()
c = db.cursor()
# Insert a row of data.
c.execute(
f"""insert into log
values ({datetime.utcnow().strftime('%Y%m%d')}, {datetime.utcnow().strftime('%H%M%S')}, ?, ... | Base | 1 |
def home():
# Get the boards from the database:
boards = Database.get_boards()
# Write to the log:
Database.write_log(f"Request to home page from {request.environ['REMOTE_ADDR']}.", request.environ['REMOTE_ADDR'])
# Render the home page, with the boards:
return render_template(
"home.h... | Base | 1 |
def about():
# Write to the log:
Database.write_log(f"Request to about page from {request.environ['REMOTE_ADDR']}.", f"{request.environ['REMOTE_ADDR']}")
return render_template(
"about.html",
description=Config.get_config()["long_description"].split("<br>"),
) | Base | 1 |
def date_filter(s):
return datetime.utcnow().strftime('%Y') | Base | 1 |
def boardView():
boardID = request.args.get("board", default=1, type=int)
pageID = request.args.get("page", default=1, type=int)
# Get the board information:
boardInfo = Database.get_board_info(boardID)
# Get the posts from the board:
posts = Database.get_posts_from_board(boardID)
# Reduc... | Base | 1 |
def postView():
# Get the post ID from the URL:
postID = request.args.get("postid", default=1, type=int)
# Get the post information:
postInfo = Database.get_post_info(postID)
# Get the comments from the post:
comments = Database.get_comments_from_post(postID)
# Get the user information:
... | Base | 1 |
def set(self, name, value, force=False):
"""Set a form element identified by ``name`` to a specified ``value``.
The type of element (input, textarea, select, ...) does not
need to be given; it is inferred by the following methods:
:func:`~Form.set_checkbox`,
:func:`~Form.set_... | Class | 2 |
def test_upload_file(httpbin):
browser = mechanicalsoup.StatefulBrowser()
browser.open(httpbin + "/forms/post")
# Create two temporary files to upload
def make_file(content):
path = tempfile.mkstemp()[1]
with open(path, "w") as fd:
fd.write(content)
return path
p... | Class | 2 |
def _make_cmd(self, tmpfilename, info_dict):
cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies', '--compression=auto']
if info_dict.get('http_headers') is not None:
for key, val in info_dict['http_headers'].items():
cmd += ['--header', f'{key}: {val}']
cmd ... | Class | 2 |
def redirect_request(self, req, fp, code, msg, headers, newurl):
if code not in (301, 302, 303, 307, 308):
raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)
new_method = req.get_method()
new_data = req.data
remove_headers = []
# A 303 must either... | Class | 2 |
def _calc_headers(self, info_dict):
res = merge_headers(self.params['http_headers'], info_dict.get('http_headers') or {})
if 'Youtubedl-No-Compression' in res: # deprecated
res.pop('Youtubedl-No-Compression', None)
res['Accept-Encoding'] = 'identity'
cookies = self.c... | Class | 2 |
def download(self, filename, info_dict, subtitle=False):
"""Download to a filename using the info from info_dict
Return True on success and False otherwise
"""
nooverwrites_and_exists = (
not self.params.get('overwrites', True)
and os.path.exists(encodeFilena... | Class | 2 |
def compat_shlex_quote(s):
import re
return s if re.match(r'^[-_\w./]+$', s) else '"%s"' % s.replace('"', '\\"') | Base | 1 |
def run(self, info):
for tmpl in self.exec_cmd:
cmd = self.parse_cmd(tmpl, info)
self.to_screen('Executing command: %s' % cmd)
retCode = subprocess.call(encodeArgument(cmd), shell=True)
if retCode != 0:
raise PostProcessingError('Command return... | Base | 1 |
def __init__(self, *args, env=None, text=False, **kwargs):
if env is None:
env = os.environ.copy()
self._fix_pyinstaller_ld_path(env)
self.__text_mode = kwargs.get('encoding') or kwargs.get('errors') or text or kwargs.get('universal_newlines')
if text is True:
... | Base | 1 |
def _real_extract(self, url):
activity_id, enrollment_id = self._match_valid_url(url).group('id', 'enrollment')
course = self._call_api('enrollment', enrollment_id)['content']
activity = traverse_obj(course, ('learning_modules', ..., 'activities', lambda _, v: int(activity_id) == v['id']), g... | Base | 1 |
def _real_extract(self, url):
qs = parse_qs(url)
src = urllib.parse.unquote(traverse_obj(qs, ('url', 0)) or '')
if src and YoutubeTabIE.suitable(src):
return self.url_result(src, YoutubeTabIE)
return self.url_result(smuggle_url(
urllib.parse.unquote(traverse_o... | Base | 1 |
def _parse_video(self, video):
title = video['title']
vimeo_id = self._search_regex(
r'https?://player\.vimeo\.com/external/(\d+)',
video['vimeoVideoURL'], 'vimeo id')
uploader_id = video.get('hostID')
return {
'_type': 'url_transparent',
... | Base | 1 |
def _unsmuggle_headers(self, url):
"""@returns (url, smuggled_data, headers)"""
url, data = unsmuggle_url(url, {})
headers = self.get_param('http_headers').copy()
if 'http_headers' in data:
headers.update(data['http_headers'])
return url, data, headers | Base | 1 |
def _smuggle_referrer(url, referrer_url):
return smuggle_url(url, {'http_headers': {'Referer': referrer_url}}) | Base | 1 |
def test_recovery_flow(self):
"""Test that recovery flow is linked correctly"""
flow = create_test_flow()
self.stage.recovery_flow = flow
self.stage.save()
FlowStageBinding.objects.create(
target=flow,
stage=self.stage,
order=0,
)
... | Base | 1 |
def update_bundles(inner_bundles: Set[Tuple[int, datetime, int]]):
for (bundle_id, date_added, file_id) in inner_bundles:
used_artifact_bundles[bundle_id] = date_added
bundle_file_ids.add(file_id) | Class | 2 |
def get_legacy_release_bundles(release: Release, dist: Optional[Distribution]):
return set(
ReleaseFile.objects.select_related("file")
.filter(
release_id=release.id,
dist_id=dist.id if dist else None,
# a `ReleaseFile` with `0` artifacts represents a release arch... | Class | 2 |
def download_file(self, file_id, project: Project):
rate_limited = ratelimits.is_limited(
project=project,
key=f"rl:ArtifactLookupEndpoint:download:{file_id}:{project.id}",
limit=10,
)
if rate_limited:
logger.info(
"notification... | Class | 2 |
def url_for_file_id(self, file_id: int) -> str:
# NOTE: Returning a self-route that requires authentication (via Bearer token)
# is not really forward compatible with a pre-signed URL that does not
# require any authentication or headers whatsoever.
# This also requires a workaround ... | Class | 2 |
def download(self, debug_file_id, project):
rate_limited = ratelimits.is_limited(
project=project,
key=f"rl:DSymFilesEndpoint:download:{debug_file_id}:{project.id}",
limit=10,
)
if rate_limited:
logger.info(
"notification.rate_l... | Class | 2 |
def allow_cors_options_wrapper(self, request: Request, *args, **kwargs):
if request.method == "OPTIONS":
response = HttpResponse(status=200)
response["Access-Control-Max-Age"] = "3600" # don't ask for options again for 1 hour
else:
response = func(self, request, ... | Pillar | 3 |
def test_allow_credentials_incorrect(self):
org = self.create_organization()
apikey = ApiKey.objects.create(organization_id=org.id, allowed_origins="*")
request = self.make_request(method="GET")
request.META["HTTP_ORIGIN"] = "http://acme.example.com"
request.META["HTTP_AUTHO... | Pillar | 3 |
def _register_template(
cls,
template: CustomConnectorTemplate,
) -> None:
"""
Registers a custom connector template by converting it to a ConnectorTemplate,
registering any custom functions, and adding it to the loader's template dictionary.
"""
connector... | Pillar | 3 |
def _register_template(
cls,
template: CustomConnectorTemplate,
) -> None:
"""
Registers a custom connector template by converting it to a ConnectorTemplate,
registering any custom functions, and adding it to the loader's template dictionary.
"""
connector... | Base | 1 |
def register_custom_functions(script: str) -> None:
"""
Registers custom functions by executing the given script in a restricted environment.
The script is compiled and executed with RestrictedPython, which is designed to reduce
the risk of executing untrusted code. It provides a set of safe builtins t... | Pillar | 3 |
def register_custom_functions(script: str) -> None:
"""
Registers custom functions by executing the given script in a restricted environment.
The script is compiled and executed with RestrictedPython, which is designed to reduce
the risk of executing untrusted code. It provides a set of safe builtins t... | Base | 1 |
def visit_AnnAssign(self, node: AnnAssign) -> AST:
return self.node_contents_visit(node) | Pillar | 3 |
def visit_AnnAssign(self, node: AnnAssign) -> AST:
return self.node_contents_visit(node) | Base | 1 |
def custom_guarded_import(
name: str,
_globals: Optional[dict] = None,
_locals: Optional[dict] = None,
fromlist: Optional[Tuple[str, ...]] = None,
level: int = 0,
) -> Any:
"""
A custom import function that prevents the import of certain potentially unsafe modules.
"""
if name in [
... | Pillar | 3 |
def custom_guarded_import(
name: str,
_globals: Optional[dict] = None,
_locals: Optional[dict] = None,
fromlist: Optional[Tuple[str, ...]] = None,
level: int = 0,
) -> Any:
"""
A custom import function that prevents the import of certain potentially unsafe modules.
"""
if name in [
... | Base | 1 |
def _load_connector_templates(self) -> None:
logger.info("Loading connectors templates from the data/saas directory")
for file in os.listdir("data/saas/config"):
if file.endswith(".yml"):
config_file = os.path.join("data/saas/config", file)
config_dict = l... | Pillar | 3 |
def _load_connector_templates(self) -> None:
logger.info("Loading connectors templates from the data/saas directory")
for file in os.listdir("data/saas/config"):
if file.endswith(".yml"):
config_file = os.path.join("data/saas/config", file)
config_dict = l... | Base | 1 |
def connector_template_invalid_dataset(
self,
planet_express_config,
planet_express_invalid_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"datas... | Pillar | 3 |
def connector_template_invalid_dataset(
self,
planet_express_config,
planet_express_invalid_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"datas... | Base | 1 |
def connector_template_no_icon(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml": planet_express_dataset,
... | Pillar | 3 |
def connector_template_no_icon(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml": planet_express_dataset,
... | Base | 1 |
def connector_template_duplicate_icons(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml":... | Pillar | 3 |
def connector_template_duplicate_icons(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml":... | Base | 1 |
def connector_template_no_functions(
self,
planet_express_config,
planet_express_dataset,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml": planet_express_dataset,
... | Pillar | 3 |
def connector_template_no_functions(
self,
planet_express_config,
planet_express_dataset,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml": planet_express_dataset,
... | Base | 1 |
def test_register_connector_template_wrong_scope(
self,
api_client: TestClient,
register_connector_template_url,
generate_auth_header,
complete_connector_template,
):
CONFIG.security.allow_custom_connector_functions = True
auth_header = generate_auth_heade... | Pillar | 3 |
def test_register_connector_template_wrong_scope(
self,
api_client: TestClient,
register_connector_template_url,
generate_auth_header,
complete_connector_template,
):
CONFIG.security.allow_custom_connector_functions = True
auth_header = generate_auth_heade... | Base | 1 |
def connector_template_missing_dataset(
self,
planet_express_config,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"functions.py": planet_express_functions,
... | Pillar | 3 |
def connector_template_missing_dataset(
self,
planet_express_config,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"functions.py": planet_express_functions,
... | Base | 1 |
def complete_connector_template(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml": planet... | Pillar | 3 |
def complete_connector_template(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"dataset.yml": planet... | Base | 1 |
def connector_template_duplicate_configs(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"1_config.yml": planet_express_config,
"2_config.... | Pillar | 3 |
def connector_template_duplicate_configs(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"1_config.yml": planet_express_config,
"2_config.... | Base | 1 |
def connector_template_wrong_contents_config(
self,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": "planet_express_config",
"dataset.yml": planet_express_dataset... | Pillar | 3 |
def connector_template_wrong_contents_config(
self,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": "planet_express_config",
"dataset.yml": planet_express_dataset... | Base | 1 |
def connector_template_duplicate_datasets(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"1_dataset.... | Pillar | 3 |
def connector_template_duplicate_datasets(
self,
planet_express_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_config,
"1_dataset.... | Base | 1 |
def connector_template_invalid_config(
self,
planet_express_invalid_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_invalid_config,
... | Pillar | 3 |
def connector_template_invalid_config(
self,
planet_express_invalid_config,
planet_express_dataset,
planet_express_functions,
planet_express_icon,
):
return create_zip_file(
{
"config.yml": planet_express_invalid_config,
... | Base | 1 |
def test_register_connector_template_allow_custom_connector_functions(
self,
mock_register_custom_functions: MagicMock,
api_client: TestClient,
register_connector_template_url,
generate_auth_header,
zip_file,
status_code,
details,
request,
... | Pillar | 3 |
def test_register_connector_template_allow_custom_connector_functions(
self,
mock_register_custom_functions: MagicMock,
api_client: TestClient,
register_connector_template_url,
generate_auth_header,
zip_file,
status_code,
details,
request,
... | Base | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.