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 NgramScorer(frequency_map):
"""Compute the score of a text by using the frequencies of ngrams. Example: -4.3622319742618245 Args: frequency_map (dict):
ngra... |
# Calculate the log probability
length = len(next(iter(frequency_map)))
# TODO: 0.01 is a magic number. Needs to be better than that.
floor = math.log10(0.01 / sum(frequency_map.values()))
ngrams = frequency.frequency_to_probability(frequency_map, decorator=math.log10)
def inner(text):
... |
<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_capability(self, capability=None, uri=None, name=None):
"""Specific add function for capabilities. Takes either: - a capability object (derived from List... |
if (capability is not None):
name = capability.capability_name
if (capability.uri is not None):
uri = capability.uri
self.add(Resource(uri=uri, capability=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 capability_info(self, name=None):
"""Return information about the requested capability from this list. Will return None if there is no information about the ... |
for r in self.resources:
if (r.capability == name):
return(r)
return(None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ui_main(fmt_table, node_dict):
"""Create the base UI in command mode.""" |
cmd_funct = {"quit": False,
"run": node_cmd,
"stop": node_cmd,
"connect": node_cmd,
"details": node_cmd,
"update": True}
ui_print("\033[?25l") # cursor off
print("{}\n".format(fmt_table))
sys.stdout.flush()
# refr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_cmd(node_dict):
"""Get main command selection.""" |
key_lu = {"q": ["quit", True], "r": ["run", True],
"s": ["stop", True], "u": ["update", True],
"c": ["connect", True], "d": ["details", True]}
ui_cmd_bar()
cmd_valid = False
input_flush()
with term.cbreak():
while not cmd_valid:
val = input_by_key()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_cmd(cmd_name, node_dict):
"""Process commands that target specific nodes.""" |
sc = {"run": cmd_startstop, "stop": cmd_startstop,
"connect": cmd_connect, "details": cmd_details}
node_num = node_selection(cmd_name, len(node_dict))
refresh_main = None
if node_num != 0:
(node_valid, node_info) = node_validate(node_dict, node_num, cmd_name)
if node_valid:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_selection(cmd_name, node_qty):
"""Determine Node via alternate input method.""" |
cmd_disp = cmd_name.upper()
cmd_title = ("\r{1}{0} NODE{2} - Enter {3}#{2}"
" ({4}0 = Exit Command{2}): ".
format(cmd_disp, C_TI, C_NORM, C_WARN, C_HEAD2))
ui_cmd_title(cmd_title)
selection_valid = False
input_flush()
with term.cbreak():
while not selec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_validate(node_dict, node_num, cmd_name):
"""Validate that command can be performed on target node.""" |
# cmd: [required-state, action-to-displayed, error-statement]
req_lu = {"run": ["stopped", "Already Running"],
"stop": ["running", "Already Stopped"],
"connect": ["running", "Can't Connect, Node Not Running"],
"details": [node_dict[node_num].state, ""]}
tm = {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 cmd_startstop(node, cmd_name, node_info):
"""Confirm command and execute it.""" |
cmd_lu = {"run": ["ex_start_node", "wait_until_running", "RUNNING"],
"stop": ["ex_stop_node", "", "STOPPING"]}
# specific delay & message {provider: {command: [delay, message]}}
cld_lu = {"azure": {"stop": [6, "Initiated"]},
"aws": {"stop": [6, "Initiated"]}}
conf_mess = ("\... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_connect(node, cmd_name, node_info):
"""Connect to node.""" |
# FUTURE: call function to check for custom connection-info
conn_info = "Defaults"
conf_mess = ("\r{0}{1} TO{2} {3} using {5}{4}{2} - Confirm [y/N]: ".
format(C_STAT[cmd_name.upper()], cmd_name.upper(), C_NORM,
node_info, conn_info, C_HEAD2))
cmd_result = 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 ssh_get_info(node):
"""Determine ssh-user and ssh-key for node.""" |
ssh_key = ""
if node.cloud == "aws":
raw_key = node.extra['key_name']
ssh_key = "-i {0}{1}.pem ".format(CONFIG_DIR, raw_key)
ssh_user = ssh_calc_aws(node)
elif node.cloud == "azure":
ssh_user = node.extra['properties']['osProfile']['adminUsername']
elif node.cloud == "gc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh_calc_aws(node):
"""Calculate default ssh-user based on image-if of AWS instance.""" |
userlu = {"ubunt": "ubuntu", "debia": "admin", "fedor": "root",
"cento": "centos", "openb": "root"}
image_name = node.driver.get_image(node.extra['image_id']).name
if not image_name:
image_name = node.name
usertemp = ['name'] + [value for key, value in list(userlu.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 ui_cmd_bar():
"""Display Command Bar.""" |
cmd_bar = ("\rSELECT COMMAND - {2}(R){1}un {0}(C){1}onnect "
"{3}(S){1}top {0}(U){1}pdate"
" {0}(Q){1}uit: ".
format(C_TI, C_NORM, C_GOOD, C_ERR))
# FUTURE - TO BE USED WHEN DETAILS IMPLEMENTED
# cmd_bar = ("\rSELECT COMMAND - {2}(R){1}un {0}(C){1}on... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def input_flush():
"""Flush the input buffer on posix and windows.""" |
try:
import sys, termios # noqa
termios.tcflush(sys.stdin, termios.TCIFLUSH)
except ImportError:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user(email, password, *args, **kwargs):
"""Get user for grant type password. Needed for grant type 'password'. Note, grant type password is by default di... |
user = datastore.find_user(email=email)
if user and user.active and verify_password(password, user.password):
return user |
<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(access_token=None, refresh_token=None):
"""Load an access token. Add support for personal access tokens compared to flask-oauthlib. If the access t... |
if access_token:
t = Token.query.filter_by(access_token=access_token).first()
if t and t.is_personal and t.user.active:
t.expires = datetime.utcnow() + timedelta(
seconds=int(current_app.config.get(
'OAUTH2_PROVIDER_TOKEN_EXPIRES_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 get_client(client_id):
"""Load the client. Needed for grant_type client_credentials. Add support for OAuth client_credentials access type, with user inactiva... |
client = Client.query.get(client_id)
if client and client.user.active:
return 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 save_token(token, request, *args, **kwargs):
"""Token persistence. :param token: A dictionary with the token data. :param request: The request instance. :ret... |
# Exclude the personal access tokens which doesn't expire.
user = request.user if request.user else current_user
# Add user information in token endpoint response.
# Currently, this is the only way to have the access to the user of the
# token as well as the token response.
token.update(user={... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_oauth2_user(valid, oauth):
"""Log in a user after having been verified.""" |
if valid:
oauth.user.login_via_oauth2 = True
_request_ctx_stack.top.user = oauth.user
identity_changed.send(current_app._get_current_object(),
identity=Identity(oauth.user.id))
return valid, oauth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jwt_verify_token(headers):
"""Verify the JWT token. :param dict headers: The request headers. :returns: The token data. :rtype: dict """ |
# Get the token from headers
token = headers.get(
current_app.config['OAUTH2SERVER_JWT_AUTH_HEADER']
)
if token is None:
raise JWTInvalidHeaderError
# Get authentication type
authentication_type = \
current_app.config['OAUTH2SERVER_JWT_AUTH_HEADER_TYPE']
# Check if t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error_handler(f):
"""Handle uncaught OAuth errors.""" |
@wraps(f)
def decorated(*args, **kwargs):
try:
return f(*args, **kwargs)
except OAuth2Error as e:
# Only FatalClientError are handled by Flask-OAuthlib (as these
# errors should not be redirect back to the client - see
# http://tools.ietf.org/html... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(*args, **kwargs):
"""View for rendering authorization request.""" |
if request.method == 'GET':
client = Client.query.filter_by(
client_id=kwargs.get('client_id')
).first()
if not client:
abort(404)
scopes = current_oauth2server.scopes
ctx = dict(
client=client,
oauth_request=kwargs.get('requ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def errors():
"""Error view in case of invalid oauth requests.""" |
from oauthlib.oauth2.rfc6749.errors import raise_from_error
try:
error = None
raise_from_error(request.values.get('error'), params=dict())
except OAuth2Error as raised:
error = raised
return render_template('invenio_oauth2server/errors.html', error=error) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info():
"""Test to verify that you have been authenticated.""" |
if current_app.testing or current_app.debug:
return jsonify(dict(
user=request.oauth.user.id,
client=request.oauth.client.client_id,
scopes=list(request.oauth.scopes)
))
else:
abort(404) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_periods(ciphertext, max_key_period):
"""Rank all key periods for ``ciphertext`` up to and including ``max_key_period`` Example: Args: ciphertext (str):
... |
if max_key_period <= 0:
raise ValueError("max_key_period must be a positive integer")
key_scores = []
for period in range(1, min(max_key_period, len(ciphertext)) + 1):
score = abs(ENGLISH_IC - index_of_coincidence(*split_columns(ciphertext, period)))
key_scores.append((period, scor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(key, ciphertext):
"""Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: HELLO Args: key (iterable):
The key to use ciphertext (str):
... |
index = 0
decrypted = ""
for char in ciphertext:
if char in string.punctuation + string.whitespace + string.digits:
decrypted += char
continue # Not part of the decryption
# Rotate character by the alphabet position of the letter in the key
alphabet = strin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def explore(self):
"""INTERACTIVE exploration source capabilities. Will use sitemap URI taken either from explicit self.sitemap_name or derived from the mappings... |
# Where do we start? Build options in starts which has entries
# that are a pair comprised of the uri and a list of acceptable
# capabilities
starts = []
if (self.sitemap_name is not None):
print("Starting from explicit --sitemap %s" % (self.sitemap_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 explore_show_head(self, uri, check_headers=None):
"""Do HEAD on uri and show infomation. Will also check headers against any values specified in check_header... |
print("HEAD %s" % (uri))
if (re.match(r'^\w+:', uri)):
# Looks like a URI
response = requests.head(uri)
else:
# Mock up response if we have a local file
response = self.head_on_file(uri)
print(" status: %s" % (response.status_code))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allowed_entries(self, capability):
"""Return list of allowed entries for given capability document. Includes handling of capability = *index where the only a... |
index = re.match(r'(.+)index$', capability)
archive = re.match(r'(.+)\-archive$', capability)
if (capability == 'capabilitylistindex'):
return([]) # not allowed so no valid references
elif (index):
return([index.group(1)]) # name without index ending
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_relative_uri(self, context, uri):
"""If uri is relative then expand in context. Prints warning if expansion happens. """ |
full_uri = urljoin(context, uri)
if (full_uri != uri):
print(" WARNING - expanded relative URI to %s" % (full_uri))
uri = full_uri
return(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 hill_climb(nsteps, start_node, get_next_node):
"""Modular hill climbing algorithm. Example: Args: nsteps (int):
The number of neighbours to visit start_node... |
outputs = []
best_score = -float('inf')
for step in range(nsteps):
next_node, score, output = get_next_node(copy.deepcopy(start_node))
# Keep track of best score and the start node becomes finish node
if score > best_score:
start_node = copy.deepcopy(next_node)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scopes_multi_checkbox(field, **kwargs):
"""Render multi checkbox widget.""" |
kwargs.setdefault('type', 'checkbox')
field_id = kwargs.pop('id', field.id)
html = [u'<div class="row">']
for value, label, checked in field.iter_choices():
choice_id = u'%s-%s' % (field_id, value)
options = dict(
kwargs,
name=field.name,
value=val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_formdata(self, valuelist):
"""Process form data.""" |
if valuelist:
self.data = '\n'.join([
x.strip() for x in
filter(lambda x: x, '\n'.join(valuelist).splitlines())
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redirect_uris(self, value):
"""Validate and store redirect URIs for client.""" |
if isinstance(value, six.text_type):
value = value.split("\n")
value = [v.strip() for v in value]
for v in value:
validate_redirect_uri(v)
self._redirect_uris = "\n".join(value) or "" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_scopes(self, scopes):
"""Set default scopes for client.""" |
validate_scopes(scopes)
self._default_scopes = " ".join(set(scopes)) if scopes 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 get_users(self):
"""Get number of users.""" |
no_users = Token.query.filter_by(
client_id=self.client_id,
is_personal=False,
is_internal=False
).count()
return no_users |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scopes(self, scopes):
"""Set scopes. :param scopes: The list of scopes. """ |
validate_scopes(scopes)
self._scopes = " ".join(set(scopes)) if scopes 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 get_visible_scopes(self):
"""Get list of non-internal scopes for token. :returns: A list of scopes. """ |
return [k for k, s in current_oauth2server.scope_choices()
if k in self.scopes] |
<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_personal(cls, name, user_id, scopes=None, is_internal=False):
"""Create a personal access token. A token that is bound to a specific user and which do... |
with db.session.begin_nested():
scopes = " ".join(scopes) if scopes else ""
c = Client(
name=name,
user_id=user_id,
is_internal=True,
is_confidential=False,
_default_scopes=scopes
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_redirect_uri(value):
"""Validate a redirect URI. Redirect URIs must be a valid URL and use https unless the host is localhost for which http is acce... |
sch, netloc, path, par, query, fra = urlparse(value)
if not (sch and netloc):
raise InvalidRedirectURIError()
if sch != 'https':
if ':' in netloc:
netloc, port = netloc.split(':', 1)
if not (netloc in ('localhost', '127.0.0.1') and sch == 'http'):
raise Insec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_scopes(value_list):
"""Validate if each element in a list is a registered scope. :param value_list: The list of scopes. :raises invenio_oauth2server... |
for value in value_list:
if value not in current_oauth2server.scopes:
raise ScopeDoesNotExists(value)
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 check_output_cwd(args, cwd, timeout=None):
'''Open a subprocess in another working directory
Raises ValueError if system binary does not exist
Raises CalledProcessError if the return code is non-zero
:returns: list of standard output and standard error from subprocess
:param args: a list of 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_otp_modehex_interpretation(self, otp):
""" Return modhex interpretation of the provided OTP. If there are multiple interpretations available, first one i... |
try:
interpretations = translate(u(otp))
except Exception:
return otp
if len(interpretations) == 0:
return otp
elif len(interpretations) > 1:
# If there are multiple interpretations first try to use the same
# translation as t... |
<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_shift_function(alphabet):
"""Construct a shift function from an alphabet. Examples: Shift cases independently <function make_shift_function.<locals>.shi... |
def shift_case_sensitive(shift, symbol):
case = [case for case in alphabet if symbol in case]
if not case:
return symbol
case = case[0]
index = case.index(symbol)
return case[(index - shift) % len(case)]
return shift_case_sensitive |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crack(ciphertext, *fitness_functions, min_key=0, max_key=26, shift_function=shift_case_english):
"""Break ``ciphertext`` by enumerating keys between ``min_ke... |
if min_key >= max_key:
raise ValueError("min_key cannot exceed max_key")
decryptions = []
for key in range(min_key, max_key):
plaintext = decrypt(key, ciphertext, shift_function=shift_function)
decryptions.append(Decryption(plaintext, key, score(plaintext, *fitness_functions)))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(key, ciphertext, shift_function=shift_case_english):
"""Decrypt Shift enciphered ``ciphertext`` using ``key``. Examples: HELLO >> decrypt(15, [0xcf, ... |
return [shift_function(key, symbol) for symbol in ciphertext] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randombytes(n):
"""Return n random bytes.""" |
# Use /dev/urandom if it is available. Fall back to random module
# if not. It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists("/dev/urandom"):
f = open("/dev/urandom")
s = f.read(n)
f.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 unicode_from_html(content):
"""Attempts to decode an HTML string into unicode. If unsuccessful, the original content is returned. """ |
encodings = get_encodings_from_content(content)
for encoding in encodings:
try:
return unicode(content, encoding)
except (UnicodeError, TypeError):
pass
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 stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator.""" |
encoding = get_encoding_from_headers(r.headers)
if encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stream_decode_gzip(iterator):
"""Stream decodes a gzip-encoded iterator""" |
try:
dec = zlib.decompressobj(16 + zlib.MAX_WBITS)
for chunk in iterator:
rv = dec.decompress(chunk)
if rv:
yield rv
buf = dec.decompress('')
rv = buf + dec.flush()
if rv:
yield rv
except zlib.error:
pass |
<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_application_key_file(self, filename=b'spotify_appkey.key'):
"""Load your libspotify application key file. If called without arguments, it tries to read ... |
with open(filename, 'rb') as fh:
self.app_key = fh.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_layout(self, data):
""" Lays the text out into separate lines and calculates their total height. """ |
c = data['output']
word_space = c.text_width(
' ',
font_name=self.font_name,
font_size=self.font_size)
# Arrange the text as words on lines
self._layout = [[]]
x = self.font_size if self.paragraph_indent else 0
for word in self.text.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 iter_content(self, chunk_size=10 * 1024, decode_unicode=None):
"""Iterates over the response data. This avoids reading the content at once into memory for la... |
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed'
)
def generate():
while 1:
chunk = self.raw.read(chunk_size)
if not chunk:
break
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 _get_fd(fileobj):
""" Get a descriptor out of a file object. :param fileobj: An integer (existing descriptor) or any object having the `fileno()` method. :ra... |
if isinstance(fileobj, int):
fd = fileobj
else:
try:
fd = fileobj.fileno()
except AttributeError:
fd = None
if fd is None or fd < 0:
raise ValueError("invalid fileobj: {!r}".format(fileobj))
return fd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister(self, fileobj):
""" Remove interest in IO events from the specified fileobj :param fileobj: Any existing file-like object that has a fileno() meth... |
fd = _get_fd(fileobj)
key = self._fd_map[fd]
try:
self._epoll.unregister(fd)
except OSError:
pass
del self._fd_map[fd]
return key |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify(self, fileobj, events, data=None):
""" Modify interest in specified IO events on the specified file object :param fileobj: Any existing file-like obje... |
fd = _get_fd(fileobj)
epoll_events = _EpollSelectorEvents(events).get_epoll_events()
if fd not in self._fd_map:
raise KeyError("{!r} is not registered".format(fileobj))
key = SelectorKey(fileobj, fd, events, data)
self._fd_map[fd] = key
self._epoll.modify(fd,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select(self, timeout=None):
""" Wait until one or more of the registered file objects becomes ready or until the timeout expires. :param timeout: maximum wai... |
if timeout is None:
epoll_timeout = -1
elif timeout <= 0:
epoll_timeout = 0
else:
epoll_timeout = timeout
max_events = len(self._fd_map) or -1
result = []
for fd, epoll_events in self._epoll.poll(epoll_timeout, max_events):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, username, password=None, blob=None, zeroconf=None):
"""Authenticate to Spotify's servers. You can login with one of three combinations: - ``usern... |
username = utils.to_char(username)
if password is not None:
password = utils.to_char(password)
spotifyconnect.Error.maybe_raise(
lib.SpConnectionLoginPassword(
username, password))
elif blob is not None:
blob = utils.to_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 on(self):
"""Turn on the alsa_sink sink. This is done automatically when the sink is instantiated, so you'll only need to call this method if you ever call :... |
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
spotifyconnect._session_instance.player.on(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def off(self):
"""Turn off the alsa_sink sink. This disconnects the sink from the relevant session events. """ |
spotifyconnect._session_instance.player.off(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
self._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 patched(f):
"""Patches a given API function to not send.""" |
def wrapped(*args, **kwargs):
kwargs['return_response'] = False
kwargs['prefetch'] = True
return f(*args, **kwargs)
return wrapped |
<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(r, pools=None):
"""Sends a given Request object.""" |
if pools:
r._pools = pools
r.send()
return r.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 _print_debug(self, *args):
"""Method output debug message into stderr :param args: Message(s) to output :rtype args: string """ |
if self.debuglevel > 1:
print(datetime.datetime.now().time(), *args, file=sys.stderr)
else:
print(*args, file=sys.stderr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_host(cls, host='localhost', port=0):
""" Parse provided hostname and extract port number :param host: Server hostname :type host: string :param port: ... |
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i + 1:]
try:
port = int(port)
except ValueError:
raise OSError('nonnumeric port')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_proxy(self, proxy_host='localhost', proxy_port=0, proxy_type=socks.HTTP, host='localhost', port=0):
"""Connect to a host on a given port via proxy se... |
if proxy_type not in socks.DEFAULT_PORTS.keys():
raise NotSupportedProxyType
(proxy_host, proxy_port) = self._parse_host(host=proxy_host, port=proxy_port)
if not proxy_port:
proxy_port = socks.DEFAULT_PORTS[proxy_type]
(host, port) = self._parse_host(host=host, p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enabled(self):
""" read or write the child sub-reaper flag of the current process This property behaves in the following manner: * If a read is attempted and... |
if self._status == self.SR_UNSUPPORTED:
return False
status = c_int()
try:
prctl(PR_GET_CHILD_SUBREAPER, addressof(status), 0, 0, 0)
except OSError:
self._status = self.SR_UNSUPPORTED
else:
self._status = self.SR_ENABLED if status ... |
<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,params):
'''
Generate API sign code
'''
for k, v in params.iteritems():
if type(v) == int: v = str(v)
elif type(v) == float: v = '%.2f'%v
elif type(v) in (list, set):
v = ','.join([str(i) for i in v])
elif ty... |
<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, data, fields=[], models={}):
'''
Create model attributes
'''
if not fields: fields = self.fields
if not models and hasattr(self, 'models'): models = self.models
for field in fields:
setattr(self,field,None)
if not data: return None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_minimum_size(self, data):
"""Returns the rotated minimum size.""" |
size = self.element.get_minimum_size(data)
if self.angle in (RotateLM.NORMAL, RotateLM.UPSIDE_DOWN):
return size
else:
return datatypes.Point(size.y, size.x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_ms_from_base(self, size):
"""Calculates the rotated minimum size from the given base minimum size.""" |
hw = size.x * 0.5
hh = size.y * 0.5
a = datatypes.Point(hw, hh).get_rotated(self.angle)
b = datatypes.Point(-hw, hh).get_rotated(self.angle)
c = datatypes.Point(hw, -hh).get_rotated(self.angle)
d = datatypes.Point(-hw, -hh).get_rotated(self.angle)
minp = a.get_... |
<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_data(self, name, default=None):
"""Get a JSON compatible value of the field """ |
value = self.get(name)
if value is Missing.Value:
return default
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 get(self, name):
"""Get the value by name """ |
# check read permission
sm = getSecurityManager()
permission = permissions.View
if not sm.checkPermission(permission, self.context):
raise Unauthorized("Not allowed to view the Plone portal")
# read the attribute
attr = getattr(self.context, name, 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 set(self, name, value, **kw):
"""Set the attribute to the given value. The keyword arguments represent the other attribute values to integrate constraints to... |
# check write permission
sm = getSecurityManager()
permission = permissions.ManagePortal
if not sm.checkPermission(permission, self.context):
raise Unauthorized("Not allowed to modify the Plone portal")
# set the attribute
if not hasattr(self.context, 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 set(self, name, value, **kw):
"""Set the field to the given value. The keyword arguments represent the other field values to integrate constraints to other v... |
# fetch the field by name
field = api.get_field(self.context, name)
# bail out if we have no field
if not field:
return False
# call the field adapter and set the value
fieldmanager = IFieldManager(field)
return fieldmanager.set(self.context, 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 can_write(self):
"""Check if the field is writeable """ |
sm = getSecurityManager()
permission = permissions.ModifyPortalContent
if not sm.checkPermission(permission, self.context):
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 can_read(self):
"""Check if the field is readable """ |
sm = getSecurityManager()
if not sm.checkPermission(permissions.View, self.context):
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 send_s3_xsd(self, url_xsd):
# pragma: no cover """This method will not be re-run always, only locally and when xsd are regenerated, read the test_008_force_s... |
if self.check_s3(self.domain, urlparse(url_xsd).path[1:]):
return url_xsd
response = urllib2.urlopen(url_xsd)
content = response.read()
cached = NamedTemporaryFile(delete=False)
named = cached.name
# Find all urls in the main xslt file.
urls = re.... |
<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_s3(self, bucket, element):
# pragma: no cover """This method is a helper con `cache_s3`. Read method `cache_s3` for more information. :param bucket: :p... |
session = boto3.Session(profile_name=self.profile_name)
s3 = session.resource('s3')
try:
s3.meta.client.head_bucket(Bucket=bucket)
except ClientError:
# If the bucket does not exists then simply use the original
# I silently fail returning everything... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_it(self, url):
"""Take an url which deliver a plain document and convert it to a temporary file, this document is an xslt file expecting contains all x... |
# TODO: Use directly the file object instead of the name of the file
# with seek(0)
cached = self._cache_it(url)
if not isfile(cached.name):
# If /tmp files are deleted
self._cache_it.cache_clear()
cached = self._cache_it(url)
return cac... |
<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_original(document, xslt):
"""Get the original chain given document path and xslt local path :param str document: local absolute path to document :param s... |
dom = etree.parse(document) # TODO: cuando este probando -
# fuente:
# http://stackoverflow.com/questions/16698935/how-to-transform-an-xml-file-using-xslt-in-python
xslt = etree.parse(xslt)
transform = etree.XSLT(xslt)
newdom = transform(dom)
return newdom |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Close the internal signalfd file descriptor if it isn't closed :raises OSError: If the underlying ``close(2)`` fails. The error message matc... |
with self._close_lock:
sfd = self._sfd
if sfd >= 0:
self._sfd = -1
self._signals = frozenset()
close(sfd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromfd(cls, fd, signals):
""" Create a new signalfd object from a given file descriptor :param fd: A pre-made file descriptor obtained from ``signalfd_create... |
if fd < 0:
_err_closed()
self = cls.__new__()
object.__init__(self)
self._sfd = fd
self._signals = signals
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 update(self, signals):
""" Update the mask of signals this signalfd reacts to :param signals: A replacement set of signal numbers to monitor :raises ValueErr... |
if self._sfd < 0:
_err_closed()
mask = sigset_t()
sigemptyset(mask)
if signals is not None:
for signal in signals:
sigaddset(mask, signal)
# flags are ignored when sfd is not -1
_signalfd(self._sfd, mask, 0)
self._signals =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, maxsignals=None):
""" Read information about currently pending signals. :param maxsignals: Maximum number of signals to read. By default this is t... |
if maxsignals is None:
maxsignals = len(self._signals)
if maxsignals <= 0:
raise ValueError("maxsignals must be greater than 0")
info_list = (signalfd_siginfo * maxsignals)()
num_read = read(self._sfd, byref(info_list), sizeof(info_list))
return info_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 add_curie(self, name, href):
"""Adds a CURIE definition. A CURIE link with the given ``name`` and ``href`` is added to the document. This method returns self... |
self.draft.set_curie(self, name, href)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_rel(self, key, rel, thing, wrap):
"""Adds ``thing`` to links or embedded resources. Calling code should not use this method directly and should use ``em... |
self.o.setdefault(key, {})
if wrap:
self.o[key].setdefault(rel, [])
if rel not in self.o[key]:
self.o[key][rel] = thing
return
existing = self.o[key].get(rel)
if isinstance(existing, list):
existing.append(thing)
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 about_box():
"""A simple about dialog box using the distribution data files.""" |
about_info = wx.adv.AboutDialogInfo()
for k, v in metadata.items():
setattr(about_info, snake2ucamel(k), v)
wx.adv.AboutBox(about_info) |
<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, xml_doc):
"""Sign the document with a third party signatory. :param str xml_doc: Document self signed in plain xml :returns answer: Answer is give... |
try:
self.client = Client(self.url)
except ValueError as e:
self.message = e.message
except URLError:
self.message = 'The url you provided: ' + \
'%s could not be reached' % self.url |
<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(key, default=None):
""" return the key from the request """ |
data = get_form() or get_query_string()
return data.get(key, default) |
<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_true(key, default=False):
""" Check if the value is in TRUE_VALUES """ |
value = get(key, default)
if isinstance(value, list):
value = value[0]
if isinstance(value, bool):
return value
if value is default:
return default
return value.lower() in TRUE_VALUES |
<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_sort_limit():
""" returns the 'sort_limit' from the request """ |
limit = _.convert(get("sort_limit"), _.to_int)
if (limit < 1):
limit = None # catalog raises IndexError if limit < 1
return limit |
<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_sort_on(allowed_indexes=None):
""" returns the 'sort_on' from the request """ |
sort_on = get("sort_on")
if allowed_indexes and sort_on not in allowed_indexes:
logger.warn("Index '{}' is not in allowed_indexes".format(sort_on))
return None
return sort_on |
<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_json_item(key, value):
""" manipulate json data on the fly """ |
data = get_json()
data[key] = value
request = get_request()
request["BODY"] = json.dumps(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 rounded_rectangle_region(width, height, radius):
""" Returns a rounded rectangle wx.Region """ |
bmp = wx.Bitmap.FromRGBA(width, height) # Mask color is #000000
dc = wx.MemoryDC(bmp)
dc.Brush = wx.Brush((255,) * 3) # Any non-black would do
dc.DrawRoundedRectangle(0, 0, width, height, radius)
dc.SelectObject(wx.NullBitmap)
bmp.SetMaskColour((0,) * 3)
return wx.Region(bmp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_after(lag):
""" Parametrized decorator for calling a function after a time ``lag`` given in milliseconds. This cancels simultaneous calls. """ |
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.timer.cancel() # Debounce
wrapper.timer = threading.Timer(lag, func, args=args, kwargs=kwargs)
wrapper.timer.start()
wrapper.timer = threading.Timer(0, lambda: None) # timer.cancel now exists
return wrapper
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Starts watching the path and running the test jobs.""" |
assert not self.watching
def selector(evt):
if evt.is_directory:
return False
path = evt.path
if path in self._last_fnames: # Detected a "killing cycle"
return False
for pattern in self.skip_pattern.split(";"):
if fnmatch(path, pattern.strip()):
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 on_close(self, evt):
""" Pop-up menu and wx.EVT_CLOSE closing event """ |
self.stop() # DoseWatcher
if evt.EventObject is not self: # Avoid deadlocks
self.Close() # wx.Frame
evt.Skip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutator(*cache_names):
"""Decorator for ``Document`` methods that change the document. This decorator ensures that the object's caches are kept in sync when ... |
def deco(fn):
@wraps(fn)
def _fn(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
finally:
for cache_name in cache_names:
setattr(self, cache_name, None)
return _fn
return deco |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canonical_key(self, key):
"""Returns the canonical key for the given ``key``.""" |
if key.startswith('/'):
return urlparse.urljoin(self.base_uri, key)
else:
return self.curies.expand(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self):
"""Returns the URL for the resource based on the ``self`` link. This method returns the ``href`` of the document's ``self`` link if it has one, or... |
if not 'self' in self.links:
return None
self_link = self.links['self']
if isinstance(self_link, list):
for link in self_link:
return link.url()
return self_link.url() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.