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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
danidee10/Staticfy
staticfy/staticfy.py
get_elements
def get_elements(html_file, tags): """ Extract all the elements we're interested in. Returns a list of tuples with the attribute as first item and the list of elements as the second item. """ with open(html_file) as f: document = BeautifulSoup(f, 'html.parser') def condition(ta...
python
def get_elements(html_file, tags): """ Extract all the elements we're interested in. Returns a list of tuples with the attribute as first item and the list of elements as the second item. """ with open(html_file) as f: document = BeautifulSoup(f, 'html.parser') def condition(ta...
[ "def", "get_elements", "(", "html_file", ",", "tags", ")", ":", "with", "open", "(", "html_file", ")", "as", "f", ":", "document", "=", "BeautifulSoup", "(", "f", ",", "'html.parser'", ")", "def", "condition", "(", "tag", ",", "attr", ")", ":", "# Don'...
Extract all the elements we're interested in. Returns a list of tuples with the attribute as first item and the list of elements as the second item.
[ "Extract", "all", "the", "elements", "we", "re", "interested", "in", "." ]
ebc555b00377394b0f714e4a173d37833fec90cb
https://github.com/danidee10/Staticfy/blob/ebc555b00377394b0f714e4a173d37833fec90cb/staticfy/staticfy.py#L71-L89
train
63,500
danidee10/Staticfy
staticfy/staticfy.py
replace_lines
def replace_lines(html_file, transformed): """Replace lines in the old file with the transformed lines.""" result = [] with codecs.open(html_file, 'r', 'utf-8') as input_file: for line in input_file: # replace all single quotes with double quotes line = re.sub(r'\'', '"', lin...
python
def replace_lines(html_file, transformed): """Replace lines in the old file with the transformed lines.""" result = [] with codecs.open(html_file, 'r', 'utf-8') as input_file: for line in input_file: # replace all single quotes with double quotes line = re.sub(r'\'', '"', lin...
[ "def", "replace_lines", "(", "html_file", ",", "transformed", ")", ":", "result", "=", "[", "]", "with", "codecs", ".", "open", "(", "html_file", ",", "'r'", ",", "'utf-8'", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "# replace...
Replace lines in the old file with the transformed lines.
[ "Replace", "lines", "in", "the", "old", "file", "with", "the", "transformed", "lines", "." ]
ebc555b00377394b0f714e4a173d37833fec90cb
https://github.com/danidee10/Staticfy/blob/ebc555b00377394b0f714e4a173d37833fec90cb/staticfy/staticfy.py#L92-L111
train
63,501
danidee10/Staticfy
staticfy/staticfy.py
staticfy
def staticfy(html_file, args=argparse.ArgumentParser()): """ Staticfy method. Loop through each line of the file and replaces the old links """ # unpack arguments static_endpoint = args.static_endpoint or 'static' framework = args.framework or os.getenv('STATICFY_FRAMEWORK', 'flask') ad...
python
def staticfy(html_file, args=argparse.ArgumentParser()): """ Staticfy method. Loop through each line of the file and replaces the old links """ # unpack arguments static_endpoint = args.static_endpoint or 'static' framework = args.framework or os.getenv('STATICFY_FRAMEWORK', 'flask') ad...
[ "def", "staticfy", "(", "html_file", ",", "args", "=", "argparse", ".", "ArgumentParser", "(", ")", ")", ":", "# unpack arguments", "static_endpoint", "=", "args", ".", "static_endpoint", "or", "'static'", "framework", "=", "args", ".", "framework", "or", "os"...
Staticfy method. Loop through each line of the file and replaces the old links
[ "Staticfy", "method", "." ]
ebc555b00377394b0f714e4a173d37833fec90cb
https://github.com/danidee10/Staticfy/blob/ebc555b00377394b0f714e4a173d37833fec90cb/staticfy/staticfy.py#L114-L144
train
63,502
danidee10/Staticfy
staticfy/staticfy.py
file_ops
def file_ops(staticfied, args): """Write to stdout or a file""" destination = args.o or args.output if destination: with open(destination, 'w') as file: file.write(staticfied) else: print(staticfied)
python
def file_ops(staticfied, args): """Write to stdout or a file""" destination = args.o or args.output if destination: with open(destination, 'w') as file: file.write(staticfied) else: print(staticfied)
[ "def", "file_ops", "(", "staticfied", ",", "args", ")", ":", "destination", "=", "args", ".", "o", "or", "args", ".", "output", "if", "destination", ":", "with", "open", "(", "destination", ",", "'w'", ")", "as", "file", ":", "file", ".", "write", "(...
Write to stdout or a file
[ "Write", "to", "stdout", "or", "a", "file" ]
ebc555b00377394b0f714e4a173d37833fec90cb
https://github.com/danidee10/Staticfy/blob/ebc555b00377394b0f714e4a173d37833fec90cb/staticfy/staticfy.py#L147-L155
train
63,503
mbarkhau/tinypng
tinypng/api.py
find_keys
def find_keys(args): """Get keys specified in arguments returns list of keys or None """ key = args['--key'] if key: return [key] keyfile = args['--apikeys'] if keyfile: return read_keyfile(keyfile) envkey = os.environ.get('TINYPNG_API_KEY', None) if envkey: ...
python
def find_keys(args): """Get keys specified in arguments returns list of keys or None """ key = args['--key'] if key: return [key] keyfile = args['--apikeys'] if keyfile: return read_keyfile(keyfile) envkey = os.environ.get('TINYPNG_API_KEY', None) if envkey: ...
[ "def", "find_keys", "(", "args", ")", ":", "key", "=", "args", "[", "'--key'", "]", "if", "key", ":", "return", "[", "key", "]", "keyfile", "=", "args", "[", "'--apikeys'", "]", "if", "keyfile", ":", "return", "read_keyfile", "(", "keyfile", ")", "en...
Get keys specified in arguments returns list of keys or None
[ "Get", "keys", "specified", "in", "arguments" ]
58e33cd5b46b26aab530a184b70856f7e936d79a
https://github.com/mbarkhau/tinypng/blob/58e33cd5b46b26aab530a184b70856f7e936d79a/tinypng/api.py#L24-L50
train
63,504
mbarkhau/tinypng
tinypng/api.py
get_shrunk_data
def get_shrunk_data(shrink_info): """Read shrunk file from tinypng.org api.""" out_url = shrink_info['output']['url'] try: return requests.get(out_url).content except HTTPError as err: if err.code != 404: raise exc = ValueError("Unable to read png file \"{0}\"".forma...
python
def get_shrunk_data(shrink_info): """Read shrunk file from tinypng.org api.""" out_url = shrink_info['output']['url'] try: return requests.get(out_url).content except HTTPError as err: if err.code != 404: raise exc = ValueError("Unable to read png file \"{0}\"".forma...
[ "def", "get_shrunk_data", "(", "shrink_info", ")", ":", "out_url", "=", "shrink_info", "[", "'output'", "]", "[", "'url'", "]", "try", ":", "return", "requests", ".", "get", "(", "out_url", ")", ".", "content", "except", "HTTPError", "as", "err", ":", "i...
Read shrunk file from tinypng.org api.
[ "Read", "shrunk", "file", "from", "tinypng", ".", "org", "api", "." ]
58e33cd5b46b26aab530a184b70856f7e936d79a
https://github.com/mbarkhau/tinypng/blob/58e33cd5b46b26aab530a184b70856f7e936d79a/tinypng/api.py#L102-L113
train
63,505
mbarkhau/tinypng
tinypng/api.py
shrink_file
def shrink_file(in_filepath, api_key=None, out_filepath=None): """Shrink png file and write it back to a new file The default file path replaces ".png" with ".tiny.png". returns api_info (including info['ouput']['filepath']) """ info = get_shrink_file_info(in_filepath, api_key, out_filepath) wr...
python
def shrink_file(in_filepath, api_key=None, out_filepath=None): """Shrink png file and write it back to a new file The default file path replaces ".png" with ".tiny.png". returns api_info (including info['ouput']['filepath']) """ info = get_shrink_file_info(in_filepath, api_key, out_filepath) wr...
[ "def", "shrink_file", "(", "in_filepath", ",", "api_key", "=", "None", ",", "out_filepath", "=", "None", ")", ":", "info", "=", "get_shrink_file_info", "(", "in_filepath", ",", "api_key", ",", "out_filepath", ")", "write_shrunk_file", "(", "info", ")", "return...
Shrink png file and write it back to a new file The default file path replaces ".png" with ".tiny.png". returns api_info (including info['ouput']['filepath'])
[ "Shrink", "png", "file", "and", "write", "it", "back", "to", "a", "new", "file" ]
58e33cd5b46b26aab530a184b70856f7e936d79a
https://github.com/mbarkhau/tinypng/blob/58e33cd5b46b26aab530a184b70856f7e936d79a/tinypng/api.py#L144-L152
train
63,506
TeleSign/python_telesign
telesign/util.py
verify_telesign_callback_signature
def verify_telesign_callback_signature(api_key, signature, json_str): """ Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature. :param api_key: the TeleSign API api_key associated with your account. :param signature: the TeleSign Authorization he...
python
def verify_telesign_callback_signature(api_key, signature, json_str): """ Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature. :param api_key: the TeleSign API api_key associated with your account. :param signature: the TeleSign Authorization he...
[ "def", "verify_telesign_callback_signature", "(", "api_key", ",", "signature", ",", "json_str", ")", ":", "your_signature", "=", "b64encode", "(", "HMAC", "(", "b64decode", "(", "api_key", ")", ",", "json_str", ".", "encode", "(", "\"utf-8\"", ")", ",", "sha25...
Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature. :param api_key: the TeleSign API api_key associated with your account. :param signature: the TeleSign Authorization header value supplied in the callback, as a string. :param json_str: the POST bo...
[ "Verify", "that", "a", "callback", "was", "made", "by", "TeleSign", "and", "was", "not", "sent", "by", "a", "malicious", "client", "by", "verifying", "the", "signature", "." ]
f0c2e4373dc8d685e1a7d65444b5e55955c340cb
https://github.com/TeleSign/python_telesign/blob/f0c2e4373dc8d685e1a7d65444b5e55955c340cb/telesign/util.py#L23-L42
train
63,507
Dani4kor/stockfishpy
stockfishpy/stockfishpy.py
Engine.setposition
def setposition(self, position): """ The move format is in long algebraic notation. Takes list of stirngs = ['e2e4', 'd7d5'] OR FEN = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1' """ try: if isinstance(position, list): ...
python
def setposition(self, position): """ The move format is in long algebraic notation. Takes list of stirngs = ['e2e4', 'd7d5'] OR FEN = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1' """ try: if isinstance(position, list): ...
[ "def", "setposition", "(", "self", ",", "position", ")", ":", "try", ":", "if", "isinstance", "(", "position", ",", "list", ")", ":", "self", ".", "send", "(", "'position startpos moves {}'", ".", "format", "(", "self", ".", "__listtostring", "(", "positio...
The move format is in long algebraic notation. Takes list of stirngs = ['e2e4', 'd7d5'] OR FEN = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'
[ "The", "move", "format", "is", "in", "long", "algebraic", "notation", "." ]
af26e8180a7d186ca0cb48d06bac9f2561432f4f
https://github.com/Dani4kor/stockfishpy/blob/af26e8180a7d186ca0cb48d06bac9f2561432f4f/stockfishpy/stockfishpy.py#L107-L156
train
63,508
jbfavre/python-protobix
protobix/datacontainer.py
DataContainer.add_item
def add_item(self, host, key, value, clock=None, state=0): """ Add a single item into DataContainer :host: hostname to which item will be linked to :key: item key as defined in Zabbix :value: item value :clock: timestemp as integer. If not provided self.clock()) will be ...
python
def add_item(self, host, key, value, clock=None, state=0): """ Add a single item into DataContainer :host: hostname to which item will be linked to :key: item key as defined in Zabbix :value: item value :clock: timestemp as integer. If not provided self.clock()) will be ...
[ "def", "add_item", "(", "self", ",", "host", ",", "key", ",", "value", ",", "clock", "=", "None", ",", "state", "=", "0", ")", ":", "if", "clock", "is", "None", ":", "clock", "=", "self", ".", "clock", "if", "self", ".", "_config", ".", "data_typ...
Add a single item into DataContainer :host: hostname to which item will be linked to :key: item key as defined in Zabbix :value: item value :clock: timestemp as integer. If not provided self.clock()) will be used
[ "Add", "a", "single", "item", "into", "DataContainer" ]
96b7095a9c2485c9e1bdba098b7d82b93f91acb1
https://github.com/jbfavre/python-protobix/blob/96b7095a9c2485c9e1bdba098b7d82b93f91acb1/protobix/datacontainer.py#L37-L58
train
63,509
jbfavre/python-protobix
protobix/datacontainer.py
DataContainer.add
def add(self, data): """ Add a list of item into the container :data: dict of items & value per hostname """ for host in data: for key in data[host]: if not data[host][key] == []: self.add_item(host, key, data[host][key])
python
def add(self, data): """ Add a list of item into the container :data: dict of items & value per hostname """ for host in data: for key in data[host]: if not data[host][key] == []: self.add_item(host, key, data[host][key])
[ "def", "add", "(", "self", ",", "data", ")", ":", "for", "host", "in", "data", ":", "for", "key", "in", "data", "[", "host", "]", ":", "if", "not", "data", "[", "host", "]", "[", "key", "]", "==", "[", "]", ":", "self", ".", "add_item", "(", ...
Add a list of item into the container :data: dict of items & value per hostname
[ "Add", "a", "list", "of", "item", "into", "the", "container" ]
96b7095a9c2485c9e1bdba098b7d82b93f91acb1
https://github.com/jbfavre/python-protobix/blob/96b7095a9c2485c9e1bdba098b7d82b93f91acb1/protobix/datacontainer.py#L60-L69
train
63,510
jbfavre/python-protobix
protobix/datacontainer.py
DataContainer._send_common
def _send_common(self, item): """ Common part of sending operations Calls SenderProtocol._send_to_zabbix Returns result as provided by _handle_response :item: either a list or a single item depending on debug_level """ total = len(item) processed = failed...
python
def _send_common(self, item): """ Common part of sending operations Calls SenderProtocol._send_to_zabbix Returns result as provided by _handle_response :item: either a list or a single item depending on debug_level """ total = len(item) processed = failed...
[ "def", "_send_common", "(", "self", ",", "item", ")", ":", "total", "=", "len", "(", "item", ")", "processed", "=", "failed", "=", "time", "=", "0", "if", "self", ".", "_config", ".", "dryrun", "is", "True", ":", "total", "=", "len", "(", "item", ...
Common part of sending operations Calls SenderProtocol._send_to_zabbix Returns result as provided by _handle_response :item: either a list or a single item depending on debug_level
[ "Common", "part", "of", "sending", "operations", "Calls", "SenderProtocol", ".", "_send_to_zabbix", "Returns", "result", "as", "provided", "by", "_handle_response" ]
96b7095a9c2485c9e1bdba098b7d82b93f91acb1
https://github.com/jbfavre/python-protobix/blob/96b7095a9c2485c9e1bdba098b7d82b93f91acb1/protobix/datacontainer.py#L149-L184
train
63,511
jbfavre/python-protobix
protobix/datacontainer.py
DataContainer._reset
def _reset(self): """ Reset main DataContainer properties """ # Reset DataContainer to default values # So that it can be reused if self.logger: # pragma: no cover self.logger.info("Reset DataContainer") self._items_list = [] self._config.data_...
python
def _reset(self): """ Reset main DataContainer properties """ # Reset DataContainer to default values # So that it can be reused if self.logger: # pragma: no cover self.logger.info("Reset DataContainer") self._items_list = [] self._config.data_...
[ "def", "_reset", "(", "self", ")", ":", "# Reset DataContainer to default values", "# So that it can be reused", "if", "self", ".", "logger", ":", "# pragma: no cover", "self", ".", "logger", ".", "info", "(", "\"Reset DataContainer\"", ")", "self", ".", "_items_list"...
Reset main DataContainer properties
[ "Reset", "main", "DataContainer", "properties" ]
96b7095a9c2485c9e1bdba098b7d82b93f91acb1
https://github.com/jbfavre/python-protobix/blob/96b7095a9c2485c9e1bdba098b7d82b93f91acb1/protobix/datacontainer.py#L186-L195
train
63,512
jbfavre/python-protobix
protobix/datacontainer.py
DataContainer.logger
def logger(self, value): """ Set logger instance for the class """ if isinstance(value, logging.Logger): self._logger = value else: if self._logger: # pragma: no cover self._logger.error("logger requires a logging instance") rai...
python
def logger(self, value): """ Set logger instance for the class """ if isinstance(value, logging.Logger): self._logger = value else: if self._logger: # pragma: no cover self._logger.error("logger requires a logging instance") rai...
[ "def", "logger", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "logging", ".", "Logger", ")", ":", "self", ".", "_logger", "=", "value", "else", ":", "if", "self", ".", "_logger", ":", "# pragma: no cover", "self", ".", ...
Set logger instance for the class
[ "Set", "logger", "instance", "for", "the", "class" ]
96b7095a9c2485c9e1bdba098b7d82b93f91acb1
https://github.com/jbfavre/python-protobix/blob/96b7095a9c2485c9e1bdba098b7d82b93f91acb1/protobix/datacontainer.py#L205-L214
train
63,513
GearPlug/jira-python
jira/client.py
Client.get_issue
def get_issue(self, issue_id, params=None): """Returns a full representation of the issue for the given issue key. The issue JSON consists of the issue key and a collection of fields. Additional information like links to workflow transition sub-resources, or HTML rendered values of the fields s...
python
def get_issue(self, issue_id, params=None): """Returns a full representation of the issue for the given issue key. The issue JSON consists of the issue key and a collection of fields. Additional information like links to workflow transition sub-resources, or HTML rendered values of the fields s...
[ "def", "get_issue", "(", "self", ",", "issue_id", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_get", "(", "self", ".", "API_URL", "+", "'issue/{}'", ".", "format", "(", "issue_id", ")", ",", "params", "=", "params", ")" ]
Returns a full representation of the issue for the given issue key. The issue JSON consists of the issue key and a collection of fields. Additional information like links to workflow transition sub-resources, or HTML rendered values of the fields supporting HTML rendering can be retrieved with ...
[ "Returns", "a", "full", "representation", "of", "the", "issue", "for", "the", "given", "issue", "key", "." ]
2af5a3defc44a80d9df49dec6808e6b63bde6f69
https://github.com/GearPlug/jira-python/blob/2af5a3defc44a80d9df49dec6808e6b63bde6f69/jira/client.py#L57-L80
train
63,514
GearPlug/jira-python
jira/client.py
Client.create_issue
def create_issue(self, data, params=None): """Creates an issue or a sub-task from a JSON representation. You can provide two parameters in request's body: update or fields. The fields, that can be set on an issue create operation, can be determined using the /rest/api/2/issue/createmeta resourc...
python
def create_issue(self, data, params=None): """Creates an issue or a sub-task from a JSON representation. You can provide two parameters in request's body: update or fields. The fields, that can be set on an issue create operation, can be determined using the /rest/api/2/issue/createmeta resourc...
[ "def", "create_issue", "(", "self", ",", "data", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_post", "(", "self", ".", "API_URL", "+", "'issue'", ",", "data", "=", "data", ",", "params", "=", "params", ")" ]
Creates an issue or a sub-task from a JSON representation. You can provide two parameters in request's body: update or fields. The fields, that can be set on an issue create operation, can be determined using the /rest/api/2/issue/createmeta resource. If a particular field is not configured to ...
[ "Creates", "an", "issue", "or", "a", "sub", "-", "task", "from", "a", "JSON", "representation", "." ]
2af5a3defc44a80d9df49dec6808e6b63bde6f69
https://github.com/GearPlug/jira-python/blob/2af5a3defc44a80d9df49dec6808e6b63bde6f69/jira/client.py#L82-L102
train
63,515
GearPlug/jira-python
jira/client.py
Client.delete_issue
def delete_issue(self, issue_id, params=None): """Deletes an individual issue. If the issue has sub-tasks you must set the deleteSubtasks=true parameter to delete the issue. You cannot delete an issue without deleting its sub-tasks. Args: issue_id: params: ...
python
def delete_issue(self, issue_id, params=None): """Deletes an individual issue. If the issue has sub-tasks you must set the deleteSubtasks=true parameter to delete the issue. You cannot delete an issue without deleting its sub-tasks. Args: issue_id: params: ...
[ "def", "delete_issue", "(", "self", ",", "issue_id", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_delete", "(", "self", ".", "API_URL", "+", "'issue/{}'", ".", "format", "(", "issue_id", ")", ",", "params", "=", "params", ")" ]
Deletes an individual issue. If the issue has sub-tasks you must set the deleteSubtasks=true parameter to delete the issue. You cannot delete an issue without deleting its sub-tasks. Args: issue_id: params: Returns:
[ "Deletes", "an", "individual", "issue", "." ]
2af5a3defc44a80d9df49dec6808e6b63bde6f69
https://github.com/GearPlug/jira-python/blob/2af5a3defc44a80d9df49dec6808e6b63bde6f69/jira/client.py#L104-L117
train
63,516
nephila/python-taiga
taiga/models/base.py
ListResource.list
def list(self, pagination=True, page_size=None, page=None, **queryparams): """ Retrieves a list of objects. By default uses local cache and remote pagination If pagination is used and no page is requested (the default), all the remote objects are retrieved and appended in a sin...
python
def list(self, pagination=True, page_size=None, page=None, **queryparams): """ Retrieves a list of objects. By default uses local cache and remote pagination If pagination is used and no page is requested (the default), all the remote objects are retrieved and appended in a sin...
[ "def", "list", "(", "self", ",", "pagination", "=", "True", ",", "page_size", "=", "None", ",", "page", "=", "None", ",", "*", "*", "queryparams", ")", ":", "if", "page_size", "and", "pagination", ":", "try", ":", "page_size", "=", "int", "(", "page_...
Retrieves a list of objects. By default uses local cache and remote pagination If pagination is used and no page is requested (the default), all the remote objects are retrieved and appended in a single list. If pagination is disabled, all the objects are fetched from the endp...
[ "Retrieves", "a", "list", "of", "objects", "." ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/base.py#L37-L86
train
63,517
nephila/python-taiga
taiga/models/base.py
InstanceResource.parse
def parse(cls, requester, entry): """ Turns a JSON object into a model instance. """ if not type(entry) is dict: return entry for key_to_parse, cls_to_parse in six.iteritems(cls.parser): if key_to_parse in entry: entry[key_to_parse] = cls_t...
python
def parse(cls, requester, entry): """ Turns a JSON object into a model instance. """ if not type(entry) is dict: return entry for key_to_parse, cls_to_parse in six.iteritems(cls.parser): if key_to_parse in entry: entry[key_to_parse] = cls_t...
[ "def", "parse", "(", "cls", ",", "requester", ",", "entry", ")", ":", "if", "not", "type", "(", "entry", ")", "is", "dict", ":", "return", "entry", "for", "key_to_parse", ",", "cls_to_parse", "in", "six", ".", "iteritems", "(", "cls", ".", "parser", ...
Turns a JSON object into a model instance.
[ "Turns", "a", "JSON", "object", "into", "a", "model", "instance", "." ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/base.py#L221-L232
train
63,518
nephila/python-taiga
taiga/models/models.py
CustomAttributeResource.set_attribute
def set_attribute(self, id, value, version=1): """ Set attribute to a specific value :param id: id of the attribute :param value: value of the attribute :param version: version of the attribute (default = 1) """ attributes = self._get_attributes(cache=True) ...
python
def set_attribute(self, id, value, version=1): """ Set attribute to a specific value :param id: id of the attribute :param value: value of the attribute :param version: version of the attribute (default = 1) """ attributes = self._get_attributes(cache=True) ...
[ "def", "set_attribute", "(", "self", ",", "id", ",", "value", ",", "version", "=", "1", ")", ":", "attributes", "=", "self", ".", "_get_attributes", "(", "cache", "=", "True", ")", "formatted_id", "=", "'{0}'", ".", "format", "(", "id", ")", "attribute...
Set attribute to a specific value :param id: id of the attribute :param value: value of the attribute :param version: version of the attribute (default = 1)
[ "Set", "attribute", "to", "a", "specific", "value" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/models.py#L30-L54
train
63,519
nephila/python-taiga
taiga/models/models.py
Project.issues_stats
def issues_stats(self): """ Get stats for issues of the project """ response = self.requester.get( '/{endpoint}/{id}/issues_stats', endpoint=self.endpoint, id=self.id ) return response.json()
python
def issues_stats(self): """ Get stats for issues of the project """ response = self.requester.get( '/{endpoint}/{id}/issues_stats', endpoint=self.endpoint, id=self.id ) return response.json()
[ "def", "issues_stats", "(", "self", ")", ":", "response", "=", "self", ".", "requester", ".", "get", "(", "'/{endpoint}/{id}/issues_stats'", ",", "endpoint", "=", "self", ".", "endpoint", ",", "id", "=", "self", ".", "id", ")", "return", "response", ".", ...
Get stats for issues of the project
[ "Get", "stats", "for", "issues", "of", "the", "project" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/models.py#L1062-L1070
train
63,520
nephila/python-taiga
taiga/models/models.py
Project.like
def like(self): """ Like the project """ self.requester.post( '/{endpoint}/{id}/like', endpoint=self.endpoint, id=self.id ) return self
python
def like(self): """ Like the project """ self.requester.post( '/{endpoint}/{id}/like', endpoint=self.endpoint, id=self.id ) return self
[ "def", "like", "(", "self", ")", ":", "self", ".", "requester", ".", "post", "(", "'/{endpoint}/{id}/like'", ",", "endpoint", "=", "self", ".", "endpoint", ",", "id", "=", "self", ".", "id", ")", "return", "self" ]
Like the project
[ "Like", "the", "project" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/models.py#L1072-L1080
train
63,521
nephila/python-taiga
taiga/models/models.py
Project.unlike
def unlike(self): """ Unlike the project """ self.requester.post( '/{endpoint}/{id}/unlike', endpoint=self.endpoint, id=self.id ) return self
python
def unlike(self): """ Unlike the project """ self.requester.post( '/{endpoint}/{id}/unlike', endpoint=self.endpoint, id=self.id ) return self
[ "def", "unlike", "(", "self", ")", ":", "self", ".", "requester", ".", "post", "(", "'/{endpoint}/{id}/unlike'", ",", "endpoint", "=", "self", ".", "endpoint", ",", "id", "=", "self", ".", "id", ")", "return", "self" ]
Unlike the project
[ "Unlike", "the", "project" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/models.py#L1082-L1090
train
63,522
nephila/python-taiga
taiga/models/models.py
Project.star
def star(self): """ Stars the project .. deprecated:: 0.8.5 Update Taiga and use like instead """ warnings.warn( "Deprecated! Update Taiga and use .like() instead", DeprecationWarning ) self.requester.post( '/{endp...
python
def star(self): """ Stars the project .. deprecated:: 0.8.5 Update Taiga and use like instead """ warnings.warn( "Deprecated! Update Taiga and use .like() instead", DeprecationWarning ) self.requester.post( '/{endp...
[ "def", "star", "(", "self", ")", ":", "warnings", ".", "warn", "(", "\"Deprecated! Update Taiga and use .like() instead\"", ",", "DeprecationWarning", ")", "self", ".", "requester", ".", "post", "(", "'/{endpoint}/{id}/star'", ",", "endpoint", "=", "self", ".", "e...
Stars the project .. deprecated:: 0.8.5 Update Taiga and use like instead
[ "Stars", "the", "project" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/models.py#L1092-L1108
train
63,523
nephila/python-taiga
taiga/models/models.py
HistoryEntity.get
def get(self, resource_id): """ Get a history element :param resource_id: ... """ response = self.requester.get( '/{endpoint}/{entity}/{id}', endpoint=self.endpoint, entity=self.entity, id=resource_id, paginate=False ) return r...
python
def get(self, resource_id): """ Get a history element :param resource_id: ... """ response = self.requester.get( '/{endpoint}/{entity}/{id}', endpoint=self.endpoint, entity=self.entity, id=resource_id, paginate=False ) return r...
[ "def", "get", "(", "self", ",", "resource_id", ")", ":", "response", "=", "self", ".", "requester", ".", "get", "(", "'/{endpoint}/{entity}/{id}'", ",", "endpoint", "=", "self", ".", "endpoint", ",", "entity", "=", "self", ".", "entity", ",", "id", "=", ...
Get a history element :param resource_id: ...
[ "Get", "a", "history", "element" ]
5b471d6b8b59e5d410162a6f1c2f0d4188445a56
https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/models.py#L1695-L1706
train
63,524
antidot/Pyckson
src/pyckson/parser.py
parse
def parse(cls, value): """Takes a class and a dict and try to build an instance of the class :param cls: The class to parse :param value: either a dict, a list or a scalar value """ if is_list_annotation(cls): if not isinstance(value, list): raise TypeError('Could not parse {} b...
python
def parse(cls, value): """Takes a class and a dict and try to build an instance of the class :param cls: The class to parse :param value: either a dict, a list or a scalar value """ if is_list_annotation(cls): if not isinstance(value, list): raise TypeError('Could not parse {} b...
[ "def", "parse", "(", "cls", ",", "value", ")", ":", "if", "is_list_annotation", "(", "cls", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "TypeError", "(", "'Could not parse {} because value is not a list'", ".", "format", ...
Takes a class and a dict and try to build an instance of the class :param cls: The class to parse :param value: either a dict, a list or a scalar value
[ "Takes", "a", "class", "and", "a", "dict", "and", "try", "to", "build", "an", "instance", "of", "the", "class" ]
44e625164a53081eb46b8d4bc38f947a575de505
https://github.com/antidot/Pyckson/blob/44e625164a53081eb46b8d4bc38f947a575de505/src/pyckson/parser.py#L6-L17
train
63,525
lwgray/pyEntrezId
PyEntrezId/Conversion.py
Conversion.convert_ensembl_to_entrez
def convert_ensembl_to_entrez(self, ensembl): """Convert Ensembl Id to Entrez Gene Id""" if 'ENST' in ensembl: pass else: raise (IndexError) # Submit resquest to NCBI eutils/Gene database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?...
python
def convert_ensembl_to_entrez(self, ensembl): """Convert Ensembl Id to Entrez Gene Id""" if 'ENST' in ensembl: pass else: raise (IndexError) # Submit resquest to NCBI eutils/Gene database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?...
[ "def", "convert_ensembl_to_entrez", "(", "self", ",", "ensembl", ")", ":", "if", "'ENST'", "in", "ensembl", ":", "pass", "else", ":", "raise", "(", "IndexError", ")", "# Submit resquest to NCBI eutils/Gene database", "server", "=", "\"http://eutils.ncbi.nlm.nih.gov/entr...
Convert Ensembl Id to Entrez Gene Id
[ "Convert", "Ensembl", "Id", "to", "Entrez", "Gene", "Id" ]
28286cf21b876dd4894bf21a222dfd1022441b75
https://github.com/lwgray/pyEntrezId/blob/28286cf21b876dd4894bf21a222dfd1022441b75/PyEntrezId/Conversion.py#L27-L47
train
63,526
lwgray/pyEntrezId
PyEntrezId/Conversion.py
Conversion.convert_entrez_to_uniprot
def convert_entrez_to_uniprot(self, entrez): """Convert Entrez Id to Uniprot Id""" server = "http://www.uniprot.org/uniprot/?query=%22GENEID+{0}%22&format=xml".format(entrez) r = requests.get(server, headers={"Content-Type": "text/xml"}) if not r.ok: r.raise_for_status() ...
python
def convert_entrez_to_uniprot(self, entrez): """Convert Entrez Id to Uniprot Id""" server = "http://www.uniprot.org/uniprot/?query=%22GENEID+{0}%22&format=xml".format(entrez) r = requests.get(server, headers={"Content-Type": "text/xml"}) if not r.ok: r.raise_for_status() ...
[ "def", "convert_entrez_to_uniprot", "(", "self", ",", "entrez", ")", ":", "server", "=", "\"http://www.uniprot.org/uniprot/?query=%22GENEID+{0}%22&format=xml\"", ".", "format", "(", "entrez", ")", "r", "=", "requests", ".", "get", "(", "server", ",", "headers", "=",...
Convert Entrez Id to Uniprot Id
[ "Convert", "Entrez", "Id", "to", "Uniprot", "Id" ]
28286cf21b876dd4894bf21a222dfd1022441b75
https://github.com/lwgray/pyEntrezId/blob/28286cf21b876dd4894bf21a222dfd1022441b75/PyEntrezId/Conversion.py#L66-L80
train
63,527
lwgray/pyEntrezId
PyEntrezId/Conversion.py
Conversion.convert_uniprot_to_entrez
def convert_uniprot_to_entrez(self, uniprot): """Convert Uniprot Id to Entrez Id""" # Submit request to NCBI eutils/Gene Database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self.options + "&db=gene&term={0}".format( uniprot) r = requests.get(serve...
python
def convert_uniprot_to_entrez(self, uniprot): """Convert Uniprot Id to Entrez Id""" # Submit request to NCBI eutils/Gene Database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self.options + "&db=gene&term={0}".format( uniprot) r = requests.get(serve...
[ "def", "convert_uniprot_to_entrez", "(", "self", ",", "uniprot", ")", ":", "# Submit request to NCBI eutils/Gene Database", "server", "=", "\"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?\"", "+", "self", ".", "options", "+", "\"&db=gene&term={0}\"", ".", "format",...
Convert Uniprot Id to Entrez Id
[ "Convert", "Uniprot", "Id", "to", "Entrez", "Id" ]
28286cf21b876dd4894bf21a222dfd1022441b75
https://github.com/lwgray/pyEntrezId/blob/28286cf21b876dd4894bf21a222dfd1022441b75/PyEntrezId/Conversion.py#L82-L105
train
63,528
lwgray/pyEntrezId
PyEntrezId/Conversion.py
Conversion.convert_accession_to_taxid
def convert_accession_to_taxid(self, accessionid): """Convert Accession Id to Tax Id """ # Submit request to NCBI eutils/Taxonomy Database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" + self.options + "&db=nuccore&id={0}&retmode=xml".format( accessionid) ...
python
def convert_accession_to_taxid(self, accessionid): """Convert Accession Id to Tax Id """ # Submit request to NCBI eutils/Taxonomy Database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" + self.options + "&db=nuccore&id={0}&retmode=xml".format( accessionid) ...
[ "def", "convert_accession_to_taxid", "(", "self", ",", "accessionid", ")", ":", "# Submit request to NCBI eutils/Taxonomy Database", "server", "=", "\"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?\"", "+", "self", ".", "options", "+", "\"&db=nuccore&id={0}&retmode=xml\"...
Convert Accession Id to Tax Id
[ "Convert", "Accession", "Id", "to", "Tax", "Id" ]
28286cf21b876dd4894bf21a222dfd1022441b75
https://github.com/lwgray/pyEntrezId/blob/28286cf21b876dd4894bf21a222dfd1022441b75/PyEntrezId/Conversion.py#L107-L133
train
63,529
lwgray/pyEntrezId
PyEntrezId/Conversion.py
Conversion.convert_symbol_to_entrezid
def convert_symbol_to_entrezid(self, symbol): """Convert Symbol to Entrez Gene Id""" entrezdict = {} server = "http://rest.genenames.org/fetch/symbol/{0}".format(symbol) r = requests.get(server, headers={"Content-Type": "application/json"}) if not r.ok: r.raise_for_st...
python
def convert_symbol_to_entrezid(self, symbol): """Convert Symbol to Entrez Gene Id""" entrezdict = {} server = "http://rest.genenames.org/fetch/symbol/{0}".format(symbol) r = requests.get(server, headers={"Content-Type": "application/json"}) if not r.ok: r.raise_for_st...
[ "def", "convert_symbol_to_entrezid", "(", "self", ",", "symbol", ")", ":", "entrezdict", "=", "{", "}", "server", "=", "\"http://rest.genenames.org/fetch/symbol/{0}\"", ".", "format", "(", "symbol", ")", "r", "=", "requests", ".", "get", "(", "server", ",", "h...
Convert Symbol to Entrez Gene Id
[ "Convert", "Symbol", "to", "Entrez", "Gene", "Id" ]
28286cf21b876dd4894bf21a222dfd1022441b75
https://github.com/lwgray/pyEntrezId/blob/28286cf21b876dd4894bf21a222dfd1022441b75/PyEntrezId/Conversion.py#L135-L150
train
63,530
beaugunderson/django-gulp
django_gulp/management/commands/runserver.py
log_local_message
def log_local_message(message_format, *args): """ Log a request so that it matches our local log format. """ prefix = '{} {}'.format(color('INFO', fg=248), color('request', fg=5)) message = message_format % args sys.stderr.write('{} {}\n'.format(prefix, message))
python
def log_local_message(message_format, *args): """ Log a request so that it matches our local log format. """ prefix = '{} {}'.format(color('INFO', fg=248), color('request', fg=5)) message = message_format % args sys.stderr.write('{} {}\n'.format(prefix, message))
[ "def", "log_local_message", "(", "message_format", ",", "*", "args", ")", ":", "prefix", "=", "'{} {}'", ".", "format", "(", "color", "(", "'INFO'", ",", "fg", "=", "248", ")", ",", "color", "(", "'request'", ",", "fg", "=", "5", ")", ")", "message",...
Log a request so that it matches our local log format.
[ "Log", "a", "request", "so", "that", "it", "matches", "our", "local", "log", "format", "." ]
227b121136941b7c32171be3262cc0dcc4a68e6f
https://github.com/beaugunderson/django-gulp/blob/227b121136941b7c32171be3262cc0dcc4a68e6f/django_gulp/management/commands/runserver.py#L13-L20
train
63,531
antidot/Pyckson
src/pyckson/serializer.py
serialize
def serialize(obj): """Takes a object and produces a dict-like representation :param obj: the object to serialize """ if isinstance(obj, list): return [serialize(o) for o in obj] return GenericSerializer(ModelProviderImpl()).serialize(obj)
python
def serialize(obj): """Takes a object and produces a dict-like representation :param obj: the object to serialize """ if isinstance(obj, list): return [serialize(o) for o in obj] return GenericSerializer(ModelProviderImpl()).serialize(obj)
[ "def", "serialize", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "serialize", "(", "o", ")", "for", "o", "in", "obj", "]", "return", "GenericSerializer", "(", "ModelProviderImpl", "(", ")", ")", ".", "se...
Takes a object and produces a dict-like representation :param obj: the object to serialize
[ "Takes", "a", "object", "and", "produces", "a", "dict", "-", "like", "representation" ]
44e625164a53081eb46b8d4bc38f947a575de505
https://github.com/antidot/Pyckson/blob/44e625164a53081eb46b8d4bc38f947a575de505/src/pyckson/serializer.py#L5-L12
train
63,532
jbasko/autoboto
botogen/indentist/blocks.py
CodeBlock.of
def of(self, *indented_blocks) -> "CodeBlock": """ By default, marks the block as expecting an indented "body" blocks of which are then supplied as arguments to this method. Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones, this will...
python
def of(self, *indented_blocks) -> "CodeBlock": """ By default, marks the block as expecting an indented "body" blocks of which are then supplied as arguments to this method. Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones, this will...
[ "def", "of", "(", "self", ",", "*", "indented_blocks", ")", "->", "\"CodeBlock\"", ":", "if", "self", ".", "closed_by", "is", "None", ":", "self", ".", "expects_body_or_pass", "=", "True", "for", "block", "in", "indented_blocks", ":", "if", "block", "is", ...
By default, marks the block as expecting an indented "body" blocks of which are then supplied as arguments to this method. Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones, this will generate a "pass" statement as the body. If there is a "closed_by"...
[ "By", "default", "marks", "the", "block", "as", "expecting", "an", "indented", "body", "blocks", "of", "which", "are", "then", "supplied", "as", "arguments", "to", "this", "method", "." ]
0329afd4730d3d78bd021116857b10e6956dffb1
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/indentist/blocks.py#L129-L156
train
63,533
jbasko/autoboto
botogen/indentist/blocks.py
CodeBlock.add
def add(self, *blocks, indentation=0) -> "CodeBlock": """ Adds sub-blocks at the specified indentation level, which defaults to 0. Nones are skipped. Returns the parent block itself, useful for chaining. """ for block in blocks: if block is not None: ...
python
def add(self, *blocks, indentation=0) -> "CodeBlock": """ Adds sub-blocks at the specified indentation level, which defaults to 0. Nones are skipped. Returns the parent block itself, useful for chaining. """ for block in blocks: if block is not None: ...
[ "def", "add", "(", "self", ",", "*", "blocks", ",", "indentation", "=", "0", ")", "->", "\"CodeBlock\"", ":", "for", "block", "in", "blocks", ":", "if", "block", "is", "not", "None", ":", "self", ".", "_blocks", ".", "append", "(", "(", "indentation"...
Adds sub-blocks at the specified indentation level, which defaults to 0. Nones are skipped. Returns the parent block itself, useful for chaining.
[ "Adds", "sub", "-", "blocks", "at", "the", "specified", "indentation", "level", "which", "defaults", "to", "0", "." ]
0329afd4730d3d78bd021116857b10e6956dffb1
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/indentist/blocks.py#L158-L170
train
63,534
jbasko/autoboto
botogen/indentist/blocks.py
CodeBlock.to_code
def to_code(self, context: Context =None): """ Generate the code and return it as a string. """ # Do not override this method! context = context or Context() for imp in self.imports: if imp not in context.imports: context.imports.append(imp) ...
python
def to_code(self, context: Context =None): """ Generate the code and return it as a string. """ # Do not override this method! context = context or Context() for imp in self.imports: if imp not in context.imports: context.imports.append(imp) ...
[ "def", "to_code", "(", "self", ",", "context", ":", "Context", "=", "None", ")", ":", "# Do not override this method!", "context", "=", "context", "or", "Context", "(", ")", "for", "imp", "in", "self", ".", "imports", ":", "if", "imp", "not", "in", "cont...
Generate the code and return it as a string.
[ "Generate", "the", "code", "and", "return", "it", "as", "a", "string", "." ]
0329afd4730d3d78bd021116857b10e6956dffb1
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/indentist/blocks.py#L239-L262
train
63,535
jbasko/autoboto
botogen/indentist/blocks.py
CodeBlock.exec
def exec(self, globals=None, locals=None): """ Execute simple code blocks. Do not attempt this on modules or other blocks where you have imports as they won't work. Instead write the code to a file and use runpy.run_path() """ if locals is None: local...
python
def exec(self, globals=None, locals=None): """ Execute simple code blocks. Do not attempt this on modules or other blocks where you have imports as they won't work. Instead write the code to a file and use runpy.run_path() """ if locals is None: local...
[ "def", "exec", "(", "self", ",", "globals", "=", "None", ",", "locals", "=", "None", ")", ":", "if", "locals", "is", "None", ":", "locals", "=", "{", "}", "builtins", ".", "exec", "(", "self", ".", "to_code", "(", ")", ",", "globals", ",", "local...
Execute simple code blocks. Do not attempt this on modules or other blocks where you have imports as they won't work. Instead write the code to a file and use runpy.run_path()
[ "Execute", "simple", "code", "blocks", "." ]
0329afd4730d3d78bd021116857b10e6956dffb1
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/indentist/blocks.py#L264-L275
train
63,536
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
train
63,537
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
train
63,538
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
train
63,539
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
train
63,540
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
train
63,541
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
train
63,542
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
train
63,543
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
train
63,544
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
train
63,545
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
train
63,546
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
train
63,547
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
train
63,548
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
train
63,549
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
train
63,550
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
train
63,551
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
train
63,552
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
train
63,553
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
train
63,554
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
train
63,555
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
train
63,556
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
train
63,557
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
train
63,558
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
train
63,559
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
train
63,560
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
train
63,561
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
train
63,562
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
train
63,563
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
train
63,564
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
train
63,565
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
train
63,566
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
train
63,567
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
train
63,568
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
train
63,569
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
train
63,570
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
train
63,571
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
train
63,572
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
train
63,573
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
train
63,574
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
train
63,575
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
train
63,576
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
train
63,577
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
train
63,578
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
train
63,579
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
train
63,580
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
train
63,581
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
train
63,582
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
train
63,583
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
train
63,584
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
train
63,585
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
train
63,586
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
train
63,587
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
train
63,588
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
train
63,589
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
train
63,590
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
train
63,591
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
train
63,592
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
train
63,593
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
train
63,594
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
train
63,595
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
train
63,596
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
train
63,597
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
train
63,598
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
train
63,599