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 imshow_z(data, name): """2D color plot of the quasiparticle weight as a function of interaction and doping"""
zmes = pick_flat_z(data) plt.figure() plt.imshow(zmes.T, origin='lower', \ extent=[data['doping'].min(), data['doping'].max(), \ 0, data['u_int'].max()], aspect=.16) plt.colorbar() plt.xlabel('$n$', fontsize=20) plt.ylabel('$U/D$', fontsize=20) plt.savefig(name+'_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 plot_mean_field_conv(N=1, n=0.5, Uspan=np.arange(0, 3.6, 0.5)): """Generates the plot on the convergenge of the mean field in single site spin hamiltonian un...
sl = Spinon(slaves=2*N, orbitals=N, avg_particles=2*n, hopping=[0.5]*2*N, orbital_e=[0]*2*N) hlog = solve_loop(sl, Uspan, [0.])[1] f, (ax1, ax2) = plt.subplots(2, sharex=True) for field in hlog: field = np.asarray(field) ax1.semilogy(abs(field[1:]-field[:-1])) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """Returns the model properties as a dict"""
result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, 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 from_config(cls): """Method to return back a loaded instance."""
config = Config() client = cls( email=config.get('email'), api_key=config.get('api_key'), server=config.get('api_server'), http_proxy=config.get('http_proxy'), https_proxy=config.get('https_proxy'), ) 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 set_debug(self, status): """Control the logging state."""
if status: self.logger.setLevel('DEBUG') else: self.logger.setLevel('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 _endpoint(self, endpoint, action, *url_args): """Return the URL for the action. :param str endpoint: The controller :param str action: The action provided by...
args = (self.api_base, endpoint, action) if action == '': args = (self.api_base, endpoint) api_url = "/".join(args) if url_args: if len(url_args) == 1: api_url += "/" + url_args[0] else: api_url += "/".join(url_args) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _json(self, response): """JSON response from server. :param response: Response from the server :throws ValueError: from requests' response.json() error :retu...
if response.status_code == 204: return None try: return response.json() except ValueError as e: raise ValueError( 'Exception: %s\n' 'request: %s, response code: %s, response: %s' % ( str(e), response.request...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get(self, endpoint, action, *url_args, **url_params): """Request API Endpoint - for GET methods. :param str endpoint: Endpoint :param str action: Endpoint A...
api_url = self._endpoint(endpoint, action, *url_args) kwargs = {'headers': self.headers, 'params': url_params, 'timeout': Client.TIMEOUT, 'verify': self.verify} if self.proxies: kwargs['proxies'] = self.proxies self.logger.debug("Requesting: %s, %s" % (api_...
<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_data(self, method, endpoint, action, data, *url_args, **url_params): """Submit to API Endpoint - for DELETE, PUT, POST methods. :param str method: Meth...
api_url = self._endpoint(endpoint, action, *url_args) data.update({'email': self.email, 'api_key': self.api_key}) data = json.dumps(data) kwargs = {'headers': self.headers, 'params': url_params, 'verify': self.verify, 'data': data} if self.proxies: ...
<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_events(events, source_ip): """Process all the events for logging and S3."""
s3 = boto3.resource('s3') table = boto3.resource("dynamodb").Table(os.environ['database']) with table.batch_writer() as batch: for idx, event in enumerate(events): event = convert_keys_to_string(event) event['sourceIp'] = source_ip event['event'] = hashlib.sha256...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cost_type(self, cost_type): """Sets the cost_type of this TableRateShipping. :param cost_type: The cost_type of this TableRateShipping. :type: str """
allowed_values = ["orderSubtotal", "weight"] if cost_type is not None and cost_type not in allowed_values: raise ValueError( "Invalid value for `cost_type` ({0}), must be one of {1}" .format(cost_type, allowed_values) ) self._cost_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 get_source(path): ''' yields all non-empty lines in a file ''' for line in read(path): if 'import' in line or len(line.strip()) == 0 or line.startswith('#'): continue if '__name__' in line and '__main__' in line: break else: yield line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, request): """ Authenticate request using HTTP Basic authentication protocl. If the user is successfully identified, the corresponding user...
# todo: can we trust that request.user variable is even defined? if request.user and request.user.is_authenticated(): return request.user if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 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 clean(): """Clean up previous garbage"""
os.chdir(os.path.join(project_root, 'docs')) sh("make clean") os.chdir(project_root) sh("rm -rf pyoauth2.egg-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 average(): """ generator that holds a rolling average """
count = 0 total = total() i=0 while 1: i = yield ((total.send(i)*1.0)/count if count else 0) count += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def args(self): """Parsed command-line arguments."""
if self._args is None: parser = self._build_parser() self._args = parser.parse_args() return self._args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_pypackage_basename(self, pytree, base): """Build the string representing the parsed package basename. :param str pytree: The pytree absolute path. :par...
dirname = os.path.dirname(pytree) parsed_package_name = base.replace(dirname, '').strip('/') return parsed_package_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 _build_parser(self): """Build the needed command-line parser."""
parser = argparse.ArgumentParser() parser.add_argument('--pytree', required=True, type=self._valid_directory, help='This is the path, absolute or relative, of the Python package ' 'that...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_pyfile_path_from_docname(self, docfile): """Build the expected Python file name based on the given documentation file name. :param str docfile: The doc...
name, ext = os.path.splitext(docfile) expected_py_name = name.replace('.', '/') + '.py' return expected_py_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 calculate_tree_differences(self, pytree, doctree): """Calculate the differences between the given trees. :param dict pytree: The dictionary of the parsed Pyt...
pykeys = set(pytree.keys()) dockeys = set(doctree.keys()) # Calculate the missing documentation files, if any. missing_doc_keys = pykeys - dockeys missing_docs = {pytree[pyfile] for pyfile in missing_doc_keys} # Calculate the missing Python files, if any. missi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_trees(self, parsed_pytree, parsed_doctree): """Compare the given parsed trees. :param dict parsed_pytree: A dictionary representing the parsed Python...
if parsed_pytree == parsed_doctree: return 0 missing_pys, missing_docs = self.calculate_tree_differences(pytree=parsed_pytree, doctree=parsed_doctree) self.pprint_tree_differences(missing_pys=missing_pys, missing_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_doc_tree(self, doctree, pypackages): """Parse the given documentation tree. :param str doctree: The absolute path to the documentation tree which is to...
parsed_doctree = {} for filename in os.listdir(doctree): if self._ignore_docfile(filename): continue expected_pyfile = self.build_pyfile_path_from_docname(filename) parsed_doctree[expected_pyfile] = filename pypackages = {name + '.py' for na...
<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_py_tree(self, pytree): """Parse the given Python package tree. :param str pytree: The absolute path to the Python tree which is to be parsed. :rtype: d...
parsed_pytree = {} pypackages = set() for base, dirs, files in os.walk(pytree): if self._ignore_pydir(os.path.basename(base)): continue # TODO(Anthony): If this is being run against a Python 3 package, this needs to be # adapted to account fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pprint_tree_differences(self, missing_pys, missing_docs): """Pprint the missing files of each given set. :param set missing_pys: The set of missing Python fi...
if missing_pys: print('The following Python files appear to be missing:') for pyfile in missing_pys: print(pyfile) print('\n') if missing_docs: print('The following documentation files appear to be missing:') for docfiile in m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _valid_directory(self, path): """Ensure that the given path is valid. :param str path: A valid directory path. :raises: :py:class:`argparse.ArgumentTypeError...
abspath = os.path.abspath(path) if not os.path.isdir(abspath): raise argparse.ArgumentTypeError('Not a valid directory: {}'.format(abspath)) return abspath
<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(self): """Parse package trees and report on any discrepancies."""
args = self.args parsed_pytree, pypackages = self.parse_py_tree(pytree=args.pytree) parsed_doctree = self.parse_doc_tree(doctree=args.doctree, pypackages=pypackages) return self.compare_trees(parsed_pytree=parsed_pytree, parsed_doctree=parsed_doctree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where_unique(cls, ip, object_id, location): """ Get db model by username """
return cls.query.filter_by( ip=ip, object_id=object_id, location=location).first()
<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_where_unique(cls, ip, object_id, location): """ delete by ip and object id """
result = cls.where_unique(ip, object_id, location) if result is None: return None result.delete() 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 do_req(self, method, url, body=None, headers=None, status=None): """Used internally to send a request to the API, left public so it can be used to talk to th...
if body is None: body = '' else: body = json.dumps(body) res = self.backend.dispatch_request(method=method, url=url, body=body, headers=sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _depaginate_all(self, url): """GETs the url provided and traverses the 'next' url that's returned while storing the data in a list. Returns a single list of ...
items = [] for x in self._depagination_generator(url): items += x return 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 create_user(self, user_id, roles=None, netmask=None, secret=None, pubkey=None): u"""Create user for the Merchant given in the X-Mcash-Merchant header. Argume...
arguments = {'id': user_id, 'roles': roles, 'netmask': netmask, 'secret': secret, 'pubkey': pubkey} return self.do_req('POST', self.merchant_api_base_url + '/user/', arguments).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_user(self, user_id, roles=None, netmask=None, secret=None, pubkey=None): """Update user. Returns the raw response object. Arguments: user_id: User id ...
arguments = {'roles': roles, 'netmask': netmask, 'secret': secret, 'pubkey': pubkey} return self.do_req('PUT', self.merchant_api_base_url + '/user/' + user_id + '/', arguments)
<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_pos(self, name, pos_type, pos_id, location=None): """Create POS resource Arguments: name: Human-readable name of the POS, used for displaying payment ...
arguments = {'name': name, 'type': pos_type, 'id': pos_id, 'location': location} return self.do_req('POST', self.merchant_api_base_url + '/pos/', arguments).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_pos(self, pos_id, name, pos_type, location=None): """Update POS resource. Returns the raw response object. Arguments: pos_id: POS id as chosen on regi...
arguments = {'name': name, 'type': pos_type, 'location': location} return self.do_req('PUT', self.merchant_api_base_url + '/pos/' + pos_id + '/', arguments)
<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_payment_request(self, customer, currency, amount, allow_credit, pos_id, pos_tid, action, ledger=None, display_message_uri=None, callback_uri=None, addi...
arguments = {'customer': customer, 'currency': currency, 'amount': amount, 'allow_credit': allow_credit, 'pos_id': pos_id, 'pos_tid': pos_tid, 'action': action, 'le...
<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_payment_request(self, tid, currency=None, amount=None, action=None, ledger=None, callback_uri=None, display_message_uri=None, capture_id=None, addition...
arguments = {'ledger': ledger, 'display_message_uri': display_message_uri, 'callback_uri': callback_uri, 'currency': currency, 'amount': amount, 'additional_amount': additional_amount, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_chat_message(self, merchant_id, channel_id, message): """post a chat message Arguments: channel_id: Scan token """
return self.do_req('POST', self.base_url + '/chat/v1/merchant/%s/channel/%s/message/' % (merchant_id, channel_id), message)
<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_shortlink(self, callback_uri=None, description=None, serial_number=None): """Register new shortlink Arguments: callback_uri: URI called by mCASH when ...
arguments = {'callback_uri': callback_uri, 'description': description, 'serial_number': serial_number} return self.do_req('POST', self.merchant_api_base_url + '/shortlink/', arguments).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_shortlink(self, shortlink_id, callback_uri=None, description=None): """Update existing shortlink registration Arguments: shortlink_id: Shortlink id as...
arguments = {'callback_uri': callback_uri, 'description': description} return self.do_req('PUT', self.merchant_api_base_url + '/shortlink/' + shortlink_id + '/', arguments)
<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_shortlink(self, shortlink_id_or_url): """Retrieve registered shortlink info Arguments: shortlink_id_or_url: Shortlink id or url, assigned by mCASH """
if "://" not in shortlink_id_or_url: shortlink_id_or_url = self.merchant_api_base_url + '/shortlink/' + shortlink_id_or_url + '/' return self.do_req('GET', shortlink_id_or_url).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_ledger(self, currency, description=None): """Create a ledger """
arguments = {'currency': currency, 'description': description} return self.do_req('POST', self.merchant_api_base_url + '/ledger/', arguments).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_ledger(self, ledger_id, description=None): """Update ledger info Arguments: ledger_id: Ledger id assigned by mCASH description: Description of the Led...
arguments = {'description': description} return self.do_req('PUT', self.merchant_api_base_url + '/ledger/' + ledger_id + '/', arguments)
<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_report(self, ledger_id, report_id, callback_uri=None): u"""Close Report When you PUT to a report, it will start the process of closing it. When the clo...
arguments = {'callback_uri': callback_uri} return self.do_req('PUT', self.merchant_api_base_url + '/ledger/' + ledger_id + '/report/' + report_id + '/', arguments)
<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_report(self, ledger_id, report_id): """Get report info Arguments: ledger_id: Id for ledger for report report_id: Report id assigned by mCASH """
return self.do_req('GET', self.merchant_api_base_url + '/ledger/' + ledger_id + '/report/' + report_id + '/').json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_permission_request(self, customer, pos_id, pos_tid, scope, ledger=None, text=None, callback_uri=None, expires_in=None): """Create permission request T...
arguments = {'customer': customer, 'pos_id': pos_id, 'pos_tid': pos_tid, 'scope': scope, 'ledger': ledger, 'text': text, 'callback_uri': callback_uri, '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 upload_receipt(self, url, data): """Upload a receipt to the give url :param url: :param data: :return: """
return self.upload_attachment(url=url, data=data, mime_type='application/vnd.mcash.receipt.v1+json')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_twitter_request_handler(twitter_api_func, call_rate_limit, call_counter, time_window_start, max_retries, wait_period, *args, **kw): """ This is a safe f...
error_count = 0 while True: try: # If we have reached the call rate limit for this function: if call_counter >= call_rate_limit: # Reset counter. call_counter = 0 # Sleep for the appropriate time. elapsed_time = 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 handle_twitter_http_error(e, error_count, call_counter, time_window_start, wait_period): """ This function handles the twitter request in case of an HTTP err...
if e.error_code == 401: # Encountered 401 Error (Not Authorized) raise e elif e.error_code == 404: # Encountered 404 Error (Not Found) raise e elif e.error_code == 429: # Encountered 429 Error (Rate Limit Exceeded) # Sleep for 15 minutes error_count +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_bundle(bundle, fixed_version=None): """ Does all of the processing required to create a bundle and write it to disk, returning its hash version """
tmp_output_file_name = '%s.%s.%s' % (os.path.join(bundle.bundle_file_root, bundle.bundle_filename), 'temp', bundle.bundle_type) iter_input = iter_bundle_files(bundle) output_pipeline = processor_pipeline(bundle.processors, iter_input) m = md5() with open(tmp_output_file_name, 'wb') as output_fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_to_text(html_string): """ returns a plain text string when given a html string text handles a, p, h1 to h6 and br, inserts newline chars to create space...
# create a valid html document from string # beware that it inserts <hmtl> <body> and <p> tags # where needed html_tree = html.document_fromstring(html_string) # handle header tags for h in html_tree.cssselect("h1, h2, h3, h4, h5, h6"): # add two newlines after a header tag h.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 random_string(**kwargs): """ By default generates a random string of 10 chars composed of digits and ascii lowercase letters. String length and pool can be o...
n = kwargs.get('length', 10) pool = kwargs.get('pool') or string.digits + string.ascii_lowercase return ''.join(random.SystemRandom().choice(pool) for _ in range(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 _run_parallel_process_with_profiling(self, start_path, stop_path, queue, filename): """ wrapper for usage of profiling """
runctx('Engine._run_parallel_process(self, start_path, stop_path, queue)', globals(), locals(), filename)
<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_parallel_process(self, start_path, stop_path, queue): """ The function calls _run_process and puts results produced by consumer at observations of top m...
process_num = int(current_process().name.split('-', 2)[1]) self._run_process(start_path, stop_path, process_num) queue.put(self.consumer.put())
<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_process(self, start_path, stop_path, process_num=0): """ The function calls _run_path for given set of paths """
# pre processing self.producer.initialize_worker(process_num) self.consumer.initialize_worker(process_num) # processing for path in range(start_path, stop_path): self._run_path(path) # post processing self.consumer.finalize_worker(process_num)
<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_path(self, path_num): """ standalone function implementing a single loop of Monte Carlo It returns list produced by consumer at observation dates :param...
# pre processing self.producer.initialize_path(path_num) self.consumer.initialize_path(path_num) # processing for new_date in self.grid: state = self.producer.evolve(new_date) self.consumer.consume(state) # post processing self.consumer....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_worker(self, process_num=None): """ reinitialize consumer for process in multiprocesing """
self.initialize(self.grid, self.num_of_paths, self.seed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_path(self, path_num=None): """ initialize consumer for next path """
self.state = copy(self.initial_state) return self.state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(self, state): """ consume new producer state """
self.state.append(self.func(state)) return self.state
<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, queue_get): """ to get states from multiprocessing.queue """
if isinstance(queue_get, (tuple, list)): self.result.extend(queue_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 walk_revctrl(dirname='', ff=''): """Return files found by the file-finder 'ff'. """
file_finder = None items = [] if not ff: distutils.log.error('No file-finder passed to walk_revctrl') sys.exit(1) for ep in pkg_resources.iter_entry_points('setuptools.file_finders'): if ff == ep.name: distutils.log.info('using %s file-finder', ep.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 cleanup_pycache(): """Remove .pyc files we leave around because of import. """
try: for file in glob.glob('setup.py[co]'): os.remove(file) if isdir('__pycache__'): for file in glob.glob(join('__pycache__', 'setup.*.py[co]')): os.remove(file) if not glob.glob(join('__pycache__', '*')): os.rmdir('__pycache__') ...
<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(args, ff=''): """Run setup.py with monkey patches applied. """
import setuptools.command.egg_info if ff == 'none': setuptools.command.egg_info.walk_revctrl = no_walk_revctrl else: setuptools.command.egg_info.walk_revctrl = partial(walk_revctrl, ff=ff) sys.argv = ['setup.py'] + args import setup cleanup_pycache()
<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_sorted_iterator(self, iterator): """ Get the iterator over the sorted items. This function decides whether the items can be sorted in memory or on disk....
lines = list(next(iterator)) if len(lines) < self.max_lines: return iter(sorted(lines, key=self.key)) import tempfile tmp_dir = tempfile.mkdtemp() fnames = self._split(chain([lines], iterator), tmp_dir) return SortedIteratorMerger([unpickle_iter(open(fname, ...
<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(self, iterator, tmp_dir): """ Splits the file into several chunks. If the original file is too big to fit in the allocated space, the sorting will be ...
fnames = [] for i, lines in enumerate(iterator): lines = list(lines) out_fname = os.path.join(tmp_dir, self.TMP_FNAME.format(i + 1)) self._write(lines, out_fname) fnames.append(out_fname) if len(lines) < self.max_lines: break ...
<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, lines, fname): """ Writes a intermediate temporary sorted file :param lines: The lines to write. :param fname: The name of the temporary file. :...
with open(fname, 'wb') as out_fhndl: for line in sorted(lines, key=self.key): pickle.dump(line, out_fhndl)
<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_iso_time(date_part, time_part): r"""Combign date and time into an iso datetime."""
str_date = datetime.datetime.strptime( date_part, '%m/%d/%Y').strftime('%Y-%m-%d') str_time = datetime.datetime.strptime( time_part, '%I:%M %p').strftime('%H:%M:%S') return str_date + "T" + str_time + "-7:00"
<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_list(host_name, client_name, client_pass): """ Pulls the list of users in a client. Inputs: - host_name: A string containing the address of the mach...
# Construct request. request = construct_request(model_type="pers", client_name=client_name, client_pass=client_pass, command="getusrs", values="whr=*") # Make request. reque...
<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_features(host_name, client_name, client_pass, feature_names): """ Add a number of numerical features in the client. Inputs: - host_name: A string contain...
init_feats = ("&".join(["%s=0"]*len(feature_names))) % tuple(feature_names) features_req = construct_request("pers", client_name, client_pass, "addftr", init_feats...
<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_features(host_name, client_name, client_pass, feature_names=None): """ Remove a number of numerical features in the client. If a list is not provided,...
# Get all features. if feature_names is None: feature_names = get_feature_names(host_name, client_name, client_pass) # Remove all features. feature_to_be_removed = ("&".join(["ftr=%s"]*len(feature_names))) % tu...
<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_feature_names(host_name, client_name, client_pass): """ Get the names of all features in a PServer client. Inputs: - host_name: A string containing the a...
# Construct request. request = construct_request(model_type="pers", client_name=client_name, client_pass=client_pass, command="getftrdef", values="ftr=*") # Send request. req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_request(model_type, client_name, client_pass, command, values): """ Construct the request url. Inputs: - model_type: PServer usage mode type. - cli...
base_request = ("{model_type}?" "clnt={client_name}|{client_pass}&" "com={command}&{values}".format(model_type=model_type, client_name=client_name, client_pass=client_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 send_request(host_name, request): """ Sends a PServer url request. Inputs: - host_name: A string containing the address of the machine where the PServer inst...
request = "%s%s" % (host_name, request) # print(request) try: result = requests.get(request) if result.status_code == 200: return result else: # print(result.status_code) raise Exception except Exception as e: # print(e) raise ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_feature_value(host_name, client_name, client_pass, user_twitter_id, feature_name, feature_score): """ Updates a single topic score, for a single user....
username = str(user_twitter_id) feature_value = "{0:.2f}".format(feature_score) joined_ftr_value = "ftr_" + feature_name + "=" + str(feature_value) values = "usr=%s&%s" % (username, joined_ftr_value) # Construct request. request = construct_request(model_type="pers", ...
<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_app(self, app): """ Initialize the application once the configuration has been loaded there. """
self.app = app self.log = app.logger.getChild('compass') self.log.debug("Initializing compass integration") self.compass_path = self.app.config.get('COMPASS_PATH', 'compass') self.config_files = self.app.config.get('COMPASS_CONFIGS', None) self.requestcheck_debug_only = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self): """ Main entry point that compiles all the specified or found compass projects. """
if self.disabled: return self._check_configs() for _, cfg in self.configs.iteritems(): cfg.parse() if cfg.changes_found() or self.skip_mtime_check: self.log.debug("Changes found for " + cfg.path \ + " or checks disabled...
<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_request(self, response): """ after_request handler for compiling the compass projects with each request. """
if response is not None and request is not None: # When used as response processor, only run if we are requesting # anything but a static resource. if request.endpoint in [None, "static"]: return response self.compile() return 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 _check_configs(self): """ Reloads the configuration files. """
configs = set(self._find_configs()) known_configs = set(self.configs.keys()) new_configs = configs - known_configs for cfg in (known_configs - configs): self.log.debug("Compass configuration has been removed: " + cfg) del self.configs[cfg] for cfg in new_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_configs(self): """ Scans the project directory for config files or returns the explicitly specified list of files. """
if self.config_files is not None: return self.config_files # Walk the whole project tree and look for "config.rb" files result = [] for path, _, files in os.walk(self.app.root_path): if "config.rb" in files: result.append(os.path.join(path, "conf...
<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(self, replace=False): """ Parse the given compass config file """
if self.last_parsed is not None \ and self.last_parsed > os.path.getmtime(self.path) \ and not replace: return self.last_parsed = time.time() with open(self.path, 'r') as file_: for line in file_: match = CONFIG_LINE_RE.mat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changes_found(self): """ Returns True if the target folder is older than the source folder. """
if self.dest is None: warnings.warn("dest directory not found!") if self.src is None: warnings.warn("src directory not found!") if self.src is None or self.dest is None: return False dest_mtime = -1 src_mtime = os.path.getmtime(self.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 compile(self, compass): """ Calls the compass script specified in the compass extension with the paths provided by the config.rb. """
try: output = subprocess.check_output( [compass.compass_path, 'compile', '-q'], cwd=self.base_dir) os.utime(self.dest, None) compass.log.debug(output) except OSError, e: if e.errno == errno.ENOENT: 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 _remove_otiose(lst): """lift deeply nested expressions out of redundant parentheses"""
listtype = type([]) while type(lst) == listtype and len(lst) == 1: lst = lst[0] return lst
<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_work_commits(repo_addr, ascending = True, tz = 'US/Eastern', correct_times = True): """Retrives work commits from repo"""
repo = git.Repo(repo_addr) commits = list(repo.iter_commits()) logs = [(c.authored_datetime, c.message.strip('\n'), str(c)) for c in repo.iter_commits()] work = pd.DataFrame.from_records(logs, columns = ['time', 'message', 'hash']) work.time = pd.DatetimeIndex([pd.Timestamp(i).tz_convert(tz) fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_topic_set(file_path): """ Opens one of the topic set resource files and returns a set of topics. - Input: - file_path: The path pointing to the topic set...
topic_set = set() file_row_gen = get_file_row_generator(file_path, ",") # The separator here is irrelevant. for file_row in file_row_gen: topic_set.add(file_row[0]) return topic_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 get_reveal_set(): """ Returns a set of all the topics that are interesting for REVEAL use-cases. """
file_path = get_package_path() + "/twitter/res/topics/story_set.txt" story_topics = get_topic_set(file_path) file_path = get_package_path() + "/twitter/res/topics/theme_set.txt" theme_topics = get_topic_set(file_path) file_path = get_package_path() + "/twitter/res/topics/attribute_set.txt" at...
<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_topic_keyword_dictionary(): """ Opens the topic-keyword map resource file and returns the corresponding python dictionary. - Input: - file_path: The path...
topic_keyword_dictionary = dict() file_row_gen = get_file_row_generator(get_package_path() + "/twitter/res/topics/topic_keyword_mapping" + ".txt", ",", "utf-8") for file_row in file_row_gen: topic_keyword_dictionary...
<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_input(self, name, ds): """ Retrieves the content of an input given a DataSource. The input acts like a filter over the outputs of the DataSource. Args: n...
columns = self.inputs.get(name) df = ds.get_dataframe() # set defaults for column in columns: if column not in df.columns: df[column] = self.defaults.get(column) return df[columns]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def domain_relationship(self): """ Returns a domain relationship equivalent with this resource relationship. """
if self.__domain_relationship is None: ent = self.relator.get_entity() self.__domain_relationship = \ self.descriptor.make_relationship(ent) return self.__domain_relationship
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit(self): """Fit MCMC AgeDepthModel"""
self._mcmcfit = self.mcmcsetup.run() self._mcmcfit.burnin(self.burnin) dmin = min(self._mcmcfit.depth_segments) dmax = max(self._mcmcfit.depth_segments) self._thick = (dmax - dmin) / len(self.mcmcfit.depth_segments) self._depth = np.arange(dmin, dmax + 0.001) sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def date(self, proxy, how='median', n=500): """Date a proxy record Parameters proxy : ProxyRecord how : str How to perform the dating. 'median' returns the avera...
assert how in ['median', 'ensemble'] ens_members = self.mcmcfit.n_members() if how == 'ensemble': select_idx = np.random.choice(range(ens_members), size=n, replace=True) out = [] for d in proxy.data.depth.values: age = self.agedepth(d) if how ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot(self, agebins=50, p=(2.5, 97.5), ax=None): """Age-depth plot"""
if ax is None: ax = plt.gca() ax.hist2d(np.repeat(self.depth, self.age_ensemble.shape[1]), self.age_ensemble.flatten(), (len(self.depth), agebins), cmin=1) ax.step(self.depth, self.age_median(), where='mid', color='red') ax.step(self.depth, self.age_percen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def agedepth(self, d): """Get calendar age for a depth Parameters d : float Sediment depth (in cm). Returns ------- Numeric giving true age at given depth. """
# TODO(brews): Function cannot handle hiatus # See lines 77 - 100 of hist2.cpp x = self.mcmcfit.sediment_rate theta0 = self.mcmcfit.headage # Age abscissa (in yrs). If array, dimension should be iterations or realizations of the sediment deltac = self.thick c0 = min(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_prior_dates(self, dwidth=30, ax=None): """Plot prior chronology dates in age-depth plot"""
if ax is None: ax = plt.gca() depth, probs = self.prior_dates() pat = [] for i, d in enumerate(depth): p = probs[i] z = np.array([p[:, 0], dwidth * p[:, 1] / np.sum(p[:, 1])]) # Normalize z = z[:, z[0].argsort(kind='mergesort')] # np.int...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_sediment_rate(self, ax=None): """Plot sediment accumulation rate prior and posterior distributions"""
if ax is None: ax = plt.gca() y_prior, x_prior = self.prior_sediment_rate() ax.plot(x_prior, y_prior, label='Prior') y_posterior = self.mcmcfit.sediment_rate density = scipy.stats.gaussian_kde(y_posterior.flat) density.covariance_factor = lambda: 0.25 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_sediment_memory(self, ax=None): """Plot sediment memory prior and posterior distributions"""
if ax is None: ax = plt.gca() y_prior, x_prior = self.prior_sediment_memory() ax.plot(x_prior, y_prior, label='Prior') y_posterior = self.mcmcfit.sediment_memory density = scipy.stats.gaussian_kde(y_posterior ** (1/self.thick)) density.covariance_factor = l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qpinfo(): """Print information of a quantitative phase imaging dataset"""
parser = qpinfo_parser() args = parser.parse_args() path = pathlib.Path(args.path).resolve() try: ds = load_data(path) except UnknownFileFormatError: print("Unknown file format: {}".format(path)) return print("{} ({})".format(ds.__class__.__doc__, ds.__class__.__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_node_meta_type(manager, handle_id): """ Returns the meta type of the supplied node as a string. :param manager: Neo4jDBSessionManager :param handle_id: U...
node = get_node(manager=manager, handle_id=handle_id, legacy=False) for label in node.labels: if label in META_TYPES: return label raise exceptions.NoMetaLabelFound(handle_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_relationship(manager, handle_id, other_handle_id, rel_type): """ Makes a relationship from node to other_node depending on which meta_type the nodes a...
meta_type = get_node_meta_type(manager, handle_id) if meta_type == 'Location': return create_location_relationship(manager, handle_id, other_handle_id, rel_type) elif meta_type == 'Logical': return create_logical_relationship(manager, handle_id, other_handle_id, rel_type) elif meta_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 parse_code(self, url, html): """ Parse the code details and TOC from the given HTML content :type url: str :param url: source URL of the page :type html: uni...
soup = BeautifulSoup(html, 'html5lib', from_encoding='utf-8') # -- main text div = (soup .find('div', id='content_false') .find('div', attrs={'class': 'data'})) code = Code(self.id_code, date_pub=self.date_pub, 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 parse_code_ul(self, url, ul): """Fill the toc item"""
li_list = ul.find_all('li', recursive=False) li = li_list[0] span_title = li.find('span', attrs={'class': re.compile(r'TM\d+Code')}, recursive=False) section = Section(span_title.attrs['id'], span_title.text.strip()) div...