repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
mk-fg/feedjack | feedjack/views.py | cache_last_modified | def cache_last_modified(request, *argz, **kwz):
'''Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator).'''
response, site, cachekey = kwz.get('_view_data') or initview(request)
if not response: return None
return response[1] | python | def cache_last_modified(request, *argz, **kwz):
'''Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator).'''
response, site, cachekey = kwz.get('_view_data') or initview(request)
if not response: return None
return response[1] | [
"def",
"cache_last_modified",
"(",
"request",
",",
"*",
"argz",
",",
"*",
"*",
"kwz",
")",
":",
"response",
",",
"site",
",",
"cachekey",
"=",
"kwz",
".",
"get",
"(",
"'_view_data'",
")",
"or",
"initview",
"(",
"request",
")",
"if",
"not",
"response",
... | Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator). | [
"Last",
"modification",
"date",
"for",
"a",
"cached",
"page",
".",
"Intended",
"for",
"usage",
"in",
"conditional",
"views",
"("
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/views.py#L37-L42 |
mk-fg/feedjack | feedjack/views.py | initview | def initview(request, response_cache=True):
'''Retrieves the basic data needed by all feeds (host, feeds, etc)
Returns a tuple of:
1. A valid cached response or None
2. The current site object
3. The cache key
4. The subscribers for the site (objects)
5. The feeds for the site (ids)'''
http_host, path_info = ( smart_unicode(part.strip('/')) for part in
[ request.META['HTTP_HOST'],
request.META.get('REQUEST_URI', request.META.get('PATH_INFO', '/')) ] )
query_string = request.META['QUERY_STRING']
url = '{0}/{1}'.format(http_host, path_info)
cachekey = u'{0}?{1}'.format(*it.imap(smart_unicode, (path_info, query_string)))
hostdict = fjcache.hostcache_get() or dict()
site_id = hostdict[url] if url in hostdict else None
if site_id and response_cache:
response = fjcache.cache_get(site_id, cachekey)
if response: return response, None, cachekey
if site_id: site = models.Site.objects.get(pk=site_id)
else: # match site from all of them
sites = list(models.Site.objects.all())
if not sites:
# Somebody is requesting something, but the user
# didn't create a site yet. Creating a default one...
site = models.Site(
name='Default Feedjack Site/Planet',
url=request.build_absolute_uri(request.path),
title='Feedjack Site Title',
description='Feedjack Site Description.'
' Please change this in the admin interface.',
template='bootstrap' )
site.save()
else:
# Select the most matching site possible,
# preferring "default" when everything else is equal
results = defaultdict(list)
for site in sites:
relevance, site_url = 0, urlparse(site.url)
if site_url.netloc == http_host: relevance += 10 # host matches
if path_info.startswith(site_url.path.strip('/')): relevance += 10 # path matches
if site.default_site: relevance += 5 # marked as "default"
results[relevance].append((site_url, site))
for relevance in sorted(results, reverse=True):
try: site_url, site = results[relevance][0]
except IndexError: pass
else: break
if site_url.netloc != http_host: # redirect to proper site hostname
response = HttpResponsePermanentRedirect(
'http://{0}/{1}{2}'.format( site_url.netloc, path_info,
'?{0}'.format(query_string) if query_string.strip() else '') )
return (response, timezone.now()), None, cachekey
hostdict[url] = site_id = site.id
fjcache.hostcache_set(hostdict)
if response_cache:
response = fjcache.cache_get(site_id, cachekey)
if response: return response, None, cachekey
return None, site, cachekey | python | def initview(request, response_cache=True):
'''Retrieves the basic data needed by all feeds (host, feeds, etc)
Returns a tuple of:
1. A valid cached response or None
2. The current site object
3. The cache key
4. The subscribers for the site (objects)
5. The feeds for the site (ids)'''
http_host, path_info = ( smart_unicode(part.strip('/')) for part in
[ request.META['HTTP_HOST'],
request.META.get('REQUEST_URI', request.META.get('PATH_INFO', '/')) ] )
query_string = request.META['QUERY_STRING']
url = '{0}/{1}'.format(http_host, path_info)
cachekey = u'{0}?{1}'.format(*it.imap(smart_unicode, (path_info, query_string)))
hostdict = fjcache.hostcache_get() or dict()
site_id = hostdict[url] if url in hostdict else None
if site_id and response_cache:
response = fjcache.cache_get(site_id, cachekey)
if response: return response, None, cachekey
if site_id: site = models.Site.objects.get(pk=site_id)
else: # match site from all of them
sites = list(models.Site.objects.all())
if not sites:
# Somebody is requesting something, but the user
# didn't create a site yet. Creating a default one...
site = models.Site(
name='Default Feedjack Site/Planet',
url=request.build_absolute_uri(request.path),
title='Feedjack Site Title',
description='Feedjack Site Description.'
' Please change this in the admin interface.',
template='bootstrap' )
site.save()
else:
# Select the most matching site possible,
# preferring "default" when everything else is equal
results = defaultdict(list)
for site in sites:
relevance, site_url = 0, urlparse(site.url)
if site_url.netloc == http_host: relevance += 10 # host matches
if path_info.startswith(site_url.path.strip('/')): relevance += 10 # path matches
if site.default_site: relevance += 5 # marked as "default"
results[relevance].append((site_url, site))
for relevance in sorted(results, reverse=True):
try: site_url, site = results[relevance][0]
except IndexError: pass
else: break
if site_url.netloc != http_host: # redirect to proper site hostname
response = HttpResponsePermanentRedirect(
'http://{0}/{1}{2}'.format( site_url.netloc, path_info,
'?{0}'.format(query_string) if query_string.strip() else '') )
return (response, timezone.now()), None, cachekey
hostdict[url] = site_id = site.id
fjcache.hostcache_set(hostdict)
if response_cache:
response = fjcache.cache_get(site_id, cachekey)
if response: return response, None, cachekey
return None, site, cachekey | [
"def",
"initview",
"(",
"request",
",",
"response_cache",
"=",
"True",
")",
":",
"http_host",
",",
"path_info",
"=",
"(",
"smart_unicode",
"(",
"part",
".",
"strip",
"(",
"'/'",
")",
")",
"for",
"part",
"in",
"[",
"request",
".",
"META",
"[",
"'HTTP_HO... | Retrieves the basic data needed by all feeds (host, feeds, etc)
Returns a tuple of:
1. A valid cached response or None
2. The current site object
3. The cache key
4. The subscribers for the site (objects)
5. The feeds for the site (ids) | [
"Retrieves",
"the",
"basic",
"data",
"needed",
"by",
"all",
"feeds",
"(",
"host",
"feeds",
"etc",
")",
"Returns",
"a",
"tuple",
"of",
":",
"1",
".",
"A",
"valid",
"cached",
"response",
"or",
"None",
"2",
".",
"The",
"current",
"site",
"object",
"3",
... | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/views.py#L45-L111 |
mk-fg/feedjack | feedjack/views.py | blogroll | def blogroll(request, btype):
'View that handles the generation of blogrolls.'
response, site, cachekey = initview(request)
if response: return response[0]
template = loader.get_template('feedjack/{0}.xml'.format(btype))
ctx = dict()
fjlib.get_extra_context(site, ctx)
ctx = Context(ctx)
response = HttpResponse(
template.render(ctx), content_type='text/xml; charset=utf-8' )
patch_vary_headers(response, ['Host'])
fjcache.cache_set(site, cachekey, (response, ctx_get(ctx, 'last_modified')))
return response | python | def blogroll(request, btype):
'View that handles the generation of blogrolls.'
response, site, cachekey = initview(request)
if response: return response[0]
template = loader.get_template('feedjack/{0}.xml'.format(btype))
ctx = dict()
fjlib.get_extra_context(site, ctx)
ctx = Context(ctx)
response = HttpResponse(
template.render(ctx), content_type='text/xml; charset=utf-8' )
patch_vary_headers(response, ['Host'])
fjcache.cache_set(site, cachekey, (response, ctx_get(ctx, 'last_modified')))
return response | [
"def",
"blogroll",
"(",
"request",
",",
"btype",
")",
":",
"response",
",",
"site",
",",
"cachekey",
"=",
"initview",
"(",
"request",
")",
"if",
"response",
":",
"return",
"response",
"[",
"0",
"]",
"template",
"=",
"loader",
".",
"get_template",
"(",
... | View that handles the generation of blogrolls. | [
"View",
"that",
"handles",
"the",
"generation",
"of",
"blogrolls",
"."
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/views.py#L124-L138 |
mk-fg/feedjack | feedjack/views.py | buildfeed | def buildfeed(request, feedclass, **criterias):
'View that handles the feeds.'
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(
etag_func=wrap(cache_etag),
last_modified_func=wrap(cache_last_modified) )\
(_buildfeed)(request, feedclass, view_data, **criterias) | python | def buildfeed(request, feedclass, **criterias):
'View that handles the feeds.'
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(
etag_func=wrap(cache_etag),
last_modified_func=wrap(cache_last_modified) )\
(_buildfeed)(request, feedclass, view_data, **criterias) | [
"def",
"buildfeed",
"(",
"request",
",",
"feedclass",
",",
"*",
"*",
"criterias",
")",
":",
"view_data",
"=",
"initview",
"(",
"request",
")",
"wrap",
"=",
"lambda",
"func",
":",
"ft",
".",
"partial",
"(",
"func",
",",
"_view_data",
"=",
"view_data",
"... | View that handles the feeds. | [
"View",
"that",
"handles",
"the",
"feeds",
"."
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/views.py#L149-L156 |
mk-fg/feedjack | feedjack/views.py | mainview | def mainview(request, **criterias):
'View that handles all page requests.'
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(
etag_func=wrap(cache_etag),
last_modified_func=wrap(cache_last_modified) )\
(_mainview)(request, view_data, **criterias) | python | def mainview(request, **criterias):
'View that handles all page requests.'
view_data = initview(request)
wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias)
return condition(
etag_func=wrap(cache_etag),
last_modified_func=wrap(cache_last_modified) )\
(_mainview)(request, view_data, **criterias) | [
"def",
"mainview",
"(",
"request",
",",
"*",
"*",
"criterias",
")",
":",
"view_data",
"=",
"initview",
"(",
"request",
")",
"wrap",
"=",
"lambda",
"func",
":",
"ft",
".",
"partial",
"(",
"func",
",",
"_view_data",
"=",
"view_data",
",",
"*",
"*",
"cr... | View that handles all page requests. | [
"View",
"that",
"handles",
"all",
"page",
"requests",
"."
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/views.py#L210-L217 |
theiviaxx/Frog | frog/views/gallery.py | index | def index(request, obj_id=None):
"""Handles a request based on method and calls the appropriate function"""
if request.method == 'GET':
return get(request, obj_id)
elif request.method == 'POST':
return post(request)
elif request.method == 'PUT':
getPutData(request)
return put(request, obj_id)
elif request.method == 'DELETE':
getPutData(request)
return delete(request, obj_id) | python | def index(request, obj_id=None):
"""Handles a request based on method and calls the appropriate function"""
if request.method == 'GET':
return get(request, obj_id)
elif request.method == 'POST':
return post(request)
elif request.method == 'PUT':
getPutData(request)
return put(request, obj_id)
elif request.method == 'DELETE':
getPutData(request)
return delete(request, obj_id) | [
"def",
"index",
"(",
"request",
",",
"obj_id",
"=",
"None",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"get",
"(",
"request",
",",
"obj_id",
")",
"elif",
"request",
".",
"method",
"==",
"'POST'",
":",
"return",
"post",
"(... | Handles a request based on method and calls the appropriate function | [
"Handles",
"a",
"request",
"based",
"on",
"method",
"and",
"calls",
"the",
"appropriate",
"function"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L69-L80 |
theiviaxx/Frog | frog/views/gallery.py | post | def post(request):
""" Create a Gallery """
defaultname = 'New Gallery %i' % Gallery.objects.all().count()
data = request.POST or json.loads(request.body)['body']
title = data.get('title', defaultname)
description = data.get('description', '')
security = int(data.get('security', Gallery.PUBLIC))
g, created = Gallery.objects.get_or_create(title=title)
g.security = security
g.description = description
g.owner = request.user
g.save()
res = Result()
res.append(g.json())
res.message = 'Gallery created' if created else ''
return JsonResponse(res.asDict()) | python | def post(request):
""" Create a Gallery """
defaultname = 'New Gallery %i' % Gallery.objects.all().count()
data = request.POST or json.loads(request.body)['body']
title = data.get('title', defaultname)
description = data.get('description', '')
security = int(data.get('security', Gallery.PUBLIC))
g, created = Gallery.objects.get_or_create(title=title)
g.security = security
g.description = description
g.owner = request.user
g.save()
res = Result()
res.append(g.json())
res.message = 'Gallery created' if created else ''
return JsonResponse(res.asDict()) | [
"def",
"post",
"(",
"request",
")",
":",
"defaultname",
"=",
"'New Gallery %i'",
"%",
"Gallery",
".",
"objects",
".",
"all",
"(",
")",
".",
"count",
"(",
")",
"data",
"=",
"request",
".",
"POST",
"or",
"json",
".",
"loads",
"(",
"request",
".",
"body... | Create a Gallery | [
"Create",
"a",
"Gallery"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L111-L129 |
theiviaxx/Frog | frog/views/gallery.py | put | def put(request, obj_id=None):
""" Adds Image and Video objects to Gallery based on GUIDs """
data = request.PUT or json.loads(request.body)['body']
guids = data.get('guids', '').split(',')
move = data.get('from')
security = request.PUT.get('security')
gallery = Gallery.objects.get(pk=obj_id)
if guids:
objects = getObjectsFromGuids(guids)
images = filter(lambda x: isinstance(x, Image), objects)
videos = filter(lambda x: isinstance(x, Video), objects)
gallery.images.add(*images)
gallery.videos.add(*videos)
if move:
fromgallery = Gallery.objects.get(pk=move)
fromgallery.images.remove(*images)
fromgallery.videos.remove(*videos)
if security is not None:
gallery.security = json.loads(security)
gallery.save()
for child in gallery.gallery_set.all():
child.security = gallery.security
child.save()
res = Result()
res.append(gallery.json())
return JsonResponse(res.asDict()) | python | def put(request, obj_id=None):
""" Adds Image and Video objects to Gallery based on GUIDs """
data = request.PUT or json.loads(request.body)['body']
guids = data.get('guids', '').split(',')
move = data.get('from')
security = request.PUT.get('security')
gallery = Gallery.objects.get(pk=obj_id)
if guids:
objects = getObjectsFromGuids(guids)
images = filter(lambda x: isinstance(x, Image), objects)
videos = filter(lambda x: isinstance(x, Video), objects)
gallery.images.add(*images)
gallery.videos.add(*videos)
if move:
fromgallery = Gallery.objects.get(pk=move)
fromgallery.images.remove(*images)
fromgallery.videos.remove(*videos)
if security is not None:
gallery.security = json.loads(security)
gallery.save()
for child in gallery.gallery_set.all():
child.security = gallery.security
child.save()
res = Result()
res.append(gallery.json())
return JsonResponse(res.asDict()) | [
"def",
"put",
"(",
"request",
",",
"obj_id",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"PUT",
"or",
"json",
".",
"loads",
"(",
"request",
".",
"body",
")",
"[",
"'body'",
"]",
"guids",
"=",
"data",
".",
"get",
"(",
"'guids'",
",",
"''",... | Adds Image and Video objects to Gallery based on GUIDs | [
"Adds",
"Image",
"and",
"Video",
"objects",
"to",
"Gallery",
"based",
"on",
"GUIDs"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L133-L165 |
theiviaxx/Frog | frog/views/gallery.py | delete | def delete(request, obj_id=None):
""" Removes ImageVideo objects from Gallery """
data = request.DELETE or json.loads(request.body)
guids = data.get('guids').split(',')
objects = getObjectsFromGuids(guids)
gallery = Gallery.objects.get(pk=obj_id)
LOGGER.info('{} removed {} from {}'.format(request.user.email, guids, gallery))
for o in objects:
if isinstance(o, Image):
gallery.images.remove(o)
elif isinstance(o, Video):
gallery.videos.remove(o)
res = Result()
return JsonResponse(res.asDict()) | python | def delete(request, obj_id=None):
""" Removes ImageVideo objects from Gallery """
data = request.DELETE or json.loads(request.body)
guids = data.get('guids').split(',')
objects = getObjectsFromGuids(guids)
gallery = Gallery.objects.get(pk=obj_id)
LOGGER.info('{} removed {} from {}'.format(request.user.email, guids, gallery))
for o in objects:
if isinstance(o, Image):
gallery.images.remove(o)
elif isinstance(o, Video):
gallery.videos.remove(o)
res = Result()
return JsonResponse(res.asDict()) | [
"def",
"delete",
"(",
"request",
",",
"obj_id",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"DELETE",
"or",
"json",
".",
"loads",
"(",
"request",
".",
"body",
")",
"guids",
"=",
"data",
".",
"get",
"(",
"'guids'",
")",
".",
"split",
"(",
... | Removes ImageVideo objects from Gallery | [
"Removes",
"ImageVideo",
"objects",
"from",
"Gallery"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L169-L186 |
theiviaxx/Frog | frog/views/gallery.py | filterObjects | def filterObjects(request, obj_id):
"""
Filters Gallery for the requested ImageVideo objects. Returns a Result object with
serialized objects
"""
if int(obj_id) == 0:
obj = None
else:
obj = Gallery.objects.get(pk=obj_id)
isanonymous = request.user.is_anonymous()
if isanonymous and obj is None:
LOGGER.warn('There was an anonymous access attempt from {} to {}'.format(getClientIP(request), obj))
raise PermissionDenied()
if isanonymous and obj and obj.security != Gallery.PUBLIC:
LOGGER.warn('There was an anonymous access attempt from {} to {}'.format(getClientIP(request), obj))
raise PermissionDenied()
tags = json.loads(request.GET.get('filters', '[[]]'))
more = json.loads(request.GET.get('more', 'false'))
orderby = request.GET.get('orderby', request.user.frog_prefs.get().json()['orderby'])
tags = [t for t in tags if t]
return _filter(request, obj, tags=tags, more=more, orderby=orderby) | python | def filterObjects(request, obj_id):
"""
Filters Gallery for the requested ImageVideo objects. Returns a Result object with
serialized objects
"""
if int(obj_id) == 0:
obj = None
else:
obj = Gallery.objects.get(pk=obj_id)
isanonymous = request.user.is_anonymous()
if isanonymous and obj is None:
LOGGER.warn('There was an anonymous access attempt from {} to {}'.format(getClientIP(request), obj))
raise PermissionDenied()
if isanonymous and obj and obj.security != Gallery.PUBLIC:
LOGGER.warn('There was an anonymous access attempt from {} to {}'.format(getClientIP(request), obj))
raise PermissionDenied()
tags = json.loads(request.GET.get('filters', '[[]]'))
more = json.loads(request.GET.get('more', 'false'))
orderby = request.GET.get('orderby', request.user.frog_prefs.get().json()['orderby'])
tags = [t for t in tags if t]
return _filter(request, obj, tags=tags, more=more, orderby=orderby) | [
"def",
"filterObjects",
"(",
"request",
",",
"obj_id",
")",
":",
"if",
"int",
"(",
"obj_id",
")",
"==",
"0",
":",
"obj",
"=",
"None",
"else",
":",
"obj",
"=",
"Gallery",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"obj_id",
")",
"isanonymous",
"=",... | Filters Gallery for the requested ImageVideo objects. Returns a Result object with
serialized objects | [
"Filters",
"Gallery",
"for",
"the",
"requested",
"ImageVideo",
"objects",
".",
"Returns",
"a",
"Result",
"object",
"with",
"serialized",
"objects"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L190-L216 |
theiviaxx/Frog | frog/views/gallery.py | _filter | def _filter(request, object_, tags=None, more=False, orderby='created'):
"""Filters Piece objects from self based on filters, search, and range
:param tags: List of tag IDs to filter
:type tags: list
:param more -- bool, Returns more of the same filtered set of images based on session range
return list, Objects filtered
"""
res = Result()
models = QUERY_MODELS
idDict = {}
objDict = {}
data = {}
modelmap = {}
length = 75
# -- Get all IDs for each model
for m in models:
modelmap[m.model_class()] = m.model
if object_:
idDict[m.model] = m.model_class().objects.filter(gallery=object_)
else:
idDict[m.model] = m.model_class().objects.all()
if idDict[m.model] is None:
continue
if tags:
for bucket in tags:
searchQuery = ""
o = None
for item in bucket:
if item == 0:
# -- filter by tagless
idDict[m.model].annotate(num_tags=Count('tags'))
if not o:
o = Q()
o |= Q(num_tags__lte=1)
break
elif isinstance(item, six.integer_types):
# -- filter by tag
if not o:
o = Q()
o |= Q(tags__id=item)
else:
# -- add to search string
searchQuery += item + ' '
if not HAYSTACK:
if not o:
o = Q()
# -- use a basic search
o |= Q(title__icontains=item)
if HAYSTACK and searchQuery != "":
# -- once all tags have been filtered, filter by search
searchIDs = search(searchQuery, m.model_class())
if searchIDs:
if not o:
o = Q()
o |= Q(id__in=searchIDs)
if o:
# -- apply the filters
idDict[m.model] = idDict[m.model].annotate(num_tags=Count('tags')).filter(o)
else:
idDict[m.model] = idDict[m.model].none()
# -- Get all ids of filtered objects, this will be a very fast query
idDict[m.model] = list(idDict[m.model].order_by('-{}'.format(orderby)).values_list('id', flat=True))
lastid = request.session.get('last_{}'.format(m.model), 0)
if not idDict[m.model]:
continue
if not more:
lastid = idDict[m.model][0]
index = idDict[m.model].index(lastid)
if more and lastid != 0:
index += 1
idDict[m.model] = idDict[m.model][index:index + length]
# -- perform the main query to retrieve the objects we want
objDict[m.model] = m.model_class().objects.filter(id__in=idDict[m.model])
objDict[m.model] = objDict[m.model].select_related('author').prefetch_related('tags').order_by('-{}'.format(orderby))
objDict[m.model] = list(objDict[m.model])
# -- combine and sort all objects by date
objects = _sortObjects(orderby, **objDict) if len(models) > 1 else objDict.values()[0]
objects = objects[:length]
# -- Find out last ids
lastids = {}
for obj in objects:
lastids['last_{}'.format(modelmap[obj.__class__])] = obj.id
for key, value in lastids.items():
request.session[key] = value
# -- serialize objects
for i in objects:
res.append(i.json())
data['count'] = len(objects)
if settings.DEBUG:
data['queries'] = connection.queries
res.value = data
return JsonResponse(res.asDict()) | python | def _filter(request, object_, tags=None, more=False, orderby='created'):
"""Filters Piece objects from self based on filters, search, and range
:param tags: List of tag IDs to filter
:type tags: list
:param more -- bool, Returns more of the same filtered set of images based on session range
return list, Objects filtered
"""
res = Result()
models = QUERY_MODELS
idDict = {}
objDict = {}
data = {}
modelmap = {}
length = 75
# -- Get all IDs for each model
for m in models:
modelmap[m.model_class()] = m.model
if object_:
idDict[m.model] = m.model_class().objects.filter(gallery=object_)
else:
idDict[m.model] = m.model_class().objects.all()
if idDict[m.model] is None:
continue
if tags:
for bucket in tags:
searchQuery = ""
o = None
for item in bucket:
if item == 0:
# -- filter by tagless
idDict[m.model].annotate(num_tags=Count('tags'))
if not o:
o = Q()
o |= Q(num_tags__lte=1)
break
elif isinstance(item, six.integer_types):
# -- filter by tag
if not o:
o = Q()
o |= Q(tags__id=item)
else:
# -- add to search string
searchQuery += item + ' '
if not HAYSTACK:
if not o:
o = Q()
# -- use a basic search
o |= Q(title__icontains=item)
if HAYSTACK and searchQuery != "":
# -- once all tags have been filtered, filter by search
searchIDs = search(searchQuery, m.model_class())
if searchIDs:
if not o:
o = Q()
o |= Q(id__in=searchIDs)
if o:
# -- apply the filters
idDict[m.model] = idDict[m.model].annotate(num_tags=Count('tags')).filter(o)
else:
idDict[m.model] = idDict[m.model].none()
# -- Get all ids of filtered objects, this will be a very fast query
idDict[m.model] = list(idDict[m.model].order_by('-{}'.format(orderby)).values_list('id', flat=True))
lastid = request.session.get('last_{}'.format(m.model), 0)
if not idDict[m.model]:
continue
if not more:
lastid = idDict[m.model][0]
index = idDict[m.model].index(lastid)
if more and lastid != 0:
index += 1
idDict[m.model] = idDict[m.model][index:index + length]
# -- perform the main query to retrieve the objects we want
objDict[m.model] = m.model_class().objects.filter(id__in=idDict[m.model])
objDict[m.model] = objDict[m.model].select_related('author').prefetch_related('tags').order_by('-{}'.format(orderby))
objDict[m.model] = list(objDict[m.model])
# -- combine and sort all objects by date
objects = _sortObjects(orderby, **objDict) if len(models) > 1 else objDict.values()[0]
objects = objects[:length]
# -- Find out last ids
lastids = {}
for obj in objects:
lastids['last_{}'.format(modelmap[obj.__class__])] = obj.id
for key, value in lastids.items():
request.session[key] = value
# -- serialize objects
for i in objects:
res.append(i.json())
data['count'] = len(objects)
if settings.DEBUG:
data['queries'] = connection.queries
res.value = data
return JsonResponse(res.asDict()) | [
"def",
"_filter",
"(",
"request",
",",
"object_",
",",
"tags",
"=",
"None",
",",
"more",
"=",
"False",
",",
"orderby",
"=",
"'created'",
")",
":",
"res",
"=",
"Result",
"(",
")",
"models",
"=",
"QUERY_MODELS",
"idDict",
"=",
"{",
"}",
"objDict",
"=",... | Filters Piece objects from self based on filters, search, and range
:param tags: List of tag IDs to filter
:type tags: list
:param more -- bool, Returns more of the same filtered set of images based on session range
return list, Objects filtered | [
"Filters",
"Piece",
"objects",
"from",
"self",
"based",
"on",
"filters",
"search",
"and",
"range"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L219-L331 |
theiviaxx/Frog | frog/views/gallery.py | _sortObjects | def _sortObjects(orderby='created', **kwargs):
"""Sorts lists of objects and combines them into a single list"""
o = []
for m in kwargs.values():
for l in iter(m):
o.append(l)
o = list(set(o))
sortfunc = _sortByCreated if orderby == 'created' else _sortByModified
if six.PY2:
o.sort(sortfunc)
else:
o.sort(key=functools.cmp_to_key(sortfunc))
return o | python | def _sortObjects(orderby='created', **kwargs):
"""Sorts lists of objects and combines them into a single list"""
o = []
for m in kwargs.values():
for l in iter(m):
o.append(l)
o = list(set(o))
sortfunc = _sortByCreated if orderby == 'created' else _sortByModified
if six.PY2:
o.sort(sortfunc)
else:
o.sort(key=functools.cmp_to_key(sortfunc))
return o | [
"def",
"_sortObjects",
"(",
"orderby",
"=",
"'created'",
",",
"*",
"*",
"kwargs",
")",
":",
"o",
"=",
"[",
"]",
"for",
"m",
"in",
"kwargs",
".",
"values",
"(",
")",
":",
"for",
"l",
"in",
"iter",
"(",
"m",
")",
":",
"o",
".",
"append",
"(",
"... | Sorts lists of objects and combines them into a single list | [
"Sorts",
"lists",
"of",
"objects",
"and",
"combines",
"them",
"into",
"a",
"single",
"list"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L334-L348 |
theiviaxx/Frog | frog/views/gallery.py | _sortByCreated | def _sortByCreated(a, b):
"""Sort function for object by created date"""
if a.created < b.created:
return 1
elif a.created > b.created:
return -1
else:
return 0 | python | def _sortByCreated(a, b):
"""Sort function for object by created date"""
if a.created < b.created:
return 1
elif a.created > b.created:
return -1
else:
return 0 | [
"def",
"_sortByCreated",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
".",
"created",
"<",
"b",
".",
"created",
":",
"return",
"1",
"elif",
"a",
".",
"created",
">",
"b",
".",
"created",
":",
"return",
"-",
"1",
"else",
":",
"return",
"0"
] | Sort function for object by created date | [
"Sort",
"function",
"for",
"object",
"by",
"created",
"date"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L351-L358 |
theiviaxx/Frog | frog/views/gallery.py | _sortByModified | def _sortByModified(a, b):
"""Sort function for object by modified date"""
if a.modified < b.modified:
return 1
elif a.modified > b.modified:
return -1
else:
return 0 | python | def _sortByModified(a, b):
"""Sort function for object by modified date"""
if a.modified < b.modified:
return 1
elif a.modified > b.modified:
return -1
else:
return 0 | [
"def",
"_sortByModified",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
".",
"modified",
"<",
"b",
".",
"modified",
":",
"return",
"1",
"elif",
"a",
".",
"modified",
">",
"b",
".",
"modified",
":",
"return",
"-",
"1",
"else",
":",
"return",
"0"
] | Sort function for object by modified date | [
"Sort",
"function",
"for",
"object",
"by",
"modified",
"date"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L361-L368 |
theiviaxx/Frog | frog/views/gallery.py | search | def search(query, model):
""" Performs a search query and returns the object ids """
query = query.strip()
LOGGER.debug(query)
sqs = SearchQuerySet()
results = sqs.raw_search('{}*'.format(query)).models(model)
if not results:
results = sqs.raw_search('*{}'.format(query)).models(model)
if not results:
results = sqs.raw_search('*{}*'.format(query)).models(model)
return [o.pk for o in results] | python | def search(query, model):
""" Performs a search query and returns the object ids """
query = query.strip()
LOGGER.debug(query)
sqs = SearchQuerySet()
results = sqs.raw_search('{}*'.format(query)).models(model)
if not results:
results = sqs.raw_search('*{}'.format(query)).models(model)
if not results:
results = sqs.raw_search('*{}*'.format(query)).models(model)
return [o.pk for o in results] | [
"def",
"search",
"(",
"query",
",",
"model",
")",
":",
"query",
"=",
"query",
".",
"strip",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"query",
")",
"sqs",
"=",
"SearchQuerySet",
"(",
")",
"results",
"=",
"sqs",
".",
"raw_search",
"(",
"'{}*'",
".",
"f... | Performs a search query and returns the object ids | [
"Performs",
"a",
"search",
"query",
"and",
"returns",
"the",
"object",
"ids"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/gallery.py#L371-L382 |
janpipek/iso639-python | iso639/__init__.py | find | def find(whatever=None, language=None, iso639_1=None,
iso639_2=None, native=None):
"""Find data row with the language.
:param whatever: key to search in any of the following fields
:param language: key to search in English language name
:param iso639_1: key to search in ISO 639-1 code (2 digits)
:param iso639_2: key to search in ISO 639-2 code (3 digits,
bibliographic & terminological)
:param native: key to search in native language name
:return: a dict with keys (u'name', u'iso639_1', u'iso639_2_b',
u'iso639_2_t', u'native')
All arguments can be both string or unicode (Python 2).
If there are multiple names defined, any of these can be looked for.
"""
if whatever:
keys = [u'name', u'iso639_1', u'iso639_2_b', u'iso639_2_t', u'native']
val = whatever
elif language:
keys = [u'name']
val = language
elif iso639_1:
keys = [u'iso639_1']
val = iso639_1
elif iso639_2:
keys = [u'iso639_2_b', u'iso639_2_t']
val = iso639_2
elif native:
keys = [u'native']
val = native
else:
raise ValueError('Invalid search criteria.')
val = unicode(val).lower()
return next((item for item in data if any(
val in item[key].lower().split("; ") for key in keys)), None) | python | def find(whatever=None, language=None, iso639_1=None,
iso639_2=None, native=None):
"""Find data row with the language.
:param whatever: key to search in any of the following fields
:param language: key to search in English language name
:param iso639_1: key to search in ISO 639-1 code (2 digits)
:param iso639_2: key to search in ISO 639-2 code (3 digits,
bibliographic & terminological)
:param native: key to search in native language name
:return: a dict with keys (u'name', u'iso639_1', u'iso639_2_b',
u'iso639_2_t', u'native')
All arguments can be both string or unicode (Python 2).
If there are multiple names defined, any of these can be looked for.
"""
if whatever:
keys = [u'name', u'iso639_1', u'iso639_2_b', u'iso639_2_t', u'native']
val = whatever
elif language:
keys = [u'name']
val = language
elif iso639_1:
keys = [u'iso639_1']
val = iso639_1
elif iso639_2:
keys = [u'iso639_2_b', u'iso639_2_t']
val = iso639_2
elif native:
keys = [u'native']
val = native
else:
raise ValueError('Invalid search criteria.')
val = unicode(val).lower()
return next((item for item in data if any(
val in item[key].lower().split("; ") for key in keys)), None) | [
"def",
"find",
"(",
"whatever",
"=",
"None",
",",
"language",
"=",
"None",
",",
"iso639_1",
"=",
"None",
",",
"iso639_2",
"=",
"None",
",",
"native",
"=",
"None",
")",
":",
"if",
"whatever",
":",
"keys",
"=",
"[",
"u'name'",
",",
"u'iso639_1'",
",",
... | Find data row with the language.
:param whatever: key to search in any of the following fields
:param language: key to search in English language name
:param iso639_1: key to search in ISO 639-1 code (2 digits)
:param iso639_2: key to search in ISO 639-2 code (3 digits,
bibliographic & terminological)
:param native: key to search in native language name
:return: a dict with keys (u'name', u'iso639_1', u'iso639_2_b',
u'iso639_2_t', u'native')
All arguments can be both string or unicode (Python 2).
If there are multiple names defined, any of these can be looked for. | [
"Find",
"data",
"row",
"with",
"the",
"language",
"."
] | train | https://github.com/janpipek/iso639-python/blob/08c0ac872ac69ab19ccc3b221e43f3f6629e60ef/iso639/__init__.py#L16-L51 |
janpipek/iso639-python | iso639/__init__.py | to_iso639_1 | def to_iso639_1(key):
"""Find ISO 639-1 code for language specified by key.
>>> to_iso639_1("swe")
u'sv'
>>> to_iso639_1("English")
u'en'
"""
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'iso639_1'] | python | def to_iso639_1(key):
"""Find ISO 639-1 code for language specified by key.
>>> to_iso639_1("swe")
u'sv'
>>> to_iso639_1("English")
u'en'
"""
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'iso639_1'] | [
"def",
"to_iso639_1",
"(",
"key",
")",
":",
"item",
"=",
"find",
"(",
"whatever",
"=",
"key",
")",
"if",
"not",
"item",
":",
"raise",
"NonExistentLanguageError",
"(",
"'Language does not exist.'",
")",
"return",
"item",
"[",
"u'iso639_1'",
"]"
] | Find ISO 639-1 code for language specified by key.
>>> to_iso639_1("swe")
u'sv'
>>> to_iso639_1("English")
u'en' | [
"Find",
"ISO",
"639",
"-",
"1",
"code",
"for",
"language",
"specified",
"by",
"key",
"."
] | train | https://github.com/janpipek/iso639-python/blob/08c0ac872ac69ab19ccc3b221e43f3f6629e60ef/iso639/__init__.py#L80-L91 |
janpipek/iso639-python | iso639/__init__.py | to_iso639_2 | def to_iso639_2(key, type='B'):
"""Find ISO 639-2 code for language specified by key.
:param type: "B" - bibliographical (default), "T" - terminological
>>> to_iso639_2("German")
u'ger'
>>> to_iso639_2("German", "T")
u'deu'
"""
if type not in ('B', 'T'):
raise ValueError('Type must be either "B" or "T".')
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
if type == 'T' and item[u'iso639_2_t']:
return item[u'iso639_2_t']
return item[u'iso639_2_b'] | python | def to_iso639_2(key, type='B'):
"""Find ISO 639-2 code for language specified by key.
:param type: "B" - bibliographical (default), "T" - terminological
>>> to_iso639_2("German")
u'ger'
>>> to_iso639_2("German", "T")
u'deu'
"""
if type not in ('B', 'T'):
raise ValueError('Type must be either "B" or "T".')
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
if type == 'T' and item[u'iso639_2_t']:
return item[u'iso639_2_t']
return item[u'iso639_2_b'] | [
"def",
"to_iso639_2",
"(",
"key",
",",
"type",
"=",
"'B'",
")",
":",
"if",
"type",
"not",
"in",
"(",
"'B'",
",",
"'T'",
")",
":",
"raise",
"ValueError",
"(",
"'Type must be either \"B\" or \"T\".'",
")",
"item",
"=",
"find",
"(",
"whatever",
"=",
"key",
... | Find ISO 639-2 code for language specified by key.
:param type: "B" - bibliographical (default), "T" - terminological
>>> to_iso639_2("German")
u'ger'
>>> to_iso639_2("German", "T")
u'deu' | [
"Find",
"ISO",
"639",
"-",
"2",
"code",
"for",
"language",
"specified",
"by",
"key",
"."
] | train | https://github.com/janpipek/iso639-python/blob/08c0ac872ac69ab19ccc3b221e43f3f6629e60ef/iso639/__init__.py#L94-L111 |
janpipek/iso639-python | iso639/__init__.py | to_name | def to_name(key):
"""Find the English name for the language specified by key.
>>> to_name('br')
u'Breton'
>>> to_name('sw')
u'Swahili'
"""
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'name'] | python | def to_name(key):
"""Find the English name for the language specified by key.
>>> to_name('br')
u'Breton'
>>> to_name('sw')
u'Swahili'
"""
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'name'] | [
"def",
"to_name",
"(",
"key",
")",
":",
"item",
"=",
"find",
"(",
"whatever",
"=",
"key",
")",
"if",
"not",
"item",
":",
"raise",
"NonExistentLanguageError",
"(",
"'Language does not exist.'",
")",
"return",
"item",
"[",
"u'name'",
"]"
] | Find the English name for the language specified by key.
>>> to_name('br')
u'Breton'
>>> to_name('sw')
u'Swahili' | [
"Find",
"the",
"English",
"name",
"for",
"the",
"language",
"specified",
"by",
"key",
"."
] | train | https://github.com/janpipek/iso639-python/blob/08c0ac872ac69ab19ccc3b221e43f3f6629e60ef/iso639/__init__.py#L114-L125 |
janpipek/iso639-python | iso639/__init__.py | to_native | def to_native(key):
"""Find the native name for the language specified by key.
>>> to_native('br')
u'brezhoneg'
>>> to_native('sw')
u'Kiswahili'
"""
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'native'] | python | def to_native(key):
"""Find the native name for the language specified by key.
>>> to_native('br')
u'brezhoneg'
>>> to_native('sw')
u'Kiswahili'
"""
item = find(whatever=key)
if not item:
raise NonExistentLanguageError('Language does not exist.')
return item[u'native'] | [
"def",
"to_native",
"(",
"key",
")",
":",
"item",
"=",
"find",
"(",
"whatever",
"=",
"key",
")",
"if",
"not",
"item",
":",
"raise",
"NonExistentLanguageError",
"(",
"'Language does not exist.'",
")",
"return",
"item",
"[",
"u'native'",
"]"
] | Find the native name for the language specified by key.
>>> to_native('br')
u'brezhoneg'
>>> to_native('sw')
u'Kiswahili' | [
"Find",
"the",
"native",
"name",
"for",
"the",
"language",
"specified",
"by",
"key",
"."
] | train | https://github.com/janpipek/iso639-python/blob/08c0ac872ac69ab19ccc3b221e43f3f6629e60ef/iso639/__init__.py#L128-L139 |
mthornhill/django-postal | src/postal/views.py | address_inline | def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"):
""" Displays postal address with localized fields """
country_prefix = "country"
prefix = request.POST.get('prefix', prefix)
if prefix:
country_prefix = prefix + '-country'
country_code = request.POST.get(country_prefix, country_code)
form_class = form_factory(country_code=country_code)
if request.method == "POST":
data = {}
for (key, val) in request.POST.items():
if val is not None and len(val) > 0:
data[key] = val
data.update({country_prefix: country_code})
form = form_class(prefix=prefix, initial=data)
else:
form = form_class(prefix=prefix)
return render_to_string(template_name, RequestContext(request, {
"form": form,
"prefix": prefix,
})) | python | def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"):
""" Displays postal address with localized fields """
country_prefix = "country"
prefix = request.POST.get('prefix', prefix)
if prefix:
country_prefix = prefix + '-country'
country_code = request.POST.get(country_prefix, country_code)
form_class = form_factory(country_code=country_code)
if request.method == "POST":
data = {}
for (key, val) in request.POST.items():
if val is not None and len(val) > 0:
data[key] = val
data.update({country_prefix: country_code})
form = form_class(prefix=prefix, initial=data)
else:
form = form_class(prefix=prefix)
return render_to_string(template_name, RequestContext(request, {
"form": form,
"prefix": prefix,
})) | [
"def",
"address_inline",
"(",
"request",
",",
"prefix",
"=",
"\"\"",
",",
"country_code",
"=",
"None",
",",
"template_name",
"=",
"\"postal/form.html\"",
")",
":",
"country_prefix",
"=",
"\"country\"",
"prefix",
"=",
"request",
".",
"POST",
".",
"get",
"(",
... | Displays postal address with localized fields | [
"Displays",
"postal",
"address",
"with",
"localized",
"fields"
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/views.py#L11-L37 |
lobocv/pyperform | pyperform/benchmark.py | Benchmark.write_log | def write_log(self, fs=None):
"""
Write the results of the benchmark to a log file.
:param fs: file-like object.
"""
log = StringIO.StringIO()
log.write(self.setup_src)
# If the function is not bound, write the test score to the log
if not self.is_class_method:
time_avg = convert_time_units(self.time_average_seconds)
log.write("\nAverage time: {0} \n".format(time_avg))
if fs:
with open(fs, 'w') as _f:
_f.write(log.getvalue()) | python | def write_log(self, fs=None):
"""
Write the results of the benchmark to a log file.
:param fs: file-like object.
"""
log = StringIO.StringIO()
log.write(self.setup_src)
# If the function is not bound, write the test score to the log
if not self.is_class_method:
time_avg = convert_time_units(self.time_average_seconds)
log.write("\nAverage time: {0} \n".format(time_avg))
if fs:
with open(fs, 'w') as _f:
_f.write(log.getvalue()) | [
"def",
"write_log",
"(",
"self",
",",
"fs",
"=",
"None",
")",
":",
"log",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"log",
".",
"write",
"(",
"self",
".",
"setup_src",
")",
"# If the function is not bound, write the test score to the log",
"if",
"not",
"self... | Write the results of the benchmark to a log file.
:param fs: file-like object. | [
"Write",
"the",
"results",
"of",
"the",
"benchmark",
"to",
"a",
"log",
"file",
".",
":",
"param",
"fs",
":",
"file",
"-",
"like",
"object",
"."
] | train | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/benchmark.py#L68-L83 |
lobocv/pyperform | pyperform/benchmark.py | Benchmark.run_timeit | def run_timeit(self, stmt, setup):
""" Create the function call statement as a string used for timeit. """
_timer = timeit.Timer(stmt=stmt, setup=setup)
trials = _timer.repeat(self.timeit_repeat, self.timeit_number)
self.time_average_seconds = sum(trials) / len(trials) / self.timeit_number
# Convert into reasonable time units
time_avg = convert_time_units(self.time_average_seconds)
return time_avg | python | def run_timeit(self, stmt, setup):
""" Create the function call statement as a string used for timeit. """
_timer = timeit.Timer(stmt=stmt, setup=setup)
trials = _timer.repeat(self.timeit_repeat, self.timeit_number)
self.time_average_seconds = sum(trials) / len(trials) / self.timeit_number
# Convert into reasonable time units
time_avg = convert_time_units(self.time_average_seconds)
return time_avg | [
"def",
"run_timeit",
"(",
"self",
",",
"stmt",
",",
"setup",
")",
":",
"_timer",
"=",
"timeit",
".",
"Timer",
"(",
"stmt",
"=",
"stmt",
",",
"setup",
"=",
"setup",
")",
"trials",
"=",
"_timer",
".",
"repeat",
"(",
"self",
".",
"timeit_repeat",
",",
... | Create the function call statement as a string used for timeit. | [
"Create",
"the",
"function",
"call",
"statement",
"as",
"a",
"string",
"used",
"for",
"timeit",
"."
] | train | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/benchmark.py#L85-L92 |
gmr/email-normalize | email_normalize.py | _get_mx_exchanges | def _get_mx_exchanges(domain):
"""Fetch the MX records for the specified domain
:param str domain: The domain to get the MX records for
:rtype: list
"""
try:
answer = resolver.query(domain, 'MX')
return [str(record.exchange).lower()[:-1] for record in answer]
except (resolver.NoAnswer, resolver.NoNameservers, resolver.NotAbsolute,
resolver.NoRootSOA, resolver.NXDOMAIN, resolver.Timeout) as error:
LOGGER.error('Error querying MX for %s: %r', domain, error)
return [] | python | def _get_mx_exchanges(domain):
"""Fetch the MX records for the specified domain
:param str domain: The domain to get the MX records for
:rtype: list
"""
try:
answer = resolver.query(domain, 'MX')
return [str(record.exchange).lower()[:-1] for record in answer]
except (resolver.NoAnswer, resolver.NoNameservers, resolver.NotAbsolute,
resolver.NoRootSOA, resolver.NXDOMAIN, resolver.Timeout) as error:
LOGGER.error('Error querying MX for %s: %r', domain, error)
return [] | [
"def",
"_get_mx_exchanges",
"(",
"domain",
")",
":",
"try",
":",
"answer",
"=",
"resolver",
".",
"query",
"(",
"domain",
",",
"'MX'",
")",
"return",
"[",
"str",
"(",
"record",
".",
"exchange",
")",
".",
"lower",
"(",
")",
"[",
":",
"-",
"1",
"]",
... | Fetch the MX records for the specified domain
:param str domain: The domain to get the MX records for
:rtype: list | [
"Fetch",
"the",
"MX",
"records",
"for",
"the",
"specified",
"domain"
] | train | https://github.com/gmr/email-normalize/blob/407d8271285e40afd77c94ee2dd2180dfdedffdb/email_normalize.py#L35-L48 |
gmr/email-normalize | email_normalize.py | _domain_check | def _domain_check(domain, domain_list, resolve):
"""Returns ``True`` if the ``domain`` is serviced by the ``domain_list``.
:param str domain: The domain to check
:param list domain_list: The domains to check for
:param bool resolve: Resolve the domain
:rtype: bool
"""
if domain in domain_list:
return True
if resolve:
for exchange in _get_mx_exchanges(domain):
for value in domain_list:
if exchange.endswith(value):
return True
return False | python | def _domain_check(domain, domain_list, resolve):
"""Returns ``True`` if the ``domain`` is serviced by the ``domain_list``.
:param str domain: The domain to check
:param list domain_list: The domains to check for
:param bool resolve: Resolve the domain
:rtype: bool
"""
if domain in domain_list:
return True
if resolve:
for exchange in _get_mx_exchanges(domain):
for value in domain_list:
if exchange.endswith(value):
return True
return False | [
"def",
"_domain_check",
"(",
"domain",
",",
"domain_list",
",",
"resolve",
")",
":",
"if",
"domain",
"in",
"domain_list",
":",
"return",
"True",
"if",
"resolve",
":",
"for",
"exchange",
"in",
"_get_mx_exchanges",
"(",
"domain",
")",
":",
"for",
"value",
"i... | Returns ``True`` if the ``domain`` is serviced by the ``domain_list``.
:param str domain: The domain to check
:param list domain_list: The domains to check for
:param bool resolve: Resolve the domain
:rtype: bool | [
"Returns",
"True",
"if",
"the",
"domain",
"is",
"serviced",
"by",
"the",
"domain_list",
"."
] | train | https://github.com/gmr/email-normalize/blob/407d8271285e40afd77c94ee2dd2180dfdedffdb/email_normalize.py#L51-L67 |
gmr/email-normalize | email_normalize.py | normalize | def normalize(email_address, resolve=True):
"""Return the normalized email address, removing
:param str email_address: The normalized email address
:param bool resolve: Resolve the domain
:rtype: str
"""
address = utils.parseaddr(email_address)
local_part, domain_part = address[1].lower().split('@')
# Plus addressing is supported by Microsoft domains and FastMail
if domain_part in MICROSOFT_DOMAINS:
if '+' in local_part:
local_part = local_part.split('+')[0]
# GMail supports plus addressing and throw-away period delimiters
elif _is_gmail(domain_part, resolve):
local_part = local_part.replace('.', '').split('+')[0]
# Yahoo domain handling of - is like plus addressing
elif _is_yahoo(domain_part, resolve):
if '-' in local_part:
local_part = local_part.split('-')[0]
# FastMail has domain part username aliasing and plus addressing
elif _is_fastmail(domain_part, resolve):
domain_segments = domain_part.split('.')
if len(domain_segments) > 2:
local_part = domain_segments[0]
domain_part = '.'.join(domain_segments[1:])
elif '+' in local_part:
local_part = local_part.split('+')[0]
return '@'.join([local_part, domain_part]) | python | def normalize(email_address, resolve=True):
"""Return the normalized email address, removing
:param str email_address: The normalized email address
:param bool resolve: Resolve the domain
:rtype: str
"""
address = utils.parseaddr(email_address)
local_part, domain_part = address[1].lower().split('@')
# Plus addressing is supported by Microsoft domains and FastMail
if domain_part in MICROSOFT_DOMAINS:
if '+' in local_part:
local_part = local_part.split('+')[0]
# GMail supports plus addressing and throw-away period delimiters
elif _is_gmail(domain_part, resolve):
local_part = local_part.replace('.', '').split('+')[0]
# Yahoo domain handling of - is like plus addressing
elif _is_yahoo(domain_part, resolve):
if '-' in local_part:
local_part = local_part.split('-')[0]
# FastMail has domain part username aliasing and plus addressing
elif _is_fastmail(domain_part, resolve):
domain_segments = domain_part.split('.')
if len(domain_segments) > 2:
local_part = domain_segments[0]
domain_part = '.'.join(domain_segments[1:])
elif '+' in local_part:
local_part = local_part.split('+')[0]
return '@'.join([local_part, domain_part]) | [
"def",
"normalize",
"(",
"email_address",
",",
"resolve",
"=",
"True",
")",
":",
"address",
"=",
"utils",
".",
"parseaddr",
"(",
"email_address",
")",
"local_part",
",",
"domain_part",
"=",
"address",
"[",
"1",
"]",
".",
"lower",
"(",
")",
".",
"split",
... | Return the normalized email address, removing
:param str email_address: The normalized email address
:param bool resolve: Resolve the domain
:rtype: str | [
"Return",
"the",
"normalized",
"email",
"address",
"removing"
] | train | https://github.com/gmr/email-normalize/blob/407d8271285e40afd77c94ee2dd2180dfdedffdb/email_normalize.py#L103-L137 |
nad2000/W3C-Validator | w3c_validator/validator.py | validate | def validate(filename, verbose=False):
"""
Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
"""
# is_css = filename.endswith(".css")
is_remote = filename.startswith("http://") or filename.startswith(
"https://")
with tempfile.TemporaryFile() if is_remote else open(
filename, "rb") as f:
if is_remote:
r = requests.get(filename, verify=False)
f.write(r.content)
f.seek(0)
# if is_css:
# cmd = (
# "curl -sF \"file=@%s;type=text/css\" -F output=json -F warning=0 %s"
# % (quoted_filename, CSS_VALIDATOR_URL))
# _ = cmd
# else:
r = requests.post(
HTML_VALIDATOR_URL,
files={"file": (filename, f, "text/html")},
data={
"out": "json",
"showsource": "yes",
},
verify=False)
return r.json() | python | def validate(filename, verbose=False):
"""
Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
"""
# is_css = filename.endswith(".css")
is_remote = filename.startswith("http://") or filename.startswith(
"https://")
with tempfile.TemporaryFile() if is_remote else open(
filename, "rb") as f:
if is_remote:
r = requests.get(filename, verify=False)
f.write(r.content)
f.seek(0)
# if is_css:
# cmd = (
# "curl -sF \"file=@%s;type=text/css\" -F output=json -F warning=0 %s"
# % (quoted_filename, CSS_VALIDATOR_URL))
# _ = cmd
# else:
r = requests.post(
HTML_VALIDATOR_URL,
files={"file": (filename, f, "text/html")},
data={
"out": "json",
"showsource": "yes",
},
verify=False)
return r.json() | [
"def",
"validate",
"(",
"filename",
",",
"verbose",
"=",
"False",
")",
":",
"# is_css = filename.endswith(\".css\")",
"is_remote",
"=",
"filename",
".",
"startswith",
"(",
"\"http://\"",
")",
"or",
"filename",
".",
"startswith",
"(",
"\"https://\"",
")",
"with",
... | Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status. | [
"Validate",
"file",
"and",
"return",
"JSON",
"result",
"as",
"dictionary",
"."
] | train | https://github.com/nad2000/W3C-Validator/blob/81eb35ef9c1fa87c82731b335c46f873e97a4dea/w3c_validator/validator.py#L31-L66 |
nad2000/W3C-Validator | w3c_validator/validator.py | main | def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validator",
)
parser.add_argument(
"--log",
default="INFO",
help=("log level: DEBUG, INFO or INFO "
"(default: INFO)"))
parser.add_argument(
"--version", action="version", version="%(prog)s " + __version__)
parser.add_argument(
"--verbose", help="increase output verbosity", action="store_true")
parser.add_argument(
"source", metavar="F", type=str, nargs="+", help="file or URL")
args = parser.parse_args()
logging.basicConfig(level=getattr(logging, args.log))
LOGGER.info("Files to validate: \n {0}".format("\n ".join(args.source)))
LOGGER.info("Number of files: {0}".format(len(args.source)))
errors = 0
warnings = 0
for f in args.source:
LOGGER.info("validating: %s ..." % f)
retrys = 0
while retrys < 2:
result = validate(f, verbose=args.verbose)
if result:
break
time.sleep(2)
retrys += 1
LOGGER.info("retrying: %s ..." % f)
else:
LOGGER.info("failed: %s" % f)
errors += 1
continue
# import pdb; pdb.set_trace()
if f.endswith(".css"):
errorcount = result["cssvalidation"]["result"]["errorcount"]
warningcount = result["cssvalidation"]["result"]["warningcount"]
errors += errorcount
warnings += warningcount
if errorcount > 0:
LOGGER.info("errors: %d" % errorcount)
if warningcount > 0:
LOGGER.info("warnings: %d" % warningcount)
else:
for msg in result["messages"]:
print_msg(msg)
if msg["type"] == "error":
errors += 1
else:
warnings += 1
sys.exit(min(errors, 255)) | python | def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validator",
)
parser.add_argument(
"--log",
default="INFO",
help=("log level: DEBUG, INFO or INFO "
"(default: INFO)"))
parser.add_argument(
"--version", action="version", version="%(prog)s " + __version__)
parser.add_argument(
"--verbose", help="increase output verbosity", action="store_true")
parser.add_argument(
"source", metavar="F", type=str, nargs="+", help="file or URL")
args = parser.parse_args()
logging.basicConfig(level=getattr(logging, args.log))
LOGGER.info("Files to validate: \n {0}".format("\n ".join(args.source)))
LOGGER.info("Number of files: {0}".format(len(args.source)))
errors = 0
warnings = 0
for f in args.source:
LOGGER.info("validating: %s ..." % f)
retrys = 0
while retrys < 2:
result = validate(f, verbose=args.verbose)
if result:
break
time.sleep(2)
retrys += 1
LOGGER.info("retrying: %s ..." % f)
else:
LOGGER.info("failed: %s" % f)
errors += 1
continue
# import pdb; pdb.set_trace()
if f.endswith(".css"):
errorcount = result["cssvalidation"]["result"]["errorcount"]
warningcount = result["cssvalidation"]["result"]["warningcount"]
errors += errorcount
warnings += warningcount
if errorcount > 0:
LOGGER.info("errors: %d" % errorcount)
if warningcount > 0:
LOGGER.info("warnings: %d" % warningcount)
else:
for msg in result["messages"]:
print_msg(msg)
if msg["type"] == "error":
errors += 1
else:
warnings += 1
sys.exit(min(errors, 255)) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"[v\"",
"+",
"__version__",
"+",
"\"] \"",
"+",
"__doc__",
",",
"prog",
"=",
"\"w3c_validator\"",
",",
")",
"parser",
".",
"add_argument",
"(",
"\"--... | Parser the command line and run the validator. | [
"Parser",
"the",
"command",
"line",
"and",
"run",
"the",
"validator",
"."
] | train | https://github.com/nad2000/W3C-Validator/blob/81eb35ef9c1fa87c82731b335c46f873e97a4dea/w3c_validator/validator.py#L69-L128 |
gmr/tredis | tredis/common.py | format_info_response | def format_info_response(value):
"""Format the response from redis
:param str value: The return response from redis
:rtype: dict
"""
info = {}
for line in value.decode('utf-8').splitlines():
if not line or line[0] == '#':
continue
if ':' in line:
key, value = line.split(':', 1)
info[key] = parse_info_value(value)
return info | python | def format_info_response(value):
"""Format the response from redis
:param str value: The return response from redis
:rtype: dict
"""
info = {}
for line in value.decode('utf-8').splitlines():
if not line or line[0] == '#':
continue
if ':' in line:
key, value = line.split(':', 1)
info[key] = parse_info_value(value)
return info | [
"def",
"format_info_response",
"(",
"value",
")",
":",
"info",
"=",
"{",
"}",
"for",
"line",
"in",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"line",
"or",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
... | Format the response from redis
:param str value: The return response from redis
:rtype: dict | [
"Format",
"the",
"response",
"from",
"redis"
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/common.py#L43-L57 |
aganezov/bg | bg/multicolor.py | Multicolor.update | def update(self, *args):
""" Updates information about colors and their multiplicity in respective :class:`Multicolor` instance.
By iterating over supplied arguments each of which should represent a color object, updates information about colors and their multiplicity in current :class:`Multicolor` instance.
:param args: variable number of colors to add to currently existing multi colors data
:type args: any hashable python object
:return: ``None``, performs inplace changes to :attr:`Multicolor.multicolors` attribute
"""
self.multicolors = self.multicolors + Counter(arg for arg in args) | python | def update(self, *args):
""" Updates information about colors and their multiplicity in respective :class:`Multicolor` instance.
By iterating over supplied arguments each of which should represent a color object, updates information about colors and their multiplicity in current :class:`Multicolor` instance.
:param args: variable number of colors to add to currently existing multi colors data
:type args: any hashable python object
:return: ``None``, performs inplace changes to :attr:`Multicolor.multicolors` attribute
"""
self.multicolors = self.multicolors + Counter(arg for arg in args) | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"multicolors",
"=",
"self",
".",
"multicolors",
"+",
"Counter",
"(",
"arg",
"for",
"arg",
"in",
"args",
")"
] | Updates information about colors and their multiplicity in respective :class:`Multicolor` instance.
By iterating over supplied arguments each of which should represent a color object, updates information about colors and their multiplicity in current :class:`Multicolor` instance.
:param args: variable number of colors to add to currently existing multi colors data
:type args: any hashable python object
:return: ``None``, performs inplace changes to :attr:`Multicolor.multicolors` attribute | [
"Updates",
"information",
"about",
"colors",
"and",
"their",
"multiplicity",
"in",
"respective",
":",
"class",
":",
"Multicolor",
"instance",
"."
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/multicolor.py#L43-L52 |
aganezov/bg | bg/multicolor.py | Multicolor.__delete | def __delete(self, multicolor):
""" Reduces information :class:`Multicolor` attribute by iterating over supplied colors data.
In case supplied argument is a :class:`Multicolor` instance, multi-color specific information to de deleted is set to its :attr:`Multicolor.multicolors`.
In other cases multi-color specific information to de deleted is obtained from iterating over the argument.
Colors and their multiplicity is reduces with a help of ``-`` method of python Counter object.
:param multicolor: information about colors to be deleted from :class:`Multicolor` object
:type multicolor: any iterable with colors object as entries or :class:`Multicolor`
:return: ``None``, performs inplace changes
"""
if isinstance(multicolor, Multicolor):
to_delete = multicolor.multicolors
else:
to_delete = Counter(color for color in multicolor)
self.multicolors = self.multicolors - to_delete | python | def __delete(self, multicolor):
""" Reduces information :class:`Multicolor` attribute by iterating over supplied colors data.
In case supplied argument is a :class:`Multicolor` instance, multi-color specific information to de deleted is set to its :attr:`Multicolor.multicolors`.
In other cases multi-color specific information to de deleted is obtained from iterating over the argument.
Colors and their multiplicity is reduces with a help of ``-`` method of python Counter object.
:param multicolor: information about colors to be deleted from :class:`Multicolor` object
:type multicolor: any iterable with colors object as entries or :class:`Multicolor`
:return: ``None``, performs inplace changes
"""
if isinstance(multicolor, Multicolor):
to_delete = multicolor.multicolors
else:
to_delete = Counter(color for color in multicolor)
self.multicolors = self.multicolors - to_delete | [
"def",
"__delete",
"(",
"self",
",",
"multicolor",
")",
":",
"if",
"isinstance",
"(",
"multicolor",
",",
"Multicolor",
")",
":",
"to_delete",
"=",
"multicolor",
".",
"multicolors",
"else",
":",
"to_delete",
"=",
"Counter",
"(",
"color",
"for",
"color",
"in... | Reduces information :class:`Multicolor` attribute by iterating over supplied colors data.
In case supplied argument is a :class:`Multicolor` instance, multi-color specific information to de deleted is set to its :attr:`Multicolor.multicolors`.
In other cases multi-color specific information to de deleted is obtained from iterating over the argument.
Colors and their multiplicity is reduces with a help of ``-`` method of python Counter object.
:param multicolor: information about colors to be deleted from :class:`Multicolor` object
:type multicolor: any iterable with colors object as entries or :class:`Multicolor`
:return: ``None``, performs inplace changes | [
"Reduces",
"information",
":",
"class",
":",
"Multicolor",
"attribute",
"by",
"iterating",
"over",
"supplied",
"colors",
"data",
"."
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/multicolor.py#L95-L111 |
aganezov/bg | bg/multicolor.py | Multicolor.__merge | def __merge(cls, *multicolors):
""" Produces a new :class:`Multicolor` object resulting from gathering information from all supplied :class:`Multicolor` instances.
New :class:`Multicolor` is created and its :attr:`Multicolor.multicolors` attribute is updated with similar attributes of supplied :class:`Multicolor` objects.
Accounts for subclassing.
:param multicolors: variable number of :class:`Multicolor` objects
:type multicolors: :class:`Multicolor`
:return: object containing gathered information from all supplied arguments
:rtype: :class:`Multicolor`
"""
result = cls()
for multicolor in multicolors:
result.multicolors = result.multicolors + multicolor.multicolors
return result | python | def __merge(cls, *multicolors):
""" Produces a new :class:`Multicolor` object resulting from gathering information from all supplied :class:`Multicolor` instances.
New :class:`Multicolor` is created and its :attr:`Multicolor.multicolors` attribute is updated with similar attributes of supplied :class:`Multicolor` objects.
Accounts for subclassing.
:param multicolors: variable number of :class:`Multicolor` objects
:type multicolors: :class:`Multicolor`
:return: object containing gathered information from all supplied arguments
:rtype: :class:`Multicolor`
"""
result = cls()
for multicolor in multicolors:
result.multicolors = result.multicolors + multicolor.multicolors
return result | [
"def",
"__merge",
"(",
"cls",
",",
"*",
"multicolors",
")",
":",
"result",
"=",
"cls",
"(",
")",
"for",
"multicolor",
"in",
"multicolors",
":",
"result",
".",
"multicolors",
"=",
"result",
".",
"multicolors",
"+",
"multicolor",
".",
"multicolors",
"return"... | Produces a new :class:`Multicolor` object resulting from gathering information from all supplied :class:`Multicolor` instances.
New :class:`Multicolor` is created and its :attr:`Multicolor.multicolors` attribute is updated with similar attributes of supplied :class:`Multicolor` objects.
Accounts for subclassing.
:param multicolors: variable number of :class:`Multicolor` objects
:type multicolors: :class:`Multicolor`
:return: object containing gathered information from all supplied arguments
:rtype: :class:`Multicolor` | [
"Produces",
"a",
"new",
":",
"class",
":",
"Multicolor",
"object",
"resulting",
"from",
"gathering",
"information",
"from",
"all",
"supplied",
":",
"class",
":",
"Multicolor",
"instances",
"."
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/multicolor.py#L114-L129 |
aganezov/bg | bg/multicolor.py | Multicolor.__left_merge | def __left_merge(multicolor1, multicolor2):
""" Updates first supplied :class:`Multicolor` instance with information from second supplied :class:`Multicolor` instance.
First supplied instances attribute :attr:`Multicolor.multicolors` is updated with a help of ``+`` method of python Counter object.
:param multicolor1: instance to update information in
:type multicolor1: :class:`Multicolor`
:param multicolor2: instance to use information for update from
:type multicolor2: :class:`Multicolor`
:return: updated first supplied :class:`Multicolor` instance
:rtype: :class:`Multicolor`
"""
multicolor1.multicolors = multicolor1.multicolors + multicolor2.multicolors
return multicolor1 | python | def __left_merge(multicolor1, multicolor2):
""" Updates first supplied :class:`Multicolor` instance with information from second supplied :class:`Multicolor` instance.
First supplied instances attribute :attr:`Multicolor.multicolors` is updated with a help of ``+`` method of python Counter object.
:param multicolor1: instance to update information in
:type multicolor1: :class:`Multicolor`
:param multicolor2: instance to use information for update from
:type multicolor2: :class:`Multicolor`
:return: updated first supplied :class:`Multicolor` instance
:rtype: :class:`Multicolor`
"""
multicolor1.multicolors = multicolor1.multicolors + multicolor2.multicolors
return multicolor1 | [
"def",
"__left_merge",
"(",
"multicolor1",
",",
"multicolor2",
")",
":",
"multicolor1",
".",
"multicolors",
"=",
"multicolor1",
".",
"multicolors",
"+",
"multicolor2",
".",
"multicolors",
"return",
"multicolor1"
] | Updates first supplied :class:`Multicolor` instance with information from second supplied :class:`Multicolor` instance.
First supplied instances attribute :attr:`Multicolor.multicolors` is updated with a help of ``+`` method of python Counter object.
:param multicolor1: instance to update information in
:type multicolor1: :class:`Multicolor`
:param multicolor2: instance to use information for update from
:type multicolor2: :class:`Multicolor`
:return: updated first supplied :class:`Multicolor` instance
:rtype: :class:`Multicolor` | [
"Updates",
"first",
"supplied",
":",
"class",
":",
"Multicolor",
"instance",
"with",
"information",
"from",
"second",
"supplied",
":",
"class",
":",
"Multicolor",
"instance",
"."
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/multicolor.py#L132-L145 |
aganezov/bg | bg/multicolor.py | Multicolor.similarity_score | def similarity_score(multicolor1, multicolor2):
""" Computes how similar two :class:`Multicolor` objects are from perspective of information, that they contain.
Two multicolors are called to be similar if they contain same colors (at least one). Multiplicity of colors is taken into account as well.
:param multicolor1: first out of two multi-colors to compute similarity between
:type multicolor1: :class:`Multicolor`
:param multicolor2: second out of two multi-colors to compute similarity between
:type multicolor2: :class:`Multicolor`
:return: the similarity score between two supplied :class:`Multicolor` object
:rtype: ``int``
"""
result = 0
for key, value in multicolor1.multicolors.items():
if key in multicolor2.multicolors:
result += min(value, multicolor2.multicolors[key])
return result | python | def similarity_score(multicolor1, multicolor2):
""" Computes how similar two :class:`Multicolor` objects are from perspective of information, that they contain.
Two multicolors are called to be similar if they contain same colors (at least one). Multiplicity of colors is taken into account as well.
:param multicolor1: first out of two multi-colors to compute similarity between
:type multicolor1: :class:`Multicolor`
:param multicolor2: second out of two multi-colors to compute similarity between
:type multicolor2: :class:`Multicolor`
:return: the similarity score between two supplied :class:`Multicolor` object
:rtype: ``int``
"""
result = 0
for key, value in multicolor1.multicolors.items():
if key in multicolor2.multicolors:
result += min(value, multicolor2.multicolors[key])
return result | [
"def",
"similarity_score",
"(",
"multicolor1",
",",
"multicolor2",
")",
":",
"result",
"=",
"0",
"for",
"key",
",",
"value",
"in",
"multicolor1",
".",
"multicolors",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"multicolor2",
".",
"multicolors",
":",
... | Computes how similar two :class:`Multicolor` objects are from perspective of information, that they contain.
Two multicolors are called to be similar if they contain same colors (at least one). Multiplicity of colors is taken into account as well.
:param multicolor1: first out of two multi-colors to compute similarity between
:type multicolor1: :class:`Multicolor`
:param multicolor2: second out of two multi-colors to compute similarity between
:type multicolor2: :class:`Multicolor`
:return: the similarity score between two supplied :class:`Multicolor` object
:rtype: ``int`` | [
"Computes",
"how",
"similar",
"two",
":",
"class",
":",
"Multicolor",
"objects",
"are",
"from",
"perspective",
"of",
"information",
"that",
"they",
"contain",
"."
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/multicolor.py#L148-L164 |
aganezov/bg | bg/multicolor.py | Multicolor.split_colors | def split_colors(cls, multicolor, guidance=None, sorted_guidance=False,
account_for_color_multiplicity_in_guidance=True):
""" Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object.
Guidance is an iterable type of object where each entry has information about groups of colors that has to be separated for current :attr:`Multicolor.multicolors` chunk.
If no Guidance is provided, single-color guidance of :attr:`Multicolor.multicolors` is created.
Guidance object is first reversed sorted to iterate over it from larges color set to the smallest one, as small color sets might be subsets of bigger ones, and shall be utilized only if bigger sets didn't help in separating.
During the first iteration over the guidance information all subsets of :attr:`Multicolor.multicolors` that equal to entries of guidance are recorded.
During second iteration over remaining of the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded.
After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own.
Multiplicity of all separated colors in respective chunks is preserved.
Accounts for subclassing.
:param multicolor: an instance information about colors in which is to be split
:type multicolor: :class:`Multicolor`
:param guidance: information how colors have to be split in current :class:`Multicolor` object
:type guidance: iterable where each entry is iterable with colors entries
:param sorted_guidance: a flag, that indicates is sorting of provided guidance is in order
:return: a list of new :class:`Multicolor` object colors information in which complies with guidance information
:rtype: ``list`` of :class:`Multicolor` objects
"""
if guidance is None:
###############################################################################################
#
# if guidance is not specified, it will be derived from colors in the targeted multicolor
# initially the multiplicity of colors remains as is
#
###############################################################################################
guidance = [Multicolor(*(color for _ in range(multicolor.multicolors[color]))) for color in multicolor.colors]
###############################################################################################
#
# since at this we have a single-colored (maybe with multiplicity greater than 1)
# we don't need to sort anything, as there will be no overlapping multicolor in guidance
#
###############################################################################################
sorted_guidance = True
###############################################################################################
#
# a reference to the targeted multicolor.
# such reference is created only for the future requirement to access information about original multicolor
# Is done for the sake of code clarity and consistency.
#
###############################################################################################
splitting_multicolor = deepcopy(multicolor)
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# we need to create a new guidance (even if original is perfect)
# a new one shall preserve the order of the original, but all multicolors in it
# while keeping information about the actual colors itself, shall have multiplicity equal to 1
#
###############################################################################################
splitting_multicolor = Multicolor(*multicolor.colors)
colors_guidance = [Multicolor(*tmp_multicolor.colors) for tmp_multicolor in guidance]
###############################################################################################
#
# since there might be different multicolors, with the same colors content
# and they will be changed to same multicolors object, after colors multiplicity adjustment
# we need, while preserving the order, leave only unique ones in (the first appearance)
#
###############################################################################################
unique = set()
guidance = []
for c_multicolor in colors_guidance:
if c_multicolor.hashable_representation not in unique:
unique.add(c_multicolor.hashable_representation)
guidance.append(c_multicolor)
if not sorted_guidance:
###############################################################################################
#
# if arguments in function call do not specify explicitly, that the guidance shall be used "as is"
# it is sorted to put "bigger" multicolors in front, and smaller at the back
# as bigger multicolor might contain several smaller multicolors from the guidance, but the correct splitting
# always assumes that the smaller is the splitted result, the better it is
# and such minimization can be obtained only if the biggest chunk of targeted multicolor are ripped off of it first
#
###############################################################################################
guidance = sorted({g_multicolor.hashable_representation for g_multicolor in guidance},
key=lambda g_multicolor: len(g_multicolor),
reverse=True)
guidance = [Multicolor(*hashed) for hashed in guidance]
first_run_result = []
second_run_result = []
for g_multicolor in guidance:
###############################################################################################
#
# first we determine which multicolors in guidance are fully present in the multicolor to split
# "<=" operator can be read as "is_multi_subset_of"
# and retrieve as many copies of it from the multicolor, as we can
# Example:
# multicolor has only one color "blue" with multiplicity "4"
# in guidance we have multicolor with color "blue" with multiplicity "2"
# we must retrieve it fully twice
#
###############################################################################################
###############################################################################################
#
# empty guidance multicolors shall be ignored, as they have no impact on the splitting algorithm
#
###############################################################################################
if len(g_multicolor.colors) == 0:
continue
while g_multicolor <= splitting_multicolor:
first_run_result.append(g_multicolor)
splitting_multicolor -= g_multicolor
for g_multicolor in guidance:
###############################################################################################
#
# secondly we determine which multicolors in guidance are partially present in the multicolor
# NOTE that this is not possible for the case of tree consistent multicolor
# as every partially present
#
###############################################################################################
while len(g_multicolor.intersect(splitting_multicolor).multicolors) > 0:
second_run_result.append(g_multicolor.intersect(splitting_multicolor))
splitting_multicolor -= g_multicolor.intersect(splitting_multicolor)
appendix = splitting_multicolor
result = deepcopy(first_run_result) + deepcopy(second_run_result) + deepcopy([appendix] if len(appendix.multicolors) > 0 else [])
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# if we didn't care for guidance multicolors colors multiplicity, we we splitting a specially created Multicolor
# based only on the colors content.
# After this is done, we need to restore the original multiplicity of each color in result multicolors to the
# count they had in the targeted for splitting multicolor.
# This is possible since in the case when we do not account for colors multiplicity in guidance, we have
# splitting_color variable referencing not the supplied multicolor, and thus internal changes are not made to
# supplied multicolor.
#
###############################################################################################
for r_multicolor in result:
for color in r_multicolor.colors:
r_multicolor.multicolors[color] = multicolor.multicolors[color]
return result | python | def split_colors(cls, multicolor, guidance=None, sorted_guidance=False,
account_for_color_multiplicity_in_guidance=True):
""" Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object.
Guidance is an iterable type of object where each entry has information about groups of colors that has to be separated for current :attr:`Multicolor.multicolors` chunk.
If no Guidance is provided, single-color guidance of :attr:`Multicolor.multicolors` is created.
Guidance object is first reversed sorted to iterate over it from larges color set to the smallest one, as small color sets might be subsets of bigger ones, and shall be utilized only if bigger sets didn't help in separating.
During the first iteration over the guidance information all subsets of :attr:`Multicolor.multicolors` that equal to entries of guidance are recorded.
During second iteration over remaining of the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded.
After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own.
Multiplicity of all separated colors in respective chunks is preserved.
Accounts for subclassing.
:param multicolor: an instance information about colors in which is to be split
:type multicolor: :class:`Multicolor`
:param guidance: information how colors have to be split in current :class:`Multicolor` object
:type guidance: iterable where each entry is iterable with colors entries
:param sorted_guidance: a flag, that indicates is sorting of provided guidance is in order
:return: a list of new :class:`Multicolor` object colors information in which complies with guidance information
:rtype: ``list`` of :class:`Multicolor` objects
"""
if guidance is None:
###############################################################################################
#
# if guidance is not specified, it will be derived from colors in the targeted multicolor
# initially the multiplicity of colors remains as is
#
###############################################################################################
guidance = [Multicolor(*(color for _ in range(multicolor.multicolors[color]))) for color in multicolor.colors]
###############################################################################################
#
# since at this we have a single-colored (maybe with multiplicity greater than 1)
# we don't need to sort anything, as there will be no overlapping multicolor in guidance
#
###############################################################################################
sorted_guidance = True
###############################################################################################
#
# a reference to the targeted multicolor.
# such reference is created only for the future requirement to access information about original multicolor
# Is done for the sake of code clarity and consistency.
#
###############################################################################################
splitting_multicolor = deepcopy(multicolor)
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# we need to create a new guidance (even if original is perfect)
# a new one shall preserve the order of the original, but all multicolors in it
# while keeping information about the actual colors itself, shall have multiplicity equal to 1
#
###############################################################################################
splitting_multicolor = Multicolor(*multicolor.colors)
colors_guidance = [Multicolor(*tmp_multicolor.colors) for tmp_multicolor in guidance]
###############################################################################################
#
# since there might be different multicolors, with the same colors content
# and they will be changed to same multicolors object, after colors multiplicity adjustment
# we need, while preserving the order, leave only unique ones in (the first appearance)
#
###############################################################################################
unique = set()
guidance = []
for c_multicolor in colors_guidance:
if c_multicolor.hashable_representation not in unique:
unique.add(c_multicolor.hashable_representation)
guidance.append(c_multicolor)
if not sorted_guidance:
###############################################################################################
#
# if arguments in function call do not specify explicitly, that the guidance shall be used "as is"
# it is sorted to put "bigger" multicolors in front, and smaller at the back
# as bigger multicolor might contain several smaller multicolors from the guidance, but the correct splitting
# always assumes that the smaller is the splitted result, the better it is
# and such minimization can be obtained only if the biggest chunk of targeted multicolor are ripped off of it first
#
###############################################################################################
guidance = sorted({g_multicolor.hashable_representation for g_multicolor in guidance},
key=lambda g_multicolor: len(g_multicolor),
reverse=True)
guidance = [Multicolor(*hashed) for hashed in guidance]
first_run_result = []
second_run_result = []
for g_multicolor in guidance:
###############################################################################################
#
# first we determine which multicolors in guidance are fully present in the multicolor to split
# "<=" operator can be read as "is_multi_subset_of"
# and retrieve as many copies of it from the multicolor, as we can
# Example:
# multicolor has only one color "blue" with multiplicity "4"
# in guidance we have multicolor with color "blue" with multiplicity "2"
# we must retrieve it fully twice
#
###############################################################################################
###############################################################################################
#
# empty guidance multicolors shall be ignored, as they have no impact on the splitting algorithm
#
###############################################################################################
if len(g_multicolor.colors) == 0:
continue
while g_multicolor <= splitting_multicolor:
first_run_result.append(g_multicolor)
splitting_multicolor -= g_multicolor
for g_multicolor in guidance:
###############################################################################################
#
# secondly we determine which multicolors in guidance are partially present in the multicolor
# NOTE that this is not possible for the case of tree consistent multicolor
# as every partially present
#
###############################################################################################
while len(g_multicolor.intersect(splitting_multicolor).multicolors) > 0:
second_run_result.append(g_multicolor.intersect(splitting_multicolor))
splitting_multicolor -= g_multicolor.intersect(splitting_multicolor)
appendix = splitting_multicolor
result = deepcopy(first_run_result) + deepcopy(second_run_result) + deepcopy([appendix] if len(appendix.multicolors) > 0 else [])
if not account_for_color_multiplicity_in_guidance:
###############################################################################################
#
# if we didn't care for guidance multicolors colors multiplicity, we we splitting a specially created Multicolor
# based only on the colors content.
# After this is done, we need to restore the original multiplicity of each color in result multicolors to the
# count they had in the targeted for splitting multicolor.
# This is possible since in the case when we do not account for colors multiplicity in guidance, we have
# splitting_color variable referencing not the supplied multicolor, and thus internal changes are not made to
# supplied multicolor.
#
###############################################################################################
for r_multicolor in result:
for color in r_multicolor.colors:
r_multicolor.multicolors[color] = multicolor.multicolors[color]
return result | [
"def",
"split_colors",
"(",
"cls",
",",
"multicolor",
",",
"guidance",
"=",
"None",
",",
"sorted_guidance",
"=",
"False",
",",
"account_for_color_multiplicity_in_guidance",
"=",
"True",
")",
":",
"if",
"guidance",
"is",
"None",
":",
"################################... | Produces several new instances of :class:`Multicolor` object by splitting information about colors by using provided guidance iterable set-like object.
Guidance is an iterable type of object where each entry has information about groups of colors that has to be separated for current :attr:`Multicolor.multicolors` chunk.
If no Guidance is provided, single-color guidance of :attr:`Multicolor.multicolors` is created.
Guidance object is first reversed sorted to iterate over it from larges color set to the smallest one, as small color sets might be subsets of bigger ones, and shall be utilized only if bigger sets didn't help in separating.
During the first iteration over the guidance information all subsets of :attr:`Multicolor.multicolors` that equal to entries of guidance are recorded.
During second iteration over remaining of the guidance information, if colors in :attr:`Multicolor.multicolors` form subsets of guidance entries, such instances are recorded.
After this two iterations, the rest of :attr:`Multicolor.multicolors` is recorded as non-tackled and is recorded on its own.
Multiplicity of all separated colors in respective chunks is preserved.
Accounts for subclassing.
:param multicolor: an instance information about colors in which is to be split
:type multicolor: :class:`Multicolor`
:param guidance: information how colors have to be split in current :class:`Multicolor` object
:type guidance: iterable where each entry is iterable with colors entries
:param sorted_guidance: a flag, that indicates is sorting of provided guidance is in order
:return: a list of new :class:`Multicolor` object colors information in which complies with guidance information
:rtype: ``list`` of :class:`Multicolor` objects | [
"Produces",
"several",
"new",
"instances",
"of",
":",
"class",
":",
"Multicolor",
"object",
"by",
"splitting",
"information",
"about",
"colors",
"by",
"using",
"provided",
"guidance",
"iterable",
"set",
"-",
"like",
"object",
"."
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/multicolor.py#L167-L303 |
aganezov/bg | bg/multicolor.py | Multicolor.intersect | def intersect(self, other):
""" Computes the multiset intersection, between the current Multicolor and the supplied Multicolor
:param other: another Multicolor object to compute a multiset intersection with
:return:
:raise TypeError: an intersection can be computed only between two Multicolor objects
"""
if not isinstance(other, Multicolor):
raise TypeError("Multicolor can be intersected only with another Multicolor object")
intersection_colors_core = self.colors.intersection(other.colors)
colors_count = {color: min(self.multicolors[color], other.multicolors[color]) for color in intersection_colors_core}
return Multicolor(*(color for color in colors_count for _ in range(colors_count[color]))) | python | def intersect(self, other):
""" Computes the multiset intersection, between the current Multicolor and the supplied Multicolor
:param other: another Multicolor object to compute a multiset intersection with
:return:
:raise TypeError: an intersection can be computed only between two Multicolor objects
"""
if not isinstance(other, Multicolor):
raise TypeError("Multicolor can be intersected only with another Multicolor object")
intersection_colors_core = self.colors.intersection(other.colors)
colors_count = {color: min(self.multicolors[color], other.multicolors[color]) for color in intersection_colors_core}
return Multicolor(*(color for color in colors_count for _ in range(colors_count[color]))) | [
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Multicolor",
")",
":",
"raise",
"TypeError",
"(",
"\"Multicolor can be intersected only with another Multicolor object\"",
")",
"intersection_colors_core",
"=",
"se... | Computes the multiset intersection, between the current Multicolor and the supplied Multicolor
:param other: another Multicolor object to compute a multiset intersection with
:return:
:raise TypeError: an intersection can be computed only between two Multicolor objects | [
"Computes",
"the",
"multiset",
"intersection",
"between",
"the",
"current",
"Multicolor",
"and",
"the",
"supplied",
"Multicolor"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/multicolor.py#L494-L505 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | text2wfreq | def text2wfreq(text, output_file, hashtablesize=1000000, verbosity=2):
"""
List of every word which occurred in the text, along with its number of occurrences.
Notes : Uses a hash-table to provide an efficient method of counting word occurrences. Output list is not sorted (due to "randomness" of the hash-table), but can be easily sorted into the user's desired order by the UNIX sort command. In any case, the output does not need to be sorted in order to serve as input for wfreq2vocab. Higher values for the hashtablesize parameter require more memory, but can reduce computation time.
"""
cmd = ['text2wfreq', '-hash', hashtablesize,
'-verbosity', verbosity]
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as input_f:
input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text)
input_f.seek(0)
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | python | def text2wfreq(text, output_file, hashtablesize=1000000, verbosity=2):
"""
List of every word which occurred in the text, along with its number of occurrences.
Notes : Uses a hash-table to provide an efficient method of counting word occurrences. Output list is not sorted (due to "randomness" of the hash-table), but can be easily sorted into the user's desired order by the UNIX sort command. In any case, the output does not need to be sorted in order to serve as input for wfreq2vocab. Higher values for the hashtablesize parameter require more memory, but can reduce computation time.
"""
cmd = ['text2wfreq', '-hash', hashtablesize,
'-verbosity', verbosity]
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as input_f:
input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text)
input_f.seek(0)
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | [
"def",
"text2wfreq",
"(",
"text",
",",
"output_file",
",",
"hashtablesize",
"=",
"1000000",
",",
"verbosity",
"=",
"2",
")",
":",
"cmd",
"=",
"[",
"'text2wfreq'",
",",
"'-hash'",
",",
"hashtablesize",
",",
"'-verbosity'",
",",
"verbosity",
"]",
"# Ensure tha... | List of every word which occurred in the text, along with its number of occurrences.
Notes : Uses a hash-table to provide an efficient method of counting word occurrences. Output list is not sorted (due to "randomness" of the hash-table), but can be easily sorted into the user's desired order by the UNIX sort command. In any case, the output does not need to be sorted in order to serve as input for wfreq2vocab. Higher values for the hashtablesize parameter require more memory, but can reduce computation time. | [
"List",
"of",
"every",
"word",
"which",
"occurred",
"in",
"the",
"text",
"along",
"with",
"its",
"number",
"of",
"occurrences",
".",
"Notes",
":",
"Uses",
"a",
"hash",
"-",
"table",
"to",
"provide",
"an",
"efficient",
"method",
"of",
"counting",
"word",
... | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L92-L114 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | wfreq2vocab | def wfreq2vocab(wfreq_file, output_file, top=None, gt=None, records=1000000, verbosity=2):
"""
Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file.
The top parameter allows the user to specify the size of the vocabulary; if the function is called with the parameter top=20000, then the vocabulary will consist of the most common 20,000 words.
The gt parameter allows the user to specify the number of times that a word must occur to be included in the vocabulary; if the function is called with the parameter gt=10, then the vocabulary will consist of all the words which occurred more than 10 times.
If neither the gt, nor the top parameters are specified, then the function runs with the default setting of taking the top 20,000 words.
The records parameter (default: 1000000) allows the user to specify how many of the word and count records to allocate memory for. If the number of words in the input exceeds this number, then the function will fail and raise a ConversionError, but a high number will obviously result in a higher memory requirement.
"""
cmd = ['wfreq2vocab', '-verbosity', verbosity,
'-records', records]
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
if top:
cmd.extend(['-top',top])
elif gt:
cmd.extend(['-gt',gt])
with open(wfreq_file,'r') as input_f:
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | python | def wfreq2vocab(wfreq_file, output_file, top=None, gt=None, records=1000000, verbosity=2):
"""
Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file.
The top parameter allows the user to specify the size of the vocabulary; if the function is called with the parameter top=20000, then the vocabulary will consist of the most common 20,000 words.
The gt parameter allows the user to specify the number of times that a word must occur to be included in the vocabulary; if the function is called with the parameter gt=10, then the vocabulary will consist of all the words which occurred more than 10 times.
If neither the gt, nor the top parameters are specified, then the function runs with the default setting of taking the top 20,000 words.
The records parameter (default: 1000000) allows the user to specify how many of the word and count records to allocate memory for. If the number of words in the input exceeds this number, then the function will fail and raise a ConversionError, but a high number will obviously result in a higher memory requirement.
"""
cmd = ['wfreq2vocab', '-verbosity', verbosity,
'-records', records]
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
if top:
cmd.extend(['-top',top])
elif gt:
cmd.extend(['-gt',gt])
with open(wfreq_file,'r') as input_f:
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | [
"def",
"wfreq2vocab",
"(",
"wfreq_file",
",",
"output_file",
",",
"top",
"=",
"None",
",",
"gt",
"=",
"None",
",",
"records",
"=",
"1000000",
",",
"verbosity",
"=",
"2",
")",
":",
"cmd",
"=",
"[",
"'wfreq2vocab'",
",",
"'-verbosity'",
",",
"verbosity",
... | Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file.
The top parameter allows the user to specify the size of the vocabulary; if the function is called with the parameter top=20000, then the vocabulary will consist of the most common 20,000 words.
The gt parameter allows the user to specify the number of times that a word must occur to be included in the vocabulary; if the function is called with the parameter gt=10, then the vocabulary will consist of all the words which occurred more than 10 times.
If neither the gt, nor the top parameters are specified, then the function runs with the default setting of taking the top 20,000 words.
The records parameter (default: 1000000) allows the user to specify how many of the word and count records to allocate memory for. If the number of words in the input exceeds this number, then the function will fail and raise a ConversionError, but a high number will obviously result in a higher memory requirement. | [
"Takes",
"a",
"a",
"word",
"unigram",
"file",
"as",
"produced",
"by",
"text2wfreq",
"and",
"converts",
"it",
"to",
"a",
"vocabulary",
"file",
".",
"The",
"top",
"parameter",
"allows",
"the",
"user",
"to",
"specify",
"the",
"size",
"of",
"the",
"vocabulary"... | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L116-L144 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | text2wngram | def text2wngram(text, output_file, n=3, chars=63636363, words=9090909, compress=False, verbosity=2):
"""
List of every word n-gram which occurred in the text, along with its number of occurrences.
The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and words parameters.
"""
cmd = ['text2wngram']
if n:
cmd.extend(['-n', n])
if chars:
cmd.extend(['-chars', chars])
if words:
cmd.extend(['-words', words])
if compress:
cmd.append('-compress')
if verbosity:
cmd.extend(['-verbosity', verbosity])
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as input_f:
input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text)
input_f.seek(0)
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
with do_in_tempdir():
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | python | def text2wngram(text, output_file, n=3, chars=63636363, words=9090909, compress=False, verbosity=2):
"""
List of every word n-gram which occurred in the text, along with its number of occurrences.
The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and words parameters.
"""
cmd = ['text2wngram']
if n:
cmd.extend(['-n', n])
if chars:
cmd.extend(['-chars', chars])
if words:
cmd.extend(['-words', words])
if compress:
cmd.append('-compress')
if verbosity:
cmd.extend(['-verbosity', verbosity])
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as input_f:
input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text)
input_f.seek(0)
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
with do_in_tempdir():
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | [
"def",
"text2wngram",
"(",
"text",
",",
"output_file",
",",
"n",
"=",
"3",
",",
"chars",
"=",
"63636363",
",",
"words",
"=",
"9090909",
",",
"compress",
"=",
"False",
",",
"verbosity",
"=",
"2",
")",
":",
"cmd",
"=",
"[",
"'text2wngram'",
"]",
"if",
... | List of every word n-gram which occurred in the text, along with its number of occurrences.
The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and words parameters. | [
"List",
"of",
"every",
"word",
"n",
"-",
"gram",
"which",
"occurred",
"in",
"the",
"text",
"along",
"with",
"its",
"number",
"of",
"occurrences",
".",
"The",
"maximum",
"numbers",
"of",
"charactors",
"and",
"words",
"that",
"can",
"be",
"stored",
"in",
"... | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L146-L183 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | ngram2mgram | def ngram2mgram(input_file, output_file, n, m, words=False, ascii_idngram=False):
"""
Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n.
"""
cmd = ['ngram2mgram', '-n', n,
'-m', m]
if words and ascii_idngram:
raise ConversionError("Parameters 'words' and 'ascii_idngram' cannot both be True")
if words:
cmd.append('-words')
elif ascii_idngram:
cmd.append('-ascii')
else:
cmd.append('-binary')
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with open(input_file,'r') as input_f:
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | python | def ngram2mgram(input_file, output_file, n, m, words=False, ascii_idngram=False):
"""
Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n.
"""
cmd = ['ngram2mgram', '-n', n,
'-m', m]
if words and ascii_idngram:
raise ConversionError("Parameters 'words' and 'ascii_idngram' cannot both be True")
if words:
cmd.append('-words')
elif ascii_idngram:
cmd.append('-ascii')
else:
cmd.append('-binary')
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with open(input_file,'r') as input_f:
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | [
"def",
"ngram2mgram",
"(",
"input_file",
",",
"output_file",
",",
"n",
",",
"m",
",",
"words",
"=",
"False",
",",
"ascii_idngram",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'ngram2mgram'",
",",
"'-n'",
",",
"n",
",",
"'-m'",
",",
"m",
"]",
"if",
"w... | Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n. | [
"Takes",
"either",
"a",
"word",
"n",
"-",
"gram",
"file",
"or",
"an",
"id",
"n",
"-",
"gram",
"file",
"and",
"outputs",
"a",
"file",
"of",
"the",
"same",
"type",
"where",
"m",
"<",
"n",
"."
] | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L244-L273 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | wngram2idngram | def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10):
"""
Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format.
Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this should not be an issue, as they will already be alphabetically sorted.
"""
cmd = ['wngram2idngram', '-vocab', os.path.abspath(vocab_file),
'-idngram', os.path.abspath(output_file)]
if buffersize:
cmd.extend(['-buffer', buffersize])
if hashtablesize:
cmd.extend(['-hash', hashtablesize])
if files:
cmd.extend(['-files', files])
if verbosity:
cmd.extend(['-verbosity', verbosity])
if n:
cmd.extend(['-n', n])
if fof_size:
cmd.extend(['-fof_size', fof_size])
if compress:
cmd.append('-compress')
if write_ascii:
cmd.append('-write_ascii')
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as output_f:
with tempfile.SpooledTemporaryFile() as input_f:
input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text)
input_f.seek(0)
with output_to_debuglogger() as err_f:
with do_in_tempdir():
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
output = output_f.read()
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%r' returned with non-zero exit status '%s'" % (cmd, exitcode))
if sys.version_info >= (3,) and type(output) is bytes:
output = output.decode('utf-8')
return output.strip() | python | def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10):
"""
Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format.
Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this should not be an issue, as they will already be alphabetically sorted.
"""
cmd = ['wngram2idngram', '-vocab', os.path.abspath(vocab_file),
'-idngram', os.path.abspath(output_file)]
if buffersize:
cmd.extend(['-buffer', buffersize])
if hashtablesize:
cmd.extend(['-hash', hashtablesize])
if files:
cmd.extend(['-files', files])
if verbosity:
cmd.extend(['-verbosity', verbosity])
if n:
cmd.extend(['-n', n])
if fof_size:
cmd.extend(['-fof_size', fof_size])
if compress:
cmd.append('-compress')
if write_ascii:
cmd.append('-write_ascii')
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as output_f:
with tempfile.SpooledTemporaryFile() as input_f:
input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text)
input_f.seek(0)
with output_to_debuglogger() as err_f:
with do_in_tempdir():
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
output = output_f.read()
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%r' returned with non-zero exit status '%s'" % (cmd, exitcode))
if sys.version_info >= (3,) and type(output) is bytes:
output = output.decode('utf-8')
return output.strip() | [
"def",
"wngram2idngram",
"(",
"input_file",
",",
"vocab_file",
",",
"output_file",
",",
"buffersize",
"=",
"100",
",",
"hashtablesize",
"=",
"2000000",
",",
"files",
"=",
"20",
",",
"compress",
"=",
"False",
",",
"verbosity",
"=",
"2",
",",
"n",
"=",
"3"... | Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format.
Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this should not be an issue, as they will already be alphabetically sorted. | [
"Takes",
"a",
"word",
"N",
"-",
"gram",
"file",
"and",
"a",
"vocabulary",
"file",
"and",
"lists",
"every",
"id",
"n",
"-",
"gram",
"which",
"occurred",
"in",
"the",
"text",
"along",
"with",
"its",
"number",
"of",
"occurrences",
"in",
"either",
"ASCII",
... | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L275-L327 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | idngram2stats | def idngram2stats(input_file, output_file, n=3, fof_size=50, verbosity=2, ascii_input=False):
"""
Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in idngram2lm.
"""
cmd = ['idngram2stats']
if n:
cmd.extend(['-n', n])
if fof_size:
cmd.extend(['-fof_size'], fof_size)
if verbosity:
cmd.extend(['-verbosity'], verbosity)
if ascii_input:
cmd.append(['-ascii_input'])
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with open(input_file,'r') as input_f:
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | python | def idngram2stats(input_file, output_file, n=3, fof_size=50, verbosity=2, ascii_input=False):
"""
Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in idngram2lm.
"""
cmd = ['idngram2stats']
if n:
cmd.extend(['-n', n])
if fof_size:
cmd.extend(['-fof_size'], fof_size)
if verbosity:
cmd.extend(['-verbosity'], verbosity)
if ascii_input:
cmd.append(['-ascii_input'])
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with open(input_file,'r') as input_f:
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | [
"def",
"idngram2stats",
"(",
"input_file",
",",
"output_file",
",",
"n",
"=",
"3",
",",
"fof_size",
"=",
"50",
",",
"verbosity",
"=",
"2",
",",
"ascii_input",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'idngram2stats'",
"]",
"if",
"n",
":",
"cmd",
"."... | Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in idngram2lm. | [
"Lists",
"the",
"frequency",
"-",
"of",
"-",
"frequencies",
"for",
"each",
"of",
"the",
"2",
"-",
"grams",
"...",
"n",
"-",
"grams",
"which",
"can",
"enable",
"the",
"user",
"to",
"choose",
"appropriate",
"cut",
"-",
"offs",
"and",
"to",
"specify",
"ap... | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L329-L358 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | mergeidngram | def mergeidngram(output_file, input_files, n=3, ascii_input=False, ascii_output=False):
"""
Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram.
Notes : This function can also be used to convert id n-gram files between ascii and binary formats.
"""
cmd = ['mergeidngram']
if n:
cmd.extend(['-n', n])
if ascii_input:
cmd.append('-ascii_input')
if ascii_output:
cmd.append('-ascii_output')
if len(input_file) > 1:
raise MergeError("mergeidngram needs at least 1 input file")
cmd.extend(input_files)
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | python | def mergeidngram(output_file, input_files, n=3, ascii_input=False, ascii_output=False):
"""
Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram.
Notes : This function can also be used to convert id n-gram files between ascii and binary formats.
"""
cmd = ['mergeidngram']
if n:
cmd.extend(['-n', n])
if ascii_input:
cmd.append('-ascii_input')
if ascii_output:
cmd.append('-ascii_output')
if len(input_file) > 1:
raise MergeError("mergeidngram needs at least 1 input file")
cmd.extend(input_files)
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with open(output_file,'w+') as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdout=output_f, stderr=err_f)
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode)) | [
"def",
"mergeidngram",
"(",
"output_file",
",",
"input_files",
",",
"n",
"=",
"3",
",",
"ascii_input",
"=",
"False",
",",
"ascii_output",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'mergeidngram'",
"]",
"if",
"n",
":",
"cmd",
".",
"extend",
"(",
"[",
... | Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram.
Notes : This function can also be used to convert id n-gram files between ascii and binary formats. | [
"Takes",
"a",
"set",
"of",
"id",
"n",
"-",
"gram",
"files",
"(",
"in",
"either",
"binary",
"(",
"by",
"default",
")",
"or",
"ASCII",
"(",
"if",
"specified",
")",
"format",
"-",
"note",
"that",
"they",
"should",
"all",
"be",
"in",
"the",
"same",
"fo... | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L360-L392 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | idngram2lm | def idngram2lm(idngram_file, vocab_file, output_file, context_file=None, vocab_type=1, oov_fraction=0.5, four_byte_counts=False, min_unicount=0, zeroton_fraction=False, n=3, verbosity=2, arpa_output=True, ascii_input=False):
"""
Takes an idngram-file (in either binary (by default) or ASCII (if specified) format), a vocabulary file, and (optionally) a context cues file. Additional command line parameters will specify the cutoffs, the discounting strategy and parameters, etc. It outputs a language model, in either binary format (to be read by evallm), or in ARPA format.
"""
# TODO: Args still missing
# [ -calc_mem | -buffer 100 | -spec_num y ... z ]
# [ -two_byte_bo_weights
# [ -min_bo_weight nnnnn] [ -max_bo_weight nnnnn] [ -out_of_range_bo_weights] ]
# [ -linear | -absolute | -good_turing | -witten_bell ]
# [ -disc_ranges 1 7 7 ]
# [ -cutoffs 0 ... 0 ]
cmd = ['idngram2lm', '-idngram', os.path.abspath(idngram_file),
'-vocab', os.path.abspath(vocab_file),
'-vocab_type', vocab_type,
'-oov_fraction', oov_fraction,
'-min_unicount',min_unicount,
'-verbosity',verbosity,
'-n',n]
if arpa_output:
cmd.extend(['-arpa',output_file])
else:
cmd.extend(['-binary',output_file])
if four_byte_counts:
cmd.append('-four_byte_counts')
if zeroton_fraction:
cmd.append('-zeroton_fraction')
if ascii_input:
cmd.append('-ascii_input')
else:
cmd.append('-bin_input')
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdout=output_f, stderr=err_f)
output = output_f.read()
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode))
if sys.version_info >= (3,) and type(output) is bytes:
output = output.decode('utf-8')
return output.strip() | python | def idngram2lm(idngram_file, vocab_file, output_file, context_file=None, vocab_type=1, oov_fraction=0.5, four_byte_counts=False, min_unicount=0, zeroton_fraction=False, n=3, verbosity=2, arpa_output=True, ascii_input=False):
"""
Takes an idngram-file (in either binary (by default) or ASCII (if specified) format), a vocabulary file, and (optionally) a context cues file. Additional command line parameters will specify the cutoffs, the discounting strategy and parameters, etc. It outputs a language model, in either binary format (to be read by evallm), or in ARPA format.
"""
# TODO: Args still missing
# [ -calc_mem | -buffer 100 | -spec_num y ... z ]
# [ -two_byte_bo_weights
# [ -min_bo_weight nnnnn] [ -max_bo_weight nnnnn] [ -out_of_range_bo_weights] ]
# [ -linear | -absolute | -good_turing | -witten_bell ]
# [ -disc_ranges 1 7 7 ]
# [ -cutoffs 0 ... 0 ]
cmd = ['idngram2lm', '-idngram', os.path.abspath(idngram_file),
'-vocab', os.path.abspath(vocab_file),
'-vocab_type', vocab_type,
'-oov_fraction', oov_fraction,
'-min_unicount',min_unicount,
'-verbosity',verbosity,
'-n',n]
if arpa_output:
cmd.extend(['-arpa',output_file])
else:
cmd.extend(['-binary',output_file])
if four_byte_counts:
cmd.append('-four_byte_counts')
if zeroton_fraction:
cmd.append('-zeroton_fraction')
if ascii_input:
cmd.append('-ascii_input')
else:
cmd.append('-bin_input')
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdout=output_f, stderr=err_f)
output = output_f.read()
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode))
if sys.version_info >= (3,) and type(output) is bytes:
output = output.decode('utf-8')
return output.strip() | [
"def",
"idngram2lm",
"(",
"idngram_file",
",",
"vocab_file",
",",
"output_file",
",",
"context_file",
"=",
"None",
",",
"vocab_type",
"=",
"1",
",",
"oov_fraction",
"=",
"0.5",
",",
"four_byte_counts",
"=",
"False",
",",
"min_unicount",
"=",
"0",
",",
"zerot... | Takes an idngram-file (in either binary (by default) or ASCII (if specified) format), a vocabulary file, and (optionally) a context cues file. Additional command line parameters will specify the cutoffs, the discounting strategy and parameters, etc. It outputs a language model, in either binary format (to be read by evallm), or in ARPA format. | [
"Takes",
"an",
"idngram",
"-",
"file",
"(",
"in",
"either",
"binary",
"(",
"by",
"default",
")",
"or",
"ASCII",
"(",
"if",
"specified",
")",
"format",
")",
"a",
"vocabulary",
"file",
"and",
"(",
"optionally",
")",
"a",
"context",
"cues",
"file",
".",
... | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L394-L446 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | binlm2arpa | def binlm2arpa(input_file, output_file, verbosity=2):
"""
Converts a binary format language model, as generated by idngram2lm, into an an ARPA format language model.
"""
cmd = ['binlm2arpa', '-binary', input_file,
'-arpa'. output_file]
if verbosity:
cmd.extend(['-verbosity', verbosity])
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdout=output_f, stderr=err_f)
output = output_f.read()
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode))
if sys.version_info >= (3,) and type(output) is bytes:
output = output.decode('utf-8')
return output.strip() | python | def binlm2arpa(input_file, output_file, verbosity=2):
"""
Converts a binary format language model, as generated by idngram2lm, into an an ARPA format language model.
"""
cmd = ['binlm2arpa', '-binary', input_file,
'-arpa'. output_file]
if verbosity:
cmd.extend(['-verbosity', verbosity])
# Ensure that every parameter is of type 'str'
cmd = [str(x) for x in cmd]
with tempfile.SpooledTemporaryFile() as output_f:
with output_to_debuglogger() as err_f:
exitcode = subprocess.call(cmd, stdout=output_f, stderr=err_f)
output = output_f.read()
logger = logging.getLogger(__name__)
logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode))
if exitcode != 0:
raise ConversionError("'%s' returned with non-zero exit status '%s'" % (cmd[0], exitcode))
if sys.version_info >= (3,) and type(output) is bytes:
output = output.decode('utf-8')
return output.strip() | [
"def",
"binlm2arpa",
"(",
"input_file",
",",
"output_file",
",",
"verbosity",
"=",
"2",
")",
":",
"cmd",
"=",
"[",
"'binlm2arpa'",
",",
"'-binary'",
",",
"input_file",
",",
"'-arpa'",
".",
"output_file",
"]",
"if",
"verbosity",
":",
"cmd",
".",
"extend",
... | Converts a binary format language model, as generated by idngram2lm, into an an ARPA format language model. | [
"Converts",
"a",
"binary",
"format",
"language",
"model",
"as",
"generated",
"by",
"idngram2lm",
"into",
"an",
"an",
"ARPA",
"format",
"language",
"model",
"."
] | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L448-L475 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | text2vocab | def text2vocab(text, output_file, text2wfreq_kwargs={}, wfreq2vocab_kwargs={}):
"""
Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text.
"""
with tempfile.NamedTemporaryFile(suffix='.wfreq', delete=False) as f:
wfreq_file = f.name
try:
text2wfreq(text, wfreq_file, **text2wfreq_kwargs)
wfreq2vocab(wfreq_file, output_file, **wfreq2vocab_kwargs)
except ConversionError:
raise
finally:
os.remove(wfreq_file) | python | def text2vocab(text, output_file, text2wfreq_kwargs={}, wfreq2vocab_kwargs={}):
"""
Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text.
"""
with tempfile.NamedTemporaryFile(suffix='.wfreq', delete=False) as f:
wfreq_file = f.name
try:
text2wfreq(text, wfreq_file, **text2wfreq_kwargs)
wfreq2vocab(wfreq_file, output_file, **wfreq2vocab_kwargs)
except ConversionError:
raise
finally:
os.remove(wfreq_file) | [
"def",
"text2vocab",
"(",
"text",
",",
"output_file",
",",
"text2wfreq_kwargs",
"=",
"{",
"}",
",",
"wfreq2vocab_kwargs",
"=",
"{",
"}",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.wfreq'",
",",
"delete",
"=",
"False",
"... | Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text. | [
"Convienience",
"function",
"that",
"uses",
"text2wfreq",
"and",
"wfreq2vocab",
"to",
"create",
"a",
"vocabulary",
"file",
"from",
"text",
"."
] | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L477-L490 |
Holzhaus/python-cmuclmtk | cmuclmtk/__init__.py | text2lm | def text2lm(text, output_file, vocab_file=None, text2idngram_kwargs={}, idngram2lm_kwargs={}):
"""
Convienience function to directly convert text (and vocabulary) into a language model.
"""
if vocab_file:
used_vocab_file = vocab_file
else:
# Create temporary vocab file
with tempfile.NamedTemporaryFile(suffix='.vocab', delete=False) as f:
used_vocab_file = f.name
text2vocab(text, used_vocab_file)
# Create temporary idngram file
with tempfile.NamedTemporaryFile(suffix='.idngram', delete=False) as f:
idngram_file = f.name
try:
output1 = text2idngram(text, vocab_file=used_vocab_file, output_file=idngram_file, **text2idngram_kwargs)
output2 = idngram2lm(idngram_file, vocab_file=used_vocab_file, output_file=output_file, **idngram2lm_kwargs)
except ConversionError:
output = (None, None)
raise
else:
output = (output1, output2)
finally:
# Remove temporary files
if not vocab_file:
os.remove(used_vocab_file)
os.remove(idngram_file)
return output | python | def text2lm(text, output_file, vocab_file=None, text2idngram_kwargs={}, idngram2lm_kwargs={}):
"""
Convienience function to directly convert text (and vocabulary) into a language model.
"""
if vocab_file:
used_vocab_file = vocab_file
else:
# Create temporary vocab file
with tempfile.NamedTemporaryFile(suffix='.vocab', delete=False) as f:
used_vocab_file = f.name
text2vocab(text, used_vocab_file)
# Create temporary idngram file
with tempfile.NamedTemporaryFile(suffix='.idngram', delete=False) as f:
idngram_file = f.name
try:
output1 = text2idngram(text, vocab_file=used_vocab_file, output_file=idngram_file, **text2idngram_kwargs)
output2 = idngram2lm(idngram_file, vocab_file=used_vocab_file, output_file=output_file, **idngram2lm_kwargs)
except ConversionError:
output = (None, None)
raise
else:
output = (output1, output2)
finally:
# Remove temporary files
if not vocab_file:
os.remove(used_vocab_file)
os.remove(idngram_file)
return output | [
"def",
"text2lm",
"(",
"text",
",",
"output_file",
",",
"vocab_file",
"=",
"None",
",",
"text2idngram_kwargs",
"=",
"{",
"}",
",",
"idngram2lm_kwargs",
"=",
"{",
"}",
")",
":",
"if",
"vocab_file",
":",
"used_vocab_file",
"=",
"vocab_file",
"else",
":",
"# ... | Convienience function to directly convert text (and vocabulary) into a language model. | [
"Convienience",
"function",
"to",
"directly",
"convert",
"text",
"(",
"and",
"vocabulary",
")",
"into",
"a",
"language",
"model",
"."
] | train | https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L492-L521 |
gmr/tredis | tredis/hyperloglog.py | HyperLogLogMixin.pfadd | def pfadd(self, key, *elements):
"""Adds all the element arguments to the HyperLogLog data structure
stored at the variable name specified as first argument.
As a side effect of this command the HyperLogLog internals may be
updated to reflect a different estimation of the number of unique items
added so far (the cardinality of the set).
If the approximated cardinality estimated by the HyperLogLog changed
after executing the command, :meth:`~tredis.RedisClient.pfadd` returns
``1``, otherwise ``0`` is returned. The command automatically creates
an empty HyperLogLog structure (that is, a Redis String of a specified
length and with a given encoding) if the specified key does not exist.
To call the command without elements but just the variable name is
valid, this will result into no operation performed if the variable
already exists, or just the creation of the data structure if the key
does not exist (in the latter case ``1`` is returned).
For an introduction to HyperLogLog data structure check
:meth:`~tredis.RedisClient.pfcount`.
.. versionadded:: 0.2.0
.. note:: **Time complexity**: ``O(1)`` to add every element.
:param key: The key to add the elements to
:type key: :class:`str`, :class:`bytes`
:param elements: One or more elements to add
:type elements: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
"""
return self._execute([b'PFADD', key] + list(elements), 1) | python | def pfadd(self, key, *elements):
"""Adds all the element arguments to the HyperLogLog data structure
stored at the variable name specified as first argument.
As a side effect of this command the HyperLogLog internals may be
updated to reflect a different estimation of the number of unique items
added so far (the cardinality of the set).
If the approximated cardinality estimated by the HyperLogLog changed
after executing the command, :meth:`~tredis.RedisClient.pfadd` returns
``1``, otherwise ``0`` is returned. The command automatically creates
an empty HyperLogLog structure (that is, a Redis String of a specified
length and with a given encoding) if the specified key does not exist.
To call the command without elements but just the variable name is
valid, this will result into no operation performed if the variable
already exists, or just the creation of the data structure if the key
does not exist (in the latter case ``1`` is returned).
For an introduction to HyperLogLog data structure check
:meth:`~tredis.RedisClient.pfcount`.
.. versionadded:: 0.2.0
.. note:: **Time complexity**: ``O(1)`` to add every element.
:param key: The key to add the elements to
:type key: :class:`str`, :class:`bytes`
:param elements: One or more elements to add
:type elements: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
"""
return self._execute([b'PFADD', key] + list(elements), 1) | [
"def",
"pfadd",
"(",
"self",
",",
"key",
",",
"*",
"elements",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'PFADD'",
",",
"key",
"]",
"+",
"list",
"(",
"elements",
")",
",",
"1",
")"
] | Adds all the element arguments to the HyperLogLog data structure
stored at the variable name specified as first argument.
As a side effect of this command the HyperLogLog internals may be
updated to reflect a different estimation of the number of unique items
added so far (the cardinality of the set).
If the approximated cardinality estimated by the HyperLogLog changed
after executing the command, :meth:`~tredis.RedisClient.pfadd` returns
``1``, otherwise ``0`` is returned. The command automatically creates
an empty HyperLogLog structure (that is, a Redis String of a specified
length and with a given encoding) if the specified key does not exist.
To call the command without elements but just the variable name is
valid, this will result into no operation performed if the variable
already exists, or just the creation of the data structure if the key
does not exist (in the latter case ``1`` is returned).
For an introduction to HyperLogLog data structure check
:meth:`~tredis.RedisClient.pfcount`.
.. versionadded:: 0.2.0
.. note:: **Time complexity**: ``O(1)`` to add every element.
:param key: The key to add the elements to
:type key: :class:`str`, :class:`bytes`
:param elements: One or more elements to add
:type elements: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError` | [
"Adds",
"all",
"the",
"element",
"arguments",
"to",
"the",
"HyperLogLog",
"data",
"structure",
"stored",
"at",
"the",
"variable",
"name",
"specified",
"as",
"first",
"argument",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/hyperloglog.py#L7-L41 |
gmr/tredis | tredis/hyperloglog.py | HyperLogLogMixin.pfmerge | def pfmerge(self, dest_key, *keys):
"""Merge multiple HyperLogLog values into an unique value that will
approximate the cardinality of the union of the observed Sets of the
source HyperLogLog structures.
The computed merged HyperLogLog is set to the destination variable,
which is created if does not exist (defaulting to an empty
HyperLogLog).
.. versionadded:: 0.2.0
.. note::
**Time complexity**: ``O(N)`` to merge ``N`` HyperLogLogs, but
with high constant times.
:param dest_key: The destination key
:type dest_key: :class:`str`, :class:`bytes`
:param keys: One or more keys
:type keys: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
"""
return self._execute([b'PFMERGE', dest_key] + list(keys), b'OK') | python | def pfmerge(self, dest_key, *keys):
"""Merge multiple HyperLogLog values into an unique value that will
approximate the cardinality of the union of the observed Sets of the
source HyperLogLog structures.
The computed merged HyperLogLog is set to the destination variable,
which is created if does not exist (defaulting to an empty
HyperLogLog).
.. versionadded:: 0.2.0
.. note::
**Time complexity**: ``O(N)`` to merge ``N`` HyperLogLogs, but
with high constant times.
:param dest_key: The destination key
:type dest_key: :class:`str`, :class:`bytes`
:param keys: One or more keys
:type keys: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
"""
return self._execute([b'PFMERGE', dest_key] + list(keys), b'OK') | [
"def",
"pfmerge",
"(",
"self",
",",
"dest_key",
",",
"*",
"keys",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'PFMERGE'",
",",
"dest_key",
"]",
"+",
"list",
"(",
"keys",
")",
",",
"b'OK'",
")"
] | Merge multiple HyperLogLog values into an unique value that will
approximate the cardinality of the union of the observed Sets of the
source HyperLogLog structures.
The computed merged HyperLogLog is set to the destination variable,
which is created if does not exist (defaulting to an empty
HyperLogLog).
.. versionadded:: 0.2.0
.. note::
**Time complexity**: ``O(N)`` to merge ``N`` HyperLogLogs, but
with high constant times.
:param dest_key: The destination key
:type dest_key: :class:`str`, :class:`bytes`
:param keys: One or more keys
:type keys: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError` | [
"Merge",
"multiple",
"HyperLogLog",
"values",
"into",
"an",
"unique",
"value",
"that",
"will",
"approximate",
"the",
"cardinality",
"of",
"the",
"union",
"of",
"the",
"observed",
"Sets",
"of",
"the",
"source",
"HyperLogLog",
"structures",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/hyperloglog.py#L87-L111 |
mthornhill/django-postal | src/postal/resource.py | Emitter.construct | def construct(self):
"""
Recursively serialize a lot of types, and
in cases where it doesn't recognize the type,
it will fall back to Django's `smart_unicode`.
Returns `dict`.
"""
def _any(thing, fields=None):
"""
Dispatch, all types are routed through here.
"""
ret = None
if isinstance(thing, QuerySet):
ret = _qs(thing, fields)
elif isinstance(thing, (tuple, list, set)):
ret = _list(thing, fields)
elif isinstance(thing, dict):
ret = _dict(thing, fields)
elif isinstance(thing, decimal.Decimal):
ret = str(thing)
elif isinstance(thing, Model):
ret = _model(thing, fields)
elif isinstance(thing, HttpResponse):
raise HttpStatusCode(thing)
elif inspect.isfunction(thing):
if not inspect.getargspec(thing)[0]:
ret = _any(thing())
elif hasattr(thing, '__emittable__'):
f = thing.__emittable__
if inspect.ismethod(f) and len(inspect.getargspec(f)[0]) == 1:
ret = _any(f())
elif repr(thing).startswith("<django.db.models.fields.related.RelatedManager"):
ret = _any(thing.all())
else:
ret = smart_unicode(thing, strings_only=True)
return ret
def _fk(data, field):
"""
Foreign keys.
"""
return _any(getattr(data, field.name))
def _related(data, fields=None):
"""
Foreign keys.
"""
return [ _model(m, fields) for m in data.iterator() ]
def _m2m(data, field, fields=None):
"""
Many to many (re-route to `_model`.)
"""
return [ _model(m, fields) for m in getattr(data, field.name).iterator() ]
def _model(data, fields=None):
"""
Models. Will respect the `fields` and/or
`exclude` on the handler (see `typemapper`.)
"""
ret = { }
handler = self.in_typemapper(type(data), self.anonymous)
get_absolute_uri = False
if handler or fields:
v = lambda f: getattr(data, f.attname)
if handler:
fields = getattr(handler, 'fields')
if not fields or hasattr(handler, 'fields'):
"""
Fields was not specified, try to find teh correct
version in the typemapper we were sent.
"""
mapped = self.in_typemapper(type(data), self.anonymous)
get_fields = set(mapped.fields)
exclude_fields = set(mapped.exclude).difference(get_fields)
if 'absolute_uri' in get_fields:
get_absolute_uri = True
if not get_fields:
get_fields = set([ f.attname.replace("_id", "", 1)
for f in data._meta.fields + data._meta.virtual_fields])
if hasattr(mapped, 'extra_fields'):
get_fields.update(mapped.extra_fields)
# sets can be negated.
for exclude in exclude_fields:
if isinstance(exclude, basestring):
get_fields.discard(exclude)
elif isinstance(exclude, re._pattern_type):
for field in get_fields.copy():
if exclude.match(field):
get_fields.discard(field)
else:
get_fields = set(fields)
met_fields = self.method_fields(handler, get_fields)
for f in data._meta.local_fields + data._meta.virtual_fields:
if f.serialize and not any([ p in met_fields for p in [ f.attname, f.name ]]):
if not f.rel:
if f.attname in get_fields:
ret[f.attname] = _any(v(f))
get_fields.remove(f.attname)
else:
if f.attname[:-3] in get_fields:
ret[f.name] = _fk(data, f)
get_fields.remove(f.name)
for mf in data._meta.many_to_many:
if mf.serialize and mf.attname not in met_fields:
if mf.attname in get_fields:
ret[mf.name] = _m2m(data, mf)
get_fields.remove(mf.name)
# try to get the remainder of fields
for maybe_field in get_fields:
if isinstance(maybe_field, (list, tuple)):
model, fields = maybe_field
inst = getattr(data, model, None)
if inst:
if hasattr(inst, 'all'):
ret[model] = _related(inst, fields)
elif callable(inst):
if len(inspect.getargspec(inst)[0]) == 1:
ret[model] = _any(inst(), fields)
else:
ret[model] = _model(inst, fields)
elif maybe_field in met_fields:
# Overriding normal field which has a "resource method"
# so you can alter the contents of certain fields without
# using different names.
ret[maybe_field] = _any(met_fields[maybe_field](data))
else:
maybe = getattr(data, maybe_field, None)
if maybe is not None:
if callable(maybe):
if len(inspect.getargspec(maybe)[0]) <= 1:
ret[maybe_field] = _any(maybe())
else:
ret[maybe_field] = _any(maybe)
else:
handler_f = getattr(handler or self.handler, maybe_field, None)
if handler_f:
ret[maybe_field] = _any(handler_f(data))
else:
for f in data._meta.fields:
ret[f.attname] = _any(getattr(data, f.attname))
fields = dir(data.__class__) + ret.keys()
add_ons = [k for k in dir(data) if k not in fields]
for k in add_ons:
ret[k] = _any(getattr(data, k))
# resouce uri
if self.in_typemapper(type(data), self.anonymous):
handler = self.in_typemapper(type(data), self.anonymous)
if hasattr(handler, 'resource_uri'):
url_id, fields = handler.resource_uri(data)
try:
ret['resource_uri'] = permalink(lambda: (url_id, fields))()
except NoReverseMatch, e:
pass
if hasattr(data, 'get_api_url') and 'resource_uri' not in ret:
try:
ret['resource_uri'] = data.get_api_url()
except:
pass
# absolute uri
if hasattr(data, 'get_absolute_url') and get_absolute_uri:
try:
ret['absolute_uri'] = data.get_absolute_url()
except:
pass
return ret
def _qs(data, fields=None):
"""
Querysets.
"""
return [_any(v, fields) for v in data ]
def _list(data, fields=None):
"""
Lists.
"""
return [_any(v, fields) for v in data ]
def _dict(data, fields=None):
"""
Dictionaries.
"""
return dict([(k, _any(v, fields)) for k, v in data.iteritems()])
# Kickstart the seralizin'.
return _any(self.data, self.fields) | python | def construct(self):
"""
Recursively serialize a lot of types, and
in cases where it doesn't recognize the type,
it will fall back to Django's `smart_unicode`.
Returns `dict`.
"""
def _any(thing, fields=None):
"""
Dispatch, all types are routed through here.
"""
ret = None
if isinstance(thing, QuerySet):
ret = _qs(thing, fields)
elif isinstance(thing, (tuple, list, set)):
ret = _list(thing, fields)
elif isinstance(thing, dict):
ret = _dict(thing, fields)
elif isinstance(thing, decimal.Decimal):
ret = str(thing)
elif isinstance(thing, Model):
ret = _model(thing, fields)
elif isinstance(thing, HttpResponse):
raise HttpStatusCode(thing)
elif inspect.isfunction(thing):
if not inspect.getargspec(thing)[0]:
ret = _any(thing())
elif hasattr(thing, '__emittable__'):
f = thing.__emittable__
if inspect.ismethod(f) and len(inspect.getargspec(f)[0]) == 1:
ret = _any(f())
elif repr(thing).startswith("<django.db.models.fields.related.RelatedManager"):
ret = _any(thing.all())
else:
ret = smart_unicode(thing, strings_only=True)
return ret
def _fk(data, field):
"""
Foreign keys.
"""
return _any(getattr(data, field.name))
def _related(data, fields=None):
"""
Foreign keys.
"""
return [ _model(m, fields) for m in data.iterator() ]
def _m2m(data, field, fields=None):
"""
Many to many (re-route to `_model`.)
"""
return [ _model(m, fields) for m in getattr(data, field.name).iterator() ]
def _model(data, fields=None):
"""
Models. Will respect the `fields` and/or
`exclude` on the handler (see `typemapper`.)
"""
ret = { }
handler = self.in_typemapper(type(data), self.anonymous)
get_absolute_uri = False
if handler or fields:
v = lambda f: getattr(data, f.attname)
if handler:
fields = getattr(handler, 'fields')
if not fields or hasattr(handler, 'fields'):
"""
Fields was not specified, try to find teh correct
version in the typemapper we were sent.
"""
mapped = self.in_typemapper(type(data), self.anonymous)
get_fields = set(mapped.fields)
exclude_fields = set(mapped.exclude).difference(get_fields)
if 'absolute_uri' in get_fields:
get_absolute_uri = True
if not get_fields:
get_fields = set([ f.attname.replace("_id", "", 1)
for f in data._meta.fields + data._meta.virtual_fields])
if hasattr(mapped, 'extra_fields'):
get_fields.update(mapped.extra_fields)
# sets can be negated.
for exclude in exclude_fields:
if isinstance(exclude, basestring):
get_fields.discard(exclude)
elif isinstance(exclude, re._pattern_type):
for field in get_fields.copy():
if exclude.match(field):
get_fields.discard(field)
else:
get_fields = set(fields)
met_fields = self.method_fields(handler, get_fields)
for f in data._meta.local_fields + data._meta.virtual_fields:
if f.serialize and not any([ p in met_fields for p in [ f.attname, f.name ]]):
if not f.rel:
if f.attname in get_fields:
ret[f.attname] = _any(v(f))
get_fields.remove(f.attname)
else:
if f.attname[:-3] in get_fields:
ret[f.name] = _fk(data, f)
get_fields.remove(f.name)
for mf in data._meta.many_to_many:
if mf.serialize and mf.attname not in met_fields:
if mf.attname in get_fields:
ret[mf.name] = _m2m(data, mf)
get_fields.remove(mf.name)
# try to get the remainder of fields
for maybe_field in get_fields:
if isinstance(maybe_field, (list, tuple)):
model, fields = maybe_field
inst = getattr(data, model, None)
if inst:
if hasattr(inst, 'all'):
ret[model] = _related(inst, fields)
elif callable(inst):
if len(inspect.getargspec(inst)[0]) == 1:
ret[model] = _any(inst(), fields)
else:
ret[model] = _model(inst, fields)
elif maybe_field in met_fields:
# Overriding normal field which has a "resource method"
# so you can alter the contents of certain fields without
# using different names.
ret[maybe_field] = _any(met_fields[maybe_field](data))
else:
maybe = getattr(data, maybe_field, None)
if maybe is not None:
if callable(maybe):
if len(inspect.getargspec(maybe)[0]) <= 1:
ret[maybe_field] = _any(maybe())
else:
ret[maybe_field] = _any(maybe)
else:
handler_f = getattr(handler or self.handler, maybe_field, None)
if handler_f:
ret[maybe_field] = _any(handler_f(data))
else:
for f in data._meta.fields:
ret[f.attname] = _any(getattr(data, f.attname))
fields = dir(data.__class__) + ret.keys()
add_ons = [k for k in dir(data) if k not in fields]
for k in add_ons:
ret[k] = _any(getattr(data, k))
# resouce uri
if self.in_typemapper(type(data), self.anonymous):
handler = self.in_typemapper(type(data), self.anonymous)
if hasattr(handler, 'resource_uri'):
url_id, fields = handler.resource_uri(data)
try:
ret['resource_uri'] = permalink(lambda: (url_id, fields))()
except NoReverseMatch, e:
pass
if hasattr(data, 'get_api_url') and 'resource_uri' not in ret:
try:
ret['resource_uri'] = data.get_api_url()
except:
pass
# absolute uri
if hasattr(data, 'get_absolute_url') and get_absolute_uri:
try:
ret['absolute_uri'] = data.get_absolute_url()
except:
pass
return ret
def _qs(data, fields=None):
"""
Querysets.
"""
return [_any(v, fields) for v in data ]
def _list(data, fields=None):
"""
Lists.
"""
return [_any(v, fields) for v in data ]
def _dict(data, fields=None):
"""
Dictionaries.
"""
return dict([(k, _any(v, fields)) for k, v in data.iteritems()])
# Kickstart the seralizin'.
return _any(self.data, self.fields) | [
"def",
"construct",
"(",
"self",
")",
":",
"def",
"_any",
"(",
"thing",
",",
"fields",
"=",
"None",
")",
":",
"\"\"\"\n Dispatch, all types are routed through here.\n \"\"\"",
"ret",
"=",
"None",
"if",
"isinstance",
"(",
"thing",
",",
"QuerySet... | Recursively serialize a lot of types, and
in cases where it doesn't recognize the type,
it will fall back to Django's `smart_unicode`.
Returns `dict`. | [
"Recursively",
"serialize",
"a",
"lot",
"of",
"types",
"and",
"in",
"cases",
"where",
"it",
"doesn",
"t",
"recognize",
"the",
"type",
"it",
"will",
"fall",
"back",
"to",
"Django",
"s",
"smart_unicode",
"."
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L65-L279 |
mthornhill/django-postal | src/postal/resource.py | Emitter.get | def get(cls, format):
"""
Gets an emitter, returns the class and a content-type.
"""
if cls.EMITTERS.has_key(format):
return cls.EMITTERS.get(format)
raise ValueError("No emitters found for type %s" % format) | python | def get(cls, format):
"""
Gets an emitter, returns the class and a content-type.
"""
if cls.EMITTERS.has_key(format):
return cls.EMITTERS.get(format)
raise ValueError("No emitters found for type %s" % format) | [
"def",
"get",
"(",
"cls",
",",
"format",
")",
":",
"if",
"cls",
".",
"EMITTERS",
".",
"has_key",
"(",
"format",
")",
":",
"return",
"cls",
".",
"EMITTERS",
".",
"get",
"(",
"format",
")",
"raise",
"ValueError",
"(",
"\"No emitters found for type %s\"",
"... | Gets an emitter, returns the class and a content-type. | [
"Gets",
"an",
"emitter",
"returns",
"the",
"class",
"and",
"a",
"content",
"-",
"type",
"."
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L303-L310 |
mthornhill/django-postal | src/postal/resource.py | Emitter.register | def register(cls, name, klass, content_type='text/plain'):
"""
Register an emitter.
Parameters::
- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)
- `klass`: The emitter class.
- `content_type`: The content type to serve response as.
"""
cls.EMITTERS[name] = (klass, content_type) | python | def register(cls, name, klass, content_type='text/plain'):
"""
Register an emitter.
Parameters::
- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)
- `klass`: The emitter class.
- `content_type`: The content type to serve response as.
"""
cls.EMITTERS[name] = (klass, content_type) | [
"def",
"register",
"(",
"cls",
",",
"name",
",",
"klass",
",",
"content_type",
"=",
"'text/plain'",
")",
":",
"cls",
".",
"EMITTERS",
"[",
"name",
"]",
"=",
"(",
"klass",
",",
"content_type",
")"
] | Register an emitter.
Parameters::
- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)
- `klass`: The emitter class.
- `content_type`: The content type to serve response as. | [
"Register",
"an",
"emitter",
"."
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L313-L322 |
mthornhill/django-postal | src/postal/resource.py | Resource.determine_emitter | def determine_emitter(self, request, *args, **kwargs):
"""
Function for determening which emitter to use
for output. It lives here so you can easily subclass
`Resource` in order to change how emission is detected.
You could also check for the `Accept` HTTP header here,
since that pretty much makes sense. Refer to `Mimer` for
that as well.
"""
em = kwargs.pop('emitter_format', None)
if not em:
em = request.GET.get('format', 'json')
return em | python | def determine_emitter(self, request, *args, **kwargs):
"""
Function for determening which emitter to use
for output. It lives here so you can easily subclass
`Resource` in order to change how emission is detected.
You could also check for the `Accept` HTTP header here,
since that pretty much makes sense. Refer to `Mimer` for
that as well.
"""
em = kwargs.pop('emitter_format', None)
if not em:
em = request.GET.get('format', 'json')
return em | [
"def",
"determine_emitter",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"em",
"=",
"kwargs",
".",
"pop",
"(",
"'emitter_format'",
",",
"None",
")",
"if",
"not",
"em",
":",
"em",
"=",
"request",
".",
"GET",
".",... | Function for determening which emitter to use
for output. It lives here so you can easily subclass
`Resource` in order to change how emission is detected.
You could also check for the `Accept` HTTP header here,
since that pretty much makes sense. Refer to `Mimer` for
that as well. | [
"Function",
"for",
"determening",
"which",
"emitter",
"to",
"use",
"for",
"output",
".",
"It",
"lives",
"here",
"so",
"you",
"can",
"easily",
"subclass",
"Resource",
"in",
"order",
"to",
"change",
"how",
"emission",
"is",
"detected",
"."
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L429-L444 |
mthornhill/django-postal | src/postal/resource.py | Resource.form_validation_response | def form_validation_response(self, e):
"""
Method to return form validation error information.
You will probably want to override this in your own
`Resource` subclass.
"""
resp = rc.BAD_REQUEST
resp.write(' '+str(e.form.errors))
return resp | python | def form_validation_response(self, e):
"""
Method to return form validation error information.
You will probably want to override this in your own
`Resource` subclass.
"""
resp = rc.BAD_REQUEST
resp.write(' '+str(e.form.errors))
return resp | [
"def",
"form_validation_response",
"(",
"self",
",",
"e",
")",
":",
"resp",
"=",
"rc",
".",
"BAD_REQUEST",
"resp",
".",
"write",
"(",
"' '",
"+",
"str",
"(",
"e",
".",
"form",
".",
"errors",
")",
")",
"return",
"resp"
] | Method to return form validation error information.
You will probably want to override this in your own
`Resource` subclass. | [
"Method",
"to",
"return",
"form",
"validation",
"error",
"information",
".",
"You",
"will",
"probably",
"want",
"to",
"override",
"this",
"in",
"your",
"own",
"Resource",
"subclass",
"."
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L446-L454 |
mthornhill/django-postal | src/postal/resource.py | Resource.anonymous | def anonymous(self):
"""
Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.)
"""
if hasattr(self.handler, 'anonymous'):
anon = self.handler.anonymous
if callable(anon):
return anon
for klass in typemapper.keys():
if anon == klass.__name__:
return klass
return None | python | def anonymous(self):
"""
Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.)
"""
if hasattr(self.handler, 'anonymous'):
anon = self.handler.anonymous
if callable(anon):
return anon
for klass in typemapper.keys():
if anon == klass.__name__:
return klass
return None | [
"def",
"anonymous",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"handler",
",",
"'anonymous'",
")",
":",
"anon",
"=",
"self",
".",
"handler",
".",
"anonymous",
"if",
"callable",
"(",
"anon",
")",
":",
"return",
"anon",
"for",
"klass",
"... | Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.) | [
"Gets",
"the",
"anonymous",
"handler",
".",
"Also",
"tries",
"to",
"grab",
"a",
"class",
"if",
"the",
"anonymous",
"value",
"is",
"a",
"string",
"so",
"that",
"we",
"can",
"define",
"anonymous",
"handlers",
"that",
"aren",
"t",
"defined",
"yet",
"(",
"li... | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L457-L474 |
mthornhill/django-postal | src/postal/resource.py | Resource.cleanup_request | def cleanup_request(request):
"""
Removes `oauth_` keys from various dicts on the
request object, and returns the sanitized version.
"""
for method_type in ('GET', 'PUT', 'POST', 'DELETE'):
block = getattr(request, method_type, { })
if True in [ k.startswith("oauth_") for k in block.keys() ]:
sanitized = block.copy()
for k in sanitized.keys():
if k.startswith("oauth_"):
sanitized.pop(k)
setattr(request, method_type, sanitized)
return request | python | def cleanup_request(request):
"""
Removes `oauth_` keys from various dicts on the
request object, and returns the sanitized version.
"""
for method_type in ('GET', 'PUT', 'POST', 'DELETE'):
block = getattr(request, method_type, { })
if True in [ k.startswith("oauth_") for k in block.keys() ]:
sanitized = block.copy()
for k in sanitized.keys():
if k.startswith("oauth_"):
sanitized.pop(k)
setattr(request, method_type, sanitized)
return request | [
"def",
"cleanup_request",
"(",
"request",
")",
":",
"for",
"method_type",
"in",
"(",
"'GET'",
",",
"'PUT'",
",",
"'POST'",
",",
"'DELETE'",
")",
":",
"block",
"=",
"getattr",
"(",
"request",
",",
"method_type",
",",
"{",
"}",
")",
"if",
"True",
"in",
... | Removes `oauth_` keys from various dicts on the
request object, and returns the sanitized version. | [
"Removes",
"oauth_",
"keys",
"from",
"various",
"dicts",
"on",
"the",
"request",
"object",
"and",
"returns",
"the",
"sanitized",
"version",
"."
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L593-L610 |
mthornhill/django-postal | src/postal/resource.py | Resource.error_handler | def error_handler(self, e, request, meth, em_format):
"""
Override this method to add handling of errors customized for your
needs
"""
if isinstance(e, FormValidationError):
return self.form_validation_response(e)
elif isinstance(e, TypeError):
result = rc.BAD_REQUEST
hm = HandlerMethod(meth)
sig = hm.signature
msg = 'Method signature does not match.\n\n'
if sig:
msg += 'Signature should be: %s' % sig
else:
msg += 'Resource does not expect any parameters.'
if self.display_errors:
msg += '\n\nException was: %s' % str(e)
result.content = format_error(msg)
return result
elif isinstance(e, Http404):
return rc.NOT_FOUND
elif isinstance(e, HttpStatusCode):
return e.response
else:
"""
On errors (like code errors), we'd like to be able to
give crash reports to both admins and also the calling
user. There's two setting parameters for this:
Parameters::
- `PISTON_EMAIL_ERRORS`: Will send a Django formatted
error email to people in `settings.ADMINS`.
- `PISTON_DISPLAY_ERRORS`: Will return a simple traceback
to the caller, so he can tell you what error they got.
If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will
receive a basic "500 Internal Server Error" message.
"""
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
if self.email_errors:
self.email_exception(rep)
if self.display_errors:
return HttpResponseServerError(
format_error('\n'.join(rep.format_exception())))
else:
raise | python | def error_handler(self, e, request, meth, em_format):
"""
Override this method to add handling of errors customized for your
needs
"""
if isinstance(e, FormValidationError):
return self.form_validation_response(e)
elif isinstance(e, TypeError):
result = rc.BAD_REQUEST
hm = HandlerMethod(meth)
sig = hm.signature
msg = 'Method signature does not match.\n\n'
if sig:
msg += 'Signature should be: %s' % sig
else:
msg += 'Resource does not expect any parameters.'
if self.display_errors:
msg += '\n\nException was: %s' % str(e)
result.content = format_error(msg)
return result
elif isinstance(e, Http404):
return rc.NOT_FOUND
elif isinstance(e, HttpStatusCode):
return e.response
else:
"""
On errors (like code errors), we'd like to be able to
give crash reports to both admins and also the calling
user. There's two setting parameters for this:
Parameters::
- `PISTON_EMAIL_ERRORS`: Will send a Django formatted
error email to people in `settings.ADMINS`.
- `PISTON_DISPLAY_ERRORS`: Will return a simple traceback
to the caller, so he can tell you what error they got.
If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will
receive a basic "500 Internal Server Error" message.
"""
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
if self.email_errors:
self.email_exception(rep)
if self.display_errors:
return HttpResponseServerError(
format_error('\n'.join(rep.format_exception())))
else:
raise | [
"def",
"error_handler",
"(",
"self",
",",
"e",
",",
"request",
",",
"meth",
",",
"em_format",
")",
":",
"if",
"isinstance",
"(",
"e",
",",
"FormValidationError",
")",
":",
"return",
"self",
".",
"form_validation_response",
"(",
"e",
")",
"elif",
"isinstanc... | Override this method to add handling of errors customized for your
needs | [
"Override",
"this",
"method",
"to",
"add",
"handling",
"of",
"errors",
"customized",
"for",
"your",
"needs"
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/resource.py#L626-L680 |
marteinn/wpparser | wpparser/parser.py | parse | def parse(path):
"""
Parses xml and returns a formatted dict.
Example:
wpparser.parse("./blog.wordpress.2014-09-26.xml")
Will return:
{
"blog": {
"tagline": "Tagline",
"site_url": "http://marteinn.se/blog",
"blog_url": "http://marteinn.se/blog",
"language": "en-US",
"title": "Marteinn / Blog"
},
"authors: [{
"login": "admin",
"last_name": None,
"display_name": "admin",
"email": "martin@marteinn.se",
"first_name": None}
],
"categories": [{
"parent": None,
"term_id": "3",
"name": "Action Script",
"nicename": "action-script",
"children": [{
"parent": "action-script",
"term_id": "20",
"name": "Flash related",
"nicename": "flash-related",
"children": []
}]
}],
"tags": [{"term_id": "36", "slug": "bash", "name": "Bash"}],
"posts": [{
"creator": "admin",
"excerpt": None,
"post_date_gmt": "2014-09-22 20:10:40",
"post_date": "2014-09-22 21:10:40",
"post_type": "post",
"menu_order": "0",
"guid": "http://marteinn.se/blog/?p=828",
"title": "Post Title",
"comments": [{
"date_gmt": "2014-09-24 23:08:31",
"parent": "0",
"date": "2014-09-25 00:08:31",
"id": "85929",
"user_id": "0",
"author": u"Author",
"author_email": None,
"author_ip": "111.111.111.111",
"approved": "1",
"content": u"Comment title",
"author_url": "http://example.com",
"type": "pingback"
}],
"content": "Text",
"post_parent": "0",
"post_password": None,
"status": "publish",
"description": None,
"tags": ["tag"],
"ping_status": "open",
"post_id": "828",
"link": "http://www.marteinn.se/blog/slug/",
"pub_date": "Mon, 22 Sep 2014 20:10:40 +0000",
"categories": ["category"],
"is_sticky": "0",
"post_name": "slug"
}]
}
"""
doc = ET.parse(path).getroot()
channel = doc.find("./channel")
blog = _parse_blog(channel)
authors = _parse_authors(channel)
categories = _parse_categories(channel)
tags = _parse_tags(channel)
posts = _parse_posts(channel)
return {
"blog": blog,
"authors": authors,
"categories": categories,
"tags": tags,
"posts": posts,
} | python | def parse(path):
"""
Parses xml and returns a formatted dict.
Example:
wpparser.parse("./blog.wordpress.2014-09-26.xml")
Will return:
{
"blog": {
"tagline": "Tagline",
"site_url": "http://marteinn.se/blog",
"blog_url": "http://marteinn.se/blog",
"language": "en-US",
"title": "Marteinn / Blog"
},
"authors: [{
"login": "admin",
"last_name": None,
"display_name": "admin",
"email": "martin@marteinn.se",
"first_name": None}
],
"categories": [{
"parent": None,
"term_id": "3",
"name": "Action Script",
"nicename": "action-script",
"children": [{
"parent": "action-script",
"term_id": "20",
"name": "Flash related",
"nicename": "flash-related",
"children": []
}]
}],
"tags": [{"term_id": "36", "slug": "bash", "name": "Bash"}],
"posts": [{
"creator": "admin",
"excerpt": None,
"post_date_gmt": "2014-09-22 20:10:40",
"post_date": "2014-09-22 21:10:40",
"post_type": "post",
"menu_order": "0",
"guid": "http://marteinn.se/blog/?p=828",
"title": "Post Title",
"comments": [{
"date_gmt": "2014-09-24 23:08:31",
"parent": "0",
"date": "2014-09-25 00:08:31",
"id": "85929",
"user_id": "0",
"author": u"Author",
"author_email": None,
"author_ip": "111.111.111.111",
"approved": "1",
"content": u"Comment title",
"author_url": "http://example.com",
"type": "pingback"
}],
"content": "Text",
"post_parent": "0",
"post_password": None,
"status": "publish",
"description": None,
"tags": ["tag"],
"ping_status": "open",
"post_id": "828",
"link": "http://www.marteinn.se/blog/slug/",
"pub_date": "Mon, 22 Sep 2014 20:10:40 +0000",
"categories": ["category"],
"is_sticky": "0",
"post_name": "slug"
}]
}
"""
doc = ET.parse(path).getroot()
channel = doc.find("./channel")
blog = _parse_blog(channel)
authors = _parse_authors(channel)
categories = _parse_categories(channel)
tags = _parse_tags(channel)
posts = _parse_posts(channel)
return {
"blog": blog,
"authors": authors,
"categories": categories,
"tags": tags,
"posts": posts,
} | [
"def",
"parse",
"(",
"path",
")",
":",
"doc",
"=",
"ET",
".",
"parse",
"(",
"path",
")",
".",
"getroot",
"(",
")",
"channel",
"=",
"doc",
".",
"find",
"(",
"\"./channel\"",
")",
"blog",
"=",
"_parse_blog",
"(",
"channel",
")",
"authors",
"=",
"_par... | Parses xml and returns a formatted dict.
Example:
wpparser.parse("./blog.wordpress.2014-09-26.xml")
Will return:
{
"blog": {
"tagline": "Tagline",
"site_url": "http://marteinn.se/blog",
"blog_url": "http://marteinn.se/blog",
"language": "en-US",
"title": "Marteinn / Blog"
},
"authors: [{
"login": "admin",
"last_name": None,
"display_name": "admin",
"email": "martin@marteinn.se",
"first_name": None}
],
"categories": [{
"parent": None,
"term_id": "3",
"name": "Action Script",
"nicename": "action-script",
"children": [{
"parent": "action-script",
"term_id": "20",
"name": "Flash related",
"nicename": "flash-related",
"children": []
}]
}],
"tags": [{"term_id": "36", "slug": "bash", "name": "Bash"}],
"posts": [{
"creator": "admin",
"excerpt": None,
"post_date_gmt": "2014-09-22 20:10:40",
"post_date": "2014-09-22 21:10:40",
"post_type": "post",
"menu_order": "0",
"guid": "http://marteinn.se/blog/?p=828",
"title": "Post Title",
"comments": [{
"date_gmt": "2014-09-24 23:08:31",
"parent": "0",
"date": "2014-09-25 00:08:31",
"id": "85929",
"user_id": "0",
"author": u"Author",
"author_email": None,
"author_ip": "111.111.111.111",
"approved": "1",
"content": u"Comment title",
"author_url": "http://example.com",
"type": "pingback"
}],
"content": "Text",
"post_parent": "0",
"post_password": None,
"status": "publish",
"description": None,
"tags": ["tag"],
"ping_status": "open",
"post_id": "828",
"link": "http://www.marteinn.se/blog/slug/",
"pub_date": "Mon, 22 Sep 2014 20:10:40 +0000",
"categories": ["category"],
"is_sticky": "0",
"post_name": "slug"
}]
} | [
"Parses",
"xml",
"and",
"returns",
"a",
"formatted",
"dict",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L29-L124 |
marteinn/wpparser | wpparser/parser.py | _parse_blog | def _parse_blog(element):
"""
Parse and return genral blog data (title, tagline etc).
"""
title = element.find("./title").text
tagline = element.find("./description").text
language = element.find("./language").text
site_url = element.find("./{%s}base_site_url" % WP_NAMESPACE).text
blog_url = element.find("./{%s}base_blog_url" % WP_NAMESPACE).text
return {
"title": title,
"tagline": tagline,
"language": language,
"site_url": site_url,
"blog_url": blog_url,
} | python | def _parse_blog(element):
"""
Parse and return genral blog data (title, tagline etc).
"""
title = element.find("./title").text
tagline = element.find("./description").text
language = element.find("./language").text
site_url = element.find("./{%s}base_site_url" % WP_NAMESPACE).text
blog_url = element.find("./{%s}base_blog_url" % WP_NAMESPACE).text
return {
"title": title,
"tagline": tagline,
"language": language,
"site_url": site_url,
"blog_url": blog_url,
} | [
"def",
"_parse_blog",
"(",
"element",
")",
":",
"title",
"=",
"element",
".",
"find",
"(",
"\"./title\"",
")",
".",
"text",
"tagline",
"=",
"element",
".",
"find",
"(",
"\"./description\"",
")",
".",
"text",
"language",
"=",
"element",
".",
"find",
"(",
... | Parse and return genral blog data (title, tagline etc). | [
"Parse",
"and",
"return",
"genral",
"blog",
"data",
"(",
"title",
"tagline",
"etc",
")",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L127-L144 |
marteinn/wpparser | wpparser/parser.py | _parse_authors | def _parse_authors(element):
"""
Returns a well formatted list of users that can be matched against posts.
"""
authors = []
items = element.findall("./{%s}author" % WP_NAMESPACE)
for item in items:
login = item.find("./{%s}author_login" % WP_NAMESPACE).text
email = item.find("./{%s}author_email" % WP_NAMESPACE).text
first_name = item.find("./{%s}author_first_name" % WP_NAMESPACE).text
last_name = item.find("./{%s}author_last_name" % WP_NAMESPACE).text
display_name = item.find(
"./{%s}author_display_name" % WP_NAMESPACE).text
authors.append({
"login": login,
"email": email,
"display_name": display_name,
"first_name": first_name,
"last_name": last_name
})
return authors | python | def _parse_authors(element):
"""
Returns a well formatted list of users that can be matched against posts.
"""
authors = []
items = element.findall("./{%s}author" % WP_NAMESPACE)
for item in items:
login = item.find("./{%s}author_login" % WP_NAMESPACE).text
email = item.find("./{%s}author_email" % WP_NAMESPACE).text
first_name = item.find("./{%s}author_first_name" % WP_NAMESPACE).text
last_name = item.find("./{%s}author_last_name" % WP_NAMESPACE).text
display_name = item.find(
"./{%s}author_display_name" % WP_NAMESPACE).text
authors.append({
"login": login,
"email": email,
"display_name": display_name,
"first_name": first_name,
"last_name": last_name
})
return authors | [
"def",
"_parse_authors",
"(",
"element",
")",
":",
"authors",
"=",
"[",
"]",
"items",
"=",
"element",
".",
"findall",
"(",
"\"./{%s}author\"",
"%",
"WP_NAMESPACE",
")",
"for",
"item",
"in",
"items",
":",
"login",
"=",
"item",
".",
"find",
"(",
"\"./{%s}a... | Returns a well formatted list of users that can be matched against posts. | [
"Returns",
"a",
"well",
"formatted",
"list",
"of",
"users",
"that",
"can",
"be",
"matched",
"against",
"posts",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L147-L171 |
marteinn/wpparser | wpparser/parser.py | _parse_categories | def _parse_categories(element):
"""
Returns a list with categories with relations.
"""
reference = {}
items = element.findall("./{%s}category" % WP_NAMESPACE)
for item in items:
term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text
nicename = item.find("./{%s}category_nicename" % WP_NAMESPACE).text
name = item.find("./{%s}cat_name" % WP_NAMESPACE).text
parent = item.find("./{%s}category_parent" % WP_NAMESPACE).text
category = {
"term_id": term_id,
"nicename": nicename,
"name": name,
"parent": parent
}
reference[nicename] = category
return _build_category_tree(None, reference=reference) | python | def _parse_categories(element):
"""
Returns a list with categories with relations.
"""
reference = {}
items = element.findall("./{%s}category" % WP_NAMESPACE)
for item in items:
term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text
nicename = item.find("./{%s}category_nicename" % WP_NAMESPACE).text
name = item.find("./{%s}cat_name" % WP_NAMESPACE).text
parent = item.find("./{%s}category_parent" % WP_NAMESPACE).text
category = {
"term_id": term_id,
"nicename": nicename,
"name": name,
"parent": parent
}
reference[nicename] = category
return _build_category_tree(None, reference=reference) | [
"def",
"_parse_categories",
"(",
"element",
")",
":",
"reference",
"=",
"{",
"}",
"items",
"=",
"element",
".",
"findall",
"(",
"\"./{%s}category\"",
"%",
"WP_NAMESPACE",
")",
"for",
"item",
"in",
"items",
":",
"term_id",
"=",
"item",
".",
"find",
"(",
"... | Returns a list with categories with relations. | [
"Returns",
"a",
"list",
"with",
"categories",
"with",
"relations",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L174-L196 |
marteinn/wpparser | wpparser/parser.py | _build_category_tree | def _build_category_tree(slug, reference=None, items=None):
"""
Builds a recursive tree with category relations as children.
"""
if items is None:
items = []
for key in reference:
category = reference[key]
if category["parent"] == slug:
children = _build_category_tree(category["nicename"],
reference=reference)
category["children"] = children
items.append(category)
return items | python | def _build_category_tree(slug, reference=None, items=None):
"""
Builds a recursive tree with category relations as children.
"""
if items is None:
items = []
for key in reference:
category = reference[key]
if category["parent"] == slug:
children = _build_category_tree(category["nicename"],
reference=reference)
category["children"] = children
items.append(category)
return items | [
"def",
"_build_category_tree",
"(",
"slug",
",",
"reference",
"=",
"None",
",",
"items",
"=",
"None",
")",
":",
"if",
"items",
"is",
"None",
":",
"items",
"=",
"[",
"]",
"for",
"key",
"in",
"reference",
":",
"category",
"=",
"reference",
"[",
"key",
... | Builds a recursive tree with category relations as children. | [
"Builds",
"a",
"recursive",
"tree",
"with",
"category",
"relations",
"as",
"children",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L199-L216 |
marteinn/wpparser | wpparser/parser.py | _parse_tags | def _parse_tags(element):
"""
Retrieves and parses tags into a array/dict.
Example:
[{"term_id": 1, "slug": "python", "name": "Python"},
{"term_id": 2, "slug": "java", "name": "Java"}]
"""
tags = []
items = element.findall("./{%s}tag" % WP_NAMESPACE)
for item in items:
term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text
slug = item.find("./{%s}tag_slug" % WP_NAMESPACE).text
name = item.find("./{%s}tag_name" % WP_NAMESPACE).text
tag = {
"term_id": term_id,
"slug": slug,
"name": name,
}
tags.append(tag)
return tags | python | def _parse_tags(element):
"""
Retrieves and parses tags into a array/dict.
Example:
[{"term_id": 1, "slug": "python", "name": "Python"},
{"term_id": 2, "slug": "java", "name": "Java"}]
"""
tags = []
items = element.findall("./{%s}tag" % WP_NAMESPACE)
for item in items:
term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text
slug = item.find("./{%s}tag_slug" % WP_NAMESPACE).text
name = item.find("./{%s}tag_name" % WP_NAMESPACE).text
tag = {
"term_id": term_id,
"slug": slug,
"name": name,
}
tags.append(tag)
return tags | [
"def",
"_parse_tags",
"(",
"element",
")",
":",
"tags",
"=",
"[",
"]",
"items",
"=",
"element",
".",
"findall",
"(",
"\"./{%s}tag\"",
"%",
"WP_NAMESPACE",
")",
"for",
"item",
"in",
"items",
":",
"term_id",
"=",
"item",
".",
"find",
"(",
"\"./{%s}term_id\... | Retrieves and parses tags into a array/dict.
Example:
[{"term_id": 1, "slug": "python", "name": "Python"},
{"term_id": 2, "slug": "java", "name": "Java"}] | [
"Retrieves",
"and",
"parses",
"tags",
"into",
"a",
"array",
"/",
"dict",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L219-L245 |
marteinn/wpparser | wpparser/parser.py | _parse_posts | def _parse_posts(element):
"""
Returns a list with posts.
"""
posts = []
items = element.findall("item")
for item in items:
title = item.find("./title").text
link = item.find("./link").text
pub_date = item.find("./pubDate").text
creator = item.find("./{%s}creator" % DC_NAMESPACE).text
guid = item.find("./guid").text
description = item.find("./description").text
content = item.find("./{%s}encoded" % CONTENT_NAMESPACE).text
excerpt = item.find("./{%s}encoded" % EXCERPT_NAMESPACE).text
post_id = item.find("./{%s}post_id" % WP_NAMESPACE).text
post_date = item.find("./{%s}post_date" % WP_NAMESPACE).text
post_date_gmt = item.find("./{%s}post_date_gmt" % WP_NAMESPACE).text
status = item.find("./{%s}status" % WP_NAMESPACE).text
post_parent = item.find("./{%s}post_parent" % WP_NAMESPACE).text
menu_order = item.find("./{%s}menu_order" % WP_NAMESPACE).text
post_type = item.find("./{%s}post_type" % WP_NAMESPACE).text
post_name = item.find("./{%s}post_name" % WP_NAMESPACE).text
is_sticky = item.find("./{%s}is_sticky" % WP_NAMESPACE).text
ping_status = item.find("./{%s}ping_status" % WP_NAMESPACE).text
post_password = item.find("./{%s}post_password" % WP_NAMESPACE).text
category_items = item.findall("./category")
categories = []
tags = []
for category_item in category_items:
if category_item.attrib["domain"] == "category":
item_list = categories
else:
item_list = tags
item_list.append(category_item.attrib["nicename"])
post = {
"title": title,
"link": link,
"pub_date": pub_date,
"creator": creator,
"guid": guid,
"description": description,
"content": content,
"excerpt": excerpt,
"post_id": post_id,
"post_date": post_date,
"post_date_gmt": post_date_gmt,
"status": status,
"post_parent": post_parent,
"menu_order": menu_order,
"post_type": post_type,
"post_name": post_name,
"categories": categories,
"is_sticky": is_sticky,
"ping_status": ping_status,
"post_password": post_password,
"tags": tags,
}
post["postmeta"] = _parse_postmeta(item)
post["comments"] = _parse_comments(item)
posts.append(post)
return posts | python | def _parse_posts(element):
"""
Returns a list with posts.
"""
posts = []
items = element.findall("item")
for item in items:
title = item.find("./title").text
link = item.find("./link").text
pub_date = item.find("./pubDate").text
creator = item.find("./{%s}creator" % DC_NAMESPACE).text
guid = item.find("./guid").text
description = item.find("./description").text
content = item.find("./{%s}encoded" % CONTENT_NAMESPACE).text
excerpt = item.find("./{%s}encoded" % EXCERPT_NAMESPACE).text
post_id = item.find("./{%s}post_id" % WP_NAMESPACE).text
post_date = item.find("./{%s}post_date" % WP_NAMESPACE).text
post_date_gmt = item.find("./{%s}post_date_gmt" % WP_NAMESPACE).text
status = item.find("./{%s}status" % WP_NAMESPACE).text
post_parent = item.find("./{%s}post_parent" % WP_NAMESPACE).text
menu_order = item.find("./{%s}menu_order" % WP_NAMESPACE).text
post_type = item.find("./{%s}post_type" % WP_NAMESPACE).text
post_name = item.find("./{%s}post_name" % WP_NAMESPACE).text
is_sticky = item.find("./{%s}is_sticky" % WP_NAMESPACE).text
ping_status = item.find("./{%s}ping_status" % WP_NAMESPACE).text
post_password = item.find("./{%s}post_password" % WP_NAMESPACE).text
category_items = item.findall("./category")
categories = []
tags = []
for category_item in category_items:
if category_item.attrib["domain"] == "category":
item_list = categories
else:
item_list = tags
item_list.append(category_item.attrib["nicename"])
post = {
"title": title,
"link": link,
"pub_date": pub_date,
"creator": creator,
"guid": guid,
"description": description,
"content": content,
"excerpt": excerpt,
"post_id": post_id,
"post_date": post_date,
"post_date_gmt": post_date_gmt,
"status": status,
"post_parent": post_parent,
"menu_order": menu_order,
"post_type": post_type,
"post_name": post_name,
"categories": categories,
"is_sticky": is_sticky,
"ping_status": ping_status,
"post_password": post_password,
"tags": tags,
}
post["postmeta"] = _parse_postmeta(item)
post["comments"] = _parse_comments(item)
posts.append(post)
return posts | [
"def",
"_parse_posts",
"(",
"element",
")",
":",
"posts",
"=",
"[",
"]",
"items",
"=",
"element",
".",
"findall",
"(",
"\"item\"",
")",
"for",
"item",
"in",
"items",
":",
"title",
"=",
"item",
".",
"find",
"(",
"\"./title\"",
")",
".",
"text",
"link"... | Returns a list with posts. | [
"Returns",
"a",
"list",
"with",
"posts",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L248-L317 |
marteinn/wpparser | wpparser/parser.py | _parse_postmeta | def _parse_postmeta(element):
import phpserialize
"""
Retrive post metadata as a dictionary
"""
metadata = {}
fields = element.findall("./{%s}postmeta" % WP_NAMESPACE)
for field in fields:
key = field.find("./{%s}meta_key" % WP_NAMESPACE).text
value = field.find("./{%s}meta_value" % WP_NAMESPACE).text
if key == "_wp_attachment_metadata":
stream = StringIO(value.encode())
try:
data = phpserialize.load(stream)
metadata["attachment_metadata"] = data
except ValueError as e:
pass
except Exception as e:
raise(e)
if key == "_wp_attached_file":
metadata["attached_file"] = value
return metadata | python | def _parse_postmeta(element):
import phpserialize
"""
Retrive post metadata as a dictionary
"""
metadata = {}
fields = element.findall("./{%s}postmeta" % WP_NAMESPACE)
for field in fields:
key = field.find("./{%s}meta_key" % WP_NAMESPACE).text
value = field.find("./{%s}meta_value" % WP_NAMESPACE).text
if key == "_wp_attachment_metadata":
stream = StringIO(value.encode())
try:
data = phpserialize.load(stream)
metadata["attachment_metadata"] = data
except ValueError as e:
pass
except Exception as e:
raise(e)
if key == "_wp_attached_file":
metadata["attached_file"] = value
return metadata | [
"def",
"_parse_postmeta",
"(",
"element",
")",
":",
"import",
"phpserialize",
"metadata",
"=",
"{",
"}",
"fields",
"=",
"element",
".",
"findall",
"(",
"\"./{%s}postmeta\"",
"%",
"WP_NAMESPACE",
")",
"for",
"field",
"in",
"fields",
":",
"key",
"=",
"field",
... | Retrive post metadata as a dictionary | [
"Retrive",
"post",
"metadata",
"as",
"a",
"dictionary"
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L320-L347 |
marteinn/wpparser | wpparser/parser.py | _parse_comments | def _parse_comments(element):
"""
Returns a list with comments.
"""
comments = []
items = element.findall("./{%s}comment" % WP_NAMESPACE)
for item in items:
comment_id = item.find("./{%s}comment_id" % WP_NAMESPACE).text
author = item.find("./{%s}comment_author" % WP_NAMESPACE).text
email = item.find("./{%s}comment_author_email" % WP_NAMESPACE).text
author_url = item.find("./{%s}comment_author_url" % WP_NAMESPACE).text
author_ip = item.find("./{%s}comment_author_IP" % WP_NAMESPACE).text
date = item.find("./{%s}comment_date" % WP_NAMESPACE).text
date_gmt = item.find("./{%s}comment_date_gmt" % WP_NAMESPACE).text
content = item.find("./{%s}comment_content" % WP_NAMESPACE).text
approved = item.find("./{%s}comment_approved" % WP_NAMESPACE).text
comment_type = item.find("./{%s}comment_type" % WP_NAMESPACE).text
parent = item.find("./{%s}comment_parent" % WP_NAMESPACE).text
user_id = item.find("./{%s}comment_user_id" % WP_NAMESPACE).text
comment = {
"id": comment_id,
"author": author,
"author_email": email,
"author_url": author_url,
"author_ip": author_ip,
"date": date,
"date_gmt": date_gmt,
"content": content,
"approved": approved,
"type": comment_type,
"parent": parent,
"user_id": user_id,
}
comments.append(comment)
return comments | python | def _parse_comments(element):
"""
Returns a list with comments.
"""
comments = []
items = element.findall("./{%s}comment" % WP_NAMESPACE)
for item in items:
comment_id = item.find("./{%s}comment_id" % WP_NAMESPACE).text
author = item.find("./{%s}comment_author" % WP_NAMESPACE).text
email = item.find("./{%s}comment_author_email" % WP_NAMESPACE).text
author_url = item.find("./{%s}comment_author_url" % WP_NAMESPACE).text
author_ip = item.find("./{%s}comment_author_IP" % WP_NAMESPACE).text
date = item.find("./{%s}comment_date" % WP_NAMESPACE).text
date_gmt = item.find("./{%s}comment_date_gmt" % WP_NAMESPACE).text
content = item.find("./{%s}comment_content" % WP_NAMESPACE).text
approved = item.find("./{%s}comment_approved" % WP_NAMESPACE).text
comment_type = item.find("./{%s}comment_type" % WP_NAMESPACE).text
parent = item.find("./{%s}comment_parent" % WP_NAMESPACE).text
user_id = item.find("./{%s}comment_user_id" % WP_NAMESPACE).text
comment = {
"id": comment_id,
"author": author,
"author_email": email,
"author_url": author_url,
"author_ip": author_ip,
"date": date,
"date_gmt": date_gmt,
"content": content,
"approved": approved,
"type": comment_type,
"parent": parent,
"user_id": user_id,
}
comments.append(comment)
return comments | [
"def",
"_parse_comments",
"(",
"element",
")",
":",
"comments",
"=",
"[",
"]",
"items",
"=",
"element",
".",
"findall",
"(",
"\"./{%s}comment\"",
"%",
"WP_NAMESPACE",
")",
"for",
"item",
"in",
"items",
":",
"comment_id",
"=",
"item",
".",
"find",
"(",
"\... | Returns a list with comments. | [
"Returns",
"a",
"list",
"with",
"comments",
"."
] | train | https://github.com/marteinn/wpparser/blob/e850d2f04333756ebae50d9fc25b6efb1946c54c/wpparser/parser.py#L350-L389 |
fortaa/dam1021 | src/dam1021.py | Connection.open_umanager | def open_umanager(self):
"""Used to open an uManager session.
"""
if self.umanager_opened:
return
self.ser.write(self.cmd_umanager_invocation)
# optimistic approach first: assume umanager is not invoked
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout*self.umanager_waitcoeff):
self.umanager_opened = True
else:
#if we are already in umanager, this will give us a fresh prompt
self.ser.write(self.cr)
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout):
self.umanager_opened = True
if self.umanager_opened:
log.debug("uManager opened")
else:
raise Dam1021Error(1,"Failed to open uManager") | python | def open_umanager(self):
"""Used to open an uManager session.
"""
if self.umanager_opened:
return
self.ser.write(self.cmd_umanager_invocation)
# optimistic approach first: assume umanager is not invoked
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout*self.umanager_waitcoeff):
self.umanager_opened = True
else:
#if we are already in umanager, this will give us a fresh prompt
self.ser.write(self.cr)
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout):
self.umanager_opened = True
if self.umanager_opened:
log.debug("uManager opened")
else:
raise Dam1021Error(1,"Failed to open uManager") | [
"def",
"open_umanager",
"(",
"self",
")",
":",
"if",
"self",
".",
"umanager_opened",
":",
"return",
"self",
".",
"ser",
".",
"write",
"(",
"self",
".",
"cmd_umanager_invocation",
")",
"# optimistic approach first: assume umanager is not invoked",
"if",
"self",
".",
... | Used to open an uManager session. | [
"Used",
"to",
"open",
"an",
"uManager",
"session",
"."
] | train | https://github.com/fortaa/dam1021/blob/1bc5b75ebf2cc7bc8dc2a451793a9e769e16ce5f/src/dam1021.py#L150-L170 |
fortaa/dam1021 | src/dam1021.py | Connection.close_umanager | def close_umanager(self, force=False):
"""Used to close an uManager session.
:param force: try to close a session regardless of a connection object internal state
"""
if not (force or self.umanager_opened):
return
# make sure we've got a fresh prompt
self.ser.write(self.cr)
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout):
self.ser.write(''.join((self.cmd_umanager_termination,self.cr)))
if self.read_loop(lambda x: x.endswith(self.buf_on_exit),self.timeout):
log.debug("uManager closed")
else:
raise Dam1021Error(2,"Failed to close uManager")
else:
log.debug("uManager already closed")
self.umanager_opened = False | python | def close_umanager(self, force=False):
"""Used to close an uManager session.
:param force: try to close a session regardless of a connection object internal state
"""
if not (force or self.umanager_opened):
return
# make sure we've got a fresh prompt
self.ser.write(self.cr)
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout):
self.ser.write(''.join((self.cmd_umanager_termination,self.cr)))
if self.read_loop(lambda x: x.endswith(self.buf_on_exit),self.timeout):
log.debug("uManager closed")
else:
raise Dam1021Error(2,"Failed to close uManager")
else:
log.debug("uManager already closed")
self.umanager_opened = False | [
"def",
"close_umanager",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"(",
"force",
"or",
"self",
".",
"umanager_opened",
")",
":",
"return",
"# make sure we've got a fresh prompt",
"self",
".",
"ser",
".",
"write",
"(",
"self",
".",
"cr... | Used to close an uManager session.
:param force: try to close a session regardless of a connection object internal state | [
"Used",
"to",
"close",
"an",
"uManager",
"session",
".",
":",
"param",
"force",
":",
"try",
"to",
"close",
"a",
"session",
"regardless",
"of",
"a",
"connection",
"object",
"internal",
"state"
] | train | https://github.com/fortaa/dam1021/blob/1bc5b75ebf2cc7bc8dc2a451793a9e769e16ce5f/src/dam1021.py#L172-L191 |
fortaa/dam1021 | src/dam1021.py | Connection.download | def download(self,data,um_update=False):
"""Used to download firmware or filter set.
:param data: binary string to push via serial
:param um_update: flag whether to update umanager
"""
self.open_umanager()
self.ser.write(''.join((self.cmd_download,self.cr)))
if self.read_loop(lambda x: x.endswith(self.xmodem_crc),self.timeout):
if self.xmodem.send(StringIO.StringIO(data)):
log.info("Data sent")
else:
raise Dam1021Error(4,"Error during file download")
else:
raise Dam1021Error(3,"uManager is not ready to accept a data")
if self.read_loop(lambda x: x.lower().find(self.reprogram_ack) != -1,self.timeout):
skr_sum = hashlib.sha1(data).hexdigest()
log.info("File downloaded. Data SHA-1 checksum: {}".format(skr_sum))
else:
raise Dam1021Error(5,"uManager accepted data and not reprogrammed")
if um_update:
self.ser.write(''.join((self.cmd_update,self.cr)))
if self.read_loop(lambda x: x.lower().find(self.update_confirmation) != -1,self.timeout*self.umanager_waitcoeff):
self.ser.write(self.update_ack)
else:
raise Dam1021Error(13,"Error during update command invocation")
if self.read_loop(lambda x: x.lower().find(self.update_reset) != -1,self.timeout*self.umanager_waitcoeff):
log.info("uManager updated")
else:
raise Dam1021Error(14,"Update failed")
else:
self.close_umanager()
return skr_sum | python | def download(self,data,um_update=False):
"""Used to download firmware or filter set.
:param data: binary string to push via serial
:param um_update: flag whether to update umanager
"""
self.open_umanager()
self.ser.write(''.join((self.cmd_download,self.cr)))
if self.read_loop(lambda x: x.endswith(self.xmodem_crc),self.timeout):
if self.xmodem.send(StringIO.StringIO(data)):
log.info("Data sent")
else:
raise Dam1021Error(4,"Error during file download")
else:
raise Dam1021Error(3,"uManager is not ready to accept a data")
if self.read_loop(lambda x: x.lower().find(self.reprogram_ack) != -1,self.timeout):
skr_sum = hashlib.sha1(data).hexdigest()
log.info("File downloaded. Data SHA-1 checksum: {}".format(skr_sum))
else:
raise Dam1021Error(5,"uManager accepted data and not reprogrammed")
if um_update:
self.ser.write(''.join((self.cmd_update,self.cr)))
if self.read_loop(lambda x: x.lower().find(self.update_confirmation) != -1,self.timeout*self.umanager_waitcoeff):
self.ser.write(self.update_ack)
else:
raise Dam1021Error(13,"Error during update command invocation")
if self.read_loop(lambda x: x.lower().find(self.update_reset) != -1,self.timeout*self.umanager_waitcoeff):
log.info("uManager updated")
else:
raise Dam1021Error(14,"Update failed")
else:
self.close_umanager()
return skr_sum | [
"def",
"download",
"(",
"self",
",",
"data",
",",
"um_update",
"=",
"False",
")",
":",
"self",
".",
"open_umanager",
"(",
")",
"self",
".",
"ser",
".",
"write",
"(",
"''",
".",
"join",
"(",
"(",
"self",
".",
"cmd_download",
",",
"self",
".",
"cr",
... | Used to download firmware or filter set.
:param data: binary string to push via serial
:param um_update: flag whether to update umanager | [
"Used",
"to",
"download",
"firmware",
"or",
"filter",
"set",
".",
":",
"param",
"data",
":",
"binary",
"string",
"to",
"push",
"via",
"serial",
":",
"param",
"um_update",
":",
"flag",
"whether",
"to",
"update",
"umanager"
] | train | https://github.com/fortaa/dam1021/blob/1bc5b75ebf2cc7bc8dc2a451793a9e769e16ce5f/src/dam1021.py#L193-L231 |
fortaa/dam1021 | src/dam1021.py | Connection.list_current_filter_set | def list_current_filter_set(self,raw=False):
"""User to list a currently selected filter set"""
buf = []
self.open_umanager()
self.ser.write(''.join((self.cmd_current_filter_list,self.cr)))
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout,lambda x,y,z: buf.append(y.rstrip()[:-1])):
if raw:
rv = buf = buf[0]
else:
rv, buf = self.filter_organizer(buf[0])
else:
raise Dam1021Error(16,"Failed to list currently selected filter set")
self.close_umanager()
log.info(buf)
return rv | python | def list_current_filter_set(self,raw=False):
"""User to list a currently selected filter set"""
buf = []
self.open_umanager()
self.ser.write(''.join((self.cmd_current_filter_list,self.cr)))
if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout,lambda x,y,z: buf.append(y.rstrip()[:-1])):
if raw:
rv = buf = buf[0]
else:
rv, buf = self.filter_organizer(buf[0])
else:
raise Dam1021Error(16,"Failed to list currently selected filter set")
self.close_umanager()
log.info(buf)
return rv | [
"def",
"list_current_filter_set",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"buf",
"=",
"[",
"]",
"self",
".",
"open_umanager",
"(",
")",
"self",
".",
"ser",
".",
"write",
"(",
"''",
".",
"join",
"(",
"(",
"self",
".",
"cmd_current_filter_list",... | User to list a currently selected filter set | [
"User",
"to",
"list",
"a",
"currently",
"selected",
"filter",
"set"
] | train | https://github.com/fortaa/dam1021/blob/1bc5b75ebf2cc7bc8dc2a451793a9e769e16ce5f/src/dam1021.py#L374-L392 |
gmr/tredis | tredis/lists.py | ListsMixin.lrange | def lrange(self, key, start, end):
"""
Returns the specified elements of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to start retrieving elements from
:param int end: zero-based index at which to stop retrieving elements
:rtype: list
:raises: :exc:`~tredis.exceptions.TRedisException`
The offsets start and stop are zero-based indexes, with 0 being the
first element of the list (the head of the list), 1 being the next
element and so on.
These offsets can also be negative numbers indicating offsets
starting at the end of the list. For example, -1 is the last element
of the list, -2 the penultimate, and so on.
Note that if you have a list of numbers from 0 to 100,
``lrange(key, 0, 10)`` will return 11 elements, that is, the
rightmost item is included. This may or may not be consistent with
behavior of range-related functions in your programming language of
choice (think Ruby's ``Range.new``, ``Array#slice`` or Python's
:func:`range` function).
Out of range indexes will not produce an error. If start is larger
than the end of the list, an empty list is returned. If stop is
larger than the actual end of the list, Redis will treat it like the
last element of the list.
.. note::
**Time complexity** ``O(S+N)`` where ``S`` is the distance of
start offset from ``HEAD`` for small lists, from nearest end
(``HEAD`` or ``TAIL``) for large lists; and ``N`` is the number
of elements in the specified range.
"""
return self._execute([b'LRANGE', key, start, end]) | python | def lrange(self, key, start, end):
"""
Returns the specified elements of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to start retrieving elements from
:param int end: zero-based index at which to stop retrieving elements
:rtype: list
:raises: :exc:`~tredis.exceptions.TRedisException`
The offsets start and stop are zero-based indexes, with 0 being the
first element of the list (the head of the list), 1 being the next
element and so on.
These offsets can also be negative numbers indicating offsets
starting at the end of the list. For example, -1 is the last element
of the list, -2 the penultimate, and so on.
Note that if you have a list of numbers from 0 to 100,
``lrange(key, 0, 10)`` will return 11 elements, that is, the
rightmost item is included. This may or may not be consistent with
behavior of range-related functions in your programming language of
choice (think Ruby's ``Range.new``, ``Array#slice`` or Python's
:func:`range` function).
Out of range indexes will not produce an error. If start is larger
than the end of the list, an empty list is returned. If stop is
larger than the actual end of the list, Redis will treat it like the
last element of the list.
.. note::
**Time complexity** ``O(S+N)`` where ``S`` is the distance of
start offset from ``HEAD`` for small lists, from nearest end
(``HEAD`` or ``TAIL``) for large lists; and ``N`` is the number
of elements in the specified range.
"""
return self._execute([b'LRANGE', key, start, end]) | [
"def",
"lrange",
"(",
"self",
",",
"key",
",",
"start",
",",
"end",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'LRANGE'",
",",
"key",
",",
"start",
",",
"end",
"]",
")"
] | Returns the specified elements of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to start retrieving elements from
:param int end: zero-based index at which to stop retrieving elements
:rtype: list
:raises: :exc:`~tredis.exceptions.TRedisException`
The offsets start and stop are zero-based indexes, with 0 being the
first element of the list (the head of the list), 1 being the next
element and so on.
These offsets can also be negative numbers indicating offsets
starting at the end of the list. For example, -1 is the last element
of the list, -2 the penultimate, and so on.
Note that if you have a list of numbers from 0 to 100,
``lrange(key, 0, 10)`` will return 11 elements, that is, the
rightmost item is included. This may or may not be consistent with
behavior of range-related functions in your programming language of
choice (think Ruby's ``Range.new``, ``Array#slice`` or Python's
:func:`range` function).
Out of range indexes will not produce an error. If start is larger
than the end of the list, an empty list is returned. If stop is
larger than the actual end of the list, Redis will treat it like the
last element of the list.
.. note::
**Time complexity** ``O(S+N)`` where ``S`` is the distance of
start offset from ``HEAD`` for small lists, from nearest end
(``HEAD`` or ``TAIL``) for large lists; and ``N`` is the number
of elements in the specified range. | [
"Returns",
"the",
"specified",
"elements",
"of",
"the",
"list",
"stored",
"at",
"key",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/lists.py#L27-L67 |
gmr/tredis | tredis/lists.py | ListsMixin.ltrim | def ltrim(self, key, start, stop):
"""
Crop a list to the specified range.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to first element to retain
:param int stop: zero-based index of the last element to retain
:returns: did the operation succeed?
:rtype: bool
:raises: :exc:`~tredis.exceptions.TRedisException`
Trim an existing list so that it will contain only the specified
range of elements specified.
Both `start` and `stop` are zero-based indexes, where 0 is the first
element of the list (the head), 1 the next element and so on.
For example: ``ltrim('foobar', 0, 2)`` will modify the list stored at
``foobar`` so that only the first three elements of the list will
remain.
`start` and `stop` can also be negative numbers indicating offsets
from the end of the list, where -1 is the last element of the list,
-2 the penultimate element and so on.
Out of range indexes will not produce an error: if `start` is larger
than the `end` of the list, or `start > end`, the result will be an
empty list (which causes `key` to be removed). If `end` is larger
than the end of the list, Redis will treat it like the last element
of the list.
A common use of LTRIM is together with LPUSH / RPUSH. For example::
client.lpush('mylist', 'somelement')
client.ltrim('mylist', 0, 99)
This pair of commands will push a new element on the list, while
making sure that the list will not grow larger than 100 elements.
This is very useful when using Redis to store logs for example. It is
important to note that when used in this way LTRIM is an O(1)
operation because in the average case just one element is removed
from the tail of the list.
.. note::
Time complexity: ``O(N)`` where `N` is the number of elements to
be removed by the operation.
"""
return self._execute([b'LTRIM', key, start, stop], b'OK') | python | def ltrim(self, key, start, stop):
"""
Crop a list to the specified range.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to first element to retain
:param int stop: zero-based index of the last element to retain
:returns: did the operation succeed?
:rtype: bool
:raises: :exc:`~tredis.exceptions.TRedisException`
Trim an existing list so that it will contain only the specified
range of elements specified.
Both `start` and `stop` are zero-based indexes, where 0 is the first
element of the list (the head), 1 the next element and so on.
For example: ``ltrim('foobar', 0, 2)`` will modify the list stored at
``foobar`` so that only the first three elements of the list will
remain.
`start` and `stop` can also be negative numbers indicating offsets
from the end of the list, where -1 is the last element of the list,
-2 the penultimate element and so on.
Out of range indexes will not produce an error: if `start` is larger
than the `end` of the list, or `start > end`, the result will be an
empty list (which causes `key` to be removed). If `end` is larger
than the end of the list, Redis will treat it like the last element
of the list.
A common use of LTRIM is together with LPUSH / RPUSH. For example::
client.lpush('mylist', 'somelement')
client.ltrim('mylist', 0, 99)
This pair of commands will push a new element on the list, while
making sure that the list will not grow larger than 100 elements.
This is very useful when using Redis to store logs for example. It is
important to note that when used in this way LTRIM is an O(1)
operation because in the average case just one element is removed
from the tail of the list.
.. note::
Time complexity: ``O(N)`` where `N` is the number of elements to
be removed by the operation.
"""
return self._execute([b'LTRIM', key, start, stop], b'OK') | [
"def",
"ltrim",
"(",
"self",
",",
"key",
",",
"start",
",",
"stop",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'LTRIM'",
",",
"key",
",",
"start",
",",
"stop",
"]",
",",
"b'OK'",
")"
] | Crop a list to the specified range.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param int start: zero-based index to first element to retain
:param int stop: zero-based index of the last element to retain
:returns: did the operation succeed?
:rtype: bool
:raises: :exc:`~tredis.exceptions.TRedisException`
Trim an existing list so that it will contain only the specified
range of elements specified.
Both `start` and `stop` are zero-based indexes, where 0 is the first
element of the list (the head), 1 the next element and so on.
For example: ``ltrim('foobar', 0, 2)`` will modify the list stored at
``foobar`` so that only the first three elements of the list will
remain.
`start` and `stop` can also be negative numbers indicating offsets
from the end of the list, where -1 is the last element of the list,
-2 the penultimate element and so on.
Out of range indexes will not produce an error: if `start` is larger
than the `end` of the list, or `start > end`, the result will be an
empty list (which causes `key` to be removed). If `end` is larger
than the end of the list, Redis will treat it like the last element
of the list.
A common use of LTRIM is together with LPUSH / RPUSH. For example::
client.lpush('mylist', 'somelement')
client.ltrim('mylist', 0, 99)
This pair of commands will push a new element on the list, while
making sure that the list will not grow larger than 100 elements.
This is very useful when using Redis to store logs for example. It is
important to note that when used in this way LTRIM is an O(1)
operation because in the average case just one element is removed
from the tail of the list.
.. note::
Time complexity: ``O(N)`` where `N` is the number of elements to
be removed by the operation. | [
"Crop",
"a",
"list",
"to",
"the",
"specified",
"range",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/lists.py#L69-L118 |
gmr/tredis | tredis/lists.py | ListsMixin.lpush | def lpush(self, key, *values):
"""
Insert all the specified values at the head of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of the list individually (see discussion below).
:returns: the length of the list after push operations
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
If `key` does not exist, it is created as empty list before
performing the push operations. When key holds a value that is not a
list, an error is returned.
It is possible to push multiple elements using a single command call
just specifying multiple arguments at the end of the command.
Elements are inserted one after the other to the head of the list,
from the leftmost element to the rightmost element. So for instance
``client.lpush('mylist', 'a', 'b', 'c')`` will result into a list
containing ``c`` as first element, ``b`` as second element and ``a``
as third element.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'LPUSH', key] + list(values)) | python | def lpush(self, key, *values):
"""
Insert all the specified values at the head of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of the list individually (see discussion below).
:returns: the length of the list after push operations
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
If `key` does not exist, it is created as empty list before
performing the push operations. When key holds a value that is not a
list, an error is returned.
It is possible to push multiple elements using a single command call
just specifying multiple arguments at the end of the command.
Elements are inserted one after the other to the head of the list,
from the leftmost element to the rightmost element. So for instance
``client.lpush('mylist', 'a', 'b', 'c')`` will result into a list
containing ``c`` as first element, ``b`` as second element and ``a``
as third element.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'LPUSH', key] + list(values)) | [
"def",
"lpush",
"(",
"self",
",",
"key",
",",
"*",
"values",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'LPUSH'",
",",
"key",
"]",
"+",
"list",
"(",
"values",
")",
")"
] | Insert all the specified values at the head of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of the list individually (see discussion below).
:returns: the length of the list after push operations
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
If `key` does not exist, it is created as empty list before
performing the push operations. When key holds a value that is not a
list, an error is returned.
It is possible to push multiple elements using a single command call
just specifying multiple arguments at the end of the command.
Elements are inserted one after the other to the head of the list,
from the leftmost element to the rightmost element. So for instance
``client.lpush('mylist', 'a', 'b', 'c')`` will result into a list
containing ``c`` as first element, ``b`` as second element and ``a``
as third element.
.. note::
**Time complexity**: ``O(1)`` | [
"Insert",
"all",
"the",
"specified",
"values",
"at",
"the",
"head",
"of",
"the",
"list",
"stored",
"at",
"key",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/lists.py#L120-L150 |
gmr/tredis | tredis/lists.py | ListsMixin.lpushx | def lpushx(self, key, *values):
"""
Insert values at the head of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of the list individually (see discussion below).
:returns: the length of the list after push operations, zero if
`key` does not refer to a list
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
This method inserts `values` at the head of the list stored at `key`,
only if `key` already exists and holds a list. In contrary to
:meth:`.lpush`, no operation will be performed when key does not yet
exist.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'LPUSHX', key] + list(values)) | python | def lpushx(self, key, *values):
"""
Insert values at the head of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of the list individually (see discussion below).
:returns: the length of the list after push operations, zero if
`key` does not refer to a list
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
This method inserts `values` at the head of the list stored at `key`,
only if `key` already exists and holds a list. In contrary to
:meth:`.lpush`, no operation will be performed when key does not yet
exist.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'LPUSHX', key] + list(values)) | [
"def",
"lpushx",
"(",
"self",
",",
"key",
",",
"*",
"values",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'LPUSHX'",
",",
"key",
"]",
"+",
"list",
"(",
"values",
")",
")"
] | Insert values at the head of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
beginning of the list. Each value is inserted at the beginning
of the list individually (see discussion below).
:returns: the length of the list after push operations, zero if
`key` does not refer to a list
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
This method inserts `values` at the head of the list stored at `key`,
only if `key` already exists and holds a list. In contrary to
:meth:`.lpush`, no operation will be performed when key does not yet
exist.
.. note::
**Time complexity**: ``O(1)`` | [
"Insert",
"values",
"at",
"the",
"head",
"of",
"an",
"existing",
"list",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/lists.py#L152-L176 |
gmr/tredis | tredis/lists.py | ListsMixin.rpush | def rpush(self, key, *values):
"""
Insert all the specified values at the tail of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
If `key` does not exist, it is created as empty list before performing
the push operation. When `key` holds a value that is not a list, an
error is returned.
It is possible to push multiple elements using a single command call
just specifying multiple arguments at the end of the command.
Elements are inserted one after the other to the tail of the list,
from the leftmost element to the rightmost element. So for instance
the command ``client.rpush('mylist', 'a', 'b', 'c')`` will result
in a list containing ``a`` as first element, ``b`` as second element
and ``c`` as third element.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'RPUSH', key] + list(values)) | python | def rpush(self, key, *values):
"""
Insert all the specified values at the tail of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
If `key` does not exist, it is created as empty list before performing
the push operation. When `key` holds a value that is not a list, an
error is returned.
It is possible to push multiple elements using a single command call
just specifying multiple arguments at the end of the command.
Elements are inserted one after the other to the tail of the list,
from the leftmost element to the rightmost element. So for instance
the command ``client.rpush('mylist', 'a', 'b', 'c')`` will result
in a list containing ``a`` as first element, ``b`` as second element
and ``c`` as third element.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'RPUSH', key] + list(values)) | [
"def",
"rpush",
"(",
"self",
",",
"key",
",",
"*",
"values",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'RPUSH'",
",",
"key",
"]",
"+",
"list",
"(",
"values",
")",
")"
] | Insert all the specified values at the tail of the list stored at key.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
If `key` does not exist, it is created as empty list before performing
the push operation. When `key` holds a value that is not a list, an
error is returned.
It is possible to push multiple elements using a single command call
just specifying multiple arguments at the end of the command.
Elements are inserted one after the other to the tail of the list,
from the leftmost element to the rightmost element. So for instance
the command ``client.rpush('mylist', 'a', 'b', 'c')`` will result
in a list containing ``a`` as first element, ``b`` as second element
and ``c`` as third element.
.. note::
**Time complexity**: ``O(1)`` | [
"Insert",
"all",
"the",
"specified",
"values",
"at",
"the",
"tail",
"of",
"the",
"list",
"stored",
"at",
"key",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/lists.py#L195-L224 |
gmr/tredis | tredis/lists.py | ListsMixin.rpushx | def rpushx(self, key, *values):
"""
Insert values at the tail of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations or
zero if `key` does not refer to a list
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
This method inserts value at the tail of the list stored at `key`,
only if `key` already exists and holds a list. In contrary to
method:`.rpush`, no operation will be performed when `key` does not
yet exist.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'RPUSHX', key] + list(values)) | python | def rpushx(self, key, *values):
"""
Insert values at the tail of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations or
zero if `key` does not refer to a list
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
This method inserts value at the tail of the list stored at `key`,
only if `key` already exists and holds a list. In contrary to
method:`.rpush`, no operation will be performed when `key` does not
yet exist.
.. note::
**Time complexity**: ``O(1)``
"""
return self._execute([b'RPUSHX', key] + list(values)) | [
"def",
"rpushx",
"(",
"self",
",",
"key",
",",
"*",
"values",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'RPUSHX'",
",",
"key",
"]",
"+",
"list",
"(",
"values",
")",
")"
] | Insert values at the tail of an existing list.
:param key: The list's key
:type key: :class:`str`, :class:`bytes`
:param values: One or more positional arguments to insert at the
tail of the list.
:returns: the length of the list after push operations or
zero if `key` does not refer to a list
:rtype: int
:raises: :exc:`~tredis.exceptions.TRedisException`
This method inserts value at the tail of the list stored at `key`,
only if `key` already exists and holds a list. In contrary to
method:`.rpush`, no operation will be performed when `key` does not
yet exist.
.. note::
**Time complexity**: ``O(1)`` | [
"Insert",
"values",
"at",
"the",
"tail",
"of",
"an",
"existing",
"list",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/lists.py#L226-L249 |
humangeo/rawes | rawes/encoders.py | encode_date_optional_time | def encode_date_optional_time(obj):
"""
ISO encode timezone-aware datetimes
"""
if isinstance(obj, datetime.datetime):
return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ')
raise TypeError("{0} is not JSON serializable".format(repr(obj))) | python | def encode_date_optional_time(obj):
"""
ISO encode timezone-aware datetimes
"""
if isinstance(obj, datetime.datetime):
return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ')
raise TypeError("{0} is not JSON serializable".format(repr(obj))) | [
"def",
"encode_date_optional_time",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"timezone",
"(",
"\"UTC\"",
")",
".",
"normalize",
"(",
"obj",
".",
"astimezone",
"(",
"timezone",
"(",
"\"UTC\"... | ISO encode timezone-aware datetimes | [
"ISO",
"encode",
"timezone",
"-",
"aware",
"datetimes"
] | train | https://github.com/humangeo/rawes/blob/b860100cbb4115a1c884133c83eae448ded6b2d3/rawes/encoders.py#L20-L26 |
dreipol/django-collectfaster | collectfaster/management/commands/collectstatic.py | Command.file_handler | def file_handler(self, handler_type, path, prefixed_path, source_storage):
"""
Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to
the queue for later processing.
"""
if self.faster:
if prefixed_path not in self.found_files:
self.found_files[prefixed_path] = (source_storage, path)
self.task_queue.put({
'handler_type': handler_type,
'path': path,
'prefixed_path': prefixed_path,
'source_storage': source_storage
})
self.counter += 1
else:
if handler_type == 'link':
super(Command, self).link_file(path, prefixed_path, source_storage)
else:
super(Command, self).copy_file(path, prefixed_path, source_storage) | python | def file_handler(self, handler_type, path, prefixed_path, source_storage):
"""
Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to
the queue for later processing.
"""
if self.faster:
if prefixed_path not in self.found_files:
self.found_files[prefixed_path] = (source_storage, path)
self.task_queue.put({
'handler_type': handler_type,
'path': path,
'prefixed_path': prefixed_path,
'source_storage': source_storage
})
self.counter += 1
else:
if handler_type == 'link':
super(Command, self).link_file(path, prefixed_path, source_storage)
else:
super(Command, self).copy_file(path, prefixed_path, source_storage) | [
"def",
"file_handler",
"(",
"self",
",",
"handler_type",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"if",
"self",
".",
"faster",
":",
"if",
"prefixed_path",
"not",
"in",
"self",
".",
"found_files",
":",
"self",
".",
"found_files",
... | Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to
the queue for later processing. | [
"Create",
"a",
"dict",
"with",
"all",
"kwargs",
"of",
"the",
"copy_file",
"or",
"link_file",
"method",
"of",
"the",
"super",
"class",
"and",
"add",
"it",
"to",
"the",
"queue",
"for",
"later",
"processing",
"."
] | train | https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L62-L82 |
dreipol/django-collectfaster | collectfaster/management/commands/collectstatic.py | Command.delete_file | def delete_file(self, path, prefixed_path, source_storage):
"""
We don't need all the file_exists stuff because we have to override all files anyways.
"""
if self.faster:
return True
else:
return super(Command, self).delete_file(path, prefixed_path, source_storage) | python | def delete_file(self, path, prefixed_path, source_storage):
"""
We don't need all the file_exists stuff because we have to override all files anyways.
"""
if self.faster:
return True
else:
return super(Command, self).delete_file(path, prefixed_path, source_storage) | [
"def",
"delete_file",
"(",
"self",
",",
"path",
",",
"prefixed_path",
",",
"source_storage",
")",
":",
"if",
"self",
".",
"faster",
":",
"return",
"True",
"else",
":",
"return",
"super",
"(",
"Command",
",",
"self",
")",
".",
"delete_file",
"(",
"path",
... | We don't need all the file_exists stuff because we have to override all files anyways. | [
"We",
"don",
"t",
"need",
"all",
"the",
"file_exists",
"stuff",
"because",
"we",
"have",
"to",
"override",
"all",
"files",
"anyways",
"."
] | train | https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L84-L91 |
dreipol/django-collectfaster | collectfaster/management/commands/collectstatic.py | Command.collect | def collect(self):
"""
Create some concurrent workers that process the tasks simultaneously.
"""
collected = super(Command, self).collect()
if self.faster:
self.worker_spawn_method()
self.post_processor()
return collected | python | def collect(self):
"""
Create some concurrent workers that process the tasks simultaneously.
"""
collected = super(Command, self).collect()
if self.faster:
self.worker_spawn_method()
self.post_processor()
return collected | [
"def",
"collect",
"(",
"self",
")",
":",
"collected",
"=",
"super",
"(",
"Command",
",",
"self",
")",
".",
"collect",
"(",
")",
"if",
"self",
".",
"faster",
":",
"self",
".",
"worker_spawn_method",
"(",
")",
"self",
".",
"post_processor",
"(",
")",
"... | Create some concurrent workers that process the tasks simultaneously. | [
"Create",
"some",
"concurrent",
"workers",
"that",
"process",
"the",
"tasks",
"simultaneously",
"."
] | train | https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L93-L101 |
dreipol/django-collectfaster | collectfaster/management/commands/collectstatic.py | Command.gevent_spawn | def gevent_spawn(self):
""" Spawn worker threads (using gevent) """
monkey.patch_all(thread=False)
joinall([spawn(self.gevent_worker) for x in range(self.queue_worker_amount)]) | python | def gevent_spawn(self):
""" Spawn worker threads (using gevent) """
monkey.patch_all(thread=False)
joinall([spawn(self.gevent_worker) for x in range(self.queue_worker_amount)]) | [
"def",
"gevent_spawn",
"(",
"self",
")",
":",
"monkey",
".",
"patch_all",
"(",
"thread",
"=",
"False",
")",
"joinall",
"(",
"[",
"spawn",
"(",
"self",
".",
"gevent_worker",
")",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"queue_worker_amount",
")",
"... | Spawn worker threads (using gevent) | [
"Spawn",
"worker",
"threads",
"(",
"using",
"gevent",
")"
] | train | https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L123-L126 |
dreipol/django-collectfaster | collectfaster/management/commands/collectstatic.py | Command.gevent_worker | def gevent_worker(self):
"""
Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class.
"""
while not self.task_queue.empty():
task_kwargs = self.task_queue.get()
handler_type = task_kwargs.pop('handler_type')
if handler_type == 'link':
super(Command, self).link_file(**task_kwargs)
else:
super(Command, self).copy_file(**task_kwargs) | python | def gevent_worker(self):
"""
Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class.
"""
while not self.task_queue.empty():
task_kwargs = self.task_queue.get()
handler_type = task_kwargs.pop('handler_type')
if handler_type == 'link':
super(Command, self).link_file(**task_kwargs)
else:
super(Command, self).copy_file(**task_kwargs) | [
"def",
"gevent_worker",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"task_queue",
".",
"empty",
"(",
")",
":",
"task_kwargs",
"=",
"self",
".",
"task_queue",
".",
"get",
"(",
")",
"handler_type",
"=",
"task_kwargs",
".",
"pop",
"(",
"'handler_typ... | Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. | [
"Process",
"one",
"task",
"after",
"another",
"by",
"calling",
"the",
"handler",
"(",
"copy_file",
"or",
"copy_link",
")",
"method",
"of",
"the",
"super",
"class",
"."
] | train | https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L128-L139 |
dreipol/django-collectfaster | collectfaster/management/commands/collectstatic.py | Command.mp_spawn | def mp_spawn(self):
""" Spawn worker processes (using multiprocessing) """
processes = []
for x in range(self.queue_worker_amount):
process = multiprocessing.Process(target=self.mp_worker)
process.start()
processes.append(process)
for process in processes:
process.join() | python | def mp_spawn(self):
""" Spawn worker processes (using multiprocessing) """
processes = []
for x in range(self.queue_worker_amount):
process = multiprocessing.Process(target=self.mp_worker)
process.start()
processes.append(process)
for process in processes:
process.join() | [
"def",
"mp_spawn",
"(",
"self",
")",
":",
"processes",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"queue_worker_amount",
")",
":",
"process",
"=",
"multiprocessing",
".",
"Process",
"(",
"target",
"=",
"self",
".",
"mp_worker",
")",
"p... | Spawn worker processes (using multiprocessing) | [
"Spawn",
"worker",
"processes",
"(",
"using",
"multiprocessing",
")"
] | train | https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L141-L149 |
dreipol/django-collectfaster | collectfaster/management/commands/collectstatic.py | Command.mp_worker | def mp_worker(self):
"""
Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class.
"""
while not self.task_queue.empty():
task_kwargs = self.task_queue.get()
handler_type = task_kwargs.pop('handler_type')
if handler_type == 'link':
super(Command, self).link_file(**task_kwargs)
else:
super(Command, self).copy_file(**task_kwargs)
self.task_queue.task_done() | python | def mp_worker(self):
"""
Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class.
"""
while not self.task_queue.empty():
task_kwargs = self.task_queue.get()
handler_type = task_kwargs.pop('handler_type')
if handler_type == 'link':
super(Command, self).link_file(**task_kwargs)
else:
super(Command, self).copy_file(**task_kwargs)
self.task_queue.task_done() | [
"def",
"mp_worker",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"task_queue",
".",
"empty",
"(",
")",
":",
"task_kwargs",
"=",
"self",
".",
"task_queue",
".",
"get",
"(",
")",
"handler_type",
"=",
"task_kwargs",
".",
"pop",
"(",
"'handler_type'",... | Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. | [
"Process",
"one",
"task",
"after",
"another",
"by",
"calling",
"the",
"handler",
"(",
"copy_file",
"or",
"copy_link",
")",
"method",
"of",
"the",
"super",
"class",
"."
] | train | https://github.com/dreipol/django-collectfaster/blob/13ac0df7d153a49b8c3596692741dcab441d57ce/collectfaster/management/commands/collectstatic.py#L151-L164 |
nickfrostatx/flask-hookserver | flask_hookserver.py | _load_github_hooks | def _load_github_hooks(github_url='https://api.github.com'):
"""Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503.
"""
try:
resp = requests.get(github_url + '/meta')
if resp.status_code == 200:
return resp.json()['hooks']
else:
if resp.headers.get('X-RateLimit-Remaining') == '0':
reset_ts = int(resp.headers['X-RateLimit-Reset'])
reset_string = time.strftime('%a, %d %b %Y %H:%M:%S GMT',
time.gmtime(reset_ts))
raise ServiceUnavailable('Rate limited from GitHub until ' +
reset_string)
else:
raise ServiceUnavailable('Error reaching GitHub')
except (KeyError, ValueError, requests.exceptions.ConnectionError):
raise ServiceUnavailable('Error reaching GitHub') | python | def _load_github_hooks(github_url='https://api.github.com'):
"""Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503.
"""
try:
resp = requests.get(github_url + '/meta')
if resp.status_code == 200:
return resp.json()['hooks']
else:
if resp.headers.get('X-RateLimit-Remaining') == '0':
reset_ts = int(resp.headers['X-RateLimit-Reset'])
reset_string = time.strftime('%a, %d %b %Y %H:%M:%S GMT',
time.gmtime(reset_ts))
raise ServiceUnavailable('Rate limited from GitHub until ' +
reset_string)
else:
raise ServiceUnavailable('Error reaching GitHub')
except (KeyError, ValueError, requests.exceptions.ConnectionError):
raise ServiceUnavailable('Error reaching GitHub') | [
"def",
"_load_github_hooks",
"(",
"github_url",
"=",
"'https://api.github.com'",
")",
":",
"try",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"github_url",
"+",
"'/meta'",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"return",
"resp",
".",
"... | Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503. | [
"Request",
"GitHub",
"s",
"IP",
"block",
"from",
"their",
"API",
"."
] | train | https://github.com/nickfrostatx/flask-hookserver/blob/fb5c226473f54e3469234403ec56a354374d2c41/flask_hookserver.py#L132-L156 |
nickfrostatx/flask-hookserver | flask_hookserver.py | is_github_ip | def is_github_ip(ip_str):
"""Verify that an IP address is owned by GitHub."""
if isinstance(ip_str, bytes):
ip_str = ip_str.decode()
ip = ipaddress.ip_address(ip_str)
if ip.version == 6 and ip.ipv4_mapped:
ip = ip.ipv4_mapped
for block in load_github_hooks():
if ip in ipaddress.ip_network(block):
return True
return False | python | def is_github_ip(ip_str):
"""Verify that an IP address is owned by GitHub."""
if isinstance(ip_str, bytes):
ip_str = ip_str.decode()
ip = ipaddress.ip_address(ip_str)
if ip.version == 6 and ip.ipv4_mapped:
ip = ip.ipv4_mapped
for block in load_github_hooks():
if ip in ipaddress.ip_network(block):
return True
return False | [
"def",
"is_github_ip",
"(",
"ip_str",
")",
":",
"if",
"isinstance",
"(",
"ip_str",
",",
"bytes",
")",
":",
"ip_str",
"=",
"ip_str",
".",
"decode",
"(",
")",
"ip",
"=",
"ipaddress",
".",
"ip_address",
"(",
"ip_str",
")",
"if",
"ip",
".",
"version",
"=... | Verify that an IP address is owned by GitHub. | [
"Verify",
"that",
"an",
"IP",
"address",
"is",
"owned",
"by",
"GitHub",
"."
] | train | https://github.com/nickfrostatx/flask-hookserver/blob/fb5c226473f54e3469234403ec56a354374d2c41/flask_hookserver.py#L163-L175 |
nickfrostatx/flask-hookserver | flask_hookserver.py | check_signature | def check_signature(signature, key, data):
"""Compute the HMAC signature and test against a given hash."""
if isinstance(key, type(u'')):
key = key.encode()
digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest()
# Covert everything to byte sequences
if isinstance(digest, type(u'')):
digest = digest.encode()
if isinstance(signature, type(u'')):
signature = signature.encode()
return werkzeug.security.safe_str_cmp(digest, signature) | python | def check_signature(signature, key, data):
"""Compute the HMAC signature and test against a given hash."""
if isinstance(key, type(u'')):
key = key.encode()
digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest()
# Covert everything to byte sequences
if isinstance(digest, type(u'')):
digest = digest.encode()
if isinstance(signature, type(u'')):
signature = signature.encode()
return werkzeug.security.safe_str_cmp(digest, signature) | [
"def",
"check_signature",
"(",
"signature",
",",
"key",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"type",
"(",
"u''",
")",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
")",
"digest",
"=",
"'sha1='",
"+",
"hmac",
".",
"new",
... | Compute the HMAC signature and test against a given hash. | [
"Compute",
"the",
"HMAC",
"signature",
"and",
"test",
"against",
"a",
"given",
"hash",
"."
] | train | https://github.com/nickfrostatx/flask-hookserver/blob/fb5c226473f54e3469234403ec56a354374d2c41/flask_hookserver.py#L178-L191 |
nickfrostatx/flask-hookserver | flask_hookserver.py | Hooks.init_app | def init_app(self, app, url='/hooks'):
"""Register the URL route to the application.
:param app: the optional :class:`~flask.Flask` instance to
register the extension
:param url: the url that events will be posted to
"""
app.config.setdefault('VALIDATE_IP', True)
app.config.setdefault('VALIDATE_SIGNATURE', True)
@app.route(url, methods=['POST'])
def hook():
if app.config['VALIDATE_IP']:
if not is_github_ip(request.remote_addr):
raise Forbidden('Requests must originate from GitHub')
if app.config['VALIDATE_SIGNATURE']:
key = app.config.get('GITHUB_WEBHOOKS_KEY', app.secret_key)
signature = request.headers.get('X-Hub-Signature')
if hasattr(request, 'get_data'):
# Werkzeug >= 0.9
payload = request.get_data()
else:
payload = request.data
if not signature:
raise BadRequest('Missing signature')
if not check_signature(signature, key, payload):
raise BadRequest('Wrong signature')
event = request.headers.get('X-GitHub-Event')
guid = request.headers.get('X-GitHub-Delivery')
if not event:
raise BadRequest('Missing header: X-GitHub-Event')
elif not guid:
raise BadRequest('Missing header: X-GitHub-Delivery')
if hasattr(request, 'get_json'):
# Flask >= 0.10
data = request.get_json()
else:
data = request.json
if event in self._hooks:
return self._hooks[event](data, guid)
else:
return 'Hook not used\n' | python | def init_app(self, app, url='/hooks'):
"""Register the URL route to the application.
:param app: the optional :class:`~flask.Flask` instance to
register the extension
:param url: the url that events will be posted to
"""
app.config.setdefault('VALIDATE_IP', True)
app.config.setdefault('VALIDATE_SIGNATURE', True)
@app.route(url, methods=['POST'])
def hook():
if app.config['VALIDATE_IP']:
if not is_github_ip(request.remote_addr):
raise Forbidden('Requests must originate from GitHub')
if app.config['VALIDATE_SIGNATURE']:
key = app.config.get('GITHUB_WEBHOOKS_KEY', app.secret_key)
signature = request.headers.get('X-Hub-Signature')
if hasattr(request, 'get_data'):
# Werkzeug >= 0.9
payload = request.get_data()
else:
payload = request.data
if not signature:
raise BadRequest('Missing signature')
if not check_signature(signature, key, payload):
raise BadRequest('Wrong signature')
event = request.headers.get('X-GitHub-Event')
guid = request.headers.get('X-GitHub-Delivery')
if not event:
raise BadRequest('Missing header: X-GitHub-Event')
elif not guid:
raise BadRequest('Missing header: X-GitHub-Delivery')
if hasattr(request, 'get_json'):
# Flask >= 0.10
data = request.get_json()
else:
data = request.json
if event in self._hooks:
return self._hooks[event](data, guid)
else:
return 'Hook not used\n' | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"url",
"=",
"'/hooks'",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'VALIDATE_IP'",
",",
"True",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'VALIDATE_SIGNATURE'",
",",
"True",
")",
... | Register the URL route to the application.
:param app: the optional :class:`~flask.Flask` instance to
register the extension
:param url: the url that events will be posted to | [
"Register",
"the",
"URL",
"route",
"to",
"the",
"application",
"."
] | train | https://github.com/nickfrostatx/flask-hookserver/blob/fb5c226473f54e3469234403ec56a354374d2c41/flask_hookserver.py#L39-L87 |
nickfrostatx/flask-hookserver | flask_hookserver.py | Hooks.register_hook | def register_hook(self, hook_name, fn):
"""Register a function to be called on a GitHub event."""
if hook_name not in self._hooks:
self._hooks[hook_name] = fn
else:
raise Exception('%s hook already registered' % hook_name) | python | def register_hook(self, hook_name, fn):
"""Register a function to be called on a GitHub event."""
if hook_name not in self._hooks:
self._hooks[hook_name] = fn
else:
raise Exception('%s hook already registered' % hook_name) | [
"def",
"register_hook",
"(",
"self",
",",
"hook_name",
",",
"fn",
")",
":",
"if",
"hook_name",
"not",
"in",
"self",
".",
"_hooks",
":",
"self",
".",
"_hooks",
"[",
"hook_name",
"]",
"=",
"fn",
"else",
":",
"raise",
"Exception",
"(",
"'%s hook already reg... | Register a function to be called on a GitHub event. | [
"Register",
"a",
"function",
"to",
"be",
"called",
"on",
"a",
"GitHub",
"event",
"."
] | train | https://github.com/nickfrostatx/flask-hookserver/blob/fb5c226473f54e3469234403ec56a354374d2c41/flask_hookserver.py#L89-L94 |
nickfrostatx/flask-hookserver | flask_hookserver.py | Hooks.hook | def hook(self, hook_name):
"""A decorator that's used to register a new hook handler.
:param hook_name: the event to handle
"""
def wrapper(fn):
self.register_hook(hook_name, fn)
return fn
return wrapper | python | def hook(self, hook_name):
"""A decorator that's used to register a new hook handler.
:param hook_name: the event to handle
"""
def wrapper(fn):
self.register_hook(hook_name, fn)
return fn
return wrapper | [
"def",
"hook",
"(",
"self",
",",
"hook_name",
")",
":",
"def",
"wrapper",
"(",
"fn",
")",
":",
"self",
".",
"register_hook",
"(",
"hook_name",
",",
"fn",
")",
"return",
"fn",
"return",
"wrapper"
] | A decorator that's used to register a new hook handler.
:param hook_name: the event to handle | [
"A",
"decorator",
"that",
"s",
"used",
"to",
"register",
"a",
"new",
"hook",
"handler",
"."
] | train | https://github.com/nickfrostatx/flask-hookserver/blob/fb5c226473f54e3469234403ec56a354374d2c41/flask_hookserver.py#L96-L104 |
taddeus/wspy | websocket.py | websocket.accept | def accept(self):
"""
Equivalent to socket.accept(), but transforms the socket into a
websocket instance and sends a server handshake (after receiving a
client handshake). Note that the handshake may raise a HandshakeError
exception.
"""
sock, address = self.sock.accept()
wsock = websocket(sock)
wsock.secure = self.secure
ServerHandshake(wsock).perform(self)
wsock.handshake_sent = True
return wsock, address | python | def accept(self):
"""
Equivalent to socket.accept(), but transforms the socket into a
websocket instance and sends a server handshake (after receiving a
client handshake). Note that the handshake may raise a HandshakeError
exception.
"""
sock, address = self.sock.accept()
wsock = websocket(sock)
wsock.secure = self.secure
ServerHandshake(wsock).perform(self)
wsock.handshake_sent = True
return wsock, address | [
"def",
"accept",
"(",
"self",
")",
":",
"sock",
",",
"address",
"=",
"self",
".",
"sock",
".",
"accept",
"(",
")",
"wsock",
"=",
"websocket",
"(",
"sock",
")",
"wsock",
".",
"secure",
"=",
"self",
".",
"secure",
"ServerHandshake",
"(",
"wsock",
")",
... | Equivalent to socket.accept(), but transforms the socket into a
websocket instance and sends a server handshake (after receiving a
client handshake). Note that the handshake may raise a HandshakeError
exception. | [
"Equivalent",
"to",
"socket",
".",
"accept",
"()",
"but",
"transforms",
"the",
"socket",
"into",
"a",
"websocket",
"instance",
"and",
"sends",
"a",
"server",
"handshake",
"(",
"after",
"receiving",
"a",
"client",
"handshake",
")",
".",
"Note",
"that",
"the",... | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/websocket.py#L109-L121 |
taddeus/wspy | websocket.py | websocket.connect | def connect(self, address):
"""
Equivalent to socket.connect(), but sends an client handshake request
after connecting.
`address` is a (host, port) tuple of the server to connect to.
"""
self.sock.connect(address)
ClientHandshake(self).perform()
self.handshake_sent = True | python | def connect(self, address):
"""
Equivalent to socket.connect(), but sends an client handshake request
after connecting.
`address` is a (host, port) tuple of the server to connect to.
"""
self.sock.connect(address)
ClientHandshake(self).perform()
self.handshake_sent = True | [
"def",
"connect",
"(",
"self",
",",
"address",
")",
":",
"self",
".",
"sock",
".",
"connect",
"(",
"address",
")",
"ClientHandshake",
"(",
"self",
")",
".",
"perform",
"(",
")",
"self",
".",
"handshake_sent",
"=",
"True"
] | Equivalent to socket.connect(), but sends an client handshake request
after connecting.
`address` is a (host, port) tuple of the server to connect to. | [
"Equivalent",
"to",
"socket",
".",
"connect",
"()",
"but",
"sends",
"an",
"client",
"handshake",
"request",
"after",
"connecting",
"."
] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/websocket.py#L123-L132 |
taddeus/wspy | websocket.py | websocket.send | def send(self, *args):
"""
Send a number of frames.
"""
for frame in args:
self.sock.sendall(self.apply_send_hooks(frame, False).pack()) | python | def send(self, *args):
"""
Send a number of frames.
"""
for frame in args:
self.sock.sendall(self.apply_send_hooks(frame, False).pack()) | [
"def",
"send",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"frame",
"in",
"args",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"self",
".",
"apply_send_hooks",
"(",
"frame",
",",
"False",
")",
".",
"pack",
"(",
")",
")"
] | Send a number of frames. | [
"Send",
"a",
"number",
"of",
"frames",
"."
] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/websocket.py#L148-L153 |
taddeus/wspy | websocket.py | websocket.queue_send | def queue_send(self, frame, callback=None, recv_callback=None):
"""
Enqueue `frame` to the send buffer so that it is send on the next
`do_async_send`. `callback` is an optional callable to call when the
frame has been fully written. `recv_callback` is an optional callable
to quickly set the `recv_callback` attribute to.
"""
frame = self.apply_send_hooks(frame, False)
self.sendbuf += frame.pack()
self.sendbuf_frames.append([frame, len(self.sendbuf), callback])
if recv_callback:
self.recv_callback = recv_callback | python | def queue_send(self, frame, callback=None, recv_callback=None):
"""
Enqueue `frame` to the send buffer so that it is send on the next
`do_async_send`. `callback` is an optional callable to call when the
frame has been fully written. `recv_callback` is an optional callable
to quickly set the `recv_callback` attribute to.
"""
frame = self.apply_send_hooks(frame, False)
self.sendbuf += frame.pack()
self.sendbuf_frames.append([frame, len(self.sendbuf), callback])
if recv_callback:
self.recv_callback = recv_callback | [
"def",
"queue_send",
"(",
"self",
",",
"frame",
",",
"callback",
"=",
"None",
",",
"recv_callback",
"=",
"None",
")",
":",
"frame",
"=",
"self",
".",
"apply_send_hooks",
"(",
"frame",
",",
"False",
")",
"self",
".",
"sendbuf",
"+=",
"frame",
".",
"pack... | Enqueue `frame` to the send buffer so that it is send on the next
`do_async_send`. `callback` is an optional callable to call when the
frame has been fully written. `recv_callback` is an optional callable
to quickly set the `recv_callback` attribute to. | [
"Enqueue",
"frame",
"to",
"the",
"send",
"buffer",
"so",
"that",
"it",
"is",
"send",
"on",
"the",
"next",
"do_async_send",
".",
"callback",
"is",
"an",
"optional",
"callable",
"to",
"call",
"when",
"the",
"frame",
"has",
"been",
"fully",
"written",
".",
... | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/websocket.py#L169-L181 |
taddeus/wspy | websocket.py | websocket.do_async_send | def do_async_send(self):
"""
Send any queued data. This function should only be called after a write
event on a file descriptor.
"""
assert len(self.sendbuf)
nwritten = self.sock.send(self.sendbuf)
nframes = 0
for entry in self.sendbuf_frames:
frame, offset, callback = entry
if offset <= nwritten:
nframes += 1
if callback:
callback()
else:
entry[1] -= nwritten
self.sendbuf = self.sendbuf[nwritten:]
self.sendbuf_frames = self.sendbuf_frames[nframes:] | python | def do_async_send(self):
"""
Send any queued data. This function should only be called after a write
event on a file descriptor.
"""
assert len(self.sendbuf)
nwritten = self.sock.send(self.sendbuf)
nframes = 0
for entry in self.sendbuf_frames:
frame, offset, callback = entry
if offset <= nwritten:
nframes += 1
if callback:
callback()
else:
entry[1] -= nwritten
self.sendbuf = self.sendbuf[nwritten:]
self.sendbuf_frames = self.sendbuf_frames[nframes:] | [
"def",
"do_async_send",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"sendbuf",
")",
"nwritten",
"=",
"self",
".",
"sock",
".",
"send",
"(",
"self",
".",
"sendbuf",
")",
"nframes",
"=",
"0",
"for",
"entry",
"in",
"self",
".",
"sendbuf_fr... | Send any queued data. This function should only be called after a write
event on a file descriptor. | [
"Send",
"any",
"queued",
"data",
".",
"This",
"function",
"should",
"only",
"be",
"called",
"after",
"a",
"write",
"event",
"on",
"a",
"file",
"descriptor",
"."
] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/websocket.py#L183-L205 |
taddeus/wspy | websocket.py | websocket.do_async_recv | def do_async_recv(self, bufsize):
"""
Receive any completed frames from the socket. This function should only
be called after a read event on a file descriptor.
"""
data = self.sock.recv(bufsize)
if len(data) == 0:
raise socket.error('no data to receive')
self.recvbuf += data
while contains_frame(self.recvbuf):
frame, self.recvbuf = pop_frame(self.recvbuf)
frame = self.apply_recv_hooks(frame, False)
if not self.recv_callback:
raise ValueError('no callback installed for %s' % frame)
self.recv_callback(frame) | python | def do_async_recv(self, bufsize):
"""
Receive any completed frames from the socket. This function should only
be called after a read event on a file descriptor.
"""
data = self.sock.recv(bufsize)
if len(data) == 0:
raise socket.error('no data to receive')
self.recvbuf += data
while contains_frame(self.recvbuf):
frame, self.recvbuf = pop_frame(self.recvbuf)
frame = self.apply_recv_hooks(frame, False)
if not self.recv_callback:
raise ValueError('no callback installed for %s' % frame)
self.recv_callback(frame) | [
"def",
"do_async_recv",
"(",
"self",
",",
"bufsize",
")",
":",
"data",
"=",
"self",
".",
"sock",
".",
"recv",
"(",
"bufsize",
")",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"raise",
"socket",
".",
"error",
"(",
"'no data to receive'",
")",
"self... | Receive any completed frames from the socket. This function should only
be called after a read event on a file descriptor. | [
"Receive",
"any",
"completed",
"frames",
"from",
"the",
"socket",
".",
"This",
"function",
"should",
"only",
"be",
"called",
"after",
"a",
"read",
"event",
"on",
"a",
"file",
"descriptor",
"."
] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/websocket.py#L207-L226 |
taddeus/wspy | websocket.py | websocket.enable_ssl | def enable_ssl(self, *args, **kwargs):
"""
Transforms the regular socket.socket to an ssl.SSLSocket for secure
connections. Any arguments are passed to ssl.wrap_socket:
http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket
"""
if self.handshake_sent:
raise SSLError('can only enable SSL before handshake')
self.secure = True
self.sock = ssl.wrap_socket(self.sock, *args, **kwargs) | python | def enable_ssl(self, *args, **kwargs):
"""
Transforms the regular socket.socket to an ssl.SSLSocket for secure
connections. Any arguments are passed to ssl.wrap_socket:
http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket
"""
if self.handshake_sent:
raise SSLError('can only enable SSL before handshake')
self.secure = True
self.sock = ssl.wrap_socket(self.sock, *args, **kwargs) | [
"def",
"enable_ssl",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"handshake_sent",
":",
"raise",
"SSLError",
"(",
"'can only enable SSL before handshake'",
")",
"self",
".",
"secure",
"=",
"True",
"self",
".",
"sock... | Transforms the regular socket.socket to an ssl.SSLSocket for secure
connections. Any arguments are passed to ssl.wrap_socket:
http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket | [
"Transforms",
"the",
"regular",
"socket",
".",
"socket",
"to",
"an",
"ssl",
".",
"SSLSocket",
"for",
"secure",
"connections",
".",
"Any",
"arguments",
"are",
"passed",
"to",
"ssl",
".",
"wrap_socket",
":",
"http",
":",
"//",
"docs",
".",
"python",
".",
"... | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/websocket.py#L234-L244 |
taddeus/wspy | python_digest.py | validate_nonce | def validate_nonce(nonce, secret):
'''
Is the nonce one that was generated by this library using the provided secret?
'''
nonce_components = nonce.split(':', 2)
if not len(nonce_components) == 3:
return False
timestamp = nonce_components[0]
salt = nonce_components[1]
nonce_signature = nonce_components[2]
calculated_nonce = calculate_nonce(timestamp, secret, salt)
if not nonce == calculated_nonce:
return False
return True | python | def validate_nonce(nonce, secret):
'''
Is the nonce one that was generated by this library using the provided secret?
'''
nonce_components = nonce.split(':', 2)
if not len(nonce_components) == 3:
return False
timestamp = nonce_components[0]
salt = nonce_components[1]
nonce_signature = nonce_components[2]
calculated_nonce = calculate_nonce(timestamp, secret, salt)
if not nonce == calculated_nonce:
return False
return True | [
"def",
"validate_nonce",
"(",
"nonce",
",",
"secret",
")",
":",
"nonce_components",
"=",
"nonce",
".",
"split",
"(",
"':'",
",",
"2",
")",
"if",
"not",
"len",
"(",
"nonce_components",
")",
"==",
"3",
":",
"return",
"False",
"timestamp",
"=",
"nonce_compo... | Is the nonce one that was generated by this library using the provided secret? | [
"Is",
"the",
"nonce",
"one",
"that",
"was",
"generated",
"by",
"this",
"library",
"using",
"the",
"provided",
"secret?"
] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/python_digest.py#L298-L314 |
taddeus/wspy | python_digest.py | calculate_partial_digest | def calculate_partial_digest(username, realm, password):
'''
Calculate a partial digest that may be stored and used to authenticate future
HTTP Digest sessions.
'''
return md5.md5("%s:%s:%s" % (username.encode('utf-8'), realm, password.encode('utf-8'))).hexdigest() | python | def calculate_partial_digest(username, realm, password):
'''
Calculate a partial digest that may be stored and used to authenticate future
HTTP Digest sessions.
'''
return md5.md5("%s:%s:%s" % (username.encode('utf-8'), realm, password.encode('utf-8'))).hexdigest() | [
"def",
"calculate_partial_digest",
"(",
"username",
",",
"realm",
",",
"password",
")",
":",
"return",
"md5",
".",
"md5",
"(",
"\"%s:%s:%s\"",
"%",
"(",
"username",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"realm",
",",
"password",
".",
"encode",
"(",
"'... | Calculate a partial digest that may be stored and used to authenticate future
HTTP Digest sessions. | [
"Calculate",
"a",
"partial",
"digest",
"that",
"may",
"be",
"stored",
"and",
"used",
"to",
"authenticate",
"future",
"HTTP",
"Digest",
"sessions",
"."
] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/python_digest.py#L316-L321 |
taddeus/wspy | python_digest.py | build_digest_challenge | def build_digest_challenge(timestamp, secret, realm, opaque, stale):
'''
Builds a Digest challenge that may be sent as the value of the 'WWW-Authenticate' header
in a 401 or 403 response.
'opaque' may be any value - it will be returned by the client.
'timestamp' will be incorporated and signed in the nonce - it may be retrieved from the
client's authentication request using get_nonce_timestamp()
'''
nonce = calculate_nonce(timestamp, secret)
return 'Digest %s' % format_parts(realm=realm, qop='auth', nonce=nonce,
opaque=opaque, algorithm='MD5',
stale=stale and 'true' or 'false') | python | def build_digest_challenge(timestamp, secret, realm, opaque, stale):
'''
Builds a Digest challenge that may be sent as the value of the 'WWW-Authenticate' header
in a 401 or 403 response.
'opaque' may be any value - it will be returned by the client.
'timestamp' will be incorporated and signed in the nonce - it may be retrieved from the
client's authentication request using get_nonce_timestamp()
'''
nonce = calculate_nonce(timestamp, secret)
return 'Digest %s' % format_parts(realm=realm, qop='auth', nonce=nonce,
opaque=opaque, algorithm='MD5',
stale=stale and 'true' or 'false') | [
"def",
"build_digest_challenge",
"(",
"timestamp",
",",
"secret",
",",
"realm",
",",
"opaque",
",",
"stale",
")",
":",
"nonce",
"=",
"calculate_nonce",
"(",
"timestamp",
",",
"secret",
")",
"return",
"'Digest %s'",
"%",
"format_parts",
"(",
"realm",
"=",
"re... | Builds a Digest challenge that may be sent as the value of the 'WWW-Authenticate' header
in a 401 or 403 response.
'opaque' may be any value - it will be returned by the client.
'timestamp' will be incorporated and signed in the nonce - it may be retrieved from the
client's authentication request using get_nonce_timestamp() | [
"Builds",
"a",
"Digest",
"challenge",
"that",
"may",
"be",
"sent",
"as",
"the",
"value",
"of",
"the",
"WWW",
"-",
"Authenticate",
"header",
"in",
"a",
"401",
"or",
"403",
"response",
"."
] | train | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/python_digest.py#L323-L337 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.