code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for i in range(0, len(iterable), n):
yield iterable[i:i + n] | def chunks(iterable, n) | Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 | 2.001762 | 1.729681 | 1.157301 |
for el in iterable:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
yield el | def flatten(iterable) | flat a iterable. https://stackoverflow.com/a/2158532 | 1.789359 | 1.593579 | 1.122856 |
factory = FestivalFactory(lang=lang)
return factory.iter_festival_countdown(countdown, date_obj) | def iter_festival_countdown(countdown: Optional[int] = None, date_obj: MDate = None,
lang: str = 'zh-Hans') -> FestivalCountdownIterable | Return countdown of festivals. | 4.664915 | 3.670011 | 1.27109 |
year = year or self.year
if year:
return self._resolve(year)
raise ValueError('Unable resolve the date without a specified year.') | def resolve(self, year: int = YEAR_ANY) -> MDate | Return the date object in the solar / lunar year.
:param year:
:return: | 8.515882 | 9.17271 | 0.928393 |
if self.date_class == date:
return self.resolve(year)
else:
solar_date = LCalendars.cast_date(self.resolve(year), date)
offset = solar_date.year - year
if offset:
solar_date = LCalendars.cast_date(self.resolve(year - offset), date)... | def resolve_solar(self, year: int) -> date | Return the date object in a solar year.
:param year:
:return: | 4.504385 | 4.453941 | 1.011326 |
leap_month, leap_days = _parse_leap(year_info)
res = leap_days
for month in range(1, 13):
res += (year_info >> (16 - month)) % 2 + 29
return res | def parse_year_days(year_info) | Parse year days from a year info. | 5.749176 | 5.346709 | 1.075274 |
# info => month, days, leap
leap_month, leap_days = _parse_leap(year_info)
months = [(i, 0) for i in range(1, 13)]
if leap_month > 0:
months.insert(leap_month, (leap_month, 1))
for month, leap in months:
if leap:
days = leap_days
else:
days = (ye... | def _iter_year_month(year_info) | Iter the month days in a lunar year. | 3.620408 | 3.339998 | 1.083955 |
if year == 2101:
days = [5, 20]
else:
days = TermUtils.parse_term_days(year)
term_index1 = 2 * (month - 1)
term_index2 = 2 * (month - 1) + 1
day1 = days[term_index1]
day2 = days[term_index2]
if day == day1:
term_name = ... | def get_term_info(year, month, day) | Parse solar term and stem-branch year/month/day from a solar date.
(sy, sm, sd) => (term, next_gz_month)
term for year 2101,:2101.1.5(初六) 小寒 2101.1.20(廿一) 大寒 | 3.358083 | 2.645292 | 1.269457 |
return TextUtils.STEMS[offset % 10] + TextUtils.BRANCHES[offset % 12] | def get_gz_cn(offset: int) -> str | Get n-th(0-based) GanZhi | 15.932878 | 11.424667 | 1.394603 |
solar_date = MIN_SOLAR_DATE + datetime.timedelta(days=self._offset)
sy, sm, sd = solar_date.year, solar_date.month, solar_date.day
s_offset = (datetime.date(sy, sm, sd) - MIN_SOLAR_DATE).days
gz_year = TextUtils.STEMS[(self.year - 4) % 10] + TextUtils.BRANCHES[(self.year - 4) % ... | def _get_gz_ymd(self) | (sy, sm, sd) -> term / gz_year / gz_month / gz_day | 3.073848 | 2.959138 | 1.038765 |
def _getter(item):
if getter:
custom_getter = partial(getter, key=key)
return custom_getter(item)
else:
return partial(bget, key=key, default=default)(item)
return map(_getter, iterable) | def ifetch_single(iterable, key, default=EMPTY, getter=None) | getter() g(item, key):pass | 4.147286 | 4.116065 | 1.007585 |
birthday = LCalendars.cast_date(birthday, date)
if today:
today = LCalendars.cast_date(today, date)
else:
today = date.today()
return today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day)) | def actual_age_solar(birthday, today=None) | See more at https://stackoverflow.com/questions/2217488/age-from-birthdate-in-python/9754466#9754466
:param birthday:
:param today:
:return: | 2.656529 | 2.84001 | 0.935394 |
model['typedefs'] = {}
# bitmasks and basetypes
bitmasks = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'bitmask']
basetypes = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'basetype']
for typedef in bitmasks + b... | def model_typedefs(vk, model) | Fill the model with typedefs
model['typedefs'] = {'name': 'type', ...} | 3.096022 | 2.994365 | 1.033949 |
model['enums'] = {}
# init enums dict
enums_type = [x['@name'] for x in vk['registry']['types']['type']
if x.get('@category') == 'enum']
for name in enums_type:
model['enums'][name] = {}
# create enums
enums = [x for x in vk['registry']['enums']
if ... | def model_enums(vk, model) | Fill the model with enums
model['enums'] = {'name': {'item_name': 'item_value'...}, ...} | 2.960946 | 2.970748 | 0.996701 |
model['macros'] = {}
# API Macros
macros = [x for x in vk['registry']['enums']
if x.get('@type') not in ('bitmask', 'enum')]
# TODO: Check theses values
special_values = {'1000.0f': '1000.0',
'(~0U)': 0xffffffff,
'(~0ULL)': -1,
... | def model_macros(vk, model) | Fill the model with macros
model['macros'] = {'name': value, ...} | 4.434983 | 4.38555 | 1.011272 |
model['funcpointers'] = {}
funcs = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'funcpointer']
structs = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'struct']
for f in funcs:
pfn_name = f['name']
for s in... | def model_funcpointers(vk, model) | Fill the model with function pointer
model['funcpointers'] = {'pfn_name': 'struct_name'} | 3.130166 | 2.718625 | 1.151378 |
model['exceptions'] = {}
model['errors'] = {}
all_codes = model['enums']['VkResult']
success_names = set()
error_names = set()
commands = [x for x in vk['registry']['commands']['command']]
for command in commands:
successes = command.get('@successcodes', '').split(',')
... | def model_exceptions(vk, model) | Fill the model with exceptions and errors
model['exceptions'] = {val: 'name',...}
model['errors'] = {val: 'name',...} | 3.649147 | 3.3555 | 1.087512 |
model['constructors'] = []
structs = [x for x in vk['registry']['types']['type']
if x.get('@category') in {'struct', 'union'}]
def parse_len(member):
mlen = member.get('@len')
if not mlen:
return None
if ',' in mlen:
mlen = mlen.split(','... | def model_constructors(vk, model) | Fill the model with constructors
model['constructors'] = [{'name': 'x', 'members': [{'name': 'y'}].}] | 3.272239 | 3.194216 | 1.024426 |
def get_vk_extension_functions():
names = set()
for extension in get_extensions_filtered(vk):
for req in extension['require']:
if 'command' not in req:
continue
for command in req['command']:
cn = command['@nam... | def model_functions(vk, model) | Fill the model with functions | 2.9882 | 2.999527 | 0.996224 |
model['ext_functions'] = {'instance': {}, 'device': {}}
# invert the alias to better lookup
alias = {v: k for k, v in model['alias'].items()}
for extension in get_extensions_filtered(vk):
for req in extension['require']:
if not req.get('command'):
continue
... | def model_ext_functions(vk, model) | Fill the model with extensions functions | 4.460197 | 4.40966 | 1.011461 |
model['alias'] = {}
# types
for s in vk['registry']['types']['type']:
if s.get('@category', None) == 'handle' and s.get('@alias'):
model['alias'][s['@alias']] = s['@name']
# commands
for c in vk['registry']['commands']['command']:
if c.get('@alias'):... | def model_alias(vk, model) | Fill the model with alias since V1 | 3.864502 | 3.634897 | 1.063167 |
# Force extension require to be a list
for ext in get_extensions_filtered(vk):
req = ext['require']
if not isinstance(req, list):
ext['require'] = [req] | def format_vk(vk) | Format vk before using it | 7.734885 | 8.318834 | 0.929804 |
model = {}
vk = init()
format_vk(vk)
model_alias(vk, model)
model_typedefs(vk, model)
model_enums(vk, model)
model_macros(vk, model)
model_funcpointers(vk, model)
model_exceptions(vk, model)
model_constructors(vk, model)
model_functions(vk, model)
model_ext_function... | def generate_py() | Generate the python output file | 2.988096 | 2.978889 | 1.003091 |
include_libc_path = path.join(HERE, 'fake_libc_include')
include_vulkan_path = path.join(HERE, 'vulkan_include')
out_file = path.join(HERE, path.pardir, 'vulkan', 'vulkan.cdef.h')
header = path.join(include_vulkan_path, 'vulkan.h')
command = ['cpp',
'-std=c99',
'-... | def generate_cdef() | Generate the cdef output file | 2.696687 | 2.681022 | 1.005843 |
if apps.ready:
# We're running in a real Django unit test, don't do anything.
return
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
django.setup()
mock_django_connection(disabled_features) | def mock_django_setup(settings_module, disabled_features=None) | Must be called *AT IMPORT TIME* to pretend that Django is set up.
This is useful for running tests without using the Django test runner.
This must be called before any Django models are imported, or they will
complain. Call this from a module in the calling project at import time,
then be sure to impor... | 4.06262 | 4.824241 | 0.842126 |
db = connections.databases['default']
db['PASSWORD'] = '****'
db['USER'] = '**Database disabled for unit tests**'
ConnectionHandler.__getitem__ = MagicMock(name='mock_connection')
# noinspection PyUnresolvedReferences
mock_connection = ConnectionHandler.__getitem__.return_value
if disab... | def mock_django_connection(disabled_features=None) | Overwrite the Django database configuration with a mocked version.
This is a helper function that does the actual monkey patching. | 4.06852 | 4.045625 | 1.005659 |
for model in models:
yield model
# noinspection PyProtectedMember
for parent in model._meta.parents.keys():
for parent_model in find_all_models((parent,)):
yield parent_model | def find_all_models(models) | Yield all models and their parents. | 3.512642 | 2.596108 | 1.353041 |
patchers = []
for model in find_all_models(models):
if isinstance(model.save, Mock):
# already mocked, so skip it
continue
model_name = model._meta.object_name
patchers.append(_patch_save(model, model_name))
if hasattr(model, 'objects'):
... | def mocked_relations(*models) | Mock all related field managers to make pure unit tests possible.
The resulting patcher can be used just like one from the mock module:
As a test method decorator, a test class decorator, a context manager,
or by just calling start() and stop().
@mocked_relations(Dataset):
def test_dataset(self):
... | 3.445121 | 3.552434 | 0.969792 |
# noinspection PyUnusedLocal
def absorb_mocks(test_case, *args):
return target(test_case)
should_absorb = not (self.pass_mocks or isinstance(target, type))
result = absorb_mocks if should_absorb else target
for patcher in self.patchers:
result =... | def decorate_callable(self, target) | Called as a decorator. | 5.318318 | 4.975063 | 1.068995 |
return issubclass(arr.dtype.type, np.integer) or np.allclose(arr, np.round(arr)) | def _is_array_integer(arr) | Returns True if an array contains integers (integer type or near-int
float values) and False otherwise.
>>> _is_array_integer(np.arange(10))
True
>>> _is_array_integer(np.arange(7.0, 20.0, 1.0))
True
>>> _is_array_integer(np.arange(0, 1, 0.1))
False | 3.745403 | 5.394047 | 0.694359 |
if not column_fn:
return column_fn
if not callable(column_fn):
raise TypeError('column functions must be callable')
@functools.wraps(column_fn)
def wrapped(column):
try:
return column_fn(column)
except TypeError:
if isinstance(column, np.ndarr... | def _zero_on_type_error(column_fn) | Wrap a function on an np.ndarray to return 0 on a type error. | 2.886444 | 2.54285 | 1.135121 |
assert len(rows) > 0
if not _is_non_string_iterable(partials):
# Convert partials to tuple for comparison against row slice later
partials = [(partial,) for partial in partials]
# Construct mapping of partials to values in rows
mapping = {}
for row in rows:
mapping[tupl... | def _fill_with_zeros(partials, rows, zero=None) | Find and return values from rows for all partials. In cases where no
row matches a partial, zero is assumed as value. For a row, the first
(n-1) fields are assumed to be the partial, and the last field,
the value, where n is the total number of fields in each row. It is
assumed that there is a unique ro... | 4.16481 | 4.101922 | 1.015332 |
if len(label_list) == 0:
return []
elif not _is_non_string_iterable(label_list[0]):
# Assume everything is a label. If not, it'll be caught later.
return label_list
elif len(label_list) == 1:
return label_list[0]
else:
raise ValueError("Labels {} contain mor... | def _varargs_labels_as_list(label_list) | Return a list of labels for a list of labels or singleton list of list
of labels. | 4.192717 | 4.14324 | 1.011942 |
assert len(values) > 0
first, rest = values[0], values[1:]
for v in rest:
assert v == first
return first | def _assert_same(values) | Assert that all values are identical and return the unique value. | 2.966774 | 2.625654 | 1.129918 |
if not collect.__name__.startswith('<'):
return label + ' ' + collect.__name__
else:
return label | def _collected_label(collect, label) | Label of a collected column. | 6.412184 | 6.666797 | 0.961809 |
if isinstance(value, str):
return False
if hasattr(value, '__iter__'):
return True
if isinstance(value, collections.abc.Sequence):
return True
return False | def _is_non_string_iterable(value) | Whether a value is iterable. | 2.463776 | 2.20966 | 1.115002 |
if ticks is None:
ticks = axis.get_xticks()
if (np.array(ticks) == np.rint(ticks)).all():
ticks = np.rint(ticks).astype(np.int)
if max([len(str(tick)) for tick in ticks]) > max_width:
axis.set_xticklabels(ticks, rotation='vertical') | def _vertical_x(axis, ticks=None, max_width=5) | Switch labels to vertical if they are long. | 2.852728 | 2.428169 | 1.174847 |
warnings.warn("Table.empty(labels) is deprecated. Use Table(labels)", FutureWarning)
if labels is None:
return cls()
values = [[] for label in labels]
return cls(values, labels) | def empty(cls, labels=None) | Creates an empty table. Column labels are optional. [Deprecated]
Args:
``labels`` (None or list): If ``None``, a table with 0
columns is created.
If a list, each element is a column label in a table with
0 rows.
Returns:
A new ins... | 4.696503 | 4.588119 | 1.023623 |
warnings.warn("Table.from_rows is deprecated. Use Table(labels).with_rows(...)", FutureWarning)
return cls(labels).with_rows(rows) | def from_rows(cls, rows, labels) | Create a table from a sequence of rows (fixed-length sequences). [Deprecated] | 5.509145 | 4.527276 | 1.216879 |
if not records:
return cls()
labels = sorted(list(records[0].keys()))
columns = [[rec[label] for rec in records] for label in labels]
return cls().with_columns(zip(labels, columns)) | def from_records(cls, records) | Create a table from a sequence of records (dicts with fixed keys). | 4.182784 | 3.812028 | 1.09726 |
warnings.warn("Table.from_columns_dict is deprecated. Use Table().with_columns(...)", FutureWarning)
return cls().with_columns(columns.items()) | def from_columns_dict(cls, columns) | Create a table from a mapping of column labels to column values. [Deprecated] | 6.627221 | 5.079414 | 1.304721 |
# Look for .csv at the end of the path; use "," as a separator if found
try:
path = urllib.parse.urlparse(filepath_or_buffer).path
if 'data8.berkeley.edu' in filepath_or_buffer:
raise ValueError('data8.berkeley.edu requires authentication, '
... | def read_table(cls, filepath_or_buffer, *args, **vargs) | Read a table from a file or web address.
filepath_or_buffer -- string or file handle / StringIO; The string
could be a URL. Valid URL schemes include http,
ftp, s3, and file. | 3.9743 | 3.857967 | 1.030154 |
table = type(self)()
for label, column in zip(self.labels, columns):
self._add_column_and_format(table, label, column)
return table | def _with_columns(self, columns) | Create a table from a sequence of columns, copying column labels. | 5.522501 | 4.167133 | 1.325252 |
label = self._as_label(label)
table[label] = column
if label in self._formats:
table._formats[label] = self._formats[label] | def _add_column_and_format(self, table, label, column) | Add a column to table, copying the formatter from self. | 3.918236 | 3.313173 | 1.182624 |
t = cls()
labels = df.columns
for label in df.columns:
t.append_column(label, df[label])
return t | def from_df(cls, df) | Convert a Pandas DataFrame into a Table. | 4.995504 | 3.882743 | 1.286591 |
return cls().with_columns([(f, arr[f]) for f in arr.dtype.names]) | def from_array(cls, arr) | Convert a structured NumPy array into a Table. | 8.675438 | 6.984962 | 1.242016 |
if (isinstance(index_or_label, str)
and index_or_label not in self.labels):
raise ValueError(
'The column "{}" is not in the table. The table contains '
'these columns: {}'
.format(index_or_label, ', '.join(self.labels))
... | def column(self, index_or_label) | Return the values of a column as an array.
table.column(label) is equivalent to table[label].
>>> tiles = Table().with_columns(
... 'letter', make_array('c', 'd'),
... 'count', make_array(2, 4),
... )
>>> list(tiles.column('letter'))
['c', 'd']
... | 2.069267 | 2.148914 | 0.962936 |
dtypes = [col.dtype for col in self.columns]
if len(set(dtypes)) > 1:
dtype = object
else:
dtype = None
return np.array(self.columns, dtype=dtype).T | def values(self) | Return data in `self` as a numpy array.
If all columns are the same dtype, the resulting array
will have this dtype. If there are >1 dtypes in columns,
then the resulting array will have dtype `object`. | 3.894844 | 2.716207 | 1.433928 |
if not column_or_columns:
return np.array([fn(row) for row in self.rows])
else:
if len(column_or_columns) == 1 and \
_is_non_string_iterable(column_or_columns[0]):
warnings.warn(
"column lists are deprecated; pass ea... | def apply(self, fn, *column_or_columns) | Apply ``fn`` to each element or elements of ``column_or_columns``.
If no ``column_or_columns`` provided, `fn`` is applied to each row.
Args:
``fn`` (function) -- The function to apply.
``column_or_columns``: Columns containing the arguments to ``fn``
as either co... | 3.468616 | 3.914643 | 0.886062 |
if inspect.isclass(formatter):
formatter = formatter()
if callable(formatter) and not hasattr(formatter, 'format_column'):
formatter = _formats.FunctionFormatter(formatter)
if not hasattr(formatter, 'format_column'):
raise Exception('Expected Formatte... | def set_format(self, column_or_columns, formatter) | Set the format of a column. | 3.916272 | 3.901913 | 1.00368 |
self._columns.move_to_end(column_label, last=False)
return self | def move_to_start(self, column_label) | Move a column to the first in order. | 5.252047 | 4.396432 | 1.194616 |
if not row_or_table:
return
if isinstance(row_or_table, Table):
t = row_or_table
columns = list(t.select(self.labels)._columns.values())
n = t.num_rows
else:
if (len(list(row_or_table)) != self.num_columns):
rai... | def append(self, row_or_table) | Append a row or all rows of a table. An appended table must have all
columns of self. | 2.957577 | 2.927928 | 1.010127 |
# TODO(sam): Allow append_column to take in a another table, copying
# over formatter as needed.
if not isinstance(label, str):
raise ValueError('The column label must be a string, but a '
'{} was given'.format(label.__class__.__name__))
if not isins... | def append_column(self, label, values) | Appends a column to the table or replaces a column.
``__setitem__`` is aliased to this method:
``table.append_column('new_col', make_array(1, 2, 3))`` is equivalent to
``table['new_col'] = make_array(1, 2, 3)``.
Args:
``label`` (str): The label of the new column.
... | 4.466433 | 3.77545 | 1.18302 |
if isinstance(column_label, numbers.Integral):
column_label = self._as_label(column_label)
if isinstance(column_label, str) and isinstance(new_label, str):
column_label, new_label = [column_label], [new_label]
if len(column_label) != len(new_label):
r... | def relabel(self, column_label, new_label) | Changes the label(s) of column(s) specified by ``column_label`` to
labels in ``new_label``.
Args:
``column_label`` -- (single str or array of str) The label(s) of
columns to be changed to ``new_label``.
``new_label`` -- (single str or array of str): The label na... | 3.144957 | 3.035968 | 1.035899 |
if not row_or_row_indices:
return
if isinstance(row_or_row_indices, int):
rows_remove = [row_or_row_indices]
else:
rows_remove = row_or_row_indices
for col in self._columns:
self._columns[col] = [elem for i, elem in enumerate(self[... | def remove(self, row_or_row_indices) | Removes a row or multiple rows of a table in place. | 2.200516 | 2.126427 | 1.034842 |
table = type(self)()
for label in self.labels:
if shallow:
column = self[label]
else:
column = np.copy(self[label])
self._add_column_and_format(table, label, column)
return table | def copy(self, *, shallow=False) | Return a copy of a table. | 4.400815 | 3.542172 | 1.242406 |
labels = self._varargs_as_labels(column_or_columns)
table = type(self)()
for label in labels:
self._add_column_and_format(table, label, np.copy(self[label]))
return table | def select(self, *column_or_columns) | Return a table with only the columns in ``column_or_columns``.
Args:
``column_or_columns``: Columns to select from the ``Table`` as
either column labels (``str``) or column indices (``int``).
Returns:
A new instance of ``Table`` containing only selected columns.
... | 6.914381 | 8.823013 | 0.783676 |
exclude = _varargs_labels_as_list(column_or_columns)
return self.select([c for (i, c) in enumerate(self.labels)
if i not in exclude and c not in exclude]) | def drop(self, *column_or_columns) | Return a Table with only columns other than selected label or
labels.
Args:
``column_or_columns`` (string or list of strings): The header
names or indices of the columns to be dropped.
``column_or_columns`` must be an existing header name, or a
valid col... | 7.080813 | 9.481523 | 0.746801 |
column = self._get_column(column_or_label)
if distinct:
_, row_numbers = np.unique(column, return_index=True)
else:
row_numbers = np.argsort(column, axis=0, kind='mergesort')
assert (row_numbers < self.num_rows).all(), row_numbers
if descending:
... | def sort(self, column_or_label, descending=False, distinct=False) | Return a Table of rows sorted according to the values in a column.
Args:
``column_or_label``: the column whose values are used for sorting.
``descending``: if True, sorting will be in descending, rather than
ascending order.
``distinct``: if True, repeated ... | 2.617388 | 3.432199 | 0.762598 |
# Assume that a call to group with a list of labels is a call to groups
if _is_non_string_iterable(column_or_label) and \
len(column_or_label) != self._num_rows:
return self.groups(column_or_label, collect)
self = self.copy(shallow=True)
collect = _z... | def group(self, column_or_label, collect=None) | Group rows by unique values in a column; count or aggregate others.
Args:
``column_or_label``: values to group (column label or index, or array)
``collect``: a function applied to values in other columns for each group
Returns:
A Table with each row corresponding t... | 3.753934 | 3.936067 | 0.953727 |
# Assume that a call to groups with one label is a call to group
if not _is_non_string_iterable(labels):
return self.group(labels, collect=collect)
collect = _zero_on_type_error(collect)
columns = []
labels = self._as_labels(labels)
for label in labe... | def groups(self, labels, collect=None) | Group rows by multiple columns, count or aggregate others.
Args:
``labels``: list of column names (or indices) to group on
``collect``: a function applied to values in other columns for each group
Returns: A Table with each row corresponding to a unique combination of values i... | 5.349337 | 5.397839 | 0.991014 |
pivot_columns = _as_labels(pivot_columns)
selected = self.select(pivot_columns + [value_column])
grouped = selected.groups(pivot_columns, collect=lambda x:x)
# refine bins by taking a histogram over all the data
if bins is not None:
vargs['bins'] = bins
... | def pivot_bin(self, pivot_columns, value_column, bins=None, **vargs) | Form a table with columns formed by the unique tuples in pivot_columns
containing counts per bin of the values associated with each tuple in the value_column.
By default, bins are chosen to contain all values in the value_column. The
following named arguments from numpy.histogram can be applied... | 5.253665 | 5.960618 | 0.881396 |
rows, labels = [], labels or self.labels
for row in self.rows:
[rows.append((getattr(row, key), k, v)) for k, v in row.asdict().items()
if k != key and k in labels]
return type(self)([key, 'column', 'value']).with_rows(rows) | def stack(self, key, labels=None) | Takes k original columns and returns two columns, with col. 1 of
all column names and col. 2 of all associated data. | 5.897116 | 5.517445 | 1.068813 |
names = [op.__name__ for op in ops]
ops = [_zero_on_type_error(op) for op in ops]
columns = [[op(column) for op in ops] for column in self.columns]
table = type(self)().with_columns(zip(self.labels, columns))
stats = table._unused_label('statistic')
table[stats] ... | def stats(self, ops=(min, max, np.median, sum)) | Compute statistics for each column and place them in a table. | 5.77 | 5.087626 | 1.134124 |
if isinstance(index_or_label, str):
return index_or_label
if isinstance(index_or_label, numbers.Integral):
return self.labels[index_or_label]
else:
raise ValueError(str(index_or_label) + ' is not a label or index') | def _as_label(self, index_or_label) | Convert index to label. | 2.085261 | 1.950896 | 1.068873 |
original = label
existing = self.labels
i = 2
while label in existing:
label = '{}_{}'.format(original, i)
i += 1
return label | def _unused_label(self, label) | Generate an unused label. | 4.350905 | 3.77134 | 1.153676 |
c = column_or_label
if isinstance(c, collections.Hashable) and c in self.labels:
return self[c]
elif isinstance(c, numbers.Integral):
return self[c]
elif isinstance(c, str):
raise ValueError('label "{}" not in labels {}'.format(c, self.labels)... | def _get_column(self, column_or_label) | Convert label to column and check column length. | 3.255455 | 2.853604 | 1.140822 |
percentiles = [[_util.percentile(p, column)] for column in self.columns]
return self._with_columns(percentiles) | def percentile(self, p) | Return a new table with one row containing the pth percentile for
each column.
Assumes that each column only contains one type of value.
Returns a new table with one row and the same column labels.
The row contains the pth percentile of the original column, where the
pth percen... | 9.326922 | 15.407571 | 0.605347 |
n = self.num_rows
if k is None:
k = n
index = np.random.choice(n, k, replace=with_replacement, p=weights)
columns = [[c[i] for i in index] for c in self.columns]
sample = self._with_columns(columns)
return sample | def sample(self, k=None, with_replacement=True, weights=None) | Return a new table where k rows are randomly sampled from the
original table.
Args:
``k`` -- specifies the number of rows (``int``) to be sampled from
the table. Default is k equal to number of rows in the table.
``with_replacement`` -- (``bool``) By default True... | 2.886283 | 3.516151 | 0.820864 |
dist = self._get_column(distribution)
total = sum(dist)
assert total > 0 and np.all(dist >= 0), 'Counts or a distribution required'
dist = dist/sum(dist)
sample = np.random.multinomial(k, dist)
if proportions:
sample = sample / sum(sample)
lab... | def sample_from_distribution(self, distribution, k, proportions=False) | Return a new table with the same number of rows and a new column.
The values in the distribution column are define a multinomial.
They are replaced by sample counts/proportions in the output.
>>> sizes = Table(['size', 'count']).with_rows([
... ['small', 50],
... ['mediu... | 4.999546 | 5.156996 | 0.969469 |
if not 1 <= k <= self.num_rows - 1:
raise ValueError("Invalid value of k. k must be between 1 and the"
"number of rows - 1")
rows = np.random.permutation(self.num_rows)
first = self.take(rows[:k])
rest = self.take(rows[k:])
for ... | def split(self, k) | Return a tuple of two tables where the first table contains
``k`` rows randomly sampled and the second contains the remaining rows.
Args:
``k`` (int): The number of rows randomly sampled into the first
table. ``k`` must be between 1 and ``num_rows - 1``.
Raises:
... | 3.071336 | 3.308455 | 0.928329 |
self = self.copy()
self.append(row)
return self | def with_row(self, row) | Return a table with an additional row.
Args:
``row`` (sequence): A value for each column.
Raises:
``ValueError``: If the row length differs from the column count.
>>> tiles = Table(make_array('letter', 'count', 'points'))
>>> tiles.with_row(['c', 2, 3]).with_ro... | 5.880904 | 18.973318 | 0.309957 |
self = self.copy()
self.append(self._with_columns(zip(*rows)))
return self | def with_rows(self, rows) | Return a table with additional rows.
Args:
``rows`` (sequence of sequences): Each row has a value per column.
If ``rows`` is a 2-d array, its shape must be (_, n) for n columns.
Raises:
``ValueError``: If a row length differs from the column count.
>>> til... | 8.379806 | 17.639334 | 0.475064 |
# Ensure that if with_column is called instead of with_columns;
# no error is raised.
if rest:
return self.with_columns(label, values, *rest)
new_table = self.copy()
new_table.append_column(label, values)
return new_table | def with_column(self, label, values, *rest) | Return a new table with an additional or replaced column.
Args:
``label`` (str): The column label. If an existing label is used,
the existing column will be replaced in the new table.
``values`` (single value or sequence): If a single value, every
value ... | 4.16943 | 5.090837 | 0.819007 |
if len(labels_and_values) == 1:
labels_and_values = labels_and_values[0]
if isinstance(labels_and_values, collections.abc.Mapping):
labels_and_values = list(labels_and_values.items())
if not isinstance(labels_and_values, collections.abc.Sequence):
lab... | def with_columns(self, *labels_and_values) | Return a table with additional or replaced columns.
Args:
``labels_and_values``: An alternating list of labels and values or
a list of label-value pairs. If one of the labels is in
existing table, then every value in the corresponding column is
set t... | 1.921741 | 1.758785 | 1.092653 |
copy = self.copy()
copy.relabel(label, new_label)
return copy | def relabeled(self, label, new_label) | Return a new table with ``label`` specifying column label(s)
replaced by corresponding ``new_label``.
Args:
``label`` -- (str or array of str) The label(s) of
columns to be changed.
``new_label`` -- (str or array of str): The new label(s) of
colu... | 3.833959 | 8.562819 | 0.447745 |
if columns:
self = self.select(*columns)
if 'normed' in vargs:
vargs.setdefault('density', vargs.pop('normed'))
density = vargs.get('density', False)
tag = 'density' if density else 'count'
cols = list(self._columns.values())
_, bins = np... | def bin(self, *columns, **vargs) | Group values by bin and compute counts per bin by column.
By default, bins are chosen to contain all values in all columns. The
following named arguments from numpy.histogram can be applied to
specialize bin widths:
If the original table has n columns, the resulting binned table has
... | 3.48646 | 4.088552 | 0.852737 |
def format_using_as_html(v, label=False):
if not label and hasattr(v, 'as_html'):
return v.as_html()
else:
return format_fn(v, label)
return format_using_as_html | def _use_html_if_available(format_fn) | Use the value's HTML rendering if available, overriding format_fn. | 3.337164 | 3.12379 | 1.068306 |
formats = {s: self._formats.get(s, self.formatter) for s in self.labels}
cols = self._columns.items()
fmts = [formats[k].format_column(k, v[:max_rows]) for k, v in cols]
if as_html:
fmts = list(map(type(self)._use_html_if_available, fmts))
return fmts | def _get_column_formatters(self, max_rows, as_html) | Return one value formatting function per column.
Each function has the signature f(value, label=False) -> str | 4.693404 | 4.652972 | 1.008689 |
if not max_rows or max_rows > self.num_rows:
max_rows = self.num_rows
omitted = max(0, self.num_rows - max_rows)
labels = self._columns.keys()
fmts = self._get_column_formatters(max_rows, False)
rows = [[fmt(label, label=True) for fmt, label in zip(fmts, labe... | def as_text(self, max_rows=0, sep=" | ") | Format table as text. | 2.834067 | 2.748109 | 1.031279 |
if not max_rows or max_rows > self.num_rows:
max_rows = self.num_rows
omitted = max(0, self.num_rows - max_rows)
labels = self.labels
lines = [
(0, '<table border="1" class="dataframe">'),
(1, '<thead>'),
(2, '<tr>'),
(... | def as_html(self, max_rows=0) | Format table as HTML. | 2.483723 | 2.424304 | 1.02451 |
column = self._get_column(column_or_label)
index = {}
for key, row in zip(column, self.rows):
index.setdefault(key, []).append(row)
return index | def index_by(self, column_or_label) | Return a dict keyed by values in a column that contains lists of
rows corresponding to each value. | 2.841469 | 2.553915 | 1.112593 |
dt = np.dtype(list(zip(self.labels, (c.dtype for c in self.columns))))
arr = np.empty_like(self.columns[0], dt)
for label in self.labels:
arr[label] = self[label]
return arr | def to_array(self) | Convert the table to a structured NumPy array. | 3.625938 | 3.33367 | 1.087672 |
options = self.default_options.copy()
options.update(vargs)
if column_for_xticks is not None:
x_data, y_labels = self._split_column_and_labels(column_for_xticks)
x_label = self._as_label(column_for_xticks)
else:
x_data, y_labels = None, self.... | def plot(self, column_for_xticks=None, select=None, overlay=True, width=6, height=4, **vargs) | Plot line charts for the table.
Args:
column_for_xticks (``str/array``): A column containing x-axis labels
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each plot will be displayed separately.
vargs: Additional arg... | 2.800713 | 3.08156 | 0.908862 |
options = self.default_options.copy()
# Matplotlib tries to center the labels, but we already handle that
# TODO consider changing the custom centering code and using matplotlib's default
vargs['align'] = 'edge'
options.update(vargs)
xticks, labels = self._spli... | def bar(self, column_for_categories=None, select=None, overlay=True, width=6, height=4, **vargs) | Plot bar charts for the table.
Each plot is labeled using the values in `column_for_categories` and
one plot is produced for every other column (or for the columns
designated by `select`).
Every selected column except `column_for_categories` must be numerical.
Args:
... | 4.984945 | 5.183094 | 0.96177 |
self.group(column_label).bar(column_label, **vargs) | def group_bar(self, column_label, **vargs) | Plot a bar chart for the table.
The values of the specified column are grouped and counted, and one
bar is produced for each group.
Note: This differs from ``bar`` in that there is no need to specify
bar heights; the height of a category's bar is the number of copies
of that ca... | 6.133375 | 7.809093 | 0.785415 |
options = self.default_options.copy()
# Matplotlib tries to center the labels, but we already handle that
# TODO consider changing the custom centering code and using matplotlib's default
vargs['align'] = 'edge'
options.update(vargs)
yticks, labels = self._split... | def barh(self, column_for_categories=None, select=None, overlay=True, width=6, **vargs) | Plot horizontal bar charts for the table.
Args:
``column_for_categories`` (``str``): A column containing y-axis categories
used to create buckets for bar chart.
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each... | 4.59147 | 4.994057 | 0.919387 |
self.group(column_label).barh(column_label, **vargs) | def group_barh(self, column_label, **vargs) | Plot a horizontal bar chart for the table.
The values of the specified column are grouped and counted, and one
bar is produced for each group.
Note: This differs from ``barh`` in that there is no need to specify
bar heights; the size of a category's bar is the number of copies
... | 5.059006 | 7.060841 | 0.716488 |
for label in y_labels:
if not all(isinstance(x, numbers.Real) for x in self[label]):
raise ValueError("The column '{0}' contains non-numerical "
"values. A plot cannot be drawn for this column."
.format(label))
n = len(y_label... | def _visualize(self, x_label, y_labels, ticks, overlay, draw, annotate, width=6, height=4) | Generic visualization that overlays or separates the draw function.
Raises:
ValueError: The Table contains non-numerical values in columns
other than `column_for_categories` | 2.328172 | 2.244328 | 1.037358 |
column = None if column_or_label is None else self._get_column(column_or_label)
labels = [label for i, label in enumerate(self.labels) if column_or_label not in (i, label)]
return column, labels | def _split_column_and_labels(self, column_or_label) | Return the specified column and labels of other columns. | 3.032828 | 2.522636 | 1.202246 |
warnings.warn("pivot_hist is deprecated; use "
"hist(value_column_label, group=pivot_column_label), or "
"with side_by_side=True if you really want side-by-side "
"bars.")
pvt_labels = np.unique(self[pivot_column_label])
... | def pivot_hist(self, pivot_column_label, value_column_label, overlay=True, width=6, height=4, **vargs) | Draw histograms of each category in a column. | 2.681659 | 2.672596 | 1.003391 |
# Check for non-numerical values and raise a ValueError if any found
for col in self:
if any(isinstance(cell, np.flexible) for cell in self[col]):
raise ValueError("The column '{0}' contains non-numerical "
"values. A histogram cannot be drawn for... | def boxplot(self, **vargs) | Plots a boxplot for the table.
Every column must be numerical.
Kwargs:
vargs: Additional arguments that get passed into `plt.boxplot`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot
for additional arguments that can be passed into va... | 5.039465 | 5.115924 | 0.985055 |
if arr is None:
return lambda arr: percentile(p, arr)
if hasattr(p, '__iter__'):
return np.array([percentile(x, arr) for x in p])
if p == 0:
return min(arr)
assert 0 < p <= 100, 'Percentile requires a percent'
i = (p/100) * len(arr)
return sorted(arr)[math.ceil(i) - ... | def percentile(p, arr=None) | Returns the pth percentile of the input array (the value that is at
least as great as p% of the values in the array).
If arr is not provided, percentile returns itself curried with p
>>> percentile(74.9, [1, 3, 5, 9])
5
>>> percentile(75, [1, 3, 5, 9])
5
>>> percentile(75.1, [1, 3, 5, 9])
... | 2.901443 | 3.534684 | 0.820849 |
shade = rbound is not None or lbound is not None
shade_left = rbound is not None and lbound is not None
inf = 3.5 * sd
step = 0.1
rlabel = rbound
llabel = lbound
if rbound is None:
rbound = inf + mean
rlabel = "$\infty$"
if lbound is None:
lbound = -inf + mea... | def plot_normal_cdf(rbound=None, lbound=None, mean=0, sd=1) | Plots a normal curve with specified parameters and area below curve shaded
between ``lbound`` and ``rbound``.
Args:
``rbound`` (numeric): right boundary of shaded region
``lbound`` (numeric): left boundary of shaded region; by default is negative infinity
``mean`` (numeric): mean/expe... | 2.409583 | 2.552184 | 0.944126 |
proportions = sample_proportions(sample_size, table.column(label))
return table.with_column('Random Sample', proportions) | def proportions_from_distribution(table, label, sample_size,
column_name='Random Sample') | Adds a column named ``column_name`` containing the proportions of a random
draw using the distribution in ``label``.
This method uses ``np.random.multinomial`` to draw ``sample_size`` samples
from the distribution in ``table.column(label)``, then divides by
``sample_size`` to create the resulting colum... | 4.342202 | 6.536663 | 0.664284 |
from . import Table
df = table.to_df()
if subset is not None:
# Iterate through columns
subset = np.atleast_1d(subset)
if any([i not in df.columns for i in subset]):
err = np.where([i not in df.columns for i in subset])[0]
err = "Column mismatch: {0}".fo... | def table_apply(table, func, subset=None) | Applies a function to each column and returns a Table.
Uses pandas `apply` under the hood, then converts back to a Table
Args:
table : instance of Table
The table to apply your function to
func : function
Any function that will work with DataFrame.apply
subset :... | 3.032962 | 3.109543 | 0.975372 |
if start is None:
assert not array, "Please pass starting values explicitly when array=True"
arg_count = f.__code__.co_argcount
assert arg_count > 0, "Please pass starting values explicitly for variadic functions"
start = [0] * arg_count
if not hasattr(start, '__len__'):
... | def minimize(f, start=None, smooth=False, log=None, array=False, **vargs) | Minimize a function f of one or more arguments.
Args:
f: A function that takes numbers and returns a number
start: A starting value or list of starting values
smooth: Whether to assume that f is smooth and use first-order info
log: Logging function called on the result of optimiz... | 2.932294 | 2.986574 | 0.981825 |
if len(s) >= 2 and isinstance(s[0], _number) and isinstance(s[0], _number):
lat, lon = s[1], s[0]
return [(lat, lon)]
else:
return [lat_lon for sub in s for lat_lon in _lat_lons_from_geojson(sub)] | def _lat_lons_from_geojson(s) | Return a latitude-longitude pairs from nested GeoJSON coordinates.
GeoJSON coordinates are always stored in (longitude, latitude) order. | 2.989637 | 2.903578 | 1.029639 |
if not self._folium_map:
self.draw()
return self._inline_map(self._folium_map, self._width, self._height) | def as_html(self) | Generate HTML to display map. | 6.831757 | 4.833715 | 1.413355 |
IPython.display.display(IPython.display.HTML(self.as_html())) | def show(self) | Publish HTML. | 6.111886 | 4.454967 | 1.371926 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.