repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
pytools/pytools-command
pytools_command/core.py
exec_command
def exec_command(command, **kwargs): """ Executes the given command and send the output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `stdin` (``*`` = None) -- * `stdout` (``*`` = None) -- * `stderr` (``*`` = None) -- ...
python
def exec_command(command, **kwargs): """ Executes the given command and send the output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `stdin` (``*`` = None) -- * `stdout` (``*`` = None) -- * `stderr` (``*`` = None) -- ...
[ "def", "exec_command", "(", "command", ",", "*", "*", "kwargs", ")", ":", "shell", "=", "kwargs", ".", "get", "(", "'shell'", ",", "False", ")", "stdin", "=", "kwargs", ".", "get", "(", "'stdin'", ",", "None", ")", "stdout", "=", "kwargs", ".", "ge...
Executes the given command and send the output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `stdin` (``*`` = None) -- * `stdout` (``*`` = None) -- * `stderr` (``*`` = None) -- :return: CommandReturnValue
[ "Executes", "the", "given", "command", "and", "send", "the", "output", "to", "the", "console" ]
train
https://github.com/pytools/pytools-command/blob/ec6793d8ecac46fa0899f64596aa914f4a09d7f6/pytools_command/core.py#L40-L73
pytools/pytools-command
pytools_command/core.py
observe_command
def observe_command(command, **kwargs): """ Executes the given command and captures the output without any output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `timeout` (``int`` = 15) -- Timeout in seconds * `stdin` (``*`` = None)...
python
def observe_command(command, **kwargs): """ Executes the given command and captures the output without any output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `timeout` (``int`` = 15) -- Timeout in seconds * `stdin` (``*`` = None)...
[ "def", "observe_command", "(", "command", ",", "*", "*", "kwargs", ")", ":", "shell", "=", "kwargs", ".", "get", "(", "'shell'", ",", "False", ")", "timeout", "=", "kwargs", ".", "get", "(", "'timeout'", ",", "15", ")", "stdin", "=", "kwargs", ".", ...
Executes the given command and captures the output without any output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `timeout` (``int`` = 15) -- Timeout in seconds * `stdin` (``*`` = None) -- * `stdout` (``*`` = None) -- ...
[ "Executes", "the", "given", "command", "and", "captures", "the", "output", "without", "any", "output", "to", "the", "console" ]
train
https://github.com/pytools/pytools-command/blob/ec6793d8ecac46fa0899f64596aa914f4a09d7f6/pytools_command/core.py#L76-L154
political-memory/django-representatives
representatives/migrations/0016_chamber_migrate_data.py
calculate_hash
def calculate_hash(obj): """ Computes fingerprint for an object, this code is duplicated from representatives.models.HashableModel because we don't have access to model methods in a migration scenario. """ hashable_fields = { 'Chamber': ['name', 'country', 'abbreviation'], 'Cons...
python
def calculate_hash(obj): """ Computes fingerprint for an object, this code is duplicated from representatives.models.HashableModel because we don't have access to model methods in a migration scenario. """ hashable_fields = { 'Chamber': ['name', 'country', 'abbreviation'], 'Cons...
[ "def", "calculate_hash", "(", "obj", ")", ":", "hashable_fields", "=", "{", "'Chamber'", ":", "[", "'name'", ",", "'country'", ",", "'abbreviation'", "]", ",", "'Constituency'", ":", "[", "'name'", "]", ",", "'Group'", ":", "[", "'name'", ",", "'abbreviati...
Computes fingerprint for an object, this code is duplicated from representatives.models.HashableModel because we don't have access to model methods in a migration scenario.
[ "Computes", "fingerprint", "for", "an", "object", "this", "code", "is", "duplicated", "from", "representatives", ".", "models", ".", "HashableModel", "because", "we", "don", "t", "have", "access", "to", "model", "methods", "in", "a", "migration", "scenario", "...
train
https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/migrations/0016_chamber_migrate_data.py#L9-L36
political-memory/django-representatives
representatives/migrations/0016_chamber_migrate_data.py
get_or_create
def get_or_create(cls, **kwargs): """ Implements get_or_create logic for models that inherit from representatives.models.HashableModel because we don't have access to model methods in a migration scenario. """ try: obj = cls.objects.get(**kwargs) created = False except cls.D...
python
def get_or_create(cls, **kwargs): """ Implements get_or_create logic for models that inherit from representatives.models.HashableModel because we don't have access to model methods in a migration scenario. """ try: obj = cls.objects.get(**kwargs) created = False except cls.D...
[ "def", "get_or_create", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "try", ":", "obj", "=", "cls", ".", "objects", ".", "get", "(", "*", "*", "kwargs", ")", "created", "=", "False", "except", "cls", ".", "DoesNotExist", ":", "obj", "=", "cls", ...
Implements get_or_create logic for models that inherit from representatives.models.HashableModel because we don't have access to model methods in a migration scenario.
[ "Implements", "get_or_create", "logic", "for", "models", "that", "inherit", "from", "representatives", ".", "models", ".", "HashableModel", "because", "we", "don", "t", "have", "access", "to", "model", "methods", "in", "a", "migration", "scenario", "." ]
train
https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/migrations/0016_chamber_migrate_data.py#L39-L55
gongliyu/decoutils
decoutils/__init__.py
decorator_with_args
def decorator_with_args(func, return_original=False, target_pos=0): """Enable a function to work with a decorator with arguments Args: func (callable): The input function. return_original (bool): Whether the resultant decorator returns the decorating target unchanged. If True, will return...
python
def decorator_with_args(func, return_original=False, target_pos=0): """Enable a function to work with a decorator with arguments Args: func (callable): The input function. return_original (bool): Whether the resultant decorator returns the decorating target unchanged. If True, will return...
[ "def", "decorator_with_args", "(", "func", ",", "return_original", "=", "False", ",", "target_pos", "=", "0", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "target_name", "=", "inspect", ".", "getfullargspec", "(", "func", ")...
Enable a function to work with a decorator with arguments Args: func (callable): The input function. return_original (bool): Whether the resultant decorator returns the decorating target unchanged. If True, will return the target unchanged. Otherwise, return the returned value from ...
[ "Enable", "a", "function", "to", "work", "with", "a", "decorator", "with", "arguments" ]
train
https://github.com/gongliyu/decoutils/blob/f826cda612da7e6e0767bb0e1f0ac509f8316322/decoutils/__init__.py#L9-L85
janbrohl/XMLCompare
xmlcompare.py
elements_equal
def elements_equal(first, *others): """ Check elements for equality """ f = first lf = list(f) for e in others: le = list(e) if (len(lf) != len(le) or f.tag != e.tag or f.text != e.text or f.tail != e.tail or f.attri...
python
def elements_equal(first, *others): """ Check elements for equality """ f = first lf = list(f) for e in others: le = list(e) if (len(lf) != len(le) or f.tag != e.tag or f.text != e.text or f.tail != e.tail or f.attri...
[ "def", "elements_equal", "(", "first", ",", "*", "others", ")", ":", "f", "=", "first", "lf", "=", "list", "(", "f", ")", "for", "e", "in", "others", ":", "le", "=", "list", "(", "e", ")", "if", "(", "len", "(", "lf", ")", "!=", "len", "(", ...
Check elements for equality
[ "Check", "elements", "for", "equality" ]
train
https://github.com/janbrohl/XMLCompare/blob/2592cc4a0976b7510bfa44a63822d7fb6c63b74f/xmlcompare.py#L12-L28
janbrohl/XMLCompare
xmlcompare.py
get_element
def get_element(text_or_tree_or_element): """ Get back an ET.Element for several possible input formats """ if isinstance(text_or_tree_or_element, ET.Element): return text_or_tree_or_element elif isinstance(text_or_tree_or_element, ET.ElementTree): return text_or_tree_or_element.getr...
python
def get_element(text_or_tree_or_element): """ Get back an ET.Element for several possible input formats """ if isinstance(text_or_tree_or_element, ET.Element): return text_or_tree_or_element elif isinstance(text_or_tree_or_element, ET.ElementTree): return text_or_tree_or_element.getr...
[ "def", "get_element", "(", "text_or_tree_or_element", ")", ":", "if", "isinstance", "(", "text_or_tree_or_element", ",", "ET", ".", "Element", ")", ":", "return", "text_or_tree_or_element", "elif", "isinstance", "(", "text_or_tree_or_element", ",", "ET", ".", "Eleme...
Get back an ET.Element for several possible input formats
[ "Get", "back", "an", "ET", ".", "Element", "for", "several", "possible", "input", "formats" ]
train
https://github.com/janbrohl/XMLCompare/blob/2592cc4a0976b7510bfa44a63822d7fb6c63b74f/xmlcompare.py#L31-L42
deviantony/valigator
valigator/celery.py
task_failure_handler
def task_failure_handler(task_id=None, exception=None, traceback=None, args=None, **kwargs): """Task failure handler""" # TODO: find a better way to acces workdir/archive/image task_report = {'task_id': task_id, 'exception': exception, 'tracebac...
python
def task_failure_handler(task_id=None, exception=None, traceback=None, args=None, **kwargs): """Task failure handler""" # TODO: find a better way to acces workdir/archive/image task_report = {'task_id': task_id, 'exception': exception, 'tracebac...
[ "def", "task_failure_handler", "(", "task_id", "=", "None", ",", "exception", "=", "None", ",", "traceback", "=", "None", ",", "args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# TODO: find a better way to acces workdir/archive/image", "task_report", "=", ...
Task failure handler
[ "Task", "failure", "handler" ]
train
https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/celery.py#L29-L40
esterhui/pypu
pypu/service_flickr.py
service_flickr._connectToFlickr
def _connectToFlickr(self): """Establish the actual TCP connection to Flickr""" if self.connected_to_flickr: logger.debug("Already connected to flickr") return True logger.debug("Connecting to flickr") # Do flickr authentication _flickr = flickrapi.Flick...
python
def _connectToFlickr(self): """Establish the actual TCP connection to Flickr""" if self.connected_to_flickr: logger.debug("Already connected to flickr") return True logger.debug("Connecting to flickr") # Do flickr authentication _flickr = flickrapi.Flick...
[ "def", "_connectToFlickr", "(", "self", ")", ":", "if", "self", ".", "connected_to_flickr", ":", "logger", ".", "debug", "(", "\"Already connected to flickr\"", ")", "return", "True", "logger", ".", "debug", "(", "\"Connecting to flickr\"", ")", "# Do flickr authent...
Establish the actual TCP connection to Flickr
[ "Establish", "the", "actual", "TCP", "connection", "to", "Flickr" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L50-L73
esterhui/pypu
pypu/service_flickr.py
service_flickr._isConfigFile
def _isConfigFile(self,filename): """If this is a config file or meta file return true""" ext=os.path.splitext(filename)[1].lower() if filename in self.FLICKR_CONFIG_FILES: return True elif ext in self.FLICKR_META_EXTENSIONS: return True return Fal...
python
def _isConfigFile(self,filename): """If this is a config file or meta file return true""" ext=os.path.splitext(filename)[1].lower() if filename in self.FLICKR_CONFIG_FILES: return True elif ext in self.FLICKR_META_EXTENSIONS: return True return Fal...
[ "def", "_isConfigFile", "(", "self", ",", "filename", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "lower", "(", ")", "if", "filename", "in", "self", ".", "FLICKR_CONFIG_FILES", ":", "return", "T...
If this is a config file or meta file return true
[ "If", "this", "is", "a", "config", "file", "or", "meta", "file", "return", "true" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L84-L92
esterhui/pypu
pypu/service_flickr.py
service_flickr._update_config
def _update_config(self,directory,filename): """Manages FLICKR config files""" basefilename=os.path.splitext(filename)[0] ext=os.path.splitext(filename)[1].lower() if filename==LOCATION_FILE: print("%s - Updating geotag information"%(LOCATION_FILE)) return self._u...
python
def _update_config(self,directory,filename): """Manages FLICKR config files""" basefilename=os.path.splitext(filename)[0] ext=os.path.splitext(filename)[1].lower() if filename==LOCATION_FILE: print("%s - Updating geotag information"%(LOCATION_FILE)) return self._u...
[ "def", "_update_config", "(", "self", ",", "directory", ",", "filename", ")", ":", "basefilename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "["...
Manages FLICKR config files
[ "Manages", "FLICKR", "config", "files" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L122-L141
esterhui/pypu
pypu/service_flickr.py
service_flickr._update_meta
def _update_meta(self,directory,filename): """Opens up filename.title and filename.description, updates on flickr""" if not self._connectToFlickr(): print("%s - Couldn't connect to flickr"%(directory)) return False db = self._loadDB(directory) # Look up...
python
def _update_meta(self,directory,filename): """Opens up filename.title and filename.description, updates on flickr""" if not self._connectToFlickr(): print("%s - Couldn't connect to flickr"%(directory)) return False db = self._loadDB(directory) # Look up...
[ "def", "_update_meta", "(", "self", ",", "directory", ",", "filename", ")", ":", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"%s - Couldn't connect to flickr\"", "%", "(", "directory", ")", ")", "return", "False", "db", "=", ...
Opens up filename.title and filename.description, updates on flickr
[ "Opens", "up", "filename", ".", "title", "and", "filename", ".", "description", "updates", "on", "flickr" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L143-L182
esterhui/pypu
pypu/service_flickr.py
service_flickr._load_tags
def _load_tags(self,directory): """Loads tags from tag file and return as flickr api compatible string """ #FIXME: should check if DB tracking file before using it # --- Read tags out of file _tags='' try: fullfile=os.path.join(directory,TAG_FILE) ...
python
def _load_tags(self,directory): """Loads tags from tag file and return as flickr api compatible string """ #FIXME: should check if DB tracking file before using it # --- Read tags out of file _tags='' try: fullfile=os.path.join(directory,TAG_FILE) ...
[ "def", "_load_tags", "(", "self", ",", "directory", ")", ":", "#FIXME: should check if DB tracking file before using it", "# --- Read tags out of file", "_tags", "=", "''", "try", ":", "fullfile", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "TAG_FILE...
Loads tags from tag file and return as flickr api compatible string
[ "Loads", "tags", "from", "tag", "file", "and", "return", "as", "flickr", "api", "compatible", "string" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L186-L204
esterhui/pypu
pypu/service_flickr.py
service_flickr._createphotoset
def _createphotoset(self,myset,primary_photoid): """Creates a photo set on Flickr""" if not self._connectToFlickr(): print("%s - Couldn't connect to flickr"%(directory)) return False logger.debug('Creating photo set %s with prim photo %s'\ %(myset...
python
def _createphotoset(self,myset,primary_photoid): """Creates a photo set on Flickr""" if not self._connectToFlickr(): print("%s - Couldn't connect to flickr"%(directory)) return False logger.debug('Creating photo set %s with prim photo %s'\ %(myset...
[ "def", "_createphotoset", "(", "self", ",", "myset", ",", "primary_photoid", ")", ":", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"%s - Couldn't connect to flickr\"", "%", "(", "directory", ")", ")", "return", "False", "logger...
Creates a photo set on Flickr
[ "Creates", "a", "photo", "set", "on", "Flickr" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L242-L257
esterhui/pypu
pypu/service_flickr.py
service_flickr._update_config_sets
def _update_config_sets(self,directory,files=None): """ Loads set information from file and updates on flickr, only reads first line. Format is comma separated eg. travel, 2010, South Africa, Pretoria If files is None, will update all files in DB, otherwise will only upd...
python
def _update_config_sets(self,directory,files=None): """ Loads set information from file and updates on flickr, only reads first line. Format is comma separated eg. travel, 2010, South Africa, Pretoria If files is None, will update all files in DB, otherwise will only upd...
[ "def", "_update_config_sets", "(", "self", ",", "directory", ",", "files", "=", "None", ")", ":", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"%s - Couldn't connect to flickr\"", "%", "(", "directory", ")", ")", "return", "Fa...
Loads set information from file and updates on flickr, only reads first line. Format is comma separated eg. travel, 2010, South Africa, Pretoria If files is None, will update all files in DB, otherwise will only update files that are in the flickr DB and files list
[ "Loads", "set", "information", "from", "file", "and", "updates", "on", "flickr", "only", "reads", "first", "line", ".", "Format", "is", "comma", "separated", "eg", ".", "travel", "2010", "South", "Africa", "Pretoria", "If", "files", "is", "None", "will", "...
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L259-L330
esterhui/pypu
pypu/service_flickr.py
service_flickr._getphotosets_forphoto
def _getphotosets_forphoto(self,pid): """Asks flickr which photosets photo with given pid belongs to, returns list of photoset names""" resp=self.flickr.photos_getAllContexts(photo_id=pid) if resp.attrib['stat']!='ok': logger.error("%s - flickr: photos_getAllContext ...
python
def _getphotosets_forphoto(self,pid): """Asks flickr which photosets photo with given pid belongs to, returns list of photoset names""" resp=self.flickr.photos_getAllContexts(photo_id=pid) if resp.attrib['stat']!='ok': logger.error("%s - flickr: photos_getAllContext ...
[ "def", "_getphotosets_forphoto", "(", "self", ",", "pid", ")", ":", "resp", "=", "self", ".", "flickr", ".", "photos_getAllContexts", "(", "photo_id", "=", "pid", ")", "if", "resp", ".", "attrib", "[", "'stat'", "]", "!=", "'ok'", ":", "logger", ".", "...
Asks flickr which photosets photo with given pid belongs to, returns list of photoset names
[ "Asks", "flickr", "which", "photosets", "photo", "with", "given", "pid", "belongs", "to", "returns", "list", "of", "photoset", "names" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L333-L350
esterhui/pypu
pypu/service_flickr.py
service_flickr._getphoto_originalsize
def _getphoto_originalsize(self,pid): """Asks flickr for photo original size returns tuple with width,height """ logger.debug('%s - Getting original size from flickr'%(pid)) width=None height=None resp=self.flickr.photos_getSizes(photo_id=pid) if resp.a...
python
def _getphoto_originalsize(self,pid): """Asks flickr for photo original size returns tuple with width,height """ logger.debug('%s - Getting original size from flickr'%(pid)) width=None height=None resp=self.flickr.photos_getSizes(photo_id=pid) if resp.a...
[ "def", "_getphoto_originalsize", "(", "self", ",", "pid", ")", ":", "logger", ".", "debug", "(", "'%s - Getting original size from flickr'", "%", "(", "pid", ")", ")", "width", "=", "None", "height", "=", "None", "resp", "=", "self", ".", "flickr", ".", "p...
Asks flickr for photo original size returns tuple with width,height
[ "Asks", "flickr", "for", "photo", "original", "size", "returns", "tuple", "with", "width", "height" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L352-L375
esterhui/pypu
pypu/service_flickr.py
service_flickr._getphoto_url
def _getphoto_url(self,pid,size='n'): """Returns URL to photo, optionally can link to different size images Size suffixes according to: http://www.flickr.com/services/api/misc.urls.html s small square 75x75 q large square 150x150 t thumbnail, 100 on longest...
python
def _getphoto_url(self,pid,size='n'): """Returns URL to photo, optionally can link to different size images Size suffixes according to: http://www.flickr.com/services/api/misc.urls.html s small square 75x75 q large square 150x150 t thumbnail, 100 on longest...
[ "def", "_getphoto_url", "(", "self", ",", "pid", ",", "size", "=", "'n'", ")", ":", "p", "=", "self", ".", "_getphoto_information", "(", "pid", ")", "farm", "=", "p", "[", "'farm'", "]", "server", "=", "p", "[", "'server'", "]", "secret", "=", "p",...
Returns URL to photo, optionally can link to different size images Size suffixes according to: http://www.flickr.com/services/api/misc.urls.html s small square 75x75 q large square 150x150 t thumbnail, 100 on longest side m small, 240 on longest side ...
[ "Returns", "URL", "to", "photo", "optionally", "can", "link", "to", "different", "size", "images", "Size", "suffixes", "according", "to", ":", "http", ":", "//", "www", ".", "flickr", ".", "com", "/", "services", "/", "api", "/", "misc", ".", "urls", "...
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L402-L427
esterhui/pypu
pypu/service_flickr.py
service_flickr._getphoto_information
def _getphoto_information(self,pid): """Asks flickr for photo information returns dictionary with attributes {'dateuploaded': '1383410793', 'farm': '3', 'id': '10628709834', 'isfavorite': '0', 'license': '0', 'media': 'photo', 'originalforma...
python
def _getphoto_information(self,pid): """Asks flickr for photo information returns dictionary with attributes {'dateuploaded': '1383410793', 'farm': '3', 'id': '10628709834', 'isfavorite': '0', 'license': '0', 'media': 'photo', 'originalforma...
[ "def", "_getphoto_information", "(", "self", ",", "pid", ")", ":", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"%s - Couldn't connect to flickr\"", "%", "(", "directory", ")", ")", "return", "False", "d", "=", "{", "}", "lo...
Asks flickr for photo information returns dictionary with attributes {'dateuploaded': '1383410793', 'farm': '3', 'id': '10628709834', 'isfavorite': '0', 'license': '0', 'media': 'photo', 'originalformat': 'jpg', 'originalsecret': 'b60f4f675...
[ "Asks", "flickr", "for", "photo", "information", "returns", "dictionary", "with", "attributes" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L429-L467
esterhui/pypu
pypu/service_flickr.py
service_flickr._update_config_tags
def _update_config_tags(self,directory,files=None): """ Loads tags information from file and updates on flickr, only reads first line. Format is comma separated eg. travel, 2010, South Africa, Pretoria If files is None, will update all files in DB, otherwise will only up...
python
def _update_config_tags(self,directory,files=None): """ Loads tags information from file and updates on flickr, only reads first line. Format is comma separated eg. travel, 2010, South Africa, Pretoria If files is None, will update all files in DB, otherwise will only up...
[ "def", "_update_config_tags", "(", "self", ",", "directory", ",", "files", "=", "None", ")", ":", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"%s - Couldn't connect to flickr\"", "%", "(", "directory", ")", ")", "return", "Fa...
Loads tags information from file and updates on flickr, only reads first line. Format is comma separated eg. travel, 2010, South Africa, Pretoria If files is None, will update all files in DB, otherwise will only update files that are in the flickr DB and files list
[ "Loads", "tags", "information", "from", "file", "and", "updates", "on", "flickr", "only", "reads", "first", "line", ".", "Format", "is", "comma", "separated", "eg", ".", "travel", "2010", "South", "Africa", "Pretoria", "If", "files", "is", "None", "will", ...
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L469-L502
esterhui/pypu
pypu/service_flickr.py
service_flickr._update_config_location
def _update_config_location(self,directory,files=None): """Loads location and applies to all files in given files list (or if none, all files in flickr DB) google reverse GEO to figure out location lat/long file can contain things like: Australia Sydney, Australia ...
python
def _update_config_location(self,directory,files=None): """Loads location and applies to all files in given files list (or if none, all files in flickr DB) google reverse GEO to figure out location lat/long file can contain things like: Australia Sydney, Australia ...
[ "def", "_update_config_location", "(", "self", ",", "directory", ",", "files", "=", "None", ")", ":", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"%s - Couldn't connect to flickr\"", "%", "(", "filename", ")", ")", "return", ...
Loads location and applies to all files in given files list (or if none, all files in flickr DB) google reverse GEO to figure out location lat/long file can contain things like: Australia Sydney, Australia Holcomb Campground, California. If image already has Lat...
[ "Loads", "location", "and", "applies", "to", "all", "files", "in", "given", "files", "list", "(", "or", "if", "none", "all", "files", "in", "flickr", "DB", ")" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L504-L572
esterhui/pypu
pypu/service_flickr.py
service_flickr._remove_media
def _remove_media(self,directory,files=None): """Removes specified files from flickr""" # Connect if we aren't already if not self._connectToFlickr(): logger.error("%s - Couldn't connect to flickr") return False db=self._loadDB(directory) # If no files gi...
python
def _remove_media(self,directory,files=None): """Removes specified files from flickr""" # Connect if we aren't already if not self._connectToFlickr(): logger.error("%s - Couldn't connect to flickr") return False db=self._loadDB(directory) # If no files gi...
[ "def", "_remove_media", "(", "self", ",", "directory", ",", "files", "=", "None", ")", ":", "# Connect if we aren't already", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "logger", ".", "error", "(", "\"%s - Couldn't connect to flickr\"", ")", "r...
Removes specified files from flickr
[ "Removes", "specified", "files", "from", "flickr" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L574-L608
esterhui/pypu
pypu/service_flickr.py
service_flickr._upload_media
def _upload_media(self,directory,files=None,resize_request=None): """Uploads media file to FLICKR, returns True if uploaded successfully, Will replace if already uploaded, If megapixels > 0, will scale photos before upload If no filename given, will go through all files in DB"""...
python
def _upload_media(self,directory,files=None,resize_request=None): """Uploads media file to FLICKR, returns True if uploaded successfully, Will replace if already uploaded, If megapixels > 0, will scale photos before upload If no filename given, will go through all files in DB"""...
[ "def", "_upload_media", "(", "self", ",", "directory", ",", "files", "=", "None", ",", "resize_request", "=", "None", ")", ":", "# Connect if we aren't already", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "logger", ".", "error", "(", "\"%s ...
Uploads media file to FLICKR, returns True if uploaded successfully, Will replace if already uploaded, If megapixels > 0, will scale photos before upload If no filename given, will go through all files in DB
[ "Uploads", "media", "file", "to", "FLICKR", "returns", "True", "if", "uploaded", "successfully", "Will", "replace", "if", "already", "uploaded", "If", "megapixels", ">", "0", "will", "scale", "photos", "before", "upload", "If", "no", "filename", "given", "will...
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L610-L653
esterhui/pypu
pypu/service_flickr.py
service_flickr._upload_or_replace_flickr
def _upload_or_replace_flickr(self,directory,fn,_tags=None,\ _megapixels=None,resize_request=None): """Does the actual upload to flickr. if resize_request, will resize picture only if it already exists and the geometry on flickr doesn't match what we want, returns (st...
python
def _upload_or_replace_flickr(self,directory,fn,_tags=None,\ _megapixels=None,resize_request=None): """Does the actual upload to flickr. if resize_request, will resize picture only if it already exists and the geometry on flickr doesn't match what we want, returns (st...
[ "def", "_upload_or_replace_flickr", "(", "self", ",", "directory", ",", "fn", ",", "_tags", "=", "None", ",", "_megapixels", "=", "None", ",", "resize_request", "=", "None", ")", ":", "# We should check here if ", "db", "=", "self", ".", "_loadDB", "(", "dir...
Does the actual upload to flickr. if resize_request, will resize picture only if it already exists and the geometry on flickr doesn't match what we want, returns (status,replaced)
[ "Does", "the", "actual", "upload", "to", "flickr", ".", "if", "resize_request", "will", "resize", "picture", "only", "if", "it", "already", "exists", "and", "the", "geometry", "on", "flickr", "doesn", "t", "match", "what", "we", "want", "returns", "(", "st...
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L655-L766
esterhui/pypu
pypu/service_flickr.py
service_flickr._already_resized_on_flickr
def _already_resized_on_flickr(self,fn,pid,_megapixels): """Checks if image file (fn) with photo_id (pid) has already been resized on flickr. If so, returns True""" logger.debug("%s - resize requested"%(fn)) # Get width/height from flickr width_flickr,height_flickr=self._getphoto...
python
def _already_resized_on_flickr(self,fn,pid,_megapixels): """Checks if image file (fn) with photo_id (pid) has already been resized on flickr. If so, returns True""" logger.debug("%s - resize requested"%(fn)) # Get width/height from flickr width_flickr,height_flickr=self._getphoto...
[ "def", "_already_resized_on_flickr", "(", "self", ",", "fn", ",", "pid", ",", "_megapixels", ")", ":", "logger", ".", "debug", "(", "\"%s - resize requested\"", "%", "(", "fn", ")", ")", "# Get width/height from flickr", "width_flickr", ",", "height_flickr", "=", ...
Checks if image file (fn) with photo_id (pid) has already been resized on flickr. If so, returns True
[ "Checks", "if", "image", "file", "(", "fn", ")", "with", "photo_id", "(", "pid", ")", "has", "already", "been", "resized", "on", "flickr", ".", "If", "so", "returns", "True" ]
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L768-L782
esterhui/pypu
pypu/service_flickr.py
service_flickr._getphotosets
def _getphotosets(self): """Returns dictionary of photosets retrieved from flickr d['title']['number_photos'] : Number of photos d['title']['id'] : ID of photoset d['title']['photo_id'] : ID of primary photo d['title']['url'] : URL to photoset ""...
python
def _getphotosets(self): """Returns dictionary of photosets retrieved from flickr d['title']['number_photos'] : Number of photos d['title']['id'] : ID of photoset d['title']['photo_id'] : ID of primary photo d['title']['url'] : URL to photoset ""...
[ "def", "_getphotosets", "(", "self", ")", ":", "sets", "=", "{", "}", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"Couldn't connect to flickr\"", ")", "return", "sets", "psets", "=", "self", ".", "flickr", ".", "photosets_g...
Returns dictionary of photosets retrieved from flickr d['title']['number_photos'] : Number of photos d['title']['id'] : ID of photoset d['title']['photo_id'] : ID of primary photo d['title']['url'] : URL to photoset
[ "Returns", "dictionary", "of", "photosets", "retrieved", "from", "flickr", "d", "[", "title", "]", "[", "number_photos", "]", ":", "Number", "of", "photos", "d", "[", "title", "]", "[", "id", "]", ":", "ID", "of", "photoset", "d", "[", "title", "]", ...
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L784-L806
rsalmaso/django-fluo
fluo/management/__init__.py
_get_all_permissions
def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." perms = [] for action in settings.DEFAULT_PERMISSIONS: perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name_raw))) return perms + list(opts.permissions)
python
def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." perms = [] for action in settings.DEFAULT_PERMISSIONS: perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name_raw))) return perms + list(opts.permissions)
[ "def", "_get_all_permissions", "(", "opts", ")", ":", "perms", "=", "[", "]", "for", "action", "in", "settings", ".", "DEFAULT_PERMISSIONS", ":", "perms", ".", "append", "(", "(", "_get_permission_codename", "(", "action", ",", "opts", ")", ",", "'Can %s %s'...
Returns (codename, name) for all permissions in the given opts.
[ "Returns", "(", "codename", "name", ")", "for", "all", "permissions", "in", "the", "given", "opts", "." ]
train
https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/management/__init__.py#L125-L130
krukas/Trionyx
trionyx/quickstart/__init__.py
Quickstart.create_project
def create_project(self, project_path): """ Create Trionyx project in given path :param str path: path to create project in. :raises FileExistsError: """ shutil.copytree(self.project_path, project_path) self.update_file(project_path, 'requirements.txt', { ...
python
def create_project(self, project_path): """ Create Trionyx project in given path :param str path: path to create project in. :raises FileExistsError: """ shutil.copytree(self.project_path, project_path) self.update_file(project_path, 'requirements.txt', { ...
[ "def", "create_project", "(", "self", ",", "project_path", ")", ":", "shutil", ".", "copytree", "(", "self", ".", "project_path", ",", "project_path", ")", "self", ".", "update_file", "(", "project_path", ",", "'requirements.txt'", ",", "{", "'trionyx_version'",...
Create Trionyx project in given path :param str path: path to create project in. :raises FileExistsError:
[ "Create", "Trionyx", "project", "in", "given", "path" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/quickstart/__init__.py#L30-L45
krukas/Trionyx
trionyx/quickstart/__init__.py
Quickstart.create_app
def create_app(self, apps_path, name): """ Create Trionyx app in given path :param str path: path to create app in. :param str name: name of app :raises FileExistsError: """ app_path = os.path.join(apps_path, name.lower()) shutil.copytree(self.app_path, ...
python
def create_app(self, apps_path, name): """ Create Trionyx app in given path :param str path: path to create app in. :param str name: name of app :raises FileExistsError: """ app_path = os.path.join(apps_path, name.lower()) shutil.copytree(self.app_path, ...
[ "def", "create_app", "(", "self", ",", "apps_path", ",", "name", ")", ":", "app_path", "=", "os", ".", "path", ".", "join", "(", "apps_path", ",", "name", ".", "lower", "(", ")", ")", "shutil", ".", "copytree", "(", "self", ".", "app_path", ",", "a...
Create Trionyx app in given path :param str path: path to create app in. :param str name: name of app :raises FileExistsError:
[ "Create", "Trionyx", "app", "in", "given", "path" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/quickstart/__init__.py#L47-L66
krukas/Trionyx
trionyx/quickstart/__init__.py
Quickstart.update_file
def update_file(self, project_path, file_path, variables): """ Update given file with given variables, variables in file must be inclosed with [[]]. For example you want to replace a variable secret_key, in the file its [[secret_key]]. :param str project_path: :param str file_p...
python
def update_file(self, project_path, file_path, variables): """ Update given file with given variables, variables in file must be inclosed with [[]]. For example you want to replace a variable secret_key, in the file its [[secret_key]]. :param str project_path: :param str file_p...
[ "def", "update_file", "(", "self", ",", "project_path", ",", "file_path", ",", "variables", ")", ":", "update_file", "=", "os", ".", "path", ".", "join", "(", "project_path", ",", "file_path", ")", "with", "open", "(", "update_file", ",", "'rb'", ")", "a...
Update given file with given variables, variables in file must be inclosed with [[]]. For example you want to replace a variable secret_key, in the file its [[secret_key]]. :param str project_path: :param str file_path: :param dict variables:
[ "Update", "given", "file", "with", "given", "variables", "variables", "in", "file", "must", "be", "inclosed", "with", "[[", "]]", "." ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/quickstart/__init__.py#L68-L86
firstprayer/monsql
monsql/table.py
Table.count
def count(self, query=None, distinct=False, distinct_fields=None): """ Returns the number of rows satisying a criteria, if provided. :Parameters: - query: specify the WHERE clause - distinct : boolean, whether to use DISTINCT() - distinct_fields : list or tuple...
python
def count(self, query=None, distinct=False, distinct_fields=None): """ Returns the number of rows satisying a criteria, if provided. :Parameters: - query: specify the WHERE clause - distinct : boolean, whether to use DISTINCT() - distinct_fields : list or tuple...
[ "def", "count", "(", "self", ",", "query", "=", "None", ",", "distinct", "=", "False", ",", "distinct_fields", "=", "None", ")", ":", "if", "distinct_fields", "is", "None", ":", "self", ".", "__ensure_columns", "(", ")", "if", "distinct", ":", "field", ...
Returns the number of rows satisying a criteria, if provided. :Parameters: - query: specify the WHERE clause - distinct : boolean, whether to use DISTINCT() - distinct_fields : list or tuple or strings. Each string is a column name used inside COUNT(). If none, '*' w...
[ "Returns", "the", "number", "of", "rows", "satisying", "a", "criteria", "if", "provided", ".", ":", "Parameters", ":" ]
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/table.py#L69-L109
firstprayer/monsql
monsql/table.py
Table.find
def find(self, filter={}, fields=None, skip=0, limit=None, sort=None): """ Searches the table using the filters provided. :Examples: >>> users = user_table.find({'id': {'$in': [10, 20]}, 'age': {'$gt': 20}}) # Complex query >>> user_count = len(users) >>> for us...
python
def find(self, filter={}, fields=None, skip=0, limit=None, sort=None): """ Searches the table using the filters provided. :Examples: >>> users = user_table.find({'id': {'$in': [10, 20]}, 'age': {'$gt': 20}}) # Complex query >>> user_count = len(users) >>> for us...
[ "def", "find", "(", "self", ",", "filter", "=", "{", "}", ",", "fields", "=", "None", ",", "skip", "=", "0", ",", "limit", "=", "None", ",", "sort", "=", "None", ")", ":", "if", "not", "fields", ":", "self", ".", "__ensure_columns", "(", ")", "...
Searches the table using the filters provided. :Examples: >>> users = user_table.find({'id': {'$in': [10, 20]}, 'age': {'$gt': 20}}) # Complex query >>> user_count = len(users) >>> for user in users: >>> # Do something... >>> print user.id >>> ...
[ "Searches", "the", "table", "using", "the", "filters", "provided", ".", ":", "Examples", ":" ]
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/table.py#L112-L155
firstprayer/monsql
monsql/table.py
Table.find_one
def find_one(self, filter=None, fields=None, skip=0, sort=None): """ Similar to find. This method will only retrieve one row. If no row matches, returns None """ result = self.find(filter=filter, fields=fields, skip=skip, limit=1, sort=sort) if len(result) > 0: ...
python
def find_one(self, filter=None, fields=None, skip=0, sort=None): """ Similar to find. This method will only retrieve one row. If no row matches, returns None """ result = self.find(filter=filter, fields=fields, skip=skip, limit=1, sort=sort) if len(result) > 0: ...
[ "def", "find_one", "(", "self", ",", "filter", "=", "None", ",", "fields", "=", "None", ",", "skip", "=", "0", ",", "sort", "=", "None", ")", ":", "result", "=", "self", ".", "find", "(", "filter", "=", "filter", ",", "fields", "=", "fields", ","...
Similar to find. This method will only retrieve one row. If no row matches, returns None
[ "Similar", "to", "find", ".", "This", "method", "will", "only", "retrieve", "one", "row", ".", "If", "no", "row", "matches", "returns", "None" ]
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/table.py#L158-L167
firstprayer/monsql
monsql/table.py
Table.insert
def insert(self, data_or_list_of_data): """ Insert data into the table. :Examples: >>> user_table.insert({'username': 'Jude'}) # Insert one row >>> user_table.insert([{'username': 'Andy'}, {'username': 'Julia'}, ...]) # Insert multiple rows :Parameters:...
python
def insert(self, data_or_list_of_data): """ Insert data into the table. :Examples: >>> user_table.insert({'username': 'Jude'}) # Insert one row >>> user_table.insert([{'username': 'Andy'}, {'username': 'Julia'}, ...]) # Insert multiple rows :Parameters:...
[ "def", "insert", "(", "self", ",", "data_or_list_of_data", ")", ":", "result", "=", "None", "def", "insert_data", "(", "data", ")", ":", "sql", "=", "build_insert", "(", "self", ".", "name", ",", "data", ")", "row_count", "=", "self", ".", "cursor", "....
Insert data into the table. :Examples: >>> user_table.insert({'username': 'Jude'}) # Insert one row >>> user_table.insert([{'username': 'Andy'}, {'username': 'Julia'}, ...]) # Insert multiple rows :Parameters: - data_or_list_of_data: Either a dict or a list of...
[ "Insert", "data", "into", "the", "table", ".", ":", "Examples", ":", ">>>", "user_table", ".", "insert", "(", "{", "username", ":", "Jude", "}", ")", "#", "Insert", "one", "row", ">>>", "user_table", ".", "insert", "(", "[", "{", "username", ":", "An...
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/table.py#L170-L206
firstprayer/monsql
monsql/table.py
Table.update
def update(self, query, attributes, upsert=False): """ Updates data in the table. :Parameters: - query(dict), specify the WHERE clause - attributes(dict), specify the SET clause - upsert: boolean. If True, then when there's no row matches the query, insert the ...
python
def update(self, query, attributes, upsert=False): """ Updates data in the table. :Parameters: - query(dict), specify the WHERE clause - attributes(dict), specify the SET clause - upsert: boolean. If True, then when there's no row matches the query, insert the ...
[ "def", "update", "(", "self", ",", "query", ",", "attributes", ",", "upsert", "=", "False", ")", ":", "if", "upsert", ":", "found_result", "=", "self", ".", "find_one", "(", "query", ")", "if", "not", "found_result", ":", "id", "=", "self", ".", "ins...
Updates data in the table. :Parameters: - query(dict), specify the WHERE clause - attributes(dict), specify the SET clause - upsert: boolean. If True, then when there's no row matches the query, insert the values :Return: Number of rows updated or inserted
[ "Updates", "data", "in", "the", "table", ".", ":", "Parameters", ":" ]
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/table.py#L209-L231
firstprayer/monsql
monsql/table.py
Table.remove
def remove(self, filter=None): """ Removes rows from the table. :Parameters: - query(dict), specify the WHERE clause :Return: Number of rows deleted """ sql = build_delete(table_name=self.name, condition=filter) return self.cursor.execute(sql)
python
def remove(self, filter=None): """ Removes rows from the table. :Parameters: - query(dict), specify the WHERE clause :Return: Number of rows deleted """ sql = build_delete(table_name=self.name, condition=filter) return self.cursor.execute(sql)
[ "def", "remove", "(", "self", ",", "filter", "=", "None", ")", ":", "sql", "=", "build_delete", "(", "table_name", "=", "self", ".", "name", ",", "condition", "=", "filter", ")", "return", "self", ".", "cursor", ".", "execute", "(", "sql", ")" ]
Removes rows from the table. :Parameters: - query(dict), specify the WHERE clause :Return: Number of rows deleted
[ "Removes", "rows", "from", "the", "table", ".", ":", "Parameters", ":" ]
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/table.py#L234-L245
chocobn69/sergent
sergent/ssh.py
SergentSsh.get_s3_key
def get_s3_key(self): """ get ssh key in s3 bucket with specific name, load it in StringIO file :return: """ try: c = s3.connect_to_region(self._region, aws_access_key_id=self._aws_access_key_id, ...
python
def get_s3_key(self): """ get ssh key in s3 bucket with specific name, load it in StringIO file :return: """ try: c = s3.connect_to_region(self._region, aws_access_key_id=self._aws_access_key_id, ...
[ "def", "get_s3_key", "(", "self", ")", ":", "try", ":", "c", "=", "s3", ".", "connect_to_region", "(", "self", ".", "_region", ",", "aws_access_key_id", "=", "self", ".", "_aws_access_key_id", ",", "aws_secret_access_key", "=", "self", ".", "_aws_secret_access...
get ssh key in s3 bucket with specific name, load it in StringIO file :return:
[ "get", "ssh", "key", "in", "s3", "bucket", "with", "specific", "name", "load", "it", "in", "StringIO", "file", ":", "return", ":" ]
train
https://github.com/chocobn69/sergent/blob/7fa1be723777b2a209fa9b849b56dae40445834c/sergent/ssh.py#L172-L190
chocobn69/sergent
sergent/ssh.py
SergentSsh.get_instances_by_tag
def get_instances_by_tag(self, tags): """ :param tags:list of tags you to connect to (tagname=value) :return: instance list """ try: c = ec2.connect_to_region(self._region, aws_access_key_id=self._aws_access_key_id, ...
python
def get_instances_by_tag(self, tags): """ :param tags:list of tags you to connect to (tagname=value) :return: instance list """ try: c = ec2.connect_to_region(self._region, aws_access_key_id=self._aws_access_key_id, ...
[ "def", "get_instances_by_tag", "(", "self", ",", "tags", ")", ":", "try", ":", "c", "=", "ec2", ".", "connect_to_region", "(", "self", ".", "_region", ",", "aws_access_key_id", "=", "self", ".", "_aws_access_key_id", ",", "aws_secret_access_key", "=", "self", ...
:param tags:list of tags you to connect to (tagname=value) :return: instance list
[ ":", "param", "tags", ":", "list", "of", "tags", "you", "to", "connect", "to", "(", "tagname", "=", "value", ")", ":", "return", ":", "instance", "list" ]
train
https://github.com/chocobn69/sergent/blob/7fa1be723777b2a209fa9b849b56dae40445834c/sergent/ssh.py#L192-L216
chocobn69/sergent
sergent/ssh.py
SergentSsh.connect
def connect(self, instance, tag_ssh_user, tag_ssh_port, cmd): """ execute a command on instance with ssh and return if cmd param is not None connect to ssh if cmd is None :param instance: :param tag_ssh_user: :param tag_ssh_port: :param cmd: execute this command i...
python
def connect(self, instance, tag_ssh_user, tag_ssh_port, cmd): """ execute a command on instance with ssh and return if cmd param is not None connect to ssh if cmd is None :param instance: :param tag_ssh_user: :param tag_ssh_port: :param cmd: execute this command i...
[ "def", "connect", "(", "self", ",", "instance", ",", "tag_ssh_user", ",", "tag_ssh_port", ",", "cmd", ")", ":", "ssh_user", "=", "SergentSsh", ".", "get_ssh_user", "(", "instance", ",", "tag_ssh_user", ")", "ssh_port", "=", "SergentSsh", ".", "get_ssh_port", ...
execute a command on instance with ssh and return if cmd param is not None connect to ssh if cmd is None :param instance: :param tag_ssh_user: :param tag_ssh_port: :param cmd: execute this command if not None :return:
[ "execute", "a", "command", "on", "instance", "with", "ssh", "and", "return", "if", "cmd", "param", "is", "not", "None", "connect", "to", "ssh", "if", "cmd", "is", "None", ":", "param", "instance", ":", ":", "param", "tag_ssh_user", ":", ":", "param", "...
train
https://github.com/chocobn69/sergent/blob/7fa1be723777b2a209fa9b849b56dae40445834c/sergent/ssh.py#L253-L293
gear11/pypelogs
pypeout/mysql_out.py
MySQLOut.upsert
def upsert(self, events): """Inserts/updates the given events into MySQL""" existing = self.get_existing_keys(events) inserts = [e for e in events if not e[self.key] in existing] updates = [e for e in events if e[self.key] in existing] self.insert(inserts) self.update(upd...
python
def upsert(self, events): """Inserts/updates the given events into MySQL""" existing = self.get_existing_keys(events) inserts = [e for e in events if not e[self.key] in existing] updates = [e for e in events if e[self.key] in existing] self.insert(inserts) self.update(upd...
[ "def", "upsert", "(", "self", ",", "events", ")", ":", "existing", "=", "self", ".", "get_existing_keys", "(", "events", ")", "inserts", "=", "[", "e", "for", "e", "in", "events", "if", "not", "e", "[", "self", ".", "key", "]", "in", "existing", "]...
Inserts/updates the given events into MySQL
[ "Inserts", "/", "updates", "the", "given", "events", "into", "MySQL" ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypeout/mysql_out.py#L35-L41
gear11/pypelogs
pypeout/mysql_out.py
MySQLOut.get_existing_keys
def get_existing_keys(self, events): """Returns the list of keys from the given event source that are already in the DB""" data = [e[self.key] for e in events] ss = ','.join(['%s' for _ in data]) query = 'SELECT %s FROM %s WHERE %s IN (%s)' % (self.key, self.table, self.key, ss) ...
python
def get_existing_keys(self, events): """Returns the list of keys from the given event source that are already in the DB""" data = [e[self.key] for e in events] ss = ','.join(['%s' for _ in data]) query = 'SELECT %s FROM %s WHERE %s IN (%s)' % (self.key, self.table, self.key, ss) ...
[ "def", "get_existing_keys", "(", "self", ",", "events", ")", ":", "data", "=", "[", "e", "[", "self", ".", "key", "]", "for", "e", "in", "events", "]", "ss", "=", "','", ".", "join", "(", "[", "'%s'", "for", "_", "in", "data", "]", ")", "query"...
Returns the list of keys from the given event source that are already in the DB
[ "Returns", "the", "list", "of", "keys", "from", "the", "given", "event", "source", "that", "are", "already", "in", "the", "DB" ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypeout/mysql_out.py#L43-L53
gear11/pypelogs
pypeout/mysql_out.py
MySQLOut.insert
def insert(self, events): """Constructs and executes a MySQL insert for the given events.""" if not len(events): return keys = sorted(events[0].keys()) ss = ','.join(['%s' for _ in keys]) query = 'INSERT INTO %s (%s) VALUES ' % (self.table, ','.join(keys)) dat...
python
def insert(self, events): """Constructs and executes a MySQL insert for the given events.""" if not len(events): return keys = sorted(events[0].keys()) ss = ','.join(['%s' for _ in keys]) query = 'INSERT INTO %s (%s) VALUES ' % (self.table, ','.join(keys)) dat...
[ "def", "insert", "(", "self", ",", "events", ")", ":", "if", "not", "len", "(", "events", ")", ":", "return", "keys", "=", "sorted", "(", "events", "[", "0", "]", ".", "keys", "(", ")", ")", "ss", "=", "','", ".", "join", "(", "[", "'%s'", "f...
Constructs and executes a MySQL insert for the given events.
[ "Constructs", "and", "executes", "a", "MySQL", "insert", "for", "the", "given", "events", "." ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypeout/mysql_out.py#L55-L71
krukas/Trionyx
trionyx/renderer.py
datetime_value_renderer
def datetime_value_renderer(value, **options): """Render datetime value with django formats, default is SHORT_DATETIME_FORMAT""" datetime_format = options.get('datetime_format', 'SHORT_DATETIME_FORMAT') return formats.date_format(timezone.localtime(value), datetime_format)
python
def datetime_value_renderer(value, **options): """Render datetime value with django formats, default is SHORT_DATETIME_FORMAT""" datetime_format = options.get('datetime_format', 'SHORT_DATETIME_FORMAT') return formats.date_format(timezone.localtime(value), datetime_format)
[ "def", "datetime_value_renderer", "(", "value", ",", "*", "*", "options", ")", ":", "datetime_format", "=", "options", ".", "get", "(", "'datetime_format'", ",", "'SHORT_DATETIME_FORMAT'", ")", "return", "formats", ".", "date_format", "(", "timezone", ".", "loca...
Render datetime value with django formats, default is SHORT_DATETIME_FORMAT
[ "Render", "datetime", "value", "with", "django", "formats", "default", "is", "SHORT_DATETIME_FORMAT" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/renderer.py#L21-L24
krukas/Trionyx
trionyx/renderer.py
price_value_renderer
def price_value_renderer(value, currency=None, **options): """Format price value, with current locale and CURRENCY in settings""" if not currency: currency = getattr(settings, 'CURRENCY', 'USD') return format_currency(value, currency, locale=utils.get_current_locale())
python
def price_value_renderer(value, currency=None, **options): """Format price value, with current locale and CURRENCY in settings""" if not currency: currency = getattr(settings, 'CURRENCY', 'USD') return format_currency(value, currency, locale=utils.get_current_locale())
[ "def", "price_value_renderer", "(", "value", ",", "currency", "=", "None", ",", "*", "*", "options", ")", ":", "if", "not", "currency", ":", "currency", "=", "getattr", "(", "settings", ",", "'CURRENCY'", ",", "'USD'", ")", "return", "format_currency", "("...
Format price value, with current locale and CURRENCY in settings
[ "Format", "price", "value", "with", "current", "locale", "and", "CURRENCY", "in", "settings" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/renderer.py#L32-L36
krukas/Trionyx
trionyx/renderer.py
Renderer.render_value
def render_value(self, value, **options): """Render value""" renderer = self.renderers.get(type(value), lambda value, **options: value) return renderer(value, **options)
python
def render_value(self, value, **options): """Render value""" renderer = self.renderers.get(type(value), lambda value, **options: value) return renderer(value, **options)
[ "def", "render_value", "(", "self", ",", "value", ",", "*", "*", "options", ")", ":", "renderer", "=", "self", ".", "renderers", ".", "get", "(", "type", "(", "value", ")", ",", "lambda", "value", ",", "*", "*", "options", ":", "value", ")", "retur...
Render value
[ "Render", "value" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/renderer.py#L62-L65
krukas/Trionyx
trionyx/renderer.py
Renderer.render_field
def render_field(self, obj, field_name, **options): """Render field""" try: field = obj._meta.get_field(field_name) except FieldDoesNotExist: return getattr(obj, field_name, '') if hasattr(field, 'choices') and getattr(field, 'choices'): return getatt...
python
def render_field(self, obj, field_name, **options): """Render field""" try: field = obj._meta.get_field(field_name) except FieldDoesNotExist: return getattr(obj, field_name, '') if hasattr(field, 'choices') and getattr(field, 'choices'): return getatt...
[ "def", "render_field", "(", "self", ",", "obj", ",", "field_name", ",", "*", "*", "options", ")", ":", "try", ":", "field", "=", "obj", ".", "_meta", ".", "get_field", "(", "field_name", ")", "except", "FieldDoesNotExist", ":", "return", "getattr", "(", ...
Render field
[ "Render", "field" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/renderer.py#L67-L86
ThreshingFloor/libtf
libtf/logparsers/tf_log_base.py
TFLogBase.reduce
def reduce(self, show_noisy=False): """ Yield the reduced log lines :param show_noisy: If this is true, shows the reduced log file. If this is false, it shows the logs that were deleted. """ if not show_noisy: for log in self.quiet_logs: yield...
python
def reduce(self, show_noisy=False): """ Yield the reduced log lines :param show_noisy: If this is true, shows the reduced log file. If this is false, it shows the logs that were deleted. """ if not show_noisy: for log in self.quiet_logs: yield...
[ "def", "reduce", "(", "self", ",", "show_noisy", "=", "False", ")", ":", "if", "not", "show_noisy", ":", "for", "log", "in", "self", ".", "quiet_logs", ":", "yield", "log", "[", "'raw'", "]", ".", "strip", "(", ")", "else", ":", "for", "log", "in",...
Yield the reduced log lines :param show_noisy: If this is true, shows the reduced log file. If this is false, it shows the logs that were deleted.
[ "Yield", "the", "reduced", "log", "lines" ]
train
https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_log_base.py#L80-L92
ThreshingFloor/libtf
libtf/logparsers/tf_log_base.py
TFLogBase._get_filter
def _get_filter(self, features): """ Gets the filter for the features in the object :param features: The features of the syslog file """ # This chops the features up into smaller lists so the api can handle them for ip_batch in (features['ips'][pos:pos + self.ip_query_b...
python
def _get_filter(self, features): """ Gets the filter for the features in the object :param features: The features of the syslog file """ # This chops the features up into smaller lists so the api can handle them for ip_batch in (features['ips'][pos:pos + self.ip_query_b...
[ "def", "_get_filter", "(", "self", ",", "features", ")", ":", "# This chops the features up into smaller lists so the api can handle them", "for", "ip_batch", "in", "(", "features", "[", "'ips'", "]", "[", "pos", ":", "pos", "+", "self", ".", "ip_query_batch_size", ...
Gets the filter for the features in the object :param features: The features of the syslog file
[ "Gets", "the", "filter", "for", "the", "features", "in", "the", "object" ]
train
https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_log_base.py#L94-L106
ThreshingFloor/libtf
libtf/logparsers/tf_log_base.py
TFLogBase._send_features
def _send_features(self, features): """ Send a query to the backend api with a list of observed features in this log file :param features: Features found in the log file :return: Response text from ThreshingFloor API """ # Hit the auth endpoint with a list of features ...
python
def _send_features(self, features): """ Send a query to the backend api with a list of observed features in this log file :param features: Features found in the log file :return: Response text from ThreshingFloor API """ # Hit the auth endpoint with a list of features ...
[ "def", "_send_features", "(", "self", ",", "features", ")", ":", "# Hit the auth endpoint with a list of features", "try", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "base_uri", "+", "self", ".", "api_endpoint", ",", "json", "=", "features", ","...
Send a query to the backend api with a list of observed features in this log file :param features: Features found in the log file :return: Response text from ThreshingFloor API
[ "Send", "a", "query", "to", "the", "backend", "api", "with", "a", "list", "of", "observed", "features", "in", "this", "log", "file" ]
train
https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_log_base.py#L108-L127
crcresearch/py-utils
crc_nd/utils/file_io.py
clean_out_dir
def clean_out_dir(directory): """ Delete all the files and subdirectories in a directory. """ if not isinstance(directory, path): directory = path(directory) for file_path in directory.files(): file_path.remove() for dir_path in directory.dirs(): dir_path.rmtree()
python
def clean_out_dir(directory): """ Delete all the files and subdirectories in a directory. """ if not isinstance(directory, path): directory = path(directory) for file_path in directory.files(): file_path.remove() for dir_path in directory.dirs(): dir_path.rmtree()
[ "def", "clean_out_dir", "(", "directory", ")", ":", "if", "not", "isinstance", "(", "directory", ",", "path", ")", ":", "directory", "=", "path", "(", "directory", ")", "for", "file_path", "in", "directory", ".", "files", "(", ")", ":", "file_path", ".",...
Delete all the files and subdirectories in a directory.
[ "Delete", "all", "the", "files", "and", "subdirectories", "in", "a", "directory", "." ]
train
https://github.com/crcresearch/py-utils/blob/04caf0425a047baf900da726cf47c42413b0dd81/crc_nd/utils/file_io.py#L14-L23
shi-cong/PYSTUDY
PYSTUDY/loglib.py
Logger.check_log_file_size
def check_log_file_size(self): """如果日志文件超过100M,先保存源文件,再将原日志文件名后加“_时间戳”保存,再 重新以原文件名以追加模式创建,这样就实现了,只要日志文件超过100M就自动备份。 从而实现了控制日志文件大小的效果,由于在多线程进行同一个文件写入的时候,如果 文件大小超过了100m,而这一时刻,也有很多线程监测到了文件大小超限制,所以这时 那些知道超过了限制的线程就会改名文件,然后以追加方式重新打开文件,这样就会造成 改名后的文件的大小有的字节数在0字节这个范围,所以,我引入了锁来控制。 ...
python
def check_log_file_size(self): """如果日志文件超过100M,先保存源文件,再将原日志文件名后加“_时间戳”保存,再 重新以原文件名以追加模式创建,这样就实现了,只要日志文件超过100M就自动备份。 从而实现了控制日志文件大小的效果,由于在多线程进行同一个文件写入的时候,如果 文件大小超过了100m,而这一时刻,也有很多线程监测到了文件大小超限制,所以这时 那些知道超过了限制的线程就会改名文件,然后以追加方式重新打开文件,这样就会造成 改名后的文件的大小有的字节数在0字节这个范围,所以,我引入了锁来控制。 ...
[ "def", "check_log_file_size", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "getsize", "(", "self", ".", "fileName", ")", ">=", "1024", "*", "1024", "*", "1024", ":", "# 关闭文件", "self", ".", "__f", ".", "close", "(", ")", "# 改名", "r...
如果日志文件超过100M,先保存源文件,再将原日志文件名后加“_时间戳”保存,再 重新以原文件名以追加模式创建,这样就实现了,只要日志文件超过100M就自动备份。 从而实现了控制日志文件大小的效果,由于在多线程进行同一个文件写入的时候,如果 文件大小超过了100m,而这一时刻,也有很多线程监测到了文件大小超限制,所以这时 那些知道超过了限制的线程就会改名文件,然后以追加方式重新打开文件,这样就会造成 改名后的文件的大小有的字节数在0字节这个范围,所以,我引入了锁来控制。
[ "如果日志文件超过100M,先保存源文件,再将原日志文件名后加“_时间戳”保存,再", "重新以原文件名以追加模式创建,这样就实现了,只要日志文件超过100M就自动备份。", "从而实现了控制日志文件大小的效果,由于在多线程进行同一个文件写入的时候,如果", "文件大小超过了100m,而这一时刻,也有很多线程监测到了文件大小超限制,所以这时", "那些知道超过了限制的线程就会改名文件,然后以追加方式重新打开文件,这样就会造成", "改名后的文件的大小有的字节数在0字节这个范围,所以,我引入了锁来控制。" ]
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/loglib.py#L23-L38
shi-cong/PYSTUDY
PYSTUDY/loglib.py
Logger.log
def log(self, message): """ 打印或写日志 :params message: 要打印或要写的日志 """ theLog = '[日志名:%s] [时间:%s] \n[内容:\n%s]\n\n' % ( self.startName, timestamp_to_time(get_current_timestamp()), message) if not self.fileName: print(theLog) else: ...
python
def log(self, message): """ 打印或写日志 :params message: 要打印或要写的日志 """ theLog = '[日志名:%s] [时间:%s] \n[内容:\n%s]\n\n' % ( self.startName, timestamp_to_time(get_current_timestamp()), message) if not self.fileName: print(theLog) else: ...
[ "def", "log", "(", "self", ",", "message", ")", ":", "theLog", "=", "'[日志名:%s] [时间:%s] \\n[内容:\\n%s]\\n\\n' % (", "", "", "self", ".", "startName", ",", "timestamp_to_time", "(", "get_current_timestamp", "(", ")", ")", ",", "message", ")", "if", "not", "self",...
打印或写日志 :params message: 要打印或要写的日志
[ "打印或写日志", ":", "params", "message", ":", "要打印或要写的日志" ]
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/loglib.py#L40-L52
davidwtbuxton/appengine.py
appengine.py
_extract_zip
def _extract_zip(archive, dest=None, members=None): """Extract the ZipInfo object to a real file on the path targetpath.""" # Python 2.5 compatibility. dest = dest or os.getcwd() members = members or archive.infolist() for member in members: if isinstance(member, basestring): me...
python
def _extract_zip(archive, dest=None, members=None): """Extract the ZipInfo object to a real file on the path targetpath.""" # Python 2.5 compatibility. dest = dest or os.getcwd() members = members or archive.infolist() for member in members: if isinstance(member, basestring): me...
[ "def", "_extract_zip", "(", "archive", ",", "dest", "=", "None", ",", "members", "=", "None", ")", ":", "# Python 2.5 compatibility.", "dest", "=", "dest", "or", "os", ".", "getcwd", "(", ")", "members", "=", "members", "or", "archive", ".", "infolist", ...
Extract the ZipInfo object to a real file on the path targetpath.
[ "Extract", "the", "ZipInfo", "object", "to", "a", "real", "file", "on", "the", "path", "targetpath", "." ]
train
https://github.com/davidwtbuxton/appengine.py/blob/9ef666c282406b3d8799bfa4c70f99870b21a236/appengine.py#L23-L33
davidwtbuxton/appengine.py
appengine.py
make_parser
def make_parser(): """Returns a new option parser.""" p = optparse.OptionParser() p.add_option('--prefix', metavar='DIR', help='install SDK in DIR') p.add_option('--bindir', metavar='DIR', help='install tools in DIR') p.add_option('--force', action='store_true', default=False, help='over-wri...
python
def make_parser(): """Returns a new option parser.""" p = optparse.OptionParser() p.add_option('--prefix', metavar='DIR', help='install SDK in DIR') p.add_option('--bindir', metavar='DIR', help='install tools in DIR') p.add_option('--force', action='store_true', default=False, help='over-wri...
[ "def", "make_parser", "(", ")", ":", "p", "=", "optparse", ".", "OptionParser", "(", ")", "p", ".", "add_option", "(", "'--prefix'", ",", "metavar", "=", "'DIR'", ",", "help", "=", "'install SDK in DIR'", ")", "p", ".", "add_option", "(", "'--bindir'", "...
Returns a new option parser.
[ "Returns", "a", "new", "option", "parser", "." ]
train
https://github.com/davidwtbuxton/appengine.py/blob/9ef666c282406b3d8799bfa4c70f99870b21a236/appengine.py#L60-L70
davidwtbuxton/appengine.py
appengine.py
parse_args
def parse_args(argv): """Returns a tuple of (opts, args) for arguments.""" parser = make_parser() opts, args = parser.parse_args(argv[1:]) # Use APPENGINEPY_SDK_VERSION if set. if not args and (sdk_version_key in os.environ): args = (os.environ[sdk_version_key],) return opts, args
python
def parse_args(argv): """Returns a tuple of (opts, args) for arguments.""" parser = make_parser() opts, args = parser.parse_args(argv[1:]) # Use APPENGINEPY_SDK_VERSION if set. if not args and (sdk_version_key in os.environ): args = (os.environ[sdk_version_key],) return opts, args
[ "def", "parse_args", "(", "argv", ")", ":", "parser", "=", "make_parser", "(", ")", "opts", ",", "args", "=", "parser", ".", "parse_args", "(", "argv", "[", "1", ":", "]", ")", "# Use APPENGINEPY_SDK_VERSION if set.", "if", "not", "args", "and", "(", "sd...
Returns a tuple of (opts, args) for arguments.
[ "Returns", "a", "tuple", "of", "(", "opts", "args", ")", "for", "arguments", "." ]
train
https://github.com/davidwtbuxton/appengine.py/blob/9ef666c282406b3d8799bfa4c70f99870b21a236/appengine.py#L73-L83
davidwtbuxton/appengine.py
appengine.py
check_version
def check_version(url=VERSION_URL): """Returns the version string for the latest SDK.""" for line in get(url): if 'release:' in line: return line.split(':')[-1].strip(' \'"\r\n')
python
def check_version(url=VERSION_URL): """Returns the version string for the latest SDK.""" for line in get(url): if 'release:' in line: return line.split(':')[-1].strip(' \'"\r\n')
[ "def", "check_version", "(", "url", "=", "VERSION_URL", ")", ":", "for", "line", "in", "get", "(", "url", ")", ":", "if", "'release:'", "in", "line", ":", "return", "line", ".", "split", "(", "':'", ")", "[", "-", "1", "]", ".", "strip", "(", "' ...
Returns the version string for the latest SDK.
[ "Returns", "the", "version", "string", "for", "the", "latest", "SDK", "." ]
train
https://github.com/davidwtbuxton/appengine.py/blob/9ef666c282406b3d8799bfa4c70f99870b21a236/appengine.py#L92-L96
davidwtbuxton/appengine.py
appengine.py
parse_sdk_name
def parse_sdk_name(name): """Returns a filename or URL for the SDK name. The name can be a version string, a remote URL or a local path. """ # Version like x.y.z, return as-is. if all(part.isdigit() for part in name.split('.', 2)): return DOWNLOAD_URL % name # A network location. u...
python
def parse_sdk_name(name): """Returns a filename or URL for the SDK name. The name can be a version string, a remote URL or a local path. """ # Version like x.y.z, return as-is. if all(part.isdigit() for part in name.split('.', 2)): return DOWNLOAD_URL % name # A network location. u...
[ "def", "parse_sdk_name", "(", "name", ")", ":", "# Version like x.y.z, return as-is.", "if", "all", "(", "part", ".", "isdigit", "(", ")", "for", "part", "in", "name", ".", "split", "(", "'.'", ",", "2", ")", ")", ":", "return", "DOWNLOAD_URL", "%", "nam...
Returns a filename or URL for the SDK name. The name can be a version string, a remote URL or a local path.
[ "Returns", "a", "filename", "or", "URL", "for", "the", "SDK", "name", "." ]
train
https://github.com/davidwtbuxton/appengine.py/blob/9ef666c282406b3d8799bfa4c70f99870b21a236/appengine.py#L99-L114
davidwtbuxton/appengine.py
appengine.py
open_sdk
def open_sdk(url): """Open the SDK from the URL, which can be either a network location or a filename path. Returns a file-like object open for reading. """ if urlparse.urlparse(url).scheme: return _download(url) else: return open(url)
python
def open_sdk(url): """Open the SDK from the URL, which can be either a network location or a filename path. Returns a file-like object open for reading. """ if urlparse.urlparse(url).scheme: return _download(url) else: return open(url)
[ "def", "open_sdk", "(", "url", ")", ":", "if", "urlparse", ".", "urlparse", "(", "url", ")", ".", "scheme", ":", "return", "_download", "(", "url", ")", "else", ":", "return", "open", "(", "url", ")" ]
Open the SDK from the URL, which can be either a network location or a filename path. Returns a file-like object open for reading.
[ "Open", "the", "SDK", "from", "the", "URL", "which", "can", "be", "either", "a", "network", "location", "or", "a", "filename", "path", ".", "Returns", "a", "file", "-", "like", "object", "open", "for", "reading", "." ]
train
https://github.com/davidwtbuxton/appengine.py/blob/9ef666c282406b3d8799bfa4c70f99870b21a236/appengine.py#L117-L124
davidwtbuxton/appengine.py
appengine.py
_download
def _download(url): """Downloads an URL and returns a file-like object open for reading, compatible with zipping.ZipFile (it has a seek() method). """ fh = StringIO() for line in get(url): fh.write(line) fh.seek(0) return fh
python
def _download(url): """Downloads an URL and returns a file-like object open for reading, compatible with zipping.ZipFile (it has a seek() method). """ fh = StringIO() for line in get(url): fh.write(line) fh.seek(0) return fh
[ "def", "_download", "(", "url", ")", ":", "fh", "=", "StringIO", "(", ")", "for", "line", "in", "get", "(", "url", ")", ":", "fh", ".", "write", "(", "line", ")", "fh", ".", "seek", "(", "0", ")", "return", "fh" ]
Downloads an URL and returns a file-like object open for reading, compatible with zipping.ZipFile (it has a seek() method).
[ "Downloads", "an", "URL", "and", "returns", "a", "file", "-", "like", "object", "open", "for", "reading", "compatible", "with", "zipping", ".", "ZipFile", "(", "it", "has", "a", "seek", "()", "method", ")", "." ]
train
https://github.com/davidwtbuxton/appengine.py/blob/9ef666c282406b3d8799bfa4c70f99870b21a236/appengine.py#L127-L137
bcho/bearychat-py
bearychat/incoming.py
Incoming.reset
def reset(self): '''Reset stream.''' self._text = None self._markdown = False self._channel = Incoming.DEFAULT_CHANNEL self._attachments = [] return self
python
def reset(self): '''Reset stream.''' self._text = None self._markdown = False self._channel = Incoming.DEFAULT_CHANNEL self._attachments = [] return self
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_text", "=", "None", "self", ".", "_markdown", "=", "False", "self", ".", "_channel", "=", "Incoming", ".", "DEFAULT_CHANNEL", "self", ".", "_attachments", "=", "[", "]", "return", "self" ]
Reset stream.
[ "Reset", "stream", "." ]
train
https://github.com/bcho/bearychat-py/blob/d492595d6334dfba511f82770995160ee12b5de1/bearychat/incoming.py#L43-L50
bcho/bearychat-py
bearychat/incoming.py
Incoming.with_text
def with_text(self, text, markdown=None): '''Set text content. :param text: text content. :param markdown: is markdown? Defaults to ``False``. ''' self._text = text self._markdown = markdown or False return self
python
def with_text(self, text, markdown=None): '''Set text content. :param text: text content. :param markdown: is markdown? Defaults to ``False``. ''' self._text = text self._markdown = markdown or False return self
[ "def", "with_text", "(", "self", ",", "text", ",", "markdown", "=", "None", ")", ":", "self", ".", "_text", "=", "text", "self", ".", "_markdown", "=", "markdown", "or", "False", "return", "self" ]
Set text content. :param text: text content. :param markdown: is markdown? Defaults to ``False``.
[ "Set", "text", "content", "." ]
train
https://github.com/bcho/bearychat-py/blob/d492595d6334dfba511f82770995160ee12b5de1/bearychat/incoming.py#L61-L70
bcho/bearychat-py
bearychat/incoming.py
Incoming.build_message
def build_message(self): '''Build a message. :raises InvalidPayloadError: ''' if self._text is None: raise InvalidPayloadError('text is required') message = { 'text': self._text, 'markdown': self._markdown } if self._channel ...
python
def build_message(self): '''Build a message. :raises InvalidPayloadError: ''' if self._text is None: raise InvalidPayloadError('text is required') message = { 'text': self._text, 'markdown': self._markdown } if self._channel ...
[ "def", "build_message", "(", "self", ")", ":", "if", "self", ".", "_text", "is", "None", ":", "raise", "InvalidPayloadError", "(", "'text is required'", ")", "message", "=", "{", "'text'", ":", "self", ".", "_text", ",", "'markdown'", ":", "self", ".", "...
Build a message. :raises InvalidPayloadError:
[ "Build", "a", "message", "." ]
train
https://github.com/bcho/bearychat-py/blob/d492595d6334dfba511f82770995160ee12b5de1/bearychat/incoming.py#L88-L111
bcho/bearychat-py
bearychat/incoming.py
Incoming.push
def push(self): '''Deliver the message.''' message = self.build_message() return requests.post(self.hook, json=message)
python
def push(self): '''Deliver the message.''' message = self.build_message() return requests.post(self.hook, json=message)
[ "def", "push", "(", "self", ")", ":", "message", "=", "self", ".", "build_message", "(", ")", "return", "requests", ".", "post", "(", "self", ".", "hook", ",", "json", "=", "message", ")" ]
Deliver the message.
[ "Deliver", "the", "message", "." ]
train
https://github.com/bcho/bearychat-py/blob/d492595d6334dfba511f82770995160ee12b5de1/bearychat/incoming.py#L113-L116
cabalgata/cabalgata-silla-de-montar
cabalgata/silla/factories.py
load_factory
def load_factory(name, directory, configuration=None): """ Load a factory and have it initialize in a particular directory :param name: the name of the plugin to load :param directory: the directory where the factory will reside :return: """ for entry_point in pkg_resources.iter_entry_points(ENT...
python
def load_factory(name, directory, configuration=None): """ Load a factory and have it initialize in a particular directory :param name: the name of the plugin to load :param directory: the directory where the factory will reside :return: """ for entry_point in pkg_resources.iter_entry_points(ENT...
[ "def", "load_factory", "(", "name", ",", "directory", ",", "configuration", "=", "None", ")", ":", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "ENTRY_POINT", ")", ":", "if", "entry_point", ".", "name", "==", "name", ":", "fact...
Load a factory and have it initialize in a particular directory :param name: the name of the plugin to load :param directory: the directory where the factory will reside :return:
[ "Load", "a", "factory", "and", "have", "it", "initialize", "in", "a", "particular", "directory", ":", "param", "name", ":", "the", "name", "of", "the", "plugin", "to", "load", ":", "param", "directory", ":", "the", "directory", "where", "the", "factory", ...
train
https://github.com/cabalgata/cabalgata-silla-de-montar/blob/6f1de56f207e55d788d56636f623c0e3ce1aa750/cabalgata/silla/factories.py#L24-L35
Ingener74/Silly-Crossbow
SillyCrossbow/SillyCrossbow/crop.py
crop_image
def crop_image(image, threshold): """ Найти непрозрачную область на изображении и вырезать её :param image: Изображение :param threshold: Порог прозрачности для обрезания :return: cropped_image - вырезанное изображение x, y, width, height - координаты и размер вырезаннго прямоугольника ...
python
def crop_image(image, threshold): """ Найти непрозрачную область на изображении и вырезать её :param image: Изображение :param threshold: Порог прозрачности для обрезания :return: cropped_image - вырезанное изображение x, y, width, height - координаты и размер вырезаннго прямоугольника ...
[ "def", "crop_image", "(", "image", ",", "threshold", ")", ":", "cropper", "=", "CropTransparent", "(", "image", ".", "width", "(", ")", ",", "image", ".", "height", "(", ")", ",", "threshold", ",", "str", "(", "image", ".", "constBits", "(", ")", ")"...
Найти непрозрачную область на изображении и вырезать её :param image: Изображение :param threshold: Порог прозрачности для обрезания :return: cropped_image - вырезанное изображение x, y, width, height - координаты и размер вырезаннго прямоугольника
[ "Найти", "непрозрачную", "область", "на", "изображении", "и", "вырезать", "её", ":", "param", "image", ":", "Изображение", ":", "param", "threshold", ":", "Порог", "прозрачности", "для", "обрезания", ":", "return", ":", "cropped_image", "-", "вырезанное", "изобр...
train
https://github.com/Ingener74/Silly-Crossbow/blob/ac70265f885ea6bdcea04c737b0f8528be023263/SillyCrossbow/SillyCrossbow/crop.py#L19-L35
briancappello/flask-sqlalchemy-bundle
flask_sqlalchemy_bundle/meta/model_registry.py
_ModelRegistry._convert_bases_to_mixins
def _convert_bases_to_mixins(self, mcs_args: McsArgs): """ For each base class in bases that the _ModelRegistry knows about, create a replacement class containing the methods and attributes from the base class: - the mixin should only extend object (not db.Model) - if a...
python
def _convert_bases_to_mixins(self, mcs_args: McsArgs): """ For each base class in bases that the _ModelRegistry knows about, create a replacement class containing the methods and attributes from the base class: - the mixin should only extend object (not db.Model) - if a...
[ "def", "_convert_bases_to_mixins", "(", "self", ",", "mcs_args", ":", "McsArgs", ")", ":", "def", "_mixin_name", "(", "name", ")", ":", "return", "f'{name}_FSQLAConvertedMixin'", "new_base_names", "=", "set", "(", ")", "new_bases", "=", "[", "]", "for", "b", ...
For each base class in bases that the _ModelRegistry knows about, create a replacement class containing the methods and attributes from the base class: - the mixin should only extend object (not db.Model) - if any of the attributes are MapperProperty instances (relationship, ...
[ "For", "each", "base", "class", "in", "bases", "that", "the", "_ModelRegistry", "knows", "about", "create", "a", "replacement", "class", "containing", "the", "methods", "and", "attributes", "from", "the", "base", "class", ":", "-", "the", "mixin", "should", ...
train
https://github.com/briancappello/flask-sqlalchemy-bundle/blob/8150896787907ef0001839b5a6ef303edccb9b6c/flask_sqlalchemy_bundle/meta/model_registry.py#L149-L201
luismasuelli/python-cantrips
cantrips/patterns/identify.py
List.create
def create(self, key, *args, **kwargs): """ Creates and inserts an identified object with the passed params using the specified class. """ instance = self._class(key, *args, **kwargs) self._events.create.trigger(list=self, instance=instance, key=key, args=args, kwargs...
python
def create(self, key, *args, **kwargs): """ Creates and inserts an identified object with the passed params using the specified class. """ instance = self._class(key, *args, **kwargs) self._events.create.trigger(list=self, instance=instance, key=key, args=args, kwargs...
[ "def", "create", "(", "self", ",", "key", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "instance", "=", "self", ".", "_class", "(", "key", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_events", ".", "create", ".", "trig...
Creates and inserts an identified object with the passed params using the specified class.
[ "Creates", "and", "inserts", "an", "identified", "object", "with", "the", "passed", "params", "using", "the", "specified", "class", "." ]
train
https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/patterns/identify.py#L53-L60
luismasuelli/python-cantrips
cantrips/patterns/identify.py
List.insert
def insert(self, identified): """ Inserts an already-created identified object of the expected class. """ if not isinstance(identified, self._class): raise self.Error("Passed instance is not of the needed class", self.Error.INVALID_INSTANCE_CLASS...
python
def insert(self, identified): """ Inserts an already-created identified object of the expected class. """ if not isinstance(identified, self._class): raise self.Error("Passed instance is not of the needed class", self.Error.INVALID_INSTANCE_CLASS...
[ "def", "insert", "(", "self", ",", "identified", ")", ":", "if", "not", "isinstance", "(", "identified", ",", "self", ".", "_class", ")", ":", "raise", "self", ".", "Error", "(", "\"Passed instance is not of the needed class\"", ",", "self", ".", "Error", "....
Inserts an already-created identified object of the expected class.
[ "Inserts", "an", "already", "-", "created", "identified", "object", "of", "the", "expected", "class", "." ]
train
https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/patterns/identify.py#L62-L78
luismasuelli/python-cantrips
cantrips/patterns/identify.py
List.remove
def remove(self, identified): """ Removes an already-created identified object. A key may be passed instead of an identified object. If an object is passed, and its key is held by another object inside the record, an error is triggered. Returns the removed object. ...
python
def remove(self, identified): """ Removes an already-created identified object. A key may be passed instead of an identified object. If an object is passed, and its key is held by another object inside the record, an error is triggered. Returns the removed object. ...
[ "def", "remove", "(", "self", ",", "identified", ")", ":", "by_val", "=", "isinstance", "(", "identified", ",", "Identified", ")", "if", "by_val", ":", "key", "=", "identified", ".", "key", "if", "not", "isinstance", "(", "identified", ",", "self", ".", ...
Removes an already-created identified object. A key may be passed instead of an identified object. If an object is passed, and its key is held by another object inside the record, an error is triggered. Returns the removed object.
[ "Removes", "an", "already", "-", "created", "identified", "object", ".", "A", "key", "may", "be", "passed", "instead", "of", "an", "identified", "object", ".", "If", "an", "object", "is", "passed", "and", "its", "key", "is", "held", "by", "another", "obj...
train
https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/patterns/identify.py#L80-L106
pydron/twistit
twistit/_timeout.py
timeout_deferred
def timeout_deferred(deferred, timeout, error_message="Timeout occured"): """ Waits a given time, if the given deferred hasn't called back by then we cancel it. If the deferred was cancelled by the timeout, a `TimeoutError` error is produced. Returns `deferred`. """ timeout_occured...
python
def timeout_deferred(deferred, timeout, error_message="Timeout occured"): """ Waits a given time, if the given deferred hasn't called back by then we cancel it. If the deferred was cancelled by the timeout, a `TimeoutError` error is produced. Returns `deferred`. """ timeout_occured...
[ "def", "timeout_deferred", "(", "deferred", ",", "timeout", ",", "error_message", "=", "\"Timeout occured\"", ")", ":", "timeout_occured", "=", "[", "False", "]", "def", "got_result", "(", "result", ")", ":", "if", "not", "timeout_occured", "[", "0", "]", ":...
Waits a given time, if the given deferred hasn't called back by then we cancel it. If the deferred was cancelled by the timeout, a `TimeoutError` error is produced. Returns `deferred`.
[ "Waits", "a", "given", "time", "if", "the", "given", "deferred", "hasn", "t", "called", "back", "by", "then", "we", "cancel", "it", ".", "If", "the", "deferred", "was", "cancelled", "by", "the", "timeout", "a", "TimeoutError", "error", "is", "produced", ...
train
https://github.com/pydron/twistit/blob/23ac43b830083fd32c400fcdfa5300e302769c74/twistit/_timeout.py#L24-L58
bitlabstudio/django-unshorten
unshorten/auth.py
SimpleAuthentication.http_auth
def http_auth(self): """ Returns ``True`` if valid http auth credentials are found in the request header. """ if 'HTTP_AUTHORIZATION' in self.request.META.keys(): authmeth, auth = self.request.META['HTTP_AUTHORIZATION'].split( ' ', 1) if a...
python
def http_auth(self): """ Returns ``True`` if valid http auth credentials are found in the request header. """ if 'HTTP_AUTHORIZATION' in self.request.META.keys(): authmeth, auth = self.request.META['HTTP_AUTHORIZATION'].split( ' ', 1) if a...
[ "def", "http_auth", "(", "self", ")", ":", "if", "'HTTP_AUTHORIZATION'", "in", "self", ".", "request", ".", "META", ".", "keys", "(", ")", ":", "authmeth", ",", "auth", "=", "self", ".", "request", ".", "META", "[", "'HTTP_AUTHORIZATION'", "]", ".", "s...
Returns ``True`` if valid http auth credentials are found in the request header.
[ "Returns", "True", "if", "valid", "http", "auth", "credentials", "are", "found", "in", "the", "request", "header", "." ]
train
https://github.com/bitlabstudio/django-unshorten/blob/6d184de908bb9df3aad5ac3fd9732d976afb6953/unshorten/auth.py#L38-L54
hactar-is/frink
frink/__init__.py
Frink.init
def init(self, db=RDB_DB, host=RDB_HOST, port=RDB_PORT): """Create the Frink object to store the connection credentials.""" self.RDB_HOST = host self.RDB_PORT = port self.RDB_DB = db from .connection import RethinkDB self.rdb = RethinkDB() self.rdb.init()
python
def init(self, db=RDB_DB, host=RDB_HOST, port=RDB_PORT): """Create the Frink object to store the connection credentials.""" self.RDB_HOST = host self.RDB_PORT = port self.RDB_DB = db from .connection import RethinkDB self.rdb = RethinkDB() self.rdb.init()
[ "def", "init", "(", "self", ",", "db", "=", "RDB_DB", ",", "host", "=", "RDB_HOST", ",", "port", "=", "RDB_PORT", ")", ":", "self", ".", "RDB_HOST", "=", "host", "self", ".", "RDB_PORT", "=", "port", "self", ".", "RDB_DB", "=", "db", "from", ".", ...
Create the Frink object to store the connection credentials.
[ "Create", "the", "Frink", "object", "to", "store", "the", "connection", "credentials", "." ]
train
https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/__init__.py#L17-L25
zerok/zs.bibtex
src/zs/bibtex/parser.py
normalize_value
def normalize_value(text): """ This removes newlines and multiple spaces from a string. """ result = text.replace('\n', ' ') result = re.subn('[ ]{2,}', ' ', result)[0] return result
python
def normalize_value(text): """ This removes newlines and multiple spaces from a string. """ result = text.replace('\n', ' ') result = re.subn('[ ]{2,}', ' ', result)[0] return result
[ "def", "normalize_value", "(", "text", ")", ":", "result", "=", "text", ".", "replace", "(", "'\\n'", ",", "' '", ")", "result", "=", "re", ".", "subn", "(", "'[ ]{2,}'", ",", "' '", ",", "result", ")", "[", "0", "]", "return", "result" ]
This removes newlines and multiple spaces from a string.
[ "This", "removes", "newlines", "and", "multiple", "spaces", "from", "a", "string", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/parser.py#L16-L22
zerok/zs.bibtex
src/zs/bibtex/parser.py
parse_field
def parse_field(source, loc, tokens): """ Returns the tokens of a field as key-value pair. """ name = tokens[0].lower() value = normalize_value(tokens[2]) if name == 'author' and ' and ' in value: value = [field.strip() for field in value.split(' and ')] return (name, value)
python
def parse_field(source, loc, tokens): """ Returns the tokens of a field as key-value pair. """ name = tokens[0].lower() value = normalize_value(tokens[2]) if name == 'author' and ' and ' in value: value = [field.strip() for field in value.split(' and ')] return (name, value)
[ "def", "parse_field", "(", "source", ",", "loc", ",", "tokens", ")", ":", "name", "=", "tokens", "[", "0", "]", ".", "lower", "(", ")", "value", "=", "normalize_value", "(", "tokens", "[", "2", "]", ")", "if", "name", "==", "'author'", "and", "' an...
Returns the tokens of a field as key-value pair.
[ "Returns", "the", "tokens", "of", "a", "field", "as", "key", "-", "value", "pair", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/parser.py#L27-L35
zerok/zs.bibtex
src/zs/bibtex/parser.py
parse_entry
def parse_entry(source, loc, tokens): """ Converts the tokens of an entry into an Entry instance. If no applicable type is available, an UnsupportedEntryType exception is raised. """ type_ = tokens[1].lower() entry_type = structures.TypeRegistry.get_type(type_) if entry_type is None or not i...
python
def parse_entry(source, loc, tokens): """ Converts the tokens of an entry into an Entry instance. If no applicable type is available, an UnsupportedEntryType exception is raised. """ type_ = tokens[1].lower() entry_type = structures.TypeRegistry.get_type(type_) if entry_type is None or not i...
[ "def", "parse_entry", "(", "source", ",", "loc", ",", "tokens", ")", ":", "type_", "=", "tokens", "[", "1", "]", ".", "lower", "(", ")", "entry_type", "=", "structures", ".", "TypeRegistry", ".", "get_type", "(", "type_", ")", "if", "entry_type", "is",...
Converts the tokens of an entry into an Entry instance. If no applicable type is available, an UnsupportedEntryType exception is raised.
[ "Converts", "the", "tokens", "of", "an", "entry", "into", "an", "Entry", "instance", ".", "If", "no", "applicable", "type", "is", "available", "an", "UnsupportedEntryType", "exception", "is", "raised", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/parser.py#L37-L52
zerok/zs.bibtex
src/zs/bibtex/parser.py
parse_bibliography
def parse_bibliography(source, loc, tokens): """ Combines the parsed entries into a Bibliography instance. """ bib = structures.Bibliography() for entry in tokens: bib.add(entry) return bib
python
def parse_bibliography(source, loc, tokens): """ Combines the parsed entries into a Bibliography instance. """ bib = structures.Bibliography() for entry in tokens: bib.add(entry) return bib
[ "def", "parse_bibliography", "(", "source", ",", "loc", ",", "tokens", ")", ":", "bib", "=", "structures", ".", "Bibliography", "(", ")", "for", "entry", "in", "tokens", ":", "bib", ".", "add", "(", "entry", ")", "return", "bib" ]
Combines the parsed entries into a Bibliography instance.
[ "Combines", "the", "parsed", "entries", "into", "a", "Bibliography", "instance", "." ]
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/parser.py#L54-L61
zerok/zs.bibtex
src/zs/bibtex/parser.py
parse_string
def parse_string(str_, validate=False): """ Tries to parse a given string into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules. """ result = pattern.parseString(str_)[0] if validate: ...
python
def parse_string(str_, validate=False): """ Tries to parse a given string into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules. """ result = pattern.parseString(str_)[0] if validate: ...
[ "def", "parse_string", "(", "str_", ",", "validate", "=", "False", ")", ":", "result", "=", "pattern", ".", "parseString", "(", "str_", ")", "[", "0", "]", "if", "validate", ":", "result", ".", "validate", "(", ")", "return", "result" ]
Tries to parse a given string into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules.
[ "Tries", "to", "parse", "a", "given", "string", "into", "a", "Bibliography", "instance", ".", "If", "validate", "is", "passed", "as", "keyword", "argument", "and", "set", "to", "True", "the", "Bibliography", "will", "be", "validated", "using", "the", "standa...
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/parser.py#L103-L112
zerok/zs.bibtex
src/zs/bibtex/parser.py
parse_file
def parse_file(file_or_path, encoding='utf-8', validate=False): """ Tries to parse a given filepath or fileobj into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules. """ try: is_string ...
python
def parse_file(file_or_path, encoding='utf-8', validate=False): """ Tries to parse a given filepath or fileobj into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules. """ try: is_string ...
[ "def", "parse_file", "(", "file_or_path", ",", "encoding", "=", "'utf-8'", ",", "validate", "=", "False", ")", ":", "try", ":", "is_string", "=", "isinstance", "(", "file_or_path", ",", "basestring", ")", "except", "NameError", ":", "is_string", "=", "isinst...
Tries to parse a given filepath or fileobj into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules.
[ "Tries", "to", "parse", "a", "given", "filepath", "or", "fileobj", "into", "a", "Bibliography", "instance", ".", "If", "validate", "is", "passed", "as", "keyword", "argument", "and", "set", "to", "True", "the", "Bibliography", "will", "be", "validated", "usi...
train
https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/parser.py#L115-L132
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer.connection_made
def connection_made(self, transport: asyncio.transports.Transport): """连接建立起来触发的回调函数. 用于设定一些参数,并将监听任务放入事件循环,如果设置了timeout,也会将timeout_callback放入事件循环 Parameters: transport (asyncio.Transports): - 连接的传输对象 """ self._transport = transport self._remote_host = self...
python
def connection_made(self, transport: asyncio.transports.Transport): """连接建立起来触发的回调函数. 用于设定一些参数,并将监听任务放入事件循环,如果设置了timeout,也会将timeout_callback放入事件循环 Parameters: transport (asyncio.Transports): - 连接的传输对象 """ self._transport = transport self._remote_host = self...
[ "def", "connection_made", "(", "self", ",", "transport", ":", "asyncio", ".", "transports", ".", "Transport", ")", ":", "self", ".", "_transport", "=", "transport", "self", ".", "_remote_host", "=", "self", ".", "_transport", ".", "get_extra_info", "(", "'pe...
连接建立起来触发的回调函数. 用于设定一些参数,并将监听任务放入事件循环,如果设置了timeout,也会将timeout_callback放入事件循环 Parameters: transport (asyncio.Transports): - 连接的传输对象
[ "连接建立起来触发的回调函数", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L143-L167
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer.connection_lost
def connection_lost(self, exc: Exception=None): """连接丢失时触发的回调函数. 用于清理一些任务和关闭连接,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置 + 将本连接从当前的连接池中去除 Parameters: exc (Exception): - 异常,如果是None的话说明不是因为异常而关闭的连接 """ self._handlertask...
python
def connection_lost(self, exc: Exception=None): """连接丢失时触发的回调函数. 用于清理一些任务和关闭连接,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置 + 将本连接从当前的连接池中去除 Parameters: exc (Exception): - 异常,如果是None的话说明不是因为异常而关闭的连接 """ self._handlertask...
[ "def", "connection_lost", "(", "self", ",", "exc", ":", "Exception", "=", "None", ")", ":", "self", ".", "_handlertask", ".", "cancel", "(", ")", "super", "(", ")", ".", "connection_lost", "(", "exc", ")", "if", "self", ".", "_timeout_handler", ":", "s...
连接丢失时触发的回调函数. 用于清理一些任务和关闭连接,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置 + 将本连接从当前的连接池中去除 Parameters: exc (Exception): - 异常,如果是None的话说明不是因为异常而关闭的连接
[ "连接丢失时触发的回调函数", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L169-L193
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer.shutdown
def shutdown(self): """关停当前连接. 用于主动关停连接,并清理一些任务,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置 """ self._handlertask.cancel() if self._timeout_handler: self._timeout_handler.cancel() self._transport = None self._st...
python
def shutdown(self): """关停当前连接. 用于主动关停连接,并清理一些任务,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置 """ self._handlertask.cancel() if self._timeout_handler: self._timeout_handler.cancel() self._transport = None self._st...
[ "def", "shutdown", "(", "self", ")", ":", "self", ".", "_handlertask", ".", "cancel", "(", ")", "if", "self", ".", "_timeout_handler", ":", "self", ".", "_timeout_handler", ".", "cancel", "(", ")", "self", ".", "_transport", "=", "None", "self", ".", "...
关停当前连接. 用于主动关停连接,并清理一些任务,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置
[ "关停当前连接", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L195-L217
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer.timeout_callback
def timeout_callback(self): """过期回调函数. 如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调 """ # Check if elapsed time since last response exceeds our configured # maximum keep alive timeout value now = time() time_elapsed = now - self._last_response_time if ti...
python
def timeout_callback(self): """过期回调函数. 如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调 """ # Check if elapsed time since last response exceeds our configured # maximum keep alive timeout value now = time() time_elapsed = now - self._last_response_time if ti...
[ "def", "timeout_callback", "(", "self", ")", ":", "# Check if elapsed time since last response exceeds our configured", "# maximum keep alive timeout value", "now", "=", "time", "(", ")", "time_elapsed", "=", "now", "-", "self", ".", "_last_response_time", "if", "time_elaps...
过期回调函数. 如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调
[ "过期回调函数", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L234-L259
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer.writer
def writer(self, response: Dict[str, Any]): """将响应的python结构转化为字节,并写入到流中,同时刷新最后一次响应时间为当前时间 Parameters: response (Dict[str,Any]): - 要写入给客户端的响应的python结构 """ responseb = self.encoder(response) self._stream_writer.write(responseb) if self.debug: acces...
python
def writer(self, response: Dict[str, Any]): """将响应的python结构转化为字节,并写入到流中,同时刷新最后一次响应时间为当前时间 Parameters: response (Dict[str,Any]): - 要写入给客户端的响应的python结构 """ responseb = self.encoder(response) self._stream_writer.write(responseb) if self.debug: acces...
[ "def", "writer", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "responseb", "=", "self", ".", "encoder", "(", "response", ")", "self", ".", "_stream_writer", ".", "write", "(", "responseb", ")", "if", "self", ".", ...
将响应的python结构转化为字节,并写入到流中,同时刷新最后一次响应时间为当前时间 Parameters: response (Dict[str,Any]): - 要写入给客户端的响应的python结构
[ "将响应的python结构转化为字节", "并写入到流中", "同时刷新最后一次响应时间为当前时间" ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L262-L273
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer.read
async def read(self): """读取请求,并转化为python的字典结构.如果读入了EOF,那么触发回调函数connection_lost.""" try: data = await self._stream_reader.readuntil(self.SEPARATOR) except asyncio.IncompleteReadError: self.connection_lost() else: query = self.decoder(data) i...
python
async def read(self): """读取请求,并转化为python的字典结构.如果读入了EOF,那么触发回调函数connection_lost.""" try: data = await self._stream_reader.readuntil(self.SEPARATOR) except asyncio.IncompleteReadError: self.connection_lost() else: query = self.decoder(data) i...
[ "async", "def", "read", "(", "self", ")", ":", "try", ":", "data", "=", "await", "self", ".", "_stream_reader", ".", "readuntil", "(", "self", ".", "SEPARATOR", ")", "except", "asyncio", ".", "IncompleteReadError", ":", "self", ".", "connection_lost", "(",...
读取请求,并转化为python的字典结构.如果读入了EOF,那么触发回调函数connection_lost.
[ "读取请求", "并转化为python的字典结构", ".", "如果读入了EOF", "那么触发回调函数connection_lost", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L275-L287
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer.query_handler
async def query_handler(self): """根据获取到的不同请求执行不同的动作.会在建立连接后被放入事件循环. 主要为3种请求: + 验证请求 + 心跳请求 + 任务调用请求 如果中途有步骤报错也负责将对应的错误转化为错误信息发送给客户端. """ while True: request = await self.read() if request is None: break ...
python
async def query_handler(self): """根据获取到的不同请求执行不同的动作.会在建立连接后被放入事件循环. 主要为3种请求: + 验证请求 + 心跳请求 + 任务调用请求 如果中途有步骤报错也负责将对应的错误转化为错误信息发送给客户端. """ while True: request = await self.read() if request is None: break ...
[ "async", "def", "query_handler", "(", "self", ")", ":", "while", "True", ":", "request", "=", "await", "self", ".", "read", "(", ")", "if", "request", "is", "None", ":", "break", "ID", "=", "request", ".", "get", "(", "'ID'", ")", "try", ":", "if",...
根据获取到的不同请求执行不同的动作.会在建立连接后被放入事件循环. 主要为3种请求: + 验证请求 + 心跳请求 + 任务调用请求 如果中途有步骤报错也负责将对应的错误转化为错误信息发送给客户端.
[ "根据获取到的不同请求执行不同的动作", ".", "会在建立连接后被放入事件循环", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L291-L355
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer._check_auth_handler
def _check_auth_handler(self, request: Dict[str, Any]): """用于验证客户端是否有权限调服务. 如果服务端有验证信息,则会根据验证信息判断是否合法 + 如果合法,那么返回一条信息用于响应验证请求 + 如果不合法,那么返回验证错误 如果服务端没有验证信息 + 如果验证信息都为空,直接返回响应 + 如果信息不为空,那么返回验证错误 Parameters: request (Dict[str, Any]): - python字典...
python
def _check_auth_handler(self, request: Dict[str, Any]): """用于验证客户端是否有权限调服务. 如果服务端有验证信息,则会根据验证信息判断是否合法 + 如果合法,那么返回一条信息用于响应验证请求 + 如果不合法,那么返回验证错误 如果服务端没有验证信息 + 如果验证信息都为空,直接返回响应 + 如果信息不为空,那么返回验证错误 Parameters: request (Dict[str, Any]): - python字典...
[ "def", "_check_auth_handler", "(", "self", ",", "request", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "a_username", "=", "request", ".", "get", "(", "\"AUTH\"", ")", ".", "get", "(", "\"USERNAME\"", ")", "a_password", "=", "request", ".", "get...
用于验证客户端是否有权限调服务. 如果服务端有验证信息,则会根据验证信息判断是否合法 + 如果合法,那么返回一条信息用于响应验证请求 + 如果不合法,那么返回验证错误 如果服务端没有验证信息 + 如果验证信息都为空,直接返回响应 + 如果信息不为空,那么返回验证错误 Parameters: request (Dict[str, Any]): - python字典形式的请求 Return: (bool): - 请求是否被验证通过,通过了返回True ...
[ "用于验证客户端是否有权限调服务", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L358-L410
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer._RPC_handler
async def _RPC_handler(self, request: Dict[str, Any]): """用于调用函数并执行.同时如果执行出错也负责将错误转化为对应的调用错误返回给客户端. 执行成功后根据结果进行不同的处理,如果注册的是函数,实例中的方法,或者协程,则获取计算得的结果,并返回给客户端. 如果是异步生成器函数,那么返回的就是一个对应的异步生成器,我们通过对其包装后循环调用实现流传输. Parameters: request (Dict[str, Any]): - python字典形式的请求 Raise...
python
async def _RPC_handler(self, request: Dict[str, Any]): """用于调用函数并执行.同时如果执行出错也负责将错误转化为对应的调用错误返回给客户端. 执行成功后根据结果进行不同的处理,如果注册的是函数,实例中的方法,或者协程,则获取计算得的结果,并返回给客户端. 如果是异步生成器函数,那么返回的就是一个对应的异步生成器,我们通过对其包装后循环调用实现流传输. Parameters: request (Dict[str, Any]): - python字典形式的请求 Raise...
[ "async", "def", "_RPC_handler", "(", "self", ",", "request", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "ID", "=", "request", ".", "get", "(", "\"ID\"", ")", "method", "=", "request", ".", "get", "(", "\"METHOD\"", ")", "with_return", "=", ...
用于调用函数并执行.同时如果执行出错也负责将错误转化为对应的调用错误返回给客户端. 执行成功后根据结果进行不同的处理,如果注册的是函数,实例中的方法,或者协程,则获取计算得的结果,并返回给客户端. 如果是异步生成器函数,那么返回的就是一个对应的异步生成器,我们通过对其包装后循环调用实现流传输. Parameters: request (Dict[str, Any]): - python字典形式的请求 Raise: (Exception): - 当执行调用后抛出了异常,且异常不在定义范围内,则抛出 R...
[ "用于调用函数并执行", ".", "同时如果执行出错也负责将错误转化为对应的调用错误返回给客户端", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L413-L497
Basic-Components/msgpack-rpc-protocol
python/pymprpc/server/protocol.py
MPProtocolServer._asyncgen_wrap
async def _asyncgen_wrap(self, cor: AsyncIterator, ID: str): """流包装器. 通过调用异步生成器传输流数据. Parameters: cor (AsyncIterator): - 异步迭代器 ID (str): - 任务的ID Return: (bool): - 当正常调用则返回True """ response = { "MPRPC": self.VERSION, ...
python
async def _asyncgen_wrap(self, cor: AsyncIterator, ID: str): """流包装器. 通过调用异步生成器传输流数据. Parameters: cor (AsyncIterator): - 异步迭代器 ID (str): - 任务的ID Return: (bool): - 当正常调用则返回True """ response = { "MPRPC": self.VERSION, ...
[ "async", "def", "_asyncgen_wrap", "(", "self", ",", "cor", ":", "AsyncIterator", ",", "ID", ":", "str", ")", ":", "response", "=", "{", "\"MPRPC\"", ":", "self", ".", "VERSION", ",", "\"CODE\"", ":", "201", ",", "\"MESSAGE\"", ":", "{", "\"ID\"", ":", ...
流包装器. 通过调用异步生成器传输流数据. Parameters: cor (AsyncIterator): - 异步迭代器 ID (str): - 任务的ID Return: (bool): - 当正常调用则返回True
[ "流包装器", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/server/protocol.py#L499-L553
luismasuelli/python-cantrips
cantrips/types/record.py
TrackableRecord.track_end
def track_end(self): """ Ends tracking of attributes changes. Returns the changes that occurred to the attributes. Only the final state of each attribute is obtained """ self.__tracking = False changes = self.__changes self.__changes = {} return ...
python
def track_end(self): """ Ends tracking of attributes changes. Returns the changes that occurred to the attributes. Only the final state of each attribute is obtained """ self.__tracking = False changes = self.__changes self.__changes = {} return ...
[ "def", "track_end", "(", "self", ")", ":", "self", ".", "__tracking", "=", "False", "changes", "=", "self", ".", "__changes", "self", ".", "__changes", "=", "{", "}", "return", "changes" ]
Ends tracking of attributes changes. Returns the changes that occurred to the attributes. Only the final state of each attribute is obtained
[ "Ends", "tracking", "of", "attributes", "changes", ".", "Returns", "the", "changes", "that", "occurred", "to", "the", "attributes", ".", "Only", "the", "final", "state", "of", "each", "attribute", "is", "obtained" ]
train
https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/types/record.py#L33-L42
lvh/maxims
maxims/creation.py
creationTime
def creationTime(item): """ Returns the creation time of the given item. """ forThisItem = _CreationTime.createdItem == item return item.store.findUnique(_CreationTime, forThisItem).timestamp
python
def creationTime(item): """ Returns the creation time of the given item. """ forThisItem = _CreationTime.createdItem == item return item.store.findUnique(_CreationTime, forThisItem).timestamp
[ "def", "creationTime", "(", "item", ")", ":", "forThisItem", "=", "_CreationTime", ".", "createdItem", "==", "item", "return", "item", ".", "store", ".", "findUnique", "(", "_CreationTime", ",", "forThisItem", ")", ".", "timestamp" ]
Returns the creation time of the given item.
[ "Returns", "the", "creation", "time", "of", "the", "given", "item", "." ]
train
https://github.com/lvh/maxims/blob/5c53b25d2cc4ccecbfe90193ade9ce0dbfbe4623/maxims/creation.py#L21-L26
davehughes/righthook
righthook/views.py
access_key
def access_key(root, key, sep='.', default=None): ''' Look up a key in a potentially nested object `root` by its `sep`-separated path. Returns `default` if the key is not found. Example: access_key({'foo': {'bar': 1}}, 'foo.bar') -> 1 ''' props = key.split('.') props.reverse() w...
python
def access_key(root, key, sep='.', default=None): ''' Look up a key in a potentially nested object `root` by its `sep`-separated path. Returns `default` if the key is not found. Example: access_key({'foo': {'bar': 1}}, 'foo.bar') -> 1 ''' props = key.split('.') props.reverse() w...
[ "def", "access_key", "(", "root", ",", "key", ",", "sep", "=", "'.'", ",", "default", "=", "None", ")", ":", "props", "=", "key", ".", "split", "(", "'.'", ")", "props", ".", "reverse", "(", ")", "while", "props", "and", "root", ":", "prop", "=",...
Look up a key in a potentially nested object `root` by its `sep`-separated path. Returns `default` if the key is not found. Example: access_key({'foo': {'bar': 1}}, 'foo.bar') -> 1
[ "Look", "up", "a", "key", "in", "a", "potentially", "nested", "object", "root", "by", "its", "sep", "-", "separated", "path", ".", "Returns", "default", "if", "the", "key", "is", "not", "found", "." ]
train
https://github.com/davehughes/righthook/blob/d40e8dea0b6ce53b3099af8ed5cb1d4dadda9dba/righthook/views.py#L17-L30
jpablo128/simplystatic
bin/s2.py
setup_parser
def setup_parser(): '''Set up the command-line options.''' p = argparse.ArgumentParser(description='Create and manage a \ SimplyStatic site.') subparsers = p.add_subparsers(help='commands', dest='command') # aliases are not supported in 2.7 for add_parser # init command init_cmd_parser = subpar...
python
def setup_parser(): '''Set up the command-line options.''' p = argparse.ArgumentParser(description='Create and manage a \ SimplyStatic site.') subparsers = p.add_subparsers(help='commands', dest='command') # aliases are not supported in 2.7 for add_parser # init command init_cmd_parser = subpar...
[ "def", "setup_parser", "(", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Create and manage a \\\nSimplyStatic site.'", ")", "subparsers", "=", "p", ".", "add_subparsers", "(", "help", "=", "'commands'", ",", "dest", "=", "'co...
Set up the command-line options.
[ "Set", "up", "the", "command", "-", "line", "options", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L27-L101
jpablo128/simplystatic
bin/s2.py
make_site_obj
def make_site_obj(argdict): '''Instantiate and return the site. This will be used for all commands''' #d = '.' d = None if 'dirname' in argdict: d = argdict['dirname'] try: s = s2site.Site(d) except Exception : # pragma: no cover print "Could not instantiate site object."...
python
def make_site_obj(argdict): '''Instantiate and return the site. This will be used for all commands''' #d = '.' d = None if 'dirname' in argdict: d = argdict['dirname'] try: s = s2site.Site(d) except Exception : # pragma: no cover print "Could not instantiate site object."...
[ "def", "make_site_obj", "(", "argdict", ")", ":", "#d = '.'", "d", "=", "None", "if", "'dirname'", "in", "argdict", ":", "d", "=", "argdict", "[", "'dirname'", "]", "try", ":", "s", "=", "s2site", ".", "Site", "(", "d", ")", "except", "Exception", ":...
Instantiate and return the site. This will be used for all commands
[ "Instantiate", "and", "return", "the", "site", ".", "This", "will", "be", "used", "for", "all", "commands" ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L103-L114
jpablo128/simplystatic
bin/s2.py
dispatch
def dispatch(argdict): '''Call the command-specific function, depending on the command.''' cmd = argdict['command'] ftc = getattr(THIS_MODULE, 'do_'+cmd) ftc(argdict)
python
def dispatch(argdict): '''Call the command-specific function, depending on the command.''' cmd = argdict['command'] ftc = getattr(THIS_MODULE, 'do_'+cmd) ftc(argdict)
[ "def", "dispatch", "(", "argdict", ")", ":", "cmd", "=", "argdict", "[", "'command'", "]", "ftc", "=", "getattr", "(", "THIS_MODULE", ",", "'do_'", "+", "cmd", ")", "ftc", "(", "argdict", ")" ]
Call the command-specific function, depending on the command.
[ "Call", "the", "command", "-", "specific", "function", "depending", "on", "the", "command", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L116-L120
jpablo128/simplystatic
bin/s2.py
do_init
def do_init(argdict): '''Create the structure of a s2site.''' site = make_site_obj(argdict) try: site.init_structure() print "Initialized directory." if argdict['randomsite']: #all_tags = ['tag1','tag2','tag3','tag4'] for i in range(1,argdict['numpages']+1): ...
python
def do_init(argdict): '''Create the structure of a s2site.''' site = make_site_obj(argdict) try: site.init_structure() print "Initialized directory." if argdict['randomsite']: #all_tags = ['tag1','tag2','tag3','tag4'] for i in range(1,argdict['numpages']+1): ...
[ "def", "do_init", "(", "argdict", ")", ":", "site", "=", "make_site_obj", "(", "argdict", ")", "try", ":", "site", ".", "init_structure", "(", ")", "print", "\"Initialized directory.\"", "if", "argdict", "[", "'randomsite'", "]", ":", "#all_tags = ['tag1','tag2'...
Create the structure of a s2site.
[ "Create", "the", "structure", "of", "a", "s2site", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L122-L138
jpablo128/simplystatic
bin/s2.py
do_add
def do_add(argdict): '''Add a new page to the site.''' site = make_site_obj(argdict) if not site.tree_ready: print "Cannot add page. You are not within a simplystatic \ tree and you didn't specify a directory." sys.exit() title = argdict['title'] try: new_page = site.add_pag...
python
def do_add(argdict): '''Add a new page to the site.''' site = make_site_obj(argdict) if not site.tree_ready: print "Cannot add page. You are not within a simplystatic \ tree and you didn't specify a directory." sys.exit() title = argdict['title'] try: new_page = site.add_pag...
[ "def", "do_add", "(", "argdict", ")", ":", "site", "=", "make_site_obj", "(", "argdict", ")", "if", "not", "site", ".", "tree_ready", ":", "print", "\"Cannot add page. You are not within a simplystatic \\\ntree and you didn't specify a directory.\"", "sys", ".", "exit", ...
Add a new page to the site.
[ "Add", "a", "new", "page", "to", "the", "site", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L140-L154
jpablo128/simplystatic
bin/s2.py
do_rename
def do_rename(argdict): '''Rename a page.''' site = make_site_obj(argdict) slug = argdict['slug'] newtitle = argdict['newtitle'] try: site.rename_page(slug, newtitle) print "Renamed page." except ValueError: # pragma: no cover print "Cannot rename. A page with the given s...
python
def do_rename(argdict): '''Rename a page.''' site = make_site_obj(argdict) slug = argdict['slug'] newtitle = argdict['newtitle'] try: site.rename_page(slug, newtitle) print "Renamed page." except ValueError: # pragma: no cover print "Cannot rename. A page with the given s...
[ "def", "do_rename", "(", "argdict", ")", ":", "site", "=", "make_site_obj", "(", "argdict", ")", "slug", "=", "argdict", "[", "'slug'", "]", "newtitle", "=", "argdict", "[", "'newtitle'", "]", "try", ":", "site", ".", "rename_page", "(", "slug", ",", "...
Rename a page.
[ "Rename", "a", "page", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L156-L166
jpablo128/simplystatic
bin/s2.py
do_gen
def do_gen(argdict): '''Generate the whole site.''' site = make_site_obj(argdict) try: st = time.time() site.generate() et = time.time() print "Generated Site in %f seconds."% (et-st) except ValueError as e: # pragma: no cover print "Cannot generate. You are not w...
python
def do_gen(argdict): '''Generate the whole site.''' site = make_site_obj(argdict) try: st = time.time() site.generate() et = time.time() print "Generated Site in %f seconds."% (et-st) except ValueError as e: # pragma: no cover print "Cannot generate. You are not w...
[ "def", "do_gen", "(", "argdict", ")", ":", "site", "=", "make_site_obj", "(", "argdict", ")", "try", ":", "st", "=", "time", ".", "time", "(", ")", "site", ".", "generate", "(", ")", "et", "=", "time", ".", "time", "(", ")", "print", "\"Generated S...
Generate the whole site.
[ "Generate", "the", "whole", "site", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L168-L178
jpablo128/simplystatic
bin/s2.py
do_ls
def do_ls(argdict): '''List pages.''' site = make_site_obj(argdict) if not site.tree_ready: print "Cannot list pages. You are not within a simplystatic \ tree and you didn't specify a directory." sys.exit() drafts = argdict['drafts'] recent = argdict['recent'] dir = site.dirs['so...
python
def do_ls(argdict): '''List pages.''' site = make_site_obj(argdict) if not site.tree_ready: print "Cannot list pages. You are not within a simplystatic \ tree and you didn't specify a directory." sys.exit() drafts = argdict['drafts'] recent = argdict['recent'] dir = site.dirs['so...
[ "def", "do_ls", "(", "argdict", ")", ":", "site", "=", "make_site_obj", "(", "argdict", ")", "if", "not", "site", ".", "tree_ready", ":", "print", "\"Cannot list pages. You are not within a simplystatic \\\ntree and you didn't specify a directory.\"", "sys", ".", "exit", ...
List pages.
[ "List", "pages", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L180-L217
jpablo128/simplystatic
bin/s2.py
do_serve
def do_serve(argdict): '''Serve the site on localhost, for testing/development.''' site = make_site_obj(argdict) os.chdir(site.dirs['www']) HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" server_address = (argdict['ip'], argdict['po...
python
def do_serve(argdict): '''Serve the site on localhost, for testing/development.''' site = make_site_obj(argdict) os.chdir(site.dirs['www']) HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" server_address = (argdict['ip'], argdict['po...
[ "def", "do_serve", "(", "argdict", ")", ":", "site", "=", "make_site_obj", "(", "argdict", ")", "os", ".", "chdir", "(", "site", ".", "dirs", "[", "'www'", "]", ")", "HandlerClass", "=", "SimpleHTTPRequestHandler", "ServerClass", "=", "BaseHTTPServer", ".", ...
Serve the site on localhost, for testing/development.
[ "Serve", "the", "site", "on", "localhost", "for", "testing", "/", "development", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/bin/s2.py#L221-L235