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 extend(self, *iterables): """Add all values of all iterables at the end of the list Args: iterables: iterable which content to add at the end Example: [1, 2]...
for value in iterables: list.extend(self, value) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_cell_value(value): """Process value for writing into a cell. Args: value: any type of variable Returns: json serialized value if value is list or d...
if isinstance(value, dict) or isinstance(value, list): return json.dumps(value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_addresses_from_input_file(input_file_name): """Read addresses from input file into list of tuples. This only supports address and zipcode headers """
mode = 'r' if sys.version_info[0] < 3: mode = 'rb' with io.open(input_file_name, mode) as input_file: reader = csv.reader(input_file, delimiter=',', quotechar='"') addresses = list(map(tuple, reader)) if len(addresses) == 0: raise Exception('No addresses found ...
<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_identifiers_from_input_file(input_file_name): """Read identifiers from input file into list of dicts with the header row values as keys, and the rest of ...
valid_identifiers = ['address', 'zipcode', 'unit', 'city', 'state', 'slug', 'block_id', 'msa', 'num_bins', 'property_type', 'client_value', 'client_value_sqft', 'meta'] mode = 'r' if sys.version_info[0] < 3: mode = 'rb' with io.open(input_file_name, mode) as input_file:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_host_from_segment(ipaddress, networkaddress, auth, url): '''Function to abstract ''' host_id = get_host_id(ipaddress, networkaddress, auth, url) remove_scope_ip(host_id, auth.creds, auth.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 generate_signature(method, version, endpoint, date, rel_url, content_type, content, access_key, secret_key, hash_type): ''' Generates the API request signature from the given parameters. ''' hash_type = hash_type hostname = endpoint._val.netloc # FI...
<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 list_with_limit(cls, limit, offset, status: str = 'ALIVE', fields: Iterable[str] = None) -> Sequence[dict]: ''' Fetches the list of agents with the given status with limit an...
<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_content(self, value: RequestContent, *, content_type: str = None): ''' Sets the content of the request. ''' assert self._attached_files is None, \ 'cannot set content because you already attached files.' guessed_content_type = 'applicati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def attach_files(self, files: Sequence[AttachedFile]): ''' Attach a list of files represented as AttachedFile. ''' assert not self._content, 'content must be empty to attach files.' self.content_type = 'multipart/form-data' self._attached_files = 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 _sign(self, rel_url, access_key=None, secret_key=None, hash_type=None): ''' Calculates the signature of the given request and adds the Authorization HTTP header. It should be called at the very end of request preparation and before sending the request to the server. '...
<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(self, **kwargs) -> 'FetchContextManager': ''' Sends the request to the server and reads the response. You may use this method either with plain synchronous Session or AsyncSession. Both the followings patterns are valid: .. code-block:: python3 from ai.bac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def connect_websocket(self, **kwargs) -> 'WebSocketContextManager': ''' Creates a WebSocket connection. .. warning:: This method only works with :class:`~ai.backend.client.session.AsyncSession`. ''' assert isinstance(self.session, AsyncSession), \ ...
<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_json_response(self, response): """For a json response, check if there was any error and throw exception. Otherwise, create a housecanary.response.Res...
response_json = response.json() # handle errors code_key = "code" if code_key in response_json and response_json[code_key] != constants.HTTP_CODE_OK: code = response_json[code_key] message = response_json if "message" in response_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 start_watcher_thread(self): """ Start watcher thread. :return: Watcher thread object. """
# Create watcher thread watcher_thread = threading.Thread(target=self.run_watcher) # If the reload mode is `spawn_wait` if self._reload_mode == self.RELOAD_MODE_V_SPAWN_WAIT: # Use non-daemon thread daemon = False # If the reload mode is not `spawn_wait...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_watcher(self): """ Watcher thread's function. :return: None. """
# Create observer observer = Observer() # Start observer observer.start() # Dict that maps file path to `watch object` watche_obj_map = {} # Run change check in a loop while not self._watcher_to_stop: # Get current watch paths o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_watch_paths(self): """ Find paths to watch. :return: Paths to watch. """
# Add directory paths in `sys.path` to watch paths watch_path_s = set(os.path.abspath(x) for x in sys.path) # For each extra path for extra_path in self._extra_paths or (): # Get the extra path's directory path extra_dir_path = os.path.dirname(os.path.abspath(ex...
<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_short_paths(self, paths): """ Find short paths of given paths. E.g. if both `/home` and `/home/aoik` exist, only keep `/home`. :param paths: Paths. :re...
# Split each path to parts. # E.g. '/home/aoik' to ['', 'home', 'aoik'] path_parts_s = [path.split(os.path.sep) for path in paths] # Root node root_node = {} # Sort these path parts by length, with the longest being the first. # # Longer paths appear 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 _collect_leaf_paths(self, node, path_parts, leaf_paths): """ Collect paths of leaf nodes. :param node: Starting node. Type is dict. Key is child node's path ...
# If the node is leaf node if not node: # Get node path node_path = '/'.join(path_parts) # Add to list leaf_paths.add(node_path) # If the node is not leaf node else: # For each child node for child_path_part, chil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, event): """ Dispatch file system event. Callback called when there is a file system event. Hooked at 2KGRW. This function overrides `FileSyste...
# Get file path file_path = event.src_path # If the file path is in extra paths if file_path in self._extra_paths: # Call `reload` self.reload() # If the file path ends with `.pyc` or `.pyo` if file_path.endswith(('.pyc', '.pyo')): #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload(self): """ Reload the program. :return: None. """
# Get reload mode reload_mode = self._reload_mode # If reload mode is `exec` if self._reload_mode == self.RELOAD_MODE_V_EXEC: # Call `reload_using_exec` self.reload_using_exec() # If reload mode is `spawn_exit` elif self._reload_mode == self.REL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload_using_exec(self): """ Reload the program process. :return: None. """
# Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Reload the program process os.execvpe( # Program file path sys.executable, # Command parts cmd_parts, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload_using_spawn_exit(self): """ Spawn a subprocess and exit the current process. :return: None. """
# Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Spawn subprocess subprocess.Popen(cmd_parts, env=env_copy, close_fds=True) # If need force exit if self._force_exit: # Force e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload_using_spawn_wait(self): """ Spawn a subprocess and wait until it finishes. :return: None. """
# Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Send interrupt to main thread interrupt_main() # Spawn subprocess and wait until it finishes subprocess.call(cmd_parts, env=env_copy, clos...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def agent(agent_id): ''' Show the information about the given agent. ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('Region', 'region'), ('First Contact', 'first_contact'), ('CPU Usage (%)', 'cpu_cur_pct'), ('Used Memory (MiB)', 'mem_cur_bytes'), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_policy(name): """ Show details about a keypair resource policy. When `name` option is omitted, the resource policy for the current access_key will b...
fields = [ ('Name', 'name'), ('Created At', 'created_at'), ('Default for Unspecified', 'default_for_unspecified'), ('Total Resource Slot', 'total_resource_slots'), ('Max Concurrent Sessions', 'max_concurrent_sessions'), ('Max Containers per Session', 'max_containers_...
<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(name, default_for_unspecified, total_resource_slots, max_concurrent_sessions, max_containers_per_session, max_vfolder_count, max_vfolder_size, idle_timeout, allowed_vfolder_hosts): ''' Add a new keypair resource policy. NAME: NAME of a new keypair resource policy. ''' with 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 delete(name): """ Delete a keypair resource policy. NAME: NAME of a keypair resource policy to delete. """
with Session() as session: if input('Are you sure? (y/n): ').lower().strip()[:1] != 'y': print('Canceled.') sys.exit(1) try: data = session.ResourcePolicy.delete(name) except Exception as e: print_error(e) sys.exit(1) if no...
<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(session_id, app, bind, port): """ Run a local proxy to a service provided by Backend.AI compute sessions. The type of proxy depends on the app definition...
api_session = None runner = None async def app_setup(): nonlocal api_session, runner loop = current_loop() api_session = AsyncSession() # TODO: generalize protocol using service ports metadata protocol = 'http' runner = ProxyRunner(api_session, session_id, 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 logs(sess_id_or_alias): ''' Shows the output logs of a running container. \b SESSID: Session ID or its alias given when creating the session. ''' with Session() as session: try: print_wait('Retrieving container logs...') kernel = session.Kernel(sess_id_or_ali...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _wrap_key(function, args, kws): ''' get the key from the function input. ''' return hashlib.md5(pickle.dumps((_from_file(function) + function.__name__, args, kws))).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get(key, adapter = MemoryAdapter): ''' get the cache value ''' try: return pickle.loads(adapter().get(key)) except CacheExpiredException: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set(key, value, timeout = -1, adapter = MemoryAdapter): ''' set cache by code, must set timeout length ''' if adapter(timeout = timeout).set(key, pickle.dumps(value)): return value else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wrapcache(timeout = -1, adapter = MemoryAdapter): ''' the Decorator to cache Function. ''' def _wrapcache(function): @wraps(function) def __wrapcache(*args, **kws): hash_key = _wrap_key(function, args, kws) try: adapter_instance = adapter() return pickle.loads(adapter_instance.get(hash_key)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys): """Creates an Excel file containing data returned by the Analytics ...
workbook = create_excel_workbook(data, result_info_key, identifier_keys) workbook.save(output_file_name) print('Saved Excel file to {}'.format(output_file_name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_analytics_data_to_csv(data, output_folder, result_info_key, identifier_keys): """Creates CSV files containing data returned by the Analytics API. Crea...
workbook = create_excel_workbook(data, result_info_key, identifier_keys) suffix = '.csv' if not os.path.exists(output_folder): os.makedirs(output_folder) for worksheet in workbook.worksheets: file_name = utilities.convert_title_to_snake_case(worksheet.title) file_path = os.p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concat_excel_reports(addresses, output_file_name, endpoint, report_type, retry, api_key, api_secret, files_path): """Creates an Excel file made up of combini...
# create the master workbook to output master_workbook = openpyxl.Workbook() if api_key is not None and api_secret is not None: client = ApiClient(api_key, api_secret) else: client = ApiClient() errors = [] # for each address, call the API and load the xlsx content in a workb...
<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_excel_workbook(data, result_info_key, identifier_keys): """Calls the analytics_data_excel module to create the Workbook"""
workbook = analytics_data_excel.get_excel_workbook(data, result_info_key, identifier_keys) adjust_column_width_workbook(workbook) return workbook
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_column_width(worksheet): """Adjust column width in worksheet. Args: worksheet: worksheet to be adjusted """
dims = {} padding = 1 for row in worksheet.rows: for cell in row: if not cell.value: continue dims[cell.column] = max( dims.get(cell.column, 0), len(str(cell.value)) ) for col, value in list(dims.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 get_ap_info(ipaddress, auth, url): """ function takes input of ipaddress to RESTFUL call to HP IMC :param ipaddress: The current IP address of the Access Poi...
get_ap_info_url = "/imcrs/wlan/apInfo/queryApBasicInfoByCondition?ipAddress=" + str(ipaddress) f_url = url + get_ap_info_url payload = None r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents # print(r.status_code) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def session(sess_id_or_alias): ''' Show detailed information for a running compute session. SESSID: Session id or its alias. ''' fields = [ ('Session ID', 'sess_id'), ('Role', 'role'), ('Image', 'image'), ('Tag', 'tag'), ('Created At', 'created_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_object_errors(self): """Gets a list of business error message strings for each of the requested objects that had a business error. If there was no error,...
if self._object_errors is None: self._object_errors = [{str(o): o.get_errors()} for o in self.objects() if o.has_error()] return self._object_errors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_object_error(self): """Returns true if any requested object had a business logic error, otherwise returns false Returns: boolean """
if self._has_object_error is None: # scan the objects for any business error codes self._has_object_error = next( (True for o in self.objects() if o.has_error()), False) return self._has_object_error
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rate_limits(self): """Returns a list of rate limit details."""
if not self._rate_limits: self._rate_limits = utilities.get_rate_limits(self.response) return self._rate_limits
<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_imc_creds(auth, url): """Function takes input of auth class object auth object and URL and returns a BOOL of TRUE if the authentication was successful....
test_url = '/imcrs' f_url = url + test_url try: response = requests.get(f_url, auth=auth, headers=HEADERS, verify=False) return bool(response.status_code == 200) except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " test_imc_creds: An Error has...
<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_full_python_version(): """ Get full Python version. E.g. - `2.7.11.final.0.32bit` - `3.5.1.final.0.64bit` :return: Full Python version. """
# Get version part, e.g. `3.5.1.final.0` version_part = '.'.join(str(x) for x in sys.version_info) # Get integer width, e.g. 32 or 64 int_width = struct.calcsize('P') * 8 # Get integer width part, e.g. `64bit` or `32bit` int_width_part = str(int_width) + 'bit' # Return full Python versio...
<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_python_path(venv_path): """ Get given virtual environment's `python` program path. :param venv_path: Virtual environment directory path. :return: `python...
# Get `bin` directory path bin_path = get_bin_path(venv_path) # Get `python` program path program_path = os.path.join(bin_path, 'python') # If the platform is Windows if sys.platform.startswith('win'): # Add `.exe` suffix to the `python` program path program_path = program_pat...
<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_options(ctx): """ Add command line options. :return: None. """
# Add option ctx.add_option( '--always', action='store_true', default=False, dest='always', help='whether always run tasks.', ) # Add option ctx.add_option( '--check-import', action='store_true', default=False, dest='check_imp...
<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_pythonpath(path): """ Prepend given path to environment variable PYTHONPATH. :param path: Path to add to PYTHONPATH. :return: New PYTHONPATH value. """
# Get PYTHONPATH value. Default is empty string. pythonpath = os.environ.setdefault('PYTHONPATH', '') # If given path is not in PYTHONPATH if path not in pythonpath.split(os.pathsep): # Prepend given path to PYTHONPATH pythonpath = os.environ['PYTHONPATH'] = \ (path + os.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_path(path): """ Wrap given path as relative path relative to top directory. Wrapper object will be handled specially in \ :paramref:`create_cmd_task.par...
# If given path is not string, # or given path is absolute path. if not isinstance(path, str) or os.path.isabs(path): # Get error message msg = 'Error (2D9ZA): Given path is not relative path: {0}.'.format( path ) # Raise error raise ValueError(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 _mark_target(type, item): """ Wrap given item as input or output target that should be added to task. Wrapper object will be handled specially in \ :paramref...
# If given type is not valid if type not in ('input', 'output'): # Get error message msg = 'Error (7D74X): Type is not valid: {0}'.format(type) # Raise error raise ValueError(msg) # If given type is valid. # Store given item orig_item = item # If given path 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 create_node(ctx, path): """ Create node for given relative path. :param ctx: BuildContext object. :param path: Relative path relative to top directory. :retu...
# Ensure given context object is BuildContext object _ensure_build_context(ctx) # Get top directory's relative path relative to `wscript` directory top_dir_relpath = os.path.relpath( # Top directory's absolute path ctx.top_dir, # `wscript` directory's absolute path ctx....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalize_items( ctx, items, str_to_node=False, node_to_str=False, allow_task=False, ): """ Normalize given items. Do several things: - Ignore None. - Flatt...
# Ensure given context object is BuildContext object _ensure_build_context(ctx) # Normalized tuples list norm_tuple_s = [] # If given items list is empty if not items: # Return empty list return norm_tuple_s # If given items list is not empty. # For given items list'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_touch_file( ctx, path, check_import=False, check_import_module=None, check_import_python=None, always=False, ): """ Update touch file at given path. D...
# Ensure given context object is BuildContext object _ensure_build_context(ctx) # Print title print_title('Update touch file: {}'.format(path)) # Create touch node touch_node = create_node(ctx, path) # Whether task needs run need_run = False # If the touch file not exists, #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chain_tasks(tasks): """ Chain given tasks. Set each task to run after its previous task. :param tasks: Tasks list. :return: Given tasks list. """
# If given tasks list is not empty if tasks: # Previous task previous_task = None # For given tasks list's each task for task in tasks: # If the task is not None. # Task can be None to allow code like ``task if _PY2 else None``. if task is no...
<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_ctx(pythonpath=None): """ Decorator that makes decorated function use BuildContext instead of \ Context instance. BuildContext instance has more method...
# If argument `pythonpath` is string if isinstance(pythonpath, str): # Create paths list containing the string path_s = [pythonpath] # If argument `pythonpath` is list elif isinstance(pythonpath, list): # Use the list as paths list path_s = pythonpath # If argument...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_ctx(func): """ Decorator that makes decorated function use ConfigurationContext instead \ of Context instance. :param func: Decorated function. :retur...
# Create ConfigurationContext subclass class _ConfigurationContext(ConfigurationContext): # Set command name for the context class cmd = func.__name__ # Set function name for the context class fun = func.__name__ # Store the created context class with the decorated functio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_ctx(ctx): """ Print given context's info. :param ctx: Context object. :return: None. """
# Print title print_title('ctx attributes') # Print context object's attributes print_text(dir(ctx)) # Print end title print_title('ctx attributes', is_end=True) # Print title print_title('ctx.options') # Print context options dict print_text(pformat(vars(ctx.options), inden...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def virtualenv_setup( ctx, python, inputs=None, outputs=None, touch=None, check_import=False, pip_setup_file=None, pip_setup_touch=None, cache_key=None, always=Fa...
# Ensure given context object is BuildContext object _ensure_build_context(ctx) # If `get-pip.py` file path is not given if pip_setup_file is None: # Not create task that sets up `pip` pip_setup_task = None # If `get-pip.py` file path is given else: # Create task 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 create_venv( ctx, python, venv_path, inputs=None, outputs=None, pip_setup_file=None, pip_setup_touch=None, virtualenv_setup_touch=None, task_name=None, cache_...
# Ensure given context object is BuildContext object _ensure_build_context(ctx) # Create task that sets up `virtualenv` package virtualenv_setup_task = virtualenv_setup( # Context ctx=ctx, # Python program path python=python, # Touch file path touch=vi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pip_ins_req( ctx, python, req_path, venv_path=None, inputs=None, outputs=None, touch=None, check_import=False, check_import_module=None, pip_setup_file=None, ...
# Ensure given context object is BuildContext object _ensure_build_context(ctx) # If virtual environment directory path is not given if venv_path is None: # Use given Python program path venv_python = python # If virtual environment directory path is given else: # 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 git_clean(ctx): """ Delete all files untracked by git. :param ctx: Context object. :return: None. """
# Get command parts cmd_part_s = [ # Program path 'git', # Clean untracked files 'clean', # Remove all untracked files '-x', # Remove untracked directories too '-d', # Force to remove '-f', # Give two `-f` flags to rem...
<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_telnet_template(auth, url, template_name= None, template_id= None): """ Takes template_name as input to issue RESTUL call to HP IMC which will delete ...
try: if template_id is None: telnet_templates = get_telnet_template(auth, url) if template_name is None: template_name = telnet_template['name'] template_id = None for template in telnet_templates: if template['name'] == templa...
<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_ssh_template(auth, url, template_name= None, template_id= None): """ Takes template_name as input to issue RESTUL call to HP IMC which will delete the...
try: if template_id is None: ssh_templates = get_ssh_template(auth, url) if template_name is None: template_name = ssh_template['name'] template_id = None for template in ssh_templates: if template['name'] == template_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 delete_snmp_template(auth, url, template_name= None, template_id= None): """ Takes template_name as input to issue RESTUL call to HP IMC which will delete th...
try: if template_id is None: snmp_templates = get_snmp_templates(auth, url) if template_name is None: template_name = snmp_template['name'] template_id = None for template in snmp_templates: if template['name'] == template_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 proxy(ctx, bind, port): """ Run a non-encrypted non-authorized API proxy server. Use this only for development and testing! """
app = web.Application() app.on_startup.append(startup_proxy) app.on_cleanup.append(cleanup_proxy) app.router.add_route("GET", r'/stream/{path:.*$}', websocket_handler) app.router.add_route("GET", r'/wsproxy/{path:.*$}', websocket_handler) app.router.add_route('*', r'/{path:.*$}', web_handler) ...
<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_dev_details(ip_address, auth, url): """Takes string input of IP address to issue RESTUL call to HP IMC :param ip_address: string object of dotted decimal...
get_dev_details_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \ str(ip_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false" f_url = url + get_dev_details_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_inteface_up(ifindex, auth, url, devid=None, devip=None): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call...
if devip is not None: devid = get_dev_details(devip, auth, url)['id'] set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up" f_url = url + set_int_up_url try: response = requests.put(f_url, auth=auth, headers=HEADERS) if response.status_co...
<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 delete(cls, access_key: str): """ Deletes an existing keypair with given ACCESSKEY. """
q = 'mutation($access_key: String!) {' \ ' delete_keypair(access_key: $access_key) {' \ ' ok msg' \ ' }' \ '}' variables = { 'access_key': access_key, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.se...
<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 list(cls, user_id: Union[int, str] = None, is_active: bool = None, fields: Iterable[str] = None) -> Sequence[dict]: ''' Lists the keypairs. You need an admin privilege for this operation. ''' if fields is None: fields = ...
<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 info(self, fields: Iterable[str] = None) -> dict: ''' Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12 ''' if fields is None: fields = ( 'a...
<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 activate(cls, access_key: str) -> dict: ''' Activates this keypair. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \ ' modify_keypair(access_key: $access_key, props: $input) {' \ ...
<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 deactivate(cls, access_key: str) -> dict: ''' Deactivates this keypair. Deactivated keypairs cannot make any API requests unless activated again by an administrator. You need an admin privilege for this operation. ''' q = 'mutation($access_key: String!, ...
<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 check_presets(cls): ''' Lists all resource presets in the current scaling group with additiona information. ''' rqst = Request(cls.session, 'POST', '/resource/check-presets') async with rqst.fetch() as resp: return await resp.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 set_imc_creds(h_url=None, imc_server=None, imc_port=None, imc_user=None,imc_pw=None): """ This function prompts user for IMC server information and credentui...
global auth, url if h_url is None: imc_protocol = input( "What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:") if imc_protocol == "1": h_url = 'http://' else: h_url = 'https://' imc_server ...
<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_version(root): """ Load and return the contents of version.json. :param root: The root path that the ``version.json`` file will be opened :type root: str...
version_json = os.path.join(root, 'version.json') if os.path.exists(version_json): with open(version_json, 'r') as version_json_file: return json.load(version_json_file) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch(self, endpoint_name, identifier_input, query_params=None): """Calls this instance's request_client's post method with the specified component endpoint ...
endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} if len(identifier_input) == 1: # If only one identifier specified, use a GET request query_params.update(identifier_input[0]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_synchronous(self, endpoint_name, query_params=None): """Calls this instance's request_client's get method with the specified component endpoint"""
endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name if query_params is None: query_params = {} return self._request_client.get(endpoint_url, query_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_identifier_input(self, identifier_data): """Convert the various formats of input identifier_data into the proper json format expected by the ApiClient fe...
identifier_input = [] if isinstance(identifier_data, list) and len(identifier_data) > 0: # if list, convert each item in the list to json for address in identifier_data: identifier_input.append(self._convert_to_identifier_json(address)) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_identifier_component(self, endpoint_name, identifier_data, query_params=None): """Common method for handling parameters before passing to api_client"""
if query_params is None: query_params = {} identifier_input = self.get_identifier_input(identifier_data) return self._api_client.fetch(endpoint_name, identifier_input, query_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_to_identifier_json(self, address_data): """Convert input address data into json format"""
if isinstance(address_data, str): # allow just passing a slug string. return {"slug": address_data} if isinstance(address_data, tuple) and len(address_data) > 0: address_json = {"address": address_data[0]} if len(address_data) > 1: addre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_report(self, address, zipcode, report_type="full", format_type="json"): """Call the value_report component Value Report only supports a single address....
query_params = { "report_type": report_type, "format": format_type, "address": address, "zipcode": zipcode } return self._api_client.fetch_synchronous("property/value_report", query_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rental_report(self, address, zipcode, format_type="json"): """Call the rental_report component Rental Report only supports a single address. Args: - address ...
# only json is supported by rental report. query_params = { "format": format_type, "address": address, "zipcode": zipcode } return self._api_client.fetch_synchronous("property/rental_report", query_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def component_mget(self, zip_data, components): """Call the zip component_mget endpoint Args: - zip_data - As described in the class docstring. - components - A ...
if not isinstance(components, list): print("Components param must be a list") return query_params = {"components": ",".join(components)} return self.fetch_identifier_component( "zip/component_mget", zip_data, query_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version(request): """ Returns the contents of version.json or a 404. """
version_json = import_string(version_callback)(settings.BASE_DIR) if version_json is None: return HttpResponseNotFound('version.json not found') else: return JsonResponse(version_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 heartbeat(request): """ Runs all the Django checks and returns a JsonResponse with either a status code of 200 or 500 depending on the results of the checks....
all_checks = checks.registry.registry.get_checks( include_deployment_checks=not settings.DEBUG, ) details = {} statuses = {} level = 0 for check in all_checks: detail = heartbeat_check_detail(check) statuses[check.__name__] = detail['status'] level = max(level,...
<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_component_results(json_data, result_key): """ Returns a list of ComponentResult from the json_data"""
component_results = [] for key, value in list(json_data.items()): if key not in [result_key, "meta"]: component_result = ComponentResult( key, value["result"], value["api_code"], value["api_code_description"] ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_error(self): """Returns whether there was a business logic error when fetching data for any components for this property. Returns: boolean """
return next( (True for cr in self.component_results if cr.has_error()), False )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_errors(self): """If there were any business errors fetching data for this property, returns the error messages. Returns: string - the error message, or N...
return [{cr.component_name: cr.get_error()} for cr in self.component_results if cr.has_error()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_json(cls, json_data): """Deserialize property json data into a Property object Args: json_data (dict): The json data for this property Returns: ...
prop = Property() address_info = json_data["address_info"] prop.address = address_info["address"] prop.block_id = address_info["block_id"] prop.zipcode = address_info["zipcode"] prop.zipcode_plus4 = address_info["zipcode_plus4"] prop.address_full = address_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 create_from_json(cls, json_data): """Deserialize block json data into a Block object Args: json_data (dict): The json data for this block Returns: Block obj...
block = Block() block_info = json_data["block_info"] block.block_id = block_info["block_id"] block.num_bins = block_info["num_bins"] if "num_bins" in block_info else None block.property_type = block_info["property_type"] if "property_type" in block_info else None block.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 create_from_json(cls, json_data): """Deserialize zipcode json data into a ZipCode object Args: json_data (dict): The json data for this zipcode Returns: Zip...
zipcode = ZipCode() zipcode.zipcode = json_data["zipcode_info"]["zipcode"] zipcode.meta = json_data["meta"] if "meta" in json_data else None zipcode.component_results = _create_component_results(json_data, "zipcode_info") return zipcode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_json(cls, json_data): """Deserialize msa json data into a Msa object Args: json_data (dict): The json data for this msa Returns: Msa object """
msa = Msa() msa.msa = json_data["msa_info"]["msa"] msa.meta = json_data["meta"] if "meta" in json_data else None msa.component_results = _create_component_results(json_data, "msa_info") return msa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def starts_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Start yielding items when a condition arise. Args: iterable: the it...
if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.dropwhile(lambda x: not condition(x), iterable)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stops_when(iterable, condition): # type: (Iterable, Union[Callable, Any]) -> Iterable """Stop yielding items when a condition arise. Args: iterable: the iter...
if not callable(condition): cond_value = condition def condition(x): return x == cond_value return itertools.takewhile(lambda x: not condition(x), iterable)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip_duplicates(iterable, key=None, fingerprints=()): # type: (Iterable, Callable, Any) -> Iterable """ Returns a generator that will yield all objects from ...
fingerprints = fingerprints or set() fingerprint = None # needed on type errors unrelated to hashing try: # duplicate some code to gain perf in the most common case if key is None: for x in iterable: if x not in fingerprints: yield x ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(iterable, chunksize, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields items from an iterator in iterable chunks. """
it = iter(iterable) while True: yield cast(itertools.chain([next(it)], itertools.islice(it, chunksize - 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 window(iterable, size=2, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields iterms by bunch of a given size, but rolling only one item in ...
iterable = iter(iterable) d = deque(itertools.islice(iterable, size), size) if cast: yield cast(d) for x in iterable: d.append(x) yield cast(d) else: yield d for x in iterable: d.append(x) yield 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 at_index(iterable, index): # type: (Iterable[T], int) -> T """" Return the item at the index of this iterable or raises IndexError. WARNING: this will consum...
try: if index < 0: return deque(iterable, maxlen=abs(index)).popleft() return next(itertools.islice(iterable, index, index + 1)) except (StopIteration, IndexError) as e: raise_from(IndexError('Index "%d" out of range' % index), e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterslice(iterable, start=0, stop=None, step=1): # type: (Iterable[T], int, int, int) -> Iterable[T] """ Like itertools.islice, but accept int and callables....
if step < 0: raise ValueError("The step can not be negative: '%s' given" % step) if not isinstance(start, int): # [Callable:Callable] if not isinstance(stop, int) and stop: return stops_when(starts_when(iterable, start), stop) # [Callable:int] return star...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def firsts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the first x items from this iterable or default. """
try: items = int(items) except (ValueError, TypeError): raise ValueError("items should be usable as an int but is currently " "'{}' of type '{}'".format(items, type(items))) # TODO: replace this so that it returns lasts() if items < 0: raise ValueError...