code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def parse_game_event(self, ge):
if ge.name == "dota_combatlog":
if ge.keys["type"] == 4:
#Something died
try:
source = self.dp.combat_log_names.get(ge.keys["sourcename"],
"unknown"... | Game events contain the combat log as well as 'chase_hero' events which
could be interesting |
def fix_file(file_name, line_ranges, options=None, in_place=False,
diff=False, verbose=0, cwd=None):
import codecs
from os import getcwd
from pep8radius.diff import get_diff
from pep8radius.shell import from_dir
if cwd is None:
cwd = getcwd()
with from_dir(cwd):
... | Calls fix_code on the source code from the passed in file over the given
line_ranges.
- If diff then this returns the udiff for the changes, otherwise
returns the fixed code.
- If in_place the changes are written to the file. |
def fix_line_range(source_code, start, end, options):
# TODO confirm behaviour outside range (indexing starts at 1)
start = max(start, 1)
options.line_range = [start, end]
from autopep8 import fix_code
fixed = fix_code(source_code, options)
try:
if options.docformatter:
... | Apply autopep8 (and docformatter) between the lines start and end of
source. |
def _maybe_print(something_to_print, end=None, min_=1, max_=99, verbose=0):
if min_ <= verbose <= max_:
import sys
print(something_to_print, end=end)
sys.stdout.flush() | Print if verbose is within min_ and max_. |
def from_diff(diff, options=None, cwd=None):
return RadiusFromDiff(diff=diff, options=options, cwd=cwd) | Create a Radius object from a diff rather than a reposistory. |
def fix(self):
from pep8radius.diff import print_diff, udiff_lines_fixed
n = len(self.filenames_diff)
_maybe_print('Applying autopep8 to touched lines in %s file(s).' % n)
any_changes = False
total_lines_changed = 0
pep8_diffs = []
for i, file_name in e... | Runs fix_file on each modified file.
- Prints progress and diff depending on options.
- Returns True if there were any changes |
def fix_file(self, file_name):
# We hope that a CalledProcessError would have already raised
# during the init if it were going to raise here.
modified_lines = self.modified_lines(file_name)
return fix_file(file_name, modified_lines, self.options,
in_pla... | Apply autopep8 to the diff lines of a file.
- Returns the diff between original and fixed file.
- If self.in_place then this writes the the fixed code the file_name.
- Prints dots to show progress depending on options. |
def version():
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
'pep8radius',
'main.py')) as input_file:
for line in input_file:
if line.startswith('__version__'):
return parse(line).body[0].value.s | Return version string. |
def multi_evaluate(self, x, out=None):
if out is None:
out = _np.empty(len(x))
else:
assert len(out) == len(x)
for i, point in enumerate(x):
out[i] = self.evaluate(point)
return out | Evaluate log of the density to propose ``x``, namely log(q(x))
for each row in x.
:param x:
Matrix-like array; the proposed points. Expect i-th accessible
as ``x[i]``.
:param out:
Vector-like array, length==``len(x)``, optional; If provided,
th... |
def url_map(base, params):
url = base
if not params:
url.rstrip("?&")
elif '?' not in url:
url += "?"
entries = []
for key, value in params.items():
if value is not None:
value = str(value)
entries.append("%s=%s" % (quote_plus(key.encode("utf-... | Return a URL with get parameters based on the params passed in
This is more forgiving than urllib.urlencode and will attempt to coerce
non-string objects into strings and automatically UTF-8 encode strings.
@param params: HTTP GET parameters |
def make_request(name, params=None, version="V001", key=None, api_type="web",
fetcher=get_page, base=None, language="en_us"):
params = params or {}
params["key"] = key or API_KEY
params["language"] = language
if not params["key"]:
raise ValueError("API key not set, please... | Make an API request |
def json_request_response(f):
@wraps(f)
def wrapper(*args, **kwargs):
response = f(*args, **kwargs)
response.raise_for_status()
return json.loads(response.content.decode('utf-8'))
API_FUNCTIONS[f.__name__] = f
return wrapper | Parse the JSON from an API response. We do this in a decorator so that our
Twisted library can reuse the underlying functions |
def get_match_history(start_at_match_id=None, player_name=None, hero_id=None,
skill=0, date_min=None, date_max=None, account_id=None,
league_id=None, matches_requested=None, game_mode=None,
min_players=None, tournament_games_only=None,
... | List of most recent 25 matches before start_at_match_id |
def get_match_history_by_sequence_num(start_at_match_seq_num,
matches_requested=None, **kwargs):
params = {
"start_at_match_seq_num": start_at_match_seq_num,
"matches_requested": matches_requested
}
return make_request("GetMatchHistoryBySequenceNum... | Most recent matches ordered by sequence number |
def get_steam_id(vanityurl, **kwargs):
params = {"vanityurl": vanityurl}
return make_request("ResolveVanityURL", params, version="v0001",
base="http://api.steampowered.com/ISteamUser/", **kwargs) | Get a players steam id from their steam name/vanity url |
def get_player_summaries(players, **kwargs):
if (isinstance(players, list)):
params = {'steamids': ','.join(str(p) for p in players)}
elif (isinstance(players, int)):
params = {'steamids': players}
else:
raise ValueError("The players input needs to be a list or int")
return ... | Get players steam profile from their steam ids |
def get_hero_image_url(hero_name, image_size="lg"):
if hero_name.startswith("npc_dota_hero_"):
hero_name = hero_name[len("npc_dota_hero_"):]
valid_sizes = ['eg', 'sb', 'lg', 'full', 'vert']
if image_size not in valid_sizes:
raise ValueError("Not a valid hero image size")
return "... | Get a hero image based on name and image size |
def generate_proxy(
prefix, base_url='', verify_ssl=True, middleware=None,
append_middleware=None, cert=None, timeout=None):
middleware = list(middleware or HttpProxy.proxy_middleware)
middleware += list(append_middleware or [])
return type('ProxyClass', (HttpProxy,), {
'base_u... | Generate a ProxyClass based view that uses the passed base_url. |
def brier_score(observations, forecasts):
machine_eps = np.finfo(float).eps
forecasts = np.asarray(forecasts)
if (forecasts < 0.0).any() or (forecasts > (1.0 + machine_eps)).any():
raise ValueError('forecasts must not be outside of the unit interval '
'[0, 1]')
obse... | Calculate the Brier score (BS)
The Brier score (BS) scores binary forecasts $k \in \{0, 1\}$,
..math:
BS(p, k) = (p_1 - k)^2,
where $p_1$ is the forecast probability of $k=1$.
Parameters
----------
observations, forecasts : array_like
Broadcast compatible arrays of forecasts ... |
def dumps(*args, **kwargs):
import json
from django.conf import settings
from argonauts.serializers import JSONArgonautsEncoder
kwargs.setdefault('cls', JSONArgonautsEncoder)
# pretty print in DEBUG mode.
if settings.DEBUG:
kwargs.setdefault('indent', 4)
kwargs.setdefault(... | Wrapper for json.dumps that uses the JSONArgonautsEncoder. |
def format(self, record):
# XXX: idea, colorize message arguments
s = super(ANSIFormatter, self).format(record)
if hasattr(self.context, 'ansi'):
s = self.context.ansi(s, **self.get_sgr(record))
return s | Overridden method that applies SGR codes to log messages. |
def added(self, context):
self._expose_argparse = context.bowl.has_spice("log:arguments")
self.configure_logging(context) | Configure generic application logging.
This method just calls ``:meth:`configure_logging()`` which sets up
everything else. This allows other components to use logging without
triggering implicit configuration. |
def configure_logging(self, context):
fmt = "%(name)-12s: %(levelname)-8s %(message)s"
formatter = ANSIFormatter(context, fmt)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logging.root.addHandler(handler) | Configure logging for the application.
:param context:
The guacamole context object.
This method attaches a :py:class:logging.StreamHandler` with a
subclass of :py:class:`logging.Formatter` to the root logger. The
specific subclass is :class:`ANSIFormatter` and it adds basi... |
def adjust_logging(self, context):
if context.early_args.log_level:
log_level = context.early_args.log_level
logging.getLogger("").setLevel(log_level)
for name in context.early_args.trace:
logging.getLogger(name).setLevel(logging.DEBUG)
_logger.in... | Adjust logging configuration.
:param context:
The guacamole context object.
This method uses the context and the results of early argument parsing
to adjust the configuration of the logging subsystem. In practice the
values passed to ``--log-level`` and ``--trace`` are appl... |
def invoked(self, ctx):
logging.debug("Some debugging message")
print("Just a normal print!")
logging.info("Some informational message")
print("Just a normal print!")
logging.warn("Some warning message")
print("Just a normal print!")
logging.error("Some e... | Guacamole method used by the command ingredient.
:param ctx:
The guacamole context object. Context provides access to all
features of guacamole.
:returns:
The return code of the command. Guacamole translates ``None`` to a
successful exit status (return co... |
def perp(weights):
r
# normalize weights
w = _np.asarray(weights) / _np.sum(weights)
# mask zero weights
w = _np.ma.MaskedArray(w, copy=False, mask=(w == 0))
# avoid NaN due to log(0) by log(1)=0
entr = - _np.sum( w * _np.log(w.filled(1.0)))
return _np.exp(entr) / len(w) | r"""Calculate the normalized perplexity :math:`\mathcal{P}` of samples
with ``weights`` :math:`\omega_i`. :math:`\mathcal{P}=0` is
terrible and :math:`\mathcal{P}=1` is perfect.
.. math::
\mathcal{P} = exp(H) / N
where
.. math::
H = - \sum_{i=1}^N \bar{\omega}_i log ~ \bar{\omeg... |
def ess(weights):
r
# normalize weights
w = _np.asarray(weights) / _np.sum(weights)
# ess
coeff_var = _np.sum((len(w) * w - 1)**2) / len(w)
return 1.0 / (1.0 + coeff_var) | r"""Calculate the normalized effective sample size :math:`ESS` [LC95]_
of samples with ``weights`` :math:`\omega_i`. :math:`ESS=0` is
terrible and :math:`ESS=1` is perfect.
.. math::
ESS = \frac{1}{1+C^2}
where
.. math::
C^2 = \frac{1}{N} \sum_{i=1}^N (N \bar{\omega}_i - 1)^2
... |
def json(a):
json_str = json_dumps(a)
# Escape all the XML/HTML special characters.
escapes = ['<', '>', '&']
for c in escapes:
json_str = json_str.replace(c, r'\u%04x' % ord(c))
# now it's safe to use mark_safe
return mark_safe(json_str) | Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter. |
def json_twisted_response(f):
def wrapper(*args, **kwargs):
response = f(*args, **kwargs)
response.addCallback(lambda x: json.loads(x))
return response
wrapper.func = f
wrapper = util.mergeFunctionMetadata(f.func, wrapper)
return wrapper | Parse the JSON from an API response. We do this in a decorator so that our
Twisted library can reuse the underlying functions |
def main(self, argv=None, exit=True):
bowl = self.prepare()
try:
retval = bowl.eat(argv)
except SystemExit as exc:
if exit:
raise
else:
return exc.args[0]
else:
if retval is None:
ret... | Shortcut to prepare a bowl of guacamole and eat it.
:param argv:
Command line arguments or None. None means that sys.argv is used
:param exit:
Raise SystemExit after finishing execution
:returns:
Whatever is returned by the eating the guacamole.
:rais... |
def dispatch_failed(self, context):
traceback.print_exception(
context.exc_type, context.exc_value, context.traceback)
raise SystemExit(1) | Print the unhandled exception and exit the application. |
def variables(template):
'''Returns the set of keywords in a uri template'''
vars = set()
for varlist in TEMPLATE.findall(template):
if varlist[0] in OPERATOR:
varlist = varlist[1:]
varspecs = varlist.split(',')
for var in varspecs:
# handle prefix values
... | Returns the set of keywords in a uri template |
def expand(template, variables):
def _sub(match):
expression = match.group(1)
operator = ""
if expression[0] in OPERATOR:
operator = expression[0]
varlist = expression[1:]
else:
varlist = expression
safe = ""
if operator in ["... | Expand template as a URI Template using variables. |
def calculate_mean(samples, weights):
r'''Calculate the mean of weighted samples (like the output of an
importance-sampling run).
:param samples:
Matrix-like numpy array; the samples to be used.
:param weights:
Vector-like numpy array; the (unnormalized) importance weights.
'''
... | r'''Calculate the mean of weighted samples (like the output of an
importance-sampling run).
:param samples:
Matrix-like numpy array; the samples to be used.
:param weights:
Vector-like numpy array; the (unnormalized) importance weights. |
def calculate_covariance(samples, weights):
r'''Calculates the covariance matrix of weighted samples (like the output of an
importance-sampling run).
:param samples:
Matrix-like numpy array; the samples to be used.
:param weights:
Vector-like numpy array; the (unnormalized) importanc... | r'''Calculates the covariance matrix of weighted samples (like the output of an
importance-sampling run).
:param samples:
Matrix-like numpy array; the samples to be used.
:param weights:
Vector-like numpy array; the (unnormalized) importance weights. |
def clear(self):
'''Clear history of samples and other internal variables to free memory.
.. note::
The proposal is untouched.
'''
self.samples.clear()
self.weights.clear()
if self.target_values is not None:
self.target_values.clear(f clear(self)... | Clear history of samples and other internal variables to free memory.
.. note::
The proposal is untouched. |
def _calculate_weights(self, this_samples, N):
this_weights = self.weights.append(N)[:,0]
if self.target_values is None:
for i in range(N):
tmp = self.target(this_samples[i]) - self.proposal.evaluate(this_samples[i])
this_weights[i] = _exp(tmp)
... | Calculate and save the weights of a run. |
def _get_samples(self, N, trace_sort):
# allocate an empty numpy array to store the run and append accept count
# (importance sampling accepts all points)
this_run = self.samples.append(N)
# store the proposed points (weights are still to be calculated)
if trace_sort:
... | Save N samples from ``self.proposal`` to ``self.samples``
This function does NOT calculate the weights.
Return a reference to this run's samples in ``self.samples``.
If ``trace_sort`` is True, additionally return an array
indicating the responsible component. (MixtureDensity only) |
def x_forwarded_for(self):
ip = self._request.META.get('REMOTE_ADDR')
current_xff = self.headers.get('X-Forwarded-For')
return '%s, %s' % (current_xff, ip) if current_xff else ip | X-Forwarded-For header value.
This is the amended header so that it contains the previous IP address
in the forwarding change. |
def _add_to_docstring(string):
'''Private wrapper function. Appends ``string`` to the
docstring of the wrapped function.
'''
def wrapper(method):
if method.__doc__ is not None:
method.__doc__ += string
else:
method.__doc__ = string
return method... | Private wrapper function. Appends ``string`` to the
docstring of the wrapped function. |
def _normalize_django_header_name(header):
# Remove HTTP_ prefix.
new_header = header.rpartition('HTTP_')[2]
# Camel case and replace _ with -
new_header = '-'.join(
x.capitalize() for x in new_header.split('_'))
return new_header | Unmunge header names modified by Django. |
def from_request(cls, request):
request_headers = HeaderDict()
other_headers = ['CONTENT_TYPE', 'CONTENT_LENGTH']
for header, value in iteritems(request.META):
is_header = header.startswith('HTTP_') or header in other_headers
normalized_header = cls._normalize_d... | Generate a HeaderDict based on django request object meta data. |
def filter(self, exclude):
filtered_headers = HeaderDict()
lowercased_ignore_list = [x.lower() for x in exclude]
for header, value in iteritems(self):
if header.lower() not in lowercased_ignore_list:
filtered_headers[header] = value
return filtered_... | Return a HeaderSet excluding the headers in the exclude list. |
def crps_gaussian(x, mu, sig, grad=False):
x = np.asarray(x)
mu = np.asarray(mu)
sig = np.asarray(sig)
# standadized x
sx = (x - mu) / sig
# some precomputations to speed up the gradient
pdf = _normpdf(sx)
cdf = _normcdf(sx)
pi_inv = 1. / np.sqrt(np.pi)
# the actual crps
... | Computes the CRPS of observations x relative to normally distributed
forecasts with mean, mu, and standard deviation, sig.
CRPS(N(mu, sig^2); x)
Formula taken from Equation (5):
Calibrated Probablistic Forecasting Using Ensemble Model Output
Statistics and Minimum CRPS Estimation. Gneiting, Rafte... |
def _discover_bounds(cdf, tol=1e-7):
class DistFromCDF(stats.distributions.rv_continuous):
def cdf(self, x):
return cdf(x)
dist = DistFromCDF()
# the ppf is the inverse cdf
lower = dist.ppf(tol)
upper = dist.ppf(1. - tol)
return lower, upper | Uses scipy's general continuous distribution methods
which compute the ppf from the cdf, then use the ppf
to find the lower and upper limits of the distribution. |
def crps_quadrature(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6):
return _crps_cdf(x, cdf_or_dist, xmin, xmax, tol) | Compute the continuously ranked probability score (CPRS) for a given
forecast distribution (cdf) and observation (x) using numerical quadrature.
This implementation allows the computation of CRPS for arbitrary forecast
distributions. If gaussianity can be assumed ``crps_gaussian`` is faster.
Parameter... |
def clear(self):
self._points = _np.empty( (self.prealloc,self.dim) )
self._slice_for_run_nr = []
self.memleft = self.prealloc | Deletes the history |
def partition(N, k):
'''Distribute ``N`` into ``k`` parts such that each part
takes the value ``N//k`` or ``N//k + 1`` where ``//`` denotes integer
division; i.e., perform the minimal lexicographic integer partition.
Example: N = 5, k = 2 --> return [3, 2]
'''
out = [N // k] * k
remainde... | Distribute ``N`` into ``k`` parts such that each part
takes the value ``N//k`` or ``N//k + 1`` where ``//`` denotes integer
division; i.e., perform the minimal lexicographic integer partition.
Example: N = 5, k = 2 --> return [3, 2] |
def dispatch(self, request, *args, **kwargs):
self.request = DownstreamRequest(request)
self.args = args
self.kwargs = kwargs
self._verify_config()
self.middleware = MiddlewareSet(self.proxy_middleware)
return self.proxy() | Dispatch all HTTP methods to the proxy. |
def proxy(self):
headers = self.request.headers.filter(self.ignored_request_headers)
qs = self.request.query_string if self.pass_query_string else ''
# Fix for django 1.10.0 bug https://code.djangoproject.com/ticket/27005
if (self.request.META.get('CONTENT_LENGTH', None) == '' ... | Retrieve the upstream content and build an HttpResponse. |
def shell_out(cmd, stderr=STDOUT, cwd=None):
if cwd is None:
from os import getcwd
cwd = getcwd() # TODO do I need to normalize this on Windows
out = check_output(cmd, cwd=cwd, stderr=stderr, universal_newlines=True)
return _clean_output(out) | Friendlier version of check_output. |
def shell_out_ignore_exitcode(cmd, stderr=STDOUT, cwd=None):
try:
return shell_out(cmd, stderr=stderr, cwd=cwd)
except CalledProcessError as c:
return _clean_output(c.output) | Same as shell_out but doesn't raise if the cmd exits badly. |
def from_dir(cwd):
"Context manager to ensure in the cwd directory."
import os
curdir = os.getcwd()
try:
os.chdir(cwd)
yield
finally:
os.chdir(curdirf from_dir(cwd):
"Context manager to ensure in the cwd directory."
import os
curdir = os.getcwd()
try:
... | Context manager to ensure in the cwd directory. |
def merge_function_with_indicator(function, indicator, alternative):
'''Returns a function such that a call to it is equivalent to:
if indicator(x):
return function(x)
else:
return alternative
Note that ``function`` is not called if indicator evaluates to False.
:param function:
... | Returns a function such that a call to it is equivalent to:
if indicator(x):
return function(x)
else:
return alternative
Note that ``function`` is not called if indicator evaluates to False.
:param function:
The function to be called when indicator returns True.
:param ... |
def text_filter(regex_base, value):
from thumbnails import get_thumbnail
regex = regex_base % {
'caption': '[a-zA-Z0-9\.\,:;/_ \(\)\-\!\?\"]+',
'image': '[a-zA-Z0-9\.:/_\-\% ]+'
}
images = re.findall(regex, value)
for i in images:
image_url = i[1]
image = get_th... | A text-filter helper, used in ``markdown_thumbnails``-filter and ``html_thumbnails``-filter.
It can be used to build custom thumbnail text-filters.
:param regex_base: A string with a regex that contains ``%(captions)s`` and ``%(image)s`` where
the caption and image should be.
:param ... |
def eat(self, argv=None):
# The setup phase, here KeyboardInterrupt is a silent sign to exit the
# application. Any error that happens here will result in a raw
# backtrace being printed to the user.
try:
self.context.argv = argv
self._added()
... | Eat the guacamole.
:param argv:
Command line arguments or None. None means that sys.argv is used
:return:
Whatever is returned by the first ingredient that agrees to perform
the command dispatch.
The eat method is called to run the application, as if it was ... |
def _dispatch(self):
for ingredient in self.ingredients:
result = ingredient.dispatch(self.context)
if result is not None:
return result | Run the dispatch() method on all ingredients. |
def clear(self):
self.sampler.clear()
self.samples_list = self._comm.gather(self.sampler.samples, root=0)
if hasattr(self.sampler, 'weights'):
self.weights_list = self._comm.gather(self.sampler.weights, root=0)
else:
self.weights_list = None | Delete the history. |
def path(self, path):
if os.path.isabs(path):
return path
return os.path.join(self.location, path) | Creates a path based on the location attribute of the backend and the path argument
of the function. If the path argument is an absolute path the path is returned.
:param path: The path that should be joined with the backends location. |
def kullback_leibler(c1, c2):
d = c2.log_det_sigma - c1.log_det_sigma
d += np.trace(c2.inv_sigma.dot(c1.sigma))
mean_diff = c1.mu - c2.mu
d += mean_diff.transpose().dot(c2.inv_sigma).dot(mean_diff)
d -= len(c1.mu)
return 0.5 * d | Kullback Leibler divergence of two Gaussians, :math:`KL(1||2)` |
def _cleanup(self, kill, verbose):
if kill:
removed_indices = self.g.prune()
self.nout -= len(removed_indices)
if verbose and removed_indices:
print('Removing %s' % removed_indices)
for j in removed_indices:
self.inv_map... | Look for dead components (weight=0) and remove them
if enabled by ``kill``.
Resize storage. Recompute determinant and covariance. |
def _distance(self):
return np.average(self.min_kl, weights=self.f.weights) | Compute the distance function d(f,g,\pi), Eq. (3) |
def _refit(self):
# temporary variables for manipulation
mu_diff = np.empty_like(self.f.components[0].mu)
sigma = np.empty_like(self.f.components[0].sigma)
mean = np.empty_like(mu_diff)
cov = np.empty_like(sigma)
for j, c in enumerate(self.g.components)... | Update the map :math:`\pi` keeping the output :math:`g` fixed
Use Eq. (7) and below in [GR04]_ |
def _regroup(self):
# clean up old maps
for j in range(self.nout):
self.inv_map[j] = []
# find smallest divergence between input component i
# and output component j of the cluster mixture density
for i in range(self.nin):
self.min_kl[i] = np.inf... | Update the output :math:`g` keeping the map :math:`\pi` fixed.
Compute the KL between all input and output components. |
def run(self, eps=1e-4, kill=True, max_steps=50, verbose=False):
r
old_distance = np.finfo(np.float64).max
new_distance = np.finfo(np.float64).max
if verbose:
print('Starting hierarchical clustering with %d components.' % len(self.g.components))
converged = False
... | r"""Perform the clustering on the input components updating the initial
guess. The result is available in the member ``self.g``.
Return the number of iterations at convergence, or None.
:param eps:
If relative change of distance between current and last step falls below ``eps``,
... |
def eventdata(payload):
headerinfo, data = payload.split('\n', 1)
headers = get_headers(headerinfo)
return headers, data | Parse a Supervisor event. |
def supervisor_events(stdin, stdout):
while True:
stdout.write('READY\n')
stdout.flush()
line = stdin.readline()
headers = get_headers(line)
payload = stdin.read(int(headers['len']))
event_headers, event_data = eventdata(payload)
yield event_headers, ... | An event stream from Supervisor. |
def main():
env = os.environ
try:
host = env['SYSLOG_SERVER']
port = int(env['SYSLOG_PORT'])
socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \
else socket.SOCK_STREAM
except KeyError:
sys.exit("SYSLOG_SERVER, SYSLOG_PORT and SYSLOG_PROTO are re... | Main application loop. |
def formatTime(self, record, datefmt=None):
formatted = super(PalletFormatter, self).formatTime(
record, datefmt=datefmt)
return formatted + '.%03dZ' % record.msecs | Format time, including milliseconds. |
def modified_lines_from_udiff(udiff):
chunks = re.split('\n@@ [^\n]+\n', udiff)[1:]
line_numbers = re.findall('@@\s[+-]\d+,\d+ \+(\d+)', udiff)
line_numbers = list(map(int, line_numbers))
for c, start in zip(chunks, line_numbers):
ilines = enumerate((line for line in c.splitlines()
... | Extract from a udiff an iterator of tuples of (start, end) line
numbers. |
def get_diff(original, fixed, file_name,
original_label='original', fixed_label='fixed'):
original, fixed = original.splitlines(True), fixed.splitlines(True)
newline = '\n'
from difflib import unified_diff
diff = unified_diff(original, fixed,
os.path.join(origi... | Return text of unified diff between original and fixed. |
def print_diff(diff, color=True):
import colorama
if not diff:
return
if not color:
colorama.init = lambda autoreset: None
colorama.Fore.RED = ''
colorama.Back.RED = ''
colorama.Fore.GREEN = ''
colorama.deinit = lambda: None
colorama.init(autoreset... | Pretty printing for a diff, if color then we use a simple color scheme
(red for removed lines, green for added lines). |
def _get_log_rho_metropolis_hastings(self, proposed_point, proposed_eval):
return self._get_log_rho_metropolis(proposed_point, proposed_eval)\
- self.proposal.evaluate (proposed_point, self.current) \
+ self.proposal.evaluate (self.current, proposed_point) | calculate log(metropolis ratio times hastings factor) |
def _update_scale_factor(self, accept_rate):
'''Private function.
Updates the covariance scaling factor ``covar_scale_factor``
according to its limits
'''
if accept_rate > self.force_acceptance_max and self.covar_scale_factor < self.covar_scale_factor_max:
self.covar... | Private function.
Updates the covariance scaling factor ``covar_scale_factor``
according to its limits |
def get_thumbnail(self, original, size, crop, options):
try:
image = self.create(original, size, crop, options)
except ThumbnailError:
image = None
finally:
self.cleanup(original)
return image | Wrapper for .create() with cleanup.
:param original:
:param size:
:param crop:
:param options:
:return: An image object |
def create(self, original, size, crop, options=None):
if options is None:
options = self.evaluate_options()
image = self.engine_load_image(original)
image = self.scale(image, size, crop, options)
crop = self.parse_crop(crop, self.get_image_size(image), size)
... | Creates a thumbnail. It loads the image, scales it and crops it.
:param original:
:param size:
:param crop:
:param options:
:return: |
def scale(self, image, size, crop, options):
original_size = self.get_image_size(image)
factor = self._calculate_scaling_factor(original_size, size, crop is not None)
if factor < 1 or options['scale_up']:
width = int(original_size[0] * factor)
height = int(origi... | Wrapper for ``engine_scale``, checks if the scaling factor is below one or that scale_up
option is set to True before calling ``engine_scale``.
:param image:
:param size:
:param crop:
:param options:
:return: |
def crop(self, image, size, crop, options):
if not crop:
return image
return self.engine_crop(image, size, crop, options) | Wrapper for ``engine_crop``, will return without calling ``engine_crop`` if crop is None.
:param image:
:param size:
:param crop:
:param options:
:return: |
def colormode(self, image, options):
mode = options['colormode']
return self.engine_colormode(image, mode) | Wrapper for ``engine_colormode``.
:param image:
:param options:
:return: |
def parse_size(size):
if size.startswith('x'):
return None, int(size.replace('x', ''))
if 'x' in size:
return int(size.split('x')[0]), int(size.split('x')[1])
return int(size), None | Parses size string into a tuple
:param size: String on the form '100', 'x100 or '100x200'
:return: Tuple of two integers for width and height
:rtype: tuple |
def parse_crop(self, crop, original_size, size):
if crop is None:
return None
crop = crop.split(' ')
if len(crop) == 1:
crop = crop[0]
x_crop = 50
y_crop = 50
if crop in CROP_ALIASES['x']:
x_crop = CROP_ALIASES... | Parses crop into a tuple usable by the crop function.
:param crop: String with the crop settings.
:param original_size: A tuple of size of the image that should be cropped.
:param size: A tuple of the wanted size.
:return: Tuple of two integers with crop settings
:rtype: tuple |
def calculate_offset(percent, original_length, length):
return int(
max(
0,
min(percent * original_length / 100.0, original_length - length / 2) - length / 2)
) | Calculates crop offset based on percentage.
:param percent: A percentage representing the size of the offset.
:param original_length: The length the distance that should be cropped.
:param length: The desired length.
:return: The offset in pixels
:rtype: int |
def get_app_template_dir(app_name):
if app_name in _cache:
return _cache[app_name]
template_dir = None
for app in settings.INSTALLED_APPS:
if app.split('.')[-1] == app_name:
# Do not hide import errors; these should never happen at this
# point anyway
... | Get the template directory for an application
We do not use django.db.models.get_app, because this will fail if an
app does not have any models.
Returns a full path, or None if the app was not found. |
def get_template_sources(self, template_name, template_dirs=None):
if ':' not in template_name:
return []
app_name, template_name = template_name.split(":", 1)
template_dir = get_app_template_dir(app_name)
if template_dir:
return [get_template_path(templa... | Return the absolute paths to "template_name" in the specified app
If the name does not contain an app name (no colon), an empty list
is returned.
The parent FilesystemLoader.load_template_source() will take care
of the actual loading for us. |
def parse_arguments():
parser = argparse.ArgumentParser(prog=sys.argv[0],
description='Send Webhooks Channel events to IFTTT',
epilog='Visit https://ifttt.com/channels/maker_webhooks for more information')
parser.add_argument('--ver... | Parse command line arguments |
def main():
args = parse_arguments()
if args.key is None:
print("Error: Must provide IFTTT secret key.")
sys.exit(1)
try:
res = pyfttt.send_event(api_key=args.key, event=args.event,
value1=args.value1, value2=args.value2,
... | Main function for pyfttt command line tool |
def import_string(dotted_path):
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
raise ImportError('%s doesn\'t look like a valid path' % dotted_path)
module = __import__(module_path, fromlist=[class_name])
try:
return getattr(module, class_name... | Import a dotted module path.
Returns the attribute/class designated by the last name in the path.
Raises ImportError if the import fails. |
def argsort_indices(a, axis=-1):
a = np.asarray(a)
ind = list(np.ix_(*[np.arange(d) for d in a.shape]))
ind[axis] = a.argsort(axis)
return tuple(ind) | Like argsort, but returns an index suitable for sorting the
the original array even if that array is multidimensional |
def send_event(api_key, event, value1=None, value2=None, value3=None):
url = 'https://maker.ifttt.com/trigger/{e}/with/key/{k}/'.format(e=event,
k=api_key)
payload = {'value1': value1, 'value2': value2, 'value3': value3}
return reque... | Send an event to the IFTTT maker channel
Parameters:
-----------
api_key : string
Your IFTTT API key
event : string
The name of the IFTTT event to trigger
value1 :
Optional: Extra data sent with the event (default: None)
value2 :
Optional: Extra data sent with th... |
def get_localized_docstring(obj, domain):
if obj.__class__.__doc__ is not None:
return inspect.cleandoc(
gettext.dgettext(domain, obj.__class__.__doc__)) | Get a cleaned-up, localized copy of docstring of this class. |
def get_cmd_help(self):
try:
return self.help
except AttributeError:
pass
try:
return get_localized_docstring(
self, self.get_gettext_domain()
).splitlines()[0].rstrip('.').lower()
except (AttributeError, IndexError... | Get the single-line help of this command.
:returns:
``self.help``, if defined
:returns:
The first line of the docstring, without the trailing dot, if
present.
:returns:
None, otherwise |
def get_cmd_description(self):
try:
return self.description
except AttributeError:
pass
try:
return '\n'.join(
get_localized_docstring(
self, self.get_gettext_domain()
).splitlines()[1:]
... | Get the leading, multi-line description of this command.
:returns:
``self.description``, if defined
:returns:
A substring of the class docstring between the first line (which
is discarded) and the string ``@EPILOG@``, if present, or the end
of the docstri... |
def get_cmd_epilog(self):
try:
return self.source.epilog
except AttributeError:
pass
try:
return '\n'.join(
get_localized_docstring(
self, self.get_gettext_domain()
).splitlines()[1:]
).s... | Get the trailing, multi-line description of this command.
:returns:
``self.epilog``, if defined
:returns:
A substring of the class docstring between the string ``@EPILOG``
and the end of the docstring, if defined
:returns:
None, otherwise
... |
def main(self, argv=None, exit=True):
return CommandRecipe(self).main(argv, exit) | Shortcut for running a command.
See :meth:`guacamole.recipes.Recipe.main()` for details. |
def get_ingredients(self):
return [
cmdtree.CommandTreeBuilder(self.command),
cmdtree.CommandTreeDispatcher(),
argparse.AutocompleteIngredient(),
argparse.ParserIngredient(),
crash.VerboseCrashHandler(),
ansi.ANSIIngredient(),
... | Get a list of ingredients for guacamole. |
def register_arguments(self, parser):
parser.add_argument('x', type=int, help='the first value')
parser.add_argument('y', type=int, help='the second value') | Guacamole method used by the argparse ingredient.
:param parser:
Argument parser (from :mod:`argparse`) specific to this command. |
def invoked(self, ctx):
print("{} + {} = {}".format(
ctx.args.x,
ctx.args.y,
ctx.args.x + ctx.args.y)) | Guacamole method used by the command ingredient.
:param ctx:
The guacamole context object. Context provides access to all
features of guacamole. The argparse ingredient adds the ``args``
attribute to it. That attribute contains the result of parsing
command line ... |
def hsv(h, s, v):
if 360 < h < 0:
raise ValueError("h out of range: {}".format(h))
if 1 < s < 0:
raise ValueError("s out of range: {}".format(h))
if 1 < v < 0:
raise ValueError("v out of range: {}".format(h))
c = v * s # chroma
h1 = h / 60
x = c * (1 - abs(h1 % 2 - ... | Convert HSV (hue, saturation, value) to RGB. |
def invoked(self, ctx):
if not ctx.ansi.is_enabled:
print("You need color support to use this demo")
else:
print(ctx.ansi.cmd('erase_display'))
self._demo_fg_color(ctx)
self._demo_bg_color(ctx)
self._demo_bg_indexed(ctx)
se... | Method called when the command is invoked. |
def get(self, thumbnail_name):
if isinstance(thumbnail_name, list):
thumbnail_name = '/'.join(thumbnail_name)
return self._get(thumbnail_name) | Wrapper for ``_get``, which converts the thumbnail_name to String if necessary before
calling ``_get``
:rtype: Thumbnail |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.