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 _get_parsed_args(command_name, doc, argv): # type: (str, str, typing.List[str]) -> typing.Dict[str, typing.Any] """Parse the docstring with docopt. Args: com...
_LOGGER.debug('Parsing docstring: """%s""" with arguments %s.', doc, argv) args = docopt(doc, argv=argv) if command_name == settings.command: args[command_name] = True return 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 trace(msg): """Print a trace message to stderr if environment variable is set. """
if os.environ.get('JARN_TRACE') == '1': print('TRACE:', msg, file=sys.stderr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Efn(Ms,eccs): """works for -2pi < Ms < 2pi, e <= 0.97"""
Ms = np.atleast_1d(Ms) eccs = np.atleast_1d(eccs) unit = np.floor(Ms / (2*np.pi)) Es = EFN((Ms % (2*np.pi)),eccs) Es += unit*(2*np.pi) return Es
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_modules_from_last_session(seashcommanddict): """ Enable every module that isn't marked as disabled in the modules folder. This function is meant to be...
successfully_enabled_modules = [] modules_to_enable = get_enabled_modules() for modulename in modules_to_enable: # There are no bad side effects to seash's state when we do this # The only thing that should happen is that the modulename.disabled file # gets created (temporarily) disable(seashcomm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_module_folder_exists(): """ Checks to see if the module folder exists. If it does not, create it. If there is an existing file with the same name, we...
if not os.path.isdir(MODULES_FOLDER_PATH): try: os.mkdir(MODULES_FOLDER_PATH) except OSError, e: if "file already exists" in str(e): raise RuntimeError("Could not create modules folder: file exists with the same 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_configuration_from_settings(self, setting_info): """ Returns a dictionary with configuration names as keys and setting values extracted from this configu...
settings = self.get_settings() return dict([(name, settings.get(key)) for (name, key) in setting_info if not settings.get(key, None) is 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 add_repository(self, name, repository_type, repository_class, aggregate_class, make_default, configuration): """ Generic method for adding a repository. """
repo_mgr = self.get_registered_utility(IRepositoryManager) if name is None: # If no name was given, this is assumed to be the ROOT repository # for the given repository type. name = REPOSITORY_DOMAINS.ROOT repo = repo_mgr.new(repository_type, name=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 encrypt_email(email): """ The default encryption function for storing emails in the database. This uses AES and the encryption key defined in the application...
aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.encrypt(email)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shortlink_scanned(self, data): """Called when a shortlink_scanned event is received """
# Inform log that we received an event self.logger.info("Received shortlink_scanned event") data = json.loads(data) customer_token = str(data['object']['id']) response = self.mapiclient.create_payment_request( customer=customer_token, currency="NOK", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pusher_connected(self, data): """Called when the pusherclient is connected """
# Inform user that pusher is done connecting self.logger.info("Pusherclient connected") # Bind the events we want to listen to self.callback_client.bind("payment_authorized", self.payment_authorized) self.callback_client.bind("shortlink_scanned...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, *args, **kwargs): """ Checks the cache to see if there's a cached entry for this pk. If not, fetches using super then stores the result in cache. M...
if self.query.where: # If there is any other ``where`` filter on this QuerySet just call # super. There will be a where clause if this QuerySet has already # been filtered/cloned. return super(CachingQuerySet, self).get(*args, **kwargs) # Punt on anythi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_path(self, name): """ Fetch contents from the path retrieved via lookup_path. No caching will be done. """
with codecs.open(self.lookup_path(name), encoding='utf-8') as fd: return fd.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, mold_id, data, wrapper_tag='div'): """ Execute a mold `mold_id` by rendering through ``env``. This is done using its default template, with dat...
template = self.load_mold(mold_id) kwargs = {} kwargs.update(data) kwargs['_nunja_data_'] = 'data-nunja="%s"' % mold_id kwargs['_template_'] = template kwargs['_wrapper_tag_'] = wrapper_tag return self._core_template_.render(**kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, mold_id, data): """ Render a mold `mold_id`. No wrappers are applied as only the default template defined for the mold is rendered. """
template = self.load_mold(mold_id) return template.render(**data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_model_table(self, part): """ Returns a list that represents the table. :param part: The table header, table footer or table body. :type part: hatemile.u...
rows = self.parser.find(part).find_children('tr').list_results() table = [] for row in rows: table.append(self._get_model_row(self.parser.find( row ).find_children('td,th').list_results())) return self._get_valid_model_table(table)
<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_valid_model_table(self, ros): """ Returns a list that represents the table with the rowspans. :param ros: The list that represents the table without the...
# pylint: disable=no-self-use new_table = [] if bool(ros): length_table = len(ros) for row_index in range(0, length_table): cells_added = 0 original_row = [] + ros[row_index] if len(new_table) <= row_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 _get_model_row(self, row): """ Returns a list that represents the line of table with the colspans. :param row: The list that represents the line of table wit...
# pylint: disable=no-self-use new_row = [] + row size = len(row) for i in range(0, size): cell = row[i] if cell.has_attribute('colspan'): colspan = int(cell.get_attribute('colspan')) if colspan > 1: for j in ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_header(self, hed): """ Validate the list that represents the table header. :param hed: The list that represents the table header. :type hed: list(l...
# pylint: disable=no-self-use if not bool(hed): return False length = -1 for row in hed: if not bool(row): return False elif length == -1: length = len(row) elif len(row) != length: return F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_cells_headers_ids(self, hed, index): """ Returns a list with ids of rows of same column. :param hed: The list that represents the table header. :type he...
# pylint: disable=no-self-use ids = [] for row in hed: if row[index].get_tag_name() == 'TH': ids.append(row[index].get_attribute('id')) return ids
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _associate_data_cells_with_header_cells_of_row(self, element): """ Associate the data cell with header cell of row. :param element: The table body or table f...
table = self._get_model_table(element) for row in table: headers_ids = [] for cell in row: if cell.get_tag_name() == 'TH': self.id_generator.generate_id(cell) headers_ids.append(cell.get_attribute('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 _prepare_header_cells(self, table_header): """ Set the scope of header cells of table header. :param table_header: The table header. :type table_header: hate...
cells = self.parser.find(table_header).find_children( 'tr' ).find_children('th').list_results() for cell in cells: self.id_generator.generate_id(cell) cell.set_attribute('scope', 'col')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt(clear_text) -> str: """ Use config.json key to encrypt """
if not isinstance(clear_text, bytes): clear_text = str.encode(clear_text) cipher = Fernet(current_app.config['KEY']) return cipher.encrypt(clear_text).decode("utf-8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt(crypt_text) -> str: """ Use config.json key to decrypt """
cipher = Fernet(current_app.config['KEY']) if not isinstance(crypt_text, bytes): crypt_text = str.encode(crypt_text) return cipher.decrypt(crypt_text).decode("utf-8")
<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_volume(self, id): """ return volume information if the argument is an id or a path """
# If the id is actually a path if exists(id): with open(id) as file: size = os.lseek(file.fileno(), 0, os.SEEK_END) return {'path': id, 'size': size} return self.volume.get(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 randomize(self, device=None, percent=100, silent=False): """ Writes random data to the beginning of each 4MB block on a block device this is useful when perf...
volume = self.get_volume(device) # The number of blocks in the volume blocks = int(volume['size'] / BLOCK_SIZE) # How many writes should be to the device # (based on the percentage requested) num_writes = int(blocks * percent * 0.01) # Build a list of offsets we ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backup(self, id=None, src=None, timestamp=None): """ This runs a backup job outside of the storage api, which is useful for performance testing backups """
# Set basic Logging logging.basicConfig() # Get the lunr logger log = logger.get_logger() # Output Debug level info log.logger.setLevel(logging.DEBUG) # Load the local storage configuration conf = LunrConfig.from_storage_conf() # If no time provid...
<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_ip(request): """Return the IP address inside the HTTP_X_FORWARDED_FOR var inside the `request` object. The return of this function can be overrided by th...
if getsetting('LOCAL_GEOLOCATION_IP'): return getsetting('LOCAL_GEOLOCATION_IP') forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if not forwarded_for: return UNKNOWN_IP for ip in forwarded_for.split(','): ip = ip.strip() if not ip.startswith('10.') and not ip...
<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_connection(self): """Return a valid redis connection based on the following settings * `REDIS_CONNECTIONS` * `EVENTLIB_REDIS_CONFIG_NAME` The first one i...
if self.conn: return self.conn redis_configs = getsetting('REDIS_CONNECTIONS') if redis_configs: config_name = getsetting('EVENTLIB_REDIS_CONFIG_NAME', 'default') config = redis_configs[config_name] host = config['HOST'] port = confi...
<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_setup_py(self, args, echo=True, echo2=True, ff=''): """Run setup.py with monkey-patched setuptools. The patch forces setuptools to use the file-finder '...
python = self.python if ff: setup_py = '-c"%s"' % (RUN_SETUP % locals()) else: setup_py = 'setup.py %s' % ' '.join(args) rc, lines = self.process.popen( '"%(python)s" %(setup_py)s' % locals(), echo=echo, echo2=echo2) return rc, lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def app_factory(global_settings, **local_settings): # pylint: disable=W0613 """ Default factory for creating a WSGI application using the everest configurator an...
config = Configurator() config.setup_registry(settings=local_settings, root_factory=RootFactory()) if 'configure_zcml' in local_settings: config.load_zcml(local_settings['configure_zcml']) app = config.make_wsgi_app() # In the absence of an application name in the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def fetch_page(session, host): """ Perform the page fetch from an individual host. `session` - An aiohttp [client session](http://aiohttp.readthedocs.io/en...
await asyncio.sleep(random.randint(0, 25) * 0.1) start = time.time() logger.info('Fetch from {}'.format(host)) try: response = await session.get(host, allow_redirects=False) except aiohttp.ClientResponseError as err: # likely a 404 implying HTTP but no page # likely a 401 i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def asynchronous(urls=None, re_filter=None): """ Asynchronous request manager for session. Returns list of responses that match the filter. `urls` - tuple ...
class _URLBase(str): """ Convenient access to hostname (ip) portion of the URL """ @property def hostname(self): return urlsplit(self).hostname http_devices = {} qualified_devices = [] connection = aiohttp.TCPConnector(limit=0) async with aiohttp.ClientSession(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 url_generator(network=None, path=''): """ Return a tuple of URLs with path, one for each host on network `network` - IP address and subnet mask compatible wi...
network_object = ipaddress.ip_network(network) if network_object.num_addresses > 256: # will need to batch process this case otherwise we run out of selectors logger.error('Scan limited to 256 addresses, requested %d.', network_object.num_addresses) raise NotImplementedError elif ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def survey(network=None, path='', pattern='', log=False): """ Search network for hosts with a response to path that matches pattern `network` - IP address and su...
if log: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.CRITICAL) network_scan = asyncio.ensure_future(asynchronous( urls=url_generator(network=network, path=path), re_filter=re.compile(pattern)) ) ioloop = asyncio.get_event_loop() ioloop.run_un...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hidden_cursor(): """Temporarily hide the terminal cursor."""
if sys.stdout.isatty(): _LOGGER.debug('Hiding cursor.') print('\x1B[?25l', end='') sys.stdout.flush() try: yield finally: if sys.stdout.isatty(): _LOGGER.debug('Showing cursor.') print('\n\x1B[?25h', end='') sys.stdout.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_status(): """Display an OK or FAILED message for the context block."""
def print_status(msg, color): """Print the status message. Args: msg: The message to display (e.g. OK or FAILED). color: The ANSI color code to use in displaying the message. """ print('\r' if sys.stdout.isatty() else '\t', end='') print('{}{}[{color...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pusher_connect_handler(self, data): """Event handler for the connection_established event. Binds the shortlink_scanned event """
self.channel = self.pusher.subscribe(self.pos_callback_chan) for listener in self.pusher_connected_listeners: listener(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 _runForever(self, stop_event): """Runs the main loop Arguments: stop_event: threading.Event() as a stop signal """
while(not stop_event.is_set()): state = self.pusher.connection.state if (state is not "connecting" and state is not "connected"): self.logger.warning( "Pusher seems to be disconnected, trying to reconnect") self.pu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stops the pusherclient cleanly """
self.pusherthread_stop.set() self.pusher.disconnect() # wait until pusher is down while self.pusher.connection.state is "connected": sleep(0.1) logging.info("shutting down pusher connector thread")
<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, filename, bs=512): """Loads GPT partition table. Args: filename (str): path to file or device to open for reading bs (uint): Block size of the v...
with open(filename, 'rb') as f: f.seek(GPT_HEADER_OFFSET + 0x0C) header_size = struct.unpack("<I", f.read(4))[0] f.seek(GPT_HEADER_OFFSET) header_data = f.read(header_size) self.header = GPT_HEADER(header_data) if (self.header.signature ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def global_to_local(self, index): """ Calculate local index from global index :param index: input index :return: local index for data """
if (type(index) is int) or (type(index) is slice): if len(self.__mask) > 1: raise IndexError('check length of parameter index') # 1D array if type(index) is int: return self.int_global_to_local(index) elif type(index) is slice: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int_global_to_local_start(self, index, axis=0): """ Calculate local index from global index from start_index :param index: global index as integer :param axi...
if index >= self.__mask[axis].stop-self.__halos[1][axis]: return None if index < self.__mask[axis].start: return 0 return index-self.__mask[axis].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 int_global_to_local_stop(self, index, axis=0): """ Calculate local index from global index from stop_index :param index: global index as integer :param axis:...
if index < self.__mask[axis].start+self.__halos[0][axis]: return None if index > self.__mask[axis].stop: return self.__mask[axis].stop-self.__mask[axis].start return index-self.__mask[axis].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 int_global_to_local(self, index, axis=0): """ Calculate local index from global index for integer input :param index: global index as integer :param axis: cu...
# Warum >= an dieser Stelle. Eigentlich sollte > ausreichend sein! Test! if index >= self.__mask[axis].stop-self.__halos[1][axis]: return None if index < self.__mask[axis].start+self.__halos[0][axis]: return None return index-self.__mask[axis].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 int_out_of_bounds(self, index, axis=0): """ examples if index is out of local processing bounds function is used to perform examples for index of type intege...
#if index >= self._global_shape[axis]: if index > self._global_shape[axis]: raise IndexError('index is larger than the upper bound') # wrap around index if negative like in python if index < 0: index += self._global_shape[axis] #warnings.warn('warp a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def out_of_bounds(self, index): """ Check index for out of bounds :param index: index as integer, tuple or slice :return: local index as tuple """
if type(index) is int: return self.int_out_of_bounds(index) elif type(index) is slice: return self.slice_out_of_bounds(index) elif type(index) is tuple: local_index = [] for k, item in enumerate(index): if type(item) is slice:...
<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_server_setting(self, protocol, host='127.0.0.1', port=8000, debug=False, ssl=None, sock=None, workers=1, loop=None, backlog=100, has_log=True): '''Helper function used by `run`.''' if isinstance(ssl, dict): # try common aliaseses...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(path): """Verify that `path` has the qpimage series file format"""
valid = False try: h5 = h5py.File(path, mode="r") qpi0 = h5["qpi_0"] except (OSError, KeyError): pass else: if ("qpimage version" in qpi0.attrs and "phase" in qpi0 and "amplitude" in qpi0 and ...
<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_requirements(output_path=None): """ Loop through the INSTALLED_APPS and create a set of requirements for pip. if output_path is ``None`` then write ...
from django.conf import settings reqs = set() for app in settings.INSTALLED_APPS: if app in mapping.keys(): reqs |= set(mapping[app]) if output_path is None: print "--extra-index-url=http://opensource.washingtontimes.com/pypi/simple/" for item in reqs: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_mbr_plugin(self, fs_id, plugin): """Used in plugin's registration routine, to associate it's detection method with given filesystem id Args: fs_id: ...
self.logger.debug('MBR: {}, FS ID: {}' .format(self.__get_plugin_name(plugin), fs_id)) self.__mbr_plugins[fs_id].append(plugin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_gpt_plugin(self, fs_guid, plugin): """Used in plugin's registration routine, to associate it's detection method with given filesystem guid Args: fs_...
key = uuid.UUID(fs_guid.lower()) self.logger.debug('GPT: {}, GUID: {}' .format(self.__get_plugin_name(plugin), fs_guid)) self.__gpt_plugins[key].append(plugin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_mbr(self, filename, offset, fs_id): """Used by rawdisk.session.Session to match mbr partitions against filesystem plugins. Args: filename: device or f...
self.logger.debug('Detecting MBR partition type') if fs_id not in self.__mbr_plugins: return None else: plugins = self.__mbr_plugins.get(fs_id) for plugin in plugins: if plugin.detect(filename, offset): return plugin.get_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 detect_gpt(self, filename, offset, fs_guid): """Used by rawdisk.session.Session to match gpt partitions agains filesystem plugins. Args: filename: device or ...
self.logger.debug('Detecting GPT partition type') if fs_guid not in self.__gpt_plugins: return None else: plugins = self.__gpt_plugins.get(fs_guid) for plugin in plugins: if plugin.detect(filename, offset): return plugin.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inject_documentation(**options): """ Generate configuration documentation in reStructuredText_ syntax. :param options: Any keyword arguments are passed on to...
import cog loader = ConfigLoader(**options) cog.out("\n" + loader.documentation + "\n\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 read_file(self, filename): """ Read a text file and provide feedback to the user. :param filename: The pathname of the file to read (a string). :returns: The...
logger.info("Reading file: %s", format_path(filename)) contents = self.context.read_file(filename) num_lines = len(contents.splitlines()) logger.debug("Read %s from %s.", pluralize(num_lines, 'line'), format_path(filename)) return conten...
<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_file(self, filename): """ Execute a file and provide feedback to the user. :param filename: The pathname of the file to execute (a string). :returns:...
logger.info("Executing file: %s", format_path(filename)) contents = self.context.execute(filename, capture=True).stdout num_lines = len(contents.splitlines()) logger.debug("Execution of %s yielded % of output.", format_path(filename), pluralize(...
<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_file(self, filename, contents): """ Write a text file and provide feedback to the user. :param filename: The pathname of the file to write (a string). ...
logger.info("Writing file: %s", format_path(filename)) contents = contents.rstrip() + b"\n" self.context.write_file(filename, contents) logger.debug("Wrote %s to %s.", pluralize(len(contents.splitlines()), "line"), format_path(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 validate_input(function): """Decorator that validates the kwargs of the function passed to it."""
@wraps(function) def wrapper(*args, **kwargs): try: name = function.__name__ + '_validator' # find validator name globals()[name](kwargs) # call validation function return function(*args, **kwargs) except KeyError: raise Exception("Could not fin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getModulePath(project_path,module_name,verbose): '''Searches for module_name in searchpath and returns the filepath. If no filepath was found, returns None.''' if not module_name: return None sys.path.append(project_path) try: package = pkgutil.get_loader(module_name) except ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getImportFromObjects(node): '''Returns a list of objects referenced by import from node''' somenames = [x.asname for x in node.names if x.asname] othernames = [x.name for x in node.names if not x.asname] return somenames+othernames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_slug_expression(attr): """ Converts the given instrumented string attribute into an SQL expression that can be used as a slug. Slugs are identifiers for m...
slug_expr = sa_func.replace(attr, ' ', '-') slug_expr = sa_func.replace(slug_expr, '_', '-') slug_expr = sa_func.lower(slug_expr) return slug_expr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mapper(class_, local_table=None, id_attribute='id', slug_expression=None, *args, **kwargs): """ Convenience wrapper around the SA mapper which will set up th...
mpr = sa_mapper(class_, local_table=local_table, *args, **kwargs) # Set up the ID attribute as a hybrid property, if necessary. if id_attribute != 'id': # Make sure we are not overwriting an already mapped or customized # 'id' attribute. if 'id' in mpr.columns: mpr.dispo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def synonym(name): """ Utility function mimicking the behavior of the old SA synonym function with the new hybrid property semantics. """
return hybrid_property(lambda inst: getattr(inst, name), lambda inst, value: setattr(inst, name, value), expr=lambda cls: getattr(cls, 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 map_system_entities(engine, metadata, reset): """ Maps all system entities. """
# Map the user message system entity. msg_tbl = Table('_user_messages', metadata, Column('guid', String, nullable=False, primary_key=True), Column('text', String, nullable=False), Column('time_stamp', DateTime(timezone=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 schematron(self, fn=None, outfn=None, ext='.sch'): """convert the Schema to schematron and save at the given output filename or with the given extension."""
from .xslt import XSLT from . import PATH, XML, etree fn = fn or self.fn if os.path.splitext(fn)[-1].lower()==ext: return fn elif os.path.splitext(fn)[-1].lower()!='.rng': fn = Schema(fn=fn).trang(ext='.rng') rng2sch = XSLT(fn=os.path.join(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 xhtml(self, outfn=None, ext='.xhtml', css=None, **params): """convert the Schema to XHTML with the given output filename or with the given extension."""
from markdown import markdown from copy import deepcopy from bl.file import File from .xslt import XSLT from .rng import RNG from . import XML, PATH, etree rncfn = os.path.splitext(self.fn)[0] + '.rnc' rngfn = os.path.splitext(self.fn)[0] + '.rng' ...
<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_tag(cls, tag, schemas, ext='.rnc'): """load a schema using an element's tag. schemas can be a string or a list of strings"""
return cls(fn=cls.filename(tag, schemas, ext=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 filename(cls, tag, schemas, ext='.rnc'): """given a tag and a list of schemas, return the filename of the schema. If schemas is a string, treat it as a comma...
if type(schemas)==str: schemas = re.split("\s*,\s*", schemas) for schema in schemas: fn = os.path.join(schema, cls.dirname(tag), cls.basename(tag, ext=ext)) if os.path.exists(fn): return 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 errors_as_text(self): """ only available to Django 1.7+ """
errors = [] errors.append(self.non_field_errors().as_text()) errors_data = self.errors.as_data() for key, value in errors_data.items(): field_label = self.fields[key].label err_descn = ''.join([force_text(e.message) for e in value]) error = "%s %s" % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_attr2fields(self, attr_name, attr_val, fields=[], exclude=[], include_all_if_empty=True): """ add attr to fields """
for f in self.filter_fields(fields, exclude, include_all_if_empty): f = self.fields[f.name] org_val = f.widget.attrs.get(attr_name, '') f.widget.attrs[attr_name] = '%s %s' % (org_val, attr_val) if org_val else attr_val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_class2fields(self, html_class, fields=[], exclude=[], include_all_if_empty=True): """ add class to html widgets. """
self.add_attr2fields('class', html_class, fields, exclude)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_required_fields(self, fields=[]): """ set required to True """
fields = self.filter_fields(fields) for f in fields: f = self.fields[f.name] f.required = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_uniqe(self, obj_class, error_msg=_('Must be unique'), **kwargs): """ check if this object is unique """
if obj_class.objects.filter(**kwargs).exclude(pk=self.instance.pk): raise forms.ValidationError(error_msg)
<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_info(pyfile): '''Retrieve dunder values from a pyfile''' info = {} info_re = re.compile(r"^__(\w+)__ = ['\"](.*)['\"]") with open(pyfile, 'r') as f: for line in f.readlines(): match = info_re.search(line) if match: info[match.group(1)] = match.grou...
<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(): """Entrypoint for ``lander`` executable."""
args = parse_args() config_logger(args) logger = structlog.get_logger(__name__) if args.show_version: # only print the version print_version() sys.exit(0) version = pkg_resources.get_distribution('lander').version logger.info('Lander version {0}'.format(version)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_node(self, node): """ Adds node if name is available or pre-existing node returns True if added returns False if not added """
if self._is_node_reserved(node): return False # Put node in map self._node_map[node.get_id()] = node 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 join(self, distbase, location): """Join 'distbase' and 'location' in such way that the result is a valid scp destination. """
sep = '' if distbase and distbase[-1] not in (':', '/'): sep = '/' return distbase + sep + location
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_location(self, location, depth=0): """Resolve aliases and apply distbase. """
if not location: return [] if location in self.aliases: res = [] if depth > MAXALIASDEPTH: err_exit('Maximum alias depth exceeded: %(location)s' % locals()) for loc in self.aliases[location]: res.extend(self.get_location(lo...
<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_default_location(self): """Return the default location. """
res = [] for location in self.distdefault: res.extend(self.get_location(location)) 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 check_empty_locations(self, locations=None): """Fail if 'locations' is empty. """
if locations is None: locations = self.locations if not locations: err_exit('mkrelease: option -d is required\n%s' % USAGE)
<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_valid_locations(self, locations=None): """Fail if 'locations' contains bad destinations. """
if locations is None: locations = self.locations for location in locations: if (not self.is_server(location) and not self.is_ssh_url(location) and not self.has_host(location)): err_exit('Unknown location: %(location)s' % locals())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_locations(self): """Print known dist-locations and exit. """
known = self.defaults.get_known_locations() for default in self.defaults.distdefault: if default not in known: known.add(default) if not known: err_exit('No locations', 0) for location in sorted(known): if location in self.defaults.dis...
<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_uploadflags(self, location): """Return uploadflags for the given server. """
uploadflags = [] server = self.defaults.servers[location] if self.sign: uploadflags.append('--sign') elif server.sign is not None: if server.sign: uploadflags.append('--sign') elif self.defaults.sign: uploadflags.append('--sig...
<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_options(self): """Process the command line. """
args = self.parse_options(self.args) if args: self.directory = args[0] if self.develop: self.skiptag = True if not self.develop: self.develop = self.defaults.develop if not self.develop: self.infoflags = self.setuptools.infoflags...
<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_package(self): """Get the URL or sandbox to release. """
directory = self.directory develop = self.develop scmtype = self.scmtype self.scm = self.scms.get_scm(scmtype, directory) if self.scm.is_valid_url(directory): directory = self.urlparser.abspath(directory) self.remoteurl = directory self.isr...
<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_release(self): """Build and distribute the package. """
directory = self.directory infoflags = self.infoflags branch = self.branch develop = self.develop scmtype = self.scm.name tempdir = abspath(tempfile.mkdtemp(prefix='mkrelease-')) try: if self.isremote: directory = join(tempdir, 'build...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_gateway( cls, launch_jvm: bool = True, gateway: Union[GatewayParameters, Dict[str, Any]] = None, callback_server: Union[CallbackServerParameters, Di...
assert check_argument_types() classpath = classpath if isinstance(classpath, str) else os.pathsep.join(classpath) javaopts = list(javaopts) # Substitute package names with their absolute directory paths for match in package_re.finditer(classpath): pkgname = match.gr...
<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, filename, offset): """Loads NTFS volume information Args: filename (str): Path to file/device to read the volume \ information from. offset (uint...
self.offset = offset self.filename = filename self.bootsector = BootSector( filename=filename, length=NTFS_BOOTSECTOR_SIZE, offset=self.offset) self.mft_table = MftTable( mft_entry_size=self.bootsector.mft_record_size, filena...
<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_mft_zone_size(self, num_clusters, mft_zone_multiplier=1): """Returns mft zone size in clusters. From ntfs_progs.1.22."""
sizes = { 4: num_clusters >> 1, # 50% 3: (num_clusters * 3) >> 3, # 37,5% 2: num_clusters >> 2, # 25% } return sizes.get(mft_zone_multiplier, num_clusters >> 3)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Closes all the iterators. This is particularly important if the iterators are files. """
if hasattr(self, 'iterators'): for it in self.iterators: if hasattr(it, 'close'): it.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 _update_sorting(self): """ Insert new entries into the merged iterator. :param sorted_tops: A SortedDict. :param tops: The most recent entry from each iterat...
key = self.key sorted_tops = self.sorted_tops tops = self.tops iterators = self.iterators for idx in self.idxs: try: tops[idx] = next(iterators[idx]) top_key = key(tops[idx]) if top_key not in sorted_tops: ...
<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_user_stats(): # type: () -> pd.Series """ Get number of distinct email addresses in observed domains TODO: get up to date with new projects layout How...
fname = os.path.join(os.path.dirname(__file__), "email_domain_users.csv") stats = pd.read_csv(fname, header=0, squeeze=True, index_col=0) return stats[pd.notnull(stats.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 is_university(addr): # type: (Union[str, unicode]) -> bool """ Check if provided email has a university domain - either in .edu domain (except public sercice...
addr_domain = domain(addr) if not addr_domain: # invalid email return False chunks = addr_domain.split(".") if len(chunks) < 2: # local or invalid address return False domains = university_domains() # many universitites have departmental emails, such as cs.cmu.edu. However, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_public(addr): # type: (Union[str, unicode]) -> bool """ Check if the passed email registered at a free pubic mail server :param addr: email address to che...
addr_domain = domain(addr) if not addr_domain: # anybody can use invalid email return True chunks = addr_domain.rsplit(".", 1) return len(chunks) < 2 \ or addr_domain.endswith("local") \ or addr_domain in public_domains()
<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_color(self, text, attr=None): '''write text at current cursor position and interpret color escapes. return the number of characters written. ''' log(u'write_color("%s", %s)' % (text, attr)) chunks = self.terminal_escape.split(text) log(u'chunks=%s' % rep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(self): """List of hologram data file names in the input zip file"""
if self._files is None: self._files = SeriesZipTifHolo._index_files(self.path) return self._files
<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_time(self, idx): """Time for each TIFF file If there are no metadata keyword arguments defined for the TIFF file format, then the zip file `date_time` va...
# first try to get the time from the TIFF file # (possible meta data keywords) ds = self._get_dataset(idx) thetime = ds.get_time() if np.isnan(thetime): # use zipfile date_time zf = zipfile.ZipFile(self.path) info = zf.getinfo(self.files[idx])...
<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_data(self, localvars, remotevars, inds, shape): """ Method that does the updating of local netcdf cache with remote data """
# If user specifies 'all' then entire xy domain is # grabbed, default is 4, specified in the model_controller if self.horiz_size == 'all': y, y_1 = 0, shape[-2] x, x_1 = 0, shape[-1] else: r = self.horiz_size x, x_1 = self.point_get.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 need_data(self, i): """ Method to test if cache contains the data that the particle needs """
# If we are not caching, we always grab data from the raw source if self.caching is False: return False logger.debug("Checking cache for data availability at %s." % self.part.location.logstring()) try: # Tell the DataController that we are going to be reading ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linterp(self, setx, sety, x): """ Linear interp of model data values between time steps """
if math.isnan(sety[0]) or math.isnan(setx[0]): return np.nan #if math.isnan(sety[0]): # sety[0] = 0. #if math.isnan(sety[1]): # sety[1] = 0. return sety[0] + (x - setx[0]) * ( (sety[1]-sety[0]) / (setx[1]-setx[0]) )