rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
visited = set() def is_visited(key): if key in visited: return True else: visited.add(key) return False result = [r for r in result if not is_visited(r.key)] | def _get_recent_changes(): site = web.ctx.get('site') or delegate.create_site() web.ctx.setdefault("ip", "127.0.0.1") q = {"bot": False, "limit": 50} result = site.versions(q) def process_thing(thing): t = web.storage() for k in ["key", "title", "name", "displayname"]: t[k] = thing[k] t['type'] = web.storage(key=thin... | |
solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=* %%2Cscore&qt=standard&wt=json" % (q, offset, rows) | solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=*%%2Cscore&qt=standard&wt=json" % (web.urlquote(q), offset, rows) | def simple_search(q, offset=0, rows=20, sort=None): solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=* %%2Cscore&qt=standard&wt=json" % (q, offset, rows) if sort: solr_select += "&sort=" + url_quote(sort) return json.load(urllib.urlopen(solr_select)) |
solr_select += "&sort=" + url_quote(sort) | solr_select += "&sort=" + web.urlquote(sort) | def simple_search(q, offset=0, rows=20, sort=None): solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=* %%2Cscore&qt=standard&wt=json" % (q, offset, rows) if sort: solr_select += "&sort=" + url_quote(sort) return json.load(urllib.urlopen(solr_select)) |
root_url = 'http://ia331508:8983/solr/works/select?wt=json&indent=on&rows=%d&start=%d&q.op=AND&q=%s&fl=edition_key' | root_url = solr_select_url + '?wt=json&indent=on&rows=%d&start=%d&q.op=AND&q=%s&fl=edition_key' | def find_ebook_count(field, key): q = '%s_key:%s+AND+(overdrive_s:*+OR+ia:*)' % (field, re_chars.sub(r'\\\1', key).encode('utf-8')) root_url = 'http://ia331508:8983/solr/works/select?wt=json&indent=on&rows=%d&start=%d&q.op=AND&q=%s&fl=edition_key' rows = 1000 ebook_count = 0 start = 0 solr_url = root_url % (rows, sta... |
if key.split("/")[1] in ['a', 'b', 'l', 'user']: | if "/" in key and key.split("/")[1] in ['a', 'b', 'l', 'user']: | def _process_key(self, key): mapping = ( "/l/", "/languages/", "/a/", "/authors/", "/b/", "/books/", "/user/", "/people/" ) if key.split("/")[1] in ['a', 'b', 'l', 'user']: for old, new in web.group(mapping, 2): if key.startswith(old): return new + key[len(old):] return key |
def abbey_to_par(f, debug=False): | def abbyy_to_par(f, debug=False): | def abbey_to_par(f, debug=False): prev = '' page_count = 0 for event, element in iterparse(f): if element.tag == page_tag: page_count+= 1 if debug: print 'page', page_count page_break = True for block in element: assert block.tag == block_tag if block.attrib['blockType'] in ('Picture', 'Table'): continue assert block.a... |
for i in abbey_to_par(sys.stdin, debug=False): | for i in abbyy_to_par(sys.stdin, debug=False): | def abbey_to_par(f, debug=False): prev = '' page_count = 0 for event, element in iterparse(f): if element.tag == page_tag: page_count+= 1 if debug: print 'page', page_count page_break = True for block in element: assert block.tag == block_tag if block.attrib['blockType'] in ('Picture', 'Table'): continue assert block.a... |
" ORDER BY thing.last_modified LIMIT 10") | " ORDER BY thing.last_modified LIMIT 10", vars=locals()) | def query(key, value): key_id = get_property_id(key) db = get_db() rows = db.query("SELECT thing.key" + " FROM thing, edition_str" + " WHERE thing.id=edition_str.thing_id" + " AND key_id=$key_id" + " AND value=$value" + " ORDER BY thing.last_modified LIMIT 10") return [row.key for row in rows] |
if lines[i].strip() and lines[i+1].strip() and not markdown.RE.regExp['tabbed'].match(lines[i]): | if (lines[i].strip() and lines[i+1].strip() and not markdown.RE.regExp['tabbed'].match(lines[i]) and not LINK_REFERENCE_RE.match(lines[i])): | def run(self, lines) : for i in range(len(lines)-1): # append <br/> to all lines expect blank lines and the line before blankline. if lines[i].strip() and lines[i+1].strip() and not markdown.RE.regExp['tabbed'].match(lines[i]): lines[i] += "<br />" return lines |
re_isbn_field = re.compile('^\s*(?:isbn[:\s]*)([-0-9X]{9,})\s*$', re.I) | re_isbn_field = re.compile('^\s*(?:isbn[:\s]*)?([-0-9X]{9,})\s*$', re.I) | def advanced_to_simple(params): q_list = [] q = params.get('q', None) if q and q != '*:*': q_list.append(params['q']) for k in 'title', 'author': if k in params: q_list.append("%s:(%s)" % (k, params[k])) return ' '.join(q_list) |
if 'isbn' in i and all(not v for v in i.values()): | if 'isbn' in i and all(not v for k, v in i.items() if k != 'isbn'): | def GET(self): i = web.input(author_key=[], language=[], first_publish_year=[], publisher_facet=[], subject_facet=[], person_facet=[], place_facet=[], time_facet=[]) params = self.clean_inputs(i) |
self.seeds_db.mark_seeds_for_update() | self.seeds_db.mark_seeds_for_update(ctx.seeds.keys()) | def process_changesets(self, changesets): ctx = UpdaterContext() for chunk in web.group(changesets, 50): chunk = list(chunk) works = [work for changeset in chunk for work in self._get_works(changeset)] |
for row in self.db.view("seeds2/seeds", keys=keys, include_docs=True) | for row in self.db.view("seeds/seeds", keys=keys, include_docs=True) | def update_editions(self, ctx, editions): editions = list(editions) logging.info("works_db: BEGIN update_editions %s", len(editions)) # remove duplicate entries from editions editions = dict((e['key'], e) for e in editions).values() keys = [e['key'] for e in editions] old_works = dict((row.key, row.doc) for row in sel... |
counts = self.works_db.db.view("seeds2/seeds", keys=list(seeds)) | counts = self.works_db.db.view("seeds/seeds", keys=list(seeds)) | def _update_seeds(self, seeds): counts = self.works_db.db.view("seeds2/seeds", keys=list(seeds)) |
return [s.decode('utf-8') for s in csv.reader(f).next()] | return [s.decode('utf-8') for s in csv.reader(f, dialect='excel', skipinitialspace=True).next()] | def read_subject(subjects): if not subjects: return [] f = StringIO(subjects.encode('utf-8')) # no unicode in csv module return [s.decode('utf-8') for s in csv.reader(f).next()] |
params = clean_input(i) | params = self.clean_inputs(i) | def GET(self): i = web.input(author_key=[], language=[], first_publish_year=[], publisher_facet=[], subject_facet=[], person_facet=[], place_facet=[], time_facet=[]) params = clean_input(i) |
ol.store.indexer = Indexer() | def init_plugin(): """Initialize infobase plugin.""" from infogami.infobase import common, dbstore, server, logger dbstore.default_schema = schema.get_schema() if config.get('errorlog'): common.record_exception = lambda: save_error(config.errorlog, 'infobase') ol = server.get_site('openlibrary.org') ib = server._info... | |
author.photos = [photoid] + [photo.id for photo in book.get_photos()] | author.photos = [photoid] + [photo.id for photo in author.get_photos()] | def save(self, author, photoid): author.photos = [photoid] + [photo.id for photo in book.get_photos()] author._save("Added new photo") |
class subjects_covers(delegate.page): path = '/subjects/(.+)/covers' encoding = "json" @jsonapi def GET(self, path_info): i = web.input(offset=0, limit=12) try: offset = int(i.offset) limit = int(i.limit) except ValueError: return [] (subject_type, key, full_key, q) = read_subject(path_info) solr_select = solr_select... | @jsonapi def subjects_covers(path_info): i = web.input(offset=0, limit=12) try: offset = int(i.offset) limit = int(i.limit) except ValueError: return [] (subject_type, key, full_key, q) = read_subject(path_info) solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=key,author_name,author_... | def read_subject(path_info): m = re_subject_types.match(path_info) if m: subject_type = subject_types[m.group(1)] key = str_to_key(m.group(2)).lower().replace('_', ' ') full_key = '/subjects/%s/%s' % (m.group(1), key) q = '%s_key:"%s"' % (subject_type, url_quote(key)) else: subject_type = 'subject' key = str_to_key(pat... |
config = dict(web.config.get("fastcgi")) | config = dict(web.config.get("fastcgi", {})) | def runfcgi(func, addr=('localhost', 8000)): """Runs a WSGI function as a FastCGI pre-fork server.""" config = dict(web.config.get("fastcgi")) mode = config.pop("mode", None) if mode == "prefork": import flup.server.fcgi_fork as flups else: import flup.server.fcgi as flups return flups.WSGIServer(func, multiplexed=Tr... |
If date is specified, only revisions created before that date will be considered. """ filter = date and (lambda doc: doc['last_modified']['value'] < date) | If date is specified, only revisions created on or before that date will be considered. """ filter = date and (lambda doc: doc['last_modified']['value'] < date + "Z") | def generate_cdump(data_file, date=None): """Generates cdump from a copy of data table. If date is specified, only revisions created before that date will be considered. """ filter = date and (lambda doc: doc['last_modified']['value'] < date) print_dump(read_data_file(data_file), filter=filter) |
def GET(sef, key): | def GET(self, key): | def GET(sef, key): page = web.ctx.site.get(key) |
return get_message_from_template("messages", name, *args) def get_message_from_template(template_name, name, *args): | return get_message_from_template("messages", name, args) def get_message_from_template(template_name, name, args): | def get_message(name, *args): """Return message with given name from messages.tmpl template""" return get_message_from_template("messages", name, *args) |
return " x ".join(str(d[k]) for k in self.fields) + ' ' + d['units'] | return " x ".join(str(d[k]) for k in self.fields) + ' ' + d.get('units', '') | def format(self, d): return " x ".join(str(d[k]) for k in self.fields) + ' ' + d['units'] |
d = self.get_data(key) | try: d = self.get_data(key) except web.HTTPError, e: if web.ctx.status.lower() == "404 not found": d = {"key": key} else: raise | def GET(self, key): # only allow admin users to edit yaml if not self.is_admin(): return render.permission_denied(key, 'Permission Denied') d = self.get_data(key) return render.edit_yaml(key, self.dump(d)) |
cover = Image("b", coverid) | cover = Image(web.ctx.site, "b", coverid) | def POST(self, key): book = web.ctx.site.get(key) if not book: raise web.notfound("") i = web.input(file={}, url="") # remove references to field storage objects web.ctx.pop("_fieldstorage", None) data = self.upload(key, i) coverid = data.get('id') if coverid: self.save(book, coverid, url=i.url) cover = Image("b", ... |
if page.type.key == '/type/delete' and page.books != []: | if page.type.key == '/type/author': return books = web.ctx.site.things({"type": "/type/edition", "authors": page.key}) books = books or web.ctx.site.things({"type": "/type/work", "authors": {"author": {"key": page.key}}}) if page.type.key == '/type/delete' and books: | def before_new_version(self, page): if page.key.startswith('/a/') or page.key.startswith('/authors/'): if page.type.key == '/type/delete' and page.books != []: raise ValidationException("Deleting author pages is not allowed.") elif page.type.key != '/type/author' and page.books != []: raise ValidationException("Changin... |
elif page.type.key != '/type/author' and page.books != []: | elif page.type.key != '/type/author' and books: | def before_new_version(self, page): if page.key.startswith('/a/') or page.key.startswith('/authors/'): if page.type.key == '/type/delete' and page.books != []: raise ValidationException("Deleting author pages is not allowed.") elif page.type.key != '/type/author' and page.books != []: raise ValidationException("Changin... |
def get_all_lists(self): | def get_lists(self): data = self.urlopen("/people/" + self.username + "/lists.json").read() return simplejson.loads(data) | |
return web.ctx.site.get(path) | return web.ctx.site.get(key) | def get_doc(self, key): if key.startswith("/subjects/"): s = worksearch.get_subject(key) if s.work_count > 0: return s else: return None else: return web.ctx.site.get(path) |
if latest.get(key, -1) < int(revision): latest[key] = i | if latest.get(key, -1)[-1] < int(revision): latest[key] = (i, int(revision)) | def generate_dump(cdump_file): """Generate dump from cdump. This is done in two passes. In pass 1, line numbers of the latest revisions are stored in a dictionary. In pass 2, the line numbers are sorted and those lines from the file are written to stdout. The cdump file is read twice, once in each pass and complexity... |
rows = latest.values() | rows = [index for index, rev in latest.values()] | def generate_dump(cdump_file): """Generate dump from cdump. This is done in two passes. In pass 1, line numbers of the latest revisions are stored in a dictionary. In pass 2, the line numbers are sorted and those lines from the file are written to stdout. The cdump file is read twice, once in each pass and complexity... |
return set() | return {} | def get_ia_meta_fields(self): if not self.get('ocaid', None): return set() ia = self.ocaid url = 'http://www.archive.org/download/%s/%s_meta.xml' % (ia, ia) reply = { 'collection': set() } for line in urllib2.urlopen(url): m = re_meta_field.search(line) if not m: continue k = m.group(1).lower() v = m.group(2) if k == '... |
not_cached = ['/b/', '/a/', '/books/', '/authors/', '/works/', '/subjects/', '/publishers/', '/upstream/'] | not_cached = ['/b/', '/a/', '/books/', '/authors/', '/works/', '/subjects/', '/publishers/', '/user/', '/usergroup/', '/people/'] | def http_notify(site, old, new): """Notify listeners over http.""" data = new.format_data() json = simplejson.dumps(data) key = data['key'] # optimize the most common case. # The following prefixes are never cached at the client. Avoid cache invalidation in that case. not_cached = ['/b/', '/a/', '/books/', '/authors/'... |
db.query('insert into subjects (field, key, publish_year, ebook_count) values ($field, $key, $year, $count)', vars=locals()) | ebook_count_db.query('insert into subjects (field, key, publish_year, ebook_count) values ($field, $key, $year, $count)', vars=locals()) | def db_lookup(field, key, publish_year=None): sql = 'select sum(ebook_count) as num from subjects where field=$field and key=$key' if publish_year: if isinstance(publish_year, list): sql += ' and publish_year between $y1 and $y2' (y1, y2) = publish_year else: sql += ' and publish_year=$publish_year' return list(ebook_c... |
master = BasicMergeEngine.merge_docs(self, master, dup) if 'name' in dup: master.setdefault('alternate_names', []).append(dup['name']) master['alternate_names'] = uniq(master['alternate_names']) | if dup['type']['key'] == '/type/author': master = BasicMergeEngine.merge_docs(self, master, dup) if 'name' in dup: master.setdefault('alternate_names', []).append(dup['name']) master['alternate_names'] = uniq(master['alternate_names']) | def merge_docs(self, master, dup): master = BasicMergeEngine.merge_docs(self, master, dup) if 'name' in dup: master.setdefault('alternate_names', []).append(dup['name']) master['alternate_names'] = uniq(master['alternate_names']) return master |
keys = uniq(i.key) | keys = uniq(i.key) keys = self.filter_authors(keys) | def GET(self): i = web.input(key=[]) keys = uniq(i.key) return render_template('merge/authors', keys, top_books_from_author=top_books_from_author) |
return 'ipad' in useragent \ or 'iphone' in useragent | return 'ipad' in useragent or 'iphone' in useragent | def is_mobile_device(self, environ): useragent = environ.get('HTTP_USER_AGENT', '').lower() return 'ipad' in useragent \ or 'iphone' in useragent |
cookies = self.cookies(environ, mobile="false") | cookies = self.cookies(environ, mobile="true") | def __call__(self, environ, start_response): cookies = self.cookies(environ, mobile="false") # delegate to mobile app when cookie mobile is set to true. if cookies.mobile == "true" or self.is_mobile_device(environ): return mobile_wsgi_app(environ, start_response) else: return self.wsgi_app(environ, start_response) |
if cookies.mobile == "true" or self.is_mobile_device(environ): | if cookies.mobile == "true" and self.is_mobile_device(environ): | def __call__(self, environ, start_response): cookies = self.cookies(environ, mobile="false") # delegate to mobile app when cookie mobile is set to true. if cookies.mobile == "true" or self.is_mobile_device(environ): return mobile_wsgi_app(environ, start_response) else: return self.wsgi_app(environ, start_response) |
"/books/.*", "books", "/authors/.*", "authors", | "(/books/OL\d+M)(?:/.*)?", "book", "(/authors/OL\d+A)(?:/.*)?", "author", | def __call__(self, environ, start_response): cookies = self.cookies(environ, mobile="false") # delegate to mobile app when cookie mobile is set to true. if cookies.mobile == "true" or self.is_mobile_device(environ): return mobile_wsgi_app(environ, start_response) else: return self.wsgi_app(environ, start_response) |
result = download(get_ol_url() + '/query.json?' + urllib.urlencode(d)) | result = download(get_ol_url() + '/api/things?' + urllib.urlencode(d)) | def ol_things(key, value): query = { 'type': '/type/edition', key: value, 'sort': 'last_modified', 'limit': 10 } try: d = dict(query=simplejson.dumps(query)) result = download(get_ol_url() + '/query.json?' + urllib.urlencode(d)) result = simplejson.loads(result) olids = result['result'] return [olid.split('/')[-1] for ... |
olids = result['result'] return [olid.split('/')[-1] for olid in olids] | return result['result'] | def ol_things(key, value): query = { 'type': '/type/edition', key: value, 'sort': 'last_modified', 'limit': 10 } try: d = dict(query=simplejson.dumps(query)) result = download(get_ol_url() + '/query.json?' + urllib.urlencode(d)) result = simplejson.loads(result) olids = result['result'] return [olid.split('/')[-1] for ... |
subject.ebook_count = dict(result.facets["has_fulltext"]).get("true", 0) | subject.ebook_count = fast_ebook_count(meta.name, q[meta.facet_key], q.get('publish_year')) | def facet_wrapper(facet, value, count): if facet == "publish_year": return [int(value), count] elif facet == "publisher_facet": return web.storage(name=value, count=count) elif facet == "author_facet": author = read_author_facet(value) # FIXME return web.storage(name=author[1], key="/authors/" + author[0], count=count)... |
elif re_field.search(q_param): | elif re_fields.search(q_param): | def run_solr_query(param = {}, rows=100, page=1, sort=None, spellcheck_count=None): if spellcheck_count == None: spellcheck_count = default_spellcheck_count q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) use_dismax = False if q_param: if q_param == '*:*': q_lis... |
q_list.append(q_param) | q_list.append(q_param.strip().replace(':', '\:')) | def run_solr_query(param = {}, rows=100, page=1, sort=None, spellcheck_count=None): if spellcheck_count == None: spellcheck_count = default_spellcheck_count q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) use_dismax = False if q_param: if q_param == '*:*': q_lis... |
check_params = ['title', 'publisher', 'isbn', 'oclc', 'lccn', 'contribtor'] + facet_fields | check_params = ['title', 'publisher', 'isbn', 'oclc', 'lccn', 'contribtor'] | def run_solr_query(param = {}, rows=100, page=1, sort=None): q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) if q_param: if q_param == '*:*' or re_fields.match(q_param): q_list.append(q_param) else: isbn = read_isbn(q_param) if isbn: q_list.append('isbn:(%s)' % ... |
q_list += ['%s:(%s)' % (k, param[k]) for k in 'has_fulltext', 'fiction' if k in param] | if 'has_fulltext' in param: q_list.append('has_fulltext:%s' % param['has_fulltext']) q_list += ['%s:"%s"' % (k, param[k]) for k in facet_fields if k in param] | def run_solr_query(param = {}, rows=100, page=1, sort=None): q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) if q_param: if q_param == '*:*' or re_fields.match(q_param): q_list.append(q_param) else: isbn = read_isbn(q_param) if isbn: q_list.append('isbn:(%s)' % ... |
q = " OR ".join("seed:" + escape(seed) for seed in seeds) | q = " OR ".join("seed:" + escape(seed.encode('utf-8')) for seed in seeds) | def escape(value): special_chars = '+-&|!(){}[]^"~*?:\\' pattern = "([%s])" % re.escape(special_chars) quote = '"' return quote + web.re_compile(pattern).sub(r'\\\1', value) + quote |
if not options.template_root.endswith("/"): options.template_root += "/" | options.template_root = options.template_root.rstrip("/") | def parse_options(args=None): parser = OptionParser(args) parser.add_option("-s", "--server", dest="server", default="http://openlibrary.org/", help="URL of the openlibrary website (default: %default)") parser.add_option("--template-root", dest="template_root", default="/", help="Template root (default: %default)") par... |
details=False)] | details=True)] | def GET(self): i = web.input(q="", limit=5) i.limit = safeint(i.limit, 5) # temporary implementation until author solr is ready data = web.ctx.site.things( {"type": "/type/author", "name~": i.q.title() + "*", "sort": "name", "name": None, "limit": i.limit}, details=True) for d in data: d.subjects = [] d.works = [w.tit... |
solr_host = config.plugin_worksearch.get['solr'] | solr_host = config.plugin_inside['solr'] | def quote_snippet(snippet): return re_trans.sub(lambda m: trans[m.group(1)], web.htmlquote(snippet)) |
web.ctx.site.save_many(updates, comment='merge authors', action="merge-authors", data=data) | return web.ctx.site.save_many(updates, comment='merge authors', action="merge-authors", data=data) | def do_merge(self, master, old_keys): master_author = web.ctx.site.get(master).dict() master_author['type']['key'] == '/type/author' edition_keys = set() work_keys = set() updates = [] master_needs_save = False for old in old_keys: q = { 'type': '/type/edition', 'authors': {'key': old}, 'works': None, 'limit': 10000, }... |
json = web.data() data = simplejson.loads(json) | jsontext = web.data() data = json.loads(jsontext) | def POST(self): json = web.data() data = simplejson.loads(json) master = data['master'] duplicates = data['duplicates'] return merge_authors().do_merge(master, duplicates) |
return merge_authors().do_merge(master, duplicates) | result = merge_authors().do_merge(master, duplicates) return delegate.RawText(json.dumps(result), content_type="application/json") | def POST(self): json = web.data() data = simplejson.loads(json) master = data['master'] duplicates = data['duplicates'] return merge_authors().do_merge(master, duplicates) |
saveutil.commit(comment, action="add-book") | saveutil.commit(comment=comment, action="add-book") | def work_match(self, saveutil, work, i): edition = self._make_edition(work, i) saveutil.save(edition) comment = utils.get_message("comment_add_book") saveutil.commit(comment, action="add-book") |
OL.save_many(write.values()[:3], comment="Adding tags to New York Times %s bestsellers" % ln) | OL.save_many(write.values(), comment="Adding tags to New York Times %s bestsellers" % ln) | def write_machine_tags(ln, books): key_to_nyt = {} for book in books: for work in book['ol:works']: key_to_nyt[work] = book['nyt'] works = OL.get_many(list(set(key_to_nyt.keys()))) write = {} for work in works: nyt = key_to_nyt[work['key']] tags = ("New York Times bestseller", "nyt:%s=%s" % ("_".join([s.lower() for s ... |
return Seed(self, s) | return Seed(self, seed) | def get_seed(self, seed): if isinstance(seed, dict): seed = seed['key'] return Seed(self, s) |
q_list.append('author_name:(' + v + ')') q_list.append('author_alternative_name:(' + v + ')') | q_list.append('(author_name:(' + v + ') OR author_alternative_name:(' + v + '))') | def run_solr_query(param = {}, rows=100, page=1, sort=None): q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) if q_param: if q_param == '*:*' or re_fields.match(q_param): q_list.append(q_param) else: isbn = read_isbn(q_param) if isbn: q_list.append('isbn:(%s)' % ... |
if base in ['authors', 'books', 'works', 'people', 'usergroup', 'permission']: | if base in ['authors', 'books', 'works', 'languages', 'people', 'usergroup', 'permission']: | def process_json(key, json): if key is None or json is None: return None base = key[1:].split("/")[0] if base in ['authors', 'books', 'works', 'people', 'usergroup', 'permission']: data = simplejson.loads(json) data = _process_data(data) json = simplejson.dumps(data) return json |
if not id_name in e or e[id_name] != id_value: | if not id_name in e or id_value not in e[id_name]: | def try_edition_match(self, work=None, title=None, author_key=None, publisher=None, publish_year=None, id_name=None, id_value=None): # insufficient data if not publisher and not publish_year and not id_value: return q = {} work and q.setdefault('key', work.key.split("/")[-1]) title and q.setdefault('title', title) au... |
is_pbk = False tag_006_says_electric = False | def index_fields(data, want, check_author = True): if str(data)[6:8] != 'am': # only want books return None edition = {} # ['006', '010', '020', '035', '245'] author = { '100': 'person', '110': 'org', '111': 'even', } if check_author: want += author.keys() fields = get_tag_lines(data, ['006', '008', '260'] + want) re... | |
return None | tag_006_says_electric = True | def index_fields(data, want, check_author = True): if str(data)[6:8] != 'am': # only want books return None edition = {} # ['006', '010', '020', '035', '245'] author = { '100': 'person', '110': 'org', '111': 'even', } if check_author: want += author.keys() fields = get_tag_lines(data, ['006', '008', '260'] + want) re... |
key, title = row.value | key, title = row.value['key'], row.value['name'] | def get_subjects(self, limit=20): keys = [[seed, "subjects"] for seed in self._get_rawseeds()] rows = self._seeds_view(keys=keys, reduce=False) # store the counts of subject to pick the top ones subject_counts = defaultdict(lambda: 0) # store counts of tiles of each subject to find the most used title for each subjec... |
if not accept_electronic and line[0] == 'm': return None | if line[0] == 'm': tag_006_says_electric = True | def read_edition(data, accept_electronic = False): edition = {} want = ['001', '003', '006', '008', '010', '020', '035', \ '100', '110', '111', '700', '710', '711', '245', '260', '300'] fields = get_tag_lines(data, want) read_tag = [ ('001', read_control_number, 'control_number'), ('010', read_lccn, 'lccn'), ('020', re... |
def is_daisy_encrypted(ia): | re_collection = re.compile(r'<collection>(.*)</collection>', re.I) def get_ia_collection(ia): | def is_daisy_encrypted(ia): url = 'http://www.archive.org/download/%s/%s_meta.xml' % (ia, ia) look_for = '<collection>printdisabled</collection>' for attempt in range(20): try: return any(i.strip().lower() == look_for for i in urlopen(url)) except: print 'retry', attempt sleep(5) return False |
look_for = '<collection>printdisabled</collection>' for attempt in range(20): | print 'getting:', url for attempt in range(5): | def is_daisy_encrypted(ia): url = 'http://www.archive.org/download/%s/%s_meta.xml' % (ia, ia) look_for = '<collection>printdisabled</collection>' for attempt in range(20): try: return any(i.strip().lower() == look_for for i in urlopen(url)) except: print 'retry', attempt sleep(5) return False |
return any(i.strip().lower() == look_for for i in urlopen(url)) except: print 'retry', attempt | matches = (re_collection.search(line) for line in urlopen(url)) return set(m.group(1).lower() for m in matches if m) except URLError: print 'retry', attempt, url | def is_daisy_encrypted(ia): url = 'http://www.archive.org/download/%s/%s_meta.xml' % (ia, ia) look_for = '<collection>printdisabled</collection>' for attempt in range(20): try: return any(i.strip().lower() == look_for for i in urlopen(url)) except: print 'retry', attempt sleep(5) return False |
return False | return set() | def is_daisy_encrypted(ia): url = 'http://www.archive.org/download/%s/%s_meta.xml' % (ia, ia) look_for = '<collection>printdisabled</collection>' for attempt in range(20): try: return any(i.strip().lower() == look_for for i in urlopen(url)) except: print 'retry', attempt sleep(5) return False |
if 'ocaid' in e and is_daisy_encrypted(e['ocaid']): e['encrypted_daisy'] = True | if 'ocaid' in e: collection = get_ia_collection(e['ocaid']) print 'collection:', collection e['ia_collection'] = collection e['public_scan'] = ('lendinglibrary' not in collection) and ('printdisabled' not in collection) overdrive_id = e.get('identifiers', {}).get('overdrive_id', None) if overdrive_id: e['overdrive'] = ... | def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1) |
'subject_people': 'people', | 'subject_people': 'person', | def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1) |
has_fulltext = any(e.get('ocaid', None) and not e.get('encrypted_daisy', None) for e in editions) | has_fulltext = any(e.get('ocaid', None) or e.get('overdrive', None) for e in editions) print 'has_fulltext:', has_fulltext | def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1) |
goog = set() non_goog = set() for e in editions: if 'ocaid' in e: assert isinstance(e['ocaid'], basestring) i = e['ocaid'].strip() | pub_goog = set() pub_nongoog = set() nonpub_goog = set() nonpub_nongoog = set() public_scan = False all_collection = set() all_overdrive = set() lending_edition = None for e in editions: if 'overdrive' in e: all_overdrive.add(e['overdrive']) if 'ocaid' not in e: continue if not lending_edition and 'lendinglibrary' in ... | def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1) |
goog.add(i) | pub_goog.add(i) | def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1) |
non_goog.add(i) add_field_list(doc, 'ia', list(non_goog) + list(goog)) | pub_nongoog.add(i) else: if i.endswith('goog'): nonpub_goog.add(i) else: nonpub_nongoog.add(i) print 'lending_edition:', lending_edition ia_list = list(pub_nongoog) + list(pub_goog) + list(nonpub_nongoog) + list(nonpub_goog) add_field_list(doc, 'ia', ia_list) if has_fulltext: add_field(doc, 'public_scan_b', public_scan... | def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1) |
return random.sample(changes, n) | if len(changes) > n: return random.sample(changes, n) else: return changes | def get_random_recent_changes(n): if "recentchanges_v2" in web.ctx.features: changes = _get_recent_changes2() else: changes = _get_recent_changes() return random.sample(changes, n) |
path = "(/(?:people|books|works|authors|subjects)/\w+)/lists" | path = "(/(?:people|books|works|authors|subjects)/[^/]+)/lists" | def GET(self): return render_template("lists/home") |
print 'validation failed', f.render() | def POST(self): i = web.input('email', 'password', 'username') i.displayname = i.get('displayname') or i.username f = forms.Register() if not f.validates(i): print 'validation failed', f.render() return render['account/create'](f) try: web.ctx.site.register(i.username, i.displayname, i.email, i.password) except Clie... | |
path = "/account/.*" def GET(self): return render.notfound(create=False) | path = "(/account/.*)" def GET(self, path): print "account_others", path return render.notfound(path, create=False) | def POST(self): key = context.user.key + '/preferences' prefs = web.ctx.site.get(key) d = (prefs and prefs.dict()) or {'key': key, 'type': {'key': '/type/object'}} d['notifications'] = web.input() web.ctx.site.save(d, 'save notifications') add_flash_message('note', _("Notification preferences have been updated succ... |
if key.startswith("/a/"): return "/authors/" + key[len("/a/"):] if key.startswith("/l/"): return "/languages/" + key[len("/l/"):] if key.startswith("/user/"): key2 = key.replace("/user/", "/people/") if self.exists(key2): return key2 if key.startswith("/b/"): key2 = key.replace("/b/", "/books/") if self.exists(key2)... | mapping = ( "/l/", "/languages/", "/a/", "/authors/", "/b/", "/books/", "/user/", "/people/" ) for old, new in web.group(mapping, 2): if key.startswith(old): return new + key[len(old):] | def _process_key(self, key): # migration of authors and languages is complete if key.startswith("/a/"): return "/authors/" + key[len("/a/"):] if key.startswith("/l/"): return "/languages/" + key[len("/l/"):] # migration of users and books is still in progress if key.startswith("/user/"): key2 = key.replace("/user/", "... |
if web.ctx.path == "/api/get" and 'key' in data: | if web.ctx.get('path') == "/api/get" and 'key' in data: | def get(self, sitename, data): if web.ctx.path == "/api/get" and 'key' in data: data['key'] = self._process_key(data['key']) response = ConnectionMiddleware.get(self, sitename, data) if response: data = simplejson.loads(response) response = simplejson.dumps(self._process(data)) return response |
assert re_edition_key.match(e['key']) mc = get_mc(e['key']) | m = re_edition_key.match(e['key']) if not m: print e['key'] mc = get_mc('/b/' + m.group(1)) | def get_marc_source(w): found = set() for e in w['editions']: sr = e.get('source_records', []) if sr: found.update(i[5:] for i in sr if i.startswith('marc:')) else: assert re_edition_key.match(e['key']) mc = get_mc(e['key']) if mc and not mc.startswith('amazon:') and not re_ia_marc.match(mc): found.add(mc) return found... |
for k, v in q.items(): if isinstance(v, basestring): q[k] = convert_key(v) elif isinstance(v, list): q[k] = [convert_key(x) for x in v] self.input.query = simplejson.dumps(q) | def convert_keys(q): if isinstance(q, dict): return dict((k, convert_keys(v)) for k, v in q.items()) elif isinstance(q, list): return [convert_keys(x) for x in q] elif isinstance(q, basestring): return convert_key(q) else: return q self.input.query = simplejson.dumps(convert_keys(q)) | def before_request(self): if 'query' in self.input: q = self.input.query q = simplejson.loads(q) for k, v in q.items(): if isinstance(v, basestring): q[k] = convert_key(v) elif isinstance(v, list): q[k] = [convert_key(x) for x in v] self.input.query = simplejson.dumps(q) |
if not ftoken_db: | if ftoken_db is None: | def GET(self): global ftoken_db i = web.input(author_key=[], language=[], first_publish_year=[], publisher_facet=[], subject_facet=[], person_facet=[], place_facet=[], time_facet=[], ftokens=[]) if i.get('ftokens', []): if not ftoken_db: ftoken_db = dbm.open('/olsystem/ftokens', 'r') token = i.ftokens[0] if token in ft... |
if token in ftoken_db: raise web.seeother('/subject/' + ftoken_db[token].lower().replace(' ', '_')) | if ftoken_db.get(token, None): raise web.seeother('/subject/' + ftoken_db[token].decode('utf-8').lower().replace(' ', '_')) | def GET(self): global ftoken_db i = web.input(author_key=[], language=[], first_publish_year=[], publisher_facet=[], subject_facet=[], person_facet=[], place_facet=[], time_facet=[], ftokens=[]) if i.get('ftokens', []): if not ftoken_db: ftoken_db = dbm.open('/olsystem/ftokens', 'r') token = i.ftokens[0] if token in ft... |
print >> open(statefile, 'w'), offset | print >> open(state_file, 'w'), offset | def run_update(): global authors_to_update global works_to_update global last_update last_update = time() print 'running update: %s works %s authors' % (len(works_to_update), len(authors_to_update)) if works_to_update: requests = [] num = 0 total = len(works_to_update) for wkey in works_to_update: num += 1 print 'updat... |
for work in works: | for work in works.values(): | def write_machine_tags(ln, books): key_to_nyt = {} for book in books: for work in book['ol:works']: key_to_nyt[work] = book['nyt'] works = OL.get_many(list(set(key_to_nyt.keys()))) write = {} for work in works: nyt = key_to_nyt[work['key']] tags = ("New York Times bestseller", "nyt:%s=%s" % ("_".join([s.lower() for s ... |
tags = ("New York Times bestseller", "nyt:%s=%s" % ("_".join([s.lower() for s in ln.split()]), nyt['bestsellers_date'])) | tags = ( "New York Times bestseller", "nyt:%s=%s" % ("_".join([s.lower() for s in ln.split()]), _get_first_bestseller_date(nyt)) ) | def write_machine_tags(ln, books): key_to_nyt = {} for book in books: for work in book['ol:works']: key_to_nyt[work] = book['nyt'] works = OL.get_many(list(set(key_to_nyt.keys()))) write = {} for work in works: nyt = key_to_nyt[work['key']] tags = ("New York Times bestseller", "nyt:%s=%s" % ("_".join([s.lower() for s ... |
w[k].extend(s for s in subjects if s not in w[k]) | existing_subjects = set(w.get(k, [])) w.setdefault(k, []).extend(s for s in subjects if s not in existing_subjects) | def add_subjects_to_work(subjects, w): mapping = { 'subject': 'subjects', 'place': 'subject_places', 'time': 'subject_times', 'person': 'subject_people', } for k, v in subjects.items(): k = mapping[k] subjects = [i[0] for i in sorted(v.items(), key=lambda i:i[1], reverse=True) if i != ''] w[k].extend(s for s in subject... |
existing_work[k] = list(v) | existing_subjects = set(existing_work.get(k, [])) existing_work.setdefault(k, []).extend(s for s in v if s not in existing_subjects) | def update_work_with_best_match(akey, w, work_to_edition, do_updates, fh_log): work_updated = [] best = w['best_match']['key'] update = [] subjects_from_existing_works = defaultdict(set) for wkey in w['existing_works'].iterkeys(): if wkey == best: continue existing = get_with_retry(wkey) for k in 'subjects', 'subject_p... |
if len(params.keys()) == ['isbn']: isbn_redirect(params['isbn']) | if i.keys() == ['isbn']: isbn_redirect(i.isbn) | def GET(self): i = web.input(author_key=[], language=[], first_publish_year=[], publisher_facet=[], subject_facet=[], person_facet=[], place_facet=[], time_facet=[]) params = self.clean_inputs(i) |
return i + 1 | return editions[i + 1] | def get_next(self): """Next edition of work""" if len(self.get('works', [])) != 1: return editions = sorted_work_editions(self.works[0].get_olid()) try: i = editions.index(self.get_olid()) except ValueError: return if i + 1 == len(editions): return return i + 1 |
return i - 1 | return editions[i - 1] | def get_prev(self): """Previous edition of work""" if len(self.get('works', [])) != 1: return editions = sorted_work_editions(self.works[0].get_olid()) try: i = editions.index(self.get_olid()) except ValueError: return if i == 0: return return i - 1 |
self.physical_dimensions = d and UnitParser(["height", "width", "depth"]).format(d) | if d: self.physical_dimensions = UnitParser(["height", "width", "depth"]).format(d) | def set_physical_dimensions(self, d): self.physical_dimensions = d and UnitParser(["height", "width", "depth"]).format(d) |
section = "[%s]" % web.rstrips(options.dest, "http://") | section = "[%s]" % web.lstrips(options.dest, "http://").strip("/") | def main(): options, args = parse_args() if options.src.startswith("http://"): src = OpenLibrary(options.src) else: src = Disk(options.src) if options.dest.startswith("http://"): dest = OpenLibrary(options.dest) section = "[%s]" % web.rstrips(options.dest, "http://") if section in read_lines(os.path.expanduser("~/.ol... |
return af.split('\t') | if '\t' in af: return af.split('\t') else: return re_author_facet.match(af).groups() | def read_author_facet(af): return af.split('\t') |
all_fields = search_fields + ["has_fulltext", "title_suggest", "edition_count", "publish_year", "language", "number_of_pages", "ia_count", "publisher_facet", "author_facet", "fiction", "first_publish_year"] facet_fields = ["has_fulltext", "author_facet", "language", "first_publish_year", "publisher_facet", "fiction", ... | all_fields = search_fields + ["has_fulltext", "title_suggest", "edition_count", "publish_year", "language", "number_of_pages", "ia_count", "publisher_facet", "author_facet", "first_publish_year"] facet_fields = ["has_fulltext", "author_facet", "language", "first_publish_year", "publisher_facet", "subject_facet", "pers... | def read_author_facet(af): return af.split('\t') |
if name in ('fiction', 'has_fulltext'): true_count = e_lst.find("int[@name='true']").text false_count = e_lst.find("int[@name='false']").text | if name == 'has_fulltext': e_true = e_lst.find("int[@name='true']") true_count = e_true.text if e_true else 0 e_false = e_lst.find("int[@name='false']") false_count = e_false.text if e_false else 0 | def read_facets(root): bool_map = dict(true='yes', false='no') e_facet_counts = root.find("lst[@name='facet_counts']") e_facet_fields = e_facet_counts.find("lst[@name='facet_fields']") facets = {} for e_lst in e_facet_fields: assert e_lst.tag == 'lst' name = e_lst.attrib['name'] if name == 'author_facet': name = 'autho... |
first_publish_year = (w['first_publish_year'][0] if 'first_publish_year' in w else None), | first_publish_year = (w['first_publish_year'] if 'first_publish_year' in w else None), | def work_object(w): obj = dict( authors = [web.storage(key='/authors/' + k, name=n) for k, n in zip(w['author_key'], w['author_name'])], edition_count = w['edition_count'], key = '/works/' + w['key'], title = w['title'], cover_edition_key = w.get('cover_edition_key', None), first_publish_year = (w['first_publish_year']... |
solr_select += '&sort=first_publish_year' | solr_select += '&sort=first_publish_year+asc' | def works_by_author(akey, sort='editions', offset=0, limit=1000): q='author_key:' + akey solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=key,author_name,author_key,title,edition_count,ia,cover_edition_key,has_fulltext,first_publish_year&qt=standard&wt=json" % (q, offset, limit) facet... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.