repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.flushIndexes | def flushIndexes(self) :
"drops all indexes created by Raba"
for n in self.getIndexes(rabaOnly = True) :
self.dropIndexByName(n[1]) | python | def flushIndexes(self) :
"drops all indexes created by Raba"
for n in self.getIndexes(rabaOnly = True) :
self.dropIndexByName(n[1]) | [
"def",
"flushIndexes",
"(",
"self",
")",
":",
"for",
"n",
"in",
"self",
".",
"getIndexes",
"(",
"rabaOnly",
"=",
"True",
")",
":",
"self",
".",
"dropIndexByName",
"(",
"n",
"[",
"1",
"]",
")"
] | drops all indexes created by Raba | [
"drops",
"all",
"indexes",
"created",
"by",
"Raba"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L94-L97 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.createIndex | def createIndex(self, table, fields, where = '', whereValues = []) :
"""Creates indexes for Raba Class a fields resulting in significantly faster SELECTs but potentially slower UPADTES/INSERTS and a bigger DBs
Fields can be a list of fields for Multi-Column Indices, or siply the name of one single field.
With the where close you can create a partial index by adding conditions
-----
only for sqlite 3.8.0+
where : optional ex: name = ? AND hair_color = ?
whereValues : optional, ex: ["britney", 'black']
"""
versioTest = sq.sqlite_version_info[0] >= 3 and sq.sqlite_version_info[1] >= 8
if len(where) > 0 and not versioTest :
#raise FutureWarning("Partial joints (with the WHERE clause) where only implemented in sqlite 3.8.0+, your version is: %s. Sorry about that." % sq.sqlite_version)
sys.stderr.write("WARNING: IGNORING THE \"WHERE\" CLAUSE in INDEX. Partial indexes where only implemented in sqlite 3.8.0+, your version is: %s. Sorry about that.\n" % sq.sqlite_version)
indexTable = self.makeIndexTableName(table, fields)
else :
indexTable = self.makeIndexTableName(table, fields, where, whereValues)
if type(fields) is types.ListType :
sql = "CREATE INDEX IF NOT EXISTS %s on %s(%s)" %(indexTable, table, ', '.join(fields))
else :
sql = "CREATE INDEX IF NOT EXISTS %s on %s(%s)" %(indexTable, table, fields)
if len(where) > 0 and versioTest:
sql = "%s WHERE %s;" % (sql, where)
self.execute(sql, whereValues)
else :
self.execute(sql) | python | def createIndex(self, table, fields, where = '', whereValues = []) :
"""Creates indexes for Raba Class a fields resulting in significantly faster SELECTs but potentially slower UPADTES/INSERTS and a bigger DBs
Fields can be a list of fields for Multi-Column Indices, or siply the name of one single field.
With the where close you can create a partial index by adding conditions
-----
only for sqlite 3.8.0+
where : optional ex: name = ? AND hair_color = ?
whereValues : optional, ex: ["britney", 'black']
"""
versioTest = sq.sqlite_version_info[0] >= 3 and sq.sqlite_version_info[1] >= 8
if len(where) > 0 and not versioTest :
#raise FutureWarning("Partial joints (with the WHERE clause) where only implemented in sqlite 3.8.0+, your version is: %s. Sorry about that." % sq.sqlite_version)
sys.stderr.write("WARNING: IGNORING THE \"WHERE\" CLAUSE in INDEX. Partial indexes where only implemented in sqlite 3.8.0+, your version is: %s. Sorry about that.\n" % sq.sqlite_version)
indexTable = self.makeIndexTableName(table, fields)
else :
indexTable = self.makeIndexTableName(table, fields, where, whereValues)
if type(fields) is types.ListType :
sql = "CREATE INDEX IF NOT EXISTS %s on %s(%s)" %(indexTable, table, ', '.join(fields))
else :
sql = "CREATE INDEX IF NOT EXISTS %s on %s(%s)" %(indexTable, table, fields)
if len(where) > 0 and versioTest:
sql = "%s WHERE %s;" % (sql, where)
self.execute(sql, whereValues)
else :
self.execute(sql) | [
"def",
"createIndex",
"(",
"self",
",",
"table",
",",
"fields",
",",
"where",
"=",
"''",
",",
"whereValues",
"=",
"[",
"]",
")",
":",
"versioTest",
"=",
"sq",
".",
"sqlite_version_info",
"[",
"0",
"]",
">=",
"3",
"and",
"sq",
".",
"sqlite_version_info"... | Creates indexes for Raba Class a fields resulting in significantly faster SELECTs but potentially slower UPADTES/INSERTS and a bigger DBs
Fields can be a list of fields for Multi-Column Indices, or siply the name of one single field.
With the where close you can create a partial index by adding conditions
-----
only for sqlite 3.8.0+
where : optional ex: name = ? AND hair_color = ?
whereValues : optional, ex: ["britney", 'black'] | [
"Creates",
"indexes",
"for",
"Raba",
"Class",
"a",
"fields",
"resulting",
"in",
"significantly",
"faster",
"SELECTs",
"but",
"potentially",
"slower",
"UPADTES",
"/",
"INSERTS",
"and",
"a",
"bigger",
"DBs",
"Fields",
"can",
"be",
"a",
"list",
"of",
"fields",
... | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L112-L138 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.dropIndex | def dropIndex(self, table, fields, where = '') :
"DROPs an index created by RabaDb see createIndexes()"
indexTable = self.makeIndexTableName(table, fields, where)
self.dropIndexByName(indexTable) | python | def dropIndex(self, table, fields, where = '') :
"DROPs an index created by RabaDb see createIndexes()"
indexTable = self.makeIndexTableName(table, fields, where)
self.dropIndexByName(indexTable) | [
"def",
"dropIndex",
"(",
"self",
",",
"table",
",",
"fields",
",",
"where",
"=",
"''",
")",
":",
"indexTable",
"=",
"self",
".",
"makeIndexTableName",
"(",
"table",
",",
"fields",
",",
"where",
")",
"self",
".",
"dropIndexByName",
"(",
"indexTable",
")"
... | DROPs an index created by RabaDb see createIndexes() | [
"DROPs",
"an",
"index",
"created",
"by",
"RabaDb",
"see",
"createIndexes",
"()"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L140-L143 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.enableStats | def enableStats(self, bol, logQueries = False) :
"If bol == True, Raba will keep a count of every query time performed, logQueries == True it will also keep a record of all the queries "
self._enableStats = bol
self._logQueries = logQueries
if bol :
self._enableStats = True
self.eraseStats()
self.startTime = time.time() | python | def enableStats(self, bol, logQueries = False) :
"If bol == True, Raba will keep a count of every query time performed, logQueries == True it will also keep a record of all the queries "
self._enableStats = bol
self._logQueries = logQueries
if bol :
self._enableStats = True
self.eraseStats()
self.startTime = time.time() | [
"def",
"enableStats",
"(",
"self",
",",
"bol",
",",
"logQueries",
"=",
"False",
")",
":",
"self",
".",
"_enableStats",
"=",
"bol",
"self",
".",
"_logQueries",
"=",
"logQueries",
"if",
"bol",
":",
"self",
".",
"_enableStats",
"=",
"True",
"self",
".",
"... | If bol == True, Raba will keep a count of every query time performed, logQueries == True it will also keep a record of all the queries | [
"If",
"bol",
"==",
"True",
"Raba",
"will",
"keep",
"a",
"count",
"of",
"every",
"query",
"time",
"performed",
"logQueries",
"==",
"True",
"it",
"will",
"also",
"keep",
"a",
"record",
"of",
"all",
"the",
"queries"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L154-L161 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.execute | def execute(self, sql, values = ()) :
"executes an sql command for you or appends it to the current transacations. returns a cursor"
sql = sql.strip()
self._debugActions(sql, values)
cur = self.connection.cursor()
cur.execute(sql, values)
return cur | python | def execute(self, sql, values = ()) :
"executes an sql command for you or appends it to the current transacations. returns a cursor"
sql = sql.strip()
self._debugActions(sql, values)
cur = self.connection.cursor()
cur.execute(sql, values)
return cur | [
"def",
"execute",
"(",
"self",
",",
"sql",
",",
"values",
"=",
"(",
")",
")",
":",
"sql",
"=",
"sql",
".",
"strip",
"(",
")",
"self",
".",
"_debugActions",
"(",
"sql",
",",
"values",
")",
"cur",
"=",
"self",
".",
"connection",
".",
"cursor",
"(",... | executes an sql command for you or appends it to the current transacations. returns a cursor | [
"executes",
"an",
"sql",
"command",
"for",
"you",
"or",
"appends",
"it",
"to",
"the",
"current",
"transacations",
".",
"returns",
"a",
"cursor"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L219-L225 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.initateSave | def initateSave(self, obj) :
"""Tries to initiates a save sessions. Each object can only be saved once during a session.
The session begins when a raba object initates it and ends when this object and all it's dependencies have been saved"""
if self.saveIniator != None :
return False
self.saveIniator = obj
return True | python | def initateSave(self, obj) :
"""Tries to initiates a save sessions. Each object can only be saved once during a session.
The session begins when a raba object initates it and ends when this object and all it's dependencies have been saved"""
if self.saveIniator != None :
return False
self.saveIniator = obj
return True | [
"def",
"initateSave",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"saveIniator",
"!=",
"None",
":",
"return",
"False",
"self",
".",
"saveIniator",
"=",
"obj",
"return",
"True"
] | Tries to initiates a save sessions. Each object can only be saved once during a session.
The session begins when a raba object initates it and ends when this object and all it's dependencies have been saved | [
"Tries",
"to",
"initiates",
"a",
"save",
"sessions",
".",
"Each",
"object",
"can",
"only",
"be",
"saved",
"once",
"during",
"a",
"session",
".",
"The",
"session",
"begins",
"when",
"a",
"raba",
"object",
"initates",
"it",
"and",
"ends",
"when",
"this",
"... | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L268-L274 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.freeSave | def freeSave(self, obj) :
"""THIS IS WHERE COMMITS TAKE PLACE!
Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session"""
if self.saveIniator is obj and not self.inTransaction :
self.saveIniator = None
self.savedObject = set()
self.connection.commit()
return True
return False | python | def freeSave(self, obj) :
"""THIS IS WHERE COMMITS TAKE PLACE!
Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session"""
if self.saveIniator is obj and not self.inTransaction :
self.saveIniator = None
self.savedObject = set()
self.connection.commit()
return True
return False | [
"def",
"freeSave",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"saveIniator",
"is",
"obj",
"and",
"not",
"self",
".",
"inTransaction",
":",
"self",
".",
"saveIniator",
"=",
"None",
"self",
".",
"savedObject",
"=",
"set",
"(",
")",
"self",
"... | THIS IS WHERE COMMITS TAKE PLACE!
Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session | [
"THIS",
"IS",
"WHERE",
"COMMITS",
"TAKE",
"PLACE!",
"Ends",
"a",
"saving",
"session",
"only",
"the",
"initiator",
"can",
"end",
"a",
"session",
".",
"The",
"commit",
"is",
"performed",
"at",
"the",
"end",
"of",
"the",
"session"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L276-L284 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.registerSave | def registerSave(self, obj) :
"""Each object can only be save donce during a session, returns False if the object has already been saved. True otherwise"""
if obj._runtimeId in self.savedObject :
return False
self.savedObject.add(obj._runtimeId)
return True | python | def registerSave(self, obj) :
"""Each object can only be save donce during a session, returns False if the object has already been saved. True otherwise"""
if obj._runtimeId in self.savedObject :
return False
self.savedObject.add(obj._runtimeId)
return True | [
"def",
"registerSave",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"_runtimeId",
"in",
"self",
".",
"savedObject",
":",
"return",
"False",
"self",
".",
"savedObject",
".",
"add",
"(",
"obj",
".",
"_runtimeId",
")",
"return",
"True"
] | Each object can only be save donce during a session, returns False if the object has already been saved. True otherwise | [
"Each",
"object",
"can",
"only",
"be",
"save",
"donce",
"during",
"a",
"session",
"returns",
"False",
"if",
"the",
"object",
"has",
"already",
"been",
"saved",
".",
"True",
"otherwise"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L286-L292 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.delete | def delete(self, table, where, values = ()) :
"""where is a string of condictions without the sql 'WHERE'. ex: deleteRabaObject('Gene', where = raba_id = ?, values = (33,))"""
sql = 'DELETE FROM %s WHERE %s' % (table, where)
return self.execute(sql, values) | python | def delete(self, table, where, values = ()) :
"""where is a string of condictions without the sql 'WHERE'. ex: deleteRabaObject('Gene', where = raba_id = ?, values = (33,))"""
sql = 'DELETE FROM %s WHERE %s' % (table, where)
return self.execute(sql, values) | [
"def",
"delete",
"(",
"self",
",",
"table",
",",
"where",
",",
"values",
"=",
"(",
")",
")",
":",
"sql",
"=",
"'DELETE FROM %s WHERE %s'",
"%",
"(",
"table",
",",
"where",
")",
"return",
"self",
".",
"execute",
"(",
"sql",
",",
"values",
")"
] | where is a string of condictions without the sql 'WHERE'. ex: deleteRabaObject('Gene', where = raba_id = ?, values = (33,)) | [
"where",
"is",
"a",
"string",
"of",
"condictions",
"without",
"the",
"sql",
"WHERE",
".",
"ex",
":",
"deleteRabaObject",
"(",
"Gene",
"where",
"=",
"raba_id",
"=",
"?",
"values",
"=",
"(",
"33",
"))"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L294-L297 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.getLastRabaId | def getLastRabaId(self, cls) :
"""keep track all loaded raba classes"""
self.loadedRabaClasses[cls.__name__] = cls
sql = 'SELECT MAX(raba_id) from %s LIMIT 1' % (cls.__name__)
cur = self.execute(sql)
res = cur.fetchone()
try :
return int(res[0])+1
except TypeError:
return 0 | python | def getLastRabaId(self, cls) :
"""keep track all loaded raba classes"""
self.loadedRabaClasses[cls.__name__] = cls
sql = 'SELECT MAX(raba_id) from %s LIMIT 1' % (cls.__name__)
cur = self.execute(sql)
res = cur.fetchone()
try :
return int(res[0])+1
except TypeError:
return 0 | [
"def",
"getLastRabaId",
"(",
"self",
",",
"cls",
")",
":",
"self",
".",
"loadedRabaClasses",
"[",
"cls",
".",
"__name__",
"]",
"=",
"cls",
"sql",
"=",
"'SELECT MAX(raba_id) from %s LIMIT 1'",
"%",
"(",
"cls",
".",
"__name__",
")",
"cur",
"=",
"self",
".",
... | keep track all loaded raba classes | [
"keep",
"track",
"all",
"loaded",
"raba",
"classes"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L299-L308 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.createTable | def createTable(self, tableName, strFields) :
'creates a table and resturns the ursor, if the table already exists returns None'
if not self.tableExits(tableName) :
sql = 'CREATE TABLE %s ( %s)' % (tableName, strFields)
self.execute(sql)
self.tables.add(tableName)
return True
return False | python | def createTable(self, tableName, strFields) :
'creates a table and resturns the ursor, if the table already exists returns None'
if not self.tableExits(tableName) :
sql = 'CREATE TABLE %s ( %s)' % (tableName, strFields)
self.execute(sql)
self.tables.add(tableName)
return True
return False | [
"def",
"createTable",
"(",
"self",
",",
"tableName",
",",
"strFields",
")",
":",
"if",
"not",
"self",
".",
"tableExits",
"(",
"tableName",
")",
":",
"sql",
"=",
"'CREATE TABLE %s ( %s)'",
"%",
"(",
"tableName",
",",
"strFields",
")",
"self",
".",
"execute"... | creates a table and resturns the ursor, if the table already exists returns None | [
"creates",
"a",
"table",
"and",
"resturns",
"the",
"ursor",
"if",
"the",
"table",
"already",
"exists",
"returns",
"None"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L339-L346 |
tariqdaouda/rabaDB | rabaDB/rabaSetup.py | RabaConnection.dropColumnsFromRabaObjTable | def dropColumnsFromRabaObjTable(self, name, lstFieldsToKeep) :
"Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds"
if len(lstFieldsToKeep) == 0 :
raise ValueError("There are no fields to keep")
cpy = name+'_copy'
sqlFiledsStr = ', '.join(lstFieldsToKeep)
self.createTable(cpy, 'raba_id INTEGER PRIMARY KEY AUTOINCREMENT, json, %s' % (sqlFiledsStr))
sql = "INSERT INTO %s SELECT %s FROM %s;" % (cpy, 'raba_id, json, %s' % sqlFiledsStr, name)
self.execute(sql)
self.dropTable(name)
self.renameTable(cpy, name) | python | def dropColumnsFromRabaObjTable(self, name, lstFieldsToKeep) :
"Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds"
if len(lstFieldsToKeep) == 0 :
raise ValueError("There are no fields to keep")
cpy = name+'_copy'
sqlFiledsStr = ', '.join(lstFieldsToKeep)
self.createTable(cpy, 'raba_id INTEGER PRIMARY KEY AUTOINCREMENT, json, %s' % (sqlFiledsStr))
sql = "INSERT INTO %s SELECT %s FROM %s;" % (cpy, 'raba_id, json, %s' % sqlFiledsStr, name)
self.execute(sql)
self.dropTable(name)
self.renameTable(cpy, name) | [
"def",
"dropColumnsFromRabaObjTable",
"(",
"self",
",",
"name",
",",
"lstFieldsToKeep",
")",
":",
"if",
"len",
"(",
"lstFieldsToKeep",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"There are no fields to keep\"",
")",
"cpy",
"=",
"name",
"+",
"'_copy'",
... | Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds | [
"Removes",
"columns",
"from",
"a",
"RabaObj",
"table",
".",
"lstFieldsToKeep",
"should",
"not",
"contain",
"raba_id",
"or",
"json",
"fileds"
] | train | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/rabaSetup.py#L355-L366 |
Sliim/soundcloud-syncer | ssyncer/suser.py | suser.get_likes | def get_likes(self, offset=0, limit=50):
""" Get user's likes. """
response = self.client.get(
self.client.USER_LIKES % (self.name, offset, limit))
return self._parse_response(response, strack) | python | def get_likes(self, offset=0, limit=50):
""" Get user's likes. """
response = self.client.get(
self.client.USER_LIKES % (self.name, offset, limit))
return self._parse_response(response, strack) | [
"def",
"get_likes",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"50",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"client",
".",
"USER_LIKES",
"%",
"(",
"self",
".",
"name",
",",
"offset",
",",
"li... | Get user's likes. | [
"Get",
"user",
"s",
"likes",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/suser.py#L38-L42 |
Sliim/soundcloud-syncer | ssyncer/suser.py | suser.get_tracks | def get_tracks(self, offset=0, limit=50):
""" Get user's tracks. """
response = self.client.get(
self.client.USER_TRACKS % (self.name, offset, limit))
return self._parse_response(response, strack) | python | def get_tracks(self, offset=0, limit=50):
""" Get user's tracks. """
response = self.client.get(
self.client.USER_TRACKS % (self.name, offset, limit))
return self._parse_response(response, strack) | [
"def",
"get_tracks",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"50",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"client",
".",
"USER_TRACKS",
"%",
"(",
"self",
".",
"name",
",",
"offset",
",",
"... | Get user's tracks. | [
"Get",
"user",
"s",
"tracks",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/suser.py#L44-L48 |
Sliim/soundcloud-syncer | ssyncer/suser.py | suser.get_playlists | def get_playlists(self, offset=0, limit=50):
""" Get user's playlists. """
response = self.client.get(
self.client.USER_PLAYLISTS % (self.name, offset, limit))
return self._parse_response(response, splaylist)
return playlists | python | def get_playlists(self, offset=0, limit=50):
""" Get user's playlists. """
response = self.client.get(
self.client.USER_PLAYLISTS % (self.name, offset, limit))
return self._parse_response(response, splaylist)
return playlists | [
"def",
"get_playlists",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"50",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"client",
".",
"USER_PLAYLISTS",
"%",
"(",
"self",
".",
"name",
",",
"offset",
",... | Get user's playlists. | [
"Get",
"user",
"s",
"playlists",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/suser.py#L50-L56 |
Sliim/soundcloud-syncer | ssyncer/suser.py | suser._parse_response | def _parse_response(self, response, target_object=strack):
""" Generic response parser method """
objects = json.loads(response.read().decode("utf-8"))
list = []
for obj in objects:
list.append(target_object(obj, client=self.client))
return list | python | def _parse_response(self, response, target_object=strack):
""" Generic response parser method """
objects = json.loads(response.read().decode("utf-8"))
list = []
for obj in objects:
list.append(target_object(obj, client=self.client))
return list | [
"def",
"_parse_response",
"(",
"self",
",",
"response",
",",
"target_object",
"=",
"strack",
")",
":",
"objects",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"list",
"=",
"[",
"]",
"fo... | Generic response parser method | [
"Generic",
"response",
"parser",
"method"
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/suser.py#L58-L64 |
PGower/PyCanvas | pycanvas/apis/announcement_external_feeds.py | AnnouncementExternalFeedsAPI.create_external_feed_courses | def create_external_feed_courses(self, url, course_id, header_match=None, verbosity=None):
"""
Create an external feed.
Create a new external feed for the course or group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - url
"""The url to the external rss or atom feed"""
data["url"] = url
# OPTIONAL - header_match
"""If given, only feed entries that contain this string in their title will be imported"""
if header_match is not None:
data["header_match"] = header_match
# OPTIONAL - verbosity
"""Defaults to "full""""
if verbosity is not None:
self._validate_enum(verbosity, ["full", "truncate", "link_only"])
data["verbosity"] = verbosity
self.logger.debug("POST /api/v1/courses/{course_id}/external_feeds with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/external_feeds".format(**path), data=data, params=params, single_item=True) | python | def create_external_feed_courses(self, url, course_id, header_match=None, verbosity=None):
"""
Create an external feed.
Create a new external feed for the course or group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - url
"""The url to the external rss or atom feed"""
data["url"] = url
# OPTIONAL - header_match
"""If given, only feed entries that contain this string in their title will be imported"""
if header_match is not None:
data["header_match"] = header_match
# OPTIONAL - verbosity
"""Defaults to "full""""
if verbosity is not None:
self._validate_enum(verbosity, ["full", "truncate", "link_only"])
data["verbosity"] = verbosity
self.logger.debug("POST /api/v1/courses/{course_id}/external_feeds with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/external_feeds".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_external_feed_courses",
"(",
"self",
",",
"url",
",",
"course_id",
",",
"header_match",
"=",
"None",
",",
"verbosity",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_... | Create an external feed.
Create a new external feed for the course or group. | [
"Create",
"an",
"external",
"feed",
".",
"Create",
"a",
"new",
"external",
"feed",
"for",
"the",
"course",
"or",
"group",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/announcement_external_feeds.py#L53-L83 |
PGower/PyCanvas | pycanvas/apis/announcement_external_feeds.py | AnnouncementExternalFeedsAPI.create_external_feed_groups | def create_external_feed_groups(self, url, group_id, header_match=None, verbosity=None):
"""
Create an external feed.
Create a new external feed for the course or group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - url
"""The url to the external rss or atom feed"""
data["url"] = url
# OPTIONAL - header_match
"""If given, only feed entries that contain this string in their title will be imported"""
if header_match is not None:
data["header_match"] = header_match
# OPTIONAL - verbosity
"""Defaults to "full""""
if verbosity is not None:
self._validate_enum(verbosity, ["full", "truncate", "link_only"])
data["verbosity"] = verbosity
self.logger.debug("POST /api/v1/groups/{group_id}/external_feeds with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/external_feeds".format(**path), data=data, params=params, single_item=True) | python | def create_external_feed_groups(self, url, group_id, header_match=None, verbosity=None):
"""
Create an external feed.
Create a new external feed for the course or group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - url
"""The url to the external rss or atom feed"""
data["url"] = url
# OPTIONAL - header_match
"""If given, only feed entries that contain this string in their title will be imported"""
if header_match is not None:
data["header_match"] = header_match
# OPTIONAL - verbosity
"""Defaults to "full""""
if verbosity is not None:
self._validate_enum(verbosity, ["full", "truncate", "link_only"])
data["verbosity"] = verbosity
self.logger.debug("POST /api/v1/groups/{group_id}/external_feeds with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/external_feeds".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_external_feed_groups",
"(",
"self",
",",
"url",
",",
"group_id",
",",
"header_match",
"=",
"None",
",",
"verbosity",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\... | Create an external feed.
Create a new external feed for the course or group. | [
"Create",
"an",
"external",
"feed",
".",
"Create",
"a",
"new",
"external",
"feed",
"for",
"the",
"course",
"or",
"group",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/announcement_external_feeds.py#L85-L115 |
PGower/PyCanvas | pycanvas/apis/announcement_external_feeds.py | AnnouncementExternalFeedsAPI.delete_external_feed_courses | def delete_external_feed_courses(self, course_id, external_feed_id):
"""
Delete an external feed.
Deletes the external feed.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - external_feed_id
"""ID"""
path["external_feed_id"] = external_feed_id
self.logger.debug("DELETE /api/v1/courses/{course_id}/external_feeds/{external_feed_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/courses/{course_id}/external_feeds/{external_feed_id}".format(**path), data=data, params=params, single_item=True) | python | def delete_external_feed_courses(self, course_id, external_feed_id):
"""
Delete an external feed.
Deletes the external feed.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - external_feed_id
"""ID"""
path["external_feed_id"] = external_feed_id
self.logger.debug("DELETE /api/v1/courses/{course_id}/external_feeds/{external_feed_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/courses/{course_id}/external_feeds/{external_feed_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"delete_external_feed_courses",
"(",
"self",
",",
"course_id",
",",
"external_feed_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"course_id\"",
"]"... | Delete an external feed.
Deletes the external feed. | [
"Delete",
"an",
"external",
"feed",
".",
"Deletes",
"the",
"external",
"feed",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/announcement_external_feeds.py#L117-L136 |
PGower/PyCanvas | pycanvas/apis/announcement_external_feeds.py | AnnouncementExternalFeedsAPI.delete_external_feed_groups | def delete_external_feed_groups(self, group_id, external_feed_id):
"""
Delete an external feed.
Deletes the external feed.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - external_feed_id
"""ID"""
path["external_feed_id"] = external_feed_id
self.logger.debug("DELETE /api/v1/groups/{group_id}/external_feeds/{external_feed_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/groups/{group_id}/external_feeds/{external_feed_id}".format(**path), data=data, params=params, single_item=True) | python | def delete_external_feed_groups(self, group_id, external_feed_id):
"""
Delete an external feed.
Deletes the external feed.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - external_feed_id
"""ID"""
path["external_feed_id"] = external_feed_id
self.logger.debug("DELETE /api/v1/groups/{group_id}/external_feeds/{external_feed_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/groups/{group_id}/external_feeds/{external_feed_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"delete_external_feed_groups",
"(",
"self",
",",
"group_id",
",",
"external_feed_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
... | Delete an external feed.
Deletes the external feed. | [
"Delete",
"an",
"external",
"feed",
".",
"Deletes",
"the",
"external",
"feed",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/announcement_external_feeds.py#L138-L157 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.count_token_occurrences | def count_token_occurrences(cls, words):
"""
Creates a key/value set of word/count for a given sample of text
:param words: full list of all tokens, non-unique
:type words: list
:return: key/value pairs of words and their counts in the list
:rtype: dict
"""
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts | python | def count_token_occurrences(cls, words):
"""
Creates a key/value set of word/count for a given sample of text
:param words: full list of all tokens, non-unique
:type words: list
:return: key/value pairs of words and their counts in the list
:rtype: dict
"""
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts | [
"def",
"count_token_occurrences",
"(",
"cls",
",",
"words",
")",
":",
"counts",
"=",
"{",
"}",
"for",
"word",
"in",
"words",
":",
"if",
"word",
"in",
"counts",
":",
"counts",
"[",
"word",
"]",
"+=",
"1",
"else",
":",
"counts",
"[",
"word",
"]",
"="... | Creates a key/value set of word/count for a given sample of text
:param words: full list of all tokens, non-unique
:type words: list
:return: key/value pairs of words and their counts in the list
:rtype: dict | [
"Creates",
"a",
"key",
"/",
"value",
"set",
"of",
"word",
"/",
"count",
"for",
"a",
"given",
"sample",
"of",
"text"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L60-L75 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.calculate_category_probability | def calculate_category_probability(self):
"""
Caches the individual probabilities for each category
"""
total_tally = 0.0
probs = {}
for category, bayes_category in \
self.categories.get_categories().items():
count = bayes_category.get_tally()
total_tally += count
probs[category] = count
# Calculating the probability
for category, count in probs.items():
if total_tally > 0:
probs[category] = float(count)/float(total_tally)
else:
probs[category] = 0.0
for category, probability in probs.items():
self.probabilities[category] = {
# Probability that any given token is of this category
'prc': probability,
# Probability that any given token is not of this category
'prnc': sum(probs.values()) - probability
} | python | def calculate_category_probability(self):
"""
Caches the individual probabilities for each category
"""
total_tally = 0.0
probs = {}
for category, bayes_category in \
self.categories.get_categories().items():
count = bayes_category.get_tally()
total_tally += count
probs[category] = count
# Calculating the probability
for category, count in probs.items():
if total_tally > 0:
probs[category] = float(count)/float(total_tally)
else:
probs[category] = 0.0
for category, probability in probs.items():
self.probabilities[category] = {
# Probability that any given token is of this category
'prc': probability,
# Probability that any given token is not of this category
'prnc': sum(probs.values()) - probability
} | [
"def",
"calculate_category_probability",
"(",
"self",
")",
":",
"total_tally",
"=",
"0.0",
"probs",
"=",
"{",
"}",
"for",
"category",
",",
"bayes_category",
"in",
"self",
".",
"categories",
".",
"get_categories",
"(",
")",
".",
"items",
"(",
")",
":",
"cou... | Caches the individual probabilities for each category | [
"Caches",
"the",
"individual",
"probabilities",
"for",
"each",
"category"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L83-L108 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.train | def train(self, category, text):
"""
Trains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to train the category with
:type text: str
"""
try:
bayes_category = self.categories.get_category(category)
except KeyError:
bayes_category = self.categories.add_category(category)
tokens = self.tokenizer(str(text))
occurrence_counts = self.count_token_occurrences(tokens)
for word, count in occurrence_counts.items():
bayes_category.train_token(word, count)
# Updating our per-category overall probabilities
self.calculate_category_probability() | python | def train(self, category, text):
"""
Trains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to train the category with
:type text: str
"""
try:
bayes_category = self.categories.get_category(category)
except KeyError:
bayes_category = self.categories.add_category(category)
tokens = self.tokenizer(str(text))
occurrence_counts = self.count_token_occurrences(tokens)
for word, count in occurrence_counts.items():
bayes_category.train_token(word, count)
# Updating our per-category overall probabilities
self.calculate_category_probability() | [
"def",
"train",
"(",
"self",
",",
"category",
",",
"text",
")",
":",
"try",
":",
"bayes_category",
"=",
"self",
".",
"categories",
".",
"get_category",
"(",
"category",
")",
"except",
"KeyError",
":",
"bayes_category",
"=",
"self",
".",
"categories",
".",
... | Trains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to train the category with
:type text: str | [
"Trains",
"a",
"category",
"with",
"a",
"sample",
"of",
"text"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L110-L131 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.untrain | def untrain(self, category, text):
"""
Untrains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to untrain the category with
:type text: str
"""
try:
bayes_category = self.categories.get_category(category)
except KeyError:
return
tokens = self.tokenizer(str(text))
occurance_counts = self.count_token_occurrences(tokens)
for word, count in occurance_counts.items():
bayes_category.untrain_token(word, count)
# Updating our per-category overall probabilities
self.calculate_category_probability() | python | def untrain(self, category, text):
"""
Untrains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to untrain the category with
:type text: str
"""
try:
bayes_category = self.categories.get_category(category)
except KeyError:
return
tokens = self.tokenizer(str(text))
occurance_counts = self.count_token_occurrences(tokens)
for word, count in occurance_counts.items():
bayes_category.untrain_token(word, count)
# Updating our per-category overall probabilities
self.calculate_category_probability() | [
"def",
"untrain",
"(",
"self",
",",
"category",
",",
"text",
")",
":",
"try",
":",
"bayes_category",
"=",
"self",
".",
"categories",
".",
"get_category",
"(",
"category",
")",
"except",
"KeyError",
":",
"return",
"tokens",
"=",
"self",
".",
"tokenizer",
... | Untrains a category with a sample of text
:param category: the name of the category we want to train
:type category: str
:param text: the text we want to untrain the category with
:type text: str | [
"Untrains",
"a",
"category",
"with",
"a",
"sample",
"of",
"text"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L133-L154 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.classify | def classify(self, text):
"""
Chooses the highest scoring category for a sample of text
:param text: sample text to classify
:type text: str
:return: the "winning" category
:rtype: str
"""
score = self.score(text)
if not score:
return None
return sorted(score.items(), key=lambda v: v[1])[-1][0] | python | def classify(self, text):
"""
Chooses the highest scoring category for a sample of text
:param text: sample text to classify
:type text: str
:return: the "winning" category
:rtype: str
"""
score = self.score(text)
if not score:
return None
return sorted(score.items(), key=lambda v: v[1])[-1][0] | [
"def",
"classify",
"(",
"self",
",",
"text",
")",
":",
"score",
"=",
"self",
".",
"score",
"(",
"text",
")",
"if",
"not",
"score",
":",
"return",
"None",
"return",
"sorted",
"(",
"score",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"v",
":... | Chooses the highest scoring category for a sample of text
:param text: sample text to classify
:type text: str
:return: the "winning" category
:rtype: str | [
"Chooses",
"the",
"highest",
"scoring",
"category",
"for",
"a",
"sample",
"of",
"text"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L156-L168 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.score | def score(self, text):
"""
Scores a sample of text
:param text: sample text to score
:type text: str
:return: dict of scores per category
:rtype: dict
"""
occurs = self.count_token_occurrences(self.tokenizer(text))
scores = {}
for category in self.categories.get_categories().keys():
scores[category] = 0
categories = self.categories.get_categories().items()
for word, count in occurs.items():
token_scores = {}
# Adding up individual token scores
for category, bayes_category in categories:
token_scores[category] = \
float(bayes_category.get_token_count(word))
# We use this to get token-in-category probabilities
token_tally = sum(token_scores.values())
# If this token isn't found anywhere its probability is 0
if token_tally == 0.0:
continue
# Calculating bayes probabiltity for this token
# http://en.wikipedia.org/wiki/Naive_Bayes_spam_filtering
for category, token_score in token_scores.items():
# Bayes probability * the number of occurances of this token
scores[category] += count * \
self.calculate_bayesian_probability(
category,
token_score,
token_tally
)
# Removing empty categories from the results
final_scores = {}
for category, score in scores.items():
if score > 0:
final_scores[category] = score
return final_scores | python | def score(self, text):
"""
Scores a sample of text
:param text: sample text to score
:type text: str
:return: dict of scores per category
:rtype: dict
"""
occurs = self.count_token_occurrences(self.tokenizer(text))
scores = {}
for category in self.categories.get_categories().keys():
scores[category] = 0
categories = self.categories.get_categories().items()
for word, count in occurs.items():
token_scores = {}
# Adding up individual token scores
for category, bayes_category in categories:
token_scores[category] = \
float(bayes_category.get_token_count(word))
# We use this to get token-in-category probabilities
token_tally = sum(token_scores.values())
# If this token isn't found anywhere its probability is 0
if token_tally == 0.0:
continue
# Calculating bayes probabiltity for this token
# http://en.wikipedia.org/wiki/Naive_Bayes_spam_filtering
for category, token_score in token_scores.items():
# Bayes probability * the number of occurances of this token
scores[category] += count * \
self.calculate_bayesian_probability(
category,
token_score,
token_tally
)
# Removing empty categories from the results
final_scores = {}
for category, score in scores.items():
if score > 0:
final_scores[category] = score
return final_scores | [
"def",
"score",
"(",
"self",
",",
"text",
")",
":",
"occurs",
"=",
"self",
".",
"count_token_occurrences",
"(",
"self",
".",
"tokenizer",
"(",
"text",
")",
")",
"scores",
"=",
"{",
"}",
"for",
"category",
"in",
"self",
".",
"categories",
".",
"get_cate... | Scores a sample of text
:param text: sample text to score
:type text: str
:return: dict of scores per category
:rtype: dict | [
"Scores",
"a",
"sample",
"of",
"text"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L170-L218 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.calculate_bayesian_probability | def calculate_bayesian_probability(self, cat, token_score, token_tally):
"""
Calculates the bayesian probability for a given token/category
:param cat: The category we're scoring for this token
:type cat: str
:param token_score: The tally of this token for this category
:type token_score: float
:param token_tally: The tally total for this token from all categories
:type token_tally: float
:return: bayesian probability
:rtype: float
"""
# P that any given token IS in this category
prc = self.probabilities[cat]['prc']
# P that any given token is NOT in this category
prnc = self.probabilities[cat]['prnc']
# P that this token is NOT of this category
prtnc = (token_tally - token_score) / token_tally
# P that this token IS of this category
prtc = token_score / token_tally
# Assembling the parts of the bayes equation
numerator = (prtc * prc)
denominator = (numerator + (prtnc * prnc))
# Returning the calculated bayes probability unless the denom. is 0
return numerator / denominator if denominator != 0.0 else 0.0 | python | def calculate_bayesian_probability(self, cat, token_score, token_tally):
"""
Calculates the bayesian probability for a given token/category
:param cat: The category we're scoring for this token
:type cat: str
:param token_score: The tally of this token for this category
:type token_score: float
:param token_tally: The tally total for this token from all categories
:type token_tally: float
:return: bayesian probability
:rtype: float
"""
# P that any given token IS in this category
prc = self.probabilities[cat]['prc']
# P that any given token is NOT in this category
prnc = self.probabilities[cat]['prnc']
# P that this token is NOT of this category
prtnc = (token_tally - token_score) / token_tally
# P that this token IS of this category
prtc = token_score / token_tally
# Assembling the parts of the bayes equation
numerator = (prtc * prc)
denominator = (numerator + (prtnc * prnc))
# Returning the calculated bayes probability unless the denom. is 0
return numerator / denominator if denominator != 0.0 else 0.0 | [
"def",
"calculate_bayesian_probability",
"(",
"self",
",",
"cat",
",",
"token_score",
",",
"token_tally",
")",
":",
"# P that any given token IS in this category",
"prc",
"=",
"self",
".",
"probabilities",
"[",
"cat",
"]",
"[",
"'prc'",
"]",
"# P that any given token ... | Calculates the bayesian probability for a given token/category
:param cat: The category we're scoring for this token
:type cat: str
:param token_score: The tally of this token for this category
:type token_score: float
:param token_tally: The tally total for this token from all categories
:type token_tally: float
:return: bayesian probability
:rtype: float | [
"Calculates",
"the",
"bayesian",
"probability",
"for",
"a",
"given",
"token",
"/",
"category"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L220-L247 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.tally | def tally(self, category):
"""
Gets the tally for a requested category
:param category: The category we want a tally for
:type category: str
:return: tally for a given category
:rtype: int
"""
try:
bayes_category = self.categories.get_category(category)
except KeyError:
return 0
return bayes_category.get_tally() | python | def tally(self, category):
"""
Gets the tally for a requested category
:param category: The category we want a tally for
:type category: str
:return: tally for a given category
:rtype: int
"""
try:
bayes_category = self.categories.get_category(category)
except KeyError:
return 0
return bayes_category.get_tally() | [
"def",
"tally",
"(",
"self",
",",
"category",
")",
":",
"try",
":",
"bayes_category",
"=",
"self",
".",
"categories",
".",
"get_category",
"(",
"category",
")",
"except",
"KeyError",
":",
"return",
"0",
"return",
"bayes_category",
".",
"get_tally",
"(",
")... | Gets the tally for a requested category
:param category: The category we want a tally for
:type category: str
:return: tally for a given category
:rtype: int | [
"Gets",
"the",
"tally",
"for",
"a",
"requested",
"category"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L249-L263 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.get_cache_location | def get_cache_location(self):
"""
Gets the location of the cache file
:return: the location of the cache file
:rtype: string
"""
filename = self.cache_path if \
self.cache_path[-1:] == '/' else \
self.cache_path + '/'
filename += self.cache_file
return filename | python | def get_cache_location(self):
"""
Gets the location of the cache file
:return: the location of the cache file
:rtype: string
"""
filename = self.cache_path if \
self.cache_path[-1:] == '/' else \
self.cache_path + '/'
filename += self.cache_file
return filename | [
"def",
"get_cache_location",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"cache_path",
"if",
"self",
".",
"cache_path",
"[",
"-",
"1",
":",
"]",
"==",
"'/'",
"else",
"self",
".",
"cache_path",
"+",
"'/'",
"filename",
"+=",
"self",
".",
"cache_... | Gets the location of the cache file
:return: the location of the cache file
:rtype: string | [
"Gets",
"the",
"location",
"of",
"the",
"cache",
"file"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L265-L276 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.cache_persist | def cache_persist(self):
"""
Saves the current trained data to the cache.
This is initiated by the program using this module
"""
filename = self.get_cache_location()
pickle.dump(self.categories, open(filename, 'wb')) | python | def cache_persist(self):
"""
Saves the current trained data to the cache.
This is initiated by the program using this module
"""
filename = self.get_cache_location()
pickle.dump(self.categories, open(filename, 'wb')) | [
"def",
"cache_persist",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"get_cache_location",
"(",
")",
"pickle",
".",
"dump",
"(",
"self",
".",
"categories",
",",
"open",
"(",
"filename",
",",
"'wb'",
")",
")"
] | Saves the current trained data to the cache.
This is initiated by the program using this module | [
"Saves",
"the",
"current",
"trained",
"data",
"to",
"the",
"cache",
".",
"This",
"is",
"initiated",
"by",
"the",
"program",
"using",
"this",
"module"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L278-L284 |
hickeroar/simplebayes | simplebayes/__init__.py | SimpleBayes.cache_train | def cache_train(self):
"""
Loads the data for this classifier from a cache file
:return: whether or not we were successful
:rtype: bool
"""
filename = self.get_cache_location()
if not os.path.exists(filename):
return False
categories = pickle.load(open(filename, 'rb'))
assert isinstance(categories, BayesCategories), \
"Cache data is either corrupt or invalid"
self.categories = categories
# Updating our per-category overall probabilities
self.calculate_category_probability()
return True | python | def cache_train(self):
"""
Loads the data for this classifier from a cache file
:return: whether or not we were successful
:rtype: bool
"""
filename = self.get_cache_location()
if not os.path.exists(filename):
return False
categories = pickle.load(open(filename, 'rb'))
assert isinstance(categories, BayesCategories), \
"Cache data is either corrupt or invalid"
self.categories = categories
# Updating our per-category overall probabilities
self.calculate_category_probability()
return True | [
"def",
"cache_train",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"get_cache_location",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"False",
"categories",
"=",
"pickle",
".",
"load",
"(",
"open... | Loads the data for this classifier from a cache file
:return: whether or not we were successful
:rtype: bool | [
"Loads",
"the",
"data",
"for",
"this",
"classifier",
"from",
"a",
"cache",
"file"
] | train | https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/__init__.py#L286-L308 |
theonion/django-bulbs | bulbs/contributions/models.py | ContributorRole.create_feature_type_rates | def create_feature_type_rates(self, created=False):
"""
If the role is being created we want to populate a rate for all existing feature_types.
"""
if created:
for feature_type in FeatureType.objects.all():
FeatureTypeRate.objects.create(role=self, feature_type=feature_type, rate=0) | python | def create_feature_type_rates(self, created=False):
"""
If the role is being created we want to populate a rate for all existing feature_types.
"""
if created:
for feature_type in FeatureType.objects.all():
FeatureTypeRate.objects.create(role=self, feature_type=feature_type, rate=0) | [
"def",
"create_feature_type_rates",
"(",
"self",
",",
"created",
"=",
"False",
")",
":",
"if",
"created",
":",
"for",
"feature_type",
"in",
"FeatureType",
".",
"objects",
".",
"all",
"(",
")",
":",
"FeatureTypeRate",
".",
"objects",
".",
"create",
"(",
"ro... | If the role is being created we want to populate a rate for all existing feature_types. | [
"If",
"the",
"role",
"is",
"being",
"created",
"we",
"want",
"to",
"populate",
"a",
"rate",
"for",
"all",
"existing",
"feature_types",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/models.py#L172-L178 |
flowroute/txjason | txjason/handler.py | Handler.addToService | def addToService(self, service, namespace=None, seperator='.'):
"""
Add this Handler's exported methods to an RPC Service instance.
"""
if namespace is None:
namespace = []
if isinstance(namespace, basestring):
namespace = [namespace]
for n, m in inspect.getmembers(self, inspect.ismethod):
if hasattr(m, 'export_rpc'):
try:
name = seperator.join(namespace + m.export_rpc)
except TypeError:
name = seperator.join(namespace + [m.export_rpc])
service.add(m, name) | python | def addToService(self, service, namespace=None, seperator='.'):
"""
Add this Handler's exported methods to an RPC Service instance.
"""
if namespace is None:
namespace = []
if isinstance(namespace, basestring):
namespace = [namespace]
for n, m in inspect.getmembers(self, inspect.ismethod):
if hasattr(m, 'export_rpc'):
try:
name = seperator.join(namespace + m.export_rpc)
except TypeError:
name = seperator.join(namespace + [m.export_rpc])
service.add(m, name) | [
"def",
"addToService",
"(",
"self",
",",
"service",
",",
"namespace",
"=",
"None",
",",
"seperator",
"=",
"'.'",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"namespace",
",",
"basestring",
")",
"... | Add this Handler's exported methods to an RPC Service instance. | [
"Add",
"this",
"Handler",
"s",
"exported",
"methods",
"to",
"an",
"RPC",
"Service",
"instance",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/handler.py#L44-L59 |
bast/flanders | cmake/update.py | print_progress_bar | def print_progress_bar(text, done, total, width):
"""
Print progress bar.
"""
if total > 0:
n = int(float(width) * float(done) / float(total))
sys.stdout.write("\r{0} [{1}{2}] ({3}/{4})".format(text, '#' * n, ' ' * (width - n), done, total))
sys.stdout.flush() | python | def print_progress_bar(text, done, total, width):
"""
Print progress bar.
"""
if total > 0:
n = int(float(width) * float(done) / float(total))
sys.stdout.write("\r{0} [{1}{2}] ({3}/{4})".format(text, '#' * n, ' ' * (width - n), done, total))
sys.stdout.flush() | [
"def",
"print_progress_bar",
"(",
"text",
",",
"done",
",",
"total",
",",
"width",
")",
":",
"if",
"total",
">",
"0",
":",
"n",
"=",
"int",
"(",
"float",
"(",
"width",
")",
"*",
"float",
"(",
"done",
")",
"/",
"float",
"(",
"total",
")",
")",
"... | Print progress bar. | [
"Print",
"progress",
"bar",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/update.py#L33-L40 |
bast/flanders | cmake/update.py | fetch_modules | def fetch_modules(config, relative_path, download_directory):
"""
Assemble modules which will
be included in CMakeLists.txt.
"""
from collections import Iterable, namedtuple, defaultdict
from autocmake.extract import extract_list, to_d, to_l
from autocmake.parse_rst import parse_cmake_module
cleaned_config = defaultdict(lambda: [])
modules = []
Module = namedtuple('Module', 'path name')
num_sources = len(extract_list(config, 'source'))
print_progress_bar(text='- assembling modules:',
done=0,
total=num_sources,
width=30)
if 'modules' in config:
i = 0
for t in config['modules']:
for k, v in t.items():
d = to_d(v)
for _k, _v in to_d(v).items():
cleaned_config[_k] = flat_add(cleaned_config[_k], _v)
# fetch sources and parse them
if 'source' in d:
for src in to_l(d['source']):
i += 1
# we download the file
module_name = os.path.basename(src)
if 'http' in src:
path = download_directory
name = 'autocmake_{0}'.format(module_name)
dst = os.path.join(download_directory, 'autocmake_{0}'.format(module_name))
fetch_url(src, dst)
file_name = dst
fetch_dst_directory = download_directory
else:
if os.path.exists(src):
path = os.path.dirname(src)
name = module_name
file_name = src
fetch_dst_directory = path
else:
sys.stderr.write("ERROR: {0} does not exist\n".format(src))
sys.exit(-1)
# we infer config from the module documentation
# dictionary d overrides the configuration in the module documentation
# this allows to override interpolation inside the module
with open(file_name, 'r') as f:
parsed_config = parse_cmake_module(f.read(), d)
for _k2, _v2 in parsed_config.items():
if _k2 not in to_d(v):
# we add to clean_config only if the entry does not exist
# in parent autocmake.yml already
# this allows to override
cleaned_config[_k2] = flat_add(cleaned_config[_k2], _v2)
modules.append(Module(path=path, name=name))
print_progress_bar(text='- assembling modules:',
done=i,
total=num_sources,
width=30)
print('')
return modules, cleaned_config | python | def fetch_modules(config, relative_path, download_directory):
"""
Assemble modules which will
be included in CMakeLists.txt.
"""
from collections import Iterable, namedtuple, defaultdict
from autocmake.extract import extract_list, to_d, to_l
from autocmake.parse_rst import parse_cmake_module
cleaned_config = defaultdict(lambda: [])
modules = []
Module = namedtuple('Module', 'path name')
num_sources = len(extract_list(config, 'source'))
print_progress_bar(text='- assembling modules:',
done=0,
total=num_sources,
width=30)
if 'modules' in config:
i = 0
for t in config['modules']:
for k, v in t.items():
d = to_d(v)
for _k, _v in to_d(v).items():
cleaned_config[_k] = flat_add(cleaned_config[_k], _v)
# fetch sources and parse them
if 'source' in d:
for src in to_l(d['source']):
i += 1
# we download the file
module_name = os.path.basename(src)
if 'http' in src:
path = download_directory
name = 'autocmake_{0}'.format(module_name)
dst = os.path.join(download_directory, 'autocmake_{0}'.format(module_name))
fetch_url(src, dst)
file_name = dst
fetch_dst_directory = download_directory
else:
if os.path.exists(src):
path = os.path.dirname(src)
name = module_name
file_name = src
fetch_dst_directory = path
else:
sys.stderr.write("ERROR: {0} does not exist\n".format(src))
sys.exit(-1)
# we infer config from the module documentation
# dictionary d overrides the configuration in the module documentation
# this allows to override interpolation inside the module
with open(file_name, 'r') as f:
parsed_config = parse_cmake_module(f.read(), d)
for _k2, _v2 in parsed_config.items():
if _k2 not in to_d(v):
# we add to clean_config only if the entry does not exist
# in parent autocmake.yml already
# this allows to override
cleaned_config[_k2] = flat_add(cleaned_config[_k2], _v2)
modules.append(Module(path=path, name=name))
print_progress_bar(text='- assembling modules:',
done=i,
total=num_sources,
width=30)
print('')
return modules, cleaned_config | [
"def",
"fetch_modules",
"(",
"config",
",",
"relative_path",
",",
"download_directory",
")",
":",
"from",
"collections",
"import",
"Iterable",
",",
"namedtuple",
",",
"defaultdict",
"from",
"autocmake",
".",
"extract",
"import",
"extract_list",
",",
"to_d",
",",
... | Assemble modules which will
be included in CMakeLists.txt. | [
"Assemble",
"modules",
"which",
"will",
"be",
"included",
"in",
"CMakeLists",
".",
"txt",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/update.py#L54-L127 |
bast/flanders | cmake/update.py | main | def main(argv):
"""
Main function.
"""
if len(argv) != 2:
sys.stderr.write("\nYou can update a project in two steps.\n\n")
sys.stderr.write("Step 1: Update or create infrastructure files\n")
sys.stderr.write(" which will be needed to configure and build the project:\n")
sys.stderr.write(" $ {0} --self\n\n".format(argv[0]))
sys.stderr.write("Step 2: Create CMakeLists.txt and setup script in PROJECT_ROOT:\n")
sys.stderr.write(" $ {0} <PROJECT_ROOT>\n".format(argv[0]))
sys.stderr.write(" example:\n")
sys.stderr.write(" $ {0} ..\n".format(argv[0]))
sys.exit(-1)
if argv[1] in ['-h', '--help']:
print('Usage:')
for t, h in [('python update.py --self',
'Update this script and fetch or update infrastructure files under autocmake/.'),
('python update.py <builddir>',
'(Re)generate CMakeLists.txt and setup script and fetch or update CMake modules.'),
('python update.py (-h | --help)',
'Show this help text.')]:
print(' {0:30} {1}'.format(t, h))
sys.exit(0)
if argv[1] == '--self':
# update self
if not os.path.isfile('autocmake.yml'):
print('- fetching example autocmake.yml')
fetch_url(
src='{0}example/autocmake.yml'.format(AUTOCMAKE_GITHUB_URL),
dst='autocmake.yml'
)
if not os.path.isfile('.gitignore'):
print('- creating .gitignore')
with open('.gitignore', 'w') as f:
f.write('*.pyc\n')
for f in ['autocmake/configure.py',
'autocmake/__init__.py',
'autocmake/external/docopt.py',
'autocmake/external/__init__.py',
'autocmake/generate.py',
'autocmake/extract.py',
'autocmake/interpolate.py',
'autocmake/parse_rst.py',
'autocmake/parse_yaml.py',
'update.py']:
print('- fetching {0}'.format(f))
fetch_url(
src='{0}{1}'.format(AUTOCMAKE_GITHUB_URL, f),
dst='{0}'.format(f)
)
# finally create a README.md with licensing information
with open('README.md', 'w') as f:
print('- generating licensing information')
f.write(licensing_info())
sys.exit(0)
process_yaml(argv) | python | def main(argv):
"""
Main function.
"""
if len(argv) != 2:
sys.stderr.write("\nYou can update a project in two steps.\n\n")
sys.stderr.write("Step 1: Update or create infrastructure files\n")
sys.stderr.write(" which will be needed to configure and build the project:\n")
sys.stderr.write(" $ {0} --self\n\n".format(argv[0]))
sys.stderr.write("Step 2: Create CMakeLists.txt and setup script in PROJECT_ROOT:\n")
sys.stderr.write(" $ {0} <PROJECT_ROOT>\n".format(argv[0]))
sys.stderr.write(" example:\n")
sys.stderr.write(" $ {0} ..\n".format(argv[0]))
sys.exit(-1)
if argv[1] in ['-h', '--help']:
print('Usage:')
for t, h in [('python update.py --self',
'Update this script and fetch or update infrastructure files under autocmake/.'),
('python update.py <builddir>',
'(Re)generate CMakeLists.txt and setup script and fetch or update CMake modules.'),
('python update.py (-h | --help)',
'Show this help text.')]:
print(' {0:30} {1}'.format(t, h))
sys.exit(0)
if argv[1] == '--self':
# update self
if not os.path.isfile('autocmake.yml'):
print('- fetching example autocmake.yml')
fetch_url(
src='{0}example/autocmake.yml'.format(AUTOCMAKE_GITHUB_URL),
dst='autocmake.yml'
)
if not os.path.isfile('.gitignore'):
print('- creating .gitignore')
with open('.gitignore', 'w') as f:
f.write('*.pyc\n')
for f in ['autocmake/configure.py',
'autocmake/__init__.py',
'autocmake/external/docopt.py',
'autocmake/external/__init__.py',
'autocmake/generate.py',
'autocmake/extract.py',
'autocmake/interpolate.py',
'autocmake/parse_rst.py',
'autocmake/parse_yaml.py',
'update.py']:
print('- fetching {0}'.format(f))
fetch_url(
src='{0}{1}'.format(AUTOCMAKE_GITHUB_URL, f),
dst='{0}'.format(f)
)
# finally create a README.md with licensing information
with open('README.md', 'w') as f:
print('- generating licensing information')
f.write(licensing_info())
sys.exit(0)
process_yaml(argv) | [
"def",
"main",
"(",
"argv",
")",
":",
"if",
"len",
"(",
"argv",
")",
"!=",
"2",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\nYou can update a project in two steps.\\n\\n\"",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Step 1: Update or create infra... | Main function. | [
"Main",
"function",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/update.py#L216-L276 |
bast/flanders | cmake/update.py | fetch_url | def fetch_url(src, dst):
"""
Fetch file from URL src and save it to dst.
"""
# we do not use the nicer sys.version_info.major
# for compatibility with Python < 2.7
if sys.version_info[0] > 2:
import urllib.request
class URLopener(urllib.request.FancyURLopener):
def http_error_default(self, url, fp, errcode, errmsg, headers):
sys.stderr.write("ERROR: could not fetch {0}\n".format(url))
sys.exit(-1)
else:
import urllib
class URLopener(urllib.FancyURLopener):
def http_error_default(self, url, fp, errcode, errmsg, headers):
sys.stderr.write("ERROR: could not fetch {0}\n".format(url))
sys.exit(-1)
dirname = os.path.dirname(dst)
if dirname != '':
if not os.path.isdir(dirname):
os.makedirs(dirname)
opener = URLopener()
opener.retrieve(src, dst) | python | def fetch_url(src, dst):
"""
Fetch file from URL src and save it to dst.
"""
# we do not use the nicer sys.version_info.major
# for compatibility with Python < 2.7
if sys.version_info[0] > 2:
import urllib.request
class URLopener(urllib.request.FancyURLopener):
def http_error_default(self, url, fp, errcode, errmsg, headers):
sys.stderr.write("ERROR: could not fetch {0}\n".format(url))
sys.exit(-1)
else:
import urllib
class URLopener(urllib.FancyURLopener):
def http_error_default(self, url, fp, errcode, errmsg, headers):
sys.stderr.write("ERROR: could not fetch {0}\n".format(url))
sys.exit(-1)
dirname = os.path.dirname(dst)
if dirname != '':
if not os.path.isdir(dirname):
os.makedirs(dirname)
opener = URLopener()
opener.retrieve(src, dst) | [
"def",
"fetch_url",
"(",
"src",
",",
"dst",
")",
":",
"# we do not use the nicer sys.version_info.major",
"# for compatibility with Python < 2.7",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
":",
"import",
"urllib",
".",
"request",
"class",
"URLopener... | Fetch file from URL src and save it to dst. | [
"Fetch",
"file",
"from",
"URL",
"src",
"and",
"save",
"it",
"to",
"dst",
"."
] | train | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/update.py#L286-L313 |
PGower/PyCanvas | pycanvas/apis/poll_submissions.py | PollSubmissionsAPI.get_single_poll_submission | def get_single_poll_submission(self, id, poll_id, poll_session_id):
"""
Get a single poll submission.
Returns the poll submission with the given id
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - poll_id
"""ID"""
path["poll_id"] = poll_id
# REQUIRED - PATH - poll_session_id
"""ID"""
path["poll_session_id"] = poll_session_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
self.logger.debug("GET /api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions/{id}".format(**path), data=data, params=params, no_data=True) | python | def get_single_poll_submission(self, id, poll_id, poll_session_id):
"""
Get a single poll submission.
Returns the poll submission with the given id
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - poll_id
"""ID"""
path["poll_id"] = poll_id
# REQUIRED - PATH - poll_session_id
"""ID"""
path["poll_session_id"] = poll_session_id
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
self.logger.debug("GET /api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions/{id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"get_single_poll_submission",
"(",
"self",
",",
"id",
",",
"poll_id",
",",
"poll_session_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - poll_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"poll_id\"",... | Get a single poll submission.
Returns the poll submission with the given id | [
"Get",
"a",
"single",
"poll",
"submission",
".",
"Returns",
"the",
"poll",
"submission",
"with",
"the",
"given",
"id"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/poll_submissions.py#L19-L42 |
PGower/PyCanvas | pycanvas/apis/poll_submissions.py | PollSubmissionsAPI.create_single_poll_submission | def create_single_poll_submission(self, poll_id, poll_session_id, poll_submissions_poll_choice_id):
"""
Create a single poll submission.
Create a new poll submission for this poll session
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - poll_id
"""ID"""
path["poll_id"] = poll_id
# REQUIRED - PATH - poll_session_id
"""ID"""
path["poll_session_id"] = poll_session_id
# REQUIRED - poll_submissions[poll_choice_id]
"""The chosen poll choice for this submission."""
data["poll_submissions[poll_choice_id]"] = poll_submissions_poll_choice_id
self.logger.debug("POST /api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions".format(**path), data=data, params=params, no_data=True) | python | def create_single_poll_submission(self, poll_id, poll_session_id, poll_submissions_poll_choice_id):
"""
Create a single poll submission.
Create a new poll submission for this poll session
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - poll_id
"""ID"""
path["poll_id"] = poll_id
# REQUIRED - PATH - poll_session_id
"""ID"""
path["poll_session_id"] = poll_session_id
# REQUIRED - poll_submissions[poll_choice_id]
"""The chosen poll choice for this submission."""
data["poll_submissions[poll_choice_id]"] = poll_submissions_poll_choice_id
self.logger.debug("POST /api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/polls/{poll_id}/poll_sessions/{poll_session_id}/poll_submissions".format(**path), data=data, params=params, no_data=True) | [
"def",
"create_single_poll_submission",
"(",
"self",
",",
"poll_id",
",",
"poll_session_id",
",",
"poll_submissions_poll_choice_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - poll_id\r",
"\"\"\"ID\"\"\"",
... | Create a single poll submission.
Create a new poll submission for this poll session | [
"Create",
"a",
"single",
"poll",
"submission",
".",
"Create",
"a",
"new",
"poll",
"submission",
"for",
"this",
"poll",
"session"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/poll_submissions.py#L44-L67 |
theonion/django-bulbs | bulbs/poll/viewsets.py | PollViewSet.list | def list(self, request, *args, **kwargs):
"""Modified list view to driving listing from ES"""
search_kwargs = {"published": False}
query_params = get_query_params(self.request)
for field_name in ("status"):
if field_name in query_params:
search_kwargs[field_name] = query_params.get(field_name)
if "search" in query_params:
search_kwargs["query"] = query_params.get("search")
# active/closed are semantics of the Poll model
# active is analagous to 'published' in Content
# closed is in relation to the end_date of a Poll
if "active" in query_params:
del search_kwargs["published"]
search_kwargs["active"] = True
if "closed" in query_params:
del search_kwargs["published"]
search_kwargs["closed"] = True
queryset = self.model.search_objects.search(**search_kwargs)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) | python | def list(self, request, *args, **kwargs):
"""Modified list view to driving listing from ES"""
search_kwargs = {"published": False}
query_params = get_query_params(self.request)
for field_name in ("status"):
if field_name in query_params:
search_kwargs[field_name] = query_params.get(field_name)
if "search" in query_params:
search_kwargs["query"] = query_params.get("search")
# active/closed are semantics of the Poll model
# active is analagous to 'published' in Content
# closed is in relation to the end_date of a Poll
if "active" in query_params:
del search_kwargs["published"]
search_kwargs["active"] = True
if "closed" in query_params:
del search_kwargs["published"]
search_kwargs["closed"] = True
queryset = self.model.search_objects.search(**search_kwargs)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) | [
"def",
"list",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"search_kwargs",
"=",
"{",
"\"published\"",
":",
"False",
"}",
"query_params",
"=",
"get_query_params",
"(",
"self",
".",
"request",
")",
"for",
"field_name"... | Modified list view to driving listing from ES | [
"Modified",
"list",
"view",
"to",
"driving",
"listing",
"from",
"ES"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/poll/viewsets.py#L38-L70 |
karel-brinda/rnftools | rnftools/mishmash/WgSim.py | WgSim.recode_wgsim_reads | def recode_wgsim_reads(
rnf_fastq_fo,
fai_fo,
genome_id,
wgsim_fastq_1_fn,
wgsim_fastq_2_fn=None,
number_of_read_tuples=10**9,
):
"""Convert WgSim FASTQ files to RNF FASTQ files.
Args:
rnf_fastq_fo (file): File object of the target RNF file.
fai_fo (file): File object of FAI index of the reference genome.
genome_id (int): RNF genome ID.
wgsim_fastq_1_fn (str): File name of the first WgSim FASTQ file.
wgsim_fastq_2_fn (str): File name of the second WgSim FASTQ file.
number_of_read_tuples (int): Expected number of read tuples (to estimate widths).
"""
wgsim_pattern = re.compile(
'@(.*)_([0-9]+)_([0-9]+)_([0-9]+):([0-9]+):([0-9]+)_([0-9]+):([0-9]+):([0-9]+)_([0-9a-f]+)/([12])'
)
"""
WGSIM read name format
1) contig name (chromsome name)
2) start end 1 (one-based)
3) end end 2 (one-based)
4) number of errors end 1
5) number of substitutions end 1
6) number of indels end 1
5) number of errors end 2
6) number of substitutions end 2
7) number of indels end 2
10) id
11) pair
"""
fai_index = rnftools.utils.FaIdx(fai_fo)
read_tuple_id_width = len(format(number_of_read_tuples, 'x'))
last_read_tuple_name = None
fq_creator = rnftools.rnfformat.FqCreator(
fastq_fo=rnf_fastq_fo,
read_tuple_id_width=read_tuple_id_width,
genome_id_width=2,
chr_id_width=fai_index.chr_id_width,
coor_width=fai_index.coor_width,
info_reads_in_tuple=True,
info_simulator="wgsim",
)
reads_in_tuple = 2
if wgsim_fastq_2_fn is None:
reads_in_tuple = 1
i = 0
with open(wgsim_fastq_1_fn, "r+") as f_inp_1:
if reads_in_tuple == 2:
# todo: close file
f_inp_2 = open(wgsim_fastq_2_fn)
for line_a in f_inp_1:
lines = [line_a.strip()]
if reads_in_tuple == 2:
lines.append(f_inp_2.readline().strip())
if i % 4 == 0:
segments = []
# bases=[]
# qualities=[]
m = wgsim_pattern.search(lines[0])
if m is None:
rnftools.utils.error(
"Read tuple '{}' was not generated by WgSim.".format(lines[0][1:]), program="RNFtools",
subprogram="MIShmash", exception=ValueError
)
contig_name = m.group(1)
start_1 = int(m.group(2))
end_2 = int(m.group(3))
errors_1 = int(m.group(4))
substitutions_1 = int(m.group(5))
indels_1 = int(m.group(6))
errors_2 = int(m.group(7))
substitutions_2 = int(m.group(8))
indels_2 = int(m.group(9))
read_tuple_id_w = int(m.group(10), 16)
pair = int(m.group(11))
chr_id = fai_index.dict_chr_ids[contig_name] if fai_index.dict_chr_ids != {} else "0"
if start_1 < end_2:
direction_1 = "F"
direction_2 = "R"
else:
direction_1 = "R"
direction_2 = "F"
segment1 = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_1,
left=start_1,
right=0,
)
segment2 = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_2,
left=0,
right=end_2,
)
elif i % 4 == 1:
bases = lines[0]
if reads_in_tuple == 2:
bases2 = lines[1]
elif i % 4 == 2:
pass
elif i % 4 == 3:
qualities = lines[0]
if reads_in_tuple == 2:
qualities2 = lines[1]
if reads_in_tuple == 1:
fq_creator.add_read(
read_tuple_id=i // 4 + 1,
bases=bases,
qualities=qualities,
segments=[segment1, segment2],
)
else:
fq_creator.add_read(
read_tuple_id=i // 4 + 1,
bases=bases,
qualities=qualities,
segments=[segment1],
)
fq_creator.add_read(
read_tuple_id=i // 4 + 1,
bases=bases2,
qualities=qualities2,
segments=[segment2],
)
i += 1
fq_creator.flush_read_tuple() | python | def recode_wgsim_reads(
rnf_fastq_fo,
fai_fo,
genome_id,
wgsim_fastq_1_fn,
wgsim_fastq_2_fn=None,
number_of_read_tuples=10**9,
):
"""Convert WgSim FASTQ files to RNF FASTQ files.
Args:
rnf_fastq_fo (file): File object of the target RNF file.
fai_fo (file): File object of FAI index of the reference genome.
genome_id (int): RNF genome ID.
wgsim_fastq_1_fn (str): File name of the first WgSim FASTQ file.
wgsim_fastq_2_fn (str): File name of the second WgSim FASTQ file.
number_of_read_tuples (int): Expected number of read tuples (to estimate widths).
"""
wgsim_pattern = re.compile(
'@(.*)_([0-9]+)_([0-9]+)_([0-9]+):([0-9]+):([0-9]+)_([0-9]+):([0-9]+):([0-9]+)_([0-9a-f]+)/([12])'
)
"""
WGSIM read name format
1) contig name (chromsome name)
2) start end 1 (one-based)
3) end end 2 (one-based)
4) number of errors end 1
5) number of substitutions end 1
6) number of indels end 1
5) number of errors end 2
6) number of substitutions end 2
7) number of indels end 2
10) id
11) pair
"""
fai_index = rnftools.utils.FaIdx(fai_fo)
read_tuple_id_width = len(format(number_of_read_tuples, 'x'))
last_read_tuple_name = None
fq_creator = rnftools.rnfformat.FqCreator(
fastq_fo=rnf_fastq_fo,
read_tuple_id_width=read_tuple_id_width,
genome_id_width=2,
chr_id_width=fai_index.chr_id_width,
coor_width=fai_index.coor_width,
info_reads_in_tuple=True,
info_simulator="wgsim",
)
reads_in_tuple = 2
if wgsim_fastq_2_fn is None:
reads_in_tuple = 1
i = 0
with open(wgsim_fastq_1_fn, "r+") as f_inp_1:
if reads_in_tuple == 2:
# todo: close file
f_inp_2 = open(wgsim_fastq_2_fn)
for line_a in f_inp_1:
lines = [line_a.strip()]
if reads_in_tuple == 2:
lines.append(f_inp_2.readline().strip())
if i % 4 == 0:
segments = []
# bases=[]
# qualities=[]
m = wgsim_pattern.search(lines[0])
if m is None:
rnftools.utils.error(
"Read tuple '{}' was not generated by WgSim.".format(lines[0][1:]), program="RNFtools",
subprogram="MIShmash", exception=ValueError
)
contig_name = m.group(1)
start_1 = int(m.group(2))
end_2 = int(m.group(3))
errors_1 = int(m.group(4))
substitutions_1 = int(m.group(5))
indels_1 = int(m.group(6))
errors_2 = int(m.group(7))
substitutions_2 = int(m.group(8))
indels_2 = int(m.group(9))
read_tuple_id_w = int(m.group(10), 16)
pair = int(m.group(11))
chr_id = fai_index.dict_chr_ids[contig_name] if fai_index.dict_chr_ids != {} else "0"
if start_1 < end_2:
direction_1 = "F"
direction_2 = "R"
else:
direction_1 = "R"
direction_2 = "F"
segment1 = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_1,
left=start_1,
right=0,
)
segment2 = rnftools.rnfformat.Segment(
genome_id=genome_id,
chr_id=chr_id,
direction=direction_2,
left=0,
right=end_2,
)
elif i % 4 == 1:
bases = lines[0]
if reads_in_tuple == 2:
bases2 = lines[1]
elif i % 4 == 2:
pass
elif i % 4 == 3:
qualities = lines[0]
if reads_in_tuple == 2:
qualities2 = lines[1]
if reads_in_tuple == 1:
fq_creator.add_read(
read_tuple_id=i // 4 + 1,
bases=bases,
qualities=qualities,
segments=[segment1, segment2],
)
else:
fq_creator.add_read(
read_tuple_id=i // 4 + 1,
bases=bases,
qualities=qualities,
segments=[segment1],
)
fq_creator.add_read(
read_tuple_id=i // 4 + 1,
bases=bases2,
qualities=qualities2,
segments=[segment2],
)
i += 1
fq_creator.flush_read_tuple() | [
"def",
"recode_wgsim_reads",
"(",
"rnf_fastq_fo",
",",
"fai_fo",
",",
"genome_id",
",",
"wgsim_fastq_1_fn",
",",
"wgsim_fastq_2_fn",
"=",
"None",
",",
"number_of_read_tuples",
"=",
"10",
"**",
"9",
",",
")",
":",
"wgsim_pattern",
"=",
"re",
".",
"compile",
"("... | Convert WgSim FASTQ files to RNF FASTQ files.
Args:
rnf_fastq_fo (file): File object of the target RNF file.
fai_fo (file): File object of FAI index of the reference genome.
genome_id (int): RNF genome ID.
wgsim_fastq_1_fn (str): File name of the first WgSim FASTQ file.
wgsim_fastq_2_fn (str): File name of the second WgSim FASTQ file.
number_of_read_tuples (int): Expected number of read tuples (to estimate widths). | [
"Convert",
"WgSim",
"FASTQ",
"files",
"to",
"RNF",
"FASTQ",
"files",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/mishmash/WgSim.py#L177-L330 |
theonion/django-bulbs | bulbs/api/permissions.py | HasPermissionOrIsAuthor.has_object_permission | def has_object_permission(self, request, view, obj):
"""determines if requesting user has permissions for the object
:param request: WSGI request object - where we get the user from
:param view: the view calling for permission
:param obj: the object in question
:return: `bool`
"""
# Give permission if we're not protecting this method
if self.protected_methods and request.method not in self.protected_methods:
return True
user = getattr(request, "user", None)
if not user or user.is_anonymous():
return False
if self.require_staff and not user.is_staff:
return False
# if they have higher-level privileges we can return true right now
if user.has_perms(self.permissions):
return True
# no? ok maybe they're the author and have appropriate author permissions.
authors_field = getattr(obj, self.authors_field, None)
if not authors_field:
return False
if self.author_permissions and not user.has_perms(self.author_permissions):
return False
return user in authors_field.all() | python | def has_object_permission(self, request, view, obj):
"""determines if requesting user has permissions for the object
:param request: WSGI request object - where we get the user from
:param view: the view calling for permission
:param obj: the object in question
:return: `bool`
"""
# Give permission if we're not protecting this method
if self.protected_methods and request.method not in self.protected_methods:
return True
user = getattr(request, "user", None)
if not user or user.is_anonymous():
return False
if self.require_staff and not user.is_staff:
return False
# if they have higher-level privileges we can return true right now
if user.has_perms(self.permissions):
return True
# no? ok maybe they're the author and have appropriate author permissions.
authors_field = getattr(obj, self.authors_field, None)
if not authors_field:
return False
if self.author_permissions and not user.has_perms(self.author_permissions):
return False
return user in authors_field.all() | [
"def",
"has_object_permission",
"(",
"self",
",",
"request",
",",
"view",
",",
"obj",
")",
":",
"# Give permission if we're not protecting this method",
"if",
"self",
".",
"protected_methods",
"and",
"request",
".",
"method",
"not",
"in",
"self",
".",
"protected_met... | determines if requesting user has permissions for the object
:param request: WSGI request object - where we get the user from
:param view: the view calling for permission
:param obj: the object in question
:return: `bool` | [
"determines",
"if",
"requesting",
"user",
"has",
"permissions",
"for",
"the",
"object"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/permissions.py#L11-L44 |
theonion/django-bulbs | bulbs/api/permissions.py | CanEditCmsNotifications.has_permission | def has_permission(self, request, view):
"""If method is GET, user can access, if method is PUT or POST user must be a superuser.
"""
has_permission = False
if request.method == "GET" \
or request.method in ["PUT", "POST", "DELETE"] \
and request.user and request.user.is_superuser:
has_permission = True
return has_permission | python | def has_permission(self, request, view):
"""If method is GET, user can access, if method is PUT or POST user must be a superuser.
"""
has_permission = False
if request.method == "GET" \
or request.method in ["PUT", "POST", "DELETE"] \
and request.user and request.user.is_superuser:
has_permission = True
return has_permission | [
"def",
"has_permission",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"has_permission",
"=",
"False",
"if",
"request",
".",
"method",
"==",
"\"GET\"",
"or",
"request",
".",
"method",
"in",
"[",
"\"PUT\"",
",",
"\"POST\"",
",",
"\"DELETE\"",
"]",
"... | If method is GET, user can access, if method is PUT or POST user must be a superuser. | [
"If",
"method",
"is",
"GET",
"user",
"can",
"access",
"if",
"method",
"is",
"PUT",
"or",
"POST",
"user",
"must",
"be",
"a",
"superuser",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/permissions.py#L78-L86 |
klen/muffin-rest | muffin_rest/api.py | Api.bind | def bind(self, app):
"""Bind API to Muffin."""
self.parent = app
app.add_subapp(self.prefix, self.app) | python | def bind(self, app):
"""Bind API to Muffin."""
self.parent = app
app.add_subapp(self.prefix, self.app) | [
"def",
"bind",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"parent",
"=",
"app",
"app",
".",
"add_subapp",
"(",
"self",
".",
"prefix",
",",
"self",
".",
"app",
")"
] | Bind API to Muffin. | [
"Bind",
"API",
"to",
"Muffin",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/api.py#L36-L39 |
klen/muffin-rest | muffin_rest/api.py | Api.register | def register(self, *paths, methods=None, name=None):
"""Register handler to the API."""
if isinstance(methods, str):
methods = [methods]
def wrapper(handler):
if isinstance(handler, (FunctionType, MethodType)):
handler = RESTHandler.from_view(handler, *(methods or ['GET']))
if handler.name in self.handlers:
raise muffin.MuffinException('Handler is already registered: %s' % handler.name)
self.handlers[tuple(paths or ["/{0}/{{{0}}}".format(handler.name)])] = handler
handler.bind(self.app, *paths, methods=methods, name=name or handler.name)
return handler
# Support for @app.register(func)
if len(paths) == 1 and callable(paths[0]):
view = paths[0]
paths = []
return wrapper(view)
return wrapper | python | def register(self, *paths, methods=None, name=None):
"""Register handler to the API."""
if isinstance(methods, str):
methods = [methods]
def wrapper(handler):
if isinstance(handler, (FunctionType, MethodType)):
handler = RESTHandler.from_view(handler, *(methods or ['GET']))
if handler.name in self.handlers:
raise muffin.MuffinException('Handler is already registered: %s' % handler.name)
self.handlers[tuple(paths or ["/{0}/{{{0}}}".format(handler.name)])] = handler
handler.bind(self.app, *paths, methods=methods, name=name or handler.name)
return handler
# Support for @app.register(func)
if len(paths) == 1 and callable(paths[0]):
view = paths[0]
paths = []
return wrapper(view)
return wrapper | [
"def",
"register",
"(",
"self",
",",
"*",
"paths",
",",
"methods",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"methods",
",",
"str",
")",
":",
"methods",
"=",
"[",
"methods",
"]",
"def",
"wrapper",
"(",
"handler",
")"... | Register handler to the API. | [
"Register",
"handler",
"to",
"the",
"API",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/api.py#L41-L65 |
klen/muffin-rest | muffin_rest/api.py | Api.swagger_schema | def swagger_schema(self, request):
"""Render API Schema."""
if self.parent is None:
return {}
spec = APISpec(
self.parent.name, self.parent.cfg.get('VERSION', ''),
plugins=['apispec.ext.marshmallow'], basePatch=self.prefix
)
for paths, handler in self.handlers.items():
spec.add_tag({
'name': handler.name,
'description': utils.dedent(handler.__doc__ or ''),
})
for path in paths:
operations = {}
for http_method in handler.methods:
method = getattr(handler, http_method.lower())
operation = OrderedDict({
'tags': [handler.name],
'summary': method.__doc__,
'produces': ['application/json'],
'responses': {200: {'schema': {'$ref': {'#/definitions/' + handler.name}}}}
})
operation.update(utils.load_yaml_from_docstring(method.__doc__) or {})
operations[http_method.lower()] = operation
spec.add_path(self.prefix + path, operations=operations)
if getattr(handler, 'Schema', None):
kwargs = {}
if getattr(handler.meta, 'model', None):
kwargs['description'] = utils.dedent(handler.meta.model.__doc__ or '')
spec.definition(handler.name, schema=handler.Schema, **kwargs)
return deepcopy(spec.to_dict()) | python | def swagger_schema(self, request):
"""Render API Schema."""
if self.parent is None:
return {}
spec = APISpec(
self.parent.name, self.parent.cfg.get('VERSION', ''),
plugins=['apispec.ext.marshmallow'], basePatch=self.prefix
)
for paths, handler in self.handlers.items():
spec.add_tag({
'name': handler.name,
'description': utils.dedent(handler.__doc__ or ''),
})
for path in paths:
operations = {}
for http_method in handler.methods:
method = getattr(handler, http_method.lower())
operation = OrderedDict({
'tags': [handler.name],
'summary': method.__doc__,
'produces': ['application/json'],
'responses': {200: {'schema': {'$ref': {'#/definitions/' + handler.name}}}}
})
operation.update(utils.load_yaml_from_docstring(method.__doc__) or {})
operations[http_method.lower()] = operation
spec.add_path(self.prefix + path, operations=operations)
if getattr(handler, 'Schema', None):
kwargs = {}
if getattr(handler.meta, 'model', None):
kwargs['description'] = utils.dedent(handler.meta.model.__doc__ or '')
spec.definition(handler.name, schema=handler.Schema, **kwargs)
return deepcopy(spec.to_dict()) | [
"def",
"swagger_schema",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"{",
"}",
"spec",
"=",
"APISpec",
"(",
"self",
".",
"parent",
".",
"name",
",",
"self",
".",
"parent",
".",
"cfg",
".",
"get",... | Render API Schema. | [
"Render",
"API",
"Schema",
"."
] | train | https://github.com/klen/muffin-rest/blob/1d85bdd3b72a89eaeab8c4086926260a960408aa/muffin_rest/api.py#L99-L135 |
lordmauve/lepton | lepton/domain.py | Box | def Box(*args, **kw):
"""Axis-aligned box domain (same as AABox for now)
WARNING: Deprecated, use AABox instead. This domain will mean something
different in future versions of lepton
"""
import warnings
warnings.warn("lepton.domain.Box is deprecated, use AABox instead. "
"This domain class will mean something different in future versions of lepton",
stacklevel=2)
return AABox(*args, **kw) | python | def Box(*args, **kw):
"""Axis-aligned box domain (same as AABox for now)
WARNING: Deprecated, use AABox instead. This domain will mean something
different in future versions of lepton
"""
import warnings
warnings.warn("lepton.domain.Box is deprecated, use AABox instead. "
"This domain class will mean something different in future versions of lepton",
stacklevel=2)
return AABox(*args, **kw) | [
"def",
"Box",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"lepton.domain.Box is deprecated, use AABox instead. \"",
"\"This domain class will mean something different in future versions of lepton\"",
",",
"stacklevel"... | Axis-aligned box domain (same as AABox for now)
WARNING: Deprecated, use AABox instead. This domain will mean something
different in future versions of lepton | [
"Axis",
"-",
"aligned",
"box",
"domain",
"(",
"same",
"as",
"AABox",
"for",
"now",
")"
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/lepton/domain.py#L103-L113 |
theonion/django-bulbs | bulbs/promotion/models.py | update_pzone | def update_pzone(**kwargs):
"""Update pzone data in the DB"""
pzone = PZone.objects.get(**kwargs)
# get the data and loop through operate_on, applying them if necessary
when = timezone.now()
data = pzone.data
for operation in pzone.operations.filter(when__lte=when, applied=False):
data = operation.apply(data)
operation.applied = True
operation.save()
pzone.data = data
# create a history entry
pzone.history.create(data=pzone.data)
# save modified pzone, making transactions permanent
pzone.save() | python | def update_pzone(**kwargs):
"""Update pzone data in the DB"""
pzone = PZone.objects.get(**kwargs)
# get the data and loop through operate_on, applying them if necessary
when = timezone.now()
data = pzone.data
for operation in pzone.operations.filter(when__lte=when, applied=False):
data = operation.apply(data)
operation.applied = True
operation.save()
pzone.data = data
# create a history entry
pzone.history.create(data=pzone.data)
# save modified pzone, making transactions permanent
pzone.save() | [
"def",
"update_pzone",
"(",
"*",
"*",
"kwargs",
")",
":",
"pzone",
"=",
"PZone",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"kwargs",
")",
"# get the data and loop through operate_on, applying them if necessary",
"when",
"=",
"timezone",
".",
"now",
"(",
")",
... | Update pzone data in the DB | [
"Update",
"pzone",
"data",
"in",
"the",
"DB"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/promotion/models.py#L15-L33 |
theonion/django-bulbs | bulbs/promotion/models.py | PZoneManager.operate_on | def operate_on(self, when=None, apply=False, **kwargs):
"""Do something with operate_on. If apply is True, all transactions will
be applied and saved via celery task."""
# get pzone based on id
pzone = self.get(**kwargs)
# cache the current time
now = timezone.now()
# ensure we have some value for when
if when is None:
when = now
if when < now:
histories = pzone.history.filter(date__lte=when)
if histories.exists():
# we have some history, use its data
pzone.data = histories[0].data
else:
# only apply operations if cache is expired or empty, or we're looking at the future
data = pzone.data
# Get the cached time of the next expiration
next_operation_time = cache.get('pzone-operation-expiry-' + pzone.name)
if next_operation_time is None or next_operation_time < when:
# start applying operations
pending_operations = pzone.operations.filter(when__lte=when, applied=False)
for operation in pending_operations:
data = operation.apply(data)
# reassign data
pzone.data = data
if apply and pending_operations.exists():
# there are operations to apply, do celery task
update_pzone.delay(**kwargs)
# return pzone, modified if apply was True
return pzone | python | def operate_on(self, when=None, apply=False, **kwargs):
"""Do something with operate_on. If apply is True, all transactions will
be applied and saved via celery task."""
# get pzone based on id
pzone = self.get(**kwargs)
# cache the current time
now = timezone.now()
# ensure we have some value for when
if when is None:
when = now
if when < now:
histories = pzone.history.filter(date__lte=when)
if histories.exists():
# we have some history, use its data
pzone.data = histories[0].data
else:
# only apply operations if cache is expired or empty, or we're looking at the future
data = pzone.data
# Get the cached time of the next expiration
next_operation_time = cache.get('pzone-operation-expiry-' + pzone.name)
if next_operation_time is None or next_operation_time < when:
# start applying operations
pending_operations = pzone.operations.filter(when__lte=when, applied=False)
for operation in pending_operations:
data = operation.apply(data)
# reassign data
pzone.data = data
if apply and pending_operations.exists():
# there are operations to apply, do celery task
update_pzone.delay(**kwargs)
# return pzone, modified if apply was True
return pzone | [
"def",
"operate_on",
"(",
"self",
",",
"when",
"=",
"None",
",",
"apply",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# get pzone based on id",
"pzone",
"=",
"self",
".",
"get",
"(",
"*",
"*",
"kwargs",
")",
"# cache the current time",
"now",
"=",
... | Do something with operate_on. If apply is True, all transactions will
be applied and saved via celery task. | [
"Do",
"something",
"with",
"operate_on",
".",
"If",
"apply",
"is",
"True",
"all",
"transactions",
"will",
"be",
"applied",
"and",
"saved",
"via",
"celery",
"task",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/promotion/models.py#L38-L79 |
theonion/django-bulbs | bulbs/promotion/models.py | PZoneManager.preview | def preview(self, when=timezone.now(), **kwargs):
"""Preview transactions, but don't actually save changes to list."""
return self.operate_on(when=when, apply=False, **kwargs) | python | def preview(self, when=timezone.now(), **kwargs):
"""Preview transactions, but don't actually save changes to list."""
return self.operate_on(when=when, apply=False, **kwargs) | [
"def",
"preview",
"(",
"self",
",",
"when",
"=",
"timezone",
".",
"now",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"operate_on",
"(",
"when",
"=",
"when",
",",
"apply",
"=",
"False",
",",
"*",
"*",
"kwargs",
")"
] | Preview transactions, but don't actually save changes to list. | [
"Preview",
"transactions",
"but",
"don",
"t",
"actually",
"save",
"changes",
"to",
"list",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/promotion/models.py#L81-L84 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.get_download_link | def get_download_link(self):
""" Get direct download link with soudcloud's redirect system. """
url = None
if not self.get("downloadable"):
try:
url = self.client.get_location(
self.client.STREAM_URL % self.get("id"))
except serror as e:
print(e)
if not url:
try:
url = self.client.get_location(
self.client.DOWNLOAD_URL % self.get("id"))
except serror as e:
print(e)
return url | python | def get_download_link(self):
""" Get direct download link with soudcloud's redirect system. """
url = None
if not self.get("downloadable"):
try:
url = self.client.get_location(
self.client.STREAM_URL % self.get("id"))
except serror as e:
print(e)
if not url:
try:
url = self.client.get_location(
self.client.DOWNLOAD_URL % self.get("id"))
except serror as e:
print(e)
return url | [
"def",
"get_download_link",
"(",
"self",
")",
":",
"url",
"=",
"None",
"if",
"not",
"self",
".",
"get",
"(",
"\"downloadable\"",
")",
":",
"try",
":",
"url",
"=",
"self",
".",
"client",
".",
"get_location",
"(",
"self",
".",
"client",
".",
"STREAM_URL"... | Get direct download link with soudcloud's redirect system. | [
"Get",
"direct",
"download",
"link",
"with",
"soudcloud",
"s",
"redirect",
"system",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L82-L99 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.get_file_extension | def get_file_extension(self, filepath):
"""
This method check mimetype to define file extension.
If it can't, it use original-format metadata.
"""
mtype = magic.from_file(filepath, mime=True)
if type(mtype) == bytes:
mtype = mtype.decode("utf-8")
if mtype == "audio/mpeg":
ext = ".mp3"
elif mtype == "audio/x-wav":
ext = ".wav"
else:
ext = "." + self.get("original-format")
return ext | python | def get_file_extension(self, filepath):
"""
This method check mimetype to define file extension.
If it can't, it use original-format metadata.
"""
mtype = magic.from_file(filepath, mime=True)
if type(mtype) == bytes:
mtype = mtype.decode("utf-8")
if mtype == "audio/mpeg":
ext = ".mp3"
elif mtype == "audio/x-wav":
ext = ".wav"
else:
ext = "." + self.get("original-format")
return ext | [
"def",
"get_file_extension",
"(",
"self",
",",
"filepath",
")",
":",
"mtype",
"=",
"magic",
".",
"from_file",
"(",
"filepath",
",",
"mime",
"=",
"True",
")",
"if",
"type",
"(",
"mtype",
")",
"==",
"bytes",
":",
"mtype",
"=",
"mtype",
".",
"decode",
"... | This method check mimetype to define file extension.
If it can't, it use original-format metadata. | [
"This",
"method",
"check",
"mimetype",
"to",
"define",
"file",
"extension",
".",
"If",
"it",
"can",
"t",
"it",
"use",
"original",
"-",
"format",
"metadata",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L107-L122 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.gen_localdir | def gen_localdir(self, localdir):
"""
Generate local directory where track will be saved.
Create it if not exists.
"""
directory = "{0}/{1}/".format(localdir, self.get("username"))
if not os.path.exists(directory):
os.makedirs(directory)
return directory | python | def gen_localdir(self, localdir):
"""
Generate local directory where track will be saved.
Create it if not exists.
"""
directory = "{0}/{1}/".format(localdir, self.get("username"))
if not os.path.exists(directory):
os.makedirs(directory)
return directory | [
"def",
"gen_localdir",
"(",
"self",
",",
"localdir",
")",
":",
"directory",
"=",
"\"{0}/{1}/\"",
".",
"format",
"(",
"localdir",
",",
"self",
".",
"get",
"(",
"\"username\"",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")... | Generate local directory where track will be saved.
Create it if not exists. | [
"Generate",
"local",
"directory",
"where",
"track",
"will",
"be",
"saved",
".",
"Create",
"it",
"if",
"not",
"exists",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L130-L138 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.track_exists | def track_exists(self, localdir):
""" Check if track exists in local directory. """
path = glob.glob(self.gen_localdir(localdir) +
self.gen_filename() + "*")
if len(path) > 0 and os.path.getsize(path[0]) > 0:
return True
return False | python | def track_exists(self, localdir):
""" Check if track exists in local directory. """
path = glob.glob(self.gen_localdir(localdir) +
self.gen_filename() + "*")
if len(path) > 0 and os.path.getsize(path[0]) > 0:
return True
return False | [
"def",
"track_exists",
"(",
"self",
",",
"localdir",
")",
":",
"path",
"=",
"glob",
".",
"glob",
"(",
"self",
".",
"gen_localdir",
"(",
"localdir",
")",
"+",
"self",
".",
"gen_filename",
"(",
")",
"+",
"\"*\"",
")",
"if",
"len",
"(",
"path",
")",
"... | Check if track exists in local directory. | [
"Check",
"if",
"track",
"exists",
"in",
"local",
"directory",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L140-L146 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.get_ignored_tracks | def get_ignored_tracks(self, localdir):
""" Get ignored tracks list. """
ignore_file = "%s/.ignore" % localdir
list = []
if os.path.exists(ignore_file):
f = open(ignore_file)
ignored = f.readlines()
f.close()
for i in ignored:
list.append("%s/%s" % (localdir, i.rstrip()))
return list | python | def get_ignored_tracks(self, localdir):
""" Get ignored tracks list. """
ignore_file = "%s/.ignore" % localdir
list = []
if os.path.exists(ignore_file):
f = open(ignore_file)
ignored = f.readlines()
f.close()
for i in ignored:
list.append("%s/%s" % (localdir, i.rstrip()))
return list | [
"def",
"get_ignored_tracks",
"(",
"self",
",",
"localdir",
")",
":",
"ignore_file",
"=",
"\"%s/.ignore\"",
"%",
"localdir",
"list",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ignore_file",
")",
":",
"f",
"=",
"open",
"(",
"ignore_file",... | Get ignored tracks list. | [
"Get",
"ignored",
"tracks",
"list",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L148-L160 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.download | def download(self, localdir, max_retry):
""" Download a track in local directory. """
local_file = self.gen_localdir(localdir) + self.gen_filename()
if self.track_exists(localdir):
print("Track {0} already downloaded, skipping!".format(
self.get("id")))
return False
if local_file in self.get_ignored_tracks(localdir):
print("\033[93mTrack {0} ignored, skipping!!\033[0m".format(
self.get("id")))
return False
dlurl = self.get_download_link()
if not dlurl:
raise serror("Can't download track_id:%d|%s" % (
self.get("id"),
self.get("title")))
retry = max_retry
print("\nDownloading %s (%d).." % (self.get("title"), self.get("id")))
while True:
try:
urllib.request.urlretrieve(dlurl, local_file,
self._progress_hook)
break
except Exception as e:
if os.path.isfile(local_file):
os.unlink(local_file)
retry -= 1
if retry < 0:
raise serror("Can't download track-id %s, max retry "
"reached (%d). Error occured: %s" % (
self.get("id"), max_retry, type(e)))
else:
print("\033[93mError occured for track-id %s (%s). "
"Retrying.. (%d/%d) \033[0m" % (
self.get("id"),
type(e),
max_retry - retry,
max_retry))
except KeyboardInterrupt:
if os.path.isfile(local_file):
os.unlink(local_file)
raise serror("KeyBoard Interrupt: Incomplete file removed.")
self.filepath = local_file + self.get_file_extension(local_file)
os.rename(local_file, self.filepath)
print("Downloaded => %s" % self.filepath)
self.downloaded = True
return True | python | def download(self, localdir, max_retry):
""" Download a track in local directory. """
local_file = self.gen_localdir(localdir) + self.gen_filename()
if self.track_exists(localdir):
print("Track {0} already downloaded, skipping!".format(
self.get("id")))
return False
if local_file in self.get_ignored_tracks(localdir):
print("\033[93mTrack {0} ignored, skipping!!\033[0m".format(
self.get("id")))
return False
dlurl = self.get_download_link()
if not dlurl:
raise serror("Can't download track_id:%d|%s" % (
self.get("id"),
self.get("title")))
retry = max_retry
print("\nDownloading %s (%d).." % (self.get("title"), self.get("id")))
while True:
try:
urllib.request.urlretrieve(dlurl, local_file,
self._progress_hook)
break
except Exception as e:
if os.path.isfile(local_file):
os.unlink(local_file)
retry -= 1
if retry < 0:
raise serror("Can't download track-id %s, max retry "
"reached (%d). Error occured: %s" % (
self.get("id"), max_retry, type(e)))
else:
print("\033[93mError occured for track-id %s (%s). "
"Retrying.. (%d/%d) \033[0m" % (
self.get("id"),
type(e),
max_retry - retry,
max_retry))
except KeyboardInterrupt:
if os.path.isfile(local_file):
os.unlink(local_file)
raise serror("KeyBoard Interrupt: Incomplete file removed.")
self.filepath = local_file + self.get_file_extension(local_file)
os.rename(local_file, self.filepath)
print("Downloaded => %s" % self.filepath)
self.downloaded = True
return True | [
"def",
"download",
"(",
"self",
",",
"localdir",
",",
"max_retry",
")",
":",
"local_file",
"=",
"self",
".",
"gen_localdir",
"(",
"localdir",
")",
"+",
"self",
".",
"gen_filename",
"(",
")",
"if",
"self",
".",
"track_exists",
"(",
"localdir",
")",
":",
... | Download a track in local directory. | [
"Download",
"a",
"track",
"in",
"local",
"directory",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L162-L217 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.process_tags | def process_tags(self, tag=None):
"""Process ID3 Tags for mp3 files."""
if self.downloaded is False:
raise serror("Track not downloaded, can't process tags..")
filetype = magic.from_file(self.filepath, mime=True)
if filetype != "audio/mpeg":
raise serror("Cannot process tags for file type %s." % filetype)
print("Processing tags for %s.." % self.filepath)
if tag is None:
tag = stag()
tag.load_id3(self)
tag.write_id3(self.filepath) | python | def process_tags(self, tag=None):
"""Process ID3 Tags for mp3 files."""
if self.downloaded is False:
raise serror("Track not downloaded, can't process tags..")
filetype = magic.from_file(self.filepath, mime=True)
if filetype != "audio/mpeg":
raise serror("Cannot process tags for file type %s." % filetype)
print("Processing tags for %s.." % self.filepath)
if tag is None:
tag = stag()
tag.load_id3(self)
tag.write_id3(self.filepath) | [
"def",
"process_tags",
"(",
"self",
",",
"tag",
"=",
"None",
")",
":",
"if",
"self",
".",
"downloaded",
"is",
"False",
":",
"raise",
"serror",
"(",
"\"Track not downloaded, can't process tags..\"",
")",
"filetype",
"=",
"magic",
".",
"from_file",
"(",
"self",
... | Process ID3 Tags for mp3 files. | [
"Process",
"ID3",
"Tags",
"for",
"mp3",
"files",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L219-L231 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.convert | def convert(self):
"""Convert file in mp3 format."""
if self.downloaded is False:
raise serror("Track not downloaded, can't convert file..")
filetype = magic.from_file(self.filepath, mime=True)
if filetype == "audio/mpeg":
print("File is already in mp3 format. Skipping convert.")
return False
rootpath = os.path.dirname(os.path.dirname(self.filepath))
backupdir = rootpath + "/backups/" + self.get("username")
if not os.path.exists(backupdir):
os.makedirs(backupdir)
backupfile = "%s/%s%s" % (
backupdir,
self.gen_filename(),
self.get_file_extension(self.filepath))
newfile = "%s.mp3" % self.filename_without_extension()
os.rename(self.filepath, backupfile)
self.filepath = newfile
print("Converting to %s.." % newfile)
song = AudioSegment.from_file(backupfile)
return song.export(newfile, format="mp3") | python | def convert(self):
"""Convert file in mp3 format."""
if self.downloaded is False:
raise serror("Track not downloaded, can't convert file..")
filetype = magic.from_file(self.filepath, mime=True)
if filetype == "audio/mpeg":
print("File is already in mp3 format. Skipping convert.")
return False
rootpath = os.path.dirname(os.path.dirname(self.filepath))
backupdir = rootpath + "/backups/" + self.get("username")
if not os.path.exists(backupdir):
os.makedirs(backupdir)
backupfile = "%s/%s%s" % (
backupdir,
self.gen_filename(),
self.get_file_extension(self.filepath))
newfile = "%s.mp3" % self.filename_without_extension()
os.rename(self.filepath, backupfile)
self.filepath = newfile
print("Converting to %s.." % newfile)
song = AudioSegment.from_file(backupfile)
return song.export(newfile, format="mp3") | [
"def",
"convert",
"(",
"self",
")",
":",
"if",
"self",
".",
"downloaded",
"is",
"False",
":",
"raise",
"serror",
"(",
"\"Track not downloaded, can't convert file..\"",
")",
"filetype",
"=",
"magic",
".",
"from_file",
"(",
"self",
".",
"filepath",
",",
"mime",
... | Convert file in mp3 format. | [
"Convert",
"file",
"in",
"mp3",
"format",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L233-L258 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack.download_artwork | def download_artwork(self, localdir, max_retry):
"""
Download track's artwork and return file path.
Artwork's path is saved in track's metadata as 'artwork-path' key.
"""
if self.get("artwork-url") == "None":
self.metadata["artwork-path"] = None
return None
artwork_dir = localdir + "/artworks"
if not os.path.isdir(artwork_dir):
if os.path.isfile(artwork_dir):
os.unlink(artwork_dir)
os.mkdir(artwork_dir)
artwork_filepath = artwork_dir + "/" + self.gen_artwork_filename()
retry = max_retry
while True:
try:
res = urllib.request.urlopen(self.get("artwork-url"))
with open(artwork_filepath, "wb") as file:
file.write(res.read())
break
except Exception as e:
retry -= 1
if retry < 0:
print(serror("Can't download track's artwork, max retry "
"reached (%d). Error occured: %s" % (
max_retry, type(e))))
return False
else:
print("\033[93mTrack's artwork download failed (%s). "
"Retrying.. (%d/%d) \033[0m" % (
type(e),
max_retry - retry,
max_retry))
self.metadata["artwork-path"] = artwork_filepath | python | def download_artwork(self, localdir, max_retry):
"""
Download track's artwork and return file path.
Artwork's path is saved in track's metadata as 'artwork-path' key.
"""
if self.get("artwork-url") == "None":
self.metadata["artwork-path"] = None
return None
artwork_dir = localdir + "/artworks"
if not os.path.isdir(artwork_dir):
if os.path.isfile(artwork_dir):
os.unlink(artwork_dir)
os.mkdir(artwork_dir)
artwork_filepath = artwork_dir + "/" + self.gen_artwork_filename()
retry = max_retry
while True:
try:
res = urllib.request.urlopen(self.get("artwork-url"))
with open(artwork_filepath, "wb") as file:
file.write(res.read())
break
except Exception as e:
retry -= 1
if retry < 0:
print(serror("Can't download track's artwork, max retry "
"reached (%d). Error occured: %s" % (
max_retry, type(e))))
return False
else:
print("\033[93mTrack's artwork download failed (%s). "
"Retrying.. (%d/%d) \033[0m" % (
type(e),
max_retry - retry,
max_retry))
self.metadata["artwork-path"] = artwork_filepath | [
"def",
"download_artwork",
"(",
"self",
",",
"localdir",
",",
"max_retry",
")",
":",
"if",
"self",
".",
"get",
"(",
"\"artwork-url\"",
")",
"==",
"\"None\"",
":",
"self",
".",
"metadata",
"[",
"\"artwork-path\"",
"]",
"=",
"None",
"return",
"None",
"artwor... | Download track's artwork and return file path.
Artwork's path is saved in track's metadata as 'artwork-path' key. | [
"Download",
"track",
"s",
"artwork",
"and",
"return",
"file",
"path",
".",
"Artwork",
"s",
"path",
"is",
"saved",
"in",
"track",
"s",
"metadata",
"as",
"artwork",
"-",
"path",
"key",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L264-L302 |
Sliim/soundcloud-syncer | ssyncer/strack.py | strack._progress_hook | def _progress_hook(self, blocknum, blocksize, totalsize):
""" Progress hook for urlretrieve. """
read = blocknum * blocksize
if totalsize > 0:
percent = read * 1e2 / totalsize
s = "\r%d%% %*d / %d" % (
percent, len(str(totalsize)), read, totalsize)
sys.stdout.write(s)
if read >= totalsize:
sys.stdout.write("\n")
else:
sys.stdout.write("read %d\n" % read) | python | def _progress_hook(self, blocknum, blocksize, totalsize):
""" Progress hook for urlretrieve. """
read = blocknum * blocksize
if totalsize > 0:
percent = read * 1e2 / totalsize
s = "\r%d%% %*d / %d" % (
percent, len(str(totalsize)), read, totalsize)
sys.stdout.write(s)
if read >= totalsize:
sys.stdout.write("\n")
else:
sys.stdout.write("read %d\n" % read) | [
"def",
"_progress_hook",
"(",
"self",
",",
"blocknum",
",",
"blocksize",
",",
"totalsize",
")",
":",
"read",
"=",
"blocknum",
"*",
"blocksize",
"if",
"totalsize",
">",
"0",
":",
"percent",
"=",
"read",
"*",
"1e2",
"/",
"totalsize",
"s",
"=",
"\"\\r%d%% %... | Progress hook for urlretrieve. | [
"Progress",
"hook",
"for",
"urlretrieve",
"."
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L304-L316 |
Sliim/soundcloud-syncer | ssyncer/strack.py | stag.load_id3 | def load_id3(self, track):
""" Load id3 tags from strack metadata """
if not isinstance(track, strack):
raise TypeError('strack object required')
timestamp = calendar.timegm(parse(track.get("created-at")).timetuple())
self.mapper[TIT1] = TIT1(text=track.get("description"))
self.mapper[TIT2] = TIT2(text=track.get("title"))
self.mapper[TIT3] = TIT3(text=track.get("tags-list"))
self.mapper[TDOR] = TDOR(text=str(timestamp))
self.mapper[TLEN] = TLEN(text=track.get("duration"))
self.mapper[TOFN] = TOFN(text=track.get("permalink"))
self.mapper[TCON] = TCON(text=track.get("genre"))
self.mapper[TCOP] = TCOP(text=track.get("license"))
self.mapper[WOAS] = WOAS(url=track.get("permalink-url"))
self.mapper[WOAF] = WOAF(url=track.get("uri"))
self.mapper[TPUB] = TPUB(text=track.get("username"))
self.mapper[WOAR] = WOAR(url=track.get("user-url"))
self.mapper[TPE1] = TPE1(text=track.get("artist"))
self.mapper[TALB] = TALB(text="%s Soundcloud tracks"
% track.get("artist"))
if track.get("artwork-path") is not None:
self.mapper[APIC] = APIC(value=track.get("artwork-path")) | python | def load_id3(self, track):
""" Load id3 tags from strack metadata """
if not isinstance(track, strack):
raise TypeError('strack object required')
timestamp = calendar.timegm(parse(track.get("created-at")).timetuple())
self.mapper[TIT1] = TIT1(text=track.get("description"))
self.mapper[TIT2] = TIT2(text=track.get("title"))
self.mapper[TIT3] = TIT3(text=track.get("tags-list"))
self.mapper[TDOR] = TDOR(text=str(timestamp))
self.mapper[TLEN] = TLEN(text=track.get("duration"))
self.mapper[TOFN] = TOFN(text=track.get("permalink"))
self.mapper[TCON] = TCON(text=track.get("genre"))
self.mapper[TCOP] = TCOP(text=track.get("license"))
self.mapper[WOAS] = WOAS(url=track.get("permalink-url"))
self.mapper[WOAF] = WOAF(url=track.get("uri"))
self.mapper[TPUB] = TPUB(text=track.get("username"))
self.mapper[WOAR] = WOAR(url=track.get("user-url"))
self.mapper[TPE1] = TPE1(text=track.get("artist"))
self.mapper[TALB] = TALB(text="%s Soundcloud tracks"
% track.get("artist"))
if track.get("artwork-path") is not None:
self.mapper[APIC] = APIC(value=track.get("artwork-path")) | [
"def",
"load_id3",
"(",
"self",
",",
"track",
")",
":",
"if",
"not",
"isinstance",
"(",
"track",
",",
"strack",
")",
":",
"raise",
"TypeError",
"(",
"'strack object required'",
")",
"timestamp",
"=",
"calendar",
".",
"timegm",
"(",
"parse",
"(",
"track",
... | Load id3 tags from strack metadata | [
"Load",
"id3",
"tags",
"from",
"strack",
"metadata"
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L324-L348 |
Sliim/soundcloud-syncer | ssyncer/strack.py | stag.write_id3 | def write_id3(self, filename):
""" Write id3 tags """
if not os.path.exists(filename):
raise ValueError("File doesn't exists.")
self.mapper.write(filename) | python | def write_id3(self, filename):
""" Write id3 tags """
if not os.path.exists(filename):
raise ValueError("File doesn't exists.")
self.mapper.write(filename) | [
"def",
"write_id3",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"\"File doesn't exists.\"",
")",
"self",
".",
"mapper",
".",
"write",
"(",
"filename",
")"
] | Write id3 tags | [
"Write",
"id3",
"tags"
] | train | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L350-L355 |
lordmauve/lepton | lepton/texturizer.py | _atlas_from_images | def _atlas_from_images(images):
"""Create a pyglet texture atlas from a sequence of images.
Return a tuple of (atlas, textures)
"""
import pyglet
widest = max(img.width for img in images)
height = sum(img.height for img in images)
atlas = pyglet.image.atlas.TextureAtlas(
width=_nearest_pow2(widest), height=_nearest_pow2(height))
textures = [atlas.add(image) for image in images]
return atlas, textures | python | def _atlas_from_images(images):
"""Create a pyglet texture atlas from a sequence of images.
Return a tuple of (atlas, textures)
"""
import pyglet
widest = max(img.width for img in images)
height = sum(img.height for img in images)
atlas = pyglet.image.atlas.TextureAtlas(
width=_nearest_pow2(widest), height=_nearest_pow2(height))
textures = [atlas.add(image) for image in images]
return atlas, textures | [
"def",
"_atlas_from_images",
"(",
"images",
")",
":",
"import",
"pyglet",
"widest",
"=",
"max",
"(",
"img",
".",
"width",
"for",
"img",
"in",
"images",
")",
"height",
"=",
"sum",
"(",
"img",
".",
"height",
"for",
"img",
"in",
"images",
")",
"atlas",
... | Create a pyglet texture atlas from a sequence of images.
Return a tuple of (atlas, textures) | [
"Create",
"a",
"pyglet",
"texture",
"atlas",
"from",
"a",
"sequence",
"of",
"images",
".",
"Return",
"a",
"tuple",
"of",
"(",
"atlas",
"textures",
")"
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/lepton/texturizer.py#L34-L45 |
lordmauve/lepton | lepton/texturizer.py | create_point_texture | def create_point_texture(size, feather=0):
"""Create and load a circular grayscale image centered in a square texture
with a width and height of size. The radius of the circle is size / 2.
Since size is used as the texture width and height, it should typically
be a power of two.
Feather determines the softness of the edge of the circle. The default,
zero, creates a hard edged circle. Larger feather values create softer
edges for blending. The point at the center of the texture is always
white.
Return the OpenGL texture name (id) for the resulting texture. This
value can be passed directy to a texturizer or glBindTexture
"""
from pyglet import gl
assert feather >= 0, 'Expected feather value >= 0'
coords = range(size)
texel = (gl.GLfloat * size**2)()
r = size / 2.0
c = feather + 1.0
for y in coords:
col = y * size
for x in coords:
d = math.sqrt((x - r)**2 + (y - r)**2)
if d < r and (1.0 - 1.0 / (d / r - 1.0)) < 100:
texel[x + col] = c**2 / c**(1.0 - 1.0 / (d / r - 1.0))
else:
texel[x + col] = 0
id = gl.GLuint()
gl.glGenTextures(1, ctypes.byref(id))
gl.glBindTexture(gl.GL_TEXTURE_2D, id.value)
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4)
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, size, size, 0,
gl.GL_LUMINANCE, gl.GL_FLOAT, ctypes.byref(texel))
gl.glFlush()
return id.value | python | def create_point_texture(size, feather=0):
"""Create and load a circular grayscale image centered in a square texture
with a width and height of size. The radius of the circle is size / 2.
Since size is used as the texture width and height, it should typically
be a power of two.
Feather determines the softness of the edge of the circle. The default,
zero, creates a hard edged circle. Larger feather values create softer
edges for blending. The point at the center of the texture is always
white.
Return the OpenGL texture name (id) for the resulting texture. This
value can be passed directy to a texturizer or glBindTexture
"""
from pyglet import gl
assert feather >= 0, 'Expected feather value >= 0'
coords = range(size)
texel = (gl.GLfloat * size**2)()
r = size / 2.0
c = feather + 1.0
for y in coords:
col = y * size
for x in coords:
d = math.sqrt((x - r)**2 + (y - r)**2)
if d < r and (1.0 - 1.0 / (d / r - 1.0)) < 100:
texel[x + col] = c**2 / c**(1.0 - 1.0 / (d / r - 1.0))
else:
texel[x + col] = 0
id = gl.GLuint()
gl.glGenTextures(1, ctypes.byref(id))
gl.glBindTexture(gl.GL_TEXTURE_2D, id.value)
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4)
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, size, size, 0,
gl.GL_LUMINANCE, gl.GL_FLOAT, ctypes.byref(texel))
gl.glFlush()
return id.value | [
"def",
"create_point_texture",
"(",
"size",
",",
"feather",
"=",
"0",
")",
":",
"from",
"pyglet",
"import",
"gl",
"assert",
"feather",
">=",
"0",
",",
"'Expected feather value >= 0'",
"coords",
"=",
"range",
"(",
"size",
")",
"texel",
"=",
"(",
"gl",
".",
... | Create and load a circular grayscale image centered in a square texture
with a width and height of size. The radius of the circle is size / 2.
Since size is used as the texture width and height, it should typically
be a power of two.
Feather determines the softness of the edge of the circle. The default,
zero, creates a hard edged circle. Larger feather values create softer
edges for blending. The point at the center of the texture is always
white.
Return the OpenGL texture name (id) for the resulting texture. This
value can be passed directy to a texturizer or glBindTexture | [
"Create",
"and",
"load",
"a",
"circular",
"grayscale",
"image",
"centered",
"in",
"a",
"square",
"texture",
"with",
"a",
"width",
"and",
"height",
"of",
"size",
".",
"The",
"radius",
"of",
"the",
"circle",
"is",
"size",
"/",
"2",
".",
"Since",
"size",
... | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/lepton/texturizer.py#L93-L130 |
lordmauve/lepton | lepton/texturizer.py | SpriteTexturizer.from_images | def from_images(cls, images, weights=None, filter=None, wrap=None,
aspect_adjust_width=False, aspect_adjust_height=False):
"""Create a SpriteTexturizer from a sequence of Pyglet images.
Note all the images must be able to fit into a single OpenGL texture, so
their combined size should typically be less than 1024x1024
"""
import pyglet
atlas, textures = _atlas_from_images(images)
texturizer = cls(
atlas.texture.id, [tex.tex_coords for tex in textures],
weights, filter or pyglet.gl.GL_LINEAR, wrap or pyglet.gl.GL_CLAMP,
aspect_adjust_width, aspect_adjust_height)
texturizer.atlas = atlas
texturizer.textures = textures
return texturizer | python | def from_images(cls, images, weights=None, filter=None, wrap=None,
aspect_adjust_width=False, aspect_adjust_height=False):
"""Create a SpriteTexturizer from a sequence of Pyglet images.
Note all the images must be able to fit into a single OpenGL texture, so
their combined size should typically be less than 1024x1024
"""
import pyglet
atlas, textures = _atlas_from_images(images)
texturizer = cls(
atlas.texture.id, [tex.tex_coords for tex in textures],
weights, filter or pyglet.gl.GL_LINEAR, wrap or pyglet.gl.GL_CLAMP,
aspect_adjust_width, aspect_adjust_height)
texturizer.atlas = atlas
texturizer.textures = textures
return texturizer | [
"def",
"from_images",
"(",
"cls",
",",
"images",
",",
"weights",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"wrap",
"=",
"None",
",",
"aspect_adjust_width",
"=",
"False",
",",
"aspect_adjust_height",
"=",
"False",
")",
":",
"import",
"pyglet",
"atlas",
... | Create a SpriteTexturizer from a sequence of Pyglet images.
Note all the images must be able to fit into a single OpenGL texture, so
their combined size should typically be less than 1024x1024 | [
"Create",
"a",
"SpriteTexturizer",
"from",
"a",
"sequence",
"of",
"Pyglet",
"images",
"."
] | train | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/lepton/texturizer.py#L52-L67 |
Sanji-IO/sanji | sanji/message.py | parse_querystring | def parse_querystring(querystring):
"""
Return parsed querystring in dict
"""
if querystring is None or len(querystring) == 0:
return {}
qs_dict = parse.parse_qs(querystring, keep_blank_values=True)
for key in qs_dict:
if len(qs_dict[key]) != 1:
continue
qs_dict[key] = qs_dict[key][0]
if qs_dict[key] == '':
qs_dict[key] = True
return dict((key, qs_dict[key]) for key in qs_dict if len(key) != 0) | python | def parse_querystring(querystring):
"""
Return parsed querystring in dict
"""
if querystring is None or len(querystring) == 0:
return {}
qs_dict = parse.parse_qs(querystring, keep_blank_values=True)
for key in qs_dict:
if len(qs_dict[key]) != 1:
continue
qs_dict[key] = qs_dict[key][0]
if qs_dict[key] == '':
qs_dict[key] = True
return dict((key, qs_dict[key]) for key in qs_dict if len(key) != 0) | [
"def",
"parse_querystring",
"(",
"querystring",
")",
":",
"if",
"querystring",
"is",
"None",
"or",
"len",
"(",
"querystring",
")",
"==",
"0",
":",
"return",
"{",
"}",
"qs_dict",
"=",
"parse",
".",
"parse_qs",
"(",
"querystring",
",",
"keep_blank_values",
"... | Return parsed querystring in dict | [
"Return",
"parsed",
"querystring",
"in",
"dict"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L16-L31 |
Sanji-IO/sanji | sanji/message.py | Message.to_json | def to_json(self, pretty=True):
"""
to_json will call to_dict then dumps into json format
"""
data_dict = self.to_dict()
if pretty:
return json.dumps(
data_dict, sort_keys=True, indent=2)
return json.dumps(data_dict, sort_keys=True) | python | def to_json(self, pretty=True):
"""
to_json will call to_dict then dumps into json format
"""
data_dict = self.to_dict()
if pretty:
return json.dumps(
data_dict, sort_keys=True, indent=2)
return json.dumps(data_dict, sort_keys=True) | [
"def",
"to_json",
"(",
"self",
",",
"pretty",
"=",
"True",
")",
":",
"data_dict",
"=",
"self",
".",
"to_dict",
"(",
")",
"if",
"pretty",
":",
"return",
"json",
".",
"dumps",
"(",
"data_dict",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"2",
... | to_json will call to_dict then dumps into json format | [
"to_json",
"will",
"call",
"to_dict",
"then",
"dumps",
"into",
"json",
"format"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L150-L158 |
Sanji-IO/sanji | sanji/message.py | Message.to_dict | def to_dict(self):
"""
to_dict will clean all protected and private properties
"""
return dict(
(k, self.__dict__[k]) for k in self.__dict__ if k.find("_") != 0) | python | def to_dict(self):
"""
to_dict will clean all protected and private properties
"""
return dict(
(k, self.__dict__[k]) for k in self.__dict__ if k.find("_") != 0) | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"self",
".",
"__dict__",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"self",
".",
"__dict__",
"if",
"k",
".",
"find",
"(",
"\"_\"",
")",
"!=",
"0",
")"
] | to_dict will clean all protected and private properties | [
"to_dict",
"will",
"clean",
"all",
"protected",
"and",
"private",
"properties"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L160-L165 |
Sanji-IO/sanji | sanji/message.py | Message.match | def match(self, route):
"""
Match input route and return new Message instance
with parsed content
"""
_resource = trim_resource(self.resource)
self.method = self.method.lower()
resource_match = route.resource_regex.search(_resource)
if resource_match is None:
return None
# build params and querystring
params = resource_match.groupdict()
querystring = params.pop("querystring", "")
setattr(self, "param", params)
setattr(self, "query", parse_querystring(querystring))
return copy.deepcopy(self) | python | def match(self, route):
"""
Match input route and return new Message instance
with parsed content
"""
_resource = trim_resource(self.resource)
self.method = self.method.lower()
resource_match = route.resource_regex.search(_resource)
if resource_match is None:
return None
# build params and querystring
params = resource_match.groupdict()
querystring = params.pop("querystring", "")
setattr(self, "param", params)
setattr(self, "query", parse_querystring(querystring))
return copy.deepcopy(self) | [
"def",
"match",
"(",
"self",
",",
"route",
")",
":",
"_resource",
"=",
"trim_resource",
"(",
"self",
".",
"resource",
")",
"self",
".",
"method",
"=",
"self",
".",
"method",
".",
"lower",
"(",
")",
"resource_match",
"=",
"route",
".",
"resource_regex",
... | Match input route and return new Message instance
with parsed content | [
"Match",
"input",
"route",
"and",
"return",
"new",
"Message",
"instance",
"with",
"parsed",
"content"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L167-L184 |
Sanji-IO/sanji | sanji/message.py | Message.to_response | def to_response(self, sign, code=200, data=None):
"""
transform message to response message
Notice: this method will return a deepcopy
"""
msg = copy.deepcopy(self)
msg.data = data
setattr(msg, 'code', code)
for _ in ["query", "param", "tunnel"]:
if not hasattr(msg, _):
continue
delattr(msg, _)
if hasattr(msg, 'sign') and isinstance(msg.sign, list):
msg.sign.append(sign)
else:
msg.sign = [sign]
msg._type = Message.get_message_type(msg.__dict__)
return msg | python | def to_response(self, sign, code=200, data=None):
"""
transform message to response message
Notice: this method will return a deepcopy
"""
msg = copy.deepcopy(self)
msg.data = data
setattr(msg, 'code', code)
for _ in ["query", "param", "tunnel"]:
if not hasattr(msg, _):
continue
delattr(msg, _)
if hasattr(msg, 'sign') and isinstance(msg.sign, list):
msg.sign.append(sign)
else:
msg.sign = [sign]
msg._type = Message.get_message_type(msg.__dict__)
return msg | [
"def",
"to_response",
"(",
"self",
",",
"sign",
",",
"code",
"=",
"200",
",",
"data",
"=",
"None",
")",
":",
"msg",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"msg",
".",
"data",
"=",
"data",
"setattr",
"(",
"msg",
",",
"'code'",
",",
"code"... | transform message to response message
Notice: this method will return a deepcopy | [
"transform",
"message",
"to",
"response",
"message",
"Notice",
":",
"this",
"method",
"will",
"return",
"a",
"deepcopy"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L186-L207 |
Sanji-IO/sanji | sanji/message.py | Message.to_event | def to_event(self):
"""
get rid of id, sign, tunnel and update message type
Notice: this method will return a deepcopy
"""
msg = copy.deepcopy(self)
for _ in ["id", "sign", "tunnel", "query", "param"]:
if not hasattr(msg, _):
continue
delattr(msg, _)
msg._type = Message.get_message_type(msg.__dict__)
return msg | python | def to_event(self):
"""
get rid of id, sign, tunnel and update message type
Notice: this method will return a deepcopy
"""
msg = copy.deepcopy(self)
for _ in ["id", "sign", "tunnel", "query", "param"]:
if not hasattr(msg, _):
continue
delattr(msg, _)
msg._type = Message.get_message_type(msg.__dict__)
return msg | [
"def",
"to_event",
"(",
"self",
")",
":",
"msg",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"for",
"_",
"in",
"[",
"\"id\"",
",",
"\"sign\"",
",",
"\"tunnel\"",
",",
"\"query\"",
",",
"\"param\"",
"]",
":",
"if",
"not",
"hasattr",
"(",
"msg",
... | get rid of id, sign, tunnel and update message type
Notice: this method will return a deepcopy | [
"get",
"rid",
"of",
"id",
"sign",
"tunnel",
"and",
"update",
"message",
"type",
"Notice",
":",
"this",
"method",
"will",
"return",
"a",
"deepcopy"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L209-L222 |
Sanji-IO/sanji | sanji/message.py | Message.get_message_type | def get_message_type(message):
"""
Return message's type
"""
for msg_type in MessageType.FIELDS:
if Message.is_type(msg_type, message):
return msg_type
return MessageType.UNKNOWN | python | def get_message_type(message):
"""
Return message's type
"""
for msg_type in MessageType.FIELDS:
if Message.is_type(msg_type, message):
return msg_type
return MessageType.UNKNOWN | [
"def",
"get_message_type",
"(",
"message",
")",
":",
"for",
"msg_type",
"in",
"MessageType",
".",
"FIELDS",
":",
"if",
"Message",
".",
"is_type",
"(",
"msg_type",
",",
"message",
")",
":",
"return",
"msg_type",
"return",
"MessageType",
".",
"UNKNOWN"
] | Return message's type | [
"Return",
"message",
"s",
"type"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L225-L233 |
Sanji-IO/sanji | sanji/message.py | Message.is_type | def is_type(msg_type, msg):
"""
Return message's type is or not
"""
for prop in MessageType.FIELDS[msg_type]["must"]:
if msg.get(prop, False) is False:
return False
for prop in MessageType.FIELDS[msg_type]["prohibit"]:
if msg.get(prop, False) is not False:
return False
return True | python | def is_type(msg_type, msg):
"""
Return message's type is or not
"""
for prop in MessageType.FIELDS[msg_type]["must"]:
if msg.get(prop, False) is False:
return False
for prop in MessageType.FIELDS[msg_type]["prohibit"]:
if msg.get(prop, False) is not False:
return False
return True | [
"def",
"is_type",
"(",
"msg_type",
",",
"msg",
")",
":",
"for",
"prop",
"in",
"MessageType",
".",
"FIELDS",
"[",
"msg_type",
"]",
"[",
"\"must\"",
"]",
":",
"if",
"msg",
".",
"get",
"(",
"prop",
",",
"False",
")",
"is",
"False",
":",
"return",
"Fal... | Return message's type is or not | [
"Return",
"message",
"s",
"type",
"is",
"or",
"not"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L236-L247 |
flowroute/txjason | txjason/service.py | JSONRPCService.add | def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required | python | def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required | [
"def",
"add",
"(",
"self",
",",
"f",
",",
"name",
"=",
"None",
",",
"types",
"=",
"None",
",",
"required",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"fname",
"=",
"f",
".",
"__name__",
"# Register the function using its own name.",
"else",
... | Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments. | [
"Adds",
"a",
"new",
"method",
"to",
"the",
"jsonrpc",
"service",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L108-L137 |
flowroute/txjason | txjason/service.py | JSONRPCService.stopServing | def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None) | python | def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None) | [
"def",
"stopServing",
"(",
"self",
",",
"exception",
"=",
"None",
")",
":",
"if",
"exception",
"is",
"None",
":",
"exception",
"=",
"ServiceUnavailableError",
"self",
".",
"serve_exception",
"=",
"exception",
"if",
"self",
".",
"pending",
":",
"d",
"=",
"s... | Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending. | [
"Returns",
"a",
"deferred",
"that",
"will",
"fire",
"immediately",
"if",
"there",
"are",
"no",
"pending",
"requests",
"otherwise",
"when",
"the",
"last",
"request",
"is",
"removed",
"from",
"self",
".",
"pending",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L139-L151 |
flowroute/txjason | txjason/service.py | JSONRPCService.call | def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result)) | python | def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result)) | [
"def",
"call",
"(",
"self",
",",
"jsondata",
")",
":",
"result",
"=",
"yield",
"self",
".",
"call_py",
"(",
"jsondata",
")",
"if",
"result",
"is",
"None",
":",
"defer",
".",
"returnValue",
"(",
"None",
")",
"else",
":",
"defer",
".",
"returnValue",
"... | Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format | [
"Calls",
"jsonrpc",
"service",
"s",
"method",
"and",
"returns",
"its",
"return",
"value",
"in",
"a",
"JSON",
"string",
"or",
"None",
"if",
"there",
"is",
"none",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L163-L175 |
flowroute/txjason | txjason/service.py | JSONRPCService.call_py | def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc'])) | python | def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc'])) | [
"def",
"call_py",
"(",
"self",
",",
"jsondata",
")",
":",
"try",
":",
"try",
":",
"rdata",
"=",
"json",
".",
"loads",
"(",
"jsondata",
")",
"except",
"ValueError",
":",
"raise",
"ParseError",
"except",
"ParseError",
",",
"e",
":",
"defer",
".",
"return... | Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes. | [
"Calls",
"jsonrpc",
"service",
"s",
"method",
"and",
"returns",
"its",
"return",
"value",
"in",
"python",
"object",
"format",
"or",
"None",
"if",
"there",
"is",
"none",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L178-L263 |
flowroute/txjason | txjason/service.py | JSONRPCService._get_err | def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond | python | def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond | [
"def",
"_get_err",
"(",
"self",
",",
"e",
",",
"id",
"=",
"None",
",",
"jsonrpc",
"=",
"DEFAULT_JSONRPC",
")",
":",
"# Do not respond to notifications when the request is valid.",
"if",
"not",
"id",
"and",
"not",
"isinstance",
"(",
"e",
",",
"ParseError",
")",
... | Returns jsonrpc error message. | [
"Returns",
"jsonrpc",
"error",
"message",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L265-L290 |
flowroute/txjason | txjason/service.py | JSONRPCService._man_args | def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults) | python | def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults) | [
"def",
"_man_args",
"(",
"self",
",",
"f",
")",
":",
"argcount",
"=",
"f",
".",
"func_code",
".",
"co_argcount",
"# account for \"self\" getting passed to class instance methods",
"if",
"isinstance",
"(",
"f",
",",
"types",
".",
"MethodType",
")",
":",
"argcount",... | Returns number of mandatory arguments required by given function. | [
"Returns",
"number",
"of",
"mandatory",
"arguments",
"required",
"by",
"given",
"function",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L312-L325 |
flowroute/txjason | txjason/service.py | JSONRPCService._max_args | def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults) | python | def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults) | [
"def",
"_max_args",
"(",
"self",
",",
"f",
")",
":",
"if",
"f",
".",
"func_defaults",
"is",
"None",
":",
"return",
"f",
".",
"func_code",
".",
"co_argcount",
"return",
"f",
".",
"func_code",
".",
"co_argcount",
"+",
"len",
"(",
"f",
".",
"func_defaults... | Returns maximum number of arguments accepted by given function. | [
"Returns",
"maximum",
"number",
"of",
"arguments",
"accepted",
"by",
"given",
"function",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L327-L334 |
flowroute/txjason | txjason/service.py | JSONRPCService._get_id | def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None | python | def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None | [
"def",
"_get_id",
"(",
"self",
",",
"rdata",
")",
":",
"if",
"'id'",
"in",
"rdata",
":",
"if",
"isinstance",
"(",
"rdata",
"[",
"'id'",
"]",
",",
"basestring",
")",
"or",
"isinstance",
"(",
"rdata",
"[",
"'id'",
"]",
",",
"int",
")",
"or",
"isinsta... | Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type. | [
"Returns",
"jsonrpc",
"request",
"s",
"id",
"value",
"or",
"None",
"if",
"there",
"is",
"none",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L358-L376 |
flowroute/txjason | txjason/service.py | JSONRPCService._get_method | def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method'] | python | def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method'] | [
"def",
"_get_method",
"(",
"self",
",",
"rdata",
")",
":",
"if",
"'method'",
"in",
"rdata",
":",
"if",
"not",
"isinstance",
"(",
"rdata",
"[",
"'method'",
"]",
",",
"basestring",
")",
":",
"raise",
"InvalidRequestError",
"else",
":",
"raise",
"InvalidReque... | Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist. | [
"Returns",
"jsonrpc",
"request",
"s",
"method",
"value",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L378-L395 |
flowroute/txjason | txjason/service.py | JSONRPCService._get_params | def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None | python | def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None | [
"def",
"_get_params",
"(",
"self",
",",
"rdata",
")",
":",
"if",
"'params'",
"in",
"rdata",
":",
"if",
"isinstance",
"(",
"rdata",
"[",
"'params'",
"]",
",",
"dict",
")",
"or",
"isinstance",
"(",
"rdata",
"[",
"'params'",
"]",
",",
"list",
")",
"or",... | Returns a list of jsonrpc request's method parameters. | [
"Returns",
"a",
"list",
"of",
"jsonrpc",
"request",
"s",
"method",
"parameters",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L397-L410 |
flowroute/txjason | txjason/service.py | JSONRPCService._fill_request | def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata) | python | def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata) | [
"def",
"_fill_request",
"(",
"self",
",",
"request",
",",
"rdata",
")",
":",
"if",
"not",
"isinstance",
"(",
"rdata",
",",
"dict",
")",
":",
"raise",
"InvalidRequestError",
"request",
"[",
"'jsonrpc'",
"]",
"=",
"self",
".",
"_get_jsonrpc",
"(",
"rdata",
... | Fills request with data from the jsonrpc call. | [
"Fills",
"request",
"with",
"data",
"from",
"the",
"jsonrpc",
"call",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L412-L420 |
flowroute/txjason | txjason/service.py | JSONRPCService._call_method | def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result) | python | def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result) | [
"def",
"_call_method",
"(",
"self",
",",
"request",
")",
":",
"method",
"=",
"self",
".",
"method_data",
"[",
"request",
"[",
"'method'",
"]",
"]",
"[",
"'method'",
"]",
"params",
"=",
"request",
"[",
"'params'",
"]",
"result",
"=",
"None",
"try",
":",... | Calls given method with given params and returns it value. | [
"Calls",
"given",
"method",
"with",
"given",
"params",
"and",
"returns",
"it",
"value",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L423-L457 |
flowroute/txjason | txjason/service.py | JSONRPCService._handle_request | def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond) | python | def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond) | [
"def",
"_handle_request",
"(",
"self",
",",
"request",
")",
":",
"if",
"'types'",
"in",
"self",
".",
"method_data",
"[",
"request",
"[",
"'method'",
"]",
"]",
":",
"self",
".",
"_validate_params_types",
"(",
"request",
"[",
"'method'",
"]",
",",
"request",... | Handles given request and returns its response. | [
"Handles",
"given",
"request",
"and",
"returns",
"its",
"response",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L465-L505 |
flowroute/txjason | txjason/service.py | JSONRPCService._validate_params_types | def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key)) | python | def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key)) | [
"def",
"_validate_params_types",
"(",
"self",
",",
"method",
",",
"params",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"list",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"method_data",
"[",
"method",
"]",
"[",
"'types'",
"]",
",",
"l... | Validates request's parameter types. | [
"Validates",
"request",
"s",
"parameter",
"types",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L514-L546 |
flowroute/txjason | txjason/service.py | JSONRPCClientService.startService | def startService(self):
"""
Start the service and connect the JSONRPCClientFactory.
"""
self.clientFactory.connect().addErrback(
log.err, 'error starting the JSON-RPC client service %r' % (self,))
service.Service.startService(self) | python | def startService(self):
"""
Start the service and connect the JSONRPCClientFactory.
"""
self.clientFactory.connect().addErrback(
log.err, 'error starting the JSON-RPC client service %r' % (self,))
service.Service.startService(self) | [
"def",
"startService",
"(",
"self",
")",
":",
"self",
".",
"clientFactory",
".",
"connect",
"(",
")",
".",
"addErrback",
"(",
"log",
".",
"err",
",",
"'error starting the JSON-RPC client service %r'",
"%",
"(",
"self",
",",
")",
")",
"service",
".",
"Service... | Start the service and connect the JSONRPCClientFactory. | [
"Start",
"the",
"service",
"and",
"connect",
"the",
"JSONRPCClientFactory",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L560-L566 |
flowroute/txjason | txjason/service.py | JSONRPCClientService.callRemote | def callRemote(self, *a, **kw):
"""
Make a callRemote request of the JSONRPCClientFactory.
"""
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.callRemote(*a, **kw) | python | def callRemote(self, *a, **kw):
"""
Make a callRemote request of the JSONRPCClientFactory.
"""
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.callRemote(*a, **kw) | [
"def",
"callRemote",
"(",
"self",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"defer",
".",
"fail",
"(",
"ServiceStopped",
"(",
")",
")",
"return",
"self",
".",
"clientFactory",
".",
"callRemote",... | Make a callRemote request of the JSONRPCClientFactory. | [
"Make",
"a",
"callRemote",
"request",
"of",
"the",
"JSONRPCClientFactory",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L575-L581 |
flowroute/txjason | txjason/service.py | JSONRPCError.dumps | def dumps(self):
"""Return the Exception data in a format for JSON-RPC."""
error = {'code': self.code,
'message': str(self.message)}
if self.data is not None:
error['data'] = self.data
return error | python | def dumps(self):
"""Return the Exception data in a format for JSON-RPC."""
error = {'code': self.code,
'message': str(self.message)}
if self.data is not None:
error['data'] = self.data
return error | [
"def",
"dumps",
"(",
"self",
")",
":",
"error",
"=",
"{",
"'code'",
":",
"self",
".",
"code",
",",
"'message'",
":",
"str",
"(",
"self",
".",
"message",
")",
"}",
"if",
"self",
".",
"data",
"is",
"not",
"None",
":",
"error",
"[",
"'data'",
"]",
... | Return the Exception data in a format for JSON-RPC. | [
"Return",
"the",
"Exception",
"data",
"in",
"a",
"format",
"for",
"JSON",
"-",
"RPC",
"."
] | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L615-L624 |
shmir/PyIxNetwork | ixnetwork/api/ixn_rest.py | IxnRestWrapper.add | def add(self, parent, obj_type, **attributes):
""" IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: STC object reference.
"""
response = self.post(self.server_url + parent.ref + '/' + obj_type, attributes)
return self._get_href(response.json()) | python | def add(self, parent, obj_type, **attributes):
""" IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: STC object reference.
"""
response = self.post(self.server_url + parent.ref + '/' + obj_type, attributes)
return self._get_href(response.json()) | [
"def",
"add",
"(",
"self",
",",
"parent",
",",
"obj_type",
",",
"*",
"*",
"attributes",
")",
":",
"response",
"=",
"self",
".",
"post",
"(",
"self",
".",
"server_url",
"+",
"parent",
".",
"ref",
"+",
"'/'",
"+",
"obj_type",
",",
"attributes",
")",
... | IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: STC object reference. | [
"IXN",
"API",
"add",
"command"
] | train | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/api/ixn_rest.py#L207-L217 |
karel-brinda/rnftools | rnftools/rnfformat/ReadTuple.py | ReadTuple.stringize | def stringize(
self,
rnf_profile=RnfProfile(),
):
"""Create RNF representation of this read.
Args:
read_tuple_id_width (int): Maximal expected string length of read tuple ID.
genome_id_width (int): Maximal expected string length of genome ID.
chr_id_width (int): Maximal expected string length of chromosome ID.
coor_width (int): Maximal expected string length of a coordinate.
"""
sorted_segments = sorted(self.segments,
key=lambda x: (
x.genome_id * (10 ** 23) +
x.chr_id * (10 ** 21) +
(x.left + (int(x.left == 0) * x.right - 1)) * (10 ** 11) +
x.right * (10 ** 1) +
int(x.direction == "F")
)
)
segments_strings = [x.stringize(rnf_profile) for x in sorted_segments]
read_tuple_name = "__".join(
[
self.prefix,
format(self.read_tuple_id, 'x').zfill(rnf_profile.read_tuple_id_width),
",".join(segments_strings),
self.suffix,
]
)
return read_tuple_name | python | def stringize(
self,
rnf_profile=RnfProfile(),
):
"""Create RNF representation of this read.
Args:
read_tuple_id_width (int): Maximal expected string length of read tuple ID.
genome_id_width (int): Maximal expected string length of genome ID.
chr_id_width (int): Maximal expected string length of chromosome ID.
coor_width (int): Maximal expected string length of a coordinate.
"""
sorted_segments = sorted(self.segments,
key=lambda x: (
x.genome_id * (10 ** 23) +
x.chr_id * (10 ** 21) +
(x.left + (int(x.left == 0) * x.right - 1)) * (10 ** 11) +
x.right * (10 ** 1) +
int(x.direction == "F")
)
)
segments_strings = [x.stringize(rnf_profile) for x in sorted_segments]
read_tuple_name = "__".join(
[
self.prefix,
format(self.read_tuple_id, 'x').zfill(rnf_profile.read_tuple_id_width),
",".join(segments_strings),
self.suffix,
]
)
return read_tuple_name | [
"def",
"stringize",
"(",
"self",
",",
"rnf_profile",
"=",
"RnfProfile",
"(",
")",
",",
")",
":",
"sorted_segments",
"=",
"sorted",
"(",
"self",
".",
"segments",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
".",
"genome_id",
"*",
"(",
"10",
"**",
... | Create RNF representation of this read.
Args:
read_tuple_id_width (int): Maximal expected string length of read tuple ID.
genome_id_width (int): Maximal expected string length of genome ID.
chr_id_width (int): Maximal expected string length of chromosome ID.
coor_width (int): Maximal expected string length of a coordinate. | [
"Create",
"RNF",
"representation",
"of",
"this",
"read",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/rnfformat/ReadTuple.py#L36-L70 |
karel-brinda/rnftools | rnftools/rnfformat/ReadTuple.py | ReadTuple.destringize | def destringize(self, string):
"""Get RNF values for this read from its textual representation and save them
into this object.
Args:
string(str): Textual representation of a read.
Raises:
ValueError
"""
# todo: assert -- starting with (, ending with )
# (prefix,read_tuple_id,segments_t,suffix)=(text).split("__")
# segments=segments_t.split("),(")
m = read_tuple_destr_pattern.match(string)
if not m:
smbl.messages.error(
"'{}' is not a valid read name with respect to the RNF specification".format(string),
program="RNFtools", subprogram="RNF format", exception=ValueError
)
groups = m.groups()
# todo: check number of groups
self.prefix = groups[0]
read_tuple_id = groups[1]
self.read_tuple_id = int(read_tuple_id, 16)
self.segments = []
segments_str = groups[2:-1]
for b_str in segments_str:
if b_str is not None:
if b_str[0] == ",":
b_str = b_str[1:]
b = rnftools.rnfformat.Segment()
b.destringize(b_str)
self.segments.append(b)
self.suffix = groups[-1] | python | def destringize(self, string):
"""Get RNF values for this read from its textual representation and save them
into this object.
Args:
string(str): Textual representation of a read.
Raises:
ValueError
"""
# todo: assert -- starting with (, ending with )
# (prefix,read_tuple_id,segments_t,suffix)=(text).split("__")
# segments=segments_t.split("),(")
m = read_tuple_destr_pattern.match(string)
if not m:
smbl.messages.error(
"'{}' is not a valid read name with respect to the RNF specification".format(string),
program="RNFtools", subprogram="RNF format", exception=ValueError
)
groups = m.groups()
# todo: check number of groups
self.prefix = groups[0]
read_tuple_id = groups[1]
self.read_tuple_id = int(read_tuple_id, 16)
self.segments = []
segments_str = groups[2:-1]
for b_str in segments_str:
if b_str is not None:
if b_str[0] == ",":
b_str = b_str[1:]
b = rnftools.rnfformat.Segment()
b.destringize(b_str)
self.segments.append(b)
self.suffix = groups[-1] | [
"def",
"destringize",
"(",
"self",
",",
"string",
")",
":",
"# todo: assert -- starting with (, ending with )",
"# (prefix,read_tuple_id,segments_t,suffix)=(text).split(\"__\")",
"# segments=segments_t.split(\"),(\")",
"m",
"=",
"read_tuple_destr_pattern",
".",
"match",
"(",
"strin... | Get RNF values for this read from its textual representation and save them
into this object.
Args:
string(str): Textual representation of a read.
Raises:
ValueError | [
"Get",
"RNF",
"values",
"for",
"this",
"read",
"from",
"its",
"textual",
"representation",
"and",
"save",
"them",
"into",
"this",
"object",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/rnfformat/ReadTuple.py#L72-L106 |
bharadwaj-raju/libdesktop | libdesktop/desktopfile.py | construct | def construct(name, exec_, terminal=False, additional_opts={}):
'''Construct a .desktop file and return it as a string.
Create a standards-compliant .desktop file, returning it as a string.
Args:
name (str) : The program's name.
exec\_ (str) : The command.
terminal (bool): Determine if program should be run in a terminal emulator or not. Defaults to ``False``.
additional_opts (dict): Any additional fields.
Returns:
str: The constructed .desktop file.
'''
desktop_file = '[Desktop Entry]\n'
desktop_file_dict = {
'Name': name,
'Exec': exec_,
'Terminal': 'true' if terminal else 'false',
'Comment': additional_opts.get('Comment', name)
}
desktop_file = ('[Desktop Entry]\nName={name}\nExec={exec_}\n'
'Terminal={terminal}\nComment={comment}\n')
desktop_file = desktop_file.format(name=desktop_file_dict['Name'],
exec_=desktop_file_dict['Exec'],
terminal=desktop_file_dict['Terminal'],
comment=desktop_file_dict['Comment'])
if additional_opts is None:
additional_opts = {}
for option in additional_opts:
if not option in desktop_file_dict:
desktop_file += '%s=%s\n' % (option, additional_opts[option])
return desktop_file | python | def construct(name, exec_, terminal=False, additional_opts={}):
'''Construct a .desktop file and return it as a string.
Create a standards-compliant .desktop file, returning it as a string.
Args:
name (str) : The program's name.
exec\_ (str) : The command.
terminal (bool): Determine if program should be run in a terminal emulator or not. Defaults to ``False``.
additional_opts (dict): Any additional fields.
Returns:
str: The constructed .desktop file.
'''
desktop_file = '[Desktop Entry]\n'
desktop_file_dict = {
'Name': name,
'Exec': exec_,
'Terminal': 'true' if terminal else 'false',
'Comment': additional_opts.get('Comment', name)
}
desktop_file = ('[Desktop Entry]\nName={name}\nExec={exec_}\n'
'Terminal={terminal}\nComment={comment}\n')
desktop_file = desktop_file.format(name=desktop_file_dict['Name'],
exec_=desktop_file_dict['Exec'],
terminal=desktop_file_dict['Terminal'],
comment=desktop_file_dict['Comment'])
if additional_opts is None:
additional_opts = {}
for option in additional_opts:
if not option in desktop_file_dict:
desktop_file += '%s=%s\n' % (option, additional_opts[option])
return desktop_file | [
"def",
"construct",
"(",
"name",
",",
"exec_",
",",
"terminal",
"=",
"False",
",",
"additional_opts",
"=",
"{",
"}",
")",
":",
"desktop_file",
"=",
"'[Desktop Entry]\\n'",
"desktop_file_dict",
"=",
"{",
"'Name'",
":",
"name",
",",
"'Exec'",
":",
"exec_",
"... | Construct a .desktop file and return it as a string.
Create a standards-compliant .desktop file, returning it as a string.
Args:
name (str) : The program's name.
exec\_ (str) : The command.
terminal (bool): Determine if program should be run in a terminal emulator or not. Defaults to ``False``.
additional_opts (dict): Any additional fields.
Returns:
str: The constructed .desktop file. | [
"Construct",
"a",
".",
"desktop",
"file",
"and",
"return",
"it",
"as",
"a",
"string",
".",
"Create",
"a",
"standards",
"-",
"compliant",
".",
"desktop",
"file",
"returning",
"it",
"as",
"a",
"string",
".",
"Args",
":",
"name",
"(",
"str",
")",
":",
"... | train | https://github.com/bharadwaj-raju/libdesktop/blob/4d6b815755c76660b6ef4d2db6f54beff38c0db7/libdesktop/desktopfile.py#L33-L69 |
bharadwaj-raju/libdesktop | libdesktop/desktopfile.py | execute | def execute(desktop_file, files=None, return_cmd=False, background=False):
'''Execute a .desktop file.
Executes a given .desktop file path properly.
Args:
desktop_file (str) : The path to the .desktop file.
files (list): Any files to be launched by the .desktop. Defaults to empty list.
return_cmd (bool): Return the command (as ``str``) instead of executing. Defaults to ``False``.
background (bool): Run command in background. Defaults to ``False``.
Returns:
str: Only if ``return_cmd``. Returns command instead of running it. Else returns nothing.
'''
# Attempt to manually parse and execute
desktop_file_exec = parse(desktop_file)['Exec']
for i in desktop_file_exec.split():
if i.startswith('%'):
desktop_file_exec = desktop_file_exec.replace(i, '')
desktop_file_exec = desktop_file_exec.replace(r'%F', '')
desktop_file_exec = desktop_file_exec.replace(r'%f', '')
if files:
for i in files:
desktop_file_exec += ' ' + i
if parse(desktop_file)['Terminal']:
# Use eval and __import__ to bypass a circular dependency
desktop_file_exec = eval(
('__import__("libdesktop").applications.terminal(exec_="%s",'
' keep_open_after_cmd_exec=True, return_cmd=True)') %
desktop_file_exec)
if return_cmd:
return desktop_file_exec
desktop_file_proc = sp.Popen([desktop_file_exec], shell=True)
if not background:
desktop_file_proc.wait() | python | def execute(desktop_file, files=None, return_cmd=False, background=False):
'''Execute a .desktop file.
Executes a given .desktop file path properly.
Args:
desktop_file (str) : The path to the .desktop file.
files (list): Any files to be launched by the .desktop. Defaults to empty list.
return_cmd (bool): Return the command (as ``str``) instead of executing. Defaults to ``False``.
background (bool): Run command in background. Defaults to ``False``.
Returns:
str: Only if ``return_cmd``. Returns command instead of running it. Else returns nothing.
'''
# Attempt to manually parse and execute
desktop_file_exec = parse(desktop_file)['Exec']
for i in desktop_file_exec.split():
if i.startswith('%'):
desktop_file_exec = desktop_file_exec.replace(i, '')
desktop_file_exec = desktop_file_exec.replace(r'%F', '')
desktop_file_exec = desktop_file_exec.replace(r'%f', '')
if files:
for i in files:
desktop_file_exec += ' ' + i
if parse(desktop_file)['Terminal']:
# Use eval and __import__ to bypass a circular dependency
desktop_file_exec = eval(
('__import__("libdesktop").applications.terminal(exec_="%s",'
' keep_open_after_cmd_exec=True, return_cmd=True)') %
desktop_file_exec)
if return_cmd:
return desktop_file_exec
desktop_file_proc = sp.Popen([desktop_file_exec], shell=True)
if not background:
desktop_file_proc.wait() | [
"def",
"execute",
"(",
"desktop_file",
",",
"files",
"=",
"None",
",",
"return_cmd",
"=",
"False",
",",
"background",
"=",
"False",
")",
":",
"# Attempt to manually parse and execute",
"desktop_file_exec",
"=",
"parse",
"(",
"desktop_file",
")",
"[",
"'Exec'",
"... | Execute a .desktop file.
Executes a given .desktop file path properly.
Args:
desktop_file (str) : The path to the .desktop file.
files (list): Any files to be launched by the .desktop. Defaults to empty list.
return_cmd (bool): Return the command (as ``str``) instead of executing. Defaults to ``False``.
background (bool): Run command in background. Defaults to ``False``.
Returns:
str: Only if ``return_cmd``. Returns command instead of running it. Else returns nothing. | [
"Execute",
"a",
".",
"desktop",
"file",
".",
"Executes",
"a",
"given",
".",
"desktop",
"file",
"path",
"properly",
".",
"Args",
":",
"desktop_file",
"(",
"str",
")",
":",
"The",
"path",
"to",
"the",
".",
"desktop",
"file",
".",
"files",
"(",
"list",
... | train | https://github.com/bharadwaj-raju/libdesktop/blob/4d6b815755c76660b6ef4d2db6f54beff38c0db7/libdesktop/desktopfile.py#L72-L112 |
bharadwaj-raju/libdesktop | libdesktop/desktopfile.py | locate | def locate(desktop_filename_or_name):
'''Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the filename of a .desktop file or the name of an application.
Returns:
list: A list of all matching .desktop files found.
'''
paths = [
os.path.expanduser('~/.local/share/applications'),
'/usr/share/applications']
result = []
for path in paths:
for file in os.listdir(path):
if desktop_filename_or_name in file.split(
'.') or desktop_filename_or_name == file:
# Example: org.gnome.gedit
result.append(os.path.join(path, file))
else:
file_parsed = parse(os.path.join(path, file))
try:
if desktop_filename_or_name.lower() == file_parsed[
'Name'].lower():
result.append(file)
elif desktop_filename_or_name.lower() == file_parsed[
'Exec'].split(' ')[0]:
result.append(file)
except KeyError:
pass
for res in result:
if not res.endswith('.desktop'):
result.remove(res)
if not result and not result.endswith('.desktop'):
result.extend(locate(desktop_filename_or_name + '.desktop'))
return result | python | def locate(desktop_filename_or_name):
'''Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the filename of a .desktop file or the name of an application.
Returns:
list: A list of all matching .desktop files found.
'''
paths = [
os.path.expanduser('~/.local/share/applications'),
'/usr/share/applications']
result = []
for path in paths:
for file in os.listdir(path):
if desktop_filename_or_name in file.split(
'.') or desktop_filename_or_name == file:
# Example: org.gnome.gedit
result.append(os.path.join(path, file))
else:
file_parsed = parse(os.path.join(path, file))
try:
if desktop_filename_or_name.lower() == file_parsed[
'Name'].lower():
result.append(file)
elif desktop_filename_or_name.lower() == file_parsed[
'Exec'].split(' ')[0]:
result.append(file)
except KeyError:
pass
for res in result:
if not res.endswith('.desktop'):
result.remove(res)
if not result and not result.endswith('.desktop'):
result.extend(locate(desktop_filename_or_name + '.desktop'))
return result | [
"def",
"locate",
"(",
"desktop_filename_or_name",
")",
":",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.local/share/applications'",
")",
",",
"'/usr/share/applications'",
"]",
"result",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
... | Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the filename of a .desktop file or the name of an application.
Returns:
list: A list of all matching .desktop files found. | [
"Locate",
"a",
".",
"desktop",
"from",
"the",
"standard",
"locations",
".",
"Find",
"the",
"path",
"to",
"the",
".",
"desktop",
"file",
"of",
"a",
"given",
".",
"desktop",
"filename",
"or",
"application",
"name",
".",
"Standard",
"locations",
":",
"-",
"... | train | https://github.com/bharadwaj-raju/libdesktop/blob/4d6b815755c76660b6ef4d2db6f54beff38c0db7/libdesktop/desktopfile.py#L115-L160 |
bharadwaj-raju/libdesktop | libdesktop/desktopfile.py | parse | def parse(desktop_file_or_string):
'''Parse a .desktop file.
Parse a .desktop file or a string with its contents into an easy-to-use dict, with standard values present even if not defined in file.
Args:
desktop_file_or_string (str): Either the path to a .desktop file or a string with a .desktop file as its contents.
Returns:
dict: A dictionary of the parsed file.'''
if os.path.isfile(desktop_file_or_string):
with open(desktop_file_or_string) as f:
desktop_file = f.read()
else:
desktop_file = desktop_file_or_string
result = {}
for line in desktop_file.split('\n'):
if '=' in line:
result[line.split('=')[0]] = line.split('=')[1]
for key, value in result.items():
if value == 'false':
result[key] = False
elif value == 'true':
result[key] = True
if not 'Terminal' in result:
result['Terminal'] = False
if not 'Hidden' in result:
result['Hidden'] = False
return result | python | def parse(desktop_file_or_string):
'''Parse a .desktop file.
Parse a .desktop file or a string with its contents into an easy-to-use dict, with standard values present even if not defined in file.
Args:
desktop_file_or_string (str): Either the path to a .desktop file or a string with a .desktop file as its contents.
Returns:
dict: A dictionary of the parsed file.'''
if os.path.isfile(desktop_file_or_string):
with open(desktop_file_or_string) as f:
desktop_file = f.read()
else:
desktop_file = desktop_file_or_string
result = {}
for line in desktop_file.split('\n'):
if '=' in line:
result[line.split('=')[0]] = line.split('=')[1]
for key, value in result.items():
if value == 'false':
result[key] = False
elif value == 'true':
result[key] = True
if not 'Terminal' in result:
result['Terminal'] = False
if not 'Hidden' in result:
result['Hidden'] = False
return result | [
"def",
"parse",
"(",
"desktop_file_or_string",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"desktop_file_or_string",
")",
":",
"with",
"open",
"(",
"desktop_file_or_string",
")",
"as",
"f",
":",
"desktop_file",
"=",
"f",
".",
"read",
"(",
")",
... | Parse a .desktop file.
Parse a .desktop file or a string with its contents into an easy-to-use dict, with standard values present even if not defined in file.
Args:
desktop_file_or_string (str): Either the path to a .desktop file or a string with a .desktop file as its contents.
Returns:
dict: A dictionary of the parsed file. | [
"Parse",
"a",
".",
"desktop",
"file",
".",
"Parse",
"a",
".",
"desktop",
"file",
"or",
"a",
"string",
"with",
"its",
"contents",
"into",
"an",
"easy",
"-",
"to",
"-",
"use",
"dict",
"with",
"standard",
"values",
"present",
"even",
"if",
"not",
"defined... | train | https://github.com/bharadwaj-raju/libdesktop/blob/4d6b815755c76660b6ef4d2db6f54beff38c0db7/libdesktop/desktopfile.py#L163-L196 |
saghul/evergreen | evergreen/futures/_base.py | as_completed | def as_completed(fs, timeout=None):
"""An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator that yields the given Futures as they complete (finished or
cancelled).
Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
"""
with _AcquireFutures(fs):
finished = set(f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
pending = set(fs) - finished
waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
timer = Timeout(timeout)
timer.start()
try:
for future in finished:
yield future
while pending:
waiter.event.wait()
with waiter.lock:
finished = waiter.finished_futures
waiter.finished_futures = []
waiter.event.clear()
for future in finished:
yield future
pending.remove(future)
except Timeout as e:
if timer is not e:
raise
raise TimeoutError('%d (of %d) futures unfinished' % (len(pending), len(fs)))
finally:
timer.cancel()
for f in fs:
f._waiters.remove(waiter) | python | def as_completed(fs, timeout=None):
"""An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator that yields the given Futures as they complete (finished or
cancelled).
Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
"""
with _AcquireFutures(fs):
finished = set(f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
pending = set(fs) - finished
waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
timer = Timeout(timeout)
timer.start()
try:
for future in finished:
yield future
while pending:
waiter.event.wait()
with waiter.lock:
finished = waiter.finished_futures
waiter.finished_futures = []
waiter.event.clear()
for future in finished:
yield future
pending.remove(future)
except Timeout as e:
if timer is not e:
raise
raise TimeoutError('%d (of %d) futures unfinished' % (len(pending), len(fs)))
finally:
timer.cancel()
for f in fs:
f._waiters.remove(waiter) | [
"def",
"as_completed",
"(",
"fs",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"_AcquireFutures",
"(",
"fs",
")",
":",
"finished",
"=",
"set",
"(",
"f",
"for",
"f",
"in",
"fs",
"if",
"f",
".",
"_state",
"in",
"[",
"CANCELLED_AND_NOTIFIED",
",",
"FI... | An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator that yields the given Futures as they complete (finished or
cancelled).
Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout. | [
"An",
"iterator",
"over",
"the",
"given",
"futures",
"that",
"yields",
"each",
"as",
"it",
"completes",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/futures/_base.py#L180-L223 |
saghul/evergreen | evergreen/futures/_base.py | Executor.map | def map(self, fn, *iterables, **kwargs):
"""Returns a iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.
Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
loop = evergreen.current.loop
timeout = kwargs.get('timeout')
if timeout is not None:
end_time = timeout + loop.time()
fs = [self.submit(fn, *args) for args in zip(*iterables)]
# Yield must be hidden in closure so that the futures are submitted
# before the first iterator value is required.
def result_iterator():
try:
for future in fs:
if timeout is None:
yield future.get()
else:
yield future.get(end_time - loop.time())
finally:
for future in fs:
future.cancel()
return result_iterator() | python | def map(self, fn, *iterables, **kwargs):
"""Returns a iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.
Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
loop = evergreen.current.loop
timeout = kwargs.get('timeout')
if timeout is not None:
end_time = timeout + loop.time()
fs = [self.submit(fn, *args) for args in zip(*iterables)]
# Yield must be hidden in closure so that the futures are submitted
# before the first iterator value is required.
def result_iterator():
try:
for future in fs:
if timeout is None:
yield future.get()
else:
yield future.get(end_time - loop.time())
finally:
for future in fs:
future.cancel()
return result_iterator() | [
"def",
"map",
"(",
"self",
",",
"fn",
",",
"*",
"iterables",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"evergreen",
".",
"current",
".",
"loop",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
")",
"if",
"timeout",
"is",
"not",
"None"... | Returns a iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.
Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values. | [
"Returns",
"a",
"iterator",
"equivalent",
"to",
"map",
"(",
"fn",
"iter",
")",
"."
] | train | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/futures/_base.py#L409-L447 |
20c/vodka | vodka/plugins/wsgi.py | WSGIPlugin.set_server | def set_server(self, wsgi_app, fnc_serve=None):
"""
figures out how the wsgi application is to be served
according to config
"""
self.set_wsgi_app(wsgi_app)
ssl_config = self.get_config("ssl")
ssl_context = {}
if self.get_config("server") == "gevent":
if ssl_config.get("enabled"):
ssl_context["certfile"] = ssl_config.get("cert")
ssl_context["keyfile"] = ssl_config.get("key")
from gevent.pywsgi import WSGIServer
http_server = WSGIServer(
(self.host, self.port),
wsgi_app,
**ssl_context
)
self.log.debug("Serving WSGI via gevent.pywsgi.WSGIServer")
fnc_serve = http_server.serve_forever
elif self.get_config("server") == "uwsgi":
self.pluginmgr_config["start_manual"] = True
elif self.get_config("server") == "gunicorn":
self.pluginmgr_config["start_manual"] = True
elif self.get_config("server") == "self":
fnc_serve = self.run
# figure out async handler
if self.get_config("async") == "gevent":
# handle async via gevent
import gevent
self.log.debug("Handling wsgi on gevent")
self.worker = gevent.spawn(fnc_serve)
elif self.get_config("async") == "thread":
self.worker = fnc_serve
else:
self.worker = fnc_serve | python | def set_server(self, wsgi_app, fnc_serve=None):
"""
figures out how the wsgi application is to be served
according to config
"""
self.set_wsgi_app(wsgi_app)
ssl_config = self.get_config("ssl")
ssl_context = {}
if self.get_config("server") == "gevent":
if ssl_config.get("enabled"):
ssl_context["certfile"] = ssl_config.get("cert")
ssl_context["keyfile"] = ssl_config.get("key")
from gevent.pywsgi import WSGIServer
http_server = WSGIServer(
(self.host, self.port),
wsgi_app,
**ssl_context
)
self.log.debug("Serving WSGI via gevent.pywsgi.WSGIServer")
fnc_serve = http_server.serve_forever
elif self.get_config("server") == "uwsgi":
self.pluginmgr_config["start_manual"] = True
elif self.get_config("server") == "gunicorn":
self.pluginmgr_config["start_manual"] = True
elif self.get_config("server") == "self":
fnc_serve = self.run
# figure out async handler
if self.get_config("async") == "gevent":
# handle async via gevent
import gevent
self.log.debug("Handling wsgi on gevent")
self.worker = gevent.spawn(fnc_serve)
elif self.get_config("async") == "thread":
self.worker = fnc_serve
else:
self.worker = fnc_serve | [
"def",
"set_server",
"(",
"self",
",",
"wsgi_app",
",",
"fnc_serve",
"=",
"None",
")",
":",
"self",
".",
"set_wsgi_app",
"(",
"wsgi_app",
")",
"ssl_config",
"=",
"self",
".",
"get_config",
"(",
"\"ssl\"",
")",
"ssl_context",
"=",
"{",
"}",
"if",
"self",
... | figures out how the wsgi application is to be served
according to config | [
"figures",
"out",
"how",
"the",
"wsgi",
"application",
"is",
"to",
"be",
"served",
"according",
"to",
"config"
] | train | https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/plugins/wsgi.py#L125-L180 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.