text
stringlengths
81
112k
Convert an interface name to an index value. def get_index(self): ''' Convert an interface name to an index value. ''' ifreq = struct.pack('16si', self.name, 0) res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq) return struct.unpack("16si", res)[1]
Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_flow_control def set_pause_param(self, autoneg, rx_pause, tx_pause): ...
Return version string. def get_version(): """Return version string.""" with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
Split a string with comma or space-separated elements into a list. def split_elements(value): """Split a string with comma or space-separated elements into a list.""" l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
Generate Python 2 code from Python 3 code. def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False): """Generate Python 2 code from Python 3 code.""" def copy(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst)): shutil.copy(src, dst)...
Default setup hook. def default_hook(config): """Default setup hook.""" if (any(arg.startswith('bdist') for arg in sys.argv) and os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)): shutil.rmtree(LIB_DIR) if IS_PY2K and any(arg.startswith('install') or ...
Returns the default interface def get_default_if(): """ Returns the default interface """ f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break exce...
Returns the default gateway def get_default_gw(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_rou...
Create the module instance of the GraphiteClient. def init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """ global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickl...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. def send(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ ...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. def send_dict(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. def send_list(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """...
Allow the module to be called from the cli. def cli(): """ Allow the module to be called from the cli. """ import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metr...
Make a TCP connection to the graphite server on port self.port def connect(self): """ Make a TCP connection to the graphite server on port self.port """ self.socket = socket.socket() self.socket.settimeout(self.timeout_in_seconds) try: self.socket.connect(sel...
Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and random delay in range 1..`jitter` (exponential backoff) :param sleep: time to sleep ...
Close the TCP connection with the graphite server. def disconnect(self): """ Close the TCP connection with the graphite server. """ try: self.socket.shutdown(1) # If its currently a socket, set it to None except AttributeError: self.socket = None...
Dispatch the different steps of sending def _dispatch_send(self, message): """ Dispatch the different steps of sending """ if self.dryrun: return message if not self.socket: raise GraphiteSendException( "Socket was not created before sen...
Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the socket connection is no longer valid. def _send_and_...
Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :param timestmap: epoch time of the event :type prefix: float or int ...
Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default format...
Check if socket have been monkey patched by gevent def enable_asynchronous(self): """Check if socket have been monkey patched by gevent""" def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False ...
Covert a string that is ready to be sent to graphite into a tuple def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") ...
Given a message send it to the graphite server. def _send(self, message): """ Given a message send it to the graphite server. """ # An option to lowercase the entire message if self.lowercase_metric_names: message = message.lower() # convert the message into a pickled payl...
Make sure the metric is free of control chars, spaces, tabs, etc. def clean_metric_name(self, metric_name): """ Make sure the metric is free of control chars, spaces, tabs, etc. """ if not self._clean_metric_name: return metric_name metric_name = str(metric_name) ...
Get supported languages (by querying the server). def _get_languages(cls) -> set: """Get supported languages (by querying the server).""" if not cls._server_is_alive(): cls._start_server_on_free_port() url = urllib.parse.urljoin(cls._url, 'Languages') languages = set() ...
Get matches element attributes. def _get_attrib(cls): """Get matches element attributes.""" if not cls._server_is_alive(): cls._start_server_on_free_port() params = {'language': FAILSAFE_LANGUAGE, 'text': ''} data = urllib.parse.urlencode(params).encode() root = cls....
Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the page is empty. def get_form(self, request, obj=None, **kwargs):...
Create the cache key for the current page and language def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = page.node.site_id except AttributeError: # CMS_3_4 site_id = page.site_id...
Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a...
Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 ...
Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and rele...
Return filtered data register value for the provided pin (0-11). Useful for debugging. def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)'...
Return baseline data register value for the provided pin (0-11). Useful for debugging. def baseline_data(self, pin): """Return baseline data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)'...
Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being to...
Return True if the specified pin is being touched, otherwise returns False. def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched...
Decorator straight up stolen from stackoverflow def profileit(func): """ Decorator straight up stolen from stackoverflow """ def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile" # Name the data file sensibly prof = cProfile.Profile() prof.enable() retval = p...
Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: string :returns: a function that f...
Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that filters by the server response time. :...
Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted. :type max_waiting: string :returns: a ...
Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument on --help for its format) to limit the ...
Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rtype: function def filter_response_size(...
Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple def _get_fields_for_model(model): """ Gets all of the fields on the model. :param Declarative...
Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple def _get_re...
Creates a ResourceBase subclass by inspecting a SQLAlchemy Model. This is somewhat more restrictive than explicitly creating managers and resources. However, if you only need any of the basic CRUD+L operations, :param sqlalchemy.Model model: This is the model that will be ...
Logic to decide if the file should be processed or just needs to be loaded from its pickle data. def _is_pickle_valid(self): """Logic to decide if the file should be processed or just needs to be loaded from its pickle data. """ if not os.path.exists(self._pickle_file): ...
Load data from a pickle file. def _load(self): """Load data from a pickle file. """ with open(self._pickle_file, 'rb') as source: pickler = pickle.Unpickler(source) for attribute in self._pickle_attributes: pickle_data = pickler.load() setattr(se...
Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time. def _save(self): """Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the ...
Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str...
Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further processed with commands (top paths, http status counter......
Returns a list of all methods that start with ``cmd_``. def commands(cls): """Returns a list of all methods that start with ``cmd_``.""" cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')] return cmds
Reports a breakdown of how many requests have been made per HTTP method (GET, POST...). def cmd_http_methods(self): """Reports a breakdown of how many requests have been made per HTTP method (GET, POST...). """ methods = defaultdict(int) for line in self._valid_lines: ...
Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured. def cmd_ip_counter(self): """Reports a breakdown of...
Generate statistics about HTTP status codes. 404, 500 and so on. def cmd_status_codes_counter(self): """Generate statistics about HTTP status codes. 404, 500 and so on. """ status_codes = defaultdict(int) for line in self._valid_lines: status_codes[line.status_code] += 1 ...
Generate statistics about HTTP requests' path. def cmd_request_path_counter(self): """Generate statistics about HTTP requests' path.""" paths = defaultdict(int) for line in self._valid_lines: paths[line.http_request_path] += 1 return paths
List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally. def cmd_slow_requests(self): """List...
Returns the average response time of all, non aborted, requests. def cmd_average_response_time(self): """Returns the average response time of all, non aborted, requests.""" average = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response >...
Returns the average queue time of all, non aborted, requests. def cmd_average_waiting_time(self): """Returns the average queue time of all, non aborted, requests.""" average = [ line.time_wait_queues for line in self._valid_lines if line.time_wait_queues >= 0 ...
Generate statistics regarding how many requests were processed by each downstream server. def cmd_server_load(self): """Generate statistics regarding how many requests were processed by each downstream server. """ servers = defaultdict(int) for line in self._valid_lines:...
Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which peak can be ignored. Currently ...
Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they should be configurable. def cmd_connection...
Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise. def cmd_requests_per_minute(self): """Generates statistics on how many requests were made per minute. ...
Returns the raw lines to be printed. def cmd_print(self): """Returns the raw lines to be printed.""" if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and log...
Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or globally. def _sort_and_trim(data, reverse=False): ...
Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database. def db_access_point(func): """ Wraps a function that actually accesses the database...
Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. :return: The python type of the column :rtype...
Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that is appropriate for translating a strin...
Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to. If the cls._create_fields is defined then it will ...
Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values ...
Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned models on :return: A tuple of the list of dictionary representation ...
Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :param dict updates: The columns and the values to upda...
Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dictionary :rtype: dict :raises: NotFoundException def delete(sel...
Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized model. :rtype: dict def serialize_model(self, model, field_dict...
A recursive function for serializing a model into a json ready format. def _serialize_model_helper(self, model, field_dict=None): """ A recursive function for serializing a model into a json ready format. """ field_dict = field_dict or self.dot_field_list_to_dict() ...
Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqlalchemy orm model instance. def _get_model(self, lookup_keys, se...
Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strings indicating the valid fields. Defaults to self.fields. :re...
Prints all commands available from Log with their description. def print_commands(): """Prints all commands available from Log with their description. """ dummy_log_file = Log() commands = Log.commands() commands.sort() for cmd in commands: cmd = getattr(dummy_log_file, 'cmd_{0...
Prints all filters available with their description. def print_filters(): """Prints all filters available with their description.""" for filter_name in VALID_FILTERS: filter_func = getattr(filters, 'filter_{0}'.format(filter_name)) description = filter_func.__doc__ if description: ...
Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class def add_observer(self, observer): """ Adds weak ref to an observer. @param obser...
Removes all registered observers. def remove_all_observers(self): """ Removes all registered observers. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: self.remove_observer(observer)
Spawns new NSThread to handle notifications. def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None) self._thread....
Stops spawned NSThread. def stopThread(self): """Stops spawned NSThread.""" if self._thread is not None: self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES) self._thread = None
Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop. def runPowerNotificationsThread(self): """Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" pool = NSAutoreleasePool.alloc().init() @objc.callbackFor(IOPSNotif...
Removes the only source from NSRunLoop and cancels thread. def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThre...
Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() def addObserver(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() """ with...
Removes an observer. @param observer: Previously added observer def removeObserver(self, observer): """ Removes an observer. @param observer: Previously added observer """ with self._lock: self._weak_observers.remove(weakref.ref(observer)) if le...
Called in response to IOPSNotificationCreateRunLoopSource() event. def on_power_source_notification(self): """ Called in response to IOPSNotificationCreateRunLoopSource() event. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer...
In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSG...
Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ def add_observer(self, observer): """ Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ super(PowerManage...
Stops thread and invalidates source. def remove_observer(self, observer): """ Stops thread and invalidates source. """ super(PowerManagement, self).remove_observer(observer) if len(self._weak_observers) == 0: if not self._cf_run_loop: PowerManagement....
Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_...
Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. def get_low_battery_warning_level(self): """ Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise Window...
Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus...
FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported def power_source_type(): """ ...
TODO @return: Tuple (energy_full, energy_now, power_now) def get_battery_state(): """ TODO @return: Tuple (energy_full, energy_now, power_now) """ energy_now = float(100.0) power_now = float(100.0) energy_full = float(100.0) return energy_full, en...
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. def get_providing_power_source_type(self): ...
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. def get_low_battery_warning_level(self): """ Looks thro...
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac powe...
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. def get_providing_power_source_type(self): ...
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac powe...