code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Do not override this method! context = context or Context() for imp in self.imports: if imp not in context.imports: context.imports.append(imp) counter = Counter() lines = list(self.to_lines(context=context, counter=counter)) if c...
def to_code(self, context: Context =None)
Generate the code and return it as a string.
5.145258
4.555245
1.129524
if locals is None: locals = {} builtins.exec(self.to_code(), globals, locals) return locals
def exec(self, globals=None, locals=None)
Execute simple code blocks. Do not attempt this on modules or other blocks where you have imports as they won't work. Instead write the code to a file and use runpy.run_path()
4.542277
5.438185
0.835256
assert "name" not in kwargs kwargs.setdefault("code", self) code = CodeBlock(**kwargs) for block in blocks: if block is not None: code._blocks.append((0, block)) return code
def block(self, *blocks, **kwargs) -> "CodeBlock"
Build a basic code block. Positional arguments should be instances of CodeBlock or strings. All code blocks passed as positional arguments are added at indentation level 0. None blocks are skipped.
4.516434
4.063749
1.111396
code = self.block(f"{name} = {{}}") for p in params: code.add( self.block(f"if {p.name} is not {not_specified_literal}:").of( f"{name}[{p.name!r}] = {p.name}" ), ) return code
def dict_from_locals(self, name, params: List[Parameter], not_specified_literal=Constants.VALUE_NOT_SET)
Generate code for a dictionary of locals whose value is not the specified literal.
3.951924
3.395138
1.163995
if str(self.config.build_dir) not in sys.path: sys.path.append(str(self.config.build_dir)) return importlib.import_module(self.config.target_package)
def import_generated_autoboto(self)
Imports the autoboto package generated in the build directory (not target_dir). For example: autoboto = botogen.import_generated_autoboto()
3.23608
3.092787
1.046331
if str(self.config.build_dir) not in sys.path: sys.path.append(str(self.config.build_dir)) return importlib.import_module(f"{self.config.target_package}.{name}")
def import_generated_autoboto_module(self, name)
Imports a module from the generated autoboto package in the build directory (not target_dir). For example, to import autoboto.services.s3.shapes, call: botogen.import_generated_autoboto_module("services.s3.shapes")
3.032438
3.265425
0.92865
result = self.raw_request.get( 'search', query={'project': project, 'text': text} ) result = result.json() search_result = SearchResult() search_result.tasks = self.tasks.parse_list(result['tasks']) search_result.issues = self.issues.parse_list(result...
def search(self, project, text='')
Search in your Taiga.io instance :param project: the project id :param text: the query of your search
2.409602
2.340778
1.029402
headers = { 'Content-type': 'application/json' } payload = { 'type': self.auth_type, 'username': username, 'password': password } try: full_url = utils.urljoin(self.host, '/api/v1/auth') response = r...
def auth(self, username, password)
Authenticate you :param username: your username :param password: your password
2.71555
2.843632
0.954958
headers = { 'Content-type': 'application/json' } payload = { 'application': app_id, 'auth_code': auth_code, 'state': state } try: full_url = utils.urljoin( self.host, '/api/v1/app...
def auth_app(self, app_id, app_secret, auth_code, state='')
Authenticate an app :param app_id: the app id :param app_secret: the app secret :param auth_code: the app auth code
2.6843
2.761106
0.972183
data_headers = [] num_created = 0 num_updated = 0 for line in lines_iterator: line = line.decode() if line[0] == "#": if line[0:4] == "#ISO": data_headers = line.strip('# ').split('\t') if data_headers != DATA_HEADERS_ORDERED: ...
def parse_geonames_data(lines_iterator)
Parses countries table data from geonames.org, updating or adding records as needed. currency_symbol is not part of the countries table and is supplemented using the data obtained from the link provided in the countries table. :type lines_iterator: collections.iterable :return: num_updated: int, num_cre...
2.86219
2.615243
1.094426
members = collections.OrderedDict() required_names = self.metadata.get("required", ()) for name, shape in self.members.items(): members[name] = AbShapeMember(name=name, shape=shape, is_required=name in required_names) if self.is_output_shape: # ResponseM...
def sorted_members(self)
Iterate over sorted members of shape in the same order in which the members are declared except yielding the required members before any optional members.
4.436006
4.052309
1.094686
self.frontends = [] self.backends = [] self.listeners = [] csv = [ l for l in self._fetch().strip(' #').split('\n') if l ] if self.failed: return #read fields header to create keys self.fields = [ f for f in csv.pop(0).split(',') if f ] ...
def update(self)
Fetch and parse stats
4.541414
4.276963
1.061831
if value.isdigit(): return int(value) if isinstance(value, bytes): return value.decode('utf-8') else: return value
def _decode(value)
decode byte strings and convert to int where needed
3.039093
2.493762
1.218678
ext, rndr = make_flags(**options) if renderer: md = misaka.Markdown(renderer,ext) result = md(text) else: result = misaka.html(text, extensions=ext, render_flags=rndr) if options.get("smartypants"): result = misaka.smartypants(result) return Markup(result)
def markdown(text, renderer=None, **options)
Parses the provided Markdown-formatted text into valid HTML, and returns it as a :class:`flask.Markup` instance. :param text: Markdown-formatted text to be rendered into HTML :param renderer: A custom misaka renderer to be used instead of the default one :param options: Additional options for customizi...
5.254102
5.580887
0.941446
options = self.defaults if overrides: options = copy(options) options.update(overrides) return markdown(text, self.renderer, **options)
def render(self, text, **overrides)
It delegates to the :func:`markdown` function, passing any default options or renderer set in the :meth:`__init__` method. The ``markdown`` template filter calls this method. :param text: Markdown-formatted text to be rendered to HTML :param overrides: Additional options which may over...
5.534892
7.093962
0.780226
if not issubclass(cls, Enum): raise TypeError('caseinsensitive decorator can only be applied to subclasses of enum.Enum') enum_options = getattr(cls, PYCKSON_ENUM_OPTIONS, {}) enum_options[ENUM_CASE_INSENSITIVE] = True setattr(cls, PYCKSON_ENUM_OPTIONS, enum_options) return cls
def caseinsensitive(cls)
Annotation function to set an Enum to be case insensitive on parsing
3.434087
3.14507
1.091895
try: from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandL...
def win32_utf8_argv()
Uses shell32.GetCommandLineArgvW to get sys.argv as a list of UTF-8 strings. Versions 2.5 and older of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'. Returns None on failure. Example usage: >>> def ma...
1.743731
1.779542
0.979876
digests = {"hex": binascii.b2a_hex, "base64": binascii.b2a_base64, "hqx": binascii.b2a_hqx} digestor = digests.get(digest) if not digestor: TripleSecError(u"Digestor not supported.") binary_result = self.encrypt(data, key, v, ex...
def encrypt_ascii(self, data, key=None, v=None, extra_bytes=0, digest="hex")
Encrypt data and return as ascii string. Hexadecimal digest as default. Avaiable digests: hex: Hexadecimal base64: Base 64 hqx: hexbin4
3.333949
3.516923
0.947973
digests = {"hex": binascii.a2b_hex, "base64": binascii.a2b_base64, "hqx": binascii.a2b_hqx} digestor = digests.get(digest) if not digestor: TripleSecError(u"Digestor not supported.") binary_string = digestor(ascii_string) ...
def decrypt_ascii(self, ascii_string, key=None, digest="hex")
Receive ascii string and return decrypted data. Avaiable digests: hex: Hexadecimal base64: Base 64 hqx: hexbin4
3.202763
3.38419
0.94639
r = self.search_movie(title) return self._match_results(r, title, year)
def resolve_movie(self, title, year=None)
Tries to find a movie with a given title and year
7.625286
9.171014
0.831455
r = self.search_tv_show(title) return self._match_results(r, title, year)
def resolve_tv_show(self, title, year=None)
Tries to find a movie with a given title and year
6.720861
7.402375
0.907933
'''Calculate the Gelman-Rubin R value (Chapter 2.2 in [GR92]_). The R value can be used to quantify mixing of "multiple iterative simulations" (e.g. Markov Chains) in parameter space. An R value "close to one" indicates that all chains explored the same region of the parameter. .. note:: ...
def r_value(means, variances, n, approx=False)
Calculate the Gelman-Rubin R value (Chapter 2.2 in [GR92]_). The R value can be used to quantify mixing of "multiple iterative simulations" (e.g. Markov Chains) in parameter space. An R value "close to one" indicates that all chains explored the same region of the parameter. .. note:: Th...
4.607077
3.110675
1.481054
'''Group ``m`` (Markov) chains whose common :py:func:`.r_value` is less than ``critical_r`` in each of the D dimensions. :param means: (m x D) Matrix-like array; the mean value estimates. :param variances: (m x D) Matrix-like array; the variance estimates. ''' assert len(mea...
def r_group(means, variances, n, critical_r=2., approx=False)
Group ``m`` (Markov) chains whose common :py:func:`.r_value` is less than ``critical_r`` in each of the D dimensions. :param means: (m x D) Matrix-like array; the mean value estimates. :param variances: (m x D) Matrix-like array; the variance estimates.
3.202267
2.236232
1.431993
'''Helper function for :py:func:`.make_r_gaussmix` and :py:func:`.make_r_tmix`. Group the ``data`` according to the R value and split each group into ``K_g`` patches. Return the patch means and covariances. For details see the docstrings of the above mentioned functions. ''' def append_comp...
def _make_r_patches(data, K_g, critical_r, indices, approx)
Helper function for :py:func:`.make_r_gaussmix` and :py:func:`.make_r_tmix`. Group the ``data`` according to the R value and split each group into ``K_g`` patches. Return the patch means and covariances. For details see the docstrings of the above mentioned functions.
4.05372
3.32465
1.219292
'''Use ``data`` from multiple "Iterative Simulations" (e.g. Markov Chains) to form a Gaussian Mixture. This approach refers to the "long patches" in [BC13]_. The idea is to group chains according to their R-value as in :py:func:`.r_group` and form ``K_g`` Gaussian Components per chain group. On...
def make_r_gaussmix(data, K_g=15, critical_r=2., indices=None, approx=False)
Use ``data`` from multiple "Iterative Simulations" (e.g. Markov Chains) to form a Gaussian Mixture. This approach refers to the "long patches" in [BC13]_. The idea is to group chains according to their R-value as in :py:func:`.r_group` and form ``K_g`` Gaussian Components per chain group. Once the ...
8.035106
1.248231
6.437195
'''Use ``data`` from multiple "Iterative Simulations" (e.g. Markov Chains) to form a Student t Mixture. This approach refers to the "long patches" in [BC13]_. The idea is to group chains according to their R-value as in :py:func:`.r_group` and form ``K_g`` Student t Components per chain group. ...
def make_r_tmix(data, K_g=15, critical_r=2., dof=5., indices=None, approx=False)
Use ``data`` from multiple "Iterative Simulations" (e.g. Markov Chains) to form a Student t Mixture. This approach refers to the "long patches" in [BC13]_. The idea is to group chains according to their R-value as in :py:func:`.r_group` and form ``K_g`` Student t Components per chain group. Once th...
7.556301
1.677652
4.504094
filename = os.path.join(os.path.dirname(__file__), "data", "heroes.json") with open(filename) as f: heroes = json.loads(f.read())["result"]["heroes"] for hero in heroes: HEROES_CACHE[hero["id"]] = hero
def load_heroes()
Load hero details from JSON file into memoy
2.472553
2.318966
1.066231
filename = os.path.join(os.path.dirname(__file__), "data", "items.json") with open(filename) as f: items = json.loads(f.read())["result"]["items"] for item in items: ITEMS_CACHE[item["id"]] = item
def load_items()
Load item details fom JSON file into memory
2.914953
2.60521
1.118894
context.cmd_tree = self._build_cmd_tree(self.command) context.cmd_toplevel = context.cmd_tree.cmd_obj # Collect spices from the top-level command for spice in context.cmd_toplevel.get_cmd_spices(): context.bowl.add_spice(spice)
def added(self, context)
Ingredient method called before anything else. Here this method just builds the full command tree and stores it inside the context as the ``cmd_tree`` attribute. The structure of the tree is explained by the :func:`build_cmd_tree()` function.
7.363873
6.244187
1.179316
if isinstance(cmd_cls, type): cmd_obj = cmd_cls() else: cmd_obj = cmd_cls if cmd_name is None: cmd_name = cmd_obj.get_cmd_name() return cmd_tree_node(cmd_name, cmd_obj, tuple([ self._build_cmd_tree(subcmd_cls, subcmd_name) ...
def _build_cmd_tree(self, cmd_cls, cmd_name=None)
Build a tree of commands. :param cmd_cls: The Command class or object to start with. :param cmd_name: Hard-coded name of the command (can be None for auto-detection) :returns: A tree structure represented as tuple ``(cmd_obj, cmd_name, childre...
2.299725
2.517445
0.913516
global index index += 1 with open("%s_%s.dump" % (file_prefix, index), 'w') as f: f.write(message.SerializeToString()) f.close()
def debug_dump(message, file_prefix="dump")
Utility while developing to dump message data to play with in the interpreter
3.707647
3.878578
0.95593
t = player.team if invert: t = not player.team return getattr(player, "%s_%s" % ("goodguy" if t else "badguy", attr))
def get_side_attr(attr, invert, player)
Get a player attribute that depends on which side the player is on. A creep kill for a radiant hero is a badguy_kill, while a creep kill for a dire hero is a goodguy_kill.
6.410164
4.273097
1.500122
self.creep_kill_types[target] += 1 matched = False for k, v in self.creep_types.iteritems(): if target.startswith(k): matched = True setattr(self, v, getattr(self, v) + 1) break if not matched: print('> un...
def creep_kill(self, target, timestamp)
A creep was tragically killed. Need to split this into radiant/dire and neutrals
4.440986
4.07206
1.090599
aegises = deque(self.aegis) next_aegis = aegises.popleft() if aegises else None aegis_expires = None active_aegis = None real_kills = [] for kill in self.kills: if next_aegis and next_aegis[0] < kill["tick"]: active_aegis = next_ae...
def calculate_kills(self)
At the end of the game calculate kills/deaths, taking aegis into account This has to be done at the end when we have a playerid : hero map
3.304586
3.120301
1.05906
if event.chat and event.format == "DOTA_Chat_All": self.chatlog.append((event.prefix, event.text))
def parse_say_text(self, event)
All chat
15.573889
13.237707
1.176479
if event.type == dota_usermessages_pb2.CHAT_MESSAGE_AEGIS: self.aegis.append((self.tick, event.playerid_1))
def parse_dota_um(self, event)
The chat messages that arrive when certain events occur. The most useful ones are CHAT_MESSAGE_RUNE_PICKUP, CHAT_MESSAGE_RUNE_BOTTLE, CHAT_MESSAGE_GLYPH_USED, CHAT_MESSAGE_TOWER_KILL
13.062158
10.104864
1.29266
if not player.ishltv: self.player_info[player.name] = { "user_id": player.userID, "guid": player.guid, "bot": player.fakeplayer, }
def parse_player_info(self, player)
Parse a PlayerInfo struct. This arrives before a FileInfo message
8.972805
8.272259
1.084686
self.info["playback_time"] = file_info.playback_time self.info["match_id"] = file_info.game_info.dota.match_id self.info["game_mode"] = file_info.game_info.dota.game_mode self.info["game_winner"] = file_info.game_info.dota.game_winner for index, player in enumerate(fil...
def parse_file_info(self, file_info)
The CDemoFileInfo contains our winners as well as the length of the demo
3.023142
2.980223
1.014401
if ge.name == "dota_combatlog": if ge.keys["type"] == 4: #Something died try: source = self.dp.combat_log_names.get(ge.keys["sourcename"], "unknown") target = s...
def parse_game_event(self, ge)
Game events contain the combat log as well as 'chase_hero' events which could be interesting
4.347062
4.302851
1.010275
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): try: with codecs.open(file_name, 'r', encoding='utf-8') as f: original = f.read() ...
def fix_file(file_name, line_ranges, options=None, in_place=False, diff=False, verbose=0, cwd=None)
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.
3.429193
3.595231
0.953817
'''Apply autopep8 over the line_ranges, returns the corrected code. Note: though this is not checked for line_ranges should not overlap. Example ------- >>> code = "def f( x ):\\n if True:\\n return 2*x" >>> print(fix_code(code, [(1, 1), (3, 3)])) def f(x): if True: r...
def fix_code(source_code, line_ranges, options=None, verbose=0)
Apply autopep8 over the line_ranges, returns the corrected code. Note: though this is not checked for line_ranges should not overlap. Example ------- >>> code = "def f( x ):\\n if True:\\n return 2*x" >>> print(fix_code(code, [(1, 1), (3, 3)])) def f(x): if True: return 2...
5.299944
3.352699
1.5808
# 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: from docformatter import format_code fix...
def fix_line_range(source_code, start, end, options)
Apply autopep8 (and docformatter) between the lines start and end of source.
4.637673
4.349769
1.066188
if min_ <= verbose <= max_: import sys print(something_to_print, end=end) sys.stdout.flush()
def _maybe_print(something_to_print, end=None, min_=1, max_=99, verbose=0)
Print if verbose is within min_ and max_.
2.795554
2.642721
1.057831
return RadiusFromDiff(diff=diff, options=options, cwd=cwd)
def from_diff(diff, options=None, cwd=None)
Create a Radius object from a diff rather than a reposistory.
11.169127
4.636683
2.408861
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 enumerate(self.f...
def fix(self)
Runs fix_file on each modified file. - Prints progress and diff depending on options. - Returns True if there were any changes
3.566704
3.497406
1.019814
# 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_place=self.in_place, diff=True, ...
def fix_file(self, file_name)
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.
7.886237
7.237293
1.089667
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
def version()
Return version string.
3.923524
3.716041
1.055834
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
def multi_evaluate(self, x, out=None)
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...
2.352802
2.900235
0.811245
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-8")), ...
def url_map(base, params)
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
3.11802
3.199515
0.974529
params = params or {} params["key"] = key or API_KEY params["language"] = language if not params["key"]: raise ValueError("API key not set, please set DOTA2_API_KEY") url = url_map("%s%s/%s/" % (base or BASE_URL, name, version), params) return fetcher(url)
def make_request(name, params=None, version="V001", key=None, api_type="web", fetcher=get_page, base=None, language="en_us")
Make an API request
3.735904
3.848835
0.970658
@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
def json_request_response(f)
Parse the JSON from an API response. We do this in a decorator so that our Twisted library can reuse the underlying functions
2.516483
2.585076
0.973466
params = { "start_at_match_id": start_at_match_id, "player_name": player_name, "hero_id": hero_id, "skill": skill, "date_min": date_min, "date_max": date_max, "account_id": account_id, "league_id": league_id, "matches_requested": matches_...
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
1.337417
1.371538
0.975122
params = { "start_at_match_seq_num": start_at_match_seq_num, "matches_requested": matches_requested } return make_request("GetMatchHistoryBySequenceNum", params, **kwargs)
def get_match_history_by_sequence_num(start_at_match_seq_num, matches_requested=None, **kwargs)
Most recent matches ordered by sequence number
2.582082
2.541245
1.01607
params = {"vanityurl": vanityurl} return make_request("ResolveVanityURL", params, version="v0001", base="http://api.steampowered.com/ISteamUser/", **kwargs)
def get_steam_id(vanityurl, **kwargs)
Get a players steam id from their steam name/vanity url
4.714327
4.467318
1.055293
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 make_request("GetPlayerSummaries", params, ve...
def get_player_summaries(players, **kwargs)
Get players steam profile from their steam ids
3.379026
3.007411
1.123566
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 "http://media.steampowered.com/apps/dota2/images/hero...
def get_hero_image_url(hero_name, image_size="lg")
Get a hero image based on name and image size
2.863358
2.833582
1.010508
middleware = list(middleware or HttpProxy.proxy_middleware) middleware += list(append_middleware or []) return type('ProxyClass', (HttpProxy,), { 'base_url': base_url, 'reverse_urls': [(prefix, base_url)], 'verify_ssl': verify_ssl, 'proxy_middleware': middleware, ...
def generate_proxy( prefix, base_url='', verify_ssl=True, middleware=None, append_middleware=None, cert=None, timeout=None)
Generate a ProxyClass based view that uses the passed base_url.
3.410375
2.949243
1.156356
routes = [] for name, config in iteritems(config): pattern = r'^%s(?P<url>.*)$' % re.escape(config['prefix'].lstrip('/')) proxy = generate_proxy( prefix=config['prefix'], base_url=config['base_url'], verify_ssl=config.get('verify_ssl', True), middleware=...
def generate_routes(config)
Generate a list of urls that map to generated proxy views. generate_routes({ 'test_proxy': { 'base_url': 'https://google.com/', 'prefix': '/test_prefix/', 'verify_ssl': False, 'csrf_exempt: False', 'middleware': ['djproxy.proxy_middleware.AddXFF']...
3.189204
2.313197
1.378699
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]') observations = np.asarray(observations) if...
def brier_score(observations, forecasts)
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 ...
2.820771
2.86339
0.985116
observations = np.asarray(observations) threshold = np.asarray(threshold) forecasts = np.asarray(forecasts) if axis != -1: forecasts = move_axis_to_end(forecasts, axis) if forecasts.shape == observations.shape: forecasts = forecasts[..., np.newaxis] if observations.shape ...
def threshold_brier_score(observations, forecasts, threshold, issorted=False, axis=-1)
Calculate the Brier scores of an ensemble for exceeding given thresholds. According to the threshold decomposition of CRPS, the resulting Brier scores can thus be summed along the last axis to calculate CRPS, as .. math:: CRPS(F, x) = \int_z BS(F(z), H(z - x)) dz where $F(x) = \int_{z \leq x}...
2.660462
2.855045
0.931846
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('separators', (',', ': ')) ...
def dumps(*args, **kwargs)
Wrapper for json.dumps that uses the JSONArgonautsEncoder.
3.488933
2.391369
1.458969
# 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
def format(self, record)
Overridden method that applies SGR codes to log messages.
9.181499
7.36591
1.246485
self._expose_argparse = context.bowl.has_spice("log:arguments") self.configure_logging(context)
def added(self, 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.
66.323532
48.474396
1.368218
fmt = "%(name)-12s: %(levelname)-8s %(message)s" formatter = ANSIFormatter(context, fmt) handler = logging.StreamHandler() handler.setFormatter(formatter) logging.root.addHandler(handler)
def configure_logging(self, context)
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...
3.154137
2.667458
1.18245
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.info("Enabled tracing on logger %r", ...
def adjust_logging(self, context)
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...
4.188655
3.339884
1.254132
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 error message") p...
def invoked(self, ctx)
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...
2.814252
2.825274
0.996099
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)
def perp(weights)
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...
5.859912
6.159573
0.95135
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)
def ess(weights)
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 ...
6.649834
6.828205
0.973877
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)
def json(a)
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.
3.787139
4.157163
0.910991
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
def json_twisted_response(f)
Parse the JSON from an API response. We do this in a decorator so that our Twisted library can reuse the underlying functions
4.635327
4.291341
1.080158
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: retval = 0 if exit: ...
def main(self, argv=None, exit=True)
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...
3.689584
2.741254
1.345947
traceback.print_exception( context.exc_type, context.exc_value, context.traceback) raise SystemExit(1)
def dispatch_failed(self, context)
Print the unhandled exception and exit the application.
5.106312
3.702928
1.378993
'''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 var = var.split('...
def variables(template)
Returns the set of keywords in a uri template
5.214895
4.257026
1.225009
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 ["+", "#"]: safe = RESE...
def expand(template, variables)
Expand template as a URI Template using variables.
2.709263
2.697035
1.004534
r'''Calculate the expectation value of function ``f`` using weighted samples (like the output of an importance-sampling run). Denoting :math:`x_n` as the sample n and :math:`w_n` as its (normalized) weight, the following is returned: .. math:: \sum_{n=1}^{N} w_n f(x_n) \mathrm{\ \...
def calculate_expectation(samples, weights, f)
r'''Calculate the expectation value of function ``f`` using weighted samples (like the output of an importance-sampling run). Denoting :math:`x_n` as the sample n and :math:`w_n` as its (normalized) weight, the following is returned: .. math:: \sum_{n=1}^{N} w_n f(x_n) \mathrm{\ \ whe...
4.818443
1.607864
2.996799
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. ''' assert len(samples) == len(weights...
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.
5.11974
2.134885
2.398134
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. ''' assert len(samples) ...
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) importance weights.
4.721963
2.758698
1.711664
# shallow copy --> can safely modify (need numpy arrays --> can overwrite with np.asarray) samples = list(samples) weights = list(weights) assert len(samples) == len(weights), \ "Got %i importance-sampling runs but %i weights" % (len(samples), len(weights)) assert len(samples) == len(prop...
def combine_weights(samples, weights, proposals)
Calculate the `deterministic mixture weights` according to [Cor+12]_ given ``samples``, standard ``weights`` and their ``proposals`` for a number of steps in which importance samples are computed for the same target density but different proposals. Return the weights as a :class:`pypmc.tools.History` s...
3.150545
2.945521
1.069606
'''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()
def clear(self)
Clear history of samples and other internal variables to free memory. .. note:: The proposal is untouched.
8.776338
2.861534
3.067004
'''Run the sampler, store the history of visited points into the member variable ``self.samples`` and the importance weights into ``self.weights``. .. seealso:: :py:class:`pypmc.tools.History` :param N: Integer; the number of samples to be drawn. ...
def run(self, N=1, trace_sort=False)
Run the sampler, store the history of visited points into the member variable ``self.samples`` and the importance weights into ``self.weights``. .. seealso:: :py:class:`pypmc.tools.History` :param N: Integer; the number of samples to be drawn. :param t...
5.355993
1.657471
3.231425
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) else: this_target_values = self...
def _calculate_weights(self, this_samples, N)
Calculate and save the weights of a run.
2.619305
2.615252
1.00155
# 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: this_run[:], origin = self.p...
def _get_samples(self, N, 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)
8.181812
7.402092
1.105338
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
def x_forwarded_for(self)
X-Forwarded-For header value. This is the amended header so that it contains the previous IP address in the forwarding change.
4.266069
4.011762
1.06339
def _inherit_docstring(from_class): '''Private wrapper function to inherit docstrings from Base class Usage example: class mood(object): 'describes typical reactions of a person in a specific mood' def how_are_you(self): 'returns a typical answer to How are you? being i...
Private wrapper function to inherit docstrings from Base class Usage example: class mood(object): 'describes typical reactions of a person in a specific mood' def how_are_you(self): 'returns a typical answer to How are you? being in specific mood' raise NotImple...
null
null
null
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.
null
null
null
# 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
def _normalize_django_header_name(header)
Unmunge header names modified by Django.
4.846831
4.264457
1.136565
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_django_header_name(header) ...
def from_request(cls, request)
Generate a HeaderDict based on django request object meta data.
3.61368
2.989857
1.208646
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_headers
def filter(self, exclude)
Return a HeaderSet excluding the headers in the exclude list.
3.507748
2.911447
1.204813
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 crps = sig * (sx * (2 * cdf - 1) + 2 * pdf...
def crps_gaussian(x, mu, sig, grad=False)
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...
3.149362
3.465708
0.908721
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
def _discover_bounds(cdf, tol=1e-7)
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.
4.084346
3.5042
1.165557
# TODO: this function is pretty slow. Look for clever ways to speed it up. # allow for directly passing in scipy.stats distribution objects. cdf = getattr(cdf_or_dist, 'cdf', cdf_or_dist) assert callable(cdf) # if bounds aren't given, discover them if xmin is None or xmax is None: ...
def _crps_cdf_single(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6)
See crps_cdf for docs.
4.346507
4.30645
1.009302
return _crps_cdf(x, cdf_or_dist, xmin, xmax, tol)
def crps_quadrature(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6)
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...
2.907283
5.961411
0.487684
observations = np.asarray(observations) forecasts = np.asarray(forecasts) weights = np.asarray(weights) if weights.ndim > 0: weights = np.where(~np.isnan(forecasts), weights, np.nan) weights = weights / np.nanmean(weights, axis=-1, keepdims=True) if observations.ndim == forecas...
def _crps_ensemble_vectorized(observations, forecasts, weights=1)
An alternative but simpler implementation of CRPS for testing purposes This implementation is based on the identity: .. math:: CRPS(F, x) = E_F|X - x| - 1/2 * E_F|X - X'| where X and X' denote independent random variables drawn from the forecast distribution F, and E_F denotes the expectation...
3.477448
3.538743
0.982679
observations = np.asarray(observations) forecasts = np.asarray(forecasts) if axis != -1: forecasts = move_axis_to_end(forecasts, axis) if weights is not None: weights = move_axis_to_end(weights, axis) if weights.shape != forecasts.shape: raise ValueError('foreca...
def crps_ensemble(observations, forecasts, weights=None, issorted=False, axis=-1)
Calculate the continuous ranked probability score (CRPS) for a set of explicit forecast realizations. The CRPS compares the empirical distribution of an ensemble forecast to a scalar observation. Smaller scores indicate better skill. CRPS is defined for one-dimensional random variables with a probabil...
2.521744
2.595505
0.971581
'''Allocate memory for a new run and return a reference to that memory wrapped in an array of size ``(new_points_len, self.dim)``. :param new_points_len: Integer; the number of points to be stored in the target memory. ''' new_points_len = int(new_points_len) ...
def append(self, new_points_len)
Allocate memory for a new run and return a reference to that memory wrapped in an array of size ``(new_points_len, self.dim)``. :param new_points_len: Integer; the number of points to be stored in the target memory.
4.331606
3.192515
1.356801
self._points = _np.empty( (self.prealloc,self.dim) ) self._slice_for_run_nr = [] self.memleft = self.prealloc
def clear(self)
Deletes the history
17.786114
18.845102
0.943806
'''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 remainder = N % k for i i...
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]
5.614849
1.826086
3.074799
'''Patch ``data`` (for example Markov chain output) into parts of length ``L``. Return a Gaussian mixture where each component gets the empirical mean and covariance of one patch. :param data: Matrix-like array; the points to be patched. Expect ``data[i]`` as the d-dimensional i-th poi...
def patch_data(data, L=100, try_diag=True, verbose=False)
Patch ``data`` (for example Markov chain output) into parts of length ``L``. Return a Gaussian mixture where each component gets the empirical mean and covariance of one patch. :param data: Matrix-like array; the points to be patched. Expect ``data[i]`` as the d-dimensional i-th point. ...
3.790951
1.814511
2.089241
self.request = DownstreamRequest(request) self.args = args self.kwargs = kwargs self._verify_config() self.middleware = MiddlewareSet(self.proxy_middleware) return self.proxy()
def dispatch(self, request, *args, **kwargs)
Dispatch all HTTP methods to the proxy.
7.711533
6.152314
1.253436
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) == '' and ...
def proxy(self)
Retrieve the upstream content and build an HttpResponse.
3.451737
3.374474
1.022896