Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def is_enabled(): output = subprocess.check_output(['ufw', 'status'], universal_newlines=True, env={'LANG': 'en_US', 'PATH': os.environ['PATH']}) ...
[ "\n Check if `ufw` is enabled\n\n :returns: True if ufw is enabled\n " ]
Please provide a description of the function:def is_ipv6_ok(soft_fail=False): # do we have IPv6 in the machine? if os.path.isdir('/proc/sys/net/ipv6'): # is ip6tables kernel module loaded? if not is_module_loaded('ip6_tables'): # ip6tables support isn't complete, let's try to l...
[ "\n Check if IPv6 support is present and ip6tables functional\n\n :param soft_fail: If set to True and IPv6 support is broken, then reports\n that the host doesn't have IPv6 support, otherwise a\n UFWIPv6Error exception is raised.\n :returns: True if IPv6 is workin...
Please provide a description of the function:def disable_ipv6(): exit_code = subprocess.call(['sed', '-i', 's/IPV6=.*/IPV6=no/g', '/etc/default/ufw']) if exit_code == 0: hookenv.log('IPv6 support in ufw disabled', level='INFO') else: hookenv.log("Couldn'...
[ "\n Disable ufw IPv6 support in /etc/default/ufw\n " ]
Please provide a description of the function:def enable(soft_fail=False): if is_enabled(): return True if not is_ipv6_ok(soft_fail): disable_ipv6() output = subprocess.check_output(['ufw', 'enable'], universal_newlines=True, ...
[ "\n Enable ufw\n\n :param soft_fail: If set to True silently disables IPv6 support in ufw,\n otherwise a UFWIPv6Error exception is raised when IP6\n support is broken.\n :returns: True if ufw is successfully enabled\n " ]
Please provide a description of the function:def reload(): output = subprocess.check_output(['ufw', 'reload'], universal_newlines=True, env={'LANG': 'en_US', 'PATH': os.environ['PATH']}) m =...
[ "\n Reload ufw\n\n :returns: True if ufw is successfully enabled\n " ]
Please provide a description of the function:def default_policy(policy='deny', direction='incoming'): if policy not in ['allow', 'deny', 'reject']: raise UFWError(('Unknown policy %s, valid values: ' 'allow, deny, reject') % policy) if direction not in ['incoming', 'outgoin...
[ "\n Changes the default policy for traffic `direction`\n\n :param policy: allow, deny or reject\n :param direction: traffic direction, possible values: incoming, outgoing,\n routed\n " ]
Please provide a description of the function:def modify_access(src, dst='any', port=None, proto=None, action='allow', index=None): if not is_enabled(): hookenv.log('ufw is disabled, skipping modify_access()', level='WARN') return if action == 'delete': cmd = ['ufw...
[ "\n Grant access to an address or subnet\n\n :param src: address (e.g. 192.168.1.234) or subnet\n (e.g. 192.168.1.0/24).\n :param dst: destiny of the connection, if the machine has multiple IPs and\n connections to only one of those have to accepted this is the\n ...
Please provide a description of the function:def grant_access(src, dst='any', port=None, proto=None, index=None): return modify_access(src, dst=dst, port=port, proto=proto, action='allow', index=index)
[ "\n Grant access to an address or subnet\n\n :param src: address (e.g. 192.168.1.234) or subnet\n (e.g. 192.168.1.0/24).\n :param dst: destiny of the connection, if the machine has multiple IPs and\n connections to only one of those have to accepted this is the\n ...
Please provide a description of the function:def revoke_access(src, dst='any', port=None, proto=None): return modify_access(src, dst=dst, port=port, proto=proto, action='delete')
[ "\n Revoke access to an address or subnet\n\n :param src: address (e.g. 192.168.1.234) or subnet\n (e.g. 192.168.1.0/24).\n :param dst: destiny of the connection, if the machine has multiple IPs and\n connections to only one of those have to accepted this is the\n ...
Please provide a description of the function:def service(name, action): if action == 'open': subprocess.check_output(['ufw', 'allow', str(name)], universal_newlines=True) elif action == 'close': subprocess.check_output(['ufw', 'delete', 'allow', str(name)], ...
[ "\n Open/close access to a service\n\n :param name: could be a service name defined in `/etc/services` or a port\n number.\n :param action: `open` or `close`\n " ]
Please provide a description of the function:def modprobe(module, persist=True): cmd = ['modprobe', module] log('Loading kernel module %s' % module, level=INFO) subprocess.check_call(cmd) if persist: persistent_modprobe(module)
[ "Load a kernel module and configure for auto-load on reboot." ]
Please provide a description of the function:def rmmod(module, force=False): cmd = ['rmmod'] if force: cmd.append('-f') cmd.append(module) log('Removing kernel module %s' % module, level=INFO) return subprocess.check_call(cmd)
[ "Remove a module from the linux kernel" ]
Please provide a description of the function:def is_module_loaded(module): matches = re.findall('^%s[ ]+' % module, lsmod(), re.M) return len(matches) > 0
[ "Checks if a kernel module is already loaded" ]
Please provide a description of the function:def get_config(): '''Gather and sanity-check volume configuration data''' volume_config = {} config = hookenv.config() errors = False if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'): volume_config['ephemeral'] = True ...
[]
Please provide a description of the function:def configure_volume(before_change=lambda: None, after_change=lambda: None): '''Set up storage (or don't) according to the charm's volume configuration. Returns the mount point or "ephemeral". before_change and after_change are optional functions to be call...
[]
Please provide a description of the function:def get_audits(): audits = [] settings = utils.get_settings('os') # Ensure that the /etc/security/limits.d directory is only writable # by the root user, but others can execute and read. audits.append(DirectoryPermissionAudit('/etc/security/limits.d...
[ "Get OS hardening security limits audits.\n\n :returns: dictionary of audits\n " ]
Please provide a description of the function:def _take_action(self): # Do the action if there isn't an unless override. if self.unless is None: return True # Invoke the callback if there is one. if hasattr(self.unless, '__call__'): return not self.unless...
[ "Determines whether to perform the action or not.\n\n Checks whether or not an action should be taken. This is determined by\n the truthy value for the unless parameter. If unless is a callback\n method, it will be invoked with no parameters in order to determine\n whether or not the act...
Please provide a description of the function:def install_alternative(name, target, source, priority=50): ''' Install alternative configuration ''' if (os.path.exists(target) and not os.path.islink(target)): # Move existing file/directory away before installing shutil.move(target, '{}.bak'.format...
[]
Please provide a description of the function:def ensure_packages(packages): required = filter_installed_packages(packages) if required: apt_install(required, fatal=True)
[ "Install but do not upgrade required plugin packages." ]
Please provide a description of the function:def _calculate_workers(): ''' Determine the number of worker processes based on the CPU count of the unit containing the application. Workers will be limited to MAX_DEFAULT_WORKERS in container environments where no worker-multipler configuration opt...
[]
Please provide a description of the function:def context_complete(self, ctxt): # Fresh start self.complete = False self.missing_data = [] for k, v in six.iteritems(ctxt): if v is None or v == '': if k not in self.missing_data: self...
[ "Check for missing data for the required context data.\n Set self.missing_data if it exists and return False.\n Set self.complete if no missing data and return True.\n " ]
Please provide a description of the function:def get_related(self): # Fresh start self.related = False try: for interface in self.interfaces: if relation_ids(interface): self.related = True return self.related except At...
[ "Check if any of the context interfaces have relation ids.\n Set self.related and return True if one of the interfaces\n has relation ids.\n " ]
Please provide a description of the function:def canonical_names(self): cns = [] for r_id in relation_ids('identity-service'): for unit in related_units(r_id): rdata = relation_get(rid=r_id, unit=unit) for k in rdata: if k.startswi...
[ "Figure out which canonical names clients will access this service.\n " ]
Please provide a description of the function:def get_network_addresses(self): addresses = [] for net_type in [INTERNAL, ADMIN, PUBLIC]: net_config = config(ADDRESS_MAP[net_type]['config']) # NOTE(jamespage): Fallback must always be private address # ...
[ "For each network configured, return corresponding address and\n hostnamr or vip (if available).\n\n Returns a list of tuples of the form:\n\n [(address_in_net_a, hostname_in_net_a),\n (address_in_net_b, hostname_in_net_b),\n ...]\n\n or, if no hostname...
Please provide a description of the function:def resolve_ports(self, ports): if not ports: return None hwaddr_to_nic = {} hwaddr_to_ip = {} for nic in list_nics(): # Ignore virtual interfaces (bond masters will be identified from # their slav...
[ "Resolve NICs not yet bound to bridge(s)\n\n If hwaddress provided then returns resolved hwaddress otherwise NIC.\n " ]
Please provide a description of the function:def _determine_ctxt(self): rel = os_release(self.pkg, base='icehouse') version = '2' if CompareOpenStackReleases(rel) >= 'pike': version = '3' service_type = 'volumev{version}'.format(version=version) service_name...
[ "Determines the Volume API endpoint information.\n\n Determines the appropriate version of the API that should be used\n as well as the catalog_info string that would be supplied. Returns\n a dict containing the volume_api_version and the volume_catalog_info.\n " ]
Please provide a description of the function:def _determine_ctxt(self): if config('aa-profile-mode') in ['disable', 'enforce', 'complain']: ctxt = {'aa_profile_mode': config('aa-profile-mode'), 'ubuntu_release': lsb_release()['DISTRIB_RELEASE']} if self.aa_pr...
[ "\n Validate aa-profile-mode settings is disable, enforce, or complain.\n\n :return ctxt: Dictionary of the apparmor profile or None\n " ]
Please provide a description of the function:def manually_disable_aa_profile(self): profile_path = '/etc/apparmor.d' disable_path = '/etc/apparmor.d/disable' if not os.path.lexists(os.path.join(disable_path, self.aa_profile)): os.symlink(os.path.join(profile_path, self.aa_pr...
[ "\n Manually disable an apparmor profile.\n\n If aa-profile-mode is set to disabled (default) this is required as the\n template has been written but apparmor is yet unaware of the profile\n and aa-disable aa-profile fails. Without this the profile would kick\n into enforce mode o...
Please provide a description of the function:def setup_aa_profile(self): self() if not self.ctxt: log("Not enabling apparmor Profile") return self.install_aa_utils() cmd = ['aa-{}'.format(self.ctxt['aa_profile_mode'])] cmd.append(self.ctxt['aa_pro...
[ "\n Setup an apparmor profile.\n The ctxt dictionary will contain the apparmor profile mode and\n the apparmor profile name.\n Makes calls out to aa-disable, aa-complain, or aa-enforce to setup\n the apparmor profile.\n " ]
Please provide a description of the function:def execd_module_paths(execd_dir=None): if not execd_dir: execd_dir = default_execd_dir() if not os.path.exists(execd_dir): return for subpath in os.listdir(execd_dir): module = os.path.join(execd_dir, subpath) if os.path.is...
[ "Generate a list of full paths to modules within execd_dir." ]
Please provide a description of the function:def execd_submodule_paths(command, execd_dir=None): for module_path in execd_module_paths(execd_dir): path = os.path.join(module_path, command) if os.access(path, os.X_OK) and os.path.isfile(path): yield path
[ "Generate a list of full paths to the specified command within exec_dir.\n " ]
Please provide a description of the function:def execd_run(command, execd_dir=None, die_on_error=True, stderr=subprocess.STDOUT): for submodule_path in execd_submodule_paths(command, execd_dir): try: subprocess.check_output(submodule_path, stderr=stderr, ...
[ "Run command for each module within execd_dir which defines it." ]
Please provide a description of the function:def getrange(self, key_prefix, strip=False): self.cursor.execute("select key, data from kv where key like ?", ['%s%%' % key_prefix]) result = self.cursor.fetchall() if not result: return {} if ...
[ "\n Get a range of keys starting with a common prefix as a mapping of\n keys to values.\n\n :param str key_prefix: Common prefix among all keys\n :param bool strip: Optionally strip the common prefix from the key\n names in the returned dict\n :return dict: A (possibly ...
Please provide a description of the function:def update(self, mapping, prefix=""): for k, v in mapping.items(): self.set("%s%s" % (prefix, k), v)
[ "\n Set the values of multiple keys at once.\n\n :param dict mapping: Mapping of keys to values\n :param str prefix: Optional prefix to apply to all keys in `mapping`\n before setting\n " ]
Please provide a description of the function:def unset(self, key): self.cursor.execute('delete from kv where key=?', [key]) if self.revision and self.cursor.rowcount: self.cursor.execute( 'insert into kv_revisions values (?, ?, ?)', [key, self.revisio...
[ "\n Remove a key from the database entirely.\n " ]
Please provide a description of the function:def unsetrange(self, keys=None, prefix=""): if keys is not None: keys = ['%s%s' % (prefix, key) for key in keys] self.cursor.execute('delete from kv where key in (%s)' % ','.join(['?'] * len(keys)), keys) if self.revision ...
[ "\n Remove a range of keys starting with a common prefix, from the database\n entirely.\n\n :param list keys: List of keys to remove.\n :param str prefix: Optional prefix to apply to all keys in ``keys``\n before removing.\n " ]
Please provide a description of the function:def set(self, key, value): serialized = json.dumps(value) self.cursor.execute('select data from kv where key=?', [key]) exists = self.cursor.fetchone() # Skip mutations to the same value if exists: if exists[0] =...
[ "\n Set a value in the database.\n\n :param str key: Key to set the value for\n :param value: Any JSON-serializable value to be set\n " ]
Please provide a description of the function:def delta(self, mapping, prefix): previous = self.getrange(prefix, strip=True) if not previous: pk = set() else: pk = set(previous.keys()) ck = set(mapping.keys()) delta = DeltaSet() # added ...
[ "\n return a delta containing values that have changed.\n " ]
Please provide a description of the function:def hook_scope(self, name=""): assert not self.revision self.cursor.execute( 'insert into hooks (hook, date) values (?, ?)', (name or sys.argv[0], datetime.datetime.utcnow().isoformat())) self.revision = s...
[ "Scope all future interactions to the current hook execution\n revision." ]
Please provide a description of the function:def add_bridge(name, datapath_type=None): ''' Add the named bridge to openvswitch ''' log('Creating bridge {}'.format(name)) cmd = ["ovs-vsctl", "--", "--may-exist", "add-br", name] if datapath_type is not None: cmd += ['--', 'set', 'bridge', name, ...
[]
Please provide a description of the function:def add_bridge_port(name, port, promisc=False): ''' Add a port to the named openvswitch bridge ''' log('Adding port {} to bridge {}'.format(port, name)) subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-port", name, port]) ...
[]
Please provide a description of the function:def del_bridge_port(name, port): ''' Delete a port from the named openvswitch bridge ''' log('Deleting port {} from bridge {}'.format(port, name)) subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-port", name, port]) sub...
[]
Please provide a description of the function:def add_ovsbridge_linuxbridge(name, bridge): ''' Add linux bridge to the named openvswitch bridge :param name: Name of ovs bridge to be added to Linux bridge :param bridge: Name of Linux bridge to be added to ovs bridge :returns: True if veth is added between...
[]
Please provide a description of the function:def is_linuxbridge_interface(port): ''' Check if the interface is a linuxbridge bridge :param port: Name of an interface to check whether it is a Linux bridge :returns: True if port is a Linux bridge''' if os.path.exists('/sys/class/net/' + port + '/bridge')...
[]
Please provide a description of the function:def get_certificate(): ''' Read openvswitch certificate from disk ''' if os.path.exists(CERT_PATH): log('Reading ovs certificate from {}'.format(CERT_PATH)) with open(CERT_PATH, 'r') as cert: full_cert = cert.read() begin_marke...
[]
Please provide a description of the function:def check_for_eni_source(): ''' Juju removes the source line when setting up interfaces, replace if missing ''' with open('/etc/network/interfaces', 'r') as eni: for line in eni: if line == 'source /etc/network/interfaces.d/*': ...
[]
Please provide a description of the function:def enable_ipfix(bridge, target): '''Enable IPfix on bridge to target. :param bridge: Bridge to monitor :param target: IPfix remote endpoint ''' cmd = ['ovs-vsctl', 'set', 'Bridge', bridge, 'ipfix=@i', '--', '--id=@i', 'create', 'IPFIX', 'targe...
[]
Please provide a description of the function:def delete_package(self, cache, pkg): if self.is_virtual_package(pkg): log("Package '%s' appears to be virtual - purging provides" % pkg.name, level=DEBUG) for _p in pkg.provides_list: self.delete_packa...
[ "Deletes the package from the system.\n\n Deletes the package form the system, properly handling virtual\n packages.\n\n :param cache: the apt cache\n :param pkg: the package to remove\n " ]
Please provide a description of the function:def _get_ip_address(self, request): ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None) if ipaddr: # X_FORWARDED_FOR returns client1, proxy1, proxy2,... return ipaddr.split(",")[0].strip() return request.META.get("...
[ "Get the remote ip address the request was generated from. " ]
Please provide a description of the function:def _get_view_name(self, request): method = request.method.lower() try: attributes = getattr(self, method) view_name = type(attributes.__self__).__module__ + '.' + type(attributes.__self__).__name__ return view_nam...
[ "Get view name." ]
Please provide a description of the function:def _get_view_method(self, request): if hasattr(self, 'action'): return self.action if self.action else None return request.method.lower()
[ "Get view method." ]
Please provide a description of the function:def _get_response_ms(self): response_timedelta = now() - self.log['requested_at'] response_ms = int(response_timedelta.total_seconds() * 1000) return max(response_ms, 0)
[ "\n Get the duration of the request response cycle is milliseconds.\n In case of negative duration 0 is returned.\n " ]
Please provide a description of the function:def should_log(self, request, response): return self.logging_methods == '__all__' or request.method in self.logging_methods
[ "\n Method that should return a value that evaluated to True if the request should be logged.\n By default, check if the request method is in logging_methods.\n " ]
Please provide a description of the function:def _clean_data(self, data): if isinstance(data, bytes): data = data.decode(errors='replace') if isinstance(data, list): return [self._clean_data(d) for d in data] if isinstance(data, dict): SENSITIVE_FIEL...
[ "\n Clean a dictionary of data of potentially sensitive info before\n sending to the database.\n Function based on the \"_clean_credentials\" function of django\n (https://github.com/django/django/blob/stable/1.11.x/django/contrib/auth/__init__.py#L50)\n\n Fields defined by django...
Please provide a description of the function:def trace(): import traceback import sys tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # script name + line number line = tbinfo.split(", ")[1] # Get Python syntax error # synerror = traceback.format_exc().splitlines()[-1...
[ "\n trace finds the line, the filename\n and error message and returns it\n to the user\n " ]
Please provide a description of the function:def main(*argv): try: # Inputs # adminUsername = argv[0] adminPassword = argv[1] siteURL = argv[2] username = argv[3] itemId = argv[4] folderId = argv[5] # Logic # sh = arcre...
[ " main driver of program " ]
Please provide a description of the function:def merge_dicts(dicts, op=operator.add): a = None for b in dicts: if a is None: a = b.copy() else: a = dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)]) return a
[ "Merge a list of dictionaries.\n\n Args:\n dicts (list): a list of dictionary objects\n op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`.\n\n Returns:\n dict: the merged dictionary\n\n " ]
Please provide a description of the function:def getLayerIndex(url): urlInfo = None urlSplit = None inx = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') inx = urlSplit[len(urlSplit)-1] if is_number(inx): return int(inx...
[ "Extract the layer index from a url.\n\n Args:\n url (str): The url to parse.\n\n Returns:\n int: The layer index.\n\n Examples:\n >>> url = \"http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12\"\n >>> arcresthelper.common.getLayerIndex(url)\n ...
Please provide a description of the function:def getLayerName(url): urlInfo = None urlSplit = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') name = urlSplit[len(urlSplit)-3] return name except: return url finally: ...
[ "Extract the layer name from a url.\n\n Args:\n url (str): The url to parse.\n\n Returns:\n str: The layer name.\n\n Examples:\n >>> url = \"http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12\"\n >>> arcresthelper.common.getLayerIndex(url)\n 't...
Please provide a description of the function:def random_string_generator(size=6, chars=string.ascii_uppercase): try: return ''.join(random.choice(chars) for _ in range(size)) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "rando...
[ "Generates a random string from a set of characters.\n\n Args:\n size (int): The length of the resultant string. Defaults to 6.\n chars (str): The characters to be used by :py:func:`random.choice`. Defaults to :py:const:`string.ascii_uppercase`.\n\n Returns:\n str: The randomly generated ...
Please provide a description of the function:def random_int_generator(maxrange): try: return random.randint(0,maxrange) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "random_int_generator", "line": line, ...
[ "Generates a random integer from 0 to `maxrange`, inclusive.\n\n Args:\n maxrange (int): The upper range of integers to randomly choose.\n\n Returns:\n int: The randomly generated integer from :py:func:`random.randint`.\n\n Examples:\n >>> arcresthelper.common.random_int_generator(15)\...
Please provide a description of the function:def local_time_to_online(dt=None): is_dst = None utc_offset = None try: if dt is None: dt = datetime.datetime.now() is_dst = time.daylight > 0 and time.localtime().tm_isdst > 0 utc_offset = (time.altzone if is_dst else t...
[ "Converts datetime object to a UTC timestamp for AGOL.\n\n Args:\n dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`.\n\n Returns:\n float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000)\n\...
Please provide a description of the function:def online_time_to_string(value, timeFormat, utcOffset=0): try: return datetime.datetime.fromtimestamp(value/1000 + utcOffset*3600).strftime(timeFormat) except: line, filename, synerror = trace() raise ArcRestHelperError({ ...
[ "Converts AGOL timestamp to formatted string.\n\n Args:\n value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)\n timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.\n utcOffset (int): Hours difference from UTC and desired ou...
Please provide a description of the function:def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False
[ "Determines if the input is numeric\n\n Args:\n s: The value to check.\n Returns:\n bool: ``True`` if the input is numeric, ``False`` otherwise.\n\n " ]
Please provide a description of the function:def init_config_json(config_file): json_data = None try: if os.path.exists(config_file): #Load the config file with open(config_file) as json_file: json_data = json.load(json_file) return unicode_conve...
[ "Deserializes a JSON configuration file.\n\n Args:\n config_file (str): The path to the JSON file.\n Returns:\n dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.\n\n " ]
Please provide a description of the function:def write_config_json(config_file, data): outfile = None try: with open(config_file, 'w') as outfile: json.dump(data, outfile) except: line, filename, synerror = trace() raise ArcRestHelperError({ "func...
[ "Serializes an object to disk.\n\n Args:\n config_file (str): The path on disk to save the file.\n data (object): The object to serialize.\n\n " ]
Please provide a description of the function:def unicode_convert(obj): try: if isinstance(obj, dict): return {unicode_convert(key): unicode_convert(value) for key, value in obj.items()} elif isinstance(obj, list): return [unicode_convert(element) for element in obj] ...
[ "Converts unicode objects to anscii.\n\n Args:\n obj (object): The object to convert.\n Returns:\n The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained.\n\n " ]
Please provide a description of the function:def find_replace_string(obj, find, replace): try: strobj = str(obj) newStr = string.replace(strobj, find, replace) if newStr == strobj: return obj else: return newStr except: line, filename, syner...
[ "Performs a string.replace() on the input object.\n\n Args:\n obj (object): The object to find/replace. It will be cast to ``str``.\n find (str): The string to search for.\n replace (str): The string to replace with.\n Returns:\n str: The replaced string.\n\n " ]
Please provide a description of the function:def find_replace(obj, find, replace): try: if isinstance(obj, dict): return {find_replace(key,find,replace): find_replace(value,find,replace) for key, value in obj.items()} elif isinstance(obj, list): return [find_replace(elem...
[ " Searches an object and performs a find and replace.\n\n Args:\n obj (object): The object to iterate and find/replace.\n find (str): The string to search for.\n replace (str): The string to replace with.\n Returns:\n object: The object with replaced strings.\n\n " ]
Please provide a description of the function:def chunklist(l, n): n = max(1, n) for i in range(0, len(l), n): yield l[i:i+n]
[ "Yield successive n-sized chunks from l.\n\n Args:\n l (object): The object to chunk.\n n (int): The size of the chunks.\n Yields:\n The next chunk in the object.\n Raises:\n TypeError: if ``l`` has no :py:func:`len`.\n Examples:\n >>> for c in arcresthelper.common.chu...
Please provide a description of the function:def init_log(log_file): #Create the log file log = None try: log = open(log_file, 'a') #Change the output to both the windows and log file #original = sys.stdout sys.stdout = Tee(sys.stdout, log) except: pass ...
[ " Creates log file on disk and \"Tees\" :py:class:`sys.stdout` to console and disk\n\n Args:\n log_file (str): The path on disk to append or create the log file.\n\n Returns:\n file: The opened log file.\n " ]
Please provide a description of the function:def close_log(log_file): sys.stdout = sys.__stdout__ if log_file is not None: log_file.close() del log_file
[ " Closes the open file and returns :py:class:`sys.stdout` to the default (i.e., console output).\n\n Args:\n log_file (file): The file object to close.\n\n " ]
Please provide a description of the function:def _tostr(self,obj): if not obj: return '' if isinstance(obj, list): return ', '.join(map(self._tostr, obj)) return str(obj)
[ " converts a object to list, if object is a list, it creates a\n comma seperated string.\n " ]
Please provide a description of the function:def _unzip_file(self, zip_file, out_folder): try: zf = zipfile.ZipFile(zip_file, 'r') zf.extractall(path=out_folder) zf.close() del zf return True except: return False
[ " unzips a file to a given folder " ]
Please provide a description of the function:def _list_files(self, path): files = [] for f in glob.glob(pathname=path): files.append(f) files.sort() return files
[ "lists files in a given directory" ]
Please provide a description of the function:def _get_content_type(self, filename): mntype = mimetypes.guess_type(filename)[0] filename, fileExtension = os.path.splitext(filename) if mntype is None and\ fileExtension.lower() == ".csv": mntype = "text/csv" ...
[ " gets the content type of a file " ]
Please provide a description of the function:def trace(): import traceback, inspect, sys tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] filename = inspect.getfile(inspect.currentframe()) # script name + line number line = tbinfo.split(", ")[1] # Get Python syntax error #...
[ "\n trace finds the line, the filename\n and error message and returns it\n to the user\n " ]
Please provide a description of the function:def style(self, value): if self._style != value and \ value in self._styles: self._style = value
[ "gets/sets the style" ]
Please provide a description of the function:def angle(self, value): if self._angle != value and \ isinstance(value, (int, float, long)): self._angle = value
[ "gets/sets the angle" ]
Please provide a description of the function:def color(self, value): if self._color != value and \ isinstance(value, Color): self._color = value
[ "gets/sets the color" ]
Please provide a description of the function:def size(self, value): if self._size != value and \ isinstance(value, (int, float, long)): self._size = value
[ "gets/sets the size" ]
Please provide a description of the function:def xoffset(self, value): if self._xoffset != value and \ isinstance(value, (int, float, long)): self._xoffset = value
[ "gets/sets the xoffset" ]
Please provide a description of the function:def yoffset(self, value): if self._yoffset != value and \ isinstance(value, (int, float, long)): self._yoffset = value
[ "gets/sets the yoffset" ]
Please provide a description of the function:def outlineWidth(self, value): if isinstance(value, (int, float, long)) and \ not self._outline is None: self._outline['width'] = value
[ "gets/sets the outlineWidth" ]
Please provide a description of the function:def outlineColor(self, value): if isinstance(value, Color) and \ not self._outline is None: self._outline['color'] = value
[ "gets/sets the outlineColor" ]
Please provide a description of the function:def value(self): if self._outline is None: return { "type" : "esriSMS", "style" : self._style, "color" : self._color.value, "size" : self._size, "angle" : self._angle...
[ "returns the object as dictionary" ]
Please provide a description of the function:def width(self, value): if self._width != value and \ isinstance(value, (int, float, long)): self._width = value
[ "gets/sets the width" ]
Please provide a description of the function:def value(self): return { "type" : self._type, "style" : self._style, "color" : self._color.value, "width" : self._width }
[ "gets the color value" ]
Please provide a description of the function:def value(self): if self._outline is None: return { "type" : self._type, "style" : self._style, "color" : self._color.value, } else: return { "type" :...
[ "gets the color value" ]
Please provide a description of the function:def red(self, value): if value != self._red and \ isinstance(value, int): self._red = value
[ "gets/sets the red value" ]
Please provide a description of the function:def green(self, value): if value != self._green and \ isinstance(value, int): self._green = value
[ "gets/sets the green value" ]
Please provide a description of the function:def blue(self, value): if value != self._blue and \ isinstance(value, int): self._blue = value
[ "gets/sets the blue value" ]
Please provide a description of the function:def alpha(self, value): if value != self._alpha and \ isinstance(value, int): self._alpha = value
[ "gets/sets the alpha value" ]
Please provide a description of the function:def value(self): return [self._red, self._green, self._blue, self._alpha]
[ "gets the color value" ]
Please provide a description of the function:def unfederate(self, serverId): url = self._url + "/servers/{serverid}/unfederate".format( serverid=serverId) params = {"f" : "json"} return self._get(url=url, param_dict=params, p...
[ "\n This operation unfederates an ArcGIS Server from Portal for ArcGIS\n " ]
Please provide a description of the function:def validateAllServers(self): url = self._url + "/servers/validate" params = {"f" : "json"} return self._get(url=url, param_dict=params, proxy_port=self._proxy_port, p...
[ "\n This operation provides status information about a specific ArcGIS\n Server federated with Portal for ArcGIS.\n\n Parameters:\n serverId - unique id of the server\n " ]
Please provide a description of the function:def editLogSettings(self, logLocation, logLevel="WARNING", maxLogFileAge=90): url = self._url + "/settings/edit" params = { "f" : "json", "logDir" : logLocation, "logLevel" : logLevel, "maxLogFileAge" :...
[ "\n edits the log settings for the portal site\n\n Inputs:\n logLocation - file path to where you want the log files saved\n on disk\n logLevel - this is the level of detail saved in the log files\n Levels are: OFF, SEVERE, WARNING, INFO, FI...
Please provide a description of the function:def query(self, logLevel="WARNING", source="ALL", startTime=None, endTime=None, logCodes=None, users=None, messageCount=1000): url = self._url + "/query" filter_value = {"codes":[], "users":[], "source": "*"} if so...
[ "\n allows users to look at the log files from a the REST endpoint\n\n Inputs:\n logLevel - this is the level of detail saved in the log files\n Levels are: OFF, SEVERE, WARNING, INFO, FINE, VERBOSE, and\n DEBUG\n source - the type of inf...
Please provide a description of the function:def deleteCertificate(self, certName): params = {"f" : "json"} url = self._url + "/sslCertificates/{cert}/delete".format( cert=certName) return self._post(url=url, param_dict=params, proxy_port=self._pro...
[ "\n This operation deletes an SSL certificate from the key store. Once\n a certificate is deleted, it cannot be retrieved or used to enable\n SSL.\n\n Inputs:\n certName - name of the cert to delete\n\n " ]
Please provide a description of the function:def exportCertificate(self, certName, outFolder=None): params = {"f" : "json"} url = self._url + "/sslCertificates/{cert}/export".format( cert=certName) if outFolder is None: outFolder = tempfile.gettempdir() r...
[ "\n This operation downloads an SSL certificate. The file returned by\n the server is an X.509 certificate. The downloaded certificate can\n be imported into a client that is making HTTP requests.\n\n Inputs:\n certName - name of the cert to export\n outFolder - folder ...