id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
46,600
jbasko/autoboto
botogen/indentist/code_generator.py
CodeGenerator.block
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. """ assert ...
python
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. """ assert ...
[ "def", "block", "(", "self", ",", "*", "blocks", ",", "*", "*", "kwargs", ")", "->", "\"CodeBlock\"", ":", "assert", "\"name\"", "not", "in", "kwargs", "kwargs", ".", "setdefault", "(", "\"code\"", ",", "self", ")", "code", "=", "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.
[ "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",...
0329afd4730d3d78bd021116857b10e6956dffb1
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/indentist/code_generator.py#L25-L38
46,601
jbasko/autoboto
botogen/indentist/code_generator.py
CodeGenerator.dict_from_locals
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. """ code = self.block(f"{name} = {{}}") for p in params: code.add( ...
python
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. """ code = self.block(f"{name} = {{}}") for p in params: code.add( ...
[ "def", "dict_from_locals", "(", "self", ",", "name", ",", "params", ":", "List", "[", "Parameter", "]", ",", "not_specified_literal", "=", "Constants", ".", "VALUE_NOT_SET", ")", ":", "code", "=", "self", ".", "block", "(", "f\"{name} = {{}}\"", ")", "for", ...
Generate code for a dictionary of locals whose value is not the specified literal.
[ "Generate", "code", "for", "a", "dictionary", "of", "locals", "whose", "value", "is", "not", "the", "specified", "literal", "." ]
0329afd4730d3d78bd021116857b10e6956dffb1
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/indentist/code_generator.py#L56-L67
46,602
nephila/python-taiga
taiga/client.py
TaigaAPI.search
def search(self, project, text=''): """ Search in your Taiga.io instance :param project: the project id :param text: the query of your search """ result = self.raw_request.get( 'search', query={'project': project, 'text': text} ) result = resu...
python
def search(self, project, text=''): """ Search in your Taiga.io instance :param project: the project id :param text: the query of your search """ result = self.raw_request.get( 'search', query={'project': project, 'text': text} ) result = resu...
[ "def", "search", "(", "self", ",", "project", ",", "text", "=", "''", ")", ":", "result", "=", "self", ".", "raw_request", ".", "get", "(", "'search'", ",", "query", "=", "{", "'project'", ":", "project", ",", "'text'", ":", "text", "}", ")", "resu...
Search in your Taiga.io instance :param project: the project id :param text: the query of your search
[ "Search", "in", "your", "Taiga", ".", "io", "instance" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/client.py#L81-L101
46,603
nephila/python-taiga
taiga/client.py
TaigaAPI.auth_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 """ headers = { 'Content-type': 'application/json' } p...
python
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 """ headers = { 'Content-type': 'application/json' } p...
[ "def", "auth_app", "(", "self", ",", "app_id", ",", "app_secret", ",", "auth_code", ",", "state", "=", "''", ")", ":", "headers", "=", "{", "'Content-type'", ":", "'application/json'", "}", "payload", "=", "{", "'application'", ":", "app_id", ",", "'auth_c...
Authenticate an app :param app_id: the app id :param app_secret: the app secret :param auth_code: the app auth code
[ "Authenticate", "an", "app" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/client.py#L143-L208
46,604
jbasko/autoboto
botogen/ab.py
AbStructureShape.sorted_members
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. """ members = collections.OrderedDict() required_names = self.metadata.get("req...
python
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. """ members = collections.OrderedDict() required_names = self.metadata.get("req...
[ "def", "sorted_members", "(", "self", ")", ":", "members", "=", "collections", ".", "OrderedDict", "(", ")", "required_names", "=", "self", ".", "metadata", ".", "get", "(", "\"required\"", ",", "(", ")", ")", "for", "name", ",", "shape", "in", "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.
[ "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", "." ]
0329afd4730d3d78bd021116857b10e6956dffb1
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/ab.py#L77-L96
46,605
bcicen/haproxy-stats
haproxystats/__init__.py
HAProxyServer.update
def update(self): """ Fetch and parse stats """ 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 =...
python
def update(self): """ Fetch and parse stats """ 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 =...
[ "def", "update", "(", "self", ")", ":", "self", ".", "frontends", "=", "[", "]", "self", ".", "backends", "=", "[", "]", "self", ".", "listeners", "=", "[", "]", "csv", "=", "[", "l", "for", "l", "in", "self", ".", "_fetch", "(", ")", ".", "s...
Fetch and parse stats
[ "Fetch", "and", "parse", "stats" ]
f9268244b84eb52095d07b577646fdea4135fe3b
https://github.com/bcicen/haproxy-stats/blob/f9268244b84eb52095d07b577646fdea4135fe3b/haproxystats/__init__.py#L36-L67
46,606
bcicen/haproxy-stats
haproxystats/__init__.py
HAProxyService._decode
def _decode(value): """ decode byte strings and convert to int where needed """ if value.isdigit(): return int(value) if isinstance(value, bytes): return value.decode('utf-8') else: return value
python
def _decode(value): """ decode byte strings and convert to int where needed """ if value.isdigit(): return int(value) if isinstance(value, bytes): return value.decode('utf-8') else: return value
[ "def", "_decode", "(", "value", ")", ":", "if", "value", ".", "isdigit", "(", ")", ":", "return", "int", "(", "value", ")", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "return", "value", ".", "decode", "(", "'utf-8'", ")", "else", ":"...
decode byte strings and convert to int where needed
[ "decode", "byte", "strings", "and", "convert", "to", "int", "where", "needed" ]
f9268244b84eb52095d07b577646fdea4135fe3b
https://github.com/bcicen/haproxy-stats/blob/f9268244b84eb52095d07b577646fdea4135fe3b/haproxystats/__init__.py#L115-L124
46,607
antidot/Pyckson
src/pyckson/decorators.py
caseinsensitive
def caseinsensitive(cls): """Annotation function to set an Enum to be case insensitive on parsing""" 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_C...
python
def caseinsensitive(cls): """Annotation function to set an Enum to be case insensitive on parsing""" 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_C...
[ "def", "caseinsensitive", "(", "cls", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Enum", ")", ":", "raise", "TypeError", "(", "'caseinsensitive decorator can only be applied to subclasses of enum.Enum'", ")", "enum_options", "=", "getattr", "(", "cls", ",...
Annotation function to set an Enum to be case insensitive on parsing
[ "Annotation", "function", "to", "set", "an", "Enum", "to", "be", "case", "insensitive", "on", "parsing" ]
44e625164a53081eb46b8d4bc38f947a575de505
https://github.com/antidot/Pyckson/blob/44e625164a53081eb46b8d4bc38f947a575de505/src/pyckson/decorators.py#L30-L37
46,608
keybase/python-triplesec
triplesec/utils.py
win32_utf8_argv
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. ...
python
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. ...
[ "def", "win32_utf8_argv", "(", ")", ":", "try", ":", "from", "ctypes", "import", "POINTER", ",", "byref", ",", "cdll", ",", "c_int", ",", "windll", "from", "ctypes", ".", "wintypes", "import", "LPCWSTR", ",", "LPWSTR", "GetCommandLineW", "=", "cdll", ".", ...
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...
[ "Uses", "shell32", ".", "GetCommandLineArgvW", "to", "get", "sys", ".", "argv", "as", "a", "list", "of", "UTF", "-", "8", "strings", "." ]
0a73e18cfe542d0cd5ee57bd823a67412b4b717e
https://github.com/keybase/python-triplesec/blob/0a73e18cfe542d0cd5ee57bd823a67412b4b717e/triplesec/utils.py#L57-L99
46,609
keybase/python-triplesec
triplesec/__init__.py
TripleSec.encrypt_ascii
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 """ ...
python
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 """ ...
[ "def", "encrypt_ascii", "(", "self", ",", "data", ",", "key", "=", "None", ",", "v", "=", "None", ",", "extra_bytes", "=", "0", ",", "digest", "=", "\"hex\"", ")", ":", "digests", "=", "{", "\"hex\"", ":", "binascii", ".", "b2a_hex", ",", "\"base64\"...
Encrypt data and return as ascii string. Hexadecimal digest as default. Avaiable digests: hex: Hexadecimal base64: Base 64 hqx: hexbin4
[ "Encrypt", "data", "and", "return", "as", "ascii", "string", ".", "Hexadecimal", "digest", "as", "default", "." ]
0a73e18cfe542d0cd5ee57bd823a67412b4b717e
https://github.com/keybase/python-triplesec/blob/0a73e18cfe542d0cd5ee57bd823a67412b4b717e/triplesec/__init__.py#L91-L110
46,610
keybase/python-triplesec
triplesec/__init__.py
TripleSec.decrypt_ascii
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 """ digests = {"hex": binascii.a2b_hex, "base...
python
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 """ digests = {"hex": binascii.a2b_hex, "base...
[ "def", "decrypt_ascii", "(", "self", ",", "ascii_string", ",", "key", "=", "None", ",", "digest", "=", "\"hex\"", ")", ":", "digests", "=", "{", "\"hex\"", ":", "binascii", ".", "a2b_hex", ",", "\"base64\"", ":", "binascii", ".", "a2b_base64", ",", "\"hq...
Receive ascii string and return decrypted data. Avaiable digests: hex: Hexadecimal base64: Base 64 hqx: hexbin4
[ "Receive", "ascii", "string", "and", "return", "decrypted", "data", "." ]
0a73e18cfe542d0cd5ee57bd823a67412b4b717e
https://github.com/keybase/python-triplesec/blob/0a73e18cfe542d0cd5ee57bd823a67412b4b717e/triplesec/__init__.py#L169-L187
46,611
andrewsnowden/dota2py
dota2py/data.py
load_heroes
def load_heroes(): """ Load hero details from JSON file into memoy """ 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"]] = he...
python
def load_heroes(): """ Load hero details from JSON file into memoy """ 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"]] = he...
[ "def", "load_heroes", "(", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"data\"", ",", "\"heroes.json\"", ")", "with", "open", "(", "filename", ")", "as", "f", ":", ...
Load hero details from JSON file into memoy
[ "Load", "hero", "details", "from", "JSON", "file", "into", "memoy" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/data.py#L52-L62
46,612
andrewsnowden/dota2py
dota2py/data.py
load_items
def load_items(): """ Load item details fom JSON file into memory """ 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
python
def load_items(): """ Load item details fom JSON file into memory """ 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", "(", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"data\"", ",", "\"items.json\"", ")", "with", "open", "(", "filename", ")", "as", "f", ":", "i...
Load item details fom JSON file into memory
[ "Load", "item", "details", "fom", "JSON", "file", "into", "memory" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/data.py#L65-L75
46,613
zyga/guacamole
guacamole/ingredients/cmdtree.py
CommandTreeBuilder._build_cmd_tree
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 struc...
python
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 struc...
[ "def", "_build_cmd_tree", "(", "self", ",", "cmd_cls", ",", "cmd_name", "=", "None", ")", ":", "if", "isinstance", "(", "cmd_cls", ",", "type", ")", ":", "cmd_obj", "=", "cmd_cls", "(", ")", "else", ":", "cmd_obj", "=", "cmd_cls", "if", "cmd_name", "is...
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...
[ "Build", "a", "tree", "of", "commands", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/ingredients/cmdtree.py#L77-L126
46,614
andrewsnowden/dota2py
dota2py/summary.py
debug_dump
def debug_dump(message, file_prefix="dump"): """ Utility while developing to dump message data to play with in the interpreter """ global index index += 1 with open("%s_%s.dump" % (file_prefix, index), 'w') as f: f.write(message.SerializeToString()) f.close()
python
def debug_dump(message, file_prefix="dump"): """ Utility while developing to dump message data to play with in the interpreter """ 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\"", ")", ":", "global", "index", "index", "+=", "1", "with", "open", "(", "\"%s_%s.dump\"", "%", "(", "file_prefix", ",", "index", ")", ",", "'w'", ")", "as", "f", ":", "f", ".", "...
Utility while developing to dump message data to play with in the interpreter
[ "Utility", "while", "developing", "to", "dump", "message", "data", "to", "play", "with", "in", "the", "interpreter" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/summary.py#L14-L25
46,615
andrewsnowden/dota2py
dota2py/summary.py
get_side_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. """ t = player.team if invert: t = not player.team return geta...
python
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. """ t = player.team if invert: t = not player.team return geta...
[ "def", "get_side_attr", "(", "attr", ",", "invert", ",", "player", ")", ":", "t", "=", "player", ".", "team", "if", "invert", ":", "t", "=", "not", "player", ".", "team", "return", "getattr", "(", "player", ",", "\"%s_%s\"", "%", "(", "\"goodguy\"", ...
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.
[ "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...
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/summary.py#L28-L38
46,616
andrewsnowden/dota2py
dota2py/summary.py
DemoSummary.parse_dota_um
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 """ if event.type == dota_usermessages_pb2.CH...
python
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 """ if event.type == dota_usermessages_pb2.CH...
[ "def", "parse_dota_um", "(", "self", ",", "event", ")", ":", "if", "event", ".", "type", "==", "dota_usermessages_pb2", ".", "CHAT_MESSAGE_AEGIS", ":", "self", ".", "aegis", ".", "append", "(", "(", "self", ".", "tick", ",", "event", ".", "playerid_1", "...
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
[ "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" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/summary.py#L279-L287
46,617
andrewsnowden/dota2py
dota2py/summary.py
DemoSummary.parse_player_info
def parse_player_info(self, player): """ Parse a PlayerInfo struct. This arrives before a FileInfo message """ if not player.ishltv: self.player_info[player.name] = { "user_id": player.userID, "guid": player.guid, "bot": player....
python
def parse_player_info(self, player): """ Parse a PlayerInfo struct. This arrives before a FileInfo message """ if not player.ishltv: self.player_info[player.name] = { "user_id": player.userID, "guid": player.guid, "bot": player....
[ "def", "parse_player_info", "(", "self", ",", "player", ")", ":", "if", "not", "player", ".", "ishltv", ":", "self", ".", "player_info", "[", "player", ".", "name", "]", "=", "{", "\"user_id\"", ":", "player", ".", "userID", ",", "\"guid\"", ":", "play...
Parse a PlayerInfo struct. This arrives before a FileInfo message
[ "Parse", "a", "PlayerInfo", "struct", ".", "This", "arrives", "before", "a", "FileInfo", "message" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/summary.py#L296-L305
46,618
andrewsnowden/dota2py
dota2py/summary.py
DemoSummary.parse_file_info
def parse_file_info(self, file_info): """ The CDemoFileInfo contains our winners as well as the length of the demo """ self.info["playback_time"] = file_info.playback_time self.info["match_id"] = file_info.game_info.dota.match_id self.info["game_mode"] = file_inf...
python
def parse_file_info(self, file_info): """ The CDemoFileInfo contains our winners as well as the length of the demo """ self.info["playback_time"] = file_info.playback_time self.info["match_id"] = file_info.game_info.dota.match_id self.info["game_mode"] = file_inf...
[ "def", "parse_file_info", "(", "self", ",", "file_info", ")", ":", "self", ".", "info", "[", "\"playback_time\"", "]", "=", "file_info", ".", "playback_time", "self", ".", "info", "[", "\"match_id\"", "]", "=", "file_info", ".", "game_info", ".", "dota", "...
The CDemoFileInfo contains our winners as well as the length of the demo
[ "The", "CDemoFileInfo", "contains", "our", "winners", "as", "well", "as", "the", "length", "of", "the", "demo" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/summary.py#L307-L325
46,619
andrewsnowden/dota2py
dota2py/summary.py
DemoSummary.parse_game_event
def parse_game_event(self, ge): """ Game events contain the combat log as well as 'chase_hero' events which could be interesting """ if ge.name == "dota_combatlog": if ge.keys["type"] == 4: #Something died try: sour...
python
def parse_game_event(self, ge): """ Game events contain the combat log as well as 'chase_hero' events which could be interesting """ if ge.name == "dota_combatlog": if ge.keys["type"] == 4: #Something died try: sour...
[ "def", "parse_game_event", "(", "self", ",", "ge", ")", ":", "if", "ge", ".", "name", "==", "\"dota_combatlog\"", ":", "if", "ge", ".", "keys", "[", "\"type\"", "]", "==", "4", ":", "#Something died", "try", ":", "source", "=", "self", ".", "dp", "."...
Game events contain the combat log as well as 'chase_hero' events which could be interesting
[ "Game", "events", "contain", "the", "combat", "log", "as", "well", "as", "chase_hero", "events", "which", "could", "be", "interesting" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/summary.py#L327-L364
46,620
hayd/pep8radius
pep8radius/radius.py
fix_file
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...
python
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...
[ "def", "fix_file", "(", "file_name", ",", "line_ranges", ",", "options", "=", "None", ",", "in_place", "=", "False", ",", "diff", "=", "False", ",", "verbose", "=", "0", ",", "cwd", "=", "None", ")", ":", "import", "codecs", "from", "os", "import", "...
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.
[ "Calls", "fix_code", "on", "the", "source", "code", "from", "the", "passed", "in", "file", "over", "the", "given", "line_ranges", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L163-L198
46,621
hayd/pep8radius
pep8radius/radius.py
fix_code
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(c...
python
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(c...
[ "def", "fix_code", "(", "source_code", ",", "line_ranges", ",", "options", "=", "None", ",", "verbose", "=", "0", ")", ":", "if", "options", "is", "None", ":", "from", "pep8radius", ".", "main", "import", "parse_args", "options", "=", "parse_args", "(", ...
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...
[ "Apply", "autopep8", "over", "the", "line_ranges", "returns", "the", "corrected", "code", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L201-L234
46,622
hayd/pep8radius
pep8radius/radius.py
_maybe_print
def _maybe_print(something_to_print, end=None, min_=1, max_=99, verbose=0): """Print if verbose is within min_ and max_.""" if min_ <= verbose <= max_: import sys print(something_to_print, end=end) sys.stdout.flush()
python
def _maybe_print(something_to_print, end=None, min_=1, max_=99, verbose=0): """Print if verbose is within min_ and max_.""" 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", ")", ":", "if", "min_", "<=", "verbose", "<=", "max_", ":", "import", "sys", "print", "(", "something_...
Print if verbose is within min_ and max_.
[ "Print", "if", "verbose", "is", "within", "min_", "and", "max_", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L265-L270
46,623
hayd/pep8radius
pep8radius/radius.py
Radius.from_diff
def from_diff(diff, options=None, cwd=None): """Create a Radius object from a diff rather than a reposistory. """ return RadiusFromDiff(diff=diff, options=options, cwd=cwd)
python
def from_diff(diff, options=None, cwd=None): """Create a Radius object from a diff rather than a reposistory. """ return RadiusFromDiff(diff=diff, options=options, cwd=cwd)
[ "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.
[ "Create", "a", "Radius", "object", "from", "a", "diff", "rather", "than", "a", "reposistory", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L70-L73
46,624
hayd/pep8radius
pep8radius/radius.py
Radius.fix
def fix(self): """Runs fix_file on each modified file. - Prints progress and diff depending on options. - Returns True if there were any changes """ from pep8radius.diff import print_diff, udiff_lines_fixed n = len(self.filenames_diff) _maybe_print('Applying au...
python
def fix(self): """Runs fix_file on each modified file. - Prints progress and diff depending on options. - Returns True if there were any changes """ from pep8radius.diff import print_diff, udiff_lines_fixed n = len(self.filenames_diff) _maybe_print('Applying au...
[ "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"...
Runs fix_file on each modified file. - Prints progress and diff depending on options. - Returns True if there were any changes
[ "Runs", "fix_file", "on", "each", "modified", "file", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L78-L119
46,625
hayd/pep8radius
pep8radius/radius.py
Radius.fix_file
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. """ # We hope tha...
python
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. """ # We hope tha...
[ "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", ...
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.
[ "Apply", "autopep8", "to", "the", "diff", "lines", "of", "a", "file", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L121-L135
46,626
andrewsnowden/dota2py
dota2py/api.py
url_map
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 """ url = base ...
python
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 """ url = base ...
[ "def", "url_map", "(", "base", ",", "params", ")", ":", "url", "=", "base", "if", "not", "params", ":", "url", ".", "rstrip", "(", "\"?&\"", ")", "elif", "'?'", "not", "in", "url", ":", "url", "+=", "\"?\"", "entries", "=", "[", "]", "for", "key"...
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
[ "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", "st...
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/api.py#L31-L55
46,627
andrewsnowden/dota2py
dota2py/api.py
make_request
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 """ params = params or {} params["key"] = key or API_KEY params["language"] = language if not params["key"]: raise ...
python
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 """ params = params or {} params["key"] = key or API_KEY params["language"] = language if not params["key"]: raise ...
[ "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
[ "Make", "an", "API", "request" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/api.py#L68-L82
46,628
andrewsnowden/dota2py
dota2py/api.py
get_match_history
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, ...
python
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, ...
[ "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", ",", "lea...
List of most recent 25 matches before start_at_match_id
[ "List", "of", "most", "recent", "25", "matches", "before", "start_at_match_id" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/api.py#L101-L125
46,629
andrewsnowden/dota2py
dota2py/api.py
get_match_history_by_sequence_num
def get_match_history_by_sequence_num(start_at_match_seq_num, matches_requested=None, **kwargs): """ Most recent matches ordered by sequence number """ params = { "start_at_match_seq_num": start_at_match_seq_num, "matches_requested": matches_requeste...
python
def get_match_history_by_sequence_num(start_at_match_seq_num, matches_requested=None, **kwargs): """ Most recent matches ordered by sequence number """ params = { "start_at_match_seq_num": start_at_match_seq_num, "matches_requested": matches_requeste...
[ "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\"", ":", "matc...
Most recent matches ordered by sequence number
[ "Most", "recent", "matches", "ordered", "by", "sequence", "number" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/api.py#L129-L140
46,630
andrewsnowden/dota2py
dota2py/api.py
get_player_summaries
def get_player_summaries(players, **kwargs): """ Get players steam profile from their steam ids """ if (isinstance(players, list)): params = {'steamids': ','.join(str(p) for p in players)} elif (isinstance(players, int)): params = {'steamids': players} else: raise ValueEr...
python
def get_player_summaries(players, **kwargs): """ Get players steam profile from their steam ids """ if (isinstance(players, list)): params = {'steamids': ','.join(str(p) for p in players)} elif (isinstance(players, int)): params = {'steamids': players} else: raise ValueEr...
[ "def", "get_player_summaries", "(", "players", ",", "*", "*", "kwargs", ")", ":", "if", "(", "isinstance", "(", "players", ",", "list", ")", ")", ":", "params", "=", "{", "'steamids'", ":", "','", ".", "join", "(", "str", "(", "p", ")", "for", "p",...
Get players steam profile from their steam ids
[ "Get", "players", "steam", "profile", "from", "their", "steam", "ids" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/api.py#L162-L173
46,631
andrewsnowden/dota2py
dota2py/api.py
get_hero_image_url
def get_hero_image_url(hero_name, image_size="lg"): """ Get a hero image based on name and image size """ 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: ...
python
def get_hero_image_url(hero_name, image_size="lg"): """ Get a hero image based on name and image size """ 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: ...
[ "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_si...
Get a hero image based on name and image size
[ "Get", "a", "hero", "image", "based", "on", "name", "and", "image", "size" ]
67637f4b9c160ea90c11b7e81545baf350affa7a
https://github.com/andrewsnowden/dota2py/blob/67637f4b9c160ea90c11b7e81545baf350affa7a/dota2py/api.py#L185-L198
46,632
thomasw/djproxy
djproxy/urls.py
generate_proxy
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.""" middleware = list(middleware or HttpProxy.proxy_middleware) middleware += list(append_middleware ...
python
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.""" middleware = list(middleware or HttpProxy.proxy_middleware) middleware += list(append_middleware ...
[ "def", "generate_proxy", "(", "prefix", ",", "base_url", "=", "''", ",", "verify_ssl", "=", "True", ",", "middleware", "=", "None", ",", "append_middleware", "=", "None", ",", "cert", "=", "None", ",", "timeout", "=", "None", ")", ":", "middleware", "=",...
Generate a ProxyClass based view that uses the passed base_url.
[ "Generate", "a", "ProxyClass", "based", "view", "that", "uses", "the", "passed", "base_url", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/urls.py#L9-L23
46,633
thomasw/djproxy
djproxy/urls.py
generate_routes
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':...
python
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':...
[ "def", "generate_routes", "(", "config", ")", ":", "routes", "=", "[", "]", "for", "name", ",", "config", "in", "iteritems", "(", "config", ")", ":", "pattern", "=", "r'^%s(?P<url>.*)$'", "%", "re", ".", "escape", "(", "config", "[", "'prefix'", "]", "...
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']...
[ "Generate", "a", "list", "of", "urls", "that", "map", "to", "generated", "proxy", "views", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/urls.py#L26-L87
46,634
TheClimateCorporation/properscoring
properscoring/_brier.py
threshold_brier_score
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 ...
python
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 ...
[ "def", "threshold_brier_score", "(", "observations", ",", "forecasts", ",", "threshold", ",", "issorted", "=", "False", ",", "axis", "=", "-", "1", ")", ":", "observations", "=", "np", ".", "asarray", "(", "observations", ")", "threshold", "=", "np", ".", ...
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}...
[ "Calculate", "the", "Brier", "scores", "of", "an", "ensemble", "for", "exceeding", "given", "thresholds", "." ]
1ca13dcbc1abf53d07474b74fbe3567fd4045668
https://github.com/TheClimateCorporation/properscoring/blob/1ca13dcbc1abf53d07474b74fbe3567fd4045668/properscoring/_brier.py#L93-L190
46,635
fusionbox/django-argonauts
argonauts/__init__.py
dumps
def dumps(*args, **kwargs): """ Wrapper for json.dumps that uses the JSONArgonautsEncoder. """ import json from django.conf import settings from argonauts.serializers import JSONArgonautsEncoder kwargs.setdefault('cls', JSONArgonautsEncoder) # pretty print in DEBUG mode. if setting...
python
def dumps(*args, **kwargs): """ Wrapper for json.dumps that uses the JSONArgonautsEncoder. """ import json from django.conf import settings from argonauts.serializers import JSONArgonautsEncoder kwargs.setdefault('cls', JSONArgonautsEncoder) # pretty print in DEBUG mode. if setting...
[ "def", "dumps", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "json", "from", "django", ".", "conf", "import", "settings", "from", "argonauts", ".", "serializers", "import", "JSONArgonautsEncoder", "kwargs", ".", "setdefault", "(", "'cls'", ...
Wrapper for json.dumps that uses the JSONArgonautsEncoder.
[ "Wrapper", "for", "json", ".", "dumps", "that", "uses", "the", "JSONArgonautsEncoder", "." ]
0f64f9700199e8c70a1cb9a055b8e31f6843933d
https://github.com/fusionbox/django-argonauts/blob/0f64f9700199e8c70a1cb9a055b8e31f6843933d/argonauts/__init__.py#L12-L29
46,636
zyga/guacamole
guacamole/ingredients/log.py
ANSIFormatter.format
def format(self, record): """Overridden method that applies SGR codes to log messages.""" # 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
python
def format(self, record): """Overridden method that applies SGR codes to log messages.""" # 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", ")", ":", "# XXX: idea, colorize message arguments", "s", "=", "super", "(", "ANSIFormatter", ",", "self", ")", ".", "format", "(", "record", ")", "if", "hasattr", "(", "self", ".", "context", ",", "'ansi'", ")"...
Overridden method that applies SGR codes to log messages.
[ "Overridden", "method", "that", "applies", "SGR", "codes", "to", "log", "messages", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/ingredients/log.py#L49-L55
46,637
zyga/guacamole
guacamole/ingredients/log.py
Logging.added
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. """ self._expose_argpa...
python
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. """ self._expose_argpa...
[ "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.
[ "Configure", "generic", "application", "logging", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/ingredients/log.py#L99-L108
46,638
zyga/guacamole
guacamole/ingredients/log.py
Logging.configure_logging
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 sp...
python
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 sp...
[ "def", "configure_logging", "(", "self", ",", "context", ")", ":", "fmt", "=", "\"%(name)-12s: %(levelname)-8s %(message)s\"", "formatter", "=", "ANSIFormatter", "(", "context", ",", "fmt", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "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...
[ "Configure", "logging", "for", "the", "application", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/ingredients/log.py#L161-L178
46,639
zyga/guacamole
guacamole/ingredients/log.py
Logging.adjust_logging
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 va...
python
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 va...
[ "def", "adjust_logging", "(", "self", ",", "context", ")", ":", "if", "context", ".", "early_args", ".", "log_level", ":", "log_level", "=", "context", ".", "early_args", ".", "log_level", "logging", ".", "getLogger", "(", "\"\"", ")", ".", "setLevel", "("...
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...
[ "Adjust", "logging", "configuration", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/ingredients/log.py#L180-L196
46,640
fusionbox/django-argonauts
argonauts/templatetags/argonauts.py
json
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 filt...
python
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 filt...
[ "def", "json", "(", "a", ")", ":", "json_str", "=", "json_dumps", "(", "a", ")", "# Escape all the XML/HTML special characters.", "escapes", "=", "[", "'<'", ",", "'>'", ",", "'&'", "]", "for", "c", "in", "escapes", ":", "json_str", "=", "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.
[ "Output", "the", "json", "encoding", "of", "its", "argument", "." ]
0f64f9700199e8c70a1cb9a055b8e31f6843933d
https://github.com/fusionbox/django-argonauts/blob/0f64f9700199e8c70a1cb9a055b8e31f6843933d/argonauts/templatetags/argonauts.py#L12-L31
46,641
zyga/guacamole
guacamole/recipes/__init__.py
Recipe.main
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: Whate...
python
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: Whate...
[ "def", "main", "(", "self", ",", "argv", "=", "None", ",", "exit", "=", "True", ")", ":", "bowl", "=", "self", ".", "prepare", "(", ")", "try", ":", "retval", "=", "bowl", ".", "eat", "(", "argv", ")", "except", "SystemExit", "as", "exc", ":", ...
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...
[ "Shortcut", "to", "prepare", "a", "bowl", "of", "guacamole", "and", "eat", "it", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/recipes/__init__.py#L89-L131
46,642
zyga/guacamole
guacamole/ingredients/crash.py
VerboseCrashHandler.dispatch_failed
def dispatch_failed(self, context): """Print the unhandled exception and exit the application.""" traceback.print_exception( context.exc_type, context.exc_value, context.traceback) raise SystemExit(1)
python
def dispatch_failed(self, context): """Print the unhandled exception and exit the application.""" traceback.print_exception( context.exc_type, context.exc_value, context.traceback) raise SystemExit(1)
[ "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.
[ "Print", "the", "unhandled", "exception", "and", "exit", "the", "application", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/ingredients/crash.py#L40-L44
46,643
uri-templates/uritemplate-py
uritemplate/__init__.py
variables
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 ...
python
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 ...
[ "def", "variables", "(", "template", ")", ":", "vars", "=", "set", "(", ")", "for", "varlist", "in", "TEMPLATE", ".", "findall", "(", "template", ")", ":", "if", "varlist", "[", "0", "]", "in", "OPERATOR", ":", "varlist", "=", "varlist", "[", "1", ...
Returns the set of keywords in a uri template
[ "Returns", "the", "set", "of", "keywords", "in", "a", "uri", "template" ]
8e13d804ac8641f3b5948eb208c75465ad649da1
https://github.com/uri-templates/uritemplate-py/blob/8e13d804ac8641f3b5948eb208c75465ad649da1/uritemplate/__init__.py#L39-L53
46,644
uri-templates/uritemplate-py
uritemplate/__init__.py
expand
def expand(template, variables): """ Expand template as a URI Template using variables. """ def _sub(match): expression = match.group(1) operator = "" if expression[0] in OPERATOR: operator = expression[0] varlist = expression[1:] else: ...
python
def expand(template, variables): """ Expand template as a URI Template using variables. """ def _sub(match): expression = match.group(1) operator = "" if expression[0] in OPERATOR: operator = expression[0] varlist = expression[1:] else: ...
[ "def", "expand", "(", "template", ",", "variables", ")", ":", "def", "_sub", "(", "match", ")", ":", "expression", "=", "match", ".", "group", "(", "1", ")", "operator", "=", "\"\"", "if", "expression", "[", "0", "]", "in", "OPERATOR", ":", "operator...
Expand template as a URI Template using variables.
[ "Expand", "template", "as", "a", "URI", "Template", "using", "variables", "." ]
8e13d804ac8641f3b5948eb208c75465ad649da1
https://github.com/uri-templates/uritemplate-py/blob/8e13d804ac8641f3b5948eb208c75465ad649da1/uritemplate/__init__.py#L192-L265
46,645
fredRos/pypmc
pypmc/sampler/importance_sampling.py
ImportanceSampler.clear
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()
python
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()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "samples", ".", "clear", "(", ")", "self", ".", "weights", ".", "clear", "(", ")", "if", "self", ".", "target_values", "is", "not", "None", ":", "self", ".", "target_values", ".", "clear", "(", ")...
Clear history of samples and other internal variables to free memory. .. note:: The proposal is untouched.
[ "Clear", "history", "of", "samples", "and", "other", "internal", "variables", "to", "free", "memory", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/importance_sampling.py#L146-L156
46,646
fredRos/pypmc
pypmc/sampler/importance_sampling.py
ImportanceSampler.run
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...
python
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...
[ "def", "run", "(", "self", ",", "N", "=", "1", ",", "trace_sort", "=", "False", ")", ":", "if", "N", "==", "0", ":", "return", "0", "if", "trace_sort", ":", "this_samples", ",", "origin", "=", "self", ".", "_get_samples", "(", "N", ",", "trace_sort...
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...
[ "Run", "the", "sampler", "store", "the", "history", "of", "visited", "points", "into", "the", "member", "variable", "self", ".", "samples", "and", "the", "importance", "weights", "into", "self", ".", "weights", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/importance_sampling.py#L158-L195
46,647
fredRos/pypmc
pypmc/sampler/importance_sampling.py
ImportanceSampler._calculate_weights
def _calculate_weights(self, this_samples, N): """Calculate and save the weights of a run.""" 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]) ...
python
def _calculate_weights(self, this_samples, N): """Calculate and save the weights of a run.""" 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]) ...
[ "def", "_calculate_weights", "(", "self", ",", "this_samples", ",", "N", ")", ":", "this_weights", "=", "self", ".", "weights", ".", "append", "(", "N", ")", "[", ":", ",", "0", "]", "if", "self", ".", "target_values", "is", "None", ":", "for", "i", ...
Calculate and save the weights of a run.
[ "Calculate", "and", "save", "the", "weights", "of", "a", "run", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/importance_sampling.py#L197-L211
46,648
fredRos/pypmc
pypmc/sampler/importance_sampling.py
ImportanceSampler._get_samples
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 ...
python
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 ...
[ "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", ")", "# s...
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)
[ "Save", "N", "samples", "from", "self", ".", "proposal", "to", "self", ".", "samples", "This", "function", "does", "NOT", "calculate", "the", "weights", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/importance_sampling.py#L213-L232
46,649
thomasw/djproxy
djproxy/request.py
DownstreamRequest.x_forwarded_for
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. """ ip = self._request.META.get('REMOTE_ADDR') current_xff = self.headers.get('X-Forwarded-For') return ...
python
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. """ ip = self._request.META.get('REMOTE_ADDR') current_xff = self.headers.get('X-Forwarded-For') return ...
[ "def", "x_forwarded_for", "(", "self", ")", ":", "ip", "=", "self", ".", "_request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ")", "current_xff", "=", "self", ".", "headers", ".", "get", "(", "'X-Forwarded-For'", ")", "return", "'%s, %s'", "%", "("...
X-Forwarded-For header value. This is the amended header so that it contains the previous IP address in the forwarding change.
[ "X", "-", "Forwarded", "-", "For", "header", "value", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/request.py#L29-L39
46,650
fredRos/pypmc
pypmc/tools/_doc.py
_add_to_docstring
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...
python
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...
[ "def", "_add_to_docstring", "(", "string", ")", ":", "def", "wrapper", "(", "method", ")", ":", "if", "method", ".", "__doc__", "is", "not", "None", ":", "method", ".", "__doc__", "+=", "string", "else", ":", "method", ".", "__doc__", "=", "string", "r...
Private wrapper function. Appends ``string`` to the docstring of the wrapped function.
[ "Private", "wrapper", "function", ".", "Appends", "string", "to", "the", "docstring", "of", "the", "wrapped", "function", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/tools/_doc.py#L41-L52
46,651
thomasw/djproxy
djproxy/headers.py
HeaderDict._normalize_django_header_name
def _normalize_django_header_name(header): """Unmunge header names modified by Django.""" # 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('_')) ...
python
def _normalize_django_header_name(header): """Unmunge header names modified by Django.""" # 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('_')) ...
[ "def", "_normalize_django_header_name", "(", "header", ")", ":", "# Remove HTTP_ prefix.", "new_header", "=", "header", ".", "rpartition", "(", "'HTTP_'", ")", "[", "2", "]", "# Camel case and replace _ with -", "new_header", "=", "'-'", ".", "join", "(", "x", "."...
Unmunge header names modified by Django.
[ "Unmunge", "header", "names", "modified", "by", "Django", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/headers.py#L10-L18
46,652
thomasw/djproxy
djproxy/headers.py
HeaderDict.from_request
def from_request(cls, request): """Generate a HeaderDict based on django request object meta data.""" request_headers = HeaderDict() other_headers = ['CONTENT_TYPE', 'CONTENT_LENGTH'] for header, value in iteritems(request.META): is_header = header.startswith('HTTP_') or hea...
python
def from_request(cls, request): """Generate a HeaderDict based on django request object meta data.""" request_headers = HeaderDict() other_headers = ['CONTENT_TYPE', 'CONTENT_LENGTH'] for header, value in iteritems(request.META): is_header = header.startswith('HTTP_') or hea...
[ "def", "from_request", "(", "cls", ",", "request", ")", ":", "request_headers", "=", "HeaderDict", "(", ")", "other_headers", "=", "[", "'CONTENT_TYPE'", ",", "'CONTENT_LENGTH'", "]", "for", "header", ",", "value", "in", "iteritems", "(", "request", ".", "ME...
Generate a HeaderDict based on django request object meta data.
[ "Generate", "a", "HeaderDict", "based", "on", "django", "request", "object", "meta", "data", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/headers.py#L21-L33
46,653
thomasw/djproxy
djproxy/headers.py
HeaderDict.filter
def filter(self, exclude): """Return a HeaderSet excluding the headers in the exclude list.""" 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: ...
python
def filter(self, exclude): """Return a HeaderSet excluding the headers in the exclude list.""" 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: ...
[ "def", "filter", "(", "self", ",", "exclude", ")", ":", "filtered_headers", "=", "HeaderDict", "(", ")", "lowercased_ignore_list", "=", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "exclude", "]", "for", "header", ",", "value", "in", "iteritems", ...
Return a HeaderSet excluding the headers in the exclude list.
[ "Return", "a", "HeaderSet", "excluding", "the", "headers", "in", "the", "exclude", "list", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/headers.py#L35-L44
46,654
TheClimateCorporation/properscoring
properscoring/_crps.py
crps_gaussian
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 ...
python
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 ...
[ "def", "crps_gaussian", "(", "x", ",", "mu", ",", "sig", ",", "grad", "=", "False", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "mu", "=", "np", ".", "asarray", "(", "mu", ")", "sig", "=", "np", ".", "asarray", "(", "sig", ")", ...
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...
[ "Computes", "the", "CRPS", "of", "observations", "x", "relative", "to", "normally", "distributed", "forecasts", "with", "mean", "mu", "and", "standard", "deviation", "sig", "." ]
1ca13dcbc1abf53d07474b74fbe3567fd4045668
https://github.com/TheClimateCorporation/properscoring/blob/1ca13dcbc1abf53d07474b74fbe3567fd4045668/properscoring/_crps.py#L24-L78
46,655
TheClimateCorporation/properscoring
properscoring/_crps.py
_discover_bounds
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. """ class DistFromCDF(stats.distributions.rv_continuous): def cdf(self, x): ...
python
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. """ class DistFromCDF(stats.distributions.rv_continuous): def cdf(self, x): ...
[ "def", "_discover_bounds", "(", "cdf", ",", "tol", "=", "1e-7", ")", ":", "class", "DistFromCDF", "(", "stats", ".", "distributions", ".", "rv_continuous", ")", ":", "def", "cdf", "(", "self", ",", "x", ")", ":", "return", "cdf", "(", "x", ")", "dist...
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.
[ "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", "." ]
1ca13dcbc1abf53d07474b74fbe3567fd4045668
https://github.com/TheClimateCorporation/properscoring/blob/1ca13dcbc1abf53d07474b74fbe3567fd4045668/properscoring/_crps.py#L81-L94
46,656
TheClimateCorporation/properscoring
properscoring/_crps.py
_crps_cdf_single
def _crps_cdf_single(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6): """ See crps_cdf for docs. """ # 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) a...
python
def _crps_cdf_single(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6): """ See crps_cdf for docs. """ # 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) a...
[ "def", "_crps_cdf_single", "(", "x", ",", "cdf_or_dist", ",", "xmin", "=", "None", ",", "xmax", "=", "None", ",", "tol", "=", "1e-6", ")", ":", "# TODO: this function is pretty slow. Look for clever ways to speed it up.", "# allow for directly passing in scipy.stats distri...
See crps_cdf for docs.
[ "See", "crps_cdf", "for", "docs", "." ]
1ca13dcbc1abf53d07474b74fbe3567fd4045668
https://github.com/TheClimateCorporation/properscoring/blob/1ca13dcbc1abf53d07474b74fbe3567fd4045668/properscoring/_crps.py#L97-L146
46,657
TheClimateCorporation/properscoring
properscoring/_crps.py
_crps_ensemble_vectorized
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 variab...
python
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 variab...
[ "def", "_crps_ensemble_vectorized", "(", "observations", ",", "forecasts", ",", "weights", "=", "1", ")", ":", "observations", "=", "np", ".", "asarray", "(", "observations", ")", "forecasts", "=", "np", ".", "asarray", "(", "forecasts", ")", "weights", "=",...
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...
[ "An", "alternative", "but", "simpler", "implementation", "of", "CRPS", "for", "testing", "purposes" ]
1ca13dcbc1abf53d07474b74fbe3567fd4045668
https://github.com/TheClimateCorporation/properscoring/blob/1ca13dcbc1abf53d07474b74fbe3567fd4045668/properscoring/_crps.py#L187-L235
46,658
fredRos/pypmc
pypmc/tools/_history.py
History.clear
def clear(self): """Deletes the history""" self._points = _np.empty( (self.prealloc,self.dim) ) self._slice_for_run_nr = [] self.memleft = self.prealloc
python
def clear(self): """Deletes the history""" self._points = _np.empty( (self.prealloc,self.dim) ) self._slice_for_run_nr = [] self.memleft = self.prealloc
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_points", "=", "_np", ".", "empty", "(", "(", "self", ".", "prealloc", ",", "self", ".", "dim", ")", ")", "self", ".", "_slice_for_run_nr", "=", "[", "]", "self", ".", "memleft", "=", "self", "...
Deletes the history
[ "Deletes", "the", "history" ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/tools/_history.py#L112-L116
46,659
thomasw/djproxy
djproxy/views.py
HttpProxy.dispatch
def dispatch(self, request, *args, **kwargs): """Dispatch all HTTP methods to the proxy.""" self.request = DownstreamRequest(request) self.args = args self.kwargs = kwargs self._verify_config() self.middleware = MiddlewareSet(self.proxy_middleware) return self....
python
def dispatch(self, request, *args, **kwargs): """Dispatch all HTTP methods to the proxy.""" self.request = DownstreamRequest(request) self.args = args self.kwargs = kwargs self._verify_config() self.middleware = MiddlewareSet(self.proxy_middleware) return self....
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", "=", "DownstreamRequest", "(", "request", ")", "self", ".", "args", "=", "args", "self", ".", "kwargs", "=", "kwargs", "self"...
Dispatch all HTTP methods to the proxy.
[ "Dispatch", "all", "HTTP", "methods", "to", "the", "proxy", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/views.py#L51-L61
46,660
thomasw/djproxy
djproxy/views.py
HttpProxy.proxy
def proxy(self): """Retrieve the upstream content and build an HttpResponse.""" 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 ...
python
def proxy(self): """Retrieve the upstream content and build an HttpResponse.""" 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 ...
[ "def", "proxy", "(", "self", ")", ":", "headers", "=", "self", ".", "request", ".", "headers", ".", "filter", "(", "self", ".", "ignored_request_headers", ")", "qs", "=", "self", ".", "request", ".", "query_string", "if", "self", ".", "pass_query_string", ...
Retrieve the upstream content and build an HttpResponse.
[ "Retrieve", "the", "upstream", "content", "and", "build", "an", "HttpResponse", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/views.py#L63-L90
46,661
hayd/pep8radius
pep8radius/shell.py
shell_out
def shell_out(cmd, stderr=STDOUT, cwd=None): """Friendlier version of check_output.""" 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)
python
def shell_out(cmd, stderr=STDOUT, cwd=None): """Friendlier version of check_output.""" 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)
[ "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", "=", ...
Friendlier version of check_output.
[ "Friendlier", "version", "of", "check_output", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/shell.py#L52-L59
46,662
hayd/pep8radius
pep8radius/shell.py
shell_out_ignore_exitcode
def shell_out_ignore_exitcode(cmd, stderr=STDOUT, cwd=None): """Same as shell_out but doesn't raise if the cmd exits badly.""" try: return shell_out(cmd, stderr=stderr, cwd=cwd) except CalledProcessError as c: return _clean_output(c.output)
python
def shell_out_ignore_exitcode(cmd, stderr=STDOUT, cwd=None): """Same as shell_out but doesn't raise if the cmd exits badly.""" try: return shell_out(cmd, stderr=stderr, cwd=cwd) except CalledProcessError as c: return _clean_output(c.output)
[ "def", "shell_out_ignore_exitcode", "(", "cmd", ",", "stderr", "=", "STDOUT", ",", "cwd", "=", "None", ")", ":", "try", ":", "return", "shell_out", "(", "cmd", ",", "stderr", "=", "stderr", ",", "cwd", "=", "cwd", ")", "except", "CalledProcessError", "as...
Same as shell_out but doesn't raise if the cmd exits badly.
[ "Same", "as", "shell_out", "but", "doesn", "t", "raise", "if", "the", "cmd", "exits", "badly", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/shell.py#L62-L67
46,663
hayd/pep8radius
pep8radius/shell.py
from_dir
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(curdir)
python
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(curdir)
[ "def", "from_dir", "(", "cwd", ")", ":", "import", "os", "curdir", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "cwd", ")", "yield", "finally", ":", "os", ".", "chdir", "(", "curdir", ")" ]
Context manager to ensure in the cwd directory.
[ "Context", "manager", "to", "ensure", "in", "the", "cwd", "directory", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/shell.py#L79-L87
46,664
python-thumbnails/python-thumbnails
thumbnails/templatetags/thumbnails.py
text_filter
def text_filter(regex_base, value): """ 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 ...
python
def text_filter(regex_base, value): """ 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 ...
[ "def", "text_filter", "(", "regex_base", ",", "value", ")", ":", "from", "thumbnails", "import", "get_thumbnail", "regex", "=", "regex_base", "%", "{", "'caption'", ":", "'[a-zA-Z0-9\\.\\,:;/_ \\(\\)\\-\\!\\?\\\"]+'", ",", "'image'", ":", "'[a-zA-Z0-9\\.:/_\\-\\% ]+'", ...
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 ...
[ "A", "text", "-", "filter", "helper", "used", "in", "markdown_thumbnails", "-", "filter", "and", "html_thumbnails", "-", "filter", ".", "It", "can", "be", "used", "to", "build", "custom", "thumbnail", "text", "-", "filters", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/templatetags/thumbnails.py#L57-L82
46,665
zyga/guacamole
guacamole/core.py
Bowl.eat
def eat(self, argv=None): """ 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 i...
python
def eat(self, argv=None): """ 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 i...
[ "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", ...
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 ...
[ "Eat", "the", "guacamole", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/core.py#L212-L258
46,666
fredRos/pypmc
pypmc/tools/parallel_sampler.py
MPISampler.clear
def clear(self): """Delete the history.""" 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_...
python
def clear(self): """Delete the history.""" 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_...
[ "def", "clear", "(", "self", ")", ":", "self", ".", "sampler", ".", "clear", "(", ")", "self", ".", "samples_list", "=", "self", ".", "_comm", ".", "gather", "(", "self", ".", "sampler", ".", "samples", ",", "root", "=", "0", ")", "if", "hasattr", ...
Delete the history.
[ "Delete", "the", "history", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/tools/parallel_sampler.py#L73-L80
46,667
python-thumbnails/python-thumbnails
thumbnails/storage_backends.py
BaseStorageBackend.path
def path(self, 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. """ if os...
python
def path(self, 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. """ if os...
[ "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.
[ "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",...
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/storage_backends.py#L16-L25
46,668
fredRos/pypmc
pypmc/mix_adapt/hierarchical.py
Hierarchical.run
def run(self, eps=1e-4, kill=True, max_steps=50, verbose=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 relativ...
python
def run(self, eps=1e-4, kill=True, max_steps=50, verbose=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 relativ...
[ "def", "run", "(", "self", ",", "eps", "=", "1e-4", ",", "kill", "=", "True", ",", "max_steps", "=", "50", ",", "verbose", "=", "False", ")", ":", "old_distance", "=", "np", ".", "finfo", "(", "np", ".", "float64", ")", ".", "max", "new_distance", ...
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``, ...
[ "r", "Perform", "the", "clustering", "on", "the", "input", "components", "updating", "the", "initial", "guess", ".", "The", "result", "is", "available", "in", "the", "member", "self", ".", "g", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/mix_adapt/hierarchical.py#L153-L219
46,669
infoxchange/supervisor-logging
supervisor_logging/__init__.py
eventdata
def eventdata(payload): """ Parse a Supervisor event. """ headerinfo, data = payload.split('\n', 1) headers = get_headers(headerinfo) return headers, data
python
def eventdata(payload): """ Parse a Supervisor event. """ headerinfo, data = payload.split('\n', 1) headers = get_headers(headerinfo) return headers, data
[ "def", "eventdata", "(", "payload", ")", ":", "headerinfo", ",", "data", "=", "payload", ".", "split", "(", "'\\n'", ",", "1", ")", "headers", "=", "get_headers", "(", "headerinfo", ")", "return", "headers", ",", "data" ]
Parse a Supervisor event.
[ "Parse", "a", "Supervisor", "event", "." ]
2d4411378fb52799bc506a68f1a914cbe671b13b
https://github.com/infoxchange/supervisor-logging/blob/2d4411378fb52799bc506a68f1a914cbe671b13b/supervisor_logging/__init__.py#L74-L81
46,670
infoxchange/supervisor-logging
supervisor_logging/__init__.py
supervisor_events
def supervisor_events(stdin, stdout): """ An event stream from Supervisor. """ 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 = e...
python
def supervisor_events(stdin, stdout): """ An event stream from Supervisor. """ 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 = e...
[ "def", "supervisor_events", "(", "stdin", ",", "stdout", ")", ":", "while", "True", ":", "stdout", ".", "write", "(", "'READY\\n'", ")", "stdout", ".", "flush", "(", ")", "line", "=", "stdin", ".", "readline", "(", ")", "headers", "=", "get_headers", "...
An event stream from Supervisor.
[ "An", "event", "stream", "from", "Supervisor", "." ]
2d4411378fb52799bc506a68f1a914cbe671b13b
https://github.com/infoxchange/supervisor-logging/blob/2d4411378fb52799bc506a68f1a914cbe671b13b/supervisor_logging/__init__.py#L84-L102
46,671
infoxchange/supervisor-logging
supervisor_logging/__init__.py
main
def main(): """ Main application loop. """ 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_SERVE...
python
def main(): """ Main application loop. """ 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_SERVE...
[ "def", "main", "(", ")", ":", "env", "=", "os", ".", "environ", "try", ":", "host", "=", "env", "[", "'SYSLOG_SERVER'", "]", "port", "=", "int", "(", "env", "[", "'SYSLOG_PORT'", "]", ")", "socktype", "=", "socket", ".", "SOCK_DGRAM", "if", "env", ...
Main application loop.
[ "Main", "application", "loop", "." ]
2d4411378fb52799bc506a68f1a914cbe671b13b
https://github.com/infoxchange/supervisor-logging/blob/2d4411378fb52799bc506a68f1a914cbe671b13b/supervisor_logging/__init__.py#L105-L137
46,672
infoxchange/supervisor-logging
supervisor_logging/__init__.py
PalletFormatter.formatTime
def formatTime(self, record, datefmt=None): """ Format time, including milliseconds. """ formatted = super(PalletFormatter, self).formatTime( record, datefmt=datefmt) return formatted + '.%03dZ' % record.msecs
python
def formatTime(self, record, datefmt=None): """ Format time, including milliseconds. """ formatted = super(PalletFormatter, self).formatTime( record, datefmt=datefmt) return formatted + '.%03dZ' % record.msecs
[ "def", "formatTime", "(", "self", ",", "record", ",", "datefmt", "=", "None", ")", ":", "formatted", "=", "super", "(", "PalletFormatter", ",", "self", ")", ".", "formatTime", "(", "record", ",", "datefmt", "=", "datefmt", ")", "return", "formatted", "+"...
Format time, including milliseconds.
[ "Format", "time", "including", "milliseconds", "." ]
2d4411378fb52799bc506a68f1a914cbe671b13b
https://github.com/infoxchange/supervisor-logging/blob/2d4411378fb52799bc506a68f1a914cbe671b13b/supervisor_logging/__init__.py#L49-L56
46,673
hayd/pep8radius
pep8radius/diff.py
get_diff
def get_diff(original, fixed, file_name, original_label='original', fixed_label='fixed'): """Return text of unified diff between original and fixed.""" original, fixed = original.splitlines(True), fixed.splitlines(True) newline = '\n' from difflib import unified_diff diff = unified_dif...
python
def get_diff(original, fixed, file_name, original_label='original', fixed_label='fixed'): """Return text of unified diff between original and fixed.""" original, fixed = original.splitlines(True), fixed.splitlines(True) newline = '\n' from difflib import unified_diff diff = unified_dif...
[ "def", "get_diff", "(", "original", ",", "fixed", ",", "file_name", ",", "original_label", "=", "'original'", ",", "fixed_label", "=", "'fixed'", ")", ":", "original", ",", "fixed", "=", "original", ".", "splitlines", "(", "True", ")", ",", "fixed", ".", ...
Return text of unified diff between original and fixed.
[ "Return", "text", "of", "unified", "diff", "between", "original", "and", "fixed", "." ]
0c1d14835d390f7feeb602f35a768e52ce306a0a
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/diff.py#L34-L51
46,674
fredRos/pypmc
pypmc/sampler/markov_chain.py
MarkovChain.run
def run(self, N=1): '''Run the chain and store the history of visited points into the member variable ``self.samples``. Returns the number of accepted points during the run. .. seealso:: :py:class:`pypmc.tools.History` :param N: An int which defines the...
python
def run(self, N=1): '''Run the chain and store the history of visited points into the member variable ``self.samples``. Returns the number of accepted points during the run. .. seealso:: :py:class:`pypmc.tools.History` :param N: An int which defines the...
[ "def", "run", "(", "self", ",", "N", "=", "1", ")", ":", "if", "N", "==", "0", ":", "return", "0", "# set the accept function", "if", "self", ".", "proposal", ".", "symmetric", ":", "get_log_rho", "=", "self", ".", "_get_log_rho_metropolis", "else", ":",...
Run the chain and store the history of visited points into the member variable ``self.samples``. Returns the number of accepted points during the run. .. seealso:: :py:class:`pypmc.tools.History` :param N: An int which defines the number of steps to run the cha...
[ "Run", "the", "chain", "and", "store", "the", "history", "of", "visited", "points", "into", "the", "member", "variable", "self", ".", "samples", ".", "Returns", "the", "number", "of", "accepted", "points", "during", "the", "run", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/markov_chain.py#L98-L163
46,675
fredRos/pypmc
pypmc/sampler/markov_chain.py
AdaptiveMarkovChain.set_adapt_params
def set_adapt_params(self, *args, **kwargs): r"""Sets variables for covariance adaptation. When :meth:`.adapt` is called, the proposal's covariance matrix is adapted in order to improve the chain's performance. The aim is to improve the efficiency of the chain by making better p...
python
def set_adapt_params(self, *args, **kwargs): r"""Sets variables for covariance adaptation. When :meth:`.adapt` is called, the proposal's covariance matrix is adapted in order to improve the chain's performance. The aim is to improve the efficiency of the chain by making better p...
[ "def", "set_adapt_params", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "!=", "(", ")", ":", "raise", "TypeError", "(", "'keyword args only; try set_adapt_parameters(keyword = value)'", ")", "self", ".", "covar_scale_multiplier",...
r"""Sets variables for covariance adaptation. When :meth:`.adapt` is called, the proposal's covariance matrix is adapted in order to improve the chain's performance. The aim is to improve the efficiency of the chain by making better proposals and forcing the acceptance rate :math:`\alph...
[ "r", "Sets", "variables", "for", "covariance", "adaptation", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/markov_chain.py#L215-L340
46,676
fredRos/pypmc
pypmc/sampler/markov_chain.py
AdaptiveMarkovChain._update_scale_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...
python
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...
[ "def", "_update_scale_factor", "(", "self", ",", "accept_rate", ")", ":", "if", "accept_rate", ">", "self", ".", "force_acceptance_max", "and", "self", ".", "covar_scale_factor", "<", "self", ".", "covar_scale_factor_max", ":", "self", ".", "covar_scale_factor", "...
Private function. Updates the covariance scaling factor ``covar_scale_factor`` according to its limits
[ "Private", "function", ".", "Updates", "the", "covariance", "scaling", "factor", "covar_scale_factor", "according", "to", "its", "limits" ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/sampler/markov_chain.py#L391-L400
46,677
python-thumbnails/python-thumbnails
thumbnails/engines/base.py
BaseThumbnailEngine.create
def create(self, original, size, crop, options=None): """ Creates a thumbnail. It loads the image, scales it and crops it. :param original: :param size: :param crop: :param options: :return: """ if options is None: options = self.evalu...
python
def create(self, original, size, crop, options=None): """ Creates a thumbnail. It loads the image, scales it and crops it. :param original: :param size: :param crop: :param options: :return: """ if options is None: options = self.evalu...
[ "def", "create", "(", "self", ",", "original", ",", "size", ",", "crop", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "self", ".", "evaluate_options", "(", ")", "image", "=", "self", ".", "engine_load_image...
Creates a thumbnail. It loads the image, scales it and crops it. :param original: :param size: :param crop: :param options: :return:
[ "Creates", "a", "thumbnail", ".", "It", "loads", "the", "image", "scales", "it", "and", "crops", "it", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/engines/base.py#L43-L60
46,678
python-thumbnails/python-thumbnails
thumbnails/engines/base.py
BaseThumbnailEngine.scale
def scale(self, image, size, crop, options): """ 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: :retur...
python
def scale(self, image, size, crop, options): """ 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: :retur...
[ "def", "scale", "(", "self", ",", "image", ",", "size", ",", "crop", ",", "options", ")", ":", "original_size", "=", "self", ".", "get_image_size", "(", "image", ")", "factor", "=", "self", ".", "_calculate_scaling_factor", "(", "original_size", ",", "size...
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:
[ "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", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/engines/base.py#L62-L81
46,679
python-thumbnails/python-thumbnails
thumbnails/engines/base.py
BaseThumbnailEngine.crop
def crop(self, 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: """ if not crop: return image ...
python
def crop(self, 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: """ if not crop: return image ...
[ "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:
[ "Wrapper", "for", "engine_crop", "will", "return", "without", "calling", "engine_crop", "if", "crop", "is", "None", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/engines/base.py#L83-L95
46,680
python-thumbnails/python-thumbnails
thumbnails/engines/base.py
BaseThumbnailEngine.colormode
def colormode(self, image, options): """ Wrapper for ``engine_colormode``. :param image: :param options: :return: """ mode = options['colormode'] return self.engine_colormode(image, mode)
python
def colormode(self, image, options): """ Wrapper for ``engine_colormode``. :param image: :param options: :return: """ mode = options['colormode'] return self.engine_colormode(image, mode)
[ "def", "colormode", "(", "self", ",", "image", ",", "options", ")", ":", "mode", "=", "options", "[", "'colormode'", "]", "return", "self", ".", "engine_colormode", "(", "image", ",", "mode", ")" ]
Wrapper for ``engine_colormode``. :param image: :param options: :return:
[ "Wrapper", "for", "engine_colormode", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/engines/base.py#L124-L133
46,681
python-thumbnails/python-thumbnails
thumbnails/engines/base.py
BaseThumbnailEngine.parse_size
def parse_size(size): """ 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 """ if size.startswith('x'): return None, int(size.replace('x', '')) ...
python
def parse_size(size): """ 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 """ if size.startswith('x'): return None, int(size.replace('x', '')) ...
[ "def", "parse_size", "(", "size", ")", ":", "if", "size", ".", "startswith", "(", "'x'", ")", ":", "return", "None", ",", "int", "(", "size", ".", "replace", "(", "'x'", ",", "''", ")", ")", "if", "'x'", "in", "size", ":", "return", "int", "(", ...
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
[ "Parses", "size", "string", "into", "a", "tuple" ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/engines/base.py#L174-L186
46,682
python-thumbnails/python-thumbnails
thumbnails/engines/base.py
BaseThumbnailEngine.parse_crop
def parse_crop(self, crop, original_size, size): """ 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. :ret...
python
def parse_crop(self, crop, original_size, size): """ 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. :ret...
[ "def", "parse_crop", "(", "self", ",", "crop", ",", "original_size", ",", "size", ")", ":", "if", "crop", "is", "None", ":", "return", "None", "crop", "=", "crop", ".", "split", "(", "' '", ")", "if", "len", "(", "crop", ")", "==", "1", ":", "cro...
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
[ "Parses", "crop", "into", "a", "tuple", "usable", "by", "the", "crop", "function", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/engines/base.py#L188-L213
46,683
python-thumbnails/python-thumbnails
thumbnails/engines/base.py
BaseThumbnailEngine.calculate_offset
def calculate_offset(percent, original_length, length): """ 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. ...
python
def calculate_offset(percent, original_length, length): """ 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. ...
[ "def", "calculate_offset", "(", "percent", ",", "original_length", ",", "length", ")", ":", "return", "int", "(", "max", "(", "0", ",", "min", "(", "percent", "*", "original_length", "/", "100.0", ",", "original_length", "-", "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
[ "Calculates", "crop", "offset", "based", "on", "percentage", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/engines/base.py#L216-L230
46,684
briandconnelly/pyfttt
pyfttt/cmd_script.py
main
def main(): """Main function for pyfttt command line tool""" 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.val...
python
def main(): """Main function for pyfttt command line tool""" 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.val...
[ "def", "main", "(", ")", ":", "args", "=", "parse_arguments", "(", ")", "if", "args", ".", "key", "is", "None", ":", "print", "(", "\"Error: Must provide IFTTT secret key.\"", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "res", "=", "pyfttt", "....
Main function for pyfttt command line tool
[ "Main", "function", "for", "pyfttt", "command", "line", "tool" ]
fed3d8ec87811cf33c87d9d102845a420204577b
https://github.com/briandconnelly/pyfttt/blob/fed3d8ec87811cf33c87d9d102845a420204577b/pyfttt/cmd_script.py#L37-L75
46,685
fredRos/pypmc
pypmc/tools/_plot.py
plot_responsibility
def plot_responsibility(data, responsibility, cmap='nipy_spectral'): '''Classify the 2D ``data`` according to the ``responsibility`` and make a scatter plot of each data point with the color of the component it is most likely from. The ``responsibility`` is normalized internally ...
python
def plot_responsibility(data, responsibility, cmap='nipy_spectral'): '''Classify the 2D ``data`` according to the ``responsibility`` and make a scatter plot of each data point with the color of the component it is most likely from. The ``responsibility`` is normalized internally ...
[ "def", "plot_responsibility", "(", "data", ",", "responsibility", ",", "cmap", "=", "'nipy_spectral'", ")", ":", "import", "numpy", "as", "np", "from", "matplotlib", "import", "pyplot", "as", "plt", "from", "matplotlib", ".", "cm", "import", "get_cmap", "data"...
Classify the 2D ``data`` according to the ``responsibility`` and make a scatter plot of each data point with the color of the component it is most likely from. The ``responsibility`` is normalized internally such that each row sums to unity. :param data: matrix-like; one row = one 2D sample ...
[ "Classify", "the", "2D", "data", "according", "to", "the", "responsibility", "and", "make", "a", "scatter", "plot", "of", "each", "data", "point", "with", "the", "color", "of", "the", "component", "it", "is", "most", "likely", "from", ".", "The", "responsi...
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/tools/_plot.py#L132-L183
46,686
thomasw/djproxy
djproxy/util.py
import_string
def import_string(dotted_path): """ Import a dotted module path. Returns the attribute/class designated by the last name in the path. Raises ImportError if the import fails. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImportError(...
python
def import_string(dotted_path): """ Import a dotted module path. Returns the attribute/class designated by the last name in the path. Raises ImportError if the import fails. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImportError(...
[ "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'", "...
Import a dotted module path. Returns the attribute/class designated by the last name in the path. Raises ImportError if the import fails.
[ "Import", "a", "dotted", "module", "path", "." ]
c8b3a44e330683f0625b67dfe3d6d995684b6e4a
https://github.com/thomasw/djproxy/blob/c8b3a44e330683f0625b67dfe3d6d995684b6e4a/djproxy/util.py#L6-L27
46,687
fredRos/pypmc
pypmc/tools/indicator/_indicator_factory.py
ball
def ball(center, radius=1., bdy=True): '''Returns the indicator function of a ball. :param center: A vector-like numpy array, defining the center of the ball.\n len(center) fixes the dimension. :param radius: Float or int, the radius of the ball :param bdy: Bool, Wh...
python
def ball(center, radius=1., bdy=True): '''Returns the indicator function of a ball. :param center: A vector-like numpy array, defining the center of the ball.\n len(center) fixes the dimension. :param radius: Float or int, the radius of the ball :param bdy: Bool, Wh...
[ "def", "ball", "(", "center", ",", "radius", "=", "1.", ",", "bdy", "=", "True", ")", ":", "center", "=", "_np", ".", "array", "(", "center", ")", "# copy input parameter", "dim", "=", "len", "(", "center", ")", "if", "bdy", ":", "def", "ball_indicat...
Returns the indicator function of a ball. :param center: A vector-like numpy array, defining the center of the ball.\n len(center) fixes the dimension. :param radius: Float or int, the radius of the ball :param bdy: Bool, When ``x`` is at the ball's boundary then ...
[ "Returns", "the", "indicator", "function", "of", "a", "ball", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/tools/indicator/_indicator_factory.py#L5-L48
46,688
fredRos/pypmc
pypmc/tools/indicator/_indicator_factory.py
hyperrectangle
def hyperrectangle(lower, upper, bdy=True): '''Returns the indicator function of a hyperrectangle. :param lower: Vector-like numpy array, defining the lower boundary of the hyperrectangle.\n len(lower) fixes the dimension. :param upper: Vector-like numpy array, defining the upper...
python
def hyperrectangle(lower, upper, bdy=True): '''Returns the indicator function of a hyperrectangle. :param lower: Vector-like numpy array, defining the lower boundary of the hyperrectangle.\n len(lower) fixes the dimension. :param upper: Vector-like numpy array, defining the upper...
[ "def", "hyperrectangle", "(", "lower", ",", "upper", ",", "bdy", "=", "True", ")", ":", "# copy input", "lower", "=", "_np", ".", "array", "(", "lower", ")", "upper", "=", "_np", ".", "array", "(", "upper", ")", "dim", "=", "len", "(", "lower", ")"...
Returns the indicator function of a hyperrectangle. :param lower: Vector-like numpy array, defining the lower boundary of the hyperrectangle.\n len(lower) fixes the dimension. :param upper: Vector-like numpy array, defining the upper boundary of the hyperrectangle.\n :param bdy:...
[ "Returns", "the", "indicator", "function", "of", "a", "hyperrectangle", "." ]
9138b67c976f0d58edd080353d16769a47794d09
https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/tools/indicator/_indicator_factory.py#L50-L96
46,689
python-thumbnails/python-thumbnails
thumbnails/__init__.py
get_thumbnail
def get_thumbnail(original, size, **options): """ Creates or gets an already created thumbnail for the given image with the given size and options. :param original: File-path, url or base64-encoded string of the image that you want an thumbnail. :param size: String with the wan...
python
def get_thumbnail(original, size, **options): """ Creates or gets an already created thumbnail for the given image with the given size and options. :param original: File-path, url or base64-encoded string of the image that you want an thumbnail. :param size: String with the wan...
[ "def", "get_thumbnail", "(", "original", ",", "size", ",", "*", "*", "options", ")", ":", "engine", "=", "get_engine", "(", ")", "cache", "=", "get_cache_backend", "(", ")", "original", "=", "SourceFile", "(", "original", ")", "crop", "=", "options", "."...
Creates or gets an already created thumbnail for the given image with the given size and options. :param original: File-path, url or base64-encoded string of the image that you want an thumbnail. :param size: String with the wanted thumbnail size. On the form: ``200x200``, ``200`` or ...
[ "Creates", "or", "gets", "an", "already", "created", "thumbnail", "for", "the", "given", "image", "with", "the", "given", "size", "and", "options", "." ]
d8dc0ff5410f730de2a0e5759e8a818b19de35b9
https://github.com/python-thumbnails/python-thumbnails/blob/d8dc0ff5410f730de2a0e5759e8a818b19de35b9/thumbnails/__init__.py#L11-L65
46,690
TheClimateCorporation/properscoring
properscoring/_utils.py
argsort_indices
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
python
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
[ "def", "argsort_indices", "(", "a", ",", "axis", "=", "-", "1", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ")", "ind", "=", "list", "(", "np", ".", "ix_", "(", "*", "[", "np", ".", "arange", "(", "d", ")", "for", "d", "in", "a", ...
Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional
[ "Like", "argsort", "but", "returns", "an", "index", "suitable", "for", "sorting", "the", "the", "original", "array", "even", "if", "that", "array", "is", "multidimensional" ]
1ca13dcbc1abf53d07474b74fbe3567fd4045668
https://github.com/TheClimateCorporation/properscoring/blob/1ca13dcbc1abf53d07474b74fbe3567fd4045668/properscoring/_utils.py#L12-L19
46,691
briandconnelly/pyfttt
pyfttt/sending.py
send_event
def send_event(api_key, event, value1=None, value2=None, value3=None): """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 th...
python
def send_event(api_key, event, value1=None, value2=None, value3=None): """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 th...
[ "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", ",", ...
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...
[ "Send", "an", "event", "to", "the", "IFTTT", "maker", "channel" ]
fed3d8ec87811cf33c87d9d102845a420204577b
https://github.com/briandconnelly/pyfttt/blob/fed3d8ec87811cf33c87d9d102845a420204577b/pyfttt/sending.py#L7-L28
46,692
zyga/guacamole
guacamole/recipes/cmd.py
get_localized_docstring
def get_localized_docstring(obj, domain): """Get a cleaned-up, localized copy of docstring of this class.""" if obj.__class__.__doc__ is not None: return inspect.cleandoc( gettext.dgettext(domain, obj.__class__.__doc__))
python
def get_localized_docstring(obj, domain): """Get a cleaned-up, localized copy of docstring of this class.""" if obj.__class__.__doc__ is not None: return inspect.cleandoc( gettext.dgettext(domain, obj.__class__.__doc__))
[ "def", "get_localized_docstring", "(", "obj", ",", "domain", ")", ":", "if", "obj", ".", "__class__", ".", "__doc__", "is", "not", "None", ":", "return", "inspect", ".", "cleandoc", "(", "gettext", ".", "dgettext", "(", "domain", ",", "obj", ".", "__clas...
Get a cleaned-up, localized copy of docstring of this class.
[ "Get", "a", "cleaned", "-", "up", "localized", "copy", "of", "docstring", "of", "this", "class", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/recipes/cmd.py#L396-L400
46,693
zyga/guacamole
guacamole/recipes/cmd.py
Command.get_cmd_help
def get_cmd_help(self): """ 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 """ ...
python
def get_cmd_help(self): """ 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_help", "(", "self", ")", ":", "try", ":", "return", "self", ".", "help", "except", "AttributeError", ":", "pass", "try", ":", "return", "get_localized_docstring", "(", "self", ",", "self", ".", "get_gettext_domain", "(", ")", ")", ".", "spl...
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
[ "Get", "the", "single", "-", "line", "help", "of", "this", "command", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/recipes/cmd.py#L216-L237
46,694
zyga/guacamole
guacamole/recipes/cmd.py
Command.get_cmd_description
def get_cmd_description(self): """ 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@``...
python
def get_cmd_description(self): """ 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@``...
[ "def", "get_cmd_description", "(", "self", ")", ":", "try", ":", "return", "self", ".", "description", "except", "AttributeError", ":", "pass", "try", ":", "return", "'\\n'", ".", "join", "(", "get_localized_docstring", "(", "self", ",", "self", ".", "get_ge...
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...
[ "Get", "the", "leading", "multi", "-", "line", "description", "of", "this", "command", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/recipes/cmd.py#L239-L272
46,695
zyga/guacamole
guacamole/recipes/cmd.py
Command.get_cmd_epilog
def get_cmd_epilog(self): """ 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 ...
python
def get_cmd_epilog(self): """ 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 ...
[ "def", "get_cmd_epilog", "(", "self", ")", ":", "try", ":", "return", "self", ".", "source", ".", "epilog", "except", "AttributeError", ":", "pass", "try", ":", "return", "'\\n'", ".", "join", "(", "get_localized_docstring", "(", "self", ",", "self", ".", ...
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 ...
[ "Get", "the", "trailing", "multi", "-", "line", "description", "of", "this", "command", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/recipes/cmd.py#L274-L305
46,696
zyga/guacamole
guacamole/recipes/cmd.py
Command.main
def main(self, argv=None, exit=True): """ Shortcut for running a command. See :meth:`guacamole.recipes.Recipe.main()` for details. """ return CommandRecipe(self).main(argv, exit)
python
def main(self, argv=None, exit=True): """ Shortcut for running a command. See :meth:`guacamole.recipes.Recipe.main()` for details. """ return CommandRecipe(self).main(argv, exit)
[ "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.
[ "Shortcut", "for", "running", "a", "command", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/recipes/cmd.py#L387-L393
46,697
zyga/guacamole
guacamole/recipes/cmd.py
CommandRecipe.get_ingredients
def get_ingredients(self): """Get a list of ingredients for guacamole.""" return [ cmdtree.CommandTreeBuilder(self.command), cmdtree.CommandTreeDispatcher(), argparse.AutocompleteIngredient(), argparse.ParserIngredient(), crash.VerboseCrashHand...
python
def get_ingredients(self): """Get a list of ingredients for guacamole.""" return [ cmdtree.CommandTreeBuilder(self.command), cmdtree.CommandTreeDispatcher(), argparse.AutocompleteIngredient(), argparse.ParserIngredient(), crash.VerboseCrashHand...
[ "def", "get_ingredients", "(", "self", ")", ":", "return", "[", "cmdtree", ".", "CommandTreeBuilder", "(", "self", ".", "command", ")", ",", "cmdtree", ".", "CommandTreeDispatcher", "(", ")", ",", "argparse", ".", "AutocompleteIngredient", "(", ")", ",", "ar...
Get a list of ingredients for guacamole.
[ "Get", "a", "list", "of", "ingredients", "for", "guacamole", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/guacamole/recipes/cmd.py#L411-L421
46,698
zyga/guacamole
examples/adder.py
Addder.register_arguments
def register_arguments(self, parser): """ Guacamole method used by the argparse ingredient. :param parser: Argument parser (from :mod:`argparse`) specific to this command. """ parser.add_argument('x', type=int, help='the first value') parser.add_argument('y',...
python
def register_arguments(self, parser): """ Guacamole method used by the argparse ingredient. :param parser: Argument parser (from :mod:`argparse`) specific to this command. """ parser.add_argument('x', type=int, help='the first value') parser.add_argument('y',...
[ "def", "register_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'x'", ",", "type", "=", "int", ",", "help", "=", "'the first value'", ")", "parser", ".", "add_argument", "(", "'y'", ",", "type", "=", "int", ",", ...
Guacamole method used by the argparse ingredient. :param parser: Argument parser (from :mod:`argparse`) specific to this command.
[ "Guacamole", "method", "used", "by", "the", "argparse", "ingredient", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/examples/adder.py#L45-L53
46,699
zyga/guacamole
examples/rainbow.py
ANSIDemo.invoked
def invoked(self, ctx): """Method called when the command is invoked.""" 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) ...
python
def invoked(self, ctx): """Method called when the command is invoked.""" 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) ...
[ "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'...
Method called when the command is invoked.
[ "Method", "called", "when", "the", "command", "is", "invoked", "." ]
105c10a798144e3b89659b500d7c2b84b0c76546
https://github.com/zyga/guacamole/blob/105c10a798144e3b89659b500d7c2b84b0c76546/examples/rainbow.py#L45-L55