text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_shakes(self):
""" Get a list of Shake objects for the currently authenticated user. Returns: A list of Shake objects. """ |
endpoint = '/api/shakes'
data = self._make_request(verb="GET", endpoint=endpoint)
shakes = [Shake.NewFromJSON(shk) for shk in data['shakes']]
return shakes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_shared_files_from_shake(self, shake_id=None, before=None, after=None):
""" Returns a list of SharedFile objects from a particular shake. Args: shake_id (int):
Shake from which to get a list of SharedFiles before (str):
get 10 SharedFile objects before (but not including) the SharedFile given by `before` for the given Shake. after (str):
get 10 SharedFile objects after (but not including) the SharedFile give by `after' for the given Shake. Returns: List (list) of SharedFiles. """ |
if before and after:
raise Exception("You cannot specify both before and after keys")
endpoint = '/api/shakes'
if shake_id:
endpoint += '/{0}'.format(shake_id)
if before:
endpoint += '/before/{0}'.format(before)
elif after:
endpoint += '/after/{0}'.format(after)
data = self._make_request(verb="GET", endpoint=endpoint)
return [SharedFile.NewFromJSON(f) for f in data['sharedfiles']] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_shared_file(self, sharekey=None):
""" Returns a SharedFile object given by the sharekey. Args: sharekey (str):
Sharekey of the SharedFile you want to retrieve. Returns: SharedFile """ |
if not sharekey:
raise Exception("You must specify a sharekey.")
endpoint = '/api/sharedfile/{0}'.format(sharekey)
data = self._make_request('GET', endpoint)
return SharedFile.NewFromJSON(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def like_shared_file(self, sharekey=None):
""" 'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (str):
Sharekey for the file you want to 'like'. Returns: Either a SharedFile on success, or an exception on error. """ |
if not sharekey:
raise Exception(
"You must specify a sharekey of the file you"
"want to 'like'.")
endpoint = '/api/sharedfile/{sharekey}/like'.format(sharekey=sharekey)
data = self._make_request("POST", endpoint=endpoint, data=None)
try:
sf = SharedFile.NewFromJSON(data)
sf.liked = True
return sf
except:
raise Exception("{0}".format(data['error'])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_shared_file(self, sharekey=None):
""" Save a SharedFile to your Shake. Args: sharekey (str):
Sharekey for the file to save. Returns: SharedFile saved to your shake. """ |
endpoint = '/api/sharedfile/{sharekey}/save'.format(sharekey=sharekey)
data = self._make_request("POST", endpoint=endpoint, data=None)
try:
sf = SharedFile.NewFromJSON(data)
sf.saved = True
return sf
except:
raise Exception("{0}".format(data['error'])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_friends_shake(self, before=None, after=None):
""" Contrary to the endpoint naming, this resource is for a list of SharedFiles from your friends on mlkshk. Returns: List of SharedFiles. """ |
if before and after:
raise Exception("You cannot specify both before and after keys")
endpoint = '/api/friends'
if before:
endpoint += '/before/{0}'.format(before)
elif after:
endpoint += '/after/{0}'.format(after)
data = self._make_request("GET", endpoint=endpoint)
return [SharedFile.NewFromJSON(sf) for sf in data['friend_shake']] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_comments(self, sharekey=None):
""" Retrieve comments on a SharedFile Args: sharekey (str):
Sharekey for the file from which you want to return the set of comments. Returns: List of Comment objects. """ |
if not sharekey:
raise Exception(
"You must specify a sharekey of the file you"
"want to 'like'.")
endpoint = '/api/sharedfile/{0}/comments'.format(sharekey)
data = self._make_request("GET", endpoint=endpoint)
return [Comment.NewFromJSON(c) for c in data['comments']] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_comment(self, sharekey=None, comment=None):
""" Post a comment on behalf of the current user to the SharedFile with the given sharekey. Args: sharekey (str):
Sharekey of the SharedFile to which you'd like to post a comment. comment (str):
Text of the comment to post. Returns: Comment object. """ |
endpoint = '/api/sharedfile/{0}/comments'.format(sharekey)
post_data = {'body': comment}
data = self._make_request("POST", endpoint=endpoint, data=post_data)
return Comment.NewFromJSON(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_shared_file(self, image_file=None, source_link=None, shake_id=None, title=None, description=None):
""" Upload an image. TODO: Don't have a pro account to test (or even write) code to upload a shared filed to a particular shake. Args: image_file (str):
path to an image (jpg/gif) on your computer. source_link (str):
URL of a source (youtube/vine/etc.) shake_id (int):
shake to which to upload the file or source_link [optional] title (str):
title of the SharedFile [optional] description (str):
description of the SharedFile Returns: SharedFile key. """ |
if image_file and source_link:
raise Exception('You can only specify an image file or '
'a source link, not both.')
if not image_file and not source_link:
raise Exception('You must specify an image file or a source link')
content_type = self._get_image_type(image_file)
if not title:
title = os.path.basename(image_file)
f = open(image_file, 'rb')
endpoint = '/api/upload'
files = {'file': (title, f, content_type)}
data = self._make_request('POST', endpoint=endpoint, files=files)
f.close()
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_edge(self, u, v, **attr):
"""
Add an edge between vertices u and v and update edge attributes
""" |
if u not in self.vertices:
self.vertices[u] = []
if v not in self.vertices:
self.vertices[v] = []
vertex = (u, v)
self.edges[vertex] = {}
if attr:
self.edges[vertex].update(attr)
self.vertices[u].append(v)
self.vertices[v].append(u) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_edge(self, u, v):
"""
Remove the edge between vertices u and v
""" |
try:
self.edges.pop((u, v))
except KeyError:
raise GraphInsertError("Edge %s-%s doesn't exist." % (u, v))
self.vertices[u].remove(v)
self.vertices[v].remove(u) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def degree(self, vertex):
"""
Return the degree of a vertex
""" |
try:
return len(self.vertices[vertex])
except KeyError:
raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli_certify_core_integer( config, min_value, max_value, value, ):
"""Console script for certify_int""" |
def parser(v):
# Attempt a json/pickle decode:
try:
v = load_json_pickle(v, config)
except Exception:
pass
# Attempt a straight conversion to integer:
try:
return int(v)
except Exception as err:
six.raise_from(
CertifierTypeError(
message='Not integer: {x}'.format(
x=v,
),
value=v,
),
err,
)
execute_cli_command(
'integer',
config,
parser,
certify_int,
value[0] if value else None,
min_value=min_value,
max_value=max_value,
required=config['required'],
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _warn_dupkey(self, k):
""" Really odd function - used to help ensure we actually warn for duplicate keys. """ |
if self._privflags & PYCBC_CONN_F_WARNEXPLICIT:
warnings.warn_explicit(
'Found duplicate keys! {0}'.format(k), RuntimeWarning,
__file__, -1, module='couchbase_ffi.bucket', registry={})
else:
warnings.warn('Found duplicate keys!', RuntimeWarning) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_text(self, xml, name):
""" Gets the element's text value from the XML object provided. """ |
nodes = xml.getElementsByTagName("wp:comment_" + name)[0].childNodes
accepted_types = [Node.CDATA_SECTION_NODE, Node.TEXT_NODE]
return "".join([n.data for n in nodes if n.nodeType in accepted_types]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_import(self, options):
""" Gets the posts from either the provided URL or the path if it is local. """ |
url = options.get("url")
if url is None:
raise CommandError("Usage is import_wordpress %s" % self.args)
try:
import feedparser
except ImportError:
raise CommandError("Could not import the feedparser library.")
feed = feedparser.parse(url)
# We use the minidom parser as well because feedparser won't
# interpret WXR comments correctly and ends up munging them.
# xml.dom.minidom is used simply to pull the comments when we
# get to them.
xml = parse(url)
xmlitems = xml.getElementsByTagName("item")
for (i, entry) in enumerate(feed["entries"]):
# Get a pointer to the right position in the minidom as well.
xmlitem = xmlitems[i]
content = linebreaks(self.wp_caption(entry.content[0]["value"]))
# Get the time struct of the published date if possible and
# the updated date if we can't.
pub_date = getattr(entry, "published_parsed", entry.updated_parsed)
if pub_date:
pub_date = datetime.fromtimestamp(mktime(pub_date))
pub_date -= timedelta(seconds=timezone)
# Tags and categories are all under "tags" marked with a scheme.
terms = defaultdict(set)
for item in getattr(entry, "tags", []):
terms[item.scheme].add(item.term)
if entry.wp_post_type == "post":
post = self.add_post(title=entry.title, content=content,
pub_date=pub_date, tags=terms["tag"],
categories=terms["category"],
old_url=entry.id)
# Get the comments from the xml doc.
for c in xmlitem.getElementsByTagName("wp:comment"):
name = self.get_text(c, "author")
email = self.get_text(c, "author_email")
url = self.get_text(c, "author_url")
body = self.get_text(c, "content")
pub_date = self.get_text(c, "date_gmt")
fmt = "%Y-%m-%d %H:%M:%S"
pub_date = datetime.strptime(pub_date, fmt)
pub_date -= timedelta(seconds=timezone)
self.add_comment(post=post, name=name, email=email,
body=body, website=url,
pub_date=pub_date)
elif entry.wp_post_type == "page":
old_id = getattr(entry, "wp_post_id")
parent_id = getattr(entry, "wp_post_parent")
self.add_page(title=entry.title, content=content,
tags=terms["tag"], old_id=old_id,
old_parent_id=parent_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wp_caption(self, post):
""" Filters a Wordpress Post for Image Captions and renders to match HTML. """ |
for match in re.finditer(r"\[caption (.*?)\](.*?)\[/caption\]", post):
meta = '<div '
caption = ''
for imatch in re.finditer(r'(\w+)="(.*?)"', match.group(1)):
if imatch.group(1) == 'id':
meta += 'id="%s" ' % imatch.group(2)
if imatch.group(1) == 'align':
meta += 'class="wp-caption %s" ' % imatch.group(2)
if imatch.group(1) == 'width':
width = int(imatch.group(2)) + 10
meta += 'style="width: %spx;" ' % width
if imatch.group(1) == 'caption':
caption = imatch.group(2)
parts = (match.group(2), caption)
meta += '>%s<p class="wp-caption-text">%s</p></div>' % parts
post = post.replace(match.group(0), meta)
return post |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_emote_mappings(json_obj_files=[]):
""" Reads the contents of a list of files of json objects and combines them into one large json object. """ |
super_json = {}
for fname in json_obj_files:
with open(fname) as f:
super_json.update(json.loads(f.read().decode('utf-8')))
return super_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tls_property(default=None):
"""Creates a class-wide instance property with a thread-specific value.""" |
class TLSProperty(object):
def __init__(self):
from threading import local
self.local = local()
def __get__(self, instance, cls):
if not instance:
return self
return self.value
def __set__(self, instance, value):
self.value = value
def _get_value(self):
return getattr(self.local, 'value', default)
def _set_value(self, value):
self.local.value = value
value = property(_get_value, _set_value)
return TLSProperty() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup(self):
""" The meat of this middleware. Returns None and sets settings.SITE_ID if able to find a Site object by domain and its subdomain is valid. Returns an HttpResponsePermanentRedirect to the Site's default subdomain if a site is found but the requested subdomain is not supported, or if domain_unsplit is defined in settings.HOSTNAME_REDIRECTS Otherwise, returns False. """ |
# check to see if this hostname is actually a env hostname
if self.domain:
if self.subdomain:
self.domain_unsplit = '%s.%s' % (self.subdomain, self.domain)
else:
self.domain_unsplit = self.domain
self.domain_requested = self.domain_unsplit
# check cache
cache_key = 'site_id:%s' % self.domain_unsplit
site_id = cache.get(cache_key)
if site_id:
SITE_ID.value = site_id
try:
self.site = Site.objects.get(id=site_id)
except Site.DoesNotExist:
# This might happen if the Site object was deleted from the
# database after it was cached. Remove from cache and act
# as if the cache lookup failed.
cache.delete(cache_key)
else:
return None
# check database
try:
self.site = Site.objects.get(domain=self.domain)
except Site.DoesNotExist:
return False
if not self.site:
return False
SITE_ID.value = self.site.pk
cache.set(cache_key, SITE_ID.value, 5*60)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def theme_lookup(self):
""" Returns theme based on site Returns None and sets settings.THEME if able to find a theme object by site. Otherwise, returns False. """ |
# check cache
cache_key = 'theme:%s' % self.domain_unsplit
theme = cache.get(cache_key)
if theme:
THEME.value = theme
return None
# check database
if hasattr(self.site, 'themes'):
try:
themes = [theme.name for theme in self.site.themes.all()]
THEME.value = themes[0]
cache.set(cache_key, THEME.value, 5*60)
except:
return False
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def age(self, as_at_date=None):
""" Compute the person's age """ |
if self.date_of_death != None or self.is_deceased == True:
return None
as_at_date = date.today() if as_at_date == None else as_at_date
if self.date_of_birth != None:
if (as_at_date.month >= self.date_of_birth.month) and (as_at_date.day >= self.date_of_birth.day):
return (as_at_date.year - self.date_of_birth.year)
else:
return ((as_at_date.year - self.date_of_birth.year) -1)
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self):
""" Return the person's name. If we have special titles, use them, otherwise, don't include the title. """ |
if self.title in ["DR", "SIR", "LORD"]:
return "%s %s %s" % (self.get_title_display(), self.first_name, self.last_name)
else:
return "%s %s" % (self.first_name, self.last_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def full_name(self):
""" Return the title and full name """ |
return "%s %s %s %s" % (self.get_title_display(),
self.first_name,
self.other_names.replace(",", ""),
self.last_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, *args, **kwargs):
""" If date of death is specified, set is_deceased to true """ |
if self.date_of_death != None:
self.is_deceased = True
# Since we often copy and paste names from strange sources, do some basic cleanup
self.first_name = self.first_name.strip()
self.last_name = self.last_name.strip()
self.other_names = self.other_names.strip()
# Call save method
super(Person, self).save(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def storedata(filename=None):
"""Store the state of the current credolib workspace in a pickle file.""" |
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'wb') as f:
d = {}
for var in ['_headers', '_loaders', '_data1d', '_data2d', '_data1dunited',
'allsamplenames', '_headers_sample', 'badfsns', '_rowavg',
'saveto_dir',
'badfsns_datcmp', 'auximages_dir', 'subtractedsamplenames', 'outputpath', 'saveto_dir_rel',
'auximages_dir_rel', 'crd_prefix']:
try:
d[var] = ns[var]
except KeyError:
warnings.warn('Skipping storage of unavailable variable "%s"' % var)
pickle.dump(d, f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restoredata(filename=None):
"""Restore the state of the credolib workspace from a pickle file.""" |
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'rb') as f:
d = pickle.load(f)
for k in d.keys():
ns[k] = d[k] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocorrect(query, possibilities, delta=0.75):
"""Attempts to figure out what possibility the query is This autocorrect function is rather simple right now with plans for later improvement. Right now, it just attempts to finish spelling a word as much as possible, and then determines which possibility is closest to said word. Args: query (unicode):
query to attempt to complete possibilities (list):
list of unicodes of possible answers for query delta (float):
Minimum delta similarity between query and any given possibility for possibility to be considered. Delta used by difflib.get_close_matches(). Returns: unicode: best guess of correct answer Raises: AssertionError: raised if no matches found Example: .. code-block:: Python 'bowtie2' """ |
# TODO: Make this way more robust and awesome using probability, n-grams?
possibilities = [possibility.lower() for possibility in possibilities]
# Don't waste time for exact matches
if query in possibilities:
return query
# Complete query as much as possible
options = [word for word in possibilities if word.startswith(query)]
if len(options) > 0:
possibilities = options
query = max_substring(options)
# Identify possible matches and return best match
matches = get_close_matches(query, possibilities, cutoff=delta)
# Raise error if no matches
try:
assert len(matches) > 0
except AssertionError:
raise AssertionError('No matches for "{0}" found'.format(query))
return matches[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self, overwrite):
"""Generate service files. This exposes several comforts. `self.files` is a list into which all generated file paths will be appended. It is later returned by `generate` to be consumed by any program that wants to do something with it. `self.templates` is the directory in which all templates are stored. New init system implementations can use this to easily pull template files. `self.template_prefix` is a prefix for all template files. Since all template files should be named `<INIT_SYS_NAME>*`, this will basically just provide the prefix before the * for you to use. `self.generate_into_prefix` is a prefix for the path into which files will be generated. This is NOT the destination path for the file when deploying the service. `self.overwrite` automatically deals with overwriting files so that the developer doesn't have to address this. It is provided by the API or by the CLI and propagated. """ |
self.files = []
tmp = utils.get_tmp_dir(self.init_system, self.name)
self.templates = os.path.join(os.path.dirname(__file__), 'templates')
self.template_prefix = self.init_system
self.generate_into_prefix = os.path.join(tmp, self.name)
self.overwrite = overwrite |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self, **kwargs):
"""Retrieve the status of a service `name` or all services for the current init system. """ |
self.services = dict(
init_system=self.init_system,
services=[]
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_file_from_template(self, template, destination):
"""Generate a file from a Jinja2 `template` and writes it to `destination` using `params`. `overwrite` allows to overwrite existing files. It is passed to the `generate` method. This is used by the different init implementations to generate init scripts/configs and deploy them to the relevant directories. Templates are looked up under init/templates/`template`. If the `destination` directory doesn't exist, it will alert the user and exit. We don't want to be creating any system related directories out of the blue. The exception to the rule is with nssm. While it may seem a bit weird, not all relevant directories exist out of the box. For instance, `/etc/sysconfig` doesn't necessarily exist even if systemd is used by default. """ |
# We cast the object to a string before passing it on as py3.x
# will fail on Jinja2 if there are ints/bytes (not strings) in the
# template which will not allow `env.from_string(template)` to
# take place.
templates = str(pkgutil.get_data(__name__, os.path.join(
'templates', template)))
pretty_params = json.dumps(self.params, indent=4, sort_keys=True)
self.logger.debug(
'Rendering %s with params: %s...', template, pretty_params)
generated = jinja2.Environment().from_string(
templates).render(self.params)
self.logger.debug('Writing generated file to %s...', destination)
self._should_overwrite(destination)
with open(destination, 'w') as f:
f.write(generated)
self.files.append(destination) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_value_to_es(value, ranges, obj, method=None):
""" Takes an value and converts it to an elasticsearch representation args: value: the value to convert ranges: the list of ranges method: convertion method to use 'None': default -> converts the value to its json value 'missing_obj': adds attributes as if the value should have been a rdfclass object """ |
def sub_convert(val):
"""
Returns the json value for a simple datatype or the subject uri if the
value is a rdfclass
args:
val: the value to convert
"""
if isinstance(val, BaseRdfDataType):
return val.to_json
elif isinstance(value, __MODULE__.rdfclass.RdfClassBase):
return val.subject.sparql_uri
return val
if method == "missing_obj":
rtn_obj = {
"rdf_type": [rng.sparql_uri for rng in ranges], # pylint: disable=no-member
"label": [getattr(obj, label)[0] \
for label in LABEL_FIELDS \
if hasattr(obj, label)][0]}
try:
rtn_obj['uri'] = value.sparql_uri
rtn_obj["rdfs_label"] = NSM.nouri(value.sparql_uri)
except AttributeError:
rtn_obj['uri'] = "None Specified"
rtn_obj['rdfs_label'] = sub_convert(value)
rtn_obj['value'] = rtn_obj['rdfs_label']
return rtn_obj
return sub_convert(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_idx_types(rng_def, ranges):
""" Returns the elasticsearch index types for the obj args: rng_def: the range defintion dictionay ranges: rdfproperty ranges """ |
idx_types = rng_def.get('kds_esIndexType', []).copy()
if not idx_types:
nested = False
for rng in ranges:
if range_is_obj(rng, __MODULE__.rdfclass):
nested = True
if nested:
idx_types.append('es_Nested')
return idx_types |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_prop_range_defs(class_names, def_list):
""" Filters the range defitions based on the bound class args: obj: the rdffroperty instance """ |
try:
cls_options = set(class_names + ['kdr_AllClasses'])
return [rng_def for rng_def in def_list \
if not isinstance(rng_def, BlankNode) \
and cls_options.difference(\
set(rng_def.get('kds_appliesToClass', []))) < \
cls_options]
except AttributeError:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range_is_obj(rng, rdfclass):
""" Test to see if range for the class should be an object or a litteral """ |
if rng == 'rdfs_Literal':
return False
if hasattr(rdfclass, rng):
mod_class = getattr(rdfclass, rng)
for item in mod_class.cls_defs['rdf_type']:
try:
if issubclass(getattr(rdfclass, item),
rdfclass.rdfs_Literal):
return False
except AttributeError:
pass
if isinstance(mod_class, rdfclass.RdfClassMeta):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_es_value(obj, def_obj):
""" Returns the value for an object that goes into the elacticsearch 'value' field args: obj: data object to update def_obj: the class instance that has defintion values """ |
def get_dict_val(item):
"""
Returns the string representation of the dict item
"""
if isinstance(item, dict):
return str(item.get('value'))
return str(item)
value_flds = []
if def_obj.es_defs.get('kds_esValue'):
value_flds = def_obj.es_defs['kds_esValue'].copy()
else:
# pdb.set_trace()
value_flds = set(obj).difference(__ALL_IGN__)
value_flds = list(value_flds)
value_flds += __COMBINED__
try:
obj['value'] = [obj.get(label) for label in value_flds
if obj.get(label)][0]
except IndexError:
obj['value'] = ", ".join(["%s: %s" % (value.get('label'),
value.get('value'))
for prop, value in obj.items()
if isinstance(value, dict) and \
value.get('label')])
if isinstance(obj['value'], list):
obj['value'] = ", ".join([get_dict_val(item) for item in obj['value']])
else:
obj['value'] = get_dict_val(obj['value'])
if str(obj['value']).strip().endswith("/"):
obj['value'] = str(obj['value']).strip()[:-1].strip()
if not obj['value']:
obj['value'] = obj.get('uri', '')
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_es_label(obj, def_obj):
""" Returns object with label for an object that goes into the elacticsearch 'label' field args: obj: data object to update def_obj: the class instance that has defintion values """ |
label_flds = LABEL_FIELDS
if def_obj.es_defs.get('kds_esLabel'):
label_flds = def_obj.es_defs['kds_esLabel'] + LABEL_FIELDS
try:
for label in label_flds:
if def_obj.cls_defs.get(label):
obj['label'] = def_obj.cls_defs[label][0]
break
if not obj.get('label'):
obj['label'] = def_obj.__class__.__name__.split("_")[-1]
except AttributeError:
# an attribute error is caused when the class is only
# an instance of the BaseRdfClass. We will search the rdf_type
# property and construct a label from rdf_type value
if def_obj.get('rdf_type'):
obj['label'] = def_obj['rdf_type'][-1].value[-1]
else:
obj['label'] = "no_label"
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_es_ids(obj, def_obj):
""" Returns the object updated with the 'id' and 'uri' fields for the elasticsearch document args: obj: data object to update def_obj: the class instance that has defintion values """ |
try:
path = ""
for base in [def_obj.__class__] + list(def_obj.__class__.__bases__):
if hasattr(base, 'es_defs') and base.es_defs:
path = "%s/%s/" % (base.es_defs['kds_esIndex'][0],
base.es_defs['kds_esDocType'][0])
continue
except KeyError:
path = ""
if def_obj.subject.type == 'uri':
obj['uri'] = def_obj.subject.clean_uri
obj['id'] = path + make_es_id(obj['uri'])
elif def_obj.subject.type == 'bnode':
obj['id'] = path + def_obj.bnode_id()
else:
obj['id'] = path + make_es_id(str(obj['value']))
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_es_id(uri):
""" Creates the id based off of the uri value Args: ----- uri: the uri to conver to an elasticsearch id """ |
try:
uri = uri.clean_uri
except AttributeError:
pass
return sha1(uri.encode()).hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gp_norm(infile):
"""indentify normalization region""" |
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.path.realpath(os.path.join(
inDir, 'rawdata', energy, 'pt-integrated', infile+'.dat'
))
data_import = np.loadtxt(open(file_url, 'rb'))
data_import[:,1] += eidx * 0.2
data_import[:,4] = data_import[:,3]
data_import[:,(2,3)] = 0
data.append(data_import)
titles.append(' '.join([getEnergy4Key(energy), 'GeV']))
nData = len(data)
lines = dict(
('x={}'.format(1+i*0.2), 'lc {} lt 2 lw 4'.format(default_colors[-2]))
for i in range(nData)
)
lines.update(dict(
('x={}'.format(1+i*0.2+0.02), 'lc {} lt 3 lw 4'.format(default_colors[-5]))
for i in range(nData)
))
lines.update(dict(
('x={}'.format(1+i*0.2-0.02), 'lc {} lt 3 lw 4'.format(default_colors[-5]))
for i in range(nData)
))
lines.update({'y=0.9': 'lc {} lt 1 lw 4'.format(default_colors[-2])})
charges = '++' if infile == 'rpp' else '--'
make_plot(
name = '%s/norm_range_%s' % (outDir,infile), xr = [0,2], yr = [0.9,1.7],
data = data, properties = [
'lt 1 lw 3 lc %s pt 1' % (default_colors[i]) # (i/2)%4
for i in range(nData)
], titles = titles, size = '8in,8in',
lmargin = 0.05, rmargin = 0.99, tmargin = 0.93, bmargin = 0.14,
xlabel = 'dielectron invariant mass, M_{ee} (GeV/c^{2})',
lines = lines, key = [
'maxrows 1', 'nobox', 'samplen 0.1', 'width -1', 'at graph 1,1.1'
], labels = {
'SE_{%s} / ME@_{%s}^N' % (charges, charges): (0.3, 1.3)
}, gpcalls = [
'ytics (1,"1" 1.2, "1" 1.4, "1" 1.6)', 'boxwidth 0.002',
],
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version():
""" Get the version from the source, but without importing. """ |
with open('sj.py') as source:
for node in ast.walk(ast.parse(source.read(), 'sj.py')):
if node.__class__.__name__ == 'Assign' and \
node.targets[0].__class__.__name__ == 'Name' and \
node.targets[0].id == '__version__':
return node.value.s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_field(self, setting, field_class, name, code=None):
""" Initialize a field whether it is built with a custom name for a specific translation language or not. """ |
kwargs = {
"label": setting["label"] + ":",
"required": setting["type"] in (int, float),
"initial": getattr(settings, name),
"help_text": self.format_help(setting["description"]),
}
if setting["choices"]:
field_class = forms.ChoiceField
kwargs["choices"] = setting["choices"]
field_instance = field_class(**kwargs)
code_name = ('_modeltranslation_' + code if code else '')
self.fields[name + code_name] = field_instance
css_class = field_class.__name__.lower()
field_instance.widget.attrs["class"] = css_class
if code:
field_instance.widget.attrs["class"] += " modeltranslation" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Save each of the settings to the DB. """ |
active_language = get_language()
for (name, value) in self.cleaned_data.items():
if name not in registry:
name, code = name.rsplit('_modeltranslation_', 1)
else:
code = None
setting_obj, created = Setting.objects.get_or_create(name=name)
if settings.USE_MODELTRANSLATION:
if registry[name]["translatable"]:
try:
activate(code)
except:
pass
finally:
setting_obj.value = value
activate(active_language)
else:
# Duplicate the value of the setting for every language
for code in OrderedDict(settings.LANGUAGES):
setattr(setting_obj,
build_localized_fieldname('value', code),
value)
else:
setting_obj.value = value
setting_obj.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_help(self, description):
""" Format the setting's description into HTML. """ |
for bold in ("``", "*"):
parts = []
if description is None:
description = ""
for i, s in enumerate(description.split(bold)):
parts.append(s if i % 2 == 0 else "<b>%s</b>" % s)
description = "".join(parts)
description = urlize(description, autoescape=False)
return mark_safe(description.replace("\n", "<br>")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bestfit_func(self, bestfit_x):
""" Returns bestfit_y value args: bestfit_x: scalar, array_like x value return: scalar, array_like bestfit y value """ |
bestfit_x = np.array(bestfit_x)
if not self.done_bestfit:
raise KeyError("Do do_bestfit first")
bestfit_y = 0
for idx, val in enumerate(self.fit_args):
bestfit_y += val * (bestfit_x **
(self.args.get("degree", 1) - idx))
return bestfit_y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(request, template="accounts/account_login.html", form_class=LoginForm, extra_context=None):
""" Login form. """ |
form = form_class(request.POST or None)
if request.method == "POST" and form.is_valid():
authenticated_user = form.save()
info(request, _("Successfully logged in"))
auth_login(request, authenticated_user)
return login_redirect(request)
context = {"form": form, "title": _("Log in")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signup(request, template="accounts/account_signup.html", extra_context=None):
""" Signup form. """ |
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
new_user = form.save()
if not new_user.is_active:
if settings.ACCOUNTS_APPROVAL_REQUIRED:
send_approve_mail(request, new_user)
info(request, _("Thanks for signing up! You'll receive "
"an email when your account is activated."))
else:
send_verification_mail(request, new_user, "signup_verify")
info(request, _("A verification email has been sent with "
"a link for activating your account."))
return redirect(next_url(request) or "/")
else:
info(request, _("Successfully signed up"))
auth_login(request, new_user)
return login_redirect(request)
context = {"form": form, "title": _("Sign up")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signup_verify(request, uidb36=None, token=None):
""" View for the link in the verification email sent to a new user when they create an account and ``ACCOUNTS_VERIFICATION_REQUIRED`` is set to ``True``. Activates the user and logs them in, redirecting to the URL they tried to access when signing up. """ |
user = authenticate(uidb36=uidb36, token=token, is_active=False)
if user is not None:
user.is_active = True
user.save()
auth_login(request, user)
info(request, _("Successfully signed up"))
return login_redirect(request)
else:
error(request, _("The link you clicked is no longer valid."))
return redirect("/") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile(request, username, template="accounts/account_profile.html", extra_context=None):
""" Display a profile. """ |
lookup = {"username__iexact": username, "is_active": True}
context = {"profile_user": get_object_or_404(User, **lookup)}
context.update(extra_context or {})
return TemplateResponse(request, template, context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile_update(request, template="accounts/account_profile_update.html", extra_context=None):
""" Profile update form. """ |
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None,
instance=request.user)
if request.method == "POST" and form.is_valid():
user = form.save()
info(request, _("Profile updated"))
try:
return redirect("profile", username=user.username)
except NoReverseMatch:
return redirect("profile_update")
context = {"form": form, "title": _("Update Profile")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_branch_sha(profile, name):
"""Get the SHA a branch's HEAD points to. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the branch. Returns: The requested SHA. """ |
ref = "heads/" + name
data = refs.get_ref(profile, ref)
head = data.get("head")
sha = head.get("sha")
return sha |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_branch(profile, name):
"""Fetch a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the branch to fetch. Returns: A dict with data baout the branch. """ |
ref = "heads/" + name
data = refs.get_ref(profile, ref)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_branch(profile, name, branch_off):
"""Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the new branch. branch_off The name of a branch to create the new branch off of. Returns: A dict with data about the new branch. """ |
branch_off_sha = get_branch_sha(profile, branch_off)
ref = "heads/" + name
data = refs.create_ref(profile, ref, branch_off_sha)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_branch(profile, name, sha):
"""Move a branch's HEAD to a new SHA. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the branch to update. sha The commit SHA to point the branch's HEAD to. Returns: A dict with data about the branch. """ |
ref = "heads/" + name
data = refs.update_ref(profile, ref, sha)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_branch(profile, name):
"""Delete a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name The name of the branch to delete. Returns: The response of the DELETE request. """ |
ref = "heads/" + name
data = refs.delete_ref(profile, ref)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(profile, branch, merge_into):
"""Merge a branch into another branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of the branch to merge. merge_into The name of the branch you want to merge into. Returns: A dict wtih data about the merge. """ |
data = merges.merge(profile, branch, merge_into)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_callbacks(self, name):
""" Returns True if there are callbacks attached to the specified event name. Returns False if not """ |
r = self.event_listeners.get(name)
if not r:
return False
return len(r) > 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on(self, name, callback, once=False):
""" Adds a callback to the event specified by name once <bool> if True the callback will be removed once it's been triggered """ |
if name not in self.event_listeners:
self.event_listeners[name] = []
self.event_listeners[name].append((callback, once)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def off(self, name, callback, once=False):
""" Removes callback to the event specified by name """ |
if name not in self.event_listeners:
return
self.event_listeners[name].remove((callback, once)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger(self, name, *args, **kwargs):
""" Triggers the event specified by name and passes self in keyword argument "event_origin" All additional arguments and keyword arguments are passed through as well """ |
mark_remove = []
for callback, once in self.event_listeners.get(name, []):
callback(event_origin=self, *args, **kwargs)
if once:
mark_remove.append( (callback, once) )
for callback, once in mark_remove:
self.off(name, callback, once=once) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_final_destination(self):
"""Get a list of final destinations for a stop.""" |
dest = []
await self.get_departures()
for departure in self._departures:
dep = {}
dep['line'] = departure.get('line')
dep['destination'] = departure.get('destination')
dest.append(dep)
return [dict(t) for t in {tuple(d.items()) for d in dest}] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_name(name, module=None):
"""Resolve a dotted name to a module and its parts. This is stolen wholesale from unittest.TestLoader.loadTestByName. """ |
parts = name.split('.')
parts_copy = parts[:]
if module is None:
while parts_copy: # pragma: no cover
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
obj = getattr(obj, part)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_mobile(view):
"""View Decorator that adds a "mobile" attribute to the request which is True or False depending on whether the request should be considered to come from a small-screen device such as a phone or a PDA""" |
@wraps(view)
def detected(request, *args, **kwargs):
MobileDetectionMiddleware.process_request(request)
return view(request, *args, **kwargs)
detected.__doc__ = '%s\n[Wrapped by detect_mobile which detects if the request is from a phone]' % view.__doc__
return detected |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def masked(a, b):
"""Return a numpy array with values from a where elements in b are not False. Populate with numpy.nan where b is False. When plotting, those elements look like missing, which can be a desired result. """ |
if np.any([a.dtype.kind.startswith(c) for c in ['i', 'u', 'f', 'c']]):
n = np.array([np.nan for i in range(len(a))])
else:
n = np.array([None for i in range(len(a))])
# a = a.astype(object)
return np.where(b, a, n) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def duration_bool(b, rule, samplerate=None):
""" Mask the parts in b being True but does not meet the duration rules. Return an updated copy of b. b: 1d array with True or False elements. rule: str The rule including the string 'dur' to be evaled. samplerate: None or float Has an effect on the result. For each part of b that is True, a variable ``dur`` is set to the count of elements, or the result of (len(part) / samplerate). And then eval is called on the rule. """ |
if rule is None:
return b
slicelst = slicelist(b)
b2 = np.array(b)
if samplerate is None:
samplerate = 1.0
for sc in slicelst:
dur = (sc.stop - sc.start) / samplerate # NOQA
if not eval(rule):
b2[sc] = False
return b2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startstop_bool(pack):
"""Make a bool array based on start and stop conditions. pack: pack.ChannelPack instance If there is start conditions but no stop conditions, this is legal, the True section will begin at first start and remain the rest of the array. Likewise, if there is stop conditions but no start condition, the returned array will be all True until the first stop slice, and the rest of the array is set to False. """ |
b_TRUE = np.ones(pack.rec_cnt) == True # NOQA
start_list = pack.conconf.conditions_list('startcond')
stop_list = pack.conconf.conditions_list('stopcond')
# Pre-check:
runflag = 'startstop'
if not start_list and not stop_list:
return b_TRUE
elif not start_list:
runflag = 'stoponly'
elif not stop_list:
runflag = 'start_only'
# startb:
if runflag == 'stoponly':
# all False (dummy assignment)
startb = b_TRUE == False # NOQA
else:
startb = b_TRUE
for cond in start_list:
startb = startb & pack._mask_array(cond)
# stopb:
if runflag == 'startonly':
# all False (dummy assignment)
stopb = b_TRUE == False # NOQA
else:
stopb = b_TRUE
for cond in stop_list:
stopb = stopb & pack._mask_array(cond)
stopextend = pack.conconf.get_stopextend()
return _startstop_bool(startb, stopb, runflag, stopextend) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _startstop_bool(startb, stopb, runflag, stopextend):
"""Return boolean array based on start and stop conditions. startb, stopb: Numpy 1D arrays of the same length. Boolean arrays for start and stop conditions being fullfilled or not. """ |
# All false at start
res = np.zeros(len(startb)) == True # NOQA
start_slices = slicelist(startb)
stop_slices = slicelist(stopb)
# Special case when there is a start but no stop slice or vice versa:
# if start_slices and not stop_slices:
if runflag == 'startonly':
try:
start = start_slices[0]
# Make True from first start and rest of array.
res[start.start:] = True
return res
except IndexError:
# Only start specified but no start condition
# fullfilled. Return all False.
return res
elif runflag == 'stoponly':
try:
stop = stop_slices[0]
res[:stop.start + stopextend] = True # Make True up to first stop.
return res
except IndexError:
# Only stop specified but no stop condition fullfilled
# Return all True
return res == False # NOQA
stop = slice(0, 0) # For first check
start = slice(0, 0) # For a possibly empty list start_slices.
for start in start_slices:
if start.start < stop.start:
continue
for stop in stop_slices:
if stop.start > start.start:
res[start.start: stop.start + stopextend] = True
break # Next start
else:
# On a given start slice, the entire list of stop slices was
# exhausted, none being later than the given start. It must mean
# that from this given start, the rest is to be True:
break
# There was no stop for the last start in loop
if start.start > stop.start:
res[start.start:] = True
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slicelist(b):
"""Produce a list of slices given the boolean array b. Start and stop in each slice describe the True sections in b.""" |
slicelst = []
started = False
for i, e in enumerate(b):
if e and not started:
start = i
started = True
elif not e and started:
slicelst.append(slice(start, i))
started = False
if e:
slicelst.append(slice(start, i + 1)) # True in the end.
return slicelst |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_archive(archive):
""" Save `archive` into database and into proper indexes. Attr: archive (obj):
Instance of the :class:`.DBArchive`. Returns: obj: :class:`.DBArchive` without data. Raises: InvalidType: When the `archive` is not instance of :class:`.DBArchive`. UnindexablePublication: When there is no index (property) which can be used to index `archive` in database. """ |
_assert_obj_type(archive, obj_type=DBArchive)
_get_handler().store_object(archive)
return archive.to_comm(light_request=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(argv):
""" Basic command line script for testing library. """ |
# Parse command line arguments
parser = argparse.ArgumentParser(
description="LifeSOSpy v{} - {}".format(
PROJECT_VERSION, PROJECT_DESCRIPTION))
parser.add_argument(
'-H', '--host',
help="Hostname/IP Address for the LifeSOS server, if we are to run as a client.",
default=None)
parser.add_argument(
'-P', '--port',
help="TCP port for the LifeSOS ethernet interface.",
default=str(BaseUnit.TCP_PORT))
parser.add_argument(
'-p', '--password',
help="Password for the Master user, if remote access requires it.",
default='')
parser.add_argument(
'-v', '--verbose',
help="Display all logging output.",
action='store_true')
args = parser.parse_args()
# Configure logger
logging.basicConfig(
format="%(asctime)s %(levelname)-5s (%(threadName)s) [%(name)s] %(message)s",
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG if args.verbose else logging.INFO)
# Create base unit instance and start up interface
print("LifeSOSpy v{} - {}\n".format(PROJECT_VERSION, PROJECT_DESCRIPTION))
loop = asyncio.get_event_loop()
baseunit = BaseUnit(args.host, args.port)
if args.password:
baseunit.password = args.password
baseunit.start()
# Provide interactive prompt for running test commands on another thread
loop.run_until_complete(
loop.run_in_executor(
None, _handle_interactive_baseunit_tests, baseunit, loop))
# Shut down interface and event loop
baseunit.stop()
loop.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datetime(self):
"""Return `datetime` object""" |
return dt.datetime(
self.year(), self.month(), self.day(),
self.hour(), self.minute(), self.second(),
int(self.millisecond() * 1e3)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_command(self, name):
"""Wrap command class in constructor.""" |
def command(options):
client = ZookeeperClient(
"%s:%d" % (options.pop('host'), options.pop('port')),
session_timeout=1000
)
path = options.pop('path_prefix')
force = options.pop('force')
extra = options.pop('extra')
# Apply settings to options dictionary. While this does
# conflate arguments for the utility with command options,
# that's something we're willing to accept.
options.update(extra)
controller = Command(client, path, self.services, force)
method = getattr(controller, "cmd_%s" % name)
return method(**options)
return command |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_installed_version(vcs):
"""Get the installed version for this project. Args: vcs (easyci.vcs.base.Vcs) Returns: str - version number Raises: VersionNotInstalledError """ |
version_path = _get_version_path(vcs)
if not os.path.exists(version_path):
raise VersionNotInstalledError
with open(version_path, 'r') as f:
return f.read().strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_installed_version(vcs, version):
"""Set the installed version for this project. Args: vcs (easyci.vcs.base.Vcs) version (str) """ |
version_path = _get_version_path(vcs)
with open(version_path, 'w') as f:
f.write(version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_urls(self, **kwargs):
""" Ensure the correct host by injecting the current site. """ |
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(DisplayableSitemap, self).get_urls(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
m = username_re.match(path)
if m:
usernames[m.group('username')] += count
elif hostname in ['twitter.com', 'www.facebook.com']:
usernames[path.lstrip('/')] += count
return usernames |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleaned_data(self):
""" When cleaned_data is initially accessed, we want to ensure the form gets validated which has the side effect of setting cleaned_data to something. """ |
if not hasattr(self, "_cleaned_data"):
self._cleaned_data = {}
self.is_valid()
return self._cleaned_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self):
""" This should return an elasticsearch-DSL Search instance, list or queryset based on the values in self.cleaned_data. """ |
results = self.index.objects.all()
# reduce the results based on the q field
if self.cleaned_data.get("q"):
results = results.query(
"multi_match",
query=self.cleaned_data['q'],
fields=self.get_fields(),
# this prevents ES from erroring out when a string is used on a
# number field (for example)
lenient=True
)
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plug(self):
'''Add the actor's methods to the callback registry.'''
if self.__plugged:
return
for _, method in inspect.getmembers(self, predicate=inspect.ismethod):
if hasattr(method, '_callback_messages'):
for message in method._callback_messages:
global_callbacks[message].add(method)
self.__plugged = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global_callbacks[message] -= members
self.__plugged = False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_event_queue:
self.process_event(global_event_queue.popleft()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def halt(self, message, emitter, *args, **kwargs):
'''Halt the execution of the loop.'''
self.process_event((FINISH, self, (), {}))
global_event_queue.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated.
This is useful for handling thread local services like database
connections.
:param str param_name: name of function parameter to inject into
:param fun_param_value: the value to insert
:type fun_param_value: a closure that can be applied with zero
arguments
'''
class _(object):
api = 2
def apply(self, callback, route):
if param_name not in inspect.getargspec(route.callback)[0]:
return callback
def _(*args, **kwargs):
pval = fun_param_value()
if pval is None:
logger.error('service "%s" unavailable', param_name)
bottle.abort(503, 'service "%s" unavailable' % param_name)
return
kwargs[param_name] = pval
return callback(*args, **kwargs)
return _
return _() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
# If the user never sets a config instance, then just create
# a default.
self.config = Config()
if self.mount_prefix is None:
self.mount_prefix = self.config.config.get('url_prefix')
self.inject('config', lambda: self.config)
self.inject('kvlclient', lambda: self.config.kvlclient)
self.inject('store', lambda: self.config.store)
self.inject('label_store', lambda: self.config.label_store)
self.inject('tags', lambda: self.config.tags)
self.inject('search_engines', lambda: self.search_engines)
self.inject('filters', lambda: self.filters)
self.inject('request', lambda: bottle.request)
self.inject('response', lambda: bottle.response)
# DEPRECATED. Remove. ---AG
self.inject('visid_to_dbid', lambda: self.visid_to_dbid)
self.inject('dbid_to_visid', lambda: self.dbid_to_visid)
# Also DEPRECATED.
self.inject('label_hooks', lambda: [])
# Load routes defined in entry points.
for extroute in self.config.config.get('external_routes', []):
mod, fun_name = extroute.split(':')
logger.info('Loading external route: %s', extroute)
fun = getattr(__import__(mod, fromlist=[fun_name]), fun_name)
self.add_routes(fun())
# This adds the `json=True` feature on routes, which always coerces
# the output to JSON. Bottle, by default, only permits dictionaries
# to be JSON, which is the correct behavior. (Because returning JSON
# arrays is a hazard.)
#
# So we should fix the routes and then remove this. ---AG
self.app.install(JsonPlugin())
# Throw away the app and return it. Because this is elimination!
app = self.app
self.app = None
if self.mount_prefix is not None:
root = bottle.Bottle()
root.mount(self.mount_prefix, app)
return root
else:
return app |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_search_engine(self, name, engine):
'''Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations given a query.
The ``engine`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``engine`` is ``None``, then it removes a possibly existing
search engine named ``name``.
:param str name: The name of the search engine. This appears
in the list of search engines provided to the
user, and is how the search engine is invoked
via REST.
:param engine: A search engine *class*.
:type engine: `type`
:rtype: :class:`WebBuilder`
'''
if engine is None:
self.search_engines.pop(name, None)
self.search_engines[name] = engine
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_filter(self, name, filter):
'''Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The ``filter`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``filter`` is ``None``, then it removes a possibly existing
filter named ``name``.
:param str name: The name of the filter. This is how the search engine
is invoked via REST.
:param engine: A filter *class*.
:type engine: `type`
:rtype: :class:`WebBuilder`
'''
if name is None:
self.filters.pop(name, None)
self.filters[name] = filter
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_routes(self, routes):
'''Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder`
'''
# Basically the same as `self.app.merge(routes)`, except this
# changes the owner of the route so that plugins on `self.app`
# apply to the routes given here.
if isinstance(routes, bottle.Bottle):
routes = routes.routes
for route in routes:
route.app = self.app
self.app.add_route(route)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def enable_cors(self):
'''Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder`
'''
def access_control_headers():
bottle.response.headers['Access-Control-Allow-Origin'] = '*'
bottle.response.headers['Access-Control-Allow-Methods'] = \
'GET, POST, PUT, DELETE, OPTIONS'
bottle.response.headers['Access-Control-Allow-Headers'] = \
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
def options_response(res):
if bottle.request.method == 'OPTIONS':
new_res = bottle.HTTPResponse()
new_res.headers['Access-Control-Allow-Origin'] = '*'
new_res.headers['Access-Control-Allow-Methods'] = \
bottle.request.headers.get(
'Access-Control-Request-Method', '')
new_res.headers['Access-Control-Allow-Headers'] = \
bottle.request.headers.get(
'Access-Control-Request-Headers', '')
return new_res
res.headers['Allow'] += ', OPTIONS'
return bottle.request.app.default_error_handler(res)
self.app.add_hook('after_request', access_control_headers)
self.app.error_handler[int(405)] = options_response
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_properties(self) -> 'PygalleBaseClass': """ Initialize the Pigalle properties. # Returns: PygalleBaseClass: The current instance. """ |
self._pigalle = {
PygalleBaseClass.__KEYS.INTERNALS: dict(),
PygalleBaseClass.__KEYS.PUBLIC: dict()
}
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, key: str, value: Any) -> 'PygalleBaseClass': """ Define a public property. :param key: :param value: :return: """ |
self.public()[key] = value
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_category(self, category: str = None) -> 'PygalleBaseClass': """ Define the category of the class. # Arguments category: The name of category. # Returns: PygalleBaseClass: An instance of :class:`PygalleBaseClass` """ |
return self.set_internal(PygalleBaseClass.__KEYS.CATEGORY, category) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance_of(self, kls: Any) -> bool: """ Return true if the current object is an instance of passed type. # Arguments kls: The class. # Returns: bool: * Return true if the current object is an instance of passed type. * False else. """ |
if not kls:
raise ValueError
return isinstance(self, kls) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_pigalle_class(kls: ClassVar) -> bool: """ Return true if the passed object as argument is a class being to the Pigalle framework. # Arguments kls: The class to check. # Returns: bool: * True if class is Pigalle. * False else. """ |
return (kls is PygalleBaseClass) or (issubclass(type(kls), PygalleBaseClass)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_pigalle(obj: Any) -> bool: """ Return true if the passed object as argument is a class or an instance of class being to the Pigalle framework. # Arguments obj: The class or object to test. # Returns: bool: * True if class or object is Pigalle. * False else. """ |
return PygalleBaseClass.is_pigalle_class(obj) or PygalleBaseClass.is_pigalle_instance(obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_method(self, key: str) -> bool: """ Return if a method exists for the current instance. # Arguments key: The method name. # Returns: bool: * True if the current instance has the provided method. * False else. """ |
return hasattr(self.__class__, key) and callable(getattr(self.__class__, key)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_context(tex_file, extracted_image_data):
"""Extract context. Given a .tex file and a label name, this function will extract the text before and after for all the references made to this label in the text. The number of characters to extract before and after is configurable. :param tex_file (list):
path to .tex file a list of tuples of images matched to labels and captions from this document. :return extracted_image_data ([(string, string, list, list), extracted contexts """ |
if os.path.isdir(tex_file) or not os.path.exists(tex_file):
return []
lines = "".join(get_lines_from_file(tex_file))
# Generate context for each image and its assoc. labels
for data in extracted_image_data:
context_list = []
# Generate a list of index tuples for all matches
indicies = [match.span()
for match in re.finditer(r"(\\(?:fig|ref)\{%s\})" %
(re.escape(data['label']),),
lines)]
for startindex, endindex in indicies:
# Retrive all lines before label until beginning of file
i = startindex - CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
if i < 0:
text_before = lines[:startindex]
else:
text_before = lines[i:startindex]
context_before = get_context(text_before, backwards=True)
# Retrive all lines from label until end of file and get context
i = endindex + CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
text_after = lines[endindex:i]
context_after = get_context(text_after)
context_list.append(
context_before + ' \\ref{' + data['label'] + '} ' +
context_after
)
data['contexts'] = context_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intelligently_find_filenames(line, TeX=False, ext=False, commas_okay=False):
"""Intelligently find filenames. Find the filename in the line. We don't support all filenames! Just eps and ps for now. :param: line (string):
the line we want to get a filename out of """ |
files_included = ['ERROR']
if commas_okay:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.,%#]+'
else:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.%#]+'
if ext:
valid_for_filename += '\.e*ps[texfi2]*'
if TeX:
valid_for_filename += '[\.latex]*'
file_inclusion = re.findall('=' + valid_for_filename + '[ ,]', line)
if len(file_inclusion) > 0:
# right now it looks like '=FILENAME,' or '=FILENAME '
for file_included in file_inclusion:
files_included.append(file_included[1:-1])
file_inclusion = re.findall('(?:[ps]*file=|figure=)' +
valid_for_filename + '[,\\]} ]*', line)
if len(file_inclusion) > 0:
# still has the =
for file_included in file_inclusion:
part_before_equals = file_included.split('=')[0]
if len(part_before_equals) != file_included:
file_included = file_included[
len(part_before_equals) + 1:].strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall(
'["\'{\\[]' + valid_for_filename + '[}\\],"\']',
line)
if len(file_inclusion) > 0:
# right now it's got the {} or [] or "" or '' around it still
for file_included in file_inclusion:
file_included = file_included[1:-1]
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('^' + valid_for_filename + '$', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('^' + valid_for_filename + '[,\\} $]', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('\\s*' + valid_for_filename + '\\s*$', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
if files_included != ['ERROR']:
files_included = files_included[1:] # cut off the dummy
for file_included in files_included:
if file_included == '':
files_included.remove(file_included)
if ' ' in file_included:
for subfile in file_included.split(' '):
if subfile not in files_included:
files_included.append(subfile)
if ',' in file_included:
for subfile in file_included.split(' '):
if subfile not in files_included:
files_included.append(subfile)
return files_included |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_lines_from_file(filepath, encoding="UTF-8"):
"""Return an iterator over lines.""" |
try:
fd = codecs.open(filepath, 'r', encoding)
lines = fd.readlines()
except UnicodeDecodeError:
# Fall back to 'ISO-8859-1'
fd = codecs.open(filepath, 'r', 'ISO-8859-1')
lines = fd.readlines()
finally:
fd.close()
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_request(self, conf, post_params={}):
"""Make a request to the API and return data in a pythonic object""" |
endpoint, requires_auth = conf
# setup the url and the request objects
url = '%s%s.php' % (self.api_url, endpoint)
log.debug('Setting url to %s' % url)
request = urllib2.Request(url)
# tack on authentication if needed
log.debug('Post params: %s' % post_params)
if requires_auth:
post_params.update({
'user': self.username,
'pass': self.password
})
# url encode all parameters
data = urlencode(post_params).encode('utf-8')
# gimme some bitcoins!
try:
log.debug('Requesting data from %s' % url)
response = urllib2.urlopen(request, data)
return json.loads(response.read())
except urllib2.URLError as e:
log.debug('Full error: %s' % e)
if hasattr(e, 'reason'):
self.log.error('Could not reach host. Reason: %s' % e.reason)
elif hasattr(e, 'code'):
self.log.error('Could not fulfill request. Error Code: %s' % e.code)
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.