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 getColumnsClasses(self, view=None):
"""Determine whether a column should be shown. The left column is called plone.leftcolumn; the right column is called plone.rightcolumn. """ |
plone_view = getMultiAdapter(
(self.context, self.request), name=u'plone')
portal_state = getMultiAdapter(
(self.context, self.request), name=u'plone_portal_state')
sl = plone_view.have_portlets('plone.leftcolumn', view=view)
sr = plone_view.have_portlets('plone.rightcolumn', view=view)
isRTL = portal_state.is_rtl()
# pre-fill dictionary
columns = dict(one="", content="", two="")
if not sl and not sr:
# we don't have columns, thus conten takes the whole width
columns['content'] = "col-md-12"
elif sl and sr:
# In case we have both columns, content takes 50% of the whole
# width and the rest 50% is spread between the columns
columns['one'] = "col-xs-12 col-md-2"
columns['content'] = "col-xs-12 col-md-8"
columns['two'] = "col-xs-12 col-md-2"
elif (sr and not sl) and not isRTL:
# We have right column and we are NOT in RTL language
columns['content'] = "col-xs-12 col-md-10"
columns['two'] = "col-xs-12 col-md-2"
elif (sl and not sr) and isRTL:
# We have left column and we are in RTL language
columns['one'] = "col-xs-12 col-md-2"
columns['content'] = "col-xs-12 col-md-10"
elif (sl and not sr) and not isRTL:
# We have left column and we are in NOT RTL language
columns['one'] = "col-xs-12 col-md-2"
columns['content'] = "col-xs-12 col-md-10"
# # append cell to each css-string
# for key, value in columns.items():
# columns[key] = "cell " + value
return columns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setupitems(self):
"""Lookup available setup items :returns: catalog brains """ |
query = {
"path": {
"query": api.get_path(self.setup),
"depth": 1,
},
}
items = api.search(query, "portal_catalog")
# filter out items
items = filter(lambda item: not item.exclude_from_nav, items)
# sort by (translated) title
def cmp_by_translated_title(brain1, brain2):
title1 = t(api.get_title(brain1))
title2 = t(api.get_title(brain2))
return cmp(title1, title2)
return sorted(items, cmp=cmp_by_translated_title) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def content_type(self):
"""Returns the content-type value determined by file extension.""" |
if hasattr(self, '_content_type'):
return self._content_type
filename, extension = os.path.splitext(self._file_path)
if extension == '.csv':
self._content_type = 'text/csv'
elif extension == '.tsv':
self._content_type = 'text/tab-separated-values'
else:
self._content_type = 'text/plain'
return self._content_type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perform(self):
"""Executes the current TONUpload object.""" |
if self._file_size < self._SINGLE_UPLOAD_MAX:
resource = "{0}{1}".format(self._DEFAULT_RESOURCE, self.bucket)
response = self.__upload(resource, open(self._file_path, 'rb').read())
return response.headers['location']
else:
response = self.__init_chunked_upload()
min_chunk_size = int(response.headers['x-ton-min-chunk-size'])
chunk_size = min_chunk_size * self._DEFAULT_CHUNK_SIZE
location = response.headers['location']
f = open(self._file_path, 'rb')
bytes_read = 0
while True:
bytes = f.read(chunk_size)
if not bytes:
break
bytes_start = bytes_read
bytes_read += len(bytes)
response = self.__upload_chunk(location, chunk_size, bytes, bytes_start, bytes_read)
response_time = int(response.headers['x-response-time'])
chunk_size = min_chunk_size * size(self._DEFAULT_CHUNK_SIZE,
self._RESPONSE_TIME_MAX,
response_time)
f.close()
return location.split("?")[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 __upload(self, resource, bytes):
"""Performs a single chunk upload.""" |
# note: string conversion required here due to open encoding bug in requests-oauthlib.
headers = {
'x-ton-expires': http_time(self.options.get('x-ton-expires', self._DEFAULT_EXPIRE)),
'content-length': str(self._file_size),
'content-type': self.content_type
}
return Request(self._client, 'post', resource,
domain=self._DEFAULT_DOMAIN, headers=headers, body=bytes).perform() |
<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_chunked_upload(self):
"""Initialization for a multi-chunk upload.""" |
# note: string conversion required here due to open encoding bug in requests-oauthlib.
headers = {
'x-ton-content-type': self.content_type,
'x-ton-content-length': str(self._file_size),
'x-ton-expires': http_time(self.options.get('x-ton-expires', self._DEFAULT_EXPIRE)),
'content-length': str(0),
'content-type': self.content_type
}
resource = "{0}{1}?resumable=true".format(self._DEFAULT_RESOURCE, self._DEFAULT_BUCKET)
return Request(self._client, 'post', resource,
domain=self._DEFAULT_DOMAIN, headers=headers).perform() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __upload_chunk(self, resource, chunk_size, bytes, bytes_start, bytes_read):
"""Uploads a single chunk of a multi-chunk upload.""" |
# note: string conversion required here due to open encoding bug in requests-oauthlib.
headers = {
'content-type': self.content_type,
'content-length': str(min([chunk_size, self._file_size - bytes_read])),
'content-range': "bytes {0}-{1}/{2}".format(
bytes_start, bytes_read - 1, self._file_size)
}
return Request(self._client, 'put', resource,
domain=self._DEFAULT_DOMAIN, headers=headers, body=bytes).perform() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
"""Returns the next item in the cursor.""" |
if self._current_index < len(self._collection):
value = self._collection[self._current_index]
self._current_index += 1
return value
elif self._next_cursor:
self.__fetch_next()
return self.next()
else:
self._current_index = 0
raise StopIteration |
<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):
""" Saves or updates the current object instance depending on the presence of `object.id`. """ |
params = self.to_params()
if 'tweet_id' in params:
params['tweet_ids'] = [params['tweet_id']]
del params['tweet_id']
if self.id:
raise HTTPError("Method PUT not allowed.")
resource = self.RESOURCE_COLLECTION.format(account_id=self.account.id)
response = Request(self.account.client, 'post', resource, params=params).perform()
return self.from_response(response.body['data'][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 preview(self):
""" Returns an HTML preview for a Scheduled Tweet. """ |
if self.id:
resource = self.PREVIEW
resource = resource.format(account_id=self.account.id, id=self.id)
response = Request(self.account.client, 'get', resource).perform()
return response.body['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 load(klass, client, id, **kwargs):
"""Returns an object instance for a given resource.""" |
resource = klass.RESOURCE.format(id=id)
response = Request(client, 'get', resource, params=kwargs).perform()
return klass(client).from_response(response.body['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 all(klass, client, **kwargs):
"""Returns a Cursor instance for a given resource.""" |
resource = klass.RESOURCE_COLLECTION
request = Request(client, 'get', resource, params=kwargs)
return Cursor(klass, request, init_with=[client]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def features(self):
""" Returns a collection of features available to the current account. """ |
self._validate_loaded()
resource = self.FEATURES.format(id=self.id)
response = Request(self.client, 'get', resource).perform()
return response.body['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 scoped_timeline(self, *id, **kwargs):
""" Returns the most recent promotable Tweets created by the specified Twitter user. """ |
self._validate_loaded()
params = {'user_id': id}
params.update(kwargs)
resource = self.SCOPED_TIMELINE.format(id=self.id)
response = Request(self.client, 'get', resource, params=params).perform()
return response.body['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 get_version():
"""Returns a string representation of the current SDK version.""" |
if isinstance(VERSION[-1], str):
return '.'.join(map(str, VERSION[:-1])) + VERSION[-1]
return '.'.join(map(str, 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 to_time(time, granularity):
"""Returns a truncated and rounded time string based on the specified granularity.""" |
if not granularity:
if type(time) is datetime.date:
return format_date(time)
else:
return format_time(time)
if granularity == GRANULARITY.HOUR:
return format_time(remove_minutes(time))
elif granularity == GRANULARITY.DAY:
return format_date(remove_hours(time))
else:
return format_time(time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_time(time):
"""Formats a datetime as an RFC 1123 compliant string.""" |
return formatdate(timeval=mktime(time.timetuple()), localtime=False, usegmt=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 size(default_chunk_size, response_time_max, response_time_actual):
"""Determines the chunk size based on response times.""" |
if response_time_actual == 0:
response_time_actual = 1
scale = 1 / (response_time_actual / response_time_max)
size = int(default_chunk_size * scale)
return min(max(size, 1), default_chunk_size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sandbox():
"""Enables and disables sandbox mode.""" |
def fget(self):
return self._options.get('sandbox', None)
def fset(self, value):
self._options['sandbox'] = value
return locals() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trace():
"""Enables and disables request tracing.""" |
def fget(self):
return self._options.get('trace', None)
def fset(self, value):
self._options['trace'] = value
return locals() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def platform_versions(klass, account, **kwargs):
"""Returns a list of supported platform versions""" |
resource = klass.RESOURCE_OPTIONS + 'platform_versions'
request = Request(account.client, 'get', resource, params=kwargs)
return Cursor(None, request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def targeting_criteria(self, id=None, **kwargs):
""" Returns a collection of targeting criteria available to the current line item. """ |
self._validate_loaded()
if id is None:
return TargetingCriteria.all(self.account, self.id, **kwargs)
else:
return TargetingCriteria.load(self.account, id, **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 preview(klass, account, **kwargs):
""" Returns an HTML preview of a tweet, either new or existing. """ |
params = {}
params.update(kwargs)
# handles array to string conversion for media IDs
if 'media_ids' in params and isinstance(params['media_ids'], list):
params['media_ids'] = ','.join(map(str, params['media_ids']))
resource = klass.TWEET_ID_PREVIEW if params.get('id') else klass.TWEET_PREVIEW
resource = resource.format(account_id=account.id, id=params.get('id'))
response = Request(account.client, 'get', resource, params=params).perform()
return response.body['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(klass, account, **kwargs):
""" Creates a "Promoted-Only" Tweet using the specialized Ads API end point. """ |
params = {}
params.update(kwargs)
# handles array to string conversion for media IDs
if 'media_ids' in params and isinstance(params['media_ids'], list):
params['media_ids'] = ','.join(map(str, params['media_ids']))
resource = klass.TWEET_CREATE.format(account_id=account.id)
response = Request(account.client, 'post', resource, params=params).perform()
return response.body['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 resource_property(klass, name, **kwargs):
"""Builds a resource object property.""" |
klass.PROPERTIES[name] = kwargs
def getter(self):
return getattr(self, '_%s' % name, kwargs.get('default', None))
if kwargs.get('readonly', False):
setattr(klass, name, property(getter))
else:
def setter(self, value):
setattr(self, '_%s' % name, value)
setattr(klass, name, property(getter, setter)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_response(self, response):
""" Populates a given objects attributes from a parsed JSON API response. This helper handles all necessary type coercions as it assigns attribute values. """ |
for name in self.PROPERTIES:
attr = '_{0}'.format(name)
transform = self.PROPERTIES[name].get('transform', None)
value = response.get(name, None)
if transform and transform == TRANSFORM.TIME and value:
setattr(self, attr, dateutil.parser.parse(value))
if isinstance(value, int) and value == 0:
continue # skip attribute
else:
setattr(self, attr, 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 to_params(self):
""" Generates a Hash of property values for the current object. This helper handles all necessary type coercions as it generates its output. """ |
params = {}
for name in self.PROPERTIES:
attr = '_{0}'.format(name)
value = getattr(self, attr, None) or getattr(self, name, None)
# skip attribute
if value is None:
continue
if isinstance(value, datetime):
params[name] = format_time(value)
elif isinstance(value, list):
params[name] = ','.join(map(str, value))
elif isinstance(value, bool):
params[name] = str(value).lower()
else:
params[name] = value
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stats(self, metrics, **kwargs):
# noqa """ Pulls a list of metrics for the current object instance. """ |
return self.__class__.all_stats(self.account, [self.id], metrics, **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 _standard_params(klass, ids, metric_groups, **kwargs):
""" Sets the standard params for a stats request """ |
end_time = kwargs.get('end_time', datetime.utcnow())
start_time = kwargs.get('start_time', end_time - timedelta(seconds=604800))
granularity = kwargs.get('granularity', GRANULARITY.HOUR)
placement = kwargs.get('placement', PLACEMENT.ALL_ON_TWITTER)
params = {
'metric_groups': ','.join(metric_groups),
'start_time': to_time(start_time, granularity),
'end_time': to_time(end_time, granularity),
'granularity': granularity.upper(),
'entity': klass.ANALYTICS_MAP[klass.__name__],
'placement': placement
}
params['entity_ids'] = ','.join(ids)
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_stats(klass, account, ids, metric_groups, **kwargs):
""" Pulls a list of metrics for a specified set of object IDs. """ |
params = klass._standard_params(ids, metric_groups, **kwargs)
resource = klass.RESOURCE_SYNC.format(account_id=account.id)
response = Request(account.client, 'get', resource, params=params).perform()
return response.body['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 queue_async_stats_job(klass, account, ids, metric_groups, **kwargs):
""" Queues a list of metrics for a specified set of object IDs asynchronously """ |
params = klass._standard_params(ids, metric_groups, **kwargs)
params['platform'] = kwargs.get('platform', None)
params['country'] = kwargs.get('country', None)
params['segmentation_type'] = kwargs.get('segmentation_type', None)
resource = klass.RESOURCE_ASYNC.format(account_id=account.id)
response = Request(account.client, 'post', resource, params=params).perform()
return response.body['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(klass, account, name):
""" Creates a new tailored audience. """ |
audience = klass(account)
getattr(audience, '__create_audience__')(name)
try:
return audience.reload()
except BadRequest as e:
audience.delete()
raise e |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def users(self, params):
""" This is a private API and requires whitelisting from Twitter. This endpoint will allow partners to add, update and remove users from a given tailored_audience_id. The endpoint will also accept multiple user identifier types per user as well. """ |
resource = self.RESOURCE_USERS.format(account_id=self.account.id, id=self.id)
headers = {'Content-Type': 'application/json'}
response = Request(self.account.client,
'post',
resource,
headers=headers,
body=json.dumps(params)).perform()
success_count = response.body['data']['success_count']
total_count = response.body['data']['total_count']
return (success_count, total_count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permissions(self, **kwargs):
""" Returns a collection of permissions for the curent tailored audience. """ |
self._validate_loaded()
return TailoredAudiencePermission.all(self.account, self.id, **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 all(klass, account, tailored_audience_id, **kwargs):
"""Returns a Cursor instance for the given tailored audience permission resource.""" |
resource = klass.RESOURCE_COLLECTION.format(
account_id=account.id,
tailored_audience_id=tailored_audience_id)
request = Request(account.client, 'get', resource, params=kwargs)
return Cursor(klass, request, init_with=[account]) |
<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):
""" Saves or updates the current tailored audience permission. """ |
if self.id:
method = 'put'
resource = self.RESOURCE.format(
account_id=self.account.id,
tailored_audience_id=self.tailored_audience_id,
id=self.id)
else:
method = 'post'
resource = self.RESOURCE_COLLECTION.format(
account_id=self.account.id,
tailored_audience_id=self.tailored_audience_id)
response = Request(
self.account.client, method,
resource, params=self.to_params()).perform()
return self.from_response(response.body['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(self):
""" Deletes the current tailored audience permission. """ |
resource = self.RESOURCE.format(
account_id=self.account.id,
tailored_audience_id=self.tailored_audience_id,
id=self.id)
response = Request(self.account.client, 'delete', resource).perform()
return self.from_response(response.body['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 __get(klass, account, client, params):
""" Helper function to get the conversation data Returns a Cursor instance """ |
resource = klass.RESOURCE_CONVERSATIONS.format(account_id=account.id)
request = Request(
account.client, klass.METHOD,
resource, headers=klass.HEADERS, body=params)
return Cursor(klass, request, init_with=[account]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conversations(self):
""" Get the conversation topics for an input targeting criteria """ |
body = {
"conversation_type": self.conversation_type,
"audience_definition": self.audience_definition,
"targeting_inputs": self.targeting_inputs
}
return self.__get(account=self.account, client=self.account.client, params=json.dumps(body)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def demographics(self):
""" Get the demographic breakdown for an input targeting criteria """ |
body = {
"audience_definition": self.audience_definition,
"targeting_inputs": self.targeting_inputs
}
resource = self.RESOURCE_DEMOGRAPHICS.format(account_id=self.account.id)
response = Request(
self.account.client, self.METHOD,
resource, headers=self.HEADERS, body=json.dumps(body)).perform()
return response.body['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 setupEnvironment(self, cmd):
""" Turn all build properties into environment variables """ |
shell.ShellCommand.setupEnvironment(self, cmd)
env = {}
for k, v in self.build.getProperties().properties.items():
env[str(k)] = str(v[0])
if cmd.args['env'] is None:
cmd.args['env'] = {}
cmd.args['env'].update(env) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateStats(self, log):
""" Parse test results out of common test harnesses. Currently supported are: * Plone * Nose * Trial * Something mitchell wrote in Java """ |
stdio = log.getText()
total = passed = skipped = fails = warnings = errors = 0
hastests = False
# Plone? That has lines starting "Ran" and "Total". Total is missing if there is only a single layer.
# For this reason, we total ourselves which lets us work even if someone runes 2 batches of plone tests
# from a single target
# Example::
# Ran 24 tests with 0 failures and 0 errors in 0.009 seconds
if not hastests:
outputs = re.findall(
"Ran (?P<count>[\d]+) tests with (?P<fail>[\d]+) failures and (?P<error>[\d]+) errors",
stdio)
for output in outputs:
total += int(output[0])
fails += int(output[1])
errors += int(output[2])
hastests = True
# Twisted
# Example::
# FAILED (errors=5, successes=11)
# PASSED (successes=16)
if not hastests:
for line in stdio.split("\n"):
if line.startswith("FAILED (") or line.startswith("PASSED ("):
hastests = True
line = line[8:][:-1]
stats = line.split(", ")
data = {}
for stat in stats:
k, v = stat.split("=")
data[k] = int(v)
if "successes" not in data:
total = 0
for number in re.findall(
"Ran (?P<count>[\d]+) tests in ", stdio):
total += int(number)
data["successes"] = total - sum(data.values())
# This matches Nose and Django output
# Example::
# Ran 424 tests in 152.927s
# FAILED (failures=1)
# FAILED (errors=3)
if not hastests:
fails += len(re.findall('FAIL:', stdio))
errors += len(
re.findall(
'======================================================================\nERROR:',
stdio))
for number in re.findall("Ran (?P<count>[\d]+)", stdio):
total += int(number)
hastests = True
# We work out passed at the end because most test runners dont tell us
# and we can't distinguish between different test systems easily so we
# might double count.
passed = total - (skipped + fails + errors + warnings)
# Update the step statistics with out shiny new totals
if hastests:
self.setStatistic('total', total)
self.setStatistic('fails', fails)
self.setStatistic('errors', errors)
self.setStatistic('warnings', warnings)
self.setStatistic('skipped', skipped)
self.setStatistic('passed', passed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def saveConfig(self, request):
"""I save the config, and run check_config, potencially returning errors""" |
res = yield self.assertAllowed(request)
if res:
defer.returnValue(res)
request.setHeader('Content-Type', 'application/json')
if self._in_progress:
defer.returnValue(json.dumps({'success': False, 'errors': ['reconfig already in progress']}))
self._in_progress = True
cfg = json.loads(request.content.read())
if cfg != self._cfg:
try:
err = yield self.saveCfg(cfg)
except Exception as e: # noqa
err = [repr(e)]
if err is not None:
self._in_progress = False
yield self.saveCfg(self._cfg)
defer.returnValue(json.dumps({'success': False, 'errors': err}))
yield self.ep.master.reconfig()
defer.returnValue(json.dumps({'success': 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 anti_alias(map_in, steps):
""" Execute the anti_alias operation steps times on the given map """ |
height, width = map_in.shape
map_part = (2.0/11.0)*map_in
# notice how [-1/sqrt(3), -1/sqrt(3), -1/sqrt(3)] * [-1/sqrt(3), -1/sqrt(3), -1/sqrt(3)]^T
# equals [[1/3, 1/3, 1/3], [1/3, 1/3, 1/3], [1/3, 1/3, 1/3]]
# multiply that by (3/11) and we have the 2d kernel from the example above
# therefore the kernel is seperable
w = -1.0/numpy.sqrt(3.0)
kernel = [w, w, w]
def _anti_alias_step(original):
# cf. comments above fo the factor
# this also makes a copy which might actually be superfluous
result = original * (3.0/11.0)
# we need to handle boundary conditions by hand, unfortunately
# there might be a better way but this works (circular boundary)
# notice how we'll need to add 2 to width and height later
# because of this
result = numpy.append(result, [result[0,:]], 0)
result = numpy.append(result, numpy.transpose([result[:,0]]), 1)
result = numpy.insert(result, [0], [result[-2,:]],0)
result = numpy.insert(result, [0], numpy.transpose([result[:,-2]]), 1)
# with a seperable kernel we can convolve the rows first ...
for y in range(height+2):
result[y,1:-1] = numpy.convolve(result[y,:], kernel, 'valid')
# ... and then the columns
for x in range(width+2):
result[1:-1,x] = numpy.convolve(result[:,x], kernel, 'valid')
# throw away invalid values at the boundary
result = result[1:-1,1:-1]
result += map_part
return result
current = map_in
for i in range(steps):
current = _anti_alias_step(current)
return current |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def count_neighbours(mask, radius=1):
'''Count how many neighbours of a coordinate are set to one.
This uses the same principles as anti_alias, compare comments there.'''
height, width = mask.shape
f = 2.0*radius+1.0
w = -1.0/numpy.sqrt(f)
kernel = [w]*radius + [w] + [w]*radius
result = mask * f
for y in range(height):
result[y,:] = numpy.convolve(result[y,:], kernel, 'same')
for x in range(width):
result[:,x] = numpy.convolve(result[:, x], kernel, 'same')
return result - mask |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def average_colors(c1, c2):
''' Average the values of two colors together '''
r = int((c1[0] + c2[0])/2)
g = int((c1[1] + c2[1])/2)
b = int((c1[2] + c2[2])/2)
return (r, g, b) |
<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_normalized_elevation_array(world):
''' Convert raw elevation into normalized values between 0 and 255,
and return a numpy array of these values '''
e = world.layers['elevation'].data
ocean = world.layers['ocean'].data
mask = numpy.ma.array(e, mask=ocean) # only land
min_elev_land = mask.min()
max_elev_land = mask.max()
elev_delta_land = max_elev_land - min_elev_land
mask = numpy.ma.array(e, mask=numpy.logical_not(ocean)) # only ocean
min_elev_sea = mask.min()
max_elev_sea = mask.max()
elev_delta_sea = max_elev_sea - min_elev_sea
c = numpy.empty(e.shape, dtype=numpy.float)
c[numpy.invert(ocean)] = (e[numpy.invert(ocean)] - min_elev_land) * 127 / elev_delta_land + 128
c[ocean] = (e[ocean] - min_elev_sea) * 127 / elev_delta_sea
c = numpy.rint(c).astype(dtype=numpy.int32) # proper rounding
return c |
<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_biome_color_based_on_elevation(world, elev, x, y, rng):
''' This is the "business logic" for determining the base biome color in satellite view.
This includes generating some "noise" at each spot in a pixel's rgb value, potentially
modifying the noise based on elevation, and finally incorporating this with the base biome color.
The basic rules regarding noise generation are:
- Oceans have no noise added
- land tiles start with noise somewhere inside (-NOISE_RANGE, NOISE_RANGE) for each rgb value
- land tiles with high elevations further modify the noise by set amounts (to drain some of the
color and make the map look more like mountains)
The biome's base color may be interpolated with a predefined mountain brown color if the elevation is high enough.
Finally, the noise plus the biome color are added and returned.
rng refers to an instance of a random number generator used to draw the random samples needed by this function.
'''
v = world.biome_at((x, y)).name()
biome_color = _biome_satellite_colors[v]
# Default is no noise - will be overwritten if this tile is land
noise = (0, 0, 0)
if world.is_land((x, y)):
## Generate some random noise to apply to this pixel
# There is noise for each element of the rgb value
# This noise will be further modified by the height of this tile
noise = rng.randint(-NOISE_RANGE, NOISE_RANGE, size=3) # draw three random numbers at once
####### Case 1 - elevation is very high ########
if elev > HIGH_MOUNTAIN_ELEV:
# Modify the noise to make the area slightly brighter to simulate snow-topped mountains.
noise = add_colors(noise, HIGH_MOUNTAIN_NOISE_MODIFIER)
# Average the biome's color with the MOUNTAIN_COLOR to tint the terrain
biome_color = average_colors(biome_color, MOUNTAIN_COLOR)
####### Case 2 - elevation is high ########
elif elev > MOUNTAIN_ELEV:
# Modify the noise to make this tile slightly darker, especially draining the green
noise = add_colors(noise, MOUNTAIN_NOISE_MODIFIER)
# Average the biome's color with the MOUNTAIN_COLOR to tint the terrain
biome_color = average_colors(biome_color, MOUNTAIN_COLOR)
####### Case 3 - elevation is somewhat high ########
elif elev > HIGH_HILL_ELEV:
noise = add_colors(noise, HIGH_HILL_NOISE_MODIFIER)
####### Case 4 - elevation is a little bit high ########
elif elev > HILL_ELEV:
noise = add_colors(noise, HILL_NOISE_MODIFIER)
# There is also a minor base modifier to the pixel's rgb value based on height
modification_amount = int(elev / BASE_ELEVATION_INTENSITY_MODIFIER)
base_elevation_modifier = (modification_amount, modification_amount, modification_amount)
this_tile_color = add_colors(biome_color, noise, base_elevation_modifier)
return this_tile_color |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_water_flow(self, world, water_path):
"""Find the flow direction for each cell in heightmap""" |
# iterate through each cell
for x in range(world.width - 1):
for y in range(world.height - 1):
# search around cell for a direction
path = self.find_quick_path([x, y], world)
if path:
tx, ty = path
flow_dir = [tx - x, ty - y]
key = 0
for direction in DIR_NEIGHBORS_CENTER:
if direction == flow_dir:
water_path[y, x] = key
key += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def river_sources(world, water_flow, water_path):
"""Find places on map where sources of river can be found""" |
river_source_list = []
# Using the wind and rainfall data, create river 'seeds' by
# flowing rainfall along paths until a 'flow' threshold is reached
# and we have a beginning of a river... trickle->stream->river->sea
# step one: Using flow direction, follow the path for each cell
# adding the previous cell's flow to the current cell's flow.
# step two: We loop through the water flow map looking for cells
# above the water flow threshold. These are our river sources and
# we mark them as rivers. While looking, the cells with no
# out-going flow, above water flow threshold and are still
# above sea level are marked as 'sources'.
for y in range(0, world.height - 1):
for x in range(0, world.width - 1):
rain_fall = world.layers['precipitation'].data[y, x]
water_flow[y, x] = rain_fall
if water_path[y, x] == 0:
continue # ignore cells without flow direction
cx, cy = x, y # begin with starting location
neighbour_seed_found = False
# follow flow path to where it may lead
while not neighbour_seed_found:
# have we found a seed?
if world.is_mountain((cx, cy)) and water_flow[cy, cx] >= RIVER_TH:
# try not to create seeds around other seeds
for seed in river_source_list:
sx, sy = seed
if in_circle(9, cx, cy, sx, sy):
neighbour_seed_found = True
if neighbour_seed_found:
break # we do not want seeds for neighbors
river_source_list.append([cx, cy]) # river seed
break
# no path means dead end...
if water_path[cy, cx] == 0:
break # break out of loop
# follow path, add water flow from previous cell
dx, dy = DIR_NEIGHBORS_CENTER[water_path[cy, cx]]
nx, ny = cx + dx, cy + dy # calculate next cell
water_flow[ny, nx] += rain_fall
cx, cy = nx, ny # set current cell to next cell
return river_source_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 cleanUpFlow(self, river, world):
'''Validate that for each point in river is equal to or lower than the
last'''
celevation = 1.0
for r in river:
rx, ry = r
relevation = world.layers['elevation'].data[ry, rx]
if relevation <= celevation:
celevation = relevation
elif relevation > celevation:
world.layers['elevation'].data[ry, rx] = celevation
return river |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def findLowerElevation(self, source, world):
'''Try to find a lower elevation with in a range of an increasing
circle's radius and try to find the best path and return it'''
x, y = source
currentRadius = 1
maxRadius = 40
lowestElevation = world.layers['elevation'].data[y, x]
destination = []
notFound = True
isWrapped = False
wrapped = []
while notFound and currentRadius <= maxRadius:
for cx in range(-currentRadius, currentRadius + 1):
for cy in range(-currentRadius, currentRadius + 1):
rx, ry = x + cx, y + cy
# are we within bounds?
if not self.wrap and not world.contains((rx, ry)):
continue
# are we within a circle?
if not in_circle(currentRadius, x, y, rx, ry):
continue
rx, ry = overflow(rx, world.width), overflow(ry,
world.height)
# if utilities.outOfBounds([x+cx, y+cy], self.size):
# print "Fixed:",x ,y, rx, ry
elevation = world.layers['elevation'].data[ry, rx]
# have we found a lower elevation?
if elevation < lowestElevation:
lowestElevation = elevation
destination = [rx, ry]
notFound = False
if not world.contains((x + cx, y + cy)):
wrapped.append(destination)
currentRadius += 1
if destination in wrapped:
isWrapped = True
# print "Wrapped lower elevation found:", rx, ry, "!"
return isWrapped, 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 rivermap_update(self, river, water_flow, rivermap, precipitations):
"""Update the rivermap with the rainfall that is to become the waterflow""" |
isSeed = True
px, py = (0, 0)
for x, y in river:
if isSeed:
rivermap[y, x] = water_flow[y, x]
isSeed = False
else:
rivermap[y, x] = precipitations[y, x] + rivermap[py, px]
px, py = x, 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 draw_rivers_on_image(world, target, factor=1):
"""Draw only the rivers, it expect the background to be in place """ |
for y in range(world.height):
for x in range(world.width):
if world.is_land((x, y)) and (world.layers['river_map'].data[y, x] > 0.0):
for dx in range(factor):
for dy in range(factor):
target.set_pixel(x * factor + dx, y * factor + dy, (0, 0, 128, 255))
if world.is_land((x, y)) and (world.layers['lake_map'].data[y, x] != 0):
for dx in range(factor):
for dy in range(factor):
target.set_pixel(x * factor + dx, y * factor + dy, (0, 100, 128, 255)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def center_land(world):
"""Translate the map horizontally and vertically to put as much ocean as possible at the borders. It operates on elevation and plates map""" |
y_sums = world.layers['elevation'].data.sum(1) # 1 == sum along x-axis
y_with_min_sum = y_sums.argmin()
if get_verbose():
print("geo.center_land: height complete")
x_sums = world.layers['elevation'].data.sum(0) # 0 == sum along y-axis
x_with_min_sum = x_sums.argmin()
if get_verbose():
print("geo.center_land: width complete")
latshift = 0
world.layers['elevation'].data = numpy.roll(numpy.roll(world.layers['elevation'].data, -y_with_min_sum + latshift, axis=0), - x_with_min_sum, axis=1)
world.layers['plates'].data = numpy.roll(numpy.roll(world.layers['plates'].data, -y_with_min_sum + latshift, axis=0), - x_with_min_sum, axis=1)
if get_verbose():
print("geo.center_land: width complete") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def place_oceans_at_map_borders(world):
""" Lower the elevation near the border of the map """ |
ocean_border = int(min(30, max(world.width / 5, world.height / 5)))
def place_ocean(x, y, i):
world.layers['elevation'].data[y, x] = \
(world.layers['elevation'].data[y, x] * i) / ocean_border
for x in range(world.width):
for i in range(ocean_border):
place_ocean(x, i, i)
place_ocean(x, world.height - i - 1, i)
for y in range(world.height):
for i in range(ocean_border):
place_ocean(i, y, i)
place_ocean(world.width - i - 1, y, i) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def harmonize_ocean(ocean, elevation, ocean_level):
""" The goal of this function is to make the ocean floor less noisy. The underwater erosion should cause the ocean floor to be more uniform """ |
shallow_sea = ocean_level * 0.85
midpoint = shallow_sea / 2.0
ocean_points = numpy.logical_and(elevation < shallow_sea, ocean)
shallow_ocean = numpy.logical_and(elevation < midpoint, ocean_points)
elevation[shallow_ocean] = midpoint - ((midpoint - elevation[shallow_ocean]) / 5.0)
deep_ocean = numpy.logical_and(elevation > midpoint, ocean_points)
elevation[deep_ocean] = midpoint + ((elevation[deep_ocean] - midpoint) / 5.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 _always_strings(env_dict):
""" On Windows and Python 2, environment dictionaries must be strings and not unicode. """ |
if IS_WINDOWS or PY2:
env_dict.update((key, str(value)) for (key, value) in env_dict.items())
return env_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compat_stat(path):
""" Generate stat as found on Python 3.2 and later. """ |
stat = os.stat(path)
info = get_file_info(path)
# rewrite st_ino, st_dev, and st_nlink based on file info
return nt.stat_result(
(stat.st_mode,) +
(info.file_index, info.volume_serial_number, info.number_of_links) +
stat[4:]
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scm_find_files(path, scm_files, scm_dirs):
""" setuptools compatible file finder that follows symlinks - path: the root directory from which to search - scm_files: set of scm controlled files and symlinks (including symlinks to directories) - scm_dirs: set of scm controlled directories (including directories containing no scm controlled files) scm_files and scm_dirs must be absolute with symlinks resolved (realpath), with normalized case (normcase) Spec here: http://setuptools.readthedocs.io/en/latest/setuptools.html#\ adding-support-for-revision-control-systems """ |
realpath = os.path.normcase(os.path.realpath(path))
seen = set()
res = []
for dirpath, dirnames, filenames in os.walk(realpath, followlinks=True):
# dirpath with symlinks resolved
realdirpath = os.path.normcase(os.path.realpath(dirpath))
def _link_not_in_scm(n):
fn = os.path.join(realdirpath, os.path.normcase(n))
return os.path.islink(fn) and fn not in scm_files
if realdirpath not in scm_dirs:
# directory not in scm, don't walk it's content
dirnames[:] = []
continue
if (
os.path.islink(dirpath)
and not os.path.relpath(realdirpath, realpath).startswith(os.pardir)
):
# a symlink to a directory not outside path:
# we keep it in the result and don't walk its content
res.append(os.path.join(path, os.path.relpath(dirpath, path)))
dirnames[:] = []
continue
if realdirpath in seen:
# symlink loop protection
dirnames[:] = []
continue
dirnames[:] = [dn for dn in dirnames if not _link_not_in_scm(dn)]
for filename in filenames:
if _link_not_in_scm(filename):
continue
# dirpath + filename with symlinks preserved
fullfilename = os.path.join(dirpath, filename)
if os.path.normcase(os.path.realpath(fullfilename)) in scm_files:
res.append(os.path.join(path, os.path.relpath(fullfilename, path)))
seen.add(realdirpath)
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 session(self):
""" Creates a context with an open SQLAlchemy session. """ |
engine = self.engine
connection = engine.connect()
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=True, bind=engine))
yield db_session
db_session.close()
connection.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 kill(arg1, arg2):
"""Stops a proces that contains arg1 and is filtered by arg2 """ |
from subprocess import Popen, PIPE
# Wait until ready
t0 = time.time()
# Wait no more than these many seconds
time_out = 30
running = True
while running and time.time() - t0 < time_out:
if os.name == 'nt':
p = Popen(
'tasklist | find "%s"' % arg1,
shell=True,
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
close_fds=False)
else:
p = Popen(
'ps aux | grep %s' % arg1,
shell=True,
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
close_fds=True)
lines = p.stdout.readlines()
running = False
for line in lines:
# this kills all java.exe and python including self in windows
if ('%s' % arg2 in line) or (os.name == 'nt'
and '%s' % arg1 in line):
running = True
# Get pid
fields = line.strip().split()
info('Stopping %s (process number %s)' % (arg1, fields[1]))
if os.name == 'nt':
kill = 'taskkill /F /PID "%s"' % fields[1]
else:
kill = 'kill -9 %s 2> /dev/null' % fields[1]
os.system(kill)
# Give it a little more time
time.sleep(1)
else:
pass
if running:
raise Exception('Could not stop %s: '
'Running processes are\n%s' % (arg1, '\n'.join(
[l.strip() for l in 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 sign(self, consumer_secret, method, url, oauth_token_secret=None, **params):
"""Create a signature using HMAC-SHA1.""" |
# build the url the same way aiohttp will build the query later on
# cf https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client.py#L151
# and https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client_reqrep.py#L81
url = yarl.URL(url).with_query(sorted(params.items()))
url, params = str(url).split('?', 1)
method = method.upper()
signature = b"&".join(map(self._escape, (method, url, params)))
key = self._escape(consumer_secret) + b"&"
if oauth_token_secret:
key += self._escape(oauth_token_secret)
hashed = hmac.new(key, signature, sha1)
return base64.b64encode(hashed.digest()).decode() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign(self, consumer_secret, method, url, oauth_token_secret=None, **params):
"""Create a signature using PLAINTEXT.""" |
key = self._escape(consumer_secret) + b'&'
if oauth_token_secret:
key += self._escape(oauth_token_secret)
return key.decode() |
<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_url(self, url):
"""Build provider's url. Join with base_url part if needed.""" |
if self.base_url and not url.startswith(('http://', 'https://')):
return urljoin(self.base_url, url)
return url |
<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 _request(self, method, url, loop=None, timeout=None, **kwargs):
"""Make a request through AIOHTTP.""" |
session = self.session or aiohttp.ClientSession(
loop=loop, conn_timeout=timeout, read_timeout=timeout)
try:
async with session.request(method, url, **kwargs) as response:
if response.status / 100 > 2:
raise web.HTTPBadRequest(
reason='HTTP status code: %s' % response.status)
if 'json' in response.headers.get('CONTENT-TYPE'):
data = await response.json()
else:
data = await response.text()
data = dict(parse_qsl(data))
return data
except asyncio.TimeoutError:
raise web.HTTPBadRequest(reason='HTTP Timeout')
finally:
if not self.session and not session.closed:
await session.close() |
<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 user_info(self, loop=None, **kwargs):
"""Load user information from provider.""" |
if not self.user_info_url:
raise NotImplementedError(
'The provider doesnt support user_info method.')
data = await self.request('GET', self.user_info_url, loop=loop, **kwargs)
user = User(**dict(self.user_parse(data)))
return user, 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 request(self, method, url, params=None, **aio_kwargs):
"""Make a request to provider.""" |
oparams = {
'oauth_consumer_key': self.consumer_key,
'oauth_nonce': sha1(str(RANDOM()).encode('ascii')).hexdigest(),
'oauth_signature_method': self.signature.name,
'oauth_timestamp': str(int(time.time())),
'oauth_version': self.version,
}
oparams.update(params or {})
if self.oauth_token:
oparams['oauth_token'] = self.oauth_token
url = self._get_url(url)
if urlsplit(url).query:
raise ValueError(
'Request parameters should be in the "params" parameter, '
'not inlined in the URL')
oparams['oauth_signature'] = self.signature.sign(
self.consumer_secret, method, url,
oauth_token_secret=self.oauth_token_secret, **oparams)
self.logger.debug("%s %s", url, oparams)
return self._request(method, url, params=oparams, **aio_kwargs) |
<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_request_token(self, loop=None, **params):
"""Get a request_token and request_token_secret from OAuth1 provider.""" |
params = dict(self.params, **params)
data = await self.request('GET', self.request_token_url, params=params, loop=loop)
self.oauth_token = data.get('oauth_token')
self.oauth_token_secret = data.get('oauth_token_secret')
return self.oauth_token, self.oauth_token_secret, data |
<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_access_token(self, oauth_verifier, request_token=None, loop=None, **params):
"""Get access_token from OAuth1 provider. :returns: (access_token, access_token_secret, provider_data) """ |
# Possibility to provide REQUEST DATA to the method
if not isinstance(oauth_verifier, str) and self.shared_key in oauth_verifier:
oauth_verifier = oauth_verifier[self.shared_key]
if request_token and self.oauth_token != request_token:
raise web.HTTPBadRequest(
reason='Failed to obtain OAuth 1.0 access token. '
'Request token is invalid')
data = await self.request('POST', self.access_token_url, params={
'oauth_verifier': oauth_verifier, 'oauth_token': request_token}, loop=loop)
self.oauth_token = data.get('oauth_token')
self.oauth_token_secret = data.get('oauth_token_secret')
return self.oauth_token, self.oauth_token_secret, 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 get_authorize_url(self, **params):
"""Return formatted authorize URL.""" |
params = dict(self.params, **params)
params.update({'client_id': self.client_id, 'response_type': 'code'})
return self.authorize_url + '?' + urlencode(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, url, params=None, headers=None, access_token=None, **aio_kwargs):
"""Request OAuth2 resource.""" |
url = self._get_url(url)
params = params or {}
access_token = access_token or self.access_token
if access_token:
if isinstance(params, list):
if self.access_token_key not in dict(params):
params.append((self.access_token_key, access_token))
else:
params[self.access_token_key] = access_token
headers = headers or {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
return self._request(method, url, params=params, headers=headers, **aio_kwargs) |
<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_access_token(self, code, loop=None, redirect_uri=None, **payload):
"""Get an access_token from OAuth provider. :returns: (access_token, provider_data) """ |
# Possibility to provide REQUEST DATA to the method
payload.setdefault('grant_type', 'authorization_code')
payload.update({'client_id': self.client_id, 'client_secret': self.client_secret})
if not isinstance(code, str) and self.shared_key in code:
code = code[self.shared_key]
payload['refresh_token' if payload['grant_type'] == 'refresh_token' else 'code'] = code
redirect_uri = redirect_uri or self.params.get('redirect_uri')
if redirect_uri:
payload['redirect_uri'] = redirect_uri
self.access_token = None
data = await self.request('POST', self.access_token_url, data=payload, loop=loop)
try:
self.access_token = data['access_token']
except KeyError:
self.logger.error(
'Error when getting the access token.\nData returned by OAuth server: %r',
data,
)
raise web.HTTPBadRequest(reason='Failed to obtain OAuth access token.')
return self.access_token, data |
<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 user_info(self, params=None, **kwargs):
"""Facebook required fields-param.""" |
params = params or {}
params[
'fields'] = 'id,email,first_name,last_name,name,link,locale,' \
'gender,location'
return await super(FacebookClient, self).user_info(params=params, **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 hijack_require_http_methods(fn):
""" Wrapper for "require_http_methods" decorator. POST required by default, GET can optionally be allowed """ |
required_methods = ['POST']
if hijack_settings.HIJACK_ALLOW_GET_REQUESTS:
required_methods.append('GET')
return require_http_methods(required_methods)(fn) |
<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_authorized_default(hijacker, hijacked):
"""Checks if the user has the correct permission to Hijack another user. By default only superusers are allowed to hijack. An exception is made to allow staff members to hijack when HIJACK_AUTHORIZE_STAFF is enabled in the Django settings. By default it prevents staff users from hijacking other staff users. This can be disabled by enabling the HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF setting in the Django settings. Staff users can never hijack superusers. """ |
if hijacker.is_superuser:
return True
if hijacked.is_superuser:
return False
if hijacker.is_staff and hijack_settings.HIJACK_AUTHORIZE_STAFF:
if hijacked.is_staff and not hijack_settings.HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF:
return False
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 is_authorized(hijack, hijacked):
'''
Evaluates the authorization check specified in settings
'''
authorization_check = import_string(hijack_settings.HIJACK_AUTHORIZATION_CHECK)
return authorization_check(hijack, hijacked) |
<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_downloadable(self, response):
'''
Checks whether the response object is a html page
or a likely downloadable file.
Intended to detect error pages or prompts
such as kaggle's competition rules acceptance prompt.
Returns True if the response is a html page. False otherwise.
'''
content_type = response.headers.get('Content-Type', '')
content_disp = response.headers.get('Content-Disposition', '')
if 'text/html' in content_type and 'attachment' not in content_disp:
# This response is a html file
# which is not marked as an attachment,
# so we likely hit a rules acceptance prompt
return False
return 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 count(self):
""" Returns the number of records the query would yield""" |
self.request_params.update({'sysparm_count': True})
response = self.session.get(self._get_stats_url(),
params=self._get_formatted_query(fields=list(),
limit=None,
order_by=list(),
offset=None))
content = self._get_content(response)
return int(content['stats']['count']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _all_inner(self, fields, limit, order_by, offset):
"""Yields all records for the query and follows links if present on the response after validating :return: List of records with content """ |
response = self.session.get(self._get_table_url(),
params=self._get_formatted_query(fields, limit, order_by, offset))
yield self._get_content(response)
while 'next' in response.links:
self.url_link = response.links['next']['url']
response = self.session.get(self.url_link)
yield self._get_content(response) |
<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_one(self, fields=list()):
"""Convenience function for queries returning only one result. Validates response before returning. :param fields: List of fields to return in the result :raise: :MultipleResults: if more than one match is found :return: - Record content """ |
response = self.session.get(self._get_table_url(),
params=self._get_formatted_query(fields, limit=None, order_by=list(), offset=None))
content = self._get_content(response)
l = len(content)
if l > 1:
raise MultipleResults('Multiple results for get_one()')
if len(content) == 0:
return {}
return content[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 insert(self, payload):
"""Inserts a new record with the payload passed as an argument :param payload: The record to create (dict) :return: - Created record """ |
response = self.session.post(self._get_table_url(), data=json.dumps(payload))
return self._get_content(response) |
<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(self):
"""Deletes the queried record and returns response content after response validation :raise: :NoResults: if query returned no results :NotImplementedError: if query returned more than one result (currently not supported) :return: - Delete response content (Generally always {'Success': True}) """ |
try:
result = self.get_one()
if 'sys_id' not in result:
raise NoResults()
except MultipleResults:
raise MultipleResults("Deletion of multiple records is not supported")
except NoResults as e:
e.args = ('Cannot delete a non-existing record',)
raise
response = self.session.delete(self._get_table_url(sys_id=result['sys_id']))
return self._get_content(response) |
<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(self, payload):
"""Updates the queried record with `payload` and returns the updated record after validating the response :param payload: Payload to update the record with :raise: :NoResults: if query returned no results :MultipleResults: if query returned more than one result (currently not supported) :return: - The updated record """ |
try:
result = self.get_one()
if 'sys_id' not in result:
raise NoResults()
except MultipleResults:
raise MultipleResults("Update of multiple records is not supported")
except NoResults as e:
e.args = ('Cannot update a non-existing record',)
raise
if not isinstance(payload, dict):
raise InvalidUsage("Update payload must be of type dict")
response = self.session.put(self._get_table_url(sys_id=result['sys_id']), data=json.dumps(payload))
return self._get_content(response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone(self, reset_fields=list()):
"""Clones the queried record :param reset_fields: Fields to reset :raise: :NoResults: if query returned no results :MultipleResults: if query returned more than one result (currently not supported) :UnexpectedResponse: informs the user about what likely went wrong :return: - The cloned record """ |
if not isinstance(reset_fields, list):
raise InvalidUsage("reset_fields must be a `list` of fields")
try:
response = self.get_one()
if 'sys_id' not in response:
raise NoResults()
except MultipleResults:
raise MultipleResults('Cloning multiple records is not supported')
except NoResults as e:
e.args = ('Cannot clone a non-existing record',)
raise
payload = {}
# Iterate over fields in the result
for field in response:
# Ignore fields in reset_fields
if field in reset_fields:
continue
item = response[field]
# Check if the item is of type dict and has a sys_id ref (value)
if isinstance(item, dict) and 'value' in item:
payload[field] = item['value']
else:
payload[field] = item
try:
return self.insert(payload)
except UnexpectedResponse as e:
if e.status_code == 403:
# User likely attempted to clone a record without resetting a unique field
e.args = ('Unable to create clone. Make sure unique fields has been reset.',)
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach(self, file):
"""Attaches the queried record with `file` and returns the response after validating the response :param file: File to attach to the record :raise: :NoResults: if query returned no results :MultipleResults: if query returned more than one result (currently not supported) :return: - The attachment record metadata """ |
try:
result = self.get_one()
if 'sys_id' not in result:
raise NoResults()
except MultipleResults:
raise MultipleResults('Attaching a file to multiple records is not supported')
except NoResults:
raise NoResults('Attempted to attach file to a non-existing record')
if not os.path.isfile(file):
raise InvalidUsage("Attachment '%s' must be an existing regular file" % file)
response = self.session.post(
self._get_attachment_url('upload'),
data={
'table_name': self.table,
'table_sys_id': result['sys_id'],
'file_name': ntpath.basename(file)
},
files={'file': open(file, 'rb')},
headers={'content-type': None} # Temporarily override header
)
return self._get_content(response) |
<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_content(self, response):
"""Checks for errors in the response. Returns response content, in bytes. :param response: response object :raise: :UnexpectedResponse: if the server responded with an unexpected response :return: - ServiceNow response content """ |
method = response.request.method
self.last_response = response
server_error = {
'summary': None,
'details': None
}
try:
content_json = response.json()
if 'error' in content_json:
e = content_json['error']
if 'message' in e:
server_error['summary'] = e['message']
if 'detail' in e:
server_error['details'] = e['detail']
except ValueError:
content_json = {}
if method == 'DELETE':
# Make sure the delete operation returned the expected response
if response.status_code == 204:
return {'success': True}
else:
raise UnexpectedResponse(
204, response.status_code, method,
server_error['summary'], server_error['details']
)
# Make sure the POST operation returned the expected response
elif method == 'POST' and response.status_code != 201:
raise UnexpectedResponse(
201, response.status_code, method,
server_error['summary'], server_error['details']
)
# It seems that Helsinki and later returns status 200 instead of 404 on empty result sets
if ('result' in content_json and len(content_json['result']) == 0) or response.status_code == 404:
if self.raise_on_empty is True:
raise NoResults('Query yielded no results')
elif 'error' in content_json:
raise UnexpectedResponse(
200, response.status_code, method,
server_error['summary'], server_error['details']
)
if 'result' not in content_json:
raise MissingResult("The request was successful but the content didn't contain the expected 'result'")
return content_json['result'] |
<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_session(self, session):
"""Creates a new session with basic auth, unless one was provided, and sets headers. :param session: (optional) Session to re-use :return: - :class:`requests.Session` object """ |
if not session:
logger.debug('(SESSION_CREATE) User: %s' % self._user)
s = requests.Session()
s.auth = HTTPBasicAuth(self._user, self._password)
else:
logger.debug('(SESSION_CREATE) Object: %s' % session)
s = session
s.headers.update(
{
'content-type': 'application/json',
'accept': 'application/json',
'User-Agent': 'pysnow/%s' % pysnow.__version__
}
)
return 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 get(self, *args, **kwargs):
"""Fetches one or more records :return: - :class:`pysnow.Response` object """ |
self._parameters.query = kwargs.pop('query', {}) if len(args) == 0 else args[0]
self._parameters.limit = kwargs.pop('limit', 10000)
self._parameters.offset = kwargs.pop('offset', 0)
self._parameters.fields = kwargs.pop('fields', kwargs.pop('fields', []))
return self._get_response('GET', stream=kwargs.pop('stream', 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 update(self, query, payload):
"""Updates a record :param query: Dictionary, string or :class:`QueryBuilder` object :param payload: Dictionary payload :return: - Dictionary of the updated record """ |
if not isinstance(payload, dict):
raise InvalidUsage("Update payload must be of type dict")
record = self.get(query).one()
self._url = self._url_builder.get_appended_custom("/{0}".format(record['sys_id']))
return self._get_response('PUT', data=json.dumps(payload)) |
<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(self, query):
"""Deletes a record :param query: Dictionary, string or :class:`QueryBuilder` object :return: - Dictionary containing status of the delete operation """ |
record = self.get(query=query).one()
self._url = self._url_builder.get_appended_custom("/{0}".format(record['sys_id']))
return self._get_response('DELETE').one() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def custom(self, method, path_append=None, headers=None, **kwargs):
"""Creates a custom request :param method: HTTP method :param path_append: (optional) append path to resource.api_path :param headers: (optional) Dictionary of headers to add or override :param kwargs: kwargs to pass along to :class:`requests.Request` :return: - :class:`pysnow.Response` object """ |
if headers:
self._session.headers.update(headers)
if path_append is not None:
try:
self._url = self._url_builder.get_appended_custom(path_append)
except InvalidUsage:
raise InvalidUsage("Argument 'path_append' must be a string in the following format: "
"/path-to-append[/.../...]")
return self._get_response(method, **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 attachments(self):
"""Provides an `Attachment` API for this resource. Enables easy listing, deleting and creating new attachments. :return: Attachment object """ |
resource = copy(self)
resource._url_builder = URLBuilder(self._base_url, self._base_path, '/attachment')
path = self._api_path.strip('/').split('/')
if path[0] != 'table':
raise InvalidUsage('The attachment API can only be used with the table API')
return Attachment(resource, path[1]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, path_append=None, headers=None, **kwargs):
"""Create a custom request :param method: HTTP method to use :param path_append: (optional) relative to :attr:`api_path` :param headers: (optional) Dictionary of headers to add or override :param kwargs: kwargs to pass along to :class:`requests.Request` :return: - :class:`Response` object """ |
return self._request.custom(method, path_append=path_append, headers=headers, **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 _get_buffered_response(self):
"""Returns a buffered response :return: Buffered response """ |
response = self._get_response()
if response.request.method == 'DELETE' and response.status_code == 204:
return [{'status': 'record deleted'}], 1
result = self._response.json().get('result', None)
if result is None:
raise MissingResult('The expected `result` key was missing in the response. Cannot continue')
length = 0
if isinstance(result, list):
length = len(result)
elif isinstance(result, dict):
result = [result]
length = 1
return result, length |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
"""Returns a chained generator response containing all matching records :return: - Iterable response """ |
if self._stream:
return chain.from_iterable(self._get_streamed_response())
return self._get_buffered_response()[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 first(self):
"""Return the first record or raise an exception if the result doesn't contain any data :return: - Dictionary containing the first item in the response content :raise: - NoResults: If no results were found """ |
if not self._stream:
raise InvalidUsage('first() is only available when stream=True')
try:
content = next(self.all())
except StopIteration:
raise NoResults("No records found")
return content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def one(self):
"""Return exactly one record or raise an exception. :return: - Dictionary containing the only item in the response content :raise: - MultipleResults: If more than one records are present in the content - NoResults: If the result is empty """ |
result, count = self._get_buffered_response()
if count == 0:
raise NoResults("No records found")
elif count > 1:
raise MultipleResults("Expected single-record result, got multiple")
return result[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 upload(self, *args, **kwargs):
"""Convenience method for attaching files to a fetched record :param args: args to pass along to `Attachment.upload` :param kwargs: kwargs to pass along to `Attachment.upload` :return: upload response object """ |
return self._resource.attachments.upload(self['sys_id'], *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 get(self, sys_id=None, limit=100):
"""Returns a list of attachments :param sys_id: record sys_id to list attachments for :param limit: override the default limit of 100 :return: list of attachments """ |
if sys_id:
return self.resource.get(query={'table_sys_id': sys_id, 'table_name': self.table_name}).all()
return self.resource.get(query={'table_name': self.table_name}, limit=limit).all() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.