repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
sprockets/sprockets.clients.cassandra
sprockets/clients/cassandra/__init__.py
CassandraConnection._callback
def _callback(self, cassandra_future, tornado_future): """Cassandra async I/O loop callback handler.""" try: result = cassandra_future.result() except Exception as exc: return tornado_future.set_exception(exc) tornado_future.set_result(result)
python
def _callback(self, cassandra_future, tornado_future): """Cassandra async I/O loop callback handler.""" try: result = cassandra_future.result() except Exception as exc: return tornado_future.set_exception(exc) tornado_future.set_result(result)
[ "def", "_callback", "(", "self", ",", "cassandra_future", ",", "tornado_future", ")", ":", "try", ":", "result", "=", "cassandra_future", ".", "result", "(", ")", "except", "Exception", "as", "exc", ":", "return", "tornado_future", ".", "set_exception", "(", ...
Cassandra async I/O loop callback handler.
[ "Cassandra", "async", "I", "/", "O", "loop", "callback", "handler", "." ]
train
https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L121-L127
cdeboever3/cdpybio
cdpybio/plink.py
read_linear2
def read_linear2(fn, header=True): """Read a plink 2 output file of type glm.linear into a pandas DataFrame. Parameters ---------- fn : str Path to the plink file. The file can be gzipped or not. header : str True if the file has a header (this is generally the case unless the ...
python
def read_linear2(fn, header=True): """Read a plink 2 output file of type glm.linear into a pandas DataFrame. Parameters ---------- fn : str Path to the plink file. The file can be gzipped or not. header : str True if the file has a header (this is generally the case unless the ...
[ "def", "read_linear2", "(", "fn", ",", "header", "=", "True", ")", ":", "dtypes", "=", "{", "'#CHROM'", ":", "str", ",", "'POS'", ":", "int", ",", "'ID'", ":", "str", ",", "'REF'", ":", "str", ",", "'ALT1'", ":", "str", ",", "'TEST'", ":", "str",...
Read a plink 2 output file of type glm.linear into a pandas DataFrame. Parameters ---------- fn : str Path to the plink file. The file can be gzipped or not. header : str True if the file has a header (this is generally the case unless the file has been processed after it was ...
[ "Read", "a", "plink", "2", "output", "file", "of", "type", "glm", ".", "linear", "into", "a", "pandas", "DataFrame", "." ]
train
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/plink.py#L6-L45
cdeboever3/cdpybio
cdpybio/plink.py
parse_log2
def parse_log2(fn): """Parse out some information from a plink 2 log. This function currently only supports log files from linear or logistic regression. Parameters ---------- fn : str Path to the plink log file. Returns ------- res : pandas.DataFrame Dataframe with lo...
python
def parse_log2(fn): """Parse out some information from a plink 2 log. This function currently only supports log files from linear or logistic regression. Parameters ---------- fn : str Path to the plink log file. Returns ------- res : pandas.DataFrame Dataframe with lo...
[ "def", "parse_log2", "(", "fn", ")", ":", "with", "open", "(", "fn", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "if", "len", "(", "lines", ")", "==", "0", ":", "sys", ".", "stderr", ".", "write", "(", "'Empty log file: {}...
Parse out some information from a plink 2 log. This function currently only supports log files from linear or logistic regression. Parameters ---------- fn : str Path to the plink log file. Returns ------- res : pandas.DataFrame Dataframe with log file information.
[ "Parse", "out", "some", "information", "from", "a", "plink", "2", "log", ".", "This", "function", "currently", "only", "supports", "log", "files", "from", "linear", "or", "logistic", "regression", "." ]
train
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/plink.py#L99-L151
shaypal5/pdutil
pdutil/transform/transform.py
x_y_by_col_lbl
def x_y_by_col_lbl(df, y_col_lbl): """Returns an X dataframe and a y series by the given column name. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object The label of the y column. Returns ------- X, y : pandas.DataFrame, pandas.Series...
python
def x_y_by_col_lbl(df, y_col_lbl): """Returns an X dataframe and a y series by the given column name. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object The label of the y column. Returns ------- X, y : pandas.DataFrame, pandas.Series...
[ "def", "x_y_by_col_lbl", "(", "df", ",", "y_col_lbl", ")", ":", "x_cols", "=", "[", "col", "for", "col", "in", "df", ".", "columns", "if", "col", "!=", "y_col_lbl", "]", "return", "df", "[", "x_cols", "]", ",", "df", "[", "y_col_lbl", "]" ]
Returns an X dataframe and a y series by the given column name. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object The label of the y column. Returns ------- X, y : pandas.DataFrame, pandas.Series A dataframe made up of all column...
[ "Returns", "an", "X", "dataframe", "and", "a", "y", "series", "by", "the", "given", "column", "name", "." ]
train
https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/transform/transform.py#L4-L36
shaypal5/pdutil
pdutil/transform/transform.py
x_y_by_col_lbl_inplace
def x_y_by_col_lbl_inplace(df, y_col_lbl): """Breaks the given dataframe into an X frame and a y series by the given column name. The original frame is returned, without the y series column, as the X frame, so no new dataframes are created. Parameters ---------- df : pandas.DataFrame ...
python
def x_y_by_col_lbl_inplace(df, y_col_lbl): """Breaks the given dataframe into an X frame and a y series by the given column name. The original frame is returned, without the y series column, as the X frame, so no new dataframes are created. Parameters ---------- df : pandas.DataFrame ...
[ "def", "x_y_by_col_lbl_inplace", "(", "df", ",", "y_col_lbl", ")", ":", "y", "=", "df", "[", "y_col_lbl", "]", "df", ".", "drop", "(", "labels", "=", "y_col_lbl", ",", "axis", "=", "1", ",", "inplace", "=", "True", ",", ")", "return", "df", ",", "y...
Breaks the given dataframe into an X frame and a y series by the given column name. The original frame is returned, without the y series column, as the X frame, so no new dataframes are created. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object...
[ "Breaks", "the", "given", "dataframe", "into", "an", "X", "frame", "and", "a", "y", "series", "by", "the", "given", "column", "name", "." ]
train
https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/transform/transform.py#L39-L80
shaypal5/pdutil
pdutil/transform/transform.py
or_by_masks
def or_by_masks(df, masks): """Returns a sub-dataframe by the logical or over the given masks. Parameters ---------- df : pandas.DataFrame The dataframe to take a subframe of. masks : list A list of pandas.Series of dtype bool, indexed identically to the given dataframe. ...
python
def or_by_masks(df, masks): """Returns a sub-dataframe by the logical or over the given masks. Parameters ---------- df : pandas.DataFrame The dataframe to take a subframe of. masks : list A list of pandas.Series of dtype bool, indexed identically to the given dataframe. ...
[ "def", "or_by_masks", "(", "df", ",", "masks", ")", ":", "if", "len", "(", "masks", ")", "<", "1", ":", "return", "df", "if", "len", "(", "masks", ")", "==", "1", ":", "return", "df", "[", "masks", "[", "0", "]", "]", "overall_mask", "=", "mask...
Returns a sub-dataframe by the logical or over the given masks. Parameters ---------- df : pandas.DataFrame The dataframe to take a subframe of. masks : list A list of pandas.Series of dtype bool, indexed identically to the given dataframe. Returns ------- pandas.Da...
[ "Returns", "a", "sub", "-", "dataframe", "by", "the", "logical", "or", "over", "the", "given", "masks", "." ]
train
https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/transform/transform.py#L83-L118
kevwo/alt
alt/http.py
invoke_rest_method
def invoke_rest_method(**kwargs): """ Invokes a rest api test :param kwargs: REQUIRED: method = 'GET', 'POST', 'PUT', 'DELETE' url = "http://localhost/api/controller" or baseurl = "http://localhost/" endpoint = "api/co...
python
def invoke_rest_method(**kwargs): """ Invokes a rest api test :param kwargs: REQUIRED: method = 'GET', 'POST', 'PUT', 'DELETE' url = "http://localhost/api/controller" or baseurl = "http://localhost/" endpoint = "api/co...
[ "def", "invoke_rest_method", "(", "*", "*", "kwargs", ")", ":", "logger", "=", "kwargs", ".", "get", "(", "'logger'", ",", "get_default_logger", "(", ")", ")", "args", "=", "{", "}", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "{", "...
Invokes a rest api test :param kwargs: REQUIRED: method = 'GET', 'POST', 'PUT', 'DELETE' url = "http://localhost/api/controller" or baseurl = "http://localhost/" endpoint = "api/controller" OPTIONAL: headers ...
[ "Invokes", "a", "rest", "api", "test", ":", "param", "kwargs", ":", "REQUIRED", ":" ]
train
https://github.com/kevwo/alt/blob/141e2b127eecbb843721e16e5b413577353ac83f/alt/http.py#L6-L63
MacHu-GWU/angora-project
angora/visual/timeseries.py
plot_one_day
def plot_one_day(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一天。 major tick = every hours minor tick = every 15 minutes """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) hours = HourLocator(range(24)) ...
python
def plot_one_day(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一天。 major tick = every hours minor tick = every 15 minutes """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) hours = HourLocator(range(24)) ...
[ "def", "plot_one_day", "(", "x", ",", "y", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "title", "=", "None", ",", "ylim", "=", "None", ")", ":", "plt", ".", "close", "(", "\"all\"", ")", "fig", "=", "plt", ".", "figure", "(", "...
时间跨度为一天。 major tick = every hours minor tick = every 15 minutes
[ "时间跨度为一天。", "major", "tick", "=", "every", "hours", "minor", "tick", "=", "every", "15", "minutes" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/visual/timeseries.py#L36-L84
MacHu-GWU/angora-project
angora/visual/timeseries.py
plot_one_month
def plot_one_month(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一月。 major tick = every days """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) days = DayLocator(range(365)) daysFmt = DateFormatter("%Y-%m-...
python
def plot_one_month(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一月。 major tick = every days """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) days = DayLocator(range(365)) daysFmt = DateFormatter("%Y-%m-...
[ "def", "plot_one_month", "(", "x", ",", "y", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "title", "=", "None", ",", "ylim", "=", "None", ")", ":", "plt", ".", "close", "(", "\"all\"", ")", "fig", "=", "plt", ".", "figure", "(", ...
时间跨度为一月。 major tick = every days
[ "时间跨度为一月。", "major", "tick", "=", "every", "days" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/visual/timeseries.py#L136-L179
MacHu-GWU/angora-project
angora/visual/timeseries.py
plot_one_quarter
def plot_one_quarter(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一年。 major tick = every months minor tick = every 15th day in a month """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) months = MonthLocat...
python
def plot_one_quarter(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一年。 major tick = every months minor tick = every 15th day in a month """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) months = MonthLocat...
[ "def", "plot_one_quarter", "(", "x", ",", "y", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "title", "=", "None", ",", "ylim", "=", "None", ")", ":", "plt", ".", "close", "(", "\"all\"", ")", "fig", "=", "plt", ".", "figure", "(",...
时间跨度为一年。 major tick = every months minor tick = every 15th day in a month
[ "时间跨度为一年。", "major", "tick", "=", "every", "months", "minor", "tick", "=", "every", "15th", "day", "in", "a", "month" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/visual/timeseries.py#L181-L229
MacHu-GWU/angora-project
angora/visual/timeseries.py
visualize
def visualize(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """A universal function plot arbitrary time series data. """ total_seconds = (x[-1] - x[0]).total_seconds() if total_seconds <= 86400 * 1 * 3: return plot_one_day(x, y, xlabel, ylabel, title, ylim) elif total_seconds ...
python
def visualize(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """A universal function plot arbitrary time series data. """ total_seconds = (x[-1] - x[0]).total_seconds() if total_seconds <= 86400 * 1 * 3: return plot_one_day(x, y, xlabel, ylabel, title, ylim) elif total_seconds ...
[ "def", "visualize", "(", "x", ",", "y", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "title", "=", "None", ",", "ylim", "=", "None", ")", ":", "total_seconds", "=", "(", "x", "[", "-", "1", "]", "-", "x", "[", "0", "]", ")", ...
A universal function plot arbitrary time series data.
[ "A", "universal", "function", "plot", "arbitrary", "time", "series", "data", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/visual/timeseries.py#L281-L298
andy-esch/sqterritory
sqterritory/territory.py
compactness_frompts
def compactness_frompts(geoseries): """ Inverse of 4 * pi * Area / perimeter^2 """ measure = ( 4 * 3.1415 * ( (geoseries.unary_union).convex_hull.area) ) / ( (geoseries.unary_union).convex_hull.length ) return measure
python
def compactness_frompts(geoseries): """ Inverse of 4 * pi * Area / perimeter^2 """ measure = ( 4 * 3.1415 * ( (geoseries.unary_union).convex_hull.area) ) / ( (geoseries.unary_union).convex_hull.length ) return measure
[ "def", "compactness_frompts", "(", "geoseries", ")", ":", "measure", "=", "(", "4", "*", "3.1415", "*", "(", "(", "geoseries", ".", "unary_union", ")", ".", "convex_hull", ".", "area", ")", ")", "/", "(", "(", "geoseries", ".", "unary_union", ")", ".",...
Inverse of 4 * pi * Area / perimeter^2
[ "Inverse", "of", "4", "*", "pi", "*", "Area", "/", "perimeter^2" ]
train
https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L28-L38
andy-esch/sqterritory
sqterritory/territory.py
MinCostFlow._get_target_nearest
def _get_target_nearest(self): """Get nearest target for each origin""" reps_query = """ SELECT DISTINCT ON(g2.cartodb_id) g1.cartodb_id As origin_id, g2.the_geom, g2.cartodb_id + {maxorigin} as cartodb_id, g2.the_geom_webm...
python
def _get_target_nearest(self): """Get nearest target for each origin""" reps_query = """ SELECT DISTINCT ON(g2.cartodb_id) g1.cartodb_id As origin_id, g2.the_geom, g2.cartodb_id + {maxorigin} as cartodb_id, g2.the_geom_webm...
[ "def", "_get_target_nearest", "(", "self", ")", ":", "reps_query", "=", "\"\"\"\n SELECT DISTINCT ON(g2.cartodb_id)\n g1.cartodb_id As origin_id,\n g2.the_geom,\n g2.cartodb_id + {maxorigin} as cartodb_id,\n g2.the_geom_webm...
Get nearest target for each origin
[ "Get", "nearest", "target", "for", "each", "origin" ]
train
https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L74-L102
andy-esch/sqterritory
sqterritory/territory.py
MinCostFlow._get_demand_graph
def _get_demand_graph(self): """create demand graph""" # The number of clusters K = self.origins.shape[0] # Set the number of accounts in each cluster to be the same # as for the nearest neighbor solution demand = self.nearest_targets.groupby('origin_id')['geometry'].cou...
python
def _get_demand_graph(self): """create demand graph""" # The number of clusters K = self.origins.shape[0] # Set the number of accounts in each cluster to be the same # as for the nearest neighbor solution demand = self.nearest_targets.groupby('origin_id')['geometry'].cou...
[ "def", "_get_demand_graph", "(", "self", ")", ":", "# The number of clusters", "K", "=", "self", ".", "origins", ".", "shape", "[", "0", "]", "# Set the number of accounts in each cluster to be the same", "# as for the nearest neighbor solution", "demand", "=", "self", "....
create demand graph
[ "create", "demand", "graph" ]
train
https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L104-L137
andy-esch/sqterritory
sqterritory/territory.py
MinCostFlow.calc
def calc(self, maxiter=100, fixedprec=1e9): """Min Cost Flow""" source_data_holder = [] N = self.targets.shape[0] K = self.origins.shape[0] # dict of labels for each target node M, demand = self._get_demand_graph() max_dist_trip = 400 # kilometers cost_...
python
def calc(self, maxiter=100, fixedprec=1e9): """Min Cost Flow""" source_data_holder = [] N = self.targets.shape[0] K = self.origins.shape[0] # dict of labels for each target node M, demand = self._get_demand_graph() max_dist_trip = 400 # kilometers cost_...
[ "def", "calc", "(", "self", ",", "maxiter", "=", "100", ",", "fixedprec", "=", "1e9", ")", ":", "source_data_holder", "=", "[", "]", "N", "=", "self", ".", "targets", ".", "shape", "[", "0", "]", "K", "=", "self", ".", "origins", ".", "shape", "[...
Min Cost Flow
[ "Min", "Cost", "Flow" ]
train
https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L139-L278
andy-esch/sqterritory
sqterritory/territory.py
MinCostFlow.results_to_table
def results_to_table(self): """Process self.results and send to carto table""" # Get Labels baseline_labels = self.nearest_targets['origin_id'].values mcf_labels = self.results['model_labels']['labels'].values # Create the outcomes outcome = pd.DataFrame({ ...
python
def results_to_table(self): """Process self.results and send to carto table""" # Get Labels baseline_labels = self.nearest_targets['origin_id'].values mcf_labels = self.results['model_labels']['labels'].values # Create the outcomes outcome = pd.DataFrame({ ...
[ "def", "results_to_table", "(", "self", ")", ":", "# Get Labels", "baseline_labels", "=", "self", ".", "nearest_targets", "[", "'origin_id'", "]", ".", "values", "mcf_labels", "=", "self", ".", "results", "[", "'model_labels'", "]", "[", "'labels'", "]", ".", ...
Process self.results and send to carto table
[ "Process", "self", ".", "results", "and", "send", "to", "carto", "table" ]
train
https://github.com/andy-esch/sqterritory/blob/53bcf7c8946f5d216d1ceccf55f9f339125b8205/sqterritory/territory.py#L280-L324
briancappello/flask-sqlalchemy-bundle
flask_sqlalchemy_bundle/meta/model_meta_factory.py
ModelMetaFactory._get_model_meta_options
def _get_model_meta_options(self) -> List[MetaOption]: """" Define fields allowed in the Meta class on end-user models, and the behavior of each. Custom ModelMetaOptions classes should override this method to customize the options supported on class Meta of end-user models. ...
python
def _get_model_meta_options(self) -> List[MetaOption]: """" Define fields allowed in the Meta class on end-user models, and the behavior of each. Custom ModelMetaOptions classes should override this method to customize the options supported on class Meta of end-user models. ...
[ "def", "_get_model_meta_options", "(", "self", ")", "->", "List", "[", "MetaOption", "]", ":", "# we can't use current_app to determine if we're under test, because it", "# doesn't exist yet", "testing_options", "=", "(", "[", "]", "if", "os", ".", "getenv", "(", "'FLAS...
Define fields allowed in the Meta class on end-user models, and the behavior of each. Custom ModelMetaOptions classes should override this method to customize the options supported on class Meta of end-user models.
[ "Define", "fields", "allowed", "in", "the", "Meta", "class", "on", "end", "-", "user", "models", "and", "the", "behavior", "of", "each", "." ]
train
https://github.com/briancappello/flask-sqlalchemy-bundle/blob/8150896787907ef0001839b5a6ef303edccb9b6c/flask_sqlalchemy_bundle/meta/model_meta_factory.py#L30-L63
rjw57/throw
throw/minus/minus.py
CreateGallery
def CreateGallery(): """Creates a Gallery on the server. Returns a Gallery object with the editor_id and reader_id. """ url = 'http://min.us/api/CreateGallery' response = _dopost(url) _editor_id = response["editor_id"] _reader_id = response["reader_id"] return Gallery(_reader_id, edi...
python
def CreateGallery(): """Creates a Gallery on the server. Returns a Gallery object with the editor_id and reader_id. """ url = 'http://min.us/api/CreateGallery' response = _dopost(url) _editor_id = response["editor_id"] _reader_id = response["reader_id"] return Gallery(_reader_id, edi...
[ "def", "CreateGallery", "(", ")", ":", "url", "=", "'http://min.us/api/CreateGallery'", "response", "=", "_dopost", "(", "url", ")", "_editor_id", "=", "response", "[", "\"editor_id\"", "]", "_reader_id", "=", "response", "[", "\"reader_id\"", "]", "return", "Ga...
Creates a Gallery on the server. Returns a Gallery object with the editor_id and reader_id.
[ "Creates", "a", "Gallery", "on", "the", "server", ".", "Returns", "a", "Gallery", "object", "with", "the", "editor_id", "and", "reader_id", "." ]
train
https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/minus/minus.py#L102-L114
rjw57/throw
throw/minus/minus.py
UploadItem
def UploadItem(filename, gallery, desiredName=None, progress_cb=None): """filename is the full file location and name of the file WARNING: If your desiredName doesn't have a proper file extension (SHOULD be the same as the filename) it'll still upload, but you won't be able to download it or view it onl...
python
def UploadItem(filename, gallery, desiredName=None, progress_cb=None): """filename is the full file location and name of the file WARNING: If your desiredName doesn't have a proper file extension (SHOULD be the same as the filename) it'll still upload, but you won't be able to download it or view it onl...
[ "def", "UploadItem", "(", "filename", ",", "gallery", ",", "desiredName", "=", "None", ",", "progress_cb", "=", "None", ")", ":", "# Must have the ? because urlencode doesn't add that on itself", "url", "=", "'http://min.us/api/UploadItem?'", "if", "desiredName", ":", "...
filename is the full file location and name of the file WARNING: If your desiredName doesn't have a proper file extension (SHOULD be the same as the filename) it'll still upload, but you won't be able to download it or view it online. You can edit the name later to add the extension, but be careful, bec...
[ "filename", "is", "the", "full", "file", "location", "and", "name", "of", "the", "file", "WARNING", ":", "If", "your", "desiredName", "doesn", "t", "have", "a", "proper", "file", "extension", "(", "SHOULD", "be", "the", "same", "as", "the", "filename", "...
train
https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/minus/minus.py#L117-L153
rjw57/throw
throw/minus/minus.py
_dopost
def _dopost(url, params=None, payload=None, progress_cb=None): """Do a HTTP post to upload some data. If progress_cb is not None, it should be a callable which takes two arguments: the total number of bytes to upload and the number of bytes which have been uploaded. The callable is called periodically t...
python
def _dopost(url, params=None, payload=None, progress_cb=None): """Do a HTTP post to upload some data. If progress_cb is not None, it should be a callable which takes two arguments: the total number of bytes to upload and the number of bytes which have been uploaded. The callable is called periodically t...
[ "def", "_dopost", "(", "url", ",", "params", "=", "None", ",", "payload", "=", "None", ",", "progress_cb", "=", "None", ")", ":", "if", "params", ":", "encoded", "=", "urlencode", "(", "params", ")", "else", ":", "encoded", "=", "''", "url", "=", "...
Do a HTTP post to upload some data. If progress_cb is not None, it should be a callable which takes two arguments: the total number of bytes to upload and the number of bytes which have been uploaded. The callable is called periodically to show the progress of the upload.
[ "Do", "a", "HTTP", "post", "to", "upload", "some", "data", ".", "If", "progress_cb", "is", "not", "None", "it", "should", "be", "a", "callable", "which", "takes", "two", "arguments", ":", "the", "total", "number", "of", "bytes", "to", "upload", "and", ...
train
https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/minus/minus.py#L160-L210
rjw57/throw
throw/minus/minus.py
Gallery.GetItems
def GetItems(self): """Updates self.name and self.items and returns (self.name, self.items)""" url = 'http://min.us/api/GetItems/' + 'm' + self.reader_id response = _doget(url) self.name = response["GALLERY_TITLE"] # To get the item id, we have to take the file name from the UR...
python
def GetItems(self): """Updates self.name and self.items and returns (self.name, self.items)""" url = 'http://min.us/api/GetItems/' + 'm' + self.reader_id response = _doget(url) self.name = response["GALLERY_TITLE"] # To get the item id, we have to take the file name from the UR...
[ "def", "GetItems", "(", "self", ")", ":", "url", "=", "'http://min.us/api/GetItems/'", "+", "'m'", "+", "self", ".", "reader_id", "response", "=", "_doget", "(", "url", ")", "self", ".", "name", "=", "response", "[", "\"GALLERY_TITLE\"", "]", "# To get the i...
Updates self.name and self.items and returns (self.name, self.items)
[ "Updates", "self", ".", "name", "and", "self", ".", "items", "and", "returns", "(", "self", ".", "name", "self", ".", "items", ")" ]
train
https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/minus/minus.py#L48-L59
rjw57/throw
throw/minus/minus.py
Gallery.SaveGallery
def SaveGallery(self, name=None, items=None): """Use this to update the gallery name or change sort order. Specify which attribute (name or items or both) you want to change.""" url = 'http://min.us/api/SaveGallery' if not name: if not self.name: name = self...
python
def SaveGallery(self, name=None, items=None): """Use this to update the gallery name or change sort order. Specify which attribute (name or items or both) you want to change.""" url = 'http://min.us/api/SaveGallery' if not name: if not self.name: name = self...
[ "def", "SaveGallery", "(", "self", ",", "name", "=", "None", ",", "items", "=", "None", ")", ":", "url", "=", "'http://min.us/api/SaveGallery'", "if", "not", "name", ":", "if", "not", "self", ".", "name", ":", "name", "=", "self", ".", "GetItems", "(",...
Use this to update the gallery name or change sort order. Specify which attribute (name or items or both) you want to change.
[ "Use", "this", "to", "update", "the", "gallery", "name", "or", "change", "sort", "order", ".", "Specify", "which", "attribute", "(", "name", "or", "items", "or", "both", ")", "you", "want", "to", "change", "." ]
train
https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/minus/minus.py#L62-L88
renzon/gaepermission
gaepermission/facade.py
save_user_cmd
def save_user_cmd(email, name=None, groups=None, locale='en_US', timezone='US/Eastern'): """ Command to save a user :param email: user email :param name: user name :param groups: user permission groups :return: A command that validate date and save the user """ if name is None: n...
python
def save_user_cmd(email, name=None, groups=None, locale='en_US', timezone='US/Eastern'): """ Command to save a user :param email: user email :param name: user name :param groups: user permission groups :return: A command that validate date and save the user """ if name is None: n...
[ "def", "save_user_cmd", "(", "email", ",", "name", "=", "None", ",", "groups", "=", "None", ",", "locale", "=", "'en_US'", ",", "timezone", "=", "'US/Eastern'", ")", ":", "if", "name", "is", "None", ":", "name", "=", "email", "if", "groups", "is", "N...
Command to save a user :param email: user email :param name: user name :param groups: user permission groups :return: A command that validate date and save the user
[ "Command", "to", "save", "a", "user", ":", "param", "email", ":", "user", "email", ":", "param", "name", ":", "user", "name", ":", "param", "groups", ":", "user", "permission", "groups", ":", "return", ":", "A", "command", "that", "validate", "date", "...
train
https://github.com/renzon/gaepermission/blob/1a3534a7ef150ba31fa8df3bc8445557cab3d79d/gaepermission/facade.py#L19-L31
renzon/gaepermission
gaepermission/facade.py
logged_user
def logged_user(request): """ Returns a command that retrieves the current logged user based on secure cookie If there is no logged user, the result from command is None """ dct = cookie_facade.retrive_cookie_data(request, USER_COOKIE_NAME).execute().result if dct is None: return Command...
python
def logged_user(request): """ Returns a command that retrieves the current logged user based on secure cookie If there is no logged user, the result from command is None """ dct = cookie_facade.retrive_cookie_data(request, USER_COOKIE_NAME).execute().result if dct is None: return Command...
[ "def", "logged_user", "(", "request", ")", ":", "dct", "=", "cookie_facade", ".", "retrive_cookie_data", "(", "request", ",", "USER_COOKIE_NAME", ")", ".", "execute", "(", ")", ".", "result", "if", "dct", "is", "None", ":", "return", "Command", "(", ")", ...
Returns a command that retrieves the current logged user based on secure cookie If there is no logged user, the result from command is None
[ "Returns", "a", "command", "that", "retrieves", "the", "current", "logged", "user", "based", "on", "secure", "cookie", "If", "there", "is", "no", "logged", "user", "the", "result", "from", "command", "is", "None" ]
train
https://github.com/renzon/gaepermission/blob/1a3534a7ef150ba31fa8df3bc8445557cab3d79d/gaepermission/facade.py#L57-L65
renzon/gaepermission
gaepermission/facade.py
login_checking_email
def login_checking_email(pending_id, ticket, response, detail_url='https://pswdless.appspot.com/rest/detail'): """ Log user in using Passwordless service :param pending_id: PendingExternalToMainUser's id :param ticket: ticket returned from Passwordless :param response: Response object from webapp2 ...
python
def login_checking_email(pending_id, ticket, response, detail_url='https://pswdless.appspot.com/rest/detail'): """ Log user in using Passwordless service :param pending_id: PendingExternalToMainUser's id :param ticket: ticket returned from Passwordless :param response: Response object from webapp2 ...
[ "def", "login_checking_email", "(", "pending_id", ",", "ticket", ",", "response", ",", "detail_url", "=", "'https://pswdless.appspot.com/rest/detail'", ")", ":", "return", "LoginCheckingEmail", "(", "pending_id", ",", "ticket", ",", "response", ",", "USER_COOKIE_NAME", ...
Log user in using Passwordless service :param pending_id: PendingExternalToMainUser's id :param ticket: ticket returned from Passwordless :param response: Response object from webapp2 :param detail_url: url to check ticket and user data :return: a Command that log user in when executed
[ "Log", "user", "in", "using", "Passwordless", "service", ":", "param", "pending_id", ":", "PendingExternalToMainUser", "s", "id", ":", "param", "ticket", ":", "ticket", "returned", "from", "Passwordless", ":", "param", "response", ":", "Response", "object", "fro...
train
https://github.com/renzon/gaepermission/blob/1a3534a7ef150ba31fa8df3bc8445557cab3d79d/gaepermission/facade.py#L89-L98
renzon/gaepermission
gaepermission/facade.py
find_users_by_email_starting_with
def find_users_by_email_starting_with(email_prefix=None, cursor=None, page_size=30): """ Returns a command that retrieves users by its email_prefix, ordered by email. It returns a max number of users defined by page_size arg. Next result can be retrieved using cursor, in a next call. It is provided in c...
python
def find_users_by_email_starting_with(email_prefix=None, cursor=None, page_size=30): """ Returns a command that retrieves users by its email_prefix, ordered by email. It returns a max number of users defined by page_size arg. Next result can be retrieved using cursor, in a next call. It is provided in c...
[ "def", "find_users_by_email_starting_with", "(", "email_prefix", "=", "None", ",", "cursor", "=", "None", ",", "page_size", "=", "30", ")", ":", "email_prefix", "=", "email_prefix", "or", "''", "return", "ModelSearchCommand", "(", "MainUser", ".", "query_email_sta...
Returns a command that retrieves users by its email_prefix, ordered by email. It returns a max number of users defined by page_size arg. Next result can be retrieved using cursor, in a next call. It is provided in cursor attribute from command.
[ "Returns", "a", "command", "that", "retrieves", "users", "by", "its", "email_prefix", "ordered", "by", "email", ".", "It", "returns", "a", "max", "number", "of", "users", "defined", "by", "page_size", "arg", ".", "Next", "result", "can", "be", "retrieved", ...
train
https://github.com/renzon/gaepermission/blob/1a3534a7ef150ba31fa8df3bc8445557cab3d79d/gaepermission/facade.py#L108-L117
renzon/gaepermission
gaepermission/facade.py
find_users_by_email_and_group
def find_users_by_email_and_group(email_prefix=None, group=None, cursor=None, page_size=30): """ Returns a command that retrieves users by its email_prefix, ordered by email and by Group. If Group is None, only users without any group are going to be searched It returns a max number of users defined by ...
python
def find_users_by_email_and_group(email_prefix=None, group=None, cursor=None, page_size=30): """ Returns a command that retrieves users by its email_prefix, ordered by email and by Group. If Group is None, only users without any group are going to be searched It returns a max number of users defined by ...
[ "def", "find_users_by_email_and_group", "(", "email_prefix", "=", "None", ",", "group", "=", "None", ",", "cursor", "=", "None", ",", "page_size", "=", "30", ")", ":", "email_prefix", "=", "email_prefix", "or", "''", "return", "ModelSearchCommand", "(", "MainU...
Returns a command that retrieves users by its email_prefix, ordered by email and by Group. If Group is None, only users without any group are going to be searched It returns a max number of users defined by page_size arg. Next result can be retrieved using cursor, in a next call. It is provided in cursor at...
[ "Returns", "a", "command", "that", "retrieves", "users", "by", "its", "email_prefix", "ordered", "by", "email", "and", "by", "Group", ".", "If", "Group", "is", "None", "only", "users", "without", "any", "group", "are", "going", "to", "be", "searched", "It"...
train
https://github.com/renzon/gaepermission/blob/1a3534a7ef150ba31fa8df3bc8445557cab3d79d/gaepermission/facade.py#L120-L130
rehandalal/buchner
buchner/project-template/PROJECTMODULE/errors.py
json_error
def json_error(code, message): """Returns a JSON-ified error object""" # Message can be an unserializable object. message = repr(message) return jsonify(dict(request=request.path, message=message)), code
python
def json_error(code, message): """Returns a JSON-ified error object""" # Message can be an unserializable object. message = repr(message) return jsonify(dict(request=request.path, message=message)), code
[ "def", "json_error", "(", "code", ",", "message", ")", ":", "# Message can be an unserializable object.", "message", "=", "repr", "(", "message", ")", "return", "jsonify", "(", "dict", "(", "request", "=", "request", ".", "path", ",", "message", "=", "message"...
Returns a JSON-ified error object
[ "Returns", "a", "JSON", "-", "ified", "error", "object" ]
train
https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/PROJECTMODULE/errors.py#L12-L16
rehandalal/buchner
buchner/project-template/PROJECTMODULE/errors.py
error
def error(code, message, template): """A generic error handler""" if json_requested(): return json_error(code, message) else: return render_template(template, message=message), code
python
def error(code, message, template): """A generic error handler""" if json_requested(): return json_error(code, message) else: return render_template(template, message=message), code
[ "def", "error", "(", "code", ",", "message", ",", "template", ")", ":", "if", "json_requested", "(", ")", ":", "return", "json_error", "(", "code", ",", "message", ")", "else", ":", "return", "render_template", "(", "template", ",", "message", "=", "mess...
A generic error handler
[ "A", "generic", "error", "handler" ]
train
https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/PROJECTMODULE/errors.py#L19-L24
MacHu-GWU/angora-project
angora/text/strtemplate.py
StrTemplate.straight_line
def straight_line(title, length=100, linestyle="=", pad=0): """Return a fixed-length straight line with some text at the center. Usage Example:: >>> StringTemplate.straight_line("Hello world!", 20, "-", 1) --- Hello world! --- """ text = "{:%...
python
def straight_line(title, length=100, linestyle="=", pad=0): """Return a fixed-length straight line with some text at the center. Usage Example:: >>> StringTemplate.straight_line("Hello world!", 20, "-", 1) --- Hello world! --- """ text = "{:%...
[ "def", "straight_line", "(", "title", ",", "length", "=", "100", ",", "linestyle", "=", "\"=\"", ",", "pad", "=", "0", ")", ":", "text", "=", "\"{:%s^%s}\"", "%", "(", "linestyle", ",", "length", ")", "return", "text", ".", "format", "(", "\"%s%s%s\"",...
Return a fixed-length straight line with some text at the center. Usage Example:: >>> StringTemplate.straight_line("Hello world!", 20, "-", 1) --- Hello world! ---
[ "Return", "a", "fixed", "-", "length", "straight", "line", "with", "some", "text", "at", "the", "center", ".", "Usage", "Example", "::", ">>>", "StringTemplate", ".", "straight_line", "(", "Hello", "world!", "20", "-", "1", ")", "---", "Hello", "world!", ...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/strtemplate.py#L30-L39
MacHu-GWU/angora-project
angora/text/strtemplate.py
StrTemplate.straight_line_show
def straight_line_show(title, length=100, linestyle="=", pad=0): """Print a formatted straight line. """ print(StrTemplate.straight_line( title=title, length=length, linestyle=linestyle, pad=pad))
python
def straight_line_show(title, length=100, linestyle="=", pad=0): """Print a formatted straight line. """ print(StrTemplate.straight_line( title=title, length=length, linestyle=linestyle, pad=pad))
[ "def", "straight_line_show", "(", "title", ",", "length", "=", "100", ",", "linestyle", "=", "\"=\"", ",", "pad", "=", "0", ")", ":", "print", "(", "StrTemplate", ".", "straight_line", "(", "title", "=", "title", ",", "length", "=", "length", ",", "lin...
Print a formatted straight line.
[ "Print", "a", "formatted", "straight", "line", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/strtemplate.py#L42-L46
MacHu-GWU/angora-project
angora/text/strtemplate.py
StrTemplate.indented_show
def indented_show(text, howmany=1): """Print a formatted indented text. """ print(StrTemplate.pad_indent(text=text, howmany=howmany))
python
def indented_show(text, howmany=1): """Print a formatted indented text. """ print(StrTemplate.pad_indent(text=text, howmany=howmany))
[ "def", "indented_show", "(", "text", ",", "howmany", "=", "1", ")", ":", "print", "(", "StrTemplate", ".", "pad_indent", "(", "text", "=", "text", ",", "howmany", "=", "howmany", ")", ")" ]
Print a formatted indented text.
[ "Print", "a", "formatted", "indented", "text", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/strtemplate.py#L60-L63
MacHu-GWU/angora-project
angora/text/strtemplate.py
StrTemplate.box
def box(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): """Return a ascii box, with your text center-aligned. Usage Example:: >>> StringTemplate.box("Hello world!", 20, 5) +------------------+ | | | ...
python
def box(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): """Return a ascii box, with your text center-aligned. Usage Example:: >>> StringTemplate.box("Hello world!", 20, 5) +------------------+ | | | ...
[ "def", "box", "(", "text", ",", "width", "=", "100", ",", "height", "=", "3", ",", "corner", "=", "\"+\"", ",", "horizontal", "=", "\"-\"", ",", "vertical", "=", "\"|\"", ")", ":", "if", "width", "<=", "len", "(", "text", ")", "-", "4", ":", "p...
Return a ascii box, with your text center-aligned. Usage Example:: >>> StringTemplate.box("Hello world!", 20, 5) +------------------+ | | | Hello world! | | | +------------------+
[ "Return", "a", "ascii", "box", "with", "your", "text", "center", "-", "aligned", ".", "Usage", "Example", "::", ">>>", "StringTemplate", ".", "box", "(", "Hello", "world!", "20", "5", ")", "+", "------------------", "+", "|", "|", "|", "Hello", "world!",...
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/strtemplate.py#L66-L95
MacHu-GWU/angora-project
angora/text/strtemplate.py
StrTemplate.box_show
def box_show(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): """Print a formatted ascii text box. """ print(StrTemplate.box(text=text, width=width, height=height, corner=corner, horizontal=horizontal, vertical=vertical))
python
def box_show(text, width=100, height=3, corner="+", horizontal="-", vertical="|"): """Print a formatted ascii text box. """ print(StrTemplate.box(text=text, width=width, height=height, corner=corner, horizontal=horizontal, vertical=vertical))
[ "def", "box_show", "(", "text", ",", "width", "=", "100", ",", "height", "=", "3", ",", "corner", "=", "\"+\"", ",", "horizontal", "=", "\"-\"", ",", "vertical", "=", "\"|\"", ")", ":", "print", "(", "StrTemplate", ".", "box", "(", "text", "=", "te...
Print a formatted ascii text box.
[ "Print", "a", "formatted", "ascii", "text", "box", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/text/strtemplate.py#L98-L102
smarter-travel-media/stac
stac/client.py
new_maven_client
def new_maven_client(base_url, repo, is_snapshot=False, username=None, password=None): """Get a new implementation of :class:`ArtifactoryClient` for use with Maven repository layouts, optionally using the provided authentication. Most users will simply call this method to get a new Maven client instance. F...
python
def new_maven_client(base_url, repo, is_snapshot=False, username=None, password=None): """Get a new implementation of :class:`ArtifactoryClient` for use with Maven repository layouts, optionally using the provided authentication. Most users will simply call this method to get a new Maven client instance. F...
[ "def", "new_maven_client", "(", "base_url", ",", "repo", ",", "is_snapshot", "=", "False", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "if", "username", "is", "not", "None", ...
Get a new implementation of :class:`ArtifactoryClient` for use with Maven repository layouts, optionally using the provided authentication. Most users will simply call this method to get a new Maven client instance. For example: >>> client = new_maven_client('https://www.example.com/artifactory', 'libs-re...
[ "Get", "a", "new", "implementation", "of", ":", "class", ":", "ArtifactoryClient", "for", "use", "with", "Maven", "repository", "layouts", "optionally", "using", "the", "provided", "authentication", "." ]
train
https://github.com/smarter-travel-media/stac/blob/cdb29a17ede0924b122b3905a500442c62ae53b7/stac/client.py#L71-L104
smarter-travel-media/stac
stac/client.py
GenericArtifactoryClient.get_version_url
def get_version_url(self, full_name, packaging, version, descriptor=None): """Get the URL to a specific version of the given project, optionally using a descriptor to get a particular variant of the version (sources, javadocs, etc.). The name of the artifact should be composed of the group ID a...
python
def get_version_url(self, full_name, packaging, version, descriptor=None): """Get the URL to a specific version of the given project, optionally using a descriptor to get a particular variant of the version (sources, javadocs, etc.). The name of the artifact should be composed of the group ID a...
[ "def", "get_version_url", "(", "self", ",", "full_name", ",", "packaging", ",", "version", ",", "descriptor", "=", "None", ")", ":", "group", ",", "artifact", "=", "_parse_full_name", "(", "full_name", ")", "return", "self", ".", "_urls", ".", "get_url", "...
Get the URL to a specific version of the given project, optionally using a descriptor to get a particular variant of the version (sources, javadocs, etc.). The name of the artifact should be composed of the group ID and artifact ID (if available). E.g. "com.example.project.service". Depending o...
[ "Get", "the", "URL", "to", "a", "specific", "version", "of", "the", "given", "project", "optionally", "using", "a", "descriptor", "to", "get", "a", "particular", "variant", "of", "the", "version", "(", "sources", "javadocs", "etc", ".", ")", "." ]
train
https://github.com/smarter-travel-media/stac/blob/cdb29a17ede0924b122b3905a500442c62ae53b7/stac/client.py#L145-L178
kevinsprong23/aperture
aperture/util.py
increment
def increment(d, key, val=1): """ increment dict d at key by amount val no need to return since d is mutable """ if key in d: d[key] += val else: d[key] = val
python
def increment(d, key, val=1): """ increment dict d at key by amount val no need to return since d is mutable """ if key in d: d[key] += val else: d[key] = val
[ "def", "increment", "(", "d", ",", "key", ",", "val", "=", "1", ")", ":", "if", "key", "in", "d", ":", "d", "[", "key", "]", "+=", "val", "else", ":", "d", "[", "key", "]", "=", "val" ]
increment dict d at key by amount val no need to return since d is mutable
[ "increment", "dict", "d", "at", "key", "by", "amount", "val", "no", "need", "to", "return", "since", "d", "is", "mutable" ]
train
https://github.com/kevinsprong23/aperture/blob/d0420fef3b25d8afc0e5ddcfb6fe5f0ff42b9799/aperture/util.py#L7-L15
kevinsprong23/aperture
aperture/util.py
floor_nearest
def floor_nearest(x, dx=1): """ floor a number to within a given rounding accuracy """ precision = get_sig_digits(dx) return round(math.floor(float(x) / dx) * dx, precision)
python
def floor_nearest(x, dx=1): """ floor a number to within a given rounding accuracy """ precision = get_sig_digits(dx) return round(math.floor(float(x) / dx) * dx, precision)
[ "def", "floor_nearest", "(", "x", ",", "dx", "=", "1", ")", ":", "precision", "=", "get_sig_digits", "(", "dx", ")", "return", "round", "(", "math", ".", "floor", "(", "float", "(", "x", ")", "/", "dx", ")", "*", "dx", ",", "precision", ")" ]
floor a number to within a given rounding accuracy
[ "floor", "a", "number", "to", "within", "a", "given", "rounding", "accuracy" ]
train
https://github.com/kevinsprong23/aperture/blob/d0420fef3b25d8afc0e5ddcfb6fe5f0ff42b9799/aperture/util.py#L25-L30
kevinsprong23/aperture
aperture/util.py
ceil_nearest
def ceil_nearest(x, dx=1): """ ceil a number to within a given rounding accuracy """ precision = get_sig_digits(dx) return round(math.ceil(float(x) / dx) * dx, precision)
python
def ceil_nearest(x, dx=1): """ ceil a number to within a given rounding accuracy """ precision = get_sig_digits(dx) return round(math.ceil(float(x) / dx) * dx, precision)
[ "def", "ceil_nearest", "(", "x", ",", "dx", "=", "1", ")", ":", "precision", "=", "get_sig_digits", "(", "dx", ")", "return", "round", "(", "math", ".", "ceil", "(", "float", "(", "x", ")", "/", "dx", ")", "*", "dx", ",", "precision", ")" ]
ceil a number to within a given rounding accuracy
[ "ceil", "a", "number", "to", "within", "a", "given", "rounding", "accuracy" ]
train
https://github.com/kevinsprong23/aperture/blob/d0420fef3b25d8afc0e5ddcfb6fe5f0ff42b9799/aperture/util.py#L33-L38
kevinsprong23/aperture
aperture/util.py
frange
def frange(x, y, jump=1): """ range for floats """ precision = get_sig_digits(jump) while x < y: yield round(x, precision) x += jump
python
def frange(x, y, jump=1): """ range for floats """ precision = get_sig_digits(jump) while x < y: yield round(x, precision) x += jump
[ "def", "frange", "(", "x", ",", "y", ",", "jump", "=", "1", ")", ":", "precision", "=", "get_sig_digits", "(", "jump", ")", "while", "x", "<", "y", ":", "yield", "round", "(", "x", ",", "precision", ")", "x", "+=", "jump" ]
range for floats
[ "range", "for", "floats" ]
train
https://github.com/kevinsprong23/aperture/blob/d0420fef3b25d8afc0e5ddcfb6fe5f0ff42b9799/aperture/util.py#L41-L48
sahid/warm
warm/utils.py
multipart_content
def multipart_content(*files): """Returns a mutlipart content. Note: This script was clearly inspired by write-mime-multipart. """ outer = MIMEMultipart() for fname in files: mtype = get_type(fname) maintype, subtype = mtype.split('/', 1) with open(fname) as f: ...
python
def multipart_content(*files): """Returns a mutlipart content. Note: This script was clearly inspired by write-mime-multipart. """ outer = MIMEMultipart() for fname in files: mtype = get_type(fname) maintype, subtype = mtype.split('/', 1) with open(fname) as f: ...
[ "def", "multipart_content", "(", "*", "files", ")", ":", "outer", "=", "MIMEMultipart", "(", ")", "for", "fname", "in", "files", ":", "mtype", "=", "get_type", "(", "fname", ")", "maintype", ",", "subtype", "=", "mtype", ".", "split", "(", "'/'", ",", ...
Returns a mutlipart content. Note: This script was clearly inspired by write-mime-multipart.
[ "Returns", "a", "mutlipart", "content", ".", "Note", ":", "This", "script", "was", "clearly", "inspired", "by", "write", "-", "mime", "-", "multipart", "." ]
train
https://github.com/sahid/warm/blob/baf1cb73c6769a556756b9078e60c96d4b1de2bd/warm/utils.py#L47-L61
MacHu-GWU/angora-project
angora/dtypes/orderedset.py
OrderedSet.discard
def discard(self, key): """Remove a item from its member if it is a member. Usage:: >>> s = OrderedSet([1, 2, 3]) >>> s.discard(2) >>> s OrderedSet([1, 3]) **中文文档** 从有序集合中删除一个元素, 同时保持集合依然有序。 """ ...
python
def discard(self, key): """Remove a item from its member if it is a member. Usage:: >>> s = OrderedSet([1, 2, 3]) >>> s.discard(2) >>> s OrderedSet([1, 3]) **中文文档** 从有序集合中删除一个元素, 同时保持集合依然有序。 """ ...
[ "def", "discard", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "map", ":", "key", ",", "prev", ",", "next_item", "=", "self", ".", "map", ".", "pop", "(", "key", ")", "prev", "[", "2", "]", "=", "next_item", "next_item", "...
Remove a item from its member if it is a member. Usage:: >>> s = OrderedSet([1, 2, 3]) >>> s.discard(2) >>> s OrderedSet([1, 3]) **中文文档** 从有序集合中删除一个元素, 同时保持集合依然有序。
[ "Remove", "a", "item", "from", "its", "member", "if", "it", "is", "a", "member", "." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/orderedset.py#L113-L130
MacHu-GWU/angora-project
angora/dtypes/orderedset.py
OrderedSet.union
def union(*argv): """Returns union of sets as a new set. basically it's Items are ordered by set1, set2, ... **中文文档** 求多个有序集合的并集, 按照第一个集合, 第二个, ..., 这样的顺序。 """ res = OrderedSet() for ods in argv: res = res | ods return res
python
def union(*argv): """Returns union of sets as a new set. basically it's Items are ordered by set1, set2, ... **中文文档** 求多个有序集合的并集, 按照第一个集合, 第二个, ..., 这样的顺序。 """ res = OrderedSet() for ods in argv: res = res | ods return res
[ "def", "union", "(", "*", "argv", ")", ":", "res", "=", "OrderedSet", "(", ")", "for", "ods", "in", "argv", ":", "res", "=", "res", "|", "ods", "return", "res" ]
Returns union of sets as a new set. basically it's Items are ordered by set1, set2, ... **中文文档** 求多个有序集合的并集, 按照第一个集合, 第二个, ..., 这样的顺序。
[ "Returns", "union", "of", "sets", "as", "a", "new", "set", ".", "basically", "it", "s", "Items", "are", "ordered", "by", "set1", "set2", "...", "**", "中文文档", "**", "求多个有序集合的并集", "按照第一个集合", "第二个", "...", "这样的顺序。" ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/orderedset.py#L178-L189
MacHu-GWU/angora-project
angora/dtypes/orderedset.py
OrderedSet.intersection
def intersection(*argv): """Returns the intersection of multiple sets. Items are ordered by set1, set2, ... **中文文档** 求多个有序集合的交集, 按照第一个集合, 第二个, ..., 这样的顺序。 """ res = OrderedSet(argv[0]) for ods in argv: res = ods & res return res
python
def intersection(*argv): """Returns the intersection of multiple sets. Items are ordered by set1, set2, ... **中文文档** 求多个有序集合的交集, 按照第一个集合, 第二个, ..., 这样的顺序。 """ res = OrderedSet(argv[0]) for ods in argv: res = ods & res return res
[ "def", "intersection", "(", "*", "argv", ")", ":", "res", "=", "OrderedSet", "(", "argv", "[", "0", "]", ")", "for", "ods", "in", "argv", ":", "res", "=", "ods", "&", "res", "return", "res" ]
Returns the intersection of multiple sets. Items are ordered by set1, set2, ... **中文文档** 求多个有序集合的交集, 按照第一个集合, 第二个, ..., 这样的顺序。
[ "Returns", "the", "intersection", "of", "multiple", "sets", ".", "Items", "are", "ordered", "by", "set1", "set2", "..." ]
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/orderedset.py#L192-L203
esterhui/pypu
pypu/facebook_login.py
get_fb_token
def get_fb_token(): """Returns access token, optionally launches browser session to get the token via a facebook login. esterhui: got this code from the interweb, but can't find the reference now. """ global ACCESS_TOKEN if not os.path.exists(TOKEN_FILE): print "Logging you in to facebo...
python
def get_fb_token(): """Returns access token, optionally launches browser session to get the token via a facebook login. esterhui: got this code from the interweb, but can't find the reference now. """ global ACCESS_TOKEN if not os.path.exists(TOKEN_FILE): print "Logging you in to facebo...
[ "def", "get_fb_token", "(", ")", ":", "global", "ACCESS_TOKEN", "if", "not", "os", ".", "path", ".", "exists", "(", "TOKEN_FILE", ")", ":", "print", "\"Logging you in to facebook...\"", "webbrowser", ".", "open", "(", "get_url", "(", "'/oauth/authorize'", ",", ...
Returns access token, optionally launches browser session to get the token via a facebook login. esterhui: got this code from the interweb, but can't find the reference now.
[ "Returns", "access", "token", "optionally", "launches", "browser", "session", "to", "get", "the", "token", "via", "a", "facebook", "login", ".", "esterhui", ":", "got", "this", "code", "from", "the", "interweb", "but", "can", "t", "find", "the", "reference",...
train
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/facebook_login.py#L58-L77
saintic/SpliceURL
SpliceURL.py
Splice.do
def do(self): "run it, you can get a good stitching of the complete URL." return urlunparse((self.scheme, self.netloc, self.path, self.params, self.query, self.fragment))
python
def do(self): "run it, you can get a good stitching of the complete URL." return urlunparse((self.scheme, self.netloc, self.path, self.params, self.query, self.fragment))
[ "def", "do", "(", "self", ")", ":", "return", "urlunparse", "(", "(", "self", ".", "scheme", ",", "self", ".", "netloc", ",", "self", ".", "path", ",", "self", ".", "params", ",", "self", ".", "query", ",", "self", ".", "fragment", ")", ")" ]
run it, you can get a good stitching of the complete URL.
[ "run", "it", "you", "can", "get", "a", "good", "stitching", "of", "the", "complete", "URL", "." ]
train
https://github.com/saintic/SpliceURL/blob/ac2d1e854cbdfcf984bce3682b7f05ccba20938e/SpliceURL.py#L46-L48
saintic/SpliceURL
SpliceURL.py
Split.do
def do(self): "run it, you can get a tuple for (scheme, netloc, path, params, query, fragment)" _PR = urlparse(self.url) return _PR.scheme, _PR.netloc, _PR.path, _PR.params, _PR.query, _PR.fragment
python
def do(self): "run it, you can get a tuple for (scheme, netloc, path, params, query, fragment)" _PR = urlparse(self.url) return _PR.scheme, _PR.netloc, _PR.path, _PR.params, _PR.query, _PR.fragment
[ "def", "do", "(", "self", ")", ":", "_PR", "=", "urlparse", "(", "self", ".", "url", ")", "return", "_PR", ".", "scheme", ",", "_PR", ".", "netloc", ",", "_PR", ".", "path", ",", "_PR", ".", "params", ",", "_PR", ".", "query", ",", "_PR", ".", ...
run it, you can get a tuple for (scheme, netloc, path, params, query, fragment)
[ "run", "it", "you", "can", "get", "a", "tuple", "for", "(", "scheme", "netloc", "path", "params", "query", "fragment", ")" ]
train
https://github.com/saintic/SpliceURL/blob/ac2d1e854cbdfcf984bce3682b7f05ccba20938e/SpliceURL.py#L67-L70
saintic/SpliceURL
SpliceURL.py
Modify.do
def do(self): "run it, get a new url" scheme, netloc, path, params, query, fragment = Split(self.url).do() if isinstance(self.query, dict): query = query + "&" + urllib.urlencode(self.query) if query else urllib.urlencode(self.query) path = urljoin(path, self.path).replace(...
python
def do(self): "run it, get a new url" scheme, netloc, path, params, query, fragment = Split(self.url).do() if isinstance(self.query, dict): query = query + "&" + urllib.urlencode(self.query) if query else urllib.urlencode(self.query) path = urljoin(path, self.path).replace(...
[ "def", "do", "(", "self", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "Split", "(", "self", ".", "url", ")", ".", "do", "(", ")", "if", "isinstance", "(", "self", ".", "query", ",", "dict", ...
run it, get a new url
[ "run", "it", "get", "a", "new", "url" ]
train
https://github.com/saintic/SpliceURL/blob/ac2d1e854cbdfcf984bce3682b7f05ccba20938e/SpliceURL.py#L89-L98
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
PeriodFilter.lookups
def lookups(self, request, model_admin): """ Performs lookup in the same way the reporting tool allows to generate a report. :param request: Current request :param model_admin: Current model admin. It must implement get_period_options as returning a list of (k, v). :raises: Attri...
python
def lookups(self, request, model_admin): """ Performs lookup in the same way the reporting tool allows to generate a report. :param request: Current request :param model_admin: Current model admin. It must implement get_period_options as returning a list of (k, v). :raises: Attri...
[ "def", "lookups", "(", "self", ",", "request", ",", "model_admin", ")", ":", "if", "model_admin", ".", "tracked_stamps", "in", "{", "'create'", ",", "'update'", ",", "'both'", "}", ":", "prefix", "=", "model_admin", ".", "tracked_stamps", "+", "':'", "else...
Performs lookup in the same way the reporting tool allows to generate a report. :param request: Current request :param model_admin: Current model admin. It must implement get_period_options as returning a list of (k, v). :raises: AttributeError, ValueError, or any exception triggered by get_peri...
[ "Performs", "lookup", "in", "the", "same", "way", "the", "reporting", "tool", "allows", "to", "generate", "a", "report", ".", ":", "param", "request", ":", "Current", "request", ":", "param", "model_admin", ":", "Current", "model", "admin", ".", "It", "mus...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L42-L56
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
PeriodFilter.queryset
def queryset(self, request, queryset): """ Will invoke .created_on(period) or .updated_on(period) depending on how it is specified in each subclass (A queryset obtained from the Tracked* models will have a created_on and updated_on models as shortcuts). :param request: ...
python
def queryset(self, request, queryset): """ Will invoke .created_on(period) or .updated_on(period) depending on how it is specified in each subclass (A queryset obtained from the Tracked* models will have a created_on and updated_on models as shortcuts). :param request: ...
[ "def", "queryset", "(", "self", ",", "request", ",", "queryset", ")", ":", "value", "=", "self", ".", "value", "(", ")", "try", ":", "if", "not", "value", ":", "return", "queryset", "prefix", ",", "period", "=", "value", ".", "split", "(", "':'", "...
Will invoke .created_on(period) or .updated_on(period) depending on how it is specified in each subclass (A queryset obtained from the Tracked* models will have a created_on and updated_on models as shortcuts). :param request: :param queryset: :return: filtered queryset.
[ "Will", "invoke", ".", "created_on", "(", "period", ")", "or", ".", "updated_on", "(", "period", ")", "depending", "on", "how", "it", "is", "specified", "in", "each", "subclass", "(", "A", "queryset", "obtained", "from", "the", "Tracked", "*", "models", ...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L58-L82
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.get_list_filter
def get_list_filter(self, request): """ Adds the period filter to the filters list. :param request: Current request. :return: Iterable of filters. """ original = super(TrackedLiveAdmin, self).get_list_filter(request) return original + type(original)([PeriodFilter...
python
def get_list_filter(self, request): """ Adds the period filter to the filters list. :param request: Current request. :return: Iterable of filters. """ original = super(TrackedLiveAdmin, self).get_list_filter(request) return original + type(original)([PeriodFilter...
[ "def", "get_list_filter", "(", "self", ",", "request", ")", ":", "original", "=", "super", "(", "TrackedLiveAdmin", ",", "self", ")", ".", "get_list_filter", "(", "request", ")", "return", "original", "+", "type", "(", "original", ")", "(", "[", "PeriodFil...
Adds the period filter to the filters list. :param request: Current request. :return: Iterable of filters.
[ "Adds", "the", "period", "filter", "to", "the", "filters", "list", ".", ":", "param", "request", ":", "Current", "request", ".", ":", "return", ":", "Iterable", "of", "filters", "." ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L96-L104
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.get_reporters
def get_reporters(self): """ Converts the report_generators list to a dictionary, and caches the result. :return: A dictionary with such references. """ if not hasattr(self, '_report_generators_by_key'): self._report_generators_by_key = {r.key: r for r in self.report...
python
def get_reporters(self): """ Converts the report_generators list to a dictionary, and caches the result. :return: A dictionary with such references. """ if not hasattr(self, '_report_generators_by_key'): self._report_generators_by_key = {r.key: r for r in self.report...
[ "def", "get_reporters", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_report_generators_by_key'", ")", ":", "self", ".", "_report_generators_by_key", "=", "{", "r", ".", "key", ":", "r", "for", "r", "in", "self", ".", "report_generato...
Converts the report_generators list to a dictionary, and caches the result. :return: A dictionary with such references.
[ "Converts", "the", "report_generators", "list", "to", "a", "dictionary", "and", "caches", "the", "result", ".", ":", "return", ":", "A", "dictionary", "with", "such", "references", "." ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L106-L114
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.get_period_options
def get_period_options(self): """ Given the current setting in report_period_type, returns a list of options (suitable for select) as an array or pairs telling the valid periods to select. :return: An array of period options. """ if self.report_period_type == 'ago': ...
python
def get_period_options(self): """ Given the current setting in report_period_type, returns a list of options (suitable for select) as an array or pairs telling the valid periods to select. :return: An array of period options. """ if self.report_period_type == 'ago': ...
[ "def", "get_period_options", "(", "self", ")", ":", "if", "self", ".", "report_period_type", "==", "'ago'", ":", "return", "PERIOD_AGO_LOOKUPS", "elif", "self", ".", "report_period_type", "==", "'current'", ":", "return", "PERIOD_CURRENT_LOOKUPS", "elif", "self", ...
Given the current setting in report_period_type, returns a list of options (suitable for select) as an array or pairs telling the valid periods to select. :return: An array of period options.
[ "Given", "the", "current", "setting", "in", "report_period_type", "returns", "a", "list", "of", "options", "(", "suitable", "for", "select", ")", "as", "an", "array", "or", "pairs", "telling", "the", "valid", "periods", "to", "select", ".", ":", "return", ...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L116-L130
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.get_urls
def get_urls(self): """ Returns additional urls to add to a result of `get_urls` in a descendant ModelAdmin :return: A list of url declarations. """ info = self.model._meta.app_label, self.model._meta.model_name return [ url(r'^report/(?P<key>\w+)/(?P<period>...
python
def get_urls(self): """ Returns additional urls to add to a result of `get_urls` in a descendant ModelAdmin :return: A list of url declarations. """ info = self.model._meta.app_label, self.model._meta.model_name return [ url(r'^report/(?P<key>\w+)/(?P<period>...
[ "def", "get_urls", "(", "self", ")", ":", "info", "=", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "model_name", "return", "[", "url", "(", "r'^report/(?P<key>\\w+)/(?P<period>\\w)$'", ",", "self", "....
Returns additional urls to add to a result of `get_urls` in a descendant ModelAdmin :return: A list of url declarations.
[ "Returns", "additional", "urls", "to", "add", "to", "a", "result", "of", "get_urls", "in", "a", "descendant", "ModelAdmin", ":", "return", ":", "A", "list", "of", "url", "declarations", "." ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L141-L152
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.changelist_view
def changelist_view(self, request, extra_context=None): """ Updates the changelist view to include settings from this admin. """ return super(TrackedLiveAdmin, self).changelist_view( request, dict(extra_context or {}, url_name='admin:%s_%s_tracking_...
python
def changelist_view(self, request, extra_context=None): """ Updates the changelist view to include settings from this admin. """ return super(TrackedLiveAdmin, self).changelist_view( request, dict(extra_context or {}, url_name='admin:%s_%s_tracking_...
[ "def", "changelist_view", "(", "self", ",", "request", ",", "extra_context", "=", "None", ")", ":", "return", "super", "(", "TrackedLiveAdmin", ",", "self", ")", ".", "changelist_view", "(", "request", ",", "dict", "(", "extra_context", "or", "{", "}", ","...
Updates the changelist view to include settings from this admin.
[ "Updates", "the", "changelist", "view", "to", "include", "settings", "from", "this", "admin", "." ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L154-L164
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.render_report_error
def render_report_error(self, request, error, status): """ Renders the report errors template. """ opts = self.model._meta app_label = opts.app_label request.current_app = self.admin_site.name context = dict( self.admin_site.each_context(request), ...
python
def render_report_error(self, request, error, status): """ Renders the report errors template. """ opts = self.model._meta app_label = opts.app_label request.current_app = self.admin_site.name context = dict( self.admin_site.each_context(request), ...
[ "def", "render_report_error", "(", "self", ",", "request", ",", "error", ",", "status", ")", ":", "opts", "=", "self", ".", "model", ".", "_meta", "app_label", "=", "opts", ".", "app_label", "request", ".", "current_app", "=", "self", ".", "admin_site", ...
Renders the report errors template.
[ "Renders", "the", "report", "errors", "template", "." ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L166-L185
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.get_period_queryset
def get_period_queryset(self, request, period): """ Computes the queryset for a specific period and, perhaps, a request. :param request: current request being processed. :param period: current requested period. :return: a queryset """ qs = self.get_queryset(reque...
python
def get_period_queryset(self, request, period): """ Computes the queryset for a specific period and, perhaps, a request. :param request: current request being processed. :param period: current requested period. :return: a queryset """ qs = self.get_queryset(reque...
[ "def", "get_period_queryset", "(", "self", ",", "request", ",", "period", ")", ":", "qs", "=", "self", ".", "get_queryset", "(", "request", ")", "if", "not", "period", ":", "return", "qs", "if", "self", ".", "tracked_stamps", "==", "'create'", ":", "retu...
Computes the queryset for a specific period and, perhaps, a request. :param request: current request being processed. :param period: current requested period. :return: a queryset
[ "Computes", "the", "queryset", "for", "a", "specific", "period", "and", "perhaps", "a", "request", ".", ":", "param", "request", ":", "current", "request", "being", "processed", ".", ":", "param", "period", ":", "current", "requested", "period", ".", ":", ...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L187-L205
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/admin.py
TrackedLiveAdmin.report_view
def report_view(self, request, key, period): """ Processes the reporting action. """ if not self.has_change_permission(request, None): raise PermissionDenied reporters = self.get_reporters() try: reporter = reporters[key] except KeyError:...
python
def report_view(self, request, key, period): """ Processes the reporting action. """ if not self.has_change_permission(request, None): raise PermissionDenied reporters = self.get_reporters() try: reporter = reporters[key] except KeyError:...
[ "def", "report_view", "(", "self", ",", "request", ",", "key", ",", "period", ")", ":", "if", "not", "self", ".", "has_change_permission", "(", "request", ",", "None", ")", ":", "raise", "PermissionDenied", "reporters", "=", "self", ".", "get_reporters", "...
Processes the reporting action.
[ "Processes", "the", "reporting", "action", "." ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/admin.py#L207-L232
almcc/cinder-data
cinder_data/store.py
Store.find_record
def find_record(self, model_class, record_id, reload=False): """Return a instance of model_class from the API or the local cache. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. ...
python
def find_record(self, model_class, record_id, reload=False): """Return a instance of model_class from the API or the local cache. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. ...
[ "def", "find_record", "(", "self", ",", "model_class", ",", "record_id", ",", "reload", "=", "False", ")", ":", "cached_model", "=", "self", ".", "peek_record", "(", "model_class", ",", "record_id", ")", "if", "cached_model", "is", "not", "None", "and", "r...
Return a instance of model_class from the API or the local cache. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. record_id (int): The id of the record requested. reload (b...
[ "Return", "a", "instance", "of", "model_class", "from", "the", "API", "or", "the", "local", "cache", "." ]
train
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/store.py#L23-L39
almcc/cinder-data
cinder_data/store.py
Store.peek_record
def peek_record(self, model_class, record_id): """Return an instance of the model_class from the cache if it is present. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. record_...
python
def peek_record(self, model_class, record_id): """Return an instance of the model_class from the cache if it is present. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. record_...
[ "def", "peek_record", "(", "self", ",", "model_class", ",", "record_id", ")", ":", "if", "self", ".", "_cache", ":", "return", "self", ".", "_cache", ".", "get_record", "(", "model_class", ".", "__name__", ",", "record_id", ")", "else", ":", "return", "N...
Return an instance of the model_class from the cache if it is present. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. record_id (int): The id of the record requested. Returns...
[ "Return", "an", "instance", "of", "the", "model_class", "from", "the", "cache", "if", "it", "is", "present", "." ]
train
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/store.py#L41-L55
almcc/cinder-data
cinder_data/store.py
Store.find_all
def find_all(self, model_class, params={}): """Return an list of models from the API and caches the result. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. params (dict, option...
python
def find_all(self, model_class, params={}): """Return an list of models from the API and caches the result. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. params (dict, option...
[ "def", "find_all", "(", "self", ",", "model_class", ",", "params", "=", "{", "}", ")", ":", "url", "=", "'{host}/{namespace}/{model}{params}'", ".", "format", "(", "host", "=", "self", ".", "_host", ",", "namespace", "=", "self", ".", "_namespace", ",", ...
Return an list of models from the API and caches the result. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. params (dict, optional): Description Returns: list: A ...
[ "Return", "an", "list", "of", "models", "from", "the", "API", "and", "caches", "the", "result", "." ]
train
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/store.py#L57-L83
almcc/cinder-data
cinder_data/store.py
Store.peek_all
def peek_all(self, model_class): """Return a list of models from the local cache. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. Returns: list: A list of instances of...
python
def peek_all(self, model_class): """Return a list of models from the local cache. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. Returns: list: A list of instances of...
[ "def", "peek_all", "(", "self", ",", "model_class", ")", ":", "if", "self", ".", "_cache", ":", "return", "self", ".", "_cache", ".", "get_records", "(", "model_class", ".", "__name__", ")", "else", ":", "return", "[", "]" ]
Return a list of models from the local cache. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. Returns: list: A list of instances of you model_class or and empty list.
[ "Return", "a", "list", "of", "models", "from", "the", "local", "cache", "." ]
train
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/store.py#L85-L98
almcc/cinder-data
cinder_data/store.py
Store._get_record
def _get_record(self, model_class, record_id): """Get a single record from the API. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. record_id (int): The id of the record reques...
python
def _get_record(self, model_class, record_id): """Get a single record from the API. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. record_id (int): The id of the record reques...
[ "def", "_get_record", "(", "self", ",", "model_class", ",", "record_id", ")", ":", "url", "=", "'{host}/{namespace}/{model}/{id}'", ".", "format", "(", "host", "=", "self", ".", "_host", ",", "namespace", "=", "self", ".", "_namespace", ",", "model", "=", ...
Get a single record from the API. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. record_id (int): The id of the record requested. Returns: :class:`cinder_data.mod...
[ "Get", "a", "single", "record", "from", "the", "API", "." ]
train
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/store.py#L100-L123
almcc/cinder-data
cinder_data/store.py
Store._translate_name
def _translate_name(name): """Translate the class name to the API endpoint. For example, Car would become cars, FastCar would become fast-cars. Args: name (string): Camel case name (singular) Returns: string: A pluraised, dasherized string. """ ...
python
def _translate_name(name): """Translate the class name to the API endpoint. For example, Car would become cars, FastCar would become fast-cars. Args: name (string): Camel case name (singular) Returns: string: A pluraised, dasherized string. """ ...
[ "def", "_translate_name", "(", "name", ")", ":", "underscored", "=", "inflection", ".", "underscore", "(", "name", ")", "dasherized", "=", "inflection", ".", "dasherize", "(", "underscored", ")", "words", "=", "dasherized", ".", "split", "(", "'-'", ")", "...
Translate the class name to the API endpoint. For example, Car would become cars, FastCar would become fast-cars. Args: name (string): Camel case name (singular) Returns: string: A pluraised, dasherized string.
[ "Translate", "the", "class", "name", "to", "the", "API", "endpoint", "." ]
train
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/store.py#L139-L155
almcc/cinder-data
cinder_data/store.py
Store._build_param_string
def _build_param_string(params): """Build query params string from a dictionary. Args: params (dict): A dictionary of params Returns: string: A valid url query params string. """ pairs = [] for key, value in params.iteritems(): if val...
python
def _build_param_string(params): """Build query params string from a dictionary. Args: params (dict): A dictionary of params Returns: string: A valid url query params string. """ pairs = [] for key, value in params.iteritems(): if val...
[ "def", "_build_param_string", "(", "params", ")", ":", "pairs", "=", "[", "]", "for", "key", ",", "value", "in", "params", ".", "iteritems", "(", ")", ":", "if", "value", "is", "None", ":", "value", "=", "''", "pairs", ".", "append", "(", "'{0}={1}'"...
Build query params string from a dictionary. Args: params (dict): A dictionary of params Returns: string: A valid url query params string.
[ "Build", "query", "params", "string", "from", "a", "dictionary", "." ]
train
https://github.com/almcc/cinder-data/blob/4159a5186c4b4fc32354749892e86130530f6ec5/cinder_data/store.py#L158-L174
neithere/django-navigation
navigation/resolvers.py
_resolve_by_settings_urls
def _resolve_by_settings_urls(request, url, urlconf=None): """ Finds appropriate URL in settings dictionary ``NAVIGATION_URL_MAP`` and returns the Crumb object based on the value. The values can be strings or functions (or any callables). The functions are called as views. The callable values do not...
python
def _resolve_by_settings_urls(request, url, urlconf=None): """ Finds appropriate URL in settings dictionary ``NAVIGATION_URL_MAP`` and returns the Crumb object based on the value. The values can be strings or functions (or any callables). The functions are called as views. The callable values do not...
[ "def", "_resolve_by_settings_urls", "(", "request", ",", "url", ",", "urlconf", "=", "None", ")", ":", "mapping", "=", "getattr", "(", "settings", ",", "'NAVIGATION_URL_MAP'", ",", "{", "}", ")", "title", "=", "mapping", ".", "get", "(", "url", ",", "Non...
Finds appropriate URL in settings dictionary ``NAVIGATION_URL_MAP`` and returns the Crumb object based on the value. The values can be strings or functions (or any callables). The functions are called as views. The callable values do not require that an existing endpoint and always get only one argument...
[ "Finds", "appropriate", "URL", "in", "settings", "dictionary", "NAVIGATION_URL_MAP", "and", "returns", "the", "Crumb", "object", "based", "on", "the", "value", ".", "The", "values", "can", "be", "strings", "or", "functions", "(", "or", "any", "callables", ")",...
train
https://github.com/neithere/django-navigation/blob/aff8d671a8431c84dde65cba6236ea8c16a08b4d/navigation/resolvers.py#L94-L116
neithere/django-navigation
navigation/resolvers.py
_resolve_by_callback
def _resolve_by_callback(request, url, urlconf=None): """ Finds a view function by urlconf. If the function has attribute 'navigation', it is used as breadcrumb title. Such title can be either a callable or an object with `__unicode__` attribute. If it is callable, it must follow the views API (i.e....
python
def _resolve_by_callback(request, url, urlconf=None): """ Finds a view function by urlconf. If the function has attribute 'navigation', it is used as breadcrumb title. Such title can be either a callable or an object with `__unicode__` attribute. If it is callable, it must follow the views API (i.e....
[ "def", "_resolve_by_callback", "(", "request", ",", "url", ",", "urlconf", "=", "None", ")", ":", "try", ":", "callback", ",", "args", ",", "kwargs", "=", "_resolve_url", "(", "url", ",", "request", ",", "urlconf", "=", "urlconf", ")", "except", "urlreso...
Finds a view function by urlconf. If the function has attribute 'navigation', it is used as breadcrumb title. Such title can be either a callable or an object with `__unicode__` attribute. If it is callable, it must follow the views API (i.e. the only required argument is request object). It is also exp...
[ "Finds", "a", "view", "function", "by", "urlconf", ".", "If", "the", "function", "has", "attribute", "navigation", "it", "is", "used", "as", "breadcrumb", "title", ".", "Such", "title", "can", "be", "either", "a", "callable", "or", "an", "object", "with", ...
train
https://github.com/neithere/django-navigation/blob/aff8d671a8431c84dde65cba6236ea8c16a08b4d/navigation/resolvers.py#L150-L184
selenol/selenol-python
selenol_python/connections.py
SelenolWSConnection.send
def send(self, message): """Send a the defined message to the backend. :param message: Message to be send, usually a Python dictionary. """ try: self.ws.send(json.dumps(message)) except websocket._exceptions.WebSocketConnectionClosedException: raise Selen...
python
def send(self, message): """Send a the defined message to the backend. :param message: Message to be send, usually a Python dictionary. """ try: self.ws.send(json.dumps(message)) except websocket._exceptions.WebSocketConnectionClosedException: raise Selen...
[ "def", "send", "(", "self", ",", "message", ")", ":", "try", ":", "self", ".", "ws", ".", "send", "(", "json", ".", "dumps", "(", "message", ")", ")", "except", "websocket", ".", "_exceptions", ".", "WebSocketConnectionClosedException", ":", "raise", "Se...
Send a the defined message to the backend. :param message: Message to be send, usually a Python dictionary.
[ "Send", "a", "the", "defined", "message", "to", "the", "backend", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/connections.py#L37-L45
selenol/selenol-python
selenol_python/connections.py
SelenolWSConnection.recv
def recv(self): """Receive message from the backend or wait unilt next message.""" try: message = self.ws.recv() return json.loads(message) except websocket._exceptions.WebSocketConnectionClosedException as ex: raise SelenolWebSocketClosedException() from ex
python
def recv(self): """Receive message from the backend or wait unilt next message.""" try: message = self.ws.recv() return json.loads(message) except websocket._exceptions.WebSocketConnectionClosedException as ex: raise SelenolWebSocketClosedException() from ex
[ "def", "recv", "(", "self", ")", ":", "try", ":", "message", "=", "self", ".", "ws", ".", "recv", "(", ")", "return", "json", ".", "loads", "(", "message", ")", "except", "websocket", ".", "_exceptions", ".", "WebSocketConnectionClosedException", "as", "...
Receive message from the backend or wait unilt next message.
[ "Receive", "message", "from", "the", "backend", "or", "wait", "unilt", "next", "message", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/connections.py#L47-L53
krukas/Trionyx
trionyx/trionyx/management/commands/create_app.py
Command.handle
def handle(self, *args, **options): """Create new app""" quickstart = Quickstart() try: quickstart.create_app(os.path.join(settings.BASE_DIR, 'apps'), options.get('name')) self.stdout.write( self.style.SUCCESS("Successfully created app ({name}), don't for...
python
def handle(self, *args, **options): """Create new app""" quickstart = Quickstart() try: quickstart.create_app(os.path.join(settings.BASE_DIR, 'apps'), options.get('name')) self.stdout.write( self.style.SUCCESS("Successfully created app ({name}), don't for...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "quickstart", "=", "Quickstart", "(", ")", "try", ":", "quickstart", ".", "create_app", "(", "os", ".", "path", ".", "join", "(", "settings", ".", "BASE_DIR", ",", ...
Create new app
[ "Create", "new", "app" ]
train
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/management/commands/create_app.py#L25-L38
ANCIR/granoloader
granoloader/command.py
make_client
def make_client(host, project_name, api_key, create_project): """ Instantiate the grano client based on environment variables or command line settings. """ if host is None: raise click.BadParameter('No grano server host is set', param=host) if project_name is None: raise click.BadParamet...
python
def make_client(host, project_name, api_key, create_project): """ Instantiate the grano client based on environment variables or command line settings. """ if host is None: raise click.BadParameter('No grano server host is set', param=host) if project_name is None: raise click.BadParamet...
[ "def", "make_client", "(", "host", ",", "project_name", ",", "api_key", ",", "create_project", ")", ":", "if", "host", "is", "None", ":", "raise", "click", ".", "BadParameter", "(", "'No grano server host is set'", ",", "param", "=", "host", ")", "if", "proj...
Instantiate the grano client based on environment variables or command line settings.
[ "Instantiate", "the", "grano", "client", "based", "on", "environment", "variables", "or", "command", "line", "settings", "." ]
train
https://github.com/ANCIR/granoloader/blob/c48b1bd50403dd611340c5f51637f7c5ca54059c/granoloader/command.py#L21-L40
ANCIR/granoloader
granoloader/command.py
csv
def csv(ctx, force, threads, mapping, data): """ Load CSV data into a grano instance using a mapping specification. """ # Find out how many lines there are (for the progress bar). lines = 0 for line in DictReader(data): lines += 1 data.seek(0) # set up objects mapping = yaml.load(m...
python
def csv(ctx, force, threads, mapping, data): """ Load CSV data into a grano instance using a mapping specification. """ # Find out how many lines there are (for the progress bar). lines = 0 for line in DictReader(data): lines += 1 data.seek(0) # set up objects mapping = yaml.load(m...
[ "def", "csv", "(", "ctx", ",", "force", ",", "threads", ",", "mapping", ",", "data", ")", ":", "# Find out how many lines there are (for the progress bar).", "lines", "=", "0", "for", "line", "in", "DictReader", "(", "data", ")", ":", "lines", "+=", "1", "da...
Load CSV data into a grano instance using a mapping specification.
[ "Load", "CSV", "data", "into", "a", "grano", "instance", "using", "a", "mapping", "specification", "." ]
train
https://github.com/ANCIR/granoloader/blob/c48b1bd50403dd611340c5f51637f7c5ca54059c/granoloader/command.py#L69-L105
ANCIR/granoloader
granoloader/command.py
schema
def schema(ctx, schema): """ Load schema definitions from a YAML file. """ data = yaml.load(schema) if not isinstance(data, (list, tuple)): data = [data] with click.progressbar(data, label=schema.name) as bar: for schema in bar: ctx.obj['grano'].schemata.upsert(schema)
python
def schema(ctx, schema): """ Load schema definitions from a YAML file. """ data = yaml.load(schema) if not isinstance(data, (list, tuple)): data = [data] with click.progressbar(data, label=schema.name) as bar: for schema in bar: ctx.obj['grano'].schemata.upsert(schema)
[ "def", "schema", "(", "ctx", ",", "schema", ")", ":", "data", "=", "yaml", ".", "load", "(", "schema", ")", "if", "not", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ")", ")", ":", "data", "=", "[", "data", "]", "with", "click", "...
Load schema definitions from a YAML file.
[ "Load", "schema", "definitions", "from", "a", "YAML", "file", "." ]
train
https://github.com/ANCIR/granoloader/blob/c48b1bd50403dd611340c5f51637f7c5ca54059c/granoloader/command.py#L111-L118
JNRowe/jnrbase
jnrbase/json_datetime.py
json_using_iso8601
def json_using_iso8601(__obj: Dict) -> Dict: """Parse ISO-8601 values from JSON databases. See :class:`json.JSONDecoder` Args: __obj: Object to decode """ for key, value in __obj.items(): with suppress(TypeError, ValueError): __obj[key] = parse_datetime(value) w...
python
def json_using_iso8601(__obj: Dict) -> Dict: """Parse ISO-8601 values from JSON databases. See :class:`json.JSONDecoder` Args: __obj: Object to decode """ for key, value in __obj.items(): with suppress(TypeError, ValueError): __obj[key] = parse_datetime(value) w...
[ "def", "json_using_iso8601", "(", "__obj", ":", "Dict", ")", "->", "Dict", ":", "for", "key", ",", "value", "in", "__obj", ".", "items", "(", ")", ":", "with", "suppress", "(", "TypeError", ",", "ValueError", ")", ":", "__obj", "[", "key", "]", "=", ...
Parse ISO-8601 values from JSON databases. See :class:`json.JSONDecoder` Args: __obj: Object to decode
[ "Parse", "ISO", "-", "8601", "values", "from", "JSON", "databases", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/json_datetime.py#L61-L74
Apitax/Apitax
apitax/api/controllers/migrations/scriptax_controller.py
create_driver_script
def create_driver_script(name, create=None): # noqa: E501 """Create a new script Create a new script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param create: The data needed to create this script :type create: dict | bytes :rtype: Response """ ...
python
def create_driver_script(name, create=None): # noqa: E501 """Create a new script Create a new script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param create: The data needed to create this script :type create: dict | bytes :rtype: Response """ ...
[ "def", "create_driver_script", "(", "name", ",", "create", "=", "None", ")", ":", "# noqa: E501", "if", "connexion", ".", "request", ".", "is_json", ":", "create", "=", "Create1", ".", "from_dict", "(", "connexion", ".", "request", ".", "get_json", "(", ")...
Create a new script Create a new script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param create: The data needed to create this script :type create: dict | bytes :rtype: Response
[ "Create", "a", "new", "script" ]
train
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/scriptax_controller.py#L20-L44
Apitax/Apitax
apitax/api/controllers/migrations/scriptax_controller.py
get_driver_script
def get_driver_script(name, name2=None): # noqa: E501 """Retrieve the contents of a script Retrieve the contents of a script # noqa: E501 :param name2: Get status of a driver with this name :type name2: str :param name: The script name. :type name: str :rtype: Response """ respon...
python
def get_driver_script(name, name2=None): # noqa: E501 """Retrieve the contents of a script Retrieve the contents of a script # noqa: E501 :param name2: Get status of a driver with this name :type name2: str :param name: The script name. :type name: str :rtype: Response """ respon...
[ "def", "get_driver_script", "(", "name", ",", "name2", "=", "None", ")", ":", "# noqa: E501", "response", "=", "errorIfUnauthorized", "(", "role", "=", "'user'", ")", "if", "response", ":", "return", "response", "else", ":", "response", "=", "ApitaxResponse", ...
Retrieve the contents of a script Retrieve the contents of a script # noqa: E501 :param name2: Get status of a driver with this name :type name2: str :param name: The script name. :type name: str :rtype: Response
[ "Retrieve", "the", "contents", "of", "a", "script" ]
train
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/scriptax_controller.py#L76-L102
Apitax/Apitax
apitax/api/controllers/migrations/scriptax_controller.py
get_driver_script_catalog
def get_driver_script_catalog(name): # noqa: E501 """Retrieve the script catalog Retrieve the script catalog # noqa: E501 :param name: Get status of a driver with this name :type name: str :rtype: Response """ response = errorIfUnauthorized(role='user') if response: return r...
python
def get_driver_script_catalog(name): # noqa: E501 """Retrieve the script catalog Retrieve the script catalog # noqa: E501 :param name: Get status of a driver with this name :type name: str :rtype: Response """ response = errorIfUnauthorized(role='user') if response: return r...
[ "def", "get_driver_script_catalog", "(", "name", ")", ":", "# noqa: E501", "response", "=", "errorIfUnauthorized", "(", "role", "=", "'user'", ")", "if", "response", ":", "return", "response", "else", ":", "response", "=", "ApitaxResponse", "(", ")", "driver", ...
Retrieve the script catalog Retrieve the script catalog # noqa: E501 :param name: Get status of a driver with this name :type name: str :rtype: Response
[ "Retrieve", "the", "script", "catalog" ]
train
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/scriptax_controller.py#L106-L127
Apitax/Apitax
apitax/api/controllers/migrations/scriptax_controller.py
rename_driver_script
def rename_driver_script(name, rename=None): # noqa: E501 """Rename a script Rename a script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param rename: The data needed to save this script :type rename: dict | bytes :rtype: Response """ if conne...
python
def rename_driver_script(name, rename=None): # noqa: E501 """Rename a script Rename a script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param rename: The data needed to save this script :type rename: dict | bytes :rtype: Response """ if conne...
[ "def", "rename_driver_script", "(", "name", ",", "rename", "=", "None", ")", ":", "# noqa: E501", "if", "connexion", ".", "request", ".", "is_json", ":", "rename", "=", "Rename", ".", "from_dict", "(", "connexion", ".", "request", ".", "get_json", "(", ")"...
Rename a script Rename a script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param rename: The data needed to save this script :type rename: dict | bytes :rtype: Response
[ "Rename", "a", "script" ]
train
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/scriptax_controller.py#L131-L156
Apitax/Apitax
apitax/api/controllers/migrations/scriptax_controller.py
save_driver_script
def save_driver_script(name, save=None): # noqa: E501 """Save a script Save a script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param save: The data needed to save this script :type save: dict | bytes :rtype: Response """ if connexion.request...
python
def save_driver_script(name, save=None): # noqa: E501 """Save a script Save a script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param save: The data needed to save this script :type save: dict | bytes :rtype: Response """ if connexion.request...
[ "def", "save_driver_script", "(", "name", ",", "save", "=", "None", ")", ":", "# noqa: E501", "if", "connexion", ".", "request", ".", "is_json", ":", "save", "=", "Save1", ".", "from_dict", "(", "connexion", ".", "request", ".", "get_json", "(", ")", ")"...
Save a script Save a script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param save: The data needed to save this script :type save: dict | bytes :rtype: Response
[ "Save", "a", "script" ]
train
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/scriptax_controller.py#L160-L184
lddubeau/glerbl
glerbl/__init__.py
get_tmpdir
def get_tmpdir(): """ On first invocation, creates a temporary directory and returns its path. Subsequent invocations uses the same directory. :returns: A temporary directory created for this run of glerbl. :rtype: :class:`str` """ global __tmpdir if __tmpdir is not None: return...
python
def get_tmpdir(): """ On first invocation, creates a temporary directory and returns its path. Subsequent invocations uses the same directory. :returns: A temporary directory created for this run of glerbl. :rtype: :class:`str` """ global __tmpdir if __tmpdir is not None: return...
[ "def", "get_tmpdir", "(", ")", ":", "global", "__tmpdir", "if", "__tmpdir", "is", "not", "None", ":", "return", "__tmpdir", "__tmpdir", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'.tmp.glerbl.'", ",", "dir", "=", "\".\"", ")", "atexit", ".", "...
On first invocation, creates a temporary directory and returns its path. Subsequent invocations uses the same directory. :returns: A temporary directory created for this run of glerbl. :rtype: :class:`str`
[ "On", "first", "invocation", "creates", "a", "temporary", "directory", "and", "returns", "its", "path", ".", "Subsequent", "invocations", "uses", "the", "same", "directory", "." ]
train
https://github.com/lddubeau/glerbl/blob/b43adf851f8ce4c5b1dba22ee3556a169681bce1/glerbl/__init__.py#L17-L32
lddubeau/glerbl
glerbl/__init__.py
get_against
def get_against(): """ Determines the revision against which the staged data ought to be checked. :returns: The revision. :rtype: :class:`str` """ global __cached_against if __cached_against is not None: return __cached_against status = subprocess.call(["git", "rev-parse", "--v...
python
def get_against(): """ Determines the revision against which the staged data ought to be checked. :returns: The revision. :rtype: :class:`str` """ global __cached_against if __cached_against is not None: return __cached_against status = subprocess.call(["git", "rev-parse", "--v...
[ "def", "get_against", "(", ")", ":", "global", "__cached_against", "if", "__cached_against", "is", "not", "None", ":", "return", "__cached_against", "status", "=", "subprocess", ".", "call", "(", "[", "\"git\"", ",", "\"rev-parse\"", ",", "\"--verify\"", ",", ...
Determines the revision against which the staged data ought to be checked. :returns: The revision. :rtype: :class:`str`
[ "Determines", "the", "revision", "against", "which", "the", "staged", "data", "ought", "to", "be", "checked", "." ]
train
https://github.com/lddubeau/glerbl/blob/b43adf851f8ce4c5b1dba22ee3556a169681bce1/glerbl/__init__.py#L36-L57
JNRowe/jnrbase
jnrbase/entry.py
entry_point
def entry_point(__func: Callable) -> Callable: """Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run """ if __func.__module__ == '__main__': import sys sys.exit(__func()) ...
python
def entry_point(__func: Callable) -> Callable: """Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run """ if __func.__module__ == '__main__': import sys sys.exit(__func()) ...
[ "def", "entry_point", "(", "__func", ":", "Callable", ")", "->", "Callable", ":", "if", "__func", ".", "__module__", "==", "'__main__'", ":", "import", "sys", "sys", ".", "exit", "(", "__func", "(", ")", ")", "else", ":", "return", "__func" ]
Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run
[ "Execute", "function", "when", "module", "is", "run", "directly", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/entry.py#L24-L37
ryanhorn/tyoiOAuth2
tyoi/oauth2/grants/__init__.py
AuthorizationCode.build_auth_uri
def build_auth_uri(endpoint, client_id, redirect_uri=None, scope=None, state=None): """ Helper method builds the uri that a user must be redirected to for authentication/authorization using the authorization_code grant type. endpoint - The authorization endpoint client_...
python
def build_auth_uri(endpoint, client_id, redirect_uri=None, scope=None, state=None): """ Helper method builds the uri that a user must be redirected to for authentication/authorization using the authorization_code grant type. endpoint - The authorization endpoint client_...
[ "def", "build_auth_uri", "(", "endpoint", ",", "client_id", ",", "redirect_uri", "=", "None", ",", "scope", "=", "None", ",", "state", "=", "None", ")", ":", "params", "=", "{", "'response_type'", ":", "'code'", ",", "'client_id'", ":", "client_id", "}", ...
Helper method builds the uri that a user must be redirected to for authentication/authorization using the authorization_code grant type. endpoint - The authorization endpoint client_id - The client id redirect_uri - The redirect uri scope - A list of permissio...
[ "Helper", "method", "builds", "the", "uri", "that", "a", "user", "must", "be", "redirected", "to", "for", "authentication", "/", "authorization", "using", "the", "authorization_code", "grant", "type", "." ]
train
https://github.com/ryanhorn/tyoiOAuth2/blob/e6a388868ee05c5fef3bec795c5efd88c19b0955/tyoi/oauth2/grants/__init__.py#L21-L47
DallasMorningNews/django-datafreezer
datafreezer/models.py
create_col_nums
def create_col_nums(): """Return column numbers and letters that repeat up to NUM_REPEATS. I.e., NUM_REPEATS = 2 would return a list of 26 * 26 = 676 2-tuples. """ NUM_REPEATS = 2 column_letters = list( string.ascii_uppercase ) + map( ''.join, itertools.product( ...
python
def create_col_nums(): """Return column numbers and letters that repeat up to NUM_REPEATS. I.e., NUM_REPEATS = 2 would return a list of 26 * 26 = 676 2-tuples. """ NUM_REPEATS = 2 column_letters = list( string.ascii_uppercase ) + map( ''.join, itertools.product( ...
[ "def", "create_col_nums", "(", ")", ":", "NUM_REPEATS", "=", "2", "column_letters", "=", "list", "(", "string", ".", "ascii_uppercase", ")", "+", "map", "(", "''", ".", "join", ",", "itertools", ".", "product", "(", "string", ".", "ascii_uppercase", ",", ...
Return column numbers and letters that repeat up to NUM_REPEATS. I.e., NUM_REPEATS = 2 would return a list of 26 * 26 = 676 2-tuples.
[ "Return", "column", "numbers", "and", "letters", "that", "repeat", "up", "to", "NUM_REPEATS", "." ]
train
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/models.py#L18-L41
emin63/eyap
eyap/core/redis_comments.py
RedisCommentThread.add_comment
def add_comment(self, body, allow_create=False, allow_hashes=False, summary=None): """Add comment as required by comments.CommentThread parent class. """ thread_id = self.lookup_thread_id() if not allow_create and not self.redis.exists(thread_id): raise Va...
python
def add_comment(self, body, allow_create=False, allow_hashes=False, summary=None): """Add comment as required by comments.CommentThread parent class. """ thread_id = self.lookup_thread_id() if not allow_create and not self.redis.exists(thread_id): raise Va...
[ "def", "add_comment", "(", "self", ",", "body", ",", "allow_create", "=", "False", ",", "allow_hashes", "=", "False", ",", "summary", "=", "None", ")", ":", "thread_id", "=", "self", ".", "lookup_thread_id", "(", ")", "if", "not", "allow_create", "and", ...
Add comment as required by comments.CommentThread parent class.
[ "Add", "comment", "as", "required", "by", "comments", ".", "CommentThread", "parent", "class", "." ]
train
https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/redis_comments.py#L25-L45
CivicSpleen/ckcache
ckcache/async.py
submit_task
def submit_task(rel_path, cache_string, buffer): """Put an upload job on the queue, and start the thread if required""" global upload_queue global upload_thread upload_queue.put((rel_path, cache_string, buffer)) if upload_thread is None or not upload_thread.is_alive(): upload_thread = Uploa...
python
def submit_task(rel_path, cache_string, buffer): """Put an upload job on the queue, and start the thread if required""" global upload_queue global upload_thread upload_queue.put((rel_path, cache_string, buffer)) if upload_thread is None or not upload_thread.is_alive(): upload_thread = Uploa...
[ "def", "submit_task", "(", "rel_path", ",", "cache_string", ",", "buffer", ")", ":", "global", "upload_queue", "global", "upload_thread", "upload_queue", ".", "put", "(", "(", "rel_path", ",", "cache_string", ",", "buffer", ")", ")", "if", "upload_thread", "is...
Put an upload job on the queue, and start the thread if required
[ "Put", "an", "upload", "job", "on", "the", "queue", "and", "start", "the", "thread", "if", "required" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/async.py#L53-L61
CivicSpleen/ckcache
ckcache/async.py
ThreadedWriteCache.remove
def remove(self, rel_path, propagate=False): '''Delete the file from the cache, and from the upstream''' if not self.upstream: raise Exception("Must have an upstream") # Must always propagate, since this is really just a filter. self.upstream.remove(self._rename(rel_path), ...
python
def remove(self, rel_path, propagate=False): '''Delete the file from the cache, and from the upstream''' if not self.upstream: raise Exception("Must have an upstream") # Must always propagate, since this is really just a filter. self.upstream.remove(self._rename(rel_path), ...
[ "def", "remove", "(", "self", ",", "rel_path", ",", "propagate", "=", "False", ")", ":", "if", "not", "self", ".", "upstream", ":", "raise", "Exception", "(", "\"Must have an upstream\"", ")", "# Must always propagate, since this is really just a filter.", "self", "...
Delete the file from the cache, and from the upstream
[ "Delete", "the", "file", "from", "the", "cache", "and", "from", "the", "upstream" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/async.py#L163-L170
CivicSpleen/ckcache
ckcache/async.py
ThreadedWriteCache.list
def list(self, path=None, with_metadata=False, include_partitions=False): '''get a list of all of the files in the repository''' return self.upstream.list( path, with_metadata=with_metadata, include_partitions=include_partitions)
python
def list(self, path=None, with_metadata=False, include_partitions=False): '''get a list of all of the files in the repository''' return self.upstream.list( path, with_metadata=with_metadata, include_partitions=include_partitions)
[ "def", "list", "(", "self", ",", "path", "=", "None", ",", "with_metadata", "=", "False", ",", "include_partitions", "=", "False", ")", ":", "return", "self", ".", "upstream", ".", "list", "(", "path", ",", "with_metadata", "=", "with_metadata", ",", "in...
get a list of all of the files in the repository
[ "get", "a", "list", "of", "all", "of", "the", "files", "in", "the", "repository" ]
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/async.py#L190-L195
herereadthis/anyone
anyone/anyone.py
Poem.get_verse
def get_verse(self, v=1): """Get a specific verse.""" verse_count = len(self.verses) if v - 1 < verse_count: return self.verses[v - 1]
python
def get_verse(self, v=1): """Get a specific verse.""" verse_count = len(self.verses) if v - 1 < verse_count: return self.verses[v - 1]
[ "def", "get_verse", "(", "self", ",", "v", "=", "1", ")", ":", "verse_count", "=", "len", "(", "self", ".", "verses", ")", "if", "v", "-", "1", "<", "verse_count", ":", "return", "self", ".", "verses", "[", "v", "-", "1", "]" ]
Get a specific verse.
[ "Get", "a", "specific", "verse", "." ]
train
https://github.com/herereadthis/anyone/blob/ac9917014ec5d4882df89b1757416e9ceca86edb/anyone/anyone.py#L35-L39
herereadthis/anyone
anyone/anyone.py
Poem.get_line
def get_line(self, line=1): """Return a specific line.""" verse_size = len(self.get_verse()) + 1 if line > 1: verse = math.floor((line - 1) / verse_size) line_in_verse = (line - 1) % verse_size try: return self.verses[verse][line_in_verse] ...
python
def get_line(self, line=1): """Return a specific line.""" verse_size = len(self.get_verse()) + 1 if line > 1: verse = math.floor((line - 1) / verse_size) line_in_verse = (line - 1) % verse_size try: return self.verses[verse][line_in_verse] ...
[ "def", "get_line", "(", "self", ",", "line", "=", "1", ")", ":", "verse_size", "=", "len", "(", "self", ".", "get_verse", "(", ")", ")", "+", "1", "if", "line", ">", "1", ":", "verse", "=", "math", ".", "floor", "(", "(", "line", "-", "1", ")...
Return a specific line.
[ "Return", "a", "specific", "line", "." ]
train
https://github.com/herereadthis/anyone/blob/ac9917014ec5d4882df89b1757416e9ceca86edb/anyone/anyone.py#L41-L52
herereadthis/anyone
anyone/anyone.py
Poem.print_poem
def print_poem(self): """Print all the verses.""" for index, verse in enumerate(self.verses): for line in verse: print(line) if index != len(self.verses) - 1: print('')
python
def print_poem(self): """Print all the verses.""" for index, verse in enumerate(self.verses): for line in verse: print(line) if index != len(self.verses) - 1: print('')
[ "def", "print_poem", "(", "self", ")", ":", "for", "index", ",", "verse", "in", "enumerate", "(", "self", ".", "verses", ")", ":", "for", "line", "in", "verse", ":", "print", "(", "line", ")", "if", "index", "!=", "len", "(", "self", ".", "verses",...
Print all the verses.
[ "Print", "all", "the", "verses", "." ]
train
https://github.com/herereadthis/anyone/blob/ac9917014ec5d4882df89b1757416e9ceca86edb/anyone/anyone.py#L54-L60
Othernet-Project/squery-pg
squery_pg/migrations.py
get_mods
def get_mods(package): """ List all loadable python modules in a directory This function looks inside the specified directory for all files that look like Python modules with a numeric prefix and returns them. It will omit any duplicates and return file names without extension. :param package: pac...
python
def get_mods(package): """ List all loadable python modules in a directory This function looks inside the specified directory for all files that look like Python modules with a numeric prefix and returns them. It will omit any duplicates and return file names without extension. :param package: pac...
[ "def", "get_mods", "(", "package", ")", ":", "pkgdir", "=", "package", ".", "__path__", "[", "0", "]", "matches", "=", "filter", "(", "None", ",", "[", "PYMOD_RE", ".", "match", "(", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "pkgdir", ...
List all loadable python modules in a directory This function looks inside the specified directory for all files that look like Python modules with a numeric prefix and returns them. It will omit any duplicates and return file names without extension. :param package: package object :returns: ...
[ "List", "all", "loadable", "python", "modules", "in", "a", "directory" ]
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L45-L60
Othernet-Project/squery-pg
squery_pg/migrations.py
get_new
def get_new(modules, min_major_version, min_minor_version): """ Get list of migrations that haven't been run yet :param modules: iterable containing module names :param min_major_version: minimum major version :param min_minor_version: minimum minor version :returns: retur...
python
def get_new(modules, min_major_version, min_minor_version): """ Get list of migrations that haven't been run yet :param modules: iterable containing module names :param min_major_version: minimum major version :param min_minor_version: minimum minor version :returns: retur...
[ "def", "get_new", "(", "modules", ",", "min_major_version", ",", "min_minor_version", ")", ":", "for", "mod_data", "in", "modules", ":", "(", "modname", ",", "mod_major_version", ",", "mod_minor_version", ")", "=", "mod_data", "if", "(", "mod_major_version", ">"...
Get list of migrations that haven't been run yet :param modules: iterable containing module names :param min_major_version: minimum major version :param min_minor_version: minimum minor version :returns: return an iterator that yields only items which ...
[ "Get", "list", "of", "migrations", "that", "haven", "t", "been", "run", "yet" ]
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L63-L77
Othernet-Project/squery-pg
squery_pg/migrations.py
load_mod
def load_mod(module, package): """ Load a module named ``module`` from given search``path`` The module path prefix is set according to the ``prefix`` argument. By defualt the module is loaded as if it comes from a global 'db_migrations' package. As such, it may conflict with any 'db_migration' pac...
python
def load_mod(module, package): """ Load a module named ``module`` from given search``path`` The module path prefix is set according to the ``prefix`` argument. By defualt the module is loaded as if it comes from a global 'db_migrations' package. As such, it may conflict with any 'db_migration' pac...
[ "def", "load_mod", "(", "module", ",", "package", ")", ":", "name", "=", "'%s.%s'", "%", "(", "package", ".", "__name__", ",", "module", ")", "if", "name", "in", "sys", ".", "modules", ":", "return", "sys", ".", "modules", "[", "name", "]", "return",...
Load a module named ``module`` from given search``path`` The module path prefix is set according to the ``prefix`` argument. By defualt the module is loaded as if it comes from a global 'db_migrations' package. As such, it may conflict with any 'db_migration' package. The module can be looked up in ``...
[ "Load", "a", "module", "named", "module", "from", "given", "search", "path" ]
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L80-L100
Othernet-Project/squery-pg
squery_pg/migrations.py
unpack_version
def unpack_version(version): """Unpack a single version integer into the two major and minor components.""" minor_version = version % VERSION_MULTIPLIER major_version = (version - minor_version) / VERSION_MULTIPLIER return (major_version, minor_version)
python
def unpack_version(version): """Unpack a single version integer into the two major and minor components.""" minor_version = version % VERSION_MULTIPLIER major_version = (version - minor_version) / VERSION_MULTIPLIER return (major_version, minor_version)
[ "def", "unpack_version", "(", "version", ")", ":", "minor_version", "=", "version", "%", "VERSION_MULTIPLIER", "major_version", "=", "(", "version", "-", "minor_version", ")", "/", "VERSION_MULTIPLIER", "return", "(", "major_version", ",", "minor_version", ")" ]
Unpack a single version integer into the two major and minor components.
[ "Unpack", "a", "single", "version", "integer", "into", "the", "two", "major", "and", "minor", "components", "." ]
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L108-L113
Othernet-Project/squery-pg
squery_pg/migrations.py
get_version
def get_version(db, name): """ Query database and return migration version. WARNING: side effecting function! if no version information can be found, any existing database matching the passed one's name will be deleted and recreated. :param db: connetion object :param name: associated name ...
python
def get_version(db, name): """ Query database and return migration version. WARNING: side effecting function! if no version information can be found, any existing database matching the passed one's name will be deleted and recreated. :param db: connetion object :param name: associated name ...
[ "def", "get_version", "(", "db", ",", "name", ")", ":", "try", ":", "result", "=", "db", ".", "fetchone", "(", "GET_VERSION_SQL", ",", "dict", "(", "name", "=", "name", ")", ")", "except", "psycopg2", ".", "ProgrammingError", "as", "exc", ":", "if", ...
Query database and return migration version. WARNING: side effecting function! if no version information can be found, any existing database matching the passed one's name will be deleted and recreated. :param db: connetion object :param name: associated name :returns: current migrati...
[ "Query", "database", "and", "return", "migration", "version", ".", "WARNING", ":", "side", "effecting", "function!", "if", "no", "version", "information", "can", "be", "found", "any", "existing", "database", "matching", "the", "passed", "one", "s", "name", "wi...
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L123-L143
Othernet-Project/squery-pg
squery_pg/migrations.py
set_version
def set_version(db, name, major_version, minor_version): """ Set database migration version :param db: connetion object :param name: associated name :param major_version: integer major version of migration :param minor_version: integer minor version of migration """ ...
python
def set_version(db, name, major_version, minor_version): """ Set database migration version :param db: connetion object :param name: associated name :param major_version: integer major version of migration :param minor_version: integer minor version of migration """ ...
[ "def", "set_version", "(", "db", ",", "name", ",", "major_version", ",", "minor_version", ")", ":", "version", "=", "pack_version", "(", "major_version", ",", "minor_version", ")", "db", ".", "execute", "(", "SET_VERSION_SQL", ",", "dict", "(", "name", "=", ...
Set database migration version :param db: connetion object :param name: associated name :param major_version: integer major version of migration :param minor_version: integer minor version of migration
[ "Set", "database", "migration", "version" ]
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L146-L155
Othernet-Project/squery-pg
squery_pg/migrations.py
run_migration
def run_migration(name, major_version, minor_version, db, mod, conf={}): """ Run migration script :param major_version: major version number of the migration :param minor_version: minor version number of the migration :param db: database connection object :param path: path of th...
python
def run_migration(name, major_version, minor_version, db, mod, conf={}): """ Run migration script :param major_version: major version number of the migration :param minor_version: minor version number of the migration :param db: database connection object :param path: path of th...
[ "def", "run_migration", "(", "name", ",", "major_version", ",", "minor_version", ",", "db", ",", "mod", ",", "conf", "=", "{", "}", ")", ":", "with", "db", ".", "transaction", "(", ")", ":", "mod", ".", "up", "(", "db", ",", "conf", ")", "set_versi...
Run migration script :param major_version: major version number of the migration :param minor_version: minor version number of the migration :param db: database connection object :param path: path of the migration script :param conf: application configuration (if any)
[ "Run", "migration", "script" ]
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L158-L169
Othernet-Project/squery-pg
squery_pg/migrations.py
migrate
def migrate(db, name, package, conf={}): """ Run all migrations that have not been run Migrations will be run inside a transaction. :param db: database connection object :param name: name associated with the migrations :param package: package that contains the migra...
python
def migrate(db, name, package, conf={}): """ Run all migrations that have not been run Migrations will be run inside a transaction. :param db: database connection object :param name: name associated with the migrations :param package: package that contains the migra...
[ "def", "migrate", "(", "db", ",", "name", ",", "package", ",", "conf", "=", "{", "}", ")", ":", "(", "current_major_version", ",", "current_minor_version", ")", "=", "get_version", "(", "db", ",", "name", ")", "package", "=", "importlib", ".", "import_mo...
Run all migrations that have not been run Migrations will be run inside a transaction. :param db: database connection object :param name: name associated with the migrations :param package: package that contains the migrations :param conf: application con...
[ "Run", "all", "migrations", "that", "have", "not", "been", "run" ]
train
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L172-L195
mayfield/shellish
shellish/rendering/html.py
html2vtml
def html2vtml(vtmarkup): """ Convert hypertext markup into vt markup. The output can be given to `vtmlrender` for converstion to VT100 sequences. """ try: htmlconv.feed(vtmarkup) htmlconv.close() return htmlconv.getvalue() finally: htmlconv.reset()
python
def html2vtml(vtmarkup): """ Convert hypertext markup into vt markup. The output can be given to `vtmlrender` for converstion to VT100 sequences. """ try: htmlconv.feed(vtmarkup) htmlconv.close() return htmlconv.getvalue() finally: htmlconv.reset()
[ "def", "html2vtml", "(", "vtmarkup", ")", ":", "try", ":", "htmlconv", ".", "feed", "(", "vtmarkup", ")", "htmlconv", ".", "close", "(", ")", "return", "htmlconv", ".", "getvalue", "(", ")", "finally", ":", "htmlconv", ".", "reset", "(", ")" ]
Convert hypertext markup into vt markup. The output can be given to `vtmlrender` for converstion to VT100 sequences.
[ "Convert", "hypertext", "markup", "into", "vt", "markup", ".", "The", "output", "can", "be", "given", "to", "vtmlrender", "for", "converstion", "to", "VT100", "sequences", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/rendering/html.py#L206-L215