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 _on_connect_error(self, sock, err):
# pylint: disable=unused-argument """Error received from websocket""" |
if isinstance(err, SystemExit):
self.log.error(f"Shutting down websocket connection")
else:
self.log.error(f"Websocket error: {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 connect(self, sock):
"""Attach a given socket to a channel""" |
def cbwrap(*args, **kwargs):
"""Callback wrapper; passes in response_type"""
self.callback(self.response_type, *args, **kwargs)
self.sock = sock
self.sock.subscribe(self.channel)
self.sock.onchannel(self.channel, cbwrap) |
<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_cmd(cmd, input=None, timeout=30, max_try=3, num_try=1):
'''Run command `cmd`.
It's like that, and that's the way it is.
'''
if type(cmd) == str:
cmd = cmd.split()
process = subprocess.Popen(cmd,
stdin=open('/dev/null', 'r'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
communicate_has_timeout = func_has_arg(func=process.communicate,
arg='timeout')
exception = Exception
if communicate_has_timeout:
exception = subprocess.TimeoutExpired # python 3.x
stdout = stderr = b''
exitcode = None
try:
if communicate_has_timeout:
# python 3.x
stdout, stderr = process.communicate(input, timeout)
exitcode = process.wait()
else:
# python 2.x
if timeout is None:
stdout, stderr = process.communicate(input)
exitcode = process.wait()
else:
# thread-recipe: https://stackoverflow.com/a/4825933
def target():
# closure-recipe: https://stackoverflow.com/a/23558809
target.out, target.err = process.communicate(input)
import threading
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
process.terminate()
thread.join()
exitcode = None
else:
exitcode = process.wait()
stdout = target.out
stderr = target.err
except exception:
if num_try < max_try:
return run_cmd(cmd, input, timeout, max_try, num_try+1)
else:
return CmdResult(exitcode, stdout, stderr, cmd, input)
return CmdResult(exitcode, stdout, stderr, cmd, input) |
<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_options(options, parser):
""" check options requirements, print and return exit value """ |
if not options.get('release_environment', None):
print("release environment is required")
parser.print_help()
return os.EX_USAGE
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self):
""" write all needed state info to filesystem """ |
dumped = self._fax.codec.dump(self.__state, open(self.state_file, 'w')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expected_param_keys(self):
"""returns a list of params that this ConfigTemplate expects to receive""" |
expected_keys = []
r = re.compile('%\(([^\)]+)\)s')
for block in self.keys():
for key in self[block].keys():
s = self[block][key]
if type(s)!=str: continue
md = re.search(r, s)
while md is not None:
k = md.group(1)
if k not in expected_keys:
expected_keys.append(k)
s = s[md.span()[1]:]
md = re.search(r, s)
return expected_keys |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Takes a crash id, pulls down data from Socorro, generates signature data""" |
parser = argparse.ArgumentParser(
formatter_class=WrappedTextHelpFormatter,
description=DESCRIPTION
)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
parser.add_argument(
'crashid', help='crash id to generate signatures for'
)
args = parser.parse_args()
api_token = os.environ.get('SOCORRO_API_TOKEN', '')
crash_id = args.crashid.strip()
resp = fetch('/RawCrash/', crash_id, api_token)
if resp.status_code == 404:
printerr('%s: does not exist.' % crash_id)
return 1
if resp.status_code == 429:
printerr('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
printerr('HTTP 500: %s' % resp.content)
return 1
raw_crash = resp.json()
# If there's an error in the raw crash, then something is wrong--probably with the API
# token. So print that out and exit.
if 'error' in raw_crash:
print('Error fetching raw crash: %s' % raw_crash['error'], file=sys.stderr)
return 1
resp = fetch('/ProcessedCrash/', crash_id, api_token)
if resp.status_code == 404:
printerr('%s: does not have processed crash.' % crash_id)
return 1
if resp.status_code == 429:
printerr('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
printerr('HTTP 500: %s' % resp.content)
return 1
processed_crash = resp.json()
# If there's an error in the processed crash, then something is wrong--probably with the
# API token. So print that out and exit.
if 'error' in processed_crash:
printerr('Error fetching processed crash: %s' % processed_crash['error'])
return 1
crash_data = convert_to_crash_data(raw_crash, processed_crash)
print(json.dumps(crash_data, indent=2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fill_text(self, text, width, indent):
"""Wraps text like HelpFormatter, but doesn't squash lines This makes it easier to do lists and paragraphs. """ |
parts = text.split('\n\n')
for i, part in enumerate(parts):
# Check to see if it's a bulleted list--if so, then fill each line
if part.startswith('* '):
subparts = part.split('\n')
for j, subpart in enumerate(subparts):
subparts[j] = super(WrappedTextHelpFormatter, self)._fill_text(
subpart, width, indent
)
parts[i] = '\n'.join(subparts)
else:
parts[i] = super(WrappedTextHelpFormatter, self)._fill_text(part, width, indent)
return '\n\n'.join(parts) |
<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_api_services_by_name(self):
"""Return a dict of services by name""" |
if not self.services_by_name:
self.services_by_name = dict({s.get('name'): s for s in self.conf
.get("api")
.get("services")})
return self.services_by_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 get_api_endpoints(self, apiname):
"""Returns the API endpoints""" |
try:
return self.services_by_name\
.get(apiname)\
.get("endpoints")\
.copy()
except AttributeError:
raise Exception(f"Couldn't find the API endpoints") |
<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_ws_subscriptions(self, apiname):
"""Returns the websocket subscriptions""" |
try:
return self.services_by_name\
.get(apiname)\
.get("subscriptions")\
.copy()
except AttributeError:
raise Exception(f"Couldn't find the websocket subscriptions") |
<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_api(self, name=None):
"""Returns the API configuration""" |
if name is None:
try:
return self.conf.get("api").copy()
except: # NOQA
raise Exception(f"Couldn't find the API configuration") |
<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_api_service(self, name=None):
"""Returns the specific service config definition""" |
try:
svc = self.services_by_name.get(name, None)
if svc is None:
raise ValueError(f"Couldn't find the API service configuration")
return svc
except: # NOQA
raise Exception(f"Failed to retrieve the API service configuration") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ex_type_str(exobj):
"""Return a string corresponding to the exception type.""" |
regexp = re.compile(r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>")
exc_type = str(exobj)
if regexp.match(exc_type):
exc_type = regexp.match(exc_type).groups()[0]
exc_type = exc_type[11:] if exc_type.startswith("exceptions.") else exc_type
if "." in exc_type:
exc_type = exc_type.split(".")[-1]
return exc_type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unicode_to_ascii(obj):
# pragma: no cover """Convert to ASCII.""" |
# pylint: disable=E0602,R1717
if isinstance(obj, dict):
return dict(
[
(_unicode_to_ascii(key), _unicode_to_ascii(value))
for key, value in obj.items()
]
)
if isinstance(obj, list):
return [_unicode_to_ascii(element) for element in obj]
if isinstance(obj, unicode):
return obj.encode("utf-8")
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_remote_executors(hub_ip, port = 4444):
''' Get remote hosts from Selenium Grid Hub Console
@param hub_ip: hub ip of selenium grid hub
@param port: hub port of selenium grid hub
'''
resp = requests.get("http://%s:%s/grid/console" %(hub_ip, port))
remote_hosts = ()
if resp.status_code == 200:
remote_hosts = re.findall("remoteHost: ([\w/\.:]+)",resp.text)
return [host + "/wd/hub" for host in remote_hosts] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _production(self):
"""Calculate total energy production. Not rounded""" |
return self._nuclear + self._diesel + self._gas + self._wind + self._combined + self._vapor + self._solar + self._hydraulic + self._carbon + self._waste + self._other |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _links(self):
"""Calculate total energy production. Not Rounded""" |
total = 0.0
for value in self.link.values():
total += value
return total |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interface(self, context):
"""Implement the interface for the adapter object""" |
self.context = context
self.callback = self.context.get("callback") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _element(cls):
''' find the element with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
driver = Web.driver
try:
elements = WebDriverWait(driver, cls.__control["timeout"]).until(lambda driver: getattr(driver,"find_elements")(cls.__control["by"], cls.__control["value"]))
except:
raise Exception("Timeout at %d seconds.Element(%s) not found." %(cls.__control["timeout"],cls.__control["by"]))
if len(elements) < cls.__control["index"] + 1:
raise Exception("Element [%s]: Element Index Issue! There are [%s] Elements! Index=[%s]" % (cls.__name__, len(elements), cls.__control["index"]))
if len(elements) > 1:
print("Element [%s]: There are [%d] elements, choosed index=%d" %(cls.__name__,len(elements),cls.__control["index"]))
elm = elements[cls.__control["index"]]
cls.__control["index"] = 0
return elm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _elements(cls):
''' find the elements with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
driver = Web.driver
try:
elements = WebDriverWait(driver, cls.__control["timeout"]).until(lambda driver: getattr(driver,"find_elements")(cls.__control["by"], cls.__control["value"]))
except:
raise Exception("Timeout at %d seconds.Element(%s) not found." %(cls.__control["timeout"],cls.__control["by"]))
return elements |
<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(xCqNck7t, **kwargs):
"""Updates the Dict with the given values. Turns internal dicts into Dicts.""" |
def dict_list_val(inlist):
l = []
for i in inlist:
if type(i)==dict:
l.append(Dict(**i))
elif type(i)==list:
l.append(make_list(i))
elif type(i)==bytes:
l.append(i.decode('UTF-8'))
else:
l.append(i)
return l
for k in list(kwargs.keys()):
if type(kwargs[k])==dict:
xCqNck7t[k] = Dict(**kwargs[k])
elif type(kwargs[k])==list:
xCqNck7t[k] = dict_list_val(kwargs[k])
else:
xCqNck7t[k] = kwargs[k] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keys(self, key=None, reverse=False):
"""sort the keys before returning them""" |
ks = sorted(list(dict.keys(self)), key=key, reverse=reverse)
return ks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hub(self, port):
''' java -jar selenium-server.jar -role hub -port 4444
@param port: listen port of selenium hub
'''
self._ip = "localhost"
self._port = port
self.command = [self._conf["java_path"], "-jar", self._conf["jar_path"], "-port", str(port), "-role", "hub"]
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 start_server(self):
"""start the selenium Remote Server.""" |
self.__subp = subprocess.Popen(self.command)
#print("\tselenium jar pid[%s] is running." %self.__subp.pid)
time.sleep(2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def negate_gate(wordlen, input='x', output='~x'):
"""Implements two's complement negation.""" |
neg = bitwise_negate(wordlen, input, "tmp")
inc = inc_gate(wordlen, "tmp", output)
return neg >> inc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_list(lobj):
""" Recursively flattens a list. :param lobj: List to flatten :type lobj: list :rtype: list For example: [1, 2, 3, 4, 5, 6, 7] """ |
ret = []
for item in lobj:
if isinstance(item, list):
for sub_item in flatten_list(item):
ret.append(sub_item)
else:
ret.append(item)
return 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 load(self, file=CONFIG_FILE):
""" load a configuration file. loads default config if file is not found """ |
if not os.path.exists(file):
print("Config file was not found under %s. Default file has been created" % CONFIG_FILE)
self._settings = yaml.load(DEFAULT_CONFIG, yaml.RoundTripLoader)
self.save(file)
sys.exit()
with open(file, 'r') as f:
self._settings = yaml.load(f, yaml.RoundTripLoader) |
<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, file=CONFIG_FILE):
""" Save configuration to provided path as a yaml file """ |
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "w") as f:
yaml.dump(self._settings, f, Dumper=yaml.RoundTripDumper, width=float("inf")) |
<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):
"""Create the corresponding index. Will overwrite existing indexes of the same name.""" |
body = dict()
if self.mapping is not None:
body['mappings'] = self.mapping
if self.settings is not None:
body['settings'] = self.settings
else:
body['settings'] = self._default_settings()
self.instance.indices.create(self.index, 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 search(self, query=None, size=100, unpack=True):
"""Search the index with a query. Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned. The default number of hits returned is 100. """ |
logging.info('Download all documents from index %s.', self.index)
if query is None:
query = self.match_all
results = list()
data = self.instance.search(index=self.index, doc_type=self.doc_type, body=query, size=size)
if unpack:
for items in data['hits']['hits']:
if '_source' in items:
results.append(items['_source'])
else:
results.append(items)
else:
results = data['hits']['hits']
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scan_index(self, query: Union[Dict[str, str], None] = None) -> List[Dict[str, str]]: """Scan the index with the query. Will return any number of results above 10'000. Important to note is, that all the data is loaded into memory at once and returned. This works only with small data sets. Use scroll otherwise which returns a generator to cycle through the resources in set chunks. :param query: The query used to scan the index. Default None will return the entire index. :returns list of dicts: The list of dictionaries contains all the documents without metadata. """ |
if query is None:
query = self.match_all
logging.info('Download all documents from index %s with query %s.', self.index, query)
results = list()
data = scan(self.instance, index=self.index, doc_type=self.doc_type, query=query)
for items in data:
if '_source' in items:
results.append(items['_source'])
else:
results.append(items)
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scroll(self, query=None, scroll='5m', size=100, unpack=True):
"""Scroll an index with the specified search query. Works as a generator. Will yield `size` results per iteration until all hits are returned. """ |
query = self.match_all if query is None else query
response = self.instance.search(index=self.index, doc_type=self.doc_type, body=query, size=size, scroll=scroll)
while len(response['hits']['hits']) > 0:
scroll_id = response['_scroll_id']
logging.debug(response)
if unpack:
yield [source['_source'] if '_source' in source else source for source in response['hits']['hits']]
else:
yield response['hits']['hits']
response = self.instance.scroll(scroll_id=scroll_id, scroll=scroll) |
<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, identifier):
"""Fetch document by _id. Returns None if it is not found. (Will log a warning if not found as well. Should not be used to search an id.)""" |
logging.info('Download document with id ' + str(identifier) + '.')
try:
record = self.instance.get(index=self.index, doc_type=self.doc_type, id=identifier)
if '_source' in record:
return record['_source']
else:
return record
except NotFoundError:
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 index_into(self, document, id) -> bool: """Index a single document into the index.""" |
try:
self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id)
except RequestError as ex:
logging.error(ex)
return False
else:
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 delete(self, doc_id: str) -> bool: """Delete a document with id.""" |
try:
self.instance.delete(self.index, self.doc_type, doc_id)
except RequestError as ex:
logging.error(ex)
return False
else:
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 update(self, doc: dict, doc_id: str):
"""Partial update to a single document. Uses the Update API with the specified partial document. """ |
body = {
'doc': doc
}
self.instance.update(self.index, self.doc_type, doc_id, body=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 script_update(self, script: str, params: Union[dict, None], doc_id: str):
"""Uses painless script to update a document. See documentation for more information. """ |
body = {
'script': {
'source': script,
'lang': 'painless'
}
}
if params is not None:
body['script']['params'] = params
self.instance.update(self.index, self.doc_type, doc_id, body=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 bulk(self, data: List[Dict[str, str]], identifier_key: str, op_type='index', upsert=False, keep_id_key=False) -> bool: """ Takes a list of dictionaries and an identifier key and indexes everything into this index. :param data: List of dictionaries containing the data to be indexed. :param identifier_key: The name of the dictionary element which should be used as _id. This will be removed from the body. Is ignored when None or empty string. This will cause elastic to create their own _id. :param op_type: What should be done: 'index', 'delete', 'update'. :param upsert: The update op_type can be upserted, which will create a document if not already present. :param keep_id_key Determines if the value designated as the identifier_key should be kept as part of the document or removed from it. :returns Returns True if all the messages were indexed without errors. False otherwise. """ |
bulk_objects = []
for document in data:
bulk_object = dict()
bulk_object['_op_type'] = op_type
if identifier_key is not None and identifier_key != '':
bulk_object['_id'] = document[identifier_key]
if not keep_id_key:
document.pop(identifier_key)
if bulk_object['_id'] == '':
bulk_object.pop('_id')
if op_type == 'index':
bulk_object['_source'] = document
elif op_type == 'update':
bulk_object['doc'] = document
if upsert:
bulk_object['doc_as_upsert'] = True
bulk_objects.append(bulk_object)
logging.debug(str(bulk_object))
logging.info('Start bulk index for ' + str(len(bulk_objects)) + ' objects.')
errors = bulk(self.instance, actions=bulk_objects, index=self.index, doc_type=self.doc_type,
raise_on_error=False)
logging.info(str(errors[0]) + ' documents were successfully indexed/updated/deleted.')
if errors[0] - len(bulk_objects) != 0:
logging.error(str(len(bulk_objects) - errors[0]) + ' documents could not be indexed/updated/deleted.')
for error in errors[1]:
logging.error(str(error))
return False
else:
logging.debug('Finished bulk %s.', op_type)
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 reindex(self, new_index_name: str, identifier_key: str, **kwargs) -> 'ElasticIndex': """Reindex the entire index. Scrolls the old index and bulk indexes all data into the new index. :param new_index_name: :param identifier_key: :param kwargs: Overwrite ElasticIndex __init__ params. :return: """ |
if 'url' not in kwargs:
kwargs['url'] = self.url
if 'doc_type' not in kwargs:
kwargs['doc_type'] = self.doc_type
if 'mapping' not in kwargs:
kwargs['mapping'] = self.mapping
new_index = ElasticIndex(new_index_name, **kwargs)
for results in self.scroll(size=500):
new_index.bulk(results, identifier_key)
return new_index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, path: str, file_name: str = "", **kwargs: dict):
""" Dumps the entire index into a json file. :param path: The path to directory where the dump should be stored. :param file_name: Name of the file the dump should be stored in. If empty the index name is used. :param kwargs: Keyword arguments for the json converter. (ex. indent=4, ensure_ascii=False) """ |
export = list()
for results in self.scroll():
export.extend(results)
if not path.endswith('/'):
path += '/'
if file_name == '':
file_name = self.index
if not file_name.endswith('.json'):
file_name += '.json'
store = path + file_name
with open(store, 'w') as fp:
json.dump(export, fp, **kwargs)
logging.info("Extracted %s records from the index %s and stored them in %s/%s.", len(export), self.index, path, file_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 main():
""" parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon """ |
(options, _) = _parse_args()
if options.change_password:
c.keyring_set_password(c["username"])
sys.exit(0)
if options.select:
courses = client.get_courses()
c.selection_dialog(courses)
c.save()
sys.exit(0)
if options.stop:
os.system("kill -2 `cat ~/.studdp/studdp.pid`")
sys.exit(0)
task = _MainLoop(options.daemonize, options.update_courses)
if options.daemonize:
log.info("daemonizing...")
with daemon.DaemonContext(working_directory=".", pidfile=PIDLockFile(PID_FILE)):
# we have to create a new logger in the daemon context
handler = logging.FileHandler(LOG_PATH)
handler.setFormatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
log.addHandler(handler)
task()
else:
task() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self, signature_data):
"""Takes data and returns a signature :arg dict signature_data: data to use to generate a signature :returns: ``Result`` instance """ |
result = Result()
for rule in self.pipeline:
rule_name = rule.__class__.__name__
try:
if rule.predicate(signature_data, result):
rule.action(signature_data, result)
except Exception as exc:
if self.error_handler:
self.error_handler(
signature_data,
exc_info=sys.exc_info(),
extra={'rule': rule_name}
)
result.info(rule_name, 'Rule failed: %s', exc)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unblast(name2vals, name_map):
"""Helper function to lift str -> bool maps used by aiger to the word level. Dual of the `_blast` function.""" |
def _collect(names):
return tuple(name2vals[n] for n in names)
return {bvname: _collect(names) for bvname, names in name_map} |
<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_logger(self):
"""Generates a logger instance from the singleton""" |
name = "bors"
if hasattr(self, "name"):
name = self.name
self.log = logging.getLogger(name)
try:
lvl = self.conf.get_log_level()
except AttributeError:
lvl = self.context.get("log_level", None)
self.log.setLevel(getattr(logging, lvl, logging.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 get_cls(project_name, project_data):
""" gets class from name and data, sets base level attrs defaults to facsimile.base.Facsimile """ |
if project_name:
cls = getattr(facsimile.base, project_data.get('class', 'Facsimile'))
cls.name = project_name
else:
cls = facsimile.base.Facsimile
return 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 check_recaptcha(view_func):
"""Chech that the entered recaptcha data is correct""" |
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post(
'https://www.google.com/recaptcha/api/siteverify',
data=data
)
result = r.json()
if result['success']:
request.recaptcha_is_valid = True
else:
request.recaptcha_is_valid = False
error_message = 'Invalid reCAPTCHA. Please try again. '
error_message += str(result['error-codes'])
print(error_message)
return view_func(request, *args, **kwargs)
return _wrapped_view |
<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, context):
"""Execute the strategies on the given context""" |
for ware in self.middleware:
ware.premessage(context)
context = ware.bind(context)
ware.postmessage(context)
return context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self):
"""Perform cleanup! We're goin' down!!!""" |
for ware in self.middleware:
ware.preshutdown()
self._shutdown()
ware.postshutdown() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(argv=None):
"""Generates documentation for signature generation pipeline""" |
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'pipeline',
help='Python dotted path to rules pipeline to document'
)
parser.add_argument('output', help='output file')
if argv is None:
args = parser.parse_args()
else:
args = parser.parse_args(argv)
print('Generating documentation for %s in %s...' % (args.pipeline, args.output))
rules = import_rules(args.pipeline)
with open(args.output, 'w') as fp:
fp.write('.. THIS IS AUTOGEMERATED USING:\n')
fp.write(' \n')
fp.write(' %s\n' % (' '.join(sys.argv)))
fp.write(' \n')
fp.write('Signature generation rules pipeline\n')
fp.write('===================================\n')
fp.write('\n')
fp.write('\n')
fp.write(
'This is the signature generation pipeline defined at ``%s``:\n' %
args.pipeline
)
fp.write('\n')
for i, rule in enumerate(rules):
li = '%s. ' % (i + 1)
fp.write('%s%s\n' % (
li,
indent(get_doc(rule), ' ' * len(li))
))
fp.write('\n') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle(self, *args, **options):
"""This function is called by the Django API to specify how this object will be saved to the database. """ |
taxonomy_id = options['taxonomy_id']
# Remove leading and trailing blank characters in "common_name"
# and "scientific_name
common_name = options['common_name'].strip()
scientific_name = options['scientific_name'].strip()
if common_name and scientific_name:
# A 'slug' is a label for an object in django, which only contains
# letters, numbers, underscores, and hyphens, thus making it URL-
# usable. The slugify method in django takes any string and
# converts it to this format. For more information, see:
# http://stackoverflow.com/questions/427102/what-is-a-slug-in-django
slug = slugify(scientific_name)
logger.info("Slug generated: %s", slug)
# If organism exists, update with passed parameters
try:
org = Organism.objects.get(taxonomy_id=taxonomy_id)
org.common_name = common_name
org.scientific_name = scientific_name
org.slug = slug
# If organism doesn't exist, construct an organism object
# (see organisms/models.py).
except Organism.DoesNotExist:
org = Organism(taxonomy_id=taxonomy_id,
common_name=common_name,
scientific_name=scientific_name,
slug=slug
)
org.save() # Save to the database.
else:
# Report an error if the user did not fill out all fields.
logger.error(
"Failed to add or update organism. "
"Please check that all fields are filled correctly."
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False):
"""Creates a window of given resolution. :param resolution: the resolution of the windows as (width, height) in pixels :type resolution: tuple :param pygame_flags: modify the creation of the window. For further information see :ref:`creating_a_window` :type pygame_flags: int :param display_pos: determines the position on the desktop where the window is created. In a multi monitor system this can be used to position the window on a different monitor. E.g. the monitor to the right of the main-monitor would be at position (1920, 0) if the main monitor has the width 1920. :type display_pos: tuple :param interactive_mode: Will install a thread, that emptys the event-queue every 100ms. This is neccessary to be able to use the display() function in an interactive console on windows systems. If interactive_mode is set, init() will return a reference to the background thread. This thread has a stop() method which can be used to cancel it. If you use ctrl+d or exit() within ipython, while the thread is still running, ipython will become unusable, but not close. :type interactive_mode: bool :return: a reference to the display screen, or a reference to the background thread if interactive_mode was set to true. In the second scenario you can obtain a reference to the display surface via pygame.display.get_surface() :rtype: pygame.Surface """ |
os.environ['SDL_VIDEO_WINDOW_POS'] = "{}, {}".format(*display_pos)
pygame.init()
pygame.font.init()
disp = pygame.display.set_mode(resolution, pygame_flags)
return _PumpThread() if interactive_mode else disp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def empty_surface(fill_color, size=None):
"""Returns an empty surface filled with fill_color. :param fill_color: color to fill the surface with :type fill_color: pygame.Color :param size: the size of the new surface, if None its created to be the same size as the screen :type size: int-2-tuple """ |
sr = pygame.display.get_surface().get_rect()
surf = pygame.Surface(size or (sr.w, sr.h))
surf.fill(fill_color)
return surf |
<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):
""" Called by internal API subsystem to initialize websockets connections in the API interface """ |
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
def on_ws_connect(*args, **kwargs):
"""Callback on connect hook to set is_connected_ws"""
self.is_connected_ws = True
self.api.on_ws_connect(*args, **kwargs)
# Initialize websocket in a thread with channels
if hasattr(self.api, "on_ws_connect"):
self.thread = Process(target=self.api.connect_ws, args=(
on_ws_connect, [
SockChannel(channel, res_type, self._generate_result)
for channel, res_type in
self
.context
.get("conf")
.get("subscriptions")
.items()
]))
self.thread.start() |
<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_channels(self, channels):
""" Take a list of SockChannel objects and extend the websock listener """ |
chans = [
SockChannel(chan, res, self._generate_result)
for chan, res in channels.items()
]
self.api.channels.extend(chans)
self.api.connect_channels(chans) |
<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_result(self, res_type, channel, result):
"""Generate the result object""" |
schema = self.api.ws_result_schema()
schema.context['channel'] = channel
schema.context['response_type'] = res_type
self.callback(schema.load(result), self.context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rand_elem(seq, n=None):
"""returns a random element from seq n times. If n is None, it continues indefinitly""" |
return map(random.choice, repeat(seq, n) if n is not None else repeat(seq)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def first_paragraph(multiline_str, without_trailing_dot=True, maxlength=None):
'''Return first paragraph of multiline_str as a oneliner.
When without_trailing_dot is True, the last char of the first paragraph
will be removed, if it is a dot ('.').
Examples:
>>> multiline_str = 'first line\\nsecond line\\n\\nnext paragraph'
>>> print(first_paragraph(multiline_str))
first line second line
>>> multiline_str = 'first \\n second \\n \\n next paragraph '
>>> print(first_paragraph(multiline_str))
first second
>>> multiline_str = 'first line\\nsecond line\\n\\nnext paragraph'
>>> print(first_paragraph(multiline_str, maxlength=3))
fir
>>> multiline_str = 'first line\\nsecond line\\n\\nnext paragraph'
>>> print(first_paragraph(multiline_str, maxlength=78))
first line second line
>>> multiline_str = 'first line.'
>>> print(first_paragraph(multiline_str))
first line
>>> multiline_str = 'first line.'
>>> print(first_paragraph(multiline_str, without_trailing_dot=False))
first line.
>>> multiline_str = ''
>>> print(first_paragraph(multiline_str))
<BLANKLINE>
'''
stripped = '\n'.join([line.strip() for line in multiline_str.splitlines()])
paragraph = stripped.split('\n\n')[0]
res = paragraph.replace('\n', ' ')
if without_trailing_dot:
res = res.rsplit('.', 1)[0]
if maxlength:
res = res[0:maxlength]
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_doc1(*args, **kwargs):
'''Print the first paragraph of the docstring of the decorated function. The paragraph will be printed as a oneliner. May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``) or with named arguments ``color``, ``bold``, ``prefix`` of ``tail`` (eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``). Examples: |
# ... pass
# ...
# >>> foo()
# \033[34mFirst line of docstring\033[0m
# >>> @print_doc1
# ... def foo():
# ... """First paragraph of docstring which contains more than one
# ... line.
# ...
# ... Another paragraph.
# ... """
# ... pass
# ...
# >>> foo()
# \033[34mFirst paragraph of docstring which contains more than one line\033[0m
'''
# output settings from kwargs or take defaults
color = kwargs.get('color', blue)
bold = kwargs.get('bold', False)
prefix = kwargs.get('prefix', '')
tail = kwargs.get('tail', '\n')
def real_decorator(func):
'''real decorator function'''
@wraps(func)
def wrapper(*args, **kwargs):
'''the wrapper function'''
try:
prgf = first_paragraph(func.__doc__)
print(color(prefix + prgf + tail, bold))
except AttributeError as exc:
name = func.__name__
print(red(flo('{name}() has no docstring')))
raise(exc)
return func(*args, **kwargs)
return wrapper
invoked = bool(not args or kwargs)
if not invoked:
# invoke decorator function which returns the wrapper function
return real_decorator(func=args[0])
return real_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 print_full_name(*args, **kwargs):
'''Decorator, print the full name of the decorated function.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, or ``prefix``
(eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``).
'''
color = kwargs.get('color', default_color)
bold = kwargs.get('bold', False)
prefix = kwargs.get('prefix', '')
tail = kwargs.get('tail', '')
def real_decorator(func):
'''real decorator function'''
@wraps(func)
def wrapper(*args, **kwargs):
'''the wrapper function'''
first_line = ''
try:
first_line = func.__module__ + '.' + func.__qualname__
except AttributeError as exc:
first_line = func.__name__
print(color(prefix + first_line + tail, bold))
return func(*args, **kwargs)
return wrapper
invoked = bool(not args or kwargs)
if not invoked:
# invoke decorator function which returns the wrapper function
return real_decorator(func=args[0])
return real_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 filled_out_template_str(template, **substitutions):
'''Return str template with applied substitutions.
Example:
>>> template = 'Asyl for {{name}} {{surname}}!'
>>> filled_out_template_str(template, name='Edward', surname='Snowden')
'Asyl for Edward Snowden!'
>>> template = '[[[foo]]] was substituted by {{foo}}'
>>> filled_out_template_str(template, foo='bar')
'{{foo}} was substituted by bar'
>>> template = 'names wrapped by {single} {curly} {braces} {{curly}}'
>>> filled_out_template_str(template, curly='remains unchanged')
'names wrapped by {single} {curly} {braces} remains unchanged'
'''
template = template.replace('{', '{{')
template = template.replace('}', '}}')
template = template.replace('{{{{', '{')
template = template.replace('}}}}', '}')
template = template.format(**substitutions)
template = template.replace('{{', '{')
template = template.replace('}}', '}')
template = template.replace('[[[', '{{')
template = template.replace(']]]', '}}')
return template |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def filled_out_template(filename, **substitutions):
'''Return content of file filename with applied substitutions.'''
res = None
with open(filename, 'r') as fp:
template = fp.read()
res = filled_out_template_str(template, **substitutions)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def convert_unicode_2_utf8(input):
'''Return a copy of `input` with every str component encoded from unicode to
utf-8.
'''
if isinstance(input, dict):
try:
# python-2.6
return dict((convert_unicode_2_utf8(key), convert_unicode_2_utf8(value))
for key, value
in input.iteritems())
except AttributeError:
# since python-2.7 cf. http://stackoverflow.com/a/1747827
# [the ugly eval('...') is required for a valid syntax on
# python-2.6, cf. http://stackoverflow.com/a/25049535]
return eval('''{convert_unicode_2_utf8(key): convert_unicode_2_utf8(value)
for key, value
in input.items()}''')
elif isinstance(input, list):
return [convert_unicode_2_utf8(element) for element in input]
# elif order relevant: python2 vs. python3
# cf. http://stackoverflow.com/a/19877309
elif isinstance(input, str):
return input
else:
try:
if eval('''isinstance(input, unicode)'''):
return input.encode('utf-8')
except NameError:
# unicode does not exist in python-3.x
pass
return input |
<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_json(filename, gzip_mode=False):
'''Return the json-file data, with all strings utf-8 encoded.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'rt') as fh:
data = json.load(fh)
data = convert_unicode_2_utf8(data)
return data
except AttributeError:
# Python-2.6
fh = open_file(filename, 'rt')
data = json.load(fh)
fh.close()
data = convert_unicode_2_utf8(data)
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 write_json(data, filename, gzip_mode=False):
'''Write the python data structure as a json-Object to filename.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'wt') as fh:
json.dump(obj=data, fp=fh, sort_keys=True)
except AttributeError:
# Python-2.6
fh = open_file(filename, 'wt')
json.dump(obj=data, fp=fh, sort_keys=True)
fh.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 text_with_newlines(text, line_length=78, newline='\n'):
'''Return text with a `newline` inserted after each `line_length` char.
Return `text` unchanged if line_length == 0.
'''
if line_length > 0:
if len(text) <= line_length:
return text
else:
return newline.join([text[idx:idx+line_length]
for idx
in range(0, len(text), line_length)])
else:
return 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 _readlines(fname, fpointer1=open, fpointer2=open):
# pragma: no cover """Read all lines from file.""" |
# fpointer1, fpointer2 arguments to ease testing
try:
with fpointer1(fname, "r") as fobj:
return fobj.readlines()
except UnicodeDecodeError: # pragma: no cover
with fpointer2(fname, "r", encoding="utf-8") as fobj:
return fobj.readlines() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def launch_plugin(self):
'''
launch nagios_plugin command
'''
# nagios_plugins probes
for plugin in self.plugins:
# Construct the nagios_plugin command
command = ('%s%s' % (self.plugins[plugin]['path'], self.plugins[plugin]['command']))
try:
nagios_plugin = subprocess.Popen(command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError:
LOG.error("[nagios_plugins]: '%s' executable is missing",
command)
else:
output = nagios_plugin.communicate()[0].strip()
return_code = nagios_plugin.returncode
if return_code >= len(STATUSES):
LOG.error("[nagios_plugins]: '%s' executable has an issue, return code: %s",
command, return_code)
else:
LOG.log(STATUSES[return_code][1],
"[nagios_plugins][%s] (%s status): %s",
plugin,
STATUSES[return_code][0],
output)
yield {'return_code': int(return_code),
'output': str(output),
'time_stamp': int(time.time()),
'service_description': plugin,
'specific_servers': self.plugins[plugin]['servers']} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):
"""for a given path and regexp pattern, return the files that match""" |
return sorted(
[
Class(fn=fn)
for fn in rglob(path, f"*{ext or ''}")
if re.search(pattern, os.path.basename(fn), flags=flags) is not None
and os.path.basename(fn)[0] != '~' # omit temp files
],
key=sortkey,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self, new_fn):
"""copy the file to the new_fn, preserving atime and mtime""" |
new_file = self.__class__(fn=str(new_fn))
new_file.write(data=self.read())
new_file.utime(self.atime, self.mtime)
return new_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 make_basename(self, fn=None, ext=None):
"""make a filesystem-compliant basename for this file""" |
fb, oldext = os.path.splitext(os.path.basename(fn or self.fn))
ext = ext or oldext.lower()
fb = String(fb).hyphenify(ascii=True)
return ''.join([fb, ext]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tempfile(self, mode='wb', **args):
"write the contents of the file to a tempfile and return the tempfile filename"
tf = tempfile.NamedTemporaryFile(mode=mode)
self.write(tf.name, mode=mode, **args)
return tfn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""delete the file from the filesystem.""" |
if self.isfile:
os.remove(self.fn)
elif self.isdir:
shutil.rmtree(self.fn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readable_size(C, bytes, suffix='B', decimals=1, sep='\u00a0'):
"""given a number of bytes, return the file size in readable units""" |
if bytes is None:
return
size = float(bytes)
for unit in C.SIZE_UNITS:
if abs(size) < 1024 or unit == C.SIZE_UNITS[-1]:
return "{size:.{decimals}f}{sep}{unit}{suffix}".format(
size=size,
unit=unit,
suffix=suffix,
sep=sep,
decimals=C.SIZE_UNITS.index(unit) > 0 and decimals or 0, # B with no decimal
)
size /= 1024 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, url, method, data=None, headers=None):
"""Makes a HTTP call, formats response and does error handling. """ |
http_headers = merge_dict(self.default_headers, headers or {})
request_data = merge_dict({'api_key': self.apikey}, data or {})
logger.info('HTTP %s REQUEST TO %s' % (method, url))
start = datetime.datetime.now()
try:
response = requests.request(method=method, url=url, data=json.dumps(request_data),
headers=http_headers)
except exceptions.BadRequestError as e:
return json.loads({'errors': e.content})
duration = datetime.datetime.now() - start
logger.info('RESPONSE %s DURATION %s.%s' % (response.encoding, duration.seconds,
duration.microseconds))
return json.loads(response.content) if response.content 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 calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
""" Calculates a good piece size for a size """ |
logger.debug('Calculating piece size for %i' % size)
for i in range(min_piece_size, max_piece_size): # 20 = 1MB
if size / (2**i) < max_piece_count:
break
return 2**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 split_pieces(piece_list, segments, num):
""" Prepare a list of all pieces grouped together """ |
piece_groups = []
pieces = list(piece_list)
while pieces:
for i in range(segments):
p = pieces[i::segments][:num]
if not p:
break
piece_groups.append(p)
pieces = pieces[num * segments:]
return piece_groups |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rglob(dirname, pattern, dirs=False, sort=True):
"""recursive glob, gets all files that match the pattern within the directory tree""" |
fns = []
path = str(dirname)
if os.path.isdir(path):
fns = glob(os.path.join(escape(path), pattern))
dns = [fn for fn
in [os.path.join(path, fn)
for fn in os.listdir(path)]
if os.path.isdir(fn)]
if dirs==True:
fns += dns
for d in dns:
fns += rglob(d, pattern)
if sort==True:
fns.sort()
else:
log.warn("not a directory: %r" % path)
return fns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def after(parents, func=None):
'''Create a new Future whose completion depends on parent futures
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
callback returns a future or list of futures. In those cases, waiting
on the dependent will also wait for all those futures, and the result
(or list of results) of those future(s) will then be the final value.
:param parents:
A list of futures, all of which must be complete before the
dependent's function runs.
:type parents: list
:param function func:
The function to determine the value of the dependent future. It
will take as many arguments as it has parents, and they will be the
results of those futures.
:returns:
a :class:`Dependent`, which is a subclass of :class:`Future` and
has all its capabilities.
'''
if func is None:
return lambda f: after(parents, f)
dep = Dependent(parents, func)
for parent in parents:
if parent.complete:
dep._incoming(parent, parent.value)
else:
parent._children.append(weakref.ref(dep))
return dep |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wait_all(futures, timeout=None):
'''Wait for the completion of all futures in a list
:param list future: a list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, can block indefinitely.
:type timeout: float or None
:raises WaitTimeout: if a timeout is provided and hit
'''
if timeout is not None:
deadline = time.time() + timeout
for fut in futures:
fut.wait(deadline - time.time())
else:
for fut in futures:
fut.wait() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def value(self):
'''The final value, if it has arrived
:raises: AttributeError, if not yet complete
:raises: an exception if the Future was :meth:`abort`\ed
'''
if not self._done.is_set():
raise AttributeError("value")
if self._failure:
raise self._failure[0], self._failure[1], self._failure[2]
return self._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 finish(self, value):
'''Give the future it's value and trigger any associated callbacks
:param value: the new value for the future
:raises:
:class:`AlreadyComplete <junction.errors.AlreadyComplete>` if
already complete
'''
if self._done.is_set():
raise errors.AlreadyComplete()
self._value = value
for cb in self._cbacks:
backend.schedule(cb, args=(value,))
self._cbacks = None
for wait in list(self._waits):
wait.finish(self)
self._waits = None
for child in self._children:
child = child()
if child is None:
continue
child._incoming(self, value)
self._children = None
self._done.set() |
<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_finish(self, func):
'''Assign a callback function to be run when successfully complete
:param function func:
A callback to run when complete. It will be given one argument (the
value that has arrived), and it's return value is ignored.
'''
if self._done.is_set():
if self._failure is None:
backend.schedule(func, args=(self._value,))
else:
self._cbacks.append(func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def after(self, func=None, other_parents=None):
'''Create a new Future whose completion depends on this one
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
callback returns a future or list of futures. In those cases, waiting
on the dependent will also wait for all those futures, and the result
(or list of results) of those future(s) will then be the final value.
:param function func:
The function to determine the value of the dependent future. It
will take as many arguments as it has parents, and they will be the
results of those futures.
:param other_parents:
A list of futures, all of which (along with this one) must be
complete before the dependent's function runs.
:type other_parents: list or None
:returns:
a :class:`Dependent`, which is a subclass of :class:`Future` and
has all its capabilities.
'''
parents = [self]
if other_parents is not None:
parents += other_parents
return after(parents, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def os_path_transform(self, s, sep=os.path.sep):
""" transforms any os path into unix style """ |
if sep == '/':
return s
else:
return s.replace(sep, '/') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_dst(self, dst_dir, src):
""" finds the destination based on source if source is an absolute path, and there's no pattern, it copies the file to base dst_dir """ |
if os.path.isabs(src):
return os.path.join(dst_dir, os.path.basename(src))
return os.path.join(dst_dir, src) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, fn=None):
"""copy the zip file from its filename to the given filename.""" |
fn = fn or self.fn
if not os.path.exists(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
f = open(self.fn, 'rb')
b = f.read()
f.close()
f = open(fn, 'wb')
f.write(b)
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 assign(self, attrs):
"""Merge new attributes """ |
for k, v in attrs.items():
setattr(self, k, v) |
<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_rust_function(self, function, line):
"""Normalizes a single rust frame with a function""" |
# Drop the prefix and return type if there is any
function = drop_prefix_and_return_type(function)
# Collapse types
function = collapse(
function,
open_string='<',
close_string='>',
replacement='<T>',
exceptions=(' as ',)
)
# Collapse arguments
if self.collapse_arguments:
function = collapse(
function,
open_string='(',
close_string=')',
replacement=''
)
if self.signatures_with_line_numbers_re.match(function):
function = '{}:{}'.format(function, line)
# Remove spaces before all stars, ampersands, and commas
function = self.fixup_space.sub('', function)
# Ensure a space after commas
function = self.fixup_comma.sub(', ', function)
# Remove rust-generated uniqueness hashes
function = self.fixup_hash.sub('', function)
return function |
<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_cpp_function(self, function, line):
"""Normalizes a single cpp frame with a function""" |
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len(ref)].strip()
# Drop the prefix and return type if there is any if it's not operator
# overloading--operator overloading syntax doesn't have the things
# we're dropping here and can look curious, so don't try
if '::operator' not in function:
function = drop_prefix_and_return_type(function)
# Collapse types
function = collapse(
function,
open_string='<',
close_string='>',
replacement='<T>',
exceptions=('name omitted', 'IPC::ParamTraits')
)
# Collapse arguments
if self.collapse_arguments:
function = collapse(
function,
open_string='(',
close_string=')',
replacement='',
exceptions=('anonymous namespace', 'operator')
)
# Remove PGO cold block labels like "[clone .cold.222]". bug #1397926
if 'clone .cold' in function:
function = collapse(
function,
open_string='[',
close_string=']',
replacement=''
)
if self.signatures_with_line_numbers_re.match(function):
function = '{}:{}'.format(function, line)
# Remove spaces before all stars, ampersands, and commas
function = self.fixup_space.sub('', function)
# Ensure a space after commas
function = self.fixup_comma.sub(', ', function)
return function |
<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_frame( self, module=None, function=None, file=None, line=None, module_offset=None, offset=None, normalized=None, **kwargs # eat any extra kwargs passed in ):
"""Normalizes a single frame Returns a structured conglomeration of the input parameters to serve as a signature. The parameter names of this function reflect the exact names of the fields from the jsonMDSW frame output. This allows this function to be invoked by passing a frame as ``**a_frame``. Sometimes, a frame may already have a normalized version cached. If that exists, return it instead. """ |
# If there's a cached normalized value, use that so we don't spend time
# figuring it out again
if normalized is not None:
return normalized
if function:
# If there's a filename and it ends in .rs, then normalize using
# Rust rules
if file and (parse_source_file(file) or '').endswith('.rs'):
return self.normalize_rust_function(
function=function,
line=line
)
# Otherwise normalize it with C/C++ rules
return self.normalize_cpp_function(
function=function,
line=line
)
# If there's a file and line number, use that
if file and line:
filename = file.rstrip('/\\')
if '\\' in filename:
file = filename.rsplit('\\')[-1]
else:
file = filename.rsplit('/')[-1]
return '{}#{}'.format(file, line)
# If there's an offset and no module/module_offset, use that
if not module and not module_offset and offset:
return '@{}'.format(offset)
# Return module/module_offset
return '{}@{}'.format(module or '', module_offset) |
<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_tag(t):
"""Fix up some garbage errors.""" |
# TODO: when score present, include info.
t = _scored_patt.sub(string=t, repl='')
if t == '_country_' or t.startswith('_country:'):
t = 'nnp_country'
elif t == 'vpb':
t = 'vb' # "carjack" is listed with vpb tag.
elif t == 'nnd':
t = 'nns' # "abbes" is listed with nnd tag.
elif t == 'nns_root:':
t = 'nns' # 'micros' is listed as nns_root.
elif t == 'root:zygote':
t = 'nn' # 'root:zygote' for zygote. :-/
elif t.startswith('root:'):
t = 'uh' # Don't know why, but these are all UH tokens.
elif t in ('abbr_united_states_marine_corps', 'abbr_orange_juice'):
t = "abbreviation"
elif t == '+abbreviation':
t = 'abbreviation'
elif t.startswith('fw_misspelling:'):
t = 'fw'
return 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 parent(self):
"""return the parent URL, with params, query, and fragment in place""" |
path = '/'.join(self.path.split('/')[:-1])
s = path.strip('/').split(':')
if len(s)==2 and s[1]=='':
return None
else:
return self.__class__(self, path=path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(C, *args, **kwargs):
"""join a list of url elements, and include any keyword arguments, as a new URL""" |
u = C('/'.join([str(arg).strip('/') for arg in args]), **kwargs)
return u |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def select_peer(peer_addrs, service, routing_id, method):
'''Choose a target from the available peers for a singular message
:param peer_addrs:
the ``(host, port)``s of the peers eligible to handle the RPC, and
possibly a ``None`` entry if this hub can handle it locally
:type peer_addrs: list
:param service: the service of the message
:type service: anything hash-able
:param routing_id: the routing_id of the message
:type routing_id: int
:param method: the message method name
:type method: string
:returns: one of the provided peer_addrs
There is no reason to call this method directly, but it may be useful to
override it in a Hub subclass.
This default implementation uses ``None`` if it is available (prefer local
handling), then falls back to a random selection.
'''
if any(p is None for p in peer_addrs):
return None
return random.choice(peer_addrs) |
<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, key=None, **params):
"""initialize process timing for the current stack""" |
self.params.update(**params)
key = key or self.stack_key
if key is not None:
self.current_times[key] = time() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finish(self):
"""record the current stack process as finished""" |
self.report(fraction=1.0)
key = self.stack_key
if key is not None:
if self.data.get(key) is None:
self.data[key] = []
start_time = self.current_times.get(key) or time()
self.data[key].append(Dict(runtime=time()-start_time, **self.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 add_directive_header(self, sig):
"""Add the directive header and options to the generated content.""" |
domain = getattr(self, 'domain', 'py')
directive = getattr(self, 'directivetype', "module")
name = self.format_name()
self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig),
'<autodoc>')
if self.options.noindex:
self.add_line(u' :noindex:', '<autodoc>')
if self.objpath:
# Be explicit about the module, this is necessary since .. class::
# etc. don't support a prepended module name
self.add_line(u' :module: %s' % self.modname, '<autodoc>') |
<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(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
# don't have the connection attempt reconnects, because when it goes
# down we are going to cycle to the next potential peer from the Client
self._peer = connection.Peer(
None, self._dispatcher, self._addrs.popleft(),
backend.Socket(), reconnect=False)
self._peer.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reset(self):
"Close the current failed connection and prepare for a new one"
log.info("resetting client")
rpc_client = self._rpc_client
self._addrs.append(self._peer.addr)
self.__init__(self._addrs)
self._rpc_client = rpc_client
self._dispatcher.rpc_client = rpc_client
rpc_client._client = weakref.ref(self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.