code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
from . import LocalFile
if os.path.isdir(filename) and self.source is None:
raise ValueError("Cannot write this object to "
"directory %s without an explicit filename." % filename)
target = get_target_path(filename, self.source)
if (en... | def put(self, filename, encoding=None) | Write the file to the given path
Args:
filename(str): path to write this file to
Returns:
LocalFile: reference to the copy of the file stored at ``filename`` | 4.689109 | 4.602537 | 1.01881 |
access_type = self._get_access_type(mode)
if access_type == 't' and encoding is not None and encoding != self.encoded_with:
warnings.warn('Attempting to decode %s as "%s", but encoding is declared as "%s"'
% (self, encoding, self.encoded_with))
if... | def open(self, mode='r', encoding=None) | Return file-like object
Args:
mode (str): access mode (only reading modes are supported)
encoding (str): text decoding method for text access (default: system default)
Returns:
io.BytesIO OR io.TextIOWrapper: buffer accessing the file as bytes or characters | 3.422565 | 3.386127 | 1.010761 |
if os.path.exists(destination):
if not os.path.isdir(destination):
raise OSError('Cannot write to requested destination %s - file exists' % destination)
return os.path.join(destination, os.path.basename(origname))
else:
destdir = os.path.abspath(os.path.join(destination,... | def get_target_path(destination, origname) | Implements the directory/path semantics of linux mv/cp etc.
Examples:
>>> import os
>>> os.makedirs('./a')
>>> get_target_path('./a', '/tmp/myfile')
'./myfile'
>>> get_target_path('./a/b', '/tmp/myfile')
'./a/b'
Raises:
OSError: if neither destination NO... | 2.199093 | 2.380827 | 0.923667 |
from . import LocalFile
target = get_target_path(filename, self.source)
with self.open('rb') as infile, open(target, 'wb') as outfile:
shutil.copyfileobj(infile, outfile)
return LocalFile(target) | def put(self, filename) | Write the file to the given path
Args:
filename(str): path to write this file to
Returns:
LocalFile: reference to the copy of the file stored at ``filename`` | 4.237209 | 4.595626 | 0.922009 |
access_type = None
for char in mode: # figure out whether it's binary or text access
if char in 'bt':
if access_type is not None:
raise IOError('File mode "%s" contains contradictory flags' % mode)
access_type = char
e... | def _get_access_type(self, mode) | Make sure mode is appropriate; return 'b' for binary access and 't' for text | 5.098997 | 4.182472 | 1.219135 |
if inspect.ismethod(func):
func = func.__func__
elif not inspect.isroutine(func):
raise TypeError("'{!r}' is not a Python function".format(func))
# AMVMOD: deal with python 2 builtins that don't define these
code = getattr(func, '__code__', None)
closure = getattr(func, '__clo... | def getclosurevars(func) | Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
Note:
Modified function from the ... | 3.071491 | 2.944212 | 1.04323 |
target = get_target_path(destination, self.localpath)
shutil.copytree(self.localpath, target) | def put(self, destination) | Copy the referenced directory to this path
The semantics of this command are similar to unix ``cp``: if ``destination`` already
exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If
it does not already exist, the directory will be renamed to this path (the ... | 5.516479 | 8.102945 | 0.680799 |
target = get_target_path(destination, self.dirname)
valid_paths = (self.dirname, './%s' % self.dirname)
with tarfile.open(self.archive_path, 'r:*') as tf:
members = []
for tarinfo in tf:
# Get only files under the directory `self.dirname`
... | def put(self, destination) | Copy the referenced directory to this path
Note:
This ignores anything not in the desired directory, given by ``self.dirname``.
Args:
destination (str): path to put this directory (which must NOT already exist)
References:
https://stackoverflow.com/a/826108... | 3.562063 | 3.56863 | 0.99816 |
if not self._fetched:
self._fetch()
DirectoryArchive.put(self, destination) | def put(self, destination) | Copy the referenced directory to this path
Args:
destination (str): path to put this directory (which must NOT already exist) | 11.104877 | 13.915688 | 0.798011 |
from pathlib import Path
root = Path(native_str(target))
for outputpath, outputfile in job.get_output().items():
path = Path(native_str(outputpath))
# redirect absolute paths into the appropriate subdirectory
if path.is_absolute():
i... | def dump_all_outputs(self, job, target, abspaths=None) | Default dumping strategy - potentially slow for large numbers of files
Subclasses should offer faster implementations, if available | 3.280457 | 3.363811 | 0.97522 |
if isinstance(command, PythonCall):
return PythonJob(self, image, command, **kwargs)
else:
return Job(self, image, command, **kwargs) | def launch(self, image, command, **kwargs) | Create a job on this engine
Args:
image (str): name of the docker image to launch
command (str): shell command to run | 4.147234 | 5.116932 | 0.810492 |
if ord(char) < 128:
return 1
elif unicodedata.east_asian_width(char) in ('F', 'W'):
return 2
elif unicodedata.category(char) in ('Mn',):
return 0
else:
return 1 | def char_width(char) | Get the display length of a unicode character. | 2.179101 | 2.317898 | 0.940119 |
text = unicodedata.normalize('NFD', text)
return sum(char_width(char) for char in text) | def display_len(text) | Get the display length of a string. This can differ from the character
length if the string contains wide characters. | 4.799141 | 5.256269 | 0.913032 |
return tuple(name for name in names
if regex.search(name) is not None) | def filter_regex(names, regex) | Return a tuple of strings that match the regular expression pattern. | 5.13544 | 4.209638 | 1.219925 |
return tuple(name for name in names
if fnmatch.fnmatch(name, pattern)) | def filter_wildcard(names, pattern) | Return a tuple of strings that match a shell-style wildcard pattern. | 4.438235 | 3.860858 | 1.149546 |
if '__doc__' in attrs:
lstrip = getattr(obj.__doc__, 'lstrip', False)
return lstrip and any(lstrip()) | def match(self, obj, attrs) | Only match if the object contains a non-empty docstring. | 9.142226 | 6.651422 | 1.374477 |
to_run = self.prepare_namespace(func)
result = to_run(*self.args, **self.kwargs)
return result | def run(self, func=None) | Evaluates the packaged function as func(*self.args,**self.kwargs)
If func is a method of an object, it's accessed as getattr(self.obj,__name__).
If it's a user-defined function, it needs to be passed in here because it can't
be serialized.
Returns:
object: function's return ... | 6.089868 | 5.910115 | 1.030414 |
if self.is_imethod:
to_run = getattr(self.obj, self.imethod_name)
else:
to_run = func
for varname, modulename in self.global_modules.items():
to_run.__globals__[varname] = __import__(modulename)
if self.global_closure:
to_run.__gl... | def prepare_namespace(self, func) | Prepares the function to be run after deserializing it.
Re-associates any previously bound variables and modules from the closure
Returns:
callable: ready-to-call function | 3.390342 | 3.183789 | 1.064876 |
results = []
add = results.append
add('.. list-table:: %s' % title)
add(' :header-rows: 1')
if columns:
add(' :widths: %s' % (','.join(str(c) for c in columns)))
add('')
add(' - * %s' % headers[0])
for h in headers[1:]:
add(' * %s' % h)
for row in data:... | def make_list_table(headers, data, title='', columns=None) | Build a list-table directive.
:param headers: List of header values.
:param data: Iterable of row data, yielding lists or tuples with rows.
:param title: Optional text to show as the table title.
:param columns: Optional widths for the columns. | 1.818259 | 1.844312 | 0.985874 |
header_names = [h[0] for h in headers]
header_keys = [h[1] for h in headers]
row_data = (
[d.get(k) for k in header_keys]
for d in data
)
return make_list_table(header_names, row_data, title, columns) | def make_list_table_from_mappings(headers, data, title, columns=None) | Build a list-table directive.
:param headers: List of tuples containing header title and key value.
:param data: Iterable of row data, yielding mappings with rows.
:param title: Optional text to show as the table title.
:param columns: Optional widths for the columns. | 2.534463 | 2.540297 | 0.997703 |
'Format a decimal.Decimal like to 2 decimal places.'
if not isinstance(value, Decimal):
value = Decimal(str(value))
return value.quantize(TWOPLACES) | def decimal_format(value, TWOPLACES=Decimal(100) ** -2) | Format a decimal.Decimal like to 2 decimal places. | 4.395307 | 2.704621 | 1.62511 |
'''Display two radio buttons for turning notifications on or off.
The default value is is have alerts_on = True.
'''
default_alert_value = True
if not profile:
alerts_on = True
else:
notifications = profile.get('notifications', {})
alerts_on = notifications.get(obj_type, ... | def notification_preference(obj_type, profile) | Display two radio buttons for turning notifications on or off.
The default value is is have alerts_on = True. | 5.587654 | 2.838047 | 1.968838 |
'''If the committee id no longer exists in mongo for some reason,
this function returns None.
'''
if 'committee_id' in self:
_id = self['committee_id']
return self.document._old_roles_committees.get(_id)
else:
return self | def committee_object(self) | If the committee id no longer exists in mongo for some reason,
this function returns None. | 9.660376 | 4.501205 | 2.146175 |
'''Return old roles, grouped first by term, then by chamber,
then by type.'''
wrapper = self._old_role_wrapper
chamber_getter = operator.methodcaller('get', 'chamber')
for term, roles in self.get('old_roles', {}).items():
chamber_roles = defaultdict(lambda: defaultdic... | def old_roles_manager(self) | Return old roles, grouped first by term, then by chamber,
then by type. | 4.447371 | 3.054967 | 1.455784 |
name = re.sub(
r'^(Senator|Representative|Sen\.?|Rep\.?|'
'Hon\.?|Right Hon\.?|Mr\.?|Mrs\.?|Ms\.?|L\'hon\.?|'
'Assembly(member|man|woman)) ',
'',
name)
return name.strip().lower().replace('.', '') | def _normalize(self, name) | Normalizes a legislator name by stripping titles from the front,
converting to lowercase and removing punctuation. | 10.195889 | 8.413989 | 1.211778 |
name, obj = legislator, legislator['_id']
if (legislator['roles'] and legislator['roles'][0]['term'] ==
self._term and legislator['roles'][0]['type'] == 'member'):
chamber = legislator['roles'][0]['chamber']
else:
try:
chamber = l... | def _learn(self, legislator) | Expects a dictionary with full_name, first_name, last_name and
middle_name elements as key.
While this can grow quickly, we should never be dealing with
more than a few hundred legislators at a time so don't worry about
it. | 1.972569 | 1.962679 | 1.005039 |
try:
return self._manual[chamber][name]
except KeyError:
pass
if chamber == 'joint':
chamber = None
try:
return self._codes[chamber][name]
except KeyError:
pass
if chamber not in self._names:
... | def match(self, name, chamber=None) | If this matcher has uniquely seen a matching name, return its
value. Otherwise, return None.
If chamber is set then the search will be limited to legislators
with matching chamber. If chamber is None then the search
will be cross-chamber. | 3.539885 | 3.428743 | 1.032415 |
# act of importing puts it into the registry
try:
module = importlib.import_module(mod_path)
except ImportError as e:
raise ScrapeError("could not import %s" % mod_path, e)
# now find the class within the module
ScraperClass = None
for k, v in module.__dict__.items():
... | def get_scraper(mod_path, scraper_type) | import a scraper from the scraper registry | 2.565239 | 2.497861 | 1.026975 |
types = ('bill', 'committee', 'person', 'vote', 'event')
for type in types:
schema_path = os.path.join(os.path.split(__file__)[0],
'../schemas/%s.json' % type)
self._schema[type] = json.load(open(schema_path))
self._sc... | def _load_schemas(self) | load all schemas into schema dict | 4.149538 | 3.977555 | 1.043238 |
if latest_only:
if session != self.metadata['terms'][-1]['sessions'][-1]:
raise NoDataForPeriod(session)
for t in self.metadata['terms']:
if session in t['sessions']:
return True
raise NoDataForPeriod(session) | def validate_session(self, session, latest_only=False) | Check that a session is present in the metadata dictionary.
raises :exc:`~billy.scrape.NoDataForPeriod` if session is invalid
:param session: string representing session to check | 5.129236 | 3.700078 | 1.386251 |
if latest_only:
if term == self.metadata['terms'][-1]['name']:
return True
else:
raise NoDataForPeriod(term)
for t in self.metadata['terms']:
if term == t['name']:
return True
raise NoDataForPeriod(ter... | def validate_term(self, term, latest_only=False) | Check that a term is present in the metadata dictionary.
raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid
:param term: string representing term to check
:param latest_only: if True, will raise exception if term is not
the current term (default: ... | 3.408191 | 2.403957 | 1.417742 |
self['sources'].append(dict(url=url, **kwargs)) | def add_source(self, url, **kwargs) | Add a source URL from which data related to this object was scraped.
:param url: the location of the source | 5.530247 | 9.435826 | 0.58609 |
'''Guess where the ends of the columns lie.
'''
ends = collections.Counter()
for line in self.text.splitlines():
for matchobj in re.finditer('\s{2,}', line.lstrip()):
ends[matchobj.end()] += 1
return ends | def _get_column_ends(self) | Guess where the ends of the columns lie. | 5.275315 | 4.105668 | 1.284886 |
'''Use the guessed ends to guess the boundaries of the plain
text columns.
'''
# Try to figure out the most common column boundaries.
ends = self._get_column_ends()
if not ends:
# If there aren't even any nontrivial sequences of whitespace
# dividi... | def _get_column_boundaries(self) | Use the guessed ends to guess the boundaries of the plain
text columns. | 5.770529 | 4.87815 | 1.182934 |
'''Using self.boundaries, extract cells from the given line.
'''
for boundary in self.boundaries:
cell = line.lstrip()[boundary].strip()
if cell:
for cell in re.split('\s{3,}', cell):
yield cell
else:
yield N... | def getcells(self, line) | Using self.boundaries, extract cells from the given line. | 6.46312 | 3.791417 | 1.704671 |
'''Returns an iterator of row tuples.
'''
for line in self.text.splitlines():
yield tuple(self.getcells(line)) | def rows(self) | Returns an iterator of row tuples. | 8.664966 | 5.827564 | 1.486893 |
'''Returns an interator of all cells in the table.
'''
for line in self.text.splitlines():
for cell in self.getcells(line):
yield cell | def cells(self) | Returns an interator of all cells in the table. | 6.859457 | 4.023094 | 1.705021 |
'A generator of previous page integers.'
skip = self.skip
if skip == 0:
return 0
count, remainder = divmod(skip, self.limit)
return count | def _previous_pages_count(self) | A generator of previous page integers. | 8.64642 | 6.398818 | 1.351253 |
'A generator of previous page integers.'
count = self._previous_pages_count() + 1
for i in reversed(range(1, count)):
yield i | def previous_pages_numbers(self) | A generator of previous page integers. | 8.558461 | 5.937204 | 1.441497 |
'''"Showing 40 - 50 of 234 results
^
'''
count = self.count
range_end = self.range_start + self.limit - 1
if count < range_end:
range_end = count
return range_end | def range_end(self) | "Showing 40 - 50 of 234 results
^ | 8.746703 | 3.340226 | 2.618596 |
'''Returns a generator of tuples (string, page_number, clickable),
where `string` is the text of the html link, `page_number` is
the number of the page the link points to, and `clickable` is
a boolean indicating whether the link is clickable or not.
'''
div, mod = divmod(... | def pagination_data(self, max_number_of_links=7) | Returns a generator of tuples (string, page_number, clickable),
where `string` is the text of the html link, `page_number` is
the number of the page the link points to, and `clickable` is
a boolean indicating whether the link is clickable or not. | 2.332299 | 2.142844 | 1.088413 |
_clear_scraped_data(options.output_dir, scraper_type)
scraper = _get_configured_scraper(scraper_type, options, metadata)
ua_email = os.environ.get('BILLY_UA_EMAIL')
if ua_email and scraper:
scraper.user_agent += ' ({})'.format(ua_email)
if not scraper:
return [{
"ty... | def _run_scraper(scraper_type, options, metadata) | scraper_type: bills, legislators, committees, votes | 3.827433 | 3.700697 | 1.034246 |
meta = db.metadata.find_one({'_id': abbr})
current_term = meta['terms'][-1]
current_session = current_term['sessions'][-1]
for bill in db.bills.find({settings.LEVEL_FIELD: abbr}):
if bill['session'] == current_session:
bill['_current_session'] = True
else:
b... | def populate_current_fields(abbr) | Set/update _current_term and _current_session fields on all bills
for a given location. | 2.777827 | 2.281077 | 1.21777 |
self._reset_sequence()
for item in item_list:
key = self.nondup_key_for_item(item)
self.ids[key] = item[self.id_key] | def learn_ids(self, item_list) | read in already set ids on objects | 5.772347 | 5.170711 | 1.116355 |
self._reset_sequence()
for item in item_list:
key = self.nondup_key_for_item(item)
item[self.id_key] = self.ids.get(key) or self._get_next_id() | def set_ids(self, item_list) | set ids on an object, using internal mapping then new ids | 5.264282 | 4.485559 | 1.173607 |
# for all current legislators
for legislator in db.legislators.find({'roles': {'$elemMatch': {
'term': current_term, settings.LEVEL_FIELD: abbr}}}):
# for all committee roles
for role in legislator['roles']:
if (role['type'] == 'committee member' and
... | def import_committees_from_legislators(current_term, abbr) | create committees from legislators that have committee roles | 2.493239 | 2.481833 | 1.004596 |
self['sponsors'].append(dict(type=type, name=name, **kwargs)) | def add_sponsor(self, type, name, **kwargs) | Associate a sponsor with this bill.
:param type: the type of sponsorship, e.g. 'primary', 'cosponsor'
:param name: the name of the sponsor as provided by the official source | 3.803767 | 5.705123 | 0.666728 |
if not mimetype:
raise ValueError('mimetype parameter to add_version is required')
if on_duplicate != 'ignore':
if url in self._seen_versions:
if on_duplicate == 'error':
raise ValueError('duplicate version url %s' % url)
... | def add_version(self, name, url, mimetype=None, on_duplicate='error',
**kwargs) | Add a version of the text of this bill.
:param name: a name given to this version of the text, e.g.
'As Introduced', 'Version 2', 'As amended', 'Enrolled'
:param url: the location of this version on the legislative website.
:param mimetype: MIME type of the document
... | 2.479247 | 2.336777 | 1.060969 |
def _cleanup_list(obj, default):
if not obj:
obj = default
elif isinstance(obj, string_types):
obj = [obj]
elif not isinstance(obj, list):
obj = list(obj)
return obj
type = _cleanup_list(type, ['ot... | def add_action(self, actor, action, date, type=None, committees=None,
legislators=None, **kwargs) | Add an action that was performed on this bill.
:param actor: a string representing who performed the action.
If the action is associated with one of the chambers this
should be 'upper' or 'lower'. Alternatively, this could be
the name of a committee, a specific legislator, or an o... | 2.534014 | 2.582878 | 0.981082 |
companion = {'bill_id': bill_id,
'session': session or self['session'],
'chamber': chamber}
self['companions'].append(companion) | def add_companion(self, bill_id, session=None, chamber=None) | Associate another bill with this one.
If session isn't set it will be set to self['session']. | 2.935997 | 2.589039 | 1.13401 |
'''
Context:
all_metadata
Templates:
- billy/web/public/homepage.html
'''
all_metadata = db.metadata.find()
return render(request, templatename('homepage'),
dict(all_metadata=all_metadata)) | def homepage(request) | Context:
all_metadata
Templates:
- billy/web/public/homepage.html | 8.74686 | 4.044984 | 2.162396 |
'''
Context:
- all_metadata
Templates:
- billy/web/public/downloads.html
'''
all_metadata = sorted(db.metadata.find(), key=lambda x: x['name'])
return render(request, 'billy/web/public/downloads.html',
{'all_metadata': all_metadata}) | def downloads(request) | Context:
- all_metadata
Templates:
- billy/web/public/downloads.html | 4.137932 | 2.462642 | 1.680282 |
'''
Context:
- request
- lat
- long
- located
- legislators
Templates:
- billy/web/public/find_your_legislator_table.html
'''
# check if lat/lon are set
# if leg_search is set, they most likely don't have ECMAScript enabled.
# XXX: fallback b... | def find_your_legislator(request) | Context:
- request
- lat
- long
- located
- legislators
Templates:
- billy/web/public/find_your_legislator_table.html | 4.287927 | 3.665498 | 1.169807 |
for legislator in db.legislators.find(
{'roles': {'$elemMatch':
{settings.LEVEL_FIELD: abbr, 'term': current_term}}}):
active_role = legislator['roles'][0]
if not active_role.get('end_date') and active_role['type'] == 'member':
legislator['active'] = True... | def activate_legislators(current_term, abbr) | Sets the 'active' flag on legislators and populates top-level
district/chamber/party fields for currently serving legislators. | 2.496595 | 2.380281 | 1.048866 |
self['roles'].append(dict(role=role, term=term,
start_date=start_date,
end_date=end_date, **kwargs)) | def add_role(self, role, term, start_date=None, end_date=None,
**kwargs) | Examples:
leg.add_role('member', term='2009', chamber='upper',
party='Republican', district='10th') | 2.580604 | 2.692213 | 0.958544 |
office_dict = dict(type=type, address=address, name=name, phone=phone,
fax=fax, email=email, **kwargs)
self['offices'].append(office_dict) | def add_office(self, type, name, address=None, phone=None, fax=None,
email=None, **kwargs) | Allowed office types:
capitol
district | 2.362842 | 2.617931 | 0.902561 |
# This data should change very rarely and is queried very often so
# cache it here
abbr = abbr.lower()
if abbr in __metadata:
return __metadata[abbr]
rv = db.metadata.find_one({'_id': abbr})
__metadata[abbr] = rv
return rv | def metadata(abbr, __metadata=__metadata) | Grab the metadata for the given two-letter abbreviation. | 5.464816 | 5.380319 | 1.015705 |
'''Creates the path if it doesn't exist'''
old_dir = os.getcwd()
try:
os.makedirs(path)
except OSError:
pass
os.chdir(path)
try:
yield
finally:
os.chdir(old_dir) | def cd(path) | Creates the path if it doesn't exist | 2.630539 | 2.648121 | 0.993361 |
pdict = {}
for k, v in schema['properties'].items():
pdict[k] = {}
if 'items' in v and 'properties' in v['items']:
pdict[k] = _get_property_dict(v['items'])
pdict[settings.LEVEL_FIELD] = {}
return pdict | def _get_property_dict(schema) | given a schema object produce a nested dictionary of fields | 2.887828 | 2.765154 | 1.044364 |
if '_id' in obj:
raise ValueError("object already has '_id' field")
# add created_at/updated_at on insert
obj['created_at'] = datetime.datetime.utcnow()
obj['updated_at'] = obj['created_at']
if obj['_type'] == 'person' or obj['_type'] == 'legislator':
collection = db.legislato... | def insert_with_id(obj) | Generates a unique ID for the supplied legislator/committee/bill
and inserts it into the appropriate collection. | 2.462316 | 2.354392 | 1.045839 |
# need_save = something has changed
need_save = False
locked_fields = old.get('_locked_fields', [])
for key, value in new.items():
# don't update locked fields
if key in locked_fields:
continue
if old.get(key) != value:
if sneaky_update_filter and... | def update(old, new, collection, sneaky_update_filter=None) | update an existing object with a new one, only saving it and
setting updated_at if something has changed
old
old object
new
new object
collection
collection to save changed object to
sneaky_update_filter
a filter for updates to obj... | 2.990915 | 3.107806 | 0.962388 |
for key in ('date', 'when', 'end', 'start_date', 'end_date'):
value = obj.get(key)
if value:
try:
obj[key] = _timestamp_to_dt(value)
except TypeError:
raise TypeError("expected float for %s, got %s" % (key, value))
for key in ('source... | def convert_timestamps(obj) | Convert unix timestamps in the scraper output to python datetimes
so that they will be saved properly as Mongo datetimes. | 3.6569 | 3.636091 | 1.005723 |
if obj['_type'] in ('person', 'legislator'):
for key in ('first_name', 'last_name'):
if key not in obj or not obj[key]:
# Need to split
(obj['first_name'], obj['last_name'],
obj['suffixes']) = name_tools.split(obj['full_name'])[1:]
... | def split_name(obj) | If the supplied legislator/person object is missing 'first_name'
or 'last_name' then use name_tools to split. | 4.918297 | 3.251404 | 1.512669 |
new_obj = {}
for key, value in obj.items():
if key in fields or key.startswith('_'):
# if there's a subschema apply it to a list or subdict
if fields.get(key):
if isinstance(value, list):
value = [_make_plus_helper(item, fields[key])
... | def _make_plus_helper(obj, fields) | add a + prefix to any fields in obj that aren't in fields | 4.518397 | 4.173007 | 1.082767 |
fields = standard_fields.get(obj['_type'], dict())
return _make_plus_helper(obj, fields) | def make_plus_fields(obj) | Add a '+' to the key of non-standard fields.
dispatch to recursive _make_plus_helper based on _type field | 10.442364 | 5.368358 | 1.945169 |
'''
This particular model needs its own constructor in order to take
advantage of the metadata cache in billy.util, which would otherwise
return unwrapped objects.
'''
obj = get_metadata(abbr)
if obj is None:
msg = 'No metadata found for abbreviation %... | def get_object(cls, abbr) | This particular model needs its own constructor in order to take
advantage of the metadata cache in billy.util, which would otherwise
return unwrapped objects. | 10.038347 | 2.609489 | 3.846863 |
'''Return an iterable of committees with all the
legislators cached for reference in the Committee model.
So do a "select_related" operation on committee members.
'''
committees = list(self.committees(*args, **kwargs))
legislators = self.legislators({'active': True},
... | def committees_legislators(self, *args, **kwargs) | Return an iterable of committees with all the
legislators cached for reference in the Committee model.
So do a "select_related" operation on committee members. | 5.681371 | 3.695935 | 1.537194 |
rd = {}
for f in fields:
v = d.get(f, None)
if isinstance(v, (str, unicode)):
v = v.encode('utf8')
elif isinstance(v, list):
v = delimiter.join(v)
rd[f] = v
return rd | def extract_fields(d, fields, delimiter='|') | get values out of an object ``d`` for saving to a csv | 2.187695 | 2.2952 | 0.953161 |
'''
Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_preview_row.html
'''
# get fixed ve... | def bill(request, abbr, session, bill_id) | Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_preview_row.html | 3.370725 | 2.512445 | 1.341611 |
'''
Context:
- abbr
- metadata
- bill
- vote
- nav_active
Templates:
- vote.html
'''
vote = db.votes.find_one(vote_id)
if vote is None:
raise Http404('no such vote: {0}'.format(vote_id))
bill = vote.bill()
return render(request, t... | def vote(request, abbr, vote_id) | Context:
- abbr
- metadata
- bill
- vote
- nav_active
Templates:
- vote.html | 4.880312 | 3.407379 | 1.432277 |
'''
Context:
- abbr
- session
- bill
- version
- metadata
- nav_active
Templates:
- billy/web/public/document.html
'''
# get fixed version
fixed_bill_id = fix_bill_id(bill_id)
# redirect if URL's id isn't fixed id without spaces
if... | def document(request, abbr, session, bill_id, doc_id) | Context:
- abbr
- session
- bill
- version
- metadata
- nav_active
Templates:
- billy/web/public/document.html | 3.508482 | 2.891928 | 1.213198 |
'''
Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc.
'''
def func(request, abbr, session, bill_id, key):
# get fixed version
... | def show_all(key) | Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc. | 4.830171 | 2.912208 | 1.658594 |
'''
Context:
If GET parameters are given:
- search_text
- form (FilterBillsForm)
- long_description
- description
- get_params
Otherwise, the only context item is an unbound FilterBillsForm.
Templates:
... | def get_context_data(self, *args, **kwargs) | Context:
If GET parameters are given:
- search_text
- form (FilterBillsForm)
- long_description
- description
- get_params
Otherwise, the only context item is an unbound FilterBillsForm.
Templates:
- Are specified i... | 3.122077 | 2.501278 | 1.248192 |
'''Handle submission of the region selection form in the base template. '''
form = get_region_select_form(request.GET)
abbr = form.data.get('abbr')
if not abbr or len(abbr) != 2:
return redirect('homepage')
return redirect('region', abbr=abbr) | def region_selection(request) | Handle submission of the region selection form in the base template. | 5.565551 | 3.928937 | 1.416554 |
'''
Context:
- abbr
- metadata
- sessions
- chambers
- joint_committee_count
- geo_bounds
- nav_active
Templates:
- bill/web/public/region.html
'''
report = db.reports.find_one({'_id': abbr})
try:
meta = Metadata.get_object... | def region(request, abbr) | Context:
- abbr
- metadata
- sessions
- chambers
- joint_committee_count
- geo_bounds
- nav_active
Templates:
- bill/web/public/region.html | 3.457251 | 2.962106 | 1.16716 |
'''
Context:
- search_text
- abbr
- metadata
- found_by_id
- bill_results
- more_bills_available
- legislators_list
- nav_active
Tempaltes:
- billy/web/public/search_results_no_query.html
- billy/web/public/search_results_bills... | def search(request, abbr) | Context:
- search_text
- abbr
- metadata
- found_by_id
- bill_results
- more_bills_available
- legislators_list
- nav_active
Tempaltes:
- billy/web/public/search_results_no_query.html
- billy/web/public/search_results_bills_legislators... | 3.679022 | 2.796678 | 1.315497 |
self['members'].append(dict(name=legislator, role=role,
**kwargs)) | def add_member(self, legislator, role='member', **kwargs) | Add a member to the committee object.
:param legislator: name of the legislator
:param role: role that legislator holds in the committee
(eg. chairman) default: 'member' | 5.11222 | 6.282513 | 0.813722 |
'''The action text, with any hyperlinked related entities.'''
action = self['action']
annotations = []
abbr = self.bill[settings.LEVEL_FIELD]
if 'related_entities' in self:
for entity in self['related_entities']:
name = entity['name']
_... | def action_display(self) | The action text, with any hyperlinked related entities. | 5.4669 | 4.450986 | 1.228245 |
'''Return the most recent date on which action_type occurred.
Action spec is a dictionary of key-value attrs to match.'''
for action in reversed(self.bill['actions']):
if action_type in action['type']:
for k, v in action_spec.items():
if action[k] ... | def _bytype(self, action_type, action_spec=None) | Return the most recent date on which action_type occurred.
Action spec is a dictionary of key-value attrs to match. | 7.307325 | 2.886072 | 2.531927 |
'''Return the yes/total ratio as a percetage string
suitable for use as as css attribute.'''
total = float(self._total_votes())
try:
return math.floor(self[key] / total * 100)
except ZeroDivisionError:
return float(0) | def _ratio(self, key) | Return the yes/total ratio as a percetage string
suitable for use as as css attribute. | 9.193559 | 3.226848 | 2.849083 |
'''A cache of dereferenced legislator objects.
'''
kwargs = {}
id_getter = operator.itemgetter('leg_id')
ids = []
for k in ('yes', 'no', 'other'):
ids.extend(map(id_getter, self[k + '_votes']))
objs = db.legislators.find({'_all_ids': {'$in': ids}}, **... | def _legislator_objects(self) | A cache of dereferenced legislator objects. | 5.313708 | 4.599016 | 1.155401 |
'''If this vote was accessed through the legislator.votes_manager,
return the value of this legislator's vote.
'''
if not hasattr(self, 'legislator'):
msg = ('legislator_vote_value can only be called '
'from a vote accessed by legislator.votes_manager.')
... | def legislator_vote_value(self) | If this vote was accessed through the legislator.votes_manager,
return the value of this legislator's vote. | 4.995534 | 3.148642 | 1.586568 |
'''Return all legislators who votes yes/no/other on this bill.
'''
#id_getter = operator.itemgetter('leg_id')
#ids = map(id_getter, self['%s_votes' % yes_no_other])
#return map(self._legislator_objects.get, ids)
result = []
for voter in self[yes_no_other + '_votes... | def _vote_legislators(self, yes_no_other) | Return all legislators who votes yes/no/other on this bill. | 3.378619 | 2.732435 | 1.236487 |
'''Guess whether this vote is a "voice vote".'''
if '+voice_vote' in self:
return True
if '+vote_type' in self:
if self['+vote_type'] == 'Voice':
return True
if 'voice vote' in self['motion'].lower():
return True
return False | def is_probably_a_voice_vote(self) | Guess whether this vote is a "voice vote". | 5.1814 | 4.17481 | 1.24111 |
'''Returns a cursor of full bill objects for any bills that have
ids. Not in use anyware as of 12/18/12, but handy to have around.
'''
bills = []
for bill in self['related_bills']:
if 'id' in bill:
bills.append(bill['id'])
return db.bills.find(... | def bill_objects(self) | Returns a cursor of full bill objects for any bills that have
ids. Not in use anyware as of 12/18/12, but handy to have around. | 7.925017 | 2.251347 | 3.520123 |
'''Return the host committee.
'''
_id = None
for participant in self['participants']:
if participant['type'] == 'host':
if set(['participant_type', 'id']) < set(participant):
# This event uses the id keyname "id".
if par... | def host(self) | Return the host committee. | 6.98492 | 5.759465 | 1.212772 |
'''Returns a list of members that chair the host committee,
including "co-chair" and "chairperson." This could concievalby
yield a false positive if the person's title is 'dunce chair'.
'''
chairs = []
# Host is guaranteed to be a committe or none.
host = self.hos... | def host_chairs(self) | Returns a list of members that chair the host committee,
including "co-chair" and "chairperson." This could concievalby
yield a false positive if the person's title is 'dunce chair'. | 11.957579 | 3.004342 | 3.980099 |
'''Return the members of the host committee.
'''
host = self.host()
if host is None:
return
for member, full_member in host.members_objects:
yield full_member | def host_members(self) | Return the members of the host committee. | 9.79312 | 6.39202 | 1.532085 |
'''
Context:
chamber
committees
abbr
metadata
chamber_name
chamber_select_template
chamber_select_collection
chamber_select_chambers
committees_table_template
show_chamber_column
sort_order
nav_active
Templates:... | def committees(request, abbr) | Context:
chamber
committees
abbr
metadata
chamber_name
chamber_select_template
chamber_select_collection
chamber_select_chambers
committees_table_template
show_chamber_column
sort_order
nav_active
Templates:
- b... | 2.714303 | 2.008759 | 1.351234 |
'''
Context:
- committee
- abbr
- metadata
- sources
- nav_active
Tempaltes:
- billy/web/public/committee.html
'''
committee = db.committees.find_one({'_id': committee_id})
if committee is None:
raise Http404
return render(request, te... | def committee(request, abbr, committee_id) | Context:
- committee
- abbr
- metadata
- sources
- nav_active
Tempaltes:
- billy/web/public/committee.html | 4.840606 | 2.771881 | 1.746325 |
# updated checks
if obj['updated_at'] >= yesterday:
report['_updated_today_count'] += 1
if obj['updated_at'] >= last_month:
report['_updated_this_month_count'] += 1
if obj['updated_at'] >= last_year:
report['_updated_this_year_count'] += 1 | def update_common(obj, report) | do updated_at checks | 3.106766 | 2.776273 | 1.119042 |
'''
Context:
- metadata
- chamber
- chamber_title
- chamber_select_template
- chamber_select_collection
- chamber_select_chambers
- show_chamber_column
- abbr
- legislators
- sort_order
- sort_key
- legislator_table
... | def legislators(request, abbr) | Context:
- metadata
- chamber
- chamber_title
- chamber_select_template
- chamber_select_collection
- chamber_select_chambers
- show_chamber_column
- abbr
- legislators
- sort_order
- sort_key
- legislator_table
- na... | 2.478692 | 2.001465 | 1.238439 |
'''
Context:
- vote_preview_row_template
- roles
- abbr
- district_id
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html... | def legislator(request, abbr, _id, slug=None) | Context:
- vote_preview_row_template
- roles
- abbr
- district_id
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- b... | 3.287383 | 2.556863 | 1.28571 |
'''
Context:
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/w... | def legislator_inactive(request, abbr, legislator) | Context:
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vo... | 3.508042 | 2.161082 | 1.62328 |
normalized_ranks = {
'BA': 'UNDERGRADUATE',
'BACHELOR': 'UNDERGRADUATE',
'BS': 'UNDERGRADUATE',
'BSC': 'UNDERGRADUATE',
'JUNIOR': 'JUNIOR',
'MAS': 'MASTER',
'MASTER': 'MASTER',
'MS': 'MASTER',
'MSC': 'MASTER',
'PD': 'POSTDOC',
... | def normalize_rank(rank) | Normalize a rank in order to be schema-compliant. | 2.607869 | 2.51619 | 1.036436 |
if not isinstance(ref_obj, dict):
return None
url = ref_obj.get('$ref', '')
return maybe_int(url.split('/')[-1]) | def get_recid_from_ref(ref_obj) | Retrieve recid from jsonref reference object.
If no recid can be parsed, returns None. | 4.867442 | 4.294826 | 1.133327 |
default_server = 'http://inspirehep.net'
server = current_app.config.get('SERVER_NAME', default_server)
if not re.match('^https?://', server):
server = u'http://{}'.format(server)
return urllib.parse.urljoin(server, relative_url) | def absolute_url(relative_url) | Returns an absolute URL from a URL relative to the server root.
The base URL is taken from the Flask app config if present, otherwise it
falls back to ``http://inspirehep.net``. | 3.243785 | 2.420137 | 1.340331 |
default_afs_path = '/afs/cern.ch/project/inspire/PROD'
afs_path = current_app.config.get('LEGACY_AFS_PATH', default_afs_path)
if file_path is None:
return
if file_path.startswith('/opt/cds-invenio/'):
file_path = os.path.relpath(file_path, '/opt/cds-invenio/')
file_path = ... | def afs_url(file_path) | Convert a file path to a URL pointing to its path on AFS.
If ``file_path`` doesn't start with ``/opt/cds-invenio/``, and hence is not on
AFS, it returns it unchanged.
The base AFS path is taken from the Flask app config if present, otherwise
it falls back to ``/afs/cern.ch/project/inspire/PROD``. | 3.066522 | 2.011533 | 1.52447 |
if isinstance(obj, dict):
new_obj = {}
for key, val in obj.items():
new_val = strip_empty_values(val)
if new_val is not None:
new_obj[key] = new_val
return new_obj or None
elif isinstance(obj, (list, tuple, set)):
new_obj = []
... | def strip_empty_values(obj) | Recursively strips empty values. | 1.553715 | 1.530027 | 1.015482 |
squared_dedupe_len = 10
if isinstance(obj, dict):
new_obj = {}
for key, value in obj.items():
if key in exclude_keys:
new_obj[key] = value
else:
new_obj[key] = dedupe_all_lists(value)
return new_obj
elif isinstance(obj, (li... | def dedupe_all_lists(obj, exclude_keys=()) | Recursively remove duplucates from all lists.
Args:
obj: collection to deduplicate
exclude_keys (Container[str]): key names to ignore for deduplication | 2.134476 | 2.24753 | 0.949699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.