_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11300 | wget | train | def wget(url):
"""
Download the page into a string
"""
import urllib.parse
request = urllib.request.urlopen(url)
filestring = request.read()
return filestring | python | {
"resource": ""
} |
q11301 | autodecode | train | def autodecode(b):
""" Try to decode ``bytes`` to text - try default encoding first, otherwise try to autodetect
Args:
b (bytes): byte string
Returns:
str: decoded text string
"""
import warnings
import chardet
try:
return b.decode()
except UnicodeError:
... | python | {
"resource": ""
} |
q11302 | remove_directories | train | def remove_directories(list_of_paths):
"""
Removes non-leafs from a list of directory paths
"""
found_dirs = set('/')
for path in list_of_paths:
dirs = path.strip().split('/')
for i in range(2,len(dirs)):
found_dirs.add( '/'.join(dirs[:i]) )
paths = [ path for path i... | python | {
"resource": ""
} |
q11303 | Subprocess._check_file_is_under_workingdir | train | def _check_file_is_under_workingdir(filename, wdir):
""" Raise error if input is being staged to a location not underneath the working dir
"""
p = filename
if not os.path.isabs(p):
p = os.path.join(wdir, p)
targetpath = os.path.realpath(p)
wdir = os.path.realp... | python | {
"resource": ""
} |
q11304 | FileReferenceBase._get_access_type | train | def _get_access_type(self, mode):
""" Make sure mode is appropriate; return 'b' for binary access and 't' for text
"""
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:
... | python | {
"resource": ""
} |
q11305 | getclosurevars | train | 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.
Not... | python | {
"resource": ""
} |
q11306 | EngineBase.dump_all_outputs | train | 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
"""
from pathlib import Path
root = Path(native_str(target))
for outputpath, o... | python | {
"resource": ""
} |
q11307 | EngineBase.launch | train | 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
"""
if isinstance(command, PythonCall):
return PythonJob(self, image, command... | python | {
"resource": ""
} |
q11308 | char_width | train | def char_width(char):
"""
Get the display length of a unicode character.
"""
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 | python | {
"resource": ""
} |
q11309 | display_len | train | def display_len(text):
"""
Get the display length of a string. This can differ from the character
length if the string contains wide characters.
"""
text = unicodedata.normalize('NFD', text)
return sum(char_width(char) for char in text) | python | {
"resource": ""
} |
q11310 | filter_regex | train | def filter_regex(names, regex):
"""
Return a tuple of strings that match the regular expression pattern.
"""
return tuple(name for name in names
if regex.search(name) is not None) | python | {
"resource": ""
} |
q11311 | filter_wildcard | train | def filter_wildcard(names, pattern):
"""
Return a tuple of strings that match a shell-style wildcard pattern.
"""
return tuple(name for name in names
if fnmatch.fnmatch(name, pattern)) | python | {
"resource": ""
} |
q11312 | HelpFeature.match | train | def match(self, obj, attrs):
"""
Only match if the object contains a non-empty docstring.
"""
if '__doc__' in attrs:
lstrip = getattr(obj.__doc__, 'lstrip', False)
return lstrip and any(lstrip()) | python | {
"resource": ""
} |
q11313 | PackagedFunction.prepare_namespace | train | 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
"""
if self.is_imethod:
to_run = get... | python | {
"resource": ""
} |
q11314 | decimal_format | train | def decimal_format(value, TWOPLACES=Decimal(100) ** -2):
'Format a decimal.Decimal like to 2 decimal places.'
if not isinstance(value, Decimal):
value = Decimal(str(value))
return value.quantize(TWOPLACES) | python | {
"resource": ""
} |
q11315 | notification_preference | train | 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.
'''
default_alert_value = True
if not profile:
alerts_on = True
else:
notifications = profile.get('notifications', {})
... | python | {
"resource": ""
} |
q11316 | OldRole.committee_object | train | def committee_object(self):
'''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... | python | {
"resource": ""
} |
q11317 | Legislator.context_role | train | def context_role(self, bill=None, vote=None, session=None, term=None):
'''Tell this legislator object which session to use when calculating
the legisator's context_role for a given bill or vote.
'''
# If no hints were given about the context, look for a related bill,
# then for a... | python | {
"resource": ""
} |
q11318 | Legislator.old_roles_manager | train | def old_roles_manager(self):
'''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 = d... | python | {
"resource": ""
} |
q11319 | NameMatcher._normalize | train | def _normalize(self, name):
"""
Normalizes a legislator name by stripping titles from the front,
converting to lowercase and removing punctuation.
"""
name = re.sub(
r'^(Senator|Representative|Sen\.?|Rep\.?|'
'Hon\.?|Right Hon\.?|Mr\.?|Mrs\.?|Ms\.?|L\'hon\... | python | {
"resource": ""
} |
q11320 | NameMatcher.match | train | 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-... | python | {
"resource": ""
} |
q11321 | get_scraper | train | def get_scraper(mod_path, scraper_type):
""" import a scraper from the scraper registry """
# 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 cl... | python | {
"resource": ""
} |
q11322 | Scraper._load_schemas | train | def _load_schemas(self):
""" load all schemas into schema dict """
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... | python | {
"resource": ""
} |
q11323 | Scraper.validate_session | train | 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
"""
if latest_only:
if ses... | python | {
"resource": ""
} |
q11324 | Scraper.validate_term | train | 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 ... | python | {
"resource": ""
} |
q11325 | SourcedObject.add_source | train | 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
"""
self['sources'].append(dict(url=url, **kwargs)) | python | {
"resource": ""
} |
q11326 | PlaintextColumns._get_column_ends | train | def _get_column_ends(self):
'''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 | python | {
"resource": ""
} |
q11327 | PlaintextColumns._get_column_boundaries | train | def _get_column_boundaries(self):
'''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 ... | python | {
"resource": ""
} |
q11328 | PlaintextColumns.getcells | train | def getcells(self, line):
'''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
els... | python | {
"resource": ""
} |
q11329 | PlaintextColumns.rows | train | def rows(self):
'''Returns an iterator of row tuples.
'''
for line in self.text.splitlines():
yield tuple(self.getcells(line)) | python | {
"resource": ""
} |
q11330 | PlaintextColumns.cells | train | def cells(self):
'''Returns an interator of all cells in the table.
'''
for line in self.text.splitlines():
for cell in self.getcells(line):
yield cell | python | {
"resource": ""
} |
q11331 | PaginatorBase.range_end | train | def range_end(self):
'''"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 | python | {
"resource": ""
} |
q11332 | GenericIDMatcher.learn_ids | train | def learn_ids(self, item_list):
""" read in already set ids on objects """
self._reset_sequence()
for item in item_list:
key = self.nondup_key_for_item(item)
self.ids[key] = item[self.id_key] | python | {
"resource": ""
} |
q11333 | GenericIDMatcher.set_ids | train | def set_ids(self, item_list):
""" set ids on an object, using internal mapping then new ids """
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() | python | {
"resource": ""
} |
q11334 | import_committees_from_legislators | train | def import_committees_from_legislators(current_term, abbr):
""" create committees from legislators that have committee roles """
# for all current legislators
for legislator in db.legislators.find({'roles': {'$elemMatch': {
'term': current_term, settings.LEVEL_FIELD: abbr}}}):
# for al... | python | {
"resource": ""
} |
q11335 | Bill.add_sponsor | train | 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
"""
self['sponsors'].append(dict(type=type, name... | python | {
"resource": ""
} |
q11336 | Bill.add_version | train | 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... | python | {
"resource": ""
} |
q11337 | Bill.add_action | train | 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 t... | python | {
"resource": ""
} |
q11338 | Bill.add_companion | train | 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'].
"""
companion = {'bill_id': bill_id,
'session': session or self['session'],
'... | python | {
"resource": ""
} |
q11339 | metadata | train | def metadata(abbr, __metadata=__metadata):
"""
Grab the metadata for the given two-letter abbreviation.
"""
# 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_... | python | {
"resource": ""
} |
q11340 | cd | train | def cd(path):
'''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) | python | {
"resource": ""
} |
q11341 | _get_property_dict | train | def _get_property_dict(schema):
""" given a schema object produce a nested dictionary of fields """
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.LEVE... | python | {
"resource": ""
} |
q11342 | update | train | 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 o... | python | {
"resource": ""
} |
q11343 | convert_timestamps | train | def convert_timestamps(obj):
"""
Convert unix timestamps in the scraper output to python datetimes
so that they will be saved properly as Mongo datetimes.
"""
for key in ('date', 'when', 'end', 'start_date', 'end_date'):
value = obj.get(key)
if value:
try:
... | python | {
"resource": ""
} |
q11344 | _make_plus_helper | train | def _make_plus_helper(obj, fields):
""" add a + prefix to any fields in obj that aren't in fields """
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):
... | python | {
"resource": ""
} |
q11345 | make_plus_fields | train | def make_plus_fields(obj):
"""
Add a '+' to the key of non-standard fields.
dispatch to recursive _make_plus_helper based on _type field
"""
fields = standard_fields.get(obj['_type'], dict())
return _make_plus_helper(obj, fields) | python | {
"resource": ""
} |
q11346 | Metadata.get_object | train | 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.
'''
obj = get_metadata(abbr)
if obj is None:
msg = 'No metada... | python | {
"resource": ""
} |
q11347 | Metadata.committees_legislators | train | 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.
'''
committees = list(self.committees(*args, **kwargs))
le... | python | {
"resource": ""
} |
q11348 | extract_fields | train | def extract_fields(d, fields, delimiter='|'):
""" get values out of an object ``d`` for saving to a csv """
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)
... | python | {
"resource": ""
} |
q11349 | region_selection | train | def region_selection(request):
'''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) | python | {
"resource": ""
} |
q11350 | Committee.add_member | train | 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'
"""
self['members'].append... | python | {
"resource": ""
} |
q11351 | Action.action_display | train | def action_display(self):
'''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... | python | {
"resource": ""
} |
q11352 | ActionsManager._bytype | train | 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.'''
for action in reversed(self.bill['actions']):
if action_type in action['type']:
for k, v in acti... | python | {
"resource": ""
} |
q11353 | BillVote._legislator_objects | train | def _legislator_objects(self):
'''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... | python | {
"resource": ""
} |
q11354 | BillVote.legislator_vote_value | train | def legislator_vote_value(self):
'''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 ... | python | {
"resource": ""
} |
q11355 | BillVote.is_probably_a_voice_vote | train | def is_probably_a_voice_vote(self):
'''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():
... | python | {
"resource": ""
} |
q11356 | Event.host | train | def host(self):
'''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".
... | python | {
"resource": ""
} |
q11357 | Event.host_chairs | train | 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'.
'''
chairs = []
# Host is guaranteed to be a committe or none.
... | python | {
"resource": ""
} |
q11358 | Event.host_members | train | def host_members(self):
'''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 | python | {
"resource": ""
} |
q11359 | update_common | train | def update_common(obj, report):
""" do updated_at checks """
# 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:
... | python | {
"resource": ""
} |
q11360 | normalize_rank | train | def normalize_rank(rank):
"""Normalize a rank in order to be schema-compliant."""
normalized_ranks = {
'BA': 'UNDERGRADUATE',
'BACHELOR': 'UNDERGRADUATE',
'BS': 'UNDERGRADUATE',
'BSC': 'UNDERGRADUATE',
'JUNIOR': 'JUNIOR',
'MAS': 'MASTER',
'MASTER': 'MASTER... | python | {
"resource": ""
} |
q11361 | get_recid_from_ref | train | def get_recid_from_ref(ref_obj):
"""Retrieve recid from jsonref reference object.
If no recid can be parsed, returns None.
"""
if not isinstance(ref_obj, dict):
return None
url = ref_obj.get('$ref', '')
return maybe_int(url.split('/')[-1]) | python | {
"resource": ""
} |
q11362 | absolute_url | train | 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``.
"""
default_server = 'http://inspirehep.net'
server = current_app.config.get('SERV... | python | {
"resource": ""
} |
q11363 | afs_url | train | 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.... | python | {
"resource": ""
} |
q11364 | strip_empty_values | train | def strip_empty_values(obj):
"""Recursively strips empty values."""
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... | python | {
"resource": ""
} |
q11365 | dedupe_all_lists | train | 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
"""
squared_dedupe_len = 10
if isinstance(obj, dict):
new_obj = {}
f... | python | {
"resource": ""
} |
q11366 | normalize_date_aggressively | train | def normalize_date_aggressively(date):
"""Normalize date, stripping date parts until a valid date is obtained."""
def _strip_last_part(date):
parts = date.split('-')
return '-'.join(parts[:-1])
fake_dates = {'0000', '9999'}
if date in fake_dates:
return None
try:
ret... | python | {
"resource": ""
} |
q11367 | match_country_name_to_its_code | train | def match_country_name_to_its_code(country_name, city=''):
"""Try to match country name with its code.
Name of the city helps when country_name is "Korea".
"""
if country_name:
country_name = country_name.upper().replace('.', '').strip()
if country_to_iso_code.get(country_name):
... | python | {
"resource": ""
} |
q11368 | match_us_state | train | def match_us_state(state_string):
"""Try to match a string with one of the states in the US."""
if state_string:
state_string = state_string.upper().replace('.', '').strip()
if us_state_to_iso_code.get(state_string):
return us_state_to_iso_code.get(state_string)
else:
... | python | {
"resource": ""
} |
q11369 | parse_conference_address | train | def parse_conference_address(address_string):
"""Parse a conference address.
This is a pretty dummy address parser. It only extracts country
and state (for US) and should be replaced with something better,
like Google Geocoding.
"""
geo_elements = address_string.split(',')
city = geo_eleme... | python | {
"resource": ""
} |
q11370 | parse_institution_address | train | def parse_institution_address(address, city, state_province,
country, postal_code, country_code):
"""Parse an institution address."""
address_list = force_list(address)
state_province = match_us_state(state_province) or state_province
postal_code = force_list(postal_code)
... | python | {
"resource": ""
} |
q11371 | name | train | def name(self, key, value):
"""Populate the ``name`` key.
Also populates the ``status``, ``birth_date`` and ``death_date`` keys through side effects.
"""
def _get_title(value):
c_value = force_single_element(value.get('c', ''))
if c_value != 'title (e.g. Sir)':
return c_valu... | python | {
"resource": ""
} |
q11372 | name2marc | train | def name2marc(self, key, value):
"""Populates the ``100`` field.
Also populates the ``400``, ``880``, and ``667`` fields through side
effects.
"""
result = self.get('100', {})
result['a'] = value.get('value')
result['b'] = value.get('numeration')
result['c'] = value.get('title')
re... | python | {
"resource": ""
} |
q11373 | positions | train | def positions(self, key, value):
"""Populate the positions field.
Also populates the email_addresses field by side effect.
"""
email_addresses = self.get("email_addresses", [])
current = None
record = None
recid_or_status = force_list(value.get('z'))
for el in recid_or_status:
... | python | {
"resource": ""
} |
q11374 | email_addresses2marc | train | def email_addresses2marc(self, key, value):
"""Populate the 595 MARCXML field.
Also populates the 371 field as a side effect.
"""
m_or_o = 'm' if value.get('current') else 'o'
element = {
m_or_o: value.get('value')
}
if value.get('hidden'):
return element
else:
... | python | {
"resource": ""
} |
q11375 | email_addresses595 | train | def email_addresses595(self, key, value):
"""Populates the ``email_addresses`` field using the 595 MARCXML field.
Also populates ``_private_notes`` as a side effect.
"""
emails = self.get('email_addresses', [])
if value.get('o'):
emails.append({
'value': value.get('o'),
... | python | {
"resource": ""
} |
q11376 | arxiv_categories | train | def arxiv_categories(self, key, value):
"""Populate the ``arxiv_categories`` key.
Also populates the ``inspire_categories`` key through side effects.
"""
def _is_arxiv(category):
return category in valid_arxiv_categories()
def _is_inspire(category):
schema = load_schema('elements/i... | python | {
"resource": ""
} |
q11377 | urls | train | def urls(self, key, value):
"""Populate the ``url`` key.
Also populates the ``ids`` key through side effects.
"""
description = force_single_element(value.get('y'))
url = value.get('u')
linkedin_match = LINKEDIN_URL.match(url)
twitter_match = TWITTER_URL.match(url)
wikipedia_match = WI... | python | {
"resource": ""
} |
q11378 | new_record | train | def new_record(self, key, value):
"""Populate the ``new_record`` key.
Also populates the ``ids`` key through side effects.
"""
new_record = self.get('new_record', {})
ids = self.get('ids', [])
for value in force_list(value):
for id_ in force_list(value.get('a')):
ids.append... | python | {
"resource": ""
} |
q11379 | isbns | train | def isbns(self, key, value):
"""Populate the ``isbns`` key."""
def _get_medium(value):
def _normalize(medium):
schema = load_schema('hep')
valid_media = schema['properties']['isbns']['items']['properties']['medium']['enum']
medium = medium.lower().replace('-', '').re... | python | {
"resource": ""
} |
q11380 | dois | train | def dois(self, key, value):
"""Populate the ``dois`` key.
Also populates the ``persistent_identifiers`` key through side effects.
"""
def _get_first_non_curator_source(sources):
sources_without_curator = [el for el in sources if el.upper() != 'CURATOR']
return force_single_element(sourc... | python | {
"resource": ""
} |
q11381 | texkeys | train | def texkeys(self, key, value):
"""Populate the ``texkeys`` key.
Also populates the ``external_system_identifiers`` and ``_desy_bookkeeping`` keys through side effects.
"""
def _is_oai(id_, schema):
return id_.startswith('oai:')
def _is_desy(id_, schema):
return id_ and schema in ('... | python | {
"resource": ""
} |
q11382 | arxiv_eprints | train | def arxiv_eprints(self, key, value):
"""Populate the ``arxiv_eprints`` key.
Also populates the ``report_numbers`` key through side effects.
"""
def _get_clean_arxiv_eprint(id_):
return id_.split(':')[-1]
def _is_arxiv_eprint(id_, source):
return source.lower() == 'arxiv'
def _... | python | {
"resource": ""
} |
q11383 | languages | train | def languages(self, key, value):
"""Populate the ``languages`` key."""
languages = self.get('languages', [])
values = force_list(value.get('a'))
for value in values:
for language in RE_LANGUAGE.split(value):
try:
name = language.strip().capitalize()
l... | python | {
"resource": ""
} |
q11384 | languages2marc | train | def languages2marc(self, key, value):
"""Populate the ``041`` MARC field."""
return {'a': pycountry.languages.get(alpha_2=value).name.lower()} | python | {
"resource": ""
} |
q11385 | record_affiliations | train | def record_affiliations(self, key, value):
"""Populate the ``record_affiliations`` key."""
record = get_record_ref(value.get('z'), 'institutions')
return {
'curated_relation': record is not None,
'record': record,
'value': value.get('a'),
} | python | {
"resource": ""
} |
q11386 | document_type | train | def document_type(self, key, value):
"""Populate the ``document_type`` key.
Also populates the ``_collections``, ``citeable``, ``core``, ``deleted``,
``refereed``, ``publication_type``, and ``withdrawn`` keys through side
effects.
"""
schema = load_schema('hep')
publication_type_schema = sc... | python | {
"resource": ""
} |
q11387 | document_type2marc | train | def document_type2marc(self, key, value):
"""Populate the ``980`` MARC field."""
if value in DOCUMENT_TYPE_REVERSE_MAP and DOCUMENT_TYPE_REVERSE_MAP[value]:
return {'a': DOCUMENT_TYPE_REVERSE_MAP[value]} | python | {
"resource": ""
} |
q11388 | references | train | def references(self, key, value):
"""Populate the ``references`` key."""
def _has_curator_flag(value):
normalized_nine_values = [el.upper() for el in force_list(value.get('9'))]
return 'CURATOR' in normalized_nine_values
def _is_curated(value):
return force_single_element(value.get(... | python | {
"resource": ""
} |
q11389 | documents | train | def documents(self, key, value):
"""Populate the ``documents`` key.
Also populates the ``figures`` key through side effects.
"""
def _is_hidden(value):
return 'HIDDEN' in [val.upper() for val in value] or None
def _is_figure(value):
figures_extensions = ['.png']
return valu... | python | {
"resource": ""
} |
q11390 | marcxml2record | train | def marcxml2record(marcxml):
"""Convert a MARCXML string to a JSON record.
Tries to guess which set of rules to use by inspecting the contents
of the ``980__a`` MARC field, but falls back to HEP in case nothing
matches, because records belonging to special collections logically
belong to the Litera... | python | {
"resource": ""
} |
q11391 | record2marcxml | train | def record2marcxml(record):
"""Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: a MARCXML string converted from... | python | {
"resource": ""
} |
q11392 | number_of_pages | train | def number_of_pages(self, key, value):
"""Populate the ``number_of_pages`` key."""
result = maybe_int(force_single_element(value.get('a', '')))
if result and result > 0:
return result | python | {
"resource": ""
} |
q11393 | nonfirst_authors | train | def nonfirst_authors(self, key, value):
"""Populate ``700`` MARC field.
Also populates the ``701`` MARC field through side-effects.
"""
field_700 = self.get('700__', [])
field_701 = self.get('701__', [])
is_supervisor = any(el.lower().startswith('dir') for el in force_list(value.get('e', '')))... | python | {
"resource": ""
} |
q11394 | urls | train | def urls(self, key, value):
"""Populate the ``8564`` MARC field.
Also populate the ``FFT`` field through side effects.
"""
def _is_preprint(value):
return value.get('y', '').lower() == 'preprint'
def _is_fulltext(value):
return value['u'].endswith('.pdf') and value['u'].startswith(... | python | {
"resource": ""
} |
q11395 | titles | train | def titles(self, key, value):
"""Populate the ``titles`` key."""
if not key.startswith('245'):
return {
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
}
self.setdefault('titles', []).insert(0, {
'source': value.get(... | python | {
"resource": ""
} |
q11396 | title_translations | train | def title_translations(self, key, value):
"""Populate the ``title_translations`` key."""
return {
'language': langdetect.detect(value.get('a')),
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
} | python | {
"resource": ""
} |
q11397 | titles2marc | train | def titles2marc(self, key, values):
"""Populate the ``246`` MARC field.
Also populates the ``245`` MARC field through side effects.
"""
first, rest = values[0], values[1:]
self.setdefault('245', []).append({
'a': first.get('title'),
'b': first.get('subtitle'),
'9': first.ge... | python | {
"resource": ""
} |
q11398 | title_translations2marc | train | def title_translations2marc(self, key, value):
"""Populate the ``242`` MARC field."""
return {
'a': value.get('title'),
'b': value.get('subtitle'),
'9': value.get('source'),
} | python | {
"resource": ""
} |
q11399 | imprints | train | def imprints(self, key, value):
"""Populate the ``imprints`` key."""
return {
'place': value.get('a'),
'publisher': value.get('b'),
'date': normalize_date_aggressively(value.get('c')),
} | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.