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 subjects_get(self, resource_url):
"""Get handle for subject resource at given Url. Parameters resource_url : string Url for subject resource at SCO-API Retur... |
# Get resource directory, Json representation, active flag, and cache id
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
# Create subject handle. Will raise an exception if resource is not
# in cache and cannot be downloaded.
subject = SubjectHandle(obj_js... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subjects_list(self, api_url=None, offset=0, limit=-1, properties=None):
"""Get list of subject resources from a SCO-API. Parameters api_url : string, optiona... |
# Get subject listing Url for given SCO-API and return the retrieved
# resource listing
return sco.get_resource_listing(
self.get_api_references(api_url)[sco.REF_SUBJECTS_LIST],
offset,
limit,
properties
) |
<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_disposable(clientInfo, config = {}):
""" Create a new disposable client. """ |
response = requests.put(
_format_url(
_extend(DEFAULT_CONFIG, config),
OAUTH2_ROOT + 'disposable'),
json = clientInfo)
if response.status_code != 200:
return None
else:
body = response.json()
return Blotre({
'client_id': bod... |
<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_existing_disposable_app(file, clientInfo, conf):
""" Attempt to load an existing """ |
if not os.path.isfile(file):
return None
else:
data = None
with open(file, 'r') as f:
data = json.load(f)
if not 'client' in data or not 'creds' in data:
return None
return _BlotreDisposableApp(file,
data['client'],
creds =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _try_redeem_disposable_app(file, client):
""" Attempt to redeem a one time code registred on the client. """ |
redeemedClient = client.redeem_onetime_code(None)
if redeemedClient is None:
return None
else:
return _BlotreDisposableApp(file,
redeemedClient.client,
creds = redeemedClient.creds,
config = redeemedClient.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_app_is_valid(client):
""" Check to see if the app has valid creds. """ |
try:
if 'refresh_token' in client.creds:
client.exchange_refresh_token()
else:
existing.get_token_info()
return True
except TokenEndpointError as e:
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 create_disposable_app(clientInfo, config={}):
""" Use an existing disposable app if data exists or create a new one and persist the data. """ |
file = _get_disposable_app_filename(clientInfo)
existing = _get_existing_disposable_app(file, clientInfo, config)
if existing:
if _check_app_is_valid(existing):
return existing
else:
print("Existing client has expired, must recreate.")
return _create_new... |
<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_creds(self, newCreds):
"""Manually update the current creds.""" |
self.creds = newCreds
self.on_creds_changed(newCreds)
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 normalize_uri(self, uri):
"""Convert a stream path into it's normalized form.""" |
return urllib.quote(
re.sub(r"\s", '+', uri.strip().lower()),
safe = '~@#$&()*!+=:),.?/\'') |
<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_authorization_url(self):
"""Get the authorization Url for the current client.""" |
return self._format_url(
OAUTH2_ROOT + 'authorize',
query = {
'response_type': 'code',
'client_id': self.client.get('client_id', ''),
'redirect_uri': self.client.get('redirect_uri', '')
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _access_token_endpoint(self, grantType, extraParams={}):
""" Base exchange of data for an access_token. """ |
response = requests.post(
self._format_url(OAUTH2_ROOT + 'access_token'),
data = _extend({
'grant_type': grantType,
'client_id': self.client.get('client_id', ''),
'client_secret': self.client.get('client_secret', ''),
'redi... |
<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_token_info(self):
""" Get information about the current access token. """ |
response = requests.get(
self._format_url(OAUTH2_ROOT + 'token_info', {
'token': self.creds['access_token']
}))
data = response.json()
if response.status_code != 200:
raise _token_error_from_data(data)
else:
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_auth_headers(self, base):
"""Attach the acces_token to a request.""" |
if 'access_token' in self.creds:
return _extend(base, {
'authorization': 'Bearer ' + self.creds['access_token']
})
return base |
<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_expired_response(self, response):
""" Check if the response failed because of an expired access token. """ |
if response.status_code != 401:
return False
challenge = response.headers.get('www-authenticate', '')
return 'error="invalid_token"' in challenge |
<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, type, path, args, noRetry=False):
""" Make a request to Blot're. Attempts to reply the request if it fails due to an expired access token... |
response = getattr(requests, type)(path, headers = self._add_auth_headers(_JSON_HEADERS), **args)
if response.status_code == 200 or response.status_code == 201:
return response.json()
elif not noRetry and self._is_expired_response(response) \
and 'refresh_token' in self.cr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, path, body):
"""PUT request.""" |
return self._make_request('put',
self._format_url(API_ROOT + path), {
'json': 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 get_child(self, streamId, childId, options={}):
"""Get the child of a stream.""" |
return self.get('stream/' + streamId + '/children/' + childId, options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _persist(self):
"""Persist client data.""" |
with open(self.file, 'w') as f:
json.dump({
'client': self.client,
'creds': self.creds,
'config': self.config
}, 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 options(self, parser, env=os.environ):
"""Handle parsing additional command-line options""" |
super(PerfDumpPlugin, self).options(parser, env=env)
parser.add_option("", "--perfdump-html", dest="perfdump_html_file",
help="Set destination for HTML report output") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, options, conf):
"""Configure this plugin using the given options""" |
super(PerfDumpPlugin, self).configure(options, conf)
if not self.enabled:
return
try:
self.html_output_file = options.perfdump_html_file
except:
pass
self.db = SqliteConnection.get(self.database_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 report(self, stream):
"""Displays the slowest tests""" |
self.db.commit()
stream.writeln()
self.draw_header(stream, "10 SLOWEST SETUPS")
self.display_slowest_setups(stream)
stream.writeln()
self.draw_header(stream, "10 SLOWEST TESTS")
self.display_slowest_tests(stream)
stream.writeln()
if self.html_o... |
<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_header(self, stream, header):
"""Draw header with underline""" |
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() |
<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(self, sought, view='lemma'):
'''
Returns a word instance for the hit if the "sought" word is found in the text.
Per default the "lemma" view of the words is compared.
You can specify the desired view with the optional "view" option.
'''
hits = []
for sent... |
<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(self, sought, view='lemma'):
'''
Returns a word instance for the hit if the "sought" word is found in the sentence.
Per default the "lemma" view of the words is compared.
You can specify the desired view with the optional "view" option.
'''
for word in self.wordl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def word(self, position):
'''
Returns the word instance at the given position in the sentence, None if not found.
'''
if 0 <= position < len(self.wordlist):
return self.wordlist[position]
else:
log.warn('position "{}" is not in sentence of length "{}"!'.fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def neighbors(self):
'''
Returns the left and right neighbors as Word instance.
If the word is the first one in the sentence only the right neighbor is returned and vice versa.
'''
if len(self._sentence) == 1:
return {
'left': None,
'ri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stdrepr_iterable(self, obj, *, cls=None, before=None, after=None):
""" Helper function to represent iterables. StdHRepr calls this on lists, tuples, sets and... |
if cls is None:
cls = f'hrepr-{obj.__class__.__name__}'
children = [self(a) for a in obj]
return self.titled_box((before, after), children, 'h', 'h')[cls] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stdrepr_object(self, title, elements, *, cls=None, short=False, quote_string_keys=False, delimiter=None):
""" Helper function to represent objects. Arguments... |
H = self.H
if delimiter is None and quote_string_keys is True:
delimiter = ' ↦ '
def wrap(x):
if not quote_string_keys and isinstance(x, str):
return x
else:
return self(x)
if short:
contents = []
... |
<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_matches(text):
r"""Find matching files for text. For this completer to function in Unix systems, the readline module must not treat \ and / as delimiter... |
path = os.path.expanduser(text)
if os.path.isdir(path) and not path.endswith('/'):
return [ text + '/' ]
pattern = path + '*'
is_implicit_cwd = not (path.startswith('/') or path.startswith('./'))
if is_implicit_cwd:
pattern = './' + pattern
rawlist = glob.glob(pattern)
ret ... |
<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(ctx, dname, site):
""" Launches a MySQL CLI session for the database of the specified IPS installation. """ |
assert isinstance(ctx, Context)
log = logging.getLogger('ipsv.mysql')
dname = domain_parse(dname).hostname
domain = Session.query(Domain).filter(Domain.name == dname).first()
# No such domain
if not domain:
click.secho('No such domain: {dn}'.format(dn=dname), fg='red', bold=True, err=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def target_query(plugin, port, location):
""" prepared ReQL for target """ |
return ((r.row[PLUGIN_NAME_KEY] == plugin) &
(r.row[PORT_FIELD] == port) &
(r.row[LOCATION_FIELD] == location)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enums(*names):
"""Returns a set of `EnumValue` objects with specified names and optionally orders. Values in an enumeration must have unique names and be eit... |
if len(names) != len(list(set(names))):
raise TypeError("Names in an enumeration must be unique")
item_types = set(True if isinstance(x, tuple) else False for x in names)
if len(item_types) == 2:
raise TypeError("Mixing of ordered and unordered enumeration items is not allowed")
else:
... |
<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, args=None):
"""Applicatin starting point. This will run the associated method/function/module or print a help list if it's an unknown keyword or th... |
# TODO: Add tests to how command line arguments are passed in
raw_args = self.__parser.parse_args(args=args)
args = vars(raw_args)
cmd = args.pop('cmd')
if hasattr(cmd, '__call__'):
cmd(**args) |
<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_seconds(string):
""" Converts a human readable time string into seconds. Accepts: - 's': seconds - 'm': minutes - 'h': hours - 'd': days Examples: 90 300 ... |
units = {
's': 1,
'm': 60,
'h': 60 * 60,
'd': 60 * 60 * 24
}
match = re.search(r'(?:(?P<d>\d+)d)?(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?', string)
if not match or not any(match.groups()):
raise ValueError
total = 0
for unit, seconds in units.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice_reStructuredText(input, output):
""" Slices given reStructuredText file. :param input: ReStructuredText file to slice. :type input: unicode :param outp... |
LOGGER.info("{0} | Slicing '{1}' file!".format(slice_reStructuredText.__name__, input))
file = File(input)
file.cache()
slices = OrderedDict()
for i, line in enumerate(file.content):
search = re.search(r"^\.\. \.(\w+)", line)
if search:
slices[search.groups()[0]] = 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 get(self):
""" Fetch all licenses associated with our account @rtype: list of LicenseMeta """ |
response = requests.get(self.URL, cookies=self.cookiejar)
self.log.debug('Response code: %s', response.status_code)
if response.status_code != 200:
raise HtmlParserError
soup = BeautifulSoup(response.text, "html.parser")
com_pattern = re.compile('\((.+)\)')
... |
<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_status(system_key):
""" Get Undergraduate application status @return ApplicationStatus object @InvalidSystemKey if system_key is not valid """ |
if invalid_system_key(system_key):
raise InvalidSystemKey(
"Invalid system key in get_app_status({})".format(system_key))
url = get_appstatus_url(system_key)
response = DAO.getURL(url, {})
response_data = str(response.data)
if response.status != 200:
raise DataFailureEx... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hint(invertible=True, callable=None, **hints):
""" A decorator that can optionally hang datanommer hints on a rule. """ |
def wrapper(fn):
# Hang hints on fn.
fn.hints = hints
fn.hinting_invertible = invertible
fn.hinting_callable = callable
return fn
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gather_hinting(config, rules, valid_paths):
""" Construct hint arguments for datanommer from a list of rules. """ |
hinting = collections.defaultdict(list)
for rule in rules:
root, name = rule.code_path.split(':', 1)
info = valid_paths[root][name]
if info['hints-callable']:
# Call the callable hint to get its values
result = info['hints-callable'](config=config, **rule.argu... |
<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_feed_list(feed, amount=None, list_class=None, li_class=None, list_type='ul'):
"""Generates a HTML list with items from a feed :param feed: The feed ... |
if feed.feed_type == 'twitter':
ret = ['<%s class="%s">' % (list_type, list_class or 'tweet-list')]
tweets = feed.tweets.all()
if amount:
if not int(amount):
raise ValueError('Amount must be a number')
tweets = tweets[:amount]
for t in tweets... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunks(f, chunk_size=None):
""" Read the file and yield chucks of ``chunk_size`` bytes. """ |
if not chunk_size:
chunk_size = 64 * 2 ** 10
if hasattr(f, "seek"):
f.seek(0)
while True:
data = f.read(chunk_size)
if not data:
break
yield 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 save(self, name, content):
""" Saves new content to the file specified by name. The content should be a proper File object, ready to be read from the beginni... |
# Get the proper name for the file, as it will actually be saved.
if name is None:
name = content.name
name = self.get_available_name(name)
name = self._save(name, content)
# Store filenames with forward slashes, even on Windows
return name.replace("\\", "/... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_banner(filename: str, template: str = DEFAULT_BANNER_TEMPLATE) -> None: """ Print text file to output. :param filename: Which file to print. :param temp... |
if not os.path.isfile(filename):
logger.warning("Can't find logo banner at %s", filename)
return
with open(filename, "r") as f:
banner = f.read()
formatted_banner = template.format(banner)
print(formatted_banner) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def repr_feature(feature, max_keys=100, indent=8, lexigraphic=False):
'''
generate a pretty-printed string for a feature
Currently implemented:
* StringCounter
@max_keys: truncate long counters
@indent: indent multi-line displays by this many spaces
@lexigraphic: instead of sorting cou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def only_specific_multisets(ent, multisets_to_show):
'''
returns a pretty-printed string for specific features in a FeatureCollection
'''
out_str = []
for mset_name in multisets_to_show:
for key, count in ent[mset_name].items():
out_str.append( '%s - %d: %s' % (mset_name, 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 tolerate(substitute=None, exceptions=None, switch=DEFAULT_TOLERATE_SWITCH):
""" A function decorator which makes a function fail silently To disable fail sil... |
def decorator(fn):
@wraps(fn)
def inner(*args, **kwargs):
if getattr(tolerate, 'disabled', False):
# the function has disabled so call normally.
return fn(*args, **kwargs)
if switch is not None:
status, args, kwargs = switch(*a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, action, payload):
"""Emit action with payload via `requests.post`.""" |
url = self.get_emit_api(action)
headers = {
'User-Agent': 'rio/%s' % VERSION,
'X-Rio-Protocol': '1',
}
args = dict(
url=url,
json=payload,
headers=headers,
timeout=self.timeout,
)
resp = requests.pos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_and_collapse(self):
"""Actually compile the requested regex""" |
self._real_regex = self._real_re_compile(*self._regex_args,
**self._regex_kwargs)
for attr in self._regex_attributes_to_copy:
setattr(self, attr, getattr(self._real_regex, attr)) |
<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_params(func, *args, **kwargs):
"""Turn an argument list into a dictionary. :arg function func: A function. :arg list *args: Positional arguments of `fun... |
params = dict(zip(func.func_code.co_varnames[:len(args)], args))
if func.func_defaults:
params.update(dict(zip(
func.func_code.co_varnames[-len(func.func_defaults):],
func.func_defaults)))
params.update(kwargs)
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 _check_type(name, obj, expected_type):
""" Raise a TypeError if object is not of expected type """ |
if not isinstance(obj, expected_type):
raise TypeError(
'"%s" must be an a %s' % (name, expected_type.__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 _import_module(module_name):
""" Imports the module dynamically _import_module('foo.bar') calls: __import__('foo.bar', globals(), locals(), ['bar', ], 0) """ |
fromlist = []
dot_position = module_name.rfind('.')
if dot_position > -1:
fromlist.append(
module_name[dot_position+1:len(module_name)]
)
# Import module
module = __import__(module_name, globals(), locals(), fromlist, 0)
return module |
<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(self, module_name, class_name, args=None, kwargs=None, factory_method=None, factory_args=None, factory_kwargs=None, static=False, calls=None):
""" Ini... |
if args is None:
args = []
if kwargs is None:
kwargs = {}
if factory_args is None:
factory_args = []
if factory_kwargs is None:
factory_kwargs = {}
if static is None:
static = False
# Verify
_verify_cre... |
<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_from_dict(self, dictionary):
""" Initializes an instance from a dictionary blueprint """ |
# Defaults
args = []
kwargs = {}
factory_method = None
factory_args = []
factory_kwargs = {}
static = False
calls = None
# Check dictionary for arguments
if 'args' in dictionary:
args = dictionary['args']
if '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_instantiated_service(self, name):
""" Get instantiated service by name """ |
if name not in self.instantiated_services:
raise UninstantiatedServiceException
return self.instantiated_services[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 _replace_service_arg(self, name, index, args):
""" Replace index in list with service """ |
args[index] = self.get_instantiated_service(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 _replace_scalars_in_args(self, args):
""" Replace scalars in arguments list """ |
_check_type('args', args, list)
new_args = []
for arg in args:
if isinstance(arg, list):
to_append = self._replace_scalars_in_args(arg)
elif isinstance(arg, dict):
to_append = self._replace_scalars_in_kwargs(arg)
elif isinstanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _replace_scalars_in_kwargs(self, kwargs):
""" Replace scalars in keyed arguments dictionary """ |
_check_type('kwargs', kwargs, dict)
new_kwargs = {}
for (name, value) in iteritems(kwargs):
if isinstance(value, list):
new_kwargs[name] = self._replace_scalars_in_args(value)
elif isinstance(value, dict):
new_kwargs[name] = self._replace... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _replace_services_in_args(self, args):
""" Replace service references in arguments list """ |
_check_type('args', args, list)
new_args = []
for arg in args:
if isinstance(arg, list):
new_args.append(self._replace_services_in_args(arg))
elif isinstance(arg, dict):
new_args.append(self._replace_services_in_kwargs(arg))
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 _replace_services_in_kwargs(self, kwargs):
""" Replace service references in keyed arguments dictionary """ |
_check_type('kwargs', kwargs, dict)
new_kwargs = {}
for (name, value) in iteritems(kwargs):
if isinstance(value, list):
new_kwargs[name] = self._replace_services_in_args(value)
elif isinstance(value, dict):
new_kwargs[name] = self._replac... |
<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_scalar_value(self, name):
""" Get scalar value by name """ |
if name not in self.scalars:
raise InvalidServiceConfiguration(
'Invalid Service Argument Scalar "%s" (not found)' % name
)
new_value = self.scalars.get(name)
return new_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 _replace_scalar(self, scalar):
""" Replace scalar name with scalar value """ |
if not is_arg_scalar(scalar):
return scalar
name = scalar[1:]
return self.get_scalar_value(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 _instantiate(self, module, class_name, args=None, kwargs=None, static=None):
""" Instantiates a class if provided """ |
if args is None:
args = []
if kwargs is None:
kwargs = {}
if static is None:
static = False
_check_type('args', args, list)
_check_type('kwargs', kwargs, dict)
if static and class_name is None:
return module
if 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 _handle_factory_method(self, service_obj, method_name, args=None, kwargs=None):
"""" Returns an object returned from a factory method """ |
if args is None:
args = []
if kwargs is None:
kwargs = {}
_check_type('args', args, list)
_check_type('kwargs', kwargs, dict)
# Replace args
new_args = self._replace_scalars_in_args(args)
new_kwargs = self._replace_scalars_in_kwargs(kwar... |
<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_calls(self, service_obj, calls):
""" Performs method calls on service object """ |
for call in calls:
method = call.get('method')
args = call.get('args', [])
kwargs = call.get('kwargs', {})
_check_type('args', args, list)
_check_type('kwargs', kwargs, dict)
if method is None:
raise InvalidServiceConfig... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repr_html_(self):
""" Jupyter Notebook hook to print this element as HTML. """ |
nbreset = f'<style>{css_nbreset}</style>'
resources = ''.join(map(str, self.resources))
return f'<div>{nbreset}{resources}<div class="hrepr">{self}</div></div>' |
<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_client(instance):
"""Returns an neutron client.""" |
neutron_client = utils.get_client_class(
API_NAME,
instance._api_version[API_NAME],
API_VERSIONS,
)
instance.initialize()
url = instance._url
url = url.rstrip("/")
client = neutron_client(username=instance._username,
project_name=instance._pro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Client(api_version, *args, **kwargs):
"""Return an neutron client. @param api_version: only 2.0 is supported now """ |
neutron_client = utils.get_client_class(
API_NAME,
api_version,
API_VERSIONS,
)
return neutron_client(*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 _getSuperFunc(self, s, func):
"""Return the the super function.""" |
return getattr(super(self.cls(), s), func.__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 _doc_make(*make_args):
"""Run make in sphinx' docs directory. :return: exit code """ |
if sys.platform == 'win32':
# Windows
make_cmd = ['make.bat']
else:
# Linux, Mac OS X, and others
make_cmd = ['make']
make_cmd.extend(make_args)
# Account for a stupid Python "bug" on Windows:
# <http://bugs.python.org/issue15533>
with cwd(DOCS_DIRECTORY):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coverage():
"""Run tests and show test coverage report.""" |
try:
import pytest_cov # NOQA
except ImportError:
print_failure_message(
'Install the pytest coverage plugin to use this task, '
"i.e., `pip install pytest-cov'.")
raise SystemExit(1)
import pytest
pytest.main(PYTEST_FLAGS + [
'--cov', CODE_DIREC... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_watch():
"""Watch for changes in the docs and rebuild HTML docs when changed.""" |
try:
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
except ImportError:
print_failure_message('Install the watchdog package to use this task, '
"i.e., `pip install watchdog'.")
raise SystemExit(1)
cla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_open():
"""Build the HTML docs and open them in a web browser.""" |
doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html')
if sys.platform == 'darwin':
# Mac OS X
subprocess.check_call(['open', doc_index])
elif sys.platform == 'win32':
# Windows
subprocess.check_call(['start', doc_index], shell=True)
elif sys.platform ==... |
<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_tasks():
"""Get all paver-defined tasks.""" |
from paver.tasks import environment
for tsk in environment.get_tasks():
print(tsk.shortname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makeService(self, options):
""" Construct a Node Server """ |
return NodeService(
port=options['port'],
host=options['host'],
broker_host=options['broker_host'],
broker_port=options['broker_port'],
debug=options['debug']
) |
<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_to_triplestore(self, output):
"""Method attempts to add output to Blazegraph RDF Triplestore""" |
if len(output) > 0:
result = self.ext_conn.load_data(data=output.serialize(),
datatype='rdf') |
<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_term(self, **kwargs):
"""Method generates a rdflib.Term based on kwargs""" |
term_map = kwargs.pop('term_map')
if hasattr(term_map, "termType") and\
term_map.termType == NS_MGR.rr.BlankNode.rdflib:
return rdflib.BNode()
if not hasattr(term_map, 'datatype'):
term_map.datatype = NS_MGR.xsd.anyURI.rdflib
if hasattr(term_map, "tem... |
<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, **kwargs):
"""Run method iterates through triple maps and calls the execute method""" |
if 'timestamp' not in kwargs:
kwargs['timestamp'] = datetime.datetime.utcnow().isoformat()
if 'version' not in kwargs:
kwargs['version'] = "Not Defined" #bibcat.__version__
# log.debug("kwargs: %s", pprint.pformat({k:v for k, v in kwargs.items()
# ... |
<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_context(self):
""" Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces """ |
results = self.rml.query("""
SELECT ?o {
{
?s rr:class ?o
} UNION {
?s rr:predicate ?o
}
}""")
namespaces = [Uri(row[0]).value[0]
for row in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_ld(self, output, **kwargs):
""" Returns the json-ld formated result """ |
raw_json_ld = output.serialize(format='json-ld',
context=self.context).decode()
# if there are fields that should be returned as arrays convert all
# non-array fields to an array
if not self.array_fields:
return raw_json_ld
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 execute(self, triple_map, output, **kwargs):
"""Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace):
Triple Map """ |
subject = self.generate_term(term_map=triple_map.subjectMap,
**kwargs)
start_size = len(output)
all_subjects = []
for pred_obj_map in triple_map.predicateObjectMap:
predicate = pred_obj_map.predicate
if pred_obj_map.template 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 run(self, row, **kwargs):
"""Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List):
Row from CSV Reader """ |
self.source = row
kwargs['output'] = self.__graph__()
super(CSVRowProcessor, self).run(**kwargs)
return kwargs['output'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, triple_map, output, **kwargs):
"""Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace """ |
subjects = []
logical_src_iterator = str(triple_map.logicalSource.iterator)
json_object = kwargs.get('obj', self.source)
# Removes '.' as a generic iterator, replace with '@'
if logical_src_iterator == ".":
results = [None,]
else:
json_path_exp = ... |
<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, source, **kwargs):
"""Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dic... |
kwargs['output'] = self.__graph__()
if isinstance(source, str):
import json
source = json.loads(source)
self.source = source
super(JSONProcessor, self).run(**kwargs)
self.output = kwargs['output']
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, triple_map, output, **kwargs):
"""Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map """ |
subjects = []
found_elements = self.source.xpath(
str(triple_map.logicalSource.iterator),
namespaces=self.xml_ns)
for element in found_elements:
subject = self.generate_term(term_map=triple_map.subjectMap,
element=elem... |
<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, xml, **kwargs):
"""Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text """ |
kwargs['output'] = self.__graph__()
if isinstance(xml, str):
try:
self.source = etree.XML(xml)
except ValueError:
try:
self.source = etree.XML(xml.encode())
except:
raise ValueError("Cannot r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, triple_map, output, **kwargs):
"""Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamesp... |
sparql = PREFIX + triple_map.logicalSource.query.format(
**kwargs)
bindings = self.__get_bindings__(sparql)
iterator = str(triple_map.logicalSource.iterator)
for binding in bindings:
entity_dict = binding.get(iterator)
if isinstance(entity_dict, rdfli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, message, _sender=None):
"""Sends a message to the actor represented by this `Ref`.""" |
if not _sender:
context = get_context()
if context:
_sender = context.ref
if self._cell:
if not self._cell.stopped:
self._cell.receive(message, _sender)
return
else:
self._cell = 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 security_errors(self):
"""Return just those errors associated with security""" |
errors = ErrorDict()
for f in ["honeypot", "timestamp", "security_hash"]:
if f in self.errors:
errors[f] = self.errors[f]
return errors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_security_hash(self):
"""Check the security hash.""" |
security_hash_dict = {
'content_type': self.data.get("content_type", ""),
'object_pk': self.data.get("object_pk", ""),
'timestamp': self.data.get("timestamp", ""),
}
expected_hash = self.generate_security_hash(**security_hash_dict)
actual_hash = 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 generate_security_data(self):
"""Generate a dict of security data for "initial" data.""" |
timestamp = int(time.time())
security_dict = {
'content_type': str(self.target_object._meta),
'object_pk': str(self.target_object._get_pk_val()),
'timestamp': str(timestamp),
'security_hash': self.initial_security_hash(timestamp),
}
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 generate_security_hash(self, content_type, object_pk, timestamp):
""" Generate a HMAC security hash from the provided info. """ |
info = (content_type, object_pk, timestamp)
key_salt = "django.contrib.forms.CommentSecurityForm"
value = "-".join(info)
return salted_hmac(key_salt, value).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 get_comment_create_data(self):
""" Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model... |
user_model = get_user_model()
return dict(
content_type=ContentType.objects.get_for_model(self.target_object),
object_pk=force_text(self.target_object._get_pk_val()),
text=self.cleaned_data["text"],
user=user_model.objects.latest('id'),
post_d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_comment(self):
""" If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ |
comment = self.cleaned_data["text"]
if settings.COMMENTS_ALLOW_PROFANITIES is False:
bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
if bad_words:
raise forms.ValidationError(ungettext(
"Watch your mouth! The word %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 clean_honeypot(self):
"""Check that nothing's been entered into the honeypot.""" |
value = self.cleaned_data["honeypot"]
if value:
raise forms.ValidationError(self.fields["honeypot"].label)
return 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 include_original(dec):
"""Decorate decorators so they include a copy of the original function.""" |
def meta_decorator(method):
"""Yo dawg, I heard you like decorators..."""
# pylint: disable=protected-access
decorator = dec(method)
decorator._original = method
return decorator
return meta_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 sendhello(self):
try:
# send hello
cli_hello_msg = "<hello>\n" +\
" <capabilities>\n" +\
" <capability>urn:ietf:params:netconf:base:1.0</capability>\n" ... | null |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendrpc(self, argv=[]):
self._aArgv += argv
_operation = ''
try:
self._cParams.parser(self._aArgv, self._dOptions)
# set rpc operation handler
while ... | null |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_templatetags():
""" Register templatetags defined in settings as basic templatetags """ |
from turboengine.conf import settings
from google.appengine.ext.webapp import template
for python_file in settings.TEMPLATE_PATH:
template.register_template_library(python_file) |
<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_hosts(self, pattern="all"):
""" find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. """ |
# process patterns
if isinstance(pattern, list):
pattern = ';'.join(pattern)
patterns = pattern.replace(";",":").split(":")
hosts = self._get_hosts(patterns)
# exclude hosts not in a subset, if defined
if self._subset:
subset = self._get_hosts(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_hosts(self, patterns):
""" finds hosts that match a list of patterns. Handles negative matches as well as intersection matches. """ |
hosts = set()
for p in patterns:
if p.startswith("!"):
# Discard excluded hosts
hosts.difference_update(self.__get_hosts(p))
elif p.startswith("&"):
# Only leave the intersected hosts
hosts.intersection_update(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.