code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not zone in self._zones: raise IndexError('Zone does not exist and cannot be updated: %d', zone) old_status = self._zones[zone].status if status is None: status = old_status self._zones[zone].status = status self._zones[zone].timestamp = time...
def _update_zone(self, zone, status=None)
Updates a zones status. :param zone: zone number :type zone: int :param status: zone status :type status: int :raises: IndexError
3.253042
3.214684
1.011932
return (time.time() > self._zones[zone].timestamp + Zonetracker.EXPIRE) and self._zones[zone].expander is False
def _zone_expired(self, zone)
Determine if a zone is expired or not. :param zone: zone number :type zone: int :returns: whether or not the zone is expired
14.373205
20.393372
0.704798
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handlers and open the device device.on_zone_fault += handle_zone_fault device.on_zone_restore += handle_zone_restore with device.open(baudrate=BA...
def main()
Example application that periodically faults a virtual zone and then restores it. This is an advanced feature that allows you to emulate a virtual zone. When the AlarmDecoder is configured to emulate a zone expander we can fault and restore those zones programmatically at will. These events can also b...
5.172113
4.423184
1.169319
bytes_avail = 0 if isinstance(device, alarmdecoder.devices.SerialDevice): if hasattr(device._device, "in_waiting"): bytes_avail = device._device.in_waiting else: bytes_avail = device._device.inWaiting() elif isinstance(device, alarmdecoder.devices.SocketDevice):...
def bytes_available(device)
Determines the number of bytes available for reading from an AlarmDecoder device :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: int
2.962721
2.856852
1.037058
ub = None if sys.version_info > (3,): ub = buf else: ub = bytes(buf) return ub
def bytes_hack(buf)
Hacky workaround for old installs of the library on systems without python-future that were keeping the 2to3 update from working after auto-update.
4.428393
4.73752
0.934749
data_queue = deque() with open(file_path) as firmware_handle: for line in firmware_handle: line = line.rstrip() if line != '' and line[0] == ':': data_queue.append(line + "\r") return data_queue
def read_firmware_file(file_path)
Reads a firmware file into a dequeue for processing. :param file_path: Path to the firmware file :type file_path: string :returns: deque
3.595042
3.728991
0.964079
response = None bytes_avail = bytes_available(device) if isinstance(device, alarmdecoder.devices.SerialDevice): response = device._device.read(bytes_avail) elif isinstance(device, alarmdecoder.devices.SocketDevice): response = device._device.recv(bytes_a...
def read(device)
Reads data from the specified device. :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: string
4.548978
4.154282
1.095009
def progress_stage(stage, **kwargs): if progress_callback is not None: progress_callback(stage, **kwargs) return stage if device is None: raise NoDeviceError('No device specified for firmware upload.') fds = [device._d...
def upload(device, file_path, progress_callback=None, debug=False)
Uploads firmware to an `AlarmDecoder`_ device. :param file_path: firmware file path :type file_path: string :param progress_callback: callback function used to report progress :type progress_callback: function :raises: :py:class:`~alarmdecoder.util.NoDeviceError`, :py:class:`~a...
3.706622
3.730388
0.993629
try: # Start up the detection thread such that handle_attached and handle_detached will # be called when devices are attached and detached, respectively. USBDevice.start_detection(on_attached=handle_attached, on_detached=handle_detached) # Wait for events. while True: ...
def main()
Example application that shows how to handle attach/detach events generated by the USB devices. In this case we open the device and listen for messages when it is attached. And when it is detached we remove it from our list of monitored devices.
4.785231
3.965647
1.206671
device = AlarmDecoder(USBDevice.find(device_args)) device.on_message += handle_message device.open() return device
def create_device(device_args)
Creates an AlarmDecoder from the specified USB device arguments. :param device_args: Tuple containing information on the USB device to open. :type device_args: Tuple (vid, pid, serialnumber, interface_count, description)
10.7011
9.53476
1.122325
# Create the device from the specified device arguments. dev = create_device(device) __devices[dev.id] = dev print('attached', dev.id)
def handle_attached(sender, device)
Handles attached events from USBDevice.start_detection().
9.332635
9.090114
1.02668
vendor, product, sernum, ifcount, description = device # Close and remove the device from our list. if sernum in list(__devices.keys()): __devices[sernum].close() del __devices[sernum] print('detached', sernum)
def handle_detached(sender, device)
Handles detached events from USBDevice.start_detection().
8.804534
8.156449
1.079457
if errors != 'strict': raise UnicodeError('Unsupported error handling {0}'.format(errors)) unicode_string = cls._ensure_unicode_string(string) encoded = unicode_string.translate(cls._encoding_table) return encoded, len(string)
def encode(cls, string, errors='strict')
Return the encoded version of a string. :param string: The input string to encode. :type string: `basestring` :param errors: The error handling scheme. Only 'strict' is supported. :type errors: `basestring` :return: T...
4.401724
4.305021
1.022463
if errors != 'strict': raise UnicodeError('Unsupported error handling {0}'.format(errors)) unicode_string = cls._ensure_unicode_string(string) decoded = unicode_string.translate(cls._decoding_table) return decoded, len(string)
def decode(cls, string, errors='strict')
Return the decoded version of a string. :param string: The input string to decode. :type string: `basestring` :param errors: The error handling scheme. Only 'strict' is supported. :type errors: `basestring` :return: T...
4.390333
4.141298
1.060134
if encoding == cls._codec_name: return codecs.CodecInfo( name=cls._codec_name, encode=cls.encode, decode=cls.decode, ) return None
def search_function(cls, encoding)
Search function to find 'rotunicode' codec.
3.235448
2.818561
1.147908
if not isinstance(string, six.text_type): string = string.decode('utf-8') return string
def _ensure_unicode_string(string)
Returns a unicode string for string. :param string: The input string. :type string: `basestring` :returns: A unicode string. :rtype: `unicode`
2.676409
3.449601
0.77586
return dict( time=self.timestamp, mesg=self.raw, **kwargs )
def dict(self, **kwargs)
Dictionary representation.
9.236514
8.393692
1.100411
return Client(token).api(name, url, **kwargs)
def api(name, url, token, **kwargs)
Shortcut for caling methods on `Client(token, version)`.
6.871767
3.500697
1.962971
parser = argparse.ArgumentParser() parser.add_argument('api', help=) parser.add_argument('url', help=) parser.add_argument('token', help=) parser.add_argument('-a', '--all', help=, action='store_true') parser.add_argument('-f', '--file', help=) fields = text = html = None _args = pa...
def cli()
Command line tool.
2.543227
2.522133
1.008364
try: response = requests.get(url, params=params) response.raise_for_status() # If JSON fails, return raw data # (e.g. when downloading CSV job logs). try: return response.json() except ValueError: re...
def _get(url, params=None)
HTTP GET request.
3.787516
3.739614
1.012809
try: response = requests.post(url, params=params, data=data, headers={ 'Content-Type': content_type, }) response.raise_for_status() return response.json() except NameError: url = '{0}?{1}'.format(url, urllib.urlencode(p...
def _post(url, data, content_type, params=None)
HTTP POST request.
2.097636
2.118212
0.990286
if name not in self._apis: raise ValueError('API name must be one of {0}, not {1!r}.'.format( tuple(self._apis), name)) fields = kwargs.get('fields') timeout = kwargs.get('timeout') text = kwargs.get('text') html = kwargs.get('html') i...
def api(self, name, url, **kwargs)
Generic API method.
2.636617
2.615113
1.008223
# If multiple seed URLs are specified, join with whitespace. if isinstance(urls, list): urls = ' '.join(urls) url = self.endpoint('crawl') process_url = self.endpoint(api) params = { 'token': self._token, 'seeds': urls, 'na...
def crawl(self, urls, name='crawl', api='analyze', **kwargs)
Crawlbot API. Returns a diffbot.Job object to check and retrieve crawl status.
5.591208
5.161569
1.083238
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_lrr_message += handle_lrr_message with device.open(baudrate=BAUDRATE): while True: time....
def main()
Example application that prints messages from the panel to the terminal.
7.198679
6.780627
1.061654
print(sender, message.partition, message.event_type, message.event_data)
def handle_lrr_message(sender, message)
Handles message events from the AlarmDecoder.
8.284253
8.412453
0.984761
try: self._running = False self._read_thread.stop() self._device.close() except Exception: pass self.on_close()
def close(self)
Closes the device.
5.870713
5.228935
1.122736
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_alarm += handle_alarm with device.open(baudrate=BAUDRATE): while True: time.sleep(1) ...
def main()
Example application that sends an email when an alarm event is detected.
7.062552
6.571844
1.074668
zone = kwargs.pop('zone', None) text = "Alarm: Zone {0}".format(zone) # Build the email message msg = MIMEText(text) msg['Subject'] = SUBJECT msg['From'] = FROM_ADDRESS msg['To'] = TO_ADDRESS s = smtplib.SMTP(SMTP_SERVER) # Authenticate if needed if SMTP_USERNAME is not N...
def handle_alarm(sender, **kwargs)
Handles alarm events from the AlarmDecoder.
2.619272
2.608953
1.003956
try: _, values = data.split(':') values = values.split(',') # Handle older-format events if len(values) <= 3: self.event_data, self.partition, self.event_type = values self.version = 1 # Newer-format events ...
def _parse_message(self, data)
Parses the raw message from the device. :param data: message data to parse :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
3.659472
3.633587
1.007124
return dict( time = self.timestamp, event_data = self.event_data, event_type = self.event_type, partition = self.partition, report_code = self.report_code, event_prefix ...
def dict(self, **kwargs)
Dictionary representation
2.831516
2.798848
1.011672
try: # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000. ssl_device = SocketDevice(interface=('localhost', 10000)) # Enable SSL and set the certificates to be used. # # The key/cert attributes can either be a filesystem path or an X509/PKey ...
def main()
Example application that opens a device that has been exposed to the network with ser2sock and SSL encryption and authentication.
6.058118
5.246536
1.154689
rotu_fn = get_rotunicode_function_for_decode_argument(decode=decode) return map(rotu_fn, map(safe_unicode, stream_file_lines(io_object)))
def rotunicode(io_object, decode=False)
Rotate ASCII <-> non-ASCII characters in a file. :param io_object: The file object to convert. :type io_object: :class:`io.TextIOWrapper` :param decode: If True, perform a rotunicode-decode (rotate from non-ASCII to ASCII). Defaults to False (rotate from ASCII to non-ASCII)....
8.380215
8.71977
0.961059
if extension: file_name = string file_ext = '' else: file_name, file_ext = splitext(string) encoded_value, _ = _ROT_UNICODE.encode(file_name) return encoded_value + file_ext
def ruencode(string, extension=False)
Encode a string using 'rotunicode' codec. :param string: The input string to encode. :type string: `basestring` :param extension: True if the entire input string should be encoded. False to split the input string using :func:`os.path.splitext` and encode only the fi...
4.666654
3.909734
1.193599
string = safe_unicode(string) characters = [] i = 0 string_len = len(string) while i < string_len: character = string[i] if character == '\\': # Figure out the size of the escape sequence. Most escape sequences # are two characters (e.g. '\\' and 'n'), wi...
def parse_escape_sequences(string)
Parse a string for possible escape sequences. Sample usage: >>> parse_escape_sequences('foo\\nbar') 'foo\nbar' >>> parse_escape_sequences('foo\\\\u0256') 'foo\\u0256' :param string: Any string. :type string: `basestring` :raises: :class:`ValueError` if a backsla...
5.132413
5.003161
1.025834
if not have_pyftdi: raise ImportError('The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.') cls.__devices = [] query = cls.PRODUCT_IDS if vid and pid: query = [(vid, pid)] try: cls.__devices = Ftdi.fi...
def find_all(cls, vid=None, pid=None)
Returns all FTDI devices matching our vendor and product IDs. :returns: list of devices :raises: :py:class:`~alarmdecoder.util.CommError`
5.890548
5.990963
0.983239
if not have_pyftdi: raise ImportError('The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.') cls.find_all() if len(cls.__devices) == 0: raise NoDeviceError('No AD2USB devices present.') if device is None: devi...
def find(cls, device=None)
Factory method that returns the requested :py:class:`USBDevice` device, or the first device. :param device: Tuple describing the USB device to open, as returned by find_all(). :type device: tuple :returns: :py:class:`USBDevice` object utilizing the specified devi...
7.046736
8.047819
0.875608
if not have_pyftdi: raise ImportError('The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.') cls.__detect_thread = USBDevice.DetectThread(on_attached, on_detached) try: cls.find_all() except CommError: pass ...
def start_detection(cls, on_attached=None, on_detached=None)
Starts the device detection thread. :param on_attached: function to be called when a device is attached **Callback definition:** *def callback(thread, device)* :type on_attached: function :param on_detached: function to be called when a device is detached **Callback definition:** *def callbac...
6.207933
6.734703
0.921783
self._interface = value if isinstance(value, int): self._device_number = value else: self._serial_number = value
def interface(self, value)
Sets the interface used to connect to the device. :param value: may specify either the serial number or the device index :type value: string or int
4.318616
3.201752
1.348829
# Set up defaults if baudrate is None: baudrate = USBDevice.BAUDRATE self._read_thread = Device.ReadThread(self) # Open the device and start up the thread. try: self._device.open(self._vendor_id, self._product_id, ...
def open(self, baudrate=BAUDRATE, no_reader_thread=False)
Opens the device. :param baudrate: baudrate to use :type baudrate: int :param no_reader_thread: whether or not to automatically start the reader thread. :type no_reader_thread: bool :raises: :py:class:`~alarmdecoder.util.NoDeviceError`
3.299958
3.282226
1.005402
try: Device.close(self) # HACK: Probably should fork pyftdi and make this call in .close() self._device.usb_dev.attach_kernel_driver(self._device_number) except Exception: pass
def close(self)
Closes the device.
12.58391
11.463896
1.097699
try: self._device.write_data(data) self.on_write(data=data) except FtdiError as err: raise CommError('Error writing to device: {0}'.format(str(err)), err)
def write(self, data)
Writes data to the device. :param data: data to write :type data: string :raises: :py:class:`~alarmdecoder.util.CommError`
5.262862
4.842926
1.086711
ret = None try: ret = self._device.read_data(1) except (usb.core.USBError, FtdiError) as err: raise CommError('Error reading from device: {0}'.format(str(err)), err) return ret
def read(self)
Reads a single character from the device. :returns: character read from the device :raises: :py:class:`~alarmdecoder.util.CommError`
5.315615
5.123379
1.037521
def timeout_event(): timeout_event.reading = False timeout_event.reading = True if purge_buffer: self._buffer = b'' got_line, ret = False, None timer = threading.Timer(timeout, timeout_event) if timeout > 0: ti...
def read_line(self, timeout=0.0, purge_buffer=False)
Reads a line from the device. :param timeout: read timeout :type timeout: float :param purge_buffer: Indicates whether to purge the buffer prior to reading. :type purge_buffer: bool :returns: line that was read :raises: :py:class:`~alarmdeco...
3.480806
3.547509
0.981197
return usb.util.get_string(self._device.usb_dev, 64, self._device.usb_dev.iSerialNumber)
def _get_serial_number(self)
Retrieves the FTDI device serial number. :returns: string containing the device serial number
5.645425
7.716486
0.731606
if len(color) not in (3, 4, 6, 8): raise ValueError('bad color %s' % repr(color)) if len(color) in (3, 4): r = int(color[0], 16) * 0x11 g = int(color[1], 16) * 0x11 b = int(color[2], 16) * 0x11 elif len(color) in (6, 8): r = int(color[0:2], 16) g = int(co...
def parse_color(color)
Parse a color value. I've decided not to expect a leading '#' because it's a comment character in some shells. >>> parse_color('4bf') == (0x44, 0xbb, 0xff, 0xff) True >>> parse_color('ccce') == (0xcc, 0xcc, 0xcc, 0xee) True >>> parse_color('d8b4a2') == (0xd8, 0xb4, 0xa2...
1.489902
1.503131
0.991199
try: return parse_color(value) except ValueError: raise optparse.OptionValueError("option %s: invalid color value: %r" % (opt, value))
def check_color(option, opt, value)
Validate and convert an option value of type 'color'. ``option`` is an optparse.Option instance. ``opt`` is a string with the user-supplied option name (e.g. '--bgcolor'). ``value`` is the user-supplied value.
2.606649
3.228001
0.807512
w1, h1 = img1.size w2, h2 = img2.size size_a = (w1 + spacing + w2, max(h1, h2, 1)) size_b = (max(w1, w2, 1), h1 + spacing + h2) aspect_a = size_a[0] / size_a[1] aspect_b = size_b[0] / size_b[1] goodness_a = min(desired_aspect, aspect_a) / max(desired_aspect, aspect_a) goodness_b ...
def pick_orientation(img1, img2, spacing, desired_aspect=1.618)
Pick a tiling orientation for two images. Returns either 'lr' for left-and-right, or 'tb' for top-and-bottom. Picks the one that makes the combined image have a better aspect ratio, where 'better' is defined as 'closer to 1:1.618'.
1.973186
1.910105
1.033025
w1, h1 = img1.size w2, h2 = img2.size if opts.orientation == 'auto': opts.orientation = pick_orientation(img1, img2, opts.spacing) B, S = opts.border, opts.spacing if opts.orientation == 'lr': w, h = (B + w1 + S + w2 + B, B + max(h1, h2) + B) pos1 = (B, (h - h1) // 2)...
def tile_images(img1, img2, mask1, mask2, opts)
Combine two images into one by tiling them. ``mask1`` and ``mask2`` provide optional masks for alpha-blending; pass None to avoid. Fills unused areas with ``opts.bgcolor``. Puts a ``opts.spacing``-wide bar with a thin line of ``opts.sepcolor`` color between them. ``opts.orientation`` can be ...
1.988085
1.837782
1.081785
tempdir = tempfile.mkdtemp(prefix='imgdiff-') try: imgfile = os.path.join(tempdir, filename) img.save(imgfile) started = time.time() subprocess.call([viewer, imgfile]) elapsed = time.time() - started if elapsed < grace: # Program exited too quickl...
def spawn_viewer(viewer, img, filename, grace)
Launch an external program to view an image. ``img`` is an Image object. ``viewer`` is a command name. Arguments are not allowed; exactly one argument will be passed: the name of the image file. ``filename`` is the suggested filename for a temporary file. ``grace`` is the number of seconds to w...
4.279766
4.15461
1.030124
mask = diff.point(lambda i: opacity + i * (255 - opacity) // 255) return mask
def tweak_diff(diff, opacity)
Adjust a difference map into an opacity mask for a given lowest opacity. Performs a linear map from [0; 255] to [opacity; 255]. The result is that similar areas will have a given opacity, while dissimilar areas will be opaque.
7.583743
7.509122
1.009937
x1, y1 = x1y1 x2, y2 = x2y2 w1, h1 = img1.size w2, h2 = img2.size w, h = min(w1, w2), min(h1, h2) diff = ImageChops.difference(img1.crop((x1, y1, x1+w, y1+h)), img2.crop((x2, y2, x2+w, y2+h))) diff = diff.convert('L') return diff
def diff(img1, img2, x1y1, x2y2)
Compare two images with given alignments. Returns a difference map. ``x1y1``: a tuple ``(x1, y1)`` to specify the top-left corner of the aligned area with respect to ``img1``. ``x2y2``: a tuple ``(x2, y2)`` to specify the top-left corner of the aligned area with respect to ``img2``. Either `...
1.483607
1.746551
0.84945
# identical pictures = black image = return 0 # completely different pictures = white image = return lots return sum(i * n for i, n in enumerate(diff.histogram()))
def diff_badness(diff)
Estimate the "badness" value of a difference map. Returns 0 if the pictures are identical Returns a large number if the pictures are completely different (e.g. a black field and a white field). More specifically, returns ``255 * width * height`` where ``(width, height) == diff.size``. Returns so...
22.256142
15.091146
1.474781
w1, h1 = img1.size w2, h2 = img2.size w, h = min(w1, w2), min(h1, h2) best = None best_value = 255 * w * h + 1 xr = abs(w1 - w2) + 1 yr = abs(h1 - h2) + 1 p = Progress(xr * yr, timeout=opts.timeout) for x in range(xr): if w1 > w2: x1, x2 = x, 0 else...
def best_diff(img1, img2, opts)
Find the best alignment of two images that minimizes the differences. Returns (diff, alignments) where ``diff`` is a difference map, and ``alignments`` is a tuple ((x1, y2), (x2, y2)). See ``diff()`` for the description of the alignment numbers.
2.035697
2.059365
0.988507
try: diff, ((x1, y1), (x2, y2)) = best_diff(img1, img2, opts) except KeyboardInterrupt: return None, None diff = diff.filter(ImageFilter.MaxFilter(9)) diff = tweak_diff(diff, opts.opacity) # If the images have different sizes, the areas outside the alignment # zone are cons...
def simple_highlight(img1, img2, opts)
Try to align the two images to minimize pixel differences. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, finding the aligment that minimzes the differences, and then smoothing it a bit to reduce spurious matches in areas that are percept...
4.81249
4.576554
1.051553
w1, h1 = img1.size w2, h2 = img2.size W, H = max(w1, w2), max(h1, h2) pimg1 = Image.new('RGB', (W, H), opts.bgcolor) pimg2 = Image.new('RGB', (W, H), opts.bgcolor) pimg1.paste(img1, (0, 0)) pimg2.paste(img2, (0, 0)) diff = Image.new('L', (W, H), 255) # It is not a good idea t...
def slow_highlight(img1, img2, opts)
Try to find similar areas between two images. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, smoothing it a bit to reduce spurious matches in areas that are perceptibly different (e.g. text), and then taking the point-wise minimum of ...
2.233435
2.163947
1.032112
with maybe_gzip_open(path) as f: yield reader(f, broken=broken)
def open(path, broken=False)
Context manager for opening and reading json lines files. If file extension suggests gzip (.gz or .gzip), file is decompressed on fly. Pass broken=True if you expect the file can be truncated or broken otherwise; reader will try to recover as much data as possible in this case.
7.163176
7.163682
0.999929
if self.use_legacy_protocol : return '''{}<NickName>Socket 1</NickName><Description>Socket 1</Description> <OPStatus>{}</OPStatus><Controller>1</Controller>'''.format(self.moduleParameters(module), status) else: return '''{}<NickName>Socket 1</NickN...
def controlParameters(self, module, status)
Returns control parameters as XML. :type module: str :type status: str :param module: The module number/ID :param status: The state to set (i.e. true (on) or false (off)) :return XML string to join with payload
4.559317
4.250969
1.072536
# Authenticate client if self.authenticated is None: self.authenticated = self.auth() auth = self.authenticated #If not legacy protocol, ensure auth() is called for every call if not self.use_legacy_protocol: self.authenticated = None if ...
def SOAPAction(self, Action, responseElement, params = "", recursive = False)
Generate the SOAP action call. :type Action: str :type responseElement: str :type params: str :type recursive: bool :param Action: The action to perform on the device :param responseElement: The XML element that is returned upon success :param params: Any additio...
3.806651
3.772392
1.009081
try: response = urlopen(Request('http://{}/my_cgi.cgi'.format(self.ip), b'request=create_chklst')); except (HTTPError, URLError): _LOGGER.warning("Failed to open url to {}".format(self.ip)) self._error_report = True return None lines = re...
def fetchMyCgi(self)
Fetches statistics from my_cgi.cgi
5.346564
4.914417
1.087935
res = 'N/A' if self.use_legacy_protocol: # Use /my_cgi.cgi to retrieve current consumption try: res = self.fetchMyCgi()['Meter Watt'] except: return 'N/A' else: try: res = self.SOAPAction('Ge...
def current_consumption(self)
Get the current power consumption in Watt.
7.014627
6.440889
1.089077
if self.use_legacy_protocol: # TotalConsumption currently fails on the legacy protocol and # creates a mess in the logs. Just return 'N/A' for now. return 'N/A' res = 'N/A' try: res = self.SOAPAction("GetPMWarningThreshold", "TotalConsump...
def total_consumption(self)
Get the total power consumpuntion in the device lifetime.
8.674826
7.815532
1.109947
response = self.SOAPAction('GetSocketSettings', 'OPStatus', self.moduleParameters("1")) if response is None: return 'unknown' elif response.lower() == 'true': return ON elif response.lower() == 'false': return OFF else: _L...
def state(self)
Get the device state (i.e. ON or OFF).
9.037642
7.635244
1.183674
if value.upper() == ON: return self.SOAPAction('SetSocketSettings', 'SetSocketSettingsResult', self.controlParameters("1", "true")) elif value.upper() == OFF: return self.SOAPAction('SetSocketSettings', 'SetSocketSettingsResult', self.controlParameters("1", "false")) ...
def state(self, value)
Set device state. :type value: str :param value: Future state (either ON or OFF)
5.058387
4.58576
1.103064
payload = self.initial_auth_payload() # Build initial header headers = {'Content-Type' : '"text/xml; charset=utf-8"', 'SOAPAction': '"http://purenetworks.com/HNAP1/Login"'} # Request privatekey, cookie and challenge try: response = urlopen(Reque...
def auth(self)
Authenticate using the SOAP interface. Authentication is a two-step process. First a initial payload is sent to the device requesting additional login information in the form of a publickey, a challenge string and a cookie. These values are then hashed by a MD5 algorithm producing a pri...
2.921864
2.61632
1.116784
payload = '''<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <Login xmlns="http://purenetworks.com/HNAP1/...
def auth_payload(self, login_pwd)
Generate a new payload containing generated hash information. :type login_pwd: str :param login_pwd: hashed password generated by the auth function.
2.035194
2.105751
0.966493
buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else 0 return max(fp.tell() - buffer_size, 0)
def get_known_read_position(fp, buffered=True)
Return a position in a file which is known to be read & handled. It assumes a buffered file and streaming processing.
4.206192
3.611628
1.164625
# type: (gzip.GzipFile, int) -> gzip.GzipFile pos = get_recover_position(gzfile, last_good_position=last_good_position) if pos == -1: return None fp = gzfile.fileobj fp.seek(pos) # gzfile.close() return gzip.GzipFile(fileobj=fp, mode='r')
def recover(gzfile, last_good_position)
Skip to the next possibly decompressable part of a gzip file. Return a new GzipFile object if such part is found or None if it is not found.
2.717505
3.126707
0.869127
# type: (gzip.GzipFile, int) -> int with closing(mmap.mmap(gzfile.fileno(), 0, access=mmap.ACCESS_READ)) as m: return m.find(GZIP_SIGNATURE, last_good_position + 1)
def get_recover_position(gzfile, last_good_position)
Return position of a next gzip stream in a GzipFile, or -1 if it is not found. XXX: caller must ensure that the same last_good_position is not used multiple times for the same gzfile.
3.080963
3.483597
0.88442
path = path_to_str(path) if path.endswith('.gz') or path.endswith('.gzip'): _open = gzip.open else: _open = open return _open(path, *args, **kwargs)
def maybe_gzip_open(path, *args, **kwargs)
Open file with either open or gzip.open, depending on file extension. This function doesn't handle json lines format, just opens a file in a way it is decoded transparently if needed.
2.437962
2.699373
0.903159
try: from pathlib import Path as _Path except ImportError: # Python < 3.4 class _Path: pass if isinstance(path, _Path): return str(path) return path
def path_to_str(path)
Convert pathlib.Path objects to str; return other objects as-is.
3.258797
2.714462
1.200532
factors = self.get_factor_from_api() if not factors: return [] ml = [[int(x)] * y for x, y in factors] return [y for x in ml for y in x]
def get_factor_list(self)
get_factors: [['2', 3], ['3', 2]] Returns: [2, 2, 2, 3, 3]
5.625173
5.302951
1.060763
# Create a timestamp if one was not given if timestamp is None: timestamp = int(time.time()) # Construct the message from the timestamp and the data in the request message = str(timestamp) + ''.join("%s%s" % (k,v) for k,v in sorted(data.items())) # Calculate the signature (HMAC SHA256...
def calculate_signature(key, data, timestamp=None)
Calculates the signature for the given request data.
3.173738
3.118606
1.017679
if request.headers.get('Authorization') or request.args.get('access_token'): realm = 'Bearer realm="%s", error="invalid_token"' % __package__ else: realm = 'Bearer realm="%s"' % __package__ resp = Response(None, 401, {'WWW-Authenticate': realm}) abort(401...
def authenticate(self)
Indicate to the client that it needs to authenticate via a 401.
3.235099
2.95119
1.096202
resource_conf = config.DOMAIN[resource] audiences = resource_conf.get('audiences', config.JWT_AUDIENCES) return self._perform_verification(token, audiences, allowed_roles)
def check_token(self, token, allowed_roles, resource, method)
This function is called when a token is sent throught the access_token parameter or the Authorization header as specified in the oAuth 2 specification. The provided token is validated with the JWT_SECRET defined in the Eve configuration. The token issuer (iss claim) must be the one specified by...
5.88368
5.931281
0.991975
def requires_token_wrapper(f): @wraps(f) def decorated(*args, **kwargs): try: token = request.args['access_token'] except KeyError: token = request.headers.get('Authorization', '').partition(' ')[2] ...
def requires_token(self, audiences=None, allowed_roles=None)
Decorator for functions that will be protected with token authentication. Token must be provvided either through access_token parameter or Authorization header. See check_token() method for further details.
2.289288
2.276897
1.005442
paths = self.getpaths(libname) for path in paths: if os.path.exists(path): return self.load(path) raise ImportError("%s not found." % libname)
def load_library(self,libname)
Given the name of a library, load it.
3.437127
3.270337
1.051001
if os.path.isabs(libname): yield libname else: # FIXME / TODO return '.' and os.path.dirname(__file__) for path in self.getplatformpaths(libname): yield path path = ctypes.util.find_library(libname) if path: yield path
def getpaths(self,libname)
Return a list of paths where the library might be found.
5.214416
4.691929
1.111358
'''Implements the dylib search as specified in Apple documentation: http://developer.apple.com/documentation/DeveloperTools/Conceptual/ DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html Before commencing the standard search, the method first checks the bundle's `...
def getdirs(self,libname)
Implements the dylib search as specified in Apple documentation: http://developer.apple.com/documentation/DeveloperTools/Conceptual/ DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html Before commencing the standard search, the method first checks the bundle's ``Frameworks...
3.14839
1.910526
1.647918
if isinstance(content, QuerySet): json_serializer = serializers.get_serializer('json')() serialized_content = json_serializer.serialize(content, ensure_ascii=False, indent=indent) else: try: serialized_content = json.dumps(content, cls=DecimalEncoder, ensure_ascii=False,...
def to_json(content, indent=None)
Serializes a python object as JSON This method uses the DJangoJSONEncoder to to ensure that python objects such as Decimal objects are properly serialized. It can also serialize Django QuerySet objects.
2.321229
2.282965
1.016761
base_html_template = Template(''' <html> <head> {% if style %} <style type="text/css"> {{ style }} </style> {% endif %} </head> <body> {% if style %} ...
def to_html(data)
Serializes a python object as HTML This method uses the to_json method to turn the given data object into formatted JSON that is displayed in an HTML page. If pygments in installed, syntax highlighting will also be applied to the JSON.
2.71128
2.51178
1.079425
try: serialized_content = to_json(data, indent=4) except Exception, e: serialized_content = data return serialized_content
def to_text(data)
Serializes a python object as plain text If the data can be serialized as JSON, this method will use the to_json method to format the data, otherwise the data is returned as is.
4.588089
3.967589
1.156392
def actual_decorator(obj): def test_func(request, *args, **kwargs): secret_key = secret_key_func(request, *args, **kwargs) return validate_signature(request, secret_key) or request.user.is_authenticated() decorator = request_passes_test(test_func) return wrap_o...
def auth_required(secret_key_func)
Requires that the user be authenticated either by a signature or by being actively logged in.
3.415451
3.484254
0.980253
decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_authenticated()) return wrap_object(obj, decorator)
def login_required(obj)
Requires that the user be logged in order to gain access to the resource at the specified the URI.
6.501134
7.687925
0.845629
decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_superuser) return wrap_object(obj, decorator)
def admin_required(obj)
Requires that the user be logged AND be set as a superuser
6.473576
7.083418
0.913906
def actual_decorator(obj): def test_func(request, *args, **kwargs): secret_key = secret_key_func(request, *args, **kwargs) return validate_signature(request, secret_key) decorator = request_passes_test(test_func) return wrap_object(obj, decorator) return a...
def signature_required(secret_key_func)
Requires that the request contain a valid signature to gain access to a specified resource.
3.243273
3.418999
0.948603
# Extract the request parameters according to the HTTP method data = request.GET.copy() if request.method != 'GET': message_body = getattr(request, request.method, {}) data.update(message_body) # Make sure the request contains a signature if data.get('sig', False): sig...
def validate_signature(request, secret_key)
Validates the signature associated with the given request.
3.805778
3.89134
0.978012
def sample_wr(population, k): "Chooses k random elements (with replacement) from a population" n = len(population) _random, _int = random.random, int # speed hack result = [None] * k for i in xrange(k): j = _int(_random() * n) result[i] = population[j] return result
Chooses k random elements (with replacement) from a population
null
null
null
global _DYNAMODB_CONN global _BOTO_SESSION if not _DYNAMODB_CONN: logger.debug("Creating a DynamoDB connection.") if not _BOTO_SESSION: _BOTO_SESSION = Boto3Session( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS...
def dynamodb_connection_factory()
Since SessionStore is called for every single page view, we'd be establishing new connections so frequently that performance would be hugely impacted. We'll lazy-load this here on a per-worker basis. Since boto3.resource.('dynamodb')objects are state-less (aside from security tokens), we're not too conc...
2.106776
1.921984
1.096147
response = self.table.get_item( Key={'session_key': self.session_key}, ConsistentRead=ALWAYS_CONSISTENT) if 'Item' in response: session_data = response['Item']['data'] return self.decode(session_data) else: self.create() ...
def load(self)
Loads session data from DynamoDB, runs it through the session data de-coder (base64->dict), sets ``self.session``. :rtype: dict :returns: The de-coded session data, as a dict.
4.504034
3.513489
1.281926
response = self.table.get_item( Key={'session_key': session_key}, ConsistentRead=ALWAYS_CONSISTENT) if 'Item' in response: return True else: return False
def exists(self, session_key)
Checks to see if a session currently exists in DynamoDB. :rtype: bool :returns: ``True`` if a session with the given key exists in the DB, ``False`` if not.
3.62431
3.15481
1.14882
# If the save method is called with must_create equal to True, I'm # setting self._session_key equal to None and when # self.get_or_create_session_key is called the new # session_key will be created. if must_create: self._session_key = None self._ge...
def save(self, must_create=False)
Saves the current session data to the database. :keyword bool must_create: If ``True``, a ``CreateError`` exception will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). :raises: ``CreateError`` if ``must_create`...
3.527725
3.39252
1.039854
if session_key is None: if self.session_key is None: return session_key = self.session_key self.table.delete_item(Key={'session_key': session_key})
def delete(self, session_key=None)
Deletes the current session, or the one specified in ``session_key``. :keyword str session_key: Optionally, override the session key to delete.
2.754066
3.021646
0.911446
m = self txt = "%-34s (Bits: %5.2f MAP: %7.2f D: %5.3f %3d) E: %7.3f"%( m, m.totalbits, m.MAP, m.seeddist, m.seednum, nlog10(m.pvalue)) if m.binomial!=None: txt = txt + ' Bi: %6.2f'%(nlog10(m.binomial)) if m.church != None: txt = txt + ' ch: %6.2f'%(nlog10(m...
def summary(self)
m.summary() -- Return a text string one-line summary of motif and its metrics
2.897136
2.797446
1.035636
''' m.minimal_raw_seqs() -- Return minimal list of seqs that represent consensus ''' seqs = [[], []] for letter in self.oneletter: if one2two.has_key(letter): seqs[0].append(one2two[letter][0]) seqs[1].append(one2two[letter][1]) else: ...
def minimal_raw_seqs(self)
m.minimal_raw_seqs() -- Return minimal list of seqs that represent consensus
3.30938
2.54645
1.299605
letters = [] for i in range(self.width): downcase = None if self.bits[i] < 0.25: letters.append('.') continue if self.bits[i] < 1.0: downcase = 'True' tups = [(self.ll[i][x],x) for x in ACGT if self.ll[i][x] > 0.0] ...
def _compute_oneletter(self)
m._compute_oneletter() -- [utility] Set the oneletter member variable
4.126166
4.029567
1.023973
self.nseqs = len(LOS) self.width = len(LOS[0]) for i in range(self.width): Dc = {'A': 0, 'C': 0, 'T': 0, 'G': 0, 'N': 0} for seq in LOS: key = seq[i] Dc[key] = Dc[key] + 1 del(Dc['N']) self.counts.append(Dc)
def _parse_seqs(self, LOS)
m._parse_seqs(LOS) -- [utility] Build a matrix of counts from a list of sequences
2.585969
2.362828
1.094438
self.fracs = [] self.logP = [] self.ll = [] for i in range(self.width): Dll = {'A': 0, 'C': 0, 'T': 0, 'G': 0} Df = {'A': 0, 'C': 0, 'T': 0, 'G': 0} DlogP= {'A': 0, 'C': 0, 'T': 0, 'G': 0} for key in self.counts[i].keys(): ...
def _compute_ll(self)
m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix
2.933686
2.896078
1.012986
self.ll = ll self.width = len(ll) self._compute_bg_from_ll() self._compute_logP_from_ll() self._compute_ambig_ll() self._compute_bits() self._compute_oneletter() self._maxscore()
def compute_from_ll(self,ll)
m.compute_from_ll(ll) -- Build motif from an inputed log-likelihood matrix (This function reverse-calculates the probability matrix and background frequencies that were used to construct the log-likelihood matrix)
6.458108
6.569271
0.983078
P = [] for i in range(self.width): #print i, _p = {} for L in ACGT: _p[L] = math.pow(2.0,self.logP[i][L]) P.append(_p) #print self.P = P
def _computeP(self)
m._computeP() -- [utility] Compute the probability matrix (from the internal log-probability matrix)
5.824586
4.968872
1.172215
bits = [] totbits = 0 bgbits = 0 bg = self.background UNCERT = lambda x: x*math.log(x)/math.log(2.0) for letter in ACGT: bgbits = bgbits + UNCERT(bg[letter]) for i in range(self.width): tot = 0 for letter in ACGT...
def _compute_bits(self)
m._compute_bits() -- [utility] Set m.totbits to the number of bits and m.bits to a list of bits at each position
4.167584
3.878793
1.074454