desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Init the proxy, it will connect to the given url, using the given soap namespace. @param url: The url of the remote host to call @param prefix: The namespace prefix to use, eg. \'urn:schemas-upnp-org:service:WANIPConnection:1\''
def __init__(self, url, prefix):
logging.debug("Soap Proxy: '%s', prefix: '%s'", url, prefix) self._url = url self._prefix = prefix
'Call the given remote method with the given arguments, as keywords. Returns a deferred, called with SOAPpy structure representing the soap response. @param method: The method name to call, eg. \'GetExternalIP\' @param kwargs: The parameters of the call, as keywords @return: A deferred called with the external ip addre...
def call(self, method, **kwargs):
payload = SOAPpy.buildSOAP(method=method, config=Config, namespace=self._prefix, kw=kwargs) payload = payload.replace('SOAP-ENV', 's').replace('xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"', '').replace('SOAP-ENC:root="1"', '').replace('ns1', 'u') logging.debug('SOAP Payload:\n%s', payload)...
'The http POST command was successful, we parse the SOAP answer, and return it. @param result: the xml content'
def _got_page(self, result):
parsed = SOAPpy.parseSOAPRPC(result) logging.debug('SOAP Answer:\n%s', result) logging.debug('SOAP Parsed Answer: %r', parsed) return parsed
'The HTTP POST command did not succeed, depending on the error type: - it\'s a SOAP error, we parse it and return a L{SoapError}. - it\'s another type of error (http, other), we raise it as is'
def _got_error(self, res):
logging.debug('SOAP Error:\n%s', res) if isinstance(res.value, error.Error): try: logging.debug('SOAP Error content:\n%s', res.value.response) raise SoapError(SOAPpy.parseSOAPRPC(res.value.response)['detail']) except: raise raise Exception(res.val...
'Creates the mapper, with the given L{UPnPDevice} instance. @param upnp: L{UPnPDevice} instance'
def __init__(self, upnp):
self._mapped = {} self._upnp = upnp
'See interface'
def map(self, port):
self._check_valid_port(port) if (port in self._mapped): return defer.succeed(self._mapped[port]) result = ipdiscover.get_local_ip() self._mapped[port] = result return result.addCallback(self._map_got_local_ip, port)
'See interface'
def info(self, port):
if (port in self._mapped): return self._mapped[port] else: raise ValueError(('Port %r is not currently mapped' % port))
'See interface'
def unmap(self, port):
if (port in self._mapped): existing = self._mapped[port] if (type(existing) is not tuple): existing.addCallback((lambda x: self.unmap(port))) return existing del self._mapped[port] (extaddr, extport) = existing return self._upnp.remove_port_mapping(ext...
'See interface'
def get_port_mappings(self):
return self._upnp.get_port_mappings()
'We got the local ip address, retreive the existing port mappings in the device. @param ip_result: result of L{ipdiscover.get_local_ip} @param port: a L{twisted.internet.interfaces.IListeningPort} we want to map'
def _map_got_local_ip(self, ip_result, port):
(local, ip) = ip_result return self._upnp.get_port_mappings().addCallback(self._map_got_port_mappings, ip, port)
'We got all the existing mappings in the device, find an unused one and assign it for the requested port. @param ip: The local ip of this host "x.x.x.x" @param port: a L{twisted.internet.interfaces.IListeningPort} we want to map @param mappings: result of L{UPnPDevice.get_port_mappings}'
def _map_got_port_mappings(self, mappings, ip, port):
ptype = port.getHost().type intport = port.getHost().port for extport in [random.randrange(1025, 65536) for val in range(20)]: if (not ((ptype, extport) in mappings)): break if ((ptype, extport) in mappings): existing = mappings[(ptype, extport)] (local_ip, lo...
'The port mapping was added in the device, this means:: Internet NAT LAN > IP:extaddr |> IP:local ip > Port:extport |> Port:port @param extaddr: The exernal ip address @param extport: The external port as number @param port: The internal port as a L{twisted.internet.interfaces.IList...
def _port_mapping_added(self, extaddr, extport, port):
self._mapped[port] = (extaddr, extport) return (extaddr, extport)
'Build the device, with the given SOAP proxy, and the meta-infos. @param soap_proxy: an initialized L{SoapProxy} to the device @param info: a dictionnary of various infos concerning the device extracted with L{UPnPXml}'
def __init__(self, soap_proxy, info):
self._soap_proxy = soap_proxy self._info = info
'Triggers an external ip discovery on the upnp device. Returns a deferred called with the external ip of this host. @return: A deferred called with the ip address, as "x.x.x.x" @rtype: L{twisted.internet.defer.Deferred}'
def get_external_ip(self):
result = self._soap_proxy.call('GetExternalIPAddress') result.addCallback(self._on_external_ip) return result
'Retreive the existing port mappings @see: L{portmapper.NATMapper.get_port_mappings} @return: A deferred called with the dictionnary as defined in the interface L{portmapper.NATMapper.get_port_mappings} @rtype: L{twisted.internet.defer.Deferred}'
def get_port_mappings(self):
return self._get_port_mapping()
'Add a port mapping in the upnp device. Returns a deferred. @param local_ip: the LAN ip of this host as "x.x.x.x" @param intport: the internal port number @param extport: the external port number @param desc: the description of this mapping (string) @param proto: "UDP" or "TCP" @param lease: The duration of the lease i...
def add_port_mapping(self, local_ip, intport, extport, desc, proto, lease=0):
result = self._soap_proxy.call('AddPortMapping', NewRemoteHost='', NewExternalPort=extport, NewProtocol=proto, NewInternalPort=intport, NewInternalClient=local_ip, NewEnabled=1, NewPortMappingDescription=desc, NewLeaseDuration=lease) return result.addCallbacks(self._on_port_mapping_added, self._on_no_port_mappi...
'Remove an existing port mapping on the device. Returns a deferred @param extport: the external port number associated to the mapping to be removed @param proto: either "UDP" or "TCP" @return: A deferred called with None when the mapping is done @rtype: L{twisted.internet.defer.Deferred}'
def remove_port_mapping(self, extport, proto):
result = self._soap_proxy.call('DeletePortMapping', NewRemoteHost='', NewExternalPort=extport, NewProtocol=proto) return result.addCallbacks(self._on_port_mapping_removed, self._on_no_port_mapping_removed)
'Called when we received the external ip address from the device. @param res: the SOAPpy structure of the result @return: the external ip string, as "x.x.x.x"'
def _on_external_ip(self, res):
logging.debug('Got external ip struct: %r', res) return res['NewExternalIPAddress']
'Fetch the existing mappings starting at index "mapping_id" from the device. To retreive all the mappings call this without parameters. @param mapping_id: The index of the mapping to start fetching from @param mappings: the dictionnary of already fetched mappings @return: A deferred called with the existing mappings wh...
def _get_port_mapping(self, mapping_id=0, mappings=None):
if (mappings == None): mappings = {} result = self._soap_proxy.call('GetGenericPortMappingEntry', NewPortMappingIndex=mapping_id) return result.addCallbacks((lambda x: self._on_port_mapping_received(x, (mapping_id + 1), mappings)), (lambda x: self._on_no_port_mapping_received(x, mappings)))
'Called we we receive a single mapping from the device. @param response: a SOAPpy structure, representing the device\'s answer @param mapping_id: The index of the next mapping in the device @param mappings: the already fetched mappings, see L{get_port_mappings} @return: A deferred called with the existing mappings when...
def _on_port_mapping_received(self, response, mapping_id, mappings):
logging.debug('Got mapping struct: %r', response) mappings[(response['NewProtocol'], response['NewExternalPort'])] = (response['NewInternalClient'], response['NewInternalPort']) return self._get_port_mapping(mapping_id, mappings)
'Called when we have no more port mappings to retreive, or an error occured while retreiving them. Either we have a "SpecifiedArrayIndexInvalid" SOAP error, and that\'s ok, it just means we have finished. If it returns some other error, then we fail with an UPnPError. @param mappings: the already retreived mappings @pa...
def _on_no_port_mapping_received(self, failure, mappings):
logging.debug('_on_no_port_mapping_received: %s', failure) err = failure.value message = err.args[0]['UPnPError']['errorDescription'] if ('SpecifiedArrayIndexInvalid' == message): return mappings else: return failure
'The port mapping was successfully added, return None to the deferred.'
def _on_port_mapping_added(self, response):
return None
'Called when the port mapping could not be added. Immediately raise an UPnPError, with the SOAPpy structure inside. @raise UPnPError: When the port mapping could not be added'
def _on_no_port_mapping_added(self, failure):
return failure
'The port mapping was successfully removed, return None to the deferred.'
def _on_port_mapping_removed(self, response):
return None
'Called when the port mapping could not be removed. Immediately raise an UPnPError, with the SOAPpy structure inside. @raise UPnPError: When the port mapping could not be deleted'
def _on_no_port_mapping_removed(self, failure):
return failure
'Init the protocol, no parameters needed.'
def __init__(self, *args, **kwargs):
super(UPnPProtocol, self).__init__(*args, **kwargs) self._discovery = None self._discovery_timeout = None self.mcast = None self._done = False
'Triggers a UPnP device discovery. The returned deferred will be called with the L{UPnPDevice} that has been found in the LAN. @return: A deferred called with the detected L{UPnPDevice} instance. @rtype: L{twisted.internet.defer.Deferred}'
def search_device(self):
if (self._discovery is not None): raise ValueError('already used') self._discovery = defer.Deferred() self._discovery_timeout = reactor.callLater(6, self._on_discovery_timeout) attempt = 0 mcast = None while True: try: self.mcast = reactor.listenMulticast((1900 + a...
'Returns (orphans, doas), total, (orphans_recorded_in_chain, doas_recorded_in_chain)'
def get_stale_counts(self):
my_shares = len(self.my_share_hashes) my_doa_shares = len(self.my_doa_share_hashes) delta = self.tracker_view.get_delta_to_last(self.node.best_share_var.value) my_shares_in_chain = (delta.my_count + self.removed_unstales_var.value[0]) my_doa_shares_in_chain = (delta.my_doa_count + self.removed_doa_u...
'Updates expiry node, optionally replacing value, returning new value'
def touch(self, key, value=_nothing):
if ((value is self._nothing) or (key in self.d)): (node, old_value) = self.d[key] node.delete() new_value = (old_value if (value is self._nothing) else value) self.d[key] = (self.expiry_deque.append(((time.time() + self.expiry_time), key)), new_value) return new_value
'conditions的栌匏是䞪字兞。类䌌self.params :param conditions: :param value:也是䞪字兞{\'ip\':192.168.0.1} :return:'
def update(self, conditions=None, value=None):
if (conditions and value): conditon_list = [] for key in list(conditions.keys()): if self.params.get(key, None): conditon_list.append((self.params.get(key) == conditions.get(key))) conditions = conditon_list query = self.session.query(Proxy) for co...
'conditions的栌匏是䞪字兞。类䌌self.params :param count: :param conditions: :return:'
def select(self, count=None, conditions=None):
if conditions: conditon_list = [] for key in list(conditions.keys()): if self.params.get(key, None): conditon_list.append((self.params.get(key) == conditions.get(key))) conditions = conditon_list else: conditions = [] query = self.session.query(Pro...
''
def do_GET(self):
print self.path parsed_path = urlparse.urlparse(self.path) print parsed_path print parsed_path.query data1 = ([{'ip': '192.168.0.0', 'port': 456}] * 10) d1 = json.dumps(data1, sort_keys=True, indent=4) message = ('192.168.1.1', 80) self.send_response(200) self.end_headers...
':param response: 响应 :param type: 解析方匏 :return:'
def parse(self, response, parser):
if (parser['type'] == 'xpath'): return self.XpathPraser(response, parser) elif (parser['type'] == 'regular'): return self.RegularPraser(response, parser) elif (parser['type'] == 'module'): return getattr(self, parser['moduleName'], None)(response, parser) else: return Non...
':param addr: :return:'
def AuthCountry(self, addr):
for area in CHINA_AREA: if (text_(area) in addr): return True return False
'针对xpath方匏进行解析 :param response: :param parser: :return:'
def XpathPraser(self, response, parser):
proxylist = [] root = etree.HTML(response) proxys = root.xpath(parser['pattern']) for proxy in proxys: try: ip = proxy.xpath(parser['position']['ip'])[0].text port = proxy.xpath(parser['position']['port'])[0].text type = 0 protocol = 0 ...
':param response: :param parser: :return:'
def RegularPraser(self, response, parser):
proxylist = [] pattern = re.compile(parser['pattern']) matchs = pattern.findall(response) if (matchs != None): for match in matchs: try: ip = match[parser['position']['ip']] port = match[parser['position']['port']] type = 0 ...
'Successfully issue a certificate via common name'
def test_success_cn(self):
old_stdout = sys.stdout sys.stdout = StringIO() result = acme_tiny.main(['--account-key', KEYS['account_key'].name, '--csr', KEYS['domain_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA]) sys.stdout.seek(0) crt = sys.stdout.read().encode('utf8') sys.stdout = old_stdout (out, err) = P...
'Successfully issue a certificate via subject alt name'
def test_success_san(self):
old_stdout = sys.stdout sys.stdout = StringIO() result = acme_tiny.main(['--account-key', KEYS['account_key'].name, '--csr', KEYS['san_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA]) sys.stdout.seek(0) crt = sys.stdout.read().encode('utf8') sys.stdout = old_stdout (out, err) = Pope...
'Successfully issue a certificate via command line interface'
def test_success_cli(self):
(crt, err) = Popen(['python', 'acme_tiny.py', '--account-key', KEYS['account_key'].name, '--csr', KEYS['domain_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA], stdout=PIPE, stderr=PIPE).communicate() (out, err) = Popen(['openssl', 'x509', '-text', '-noout'], stdin=PIPE, stdout=PIPE, stderr=PIPE).commun...
'OpenSSL throws an error when the account key is missing'
def test_missing_account_key(self):
try: result = acme_tiny.main(['--account-key', '/foo/bar', '--csr', KEYS['domain_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA]) except Exception as e: result = e self.assertIsInstance(result, IOError) self.assertIn('Error opening Private Key', result.args[0])
'OpenSSL throws an error when the CSR is missing'
def test_missing_csr(self):
try: result = acme_tiny.main(['--account-key', KEYS['account_key'].name, '--csr', '/foo/bar', '--acme-dir', self.tempdir, '--ca', self.CA]) except Exception as e: result = e self.assertIsInstance(result, IOError) self.assertIn('Error loading /foo/bar', result.args[0])
'Let\'s Encrypt rejects weak keys'
def test_weak_key(self):
try: result = acme_tiny.main(['--account-key', KEYS['weak_key'].name, '--csr', KEYS['domain_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA]) except Exception as e: result = e self.assertIsInstance(result, ValueError) self.assertIn('key too small', result.args[0])
'Let\'s Encrypt rejects invalid domains'
def test_invalid_domain(self):
try: result = acme_tiny.main(['--account-key', KEYS['account_key'].name, '--csr', KEYS['invalid_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA]) except Exception as e: result = e self.assertIsInstance(result, ValueError) self.assertIn('Invalid character in DNS name',...
'Should be unable verify a nonexistent domain'
def test_nonexistant_domain(self):
try: result = acme_tiny.main(['--account-key', KEYS['account_key'].name, '--csr', KEYS['nonexistent_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA]) except Exception as e: result = e self.assertIsInstance(result, ValueError) self.assertIn("but couldn't download", result.ar...
'Can\'t use the account key for the CSR'
def test_account_key_domain(self):
try: result = acme_tiny.main(['--account-key', KEYS['account_key'].name, '--csr', KEYS['account_csr'].name, '--acme-dir', self.tempdir, '--ca', self.CA]) except Exception as e: result = e self.assertIsInstance(result, ValueError) self.assertIn('certificate public key must be ...
'Remove the contents of all top-level curly brace pairs {}.'
def collapse_braces(self, src):
result = [] nesting = 0 for c in src: if (not nesting): result.append(c) if (c == '{'): nesting += 1 elif (c == '}'): nesting -= 1 result.append(c) return ''.join(result)
'Strips comments, pre-processor directives, single- and double-quoted strings from a string.'
def strip(self, src):
p = "('.')" p += '|("(?:[^"\\\\]|\\\\.)*")' p += '|(//.*?$)|(/\\*[^*]*(?:\\*(?!/)[^*]*)*\\*/)' p += ('|' + '(^\\s*#.*?$)') regex = re.compile(p, re.MULTILINE) return regex.sub(' ', src)
'Search for file-system entry with any name passed in `items` on all paths provided in `places`. Use `key` as a cache key. If `join` is True result will be a path join of place/item, otherwise only place is taken as result. Return first found match unless `multi` is True. In that case a list with all fount matches is r...
def _find(self, key, items, places, human_name, join, multi):
if (key in self): return self[key] human_name = (human_name or key) places = itertools.chain.from_iterable((os.path.expandvars(p).split(os.pathsep) for p in places)) places = map(os.path.expanduser, places) glob_places = itertools.chain.from_iterable((glob(p) for p in places)) print 'Sea...
'For `dirname_parts` like [a, b, c] return list of search paths within Arduino distribution directory like: /user/specified/path/a/b/c /usr/local/share/arduino/a/b/c /usr/share/arduino/a/b/c'
def arduino_dist_places(self, dirname_parts):
if ('arduino_dist_dir' in self): places = [self['arduino_dist_dir']] else: places = self.arduino_dist_dir_guesses return [os.path.join(p, *dirname_parts) for p in places]
'Initialize validation with empty results. Args: model [PredictableModel] The model, which is going to be validated.'
def __init__(self, model):
if (not isinstance(model, PredictableModel)): raise TypeError('Validation can only validate the type PredictableModel.') self.model = model self.validation_results = []
'Args: X [list] Input Images y [y] Class Labels description [string] experiment description'
def validate(self, X, y, description):
raise NotImplementedError('Every Validation module must implement the validate method!')
'Args: k [int] number of folds in this k-fold cross-validation (default 10)'
def __init__(self, model, k=10):
super(KFoldCrossValidation, self).__init__(model=model) self.k = k self.logger = logging.getLogger('facerec.validation.KFoldCrossValidation')
'Performs a k-fold cross validation Args: X [dim x num_data] input data to validate on y [1 x num_data] classes'
def validate(self, X, y, description='ExperimentName'):
(X, y) = shuffle(X, y) c = len(np.unique(y)) foldIndices = [] n = np.iinfo(np.int).max for i in range(0, c): idx = np.where((y == i))[0] n = min(n, idx.shape[0]) foldIndices.append(idx.tolist()) if (n < self.k): self.k = n foldSize = int(math.floor((n / self.k...
'Intialize Cross-Validation module. Args: model [Model] model for this validation'
def __init__(self, model):
super(LeaveOneOutCrossValidation, self).__init__(model=model) self.logger = logging.getLogger('facerec.validation.LeaveOneOutCrossValidation')
'Performs a LOOCV. Args: X [dim x num_data] input data to validate on y [1 x num_data] classes'
def validate(self, X, y, description='ExperimentName'):
(true_positives, false_positives, true_negatives, false_negatives) = (0, 0, 0, 0) n = y.shape[0] for i in range(0, n): self.logger.info(('Processing fold %d/%d.' % ((i + 1), n))) trainIdx = [] trainIdx.extend(range(0, i)) trainIdx.extend(range((i + 1), n)) Xtrai...
'Intialize Cross-Validation module. Args: model [Model] model for this validation'
def __init__(self, model):
super(LeaveOneClassOutCrossValidation, self).__init__(model=model) self.logger = logging.getLogger('facerec.validation.LeaveOneClassOutCrossValidation')
'TODO Add example and refactor into proper interface declaration.'
def validate(self, X, y, g, description='ExperimentName'):
(true_positives, false_positives, true_negatives, false_negatives) = (0, 0, 0, 0) for i in range(0, len(np.unique(y))): self.logger.info(('Validating Class %s.' % i)) trainIdx = np.where((y != i))[0] testIdx = np.where((y == i))[0] Xtrain = [X[t] for t in trainIdx] ...
'Args: model [PredictableModel] model to perform the validation on'
def __init__(self, model):
super(SimpleValidation, self).__init__(model=model) self.logger = logging.getLogger('facerec.validation.SimpleValidation')
'Performs a validation given training data and test data. User is responsible for non-overlapping assignment of indices. Args: X [dim x num_data] input data to validate on y [1 x num_data] classes'
def validate(self, Xtrain, ytrain, Xtest, ytest, description='ExperimentName'):
self.logger.info('Simple Validation.') self.model.compute(Xtrain, ytrain) self.logger.debug('Model computed.') (true_positives, false_positives, true_negatives, false_negatives) = (0, 0, 0, 0) count = 0 for i in ytest: self.logger.debug(('Predicting %s/%s.' % (count, len(ytest))...
'Updates the classifier.'
def update(self, X, y):
self.X.append(X) self.y = np.append(self.y, y)
'Predicts the k-nearest neighbor for a given query in q. Args: q: The given query sample, which is an array. Returns: A list with the classifier output. In this framework it is assumed, that the predicted class is always returned as first element. Moreover, this class returns the distances for the first k-Nearest Neigh...
def predict(self, q):
distances = [] for xi in self.X: xi = xi.reshape((-1), 1) d = self.dist_metric(xi, q) distances.append(d) if (len(distances) > len(self.y)): raise Exception('More distances than classes. Is your distance metric correct?') distances = np.asarray(dis...
'Args: X: The query image, which is an array. Returns: A list with the classifier output. In this framework it is assumed, that the predicted class is always returned as first element. Moreover, this class returns the libsvm output for p_labels, p_acc and p_vals. The libsvm help states: p_labels: a list of predicted la...
def predict(self, X):
X = np.asarray(X).reshape(1, (-1)) results = self.svm.predict_proba(X)[0] results_ordered_by_probability = map((lambda x: x[0]), sorted(zip(self.svm.classes_, results), key=(lambda x: x[1]), reverse=True)) predicted_label = int(results_ordered_by_probability[0]) return [predicted_label, {'results': ...
'convert self.lay to variables & placeholders'
def convert(self, feed):
for var in self.lay.wshape: self.wrap_variable(var) for ph in self.lay.h: self.wrap_pholder(ph, feed)
'wrap layer.w into variables'
def wrap_variable(self, var):
val = self.lay.w.get(var, None) if (val is None): shape = self.lay.wshape[var] args = [0.0, 0.01, shape] if ('moving_mean' in var): val = np.zeros(shape) elif ('moving_variance' in var): val = np.ones(shape) else: val = np.random.normal...
'wrap layer.h into placeholders'
def wrap_pholder(self, ph, feed):
phtype = type(self.lay.h[ph]) if (phtype is not dict): return sig = '{}/{}'.format(self.scope, ph) val = self.lay.h[ph] self.lay.h[ph] = tf.placeholder_with_default(val['dfault'], val['shape'], name=sig) feed[self.lay.h[ph]] = val['feed']
'Create a standalone const graph def that C++ can load and run.'
def savepb(self):
darknet_pb = self.to_darknet() flags_pb = self.FLAGS flags_pb.verbalise = False flags_pb.train = False tfnet_pb = TFNet(flags_pb, darknet_pb) tfnet_pb.sess = tf.Session(graph=tfnet_pb.graph) name = 'built_graph/{}.pb'.format(self.meta['name']) os.makedirs(os.path.dirname(name), exist_ok=...
'analyse FLAGS.load to know where is the source binary and what is its config. can be: None, FLAGS.model, or some other'
def get_weight_src(self, FLAGS):
self.src_bin = (FLAGS.model + self._EXT) self.src_bin = (FLAGS.binary + self.src_bin) self.src_bin = os.path.abspath(self.src_bin) exist = os.path.isfile(self.src_bin) if (FLAGS.load == str()): FLAGS.load = int() if (type(FLAGS.load) is int): self.src_cfg = FLAGS.model if...
'return a list of `layers` objects (darkop.py) given path to binaries/ and configs/'
def parse_cfg(self, model, FLAGS):
args = [model, FLAGS.binary] cfg_layers = cfg_yielder(*args) meta = dict() layers = list() for (i, info) in enumerate(cfg_layers): if (i == 0): meta = info continue else: new = create_darkop(*info) layers.append(new) return (meta, layer...
'Use `layers` and Loader to load .weights file'
def load_weights(self):
print 'Loading {} ...'.format(self.src_bin) start = time.time() args = [self.src_bin, self.src_layers] wgts_loader = loader.create_loader(*args) for layer in self.layers: layer.load(wgts_loader) stop = time.time() print 'Finished in {}s'.format((stop - start))
'deal with darknet'
def finalize(self, _):
kernel = self.w['kernel'] if (kernel is None): return kernel = kernel.reshape(self.dnshape) kernel = kernel.transpose([2, 3, 1, 0]) self.w['kernel'] = kernel
'regression tests for parsing output from GNU date(1)'
def test_gnu_date(self):
assertEqual(self.parser.parse_iso(u'2016-11-16T09:46:30,895636557-0800'), datetime(2016, 11, 16, 9, 46, 30, 895636, tzinfo=tz.tzoffset(None, ((-3600) * 8)))) assertEqual(self.parser.parse_iso(u'2016-11-16 09:51:14.682141526-08:00'), datetime(2016, 11, 16, 9, 51, 14, 682142, tzinfo=tz.tzoffset(None, ((-3600) ...
'Describes a delta within a timeframe in plain language. :param timeframe: a string representing a timeframe. :param delta: a quantity representing a delta in a timeframe. :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords'
def describe(self, timeframe, delta=0, only_distance=False):
humanized = self._format_timeframe(timeframe, delta) if (not only_distance): humanized = self._format_relative(humanized, timeframe, delta) return humanized
'Returns the day name for a specified day of the week. :param day: the ``int`` day of the week (1-7).'
def day_name(self, day):
return self.day_names[day]
'Returns the day abbreviation for a specified day of the week. :param day: the ``int`` day of the week (1-7).'
def day_abbreviation(self, day):
return self.day_abbreviations[day]
'Returns the month name for a specified month of the year. :param month: the ``int`` month of the year (1-12).'
def month_name(self, month):
return self.month_names[month]
'Returns the month abbreviation for a specified month of the year. :param month: the ``int`` month of the year (1-12).'
def month_abbreviation(self, month):
return self.month_abbreviations[month]
'Returns the month number for a month specified by name or abbreviation. :param name: the month name or abbreviation.'
def month_number(self, name):
if (self._month_name_to_ordinal is None): self._month_name_to_ordinal = self._name_to_ordinal(self.month_names) self._month_name_to_ordinal.update(self._name_to_ordinal(self.month_abbreviations)) return self._month_name_to_ordinal.get(name)
'Returns the year for specific locale if available :param name: the ``int`` year (4-digit)'
def year_full(self, year):
return u'{0:04d}'.format(year)
'Returns the year for specific locale if available :param name: the ``int`` year (4-digit)'
def year_abbreviation(self, year):
return u'{0:04d}'.format(year)[2:]
'Returns the meridian indicator for a specified hour and format token. :param hour: the ``int`` hour of the day. :param token: the format token.'
def meridian(self, hour, token):
if (token == u'a'): return (self.meridians[u'am'] if (hour < 12) else self.meridians[u'pm']) if (token == u'A'): return (self.meridians[u'AM'] if (hour < 12) else self.meridians[u'PM'])
'Returns the ordinal format of a given integer :param n: an integer'
def ordinal_number(self, n):
return self._ordinal_number(n)
'Czech aware time frame format function, takes into account the differences between past and future forms.'
def _format_timeframe(self, timeframe, delta):
form = self.timeframes[timeframe] if isinstance(form, dict): if (delta == 0): form = form[u'zero'] elif (delta > 0): form = form[u'future'] else: form = form[u'past'] delta = abs(delta) if isinstance(form, list): if ((2 <= (delta % 10) ...
'Slovak aware time frame format function, takes into account the differences between past and future forms.'
def _format_timeframe(self, timeframe, delta):
form = self.timeframes[timeframe] if isinstance(form, dict): if (delta == 0): form = form[u'zero'] elif (delta > 0): form = form[u'future'] else: form = form[u'past'] delta = abs(delta) if isinstance(form, list): if ((2 <= (delta % 10) ...
'Hebrew couple of <timeframe> aware'
def _format_timeframe(self, timeframe, delta):
couple = u'2-{0}'.format(timeframe) if ((abs(delta) == 2) and (couple in self.timeframes)): return self.timeframes[couple].format(abs(delta)) else: return self.timeframes[timeframe].format(abs(delta))
'Thai always use Buddhist Era (BE) which is CE + 543'
def year_full(self, year):
year += self.BE_OFFSET return u'{0:04d}'.format(year)
'Thai always use Buddhist Era (BE) which is CE + 543'
def year_abbreviation(self, year):
year += self.BE_OFFSET return u'{0:04d}'.format(year)[2:]
'Thai normally doesn\'t have any space between words'
def _format_relative(self, humanized, timeframe, delta):
if (timeframe == u'now'): return humanized space = (u'' if (timeframe == u'seconds') else u' ') direction = (self.past if (delta < 0) else self.future) return direction.format(humanized, space)
'Returns an :class:`Arrow <arrow.arrow.Arrow>` object based on flexible inputs. :param locale: (optional) a ``str`` specifying a locale for the parser. Defaults to \'en_us\'. :param tzinfo: (optional) a :ref:`timezone expression <tz-expr>` or tzinfo object. Replaces the timezone unless using an input form that is expli...
def get(self, *args, **kwargs):
arg_count = len(args) locale = kwargs.get('locale', 'en_us') tz = kwargs.get('tzinfo', None) if (arg_count == 0): if isinstance(tz, tzinfo): return self.type.now(tz) return self.type.utcnow() if (arg_count == 1): arg = args[0] if (arg is None): ...
'Returns an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in UTC time. Usage:: >>> import arrow >>> arrow.utcnow() <Arrow [2013-05-08T05:19:07.018993+00:00]>'
def utcnow(self):
return self.type.utcnow()
'Returns an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in the given timezone. :param tz: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to local time. Usage:: >>> import arrow >>> arrow.now() <Arrow [2013-05-07T22:19:11.363410-07:00]> >>> arrow.now(\'US/Pacific\') <Arrow [2013-05-07T22:...
def now(self, tz=None):
if (tz is None): tz = dateutil_tz.tzlocal() elif (not isinstance(tz, tzinfo)): tz = parser.TzinfoParser.parse(tz) return self.type.now(tz)
'Constructs an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in the given timezone. :param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time.'
@classmethod def now(cls, tzinfo=None):
utc = datetime.utcnow().replace(tzinfo=dateutil_tz.tzutc()) dt = utc.astimezone((dateutil_tz.tzlocal() if (tzinfo is None) else tzinfo)) return cls(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
'Constructs an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in UTC time.'
@classmethod def utcnow(cls):
dt = datetime.utcnow() return cls(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dateutil_tz.tzutc())
'Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a timestamp, converted to the given timezone. :param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either. :param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time. Timestamps should always be UTC. If you have a no...
@classmethod def fromtimestamp(cls, timestamp, tzinfo=None):
tzinfo = (tzinfo or dateutil_tz.tzlocal()) timestamp = cls._get_timestamp_from_input(timestamp) dt = datetime.fromtimestamp(timestamp, tzinfo) return cls(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
'Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a timestamp, in UTC time. :param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either.'
@classmethod def utcfromtimestamp(cls, timestamp):
timestamp = cls._get_timestamp_from_input(timestamp) dt = datetime.utcfromtimestamp(timestamp) return cls(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dateutil_tz.tzutc())
'Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a ``datetime`` and optional replacement timezone. :param dt: the ``datetime`` :param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to ``dt``\'s timezone, or UTC if naive. If you only want to replace the timezone of naive datetimes:: >>...
@classmethod def fromdatetime(cls, dt, tzinfo=None):
tzinfo = (tzinfo or dt.tzinfo or dateutil_tz.tzutc()) return cls(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo)
'Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a ``date`` and optional replacement timezone. Time values are set to 0. :param date: the ``date`` :param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to UTC.'
@classmethod def fromdate(cls, date, tzinfo=None):
tzinfo = (tzinfo or dateutil_tz.tzutc()) return cls(date.year, date.month, date.day, tzinfo=tzinfo)
'Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a date string and format, in the style of ``datetime.strptime``. Optionally replaces the parsed timezone. :param date_str: the date string. :param fmt: the format string. :param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to the par...
@classmethod def strptime(cls, date_str, fmt, tzinfo=None):
dt = datetime.strptime(date_str, fmt) tzinfo = (tzinfo or dt.tzinfo) return cls(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo)
'Returns a list of :class:`Arrow <arrow.arrow.Arrow>` objects, representing an iteration of time between two inputs. :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). :param start: A datetime expression, the start of the range. :param end: (optional) A datetime expression, the end o...
@classmethod def range(cls, frame, start, end=None, tz=None, limit=None):
(_, frame_relative, relative_steps) = cls._get_frames(frame) tzinfo = cls._get_tzinfo((start.tzinfo if (tz is None) else tz)) start = cls._get_datetime(start).replace(tzinfo=tzinfo) (end, limit) = cls._get_iteration_params(end, limit) end = cls._get_datetime(end).replace(tzinfo=tzinfo) current =...
'Returns a list of tuples, each :class:`Arrow <arrow.arrow.Arrow>` objects, representing a series of timespans between two inputs. :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). :param start: A datetime expression, the start of the range. :param end: (optional) A datetime express...
@classmethod def span_range(cls, frame, start, end, tz=None, limit=None):
tzinfo = cls._get_tzinfo((start.tzinfo if (tz is None) else tz)) start = cls.fromdatetime(start, tzinfo).span(frame)[0] _range = cls.range(frame, start, end, tz, limit) return [r.span(frame) for r in _range]
'Returns an array of tuples, each :class:`Arrow <arrow.arrow.Arrow>` objects, representing a series of intervals between two inputs. :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). :param start: A datetime expression, the start of the range. :param end: (optional) A datetime expre...
@classmethod def interval(cls, frame, start, end, interval=1, tz=None):
if (interval < 1): raise ValueError('interval has to be a positive integer') spanRange = cls.span_range(frame, start, end, tz) bound = ((len(spanRange) // interval) * interval) return [(spanRange[i][0], spanRange[((i + interval) - 1)][1]) for i in range(0, bound, interval)]