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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d83b3cb1cb8bbb40436a9a01 | train | class | @admin.register(BlackList)
class BlackListAdmin(admin.ModelAdmin):
list_display = ('id', 'user', 'ip_address', 'reason',)
| @admin.register(BlackList)
class BlackListAdmin(admin.ModelAdmin):
| list_display = ('id', 'user', 'ip_address', 'reason',)
| from django.contrib import admin
from .models import BlackList
@admin.register(BlackList)
class BlackListAdmin(admin.ModelAdmin):
| 28 | 64 | 32 | 15 | 12 | marcosvbras/inimex-api | app/blacklist/admin.py | Python | BlackListAdmin | BlackListAdmin | 4 | 6 | 4 | 5 | 711717069c82a53c94b78cc3cd9074393b8c1531 | bigcode/the-stack | train |
53a4571eada1477575c3a037 | train | function | def escape(text, chars):
"""Escapes all characters in 'chars' in text using backspaces."""
rv = ""
for char in text:
if char in chars:
rv += "\\"
rv += char
return rv
| def escape(text, chars):
| """Escapes all characters in 'chars' in text using backspaces."""
rv = ""
for char in text:
if char in chars:
rv += "\\"
rv += char
return rv
| while i < len(text):
if i + 1 < len(text) and text[i] == "\\":
rv += text[i + 1]
i += 1
else:
rv += text[i]
i += 1
return rv
def escape(text, chars):
| 64 | 64 | 52 | 6 | 57 | khatchad/vimrc | sources_non_forked/ultisnips/pythonx/UltiSnips/text.py | Python | escape | escape | 21 | 28 | 21 | 21 | e4653e0d445ea1b4e608677a86ce2894ffab4053 | bigcode/the-stack | train |
30156405ecbf27e03d458e6f | train | function | def fill_in_whitespace(text):
"""Returns 'text' with escaped whitespace replaced through whitespaces."""
text = text.replace(r"\n", "\n")
text = text.replace(r"\t", "\t")
text = text.replace(r"\r", "\r")
text = text.replace(r"\a", "\a")
text = text.replace(r"\b", "\b")
return text
| def fill_in_whitespace(text):
| """Returns 'text' with escaped whitespace replaced through whitespaces."""
text = text.replace(r"\n", "\n")
text = text.replace(r"\t", "\t")
text = text.replace(r"\r", "\r")
text = text.replace(r"\a", "\a")
text = text.replace(r"\b", "\b")
return text
|
return rv
def escape(text, chars):
"""Escapes all characters in 'chars' in text using backspaces."""
rv = ""
for char in text:
if char in chars:
rv += "\\"
rv += char
return rv
def fill_in_whitespace(text):
| 64 | 64 | 85 | 7 | 56 | khatchad/vimrc | sources_non_forked/ultisnips/pythonx/UltiSnips/text.py | Python | fill_in_whitespace | fill_in_whitespace | 31 | 38 | 31 | 31 | 609200bb77d475a15597ebda36e74f1010c4843c | bigcode/the-stack | train |
a1319f7b53ed537d81553eb6 | train | class | class LineIterator:
"""Convenience class that keeps track of line numbers in files."""
def __init__(self, text):
self._line_index = -1
self._lines = list(text.splitlines(True))
def __iter__(self):
return self
def __next__(self):
"""Returns the next line."""
if... | class LineIterator:
| """Convenience class that keeps track of line numbers in files."""
def __init__(self, text):
self._line_index = -1
self._lines = list(text.splitlines(True))
def __iter__(self):
return self
def __next__(self):
"""Returns the next line."""
if self._line_index + 1... | line is too short."""
generator = (t.strip() for t in line.split(None, 1))
head = next(generator).strip()
tail = ""
try:
tail = next(generator).strip()
except StopIteration:
pass
return head, tail
class LineIterator:
| 64 | 64 | 196 | 4 | 59 | khatchad/vimrc | sources_non_forked/ultisnips/pythonx/UltiSnips/text.py | Python | LineIterator | LineIterator | 54 | 83 | 54 | 55 | d4c8f89cb560f51c46c75e2b38eab1534101f6c7 | bigcode/the-stack | train |
d573cfb7f658e098022749bb | train | function | def unescape(text):
"""Removes '\\' escaping from 'text'."""
rv = ""
i = 0
while i < len(text):
if i + 1 < len(text) and text[i] == "\\":
rv += text[i + 1]
i += 1
else:
rv += text[i]
i += 1
return rv
| def unescape(text):
| """Removes '\\' escaping from 'text'."""
rv = ""
i = 0
while i < len(text):
if i + 1 < len(text) and text[i] == "\\":
rv += text[i + 1]
i += 1
else:
rv += text[i]
i += 1
return rv
| #!/usr/bin/env python3
# encoding: utf-8
"""Utilities to deal with text."""
def unescape(text):
| 26 | 64 | 85 | 5 | 21 | khatchad/vimrc | sources_non_forked/ultisnips/pythonx/UltiSnips/text.py | Python | unescape | unescape | 7 | 18 | 7 | 7 | 568dc186ee8458b373d3b04007f0b0d826a5dc8b | bigcode/the-stack | train |
07bcccbac547cbf9f6fa0729 | train | function | def head_tail(line):
"""Returns the first word in 'line' and the rest of 'line' or None if the
line is too short."""
generator = (t.strip() for t in line.split(None, 1))
head = next(generator).strip()
tail = ""
try:
tail = next(generator).strip()
except StopIteration:
pass
... | def head_tail(line):
| """Returns the first word in 'line' and the rest of 'line' or None if the
line is too short."""
generator = (t.strip() for t in line.split(None, 1))
head = next(generator).strip()
tail = ""
try:
tail = next(generator).strip()
except StopIteration:
pass
return head, tail
| (r"\n", "\n")
text = text.replace(r"\t", "\t")
text = text.replace(r"\r", "\r")
text = text.replace(r"\a", "\a")
text = text.replace(r"\b", "\b")
return text
def head_tail(line):
| 64 | 64 | 87 | 5 | 58 | khatchad/vimrc | sources_non_forked/ultisnips/pythonx/UltiSnips/text.py | Python | head_tail | head_tail | 41 | 51 | 41 | 41 | 7d57806509ba5d3e573a09eb673dcb7a619b9a53 | bigcode/the-stack | train |
01cf072bea48a0b397a8d6eb | train | class | class ArmControl:
'''Higher-level interface that exposes capabilities from
fetch_arm_control/Arm.py class as services.
'''
def __init__(self):
# Initialize arm state.
self._tf_listener = TransformListener()
self._arm = Arm(self._tf_listener)
self._arm.close_gripper()
... | class ArmControl:
| '''Higher-level interface that exposes capabilities from
fetch_arm_control/Arm.py class as services.
'''
def __init__(self):
# Initialize arm state.
self._tf_listener = TransformListener()
self._arm = Arm(self._tf_listener)
self._arm.close_gripper()
self._status... | bd_interaction.srv import MoveArm, MoveArmResponse, \
GetEEPose, GetEEPoseResponse, \
GetGripperState, \
GetGripperStateResponse, \
SetGripperState, \
... | 256 | 256 | 2,754 | 4 | 251 | fetchrobotics/fetch_pbd | fetch_pbd_interaction/src/fetch_pbd_interaction/arm_control.py | Python | ArmControl | ArmControl | 56 | 466 | 56 | 56 | fae87e364879cbd360d953b5149aceabd18cae89 | bigcode/the-stack | train |
c3709f34ecb9f6c5cdf2a4a8 | train | function | def report2dict(cr):
# Parse rows
tmp = list()
for row in cr.split("\n"):
parsed_row = [x for x in row.split(" ") if len(x) > 0]
if len(parsed_row) > 0:
tmp.append(parsed_row)
# Store in dictionary
measures = tmp[0]
D_class_data = defaultdict(dict)
for row in... | def report2dict(cr):
# Parse rows
| tmp = list()
for row in cr.split("\n"):
parsed_row = [x for x in row.split(" ") if len(x) > 0]
if len(parsed_row) > 0:
tmp.append(parsed_row)
# Store in dictionary
measures = tmp[0]
D_class_data = defaultdict(dict)
for row in tmp[1:]:
class_label = row[0]
... | import glob
import re
from sklearn.metrics import accuracy_score,recall_score,precision_score,f1_score
from sklearn.metrics import classification_report
from collections import defaultdict
from utils.helper_functions import separator
import os
import plotly.graph_objects as go
def report2dict(cr):
# Parse rows
| 64 | 64 | 168 | 11 | 52 | giulio93/anticipating-activities | Breakfast/Epic-paradigma II/evalIOU.py | Python | report2dict | report2dict | 14 | 35 | 14 | 15 | 09b7e5e576b67a4e3ee566477ba466221f2ef302 | bigcode/the-stack | train |
1d0801cbb583796f830d3152 | train | function | def read_sequences(filename, recog_dir, obs_percentage):
gt_file = args.ground_truth_path + re.sub('\.recog','.txt',re.sub('.*/','/',filename))
with open(gt_file, 'r') as f:
ground_truth = f.read().split('\n')[0:-1]
f.close()
# read recognized sequence
with open(filename, 'r') as f:
... | def read_sequences(filename, recog_dir, obs_percentage):
| gt_file = args.ground_truth_path + re.sub('\.recog','.txt',re.sub('.*/','/',filename))
with open(gt_file, 'r') as f:
ground_truth = f.read().split('\n')[0:-1]
f.close()
# read recognized sequence
with open(filename, 'r') as f:
recognized = f.read().split('\n')[1].split()
... | if len(parsed_row) > 0:
tmp.append(parsed_row)
# Store in dictionary
measures = tmp[0]
D_class_data = defaultdict(dict)
for row in tmp[1:]:
class_label = row[0]
for j, m in enumerate(measures):
if(class_label=='accuracy'):
D_class_data[class_label... | 131 | 131 | 439 | 11 | 119 | giulio93/anticipating-activities | Breakfast/Epic-paradigma II/evalIOU.py | Python | read_sequences | read_sequences | 37 | 66 | 37 | 38 | 60fe290ae81dc270aa9901e5e735209f54afb701 | bigcode/the-stack | train |
b99c335244124225659d3839 | train | class | class McDonaldsGTSpider(scrapy.Spider):
name = "mcdonalds_gt"
allowed_domains = ["mcdonalds.com.gt"]
def start_requests(self):
url = 'https://mcdonalds.com.gt/wp-admin/admin-ajax.php'
headers = {
'Accept-Language': 'en-US,en;q=0.9',
'Origin': 'https://mcdonalds.com.g... | class McDonaldsGTSpider(scrapy.Spider):
| name = "mcdonalds_gt"
allowed_domains = ["mcdonalds.com.gt"]
def start_requests(self):
url = 'https://mcdonalds.com.gt/wp-admin/admin-ajax.php'
headers = {
'Accept-Language': 'en-US,en;q=0.9',
'Origin': 'https://mcdonalds.com.gt',
'Accept-Encoding': 'gzip... | import json
import re
import scrapy
from locations.items import GeojsonPointItem
class McDonaldsGTSpider(scrapy.Spider):
| 28 | 122 | 409 | 10 | 17 | thismakessand/alltheplaces | locations/spiders/mcdonalds_gt.py | Python | McDonaldsGTSpider | McDonaldsGTSpider | 6 | 57 | 6 | 6 | 545bc4dab9af41fdf32de487e2ffca3ec36566c7 | bigcode/the-stack | train |
ae6869d3ff1b6d82f8d24110 | train | function | @pytest.mark.parametrize('script, result', [
('git rebase master', [
'git rebase --abort', 'git rebase --skip', 'git rebase --continue',
'rm -fr "/foo/bar/baz/egg/.git/rebase-merge"']),
('git rebase -skip', [
'git rebase --skip', 'git rebase --abort', 'git rebase --continue',
'rm... | @pytest.mark.parametrize('script, result', [
('git rebase master', [
'git rebase --abort', 'git rebase --skip', 'git rebase --continue',
'rm -fr "/foo/bar/baz/egg/.git/rebase-merge"']),
('git rebase -skip', [
'git rebase --skip', 'git rebase --abort', 'git rebase --continue',
'rm... | assert get_new_command(Command(script, output)) == result
| @pytest.mark.parametrize('script, result', [
('git rebase master', [
'git rebase --abort', 'git rebase --skip', 'git rebase --continue',
'rm -fr "/foo/bar/baz/egg/.git/rebase-merge"']),
('git rebase -skip', [
'git rebase --skip', 'git rebase --abort', 'git rebase --continue',
'rm... | 171 | 64 | 184 | 171 | 0 | benmonro/therandy | tests/rules/test_git_rebase_merge_dir.py | Python | test_get_new_command | test_get_new_command | 31 | 42 | 31 | 41 | d20401bf57d84ad8d0e107599d7c00a05d89a5a3 | bigcode/the-stack | train |
8bc2b5f61890484c68492ca1 | train | function | @pytest.mark.parametrize('script', [
'git rebase master',
'git rebase -skip',
'git rebase'])
def test_match(output, script):
assert match(Command(script, output))
| @pytest.mark.parametrize('script', [
'git rebase master',
'git rebase -skip',
'git rebase'])
def test_match(output, script):
| assert match(Command(script, output))
| "\n'
'and run me again. I am stopping in case you still have something\n'
'valuable there.\n')
@pytest.mark.parametrize('script', [
'git rebase master',
'git rebase -skip',
'git rebase'])
def test_match(output, script):
| 64 | 64 | 43 | 35 | 29 | benmonro/therandy | tests/rules/test_git_rebase_merge_dir.py | Python | test_match | test_match | 18 | 23 | 18 | 22 | 4921a849db45efe7025ec1c979625ca2b26f4d4a | bigcode/the-stack | train |
71e5a102a8fc5612e3333f61 | train | function | @pytest.fixture
def output():
return ('\n\nIt seems that there is already a rebase-merge directory, and\n'
'I wonder if you are in the middle of another rebase. If that is the\n'
'case, please try\n'
'\tgit rebase (--continue | --abort | --skip)\n'
'If that is not th... | @pytest.fixture
def output():
| return ('\n\nIt seems that there is already a rebase-merge directory, and\n'
'I wonder if you are in the middle of another rebase. If that is the\n'
'case, please try\n'
'\tgit rebase (--continue | --abort | --skip)\n'
'If that is not the case, please\n'
... | import pytest
from therandy.rules.git_rebase_merge_dir import match, get_new_command
from therandy.types import Command
@pytest.fixture
def output():
| 32 | 64 | 135 | 6 | 25 | benmonro/therandy | tests/rules/test_git_rebase_merge_dir.py | Python | output | output | 6 | 15 | 6 | 7 | 57def24a55858e22d3be89bc6acafb7461d288be | bigcode/the-stack | train |
d7e12e9cede7ef0b015672a7 | train | function | @pytest.mark.parametrize('script', ['git rebase master', 'git rebase -abort'])
def test_not_match(script):
assert not match(Command(script, ''))
| @pytest.mark.parametrize('script', ['git rebase master', 'git rebase -abort'])
def test_not_match(script):
| assert not match(Command(script, ''))
| script', [
'git rebase master',
'git rebase -skip',
'git rebase'])
def test_match(output, script):
assert match(Command(script, output))
@pytest.mark.parametrize('script', ['git rebase master', 'git rebase -abort'])
def test_not_match(script):
| 64 | 64 | 34 | 25 | 39 | benmonro/therandy | tests/rules/test_git_rebase_merge_dir.py | Python | test_not_match | test_not_match | 26 | 28 | 26 | 27 | 916bc6aa2821860eebad730f57cdb2ed7c59437b | bigcode/the-stack | train |
df467fdf3894e22d7db3bc65 | train | function | def get_option_ini(config, *names):
for name in names:
ret = config.getoption(name) # 'default' arg won't work as expected
if ret is None:
ret = config.getini(name)
if ret:
return ret
| def get_option_ini(config, *names):
| for name in names:
ret = config.getoption(name) # 'default' arg won't work as expected
if ret is None:
ret = config.getini(name)
if ret:
return ret
| once.
indentation = _remove_ansi_escape_sequences(formatted).find(lines[0])
lines[0] = formatted
return ("\n" + " " * indentation).join(lines)
else:
return self._fmt % record.__dict__
def get_option_ini(config, *names):
| 63 | 64 | 56 | 9 | 54 | grlee77/pytest | src/_pytest/logging.py | Python | get_option_ini | get_option_ini | 94 | 100 | 94 | 94 | e64b20bcf3c26972c866b239bef86af47817f102 | bigcode/the-stack | train |
f2d22c239e952af6cd0abac9 | train | class | class ColoredLevelFormatter(logging.Formatter):
"""
Colorize the %(levelname)..s part of the log format passed to __init__.
"""
LOGLEVEL_COLOROPTS = {
logging.CRITICAL: {"red"},
logging.ERROR: {"red", "bold"},
logging.WARNING: {"yellow"},
logging.WARN: {"yellow"},
... | class ColoredLevelFormatter(logging.Formatter):
| """
Colorize the %(levelname)..s part of the log format passed to __init__.
"""
LOGLEVEL_COLOROPTS = {
logging.CRITICAL: {"red"},
logging.ERROR: {"red", "bold"},
logging.WARNING: {"yellow"},
logging.WARN: {"yellow"},
logging.INFO: {"green"},
logging.DEBUG... | _pytest.compat import nullcontext
from _pytest.config import create_terminal_writer
from _pytest.pathlib import Path
DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
def _remove_ansi_escape_sequen... | 110 | 110 | 368 | 8 | 102 | grlee77/pytest | src/_pytest/logging.py | Python | ColoredLevelFormatter | ColoredLevelFormatter | 21 | 64 | 21 | 21 | 7c0cfdfd7b2101ed77959837931d713f69b2e614 | bigcode/the-stack | train |
d180cbfb65ba20d3ef8375c0 | train | class | class LogCaptureHandler(logging.StreamHandler):
"""A logging handler that stores log records and the log text."""
def __init__(self):
"""Creates a new log handler."""
logging.StreamHandler.__init__(self, StringIO())
self.records = []
def emit(self, record):
"""Keep the log ... | class LogCaptureHandler(logging.StreamHandler):
| """A logging handler that stores log records and the log text."""
def __init__(self):
"""Creates a new log handler."""
logging.StreamHandler.__init__(self, StringIO())
self.records = []
def emit(self, record):
"""Keep the log records in a list in addition to the log text.""... | orig_level = root_logger.level
root_logger.setLevel(min(orig_level, level))
try:
yield handler
finally:
if level is not None:
root_logger.setLevel(orig_level)
if add_new_handler:
root_logger.removeHandler(handler)
class LogCaptureHandler(logging.StreamHan... | 64 | 64 | 109 | 8 | 56 | grlee77/pytest | src/_pytest/logging.py | Python | LogCaptureHandler | LogCaptureHandler | 215 | 230 | 215 | 215 | efe465dfa1615a549696f48e07f75552475b9d07 | bigcode/the-stack | train |
375b0892db086f88b9eb853a | train | class | class _LiveLoggingStreamHandler(logging.StreamHandler):
"""
Custom StreamHandler used by the live logging feature: it will write a newline before the first log message
in each test.
During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured
and won't ... | class _LiveLoggingStreamHandler(logging.StreamHandler):
| """
Custom StreamHandler used by the live logging feature: it will write a newline before the first log message
in each test.
During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured
and won't appear in the terminal.
"""
def __init__(self, ... | if session.config.option.collectonly:
yield
return
if self._log_cli_enabled() and self._config.getoption("verbose") < 1:
# setting verbose flag is needed to avoid messy test progress output
self._config.option.verbose = 1
with self.live_logs_context():
... | 121 | 121 | 404 | 10 | 110 | grlee77/pytest | src/_pytest/logging.py | Python | _LiveLoggingStreamHandler | _LiveLoggingStreamHandler | 644 | 692 | 644 | 644 | 21a33c6cebd4d4739ddf30d207daec1ee75892c0 | bigcode/the-stack | train |
498cc9ef8600abc9fbaba0df | train | function | @pytest.fixture
def caplog(request):
"""Access and control log capturing.
Captured logs are available through the following properties/methods::
* caplog.messages -> list of format-interpolated log messages
* caplog.text -> string containing formatted log output
* caplog.records ... | @pytest.fixture
def caplog(request):
| """Access and control log capturing.
Captured logs are available through the following properties/methods::
* caplog.messages -> list of format-interpolated log messages
* caplog.text -> string containing formatted log output
* caplog.records -> list of logging.LogRecord ... | logger to update the level. If not given, the root logger level is updated.
"""
logger = logging.getLogger(logger)
orig_level = logger.level
logger.setLevel(level)
try:
yield
finally:
logger.setLevel(orig_level)
@pytest.fixture
def caplog(request)... | 64 | 64 | 132 | 8 | 56 | grlee77/pytest | src/_pytest/logging.py | Python | caplog | caplog | 352 | 366 | 352 | 353 | e96a377dc1d850e3ecd56ec7b35b6bbdceb68f3d | bigcode/the-stack | train |
34e0ab2bad3c3f08622784ef | train | function | @pytest.hookimpl(trylast=True)
def pytest_configure(config):
config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
| @pytest.hookimpl(trylast=True)
def pytest_configure(config):
| config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
| "'{}' is not recognized as a logging level name for "
"'{}'. Please consider passing the "
"logging level num instead.".format(log_level, setting_name)
)
# run after terminalreporter/capturemanager are configured
@pytest.hookimpl(trylast=True)
def pytest_configure(config):
| 64 | 64 | 29 | 15 | 48 | grlee77/pytest | src/_pytest/logging.py | Python | pytest_configure | pytest_configure | 395 | 397 | 395 | 396 | a838febc69979bd4af5b87fde4552777351db9a7 | bigcode/the-stack | train |
1a0eca653a1ed6b613849a48 | train | function | def pytest_addoption(parser):
"""Add options to control log capturing."""
group = parser.getgroup("logging")
def add_option_ini(option, dest, default=None, type=None, **kwargs):
parser.addini(
dest, default=default, type=type, help="default value for " + option
)
group.a... | def pytest_addoption(parser):
| """Add options to control log capturing."""
group = parser.getgroup("logging")
def add_option_ini(option, dest, default=None, type=None, **kwargs):
parser.addini(
dest, default=default, type=type, help="default value for " + option
)
group.addoption(option, dest=dest, **... | update_message(record.__dict__, lines[0])
# TODO optimize this by introducing an option that tells the
# logging framework that the indentation doesn't
# change. This allows to compute the indentation only once.
indentation = _remove_ansi_escape_sequences(formatted).find(... | 160 | 160 | 535 | 6 | 153 | grlee77/pytest | src/_pytest/logging.py | Python | pytest_addoption | pytest_addoption | 103 | 184 | 103 | 103 | 4a65963de519308a56710ef3702d76592570ac59 | bigcode/the-stack | train |
d6e5c4d2ab0863f6c3735b48 | train | class | class LogCaptureFixture:
"""Provides access and control of log capturing."""
def __init__(self, item):
"""Creates a new funcarg."""
self._item = item
# dict of log name -> log level
self._initial_log_levels = {} # Dict[str, int]
def _finalize(self):
"""Finalizes th... | class LogCaptureFixture:
| """Provides access and control of log capturing."""
def __init__(self, item):
"""Creates a new funcarg."""
self._item = item
# dict of log name -> log level
self._initial_log_levels = {} # Dict[str, int]
def _finalize(self):
"""Finalizes the fixture.
This ... | root_logger = logging.getLogger()
if formatter is not None:
handler.setFormatter(formatter)
if level is not None:
handler.setLevel(level)
# Adding the same handler twice would confuse logging system.
# Just don't do that.
add_new_handler = handler not in root_logger.handlers
... | 256 | 256 | 873 | 5 | 251 | grlee77/pytest | src/_pytest/logging.py | Python | LogCaptureFixture | LogCaptureFixture | 233 | 349 | 233 | 233 | b9a5accc122270d69285711ea27419c9564765f2 | bigcode/the-stack | train |
56c31e2578eef86476c98d81 | train | function | @contextmanager
def catching_logs(handler, formatter=None, level=None):
"""Context manager that prepares the whole logging machinery properly."""
root_logger = logging.getLogger()
if formatter is not None:
handler.setFormatter(formatter)
if level is not None:
handler.setLevel(level)
... | @contextmanager
def catching_logs(handler, formatter=None, level=None):
| """Context manager that prepares the whole logging machinery properly."""
root_logger = logging.getLogger()
if formatter is not None:
handler.setFormatter(formatter)
if level is not None:
handler.setLevel(level)
# Adding the same handler twice would confuse logging system.
# Ju... | the logging module.",
)
add_option_ini(
"--log-file-date-format",
dest="log_file_date_format",
default=DEFAULT_LOG_DATE_FORMAT,
help="log date format as used by the logging module.",
)
@contextmanager
def catching_logs(handler, formatter=None, level=None):
| 64 | 64 | 170 | 15 | 49 | grlee77/pytest | src/_pytest/logging.py | Python | catching_logs | catching_logs | 187 | 212 | 187 | 188 | 6341fb70699038d49b118c26410391bfc6a75898 | bigcode/the-stack | train |
7e3786161a6e025ebd95981b | train | class | class PercentStyleMultiline(logging.PercentStyle):
"""A logging style with special support for multiline messages.
If the message of a record consists of multiple lines, this style
formats the message as if each line were logged separately.
"""
@staticmethod
def _update_message(record_dict, me... | class PercentStyleMultiline(logging.PercentStyle):
| """A logging style with special support for multiline messages.
If the message of a record consists of multiple lines, this style
formats the message as if each line were logged separately.
"""
@staticmethod
def _update_message(record_dict, message):
tmp = record_dict.copy()
tm... | colorized_formatted_levelname, self._fmt
)
def format(self, record):
fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
self._style._fmt = fmt
return super().format(record)
class PercentStyleMultiline(logging.PercentStyle):
| 64 | 64 | 213 | 9 | 55 | grlee77/pytest | src/_pytest/logging.py | Python | PercentStyleMultiline | PercentStyleMultiline | 67 | 91 | 67 | 67 | eb8ca5a40dda5626579ad5a01123a0172b193e20 | bigcode/the-stack | train |
b057e777e51230bb1969a45e | train | function | def _remove_ansi_escape_sequences(text):
return _ANSI_ESCAPE_SEQ.sub("", text)
| def _remove_ansi_escape_sequences(text):
| return _ANSI_ESCAPE_SEQ.sub("", text)
| "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
def _remove_ansi_escape_sequences(text):
| 64 | 64 | 19 | 9 | 55 | grlee77/pytest | src/_pytest/logging.py | Python | _remove_ansi_escape_sequences | _remove_ansi_escape_sequences | 17 | 18 | 17 | 17 | 630a3d65e340c328a4a196346bf7e78be82f0619 | bigcode/the-stack | train |
16c093778b797b3492fd4e33 | train | class | class LoggingPlugin:
"""Attaches to the logging module and captures log messages for each test.
"""
def __init__(self, config):
"""Creates a new plugin to capture log messages.
The formatter can be safely shared across all handlers so
create a single one for the entire test session... | class LoggingPlugin:
| """Attaches to the logging module and captures log messages for each test.
"""
def __init__(self, config):
"""Creates a new plugin to capture log messages.
The formatter can be safely shared across all handlers so
create a single one for the entire test session here.
"""
... | (logger_name, level, message) tuples
* caplog.clear() -> clear captured records and formatted log output string
"""
result = LogCaptureFixture(request.node)
yield result
result._finalize()
def get_actual_log_level(config, *setting_names):
"""Return the actual logging level."""
fo... | 256 | 256 | 1,837 | 4 | 252 | grlee77/pytest | src/_pytest/logging.py | Python | LoggingPlugin | LoggingPlugin | 400 | 641 | 400 | 400 | 5df3770df1518f7962064e537486e458732ff6a8 | bigcode/the-stack | train |
633a75295793a9c6d7b67372 | train | function | def get_actual_log_level(config, *setting_names):
"""Return the actual logging level."""
for setting_name in setting_names:
log_level = config.getoption(setting_name)
if log_level is None:
log_level = config.getini(setting_name)
if log_level:
break
else:
... | def get_actual_log_level(config, *setting_names):
| """Return the actual logging level."""
for setting_name in setting_names:
log_level = config.getoption(setting_name)
if log_level is None:
log_level = config.getini(setting_name)
if log_level:
break
else:
return
if isinstance(log_level, str):
... | uples -> list of (logger_name, level, message) tuples
* caplog.clear() -> clear captured records and formatted log output string
"""
result = LogCaptureFixture(request.node)
yield result
result._finalize()
def get_actual_log_level(config, *setting_names):
| 64 | 64 | 163 | 11 | 53 | grlee77/pytest | src/_pytest/logging.py | Python | get_actual_log_level | get_actual_log_level | 369 | 391 | 369 | 369 | 3be0314d6d9fcab14943c19ccd0fe876f8767c8e | bigcode/the-stack | train |
d23807eca92613ef6e05fc81 | train | class | class EventStatus:
"""Stores the current status of all events.
"""
login = None
register = None
join_room = None
leave_room = None
create_room = None
send_msg = None
get_room_msgs = None
get_invite_code = None
get_room_members = None
get_joined_rooms = None
@classm... | class EventStatus:
| """Stores the current status of all events.
"""
login = None
register = None
join_room = None
leave_room = None
create_room = None
send_msg = None
get_room_msgs = None
get_invite_code = None
get_room_members = None
get_joined_rooms = None
@classmethod
def get_s... | cls.all[msg['room']['id']] = {msg_id: msg}
@classmethod
def clear(cls) -> None:
"""Clears :code:`cls.all` and :code:`cls.__new`.
"""
cls.all = dict()
cls.__new = dict()
class EventStatus:
| 64 | 64 | 177 | 4 | 60 | Den4200/pyfrost | frost/client/events/events.py | Python | EventStatus | EventStatus | 55 | 83 | 55 | 55 | 403ef85d65f170394086de1dc8420ba925b49464 | bigcode/the-stack | train |
137124c3b6b6fd986099b2f5 | train | class | class Messages:
"""All messages will be stored in this class.
"""
all = dict()
"""All messages stored.
"""
__new = dict()
"""New, unread messages.
"""
@classmethod
def get_new_msgs(cls) -> Dict[int, Dict[str, Dict[str, Union[str, Dict[str, str]]]]]:
"""Returns new, unrea... | class Messages:
| """All messages will be stored in this class.
"""
all = dict()
"""All messages stored.
"""
__new = dict()
"""New, unread messages.
"""
@classmethod
def get_new_msgs(cls) -> Dict[int, Dict[str, Dict[str, Union[str, Dict[str, str]]]]]:
"""Returns new, unread messages.
... | from typing import Dict, Optional, Union
class Messages:
| 12 | 112 | 374 | 3 | 8 | Den4200/pyfrost | frost/client/events/events.py | Python | Messages | Messages | 4 | 52 | 4 | 4 | 3f4b5fff95d53cb15b826cfc0e3f0d41d9826358 | bigcode/the-stack | train |
bd5f3cef0ebeea1fa697829b | train | function | @click.command()
@verbose_option
def main():
"""Upload the Bioregistry KG to NDEx."""
upload()
click.echo(f"Uploaded to NDEx. See: https://bioregistry.io/ndex:{NDEX_UUID}")
| @click.command()
@verbose_option
def main():
| """Upload the Bioregistry KG to NDEx."""
upload()
click.echo(f"Uploaded to NDEx. See: https://bioregistry.io/ndex:{NDEX_UUID}")
|
import bioregistry
import bioregistry.version
if TYPE_CHECKING:
import ndex2
NDEX_UUID = "aa78a43f-9c4d-11eb-9e72-0ac135e8bacf"
@click.command()
@verbose_option
def main():
| 64 | 64 | 51 | 10 | 54 | Adafede/bioregistry | src/bioregistry/upload_ndex.py | Python | main | main | 20 | 25 | 20 | 22 | ba3a347a01dcec1367d56cd848145aca66914bef | bigcode/the-stack | train |
1f615e334671fa04cbe5e46f | train | function | def upload():
"""Generate a CX graph and upload to NDEx."""
from ndex2 import NiceCXBuilder
cx = NiceCXBuilder()
cx.set_name("Bioregistry")
cx.add_network_attribute(
"description",
"An integrative meta-registry of biological databases, ontologies, and nomenclatures",
)
cx.ad... | def upload():
| """Generate a CX graph and upload to NDEx."""
from ndex2 import NiceCXBuilder
cx = NiceCXBuilder()
cx.set_name("Bioregistry")
cx.add_network_attribute(
"description",
"An integrative meta-registry of biological databases, ontologies, and nomenclatures",
)
cx.add_network_attr... | # -*- coding: utf-8 -*-
"""Generate a small knowledge graph relating entities."""
from typing import TYPE_CHECKING
import click
import pystow
from more_click import verbose_option
import bioregistry
import bioregistry.version
if TYPE_CHECKING:
import ndex2
NDEX_UUID = "aa78a43f-9c4d-11eb-9e72-0ac135e8bacf"
... | 145 | 186 | 622 | 3 | 142 | Adafede/bioregistry | src/bioregistry/upload_ndex.py | Python | upload | upload | 28 | 108 | 28 | 28 | 944469fbdbc5f8007b9470f65b4001ef0649b910 | bigcode/the-stack | train |
bf185cc5f8712e68c05ba585 | train | function | def make_resource_node(cx: "ndex2.NiceCXBuilder", prefix: str) -> int:
"""Generate a CX node for a resource."""
node = cx.add_node(
name=bioregistry.get_name(prefix),
represents=f"bioregistry:{prefix}",
)
homepage = bioregistry.get_homepage(prefix)
if homepage:
cx.add_node_at... | def make_resource_node(cx: "ndex2.NiceCXBuilder", prefix: str) -> int:
| """Generate a CX node for a resource."""
node = cx.add_node(
name=bioregistry.get_name(prefix),
represents=f"bioregistry:{prefix}",
)
homepage = bioregistry.get_homepage(prefix)
if homepage:
cx.add_node_attribute(node, "homepage", homepage)
description = bioregistry.get_d... | _attribute(node, "homepage", homepage)
description = bioregistry.get_registry_description(metaprefix)
if description:
cx.add_node_attribute(node, "description", description)
return node
def make_resource_node(cx: "ndex2.NiceCXBuilder", prefix: str) -> int:
| 64 | 64 | 150 | 22 | 41 | Adafede/bioregistry | src/bioregistry/upload_ndex.py | Python | make_resource_node | make_resource_node | 126 | 142 | 126 | 126 | 5b024512baa8d19b953601ffe566661308b7921e | bigcode/the-stack | train |
fcff6ad966ca542fdf6c5f29 | train | function | def make_registry_node(cx: "ndex2.NiceCXBuilder", metaprefix: str) -> int:
"""Generate a CX node for a registry."""
node = cx.add_node(
name=bioregistry.get_registry_name(metaprefix),
represents=f"bioregistry.registry:{metaprefix}",
)
homepage = bioregistry.get_registry_homepage(metapref... | def make_registry_node(cx: "ndex2.NiceCXBuilder", metaprefix: str) -> int:
| """Generate a CX node for a registry."""
node = cx.add_node(
name=bioregistry.get_registry_name(metaprefix),
represents=f"bioregistry.registry:{metaprefix}",
)
homepage = bioregistry.get_registry_homepage(metaprefix)
if homepage:
cx.add_node_attribute(node, "homepage", homepa... | server="http://public.ndexbio.org",
username=pystow.get_config("ndex", "username"),
password=pystow.get_config("ndex", "password"),
)
def make_registry_node(cx: "ndex2.NiceCXBuilder", metaprefix: str) -> int:
| 64 | 64 | 135 | 24 | 40 | Adafede/bioregistry | src/bioregistry/upload_ndex.py | Python | make_registry_node | make_registry_node | 111 | 123 | 111 | 111 | 3aeff9ab3fa8b7333e71296adcde4009f7032be7 | bigcode/the-stack | train |
b93ec2f6ba133b084efdeb30 | train | class | class Scraper(CrawlSpider):
name = 'IT Strategy'
allowed_domains = ['sara-sabr.github.io']
rules = (
# To-do doesnt parse presentations well atm, should be able to remove the ending '\.html$' part of the regex
Rule(LinkExtractor(allow=r'.*\/ITStrategy\/.*\.html$'),
callback='p... | class Scraper(CrawlSpider):
| name = 'IT Strategy'
allowed_domains = ['sara-sabr.github.io']
rules = (
# To-do doesnt parse presentations well atm, should be able to remove the ending '\.html$' part of the regex
Rule(LinkExtractor(allow=r'.*\/ITStrategy\/.*\.html$'),
callback='parse_item', follow=True),
... | import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from bs4 import BeautifulSoup
import logging
import settings
import time
class Scraper(CrawlSpider):
| 45 | 90 | 302 | 7 | 37 | jaysonmc/contradiction-crawler | project/scraper.py | Python | Scraper | Scraper | 10 | 47 | 10 | 11 | 64f8bfbd3dcbe5c217617ddefd846bee169c33a2 | bigcode/the-stack | train |
4612d499145e4b3b8aea8790 | train | function | def setOutput(out):
global output
output = out
genetic.setOutput(out)
| def setOutput(out):
| global output
output = out
genetic.setOutput(out)
| import genetic
import sys
output = sys.stdout
def setOutput(out):
| 16 | 64 | 20 | 5 | 10 | JoshuaBrockschmidt/ideal_ANN | simulate.py | Python | setOutput | setOutput | 6 | 9 | 6 | 6 | b8ac781c810dacd72fee098f92b7179b4e8e5f23 | bigcode/the-stack | train |
8638b43d66c8944c3c4ab97c | train | function | def simulate():
sim = genetic.Simulation(2, 1, testData, 200)
sim.simulate(30)
| def simulate():
| sim = genetic.Simulation(2, 1, testData, 200)
sim.simulate(30)
| 1, 0.1, 0.9),
(0.1, 0.9, 0.9),
(0.9, 0.1, 0.9),
(0.9, 0.9, 0.1)
)
def simulate():
| 64 | 64 | 28 | 3 | 61 | JoshuaBrockschmidt/ideal_ANN | simulate.py | Python | simulate | simulate | 19 | 21 | 19 | 19 | f461b8293772b47d3ceccbd1df2166f10e4a99bb | bigcode/the-stack | train |
0ba929a114616515ed03d3d0 | train | function | def handler(event, context):
# Load the environment variables
load_dotenv()
# Configure log level
logger.setLevel(os.getenv("HULL_LOG_LEVEL", logging.ERROR))
# Log invocation
logger.info("Hull extract processor invoked with event: %s", event)
# Parse the environment variables
logger.info... | def handler(event, context):
# Load the environment variables
| load_dotenv()
# Configure log level
logger.setLevel(os.getenv("HULL_LOG_LEVEL", logging.ERROR))
# Log invocation
logger.info("Hull extract processor invoked with event: %s", event)
# Parse the environment variables
logger.info("Parsing configuration from environment variables...")
S3_BU... | import os
import json
import csv
import requests
import boto3
import botocore
from botocore.exceptions import ClientError
from datetime import datetime, timezone
import uuid
from dotenv import load_dotenv
import logging
logger = logging.getLogger()
def __create_env_error_response(var_name: str):
message = "Lambda... | 192 | 256 | 2,005 | 13 | 178 | SMK1085/drops-hull-extract-s3 | src/extract_processor/extract_processor.py | Python | handler | handler | 32 | 220 | 32 | 33 | 12357403c8be7779e99006ae4fced61050eed413 | bigcode/the-stack | train |
41221d06b6d40a35fe58a5a4 | train | function | def __compose_segment_names(segments, segment_ids):
seg_names = []
for sid in segment_ids:
segment = next(seg for seg in segments if seg['id'] == sid)
if segment:
seg_names.append(segment['name'])
return seg_names
| def __compose_segment_names(segments, segment_ids):
| seg_names = []
for sid in segment_ids:
segment = next(seg for seg in segments if seg['id'] == sid)
if segment:
seg_names.append(segment['name'])
return seg_names
| = "Lambda function not properly configured. Missing environment variable '{0:s}'."
logger.error(message.format(var_name))
response = {
'statusCode': 500,
'body': json.dumps(message.format(var_name))
}
return response
def __compose_segment_names(segments, segment_ids):
| 64 | 64 | 57 | 11 | 52 | SMK1085/drops-hull-extract-s3 | src/extract_processor/extract_processor.py | Python | __compose_segment_names | __compose_segment_names | 24 | 30 | 24 | 24 | 9304da5f5cb40c4f9df50059e1354aa998895c1a | bigcode/the-stack | train |
2ba4f9ab46bc5bbabfd07aff | train | function | def __create_env_error_response(var_name: str):
message = "Lambda function not properly configured. Missing environment variable '{0:s}'."
logger.error(message.format(var_name))
response = {
'statusCode': 500,
'body': json.dumps(message.format(var_name))
}
return response
| def __create_env_error_response(var_name: str):
| message = "Lambda function not properly configured. Missing environment variable '{0:s}'."
logger.error(message.format(var_name))
response = {
'statusCode': 500,
'body': json.dumps(message.format(var_name))
}
return response
| import json
import csv
import requests
import boto3
import botocore
from botocore.exceptions import ClientError
from datetime import datetime, timezone
import uuid
from dotenv import load_dotenv
import logging
logger = logging.getLogger()
def __create_env_error_response(var_name: str):
| 64 | 64 | 66 | 11 | 53 | SMK1085/drops-hull-extract-s3 | src/extract_processor/extract_processor.py | Python | __create_env_error_response | __create_env_error_response | 15 | 22 | 15 | 15 | 21003cf5f017a4d6d5f601b41bbc434185d2e29a | bigcode/the-stack | train |
15a1166400fe0ff029cbf713 | train | function | @pytest.mark.version('>=3.0.7,<4')
def test_1(act_1: Action):
act_1.expected_stderr = expected_stderr_1
act_1.execute()
assert act_1.clean_stderr == act_1.clean_expected_stderr
| @pytest.mark.version('>=3.0.7,<4')
def test_1(act_1: Action):
| act_1.expected_stderr = expected_stderr_1
act_1.execute()
assert act_1.clean_stderr == act_1.clean_expected_stderr
| 35, command: create or alter user u01 tags (password = 'foo');
# Does not generate:
#Statement failed, SQLSTATE = HY000
#Password must be specified when creating user
@pytest.mark.version('>=3.0.7,<4')
def test_1(act_1: Action):
| 64 | 64 | 60 | 23 | 40 | FirebirdSQL/firebird-qa | tests/bugs/core_4841_test.py | Python | test_1 | test_1 | 79 | 83 | 79 | 80 | 51f219fddb2dc2f21f375fe65756f1c958c4744f | bigcode/the-stack | train |
0d21eee83c2fd9be1a7ca403 | train | function | @pytest.mark.version('>=4.0')
def test_1(act_2: Action):
act_2.expected_stderr = expected_stderr_2
act_2.execute()
assert act_2.clean_stderr == act_2.clean_expected_stderr
| @pytest.mark.version('>=4.0')
def test_1(act_2: Action):
| act_2.expected_stderr = expected_stderr_2
act_2.execute()
assert act_2.clean_stderr == act_2.clean_expected_stderr
| STATE = HY000
Password must be specified when creating user
Statement failed, SQLSTATE = 42000
unsuccessful metadata update
-CREATE USER PASSWORD failed
-Password must be specified when creating user
"""
@pytest.mark.version('>=4.0')
def test_1(act_2: Action):
| 64 | 64 | 56 | 19 | 45 | FirebirdSQL/firebird-qa | tests/bugs/core_4841_test.py | Python | test_1 | test_1 | 133 | 137 | 133 | 134 | 4bbabf2bbb757bf46ba4d33dd2b6b1ad6c2b9360 | bigcode/the-stack | train |
f1c0079e3217360d8b1343a3 | train | class | class DistributedPartyManagerUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory("DistributedPartyManagerUD")
def announceGenerate(self):
DistributedObjectUD.announceGenerate(self)
self.sendUpdate('partyManagerUdStartingUp') # Shouldn't have to send to anyone special,... | class DistributedPartyManagerUD(DistributedObjectUD):
| notify = DirectNotifyGlobal.directNotify.newCategory("DistributedPartyManagerUD")
def announceGenerate(self):
DistributedObjectUD.announceGenerate(self)
self.sendUpdate('partyManagerUdStartingUp') # Shouldn't have to send to anyone special, as the field is airecv
def addParty(self, todo0,... | from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class DistributedPartyManagerUD(DistributedObjectUD):
| 32 | 256 | 947 | 10 | 21 | philicheese2003/ToontownProjectAltisServer | toontown/uberdog/DistributedPartyManagerUD.py | Python | DistributedPartyManagerUD | DistributedPartyManagerUD | 4 | 130 | 4 | 4 | aba47654b02b5cb294864dcd5a806da2f0596073 | bigcode/the-stack | train |
740cbabc3b53c3e3b490542b | train | class | class TestMisc:
@pytest.mark.asyncio
async def test_format_bytes(self):
assert format_bytes(None) == "Invalid"
assert format_bytes(dict()) == "Invalid"
assert format_bytes("some bytes") == "Invalid"
assert format_bytes(-1024) == "Invalid"
assert format_bytes(0) == "0.000 ... | class TestMisc:
@pytest.mark.asyncio
| async def test_format_bytes(self):
assert format_bytes(None) == "Invalid"
assert format_bytes(dict()) == "Invalid"
assert format_bytes("some bytes") == "Invalid"
assert format_bytes(-1024) == "Invalid"
assert format_bytes(0) == "0.000 MiB"
assert format_bytes(1024) ==... | import pytest
from hddcoin.util.misc import format_bytes
from hddcoin.util.misc import format_minutes
class TestMisc:
@pytest.mark.asyncio
| 34 | 193 | 645 | 11 | 22 | JakubSido/hddcoin-blockchain | tests/util/misc.py | Python | TestMisc | TestMisc | 6 | 52 | 6 | 7 | e55f6839fa5d0403654ce0043aa7403678654364 | bigcode/the-stack | train |
4b90a725b37b67a92dad9410 | train | function | def total_characters(word_list):
"""
Counts the total number of characters in a word list. Accepts a word list where each element
is a word. Throws an Exception whenever an invalid parameter is used.
:param word_list: string word list
:return: total number of characters
:raises: TypeError
:r... | def total_characters(word_list):
| """
Counts the total number of characters in a word list. Accepts a word list where each element
is a word. Throws an Exception whenever an invalid parameter is used.
:param word_list: string word list
:return: total number of characters
:raises: TypeError
:rtype: int
"""
# check for... | try:
from functools import reduce
except ImportError:
print("No Module named reduce")
def total_characters(word_list):
| 27 | 64 | 191 | 7 | 20 | JASTYN/pythonmaster | pystrings/character_counter/__init__.py | Python | total_characters | total_characters | 7 | 29 | 7 | 7 | 2d7b7f21bdbab16d2fa106cbe212bccd9d3f87f9 | bigcode/the-stack | train |
1d6a9e063086a34617b41148 | train | class | class XSHGExchangeCalendar(PrecomputedTradingCalendar):
"""
Exchange calendar for the Shanghai Stock Exchange (XSHG, XSSC, SSE).
Open time: 9:30 Asia/Shanghai
Close time: 15:00 Asia/Shanghai
NOTE: For now, we are skipping the intra-day break from 11:30 to 13:00.
Due to the complexity around t... | class XSHGExchangeCalendar(PrecomputedTradingCalendar):
| """
Exchange calendar for the Shanghai Stock Exchange (XSHG, XSSC, SSE).
Open time: 9:30 Asia/Shanghai
Close time: 15:00 Asia/Shanghai
NOTE: For now, we are skipping the intra-day break from 11:30 to 13:00.
Due to the complexity around the Shanghai exchange holidays, we are
hardcoding a l... | 5-04-04",
"2025-05-01",
"2025-10-01",
"2025-10-02",
"2025-10-03",
"2025-10-04",
])
class XSHGExchangeCalendar(PrecomputedTradingCalendar):
| 64 | 64 | 199 | 12 | 52 | txu2014/trading_calendars | trading_calendars/exchange_calendar_xshg.py | Python | XSHGExchangeCalendar | XSHGExchangeCalendar | 470 | 495 | 470 | 470 | 6daeef56af0cfda3fec08369c89a11843cf510c2 | bigcode/the-stack | train |
44bdbc294a9949a2afa83a1c | train | class | class ResourceQueryStr(str):
"""
Extends default string with additional formatting capabilities.
"""
formatter = ResourceQueryFormatter()
def format(self, *args, **kwargs):
return self.formatter.format(self, *args, **kwargs)
| class ResourceQueryStr(str):
| """
Extends default string with additional formatting capabilities.
"""
formatter = ResourceQueryFormatter()
def format(self, *args, **kwargs):
return self.formatter.format(self, *args, **kwargs)
| item in kwargs:
self.used_kwargs[item] = kwargs.pop(item)
self.unused_kwargs = kwargs
def format_field(self, value, format_spec):
return quote(super(ResourceQueryFormatter, self).format_field(value, format_spec).encode('utf-8'))
class ResourceQueryStr(str):
| 63 | 64 | 52 | 6 | 57 | nagesh4193/python-redmine | redminelib/utilities.py | Python | ResourceQueryStr | ResourceQueryStr | 92 | 99 | 92 | 92 | c4f58228880668d9c5e70b8997f7e642b8788013 | bigcode/the-stack | train |
49ba6f96423cd4eb116e4f22 | train | class | class ResourceQueryFormatter(string.Formatter):
"""
Quotes query and memorizes all arguments, used during string formatting.
"""
def __init__(self):
self.used_kwargs = {}
self.unused_kwargs = {}
def check_unused_args(self, used_args, args, kwargs):
for item in used_args:
... | class ResourceQueryFormatter(string.Formatter):
| """
Quotes query and memorizes all arguments, used during string formatting.
"""
def __init__(self):
self.used_kwargs = {}
self.unused_kwargs = {}
def check_unused_args(self, used_args, args, kwargs):
for item in used_args:
if item in kwargs:
self... | ).
"""
result = copy.deepcopy(a)
for key, value in b.items():
if isinstance(value, dict):
result[key] = merge_dicts(value, a.get(key, {}))
else:
result[key] = value
return result
class ResourceQueryFormatter(string.Formatter):
| 64 | 64 | 126 | 8 | 55 | nagesh4193/python-redmine | redminelib/utilities.py | Python | ResourceQueryFormatter | ResourceQueryFormatter | 73 | 89 | 73 | 73 | 7541349fca1ccf9ec327f5e8f8257f6a684201d2 | bigcode/the-stack | train |
6938668392cb69cd94ece710 | train | function | def fix_unicode(cls):
"""
A class decorator that defines __unicode__, makes __str__ and __repr__
return a utf-8 encoded string and encodes unicode exception messages
to utf-8 encoded strings under Python 2. Does nothing under Python 3.
:param class cls: (required). A class where unicode should be f... | def fix_unicode(cls):
| """
A class decorator that defines __unicode__, makes __str__ and __repr__
return a utf-8 encoded string and encodes unicode exception messages
to utf-8 encoded strings under Python 2. Does nothing under Python 3.
:param class cls: (required). A class where unicode should be fixed.
"""
if s... | """
Provides helper utilities.
"""
import sys
import copy
import string
import functools
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
def fix_unicode(cls):
| 42 | 72 | 243 | 5 | 36 | nagesh4193/python-redmine | redminelib/utilities.py | Python | fix_unicode | fix_unicode | 16 | 42 | 16 | 16 | 8bea11891ed247517c481d908170c82282826ead | bigcode/the-stack | train |
eed723beae4c2072f79f0b41 | train | function | def with_metaclass(meta, *bases):
"""
Create a base class with a metaclass.
"""
class MetaClass(meta):
def __new__(cls, name, this_bases, dct):
return meta(name, bases, dct)
return type.__new__(MetaClass, 'temporary_class', (), {})
| def with_metaclass(meta, *bases):
| """
Create a base class with a metaclass.
"""
class MetaClass(meta):
def __new__(cls, name, this_bases, dct):
return meta(name, bases, dct)
return type.__new__(MetaClass, 'temporary_class', (), {})
| (cls, Exception):
cls.__init__ = decorator(cls.__init__)
return cls
cls.__unicode__ = cls.__str__
cls.__str__ = decorator(cls.__unicode__)
cls.__repr__ = decorator(cls.__repr__)
return cls
def with_metaclass(meta, *bases):
| 64 | 64 | 70 | 9 | 54 | nagesh4193/python-redmine | redminelib/utilities.py | Python | with_metaclass | with_metaclass | 45 | 52 | 45 | 45 | 7b9aade0f246488881e61fa66422f6c776a34039 | bigcode/the-stack | train |
9dbea1d4302a3d1115d8c962 | train | function | def merge_dicts(a, b):
"""
Merges dicts a and b recursively into a new dict.
:param dict a: (required).
:param dict b: (required).
"""
result = copy.deepcopy(a)
for key, value in b.items():
if isinstance(value, dict):
result[key] = merge_dicts(value, a.get(key, {}))
... | def merge_dicts(a, b):
| """
Merges dicts a and b recursively into a new dict.
:param dict a: (required).
:param dict b: (required).
"""
result = copy.deepcopy(a)
for key, value in b.items():
if isinstance(value, dict):
result[key] = merge_dicts(value, a.get(key, {}))
else:
... | class with a metaclass.
"""
class MetaClass(meta):
def __new__(cls, name, this_bases, dct):
return meta(name, bases, dct)
return type.__new__(MetaClass, 'temporary_class', (), {})
def merge_dicts(a, b):
| 63 | 64 | 97 | 8 | 55 | nagesh4193/python-redmine | redminelib/utilities.py | Python | merge_dicts | merge_dicts | 55 | 70 | 55 | 55 | 5569d117a7decaebbc2e7e21f61bbe9a25132807 | bigcode/the-stack | train |
3be05e0df1f097a523f49a5a | train | function | def null_collate(batch):
batch_size = len(batch)
input = []
truth_mask = []
truth_label = []
infor = []
for b in range(batch_size):
input.append(batch[b][0])
truth_mask.append(batch[b][1])
infor.append(batch[b][2])
input = np.stack(input)
input = image_to_input... | def null_collate(batch):
| batch_size = len(batch)
input = []
truth_mask = []
truth_label = []
infor = []
for b in range(batch_size):
input.append(batch[b][0])
truth_mask.append(batch[b][1])
infor.append(batch[b][2])
input = np.stack(input)
input = image_to_input(input, IMAGE_RGB_MEAN,IM... | _flip_lr(image, mask)
if np.random.rand()>0.5:
image, mask = do_flip_ud(image, mask)
if np.random.rand()>0.5:
image, mask = do_noise(image, mask)
return image, mask, infor
def null_collate(batch):
| 64 | 64 | 176 | 6 | 57 | evilidol/kaggle-Steel-Defect-Detection | resnet34_unet256_softmax_01/train_b0.py | Python | null_collate | null_collate | 34 | 59 | 34 | 34 | c255123fa29df49867f6df5618da18fca85f4e5c | bigcode/the-stack | train |
6222b35c3cb19c5e90feb2c3 | train | function | def run_train():
out_dir = \
'/root/share/project/kaggle/2019/steel/result2/resnet34-unet256-foldb0-0'
initial_checkpoint = \
None #'/root/share/project/kaggle/2019/steel/result1/resnet34-cam-att-cls-2b-foldb0-0/checkpoint/00048000_model.pth'
sampler = FourBalanceClassSampler #RandomS... | def run_train():
| out_dir = \
'/root/share/project/kaggle/2019/steel/result2/resnet34-unet256-foldb0-0'
initial_checkpoint = \
None #'/root/share/project/kaggle/2019/steel/result1/resnet34-cam-att-cls-2b-foldb0-0/checkpoint/00048000_model.pth'
sampler = FourBalanceClassSampler #RandomSampler #FourBalan... | numpy()
truth_attention = truth_attention.data.cpu().numpy()
probability_attention = probability_attention.data.cpu().numpy()
for b in range(0, batch_size, 4):
image_id = infor[b].image_id[:-4]
result = draw_predict_result_attention(
... | 256 | 256 | 2,585 | 4 | 251 | evilidol/kaggle-Steel-Defect-Detection | resnet34_unet256_softmax_01/train_b0.py | Python | run_train | run_train | 134 | 409 | 134 | 134 | a217a7a84cf4c4a267842a6d2b04c7e7ae9c0cba | bigcode/the-stack | train |
3a3a306e5e3b483b52866fad | train | function | def valid_augment(image, mask, infor):
return image, mask, infor
| def valid_augment(image, mask, infor):
| return image, mask, infor
| import os
os.environ['CUDA_VISIBLE_DEVICES']='0'
from common import *
from dataset import *
from model import *
def valid_augment(image, mask, infor):
| 38 | 64 | 20 | 11 | 27 | evilidol/kaggle-Steel-Defect-Detection | resnet34_unet256_softmax_01/train_b0.py | Python | valid_augment | valid_augment | 9 | 10 | 9 | 9 | 13e692e13f35cebbc1f7912d4a25db8b8645f262 | bigcode/the-stack | train |
c544b685750941fa9f962de9 | train | function | def do_valid(net, valid_loader, out_dir=None):
#out_dir=None
valid_num = np.zeros(11, np.float32)
valid_loss = np.zeros(11, np.float32)
for t, (input, truth_mask, truth_label, infor) in enumerate(valid_loader):
#if b==5: break
net.eval()
input = input.cuda()
truth_mask... | def do_valid(net, valid_loader, out_dir=None):
#out_dir=None
| valid_num = np.zeros(11, np.float32)
valid_loss = np.zeros(11, np.float32)
for t, (input, truth_mask, truth_label, infor) in enumerate(valid_loader):
#if b==5: break
net.eval()
input = input.cuda()
truth_mask = truth_mask.cuda()
truth_label = truth_label.cuda()
... | []
truth_mask = []
truth_label = []
infor = []
for b in range(batch_size):
input.append(batch[b][0])
truth_mask.append(batch[b][1])
infor.append(batch[b][2])
input = np.stack(input)
input = image_to_input(input, IMAGE_RGB_MEAN,IMAGE_RGB_STD)
input = torch.from_nump... | 181 | 182 | 608 | 18 | 163 | evilidol/kaggle-Steel-Defect-Detection | resnet34_unet256_softmax_01/train_b0.py | Python | do_valid | do_valid | 64 | 128 | 64 | 65 | ba6cb8c8d11cfd469d97549c806035fa56d553a2 | bigcode/the-stack | train |
9dc93b502cd6ea5f1a17de97 | train | function | def train_augment(image, mask, infor):
u=np.random.choice(3)
if u==0:
pass
elif u==1:
image, mask = do_random_crop_rescale(image, mask, 1600-(256-224), 224)
elif u==2:
image, mask = do_random_crop_rotate_rescale(image, mask, 1600-(256-224), 224)
if np.random.rand()>0.5:
... | def train_augment(image, mask, infor):
| u=np.random.choice(3)
if u==0:
pass
elif u==1:
image, mask = do_random_crop_rescale(image, mask, 1600-(256-224), 224)
elif u==2:
image, mask = do_random_crop_rotate_rescale(image, mask, 1600-(256-224), 224)
if np.random.rand()>0.5:
image = do_random_log_contast(ima... | import os
os.environ['CUDA_VISIBLE_DEVICES']='0'
from common import *
from dataset import *
from model import *
def valid_augment(image, mask, infor):
return image, mask, infor
def train_augment(image, mask, infor):
| 58 | 64 | 186 | 11 | 46 | evilidol/kaggle-Steel-Defect-Detection | resnet34_unet256_softmax_01/train_b0.py | Python | train_augment | train_augment | 12 | 31 | 12 | 13 | 5e8a2398ff8ae8a0ecb07c355ec1c2d613ff73e0 | bigcode/the-stack | train |
6c702768046dabbf268e4978 | train | class | class PythonOrgSearchTest1(unittest.TestCase):
def setUp(self):
print("In setUp")
caps = {'browserName': 'firefox'}
self.browser = webdriver.Remote(
command_executor='http://hub:4444/wd/hub',
desired_capabilities=caps)
self.logger = logging
self.logge... | class PythonOrgSearchTest1(unittest.TestCase):
| def setUp(self):
print("In setUp")
caps = {'browserName': 'firefox'}
self.browser = webdriver.Remote(
command_executor='http://hub:4444/wd/hub',
desired_capabilities=caps)
self.logger = logging
self.logger.info("About to call a test, should fail becaus... | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
import time
import unittest
import os
import logging
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearchTest1(unittest.TestCase):
| 64 | 64 | 212 | 10 | 53 | peterlcole/xlr-selenium-plugin | src/test/resources/mockserver/app/responses/fail1.py | Python | PythonOrgSearchTest1 | PythonOrgSearchTest1 | 19 | 44 | 19 | 20 | 4e51500ab85cfbd47026b091c831743620f1292d | bigcode/the-stack | train |
79149f504a647f5b5c26405a | train | class | class FragmentsDataService(Matrix42RestClient):
"""Fragments (/api/data/fragments), provides the operation for working with the Fragments (Instances of the Data Definitions)
The Service provides methods for CRUD operations (Create-Read-Update-Delete) for Data Definitions presented in the Schema.
Args:
... | class FragmentsDataService(Matrix42RestClient):
| """Fragments (/api/data/fragments), provides the operation for working with the Fragments (Instances of the Data Definitions)
The Service provides methods for CRUD operations (Create-Read-Update-Delete) for Data Definitions presented in the Schema.
Args:
Matrix42RestClient ([type]): Inherit Matrix... | import json
import requests
from urllib.parse import urlencode
from matrix42sdk.AuthNClient import Matrix42RestClient
from requests.exceptions import HTTPError
class FragmentsDataService(Matrix42RestClient):
| 42 | 256 | 3,664 | 10 | 31 | dmpe/matrix42sdk | matrix42sdk/api_endpoints/fragments.py | Python | FragmentsDataService | FragmentsDataService | 8 | 418 | 8 | 8 | 60ad837acd40c8b2983d1323faf87b33a2e601bd | bigcode/the-stack | train |
2998a0ebd4a11069be8c5b1b | train | class | class Client(Agent):
def __init__(self, *args: Any, client_version: Optional[str] = None, **kwargs: Any):
super().__init__(*args, **kwargs)
self.starting_time = Timestamp.now()
self._client_version: Optional[str] = (
client_version if client_version is not None else self._find_v... | class Client(Agent):
| def __init__(self, *args: Any, client_version: Optional[str] = None, **kwargs: Any):
super().__init__(*args, **kwargs)
self.starting_time = Timestamp.now()
self._client_version: Optional[str] = (
client_version if client_version is not None else self._find_version()
)
... | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR A... | 256 | 256 | 1,305 | 5 | 250 | metricq/metricq-python | metricq/client.py | Python | Client | Client | 47 | 224 | 47 | 47 | 37bead96c133c703d82ace32e46ba29a4c5b028b | bigcode/the-stack | train |
acb8c919d0d158c9d82c4b77 | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ApplicationUser',
fields=[
('username', models.CharField(max_length=200, primary_key=True, serialize=False)),
('passwor... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ApplicationUser',
fields=[
('username', models.CharField(max_length=200, primary_key=True, serialize=False)),
('password', models.CharField(max_length=200)),
... | # Generated by Django 3.1 on 2020-12-19 14:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 43 | 79 | 265 | 7 | 35 | albcristi/mobile-programming | native with local db and server/server/backend/events/migrations/0001_initial.py | Python | Migration | Migration | 7 | 43 | 7 | 8 | 1cd467b2fc8f65990c8900680f24fd6e71a9d00f | bigcode/the-stack | train |
33afabe4225d8519b5627871 | train | function | def test_issue_18_automatic():
qr = segno.make('')
assert 'M3' == qr.version
assert 'byte' == qr.mode
assert 'M' == qr.error
| def test_issue_18_automatic():
| qr = segno.make('')
assert 'M3' == qr.version
assert 'byte' == qr.mode
assert 'M' == qr.error
| == qr.mode
assert 'H' == qr.error
def test_issue_18_micro():
qr = segno.make_micro('')
assert 'M3' == qr.version
assert 'byte' == qr.mode
assert 'M' == qr.error
def test_issue_18_automatic():
| 64 | 64 | 43 | 8 | 55 | dbajar/segno | tests/test_issue18.py | Python | test_issue_18_automatic | test_issue_18_automatic | 30 | 34 | 30 | 30 | 2352a6deaa73ab4a4f446c891f15852e2303beac | bigcode/the-stack | train |
cfcaaa3fe44f0d9a98fa7a75 | train | function | def test_issue_18_zero_micro():
qr = segno.make_micro(0)
assert 'M1' == qr.version
assert 'numeric' == qr.mode
assert qr.error is None
| def test_issue_18_zero_micro():
| qr = segno.make_micro(0)
assert 'M1' == qr.version
assert 'numeric' == qr.mode
assert qr.error is None
| qr.mode
assert 'M' == qr.error
def test_issue_18_zero():
qr = segno.make_qr(0)
assert 1 == qr.version
assert 'numeric' == qr.mode
assert 'H' == qr.error
def test_issue_18_zero_micro():
| 64 | 64 | 44 | 8 | 55 | dbajar/segno | tests/test_issue18.py | Python | test_issue_18_zero_micro | test_issue_18_zero_micro | 44 | 48 | 44 | 44 | 7fe664203931847af2fcc37e4cd8aea116c462af | bigcode/the-stack | train |
a59344828c85b4da055d5ec8 | train | function | def test_issue_18():
qr = segno.make_qr('')
assert 1 == qr.version
assert 'byte' == qr.mode
assert 'H' == qr.error
| def test_issue_18():
| qr = segno.make_qr('')
assert 1 == qr.version
assert 'byte' == qr.mode
assert 'H' == qr.error
| 2020 -- Lars Heuer
# All rights reserved.
#
# License: BSD License
#
"""\
Test against issue #18.
<https://github.com/heuer/segno/issues/18>
"""
from __future__ import unicode_literals, absolute_import
import segno
def test_issue_18():
| 64 | 64 | 41 | 6 | 57 | dbajar/segno | tests/test_issue18.py | Python | test_issue_18 | test_issue_18 | 16 | 20 | 16 | 16 | 241d9892b7a9e64e51e5a555d9f1789014a6d18b | bigcode/the-stack | train |
0b2c2630f8a42f052ce00aa3 | train | function | def test_issue_18_zero():
qr = segno.make_qr(0)
assert 1 == qr.version
assert 'numeric' == qr.mode
assert 'H' == qr.error
| def test_issue_18_zero():
| qr = segno.make_qr(0)
assert 1 == qr.version
assert 'numeric' == qr.mode
assert 'H' == qr.error
| ' == qr.mode
assert 'M' == qr.error
def test_issue_18_automatic():
qr = segno.make('')
assert 'M3' == qr.version
assert 'byte' == qr.mode
assert 'M' == qr.error
def test_issue_18_zero():
| 64 | 64 | 44 | 7 | 56 | dbajar/segno | tests/test_issue18.py | Python | test_issue_18_zero | test_issue_18_zero | 37 | 41 | 37 | 37 | 1f2aee8aa999b53cc22783df99920c4af3f1ccba | bigcode/the-stack | train |
655b4e2bdb7bada6891bbfd8 | train | function | def test_issue_18_micro():
qr = segno.make_micro('')
assert 'M3' == qr.version
assert 'byte' == qr.mode
assert 'M' == qr.error
| def test_issue_18_micro():
| qr = segno.make_micro('')
assert 'M3' == qr.version
assert 'byte' == qr.mode
assert 'M' == qr.error
| """
from __future__ import unicode_literals, absolute_import
import segno
def test_issue_18():
qr = segno.make_qr('')
assert 1 == qr.version
assert 'byte' == qr.mode
assert 'H' == qr.error
def test_issue_18_micro():
| 64 | 64 | 43 | 7 | 56 | dbajar/segno | tests/test_issue18.py | Python | test_issue_18_micro | test_issue_18_micro | 23 | 27 | 23 | 23 | 6d0b8311c1158b7c77e4b772e557704586d0e5af | bigcode/the-stack | train |
c58b0366b752d3df999aa3b3 | train | function | def test_issue_18_zero_automatic():
qr = segno.make(0)
assert 'M1' == qr.version
assert 'numeric' == qr.mode
assert qr.error is None
| def test_issue_18_zero_automatic():
| qr = segno.make(0)
assert 'M1' == qr.version
assert 'numeric' == qr.mode
assert qr.error is None
| .mode
assert 'H' == qr.error
def test_issue_18_zero_micro():
qr = segno.make_micro(0)
assert 'M1' == qr.version
assert 'numeric' == qr.mode
assert qr.error is None
def test_issue_18_zero_automatic():
| 64 | 64 | 44 | 9 | 54 | dbajar/segno | tests/test_issue18.py | Python | test_issue_18_zero_automatic | test_issue_18_zero_automatic | 51 | 55 | 51 | 51 | 754e2833f9d2c579d18313b11f12e9ec8b7ab3e5 | bigcode/the-stack | train |
7e508ff50356537529539e6f | train | class | class SaveSingleTaskForSaveArtExtensionRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Domain', '2018-01-29', 'SaveSingleTaskForSaveArtExtension','domain')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr... | class SaveSingleTaskForSaveArtExtensionRequest(RpcRequest):
| def __init__(self):
RpcRequest.__init__(self, 'Domain', '2018-01-29', 'SaveSingleTaskForSaveArtExtension','domain')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regio... | information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless requir... | 176 | 176 | 587 | 13 | 162 | jia-jerry/aliyun-openapi-python-sdk | aliyun-python-sdk-domain/aliyunsdkdomain/request/v20180129/SaveSingleTaskForSaveArtExtensionRequest.py | Python | SaveSingleTaskForSaveArtExtensionRequest | SaveSingleTaskForSaveArtExtensionRequest | 23 | 104 | 23 | 24 | 0c5bbd946321961bf6b64fda6646bc006712fe52 | bigcode/the-stack | train |
ec453448087b5bc3a7a7dd4f | train | function | @pytest.mark.parametrize('command', all_commands)
def test_aesthetic_args_options_msg(command):
"""All the real commands args/options help messages start with uppercase and end with a dot."""
class FakeParser:
"""A fake to get the arguments added."""
def add_argument(self, *args, **kwargs):
... | @pytest.mark.parametrize('command', all_commands)
def test_aesthetic_args_options_msg(command):
| """All the real commands args/options help messages start with uppercase and end with a dot."""
class FakeParser:
"""A fake to get the arguments added."""
def add_argument(self, *args, **kwargs):
help_msg = kwargs.get('help')
assert help_msg, "The help message must be pr... | esthetic_help_msg(command):
"""All the real commands help msg start with uppercase and ends with a dot."""
msg = command.help_msg
assert msg[0].isupper() and msg[-1] == '.'
@pytest.mark.parametrize('command', all_commands)
def test_aesthetic_args_options_msg(command):
| 64 | 64 | 119 | 18 | 45 | fakela/charmcraft | tests/test_help.py | Python | test_aesthetic_args_options_msg | test_aesthetic_args_options_msg | 42 | 53 | 42 | 43 | 0f8bddfe60518750c865168c163e213aed4d1cdb | bigcode/the-stack | train |
e9794c9cfc50713984fb8a38 | train | function | @pytest.mark.parametrize('command', all_commands)
def test_aesthetic_help_msg(command):
"""All the real commands help msg start with uppercase and ends with a dot."""
msg = command.help_msg
assert msg[0].isupper() and msg[-1] == '.'
| @pytest.mark.parametrize('command', all_commands)
def test_aesthetic_help_msg(command):
| """All the real commands help msg start with uppercase and ends with a dot."""
msg = command.help_msg
assert msg[0].isupper() and msg[-1] == '.'
| charmcraft.helptexts import (
get_full_help,
)
from tests.factory import create_command
# -- verifications on different short help texts
all_commands = list.__add__(*[commands for _, _, commands in COMMAND_GROUPS])
@pytest.mark.parametrize('command', all_commands)
def test_aesthetic_help_msg(command):
| 64 | 64 | 58 | 17 | 47 | fakela/charmcraft | tests/test_help.py | Python | test_aesthetic_help_msg | test_aesthetic_help_msg | 35 | 39 | 35 | 36 | e753cccb5805e3b104fd8962ec4631b35674ca3f | bigcode/the-stack | train |
23c21988a0109ed39f1a4fda | train | function | def test_default_help_text():
"""All different parts for the default help."""
cmd1 = create_command('cmd1', 'Cmd help which is very long but whatever.', common_=True)
cmd2 = create_command('command-2', 'Cmd help.', common_=True)
cmd3 = create_command('cmd3', 'Extremely ' + 'super crazy long ' * 5 + ' he... | def test_default_help_text():
| """All different parts for the default help."""
cmd1 = create_command('cmd1', 'Cmd help which is very long but whatever.', common_=True)
cmd2 = create_command('command-2', 'Cmd help.', common_=True)
cmd3 = create_command('cmd3', 'Extremely ' + 'super crazy long ' * 5 + ' help.', common_=True)
cmd4 =... | ends with a dot."""
msg = command.help_msg
assert msg[0].isupper() and msg[-1] == '.'
@pytest.mark.parametrize('command', all_commands)
def test_aesthetic_args_options_msg(command):
"""All the real commands args/options help messages start with uppercase and end with a dot."""
class FakeParser:
... | 165 | 165 | 552 | 6 | 158 | fakela/charmcraft | tests/test_help.py | Python | test_default_help_text | test_default_help_text | 58 | 113 | 58 | 58 | b2b80c6194443a7faf45bea3eacc9c71456bcdd9 | bigcode/the-stack | train |
7e5bf732a0cdaa2b3608c302 | train | class | class ClearableFileInput(FileInput):
template_name = 'floppyforms/clearable_input.html'
omit_value = False
def clear_checkbox_name(self, name):
return name + '-clear'
def clear_checkbox_id(self, name):
return name + '_id'
def get_context(self, name, value, attrs):
context ... | class ClearableFileInput(FileInput):
| template_name = 'floppyforms/clearable_input.html'
omit_value = False
def clear_checkbox_name(self, name):
return name + '-clear'
def clear_checkbox_id(self, name):
return name + '_id'
def get_context(self, name, value, attrs):
context = super(ClearableFileInput, self).get... | render an existing value if it's not saved
value = None
return super(FileInput, self).render(name, value, attrs=attrs)
def value_from_datadict(self, data, files, name):
return files.get(name, None)
if django.VERSION < (1, 6):
def _has_changed(self, initial, data):
... | 98 | 98 | 327 | 8 | 89 | greyside/django-floppyforms | floppyforms/widgets.py | Python | ClearableFileInput | ClearableFileInput | 219 | 259 | 219 | 219 | f132a5561f358bd92bf9aaa5eca3e98e9060c4ce | bigcode/the-stack | train |
8d2f1789fec8a92ecce1d11d | train | class | class SelectDateWidget(forms.Widget):
"""
A Widget that splits date input into three <select> boxes.
This also serves as an example of a Widget that has more than one HTML
element and hence implements value_from_datadict.
"""
none_value = (0, '---')
month_field = '%s_month'
day_field = ... | class SelectDateWidget(forms.Widget):
| """
A Widget that splits date input into three <select> boxes.
This also serves as an example of a Widget that has more than one HTML
element and hence implements value_from_datadict.
"""
none_value = (0, '---')
month_field = '%s_month'
day_field = '%s_day'
year_field = '%s_year'
... | /radio.html'
class CheckboxSelectMultiple(SelectMultiple):
template_name = 'floppyforms/checkbox_select.html'
class MultiWidget(forms.MultiWidget):
# Backported from Django 1.7
@property
def is_hidden(self):
return all(w.is_hidden for w in self.widgets)
class SplitDateTimeWidget(MultiWidge... | 256 | 256 | 1,006 | 7 | 249 | greyside/django-floppyforms | floppyforms/widgets.py | Python | SelectDateWidget | SelectDateWidget | 605 | 724 | 605 | 605 | 9e3f25d7dc52b8bca3d5bff90474ae0143c38e3e | bigcode/the-stack | train |
c086421f3cc6158a98ccf7b4 | train | class | class CheckboxSelectMultiple(SelectMultiple):
template_name = 'floppyforms/checkbox_select.html'
| class CheckboxSelectMultiple(SelectMultiple):
| template_name = 'floppyforms/checkbox_select.html'
| initial_set = set([force_text(value) for value in initial])
data_set = set([force_text(value) for value in data])
return data_set != initial_set
class RadioSelect(Select):
template_name = 'floppyforms/radio.html'
class CheckboxSelectMultiple(SelectMultiple):
| 64 | 64 | 21 | 8 | 56 | greyside/django-floppyforms | floppyforms/widgets.py | Python | CheckboxSelectMultiple | CheckboxSelectMultiple | 571 | 572 | 571 | 571 | cf11a526ac2ab77652bdf454c1cddca100d407f3 | bigcode/the-stack | train |
18204723683b4a5ff322241a | train | class | class ColorInput(Input):
template_name = 'floppyforms/color.html'
input_type = 'color'
| class ColorInput(Input):
| template_name = 'floppyforms/color.html'
input_type = 'color'
| forms/search.html'
input_type = 'search'
class EmailInput(TextInput):
template_name = 'floppyforms/email.html'
input_type = 'email'
class URLInput(TextInput):
template_name = 'floppyforms/url.html'
input_type = 'url'
class ColorInput(Input):
| 64 | 64 | 23 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | ColorInput | ColorInput | 382 | 384 | 382 | 382 | 7d500568bd5f34b9221f5cbbf444e270b26a12a6 | bigcode/the-stack | train |
6eb557970f278609a81a2331 | train | class | class Input(Widget):
template_name = 'floppyforms/input.html'
input_type = None
datalist = None
def __init__(self, *args, **kwargs):
datalist = kwargs.pop('datalist', None)
if datalist is not None:
self.datalist = datalist
template_name = kwargs.pop('template_name', ... | class Input(Widget):
| template_name = 'floppyforms/input.html'
input_type = None
datalist = None
def __init__(self, *args, **kwargs):
datalist = kwargs.pop('datalist', None)
if datalist is not None:
self.datalist = datalist
template_name = kwargs.pop('template_name', None)
if temp... | NullBooleanSelect', 'SelectMultiple',
'RadioSelect', 'CheckboxSelectMultiple', 'SearchInput', 'RangeInput',
'ColorInput', 'EmailInput', 'URLInput', 'PhoneNumberInput', 'NumberInput',
'IPAddressInput', 'MultiWidget', 'Widget', 'SplitDateTimeWidget',
'SplitHiddenDateTimeWidget', 'MultipleHiddenInput', 'Se... | 147 | 147 | 492 | 5 | 141 | greyside/django-floppyforms | floppyforms/widgets.py | Python | Input | Input | 48 | 114 | 48 | 48 | 80a7f5c40324721b8f99da4b716144eb65c60108 | bigcode/the-stack | train |
e7cbc371b831d1fbf883678f | train | class | class Select(Input):
allow_multiple_selected = False
template_name = 'floppyforms/select.html'
def __init__(self, attrs=None, choices=()):
super(Select, self).__init__(attrs)
self.choices = list(choices)
def get_context(self, name, value, attrs=None, choices=()):
if not hasattr... | class Select(Input):
| allow_multiple_selected = False
template_name = 'floppyforms/select.html'
def __init__(self, attrs=None, choices=()):
super(Select, self).__init__(attrs)
self.choices = list(choices)
def get_context(self, name, value, attrs=None, choices=()):
if not hasattr(value, '__iter__') o... | if name not in data:
return False
value = data.get(name)
values = {'true': True, 'false': False}
if isinstance(value, six.string_types):
value = values.get(value.lower(), value)
return value
if django.VERSION < (1, 6):
def _has_changed(self, i... | 114 | 114 | 382 | 4 | 110 | greyside/django-floppyforms | floppyforms/widgets.py | Python | Select | Select | 458 | 505 | 458 | 458 | 3da95a661120d17119b6ada522b34af008bf7c04 | bigcode/the-stack | train |
175f9a5f418f110cdf788bfe | train | class | class RadioSelect(Select):
template_name = 'floppyforms/radio.html'
| class RadioSelect(Select):
| template_name = 'floppyforms/radio.html'
| is None:
data = []
if len(initial) != len(data):
return True
initial_set = set([force_text(value) for value in initial])
data_set = set([force_text(value) for value in data])
return data_set != initial_set
class RadioSelect(Select):
| 64 | 64 | 18 | 6 | 57 | greyside/django-floppyforms | floppyforms/widgets.py | Python | RadioSelect | RadioSelect | 567 | 568 | 567 | 567 | ec0de4776788139f96f8019b9aea687e997c7892 | bigcode/the-stack | train |
da5c98721d1521378e67867e | train | class | class HiddenInput(Input):
template_name = 'floppyforms/hidden.html'
input_type = 'hidden'
| class HiddenInput(Input):
| template_name = 'floppyforms/hidden.html'
input_type = 'hidden'
| super(PasswordInput, self).__init__(attrs)
self.render_value = render_value
def render(self, name, value, attrs=None):
if not self.render_value:
value = None
return super(PasswordInput, self).render(name, value, attrs)
class HiddenInput(Input):
| 64 | 64 | 24 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | HiddenInput | HiddenInput | 141 | 143 | 141 | 141 | 5a80cb807d2094ef506e2481e1a538150cecfbf1 | bigcode/the-stack | train |
a1aea176712f853f38594f96 | train | class | class NumberInput(TextInput):
template_name = 'floppyforms/number.html'
input_type = 'number'
min = None
max = None
step = None
def __init__(self, attrs=None):
default_attrs = {'min': self.min, 'max': self.max, 'step': self.step}
if attrs:
default_attrs.update(attrs)... | class NumberInput(TextInput):
| template_name = 'floppyforms/number.html'
input_type = 'number'
min = None
max = None
step = None
def __init__(self, attrs=None):
default_attrs = {'min': self.min, 'max': self.max, 'step': self.step}
if attrs:
default_attrs.update(attrs)
# Popping attrs if th... | forms/email.html'
input_type = 'email'
class URLInput(TextInput):
template_name = 'floppyforms/url.html'
input_type = 'url'
class ColorInput(Input):
template_name = 'floppyforms/color.html'
input_type = 'color'
class NumberInput(TextInput):
| 64 | 64 | 128 | 6 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | NumberInput | NumberInput | 387 | 402 | 387 | 387 | bc9a741102b73406d73e864880ee910d45e61321 | bigcode/the-stack | train |
0c0ccc341952bbecc1031c0a | train | class | class DateInput(Input):
template_name = 'floppyforms/date.html'
input_type = 'date'
supports_microseconds = False
def __init__(self, attrs=None, format=None):
super(DateInput, self).__init__(attrs)
self.format = '%Y-%m-%d'
def _format_value(self, value):
if hasattr(value, '... | class DateInput(Input):
| template_name = 'floppyforms/date.html'
input_type = 'date'
supports_microseconds = False
def __init__(self, attrs=None, format=None):
super(DateInput, self).__init__(attrs)
self.format = '%Y-%m-%d'
def _format_value(self, value):
if hasattr(value, 'strftime'):
... | , attrs=None):
default_attrs = {'cols': self.cols, 'rows': self.rows}
if attrs:
default_attrs.update(attrs)
super(Textarea, self).__init__(default_attrs)
def _format_value(self, value):
return conditional_escape(force_text(value))
class DateInput(Input):
| 64 | 64 | 189 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | DateInput | DateInput | 277 | 301 | 277 | 277 | 5d814c0cffb7539e2000a9f2e44277a832404ea5 | bigcode/the-stack | train |
56a4cddd291682ee6ebb0497 | train | class | class SplitDateTimeWidget(MultiWidget):
supports_microseconds = False
def __init__(self, attrs=None, date_format=None, time_format=None):
widgets = (DateInput(attrs=attrs, format=date_format),
TimeInput(attrs=attrs, format=time_format))
super(SplitDateTimeWidget, self).__init... | class SplitDateTimeWidget(MultiWidget):
| supports_microseconds = False
def __init__(self, attrs=None, date_format=None, time_format=None):
widgets = (DateInput(attrs=attrs, format=date_format),
TimeInput(attrs=attrs, format=time_format))
super(SplitDateTimeWidget, self).__init__(widgets, attrs)
def decompress(s... | Multiple):
template_name = 'floppyforms/checkbox_select.html'
class MultiWidget(forms.MultiWidget):
# Backported from Django 1.7
@property
def is_hidden(self):
return all(w.is_hidden for w in self.widgets)
class SplitDateTimeWidget(MultiWidget):
| 64 | 64 | 117 | 9 | 55 | greyside/django-floppyforms | floppyforms/widgets.py | Python | SplitDateTimeWidget | SplitDateTimeWidget | 582 | 594 | 582 | 582 | 2ac9c764aa5311ccc980c9ecb4af301eea4dc6da | bigcode/the-stack | train |
d5c8db659718d83129250015 | train | class | class SlugInput(TextInput):
template_name = 'floppyforms/slug.html'
"""<input type="text"> validating slugs with a pattern"""
def get_context(self, name, value, attrs):
context = super(SlugInput, self).get_context(name, value, attrs)
context['attrs']['pattern'] = "[-\w]+"
return con... | class SlugInput(TextInput):
| template_name = 'floppyforms/slug.html'
"""<input type="text"> validating slugs with a pattern"""
def get_context(self, name, value, attrs):
context = super(SlugInput, self).get_context(name, value, attrs)
context['attrs']['pattern'] = "[-\w]+"
return context
| ), input_attrs))
return mark_safe("\n".join(inputs))
def value_from_datadict(self, data, files, name):
if isinstance(data, (MultiValueDict, MergeDict)):
return data.getlist(name)
return data.get(name, None)
class SlugInput(TextInput):
| 64 | 64 | 82 | 7 | 57 | greyside/django-floppyforms | floppyforms/widgets.py | Python | SlugInput | SlugInput | 174 | 181 | 174 | 174 | b6bae8ddc6a97bf057fb3397462cfdea7205b624 | bigcode/the-stack | train |
267f147e8f667ed187886fcd | train | class | class NullBooleanSelect(Select):
def __init__(self, attrs=None):
choices = (('1', _('Unknown')),
('2', _('Yes')),
('3', _('No')))
super(NullBooleanSelect, self).__init__(attrs, choices)
def _format_value(self, value):
value = value[0]
try:
... | class NullBooleanSelect(Select):
| def __init__(self, attrs=None):
choices = (('1', _('Unknown')),
('2', _('Yes')),
('3', _('No')))
super(NullBooleanSelect, self).__init__(attrs, choices)
def _format_value(self, value):
value = value[0]
try:
value = {True: '2', Fa... | ((None, [(option_value, option_label)]))
context["optgroups"] = groups
return context
def _format_value(self, value):
if len(value) == 1 and value[0] is None:
return []
return set(force_text(v) for v in value)
class NullBooleanSelect(Select):
| 71 | 71 | 237 | 7 | 64 | greyside/django-floppyforms | floppyforms/widgets.py | Python | NullBooleanSelect | NullBooleanSelect | 508 | 538 | 508 | 508 | ec7696abd4a49abe9d692df4669c19c6d4d8a503 | bigcode/the-stack | train |
d79842a1c4a6c467682c3b7e | train | class | class SearchInput(Input):
template_name = 'floppyforms/search.html'
input_type = 'search'
| class SearchInput(Input):
| template_name = 'floppyforms/search.html'
input_type = 'search'
| = formats.get_format('TIME_INPUT_FORMATS')[0]
initial = datetime.datetime.strptime(initial, input_format).time()
except (TypeError, ValueError):
pass
return super(TimeInput, self)._has_changed(
self._format_value(initial), data
)
class... | 64 | 64 | 23 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | SearchInput | SearchInput | 367 | 369 | 367 | 367 | a7850b53f09d88dc88e85c89726c26a5d5d77083 | bigcode/the-stack | train |
1e05940d6a2e3e1a7f36f64e | train | class | class TimeInput(Input):
template_name = 'floppyforms/time.html'
input_type = 'time'
supports_microseconds = False
def __init__(self, attrs=None, format=None):
super(TimeInput, self).__init__(attrs)
if format:
self.format = format
self.manual_format = True
... | class TimeInput(Input):
| template_name = 'floppyforms/time.html'
input_type = 'time'
supports_microseconds = False
def __init__(self, attrs=None, format=None):
super(TimeInput, self).__init__(attrs)
if format:
self.format = format
self.manual_format = True
else:
self.... | = formats.get_format('DATETIME_INPUT_FORMATS')[0]
initial = datetime.datetime.strptime(initial, input_format)
except (TypeError, ValueError):
pass
return super(DateTimeInput, self)._has_changed(
self._format_value(initial), data
)
clas... | 64 | 64 | 211 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | TimeInput | TimeInput | 336 | 364 | 336 | 336 | fe82082e4a1f8b0a8c9148b498d31cc356edda44 | bigcode/the-stack | train |
19ed247659dd122f8836b9c4 | train | class | class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
def __init__(self, attrs=None, date_format=None, time_format=None):
super(SplitHiddenDateTimeWidget, self).__init__(attrs, date_format,
time_format)
for widget in self.widgets:
w... | class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
| def __init__(self, attrs=None, date_format=None, time_format=None):
super(SplitHiddenDateTimeWidget, self).__init__(attrs, date_format,
time_format)
for widget in self.widgets:
widget.input_type = 'hidden'
| Widget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
value = to_current_timezone(value)
return [value.date(), value.time().replace(microsecond=0)]
return [None, None]
class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
| 64 | 64 | 67 | 12 | 52 | greyside/django-floppyforms | floppyforms/widgets.py | Python | SplitHiddenDateTimeWidget | SplitHiddenDateTimeWidget | 597 | 602 | 597 | 597 | eb054aba76b5be1d4920a1e050a2d9aed541f362 | bigcode/the-stack | train |
e2646b5423506b3e995e50c3 | train | class | class EmailInput(TextInput):
template_name = 'floppyforms/email.html'
input_type = 'email'
| class EmailInput(TextInput):
| template_name = 'floppyforms/email.html'
input_type = 'email'
| ()
except (TypeError, ValueError):
pass
return super(TimeInput, self)._has_changed(
self._format_value(initial), data
)
class SearchInput(Input):
template_name = 'floppyforms/search.html'
input_type = 'search'
class EmailInput(TextInput):
| 64 | 64 | 24 | 6 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | EmailInput | EmailInput | 372 | 374 | 372 | 372 | 539b1f057761b6d71ca2c04315b88c1f1a7ec741 | bigcode/the-stack | train |
5fe4be2e42b14126403fe98a | train | class | class IPAddressInput(TextInput):
template_name = 'floppyforms/ipaddress.html'
"""<input type="text"> validating IP addresses with a pattern"""
ip_pattern = ("(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25"
"[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}")
def get_context(self, name, value, attrs):
co... | class IPAddressInput(TextInput):
| template_name = 'floppyforms/ipaddress.html'
"""<input type="text"> validating IP addresses with a pattern"""
ip_pattern = ("(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25"
"[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}")
def get_context(self, name, value, attrs):
context = super(IPAddressInput, sel... | text"> validating slugs with a pattern"""
def get_context(self, name, value, attrs):
context = super(SlugInput, self).get_context(name, value, attrs)
context['attrs']['pattern'] = "[-\w]+"
return context
class IPAddressInput(TextInput):
| 64 | 64 | 140 | 7 | 56 | greyside/django-floppyforms | floppyforms/widgets.py | Python | IPAddressInput | IPAddressInput | 184 | 194 | 184 | 184 | 216e149a5d79c23d0ff1d2d2de89916d5c4a3c34 | bigcode/the-stack | train |
a573b4f140ee46b74b540317 | train | class | class URLInput(TextInput):
template_name = 'floppyforms/url.html'
input_type = 'url'
| class URLInput(TextInput):
| template_name = 'floppyforms/url.html'
input_type = 'url'
| self._format_value(initial), data
)
class SearchInput(Input):
template_name = 'floppyforms/search.html'
input_type = 'search'
class EmailInput(TextInput):
template_name = 'floppyforms/email.html'
input_type = 'email'
class URLInput(TextInput):
| 64 | 64 | 24 | 6 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | URLInput | URLInput | 377 | 379 | 377 | 377 | 9291a156c80b7c6483d3dd0f3ebc88466e361147 | bigcode/the-stack | train |
60dc2ccec5193f809185ba43 | train | class | class RangeInput(NumberInput):
template_name = 'floppyforms/range.html'
input_type = 'range'
| class RangeInput(NumberInput):
| template_name = 'floppyforms/range.html'
input_type = 'range'
| .step}
if attrs:
default_attrs.update(attrs)
# Popping attrs if they're not set
for key in list(default_attrs.keys()):
if default_attrs[key] is None:
default_attrs.pop(key)
super(NumberInput, self).__init__(default_attrs)
class RangeInput(NumberInp... | 64 | 64 | 25 | 6 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | RangeInput | RangeInput | 405 | 407 | 405 | 405 | 1dc8149fd5ad3e42c72c8df74965948294e1bfb0 | bigcode/the-stack | train |
8cd382434c41dd277ce9ed43 | train | class | class MultiWidget(forms.MultiWidget):
# Backported from Django 1.7
@property
def is_hidden(self):
return all(w.is_hidden for w in self.widgets)
| class MultiWidget(forms.MultiWidget):
# Backported from Django 1.7
@property
| def is_hidden(self):
return all(w.is_hidden for w in self.widgets)
| initial_set
class RadioSelect(Select):
template_name = 'floppyforms/radio.html'
class CheckboxSelectMultiple(SelectMultiple):
template_name = 'floppyforms/checkbox_select.html'
class MultiWidget(forms.MultiWidget):
# Backported from Django 1.7
@property
| 64 | 64 | 40 | 22 | 42 | greyside/django-floppyforms | floppyforms/widgets.py | Python | MultiWidget | MultiWidget | 575 | 579 | 575 | 577 | 680f18cd5f72d7fd4c3d65e708d9cd690ac076a4 | bigcode/the-stack | train |
edc02d6d4abd16f732bf5c32 | train | class | class Textarea(Input):
template_name = 'floppyforms/textarea.html'
rows = 10
cols = 40
def __init__(self, attrs=None):
default_attrs = {'cols': self.cols, 'rows': self.rows}
if attrs:
default_attrs.update(attrs)
super(Textarea, self).__init__(default_attrs)
def ... | class Textarea(Input):
| template_name = 'floppyforms/textarea.html'
rows = 10
cols = 40
def __init__(self, attrs=None):
default_attrs = {'cols': self.cols, 'rows': self.rows}
if attrs:
default_attrs.update(attrs)
super(Textarea, self).__init__(default_attrs)
def _format_value(self, val... | the value from a
# models.ImageField that is set to None. In that case we just return
# None. Otherwise calls in the template like {{ value.url }} will raise
# a ValueError.
if not value:
return None
return value
class Textarea(Input):
| 64 | 64 | 94 | 5 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | Textarea | Textarea | 262 | 274 | 262 | 262 | 4a541f3fb77a34316bf11d67147938ed10ddecc5 | bigcode/the-stack | train |
a8e12c6c33fc84ca0649ef27 | train | class | class FileInput(Input):
template_name = 'floppyforms/file.html'
input_type = 'file'
needs_multipart_form = True
omit_value = True
def render(self, name, value, attrs=None):
if self.omit_value:
# File inputs can't render an existing value if it's not saved
value = Non... | class FileInput(Input):
| template_name = 'floppyforms/file.html'
input_type = 'file'
needs_multipart_form = True
omit_value = True
def render(self, name, value, attrs=None):
if self.omit_value:
# File inputs can't render an existing value if it's not saved
value = None
return super(F... | |[0-1]?\d?\d)){3}")
def get_context(self, name, value, attrs):
context = super(IPAddressInput, self).get_context(name, value, attrs)
context['attrs']['pattern'] = self.ip_pattern
return context
class FileInput(Input):
| 64 | 64 | 151 | 5 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | FileInput | FileInput | 197 | 216 | 197 | 197 | 00927727c456a0977740259e7efba7ffb0e27a26 | bigcode/the-stack | train |
22277d9f88c21cfb1829ff23 | train | class | class MultipleHiddenInput(HiddenInput):
"""<input type="hidden"> for fields that have a list of values"""
def __init__(self, attrs=None, choices=()):
super(MultipleHiddenInput, self).__init__(attrs)
self.choices = choices
def render(self, name, value, attrs=None, choices=()):
if val... | class MultipleHiddenInput(HiddenInput):
| """<input type="hidden"> for fields that have a list of values"""
def __init__(self, attrs=None, choices=()):
super(MultipleHiddenInput, self).__init__(attrs)
self.choices = choices
def render(self, name, value, attrs=None, choices=()):
if value is None:
value = []
... | (self, name, value, attrs=None):
if not self.render_value:
value = None
return super(PasswordInput, self).render(name, value, attrs)
class HiddenInput(Input):
template_name = 'floppyforms/hidden.html'
input_type = 'hidden'
class MultipleHiddenInput(HiddenInput):
| 69 | 69 | 233 | 8 | 61 | greyside/django-floppyforms | floppyforms/widgets.py | Python | MultipleHiddenInput | MultipleHiddenInput | 146 | 171 | 146 | 146 | b7ecca2454606ff6fc4a53115c108966f4d798f4 | bigcode/the-stack | train |
02856435b1242f137197fd2e | train | class | class Widget(forms.Widget):
is_required = False
# Backported from Django 1.7
@property
def is_hidden(self):
return self.input_type == 'hidden' if hasattr(self, 'input_type') else False
| class Widget(forms.Widget):
| is_required = False
# Backported from Django 1.7
@property
def is_hidden(self):
return self.input_type == 'hidden' if hasattr(self, 'input_type') else False
| 'EmailInput', 'URLInput', 'PhoneNumberInput', 'NumberInput',
'IPAddressInput', 'MultiWidget', 'Widget', 'SplitDateTimeWidget',
'SplitHiddenDateTimeWidget', 'MultipleHiddenInput', 'SelectDateWidget',
'SlugInput',
)
class Widget(forms.Widget):
| 64 | 64 | 52 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | Widget | Widget | 39 | 45 | 39 | 39 | 7b892cb323e195fed0c4c212b3e5c6f293530aa2 | bigcode/the-stack | train |
cee740584c146af33ee2ff76 | train | class | class TextInput(Input):
template_name = 'floppyforms/text.html'
input_type = 'text'
def __init__(self, *args, **kwargs):
if kwargs.get('attrs', None) is not None:
self.input_type = kwargs['attrs'].pop('type', self.input_type)
super(TextInput, self).__init__(*args, **kwargs)
| class TextInput(Input):
| template_name = 'floppyforms/text.html'
input_type = 'text'
def __init__(self, *args, **kwargs):
if kwargs.get('attrs', None) is not None:
self.input_type = kwargs['attrs'].pop('type', self.input_type)
super(TextInput, self).__init__(*args, **kwargs)
| template_name', None)
if template_name is None:
template_name = self.template_name
context = self.get_context(name, value, attrs=attrs or {}, **kwargs)
return loader.render_to_string(
template_name,
context,
context_instance=self.context_instance)
... | 64 | 64 | 80 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | TextInput | TextInput | 117 | 124 | 117 | 117 | fa46625140558c6fc1de47969a5c64ef10124a7e | bigcode/the-stack | train |
5d97dbc62fd9ab91134229bb | train | function | def boolean_check(v):
return not (v is False or v is None or v == '')
| def boolean_check(v):
| return not (v is False or v is None or v == '')
| Input, self).__init__(default_attrs)
class RangeInput(NumberInput):
template_name = 'floppyforms/range.html'
input_type = 'range'
class PhoneNumberInput(Input):
template_name = 'floppyforms/phonenumber.html'
input_type = 'tel'
def boolean_check(v):
| 64 | 64 | 20 | 5 | 59 | greyside/django-floppyforms | floppyforms/widgets.py | Python | boolean_check | boolean_check | 415 | 416 | 415 | 415 | 20fb6f63fda26413a191cc0d76084f9494add845 | bigcode/the-stack | train |
31f7f780b1589daa0de91482 | train | class | class PasswordInput(TextInput):
template_name = 'floppyforms/password.html'
input_type = 'password'
def __init__(self, attrs=None, render_value=False):
super(PasswordInput, self).__init__(attrs)
self.render_value = render_value
def render(self, name, value, attrs=None):
if not ... | class PasswordInput(TextInput):
| template_name = 'floppyforms/password.html'
input_type = 'password'
def __init__(self, attrs=None, render_value=False):
super(PasswordInput, self).__init__(attrs)
self.render_value = render_value
def render(self, name, value, attrs=None):
if not self.render_value:
v... | '
def __init__(self, *args, **kwargs):
if kwargs.get('attrs', None) is not None:
self.input_type = kwargs['attrs'].pop('type', self.input_type)
super(TextInput, self).__init__(*args, **kwargs)
class PasswordInput(TextInput):
| 64 | 64 | 98 | 6 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | PasswordInput | PasswordInput | 127 | 138 | 127 | 127 | 98b097228b16ec5fd6fe64003a58592cfbc912d7 | bigcode/the-stack | train |
073b47e910ba40cd42435f6d | train | class | class DateTimeInput(Input):
template_name = 'floppyforms/datetime.html'
input_type = 'datetime'
supports_microseconds = False
def __init__(self, attrs=None, format=None):
super(DateTimeInput, self).__init__(attrs)
if format:
self.format = format
self.manual_forma... | class DateTimeInput(Input):
| template_name = 'floppyforms/datetime.html'
input_type = 'datetime'
supports_microseconds = False
def __init__(self, attrs=None, format=None):
super(DateTimeInput, self).__init__(attrs)
if format:
self.format = format
self.manual_format = True
else:
... | input_format = formats.get_format('DATE_INPUT_FORMATS')[0]
initial = datetime.datetime.strptime(initial, input_format).date()
except (TypeError, ValueError):
pass
return super(DateInput, self)._has_changed(
self._format_value(initial), data
... | 67 | 67 | 224 | 6 | 61 | greyside/django-floppyforms | floppyforms/widgets.py | Python | DateTimeInput | DateTimeInput | 304 | 333 | 304 | 304 | 77521308a74db9920370d048ea3bfc6acffff157 | bigcode/the-stack | train |
7b3ad922fd1a29991a13a0e2 | train | class | class CheckboxInput(Input, forms.CheckboxInput):
template_name = 'floppyforms/checkbox.html'
input_type = 'checkbox'
def __init__(self, attrs=None, check_test=None):
super(CheckboxInput, self).__init__(attrs)
self.check_test = boolean_check if check_test is None else check_test
def get... | class CheckboxInput(Input, forms.CheckboxInput):
| template_name = 'floppyforms/checkbox.html'
input_type = 'checkbox'
def __init__(self, attrs=None, check_test=None):
super(CheckboxInput, self).__init__(attrs)
self.check_test = boolean_check if check_test is None else check_test
def get_context(self, name, value, attrs):
resul... | ).__init__(default_attrs)
class RangeInput(NumberInput):
template_name = 'floppyforms/range.html'
input_type = 'range'
class PhoneNumberInput(Input):
template_name = 'floppyforms/phonenumber.html'
input_type = 'tel'
def boolean_check(v):
return not (v is False or v is None or v == '')
class Ch... | 86 | 87 | 292 | 10 | 76 | greyside/django-floppyforms | floppyforms/widgets.py | Python | CheckboxInput | CheckboxInput | 419 | 455 | 419 | 419 | 993560f18968a7afcc5a991a40fda6c7509c1c8d | bigcode/the-stack | train |
6d0dfa748493d486aa6724c4 | train | class | class PhoneNumberInput(Input):
template_name = 'floppyforms/phonenumber.html'
input_type = 'tel'
| class PhoneNumberInput(Input):
| template_name = 'floppyforms/phonenumber.html'
input_type = 'tel'
| in list(default_attrs.keys()):
if default_attrs[key] is None:
default_attrs.pop(key)
super(NumberInput, self).__init__(default_attrs)
class RangeInput(NumberInput):
template_name = 'floppyforms/range.html'
input_type = 'range'
class PhoneNumberInput(Input):
| 64 | 64 | 25 | 6 | 58 | greyside/django-floppyforms | floppyforms/widgets.py | Python | PhoneNumberInput | PhoneNumberInput | 410 | 412 | 410 | 410 | eeab6caa32fcc4c238dc0cc5f426030d01e58e8d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.