Search is not available for this dataset
text
stringlengths
75
104k
def timestamp_YmdHMS(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an...
def datetimeobj_YmdHMS(value): """Convert timestamp string to a datetime object. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: A datetime object. Raises: Value...
def datetimeobj_epoch(value): """Convert timestamp string to a datetime object. Timestamps strings like '1383470155' are able to be converted by this function. Args: value: A timestamp string as seconds since epoch. Returns: A datetime object. Raises: ValueError: If t...
def timestamp_fmt(value, fmt): """Convert timestamp string to time in seconds since epoch. Wraps the datetime.datetime.strptime(). This is slow use the other timestamp_*() functions if possible. Args: value: A timestamp string. fmt: A timestamp format string. Returns: The ...
def timestamp_any(value): """Convert timestamp string to time in seconds since epoch. Most timestamps strings are supported in fact this wraps the dateutil.parser.parse() method. This is SLOW use the other timestamp_*() functions if possible. Args: value: A timestamp string. Returns: ...
def timestamp(value, fmt=None): """Parse a datetime to a unix timestamp. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may st...
def datetimeobj(value, fmt=None): """Parse a datetime to a datetime object. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may ...
def _fix_alert_config_dict(alert_config): """ Fix the alert config .args() dict for the correct key name """ data = alert_config.args() data['params_set'] = data.get('args') del data['args'] return data
def _get_login_payload(self, username, password): """ returns the payload the login page expects :rtype: dict """ payload = { 'csrfmiddlewaretoken': self._get_csrf_token(), 'ajax': '1', 'next': '/app/', 'username': username, ...
def _api_post(self, url, **kwargs): """ Convenience method for posting """ response = self.session.post( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {...
def _api_delete(self, url, **kwargs): """ Convenience method for deleting """ response = self.session.delete( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{...
def _api_get(self, url, **kwargs): """ Convenience method for getting """ response = self.session.get( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}...
def _login(self, username, password): """ ._login() makes three requests: * One to the /login/ page to get a CSRF cookie * One to /login/ajax/ to get a logged-in session cookie * One to /app/ to get the beginning of the account id :param username: A valid us...
def list_scheduled_queries(self): """ List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Lo...
def list_tags(self): """ List all tags for the account. The response differs from ``Hooks().list()``, in that tag dicts for anomaly alerts include a 'scheduled_query_id' key with the value being the UUID for the associated scheduled query :return: A list of all tag dict...
def get(self, name_or_id): """ Get alert by name or id :param name_or_id: The alert's name or id :type name_or_id: str :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will r...
def create(self, name, patterns, logs, trigger_config, alert_reports): """ Create an inactivity alert :param name: A name for the inactivity alert :type name: str :param patterns: A list of regexes to match :type patterns: list of str :param logs: A list of log...
def delete(self, tag_id): """ Delete the specified InactivityAlert :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries ...
def _create_scheduled_query(self, query, change, scope_unit, scope_count): """ Create the scheduled query """ query_data = { 'scheduled_query': { 'name': 'ForAnomalyReport', 'query': query, 'threshold_type': '%', ...
def create(self, name, query, scope_count, scope_unit, increase_positive, percentage_change, trigger_config, logs, alert_reports): """ Create an anomaly alert. This call...
def delete(self, tag_id): """ Delete a specified anomaly alert tag and its scheduled query This method makes 3 requests: * One to get the associated scheduled_query_id * One to delete the alert * One to delete get scheduled query :param tag_id: The ...
def unparse_range(obj): """Unparse a range argument. Args: obj: An article range. There are a number of valid formats; an integer specifying a single article or a tuple specifying an article range. If the range doesn't give a start article then all articles up to the...
def parse_newsgroup(line): """Parse a newsgroup info line to python types. Args: line: An info response line containing newsgroup info. Returns: A tuple of group name, low-water as integer, high-water as integer and posting status. Raises: ValueError: If the newsgroup ...
def parse_header(line): """Parse a header line. Args: line: A header line as a string. Returns: None if end of headers is found. A string giving the continuation line if a continuation is found. A tuple of name, value when a header line is found. Raises: ValueE...
def parse_headers(obj): """Parse a string a iterable object (including file like objects) to a python dictionary. Args: obj: An iterable object including file-like objects. Returns: An dictionary of headers. If a header is repeated then the last value for that header is given. ...
def unparse_headers(hdrs): """Parse a dictionary of headers to a string. Args: hdrs: A dictionary of headers. Returns: The headers as a string that can be used in an NNTP POST. """ return "".join([unparse_header(n, v) for n, v in hdrs.items()]) + "\r\n"
def do_POST(self): """ Handles the POST request sent by Boundary Url Action """ self.send_response(urllib2.httplib.OK) self.end_headers() content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) print("Client: {0}".format...
def run(tests=(), reporter=None, stop_after=None): """ Run the tests that are loaded by each of the strings provided. Arguments: tests (iterable): the collection of tests (specified as `str` s) to run reporter (Reporter): a `Reporter` to use for the run. If unpro...
def defaults_docstring(defaults, header=None, indent=None, footer=None): """Return a docstring from a list of defaults. """ if indent is None: indent = '' if header is None: header = '' if footer is None: footer = '' width = 60 #hbar = indent + width * '=' + '\n' # ...
def defaults_decorator(defaults): """Decorator to append default kwargs to a function. """ def decorator(func): """Function that appends default kwargs to a function. """ kwargs = dict(header='Keyword arguments\n-----------------\n', indent=' ', ...
def _load(self, **kwargs): """Load kwargs key,value pairs into __dict__ """ defaults = dict([(d[0], d[1]) for d in self.defaults]) # Require kwargs are in defaults for k in kwargs: if k not in defaults: msg = "Unrecognized attribute of %s: %s" % ( ...
def defaults_docstring(cls, header=None, indent=None, footer=None): """Add the default values to the class docstring""" return defaults_docstring(cls.defaults, header=header, indent=indent, footer=footer)
def set_value(self, value): """Set the value This invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ self.check_bounds(value) self.check_type(value) self.__value__ = value
def check_type(self, value): """Hook for type-checking, invoked during assignment. raises TypeError if neither value nor self.dtype are None and they do not match. will not raise an exception if either value or self.dtype is None """ if self.__dict__['dtype'] is None: ...
def value(self): """Return the current value. This first checks if the value is cached (i.e., if `self.__value__` is not None) If it is not cached then it invokes the `loader` function to compute the value, and caches the computed value """ if self.__value__ i...
def check_type(self, value): """Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar. """ try: scalar = asscalar(value) except ValueError as e: raise Typ...
def symmetric_error(self): """Return the symmertic error Similar to above, but zero implies no error estimate, and otherwise this will either be the symmetric error, or the average of the low,high asymmetric errors. """ # ADW: Should this be `np.nan`? if self.__e...
def set_free(self, free): """Set free/fixed status """ if free is None: self.__free__ = False return self.__free__ = bool(free)
def set_errors(self, errors): """Set parameter error estimate """ if errors is None: self.__errors__ = None return self.__errors__ = [asscalar(e) for e in errors]
def set(self, **kwargs): """Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ # Probably want to reset bounds if set fails if 'bounds' in kwargs: ...
def load_and_parse(self): """ Load the metrics file from the given path """ f = open(self.file_path, "r") metrics_json = f.read() self.metrics = json.loads(metrics_json)
def import_metrics(self): """ 1) Get command line arguments 2) Read the JSON file 3) Parse into a dictionary 4) Create or update definitions using API call """ self.v2Metrics = self.metricDefinitionV2(self.metrics) if self.v2Metrics: metrics =...
def create_from_pytz(cls, tz_info): """Create an instance using the result of the timezone() call in "pytz". """ zone_name = tz_info.zone utc_transition_times_list_raw = getattr(tz_info, '_utc_transition_times', ...
def extract_dictionary(self, metrics): """ Extract required fields from an array """ new_metrics = {} for m in metrics: metric = self.extract_fields(m) new_metrics[m['name']] = metric return new_metrics
def filter(self): """ Apply the criteria to filter out on the metrics required """ if self.filter_expression is not None: new_metrics = [] metrics = self.metrics['result'] for m in metrics: if self.filter_expression.search(m['name']): ...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.hostGroupId is not None: self.hostGroupId = self.args.hostGroupId self.path = "v1/hostgroup/{0}".format(str(self.hostGroupId))
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.tenant_id is not None: self._tenant_id = self.args.tenant_id if self.args.fingerprint_fields is not None: self._fingerprint_field...
def _call_api(self): """ Make a call to the meter via JSON RPC """ # Allocate a socket and connect to the meter sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((self.rpc_host, self.rpc_port)) self.get_json() message = [self.rpc_message.encode('utf-...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ HostgroupModify.get_arguments(self) if self.args.host_group_id is not None: self.host_group_id = self.args.host_group_id self.path = "v1/hostgroup/" + str(self.host_group_id)
def identifier(self, text): """identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;""" self._attempting(text) return concatenation([ alternation([ self.alpha_character, "_" ]), zero_or_more( alternation([ self.alpha_character, "...
def expression(self, text): """expression = number , op_mult , expression | expression_terminal , op_mult , number , [operator , expression] | expression_terminal , op_add , [operator , expression] | expression_terminal , [operator , expression] ; """ se...
def expression_terminal(self, text): """expression_terminal = identifier | terminal | option_group | repetition_group | grouping_group | special_handling ; """ self._attempt...
def option_group(self, text): """option_group = "[" , expression , "]" ;""" self._attempting(text) return concatenation([ "[", self.expression, "]" ], ignore_whitespace=True)(text).retyped(TokenType.option_group)
def terminal(self, text): """terminal = '"' . (printable - '"') + . '"' | "'" . (printable - "'") + . "'" ; """ self._attempting(text) return alternation([ concatenation([ '"', one_or_more( exclusion(self.printable, '"') ), '"' ], ign...
def operator(self, text): """operator = "|" | "." | "," | "-";""" self._attempting(text) return alternation([ "|", ".", ",", "-" ])(text).retyped(TokenType.operator)
def op_mult(self, text): """op_mult = "*" ;""" self._attempting(text) return terminal("*")(text).retyped(TokenType.op_mult)
def op_add(self, text): """op_add = "+" ;""" self._attempting(text) return terminal("+")(text).retyped(TokenType.op_add)
def setp(self, name, clear_derived=True, value=None, bounds=None, free=None, errors=None): """ Set the value (and bounds) of the named parameter. Parameters ---------- name : str The parameter name. clear_derived : bool Flag to clear...
def set_attributes(self, **kwargs): """ Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.). """ self.clear_derived() kwargs = dict(kwargs) for name...
def _init_properties(self): """ Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping """ self._missing = {} for k, p in self.params.items(): if p.required: self._missing[k] = p ...
def get_params(self, pnames=None): """ Return a list of Parameter objects Parameters ---------- pname : list or None If a list get the Parameter objects with those names If none, get all the Parameter objects Returns ------- params : lis...
def param_values(self, pnames=None): """ Return an array with the parameter values Parameters ---------- pname : list or None If a list, get the values of the `Parameter` objects with those names If none, get all values of all the `Parameter` objects Ret...
def param_errors(self, pnames=None): """ Return an array with the parameter errors Parameters ---------- pname : list of string or none If a list of strings, get the Parameter objects with those names If none, get all the Parameter objects Returns ...
def clear_derived(self): """ Reset the value of all Derived properties to None This is called by setp (and by extension __setattr__) """ for p in self.params.values(): if isinstance(p, Derived): p.clear_value()
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName)
def method(self, value): """ Before assigning the value validate that is in one of the HTTP methods we implement """ keys = self._methods.keys() if value not in keys: raise AttributeError("Method value not in " + str(keys)) else: self._meth...
def _get_environment(self): """ Gets the configuration stored in environment variables """ if 'TSP_EMAIL' in os.environ: self._email = os.environ['TSP_EMAIL'] if 'TSP_API_TOKEN' in os.environ: self._api_token = os.environ['TSP_API_TOKEN'] if 'TSP_A...
def _get_url_parameters(self): """ Encode URL parameters """ url_parameters = '' if self._url_parameters is not None: url_parameters = '?' + urllib.urlencode(self._url_parameters) return url_parameters
def metric_get(self, enabled=False, custom=False): """ Returns a metric definition identified by name :param enabled: Return only enabled metrics :param custom: Return only custom metrics :return Metrics: """ self.path = 'v1/metrics?enabled={0}&{1}'.format(enabled...
def _do_get(self): """ HTTP Get Request """ return requests.get(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _do_delete(self): """ HTTP Delete Request """ return requests.delete(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _do_post(self): """ HTTP Post Request """ return requests.post(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _do_put(self): """ HTTP Put Request """ return requests.put(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _call_api(self): """ Make an API call to get the metric definition """ self._url = self.form_url() if self._headers is not None: logging.debug(self._headers) if self._data is not None: logging.debug(self._data) if len(self._get_url_par...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ # ApiCli.get_arguments(self) if self.args.file_name is not None: self.file_name = self.args.file_name
def execute(self): """ Run the steps to execute the CLI """ # self._get_environment() self.add_arguments() self._parse_args() self.get_arguments() if self._validate_arguments(): self._plot_data() else: print(self._message)
def validate_sceneInfo(self): """Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong. """ if self.sceneInfo.prefix not in self.__satellitesMap: raise WrongSceneNameError('USGS Downloader: Prefix of %s (%s) is invalid' ...
def verify_type_product(self, satellite): """Gets satellite id """ if satellite == 'L5': id_satellite = '3119' stations = ['GLC', 'ASA', 'KIR', 'MOR', 'KHC', 'PAC', 'KIS', 'CHM', 'LGS', 'MGR', 'COA', 'MPS'] elif satellite == 'L7': id_satellite = '3373' ...
def get_remote_file_size(self, url): """Gets the filesize of a remote file """ try: req = urllib.request.urlopen(url) return int(req.getheader('Content-Length').strip()) except urllib.error.HTTPError as error: logger.error('Error retrieving size of the remote ...
def download(self, bands=None, download_dir=None, metadata=False): """Download remote .tar.bz file.""" if not download_dir: download_dir = DOWNLOAD_DIR if bands is None: bands = list(range(1, 12)) + ['BQA'] else: self.validate_bands(bands) pa...
def validate_bands(bands): """Validate bands parameter.""" if not isinstance(bands, list): raise TypeError('Parameter bands must be a "list"') valid_bands = list(range(1, 12)) + ['BQA'] for band in bands: if band not in valid_bands: raise InvalidBa...
def connect_earthexplorer(self): """ Connection to Earth explorer without proxy """ logger.info("Establishing connection to Earthexplorer") print("\n Establishing connection to Earthexplorer") try: opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor()) ...
def download_file(self, url, download_dir, sceneName): """ Downloads large files in pieces """ try: # Log logger.info('\nStarting download..') print('\n Starting download..\n') # Request req = urllib.request.urlopen(url) try: ...
def prefixed_by(prefix): """ Make a callable returning True for names starting with the given prefix. The returned callable takes two arguments, the attribute or name of the object, and possibly its corresponding value (which is ignored), as suitable for use with :meth:`ObjectLocator.is_test_module...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.metric_name is not None: self._metric_name = self.args.metric_name self.path = "v1/metrics/{0}".format(self._metric_name)
def timezone(zone): r''' Return a datetime.tzinfo implementation for the given timezone >>> from datetime import datetime, timedelta >>> utc = timezone('UTC') >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> timezone(unicode('US/Eastern')) is eastern True >>> ...
def normalize(self, dt, is_dst=False): '''Correct the timezone information on the given datetime''' if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') return dt.replace(tzinfo=self)
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.hostGroupId is not None: self.hostGroupId = self.args.hostGroupId if self.args.force is not None: self.force = self.args.force ...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) self._actions = self.args.actions if self.args.actions is not None else None self._alarm_name = self.args.alarm_name if self.args.alarm_name is not None else None ...
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False): """Escape-aware text splitting: Split text on on a delimiter, recognizing escaped delimiters.""" is_escaped = False split_count = 0 yval = [] for char in text: if is_escaped: is_escaped = False yval.append...
def esc_join(iterable, delimiter=" ", escape="\\"): """Join an iterable by a delimiter, replacing instances of delimiter in items with escape + delimiter. """ rep = escape + delimiter return delimiter.join(i.replace(delimiter, rep) for i in iterable)
def get_newline_positions(text): """Returns a list of the positions in the text where all new lines occur. This is used by get_line_and_char to efficiently find coordinates represented by offset positions. """ pos = [] for i, c in enumerate(text): if c == "\n": pos.append(i) return pos
def get_line_and_char(newline_positions, position): """Given a list of newline positions, and an offset from the start of the source code that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates. """ if newline_positions: for line_no, nl_pos in enumerate(newline_positions): ...
def point_to_source(source, position, fmt=(2, True, "~~~~~", "^")): """Point to a position in source code. source is the text we're pointing in. position is a 2-tuple of (line_number, character_number) to point to. fmt is a 4-tuple of formatting parameters, they are: name default description...
def _dump_text(self): """ Send output in textual format """ results = self._relay_output['result']; for l in results: dt = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(int(l[1]['ts']))) print("{0} {1} {2} {3}".format(l[0], dt, l[1]['type'], l[1]['msg']...
def _handle_results(self): """ Call back function to be implemented by the CLI. """ # Only process if we get HTTP result of 200 if self._api_result.status_code == requests.codes.ok: self._relay_output = json.loads(self._api_result.text) if self._raw: ...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ PluginBase.get_arguments(self) if self.args.organizationName is not None: self.organizationName = self.args.organizationName if self.args.repositoryName is not None: self....
def extract_fields(self, metric): """ Extract only the required fields for the create/update API call """ m = {} if 'name' in metric: m['name'] = metric['name'] if 'description' in metric: m['description'] = metric['description'] if 'displa...
def get_arguments(self): """ Extracts the specific arguments of this CLI """ AlarmModify.get_arguments(self) self._alarm_id = self.args.alarm_id if self.args.alarm_id is not None else None self.get_api_parameters()
def _filter(self): """ Apply the criteria to filter out on the output required """ if self._metrics or self._control or self._plugins: relays = self._relays['result']['relays'] for relay in relays: if self._metrics: del relays[r...