code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
assert yaml, 'YAMLParser requires pyyaml to be installed'
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
try:
data = stream.read().decode(encoding)
return yaml.safe_load(data)
except (Va... | def parse(self, stream, media_type=None, parser_context=None) | Parses the incoming bytestream as YAML and returns the resulting data. | 2.763666 | 2.535222 | 1.090108 |
assert yaml, 'YAMLRenderer requires pyyaml to be installed'
if data is None:
return ''
return yaml.dump(
data,
stream=None,
encoding=self.charset,
Dumper=self.encoder,
allow_unicode=not self.ensure_ascii,
... | def render(self, data, accepted_media_type=None, renderer_context=None) | Renders `data` into serialized YAML. | 4.145577 | 3.633104 | 1.141057 |
meta_vals = {
'unique_together': (("parent", "child"),)
}
if getattr(cls._meta, 'db_table', None):
meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table')
model = type('%sClosure' % cls.__name__, (models.Model,), {
'parent': models.ForeignKey(
cls._... | def create_closure_model(cls) | Creates a <Model>Closure model in the same module as the model. | 3.079667 | 3.184036 | 0.967221 |
superclasses = (
list(set(ClosureModel.__subclasses__()) &
set(cls._meta.get_parent_list()))
)
return next(iter(superclasses)) if superclasses else cls | def _toplevel(cls) | Find the top level of the chain we're in.
For example, if we have:
C inheriting from B inheriting from A inheriting from ClosureModel
C._toplevel() will return A. | 10.990214 | 7.856001 | 1.398958 |
cls._closure_model.objects.all().delete()
cls._closure_model.objects.bulk_create([cls._closure_model(
parent_id=x['pk'],
child_id=x['pk'],
depth=0
) for x in cls.objects.values("pk")])
for node in cls.objects.all():
node._closure_c... | def rebuildtable(cls) | Regenerate the entire closuretree. | 4.540107 | 3.939086 | 1.152579 |
if hasattr(self, "%s_id" % self._closure_parent_attr):
return getattr(self, "%s_id" % self._closure_parent_attr)
else:
parent = getattr(self, self._closure_parent_attr)
return parent.pk if parent else None | def _closure_parent_pk(self) | What our parent pk is in the closure tree. | 2.403724 | 2.143717 | 1.121288 |
self._closure_model.objects.filter(
**{
"parent__%s__child" % self._closure_parentref(): oldparentpk,
"child__%s__parent" % self._closure_childref(): self.pk
}
).delete() | def _closure_deletelink(self, oldparentpk) | Remove incorrect links from the closure tree. | 4.606517 | 4.447824 | 1.035679 |
linkparents = self._closure_model.objects.filter(
child__pk=self._closure_parent_pk
).values("parent", "depth")
linkchildren = self._closure_model.objects.filter(
parent__pk=self.pk
).values("child", "depth")
newlinks = [self._closure_model(
... | def _closure_createlink(self) | Create a link in the closure tree. | 2.707066 | 2.620908 | 1.032873 |
if self.is_root_node():
if not include_self:
return self._toplevel().objects.none()
else:
# Filter on pk for efficiency.
return self._toplevel().objects.filter(pk=self.pk)
params = {"%s__child" % self._closure_parentref():... | def get_ancestors(self, include_self=False, depth=None) | Return all the ancestors of this object. | 3.338578 | 3.241929 | 1.029812 |
params = {"%s__parent" % self._closure_childref():self.pk}
if depth is not None:
params["%s__depth__lte" % self._closure_childref()] = depth
descendants = self._toplevel().objects.filter(**params)
if not include_self:
descendants = descendants.exclude(pk=... | def get_descendants(self, include_self=False, depth=None) | Return all the descendants of this object. | 3.08222 | 2.9511 | 1.044431 |
objs = list(queryset)
hashobjs = dict([(x.pk, x) for x in objs] + [(self.pk, self)])
for descendant in hashobjs.values():
descendant._cached_children = []
for descendant in objs:
assert descendant._closure_parent_pk in hashobjs
parent = hashob... | def prepopulate(self, queryset) | Perpopulate a descendants query's children efficiently.
Call like: blah.prepopulate(blah.get_descendants().select_related(stuff)) | 4.033232 | 3.653033 | 1.104077 |
if hasattr(self, '_cached_children'):
children = self._toplevel().objects.filter(
pk__in=[n.pk for n in self._cached_children]
)
children._result_cache = self._cached_children
return children
else:
return self.get_desce... | def get_children(self) | Return all the children of this object. | 4.507871 | 4.267684 | 1.05628 |
if self.is_root_node():
return self
return self.get_ancestors().order_by(
"-%s__depth" % self._closure_parentref()
)[0] | def get_root(self) | Return the furthest ancestor of this node. | 11.177649 | 8.201679 | 1.362849 |
if other.pk == self.pk:
return include_self
return self._closure_model.objects.filter(
parent=other,
child=self
).exclude(pk=self.pk).exists() | def is_descendant_of(self, other, include_self=False) | Is this node a descendant of `other`? | 5.162826 | 4.847126 | 1.065131 |
return other.is_descendant_of(self, include_self=include_self) | def is_ancestor_of(self, other, include_self=False) | Is this node an ancestor of `other`? | 3.28051 | 2.531793 | 1.295726 |
base, fraction = split(digits)
# quantization beyond an order of magnitude results in a variable amount
# of decimal digits depending on the lowest common multiple,
# e.g. floor(1.2341234, 1.25) = 1.225 but floor(1.2341234, 1.5) = 1.20
if fraction * 10 % 1 > 0:
digits = base + 2
el... | def quantize(number, digits=0, q=builtins.round) | Quantize to somewhere in between a magnitude.
For example:
* ceil(55.25, 1.2) => 55.26
* floor(55.25, 1.2) => 55.24
* round(55.3333, 2.5) => 55.335
* round(12.345, 1.1) == round(12.345, 2) == 12.34 | 6.469836 | 6.691763 | 0.966836 |
@functools.wraps(fn)
def vectorized_function(values, *vargs, **kwargs):
return [fn(value, *vargs, **kwargs) for value in values]
return vectorized_function | def vectorize(fn) | Allows a method to accept a list argument, but internally deal only
with a single item of that list. | 2.914224 | 2.823092 | 1.032281 |
display = decimal.Context(prec=precision)
value = decimal.Decimal(value).normalize(context=display)
string = value.to_eng_string()
if prefix:
prefixes = {e(exponent): prefix for exponent, prefix in prefixes.items()}
return replace(string, prefixes)
else:
return string | def engineering(value, precision=3, prefix=False, prefixes=SI) | Convert a number to engineering notation. | 5.021451 | 4.760427 | 1.054832 |
reference = statistic(values)
if not reference:
return upcast([''] * len(values), values)
exponent = order(reference)
e = bound(exponent - exponent % 3, -12, 12)
# the amount of decimals is the precision minus the amount of digits
# before the decimal point, which is one more tha... | def business(values, precision=3, prefix=True, prefixes=SI, statistic=median, default='') | Convert a list of numbers to the engineering notation appropriate to a
reference point like the minimum, the median or the mean --
think of it as "business notation".
Any number will have at most the amount of significant digits of the
reference point, that is, the function will round beyond the
de... | 6.348229 | 6.302936 | 1.007186 |
chunk = []
for idx, item in enumerate(iterator, 1):
chunk.append(item)
if idx % chunksize == 0:
yield chunk
chunk = []
if chunk:
yield chunk | def chunked(iterator, chunksize) | Yields items from 'iterator' in chunks of size 'chunksize'.
>>> list(chunked([1, 2, 3, 4, 5], chunksize=2))
[(1, 2), (3, 4), (5,)] | 2.024785 | 2.820762 | 0.717815 |
try:
sock = socket.socket()
sock.connect((self.host, self.port))
return True
except (socket.error, socket.timeout):
return False
finally:
# close socket manually for sake of PyPy
sock.close() | def pre_start_check(self) | Check if process accepts connections.
.. note::
Process will be considered started, when it'll be able to accept
TCP connections as defined in initializer. | 4.125463 | 4.12594 | 0.999884 |
try:
conn = HTTPConnection(self.host, self.port)
conn.request('HEAD', self.url.path)
status = str(conn.getresponse().status)
if status == self.status or self.status_re.match(status):
conn.close()
return True
exce... | def after_start_check(self) | Check if defined URL returns expected status to a HEAD request. | 3.674558 | 3.200969 | 1.147952 |
super(OutputExecutor, self).start()
# get a polling object
self.poll_obj = select.poll()
# register a file descriptor
# POLLIN because we will wait for data to read
self.poll_obj.register(self.output(), select.POLLIN)
try:
self.wait_for(sel... | def start(self) | Start process.
:returns: itself
:rtype: OutputExecutor
.. note::
Process will be considered started, when defined banner will appear
in process output. | 5.492599 | 5.354317 | 1.025826 |
# Here we should get an empty list or list with a tuple [(fd, event)]
# When we get list with a tuple we can use readline method on
# the file descriptor.
poll_result = self.poll_obj.poll(0)
if poll_result:
line = self.output().readline()
if self... | def _wait_for_output(self) | Check if output matches banner.
.. warning::
Waiting for I/O completion. It does not work on Windows. Sorry. | 11.133155 | 9.982213 | 1.115299 |
language = language or translation.get_language()
with force_language(language):
recipients = recipients or []
if isinstance(recipients, basestring):
recipients = [recipients]
from_email = from_email or settings.DEFAULT_FROM_EMAIL
subject_templates = subject_temp... | def construct_mail(recipients=None, context=None, template_base='emailit/email', subject=None, message=None, site=None,
subject_templates=None, body_templates=None, html_templates=None, from_email=None, language=None,
**kwargs) | usage:
construct_mail(['my@email.com'], {'my_obj': obj}, template_base='myapp/emails/my_obj_notification').send()
:param recipients: recipient or list of recipients
:param context: context for template rendering
:param template_base: the base template. '.subject.txt', '.body.txt' and '.body.html' will b... | 2.055177 | 2.095037 | 0.980974 |
# pylint: disable=redefined-outer-name, reimported
# atexit functions tends to loose global imports sometimes so reimport
# everything what is needed again here:
import os
import errno
from mirakuru.base_env import processes_with_env
from mirakuru.compat import SIGKILL
pids = proce... | def cleanup_subprocesses() | On python exit: find possibly running subprocesses and kill them. | 8.012659 | 7.637062 | 1.049181 |
if self.process is None:
command = self.command
if not self._shell:
command = self.command_parts
env = os.environ.copy()
# Trick with marking subprocesses with an environment variable.
#
# There is no easy way to r... | def start(self) | Start defined process.
After process gets started, timeout countdown begins as well.
:returns: itself
:rtype: SimpleExecutor
.. note::
We want to open ``stdin``, ``stdout`` and ``stderr`` as text
streams in universal newlines mode, so we have to set
... | 6.383892 | 6.27138 | 1.01794 |
if self.process:
if self.process.stdin:
self.process.stdin.close()
if self.process.stdout:
self.process.stdout.close()
self.process = None
self._endtime = None | def _clear_process(self) | Close stdin/stdout of subprocess.
It is required because of ResourceWarning in Python 3. | 3.095571 | 2.655758 | 1.165607 |
pids = processes_with_env(ENV_UUID, self._uuid)
for pid in pids:
log.debug("Killing process %d ...", pid)
try:
os.kill(pid, sig)
except OSError as err:
if err.errno in IGNORED_ERROR_CODES:
# the process has ... | def _kill_all_kids(self, sig) | Kill all subprocesses (and its subprocesses) that executor started.
This function tries to kill all leftovers in process tree that current
executor may have left. It uses environment variable to recognise if
process have origin in this Executor so it does not give 100 % and
some daemons... | 3.793503 | 4.202371 | 0.902705 |
if sig is None:
sig = self._sig_kill
if self.running():
os.killpg(self.process.pid, sig)
if wait:
self.process.wait()
self._kill_all_kids(sig)
self._clear_process()
return self | def kill(self, wait=True, sig=None) | Kill the process if running.
:param bool wait: set to `True` to wait for the process to end,
or False, to simply proceed after sending signal.
:param int sig: signal used to kill process run by the executor.
None by default.
:returns: itself
:rtype: SimpleExecuto... | 4.02011 | 4.553904 | 0.882783 |
while self.check_timeout():
if wait_for():
return self
time.sleep(self._sleep)
self.kill()
raise TimeoutExpired(self, timeout=self._timeout) | def wait_for(self, wait_for) | Wait for callback to return True.
Simply returns if wait_for condition has been met,
raises TimeoutExpired otherwise and kills the process.
:param callback wait_for: callback to call
:raises: mirakuru.exceptions.TimeoutExpired
:returns: itself
:rtype: SimpleExecutor | 6.190305 | 5.182379 | 1.194491 |
if self.pre_start_check():
# Some other executor (or process) is running with same config:
raise AlreadyRunning(self)
super(Executor, self).start()
self.wait_for(self.check_subprocess)
return self | def start(self) | Start executor with additional checks.
Checks if previous executor isn't running then start process
(executor) and wait until it's started.
:returns: itself
:rtype: Executor | 12.484674 | 9.405146 | 1.32743 |
exit_code = self.process.poll()
if exit_code is not None and exit_code != 0:
# The main process exited with an error. Clean up the children
# if any.
self._kill_all_kids(self._sig_kill)
self._clear_process()
raise ProcessExitedWithErro... | def check_subprocess(self) | Make sure the process didn't exit with an error and run the checks.
:rtype: bool
:return: the actual check status
:raise ProcessExitedWithError: when the main process exits with
an error | 5.76866 | 5.137886 | 1.122769 |
pids = set()
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'environ'])
except (psutil.NoSuchProcess, IOError):
# can't do much if psutil is not able to get this process details
pass
else:
penv = pinfo.get(... | def processes_with_env_psutil(env_name, env_value) | Find PIDs of processes having environment variable matching given one.
Internally it uses `psutil` library.
:param str env_name: name of environment variable to be found
:param str env_value: environment variable value prefix
:return: process identifiers (PIDs) of processes that have certain
... | 2.777306 | 2.940689 | 0.94444 |
pids = set()
ps_xe = ''
try:
cmd = 'ps', 'xe', '-o', 'pid,cmd'
ps_xe = subprocess.check_output(cmd).splitlines()
except OSError as err:
if err.errno == errno.ENOENT:
log.error("`$ ps xe -o pid,cmd` command was called but it is not "
"availab... | def processes_with_env_ps(env_name, env_value) | Find PIDs of processes having environment variable matching given one.
It uses `$ ps xe -o pid,cmd` command so it works only on systems
having such command available (Linux, MacOS). If not available function
will just log error.
:param str env_name: name of environment variable to be found
:param ... | 3.767849 | 3.321516 | 1.134376 |
den = np.array(norm(x) * norm(y))
den[den == 0] = np.Inf
x_len = len(x)
fft_size = 1 << (2*x_len-1).bit_length()
cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size)))
cc = np.concatenate((cc[-(x_len-1):], cc[:x_len]))
return np.real(cc) / den | def _ncc_c(x, y) | >>> _ncc_c([1,2,3,4], [1,2,3,4])
array([ 0.13333333, 0.36666667, 0.66666667, 1. , 0.66666667,
0.36666667, 0.13333333])
>>> _ncc_c([1,1,1], [1,1,1])
array([ 0.33333333, 0.66666667, 1. , 0.66666667, 0.33333333])
>>> _ncc_c([1,2,3], [-1,-1,-1])
array([-0.15430335, -0.... | 3.457096 | 4.037029 | 0.856346 |
den = np.array(norm(x, axis=1) * norm(y))
den[den == 0] = np.Inf
x_len = x.shape[-1]
fft_size = 1 << (2*x_len-1).bit_length()
cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size)))
cc = np.concatenate((cc[:,-(x_len-1):], cc[:,:x_len]), axis=1)
return np.real(cc) / den[:, np.newaxis] | def _ncc_c_2dim(x, y) | Variant of NCCc that operates with 2 dimensional X arrays and 1 dimensional
y vector
Returns a 2 dimensional array of normalized fourier transforms | 3.216849 | 3.532389 | 0.910672 |
den = norm(x, axis=1)[:, None] * norm(y, axis=1)
den[den == 0] = np.Inf
x_len = x.shape[-1]
fft_size = 1 << (2*x_len-1).bit_length()
cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size))[:, None])
cc = np.concatenate((cc[:,:,-(x_len-1):], cc[:,:,:x_len]), axis=2)
return np.real(cc) / d... | def _ncc_c_3dim(x, y) | Variant of NCCc that operates with 2 dimensional X arrays and 2 dimensional
y vector
Returns a 3 dimensional array of normalized fourier transforms | 3.268055 | 3.788561 | 0.862611 |
ncc = _ncc_c(x, y)
idx = ncc.argmax()
dist = 1 - ncc[idx]
yshift = roll_zeropad(y, (idx + 1) - max(len(x), len(y)))
return dist, yshift | def _sbd(x, y) | >>> _sbd([1,1,1], [1,1,1])
(-2.2204460492503131e-16, array([1, 1, 1]))
>>> _sbd([0,1,2], [1,2,3])
(0.043817112532485103, array([1, 2, 3]))
>>> _sbd([1,2,3], [0,1,2])
(0.043817112532485103, array([0, 1, 2])) | 6.34978 | 7.069604 | 0.89818 |
_a = []
for i in range(len(idx)):
if idx[i] == j:
if cur_center.sum() == 0:
opt_x = x[i]
else:
_, opt_x = _sbd(cur_center, x[i])
_a.append(opt_x)
a = np.array(_a)
if len(a) == 0:
return np.zeros((1, x.shape[1]))
... | def _extract_shape(idx, x, j, cur_center) | >>> _extract_shape(np.array([0,1,2]), np.array([[1,2,3], [4,5,6]]), 1, np.array([0,3,4]))
array([-1., 0., 1.])
>>> _extract_shape(np.array([0,1,2]), np.array([[-1,2,3], [4,-5,6]]), 1, np.array([0,3,4]))
array([-0.96836405, 1.02888681, -0.06052275])
>>> _extract_shape(np.array([1,0,1,0]), np.array([[1... | 3.202807 | 3.40368 | 0.940984 |
m = x.shape[0]
idx = randint(0, k, size=m)
centroids = np.zeros((k, x.shape[1]))
distances = np.empty((m, k))
for _ in range(100):
old_idx = idx
for j in range(k):
centroids[j] = _extract_shape(idx, x, j, centroids[j])
distances = (1 - _ncc_c_3dim(x, centro... | def _kshape(x, k) | >>> from numpy.random import seed; seed(0)
>>> _kshape(np.array([[1,2,3,4], [0,1,2,3], [-1,1,-1,1], [1,2,2,3]]), 2)
(array([0, 0, 1, 0]), array([[-1.2244258 , -0.35015476, 0.52411628, 1.05046429],
[-0.8660254 , 0.8660254 , -0.8660254 , 0.8660254 ]])) | 4.11819 | 4.119413 | 0.999703 |
for ver in registry.version_info:
if ver.version_id == version_id:
return ver.id
return None | def get_version_by_version_id(version_id) | Get the internal version ID be the version.
:param Tuple version_id: Major and minor version number
:return: Internal version ID
:rtype: Integer|None | 5.801063 | 5.894411 | 0.984163 |
ver = registry.version_info.get(version_id)
if ver:
return ver.name
return 'unknown' | def get_version_name(version_id) | Get the name of a protocol version by the internal version ID.
:param Integer version_id: Internal protocol version ID
:return: Name of the version
:rtype: String | 6.11864 | 8.075394 | 0.757689 |
ver = registry.version_info.get(protocol_version)
if ver:
return ver.version_id | def get_version_id(protocol_version) | Get a tuple with major and minor version number
:param Integer protocol_version: Internal version ID
:return: Tuple of major and minor protocol version
:rtype: Tuple | 5.924061 | 11.392495 | 0.519997 |
output = compress_update(self.__ctx, b)
if self.__write:
self.__write(self.__header)
self.__header = None
self.__write(output)
self.update = self.__updateNextWrite
else:
header = self.__header
... | def update(self, b): # pylint: disable=method-hidden,invalid-name
with self.__lock | Compress data given in b, returning compressed result either from this function or writing to fp). Note:
sometimes output might be zero length (if being buffered by lz4).
Raises Lz4FramedNoDataError if input is of zero length. | 7.381485 | 6.19778 | 1.190989 |
with self.__lock:
if self.__write:
self.__write(compress_end(self.__ctx))
else:
return compress_end(self.__ctx) | def end(self) | Finalise lz4 frame, outputting any remaining as return from this function or by writing to fp) | 7.629103 | 5.413743 | 1.40921 |
if pretty:
return "%s (%x)" % (
self.enums.get(self._value, "n/a"),
self._value
)
return self.enums.get(self._value, "n/a") | def get_value_name(self, pretty=False) | Get the name of the value
:param Boolean pretty: Return the name in a pretty format
:return: The name
:rtype: String | 3.690822 | 4.406581 | 0.83757 |
if force:
self._value = value
return
if value is None:
self._value = value
return
if isinstance(value, six.integer_types):
self._value = value
return
if isinstance(value, six.string_types):
fo... | def set_value(self, value, force=False) | Set the value.
:param String|Integer value: The value to set. Must be in the enum list.
:param Boolean force: Set the value without checking it
:raises ValueError: If value name given but it isn't available
:raises TypeError: If value is not String or Integer | 3.052972 | 2.602081 | 1.173281 |
size = struct.calcsize("B")
if len(data) < size:
raise NotEnoughData(
"Not enough data to decode field '%s' value" % self.name
)
curve_type = struct.unpack("B", data[:size])[0]
if curve_type == 0x03:
self._value = ECParameter... | def dissect(self, data) | Dissect the field.
:param bytes data: The data to extract the field value from
:return: The rest of the data not used to dissect the field value
:rtype: bytes | 5.358487 | 5.207879 | 1.028919 |
key = key.encode('utf8')
challenge = challenge.encode('utf8')
sig = hmac.new(key, challenge, hashlib.sha256).digest()
return binascii.b2a_base64(sig).strip() | def compute_wcs(key, challenge) | Compute an WAMP-CRA authentication signature from an authentication
challenge and a (derived) key.
:param key: The key derived (via PBKDF2) from the secret.
:type key: str/bytes
:param challenge: The authentication challenge to sign.
:type challenge: str/bytes
:return: The authentication signa... | 2.311638 | 2.452957 | 0.942388 |
options = {"invoke": invocation_policy}
message = Register(procedure=procedure_name, options=options)
request_id = message.request_id
try:
self.send_message(message)
except ValueError:
raise WampProtocolError(
"failed to register ... | def _register_procedure(self, procedure_name, invocation_policy="single") | Register a "procedure" on a Client as callable over the Router. | 5.216652 | 5.080838 | 1.026731 |
if self.started is True:
raise WampyError("Router already started")
# will attempt to connect or start up the CrossBar
crossbar_config_path = self.config_path
cbdir = self.crossbar_directory
# starts the process from the root of the test namespace
c... | def start(self) | Start Crossbar.io in a subprocess. | 6.708916 | 5.96038 | 1.125585 |
headers = []
# https://tools.ietf.org/html/rfc6455
headers.append("GET {} HTTP/1.1".format(self.websocket_location))
headers.append("Host: {}:{}".format(self.host, self.port))
headers.append("Upgrade: websocket")
headers.append("Connection: Upgrade")
# Se... | def _get_handshake_headers(self, upgrade) | Do an HTTP upgrade handshake with the server.
Websockets upgrade from HTTP rather than TCP largely because it was
assumed that servers which provide websockets will always be talking to
a browser. Maybe a reasonable assumption once upon a time...
The headers here will go a little furth... | 3.518229 | 3.459311 | 1.017032 |
self.scheme = None
self.resource = None
self.host = None
self.port = None
if self.url is None:
return
scheme, url = self.url.split(":", 1)
parsed = urlsplit(url, scheme="http")
if parsed.hostname:
self.host = parsed.hostn... | def parse_url(self) | Parses a URL of the form:
- ws://host[:port][path]
- wss://host[:port][path]
- ws+unix:///path/to/my.socket | 2.444193 | 2.38358 | 1.02543 |
# Masking of WebSocket traffic from client to server is required
# because of the unlikely chance that malicious code could cause
# some broken proxies to do the wrong thing and use this as an
# attack of some kind. Nobody has proved that this could actually
# happen, bu... | def generate_mask(cls, mask_key, data) | Mask data.
:Parameters:
mask_key: byte string
4 byte string(byte), e.g. '\x10\xc6\xc4\x16'
data: str
data to mask | 9.835816 | 9.252442 | 1.063051 |
# the first byte contains the FIN bit, the 3 RSV bits and the
# 4 opcode bits and for a client will *always* be 1000 0001 (or 129).
# so we want the first byte to look like...
#
# 1 0 0 0 0 0 0 1 (1 is a text frame)
# +-+-+-+-+-------+
# |F|R|R|R| opco... | def generate_bytes(cls, payload, fin_bit, opcode, mask_payload) | Format data to string (buffered_bytes) to send to server. | 4.580045 | 4.573187 | 1.0015 |
u, v = edge
both_exist = u in self.vertices and v in self.vertices
# Using `is` because if they belong to the same component, they MUST
# share the same set object!
if both_exist and self.components[u] is self.components[v]:
# Both vertices are part of the s... | def add_edge(self, edge) | Add edge (u, v) to the graph. Raises InvariantError if adding the edge
would form a cycle. | 4.319156 | 3.876802 | 1.114103 |
canonical_edges = set()
for v1, neighbours in self._vertices.items():
for v2 in neighbours:
edge = self.canonical_order((v1, v2))
canonical_edges.add(edge)
return canonical_edges | def edges(self) | Edges of this graph, in canonical order. | 3.699997 | 3.225742 | 1.147022 |
seen = set()
# Micro optimization: each call to seen_add saves an extra attribute
# lookup in most iterations of the loop.
seen_add = seen.add
return tuple(x for x in sequence if not (x in seen or seen_add(x))) | def ordered_deduplicate(sequence) | Returns the sequence as a tuple with the duplicates removed,
preserving input order. Any duplicates following the first
occurrence are removed.
>>> ordered_deduplicate([1, 2, 3, 1, 32, 1, 2])
(1, 2, 3, 32)
Based on recipe from this StackOverflow post:
http://stackoverflow.com/a/480227 | 7.741824 | 7.808367 | 0.991478 |
# Ensure that we have an indexable sequence.
words = tuple(words)
# Delegate to the hash builder.
return CzechHashBuilder(words).hash_info | def hash_parameters(words, minimize_indices=False) | Gives hash parameters for the given set of words.
>>> info = hash_parameters('sun mon tue wed thu fri sat'.split())
>>> len(info.t1)
21
>>> len(info.t2)
21
>>> len(info.g) # g values are 1-indexed...
22 | 17.859106 | 25.355576 | 0.704346 |
return PickableHash(CzechHashBuilder(words, *args, **kwargs)).czech_hash | def make_pickable_hash(words, *args, **kwargs) | Creates an ordered, minimal perfect hash function for the given sequence
of words.
>>> hf = make_pickable_hash(['sun', 'mon', 'tue', 'wed', 'thu',
... 'fri', 'sat'])
>>> hf('fri')
5
>>> hf('sun')
0 | 16.521578 | 27.34477 | 0.604195 |
info = CzechHashBuilder(words, *args, **kwargs)
# Create a docstring that at least describes where the class came from...
doc = % (__name__, make_dict.__name__, name)
# Delegate to create_dict.
return create_dict_subclass(name, info.hash_function, info.words, doc) | def make_dict(name, words, *args, **kwargs) | make_dict(name, words, *args, **kwargs) -> mapping subclass
Takes a sequence of words (or a pre-built Czech HashInfo) and returns a
mapping subclass called `name` (used a dict) that employs the use of the
minimal perfect hash.
This mapping subclass has guaranteed O(1) worst-case lookups, additions,
... | 14.217113 | 13.025899 | 1.09145 |
assert hasattr(self, 'f1') and hasattr(self, 'f2')
# These are not just convenient aliases for the given
# attributes; if `self` would creep into the returned closure,
# that would ensure that a reference to this big, fat object
# would be kept alive; hence, any hash fu... | def hash_function(self) | Returns the hash function proper. Ensures that `self` is not bound to
the returned closure. | 8.846336 | 8.060704 | 1.097464 |
# Maximum length of each table, respectively.
# Hardcoded n = cm, where c = 3
# There might be a good way to choose an appropriate C,
# but [1] suggests the average amount of iterations needed
# to generate an acyclic graph is sqrt(3).
self.n = 3 * len(self.word... | def generate_acyclic_graph(self) | Generates an acyclic graph for the given words.
Adds the graph, and a list of edge-word associations to the object. | 9.136522 | 8.964154 | 1.019229 |
table = list(range(0, self.n))
random.shuffle(table)
return table | def generate_random_table(self) | Generates random tables for given word lists. | 4.934811 | 4.640277 | 1.063473 |
t1 = self.generate_random_table()
t2 = self.generate_random_table()
f1 = self.generate_func(t1)
f2 = self.generate_func(t2)
edges = [(f1(word), f2(word)) for word in self.words]
# Try to generate that graph, mack!
# Note that failure to generate the gra... | def generate_or_fail(self) | Attempts to generate a random acyclic graph, raising an
InvariantError if unable to. | 4.451401 | 4.194862 | 1.061155 |
# Ensure that `self` isn't suddenly in the closure...
n = self.n
def func(word):
return sum(x * ord(c) for x, c in zip(table, word)) % n
return func | def generate_func(self, table) | Generates a random table based mini-hashing function. | 9.858628 | 8.529808 | 1.155785 |
hash_length = len(slots)
# Returns array index -- raises a KeyError if the key does not match
# its slot value.
def index_or_key_error(key):
index = hash_func(key)
# Make sure the key is **exactly** the same.
if key != slots[index]:
raise KeyError(key)
... | def create_dict_subclass(name, hash_func, slots, doc) | Creates a dict subclass named name, using the hash_function to index
hash_length items. Doc should be any additional documentation added to the
class. | 2.88741 | 2.828153 | 1.020952 |
if not "type" in data:
if fixerrors:
data["type"] = "FeatureCollection"
else:
raise ValueError("The geojson data needs to have a type key")
if not data["type"] == "FeatureCollection":
if fixerrors:
data["type"] = "FeatureCollection"
else:... | def validate(data, skiperrors=False, fixerrors=True) | Checks that the geojson data is a feature collection, that it
contains a proper "features" attribute, and that all features are valid too.
Returns True if all goes well.
- skiperrors will throw away any features that fail to validate.
- fixerrors will attempt to auto fix any minor errors without raisin... | 2.32027 | 2.166438 | 1.071007 |
# validate nullgeometry or has type and coordinates keys
if not self._data:
# null geometry, no further checking needed
return True
elif "type" not in self._data or "coordinates" not in self._data:
raise Exception("A geometry dictionary or instance m... | def validate(self, fixerrors=True) | Validates that the geometry is correctly formatted according to the geometry type.
Parameters:
- **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True)
Returns:
- True if the geometry is valid.
Raises:
- An Exce... | 2.423446 | 2.421403 | 1.000844 |
if not "type" in self._data or self._data["type"] != "Feature":
if fixerrors:
self._data["type"] = "Feature"
else:
raise Exception("A geojson feature dictionary must contain a type key and it must be named 'Feature'.")
if not "geometry" in... | def validate(self, fixerrors=True) | Validates that the feature is correctly formatted.
Parameters:
- **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True)
Returns:
- True if the feature is valid.
Raises:
- An Exception if not valid. | 2.467963 | 2.493912 | 0.989595 |
features = self._data["features"]
if not features: return []
elif len(features) == 1: return features[0]["properties"].keys()
else:
fields = set(features[0]["properties"].keys())
for feature in features[1:]:
fields.update(feature["properti... | def all_attributes(self) | Collect and return a list of all attributes/properties/fields used in any of the features. | 3.031095 | 2.428366 | 1.248203 |
features = self._data["features"]
if not features: return []
elif len(features) == 1: return features[0]["properties"].keys()
else:
fields = set(features[0]["properties"].keys())
for feature in features[1:]:
fields.intersection_update(feat... | def common_attributes(self) | Collect and return a list of attributes/properties/fields common to all features. | 2.861828 | 2.216452 | 1.291175 |
properties = properties or {}
if isinstance(obj, Feature):
# instead of creating copy, the original feat should reference the same one that was added here
feat = obj._data
elif isinstance(obj, dict):
feat = obj.copy()
else:
feat = ... | def add_feature(self, obj=None, geometry=None, properties=None) | Adds a given feature. If obj isn't specified, geometry and properties can be set as arguments directly.
Parameters:
- **obj**: Another feature instance, an object with the \_\_geo_interface__ or a geojson dictionary of the Feature type.
- **geometry** (optional): Anything that the Geometry ins... | 5.40385 | 6.618823 | 0.816437 |
if not type in ("name","link"): raise Exception("type must be either 'name' or 'link'")
crs = self._data["crs"] = {"type":type, "properties":{} }
if type == "name":
if not name: raise Exception("name argument must be given")
crs["properties"]["name"] = name
... | def define_crs(self, type, name=None, link=None, link_type=None) | Defines the coordinate reference system for the geojson file.
For link crs, only online urls are currenlty supported
(no auxilliary crs files).
Parameters:
- **type**: The type of crs, either "name" or "link".
- **name** (optional): The crs name as an OGC formatted crs string (... | 2.270351 | 2.395193 | 0.947878 |
xmins, ymins, xmaxs, ymaxs = zip(*(feat.geometry.bbox for feat in self if feat.geometry.type != "Null"))
bbox = [min(xmins), min(ymins), max(xmaxs), max(ymaxs)]
self._data["bbox"] = bbox | def update_bbox(self) | Recalculates the bbox region attribute for the entire file.
Useful after adding and/or removing features.
No need to use this method just for saving, because saving
automatically updates the bbox. | 4.476239 | 3.623157 | 1.235453 |
uid = 0
for feature in self._data["features"]:
if feature["properties"].get("id"):
raise Exception("one of the features already had an id field")
feature["properties"]["id"] = uid
uid += 1 | def add_unique_id(self) | Adds a unique id property to each feature.
Raises:
- An Exception if any of the features already
have an "id" field. | 5.482362 | 3.564236 | 1.538159 |
for feature in self:
if feature.geometry.type != "Null":
feature.geometry._data["bbox"] = Feature(feature).geometry.bbox | def add_all_bboxes(self) | Calculates and adds a bbox attribute to the geojson entry of all feature geometries, updating any existing ones. | 10.592645 | 6.682965 | 1.585022 |
self.update_bbox()
tempfile = open(savepath,"w")
json.dump(self._data, tempfile, **kwargs)
tempfile.close() | def save(self, savepath, **kwargs) | Saves the geojson instance to file. To save with a different text encoding use the 'encoding' argument.
Parameters:
- **savepath**: Filepath to save the file. | 6.28002 | 6.167698 | 1.018211 |
with open(filepath, "r") as f:
data = json.load(f, **kwargs)
return data | def _loadfilepath(self, filepath, **kwargs) | This loads a geojson file into a geojson python
dictionary using the json module.
Note: to load with a different text encoding use the encoding argument. | 2.990687 | 2.936004 | 1.018625 |
# if missing, compute and add bbox
if not self._data.get("bbox"):
self.update_bbox()
# if missing, set crs to default crs (WGS84), see http://geojson.org/geojson-spec.html
if not self._data.get("crs"):
self._data["crs"] = {"type":"name",
... | def _prepdata(self) | Adds potentially missing items to the geojson dictionary | 4.119662 | 3.507487 | 1.174534 |
# If to_int is not assigned, simply use the identity function.
if to_int is None:
to_int = __identity
key_to_original = {to_int(original): original for original in keys}
# Create a set of all items to be hashed.
items = list(key_to_original.keys())
if minimize:
offset = ... | def hash_parameters(keys, minimize=True, to_int=None) | Calculates the parameters for a perfect hash. The result is returned
as a HashInfo tuple which has the following fields:
t
The "table parameter". This is the minimum side length of the
table used to create the hash. In practice, t**2 is the maximum
size of the output hash.
slots
... | 5.554997 | 4.736923 | 1.172702 |
# A minheap (because that's all that heapq supports :/)
# of the length of each row. Why this is important is because
# we'll be popping the largest rows when figuring out row displacements.
# Each item is a tuple of (t - |row|, y, [(xpos_1, item_1), ...]).
# Until the call to heapq.heapify(),... | def place_items_in_square(items, t) | Returns a list of rows that are stored as a priority queue to be
used with heapq functions.
>>> place_items_in_square([1,5,7], 4)
[(2, 1, [(1, 5), (3, 7)]), (3, 0, [(1, 1)])]
>>> place_items_in_square([1,5,7], 3)
[(2, 0, [(1, 1)]), (2, 1, [(2, 5)]), (2, 2, [(1, 7)])] | 7.86998 | 7.306617 | 1.077103 |
# Create a set of all of the unoccupied columns.
max_columns = t ** 2
cols = ((x, True) for x in range(max_columns))
unoccupied_columns = collections.OrderedDict(cols)
# Create the resultant and displacement vectors.
result = [None] * max_columns
displacements = [None] * t
while ... | def arrange_rows(row_queue, t) | Takes a priority queue as generated by place_items_in_square().
Arranges the items from its conceptual square to one list. Returns
both the resultant vector, plus the displacement vector, to be used
in the final output hash function.
>>> rows = [(2, 1, [(0, 1), (1, 5)]), (3, 3, [(1, 7)])]
>>> resu... | 5.161959 | 4.585335 | 1.125754 |
for free_col in unoccupied_columns:
# The offset is that such that the first item goes in the free column.
first_item_x = row[0][0]
offset = free_col - first_item_x
if check_columns_fit(unoccupied_columns, row, offset, row_length):
return offset
raise ValueError... | def find_first_fit(unoccupied_columns, row, row_length) | Finds the first index that the row's items can fit. | 6.393813 | 6.136013 | 1.042014 |
for index, item in row:
adjusted_index = (index + offset) % row_length
# Check if the index is in the appropriate place.
if adjusted_index not in unoccupied_columns:
return False
return True | def check_columns_fit(unoccupied_columns, row, offset, row_length) | Checks if all the occupied columns in the row fit in the indices
given by free columns.
>>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4)
True
>>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4)
True
>>> check_columns_fit({}, [(2, True), (3, True)], 0, 4)
False
>>>... | 4.38165 | 5.710623 | 0.767281 |
occupied_rows = {y: row for _, y, row in row_queue}
empty_row = ', '.join('...' for _ in range(t))
for y in range(t):
print('|', end=' ')
if y not in occupied_rows:
print(empty_row, end=' ')
else:
row = dict(occupied_rows[y])
all_cols = ('%3d... | def print_square(row_queue, t) | Prints a row queue as its conceptual square array. | 4.076336 | 3.927881 | 1.037795 |
# Find the first element that does not contain none.
for i, item in enumerate(reversed(xs)):
if item is not None:
break
return xs[:-i] | def trim_nones_from_right(xs) | Returns the list without all the Nones at the right end.
>>> trim_nones_from_right([1, 2, None, 4, None, 5, None, None])
[1, 2, None, 4, None, 5] | 5.117613 | 7.600373 | 0.673337 |
params = hash_parameters(keys, **kwargs)
t = params.t
r = params.r
offset = params.offset
to_int = params.to_int if params.to_int else __identity
def perfect_hash(x):
val = to_int(x) + offset
x = val % t
y = val // t
return x + r[y]
# Undocumented prop... | def make_hash(keys, **kwargs) | Creates a perfect hash function from the given keys. For a
description of the keyword arguments see :py:func:`hash_parameters`.
>>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34)
>>> hf = make_hash(l)
>>> hf(19)
1
>>> hash_parameters(l).slots[1]
19 | 5.946874 | 5.56531 | 1.068561 |
hash_func = make_hash(keys, **kwargs)
slots = hash_func.slots
# Create a docstring that at least describes where the class came from...
doc = % (__name__, make_dict.__name__, name)
return create_dict_subclass(name, hash_func, slots, doc) | def make_dict(name, keys, **kwargs) | Creates a dictionary-like mapping class that uses perfect hashing.
``name`` is the proper class name of the returned class. See
``hash_parameters()`` for documentation on all arguments after
``name``.
>>> MyDict = make_dict('MyDict', '+-<>[],.', to_int=ord)
>>> d = MyDict([('+', 1), ('-', 2)])
... | 9.551649 | 13.979758 | 0.683249 |
record_filename = os.path.join(dirname_full, RECORD_FILENAME)
if not os.path.exists(record_filename):
return None
mtime = os.stat(record_filename).st_mtime
mtime_str = datetime.fromtimestamp(mtime)
print('Found timestamp {}:{}'.format(dirname_full, mtime_str))
if Settings.record_t... | def _get_timestamp(dirname_full, remove) | Get the timestamp from the timestamp file.
Optionally mark it for removal if we're going to write another one. | 3.475275 | 3.44341 | 1.009254 |
if dirname_full not in TIMESTAMP_CACHE:
mtime = _get_timestamp(dirname_full, remove)
TIMESTAMP_CACHE[dirname_full] = mtime
return TIMESTAMP_CACHE[dirname_full] | def _get_timestamp_cached(dirname_full, remove) | Get the timestamp from the cache or fill the cache
Much quicker than reading the same files over and over | 2.332901 | 2.329667 | 1.001388 |
tstamp = _get_timestamp_cached(dirname_full, remove)
return max_none((tstamp, compare_tstamp)) | def _max_timestamps(dirname_full, remove, compare_tstamp) | Compare a timestamp file to one passed in. Get the max. | 7.625402 | 7.38599 | 1.032414 |
parent_pathname = os.path.dirname(dirname)
# max between the parent timestamp the one passed in
mtime = _max_timestamps(parent_pathname, False, mtime)
if dirname != os.path.dirname(parent_pathname):
# this is only called if we're not at the root
mtime = _get_parent_timestamp(paren... | def _get_parent_timestamp(dirname, mtime) | Get the timestamps up the directory tree. All the way to root.
Because they affect every subdirectory. | 5.048105 | 5.230454 | 0.965137 |
if Settings.optimize_after is not None:
return Settings.optimize_after
dirname = os.path.dirname(filename)
if optimize_after is None:
optimize_after = _get_parent_timestamp(dirname, optimize_after)
return _max_timestamps(dirname, True, optimize_after) | def get_walk_after(filename, optimize_after=None) | Figure out the which mtime to check against.
If we have to look up the path return that. | 4.782099 | 5.321072 | 0.89871 |
if Settings.test or Settings.list_only or not Settings.record_timestamp:
return
if not Settings.follow_symlinks and os.path.islink(pathname_full):
if Settings.verbose:
print('Not setting timestamp because not following symlinks')
return
if not os.path.isdir(pathname_... | def record_timestamp(pathname_full) | Record the timestamp of running in a dotfile. | 3.103257 | 3.036301 | 1.022052 |
# uncompress archive
tmp_dir, report_stats = comic.comic_archive_uncompress(filename_full,
image_format)
if tmp_dir is None and report_stats:
return Settings.pool.apply_async(_comic_archive_skip,
... | def walk_comic_archive(filename_full, image_format, optimize_after) | Optimize a comic archive.
This is done mostly inline to use the master processes process pool
for workers. And to avoid calling back up into walk from a dedicated
module or format processor. It does mean that we block on uncompress
and on waiting for the contents subprocesses to compress. | 4.629776 | 4.462896 | 1.037393 |
# File types
if not Settings.follow_symlinks and os.path.islink(filename_full):
return True
if os.path.basename(filename_full) == timestamp.RECORD_FILENAME:
return True
if not os.path.exists(filename_full):
if Settings.verbose:
print(filename_full, 'was not foun... | def _is_skippable(filename_full) | Handle things that are not optimizable files. | 4.340909 | 3.908117 | 1.110742 |
filename = os.path.normpath(filename)
result_set = set()
if _is_skippable(filename):
return result_set
walk_after = timestamp.get_walk_after(filename, walk_after)
# File is a directory
if os.path.isdir(filename):
return walk_dir(filename, walk_after, recurse, archive_mti... | def walk_file(filename, walk_after, recurse=None, archive_mtime=None) | Optimize an individual file. | 4.01119 | 3.948786 | 1.015803 |
if recurse is None:
recurse = Settings.recurse
result_set = set()
if not recurse:
return result_set
for root, _, filenames in os.walk(dir_path):
for filename in filenames:
filename_full = os.path.join(root, filename)
try:
results = w... | def walk_dir(dir_path, walk_after, recurse=None, archive_mtime=None) | Recursively optimize a directory. | 2.456055 | 2.430092 | 1.010684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.